<?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"><channel><title><![CDATA[materwelon's projects]]></title><description><![CDATA[materwelon's projects]]></description><link>https://materwelon.hashnode.dev</link><image><url>https://cdn.hashnode.com/uploads/logos/6a2bd41f6813342a54073887/c4a77f50-4f64-44c3-ad92-b7af9de9693a.jpg</url><title>materwelon&apos;s projects</title><link>https://materwelon.hashnode.dev</link></image><generator>RSS for Node</generator><lastBuildDate>Sat, 28 Nov 2026 20:34:31 GMT</lastBuildDate><atom:link href="https://materwelon.hashnode.dev/rss.xml" rel="self" type="application/rss+xml"/><language><![CDATA[en]]></language><ttl>60</ttl><item><title><![CDATA[How seedcord ask works]]></title><description><![CDATA[seedcord ask searches the guide from a terminal by meaning. Here's what it's useful for, why coding agents need it, and how the search is built.]]></description><link>https://materwelon.hashnode.dev/how-seedcord-ask-works</link><guid isPermaLink="true">https://materwelon.hashnode.dev/how-seedcord-ask-works</guid><category><![CDATA[AI]]></category><category><![CDATA[cloudflare]]></category><category><![CDATA[TypeScript]]></category><category><![CDATA[Node.js]]></category><category><![CDATA[discord]]></category><dc:creator><![CDATA[Dhruv]]></dc:creator><pubDate>Fri, 27 Nov 2026 11:32:31 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/6a2bd41f6813342a54073887/01902a23-da58-485e-8d18-afd2cbc8d22f.webp" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p><code>seedcord ask</code> came out with v0.23, and it only got a few lines in <a href="https://seedcord.org/blog/release-v0-23/">that post</a>. It's the most useful thing in seedcord if you build with a coding agent, so this post is all about it. What it does, why your agent needs it, and how it's built.</p>
<hr />
<h2>Asking the guide</h2>
<p>It searches the guide from a terminal, even outside a project:</p>
<pre><code class="language-sh">pnpm exec seedcord ask how do i split a long list into pages
</code></pre>
<p>It matches by <em>meaning</em>, so your question doesn't need the guide's words. That one never says "pagination", and you still get this:</p>
<pre><code class="language-txt">Pagination (Components): https://seedcord.org/guide/components/pagination.md
  - Rendering each item
  - What a paginator takes

Rendering a table (Replying): https://seedcord.org/guide/replying/render-table.md
  - Paging past the character limit
</code></pre>
<p>In a terminal you get a link to each section. An agent runs it without one of course, and that output up there is what it gets. Each link goes to the page's Markdown copy, so the agent can fetch it and read the page directly. Every guide page has one at its url plus <code>.md</code> btw.</p>
<hr />
<h2>Why your agent needs it</h2>
<p>Your agent has never seen seedcord. It's newer than whatever your model was trained on, so naturally it writes the discord.js it remembers.</p>
<p>To be fair, a lot of that gets caught. A route or an option that doesn't exist is a compile error, and lint catches more. What doesn't get caught is the agent rebuilding something seedcord already has. I had one hand-write pagination. It compiled, lint passed, and it worked, so nothing told it that seedcord ships pagination (well I did, begrudgingly, but that's besides the point).</p>
<p>Regardless, the agent has to look things up before it writes, and it doesn't know what the page is called. That's what <code>ask</code> is for. A new project's <code>AGENTS.md</code> tells the agent to run it before hand-writing anything bigger than a plain reply.</p>
<hr />
<h2>Error codes</h2>
<p>Every error seedcord throws has a number. You can paste the whole error, or only the number:</p>
<pre><code class="language-sh">pnpm exec seedcord ask 3116
</code></pre>
<pre><code class="language-txt">3116 is CliDependencyMissing

seedcord.config.ts (Build &amp; deploy): https://seedcord.org/guide/build/config.md
  - Config mistakes
</code></pre>
<p>The number is swapped for the error's name before the search runs, since <code>CliDependencyMissing</code> has words to match and <code>3116</code> doesn't.</p>
<p>That only happens when the number is the whole question. A four digit number in the middle of a sentence could just as well be a port or a year. There, <code>ask</code> tells you that the number is also an error code and gives you the command to look it up.</p>
<hr />
<h2>How it's built</h2>
<ol>
<li>When the guide builds, every heading on every page becomes a section. There are around 600 right now.</li>
<li>CI sends each section to EmbeddingGemma on Cloudflare Workers AI and gets 768 numbers back. They all go into one file, <code>vectors.bin</code>, which is about 2 MB and deploys with the site.</li>
<li>When you ask something, the guide's Worker turns your question into 768 numbers too. It compares them with every section and returns the closest 8.</li>
</ol>
<p>That last step is this:</p>
<pre><code class="language-ts">// tooling/docs-search/src/SectionIndex.ts
return (
  this.rows
    .map(({ section, vector, norm }) =&gt; {
      // cosine similarity. dividing by the lengths means a
      // long section doesn't rank higher just for being long
      const dot = vector.reduce(
        (sum, value, d) =&gt; sum + value * (question[d] ?? 0),
        0,
      );
      return { section, score: dot / (norm * questionNorm) };
    })
    // results don't show a score, so a weak match looks as
    // good as a strong one. can just drop them
    .filter(({ score }) =&gt; score &gt;= MIN_SCORE)
    .sort((a, b) =&gt; b.score - a.score)
    // you only need the top few to find your page. i actually
    // tweaked the guide a lot when testing with hundreds of
    // test questions to make sure the right page shows up in
    // the top 5
    .slice(0, limit)
    // the scores stay here. you get the page and the heading
    .map(({ section }) =&gt; guideHit(section))
);
</code></pre>
<p>We don't really need a full-fledged vector database for a guide of this size.</p>
<p>A few more things about it:</p>
<ul>
<li>Your question is the only thing that goes to the model when you search. The sections are already embedded.</li>
<li>Asking the same thing twice is free. Answers are cached at the edge, and the cache key includes a hash of the whole index, so a deploy clears it.</li>
</ul>
<p>The search box on <a href="https://seedcord.org/guide/">the guide</a> uses the same endpoint, so you get the same results there as well.</p>
<hr />
<h2>Only what changed gets embedded</h2>
<p>The guide deploys a lot, and most deploys change one page. Embedding every section each time would use up the daily allowance that the searches run on.</p>
<p>So each section's numbers are saved in their own file, and the file's name is a hash of the model's name and the section's text:</p>
<pre><code class="language-ts">// scripts/src/guide/EmbeddingCache.ts
const fileName = (document: string): string =&gt;
  `${createHash('sha256')
    .update(embedding.model)
    .update('\0')
    .update(document)
    .digest('hex')}.bin`;
</code></pre>
<p>If a file with that name exists, that section is already done. Fix a typo and that section's text hashes to a new name, so one section goes to the model and the rest are read from disk. A normal deploy logs something like this:</p>
<pre><code class="language-txt">✅ embedded 3 of 659 guide sections. The rest came from the cache.
</code></pre>
<p>I added the model's name is part of the hash so switching models changes every file name and everything gets embedded again.</p>
<p>The folder is kept in the GitHub Actions cache between deploys. GitHub removes a cache that nothing has read in over 7 days, so a weekly job restores it to make sure it doesn't get deleted.</p>
<p>Oh another cool thing. After the script writes <code>vectors.bin</code>, it loads the file with the same code the Worker uses. If the number of vectors doesn't match the number of sections, CI fails before anything deploys.</p>
<hr />
<h2>Where it falls short</h2>
<p><code>ask</code> finds pages. It doesn't answer your question, so obviously you or your agent still have to read the page.</p>
<p>It misses when the guide uses a word that nobody would search for. An agent asked about an "early return from a handler with a message", and the page it needed was called Throwing. It wasn't in the results at all. I renamed that page to Refusing a request and added a section called "Why not reply and return?", and now the same question finds it first. Most misses so far were like this one.</p>
<p>It also used to return something for every question. A search for "tsx jsx components", back when the guide had nothing on TSX, returned six unrelated pages. Now anything that scores under 0.38 is dropped, and <code>ask</code> says so when nothing matches. That number came from 200+ test questions, in case you're wondering. The weakest real one scored 0.413 and the TSX one scored 0.376.</p>
<p>For that misses thing above, I also added a button in the seed bot that you can use to report when a question doesn't find the right page. I get what you asked and what the bot returned. This helps me improve the guide and the search results over time.</p>
<hr />
<h2>The rest of it</h2>
<p>And of course, <code>ask</code> isn't the only thing in seedcord for agents:</p>
<ul>
<li><code>seedcord dev</code> without a terminal prints each log line as JSON and takes commands like <code>{"do":"restart"}</code> on stdin, so an agent can run your bot and read what happened. <a href="https://seedcord.org/guide/tooling/dev/">The dev page</a> lists the commands.</li>
<li><code>pnpm create seedcord</code> has a flag for every question it asks.</li>
<li>Every page in the guide and the reference has a Markdown copy, and each site has an <code>llms.txt</code>.</li>
</ul>
<p><a href="https://seedcord.org/guide/tooling/ask/">The ask page</a> has more on the command itself.</p>
<hr />
<p>New to seedcord? <a href="https://seedcord.org/guide/">Start here</a>. Come say hi in <a href="https://seedcord.org/chat">the Discord server</a> too.</p>
]]></content:encoded></item><item><title><![CDATA[seedcord v0.24]]></title><description><![CDATA[Four new plugins for tasks, translations, Discord OAuth, and any SQL database, plus web routes from plugins and a command that uploads your emojis.]]></description><link>https://materwelon.hashnode.dev/seedcord-v0-24</link><guid isPermaLink="true">https://materwelon.hashnode.dev/seedcord-v0-24</guid><category><![CDATA[discord]]></category><category><![CDATA[TypeScript]]></category><category><![CDATA[Node.js]]></category><category><![CDATA[vite]]></category><category><![CDATA[bots]]></category><category><![CDATA[framework]]></category><dc:creator><![CDATA[Dhruv]]></dc:creator><pubDate>Fri, 27 Nov 2026 11:29:39 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/6a2bd41f6813342a54073887/1567646f-edff-4a73-92dc-2bea282f797f.webp" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Four new plugins in the box this time. Tasks, translations, Discord OAuth, and Kysely on any database. Plugins can also answer web requests on your bot's own server now, and <code>seedcord emojis</code> manages all your bot's emojis from one folder in your repo, with a typed key for each.</p>
<p>73 changes since v0.23, and 21 of them are breaking. Don't worry though, most of those only touch one API. I'll go through the ones you'll actually notice at the end.</p>
<p>Anyway, here's what's new.</p>
<hr />
<h2>Four new plugins</h2>
<h3>Tasks</h3>
<p>Some work doesn't start from a command, like a digest every morning or a cleanup every hour. That used to be a <code>setInterval</code> in <code>bot.ts</code> that you started after login, stopped before exit, and just hoped never overlapped itself.</p>
<p><a href="https://seedcord.org/guide/plugins/tasks/"><code>@seedcord/plugin-tasks</code></a> runs a folder of task classes on a cron pattern:</p>
<pre><code class="language-ts">// src/tasks/Heartbeat.ts
@RegisterTask('*/5 * * * *')
export class Heartbeat extends Task {
  public async execute(): Promise&lt;void&gt; {
    const { size } = this.core.bot.client.guilds.cache;
    this.logger.info(`Serving ${size} servers`);
  }
}
</code></pre>
<p>The pattern is typed btw, so <code>'61 * * * *'</code> doesn't compile, and the error says which field is wrong.</p>
<p>It also <a href="https://seedcord.org/guide/plugins/tasks-scheduling/">runs a task once at a later time</a>, like an unban a day after a tempban:</p>
<pre><code class="language-ts">await this.core.tasks.schedule(Unban, {
  in: '1d',
  data: { guildId, userId },
});
</code></pre>
<p>The job goes into your <code>kv</code> store first, so it's still there after a restart if your driver saves to disk or a database. And of course, none of this runs on its own under <code>seedcord dev</code> until you pass <code>runInDev: true</code>. Nobody wants a cleanup job firing every time they save a file.</p>
<p>Huge thanks to <a href="https://github.com/camdzic">camdzic</a> for writing this whole plugin.</p>
<h3>i18n</h3>
<p>Discord sends the language each user picked with every interaction, and <a href="https://seedcord.org/guide/plugins/i18n/"><code>@seedcord/plugin-i18n</code></a> replies in it. Your strings go in <a href="https://projectfluent.org/">Fluent</a> files, one per language:</p>
<pre><code class="language-ftl"># src/locales/en-US.ftl
items =
    { $count -&gt;
        [one] You have { $count } item
       *[other] You have { $count } items
    }
