r/javascript • • Apr 13 '26

I built a virtual-scroll custom element that behaves like a normal scroll container

Thumbnail joshuaamaju.com
4 Upvotes

Iโ€™ve been working on aย virtual-scrollย custom element that tries to keep virtualization feeling close to normal HTML and CSS.

The main goal was to avoid the usual trade-offs where virtualization forces you into absolute positioning, framework-specific APIs, or awkward layout constraints.


r/javascript • • Apr 13 '26

Agentic harness in 30 lines of JavaScript

Thumbnail github.com
0 Upvotes

what is this?

After seeing a recent video from Theo, I wanted to see how far I can take a harness contained in just 30 lines of JavaScript. Turns out - far enough to be useful, it handles simple tasks just fine, works with both cloud and local models, uses just three tools (but can do with a single one, frankly speaking), cleanly handles detached commands or cancellation mid-run, has non-interactive mode and can be run with NPX.

what makes a harness

an agentic harness is surprisingly simple. it's a loop that calls an llm, checks if it wants to use tools, executes them, feeds results back, and repeats. here's how each part works.

tools

the agent needs to affect the outside world. tools are just functions that take structured args and return a string. three tools is enough for a general-purpose coding agent:

const tools = {
  bash: ({ command }) => execShell(command),    // run any shell command
  read:  ({ path }) => readFileSync(path, 'utf8'),  // read a file
  write: ({ path, content }) => (writeFileSync(path, content), 'ok'), // write a file
};

bash gives the agent access to the entire system: git, curl, compilers, package managers. read and write handle files. every tool returns a string because that's what goes back into the conversation.

tool definitions

the llm doesn't see your functions. it sees json schemas that describe what tools are available and what arguments they accept:

const defs = [
  { name: 'bash',  description: 'run bash cmd', parameters: mkp('command') },
  { name: 'read',  description: 'read a file',  parameters: mkp('path') },
  { name: 'write', description: 'write a file', parameters: mkp('path', 'content') },
].map(f => ({ type: 'function', function: f }));

mkp is a helper that builds a json schema object from a list of key names. each key becomes a required string property. the defs array is sent along with every api call so the model knows what it can do.

messages

the conversation is a flat array of message objects. each message has a role (system, user, assistant, or tool) and content. this array is the agent's entire memory:

const hist = [{ role: 'system', content: SYSTEM }];

// user says something
hist.push({ role: 'user', content: 'fix the bug in server.js' });

// assistant replies (pushed inside the loop)
// tool results get pushed too (role: 'tool')

the system message sets the agent's personality and context (working directory, date). every user message, assistant response, and tool result gets appended. the model sees the full history on each call, which is how it maintains context across multiple tool uses.

the api call

each iteration makes a single call to the chat completions endpoint. the model receives the full message history and the tool definitions:

