New Case Study:See how Anthropic automated 95% of dependency reviews with Socket.Learn More
Socket
Sign inDemoInstall
Socket

arri-validate

Package Overview
Dependencies
Maintainers
1
Versions
117
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

arri-validate - npm Package Compare versions

Comparing version 0.20.0 to 0.21.0

dist/shared/arri-validate.95ccc05f.d.cts

8

dist/index.d.ts

@@ -1,3 +0,3 @@

import { A as ASchemaOptions, a as ASchema, b as AArraySchema, c as AScalarSchema, d as AObjectSchema, e as ADiscriminatorSchema, I as InferType, R as ResolveObject, f as AStringEnumSchema, g as AObjectSchemaOptions, h as InferObjectOutput, V as ValidationData, i as ARecordSchema, S as SafeResult, j as coerce, k as errors, p as parse, s as safeCoerce, l as safeParse, m as serialize, v as validate, n as SchemaValidator, o as SchemaMetadata, q as SCHEMA_METADATA } from './shared/arri-validate.c0cca708.js';
export { G as InferObjectRawType, M as MaybeNullable, z as NumberType, N as NumberTypeValues, P as PartialBy, x as Resolve, t as ValidationError, r as ValueError, B as isAAraySchema, D as isADiscriminatorSchema, F as isAObjectSchema, E as isARecordSchema, y as isAScalarSchema, w as isASchema, C as isAStringEnumSchema, H as isObject, u as isValidationError } from './shared/arri-validate.c0cca708.js';
import { A as ASchemaOptions, a as ASchema, b as AArraySchema, c as AScalarSchema, d as AObjectSchema, e as ADiscriminatorSchema, I as InferType, R as ResolveObject, f as AStringEnumSchema, g as AObjectSchemaOptions, h as InferObjectOutput, V as ValidationData, i as ARecordSchema, S as SafeResult, j as coerce, k as errors, l as InferSubType, p as parse, s as safeCoerce, m as safeParse, n as serialize, v as validate, o as SchemaValidator, q as SchemaMetadata, r as SCHEMA_METADATA } from './shared/arri-validate.95ccc05f.js';
export { H as InferObjectRawType, M as MaybeNullable, B as NumberType, N as NumberTypeValues, P as PartialBy, y as Resolve, u as ValidationError, t as ValueError, C as isAAraySchema, E as isADiscriminatorSchema, G as isAObjectSchema, F as isARecordSchema, z as isAScalarSchema, x as isASchema, D as isAStringEnumSchema, J as isObject, w as isValidationError } from './shared/arri-validate.95ccc05f.js';
import { Schema } from 'jtd-utils';

@@ -278,3 +278,3 @@

declare namespace _namespace {
export { _namespace_any as any, _namespace_array as array, _namespace_boolean as boolean, _namespace_coerce as coerce, _namespace_compile as compile, _namespace_discriminator as discriminator, _namespace_enumerator as enumerator, _namespace_errors as errors, _namespace_extend as extend, _namespace_float32 as float32, _namespace_float64 as float64, InferType as infer, _namespace_int16 as int16, _namespace_int32 as int32, _namespace_int64 as int64, _namespace_int8 as int8, _namespace_nullable as nullable, _namespace_number as number, _namespace_object as object, _namespace_omit as omit, _namespace_optional as optional, _namespace_parse as parse, _namespace_partial as partial, _namespace_pick as pick, _namespace_record as record, _namespace_safeCoerce as safeCoerce, _namespace_safeParse as safeParse, _namespace_serialize as serialize, _namespace_string as string, _namespace_stringEnum as stringEnum, _namespace_timestamp as timestamp, _namespace_uint16 as uint16, _namespace_uint32 as uint32, _namespace_uint64 as uint64, _namespace_uint8 as uint8, _namespace_validate as validate };
export { _namespace_any as any, _namespace_array as array, _namespace_boolean as boolean, _namespace_coerce as coerce, _namespace_compile as compile, _namespace_discriminator as discriminator, _namespace_enumerator as enumerator, _namespace_errors as errors, _namespace_extend as extend, _namespace_float32 as float32, _namespace_float64 as float64, InferType as infer, InferSubType as inferSubType, _namespace_int16 as int16, _namespace_int32 as int32, _namespace_int64 as int64, _namespace_int8 as int8, _namespace_nullable as nullable, _namespace_number as number, _namespace_object as object, _namespace_omit as omit, _namespace_optional as optional, _namespace_parse as parse, _namespace_partial as partial, _namespace_pick as pick, _namespace_record as record, _namespace_safeCoerce as safeCoerce, _namespace_safeParse as safeParse, _namespace_serialize as serialize, _namespace_string as string, _namespace_stringEnum as stringEnum, _namespace_timestamp as timestamp, _namespace_uint16 as uint16, _namespace_uint32 as uint32, _namespace_uint64 as uint64, _namespace_uint8 as uint8, _namespace_validate as validate };
}

