All files json-spec.ts

100% Statements 20/20
100% Branches 6/6
100% Functions 9/9
100% Lines 20/20

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228      1x                                                                         1x       6x                               1x 4x             1x 1x                                           1x                             3x                                       1x                               1x                 1x 1x                 1x 3x                                           1x     1x                     1x     1x                             1x                      
// A loose Typescript interpretation of the JSON spec from
// http://www.ecma-international.org/publications/files/ECMA-ST/ECMA-404.pdf
 
export const InternalTypeSymbol = Symbol("InternalType");
 
export type JsonValue =
  | { [property: string]: JsonValue }
  | boolean
  | JsonValue[]
  | null
  | number
  | string;
 
// Given types T and U, return T transformed such that the fields in U are made required
type PartialRequire<T, U extends keyof T> = T & Required<Pick<T, U>>;
 
// Given a union type U, return the intersection of all its component types.
// For example, if U = A | B | C, then UnionToIntersection<U> = A & B & C.
// UnionToIntersection magic taken from https://stackoverflow.com/a/50375286/2407869
// eslint-disable-next-line @typescript-eslint/no-explicit-any
type UnionToIntersection<U> = (U extends any
? (k: U) => void
: never) extends (k: infer I) => void
  ? I
  : never;
 
interface BaseJsonSchema {
  title?: string;
  description?: string;
}
 
interface StringOptions<EnumType extends string | undefined = undefined>
  extends BaseJsonSchema {
  enum?: readonly EnumType[];
  format?: string;
  maxLength?: string;
  minLength?: string;
  pattern?: string;
}
 
const stringConstructor = <T extends string>(
  options: StringOptions<T> = {}
) => {
  type internalType = typeof options.enum extends undefined ? string : T;
  return {
    type: "string" as const,
    ...options,
    [InternalTypeSymbol]: {} as internalType
  };
};
 
interface NumberOptions extends BaseJsonSchema {
  multipleOf?: number;
  minimum?: number;
  exclusiveMinimum?: number;
  maximum?: number;
  exclusiveMaximum?: number;
  description?: string;
}
 
const numberConstructor = (options: NumberOptions = {}) => {
  return {
    type: "number" as const,
    ...options,
    [InternalTypeSymbol]: {} as number
  };
};
 
const integerConstructor = (options: NumberOptions = {}) => {
  return {
    type: "integer" as const,
    ...options,
    [InternalTypeSymbol]: {} as number
  };
};
 
interface ObjectOptions<
  Properties extends { [k: string]: JsonSchema },
  AdditionalProperties extends JsonSchema, // TODO support boolean
  RequiredProperties extends readonly (keyof Properties)[]
> extends BaseJsonSchema {
  properties?: Properties;
  additionalProperties?: AdditionalProperties;
  required: RequiredProperties; // mandatory for now, since leaving it empty is making all properties required
  propertyNames?: JsonSchema;
  minProperties?: number;
  maxProperties?: number;
  // dependencies?: any; // not yet supported
  patternProperties?: { [k: string]: JsonSchema };
}
 
const objectConstructor = <
  Properties extends { [k: string]: JsonSchema },
  AdditionalProperties extends JsonSchema, // TODO support boolean
  RequiredProperties extends readonly (keyof Properties)[]
>(
  options: ObjectOptions<Properties, AdditionalProperties, RequiredProperties>
) => {
  type internalPropertyTypes = PartialRequire<
    Partial<
      // optional by default
      { [P in keyof Properties]: Properties[P][typeof InternalTypeSymbol] }
    >,
    RequiredProperties[number]
  >;
  type additionalPropertyTypes = { [k: string]: AdditionalProperties };
  return {
    type: "object" as const,
    ...options,
    [InternalTypeSymbol]: {} as internalPropertyTypes & additionalPropertyTypes
  };
};
 
interface ArrayOptions<
  Items, // extends JsonSchema | readonly JsonSchema[],
  AdditionalItems extends Items extends JsonSchema // additionalItems doesn't make sense unless Items is a list
    ? never
    : JsonSchema // TOOD support boolean
> extends BaseJsonSchema {
  items?: Items;
  additionalItems?: AdditionalItems;
  minItems?: number;
  maxItems?: number;
  uniqueItems?: boolean;
}
 
const arrayConstructor = <
  Items extends JsonSchema | readonly JsonSchema[],
  AdditionalItems extends Items extends JsonSchema // additionalItems doesn't make sense unless Items is a list
    ? never
    : JsonSchema
>(
  options: ArrayOptions<Items, AdditionalItems> = {}
) => {
  type internalType = Items extends readonly JsonSchema[]
    ? Array<
        | Items[number][typeof InternalTypeSymbol]
        | AdditionalItems[typeof InternalTypeSymbol]
      > // this isn't strict enough, but I'm not sure if it's possible to improve this at the moment. // would be nicer to somehow concatenate the types, as in [exploded Items, ...AdditionalItems]
    : Items extends JsonSchema // not sure why this isn't inferred
    ? Items[typeof InternalTypeSymbol][]
    : never;
  return {
    type: "array" as const,
    ...options,
    [InternalTypeSymbol]: {} as internalType
  };
};
 
interface BooleanOptions extends BaseJsonSchema {}
 
const booleanConstructor = (options: BooleanOptions = {}) => {
  return {
    type: "boolean" as const,
    ...options,
    [InternalTypeSymbol]: {} as boolean
  };
};
 
interface NullOptions extends BaseJsonSchema {}
 
const nullConstructor = (options: NullOptions = {}) => {
  return {
    type: "null" as const,
    ...options,
    [InternalTypeSymbol]: ({} as unknown) as null
  };
};
 
interface AnyOfOptions<Schemas extends readonly JsonSchema[]>
  extends BaseJsonSchema {
  anyOf: Schemas;
}
 
// TODO: union of enum types not working for anyof/allof.
// I want
// typeof allOfConstructor({
//   allOf: [
//     Type.String({ enum: ["a", "b"] }),
//     Type.String({ enum: ["a", "b", "c"] })
//   ]
// })[InternalTypeSymbol];
// to be "a" | "b", but right now it's just string
 
const anyOfConstructor = <Schemas extends readonly JsonSchema[]>(
  options: AnyOfOptions<Schemas>
) => {
  return {
    ...options,
    [InternalTypeSymbol]: {} as typeof options.anyOf[number][typeof InternalTypeSymbol]
  };
};
 
interface AllOfOptions<Schemas extends readonly JsonSchema[]>
  extends BaseJsonSchema {
  allOf: Schemas;
}
 
const allOfConstructor = <Schemas extends readonly JsonSchema[]>(
  options: AllOfOptions<Schemas>
) => {
  return {
    ...options,
    [InternalTypeSymbol]: {} as UnionToIntersection<
      typeof options.allOf[number][typeof InternalTypeSymbol]
    >
  };
};
 
// TODO support oneOf
export interface InterfaceWithHiddenType {
  [InternalTypeSymbol]: unknown;
}
 
export interface JsonSchema extends InterfaceWithHiddenType {}
 
export const Schema = {
  String: stringConstructor,
  Number: numberConstructor,
  Integer: integerConstructor,
  Object: objectConstructor,
  Array: arrayConstructor,
  Boolean: booleanConstructor,
  Null: nullConstructor,
  AnyOf: anyOfConstructor,
  AllOf: allOfConstructor
};