const r = await fetch(`${base}/v1/chat/completions`, {
  method: 'POST',
  headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${key}` },
  body: JSON.stringify({ model, messages: msgs, tools: defs }),
}).then(r => r.json());
const msg = r.choices[0].message;

the response message either has content (a text reply to the user) or tool_calls (the model wants to use tools). this is the decision point that drives the whole loop.

the agentic loop

this is the core of the harness. it's a while (true) that keeps calling the llm until it responds with text instead of tool calls:

async function run(msgs) {
  while (true) {
    const msg = await callLLM(msgs);  // make the api call
    msgs.push(msg);                   // add assistant response to history
    if (!msg.tool_calls) return msg.content;  // no tools? we're done
    // otherwise, execute tools and continue...
  }
}

the loop exits only when the model decides it has enough information to respond directly. the model might call tools once or twenty times, it drives its own execution. this is what makes it agentic: the llm decides when it's done, not the code.

tool execution

when the model returns tool_calls, the harness executes each one and pushes the result back into the message history as a tool message:

for (const t of msg.tool_calls) {
  const { name } = t.function;
  const args = JSON.parse(t.function.arguments);
  const result = String(await tools[name](args));
  msgs.push({ role: 'tool', tool_call_id: t.id, content: result });
}

each tool result is tagged with the tool_call_id so the model knows which call it corresponds to. after all tool results are pushed, the loop goes back to the top and calls the llm again, now with the tool outputs in context.

the repl

the outer shell is a simple read-eval-print loop. it reads user input, pushes it as a user message, calls run(), and prints the result:

while (true) {
  const input = await ask('\n> ');
  if (input.trim()) {
    hist.push({ role: 'user', content: input });
    console.log(await run(hist));
  }
}

there's also a one-shot mode (-p 'prompt') that skips the repl and exits after a single run. both modes use the same run() function. the agentic loop doesn't care where the prompt came from.

putting it together

the full flow looks like this:

user prompt โ†’ [system, user] โ†’ llm โ†’ tool_calls? โ†’ execute tools โ†’ [tool results] โ†’ llm โ†’ ... โ†’ text response

more sophisticated agents add things like memory, retries, parallel tool calls, or multi-agent delegation, but the core is always: loop, call, check for tools, execute, repeat.

source: https://github.com/av/mi


r/javascript • • Apr 13 '26

Open-source Playwright tool that auto-tests UI flows without writing test scripts

Thumbnail cynchrolabs.com.ar
0 Upvotes

Hey all,

I built a tool called AgenTester that automatically tests a web appโ€™s UI/UX.

You just paste a URL and it:

Crawls the app

Tests CRUD flows (create/edit/delete)

Checks navigation, filters, pagination, buttons

Detects JS errors and failed network requests

Streams screenshots in real time

Generates a full HTML report with a quality score

No test scripts, no manual setup โ€” just run it and see what breaks.

Itโ€™s fully open-source and runs with Docker or Node.js.

Iโ€™d really appreciate feedback


r/javascript • • Apr 13 '26

The native scrollIntoView({ behavior: 'smooth' }) has no callback. You can't know when it finishes. This tiny wrapper returns a Promise that resolves when the scroll is done.

Thumbnail everythingfrontend.com
0 Upvotes
  • Promise-basedย โ€”ย awaitย the native smooth scroll, run code when it finishes
  • Zero dependenciesย โ€” pure TypeScript, no external packages
  • Uses the native APIย โ€” callsย element.scrollIntoView()ย under the hood, not a custom scroll implementation
  • Scroll-idle detectionย โ€” resolves by listening for scroll-end on all scrollable ancestors
  • Timeout safety netย โ€” never hangs; resolves after a configurable timeout (default 3s)
  • AbortController supportย โ€” cancel a pending scroll withย signal
  • Handles nested scrollingย โ€” detects all scrollable parent containers automatically
  • Instant fallbackย โ€” ifย behavior: 'instant'ย or smooth scroll is unsupported, resolves immediately
  • SSR safeย โ€” guards DOM access; safe to import in Node/SSR environments
  • ~0.6kB minified + gzipped

r/javascript • • Apr 12 '26

terminal-element: Terminal interface as Web Component

Thumbnail github.com
9 Upvotes

Built a terminal style interface as Web Component. Didn't think about how useful it is that much, but I often see this type of preview here and there so I thought it might be worth creating it.

Any feedback would be appreciated.


r/javascript • • Apr 13 '26

I built an AI CLI tool that analyzes your project and generates a beautiful README automatically

Thumbnail github.com
0 Upvotes

r/javascript • • Apr 13 '26

You can't cancel a JavaScript promise (except sometimes you can)

Thumbnail inngest.com
0 Upvotes

r/javascript • • Apr 12 '26

Release Re2js v2 - A pure JS RegExp engine that defeats ReDoS

Thumbnail re2js.leopard.in.ua
16 Upvotes

I'm excited to share the v2 release of re2js, a pure JavaScript port of the RE2 regular expression engine.

JavaScript's native RegExp uses a backtracking strategy, which is heavily vulnerable to Regular Expression Denial of Service (ReDoS). re2js fixes this by evaluating matches in strict linear $O(N)$ time, making catastrophic backtracking mathematically impossible.

The biggest news in v2 is the performance. Because pure JS avoids the cross-boundary serialization costs (the N-API bridge) between JavaScript and C++, re2js actually outperforms native C++ bindings (re2-node) for many operations!

๐Ÿ“Š Check out the benchmark comparisons here: RE2JS vs RE2-Node (C++ Bindings)

How does it beat C++? The Multi-Tiered Architecture

To achieve this, I ported the deepest performance architectures from the original C++ and Go implementations to dynamically route execution through a multi-tiered pipeline:

  • The Prefilter Engine & Literal Fast-Path: The engine analyzes the Abstract Syntax Tree (AST) before execution to extract mandatory string literals (e.g., extracting "error" from /error.*critical/). It then uses blistering-fast native JavaScript indexOf to instantly reject mismatches, completely bypassing the regex state-machines (making simple literal searches ~2.4x faster than C++).
  • Lazy Powerset DFA: Executes high-speed boolean .test() matches by fusing active states dynamically on the fly within V8's JIT compiler.
  • OnePass DFA: Provides high-speed capture group extraction for mathematically 1-unambiguous patterns by bypassing thread queues entirely.
  • Multi-Pattern Sets (RE2Set): Combines hundreds or thousands of regular expressions into a single combined DFA, allowing you to search a string for all patterns simultaneously in a single linear-time pass.
  • BitState Backtracker & Pike VM (NFA): Act as the robust, bounded-memory fallback engines for complex or ambiguous patterns that exceed the fast-path limits.

Keeping the Bundle Tiny: Base64 VLQ Delta Compression

Supporting full Unicode properties (like \p{Greek} or \p{Sm}) usually bloats JS regex engines with massive lookup tables.

To solve this, re2js v2 implements a custom Base64 Variable-Length Quantity (VLQ) delta compression algorithm for the Unicode range mappings (inspired from source maps spec). This shrinks thousands of codepoint ranges into tiny, dense string representations (e.g., hCZBHZBwBLLFGGBV...). This keeps the library incredibly lightweight while supporting full, standard-compliant Unicode category matching.

Try it out!

You can play around with the engine directly in your browser here: re2js Playground

Feedback and PRs are always welcome.


r/javascript • • Apr 11 '26

I built an open-source WYSIWYG editor in vanilla JavaScript (no frameworks, CDN-ready)

Thumbnail neiki.eu
32 Upvotes

r/javascript • • Apr 13 '26

AskJS [AskJS] Different Code, Same Function

0 Upvotes

Code 1:

var count = 0;

while (count < 5) {
  count++
  console.log("Hello!");
}

Code 2:

for (var count = 0; count < 5; count++) {
  console.log("Hello!");
}

Console log results for both codes:

"Hello!"
"Hello!"
"Hello!"
"Hello!"
"Hello!"

r/javascript • • Apr 11 '26

cargo-npm: Distribute Rust CLIs via npm without postinstall scripts

Thumbnail github.com
12 Upvotes

I recently built cargo-npm, a tool that packages and distributes Rust binaries directly to the npm registry.

Why another distribution tool?

While tools like cargo-dist are excellent for general release engineering, their npm installers typically rely on postinstall scripts to download pre-compiled binaries from external sources like GitHub Releases at install time. I wanted a solution that works natively within the npm ecosystem without requiring lifecycle scripts.

Relying on npm's dependency graph rather than postinstall scripts provides several architectural advantages:

  • It respects --ignore-scripts, which is increasingly enforced in corporate and CI environments for security reasons (it's also the default on pnpm).
  • It prevents installation failures caused by strict firewalls or proxies blocking GitHub Releases downloads.
  • It utilizes npm's native caching mechanisms, speeding up repeated installations.

How it works

Instead of fetching binaries at runtime, cargo-npm takes your compiled targets and generates individual, platform-specific npm packages (e.g., my-tool-linux-x64). Each of these packages contains the actual binary and uses os, cpu and libc constraints in its package.json.

It then generates a main package that users install. This main package lists the platform packages as optionalDependencies. When a user runs npm install my-tool, npm's native resolution ensures it only downloads the binary that matches the host system. A lightweight Node.js shim in the main package resolves the matching binary and executes it.

Usage

You cross-compile your Rust crate for your desired targets, and then run cargo npm generate followed by cargo npm publish. The tool handles the package generation, metadata forwarding, and parallel publishing.

You can view the documentation and source code here: https://github.com/abemedia/cargo-npm.

Feedback is welcome!


r/javascript • • Apr 11 '26

Showoff Saturday Showoff Saturday (April 11, 2026)

2 Upvotes

Did you find or create something cool this week in javascript?

Show us here!


r/javascript • • Apr 11 '26

How we made the Angular Compiler 10x faster using Rust and AI

Thumbnail voidzero.dev
0 Upvotes

r/javascript • • Apr 11 '26

We transpiled PHPUnit (54k lines, 412 files) to JavaScript. 61.3% of tests passing

Thumbnail pext.dev
0 Upvotes

r/javascript • • Apr 11 '26

[AskJS] Do you believe you're a better critical thinker than GPT 5.4 / Opus 4.6?

0 Upvotes

r/javascript • • Apr 10 '26

Zero-build privacy policies with Astro

Thumbnail openpolicy.sh
3 Upvotes

We've just made it even easier to build privacy policies from code. No Vite plugin required.


r/javascript • • Apr 09 '26

styled-components 6.4 now available

Thumbnail github.com
34 Upvotes

There's a lot of great stuff in this release! In no particular order:

  • RSC implementation promoted from experimental
  • More intelligent caching + real algorithmic speed improvements (up to 3.5x depending on workload)
  • React Native improvements (css-to-react-native v4 now supported via peer when it's out)
  • Updated cross-framework CSP support
  • A seamless Client/RSC theme system via new createTheme() API
  • attrs() typing improvements and other quality-of-life changes

Feedback welcome, especially ideas for the next major. Documentation website refresh coming later this week!


r/javascript • • Apr 10 '26

ffetch 5.1.0 adds opt-in request and response shortcuts

Thumbnail github.com
5 Upvotes

Shipped ffetch 5.1.0.

ffetch is a lightweight, production-ready HTTP client that wraps native fetch with built-in timeouts, retries with exponential backoff, lifecycle hooks, and pending request tracking. Works across browsers, Node, SSR, and edge runtimes.

New in v5.1.0: two opt-in convenience plugins.

Usage:

import { createClient } from '@fetchkit/ffetch'
import { requestShortcutsPlugin } from '@fetchkit/ffetch/plugins/request-shortcuts'
import { responseShortcutsPlugin } from '@fetchkit/ffetch/plugins/response-shortcuts'

const api = createClient({
  timeout: 10000,
  retries: 3,
  retryDelay: (ctx) => Math.pow(2, ctx.attempt - 1) * 1000 + Math.random() * 1000,
  plugins: [requestShortcutsPlugin(), responseShortcutsPlugin()],
})

const todo = await api.get('/todos/1').json()

Exponential backoff with jitter: each retry waits 2^(attempt-1) seconds plus random jitter, with timeout of 10s and max 3 retries. Plugins are optional, default behavior stays fetch-compatible.


r/javascript • • Apr 10 '26

Decorating a Promise with convenience methods without subclassing or changing what await returns

Thumbnail blog.gaborkoos.com
0 Upvotes

r/javascript • • Apr 09 '26

AskJS [AskJS] Is it just me or is debugging memory leaks in Node/V8 way worse than it used to be?

6 Upvotes

We recently upgraded our backend (late) from Node 20 to Node 24. About a week later, alarms went off when our app stopped responding; memory usage graphs looked like an obvious leak but it hadn't OOMed and restarted tasks despite --max-old-space-size limits.

I started trying to compare heap snapshots taken at different times but it seems like a mess now. Even if I run a simple setInterval(() => console.log('test')) program with Node 24.14.1 and periodically take heap snapshots, they show a slight increase over time in (compiled code) instances and system code related to timers.

I can't even tell if these increases are permanent or not. The few timer objects that increased between snapshots were only retained by feedback_cells and other internal things that I read aren't truly forcing them to be retained...V8 just doesn't guarantee those will get garbage collected immediately or on a global.gc().

And all of this irrelevant noise from feedback_cells and other internals seems rampant in the heap snapshots now, making it more time consuming to locate actual retainers from my own code.

I don't remember it always being this bad?

I've successfully debugged several other memory leaks in older versions of node, including really heady ones involving Promise.race() and async generators, but now I'm feeling powerless and shafted by recent changes to V8.

Has this been anyone else's experience?


r/javascript • • Apr 10 '26

AskJS [AskJS] Anyone else found Math.random() flagged in a security audit? How did you handle the remediation?

0 Upvotes

Security audit came back with a finding on credential generation.

Math.random() in several services, flagged for NIST 800-63B

non-compliance. The entropy requirements weren't being met and

more importantly there was no documentation proving they were.

We fixed the generation method but the audit documentation piece

is what actually took the most time. Had to go back and document

everything retroactively.

Curious what others are doing here. Are you generating compliance

documentation automatically as part of your pipeline or is this

a manual process at your organization?


r/javascript • • Apr 09 '26

Render tsx on an e-ink display

Thumbnail github.com
5 Upvotes

Hey everyone! I wanted to show a small project I've been working on; a tsx framework for rendering to an e-ink display (or tsx => canvas => image => eink to be honest).

<view direction="column" gap={20} padding={40}>  
  <text size={48} weight="bold">Hello World</text>  
  <ElectricityConsumption />  
</view>

Instead of the "common" approach of running headless Chrome and taking screenshots, this renders jsx components directly using a Yoga flexbox layout engine and a canvas. So the render is quite fast.

I also think its nice to get full type safety, snapshot testing for visual regression, and you can easily develop locally (renders to a PNG) without needing the hardware connected.

I use mine in the kitchen dashboard showing:

  • Laundry machine status (in the basement)
  • Our weekly meal plan
  • Electricity prices + power consumption
  • Weather forecast
  • Home Assistant device status via MQTT

It also has a physical button that starts the engine heater for our car, plus an led showing its state of the engine heater.

The code is open source: https://github.com/tjoskar/eink-pi-zero
And a short write-up about the build: https://tjoskar.dev/posts/2025-11-02-eink-pi/ (yes the post is a few months old now but in my first version did I use python to render everything but I really missed the typesafty, and tsx components over absolut position everything in python. But the the post is the same)

Happy to answer questions if anyone wants to build something similar!


r/javascript • • Apr 09 '26

The Intl API: The best browser API you're not using

Thumbnail polypane.app
46 Upvotes

r/javascript • • Apr 08 '26

How attackers are hiding malicious code in build configs

Thumbnail casco.com
57 Upvotes

wrote up a technical deep dive after the Better-Auth creator showed me the repeated attempts.

The attack vector is clever: wrap malicious code in a legitimate PR from a compromised contributor. Hide it in next.config.mjs or vue.config.js where devs rarely look. GitHub's UI literally scrolls it off-screen.

Three-stage obfuscation, payloads stored on Binance Smart Chain (so they can't be taken down), Socket.io C2 over port 80 (looks like normal traffic), targets all your env vars.

Found 30+ repos with the same signature. This pattern is everywhere right now.