Socket
Socket
Sign inDemoInstall

@arktype/util

Package Overview
Dependencies
Maintainers
1
Versions
78
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@arktype/util - npm Package Compare versions

Comparing version 0.0.4 to 0.0.5

dist/domain.d.ts

474

dist/main.d.ts

@@ -1,459 +0,15 @@

declare class InternalArktypeError extends Error {
}
declare const throwInternalError: (message: string) => never;
declare class ParseError extends Error {
}
declare const throwParseError: (message: string) => never;
type ZeroWidthSpace = " ";
type ErrorMessage<message extends string = string> = `${message}${ZeroWidthSpace}`;
type Completion<text extends string = string> = `${text}${ZeroWidthSpace}${ZeroWidthSpace}`;
type Fn<args extends readonly unknown[] = readonly never[], returns = unknown> = (...args: args) => returns;
type paramsOf<t> = t extends Fn<infer p> ? p : never;
type returnOf<t> = t extends Fn<never, infer r> ? r : never;
declare const cached: <T>(thunk: () => T) => () => T;
declare const isThunk: <value>(value: value) => value is Extract<value, Thunk<unknown>> extends never ? value & Thunk<unknown> : Extract<value, Thunk<unknown>>;
type Thunk<ret = unknown> = () => ret;
type thunkable<t> = t | Thunk<t>;
declare const CompiledFunction: CompiledFunction;
type CompiledFunction = new <f extends (...args: never[]) => unknown>(...args: ConstructorParameters<typeof Function>) => f & {
apply(thisArg: null, args: Parameters<f>): ReturnType<f>;
call(thisArg: null, ...args: Parameters<f>): ReturnType<f>;
};
type pathToString<segments extends string[], delimiter extends string = "/"> = segments extends [] ? "/" : join<segments, delimiter>;
type join<segments extends string[], delimiter extends string, result extends string = ""> = segments extends [infer head extends string, ...infer tail extends string[]] ? join<tail, delimiter, result extends "" ? head : `${result}${delimiter}${head}`> : result;
type split<s extends string, delimiter extends string, current extends string = "", result extends string[] = []> = s extends `${infer head}${infer tail}` ? head extends delimiter ? split<tail, delimiter, "", [...result, current]> : split<tail, delimiter, `${current}${head}`, result> : [...result, s];
declare const getPath: (root: unknown, path: string[]) => unknown;
declare const intersectUniqueLists: <item>(l: readonly item[], r: readonly item[]) => item[];
type List<t = unknown> = readonly t[];
type listable<t> = t | readonly t[];
type NonEmptyList<t = unknown> = readonly [t, ...t[]];
type CollapsingList<t = unknown> = readonly [] | t | readonly [t, t, ...t[]];
type arraySubclassToReadonly<t extends unknown[]> = readonly t[number][] & {
[k in Exclude<keyof t, keyof unknown[]>]: t[k];
};
declare const listFrom: <t>(data: t) => t extends readonly unknown[] ? [t] extends [null] ? t[] : t : t[];
declare const spliterate: <item, included extends item>(list: readonly item[], by: (item: item) => item is included) => [included: included[], excluded: Exclude<item, included>[]];
declare const ReadonlyArray: new <T extends readonly unknown[]>(...args: T) => T;
declare const includes: <array extends readonly unknown[]>(array: array, element: unknown) => element is array[number];
type stringifyUnion<t extends string> = join<unionToTuple<t>, ", ">;
type unionToTuple<t> = unionToTupleRecurse<t, []> extends infer result ? conform<result, t[]> : never;
type unionToTupleRecurse<t, result extends unknown[]> = getLastBranch<t> extends infer current ? [t] extends [never] ? result : unionToTupleRecurse<Exclude<t, current>, [current, ...result]> : never;
type getLastBranch<t> = intersectUnion<t extends unknown ? (x: t) => void : never> extends (x: infer branch) => void ? branch : never;
type intersectUnion<t> = (t extends unknown ? (_: t) => void : never) extends (_: infer intersection) => void ? intersection : never;
type overloadOf<f extends Fn, givenArgs extends readonly unknown[] = readonly unknown[]> = Exclude<collectSignatures<(() => never) & f, givenArgs, unknown>, f extends () => never ? never : () => never>;
type collectSignatures<f, givenArgs extends readonly unknown[], result> = result & f extends (...args: infer args) => infer returns ? result extends f ? never : collectSignatures<f, givenArgs, Pick<f, keyof f> & result & ((...args: args) => returns)> | (args extends givenArgs ? (...args: args) => returns : never) : never;
type Stringifiable = string | boolean | number | bigint | null | undefined;
/**
* Force an operation like `{ a: 0 } & { b: 1 }` to be computed so that it displays `{ a: 0; b: 1 }`.
*
* Also works for some non-intersections, e.g. `keyof SomeObj` => `"a" | "b" | ...`
*/
type evaluate<t> = {
[k in keyof t]: t[k];
} & unknown;
type exact<t extends object, u extends object> = {
[k in keyof t]: k extends keyof u ? t[k] : never;
};
type exactMessageOnError<t extends object, u extends object> = {
[k in keyof t]: k extends keyof u ? t[k] : ErrorMessage<`'${k & string}' is not a valid key`>;
};
type defer<t> = [t][t extends any ? 0 : never];
type merge<base, merged> = evaluate<Omit<base, keyof merged> & merged>;
type mergeAll<t extends readonly unknown[]> = t["length"] extends 1 ? t[0] : mergeAllRecurse<t>;
type mergeAllRecurse<t extends readonly unknown[]> = t extends readonly [
infer head,
...infer tail
] ? merge<head, mergeAll<tail>> : [];
/**
* Simple interesection (&) combined with evaluate to improve display
*/
type and<l, r> = evaluate<l & r>;
/**
* Interesection (`&`) that avoids evaluating `unknown` to `{}`
*/
type andPreserveUnknown<l, r> = unknown extends l & r ? unknown : evaluate<l & r>;
type isAny<t> = [unknown, t] extends [t, {}] ? true : false;
type isNever<t> = [t] extends [never] ? true : false;
type isUnknown<t> = unknown extends t ? [t] extends [{}] ? false : true : false;
type conform<t, base> = t extends base ? t : base;
type equals<t, u> = (<_>() => _ extends t ? 1 : 2) extends <_>() => _ extends u ? 1 : 2 ? true : false;
declare const id: unique symbol;
type id = typeof id;
type nominal<t, id extends string> = t & {
readonly [id]: id;
};
type satisfy<t, u extends {
[k in keyof t]: t[k];
}> = u;
type extend<t, u> = evaluate<t & u>;
type defined<t> = t & ({} | null);
type autocomplete<suggestions extends string> = suggestions | (string & {});
type widen<t, supertypes> = collectWidenedType<t, unionToTuple<supertypes>>;
type collectWidenedType<t, remaining extends unknown[], result = never> = remaining extends [infer head, ...infer tail] ? collectWidenedType<t, tail, t extends head ? result | head : result> : result;
declare const hasDomain: <data, domain extends Domain>(data: data, kind: domain) => data is data & inferDomain<domain>;
type TypesByDomain = {
bigint: bigint;
boolean: boolean;
number: number;
object: object;
string: string;
symbol: symbol;
undefined: undefined;
null: null;
};
type inferDomain<kind extends Domain> = Domain extends kind ? unknown : TypesByDomain[kind];
type Domain = evaluate<keyof TypesByDomain>;
type NullishDomain = "undefined" | "null";
type NonNullishDomain = Exclude<Domain, NullishDomain>;
type PrimitiveDomain = Exclude<Domain, "object">;
type Primitive = inferDomain<PrimitiveDomain>;
type domainOf<data> = unknown extends data ? Domain : data extends object ? "object" : data extends string ? "string" : data extends number ? "number" : data extends boolean ? "boolean" : data extends undefined ? "undefined" : data extends null ? "null" : data extends bigint ? "bigint" : data extends symbol ? "symbol" : never;
declare const domainOf: <data>(data: data) => domainOf<data>;
type Digit = 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9;
type BigintLiteral<value extends bigint = bigint> = `${value}n`;
type NumberLiteral<value extends number = number> = `${value}`;
type IntegerLiteral<value extends bigint = bigint> = `${value}`;
/**
* The goal of the number literal and bigint literal regular expressions is to:
*
* 1. Ensure definitions form a bijection with the values they represent.
* 2. Attempt to mirror TypeScript's own format for stringification of numeric
* values such that the regex should match a given definition if any only if
* a precise literal type will be inferred (in TS4.8+).
*/
/**
* Matches a well-formatted numeric expression according to the following rules:
* 1. Must include an integer portion (i.e. '.321' must be written as '0.321')
* 2. The first digit of the value must not be 0, unless the entire integer portion is 0
* 3. If the value includes a decimal, its last digit may not be 0
* 4. The value may not be "-0"
*/
declare const wellFormedNumberMatcher: RegExp;
declare const isWellFormedNumber: (s: string) => boolean;
/**
* Matches a well-formatted integer according to the following rules:
* 1. Must begin with an integer, the first digit of which cannot be 0 unless the entire value is 0
* 2. The value may not be "-0"
*/
declare const wellFormedIntegerMatcher: RegExp;
declare const isWellFormedInteger: (s: string) => boolean;
type NumericLiteralKind = "number" | "bigint" | "integer";
declare const numericLiteralDescriptions: {
readonly number: "a number";
readonly bigint: "a bigint";
readonly integer: "an integer";
};
type numericLiteralDescriptions = typeof numericLiteralDescriptions;
type writeMalformedNumericLiteralMessage<def extends string, kind extends NumericLiteralKind> = `'${def}' was parsed as ${numericLiteralDescriptions[kind]} but could not be narrowed to a literal value. Avoid unnecessary leading or trailing zeros and other abnormal notation`;
declare const writeMalformedNumericLiteralMessage: <def extends string, kind extends NumericLiteralKind>(def: def, kind: kind) => `'${def}' was parsed as ${{
readonly number: "a number";
readonly bigint: "a bigint";
readonly integer: "an integer";
}[kind]} but could not be narrowed to a literal value. Avoid unnecessary leading or trailing zeros and other abnormal notation`;
declare const tryParseNumber: <errorOnFail extends string | boolean>(token: string, options?: NumericParseOptions<errorOnFail> | undefined) => errorOnFail extends string | true ? number : number | undefined;
type tryParseNumber<token extends string, messageOnFail extends string> = token extends NumberLiteral<infer value> ? number extends value ? writeMalformedNumericLiteralMessage<token, "number"> : value : messageOnFail;
declare const tryParseInteger: <errorOnFail extends string | boolean>(token: string, options?: NumericParseOptions<errorOnFail> | undefined) => errorOnFail extends string | true ? number : number | undefined;
type tryParseInteger<token extends string, messageOnFail extends string> = token extends IntegerLiteral<infer value> ? bigint extends value ? writeMalformedNumericLiteralMessage<token, "integer"> : `${value}` extends NumberLiteral<infer valueAsNumber> ? valueAsNumber : never : messageOnFail;
type NumericParseOptions<errorOnFail extends boolean | string> = {
errorOnFail?: errorOnFail;
strict?: boolean;
};
declare const tryParseWellFormedBigint: (def: string) => bigint | undefined;
declare const builtinObjectKinds: {
readonly Array: ArrayConstructor;
readonly Date: DateConstructor;
readonly Error: ErrorConstructor;
readonly Function: FunctionConstructor;
readonly Map: MapConstructor;
readonly RegExp: RegExpConstructor;
readonly Set: SetConstructor;
readonly String: StringConstructor;
readonly Number: NumberConstructor;
readonly Boolean: BooleanConstructor;
readonly WeakMap: WeakMapConstructor;
readonly WeakSet: WeakSetConstructor;
readonly Promise: PromiseConstructor;
};
type ObjectKindSet = Record<string, Constructor>;
type BuiltinObjectConstructors = typeof builtinObjectKinds;
type BuiltinObjectKind = keyof BuiltinObjectConstructors;
type BuiltinObjects = {
[kind in BuiltinObjectKind]: InstanceType<BuiltinObjectConstructors[kind]>;
};
type instantiableObjectKind<data extends object, kinds extends ObjectKindSet> = {
[kind in keyof kinds]: kinds[kind] extends Constructor<data> ? kind : never;
}[keyof kinds];
type objectKindOf<data extends object, kinds extends ObjectKindSet = BuiltinObjectConstructors> = object extends data ? keyof kinds | undefined : data extends Fn ? "Function" : instantiableObjectKind<data, kinds> extends never ? keyof kinds | undefined : instantiableObjectKind<data, kinds>;
declare const objectKindOf: <data extends object, kinds extends ObjectKindSet = {
readonly Array: ArrayConstructor;
readonly Date: DateConstructor;
readonly Error: ErrorConstructor;
readonly Function: FunctionConstructor;
readonly Map: MapConstructor;
readonly RegExp: RegExpConstructor;
readonly Set: SetConstructor;
readonly String: StringConstructor;
readonly Number: NumberConstructor;
readonly Boolean: BooleanConstructor;
readonly WeakMap: WeakMapConstructor;
readonly WeakSet: WeakSetConstructor;
readonly Promise: PromiseConstructor;
}>(data: data, kinds?: kinds | undefined) => objectKindOf<data, kinds> | undefined;
declare const objectKindOrDomainOf: <data, kinds extends ObjectKindSet = {
readonly Array: ArrayConstructor;
readonly Date: DateConstructor;
readonly Error: ErrorConstructor;
readonly Function: FunctionConstructor;
readonly Map: MapConstructor;
readonly RegExp: RegExpConstructor;
readonly Set: SetConstructor;
readonly String: StringConstructor;
readonly Number: NumberConstructor;
readonly Boolean: BooleanConstructor;
readonly WeakMap: WeakMapConstructor;
readonly WeakSet: WeakSetConstructor;
readonly Promise: PromiseConstructor;
}>(data: data, kinds?: kinds | undefined) => (objectKindOf<data & object, kinds> & {}) | domainOf<data>;
type objectKindOrDomainOf<data, kinds extends ObjectKindSet = BuiltinObjectConstructors> = data extends object ? objectKindOf<data, kinds> extends undefined ? "object" : objectKindOf<data, kinds> : domainOf<data>;
declare const hasObjectKind: <kind extends keyof kinds, kinds extends ObjectKindSet = {
readonly Array: ArrayConstructor;
readonly Date: DateConstructor;
readonly Error: ErrorConstructor;
readonly Function: FunctionConstructor;
readonly Map: MapConstructor;
readonly RegExp: RegExpConstructor;
readonly Set: SetConstructor;
readonly String: StringConstructor;
readonly Number: NumberConstructor;
readonly Boolean: BooleanConstructor;
readonly WeakMap: WeakMapConstructor;
readonly WeakSet: WeakSetConstructor;
readonly Promise: PromiseConstructor;
}>(data: object, kind: kind, kinds?: kinds | undefined) => data is InstanceType<kinds[kind]>;
declare const isArray: (data: unknown) => data is readonly unknown[];
/** Each defaultObjectKind's completion for the phrase "Must be _____" */
declare const objectKindDescriptions: {
readonly Array: "an array";
readonly Function: "a function";
readonly Date: "a Date";
readonly RegExp: "a RegExp";
readonly Error: "an Error";
readonly Map: "a Map";
readonly Set: "a Set";
readonly String: "a String object";
readonly Number: "a Number object";
readonly Boolean: "a Boolean object";
readonly Promise: "a Promise";
readonly WeakMap: "a WeakMap";
readonly WeakSet: "a WeakSet";
};
declare const getExactBuiltinConstructorName: (constructor: unknown) => BuiltinObjectKind | undefined;
type Constructor<instance = {}> = abstract new (...args: never[]) => instance;
type instanceOf<constructor> = constructor extends Constructor<infer instance> ? instance : never;
/** Mimics output of TS's keyof operator at runtime */
declare const prototypeKeysOf: <t>(value: t) => (keyof t)[];
declare const getBaseDomainKeys: <domain extends Domain>(domain: domain) => Record<Domain, readonly PropertyKey[]>[domain][number][];
declare const constructorExtends: (constructor: Constructor, base: Constructor) => boolean;
type Dict<k extends string = string, v = unknown> = {
readonly [_ in k]: v;
};
/** Either:
* A, with all properties of B undefined
* OR
* B, with all properties of A undefined
**/
type propwiseXor<a, b> = evaluate<a & {
[k in keyof b]?: undefined;
}> | evaluate<b & {
[k in keyof a]?: undefined;
}>;
type requireKeys<o, key extends keyof o> = o & {
[requiredKey in key]-?: defined<o[requiredKey]>;
};
type PartialRecord<k extends string = string, v = unknown> = {
[_ in k]?: v;
};
type keySet<key extends string = string> = {
readonly [_ in key]?: 1;
};
type mutable<o, maxDepth extends number = 1> = mutableRecurse<o, [
], maxDepth>;
type mutableRecurse<o, depth extends 1[], maxDepth extends number> = depth["length"] extends maxDepth ? o : o extends object ? o extends Fn ? o : {
-readonly [k in keyof o]: mutableRecurse<o[k], [...depth, 1], maxDepth>;
} : o;
type entryOf<o> = {
[k in keyof o]-?: [k, o[k] & ({} | null)];
}[o extends readonly unknown[] ? keyof o & number : keyof o] & unknown;
type entriesOf<o extends object> = entryOf<o>[];
declare const entriesOf: <o extends object>(o: o) => entriesOf<o>;
type Entry<key extends PropertyKey = PropertyKey, value = unknown> = readonly [
key: key,
value: value
];
type fromEntries<entries extends readonly Entry[]> = evaluate<{
[entry in entries[number] as entry[0]]: entry[1];
}>;
declare const fromEntries: <const entries extends readonly Entry<PropertyKey, unknown>[]>(entries: entries) => { [entry in entries[number] as entry[0]]: entry[1]; } extends infer T ? { [k in keyof T]: { [entry in entries[number] as entry[0]]: entry[1]; }[k]; } : never;
declare const transform: <const o extends object, transformed extends Entry<PropertyKey, unknown> | readonly Entry<PropertyKey, unknown>[]>(o: o, flatMapEntry: (entry: { [k in keyof o]-?: [k, o[k] & ({} | null)]; }[o extends readonly unknown[] ? keyof o & number : keyof o]) => transformed) => intersectUnion<{ [entry in (transformed extends readonly Entry<PropertyKey, unknown>[] ? transformed : [transformed])[number] as entry[0]]: entry[1]; } extends infer T_1 ? { [k_2 in keyof T_1]: { [entry in (transformed extends readonly Entry<PropertyKey, unknown>[] ? transformed : [transformed])[number] as entry[0]]: entry[1]; }[k_2]; } : never> extends infer T ? { [k_1 in keyof T]: intersectUnion<{ [entry in (transformed extends readonly Entry<PropertyKey, unknown>[] ? transformed : [transformed])[number] as entry[0]]: entry[1]; } extends infer T_1 ? { [k_2 in keyof T_1]: { [entry in (transformed extends readonly Entry<PropertyKey, unknown>[] ? transformed : [transformed])[number] as entry[0]]: entry[1]; }[k_2]; } : never>[k_1]; } : never;
/** Mimics the result of Object.keys(...) */
type keysOf<o> = o extends readonly unknown[] ? number extends o["length"] ? `${number}` : keyof o & `${number}` : {
[K in keyof o]: K extends string ? K : K extends number ? `${K}` : never;
}[keyof o];
declare const keysOf: <o extends object>(o: o) => keysOf<o>[];
declare const isKeyOf: <k extends string | number | symbol, obj extends object>(k: k, obj: obj) => k is Extract<keyof obj, k>;
type requiredKeyOf<o> = {
[k in keyof o]-?: o extends {
[_ in k]-?: o[k];
} ? k : never;
}[keyof o];
type optionalKeyOf<o> = Exclude<keyof o, requiredKeyOf<o>>;
type optionalizeKeys<o, keys extends keyof o> = evaluate<{
[k in Exclude<keyof o, keys>]: o[k];
} & {
[k in keys]?: o[k];
}>;
type replaceKey<o, k extends keyof o, v> = evaluate<Omit<o, k> & {
[_ in k]: v;
}>;
type valueOf<o> = o[keyof o];
declare const ShallowClone: new <t extends object>(base: t) => t;
declare class DynamicBase<t extends object> extends ShallowClone<t> {
}
declare const NoopBase: new <t extends object>() => t;
declare class CastableBase<t extends object> extends NoopBase<t> {
}
declare const shallowClone: <input extends object>(input: input) => input;
type SerializationOptions = {
onCycle?: (value: object) => string;
onSymbol?: (value: symbol) => string;
onFunction?: (value: Function) => string;
onUndefined?: string;
};
type Json = {
[k: string | number]: JsonData;
} | readonly JsonData[];
type JsonData = string | boolean | number | null | Json;
declare const snapshot: <t>(data: t, opts?: SerializationOptions) => snapshot<t, []>;
type snapshot<t, depth extends 1[] = []> = unknown extends t ? unknown : t extends Primitive ? snapshotPrimitive<t> : t extends Function ? `(function${string})` : t extends Date ? string : depth["length"] extends 10 ? unknown : t extends List<infer item> ? List<snapshot<item, [...depth, 1]>> : {
[k in keyof t]: snapshot<t[k], [...depth, 1]>;
};
type snapshotPrimitive<t> = t extends undefined ? "(undefined)" : t extends bigint ? `${t}n` : t extends symbol ? `(symbol${string})` : t;
declare const print: (data: unknown, indent?: number) => void;
declare const stringify: (data: unknown, indent?: number) => string;
type SerializedString<value extends string = string> = `"${value}"`;
type SerializedPrimitives = {
string: SerializedString;
number: NumberLiteral;
bigint: BigintLiteral;
boolean: "true" | "false";
null: "null";
undefined: "undefined";
};
type SerializedPrimitive = SerializedPrimitives[keyof SerializedPrimitives];
type SerializablePrimitive = inferDomain<keyof SerializedPrimitives>;
declare const serializePrimitive: <value extends string | number | bigint | boolean | null | undefined>(value: value) => serializePrimitive<value>;
type serializePrimitive<value extends SerializablePrimitive> = value extends string ? `"${value}"` : value extends bigint ? `${value}n` : `${value}`;
declare const lazily: <t extends object>(thunk: () => t) => t;
/** A small set of HKT utility types based on https://github.com/poteat/hkt-toolbelt */
declare namespace Hkt {
const key: unique symbol;
type key = typeof key;
abstract class Kind<f extends Fn = Fn> {
readonly [key]: unknown;
abstract readonly f: f;
}
type apply<hkt extends Kind, args extends Parameters<hkt["f"]>[0]> = ReturnType<(hkt & {
readonly [key]: args;
})["f"]>;
interface Reify extends Kind {
f(In: conform<this[key], Kind>): reify<typeof In>;
}
const reify: <def extends Kind<Fn>>(def: def) => reify<def>;
type reify<hkt extends Kind> = <const In extends Parameters<hkt["f"]>[0]>(In: In) => Hkt.apply<hkt, In>;
}
interface AndPreserveUnknown extends Hkt.Kind {
f: (args: conform<this[Hkt.key], [unknown, unknown]>) => andPreserveUnknown<(typeof args)[0], (typeof args)[1]>;
}
type ArrayIntersectionMode = "values" | "parameters";
type intersectArrays<l extends readonly unknown[], r extends readonly unknown[], operator extends Hkt.Kind = AndPreserveUnknown> = intersectParametersRecurse<l, r, [], operator, "values">;
type intersectParameters<l extends readonly unknown[], r extends readonly unknown[], operator extends Hkt.Kind = AndPreserveUnknown> = intersectParametersRecurse<l, r, [], operator, "parameters">;
type intersectParametersRecurse<l extends readonly unknown[], r extends readonly unknown[], prefix extends readonly unknown[], intersector extends Hkt.Kind, mode extends ArrayIntersectionMode> = [parseNextElement<l, mode>, parseNextElement<r, mode>] extends [
infer lState extends ElementParseResult,
infer rState extends ElementParseResult
] ? shouldRecurse<lState, rState, mode> extends true ? intersectParametersRecurse<lState["tail"], rState["tail"], [
...prefix,
...(lState["optional"] | rState["optional"] extends true ? [Hkt.apply<intersector, [lState["head"], rState["head"]]>?] : [Hkt.apply<intersector, [lState["head"], rState["head"]]>])
], intersector, mode> : [
...prefix,
...(lState["tail"] extends readonly [] ? rState["tail"] extends readonly [] ? [] : mode extends "parameters" ? rState["tail"] : [] : rState["tail"] extends readonly [] ? mode extends "parameters" ? lState["tail"] : [] : Hkt.apply<intersector, [lState["head"], rState["head"]]>[])
] : never;
type shouldRecurse<lState extends ElementParseResult, rState extends ElementParseResult, mode extends ArrayIntersectionMode> = [lState["done"], rState["done"]] extends [true, true] ? false : mode extends "parameters" ? true : [
true,
readonly []
] extends [lState["done"], lState["tail"]] | [rState["done"], rState["tail"]] ? false : true;
type ElementParseResult = {
head: unknown;
optional: boolean;
tail: readonly unknown[];
done: boolean;
};
type parseNextElement<params extends readonly unknown[], mode extends ArrayIntersectionMode> = params extends readonly [] ? {
head: mode extends "values" ? never : unknown;
optional: true;
tail: [];
done: true;
} : params extends readonly [(infer head)?, ...infer tail] ? [tail, params] extends [params, tail] ? {
head: head;
optional: true;
tail: tail;
done: true;
} : {
head: [] extends params ? Exclude<head, undefined> : head;
optional: [] extends params ? true : false;
tail: tail;
done: false;
} : never;
type isDisjoint<l, r> = l & r extends never ? true : domainOf<l> & domainOf<r> extends never ? true : [l, r] extends [object, object] ? true extends valueOf<{
[k in Extract<keyof l & keyof r, requiredKeyOf<l> | requiredKeyOf<r>>]: isDisjoint<l[k], r[k]>;
}> ? true : false : false;
type applyElementLabels<t extends readonly unknown[], labels extends readonly unknown[]> = labels extends [unknown, ...infer labelsTail] ? t extends readonly [infer head, ...infer tail] ? readonly [
...labelElement<head, labels>,
...applyElementLabels<tail, labelsTail>
] : applyOptionalElementLabels<Required<t>, labels> : t;
type applyOptionalElementLabels<t extends readonly unknown[], labels extends readonly unknown[]> = labels extends readonly [unknown, ...infer labelsTail] ? t extends readonly [infer head, ...infer tail] ? [
...labelOptionalElement<head, labels>,
...applyOptionalElementLabels<tail, labelsTail>
] : applyRestElementLabels<t, labels> : t;
type applyRestElementLabels<t extends readonly unknown[], labels extends readonly unknown[]> = t extends readonly [] ? [] : labels extends readonly [unknown, ...infer tail] ? [...labelOptionalElement<t[0], labels>, ...applyRestElementLabels<t, tail>] : t;
type labelElement<element, labels extends readonly unknown[]> = labels extends readonly [unknown] ? {
[K in keyof labels]: element;
} : labels extends readonly [...infer head, unknown] ? labelElement<element, head> : [_: element];
type labelOptionalElement<element, label extends readonly unknown[]> = label extends readonly [unknown] ? {
[K in keyof label]?: element;
} : label extends readonly [...infer head, unknown] ? labelOptionalElement<element, head> : [_?: element];
type ComposeSignatures = {
<traits extends NonEmptyList<Constructor>>(...traits: traits): compose<traits>;
<labels extends 1[]>(): <traits extends NonEmptyList<Constructor>>(...traits: traits) => compose<traits, labels>;
};
declare const compose: ComposeSignatures;
type compose<traits extends readonly Constructor[], labels extends 1[] = []> = composeRecurse<traits, [], {}, labels>;
type composeRecurse<traits extends readonly unknown[], parameters extends readonly unknown[], instance extends {}, labels extends 1[]> = traits extends readonly [
abstract new (...args: infer nextArgs) => infer nextInstance,
...infer tail
] ? composeRecurse<tail, intersectParameters<parameters, nextArgs>, instance & nextInstance, labels> : abstract new (...args: applyElementLabels<parameters, labels>) => instance;
export { AndPreserveUnknown, BigintLiteral, BuiltinObjectConstructors, BuiltinObjectKind, BuiltinObjects, CastableBase, CollapsingList, CompiledFunction, Completion, ComposeSignatures, Constructor, Dict, Digit, Domain, DynamicBase, ErrorMessage, Fn, Hkt, IntegerLiteral, InternalArktypeError, Json, JsonData, List, NonEmptyList, NonNullishDomain, NullishDomain, NumberLiteral, NumericParseOptions, ObjectKindSet, ParseError, PartialRecord, Primitive, PrimitiveDomain, ReadonlyArray, SerializablePrimitive, SerializationOptions, SerializedPrimitive, SerializedPrimitives, Stringifiable, Thunk, ZeroWidthSpace, and, andPreserveUnknown, arraySubclassToReadonly, autocomplete, builtinObjectKinds, cached, compose, composeRecurse, conform, constructorExtends, defer, defined, domainOf, entriesOf, entryOf, equals, evaluate, exact, exactMessageOnError, extend, fromEntries, getBaseDomainKeys, getExactBuiltinConstructorName, getPath, hasDomain, hasObjectKind, id, includes, inferDomain, instanceOf, intersectArrays, intersectParameters, intersectUnion, intersectUniqueLists, isAny, isArray, isDisjoint, isKeyOf, isNever, isThunk, isUnknown, isWellFormedInteger, isWellFormedNumber, join, keySet, keysOf, lazily, listFrom, listable, merge, mergeAll, mutable, nominal, objectKindDescriptions, objectKindOf, objectKindOrDomainOf, optionalKeyOf, optionalizeKeys, overloadOf, paramsOf, pathToString, print, propwiseXor, prototypeKeysOf, replaceKey, requireKeys, requiredKeyOf, returnOf, satisfy, serializePrimitive, shallowClone, snapshot, split, spliterate, stringify, stringifyUnion, throwInternalError, throwParseError, thunkable, transform, tryParseInteger, tryParseNumber, tryParseWellFormedBigint, unionToTuple, valueOf, wellFormedIntegerMatcher, wellFormedNumberMatcher, widen, writeMalformedNumericLiteralMessage };
export * from "./domain.js";
export * from "./errors.js";
export * from "./functions.js";
export * from "./generics.js";
export * from "./hkt.js";
export * from "./intersections.js";
export * from "./lazily.js";
export * from "./lists.js";
export * from "./numericLiterals.js";
export * from "./objectKinds.js";
export * from "./records.js";
export * from "./serialize.js";
export * from "./trait.js";
export * from "./unionToTuple.js";
//# sourceMappingURL=main.d.ts.map

