From a944dd7bd4043d6d9841217237e5208ee9098837 Mon Sep 17 00:00:00 2001 From: Colin McDonnell Date: Thu, 12 May 2022 00:08:35 -0700 Subject: [PATCH] COnfigure docsify --- docs/.nojekyll => .nojekyll | 0 README.md | 263 +++-- docs/README.md | 2039 --------------------------------- docsify.js | 1 + docs/index.html => index.html | 21 +- prism.js | 31 + 6 files changed, 181 insertions(+), 2174 deletions(-) rename docs/.nojekyll => .nojekyll (100%) delete mode 100644 docs/README.md create mode 100644 docsify.js rename docs/index.html => index.html (68%) create mode 100644 prism.js diff --git a/docs/.nojekyll b/.nojekyll similarity index 100% rename from docs/.nojekyll rename to .nojekyll diff --git a/README.md b/README.md index b0f19fed7..d598de8ed 100644 --- a/README.md +++ b/README.md @@ -9,6 +9,7 @@ npm stars discord server +

@@ -28,11 +29,11 @@ These docs have been translated into [Chinese](./README_ZH.md). -# Table of contents +## Table of contents +#### Go to [zod.js.org](https://zod.js.org) >> --> - [What is Zod](#what-is-zod) - [Installation](#installation) @@ -70,7 +71,7 @@ These docs have been translated into [Chinese](./README_ZH.md). - [Maps](#maps) - [Sets](#sets) - [Unions](#unions) - - [Discriminated Unions](#discriminated-unions) + - [Discriminated Unions](#discriminated-unions) - [Recursive types](#recursive-types) - [JSON type](#json-type) - [Cyclical data](#cyclical-objects) @@ -107,7 +108,7 @@ These docs have been translated into [Chinese](./README_ZH.md). -# What is Zod +## What is Zod Zod is a TypeScript-first schema declaration and validation library. I'm using the term "schema" to broadly refer to any data type, from a simple `string` to a complex nested object. @@ -123,7 +124,7 @@ Some other great aspects: - Functional approach: [parse, don't validate](https://lexi-lambda.github.io/blog/2019/11/05/parse-don-t-validate/) - Works with plain JavaScript too! You don't need to use TypeScript. -# Sponsorship +## Sponsorship Sponsorship at any level is appreciated and encouraged. For individual developers, consider the [Cup of Coffee tier](https://github.com/sponsors/colinhacks). If you built a paid product using Zod, consider one of the [podium tiers](https://github.com/sponsors/colinhacks). @@ -242,7 +243,7 @@ Sponsorship at any level is appreciated and encouraged. For individual developer -# Installation +## Installation To install Zod v3: @@ -263,13 +264,13 @@ npm install zod } ``` -#### TypeScript requirements +### TypeScript requirements - Zod 3.x requires TypeScript 4.1+ - Zod 2.x requires TypeScript 3.7+ - Zod 1.x requires TypeScript 3.3+ -# Ecosystem +## Ecosystem There are a growing number of tools that are built atop or support Zod natively! If you've built a tool or library on top of Zod, tell me about it [on Twitter](https://twitter.com/colinhacks) or [start a Discussion](https://github.com/colinhacks/zod/discussions). I'll add it below and tweet it out. @@ -303,7 +304,7 @@ There are a growing number of tools that are built atop or support Zod natively! - [`zod-formik-adapter`](https://github.com/robertLichtnow/zod-formik-adapter): A community-maintained Formik adapter for Zod - [`react-zorm`](https://github.com/esamattis/react-zorm): Standalone `
` generation and validation for React using Zod -# Basic usage +## Basic usage Creating a simple string schema @@ -338,9 +339,9 @@ type User = z.infer; // { username: string } ``` -# Defining schemas +## Defining schemas -## Primitives +### Primitives ```ts import { z } from "zod"; @@ -367,7 +368,7 @@ z.unknown(); z.never(); ``` -## Literals +### Literals ```ts const tuna = z.literal("tuna"); @@ -380,7 +381,7 @@ tuna.value; // "tuna" > Currently there is no support for Date or bigint literals in Zod. If you have a use case for this feature, please file an issue. -## Strings +### Strings Zod includes a handful of string-specific validations. @@ -403,9 +404,7 @@ z.string().nonempty({ message: "Can't be empty" }); > Check out [validator.js](https://github.com/validatorjs/validator.js) for a bunch of other useful string validation functions. -#### Custom error messages - -You can customize certain errors when creating a string schema. +You can customize some common errors messages when creating a string schema. ```ts const name = z.string({ @@ -425,7 +424,7 @@ z.string().url({ message: "Invalid url" }); z.string().uuid({ message: "Invalid UUID" }); ``` -## Numbers +### Numbers You can customize certain error messages when creating a number schema. @@ -460,7 +459,7 @@ Optionally, you can pass in a second argument to provide a custom error message. z.number().lte(5, { message: "this👏is👏too👏big" }); ``` -## NaNs +### NaNs You can customize certain error messages when creating a nan schema. @@ -471,7 +470,7 @@ const isNaN = z.nan({ }); ``` -## Booleans +### Booleans You can customize certain error messages when creating a boolean schema. @@ -482,7 +481,7 @@ const isActive = z.boolean({ }); ``` -## Dates +### Dates z.date() accepts a date, not a date string @@ -504,7 +503,7 @@ dateSchema.safeParse(new Date("1/12/22")); // success: true dateSchema.safeParse("2022-01-12T00:00:00.000Z"); // success: true ``` -## Zod enums +### Zod enums ```ts const FishEnum = z.enum(["Salmon", "Tuna", "Trout"]); @@ -549,7 +548,7 @@ You can also retrieve the list of options as a tuple with the `.options` propert FishEnum.options; // ["Salmon", "Tuna", "Trout"]); ``` -## Native enums +### Native enums Zod enums are the recommended approach to defining and validating enums. But if you need to validate against an enum from a third-party library (or you don't want to rewrite your existing enums) you can use `z.nativeEnum()` . @@ -617,9 +616,9 @@ You can access the underlying object with the `.enum` property: FruitEnum.enum.Apple; // "apple" ``` -## Optionals +### Optionals -You can make any schema optional with `z.optional()`: +You can make any schema optional with `z.optional()`. This wraps the schema in a `ZodOptional` instance and returns the result. ```ts const schema = z.optional(z.string()); @@ -628,7 +627,7 @@ schema.parse(undefined); // => returns undefined type A = z.infer; // string | undefined ``` -You can make an existing schema optional with the `.optional()` method: +For convenience, you can also call the `.optional()` method on an existing schema. ```ts const user = z.object({ @@ -637,7 +636,7 @@ const user = z.object({ type C = z.infer; // { username?: string | undefined }; ``` -#### `.unwrap` +You can extract the wrapped schema from a `ZodOptional` instance with `.unwrap()`. ```ts const stringSchema = z.string(); @@ -645,9 +644,9 @@ const optionalString = stringSchema.optional(); optionalString.unwrap() === stringSchema; // true ``` -## Nullables +### Nullables -Similarly, you can create nullable types like so: +Similarly, you can create nullable types with `z.nullable()`. ```ts const nullableString = z.nullable(z.string()); @@ -655,14 +654,14 @@ nullableString.parse("asdf"); // => "asdf" nullableString.parse(null); // => null ``` -You can make an existing schema nullable with the `nullable` method: +Or use the `.nullable()` method. ```ts const E = z.string().nullable(); // equivalent to D type E = z.infer; // string | null ``` -#### `.unwrap` +Extract the inner schema with `.unwrap()`. ```ts const stringSchema = z.string(); @@ -670,7 +669,7 @@ const nullableString = stringSchema.nullable(); nullableString.unwrap() === stringSchema; // true ``` -## Objects +### Objects ```ts // all properties are required by default @@ -689,7 +688,7 @@ type Dog = { }; ``` -### `.shape` +#### `.shape` Use `.shape` to access the schemas for a particular key. @@ -698,7 +697,7 @@ Dog.shape.name; // => string schema Dog.shape.age; // => number schema ``` -### `.extend` +#### `.extend` You can add additional fields an object schema with the `.extend` method. @@ -710,7 +709,7 @@ const DogWithBreed = Dog.extend({ You can use `.extend` to overwrite fields! Be careful with this power! -### `.merge` +#### `.merge` Equivalent to `A.extend(B.shape)`. @@ -724,7 +723,7 @@ type Teacher = z.infer; // => { students: string[], id: string } > If the two schemas share keys, the properties of B overrides the property of A. The returned schema also inherits the "unknownKeys" policy (strip/strict/passthrough) and the catchall schema of B. -### `.pick/.omit` +#### `.pick/.omit` Inspired by TypeScript's built-in `Pick` and `Omit` utility types, all Zod object schemas have `.pick` and `.omit` methods that return a modified version. Consider this Recipe schema: @@ -753,7 +752,7 @@ type NoIDRecipe = z.infer; // => { name: string, ingredients: string[] } ``` -### `.partial` +#### `.partial` Inspired by the built-in TypeScript utility type [Partial](https://www.typescriptlang.org/docs/handbook/utility-types.html#partialt), the `.partial` method makes all properties optional. @@ -788,7 +787,7 @@ const optionalEmail = user.partial({ */ ``` -### `.deepPartial` +#### `.deepPartial` The `.partial` method is shallow — it only applies one level deep. There is also a "deep" version: @@ -818,7 +817,7 @@ const deepPartialUser = user.deepPartial(); > Important limitation: deep partials only work as expected in hierarchies of objects, arrays, and tuples. -#### Unrecognized keys +#### `.passthrough` By default Zod objects schemas strip out unrecognized keys during parsing. @@ -835,8 +834,6 @@ person.parse({ // extraKey has been stripped ``` -### `.passthrough` - Instead, if you want to pass through unknown keys, use `.passthrough()` . ```ts @@ -847,9 +844,9 @@ person.passthrough().parse({ // => { name: "bob dylan", extraKey: 61 } ``` -### `.strict` +#### `.strict` -You can _disallow_ unknown keys with `.strict()` . If there are any unknown keys in the input, Zod will throw an error. +By default Zod objects schemas strip out unrecognized keys during parsing. You can _disallow_ unknown keys with `.strict()` . If there are any unknown keys in the input, Zod will throw an error. ```ts const person = z @@ -865,11 +862,11 @@ person.parse({ // => throws ZodError ``` -### `.strip` +#### `.strip` You can use the `.strip` method to reset an object schema to the default behavior (stripping unrecognized keys). -### `.catchall` +#### `.catchall` You can pass a "catchall" schema into an object schema. All unknown keys will be validated against it. @@ -894,7 +891,7 @@ person.parse({ Using `.catchall()` obviates `.passthrough()` , `.strip()` , or `.strict()`. All keys are now considered "known". -## Arrays +### Arrays ```ts const stringArray = z.array(z.string()); @@ -910,7 +907,7 @@ z.string().optional().array(); // (string | undefined)[] z.string().array().optional(); // string[] | undefined ``` -### `.element` +#### `.element` Use `.element` to access the schema for an element of the array. @@ -918,7 +915,7 @@ Use `.element` to access the schema for an element of the array. stringArray.element; // => string schema ``` -### `.nonempty` +#### `.nonempty` If you want to ensure that an array contains at least one element, use `.nonempty()`. @@ -940,7 +937,7 @@ const nonEmptyStrings = z.string().array().nonempty({ }); ``` -### `.min/.max/.length` +#### `.min/.max/.length` ```ts z.string().array().min(5); // must contain 5 or more items @@ -950,7 +947,7 @@ z.string().array().length(5); // must contain 5 items exactly Unlike `.nonempty()` these methods do not change the inferred type. -## Tuples +### Tuples Unlike arrays, tuples have a fixed number of elements and each element can have a different type. @@ -967,7 +964,7 @@ type Athlete = z.infer; // type Athlete = [string, number, { pointsScored: number }] ``` -## Unions +### Unions Zod includes a built-in `z.union` method for composing "OR" types. @@ -1005,7 +1002,7 @@ const item = z .parse({ type: "a", a: "abc" }); ``` -## Records +### Records Record schemas are used to validate types such as `{ [k: string]: number }`. @@ -1032,7 +1029,7 @@ userStore["77d2586b-9e8e-4ecf-8b21-ea7e0530eadd"] = { }; // TypeError ``` -#### A note on numerical keys +**A note on numerical keys** You may have expected `z.record()` to accept two arguments, one for the keys and one for the values. After all, TypeScript's built-in Record type does: `Record` . Otherwise, how do you represent the TypeScript type `Record` in Zod? @@ -1049,11 +1046,9 @@ for (const key in testMap) { // prints: `1: string` ``` -As you can see, JavaScript automatically casts all object keys to strings under the hood. - -Since Zod is trying to bridge the gap between static and runtime types, it doesn't make sense to provide a way of creating a record schema with numerical keys, since there's no such thing as a numerical key in runtime JavaScript. +As you can see, JavaScript automatically casts all object keys to strings under the hood. Since Zod is trying to bridge the gap between static and runtime types, it doesn't make sense to provide a way of creating a record schema with numerical keys, since there's no such thing as a numerical key in runtime JavaScript. -## Maps +### Maps ```ts const stringNumberMap = z.map(z.string(), z.number()); @@ -1062,7 +1057,7 @@ type StringNumberMap = z.infer; // type StringNumberMap = Map ``` -## Sets +### Sets ```ts const numberSet = z.set(z.number()); @@ -1070,7 +1065,7 @@ type NumberSet = z.infer; // type NumberSet = Set ``` -### `.nonempty/.min/.max/.size` +Set schemas can be further contrainted with the following utility methods. ```ts z.set(z.string()).nonempty(); // must contain at least one item @@ -1079,9 +1074,7 @@ z.set(z.string()).max(5); // must contain 5 or fewer items z.set(z.string()).size(5); // must contain 5 items exactly ``` -## Intersections - - +### Intersections Intersections are useful for creating "logical AND" types. This is useful for intersecting two object types. @@ -1129,7 +1122,7 @@ type Teacher = z.infer; // { id:string; name:string }; ``` --> -## Recursive types +### Recursive types You can define a recursive schema in Zod, but because of a limitation of TypeScript, their type can't be statically inferred. Instead you'll need to define the type definition manually, and provide it to Zod as a "type hint". @@ -1184,7 +1177,7 @@ const Category: z.ZodType = BaseCategory.merge( ); ``` --> -#### JSON type +#### Validating JSON If you want to validate any JSON value, you can use the snippet below. @@ -1205,7 +1198,7 @@ Thanks to [ggoodman](https://github.com/ggoodman) for suggesting this. Despite supporting recursive schemas, passing cyclical data into Zod will cause an infinite loop. -## Promises +### Promises ```ts const numberPromise = z.promise(z.number()); @@ -1236,7 +1229,7 @@ const test = async () => { When "parsing" a promise, Zod checks that the passed value is an object with `.then` and `.catch` methods — that's it. So you should be able to pass non-native Promises (Bluebird, etc) into `z.promise(...).parse` with no trouble. One gotcha: the return type of the parse function will be a _native_ `Promise` , so if you have downstream logic that uses non-standard Promise methods, this won't work. --> -## Instanceof +### Instanceof You can use `z.instanceof` to check that the input is an instance of a class. This is useful to validate inputs against classes that are exported from third-party libraries. @@ -1252,7 +1245,7 @@ TestSchema.parse(new Test()); // passes TestSchema.parse("blob"); // throws ``` -## Function schemas +### Function schemas Zod also lets you define "function schemas". This makes it easy to validate the inputs and outputs of a function without intermixing your validation code and "business logic". @@ -1334,7 +1327,7 @@ const myFunction = z myFunction; // (arg: string)=>number[] ``` -## Preprocess +### Preprocess Typically Zod operates under a "parse then transform" paradigm. Zod validates the input first, then passes it through a chain of transformation functions. (For more information about transforms, read the [.transform docs](#transform).) @@ -1346,7 +1339,7 @@ const castToString = z.preprocess((val) => String(val), z.string()); This returns a `ZodEffects` instance. `ZodEffects` is a wrapper class that contains all logic pertaining to preprocessing, refinements, and transforms. -# ZodType: methods and properties +## ZodType: methods and properties All Zod schemas contain certain methods. @@ -1607,27 +1600,6 @@ stringToNumber.parse("string"); // => 6 > ⚠️ Transform functions must not throw. Make sure to use refinements before the transform or addIssue within the transform to make sure the input can be parsed by the transform. -#### Validating during transform - -Similar to `superRefine`, `transform` can optionally take a `ctx`. This allows you to simultaneously -validate and transform the value, which can be simpler than chaining `refine` and `validate`. -When calling `ctx.addIssue` make sure to still return a value of the correct type otherwise the inferred type will include `undefined`. - -```ts -const Strings = z - .string() - .transform((val, ctx) => { - const parsed = parseInt(val); - if (isNaN(parsed)) { - ctx.addIssue({ - code: z.ZodIssueCode.custom, - message: "Not a number", - }); - } - return parsed; - }); -``` - #### Chaining order Note that `stringToNumber` above is an instance of the `ZodEffects` subclass. It is NOT an instance of `ZodString`. If you want to use the built-in methods of `ZodString` (e.g. `.email()`) you must apply those methods _before_ any transforms. @@ -1641,14 +1613,33 @@ const emailToDomain = z emailToDomain.parse("colinhacks@example.com"); // => example.com ``` +#### Validating during transform + +Similar to `superRefine`, `transform` can optionally take a `ctx`. This allows you to simultaneously validate and transform the value, which can be simpler than chaining `refine` and `validate`. When calling `ctx.addIssue` make sure to still return a value of the correct type otherwise the inferred type will include `undefined`. + +```ts +const Strings = z.string().transform((val, ctx) => { + const parsed = parseInt(val); + if (isNaN(parsed)) { + ctx.addIssue({ + code: z.ZodIssueCode.custom, + message: "Not a number", + }); + } + return parsed; +}); +``` + #### Relationship to refinements -Transforms and refinements can be interleaved: +Transforms and refinements can be interleaved. These will be executed in the order they are declared. ```ts z.string() - .transform((val) => val.length) - .refine((val) => val > 25); + .transform((val) => val.toUpperCase()) + .refine((val) => val.length > 15) + .transform((val) => `Hello ${val}`) + .refine((val) => val.indexOf("!") === -1); ``` #### Async transforms @@ -1763,9 +1754,9 @@ z.object({ name: z.string() }).and(z.object({ age: z.number() })); // { name: st z.intersection(z.object({ name: z.string() }), z.object({ age: z.number() })); ``` -# Guides and concepts +## Guides and concepts -## Type inference +### Type inference You can extract the TypeScript type of any schema with `z.infer` . @@ -1777,7 +1768,7 @@ const u: A = 12; // TypeError const u: A = "asdf"; // compiles ``` -#### What about transforms? +**What about transforms?** In reality each Zod schema internally tracks **two** types: an input and an output. For most schemas (e.g. `z.string()`) these two are the same. But once you add transforms into the mix, these two values can diverge. For instance `z.string().transform(val => val.length)` has an input of `string` and an output of `number`. @@ -1794,67 +1785,75 @@ type output = z.output; // number type inferred = z.infer; // number ``` -## Writing generic functions +### Writing functions that accept Zod schemas -When attempting to write a functions that accepts a Zod schemas as an input, it's common to try something like this: +You can use `z.ZodType` as a type that will accept any Zod schema. ```ts -function makeSchemaOptional(schema: z.ZodType) { - return schema.optional(); +function runParse(schema: z.ZodType, input: unknown) { + return schema.parse(input); } ``` -This approach has some issues. The `schema` variable in this function is typed as an instance of `ZodType`, which is an abstract class that all Zod schemas inherit from. This approach loses type information, namely _which subclass_ the input actually is. +The `ZodType` class has three generic parameters. ```ts -const arg = makeSchemaOptional(z.string()); -arg.unwrap(); +class ZodType< + Output = any, + Def extends ZodTypeDef = ZodTypeDef, + Input = Output +> { ... } ``` -A better approach is for the generate parameter to refer to _the schema as a whole_. +By constraining these in your generic input, you can limit what schemas are allowable as inputs to your function: ```ts -function makeSchemaOptional(schema: T) { +function makeSchemaOptional>(schema: T) { return schema.optional(); } + +makeSchemaOptional(z.string()); +// works fine + +makeSchemaOptional(z.number()); +// Error: 'ZodNumber' is not assignable to parameter of type 'ZodType' ``` -> `ZodTypeAny` is just a shorthand for `ZodType`, a type that is broad enough to match any Zod schema. +### Writing generic functions -As you can see, `schema` is now fully and properly typed. +When attempting to write a functions that accepts a Zod schemas as an input, it's common to try something like this: ```ts -const arg = makeSchemaOptional(z.string()); -arg.unwrap(); // ZodString +function makeSchemaOptional(schema: z.ZodType) { + return schema.optional(); +} ``` -### Restricting valid schemas - -The `ZodType` class has three generic parameters. +This approach has some issues. The `schema` variable in this function is typed as an instance of `ZodType`, which is an abstract class that all Zod schemas inherit from. This approach loses type information, namely _which subclass_ the input actually is. ```ts -class ZodType< - Output, - Def extends ZodTypeDef = ZodTypeDef, - Input = Output -> { ... } +const arg = makeSchemaOptional(z.string()); +arg.unwrap(); ``` -By constraining these in your generic input, you can limit what schemas are allowable as inputs to your function: +A better approach is for the generate parameter to refer to _the schema as a whole_. ```ts -function makeSchemaOptional>(schema: T) { +function makeSchemaOptional(schema: T) { return schema.optional(); } +``` -makeSchemaOptional(z.string()); -// works fine +> `ZodTypeAny` is just a shorthand for `ZodType`, a type that is broad enough to match any Zod schema. -makeSchemaOptional(z.number()); -// Error: 'ZodNumber' is not assignable to parameter of type 'ZodType' +As you can see, `schema` is now fully and properly typed. + +```ts +const arg = makeSchemaOptional(z.string()); +arg.unwrap(); // ZodString ``` -## Error handling +### Error handling Zod provides a subclass of Error called `ZodError`. ZodErrors contain an `issues` array containing detailed information about the validation problems. @@ -1875,7 +1874,7 @@ if (!data.success) { } ``` -#### Error formatting +### Error formatting You can use the `.format()` method to convert this error into a nested object. @@ -1888,7 +1887,7 @@ data.error.format(); For detailed information about the possible error codes and how to customize error messages, check out the dedicated error handling guide: [ERROR_HANDLING.md](ERROR_HANDLING.md) -# Comparison +## Comparison There are a handful of other widely-used validation libraries, but all of them have certain design limitations that make for a non-ideal developer experience. @@ -1940,20 +1939,18 @@ Branded --> * Missing support for parsing cyclical data (maybe) * Missing error customization --> -#### Joi +**Joi** [https://github.com/hapijs/joi](https://github.com/hapijs/joi) Doesn't support static type inference 😕 -#### Yup +**Yup** [https://github.com/jquense/yup](https://github.com/jquense/yup) Yup is a full-featured library that was implemented first in vanilla JS, and later rewritten in TypeScript. -Differences - - Supports casting and transforms - All object fields are optional by default - Missing object methods: (partial, deepPartial) @@ -1964,7 +1961,7 @@ Differences -#### io-ts +**io-ts** [https://github.com/gcanti/io-ts](https://github.com/gcanti/io-ts) @@ -2015,7 +2012,7 @@ This more declarative API makes schema definitions vastly more concise. - Missing promise schemas - Missing function schemas -#### Runtypes +**Runtypes** [https://github.com/pelotom/runtypes](https://github.com/pelotom/runtypes) @@ -2028,7 +2025,7 @@ Good type inference support, but limited options for object type masking (no `.p - Missing promise schemas - Missing error customization -#### Ow +**Ow** [https://github.com/sindresorhus/ow](https://github.com/sindresorhus/ow) @@ -2036,6 +2033,6 @@ Ow is focused on function input validation. It's a library that makes it easy to If you want to validate function inputs, use function schemas in Zod! It's a much simpler approach that lets you reuse a function type declaration without repeating yourself (namely, copy-pasting a bunch of ow assertions at the beginning of every function). Also Zod lets you validate your return types as well, so you can be sure there won't be any unexpected data passed downstream. -# Changelog +## Changelog View the changelog at [CHANGELOG.md](CHANGELOG.md) diff --git a/docs/README.md b/docs/README.md deleted file mode 100644 index 486804a86..000000000 --- a/docs/README.md +++ /dev/null @@ -1,2039 +0,0 @@ -

- -

Zod

-

-

-Zod CI status -Created by Colin McDonnell -License -npm -stars -discord server -

- -
- Discord -   •   - NPM -   •   - Issues -   •   - @colinhacks -   •   - tRPC -
-
- -
- -These docs have been translated into [Chinese](./README_ZH.md). - -# Table of contents - - - -- [What is Zod](#what-is-zod) -- [Installation](#installation) -- [Ecosystem](#ecosystem) -- [Basic usage](#basic-usage) -- [Defining schemas](#defining-schemas) - - [Primitives](#primitives) - - [Literals](#literals) - - [Strings](#strings) - - [Numbers](#numbers) - - [NaNs](#nans) - - [Booleans](#booleans) - - [Dates](#dates) - - [Zod enums](#zod-enums) - - [Native enums](#native-enums) - - [Optionals](#optionals) - - [Nullables](#nullables) - - [Objects](#objects) - - [.shape](#shape) - - [.extend](#extend) - - [.merge](#merge) - - [.pick/.omit](#pickomit) - - [.partial](#partial) - - [.deepPartial](#deepPartial) - - [.passthrough](#passthrough) - - [.strict](#strict) - - [.strip](#strip) - - [.catchall](#catchall) - - [Arrays](#arrays) - - [.element](#element) - - [.nonempty](#nonempty) - - [.min/.max/.length](#minmaxlength) - - [Tuples](#tuples) - - [Records](#records) - - [Maps](#maps) - - [Sets](#sets) - - [Unions](#unions) - - [Discriminated Unions](#discriminated-unions) - - [Recursive types](#recursive-types) - - [JSON type](#json-type) - - [Cyclical data](#cyclical-objects) - - [Promises](#promises) - - [Instanceof](#instanceof) - - [Function schemas](#function-schemas) - - [Preprocess](#preprocess) -- [Schema methods](#zodtype-methods-and-properties) - - [.parse](#parse) - - [.parseAsync](#parseasync) - - [.safeParse](#safeparse) - - [.safeParseAsync](#safeparseasync) - - [.refine](#refine) - - [.superRefine](#superRefine) - - [.transform](#transform) - - [.default](#default) - - [.optional](#optional) - - [.nullable](#nullable) - - [.nullish](#nullish) - - [.array](#array) - - [.promise](#promise) - - [.or](#or) - - [.and](#and) -- [Guides and concepts](#guides-and-concepts) - - [Type inference](#type-inference) - - [Writing generic functions](#writing-generic-functions) - - [Error handling](#error-handling) -- [Comparison](#comparison) - - [Joi](#joi) - - [Yup](#yup) - - [io-ts](#io-ts) - - [Runtypes](#runtypes) -- [Changelog](#changelog) - - - -# What is Zod - -Zod is a TypeScript-first schema declaration and validation library. I'm using the term "schema" to broadly refer to any data type, from a simple `string` to a complex nested object. - -Zod is designed to be as developer-friendly as possible. The goal is to eliminate duplicative type declarations. With Zod, you declare a validator _once_ and Zod will automatically infer the static TypeScript type. It's easy to compose simpler types into complex data structures. - -Some other great aspects: - -- Zero dependencies -- Works in Node.js and all modern browsers -- Tiny: 8kb minified + zipped -- Immutable: methods (i.e. `.optional()`) return a new instance -- Concise, chainable interface -- Functional approach: [parse, don't validate](https://lexi-lambda.github.io/blog/2019/11/05/parse-don-t-validate/) -- Works with plain JavaScript too! You don't need to use TypeScript. - -# Sponsorship - -Sponsorship at any level is appreciated and encouraged. For individual developers, consider the [Cup of Coffee tier](https://github.com/sponsors/colinhacks). If you built a paid product using Zod, consider one of the [podium tiers](https://github.com/sponsors/colinhacks). - -### Gold - - - - - - - - - -
- - - -
- Astro -
- astro.build -
-

- Astro is a new kind of static
- site builder for the modern web.
- Powerful developer experience meets
- lightweight output.

-
- - - -
- Glow Wallet -
- glow.app -
-

Your new favorite -
- Solana wallet.