</code></pre>
<p>Every handler gets <code>this.t</code>:</p>
<pre><code class="language-ts">await this.reply(this.t('items', { count: 3 }));
</code></pre>
<p><code>seedcord codegen</code> types every key and its variables from the base file. So a typo in a key or a missing <code>count</code> is a compile error now. Before, a user would just see the wrong message. The plural rules go in the Fluent file, so you call <code>t</code> the same way for Arabic's six forms as for English's two.</p>
<p>And it can <a href="https://seedcord.org/guide/plugins/i18n-commands/">translate your command names and descriptions</a> before each deploy as well.</p>
<h3>OAuth</h3>
<p><code>@seedcord/plugin-oauth</code> adds Discord OAuth to your bot. Once someone logs in, your bot can call Discord as them, like listing the servers they're in:</p>
<pre><code class="language-ts">const guilds = await this.core.oauth.as(this.user.id).guilds();
</code></pre>
<p>It serves the login routes itself, keeps every user's tokens encrypted in your <code>kv</code> store, and refreshes them before they expire. On top of that, the scopes you pass to <code>OAuth.with({ scopes: ['guilds'] })</code> decide which calls are typed, so calling anything outside your scopes doesn't compile.</p>
<p>It works on gateway, http, and Workers. <a href="https://seedcord.org/guide/plugins/oauth/">OAuth</a> has the setup, including the redirect URL you have to add in the developer portal (Discord won't let a bot add it for you, sadly).</p>
<h3>Kysely, on any database</h3>
<p><code>@seedcord/plugin-kysely-postgres</code> is just <a href="https://seedcord.org/guide/plugins/kysely/"><code>@seedcord/plugin-kysely</code></a> now. It takes any Kysely dialect, so SQLite, MySQL, Postgres, and the community ones all work. <em>Who knew other databases existed, heh.</em></p>
<pre><code class="language-ts">// src/bot.ts
seedcord.attach('db', Kysely, {
  path: './services',
  dialect: () =&gt; new SqliteDialect({ database: new Database('bot.db') }),
  migrations: { path: './migrations' },
});
</code></pre>
<p>And if you'd like the <code>node:sqlite</code> that ships with Node, there's a <code>nodeSqlite()</code> helper for that.</p>
<hr />
<h2>Plugins can answer web requests</h2>
<p>Some plugins need a URL of their own, like a route that GitHub posts webhooks to. Before, you'd have to run a second web server next to your bot just for a route or two.</p>
<p>Now a plugin can <a href="https://seedcord.org/guide/writing-plugins/web-requests/">define <code>fetch()</code></a>. It gets a web <code>Request</code> and returns a <code>Response</code>, or <code>undefined</code> to pass it on:</p>
<pre><code class="language-ts">// src/plugins/Status.ts
const STATUS = new URLPattern({ pathname: '/status' });

export class Status extends Plugin {
  public async init(): Promise&lt;void&gt; {}

  public override fetch(request: Request): Response | undefined {
    if (!STATUS.test(request.url)) return undefined;

    return Response.json({ guilds: this.core.bot.client.guilds.cache.size });
  }
}
</code></pre>
<p>This works on both transports, and a gateway bot serves these routes on the same server as its health check. The OAuth plugin above is actually built on this.</p>
<p>Already have a web server, like a Hono API or a Next.js site? Set <code>port</code> to <code>false</code> in your <code>server</code> config and seedcord stays off every port. Your server passes requests to <code>bot.fetch()</code>, and the plugin routes answer from there. And yep, gateway bots can do this now, same as http bots. <a href="https://seedcord.org/guide/build/embed/">Inside your own server</a> shows it with Hono, Next.js, and Express.</p>
<hr />
<h2><code>seedcord emojis</code></h2>
<p>Application emojis belong to one application, so every test bot needed the same images uploaded again by hand in the developer portal. Then you'd copy each emoji's id into your code, and redo the whole thing for the next bot. Yeah that gets really old really fast.</p>
<p>So now your emojis just live in an <code>emojis</code> folder next to <code>seedcord.config.ts</code>. Commit it, and everyone on your team gets the same emojis on their own test bot:</p>
<pre><code class="language-sh">pnpm exec seedcord emojis push
</code></pre>
<p><code>push</code> uploads whatever your application doesn't have yet. Every file becomes a typed key, so <code>party_parrot.png</code> is <code>Emojis.PartyParrot</code> in your code, with the right id for whichever bot is running. No more copying ids around.</p>
<p>There's <a href="https://seedcord.org/guide/tooling/emojis/">a lot more</a> to it:</p>
<ul>
<li><code>list</code> compares the folder with what's on Discord. With <code>--check</code>, it exits 1 if a file isn't uploaded yet, so you can run it in CI before a deploy.</li>
<li><code>pull</code> downloads the emojis that only exist on Discord into the folder. With <code>--guild</code>, it grabs a server's emojis, and the next <code>push</code> puts them on your bot.</li>
<li><code>remove</code> deletes from Discord, and <code>--delete-file</code> takes the file with it.</li>
<li><code>push --replace</code> sends an image again after you edit it.</li>
<li>Your bot checks the folder when it starts. If a file isn't uploaded yet, it stops and tells you to run <code>push</code>.</li>
</ul>
<p>Oh and a little trick Discord's docs don't mention: a lossy AVIF or an animated GIF of 256 KiB or less keeps its full size, while most uploads get shrunk to 128 pixels.</p>
<hr />
<h2>More for plugin authors</h2>
<p>The four plugins above needed some <a href="https://seedcord.org/guide/writing-plugins/">new hooks</a>, so of course they're yours to use:</p>
<ul>
<li><code>dispatchMembers</code> runs once per interaction or event, and each result shows up as <code>this.&lt;name&gt;</code> on handlers. That's how <code>this.t</code> from i18n gets there.</li>
<li><code>prepareCommands</code> edits your commands before they go to Discord, like adding <code>name_localizations</code>.</li>
<li><code>registerCommandFiles</code> takes globs, and saving a matching file in <code>seedcord dev</code> shows the refresh prompt.</li>
<li><code>Storable</code> <strong>and</strong> <code>Stored</code> type what goes into and comes back out of <code>kv</code>, so the compiler rejects any value that JSON can't store.</li>
</ul>
<hr />
<h2>Smaller things I really like</h2>
<p><strong>Public replies by default.</strong> Set <code>bot.interactions.ephemeral</code> to <code>false</code> if most of your replies should be public.</p>
<p><strong>A reply for buttons with no handler.</strong> A command or button without one now says "This doesn't do anything right now." Pass your own handler as <code>interactions.unhandled</code> to change it.</p>
<p><strong>A warning before Discord gives up.</strong> In dev, seedcord warns you when an interaction still hasn't been answered 2.5 seconds after Discord created it. Discord fails it at 3, so you'll know before your users do.</p>
<p><code>@WebhookUrl</code> <strong>takes a function</strong> now, for a log webhook URL you keep outside the environment.</p>
<p><code>BOT_TOKEN</code> <strong>works</strong> when <code>DISCORD_BOT_TOKEN</code> isn't set, so a bot moving to seedcord can keep its old variable name.</p>
<p><strong>Bad cooldowns don't compile.</strong> <code>Cooldown('1.5h')</code> and <code>Cooldown('0s')</code> used to throw when the handler loaded.</p>
<p>And if you're moving a bot over from plain discord.js, there's a <a href="https://seedcord.org/guide/coming-from-discordjs/">new guide page</a> just for that.</p>
<hr />
<h2>Fixes</h2>
<p>20 this time. Here are a few you might have hit:</p>
<ul>
<li>A second <code>send()</code> after <code>defer()</code> replaced the first message when it should've sent a new one.</li>
<li>After <code>defer({ ephemeral: false })</code>, an error card meant only for the user posted publicly.</li>
<li>On gateway, a deleted log webhook and a refused command deploy didn't get caught.</li>
<li>On Workers, if a handler didn't await a <code>kv.update()</code>, every later update to that key hung forever.</li>
<li>If a restart pattern had a <code>!</code> in it, <code>seedcord dev</code> restarted on almost every save.</li>
<li>On Windows, <code>create-seedcord</code> and a few CLI prompts waited for Enter before exiting.</li>
</ul>
<hr />
<h2>Updating</h2>
<pre><code class="language-sh">pnpm update --latest seedcord @seedcord/gateway # or @seedcord/http
pnpm exec seedcord codegen
</code></pre>
<p>Don't forget your seedcord plugins. If you used <code>@seedcord/plugin-kysely-postgres</code>, switch to <code>@seedcord/plugin-kysely</code>. Its class is <code>Kysely</code> now, and it takes a <code>dialect</code> function. <code>pool</code> and <code>connectionString</code> are gone.</p>
<p>Your compiler catches most of the 21 breaking changes (the nutrition label did warn you). These are the ones to know about up front:</p>
<ul>
<li><p><code>tunnel</code>, <code>hmr</code>, <code>idleAnimation</code>, and an edge bot's <code>port</code> moved under <code>dev</code> in <code>seedcord.config.ts</code>.</p>
</li>
<li><p><code>port</code> and <code>healthCheck</code> are now one <code>server</code> block. <strong>A gateway bot now listens on port 3000 by default</strong>, where it used 6967, so check your host's port settings.</p>
<pre><code class="language-ts">server: { port: 8080, health: '/healthz' }
</code></pre>
</li>
<li><p>Your bot reads the <code>emojis</code> folder next to <code>seedcord.config.ts</code> when it starts, and if a file in there isn't uploaded, it stops. If you already keep other stuff in a folder with that name, move it or point <code>emojis.dir</code> at an empty folder.</p>
</li>
<li><p>After a <code>defer()</code>, every <code>send()</code> past the first one now sends a new message. Nothing warns you about this one.</p>
</li>
<li><p>An http bot answers anything that isn't a POST with a 404, where it used to send a 405. Update any uptime check that expects the 405.</p>
</li>
<li><p>An edge bot needs <code>@cloudflare/vite-plugin@2.0.0-rc.0</code> and <code>cf@1.0.0-rc.0</code>.</p>
</li>
</ul>
<p><a href="https://github.com/seedcord/seedcord/releases">The changelog</a> has everything else.</p>
<hr />
<p>v1 is getting close, so if something in the API bugs you, now's the time to tell us.</p>
<p>Thanks to <a href="https://github.com/camdzic">camdzic</a> for the tasks plugin, the ephemeral default, and the Windows prompt fix, and to <a href="https://github.com/SerenModz21">SerenModz21</a> for moving the repo to Vite+ and keeping our dependencies up to date!</p>
<p>New to seedcord? <a href="https://seedcord.org/guide/">Start here</a>, and come say hi in <a href="https://seedcord.org/chat">the Discord server</a>!</p>
]]></content:encoded></item><item><title><![CDATA[Vite & more • seedcord v0.22]]></title><description><![CDATA[Vite builds, edge bots, and a CLI for managing Discord commands. Here's what's new in seedcord v0.22.]]></description><link>https://materwelon.hashnode.dev/vite-more-seedcord-v0-22</link><guid isPermaLink="true">https://materwelon.hashnode.dev/vite-more-seedcord-v0-22</guid><category><![CDATA[discord]]></category><category><![CDATA[vite]]></category><category><![CDATA[edge]]></category><category><![CDATA[cloudflare]]></category><dc:creator><![CDATA[Dhruv]]></dc:creator><pubDate>Fri, 20 Nov 2026 18:57:13 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/6a2bd41f6813342a54073887/e1b40170-4311-4328-b040-2cad85f29b35.webp" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>With v0.22, we're bringing Vite to production builds too! <code>seedcord dev</code> was already using Vite, and now <code>seedcord build</code> does as well. With Vite 8 (Rolldown), this means faster builds and more consistency between development and production. Previously, production builds were transpiled with TypeScript and their aliases rewritten with <code>tsc-alias</code>.</p>
<p>To upgrade your bot, run your package manager's upgrade command:</p>
<pre><code class="language-sh">pnpm update --latest seedcord @seedcord/http
bun update --latest seedcord @seedcord/http
npm install seedcord@latest @seedcord/http@latest
yarn upgrade --latest seedcord @seedcord/http

