functype 1.27.2 → 2.1.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 +70 -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 +1150 -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 +290 -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 +1263 -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 +8 -13
- 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/README.md
CHANGED
|
@@ -1,3 +1,10 @@
|
|
|
1
|
+
<p align="center">
|
|
2
|
+
<picture>
|
|
3
|
+
<source media="(prefers-color-scheme: dark)" srcset="https://functype.org/logo-dark.svg">
|
|
4
|
+
<img src="https://functype.org/logo.svg" alt="functype" height="72">
|
|
5
|
+
</picture>
|
|
6
|
+
</p>
|
|
7
|
+
|
|
1
8
|
# Functype
|
|
2
9
|
|
|
3
10
|
[](https://www.npmjs.com/package/functype)
|
|
@@ -36,7 +43,7 @@ npx functype --json # JSON output for programmatic use
|
|
|
36
43
|
- **List, Set, Map**: Immutable collection types with functional operators
|
|
37
44
|
- **Try Type**: Safely execute operations that might throw exceptions
|
|
38
45
|
- **Do-notation**: Scala-like for-comprehensions with **optimized List performance** (up to 12x faster than traditional flatMap)
|
|
39
|
-
- **
|
|
46
|
+
- **IO**: Lazy effects with typed errors, dependency injection and cancellation
|
|
40
47
|
- **Http**: Typed HTTP fetch wrapper returning IO effects with HttpError ADT, auto content-type detection, and configurable clients
|
|
41
48
|
- **Lazy**: Deferred computation with memoization
|
|
42
49
|
- **Tuple**: Type-safe fixed-length arrays
|
|
@@ -58,6 +65,8 @@ functype deliberately is **not** a framework — no fiber runtime, no structured
|
|
|
58
65
|
|
|
59
66
|
## Installation
|
|
60
67
|
|
|
68
|
+
Upgrading from 1.x? [functype.org/upgrading-to-2](https://functype.org/upgrading-to-2) lists what to change.
|
|
69
|
+
|
|
61
70
|
```bash
|
|
62
71
|
# NPM
|
|
63
72
|
npm install functype
|
|
@@ -72,20 +81,15 @@ pnpm add functype
|
|
|
72
81
|
bun add functype
|
|
73
82
|
```
|
|
74
83
|
|
|
75
|
-
### Bundle Size
|
|
84
|
+
### Bundle Size
|
|
76
85
|
|
|
77
|
-
|
|
86
|
+
`dist` has one file per module, so a bundler keeps only what you use. An Option-only program ships 5.7 KB gzipped; one using `IO.gen`, Either, Option and List ships 11.5 KB. Root and subpath imports bundle the same:
|
|
78
87
|
|
|
79
88
|
```typescript
|
|
80
|
-
//
|
|
81
|
-
import { Option } from "functype/option"
|
|
82
|
-
import { Either } from "functype/either"
|
|
83
|
-
|
|
84
|
-
// Direct constructor imports (smallest bundle)
|
|
85
|
-
import { some, none } from "functype/option"
|
|
89
|
+
import { Option } from "functype/option" // bundles the same as importing from "functype"
|
|
86
90
|
```
|
|
87
91
|
|
|
88
|
-
For
|
|
92
|
+
For the measured sizes and how they are checked, see the [Bundle Size guide](docs/BUNDLE_OPTIMIZATION.md).
|
|
89
93
|
|
|
90
94
|
## Usage Examples
|
|
91
95
|
|
|
@@ -261,83 +265,56 @@ const asyncResult = await DoAsync(async function* () {
|
|
|
261
265
|
- Always returns the type of the first yielded monad
|
|
262
266
|
- Mixed types supported via Reshapeable interface
|
|
263
267
|
|
|
264
|
-
###
|
|
268
|
+
### IO
|
|
265
269
|
|
|
266
|
-
|
|
270
|
+
`IO<R, E, A>` is a lazy effect: nothing runs until you call a `run` method. `E` is the typed error and `R` the services it needs. functype 2.0 deleted `Task`, and IO replaces it.
|
|
267
271
|
|
|
268
272
|
```typescript
|
|
269
|
-
import {
|
|
273
|
+
import { IO } from "functype"
|
|
270
274
|
|
|
271
|
-
|
|
272
|
-
const syncResult = Task().Sync(() => "success")
|
|
273
|
-
// Returns: TaskSuccess<string> (extends TaskOutcome<string>)
|
|
275
|
+
type User = { id: string; name: string }
|
|
274
276
|
|
|
275
|
-
const
|
|
276
|
-
|
|
277
|
+
const loadUser = (id: string) =>
|
|
278
|
+
IO.tryPromise({
|
|
279
|
+
// the run's signal reaches fetch, so cancelling stops the request
|
|
280
|
+
try: (signal) => fetch(`/api/users/${id}`, { signal }).then((r) => r.json() as Promise<User>),
|
|
281
|
+
catch: (error) => new Error(`Failed to load ${id}: ${String(error)}`),
|
|
282
|
+
})
|
|
277
283
|
|
|
278
|
-
//
|
|
279
|
-
const
|
|
280
|
-
if (Math.random() > 0.5) {
|
|
281
|
-
return Ok("success") // Explicit success
|
|
282
|
-
}
|
|
283
|
-
return Err<string>("failed") // Explicit failure
|
|
284
|
-
})
|
|
285
|
-
|
|
286
|
-
// Auto-wrapping: raw values become Ok, thrown errors become Err
|
|
287
|
-
const autoWrapped = await Task().Async(async () => {
|
|
288
|
-
if (condition) {
|
|
289
|
-
return "raw value" // Auto-wrapped as Ok("raw value")
|
|
290
|
-
}
|
|
291
|
-
throw new Error("failed") // Auto-wrapped as Err(error)
|
|
292
|
-
})
|
|
284
|
+
// Nothing has run yet. run() gives an Either<Error, User>
|
|
285
|
+
const user = await loadUser("42").retry(2).timeout(5000).run()
|
|
293
286
|
|
|
294
|
-
//
|
|
295
|
-
const
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
async (error) => Ok("recovered from error"), // Recovery!
|
|
300
|
-
)
|
|
301
|
-
|
|
302
|
-
// Working with results
|
|
303
|
-
if (asyncResult.isSuccess()) {
|
|
304
|
-
console.log(asyncResult.value) // Access the success value
|
|
305
|
-
} else {
|
|
306
|
-
console.error(asyncResult.error) // Access the error (Throwable)
|
|
307
|
-
}
|
|
308
|
-
|
|
309
|
-
// Chaining with TaskOutcome
|
|
310
|
-
const chainedResult = await Task().Async(async () => {
|
|
311
|
-
const firstResult = await Task().Async(async () => "first")
|
|
312
|
-
if (firstResult.isFailure()) {
|
|
313
|
-
return firstResult // Propagate failure
|
|
314
|
-
}
|
|
315
|
-
|
|
316
|
-
const secondResult = await Task().Async(async () => "second")
|
|
317
|
-
if (secondResult.isFailure()) {
|
|
318
|
-
return secondResult
|
|
319
|
-
}
|
|
320
|
-
|
|
321
|
-
return Ok(`${firstResult.value} + ${secondResult.value}`)
|
|
322
|
-
})
|
|
287
|
+
// Cancel with a handle, or with your own AbortSignal
|
|
288
|
+
const { result, cancel } = loadUser("42").runCancellable()
|
|
289
|
+
const controller = new AbortController()
|
|
290
|
+
const exit = await loadUser("42").runExit({ signal: controller.signal }) // Success | Failure | Die | Interrupted
|
|
291
|
+
```
|
|
323
292
|
|
|
324
|
-
|
|
325
|
-
const fetchUserAPI = (userId: string): Promise<User> => fetch(`/api/users/${userId}`).then((r) => r.json())
|
|
293
|
+
#### Tracing
|
|
326
294
|
|
|
327
|
-
|
|
328
|
-
// Returns: (userId: string) => Promise<TaskOutcome<User>>
|
|
295
|
+
`withSpan(name, attributes?)` runs an effect in a span, and a `withSpan` inside it nests under it without being passed a parent. functype ships only the contract, `SpanTracer`: with no tracer provided, `withSpan` does nothing. A tracer has three methods. `start(name, attributes, parent)` opens a span, `run(span, fn)` runs the body with the span active, and `end(span, exit)` closes it once, for every outcome.
|
|
329
296
|
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
297
|
+
```typescript
|
|
298
|
+
import { context, type Span, SpanStatusCode, trace } from "@opentelemetry/api" // your dependency, not functype's
|
|
299
|
+
import { SpanTracer } from "functype"
|
|
300
|
+
|
|
301
|
+
const otel = trace.getTracer("my-app")
|
|
302
|
+
const otelTracer: SpanTracer<Span> = {
|
|
303
|
+
start: (name, attributes, parent) =>
|
|
304
|
+
otel.startSpan(name, { attributes }, parent ? trace.setSpan(context.active(), parent) : context.active()),
|
|
305
|
+
run: (span, fn) => context.with(trace.setSpan(context.active(), span), fn), // makes the span active
|
|
306
|
+
end: (span, exit) => {
|
|
307
|
+
if (exit._tag === "Failure" || exit._tag === "Die") span.setStatus({ code: SpanStatusCode.ERROR })
|
|
308
|
+
span.end()
|
|
309
|
+
},
|
|
333
310
|
}
|
|
334
311
|
|
|
335
|
-
//
|
|
336
|
-
|
|
337
|
-
// Success → resolves with value
|
|
338
|
-
// Failure → rejects with error
|
|
312
|
+
// Provide the tracer outside the spans
|
|
313
|
+
await loadUser("42").withSpan("loadUser", { "user.id": "42" }).provideService(SpanTracer, otelTracer).run()
|
|
339
314
|
```
|
|
340
315
|
|
|
316
|
+
This bridge is a sketch, not a package: functype has no OpenTelemetry dependency. Because `run` makes the span active, a log sink inside `withSpan` reads the trace IDs with `trace.getActiveSpan()`. That needs a registered OpenTelemetry context manager, which the Node SDK sets up; without one, `context.with` runs the body with no span active. The [IO docs](https://functype.org/io) cover nesting, cancellation and `runSync`.
|
|
317
|
+
|
|
341
318
|
### Branded Types
|
|
342
319
|
|
|
343
320
|
```typescript
|
|
@@ -405,7 +382,7 @@ const tracer: Tracer = { emit: (e) => void events.push(e) }
|
|
|
405
382
|
|
|
406
383
|
TracedOption(user, tracer, "span-1")
|
|
407
384
|
.map((u) => u.name.trim(), "trim")
|
|
408
|
-
.
|
|
385
|
+
.getOrElse(() => "anonymous", "fallback")
|
|
409
386
|
```
|
|
410
387
|
|
|
411
388
|
## Conditional Programming
|
|
@@ -696,7 +673,7 @@ list.forEach(console.log) // Logs: 1, 2, 3, 4, 5
|
|
|
696
673
|
|
|
697
674
|
## ESLint Plugin
|
|
698
675
|
|
|
699
|
-
[`eslint-plugin-functype`](https://functype.org/eslint) enforces these patterns.
|
|
676
|
+
[`eslint-plugin-functype`](https://functype.org/eslint) enforces these patterns. Its one preset, `recommended`, sets every rule to `error` or `off`, so a finding fails the build rather than sit as a warning. Declare boundaries with `Wire<T>` and `@interop`, and write bug checks as `invariant(cond, msg)`, instead of `eslint-disable`.
|
|
700
677
|
|
|
701
678
|
## Feature Matrix
|
|
702
679
|
|
|
@@ -719,20 +696,25 @@ const mappedValue = option.map((x) => x.toString())
|
|
|
719
696
|
Functype provides utilities for improved error visualization and logging:
|
|
720
697
|
|
|
721
698
|
```typescript
|
|
722
|
-
import {
|
|
699
|
+
import { Throwable, createErrorSerializer, formatError, formatErrorChain } from "functype"
|
|
723
700
|
|
|
724
|
-
//
|
|
725
|
-
const
|
|
726
|
-
|
|
701
|
+
// A failure in a named step, wrapping the error below it as its cause
|
|
702
|
+
const dbError = Throwable.apply(new Error("Database connection failed"), undefined, {
|
|
703
|
+
name: "DbQuery",
|
|
704
|
+
description: "Load the user row",
|
|
727
705
|
})
|
|
728
|
-
|
|
729
|
-
|
|
730
|
-
|
|
706
|
+
const error = Throwable.apply(new Error("Failed to fetch user", { cause: dbError }), undefined, {
|
|
707
|
+
name: "UserFetch",
|
|
708
|
+
description: "Fetch user data",
|
|
731
709
|
})
|
|
732
710
|
|
|
711
|
+
formatErrorChain(error, { includeTasks: true })
|
|
712
|
+
// [UserFetch] Failed to fetch user
|
|
713
|
+
// ↳ [DbQuery] Database connection failed
|
|
714
|
+
|
|
733
715
|
// Format the error for console display
|
|
734
716
|
console.error(
|
|
735
|
-
formatError(
|
|
717
|
+
formatError(error, {
|
|
736
718
|
includeTasks: true,
|
|
737
719
|
includeStackTrace: true,
|
|
738
720
|
colors: true,
|
|
@@ -750,7 +732,7 @@ const logger = pino({
|
|
|
750
732
|
// Log the error with full context
|
|
751
733
|
logger.error(
|
|
752
734
|
{
|
|
753
|
-
err:
|
|
735
|
+
err: error,
|
|
754
736
|
requestId: "req-123",
|
|
755
737
|
},
|
|
756
738
|
"Failed to fetch user data",
|
|
@@ -857,16 +839,16 @@ For more details, see the [Error Formatting Guide](docs/error-formatting.md).
|
|
|
857
839
|
Work that shipped but wasn't captured in the planned roadmap above:
|
|
858
840
|
|
|
859
841
|
- [x] **Scala-aligned covariance for the container family** (0.57.2 → 0.60.0)
|
|
860
|
-
- ✓ `<out T>` / `<out K, out V>` across Option, Either, Try, List, Set, Map, Lazy, LazyList, Tuple, Identity
|
|
842
|
+
- ✓ `<out T>` / `<out K, out V>` across Option, Either, Try, List, Set, Map, Lazy, LazyList, Tuple, Identity
|
|
861
843
|
- ✓ `FunctypeSum` hierarchy separating sum types (Either, Try) from iterables
|
|
862
844
|
- ✓ `Widen<A, B>` conditional-type helper enforcing Scala's `[B >: A]` lower-bound semantics in `reduce` / `reduceRight`
|
|
863
|
-
- ✓ Method-level widening patterns (`
|
|
845
|
+
- ✓ Method-level widening patterns (`orElse`, `getOrElse`, `recover`, `add`, `concat`, etc.)
|
|
864
846
|
- ✓ Contributor guide at [`docs/variance-guide.md`](docs/variance-guide.md)
|
|
865
847
|
- Deferred: ZIO-style `<in R, out E, out A>` for IO
|
|
866
848
|
- [x] **Do-notation with generator comprehensions** (`src/do/`)
|
|
867
849
|
- [x] **HTTP module** — typed fetch wrapper with validator support (`src/fetch/` — Http, HttpClient, HttpError, HttpRequest)
|
|
868
850
|
- [x] **Throwable** — enhanced error wrapper preserving stack traces and context (`src/core/throwable/`)
|
|
869
|
-
- [x] **Task / TaskOutcome** —
|
|
851
|
+
- [x] **Task / TaskOutcome** — deleted in 2.0; IO's `runCancellable`, `runExit({ signal })` and `interruptOn` replace it
|
|
870
852
|
- [x] **IO effect system companions** — Context, Tag, Layer, Exit, TestClock (`src/io/`)
|
|
871
853
|
- [x] **Ref** — mutable reference for controlled mutability (`src/ref/`)
|
|
872
854
|
- [x] **Identity** — trivial covariant container (`src/identity/`)
|
|
@@ -875,7 +857,7 @@ Work that shipped but wasn't captured in the planned roadmap above:
|
|
|
875
857
|
- [x] **MCP server for functype documentation** (`mcp-server/`)
|
|
876
858
|
- [x] **CLI — `npx functype`** (`src/cli/`)
|
|
877
859
|
- [x] **Claude Code skills** — `functype` (user guide) and `functype-developer` (contributor guide)
|
|
878
|
-
- [x] **Serialization infrastructure** — JSON /
|
|
860
|
+
- [x] **Serialization infrastructure** — JSON / binary (`src/serialization/`)
|
|
879
861
|
|
|
880
862
|
## Claude Code Skills
|
|
881
863
|
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
var e=Object.defineProperty,t=(t,n)=>{let r=Object.setPrototypeOf({},null);for(var i in t)e(r,i,{get:t[i],enumerable:!0});return n&1||e(r,Symbol.toStringTag,{value:`Module`}),n&2?r:Object.preventExtensions(r)};export{t as __exportAll};
|
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
import { Either } from "../either/index.js";
|
|
2
|
+
import { Option } from "../option/index.js";
|
|
3
|
+
import { Brand } from "./index.js";
|
|
4
|
+
export type ValidatedBrand<K extends string, T> = Brand<K, T> & {
|
|
5
|
+
readonly __validated: true;
|
|
6
|
+
};
|
|
7
|
+
export interface ValidatedBrandCompanion<K extends string, T> {
|
|
8
|
+
readonly brand: K;
|
|
9
|
+
readonly validate: (value: T) => boolean;
|
|
10
|
+
readonly of: (value: T) => Option<ValidatedBrand<K, T>>;
|
|
11
|
+
readonly from: (value: T) => Either<string, ValidatedBrand<K, T>>;
|
|
12
|
+
readonly unsafeOf: (value: T) => ValidatedBrand<K, T>;
|
|
13
|
+
readonly is: (value: unknown) => value is ValidatedBrand<K, T>;
|
|
14
|
+
readonly unwrap: (branded: Brand<K, T>) => T;
|
|
15
|
+
readonly refine: <K2 extends string>(brand: K2, validate: (value: Brand<K, T>) => boolean) => ValidatedBrandCompanion<K2, Brand<K, T>>;
|
|
16
|
+
}
|
|
17
|
+
/**
|
|
18
|
+
* Create a validated brand with runtime validation
|
|
19
|
+
* @example
|
|
20
|
+
* const Email = ValidatedBrand("Email", (s: string) => /^[^@]+@[^@]+\.[^@]+$/.test(s))
|
|
21
|
+
* const email = Email.of("user@example.com") // Some(Brand<"Email", string>)
|
|
22
|
+
*
|
|
23
|
+
* @example
|
|
24
|
+
* // With Either for error messages
|
|
25
|
+
* const Port = ValidatedBrand("Port", (n: number) => n >= 1 && n <= 65535)
|
|
26
|
+
* const result = Port.from(8080) // Right(Brand<"Port", number>)
|
|
27
|
+
* const error = Port.from(70000) // Left("Invalid Port: validation failed")
|
|
28
|
+
*
|
|
29
|
+
* @example
|
|
30
|
+
* // Type guard usage
|
|
31
|
+
* const value: unknown = "test@example.com"
|
|
32
|
+
* if (Email.is(value)) {
|
|
33
|
+
* // value is Brand<"Email", string>
|
|
34
|
+
* }
|
|
35
|
+
*
|
|
36
|
+
* @example
|
|
37
|
+
* // Best Practice: Use same brand name for seamless conversion
|
|
38
|
+
* // ValidatedBrand extends Brand, so when using the same brand name,
|
|
39
|
+
* // no casting is needed for conversion
|
|
40
|
+
* const ValidatedUserId = ValidatedBrand("UserId", (s: string) => s.length > 0)
|
|
41
|
+
* type ValidatedUserId = ReturnType<typeof ValidatedUserId.of> extends Option<infer T> ? T : never
|
|
42
|
+
* type UserId = Brand<"UserId", string>
|
|
43
|
+
*
|
|
44
|
+
* const toSimpleUserId = (id: ValidatedUserId): UserId => id // No cast needed!
|
|
45
|
+
*
|
|
46
|
+
* // Avoid different brand names which require casting:
|
|
47
|
+
* // ❌ ValidatedBrand("ValidatedUserId", ...) + Brand<"UserId", string>
|
|
48
|
+
* // ✅ ValidatedBrand("UserId", ...) + Brand<"UserId", string>
|
|
49
|
+
*/
|
|
50
|
+
export declare function ValidatedBrand<K extends string, T>(brand: K, validate: (value: T) => boolean): ValidatedBrandCompanion<K, T>;
|
|
51
|
+
/**
|
|
52
|
+
* Positive number brand (> 0)
|
|
53
|
+
* @example
|
|
54
|
+
* const price = PositiveNumber.of(19.99) // Some(Brand<"PositiveNumber", number>)
|
|
55
|
+
* const invalid = PositiveNumber.of(-5) // None
|
|
56
|
+
* const checked = PositiveNumber.from(0) // Left("Invalid PositiveNumber: validation failed")
|
|
57
|
+
*/
|
|
58
|
+
export declare const PositiveNumber: ValidatedBrandCompanion<"PositiveNumber", number>;
|
|
59
|
+
export declare const NonNegativeNumber: ValidatedBrandCompanion<"NonNegativeNumber", number>;
|
|
60
|
+
export declare const IntegerNumber: ValidatedBrandCompanion<"IntegerNumber", number>;
|
|
61
|
+
export declare const PositiveInteger: ValidatedBrandCompanion<"PositiveInteger", Brand<"PositiveNumber", number>>;
|
|
62
|
+
/**
|
|
63
|
+
* Non-empty string brand
|
|
64
|
+
* @example
|
|
65
|
+
* const name = NonEmptyString.of("John") // Some(Brand<"NonEmptyString", string>)
|
|
66
|
+
* const empty = NonEmptyString.of("") // None
|
|
67
|
+
*/
|
|
68
|
+
export declare const NonEmptyString: ValidatedBrandCompanion<"NonEmptyString", string>;
|
|
69
|
+
/**
|
|
70
|
+
* Email address brand with basic validation
|
|
71
|
+
* @example
|
|
72
|
+
* const email = EmailAddress.of("user@example.com") // Some(Brand<"EmailAddress", string>)
|
|
73
|
+
* const invalid = EmailAddress.of("not-an-email") // None
|
|
74
|
+
*
|
|
75
|
+
* @example
|
|
76
|
+
* // Using with forms
|
|
77
|
+
* const processEmail = (input: string) => {
|
|
78
|
+
* return EmailAddress.from(input)
|
|
79
|
+
* .map(email => sendWelcomeEmail(email))
|
|
80
|
+
* .getOrElse(() => "Invalid email address")
|
|
81
|
+
* }
|
|
82
|
+
*/
|
|
83
|
+
export declare const EmailAddress: ValidatedBrandCompanion<"EmailAddress", string>;
|
|
84
|
+
export declare const UrlString: ValidatedBrandCompanion<"UrlString", string>;
|
|
85
|
+
export declare const UUID: ValidatedBrandCompanion<"UUID", string>;
|
|
86
|
+
export declare const ISO8601Date: ValidatedBrandCompanion<"ISO8601Date", string>;
|
|
87
|
+
/**
|
|
88
|
+
* Create a number brand with min/max bounds
|
|
89
|
+
* @example
|
|
90
|
+
* const Percentage = BoundedNumber("Percentage", 0, 100)
|
|
91
|
+
* const valid = Percentage.of(75) // Some(Brand<"Percentage", number>)
|
|
92
|
+
* const invalid = Percentage.of(150) // None
|
|
93
|
+
*
|
|
94
|
+
* @example
|
|
95
|
+
* const Port = BoundedNumber("Port", 1, 65535)
|
|
96
|
+
* const httpPort = Port.unsafeOf(80) // Brand<"Port", number>
|
|
97
|
+
* // Port.unsafeOf(70000) // throws Error
|
|
98
|
+
*/
|
|
99
|
+
export declare function BoundedNumber(brand: string, min: number, max: number): ValidatedBrandCompanion<string, number>;
|
|
100
|
+
/**
|
|
101
|
+
* Create a string brand with length constraints
|
|
102
|
+
* @example
|
|
103
|
+
* const Username = BoundedString("Username", 3, 20)
|
|
104
|
+
* const valid = Username.of("johndoe") // Some(Brand<"Username", string>)
|
|
105
|
+
* const tooShort = Username.of("jo") // None
|
|
106
|
+
* const tooLong = Username.of("verylongusernamethatexceedslimit") // None
|
|
107
|
+
*/
|
|
108
|
+
export declare function BoundedString(brand: string, minLength: number, maxLength: number): ValidatedBrandCompanion<string, string>;
|
|
109
|
+
/**
|
|
110
|
+
* Create a string brand that matches a regex pattern
|
|
111
|
+
* @example
|
|
112
|
+
* const HexColor = PatternString("HexColor", /^#[0-9a-f]{6}$/i)
|
|
113
|
+
* const red = HexColor.of("#ff0000") // Some(Brand<"HexColor", string>)
|
|
114
|
+
* const invalid = HexColor.of("red") // None
|
|
115
|
+
*
|
|
116
|
+
* @example
|
|
117
|
+
* const PhoneNumber = PatternString("PhoneNumber", /^\+?[1-9]\d{1,14}$/)
|
|
118
|
+
* const phone = PhoneNumber.from("+1234567890")
|
|
119
|
+
* .map(p => formatPhoneNumber(p))
|
|
120
|
+
* .getOrElse(() => "Invalid phone number")
|
|
121
|
+
*/
|
|
122
|
+
export declare function PatternString(brand: string, pattern: RegExp): ValidatedBrandCompanion<string, string>;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{Left as e,Right as t}from"../either/index.js";import{Option as n}from"../option/index.js";import{Brand as r}from"./index.js";function i(a,o){return{brand:a,validate:o,of:e=>o(e)?n(r(a,e)):n.none(),from:n=>o(n)?t(r(a,n)):e(`Invalid ${a}: validation failed`),unsafeOf:e=>{if(!o(e))throw Error(`Invalid ${a}: validation failed`);return r(a,e)},is:e=>{try{return o(e)}catch{return!1}},unwrap:e=>e,refine:(e,t)=>i(e,e=>o(e)&&t(e))}}const a=i(`PositiveNumber`,e=>e>0),o=i(`NonNegativeNumber`,e=>e>=0),s=i(`IntegerNumber`,e=>Number.isInteger(e)),c=a.refine(`PositiveInteger`,e=>Number.isInteger(e)),l=i(`NonEmptyString`,e=>e.length>0),u=i(`EmailAddress`,e=>/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(e)),d=i(`UrlString`,e=>{try{return new URL(e),!0}catch{return!1}}),f=i(`UUID`,e=>/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(e)),p=i(`ISO8601Date`,e=>!isNaN(Date.parse(e))&&/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}/.test(e));function m(e,t,n){return i(e,e=>e>=t&&e<=n)}function h(e,t,n){return i(e,e=>e.length>=t&&e.length<=n)}function g(e,t){return i(e,e=>t.test(e))}export{m as BoundedNumber,h as BoundedString,u as EmailAddress,p as ISO8601Date,s as IntegerNumber,l as NonEmptyString,o as NonNegativeNumber,g as PatternString,c as PositiveInteger,a as PositiveNumber,f as UUID,d as UrlString,i as ValidatedBrand};
|
package/dist/branded/index.d.ts
CHANGED
|
@@ -1,2 +1,52 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
1
|
+
export type Brand<K extends string, T> = T & {
|
|
2
|
+
readonly __brand: K;
|
|
3
|
+
};
|
|
4
|
+
export type Unwrap<T> = T extends Brand<string, infer U> ? U : T;
|
|
5
|
+
export type ExtractBrand<T> = T extends Brand<infer K, unknown> ? K : never;
|
|
6
|
+
/**
|
|
7
|
+
* Brand is a utility for creating nominal typing in TypeScript.
|
|
8
|
+
* It creates phantom types that exist only at compile time.
|
|
9
|
+
* At runtime, the branded value IS the primitive value.
|
|
10
|
+
*
|
|
11
|
+
* @param _brand
|
|
12
|
+
* @param value - The value to brand
|
|
13
|
+
* @returns The value with phantom type brand
|
|
14
|
+
*/
|
|
15
|
+
export declare function Brand<K extends string, T>(_brand: K, value: T): Brand<K, T>;
|
|
16
|
+
/**
|
|
17
|
+
* Helper to unwrap a branded value to its underlying type
|
|
18
|
+
* Works with both Brand and ValidatedBrand
|
|
19
|
+
* @param branded - The branded value (can be null or undefined)
|
|
20
|
+
* @returns The original value without the brand
|
|
21
|
+
*
|
|
22
|
+
* Note: Also exported as 'unwrap' from 'functype/branded' for convenience
|
|
23
|
+
*/
|
|
24
|
+
export declare function unwrapBrand<K extends string, T>(branded: Brand<K, T>): T;
|
|
25
|
+
export declare function unwrapBrand<K extends string, T>(branded: Brand<K, T> | null): T | null;
|
|
26
|
+
export declare function unwrapBrand<K extends string, T>(branded: Brand<K, T> | undefined): T | undefined;
|
|
27
|
+
export declare function unwrapBrand<K extends string, T>(branded: Brand<K, T> | null | undefined): T | null | undefined;
|
|
28
|
+
/**
|
|
29
|
+
* Type guard for checking if a value has a specific brand
|
|
30
|
+
* @param value - The value to check
|
|
31
|
+
* @param _brand - The brand to check for (unused at runtime)
|
|
32
|
+
* @returns True if the value has the specified brand
|
|
33
|
+
*
|
|
34
|
+
* Note: Since brands are phantom types that exist only at compile time,
|
|
35
|
+
* this function can only provide a runtime approximation. It always returns true
|
|
36
|
+
* for non-null values, as we have no way to actually check the brand at runtime.
|
|
37
|
+
* This function is primarily for API consistency and documentation purposes.
|
|
38
|
+
*/
|
|
39
|
+
export declare function hasBrand<K extends string, T>(value: unknown, _brand: K): value is Brand<K, T>;
|
|
40
|
+
/**
|
|
41
|
+
* Create a branded type constructor for a specific brand
|
|
42
|
+
* @param brand - The brand name
|
|
43
|
+
* @returns A function that brands values with the specified brand
|
|
44
|
+
*/
|
|
45
|
+
export declare function createBrander<K extends string, T>(brand: K): (value: T) => Brand<K, T>;
|
|
46
|
+
export type BrandedString<K extends string> = Brand<K, string>;
|
|
47
|
+
export type BrandedNumber<K extends string> = Brand<K, number>;
|
|
48
|
+
export type BrandedBoolean<K extends string> = Brand<K, boolean>;
|
|
49
|
+
export declare const BrandedString: <K extends string>(brand: K) => (value: string) => BrandedString<K>;
|
|
50
|
+
export declare const BrandedNumber: <K extends string>(brand: K) => (value: number) => BrandedNumber<K>;
|
|
51
|
+
export declare const BrandedBoolean: <K extends string>(brand: K) => (value: boolean) => BrandedBoolean<K>;
|
|
52
|
+
export { unwrapBrand as unwrap };
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Curated API data for CLI output, optimized for LLM consumption.
|
|
3
|
+
*
|
|
4
|
+
* `interfaces` arrays are composed of (a) the GENERATED_INTERFACES floor
|
|
5
|
+
* derived from each type's `extends` chain in source, plus (b) optional
|
|
6
|
+
* hand-curated additions for capabilities declared inline (e.g. `List.map`
|
|
7
|
+
* lives in the interface body, not via `extends Functor`). The data-sync
|
|
8
|
+
* spec enforces that no source-declared interface is dropped from this list.
|
|
9
|
+
*/
|
|
10
|
+
export declare const VERSION: string;
|
|
11
|
+
export interface TypeData {
|
|
12
|
+
description: string;
|
|
13
|
+
interfaces: string[];
|
|
14
|
+
methods: {
|
|
15
|
+
create?: string[];
|
|
16
|
+
transform?: string[];
|
|
17
|
+
extract?: string[];
|
|
18
|
+
check?: string[];
|
|
19
|
+
other?: string[];
|
|
20
|
+
};
|
|
21
|
+
}
|
|
22
|
+
export interface InterfaceData {
|
|
23
|
+
extends?: string;
|
|
24
|
+
description: string;
|
|
25
|
+
methods: string[];
|
|
26
|
+
}
|
|
27
|
+
export declare const TYPES: Record<string, TypeData>;
|
|
28
|
+
export declare const INTERFACES: Record<string, InterfaceData>;
|
|
29
|
+
export declare const CATEGORIES: {
|
|
30
|
+
Core: string[];
|
|
31
|
+
Collection: string[];
|
|
32
|
+
Effect: string[];
|
|
33
|
+
Utility: string[];
|
|
34
|
+
Validation: string[];
|
|
35
|
+
Serialization: string[];
|
|
36
|
+
Service: string[];
|
|
37
|
+
};
|
package/dist/cli/data.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{version as e}from"../package.json.js";import{GENERATED_INTERFACES as t}from"./interfaces.generated.js";const n=e,r=(e,...n)=>Array.from(/* @__PURE__ */ new Set([...t[e],...n])).sort(),i={Option:{description:`Safe nullable handling - Some<T> or None`,interfaces:r(`Option`),methods:{create:[`Option(v)`,`Option.none()`,`Some(v)`,`None()`],transform:[`.map(f)`,`.flatMap(f)`,`.filter(p)`,`.ap(ff)`,`.orElse(() => alt)`],extract:[`.fold(n, s)`,`.foldAsync(n, s)`,`.getOrElse(() => d)`,`.orThrow(err | () => Error)`,`.expect(() => never)`,`.orNull()`,`.match({Some, None})`,`.toEither(left | () => left)`,`.toList()`,`.toArray()`],check:[`.isSome()`,`.isNone()`,`.isEmpty`,`.exists(p)`,`.every(p)`],other:[`Option.sequence(arr)`,`Option.traverse(arr, f)`]}},Either:{description:`Error handling with Left (error) or Right (success)`,interfaces:r(`Either`,`Traversable`),methods:{create:[`Right(v)`,`Left(e)`,`Either.right(v)`,`Either.left(e)`,`Either.void()`],transform:[`.map(f)`,`.mapTry(f, onError)`,`.flatMap(f)`,`.mapLeft(f)`,`.swap()`,`.orElse(() => alt)`],extract:[`.fold(l, r)`,`.foldAsync(l, r)`,`.getOrElse(() => d)`,`.orThrow(err | (left) => Error)`,`.expect((l) => never)`,`.match({Left, Right})`],check:[`.isRight()`,`.isLeft()`,`.exists(p)`,`.every(p)`],other:[`Either.sequence(arr)`,`Either.traverse(arr, f)`,`Either.traverseAsync(items, f, {concurrency?}) // in order by default, stops at first Left`,`Either.fromNullable(v, e)`]}},Try:{description:`Wrap operations that may throw - Success<T> or Failure`,interfaces:r(`Try`,`Matchable`,`Traversable`),methods:{create:[`Try(() => expr)`,`Try.success(v)`,`Try.failure(e)`,`Try.fromPromise(p)`,`Try.async(() => Promise<T>)`],transform:[`.map(f)`,`.flatMap(f)`,`.recover(f)`,`.recoverWith(f)`,`.orElse(() => alt)`],extract:[`.fold(f, s)`,`.foldAsync(f, s)`,`.getOrElse(() => d)`,`.orThrow(err | (error) => Error)`,`.expect((e) => never)`,`.toOption()`,`.toEither(left | (err) => left)`,`.toList()`,`.toArray()`],check:[`.isSuccess()`,`.isFailure()`,`.exists(p)`,`.every(p)`],other:[`Try.sequence(arr)`,`Try.traverse(arr, f)`]}},List:{description:`Immutable array with functional operations`,interfaces:r(`List`,`Functor`,`Monad`,`Foldable`,`Serializable`,`Traversable`),methods:{create:[`List([...])`,`List.of(...)`,`List.empty()`],transform:[`.map(f)`,`.flatMap(f)`,`.filter(p)`,`.take(n)`,`.takeWhile(p)`,`.takeRight(n)`,`.drop(n)`,`.dropRight(n)`,`.dropWhile(p)`,`.flatten()`,`.concat(list)`,`.reverse()`,`.distinct()`,`.sorted()`,`.sortBy(f)`,`.zip(list)`,`.zipWithIndex()`,`.prepend(v)`,`.slice(s, e)`],extract:[`.fold(z, f)`,`.reduce(f)`,`.head()`,`.headOption()`,`.tail()`,`.last()`,`.lastOption()`,`.init()`,`.indexOf(v)`,`.toArray()`],check:[`.isEmpty`,`.size`,`.contains(v)`,`.exists(p)`,`.every(p)`],other:[`.groupBy(f)`,`.partition(p)`,`.span(p)`,`.mapAsync(f, {concurrency?}) // in order by default`,`.flatMapAsync(f, {concurrency?})`]}},Set:{description:`Immutable set of unique values`,interfaces:r(`Set`,`Functor`,`Foldable`,`Serializable`,`Traversable`),methods:{create:[`Set([...])`,`Set.of(...)`,`Set.empty()`],transform:[`.map(f)`,`.flatMap(f)`,`.filter(p)`,`.filterNot(p)`,`.add(v)`,`.remove(v)`,`.union(other)`,`.intersection(other)`,`.difference(other)`,`.symmetricDifference(other)`,`.mapAsync(f, {concurrency?}) // in order by default`],extract:[`.fold(z, f)`,`.toArray()`],check:[`.has(v)`,`.isEmpty`,`.size`,`.exists(p)`,`.every(p)`,`.isSubsetOf(other)`,`.isSupersetOf(other)`,`.isDisjointFrom(other)`],other:[`import { Set } from "functype" // its own name; the built-in is globalThis.Set`]}},Obj:{description:`Immutable object wrapper with fluent operations`,interfaces:r(`Obj`,`KVTraversable`,`Foldable`,`Matchable`,`Extractable`,`Serializable`),methods:{create:[`Obj({...})`,`Obj.of({...})`,`Obj.empty()`],transform:[`.set(k, v)`,`.assign(partial)`,`.merge(obj)`,`.when(cond, partial)`,`.omit(...keys)`,`.pick(...keys)`,`.map(f)`,`.flatMap(f)`],extract:[`.get(k)`,`.value()`,`.keys()`,`.values()`,`.entries()`,`.fold(n, s)`,`.match({Obj})`],check:[`.has(k)`,`.isEmpty`,`.size`]}},Map:{description:`Immutable key-value store`,interfaces:r(`Map`),methods:{create:[`Map([[k, v], ...])`,`Map.of([k, v], ...)`,`Map.empty()`,`Map.fromJSON(json)`,`Map.fromBinary(b)`],transform:[`.add(Tuple([k, v]))`,`.remove(k)`,`.map(f)`,`.flatMap(f)`,`.ap(ff)`,`.flatMapAsync(f)`],extract:[`.get(k) // Option<V>`,`.keys() // List<K>`,`.values() // List<V>`,`.getOrElse(k, () => d)`,`.orElse(k, () => Option<V>)`,`.fold(z, f)`,`.foldLeft(z)(f)`,`.foldRight(z)(f)`,`.match({Empty, NonEmpty})`,`.toList()`,`.toSet()`,`[...map] // iterate [k, v] pairs`],check:[`.has(k) // key only`,`.contains(Tuple([k, v])) // === on the value`,`.isEmpty`,`.size`],other:[`import { Map } from "functype" // its own name; the built-in is globalThis.Map`]}},Lazy:{description:"Deferred computation with memoization. Note: `serialize()` and `toValue()` FORCE the thunk (visible side effect) since a closure cannot be JSON-serialized — there is no representable 'unevaluated post-serialize' state. Thunk failures are captured via SerializedError and rethrown on access after fromJSON.",interfaces:r(`Lazy`),methods:{create:[`Lazy(() => expr)`,`Lazy.fromValue(value) — wrap a non-deferred value`,`Lazy.evaluated(value) — reads as 'already-forced'; used by fromJSON`,`Lazy.fail(error) — Lazy that throws on access`],transform:[`.map(f)`,`.flatMap(f)`],extract:[`.fold(f)`,`.foldWith(onFailure, onSuccess)`,`.getOrElse(() => d)`,`.orNull()`,`.orThrow()`,`.toJSON()`,`Lazy.fromJSON(json)`],check:[`.isEvaluated`]}},LazyList:{description:`Lazy sequences for large/infinite data`,interfaces:r(`LazyList`,`Functor`,`Monad`,`Iterable`),methods:{create:[`LazyList(iterable)`,`LazyList.from(a, b, ...)`,`LazyList.of(a, b, ...)`,`LazyList.range(start, end)`,`LazyList.iterate(seed, f)`,`LazyList.generate(f)`,`LazyList.fromJSON(json)`],transform:[`.map(f)`,`.filter(p)`,`.take(n)`,`.takeRight(n)`,`.drop(n)`,`.takeWhile(p)`,`.dropWhile(p)`,`.concat(ll)`,`.reverse()`,`.distinct()`,`.zip(ll)`,`.zipWithIndex()`],extract:[`.head()`,`.headOption()`,`.tail()`,`.last()`,`.lastOption()`,`.init()`,`.find(p)`,`.toArray()`,`.toJSON()`],check:[`.some(p)`,`.every(p)`,`.count()`]}},Exit:{description:`Outcome of running an IO effect — Success | Failure | Die | Interrupted, returned by .runExit(). Die carries a defect: a value that is not an E. Either has no branch for one, so .run() rejects on it.`,interfaces:[],methods:{create:[`Exit.succeed(v)`,`Exit.fail(e)`,`Exit.die(defect)`,`Exit.interrupt(fiberId)`,`Exit.interrupted()`],transform:[`.map(f)`,`.mapError(f)`,`.mapBoth(onErr, onOk)`,`.flatMap(f)`],extract:[`.fold(onFailure, onSuccess, onInterrupted?, onDie?)`,`.match({Success, Failure, Interrupted, Die?})`,`.orThrow()`,`.getOrElse(() => v)`,`.toOption()`,`.toEither()`,`.toValue()`],check:[`.isSuccess()`,`.isFailure()`,`.isDie()`,`.isInterrupted()`],other:[`Exit.zip(a, b)`,`Exit.all(exits)`,`Exit.fromEither(e)`,`Exit.fromOption(o, onNone)`,`// after a guard: .value / .error / .defect / .fiberId`,`// onDie / Die are optional and fall back to the failure handler`,`// defects stay recoverable: .recover/.recoverWith/.fold/.mapError treat Die as Failure`]}},IO:{description:`Lazy effect type with typed errors and dependency injection`,interfaces:[`Functor`,`Monad`,`Foldable`,`Matchable`],methods:{create:[`IO(() => v)`,`IO.succeed(v)`,`IO.fail(e)`,`IO.sync(f)`,`IO.async(f)`,`IO.tryPromise({try, catch})`,`IO.fromEither(e)`,`IO.fromPromiseEither(f, onReject?)`,`IO.fromOption(o)`,`IO.fromTry(t)`,`IO.die(defect)`],transform:[`.map(f)`,`.mapTry(f, onError) // a throw in f becomes a typed error, not a defect`,`.flatMap(f)`,`.tap(f)`,`.mapError(f)`,`.recover(v)`,`.recoverWith(f)`],extract:[`.run() // Either<E,A> — Left holds only E; a defect or interruption rejects`,`.runOrThrow()`,`.runSync() // Either<E,A>; throws a defect or interruption`,`.runSyncOrThrow()`,`.runExit() // Exit<E,A> — the only terminal that distinguishes Failure/Die/Interrupted`,`.runCancellable() // { result, cancel }`,`.runExit({ signal }) // Interrupted on abort, E unchanged`,`.runOption()`,`.runTry()`,`.fold(onErr, onOk)`,`.match({failure, success})`],check:[],other:[`.catchTag(tag, f)`,`.catchAll(f)`,`.retry(n)`,`.retryWithDelay(n, ms)`,`.retryWhile({ n, while, delayMs? })`,`.retryWithBackoff({ n, baseMs, maxMs?, factor?, jitter?, while? })`,`.repeatUntil(done, { max, delayMs? })`,`.repeatWhile(cont, { max, delayMs? })`,`.timeout(ms) // interrupts the effect at the deadline`,`.interruptOn(signal) // stops at the next step once the AbortSignal fires; E gains InterruptedError`,`.withSpan(name, attributes?) // runs in a span via the provided SpanTracer; an inner withSpan nests under it`,`IO.async((signal?) => fetch(url, { signal })) // thunk gets the run's AbortSignal inside a region`,`.delay(ms)`,`.zip(io)`,`.pipe(f)`,`IO.all([...], { concurrency? }) // all at once by default; first failure interrupts the rest`,`IO.forEach(items, f, { concurrency? })`,`IO.race([...]) // first to settle wins; the rest are interrupted`,`IO.firstSuccessOf([...]) // tries each in order; the first success wins`,`IO.iterate(seed, step, done, { max? })`,`IO.bracket(acquire, use, release)`,`IO.gen(function*() {...})`,`IO.Do.bind().map()`,`IO.service(Tag)`,`.provideService(Tag, impl)`,`.provideLayer(layer)`]}},Cond:{description:`Conditional expression builder - replace if-else chains`,interfaces:[],methods:{create:[`Cond<T>()`],other:[`.case(pred, result)`,`.otherwise(result)`,`.eval()`]}},Match:{description:`Pattern matching - replace switch statements`,interfaces:[],methods:{create:[`Match(value)`],other:[`.case(pattern, result)`,`.when(pred, result)`,`.default(result)`,`.done()`]}},Brand:{description:`Nominal typing without runtime overhead`,interfaces:[],methods:{create:[`Brand<K, T>(value)`],extract:[`.unwrap()`,`.toString()`]}},Wire:{description:`Serialization-boundary marker for a row, collection or nullable field at DB / HTTP / JSONB boundaries. Zero runtime, assignable both ways with T. prefer-list and prefer-option skip everything inside it. A collection is Wire<ReadonlyArray<Row>>.`,interfaces:[],methods:{create:[`type UserRow = Wire<{ email: string | null }>`,`type Rows = Wire<ReadonlyArray<Row>>`,`email: Wire<string | null>`],other:[`List(rows).filter(...) // convert to List for transformation`,`Option(row.email) // convert to Option`]}},ValidatedBrand:{description:`Branded types with runtime validation`,interfaces:[],methods:{create:[`ValidatedBrand(validator)`,`.of(v)`,`.from(v)`,`.unsafeOf(v)`],check:[`.is(v)`],other:[`.refine(validator)`]}},Tuple:{description:`Fixed-size typed array`,interfaces:r(`Tuple`,`Typeable`,`Valuable`,`Iterable`),methods:{create:[`Tuple([a, b, ...])`,`Tuple.of(a, b, ...)`,`Tuple.fromJSON(json)`],extract:[`.get(i)`,`.length`,`.toArray()`,`.toJSON()`],transform:[`.map(f)`]}},Identity:{description:`The identity monad: wraps a value with no extra effect. Useful as a neutral container in generic code.`,interfaces:[],methods:{create:[`Identity(value)`,`Identity.of(value)`,`Identity.pure(value)`],extract:[`.id`],other:[`.isSame(other)`]}},Ref:{description:`Mutable reference cell for controlled, local mutability. Invariant in A by design (a mutable cell can't be widened).`,interfaces:[],methods:{create:[`Ref(initial)`,`Ref.of(initial)`],extract:[`.get()`],transform:[`.set(a)`,`.update(f)`,`.modify(f) // returns B, stores A`],other:[`.getAndSet(a)`,`.updateAndGet(f)`,`.getAndUpdate(f)`,`.compareAndSet(expected, next)`]}},Do:{description:`Generator do-notation across Option, Either, List and Try (DoAsync for promises). Short-circuits on None/Left/Failure/empty List.`,interfaces:[],methods:{create:[`Do(function* () { const a = yield* $(opt); return a })`,`DoAsync(async function* () { … })`],other:[`$(monad) // unwrap inside Do`,`isDoCapable(value)`,`unwrap(monad)`]}},invariant:{description:`One-line bug check: invariant(cond, msg) throws a tagged InvariantViolation when cond is falsy and narrows cond after it. For programmer errors only; expected failures return Either.`,interfaces:[],methods:{create:[`invariant(row, "upsert returned no row")`,"invariant(n >= 0, () => `bad step ${n}`) // lazy message"],other:[`InvariantViolation(msg) // throw directly for an unreachable branch`]}},TracedOption:{description:`Opt-in Option wrapper that emits one TraceEvent per combinator to an injected Tracer, then delegates. For code-path introspection.`,interfaces:[],methods:{create:[`TracedOption(option, tracer, spanId, seq?)`],transform:[`.map(f, label?)`,`.flatMap(f, label?)`,`.filter(p, label?)`],extract:[`.fold(onNone, onSome, label?)`,`.getOrElse(() => default, label?)`,`.unwrap() // back to Option`]}},Tracer:{description:`One-method trace sink consumed by TracedOption. Type-only, like Logger; declare your own Tag for injection.`,interfaces:[],methods:{create:[`const tracer: Tracer = { emit: (e: TraceEvent) => … }`],other:[`TraceEvent: { spanId, seq, op, tag, inTag, outTag?, label?, meta? }`]}},SpanTracer:{description:`Span contract and Tag for IO.withSpan: start, run (body with the span active), end. None provided: withSpan is a no-op.`,interfaces:[],methods:{create:[`const tracer: SpanTracer<MySpan> = { start, run, end }`,`io.withSpan("name", { key: "value" }).provideService(SpanTracer, tracer) // provide outside the spans`],other:[`OpenTelemetry: run = (span, fn) => context.with(trace.setSpan(context.active(), span), fn)`,`parent is the enclosing span in this run, or undefined; fall back to the ambient context then`]}},Stack:{description:`Immutable LIFO stack`,interfaces:[`Foldable`,`Collection`,`Serializable`,`Traversable`],methods:{create:[`Stack()`,`Stack.of(...)`],transform:[`.push(v)`,`.pop()`],extract:[`.peek()`,`.toArray()`],check:[`.isEmpty`,`.size`]}},Http:{description:"HTTP fetch wrapper returning IO<never, HttpError, HttpResponse<T>>. Pass `decode: Decoder<T>` (Either-returning) for typed responses; wrap a throwing parser such as Zod's .parse in `Decoder.fromThrowing(parse)`. 2.0 removed the `validate` field. Request bodies auto-flatten functype ADTs to primitives; `flatten: false` preserves tagged emission for functype-to-functype services. Per-call `params` (HttpQueryParams) appends query strings with proper encoding. Http.client accepts `beforeRequest` and `afterResponse` (both effectful IO transformers). `afterResponse` runs on the success path only — error handling belongs in .catchTag. Composes via .tap/.map/.flatMap/.catchTag/.retry/.retryWhile/.retryWithBackoff/.timeout.",interfaces:[],methods:{create:[`Http.get(url, { decode, params }?)`,`Http.post(url, { body, decode, params }?)`,`Http.put(url, { body, decode, params }?)`,`Http.patch(url, { body, decode, params }?)`,`Http.delete(url, { decode, params }?)`,`Http.request({ url, decode, params })`,`Http.client({ baseUrl, defaultHeaders, fetch, beforeRequest, afterResponse })`],transform:[`.tap(f)`,`.map(f)`,`.flatMap(f)`,`.mapError(f)`,`.retry(n)`,`.retryWithDelay(n, ms)`,`.retryWhile({ n, while, delayMs? })`,`.retryWithBackoff({ n, baseMs, maxMs?, factor?, jitter?, while? })`,`.timeout(ms)`],extract:[`.run()`,`.runOrThrow()`,`.runOption()`,`.runTry()`,`.runExit()`,`.runCancellable()`],check:[],other:[`.catchTag(tag, handler)`,`.catchAll(handler)`,`.recover(fallback)`,`decode: Decoder<T> (Either-returning, structural failures preserved)`,`decode: Decoder.fromThrowing(parse) (a throwing parser such as Zod .parse; a throw becomes a DecoderError leaf)`,`flatten: boolean (default true; false preserves tagged emission)`,`encode: Encoder<TReq> = (value) => JSONValue (custom wire shape; overrides flatten)`,`params: HttpQueryParams (scalar | array; undefined/null dropped; percent-encoded)`,`beforeRequest: (req) => IO<never, HttpError, HttpRequestView>`,`afterResponse: (HttpResponse<unknown>) => IO<never, HttpError, HttpResponse<unknown>> — success path only; refresh-on-401 uses .catchTag`]}},HttpError:{description:`Three-variant ADT for HTTP failures: NetworkError | HttpStatusError | DecodeError (also exported as ResponseDecodeError alias)`,interfaces:[],methods:{create:[`HttpError.networkError(url, method, cause)`,`HttpError.httpStatusError(url, method, status, statusText, body)`,`HttpError.decodeError(url, method, body, cause)`],check:[`HttpError.isNetworkError(e)`,`HttpError.isHttpStatusError(e)`,`HttpError.isDecodeError(e)`],other:[`HttpError.match(error, { NetworkError, HttpStatusError, DecodeError })`]}},Decoder:{description:"Either-returning decoder contract: `Decoder<A> = (raw: unknown) => Either<DecoderError, A>`. Bundled combinators for primitives + functype ADTs (Option/Either/List/Map, null-bias). `Decoder.tagged.*` round-trips the `{_tag, value}` shape for functype-to-functype services.",interfaces:[],methods:{create:[`Decoder.string / .number / .boolean / .unknown / .nullable(inner)`,`Decoder.fromThrowing(parse) // adapt a throwing parser such as Zod's schema.parse`,`Decoder.option(inner)`,`Decoder.either.envelope({ok, err})`,`Decoder.either.discriminated({tag, leftTag, rightTag}, l, r)`,`Decoder.list(inner) / .array(inner) / .map(inner)`,`Decoder.object({k: Decoder<V>, ...}) — accumulates field failures into Composite`,`Decoder.tagged.option/either/try/list/map/obj(inner?) — round-trips {_tag, value}`],other:[`Pluggable by construction: any (raw) => Either<DecoderError, T> IS a Decoder<T>`,`Composes across sources: Decoder.object({a: Decoder.fromZod(s), b: Decoder.option(myAjv)})`]}},DecoderError:{description:"Recursive ADT for decoder failures: Leaf | Composite. Children mirror the input tree so multi-field failures preserve structural paths. Distinct from `HttpError.DecodeError` — this is the inner structural cause that the HTTP wrapper carries.",interfaces:[],methods:{create:[`DecoderError.leaf(path, message, cause?)`,`DecoderError.composite(path, children: List<DecoderError>)`],check:[`DecoderError.isLeaf(e)`,`DecoderError.isComposite(e)`],other:[`DecoderError.match(e, { Leaf, Composite })`,`DecoderError.prepend(segment, e) — used by combinators to attribute child failures`,`DecoderError.flatten(e): List<{path, message}> — collect leaves`,`DecoderError.format(e): string — render tree as multi-line`]}},Serialization:{description:"Universal `@functype`-marked JSON serialization. `deserialize` walks parsed JSON and reconstructs any functype value found — no type argument needed. Lenient: plain JSON passes through. Strict on unknown markers (defends against Effect/fp-ts `_tag` collision). 1.2.1 adds `toEnvelope`/`fromEnvelope` for nesting inside structured serializers (SuperJSON, DBOS), and `deserializeStrict` for boundaries that require functype on the wire.",interfaces:[],methods:{create:[],transform:[`Serialization.serialize(value: unknown): string — lenient JSON codec`,`Serialization.deserialize(json: string): Try<unknown> — lenient; pass-through for unmarked JSON`,`Serialization.deserializeStrict(json: string): Try<unknown> — Failure if no @functype marker at top level`,`Serialization.toEnvelope(value: unknown): JSONValue — parsed JSON shape (1.2.2 tightened from unknown)`,`Serialization.fromEnvelope(envelope: unknown): Try<unknown> — inverse of toEnvelope; input stays permissive (Postel's law)`,`Serialization.JSONValue — exported recursive type for the envelope shape`],check:[`Serialization.isFunctypeValue(v): v is Serializable<unknown>`],other:[`Plain JSON passthrough: non-functype data walks through unchanged (use deserializeStrict to reject)`,`Strict policy on unknown markers: unknown @functype marker → Try.Failure`,`Dispatch table covers all 11 Serializable types (Option, Either, Try, List, Set, Map, Obj, Stack, Tuple, LazyList, Lazy)`,`Algebraic square: serialize ≡ JSON.stringify ∘ toEnvelope; deserialize ≡ fromEnvelope ∘ JSON.parse`,`No DBOS / SuperJSON facade — consumers wire host serializer in ~8 lines via toEnvelope/fromEnvelope`]}},SerializedError:{description:"Canonical Error projection used by Try.Failure and Lazy-with-thrown-thunk. Round-trips name + message + stack + cause chain. `e.name === 'TypeError'` survives; `instanceof TypeError` does NOT.",interfaces:[],methods:{create:[`serializeError(err: unknown): SerializedError`,`deserializeError(s: SerializedError | string): Error`],other:[`Shape: { name: string; message: string; stack?: string; cause?: SerializedError | string }`,`Non-Error throwables (strings, plain objects) projected under name: 'NonErrorThrowable'`,`Cause chain is recursive — arbitrary nesting depth survives`]}},Logger:{description:`Minimal 4-method logging interface every functype-* package targets. Type-only, no runtime. Impls live in consumers: consoleBootLogger (functype-os/config), DirectLogger (functype-log/direct). Tracer is type-only on the same terms; Clock/Random are not added.`,interfaces:[],methods:{create:[`interface Logger { debug, info, warn, error: (msg, meta?) => void }`,`import type { Logger } from "functype"`],check:[],other:[`All 4 methods MANDATORY (no defensive logger.debug?.() at call sites)`,`Signature: (message: string, metadata?: Record<string, unknown>) => void`,`DirectLogger from functype-log/direct structurally satisfies Logger (superset shape)`,`IO-shaped Logger from functype-log does NOT satisfy core Logger (methods return IO<>, not void) — bridge via toDirectLogger(ioLogger)`,`Used by: bootDiagnostics({ logger? }) in functype-os/config`]}},TypedError:{description:`Code-tagged structured error ADT (extends Throwable); TypedError.validation(...) feeds accumulating validation.`,interfaces:[],methods:{create:[`TypedError.validation(field, value, rule) → TypedError<"VALIDATION_FAILED">`,`TypedError.badRequest(reason, expected?)`,`TypedError.notFound(resource, id)`,`TypedError.auth(resource, requiredRole?)`,`TypedError.permission(action, resource, userId?)`,`TypedError.conflict(resource, value) / .rateLimit(limit, window, retryAfter?)`,`TypedError.timeout(ms, operation) / .network(url, method, status?) / .internal(errorId)`],check:[`TypedError.isTypedError(v)`,`TypedError.hasCode(e, code)`],other:[`Fields: .code, .message, .status (HTTP), .context, .timestamp, .traceId?`,`VALIDATION_FAILED context shape: { field, value, rule }`,`getErrorChain(error) → Error[] and formatErrorChain(error, { includeTasks? }) walk any error's cause chain`]}},Validation:{description:`Error-accumulating validation (functype's Validated role) — FormValidation<T> collects all field errors, not fail-fast.`,interfaces:[],methods:{create:[`Validation.rule<T>('min:18' | 'email' | 'required' | 'in:a,b' | ...)`,`Validation.combine(...validators) / Validation.custom(predicate, message)`,`Validation.validators.email / .url / .uuid / .required / .numeric / .positiveNumber / .nonEmptyString`],transform:[`Validation.form(schema, data) → FormValidation<T> (accumulates all field errors)`,`Validator<T> = (value: unknown) => Either<TypedError<'VALIDATION_FAILED'>, T>`],other:[`FormValidation<T> = Either<List<TypedError<"VALIDATION_FAILED">>, T> — functype's "Validated" accumulating result type`,`form() is flat/per-field: for cross-field (lo < hi) or dynamic-key (weights.*) checks, hand-accumulate into a List<TypedError> and return the FormValidation shape`]}}},a={Functor:{description:`Transform contained values`,methods:[`.map<B>(f: A => B): Functor<B>`]},Applicative:{extends:`Functor`,description:`Apply wrapped functions`,methods:[`.ap<B>(ff: Applicative<A => B>): Applicative<B>`]},Monad:{extends:`Applicative`,description:`Chain operations returning wrapped values`,methods:[`.flatMap<B>(f: A => Monad<B>): Monad<B>`]},Foldable:{description:`Extract via pattern matching`,methods:[`.fold<B>(empty: () => B, f: A => B): B`,`.foldLeft<B>(z: B, op: (B, A) => B): B`,`.foldRight<B>(z: B, op: (A, B) => B): B`]},Extractable:{description:`Get contained value with fallback`,methods:[`.getOrElse(d: () => T): T`,`.orThrow(e?: Error): T`,`.expect(handler: (e?) => never): T`,`.orNull(): T | null`,`.orUndefined(): T | undefined`]},Matchable:{description:`Pattern match on type variants`,methods:[`.match<R>(patterns: Record<Tag, Handler>): R`]},Traversable:{description:`Iterate and check contents`,methods:[`.size: number`,`.isEmpty: boolean`,`.contains(v: A): boolean`,`.reduce<B>(f, init): B`]},Collection:{description:`Collection operations`,methods:[`.toArray(): A[]`,`.forEach(f: A => void): void`]},Serializable:{description:`Convert to string formats`,methods:[`.serialize().toJSON(): string`,`.serialize().toBinary(): string`]}},o={Core:[`Option`,`Either`,`Try`,`Obj`,`Identity`],Collection:[`List`,`Set`,`Map`,`LazyList`,`Tuple`,`Stack`],Effect:[`IO`,`Exit`,`Http`,`HttpError`,`Decoder`,`DecoderError`],Utility:[`Lazy`,`Cond`,`Match`,`Do`,`Ref`,`Brand`,`ValidatedBrand`,`Wire`,`invariant`,`TracedOption`],Validation:[`TypedError`,`Validation`],Serialization:[`Serialization`,`SerializedError`],Service:[`Logger`,`Tracer`,`SpanTracer`]};export{o as CATEGORIES,a as INTERFACES,i as TYPES,n as VERSION};
|
package/dist/cli/exports.d.ts
CHANGED
|
@@ -1,48 +1,7 @@
|
|
|
1
|
-
//#region src/cli/data.d.ts
|
|
2
1
|
/**
|
|
3
|
-
*
|
|
4
|
-
*
|
|
5
|
-
* `interfaces` arrays are composed of (a) the GENERATED_INTERFACES floor
|
|
6
|
-
* derived from each type's `extends` chain in source, plus (b) optional
|
|
7
|
-
* hand-curated additions for capabilities declared inline (e.g. `List.map`
|
|
8
|
-
* lives in the interface body, not via `extends Functor`). The data-sync
|
|
9
|
-
* spec enforces that no source-declared interface is dropped from this list.
|
|
2
|
+
* Public API for functype CLI data.
|
|
3
|
+
* Re-exports curated type/interface metadata for use by tooling (MCP servers, editors, etc.)
|
|
10
4
|
*/
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
interfaces: string[];
|
|
15
|
-
methods: {
|
|
16
|
-
create?: string[];
|
|
17
|
-
transform?: string[];
|
|
18
|
-
extract?: string[];
|
|
19
|
-
check?: string[];
|
|
20
|
-
other?: string[];
|
|
21
|
-
};
|
|
22
|
-
}
|
|
23
|
-
interface InterfaceData {
|
|
24
|
-
extends?: string;
|
|
25
|
-
description: string;
|
|
26
|
-
methods: string[];
|
|
27
|
-
}
|
|
28
|
-
export declare const TYPES: Record<string, TypeData>;
|
|
29
|
-
export declare const INTERFACES: Record<string, InterfaceData>;
|
|
30
|
-
export declare const CATEGORIES: {
|
|
31
|
-
Core: string[];
|
|
32
|
-
Collection: string[];
|
|
33
|
-
Effect: string[];
|
|
34
|
-
Utility: string[];
|
|
35
|
-
Validation: string[];
|
|
36
|
-
Serialization: string[];
|
|
37
|
-
Service: string[];
|
|
38
|
-
};
|
|
39
|
-
//#endregion
|
|
40
|
-
//#region src/cli/full-interfaces.d.ts
|
|
41
|
-
/**
|
|
42
|
-
* Auto-generated full interface definitions.
|
|
43
|
-
* Generated by scripts/extract-interfaces.ts
|
|
44
|
-
* DO NOT EDIT MANUALLY
|
|
45
|
-
*/
|
|
46
|
-
export declare const FULL_INTERFACES: Record<string, string>;
|
|
47
|
-
//#endregion
|
|
48
|
-
export type { InterfaceData, TypeData };
|
|
5
|
+
import { CATEGORIES, INTERFACES, InterfaceData, TYPES, TypeData, VERSION } from "./data.js";
|
|
6
|
+
import { FULL_INTERFACES } from "./full-interfaces.js";
|
|
7
|
+
export { CATEGORIES, FULL_INTERFACES, INTERFACES, type InterfaceData, TYPES, type TypeData, VERSION };
|
package/dist/cli/exports.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{CATEGORIES as e,INTERFACES as t,TYPES as n,VERSION as r}from"./data.js";import{FULL_INTERFACES as i}from"./full-interfaces.js";export{e as CATEGORIES,i as FULL_INTERFACES,t as INTERFACES,n as TYPES,r as VERSION};
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
import{List as e}from"../list/index.js";import{Option as t}from"../option/index.js";import{CATEGORIES as n,INTERFACES as r,TYPES as i,VERSION as a}from"./data.js";const o=()=>{let r=e([`functype ${a} - Scala-inspired FP for TypeScript`,``]);return e(Object.entries(n)).foldLeft(r)((n,[r,a])=>{let o=n.add(r.toUpperCase());return e(a).foldLeft(o)((e,n)=>t(i[n]).fold(()=>e,t=>{let r=t.interfaces.length>0?` [${t.interfaces.join(`, `)}]`:``;return e.add(` ${n}${r}`).add(` ${t.description}`)})).add(``)}).concat(e([`Use: npx functype <Type> for details`,`Use: npx functype interfaces for interface reference`])).toArray().join(`
|
|
2
|
+
`)},s=(n,r)=>{let i=r.interfaces.length>0?` [${r.interfaces.join(`, `)}]`:``,a=e([`create`,`transform`,`extract`,`check`,`other`]),o=e([`${n}<T>${i}`,``,r.description,``]);return a.foldLeft(o)((n,i)=>t(r.methods[i]).filter(e=>e.length>0).fold(()=>n,t=>{let r=n.add(i.toUpperCase());return e(t).foldLeft(r)((e,t)=>e.add(` ${t}`)).add(``)})).toArray().join(`
|
|
3
|
+
`).trimEnd()},c=()=>{let t=e([`INTERFACES`,``]);return e(Object.entries(r)).foldLeft(t)((t,[n,r])=>{let i=r.extends?` extends ${r.extends}`:``,a=t.add(`${n}<A>${i}`).add(` ${r.description}`);return e(r.methods).foldLeft(a)((e,t)=>e.add(` ${t}`)).add(``)}).toArray().join(`
|
|
4
|
+
`).trimEnd()},l=e=>JSON.stringify(e,null,2),u=()=>({version:a,categories:n,types:i}),d=n=>t(i[n]).map(e=>({name:n,data:e})).orElse(()=>e(Object.entries(i)).find(([e])=>e.toLowerCase()===n.toLowerCase()).map(([e,t])=>({name:e,data:t}))).orUndefined(),f=()=>Object.keys(i),p=()=>r;export{c as formatInterfaces,l as formatJson,o as formatOverview,s as formatType,f as getAllTypeNames,p as getInterfacesData,u as getOverviewData,d as getType};
|