Introducing The Sweep: OX’s New Live Security Research Series
Register Now
Breaking: The 2026 Vulnpocalypse Hits PHP: Four Critical RCEs, but How Dangerous Are They?
Read the Report
Are you exposed? Connect your apps in minutes.
Scan your apps free

functype

Latest version: v2.2.0

Overview

Last scanned
24 Nov 2026
Published
24 Nov 2026
npm package Publisher: jordanburke
10 Stars
1 Forks
29 Versions
21.0K Downloads
TypeScript Repo language

Scan summary

functype was last scanned on 24 Nov 2026 at version 2.2.0. Risk score 0 of 100. No malicious behavior was detected.

  • Releases: 29 versions; the latest 5 were published within 5 days (20–24 Nov 2026).
  • Findings: No rules fired in version 2.2.0.
  • Downloads: 20,975 downloads.

Versions

29 versions published
Versions and the rules that fired in each
VersionPublishedStatus
2.2.0 LATEST 24 Nov 2026 No rules fired
2.1.0 23 Nov 2026 No rules fired
2.0.0 22 Nov 2026 No rules fired
1.27.2 22 Nov 2026 Not shown
1.27.1 20 Nov 2026 Not shown

No rules fired in 2.2.0

Findings

Findings for v2.2.0. The score is a capped sum of the weights of the rules that fired — not CVSS, not exploitability, and not a probability. It is not comparable across packages with different scan coverage.

The score describes 2.2.0; other versions have their own rules, not their own score.

README

The publisher’s own README, as collected from the registry.

Functype

NPM Version CI

A Functional Programming Library for TypeScript

Functype is a lightweight functional programming library for TypeScript, drawing inspiration from functional programming paradigms, the Scala Standard Library, and ZIO. It provides a comprehensive set of utilities and abstractions designed to facilitate functional programming within TypeScript applications.

API Documentation · Cheatsheet for Scala / cats / fp-ts users

CLI Documentation

Get LLM-optimized API reference directly in your terminal:

npx functype              # Overview of all types
npx functype Option       # Detailed info for Option type
npx functype interfaces   # All interface definitions
npx functype --json       # JSON output for programmatic use

Core Principles

  • Zero Dependencies: No third-party runtime dependencies — just TypeScript
  • Immutability: All data structures are immutable, promoting predictable and side-effect-free code. The types mark every field read-only, and eslint-plugin-functype's no-container-mutation reports a write through a cast. Under NODE_ENV=development collections also freeze each value, so a write from untyped code throws; FUNCTYPE_FREEZE=1 turns that on anywhere, such as a test suite, and FUNCTYPE_FREEZE=0 turns it off. Production doesn't freeze, because freezing was most of what building a collection cost
  • Type Safety: Leverages TypeScript's type system to ensure compile-time safety
  • Composability: Provides abstractions for building complex programs from simple components
  • Functional Paradigms: Embraces concepts like monads, functors, and type classes
  • Unified Interface: All data structures implement a common hierarchy of interfaces for consistency

Key Features

  • Option Type: Handle nullable values with Some and None types
  • Either Type: Express computation results with potential failures using Left and Right
  • List, Set, Map: Immutable collection types with functional operators
  • Try Type: Safely execute operations that might throw exceptions
  • Do-notation: Scala-like for-comprehensions with optimized List performance (up to 12x faster than traditional flatMap)
  • IO: Lazy effects with typed errors, dependency injection and cancellation
  • Http: Typed HTTP fetch wrapper returning IO effects with HttpError ADT, auto content-type detection, and configurable clients
  • Lazy: Deferred computation with memoization
  • Tuple: Type-safe fixed-length arrays
  • Typeable: Runtime type identification with compile-time safety
  • Branded Types: Nominal typing in TypeScript's structural type system
  • Error Formatting: Utilities for improved error visualization and logging
  • Unified Type Classes: Consistent interfaces across all data structures

functype vs Effect

