nalloc 0.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +282 -0
- package/build/devtools.cjs +79 -0
- package/build/devtools.cjs.map +1 -0
- package/build/devtools.d.ts +82 -0
- package/build/devtools.js +43 -0
- package/build/devtools.js.map +1 -0
- package/build/index.cjs +76 -0
- package/build/index.cjs.map +1 -0
- package/build/index.d.ts +4 -0
- package/build/index.js +5 -0
- package/build/index.js.map +1 -0
- package/build/option.cjs +279 -0
- package/build/option.cjs.map +1 -0
- package/build/option.d.ts +356 -0
- package/build/option.js +157 -0
- package/build/option.js.map +1 -0
- package/build/result.cjs +381 -0
- package/build/result.cjs.map +1 -0
- package/build/result.d.ts +442 -0
- package/build/result.js +229 -0
- package/build/result.js.map +1 -0
- package/build/safe.cjs +88 -0
- package/build/safe.cjs.map +1 -0
- package/build/safe.d.ts +29 -0
- package/build/safe.js +18 -0
- package/build/safe.js.map +1 -0
- package/build/testing.cjs +111 -0
- package/build/testing.cjs.map +1 -0
- package/build/testing.d.ts +85 -0
- package/build/testing.js +81 -0
- package/build/testing.js.map +1 -0
- package/build/types.cjs +78 -0
- package/build/types.cjs.map +1 -0
- package/build/types.d.ts +137 -0
- package/build/types.js +36 -0
- package/build/types.js.map +1 -0
- package/build/unsafe.cjs +82 -0
- package/build/unsafe.cjs.map +1 -0
- package/build/unsafe.d.ts +27 -0
- package/build/unsafe.js +11 -0
- package/build/unsafe.js.map +1 -0
- package/package.json +93 -0
- package/src/__tests__/index.ts +13 -0
- package/src/__tests__/option.ts +610 -0
- package/src/__tests__/option.types.ts +120 -0
- package/src/__tests__/result.ts +721 -0
- package/src/__tests__/result.types.ts +249 -0
- package/src/__tests__/safe.ts +24 -0
- package/src/__tests__/tooling.ts +86 -0
- package/src/__tests__/unsafe.ts +24 -0
- package/src/devtools.ts +97 -0
- package/src/index.ts +18 -0
- package/src/option.ts +510 -0
- package/src/result.ts +676 -0
- package/src/safe.ts +58 -0
- package/src/testing.ts +159 -0
- package/src/types.ts +201 -0
- package/src/unsafe.ts +47 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/result.ts"],"sourcesContent":["import { err as ERR, isOk, isErr, isSome, isNone, NONE, optionOf } from './types.js';\nimport type { Ok, Err, Result, Option, Widen, WidenNever } from './types.js';\n\nexport type { Ok, Err, Result };\nexport { isOk, isErr };\n\n/**\n * Executes a function and captures the result or error.\n * @param fn - Function to execute\n * @param onError - Optional error transformer\n * @returns Ok(result) if successful, Err(error) if thrown\n * @example\n * tryCatch(() => JSON.parse('{\"a\":1}')) // Ok({a: 1})\n * tryCatch(() => JSON.parse('invalid')) // Err(SyntaxError)\n * tryCatch(() => { throw 'oops' }, e => e) // Err('oops')\n */\nexport function tryCatch<T, E = unknown>(fn: () => T, onError?: (error: unknown) => E): Result<T, E> {\n try {\n return fn() as Ok<T>;\n } catch (error) {\n return ERR(onError ? onError(error) : (error as E));\n }\n}\n\n/**\n * Alias for tryCatch. Executes a function and captures the result or error.\n * @param fn - Function to execute\n * @returns Ok(result) if successful, Err(error) if thrown\n */\nexport function of<T, E = unknown>(fn: () => T): Result<T, E> {\n return tryCatch(fn);\n}\n\n/**\n * Executes an async function and captures the result or error.\n * @param fn - Async function to execute\n * @param onError - Optional error transformer\n * @returns Promise of Ok(result) if successful, Err(error) if rejected\n * @example\n * await tryAsync(() => fetch('/api').then(r => r.json())) // Ok(data) or Err(error)\n */\nexport async function tryAsync<T, E = unknown>(fn: () => Promise<T>, onError?: (error: unknown) => E): Promise<Result<T, E>> {\n try {\n return (await fn()) as Ok<T>;\n } catch (error) {\n return ERR(onError ? onError(error) : (error as E));\n }\n}\n\n/**\n * Alias for tryAsync. Executes an async function and captures the result or error.\n * @param fn - Async function to execute\n * @returns Promise of Ok(result) if successful, Err(error) if rejected\n */\nexport function ofAsync<T, E = unknown>(fn: () => Promise<T>): Promise<Result<T, E>> {\n return tryAsync(fn);\n}\n\n/**\n * Converts a Promise to a Result.\n * @param promise - The promise to convert\n * @param onRejected - Optional rejection handler\n * @returns Promise of Ok(value) if resolved, Err(error) if rejected\n * @example\n * await fromPromise(Promise.resolve(42)) // Ok(42)\n * await fromPromise(Promise.reject('error')) // Err('error')\n */\nexport async function fromPromise<T, E = unknown>(promise: Promise<T>, onRejected?: (reason: unknown) => E): Promise<Result<T, E>> {\n try {\n return (await promise) as Ok<T>;\n } catch (error) {\n return ERR(onRejected ? onRejected(error) : (error as E));\n }\n}\n\n/**\n * Unwraps an Ok value or returns a computed value for Err.\n * @param result - The Result to unwrap\n * @param onErr - Function called with error if Err\n * @returns The Ok value or result of onErr(error)\n * @example\n * unwrapOrReturn(ok(42), e => 0) // 42\n * unwrapOrReturn(err('fail'), e => 0) // 0\n */\nexport function unwrapOrReturn<T, E, const R>(result: Result<T, E>, onErr: (error: E) => R): T | R {\n return isOk(result) ? result : onErr(result.error);\n}\n\n/**\n * Asserts that a Result is Ok, throwing if Err.\n * @param result - The Result to assert\n * @param message - Custom error message\n * @throws Error if result is Err\n * @example\n * assertOk(ok(42)) // passes\n * assertOk(err('failed')) // throws Error\n */\nexport function assertOk<T, E>(result: Result<T, E>, message?: string): asserts result is Ok<T> {\n if (isErr(result)) {\n throw new Error(message ?? `Expected Ok result. Received error: ${String((result as Err<E>).error)}`);\n }\n}\n\n/**\n * Asserts that a Result is Err, throwing if Ok.\n * @param result - The Result to assert\n * @param message - Custom error message\n * @throws Error if result is Ok\n * @example\n * assertErr(err('failed')) // passes\n * assertErr(ok(42)) // throws Error\n */\nexport function assertErr<T, E>(result: Result<T, E>, message?: string): asserts result is Err<E> {\n if (isOk(result)) {\n throw new Error(message ?? 'Expected Err result.');\n }\n}\n\n/**\n * Checks if result is Err with a non-null error value.\n * @param result - The Result to check\n * @returns true if Err with Some error value\n */\nexport function isSomeErr<T, E>(result: Result<T, E>): boolean {\n return isErr(result) && isSome((result as Err<E>).error);\n}\n\n/**\n * Transforms the Ok value, leaving Err unchanged.\n * @param result - The Result to map\n * @param fn - Transform function\n * @returns Ok(fn(value)) if Ok, Err unchanged\n * @example\n * map(ok(2), x => x * 2) // Ok(4)\n * map(err('e'), x => x * 2) // Err('e')\n */\nexport function map<T, U, E>(result: Err<E>, fn: (value: T) => U): Err<E>;\nexport function map<T, U>(result: Ok<T>, fn: (value: T) => U): Ok<U>;\nexport function map<T, U, E>(result: Result<T, E>, fn: (value: T) => U): Result<U, E>;\nexport function map<T, U, E>(result: Result<T, E>, fn: (value: T) => U): Result<U, E> {\n if (isErr(result)) return result as Err<E>;\n return fn(result as Ok<T>) as Ok<U>;\n}\n\n/**\n * Transforms the Err value, leaving Ok unchanged.\n * @param result - The Result to map\n * @param fn - Error transform function\n * @returns Err(fn(error)) if Err, Ok unchanged\n * @example\n * mapErr(err('e'), e => e.toUpperCase()) // Err('E')\n * mapErr(ok(42), e => e.toUpperCase()) // Ok(42)\n */\nexport function mapErr<T, E, F>(result: Ok<T>, fn: (error: E) => F): Ok<T>;\nexport function mapErr<E, F>(result: Err<E>, fn: (error: E) => F): Err<F>;\nexport function mapErr<T, E, F>(result: Result<T, E>, fn: (error: E) => F): Result<T, F>;\nexport function mapErr<T, E, F>(result: Result<T, E>, fn: (error: E) => F): Result<T, F> {\n if (isOk(result)) return result;\n return ERR(fn(result.error));\n}\n\n/**\n * Chains Result-returning functions. Returns Err if the input is Err.\n * @param result - The Result to chain\n * @param fn - Function returning a Result\n * @returns The result of fn(value) if Ok, Err unchanged\n * @example\n * flatMap(ok(2), x => ok(x * 2)) // Ok(4)\n * flatMap(ok(2), x => err('fail')) // Err('fail')\n * flatMap(err('e'), x => ok(x * 2)) // Err('e')\n */\nexport function flatMap<T, U, E>(result: Err<E>, fn: (value: T) => Result<U, E>): Err<E>;\nexport function flatMap<T, U, E>(result: Result<T, E>, fn: (value: T) => Result<U, E>): Result<U, E>;\nexport function flatMap<T, U, E>(result: Result<T, E>, fn: (value: T) => Result<U, E>): Result<U, E> {\n if (isErr(result)) return result as Err<E>;\n return fn(result as Ok<T>);\n}\n\n/**\n * Alias for flatMap. Chains Result-returning functions.\n * @param result - The Result to chain\n * @param fn - Function returning a Result\n * @returns The result of fn(value) if Ok, Err unchanged\n */\nexport function andThen<T, U, E>(result: Err<E>, fn: (value: T) => Result<U, E>): Err<E>;\nexport function andThen<T, U, E>(result: Result<T, E>, fn: (value: T) => Result<U, E>): Result<U, E>;\nexport function andThen<T, U, E>(result: Result<T, E>, fn: (value: T) => Result<U, E>): Result<U, E> {\n return flatMap(result, fn);\n}\n\n/**\n * Executes a side effect if Ok, then returns the original Result.\n * @param result - The Result to tap\n * @param fn - Side effect function\n * @returns The original Result unchanged\n * @example\n * tap(ok(42), x => console.log(x)) // logs 42, returns Ok(42)\n */\nexport function tap<T, E>(result: Err<E>, fn: (value: T) => void): Err<E>;\nexport function tap<T>(result: Ok<T>, fn: (value: T) => void): Ok<T>;\nexport function tap<T, E>(result: Result<T, E>, fn: (value: T) => void): Result<T, E>;\nexport function tap<T, E>(result: Result<T, E>, fn: (value: T) => void): Result<T, E> {\n if (isOk(result)) {\n fn(result);\n }\n return result;\n}\n\n/**\n * Executes a side effect if Err, then returns the original Result.\n * @param result - The Result to tap\n * @param fn - Side effect function for error\n * @returns The original Result unchanged\n * @example\n * tapErr(err('fail'), e => console.log(e)) // logs 'fail', returns Err('fail')\n */\nexport function tapErr<T, E>(result: Ok<T>, fn: (error: E) => void): Ok<T>;\nexport function tapErr<E>(result: Err<E>, fn: (error: E) => void): Err<E>;\nexport function tapErr<T, E>(result: Result<T, E>, fn: (error: E) => void): Result<T, E>;\nexport function tapErr<T, E>(result: Result<T, E>, fn: (error: E) => void): Result<T, E> {\n if (isErr(result)) {\n fn((result as Err<E>).error);\n }\n return result;\n}\n\n/**\n * Maps both Ok and Err values simultaneously.\n * @param result - The Result to map\n * @param okFn - Transform for Ok value\n * @param errFn - Transform for Err value\n * @returns Ok(okFn(value)) if Ok, Err(errFn(error)) if Err\n * @example\n * bimap(ok(2), x => x * 2, e => e.toUpperCase()) // Ok(4)\n * bimap(err('e'), x => x * 2, e => e.toUpperCase()) // Err('E')\n */\nexport function bimap<T, U, E, F>(result: Ok<T>, okFn: (value: T) => U, errFn: (error: E) => F): Ok<U>;\nexport function bimap<T, U, E, F>(result: Err<E>, okFn: (value: T) => U, errFn: (error: E) => F): Err<F>;\nexport function bimap<T, U, E, F>(result: Result<T, E>, okFn: (value: T) => U, errFn: (error: E) => F): Result<U, F>;\nexport function bimap<T, U, E, F>(result: Result<T, E>, okFn: (value: T) => U, errFn: (error: E) => F): Result<U, F> {\n return isOk(result) ? (okFn(result) as Ok<U>) : ERR(errFn(result.error));\n}\n\n/**\n * Extracts the Ok value, throws if Err.\n * @param result - The Result to unwrap\n * @returns The contained Ok value\n * @throws Error if result is Err\n * @example\n * unwrap(ok(42)) // 42\n * unwrap(err('failed')) // throws Error\n */\nexport function unwrap<T, E>(result: Result<T, E>): T {\n if (isErr(result)) {\n throw new Error(`Called unwrap on Err: ${String((result as Err<E>).error)}`);\n }\n return result as T;\n}\n\n/**\n * Extracts the Err value, throws if Ok.\n * @param result - The Result to unwrap\n * @returns The contained error\n * @throws Error if result is Ok\n * @example\n * unwrapErr(err('failed')) // 'failed'\n * unwrapErr(ok(42)) // throws Error\n */\nexport function unwrapErr<T, E>(result: Result<T, E>): E {\n if (isOk(result)) {\n throw new Error(`Called unwrapErr on Ok: ${String(result)}`);\n }\n return result.error;\n}\n\n/**\n * Extracts the Ok value, or returns a default.\n * @param result - The Result to unwrap\n * @param defaultValue - Value if Err\n * @returns The Ok value or defaultValue\n * @example\n * unwrapOr(ok(42), 0) // 42\n * unwrapOr(err('failed'), 0) // 0\n */\nexport function unwrapOr<T, E>(result: Result<T, E>, defaultValue: T): T {\n return isOk(result) ? result : defaultValue;\n}\n\n/**\n * Extracts the Ok value, or computes a default from the error.\n * @param result - The Result to unwrap\n * @param fn - Function to compute default from error\n * @returns The Ok value or fn(error)\n * @example\n * unwrapOrElse(ok(42), e => 0) // 42\n * unwrapOrElse(err('failed'), e => 0) // 0\n */\nexport function unwrapOrElse<T, E>(result: Result<T, E>, fn: (error: E) => T): T {\n return isOk(result) ? result : fn(result.error);\n}\n\n/**\n * Maps the Ok value and returns it, or returns a default.\n * @param result - The Result to map\n * @param defaultValue - Value if Err\n * @param fn - Transform function\n * @returns fn(value) if Ok, defaultValue otherwise\n * @example\n * mapOr(ok(2), 0, x => x * 2) // 4\n * mapOr(err('e'), 0, x => x * 2) // 0\n */\nexport function mapOr<T, E, U>(result: Result<T, E>, defaultValue: U, fn: (value: T) => U): U {\n return isOk(result) ? fn(result) : defaultValue;\n}\n\n/**\n * Maps the Ok value and returns it, or computes a default.\n * @param result - The Result to map\n * @param defaultFn - Function to compute default\n * @param fn - Transform function\n * @returns fn(value) if Ok, defaultFn() otherwise\n * @example\n * mapOrElse(ok(2), () => 0, x => x * 2) // 4\n * mapOrElse(err('e'), () => 0, x => x * 2) // 0\n */\nexport function mapOrElse<T, E, U>(result: Result<T, E>, defaultFn: () => U, fn: (value: T) => U): U {\n return isOk(result) ? fn(result) : defaultFn();\n}\n\n/**\n * Extracts the Ok value, throws with custom message if Err.\n * @param result - The Result to unwrap\n * @param message - Error message prefix if Err\n * @returns The Ok value\n * @throws Error with message if Err\n * @example\n * expect(ok(42), 'missing value') // 42\n * expect(err('fail'), 'missing value') // throws Error('missing value: fail')\n */\nexport function expect<T, E>(result: Result<T, E>, message: string): T {\n if (isErr(result)) {\n throw new Error(`${message}: ${String((result as Err<E>).error)}`);\n }\n return result as Ok<T>;\n}\n\n/**\n * Extracts the Err value, throws with custom message if Ok.\n * @param result - The Result to unwrap\n * @param message - Error message prefix if Ok\n * @returns The error value\n * @throws Error with message if Ok\n * @example\n * expectErr(err('fail'), 'expected error') // 'fail'\n * expectErr(ok(42), 'expected error') // throws Error\n */\nexport function expectErr<T, E>(result: Result<T, E>, message: string): E {\n if (isOk(result)) {\n throw new Error(`${message}: ${String(result)}`);\n }\n return result.error;\n}\n\n/**\n * Returns other if result is Ok, otherwise returns the Err.\n * @param result - First Result\n * @param other - Second Result\n * @returns other if result is Ok, result (Err) otherwise\n * @example\n * and(ok(1), ok(2)) // Ok(2)\n * and(err('e'), ok(2)) // Err('e')\n */\nexport function and<T, U, E>(result: Result<T, E>, other: Result<U, E>): Result<U, E> {\n return isOk(result) ? other : result;\n}\n\n/**\n * Returns result if Ok, otherwise returns other.\n * @param result - First Result\n * @param other - Fallback Result\n * @returns result if Ok, other otherwise\n * @example\n * or(ok(1), ok(2)) // Ok(1)\n * or(err('e'), ok(2)) // Ok(2)\n */\nexport function or<T, E, F>(result: Result<T, E>, other: Result<T, F>): Result<T, F> {\n return isOk(result) ? result : other;\n}\n\n/**\n * Returns result if Ok, otherwise computes a fallback from the error.\n * @param result - First Result\n * @param fn - Function to compute fallback\n * @returns result if Ok, fn(error) otherwise\n * @example\n * orElse(ok(1), e => ok(0)) // Ok(1)\n * orElse(err('e'), e => ok(0)) // Ok(0)\n */\nexport function orElse<T, E, F>(result: Result<T, E>, fn: (error: E) => Result<T, F>): Result<T, F> {\n return isOk(result) ? result : fn(result.error);\n}\n\n/**\n * Converts a Result to an Option, discarding the error.\n * @param result - The Result to convert\n * @returns Some(value) if Ok, None if Err\n * @example\n * toOption(ok(42)) // Some(42)\n * toOption(err('failed')) // None\n */\nexport function toOption<T, E>(result: Result<T, E>): Option<T> {\n return isOk(result) ? optionOf(result) : NONE;\n}\n\n/**\n * Converts a Result's error to an Option.\n * @param result - The Result to convert\n * @returns Some(error) if Err, None if Ok\n * @example\n * toErrorOption(err('failed')) // Some('failed')\n * toErrorOption(ok(42)) // None\n */\nexport function toErrorOption<T, E>(result: Result<T, E>): Option<E> {\n return isErr(result) ? optionOf((result as Err<E>).error) : NONE;\n}\n\n/**\n * Combines two Results into a Result of a tuple.\n * @param left - First Result\n * @param right - Second Result\n * @returns Ok([a, b]) if both Ok, first Err otherwise\n * @example\n * zip(ok(1), ok('a')) // Ok([1, 'a'])\n * zip(ok(1), err('e')) // Err('e')\n */\nexport function zip<T, U, E>(left: Result<T, E>, right: Result<U, E>): Result<[T, U], E> {\n if (isErr(left)) return left as Err<E>;\n if (isErr(right)) return right as Err<E>;\n return [left as Ok<T>, right as Ok<U>] as Ok<[T, U]>;\n}\n\n/**\n * Combines two Results using a function.\n * @param left - First Result\n * @param right - Second Result\n * @param fn - Combining function\n * @returns Ok(fn(a, b)) if both Ok, first Err otherwise\n * @example\n * zipWith(ok(2), ok(3), (a, b) => a + b) // Ok(5)\n */\nexport function zipWith<T, U, V, E>(left: Result<T, E>, right: Result<U, E>, fn: (left: T, right: U) => V): Result<V, E> {\n if (isErr(left)) return left as Err<E>;\n if (isErr(right)) return right as Err<E>;\n return fn(left as Ok<T>, right as Ok<U>) as Ok<V>;\n}\n\n/**\n * Flattens a nested Result.\n * @param result - Result containing a Result\n * @returns The inner Result\n * @example\n * flatten(ok(ok(42))) // Ok(42)\n * flatten(ok(err('e'))) // Err('e')\n * flatten(err('outer')) // Err('outer')\n */\nexport function flatten<T, E>(result: Result<Result<T, E>, E>): Result<T, E> {\n return isErr(result) ? (result as Err<E>) : (result as Result<T, E>);\n}\n\n/**\n * Pattern matches on a Result, handling both Ok and Err cases.\n * @param result - The Result to match\n * @param onOk - Handler for Ok case\n * @param onErr - Handler for Err case\n * @returns Result of the matching handler\n * @example\n * match(ok(42), x => x * 2, e => 0) // 84\n * match(err('e'), x => x * 2, e => 0) // 0\n */\nexport function match<T, E, U>(result: Result<T, E>, onOk: (value: T) => U, onErr: (error: E) => U): U {\n return isOk(result) ? onOk(result) : onErr(result.error);\n}\n\n/**\n * Separates an array of Results into Ok values and Err values.\n * @param results - Array of Results\n * @returns Tuple of [Ok values, Err values]\n * @example\n * partition([ok(1), err('a'), ok(2)]) // [[1, 2], ['a']]\n */\nexport function partition<T, E>(results: Result<T, E>[]): [T[], E[]] {\n const oks: T[] = [];\n const errs: E[] = [];\n\n for (const result of results) {\n if (isOk(result)) {\n oks.push(result);\n } else {\n errs.push(result.error);\n }\n }\n\n return [oks, errs];\n}\n\n/**\n * Collects an array of Results into a Result of an array. Fails on first Err.\n * @param results - Array of Results\n * @returns Ok(values) if all Ok, first Err otherwise\n * @example\n * collect([ok(1), ok(2)]) // Ok([1, 2])\n * collect([ok(1), err('e')]) // Err('e')\n */\nexport function collect<T, E>(results: Result<T, E>[]): Result<T[], E> {\n const values: T[] = [];\n\n for (const result of results) {\n if (isErr(result)) {\n return result as Err<E>;\n }\n values.push(result as Ok<T>);\n }\n\n return values as Ok<T[]>;\n}\n\n/**\n * Collects all Results, returning all errors if any exist.\n * @param results - Array of Results\n * @returns Ok(values) if all Ok, Err(allErrors) otherwise\n * @example\n * collectAll([ok(1), ok(2)]) // Ok([1, 2])\n * collectAll([ok(1), err('a'), err('b')]) // Err(['a', 'b'])\n */\nexport function collectAll<T, E>(results: Result<T, E>[]): Result<T[], E[]> {\n const [oks, errs] = partition(results);\n return errs.length > 0 ? ERR(errs) : (oks as Ok<T[]>);\n}\n\n/**\n * Alias for collect with widened types. Collects Results into a Result of array.\n * @param results - Array of Results\n * @returns Ok(values) if all Ok, first Err otherwise\n */\nexport function all<T, E>(results: Result<T, E>[]): Result<Widen<T>[], WidenNever<E>> {\n return collect(results) as Result<Widen<T>[], WidenNever<E>>;\n}\n\n/**\n * Returns the first Ok, or all errors if none succeed.\n * @param results - Array of Results\n * @returns First Ok found, or Err(allErrors) if all fail\n * @example\n * any([err('a'), ok(1), err('b')]) // Ok(1)\n * any([err('a'), err('b')]) // Err(['a', 'b'])\n */\nexport function any<T, E>(results: Result<T, E>[]): Result<Widen<T>, WidenNever<E>[]> {\n const len = results.length;\n const errors = new Array<WidenNever<E>>(len);\n for (let i = 0; i < len; i++) {\n const result = results[i];\n if (isOk(result)) return result as Ok<Widen<T>>;\n errors[i] = (result as Err<WidenNever<E>>).error;\n }\n return ERR(errors);\n}\n\n/**\n * Transposes a Result of Option to an Option of Result.\n * @param result - Result containing an Option\n * @returns Some(Ok(value)) if Ok(Some), None if Ok(None), Some(Err) if Err\n * @example\n * transpose(ok(some(42))) // Some(Ok(42))\n * transpose(ok(none)) // None\n * transpose(err('e')) // Some(Err('e'))\n */\nexport function transpose<T, E>(result: Result<Option<T>, E>): Option<Result<T, E>> {\n if (isErr(result)) {\n return ERR((result as Err<E>).error) as Option<Result<T, E>>;\n }\n const opt = result as Option<T>;\n return isNone(opt) ? NONE : (opt as unknown as Ok<T> as Option<Result<T, E>>);\n}\n\n/**\n * Checks if Ok and the value satisfies a predicate.\n * @param result - The Result to check\n * @param predicate - Test function\n * @returns true if Ok and predicate returns true\n * @example\n * isOkAnd(ok(4), x => x > 2) // true\n * isOkAnd(ok(1), x => x > 2) // false\n * isOkAnd(err('e'), x => x > 2) // false\n */\nexport function isOkAnd<T, E>(result: Result<T, E>, predicate: (value: T) => boolean): boolean {\n return isOk(result) && predicate(result);\n}\n\n/**\n * Checks if Err and the error satisfies a predicate.\n * @param result - The Result to check\n * @param predicate - Test function\n * @returns true if Err and predicate returns true\n * @example\n * isErrAnd(err('fatal'), e => e.includes('fatal')) // true\n * isErrAnd(ok(42), e => true) // false\n */\nexport function isErrAnd<T, E>(result: Result<T, E>, predicate: (error: E) => boolean): boolean {\n return isErr(result) && predicate((result as Err<E>).error);\n}\n\n/**\n * Maps an async function over an Ok value.\n * @param result - The Result to map\n * @param fn - Async transform function\n * @param onRejected - Optional rejection handler\n * @returns Promise of mapped Result\n * @example\n * await mapAsync(ok(2), async x => x * 2) // Ok(4)\n */\nexport async function mapAsync<T, U, E = unknown>(\n result: Result<T, E>,\n fn: (value: T) => Promise<U>,\n onRejected?: (error: unknown) => E,\n): Promise<Result<U, E>> {\n if (isErr(result)) return result as Err<E>;\n return fromPromise(fn(result as Ok<T>), onRejected);\n}\n\n/**\n * Chains an async Result-returning function.\n * @param result - The Result to chain\n * @param fn - Async function returning a Result\n * @returns Promise of the chained Result\n * @example\n * await andThenAsync(ok(2), async x => ok(x * 2)) // Ok(4)\n */\nexport async function andThenAsync<T, U, E>(result: Result<T, E>, fn: (value: T) => Promise<Result<U, E>>): Promise<Result<U, E>> {\n if (isErr(result)) return result as Err<E>;\n return fn(result as Ok<T>);\n}\n\n/**\n * Pattern matches with async handlers.\n * @param result - The Result to match\n * @param onOk - Async handler for Ok\n * @param onErr - Async handler for Err\n * @returns Promise of the handler result\n */\nexport async function matchAsync<T, E, U>(result: Result<T, E>, onOk: (value: T) => Promise<U>, onErr: (error: E) => Promise<U>): Promise<U> {\n return isOk(result) ? onOk(result) : onErr(result.error);\n}\n\n/**\n * Partitions an async iterable of Results.\n * @param results - Iterable of Promise Results\n * @returns Promise of [Ok values, Err values]\n * @example\n * await partitionAsync([Promise.resolve(ok(1)), Promise.resolve(err('a'))])\n * // [[1], ['a']]\n */\nexport async function partitionAsync<T, E>(results: Iterable<Promise<Result<T, E>>>): Promise<[Widen<T>[], WidenNever<E>[]]> {\n const oks: Widen<T>[] = [];\n const errs: WidenNever<E>[] = [];\n\n for (const promise of results) {\n const result = await promise;\n if (isOk(result)) {\n oks.push(result as Ok<Widen<T>>);\n } else {\n errs.push((result as Err<WidenNever<E>>).error);\n }\n }\n\n return [oks, errs];\n}\n"],"names":["err","ERR","isOk","isErr","isSome","isNone","NONE","optionOf","tryCatch","fn","onError","error","of","tryAsync","ofAsync","fromPromise","promise","onRejected","unwrapOrReturn","result","onErr","assertOk","message","Error","String","assertErr","isSomeErr","map","mapErr","flatMap","andThen","tap","tapErr","bimap","okFn","errFn","unwrap","unwrapErr","unwrapOr","defaultValue","unwrapOrElse","mapOr","mapOrElse","defaultFn","expect","expectErr","and","other","or","orElse","toOption","toErrorOption","zip","left","right","zipWith","flatten","match","onOk","partition","results","oks","errs","push","collect","values","collectAll","length","all","any","len","errors","Array","i","transpose","opt","isOkAnd","predicate","isErrAnd","mapAsync","andThenAsync","matchAsync","partitionAsync"],"mappings":"AAAA,SAASA,OAAOC,GAAG,EAAEC,IAAI,EAAEC,KAAK,EAAEC,MAAM,EAAEC,MAAM,EAAEC,IAAI,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AAI,CAAC5C;QACX,OAAO;YACL2C,KAAKC,IAAI,CAAC,AAAC5C,OAA8BR,KAAK;QAChD;IACF;IAEA,OAAO;QAACkD;QAAKC;KAAK;AACpB"}
|
package/build/safe.cjs
ADDED
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", {
|
|
3
|
+
value: true
|
|
4
|
+
});
|
|
5
|
+
function _export(target, all) {
|
|
6
|
+
for(var name in all)Object.defineProperty(target, name, {
|
|
7
|
+
enumerable: true,
|
|
8
|
+
get: Object.getOwnPropertyDescriptor(all, name).get
|
|
9
|
+
});
|
|
10
|
+
}
|
|
11
|
+
_export(exports, {
|
|
12
|
+
get Option () {
|
|
13
|
+
return _optioncjs;
|
|
14
|
+
},
|
|
15
|
+
get Result () {
|
|
16
|
+
return _resultcjs;
|
|
17
|
+
},
|
|
18
|
+
get err () {
|
|
19
|
+
return _typescjs.err;
|
|
20
|
+
},
|
|
21
|
+
get none () {
|
|
22
|
+
return _typescjs.none;
|
|
23
|
+
},
|
|
24
|
+
get ok () {
|
|
25
|
+
return ok;
|
|
26
|
+
},
|
|
27
|
+
get some () {
|
|
28
|
+
return some;
|
|
29
|
+
}
|
|
30
|
+
});
|
|
31
|
+
const _typescjs = require("./types.cjs");
|
|
32
|
+
const _optioncjs = /*#__PURE__*/ _interop_require_wildcard(require("./option.cjs"));
|
|
33
|
+
const _resultcjs = /*#__PURE__*/ _interop_require_wildcard(require("./result.cjs"));
|
|
34
|
+
function _getRequireWildcardCache(nodeInterop) {
|
|
35
|
+
if (typeof WeakMap !== "function") return null;
|
|
36
|
+
var cacheBabelInterop = new WeakMap();
|
|
37
|
+
var cacheNodeInterop = new WeakMap();
|
|
38
|
+
return (_getRequireWildcardCache = function(nodeInterop) {
|
|
39
|
+
return nodeInterop ? cacheNodeInterop : cacheBabelInterop;
|
|
40
|
+
})(nodeInterop);
|
|
41
|
+
}
|
|
42
|
+
function _interop_require_wildcard(obj, nodeInterop) {
|
|
43
|
+
if (!nodeInterop && obj && obj.__esModule) {
|
|
44
|
+
return obj;
|
|
45
|
+
}
|
|
46
|
+
if (obj === null || typeof obj !== "object" && typeof obj !== "function") {
|
|
47
|
+
return {
|
|
48
|
+
default: obj
|
|
49
|
+
};
|
|
50
|
+
}
|
|
51
|
+
var cache = _getRequireWildcardCache(nodeInterop);
|
|
52
|
+
if (cache && cache.has(obj)) {
|
|
53
|
+
return cache.get(obj);
|
|
54
|
+
}
|
|
55
|
+
var newObj = {
|
|
56
|
+
__proto__: null
|
|
57
|
+
};
|
|
58
|
+
var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor;
|
|
59
|
+
for(var key in obj){
|
|
60
|
+
if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) {
|
|
61
|
+
var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null;
|
|
62
|
+
if (desc && (desc.get || desc.set)) {
|
|
63
|
+
Object.defineProperty(newObj, key, desc);
|
|
64
|
+
} else {
|
|
65
|
+
newObj[key] = obj[key];
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
newObj.default = obj;
|
|
70
|
+
if (cache) {
|
|
71
|
+
cache.set(obj, newObj);
|
|
72
|
+
}
|
|
73
|
+
return newObj;
|
|
74
|
+
}
|
|
75
|
+
function some(value) {
|
|
76
|
+
if (value === null || value === undefined) {
|
|
77
|
+
throw new TypeError('some() requires a non-nullable value');
|
|
78
|
+
}
|
|
79
|
+
return (0, _typescjs.some)(value);
|
|
80
|
+
}
|
|
81
|
+
function ok(value) {
|
|
82
|
+
if ((0, _typescjs.isErr)(value)) {
|
|
83
|
+
throw new TypeError('ok() cannot wrap an Err value');
|
|
84
|
+
}
|
|
85
|
+
return (0, _typescjs.ok)(value);
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
//# sourceMappingURL=safe.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/safe.ts"],"sourcesContent":["import { some as someUnsafe, ok as okUnsafe, err, none, isErr } from './types.js';\nimport type {\n Some,\n None,\n Ok,\n Err,\n Option as OptionType,\n OptionValue,\n IsOption,\n InferSome,\n Result as ResultType,\n ResultValue,\n ResultErrorType,\n IsResult,\n InferErr,\n ValueType,\n} from './types.js';\n\nexport type { Some, None, Ok, Err, OptionType, OptionValue, IsOption, InferSome, ResultType, ResultValue, ResultErrorType, IsResult, InferErr };\n\nexport { none, err };\nexport * as Option from './option.js';\nexport * as Result from './result.js';\n\n/**\n * Creates a Some value with runtime validation.\n * Throws if the value is null or undefined.\n * @param value - The value to wrap (must be non-nullable)\n * @returns The value typed as Some\n * @throws {TypeError} If value is null or undefined\n * @example\n * some(42) // Some(42)\n * some(null) // throws TypeError\n * some(undefined) // throws TypeError\n */\nexport function some<T>(value: T): Some<ValueType<T>> {\n if (value === null || value === undefined) {\n throw new TypeError('some() requires a non-nullable value');\n }\n return someUnsafe(value as ValueType<T>);\n}\n\n/**\n * Creates an Ok value with runtime validation.\n * Throws if the value is an Err (prevents accidental double-wrapping).\n * @param value - The success value\n * @returns The value typed as Ok\n * @throws {TypeError} If value is an Err\n * @example\n * ok(42) // Ok(42)\n * ok(err('fail')) // throws TypeError\n */\nexport function ok<T>(value: T): Ok<T> {\n if (isErr(value)) {\n throw new TypeError('ok() cannot wrap an Err value');\n }\n return okUnsafe(value);\n}\n"],"names":["Option","Result","err","none","ok","some","value","undefined","TypeError","someUnsafe","isErr","okUnsafe"],"mappings":";;;;;;;;;;;QAqBYA;;;QACAC;;;QAFGC;eAAAA,aAAG;;QAATC;eAAAA,cAAI;;QAgCGC;eAAAA;;QAjBAC;eAAAA;;;0BAnCqD;mEAqB7C;mEACA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAajB,SAASA,KAAQC,KAAQ;IAC9B,IAAIA,UAAU,QAAQA,UAAUC,WAAW;QACzC,MAAM,IAAIC,UAAU;IACtB;IACA,OAAOC,IAAAA,cAAU,EAACH;AACpB;AAYO,SAASF,GAAME,KAAQ;IAC5B,IAAII,IAAAA,eAAK,EAACJ,QAAQ;QAChB,MAAM,IAAIE,UAAU;IACtB;IACA,OAAOG,IAAAA,YAAQ,EAACL;AAClB"}
|
package/build/safe.d.ts
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import { err, none } from './types.js';
|
|
2
|
+
import type { Some, None, Ok, Err, Option as OptionType, OptionValue, IsOption, InferSome, Result as ResultType, ResultValue, ResultErrorType, IsResult, InferErr, ValueType } from './types.js';
|
|
3
|
+
export type { Some, None, Ok, Err, OptionType, OptionValue, IsOption, InferSome, ResultType, ResultValue, ResultErrorType, IsResult, InferErr };
|
|
4
|
+
export { none, err };
|
|
5
|
+
export * as Option from './option.js';
|
|
6
|
+
export * as Result from './result.js';
|
|
7
|
+
/**
|
|
8
|
+
* Creates a Some value with runtime validation.
|
|
9
|
+
* Throws if the value is null or undefined.
|
|
10
|
+
* @param value - The value to wrap (must be non-nullable)
|
|
11
|
+
* @returns The value typed as Some
|
|
12
|
+
* @throws {TypeError} If value is null or undefined
|
|
13
|
+
* @example
|
|
14
|
+
* some(42) // Some(42)
|
|
15
|
+
* some(null) // throws TypeError
|
|
16
|
+
* some(undefined) // throws TypeError
|
|
17
|
+
*/
|
|
18
|
+
export declare function some<T>(value: T): Some<ValueType<T>>;
|
|
19
|
+
/**
|
|
20
|
+
* Creates an Ok value with runtime validation.
|
|
21
|
+
* Throws if the value is an Err (prevents accidental double-wrapping).
|
|
22
|
+
* @param value - The success value
|
|
23
|
+
* @returns The value typed as Ok
|
|
24
|
+
* @throws {TypeError} If value is an Err
|
|
25
|
+
* @example
|
|
26
|
+
* ok(42) // Ok(42)
|
|
27
|
+
* ok(err('fail')) // throws TypeError
|
|
28
|
+
*/
|
|
29
|
+
export declare function ok<T>(value: T): Ok<T>;
|
package/build/safe.js
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import { some as someUnsafe, ok as okUnsafe, err, none, isErr } from "./types.js";
|
|
2
|
+
export { none, err };
|
|
3
|
+
export * as Option from "./option.js";
|
|
4
|
+
export * as Result from "./result.js";
|
|
5
|
+
export function some(value) {
|
|
6
|
+
if (value === null || value === undefined) {
|
|
7
|
+
throw new TypeError('some() requires a non-nullable value');
|
|
8
|
+
}
|
|
9
|
+
return someUnsafe(value);
|
|
10
|
+
}
|
|
11
|
+
export function ok(value) {
|
|
12
|
+
if (isErr(value)) {
|
|
13
|
+
throw new TypeError('ok() cannot wrap an Err value');
|
|
14
|
+
}
|
|
15
|
+
return okUnsafe(value);
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
//# sourceMappingURL=safe.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/safe.ts"],"sourcesContent":["import { some as someUnsafe, ok as okUnsafe, err, none, isErr } from './types.js';\nimport type {\n Some,\n None,\n Ok,\n Err,\n Option as OptionType,\n OptionValue,\n IsOption,\n InferSome,\n Result as ResultType,\n ResultValue,\n ResultErrorType,\n IsResult,\n InferErr,\n ValueType,\n} from './types.js';\n\nexport type { Some, None, Ok, Err, OptionType, OptionValue, IsOption, InferSome, ResultType, ResultValue, ResultErrorType, IsResult, InferErr };\n\nexport { none, err };\nexport * as Option from './option.js';\nexport * as Result from './result.js';\n\n/**\n * Creates a Some value with runtime validation.\n * Throws if the value is null or undefined.\n * @param value - The value to wrap (must be non-nullable)\n * @returns The value typed as Some\n * @throws {TypeError} If value is null or undefined\n * @example\n * some(42) // Some(42)\n * some(null) // throws TypeError\n * some(undefined) // throws TypeError\n */\nexport function some<T>(value: T): Some<ValueType<T>> {\n if (value === null || value === undefined) {\n throw new TypeError('some() requires a non-nullable value');\n }\n return someUnsafe(value as ValueType<T>);\n}\n\n/**\n * Creates an Ok value with runtime validation.\n * Throws if the value is an Err (prevents accidental double-wrapping).\n * @param value - The success value\n * @returns The value typed as Ok\n * @throws {TypeError} If value is an Err\n * @example\n * ok(42) // Ok(42)\n * ok(err('fail')) // throws TypeError\n */\nexport function ok<T>(value: T): Ok<T> {\n if (isErr(value)) {\n throw new TypeError('ok() cannot wrap an Err value');\n }\n return okUnsafe(value);\n}\n"],"names":["some","someUnsafe","ok","okUnsafe","err","none","isErr","Option","Result","value","undefined","TypeError"],"mappings":"AAAA,SAASA,QAAQC,UAAU,EAAEC,MAAMC,QAAQ,EAAEC,GAAG,EAAEC,IAAI,EAAEC,KAAK,QAAQ,aAAa;AAoBlF,SAASD,IAAI,EAAED,GAAG,GAAG;AACrB,OAAO,KAAKG,MAAM,MAAM,cAAc;AACtC,OAAO,KAAKC,MAAM,MAAM,cAAc;AAatC,OAAO,SAASR,KAAQS,KAAQ;IAC9B,IAAIA,UAAU,QAAQA,UAAUC,WAAW;QACzC,MAAM,IAAIC,UAAU;IACtB;IACA,OAAOV,WAAWQ;AACpB;AAYA,OAAO,SAASP,GAAMO,KAAQ;IAC5B,IAAIH,MAAMG,QAAQ;QAChB,MAAM,IAAIE,UAAU;IACtB;IACA,OAAOR,SAASM;AAClB"}
|
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", {
|
|
3
|
+
value: true
|
|
4
|
+
});
|
|
5
|
+
function _export(target, all) {
|
|
6
|
+
for(var name in all)Object.defineProperty(target, name, {
|
|
7
|
+
enumerable: true,
|
|
8
|
+
get: Object.getOwnPropertyDescriptor(all, name).get
|
|
9
|
+
});
|
|
10
|
+
}
|
|
11
|
+
_export(exports, {
|
|
12
|
+
get expectErr () {
|
|
13
|
+
return expectErr;
|
|
14
|
+
},
|
|
15
|
+
get expectNone () {
|
|
16
|
+
return expectNone;
|
|
17
|
+
},
|
|
18
|
+
get expectOk () {
|
|
19
|
+
return expectOk;
|
|
20
|
+
},
|
|
21
|
+
get expectSome () {
|
|
22
|
+
return expectSome;
|
|
23
|
+
},
|
|
24
|
+
get extendExpect () {
|
|
25
|
+
return extendExpect;
|
|
26
|
+
},
|
|
27
|
+
get matchers () {
|
|
28
|
+
return matchers;
|
|
29
|
+
}
|
|
30
|
+
});
|
|
31
|
+
const _typescjs = require("./types.cjs");
|
|
32
|
+
const _devtoolscjs = require("./devtools.cjs");
|
|
33
|
+
function expectOk(result, message) {
|
|
34
|
+
if ((0, _typescjs.isOk)(result)) {
|
|
35
|
+
return result;
|
|
36
|
+
}
|
|
37
|
+
const fallback = message ?? `Expected Ok(...) but received ${(0, _devtoolscjs.formatResult)(result)}`;
|
|
38
|
+
throw new Error(fallback);
|
|
39
|
+
}
|
|
40
|
+
function expectErr(result, message) {
|
|
41
|
+
if ((0, _typescjs.isErr)(result)) {
|
|
42
|
+
return result.error;
|
|
43
|
+
}
|
|
44
|
+
const fallback = message ?? `Expected Err(...) but received ${(0, _devtoolscjs.formatResult)(result)}`;
|
|
45
|
+
throw new Error(fallback);
|
|
46
|
+
}
|
|
47
|
+
function expectSome(opt, message) {
|
|
48
|
+
if ((0, _typescjs.isSome)(opt)) {
|
|
49
|
+
return opt;
|
|
50
|
+
}
|
|
51
|
+
const fallback = message ?? `Expected Some(...) but received ${(0, _devtoolscjs.formatOption)(opt)}`;
|
|
52
|
+
throw new Error(fallback);
|
|
53
|
+
}
|
|
54
|
+
function expectNone(opt, message) {
|
|
55
|
+
if ((0, _typescjs.isNone)(opt)) {
|
|
56
|
+
return;
|
|
57
|
+
}
|
|
58
|
+
const fallback = message ?? `Expected None but received ${(0, _devtoolscjs.formatOption)(opt)}`;
|
|
59
|
+
throw new Error(fallback);
|
|
60
|
+
}
|
|
61
|
+
const resultMatchers = {
|
|
62
|
+
toBeOk (received) {
|
|
63
|
+
const pass = (0, _typescjs.isOk)(received);
|
|
64
|
+
return {
|
|
65
|
+
pass,
|
|
66
|
+
message: ()=>pass ? 'Result is Ok as expected.' : `Expected Ok(...) but received ${(0, _devtoolscjs.formatResult)(received)}`
|
|
67
|
+
};
|
|
68
|
+
},
|
|
69
|
+
toBeErr (received) {
|
|
70
|
+
const pass = (0, _typescjs.isErr)(received);
|
|
71
|
+
return {
|
|
72
|
+
pass,
|
|
73
|
+
message: ()=>pass ? 'Result is Err as expected.' : `Expected Err(...) but received ${(0, _devtoolscjs.formatResult)(received)}`
|
|
74
|
+
};
|
|
75
|
+
},
|
|
76
|
+
toContainErr (received, expected) {
|
|
77
|
+
const pass = (0, _typescjs.isErr)(received) && received.error === expected;
|
|
78
|
+
return {
|
|
79
|
+
pass,
|
|
80
|
+
message: ()=>{
|
|
81
|
+
if (pass) return `Err matched expected value ${String(expected)}.`;
|
|
82
|
+
return `Expected Err(${String(expected)}) but received ${(0, _devtoolscjs.formatResult)(received)}`;
|
|
83
|
+
}
|
|
84
|
+
};
|
|
85
|
+
}
|
|
86
|
+
};
|
|
87
|
+
const optionMatchers = {
|
|
88
|
+
toBeSome (received) {
|
|
89
|
+
const pass = (0, _typescjs.isSome)(received);
|
|
90
|
+
return {
|
|
91
|
+
pass,
|
|
92
|
+
message: ()=>pass ? 'Option is Some as expected.' : `Expected Some(...) but received ${(0, _devtoolscjs.formatOption)(received)}`
|
|
93
|
+
};
|
|
94
|
+
},
|
|
95
|
+
toBeNone (received) {
|
|
96
|
+
const pass = (0, _typescjs.isNone)(received);
|
|
97
|
+
return {
|
|
98
|
+
pass,
|
|
99
|
+
message: ()=>pass ? 'Option is None as expected.' : `Expected None but received ${(0, _devtoolscjs.formatOption)(received)}`
|
|
100
|
+
};
|
|
101
|
+
}
|
|
102
|
+
};
|
|
103
|
+
const matchers = {
|
|
104
|
+
...resultMatchers,
|
|
105
|
+
...optionMatchers
|
|
106
|
+
};
|
|
107
|
+
function extendExpect(expectLike) {
|
|
108
|
+
expectLike.extend(matchers);
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
//# sourceMappingURL=testing.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/testing.ts"],"sourcesContent":["import { isOk, isErr, isSome, isNone, Result, Err, Option } from './types.js';\nimport { formatOption, formatResult } from './devtools.js';\n\n/** Result shape returned by custom matchers. */\ntype MatcherResult = { pass: boolean; message(): string };\n\n/**\n * Asserts that a Result is Ok and returns the value.\n * Throws if the Result is Err.\n * @param result - The Result to check\n * @param message - Optional custom error message\n * @returns The Ok value\n * @throws {Error} If the Result is Err\n * @example\n * expectOk(ok(42)) // returns 42\n * expectOk(err('fail')) // throws Error\n */\nexport function expectOk<T, E>(result: Result<T, E>, message?: string): T {\n if (isOk(result)) {\n return result;\n }\n\n const fallback = message ?? `Expected Ok(...) but received ${formatResult(result)}`;\n throw new Error(fallback);\n}\n\n/**\n * Asserts that a Result is Err and returns the error.\n * Throws if the Result is Ok.\n * @param result - The Result to check\n * @param message - Optional custom error message\n * @returns The error value\n * @throws {Error} If the Result is Ok\n * @example\n * expectErr(err('fail')) // returns 'fail'\n * expectErr(ok(42)) // throws Error\n */\nexport function expectErr<T, E>(result: Result<T, E>, message?: string): E {\n if (isErr(result)) {\n return (result as Err<E>).error;\n }\n\n const fallback = message ?? `Expected Err(...) but received ${formatResult(result)}`;\n throw new Error(fallback);\n}\n\n/**\n * Asserts that an Option is Some and returns the value.\n * Throws if the Option is None.\n * @param opt - The Option to check\n * @param message - Optional custom error message\n * @returns The Some value\n * @throws {Error} If the Option is None\n * @example\n * expectSome(42) // returns 42\n * expectSome(null) // throws Error\n */\nexport function expectSome<T>(opt: Option<T>, message?: string): T {\n if (isSome(opt)) {\n return opt;\n }\n const fallback = message ?? `Expected Some(...) but received ${formatOption(opt)}`;\n throw new Error(fallback);\n}\n\n/**\n * Asserts that an Option is None.\n * Throws if the Option is Some.\n * @param opt - The Option to check\n * @param message - Optional custom error message\n * @throws {Error} If the Option is Some\n * @example\n * expectNone(null) // succeeds\n * expectNone(42) // throws Error\n */\nexport function expectNone<T>(opt: Option<T>, message?: string): void {\n if (isNone(opt)) {\n return;\n }\n const fallback = message ?? `Expected None but received ${formatOption(opt)}`;\n throw new Error(fallback);\n}\n\nconst resultMatchers = {\n toBeOk(this: unknown, received: Result<unknown, unknown>): MatcherResult {\n const pass = isOk(received);\n return {\n pass,\n message: () => (pass ? 'Result is Ok as expected.' : `Expected Ok(...) but received ${formatResult(received)}`),\n };\n },\n toBeErr(this: unknown, received: Result<unknown, unknown>): MatcherResult {\n const pass = isErr(received);\n return {\n pass,\n message: () => (pass ? 'Result is Err as expected.' : `Expected Err(...) but received ${formatResult(received)}`),\n };\n },\n toContainErr(this: unknown, received: Result<unknown, unknown>, expected: unknown): MatcherResult {\n const pass = isErr(received) && (received as Err<unknown>).error === expected;\n return {\n pass,\n message: () => {\n if (pass) return `Err matched expected value ${String(expected)}.`;\n return `Expected Err(${String(expected)}) but received ${formatResult(received)}`;\n },\n };\n },\n};\n\nconst optionMatchers = {\n toBeSome(this: unknown, received: Option<unknown>): MatcherResult {\n const pass = isSome(received);\n return {\n pass,\n message: () => (pass ? 'Option is Some as expected.' : `Expected Some(...) but received ${formatOption(received)}`),\n };\n },\n toBeNone(this: unknown, received: Option<unknown>): MatcherResult {\n const pass = isNone(received);\n return {\n pass,\n message: () => (pass ? 'Option is None as expected.' : `Expected None but received ${formatOption(received)}`),\n };\n },\n};\n\n/**\n * Custom matchers for Jest/Vitest.\n * Includes toBeOk, toBeErr, toContainErr, toBeSome, toBeNone.\n * Use with expect.extend(matchers) or extendExpect(expect).\n */\nexport const matchers = {\n ...resultMatchers,\n ...optionMatchers,\n};\n\n/** Interface for test frameworks with an extend method (Jest, Vitest). */\nexport type ExpectLike = {\n extend(matchers: Record<string, (...args: any[]) => MatcherResult>): void;\n};\n\n/**\n * Extends a test framework's expect with Option and Result matchers.\n * @param expectLike - The expect object to extend (Jest/Vitest)\n * @example\n * import { expect } from 'vitest';\n * import { extendExpect } from 'nalloc/testing';\n * extendExpect(expect);\n *\n * // Now you can use:\n * expect(result).toBeOk();\n * expect(result).toBeErr();\n * expect(option).toBeSome();\n * expect(option).toBeNone();\n */\nexport function extendExpect(expectLike: ExpectLike): void {\n expectLike.extend(matchers);\n}\n"],"names":["expectErr","expectNone","expectOk","expectSome","extendExpect","matchers","result","message","isOk","fallback","formatResult","Error","isErr","error","opt","isSome","formatOption","isNone","resultMatchers","toBeOk","received","pass","toBeErr","toContainErr","expected","String","optionMatchers","toBeSome","toBeNone","expectLike","extend"],"mappings":";;;;;;;;;;;QAqCgBA;eAAAA;;QAsCAC;eAAAA;;QA1DAC;eAAAA;;QAwCAC;eAAAA;;QAmGAC;eAAAA;;QAxBHC;eAAAA;;;0BApIoD;6BACtB;AAgBpC,SAASH,SAAeI,MAAoB,EAAEC,OAAgB;IACnE,IAAIC,IAAAA,cAAI,EAACF,SAAS;QAChB,OAAOA;IACT;IAEA,MAAMG,WAAWF,WAAW,CAAC,8BAA8B,EAAEG,IAAAA,yBAAY,EAACJ,SAAS;IACnF,MAAM,IAAIK,MAAMF;AAClB;AAaO,SAAST,UAAgBM,MAAoB,EAAEC,OAAgB;IACpE,IAAIK,IAAAA,eAAK,EAACN,SAAS;QACjB,OAAO,AAACA,OAAkBO,KAAK;IACjC;IAEA,MAAMJ,WAAWF,WAAW,CAAC,+BAA+B,EAAEG,IAAAA,yBAAY,EAACJ,SAAS;IACpF,MAAM,IAAIK,MAAMF;AAClB;AAaO,SAASN,WAAcW,GAAc,EAAEP,OAAgB;IAC5D,IAAIQ,IAAAA,gBAAM,EAACD,MAAM;QACf,OAAOA;IACT;IACA,MAAML,WAAWF,WAAW,CAAC,gCAAgC,EAAES,IAAAA,yBAAY,EAACF,MAAM;IAClF,MAAM,IAAIH,MAAMF;AAClB;AAYO,SAASR,WAAca,GAAc,EAAEP,OAAgB;IAC5D,IAAIU,IAAAA,gBAAM,EAACH,MAAM;QACf;IACF;IACA,MAAML,WAAWF,WAAW,CAAC,2BAA2B,EAAES,IAAAA,yBAAY,EAACF,MAAM;IAC7E,MAAM,IAAIH,MAAMF;AAClB;AAEA,MAAMS,iBAAiB;IACrBC,QAAsBC,QAAkC;QACtD,MAAMC,OAAOb,IAAAA,cAAI,EAACY;QAClB,OAAO;YACLC;YACAd,SAAS,IAAOc,OAAO,8BAA8B,CAAC,8BAA8B,EAAEX,IAAAA,yBAAY,EAACU,WAAW;QAChH;IACF;IACAE,SAAuBF,QAAkC;QACvD,MAAMC,OAAOT,IAAAA,eAAK,EAACQ;QACnB,OAAO;YACLC;YACAd,SAAS,IAAOc,OAAO,+BAA+B,CAAC,+BAA+B,EAAEX,IAAAA,yBAAY,EAACU,WAAW;QAClH;IACF;IACAG,cAA4BH,QAAkC,EAAEI,QAAiB;QAC/E,MAAMH,OAAOT,IAAAA,eAAK,EAACQ,aAAa,AAACA,SAA0BP,KAAK,KAAKW;QACrE,OAAO;YACLH;YACAd,SAAS;gBACP,IAAIc,MAAM,OAAO,CAAC,2BAA2B,EAAEI,OAAOD,UAAU,CAAC,CAAC;gBAClE,OAAO,CAAC,aAAa,EAAEC,OAAOD,UAAU,eAAe,EAAEd,IAAAA,yBAAY,EAACU,WAAW;YACnF;QACF;IACF;AACF;AAEA,MAAMM,iBAAiB;IACrBC,UAAwBP,QAAyB;QAC/C,MAAMC,OAAON,IAAAA,gBAAM,EAACK;QACpB,OAAO;YACLC;YACAd,SAAS,IAAOc,OAAO,gCAAgC,CAAC,gCAAgC,EAAEL,IAAAA,yBAAY,EAACI,WAAW;QACpH;IACF;IACAQ,UAAwBR,QAAyB;QAC/C,MAAMC,OAAOJ,IAAAA,gBAAM,EAACG;QACpB,OAAO;YACLC;YACAd,SAAS,IAAOc,OAAO,gCAAgC,CAAC,2BAA2B,EAAEL,IAAAA,yBAAY,EAACI,WAAW;QAC/G;IACF;AACF;AAOO,MAAMf,WAAW;IACtB,GAAGa,cAAc;IACjB,GAAGQ,cAAc;AACnB;AAqBO,SAAStB,aAAayB,UAAsB;IACjDA,WAAWC,MAAM,CAACzB;AACpB"}
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
import { Result, Option } from './types.js';
|
|
2
|
+
/** Result shape returned by custom matchers. */
|
|
3
|
+
type MatcherResult = {
|
|
4
|
+
pass: boolean;
|
|
5
|
+
message(): string;
|
|
6
|
+
};
|
|
7
|
+
/**
|
|
8
|
+
* Asserts that a Result is Ok and returns the value.
|
|
9
|
+
* Throws if the Result is Err.
|
|
10
|
+
* @param result - The Result to check
|
|
11
|
+
* @param message - Optional custom error message
|
|
12
|
+
* @returns The Ok value
|
|
13
|
+
* @throws {Error} If the Result is Err
|
|
14
|
+
* @example
|
|
15
|
+
* expectOk(ok(42)) // returns 42
|
|
16
|
+
* expectOk(err('fail')) // throws Error
|
|
17
|
+
*/
|
|
18
|
+
export declare function expectOk<T, E>(result: Result<T, E>, message?: string): T;
|
|
19
|
+
/**
|
|
20
|
+
* Asserts that a Result is Err and returns the error.
|
|
21
|
+
* Throws if the Result is Ok.
|
|
22
|
+
* @param result - The Result to check
|
|
23
|
+
* @param message - Optional custom error message
|
|
24
|
+
* @returns The error value
|
|
25
|
+
* @throws {Error} If the Result is Ok
|
|
26
|
+
* @example
|
|
27
|
+
* expectErr(err('fail')) // returns 'fail'
|
|
28
|
+
* expectErr(ok(42)) // throws Error
|
|
29
|
+
*/
|
|
30
|
+
export declare function expectErr<T, E>(result: Result<T, E>, message?: string): E;
|
|
31
|
+
/**
|
|
32
|
+
* Asserts that an Option is Some and returns the value.
|
|
33
|
+
* Throws if the Option is None.
|
|
34
|
+
* @param opt - The Option to check
|
|
35
|
+
* @param message - Optional custom error message
|
|
36
|
+
* @returns The Some value
|
|
37
|
+
* @throws {Error} If the Option is None
|
|
38
|
+
* @example
|
|
39
|
+
* expectSome(42) // returns 42
|
|
40
|
+
* expectSome(null) // throws Error
|
|
41
|
+
*/
|
|
42
|
+
export declare function expectSome<T>(opt: Option<T>, message?: string): T;
|
|
43
|
+
/**
|
|
44
|
+
* Asserts that an Option is None.
|
|
45
|
+
* Throws if the Option is Some.
|
|
46
|
+
* @param opt - The Option to check
|
|
47
|
+
* @param message - Optional custom error message
|
|
48
|
+
* @throws {Error} If the Option is Some
|
|
49
|
+
* @example
|
|
50
|
+
* expectNone(null) // succeeds
|
|
51
|
+
* expectNone(42) // throws Error
|
|
52
|
+
*/
|
|
53
|
+
export declare function expectNone<T>(opt: Option<T>, message?: string): void;
|
|
54
|
+
/**
|
|
55
|
+
* Custom matchers for Jest/Vitest.
|
|
56
|
+
* Includes toBeOk, toBeErr, toContainErr, toBeSome, toBeNone.
|
|
57
|
+
* Use with expect.extend(matchers) or extendExpect(expect).
|
|
58
|
+
*/
|
|
59
|
+
export declare const matchers: {
|
|
60
|
+
toBeSome(this: unknown, received: Option<unknown>): MatcherResult;
|
|
61
|
+
toBeNone(this: unknown, received: Option<unknown>): MatcherResult;
|
|
62
|
+
toBeOk(this: unknown, received: Result<unknown, unknown>): MatcherResult;
|
|
63
|
+
toBeErr(this: unknown, received: Result<unknown, unknown>): MatcherResult;
|
|
64
|
+
toContainErr(this: unknown, received: Result<unknown, unknown>, expected: unknown): MatcherResult;
|
|
65
|
+
};
|
|
66
|
+
/** Interface for test frameworks with an extend method (Jest, Vitest). */
|
|
67
|
+
export type ExpectLike = {
|
|
68
|
+
extend(matchers: Record<string, (...args: any[]) => MatcherResult>): void;
|
|
69
|
+
};
|
|
70
|
+
/**
|
|
71
|
+
* Extends a test framework's expect with Option and Result matchers.
|
|
72
|
+
* @param expectLike - The expect object to extend (Jest/Vitest)
|
|
73
|
+
* @example
|
|
74
|
+
* import { expect } from 'vitest';
|
|
75
|
+
* import { extendExpect } from 'nalloc/testing';
|
|
76
|
+
* extendExpect(expect);
|
|
77
|
+
*
|
|
78
|
+
* // Now you can use:
|
|
79
|
+
* expect(result).toBeOk();
|
|
80
|
+
* expect(result).toBeErr();
|
|
81
|
+
* expect(option).toBeSome();
|
|
82
|
+
* expect(option).toBeNone();
|
|
83
|
+
*/
|
|
84
|
+
export declare function extendExpect(expectLike: ExpectLike): void;
|
|
85
|
+
export {};
|
package/build/testing.js
ADDED
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
import { isOk, isErr, isSome, isNone } from "./types.js";
|
|
2
|
+
import { formatOption, formatResult } from "./devtools.js";
|
|
3
|
+
export function expectOk(result, message) {
|
|
4
|
+
if (isOk(result)) {
|
|
5
|
+
return result;
|
|
6
|
+
}
|
|
7
|
+
const fallback = message ?? `Expected Ok(...) but received ${formatResult(result)}`;
|
|
8
|
+
throw new Error(fallback);
|
|
9
|
+
}
|
|
10
|
+
export function expectErr(result, message) {
|
|
11
|
+
if (isErr(result)) {
|
|
12
|
+
return result.error;
|
|
13
|
+
}
|
|
14
|
+
const fallback = message ?? `Expected Err(...) but received ${formatResult(result)}`;
|
|
15
|
+
throw new Error(fallback);
|
|
16
|
+
}
|
|
17
|
+
export function expectSome(opt, message) {
|
|
18
|
+
if (isSome(opt)) {
|
|
19
|
+
return opt;
|
|
20
|
+
}
|
|
21
|
+
const fallback = message ?? `Expected Some(...) but received ${formatOption(opt)}`;
|
|
22
|
+
throw new Error(fallback);
|
|
23
|
+
}
|
|
24
|
+
export function expectNone(opt, message) {
|
|
25
|
+
if (isNone(opt)) {
|
|
26
|
+
return;
|
|
27
|
+
}
|
|
28
|
+
const fallback = message ?? `Expected None but received ${formatOption(opt)}`;
|
|
29
|
+
throw new Error(fallback);
|
|
30
|
+
}
|
|
31
|
+
const resultMatchers = {
|
|
32
|
+
toBeOk (received) {
|
|
33
|
+
const pass = isOk(received);
|
|
34
|
+
return {
|
|
35
|
+
pass,
|
|
36
|
+
message: ()=>pass ? 'Result is Ok as expected.' : `Expected Ok(...) but received ${formatResult(received)}`
|
|
37
|
+
};
|
|
38
|
+
},
|
|
39
|
+
toBeErr (received) {
|
|
40
|
+
const pass = isErr(received);
|
|
41
|
+
return {
|
|
42
|
+
pass,
|
|
43
|
+
message: ()=>pass ? 'Result is Err as expected.' : `Expected Err(...) but received ${formatResult(received)}`
|
|
44
|
+
};
|
|
45
|
+
},
|
|
46
|
+
toContainErr (received, expected) {
|
|
47
|
+
const pass = isErr(received) && received.error === expected;
|
|
48
|
+
return {
|
|
49
|
+
pass,
|
|
50
|
+
message: ()=>{
|
|
51
|
+
if (pass) return `Err matched expected value ${String(expected)}.`;
|
|
52
|
+
return `Expected Err(${String(expected)}) but received ${formatResult(received)}`;
|
|
53
|
+
}
|
|
54
|
+
};
|
|
55
|
+
}
|
|
56
|
+
};
|
|
57
|
+
const optionMatchers = {
|
|
58
|
+
toBeSome (received) {
|
|
59
|
+
const pass = isSome(received);
|
|
60
|
+
return {
|
|
61
|
+
pass,
|
|
62
|
+
message: ()=>pass ? 'Option is Some as expected.' : `Expected Some(...) but received ${formatOption(received)}`
|
|
63
|
+
};
|
|
64
|
+
},
|
|
65
|
+
toBeNone (received) {
|
|
66
|
+
const pass = isNone(received);
|
|
67
|
+
return {
|
|
68
|
+
pass,
|
|
69
|
+
message: ()=>pass ? 'Option is None as expected.' : `Expected None but received ${formatOption(received)}`
|
|
70
|
+
};
|
|
71
|
+
}
|
|
72
|
+
};
|
|
73
|
+
export const matchers = {
|
|
74
|
+
...resultMatchers,
|
|
75
|
+
...optionMatchers
|
|
76
|
+
};
|
|
77
|
+
export function extendExpect(expectLike) {
|
|
78
|
+
expectLike.extend(matchers);
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
//# sourceMappingURL=testing.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/testing.ts"],"sourcesContent":["import { isOk, isErr, isSome, isNone, Result, Err, Option } from './types.js';\nimport { formatOption, formatResult } from './devtools.js';\n\n/** Result shape returned by custom matchers. */\ntype MatcherResult = { pass: boolean; message(): string };\n\n/**\n * Asserts that a Result is Ok and returns the value.\n * Throws if the Result is Err.\n * @param result - The Result to check\n * @param message - Optional custom error message\n * @returns The Ok value\n * @throws {Error} If the Result is Err\n * @example\n * expectOk(ok(42)) // returns 42\n * expectOk(err('fail')) // throws Error\n */\nexport function expectOk<T, E>(result: Result<T, E>, message?: string): T {\n if (isOk(result)) {\n return result;\n }\n\n const fallback = message ?? `Expected Ok(...) but received ${formatResult(result)}`;\n throw new Error(fallback);\n}\n\n/**\n * Asserts that a Result is Err and returns the error.\n * Throws if the Result is Ok.\n * @param result - The Result to check\n * @param message - Optional custom error message\n * @returns The error value\n * @throws {Error} If the Result is Ok\n * @example\n * expectErr(err('fail')) // returns 'fail'\n * expectErr(ok(42)) // throws Error\n */\nexport function expectErr<T, E>(result: Result<T, E>, message?: string): E {\n if (isErr(result)) {\n return (result as Err<E>).error;\n }\n\n const fallback = message ?? `Expected Err(...) but received ${formatResult(result)}`;\n throw new Error(fallback);\n}\n\n/**\n * Asserts that an Option is Some and returns the value.\n * Throws if the Option is None.\n * @param opt - The Option to check\n * @param message - Optional custom error message\n * @returns The Some value\n * @throws {Error} If the Option is None\n * @example\n * expectSome(42) // returns 42\n * expectSome(null) // throws Error\n */\nexport function expectSome<T>(opt: Option<T>, message?: string): T {\n if (isSome(opt)) {\n return opt;\n }\n const fallback = message ?? `Expected Some(...) but received ${formatOption(opt)}`;\n throw new Error(fallback);\n}\n\n/**\n * Asserts that an Option is None.\n * Throws if the Option is Some.\n * @param opt - The Option to check\n * @param message - Optional custom error message\n * @throws {Error} If the Option is Some\n * @example\n * expectNone(null) // succeeds\n * expectNone(42) // throws Error\n */\nexport function expectNone<T>(opt: Option<T>, message?: string): void {\n if (isNone(opt)) {\n return;\n }\n const fallback = message ?? `Expected None but received ${formatOption(opt)}`;\n throw new Error(fallback);\n}\n\nconst resultMatchers = {\n toBeOk(this: unknown, received: Result<unknown, unknown>): MatcherResult {\n const pass = isOk(received);\n return {\n pass,\n message: () => (pass ? 'Result is Ok as expected.' : `Expected Ok(...) but received ${formatResult(received)}`),\n };\n },\n toBeErr(this: unknown, received: Result<unknown, unknown>): MatcherResult {\n const pass = isErr(received);\n return {\n pass,\n message: () => (pass ? 'Result is Err as expected.' : `Expected Err(...) but received ${formatResult(received)}`),\n };\n },\n toContainErr(this: unknown, received: Result<unknown, unknown>, expected: unknown): MatcherResult {\n const pass = isErr(received) && (received as Err<unknown>).error === expected;\n return {\n pass,\n message: () => {\n if (pass) return `Err matched expected value ${String(expected)}.`;\n return `Expected Err(${String(expected)}) but received ${formatResult(received)}`;\n },\n };\n },\n};\n\nconst optionMatchers = {\n toBeSome(this: unknown, received: Option<unknown>): MatcherResult {\n const pass = isSome(received);\n return {\n pass,\n message: () => (pass ? 'Option is Some as expected.' : `Expected Some(...) but received ${formatOption(received)}`),\n };\n },\n toBeNone(this: unknown, received: Option<unknown>): MatcherResult {\n const pass = isNone(received);\n return {\n pass,\n message: () => (pass ? 'Option is None as expected.' : `Expected None but received ${formatOption(received)}`),\n };\n },\n};\n\n/**\n * Custom matchers for Jest/Vitest.\n * Includes toBeOk, toBeErr, toContainErr, toBeSome, toBeNone.\n * Use with expect.extend(matchers) or extendExpect(expect).\n */\nexport const matchers = {\n ...resultMatchers,\n ...optionMatchers,\n};\n\n/** Interface for test frameworks with an extend method (Jest, Vitest). */\nexport type ExpectLike = {\n extend(matchers: Record<string, (...args: any[]) => MatcherResult>): void;\n};\n\n/**\n * Extends a test framework's expect with Option and Result matchers.\n * @param expectLike - The expect object to extend (Jest/Vitest)\n * @example\n * import { expect } from 'vitest';\n * import { extendExpect } from 'nalloc/testing';\n * extendExpect(expect);\n *\n * // Now you can use:\n * expect(result).toBeOk();\n * expect(result).toBeErr();\n * expect(option).toBeSome();\n * expect(option).toBeNone();\n */\nexport function extendExpect(expectLike: ExpectLike): void {\n expectLike.extend(matchers);\n}\n"],"names":["isOk","isErr","isSome","isNone","formatOption","formatResult","expectOk","result","message","fallback","Error","expectErr","error","expectSome","opt","expectNone","resultMatchers","toBeOk","received","pass","toBeErr","toContainErr","expected","String","optionMatchers","toBeSome","toBeNone","matchers","extendExpect","expectLike","extend"],"mappings":"AAAA,SAASA,IAAI,EAAEC,KAAK,EAAEC,MAAM,EAAEC,MAAM,QAA6B,aAAa;AAC9E,SAASC,YAAY,EAAEC,YAAY,QAAQ,gBAAgB;AAgB3D,OAAO,SAASC,SAAeC,MAAoB,EAAEC,OAAgB;IACnE,IAAIR,KAAKO,SAAS;QAChB,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OAAOD,UAAU,eAAe,EAAEjB,aAAaa,WAAW;YACnF;QACF;IACF;AACF;AAEA,MAAMM,iBAAiB;IACrBC,UAAwBP,QAAyB;QAC/C,MAAMC,OAAOjB,OAAOgB;QACpB,OAAO;YACLC;YACAX,SAAS,IAAOW,OAAO,gCAAgC,CAAC,gCAAgC,EAAEf,aAAac,WAAW;QACpH;IACF;IACAQ,UAAwBR,QAAyB;QAC/C,MAAMC,OAAOhB,OAAOe;QACpB,OAAO;YACLC;YACAX,SAAS,IAAOW,OAAO,gCAAgC,CAAC,2BAA2B,EAAEf,aAAac,WAAW;QAC/G;IACF;AACF;AAOA,OAAO,MAAMS,WAAW;IACtB,GAAGX,cAAc;IACjB,GAAGQ,cAAc;AACnB,EAAE;AAqBF,OAAO,SAASI,aAAaC,UAAsB;IACjDA,WAAWC,MAAM,CAACH;AACpB"}
|
package/build/types.cjs
ADDED
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", {
|
|
3
|
+
value: true
|
|
4
|
+
});
|
|
5
|
+
function _export(target, all) {
|
|
6
|
+
for(var name in all)Object.defineProperty(target, name, {
|
|
7
|
+
enumerable: true,
|
|
8
|
+
get: Object.getOwnPropertyDescriptor(all, name).get
|
|
9
|
+
});
|
|
10
|
+
}
|
|
11
|
+
_export(exports, {
|
|
12
|
+
get NONE () {
|
|
13
|
+
return NONE;
|
|
14
|
+
},
|
|
15
|
+
get err () {
|
|
16
|
+
return err;
|
|
17
|
+
},
|
|
18
|
+
get isErr () {
|
|
19
|
+
return isErr;
|
|
20
|
+
},
|
|
21
|
+
get isNone () {
|
|
22
|
+
return isNone;
|
|
23
|
+
},
|
|
24
|
+
get isOk () {
|
|
25
|
+
return isOk;
|
|
26
|
+
},
|
|
27
|
+
get isSome () {
|
|
28
|
+
return isSome;
|
|
29
|
+
},
|
|
30
|
+
get none () {
|
|
31
|
+
return none;
|
|
32
|
+
},
|
|
33
|
+
get ok () {
|
|
34
|
+
return ok;
|
|
35
|
+
},
|
|
36
|
+
get optionOf () {
|
|
37
|
+
return optionOf;
|
|
38
|
+
},
|
|
39
|
+
get some () {
|
|
40
|
+
return some;
|
|
41
|
+
}
|
|
42
|
+
});
|
|
43
|
+
const NONE = undefined;
|
|
44
|
+
function isSome(opt) {
|
|
45
|
+
return opt !== null && opt !== undefined;
|
|
46
|
+
}
|
|
47
|
+
function isNone(opt) {
|
|
48
|
+
return opt === null || opt === undefined;
|
|
49
|
+
}
|
|
50
|
+
function optionOf(value) {
|
|
51
|
+
return isNone(value) ? NONE : value;
|
|
52
|
+
}
|
|
53
|
+
function some(value) {
|
|
54
|
+
return value;
|
|
55
|
+
}
|
|
56
|
+
const none = NONE;
|
|
57
|
+
const ERR_BRAND = Symbol.for('nalloc.ResultError');
|
|
58
|
+
function ResultErrorCtor(error) {
|
|
59
|
+
this.error = error;
|
|
60
|
+
}
|
|
61
|
+
ResultErrorCtor.prototype[ERR_BRAND] = true;
|
|
62
|
+
function hasErrBrand(value) {
|
|
63
|
+
return value?.[ERR_BRAND] === true;
|
|
64
|
+
}
|
|
65
|
+
function isOk(result) {
|
|
66
|
+
return !hasErrBrand(result);
|
|
67
|
+
}
|
|
68
|
+
function isErr(result) {
|
|
69
|
+
return hasErrBrand(result);
|
|
70
|
+
}
|
|
71
|
+
function ok(value) {
|
|
72
|
+
return value;
|
|
73
|
+
}
|
|
74
|
+
function err(error) {
|
|
75
|
+
return new ResultErrorCtor(error);
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
//# sourceMappingURL=types.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/types.ts"],"sourcesContent":["/** Values that represent None (absence of a value). */\nexport type NoneValueType = null | undefined | void;\n\n/** Widens literal types to their base types for better type inference. */\nexport type Widen<T> = T extends string\n ? string\n : T extends number\n ? number\n : T extends boolean\n ? boolean\n : T extends bigint\n ? bigint\n : T extends symbol\n ? symbol\n : T;\n\n/** Widens never to unknown, otherwise preserves the type. */\nexport type WidenNever<T> = [T] extends [never] ? unknown : T;\n\n/** Excludes None values from a type, leaving only valid Some values. */\nexport type ValueType<T> = Exclude<T, NoneValueType>;\n\nexport declare const SOME_BRAND: unique symbol;\n\n/** Represents a value that is present. The value itself is the Some - no wrapper object. */\nexport type Some<T> = ValueType<T> & { readonly [SOME_BRAND]: true };\n\n/** Represents the absence of a value (null or undefined). */\nexport type None = NoneValueType & { readonly [SOME_BRAND]: false };\n\n/** Constant representing None. Use this instead of null/undefined for clarity. */\nexport const NONE = undefined as None;\n\n/** A value that may or may not be present. Some(T) is the value itself; None is null/undefined. */\nexport type Option<T> = Some<ValueType<T>> | None;\n\n/** Extracts the value type from an Option type. */\nexport type OptionValue<TOption> = TOption extends Option<infer TValue> ? TValue : never;\n\n/** Type predicate: true if T is an Option type. */\nexport type IsOption<T> = T extends Option<any> ? true : false;\n\n/** Infers the Some type from a value, preserving the inner type. */\nexport type InferSome<T> = T extends Some<infer TValue> ? Some<ValueType<TValue>> : never;\n\n/**\n * Checks if an Option contains a value (is Some).\n * @param opt - The Option to check\n * @returns true if the Option is Some, false if None\n * @example\n * isSome(42) // true\n * isSome(null) // false\n * isSome(undefined) // false\n */\nexport function isSome<T>(opt: Some<T>): true;\nexport function isSome(opt: None): false;\nexport function isSome<T>(opt: unknown): opt is Some<T>;\nexport function isSome(opt: unknown): boolean {\n return opt !== null && opt !== undefined;\n}\n\n/**\n * Checks if an Option is None (absent).\n * @param opt - The Option to check\n * @returns true if the Option is None, false if Some\n * @example\n * isNone(null) // true\n * isNone(undefined) // true\n * isNone(42) // false\n */\nexport function isNone<T>(opt: Some<T>): false;\nexport function isNone(opt: None): true;\nexport function isNone(opt: unknown): opt is None;\nexport function isNone(opt: unknown): boolean {\n return opt === null || opt === undefined;\n}\n\n/**\n * Creates an Option from a nullable value. Returns None for null/undefined, Some otherwise.\n * @param value - The value to wrap\n * @returns Some(value) if value is non-null, None otherwise\n * @example\n * optionOf(42) // Some(42)\n * optionOf(null) // None\n * optionOf(undefined) // None\n */\nexport function optionOf(value: null): None;\nexport function optionOf(value: undefined): None;\nexport function optionOf<T>(value: T): T extends NoneValueType ? None : Some<T>;\nexport function optionOf<T>(value: T): Option<T> {\n return isNone(value as Option<T>) ? NONE : (value as Some<T>);\n}\n\n/**\n * Creates a Some value. Does not validate - use safe.some() for validation.\n * @param value - The value to wrap (must be non-null)\n * @returns The value typed as Some\n * @example\n * some(42) // Some(42)\n */\nexport function some<T>(value: ValueType<T>): Some<ValueType<T>> {\n return value as Some<ValueType<T>>;\n}\n\n/** Constant representing None. Alias for NONE. */\nexport const none: None = NONE;\n\ndeclare const OK_BRAND: unique symbol;\n\n/** Represents a successful Result value. The value itself is the Ok - no wrapper object. */\nexport type Ok<T> = T & { readonly [OK_BRAND]: true };\n\nconst ERR_BRAND = Symbol.for('nalloc.ResultError');\n\ninterface ResultErrorShape<E> {\n readonly error: E;\n readonly [ERR_BRAND]: true;\n}\n\nfunction ResultErrorCtor<E>(this: ResultErrorShape<E>, error: E): void {\n (this as { error: E }).error = error;\n}\n(ResultErrorCtor.prototype as { [ERR_BRAND]: true })[ERR_BRAND] = true;\n\n/** The error wrapper type used internally. */\nexport type ResultError<E> = ResultErrorShape<E>;\n\nfunction hasErrBrand(value: unknown): value is ResultError<unknown> {\n return (value as Record<symbol, unknown>)?.[ERR_BRAND] === true;\n}\n\n/** Represents a failed Result containing an error. */\nexport type Err<E> = ResultError<E>;\n\n/** A value that is either successful (Ok) or failed (Err). Ok is the value itself; Err wraps the error. */\nexport type Result<T, E> = Ok<T> | Err<E>;\n\n/** Extracts the success value type from a Result type. */\nexport type ResultValue<TResult> = TResult extends Result<infer TValue, any> ? TValue : never;\n\n/** Extracts the error type from a Result type. */\nexport type ResultErrorType<TResult> = TResult extends Result<any, infer TError> ? TError : never;\n\n/** Type predicate: true if T is a Result type. */\nexport type IsResult<T> = T extends Result<any, any> ? true : false;\n\n/** Infers the Err type from a value, preserving the error type. */\nexport type InferErr<T> = T extends Err<infer TError> ? Err<TError> : never;\n\n/**\n * Checks if a Result is Ok (successful).\n * @param result - The Result to check\n * @returns true if the Result is Ok, false if Err\n * @example\n * isOk(42) // true (Ok value)\n * isOk(err('fail')) // false\n */\nexport function isOk<T>(result: Ok<T>): true;\nexport function isOk<E>(result: Err<E>): false;\nexport function isOk<T, E>(result: Result<T, E>): result is Ok<T>;\nexport function isOk<T, E>(result: Result<T, E>): boolean {\n return !hasErrBrand(result);\n}\n\n/**\n * Checks if a Result is Err (failed).\n * @param result - The Result to check\n * @returns true if the Result is Err, false if Ok\n * @example\n * isErr(err('fail')) // true\n * isErr(42) // false (Ok value)\n */\nexport function isErr<E>(result: Err<E>): true;\nexport function isErr(result: Ok<any>): false;\nexport function isErr<T, E>(result: Result<T, E>): result is Err<E>;\nexport function isErr<T, E>(result: Result<T, E>): boolean {\n return hasErrBrand(result);\n}\n\n/**\n * Creates an Ok value. Does not validate - use safe.ok() for validation.\n * @param value - The success value\n * @returns The value typed as Ok\n * @example\n * ok(42) // Ok(42)\n */\nexport function ok<T>(value: T): Ok<T> {\n return value as Ok<T>;\n}\n\n/**\n * Creates an Err value wrapping an error.\n * @param error - The error value\n * @returns An Err containing the error\n * @example\n * err('something went wrong') // Err('something went wrong')\n * err(new Error('failed')) // Err(Error)\n */\nexport function err<E>(error: E): Err<E> {\n return new (ResultErrorCtor as unknown as new (error: E) => Err<E>)(error);\n}\n"],"names":["NONE","err","isErr","isNone","isOk","isSome","none","ok","optionOf","some","undefined","opt","value","ERR_BRAND","Symbol","for","ResultErrorCtor","error","prototype","hasErrBrand","result"],"mappings":";;;;;;;;;;;QA+BaA;eAAAA;;QAuKGC;eAAAA;;QAvBAC;eAAAA;;QAtGAC;eAAAA;;QAuFAC;eAAAA;;QAvGAC;eAAAA;;QAgDHC;eAAAA;;QAiFGC;eAAAA;;QAjGAC;eAAAA;;QAWAC;eAAAA;;;AArET,MAAMT,OAAOU;AA0Bb,SAASL,OAAOM,GAAY;IACjC,OAAOA,QAAQ,QAAQA,QAAQD;AACjC;AAcO,SAASP,OAAOQ,GAAY;IACjC,OAAOA,QAAQ,QAAQA,QAAQD;AACjC;AAcO,SAASF,SAAYI,KAAQ;IAClC,OAAOT,OAAOS,SAAsBZ,OAAQY;AAC9C;AASO,SAASH,KAAQG,KAAmB;IACzC,OAAOA;AACT;AAGO,MAAMN,OAAaN;AAO1B,MAAMa,YAAYC,OAAOC,GAAG,CAAC;AAO7B,SAASC,gBAA8CC,KAAQ;IAC7D,AAAC,IAAI,CAAkBA,KAAK,GAAGA;AACjC;AACCD,gBAAgBE,SAAS,AAA0B,CAACL,UAAU,GAAG;AAKlE,SAASM,YAAYP,KAAc;IACjC,OAAO,AAACA,OAAmC,CAACC,UAAU,KAAK;AAC7D;AA+BO,SAAST,KAAWgB,MAAoB;IAC7C,OAAO,CAACD,YAAYC;AACtB;AAaO,SAASlB,MAAYkB,MAAoB;IAC9C,OAAOD,YAAYC;AACrB;AASO,SAASb,GAAMK,KAAQ;IAC5B,OAAOA;AACT;AAUO,SAASX,IAAOgB,KAAQ;IAC7B,OAAO,IAAKD,gBAAwDC;AACtE"}
|