Skip to content

Releases

v3.24.0

Choose a tag to compare

@cldmv-bot cldmv-bot released this 02 Nov 12:37
v3.24.0
cd60a74

Slothlet v3.24.0 Changelog

Release Date: November 2026
Release Type: Minor
Branch: next → master


Overview

Version 3.24.0 finishes the identity half of the permission work that 3.23.0 started. 3.23.0 made the ownership rule hold wherever module code can write; 3.24.0 makes sure the code being checked is attributed to the module that actually wrote it. Code a caller hands to a leaf (a callback, a getter, a toString, a Proxy trap) now runs as the caller, with the leaf it runs inside as its ceiling, and code a module hands out (closures, factories, classes and their instances, iterators, accessors) runs as the module that made it, wherever it is called from later. Frames are placed by the file and the script that run them, so code compiled under another file's name is not that file's.

The rest of the release is fixes: new on a lazy folder that has not loaded yet now constructs the class, reading a cyclic object through self inside a module closes the cycle again, and the repository's development tooling moves to Node 22.22 while the runtime floor stays at 22.15.

Nothing changes in dependencies, optionalDependencies, peerDependencies or engines. With permissions on, some calls that used to be allowed because supplied code ran as the leaf are now refused; see Behavior changes and Upgrade notes.


✨ Features

