ClojureUtilitiesReference

std

Standard libraries for the foundation ecosystem.

Core utilities, concurrency, JVM tooling, integrations, and focused API references.

Library families

Start with a family overview, then follow its focused pages and walkthroughs.

Concurrency

std.concurrent

Queues, executors, requests, relays, pools, and threads.

Learn more
JVM

jvm.*

Artifacts, classloaders, namespaces, reflection, monitoring, and tools.

Learn more
Integrations

lib.*

Databases, containers, search, messaging, storage, and repositories.

Learn more
Dispatch

std.dispatch

Boards, hubs, queues, debounce, hooks, and dispatch core.

Learn more
Filesystem

std.fs

Paths, walking, archives, attributes, and watchers.

Learn more
Scheduling

std.scheduler

Runners, programs, spawns, and scheduled task lifecycle.

Learn more
Text

std.string

Case, coercion, paths, pluralization, prose, and wrapping.

Learn more
Tasks

std.task

Process and bulk task execution.

Learn more
Time

std.time

Time coercion, durations, zones, formats, and representations.

Learn more
Timeseries

std.timeseries

Journals, intervals, ranges, computation, and processing.

Learn more
Code

std.block

Code representation, traversal, and manipulation.

Learn more

std.lib

Focused foundational utilities.

Invocation

std.lib.apply

Applicative invocation and host applicatives.

Learn more
State

std.lib.atom

Nested atoms, batch updates, cursors, and derived state.

Learn more
Binary

std.lib.bin

Binary data, buffers, and low-level data handling.

Learn more
Classes

std.lib.class

Class, type, and reflection helpers.

Learn more
Collections

std.lib.collection

Extended map, sequence, tree, and diff operations.

Learn more
Lifecycle

std.lib.component

Component lifecycle and system composition primitives.

Learn more
Encoding

std.lib.encode

Encoding and decoding helpers.

Learn more
Enums

std.lib.enum

Enum and lookup helpers.

Learn more
Environment

std.lib.env

Namespace, resource, pprint, and debug utilities.

Learn more
Foundation

std.lib.foundation

Basic predicates, constructors, and helpers.

Learn more
Async

std.lib.future

Future and asynchronous coordination helpers.

Learn more
I/O

std.lib.io

I/O helpers and stream handling.

Learn more
Network

std.lib.network

Network and port utilities.

Learn more
Resources

std.lib.resource

Classpath and filesystem resource helpers.

Learn more
Schemas

std.lib.schema

Schema definitions, lookups, and validation helpers.

Learn more
Security

std.lib.security

Security, keys, providers, ciphers, and verification helpers.

Learn more
Sorting

std.lib.sort

Sorting, ordering, and topological utilities.

Learn more
Streams

std.lib.stream

Producers, collectors, pipelines, and transducers.

Learn more
Systems

std.lib.system

System topology, display, and lifecycle utilities.

Learn more
Time

std.lib.time

Time coercion and temporal helpers.

Learn more
Transforms

std.lib.transform

Composable data transformation helpers.

Learn more
Traversal

std.lib.walk

Walking and traversal helpers.

Learn more
Zippers

std.lib.zip

Zipper navigation and editing helpers.

Learn more

1    Walkthrough

The std section is organized into library families. Most workflows start by requiring the top-level namespace, then drilling into sub-namespaces for specialised behaviour.

a cross-library snippet: string case, collection transform, and time coercion