# Replace @seedcord/http with your transport, and update any Seedcord plugins you use.
</code></pre>
<p>New to seedcord? Scaffold your first bot with our <code>create-seedcord</code> CLI:</p>
<pre><code class="language-sh">pnpm create seedcord@latest
bun create seedcord@latest
npm init seedcord@latest
yarn create seedcord@latest
</code></pre>
<p>Then head over to <a href="https://seedcord.org/guide/first-bot/">our first bot guide</a>.</p>
<p>Curious what seedcord does and why? <a href="https://seedcord.org/guide/">Start here!</a></p>
<p>Here are some things from this release we'd like to highlight:</p>
<hr />
<h2>Static builds with Vite &amp; Vite plugin support</h2>
<p>As mentioned above, this release features Vite builds for production (<code>seedcord build</code>). Before, only <code>seedcord dev</code> was using Vite, which meant we had two different build paths for dev and prod. As an additional pain point, the previous production build was more of a "transpilation": at runtime, your modules were still being dynamically read from the filesystem instead of statically imported.</p>
<p>By moving to Vite and unifying dev and build, we now have consistent parsing behaviour across dev and prod, as well as reduced complexity, and no more of that runtime module importing behaviour. <em>Hooray for all!</em></p>
<p>Because we have now adopted Vite entirely, you can also use your own Vite plugins in the seedcord config file, like so:</p>
<pre><code class="language-ts">import { defineConfig } from 'seedcord/config';
import { foo } from 'vite-plugin-foo';