@@ -1,410 +0,15 @@

// domain.ts
var hasDomain = (data, kind) => domainOf(data) === kind;
var domainOf = (data) => {
const builtinType = typeof data;
return builtinType === "object" ? data === null ? "null" : "object" : builtinType === "function" ? "object" : builtinType;
};
// errors.ts
var InternalArktypeError = class extends Error {
};
var throwInternalError = (message) => {
throw new InternalArktypeError(message);
};
var ParseError = class extends Error {
};
var throwParseError = (message) => {
throw new ParseError(message);
};
// functions.ts
var cached = (thunk) => {
let isCached = false;
let result;
return () => {
if (!isCached) {
result = thunk();
isCached = true;
}
return result;
};
};
var isThunk = (value) => typeof value === "function" && value.length === 0;
var CompiledFunction = class extends Function {
constructor(...args) {
const params = args.slice(0, -1);
const body = args.at(-1);
try {
super(...params, body);
} catch (e) {
return throwInternalError(
`Encountered an unexpected error while compiling your definition:
Message: ${e}
Source: (${args.slice(0, -1)}) => {
${args.at(-1)}
}`
);
}
}
};
// generics.ts
var id = Symbol("id");
// lists.ts
var getPath = (root, path) => {
let result = root;
for (const segment of path) {
if (typeof result !== "object" || result === null) {
return void 0;
}
result = result[segment];
}
return result;
};
var intersectUniqueLists = (l, r) => {
const intersection = [...l];
for (const item of r) {
if (!l.includes(item)) {
intersection.push(item);
}
}
return intersection;
};
var listFrom = (data) => Array.isArray(data) ? data : [data];
var spliterate = (list, by) => {
const result = [
[],
[]
];
for (const item of list) {
if (by(item)) {
result[0].push(item);
} else {
result[1].push(item);
}
}
return result;
};
var ReadonlyArray = Array;
var includes = (array, element) => array.includes(element);
// numericLiterals.ts
var wellFormedNumberMatcher = /^(?!^-0$)-?(?:0|[1-9]\d*)(?:\.\d*[1-9])?$/;
var isWellFormedNumber = (s) => wellFormedNumberMatcher.test(s);
var numberLikeMatcher = /^-?\d*\.?\d*$/;
var isNumberLike = (s) => s.length !== 0 && numberLikeMatcher.test(s);
var wellFormedIntegerMatcher = /^(?:0|(?:-?[1-9]\d*))$/;
var isWellFormedInteger = (s) => wellFormedIntegerMatcher.test(s);
var integerLikeMatcher = /^-?\d+$/;
var isIntegerLike = (s) => integerLikeMatcher.test(s);
var numericLiteralDescriptions = {
number: "a number",
bigint: "a bigint",
integer: "an integer"
};
var writeMalformedNumericLiteralMessage = (def, kind) => `'${def}' was parsed as ${numericLiteralDescriptions[kind]} but could not be narrowed to a literal value. Avoid unnecessary leading or trailing zeros and other abnormal notation`;
var isWellFormed = (def, kind) => kind === "number" ? isWellFormedNumber(def) : isWellFormedInteger(def);
var parseKind = (def, kind) => kind === "number" ? Number(def) : Number.parseInt(def);
var isKindLike = (def, kind) => kind === "number" ? isNumberLike(def) : isIntegerLike(def);
var tryParseNumber = (token, options) => parseNumeric(token, "number", options);
var tryParseInteger = (token, options) => parseNumeric(token, "integer", options);
var parseNumeric = (token, kind, options) => {
const value = parseKind(token, kind);
if (!Number.isNaN(value)) {
if (isKindLike(token, kind)) {
if (options?.strict) {
return isWellFormed(token, kind) ? value : throwParseError(writeMalformedNumericLiteralMessage(token, kind));
}
return value;
}
}
return options?.errorOnFail ? throwParseError(
options?.errorOnFail === true ? `Failed to parse ${numericLiteralDescriptions[kind]} from '${token}'` : options?.errorOnFail
) : void 0;
};
var tryParseWellFormedBigint = (def) => {
if (def[def.length - 1] !== "n") {
return;
}
const maybeIntegerLiteral = def.slice(0, -1);
let value;
try {
value = BigInt(maybeIntegerLiteral);
} catch {
return;
}
if (wellFormedIntegerMatcher.test(maybeIntegerLiteral)) {
return value;
}
if (integerLikeMatcher.test(maybeIntegerLiteral)) {
return throwParseError(writeMalformedNumericLiteralMessage(def, "bigint"));
}
};
// records.ts
var entriesOf = (o) => Object.entries(o);
var fromEntries = (entries) => Object.fromEntries(entries);
var transform = (o, flatMapEntry) => Object.fromEntries(
entriesOf(o).flatMap((entry) => {
const result = flatMapEntry(entry);
return isArray(result[0]) ? result : [result];
})
);
var keysOf = (o) => Object.keys(o);
var isKeyOf = (k, obj) => k in obj;
var ShallowClone = class {
constructor(properties) {
Object.assign(this, properties);
}
};
var DynamicBase = class extends ShallowClone {
};
var NoopBase = class {
};
var CastableBase = class extends NoopBase {
};
var shallowClone = (input) => Object.create(
Object.getPrototypeOf(input),
Object.getOwnPropertyDescriptors(input)
);
// objectKinds.ts
var builtinObjectKinds = {
Array,
Date,
Error,
Function,
Map,
RegExp,
Set,
String,
Number,
Boolean,
WeakMap,
WeakSet,
Promise
};
var objectKindOf = (data, kinds) => {
const kindSet = kinds ?? builtinObjectKinds;
let prototype = Object.getPrototypeOf(data);
while (prototype?.constructor && (!kindSet[prototype.constructor.name] || !(data instanceof kindSet[prototype.constructor.name]))) {
prototype = Object.getPrototypeOf(prototype);
}
const name = prototype?.constructor?.name;
if (name === void 0 || name === "Object") {
return void 0;
}
return name;
};
var objectKindOrDomainOf = (data, kinds) => typeof data === "object" && data !== null ? objectKindOf(data, kinds) ?? "object" : domainOf(data);
var hasObjectKind = (data, kind, kinds) => objectKindOf(data, kinds) === kind;
var isArray = (data) => Array.isArray(data);
var objectKindDescriptions = {
Array: "an array",
Function: "a function",
Date: "a Date",
RegExp: "a RegExp",
Error: "an Error",
Map: "a Map",
Set: "a Set",
String: "a String object",
Number: "a Number object",
Boolean: "a Boolean object",
Promise: "a Promise",
WeakMap: "a WeakMap",
WeakSet: "a WeakSet"
};
var getExactBuiltinConstructorName = (constructor) => {
const constructorName = Object(constructor).name;
return constructorName && isKeyOf(constructorName, builtinObjectKinds) && builtinObjectKinds[constructorName] === constructor ? constructorName : void 0;
};
var prototypeKeysOf = (value) => {
const result = [];
while (value !== Object.prototype && value !== null && value !== void 0) {
for (const k of Object.getOwnPropertyNames(value)) {
if (k !== "constructor" && !result.includes(k)) {
result.push(k);
}
}
for (const symbol of Object.getOwnPropertySymbols(value)) {
if (!result.includes(symbol)) {
result.push(symbol);
}
}
value = Object.getPrototypeOf(value);
}
return result;
};
var baseKeysByDomain = {
bigint: prototypeKeysOf(0n),
boolean: prototypeKeysOf(false),
null: [],
number: prototypeKeysOf(0),
// TS doesn't include the Object prototype in keyof, so keyof object is never
object: [],
string: prototypeKeysOf(""),
symbol: prototypeKeysOf(Symbol()),
undefined: []
};
var getBaseDomainKeys = (domain) => [
...baseKeysByDomain[domain]
];
var constructorExtends = (constructor, base) => {
let current = constructor.prototype;
while (current !== null) {
if (current === base.prototype) {
return true;
}
current = Object.getPrototypeOf(current);
}
return false;
};
// serialize.ts
var snapshot = (data, opts = { onUndefined: "(undefined)" }) => serializeRecurse(data, opts, []);
var print = (data, indent) => console.log(stringify(data, indent));
var stringify = (data, indent) => {
switch (domainOf(data)) {
case "object":
return data instanceof Date ? data.toDateString() : JSON.stringify(
serializeRecurse(data, stringifyOpts, []),
null,
indent
);
case "symbol":
return stringifyOpts.onSymbol(data);
default:
return serializePrimitive(data);
}
};
var stringifyOpts = {
onCycle: () => "(cycle)",
onSymbol: (v) => `(symbol ${v.description ?? "anonymous"})`,
onFunction: (v) => `(function ${v.name ?? "anonymous"})`
};
var serializeRecurse = (data, opts, seen) => {
switch (domainOf(data)) {
case "object":
if (typeof data === "function") {
return stringifyOpts.onFunction(data);
}
if (seen.includes(data)) {
return "(cycle)";
}
const nextSeen = [...seen, data];
if (Array.isArray(data)) {
return data.map((item) => serializeRecurse(item, opts, nextSeen));
}
if (data instanceof Date) {
return data.toDateString();
}
const result = {};
for (const k in data) {
result[k] = serializeRecurse(data[k], opts, nextSeen);
}
return result;
case "symbol":
return stringifyOpts.onSymbol(data);
case "bigint":
return `${data}n`;
case "undefined":
return opts.onUndefined ?? "undefined";
default:
return data;
}
};
var serializePrimitive = (value) => typeof value === "string" ? JSON.stringify(value) : typeof value === "bigint" ? `${value}n` : `${value}`;
// lazily.ts
var lazily = (thunk) => {
let cached2;
return new Proxy({}, {
get: (_, prop) => {
if (!cached2) {
cached2 = thunk();
}
return cached2[prop];
},
set: (_, prop, value) => {
if (!cached2) {
cached2 = thunk();
}
cached2[prop] = value;
return true;
}
});
};
// trait.ts
var compose = (...args) => {
if (args.length === 0) {
return compose;
}
const traits = args;
let result = Object;
for (let i = 0; i < traits.length; i++) {
result = Object.setPrototypeOf(result, traits[i].prototype);
}
return result;
};
// hkt.ts
var Hkt;
((Hkt2) => {
class Kind {
}
Hkt2.Kind = Kind;
Hkt2.reify = (def) => def.f;
})(Hkt || (Hkt = {}));
export {
CastableBase,
CompiledFunction,
DynamicBase,
Hkt,
InternalArktypeError,
ParseError,
ReadonlyArray,
builtinObjectKinds,
cached,
compose,
constructorExtends,
domainOf,
entriesOf,
fromEntries,
getBaseDomainKeys,
getExactBuiltinConstructorName,
getPath,
hasDomain,
hasObjectKind,
id,
includes,
intersectUniqueLists,
isArray,
isKeyOf,
isThunk,
isWellFormedInteger,
isWellFormedNumber,
keysOf,
lazily,
listFrom,
objectKindDescriptions,
objectKindOf,
objectKindOrDomainOf,
print,
prototypeKeysOf,
serializePrimitive,
shallowClone,
snapshot,
spliterate,
stringify,
throwInternalError,
throwParseError,
transform,
tryParseInteger,
tryParseNumber,
tryParseWellFormedBigint,
wellFormedIntegerMatcher,
wellFormedNumberMatcher,
writeMalformedNumericLiteralMessage
};
export * from "./domain.js";
export * from "./errors.js";
export * from "./functions.js";
export * from "./generics.js";
export * from "./hkt.js";
export * from "./intersections.js";
export * from "./lazily.js";
export * from "./lists.js";
export * from "./numericLiterals.js";
export * from "./objectKinds.js";
export * from "./records.js";
export * from "./serialize.js";
export * from "./trait.js";
export * from "./unionToTuple.js";
//# sourceMappingURL=main.js.map
{
"name": "@arktype/util",
"version": "0.0.4",
"version": "0.0.5",
"author": {

@@ -13,12 +13,21 @@ "name": "David Blass",

"arktype-repo": "./main.js",
"import": "./dist/main.js"
"types": "./dist/main.d.ts",
"default": "./dist/main.js"
},
"./internal/*": {
"arktype-repo": "./*",
"types": "./dist/*",
"default": "./dist/*"
}
},
"files": [
"dist"
"dist",
"**/*.ts",
"!**/*.tsBuildInfo",
"!__tests__"
],
"scripts": {
"build": "tsup --config ../repo/tsup.config.ts",
"build": "tsc --build ./tsconfig.build.json",
"test": "ts ../repo/testPackage.ts"
}
}
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