@@ -320,2 +320,2 @@

export { type AAdaptedDiscriminatorSchema, type AAdaptedObjectSchema, type AAdaptedRecordSchema, type AAdaptedSchema, type AAdaptedSchemaMetadata, type AAdaptedSchemaValidator, AArraySchema, ADiscriminatorSchema, AObjectSchema, AObjectSchemaOptions, ARecordSchema, AScalarSchema, ASchema, ASchemaOptions, AStringEnumSchema, type CompiledValidator, InferObjectOutput, InferType, ResolveObject, SCHEMA_METADATA, SafeResult, SchemaMetadata, SchemaValidator, type ValidationAdapter, ValidationData, _namespace as a, any, array, boolean, coerce, compile, discriminator, enumerator, errors, extend, float32, float64, getCompiledParser, getCompiledSerializer, createParsingTemplate as getSchemaParsingCode, createSerializationV2Template as getSchemaSerializationCode, createValidationTemplate as getSchemaValidationCode, int16, int16Max, int16Min, int32, int32Max, int32Min, int64, int64Max, int64Min, int8, int8Max, int8Min, isAAdaptedSchema, nullable, number, object, omit, optional, parse, partial, pick, record, safeCoerce, safeParse, serialize, serializeObject, string, stringEnum, timestamp, uint16, uint16Max, uint16Min, uint32, uint32Max, uint32Min, uint64, uint64Max, uint64Min, uint8, uint8Max, uint8Min, validate };
export { type AAdaptedDiscriminatorSchema, type AAdaptedObjectSchema, type AAdaptedRecordSchema, type AAdaptedSchema, type AAdaptedSchemaMetadata, type AAdaptedSchemaValidator, AArraySchema, ADiscriminatorSchema, AObjectSchema, AObjectSchemaOptions, ARecordSchema, AScalarSchema, ASchema, ASchemaOptions, AStringEnumSchema, type CompiledValidator, InferObjectOutput, InferSubType, InferType, ResolveObject, SCHEMA_METADATA, SafeResult, SchemaMetadata, SchemaValidator, type ValidationAdapter, ValidationData, _namespace as a, any, array, boolean, coerce, compile, discriminator, enumerator, errors, extend, float32, float64, getCompiledParser, getCompiledSerializer, createParsingTemplate as getSchemaParsingCode, createSerializationV2Template as getSchemaSerializationCode, createValidationTemplate as getSchemaValidationCode, int16, int16Max, int16Min, int32, int32Max, int32Min, int64, int64Max, int64Min, int8, int8Max, int8Min, isAAdaptedSchema, nullable, number, object, omit, optional, parse, partial, pick, record, safeCoerce, safeParse, serialize, serializeObject, string, stringEnum, timestamp, uint16, uint16Max, uint16Min, uint32, uint32Max, uint32Min, uint64, uint64Max, uint64Min, uint8, uint8Max, uint8Min, validate };

@@ -1,2 +0,2 @@

import { a as ASchema } from './shared/arri-validate.c0cca708.js';
import { a as ASchema } from './shared/arri-validate.95ccc05f.js';
import 'jtd-utils';

@@ -3,0 +3,0 @@