-
- - - -
- Deletype -
- deletype.com -
- -### Silver - - - - - - - -
- - - -
- Snaplet -
- snaplet.dev -
- - Marcato Partners - -
- Marcato Partners -
- marcatopartners.com -
- - Trip - -
- Trip -
- -### Bronze - - - - - - - -
- - - -
- Brandon Bayer -
- @flybayer, - creator of Blitz.js -
-
- - - -
- Jiří Brabec -
- @brabeji -
-
- - - -
- Alex Johansson -
- @alexdotjs -
- -# Installation - -To install Zod v3: - -```sh -npm install zod -``` - -⚠️ IMPORTANT: You must enable `strict` mode in your `tsconfig.json`. This is a best practice for all TypeScript projects. - -```ts -// tsconfig.json -{ - // ... - "compilerOptions": { - // ... - "strict": true - } -} -``` - -#### TypeScript requirements - -- Zod 3.x requires TypeScript 4.1+ -- Zod 2.x requires TypeScript 3.7+ -- Zod 1.x requires TypeScript 3.3+ - -# Ecosystem - -There are a growing number of tools that are built atop or support Zod natively! If you've built a tool or library on top of Zod, tell me about it [on Twitter](https://twitter.com/colinhacks) or [start a Discussion](https://github.com/colinhacks/zod/discussions). I'll add it below and tweet it out. - -- [`tRPC`](https://github.com/trpc/trpc): Build end-to-end typesafe APIs without GraphQL. -- [`ts-to-zod`](https://github.com/fabien0102/ts-to-zod): Convert TypeScript definitions into Zod schemas. -- [`zod-to-ts`](https://github.com/sachinraja/zod-to-ts): Generate TypeScript definitions from Zod schemas. -- [`@anatine/zod-openapi`](https://github.com/anatine/zod-plugins/tree/main/libs/zod-openapi): Converts a Zod schema to an OpenAPI v3.x `SchemaObject`. -- [`@anatine/zod-mock`](https://github.com/anatine/zod-plugins/tree/main/libs/zod-mock): Generate mock data from a Zod schema. Powered by [faker.js](https://github.com/Marak/Faker.js). -- [`@anatine/zod-nestjs`](https://github.com/anatine/zod-plugins/tree/main/libs/zod-nestjs): Helper methods for using Zod in a NestJS project. -- [`zod-mocking`](https://github.com/dipasqualew/zod-mocking): Generate mock data from your Zod schemas. -- [`zod-fast-check`](https://github.com/DavidTimms/zod-fast-check): Generate `fast-check` arbitraries from Zod schemas. -- [`zod-endpoints`](https://github.com/flock-community/zod-endpoints): Contract-first strictly typed endpoints with Zod. OpenAPI compatible. -- [`express-zod-api`](https://github.com/RobinTail/express-zod-api): Build Express-based APIs with I/O schema validation and custom middlewares. -- [`zod-to-json-schema`](https://github.com/StefanTerdell/zod-to-json-schema): Convert your Zod schemas into [JSON Schemas](https://json-schema.org/). -- [`json-schema-to-zod`](https://github.com/StefanTerdell/json-schema-to-zod): Convert your [JSON Schemas](https://json-schema.org/) into Zod schemas. Use it live [here](https://StefanTerdell.github.io/json-schema-to-zod-react/). -- [`json-to-zod`](https://github.com/rsinohara/json-to-zod): Convert JSON objects into Zod schemas. Use it live [here](https://rsinohara.github.io/json-to-zod-react/). -- [`zod-dto`](https://github.com/kbkk/abitia/tree/master/packages/zod-dto): Generate Nest.js DTOs from a Zod schema. -- [`soly`](https://github.com/mdbetancourt/soly): Create CLI applications with zod. -- [`graphql-codegen-typescript-validation-schema`](https://github.com/Code-Hex/graphql-codegen-typescript-validation-schema): GraphQL Code Generator plugin to generate form validation schema from your GraphQL schema -- [`zod-prisma`](https://github.com/CarterGrimmeisen/zod-prisma): Generate Zod schemas from your Prisma schema. -- [`fastify-type-provider-zod`](https://github.com/turkerdev/fastify-type-provider-zod): Create Fastify type providers from Zod schemas -- [`Supervillain`](https://github.com/Southclaws/supervillain): Generate Zod schemas from your Go structs -- [`zod-to-openapi`](https://github.com/asteasolutions/zod-to-openapi): Generate full OpenAPI (Swagger) docs from Zod, including schemas, endpoints & parameters -- [`prisma-zod-generator`](https://github.com/omar-dulaimi/prisma-zod-generator): Emit Zod schemas from your Prisma schema. -- [`prisma-trpc-generator`](https://github.com/omar-dulaimi/prisma-trpc-generator): Emit fully implemented tRPC routers and their validation schemas using Zod. -- [`nestjs-graphql-zod`](https://github.com/incetarik/nestjs-graphql-zod): Generates NestJS GraphQL model classes from Zod schemas dynamically and provides GraphQL method decorators working with Zod schemas. - -### Form integrations - -- [`react-hook-form`](https://github.com/react-hook-form/resolvers#zod): A first-party Zod resolver for React Hook Form -- [`zod-formik-adapter`](https://github.com/robertLichtnow/zod-formik-adapter): A community-maintained Formik adapter for Zod -- [`react-zorm`](https://github.com/esamattis/react-zorm): Standalone `` generation and validation for React using Zod - -# Basic usage - -Creating a simple string schema - -```ts -import { z } from "zod"; - -// creating a schema for strings -const mySchema = z.string(); - -// parsing -mySchema.parse("tuna"); // => "tuna" -mySchema.parse(12); // => throws ZodError - -// "safe" parsing (doesn't throw error if validation fails) -mySchema.safeParse("tuna"); // => { success: true; data: "tuna" } -mySchema.safeParse(12); // => { success: false; error: ZodError } -``` - -Creating an object schema - -```ts -import { z } from "zod"; - -const User = z.object({ - username: z.string(), -}); - -User.parse({ username: "Ludwig" }); - -// extract the inferred type -type User = z.infer; -// { username: string } -``` - -# Defining schemas - -## Primitives - -```ts -import { z } from "zod"; - -// primitive values -z.string(); -z.number(); -z.bigint(); -z.boolean(); -z.date(); - -// empty types -z.undefined(); -z.null(); -z.void(); // accepts undefined - -// catch-all types -// allows any value -z.any(); -z.unknown(); - -// never type -// allows no values -z.never(); -``` - -## Literals - -```ts -const tuna = z.literal("tuna"); -const twelve = z.literal(12); -const tru = z.literal(true); - -// retrieve literal value -tuna.value; // "tuna" -``` - -> Currently there is no support for Date or bigint literals in Zod. If you have a use case for this feature, please file an issue. - -## Strings - -Zod includes a handful of string-specific validations. - -```ts -z.string().max(5); -z.string().min(5); -z.string().length(5); -z.string().email(); -z.string().url(); -z.string().uuid(); -z.string().cuid(); -z.string().regex(regex); - -// deprecated, equivalent to .min(1) -z.string().nonempty(); - -// optional custom error message -z.string().nonempty({ message: "Can't be empty" }); -``` - -> Check out [validator.js](https://github.com/validatorjs/validator.js) for a bunch of other useful string validation functions. - -#### Custom error messages - -You can customize certain errors when creating a string schema. - -```ts -const name = z.string({ - required_error: "Name is required", - invalid_type_error: "Name must be a string", -}); -``` - -When using validation methods, you can pass in an additional argument to provide a custom error message. - -```ts -z.string().min(5, { message: "Must be 5 or more characters long" }); -z.string().max(5, { message: "Must be 5 or fewer characters long" }); -z.string().length(5, { message: "Must be exactly 5 characters long" }); -z.string().email({ message: "Invalid email address" }); -z.string().url({ message: "Invalid url" }); -z.string().uuid({ message: "Invalid UUID" }); -``` - -## Numbers - -You can customize certain error messages when creating a number schema. - -```ts -const age = z.number({ - required_error: "Age is required", - invalid_type_error: "Age must be a number", -}); -``` - -Zod includes a handful of number-specific validations. - -```ts -z.number().gt(5); -z.number().gte(5); // alias .min(5) -z.number().lt(5); -z.number().lte(5); // alias .max(5) - -z.number().int(); // value must be an integer - -z.number().positive(); // > 0 -z.number().nonnegative(); // >= 0 -z.number().negative(); // < 0 -z.number().nonpositive(); // <= 0 - -z.number().multipleOf(5); // Evenly divisible by 5. Alias .step(5) -``` - -Optionally, you can pass in a second argument to provide a custom error message. - -```ts -z.number().lte(5, { message: "this👏is👏too👏big" }); -``` - -## NaNs - -You can customize certain error messages when creating a nan schema. - -```ts -const isNaN = z.nan({ - required_error: "isNaN is required", - invalid_type_error: "isNaN must be not a number", -}); -``` - -## Booleans - -You can customize certain error messages when creating a boolean schema. - -```ts -const isActive = z.boolean({ - required_error: "isActive is required", - invalid_type_error: "isActive must be a boolean", -}); -``` - -## Dates - -z.date() accepts a date, not a date string - -```ts -z.date().safeParse(new Date()); // success: true -z.date().safeParse("2022-01-12T00:00:00.000Z"); // success: false -``` - -To allow for dates or date strings, you can use preprocess - -```ts -const dateSchema = z.preprocess((arg) => { - if (typeof arg == "string" || arg instanceof Date) return new Date(arg); -}, z.date()); -type DateSchema = z.infer; -// type DateSchema = Date - -dateSchema.safeParse(new Date("1/12/22")); // success: true -dateSchema.safeParse("2022-01-12T00:00:00.000Z"); // success: true -``` - -## Zod enums - -```ts -const FishEnum = z.enum(["Salmon", "Tuna", "Trout"]); -type FishEnum = z.infer; -// 'Salmon' | 'Tuna' | 'Trout' -``` - -`z.enum` is a Zod-native way to declare a schema with a fixed set of allowable _string_ values. Pass the array of values directly into `z.enum()`. Alternatively, use `as const` to define your enum values as a tuple of strings. See the [const assertion docs](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-4.html#const-assertions) for details. - -```ts -const VALUES = ["Salmon", "Tuna", "Trout"] as const; -const FishEnum = z.enum(VALUES); -``` - -This is not allowed, since Zod isn't able to infer the exact values of each elements. - -```ts -const fish = ["Salmon", "Tuna", "Trout"]; -const FishEnum = z.enum(fish); -``` - -**Autocompletion** - -To get autocompletion with a Zod enum, use the `.enum` property of your schema: - -```ts -FishEnum.enum.Salmon; // => autocompletes - -FishEnum.enum; -/* -=> { - Salmon: "Salmon", - Tuna: "Tuna", - Trout: "Trout", -} -*/ -``` - -You can also retrieve the list of options as a tuple with the `.options` property: - -```ts -FishEnum.options; // ["Salmon", "Tuna", "Trout"]); -``` - -## Native enums - -Zod enums are the recommended approach to defining and validating enums. But if you need to validate against an enum from a third-party library (or you don't want to rewrite your existing enums) you can use `z.nativeEnum()` . - -**Numeric enums** - -```ts -enum Fruits { - Apple, - Banana, -} - -const FruitEnum = z.nativeEnum(Fruits); -type FruitEnum = z.infer; // Fruits - -FruitEnum.parse(Fruits.Apple); // passes -FruitEnum.parse(Fruits.Banana); // passes -FruitEnum.parse(0); // passes -FruitEnum.parse(1); // passes -FruitEnum.parse(3); // fails -``` - -**String enums** - -```ts -enum Fruits { - Apple = "apple", - Banana = "banana", - Cantaloupe, // you can mix numerical and string enums -} - -const FruitEnum = z.nativeEnum(Fruits); -type FruitEnum = z.infer; // Fruits - -FruitEnum.parse(Fruits.Apple); // passes -FruitEnum.parse(Fruits.Cantaloupe); // passes -FruitEnum.parse("apple"); // passes -FruitEnum.parse("banana"); // passes -FruitEnum.parse(0); // passes -FruitEnum.parse("Cantaloupe"); // fails -``` - -**Const enums** - -The `.nativeEnum()` function works for `as const` objects as well. ⚠️ `as const` required TypeScript 3.4+! - -```ts -const Fruits = { - Apple: "apple", - Banana: "banana", - Cantaloupe: 3, -} as const; - -const FruitEnum = z.nativeEnum(Fruits); -type FruitEnum = z.infer; // "apple" | "banana" | 3 - -FruitEnum.parse("apple"); // passes -FruitEnum.parse("banana"); // passes -FruitEnum.parse(3); // passes -FruitEnum.parse("Cantaloupe"); // fails -``` - -You can access the underlying object with the `.enum` property: - -```ts -FruitEnum.enum.Apple; // "apple" -``` - -## Optionals - -You can make any schema optional with `z.optional()`: - -```ts -const schema = z.optional(z.string()); - -schema.parse(undefined); // => returns undefined -type A = z.infer; // string | undefined -``` - -You can make an existing schema optional with the `.optional()` method: - -```ts -const user = z.object({ - username: z.string().optional(), -}); -type C = z.infer; // { username?: string | undefined }; -``` - -#### `.unwrap` - -```ts -const stringSchema = z.string(); -const optionalString = stringSchema.optional(); -optionalString.unwrap() === stringSchema; // true -``` - -## Nullables - -Similarly, you can create nullable types like so: - -```ts -const nullableString = z.nullable(z.string()); -nullableString.parse("asdf"); // => "asdf" -nullableString.parse(null); // => null -``` - -You can make an existing schema nullable with the `nullable` method: - -```ts -const E = z.string().nullable(); // equivalent to D -type E = z.infer; // string | null -``` - -#### `.unwrap` - -```ts -const stringSchema = z.string(); -const nullableString = stringSchema.nullable(); -nullableString.unwrap() === stringSchema; // true -``` - -## Objects - -```ts -// all properties are required by default -const Dog = z.object({ - name: z.string(), - age: z.number(), -}); - -// extract the inferred type like this -type Dog = z.infer; - -// equivalent to: -type Dog = { - name: string; - age: number; -}; -``` - -### `.shape` - -Use `.shape` to access the schemas for a particular key. - -```ts -Dog.shape.name; // => string schema -Dog.shape.age; // => number schema -``` - -### `.extend` - -You can add additional fields an object schema with the `.extend` method. - -```ts -const DogWithBreed = Dog.extend({ - breed: z.string(), -}); -``` - -You can use `.extend` to overwrite fields! Be careful with this power! - -### `.merge` - -Equivalent to `A.extend(B.shape)`. - -```ts -const BaseTeacher = z.object({ students: z.array(z.string()) }); -const HasID = z.object({ id: z.string() }); - -const Teacher = BaseTeacher.merge(HasID); -type Teacher = z.infer; // => { students: string[], id: string } -``` - -> If the two schemas share keys, the properties of B overrides the property of A. The returned schema also inherits the "unknownKeys" policy (strip/strict/passthrough) and the catchall schema of B. - -### `.pick/.omit` - -Inspired by TypeScript's built-in `Pick` and `Omit` utility types, all Zod object schemas have `.pick` and `.omit` methods that return a modified version. Consider this Recipe schema: - -```ts -const Recipe = z.object({ - id: z.string(), - name: z.string(), - ingredients: z.array(z.string()), -}); -``` - -To only keep certain keys, use `.pick` . - -```ts -const JustTheName = Recipe.pick({ name: true }); -type JustTheName = z.infer; -// => { name: string } -``` - -To remove certain keys, use `.omit` . - -```ts -const NoIDRecipe = Recipe.omit({ id: true }); - -type NoIDRecipe = z.infer; -// => { name: string, ingredients: string[] } -``` - -### `.partial` - -Inspired by the built-in TypeScript utility type [Partial](https://www.typescriptlang.org/docs/handbook/utility-types.html#partialt), the `.partial` method makes all properties optional. - -Starting from this object: - -```ts -const user = z.object({ - email: z.string() - username: z.string(), -}); -// { email: string; username: string } -``` - -We can create a partial version: - -```ts -const partialUser = user.partial(); -// { email?: string | undefined; username?: string | undefined } -``` - -You can also specify which properties to make optional: - -```ts -const optionalEmail = user.partial({ - email: true, -}); -/* -{ - email?: string | undefined; - username: string -} -*/ -``` - -### `.deepPartial` - -The `.partial` method is shallow — it only applies one level deep. There is also a "deep" version: - -```ts -const user = z.object({ - username: z.string(), - location: z.object({ - latitude: z.number(), - longitude: z.number(), - }), - strings: z.array(z.object({ value: z.string() })), -}); - -const deepPartialUser = user.deepPartial(); - -/* -{ - username?: string | undefined, - location?: { - latitude?: number | undefined; - longitude?: number | undefined; - } | undefined, - strings?: { value?: string}[] -} -*/ -``` - -> Important limitation: deep partials only work as expected in hierarchies of objects, arrays, and tuples. - -#### Unrecognized keys - -By default Zod objects schemas strip out unrecognized keys during parsing. - -```ts -const person = z.object({ - name: z.string(), -}); - -person.parse({ - name: "bob dylan", - extraKey: 61, -}); -// => { name: "bob dylan" } -// extraKey has been stripped -``` - -### `.passthrough` - -Instead, if you want to pass through unknown keys, use `.passthrough()` . - -```ts -person.passthrough().parse({ - name: "bob dylan", - extraKey: 61, -}); -// => { name: "bob dylan", extraKey: 61 } -``` - -### `.strict` - -You can _disallow_ unknown keys with `.strict()` . If there are any unknown keys in the input, Zod will throw an error. - -```ts -const person = z - .object({ - name: z.string(), - }) - .strict(); - -person.parse({ - name: "bob dylan", - extraKey: 61, -}); -// => throws ZodError -``` - -### `.strip` - -You can use the `.strip` method to reset an object schema to the default behavior (stripping unrecognized keys). - -### `.catchall` - -You can pass a "catchall" schema into an object schema. All unknown keys will be validated against it. - -```ts -const person = z - .object({ - name: z.string(), - }) - .catchall(z.number()); - -person.parse({ - name: "bob dylan", - validExtraKey: 61, // works fine -}); - -person.parse({ - name: "bob dylan", - validExtraKey: false, // fails -}); -// => throws ZodError -``` - -Using `.catchall()` obviates `.passthrough()` , `.strip()` , or `.strict()`. All keys are now considered "known". - -## Arrays - -```ts -const stringArray = z.array(z.string()); - -// equivalent -const stringArray = z.string().array(); -``` - -Be careful with the `.array()` method. It returns a new `ZodArray` instance. This means the _order_ in which you call methods matters. For instance: - -```ts -z.string().optional().array(); // (string | undefined)[] -z.string().array().optional(); // string[] | undefined -``` - -### `.element` - -Use `.element` to access the schema for an element of the array. - -```ts -stringArray.element; // => string schema -``` - -### `.nonempty` - -If you want to ensure that an array contains at least one element, use `.nonempty()`. - -```ts -const nonEmptyStrings = z.string().array().nonempty(); -// the inferred type is now -// [string, ...string[]] - -nonEmptyStrings.parse([]); // throws: "Array cannot be empty" -nonEmptyStrings.parse(["Ariana Grande"]); // passes -``` - -You can optionally specify a custom error message: - -```ts -// optional custom error message -const nonEmptyStrings = z.string().array().nonempty({ - message: "Can't be empty!", -}); -``` - -### `.min/.max/.length` - -```ts -z.string().array().min(5); // must contain 5 or more items -z.string().array().max(5); // must contain 5 or fewer items -z.string().array().length(5); // must contain 5 items exactly -``` - -Unlike `.nonempty()` these methods do not change the inferred type. - -## Tuples - -Unlike arrays, tuples have a fixed number of elements and each element can have a different type. - -```ts -const athleteSchema = z.tuple([ - z.string(), // name - z.number(), // jersey number - z.object({ - pointsScored: z.number(), - }), // statistics -]); - -type Athlete = z.infer; -// type Athlete = [string, number, { pointsScored: number }] -``` - -## Unions - -Zod includes a built-in `z.union` method for composing "OR" types. - -```ts -const stringOrNumber = z.union([z.string(), z.number()]); - -stringOrNumber.parse("foo"); // passes -stringOrNumber.parse(14); // passes -``` - -Zod will test the input against each of the "options" in order and return the first value that validates successfully. - -For convenience, you can also use the `.or` method: - -```ts -const stringOrNumber = z.string().or(z.number()); -``` - -### Discriminated unions - -If the union consists of object schemas all identifiable by a common property, it is possible to use -the `z.discriminatedUnion` method. - -The advantage is in more efficient evaluation and more human friendly errors. With the basic union method the input is -tested against each of the provided "options", and in the case of invalidity, issues for all the "options" are shown in -the zod error. On the other hand, the discriminated union allows for selecting just one of the "options", testing -against it, and showing only the issues related to this "option". - -```ts -const item = z - .discriminatedUnion("type", [ - z.object({ type: z.literal("a"), a: z.string() }), - z.object({ type: z.literal("b"), b: z.string() }), - ]) - .parse({ type: "a", a: "abc" }); -``` - -## Records - -Record schemas are used to validate types such as `{ [k: string]: number }`. - -If you want to validate the _values_ of an object against some schema but don't care about the keys, use `Record`. - -```ts -const NumberCache = z.record(z.number()); - -type NumberCache = z.infer; -// => { [k: string]: number } -``` - -This is particularly useful for storing or caching items by ID. - -```ts -const userStore: UserStore = {}; - -userStore["77d2586b-9e8e-4ecf-8b21-ea7e0530eadd"] = { - name: "Carlotta", -}; // passes - -userStore["77d2586b-9e8e-4ecf-8b21-ea7e0530eadd"] = { - whatever: "Ice cream sundae", -}; // TypeError -``` - -#### A note on numerical keys - -You may have expected `z.record()` to accept two arguments, one for the keys and one for the values. After all, TypeScript's built-in Record type does: `Record` . Otherwise, how do you represent the TypeScript type `Record` in Zod? - -As it turns out, TypeScript's behavior surrounding `[k: number]` is a little unintuitive: - -```ts -const testMap: { [k: number]: string } = { - 1: "one", -}; - -for (const key in testMap) { - console.log(`${key}: ${typeof key}`); -} -// prints: `1: string` -``` - -As you can see, JavaScript automatically casts all object keys to strings under the hood. - -Since Zod is trying to bridge the gap between static and runtime types, it doesn't make sense to provide a way of creating a record schema with numerical keys, since there's no such thing as a numerical key in runtime JavaScript. - -## Maps - -```ts -const stringNumberMap = z.map(z.string(), z.number()); - -type StringNumberMap = z.infer; -// type StringNumberMap = Map -``` - -## Sets - -```ts -const numberSet = z.set(z.number()); -type NumberSet = z.infer; -// type NumberSet = Set -``` - -### `.nonempty/.min/.max/.size` - -```ts -z.set(z.string()).nonempty(); // must contain at least one item -z.set(z.string()).min(5); // must contain 5 or more items -z.set(z.string()).max(5); // must contain 5 or fewer items -z.set(z.string()).size(5); // must contain 5 items exactly -``` - -## Intersections - - - -Intersections are useful for creating "logical AND" types. This is useful for intersecting two object types. - -```ts -const Person = z.object({ - name: z.string(), -}); - -const Employee = z.object({ - role: z.string(), -}); - -const EmployedPerson = z.intersection(Person, Employee); - -// equivalent to: -const EmployedPerson = Person.and(Employee); -``` - -Though in many cases, it is recommended to use `A.merge(B)` to merge two objects. The `.merge` method returns a new `ZodObject` instance, whereas `A.and(B)` returns a less useful `ZodIntersection` instance that lacks common object methods like `pick` and `omit`. - -```ts -const a = z.union([z.number(), z.string()]); -const b = z.union([z.number(), z.boolean()]); -const c = z.intersection(a, b); - -type c = z.infer; // => number -``` - - - - - -## Recursive types - -You can define a recursive schema in Zod, but because of a limitation of TypeScript, their type can't be statically inferred. Instead you'll need to define the type definition manually, and provide it to Zod as a "type hint". - -```ts -interface Category { - name: string; - subcategories: Category[]; -} - -// cast to z.ZodType -const Category: z.ZodType = z.lazy(() => - z.object({ - name: z.string(), - subcategories: z.array(Category), - }) -); - -Category.parse({ - name: "People", - subcategories: [ - { - name: "Politicians", - subcategories: [{ name: "Presidents", subcategories: [] }], - }, - ], -}); // passes -``` - -Unfortunately this code is a bit duplicative, since you're declaring the types twice: once in the interface and again in the Zod definition. - - - -#### JSON type - -If you want to validate any JSON value, you can use the snippet below. - -```ts -const literalSchema = z.union([z.string(), z.number(), z.boolean(), z.null()]); -type Literal = z.infer; -type Json = Literal | { [key: string]: Json } | Json[]; -const jsonSchema: z.ZodType = z.lazy(() => - z.union([literalSchema, z.array(jsonSchema), z.record(jsonSchema)]) -); - -jsonSchema.parse(data); -``` - -Thanks to [ggoodman](https://github.com/ggoodman) for suggesting this. - -#### Cyclical objects - -Despite supporting recursive schemas, passing cyclical data into Zod will cause an infinite loop. - -## Promises - -```ts -const numberPromise = z.promise(z.number()); -``` - -"Parsing" works a little differently with promise schemas. Validation happens in two parts: - -1. Zod synchronously checks that the input is an instance of Promise (i.e. an object with `.then` and `.catch` methods.). -2. Zod uses `.then` to attach an additional validation step onto the existing Promise. You'll have to use `.catch` on the returned Promise to handle validation failures. - -```ts -numberPromise.parse("tuna"); -// ZodError: Non-Promise type: string - -numberPromise.parse(Promise.resolve("tuna")); -// => Promise - -const test = async () => { - await numberPromise.parse(Promise.resolve("tuna")); - // ZodError: Non-number type: string - - await numberPromise.parse(Promise.resolve(3.14)); - // => 3.14 -}; -``` - - - -## Instanceof - -You can use `z.instanceof` to check that the input is an instance of a class. This is useful to validate inputs against classes that are exported from third-party libraries. - -```ts -class Test { - name: string; -} - -const TestSchema = z.instanceof(Test); - -const blob: any = "whatever"; -TestSchema.parse(new Test()); // passes -TestSchema.parse("blob"); // throws -``` - -## Function schemas - -Zod also lets you define "function schemas". This makes it easy to validate the inputs and outputs of a function without intermixing your validation code and "business logic". - -You can create a function schema with `z.function(args, returnType)` . - -```ts -const myFunction = z.function(); - -type myFunction = z.infer; -// => ()=>unknown -``` - -**Define inputs and output** - -```ts -const myFunction = z - .function() - .args(z.string(), z.number()) // accepts an arbitrary number of arguments - .returns(z.boolean()); -type myFunction = z.infer; -// => (arg0: string, arg1: number)=>boolean -``` - -**Extract the input and output schemas** -You can extract the parameters and return type of a function schema. - -```ts -myFunction.parameters(); -// => ZodTuple<[ZodString, ZodNumber]> - -myFunction.returnType(); -// => ZodBoolean -``` - - - -> You can use the special `z.void()` option if your function doesn't return anything. This will let Zod properly infer the type of void-returning functions. (Void-returning functions actually return undefined.) - - - -Function schemas have an `.implement()` method which accepts a function and returns a new function that automatically validates it's inputs and outputs. - -```ts -const trimmedLength = z - .function() - .args(z.string()) // accepts an arbitrary number of arguments - .returns(z.number()) - .implement((x) => { - // TypeScript knows x is a string! - return x.trim().length; - }); - -trimmedLength("sandwich"); // => 8 -trimmedLength(" asdf "); // => 4 -``` - -If you only care about validating inputs, that's fine: - -```ts -const myFunction = z - .function() - .args(z.string()) - .implement((arg) => { - return [arg.length]; // - }); -myFunction; // (arg: string)=>number[] -``` - -## Preprocess - -Typically Zod operates under a "parse then transform" paradigm. Zod validates the input first, then passes it through a chain of transformation functions. (For more information about transforms, read the [.transform docs](#transform).) - -But sometimes you want to apply some transform to the input _before_ parsing happens. A common use case: type coercion. Zod enables this with the `z.preprocess()`. - -```ts -const castToString = z.preprocess((val) => String(val), z.string()); -``` - -This returns a `ZodEffects` instance. `ZodEffects` is a wrapper class that contains all logic pertaining to preprocessing, refinements, and transforms. - -# ZodType: methods and properties - -All Zod schemas contain certain methods. - -### `.parse` - -`.parse(data:unknown): T` - -Given any Zod schema, you can call its `.parse` method to check `data` is valid. If it is, a value is returned with full type information! Otherwise, an error is thrown. - -> IMPORTANT: The value returned by `.parse` is a _deep clone_ of the variable you passed in. - -```ts -const stringSchema = z.string(); -stringSchema.parse("fish"); // => returns "fish" -stringSchema.parse(12); // throws Error('Non-string type: number'); -``` - -### `.parseAsync` - -`.parseAsync(data:unknown): Promise` - -If you use asynchronous [refinements](#refine) or [transforms](#transform) (more on those later), you'll need to use `.parseAsync` - -```ts -const stringSchema = z.string().refine(async (val) => val.length > 20); -const value = await stringSchema.parseAsync("hello"); // => hello -``` - -### `.safeParse` - -`.safeParse(data:unknown): { success: true; data: T; } | { success: false; error: ZodError; }` - -If you don't want Zod to throw errors when validation fails, use `.safeParse`. This method returns an object containing either the successfully parsed data or a ZodError instance containing detailed information about the validation problems. - -```ts -stringSchema.safeParse(12); -// => { success: false; error: ZodError } - -stringSchema.safeParse("billie"); -// => { success: true; data: 'billie' } -``` - -The result is a _discriminated union_ so you can handle errors very conveniently: - -```ts -const result = stringSchema.safeParse("billie"); -if (!result.success) { - // handle error then return - result.error; -} else { - // do something - result.data; -} -``` - -### `.safeParseAsync` - -> Alias: `.spa` - -An asynchronous version of `safeParse`. - -```ts -await stringSchema.safeParseAsync("billie"); -``` - -For convenience, this has been aliased to `.spa`: - -```ts -await stringSchema.spa("billie"); -``` - -### `.refine` - -`.refine(validator: (data:T)=>any, params?: RefineParams)` - -Zod lets you provide custom validation logic via _refinements_. (For advanced features like creating multiple issues and customizing error codes, see [`.superRefine`](#superrefine).) - -Zod was designed to mirror TypeScript as closely as possible. But there are many so-called "refinement types" you may wish to check for that can't be represented in TypeScript's type system. For instance: checking that a number is an integer or that a string is a valid email address. - -For example, you can define a custom validation check on _any_ Zod schema with `.refine` : - -```ts -const myString = z.string().refine((val) => val.length <= 255, { - message: "String can't be more than 255 characters", -}); -``` - -> ⚠️ Refinement functions should not throw. Instead they should return a falsy value to signal failure. - -#### Arguments - -As you can see, `.refine` takes two arguments. - -1. The first is the validation function. This function takes one input (of type `T` — the inferred type of the schema) and returns `any`. Any truthy value will pass validation. (Prior to zod@1.6.2 the validation function had to return a boolean.) -2. The second argument accepts some options. You can use this to customize certain error-handling behavior: - -```ts -type RefineParams = { - // override error message - message?: string; - - // appended to error path - path?: (string | number)[]; - - // params object you can use to customize message - // in error map - params?: object; -}; -``` - -For advanced cases, the second argument can also be a function that returns `RefineParams`/ - -```ts -z.string().refine( - (val) => val.length > 10, - (val) => ({ message: `${val} is not more than 10 characters` }) -); -``` - -#### Customize error path - -```ts -const passwordForm = z - .object({ - password: z.string(), - confirm: z.string(), - }) - .refine((data) => data.password === data.confirm, { - message: "Passwords don't match", - path: ["confirm"], // path of error - }) - .parse({ password: "asdf", confirm: "qwer" }); -``` - -Because you provided a `path` parameter, the resulting error will be: - -```ts -ZodError { - issues: [{ - "code": "custom", - "path": [ "confirm" ], - "message": "Passwords don't match" - }] -} -``` - -#### Asynchronous refinements - -Refinements can also be async: - -```ts -const userId = z.string().refine(async (id) => { - // verify that ID exists in database - return true; -}); -``` - -> ⚠️If you use async refinements, you must use the `.parseAsync` method to parse data! Otherwise Zod will throw an error. - -#### Relationship to transforms - -Transforms and refinements can be interleaved: - -```ts -z.string() - .transform((val) => val.length) - .refine((val) => val > 25); -``` - - - -### `.superRefine` - -The `.refine` method is actually syntactic sugar atop a more versatile (and verbose) method called `superRefine`. Here's an example: - -```ts -const Strings = z.array(z.string()).superRefine((val, ctx) => { - if (val.length > 3) { - ctx.addIssue({ - code: z.ZodIssueCode.too_big, - maximum: 3, - type: "array", - inclusive: true, - message: "Too many items 😡", - }); - } - - if (val.length !== new Set(val).size) { - ctx.addIssue({ - code: z.ZodIssueCode.custom, - message: `No duplicated allowed.`, - }); - } -}); -``` - -You can add as many issues as you like. If `ctx.addIssue` is NOT called during the execution of the function, validation passes. - -Normally refinements always create issues with a `ZodIssueCode.custom` error code, but with `superRefine` you can create any issue of any code. Each issue code is described in detail in the Error Handling guide: [ERROR_HANDLING.md](ERROR_HANDLING.md). - -#### Abort early - -By default, parsing will continue even after a refinement check fails. For instance, if you chain together multiple refinements, they will all be executed. However, it may be desirable to _abort early_ to prevent later refinements from being executed. To achieve this, pass the `fatal` flag to `ctx.addIssue`: - -```ts -const Strings = z - .number() - .superRefine((val, ctx) => { - if (val < 10) { - ctx.addIssue({ - code: z.ZodIssueCode.custom, - message: "foo", - fatal: true, - }); - } - }) - .superRefine((val, ctx) => { - if (val !== " ") { - ctx.addIssue({ - code: z.ZodIssueCode.custom, - message: "bar", - }); - } - }); -``` - -### `.transform` - -To transform data after parsing, use the `transform` method. - -```ts -const stringToNumber = z.string().transform((val) => myString.length); -stringToNumber.parse("string"); // => 6 -``` - -> ⚠️ Transform functions must not throw. Make sure to use refinements before the transform or addIssue within the transform to make sure the input can be parsed by the transform. - -#### Validating during transform - -Similar to `superRefine`, `transform` can optionally take a `ctx`. This allows you to simultaneously -validate and transform the value, which can be simpler than chaining `refine` and `validate`. -When calling `ctx.addIssue` make sure to still return a value of the correct type otherwise the inferred type will include `undefined`. - -```ts -const Strings = z.string().transform((val, ctx) => { - const parsed = parseInt(val); - if (isNaN(parsed)) { - ctx.addIssue({ - code: z.ZodIssueCode.custom, - message: "Not a number", - }); - } - return parsed; -}); -``` - -#### Chaining order - -Note that `stringToNumber` above is an instance of the `ZodEffects` subclass. It is NOT an instance of `ZodString`. If you want to use the built-in methods of `ZodString` (e.g. `.email()`) you must apply those methods _before_ any transforms. - -```ts -const emailToDomain = z - .string() - .email() - .transform((val) => val.split("@")[1]); - -emailToDomain.parse("colinhacks@example.com"); // => example.com -``` - -#### Relationship to refinements - -Transforms and refinements can be interleaved: - -```ts -z.string() - .transform((val) => val.length) - .refine((val) => val > 25); -``` - -#### Async transforms - -Transforms can also be async. - -```ts -const IdToUser = z - .string() - .uuid() - .transform(async (id) => { - return await getUserById(id); - }); -``` - -> ⚠️ If your schema contains asynchronous transforms, you must use .parseAsync() or .safeParseAsync() to parse data. Otherwise Zod will throw an error. - -### `.default` - -You can use transforms to implement the concept of "default values" in Zod. - -```ts -const stringWithDefault = z.string().default("tuna"); - -stringWithDefault.parse(undefined); // => "tuna" -``` - -Optionally, you can pass a function into `.default` that will be re-executed whenever a default value needs to be generated: - -```ts -const numberWithRandomDefault = z.number().default(Math.random); - -numberWithRandomDefault.parse(undefined); // => 0.4413456736055323 -numberWithRandomDefault.parse(undefined); // => 0.1871840107401901 -numberWithRandomDefault.parse(undefined); // => 0.7223408162401552 -``` - -### `.optional` - -A convenience method that returns an optional version of a schema. - -```ts -const optionalString = z.string().optional(); // string | undefined - -// equivalent to -z.optional(z.string()); -``` - -### `.nullable` - -A convenience method that returns an nullable version of a schema. - -```ts -const nullableString = z.string().nullable(); // string | null - -// equivalent to -z.nullable(z.string()); -``` - -### `.nullish` - -A convenience method that returns a "nullish" version of a schema. Nullish schemas will accept both `undefined` and `null`. Read more about the concept of "nullish" [here](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-7.html#nullish-coalescing). - -```ts -const nullishString = z.string().nullish(); // string | null | undefined - -// equivalent to -z.string().optional().nullable(); -``` - -### `.array` - -A convenience method that returns an array schema for the given type: - -```ts -const nullableString = z.string().array(); // string[] - -// equivalent to -z.array(z.string()); -``` - -### `.promise` - -A convenience method for promise types: - -```ts -const stringPromise = z.string().promise(); // Promise - -// equivalent to -z.promise(z.string()); -``` - -### `.or` - -A convenience method for union types. - -```ts -z.string().or(z.number()); // string | number - -// equivalent to -z.union([z.string(), z.number()]); -``` - -### `.and` - -A convenience method for creating intersection types. - -```ts -z.object({ name: z.string() }).and(z.object({ age: z.number() })); // { name: string } & { age: number } - -// equivalent to -z.intersection(z.object({ name: z.string() }), z.object({ age: z.number() })); -``` - -# Guides and concepts - -## Type inference - -You can extract the TypeScript type of any schema with `z.infer` . - -```ts -const A = z.string(); -type A = z.infer; // string - -const u: A = 12; // TypeError -const u: A = "asdf"; // compiles -``` - -#### What about transforms? - -In reality each Zod schema internally tracks **two** types: an input and an output. For most schemas (e.g. `z.string()`) these two are the same. But once you add transforms into the mix, these two values can diverge. For instance `z.string().transform(val => val.length)` has an input of `string` and an output of `number`. - -You can separately extract the input and output types like so: - -```ts -const stringToNumber = z.string().transform((val) => val.length); - -// ⚠️ Important: z.infer returns the OUTPUT type! -type input = z.input; // string -type output = z.output; // number - -// equivalent to z.output! -type inferred = z.infer; // number -``` - -## Writing generic functions - -When attempting to write a functions that accepts a Zod schemas as an input, it's common to try something like this: - -```ts -function makeSchemaOptional(schema: z.ZodType) { - return schema.optional(); -} -``` - -This approach has some issues. The `schema` variable in this function is typed as an instance of `ZodType`, which is an abstract class that all Zod schemas inherit from. This approach loses type information, namely _which subclass_ the input actually is. - -```ts -const arg = makeSchemaOptional(z.string()); -arg.unwrap(); -``` - -A better approach is for the generate parameter to refer to _the schema as a whole_. - -```ts -function makeSchemaOptional(schema: T) { - return schema.optional(); -} -``` - -> `ZodTypeAny` is just a shorthand for `ZodType`, a type that is broad enough to match any Zod schema. - -As you can see, `schema` is now fully and properly typed. - -```ts -const arg = makeSchemaOptional(z.string()); -arg.unwrap(); // ZodString -``` - -### Restricting valid schemas - -The `ZodType` class has three generic parameters. - -```ts -class ZodType< - Output, - Def extends ZodTypeDef = ZodTypeDef, - Input = Output -> { ... } -``` - -By constraining these in your generic input, you can limit what schemas are allowable as inputs to your function: - -```ts -function makeSchemaOptional>(schema: T) { - return schema.optional(); -} - -makeSchemaOptional(z.string()); -// works fine - -makeSchemaOptional(z.number()); -// Error: 'ZodNumber' is not assignable to parameter of type 'ZodType' -``` - -## Error handling - -Zod provides a subclass of Error called `ZodError`. ZodErrors contain an `issues` array containing detailed information about the validation problems. - -```ts -const data = z.object({ name: z.string() }).safeParse({ name: 12 }); - -if (!data.success) { - data.error.issues; - /* [ - { - "code": "invalid_type", - "expected": "string", - "received": "number", - "path": [ "name" ], - "message": "Expected string, received number" - } - ] */ -} -``` - -#### Error formatting - -You can use the `.format()` method to convert this error into a nested object. - -```ts -data.error.format(); -/* { - name: { _errors: [ 'Expected string, received number' ] } -} */ -``` - -For detailed information about the possible error codes and how to customize error messages, check out the dedicated error handling guide: [ERROR_HANDLING.md](ERROR_HANDLING.md) - -# Comparison - -There are a handful of other widely-used validation libraries, but all of them have certain design limitations that make for a non-ideal developer experience. - - - - - - - -#### Joi - -[https://github.com/hapijs/joi](https://github.com/hapijs/joi) - -Doesn't support static type inference 😕 - -#### Yup - -[https://github.com/jquense/yup](https://github.com/jquense/yup) - -Yup is a full-featured library that was implemented first in vanilla JS, and later rewritten in TypeScript. - -Differences - -- Supports casting and transforms -- All object fields are optional by default -- Missing object methods: (partial, deepPartial) - -- Missing promise schemas -- Missing function schemas -- Missing union & intersection schemas - - - -#### io-ts - -[https://github.com/gcanti/io-ts](https://github.com/gcanti/io-ts) - -io-ts is an excellent library by gcanti. The API of io-ts heavily inspired the design of Zod. - -In our experience, io-ts prioritizes functional programming purity over developer experience in many cases. This is a valid and admirable design goal, but it makes io-ts particularly hard to integrate into an existing codebase with a more procedural or object-oriented bias. For instance, consider how to define an object with optional properties in io-ts: - -```ts -import * as t from "io-ts"; - -const A = t.type({ - foo: t.string, -}); - -const B = t.partial({ - bar: t.number, -}); - -const C = t.intersection([A, B]); - -type C = t.TypeOf; -// returns { foo: string; bar?: number | undefined } -``` - -You must define the required and optional props in separate object validators, pass the optionals through `t.partial` (which marks all properties as optional), then combine them with `t.intersection` . - -Consider the equivalent in Zod: - -```ts -const C = z.object({ - foo: z.string(), - bar: z.number().optional(), -}); - -type C = z.infer; -// returns { foo: string; bar?: number | undefined } -``` - -This more declarative API makes schema definitions vastly more concise. - -`io-ts` also requires the use of gcanti's functional programming library `fp-ts` to parse results and handle errors. This is another fantastic resource for developers looking to keep their codebase strictly functional. But depending on `fp-ts` necessarily comes with a lot of intellectual overhead; a developer has to be familiar with functional programming concepts and the `fp-ts` nomenclature to use the library. - -- Supports codecs with serialization & deserialization transforms -- Supports branded types -- Supports advanced functional programming, higher-kinded types, `fp-ts` compatibility -- Missing object methods: (pick, omit, partial, deepPartial, merge, extend) -- Missing nonempty arrays with proper typing (`[T, ...T[]]`) -- Missing promise schemas -- Missing function schemas - -#### Runtypes - -[https://github.com/pelotom/runtypes](https://github.com/pelotom/runtypes) - -Good type inference support, but limited options for object type masking (no `.pick` , `.omit` , `.extend` , etc.). No support for `Record` s (their `Record` is equivalent to Zod's `object` ). They DO support branded and readonly types, which Zod does not. - -- Supports "pattern matching": computed properties that distribute over unions -- Supports readonly types -- Missing object methods: (deepPartial, merge) -- Missing nonempty arrays with proper typing (`[T, ...T[]]`) -- Missing promise schemas -- Missing error customization - -#### Ow - -[https://github.com/sindresorhus/ow](https://github.com/sindresorhus/ow) - -Ow is focused on function input validation. It's a library that makes it easy to express complicated assert statements, but it doesn't let you parse untyped data. They support a much wider variety of types; Zod has a nearly one-to-one mapping with TypeScript's type system, whereas ow lets you validate several highly-specific types out of the box (e.g. `int32Array` , see full list in their README). - -If you want to validate function inputs, use function schemas in Zod! It's a much simpler approach that lets you reuse a function type declaration without repeating yourself (namely, copy-pasting a bunch of ow assertions at the beginning of every function). Also Zod lets you validate your return types as well, so you can be sure there won't be any unexpected data passed downstream. - -# Changelog - -View the changelog at [CHANGELOG.md](CHANGELOG.md) diff --git a/docsify.js b/docsify.js new file mode 100644 index 000000000..eef06bd79 --- /dev/null +++ b/docsify.js @@ -0,0 +1 @@ +!function(){function s(n){var r=Object.create(null);return function(e){var t=c(e)?e:JSON.stringify(e);return r[t]||(r[t]=n(e))}}var o=s(function(e){return e.replace(/([A-Z])/g,function(e){return"-"+e.toLowerCase()})}),l=Object.prototype.hasOwnProperty,y=Object.assign||function(e){for(var t=arguments,n=1;n/gm),it=Q(/^data-[\-\w.\u00B7-\uFFFF]/),ot=Q(/^aria-[\-\w]+$/),at=Q(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|cid|xmpp):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i),st=Q(/^(?:\w+script|data):/i),lt=Q(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g),ct="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e};function ut(e){if(Array.isArray(e)){for(var t=0,n=Array(e.length);t/i,t))xe(o,e);else{W&&(t=De(t,F," "),t=De(t,C," "));var l=e.nodeName.toLowerCase();if(Re(l,s,t))try{a?e.setAttributeNS(a,o,t):e.setAttribute(o,t),Le(c.removed)}catch(e){}}}Te("afterSanitizeAttributes",e,null)}}function $e(e){var t,n=Se(e);for(Te("beforeSanitizeShadowDOM",e,null);t=n.nextNode();)Te("uponSanitizeShadowNode",t,null),Ee(t)||(t.content instanceof u&&$e(t.content),Oe(t));Te("afterSanitizeShadowDOM",e,null)}return c.sanitize=function(e,t){var n,r=void 0,i=void 0,o=void 0;if((fe=!e)&&(e="\x3c!--\x3e"),"string"!=typeof e&&!Ae(e)){if("function"!=typeof e.toString)throw He("toString is not a function");if("string"!=typeof(e=e.toString()))throw He("dirty is not a string, aborting")}if(!c.isSupported){if("object"===ct(s.toStaticHTML)||"function"==typeof s.toStaticHTML){if("string"==typeof e)return s.toStaticHTML(e);if(Ae(e))return s.toStaticHTML(e.outerHTML)}return e}if(Y||O(t),c.removed=[],"string"==typeof e&&(re=!1),!re)if(e instanceof p)1===(t=(r=_e("\x3c!----\x3e")).ownerDocument.importNode(e,!0)).nodeType&&"BODY"===t.nodeName||"HTML"===t.nodeName?r=t:r.appendChild(t);else{if(!K&&!W&&!V&&-1===e.indexOf("<"))return k&&ee?k.createHTML(e):e;if(!(r=_e(e)))return K?null:w}r&&X&&we(r.firstChild);for(var a=Se(re?e:r);n=a.nextNode();)3===n.nodeType&&n===i||Ee(n)||(n.content instanceof u&&$e(n.content),Oe(n),i=n);if(i=null,re)return e;if(K){if(Q)for(o=S.call(r.ownerDocument);r.firstChild;)o.appendChild(r.firstChild);else o=r;return J&&(o=T.call(l,o,!0)),o}return e=V?r.outerHTML:r.innerHTML,W&&(e=De(e,F," "),e=De(e,C," ")),k&&ee?k.createHTML(e):e},c.setConfig=function(e){O(e),Y=!0},c.clearConfig=function(){ge=null,Y=!1},c.isValidAttribute=function(e,t,n){return ge||O({}),e=Ne(e),t=Ne(t),Re(e,t,n)},c.addHook=function(e,t){"function"==typeof t&&(R[e]=R[e]||[],ze(R[e],t))},c.removeHook=function(e){R[e]&&Le(R[e])},c.removeHooks=function(e){R[e]&&(R[e]=[])},c.removeAllHooks=function(){R={}},c}();function se(e){var t,n=e.loaded,r=e.total,i=e.step;ie||((e=v("div")).classList.add("progress"),a(g,e),ie=e),t=i?80<(t=parseInt(ie.style.width||0,10)+i)?80:t:Math.floor(n/r*100),ie.style.opacity=1,ie.style.width=95<=t?"100%":t+"%",95<=t&&(clearTimeout(oe),oe=setTimeout(function(e){ie.style.opacity=0,ie.style.width="0%"},200))}var le={};function ce(i,e,t){void 0===e&&(e=!1),void 0===t&&(t={});function o(){a.addEventListener.apply(a,arguments)}var n,a=new XMLHttpRequest,r=le[i];if(r)return{then:function(e){return e(r.content,r.opt)},abort:u};for(n in a.open("GET",i),t)l.call(t,n)&&a.setRequestHeader(n,t[n]);return a.send(),{then:function(t,n){var r;void 0===n&&(n=u),e&&(r=setInterval(function(e){return se({step:Math.floor(5*Math.random()+1)})},500),o("progress",se),o("loadend",function(e){se(e),clearInterval(r)})),o("error",n),o("load",function(e){e=e.target;400<=e.status?n(e):(e=le[i]={content:e.response,opt:{updatedAt:a.getResponseHeader("last-modified")}},t(e.content,e.opt))})},abort:function(e){return 4!==a.readyState&&a.abort()}}}function ue(e,t){e.innerHTML=e.innerHTML.replace(/var\(\s*--theme-color.*?\)/g,t)}var pe=f.title;function he(){var e,t=d("section.cover");t&&(e=t.getBoundingClientRect().height,window.pageYOffset>=e||t.classList.contains("hidden")?S(g,"add","sticky"):S(g,"remove","sticky"))}function de(e,t,r,n){var i=[];null!=(t=d(t))&&(i=k(t,"a"));var o,a=decodeURI(e.toURL(e.getCurrentPath()));return i.sort(function(e,t){return t.href.length-e.href.length}).forEach(function(e){var t=decodeURI(e.getAttribute("href")),n=r?e.parentNode:e;e.title=e.title||e.innerText,0!==a.indexOf(t)||o?S(n,"remove","active"):(o=e,S(n,"add","active"))}),n&&(f.title=o?o.title||o.innerText+" - "+pe:pe),o}function fe(e,t){for(var n=0;nthis.end&&e>=this.next}[this.direction]}},{key:"_defaultEase",value:function(e,t,n,r){return(e/=r/2)<1?n/2*e*e+t:-n/2*(--e*(e-2)-1)+t}}]),be);function be(){var e=0l){t=t||p;break}t=p}!t||(n=xe[Re(e,t.getAttribute("data-id"))])&&n!==a&&(a&&a.classList.remove("active"),n.classList.add("active"),a=n,!_e&&g.classList.contains("sticky")&&(s=r.clientHeight,e=a.offsetTop+a.clientHeight+40,n=a.offsetTop>=o.scrollTop&&e<=o.scrollTop+s,a=+e"']/),yt=/[&<>"']/g,bt=/[<>"']|&(?!#?\w+;)/,kt=/[<>"']|&(?!#?\w+;)/g,wt={"&":"&","<":"<",">":">",'"':""","'":"'"};var xt=/&(#(?:\d+)|(?:#x[0-9A-Fa-f]+)|(?:\w+));?/gi;function _t(e){return e.replace(xt,function(e,t){return"colon"===(t=t.toLowerCase())?":":"#"===t.charAt(0)?"x"===t.charAt(1)?String.fromCharCode(parseInt(t.substring(2),16)):String.fromCharCode(+t.substring(1)):""})}var St=/(^|[^\[])\^/g;var At=/[^\w:]/g,Tt=/^$|^[a-z][a-z0-9+.-]*:|^[?#]/i;var Et={},Rt=/^[^:]+:\/*[^/]*$/,Ot=/^([^:]+:)[\s\S]*$/,$t=/^([^:]+:\/*[^/]*)[\s\S]*$/;function Ft(e,t){Et[" "+e]||(Rt.test(e)?Et[" "+e]=e+"/":Et[" "+e]=Ct(e,"/",!0));var n=-1===(e=Et[" "+e]).indexOf(":");return"//"===t.substring(0,2)?n?t:e.replace(Ot,"$1")+t:"/"===t.charAt(0)?n?t:e.replace($t,"$1")+t:e+t}function Ct(e,t,n){var r=e.length;if(0===r)return"";for(var i=0;it)n.splice(t);else for(;n.length>=1,e+=e;return n+e},jt=mt.defaults,Ht=Ct,qt=It,Ut=Lt,Bt=I;function Zt(e,t,n){var r=t.href,i=t.title?Ut(t.title):null,t=e[1].replace(/\\([\[\]])/g,"$1");return"!"!==e[0].charAt(0)?{type:"link",raw:n,href:r,title:i,text:t}:{type:"image",raw:n,href:r,title:i,text:Ut(t)}}var Gt=function(){function e(e){this.options=e||jt}return e.prototype.space=function(e){e=this.rules.block.newline.exec(e);if(e)return 1=n.length?e.slice(n.length):e}).join("\n")}(n,t[3]||"");return{type:"code",raw:n,lang:t[2]?t[2].trim():t[2],text:e}}},e.prototype.heading=function(e){var t=this.rules.block.heading.exec(e);if(t){var n=t[2].trim();return/#$/.test(n)&&(e=Ht(n,"#"),!this.options.pedantic&&e&&!/ $/.test(e)||(n=e.trim())),{type:"heading",raw:t[0],depth:t[1].length,text:n}}},e.prototype.nptable=function(e){e=this.rules.block.nptable.exec(e);if(e){var t={type:"table",header:qt(e[1].replace(/^ *| *\| *$/g,"")),align:e[2].replace(/^ *|\| *$/g,"").split(/ *\| */),cells:e[3]?e[3].replace(/\n$/,"").split("\n"):[],raw:e[0]};if(t.header.length===t.align.length){for(var n=t.align.length,r=0;r ?/gm,"");return{type:"blockquote",raw:t[0],text:e}}},e.prototype.list=function(e){e=this.rules.block.list.exec(e);if(e){for(var t,n,r,i,o,a=e[0],s=e[2],l=1d[1].length:r[1].length>d[0].length||3/i.test(e[0])&&(t=!1),!n&&/^<(pre|code|kbd|script)(\s|>)/i.test(e[0])?n=!0:n&&/^<\/(pre|code|kbd|script)(\s|>)/i.test(e[0])&&(n=!1),{type:this.options.sanitize?"text":"html",raw:e[0],inLink:t,inRawBlock:n,text:this.options.sanitize?this.options.sanitizer?this.options.sanitizer(e[0]):Ut(e[0]):e[0]}},e.prototype.link=function(e){var t=this.rules.inline.link.exec(e);if(t){var n=t[2].trim();if(!this.options.pedantic&&/^$/.test(n))return;e=Ht(n.slice(0,-1),"\\");if((n.length-e.length)%2==0)return}else{var r=Bt(t[2],"()");-1$/.test(n)?r.slice(1):r.slice(1,-1)),Zt(t,{href:r?r.replace(this.rules.inline._escapes,"$1"):r,title:o?o.replace(this.rules.inline._escapes,"$1"):o},t[0])}},e.prototype.reflink=function(e,t){if((n=this.rules.inline.reflink.exec(e))||(n=this.rules.inline.nolink.exec(e))){e=(n[2]||n[1]).replace(/\s+/g," ");if((e=t[e.toLowerCase()])&&e.href)return Zt(n,e,n[0]);var n=n[0].charAt(0);return{type:"text",raw:n,text:n}}},e.prototype.strong=function(e,t,n){void 0===n&&(n="");var r=this.rules.inline.strong.start.exec(e);if(r&&(!r[1]||r[1]&&(""===n||this.rules.inline.punctuation.exec(n)))){t=t.slice(-1*e.length);var i,o="**"===r[0]?this.rules.inline.strong.endAst:this.rules.inline.strong.endUnd;for(o.lastIndex=0;null!=(r=o.exec(t));)if(i=this.rules.inline.strong.middle.exec(t.slice(0,r.index+3)))return{type:"strong",raw:e.slice(0,i[0].length),text:e.slice(2,i[0].length-2)}}},e.prototype.em=function(e,t,n){void 0===n&&(n="");var r=this.rules.inline.em.start.exec(e);if(r&&(!r[1]||r[1]&&(""===n||this.rules.inline.punctuation.exec(n)))){t=t.slice(-1*e.length);var i,o="*"===r[0]?this.rules.inline.em.endAst:this.rules.inline.em.endUnd;for(o.lastIndex=0;null!=(r=o.exec(t));)if(i=this.rules.inline.em.middle.exec(t.slice(0,r.index+2)))return{type:"em",raw:e.slice(0,i[0].length),text:e.slice(1,i[0].length-1)}}},e.prototype.codespan=function(e){var t=this.rules.inline.code.exec(e);if(t){var n=t[2].replace(/\n/g," "),r=/[^ ]/.test(n),e=/^ /.test(n)&&/ $/.test(n);return r&&e&&(n=n.substring(1,n.length-1)),n=Ut(n,!0),{type:"codespan",raw:t[0],text:n}}},e.prototype.br=function(e){e=this.rules.inline.br.exec(e);if(e)return{type:"br",raw:e[0]}},e.prototype.del=function(e){e=this.rules.inline.del.exec(e);if(e)return{type:"del",raw:e[0],text:e[2]}},e.prototype.autolink=function(e,t){e=this.rules.inline.autolink.exec(e);if(e){var n,t="@"===e[2]?"mailto:"+(n=Ut(this.options.mangle?t(e[1]):e[1])):n=Ut(e[1]);return{type:"link",raw:e[0],text:n,href:t,tokens:[{type:"text",raw:n,text:n}]}}},e.prototype.url=function(e,t){var n,r,i,o;if(n=this.rules.inline.url.exec(e)){if("@"===n[2])i="mailto:"+(r=Ut(this.options.mangle?t(n[0]):n[0]));else{for(;o=n[0],n[0]=this.rules.inline._backpedal.exec(n[0])[0],o!==n[0];);r=Ut(n[0]),i="www."===n[1]?"http://"+r:r}return{type:"link",raw:n[0],text:r,href:i,tokens:[{type:"text",raw:r,text:r}]}}},e.prototype.inlineText=function(e,t,n){e=this.rules.inline.text.exec(e);if(e){n=t?this.options.sanitize?this.options.sanitizer?this.options.sanitizer(e[0]):Ut(e[0]):e[0]:Ut(this.options.smartypants?n(e[0]):e[0]);return{type:"text",raw:e[0],text:n}}},e}(),It=Dt,I=Nt,Dt=Pt,Nt={newline:/^(?: *(?:\n|$))+/,code:/^( {4}[^\n]+(?:\n(?: *(?:\n|$))*)?)+/,fences:/^ {0,3}(`{3,}(?=[^`\n]*\n)|~{3,})([^\n]*)\n(?:|([\s\S]*?)\n)(?: {0,3}\1[~`]* *(?:\n+|$)|$)/,hr:/^ {0,3}((?:- *){3,}|(?:_ *){3,}|(?:\* *){3,})(?:\n+|$)/,heading:/^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/,blockquote:/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/,list:/^( {0,3})(bull) [\s\S]+?(?:hr|def|\n{2,}(?! )(?! {0,3}bull )\n*|\s*$)/,html:"^ {0,3}(?:<(script|pre|style)[\\s>][\\s\\S]*?(?:[^\\n]*\\n+|$)|comment[^\\n]*(\\n+|$)|<\\?[\\s\\S]*?(?:\\?>\\n*|$)|\\n*|$)|\\n*|$)|)[\\s\\S]*?(?:\\n{2,}|$)|<(?!script|pre|style)([a-z][\\w-]*)(?:attribute)*? */?>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:\\n{2,}|$)|(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:\\n{2,}|$))",def:/^ {0,3}\[(label)\]: *\n? *]+)>?(?:(?: +\n? *| *\n *)(title))? *(?:\n+|$)/,nptable:It,table:It,lheading:/^([^\n]+)\n {0,3}(=+|-+) *(?:\n+|$)/,_paragraph:/^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html| +\n)[^\n]+)*)/,text:/^[^\n]+/,_label:/(?!\s*\])(?:\\[\[\]]|[^\[\]])+/,_title:/(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/};Nt.def=I(Nt.def).replace("label",Nt._label).replace("title",Nt._title).getRegex(),Nt.bullet=/(?:[*+-]|\d{1,9}[.)])/,Nt.item=/^( *)(bull) ?[^\n]*(?:\n(?! *bull ?)[^\n]*)*/,Nt.item=I(Nt.item,"gm").replace(/bull/g,Nt.bullet).getRegex(),Nt.listItemStart=I(/^( *)(bull)/).replace("bull",Nt.bullet).getRegex(),Nt.list=I(Nt.list).replace(/bull/g,Nt.bullet).replace("hr","\\n+(?=\\1?(?:(?:- *){3,}|(?:_ *){3,}|(?:\\* *){3,})(?:\\n+|$))").replace("def","\\n+(?="+Nt.def.source+")").getRegex(),Nt._tag="address|article|aside|base|basefont|blockquote|body|caption|center|col|colgroup|dd|details|dialog|dir|div|dl|dt|fieldset|figcaption|figure|footer|form|frame|frameset|h[1-6]|head|header|hr|html|iframe|legend|li|link|main|menu|menuitem|meta|nav|noframes|ol|optgroup|option|p|param|section|source|summary|table|tbody|td|tfoot|th|thead|title|tr|track|ul",Nt._comment=/|$)/,Nt.html=I(Nt.html,"i").replace("comment",Nt._comment).replace("tag",Nt._tag).replace("attribute",/ +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex(),Nt.paragraph=I(Nt._paragraph).replace("hr",Nt.hr).replace("heading"," {0,3}#{1,6} ").replace("|lheading","").replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)]) ").replace("html",")|<(?:script|pre|style|!--)").replace("tag",Nt._tag).getRegex(),Nt.blockquote=I(Nt.blockquote).replace("paragraph",Nt.paragraph).getRegex(),Nt.normal=Dt({},Nt),Nt.gfm=Dt({},Nt.normal,{nptable:"^ *([^|\\n ].*\\|.*)\\n {0,3}([-:]+ *\\|[-| :]*)(?:\\n((?:(?!\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)",table:"^ *\\|(.+)\\n {0,3}\\|?( *[-:]+[-| :]*)(?:\\n *((?:(?!\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)"}),Nt.gfm.nptable=I(Nt.gfm.nptable).replace("hr",Nt.hr).replace("heading"," {0,3}#{1,6} ").replace("blockquote"," {0,3}>").replace("code"," {4}[^\\n]").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)]) ").replace("html",")|<(?:script|pre|style|!--)").replace("tag",Nt._tag).getRegex(),Nt.gfm.table=I(Nt.gfm.table).replace("hr",Nt.hr).replace("heading"," {0,3}#{1,6} ").replace("blockquote"," {0,3}>").replace("code"," {4}[^\\n]").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)]) ").replace("html",")|<(?:script|pre|style|!--)").replace("tag",Nt._tag).getRegex(),Nt.pedantic=Dt({},Nt.normal,{html:I("^ *(?:comment *(?:\\n|\\s*$)|<(tag)[\\s\\S]+? *(?:\\n{2,}|\\s*$)|\\s]*)*?/?> *(?:\\n{2,}|\\s*$))").replace("comment",Nt._comment).replace(/tag/g,"(?!(?:a|em|strong|small|s|cite|q|dfn|abbr|data|time|code|var|samp|kbd|sub|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo|span|br|wbr|ins|del|img)\\b)\\w+(?!:|[^\\w\\s@]*@)\\b").getRegex(),def:/^ *\[([^\]]+)\]: *]+)>?(?: +(["(][^\n]+[")]))? *(?:\n+|$)/,heading:/^(#{1,6})(.*)(?:\n+|$)/,fences:It,paragraph:I(Nt.normal._paragraph).replace("hr",Nt.hr).replace("heading"," *#{1,6} *[^\n]").replace("lheading",Nt.lheading).replace("blockquote"," {0,3}>").replace("|fences","").replace("|list","").replace("|html","").getRegex()});It={escape:/^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/,autolink:/^<(scheme:[^\s\x00-\x1f<>]*|email)>/,url:It,tag:"^comment|^|^<[a-zA-Z][\\w-]*(?:attribute)*?\\s*/?>|^<\\?[\\s\\S]*?\\?>|^|^",link:/^!?\[(label)\]\(\s*(href)(?:\s+(title))?\s*\)/,reflink:/^!?\[(label)\]\[(?!\s*\])((?:\\[\[\]]?|[^\[\]\\])+)\]/,nolink:/^!?\[(?!\s*\])((?:\[[^\[\]]*\]|\\[\[\]]|[^\[\]])*)\](?:\[\])?/,reflinkSearch:"reflink|nolink(?!\\()",strong:{start:/^(?:(\*\*(?=[*punctuation]))|\*\*)(?![\s])|__/,middle:/^\*\*(?:(?:(?!overlapSkip)(?:[^*]|\\\*)|overlapSkip)|\*(?:(?!overlapSkip)(?:[^*]|\\\*)|overlapSkip)*?\*)+?\*\*$|^__(?![\s])((?:(?:(?!overlapSkip)(?:[^_]|\\_)|overlapSkip)|_(?:(?!overlapSkip)(?:[^_]|\\_)|overlapSkip)*?_)+?)__$/,endAst:/[^punctuation\s]\*\*(?!\*)|[punctuation]\*\*(?!\*)(?:(?=[punctuation_\s]|$))/,endUnd:/[^\s]__(?!_)(?:(?=[punctuation*\s])|$)/},em:{start:/^(?:(\*(?=[punctuation]))|\*)(?![*\s])|_/,middle:/^\*(?:(?:(?!overlapSkip)(?:[^*]|\\\*)|overlapSkip)|\*(?:(?!overlapSkip)(?:[^*]|\\\*)|overlapSkip)*?\*)+?\*$|^_(?![_\s])(?:(?:(?!overlapSkip)(?:[^_]|\\_)|overlapSkip)|_(?:(?!overlapSkip)(?:[^_]|\\_)|overlapSkip)*?_)+?_$/,endAst:/[^punctuation\s]\*(?!\*)|[punctuation]\*(?!\*)(?:(?=[punctuation_\s]|$))/,endUnd:/[^\s]_(?!_)(?:(?=[punctuation*\s])|$)/},code:/^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/,br:/^( {2,}|\\)\n(?!\s*$)/,del:It,text:/^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\?@\\[\\]`^{|}~"};It.punctuation=I(It.punctuation).replace(/punctuation/g,It._punctuation).getRegex(),It._blockSkip="\\[[^\\]]*?\\]\\([^\\)]*?\\)|`[^`]*?`|<[^>]*?>",It._overlapSkip="__[^_]*?__|\\*\\*\\[^\\*\\]*?\\*\\*",It._comment=I(Nt._comment).replace("(?:--\x3e|$)","--\x3e").getRegex(),It.em.start=I(It.em.start).replace(/punctuation/g,It._punctuation).getRegex(),It.em.middle=I(It.em.middle).replace(/punctuation/g,It._punctuation).replace(/overlapSkip/g,It._overlapSkip).getRegex(),It.em.endAst=I(It.em.endAst,"g").replace(/punctuation/g,It._punctuation).getRegex(),It.em.endUnd=I(It.em.endUnd,"g").replace(/punctuation/g,It._punctuation).getRegex(),It.strong.start=I(It.strong.start).replace(/punctuation/g,It._punctuation).getRegex(),It.strong.middle=I(It.strong.middle).replace(/punctuation/g,It._punctuation).replace(/overlapSkip/g,It._overlapSkip).getRegex(),It.strong.endAst=I(It.strong.endAst,"g").replace(/punctuation/g,It._punctuation).getRegex(),It.strong.endUnd=I(It.strong.endUnd,"g").replace(/punctuation/g,It._punctuation).getRegex(),It.blockSkip=I(It._blockSkip,"g").getRegex(),It.overlapSkip=I(It._overlapSkip,"g").getRegex(),It._escapes=/\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/g,It._scheme=/[a-zA-Z][a-zA-Z0-9+.-]{1,31}/,It._email=/[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+(@)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+(?![-_])/,It.autolink=I(It.autolink).replace("scheme",It._scheme).replace("email",It._email).getRegex(),It._attribute=/\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/,It.tag=I(It.tag).replace("comment",It._comment).replace("attribute",It._attribute).getRegex(),It._label=/(?:\[(?:\\.|[^\[\]\\])*\]|\\.|`[^`]*`|[^\[\]\\`])*?/,It._href=/<(?:\\.|[^\n<>\\])+>|[^\s\x00-\x1f]*/,It._title=/"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/,It.link=I(It.link).replace("label",It._label).replace("href",It._href).replace("title",It._title).getRegex(),It.reflink=I(It.reflink).replace("label",It._label).getRegex(),It.reflinkSearch=I(It.reflinkSearch,"g").replace("reflink",It.reflink).replace("nolink",It.nolink).getRegex(),It.normal=Dt({},It),It.pedantic=Dt({},It.normal,{strong:{start:/^__|\*\*/,middle:/^__(?=\S)([\s\S]*?\S)__(?!_)|^\*\*(?=\S)([\s\S]*?\S)\*\*(?!\*)/,endAst:/\*\*(?!\*)/g,endUnd:/__(?!_)/g},em:{start:/^_|\*/,middle:/^()\*(?=\S)([\s\S]*?\S)\*(?!\*)|^_(?=\S)([\s\S]*?\S)_(?!_)/,endAst:/\*(?!\*)/g,endUnd:/_(?!_)/g},link:I(/^!?\[(label)\]\((.*?)\)/).replace("label",It._label).getRegex(),reflink:I(/^!?\[(label)\]\s*\[([^\]]*)\]/).replace("label",It._label).getRegex()}),It.gfm=Dt({},It.normal,{escape:I(It.escape).replace("])","~|])").getRegex(),_extended_email:/[A-Za-z0-9._+-]+(@)[a-zA-Z0-9-_]+(?:\.[a-zA-Z0-9-_]*[a-zA-Z0-9])+(?![-_])/,url:/^((?:ftp|https?):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/,_backpedal:/(?:[^?!.,:;*_~()&]+|\([^)]*\)|&(?![a-zA-Z0-9]+;$)|[?!.,:;*_~)]+(?!$))+/,del:/^(~~?)(?=[^\s~])([\s\S]*?[^\s~])\1(?=[^~]|$)/,text:/^([`~]+|[^`~])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\'+(n?e:nn(e,!0))+"\n":"
"+(n?e:nn(e,!0))+"
\n"},e.prototype.blockquote=function(e){return"
\n"+e+"
\n"},e.prototype.html=function(e){return e},e.prototype.heading=function(e,t,n,r){return this.options.headerIds?"'+e+"\n":""+e+"\n"},e.prototype.hr=function(){return this.options.xhtml?"
\n":"
\n"},e.prototype.list=function(e,t,n){var r=t?"ol":"ul";return"<"+r+(t&&1!==n?' start="'+n+'"':"")+">\n"+e+"\n"},e.prototype.listitem=function(e){return"
  • "+e+"
  • \n"},e.prototype.checkbox=function(e){return" "},e.prototype.paragraph=function(e){return"

    "+e+"

    \n"},e.prototype.table=function(e,t){return"\n\n"+e+"\n"+(t=t&&""+t+"")+"
    \n"},e.prototype.tablerow=function(e){return"\n"+e+"\n"},e.prototype.tablecell=function(e,t){var n=t.header?"th":"td";return(t.align?"<"+n+' align="'+t.align+'">':"<"+n+">")+e+"\n"},e.prototype.strong=function(e){return""+e+""},e.prototype.em=function(e){return""+e+""},e.prototype.codespan=function(e){return""+e+""},e.prototype.br=function(){return this.options.xhtml?"
    ":"
    "},e.prototype.del=function(e){return""+e+""},e.prototype.link=function(e,t,n){if(null===(e=tn(this.options.sanitize,this.options.baseUrl,e)))return n;e='"},e.prototype.image=function(e,t,n){if(null===(e=tn(this.options.sanitize,this.options.baseUrl,e)))return n;n=''+n+'":">"},e.prototype.text=function(e){return e},e}(),on=function(){function e(){}return e.prototype.strong=function(e){return e},e.prototype.em=function(e){return e},e.prototype.codespan=function(e){return e},e.prototype.del=function(e){return e},e.prototype.html=function(e){return e},e.prototype.text=function(e){return e},e.prototype.link=function(e,t,n){return""+n},e.prototype.image=function(e,t,n){return""+n},e.prototype.br=function(){return""},e}(),an=function(){function e(){this.seen={}}return e.prototype.serialize=function(e){return e.toLowerCase().trim().replace(/<[!\/a-z].*?>/gi,"").replace(/[\u2000-\u206F\u2E00-\u2E7F\\'!"#$%&()*+,./:;<=>?@[\]^`{|}~]/g,"").replace(/\s/g,"-")},e.prototype.getNextSafeSlug=function(e,t){var n=e,r=0;if(this.seen.hasOwnProperty(n))for(r=this.seen[e];n=e+"-"+ ++r,this.seen.hasOwnProperty(n););return t||(this.seen[e]=r,this.seen[n]=0),n},e.prototype.slug=function(e,t){void 0===t&&(t={});var n=this.serialize(e);return this.getNextSafeSlug(n,t.dryrun)},e}(),sn=mt.defaults,ln=zt,cn=function(){function n(e){this.options=e||sn,this.options.renderer=this.options.renderer||new rn,this.renderer=this.options.renderer,this.renderer.options=this.options,this.textRenderer=new on,this.slugger=new an}return n.parse=function(e,t){return new n(t).parse(e)},n.parseInline=function(e,t){return new n(t).parseInline(e)},n.prototype.parse=function(e,t){void 0===t&&(t=!0);for(var n,r,i,o,a,s,l,c,u,p,h,d,f,g,m,v="",y=e.length,b=0;bAn error occurred:

    "+hn(e.message+"",!0)+"
    ";throw e}}fn.options=fn.setOptions=function(e){return un(fn.defaults,e),dn(fn.defaults),fn},fn.getDefaults=Lt,fn.defaults=mt,fn.use=function(o){var t,e=un({},o);if(o.renderer){var n,a=fn.defaults.renderer||new rn;for(n in o.renderer)!function(r){var i=a[r];a[r]=function(){for(var e=[],t=arguments.length;t--;)e[t]=arguments[t];var n=o.renderer[r].apply(a,e);return!1===n&&(n=i.apply(a,e)),n}}(n);e.renderer=a}if(o.tokenizer){var i,s=fn.defaults.tokenizer||new Gt;for(i in o.tokenizer)!function(){var r=s[i];s[i]=function(){for(var e=[],t=arguments.length;t--;)e[t]=arguments[t];var n=o.tokenizer[i].apply(s,e);return!1===n&&(n=r.apply(s,e)),n}}();e.tokenizer=s}o.walkTokens&&(t=fn.defaults.walkTokens,e.walkTokens=function(e){o.walkTokens(e),t&&t(e)}),fn.setOptions(e)},fn.walkTokens=function(e,t){for(var n=0,r=e;nAn error occurred:

    "+hn(e.message+"",!0)+"
    ";throw e}},fn.Parser=cn,fn.parser=cn.parse,fn.Renderer=rn,fn.TextRenderer=on,fn.Lexer=Jt,fn.lexer=Jt.lex,fn.Tokenizer=Gt,fn.Slugger=an;var gn=fn.parse=fn;function mn(e,n){if(void 0===n&&(n='
      {inner}
    '),!e||!e.length)return"";var r="";return e.forEach(function(e){var t=e.title.replace(/(<([^>]+)>)/g,"");r+='
  • '+e.title+"
  • ",e.children&&(r+=mn(e.children,n))}),n.replace("{inner}",r)}function vn(e,t){return'

    '+t.slice(5).trim()+"

    "}function yn(e,r){var i=[],o={};return e.forEach(function(e){var t=e.level||1,n=t-1;r?@[\]^`{|}~]/g;function wn(e){return e.toLowerCase()}function xn(e){if("string"!=typeof e)return"";var t=e.trim().replace(/[A-Z]+/g,wn).replace(/<[^>]+>/g,"").replace(kn,"").replace(/\s/g,"-").replace(/-+/g,"-").replace(/^(\d)/,"_$1"),e=bn[t],e=l.call(bn,t)?e+1:0;return(bn[t]=e)&&(t=t+"-"+e),t}function _n(e,t){return''+t+''}function Sn(e){void 0===e&&(e="");var r={};return{str:e=e&&e.replace(/^('|")/,"").replace(/('|")$/,"").replace(/(?:^|\s):([\w-]+:?)=?([\w-%]+)?/g,function(e,t,n){return-1===t.indexOf(":")?(r[t]=n&&n.replace(/"/g,"")||!0,""):e}).trim(),config:r}}function An(e){return void 0===e&&(e=""),e.replace(/(<\/?a.*?>)/gi,"")}xn.clear=function(){bn={}};var Tn,En=ft(function(e){var a,s,l,c,u,r,t,i=function(l){var c=/\blang(?:uage)?-([\w-]+)\b/i,t=0,$={manual:l.Prism&&l.Prism.manual,disableWorkerMessageHandler:l.Prism&&l.Prism.disableWorkerMessageHandler,util:{encode:function e(t){return t instanceof F?new F(t.type,e(t.content),t.alias):Array.isArray(t)?t.map(e):t.replace(/&/g,"&").replace(/=a.reach);y+=v.value.length,v=v.next){var b=v.value;if(n.length>t.length)return;if(!(b instanceof F)){var k,w=1;if(f){if(!(k=C(m,y,t,d)))break;var x=k.index,_=k.index+k[0].length,S=y;for(S+=v.value.length;S<=x;)v=v.next,S+=v.value.length;if(S-=v.value.length,y=S,v.value instanceof F)continue;for(var A=v;A!==n.tail&&(S<_||"string"==typeof A.value);A=A.next)w++,S+=A.value.length;w--,b=t.slice(y,S),k.index-=y}else if(!(k=C(m,0,b,d)))continue;var x=k.index,T=k[0],E=b.slice(0,x),R=b.slice(x+T.length),O=y+b.length;a&&O>a.reach&&(a.reach=O);var b=v.prev;E&&(b=L(n,b,E),y+=E.length),z(n,b,w);var T=new F(s,h?$.tokenize(T,h):T,g,T);v=L(n,b,T),R&&L(n,v,R),1"+i.content+""},!l.document)return l.addEventListener&&($.disableWorkerMessageHandler||l.addEventListener("message",function(e){var t=JSON.parse(e.data),n=t.language,e=t.code,t=t.immediateClose;l.postMessage($.highlight(e,$.languages[n],n)),t&&l.close()},!1)),$;var e,n=$.util.currentScript();function r(){$.manual||$.highlightAll()}return n&&($.filename=n.src,n.hasAttribute("data-manual")&&($.manual=!0)),$.manual||("loading"===(e=document.readyState)||"interactive"===e&&n&&n.defer?document.addEventListener("DOMContentLoaded",r):window.requestAnimationFrame?window.requestAnimationFrame(r):window.setTimeout(r,16)),$}("undefined"!=typeof window?window:"undefined"!=typeof WorkerGlobalScope&&self instanceof WorkerGlobalScope?self:{});function p(e,t){var n=(n=e.className).replace(r," ")+" language-"+t;e.className=n.replace(/\s+/g," ").trim()}e.exports&&(e.exports=i),void 0!==dt&&(dt.Prism=i),i.languages.markup={comment://,prolog:/<\?[\s\S]+?\?>/,doctype:{pattern:/"'[\]]|"[^"]*"|'[^']*')+(?:\[(?:[^<"'\]]|"[^"]*"|'[^']*'|<(?!!--)|)*\]\s*)?>/i,greedy:!0,inside:{"internal-subset":{pattern:/(\[)[\s\S]+(?=\]>$)/,lookbehind:!0,greedy:!0,inside:null},string:{pattern:/"[^"]*"|'[^']*'/,greedy:!0},punctuation:/^$|[[\]]/,"doctype-tag":/^DOCTYPE/,name:/[^\s<>'"]+/}},cdata://i,tag:{pattern:/<\/?(?!\d)[^\s>\/=$<%]+(?:\s(?:\s*[^\s>\/=]+(?:\s*=\s*(?:"[^"]*"|'[^']*'|[^\s'">=]+(?=[\s>]))|(?=[\s/>])))+)?\s*\/?>/,greedy:!0,inside:{tag:{pattern:/^<\/?[^\s>\/]+/,inside:{punctuation:/^<\/?/,namespace:/^[^\s>\/:]+:/}},"attr-value":{pattern:/=\s*(?:"[^"]*"|'[^']*'|[^\s'">=]+)/,inside:{punctuation:[{pattern:/^=/,alias:"attr-equals"},/"|'/]}},punctuation:/\/?>/,"attr-name":{pattern:/[^\s>\/]+/,inside:{namespace:/^[^\s>\/:]+:/}}}},entity:[{pattern:/&[\da-z]{1,8};/i,alias:"named-entity"},/&#x?[\da-f]{1,8};/i]},i.languages.markup.tag.inside["attr-value"].inside.entity=i.languages.markup.entity,i.languages.markup.doctype.inside["internal-subset"].inside=i.languages.markup,i.hooks.add("wrap",function(e){"entity"===e.type&&(e.attributes.title=e.content.replace(/&/,"&"))}),Object.defineProperty(i.languages.markup.tag,"addInlined",{value:function(e,t){var n={};n["language-"+t]={pattern:/(^$)/i,lookbehind:!0,inside:i.languages[t]},n.cdata=/^$/i;n={"included-cdata":{pattern://i,inside:n}};n["language-"+t]={pattern:/[\s\S]+/,inside:i.languages[t]};t={};t[e]={pattern:RegExp(/(<__[^>]*>)(?:))*\]\]>|(?!)/.source.replace(/__/g,function(){return e}),"i"),lookbehind:!0,greedy:!0,inside:n},i.languages.insertBefore("markup","cdata",t)}}),i.languages.html=i.languages.markup,i.languages.mathml=i.languages.markup,i.languages.svg=i.languages.markup,i.languages.xml=i.languages.extend("markup",{}),i.languages.ssml=i.languages.xml,i.languages.atom=i.languages.xml,i.languages.rss=i.languages.xml,function(e){var t=/("|')(?:\\(?:\r\n|[\s\S])|(?!\1)[^\\\r\n])*\1/;e.languages.css={comment:/\/\*[\s\S]*?\*\//,atrule:{pattern:/@[\w-](?:[^;{\s]|\s+(?![\s{]))*(?:;|(?=\s*\{))/,inside:{rule:/^@[\w-]+/,"selector-function-argument":{pattern:/(\bselector\s*\(\s*(?![\s)]))(?:[^()\s]|\s+(?![\s)])|\((?:[^()]|\([^()]*\))*\))+(?=\s*\))/,lookbehind:!0,alias:"selector"},keyword:{pattern:/(^|[^\w-])(?:and|not|only|or)(?![\w-])/,lookbehind:!0}}},url:{pattern:RegExp("\\burl\\((?:"+t.source+"|"+/(?:[^\\\r\n()"']|\\[\s\S])*/.source+")\\)","i"),greedy:!0,inside:{function:/^url/i,punctuation:/^\(|\)$/,string:{pattern:RegExp("^"+t.source+"$"),alias:"url"}}},selector:RegExp("[^{}\\s](?:[^{};\"'\\s]|\\s+(?![\\s{])|"+t.source+")*(?=\\s*\\{)"),string:{pattern:t,greedy:!0},property:/(?!\s)[-_a-z\xA0-\uFFFF](?:(?!\s)[-\w\xA0-\uFFFF])*(?=\s*:)/i,important:/!important\b/i,function:/[-a-z0-9]+(?=\()/i,punctuation:/[(){};:,]/},e.languages.css.atrule.inside.rest=e.languages.css;t=e.languages.markup;t&&(t.tag.addInlined("style","css"),e.languages.insertBefore("inside","attr-value",{"style-attr":{pattern:/(^|["'\s])style\s*=\s*(?:"[^"]*"|'[^']*')/i,lookbehind:!0,inside:{"attr-value":{pattern:/=\s*(?:"[^"]*"|'[^']*'|[^\s'">=]+)/,inside:{style:{pattern:/(["'])[\s\S]+(?=["']$)/,lookbehind:!0,alias:"language-css",inside:e.languages.css},punctuation:[{pattern:/^=/,alias:"attr-equals"},/"|'/]}},"attr-name":/^style/i}}},t.tag))}(i),i.languages.clike={comment:[{pattern:/(^|[^\\])\/\*[\s\S]*?(?:\*\/|$)/,lookbehind:!0,greedy:!0},{pattern:/(^|[^\\:])\/\/.*/,lookbehind:!0,greedy:!0}],string:{pattern:/(["'])(?:\\(?:\r\n|[\s\S])|(?!\1)[^\\\r\n])*\1/,greedy:!0},"class-name":{pattern:/(\b(?:class|interface|extends|implements|trait|instanceof|new)\s+|\bcatch\s+\()[\w.\\]+/i,lookbehind:!0,inside:{punctuation:/[.\\]/}},keyword:/\b(?:if|else|while|do|for|return|in|instanceof|function|new|try|throw|catch|finally|null|break|continue)\b/,boolean:/\b(?:true|false)\b/,function:/\w+(?=\()/,number:/\b0x[\da-f]+\b|(?:\b\d+(?:\.\d*)?|\B\.\d+)(?:e[+-]?\d+)?/i,operator:/[<>]=?|[!=]=?=?|--?|\+\+?|&&?|\|\|?|[?*/~^%]/,punctuation:/[{}[\];(),.:]/},i.languages.javascript=i.languages.extend("clike",{"class-name":[i.languages.clike["class-name"],{pattern:/(^|[^$\w\xA0-\uFFFF])(?!\s)[_$A-Z\xA0-\uFFFF](?:(?!\s)[$\w\xA0-\uFFFF])*(?=\.(?:prototype|constructor))/,lookbehind:!0}],keyword:[{pattern:/((?:^|})\s*)(?:catch|finally)\b/,lookbehind:!0},{pattern:/(^|[^.]|\.\.\.\s*)\b(?:as|async(?=\s*(?:function\b|\(|[$\w\xA0-\uFFFF]|$))|await|break|case|class|const|continue|debugger|default|delete|do|else|enum|export|extends|for|from|function|(?:get|set)(?=\s*[\[$\w\xA0-\uFFFF])|if|implements|import|in|instanceof|interface|let|new|null|of|package|private|protected|public|return|static|super|switch|this|throw|try|typeof|undefined|var|void|while|with|yield)\b/,lookbehind:!0}],function:/#?(?!\s)[_$a-zA-Z\xA0-\uFFFF](?:(?!\s)[$\w\xA0-\uFFFF])*(?=\s*(?:\.\s*(?:apply|bind|call)\s*)?\()/,number:/\b(?:(?:0[xX](?:[\dA-Fa-f](?:_[\dA-Fa-f])?)+|0[bB](?:[01](?:_[01])?)+|0[oO](?:[0-7](?:_[0-7])?)+)n?|(?:\d(?:_\d)?)+n|NaN|Infinity)\b|(?:\b(?:\d(?:_\d)?)+\.?(?:\d(?:_\d)?)*|\B\.(?:\d(?:_\d)?)+)(?:[Ee][+-]?(?:\d(?:_\d)?)+)?/,operator:/--|\+\+|\*\*=?|=>|&&=?|\|\|=?|[!=]==|<<=?|>>>?=?|[-+*/%&|^!=<>]=?|\.{3}|\?\?=?|\?\.?|[~:]/}),i.languages.javascript["class-name"][0].pattern=/(\b(?:class|interface|extends|implements|instanceof|new)\s+)[\w.\\]+/,i.languages.insertBefore("javascript","keyword",{regex:{pattern:/((?:^|[^$\w\xA0-\uFFFF."'\])\s]|\b(?:return|yield))\s*)\/(?:\[(?:[^\]\\\r\n]|\\.)*]|\\.|[^/\\\[\r\n])+\/[gimyus]{0,6}(?=(?:\s|\/\*(?:[^*]|\*(?!\/))*\*\/)*(?:$|[\r\n,.;:})\]]|\/\/))/,lookbehind:!0,greedy:!0,inside:{"regex-source":{pattern:/^(\/)[\s\S]+(?=\/[a-z]*$)/,lookbehind:!0,alias:"language-regex",inside:i.languages.regex},"regex-flags":/[a-z]+$/,"regex-delimiter":/^\/|\/$/}},"function-variable":{pattern:/#?(?!\s)[_$a-zA-Z\xA0-\uFFFF](?:(?!\s)[$\w\xA0-\uFFFF])*(?=\s*[=:]\s*(?:async\s*)?(?:\bfunction\b|(?:\((?:[^()]|\([^()]*\))*\)|(?!\s)[_$a-zA-Z\xA0-\uFFFF](?:(?!\s)[$\w\xA0-\uFFFF])*)\s*=>))/,alias:"function"},parameter:[{pattern:/(function(?:\s+(?!\s)[_$a-zA-Z\xA0-\uFFFF](?:(?!\s)[$\w\xA0-\uFFFF])*)?\s*\(\s*)(?!\s)(?:[^()\s]|\s+(?![\s)])|\([^()]*\))+(?=\s*\))/,lookbehind:!0,inside:i.languages.javascript},{pattern:/(?!\s)[_$a-zA-Z\xA0-\uFFFF](?:(?!\s)[$\w\xA0-\uFFFF])*(?=\s*=>)/i,inside:i.languages.javascript},{pattern:/(\(\s*)(?!\s)(?:[^()\s]|\s+(?![\s)])|\([^()]*\))+(?=\s*\)\s*=>)/,lookbehind:!0,inside:i.languages.javascript},{pattern:/((?:\b|\s|^)(?!(?:as|async|await|break|case|catch|class|const|continue|debugger|default|delete|do|else|enum|export|extends|finally|for|from|function|get|if|implements|import|in|instanceof|interface|let|new|null|of|package|private|protected|public|return|set|static|super|switch|this|throw|try|typeof|undefined|var|void|while|with|yield)(?![$\w\xA0-\uFFFF]))(?:(?!\s)[_$a-zA-Z\xA0-\uFFFF](?:(?!\s)[$\w\xA0-\uFFFF])*\s*)\(\s*|\]\s*\(\s*)(?!\s)(?:[^()\s]|\s+(?![\s)])|\([^()]*\))+(?=\s*\)\s*\{)/,lookbehind:!0,inside:i.languages.javascript}],constant:/\b[A-Z](?:[A-Z_]|\dx?)*\b/}),i.languages.insertBefore("javascript","string",{"template-string":{pattern:/`(?:\\[\s\S]|\${(?:[^{}]|{(?:[^{}]|{[^}]*})*})+}|(?!\${)[^\\`])*`/,greedy:!0,inside:{"template-punctuation":{pattern:/^`|`$/,alias:"string"},interpolation:{pattern:/((?:^|[^\\])(?:\\{2})*)\${(?:[^{}]|{(?:[^{}]|{[^}]*})*})+}/,lookbehind:!0,inside:{"interpolation-punctuation":{pattern:/^\${|}$/,alias:"punctuation"},rest:i.languages.javascript}},string:/[\s\S]+/}}}),i.languages.markup&&i.languages.markup.tag.addInlined("script","javascript"),i.languages.js=i.languages.javascript,"undefined"!=typeof self&&self.Prism&&self.document&&(Element.prototype.matches||(Element.prototype.matches=Element.prototype.msMatchesSelector||Element.prototype.webkitMatchesSelector),a=window.Prism,s={js:"javascript",py:"python",rb:"ruby",ps1:"powershell",psm1:"powershell",sh:"bash",bat:"batch",h:"c",tex:"latex"},u="pre[data-src]:not(["+(l="data-src-status")+'="loaded"]):not(['+l+'="'+(c="loading")+'"])',r=/\blang(?:uage)?-([\w-]+)\b/i,a.hooks.add("before-highlightall",function(e){e.selector+=", "+u}),a.hooks.add("before-sanity-check",function(e){var t,n,r,i,o=e.element;o.matches(u)&&(e.code="",o.setAttribute(l,c),(t=o.appendChild(document.createElement("CODE"))).textContent="Loading…",n=o.getAttribute("data-src"),"none"===(e=e.language)&&(r=(/\.(\w+)$/.exec(n)||[,"none"])[1],e=s[r]||r),p(t,e),p(o,e),(r=a.plugins.autoloader)&&r.loadLanguages(e),(i=new XMLHttpRequest).open("GET",n,!0),i.onreadystatechange=function(){4==i.readyState&&(i.status<400&&i.responseText?(o.setAttribute(l,"loaded"),t.textContent=i.responseText,a.highlightElement(t)):(o.setAttribute(l,"failed"),400<=i.status?t.textContent="✖ Error "+i.status+" while fetching file: "+i.statusText:t.textContent="✖ Error: File does not exist or is empty"))},i.send(null))}),t=!(a.plugins.fileHighlight={highlight:function(e){for(var t,n=(e||document).querySelectorAll(u),r=0;t=n[r++];)a.highlightElement(t)}}),a.fileHighlight=function(){t||(console.warn("Prism.fileHighlight is deprecated. Use `Prism.plugins.fileHighlight.highlight` instead."),t=!0),a.plugins.fileHighlight.highlight.apply(this,arguments)})});function Rn(e,t){return"___"+e.toUpperCase()+t+"___"}Tn=Prism,Object.defineProperties(Tn.languages["markup-templating"]={},{buildPlaceholders:{value:function(r,i,e,o){var a;r.language===i&&(a=r.tokenStack=[],r.code=r.code.replace(e,function(e){if("function"==typeof o&&!o(e))return e;for(var t,n=a.length;-1!==r.code.indexOf(t=Rn(i,n));)++n;return a[n]=e,t}),r.grammar=Tn.languages.markup)}},tokenizePlaceholders:{value:function(c,u){var p,h;c.language===u&&c.tokenStack&&(c.grammar=Tn.languages[u],p=0,h=Object.keys(c.tokenStack),function e(t){for(var n=0;n=h.length);n++){var r,i,o,a,s,l=t[n];"string"==typeof l||l.content&&"string"==typeof l.content?(i=h[p],o=c.tokenStack[i],r="string"==typeof l?l:l.content,s=Rn(u,i),-1<(a=r.indexOf(s))&&(++p,i=r.substring(0,a),o=new Tn.Token(u,Tn.tokenize(o,c.grammar),"language-"+u,o),a=r.substring(a+s.length),s=[],i&&s.push.apply(s,e([i])),s.push(o),a&&s.push.apply(s,e([a])),"string"==typeof l?t.splice.apply(t,[n,1].concat(s)):l.content=s)):l.content&&e(l.content)}return t}(c.tokens))}}});function On(i,e){var o=this;this.config=i,this.router=e,this.cacheTree={},this.toc=[],this.cacheTOC={},this.linkTarget=i.externalLinkTarget||"_blank",this.linkRel="_blank"===this.linkTarget?i.externalLinkRel||"noopener":"",this.contentBase=e.getBasePath();var t=this._initRenderer();this.heading=t.heading;var a=r(e=i.markdown||{})?e(gn,t):(gn.setOptions(y(e,{renderer:y(t,e.renderer)})),gn);this._marked=a,this.compile=function(n){var r=!0,e=s(function(e){r=!1;var t="";return n?(t=c(n)?a(n):a.parser(n),t=i.noEmoji?t:t.replace(/:\+1:/g,":thumbsup:").replace(/:-1:/g,":thumbsdown:").replace(/<(pre|template|code)[^>]*?>[\s\S]+?<\/(pre|template|code)>/g,function(e){return e.replace(/:/g,"__colon__")}).replace(/:(\w+?):/gi,window.emojify||_n).replace(/__colon__/g,":"),xn.clear(),t):n})(n),t=o.router.parse().file;return r?o.toc=o.cacheTOC[t]:o.cacheTOC[t]=[].concat(o.toc),e}}var $n={},Fn={markdown:function(e){return{url:e}},mermaid:function(e){return{url:e}},iframe:function(e,t){return{html:'"}},video:function(e,t){return{html:'"}},audio:function(e,t){return{html:'"}},code:function(e,t){var n=e.match(/\.(\w+)$/);return"md"===(n=t||n&&n[1])&&(n="markdown"),{url:e,lang:n}}};On.prototype.compileEmbed=function(e,t){var n,r,i=Sn(t),o=i.str,i=i.config;if(t=o,i.include)return O(e)||(e=N(this.contentBase,F(this.router.getCurrentPath()),e)),i.type&&(r=Fn[i.type])?(n=r.call(this,e,t)).type=i.type:(r="code",/\.(md|markdown)/.test(e)?r="markdown":/\.mmd/.test(e)?r="mermaid":/\.html?/.test(e)?r="iframe":/\.(mp4|ogg)/.test(e)?r="video":/\.mp3/.test(e)&&(r="audio"),(n=Fn[r].call(this,e,t)).type=r),n.fragment=i.fragment,n},On.prototype._matchNotCompileLink=function(e){for(var t=this.config.noCompileLinks||[],n=0;n/g.test(r)&&(r=r.replace("\x3c!-- {docsify-ignore} --\x3e",""),e.title=An(r),e.ignoreSubHeading=!0),/{docsify-ignore}/g.test(r)&&(r=r.replace("{docsify-ignore}",""),e.title=An(r),e.ignoreSubHeading=!0),//g.test(r)&&(r=r.replace("\x3c!-- {docsify-ignore-all} --\x3e",""),e.title=An(r),e.ignoreAllSubs=!0),/{docsify-ignore-all}/g.test(r)&&(r=r.replace("{docsify-ignore-all}",""),e.title=An(r),e.ignoreAllSubs=!0);n=xn(i.id||r),i=o.toURL(o.getCurrentPath(),{id:n});return e.slug=i,h.toc.push(e),"'+r+""},i.code={renderer:e}.renderer.code=function(e,t){void 0===t&&(t="markup");var n=En.languages[t]||En.languages.markup;return'
    '+En.highlight(e.replace(/@DOCSIFY_QM@/g,"`"),n,t)+"
    "},i.link=(n=(t={renderer:e,router:o,linkTarget:t,linkRel:n,compilerClass:h}).renderer,a=t.router,s=t.linkTarget,l=t.linkRel,c=t.compilerClass,n.link=function(e,t,n){void 0===t&&(t="");var r=[],i=Sn(t),o=i.str,i=i.config;return s=i.target||s,l="_blank"===s?c.config.externalLinkRel||"noopener":"",t=o,O(e)||c._matchNotCompileLink(e)||i.ignore?(O(e)||"./"!==e.slice(0,2)||(e=document.URL.replace(/\/(?!.*\/).*/,"/").replace("#/./","")+e),r.push(0===e.indexOf("mailto:")?"":'target="'+s+'"'),r.push(0!==e.indexOf("mailto:")&&""!==l?' rel="'+l+'"':"")):(e===c.config.homepage&&(e="README"),e=a.toURL(e,null,a.getCurrentPath())),i.crossorgin&&"_self"===s&&"history"===c.config.routerMode&&-1===c.config.crossOriginLinks.indexOf(e)&&c.config.crossOriginLinks.push(e),i.disabled&&(r.push("disabled"),e="javascript:void(0)"),i.class&&r.push('class="'+i.class+'"'),i.id&&r.push('id="'+i.id+'"'),t&&r.push('title="'+t+'"'),'"+n+""}),i.paragraph={renderer:e}.renderer.paragraph=function(e){e=/^!>/.test(e)?vn("tip",e):/^\?>/.test(e)?vn("warn",e):"

    "+e+"

    ";return e},i.image=(r=(n={renderer:e,contentBase:r,router:o}).renderer,u=n.contentBase,p=n.router,r.image=function(e,t,n){var r=e,i=[],o=Sn(t),a=o.str,o=o.config;return t=a,o["no-zoom"]&&i.push("data-no-zoom"),t&&i.push('title="'+t+'"'),o.size&&(t=(a=o.size.split("x"))[0],(a=a[1])?i.push('width="'+t+'" height="'+a+'"'):i.push('width="'+t+'"')),o.class&&i.push('class="'+o.class+'"'),o.id&&i.push('id="'+o.id+'"'),O(e)||(r=N(u,F(p.getCurrentPath()),e)),0":''+n+'"}),i.list={renderer:e}.renderer.list=function(e,t,n){t=t?"ol":"ul";return"<"+t+" "+[/
  • /.test(e.split('class="task-list"')[0])?'class="task-list"':"",n&&1"+e+""},i.listitem={renderer:e}.renderer.listitem=function(e){return/^(]*>)/.test(e)?'
  • ":"
  • "+e+"
  • "},e.origin=i,e},On.prototype.sidebar=function(e,t){var n=this.toc,r=this.router.getCurrentPath(),i="";if(e)i=this.compile(e);else{for(var o=0;o{inner}");this.cacheTree[r]=t}return i},On.prototype.subSidebar=function(e){if(e){var t=this.router.getCurrentPath(),n=this.cacheTree,r=this.toc;r[0]&&r[0].ignoreAllSubs&&r.splice(0),r[0]&&1===r[0].level&&r.shift();for(var i=0;i\n'+e+"\n
    "}]).links={}:(t=[{type:"html",text:e}]).links={}),o({token:i,embedToken:t}),++l>=s&&o({})}}(t);t.embed.url?ce(t.embed.url).then(r):r(t.embed.html)}}({compile:n,embedTokens:s,fetch:t},function(e){var t,n=e.embedToken,e=e.token;e?(t=e.index,u.forEach(function(e){t>e.start&&(t+=e.length)}),y(c,n.links),a=a.slice(0,t).concat(n,a.slice(t+1)),u.push({start:t,length:n.length-1})):(zn[i]=a.concat(),a.links=zn[i].links=c,r(a))})}function Mn(e,t,n){var r,i,o,a;return t="function"==typeof n?n(t):"string"==typeof n?(o=[],a=0,(r=n).replace(B,function(t,e,n){o.push(r.substring(a,n-1)),a=n+=t.length+1,o.push(i&&i[t]||function(e){return("00"+("string"==typeof Z[t]?e[Z[t]]():Z[t](e))).slice(-t.length)})}),a!==r.length&&o.push(r.substring(a)),function(e){for(var t="",n=0,r=e||new Date;n404 - Not found","Vue"in window)for(var o=0,a=k(".markdown-section > *").filter(t);oscript").filter(function(e){return!/template/.test(e.type)})[0])||(e=e.innerText.trim())&&new Function(e)()),"Vue"in window){var l,c,u=[],p=Object.keys(n.vueComponents||{});2===i&&p.length&&p.forEach(function(e){window.Vue.options.components[e]||window.Vue.component(e,n.vueComponents[e])}),!Cn&&n.vueGlobalOptions&&"function"==typeof n.vueGlobalOptions.data&&(Cn=n.vueGlobalOptions.data()),u.push.apply(u,Object.keys(n.vueMounts||{}).map(function(e){return[b(r,e),n.vueMounts[e]]}).filter(function(e){var t=e[0];e[1];return t})),(n.vueGlobalOptions||p.length)&&(l=/{{2}[^{}]*}{2}/,c=/<[^>/]+\s([@:]|v-)[\w-:.[\]]+[=>\s]/,u.push.apply(u,k(".markdown-section > *").filter(function(n){return!u.some(function(e){var t=e[0];e[1];return t===n})}).filter(function(e){return e.tagName.toLowerCase()in(n.vueComponents||{})||e.querySelector(p.join(",")||null)||l.test(e.outerHTML)||c.test(e.outerHTML)}).map(function(e){var t=y({},n.vueGlobalOptions||{});return Cn&&(t.data=function(){return Cn}),[e,t]})));for(var h=0,d=u;h([^<]*?)

    $'))&&("color"===t[2]?r.style.background=t[1]+(t[3]||""):(e=t[1],S(r,"add","has-mask"),O(t[1])||(e=N(this.router.getBasePath(),t[1])),r.style.backgroundImage="url("+e+")",r.style.backgroundSize="cover",r.style.backgroundPosition="center center"),n=n.replace(t[0],"")),this._renderTo(".cover-main",n),he()):S(r,"remove","show")},t.prototype._updateRender=function(){var e,t,n,r;e=this,t=d(".app-name-link"),n=e.config.nameLink,r=e.route.path,t&&(c(e.config.nameLink)?t.setAttribute("href",n):"object"==typeof n&&(e=Object.keys(n).filter(function(e){return-1'):"")),e.coverpage&&(c+=(r=", 100%, 85%",'
    \x3c!--cover--\x3e
    ')),e.logo&&(r=/^data:image/.test(e.logo),t=/(?:http[s]?:)?\/\//.test(e.logo),n=/^\./.test(e.logo),r||t||n||(e.logo=N(this.router.getBasePath(),e.logo))),c+=(n=(t=e).name?t.name:"","
    "+('')+'
    \x3c!--main--\x3e
    '),this._renderTo(l,c,!0)):this.rendered=!0,e.mergeNavbar&&h?u=b(".sidebar"):(s.classList.add("app-nav"),e.repo||s.classList.add("no-badge")),e.loadNavbar&&w(u,s),e.themeColor&&(f.head.appendChild(v("div","").firstElementChild),o=e.themeColor,window.CSS&&window.CSS.supports&&window.CSS.supports("(--v:red)")||(e=k("style:not(.inserted),link"),[].forEach.call(e,function(e){if("STYLE"===e.nodeName)ue(e,o);else if("LINK"===e.nodeName){e=e.getAttribute("href");if(!/\.css$/.test(e))return;ce(e).then(function(e){e=v("style",e);m.appendChild(e),ue(e,o)})}}))),this._updateRender(),S(g,"ready")},t}(function(n){function e(){for(var e=[],t=arguments.length;t--;)e[t]=arguments[t];n.apply(this,e),this.route={}}return n&&(e.__proto__=n),((e.prototype=Object.create(n&&n.prototype)).constructor=e).prototype.updateRender=function(){this.router.normalize(),this.route=this.router.parse(),g.setAttribute("data-page",this.route.file)},e.prototype.initRouter=function(){var t=this,e=this.config,e=new("history"===(e.routerMode||"hash")&&i?q:H)(e);this.router=e,this.updateRender(),U=this.route,e.onchange(function(e){t.updateRender(),t._updateRender(),U.path!==t.route.path?(t.$fetch(u,t.$resetEvents.bind(t,e.source)),U=t.route):t.$resetEvents(e.source)})},e}(function(e){function t(){e.apply(this,arguments)}return e&&(t.__proto__=e),((t.prototype=Object.create(e&&e.prototype)).constructor=t).prototype.initLifecycle=function(){var n=this;this._hooks={},this._lifecycle={},["init","mounted","beforeEach","afterEach","doneEach","ready"].forEach(function(e){var t=n._hooks[e]=[];n._lifecycle[e]=function(e){return t.push(e)}})},t.prototype.callHook=function(e,n,r){void 0===r&&(r=u);var i=this._hooks[e],o=function(t){var e=i[t];t>=i.length?r(n):"function"==typeof e?2===e.length?e(n,function(e){n=e,o(t+1)}):(e=e(n),n=void 0===e?n:e,o(t+1)):o(t+1)};o(0)},t}(Hn)))))));function Un(e,t,n){return jn&&jn.abort&&jn.abort(),jn=ce(e,!0,n)}window.Docsify={util:In,dom:t,get:ce,slugify:xn,version:"4.12.2"},window.DocsifyCompiler=On,window.marked=gn,window.Prism=En,e(function(e){return new qn})}(); diff --git a/docs/index.html b/index.html similarity index 68% rename from docs/index.html rename to index.html index 1f2bd52db..671f56187 100644 --- a/docs/index.html +++ b/index.html @@ -13,6 +13,22 @@ rel="stylesheet" href="//cdn.jsdelivr.net/npm/docsify/lib/themes/vue.css" /> + @@ -28,8 +44,9 @@ diff --git a/prism.js b/prism.js new file mode 100644 index 000000000..23d6d5e8b --- /dev/null +++ b/prism.js @@ -0,0 +1,31 @@ +!(function (e) { + (e.languages.typescript = e.languages.extend("javascript", { + "class-name": { + pattern: + /(\b(?:class|extends|implements|instanceof|interface|new|type)\s+)(?!keyof\b)[_$a-zA-Z\xA0-\uFFFF][$\w\xA0-\uFFFF]*(?:\s*<(?:[^<>]|<(?:[^<>]|<[^<>]*>)*>)*>)?/, + lookbehind: !0, + greedy: !0, + inside: null, + }, + keyword: + /\b(?:abstract|as|asserts|async|await|break|case|catch|class|const|constructor|continue|debugger|declare|default|delete|do|else|enum|export|extends|finally|for|from|function|get|if|implements|import|in|instanceof|interface|is|keyof|let|module|namespace|new|null|of|package|private|protected|public|readonly|return|require|set|static|super|switch|this|throw|try|type|typeof|undefined|var|void|while|with|yield)\b/, + builtin: + /\b(?:string|Function|any|number|boolean|Array|symbol|console|Promise|unknown|never)\b/, + })), + delete e.languages.typescript.parameter; + var n = e.languages.extend("typescript", {}); + delete n["class-name"], + (e.languages.typescript["class-name"].inside = n), + e.languages.insertBefore("typescript", "function", { + "generic-function": { + pattern: + /#?[_$a-zA-Z\xA0-\uFFFF][$\w\xA0-\uFFFF]*\s*<(?:[^<>]|<(?:[^<>]|<[^<>]*>)*>)*>(?=\s*\()/, + greedy: !0, + inside: { + function: /^#?[_$a-zA-Z\xA0-\uFFFF][$\w\xA0-\uFFFF]*/, + generic: { pattern: /<[\s\S]+/, alias: "class-name", inside: n }, + }, + }, + }), + (e.languages.ts = e.languages.typescript); +})(Prism);