export default defineConfig({
    // ...
    vitePlugins: () =&gt; [foo()]
});
</code></pre>
<p>Make sure that any environment-aware plugins target the <code>seedcord</code> environment, since that's the environment that seedcord is set up in.</p>
<p>You'll find more information about using Vite plugins, and when to use seedcord plugins vs Vite plugins, on <a href="https://seedcord.org/guide/build/vite-plugins/">this guide page</a>.</p>
<p>This upgrade solves our bundling problems and lets us do something else that's pretty cool:</p>
<hr />
<h2>Edge bots</h2>
<p>You can now write HTTP bots that run on the edge (Cloudflare Workers)! Previously, the option to run bots on Workers wasn't functional, and you only had the option to run it on a server runtime like Node. With this release, you can now write bots using seedcord that build as Cloudflare Workers. These bots use Discord's Interactions webhook capability to allow your bot to receive certain events as a webhook call to your bot instead of via the Gateway, and when you're done, you can deploy them to the Cloudflare Workers platform.</p>
<p>To get started, run either of these commands (depending on your package manager):</p>
<pre><code class="language-sh">pnpm create seedcord
bun create seedcord
npm init seedcord
yarn create seedcord
</code></pre>
<p>Then select the HTTP bots option.</p>
<p><img src="./http-transport.webp" alt="Bot transport options" /></p>
<p>And finally select Cloudflare Workers.</p>
<p><img src="./cloudflare-workers.webp" alt="HTTP bot runtime selection" /></p>
<p>Make sure to fill in the remaining details as requested, and then your bot should now be scaffolded.</p>
<blockquote>
<p>Note: The runtime option will only appear for HTTP bots.</p>
</blockquote>
<p>Now, <code>cd</code> into your project directory:</p>
<pre><code class="language-sh">cd edge-bot # replace with your bot's directory
</code></pre>
<p>And run <code>seedcord dev</code> with your package manager. Your bot will now be running and ready for you to iterate on. Edit a relevant file, and your bot will have hot module replacement (HMR) activating to swap out the module you just edited, faster than you can blink!</p>
<p>In dev, the bot is running inside <code>workerd</code>, the same runtime used by Cloudflare Workers. This ensures there are few differences between your local testing and the production runtime. This is possible thanks to us moving to use Vite for both dev and build, allowing us to fully utilise the <a href="https://vite.dev/guide/api-environment">Vite Environment API</a>. This system allows us to coordinate dev and build in a separate runtime like this and accurately map the <code>seedcord</code> application. Huge thanks to the Vite team for making this!</p>
<p>Before your first deploy, log in to Cloudflare and deploy your commands. The build reads their IDs from Discord:</p>
<pre><code class="language-sh">pnpm exec cf auth login
pnpm exec seedcord commands deploy
pnpm build
pnpm exec cf deploy --prebuilt --secrets-file .secrets.env
</code></pre>
<p>Make sure <code>DISCORD_BOT_TOKEN</code> is available in your shell or <code>.env</code> when you build. For the first deploy, put every secret declared in <code>cloudflare.config.ts</code> in <code>.secrets.env</code>, not just the bot token. Keep that file out of git. After the first deploy, the scaffold's <code>deploy</code> script builds and deploys without the secrets file. With Bun, use <code>bunx</code> for each <code>pnpm exec</code> command and <code>bun run build</code> for <code>pnpm build</code>. And voila! Now you've got a seedcord edge bot deployed to Cloudflare.</p>
<p>Set Discord's <strong>Interactions Endpoint URL</strong> to your Worker URL in the developer portal.</p>
<p>Read up on this in <a href="https://seedcord.org/guide/build/workers/">the guide page</a>.</p>
<hr />
<h2>Command management via CLI</h2>
<p>If you've ever deployed any bot to Discord (not just seedcord ones), you'll know that command management is a bit of a pain. There's no way to delete your registered commands in Discord's developer portal, whether they're global or guild commands.</p>
<p>That pain is no more for seedcord bots! Starting with this version, the framework CLI now has a <code>commands</code> subcommand, which is your home for managing command deployments.</p>
<p>Running <code>seedcord commands</code> gives you the following options:</p>
<p><img src="./command-manager.webp" alt="Command manager" /></p>
<ul>
<li><strong>Deploy the commands in your code</strong> - seedcord will read your code, compile a list of commands, and deploy them according to how you configured your command (<code>guild</code> commands are deployed to a server of your choosing, <code>global</code> commands are deployed to the bot itself).</li>
<li><strong>List the commands Discord has</strong> - Lists the commands your bot has deployed globally or in servers.</li>
<li><strong>Delete guild commands that duplicate a global command</strong> - Removes guild commands that share a name with a global command.</li>
<li><strong>Delete every command globally or in guilds</strong> - Deletes every command your bot has registered, globally and/or in guilds. <em><strong>This is very destructive. Make sure you've selected the right bot and, if applicable, the right guild!</strong></em></li>
</ul>
<p>Each of these can also be accessed with subcommands:</p>
<ul>
<li><code>deploy [options]</code></li>
<li><code>list [options]</code></li>
<li><code>clean [options]</code></li>
<li><code>purge [options]</code></li>
</ul>
<p>This allows you to have simplified command management while building and maintaining your bot with seedcord!</p>
<p>To learn more about the subcommands, visit <a href="https://seedcord.org/guide/tooling/commands/">this guide page</a>.</p>
<hr />
<h2>Library mode</h2>
<p>seedcord bots can be built (and published) as libraries! This allows you to write your bots using the framework, and export them for use as part of a larger application. This will be most useful to bots on HTTP transports, as you can easily integrate them into backend frameworks like Hono, H3, Elysia, or even full-stack frameworks like Nitro, TanStack Start, Astro, and more.</p>
<p>To build library bots, omit <code>build.start</code> from your seedcord config:</p>
<pre><code class="language-ts">import { defineConfig } from 'seedcord/config';

export default defineConfig({
    root: './src',
    instance: './bot.ts'
    // do not set build.start
});
</code></pre>
<p>And now, your bot will be packaged as a library, ready for you to reuse it elsewhere.</p>
<p>To use library bots, simply import them from their bot entrypoint:</p>
<pre><code class="language-ts">import bot from '@mypkg/bot'; // Change the entrypoint to your bot package entrypoint
</code></pre>
<p>HTTP bots comply with the <code>export default { fetch }</code> standard used by Cloudflare Workers, Bun, Hono, H3, Elysia, and more. This means that you can simply pass in one <code>Request</code> object and get the <code>Response</code> from the bot. In a Node server, call <code>start()</code> before passing requests to <code>fetch()</code>; on Workers, the first request starts the bot. The <a href="https://seedcord.org/guide/build/embed/">embedding guide</a> has an example.</p>
<p>For Gateway bots, start them using the <code>start</code> method:</p>
<pre><code class="language-ts">await bot.start();
</code></pre>
<p>Your bot can now be used like a library in another app.</p>
<p>See <a href="https://seedcord.org/guide/build/package/">the guide</a> to learn more. There's also <a href="https://seedcord.org/guide/build/embed/">a guide page on integrating with web servers</a>.</p>
<hr />
<h2>Session lock files</h2>
<p>Did you ever start a dev server and forget about it? Well, as a small new addition to this update, we've added a session lock file.</p>
<p>When you start a dev session, a lock file records the Discord application ID. If another dev session starts with the same application ID, the CLI shows the first session's folder, process id, start time, and lock file path. Press <code>q</code> in that session to stop it, or remove the lock if the session has already stopped.</p>
<p><img src="./session-lock.webp" alt="lockfile dev error" /></p>
<p>This will not trigger if bots are using different applications, so it won't get in your way if you are developing several distinct bots.</p>
<hr />
<h2>Other fixes and improvements</h2>
<ul>
<li>~40 bug fixes were included in this release</li>
<li><code>create-seedcord</code> got a refreshed look, asks if you want to install dependencies and initialize a git repo, and comes with a sample uptime plugin.</li>
<li>The TUI is now more responsive for narrower screens (such as mobile or split screen on computers)</li>
<li>Certain layout and filter preferences for dev sessions are now saved across sessions.</li>
<li>The bot health check was revamped and now correctly says ready when the bot is actually ready for gateway and HTTP bots running on Node.</li>
</ul>
<p>For the rest of the release information, <a href="https://github.com/seedcord/seedcord/releases/tag/release-2026.10.25">read the release changelog</a>.</p>
<p>Join our <a href="https://seedcord.org/chat">Discord server</a> to chat with others about seedcord!</p>
]]></content:encoded></item><item><title><![CDATA[seedcord v0.23 release]]></title><description><![CDATA[A key-value store, natural language search in the guide, templates for new files, plugins that write their own types, and ~40 fixes.]]></description><link>https://materwelon.hashnode.dev/seedcord-v0-23-release</link><guid isPermaLink="true">https://materwelon.hashnode.dev/seedcord-v0-23-release</guid><category><![CDATA[release]]></category><category><![CDATA[kv]]></category><category><![CDATA[search]]></category><category><![CDATA[plugins]]></category><category><![CDATA[codegen]]></category><category><![CDATA[TypeScript]]></category><category><![CDATA[discord]]></category><category><![CDATA[tooling]]></category><dc:creator><![CDATA[Dhruv]]></dc:creator><pubDate>Fri, 20 Nov 2026 18:10:20 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/6a2bd41f6813342a54073887/7f7e15f7-a3c2-449b-92de-b8e4cf185894.webp" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>That's the bill for this release. 78 changes since v0.22, and 20 of them are breaking, so your bot is paying for some of it. It's less scary than it looks though. More on that at the end.</p>
<p>This all started as a short list of things to fix before the release, and it kept growing. One PR ended up titled "<code>feat: refactor? chore? fix? god pr</code>", which tells you how that went.</p>
<p>Here's the good stuff.</p>
<hr />
<h2>You can ask the guide questions now</h2>
<p>Docs search only works when you already know the word the docs use. You want to stop people spamming a command, and the page you need is called Cooldowns. If nobody ever told you that's what it's called, good luck.</p>
<p>So now you can type what you'd ask a person. Press <code>Cmd+K</code> or <code>/</code> on <a href="https://seedcord.org/guide/">the guide</a> and try it. These are real searches, with the top result each one got:</p>
<pre><code class="language-txt">how do i stop people from spamming a command  👉🏻  Cooldowns
how do i know which button someone clicked    👉🏻  Buttons
</code></pre>
<p>Text matches show up right away under <strong>Matches</strong>. Once you stop typing, your question goes to Cloudflare Workers AI, which turns it into a vector with EmbeddingGemma. The guide sections closest in meaning come back under <strong>Related</strong>.</p>
<p>I think this matters more than anything else on <em>the bill of changes</em> above. When you're looking something up you're usually stuck, and you don't know the right word yet.</p>
<p>You can run the same search from a terminal too, even outside a project:</p>
<pre><code class="language-sh">pnpm exec seedcord ask how do i stop someone spamming a command
</code></pre>
<p>It prints the matching pages with a link to each section. It also takes a pasted error, or an error code like <code>3116</code>.</p>
<p>This one's really useful for coding agents. I found that out working on a bot of my own. The agent hand-wrote pagination and refusal replies, and both of those ship with seedcord. <code>tc</code> and lint pass either way, so nothing told it otherwise. Now a new project has an <code>ask</code> script, and its <code>AGENTS.md</code> tells agents to search the guide before they hand-write something. Without a terminal, the command links each page's Markdown copy, so an agent can read the page directly. <a href="https://seedcord.org/guide/tooling/ask/">Here's some more about it</a>.</p>
<p>And a nice lil feature for you keyboard people out there: shortcuts in the guide!</p>
<ul>
<li>Left and right change pages</li>
<li>Shift plus left or right changes tabs</li>
<li><code>j</code> and <code>k</code> move between sections</li>
<li><code>y</code> copies a link to the section you're on</li>
<li><code>s</code> switches sites</li>
<li><code>?</code> shows all these shortcuts</li>
</ul>
<hr />
<h2>We launched a bot</h2>
<p>Meet seed, our own Discord bot. It's built with seedcord, it runs on Cloudflare Workers, and you can <a href="https://discord.com/oauth2/authorize?client_id=1195232619718254663">add it to a server or install it on your account</a>.</p>
<p>It brings that same search into Discord, so you can look stuff up without leaving the conversation:</p>
<ul>
<li><code>/search guide</code> takes a question in your own words.</li>
<li><code>/search docs</code> finds a symbol by name. Set <code>prerelease</code> to search the <code>@next</code> versions.</li>
<li><strong>Answer with docs</strong> is a right-click on someone's message. You pick a guide section that answers it, and seed posts the link and mentions them.</li>
<li><code>/versions</code> shows the latest and next version of each seedcord package.</li>
</ul>
<p>Both <code>/search</code> commands reply only to you by default. Set <code>public</code> when everyone in the channel should see the answer.</p>
<p>There's also some nice emoji utility built into the bot, and we'll continue adding helpful features like this over time.</p>
<hr />
<h2>A key-value store</h2>
<p>Bots have to remember stuff, like a member's timezone or a reminder due tomorrow. Most of us start with a <code>Map</code> at the top of a file, and it's empty again the moment the bot restarts.</p>
<p>Every bot now has <code>core.kv</code>. You ask it for a collection, then read and write records by id:</p>
<pre><code class="language-ts">// src/handlers/Timezone.ts
@SlashRoute('timezone')
export class Timezone extends SlashHandler&lt;'timezone'&gt; {
    public async execute(): Promise&lt;void&gt; {
        const preferences = this.core.kv.collection&lt;Preferences&gt;('preferences');

        await preferences.set(this.user.id, {
            timezone: this.options.getString('zone'),
            updatedAt: new Date()
        });
        await this.reply('Saved.');
    }
}
</code></pre>
<p>Leave <code>kv</code> out of your config and records stay in memory. To keep them through a restart, pass a driver:</p>
<pre><code class="language-ts">// src/bot.ts
export const seedcord = new Seedcord({
    kv: new KeyvDriver(new Keyv(new KeyvSqlite('sqlite://./kv.sqlite')))
    // ...
});
</code></pre>
<p><code>KeyvDriver</code> and <code>UnstorageDriver</code> wrap those two libraries, so you get SQLite, Redis, Postgres, the filesystem, D1 on Workers, and more. You can also write your own driver.</p>
<p>Records go through JSON, and the types know that. If your record holds a <code>Set</code> or a <code>Map</code>, the <code>collection()</code> call doesn't compile. A <code>Date</code> reads back as a <code>string</code>, and <code>get</code> shows it that way. Plugins read the same store through <code>this.kv</code>, and the rate limiter keeps its counts there too.</p>
<p><a href="https://seedcord.org/guide/built-ins/">The guide page</a> has the rest, like records that expire.</p>
<hr />
<h2><code>seedcord make</code></h2>
<p>I've started way too many buttons by copying the last one, renaming everything, and then fixing the import path because the copy was one folder deeper. Then I'd do it all again for the handler.</p>
<p><code>seedcord make</code> writes those files from templates that you keep in your project. A template is a folder of <a href="https://handlebarsjs.com/guide/">Handlebars</a> files:</p>
<pre><code class="language-txt">templates/
└─ Button/
   ├─ components/
   │  └─ {{pascal name}}.ts.hbs
   └─ handlers/
      └─ {{pascal name}}.ts.hbs
</code></pre>
<p>You pick <code>Button</code> and type <code>tickets/Appeal</code> as the name. It then asks for each value the templates read, and writes both files:</p>
<pre><code class="language-txt">src/components/tickets/Appeal.ts
src/handlers/tickets/Appeal.ts
</code></pre>
<p>New projects start with templates for a slash command, a button, a select menu, a modal, and on gateway an event. Installed plugins can ship templates too. <a href="https://seedcord.org/guide/tooling/make/">Here's how to write your own</a>.</p>
<hr />
<h2>Plugins can write types now</h2>
<p>Say your plugin translates messages, and a bot calls <code>t('greet')</code>. You wrote that plugin before any bot existed, so all it can type is <code>string</code>. A typo only shows up when a user sees the wrong message.</p>
<p>Plugins can now define <code>codegen()</code>. Whatever it returns ends up in the bot's generated types, built from that bot's own files:</p>
<pre><code class="language-txt">1. your codegen() returns a value
   { messages: { greet: true, bye: true } }

2. seedcord codegen writes it as a type into the bot's seedcord-gen.ts
   'seedcord-locales': { messages: { bye: true; greet: true } }

3. your plugin reads it back with Generated&lt;typeof Locales&gt;['messages']
   { bye: true; greet: true }
</code></pre>
<p>The Mongoose and Kysely plugins use this already, so you can delete the <code>declare module</code> blocks that list your services.</p>
<p>Two more things came with it. <code>seedcord dev</code> has a <code>g</code> key that runs codegen without restarting your bot. The generated file is also <code>seedcord-gen.ts</code> now, because <code>skipLibCheck</code> skipped the old <code>.d.ts</code>, and a stale row in there quietly turned into <code>any</code>. Now <code>tc</code> reports it.</p>
<p><a href="https://seedcord.org/guide/writing-plugins/codegen/">Writing types from codegen</a> walks through a whole plugin.</p>
<hr />
<h2>Smaller things I really like</h2>
<p><code>this.user</code> is on every interaction handler and middleware. On http in a server, <code>this.event.user</code> is undefined and you had to go through <code>member.user</code>. Now you don't have to think about it.</p>
<p><code>this.route</code> works on event handlers and on event and interaction middleware too, the same as interaction handlers.</p>
<p><code>this.match()</code> <strong>returns what its cases return</strong>, including async ones:</p>
<pre><code class="language-ts">const outcome = await this.match({
    ban: () =&gt; ({ banned: true }),
    kick: async () =&gt; ({ notified: true })
});
</code></pre>
<p><code>outcome</code> is a union of both shapes. Pass <code>this.match&lt;string&gt;()</code> if you want every case to return one type, and TypeScript reports the case that doesn't.</p>
<p><strong>One subscriber can listen to several keys:</strong></p>
<pre><code class="language-ts">@Subscribe(['levelUp'], ['levelReset'])
export class LevelLog extends Subscriber&lt;'levelUp' | 'levelReset'&gt; {
    public async execute(): Promise&lt;void&gt; {
        await this.match({
            levelUp: (data) =&gt; this.log(data.userId, `reached ${data.level}`),
            levelReset: (data) =&gt; this.log(data.userId, 'was reset')
        });
    }
}
</code></pre>
<p><code>MentionPrefix</code> is a new gateway gate for commands like <code>@bot ping</code>. Discord sends the full text of a message that mentions your bot, even without the Message Content intent, so this gets you message commands without that intent:</p>
<pre><code class="language-ts">@Gated(IgnoreBots, MentionPrefix)
@RegisterEvent([Events.MessageCreate])
export class Mentioned extends EventHandler&lt;Events.MessageCreate&gt; {
    public async execute(): Promise&lt;void&gt; {
        const [message] = this.event;
        await message.reply(`hey ${message.author.displayName}`);
    }
}
</code></pre>
<p>And finally, <strong>replies can now take raw component json</strong> next to builders, like <code>{ type: 10, content: 'hi' }</code>. That means you can use libraries like <code>@dressed/react</code> and write your components in <code>.tsx</code> files!</p>
<hr />
<h2><code>seedcord dev</code> without a terminal</h2>
<p>When stdin or stdout is a pipe, or <code>CI</code> is set, <code>seedcord dev</code> skips the TUI and prints each log line as JSON. You can drive it by writing lines like <code>{"do":"restart"}</code> or <code>{"do":"codegen"}</code> to its stdin.</p>
<p>That means a script, a container, or a coding agent can run your bot properly. A new project's <code>AGENTS.md</code> now tells an agent to do exactly that, then ask you to run the command in Discord. I test features on real bots this way all the time. <a href="https://seedcord.org/guide/tooling/dev/">The dev page</a> lists every command.</p>
<hr />
<h2>~40 fixes</h2>
<p>Way too many to list, so here are a few you might have hit:</p>
<ul>
<li>A refused Discord login, like a bad token or disallowed intents, used to sit through the whole 10 second startup timeout. Startup now fails right away with Discord's reason.</li>
<li>Moving a handler to a new file in <code>seedcord dev</code> left its route without a handler until you restarted.</li>
<li><code>seedcord dev</code> could register a new command twice.</li>
<li>An autocomplete handler that threw could leave Discord without a response.</li>
<li>Handlers could read <code>Emojis</code> before startup filled it, if an interaction came in right after login.</li>
</ul>
<p>That god PR from earlier added 3 features and fixed 5 bugs, and it finished at +3,262 / -3,250. I'm very proud of those 12 lines.</p>
<hr />
<h2>Updating</h2>
<pre><code class="language-sh">pnpm update --latest seedcord @seedcord/gateway # or @seedcord/http
pnpm exec seedcord codegen
</code></pre>
<p>Update any seedcord plugins you use too. Now, those 20 breaking changes. Most of them only matter if you use that exact API, and your compiler points right at those. Three are worth knowing up front:</p>
<ul>
<li><code>seedcord-gen.d.ts</code> is now <code>seedcord-gen.ts</code>. Delete the old file, run codegen once, and rename it in your eslint ignores, <code>.prettierignore</code>, <code>.gitattributes</code>, and editor settings.</li>
<li>Handlers on the same event now run at the same time. Nothing warns you about this one. If one handler reads what another one writes, it can get old values, so make sure to check for that.</li>
<li><code>Paginator</code> now sends an ephemeral first page by default. Nothing warns you about this one either. Pass <code>ephemeral: false</code> to keep a list public.</li>
</ul>
<p><a href="https://github.com/seedcord/seedcord/releases/tag/release-2026.11.04">The changelog</a> has everything else.</p>
<hr />
<p>Also thanks to <a href="https://github.com/lunaradev1">lunaradev1</a>, <a href="https://github.com/KTrain5169">KTrain5169</a>, and <a href="https://github.com/SerenModz21">SerenModz21</a> for their help on this release!</p>
<p>New to seedcord? <a href="https://seedcord.org/guide/">Start here</a>. Come say hi in <a href="https://seedcord.org/chat">the Discord server</a> too.</p>
<p><em>First posted on</em> <a href="https://seedcord.org/blog/release-v0-23/"><em>the seedcord blog</em></a><em>.</em></p>
]]></content:encoded></item><item><title><![CDATA[Reading typed config from .env in TypeScript]]></title><description><![CDATA[Read .env as typed values in TypeScript: a fallback that tells missing from zero, converters, and any Standard Schema validator. Zero deps.]]></description><link>https://materwelon.hashnode.dev/reading-typed-config-from-env-in-typescript</link><guid isPermaLink="true">https://materwelon.hashnode.dev/reading-typed-config-from-env-in-typescript</guid><category><![CDATA[TypeScript]]></category><category><![CDATA[Node.js]]></category><category><![CDATA[webdev]]></category><category><![CDATA[JavaScript]]></category><category><![CDATA[Environment variables]]></category><dc:creator><![CDATA[Dhruv]]></dc:creator><pubDate>Fri, 12 Jun 2026 15:33:05 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/6a2bd41f6813342a54073887/54ca9c20-e5ab-450d-86c2-99aa603c0566.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<hr />
<p><code>Number(process.env.PORT) || 3000</code></p>
<p>That line shows up in a lot of config files, and it has two bugs hiding in it.</p>
<p>Misspell <code>PORT</code> in your <code>.env</code> and you don't get an error, you get <code>3000</code>, and you find out in production. Want to set <code>PORT=0</code> on purpose? You can't: <code>Number('0') || 3000</code> is <code>3000</code> too. The <code>|| fallback</code> can't tell "missing" from "zero," and <code>process.env</code> hands you <code>string | undefined</code> regardless, so every read sits one coercion away from a quiet bug.</p>
<p>I got tired of writing that coercion by hand and keeping it correct, so I built envapt. On Node, Bun, and Deno it reads <code>process.env</code> and your <code>.env</code> files; off Node the source is pluggable, so the same reads work on Cloudflare Workers and in the browser.</p>
<h2>The typed read</h2>
<p>Here's the same port, read so the fallback only fires when the value is actually missing:</p>
<pre><code class="language-typescript">const port = Envapter.getNumber('PORT', 3000); // number, not string | undefined
const debug = Envapter.getBoolean('DEBUG', false); // 1/yes/true/on -&gt; true
</code></pre>
<p><code>getNumber</code> returns <code>number</code>. <code>PORT=0</code> reads as <code>0</code>. A typo in <code>PORT</code> is unparseable, so it takes the fallback, but <code>0</code> is a perfectly good number and keeps it. The <code>Number(x) || default</code> trap is gone because there's no <code>||</code> deciding what counts as empty.</p>
<p>The fallback also does something to the type. Passing one strips <code>undefined</code> from the return, so nothing downstream needs a <code>?? 3000</code>:</p>
<pre><code class="language-typescript">const withFallback = Envapter.getNumber('PORT', 3000);
// withFallback: number