functype is a small, dependency-free library of functional data types you adopt incrementally. Effect is a comprehensive effect system and runtime you build your application around. Both bring FP to TypeScript and overlap on the surface (an effect type, typed errors, DI), but they solve different problems. If you know Scala: functype is to Effect roughly what the standard library / cats-core is to ZIO.

  • Reach for functype when you want Scala's standard-library ergonomics — Option, Either, Try, List, do-notation — with zero runtime dependencies, adoptable one function at a time (a List or Option is just a value you can delete from a single file). It includes a lightweight ZIO-shaped IO with typed errors and DI, but no runtime to build your app around.
  • Reach for Effect when you want structured concurrency, streaming, scheduling, and an integrated batteries-included ecosystem you structure your whole application on.

functype deliberately is not a framework — no fiber runtime, no structured concurrency, no Clock/Random. What it adds instead is an LLM-native loop no other FP library has: lint rules that enforce idioms (eslint-plugin-functype), a scorer/benchmark that measures adherence (functype-eval), and an MCP server + skill that teach models the API.

Full comparison, non-goals, and "choose Effect when…": docs/vs-effect.md.

Installation

Upgrading from 1.x? functype.org/upgrading-to-2 lists what to change.

# NPM
npm install functype

# Yarn
yarn add functype

# PNPM
pnpm add functype

# Bun
bun add functype
Bundle Size

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:

import { Option } from "functype/option" // bundles the same as importing from "functype"
import { Either, IO, List, Option } from "functype/core" // the 17 names most code needs, in one import

For the measured sizes and how they are checked, see the Bundle Size guide.

Usage Examples

Option