(require '[std.string :as str]
         '[std.lib.collection :as coll]
         '[std.time :as time])

(->> {"hello-world" 1 "hello-there" 2}
     (coll/map-keys str/camel-case)
     (coll/map-vals inc))
=> {"helloWorld" 2 "helloThere" 3}

(time/to-ms 1 :m)
=> 60000

2    std.config: A Comprehensive Summary (including submodules)

The std.config module provides a powerful and flexible configuration management system for Clojure applications. It allows for defining configurations using a rich set of directives, resolving values from various sources (system properties, environment variables, project files, external files, resources), and handling sensitive data through encryption. The system is designed to be extensible, supporting different configuration formats (EDN, JSON, YAML, TOML) and secure key management (GPG).

2.1    std.config (Main Namespace)

This namespace serves as the primary entry point for the configuration system, aggregating and re-exporting key functionalities from its submodules. It defines the core directives and option types that drive the configuration resolution process.

Key Re-exported Functions:

  • From std.config.global: global.n From std.config.resolve: load, resolve, resolve-key, encrypt-text, decrypt-text.n From std.config.secure: resolve-key, encrypt-text, decrypt-text.

Core Concepts:

  • Directives: Special vector forms (e.g., [:env "VAR_NAME"], [:file "path/to/file"]) that instruct the configuration system how to resolve a value.n Option Keys: Metadata associated with configuration values (e.g., :type, :secured, :key, :default).n Option Types: Supported data types for resolved content (e.g., :text, :edn, :json, :yaml, :gpg, :gpg.public).

Key Functions:

  • get-session, swap-session, clear-session: Functions for interacting with the global session atom, which can store dynamic configuration values.n +directives+: A list of all supported configuration directives.n +opt-keys+: A list of supported option keys for configuration values.n* +opt-types+: A list of supported types for resolving configuration content.

2.2    std.config.common (Common Utilities and Multimethods)

This sub-namespace defines common multimethods that serve as extension points for resolving directives and handling different content types.

Key Functions:

  • -resolve-directive (multimethod): The primary extension point for implementing new configuration directives. It dispatches based on the first element of a directive vector.n* -resolve-type (multimethod): The primary extension point for handling different content types during resolution (e.g., parsing JSON, YAML).

2.3    std.config.ext.gpg (GPG Integration)

This sub-namespace provides integration with GPG (GNU Privacy Guard) for handling encrypted configuration values.

Key Functions:

  • resolve-type-gpg-public: Resolves content to a PGP public key (org.bouncycastle.openpgp.PGPPublicKey).n* resolve-type-gpg: Resolves content to a PGP key pair (public and private keys).

2.4    std.config.ext.json (JSON Integration)

This sub-namespace provides support for resolving configuration values from JSON content.

Key Functions:

  • resolve-type-json: Resolves JSON content into a Clojure map (with keywordized keys).

2.5    std.config.ext.toml (TOML Integration)

This sub-namespace provides support for resolving configuration values from TOML content.

Key Functions:

  • resolve-type-toml: Resolves TOML content into a Clojure map (with keywordized keys).

2.6    std.config.ext.yaml (YAML Integration)

This sub-namespace provides support for resolving configuration values from YAML content.

Key Functions:

  • resolve-type-yaml: Resolves YAML content into a Clojure map.

2.7    std.config.global (Global Configuration Sources)

This sub-namespace provides functions for accessing and consolidating configuration values from various global sources, such as system properties, environment variables, project files, and user home directory files.

Core Concepts:

  • +session+: An atom for storing dynamic, session-specific configuration.n +cache: An atom for caching resolved global configuration values.n Global record: A record type for representing consolidated global configuration.

Key Functions:

  • global?: Checks if an object is a Global record.n global-raw: Constructs a Global record from a map, applying a key transformation function.n global-env-raw: Retrieves system environment variables as a Global record.n global-properties-raw: Retrieves system properties as a Global record.n global-project-raw: Retrieves project configuration (from code.project) as a Global record.n global-env-file-raw: Reads configuration from an env.edn file in the current directory.n global-home-raw: Reads configuration from a global.edn file in the user's .hara directory.n global-session-raw: Retrieves the current session configuration.n global-all-raw: Consolidates all global configuration sources into a single Global record.n* global: The primary function for retrieving global configuration from a specified source (e.g., :env, :properties, :project, :all), with optional caching.

2.8    std.config.resolve (Directive Resolution Engine)

This sub-namespace implements the core logic for resolving configuration directives and content from various sources. It uses a recursive prewalk approach to process nested directives.

Core Concepts:

  • Directive Resolution: Directives are processed recursively, allowing for complex, dynamic configuration.n Path Tracking: *current* and *path* dynamic vars track the current resolution context for error reporting.n Error Handling: Provides ex-config for creating informative exceptions during resolution.

Key Functions:

  • ex-config: Creates a configuration-specific exception.n walk, prewalk: Modified versions of clojure.walk functions for directive resolution.n directive?: Checks if a form is a configuration directive.n resolve-directive: Resolves a single directive, handling errors.n resolve: The main function for resolving a configuration form, recursively processing all directives. It can also bind a security key for decryption.n resolve-type: Dispatches to common/-resolve-type to convert content to a specific type (e.g., :edn, :json).n resolve-select: Selects specific keys or paths from resolved content.n resolve-content: Resolves content based on options like :type, :secured, :key, :default, :select.n resolve-directive-properties: Resolves values from system properties.n resolve-directive-env: Resolves values from environment variables.n resolve-directive-project: Resolves values from project metadata.n resolve-directive-format: Formats values into a string using clojure.core/format.n resolve-directive-str: Joins values into a string.n resolve-directive-or: Returns the first non-nil resolved value from a list of options.n resolve-directive-case: Implements a case statement for configuration values.n resolve-directive-error: Throws a configuration error.n resolve-directive-merge: Merges multiple configuration maps, supporting different merge strategies (:default, :nil, :nested, :nested-nil).n resolve-directive-eval: Evaluates a Clojure form within the configuration context.n resolve-map: Resolves values from a map using a path.n resolve-directive-root: Resolves a directive relative to the root of the current configuration.n resolve-directive-parent: Resolves a directive relative to the parent of the current configuration.n resolve-directive-global: Resolves a directive from the global configuration map.n resolve-path: Resolves a path string.n resolve-directive-file: Resolves content from a local file.n resolve-directive-resource: Resolves content from a classpath resource.n resolve-directive-include: Resolves content from a file or resource, searching in multiple locations.n load: Loads and resolves a configuration file (defaults to config.edn).

2.9    std.config.secure (Secure Configuration)

This sub-namespace provides functionalities for encrypting and decrypting sensitive configuration values, typically using AES encryption.

Core Concepts:

  • Master Key: Uses a master key (from +master-key+ or *key* dynamic var) for encryption/decryption.n Key Resolution: resolve-key handles various key formats (string, map, java.security.Key).n Encryption/Decryption: Leverages std.lib.security for cryptographic operations and std.lib.encode for Base64/hex encoding.

Key Functions:

  • +master-key+: The default master key, typically loaded from global configuration.n +master-defaults+: Default settings for the encryption algorithm (AES, RAW format, secret mode).n *key*: A dynamic var holding the currently active security key.n resolve-key: Resolves a key from various inputs into a java.security.Key object.n decrypt-text: Decrypts an encrypted string (Base64 or hex encoded) using a specified key.n* encrypt-text: Encrypts a plain text string and returns its Base64 or hex encoded representation.

2.10    Usage Pattern:

The std.config module is essential for managing application configurations in a flexible, dynamic, and secure manner. It's particularly useful for:

  • Environment-Specific Configurations: Easily switching configurations based on deployment environment (dev, test, prod).n Sensitive Data Handling: Storing API keys, passwords, and other secrets securely.n Modular Configuration: Breaking down large configurations into smaller, manageable files.n Dynamic Value Resolution: Resolving values from various runtime sources (environment, system properties).n Extensible Formats: Supporting different configuration file formats.

By providing a powerful and extensible configuration system, std.config enables developers to build applications that are easily configurable and adaptable to different operational contexts.

3    std.contract: A Comprehensive Summary (including submodules)

The std.contract module provides a powerful and flexible system for defining and enforcing contracts (schemas) for data and functions in Clojure applications. Built on top of the Malli library, it offers a declarative way to specify data shapes, validate inputs and outputs, and ensure type safety. This module is crucial for improving code reliability, maintainability, and for facilitating robust API design.

3.1    std.contract (Main Namespace)

This namespace serves as the primary entry point for the contract system, aggregating and re-exporting key functionalities from its submodules. It provides a high-level interface for defining and working with contracts.

Key Re-exported Functions:

  • From std.contract.sketch: maybe, opt, fn, lax, opened, tighten, closed, norm, remove, as:sketch, as:schema.n From std.contract.type: defcase, defmultispec, defspec, spec?, common-spec, multi-spec, valid?.n From std.contract.binding: defcontract.n* From malli.core: schema, schema?.

3.2    std.contract.sketch (Schema Sketching and Transformation)

This sub-namespace provides utilities for creating and transforming Malli schemas, offering a more convenient and expressive way to define data shapes. It introduces concepts like optional keys and nullable values directly into the schema definition process.

Core Concepts:

  • Optional (Optional record): Represents a key that may or may not be present in a map.n Maybe (Maybe record): Represents a value that can be nil.n Func (Func record): Represents a function schema, allowing validation of function arity or other properties.n* Schema Transformations: Functions to modify schemas, such as making keys optional, values nullable, or closing/opening map schemas.

Key Functions:

  • optional-string, maybe-string: String representations for Optional and Maybe records.n as:optional: Creates an Optional record for a key.n optional?: Checks if an object is an Optional record.n as:maybe: Creates a Maybe record for a value.n maybe?: Checks if an object is a Maybe record.n func-string, func-invoke: String representation and invocation for Func records.n fn-sym: Extracts the symbol from a function.n func-form, func (macro): Creates a Func record from a function form.n func?: Checks if an object is a Func record.n from-schema-map: Converts a Malli AST map representation into a sketch (Clojure map with Optional/Maybe records).n from-schema: Converts a Malli schema into a sketch.n to-schema-extend (multimethod): An extension point for converting custom types to Malli schemas.n to-schema: Converts a sketch or other Clojure data into a Malli schema.n lax: Transforms a map schema to make all keys optional and all values nullable (maybe).n norm: Transforms a map schema to make all keys required (removes optionality).n closed: Closes a map schema, disallowing extra keys.n opened: Opens a map schema, allowing extra keys.n tighten: Transforms a map schema to make all keys required and all values non-nullable (removes maybe).n remove: Removes keys from a map schema.

3.3    std.contract.type (Contract Definition and Validation)

This sub-namespace provides the core mechanisms for defining and validating data against schemas. It introduces CommonSpec for single schemas and MultiSpec for multimethod-like schema dispatch.

Core Concepts:

  • CommonSpec: A record that wraps a single Malli schema, providing methods for validation and introspection.n MultiSpec: A record that manages multiple schemas, dispatching to the appropriate one based on a dispatch function, similar to defmulti.n Schema Validation: Uses Malli's validate and explain functions for robust data validation.

Key Functions:

  • check: Validates data against a schema and throws an informative exception if invalid.n common-spec-invoke, common-spec-string: Invocation and string representation for CommonSpec.n combine: Merges multiple schemas (typically map schemas).n common-spec: Creates a CommonSpec from one or more sketches/schemas.n defspec (macro): Defines a named CommonSpec.n multi-spec-invoke, multi-spec-string: Invocation and string representation for MultiSpec.n multi-gen-final: Generates the final Malli schema for a MultiSpec.n multi-spec-add: Adds a new case (dispatch value and schema) to a MultiSpec.n multi-spec-remove: Removes a case from a MultiSpec.n multi-spec: Creates a MultiSpec from a dispatch function and a map of cases.n defmultispec (macro): Defines a named MultiSpec.n defcase (macro): Adds a case to an existing MultiSpec.n spec?: Checks if an object is a CommonSpec or MultiSpec.n* valid?: Checks if data is valid against a spec, returning true or false.

3.4    std.contract.binding (Function Contract Binding)

This sub-namespace provides a mechanism to bind contracts directly to functions, enabling automatic input and output validation when the function is invoked.

Core Concepts:

  • Contract record: Encapsulates a function, its input schemas, and its output schema.n* Function Interception: When a contract is bound to a var, the contract itself becomes the var's value, intercepting calls to perform validation.

Key Functions:

  • contract-info: Returns information about a contract.n contract-invoke: Invokes the underlying function of a contract, performing input and output validation.n contract-string: String representation for Contract.n Contract (defimpl record): The concrete record type for a function contract.n contract?: Checks if an object is a Contract record.n contract-var?: Checks if a var's value is a Contract.n bound?: Checks if a contract is currently bound to its target var.n unbind: Removes a contract from a var, restoring the original function.n bind: Binds a contract to a var, replacing the original function with the contract.n parse-arg: Parses an input/output argument definition into a spec and options.n contract: Creates a Contract record.n* defcontract (macro): Defines a contract and binds it to a function var, enabling automatic validation.

3.5    Usage Pattern:

The std.contract module is invaluable for:

  • API Design and Enforcement: Clearly defining the expected structure of data for APIs and ensuring adherence.n Robustness: Catching data inconsistencies and invalid inputs early, preventing bugs.n Documentation: Schemas serve as living documentation for data structures.n Code Clarity: Making explicit the assumptions about data shapes.n Metaprogramming: Programmatically generating and manipulating schemas.n* Test-Driven Development: Writing tests that validate data against contracts.

By integrating Malli and providing a Clojure-idiomatic way to define and enforce contracts, std.contract significantly enhances the reliability and maintainability of foundation-base applications.

4    std.dom: A Comprehensive Summary (including submodules)

The std.dom module provides a powerful and flexible framework for building and managing user interfaces (UIs) in Clojure, inspired by concepts from React and other declarative UI libraries. It introduces a "code-as-data" approach to UI definition, allowing developers to describe UI structures as Clojure data (DOMs) which can then be rendered, updated, and manipulated efficiently. The module supports component-based development, local state management, reactive updates, and a robust diffing/patching mechanism for optimized UI rendering.

4.1    std.dom (Main Namespace)

This namespace serves as the primary entry point for the DOM system, aggregating and re-exporting key functionalities from its submodules. It provides a high-level interface for creating, manipulating, and interacting with DOM structures.

Key Re-exported Functions:

  • From std.dom.common: dom-attach, dom-children, dom-compile, dom-create, dom-detach, dom-item, dom-item?, dom-equal?, dom-metaclass, dom-metaprops, dom-metatype, dom-split-props, dom-top, dom-trigger, dom-vector?, dom?, dom-assert.n From std.dom.component: defcomp, dom-state-handler.n From std.dom.diff: dom-diff, dom-ops.n From std.dom.event: event-handler, handle-event.n From std.dom.find: dom-match?, dom-find, dom-find-all.n From std.dom.impl: dom-init, dom-remove, dom-render, dom-rendered, dom-replace.n From std.dom.item: item-constructor, item-setters, item-getters, item-access, item-create, item-props-set, item-props-delete, item-update, item-cleanup.n From std.dom.local: local, local-dom, local-dom-state, local-parent, local-parent-state, dom-send-local, dom-set-local.n From std.dom.react: react, dom-set-state.n From std.dom.type: metaclass, metaclass-add, metaclass-remove, metaprops, metaprops-add, metaprops-remove, metaprops-install.n From std.dom.update: dom-apply, dom-update.

4.2    std.dom.common (Core DOM Structure and Utilities)

This sub-namespace defines the fundamental Dom record, its properties, and common operations for creating, formatting, and comparing DOM nodes.

Core Concepts:

  • Dom Record: The central data structure representing a UI node. It contains tag, props, item (the actual rendered UI element), parent, handler, shadow (for components), cache, and extra metadata.n Metaclass/Metatype/Metaprops: A system for classifying and describing different types of UI elements (e.g., :dom/element, :dom/component, :dom/value).n DOM Tree: DOM nodes form a tree structure, with parent and implicit child relationships.

Key Functions:

  • dom?: Checks if an object is a Dom record.n dom-metaprops, dom-metatype, dom-metaclass: Accessors for metadata about a DOM node's type.n component?, element?, value?: Predicates for checking the metatype of a DOM node.n dom-item, dom-item?: Accessors for the actual rendered UI element associated with a DOM node.n dom-top: Returns the top-most ancestor of a DOM node.n dom-split-props: Splits properties into different categories (e.g., event handlers, regular props).n props-apply: Applies a function to properties, potentially recursing into nested DOMs.n dom-new: Creates a new Dom record.n dom-children, children->props: Functions for managing children within DOM props.n dom-create: Creates a Dom record from a tag, props, and children.n dom-format: Formats a Dom record for printing (e.g., [:- :tag {:prop val} child]).n dom-tags-equal?, dom-props-equal?, dom-equal?: Functions for comparing DOM nodes.n dom-clone: Creates a shallow copy of a DOM node.n dom-vector?: Checks if a vector represents a valid DOM structure.n dom-compile: Compiles a nested vector structure into a tree of Dom records.n dom-attach, dom-detach: Attaches or detaches an event handler to a DOM node.n dom-trigger: Triggers an event, propagating it up the DOM hierarchy.n* dom-assert: Asserts that required properties are present.

4.3    std.dom.component (Component-Based Development)

This sub-namespace provides the foundation for defining reusable UI components, supporting different component types (static, local, reactive) and lifecycle hooks.

Core Concepts:

  • Component Types: :static (purely functional, no internal state), :local (manages local state), :react (reactive to external state changes).n Lifecycle Hooks: pre-render, post-render, pre-update, post-update, pre-remove, post-remove, wrap-template.n Shadow DOM: Components maintain a "shadow DOM" (:shadow field) which is their rendered output, allowing for efficient diffing.

Key Functions:

  • dom-component?: Checks if a DOM node represents a component.n component-options: Prepares component options by merging mixins and template functions.n component-install: Installs a component definition into the metaprops registry.n defcomp (macro): Defines a new UI component.n dom-render-component: Renders a component, executing its template and rendering its shadow DOM.n child-components: Collects child components within a DOM tree.n dom-remove-component: Removes a rendered component.n dom-ops-component: Generates diff operations for components.n dom-apply-component: Applies diff operations to a component.n dom-replace-component: Replaces a component with a new one.n dom-state-handler: A generic handler for updating component local state.

4.4    std.dom.diff (DOM Diffing Algorithm)

This sub-namespace implements a diffing algorithm to efficiently compare two DOM trees and generate a minimal set of operations (an "edit script") to transform one into the other. This is crucial for optimizing UI updates.

Core Concepts:

  • Edit Script: A list of operations (e.g., [:set key new-val old-val], [:delete key old-val], [:update key ops], [:list-insert index items], [:list-remove index count], [:replace new-dom old-dom]).n* Keyed Lists: Supports diffing lists of DOMs using a :dom/key property for efficient element tracking.

Key Functions:

  • dom-ops (multimethod): Generates diff operations for a given tag and old/new properties.n diff-list-element: Diffs individual elements within a list.n diff-list-elements: Diffs elements in two lists.n diff-list-dom: Diffs lists of DOMs using :dom/key.n diff-list: Generates diff operations for lists (both keyed and unkeyed).n diff-props-element: Diffs individual properties within a map.n diff-props: Generates diff operations for property maps.n dom-ops-default: Default implementation for dom-ops.n dom-diff: The main function for computing the difference between two DOM trees.

4.5    std.dom.event (Event Handling)

This sub-namespace provides a standardized mechanism for handling UI events, including event propagation and dispatching to appropriate handlers.

Key Functions:

  • event-params: Converts event input into a standardized map.n event-handler: Finds the most appropriate event handler by traversing the DOM hierarchy.n handle-local: Handles events specifically for local components.n* handle-event: The main function for handling an event, dispatching it to the correct handler based on its ID and type.

4.6    std.dom.find (DOM Traversal and Querying)

This sub-namespace provides functions for searching and matching DOM nodes within a DOM tree.

Key Functions:

  • dom-match?: Checks if a DOM node's property matches a given value or predicate.n dom-find-props: Recursively searches for a DOM node within properties.n dom-find: Finds the first matching DOM node in a tree.n dom-find-all-props: Recursively finds all matching DOM nodes within properties.n dom-find-all: Finds all matching DOM nodes in a tree.

4.7    std.dom.impl (DOM Rendering and Manipulation)

This sub-namespace provides the core implementation for rendering, removing, and replacing DOM nodes, acting as the interface to the underlying UI toolkit.

Key Functions:

  • dom-render (multimethod): Renders a DOM node into an actual UI element.n dom-render-default: Default implementation for dom-render, which constructs the UI element using item-constructor and sets its properties using item-setters.n dom-init: Renders a DOM node if it hasn't been rendered yet.n dom-rendered: Renders a DOM form and returns the actual UI element.n dom-remove (multimethod): Removes a rendered UI element from the display.n dom-remove-default: Default implementation for dom-remove.n dom-replace (multimethod): Replaces one rendered UI element with another.n* dom-replace-default: Default implementation for dom-replace.

4.8    std.dom.invoke (DOM Invocation and Extension)

This sub-namespace provides a mechanism for extending the DOM system with new UI element types and components through std.protocol.invoke/-invoke-intern.

Key Functions:

  • invoke-intern-dom: A multimethod for defining new DOM element types (:value, :element) and components (:react, :local, :static).

4.9    std.dom.item (UI Element Abstraction)

This sub-namespace provides an abstraction layer for interacting with the actual UI elements (e.g., JavaFX nodes, HTML elements). It defines how to construct, set properties, get properties, and clean up these elements.

Key Functions:

  • item-constructor (multimethod): Returns the constructor function for a UI element based on its tag.n item-setters (multimethod): Returns a map of setter functions for a UI element's properties.n item-getters (multimethod): Returns a map of getter functions for a UI element's properties.n item-access: Accesses a property of a UI element using its getter.n item-create: Creates a new UI element.n item-props-update (multimethod): Updates properties of a UI element based on diff operations.n item-props-set (multimethod): Sets properties of a UI element.n item-props-delete (multimethod): Deletes properties from a UI element.n item-update: Applies a list of diff operations to a UI element.n item-set-list (multimethod): Updates a list property of a UI element.n item-cleanup (multimethod): Cleans up a UI element when it's removed.

4.10    std.dom.local (Local State Management)

This sub-namespace provides a mechanism for managing local, mutable state within UI components, allowing components to have their own internal state that can be updated reactively.

Core Concepts:

  • Local State: Components can declare local state, which is managed by an atom.n* Watches and Triggers: Changes to local state can trigger watches and events.

Key Functions:

  • local-dom: Returns the nearest local component DOM in the hierarchy.n local-dom-state: Returns the state atom of the nearest local component.n local-parent, local-parent-state: Accessors for the parent local component and its state.n dom-ops-local: Generates diff operations for local component properties.n local-watch-create, local-watch-add, local-watch-remove: Functions for managing watches on local state.n local-trigger-add, local-trigger-remove: Functions for managing event triggers.n local-split-props: Splits properties into watchable and triggerable categories.n local-set: Sets local state properties and manages watches/triggers.n dom-send-local: Sends local events up the DOM hierarchy.n dom-apply-local: Applies diff operations to a local component.n localized-watch: Sets up initial watches and triggers for a local component.n dom-set-local: Sets a specific local state value.n localized-handler: Creates a handler for local component events.n localized-pre-render, localized-wrap-template, localized-pre-remove: Lifecycle hooks for local components.n localized: A mixin map for local components.n* local: Accesses local state within a component.

4.11    std.dom.mock (Mock UI Elements)

This sub-namespace provides mock implementations of UI elements for testing and development purposes, allowing DOM structures to be rendered and manipulated without a real UI toolkit.

Key Functions:

  • mock?: Checks if an object is a mock UI element.n mock-format: Formats a mock UI element for printing.n item-props-delete-mock, item-props-set-mock, item-set-list-mock: Custom property manipulation functions for mock elements.

4.12    std.dom.react (Reactive State Management)

This sub-namespace provides a reactive state management system for UI components, allowing components to automatically re-render when their dependencies (atoms) change.

Core Concepts:

  • *react*: A dynamic var (volatile atom) that collects all atoms accessed within a reactive component's render function.n* Watches: Components automatically add watches to their dependent atoms, triggering re-renders on change.

Key Functions:

  • reactive-pre-render: Sets up the reactive context for a component.n reactive-wrap-template: Wraps a component's template function to track atom dependencies.n reactive-pre-remove: Cleans up reactive watches.n reactive: A mixin map for reactive components.n react: Accesses a value from an atom, registering it as a dependency for the current reactive component.n* dom-set-state: Sets a state value in an atom, potentially triggering reactive updates.

4.13    std.dom.type (DOM Type System)

This sub-namespace defines the type system for DOM nodes, including metaclasses and metaprops, which describe the characteristics and behavior of different UI elements.

Core Concepts:

  • Metaclass: A classification of UI elements (e.g., :dom/value, :dom/element, :dom/component).n* Metaprops: Metadata associated with a specific UI tag (e.g., :mock/label), including its metaclass, metatype, constructor, and property definitions.

Key Functions:

  • +metaclass+, +metaprops-tag+: Atoms storing metaclass and metaprops definitions.n metaclass, metaclass-remove, metaclass-add: Functions for managing metaclass definitions.n metaprops, metaprops-add, metaprops-remove, metaprops-install: Functions for managing metaprops definitions.

4.14    std.dom.update (DOM Update and Patching)

This sub-namespace applies the diff operations generated by std.dom.diff to a rendered DOM tree, efficiently updating the UI.

Key Functions:

  • dom-apply (multimethod): Applies a list of diff operations to a DOM node.n update-set: Applies a :set operation to properties.n update-list-insert, update-list-remove, update-list-update, update-list-append, update-list-drop: Functions for applying list-specific diff operations.n update-list: Applies list diff operations to a property.n update-props-delete, update-props-update: Functions for applying property-specific diff operations.n update-props: Applies diff operations to a property map.n dom-apply-default: Default implementation for dom-apply.n dom-update: Updates a DOM node to match a new DOM node by computing and applying diffs.n dom-refresh: Refreshes a DOM node, typically used for components.

4.15    Usage Pattern:

The std.dom module is essential for building dynamic and interactive user interfaces in Clojure. It provides:

  • Declarative UI: Define UI as data, making it easier to reason about and manipulate.n Component-Based Architecture: Promote reusability and modularity in UI development.n Efficient Updates: Diffing and patching algorithms minimize UI re-renders.n Reactive Programming: Automatic UI updates in response to state changes.n Local State Management: Encapsulate component-specific state.n* Extensibility: A protocol-driven design allows for integration with various UI toolkits (e.g., JavaFX, HTML/JS).

By offering a comprehensive set of tools for UI definition, rendering, and management, std.dom empowers developers to create sophisticated user experiences within the foundation-base ecosystem.

5    std.html: A Comprehensive Summary

The std.html namespace provides a Clojure-idiomatic way to parse, manipulate, and generate HTML content, leveraging the powerful Jsoup Java library. It allows developers to represent HTML as Clojure data structures (trees), convert between these trees and Jsoup Node objects, and perform common HTML operations like parsing, formatting, and CSS-like selection. This module is particularly useful for web scraping, HTML templating, and processing HTML content within Clojure applications.

5.1    Core Concepts:

  • Jsoup Integration: The module is built on top of Jsoup, providing access to its robust HTML parsing and manipulation capabilities.n HTML as Data: HTML structures are represented as Clojure vectors, where the first element is a keyword representing the tag, followed by an optional map of attributes, and then child elements (which can be strings, other vectors, or Jsoup Node objects).n Node Objects: Jsoup Node objects (e.g., Element, TextNode, Document) are used internally for efficient HTML manipulation.n* Conversion Functions: A set of functions for seamless conversion between HTML strings, Jsoup Node objects, and Clojure tree representations.

5.2    Key Functions:

  • node->tree (multimethod):n Purpose: Converts a Jsoup Node object (or its subclasses like Element, TextNode, Document) into a Clojure tree representation.n Usage: (node->tree (parse "<body><div>hello</div>world</body>"))n tree->node:n Purpose: Converts a Clojure tree representation of HTML into a Jsoup Element object.n Usage: (tree->node [:body [:div "hello"] "world"])n* **parse**:n * **Purpose:** Parses an HTML string into a Jsoup Element object. It intelligently handles different HTML structures (full HTML, body fragments).n * **Usage:** (parse "
    hello
    world")n* **inline**:n * **Purpose:** Removes all newlines from an HTML string, effectively inlining it.n * **Usage:** (inline (html [:body [:div "hello"] "world"]))n
    tighten:n Purpose: Removes unnecessary newlines and whitespace from HTML elements that contain no internal elements, making the HTML more compact.n Usage: (tighten "<b>&#92;nhello&#92;n</b>")n generate:n Purpose: Generates a formatted HTML string from a Jsoup Element object.n Usage: (generate (tree->node [:body [:div "hello"] "world"]))n* **html**:n * **Purpose:** A versatile function that converts various representations (string, vector tree, Jsoup Node) into a formatted HTML string.n * **Usage:** (html [:body [:div "hello"] "world"])n html-inline:n Purpose: Generates an inlined HTML string (without newlines) from a representation.n Usage: (html-inline [:body [:div "hello"] "world"])n* **node**:n * **Purpose:** Converts various representations (string, vector tree) into a Jsoup Node object.n * **Usage:** (node [:body [:div "hello"] "world"])n tree:n Purpose: Converts various representations (string, Jsoup Node) into a Clojure tree representation of HTML.n Usage: (tree +content+)n IText Protocol:n Purpose: Defines a text method for extracting the text content from Jsoup Elements or Element objects.n select:n Purpose: Applies a CSS selector query to a Jsoup Element and returns matching Elements.n Usage: (select my-node "div.my-class")n select-first:n Purpose: Applies a CSS selector query and returns the first matching Element.n * Usage: (select-first my-node "p")

5.3    Usage Pattern:

This namespace is highly valuable for:

  • Web Scraping: Easily parsing HTML from web pages and extracting specific data using CSS selectors.n HTML Templating: Generating dynamic HTML content from Clojure data.n Content Transformation: Modifying existing HTML structures programmatically.n Testing: Creating and asserting against HTML structures in tests.n Data Extraction: Extracting text or attributes from HTML documents.

By providing a seamless bridge between Clojure data and Jsoup's HTML manipulation capabilities, std.html empowers developers to work with HTML content effectively within their Clojure applications.

6    std.image: A Comprehensive Summary (including submodules)

The std.image module provides a comprehensive and extensible framework for image processing in Clojure. It abstracts away the complexities of underlying image representations (like Java's AWT BufferedImage) and offers a unified API for reading, writing, manipulating, and displaying images. The module emphasizes a "code-as-data" approach, allowing image properties and operations to be expressed as Clojure data structures.

6.1    std.image (Main Namespace)

This namespace serves as the primary entry point for image operations, aggregating and re-exporting key functionalities from its submodules. It defines core image concepts and provides high-level functions for common image tasks.

Core Concepts:

  • IRepresentation Protocol: The central abstraction for image data, defining methods for accessing image channels, size, model, and raw data, as well as creating subimages.n ITransfer Protocol: Defines methods for converting image data between different formats (e.g., byte-gray, int-argb) and writing images to sinks.n ISize Protocol: Defines methods for accessing image width and height.n* Default Settings: Dynamic vars (*default-type*, *default-model*, *default-view*) for configuring default image handling.

Key Functions:

  • default-type: Sets or retrieves the default image type (e.g., BufferedImage).n default-model: Sets or retrieves the default image model (e.g., :int-argb).n default-view: Sets or retrieves the default display view (e.g., :awt).n image?: Checks if an object is an image (implements IRepresentation).n image-channels: Returns the raw channel data of an image.n image-size: Returns the size (width, height) of an image.n image-model: Returns the color model of an image.n image-data: Returns the raw pixel data of an image.n size?: Checks if an object represents an image size.n height, width: Returns the height or width of an image or size object.n subimage: Extracts a rectangular subimage.n blank: Creates a blank image of a specified size and model.n read: Reads an image from a source (e.g., file path) into a specified model and type.n to-byte-gray: Converts an image to a byte-gray representation.n to-int-argb: Converts an image to an int-argb representation.n write: Writes an image to a sink (e.g., file path).n image: Creates an image from size, model, and data.n coerce: Converts an image to a different type or model.n display-class: Shows which types can be displayed.n* display: Displays an image using a specified viewer.

6.2    std.image.awt (AWT Integration)

This sub-namespace provides the concrete implementation for handling images using Java's Abstract Window Toolkit (AWT) BufferedImage. It extends the std.image.protocol to BufferedImage and provides AWT-specific I/O and display functionalities.

Key Functions:

  • Extends BufferedImage to IRepresentation and ITransfer.n image (multimethod): Creates a BufferedImage from image data.n blank (multimethod): Creates a blank BufferedImage.n read (multimethod): Reads an image into a BufferedImage.n display (multimethod): Displays a BufferedImage in an AWT/Swing window.n* display-class (multimethod): Returns #{BufferedImage}.

6.3    std.image.awt.common (AWT Common Utilities)

This sub-namespace provides helper functions for working with AWT BufferedImage objects, including extracting size, model, and data, and performing conversions.

Key Functions:

  • type-lookup, name-lookup: Maps between AWT BufferedImage types and std.image model labels.n image-size: Returns the size of a BufferedImage.n image-model: Returns the std.image model of a BufferedImage.n image-data: Returns the raw pixel data of a BufferedImage.n image-channels: Returns the channel data of a BufferedImage.n subimage: Extracts a subimage from a BufferedImage.n image-to-byte-gray: Converts a BufferedImage to byte-gray data.n image-to-int-argb: Converts a BufferedImage to int-argb data.n image: Creates a BufferedImage from std.image data.

6.4    std.image.awt.display (AWT Image Display)

This sub-namespace provides functionality for displaying BufferedImage objects in a Swing JFrame.

Key Functions:

  • create-viewer: Creates a Swing JFrame and JComponent for displaying images.n* display: Displays a BufferedImage in the created viewer, with options for channel selection.

6.5    std.image.awt.io (AWT Image I/O)

This sub-namespace provides functions for reading and writing BufferedImage objects using javax.imageio.ImageIO.

Key Functions:

  • providers: Lists available ImageIO service providers (readers, writers, transcoders).n supported-formats: Lists supported image formats (e.g., PNG, JPEG).n awt->int-argb: Converts an indexed or custom BufferedImage to TYPE_INT_ARGB.n read: Reads an image from an input source into a BufferedImage.n write: Writes a BufferedImage to an output sink in a specified format.

6.6    std.image.awt.rendering (AWT Rendering Hints)

This sub-namespace provides utilities for configuring rendering hints for Java2D Graphics2D objects, allowing control over image quality and performance.

Key Functions:

  • hint-lookup, hint-keys, hint-values: Maps between keyword representations of rendering hints and their AWT RenderingHints constants.n hint-options: Lists available options for rendering hints.n hints: Creates a map of RenderingHints objects from keyword options.

6.7    std.image.base (Base Image Representation)

This sub-namespace defines a generic, data-oriented Image record that serves as a common representation for image data, independent of specific AWT BufferedImage implementations. It extends the std.image.protocol to this Image record.

Key Functions:

  • Image record: A record that holds model, size, and data for an image.n image: Creates an Image record.n read (multimethod): Reads an image into an Image record.n blank (multimethod): Creates a blank Image record.n display (multimethod): Displays an Image record.n* display-class (multimethod): Returns #{std.image.base.Image}.

6.8    std.image.base.common (Base Image Common Utilities)

This sub-namespace provides fundamental operations for manipulating the generic Image record, including channel creation, copying, subimaging, and conversions between different standard image types (color, grayscale).

Key Functions:

  • create-channels: Creates raw data arrays for image channels based on a model.n empty: Creates an empty Image record.n copy: Creates a copy of an Image record.n subimage: Extracts a subimage from an Image record.n display-standard-data: Converts raw image data (arrays) into Clojure vectors for display.n standard-color-data->standard-gray: Converts standard color data to standard grayscale data.n standard-color->standard-gray: Converts a standard color image to a standard grayscale image.n standard-gray->standard-color: Converts a standard grayscale image to a standard color image.n standard-type->standard-type: Converts between standard image types (color/gray).n mask-value: Extracts a value from an integer using a bitmask.n shift-value: Shifts a value by a specified number of bits.n retrieve-single: Retrieves a single channel's data from an image.n slice: Extracts a single channel (e.g., red, green, blue, alpha) from an image as a new grayscale image.n retrieve-all: Retrieves all channel data from an image.n color->standard-color: Converts a color image to a standard color image.n gray->standard-gray: Converts a grayscale image to a standard grayscale image.n type->standard-type: Converts an image to a standard type (color or gray).n set-single-val: Calculates a single pixel value from channel inputs.n set-single: Sets a single channel's data.n set-all: Sets all channels' data according to a model.n convert-base: Converts an image between different models via standard intermediate types.n convert: Converts an image to a specified model.n base-map: Returns the base map representation of an image.

6.9    std.image.base.display (Base Image Display)

This sub-namespace provides functions for rendering generic Image records as ASCII art strings, suitable for console output.

Key Functions:

  • render-string: Renders rows of pixel values into an ASCII string using a gradient table.n byte-gray->rows: Converts byte-gray data into rows of pixel values.n render-byte-gray: Renders a byte-gray image as an ASCII string.n int-argb->rows: Converts int-argb data into rows of grayscale pixel values.n render-int-argb: Renders an int-argb image as an ASCII string.n render: Renders an image (potentially slicing a channel) into an ASCII string.n display: Prints an ASCII representation of an image to the console.n* animate: Animates a sequence of images in the console.

6.10    std.image.base.display.gradient (ASCII Gradient Generation)

This sub-namespace provides utilities for generating ASCII character gradients, used by std.image.base.display to render images as text.

Key Functions:

  • ramp-dark, ramp-light: Predefined strings of characters for dark and light gradients.n create-lookup: Creates a lookup map for characters based on a range.n create-single: Creates a single-character gradient map.n create-multi: Creates a multi-character gradient map (for wider pixels).n lookup-char: Looks up a character from a gradient table based on a numeric value.

6.11    std.image.base.model (Image Color Models)

This sub-namespace defines a comprehensive set of image color models, specifying how pixel data is organized and interpreted.

Core Concepts:

  • model-lookup: A map defining various image models (e.g., :int-argb, :byte-gray, :3-byte-rgb), including their type (:color, :gray), metadata (channel types, spans), and data access definitions.n* Channel Access: Defines how to extract and combine individual color channels (alpha, red, green, blue) from raw pixel data.

Key Functions:

  • create-model: Creates an image model definition from a label.n *defaults*: Default color and grayscale models.n model-inv-table: Creates an inverse access table for setting data within an image.n* model: Creates an image model, allowing for overwrites of predefined models.

6.12    std.image.base.size (Image Size Utilities)

This sub-namespace provides utilities for working with image dimensions (width and height).

Key Functions:

  • Extends IPersistentVector and IPersistentMap to ISize.n size->map: Converts a size representation (vector or map) to a map with :width and :height.n length: Calculates the total number of pixels (width * height).

6.13    std.image.base.util (Base Image Low-Level Utilities)

This sub-namespace provides low-level utility functions for bit manipulation, array conversions, and generating code for packing/unpacking pixel data.

Key Functions:

  • type-lookup: Maps Java primitive types to their properties (size, array functions, unchecked functions, aset functions).n int->bytes, bytes->int: Converts between integers and byte arrays (for ARGB values).n array-fn: Returns the appropriate primitive array constructor function based on element size.n mask: Generates a bitmask.n form-params: Returns bitmasks and start positions for packing/unpacking values.n <<form, <<fn, <<: Functions for generating code and applying functions to pack multiple values into a single integer.n >>form, >>fn, >>: Functions for generating code and applying functions to unpack a single integer into multiple values.n byte-argb->byte-gray, int-argb->byte-gray: Converts ARGB data to grayscale.n byte-gray->int-argb: Converts grayscale data to ARGB.

6.14    std.image.protocol (Image Protocols)

This sub-namespace defines the core protocols that abstract image representation, manipulation, and display, allowing for extensible image handling.

Key Protocols:

  • ISize: Defines -width and -height.n IRepresentation: Defines -channels, -size, -model, -data, -subimage.n ITransfer: Defines -to-byte-gray, -to-int-argb, -write.n ITransform: Defines -op for image transformations.n Multimethods: -image, -blank, -read, -display, -display-class.

6.15    Usage Pattern:

The std.image module is essential for any Clojure application that needs to perform image processing tasks. It provides:

  • Unified API: A consistent way to interact with images regardless of their underlying representation.n Extensibility: New image types and operations can be added by extending protocols.n Data-Oriented Approach: Image data and models are represented as Clojure data, facilitating manipulation.n Low-Level Control: Access to raw pixel data and bit manipulation utilities.n Debugging and Visualization: ASCII rendering for quick inspection of image content.

By offering a comprehensive and extensible image processing framework, std.image empowers developers to integrate image functionalities seamlessly into their Clojure applications.

7    std.json: A Comprehensive Summary

The std.json namespace provides a robust and flexible API for serializing and deserializing Clojure data to and from JSON format. It leverages the Jackson JSON processor, offering extensive customization options for handling various Clojure data types, including keywords, symbols, ratios, vars, and persistent collections. The module aims to provide a seamless and efficient way to work with JSON data in Clojure applications.

7.1    Core Concepts:

  • Jackson Integration: Built on top of com.fasterxml.jackson.databind.ObjectMapper, providing high-performance JSON processing.n Clojure Data Type Support: Custom serializers and deserializers are provided for common Clojure data structures and types, ensuring correct round-tripping between Clojure and JSON.n Customization: Offers various options for configuring the ObjectMapper, such as pretty printing, handling BigDecimals, escaping non-ASCII characters, and custom key encoding/decoding.n* Protocol-based I/O: Uses protocols (ReadValue, WriteValue) to abstract over different input/output sources (strings, files, streams).

7.2    Key Functions:

  • clojure-module:n Purpose: Creates a com.fasterxml.jackson.databind.module.SimpleModule that registers custom serializers and deserializers for Clojure types.n Options: Supports encode-key-fn, decode-key-fn for custom key transformations, encoders for additional custom serializers, and date-format.n object-mapper:n Purpose: Creates and configures a com.fasterxml.jackson.databind.ObjectMapper instance with the clojure-module and other specified options.n Options: pretty (for pretty printing), bigdecimals, escape-non-ascii, and modules for registering additional Jackson modules.n +default-mapper+: A default ObjectMapper instance with basic Clojure serialization.n +keyword-mapper+: An ObjectMapper that deserializes JSON keys to Clojure keywords.n +keyword-case-mapper+: An ObjectMapper that deserializes JSON keys to Clojure keywords, converting them to spear-case.n +keyword-js-mapper+: An ObjectMapper that deserializes JSON keys, replacing underscores with hyphens and converting to keywords.n +keyword-spear-mapper+: An ObjectMapper that deserializes JSON keys, replacing spaces with hyphens and converting to keywords.n ReadValue Protocol:n Purpose: Defines the -read-value method for reading JSON from various sources (File, URL, String, Reader, InputStream).n WriteValue Protocol:n Purpose: Defines the -write-value method for writing JSON to various sinks (File, OutputStream, DataOutput, Writer).n read:n Purpose: Reads JSON content from an object (string, file, stream) and deserializes it into Clojure data.n Usage: (read "{&#92;"a&#92;":1,&#92;"b&#92;":2}") => {"a" 1, "b" 2}n write:n Purpose: Serializes Clojure data into a JSON string.n Usage: (write {:a 1 :b 2}) => "{&#92;"a&#92;":1,&#92;"b&#92;":2}"n write-pp:n Purpose: Serializes Clojure data into a pretty-printed JSON string.n Usage: (write-pp {:a 1 :b 2})n write-bytes:n Purpose: Serializes Clojure data into a JSON byte array.n Usage: (String. (write-bytes {:a 1 :b 2}))n write-to:n Purpose: Writes Clojure data as JSON to a specified sink (file, output stream).n Usage: (write-to my-output-stream {:a 1 :b 2})n sys:resource-json:n * Purpose: Reads and caches JSON content from a classpath resource, deserializing keys to spear-case keywords.

7.3    Usage Pattern:

This namespace is crucial for any Clojure application that needs to:

  • Interact with Web Services/APIs: Send and receive JSON data.n Store Configuration: Use JSON as a configuration file format.n Data Exchange: Exchange data with other systems that use JSON.n* Logging: Log structured data in JSON format.

By providing a powerful, customizable, and efficient JSON serialization/deserialization library, std.json simplifies working with JSON data in Clojure applications.

8    std.lib Recommendations

Here are some recommendations for new functionality in the broader std.lib codebase. These suggestions aim to fill in some common gaps in a foundational library and would make the foundation-base ecosystem more self-contained and powerful.

  • std.lib.json:n Justification: JSON is the de-facto standard for data interchange on the web. A dedicated namespace for JSON operations would be extremely valuable for any part of the system that needs to interact with web services or read/write configuration files.n Recommended Functionality:n encode: Serializes a Clojure data structure to a JSON string.n decode: Parses a JSON string into a Clojure data structure.n Support for custom encoders/decoders for custom data types.n Functions for working with JSON schemas for validation.n Example Usage:n ```clojuren (require '[std.lib.json :as json])nn (def my-map {:a 1 :b "hello"})n (def json-string (json/encode my-map))n ;; => "{\"a\":1,\"b\":\"hello\"}"nn (json/decode json-string)n ;; => {:a 1, :b "hello"}n ```nn std.lib.http:n Justification: Many modern applications need to communicate with other services over HTTP. A built-in HTTP client would simplify this greatly, providing a consistent API for making requests and handling responses.n Recommended Functionality:n Functions for all standard HTTP methods: get, post, put, delete, patch.n Easy ways to set headers, query parameters, and request bodies.n Automatic parsing of response bodies (e.g., JSON).n Support for both synchronous and asynchronous requests (leveraging std.lib.future).n Connection pooling for performance.n Example Usage:n ```clojuren (require '[std.lib.http :as http])nn (def response (http/get "https://api.example.com/users/1"))n (:body response)n ;; => {:id 1, :name "John Doe"}n ```nn std.lib.csv:n Justification: CSV is a common format for data import/export. A library for handling CSV files would be useful for data processing tasks.n Recommended Functionality:n read-csv: Reads a CSV file into a sequence of maps or vectors.n write-csv: Writes a sequence of maps or vectors to a CSV file.n Options for specifying delimiters, quote characters, and headers.n Example Usage:n ```clojuren (require '[std.lib.csv :as csv])nn (def data [{:name "John", :age 30} {:name "Jane", :age 25}])n (csv/write-csv "users.csv" data)nn (csv/read-csv "users.csv")n ;; => [{:name "John", :age "30"}, {:name "Jane", :age "25"}]n ```nn std.lib.xml:n Justification: While less common than JSON, XML is still used in many enterprise systems and for configuration files. An XML parsing and generation library would be a valuable addition.n Recommended Functionality:n parse: Parses an XML string or file into a Clojure data structure (e.g., a nested map).n emit: Emits a Clojure data structure as an XML string.n Support for namespaces and attributes.n Example Usage:n ```clojuren (require '[std.lib.xml :as xml])nn (def xml-string "John")n (xml/parse xml-string)n ;; => {:tag :user, :content [{:tag :name, :content ["John"]}]}n ```nn std.lib.crypto:n Justification: std.lib.security provides a good foundation, but a more comprehensive and higher-level cryptography library would be beneficial for applications with more advanced security requirements.n Recommended Functionality:n Symmetric encryption with common algorithms like AES-GCM.n Asymmetric encryption with RSA and EC.n Digital signatures with RSA and ECDSA.n Password hashing with algorithms like bcrypt or scrypt.n Key derivation functions.n Example Usage:n ```clojuren (require '[std.lib.crypto :as crypto])nn (def hashed-password (crypto/hash-password "my-secret-password"))n (crypto/verify-password "my-secret-password" hashed-password)n ;; => truen ```nn std.lib.stats:n Justification: For applications that need to perform data analysis or monitoring, a basic statistics library would be very helpful.n Recommended Functionality:n mean, median, mode: For calculating measures of central tendency.n variance, stdev: For calculating measures of dispersion.n percentiles, quartiles: For understanding the distribution of data.n correlation: For measuring the relationship between two variables.n Example Usage:n ```clojuren (require '[std.lib.stats :as stats])nn (def numbers [1 2 3 4 5])n (stats/mean numbers)n ;; => 3n (stats/stdev numbers)n ;; => 1.58...n ```nn std.lib.date:n Justification: std.lib.time is good for low-level time measurements, but a more feature-rich date and time library is needed for many applications.n Recommended Functionality:n Support for time zones.n Date and time arithmetic (e.g., adding/subtracting days, months, years).n Parsing and formatting dates and times in various formats (e.g., ISO 8601).n Functions for working with date ranges and intervals.n * Example Usage:n ```clojuren (require '[std.lib.date :as d])nn (def now (d/now))n (def tomorrow (d/plus now (d/days 1)))n (d/format tomorrow "yyyy-MM-dd")n ```

9    std.lib Summary

std.lib is the foundational utility library for the entire foundation-base ecosystem. It functions as a "prelude," aggregating and providing common functions used by all other modules. Its main purpose is to offer a consistent and extended set of core functionalities, tailored for the specific needs of the multi-language transpilation and runtime environment of the project.

Core Concepts:

  • Aggregation: std.lib uses a custom helper, f/intern-all (from std.lib.foundation), to pull functions from its required sub-modules and make them available directly under the std.lib namespace. This provides a single, convenient entry point for developers to access a wide range of utilities without needing to require numerous individual namespaces.nn Core Shadowing: std.lib explicitly excludes and shadows several core Clojure functions, such as ->, ->>, swap!, reset!, future, and memoize. It provides its own enhanced implementations for these, often with added features like placeholder support in threading macros (-> and ->>) or more advanced caching strategies in memoize.nn Sub-modules: The actual implementations of the functions are organized into a logical hierarchy of sub-modules. This modular design keeps the codebase clean and maintainable. The main sub-modules include:n std.lib.atom: For atomic operations.n std.lib.collection: For collection manipulations.n std.lib.component: For the component lifecycle model.n std.lib.deps: For dependency management.n std.lib.env: For environment interactions.n std.lib.foundation: For fundamental utilities.n std.lib.function: For function-related helpers.n std.lib.future: For asynchronous programming.n std.lib.io: For input/output operations.n std.lib.memoize: For memoization.n std.lib.security: For cryptographic functions.n std.lib.signal: For a signal/event system.n std.lib.stream: For data streaming and transducers.n std.lib.system: For managing system components.n std.lib.time: For time-related utilities.n std.lib.trace: For function tracing and debugging.n std.lib.transform: For data transformation.n std.lib.version: For version string parsing and comparison.n std.lib.walk: For traversing nested data structures.n std.lib.zip: For zipper-based navigation and manipulation of data structures.

Key Areas of Functionality (with Examples):

  • Atom Manipulation (std.lib.atom): Provides powerful functions for working with atoms, going beyond Clojure's core offerings.n swap-return!: Swaps the value of an atom and returns a vector of [old-value new-value].n ```clojuren (defonce my-atom (atom 0))n (swap-return! my-atom (fn [v] [v (inc v)]))n ;; => [0 1]n ```n atom:get, atom:set: Functions for getting and setting values within nested maps inside an atom.n ```clojuren (defonce nested-atom (atom {:a {:b 1}}))n (atom:get nested-atom [:a :b])n ;; => 1n (atom:set nested-atom [:a :c] 2)n @nested-atomn ;; => {:a {:b 1, :c 2}}n ```nn Collections (std.lib.collection): A rich set of functions for working with Clojure's collections.n map-keys, map-vals: For transforming map keys and values.n ```clojuren (map-keys #(keyword (clojure.string/upper-case (name %))) {:a 1 :b 2})n ;; => {:A 1, :B 2}n (map-vals inc {:a 1 :b 2})n ;; => {:a 2, :b 3}n ```n merge-nested: For deep merging of nested maps.n ```clojuren (merge-nested {:a {:b 1}} {:a {:c 2}})n ;; => {:a {:b 1, :c 2}}n ```n tree-flatten, tree-nestify: For converting between flat and nested map structures.n ```clojuren (tree-flatten {:a {:b {:c 1}}})n ;; => {:a/b/c 1}n (tree-nestify {:a/b/c 1})n ;; => {:a {:b {:c 1}}}n ```nn Concurrency (std.lib.future): A custom CompletableFuture-based future implementation.n future, then, catch: For creating and chaining asynchronous operations.n ```clojuren (-> (future (Thread/sleep 100) (+ 1 2))n (then [result] ( result 2))n (then [result] (println "Final result:" result)))n ;; Prints "Final result: 6" after a delay.n ```nn Dependency Management (std.lib.deps): A system for managing dependencies between components.n deps-ordered: For resolving and ordering dependencies in a dependency graph.n ```clojuren (deps-ordered (context {:a #{:b} :b #{:c} :c #{}}))n ;; => '(:c :b :a)n ```nn Environment (std.lib.env): Functions for interacting with the development and runtime environment.n prn, pp, pl: Enhanced printing functions that include namespace and line number information.n ```clojuren (pl {:a 1 :b 2})n ;; Prints the map with line numbers and file info.n ```n meter: For measuring the execution time of code blocks.n ```clojuren (meter "My expensive operation" (Thread/sleep 100))n ;; Prints the time taken for the operation.n ```nn System Components (std.lib.system): A hierarchical component model for building applications.n system: For defining a system of interconnected components.n ```clojuren (def topology {:db [MyDatabase] :web [WebServer :db]})n (def my-system (system topology {:db {:port 5432} :web {:port 8080}}))n (start my-system)n ```nn Zippers (std.lib.zip): A powerful zipper implementation for navigating and manipulating tree-like data structures.n vector-zip: For creating a zipper from a vector.n ```clojuren (-> (vector-zip [1 [2 3] 4])n (zip/step-inside)n (zip/step-right)n (zip/step-inside)n (zip/replace-right 99)n (zip/root-element))n ;; => [1 [2 99] 4]n ```

10    std.log: A Comprehensive Summary (including submodules)

The std.log module provides a flexible and extensible logging framework for Clojure applications, designed to handle various logging scenarios from simple console output to complex profiling and tracing. It offers a protocol-based approach, allowing for different logger implementations, and includes features like structured logging, context management, and advanced formatting for console output.

10.1    std.log (Main Namespace)

This namespace serves as the primary entry point for the logging system, aggregating and re-exporting key functionalities from its submodules. It provides high-level macros and functions for logging messages at different levels, managing logger instances, and controlling logging behavior.

Key Re-exported Functions:

  • From std.log.common: put-logger!, set-logger!, set-static!, set-level!, set-context!.n From std.log.console: console-logger.n From std.log.core: identity-logger, multi-logger, basic-logger, step.n From std.log.form: log-meta, log-runtime, log-context, log, verbose, debug, info, warn, error, fatal.n From std.log.profile: spy, show, trace, track, status, silent, action, meter, block, section, profile, note, task, todo.

Key Functions:

  • create: Creates a component-compatible logger.n logger: Creates and starts a logger.n logger?: Checks if an object is a logger.n with-indent (macro): Executes body with a given indent.n with-level (macro): Executes body with a given log level.n with-logger (macro): Executes code with a specified logger.n with-overwrite (macro): Executes code with a given overwrite context.n current-context: Returns the current logging context.n with-context (macro): Executes code with a given context.n with (macro): Enables targeted printing of statements.n with-logger-basic (macro): Executes code with the basic logger.n* with-logger-verbose (macro): Executes code with a verbose logger.

10.2    std.log.common (Common Logging Utilities)

This sub-namespace provides shared helper functions and dynamic variables for managing logging levels, contexts, and logger instances.

Core Concepts:

  • Dynamic Variables: *level*, *overwrite*, *context*, *trace*, *static*, *logger*, *logger-basic*, *logger-verbose*.n* Log Levels: +levels+ maps keywords (e.g., :debug, :info) to numeric priorities.

Key Functions:

  • set-static!, set-level!, set-context!, set-logger!, put-logger!: Functions for setting and updating global logging parameters.n default-logger: Returns the default logger instance.n basic-logger: Returns a basic logger instance.n* verbose-logger: Returns a verbose logger instance.

10.3    std.log.console (Console Logger)

This sub-namespace implements a console logger that formats and prints log entries to the console, with extensive styling and customization options.

Core Concepts:

  • +style+: A map defining default styling for different parts of a log entry (header, body, meter, status).n +levels+: Defines color schemes for different log levels.n ConsoleLogger Record: The concrete implementation of a console logger.

Key Functions:

  • style-default: Retrieves default styling.n join-with: Joins strings with a separator.n console-pprint: Pretty-prints data for console output.n console-format-line: Formats a single line for console output.n console-display?: Checks if an item should be displayed.n console-render: Renders a log entry based on its style.n console-header-label, console-header-position, console-header-date, console-header-message, console-header: Functions for rendering the log header.n console-meter-trace, console-meter-form, console-meter: Functions for rendering meter-related information.n console-status-outcome, console-status-duration, console-status-start, console-status-end, console-status-props, console-status: Functions for rendering status information.n console-body-console-text, console-body-console: Functions for rendering console text in the body.n console-body-data-context, console-body-data: Functions for rendering data in the body.n console-body-exception, console-body: Functions for rendering exceptions in the body.n console-format: Formats the entire log entry for console output.n logger-process-console: Processes log entries for console output.n console-write: Writes a log entry to the console.n* console-logger: Creates a console logger instance.

10.4    std.log.core (Core Logger Implementations)

This sub-namespace provides core logger implementations, including an identity logger (which simply returns the log entry), a multi-logger (which dispatches to multiple loggers), and a basic logger (which prints to *out*). It also defines helper functions for processing log entries and exceptions.

Core Concepts:

  • ILogger Protocol: Defines the -logger-write method for writing log entries.n IdentityLogger Record: A logger that returns the log entry unchanged.n MultiLogger Record: A logger that dispatches log entries to multiple child loggers.n* BasicLogger Record: A logger that prints log entries to *out*.

Key Functions:

  • logger-submit: Submits a log entry to a logger's queue.n logger-process: Processes a log entry, applying any fn/process transformations.n logger-enqueue: Enqueues a log entry for processing.n process-exception: Converts a Throwable into a map for logging.n logger-message: Constructs a standardized log message map.n logger-start, logger-info, logger-stop: Lifecycle and info functions for loggers.n logger-init: Initializes logger settings.n identity-logger: Creates an identity logger.n multi-logger: Creates a multi-logger.n log-raw: Sends raw data to the logger.n basic-write: Writes a log entry to *out*.n basic-logger: Creates a basic logger.n step (macro): Logs a step in a process.

10.5    std.log.element (Log Element Formatting)

This sub-namespace provides helper functions for formatting individual elements of a log entry, such as ANSI styling, headings, and time/duration displays.

Key Functions:

  • style-ansi: Constructs ANSI style codes from a style map.n style-heading: Formats a heading with styling.n elem-daily-instant: Formats a label and instant (date/time).n elem-ns-duration: Formats a label and nanosecond duration.n elem-position: Formats a code position (namespace, function, line, column).

10.6    std.log.form (Log Form Macros)

This sub-namespace provides macros for generating log entries from Clojure forms, capturing metadata like line numbers and function names. It also defines macros for different log levels.

Key Functions:

  • log-meta: Captures metadata from a form.n log-function-name: Extracts a function name from a mangled string.n log-runtime-raw, log-runtime: Captures runtime information (function, method, filename).n log-check: Checks if a log entry should be processed based on its level.n to-context: Converts various inputs to a log context map.n log-fn: The core function for logging an entry.n log-form: Generates a log entry from a form.n with-context (macro): Applies a context to the current one.n log-context: Creates a log context form.n log (macro): The main macro for logging messages.n log-data-form, deflog-data (macro): Macros for logging data at different levels (verbose, debug, info, warn).n* log-error-form, deflog-error (macro): Macros for logging errors (error, fatal).

10.7    std.log.match (Log Entry Matching)

This sub-namespace provides functions for filtering log entries based on various criteria, such as log level, namespace, function name, and custom filters.

Key Functions:

  • filter-base: Matches a value against a filter (regex, string, function).n filter-include: Checks if a value matches any of the include filters.n filter-exclude: Checks if a value does not match any of the exclude filters.n filter-value: Filters a value based on include, exclude, and ignore criteria.n match-filter: Matches an entry against a filter map.n* match: The main function for matching a log entry against logger settings.

10.8    std.log.profile (Profiling and Tracing)

This sub-namespace provides macros for profiling code execution, tracing function calls, and displaying various metrics. It integrates with the logging system to output structured performance data.

Core Concepts:

  • Spy: Logs the start and end of a function's execution, including its duration.n Trace: Tracks function calls within a nested execution flow.n Meter: Measures the execution time of a block of code.n* Status: Logs the outcome of an operation.

Key Functions:

  • spy-fn: Constructs a spy function.n bind-trace: Binds a trace ID to the log context.n spy-form: Helper for the spy macro.n defspy (macro): Creates a spy macro.n on-grey, on-white, on-color: Functions for generating console styles.n item-style: Styles a log entry.n note, spy, track, status, show, todo, action (macros): Specific profiling and tracing macros.n meter-fn: Constructs a meter function.n meter-form: Helper for the meter macro.n defmeter (macro): Creates a meter macro.n silent, trace, profile, meter, block, section, task (macros): Specific profiling and tracing macros.

10.9    std.log.template (Log Message Templating)

This sub-namespace provides a simple templating system for log messages, allowing messages to be rendered using Mustache-like syntax.

Key Functions:

  • add-template, remove-template, has-template?, list-templates: Manages message templates.n* render-message: Renders a log message using a template.

10.10    Usage Pattern:

The std.log module is essential for:

  • Debugging: Providing detailed information about program execution.n Monitoring: Tracking application behavior and performance.n Auditing: Recording important events and actions.n Profiling: Identifying performance bottlenecks.n Structured Logging: Outputting log data in a machine-readable format.

By offering a comprehensive and customizable logging solution, std.log empowers developers to gain deeper insights into their applications and build more robust and maintainable software.

11    std.make: A Comprehensive Summary (including submodules)

The std.make module provides a comprehensive framework for automating build processes, managing project configurations, and interacting with version control systems (specifically Git and GitHub). It aims to simplify the creation and maintenance of Makefiles, manage project dependencies, and streamline common development workflows like building, testing, and releasing software. The module is designed to be extensible, allowing for custom build steps and integration with various tools.

11.1    std.make (Main Namespace)

This namespace serves as the primary entry point for the build automation system, aggregating and re-exporting key functionalities from its submodules. It provides high-level functions and macros for common build tasks.

Key Re-exported Functions:

  • From std.make.compile: with:mock-compile, types:add, types:list, types:remove, build.n From std.make.common: with:internal-shell, triggers-clear, triggers-get, triggers-list, triggers-purge, triggers-set, get-triggered, make-config, dir, dir:exists?, dir:teardown, run:shell, run, run-close, run-internal, run:init, run:package, run:dev, run:test, run:release, run:start, run:stop.n From std.make.github: dir:repo-rebuild, dir:repo-setup, gh:token, gh:user, gh:exists?, gh:commit, gh:push, gh:save, gh:clone, gh:setup, gh:setup-init, gh:setup-remote, gh:local-purge, gh:dwim-init, gh:dwim-push, with-verbose.n From std.make.project: def.make, build-all, build-at, build-default, build-triggered, is-changed?.n From std.make.readme: org:tangle, org:readme.n* From std.make.bulk: bulk-container-build, bulk-container-filter, bulk-build, bulk, bulk-gh-init, bulk-gh-push.

11.2    std.make.bulk (Bulk Operations)

This sub-namespace provides functions for performing bulk operations across multiple projects or configurations, such as building multiple containers or pushing changes to multiple GitHub repositories.

Key Functions:

  • make-bulk-get-keys: Determines the order of projects to build based on dependencies and changes.n make-bulk-build: Builds multiple projects in bulk.n make-bulk: Orchestrates a bulk build process, including logging and timing.n make-bulk-container-filter: Filters configurations based on container names.n make-bulk-container-build: Builds multiple containers in bulk.n make-bulk-gh-init: Initializes multiple GitHub repositories in bulk.n make-bulk-gh-push: Pushes changes to multiple GitHub repositories in bulk.

11.3    std.make.common (Common Makefile Utilities)

This sub-namespace provides shared helper functions and dynamic variables for managing Makefile configurations, running shell commands, and handling triggers.

Core Concepts:

  • *triggers*: An atom storing a map of configurations to their associated triggers.n *tmux*: A dynamic var to control whether tmux is used for running commands.n *internal-shell*: A dynamic var to control whether commands are run in an internal shell.n* MakeConfig Record: Represents a Makefile configuration.

Key Functions:

  • with:triggers (macro): Binds the *triggers* atom.n triggers-purge, triggers-set, triggers-clear, triggers-get, triggers-list: Functions for managing triggers.n get-triggered: Retrieves configurations based on a trigger namespace.n with:internal-shell (macro): Binds *internal-shell*.n make-config-string: Returns a string representation of a MakeConfig.n make-config?: Checks if an object is a MakeConfig.n get-config-tag: Retrieves the tag of a MakeConfig.n make-config-defaults: Returns default MakeConfig settings.n make-config-map: Creates a MakeConfig map.n make-config: Creates a MakeConfig instance.n make-config-update: Updates a MakeConfig.n make-dir: Returns the build directory for a MakeConfig.n make-run: Runs a make command.n make-run-close: Closes a tmux window.n make-run-internal: Runs make commands internally.n make-shell: Opens a terminal in the build directory.n make-run-init, make-run-package, make-run-release, make-run-dev, make-run-test, make-run-start, make-run-stop: Specific make commands.n make-dir-setup: Sets up the build directory.n make-dir-exists?: Checks if the build directory exists.n* make-dir-teardown: Deletes the build directory.

11.4    std.make.compile (Compilation Utilities)

This sub-namespace provides utilities for compiling various types of files and resources, including custom formats, directories, and language-specific modules.

Core Concepts:

  • *mock-compile*: A dynamic var to enable mock compilation for testing.n* Compilation Types: Supports :resource, :directory, :custom, :script, :module.graph, :module.single, :module.schema.

Key Functions:

  • with:mock-compile (macro): Enables mock compilation.n compile-fullbody: Combines header, body, and footer into a full body.n compile-out-path: Generates the output path for a compiled file.n compile-write: Writes compiled content to a file.n compile-summarise: Summarizes compilation results.n compile-resource: Copies resources to the build directory.n compile-directory: Copies a directory to the build directory.n compile-custom: Compiles custom content.n types-list, types-add, types-remove: Manages compilation types.n compile-ext-fn (multimethod): Extensible function for compiling different file extensions (e.g., :blank, :raw, :edn, :json, :yaml, :toml, :html, :css, :sql, :redis, :vega, :gnuplot, :graphviz, :gitignore, :nginx.conf, :dockerfile, :readme.md, :makefile, :package.json).n compile-resolve: Resolves a symbol or pointer.n compile-ext: Compiles files of different extensions.n compile-single: Compiles a single file.n compile-section: Compiles a section of a Makefile.n compile-directive: Compiles a directive within a Makefile.n* compile: The main function for compiling files based on a MakeConfig.

11.5    std.make.github (GitHub Integration)

This sub-namespace provides functions for interacting with GitHub repositories, including committing, pushing, cloning, and setting up remote repositories.

Core Concepts:

  • *verbose*: A dynamic var to control verbose output for Git commands.

Key Functions:

  • with-verbose (macro): Controls verbose output.n gh-sh-opts: Creates standard shell options for Git commands.n gh-commit: Creates a Git commit.n gh-push: Pushes changes to GitHub.n gh-save: Commits and pushes changes.n gh-user, gh-token: Retrieves GitHub user and token from environment variables.n gh-exists?: Checks if a GitHub repository exists.n gh-setup-remote: Creates a remote GitHub repository.n gh-setup-local-init: Initializes a local Git repository and links it to a remote.n gh-setup-local-clone: Clones a GitHub repository.n gh-clone: Forces a Git clone.n gh-setup: Sets up a GitHub repository (clones or initializes).n gh-local-purge: Purges all checked-in files from a Git repository.n gh-refresh: Regenerates a Git repository.n gh-dwim-init: Initializes a project and pushes it to GitHub.n* gh-dwim-push: Pushes changes to GitHub.

11.6    std.make.makefile (Makefile Generation)

This sub-namespace provides functions for generating Makefile content from Clojure data structures.

Key Functions:

  • emit-headers: Emits Makefile headers (variables).n emit-target: Emits a Makefile target with its dependencies and commands.n write: Writes a Makefile from a Clojure data structure.

11.7    std.make.project (Project Management)

This sub-namespace provides functions for managing project configurations, building projects, and tracking changes.

Core Concepts:

  • def.make Macro: Defines a Makefile configuration.

Key Functions:

  • makefile-parse: Parses a Makefile for its sections.n build-default: Builds the default section of a Makefile.n changed-files: Retrieves a list of changed files from a build result.n is-changed?: Checks if a project has changed.n build-all: Builds all sections of a Makefile.n build-at: Builds a specific section of a Makefile.n def-make-fn: Implementation for def.make.n* build-triggered: Builds projects based on triggered namespaces.

11.8    std.make.readme (README Generation)

This sub-namespace provides functions for generating README.md files from Org-mode files, including tangling code blocks.

Key Functions:

  • has-orgfile?: Checks if an Org-mode file exists.n tangle-params: Extracts tangle parameters from an Org-mode file.n tangle-parse: Parses an Org-mode file for tangle blocks.n tangle: Extracts code blocks from an Org-mode file and writes them to separate files.n make-readme-raw: Filters out build-related sections from a README.n* make-readme: Generates a README.md file from an Org-mode file.

11.9    Usage Pattern:

The std.make module is essential for automating various aspects of software development within the foundation-base project. It provides:

  • Unified Build System: A consistent way to define and execute build steps across different projects and languages.n Project Scaffolding: Tools for setting up new projects with predefined structures and configurations.n Version Control Integration: Streamlined workflows for committing, pushing, and managing GitHub repositories.n Documentation Generation: Automated creation of README.md files from Org-mode sources.n Extensibility: A modular design that allows for custom build steps and integrations.

By offering a comprehensive set of build automation and project management tools, std.make simplifies the development lifecycle and promotes consistency across the foundation-base ecosystem.

12    std.math: A Comprehensive Summary (including submodules)

The std.math module provides a collection of mathematical functions and utilities for Clojure, covering basic arithmetic, statistical calculations, random number generation, and Markov chain analysis. It aims to offer a convenient and comprehensive set of tools for numerical and probabilistic computations.

12.1    std.math (Main Namespace)

This namespace serves as the primary entry point for mathematical operations, aggregating and re-exporting key functionalities from its submodules.

Key Re-exported Functions:

  • From std.math.common: abs, ceil, factorial, floor, combinatorial, log, loge, log10, mean, median, mode, variance, stdev, skew, kurtosis, histogram.n From std.math.aggregate: aggregates.n From std.math.random: rand-seed!, rand, rand-int, rand-nth, rand-digits, rand-sample.

12.2    std.math.aggregate (Aggregation Functions)

This sub-namespace provides functions for calculating various aggregate statistics on collections of numbers.

Key Functions:

  • max-fn: Returns the maximum value in a collection.n min-fn: Returns the minimum value in a collection.n range-fn: Returns the range (max - min) of a collection.n middle-fn: Returns the middle element of a sorted collection.n wrap-not-nil: A helper to wrap functions that should ignore nil values.n +aggregations+: A map of common aggregation functions (first, last, middle, mean, sum, max, min, range, stdev, mode, median, skew, variance, random).n aggregates: Calculates a set of aggregate statistics for a collection.

12.3    std.math.common (Common Mathematical Functions)

This sub-namespace provides a collection of fundamental mathematical and statistical functions.

Key Functions:

  • abs: Absolute value.n square: Squares a number.n sqrt: Square root.n ceil: Ceiling of a number.n floor: Floor of a number.n factorial: Factorial of a number.n combinatorial: Binomial coefficient (n choose i).n log: Logarithm to an arbitrary base.n loge: Natural logarithm.n log10: Base-10 logarithm.n mean: Arithmetic mean.n mode: Mode (most frequent value).n median: Median (middle value).n percentile: Calculates a percentile.n quantile: Splits data into quantiles.n variance: Sample variance.n stdev: Standard deviation.n skew: Skewness.n kurtosis: Kurtosis.n* histogram: Creates a histogram.

12.4    std.math.markov (Markov Chain Analysis)

This sub-namespace provides functions for working with Markov chains, including calculating cumulative probabilities and generating sequences based on a probability matrix.

Key Functions:

  • cumulative: Reassembles probabilities in cumulative order.n select: Selects an item randomly based on probabilities.n generate: Generates an infinite stream of tokens from a probability matrix.n tally: Helper for collate.n collate: Generates a probability map from a sequence of tokens.

12.5    std.math.random (Random Number Generation)

This sub-namespace provides functions for generating various types of random numbers and samples, leveraging org.apache.commons.math3.random.MersenneTwister.

Key Functions:

  • rand-gen: Creates a random number generator.n rand-seed!: Sets the seed of a random number generator.n rand: Generates a random double between 0 and 1.n rand-int: Generates a random integer less than n.n rand-nth: Returns a random element from a collection.n rand-normal: Generates a random number from a normal distribution.n rand-digits: Generates a random n-digit string.n* rand-sample: Samples from a collection with specified proportions.

12.6    Usage Pattern:

The std.math module is useful for:

  • Statistical Analysis: Performing common statistical calculations on data.n Data Generation: Generating random numbers and sequences.n Modeling: Implementing probabilistic models like Markov chains.n* Numerical Computations: Basic mathematical operations.

By providing a diverse set of mathematical tools, std.math supports various analytical and computational tasks within Clojure applications.

13    std.object: A Comprehensive Summary (including submodules)

The std.object module provides a powerful and extensible framework for introspecting, manipulating, and extending Java objects in Clojure. It offers a unified API for querying class metadata, accessing fields and methods, and defining custom behaviors for various object types. This module is crucial for bridging the gap between Clojure's dynamic nature and Java's static type system, enabling seamless interoperability and advanced metaprogramming capabilities.

13.1    std.object (Main Namespace)

This namespace serves as the primary entry point for object manipulation, aggregating and re-exporting key functionalities from its submodules. It provides high-level functions for common object-oriented tasks.

Key Re-exported Functions:

  • From std.object.element.class: class-convert.n From std.object.element.common: element?, element, context-class.n From std.object.element: to-element, class-info, class-hierarchy, constructor?, method?, field?, static?, instance?, public?, private?, plain?.n From std.object.query: query-class, query-instance, query-hierarchy, delegate.n From std.object.framework.access: get, get-in, set, keys, meta-clear.n From std.object.framework.read: meta-read, meta-read-exact, meta-read-exact?, to-data, to-map, read-ex, read-getters-form, read-getters, read-all-getters, read-fields.n From std.object.framework.struct: struct-fields, struct-getters, struct-accessor.n From std.object.framework.write: meta-write, meta-write-exact, meta-write-exact?, from-data, write-ex, write-setters-form, write-setters, write-all-setters, write-fields.n From std.object.framework: vector-like, map-like, string-like, unextend.

13.2    std.object.element (Object Element Abstraction)

This sub-namespace provides an abstraction layer for representing Java reflection objects (methods, fields, constructors) as Clojure data structures (Element records). This allows for a unified way to query and manipulate these elements.

Core Concepts:

  • Element Record: A data structure representing a Java reflection object, containing its name, tag (method, field, constructor), modifiers, type, container class, and delegate (the raw Java reflection object).

Key Functions:

  • to-element: Converts a java.lang.reflect object to an Element.n element-params: Returns the parameter types of an Element.n class-info: Retrieves information about a class.n class-hierarchy: Retrieves the class and interface hierarchy.n constructor?, method?, field?: Predicates for element types.n* static?, instance?, public?, private?, protected?, plain?: Predicates for element modifiers.

13.3    std.object.element.class (Class Conversion Utilities)

This sub-namespace provides utilities for converting between different representations of Java classes and types (e.g., Class objects, symbols, strings, raw type signatures).

Key Functions:

  • type->raw: Converts a Class or symbol to its raw type signature string.n raw-array->string: Converts a raw array type signature to a human-readable string.n raw->string: Converts a raw type signature to a human-readable string.n string-array->raw: Converts a human-readable array type string to a raw type signature.n string->raw: Converts any string to its raw type signature.n* class-convert (multimethod): Converts a class or type representation to another (e.g., :class, :container, :symbol, :raw, :string).

13.4    std.object.element.common (Common Element Utilities)

This sub-namespace provides common helper functions for working with Element records, such as determining the context class and checking assignability.

Key Functions:

  • context-class: Returns the Class object for a given object or class.n assignable?: Checks if a sequence of classes is assignable to another sequence.n -invoke-element (multimethod): Base method for extending invoke for Element types.n -to-element (multimethod): Base method for extending to-element from Java reflection objects.n -element-params (multimethod): Base method for extending parameter retrieval for Element types.n -format-element (multimethod): Base method for extending toString for Element types.n element: Creates an Element record.n* element?: Checks if an object is an Element.

13.5    std.object.element.impl.constructor (Constructor Element Implementation)

This sub-namespace provides the implementation details for Element records representing Java constructors.

Key Functions:

  • Extends common/-invoke-element and common/-to-element for java.lang.reflect.Constructor.

13.6    std.object.element.impl.field (Field Element Implementation)

This sub-namespace provides the implementation details for Element records representing Java fields.

Key Functions:

  • patch-field: Makes a Field accessible.n arg-params: Returns argument parameters for field getters/setters.n throw-arg-exception: Throws an argument exception.n invoke-static-field: Invokes a static field.n invoke-instance-field: Invokes an instance field.n* Extends common/-invoke-element and common/-to-element for java.lang.reflect.Field.

13.7    std.object.element.impl.hierarchy (Class Hierarchy Utilities)

This sub-namespace provides utilities for traversing and analyzing class hierarchies, particularly for finding method origins.

Key Functions:

  • has-method: Checks if a method exists in a class.n methods-with-same-name-and-count: Finds methods with the same name and parameter count.n has-overridden-method: Checks if a method is overridden.n* origins: Lists all classes that contain a particular method.

13.8    std.object.element.impl.method (Method Element Implementation)

This sub-namespace provides the implementation details for Element records representing Java methods.

Key Functions:

  • invoke-static-method: Invokes a static method.n invoke-instance-method: Invokes an instance method.n Extends common/-invoke-element and common/-to-element for java.lang.reflect.Method.

13.9    std.object.element.impl.multi (Multi-Element Handling)

This sub-namespace handles the combination of multiple Element records (e.g., overloaded methods) into a single multi-element.

Key Functions:

  • get-name: Retrieves the common name of multiple elements.n to-element-array: Converts a nested map of elements to a flat sequence.n multi-element: Combines multiple elements into one.n to-element-map-path: Creates a map path for an element.n elegible-candidates: Finds eligible candidates based on argument list.n find-method-candidate: Finds the best method candidate.n find-field-candidate: Finds the best field candidate.n find-candidate: Finds the best element candidate (method or field).n Extends common/-invoke-element for multi-elements.

13.10    std.object.element.impl.type (Element Type Utilities)

This sub-namespace provides low-level utilities for working with Java reflection types, including setting accessible flags and extracting modifiers.

Key Functions:

  • set-accessible: Sets the accessible flag for a reflection object.n add-annotations: Adds annotations to an element.n seed: Returns preliminary attributes for creating an element.

13.11    std.object.element.modifier (Modifier Utilities)

This sub-namespace provides utilities for converting between integer representations of Java modifiers and human-readable sets of keywords.

Key Functions:

  • flags, field-flags, method-flags: Maps of modifier flags.n int-to-modifiers: Converts an integer to a set of modifier keywords.n modifiers-to-int: Converts a set of modifier keywords to an integer.

13.12    std.object.element.util (Element Utility Functions)

This sub-namespace provides general utility functions for working with Element records, such as boxing arguments and matching parameter types.

Key Functions:

  • box-arg: Converts a value to a primitive type if necessary.n set-field: Sets the value of a field.n param-arg-match: Checks if an argument type matches a parameter type.n param-float-match: Matches float parameters to integer arguments.n is-congruent: Checks if argument types are congruent with parameter types.n throw-arg-exception: Throws an argument exception.n box-args: Boxes arguments to match parameter types.n format-element-method: Formats a method element.n element-params-method: Returns method parameters.

13.13    std.object.framework (Object Framework)

This sub-namespace provides a framework for extending Clojure's object model to seamlessly interact with Java objects, allowing them to behave like Clojure maps, vectors, or strings.

Key Functions:

  • string-like (macro): Extends a class to behave like a string.n map-like (macro): Extends a class to behave like a map.n vector-like (macro): Extends a class to behave like a vector.n unextend: Removes framework extensions for a class.n invoke-intern-object: Creates an invoke form for an object.

13.14    std.object.framework.access (Object Accessors)

This sub-namespace provides functions for accessing and modifying object properties using keywords or paths, abstracting away direct Java reflection.

Key Functions:

  • meta-clear: Clears all meta-read and meta-write definitions for a class.n get-with-keyword, get-with-array: Retrieves properties using keywords or arrays.n get: Retrieves a property.n get-in: Retrieves a nested property.n keys: Retrieves all accessible property keys.n set-with-keyword: Sets a property using a keyword.n set: Sets properties using a map or key-value pair.

13.15    std.object.framework.map-like (Map-Like Extension)

This sub-namespace provides the implementation for extending Java classes to behave like Clojure maps, allowing for property access and manipulation using map-like syntax.

Key Functions:

  • key-selection: Selects map entries based on include/exclude keys.n read-proxy-functions: Creates proxy functions for reading properties.n write-proxy-functions: Creates proxy functions for writing properties.n extend-map-read: Extends a class with map-like read capabilities.n extend-map-write: Extends a class with map-like write capabilities.n* extend-map-like (macro): Extends a class to behave like a map.

13.16    std.object.framework.print (Print Extension)

This sub-namespace provides utilities for extending the print-method for Java classes, allowing for custom string representations.

Key Functions:

  • assoc-print-vars: Associates print-related variables.n format-value: Formats an object into a readable string.n extend-print (macro): Extends the print-method for a class.

13.17    std.object.framework.read (Object Reading)

This sub-namespace provides functions for reading object properties, including metadata, fields, and getter methods, and converting objects to Clojure data structures.

Key Functions:

  • meta-read, meta-read-exact, meta-read-exact?: Accesses and checks read metadata.n read-fields, read-all-fields: Reads fields from an object.n +read-template+: Template for getter functions.n +read-has-opts+, +read-is-opts+, +read-get-opts+: Options for getter methods.n create-read-method-form: Creates a method form for reading.n read-getters-form, read-getters, read-all-getters: Reads getter methods.n read-ex: Creates a getter method that throws an exception.n to-data: Converts an object to Clojure data.n to-map: Converts an object to a map.

13.18    std.object.framework.string-like (String-Like Extension)

This sub-namespace provides the implementation for extending Java classes to behave like Clojure strings, allowing for conversion to and from string representations.

Key Functions:

  • extend-string-like (macro): Extends a class to behave like a string.

13.19    std.object.framework.struct (Struct-Like Access)

This sub-namespace provides functions for accessing object properties in a struct-like manner, using nested maps or vectors to define the access path.

Key Functions:

  • getter-function: Creates a getter function for a keyword.n field-function: Creates a field access function.n struct-getters: Retrieves properties using a getter specification.n struct-field-functions: Constructs field access functions.n struct-fields: Retrieves properties using a field specification.n struct-accessor: Creates an accessor function.n dir: Explores object fields.

13.20    std.object.framework.vector-like (Vector-Like Extension)

This sub-namespace provides the implementation for extending Java classes to behave like Clojure vectors, allowing for sequential access to their elements.

Key Functions:

  • extend-vector-like (macro): Extends a class to behave like a vector.

13.21    std.object.framework.write (Object Writing)

This sub-namespace provides functions for writing object properties, including metadata, fields, and setter methods, and converting Clojure data structures to Java objects.

Key Functions:

  • meta-write, meta-write-exact, meta-write-exact?: Accesses and checks write metadata.n write-fields, write-all-fields: Writes fields to an object.n create-write-method-form: Creates a method form for writing.n write-setters-form, write-setters, write-all-setters: Writes setter methods.n write-ex: Creates a setter method that throws an exception.n write-constructor: Returns a constructor element.n write-setter-element: Constructs array elements for setters.n write-setter-value: Sets a property given a keyword and value.n from-empty: Creates an object from an empty constructor.n from-constructor: Creates an object from a constructor.n from-map: Creates an object from a map.n* from-data: Creates an object from Clojure data.

13.22    std.object.query (Object Querying)

This sub-namespace provides functions for querying Java classes and objects using reflection, allowing for flexible selection and filtering of members (methods, fields, constructors).

Key Functions:

  • all-class-members: Returns all raw reflected members of a class.n all-class-elements: Returns all Element records for a class.n select-class-elements: Selects Element records from a class.n query-class: Queries the Java view of a class.n select-supers-elements: Selects elements from superclasses.n query-supers: Queries superclasses.n query-hierarchy: Queries the entire class hierarchy.n all-instance-elements: Returns all instance elements.n select-instance-elements: Selects instance elements.n query-instance: Queries an object instance.n query-instance-hierarchy: Queries an object instance hierarchy.n apply-element: Applies a class element to arguments.n delegate: Creates a delegate for transparent field access.n* invoke-intern-element: Creates an invoke form for an element.

13.23    std.object.query.filter (Query Filtering)

This sub-namespace provides functions for filtering Element records based on various criteria, such as name, modifiers, parameter types, and origins.

Key Functions:

  • has-predicate?, has-name?, has-modifier?, has-params?, has-num-params?, has-any-params?, has-all-params?, has-type?, has-origins?: Predicates for filtering.n filter-by: Filters elements by a given criterion.n filter-terms-fn: Filters elements based on a group of terms.

13.24    std.object.query.input (Query Input Processing)

This sub-namespace provides utilities for classifying and converting input arguments for object queries.

Key Functions:

  • args-classify: Classifies input arguments.n args-convert: Converts arguments to primitive classes.n args-group: Groups input arguments into categories.

13.25    std.object.query.order (Query Ordering)

This sub-namespace provides functions for sorting and ordering Element records based on various criteria.

Key Functions:

  • sort-fn: Creates a sorting function.n sort-terms-fn: Sorts elements by terms.n first-terms-fn: Returns the first element.n merge-terms-fn: Merges elements.n select-terms-fn: Selects terms to output.n* order: Orders elements based on a group of terms.

13.26    Usage Pattern:

The std.object module is essential for:

  • Java Interoperability: Seamlessly interacting with Java objects and classes from Clojure.n Metaprogramming: Dynamically inspecting and manipulating Java objects at runtime.n Framework Development: Building extensible frameworks that can adapt to different Java object models.n Data Conversion: Converting between Java objects and Clojure data structures.n Reflection-Based Tools: Creating tools that analyze and interact with Java code.

By providing a powerful and flexible object introspection and manipulation framework, std.object empowers developers to leverage the full power of the Java ecosystem within their Clojure applications.

14    std.pretty: A Comprehensive Summary (including submodules)

The std.pretty module provides a powerful and extensible pretty-printing framework for Clojure, designed to render complex data structures in a human-readable and customizable format. It supports features like intelligent line wrapping, syntax highlighting with ANSI colors, and custom handlers for various data types. This module is crucial for debugging, logging, and generating formatted output in Clojure applications.

14.1    std.pretty (Main Namespace)

This namespace serves as the primary entry point for pretty-printing, aggregating and re-exporting key functionalities from its submodules. It defines the core pretty-printing options and provides high-level functions for rendering data.

Core Concepts:

  • +defaults+: A map defining default pretty-printing options, including width, key sorting, collection delimiters, color settings, and fallback behaviors.n CanonicalPrinter: A printer implementation that produces a canonical, uncolored representation of data.n PrettyPrinter: A printer implementation that applies all pretty-printing options, including coloring and custom handlers.

Key Functions:

  • format-unknown: Formats unknown data types.n format-doc-edn: Formats EDN-like data.n format-doc: The main function for formatting data into a document.n pr-handler: A print handler for printing strings.n unknown-handler: A handler for unknown objects.n tagged-handler: A handler for tagged literals.n java-handlers, clojure-handlers, clojure-interface-handlers, common-handlers: Collections of predefined print handlers for Java and Clojure types.n canonical-printer: Creates a canonical printer.n pretty-printer: Creates a pretty printer.n render-out: Renders a document to an output stream.n pprint: Pretty-prints a value to *out*.n pprint-str: Returns the pretty-printed string.n pprint-cc: Pretty-prints using the std.concurrent.print framework.

14.2    std.pretty.color (Coloring Utilities)

This sub-namespace provides utilities for applying color and other markup to text, supporting ANSI escape codes, inline HTML styles, and HTML classes.

Key Functions:

  • -document (multimethod): Constructs a pretty-print document with optional coloring.n* -text (multimethod): Produces colored text.

14.3    std.pretty.compare (Comparison Utilities)

This sub-namespace provides a custom comparison function for various Clojure data types, used for sorting keys in maps and sets during pretty-printing.

Key Functions:

  • type-priority: Assigns a priority to different data types for comparison.n compare-seqs: Compares two sequences.n compare: Compares any two values, handling different types and collections.

14.4    std.pretty.deque (Deque Implementation)

This sub-namespace provides a simple deque (double-ended queue) implementation using clojure.core.rrb-vector, used internally by the pretty-printing engine.

Key Functions:

  • pop-left, peek-left: Removes or peeks at the leftmost element.n conj-right, conj-left, conj-both: Adds elements to either end.n update-left, update-right: Updates elements at either end.

14.5    std.pretty.dispatch (Dispatch Mechanisms)

This sub-namespace provides mechanisms for dispatching print handlers based on class inheritance, allowing for flexible and extensible type-based printing.

Key Functions:

  • chained-lookup: Chains multiple lookup functions together.n* inheritance-lookup: Creates a lookup function that considers class inheritance.

14.6    std.pretty.edn (EDN Printing)

This sub-namespace provides the core logic for visiting and formatting EDN (Extensible Data Notation) data structures, including primitive types, collections, and tagged literals.

Key Functions:

  • override?: Checks if an object implements protocol.pretty/IOverride.n edn: Converts an object to an EDN representation.n class->edn: Converts a Class object to its EDN representation.n tagged-object: Converts an object to a tagged literal.n format-date: Formats a date object.n* visit-seq, visit-tagged, visit-unknown, visit-meta, visit-edn, visit: Functions for visiting and formatting different EDN data types.

14.7    std.pretty.engine (Pretty-Printing Engine)

This sub-namespace implements the core pretty-printing algorithm, which converts a document (a hierarchical data structure representing the formatted output) into a flat sequence of operations, and then renders these operations to a string.

Key Functions:

  • serialize: Converts a document into a sequence of operations.n serialize-node-text, serialize-node-pass, serialize-node-escaped, serialize-node-span, serialize-node-line, serialize-node-break, serialize-node-group, serialize-node-nest, serialize-node-align: Functions for serializing different types of document nodes.n annotate-right: Annotates nodes with their rightmost position.n annotate-begin: Recalculates the rightmost position of begin nodes.n format-nodes: Formats nodes given a line width.n* pprint-document: Pretty-prints a document to an output stream.

14.8    std.pretty.protocol (Pretty-Printing Protocols)

This sub-namespace defines the core protocols and multimethods that enable extensible pretty-printing, allowing custom handlers for various data types and output formats.

Key Protocols:

  • IEdn: Defines the -edn method for converting an object to an EDN representation.n IOverride: A marker protocol for types that override default printing behavior.n IVisitor: Defines methods for visiting and formatting different EDN data types.

Key Multimethods:

  • -serialize-node: Serializes a document node.n -document: Constructs a pretty-print document.n -text: Produces colored text.

14.9    Usage Pattern:

The std.pretty module is essential for:

  • Debugging: Making complex data structures easier to understand in logs and console output.n User Interfaces: Generating formatted text for display in terminal-based or HTML-based applications.n Code Generation: Producing human-readable code output.n* Documentation: Formatting code examples and data structures.

By providing a flexible and powerful pretty-printing solution, std.pretty enhances the developer experience and improves the readability of Clojure applications.

15    std.print: A Comprehensive Summary (including submodules)

The std.print module provides a comprehensive set of utilities for formatted output in Clojure, focusing on enhancing readability and presentation in various contexts, including console, reports, and animated displays. It builds upon ANSI escape codes for terminal styling and offers flexible formatting options for different data types and structures.

15.1    std.print (Main Namespace)

This namespace serves as the primary entry point for formatted printing, aggregating and re-exporting key functionalities from its submodules. It provides high-level functions for printing various types of reports and styled output.

Key Re-exported Functions:

  • From std.concurrent.print: print, println, with-out-str, prn.n* From std.print.base.report: print-header, print-row, print-title, print-subtitle, print-column, print-summary, print-tree-graph.

15.2    std.print.ansi (ANSI Styling)

This sub-namespace provides functions for generating ANSI escape codes to style text in terminal environments, including colors, highlights, and text attributes.

Core Concepts:

  • +colors+, +highlights+, +attributes+: Maps defining ANSI codes for various text properties.n* +lookup+: A reverse lookup map for ANSI codes.

Key Functions:

  • encode-raw: Encodes raw ANSI modifier codes to a string.n encode: Encodes ANSI characters for modifiers (e.g., :bold, :red).n style: Styles text with ANSI modifiers.n style:remove: Removes ANSI formatting from a string.n define-ansi-forms (macro): Defines helper functions for common ANSI styles (e.g., blue, on-white, bold).

15.3    std.print.base.animate (Animation)

This sub-namespace provides utilities for displaying ASCII animations in the console.

Key Functions:

  • print-animation: Outputs an animated ASCII file or a sequence of frames.

15.4    std.print.base.report (Report Generation)

This sub-namespace provides functions for generating structured reports, including headers, titles, rows, columns, and summaries.

Key Functions:

  • print-header: Prints a report header.n print-title: Prints a report title.n print-subtitle: Prints a report subtitle.n print-row: Prints a row of data.n print-column: Prints a column of data.n print-summary: Prints a summary of results.n print-tree-graph: Prints a tree-like graph.

15.5    std.print.format (General Formatting)

This sub-namespace aggregates various formatting utilities from its submodules, providing a unified interface for common formatting tasks.

Key Functions:

  • From std.print.format.chart: bar-graph, tree-graph, sparkline, table, table:parse.n From std.print.format.common: pad, pad:left, pad:right, pad:center, justify, border, indent.n From std.print.format.report: report:bold, report:column, report:header, report:row, report:title.n* From std.print.format.time: t, t:ms, t:ns, t:time.

15.6    std.print.format.chart (Chart Formatting)

This sub-namespace provides functions for formatting various types of ASCII charts and tables for console output.

Key Functions:

  • lines:bar-graph: Formats an ASCII bar graph as lines.n bar-graph: Constructs an ASCII bar graph.n sparkline: Formats a sparkline.n tree-graph: Returns a string representation of a tree graph.n table-basic:format: Generates a basic ASCII table.n table-basic:parse: Reads a basic ASCII table from a string.n table: Generates a formatted ASCII table.n* table:parse: Parses a formatted ASCII table.

15.7    std.print.format.common (Common Formatting Utilities)

This sub-namespace provides fundamental utilities for padding, justifying, indenting, and bordering text.

Key Functions:

  • pad, pad:left, pad:right, pad:center: Functions for padding text.n justify: Justifies text to a given alignment.n indent: Indents lines of text.n pad:lines: Creates new lines of spaces.n border: Formats a border around lines of text.

15.8    std.print.format.report (Report Formatting)

This sub-namespace provides functions for formatting elements within reports, such as rows, headers, and titles.

Key Functions:

  • lines:elements: Lays out an array of elements as rows.n lines:row-basic: Lays out raw elements for a row.n lines:row: Lays out row elements with colors and results.n report:header: Formats a report header.n report:row: Formats a report row.n report:title: Formats a report title.n report:bold: Formats text in bold.n* report:column: Formats a report column.

15.9    std.print.format.time (Time Formatting)

This sub-namespace provides functions for formatting time and duration values into human-readable strings, with optional styling.

Key Functions:

  • t:time: Formats a timestamp to time only.n t:ms: Converts milliseconds to a human-readable duration.n t:ns: Converts nanoseconds to a human-readable duration.n t:text: Formats nanoseconds to a string.n t:style: Sets the color for a time duration.n* t: Formats nanoseconds to a styled string.

15.10    std.print.progress (Progress Indicators)

This sub-namespace provides utilities for displaying progress indicators in the console, including progress bars and spinners.

Key Functions:

  • replace-center: Replaces the center of a string with text.n progress-bar-string: Converts a progress percentage to a progress bar string.n progress-spinner-string: Converts progress to a spinner string.n progress-eta: Calculates the estimated time left.n progress: Creates a progress structure.n progress-string: Creates a string representation of progress.n progress-update: Updates the progress meter.n* progress-test: Demonstrates progress indicators.

15.11    Usage Pattern:

The std.print module is essential for:

  • User Feedback: Providing clear and informative output to users in console applications.n Debugging and Logging: Enhancing the readability of debug messages and log entries.n Reporting: Generating structured reports and summaries.n* Visualizations: Creating simple ASCII charts and progress indicators.

By offering a rich set of formatting and presentation tools, std.print improves the user experience and makes console-based applications more engaging and informative.

16    std.protocol: A Comprehensive Summary

The std.protocol module in foundation-base defines a comprehensive set of Clojure protocols and multimethods that establish a standardized interface for various functionalities across the ecosystem. These protocols serve as contracts, enabling polymorphic behavior and allowing different implementations to adhere to a common API. This modular design promotes extensibility, maintainability, and interoperability within the project.

The module is organized into several sub-protocols, each addressing a specific domain:

16.1    std.protocol.apply

Defines an interface for objects that can be "applied" or invoked within a runtime context, allowing for transformation of input and output.

  • IApplicable Protocol:n -apply-in [app rt args]: Applies the object within a runtime rt with args.n -apply-default [app]: Provides a default application behavior.n -transform-in [app rt args]: Transforms input arguments before application.n -transform-out [app rt args return]: Transforms the return value after application.

16.2    std.protocol.archive

Defines an interface for interacting with archive files (e.g., ZIP, JAR), providing functionalities for listing, checking, archiving, extracting, inserting, removing, writing, and streaming entries.

  • IArchive Protocol:n -url [archive]: Returns the URL of the archive.n -path [archive entry]: Returns the path of an entry within the archive.n -list [archive]: Lists all entries in the archive.n -has? [archive entry]: Checks if an entry exists in the archive.n -archive [archive root inputs]: Creates an archive from inputs at root.n -extract [archive output entries]: Extracts entries from the archive to output.n -insert [archive entry input]: Inserts an input as an entry into the archive.n -remove [archive entry]: Removes an entry from the archive.n -write [archive entry stream]: Writes an entry to a stream.n -stream [archive entry]: Returns an input stream for an entry.n -open Multimethod:n Dispatches on type and path, allowing different implementations for opening various archive types (e.g., :zip, :jar).

16.3    std.protocol.binary

Defines interfaces for converting objects to and from binary representations, and for handling byte sources, sinks, and channels.

  • IBinary Protocol:n -to-bitstr [x]: Converts x to a bit string.n -to-bitseq [x]: Converts x to a sequence of bits.n -to-bitset [x]: Converts x to a set of bits.n -to-bytes [x]: Converts x to a byte array.n -to-number [x]: Converts x to a number.n IByteSource Protocol:n -to-input-stream [obj]: Converts obj to an InputStream.n IByteSink Protocol:n -to-output-stream [obj]: Converts obj to an OutputStream.n IByteChannel Protocol:n * -to-channel [obj]: Converts obj to a java.nio.channels.Channel.

16.4    std.protocol.block

Defines interfaces for representing and manipulating code as data structures ("blocks"), forming the Abstract Syntax Tree (AST) or Intermediate Representation (IR) of the transpiler.

  • IBlock Interface:n _type []: Returns the block's type (e.g., :list, :symbol).n _tag []: Returns the semantic tag of the block.n _string []: Converts the block to its string representation.n _length []: Returns the length of the block.n _width []: Returns the width (rows) of the block.n _height []: Returns the height (columns) of the block.n _prefixed []: Returns the length of the prefix.n _suffixed []: Returns the length of the suffix.n _verify []: Checks if the block contains valid data.n IBlockModifier Interface:n _modify [accumulator input]: Modifies an accumulator with an input block.n IBlockExpression Interface:n _value []: Returns the semantic value of the block.n _value_string []: Returns the string representation of the block's value.n IBlockContainer Interface:n _children []: Returns the children of a container block.n * _replace_children [children]: Replaces the children of a container block.

16.5    std.protocol.component

Defines interfaces for managing the lifecycle and querying the state of components within the system.

  • IComponent Protocol:n -start [component]: Starts the component.n -stop [component]: Stops the component gracefully.n -kill [component]: Forcefully stops the component.n IComponentQuery Protocol:n -started? [component]: Checks if the component is started.n -stopped? [component]: Checks if the component is stopped.n -info [component level]: Returns information about the component at a given level of detail.n -remote? [component]: Checks if the component is a remote resource.n -health [component]: Returns the health status of the component.n IComponentProps Protocol:n -props [component]: Returns the properties of the component.n IComponentOptions Protocol:n -get-options [component]: Returns the options configured for the component.n IComponentTrack Protocol:n * -get-track-path [component]: Returns the tracking path for the component.

16.6    std.protocol.context

Defines interfaces for managing execution contexts, pointers to resources within those contexts, and their lifecycle.

  • ISpace Protocol:n -context-set [sp ctx key options]: Sets a context.n -context-unset [sp ctx]: Unsets a context.n -context-list [sp]: Lists available contexts.n -context-get [sp ctx]: Retrieves a context.n -rt-active [sp]: Returns the active runtime.n -rt-get [sp ctx]: Retrieves a runtime.n -rt-start [sp ctx]: Starts a runtime.n -rt-started? [sp ctx]: Checks if a runtime is started.n -rt-stopped? [sp ctx]: Checks if a runtime is stopped.n -rt-stop [sp ctx]: Stops a runtime.n IPointer Protocol:n -ptr-context [_]: Returns the context of a pointer.n -ptr-keys [ptr]: Returns the keys associated with a pointer.n -ptr-val [ptr key]: Returns the value for a key in a pointer.n IContext Protocol:n -raw-eval [rt string]: Evaluates a raw string in the runtime.n -init-ptr [rt ptr]: Initializes a pointer in the runtime.n -tags-ptr [rt ptr]: Tags a pointer.n -deref-ptr [rt ptr]: Dereferences a pointer.n -display-ptr [rt ptr]: Displays a pointer.n -invoke-ptr [rt ptr args]: Invokes a pointer with arguments.n -transform-in-ptr [rt ptr args]: Transforms input arguments for a pointer.n -transform-out-ptr [rt ptr return]: Transforms the return value from a pointer.n IContextLifeCycle Protocol:n -has-module? [rt module-id]: Checks if a module exists in the runtime.n -setup-module [rt module-id]: Sets up a module in the runtime.n -teardown-module [rt module-id]: Tears down a module in the runtime.n -has-ptr? [rt ptr]: Checks if a pointer exists in the runtime.n -setup-ptr [rt ptr]: Sets up a pointer in the runtime.n -teardown-ptr [rt ptr]: Tears down a pointer in the runtime.

16.7    std.protocol.deps

Defines interfaces for managing dependencies, including retrieving entries, compiling, and tearing down dependency graphs.

  • IDeps Protocol:n -get-entry [context id]: Retrieves a dependency entry.n -get-deps [context id]: Retrieves dependencies for an entry.n -list-entries [context]: Lists all dependency entries.n IDepsMutate Protocol:n -add-entry [context id entry deps]: Adds a dependency entry.n -remove-entry [context id]: Removes a dependency entry.n -refresh-entry [context id]: Refreshes a dependency entry.n IDepsCompile Protocol:n -step-construct [context acc id]: Constructs a dependency step.n -init-construct [context]: Initializes dependency construction.n IDepsTeardown Protocol:n -step-deconstruct [context acc id]: Deconstructs a dependency step.n IDepsLibrary Protocol:n -parse-native [context input opts]: Parses native input for the dependency library.n IDepsProducer Protocol:n -produce [context opts]: Produces dependencies.n -create Multimethod:n Dispatches on :path, used for creating dependency contexts.

16.8    std.protocol.dispatch

Defines interfaces for dispatching tasks, typically to executors or queues.

  • IDispatch Protocol:n -submit [dispatch entry]: Submits an entry for dispatch.n -bulk? [dispatch]: Checks if the dispatch mechanism supports bulk operations.n -create Multimethod:n Dispatches on :type, used for creating dispatch executors.

16.9    std.protocol.invoke

Defines multimethods for handling function invocation, package loading, and anonymous function body generation, particularly relevant for code generation and dynamic execution.

  • -invoke-intern Multimethod:n Dispatches on label, name, config, body, used for constructing forms for interning invoked functions.n -invoke-package Multimethod:n Dispatches on identity, used for loading invoke-intern types.n -fn-body Multimethod:n Dispatches on label and body, used for defining anonymous function bodies (e.g., for different target languages).n -fn-package Multimethod:n * Dispatches on identity, used for loading fn-body types.

16.10    std.protocol.log

Defines interfaces for logging, including writing log entries and processing them.

  • ILogger Protocol:n -logger-write [logger entry]: Writes a log entry.n ILoggerProcess Protocol:n -logger-process [logger entries]: Processes a collection of log entries.n -create Multimethod:n * Dispatches on :type, used for creating logger instances.

16.11    std.protocol.match

Defines an interface for template matching.

  • ITemplate Protocol:n * -match [template obj]: Matches an object against a template.

16.12    std.protocol.object

Defines multimethods for accessing and manipulating object metadata, particularly for reading and writing.

  • -meta-read Multimethod:n Dispatches on identity, used for accessing class meta information for reading from an object.n -meta-write Multimethod:n * Dispatches on identity, used for accessing class meta information for writing to an object.

16.13    std.protocol.request

Defines interfaces for making single or bulk requests and processing their responses.

  • IRequest Protocol:n -request-single [client command opts]: Makes a single request.n -process-single [client output opts]: Processes a single request's output.n -request-bulk [client commands opts]: Makes multiple requests in bulk.n -process-bulk [client inputs outputs opts]: Processes bulk request inputs and outputs.n IRequestTransact Protocol:n -transact-start [client]: Starts a transaction.n -transact-end [client]: Ends a transaction.n -transact-combine [client commands]: Combines commands within a transaction.

16.14    std.protocol.return

Defines an interface for handling return values, including checking for errors and retrieving metadata.

  • IReturn Protocol:n -get-value [obj]: Retrieves the value from a return object.n -get-error [obj]: Retrieves any error from a return object.n -has-error? [obj]: Checks if the return object contains an error.n -get-status [obj]: Retrieves the status of the return object.n -get-metadata [obj]: Retrieves metadata associated with the return object.n -is-container? [obj]: Checks if the return object is a container.

16.15    std.protocol.state

Defines interfaces and multimethods for managing state, including creation, retrieval, update, and cloning.

  • IStateGet Protocol:n -get-state [obj opts]: Retrieves the state of an object.n IStateSet Protocol:n -update-state [obj f args opts]: Updates the state of an object using a function f.n -set-state [obj v opts]: Sets the state of an object to v.n -empty-state [obj opts]: Empties the state of an object.n -clone-state [obj opts]: Clones the state of an object.n -create-state Multimethod:n Dispatches on type, data, opts, used for creating state objects.n -container-state Multimethod:n Dispatches on identity, used for returning a type for a label.

16.16    std.protocol.stream

Defines interfaces for stream-like operations, including collecting, producing, blocking, and staging.

  • ISink Protocol:n -collect [sink xf supply]: Collects items into a sink.n ISource Protocol:n -produce [source]: Produces items from a source.n IBlocking Protocol:n -take-element [source]: Takes an element from a blocking source.n IStage Protocol:n -stage-unit [stage]: Returns the unit of a stage.n -stage-realized? [stage]: Checks if a stage is realized.n * -stage-realize [stage]: Realizes a stage.

16.17    std.protocol.string

Defines interfaces and multimethods for string conversions and path separation.

  • IString Protocol:n -to-string [x]: Converts x to a string.n -from-string Multimethod:n Dispatches on string, type, opts, used for extending string-like objects.n -path-separator Multimethod:n * Dispatches on identity, used for finding the path separator for a given data type.

16.18    std.protocol.time

Defines interfaces and multimethods for handling time instants, durations, representations, and formatting/parsing.

  • IInstant Protocol:n -to-long [t]: Converts a time instant t to a long.n -has-timezone? [t]: Checks if t has timezone information.n -get-timezone [t]: Gets the timezone of t.n -with-timezone [t tz]: Sets the timezone of t.n IRepresentation Protocol:n -millisecond [t opts]: Gets the millisecond component of t.n -second [t opts]: Gets the second component of t.n -minute [t opts]: Gets the minute component of t.n -hour [t opts]: Gets the hour component of t.n -day [t opts]: Gets the day component of t.n -day-of-week [t opts]: Gets the day of the week component of t.n -month [t opts]: Gets the month component of t.n -year [t opts]: Gets the year component of t.n IDuration Protocol:n -to-length [d opts]: Converts a duration d to a length.n -time-meta Multimethod:n Dispatches on cls, used for accessing meta properties of a class related to time.n -from-long Multimethod:n Dispatches on long, opts (specifically :type), used for creating time representations from a long.n -now Multimethod:n Dispatches on opts (specifically :type), used for creating a representation of the current time.n -from-length Multimethod:n Dispatches on long, opts (specifically :type), used for creating a representation of a duration.n -formatter Multimethod:n Dispatches on pattern, opts (specifically :type), used for creating time formatters.n -format Multimethod:n Dispatches on formatter, t, opts, used for formatting time objects.n -parser Multimethod:n Dispatches on pattern, opts (specifically :type), used for creating time parsers.n -parse Multimethod:n * Dispatches on parser, s, opts (specifically :type), used for parsing time strings.

16.19    std.protocol.track

Defines an interface for tracking components.

  • ITrack Protocol:n * -track-path [component]: Returns the tracking path for a component.

16.20    std.protocol.watch

Defines an interface for adding, removing, and listing watches on objects.

  • IWatch Protocol:n -add-watch [obj k f opts]: Adds a watch to an object.n -has-watch [obj k opts]: Checks if an object has a specific watch.n -remove-watch [obj k opts]: Removes a watch from an object.n -list-watch [obj opts]: Lists all watches on an object.

16.21    std.protocol.wire

Defines interfaces and multimethods for wire-level communication, including reading, writing, closing, and serialization/deserialization of data.

  • IWire Protocol:n -read [remote]: Reads from a remote connection.n -write [remote command]: Writes a command to a remote connection.n -close [remote]: Closes a remote connection.n -as-input Multimethod:n Dispatches on val, type, used for converting an object to an input format.n -serialize-bytes Multimethod:n Dispatches on val, type, used for converting an object to bytes.n -deserialize-bytes Multimethod:n * Dispatches on bytes, type, used for converting bytes back to an object.

Overall Importance:

The std.protocol module is central to the foundation-base project's architectural design. By defining clear, extensible interfaces, it enables:

  • Polymorphism: Different data types and implementations can adhere to the same behavioral contracts, promoting code reuse and flexibility.n Modularity: Functionalities are decoupled from concrete implementations, making it easier to swap out or add new components without affecting the entire system.n Extensibility: New types can easily extend existing protocols, allowing the system to evolve and adapt to new requirements.n Testability: Protocols provide well-defined boundaries, simplifying the testing of individual components.n Clarity and Documentation: Protocols serve as self-documenting APIs, clearly outlining the expected behavior of various system parts.

This comprehensive set of protocols forms the backbone of foundation-base, facilitating its advanced capabilities in transpilation, runtime management, and multi-language support.

17    std.text: A Comprehensive Summary

The std.text module in foundation-base provides functionalities for text processing, specifically focusing on text differencing and full-text indexing. It integrates with external libraries (like difflib for Java) and offers tools for comparing text, applying/reverting patches, and creating searchable text indexes with stemming and persistence capabilities.

The module is organized into two main sub-namespaces:

17.1    std.text.diff

This namespace provides utilities for computing and applying differences between text sequences, often referred to as "diffing" and "patching." It leverages the difflib Java library.

  • create-patch [arr]: Creates a difflib.Patch object from a collection of delta maps.n object/vector-like Patch: Extends difflib.Patch to be treated as a vector-like object, allowing conversion to/from data maps.n object/string-like Delta$TYPE: Extends difflib.Delta$TYPE to be treated as a string-like object, allowing conversion to/from string representations.n create-delta [map]: Creates a difflib.Delta object (e.g., InsertDelta, ChangeDelta, DeleteDelta) from a map representation.n object/map-like Delta: Extends difflib.Delta to be treated as a map-like object, allowing conversion to/from data maps.n create-chunk [map]: Creates a difflib.Chunk object from a map representation.n object/map-like Chunk: Extends difflib.Chunk to be treated as a map-like object, allowing conversion to/from data maps.n diff [original revised]: Computes the differences between two text strings (or sequences of lines) and returns a collection of delta maps.n patch [original diff]: Applies a series of diff deltas to an original text, returning the revised text.n unpatch [revised diff]: Reverts a series of diff deltas from a revised text, restoring the original text.n ->string [deltas]: Converts a collection of delta maps into a human-readable string representation, often with ANSI color coding for added/removed lines.n* summary [deltas]: Creates a summary of the diffs, counting the number of deletions and insertions.

17.2    std.text.index

This namespace provides functionalities for creating and querying a full-text search index, including text stemming and disk persistence. It uses std.text.index.stemmer and std.text.index.porter for stemming.

  • Index Record: A Clojure record to hold the index data (a map from stem to a map of keys to weights) and the stemmer function.n make-index [& [stemmer-func]]: Creates a new search index, optionally specifying a custom stemmer function (defaults to Porter stemmer). The index is managed as an agent for concurrent updates.n add-entry [index stem key weight]: Adds an entry to the index for a given stem, associating it with a key and weight.n remove-entries [index key stems]: Removes entries associated with a key for a given set of stems.n index-text [index key data & [weight]]: Adds text to the index. It processes text blocks, stems words, calculates frequencies, and updates the index with associated keys and weights.n unindex-text [index key txt]: Removes text associated with a key from the index.n unindex-all [index key]: Clears all entries associated with a specific key from the index.n query [index query-string]: Queries the index with a query-string, returning a map of stems to their associated key-weight maps.n merge-and [query-results]: Merges query results using an "AND" logic, returning a map of IDs to their combined scores (multiplied weights).n merge-or [query-results]: Merges query results using an "OR" logic, returning a map of IDs to their combined scores (summed weights).n search [index term & [merge-style]]: Performs a search on the index for a given term, using either "AND" (default) or "OR" merge style, and returns sorted results.n save-index [index & [filename-or-file]]: Saves the index data to a file, optionally specifying the filename.n load-index [index filename-or-file]: Loads index data from a file into the index.

Overall Importance:

The std.text module is a valuable component for applications requiring text analysis, comparison, and search capabilities within the foundation-base project.

  • Text Differencing: The std.text.diff namespace is crucial for tasks like version control, code review tools, or any application that needs to highlight changes between text documents. Its integration with difflib provides robust diffing algorithms, and the ->string function offers user-friendly output.n Full-Text Search: The std.text.index namespace provides a lightweight yet powerful full-text indexing solution. This is essential for applications that need to search through large volumes of text efficiently, such as documentation systems, knowledge bases, or code search tools. The use of stemming improves search relevance, and agent-based concurrency ensures safe updates.n Foundation for Text-Based Tools: Both sub-modules provide foundational building blocks for creating more sophisticated text-based tools and features within the foundation-base ecosystem, supporting its broader goals of code generation and language processing.

By offering these specialized text processing functionalities, std.text enhances the project's ability to manage and interact with textual data effectively.