const noFallback = Envapter.getNumber('PORT');
// noFallback: number | undefined
</code></pre>
<p>Leave the fallback off and you get <code>number | undefined</code>. The type makes you handle the missing case instead of letting you forget. And <code>getBoolean</code> reads <code>1</code>, <code>yes</code>, <code>true</code>, <code>on</code> as true and <code>0</code>, <code>no</code>, <code>false</code>, <code>off</code> as false, case-insensitively, so <code>DEBUG=1</code> is <code>true</code> and not the silent <code>false</code> that <code>=== 'true'</code> gives you.</p>
<h2>The shapes that aren't primitives</h2>
<p>Most config isn't a bare number. It's a URL, a comma list, a JSON blob, a timeout. <code>getUsing</code> takes a converter token and hands back the matching type:</p>
<pre><code class="language-typescript">const apiUrl = Envapter.getUsing('API_URL', Converters.Url); // URL | undefined

const origins = Envapter.getUsing('ALLOWED_ORIGINS', Converters.array({ of: Converters.Url })); // URL[] | undefined

const ttl = Envapter.getUsing('CACHE_TTL', Converters.Time, '5m'); // "5m" -&gt; 300000 (ms); number
</code></pre>
<p><code>Converters.Url</code> runs the value through <code>new URL</code>, so a non-absolute URL takes the fallback instead of slipping through as a string. <code>Converters.array({ of: Converters.Url })</code> splits on the delimiter and converts each element, so the type is <code>URL[]</code>, not the <code>string[]</code> you'd <code>.split(',')</code> your way to. <code>Converters.Time</code> reads <code>5m</code> and returns <code>300000</code>, which means a timeout in your <code>.env</code> reads the way you'd write it in code rather than as a pile of zeroes you have to count.</p>
<p>The built-in tokens cover number, integer, float, boolean, bigint, symbol, JSON, URL, RegExp, Date, duration, and arrays. When none of them fit, <code>getWith</code> takes a plain <code>(raw, fallback) =&gt; T</code>:</p>
<pre><code class="language-typescript">const toBytes = (raw: string | undefined) =&gt; {
    const n = Number.parseInt(raw ?? '0', 10);
    if (/gb$/i.test(raw ?? '')) return n * 1e9;
    if (/mb$/i.test(raw ?? '')) return n * 1e6;
    if (/kb$/i.test(raw ?? '')) return n * 1e3;
    return n;
};