{
"name": "arri-validate",
"version": "0.20.0",
"version": "0.21.0",
"type": "module",

@@ -28,8 +28,8 @@ "license": "MIT",

"uncrypto": "^0.1.3",
"jtd-utils": "0.20.0"
"jtd-utils": "0.21.0"
},
"devDependencies": {
"@faker-js/faker": "^8.3.1",
"@faker-js/faker": "^8.4.0",
"benny": "^3.7.1"
}
}
# Arri Validate
**This is a work in progress. Stuff will break!**
A type builder and validation library built on top of the [Json Type Definition (RFC 8927)](https://jsontypedef.com) This library is pretty similar to [Typebox](https://github.com/sinclairzx81/typebox) except that it creates Json Type Definition (JTD) objects instead of Json Schema objects.

@@ -9,2 +7,30 @@

## Table of Contents
- [Installation](#installation)
- [Basic Example](#basic-example)
- [Supported Types](#supported-types)
- [Primitives](#primitives)
- [Enums](#enums)
- [Arrays / Lists](#arrays--lists)
- [Objects](#objects)
- [Records / Maps](#records--maps)
- [Discriminated Unions](#discriminated-unions)
- [Modifiers](#modifiers)
- [Optional](#optional)
- [Nullable](#nullable)
- [Extend](#extend)
- [Omit](#omit)
- [Pick](#pick)
- [Partial](#partial)
- [Utilities](#helpers)
- [Validate](#validate)
- [Parse](#parse)
- [Safe Parse](#safe-parse)
- [Coerce](#coerce)
- [Safe Coerce](#safe-coerce)
- [Serialize](#serialize)
- [Errors](#errors)
- [Compiled Validators](#compiled-validators)
## Installation

@@ -20,3 +46,3 @@

## Example
## Basic Example

@@ -47,2 +73,509 @@ ```ts

## Project Philosophy
The goals of this project are as follows:
- Portable type definitions
- High performance validation, parsing, and serialization
- Consistent error reporting for parsing and serialization errors
I am not looking to support every feature of Typescript's type system or even every possible representation of JSON. The goal is that the data models defined through this library can be used as a source of truth across multiple programming languages. Both JSON and Typescript have to be limited to accomplish this.
### Adherence to RFC 8927
To represent the data-models in a language agnostic way this library heavily relies on JSON Type Definition (JTD). However, this library does not strictly comply with the JTD specification. The reason for this is because JTD does not support 64-bit integers. I believe sharing large integers across languages is a huge pain point especially when going to and from Javascript. For this reason alone, I have opted to break away from the JTD spec and add support for `int64` and `uint64`. So while I have no intention to break further away from the spec I am open to it if a large enough issue arises (in my view). If you use this library be aware that I'm using a superset of JTD rather than a strict spec compliant implementation.
## Supported Types
### Primitives
| Arri Schema | Typescript | Json Type Definition |
| ------------- | ---------- | --------------------- |
| a.any() | any | {} |
| a.string() | string | { "type": "string" } |
| a.boolean() | boolean | {"type": "boolean"} |
| a.timestamp() | Date | {"type": "timestamp"} |
| a.float32() | number | {"type": "float32"} |
| a.float64() | number | {"type": "float64"} |
| a.int8() | number | {"type": "int8"} |
| a.int16() | number | {"type": "int16"} |
| a.int32() | number | {"type": "int32"} |
| a.int64() | BigInt | {"type": "int64"} |
| a.uint8() | number | {"type": "uint8"} |
| a.uint16() | number | {"type": "uint16"} |
| a.uint32() | number | {"type": "uint32"} |
| a.uint64() | BigInt | {"type": "uint64"} |
### Enums
Enum schemas allow you to specify a predefine list of accepted strings
**Usage**
```ts
const Status = a.enumerator(["ACTIVE", "INACTIVE", "UNKNOWN"]);
type Status = a.infer<typeof Status>; // "ACTIVE" | "INACTIVE" | "UNKNOWN";
a.validate(Status, "BLAH"); // false
a.validate(Status, "ACTIVE"); // true
```
**Outputted JTD**
```json
{
"enum": ["ACTIVE", "INACTIVE", "UNKNOWN"]
}
```
### Arrays / Lists
**Usage**
```ts
const MyList = a.array(a.string());
type MyList = a.infer<typeof MyList>; // string[];
a.validate(MyList, [1, 2]); // false
a.validate(MyList, ["hello", "world"]); // true
```
**Outputted JTD**
```json
{
"elements": {
"type": "string"
}
}
```
### Objects
**Usage**
```ts
const User = a.object({
id: a.string(),
email: a.string(),
created: a.timestamp(),
});
type User = a.infer<typeof User>; // { id: string; email: string; created: Date; }
a.validate({
id: "1",
email: "johndoe@example.com",
created: new Date(),
}); // true
a.validate({
id: "1",
email: null,
created: new Date(),
}); // false
```
**Outputted JTD**
```json
{
"properties": {
"id": {
"type": "string"
},
"email": {
"type": "string"
},
"created": {
"type": "timestamp"
}
}
}
```
### Records / Maps
**Usage**
```ts
const R = a.record(a.boolean());
type R = a.infer<typeof R>; // Record<string, boolean>
a.validate(R, {
hello: true,
world: false,
}); // true;
a.validate(R, {
hello: "world",
}); // false;
```
**Outputted JTD**
```json
{
"values": {
"type": "boolean"
}
}
```
### Discriminated Unions
**Usage**
```ts
const Shape = a.discriminator("type", {
RECTANGLE: a.object({
width: a.float32(),
height: a.float32(),
}),
CIRCLE: a.object({
radius: a.float32(),
}),
});
type Shape = a.infer<typeof Shape>; // { type: "RECTANGLE"; width: number; height: number; } | { type: "CIRCLE"; radius: number; }
// Infer specific sub types of the union
type ShapeTypeRectangle = a.inferSubType<Shape, "type", "RECTANGLE">; // { type "RECTANGLE"; width: number; height: number; };
type ShapeTypeCircle = a.inferSubType<Shape, "type", "CIRCLE">; // { type "CIRCLE"; radius: number; }
a.validate(Shape, {
type: "RECTANGLE",
width: 1,
height: 1.5,
}); // true
a.validate(Shape, {
type: "CIRCLE",
radius: 5,
}); // true
a.validate(Shape, {
type: "CIRCLE",
width: 1,
height: 1.5,
}); // false
```
**Outputted JTD**
```json
{
"discriminator": "type",
"mapping": {
"RECTANGLE": {
"properties": {
"width": {
"type": "float32"
},
"height": {
"type": "float32"
}
}
},
"CIRCLE": {
"properties": {
"radius": {
"type": "float32"
}
}
}
}
}
```
## Modifiers
### Optional
Use `a.optional()` to make an object field optional.
```ts
const User = a.object({
id: a.string(),
email: a.optional(a.string()),
date: a.timestamp();
})
/**
* Resulting type
* {
* id: string;
* email: string | undefined;
* date: Date;
* }
*/
```
**Outputted JTD**
```json
{
"properties": {
"id": {
"type": "string"
},
"date": {
"type": "timestamp"
}
},
"optionalProperties": {
"email": {
"type": "string"
}
}
}
```
### Nullable
Use `a.nullable()` to make a particular type nullable
```ts
const name = a.nullable(a.string());
/**
* Resulting type
* string | null
*/
```
**Outputted JTD**
```json
{
"type": "string",
"nullable": true
}
```
### Extend
Extend an object schema with the `a.extend()` helper.
```ts
const A = a.object({
a: a.string(),
b: a.float32(),
});
// { a: string; b: number; }
const B = a.object({
c: a.timestamp(),
});
// { c: Date }
const C = a.extend(A, B);
// { a: string; b: number; c: Date }
```
### Omit
Use `a.omit()` to create a new object schema with certain properties removed
```ts
const A = a.object({
a: a.string(),
b: a.float32(),
});
// { a: string; b: number; }
const B = a.omit(A, ["a"]);
// { b: number; }
```
### Pick
Use `a.pick()` to create a new object schema with the a subset of properties from the parent object
```ts
const A = a.object({
a: a.string(),
b: a.float32(),
c: a.timestamp(),
});
// { a: string; b: number; c: Date; }
const B = a.pick(A, ["a", "c"]);
// { a: string; c: Date; }
```
### Partial
Use `a.partial()` to create a new object schema that makes all of the properties of the parent schema optional.
```ts
const A = a.object({
a: a.string(),
b: a.float32(),
c: a.timestamp(),
});
// { a: string; b: number; c: Date; }
const B = a.partial(A);
// { a: string | undefined; b: number | undefined; c: Date | undefined; }
```
## Helpers
### Validate
Call `a.validate()` to validate an input against an arri schema. This method also acts as a type guard, so any `any` or `unknown` types that pass validation will automatically gain autocomplete for the validated fields
```ts
const User = a.object({
id: a.string(),
name: a.string(),
});
a.validate(User, true); // false
a.validate(User, { id: "1", name: "john doe" }); // true
if (a.validate(User, someInput)) {
console.log(someInput.id); // intellisense works here
}
```
### Parse
Call `a.parse()` to parse a JSON string against an arri schema. It will also handle parsing normal objects as well.
```ts
const User = a.object({
id: a.string(),
name: a.string(),
});
// returns a User if successful or throws a ValidationError if fails
const result = a.parse(User, jsonString);
```
### Safe Parse
A safer alternative to `a.parse()` that doesn't throw an error.
```ts
const User = a.object({
id: a.string(),
name: a.string(),
});
const result = a.safeParse(User, jsonString);
if (result.success) {
console.log(result.value); // result.value will be User
} else {
console.error(result.error);
}
```
### Coerce
`a.coerce()` will attempt to convert inputs to the correct type. If it fails to convert the inputs it will throw a `ValidationError`
```ts
const A = a.object({
a: a.string(),
b: a.boolean(),
c: a.float32(),
});
a.coerce(A, {
a: "1",
b: "true",
c: "500.24",
});
// { a: "1", b: true, c: 500.24 };
```
### Safe Coerce
`a.safeCoerce()` is an alternative to `a.coerce()` that doesn't throw.
```ts
const A = a.object({
a: a.string(),
b: a.boolean(),
c: a.float32(),
});
const result = a.safeCoerce(A, someInput);
if (result.success) {
console.log(result.value);
} else {
console.error(result.error);
}
```
### Serialize
`a.serialize()` will take an input and serialize it to a valid JSON string.
```ts
const User = a.object({
id: a.string(),
name: a.string(),
});
a.serialize(User, { id: "1", name: "john doe" });
// {"id":"1","name":"john doe"}
```
Be aware that this function does not validate the input. So if you are passing in an any or unknown type into this function it is recommended that you validate it first.
### Errors
Use `a.errors()` to get all of the validation errors of a given input.
```ts
const User = a.object({
id: a.string(),
date: a.timestamp(),
});
a.errors(User, { id: 1, date: "hello world" });
/**
* [
* {
* instancePath: "/id",
* schemaPath: "/properties/id/type",
* message: "Expected string",
* },
* {
* instancePath: "/date",
* schemaPath: "/properties/id/type",
* message: "Expected instanceof Date",
* }
* ]
*
*/
```
## Compiled Validators
`arri-validate` comes with a high performance JIT compiler that transforms Arri Schemas into highly optimized validation, parsing, serialization functions.
```ts
const User = a.object({
id: a.string(),
email: a.nullable(a.string()),
created: a.timestamp(),
});
const $$User = a.compile(User);
$$User.validate(someInput);
$$User.parse(someJson);
$$User.serialize({ id: "1", email: null, created: new Date() });
```
In most cases, the compiled validators will be much faster than the standard utilities. However there is some overhead with compiling the schemas so ideally each validator would be compiled once.
Additionally the resulting methods make use of eval so they can only be used in an environment that you control such as a backend server. They WILL NOT work in a browser environment.
You can use `a.compile` for code generation. The compiler result gives you access to the generated function bodies.
```ts
$$User.compiledCode.validate; // the generated validation code
$$User.compiledCode.parse; // the generated parsing code
$$User.compiledCode.serialize; // the generated serialization code
```
## Building

@@ -49,0 +582,0 @@

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc