<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Rogerio Amorim on Medium]]></title>
        <description><![CDATA[Stories by Rogerio Amorim on Medium]]></description>
        <link>https://medium.com/@rogeriol?source=rss-82244dfb6a6a------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*PuVtgIUFe06rNjB6.</url>
            <title>Stories by Rogerio Amorim on Medium</title>
            <link>https://medium.com/@rogeriol?source=rss-82244dfb6a6a------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 22 Nov 2026 09:50:31 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@rogeriol/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com" rel="hub"/>
        <item>
            <title><![CDATA[AI Coding Agents Aren’t Magic. I Rebuilt One From Scratch in 3,292 Lines.]]></title>
            <link>https://javascript.plainenglish.io/ai-coding-agents-arent-magic-i-rebuilt-one-from-scratch-in-3-292-lines-5162a368e64d?source=rss-82244dfb6a6a------2</link>
            <guid isPermaLink="false">https://medium.com/p/5162a368e64d</guid>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[harness]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Rogerio Amorim]]></dc:creator>
            <pubDate>Mon, 09 Nov 2026 14:54:14 GMT</pubDate>
            <atom:updated>2026-11-09T14:54:14.263Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aDGIFGyyTx1nH5QPLQ4gvQ.png" /></figure><blockquote><em>I wanted to understand what actually happens between “you” and “the model.” So I threw away every abstraction, wrote the agent loop by hand, and read every line until it made sense.</em></blockquote><p>Let me guess what your day looks like.</p><ol><li>You open your AI editor.</li><li>You describe a task in English.</li><li>The model writes code.</li><li>You read the diff, frown, and fix the same thing by hand.</li><li>You do it again next week, with a slightly different prompt.</li></ol><p>Sound familiar?</p><p>Here’s the thing nobody tells you: <strong>the hard part was never the model.</strong> It was always the <em>loop</em> — the boring, invisible machinery that decides what the model can see, what it can touch, and what happens when it breaks.</p><p>Most AI coding tools hide that loop inside 50,000 lines of framework. I got tired of not knowing.</p><p>So I did something unreasonable: <strong>I wrote the entire agent from scratch, in plain TypeScript, with zero runtime dependencies.</strong> Then I read every single line until I could explain it in my sleep.</p><p><strong>Result: 3,292 lines of source. No dependencies. No build step. One file you can read in a coffee break.</strong></p><p>And in the process, I found something that changed how I think about AI agents forever.</p><h3>The moment that broke my brain 🤯</h3><p>Here is the <em>entire</em> agent loop. This is src/agent.ts, the heart of the project — with the event bookkeeping (usage tracking, this.emit(...) calls, the try/catch) elided for readability:</p><pre>for (let step = 1; step &lt;= maxSteps; step++) {<br>  let text = &quot;&quot;;<br>  const toolCalls: ToolCall[] = [];<br>  for await (const event of this.currentProvider.chat({<br>    system: this.opts.systemPrompt,<br>    messages: this.messages,<br>    tools: this.opts.tools.specs(),<br>    signal,<br>  })) {<br>    switch (event.type) {<br>      case &quot;text&quot;:<br>        text += event.text;<br>        break;<br>      case &quot;tool_call&quot;:<br>        toolCalls.push(event.toolCall);<br>        break;<br>    }<br>  }<br>  this.messages.push({ role: &quot;assistant&quot;, content: text, toolCalls });<br>  // No tools requested =&gt; the model is done.<br>  if (toolCalls.length === 0) {<br>    this.emit({ type: &quot;done&quot;, text, steps: step });<br>    return text;<br>  }<br>  // Execute every requested tool and feed the results back into history.<br>  //<br>  // Two details worth noting:<br>  //  - approvals are resolved first, one at a time, because the CLI asks<br>  //    the user a question and a prompt can&#39;t be interleaved.<br>  //  - the approved calls then run concurrently, but the results are<br>  //    appended in the order the model requested them. Providers expect<br>  //    tool results to line up with their tool calls.<br>  const decisions: Array&lt;ToolApproval | undefined&gt; = [];<br>  for (const toolCall of toolCalls) {<br>    decisions.push(await this.approve(toolCall));<br>  }<br>  const outcomes = await Promise.all(<br>    toolCalls.map(async (toolCall, index) =&gt; {<br>      const decision = decisions[index];<br>      if (decision &amp;&amp; !decision.approved) {<br>        const reason = decision.reason ?? &quot;The user denied this tool call.&quot;;<br>        return {<br>          toolCall,<br>          result: { content: reason, isError: true } satisfies ToolResult,<br>          rejected: true,<br>          reason,<br>        };<br>      }<br>      const result = await this.opts.tools.execute(<br>        toolCall.name,<br>        toolCall.arguments,<br>        { ...this.opts.toolContext, signal },<br>      );<br>      return { toolCall, result, rejected: false, reason: undefined };<br>    }),<br>  );<br>  for (const outcome of outcomes) {<br>    this.messages.push({<br>      role: &quot;tool&quot;,<br>      toolCallId: outcome.toolCall.id,<br>      toolName: outcome.toolCall.name,<br>      content: outcome.result.content,<br>      isError: outcome.result.isError,<br>    });<br>  }<br>}</pre><p>That’s it. <strong>That’s the whole thing.</strong></p><p>Read it again. It’s four moves:</p><ol><li><strong>Ask the model</strong> what it wants to do.</li><li><strong>Append its answer</strong> to the conversation history.</li><li><strong>No tools? Done.</strong> (the model is finished talking)</li><li><strong>Tools? Run them, append the results, go back to 1.</strong></li></ol><p>Everything else in every AI coding tool — the “agent framework,” the “orchestration layer,” the “multi-agent coordinator” — is <em>plumbing wrapped around these four moves</em>.</p><p>And here’s the part that made me stop and stare:</p><blockquote><strong><em>The history IS the state.</em></strong></blockquote><p>There is no hidden context object. No separate scratchpad. No “agent memory” database. The entire state of the agent is one array of messages, and it grows by exactly two operations: append the assistant’s turn, append the tool results.</p><p>The model doesn’t have memory. <em>The history is its memory.</em> Every tool result becomes part of the conversation it will read next turn.</p><pre>this.messages.push({<br>  role: &quot;tool&quot;,<br>  toolCallId: outcome.toolCall.id,<br>  toolName: outcome.toolCall.name,<br>  content: outcome.result.content,<br>});<br>//     ↑ this push IS the agent&#39;s memory. That&#39;s the whole trick.</pre><p>If you understand that one push, you understand agents.</p><h3>The dirty secret: your AI tool talks to you through a translator</h3><p>Here’s the hot take that’ll get me yelled at in the comments (please, yell — engagement is engagement):</p><p><strong>An AI coding agent doesn’t “use tools.” It asks a model to <em>write a JSON function call</em>, and then runs whatever function that JSON names.</strong></p><p>The model doesn’t execute anything. It can’t. It just emits text that <em>looks like</em> a function call:</p><pre>{<br>  &quot;id&quot;: &quot;call_abc123&quot;,<br>  &quot;name&quot;: &quot;read_file&quot;,<br>  &quot;arguments&quot;: { &quot;path&quot;: &quot;src/agent.ts&quot; }<br>}</pre><p>That’s a ToolCall — id, name, arguments. Your harness — not the model — is what decides this is allowed, finds the function, runs it, and feeds the output back.</p><p><strong>This is why AI agents fail in ways that regular programs don’t.</strong> When a model hallucinates a function name, the failure is <em>ours</em> to handle gracefully. When it hallucinates a file path, <em>we</em> have to catch it.</p><p>Now here’s the part that scales. OpenAI, Anthropic, Ollama, LM Studio, vLLM, Groq, OpenRouter — they all speak different wire formats. Anthropic sends system as a <strong>top-level field</strong>. OpenAI puts it in a messages array. Anthropic sends tool results as a <strong>user message</strong>. OpenAI uses role: &quot;tool&quot;.</p><p>So every agent framework has to solve the same problem: <strong>how do you keep the loop identical while the wire format changes underneath?</strong></p><p>The answer I landed on is a <em>normalized message type</em>. One shape. The loop only ever sees this:</p><pre>export type Message =<br>  | { role: &quot;system&quot;; content: string }<br>  | { role: &quot;user&quot;; content: string }<br>  | { role: &quot;assistant&quot;; content: string; toolCalls: ToolCall[] }<br>  | {<br>      role: &quot;tool&quot;;<br>      toolCallId: string;<br>      toolName: string;<br>      content: string;<br>      isError?: boolean;<br>    };</pre><p>Then each adapter translates at the boundary. OpenAI’s adapter:</p><pre>case &quot;tool&quot;:<br>  out.push({<br>    role: &quot;tool&quot;,<br>    tool_call_id: message.toolCallId,<br>    content: message.content,<br>  });<br>  break;</pre><p>Anthropic’s adapter — same normalized message, completely different wire format:</p><pre>// Tool results must be sent as a user message containing tool_result blocks.<br>// Consecutive results are merged into a single user turn.<br>const block = {<br>  type: &quot;tool_result&quot;,<br>  tool_use_id: message.toolCallId,<br>  content: message.content,<br>  is_error: message.isError ?? false,<br>};</pre><p><strong>Same input. Same output. Same loop. Two totally different APIs.</strong></p><p>That’s the seam. And once you see it, you realize: <em>adding a provider is a translation problem, not an architecture problem.</em> You write two functions — toOpenAIMessages() and toAnthropicMessages() — and the agent doesn&#39;t notice.</p><h3>Trick #1: the tool registry is 77 lines and that’s all it needs</h3><p>Here’s the entire contract between “what the model can see” and “what the harness can run”:</p><pre>export interface Tool {<br>  spec: ToolSpec;<br>  run(args: Record&lt;string, unknown&gt;, ctx: ToolContext): Promise&lt;ToolResult&gt;;<br>}</pre><p>Two halves. A <strong>spec</strong> (what the model sees) and a <strong>run</strong> (what actually happens). That’s it.</p><p>Want to add a tool? Here’s a real one from the project — grep_files. The spec is verbatim; I&#39;ve elided the body of run (it walks the workspace, greps, and formats path:line: text matches):</p><pre>export const grepFilesTool: Tool = {<br>  spec: {<br>    name: &quot;grep_files&quot;,<br>    description:<br>      &quot;Search file contents with a regular expression. Returns `path:line: text` matches. Useful for finding symbols.&quot;,<br>    parameters: {<br>      type: &quot;object&quot;,<br>      properties: {<br>        pattern: { type: &quot;string&quot;, description: &quot;JavaScript regular expression.&quot; },<br>        path: { type: &quot;string&quot;, description: &quot;Directory to search from. Default &#39;.&#39;.&quot; },<br>        glob: { type: &quot;string&quot;, description: &quot;Optional glob to limit files, e.g. &#39;**/*.ts&#39;.&quot; },<br>        max_results: { type: &quot;number&quot;, description: &quot;Maximum matches. Default 100.&quot; },<br>      },<br>      required: [&quot;pattern&quot;],<br>    },<br>  },<br>  async run(args, ctx) {<br>    // ...walks the workspace, greps, returns `path:line: text` matches<br>    return { content: results.join(&quot;\n&quot;) };<br>  },<br>};</pre><p><strong>That’s the whole shape of a tool.</strong> The model now knows grep_files exists, knows its arguments, and the harness knows how to run it.</p><p>Two properties I love about this design:</p><p><strong>1. The model never runs code.</strong> It requests. You decide. This is the entire security model, and it fits in one sentence.</p><p><strong>2. The spec <em>is</em> the documentation.</strong> The description and JSON Schema are sent to the model verbatim. There is no separate docstring to drift out of sync, because there is no separate docstring.</p><p>And the registry itself? 77 lines, and here’s the entire dispatch:</p><pre>async execute(<br>  name: string,<br>  args: Record&lt;string, unknown&gt;,<br>  ctx: ToolContext,<br>): Promise&lt;ToolResult&gt; {<br>  const tool = this.tools.get(name);<br>  if (!tool) {<br>    return {<br>      content: `Unknown tool &quot;${name}&quot;. Available tools: ${this.names().join(&quot;, &quot;)}`,<br>      isError: true,<br>    };<br>  }<br>  try {<br>    return capOutput(await tool.run(args, ctx));<br>  } catch (err) {<br>    return {<br>      content: `Tool &quot;${name}&quot; failed: ${err instanceof Error ? err.message : String(err)}`,<br>      isError: true,<br>    };<br>  }<br>}</pre><p>Look at the error handling. <strong>A crashing tool does not crash the agent.</strong> It becomes a <em>message to the model</em>.</p><p>That is not a detail. That is the entire reason agents work at all. A model that calls a failing tool 3 times needs to <em>see the error and adapt</em>. If the exception propagated, you’d get a stack trace and a dead process. Instead the model reads:</p><pre>Tool &quot;read_file&quot; failed: ENOENT: no such file or directory, open &#39;/abs/path/to/src/nope.ts&#39;</pre><p>and tries something else. <strong>Errors are conversation, not exceptions.</strong></p><h3>Trick #2: one line that stops a cat from eating your context window</h3><p>Every agent has the same bug: the model runs grep -r &quot;&quot; ., gets back 400,000 characters, and blows the entire context window in one tool call. The conversation is dead. You get an error from the API. The session is ruined.</p><p>One guard fixes it:</p><pre>const MAX_OUTPUT_CHARS = 24_000;<br>function capOutput(result: ToolResult): ToolResult {<br>  if (result.content.length &lt;= MAX_OUTPUT_CHARS) return result;<br>  const omitted = result.content.length - MAX_OUTPUT_CHARS;<br>  return {<br>    ...result,<br>    content: `${result.content.slice(0, MAX_OUTPUT_CHARS)}\n\n[... output truncated, ${omitted} more characters ...]`,<br>  };<br>}</pre><p><strong>Eight lines. Infinite context-window protection.</strong></p><p>And notice the truncation <em>tells the model what happened</em>. It doesn’t silently clip — it says “12,345 more characters were omitted.” The model can then decide to narrow its search. A silent truncation would send the model confidently forward with half a file and no idea it was cut off.</p><p>That’s the difference between a cap and a guard: <strong>a cap protects the system, a guard informs the model.</strong></p><h3>Trick #3: the approval gate that isn’t a security boundary (and I know it)</h3><p>Real coding agents ask before running dangerous commands. I wanted one too, but I also wanted to be honest about what it is.</p><p>The entire hook:</p><pre>export function createApprovalHook(<br>  mode: ApprovalMode,<br>  ask: (question: string) =&gt; Promise&lt;string&gt;,<br>): (toolCall: ToolCall) =&gt; Promise&lt;ToolApproval&gt; {<br>  return async (toolCall: ToolCall): Promise&lt;ToolApproval&gt; =&gt; {<br>    if (!needsApproval(mode, toolCall.name)) return { approved: true };<br>    const answer = (await ask(`  allow ${toolCall.name}(${previewCall(toolCall)})? [y/N] `))<br>      .trim().toLowerCase();<br>    if (answer === &quot;y&quot; || answer === &quot;yes&quot;) return { approved: true };<br>    return {<br>      approved: false,<br>      reason: `The user denied the call to \`${toolCall.name}\`. Do not retry it; ask what to do instead.`,<br>    };<br>  };<br>}</pre><p>But here’s the part that matters more than the code:</p><p><strong>When you deny a tool, the denial goes back to the model as a tool result.</strong> Look at the reason string — <em>&quot;Do not retry it; ask what to do instead.&quot;</em></p><p>That’s a prompt written for the model, not for the user. Without it, the model does what every LLM does when it gets a refusal: <strong>it tries the same thing again</strong>, slightly rephrased, three times, until you approve it out of exhaustion.</p><p>Denials must be <em>addressed to the model</em>, because the model is the one that has to change its mind.</p><p><strong>The approval prompt is a speed bump, not a security boundary.</strong> It stops accidental rm -rf. It does not stop a determined model, because the gate lives <em>inside the same process</em> the tool runs in. The real fix is an OS-level sandbox: separate user, separate container, separate machine.</p><p>If you take one thing from this article: <strong>know which of your security controls are theater.</strong> An approval dialog in-process is theater. A container is not.</p><h3>Trick #4: swap the model mid-conversation, without losing your thread</h3><p>This one took me an embarrassingly long time to get right.</p><p>You know that feeling. You’re deep in a conversation with Claude, and you want to try the same session on a local Ollama model. Or the OpenAI API is rate-limiting you and you want to flip to Anthropic. Every framework I tried either <strong>restarted the conversation</strong> or <strong>crashed</strong>.</p><p>The fix is one field and one method:</p><pre>export class Agent {<br>  private currentProvider: Provider;<br>  /** Swap the model backend without losing conversation history. */<br>  setProvider(provider: Provider): void {<br>    this.currentProvider = provider;<br>  }<br>}</pre><p>And the loop uses this.currentProvider, not a captured local. That&#39;s it.</p><p><strong>Why is this free?</strong> Because of the normalized Message type. The history is provider-agnostic <em>by construction</em>. It doesn&#39;t contain &quot;an OpenAI message&quot; or &quot;an Anthropic content block&quot; — it contains <em>our</em> message shape.</p><p>So switching providers is: keep the array, point at a different translator. That’s the whole call — from src/cli.ts:</p><pre>agent.setProvider(createProvider(config));</pre><p>In your own code, point it anywhere:</p><pre>agent.setProvider(<br>  new OpenAICompatibleProvider({<br>    model: &quot;qwen2.5-coder&quot;,<br>    baseUrl: &quot;http://localhost:11434/v1&quot;,<br>  }),<br>);</pre><p>The conversation survives. The next request goes to a different model, in a different wire format, and the model picks up mid-thought like nothing happened.</p><p><strong>This is what the normalized type buys you.</strong> Not “provider support.” <em>Interchangeability.</em></p><h3>Wait — zero dependencies. How is that even possible?</h3><p>Here’s package.json:</p><pre>{<br>  &quot;name&quot;: &quot;my-harness&quot;,<br>  &quot;version&quot;: &quot;0.1.0&quot;,<br>  &quot;private&quot;: true,<br>  &quot;type&quot;: &quot;module&quot;,<br>  &quot;description&quot;: &quot;A tiny, readable LLM agent harness: the loop, the tools, and swappable provider adapters.&quot;,<br>  &quot;engines&quot;: { &quot;node&quot;: &quot;&gt;=23.6&quot; },<br>  &quot;scripts&quot;: {<br>    &quot;start&quot;: &quot;node src/cli.ts&quot;,<br>    &quot;dev&quot;: &quot;node --watch src/cli.ts&quot;,<br>    &quot;mock&quot;: &quot;HARNESS_PROVIDER=mock node src/cli.ts&quot;,<br>    &quot;test&quot;: &quot;node --test test/&quot;,<br>    &quot;typecheck&quot;: &quot;tsc --noEmit&quot;<br>  },<br>  &quot;devDependencies&quot;: {<br>    &quot;@types/node&quot;: &quot;^22.10.0&quot;,<br>    &quot;typescript&quot;: &quot;^5.8.0&quot;<br>  }<br>}</pre><p><strong>Zero runtime dependencies.</strong> Two dev dependencies: TypeScript and its types. That’s it.</p><p>Three decisions did all the work:</p><p><strong>1. Node 23.6+ runs TypeScript directly.</strong> Type-stripping went stable — you literally node src/cli.ts. No build step. No bundler. No dist/. No watch process. The file you edit is the file that runs.</p><pre>node src/cli.ts &quot;what does this project do?&quot;</pre><p>That’s it. No npm run build. No waiting. No wondering if your editor&#39;s version of the code is what you&#39;re testing.</p><p><strong>2. </strong><strong>node:test instead of Vitest/Jest.</strong> The test runner is <em>in the runtime</em>:</p><pre>node --test test/     # 25 tests, 4 suites, ~200ms</pre><p>No config file. No transformer. No vitest.config.ts with 40 lines of plugin soup. And because there&#39;s no transform step, <strong>the tests run the exact source you ship.</strong></p><p><strong>3. </strong><strong>node:fs instead of a filesystem library.</strong> The built-in modules cover nearly everything: node:fs/promises, node:path, node:child_process, node:crypto, node:readline.</p><p>The streaming SSE parser? Hand-rolled, ~65 lines. The JSON Schema? A 4-field interface. The argument parsing? process.argv.</p><p><strong>Every dependency you add is a library you now maintain, document, audit, and wait for on every security update.</strong> For a teaching project, that cost is pure loss.</p><h3>The mock provider: watch the loop with no API key</h3><p>This is my favorite part, and it cost 46 lines.</p><p>Most people need an API key to see an agent work. I didn’t want that. So there’s a scripted provider that fakes one round-trip:</p><pre>export class MockProvider implements Provider {<br>  readonly name = &quot;mock&quot;;<br>  readonly model: string;<br>  constructor(model = &quot;mock-1&quot;) {<br>    this.model = model;<br>  }<br>  async *chat(req: ChatRequest): AsyncGenerator&lt;LLMEvent&gt; {<br>    const last = req.messages.at(-1);<br>    if (last &amp;&amp; last.role === &quot;tool&quot;) {<br>      const preview = truncate(last.content, 700);<br>      yield {<br>        type: &quot;text&quot;,<br>        text: `Tool \`${last.toolName}\` ${last.isError ? &quot;failed&quot; : &quot;returned&quot;}:\n\n${preview}\n\nThat is the entire loop: model → tool call → harness executes it → result is appended to the history → model sees it again. Point the harness at a real provider to keep going.`,<br>      };<br>      yield { type: &quot;finish&quot;, reason: &quot;stop&quot; };<br>      return;<br>    }<br>    yield { type: &quot;text&quot;, text: &quot;Let me look at the workspace first.&quot; };<br>    yield {<br>      type: &quot;tool_call&quot;,<br>      toolCall: {<br>        id: `call_${Date.now()}`,<br>        name: &quot;list_files&quot;,<br>        arguments: { path: &quot;.&quot;, depth: 1 },<br>      },<br>    };<br>    yield { type: &quot;finish&quot;, reason: &quot;tool_use&quot; };<br>  }<br>}</pre><p>Run it with zero configuration:</p><pre>node src/cli.ts --mock &quot;list the files here&quot;</pre><p>Real output, from the real v0.1.0:</p><pre>provider mock · model mock-1<br>assistant › Let me look at the workspace first.<br>  ⚙ list_files({&quot;path&quot;:&quot;.&quot;,&quot;depth&quot;:1})<br>  ✓ list_files · 1ms · 304 chars<br>assistant › Tool `list_files` returned:<br>.env.example<br>.gitignore<br>README.md<br>harness.config.example.json<br>package-lock.json<br>package.json<br>src/<br>src/agent.ts<br>src/cli.ts<br>src/config.ts<br>...<br>tsconfig.json</pre><pre>That is the entire loop: model → tool call → harness executes it → result is appended to the history → model sees it again. Point the harness at a real provider to keep going.</pre><pre>  context ~1.1k / 32.0k (3.5%)</pre><p><strong>No API key. No network. No account. $0.00.</strong></p><p>And this isn’t a toy — it’s the same Provider interface, the same loop, the same registry, the same message format. The <em>only</em> thing that changed is which adapter is plugged in.</p><p><strong>That’s the whole architecture, proven by construction:</strong> if the mock and a real model are interchangeable, the seam is in the right place.</p><h3>The three seams (this is the whole map)</h3><pre>             ┌─────────────────────────────────────────┐<br> user text → │ append to messages                      │<br>             │        ↓                                │<br>             │ provider.chat(messages, tools)          │<br>             │        ↓                                │<br>             │ text? print it                          │<br>             │ tool calls? approve → execute → append ─┼─┐<br>             │ no tool calls? done                     │ │<br>             └─────────────────────────────────────────┘ │<br>                        ↑                                │<br>                        └────────────────────────────────┘</pre><p>Three files own everything:</p><ul><li><strong>Seam:</strong> The loop<br><strong>File:</strong> src/agent.ts<br><strong>Lines:</strong> 288<br><strong>Contract:</strong> model → tools → results → repeat, capped at maxSteps</li><li><strong>Seam:</strong> The provider<br><strong>File:</strong> src/types.ts<br><strong>Lines:</strong> 72<br><strong>Contract:</strong> chat(req): AsyncGenerator&lt;LLMEvent&gt; over a normalized Message</li><li><strong>Seam:</strong> The tools<br><strong>File:</strong> src/tools/registry.ts<br><strong>Lines:</strong> 77<br><strong>Contract:</strong> { spec, run } — dispatch by name, cap output at 24k chars</li></ul><p><strong>288 + 72 + 77 = 437 lines.</strong> That’s the entire core. The other ~2,800 lines are the CLI (885), the filesystem tools (418), the provider adapters (561), config, sessions, and the /connect wizard.</p><p><strong>If you only read three files, read those three.</strong> Everything else is replaceable.</p><h3>What I deliberately left broken (read before you comment 👇)</h3><p>I know what you’re typing. <em>“But where’s the compaction? The retries? The sandbox? The parallel subagents?”</em></p><p>Deliberately cut. And here’s why each cut is a lesson:</p><ul><li><strong>No context compaction.</strong> History only grows. Real harness: summarize old turns. I left it so you’d <em>feel</em> the wall yourself.</li><li><strong>The context window is display-only.</strong> It prints 1.9k / 128.0k (1.5%) and then... lets the request through anyway. Real harness: truncate or reject. I left it visible-but-not-enforced so you&#39;d see that a pretty number isn&#39;t a safety mechanism.</li><li><strong>Path containment is a string check, not a sandbox.</strong> path.relative() catches ../../.env. A symlink does not. Real fix: fs.realpath before the check.</li><li><strong>Approval is opt-in and off by default.</strong> Because a prompt is a speed bump, and I’d rather you learn that by reading the code than by getting burned.</li></ul><p><strong>A 3,000-line toy that lists its lies beats a 30,000-line framework that hides them.</strong></p><h3>Steal this in 5 minutes 🏴‍☠️</h3><pre>git clone https://github.com/rogeriolaa/my-harness<br>cd my-harness<br>npm install<br>npm test               # 25 tests, 4 suites, no dependencies<br>npm run typecheck      # clean<br>node src/cli.ts --mock &quot;take a look around&quot;   # the loop, offline, $0</pre><p>Then do the thing that made me understand it: <strong>put a </strong><strong>console.log inside the loop</strong> and watch the messages array grow. Find this line in src/agent.ts:</p><pre>this.messages.push({ role: &quot;assistant&quot;, content: text, toolCalls });</pre><p>and add one line under it:</p><pre>this.messages.push({ role: &quot;assistant&quot;, content: text, toolCalls });<br>console.log(this.messages.length, this.messages.at(-1));</pre><p>Run it a few times. Watch the count go 2 → 4 — and watch the roles:</p><pre>user → assistant → tool → assistant</pre><p>One user turn in. One assistant turn with a tool call. One tool result. One final assistant turn with no tool call. <strong>That means the model is done.</strong></p><p><strong>That array IS the agent.</strong> Everything else is a detail.</p><h3>The uncomfortable truth</h3><p>AI agents aren’t magic, and they aren’t “agents” in the way the marketing suggests. They’re:</p><ol><li><strong>A loop</strong> (~40 lines of actual logic; 126 lines in agent.ts once you add approvals, usage tracking, and error handling)</li><li><strong>A normalized message type</strong> (so backends are swappable)</li><li><strong>A registry</strong> (so tools are pluggable)</li><li><strong>A system prompt</strong> (so the model knows the rules)</li></ol><p>That’s it. That’s the whole thing. I wrote it in a handful of evenings, and the code that resulted is <strong>3,292 lines</strong> with <strong>zero runtime dependencies</strong> and <strong>no build step</strong>.</p><p>Every framework you’ve used is this same four things, plus the abstraction you can’t see through.</p><p>You don’t have to adopt mine. <strong>Steal the pattern:</strong> normalize your messages, make the loop provider-agnostic, cap tool output, and — most importantly — <em>know which of your safety controls are real and which are theater.</em></p><p>Now go read those three files. agent.ts is 288 lines — and about 40 of them are the idea. You&#39;ll be done before your coffee cools.</p><p><em>If this broke your brain even a little, clap 👏 (it feeds the algorithm gods), drop your angriest “but every agent framework needs X” in the comments.</em></p><p><strong>Repo:</strong> <a href="https://github.com/rogeriolaa/my-harness">github.com/rogeriolaa/my-harness</a> — MIT licensed, 3,292 lines, zero dependencies. Go break it.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5162a368e64d" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/ai-coding-agents-arent-magic-i-rebuilt-one-from-scratch-in-3-292-lines-5162a368e64d">AI Coding Agents Aren’t Magic. I Rebuilt One From Scratch in 3,292 Lines.</a> was originally published in <a href="https://javascript.plainenglish.io">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[REST Is a Lie We All Agreed to Believe. I Proved It in 300 Lines.]]></title>
            <link>https://javascript.plainenglish.io/rest-is-a-lie-we-all-agreed-to-believe-i-proved-it-in-300-lines-e552a348ce8f?source=rss-82244dfb6a6a------2</link>
            <guid isPermaLink="false">https://medium.com/p/e552a348ce8f</guid>
            <category><![CDATA[trpc]]></category>
            <category><![CDATA[type-safe]]></category>
            <category><![CDATA[rest-api]]></category>
            <category><![CDATA[typescript]]></category>
            <dc:creator><![CDATA[Rogerio Amorim]]></dc:creator>
            <pubDate>Sun, 27 Sep 2026 09:07:29 GMT</pubDate>
            <atom:updated>2026-09-27T09:07:29.876Z</atom:updated>
            <content:encoded><![CDATA[<blockquote><em>I rebuilt tRPC from scratch in one weekend — no framework, no codegen, no React. What I found broke how I think about APIs forever.</em></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pcXuE2v1TQVdhIEY1Vg3xA.png" /></figure><p>Let me guess your workflow:</p><ol><li>You change the backend.</li><li>You <em>pray</em> the frontend still works.</li><li>TypeScript says “all good 👍”.</li><li>Production says otherwise. At 2 AM. On a Friday.</li></ol><p>I lived this loop for years. Then someone told me: <strong>“just use tRPC, bro.”</strong></p><p>My reaction? <em>“Magic type-safety across the network? That’s impossible. It’s marketing.”</em></p><p>So I did what any stubborn developer does. I rebuilt it from scratch to prove it was hype.</p><p><strong>I was wrong. And after 300 lines of plain </strong><strong>node:http + </strong><strong>fetch, I&#39;ll never design an API the old way again.</strong></p><p>Here’s the whole trick — and why 90% of REST boilerplate you’re writing is already obsolete.</p><h3>The moment that broke my brain 🤯</h3><p>Look at this. Really look:</p><pre>export const appRouter = t.router({<br>  user: t.router({<br>    getById: t.procedure<br>      .input(z.object({ id: z.string() }))<br>      .query(({ input }) =&gt; users.find((u) =&gt; u.id === input.id) ?? null),<br>    list: t.procedure.query(() =&gt; users),<br>    create: t.procedure<br>      .input(z.object({ name: z.string().min(1) }))<br>      .mutation(({ input }) =&gt; {<br>        const user = { id: String(users.length + 1), name: input.name };<br>        users.push(user);<br>        return user;<br>      }),<br>  }),<br>});</pre><pre>export type AppRouter = typeof appRouter;</pre><p>Now the client. I import <strong>zero runtime code</strong>. Just a type. A ghost. Something that doesn’t even exist in the JavaScript output:</p><pre>import type { AppRouter } from &quot;./router&quot;; // &lt;-- erased at compile time. Zero bytes.</pre><pre>const client = createClient&lt;AppRouter&gt;({ url: &quot;http://localhost:3000/trpc&quot; });</pre><pre>const one = await client.user.getById.query({ id: &quot;1&quot; });<br>//    ^? { id: string; name: string } | null  — autocomplete KNOWS.</pre><p>And then I tried to break it:</p><pre>await client.user.getById.query({ id: 123 });<br>//                              ~~ 💥 BOOM.<br>// number is not assignable to string.</pre><p><strong>I hadn’t run anything.</strong> No server. No request. No Postman. TypeScript caught a <em>network</em> bug before a single packet left my laptop.</p><p>That red squiggle gave me chills. If you’ve ever shipped a { userId } vs { id } mismatch to production, you know exactly why.</p><p><strong>This is the entire product.</strong> Everything else is just plumbing to make that squiggle appear.</p><h3>The dirty secret: your OpenAPI spec is a middleman that steals from you</h3><p>Here’s the hot take that’ll get me yelled at in the comments (please, yell — engagement is engagement):</p><p><strong>OpenAPI, codegen, hand-written DTOs, Postman collections — they’re all workarounds for one failure: your contract lives in two places.</strong></p><p>The tRPC insight is stupidly simple:</p><blockquote><em>The router object IS the schema. Export </em><em>typeof it. Done.</em></blockquote><pre>export type AppRouter = typeof appRouter;</pre><p>No YAML. No swagger-codegen step everyone forgets to run. No &quot;oops, staging is 3 versions behind the types.&quot;</p><p>TypeScript types travel at <strong>build time</strong>. JSON travels at <strong>runtime</strong>. The only job left is keeping them in sync. And that’s where most people give up and say “impossible.”</p><p>It’s not. It takes one library you’ve already heard of: <strong>Zod</strong>.</p><h3>Trick #1: One schema to rule both worlds</h3><p>Everyone uses Zod for validation. Almost nobody realizes what z.infer actually means:</p><p><strong>One definition = a runtime bouncer AND a compile-time fortune teller.</strong></p><pre>t.procedure<br>  .input(z.object({ name: z.string().min(1) }))<br>  .mutation(({ input }) =&gt; { /* input.name is string. Guaranteed. */ })</pre><p>Here’s the part nobody talks about: types check the caller you <em>control</em>. Validation checks the caller you <em>don’t</em>.</p><p>{ name: &quot;&quot; } is perfectly valid TypeScript (it&#39;s a string!). But Zod nukes it at runtime:</p><pre>{ &quot;error&quot;: { &quot;code&quot;: &quot;BAD_REQUEST&quot;, &quot;message&quot;: &quot;Invalid input&quot;, &quot;issues&quot;: [...] } }</pre><p>I learned this the hard way: <strong>type-safety without runtime validation is just optimism with extra steps.</strong> You need both. Zod gives you both from a single line.</p><p>The builder that wires this up is embarrassingly simple — just immutable accumulation:</p><pre>function createProcedure(def) {<br>  return {<br>    _def: def,<br>    input(schema) {<br>      return createProcedure({ ...def, inputSchema: schema });<br>    },<br>    query(handler) {<br>      return createProcedure({ ...def, type: &quot;query&quot;, handler });<br>    },<br>    mutation(handler) {<br>      return createProcedure({ ...def, type: &quot;mutation&quot;, handler });<br>    },<br>  };<br>}</pre><p>No decorators. No reflection. No magic. Just spread operators. (Disappointed? Good — keep reading, the real magic is next.)</p><h3>Trick #2: 10 lines that replace your entire codegen pipeline</h3><p>This is the function that made me stare at my ceiling for 20 minutes:</p><pre>type MaybeInput&lt;I&gt; = undefined extends I ? [] | [input?: undefined] : [input: I];</pre><pre>export type InferClient&lt;T&gt; = {<br>  [K in keyof T]: T[K] extends Procedure&lt;infer I, infer O&gt;<br>    ? {<br>        query: (...args: MaybeInput&lt;I&gt;) =&gt; Promise&lt;O&gt;;<br>        mutation: (...args: MaybeInput&lt;I&gt;) =&gt; Promise&lt;O&gt;;<br>      }<br>    : T[K] extends RouterRecord<br>      ? InferClient&lt;T[K]&gt;<br>      : never;<br>};</pre><p>That’s it. <strong>That’s the whole “framework.”</strong></p><p>Three boring keywords — keyof, conditional types, infer — doing the job of a 50MB Java CLI code generator:</p><ol><li>Walk every key of the server router.</li><li>See a Procedure&lt;I, O&gt;? Rip out the input I and output O with infer.</li><li>See a nested router? Recurse.</li><li>No input? Make the arg optional so client.user.list.query() just works.</li></ol><p>I didn’t trust the autocomplete, so I wrote a test that <em>proves</em> the inference:</p><pre>type Client = InferClient&lt;AppRouter&gt;;<br>expectTypeOf&lt;Client[&quot;user&quot;][&quot;getById&quot;][&quot;query&quot;]&gt;()<br>  .parameter(0)<br>  .toEqualTypeOf&lt;{ id: string }&gt;(); // passes. No mocks. Pure types.</pre><p>Let that sink in: <strong>I replaced Swagger + codegen + DTO duplication with a mapped type you can tweet.</strong></p><p>If you’re still maintaining frontend-types/ and backend-types/ folders by hand in 2026... I&#39;m saying this with love: stop. You&#39;re doing the compiler&#39;s job, badly.</p><h3>Trick #3: The Proxy hack — 20 lines of beautiful cheating</h3><p>Okay, types are fiction. At runtime, <em>something</em> has to hit the network. Here’s the entire client runtime:</p><pre>function createProxy(path: string[] = []): unknown {<br>  return new Proxy(() =&gt; {}, {<br>    get(_, prop) {<br>      if (prop === &quot;query&quot; || prop === &quot;mutation&quot;)<br>        return (input: unknown) =&gt; call(path, input);<br>      return createProxy([...path, String(prop)]);<br>    },<br>  });<br>}</pre><p>client.user.getById.query <strong>doesn&#39;t exist.</strong> It&#39;s a ghost chain. user → pushes &quot;user&quot;. getById → pushes &quot;getById&quot;. .query → fires POST /trpc/user.getById with { input }.</p><p>The server? Plain node:http. No Express. No Fastify. I wanted zero places to hide:</p><pre>// POST /trpc/&lt;dotted.path&gt;  body: { &quot;input&quot;: unknown }<br>const dottedPath = url.pathname.slice(&quot;/trpc/&quot;.length);<br>const proc = resolvePath(router, dottedPath); // split(&quot;.&quot;).reduce(...)</pre><p>See the symmetry? <strong>The type recursion and the runtime path-walk traverse the exact same tree.</strong> If they disagree, you get a red squiggle or a 404. Never silent drift. Never 2 AM pages.</p><p>That’s the whole architecture. Compile-time mirror + runtime path call. Everything else is error handling.</p><h3>What I left out (read before you rage-comment 👇)</h3><p>I know what you’re typing already: <em>“but what about caching / Dates / file uploads / WebSockets?!”</em></p><p>Deliberately cut. And here’s why each cut is a lesson:</p><ul><li><strong>POST for queries too.</strong> Real tRPC uses GET for queries. I used POST for everything = one code path. Wrong for prod, perfect for learning.</li><li><strong>JSON-only.</strong> Date becomes a string. BigInt explodes. Real fix = superjson. I left it broken so you&#39;d <em>see</em> the boundary.</li><li><strong>No batching, no auth, no subscriptions.</strong> Each deserves its own article (smash follow if you want part 2).</li><li><strong>1MB body cap.</strong> One if statement. Enough to prove I thought about it, not enough to survive Hacker News.</li></ul><p>A 300-line toy that lists its lies &gt; a 3,000-line framework that hides them. Fight me in the comments.</p><h3>Steal this in 5 minutes 🏴‍☠️</h3><pre>npm install<br>npm test          # 5 tests: roundtrip, mutation, Zod rejection, 404, type inference<br>npm run start:server   # :3000 — raw node:http, no framework<br>npm run demo:client    # feel the autocomplete. Then break it on purpose.</pre><p>Now do the thing that converted me: change { id: &quot;1&quot; } to { id: 123 } and run npx tsc --noEmit.</p><p><strong>That single error is the thesis of this whole article.</strong> A network bug, caught without a network.</p><h3>The uncomfortable truth</h3><p>tRPC isn’t magic. It’s just two halves most of us never connect:</p><ol><li><strong>Compile-time mirror</strong> (InferClient + infer)</li><li><strong>Runtime path call</strong> (Proxy + POST /trpc/&lt;path&gt;)</li></ol><p>Zod is the bridge: static type for the client you control, runtime check for the stranger you don’t.</p><p>You don’t even need to adopt tRPC. Steal the <em>pattern</em>: define the contract once as a value, export typeof it, derive the client. I now use it for internal tools, CLIs, test harnesses — anywhere I used to duplicate interfaces like a caveman.</p><p>Build the mini version once. I promise: you’ll never trust a hand-synced api-types.ts again.</p><p><em>If this broke your brain even a little, clap 👏 (it feeds the algorithm gods), drop your angriest “but REST is fine because…” in the comments, and follow for part 2: React hooks + batching + superjson. The repo is ~300 lines — go break it.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e552a348ce8f" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/rest-is-a-lie-we-all-agreed-to-believe-i-proved-it-in-300-lines-e552a348ce8f">REST Is a Lie We All Agreed to Believe. I Proved It in 300 Lines.</a> was originally published in <a href="https://javascript.plainenglish.io">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[I Built a Doctor for Your .env Files (Zero Dependencies, One Regex Away From the Truth)]]></title>
            <link>https://javascript.plainenglish.io/i-built-a-doctor-for-your-env-files-zero-dependencies-one-regex-away-from-the-truth-92942f4bbaa5?source=rss-82244dfb6a6a------2</link>
            <guid isPermaLink="false">https://medium.com/p/92942f4bbaa5</guid>
            <dc:creator><![CDATA[Rogerio Amorim]]></dc:creator>
            <pubDate>Fri, 28 Aug 2026 13:07:59 GMT</pubDate>
            <atom:updated>2026-08-28T13:07:59.133Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cNr_OQrwxpuHMtUy2mzKxA.png" /></figure><p>Every project I’ve ever joined had the same ghost: an environment variable that worked on one machine and silently broke on another. Not because of exotic infrastructure — because .env, .env.example and what the code actually reads drift apart, and nothing notices.</p><p>So last weekend I built <strong>env-doctor</strong>: a CLI that audits environment variables in JS/TS projects. It crosses three sources — your .env, your .env.example, and the process.env.X references scattered through your source code — and tells you exactly what&#39;s wrong before production does.</p><p>Repo: <a href="https://github.com/rogeriolaa/env-doctor">https://github.com/rogeriolaa/env-doctor</a></p><pre>npx @n0n3br/env-doctor .</pre><h3>What it finds</h3><p>Running it against a sample app produces this:</p><pre>🩺 env-doctor — auditing fixtures/sample-app</pre><pre>  🚨 [secret] STRIPE_API_KEY in .env looks like a real secret (high-entropy value, 34 chars)<br>  🚨 [secret] JWT_SECRET in .env looks like a real secret (JWT-shaped)<br>  ⚠ [undocumented] LEGACY_FLAG is referenced in code but not documented in .env.example<br>  ⚠ [type] &quot;MAX_RETRIES&quot; is used as a number in code, but &quot;three&quot; is not numeric (src/server.js:7)<br>  ℹ [orphan] JWT_SECRET is set in .env but never referenced in source code<br>  ℹ [orphan] CACHE_TTL is documented in .env.example but never referenced in source code</pre><pre>  6 issue(s): 2 critical, 2 warning(s), 2 info</pre><p>Five rules:</p><ol><li><strong>missing</strong> — in code + documented, but absent from your local .env. The classic &quot;why doesn&#39;t it run on my machine?&quot;</li><li><strong>undocumented</strong> — referenced in code but absent from .env.example. Works for you, breaks for the next clone.</li><li><strong>orphan</strong> — declared but never referenced. Dead config weight.</li><li><strong>secret</strong> — the value looks like a <em>real</em> credential sitting in a file that might get committed.</li><li><strong>type</strong> — MAX_RETRIES=three while the code does parseInt(process.env.MAX_RETRIES). It will be NaN at runtime, just not today.</li></ol><h3>The architecture is three parsers and one set-difference</h3><p>The whole core fits in one file with zero dependencies.</p><h3>1. A tiny dotenv parser</h3><p>Most people don’t know how many edge cases dotenv files have. Mine handles the important ones in ~30 lines:</p><pre>export function parseDotenv(text) {<br>  const out = new Map();<br>  for (const rawLine of text.split(/\r?\n/)) {<br>    const line = rawLine.trim();<br>    if (!line || line.startsWith(&#39;#&#39;)) continue;<br>    let body = line;<br>    if (body.startsWith(&#39;export &#39;)) body = body.slice(7).trim();<br>    const eq = body.indexOf(&#39;=&#39;);<br>    if (eq === -1) continue;<br>    const key = body.slice(0, eq).trim();<br>    let value = body.slice(eq + 1).trim();<br>    const q = value[0];<br>    if (q === &#39;&quot;&#39; || q === &quot;&#39;&quot;) {<br>      // quoted value: take up to the closing quote,<br>      // trailing inline comment ignored<br>      const end = value.indexOf(q, 1);<br>      if (end !== -1) { out.set(key, { value: value.slice(1, end) }); continue; }<br>    } else {<br>      const hash = value.indexOf(&#39; #&#39;);   // inline comment on unquoted values<br>      if (hash !== -1) value = value.slice(0, hash).trim();<br>    }<br>    if (key) out.set(key, { value });<br>  }<br>  return out;<br>}</pre><p>The subtle part: KEY=&quot;value&quot; # comment needs quote-aware parsing, because stripping at the first # would corrupt values that legitimately contain #.</p><h3>2. Source scanning with a regex (yes, deliberately)</h3><pre>const ENV_ACCESS =<br>  /process\.env\.([A-Z_][A-Z0-9_]*)|process\.env\[\s*[&#39;&quot;`]([A-Z_][A-Z0-9_]*)[&#39;&quot;`]\s*\]|import\.meta\.env\.([A-Z_][A-Z0-9_]*)/g;</pre><p>This catches dot access (process.env.PORT), bracket access (process.env[&#39;PORT&#39;]) and Vite&#39;s import.meta.env.X, with line numbers for output. No AST, no babel, no typescript compiler dependency.</p><p>This was a deliberate trade-off. An AST would be “more correct,” but it costs megabytes of dependencies and seconds of startup to catch a pattern nobody writes. Dynamic access like process.env[prefix + name] is invisible either way — you can&#39;t audit what&#39;s computed at runtime without running the program.</p><h3>3. The diagnosis is set algebra</h3><p>With three sets — code refs, .env keys, .env.example keys — every rule becomes a difference:</p><ul><li>missing = refs ∩ example − env</li><li>undocumented = refs − example</li><li>orphan = (env ∪ example) − refs</li></ul><p>Once framed this way, the code writes itself:</p><pre>for (const name of refNames) {<br>  if (!exNames.has(name)) {<br>    add(&#39;undocumented&#39;, &#39;warning&#39;,<br>      `${name} is referenced in code but not documented in .env.example`);<br>  }<br>}</pre><h3>The hard part: secret detection without crying wolf</h3><p>Flagging secrets is easy. The hard part is not flagging &lt;your-api-key&gt; — because a linter that screams at every placeholder gets uninstalled in a week.</p><p>My heuristic has two layers:</p><p><strong>Shape detection</strong> (always a secret):</p><pre>/^eyJ[A-Za-z0-9_-]+\./.test(v) ||        // JWT: header.payload signature shape<br>/^(ghp|gho|github_pat)_/.test(v) ||      // GitHub tokens<br>/^sk-[A-Za-z0-9]{20,}/.test(v) ||        // OpenAI-style keys<br>/^xox[baprs]-/.test(v) ||                // Slack tokens<br>/^-----BEGIN [A-Z ]*PRIVATE KEY-----/.test(v)  // PEM keys</pre><p>These token formats have grammatically distinctive prefixes. A string starting with eyJ is base64 of {&quot; — no coincidence possible.</p><p><strong>Entropy + name</strong> (probable secret): long random-looking strings (≥20 chars, mixed alphanumerics) combined with a suspicious variable name — SECRET, TOKEN, PASSWORD, API_KEY, PRIVATE, ENCRYPT...</p><p>And crucially, an escape hatch for placeholders before any of this runs:</p><pre>if (/^&lt;.*&gt;$/.test(v)) return false;                    // &lt;your-key-here&gt;<br>if (/^\$\{?\w+\}?$/.test(v)) return false;             // ${DB_PASSWORD}, $VAR<br>if (/^(changeme|xxx+|example|placeholder|todo)$/i.test(v)) return false;</pre><p>Result: real secrets flagged, example files clean.</p><h3>Type checking from usage context</h3><p>The trick for MAX_RETRIES=three is looking at <em>how</em> the code uses the variable, not just its name:</p><pre>classifyUsage(&quot;const max = parseInt(process.env.MAX_RETRIES, 10)&quot;)<br>// → { numeric: true, boolean: false }</pre><pre>classifyUsage(&quot;if (process.env.DEBUG === &#39;true&#39;) {}&quot;)<br>// → { numeric: false, boolean: true }</pre><p>If usage says numeric but Number(value) is NaN, that&#39;s a bug you&#39;d otherwise find in staging. If usage compares against &#39;true&#39; but the value is maybe, same thing.</p><h3>Proving it works: 34 tests, zero test framework</h3><p>Following the approach from my previous projects, the test suite runs on Node’s native runner — node --test, no jest, no vitest, no dev dependency at all. It covers the parser edge cases, the reference extractor, both layers of the secret heuristic (real tokens flagged, placeholders passing clean), and end-to-end CLI runs against a fixture project asserting actual exit codes.</p><p>That fixture project doubles as the demo — npm run demo audits it and shows all five rules firing.</p><h3>Where it fits</h3><p>Exit code is 1 on errors or criticals, so it drops straight into CI:</p><pre>- run: npx @n0n3br/env-doctor .</pre><p>Or wire the JSON output into something bigger:</p><pre>npx @n0n3br/env-doctor . --json | jq &#39;.issues[] | select(.severity == &quot;critical&quot;)&#39;</pre><h3>Honest limitations</h3><ul><li>Dynamic access (process.env[prefix + name]) is invisible to static scanning.</li><li>Entropy heuristics are probabilistic — a random-looking non-secret named AUTH_THING gets flagged. False positives beat leaked credentials.</li><li>Type checks only catch confident cases; this is a smoke detector, not a type system for config.</li></ul><p>The whole tool is ~350 lines of dependency-free ESM across two files. Most of the value came not from writing code but from deciding what <em>not</em> to flag — the placeholder list took longer than the parser.</p><p>What’s the oldest undocumented env var in a repo you maintain? (I found a LEGACY_FLAG in mine while writing this article. It was still being read. By nothing.)</p><p><strong>Try it:</strong> npx @n0n3br/env-doctor . — or star/watch the repo: <a href="https://github.com/rogeriolaa/env-doctor">https://github.com/rogeriolaa/env-doctor</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=92942f4bbaa5" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/i-built-a-doctor-for-your-env-files-zero-dependencies-one-regex-away-from-the-truth-92942f4bbaa5">I Built a Doctor for Your .env Files (Zero Dependencies, One Regex Away From the Truth)</a> was originally published in <a href="https://javascript.plainenglish.io">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[I Built an MCP Server That Keeps My Work Journal — Here’s Everything I Learned]]></title>
            <link>https://javascript.plainenglish.io/i-built-an-mcp-server-that-keeps-my-work-journal-heres-everything-i-learned-0f6d55786c75?source=rss-82244dfb6a6a------2</link>
            <guid isPermaLink="false">https://medium.com/p/0f6d55786c75</guid>
            <category><![CDATA[ai-tools]]></category>
            <category><![CDATA[mcp-server]]></category>
            <category><![CDATA[developer-productivity]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[typescript]]></category>
            <dc:creator><![CDATA[Rogerio Amorim]]></dc:creator>
            <pubDate>Wed, 26 Aug 2026 09:34:50 GMT</pubDate>
            <atom:updated>2026-08-26T09:34:50.318Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MFfJUWDtHMsT1H2kilnwFA.png" /></figure><p><em>A Model Context Protocol server in ~190 lines of TypeScript that turns a folder of Markdown into a searchable work journal any AI assistant can read and write. Plus: how to demo an MCP server without an editor, and the things the tutorials don’t tell you.</em></p><p>Be honest: how long did your last “log what I did today” habit last? A week? Three days?</p><p>Here’s the thing though — in 2026, <em>something else already knows what you did all day</em>: your AI assistant. It helped you debug the race condition, wrote half the tests with you, and sat through every refactor. The journal problem was never about discipline. It’s about the log being a <strong>separate place</strong> from the work.</p><p>So I flipped it: instead of me feeding a journal, why not give my assistant tools to keep one?</p><p>The natural fit is <strong>MCP (Model Context Protocol)</strong> — the standard that lets LLM clients discover and call external tools. I built dev-diary-mcp: a server that turns a plain folder of Markdown files into a searchable work journal. It ended up being the best-sized project I&#39;ve found for <em>learning</em> MCP, because it touches every core concept (tools, schemas, stdio transport, stateless storage) while staying under 200 lines.</p><p>One thing to get out of the way early: <strong>the diary is not the point</strong>. There are journal apps; you don’t need me to build another one. I picked this subject precisely because it’s small, boring, and universally understood — the ideal shape for a learning project. The real goal was to answer a question I kept asking myself: <em>“MCP servers seem like magic. Can anyone actually build one for anything?”</em></p><p>The answer, as this article will show, is yes — and once you see the whole recipe, you’ll realize the hard part was never the protocol. It’s deciding what to wrap. Your gym log, your reading list, your company’s internal wiki, your smart home — if it can be read or written by code, it can be behind an MCP server by Friday.</p><ul><li>💻 Code: <a href="https://github.com/rogeriolaa/dev-diary-mcp">github.com/rogeriolaa/dev-diary-mcp</a></li></ul><h3>What it does</h3><p>The assistant gets four tools:</p><ul><li><strong>Tool:</strong> log_work<br><strong>What it does:</strong> Appends a timestamped entry (with tags) to today’s file</li><li><strong>Tool:</strong> search_diary<br><strong>What it does:</strong> Full-text search across all entries</li><li><strong>Tool:</strong> daily_summary<br><strong>What it does:</strong> Everything logged on a given date</li><li><strong>Tool:</strong> stats<br><strong>What it does:</strong> Totals, streaks, top tags</li></ul><p>The storage format is deliberately boring. One file per day:</p><pre>## 14:32 #bugfix #websocket<br>Fixed the race condition in the WebSocket broadcast queue</pre><pre>## 16:10 #testing<br>Wrote E2E test covering two-client sync</pre><p>That’s it. No database. You can grep it, commit it, edit it by hand. This choice mattered more than I expected — more on that later.</p><h3>How to build one (the whole recipe)</h3><h3>1. The skeleton is genuinely small</h3><p>With the official TypeScript SDK (v2, implementing the 2026–07–28 spec):</p><pre>npm install @modelcontextprotocol/server zod</pre><pre>import { McpServer } from &#39;@modelcontextprotocol/server&#39;;<br>import { StdioServerTransport } from &#39;@modelcontextprotocol/server/stdio&#39;;<br>import * as z from &#39;zod/v4&#39;;</pre><pre>const server = new McpServer({ name: &#39;dev-diary&#39;, version: &#39;1.0.0&#39; });</pre><pre>server.registerTool(<br>  &#39;log_work&#39;,<br>  {<br>    description: &#39;Append a timestamped entry to the developer diary...&#39;,<br>    inputSchema: z.object({<br>      text: z.string().min(1),<br>      tags: z.array(z.string()).optional(),<br>      date: z.string().regex(/^\d{4}-\d{2}-\d{2}$/).optional(),<br>    }),<br>  },<br>  async ({ text, tags = [], date }) =&gt; {<br>    // ...append to diary/YYYY-MM-DD.md...<br>    return { content: [{ type: &#39;text&#39;, text: &#39;Logged.&#39; }] };<br>  },<br>);</pre><pre>await server.connect(new StdioServerTransport());</pre><p>That’s a complete MCP server. Four concepts carry everything:</p><ol><li><strong>registerTool(name, config, handler)</strong> — the tool catalog</li><li><strong>inputSchema</strong> — a Zod schema; the SDK turns it into JSON Schema for the client, and validates arguments for you before your handler ever runs</li><li><strong>Return value</strong> — { content: [{ type: &#39;text&#39;, text: &#39;...&#39; }] }; this is what the LLM reads as the tool&#39;s result</li><li><strong>Transport</strong> — StdioServerTransport() means the client spawns your process and speaks JSON-RPC over stdin/stdout. No ports, no auth for local use</li></ol><h3>2. Descriptions are prompts, not documentation</h3><p>This is the biggest mental shift. Your tool descriptions aren’t API docs for humans — they’re <strong>instructions the LLM reads to decide when and how to call your tool</strong>. Compare:</p><pre>// ❌ documentation-style<br>description: &#39;Appends an entry to the diary.&#39;</pre><pre>// ✅ prompt-style<br>description: &#39;Append a timestamped entry to the developer diary for today.<br>Use this whenever the user says they finished/did/fixed something and<br>wants it recorded.&#39;</pre><p>The second one tells the model <em>when to reach for the tool</em>. That “use this whenever…” clause is doing real work — it converts user intent (“I finally fixed that flaky test”) into a tool call without any explicit command.</p><p>Same for parameter descriptions: tags: &#39;Optional labels, e.g. [&quot;bugfix&quot;,&quot;api&quot;]&#39; teaches the model the expected shape by example.</p><h3>3. Design tools around questions, not tables</h3><p>My first draft had CRUD tools (add_entry, update_entry, delete_entry). Wrong shape. Nobody asks their journal to &quot;update entry 47&quot; — they ask <em>&quot;what did I do about the WebSocket bug last week?&quot;</em></p><p>So the final set maps to intents: search_diary (find things), daily_summary (recap a day), stats (the motivation view), and exactly one writer, log_work. Four tools, zero overlap, each answering a question a developer actually asks.</p><p>Rule of thumb I landed on: <strong>one tool per user question, not one per data operation.</strong></p><h3>The demo problem (and its elegant solution)</h3><p>Here’s what almost killed the project: <strong>how do you demonstrate an MCP server?</strong></p><p>The honest answer is “connect Claude Desktop to it and screenshot a chat” — which proves nothing reproducible, depends on a closed app, and can’t run in CI or on a reader’s machine.</p><p>Then I remembered the boring superpower of the spec: <strong>MCP is just client/server over stdio</strong>. Nothing stops me from writing a second, tiny program that connects to my server like any editor would and drives it end-to-end:</p><pre>import { Client } from &#39;@modelcontextprotocol/client&#39;;<br>import { StdioClientTransport } from &#39;@modelcontextprotocol/client/stdio&#39;;</pre><pre>const transport = new StdioClientTransport({<br>  command: &#39;node&#39;,<br>  args: [&#39;dist/server.js&#39;],   // spawns the server as a child process<br>});<br>const client = new Client({ name: &#39;demo-client&#39;, version: &#39;1.0.0&#39; });<br>await client.connect(transport);</pre><pre>// Exactly what Claude Desktop does under the hood:<br>const { tools } = await client.listTools();<br>await client.callTool({ name: &#39;log_work&#39;, arguments: {<br>  text: &#39;Fixed the race condition in the broadcast queue&#39;,<br>  tags: [&#39;bugfix&#39;, &#39;websocket&#39;],<br>}});</pre><p>Fifty lines later, npm run demo produces this — a full protocol session as proof:</p><pre>=== 1. listTools ===<br> • log_work — Append a timestamped entry to the developer diary...<br> • search_diary — Full-text search across every entry...<br> • daily_summary — Everything logged on a given date...<br> • stats — Totals, active days, streaks, top tags...</pre><pre>=== 2. log_work x3 ===<br>Logged to 2026-08-22.md at 19:05 (tags: bugfix, websocket)<br>...</pre><pre>=== 5. stats ===<br>📊 1 entries across 2 day(s)<br>🔥 Streak: 2 consecutive day(s)<br>🏷️ Top tags: #bugfix (1), #websocket (1)</pre><p>And because it’s a script, it’s also my <strong>integration test</strong>. Every change to the server, I run the demo; if the handshake breaks or a schema drifts, it fails loudly. Demo, docs, and test suite in one artifact.</p><p>If you want a visual route instead, the official Inspector (npx @modelcontextprotocol/inspector node dist/server.js) gives you a web UI to poke tools by hand. Both together cover development and demonstration nicely.</p><h3>Things the tutorials don’t tell you</h3><p><strong>Top-level await will betray you.</strong> The SDK README shows await server.connect(...) at module top level — fine if your package is ESM (&quot;type&quot;: &quot;module&quot;), a hard error if TypeScript compiles you to CommonJS. Wrapping startup in main() costs nothing and works everywhere.</p><p><strong>exactOptionalPropertyTypes fights optional schemas.</strong> With strict TS, passing tags: undefined into an z.string().optional() field errors. Either relax the flag or normalize args at the handler boundary. Cost me ten confused minutes.</p><p><strong>Descriptions are loaded into context.</strong> Every tool description ships to the model on every conversation where the server is connected. Verbose marketing copy wastes tokens and dilutes the useful instructions. Short, imperative, intent-focused wins.</p><p><strong>Stateless servers are a feature.</strong> My server holds no state — it re-reads whatever Markdown is on disk at every call. Consequence: I can hand-edit files between calls and never see stale data, and two clients pointed at the same folder share the truth for free. Resist putting caches in front of file-based tools until profiling says otherwise.</p><p><strong>Timezones are a trap even in a toy.</strong> new Date().toISOString().slice(11,16) gives UTC — fine until someone in UTC-3 logs at 6 PM and sees &quot;21:05&quot;. One line fixes it, but only after you notice.</p><h3>Connecting it for real</h3><p>In Claude Desktop / Cursor / any MCP-capable client (claude_desktop_config.json style):</p><pre>{<br>  &quot;mcpServers&quot;: {<br>    &quot;dev-diary&quot;: {<br>      &quot;command&quot;: &quot;node&quot;,<br>      &quot;args&quot;: [&quot;/absolute/path/to/dev-diary-mcp/dist/server.js&quot;],<br>      &quot;env&quot;: { &quot;DIARY_DIR&quot;: &quot;/home/you/journal&quot; }<br>    }<br>  }<br>}</pre><p>Point DIARY_DIR at a folder inside your dotfiles repo and your work journal versions itself as a side effect. After a week of use, ask your assistant: <em>&quot;summarize my week from the diary, group by tag&quot;</em> — and get back a status report nobody had to write.</p><h3>Why Markdown-as-database won</h3><p>I want to defend the most opinionated choice. Alternatives were SQLite (better queries, opaque storage) or JSON (parseable, ugly diffs). Plain Markdown files won because:</p><ol><li><strong>The human is a first-class client.</strong> I read my journal in editors, greps, and git logs — no tool required.</li><li><strong>Git becomes free backup + history.</strong> git log diary/ is an audit trail no database gives you by default.</li><li><strong>LLMs are phenomenal at Markdown.</strong> No serialization mismatch between what the model writes and what’s stored.</li><li><strong>Failure mode is graceful.</strong> A corrupted line is visible and fixable by hand; a corrupted SQLite page isn’t.</li></ol><p>The lesson generalizes beyond journals: <strong>when both humans and LLMs are clients of your data, store it in the format both already speak.</strong></p><h3>Try it</h3><pre>git clone https://github.com/rogeriolaa/dev-diary-mcp<br>cd dev-diary-mcp &amp;&amp; npm install &amp;&amp; npm run build &amp;&amp; npm run demo</pre><p>Then wire it into your editor’s MCP config and let your assistant start logging. The whole thing — server, demo client, README — is ~400 lines including configuration.</p><p>Building small MCP servers like this is, I think, the highest-leverage way to learn the protocol: you touch every concept, you ship something you’ll actually use daily, and the surface area is small enough to understand completely.</p><p>What would <em>your</em> five-line-a-day automation be? An MCP server for your reading list? Your gym log? Your standup notes? Tell me in the comments — and if you build one, link it. 🚀</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0f6d55786c75" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/i-built-an-mcp-server-that-keeps-my-work-journal-heres-everything-i-learned-0f6d55786c75">I Built an MCP Server That Keeps My Work Journal — Here’s Everything I Learned</a> was originally published in <a href="https://javascript.plainenglish.io">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Stop Hand-Writing Database Types: I Built a Code Generator That Reads Your Schema Instead]]></title>
            <link>https://javascript.plainenglish.io/stop-hand-writing-database-types-i-built-a-code-generator-that-reads-your-schema-instead-bd3058b99b57?source=rss-82244dfb6a6a------2</link>
            <guid isPermaLink="false">https://medium.com/p/bd3058b99b57</guid>
            <category><![CDATA[developer-tools]]></category>
            <category><![CDATA[mysql]]></category>
            <category><![CDATA[postgresql]]></category>
            <category><![CDATA[typescrit]]></category>
            <category><![CDATA[sqlite]]></category>
            <dc:creator><![CDATA[Rogerio Amorim]]></dc:creator>
            <pubDate>Sun, 23 Aug 2026 18:00:02 GMT</pubDate>
            <atom:updated>2026-08-23T18:00:02.736Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2SR49_JVOoeY31rGFAazNw.png" /></figure><p><em>db2ts: a ~450-line CLI that introspects SQLite, PostgreSQL or MySQL and emits TypeScript interfaces plus Zod schemas — no ORM, no schema DSL, no drift. Here’s the full story of building it, including the type-mapping rabbit holes nobody warns you about.</em></p><p>Every TypeScript codebase with a database has this file:</p><pre>// user.ts — hand-written, &quot;obviously correct&quot;<br>export interface User {<br>  id: number;<br>  email: string;<br>  display_name?: string;   // is it nullable? who remembers<br>  created_at: Date;        // it&#39;s TEXT in the DB. this lies.<br>}</pre><p>It was correct the day it was written. Then someone shipped a migration adding avatar BYTEA, another renamed display_name, and now the types describe a database that doesn&#39;t exist. The compiler can&#39;t save you because <strong>nothing connects the types to the actual schema</strong>.</p><p>ORMs solve this by owning your schema: you define models, they generate migrations. That’s a big philosophical commitment. Plenty of teams write SQL on purpose — for control, for performance, or because the database already exists and isn’t going anywhere.</p><p>I wanted the third option: <strong>keep SQL as the source of truth and generate the types from it.</strong> Not a framework. A tool you run after migrating, like tsc. So I built db2ts:</p><pre>npx db2ts postgres://user@localhost/mydb --zod -o src/db-types.ts</pre><pre># ✓ users (7 columns)<br># ✓ orders (6 columns)<br># ✅ 12 table(s) → src/db-types.ts</pre><ul><li>💻 Code: <a href="https://github.com/rogeriolaa/db2ts">github.com/rogeriolaa/db2ts</a> (MIT, 63 tests)</li></ul><h3>What you get</h3><p>For every table, an interface where nullability comes from the actual NOT NULL constraints:</p><pre>// AUTO-GENERATED by db2ts from mydb — do not edit by hand.<br>export interface Users {<br>  id: number;                          // PK: required<br>  email: string;                       // NOT NULL: required<br>  display_name?: string | null;        // nullable: `?` + `| null`<br>  balance: number;                     // DECIMAL → number<br>  avatar?: Uint8Array | null;          // BYTEA → Uint8Array<br>  created_at: string;                  // TIMESTAMP → string (honest!)<br>}</pre><pre>export interface Orders { /* ... */ }</pre><p>And with --zod, runtime validation schemas that follow the same rules:</p><pre>export const UsersSchema = z.object({<br>  id: z.number().optional(),                        // auto-increment: DB assigns it<br>  email: z.string(),<br>  display_name: z.string().nullable().optional(),<br>  balance: z.number(),<br>  avatar: z.instanceof(Uint8Array).nullable().optional(),<br>});</pre><p>The workflow becomes: migrate → regenerate → compiler tells you every place the schema change touched. The database finally <em>is</em> your type system.</p><h3>The architecture: adapters + one pure core</h3><p>The whole thing is three moving parts:</p><pre>src/<br>├── cli.mjs            flags, credentials, orchestration (~110 lines)<br>├── cli-core.mjs       pure arg-parsing + credential merging + filters<br>├── core.mjs           pure code generation (no I/O at all)<br>└── adapters/<br>    ├── index.mjs      registry: picks adapter from connection prefix<br>    ├── sqlite.mjs     better-sqlite3 + PRAGMA table_info   (~40 lines)<br>    ├── postgres.mjs   pg + information_schema              (~70 lines)<br>    └── mysql.mjs      mysql2 + information_schema          (~65 lines)</pre><p>The key decision: <strong>adapters normalize everything into one shape</strong>, and the generator never learns which database it came from:</p><pre>{<br>  name: &#39;users&#39;,<br>  columns: [{<br>    name: &#39;email&#39;,<br>    type: &#39;varchar(255)&#39;,<br>    notnull: true,<br>    isPrimaryKey: false,<br>    hasDefault: null,<br>    isAutoIncrement: false,<br>  }],<br>}</pre><p>This is why supporting three databases didn’t triple the work. Postgres reads information_schema.columns; SQLite has its own PRAGMA table_info; each adapter translates its dialect into the normalized form, then hands off. <strong>Adding MySQL support later took one new file and zero changes to the generator.</strong> If you ever need MSSQL or CockroachDB, that&#39;s the template.</p><h3>The type-mapping rabbit holes</h3><p>Now the part the tutorials skip: mapping SQL types to TypeScript sounds trivial until you actually do it. Things I got wrong first:</p><h3>Regex ordering matters more than you’d think</h3><p>My first mapper checked numbers before strings. Then a test failed:</p><pre>sqlToTs(&#39;ENUM(&quot;a&quot;,&quot;b&quot;)&#39;)  // → &quot;number&quot; ?!</pre><p>Why: ENUM(&quot;a&quot;,&quot;b&quot;) contains... nothing numeric. But DECIMAL(10,2) needs the decimal branch, and my ordering let INT match inside other words. The fix wasn&#39;t cleverness — it was <strong>ordering</strong>: string-ish keywords (CHAR|TEXT|ENUM|UUID) must be tested before generic number checks, because SQL type names overlap in ways that bite you:</p><pre>// order of checks:<br>1. SERIAL/BIGSERIAL     → number   (before INT catches the tail)<br>2. CHAR/TEXT/ENUM/UUID  → string   (ENUM(&quot;a&quot;) would otherwise fall through)<br>3. INT/BOOL/YEAR/BIT    → number   (BIT before BLOB! both start &quot;B&quot;)<br>4. REAL/NUMERIC/DECIMAL → number<br>5. BYTEA/BLOB           → Uint8Array<br>6. DATE/TIME            → string</pre><p>That last comment is real: BIT vs BLOB taught me to anchor patterns carefully. Every one of these orderings is now pinned by a test.</p><h3>Nullability has four states, not two</h3><p>Naive thinking: nullable or not. Reality per column:</p><ol><li>NOT NULL → required</li><li>Nullable → ? | null</li><li><strong>Auto-increment primary key</strong> → required in TypeScript (it exists after insert), but .optional() in Zod input schemas (you don&#39;t supply it)</li><li><strong>Text primary key</strong> → required everywhere, plus .min(1) in Zod</li></ol><p>That fourth case came from testing against a real schema with &quot;pk text&quot; TEXT PRIMARY KEY. In Postgres, a PK is implicitly NOT NULL — but if you only read is_nullable, some drivers report it as nullable. The generator now treats isPrimaryKey as required regardless, which matches how databases actually behave.</p><h3>Booleans are a lie (in SQLite)</h3><p>SQLite has no boolean type — everyone stores 0/1 in an INTEGER column. My tests caught the consequence: mapping BOOLEAN to boolean would be <em>wrong</em> for SQLite but right for Postgres. Current answer: map to number (the truth), with a documented future --booleans flag for people who want the prettier lie. Honesty over cosmetics, especially in generated code.</p><h3>mysql2 returns uppercase keys. Sometimes.</h3><p>This one wins the prize. My Postgres adapter read col.column_name (lowercase). The MySQL adapter copied that pattern and broke — because mysql2 returns COLUMN_NAME (uppercase) by default. The fix normalizes both spellings:</p><pre>name: c.COLUMN_NAME ?? c.column_name,</pre><p>An integration test against a live MySQL server caught it in seconds. Which brings me to…</p><h3>Testing strategy: native node:test + real databases</h3><p>I used <strong>Node’s built-in test runner</strong> — node:test, node:assert/strict — zero test dependencies. The suite is 63 tests in two layers:</p><p><strong>Unit layer</strong> (fast, no I/O): the pure functions get exhaustive tables —</p><pre>const cases = [<br>  [&#39;INTEGER&#39;, &#39;number&#39;], [&#39;NUMERIC(10,2)&#39;, &#39;number&#39;], [&#39;ENUM(&quot;a&quot;,&quot;b&quot;)&#39;, &#39;string&#39;],<br>  [&#39;BYTEA&#39;, &#39;Uint8Array&#39;], [&#39;jsonb&#39;, &#39;unknown&#39;], [&#39;weird&#39;, &#39;unknown&#39;],<br>  // ...30+ mappings across all three dialects<br>];<br>for (const [decl, expected] of cases) { /* assert */ }</pre><p><strong>Integration layer</strong> (real servers, skipped when absent): each adapter runs against an actual database server, creates its own tables, introspects them, runs the CLI end-to-end, and asserts on the generated file’s content. The suite even compiles the generated TypeScript under --strict and parses a realistic row through the emitted Zod schema at runtime.</p><pre>npm test                              # unit always run<br>DB2TS_TEST_PG=1 npm test              # + live Postgres<br>DB2TS_TEST_MYSQL=1 npm test           # + live MySQL</pre><p>Integration tests create and clean their own fixtures, so they’re CI-safe — set the env vars only where servers exist. This design caught three real bugs during development (the ENUM ordering, a mysql2 uppercase-keys mismatch, and an ESM/CJS packaging error) that unit tests alone would have missed, because the failures were in the seams between dialects.</p><h3>Features you end up needing immediately</h3><p>Once the happy path worked, three features stopped being optional:</p><p><strong>Credential flags</strong> (-u / -p). Connection strings work (postgres://user:***@host/db), but pasting passwords into shell history is bad hygiene. Flags win over the URL, special characters are URL-encoded when rebuilding connections, and passwords are masked in any error output.</p><p><strong>Table selection</strong> (-t users,orders / -x audit_log,migrations). The killer use: exclude migration and audit tables from generated output. Include-then-execute-exclude semantics, covered by tests in combination.</p><p><strong>Schema selection</strong> (-s public,inventory). Postgres schemas needed explicit support — and multiple schemas produce qualified names (inventory.items) so identically-named tables don&#39;t collide. For MySQL, where schemas <em>are</em> databases, -s acts as a database override alongside -d.</p><h3>Honest limitations</h3><ul><li><strong>JSONB/JSON maps to </strong><strong>unknown.</strong> Real JSON typing needs schema inference — a good v2 feature, not a v1 shortcut.</li><li><strong>Decimals become </strong><strong>number.</strong> JavaScript floats lose precision beyond 2⁵³; financial code wanting exact decimals should wait for the planned --decimal-as-string.</li><li><strong>Dates become </strong><strong>string.</strong> Intentional — drivers return strings, and pretending otherwise generated lies in my old hand-written types.</li><li><strong>No views yet</strong>, only base tables.</li><li><strong>One database per invocation.</strong> Multi-db merging is scriptable via -o today.</li></ul><p>None of these are hidden — they’re in the README.</p><h3>When should you use this vs an ORM?</h3><p>Honest take: if you’re starting greenfield, want migrations-managed-for-you, and like query builders — use Drizzle or Prisma. Their type generation is excellent <em>because</em> they own the schema.</p><p>db2ts is for the other world, which I suspect is bigger than Twitter admits: existing databases, teams that write SQL deliberately, stored-procedure shops, microservices sharing one read-only analytics DB, or anyone whose &quot;types&quot; have silently drifted from production. It&#39;s also genuinely useful <em>alongside</em> an ORM — generating read-model types from a reporting replica while the ORM owns the transactional side.</p><h3>Try it</h3><pre>git clone https://github.com/rogeriolaa/db2ts &amp;&amp; cd db2ts<br>npm install<br>DB2TS_TEST_PG=1 npm test        # 63 tests incl. live-database integration</pre><p>Or point it at your own database right now:</p><pre>npx db2ts &quot;$DATABASE_URL&quot; --zod --camel -o src/db-types.ts</pre><p>Then add it next to your migration step and enjoy the rarest feeling in backend development: <strong>finding out your types were wrong from the compiler instead of production.</strong></p><p>What does your team do today to keep DB types honest — ORM, handwritten, or vibes? Tell me in the comments; and if you build an adapter for another database on top of this, I’d love to link it. 🚀</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bd3058b99b57" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/stop-hand-writing-database-types-i-built-a-code-generator-that-reads-your-schema-instead-bd3058b99b57">Stop Hand-Writing Database Types: I Built a Code Generator That Reads Your Schema Instead</a> was originally published in <a href="https://javascript.plainenglish.io">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[I Built a Real-Time App With 1.7 KB of JavaScript — No Framework, No Build Step]]></title>
            <link>https://javascript.plainenglish.io/i-built-a-real-time-app-with-1-7-kb-of-javascript-no-framework-no-build-step-032005161ce1?source=rss-82244dfb6a6a------2</link>
            <guid isPermaLink="false">https://medium.com/p/032005161ce1</guid>
            <category><![CDATA[websocket]]></category>
            <category><![CDATA[web-performance]]></category>
            <category><![CDATA[server-side-rendering]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Rogerio Amorim]]></dc:creator>
            <pubDate>Sat, 22 Aug 2026 21:39:07 GMT</pubDate>
            <atom:updated>2026-08-22T21:39:07.250Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dx4KbRwERexaZQpFBRttzQ.png" /></figure><p><em>HTML over WebSockets: the server renders everything, the client just swaps fragments. Here’s what a fully reactive dashboard looks like when you delete the framework from the equation.</em></p><p>Modern front-end development has a default answer to “real-time updates”: a SPA framework, a state management layer, a virtual DOM, a bundler, and a hydration pipeline. That stack is great for large products. But it’s worth asking an uncomfortable question:</p><p><strong>If the server already knows what changed… why are we shipping a rendering engine to the browser to figure it out again?</strong></p><p>There’s an older pattern that answers this: <strong>render HTML on the server and push it over WebSockets</strong>. The client never parses JSON, never diff-anything, never re-renders. It receives ready-made HTML and swaps it into place.</p><p>To find out how far that idea actually goes in 2026, I built a complete real-time support-ticket dashboard with it — live stats, add/change/delete across clients — using <strong>zero frameworks</strong>. The entire client-side JavaScript weighs <strong>1,772 bytes</strong>. This article walks through exactly how it works.</p><h4>The architecture in one picture</h4><pre>┌──────────────┐   user intents (JSON)    ┌──────────────────┐<br>│   Browser    │ ───────────────────────▶ │      Server      │<br>│              │                          │                  │<br>│  swaps HTML  │ ◀─────────────────────── │  mutates state,  │<br>│  fragments   │   HTML fragments         │  renders HTML    │<br>└──────────────┘                          └──────────────────┘</pre><p>Two channels, opposite directions:</p><ol><li><strong>Up (client → server):</strong> tiny JSON messages describing <em>intents</em> — {action: &#39;change-status&#39;, id: 2, status: &#39;done&#39;}.</li><li><strong>Down (server → client):</strong> HTML fragments describing <em>results</em>. The server owns the entire state; whenever it changes, it renders only the affected fragment and broadcasts it to every connected client.</li></ol><p>That second point is the killer feature nobody talks about: because the server broadcasts rendered results rather than raw data, <strong>multi-user sync comes almost for free</strong>. There’s one source of truth, and every open tab converges to it.</p><h4>The whole client</h4><p>Here is <em>all</em> the JavaScript this application has. Not pseudocode — the complete file:</p><pre>// One WebSocket for the whole page.<br>const socket = new WebSocket(`ws://${location.host}`);<br> <br>// Server pushes HTML fragments; we apply them with 3 tiny helpers.<br>socket.onmessage = (event) =&gt; {<br>  const tpl = document.createElement(&#39;template&#39;);<br>  tpl.innerHTML = event.data;<br> <br>  // Out-of-band swaps: elements carrying an id replace their twin.<br>  for (const node of [...tpl.content.querySelectorAll(&#39;[id]&#39;)]) {<br>    const existing = document.getElementById(node.id);<br>    if (existing) existing.replaceWith(node);<br>  }<br>  // Deletion marker: an empty row carrying data-delete-id removes its twin.<br>  for (const marker of [...tpl.content.querySelectorAll(&#39;[data-delete-id]&#39;)]) {<br>    document.querySelector(`[data-row-id=&quot;${marker.dataset.deleteId}&quot;]`)?.remove();<br>  }<br>};<br> <br>function send(msg) {<br>  socket.send(JSON.stringify(msg));<br>}<br> <br>// Event delegation: every interactive element declares data-action.<br>document.addEventListener(&#39;submit&#39;, (e) =&gt; {<br>  if (e.target.id === &#39;new-ticket&#39;) {<br>    e.preventDefault();<br>    const fd = new FormData(e.target);<br>    send({ action: &#39;add&#39;, title: fd.get(&#39;title&#39;), priority: fd.get(&#39;priority&#39;) });<br>    e.target.reset();<br>  }<br>});<br> <br>document.addEventListener(&#39;change&#39;, (e) =&gt; {<br>  if (e.target.dataset.action === &#39;change-status&#39;) {<br>    send({ action: &#39;change-status&#39;, id: e.target.dataset.id, status: e.target.value });<br>  }<br>});<br> <br>document.addEventListener(&#39;click&#39;, (e) =&gt; {<br>  if (e.target.dataset.action === &#39;delete&#39;) {<br>    send({ action: &#39;delete&#39;, id: e.target.dataset.id });<br>  }<br>});</pre><p>That’s it. Three ideas do all the work:</p><h4>1. Fragments replace their twins by id</h4><p>When a stat changes, the server sends &lt;div id=&quot;stats&quot; class=&quot;stats&quot;&gt;...&lt;/div&gt;. The client finds the existing #stats element and replaces it. When the whole table changes, the server sends a fresh &lt;tbody id=&quot;tickets&quot;&gt;. Same rule everywhere: <em>if it has an id, it&#39;s swappable</em>. No diffing, no keys, no reconciliation algorithm — the server simply says &quot;this is the new truth for region X.&quot;</p><h4>2. Deletions use a marker protocol</h4><p>You can’t “swap” something that should disappear, so deletions travel as an empty row carrying data-delete-id. The client reads it and removes the matching [data-row-id]. Two lines of code, and it&#39;s still pure HTML semantics — no custom message format to parse.</p><p>This was actually the one bug I hit building the demo: my first version tried to broadcast executable &lt;script&gt; tags for deletions, which don&#39;t run when inserted via innerHTML. The marker approach fixed it <em>and</em> made the design more honest — the client interprets two declarative rules instead of executing remote code.</p><h4>3. Event delegation replaces component logic</h4><p>Instead of attaching listeners per element (which you’d have to re-attach after every swap), three global listeners catch submit, change, and click events bubbling up from anywhere. Interactive elements declare intent via data-action attributes:</p><pre>&lt;select data-action=&quot;change-status&quot; data-id=&quot;2&quot;&gt;<br>&lt;button data-action=&quot;delete&quot; data-id=&quot;2&quot;&gt;</pre><p>Because listeners hang off document, freshly-swapped fragments are interactive the instant they land. Zero wiring.</p><h4>The server</h4><p>The server is a single Node file (~180 lines) with no dependencies beyond ws. It has three responsibilities:</p><p><strong>Render functions</strong> — plain string templates, each owning one UI region:</p><pre>function statsHtml() {<br>  const open = tickets.filter((t) =&gt; t.status !== &#39;done&#39;).length;<br>  return `<br>    &lt;div class=&quot;stat&quot;&gt;&lt;strong&gt;${tickets.length}&lt;/strong&gt;&lt;span&gt;total&lt;/span&gt;&lt;/div&gt;<br>    &lt;div class=&quot;stat&quot;&gt;&lt;strong&gt;${open}&lt;/strong&gt;&lt;span&gt;not done&lt;/span&gt;&lt;/div&gt;`;<br>}</pre><p>Note what’s encoded right there: the same function renders the initial page <em>and</em> every subsequent update. First paint and live updates can’t drift apart, because they’re literally the same code path. In most SPAs these are two different systems (SSR/hydration vs. client re-render).</p><p><strong>Intent handling</strong> — mutate state, then broadcast only what changed:</p><pre>case &#39;change-status&#39;: {<br>  const ticket = findTicket(msg.id);<br>  if (!ticket || !STATUSES.includes(msg.status)) return;<br>  ticket.status = msg.status;<br>  broadcast(ticketRowHtml(ticket));                       // just the one row<br>  broadcast(`&lt;div id=&quot;stats&quot; ...&gt;${statsHtml()}&lt;/div&gt;`);  // stats depend on status too<br>  break;<br>}</pre><p>That last line is the entire “state management system”: when an effect reaches another region, you broadcast that region too. Explicit, greppable, zero magic.</p><p><strong>Broadcasting</strong> — every connected client receives the same fragments:</p><pre>function broadcast(html) {<br>  for (const client of wss.clients) {<br>    if (client.readyState === client.OPEN) client.send(html);<br>  }<br>}</pre><p>And that’s why multi-user sync works: user B changes a status, and user A’s screen updates without A doing anything. One writer, many readers, no merge conflicts.</p><h4>What the numbers look like</h4><p><strong>Metric:</strong> Client JS shipped<br><strong>This app:</strong> <strong>1,772 bytes</strong><br><strong>Typical React equivalent:</strong> 45–150 KB min+gzip</p><p><strong>Metric:</strong> Dependencies<br><strong>This app:</strong> 1 (ws)<br><strong>Typical React equivalent:</strong> hundreds</p><p><strong>Metric:</strong> Build step<br><strong>This app:</strong> none<br><strong>Typical React equivalent:</strong> bundler + config</p><p><strong>Metric:</strong> Hydration time<br><strong>This app:</strong> none needed<br><strong>Typical React equivalent:</strong> grows with tree size</p><p><strong>Metric:</strong> Time-to-first-paint content<br><strong>This app:</strong> immediate (server-rendered)<br><strong>Typical React equivalent:</strong> after JS parses/executes</p><p>No build tooling means the project runs with node server.js — no webpack, no vite config, no dependency audit anxiety.</p><h4>The honest trade-offs</h4><p>I’m not going to pretend this scales to everything. Here’s the straight list:</p><p><strong>Where this pattern shines:</strong></p><ul><li>Dashboards, admin panels, monitoring screens, chat, notifications, live tables — anything where <em>the server holds the truth</em> and the client displays it</li><li>Multi-user views that must stay in sync (the demo’s core trick)</li><li>Internal tools where SEO doesn’t matter but reliability does</li></ul><p><strong>Where it doesn’t:</strong></p><ul><li>Heavy offline/PWA requirements — there’s no local model of the state to work with</li><li>Rich per-pixel interactivity (drag-and-drop editors, canvas tools, animations driven by local state)</li><li>Very high-frequency updates — at some point you’re shipping more HTML than JSON would weigh; that’s when you switch specific regions to targeted JSON patches</li><li>Public apps needing fine-grained optimistic UI — every interaction round-trips the server</li></ul><p>Also worth saying: with two users editing simultaneously, <strong>last write wins</strong>. Fine for tickets, wrong for documents — that’s CRDT territory.</p><p>One subtle cost: swapping a large &lt;tbody&gt; re-creates all its rows, so focus, selection, and mid-scroll state inside that region reset. Keep your swap regions small and stateful controls outside them.</p><h4>The bigger lesson</h4><p>What surprised me most wasn’t the byte count — it was how little <em>conceptual</em> machinery the pattern needs. The entire mental model fits in one sentence: <strong>the server knows the truth and mails out pictures of it; the client tapes new pictures over old ones.</strong></p><p>No hooks rules. No dependency arrays. No stale-closure bugs. No “why did this effect fire twice.” The complexity budget went into the product instead of the rendering pipeline.</p><p>If this resonates, look into the ecosystems built around the same philosophy: <a href="https://htmx.org">htmx</a> (hypermedia-driven apps over HTTP), <a href="https://www.phoenixframework.org/">LiveView</a> (Elixir’s battle-tested version), <a href="https://hotwired.dev">Hotwire/Turbo</a> (Rails’ take), and <a href="https://data-star.dev">Datastar</a>. My demo is the hand-rolled version so the mechanics stay visible — those frameworks industrialize it.</p><h4>Try it</h4><p>The full project is ~300 lines total across four files:</p><pre>git clone https://github.com/rogeriolaa/html-over-websockets<br>cd html-over-websockets<br>npm install &amp;&amp; npm start     # http://localhost:3000</pre><p>Open it in two windows side by side. Add a ticket in one, change its status in the other, and watch both screens converge — with less JavaScript than a single medium-sized React component.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=032005161ce1" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/i-built-a-real-time-app-with-1-7-kb-of-javascript-no-framework-no-build-step-032005161ce1">I Built a Real-Time App With 1.7 KB of JavaScript — No Framework, No Build Step</a> was originally published in <a href="https://javascript.plainenglish.io">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Goodbye Boilerplate: How validateStandardSchema Made Zod + Angular Signal Forms Finally Click ]]></title>
            <link>https://javascript.plainenglish.io/goodbye-boilerplate-how-validatestandardschema-made-zod-angular-signal-forms-finally-click-8d610873b05a?source=rss-82244dfb6a6a------2</link>
            <guid isPermaLink="false">https://medium.com/p/8d610873b05a</guid>
            <category><![CDATA[signal]]></category>
            <category><![CDATA[validation]]></category>
            <category><![CDATA[forms]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[zod]]></category>
            <dc:creator><![CDATA[Rogerio Amorim]]></dc:creator>
            <pubDate>Fri, 26 Dec 2025 11:49:37 GMT</pubDate>
            <atom:updated>2025-12-26T18:45:59.841Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8q2PURbNCl6klcwn-f9FuQ.png" /></figure><p>Angular quietly added the validation helper we always needed — now you can ditch validateTree, keep your Zod schemas, and enjoy form validation that feels <em>built-in</em> 🚀</p><p>You can wire Zod into Angular Signal Forms with just one helper and delete a bunch of noisy validation code 💥. validateStandardSchema turns what used to be a hand-rolled integration into a single, readable line that scales beautifully as your forms grow.​</p><h3>Why Angular devs love Zod</h3><p>If you’re building modern Angular apps, you’ve probably noticed a pattern: every serious project eventually needs runtime validation that matches your TypeScript types, not just “hope-for-the-best” interfaces. Zod solves exactly that by letting you define schemas that are both TS types and runtime validators in one place.</p><p>This means your form model, API contracts, and validation rules can all point to the same <strong>schema</strong>, instead of being copy-pasted across components, DTOs, and “helpers-final-final.ts” files 😅.</p><ul><li>Zod schemas are composable (objects, arrays, unions, refinements, etc.).</li><li>You get rich error messages and safe parsing out of the box.</li><li>TypeScript infers types directly from your Zod schemas, not the other way around.</li></ul><h3>Signal Forms in one minute</h3><p>Angular’s new Signal Forms API drops the old FormGroup mental model and leans into signals for form state and validation. Instead of juggling FormControl, FormGroup, and change detection quirks, you work with a reactive model and a schema function that attaches validation to your fields.</p><p>​At its core, you typically do something like:</p><ul><li>Define a <strong>model signal</strong> with your form’s shape.</li><li>Call form(model, schemaFn) to create a Signal Form tree.</li><li>Use the field directive in your template so the UI stays in sync with the form state.</li></ul><p>Validation hooks into that schemaFn, which receives a schema path tree describing every field in your form. That’s where the fun starts.</p><h3>The “before” era: manual Zod wiring</h3><p>Before validateStandardSchema, the common pattern was to plug Zod into Signal Forms using validate() or even validateTree() with a custom adapter.</p><p>That usually meant:</p><ul><li>Running zodSchema.safeParse(ctx.value()) on every form change.</li><li>Translating Zod’s error format into the ValidationError structure Signal Forms expects.</li><li>Manually mapping those errors back to individual fields so the UI knows what to show.</li></ul><p>It worked, but it felt like doing your own plumbing in a house that already has pipes 🚰:</p><ul><li>Extra boilerplate to maintain as your schema grows.</li><li>Custom error mapping that you’re secretly terrified to touch.</li><li>More room for bugs whenever you change fields or validation rules.</li></ul><p>In other words, Signal Forms + Zod was powerful, but the integration layer was “DIY advanced”. validateStandardSchema changes that balance completely.</p><h3>Enter validateStandardSchema: the one-liner upgrade</h3><p>Angular now ships a helper specifically designed for schema-based validators like Zod, Valibot, and friends: validateStandardSchema. This function understands the Standard Schema spec that Zod can conform to, and it plugs directly into Signal Forms’ validation lifecycle.</p><p>The basic pattern looks like this:</p><pre>import { form, validateStandardSchema } from &#39;@angular/forms/signals&#39;;<br>import * as z from &#39;zod&#39;;<br><br>const userSchema = z.object({<br>  email: z.string().email(),<br>  password: z.string().min(8),<br>});<br><br>type User = z.infer&lt;typeof userSchema&gt;;<br><br>const model = signal&lt;User&gt;({ email: &#39;&#39;, password: &#39;&#39; });<br><br>const userForm = form(model, (schemaPath) =&gt; {<br>  validateStandardSchema(schemaPath, userSchema);<br>});</pre><ul><li>schemaPath represents your form’s shape; it’s the root of your Signal Form tree.</li><li>validateStandardSchema receives that path plus a schema that follows the StandardSchemaV1 contract, which Zod can implement.</li><li>Angular runs the schema automatically when values change, maps errors, and updates state for you.</li></ul><p>No manual safeParse, no hand-written error adapters, no custom “if success return undefined else mapErrors()” gymnastics.</p><h3>What validateStandardSchema does for you (behind the scenes)</h3><p>Under the hood, validateStandardSchema acts like a translator between your Zod schema and Angular’s validation engine.</p><p>​It handles:</p><ul><li><strong>Execution</strong>: Runs your schema against the form value whenever relevant fields change.</li><li><strong>Error mapping</strong>: Converts schema validation errors into Signal Forms’ ValidationError format.</li><li><strong>Field wiring</strong>: Connects errors back to the correct fields in the schema path tree.</li><li><strong>State updates</strong>: Keeps valid, invalid, errors, and related signals in sync, so your template “just works”.</li></ul><p>From your perspective, it feels like built-in validation:</p><ul><li>You keep Zod as the single source of truth.</li><li>Angular owns when to validate and how to propagate errors.</li><li>Your template binds to fields and error states like any other Signal Form.</li></ul><p>It’s like telling Angular: “Here’s my <strong>schema</strong>, you babysit the form state for me.” 😎</p><h3>Progressive refactor: from manual logic to one-liner</h3><p>Imagine you have an existing Signal Form already wired to Zod via validateTree. It might look roughly like this (conceptually):​​</p><ul><li>Call form(model, schemaFn).</li><li>Inside schemaFn, use validateTree(schemaPath, ctx =&gt; { ... }).</li><li>Inside that callback:</li><li>Run Zod validation on ctx.value().</li><li>If success, return undefined.</li><li>If failure, manually map each Zod issue into a field-level error structure.</li></ul><p>To refactor to validateStandardSchema, your steps become progressively simpler:</p><ul><li><strong>Extract or confirm your Zod schema</strong><br> Ensure your schema fully describes the form model: fields, types, and constraints.</li><li><strong>Remove the custom validateTree block</strong><br> Delete the validateTree call and its mapping logic from the schema function.</li><li><strong>Call validateStandardSchema instead</strong><br> Inside your form schema function, replace the entire validation block with:</li></ul><pre>validateStandardSchema(schemaPath, myZodSchema);</pre><p>This line expresses your intent clearly: “validate this form with that schema.”</p><ul><li><strong>Keep your template as-is</strong><br> Since Signal Forms still manage state the same way, your field bindings, error messages, and submit handling don’t need to change.</li></ul><p>You’ve gone from custom plumbing to a single declarative call, while preserving the same UX and validation semantics.​</p><h3>Real-world benefits: why this pattern scales</h3><p>For small demos, extra validation glue code doesn’t feel too bad. But once the app grows, validateStandardSchema starts paying serious dividends.</p><p>​<strong>1. Less code, fewer bugs</strong></p><ul><li>You delete custom error mappers that inevitably drift out of sync with your schema.</li><li>Angular handles schema execution and error propagation consistently.</li><li>Refactors become safer: when the schema changes, you don’t have to hunt through validation helpers.</li></ul><p><strong>2. Single source of truth</strong></p><ul><li>Zod remains the <strong>single</strong> authoritative definition of your data shape and constraints.</li><li>The same schema can serve: form validation, API payload validation, possibly server-side validation too, if you share code.</li></ul><p><strong>3. Cleaner mental model</strong></p><ul><li>“Form shape lives in the model, validation rules live in Zod, wiring is one line in the schema function.”</li><li>No need to remember Signal Forms’ internal error format.</li><li>New team members can understand the setup in minutes, not hours.</li></ul><h3>Going further: complex forms, arrays, and composition</h3><p>Signal Forms and schema validators pair nicely when forms get more complex: nested objects, arrays of items, multi-step flows, etc.</p><p>​A few patterns that work well:</p><ul><li><strong>Nested schemas</strong>: Use Zod object composition (e.g., addressSchema, userSchema.extend({ address: addressSchema })) and let validateStandardSchema handle the nested paths.</li><li><strong>Arrays of items</strong>: Model lists (e.g., line items, tags, attendees) as z.array(...) in Zod and as arrays in your Signal Form model; the helper still understands how to validate them.</li><li><strong>Reusable validation rules</strong>: Extract Zod schemas per feature domain (auth, billing, settings) and plug them into forms via the same pattern:</li></ul><pre>form(model, (schemaPath) =&gt; {   validateStandardSchema(schemaPath, domainSchema); });</pre><p>As your app grows, the pattern stays the same while your schemas get richer. That’s the kind of stability that makes a codebase feel “senior-level” 🌱.</p><h3>Wrap-up: from DIY wiring to native-like UX</h3><p>Angular Signal Forms already give you a modern, signal-first way to handle form state. Zod gives you type-safe, expressive validation that doubles as runtime guarantees. validateStandardSchema is the missing puzzle piece that snaps them together without ceremony.</p><p>​If your current setup still includes manual Zod parsing and custom error mapping, you’re basically doing what the framework can now do for you automatically. Swapping that out for a one-line schema integration is one of those rare refactors that gives you:</p><ul><li>Less code.</li><li>Fewer bugs.</li><li>Cleaner intent.</li><li>The exact same UX — just easier to maintain.</li></ul><p>If this walkthrough helped you simplify your forms and save a few lines (or a few headaches 😅), hit that 👏 <strong>clap button</strong> to spread the good vibes! Each clap helps more Angular devs discover this trick and clean up their projects.</p><p>And hey — don’t keep the secret to yourself. Share this article with your favorite dev group, tweet it, or drop it in your team’s chat. Let’s make boilerplate cleanup the new holiday tradition 🎄🔥</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8d610873b05a" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/goodbye-boilerplate-how-validatestandardschema-made-zod-angular-signal-forms-finally-click-8d610873b05a">Goodbye Boilerplate: How validateStandardSchema Made Zod + Angular Signal Forms Finally Click 💡</a> was originally published in <a href="https://javascript.plainenglish.io">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[React 19.2 Just Revolutionized Async — Say Goodbye to useEffect!]]></title>
            <link>https://javascript.plainenglish.io/react-19-2-just-revolutionized-async-say-goodbye-to-useeffect-698d01682bac?source=rss-82244dfb6a6a------2</link>
            <guid isPermaLink="false">https://medium.com/p/698d01682bac</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[optimization]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Rogerio Amorim]]></dc:creator>
            <pubDate>Fri, 24 Oct 2025 11:35:27 GMT</pubDate>
            <atom:updated>2025-10-27T17:02:21.504Z</atom:updated>
            <content:encoded><![CDATA[<h3>React 19.2 Just Revolutionized Async — Say Goodbye to useEffect!</h3><h4>A deep dive into Suspense, use, and GPU-powered ViewTransitions</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TQEFj1N8EmsJ1iyS7tIs3Q.jpeg" /></figure><p>Remember when you first learned React and thought “useEffect seems complicated, but I’m sure it’ll make sense eventually”?</p><p><strong>Narrator voice:</strong> <em>It did not make sense eventually.</em></p><p>Here’s the truth nobody tells you: we’ve all been doing async the hard way. While you were juggling useEffect, useState, and trying to remember which dependency array combination wouldn&#39;t trigger infinite re-renders, React&#39;s core team was cooking up something beautiful.​</p><p>React 19.2 just dropped, and it’s basically saying “remember all those patterns you learned? Yeah, forget them”. But before you rage-quit, hear me out — this is actually <em>good news.</em></p><h3>The Intervention We All Needed</h3><p>Let’s talk about the old way of doing things. You know, the way that makes junior devs cry and senior devs pretend they understand:youtube​</p><pre>function ImageGallery() {<br>  const [imageId, setImageId] = useState(1);<br>  const [imageData, setImageData] = useState(null);<br>  const [isPending, setIsPending] = useState(false);<br>  <br>  useEffect(() =&gt; {<br>    setIsPending(true);<br>    fetchImage(imageId)<br>      .then(response =&gt; {<br>        setImageData(response);<br>        setIsPending(false);<br>      })<br>      .catch(error =&gt; {<br>        // TODO: handle error (narrator: they never handled the error)<br>        setIsPending(false);<br>      });<br>  }, [imageId]); // Don&#39;t forget this or React will yell at you<br>  <br>  return (<br>    &lt;div&gt;<br>      {isPending ? (<br>        &lt;ImageSkeleton /&gt;<br>      ) : (<br>        &lt;Image data={imageData} /&gt;<br>      )}<br>      &lt;button onClick={() =&gt; setImageId(id =&gt; id + 1)}&gt;<br>        Next Image<br>      &lt;/button&gt;<br>    &lt;/div&gt;<br>  );<br>}</pre><p>If this looks like your code, congratulations! You’ve been doing React on hard mode.</p><h3>Plot Twist: There’s a Better Way</h3><p>React 19.2 introduces a radically simpler approach that’ll make you question your entire frontend career. Three new superpowers: <strong>Suspense</strong>, <strong>use</strong>, and <strong>ViewTransition</strong>.​</p><p>Here’s the same component, but written by someone who’s ascended to React enlightenment:</p><pre>import { Suspense, use, useState } from &#39;react&#39;;<br><br>function ImageGallery() {<br>  const [imageId, setImageId] = useState(1);<br>  const [imageDataPromise, setImageDataPromise] = useState(<br>    () =&gt; fetchImage(1)<br>  );<br>  <br>  return (<br>    &lt;div&gt;<br>      &lt;Suspense fallback={&lt;ImageSkeleton /&gt;}&gt;<br>        &lt;Image imageDataPromise={imageDataPromise} /&gt;<br>      &lt;/Suspense&gt;<br>      &lt;button onClick={() =&gt; {<br>        const nextId = imageId + 1;<br>        setImageId(nextId);<br>        setImageDataPromise(fetchImage(nextId));<br>      }}&gt;<br>        Next Image<br>      &lt;/button&gt;<br>    &lt;/div&gt;<br>  );<br>}<br><br>function Image({ imageDataPromise }) {<br>  const image = use(imageDataPromise); // 🪄 Magic happens here<br>  <br>  return (<br>    &lt;div&gt;<br>      &lt;h3&gt;{image.title}&lt;/h3&gt;<br>      &lt;img src={image.url} alt={image.title} /&gt;<br>    &lt;/div&gt;<br>  );<br>}</pre><p><strong>Zero</strong> useEffect. <strong>Zero</strong> manual loading states. <strong>Zero</strong> tears.​</p><h3>But Wait, It Gets Weirder (In a Good Way)</h3><p>The use hook does something that would get you fired in any other codebase: <em>it throws promises as exceptions</em>.​</p><p>I know what you’re thinking: “Exceptions for control flow? That’s a war crime against computer science!”</p><p>But here’s why it’s actually genius: when a component deep in your tree needs async data, how does it tell its great-great-grandparent Suspense boundary to show a loading state? It <em>literally</em> throws the promise up the component tree until Suspense catches it.​</p><pre>// Somewhere deep in your component tree<br>function DeepNestedComponent({ dataPromise }) {<br>  const data = use(dataPromise); <br>  // ^ This throws the promise if it&#39;s not ready<br>  // React catches it, shows fallback, waits for promise<br>  // Then re-renders when ready. Chef&#39;s kiss. 🤌<br>  <br>  return &lt;div&gt;{data.value}&lt;/div&gt;;<br>}</pre><p>The alternative? Manually propagating loading states through 47 layers of props. No thank you.</p><h3>Level Up: Actions and useTransition</h3><p>Now let’s add some spice. What if you want that button to <em>look</em> disabled while loading? React 19.2 has entered the chat with action props:<a href="https://react.dev/reference/react/useTransition">react</a>​</p><pre>import { useTransition } from &#39;react&#39;;<br>function ImageGallery() {<br>  const [imageId, setImageId] = useState(1);<br>  const [imageDataPromise, setImageDataPromise] = useState(<br>    () =&gt; fetchImage(1)<br>  );<br>  const [isPending, startTransition] = useTransition();<br>  <br>  const handleNextImage = () =&gt; {<br>    startTransition(() =&gt; {<br>      const nextId = imageId + 1;<br>      setImageId(nextId);<br>      setImageDataPromise(fetchImage(nextId));<br>    });<br>  };<br>  <br>  return (<br>    &lt;div&gt;<br>      &lt;Suspense fallback={&lt;ImageSkeleton /&gt;}&gt;<br>        &lt;Image imageDataPromise={imageDataPromise} /&gt;<br>      &lt;/Suspense&gt;<br>      &lt;button <br>        action={handleNextImage} // 👈 Blessed prop name<br>        disabled={isPending}<br>      &gt;<br>        {isPending ? &#39;Loading...&#39; : &#39;Next Image&#39;}<br>      &lt;/button&gt;<br>    &lt;/div&gt;<br>  );<br>}</pre><p>The action prop tells React &quot;hey, this triggers async work in a Suspense boundary&quot;. React handles the coordination. You handle the coffee.​</p><h3>The Final Boss: ViewTransition</h3><p>Okay, this is where things get <em>unreasonably</em> cool.</p><p>Remember when you needed JavaScript animation libraries to make smooth transitions? Remember when you’d reach for Framer Motion or React Spring just to fade an image in?</p><p>React 19.2 said “what if we just… used the browser’s GPU instead?”</p><pre>import { ViewTransition } from &#39;react&#39;;<br><br>function ImageGallery() {<br>  const [imageId, setImageId] = useState(1);<br>  const [imageDataPromise, setImageDataPromise] = useState(<br>    () =&gt; fetchImage(1)<br>  );<br>  <br>  return (<br>    &lt;div&gt;<br>      &lt;Suspense fallback={<br>        &lt;ViewTransition name=&quot;image-skeleton&quot;&gt;<br>          &lt;ImageSkeleton /&gt;<br>        &lt;/ViewTransition&gt;<br>      }&gt;<br>        &lt;ViewTransition name=&quot;image-content&quot;&gt;<br>          &lt;Image <br>            key={imageId} // Important for transitions!<br>            imageDataPromise={imageDataPromise} <br>          /&gt;<br>        &lt;/ViewTransition&gt;<br>      &lt;/Suspense&gt;<br>      &lt;button onClick={() =&gt; {<br>        const nextId = imageId + 1;<br>        setImageId(nextId);<br>        setImageDataPromise(fetchImage(nextId));<br>      }}&gt;<br>        Next Image<br>      &lt;/button&gt;<br>    &lt;/div&gt;<br>  );<br>}</pre><p>Add some CSS magic:</p><pre>::view-transition-old(image-content),<br>::view-transition-new(image-content) {<br>  animation-duration: 0.3s;<br>}<br>::view-transition-old(image-content) {<br>  animation-name: fadeOut;<br>}<br>::view-transition-new(image-content) {<br>  animation-name: fadeIn;<br>}<br>@keyframes fadeOut {<br>  to { opacity: 0; transform: scale(0.95); }<br>}<br>@keyframes fadeIn {<br>  from { opacity: 0; transform: scale(1.05); }<br>}</pre><p>Boom. Buttery smooth, GPU-accelerated transitions. No JavaScript libraries. No performance overhead. Just pure browser power.​</p><h3>The “But Actually” Section</h3><p><strong>“Isn’t this just TanStack Query with extra steps?”</strong></p><p>Fair question! TanStack Query is <em>amazing</em> and you should absolutely keep using it if it works for you. Think of React 19.2’s built-in tools as “TanStack Query Lite” — perfect for simpler use cases, but you’ll still want the real deal for advanced caching, mutations, and optimistic updates.​</p><pre>// TanStack Query version - still perfectly valid!<br>import { useQuery } from &#39;@tanstack/react-query&#39;;<br><br>function ImageGallery() {<br>  const [imageId, setImageId] = useState(1);<br>  const { data, isPending } = useQuery({<br>    queryKey: [&#39;image&#39;, imageId],<br>    queryFn: () =&gt; fetchImage(imageId)<br>  });<br>  <br>  // Simpler for this use case, honestly<br>}</pre><p><strong>“What about browser support?”</strong></p><p>The View Transition API now works in Chrome, Edge, Safari, AND Firefox. We’ve officially entered the golden age where you don’t need 47 polyfills.​</p><p><strong>“Is this production-ready?”</strong></p><p>Suspense and use? Absolutely. ViewTransition? It&#39;s experimental, so your TypeScript might complain (just tell it to chill with // @ts-ignore). But it works beautifully.​</p><h3>The Migration Path (Or: How to Convince Your Tech Lead)</h3><p>You don’t need to rewrite your entire app overnight. Start small:​</p><ol><li><strong>Find one </strong><strong>useEffect + </strong><strong>useState combo</strong> that&#39;s been annoying you</li><li><strong>Refactor it to </strong><strong>Suspense + </strong><strong>use</strong> (15 minutes, I promise)</li><li><strong>Show your team</strong> the before/after code</li><li><strong>Watch them weep</strong> with joy (or confusion, either works)</li><li><strong>Gradually adopt</strong> across more components</li></ol><p>Here’s a side-by-side migration example:</p><pre>// BEFORE: The old guard<br>function UserProfile({ userId }) {<br>  const [user, setUser] = useState(null);<br>  const [loading, setLoading] = useState(true);<br>  const [error, setError] = useState(null);<br>  <br>  useEffect(() =&gt; {<br>    setLoading(true);<br>    fetchUser(userId)<br>      .then(data =&gt; {<br>        setUser(data);<br>        setLoading(false);<br>      })<br>      .catch(err =&gt; {<br>        setError(err);<br>        setLoading(false);<br>      });<br>  }, [userId]);<br>  <br>  if (loading) return &lt;Spinner /&gt;;<br>  if (error) return &lt;Error error={error} /&gt;;<br>  return &lt;div&gt;{user.name}&lt;/div&gt;;<br>}<br><br>// AFTER: The new hotness<br>function UserProfile({ userId }) {<br>  const [userPromise, setUserPromise] = useState(<br>    () =&gt; fetchUser(userId)<br>  );<br>  <br>  return (<br>    &lt;Suspense fallback={&lt;Spinner /&gt;}&gt;<br>      &lt;UserData userPromise={userPromise} /&gt;<br>    &lt;/Suspense&gt;<br>  );<br>}<br>function UserData({ userPromise }) {<br>  const user = use(userPromise);<br>  return &lt;div&gt;{user.name}&lt;/div&gt;;<br>}</pre><p>Lines of code? <strong>Down by 40%</strong>. Bugs related to race conditions and stale state? <strong>Gone</strong>. Your sanity? <strong>Restored</strong>.​</p><h3>Advanced Patterns (For the Overachievers)</h3><h3>Parallel Loading</h3><p>Need to load multiple things at once? Just call use multiple times:​</p><pre>function Dashboard() {<br>  const [userPromise] = useState(() =&gt; fetchUser());<br>  const [postsPromise] = useState(() =&gt; fetchPosts());<br>  const [statsPromise] = useState(() =&gt; fetchStats());<br>  <br>  return (<br>    &lt;Suspense fallback={&lt;FullPageLoader /&gt;}&gt;<br>      &lt;UserInfo userPromise={userPromise} /&gt;<br>      &lt;PostsList postsPromise={postsPromise} /&gt;<br>      &lt;StatsWidget statsPromise={statsPromise} /&gt;<br>    &lt;/Suspense&gt;<br>  );<br>}<br>function UserInfo({ userPromise }) {<br>  const user = use(userPromise); // These all resolve in parallel! 🚀<br>  return &lt;div&gt;{user.name}&lt;/div&gt;;<br>}</pre><h3>Progressive Loading (The Netflix Special)</h3><p>Want some parts to load faster than others? Nested Suspense boundaries, baby:​</p><pre>function VideoPage() {<br>  return (<br>    &lt;div&gt;<br>      {/* Fast-loading title shows immediately */}<br>      &lt;Suspense fallback={&lt;TitleSkeleton /&gt;}&gt;<br>        &lt;VideoTitle /&gt;<br>      &lt;/Suspense&gt;<br>      <br>      {/* Heavy video player loads separately */}<br>      &lt;Suspense fallback={&lt;VideoSkeleton /&gt;}&gt;<br>        &lt;VideoPlayer /&gt;<br>      &lt;/Suspense&gt;<br>      <br>      {/* Comments load whenever they&#39;re ready */}<br>      &lt;Suspense fallback={&lt;CommentsSkeleton /&gt;}&gt;<br>        &lt;Comments /&gt;<br>      &lt;/Suspense&gt;<br>    &lt;/div&gt;<br>  );<br>}</pre><p>Each section pops in as soon as it’s ready. No waterfalls. No blocking. Just smooth, progressive enhancement.​</p><h3>The Error Boundary Combo</h3><p>Don’t forget error handling (narrator: <em>everyone forgets error handling</em>):</p><pre>function App() {<br>  return (<br>    &lt;ErrorBoundary fallback={&lt;ErrorPage /&gt;}&gt;<br>      &lt;Suspense fallback={&lt;LoadingPage /&gt;}&gt;<br>        &lt;MainContent /&gt;<br>      &lt;/Suspense&gt;<br>    &lt;/ErrorBoundary&gt;<br>  );<br>}</pre><p>Now your app gracefully handles both loading states AND errors. Your users will never know you spent 3 hours debugging that one edge case.​</p><h3>The Performance Story Nobody Talks About</h3><p>Here’s the dirty secret: these aren’t just nice APIs. They’re <em>faster</em>.​</p><p>By eliminating useEffect, you&#39;re removing an entire render cycle. The component renders once with a promise, suspends, then renders again with data. No intermediary &quot;pending&quot; render.​</p><p>GPU-accelerated transitions mean animations run at 60fps without touching your JavaScript thread. Your bundle size drops because you’re shipping less code. Your lighthouse score goes up. Your manager thinks you’re a wizard.</p><h3>The Hot Take Section</h3><p><strong>Controversial opinion incoming:</strong> React is eating the frontend ecosystem, and I’m here for it.​</p><p>First it came for class components (RIP). Then it came for Redux (sort of). Now it’s coming for data fetching libraries AND animation libraries.​</p><p>Is this bad? Honestly… no. Having these patterns baked into the framework means:​</p><ul><li><strong>Better performance</strong> (React can optimize at the framework level)​</li><li><strong>Smaller bundles</strong> (fewer dependencies)</li><li><strong>Easier onboarding</strong> (one way to do things)</li><li><strong>Better tooling</strong> (everything speaks the same language)</li></ul><p>Sure, some libraries will become less essential. But the remaining ones will evolve to do what React <em>can’t</em> do — and that’s where the real innovation happens.</p><h3>The “Now What?” Moment</h3><p>If you’ve made it this far, you’re probably thinking one of three things:</p><ol><li>“This is amazing, I’m refactoring everything tonight!”</li><li>“This is interesting, but I’ll wait for 20.0”</li><li>“I just learned useEffect last week, why is React doing this to me?”</li></ol><p>All valid reactions.​</p><p>My recommendation? <strong>Start experimenting now</strong>. Spin up a sandbox project. Try Suspense and use with a simple API call. Add some ViewTransition magic. Break things. Fix things. Learn the patterns.​</p><p>Because here’s the truth: this IS the future of React. Whether you adopt it today or in six months, these patterns are where the ecosystem is heading. Better to learn them now when you can afford to make mistakes.​</p><h3>The Code You Can Actually Use</h3><p>Want a production-ready starter? Here’s a complete example that handles everything:</p><pre>import { Suspense, use, useState, useTransition } from &#39;react&#39;;<br>import { ViewTransition } from &#39;react&#39;; // TypeScript will complain, ignore it<br><br>// Your fetch function with proper error handling<br>async function fetchImage(id: number) {<br>  const response = await fetch(`/api/images/${id}`);<br>  if (!response.ok) throw new Error(&#39;Failed to fetch&#39;);<br>  return response.json();<br>}<br><br>// Main component<br>export function ImageGallery() {<br>  const [imageId, setImageId] = useState(1);<br>  const [imagePromise, setImagePromise] = useState(<br>    () =&gt; fetchImage(1)<br>  );<br>  const [isPending, startTransition] = useTransition();<br>  <br>  const loadNextImage = () =&gt; {<br>    startTransition(() =&gt; {<br>      const nextId = imageId + 1;<br>      setImageId(nextId);<br>      setImagePromise(fetchImage(nextId));<br>    });<br>  };<br>  <br>  return (<br>    &lt;div className=&quot;gallery&quot;&gt;<br>      &lt;Suspense fallback={<br>        &lt;ViewTransition name=&quot;skeleton&quot;&gt;<br>          &lt;ImageSkeleton /&gt;<br>        &lt;/ViewTransition&gt;<br>      }&gt;<br>        &lt;ViewTransition name=&quot;image&quot; key={imageId}&gt;<br>          &lt;ImageDisplay imagePromise={imagePromise} /&gt;<br>        &lt;/ViewTransition&gt;<br>      &lt;/Suspense&gt;<br>      <br>      &lt;button <br>        onClick={loadNextImage}<br>        disabled={isPending}<br>        className=&quot;next-button&quot;<br>      &gt;<br>        {isPending ? &#39;⏳ Loading...&#39; : &#39;➡️ Next Image&#39;}<br>      &lt;/button&gt;<br>    &lt;/div&gt;<br>  );<br>}<br><br>// Child component using the promise<br>function ImageDisplay({ imagePromise }) {<br>  const image = use(imagePromise);<br>  <br>  return (<br>    &lt;div className=&quot;image-container&quot;&gt;<br>      &lt;h2&gt;{image.title}&lt;/h2&gt;<br>      &lt;img src={image.url} alt={image.title} /&gt;<br>    &lt;/div&gt;<br>  );<br>}<br><br>// Loading skeleton<br>function ImageSkeleton() {<br>  return (<br>    &lt;div className=&quot;skeleton&quot;&gt;<br>      &lt;div className=&quot;skeleton-title&quot; /&gt;<br>      &lt;div className=&quot;skeleton-image&quot; /&gt;<br>    &lt;/div&gt;<br>  );<br>}</pre><p>Copy. Paste. Ship it.​</p><h3>The Bottom Line</h3><p>React 19.2 didn’t just add new features — it fundamentally changed how we should think about async operations in React. The old patterns still work, but they’re becoming the equivalent of writing jQuery in 2025.​</p><p>Is it perfect? No. Is ViewTransition still experimental? Yes. Will your coworkers give you weird looks when you explain throwing promises? Absolutely.</p><p>But is it better than the useEffect + useState spaghetti we&#39;ve been writing for years?</p><p><strong>100% yes</strong>.​</p><p>Now go forth and suspend those components. Your future self will thank you.​</p><p><em>Got questions? Struggling with a migration? Drop a comment below and let’s figure it out together. And if this article saved you from one more useEffect bug, hit that clap button like it owes you money</em> 👏</p><p><em>P.S. — If you’re still using class components, we need to have a different conversation entirely…</em></p><h3>A message from our Founder</h3><p><strong>Hey, </strong><a href="https://linkedin.com/in/sunilsandhu"><strong>Sunil</strong></a><strong> here.</strong> I wanted to take a moment to thank you for reading until the end and for being a part of this community.</p><p>Did you know that our team run these publications as a volunteer effort to over 3.5m monthly readers? <strong>We don’t receive any funding, we do this to support the community. ❤️</strong></p><p>If you want to show some love, please take a moment to <strong>follow me on </strong><a href="https://linkedin.com/in/sunilsandhu"><strong>LinkedIn</strong></a><strong>, </strong><a href="https://tiktok.com/@messyfounder"><strong>TikTok</strong></a>, <a href="https://instagram.com/sunilsandhu"><strong>Instagram</strong></a>. You can also subscribe to our <a href="https://newsletter.plainenglish.io/"><strong>weekly newsletter</strong></a>.</p><p>And before you go, don’t forget to <strong>clap</strong> and <strong>follow</strong> the writer️!​</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=698d01682bac" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/react-19-2-just-revolutionized-async-say-goodbye-to-useeffect-698d01682bac">React 19.2 Just Revolutionized Async — Say Goodbye to useEffect!</a> was originally published in <a href="https://javascript.plainenglish.io">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ControlValueAccessor Is Dead. Long Live FormValueControl! ]]></title>
            <link>https://javascript.plainenglish.io/controlvalueaccessor-is-dead-long-live-formvaluecontrol-4cf2e30a4fb0?source=rss-82244dfb6a6a------2</link>
            <guid isPermaLink="false">https://medium.com/p/4cf2e30a4fb0</guid>
            <category><![CDATA[developer-experience]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[signal]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Rogerio Amorim]]></dc:creator>
            <pubDate>Sun, 19 Oct 2025 12:36:46 GMT</pubDate>
            <atom:updated>2025-10-21T07:20:31.167Z</atom:updated>
            <content:encoded><![CDATA[<h4><strong>Or: How I Learned to Stop Worrying and Love Angular Signal Forms</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/819/1*Lx1OiiME3UbWJVAVCTo9Jw.png" /></figure><p>Let’s be honest: if you’ve ever tried to create a custom form control in Angular, you’ve probably questioned your life choices. Maybe you even Googled “is web development really for me?” at 2 AM while debugging why your custom dropdown wasn’t syncing with your form. We’ve all been there.​</p><p>For years, ControlValueAccessor has been Angular&#39;s answer to custom form controls. And it worked! Kind of like how a Rube Goldberg machine &quot;works&quot;—technically functional, but unnecessarily complicated. You needed four callback methods, a provider configuration that looked like ancient hieroglyphics, and the kind of deep framework knowledge that only comes from years of suffering.​</p><p>But Angular 21’s experimental Signal Forms just dropped, and they’re about to make your life so much easier it’s almost unfair.​</p><h3>The Horror Show That Was ControlValueAccessor</h3><p>Let me paint you a picture. You want to create a simple star rating component. Five stars. Users click. Form updates. How hard could it be?​</p><p><strong>Narrator voice:</strong> <em>It was, in fact, very hard.</em></p><p>Here’s what you needed to implement with ControlValueAccessor:</p><pre>import { Component, forwardRef } from &#39;@angular/core&#39;;<br>import { ControlValueAccessor, NG_VALUE_ACCESSOR } from &#39;@angular/forms&#39;;<br>@Component({<br>  selector: &#39;app-star-rating&#39;,<br>  template: `...`,<br>  providers: [<br>    {<br>      provide: NG_VALUE_ACCESSOR,<br>      useExisting: forwardRef(() =&gt; StarRatingComponent),<br>      multi: true<br>    }<br>  ] // 👈 Already confused? We&#39;ve just started.<br>})<br>export class StarRatingComponent implements ControlValueAccessor {<br>  value: number = 0;<br>  onChange: any = () =&gt; {};<br>  onTouched: any = () =&gt; {};<br>  disabled: boolean = false;<br>  // Method 1: Framework writes value to your component<br>  writeValue(value: number): void {<br>    this.value = value;<br>  }<br>  // Method 2: Register callback for when value changes<br>  registerOnChange(fn: any): void {<br>    this.onChange = fn;<br>  }<br>  // Method 3: Register callback for when user touches control<br>  registerOnTouched(fn: any): void {<br>    this.onTouched = fn;<br>  }<br>  // Method 4: Handle disabled state<br>  setDisabledState(disabled: boolean): void {<br>    this.disabled = disabled;<br>  }<br>  // Your actual logic<br>  selectStar(rating: number): void {<br>    if (!this.disabled) {<br>      this.value = rating;<br>      this.onChange(rating); // 👈 Forget this? Enjoy debugging!<br>      this.onTouched();       // 👈 Or this? Good luck!<br>    }<br>  }<br>}</pre><p>Count those manual steps. Four interface methods. A provider configuration that needs forwardRef because JavaScript is JavaScript. Callback functions you <em>must</em> remember to call or your form silently fails. And if you forget any piece? Runtime errors that make you question why you didn&#39;t become a gardener instead.</p><h3>Enter Signal Forms: The Hero We Deserve</h3><p>Angular 21’s Signal Forms looked at this mess and said, “What if we just… didn’t?”​</p><p>Here’s the same component with the new FormValueControl interface:</p><pre>import { Component, model } from &#39;@angular/core&#39;;<br>import { FormValueControl } from &#39;@angular/forms&#39;;<br>@Component({<br>  selector: &#39;app-star-rating&#39;,<br>  template: `<br>    &lt;div class=&quot;star-container&quot;&gt;<br>      @for (star of [1, 2, 3, 4, 5]; track star) {<br>        &lt;span <br>          class=&quot;star&quot;<br>          (click)=&quot;selectStar(star)&quot;&gt;<br>          {{ star &lt;= value() ? &#39;⭐&#39; : &#39;☆&#39; }}<br>        &lt;/span&gt;<br>      }<br>    &lt;/div&gt;<br>  `<br>})<br>export class StarRatingComponent implements FormValueControl&lt;number&gt; {<br>  value = model&lt;number&gt;(0); // 👈 That&#39;s it. That&#39;s the whole thing.<br>  selectStar(rating: number): void {<br>    this.value.set(rating); // Automatic sync. Like magic, but real.<br>  }<br>}</pre><p><strong>Wait, where’s the rest of the code?</strong></p><p><em>There is no rest of the code.</em></p><p>That’s ONE property. One model() input. No callbacks. No providers. No forwardRef. No existential crisis at 2 AM. Just a signal that automatically keeps your component and form model in perfect harmony.​</p><p>When you update value in your component, the form knows. When the form updates the value, your component knows. It&#39;s bidirectional, automatic synchronization that just <em>works</em>. I know, I know—in Angular, we&#39;re not used to things &quot;just working&quot; without a PhD-level understanding of the framework internals. But here we are.​</p><h3>But Wait, There’s More! (And It Gets Better)</h3><p>Remember how ControlValueAccessor only handled value, disabled, and touched states? And if you needed anything else—like showing a &quot;required&quot; indicator—you had to do some deep-dive magic with NgControl injection and probably sacrifice a rubber duck to the debugging gods?​</p><p>Signal Forms laughed at those limitations and said, “Hold my beer.”</p><h3>Handling Disabled State (The Easy Way)</h3><pre>import { Component, input, model } from &#39;@angular/core&#39;;<br>import { FormValueControl } from &#39;@angular/forms&#39;;<br>@Component({<br>  selector: &#39;app-reaction-picker&#39;,<br>  template: `<br>    &lt;div [class.disabled]=&quot;disabled()&quot;&gt;<br>      @for (emoji of reactions; track emoji) {<br>        &lt;button <br>          (click)=&quot;select(emoji)&quot;<br>          [disabled]=&quot;disabled()&quot;&gt;<br>          {{ emoji }}<br>        &lt;/button&gt;<br>      }<br>    &lt;/div&gt;<br>  `<br>})<br>export class ReactionPickerComponent implements FormValueControl&lt;string&gt; {<br>  value = model&lt;string&gt;(&#39;&#39;);<br>  disabled = input&lt;boolean&gt;(false); // 👈 One line. Automatic sync.<br>  <br>  reactions = [&#39;😀&#39;, &#39;😍&#39;, &#39;🤔&#39;, &#39;😢&#39;, &#39;😡&#39;];<br>  select(emoji: string): void {<br>    this.value.set(emoji);<br>  }<br>}</pre><p>When your form disables the control, the disabled signal updates automatically. Your UI reacts. Users can&#39;t interact with it. No manual callback management. No forgetting to check the disabled state. It&#39;s almost like Angular finally realized we have other things to do than fight with forms.​</p><h3>Adding Required Indicators (Because Why Not?)</h3><pre>@Component({<br>  selector: &#39;app-reaction-picker&#39;,<br>  template: `<br>    &lt;div [class.disabled]=&quot;disabled()&quot;&gt;<br>      &lt;label&gt;<br>        How do you feel? <br>        @if (required()) {<br>          &lt;span class=&quot;required-marker&quot;&gt;*&lt;/span&gt;<br>        }<br>      &lt;/label&gt;<br>      @for (emoji of reactions; track emoji) {<br>        &lt;button <br>          (click)=&quot;select(emoji)&quot;<br>          [disabled]=&quot;disabled()&quot;&gt;<br>          {{ emoji }}<br>        &lt;/button&gt;<br>      }<br>    &lt;/div&gt;<br>  `<br>})<br>export class ReactionPickerComponent implements FormValueControl&lt;string&gt; {<br>  value = model&lt;string&gt;(&#39;&#39;);<br>  disabled = input&lt;boolean&gt;(false);<br>  required = input&lt;boolean&gt;(false); // 👈 Another line. Another feature.<br>  <br>  reactions = [&#39;😀&#39;, &#39;😍&#39;, &#39;🤔&#39;, &#39;😢&#39;, &#39;😡&#39;];<br>  select(emoji: string): void {<br>    this.value.set(emoji);<br>  }<br>}</pre><p>Add a required validator to your form control? The required signal updates automatically. Remove the validator? Signal updates again. You&#39;re not calling anything. You&#39;re not registering anything. You&#39;re just... building features.</p><p>This is the Angular developer experience we were promised.​</p><h3>Using Your Custom Control (The Moment of Truth)</h3><p>Here’s how you use your shiny new custom control in a form:</p><pre>import { Component } from &#39;@angular/core&#39;;<br>import { FormControl, FormGroup, Validators } from &#39;@angular/forms&#39;;<br>@Component({<br>  selector: &#39;app-feedback-form&#39;,<br>  template: `<br>    &lt;form [formGroup]=&quot;feedbackForm&quot; (ngSubmit)=&quot;submitFeedback()&quot;&gt;<br>      &lt;label&gt;Your Feedback:&lt;/label&gt;<br>      &lt;textarea <br>        formControlName=&quot;feedback&quot;<br>        rows=&quot;4&quot;&gt;<br>      &lt;/textarea&gt;<br>      &lt;app-reaction-picker <br>        [control]=&quot;feedbackForm.controls.reaction&quot;&gt;<br>      &lt;/app-reaction-picker&gt;<br>      &lt;button type=&quot;submit&quot; [disabled]=&quot;!feedbackForm.valid&quot;&gt;<br>        Submit<br>      &lt;/button&gt;<br>    &lt;/form&gt;<br>  `<br>})<br>export class FeedbackFormComponent {<br>  feedbackForm = new FormGroup({<br>    feedback: new FormControl(&#39;&#39;, [Validators.required, Validators.minLength(10)]),<br>    reaction: new FormControl(&#39;&#39;, [Validators.required])<br>  });<br>  submitFeedback(): void {<br>    if (this.feedbackForm.valid) {<br>      console.log(&#39;Form value:&#39;, this.feedbackForm.value);<br>      // { feedback: &quot;This is amazing!&quot;, reaction: &quot;😍&quot; }<br>    }<br>  }<br>}</pre><p>Notice how the custom control works <em>exactly like a built-in control</em>? That’s the point. No special incantations. No mysterious provider configurations. Just bind it with the control directive and you&#39;re done.​</p><p>Want to disable the reaction picker until the user types at least one character? Easy:</p><pre>feedbackForm = new FormGroup({<br>  feedback: new FormControl(&#39;&#39;, [Validators.required]),<br>  reaction: new FormControl({ value: &#39;&#39;, disabled: true }, [Validators.required])<br>});<br>ngOnInit() {<br>  // Enable reaction picker after user types something<br>  this.feedbackForm.controls.feedback.valueChanges.subscribe(value =&gt; {<br>    if (value &amp;&amp; value.length &gt; 0) {<br>      this.feedbackForm.controls.reaction.enable();<br>    } else {<br>      this.feedbackForm.controls.reaction.disable();<br>    }<br>  });<br>}</pre><p>Your custom control’s disabled signal updates automatically. The UI reflects the change. Everything just works. I know this feels weird. We&#39;re Angular developers—we&#39;re used to pain. But sometimes good things happen.​</p><h3>Special Cases: Checkbox Controls</h3><p>Got a toggle switch or a fancy checkbox replacement? Signal Forms have you covered with FormCheckboxControl:</p><pre>import { Component, input, model } from &#39;@angular/core&#39;;<br>import { FormCheckboxControl } from &#39;@angular/forms&#39;;<br>@Component({<br>  selector: &#39;app-toggle-switch&#39;,<br>  template: `<br>    &lt;div <br>      class=&quot;toggle-switch&quot;<br>      [class.checked]=&quot;checked()&quot;<br>      [class.disabled]=&quot;disabled()&quot;<br>      (click)=&quot;toggle()&quot;&gt;<br>      &lt;div class=&quot;toggle-slider&quot;&gt;&lt;/div&gt;<br>    &lt;/div&gt;<br>  `<br>})<br>export class ToggleSwitchComponent implements FormCheckboxControl {<br>  checked = model&lt;boolean&gt;(false); // 👈 Use &#39;checked&#39; instead of &#39;value&#39;<br>  disabled = input&lt;boolean&gt;(false);<br>  toggle(): void {<br>    if (!this.disabled()) {<br>      this.checked.update(current =&gt; !current);<br>    }<br>  }<br>}</pre><p>The only difference? Use checked instead of value. That&#39;s literally it. Angular team really said, &quot;Let&#39;s make this intuitive for once.&quot;​</p><h3>The Technical Magic (For the Nerds Like Us)</h3><p>Why does this work so much better than ControlValueAccessor? Two words: <strong>fine-grained reactivity</strong>.​</p><p>Signals provide automatic dependency tracking. When your signal changes, Angular knows <em>exactly</em> what needs to update. No zone.js running change detection on your entire component tree. No manual callback invocations that you might forget. Just precise, surgical updates exactly where they’re needed.</p><p>The old approach required you to be the middleman, manually calling callbacks to tell the form about changes. It was like being a telegraph operator — technically functional, but why are we still doing this in 2025?​</p><p>Signal Forms eliminate an entire category of bugs by removing the manual synchronization layer. You can’t forget to call a callback that doesn’t exist.​</p><h3>“But What About My ControlValueAccessor Knowledge?”</h3><p>Don’t panic. ControlValueAccessor isn&#39;t going anywhere. Template-driven and reactive forms will continue to exist alongside Signal Forms. Your existing apps won&#39;t spontaneously combust.​</p><p>In fact, Signal Forms use ControlValueAccessor under the hood for interoperability. It&#39;s abstraction layers all the way down, but now we get to work at a higher, saner level.​</p><p>Think of it like moving from assembly language to a high-level programming language. Assembly still exists. It’s still important. But you don’t need to write it every day anymore.​</p><h3>The Future Is Signal-Based (And We’re Here For It)</h3><p>Signal Forms are currently experimental, which in Angular-speak means “the API might change, so don’t bet your production app on it just yet”. But the core concepts are solid, and this is clearly where Angular is headed.​</p><p>As Angular moves away from zone-based change detection toward a signal-based reactive architecture, forms needed to evolve too. And honestly? They nailed it.​</p><p>If you want to get ahead of the curve (and write significantly less boilerplate in the process), start experimenting with Signal Forms now. By the time they’re stable, you’ll be the team expert everyone asks for help.</p><h3>The Bottom Line</h3><p>Creating custom form controls in Angular went from:</p><ul><li><strong>Four callback methods</strong> → One property</li><li><strong>Complex provider config</strong> → Nothing</li><li><strong>Manual synchronization</strong> → Automatic</li><li><strong>Limited state access</strong> → Rich form state</li><li><strong>Error-prone</strong> → Robust by default</li><li><strong>2 AM debugging sessions</strong> → Actually sleeping</li></ul><p>Is ControlValueAccessor dead? Not technically. But is it the walking dead that we&#39;re all slowly backing away from while FormValueControl becomes the new hotness? Absolutely.</p><p>Welcome to the future of Angular forms. It’s simpler, more intuitive, and finally feels like the framework respects your time.​</p><p>Now go build something amazing. And maybe — just maybe — you’ll actually enjoy working with forms.</p><p><strong>Want to dive deeper?</strong> Check out the <a href="https://angular.dev">official Angular documentation</a> and start experimenting with Angular 21. Your future self (and your keyboard, which you’ll stop rage-typing on at 2 AM) will thank you.</p><p><strong>P.S.</strong> If you’ve survived the ControlValueAccessor wars, drop a comment with your war stories. We&#39;ve all been there, and we all need therapy. 😅</p><h3>A message from our Founder</h3><p><strong>Hey, </strong><a href="https://linkedin.com/in/sunilsandhu"><strong>Sunil</strong></a><strong> here.</strong> I wanted to take a moment to thank you for reading until the end and for being a part of this community.</p><p>Did you know that our team run these publications as a volunteer effort to over 3.5m monthly readers? <strong>We don’t receive any funding, we do this to support the community. ❤️</strong></p><p>If you want to show some love, please take a moment to <strong>follow me on </strong><a href="https://linkedin.com/in/sunilsandhu"><strong>LinkedIn</strong></a><strong>, </strong><a href="https://tiktok.com/@messyfounder"><strong>TikTok</strong></a>, <a href="https://instagram.com/sunilsandhu"><strong>Instagram</strong></a>. You can also subscribe to our <a href="https://newsletter.plainenglish.io/"><strong>weekly newsletter</strong></a>.</p><p>And before you go, don’t forget to <strong>clap</strong> and <strong>follow</strong> the writer️!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4cf2e30a4fb0" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/controlvalueaccessor-is-dead-long-live-formvaluecontrol-4cf2e30a4fb0">ControlValueAccessor Is Dead. Long Live FormValueControl! 🎉</a> was originally published in <a href="https://javascript.plainenglish.io">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Stop Installing These npm Packages — Node.js Has Them Built-In Now ]]></title>
            <link>https://javascript.plainenglish.io/stop-installing-these-npm-packages-node-js-has-them-built-in-now-d4a46c17e039?source=rss-82244dfb6a6a------2</link>
            <guid isPermaLink="false">https://medium.com/p/d4a46c17e039</guid>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[npm]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Rogerio Amorim]]></dc:creator>
            <pubDate>Sat, 18 Oct 2025 21:06:39 GMT</pubDate>
            <atom:updated>2025-10-19T12:20:52.757Z</atom:updated>
            <content:encoded><![CDATA[<h3>Stop Installing These npm Packages — Node.js Has Them Built-In Now 🤯</h3><h4>Your node_modules folder is about to go on a serious diet, and your future self will thank you for it</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/819/1*qraTiHxFooIGM6ptr2ZEFA.jpeg" /></figure><p>Remember when you had to npm install literally everything to get basic stuff done in Node.js? Yeah, those days are fading fast. Node.js has been quietly adding native features that replace some of the most popular npm packages out there, and honestly, it&#39;s about time we talked about it.​</p><p>I’ve been building Node.js apps for years, and watching my node_modules folder shrink from a black hole of dependencies into something... manageable? That&#39;s the kind of dopamine hit I live for.​</p><p>Let’s dive into all the packages you can finally say goodbye to (and why you should absolutely care).</p><h3>The Game-Changer: Native TypeScript Support</h3><p><strong>ts-node/tsx → </strong><strong>--experimental-strip-types</strong></p><p>Hold onto your keyboard, because this is wild. Since Node.js v22.6.0, you can run TypeScript files directly without any transpilation step. Node.js v23.6.0 made it even better by removing the need for flags entirely.​</p><pre># Before: npm install --save-dev ts-node tsx<br>npx ts-node server.ts<br># or<br>npx tsx server.ts<br># Node.js 22.6+: Using experimental flags<br>node --experimental-strip-types server.ts<br># Node.js 23.6+: No flags needed!<br>node server.ts</pre><p>Here’s the deal though — it strips types, it doesn’t check them. You still need to run tsc --noEmit or use your IDE for type checking, but for execution? It just works.</p><pre>// server.ts - runs directly in Node.js now<br>interface User {<br>  id: string;<br>  name: string;<br>}<br>const createUser = (data: User): User =&gt; {<br>  return { ...data };<br>};<br>const user = createUser({ id: &#39;1&#39;, name: &#39;Alice&#39; });<br>console.log(user);</pre><p>For advanced TypeScript features like enums or namespaces, use the --experimental-transform-types flag:</p><pre>node --experimental-strip-types --experimental-transform-types app.ts</pre><p><strong>Is this production-ready?</strong> The flag is experimental in v22, but stable in v23.6.0+. TSX and ts-node still have their place for complex setups, but for most projects? Native support is already good enough.</p><h3>The Holy Trinity: Fetch, UUID, and Glob</h3><p><strong>node-fetch → Native </strong><strong>fetch()</strong></p><p>If you’re still installing node-fetch in 2025, we need to talk. Since Node.js v18, fetch() is globally available, just like in the browser. No imports, no installation, just pure HTTP requests out of the box.</p><pre>// Before: npm install node-fetch + @types/node-fetch<br>import fetch from &#39;node-fetch&#39;;<br>// Now: Nothing to install! Fully typed in @types/node<br>const response = await fetch(&#39;https://api.example.com/data&#39;);<br>const data = await response.json();</pre><p>This isn’t just convenient — it’s a game-changer for isomorphic code. Write once, run anywhere (browser or server), no compatibility layers needed.</p><p><strong>uuid → </strong><strong>crypto.randomUUID()</strong></p><p>The uuid package gets over 2 billion weekly downloads. TWO. BILLION. And most people just need a random UUID, which Node.js now gives you for free since v15.6.0.</p><pre>// Before: npm install uuid + @types/uuid<br>import { v4 as uuidv4 } from &#39;uuid&#39;;<br>const id = uuidv4();<br>// Now: Built-in cryptographically secure UUIDs<br>import { randomUUID } from &#39;node:crypto&#39;;<br>const id: string = randomUUID();</pre><p>It’s cryptographically secure, zero dependencies, fully typed, and one less thing to worry about in your package.json.​</p><p><strong>glob → </strong><strong>fs.glob()</strong></p><p>This one’s fresh off the press. Node.js v22 introduced native glob pattern matching, so you can finally ditch the glob package for file searching.​</p><pre>// Before: npm install glob + @types/glob<br>import glob from &#39;glob&#39;;<br>// Now: Native pattern matching with proper typing<br>import { glob } from &#39;node:fs/promises&#39;;<br>const jsFiles: string[] = await glob(&#39;**/*.js&#39;, { <br>  ignore: &#39;node_modules/**&#39; <br>});</pre><h3>The File System Crew</h3><p><strong>rimraf → </strong><strong>fs.rm({ recursive: true })</strong></p><p>Want to delete a directory and everything inside it? Node’s had you covered since v14.​</p><pre>// Before: npm install rimraf + @types/rimraf<br>import rimraf from &#39;rimraf&#39;;<br>await rimraf(&#39;dist&#39;);<br>// Now: One liner, no package, fully typed<br>import fs from &#39;node:fs/promises&#39;;<br>await fs.rm(&#39;dist&#39;, { recursive: true, force: true });</pre><p><strong>mkdirp → </strong><strong>fs.mkdir({ recursive: true })</strong></p><p>Creating nested directories used to require mkdirp. Not anymore — Node.js v10.12.0 added the recursive option.​</p><pre>// Before: npm install mkdirp + @types/mkdirp<br>import mkdirp from &#39;mkdirp&#39;;<br>await mkdirp(&#39;logs/app/errors&#39;);<br><br>// Now: Built-in recursive directory creation<br>import { mkdir } from &#39;node:fs/promises&#39;;<br>await mkdir(&#39;logs/app/errors&#39;, { recursive: true });</pre><h3>Development Tools That Got Native</h3><p><strong>nodemon → </strong><strong>--watch flag</strong></p><p>This one hit different when I discovered it. The --watch flag (stable in Node.js v19, available behind a flag in v18.11+) auto-restarts your server on file changes.​</p><pre># Before: npm install --save-dev nodemon<br>nodemon server.ts<br># Now: Native watch mode (works with TypeScript too!)<br>node --watch server.ts<br># With experimental type stripping<br>node --watch --experimental-strip-types server.ts<br># Watch specific path<br>node --watch-path=./src server.ts</pre><p>Sure, nodemon has more features, but for basic development? The native flag works perfectly. And it&#39;s TypeScript-aware when combined with type stripping.​</p><p><strong>dotenv → </strong><strong>--env-file flag</strong></p><p>Loading environment variables from .env files is now native in Node.js v20.6.0+. The dotenv package (22+ million weekly downloads) can finally rest.</p><pre># Before: npm install dotenv<br># Then: require(&#39;dotenv&#39;).config()<br># Now: Just use the flag<br>node --env-file=.env index.ts<br># Multiple env files? No problem<br>node --env-file=.env --env-file=.env.local index.ts<br># Combine with TypeScript support<br>node --env-file=.env --experimental-strip-types server.ts</pre><h3>Testing Gets Serious</h3><p><strong>Jest/Mocha → Native Test Runner</strong></p><p>Node.js v20 shipped with a built-in test runner that’s actually good. It’s faster than Jest (because it’s optimized specifically for Node, not browsers), has built-in mocking, spies, and code coverage.</p><pre>// Before: npm install --save-dev jest @types/jest<br>// Now: Just use node:test (fully typed!)<br>import { test, describe } from &#39;node:test&#39;;<br>import assert from &#39;node:assert&#39;;<br>describe(&#39;User API&#39;, () =&gt; {<br>  test(&#39;creates a user&#39;, async () =&gt; {<br>    const user = await createUser({ name: &#39;Alice&#39; });<br>    assert.strictEqual(user.name, &#39;Alice&#39;);<br>  });<br>});</pre><p>Run it with node --test, and you&#39;re done. Parallel execution, watch mode, everything you need. And yes, it works with TypeScript files too:</p><pre># Run TypeScript tests directly<br>node --test --experimental-strip-types **/*.test.ts<br># With watch mode for TDD<br>node --test --watch --experimental-strip-types **/*.test.ts</pre><h3>Utility Functions You Don’t Need Anymore</h3><p><strong>chalk/kleur → </strong><strong>util.styleText()</strong></p><p>Terminal colors without dependencies? Node.js v20.12+ introduced util.styleText() for exactly this.</p><pre>// Before: npm install chalk + @types/chalk<br>import chalk from &#39;chalk&#39;;<br>console.log(chalk.blue(&#39;Hello&#39;));<br>// Now: Native text styling (fully typed)<br>import { styleText } from &#39;node:util&#39;;<br>console.log(styleText(&#39;blue&#39;, &#39;Hello&#39;));<br>console.log(styleText([&#39;bold&#39;, &#39;red&#39;], &#39;Error!&#39;));</pre><p>It’s not as feature-rich as chalk, but for basic coloring? It&#39;s more than enough.​</p><p><strong>readable-stream → Native </strong><strong>stream module</strong></p><p>The readable-stream package (185+ million weekly downloads) was created to polyfill newer stream features. But the native stream module is now stable and feature-complete with Promise support.​</p><pre>// Before: npm install readable-stream + @types/readable-stream<br>import { pipeline } from &#39;readable-stream&#39;;// Now: Use native streams with promises (fully typed)<br>import { pipeline } from &#39;node:stream/promises&#39;;<br>import { createReadStream, createWriteStream } from &#39;node:fs&#39;;<br>await pipeline(<br>  createReadStream(&#39;input.txt&#39;),<br>  createWriteStream(&#39;output.txt&#39;)<br>);</pre><h3>Bonus: The Experimental Stuff</h3><p><strong>sqlite3/better-sqlite3 → </strong><strong>node:sqlite</strong></p><p>This one’s still experimental (requires --experimental-sqlite flag), but Node.js v22.5.0+ ships with native SQLite support.</p><pre>// Experimental, but promising (with TypeScript support!)<br>import { DatabaseSync } from &#39;node:sqlite&#39;;<br>const db = new DatabaseSync(&#39;:memory:&#39;);<br>db.exec(`CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT)`);<br>const insert = db.prepare(&#39;INSERT INTO users (name) VALUES (?)&#39;);<br>insert.run(&#39;Alice&#39;);</pre><p>It’s not production-ready yet, but watching this space.</p><h3>TypeScript Configuration Tips</h3><p>If you’re using native TypeScript support, here’s your minimal tsconfig.json:</p><pre>{<br>  &quot;compilerOptions&quot;: {<br>    &quot;module&quot;: &quot;NodeNext&quot;,<br>    &quot;moduleResolution&quot;: &quot;NodeNext&quot;,<br>    &quot;target&quot;: &quot;ES2022&quot;,<br>    &quot;allowImportingTsExtensions&quot;: true,<br>    &quot;noEmit&quot;: true,<br>    &quot;esModuleInterop&quot;: true,<br>    &quot;skipLibCheck&quot;: true<br>  }<br>}</pre><p>Key settings explained:</p><ul><li>allowImportingTsExtensions: Lets you import .ts files with the extension (required by Node.js)</li><li>noEmit: TypeScript only checks types, doesn&#39;t compile (Node.js handles execution)</li><li>module: &quot;NodeNext&quot;: Tells TypeScript to use Node.js ESM module resolution</li></ul><h3>Why This Actually Matters</h3><p><strong>Security</strong>: Every package you install is a potential security risk. Fewer dependencies = smaller attack surface.</p><p><strong>Performance</strong>: Native implementations are optimized for Node.js specifically. They’re almost always faster than third-party alternatives.</p><p><strong>Maintenance</strong>: Dependencies need updates, break with major versions, and sometimes get abandoned. Native features? Maintained by the Node.js team.</p><p><strong>Bundle Size</strong>: Smaller node_modules means faster installs, smaller Docker images, and less disk space wasted.</p><p><strong>Developer Experience</strong>: Using native features means better TypeScript support out of the box, consistent APIs, and one less thing to configure.</p><p><strong>TypeScript First-Class Support</strong>: No more juggling @types/* packages for basic functionality. The native modules are fully typed in @types/node.</p><h3>The Migration Playbook</h3><p>Don’t just rip out all your dependencies tomorrow. Here’s how to do this right:</p><ol><li><strong>Update Node.js</strong>: Get on v22 LTS or v23+ to access all these features.</li><li><strong>Start with new projects</strong>: Use native features and TypeScript support from day one.</li><li><strong>Add proper TypeScript config</strong>: Use the config above for native type stripping.</li><li><strong>Audit existing projects</strong>: Run npm ls and identify packages with native alternatives.</li><li><strong>Test thoroughly</strong>: Especially with fetch(), test runner, and TypeScript support — behavior differs slightly.</li><li><strong>Update gradually</strong>: Replace one package at a time, commit, test, repeat.</li><li><strong>Keep type checking</strong>: Use tsc --noEmit in CI/CD even with native type stripping.</li></ol><h3>The Bottom Line</h3><p>Node.js is growing up. Features that used to require external packages are becoming first-class citizens. Your node_modules folder doesn&#39;t have to be a bloated mess anymore. And now, you can even run TypeScript natively without the transpilation dance.</p><p>Does this mean every npm package is obsolete? Hell no. Libraries like axios still offer features fetch() doesn&#39;t have (request interceptors, automatic retries, better error handling). And tools like tsx might still be faster for complex TypeScript setups. But for basic functionality? Node.js has you covered.​</p><p>Next time you reach for npm install, pause for a second. Check if Node.js already has what you need. Your future self — and your CI/CD pipeline — will thank you.​</p><p>Now go delete some dependencies. You know you want to. 🚀</p><p><strong>Found this helpful?</strong> Give it a clap 👏 (or fifty — Medium lets you go wild). Every clap helps other developers discover that their node_modules folder doesn&#39;t need to be the size of a small planet.</p><p><strong>Share this with your team</strong> on Twitter, LinkedIn, or wherever developers hang out in your corner of the internet. Someone out there is about to npm install uuid and they need to see this first.</p><p>Got other packages that Node.js has replaced? Drop them in the comments below. Let’s build the ultimate list together and help the community trim down those dependencies.</p><p>Until next time — happy coding, and may your dependencies be forever minimal. ✨</p><h3>A message from our Founder</h3><p><strong>Hey, </strong><a href="https://linkedin.com/in/sunilsandhu"><strong>Sunil</strong></a><strong> here.</strong> I wanted to take a moment to thank you for reading until the end and for being a part of this community.</p><p>Did you know that our team run these publications as a volunteer effort to over 3.5m monthly readers? <strong>We don’t receive any funding, we do this to support the community. ❤️</strong></p><p>If you want to show some love, please take a moment to <strong>follow me on </strong><a href="https://linkedin.com/in/sunilsandhu"><strong>LinkedIn</strong></a><strong>, </strong><a href="https://tiktok.com/@messyfounder"><strong>TikTok</strong></a>, <a href="https://instagram.com/sunilsandhu"><strong>Instagram</strong></a>. You can also subscribe to our <a href="https://newsletter.plainenglish.io/"><strong>weekly newsletter</strong></a>.</p><p>And before you go, don’t forget to <strong>clap</strong> and <strong>follow</strong> the writer️!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d4a46c17e039" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/stop-installing-these-npm-packages-node-js-has-them-built-in-now-d4a46c17e039">Stop Installing These npm Packages — Node.js Has Them Built-In Now 🤯</a> was originally published in <a href="https://javascript.plainenglish.io">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>