// MAX_BODY=10mb
const maxBody = Envapter.getWith('MAX_BODY', toBytes); // number | undefined
</code></pre>
<p>Most typed-env libraries ask you to learn their schema. envapt doesn't have one.</p>
<p>If your code already validates things with zod (or valibot, or arktype), hand that schema to envapt and it uses it:</p>
<pre><code class="language-typescript">const port = Envapter.parse('PORT', z.coerce.number().int().min(1024)); // number
</code></pre>
<p>t3-env and znv do this job too, and do it well, but they're built on zod: the validator is the dependency. envapt uses the Standard Schema interface instead, so which validator you bring is your call, and envapt itself adds nothing to your lockfile.</p>
<p><code>parse</code> runs the value through the schema and returns whatever the schema outputs, typed. A bad <code>PORT</code> throws on the <code>parse</code> line with the validator's own message, not a <code>NaN</code> that some later arithmetic turns into garbage. A third argument is an optional fallback, returned as-is on a missing value, so it has to already satisfy the type because the schema never sees it:</p>
<pre><code class="language-typescript">const timeout = Envapter.parse('TIMEOUT_MS', z.coerce.number(), 30000); // number
</code></pre>
<h2>If you'd rather have a config class</h2>
<p>The same reads bind to a class field with a decorator. The field is declared with <code>declare</code> and no initializer, and you need <code>experimentalDecorators</code> in your <code>tsconfig.json</code>:</p>
<pre><code class="language-typescript">class Config {
    @Envapt('PORT', { converter: Converters.Number, fallback: 3000 })
    declare static readonly port: number;

    @Envapt('LOG_LEVEL', { schema: z.enum(['debug', 'info', 'warn']) })
    declare static readonly logLevel: 'debug' | 'info' | 'warn';
}
</code></pre>
<p>The <code>declare</code> and the missing initializer are load-bearing. A real field declaration under <code>useDefineForClassFields</code> emits a constructor assignment that overwrites the decorator's getter with <code>undefined</code>, so the property reads back as nothing. <code>declare</code> tells the compiler the field exists without emitting that assignment. For the common types there's sugar that takes the key and an optional fallback:</p>
<pre><code class="language-typescript">class Config {
    @EnvNum('PORT', 3000) declare static readonly port: number;
    @EnvUrl('APP_URL', new URL('http://localhost:3000')) declare static readonly appUrl: URL;
    @EnvTime('CACHE_TTL', '5m') declare static readonly ttl: number; // ms
}
</code></pre>
<h2>How I actually use it</h2>
<p>In my bot framework, seedcord, which already leans on decorators, the Discord token binds to the <code>Bot</code> class that uses it, validated by a converter right at the binding:</p>
<pre><code class="language-typescript">function validateDiscordToken(raw: string | undefined): string {
    if (!raw?.trim()) throw new Error('DISCORD_BOT_TOKEN is missing');
    if (!/^[\w-]{24,}\.[\w-]{6,}\.[\w-]{27,}$/.test(raw)) {
        throw new Error('DISCORD_BOT_TOKEN is malformed');
    }
    return raw;
}

class Bot {
    @Envapt('DISCORD_BOT_TOKEN', { converter: (raw) =&gt; validateDiscordToken(raw) })
    declare public readonly botToken: string; // string; a malformed token throws here
}
</code></pre>
<p>t3-env centralizes: you declare every variable up front in one <code>createEnv</code> call, validated once at startup. envapt puts the check on the field that uses the value. Centralizing is the right call when one app owns all its env. seedcord's config is spread across independently-built pieces (the <code>Bot</code> owns the token, a webhook subscriber owns its URL), so each piece validates its own variable where it lives, and a malformed token throws the moment that field resolves instead of in a central config module three files away.</p>
<h2>The same reads, off Node</h2>
<p>On Node, Bun, and Deno, envapt reads <code>process.env</code> and the <code>.env</code> cascade with no setup. On Cloudflare Workers and in the browser there is no filesystem, so you bind the source yourself, and once it's bound the typed reads, converters, and validators are identical.</p>
<p>In a Worker, <code>env</code> is readable at module scope and constant for a deployment, so bind it once in a config module and export the typed values. That way binding happens once per isolate, not on every request:</p>
<pre><code class="language-typescript">// config.ts
import { env } from 'cloudflare:workers';
import { Envapter, WorkerEnvSource, Converters } from 'envapt/workerd';

Envapter.useSource(new WorkerEnvSource(env));
Envapter.require('ORIGIN_URL', 'API_TOKEN');

export const config = {
    origin: Envapter.getUsing('ORIGIN_URL', Converters.Url)!,
    token: Envapter.get('API_TOKEN')!
};
</code></pre>
<pre><code class="language-typescript">// index.ts
import { config } from './config';

export default {
    async fetch(request: Request): Promise&lt;Response&gt; {
        const url = new URL(request.url);
        return fetch(new URL(url.pathname + url.search, config.origin), request);
    }
} satisfies ExportedHandler;
</code></pre>
<p>In the browser, bind whatever your bundler injects:</p>
<pre><code class="language-typescript">import { Envapter, ManualEnvSource, Converters } from 'envapt/browser';

// Vite replaces import.meta.env at build time; or a webpack DefinePlugin object
Envapter.useSource(new ManualEnvSource(import.meta.env));
const apiBase = Envapter.getUsing('API_BASE_URL', Converters.Url);
</code></pre>
<p>Import from <code>envapt/workerd</code> or <code>envapt/browser</code>, not bare <code>envapt</code>: those entries pull in no <code>node:</code> modules and drop the file-only APIs from the types, so a stray file call is a compile error instead of a runtime surprise. The <code>.env</code> cascade and the file APIs stay on Node, Bun, and Deno.</p>
<h2>Loading the .env file</h2>
<p>For local development you still want a <code>.env</code> file. On Node that's usually <code>dotenv</code>. envapt parses <code>.env</code> itself, so it loads the file without adding a dependency:</p>
<pre><code class="language-typescript">import 'envapt/config';
</code></pre>
<p>That import is a drop-in for <code>dotenv/config</code>. It reads the cascade and mirrors the result into <code>process.env</code>. The cascade is per-environment and the most-specific file wins:</p>
<pre><code class="language-plaintext">.env.production.local
.env.production
.env.local
.env
</code></pre>
<p><code>\({VAR}</code> references expand while the file is parsed, so <code>DATABASE_URL=postgres://\){DB_HOST}/${DB_NAME}</code> resolves on its own. You don't strictly need that import, either. Drop it and the typed reads still work; they read the cascade directly. The import is only there for the libraries that read <code>process.env</code> straight, before envapt does.</p>
<h2>So, finally</h2>
<p>What envapt gives you is the combination: a fallback that narrows the type and tells missing from zero, converters for the shapes that aren't strings, and validation through the schema you already wrote rather than the one a helper chose for you. If that's the shape of your config problem, the docs and the v4-to-v5 migration are at <a href="https://envapt.materwelon.dev">envapt.materwelon.dev</a>, it's on <a href="https://www.npmjs.com/package/envapt">npm</a> and <a href="https://jsr.io/@materwelon/envapt">JSR</a>, and the source is on <a href="https://github.com/materwelonDhruv/envapt">GitHub</a>. Please feel free to ask questions, report bugs, or suggest features in the repo! I'm always open to feedback and contributions.</p>
]]></content:encoded></item></channel></rss>