functype 1.27.2 → 2.0.0
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 +63 -88
- package/dist/_virtual/_rolldown/runtime.js +1 -0
- package/dist/branded/ValidatedBrand.d.ts +122 -0
- package/dist/branded/ValidatedBrand.js +1 -0
- package/dist/branded/index.d.ts +52 -2
- package/dist/cli/data.d.ts +37 -0
- package/dist/cli/data.js +1 -0
- package/dist/cli/exports.d.ts +5 -46
- package/dist/cli/exports.js +1 -1
- package/dist/cli/formatters.js +4 -0
- package/dist/cli/full-interfaces.d.ts +6 -0
- package/dist/cli/full-interfaces.js +1139 -0
- package/dist/cli/index.js +3 -6
- package/dist/cli/interfaces.generated.js +1 -0
- package/dist/collections/index.d.ts +13 -0
- package/dist/companion/Companion.d.ts +23 -0
- package/dist/companion/Companion.js +1 -0
- package/dist/companion/CompanionTypes.d.ts +30 -0
- package/dist/{CompanionTypes-BVqO7Kc2.js → companion/CompanionTypes.js} +1 -1
- package/dist/companion/index.d.ts +2 -1
- package/dist/companion/index.js +1 -1
- package/dist/conditional/Cond.d.ts +147 -0
- package/dist/conditional/Cond.js +1 -0
- package/dist/conditional/Match.d.ts +295 -0
- package/dist/conditional/Match.js +1 -0
- package/dist/conditional/index.d.ts +3 -2
- package/dist/conditional/index.js +1 -1
- package/dist/core/base/Base.d.ts +12 -0
- package/dist/core/base/Base.js +1 -0
- package/dist/core/throwable/Throwable.d.ts +38 -0
- package/dist/core/throwable/Throwable.js +1 -0
- package/dist/decoder/Decoder.d.ts +15 -0
- package/dist/decoder/DecoderCompanion.js +1 -0
- package/dist/decoder/DecoderError.d.ts +56 -0
- package/dist/decoder/DecoderError.js +2 -0
- package/dist/decoder/Encoder.d.ts +15 -0
- package/dist/decoder/index.d.ts +71 -2
- package/dist/decoder/index.js +1 -1
- package/dist/decoder/tagged.js +1 -0
- package/dist/do/index.d.ts +246 -2
- package/dist/do/index.js +1 -1
- package/dist/do/protocol.d.ts +29 -0
- package/dist/either/index.d.ts +279 -2
- package/dist/either/index.js +1 -1
- package/dist/error/ErrorChain.d.ts +60 -0
- package/dist/error/ErrorChain.js +4 -0
- package/dist/error/ErrorFormatter.d.ts +67 -0
- package/dist/error/ErrorFormatter.js +6 -0
- package/dist/error/ParseError.d.ts +6 -0
- package/dist/error/ParseError.js +1 -0
- package/dist/error/typed/TypedError.d.ts +146 -0
- package/dist/error/typed/TypedError.js +1 -0
- package/dist/error/typed/Validation.d.ts +76 -0
- package/dist/error/typed/Validation.js +1 -0
- package/dist/extractable/Extractable.d.ts +62 -0
- package/dist/extractable/Extractable.js +1 -0
- package/dist/fetch/Http.d.ts +32 -0
- package/dist/fetch/Http.js +1 -0
- package/dist/fetch/HttpClient.d.ts +80 -0
- package/dist/fetch/HttpClient.js +1 -0
- package/dist/fetch/HttpError.d.ts +57 -0
- package/dist/fetch/HttpError.js +1 -0
- package/dist/fetch/HttpRequest.d.ts +103 -0
- package/dist/fetch/index.d.ts +5 -2
- package/dist/fetch/index.js +1 -1
- package/dist/foldable/Foldable.d.ts +27 -0
- package/dist/foldable/index.d.ts +55 -0
- package/dist/foldable/index.js +1 -0
- package/dist/functype/Functype.d.ts +76 -0
- package/dist/functype/FunctypeSum.d.ts +39 -0
- package/dist/functype/index.d.ts +4 -2
- package/dist/hkt/index.d.ts +68 -0
- package/dist/hkt/index.js +1 -0
- package/dist/identity/Identity.d.ts +34 -0
- package/dist/identity/Identity.js +1 -0
- package/dist/index.d.ts +74 -8
- package/dist/index.js +1 -1
- package/dist/internal/base64.js +1 -0
- package/dist/internal/call-alone.js +1 -0
- package/dist/internal/concurrency.d.ts +11 -0
- package/dist/internal/concurrency.js +1 -0
- package/dist/internal/define.js +1 -0
- package/dist/internal/mutation-utils.js +1 -0
- package/dist/internal/signal.js +1 -0
- package/dist/internal/stringify.js +1 -0
- package/dist/invariant/index.d.ts +32 -2
- package/dist/io/Context.d.ts +112 -0
- package/dist/io/Context.js +1 -0
- package/dist/io/Exit.d.ts +249 -0
- package/dist/io/Exit.js +1 -0
- package/dist/io/IO.d.ts +1243 -0
- package/dist/io/IO.js +1 -0
- package/dist/io/Layer.d.ts +139 -0
- package/dist/io/Layer.js +1 -0
- package/dist/io/SpanTracer.d.ts +78 -0
- package/dist/io/SpanTracer.js +1 -0
- package/dist/io/Tag.d.ts +75 -0
- package/dist/io/Tag.js +1 -0
- package/dist/io/TestClock.d.ts +133 -0
- package/dist/io/TestClock.js +1 -0
- package/dist/io/index.d.ts +41 -2
- package/dist/io/index.js +1 -1
- package/dist/lazy/Lazy.d.ts +312 -0
- package/dist/lazy/Lazy.js +1 -0
- package/dist/lazy/index.d.ts +2 -2
- package/dist/lazy/index.js +1 -1
- package/dist/list/LazyList.d.ts +182 -0
- package/dist/list/LazyList.js +1 -0
- package/dist/list/index.d.ts +137 -2
- package/dist/list/index.js +1 -1
- package/dist/logger/index.d.ts +24 -2
- package/dist/map/index.d.ts +95 -2
- package/dist/map/index.js +1 -1
- package/dist/map/shim.d.ts +13 -0
- package/dist/map/shim.js +1 -0
- package/dist/matchable/Matchable.d.ts +38 -0
- package/dist/matchable/Matchable.js +1 -0
- package/dist/obj/Obj.d.ts +212 -0
- package/dist/obj/Obj.js +1 -0
- package/dist/obj/index.d.ts +2 -2
- package/dist/obj/index.js +1 -1
- package/dist/option/index.d.ts +304 -2
- package/dist/option/index.js +1 -1
- package/dist/package.json.js +1 -0
- package/dist/pipe/index.d.ts +14 -0
- package/dist/ref/Ref.d.ts +77 -0
- package/dist/ref/Ref.js +1 -0
- package/dist/reshapeable/Reshapeable.d.ts +90 -0
- package/dist/serializable/Serializable.d.ts +39 -0
- package/dist/serialization/Serialization.d.ts +147 -0
- package/dist/serialization/Serialization.js +1 -0
- package/dist/serialization/SerializationCompanion.d.ts +125 -0
- package/dist/serialization/SerializationCompanion.js +1 -0
- package/dist/serialization/error-envelope.d.ts +44 -0
- package/dist/serialization/error-envelope.js +1 -0
- package/dist/serialization/index.d.ts +4 -2
- package/dist/serialization/index.js +1 -1
- package/dist/set/index.d.ts +106 -2
- package/dist/set/index.js +1 -1
- package/dist/stack/Stack.d.ts +120 -0
- package/dist/stack/Stack.js +1 -0
- package/dist/traced/TraceEvent.d.ts +27 -0
- package/dist/traced/TracedOption.d.ts +46 -0
- package/dist/traced/TracedOption.js +1 -0
- package/dist/traced/Tracer.d.ts +26 -0
- package/dist/traversable/KVTraversable.d.ts +14 -0
- package/dist/traversable/Traversable.d.ts +30 -0
- package/dist/try/index.d.ts +238 -2
- package/dist/try/index.js +1 -1
- package/dist/tuple/index.d.ts +92 -2
- package/dist/tuple/index.js +1 -1
- package/dist/typeable/Typeable.d.ts +40 -0
- package/dist/typeable/Typeable.js +1 -0
- package/dist/typeclass/ContainerOps.d.ts +131 -0
- package/dist/typeclass/Functor.d.ts +41 -0
- package/dist/typeclass/Promisable.d.ts +33 -0
- package/dist/typeclass/index.d.ts +4 -1
- package/dist/typeclass/index.js +1 -1
- package/dist/typeclass/variance.d.ts +54 -0
- package/dist/typeclass/variance.js +1 -0
- package/dist/types/index.d.ts +1 -0
- package/dist/util/index.d.ts +1 -3
- package/dist/valuable/Valuable.d.ts +28 -0
- package/dist/valuable/Valuable.js +1 -0
- package/dist/wire/index.d.ts +40 -2
- package/package.json +7 -12
- package/dist/Brand-bfnGXuum.d.ts +0 -54
- package/dist/Companion-DiOMBHDG.js +0 -1
- package/dist/CompanionTypes-Cc90cQ4P.d.ts +0 -58
- package/dist/Invariant-DEan-SxV.d.ts +0 -35
- package/dist/Logger-BmprRS8v.d.ts +0 -27
- package/dist/Tuple-B8KM-H8Y.d.ts +0 -213
- package/dist/Wire-3hvw0Ogg.d.ts +0 -42
- package/dist/core/task/index.d.ts +0 -2
- package/dist/core/task/index.js +0 -1
- package/dist/full-interfaces-BadxJrCt.js +0 -1202
- package/dist/index-CLYh2qZu.d.ts +0 -6649
- package/dist/rolldown-runtime-DK3Fl9T5.js +0 -1
- package/dist/serialization-9_SyrfdG.js +0 -3
- package/dist/src-BQPeS6p2.js +0 -10
- package/dist/typeclass-C61yDVYd.js +0 -1
package/dist/cli/index.js
CHANGED
|
@@ -1,9 +1,6 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{
|
|
3
|
-
`)
|
|
4
|
-
`).trimEnd()},u=()=>{let e=n([`INTERFACES`,``]);return n(Object.entries(o)).foldLeft(e)((e,[t,r])=>{let i=r.extends?` extends ${r.extends}`:``,a=e.add(`${t}<A>${i}`).add(` ${r.description}`);return n(r.methods).foldLeft(a)((e,t)=>e.add(` ${t}`)).add(``)}).toArray().join(`
|
|
5
|
-
`).trimEnd()},d=e=>JSON.stringify(e,null,2),f=()=>({version:r,categories:a,types:i}),p=t=>e(i[t]).map(e=>({name:t,data:e})).or(n(Object.entries(i)).find(([e])=>e.toLowerCase()===t.toLowerCase()).map(([e,t])=>({name:e,data:t}))).orUndefined(),m=()=>Object.keys(i),h=()=>o,g=e=>{let t=n(e.slice(2));return{flags:{json:t.contains(`--json`),full:t.contains(`--full`),help:t.exists(e=>e===`--help`||e===`-h`)},args:t.filter(e=>!e.startsWith(`--`)&&e!==`-h`)}},_=t=>e(s[t]).or(n(Object.entries(s)).find(([e])=>e.toLowerCase()===t.toLowerCase()).map(([,e])=>e)),v=()=>{let e=n([`FULL INTERFACE DEFINITIONS`,`=`.repeat(60),``]);return n(Object.entries(s)).foldLeft(e)((e,[t,r])=>e.concat(n([`// ${t}`,r,``,`-`.repeat(60),``]))).toArray().join(`
|
|
6
|
-
`).trimEnd()},y=()=>{console.log(`functype - API documentation for LLMs
|
|
2
|
+
import{Match as e}from"../conditional/Match.js";import{List as t}from"../list/index.js";import{Option as n}from"../option/index.js";import{formatInterfaces as r,formatJson as i,formatOverview as a,formatType as o,getAllTypeNames as s,getInterfacesData as c,getOverviewData as l,getType as u}from"./formatters.js";import{FULL_INTERFACES as d}from"./full-interfaces.js";const f=e=>{let n=t(e.slice(2));return{flags:{json:n.contains(`--json`),full:n.contains(`--full`),help:n.exists(e=>e===`--help`||e===`-h`)},args:n.filter(e=>!e.startsWith(`--`)&&e!==`-h`)}},p=e=>n(d[e]).orElse(()=>t(Object.entries(d)).find(([t])=>t.toLowerCase()===e.toLowerCase()).map(([,e])=>e)),m=()=>{let e=t([`FULL INTERFACE DEFINITIONS`,`=`.repeat(60),``]);return t(Object.entries(d)).foldLeft(e)((e,[n,r])=>e.concat(t([`// ${n}`,r,``,`-`.repeat(60),``]))).toArray().join(`
|
|
3
|
+
`).trimEnd()},h=()=>{console.log(`functype - API documentation for LLMs
|
|
7
4
|
|
|
8
5
|
USAGE
|
|
9
6
|
npx functype Show overview of all types
|
|
@@ -24,4 +21,4 @@ EXAMPLES
|
|
|
24
21
|
npx functype Option --json # Option as JSON
|
|
25
22
|
npx functype Option --full # Full TypeScript interface
|
|
26
23
|
npx functype --full # All full interfaces (large output!)
|
|
27
|
-
`)},
|
|
24
|
+
`)},g=e=>{console.error(`Unknown type: ${e}`),console.error(``),console.error(`Available types: ${s().join(`, `)}`),console.error(``),console.error(`Use: npx functype interfaces - for interface reference`),process.exit(1)},_=e=>console.log(e),v=(e,t)=>n(u(e)).fold(()=>g(e),e=>{t.full?p(e.name).fold(()=>_(t.json?i({[e.name]:e.data}):o(e.name,e.data)),n=>_(t.json?i({[e.name]:{...e.data,fullInterface:n}}):n)):_(t.json?i({[e.name]:e.data}):o(e.name,e.data))});(()=>{let{flags:t,args:n}=f(process.argv);e(!0).when(()=>t.help,()=>h()).when(()=>n.isEmpty,()=>t.full?_(t.json?i(d):m()):_(t.json?i(l()):a())).when(()=>n.headOption().contains(`interfaces`),()=>_(t.json?i(c()):r())).default(()=>n.headOption().fold(()=>_(t.json?i(l()):a()),e=>v(e,t)))})();
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const e={Option:[`Applicative`,`AsyncMonad`,`Doable`,`Extractable`,`Foldable`,`Functor`,`Matchable`,`Monad`,`Promisable`,`Reshapeable`,`Serializable`,`Traversable`],Either:[`Applicative`,`AsyncMonad`,`Doable`,`Extractable`,`Foldable`,`Functor`,`Monad`,`Promisable`,`Reshapeable`,`Serializable`],Try:[`Applicative`,`AsyncMonad`,`Doable`,`Extractable`,`Foldable`,`Functor`,`Monad`,`Promisable`,`Reshapeable`,`Serializable`],List:[`Applicative`,`Collection`,`Doable`,`Foldable`,`Functor`,`Iterable`,`Reshapeable`,`Serializable`],Set:[`Applicative`,`Collection`,`Foldable`,`Functor`,`Iterable`,`Serializable`],Map:[`Collection`,`Foldable`,`Iterable`,`KVTraversable`,`Serializable`],Obj:[`Doable`,`Extractable`,`Foldable`,`Matchable`,`Promisable`,`Reshapeable`,`Serializable`],Lazy:[`Applicative`,`AsyncMonad`,`Extractable`,`Foldable`,`Functor`,`Monad`,`Serializable`,`Traversable`],LazyList:[`Foldable`,`Serializable`],Tuple:[`Foldable`,`Serializable`]};export{e as GENERATED_INTERFACES};
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import { List } from "../list/index.js";
|
|
2
|
+
import { Set } from "../set/index.js";
|
|
3
|
+
/**
|
|
4
|
+
* Represents a collection with conversion capabilities
|
|
5
|
+
* @interface
|
|
6
|
+
* @module Collections
|
|
7
|
+
* @category Core
|
|
8
|
+
*/
|
|
9
|
+
export interface Collection<A> {
|
|
10
|
+
toList(): List<A>;
|
|
11
|
+
toSet(): Set<A>;
|
|
12
|
+
toString(): string;
|
|
13
|
+
}
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Creates a function-object hybrid similar to Scala's companion objects.
|
|
3
|
+
* This utility allows creating TypeScript function objects with attached methods,
|
|
4
|
+
* mimicking Scala's class + companion object pattern without using classes.
|
|
5
|
+
*
|
|
6
|
+
* @param object The main function that will be invoked when the object is called
|
|
7
|
+
* @param companion Additional static methods to attach to the function
|
|
8
|
+
* @returns A function with the attached methods
|
|
9
|
+
*
|
|
10
|
+
* @example
|
|
11
|
+
* const greet = (name: string) => `Hello, ${name}!`;
|
|
12
|
+
* const methods = {
|
|
13
|
+
* formal: (name: string) => `Good day, ${name}.`,
|
|
14
|
+
* casual: (name: string) => `Hey ${name}!`
|
|
15
|
+
* };
|
|
16
|
+
* const Greeter = createCompanionObject(greet, methods);
|
|
17
|
+
*
|
|
18
|
+
* // Usage:
|
|
19
|
+
* Greeter("World"); // Hello, World!
|
|
20
|
+
* Greeter.formal("Sir"); // Good day, Sir.
|
|
21
|
+
* Greeter.casual("Friend"); // Hey Friend!
|
|
22
|
+
*/
|
|
23
|
+
export declare function Companion<ObjectF extends object, CompanionF extends object>(object: ObjectF, companion: CompanionF): ObjectF & CompanionF;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{mergeObjects as e}from"../util/index.js";function t(t,n){return e(t,n)}export{t as Companion};
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Helper types for working with the Companion pattern
|
|
3
|
+
* @module CompanionTypes
|
|
4
|
+
*/
|
|
5
|
+
/**
|
|
6
|
+
* Extracts the companion methods type from a Companion object
|
|
7
|
+
* @typeParam T - The Companion type
|
|
8
|
+
* @example
|
|
9
|
+
* ```typescript
|
|
10
|
+
* type OptionCompanionMethods = CompanionMethods<typeof Option>
|
|
11
|
+
* // { from: ..., none: ..., fromJSON: ..., etc. }
|
|
12
|
+
* ```
|
|
13
|
+
*/
|
|
14
|
+
export type CompanionMethods<T> = T extends ((...args: never[]) => unknown) & (infer C) ? C : never;
|
|
15
|
+
/**
|
|
16
|
+
* Extracts the instance type from a constructor function
|
|
17
|
+
* @typeParam T - The constructor function type
|
|
18
|
+
* @example
|
|
19
|
+
* ```typescript
|
|
20
|
+
* type OptionInstance = InstanceType<typeof Option>
|
|
21
|
+
* // Option<T>
|
|
22
|
+
* ```
|
|
23
|
+
*/
|
|
24
|
+
export type InstanceType<T> = T extends ((...args: infer Args) => infer R) ? R extends ((...args: unknown[]) => unknown) ? ReturnType<R> : R : never;
|
|
25
|
+
/**
|
|
26
|
+
* Type guard to check if a value is a Companion object (has both constructor and companion methods)
|
|
27
|
+
* @param value - The value to check
|
|
28
|
+
* @returns True if value is a Companion object
|
|
29
|
+
*/
|
|
30
|
+
export declare const isCompanion: (value: unknown) => value is ((...args: never[]) => unknown) & Record<string, unknown>;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
const e=e=>typeof e==`function`&&Object.keys(e).length>0;export{e as
|
|
1
|
+
const e=e=>typeof e==`function`&&Object.keys(e).length>0;export{e as isCompanion};
|
|
@@ -1,2 +1,3 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { Companion } from "./Companion.js";
|
|
2
|
+
import { CompanionMethods, InstanceType, isCompanion } from "./CompanionTypes.js";
|
|
2
3
|
export { Companion, CompanionMethods, InstanceType, isCompanion };
|
package/dist/companion/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{Companion as e}from"./Companion.js";import{isCompanion as t}from"./CompanionTypes.js";export{e as Companion,t as isCompanion};
|
|
@@ -0,0 +1,147 @@
|
|
|
1
|
+
import { Type } from "../types/index.js";
|
|
2
|
+
/**
|
|
3
|
+
* Conditional expression that enforces exhaustive returns without early returns.
|
|
4
|
+
* Similar to Scala's if/else expressions that always return a value.
|
|
5
|
+
*
|
|
6
|
+
* @example
|
|
7
|
+
* const discount = Cond.of<number>()
|
|
8
|
+
* .when(isPremiumMember, 0.2)
|
|
9
|
+
* .elseWhen(isRegularMember, 0.1)
|
|
10
|
+
* .else(0)
|
|
11
|
+
*
|
|
12
|
+
* @example
|
|
13
|
+
* // Chaining multiple conditions
|
|
14
|
+
* const status = Cond.of<string>()
|
|
15
|
+
* .when(response.status >= 500, "Server Error")
|
|
16
|
+
* .elseWhen(response.status >= 400, "Client Error")
|
|
17
|
+
* .elseWhen(response.status >= 200, "Success")
|
|
18
|
+
* .else("Unknown")
|
|
19
|
+
*/
|
|
20
|
+
export type Cond<T extends Type> = {
|
|
21
|
+
/**
|
|
22
|
+
* Add an if condition
|
|
23
|
+
*/
|
|
24
|
+
when: (condition: boolean, value: T | (() => T)) => Cond<T>;
|
|
25
|
+
/**
|
|
26
|
+
* Add an else-if condition
|
|
27
|
+
*/
|
|
28
|
+
elseWhen: (condition: boolean, value: T | (() => T)) => Cond<T>;
|
|
29
|
+
/**
|
|
30
|
+
* Terminal else clause - required to get the result
|
|
31
|
+
*/
|
|
32
|
+
else: (value: T | (() => T)) => T;
|
|
33
|
+
/**
|
|
34
|
+
* Get the result if a condition was met, throws if no condition met
|
|
35
|
+
*/
|
|
36
|
+
orThrow: () => T;
|
|
37
|
+
};
|
|
38
|
+
/** @internal */
|
|
39
|
+
type LazyCondChain<T> = {
|
|
40
|
+
when: (condition: () => boolean, value: () => T) => LazyCondChain<T>;
|
|
41
|
+
elseWhen: (condition: () => boolean, value: () => T) => LazyCondChain<T>;
|
|
42
|
+
else: (value: () => T) => T;
|
|
43
|
+
};
|
|
44
|
+
/**
|
|
45
|
+
* Create a new conditional expression
|
|
46
|
+
* @example
|
|
47
|
+
* const message = Cond<string>()
|
|
48
|
+
* .when(isError, "Error occurred")
|
|
49
|
+
* .when(isWarning, "Warning")
|
|
50
|
+
* .else("All good")
|
|
51
|
+
*/
|
|
52
|
+
declare const CondConstructor: <T extends Type>() => Cond<T>;
|
|
53
|
+
declare const CondStatics: {
|
|
54
|
+
/**
|
|
55
|
+
* Create a conditional expression that must end with else
|
|
56
|
+
* @example
|
|
57
|
+
* const x = 7
|
|
58
|
+
* const result = Cond.of<string>()
|
|
59
|
+
* .when(x > 10, "large")
|
|
60
|
+
* .elseWhen(x > 5, "medium")
|
|
61
|
+
* .else("small")
|
|
62
|
+
* // result = "medium"
|
|
63
|
+
*
|
|
64
|
+
* @example
|
|
65
|
+
* // With lazy evaluation
|
|
66
|
+
* const discount = Cond.of<number>()
|
|
67
|
+
* .when(isPremium, () => calculatePremiumDiscount())
|
|
68
|
+
* .when(isLoyal, () => calculateLoyaltyDiscount())
|
|
69
|
+
* .else(0)
|
|
70
|
+
*/
|
|
71
|
+
of: <T extends Type>() => Cond<T>;
|
|
72
|
+
/**
|
|
73
|
+
* Pattern matching helper that ensures exhaustiveness
|
|
74
|
+
* @example
|
|
75
|
+
* type Status = "pending" | "success" | "error"
|
|
76
|
+
* const status: Status = "success"
|
|
77
|
+
* const result = Cond.match(status)({
|
|
78
|
+
* "pending": "Waiting...",
|
|
79
|
+
* "success": "Done!",
|
|
80
|
+
* "error": "Failed!"
|
|
81
|
+
* })
|
|
82
|
+
* // result = "Done!"
|
|
83
|
+
*
|
|
84
|
+
* @example
|
|
85
|
+
* // With function values
|
|
86
|
+
* const action = "compute"
|
|
87
|
+
* const result = Cond.match(action)({
|
|
88
|
+
* "compute": () => expensiveComputation(),
|
|
89
|
+
* "cache": () => getCachedValue(),
|
|
90
|
+
* "skip": () => defaultValue
|
|
91
|
+
* })
|
|
92
|
+
*/
|
|
93
|
+
match: <T extends string | number | symbol>(value: T) => <R extends Type>(cases: Record<T, R | (() => R)>) => R;
|
|
94
|
+
/**
|
|
95
|
+
* Create a lazy conditional that defers evaluation
|
|
96
|
+
* @example
|
|
97
|
+
* // Only evaluates conditions and values when needed
|
|
98
|
+
* const getMessage = Cond.lazy<string>()
|
|
99
|
+
* .when(() => isError(), () => computeErrorMessage())
|
|
100
|
+
* .when(() => isWarning(), () => computeWarningMessage())
|
|
101
|
+
* .else(() => "Success")
|
|
102
|
+
*
|
|
103
|
+
* @example
|
|
104
|
+
* // Complex conditional with expensive checks
|
|
105
|
+
* const result = Cond.lazy<Action>()
|
|
106
|
+
* .when(
|
|
107
|
+
* () => user.role === "admin" && checkAdminPermissions(),
|
|
108
|
+
* () => ({ type: "admin", permissions: loadAdminPermissions() })
|
|
109
|
+
* )
|
|
110
|
+
* .when(
|
|
111
|
+
* () => user.role === "user" && user.isActive,
|
|
112
|
+
* () => ({ type: "user", permissions: loadUserPermissions() })
|
|
113
|
+
* )
|
|
114
|
+
* .else(() => ({ type: "guest", permissions: [] }))
|
|
115
|
+
*/
|
|
116
|
+
lazy: <T extends Type>() => LazyCondChain<T>;
|
|
117
|
+
};
|
|
118
|
+
/**
|
|
119
|
+
* Conditional expression builder for functional if/else chains
|
|
120
|
+
* @example
|
|
121
|
+
* // Basic usage
|
|
122
|
+
* const size = Cond.of<string>()
|
|
123
|
+
* .when(value > 100, "large")
|
|
124
|
+
* .elseWhen(value > 50, "medium")
|
|
125
|
+
* .else("small")
|
|
126
|
+
*
|
|
127
|
+
* @example
|
|
128
|
+
* // Pattern matching
|
|
129
|
+
* const message = Cond.match(errorCode)({
|
|
130
|
+
* 404: "Not Found",
|
|
131
|
+
* 500: "Server Error",
|
|
132
|
+
* 200: "OK"
|
|
133
|
+
* })
|
|
134
|
+
*
|
|
135
|
+
* @example
|
|
136
|
+
* // Lazy evaluation
|
|
137
|
+
* const result = Cond.lazy<string>()
|
|
138
|
+
* .when(() => checkCondition1(), () => "Result 1")
|
|
139
|
+
* .when(() => checkCondition2(), () => "Result 2")
|
|
140
|
+
* .else(() => "Default")
|
|
141
|
+
*/
|
|
142
|
+
export declare const Cond: CondCompanion;
|
|
143
|
+
/** The type of `Cond`: its constructor and its statics, named so that errors and hovers print `CondCompanion`. */
|
|
144
|
+
export interface CondCompanion extends CondConstructorType, CondStaticsType {}
|
|
145
|
+
type CondConstructorType = typeof CondConstructor;
|
|
146
|
+
type CondStaticsType = typeof CondStatics;
|
|
147
|
+
export {};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{Companion as e}from"../companion/Companion.js";const t=e=>{let n=e=>typeof e==`function`?e():e,r={when:(i,a)=>e.resolved?r:i?t({resolved:!0,value:n(a)}):r,elseWhen:(i,a)=>e.resolved?r:i?t({resolved:!0,value:n(a)}):r,else:t=>e.resolved?e.value:n(t),orThrow:()=>{if(!e.resolved)throw Error(`Conditional expression has no matching condition`);return e.value}};return r},n=()=>t({resolved:!1}),r=e(n,{of:()=>n(),match:e=>t=>{let n=t[e];if(n===void 0)throw Error(`No case defined for value: ${String(e)}`);return typeof n==`function`?n():n},lazy:()=>{let e={resolved:!1},t={when:(n,r)=>(e.resolved||n()&&(e.resolved=!0,e.value=r()),t),elseWhen:(n,r)=>(e.resolved||n()&&(e.resolved=!0,e.value=r()),t),else:t=>e.resolved?e.value:t()};return t}});export{r as Cond};
|
|
@@ -0,0 +1,295 @@
|
|
|
1
|
+
import { Option } from "../option/index.js";
|
|
2
|
+
import { Type } from "../types/index.js";
|
|
3
|
+
/**
|
|
4
|
+
* Type-level utilities for exhaustiveness checking
|
|
5
|
+
* @internal
|
|
6
|
+
*/
|
|
7
|
+
type UnionToIntersection<U> = (U extends unknown ? (k: U) => void : never) extends ((k: infer I) => void) ? I : never;
|
|
8
|
+
/** @internal */
|
|
9
|
+
type IsUnion<T> = [T] extends [UnionToIntersection<T>] ? false : true;
|
|
10
|
+
/** @internal */
|
|
11
|
+
type RequireExhaustive<T, Cases> = IsUnion<T> extends true ? (keyof Cases extends T ? (T extends keyof Cases ? Cases : never) : never) : Cases;
|
|
12
|
+
/**
|
|
13
|
+
* Pattern types for nested matching
|
|
14
|
+
* @internal
|
|
15
|
+
*/
|
|
16
|
+
type Pattern<T> = T | { [K in keyof T]?: Pattern<T[K]>; } | ((value: T) => boolean) | {
|
|
17
|
+
_: (value: T) => boolean;
|
|
18
|
+
};
|
|
19
|
+
/**
|
|
20
|
+
* Extract result from pattern
|
|
21
|
+
* @internal
|
|
22
|
+
*/
|
|
23
|
+
type PatternResult<T, R> = R | ((matched: T) => R);
|
|
24
|
+
/**
|
|
25
|
+
* Untyped Match (before first case is added).
|
|
26
|
+
* The result type R is inferred when the first case method is called.
|
|
27
|
+
* This enables proper type inference without requiring explicit type annotations.
|
|
28
|
+
*
|
|
29
|
+
* @internal
|
|
30
|
+
*/
|
|
31
|
+
export type UntypedMatch<T extends Type> = {
|
|
32
|
+
/**
|
|
33
|
+
* Match against a pattern - infers result type R from the result parameter
|
|
34
|
+
*/
|
|
35
|
+
case: <R extends Type>(pattern: Pattern<T>, result: PatternResult<T, R>) => Match<T, R>;
|
|
36
|
+
/**
|
|
37
|
+
* Match a specific value - infers result type R from the result parameter
|
|
38
|
+
*/
|
|
39
|
+
caseValue: <R extends Type>(match: T, result: R | (() => R)) => Match<T, R>;
|
|
40
|
+
/**
|
|
41
|
+
* Match multiple values - infers result type R from the result parameter
|
|
42
|
+
*/
|
|
43
|
+
caseValues: <R extends Type>(matches: T[], result: R | (() => R)) => Match<T, R>;
|
|
44
|
+
/**
|
|
45
|
+
* Match with a guard function - infers result type R from the result parameter
|
|
46
|
+
*/
|
|
47
|
+
when: <R extends Type>(guard: (value: T) => boolean, result: PatternResult<T, R>) => Match<T, R>;
|
|
48
|
+
/**
|
|
49
|
+
* Match multiple patterns (OR operation) - infers result type R from the result parameter
|
|
50
|
+
*/
|
|
51
|
+
caseAny: <R extends Type>(patterns: Pattern<T>[], result: PatternResult<T, R>) => Match<T, R>;
|
|
52
|
+
};
|
|
53
|
+
/**
|
|
54
|
+
* Pattern matching construct similar to Scala's match expressions.
|
|
55
|
+
* Supports exhaustive matching, nested patterns, and guards.
|
|
56
|
+
*
|
|
57
|
+
* @example
|
|
58
|
+
* // Basic pattern matching
|
|
59
|
+
* const result = Match(value)
|
|
60
|
+
* .case(x => x > 100, "large")
|
|
61
|
+
* .case(x => x > 50, "medium")
|
|
62
|
+
* .default("small")
|
|
63
|
+
*
|
|
64
|
+
* @example
|
|
65
|
+
* // Matching exact values
|
|
66
|
+
* const message = Match(status)
|
|
67
|
+
* .caseValue("pending", "Please wait...")
|
|
68
|
+
* .caseValue("success", "Completed!")
|
|
69
|
+
* .caseValue("error", "Failed")
|
|
70
|
+
* .default("Unknown")
|
|
71
|
+
*
|
|
72
|
+
* @example
|
|
73
|
+
* // Nested pattern matching
|
|
74
|
+
* const user = { name: "John", age: 30, role: "admin" }
|
|
75
|
+
* const msg = Match(user)
|
|
76
|
+
* .case({ role: "admin", age: n => n >= 18 }, "Adult admin")
|
|
77
|
+
* .case({ role: "user" }, u => `User: ${u.name}`)
|
|
78
|
+
* .default("Guest")
|
|
79
|
+
*/
|
|
80
|
+
export type Match<T extends Type, R extends Type> = {
|
|
81
|
+
/**
|
|
82
|
+
* Match against a pattern (value, nested object, or predicate).
|
|
83
|
+
* The result type R2 is added to the union of possible results.
|
|
84
|
+
*/
|
|
85
|
+
case: <R2 extends Type>(pattern: Pattern<T>, result: PatternResult<T, R2>) => Match<T, R | R2>;
|
|
86
|
+
/**
|
|
87
|
+
* Add a case that matches a specific value.
|
|
88
|
+
* The result type R2 is added to the union of possible results.
|
|
89
|
+
*/
|
|
90
|
+
caseValue: <R2 extends Type>(match: T, result: R2 | (() => R2)) => Match<T, R | R2>;
|
|
91
|
+
/**
|
|
92
|
+
* Add a case that matches multiple values.
|
|
93
|
+
* The result type R2 is added to the union of possible results.
|
|
94
|
+
*/
|
|
95
|
+
caseValues: <R2 extends Type>(matches: T[], result: R2 | (() => R2)) => Match<T, R | R2>;
|
|
96
|
+
/**
|
|
97
|
+
* Match with a guard function (alias for readability).
|
|
98
|
+
* The result type R2 is added to the union of possible results.
|
|
99
|
+
*/
|
|
100
|
+
when: <R2 extends Type>(guard: (value: T) => boolean, result: PatternResult<T, R2>) => Match<T, R | R2>;
|
|
101
|
+
/**
|
|
102
|
+
* Match multiple patterns (OR operation).
|
|
103
|
+
* The result type R2 is added to the union of possible results.
|
|
104
|
+
*/
|
|
105
|
+
caseAny: <R2 extends Type>(patterns: Pattern<T>[], result: PatternResult<T, R2>) => Match<T, R | R2>;
|
|
106
|
+
/**
|
|
107
|
+
* Default case - makes match non-exhaustive.
|
|
108
|
+
* The result type R2 is added to the union of possible results.
|
|
109
|
+
*/
|
|
110
|
+
default: <R2 extends Type>(result: PatternResult<T, R2>) => R | R2;
|
|
111
|
+
/**
|
|
112
|
+
* Force exhaustive matching (compile-time check for union types)
|
|
113
|
+
*/
|
|
114
|
+
exhaustive: () => R;
|
|
115
|
+
/**
|
|
116
|
+
* Get result if matched, throws if no match
|
|
117
|
+
*/
|
|
118
|
+
orThrow: (errorMessage?: string) => R;
|
|
119
|
+
/**
|
|
120
|
+
* Get result wrapped in Option
|
|
121
|
+
*/
|
|
122
|
+
toOption: () => Option<R>;
|
|
123
|
+
};
|
|
124
|
+
/**
|
|
125
|
+
* Create a new pattern match expression
|
|
126
|
+
* @example
|
|
127
|
+
* const result = Match(httpStatus)
|
|
128
|
+
* .case(s => s >= 200 && s < 300, "Success")
|
|
129
|
+
* .case(s => s >= 400 && s < 500, "Client Error")
|
|
130
|
+
* .case(s => s >= 500, "Server Error")
|
|
131
|
+
* .default("Unknown")
|
|
132
|
+
*/
|
|
133
|
+
declare const MatchConstructor: <T extends Type>(value: T) => UntypedMatch<T>;
|
|
134
|
+
declare const MatchStatics: {
|
|
135
|
+
/**
|
|
136
|
+
* Create a type-safe exhaustive match for union types
|
|
137
|
+
* @example
|
|
138
|
+
* type Status = "pending" | "success" | "error"
|
|
139
|
+
* const status: Status = "success"
|
|
140
|
+
* const result = Match.exhaustive<Status, string>({
|
|
141
|
+
* pending: "Waiting...",
|
|
142
|
+
* success: "Done!",
|
|
143
|
+
* error: "Failed!"
|
|
144
|
+
* })(status)
|
|
145
|
+
* // result = "Done!"
|
|
146
|
+
*
|
|
147
|
+
* @example
|
|
148
|
+
* // For function values, wrap in object to prevent execution
|
|
149
|
+
* type Operation = "add" | "subtract" | "multiply"
|
|
150
|
+
* const ops = Match.exhaustive<Operation, { fn: (a: number, b: number) => number }>({
|
|
151
|
+
* add: { fn: (a, b) => a + b },
|
|
152
|
+
* subtract: { fn: (a, b) => a - b },
|
|
153
|
+
* multiply: { fn: (a, b) => a * b }
|
|
154
|
+
* })
|
|
155
|
+
* const compute = ops("multiply").fn
|
|
156
|
+
* const result = compute(4, 5) // 20
|
|
157
|
+
*/
|
|
158
|
+
exhaustive: <T extends string | number | symbol, R extends Type>(cases: RequireExhaustive<T, Record<T, R>>) => (value: T) => R;
|
|
159
|
+
/**
|
|
160
|
+
* Create a partial match that requires a default
|
|
161
|
+
* @example
|
|
162
|
+
* const httpCode = 404
|
|
163
|
+
* const message = Match.partial<number, string>({
|
|
164
|
+
* 200: "OK",
|
|
165
|
+
* 201: "Created",
|
|
166
|
+
* 404: "Not Found",
|
|
167
|
+
* 500: "Server Error"
|
|
168
|
+
* }).withDefault("Unknown Status")(httpCode)
|
|
169
|
+
* // message = "Not Found"
|
|
170
|
+
*
|
|
171
|
+
* @example
|
|
172
|
+
* // With function default
|
|
173
|
+
* const getMessage = Match.partial<number, string>({
|
|
174
|
+
* 0: "Zero",
|
|
175
|
+
* 1: "One",
|
|
176
|
+
* 2: "Two"
|
|
177
|
+
* }).withDefault((n) => `Number: ${n}`)
|
|
178
|
+
* getMessage(5) // "Number: 5"
|
|
179
|
+
*/
|
|
180
|
+
partial: <T extends string | number | symbol, R extends Type>(cases: Partial<Record<T, R | ((value: T) => R)>>) => {
|
|
181
|
+
withDefault: (defaultValue: R | ((value: T) => R)) => (value: T) => R;
|
|
182
|
+
};
|
|
183
|
+
/**
|
|
184
|
+
* Pattern match with guards
|
|
185
|
+
* @example
|
|
186
|
+
* const score = 85
|
|
187
|
+
* const grade = Match.withGuards<number, string>([
|
|
188
|
+
* [n => n >= 90, "A"],
|
|
189
|
+
* [n => n >= 80, "B"],
|
|
190
|
+
* [n => n >= 70, "C"],
|
|
191
|
+
* [n => n >= 60, "D"]
|
|
192
|
+
* ]).withDefault("F")(score)
|
|
193
|
+
* // grade = "B"
|
|
194
|
+
*
|
|
195
|
+
* @example
|
|
196
|
+
* // With function results for custom messages
|
|
197
|
+
* const age = 25
|
|
198
|
+
* const category = Match.withGuards<number, string>([
|
|
199
|
+
* [n => n < 13, n => `Child (${n} years)`],
|
|
200
|
+
* [n => n < 20, n => `Teenager (${n} years)`],
|
|
201
|
+
* [n => n < 60, n => `Adult (${n} years)`],
|
|
202
|
+
* [n => n >= 60, n => `Senior (${n} years)`]
|
|
203
|
+
* ]).withDefault("Unknown")(age)
|
|
204
|
+
* // category = "Adult (25 years)"
|
|
205
|
+
*/
|
|
206
|
+
withGuards: <T extends Type, R extends Type>(guards: Array<[(value: T) => boolean, R | ((value: T) => R)]>) => {
|
|
207
|
+
withDefault: (defaultValue: R | ((value: T) => R)) => (value: T) => R;
|
|
208
|
+
};
|
|
209
|
+
/**
|
|
210
|
+
* Pattern matching for objects with specific structure
|
|
211
|
+
* @example
|
|
212
|
+
* type Event =
|
|
213
|
+
* | { type: "click"; x: number; y: number }
|
|
214
|
+
* | { type: "keypress"; key: string }
|
|
215
|
+
* | { type: "hover"; element: string }
|
|
216
|
+
*
|
|
217
|
+
* const handler = Match.struct<Event, void>()
|
|
218
|
+
* .case({ type: "click" }, (e) => console.log(`Click at ${e.x}, ${e.y}`))
|
|
219
|
+
* .case({ type: "keypress", key: "Enter" }, () => console.log("Enter pressed"))
|
|
220
|
+
* .case({ type: "hover" }, (e) => console.log(`Hovering over ${e.element}`))
|
|
221
|
+
* .build()
|
|
222
|
+
*/
|
|
223
|
+
struct: <T extends Type, R extends Type>() => {
|
|
224
|
+
case: (pattern: Pattern<T>, handler: (value: T) => R) => /*elided*/ any;
|
|
225
|
+
build: () => (value: T) => R;
|
|
226
|
+
};
|
|
227
|
+
/**
|
|
228
|
+
* Create a pattern matcher with guards and nested patterns
|
|
229
|
+
* @example
|
|
230
|
+
* type User = {
|
|
231
|
+
* name: string
|
|
232
|
+
* age: number
|
|
233
|
+
* permissions: string[]
|
|
234
|
+
* }
|
|
235
|
+
*
|
|
236
|
+
* const canAccess = Match.builder<User, boolean>()
|
|
237
|
+
* .when(u => u.permissions.includes("admin"), true)
|
|
238
|
+
* .case({ age: n => n >= 18, permissions: p => p.length > 0 }, true)
|
|
239
|
+
* .default(false)
|
|
240
|
+
* .build()
|
|
241
|
+
*/
|
|
242
|
+
builder: <T extends Type, R extends Type>() => {
|
|
243
|
+
case: (pattern: Pattern<T>, result: PatternResult<T, R>) => /*elided*/ any;
|
|
244
|
+
when: (guard: (value: T) => boolean, result: PatternResult<T, R>) => /*elided*/ any;
|
|
245
|
+
default: (result: PatternResult<T, R>) => {
|
|
246
|
+
build: () => (value: T) => R;
|
|
247
|
+
};
|
|
248
|
+
};
|
|
249
|
+
};
|
|
250
|
+
/**
|
|
251
|
+
* Pattern matching utility for type-safe conditional logic with exhaustiveness checking,
|
|
252
|
+
* nested patterns, and guard support
|
|
253
|
+
*
|
|
254
|
+
* @example
|
|
255
|
+
* // Basic pattern matching
|
|
256
|
+
* const result = Match(value)
|
|
257
|
+
* .case(x => x > 0, "positive")
|
|
258
|
+
* .case(x => x < 0, "negative")
|
|
259
|
+
* .default("zero")
|
|
260
|
+
*
|
|
261
|
+
* @example
|
|
262
|
+
* // Exhaustive matching for union types
|
|
263
|
+
* type Color = "red" | "green" | "blue"
|
|
264
|
+
* const hex = Match.exhaustive<Color, string>({
|
|
265
|
+
* red: "#FF0000",
|
|
266
|
+
* green: "#00FF00",
|
|
267
|
+
* blue: "#0000FF"
|
|
268
|
+
* })(color)
|
|
269
|
+
*
|
|
270
|
+
* @example
|
|
271
|
+
* // Nested pattern matching
|
|
272
|
+
* type User = { name: string; age: number; role: "admin" | "user" }
|
|
273
|
+
* const user: User = { name: "John", age: 30, role: "admin" }
|
|
274
|
+
*
|
|
275
|
+
* const message = Match<User, string>(user)
|
|
276
|
+
* .case({ role: "admin", age: (n) => n >= 18 }, "Adult admin")
|
|
277
|
+
* .case({ role: "user" }, u => `User: ${u.name}`)
|
|
278
|
+
* .default("Unknown")
|
|
279
|
+
*
|
|
280
|
+
* @example
|
|
281
|
+
* // Using exhaustive() method
|
|
282
|
+
* type Status = "idle" | "loading" | "success" | "error"
|
|
283
|
+
* const result = Match<Status, string>("success")
|
|
284
|
+
* .case("idle", "Waiting...")
|
|
285
|
+
* .case("loading", "Loading...")
|
|
286
|
+
* .case("success", "Done!")
|
|
287
|
+
* .case("error", "Failed!")
|
|
288
|
+
* .exhaustive()
|
|
289
|
+
*/
|
|
290
|
+
export declare const Match: MatchCompanion;
|
|
291
|
+
/** The type of `Match`: its constructor and its statics, named so that errors and hovers print `MatchCompanion`. */
|
|
292
|
+
export interface MatchCompanion extends MatchConstructorType, MatchStaticsType {}
|
|
293
|
+
type MatchConstructorType = typeof MatchConstructor;
|
|
294
|
+
type MatchStaticsType = typeof MatchStatics;
|
|
295
|
+
export {};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{Companion as e}from"../companion/Companion.js";import{Option as t}from"../option/index.js";const n=(e,t)=>t===e?!0:typeof t==`function`?t(e):t&&typeof t==`object`&&`_`in t?t._(e):typeof t==`object`&&t&&typeof e==`object`&&e?Object.entries(t).every(([t,r])=>{let i=e[t];return n(i,r)}):!1,r=e=>{let i=(e,t)=>typeof e==`function`?e(t):e,a=()=>{for(let{pattern:t,result:r}of e.patterns)if(n(e.value,t))return{matched:!0,result:i(r,e.value)};return{matched:!1}},o={case:(t,a)=>e.resolved?o:n(e.value,t)?r({value:e.value,resolved:!0,result:i(a,e.value),patterns:[]}):r({...e,patterns:[...e.patterns,{pattern:t,result:a}]}),caseValue:(t,n)=>{if(e.resolved)return o;if(e.value===t){let t=typeof n==`function`?n():n;return r({value:e.value,resolved:!0,result:t,patterns:[]})}return o},caseValues:(t,n)=>{if(e.resolved)return o;if(t.includes(e.value)){let t=typeof n==`function`?n():n;return r({value:e.value,resolved:!0,result:t,patterns:[]})}return o},when:(e,t)=>o.case(e,t),caseAny:(t,a)=>{if(e.resolved)return o;for(let o of t)if(n(e.value,o))return r({value:e.value,resolved:!0,result:i(a,e.value),patterns:[]});return r({...e,patterns:[...e.patterns,...t.map(e=>({pattern:e,result:a}))]})},default:t=>e.resolved?e.result:i(t,e.value),exhaustive:()=>{if(e.resolved)return e.result;let t=a();if(!t.matched)throw Error(`Non-exhaustive match. No pattern matched value: ${JSON.stringify(e.value)}`);return t.result},orThrow:t=>{if(e.resolved)return e.result;let n=a();if(!n.matched)throw Error(t??`No matching pattern for value: ${JSON.stringify(e.value)}`);return n.result},toOption:()=>{if(e.resolved)return t(e.result);let n=a();return n.matched?t(n.result):t.none()}};return o},i=e=>{let t=(e,t)=>typeof e==`function`?e(t):e;return{case:(i,a)=>{let o={value:e,resolved:!1,patterns:[{pattern:i,result:a}]};return n(e,i)?r({...o,resolved:!0,result:t(a,e)}):r(o)},caseValue:(t,n)=>{if(e===t){let t=typeof n==`function`?n():n;return r({value:e,resolved:!0,result:t,patterns:[]})}return r({value:e,resolved:!1,patterns:[]})},caseValues:(t,n)=>{if(t.includes(e)){let t=typeof n==`function`?n():n;return r({value:e,resolved:!0,result:t,patterns:[]})}return r({value:e,resolved:!1,patterns:[]})},when:(n,i)=>{let a={value:e,resolved:!1,patterns:[{pattern:n,result:i}]};return n(e)?r({...a,resolved:!0,result:t(i,e)}):r(a)},caseAny:(i,a)=>{for(let o of i)if(n(e,o))return r({value:e,resolved:!0,result:t(a,e),patterns:i.map(e=>({pattern:e,result:a}))});return r({value:e,resolved:!1,patterns:i.map(e=>({pattern:e,result:a}))})}}},a=e(e=>i(e),{exhaustive:e=>t=>{let n=e[t];if(n===void 0)throw Error(`No case defined for value: ${String(t)}`);return n},partial:e=>({withDefault:t=>n=>{let r=e[n];return r===void 0?typeof t==`function`?t(n):t:typeof r==`function`?r(n):r}}),withGuards:e=>({withDefault:t=>n=>{for(let[t,r]of e)if(t(n))return typeof r==`function`?r(n):r;return typeof t==`function`?t(n):t}}),struct:()=>{let e=[],t={case:(n,r)=>(e.push({pattern:n,handler:r}),t),build:()=>t=>{for(let{pattern:r,handler:i}of e)if(n(t,r))return i(t);throw Error(`No matching pattern for value: ${JSON.stringify(t)}`)}};return t},builder:()=>{let e=[],t,r={case:(t,n)=>(e.push({pattern:t,result:n}),r),when:(t,n)=>(e.push({pattern:t,result:n}),r),default:r=>(t=r,{build:()=>r=>{for(let{pattern:t,result:i}of e)if(n(r,t))return typeof i==`function`?i(r):i;if(t!==void 0)return typeof t==`function`?t(r):t;throw Error(`No matching pattern for value: ${JSON.stringify(r)}`)}})};return r}});export{a as Match};
|
|
@@ -1,2 +1,3 @@
|
|
|
1
|
-
import {
|
|
2
|
-
|
|
1
|
+
import { Cond, CondCompanion } from "./Cond.js";
|
|
2
|
+
import { Match, MatchCompanion, UntypedMatch } from "./Match.js";
|
|
3
|
+
export { Cond, CondCompanion, Match, MatchCompanion, UntypedMatch };
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{Cond as e}from"./Cond.js";import{Match as t}from"./Match.js";export{e as Cond,t as Match};
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import { DoResult } from "../../do/protocol.js";
|
|
2
|
+
/**
|
|
3
|
+
* Base Object from which most other objects inherit
|
|
4
|
+
* Now includes automatic Do-notation support via doUnwrap method
|
|
5
|
+
* @param type - The type name for the object
|
|
6
|
+
* @param body - The implementation body
|
|
7
|
+
*/
|
|
8
|
+
export declare function Base<T extends Record<string, unknown>>(type: string, body: T): T & {
|
|
9
|
+
toString(): string;
|
|
10
|
+
doUnwrap(): DoResult<unknown>;
|
|
11
|
+
_tag: string;
|
|
12
|
+
};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{Typeable as e}from"../../typeable/Typeable.js";function t(t,n){return{...e({_tag:t,impl:n}),toString(){return`${t}()`},doUnwrap(){if(`isSome`in n&&`isNone`in n){if(typeof n.isSome==`function`&&n.isSome()&&`get`in n&&typeof n.get==`function`)return{ok:!0,value:n.get()};if(typeof n.isNone==`function`&&n.isNone())return{ok:!1,empty:!0}}if(`isLeft`in n&&`isRight`in n){if(typeof n.isRight==`function`&&n.isRight()&&`value`in n)return{ok:!0,value:n.value};if(typeof n.isLeft==`function`&&n.isLeft()&&`value`in n)return{ok:!1,empty:!1,error:n.value}}if(`isSuccess`in n&&`isFailure`in n){if(typeof n.isSuccess==`function`&&n.isSuccess()&&`get`in n&&typeof n.get==`function`)return{ok:!0,value:n.get()};if(typeof n.isFailure==`function`&&n.isFailure()&&`getError`in n&&typeof n.getError==`function`)return{ok:!1,empty:!1,error:n.getError()}}return`isEmpty`in n&&`head`in n&&typeof n.head==`function`?(typeof n.isEmpty==`function`?n.isEmpty():n.isEmpty===!0)?{ok:!1,empty:!0}:{ok:!0,value:n.head()}:{ok:!0,value:n}}}}export{t as Base};
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
import { Typeable } from "../../typeable/Typeable.js";
|
|
2
|
+
/**
|
|
3
|
+
* The identifier name for Throwable type
|
|
4
|
+
*/
|
|
5
|
+
export declare const NAME: "Throwable";
|
|
6
|
+
/**
|
|
7
|
+
* @internal
|
|
8
|
+
*/
|
|
9
|
+
export type ThrowableType = Error & Typeable<typeof NAME> & {
|
|
10
|
+
readonly data?: unknown;
|
|
11
|
+
readonly cause?: Error;
|
|
12
|
+
readonly taskInfo?: {
|
|
13
|
+
name: string;
|
|
14
|
+
description: string;
|
|
15
|
+
};
|
|
16
|
+
};
|
|
17
|
+
export declare class Throwable extends Error implements ThrowableType {
|
|
18
|
+
readonly _tag: typeof NAME;
|
|
19
|
+
readonly data?: unknown;
|
|
20
|
+
readonly cause?: Error;
|
|
21
|
+
readonly taskInfo?: {
|
|
22
|
+
name: string;
|
|
23
|
+
description: string;
|
|
24
|
+
};
|
|
25
|
+
protected constructor(message: string, options?: {
|
|
26
|
+
data?: unknown | undefined;
|
|
27
|
+
cause?: Error | undefined;
|
|
28
|
+
stack?: string | undefined;
|
|
29
|
+
taskInfo?: {
|
|
30
|
+
name: string;
|
|
31
|
+
description: string;
|
|
32
|
+
} | undefined;
|
|
33
|
+
});
|
|
34
|
+
static apply(srcError: unknown, data?: unknown, taskInfo?: {
|
|
35
|
+
name: string;
|
|
36
|
+
description: string;
|
|
37
|
+
}): ThrowableType;
|
|
38
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const e=`Throwable`;var t=class t extends Error{constructor(t,n){super(t,{cause:n?.cause}),this._tag=e,this.name=n?.taskInfo?.name??`Throwable`,Object.defineProperties(this,{_tag:{value:e,writable:!1,configurable:!1},data:{value:n?.data,writable:!1,configurable:!1},taskInfo:{value:n?.taskInfo,writable:!1,configurable:!1},name:{value:n?.taskInfo?.name??`Throwable`,writable:!1,configurable:!1}}),n?.cause&&Object.defineProperty(this,"cause",{value:n.cause,writable:!1,configurable:!1}),n?.stack?this.stack=n.stack:Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor)}static apply(e,n,r){if(e instanceof Error){let i=new t(e.message,{data:n,cause:e.cause??void 0,stack:e.stack??void 0,taskInfo:r});for(let t of Object.keys(e))if(!(t in i)){let n=i;n[t]=e[t]}return i}if(e&&typeof e==`object`){let i=e,a=typeof i.message==`string`?i.message:typeof i.error==`string`?i.error:`Object error: ${JSON.stringify(i,Object.getOwnPropertyNames(i).filter(e=>i[e]!==void 0))}`,o=i.cause instanceof Error?i.cause:void 0,s=new t(a,{data:n??i,cause:o,taskInfo:r});for(let e of Object.keys(i))if(!(e in s)){let t=s;t[e]=i[e]}return s}if(typeof e==`function`){let i=e.name??`anonymous function`,a=e.toString().substring(0,100)+(e.toString().length>100?`...`:``);return new t(`Function error: ${i}`,{data:n??{functionType:typeof e,functionName:i,functionString:a},taskInfo:r})}let i=typeof e,a=e===null?`null`:e===void 0?`undefined`:String(e);if(i===`number`){let a=e,o=Number.isNaN(a)?`Number error: NaN`:Number.isFinite(a)?`Number error: ${a}`:`Number error: ${a>0?`Infinity`:`-Infinity`}`;return new t(o,{data:n??{errorType:i,errorValue:a,originalError:e},taskInfo:r})}if(i===`bigint`)return new t(`BigInt error: ${e}n`,{data:n??{errorType:i,errorValue:String(e),originalError:e},taskInfo:r});if(i===`boolean`)return new t(`Boolean error: ${e}`,{data:n??{errorType:i,errorValue:e,originalError:e},taskInfo:r});if(i===`symbol`){let a=e.description??`unnamed symbol`;return new t(`Symbol error: Symbol(${a})`,{data:n??{errorType:i,symbolDescription:a,originalError:e},taskInfo:r})}let o=typeof e==`string`?e:`${i.charAt(0).toUpperCase()+i.slice(1)} error: ${a}`;return new t(o,{data:n??{errorType:i,errorValue:a,originalError:e},taskInfo:r})}};export{e as NAME,t as Throwable};
|