Code a module made runs as that module, whoever runs it (#597, #624)

  • Code a caller hands to a leaf runs as the caller. A leaf that converts, reads or calls a value it was handed runs code the value carries: String(v) runs a toString, v.x runs a getter or a Proxy get trap, fn() runs a callback. That code is the supplier's, so it runs as the supplier, with the leaf it runs inside as its ceiling: both have to be allowed. The leaf keeps its own rights for its own code, and metadata.caller() / metadata.self() report the supplier inside supplied code.
  • Code a module hands out runs as that module. Closures, factories, classes and their instances, iterators, Proxies and accessors a module returns or stores keep running as the module that made them, with no ceiling from whoever calls them later.
  • permissions.ceiling ("leaf" by default). With "chain", the ceiling keeps every leaf the code was handed through on the way, not only the one it is running inside, and all of them are enforced.
  • permissions.provenance (true by default). A module's own function that reaches another module's call by a route slothlet does not see (a shared object, a global, a built-in it replaced) still runs as that module, with the call it runs inside as its ceiling. false turns this off.
  • Frames are held to their script. Slothlet records the SHA-256 of the source each instance module was loaded from (CallSite#getScriptHash()), so code compiled with vm or Module#_compile under a module's file name is not treated as that module's code.
  • Getters and setters on api objects run as their module and are checked as calls of their node.
  • Module-initiated api.add and reload build the added module as no module's code, while the host's own calls in the meantime stay the host's.
  • Values no module made (a package's exports, a node: built-in's, slothlet's runtime) are handed out as they are, and everything callable they reach is made by no module too. Package files record their exports as they finish loading, through Node's module load hook.
  • Works with 3.23.0's ownership rules. Every ceiling is held to the same ownership and rule checks as the caller, a kept lockCaller.caller run from handed-out code pins its module, and a node removed from the tree leaves what it made without standing.

See docs/PERMISSIONS.md for the placement rules and their limits.

⚠️ Behavior changes

These only apply while the permission system is on.

  • Supplied code needs both the supplier and the leaf to be allowed (#597). A callback, getter or conversion a module hands to a leaf used to run with the leaf's rights. It now runs as the module that supplied it, under the leaf as a ceiling, so a self.* call from inside it is refused unless both may make it. Asking a permitted module to do something on its own account still works.
  • Handing over a leaf's own function is checked as calling it (#597). Passing another module a function slothlet wraps, alone or inside plain data, gates the receiving call as though the caller had called that leaf through self.
  • Accessors on api objects are checked as calls (#597). Reading or writing a getter or setter a module exports needs permission to call the api object that holds it.
  • A callback kept and run later from another flow is no longer tied to its supplier. Pin it with self.slothlet.lockCaller.caller(fn) where it is registered, or have the supplier pin it with self.slothlet.lockCaller(fn) before handing it over.

🐛 Bug Fixes

new on a lazy folder that has not loaded yet (#685, #686)

new on the stand-in a lazy folder hands out before it loads ran the engine's default construction on the stand-in: the constructor never ran, and every member of the object it returned was another stand-in. The stand-in now loads the chain and constructs its end, under the caller identity captured at new, and resolves to the instance. A stand-in held across restart() now resolves to the live end of its chain instead of building an object without the class's prototype.

A subclass's super() through a node that has not loaded, or is still loading, has to finish synchronously, which it cannot. It now throws LAZY_SUBCLASS_BEFORE_LOAD instead of handing back a broken instance; await the node first, or use eager mode.

Cyclic members read through self close again (#688, #694)

Since 3.23.0, a plain object reached through self inside a module is a per-reader view held to the api path it was reached at. Views were cached per path, so following a cycle like conn.self = conn gave a longer path and a new view on every lap: c.self.self !== c.self, and deep equality (isDeepStrictEqual, toEqual) never found the cycle and ran until the stack ran out. A member read that walks back into a value already on its walk now gets that value's earlier view, so the cycle closes. A write round the cycle is held to that earlier, shorter path. Host reads are unchanged.

🔧 CI & tooling

  • Development needs Node 22.22; using slothlet still needs 22.15 (#689). The dev toolchain (chokidar 6) needs Node 22.22, which now sits in devEngines and is CI's minimum Node version. engines.node stays >=22.15.0, the floor slothlet's own code needs (module.registerHooks() and CallSite#getScriptHash()).
  • CI test workers sized to the runner (#696). On CI the test runner now runs one worker per 3 GB of memory and per core (4 on GitHub's hosted runner) instead of a fixed 8, which had been starving the runner until GitHub dropped it mid-run. Local runs are unchanged.
  • devcheck removed from the repository (#684). The slothlet-dev export condition already picks src/ or dist/ in a checkout. Nothing changes for installed packages; devcheck has not been published since 3.22.1.

📚 Documentation

  • docs/PERMISSIONS.md: code supplied to a leaf, code a module hands out, permissions.ceiling and permissions.provenance, script binding and its limits, and how a cycle read through self is held to its paths.
  • NEW: docs/changelog/v3/v3.24.0.md, this changelog.

🔧 Dependencies

All dev-only (#689, superseding #679 and #680):

  • chokidar ^5.0.0 → ^6.0.0
  • @vitest/istanbul-lib-coverage ^1.0.1 → ^2.1.0
  • overrides: katex >=0.19.1 <1.0.0 and minimatch ^11.0.3, both pulled in through the eslint chain, for their advisories

Upgrade notes

  • Without a permissions config, nothing changes.
  • With permissions on, code a module hands to another module's leaf is now checked as its own module under that leaf. If a supplied callback stops being allowed, grant the supplier the call it makes, or keep that work inside the leaf's own code.
  • A callback a leaf stores and runs later (a timer, an event, a queue) needs lockCaller to keep its supplier's identity.
  • To check every leaf supplied code passed through, set permissions: { ceiling: "chain" }.
  • Subclassing a lazy node before it has loaded throws LAZY_SUBCLASS_BEFORE_LOAD: await api.path first and extend what it resolves to.
  • Contributors need Node 22.22 or later to install and run the tooling; consumers still need 22.15 or later.

coverage

Metric Coverage
Statements 96.6%
Branches 94.2%
Functions 96.6%
Lines 98.1%

Avg: 96.3% · 8bee650 · Node lts/*

👥 Contributors

v3.23.0

Choose a tag to compare

@cldmv-bot cldmv-bot released this 27 Oct 04:52
v3.23.0
9c29444

Slothlet v3.23.0 Changelog

Release Date: October 2026
Release Type: Minor
Branch: next → master


Overview

Version 3.23.0 is mostly a fix release. Its headline change makes the module ownership rule hold everywhere a module can reach while the permission system is on: module code may change data only under the api path it owns, whether it writes at the top of self, several levels down, through a node another module handed it, through api.add and api.remove, or through the framework's own setters. Write permissions join the permission system as :write rules, so the host or a manifest can grant one module writes into another's subtree, and a module removed from the api keeps no standing for the code it left behind.

The one new feature is the permission system's three modes (permissions.mode): "on", "off" (the default with no permissions config), and "disabled". Off, no rule is evaluated and ownership refuses nothing, but module code still cannot change the framework's own slothlet namespace, root functions, or the framework's keys on api nodes. Only "disabled" leaves those open.

The rest of the release fixes how the api composes and behaves: eager and lazy mode now compose the same api, and a structure check compares them. Writes through an array api member reach the array, and frozen nodes keep their permission checks. Live-runtime callers are attributed correctly across overlapping calls and instances. The browser no longer needs setImmediate. Members named like name, length or then behave as members. A synchronous around hook may return a thenable derived from next(). The EventEmitter tracking that held every emitter a module listened to until shutdown now holds them weakly, so connections a module opens are collectable again.

Every dependency change is dev-only. dependencies, optionalDependencies, peerDependencies and engines are unchanged. Several fixes refuse things that used to be allowed or silently misbehaved; see Behavior changes and Upgrade notes.


✨ Features

Permission modes: on, off, disabled (#628)

permissions.mode sets how much of the permission system applies:

Mode How What applies
"on" a permissions config (the default for one), or control.enable() Every rule: calls, reads, writes, and ownership.
"off" no permissions config, mode: "off", enabled: false, or control.disable() Module code cannot change the framework's own namespace, root functions, or keys on api nodes. Nothing else is checked.
"disabled" mode: "disabled" in the config Nothing, apart from the reserved names slothlet, shutdown and destroy on self.

enabled: true and enabled: false keep working as "on" and "off". api.slothlet.permissions.control.mode reports the mode, and a mode the host switched to with control.enable() / control.disable() now holds across reload(). See docs/PERMISSIONS.md.

⚠️ Behavior changes

These are fixes, but code that relied on the old behavior will notice them.

  • The framework's own namespace is kept from module code by default (#628). With no permissions config (mode "off"), module code that assigns, defines, or deletes anything under self.slothlet, replaces self.shutdown / self.destroy, or changes a framework key on a node (__mode, ____slothletInternal, …) now gets PERMISSION_DENIED. Calls into the namespace behave as before. Set permissions: { mode: "disabled" } to leave it open.
  • Module code is held to its own api path at any depth while the permission system is on (#628). A write into another module's subtree through a nested self path or through a node another module returned now throws LOOSE_SET_NOT_OWNED (or PERMISSION_DENIED from a write rule). With the system off, ownership refuses nothing. Grant cross-module writes with a :write rule (see below).
  • api.add, api.remove, api.reload, and the metadata and versioning setters are writes when module code calls them (#628). Module code mounts, removes and reloads only under its own path, cannot reuse another live module's moduleID, and cannot mount at a path where a module it mounted is still mounted.
  • Rules module code registers are limited to its own subtree (#628). self.slothlet.permissions.addRule, a manifest mounted by module code, the permissions option of a module's api.add, and self.slothlet.event.rules.add accept only targets inside the module's own subtree. To let a module manage rules beyond it, grant it slothlet.permissions.addRule. A Proxy anywhere in a rule's condition is refused.
  • A removed module's code has no standing (#628). Functions it kept or handed out own nothing. With permissions on, their calls are refused, and they cannot reach self.slothlet.*. Its hooks, lifecycle subscribers, event listeners, rule conditions and event strategy stop. This holds even after another module is mounted under the same moduleID.
  • Another module's data objects are read-only views unless it may write them (#628). A Map, Set, Date, buffer, typed array, RegExp, Promise or WeakRef read through self from another module's path is a live view that refuses changes. Native code such as fs.write, crypto or structuredClone rejects a view, so copy first (Buffer.from(view), view.slice()). The owner, the host and a module granted the write get the object itself.
  • metadata.getFor, metadata.getForVersion, versioning.getVersionMetadata and versioning.list return copies (#628). Changing what they return no longer changes the stored data.
  • A callable then is refused where slothlet would await it (#580). A file or folder named then gives MODULE_THENABLE_NAME. A module value with a callable then becoming an api node gives MODULE_THENABLE_EXPORT. Assigning one onto a node gives API_MEMBER_THEN_RESERVED, and an api.add path or version tag segment named then is refused. Data named then (if/then/else schemas, then: 1) still reads back.
  • Reserved folder names and __proto__ exports are refused (#580, #585). A folder named like a framework-internal key fails with MODULE_RESERVED_DIRNAME, and an export named __proto__ is refused. A module's own _x or __priv exports are now kept in lazy mode, as eager mode always did.
  • addapi.mjs composes as the file named after its level (#585), at initial load as well as on api.add. Its default becomes the node, with named exports beside it, instead of being merged flat.
  • In lazy mode, a folder whose only entry is a same-named folder stays nested (#582), as in eager mode. api/x/foo/foo/get.mjs is api.x.foo.foo.get() in both modes; the old lazy path api.x.foo.get() is gone.
  • Hook handlers are called with no this (#628). A handler used to be called as a method of its own registration; it is now a plain function call, as a lifecycle subscriber's is.
  • Third-party emitters keep their listeners when the last instance shuts down (#606). Each listener is restored to the function the code registered, instead of being stripped.

🐛 Bug Fixes

Module ownership and write permissions (#628)

The ownership rule (a module mounted at P writes only under P.*) used to be checked only for a write at the top of self, permissions or not. It now covers every route module code has to another module's data, and it refuses writes while the permission system is on; with it off, ownership is still recorded but refuses nothing. Fixes #625.

  • Writes at any depth, judged by what they reach. Assignment, definition, deletion, prototype changes, preventExtensions, freeze and seal through any node read from self are judged at the path of the node they actually reach, including through a node or value another module stored or returned. A getter or a module-stored Proxy on the way is not walked through, and version dispatchers are followed to the versioned node. This also covers a write through a lazy node that has not loaded yet.
  • The framework's surface is protected. self.slothlet.*, the root functions (shutdown, destroy) and the framework-internal keys of every node cannot be changed by module code, however the module reached them, in modes "on" and "off". Built-in :write rules carry this protection, and the host can lift them for a named caller. slothlet, shutdown and destroy are refused on self when defined or deleted, as when assigned, in every mode...
Read more

v3.22.1

Choose a tag to compare

@cldmv-bot cldmv-bot released this 05 Oct 05:15
v3.22.1
d135d07

Slothlet v3.22.1 Changelog

Release Date: October 2026
Release Type: Patch
Branch: next → master


Overview

Version 3.22.1 fixes how the package loads from CommonJS. require("@cldmv/slothlet") used to return a wrapper function that was not the function ESM consumers import, and its defaults property was attached a tick later, so reading slothlet.defaults in the same tick as the require() gave undefined. The CommonJS entry now loads the ES module build through Node's synchronous require(esm) and returns that build's own default export, so CommonJS and ESM consumers get the identical function with defaults and the named slothlet alias already set. A follow-up makes that identity independent of load order.

The rest of the release is tooling. Every file header in the repository was restamped by @cldmv/fix-headers 2.1 and the shared @cldmv/configs config, which touched more than a thousand files but changed comments only, and the dev dependencies moved forward (@cldmv/fix-headers 1.3.12 to 2.2.0, @cldmv/configs 1.2.4 added, the Vitest 5.0.3 patch group, and two patched transitive packages). No runtime dependency changed, and the public API, the hooks, the permissions system and the instance lifecycle are untouched.


⚠️ Behavior changes

@cldmv/slothlet/devcheck is no longer published (#568)

devcheck.mjs is a guard that only acts inside a source checkout of this repository: it does nothing in an installed copy. It is removed from the files whitelist and from the exports map, so import "@cldmv/slothlet/devcheck" no longer resolves. index.mjs now imports it by relative path inside its existing try/catch, which is skipped in a browser and silently ignored when the file is absent, as it is in a published package. Nothing a consumer could rely on changed, but the subpath is gone.

CommonJS needs require(esm) (#568)

index.cjs now requires index.mjs directly. On a Node.js version without require(esm) (before 20.19 on the 20.x line, or before 22.12) it throws an error with code ERR_REQUIRE_ESM and a message that names the running version and points at import(). The package already declares engines.node >=22.15.0 since v3.22.0, so a supported Node.js version always has require(esm).

🐛 Bug Fixes

require() returns the ESM entry's own function, synchronously (#568)

index.cjs wrapped index.mjs in its own async function slothlet(options) that ran a dynamic import() on every call, and attached slothlet.defaults from a separate import() that settled on the microtask queue. As a result require("@cldmv/slothlet") was a different function than the ESM default export, and defaults was undefined in the tick that called require().

The entry is now a thin wrapper: it checks process.features.require_module, requires ./index.mjs, and exports that module's default. slothlet.defaults is set when require() returns, and const { slothlet } = require("@cldmv/slothlet") reads the named alias off the same function.

index.mjs itself had to become loadable through require(esm), which rejects any module graph that contains top-level await:

  • New helpers/reserved-keys module. slothlet.defaults is built by helpers/defaults, which imported ComponentBase and IMPL_METADATA_KEYS from the wrapper classes, and those reach helpers/platform and its top-level await. The two reserved-key Sets (WRAPPER_INTERNAL_KEYS, served as ComponentBase.INTERNAL_KEYS, and IMPL_METADATA_KEYS) now live in src/lib/helpers/reserved-keys.mjs, a module with no imports. The classes serve the same Set objects from there, so slothlet.defaults.reservedExports and every filter built on the Sets behave as before. The module is marked internal.
  • No top-level await for the dev check. The devcheck import runs inside an async function rather than at the top level of index.mjs.

CommonJS and ESM consumers see an identical function (#570)

The first version of the fix still wrote module.exports.slothlet = slothlet onto the function ESM consumers import, so that function's own keys were ["defaults"] for an ESM-only load and ["defaults", "slothlet"] once anything had called require(). index.mjs now sets slothlet.slothlet = slothlet itself and index.cjs no longer writes to the shared function, so both module systems see exactly defaults and slothlet whichever loads first. The generated type declarations include the slothlet property.

🧪 Tests

  • tests/node/entrypoint-cjs.cjs (run by npm test through test:node) now checks that require() returns the same function as the ESM default export, that .defaults is already set in the tick of the require(), that .defaults.routines is an array, that the named alias matches the ESM named export, and that CJS and ESM loads expose the same own keys in a fresh process. A child process started with --no-experimental-require-module checks that the entry fails with ERR_REQUIRE_ESM, the version requirement and the import() hint.
  • The Vitest setup files no longer carry a commented-out @cldmv/slothlet/devcheck import.

🔧 CI & tooling

File headers restamped, and the shared fix-headers config adopted (#569)

  • Framed header layout. @cldmv/fix-headers 2.1 writes each header with an empty * line inside the opener and before the closer. Running npm run fix:headers rewrote the header of about 1,150 source, test, tool and fixture files in that layout, refreshed @Last modified time, and corrected 89 @Date epochs that did not match their date text. Header comments are the only change in those files, and the types/*.d.mts.map files were regenerated for the shifted lines. No JSON or Markdown file was touched.
  • ISO dates. The shared config turns on normalizeDateFormat, so every header date is written as 2026-10-03T20:02:20-07:00. Before, @Last modified time used a space form (2026-10-03 20:02:20 -07:00) next to an ISO @Date, and 580 @Date values were still in the space form. Each date keeps its instant.
  • Shared config. tools/dev/fix-headers.mjs no longer hard-codes house settings. It passes the new .configs/fix-headers.json, which extends @cldmv/configs/fix-headers.json and sets only the project name, and keeps the repository's own include lists. The shared settings restamped another 288 headers: @Author and @Last modified by use the signing-key name, four last-modified emails moved to the noreply address, and 16 @Date values moved back to the file's first commit. The wrapper passes margin: 1, because the default margin of 2 is collapsed to 1 by Prettier and the precommit fix:headers and format steps would otherwise rewrite every file back and forth.
  • --diff prints the diff. npm run fix:headers -- --diff (and --dry-run, which implies it) now prints each changed file's header diff instead of only listing file names.
  • Header checks accept the framed layout. The header and stacked-header checks in tools/dev/analyze-errors.mjs allow empty comment lines just inside the opener and before the closer, so the new layout is not reported as a missing header.
  • Later bumps changed nothing. fix-headers 2.2.0 (#572) and @cldmv/configs 1.2.4 (#572) ran fix:headers and restamped 0 files. From 2.2.0 the @Last modified by tag follows content edits only, and 1.2.4 sets forceAuthorUpdate and forceLastModifiedAuthorUpdate to false, so @Author is never rewritten.

The comment-only edits to the build tools (tools/build/build-subpackages.mjs, tools/build/build-typestubs.mjs) just drop their mentions of ./devcheck.

📚 Documentation

🔧 Dependencies

All dev-only. dependencies, optionalDependencies and peerDependencies are unchanged, and the only entries that moved in the lockfile are the ones below.

  • @cldmv/fix-headers ^1.3.10 → ^2.2.0 (locked 1.3.12 to 2.2.0), in four steps: 2.1.0 (#564, Dependabot), 2.1.4 (#569, with the restamp above) and 2.2.0 (#572, no headers changed).
  • @cldmv/configs ^1.2.4, newly added as a dev dependency (#569 added it at ^1.2.2, #572 raised it to 1.2.4). Provides the shared fix-headers config that .configs/fix-headers.json extends.
  • Vitest 5.0.2 → 5.0.3 patch group (#566): vitest, @vitest/browser, @vitest/browser-playwright and @vitest/coverage-v8 5.0.2 to 5.0.3, @vitest/istanbul-lib-coverage 1.0.1 to 1.0.2, chalk 6.0.0 to 6.0.1 and ignore 7.0.10 to 7.0.11. The package.json ranges already allowed these, so only the lockfile changed. The resolution also moves the transitive why-is-node-running from 3.2.2 to 3.2.1, the version vitest asks for.
  • Indirect dev dependencies from Dependabot's npm_and_yarn group: markdown-it 14.2.0 to 14.3.2 (#561) and brace-expansion 5.0.9 to 5.0.12 together with markdown-it (#565). Lockfile only.

Upgrade notes

Read more

v2.8.0

Choose a tag to compare

@cldmv-bot cldmv-bot released this 30 Dec 00:44
v2.8.0
e10e7b4

release: v2.8.0 (#69)

release: v2.8.0 - Dynamic API Extension and Management Methods

🎯 Major Features

Dynamic API Extension with addApi() Method

Implemented addApi(apiPath, folderPath) method to dynamically extend the Slothlet API at runtime by loading modules from a folder and merging them at a specified dotted path (e.g., runtime.plugins, services.external).

Key Capabilities:

  • Load and merge API modules at runtime without restarting the application
  • Support for deeply nested paths with automatic intermediate object creation
  • Full compatibility with both lazy and eager loading modes
  • Automatic live binding updates for multi-instance isolation
  • Slothlet's function.property pattern support (can extend functions with properties)

Management Methods with Proper TypeScript Support

Added comprehensive TypeScript definitions for all management methods:

  • shutdown() - Cleanup and resource disposal with conditional enumerable
  • addApi(apiPath, folderPath) - Dynamic API extension
  • describe(showAll?) - API metadata with accurate return type signatures

🛡️ Configuration & Safety

New allowApiOverwrite Configuration Option

  • Default: true (backwards compatible)
  • Purpose: Prevent accidental endpoint overwrites during dynamic API extension
  • Behavior:
    • When false: Logs warning and skips overwrite attempts
    • When true: Allows overwrites with data loss warnings

Input Validation & Error Handling

  • Normalize apiPath by trimming whitespace before validation
  • Validate folderPath parameter type to prevent unclear errors
  • Handle null/undefined/primitive newModules cases with warnings
  • Prevent empty path segments (consecutive dots, leading/trailing dots)
  • Clear error messages: "non-empty, non-whitespace string"

🐛 Critical Fixes

Fixed Non-Enumerable Management Methods Issue

Fixed mutateLiveBindingFunction to properly copy non-enumerable management methods:

  • Previously used Object.entries() which only copies enumerable properties
  • Now explicitly copies shutdown, addApi, and describe with property descriptors
  • Ensures management methods are accessible in all contexts (ESM and CJS)

Conditional Enumerable Properties

  • shutdown: enumerable when user-defined shutdown exists, non-enumerable when management-only
  • addApi: always non-enumerable (hidden from API iteration)
  • describe: non-enumerable by default (management method)

TypeScript Type Consistency

Updated all entry points (index.mjs, index.cjs) to return SlothletAPI type:

SlothletAPI {
  shutdown: () => Promise<void>
  addApi: (apiPath: string, folderPath: string) => Promise<void>
  describe: (showAll?: boolean) => ((string|symbol)[]|object|Promise<object>)
}

📚 Documentation

JSDoc Enhancements

  • Added comprehensive JSDoc for addApi() method with examples
  • Race condition warning for concurrent addApi calls
  • Documented shallow merge behavior for Object.assign
  • Explained intermediate path navigation (function.property pattern)
  • Added parameter documentation to all entry points

README Updates

  • Configuration section for allowApiOverwrite option
  • Examples showing enable/disable overwrite protection
  • Concurrency warning for addApi method usage
  • Complete API extension workflow examples

🧪 Test Coverage

Comprehensive addApi Test Suite

Added tests/test-add-api.mjs with 7 test scenarios:

  1. Eager mode - Basic API extension with immediate loading
  2. Lazy mode - API extension with proxy-based lazy loading
  3. Nested paths - Deep path creation (level1.level2.level3)
  4. Error handling - Non-existent folders, invalid parameters, empty segments
  5. Merging - Adding to existing objects without data loss
  6. Function extension - Adding properties to functions (slothlet pattern)
  7. allowApiOverwrite - Testing overwrite prevention and permission

Test Results

  • All 26 test cases passing
  • Edge case coverage: whitespace-only paths, non-string parameters, null/undefined handling
  • Validation: Full precommit suite passing (6/6 steps)

📝 Migration Guide

Enabling Overwrite Protection

const api = await slothlet({
  dir: './api',
  allowApiOverwrite: false  // Prevent accidental overwrites
});

// First call succeeds
await api.addApi('plugins.auth', './plugins/auth');

// Second call to same path logs warning and skips
await api.addApi('plugins.auth', './plugins/oauth');  
// Warning: Skipping addApi: API path "plugins.auth" already exists

Dynamic API Extension Example

const api = await slothlet({ dir: './api' });

// Extend API at runtime
await api.addApi('runtime.newFeature', './features/new-feature');

// Access new API immediately
const result = api.runtime.newFeature.someMethod();

✅ Validation

All precommit validation steps passed:

  • ✅ API Structure Debug (576ms)
  • ✅ Node Test Suite - 26 tests passed (22164ms)
  • ✅ Build Distribution (1029ms)
  • ✅ Node ViTest Suite (1808ms)
  • ✅ Build TypeScript Types (2425ms)
  • ✅ Validate TypeScript (33829ms)

Full Changelog: v2.7.1...v2.8.0

v2.7.0

Choose a tag to compare

@cldmv-bot cldmv-bot released this 27 Dec 03:08
v2.7.0
25657d3

release: v2.7.0 (#66)

release: v2.7.0 (#66)

Release: v2.7.0 - Complete Hooks System Implementation

🚀 MAJOR FEATURE RELEASE - COMPREHENSIVE HOOKS SYSTEM FOR API INTERCEPTION
• Implement complete 4-hook system (before/after/always/error) enabling sophisticated function interception patterns across both lazy and eager loading modes
• Add error source tracking providing detailed context about error origins (before hook, function, after hook, always hook) with hook ID, tag, timestamp, and stack traces
• Introduce suppressErrors option allowing error observation without execution failure, enabling non-blocking error monitoring and logging patterns
• Enhance always hooks with full execution context including error state (hasError, errors array) enabling unified success/error logging with single hook
• Implement pattern-based hook removal, type filtering for list/clear operations achieving full feature parity with documented API

✨ HOOK SYSTEM ARCHITECTURE AND CAPABILITIES
• Before hooks: Modify function arguments, short-circuit execution with custom return values, implement validation/caching patterns with priority-based execution
• After hooks: Transform function results, chain multiple transformations in priority order, only execute when functions complete (skipped on short-circuit)
• Always hooks: Observe final results with complete context (path, result, hasError, errors), run like finally blocks even when errors occur or execution cancelled
• Error hooks: Monitor errors with detailed source tracking, receive error type/class information, perfect for centralized error monitoring and alerting systems
• Pattern matching: Glob-based path filtering (*, **, {alt1,alt2}, !negation) with priority-based execution order ensuring predictable hook behavior

🔒 ERROR HANDLING AND RELIABILITY IMPROVEMENTS
• Error source tracking: Detailed origin information (type: 'before'|'function'|'after'|'always', hookId, hookTag, timestamp, stack) enabling precise error debugging
• suppressErrors option: Error hooks always execute, errors thrown only when suppressErrors=false (default), enabling graceful degradation patterns
• WeakSet-based error tracking: Replaced error object mutation with WeakSet preventing issues with frozen/non-extensible errors from external libraries
• Always hooks error context: Full execution context with hasError boolean and errors array eliminating need for separate error+always hooks for comprehensive logging
• Cross-mode compatibility: Identical hook behavior across AsyncLocalStorage and live-bindings runtimes ensuring consistent interception patterns

🛠️ API ENHANCEMENTS AND FEATURE PARITY
• Pattern-based removal: api.hooks.off('math.*') removes all matching hooks using glob pattern compilation with negation support
• Type filtering for clear: api.hooks.clear('before') removes only specified hook type, api.hooks.clear() removes all hooks
• Type filtering for list: api.hooks.list('before') returns filtered hooks, api.hooks.list() returns all hooks with metadata
• Handler signature documentation: Clear parameter documentation for each hook type preventing confusion during registration
• Internal property protection: hooks, __ctx, shutdown, _impl properties excluded from hook execution preventing infinite recursion

Technical Implementation:

  • Complete HookManager class with priority-based execution, glob pattern matching, WeakSet error tracking, and type filtering
  • Integrated hook execution into both runtime systems (AsyncLocalStorage and live-bindings) maintaining performance characteristics
  • executeAlwaysHooks enhanced to accept errors array parameter, passing empty array on success, error array on failure
  • Pattern compilation supporting *, **, brace expansion {a,b}, negation !pattern with maximum nesting depth protection
  • Hooks API wrapper exposing on/off/enable/disable/clear/list methods with full parameter forwarding

Use Case Examples:

  • Unified logging: Single always hook handles both success and error scenarios with conditional logic based on hasError flag
  • Metrics tracking: Monitor call counts, success rates, error rates across API functions using pattern-matched hooks
  • Caching: Before hooks check cache, short-circuit on hit, after hooks populate cache on miss
  • Authorization: Before hooks validate permissions, cancel execution for unauthorized access
  • Error monitoring: Error hooks report to monitoring service with full source context for debugging

Impact Assessment:
Enhanced capabilities - sophisticated function interception patterns enable advanced monitoring, caching, validation, and transformation scenarios; improved developer experience through unified logging patterns and clear handler signatures; enhanced reliability through WeakSet-based error tracking and consistent cross-mode behavior; maintained performance characteristics with minimal overhead for disabled hooks fast-path.

Testing Coverage:
Comprehensive test suite with 40+ tests covering hook execution order, priority handling, pattern matching, error source tracking, suppressErrors behavior, always hook error context, pattern-based removal, type filtering, internal property protection, and cross-mode consistency.

Breaking Changes: None - completely additive feature set with no API modifications
Performance Impact: Minimal - hooks disabled by default, fast-path bypass when disabled, lazy materialization preserved
Hook Reliability: Production-ready - comprehensive testing, WeakSet immutability, consistent behavior across modes

This release establishes slothlet as a sophisticated module loader with enterprise-grade function interception capabilities, enabling advanced monitoring, caching, validation, and transformation patterns while maintaining the performance characteristics that define the framework.

Co-authored-by: Nate - CLDMV [email protected]

v2.6.2

Choose a tag to compare

@cldmv-bot cldmv-bot released this 15 Nov 21:07
v2.6.2
aa2fabd

Release: v2.6.2 - Custom Export Conditions and Enhanced Developer Experience

🚀 CRITICAL FIX: EXPORT CONDITIONS MIGRATION - CONSUMER CONFLICT PREVENTION
• Migrate from standard development to custom slothlet-dev export conditions preventing conflicts with consuming applications using their own development configurations
• Resolve consumer module conflicts where slothlet's development mode would interfere with consumer applications' own development/production export condition logic
• Implement isolated development environment using slothlet-dev condition ensuring slothlet's internal development workflow doesn't affect consumer module resolution
• Maintain complete source/dist separation for slothlet development while providing clean production exports for consuming applications
• Establish precedent for library-specific export conditions preventing ecosystem-wide development mode conflicts

📚 MAJOR DOCUMENTATION OVERHAUL - AI AGENT INTEGRATION AND README IMPROVEMENTS
• NEW: AI Agent Usage Guide - Create comprehensive copilot-instructions.md providing detailed slothlet architecture guide specifically designed for AI-assisted development workflows
• README.md Major Updates - Fix broken Mermaid diagrams, update version references from outdated examples, correct runtime system documentation, and improve architectural explanations
• Document dual loading system (lazy/eager), AsyncLocalStorage context isolation, live-binding patterns, and file-to-API transformation logic for immediate developer understanding
• Provide condensed development guide focusing on critical architectural patterns, debugging workflows, JSDoc standards, and essential command sequences for AI agent productivity
• Establish clear methodology for AI agents to understand slothlet's module loader framework, performance characteristics, and development environment setup requirements

🔧 CI/TEST INFRASTRUCTURE ADAPTATION - VITEST EXPORT CONDITIONS SUPPORT
• Configure Vitest to handle custom slothlet-dev export conditions through dual-pipeline resolution (resolve.conditions + ssr.resolve.conditions)
• Resolve Vitest module resolution failures with self-importing packages using custom export conditions by explicitly configuring both main and SSR resolvers
• Add nodeOptions: ["--conditions=slothlet-dev"] ensuring Node.js process respects custom conditions alongside Vitest's bundler configuration
• Implement comprehensive test environment configuration preventing CI failures while maintaining development/production separation
• Bridge gap between Node.js native module resolution and Vite/Vitest bundler resolution for custom export conditions

🛡️ WORKFLOW CONSISTENCY AND ENVIRONMENT STANDARDIZATION
• Add test_environment input parameter to release workflow matching ci.yml configuration ensuring consistent test environment handling across all workflows
• Standardize environment configuration with slothlet-dev default across all development tooling preventing environment variable conflicts
• Maintain backward compatibility for existing development workflows while establishing isolated library development environment
• Preserve existing functionality for consumers while preventing development mode interference through custom export condition isolation
• Complete validation pipeline ensuring no regressions in API structure, builds, or TypeScript definitions under new export condition system

🏗️ EXPORT CONDITIONS ARCHITECTURE AND ECOSYSTEM COMPATIBILITY
• Document fundamental separation between library-internal development conditions (slothlet-dev) and consumer application conditions (development/production)
• Implement maintainable pattern for custom export conditions supporting both modern tooling requirements and Node.js native module resolution
• Establish clear precedent for library developers facing similar consumer conflicts with standard development export conditions
• Create comprehensive tooling configuration patterns for Vitest, Node.js, and other JavaScript ecosystem tools supporting custom export conditions
• Set foundation for sustainable library development practices preventing consumer environment interference

Technical Implementation:

  • Export conditions: Changed from development to slothlet-dev in package.json exports preventing consumer conflicts
  • Documentation: New copilot-instructions.md + comprehensive README.md updates with fixed diagrams and current version info
  • Vitest config: Dual-pipeline resolution with custom conditions (resolve.conditions + ssr.resolve.conditions)
  • Node integration: nodeOptions: ["--conditions=slothlet-dev"] + environment variables for complete compatibility
  • Workflow standardization: test_environment parameter across CI and release workflows with slothlet-dev default

Root Cause Analysis: Standard development export condition conflicts with consuming applications' own development configurations; libraries need isolated development environments to prevent consumer module resolution interference; modern tooling requires explicit configuration for custom export conditions.

Migration Strategy: Isolate library development through custom export conditions; adapt CI/test infrastructure to support custom conditions; maintain consumer compatibility through clean production exports; preserve all existing functionality while preventing environment conflicts.

Consumer Impact: Positive - eliminates development mode conflicts; consuming applications no longer affected by slothlet's internal development configuration; cleaner separation between library and consumer development environments; improved developer experience with comprehensive documentation.

Breaking Changes: None - fully backward compatible with enhanced consumer isolation
Performance Impact: Neutral - configuration changes only, no runtime modifications
Documentation Impact: Major - comprehensive AI agent integration guide and updated README with current information
Ecosystem Compatibility: Enhanced - prevents consumer conflicts while maintaining full tooling support

This release resolves critical consumer environment conflicts through custom export conditions while delivering major documentation improvements including dedicated AI agent usage guide and comprehensive README updates, establishing sustainable library development practices with enhanced developer experience.

v3.3.1

Choose a tag to compare

@cldmv-bot cldmv-bot released this 15 Nov 21:07
8c32dd9

Slothlet v3.3.1 Changelog

Release Date: April 26, 2026
Release Type: Patch
Branch: release/3.3.1


Overview

Version 3.3.1 is a bug-fix release that closes a silent failure when user code calls new on a Slothlet-proxied class export.

No breaking changes. All v3.3.0 configuration and API usage is fully compatible.


🐛 Bug Fixes

new on proxied class exports now works correctly

Before: Calling new api.someModule.MyClass(args) silently produced an empty plain object {}. The real constructor body never ran, no own properties were set, and the prototype chain was missing (methods were undefined). No error was thrown because JavaScript's [[Construct]] fallback constructs the empty stub function that Slothlet uses as a proxy target.

After: new api.someModule.MyClass(args) returns a fully constructed instance with all own properties set and the complete prototype chain intact.

Root cause

The Proxy handler assembled in UnifiedWrapper.createProxy() had no construct trap. Without one, new proxy(args) falls back to Reflect.construct(proxyTarget, args) where proxyTarget is an empty function(){} stub — the constructor body of the real class never runs.

Additionally, the newTarget argument must be the real impl function (not the proxy). Passing the proxy as newTarget routes newTarget.prototype through the getTrap, which returns a child wrapper instead of the real class prototype, breaking the prototype chain even when the constructor body ran.

What changed

A constructTrap was added to the proxy handler in src/lib/handlers/unified-wrapper.mjs:

  • Eager mode / already-materialized: delegates directly via Reflect.construct(impl, args, impl).
  • Lazy mode, in-flight: the trap returns a Promise so callers can await new api.MyClass(args) and receive the real instance once materialization completes.
  • Lazy mode, not yet materialized: fires _materialize() then enters the in-flight path above.
  • Non-callable impl: throws INVALID_CONFIG_NOT_A_FUNCTION, consistent with applyTrap.

The constructed instance is returned unwrapped — no re-proxying — so private class fields (stored in per-instance WeakMaps keyed on the raw instance) continue to work correctly.

Example

// api/adapters/openai-backend.mjs
export class OpenAIBackendAdapter {
	#token;
	constructor(config) {
		this.model = config.model;
		this.#token = config.token;
	}
	listModels() {
		return ["gpt-4o"];
	}
}

// Consumer (eager mode)
const adapter = new api.adapters.openaiBackend.OpenAIBackendAdapter({ model: "gpt-4o", token: "sk-..." });
console.log(adapter.model); // "gpt-4o"   ← was {} before
console.log(adapter.listModels()); // ["gpt-4o"] ← was TypeError before

// Consumer (lazy mode — await the constructor call)
const adapter = await new api.adapters.openaiBackend.OpenAIBackendAdapter({ model: "gpt-4o", token: "sk-..." });

🧪 Tests

  • Added api_tests/api_test/classes.mjs — fixture with Counter (own properties + prototype methods) and Secrets (private field via #token).
  • Added tests/vitests/suites/handlers/unified-wrapper-construct-trap.test.vitest.mjs — 40 tests across all 8 matrix configurations (eager × 4, lazy × 4) covering:
    • Constructor body execution (own property set)
    • Prototype chain preservation (methods callable)
    • Instance identity (not.toEqual({}))
    • Private class field correctness (no re-proxy)
    • Prototype consistency across multiple new calls

v3.2.2

Choose a tag to compare

@cldmv-bot cldmv-bot released this 15 Nov 21:07
a979e8f

Slothlet v3.2.2 Changelog

Release Date: April 12, 2026
Release Type: Patch
Branch: release/3.2.2


Overview

Version 3.2.2 is a patch release that adds a missing set trap to the version dispatcher proxy introduced in v3.2.0. Without the trap, plain property assignment of the form self.versionedPath.prop = value would throw a TypeError: Cannot redefine property in strict mode — even on the very first write. This made it impossible for any versioned module to store runtime state (e.g. a database client, a connected socket) on a versioned API path via the dispatcher.

No public API or configuration changes. All v3.2.0 and v3.2.1 usage is fully compatible.


🐛 Bug Fixes

Dispatcher Proxy: Missing set Trap

Problem: The version dispatcher proxy had no set trap. Without it, JavaScript's engine uses the default [[Set]] path (OrdinarySetWithOwnDescriptor), which consults [[GetOwnProperty]] on the receiver (the dispatcher proxy itself) before writing. The dispatcher's getOwnPropertyDescriptor trap returns { writable: false } for every unknown property — a deliberate choice to avoid prematurely invoking version resolution during property enumeration. As a result, the default [[Set]] sees writable: false and throws TypeError: Cannot redefine property: <prop> in strict mode before the value is ever written.

Impact: Any module that stored runtime state on a versioned API path through the dispatcher — e.g.:

// inside a versioned module using self
self.cache.redisClient = client;
self.db.connection = pool;

would crash with TypeError: Cannot redefine property, leaving the module in a broken half-initialized state. The direct versioned path (self.v1.cache.redisClient = client) worked correctly because it hits UnifiedWrapper directly, bypassing the dispatcher.

Fix: Added a set trap to createDispatcher() that delegates via Reflect.set(vw, prop, value, vw) to the real versioned wrapper's own setTrap. UnifiedWrapper.setTrap performs the correct delete → Object.defineProperty(configurable: true) cycle, keeping properties perpetually reassignable.

The trap also guards against writes to keys where the get trap returns fixed values rather than delegating to the versioned wrapper (framework internals, stable accessors, well-known string props such as toString/valueOf/toJSON/then, and all symbols). Forwarding writes for those keys to the versioned wrapper would create invisible hidden state — the write appears to succeed but is never observable through the dispatcher's get trap. Those writes are silently absorbed (return true) to keep set/get behaviour consistent.

Keys absorbed (not forwarded to versioned wrapper):

  • Framework internals: ____slothletInternal, _impl, __impl, __state, __invalid
  • Stable framework accessors: __isVersionDispatcher, __mode, __apiPath, __slothletPath, __isCallable, __materializeOnCreate, __materialized, __inFlight, __displayName, __moduleID, _materialize, length, name
  • Structural / thenable props: then, constructor, toString, valueOf, toJSON
  • All symbols (including Symbol.toStringTag — UnifiedWrapper computes it dynamically on reads, so forwarding writes would create unobservable hidden state)

Keys forwarded to versioned wrapper (get delegates to vw): __metadata, __filePath, __sourceFolder, __type, and all user-defined string properties.


🧪 Tests

New Suite: versioning-dispatcher-set.test.vitest.mjs

Added 9 test cases (72 total across the full matrix) covering:

  • First assignment through dispatcher does not throw
  • Assigned value is readable back through the dispatcher
  • Value is stored on the versioned wrapper, not the dispatcher target
  • Repeated assignment (reassignment cycle) does not throw
  • Multiple distinct properties can be assigned
  • Assignment routes to the active default version when two versions exist
  • Writes to framework accessor keys are silently absorbed without throwing and without changing what get returns
  • Writes to symbol keys are silently absorbed and do not appear on the versioned wrapper
  • Absorbed writes do not pollute the versioned wrapper

📦 Files Changed

File Change
src/lib/handlers/version-manager.mjs Added set trap to the dispatcher proxy; absorbs special-case keys; delegates user-defined string props to the versioned wrapper via Reflect.set(vw, prop, value, vw); full JSDoc
tests/vitests/suites/versioning/versioning-dispatcher-set.test.vitest.mjs New test suite: 9 cases covering the set trap fix and special-case key absorption
types/src/lib/handlers/version-manager.d.mts.map Regenerated type declaration sourcemap

🔄 Upgrade from v3.2.1

No changes required. Install the update:

npm install @cldmv/[email protected]

All v3.2.0 and v3.2.1 configuration and API usage is fully compatible.


v2.0.0

Choose a tag to compare

@cldmv-bot cldmv-bot released this 27 Dec 03:07
v2.0.0
d80ba87

🚀 What's Changed

💥 Breaking Changes

No breaking changes

✨ Features

No new features

🐛 Bug Fixes

No bug fixes

🔧 Other Changes

No other changes

📦 Installation

@cldmv/[email protected]
npm install @cldmv/[email protected]

@cldmv/slothlet-types v3.24.0

Choose a tag to compare

@cldmv-bot cldmv-bot released this 02 Nov 12:38
cd60a74

Part of @cldmv/slothlet v3.24.0 — built from the same commit and published at the same version.