{@includeCode test/docs/documentation-examples.spec.ts#readme-option-basic}

Either

{@includeCode test/docs/documentation-examples.spec.ts#readme-either-basic}

List
import { List } from "functype"

const numbers = List([1, 2, 3, 4])

// Transform
const doubled = numbers.map((x) => x * 2) // List([2, 4, 6, 8])

// Filter
const evens = numbers.filter((x) => x % 2 === 0) // List([2, 4])

// Reduce
const sum = numbers.foldLeft(0)((acc, x) => acc + x) // 10

// Add/remove elements (immutably)
const withFive = numbers.add(5) // List([1, 2, 3, 4, 5])
const without3 = numbers.remove(3) // List([1, 2, 4])

// Universal container operations
const hasEven = numbers.exists((x) => x % 2 === 0) // true
const firstEven = numbers.find((x) => x % 2 === 0) // Some(2)
const evenCount = numbers.count((x) => x % 2 === 0) // 2
Try
import { Try } from "functype"

// Safely execute code that might throw
const result = Try(() => {
  // Potentially throwing operation
  return JSON.parse('{"name": "John"}')
})

// Handle success/failure
if (result.isSuccess()) {
  console.log("Result:", result.get())
} else {
  console.error("Error:", result.error)
}

// Transform with map (only applies on Success)
const name = result.map((obj) => obj.name)

// Convert to Either
const either = result.toEither()
Lazy
import { Lazy } from "functype"

// Create lazy computations
const expensive = Lazy(() => {
  console.log("Computing...")
  return Math.random() * 1000
})

// Value is computed on first access and memoized
const value1 = expensive.get() // Logs "Computing...", returns number
const value2 = expensive.get() // Returns same number, no log

// Transform lazy values
const doubled = expensive.map((x) => x * 2)
const formatted = doubled.map((x) => `Value: ${x}`)

// Chain computations
const result = Lazy(() => 10)
  .flatMap((x) => Lazy(() => x + 5))
  .map((x) => x * 2)
  .get() // 30
Do-notation (High-Performance For-Comprehensions)

Functype provides generator-based Do-notation for monadic composition, similar to Scala's for-comprehensions, with significant performance advantages for List operations:

import { Do, DoAsync, $ } from "functype"
import { Option, Right, Left, List, Try } from "functype"

// Chain multiple Option operations
const result = Do(function* () {
  const x = yield* $(Option(5)) // Extract value from Option
  const y = yield* $(Option(10)) // Extract value from another Option
  const z = x + y // Regular computation
  return z * 2 // Return final result
})
// result: Option<number> with value 30

// Mix different monad types (with Reshapeable)
const mixed = Do(function* () {
  const a = yield* $(Option(5)) // From Option
  const b = yield* $(Right<string, number>(10)) // From Either
  const c = yield* $(List([15])) // From List
  const d = yield* $(Try(() => 20)) // From Try
  return a + b + c + d
})
// Convert result to desired type
const asOption = mixed.toOption() // Option<number> with value 50

// Error propagation - short-circuits on failure
const validation = Do(function* () {
  const email = yield* $(validateEmail("user@example.com")) // Returns Option
  const user = yield* $(fetchUser(email)) // Returns Either
  const profile = yield* $(loadProfile(user.id)) // Returns Try
  return profile
})
// If any step fails, the entire computation short-circuits

// List comprehensions - up to 12x FASTER than traditional flatMap!
const pairs = Do(function* () {
  const x = yield* $(List([1, 2, 3]))
  const y = yield* $(List([10, 20]))
  return { x, y, product: x * y }
})
// pairs: List with 6 elements (all combinations)

// Performance comparison:
// Traditional: list.flatMap(x => list.flatMap(y => List([{x, y}]))) - slower
// Do-notation: 2.5x to 12x faster for cartesian products!

// Async operations with DoAsync
const asyncResult = await DoAsync(async function* () {
  const user = yield* $(await fetchUserAsync(userId)) // Async Option
  const score = yield* $(await getScoreAsync(user.id)) // Async Either
  const bonus = yield* $(await calculateBonus(score)) // Async Try
  return score + bonus
})

Performance Advantages:

  • List Comprehensions: 2.5x to 12x faster than nested flatMap chains
  • Optimized for Cartesian Products: Efficient handling of multiple List yields
  • Smart Caching: Constructor lookups cached after first type detection
  • Inline Helpers: Reduced overhead from repeated type checks

When to Use Do-notation:

✅ Best for:

  • Complex List comprehensions (huge performance win!)
  • Cartesian products and filtered combinations
  • Mixed monad types (leveraging Reshapeable)
  • Improved readability for multi-step operations

⚠️ Consider alternatives for:

  • Simple 2-3 step Option/Either chains (traditional flatMap is ~2x faster)
  • Performance-critical hot paths with simple monads
  • Early termination scenarios (flatMap auto-short-circuits more efficiently)

Key Differences from Scala:

  • Uses yield* $(monad) instead of x <- monad
  • No native guard syntax (use conditions with early return)
  • Always returns the type of the first yielded monad
  • Mixed types supported via Reshapeable interface
IO

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.

import { IO } from "functype"

type User = { id: string; name: string; settings: string }

const loadUser = (id: string) =>
  IO.tryPromise({
    // the run's signal reaches fetch, so cancelling stops the request
    try: (signal) => fetch(`/api/users/${id}`, { signal }).then((r) => r.json() as Promise<User>),
    catch: (error) => new Error(`Failed to load ${id}: ${String(error)}`),
  })

// Nothing has run yet. run() gives an Either<Error, User>
const user = await loadUser("42").retry(2).timeout(5000).run()

// Cancel with a handle, or with your own AbortSignal
const { result, cancel } = loadUser("42").runCancellable()
const controller = new AbortController()
const exit = await loadUser("42").runExit({ signal: controller.signal }) // Success | Failure | Die | Interrupted

// A callback that may throw: in map a throw is a defect and run() rejects; mapTry makes it a typed error
const settings = loadUser("42").mapTry(
  (user) => JSON.parse(user.settings) as unknown,
  (error) => new Error(`Bad settings: ${String(error)}`),
)
Tracing

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.

import { context, type Span, SpanStatusCode, trace } from "@opentelemetry/api" // your dependency, not functype's
import { SpanTracer } from "functype"

const otel = trace.getTracer("my-app")
const otelTracer: SpanTracer<Span> = {
  start: (name, attributes, parent) =>
    otel.startSpan(name, { attributes }, parent ? trace.setSpan(context.active(), parent) : context.active()),
  run: (span, fn) => context.with(trace.setSpan(context.active(), span), fn), // makes the span active
  end: (span, exit) => {
    if (exit._tag === "Failure" || exit._tag === "Die") span.setStatus({ code: SpanStatusCode.ERROR })
    span.end()
  },
}

// Provide the tracer outside the spans
await loadUser("42").withSpan("loadUser", { "user.id": "42" }).provideService(SpanTracer, otelTracer).run()

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 cover nesting, cancellation and runSync.

Branded Types
import { Brand, ValidatedBrand } from "functype/branded"

// Create branded types for stronger type safety
type UserId = Brand<"UserId", string>
type Email = Brand<"Email", string>

// Simple branding - branded values ARE primitives!
const userId = Brand("UserId", "U123456")
console.log(userId) // "U123456" - it IS a string
console.log(typeof userId) // "string"
console.log(userId.toUpperCase()) // "U123456" - string methods work!

// Runtime-validated branding for safer input handling
const EmailValidator = ValidatedBrand("Email", (s: string) => /^[^@]+@[^@]+\.[^@]+$/.test(s))
const UserIdValidator = ValidatedBrand("UserId", (s: string) => /^U\d{6}$/.test(s))

// Safe creation with Option/Either return types
const email = EmailValidator.of("user@example.com") // Some(Brand<"Email", string>)
const invalidEmail = EmailValidator.of("invalid") // None

const userResult = UserIdValidator.from("U123456") // Right(Brand<"UserId", string>)
const userError = UserIdValidator.from("invalid") // Left("Invalid UserId: validation failed")

// Type safety in action
function getUserByEmail(email: Email): User {
  /* ... */
}

// These calls are type-safe
const userId = UserId("U123456")
const email = Email("user@example.com")
const user = getUserByEmail(email) // Works

// These would be type errors
getUserByEmail("invalid") // Type error: Argument of type 'string' is not assignable to parameter of type 'Email'
getUserByEmail(userId) // Type error: Argument of type 'UserId' is not assignable to parameter of type 'Email'
Wire — serialization boundaries

Wire<T> marks a value in its serialization-safe shape: a DB row, an HTTP body, a JSONB payload. Zero runtime, assignable both ways with T, and the ESLint plugin's prefer-option / prefer-list skip everything inside it.

import type { Wire } from "functype"

type UserRow = Wire<{ readonly email: string | null; readonly tags: ReadonlyArray<string> }>
type UserRows = Wire<ReadonlyArray<UserRow>>

// Convert inside the pipeline
const reachable = List(rows).filter((u) => Option(u.email).isSome())
TracedOption — code-path introspection

Opt-in wrapper that emits one structured event per Option combinator to an injected Tracer:

import { TracedOption, type Tracer, type TraceEvent } from "functype"

const events: TraceEvent[] = []
const tracer: Tracer = { emit: (e) => void events.push(e) }

TracedOption(user, tracer, "span-1")
  .map((u) => u.name.trim(), "trim")
  .getOrElse(() => "anonymous", "fallback")

Conditional Programming

Functype provides Cond and Match for functional conditional logic without early returns:

Cond

OX Radar and Response Center

Find threats in your stack.

OX Radar can check high-priority threats, like critical package CVEs, against your context.

Each incident is marked Detected or Not Detected with a remediation plan and proof all tracked in the Response Center.

Where it’s listed

The probe returned only these fields for this server — auth requirement, protocol and tool list weren’t observed, so they’re not shown (never guessed).

  • npm functype

References

The publisher’s own links, as the registry reports them. These are not sources for the assessment on this page.

Scan your whole stack

Group 1261154050 1
Group 1261154050
 

From OX Research Newsroom

Microsoft's Official agent framework Hijacked
AI & VibeSec

BREAKING: Hijacked Releases of Microsoft’s Official agent-framework Steals Azure and CI Credentials

PHP2Shell, Day 5 93.6% of Measurable Instances Still Unpatched (1)
Vulnerability Insights

PHP2Shell, Day 5: The Panic Hasn’t Turned Into Patching

Cry2Wolf: How to Tell a Real Bug from a Nothingburger
AI & VibeSec

Cry2Wolf: Not Every Branded Bug Deserves a Fire Drill

Frame 2085668439 (1)
Group 1261154229