Update dependency arktype to v2.1.28
This MR contains the following updates:
| Package | Change | Age | Confidence |
|---|---|---|---|
| arktype (source) | ^2.1.0 -> ^2.1.28 |
||
| arktype (source) | 2.1.22 -> 2.1.28 |
Release Notes
arktypeio/arktype (arktype)
v2.1.28
JSON Schema improvements
- Adds support for the new Standard JSON Schema interface (see standardschema.dev)
- Now accepts a
targetoption and can generate draft-07 in addition to draft-2020-12
Standard Schema is now a valid definition
Any Standard Schema compliant validator can now be passed directly to type, either directly or nested in a structural ArkType definition, and will be fully inferred and validated.
import { type } from "arktype"
import * as v from "valibot"
import z from "zod"
const ZodAddress = z.object({
street: z.string(),
city: z.string()
})
const User = type({
name: "string",
age: v.number(),
address: ZodAddress
})
e(x)ec mode for regex types
const User = type({
// x-prefix a regex literal to parse its type-safe capture groups
birthday: "x/^(?<month>\\d{2})-(?<day>\\d{2})-(?<year>\\d{4})$/"
})
const data = User.assert({ birthday: "05-21-1993" })
// fully type-safe via arkregex
console.log(data.birthday.groups) // { month: "05", day: "21", year: "1993" }
more flexible type.declare
Optionality can now be expressed via a property value in addition to its key:
type Expected = { f?: string }
const T = type.declare<Expected>().type({
// previously failed with `"f?" is missing`
f: "string?"
})
fixed a bug causing predicate errors after the first to not be reported
import { type } from "arktype"
const Dates = type({
date1: "string.date",
date2: "string.date",
date3: "string.date"
})
// now correctly reports the errors on `date2` and `date3` in addition to `date1`
Dates.assert({
date1: "",
date2: "",
date3: ""
})
See #1557
v2.1.27
fix assignability for certain objects like Module
The following assignment will now correctly fail (thanks @LukeAbby)
import { type } from "arktype"
const types: Module<{ foo: string }> = type.module({ foo: "unknown" })
bump regex inference to arkregex 0.0.3
v2.1.26
es2020 compatibility
Remove usages of newer prototypes methods like .at() to better support legacy browsers
improve external generic inference
Some inference scenarios like the following involving default values are now more cooperative (thanks @Andarist)
function someFunction<TSchema extends Record<string, any>>(
schema: Type<TSchema, {}>
): (typeof schema)["infer"] {
const someData = { hello: "world" }
return schema.assert(someData)
}
const schema = type({
hello: type("string").pipe(s => s === "world"),
goodbye: "string='blah'"
})
someFunction(schema)
v2.1.25
bump regex inference to arkregex 0.0.2
v2.1.24
bump regex inference to arkregex 0.0.1
duplicate key errors
Definitions like the following now throw a descriptive error:
const T = type({
foo: "string",
foo?: "string"
})
v2.1.23
regex literals are now inferred (will be announced and documented as part of 2.2)
fix an issue with some discriminated morphs (thanks @JeremyMoeglich)
See #1464
v2.1.22
fix an issue with some recursive transforms
See #1496
v2.1.21
~standard toJSONSchema support
Adds support for the upcoming StandardJSONSchemaSourceV1 spec (standardschema.dev)
v2.1.20
toJsonSchema config
Some ArkType features don't have JSON Schema equivalents. By default, toJsonSchema() will throw in these cases.
This behavior can be configured granularly to match your needs.
const T = type({
"[symbol]": "string",
birthday: "Date"
})
const schema = T.toJsonSchema({
fallback: {
// ✅ the "default" key is a fallback for any non-explicitly handled code
// ✅ ctx includes "base" (represents the schema being generated) and other code-specific props
// ✅ returning `ctx.base` will effectively ignore the incompatible constraint
default: ctx => ctx.base,
// handle specific incompatibilities granularly
date: ctx => ({
...ctx.base,
type: "string",
format: "date-time",
description: ctx.after ? `after ${ctx.after}` : "anytime"
})
}
})
const result = {
$schema: "https://json-schema.org/draft/2020-12/schema",
type: "object",
properties: {
// Date instance is now a date-time string as specified by the `date` handler
birthday: { type: "string", format: "date-time", description: "anytime" }
},
required: ["birthday"]
// symbolic index signature ignored as specified by the `default` handler
}
a default handler can also be specified at the root of a fallback config:
const T = type({
"[symbol]": "string",
birthday: "Date"
})
//--- cut ---
const schema = T.toJsonSchema({
// "just make it work"
fallback: ctx => ctx.base
})
These options can also be set at a global or scope-level.
Fallback Codes
This is the full list of configurable reasons toJsonSchema() can fail.
| Code | Description |
|---|---|
arrayObject |
arrays with object properties |
arrayPostfix |
arrays with postfix elements |
defaultValue |
non-serializable default value |
domain |
non-serializable type keyword (always bigint or symbol) |
morph |
transformation |
patternIntersection |
multiple regex constraints |
predicate |
custom narrow function |
proto |
non-serializable instanceof
|
symbolKey |
symbolic key on an object |
unit |
non-serializable === reference (e.g. undefined) |
date |
a Date instance (supercedes proto for Dates ) |
cyclic types can now be converted to JSON Schema
// previously this threw
const schema = type("object.json").toJsonSchema()
// now generates the following schema
const result = {
$ref: "#/$defs/intersection11",
$defs: {
intersection11: {
type: "object",
additionalProperties: { $ref: "#/$defs/jsonData1" }
},
jsonData1: {
anyOf: [
{ $ref: "#/$defs/intersection11" },
{ type: "number" },
{ type: "string" },
{ type: "boolean" },
{ type: "null" }
]
}
}
}
temporarily disable discrimination for cyclic unions
This addresses multiple issues while we work on a permanent solution for accurately discriminating cyclic unions, tracked here.
addresses inference issues on some n-ary APIs like type.or outside the default scope (see the MR- thanks @simonwkla) 🎊
v2.1.19
Multiple improvements to toJsonSchema() output, aligning it more closely with Open API standards.
Faster completion triggers for shallow string definitions
// old: ~1s delay after typing this before completions
// new: completions are almost instant
type("")
This isn't actually an overall perf improvement, but just a language server optimization to trigger autocomplete sooner.
Counterintuitively, in previous 2.x versions, strings that are part of an object definition trigger completions much faster than shallow strings.
v2.1.18
Fix an issue causing metatypes like Default and Out to not be extracted from some recursive definitions:
const T = type({
defaulted: "number = 0",
"nested?": "this"
})
const t = T.assert({})
// old: Default<number, 0> | undefined
// new: number | undefined
t.nested?.defaulted
v2.1.17
Unsatisfiable types for index signature intersections will now result in a ParseError thanks to the work of @TizzySaurus on the upcoming @ark/json-schema package
v2.1.16
Fix an issue causing non-serializable error config to lead to incorrect error messages in some JIT-mode cases:
const MyUnion = type('"abc" | "cde"').configure({
message: () => "fail"
})
// old: "$ark.message"
// new: "fail"
MyUnion.assert("efg")
Added a workaround for environments where global prototypes like FormData have degenerate resolutions like {} (currently the case in @types/bun, see oven-sh/bun#18689)
const T = type("string.numeric.parse")
// previously, if a global prototype like FormData resolved to {}, it prevented
// ArkType from extracting the input/output of morphs, leading to inference like the following:
// old (with @​bun/types): (In: string) => To<number>
// new (with @​bun/types): number
type Parsed = typeof T.inferOut
v2.1.15
.configure({}, selector) fixes
const User = type({
name: "string",
platform: "'android' | 'ios'",
"version?": "number | string"
})
// prior to 2.1.15, the selector was not applied
// when configuring references
const ConfiguredUser = User.configure(
{ description: "A STRING" },
{
kind: "domain",
where: d => d.domain === "string"
}
)
// old: A STRING
// new: A STRING
ConfiguredUser.get("name").description
// old: A STRING
// new: "android" | "ios"
ConfiguredUser.get("platform").description
// old: A STRING or undefined
// new: a number, A STRING or undefined
ConfiguredUser.get("version").description
With the much more powerful .configure + selector API now available, the internal .withMeta method was removed as it can be trivially achieved via a self-selector:
// < 2.1.15
myType.withMeta("some shallow description")
// >= 2.1.15
myType.configure("some shallow description", "self")
v2.1.14
improve .expression for regex constraints
const T = type(/^a.*z$/)
// old: string /^a.*z$/
// new: /^a.*z$/
console.log(T.expression)
v2.1.13
Add standalone functions for n-ary operators
// accept ...definitions
const union = type.or(type.string, "number", { key: "unknown" })
const Base = type({
foo: "string"
})
// accepts ...definitions
const intersection = type.and(
Base,
{
bar: "number"
},
{
baz: "string"
}
)
const zildjian = Symbol()
const Base = type({
"[string]": "number",
foo: "0",
[zildjian]: "true"
})
// accepts ...objectDefinitions
const merged = type.merge(
Base,
{
"[string]": "bigint",
"foo?": "1n"
},
{
includeThisPropAlso: "true"
}
)
// accepts ...morphsOrTypes
const trimStartToNonEmpty = type.pipe(
type.string,
s => s.trimStart(),
type.string.atLeastLength(1)
)
v2.1.12
exactOptionalPropertyTypes
By default, ArkType validates optional keys as if TypeScript's exactOptionalPropertyTypes is set to true.
const MyObj = type({
"key?": "number"
})
// valid data
const validResult = myObj({})
// Error: key must be a number (was undefined)
const errorResult = myObj({ key: undefined })
This approach allows the most granular control over optionality, as | undefined can be added to properties that should accept it.
However, if you have not enabled TypeScript's exactOptionalPropertyTypes setting, you may globally configure ArkType's exactOptionalPropertyTypes to false to match TypeScript's behavior. If you do this, we'd recommend making a plan to enable exactOptionalPropertyTypes in the future.
import { configure } from "arktype/config"
// since the default in ArkType is `true`, this will only have an effect if set to `false`
configure({ exactOptionalPropertyTypes: false })
import "./config.ts"
// import your config file before arktype
import { type } from "arktype"
const MyObj = type({
"key?": "number"
})
// valid data
const validResult = myObj({})
// now also valid data (would be an error by default)
const secondResult = myObj({ key: undefined })
WARNING: exactOptionalPropertyTypes does not yet affect default values!
const MyObj = type({
key: "number = 5"
})
// { key: 5 }
const omittedResult = myObj({})
// { key: undefined }
const undefinedResult = myObj({ key: undefined })
Support for this is tracked as part of this broader configurable defaultability issue.
v2.1.11
- Expose
selectmethod directly onType(previously was only available on.internal) - Improve missing property error messages
v2.1.10
Added a new select method for introspecting references of a node:
NOTE: @ark/schema's API is not semver stable, so this API may change slightly over time (though we will try to ensure it doesn't).
// extract deep references to exclusive `min` nodes
const result = myType.select({
kind: "min",
where: node => node.exclusive
})
These selectors can also be used to select references for configuration:
// configure string node references
const result = myType.configure(
{ description: "a referenced string" },
{
kind: "domain",
where: node => node.domain === "string"
}
)
ArkErrors are now JSON stringifiable and have two new props: flatByPath and flatProblemsByPath.
const NEvenAtLeast2 = type({
n: "number % 2 > 2"
})
const out = nEvenAtLeast2({ n: 1 })
if (out instanceof type.errors) {
console.log(out.flatByPath)
const output = {
n: [
{
data: 1,
path: ["n"],
code: "divisor",
description: "even",
meta: {},
rule: 2,
expected: "even",
actual: "1",
problem: "must be even (was 1)",
message: "n must be even (was 1)"
},
{
data: 1,
path: ["n"],
code: "min",
description: "at least 2",
meta: {},
rule: 2,
expected: "at least 2",
actual: "1",
problem: "must be at least 2 (was 1)",
message: "n must be at least 2 (was 1)"
}
]
}
console.log(out.flatProblemsByPath)
const output2 = {
n: ["must be even (was 1)", "must be at least 2 (was 1)"]
}
}
v2.1.9
The |> operator pipes output to another Type parsed from a definition.
It is now string-embeddable:
const TrimToNonEmpty = type("string.trim |> string > 0")
const Equivalent = type("string.trim").to("string > 0")
v2.1.8
- improve 3+ arg generic invocations
- add
string.hex(thanks @HoaX7 - #1351) - switch from AggregateError to TraversalError for better crash formatting (thanks @LukeAbby - #1349)
v2.1.7
Address a rare crash on an invalid ctx reference in some jitless cases
Closes #1346
v2.1.6
Improve some type-level parse errors on expressions with invalid finalizers
v2.1.5
Fix JSDoc and go-to definition for unparsed keys
Addresses #1294
const T = type({
/** FOO */
foo: "string",
/** BAR */
bar: "number?"
})
const out = T.assert({ foo: "foo" })
// go-to definition will now navigate to the foo prop from the type call
// hovering foo now displays "FOO"
console.log(out.foo)
// go-to definition will now navigate to the bar prop from the type call
// hovering bar now displays "BAR"
// (the ? must be in the value for this to work)
console.log(out.bar)
v2.1.4
Static hermes compatibility (#1027)
v2.1.3
Fix a jitless-mode bug causing default + onUndeclaredKey transformations to not apply (#1335)
v2.1.2
JSON Schema improvements
- Adds support for the new Standard JSON Schema interface (see standardschema.dev)
- Now accepts a
targetoption and can generate draft-07 in addition to draft-2020-12
Standard Schema is now a valid definition
Any Standard Schema compliant validator can now be passed directly to type, either directly or nested in a structural ArkType definition, and will be fully inferred and validated.
import { type } from "arktype"
import * as v from "valibot"
import z from "zod"
const ZodAddress = z.object({
street: z.string(),
city: z.string()
})
const User = type({
name: "string",
age: v.number(),
address: ZodAddress
})
e(x)ec mode for regex types
const User = type({
// x-prefix a regex literal to parse its type-safe capture groups
birthday: "x/^(?<month>\\d{2})-(?<day>\\d{2})-(?<year>\\d{4})$/"
})
const data = User.assert({ birthday: "05-21-1993" })
// fully type-safe via arkregex
console.log(data.birthday.groups) // { month: "05", day: "21", year: "1993" }
more flexible type.declare
Optionality can now be expressed via a property value in addition to its key:
type Expected = { f?: string }
const T = type.declare<Expected>().type({
// previously failed with `"f?" is missing`
f: "string?"
})
fixed a bug causing predicate errors after the first to not be reported
import { type } from "arktype"
const Dates = type({
date1: "string.date",
date2: "string.date",
date3: "string.date"
})
// now correctly reports the errors on `date2` and `date3` in addition to `date1`
Dates.assert({
date1: "",
date2: "",
date3: ""
})
See #1557
v2.1.1
Multiple improvements to toJsonSchema() output, aligning it more closely with Open API standards.
Faster completion triggers for shallow string definitions
// old: ~1s delay after typing this before completions
// new: completions are almost instant
type("")
This isn't actually an overall perf improvement, but just a language server optimization to trigger autocomplete sooner.
Counterintuitively, in previous 2.x versions, strings that are part of an object definition trigger completions much faster than shallow strings.
Configuration
-
If you want to rebase/retry this MR, check this box
This MR has been generated by Renovate Bot.