洪 民憙 (Hong Minhee) :nonbinary:'s avatar

洪 民憙 (Hong Minhee) :nonbinary:

@hongminhee@hollo.social

1,072 following1,884 followers

An intersectionalist, feminist, and socialist living in Seoul (UTC+09:00). @tokolovesme's spouse. Who's behind @fedify, @hollo, and @botkit. Write some free software in , , , & . They/them.

서울에 사는 交叉女性主義者이자 社會主義者. 金剛兔(@tokolovesme)의 配偶者. @fedify, @hollo, @botkit 메인테이너. , , , 等으로 自由 소프트웨어 만듦.

()

Pinned

@hongminhee@hollo.social

Hello! I'm Hong Minhee (洪 民憙), an open source software engineer in my late 30s, living in Seoul, Korea. I'm bisexual and non-binary (they/them), and an enthusiastic advocate of free/open source software and the fediverse.

I work full-time on @fedify, an ActivityPub server framework in TypeScript, funded by @sovtechfund. I'm also the creator of @hollo, a single-user ActivityPub microblog; @botkit, an ActivityPub bot framework; Hackers' Pub, a fediverse platform for software developers; and LogTape, a logging library for JavaScript and TypeScript.

I have a long interest in East Asian languages (CJK) and Unicode. I post mostly in English here, though occasionally in Japanese or in mixed-script Korean (國漢文混用體), a traditional writing style that interleaves Chinese characters with the native Korean alphabet. Wanting to write in that style was actually one of the reasons I joined the fediverse. Feel free to talk to me in English, Korean, Japanese, or even Literary Chinese!

en.wikipedia.org

Korean mixed script - Wikipedia

Pinned

はじめまして!ソウル在住の30代後半のオープンソースソフトウェアエンジニア、洪 民憙ホン・ミンヒと申します。バイセクシュアル(bisexual)・ノンバイナリー(non-binary)で、自由・オープンソースソフトウェア(F/OSS)とフェディバース(fediverse)の熱烈な支持者です。

STF(@sovtechfund)の支援を受け、TypeScript用ActivityPubサーバーフレームワーク「@fedify」の開発に専念しています。他にも、おひとり様向けのActivityPubマイクロブログ「@hollo」、ActivityPubボットフレームワーク「@botkit」、ソフトウェア開発者向けフェディバースプラットフォームHackers' Pub、JavaScript・TypeScript用ロギングライブラリLogTapeなどの制作者でもあります。

東アジア言語(いわゆるCJK)とUnicodeにも興味があります。このアカウントでは主に英語で投稿していますが、時々日本語や国漢文混用体(漢字ハングル混じり文)の韓国語でも書いています。実はこの文体で書きたくてフェディバースを始めた、という経緯もあります。日本語、英語、韓国語、漢文でも気軽に話しかけてください!

speakerdeck.com

国漢文混用体からHolloまで

本発表では、韓国語の「国漢文混用体」(漢字ハングル混じり文)を自分のフェディバース投稿に実装したいという小さな目標から始まった旅路を共有します。 この目標を達成するために、ActivityPubのJSON-LDの複雑さやHTTP Signatures、WebFingerなどの仕様を理解する必要性に…

Pinned

安寧(안녕)하세요! 저는 서울에 살고 있는 30() 後半(후반)의 오픈 소스 소프트웨어 엔지니어 洪民憙(홍민희)입니다. 兩性愛者(양성애자)(bisexual)이자 논바이너리(non-binary)이며, 自由(자유)·오픈 소스 소프트웨어(F/OSS)와 聯合宇宙(연합우주)(fediverse)의 熱烈(열렬)支持者(지지자)이기도 합니다.

STF(@sovtechfund)의 支援(지원)을 받아 TypeScript() ActivityPub 서버 프레임워크 @fedify 開發(개발)專業(전업)으로 ()하고 있습니다. 그 ()에도 싱글 유저() ActivityPub 마이크로블로그 @hollo, ActivityPub 봇 프레임워크 @botkit, 소프트웨어 開發者(개발자)를 위한 聯合宇宙(연합우주) 플랫폼 Hackers' Pub, JavaScript·TypeScript() 로깅 라이브러리 LogTape ()製作者(제작자)이기도 합니다.

()아시아 言語(언어)(이른바 CJK)와 Unicode에도 關心(관심)이 많습니다. 이 計定(계정)에서는 ()英語(영어)로 포스팅하지만, 때때로 日本語(일본어)國漢文混用體(국한문 혼용체) 韓國語(한국어)로도 씁니다. 聯合宇宙(연합우주)에 오게 된 動機(동기) () 하나가 바로 國漢文混用體(국한문 혼용체)로 글을 쓰고 싶었기 때문이기도 하고요. 韓國語(한국어), 英語(영어), 日本語(일본어), 아니면 漢文(한문)으로도 말을 걸어주세요!

logtape.org

LogTape

Unobtrusive logging library with zero dependencies—library-first design for Deno, Node.js, Bun, browsers, and edge functions

複数のパーサーを合成するとき、一つでも非同期なら結果も非同期になる——これをTypeScriptの型レベルで表現するのが意外と難しかった。Optiqueでの設計過程を書きました。

https://zenn.dev/hongminhee/articles/d27ca1e6effa11

zenn.dev

TypeScriptで型安全な同期・非同期モード切り替えを実装する

@mitsuhiko@hachyderm.io · Reply to FediThing :progress_pride:

@FediThing @glyph LLMs are trained on human-created material in much the same way a person learns by reading books and then acting on what they've learned. They don't directly reproduce that material.

As I mentioned I strongly believe that broad sharing of knowledge is a net benefit to humanity. Questions of credit and attribution are a separate issue and to discuss them meaningfully, you first have to be clear about what you consider reasonable attribution in the first place.

You can take for instance the tankgame and then tell me which part should be attributed and is not, and what you would be attributing it to.

On the "against the will": I want you to use the code I wrote, it's definitely not against my will that LLMs are trained on the code I wrote over the years.

@hongminhee@hollo.social

0.9.0 is here!

This release brings /await support to parsers. Now you can validate input against external resources—databases, APIs, Git repositories—directly at parse time, with full type safety.

The new @optique/git package showcases this: validate branch names, tags, and commit SHAs against an actual Git repo, complete with shell completion suggestions.

Other highlights:

  • Hidden option support for deprecated/internal flags
  • Numeric choices in choice()
  • Security fix for shell completion scripts

Fully backward compatible—your existing parsers work unchanged.

https://github.com/dahlia/optique/discussions/75

github.com

Optique 0.9.0: Async parsers and Git reference validation · dahlia/optique · Discussion #75

We're excited to announce Optique 0.9.0! This release brings two major features: full async/await support for parsers and a new @optique/git package for validating Git references against actual rep...

@hongminhee@hollo.social

My last salaried job was at a company that built blockchain technology. No, it wasn't for cryptocurrency. The goal was to use blockchain to create a fully peer-to-peer, decentralized game. I found it a technically interesting goal. I've always been fascinated by decentralized technologies, which is also why I'm drawn to ActivityPub. Another thing that attracted me was the promise that this technology would be implemented as 100% open source. I had always wanted to work on open source full-time, so I accepted the offer.

However, once I started working there, I found myself increasingly disappointed. The organization gradually filled up with so-called “crypto bros,” and the culture shifted toward prioritizing token price over technical achievement. I and a few close colleagues believed that introducing partial centralization to the fully decentralized system—whether to defend the token price or to rush a release—was not a “minor compromise” but a “major corruption.” The rest of the organization didn't see it that way.

One of the most painful things about being in that organization was the fact that the technology I was creating was not only unhelpful to society, but was actually harming the environment and society. At the time, I felt like I was working for a tobacco company—knowing that cigarettes harm people's health, yet turning a blind eye and doing the job anyway.

I'm no fan of cryptocurrency, but I still think blockchain has technically interesting aspects. However, blockchain has already become socially inseparable from cryptocurrency, and even if blockchain is technically interesting, there are very few domains where it's actually useful. Furthermore, the negative environmental impact of blockchain technology is a problem that must be solved for it to be taken seriously. In its current state, when I weigh the harm against the utility, I believe the harm overwhelmingly outweighs it.

Anyway, I have now completely said goodbye to blockchain technology. I feel at ease now that I don't have to live with that guilt anymore. I also came to realize that engineers must consider not only the technical interest of a technology but also its social impact. So for now, I want to focus on ActivityPub. I find it both technically interesting and socially meaningful!

@hongminhee@hollo.social

Okay, I've finished the slides for my presentation at FOSDEM 2026. Of course, I'll probably keep fine-tuning them until the presentation day, but it's a weight off my shoulders. However, since I have to present in English, I need to practice delivering it in English every day from now until the event.

@mitchellh@hachyderm.io · Reply to Mitchell Hashimoto

I will repeat that I was not sitting back at all during those 6 hours. While agents were working, I was working, just on separate -- but related -- tasks. I know for a fact that I could not have completed this amount of work in 6 hours fully manually (based on the experience that I've written something like 30+ bindings to C libraries in the past decade, probably more).

@mitchellh@hachyderm.io

I wrote Zig bindings to quickjs-ng with 96% API coverage (~240 exported C decls) with unit tests, examples, and doc strings on all functions in less than 6 total hours with AI assistance. I never want to hear that AI isn't faster ever again. github.com/mitchellh/zig-quick

This isn't slop. I worked for those 6 hours.

I was reviewing everything it outputted, updating my AGENTS.md to course correct future work, ensuring the output was idiomatic Zig, writing my own tests on the side to verify its work (while it worked), and more. My work was split across ~40 separate Amp threads (not one mega session, which doesn't work anyways unless you're orchestrating).

I have a ton of experience writing bindings to libraries for various languages, especially Zig. I have never achieved this much coverage in so little time with such high quality (e.g. test coverage). My usual approach is to get bind just-enough of the surface area to do my actual work and move on. This time I thought I'd draw the whole owl, because it's a new world. And I'm very happy with the result.

Anyone with experience writing bindings knows that you do some small surface area, then the rest of the coverage is annoying repetition. That's why I usually stopped. Well, LLMs/agents are really, really good at annoying repetition and pattern matching. So going from 5% API coverage to 95% is... cake.

There is probably some corners that are kind of nasty still, but I've been re-reviewing every line of code manually and there is nothing major. Definitely some areas that can just use a nicer Zig interfaces over the C API, but that's about it.

I plan on writing a longer form blog showcasing my threads, but you can at least see the final AGENTS.md I produced in the linked repo.

github.com/mitchellh/zig-quick

github.com

GitHub - mitchellh/zig-quickjs-ng: Zig build and bindings for quickjs-ng

Zig build and bindings for quickjs-ng. Contribute to mitchellh/zig-quickjs-ng development by creating an account on GitHub.

@parksb@silicon.moe

모던코리아 한국 미술 2부작 중 <2부 여성-민중-미술>은 80년대 민주화운동과 민중미술, 여성예술가를 조명한다. "네가 아무리 잘나봤자 시집가면 끝이야", "운동하려면 음악이나 미술은 버리고 와라" 따위의 말과 싸워온 사람들의 이야기. vod.kbs.co.kr/index.html?sourc

vod.kbs.co.kr

모던코리아 한국 미술 - KBS

한국 미술 2부작 - 2부 여성-민중-미술

This time, I tried writing a prompt to draw an illustration of the mascots from the Mastodon, Lemmy, Fedify, Misskey, and Akkoma projects all getting along together.

An illustration shows the mascots of several fediverse projects happily gathered in a sunny, green meadow with rolling hills and wildflowers. In the center, the blue dinosaur mascot of Fedify holds a paper with a colorful network diagram in its mouth, smiling. To the left, the yellow elephant mascot of Mastodon walks playfully with the small white mouse mascot of Lemmy perched on its trunk. To the right, the anime-style girl mascot of Misskey, wearing a sailor uniform and cat ears, kneels and smiles, with the white Among Us-like wizard mascot of Akkoma next to her. The overall mood is cheerful and friendly.
ALT text

An illustration shows the mascots of several fediverse projects happily gathered in a sunny, green meadow with rolling hills and wildflowers. In the center, the blue dinosaur mascot of Fedify holds a paper with a colorful network diagram in its mouth, smiling. To the left, the yellow elephant mascot of Mastodon walks playfully with the small white mouse mascot of Lemmy perched on its trunk. To the right, the anime-style girl mascot of Misskey, wearing a sailor uniform and cat ears, kneels and smiles, with the white Among Us-like wizard mascot of Akkoma next to her. The overall mood is cheerful and friendly.

This time, I tried writing a prompt to draw an illustration of the mascots from the Mastodon, Lemmy, Fedify, Misskey, and Akkoma projects all getting along together.

An illustration shows the mascots of several fediverse projects happily gathered in a sunny, green meadow with rolling hills and wildflowers. In the center, the blue dinosaur mascot of Fedify holds a paper with a colorful network diagram in its mouth, smiling. To the left, the yellow elephant mascot of Mastodon walks playfully with the small white mouse mascot of Lemmy perched on its trunk. To the right, the anime-style girl mascot of Misskey, wearing a sailor uniform and cat ears, kneels and smiles, with the white Among Us-like wizard mascot of Akkoma next to her. The overall mood is cheerful and friendly.
ALT text

An illustration shows the mascots of several fediverse projects happily gathered in a sunny, green meadow with rolling hills and wildflowers. In the center, the blue dinosaur mascot of Fedify holds a paper with a colorful network diagram in its mouth, smiling. To the left, the yellow elephant mascot of Mastodon walks playfully with the small white mouse mascot of Lemmy perched on its trunk. To the right, the anime-style girl mascot of Misskey, wearing a sailor uniform and cat ears, kneels and smiles, with the white Among Us-like wizard mascot of Akkoma next to her. The overall mood is cheerful and friendly.

@hongminhee@hollo.social

Using Nano Banana Pro, I composited an image to make it look like the cute dinosaur from the Fedify logo was standing in front of the ULB (Université libre de Bruxelles) building in Brussels, where FOSDEM is held.

A photograph showing a giant, animated blue cartoon brachiosaurus standing next to a real-world brick university building with large glass windows and the letters “ULB” on the façade. The friendly-looking dinosaur holds a white paper with a colorful network diagram in its mouth. Parked cars and a street are in the foreground under an overcast sky.
ALT text

A photograph showing a giant, animated blue cartoon brachiosaurus standing next to a real-world brick university building with large glass windows and the letters “ULB” on the façade. The friendly-looking dinosaur holds a white paper with a colorful network diagram in its mouth. Parked cars and a street are in the foreground under an overcast sky.

@macrumors@mastodon.social
@hongminhee@hackers.pub

Hi ! I'm working on Hackers' Pub, a small -powered social platform for developers and tech folks.

We're currently drafting a content (/) system and would really appreciate any feedback from those who have experience with federated moderation—we're still learning.

Some ideas we're exploring:

  • Protecting reporter anonymity while giving reported users enough context to understand and improve
  • Graduated responses (warning → content removal → suspension) rather than jumping to bans
  • Using LLM to help match reports to code of conduct provisions
  • Supporting ActivityPub Flag activity for cross-instance reports

Our guiding principle is that moderation should be about growth, not punishment. Expulsion is the last resort.

Here's the full draft if you're curious: https://github.com/hackers-pub/hackerspub/issues/192.

If you've dealt with moderation in federated contexts, what challenges did you run into? What worked well? We'd love to hear your thoughts.

github.com

Implement flag (report) system for content moderation · Issue #192 · hackers-pub/hackerspub

NoteThis issue is based on the Korean specification document Hackers' Pub 신고(flag) 기능 기획서. Summary This issue proposes implementing a comprehensive flag (report) system for Hackers' Pub that allows...

@hongminhee@hollo.social

I wrote about setting up logging that's more useful than console.log() but doesn't require a Ph.D. in configuration. Covers categories, structured logging, request tracing, and production tips.

https://hackers.pub/@hongminhee/2026/logging-nodejs-deno-bun-2026

hackers.pub

Logging in Node.js (or Deno or Bun or edge functions) in 2026

It's 2 AM. Something is wrong in production. Users are complaining, but you're not sure what's happening—your only clues are a handful of console.log statements you sprinkled around during development. Half of them say things like “here” or “this works.” The other half dump entire objects that scroll off the screen. Good luck. We've all been there. And yet, setting up “proper” logging often feels like overkill. Traditional logging libraries like winston or Pino come with their own learning curves, configuration formats, and assumptions about how you'll deploy your app. If you're working with edge functions or trying to keep your bundle small, adding a logging library can feel like bringing a sledgehammer to hang a picture frame. I'm a fan of the “just enough” approach—more than raw console.log, but without the weight of a full-blown logging framework. We'll start from console.log(), understand its real limitations (not the exaggerated ones), and work toward a setup that's actually useful. I'll be using LogTape for the examples—it's a zero-dependency logging library that works across Node.js, Deno, Bun, and edge functions, and stays out of your way when you don't need it. Starting with console methods—and where they fall short The console object is JavaScript's great equalizer. It's built-in, it works everywhere, and it requires zero setup. You even get basic severity levels: console.debug(), console.info(), console.warn(), and console.error(). In browser DevTools and some terminal environments, these show up with different colors or icons. console.debug("Connecting to database...");console.info("Server started on port 3000");console.warn("Cache miss for user 123");console.error("Failed to process payment"); For small scripts or quick debugging, this is perfectly fine. But once your application grows beyond a few files, the cracks start to show: No filtering without code changes. Want to hide debug messages in production? You'll need to wrap every console.debug() call in a conditional, or find-and-replace them all. There's no way to say “show me only warnings and above” at runtime. Everything goes to the console. What if you want to write logs to a file? Send errors to Sentry? Stream logs to CloudWatch? You'd have to replace every console.* call with something else—and hope you didn't miss any. No context about where logs come from. When your app has dozens of modules, a log message like “Connection failed” doesn't tell you much. Was it the database? The cache? A third-party API? You end up prefixing every message manually: console.error("[database] Connection failed"). No structured data. Modern log analysis tools work best with structured data (JSON). But console.log("User logged in", { userId: 123 }) just prints User logged in { userId: 123 } as a string—not very useful for querying later. Libraries pollute your logs. If you're using a library that logs with console.*, those messages show up whether you want them or not. And if you're writing a library, your users might not appreciate unsolicited log messages. What you actually need from a logging system Before diving into code, let's think about what would actually solve the problems above. Not a wish list of features, but the practical stuff that makes a difference when you're debugging at 2 AM or trying to understand why requests are slow. Log levels with filtering A logging system should let you categorize messages by severity—trace, debug, info, warning, error, fatal—and then filter them based on what you need. During development, you want to see everything. In production, maybe just warnings and above. The key is being able to change this without touching your code. Categories When your app grows beyond a single file, you need to know where logs are coming from. A good logging system lets you tag logs with categories like ["my-app", "database"] or ["my-app", "auth", "oauth"]. Even better, it lets you set different log levels for different categories—maybe you want debug logs from the database module but only warnings from everything else. Sinks (multiple output destinations) “Sink” is just a fancy word for “where logs go.” You might want logs to go to the console during development, to files in production, and to an external service like Sentry or CloudWatch for errors. A good logging system lets you configure multiple sinks and route different logs to different destinations. Structured logging Instead of logging strings, you log objects with properties. This makes logs machine-readable and queryable: // Instead of this:logger.info("User 123 logged in from 192.168.1.1");// You do this:logger.info("User logged in", { userId: 123, ip: "192.168.1.1" }); Now you can search for all logs where userId === 123 or filter by IP address. Context for request tracing In a web server, you often want all logs from a single request to share a common identifier (like a request ID). This makes it possible to trace a request's journey through your entire system. Getting started with LogTape There are plenty of logging libraries out there. winston has been around forever and has a plugin for everything. Pino is fast and outputs JSON. bunyan, log4js, signale—the list goes on. So why LogTape? A few reasons stood out to me: Zero dependencies. Not “few dependencies”—actually zero. In an era where a single npm install can pull in hundreds of packages, this matters for security, bundle size, and not having to wonder why your lockfile just changed. Works everywhere. The same code runs on Node.js, Deno, Bun, browsers, and edge functions like Cloudflare Workers. No polyfills, no conditional imports, no “this feature only works on Node.” Doesn't force itself on users. If you're writing a library, you can add logging without your users ever knowing—unless they want to see the logs. This is a surprisingly rare feature. Let's set it up: npm add @logtape/logtape # npmpnpm add @logtape/logtape # pnpmyarn add @logtape/logtape # Yarndeno add jsr:@logtape/logtape # Denobun add @logtape/logtape # Bun Configuration happens once, at your application's entry point: import { configure, getConsoleSink, getLogger } from "@logtape/logtape";await configure({ sinks: { console: getConsoleSink(), // Where logs go }, loggers: [ { category: ["my-app"], lowestLevel: "debug", sinks: ["console"] }, // What to log ],});// Now you can log from anywhere in your app:const logger = getLogger(["my-app", "server"]);logger.info`Server started on port 3000`;logger.debug`Request received: ${{ method: "GET", path: "/api/users" }}`; Notice a few things: Configuration is explicit. You decide where logs go (sinks) and which logs to show (lowestLevel). Categories are hierarchical. The logger ["my-app", "server"] inherits settings from ["my-app"]. Template literals work. You can use backticks for a natural logging syntax. Categories and filtering: Controlling log verbosity Here's a scenario: you're debugging a database issue. You want to see every query, every connection attempt, every retry. But you don't want to wade through thousands of HTTP request logs to find them. Categories let you solve this. Instead of one global log level, you can set different verbosity for different parts of your application. await configure({ sinks: { console: getConsoleSink(), }, loggers: [ { category: ["my-app"], lowestLevel: "info", sinks: ["console"] }, // Default: info and above { category: ["my-app", "database"], lowestLevel: "debug", sinks: ["console"] }, // DB module: show debug too ],}); Now when you log from different parts of your app: // In your database module:const dbLogger = getLogger(["my-app", "database"]);dbLogger.debug`Executing query: ${sql}`; // This shows up// In your HTTP module:const httpLogger = getLogger(["my-app", "http"]);httpLogger.debug`Received request`; // This is filtered out (below "info")httpLogger.info`GET /api/users 200`; // This shows up Controlling third-party library logs If you're using libraries that also use LogTape, you can control their logs separately: await configure({ sinks: { console: getConsoleSink() }, loggers: [ { category: ["my-app"], lowestLevel: "debug", sinks: ["console"] }, // Only show warnings and above from some-library { category: ["some-library"], lowestLevel: "warning", sinks: ["console"] }, ],}); The root logger Sometimes you want a catch-all configuration. The root logger (empty category []) catches everything: await configure({ sinks: { console: getConsoleSink() }, loggers: [ // Catch all logs at info level { category: [], lowestLevel: "info", sinks: ["console"] }, // But show debug for your app { category: ["my-app"], lowestLevel: "debug", sinks: ["console"] }, ],}); Log levels and when to use them LogTape has six log levels. Choosing the right one isn't just about severity—it's about who needs to see the message and when. LevelWhen to use ittraceVery detailed diagnostic info. Loop iterations, function entry/exit. Usually only enabled when hunting a specific bug.debugInformation useful during development. Variable values, state changes, flow control decisions.infoNormal operational messages. “Server started,” “User logged in,” “Job completed.”warningSomething unexpected happened, but the app can continue. Deprecated API usage, retry attempts, missing optional config.errorSomething failed. An operation couldn't complete, but the app is still running.fatalThe app is about to crash or is in an unrecoverable state.const logger = getLogger(["my-app"]);logger.trace`Entering processUser function`;logger.debug`Processing user ${{ userId: 123 }}`;logger.info`User successfully created`;logger.warn`Rate limit approaching: ${980}/1000 requests`;logger.error`Failed to save user: ${error.message}`;logger.fatal`Database connection lost, shutting down`; A good rule of thumb: in production, you typically run at info or warning level. During development or when debugging, you drop down to debug or trace. Structured logging: Beyond plain text At some point, you'll want to search your logs. “Show me all errors from the payment service in the last hour.” “Find all requests from user 12345.” “What's the average response time for the /api/users endpoint?” If your logs are plain text strings, these queries are painful. You end up writing regexes, hoping the log format is consistent, and cursing past-you for not thinking ahead. Structured logging means attaching data to your logs as key-value pairs, not just embedding them in strings. This makes logs machine-readable and queryable. LogTape supports two syntaxes for this: Template literals (great for simple messages) const userId = 123;const action = "login";logger.info`User ${userId} performed ${action}`; Message templates with properties (great for structured data) logger.info("User performed action", { userId: 123, action: "login", ip: "192.168.1.1", timestamp: new Date().toISOString(),}); You can reference properties in your message using placeholders: logger.info("User {userId} logged in from {ip}", { userId: 123, ip: "192.168.1.1",});// Output: User 123 logged in from 192.168.1.1 Nested property access LogTape supports dot notation and array indexing in placeholders: logger.info("Order {order.id} placed by {order.customer.name}", { order: { id: "ORD-001", customer: { name: "Alice", email: "alice@example.com" }, },});logger.info("First item: {items[0].name}", { items: [{ name: "Widget", price: 9.99 }],}); Machine-readable output with JSON Lines For production, you often want logs as JSON (one object per line). LogTape has a built-in formatter for this: import { configure, getConsoleSink, jsonLinesFormatter } from "@logtape/logtape";await configure({ sinks: { console: getConsoleSink({ formatter: jsonLinesFormatter }), }, loggers: [ { category: [], lowestLevel: "info", sinks: ["console"] }, ],}); Output: {"@timestamp":"2026-01-15T10:30:00.000Z","level":"INFO","message":"User logged in","logger":"my-app","properties":{"userId":123}} Sending logs to different destinations (sinks) So far we've been sending everything to the console. That's fine for development, but in production you'll likely want logs to go elsewhere—or to multiple places at once. Think about it: console output disappears when the process restarts. If your server crashes at 3 AM, you want those logs to be somewhere persistent. And when an error occurs, you might want it to show up in your error tracking service immediately, not just sit in a log file waiting for someone to grep through it. This is where sinks come in. A sink is just a function that receives log records and does something with them. LogTape comes with several built-in sinks, and creating your own is trivial. Console sink The simplest sink—outputs to the console: import { getConsoleSink } from "@logtape/logtape";const consoleSink = getConsoleSink(); File sink For writing logs to files, install the @logtape/file package: npm add @logtape/fileimport { getFileSink, getRotatingFileSink } from "@logtape/file";// Simple file sinkconst fileSink = getFileSink("app.log");// Rotating file sink (rotates when file reaches 10MB, keeps 5 old files)const rotatingFileSink = getRotatingFileSink("app.log", { maxSize: 10 * 1024 * 1024, // 10MB maxFiles: 5,}); Why rotating files? Without rotation, your log file grows indefinitely until it fills up the disk. With rotation, old logs are automatically archived and eventually deleted, keeping disk usage under control. This is especially important for long-running servers. External services For production systems, you often want logs to go to specialized services that provide search, alerting, and visualization. LogTape has packages for popular services: // OpenTelemetry (for observability platforms like Jaeger, Honeycomb, Datadog)import { getOpenTelemetrySink } from "@logtape/otel";// Sentry (for error tracking with stack traces and context)import { getSentrySink } from "@logtape/sentry";// AWS CloudWatch Logs (for AWS-native log aggregation)import { getCloudWatchLogsSink } from "@logtape/cloudwatch-logs"; The OpenTelemetry sink is particularly useful if you're already using OpenTelemetry for tracing—your logs will automatically correlate with your traces, making debugging distributed systems much easier. Multiple sinks Here's where things get interesting. You can send different logs to different destinations based on their level or category: await configure({ sinks: { console: getConsoleSink(), file: getFileSink("app.log"), errors: getSentrySink(), }, loggers: [ { category: [], lowestLevel: "info", sinks: ["console", "file"] }, // Everything to console + file { category: [], lowestLevel: "error", sinks: ["errors"] }, // Errors also go to Sentry ],}); Notice that a log record can go to multiple sinks. An error log in this configuration goes to the console, the file, and Sentry. This lets you have comprehensive local logs while also getting immediate alerts for critical issues. Custom sinks Sometimes you need to send logs somewhere that doesn't have a pre-built sink. Maybe you have an internal logging service, or you want to send logs to a Slack channel, or store them in a database. A sink is just a function that takes a LogRecord. That's it: import type { Sink } from "@logtape/logtape";const slackSink: Sink = (record) => { // Only send errors and fatals to Slack if (record.level === "error" || record.level === "fatal") { fetch("https://hooks.slack.com/services/YOUR/WEBHOOK/URL", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ text: `[${record.level.toUpperCase()}] ${record.message.join("")}`, }), }); }}; The simplicity of sink functions means you can integrate LogTape with virtually any logging backend in just a few lines of code. Request tracing with contexts Here's a scenario you've probably encountered: a user reports an error, you check the logs, and you find a sea of interleaved messages from dozens of concurrent requests. Which log lines belong to the user's request? Good luck figuring that out. This is where request tracing comes in. The idea is simple: assign a unique identifier to each request, and include that identifier in every log message produced while handling that request. Now you can filter your logs by request ID and see exactly what happened, in order, for that specific request. LogTape supports this through contexts—a way to attach properties to log messages without passing them around explicitly. Explicit context The simplest approach is to create a logger with attached properties using .with(): function handleRequest(req: Request) { const requestId = crypto.randomUUID(); const logger = getLogger(["my-app", "http"]).with({ requestId }); logger.info`Request received`; // Includes requestId automatically processRequest(req, logger); logger.info`Request completed`; // Also includes requestId} This works well when you're passing the logger around explicitly. But what about code that's deeper in your call stack? What about code in libraries that don't know about your logger instance? Implicit context This is where implicit contexts shine. Using withContext(), you can set properties that automatically appear in all log messages within a callback—even in nested function calls, async operations, and third-party libraries (as long as they use LogTape). First, enable implicit contexts in your configuration: import { configure, getConsoleSink } from "@logtape/logtape";import { AsyncLocalStorage } from "node:async_hooks";await configure({ sinks: { console: getConsoleSink() }, loggers: [ { category: ["my-app"], lowestLevel: "debug", sinks: ["console"] }, ], contextLocalStorage: new AsyncLocalStorage(),}); Then use withContext() in your request handler: import { withContext, getLogger } from "@logtape/logtape";function handleRequest(req: Request) { const requestId = crypto.randomUUID(); return withContext({ requestId }, async () => { // Every log message in this callback includes requestId—automatically const logger = getLogger(["my-app"]); logger.info`Processing request`; await validateInput(req); // Logs here include requestId await processBusinessLogic(req); // Logs here too await saveToDatabase(req); // And here logger.info`Request complete`; });} The magic is that validateInput, processBusinessLogic, and saveToDatabase don't need to know anything about the request ID. They just call getLogger() and log normally, and the request ID appears in their logs automatically. This works even across async boundaries—the context follows the execution flow, not the call stack. This is incredibly powerful for debugging. When something goes wrong, you can search for the request ID and see every log message from every module that was involved in handling that request. Framework integrations Setting up request tracing manually can be tedious. LogTape has dedicated packages for popular frameworks that handle this automatically: // Expressimport { expressLogger } from "@logtape/express";app.use(expressLogger());// Fastifyimport { getLogTapeFastifyLogger } from "@logtape/fastify";const app = Fastify({ loggerInstance: getLogTapeFastifyLogger() });// Honoimport { honoLogger } from "@logtape/hono";app.use(honoLogger());// Koaimport { koaLogger } from "@logtape/koa";app.use(koaLogger()); These middlewares automatically generate request IDs, set up implicit contexts, and log request/response information. You get comprehensive request logging with a single line of code. Using LogTape in libraries vs applications If you've ever used a library that spams your console with unwanted log messages, you know how annoying it can be. And if you've ever tried to add logging to your own library, you've faced a dilemma: should you use console.log() and annoy your users? Require them to install and configure a specific logging library? Or just... not log anything? LogTape solves this with its library-first design. Libraries can add as much logging as they want, and it costs their users nothing unless they explicitly opt in. If you're writing a library The rule is simple: use getLogger() to log, but never call configure(). Configuration is the application's responsibility, not the library's. // my-library/src/database.tsimport { getLogger } from "@logtape/logtape";const logger = getLogger(["my-library", "database"]);export function connect(url: string) { logger.debug`Connecting to ${url}`; // ... connection logic ... logger.info`Connected successfully`;} What happens when someone uses your library? If they haven't configured LogTape, nothing happens. The log calls are essentially no-ops—no output, no errors, no performance impact. Your library works exactly as if the logging code wasn't there. If they have configured LogTape, they get full control. They can see your library's debug logs if they're troubleshooting an issue, or silence them entirely if they're not interested. They decide, not you. This is fundamentally different from using console.log() in a library. With console.log(), your users have no choice—they see your logs whether they want to or not. With LogTape, you give them the power to decide. If you're writing an application You configure LogTape once in your entry point. This single configuration controls logging for your entire application, including any libraries that use LogTape: await configure({ sinks: { console: getConsoleSink() }, loggers: [ { category: ["my-app"], lowestLevel: "debug", sinks: ["console"] }, // Your app: verbose { category: ["my-library"], lowestLevel: "warning", sinks: ["console"] }, // Library: quiet { category: ["noisy-library"], lowestLevel: "fatal", sinks: [] }, // That one library: silent ],}); This separation of concerns—libraries log, applications configure—makes for a much healthier ecosystem. Library authors can add detailed logging for debugging without worrying about annoying their users. Application developers can tune logging to their needs without digging through library code. Migrating from another logger? If your application already uses winston, Pino, or another logging library, you don't have to migrate everything at once. LogTape provides adapters that route LogTape logs to your existing logging setup: import { install } from "@logtape/adaptor-winston";import winston from "winston";install(winston.createLogger({ /* your existing config */ })); This is particularly useful when you want to use a library that uses LogTape, but you're not ready to switch your whole application over. The library's logs will flow through your existing winston (or Pino) configuration, and you can migrate gradually if you choose to. Production considerations Development and production have different needs. During development, you want verbose logs, pretty formatting, and immediate feedback. In production, you care about performance, reliability, and not leaking sensitive data. Here are some things to keep in mind. Non-blocking mode By default, logging is synchronous—when you call logger.info(), the message is written to the sink before the function returns. This is fine for development, but in a high-throughput production environment, the I/O overhead of writing every log message can add up. Non-blocking mode buffers log messages and writes them in the background: const consoleSink = getConsoleSink({ nonBlocking: true });const fileSink = getFileSink("app.log", { nonBlocking: true }); The tradeoff is that logs might be slightly delayed, and if your process crashes, some buffered logs might be lost. But for most production workloads, the performance benefit is worth it. Sensitive data redaction Logs have a way of ending up in unexpected places—log aggregation services, debugging sessions, support tickets. If you're logging request data, user information, or API responses, you might accidentally expose sensitive information like passwords, API keys, or personal data. LogTape's @logtape/redaction package helps you catch these before they become a problem: import { redactByPattern, EMAIL_ADDRESS_PATTERN, CREDIT_CARD_NUMBER_PATTERN, type RedactionPattern,} from "@logtape/redaction";import { defaultConsoleFormatter, configure, getConsoleSink } from "@logtape/logtape";const BEARER_TOKEN_PATTERN: RedactionPattern = { pattern: /Bearer [A-Za-z0-9\-._~+\/]+=*/g, replacement: "[REDACTED]",};const formatter = redactByPattern(defaultConsoleFormatter, [ EMAIL_ADDRESS_PATTERN, CREDIT_CARD_NUMBER_PATTERN, BEARER_TOKEN_PATTERN,]);await configure({ sinks: { console: getConsoleSink({ formatter }), }, // ...}); With this configuration, email addresses, credit card numbers, and bearer tokens are automatically replaced with [REDACTED] in your log output. The @logtape/redaction package comes with built-in patterns for common sensitive data types, and you can define custom patterns for anything else. It's not foolproof—you should still be mindful of what you log—but it provides a safety net. See the redaction documentation for more patterns and field-based redaction. Edge functions and serverless Edge functions (Cloudflare Workers, Vercel Edge Functions, etc.) have a unique constraint: they can be terminated immediately after returning a response. If you have buffered logs that haven't been flushed yet, they'll be lost. The solution is to explicitly flush logs before returning: import { configure, dispose } from "@logtape/logtape";export default { async fetch(request, env, ctx) { await configure({ /* ... */ }); // ... handle request ... ctx.waitUntil(dispose()); // Flush logs before worker terminates return new Response("OK"); },}; The dispose() function flushes all buffered logs and cleans up resources. By passing it to ctx.waitUntil(), you ensure the worker stays alive long enough to finish writing logs, even after the response has been sent. Wrapping up Logging isn't glamorous, but it's one of those things that makes a huge difference when something goes wrong. The setup I've described here—categories for organization, structured data for queryability, contexts for request tracing—isn't complicated, but it's a significant step up from scattered console.log statements. LogTape isn't the only way to achieve this, but I've found it hits a nice sweet spot: powerful enough for production use, simple enough that you're not fighting the framework, and light enough that you don't feel guilty adding it to a library. If you want to dig deeper, the LogTape documentation covers advanced topics like custom filters, the “fingers crossed” pattern for buffering debug logs until an error occurs, and more sink options. The GitHub repository is also a good place to report issues or see what's coming next. Now go add some proper logging to that side project you've been meaning to clean up. Your future 2 AM self will thank you.

@hongminhee@hackers.pub

It's 2 AM. Something is wrong in production. Users are complaining, but you're not sure what's happening—your only clues are a handful of console.log statements you sprinkled around during development. Half of them say things like “here” or “this works.” The other half dump entire objects that scroll off the screen. Good luck.

We've all been there. And yet, setting up “proper” logging often feels like overkill. Traditional logging libraries like winston or Pino come with their own learning curves, configuration formats, and assumptions about how you'll deploy your app. If you're working with edge functions or trying to keep your bundle small, adding a logging library can feel like bringing a sledgehammer to hang a picture frame.

I'm a fan of the “just enough” approach—more than raw console.log, but without the weight of a full-blown logging framework. We'll start from console.log(), understand its real limitations (not the exaggerated ones), and work toward a setup that's actually useful. I'll be using LogTape for the examples—it's a zero-dependency logging library that works across Node.js, Deno, Bun, and edge functions, and stays out of your way when you don't need it.

Starting with console methods—and where they fall short

The console object is JavaScript's great equalizer. It's built-in, it works everywhere, and it requires zero setup. You even get basic severity levels: console.debug(), console.info(), console.warn(), and console.error(). In browser DevTools and some terminal environments, these show up with different colors or icons.

console.debug("Connecting to database...");
console.info("Server started on port 3000");
console.warn("Cache miss for user 123");
console.error("Failed to process payment");

For small scripts or quick debugging, this is perfectly fine. But once your application grows beyond a few files, the cracks start to show:

No filtering without code changes. Want to hide debug messages in production? You'll need to wrap every console.debug() call in a conditional, or find-and-replace them all. There's no way to say “show me only warnings and above” at runtime.

Everything goes to the console. What if you want to write logs to a file? Send errors to Sentry? Stream logs to CloudWatch? You'd have to replace every console.* call with something else—and hope you didn't miss any.

No context about where logs come from. When your app has dozens of modules, a log message like “Connection failed” doesn't tell you much. Was it the database? The cache? A third-party API? You end up prefixing every message manually: console.error("[database] Connection failed").

No structured data. Modern log analysis tools work best with structured data (JSON). But console.log("User logged in", { userId: 123 }) just prints User logged in { userId: 123 } as a string—not very useful for querying later.

Libraries pollute your logs. If you're using a library that logs with console.*, those messages show up whether you want them or not. And if you're writing a library, your users might not appreciate unsolicited log messages.

What you actually need from a logging system

Before diving into code, let's think about what would actually solve the problems above. Not a wish list of features, but the practical stuff that makes a difference when you're debugging at 2 AM or trying to understand why requests are slow.

Log levels with filtering

A logging system should let you categorize messages by severity—trace, debug, info, warning, error, fatal—and then filter them based on what you need. During development, you want to see everything. In production, maybe just warnings and above. The key is being able to change this without touching your code.

Categories

When your app grows beyond a single file, you need to know where logs are coming from. A good logging system lets you tag logs with categories like ["my-app", "database"] or ["my-app", "auth", "oauth"]. Even better, it lets you set different log levels for different categories—maybe you want debug logs from the database module but only warnings from everything else.

Sinks (multiple output destinations)

“Sink” is just a fancy word for “where logs go.” You might want logs to go to the console during development, to files in production, and to an external service like Sentry or CloudWatch for errors. A good logging system lets you configure multiple sinks and route different logs to different destinations.

Structured logging

Instead of logging strings, you log objects with properties. This makes logs machine-readable and queryable:

// Instead of this:
logger.info("User 123 logged in from 192.168.1.1");

// You do this:
logger.info("User logged in", { userId: 123, ip: "192.168.1.1" });

Now you can search for all logs where userId === 123 or filter by IP address.

Context for request tracing

In a web server, you often want all logs from a single request to share a common identifier (like a request ID). This makes it possible to trace a request's journey through your entire system.

Getting started with LogTape

There are plenty of logging libraries out there. winston has been around forever and has a plugin for everything. Pino is fast and outputs JSON. bunyan, log4js, signale—the list goes on.

So why LogTape? A few reasons stood out to me:

Zero dependencies. Not “few dependencies”—actually zero. In an era where a single npm install can pull in hundreds of packages, this matters for security, bundle size, and not having to wonder why your lockfile just changed.

Works everywhere. The same code runs on Node.js, Deno, Bun, browsers, and edge functions like Cloudflare Workers. No polyfills, no conditional imports, no “this feature only works on Node.”

Doesn't force itself on users. If you're writing a library, you can add logging without your users ever knowing—unless they want to see the logs. This is a surprisingly rare feature.

Let's set it up:

npm add @logtape/logtape       # npm
pnpm add @logtape/logtape      # pnpm
yarn add @logtape/logtape      # Yarn
deno add jsr:@logtape/logtape  # Deno
bun add @logtape/logtape       # Bun

Configuration happens once, at your application's entry point:

import { configure, getConsoleSink, getLogger } from "@logtape/logtape";

await configure({
  sinks: {
    console: getConsoleSink(),  // Where logs go
  },
  loggers: [
    { category: ["my-app"], lowestLevel: "debug", sinks: ["console"] },  // What to log
  ],
});

// Now you can log from anywhere in your app:
const logger = getLogger(["my-app", "server"]);
logger.info`Server started on port 3000`;
logger.debug`Request received: ${{ method: "GET", path: "/api/users" }}`;

Notice a few things:

  1. Configuration is explicit. You decide where logs go (sinks) and which logs to show (lowestLevel).
  2. Categories are hierarchical. The logger ["my-app", "server"] inherits settings from ["my-app"].
  3. Template literals work. You can use backticks for a natural logging syntax.

Categories and filtering: Controlling log verbosity

Here's a scenario: you're debugging a database issue. You want to see every query, every connection attempt, every retry. But you don't want to wade through thousands of HTTP request logs to find them.

Categories let you solve this. Instead of one global log level, you can set different verbosity for different parts of your application.

await configure({
  sinks: {
    console: getConsoleSink(),
  },
  loggers: [
    { category: ["my-app"], lowestLevel: "info", sinks: ["console"] },  // Default: info and above
    { category: ["my-app", "database"], lowestLevel: "debug", sinks: ["console"] },  // DB module: show debug too
  ],
});

Now when you log from different parts of your app:

// In your database module:
const dbLogger = getLogger(["my-app", "database"]);
dbLogger.debug`Executing query: ${sql}`;  // This shows up

// In your HTTP module:
const httpLogger = getLogger(["my-app", "http"]);
httpLogger.debug`Received request`;  // This is filtered out (below "info")
httpLogger.info`GET /api/users 200`;  // This shows up

Controlling third-party library logs

If you're using libraries that also use LogTape, you can control their logs separately:

await configure({
  sinks: { console: getConsoleSink() },
  loggers: [
    { category: ["my-app"], lowestLevel: "debug", sinks: ["console"] },
    // Only show warnings and above from some-library
    { category: ["some-library"], lowestLevel: "warning", sinks: ["console"] },
  ],
});

The root logger

Sometimes you want a catch-all configuration. The root logger (empty category []) catches everything:

await configure({
  sinks: { console: getConsoleSink() },
  loggers: [
    // Catch all logs at info level
    { category: [], lowestLevel: "info", sinks: ["console"] },
    // But show debug for your app
    { category: ["my-app"], lowestLevel: "debug", sinks: ["console"] },
  ],
});

Log levels and when to use them

LogTape has six log levels. Choosing the right one isn't just about severity—it's about who needs to see the message and when.

Level When to use it
trace Very detailed diagnostic info. Loop iterations, function entry/exit. Usually only enabled when hunting a specific bug.
debug Information useful during development. Variable values, state changes, flow control decisions.
info Normal operational messages. “Server started,” “User logged in,” “Job completed.”
warning Something unexpected happened, but the app can continue. Deprecated API usage, retry attempts, missing optional config.
error Something failed. An operation couldn't complete, but the app is still running.
fatal The app is about to crash or is in an unrecoverable state.
const logger = getLogger(["my-app"]);

logger.trace`Entering processUser function`;
logger.debug`Processing user ${{ userId: 123 }}`;
logger.info`User successfully created`;
logger.warn`Rate limit approaching: ${980}/1000 requests`;
logger.error`Failed to save user: ${error.message}`;
logger.fatal`Database connection lost, shutting down`;

A good rule of thumb: in production, you typically run at info or warning level. During development or when debugging, you drop down to debug or trace.

Structured logging: Beyond plain text

At some point, you'll want to search your logs. “Show me all errors from the payment service in the last hour.” “Find all requests from user 12345.” “What's the average response time for the /api/users endpoint?”

If your logs are plain text strings, these queries are painful. You end up writing regexes, hoping the log format is consistent, and cursing past-you for not thinking ahead.

Structured logging means attaching data to your logs as key-value pairs, not just embedding them in strings. This makes logs machine-readable and queryable.

LogTape supports two syntaxes for this:

Template literals (great for simple messages)

const userId = 123;
const action = "login";
logger.info`User ${userId} performed ${action}`;

Message templates with properties (great for structured data)

logger.info("User performed action", {
  userId: 123,
  action: "login",
  ip: "192.168.1.1",
  timestamp: new Date().toISOString(),
});

You can reference properties in your message using placeholders:

logger.info("User {userId} logged in from {ip}", {
  userId: 123,
  ip: "192.168.1.1",
});
// Output: User 123 logged in from 192.168.1.1

Nested property access

LogTape supports dot notation and array indexing in placeholders:

logger.info("Order {order.id} placed by {order.customer.name}", {
  order: {
    id: "ORD-001",
    customer: { name: "Alice", email: "alice@example.com" },
  },
});

logger.info("First item: {items[0].name}", {
  items: [{ name: "Widget", price: 9.99 }],
});

Machine-readable output with JSON Lines

For production, you often want logs as JSON (one object per line). LogTape has a built-in formatter for this:

import { configure, getConsoleSink, jsonLinesFormatter } from "@logtape/logtape";

await configure({
  sinks: {
    console: getConsoleSink({ formatter: jsonLinesFormatter }),
  },
  loggers: [
    { category: [], lowestLevel: "info", sinks: ["console"] },
  ],
});

Output:

{"@timestamp":"2026-01-15T10:30:00.000Z","level":"INFO","message":"User logged in","logger":"my-app","properties":{"userId":123}}

Sending logs to different destinations (sinks)

So far we've been sending everything to the console. That's fine for development, but in production you'll likely want logs to go elsewhere—or to multiple places at once.

Think about it: console output disappears when the process restarts. If your server crashes at 3 AM, you want those logs to be somewhere persistent. And when an error occurs, you might want it to show up in your error tracking service immediately, not just sit in a log file waiting for someone to grep through it.

This is where sinks come in. A sink is just a function that receives log records and does something with them. LogTape comes with several built-in sinks, and creating your own is trivial.

Console sink

The simplest sink—outputs to the console:

import { getConsoleSink } from "@logtape/logtape";

const consoleSink = getConsoleSink();

File sink

For writing logs to files, install the @logtape/file package:

npm add @logtape/file
import { getFileSink, getRotatingFileSink } from "@logtape/file";

// Simple file sink
const fileSink = getFileSink("app.log");

// Rotating file sink (rotates when file reaches 10MB, keeps 5 old files)
const rotatingFileSink = getRotatingFileSink("app.log", {
  maxSize: 10 * 1024 * 1024,  // 10MB
  maxFiles: 5,
});

Why rotating files? Without rotation, your log file grows indefinitely until it fills up the disk. With rotation, old logs are automatically archived and eventually deleted, keeping disk usage under control. This is especially important for long-running servers.

External services

For production systems, you often want logs to go to specialized services that provide search, alerting, and visualization. LogTape has packages for popular services:

// OpenTelemetry (for observability platforms like Jaeger, Honeycomb, Datadog)
import { getOpenTelemetrySink } from "@logtape/otel";

// Sentry (for error tracking with stack traces and context)
import { getSentrySink } from "@logtape/sentry";

// AWS CloudWatch Logs (for AWS-native log aggregation)
import { getCloudWatchLogsSink } from "@logtape/cloudwatch-logs";

The OpenTelemetry sink is particularly useful if you're already using OpenTelemetry for tracing—your logs will automatically correlate with your traces, making debugging distributed systems much easier.

Multiple sinks

Here's where things get interesting. You can send different logs to different destinations based on their level or category:

await configure({
  sinks: {
    console: getConsoleSink(),
    file: getFileSink("app.log"),
    errors: getSentrySink(),
  },
  loggers: [
    { category: [], lowestLevel: "info", sinks: ["console", "file"] },  // Everything to console + file
    { category: [], lowestLevel: "error", sinks: ["errors"] },  // Errors also go to Sentry
  ],
});

Notice that a log record can go to multiple sinks. An error log in this configuration goes to the console, the file, and Sentry. This lets you have comprehensive local logs while also getting immediate alerts for critical issues.

Custom sinks

Sometimes you need to send logs somewhere that doesn't have a pre-built sink. Maybe you have an internal logging service, or you want to send logs to a Slack channel, or store them in a database.

A sink is just a function that takes a LogRecord. That's it:

import type { Sink } from "@logtape/logtape";

const slackSink: Sink = (record) => {
  // Only send errors and fatals to Slack
  if (record.level === "error" || record.level === "fatal") {
    fetch("https://hooks.slack.com/services/YOUR/WEBHOOK/URL", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({
        text: `[${record.level.toUpperCase()}] ${record.message.join("")}`,
      }),
    });
  }
};

The simplicity of sink functions means you can integrate LogTape with virtually any logging backend in just a few lines of code.

Request tracing with contexts

Here's a scenario you've probably encountered: a user reports an error, you check the logs, and you find a sea of interleaved messages from dozens of concurrent requests. Which log lines belong to the user's request? Good luck figuring that out.

This is where request tracing comes in. The idea is simple: assign a unique identifier to each request, and include that identifier in every log message produced while handling that request. Now you can filter your logs by request ID and see exactly what happened, in order, for that specific request.

LogTape supports this through contexts—a way to attach properties to log messages without passing them around explicitly.

Explicit context

The simplest approach is to create a logger with attached properties using .with():

function handleRequest(req: Request) {
  const requestId = crypto.randomUUID();
  const logger = getLogger(["my-app", "http"]).with({ requestId });

  logger.info`Request received`;  // Includes requestId automatically
  processRequest(req, logger);
  logger.info`Request completed`;  // Also includes requestId
}

This works well when you're passing the logger around explicitly. But what about code that's deeper in your call stack? What about code in libraries that don't know about your logger instance?

Implicit context

This is where implicit contexts shine. Using withContext(), you can set properties that automatically appear in all log messages within a callback—even in nested function calls, async operations, and third-party libraries (as long as they use LogTape).

First, enable implicit contexts in your configuration:

import { configure, getConsoleSink } from "@logtape/logtape";
import { AsyncLocalStorage } from "node:async_hooks";

await configure({
  sinks: { console: getConsoleSink() },
  loggers: [
    { category: ["my-app"], lowestLevel: "debug", sinks: ["console"] },
  ],
  contextLocalStorage: new AsyncLocalStorage(),
});

Then use withContext() in your request handler:

import { withContext, getLogger } from "@logtape/logtape";

function handleRequest(req: Request) {
  const requestId = crypto.randomUUID();

  return withContext({ requestId }, async () => {
    // Every log message in this callback includes requestId—automatically
    const logger = getLogger(["my-app"]);
    logger.info`Processing request`;

    await validateInput(req);   // Logs here include requestId
    await processBusinessLogic(req);  // Logs here too
    await saveToDatabase(req);  // And here

    logger.info`Request complete`;
  });
}

The magic is that validateInput, processBusinessLogic, and saveToDatabase don't need to know anything about the request ID. They just call getLogger() and log normally, and the request ID appears in their logs automatically. This works even across async boundaries—the context follows the execution flow, not the call stack.

This is incredibly powerful for debugging. When something goes wrong, you can search for the request ID and see every log message from every module that was involved in handling that request.

Framework integrations

Setting up request tracing manually can be tedious. LogTape has dedicated packages for popular frameworks that handle this automatically:

// Express
import { expressLogger } from "@logtape/express";
app.use(expressLogger());

// Fastify
import { getLogTapeFastifyLogger } from "@logtape/fastify";
const app = Fastify({ loggerInstance: getLogTapeFastifyLogger() });

// Hono
import { honoLogger } from "@logtape/hono";
app.use(honoLogger());

// Koa
import { koaLogger } from "@logtape/koa";
app.use(koaLogger());

These middlewares automatically generate request IDs, set up implicit contexts, and log request/response information. You get comprehensive request logging with a single line of code.

Using LogTape in libraries vs applications

If you've ever used a library that spams your console with unwanted log messages, you know how annoying it can be. And if you've ever tried to add logging to your own library, you've faced a dilemma: should you use console.log() and annoy your users? Require them to install and configure a specific logging library? Or just... not log anything?

LogTape solves this with its library-first design. Libraries can add as much logging as they want, and it costs their users nothing unless they explicitly opt in.

If you're writing a library

The rule is simple: use getLogger() to log, but never call configure(). Configuration is the application's responsibility, not the library's.

// my-library/src/database.ts
import { getLogger } from "@logtape/logtape";

const logger = getLogger(["my-library", "database"]);

export function connect(url: string) {
  logger.debug`Connecting to ${url}`;
  // ... connection logic ...
  logger.info`Connected successfully`;
}

What happens when someone uses your library?

If they haven't configured LogTape, nothing happens. The log calls are essentially no-ops—no output, no errors, no performance impact. Your library works exactly as if the logging code wasn't there.

If they have configured LogTape, they get full control. They can see your library's debug logs if they're troubleshooting an issue, or silence them entirely if they're not interested. They decide, not you.

This is fundamentally different from using console.log() in a library. With console.log(), your users have no choice—they see your logs whether they want to or not. With LogTape, you give them the power to decide.

If you're writing an application

You configure LogTape once in your entry point. This single configuration controls logging for your entire application, including any libraries that use LogTape:

await configure({
  sinks: { console: getConsoleSink() },
  loggers: [
    { category: ["my-app"], lowestLevel: "debug", sinks: ["console"] },  // Your app: verbose
    { category: ["my-library"], lowestLevel: "warning", sinks: ["console"] },  // Library: quiet
    { category: ["noisy-library"], lowestLevel: "fatal", sinks: [] },  // That one library: silent
  ],
});

This separation of concerns—libraries log, applications configure—makes for a much healthier ecosystem. Library authors can add detailed logging for debugging without worrying about annoying their users. Application developers can tune logging to their needs without digging through library code.

Migrating from another logger?

If your application already uses winston, Pino, or another logging library, you don't have to migrate everything at once. LogTape provides adapters that route LogTape logs to your existing logging setup:

import { install } from "@logtape/adaptor-winston";
import winston from "winston";

install(winston.createLogger({ /* your existing config */ }));

This is particularly useful when you want to use a library that uses LogTape, but you're not ready to switch your whole application over. The library's logs will flow through your existing winston (or Pino) configuration, and you can migrate gradually if you choose to.

Production considerations

Development and production have different needs. During development, you want verbose logs, pretty formatting, and immediate feedback. In production, you care about performance, reliability, and not leaking sensitive data. Here are some things to keep in mind.

Non-blocking mode

By default, logging is synchronous—when you call logger.info(), the message is written to the sink before the function returns. This is fine for development, but in a high-throughput production environment, the I/O overhead of writing every log message can add up.

Non-blocking mode buffers log messages and writes them in the background:

const consoleSink = getConsoleSink({ nonBlocking: true });
const fileSink = getFileSink("app.log", { nonBlocking: true });

The tradeoff is that logs might be slightly delayed, and if your process crashes, some buffered logs might be lost. But for most production workloads, the performance benefit is worth it.

Sensitive data redaction

Logs have a way of ending up in unexpected places—log aggregation services, debugging sessions, support tickets. If you're logging request data, user information, or API responses, you might accidentally expose sensitive information like passwords, API keys, or personal data.

LogTape's @logtape/redaction package helps you catch these before they become a problem:

import {
  redactByPattern,
  EMAIL_ADDRESS_PATTERN,
  CREDIT_CARD_NUMBER_PATTERN,
  type RedactionPattern,
} from "@logtape/redaction";
import { defaultConsoleFormatter, configure, getConsoleSink } from "@logtape/logtape";

const BEARER_TOKEN_PATTERN: RedactionPattern = {
  pattern: /Bearer [A-Za-z0-9\-._~+\/]+=*/g,
  replacement: "[REDACTED]",
};

const formatter = redactByPattern(defaultConsoleFormatter, [
  EMAIL_ADDRESS_PATTERN,
  CREDIT_CARD_NUMBER_PATTERN,
  BEARER_TOKEN_PATTERN,
]);

await configure({
  sinks: {
    console: getConsoleSink({ formatter }),
  },
  // ...
});

With this configuration, email addresses, credit card numbers, and bearer tokens are automatically replaced with [REDACTED] in your log output. The @logtape/redaction package comes with built-in patterns for common sensitive data types, and you can define custom patterns for anything else. It's not foolproof—you should still be mindful of what you log—but it provides a safety net.

See the redaction documentation for more patterns and field-based redaction.

Edge functions and serverless

Edge functions (Cloudflare Workers, Vercel Edge Functions, etc.) have a unique constraint: they can be terminated immediately after returning a response. If you have buffered logs that haven't been flushed yet, they'll be lost.

The solution is to explicitly flush logs before returning:

import { configure, dispose } from "@logtape/logtape";

export default {
  async fetch(request, env, ctx) {
    await configure({ /* ... */ });
    
    // ... handle request ...
    
    ctx.waitUntil(dispose());  // Flush logs before worker terminates
    
    return new Response("OK");
  },
};

The dispose() function flushes all buffered logs and cleans up resources. By passing it to ctx.waitUntil(), you ensure the worker stays alive long enough to finish writing logs, even after the response has been sent.

Wrapping up

Logging isn't glamorous, but it's one of those things that makes a huge difference when something goes wrong. The setup I've described here—categories for organization, structured data for queryability, contexts for request tracing—isn't complicated, but it's a significant step up from scattered console.log statements.

LogTape isn't the only way to achieve this, but I've found it hits a nice sweet spot: powerful enough for production use, simple enough that you're not fighting the framework, and light enough that you don't feel guilty adding it to a library.

If you want to dig deeper, the LogTape documentation covers advanced topics like custom filters, the “fingers crossed” pattern for buffering debug logs until an error occurs, and more sink options. The GitHub repository is also a good place to report issues or see what's coming next.

Now go add some proper logging to that side project you've been meaning to clean up. Your future 2 AM self will thank you.

github.com

GitHub - dahlia/logtape: Simple logging library with zero dependencies for Deno, Node.js, Bun, browsers, and edge functions

Simple logging library with zero dependencies for Deno, Node.js, Bun, browsers, and edge functions - dahlia/logtape

@hongminhee@hollo.social

Wrote about designing type-safe sync/async mode support in TypeScript. Making object({ sync: syncParser, async: asyncParser }) automatically infer as async turned out to be trickier than expected.

https://hackers.pub/@hongminhee/2026/typescript-sync-async-type-safety

hackers.pub

Designing type-safe sync/async mode support in TypeScript

I recently added sync/async mode support to Optique, a type-safe CLI parserfor TypeScript. It turned out to be one of the trickier features I'veimplemented—the object() combinator alone needed to compute a combined modefrom all its child parsers, and TypeScript's inference kept hitting edge cases. What is Optique? Optique is a type-safe, combinatorial CLI parser for TypeScript, inspired byHaskell's optparse-applicative. Instead of decorators or builder patterns,you compose small parsers into larger ones using combinators, and TypeScriptinfers the result types. Here's a quick taste: import { object } from "@optique/core/constructs";import { argument, option } from "@optique/core/primitives";import { string, integer } from "@optique/core/valueparser";import { run } from "@optique/run";const cli = object({ name: argument(string()), count: option("-n", "--count", integer()),});// TypeScript infers: { name: string; count: number | undefined }const result = run(cli); // sync by default The type inference works through arbitrarily deep compositions—in most cases,you don't need explicit type annotations. How it started Lucas Garron (@lgarron) opened an issue requestingasync support for shell completions. He wanted to provideTab-completion suggestions by running shell commands likegit for-each-ref to list branches and tags. // Lucas's example: fetching Git branches and tags in parallelconst [branches, tags] = await Promise.all([ $`git for-each-ref --format='%(refname:short)' refs/heads/`.text(), $`git for-each-ref --format='%(refname:short)' refs/tags/`.text(),]); At first, I didn't like the idea. Optique's entire API was synchronous, whichmade it simpler to reason about and avoided the “async infection” problem whereone async function forces everything upstream to become async. I argued thatshell completion should be near-instantaneous, and if you need async data, youshould cache it at startup. But Lucas pushed back. The filesystem is a database, and many usefulcompletions inherently require async work—Git refs change constantly, andpre-caching everything at startup doesn't scale for large repos. Fair point. What I needed to solve So, how do you support both sync and async execution modes in a composableparser library while maintaining type safety? The key requirements were: parse() returns T or Promise<T> complete() returns T or Promise<T> suggest() returns Iterable<T> or AsyncIterable<T> When combining parsers, if any parser is async, the combined resultmust be async Existing sync code should continue to work unchanged The fourth requirement is the tricky one. Consider this: const syncParser = flag("--verbose");const asyncParser = option("--branch", asyncValueParser);// What's the type of this?const combined = object({ verbose: syncParser, branch: asyncParser }); The combined parser should be async because one of its fields is async.This means we need type-level logic to compute the combined mode. Five design options I explored five different approaches, each with its own trade-offs. Option A: conditional types with mode parameter Add a mode type parameter to Parser and use conditional types: type Mode = "sync" | "async";type ModeValue<M extends Mode, T> = M extends "async" ? Promise<T> : T;interface Parser<M extends Mode, TValue, TState> { parse(context: ParserContext<TState>): ModeValue<M, ParserResult<TState>>; // ...} The challenge is computing combined modes: type CombineModes<T extends Record<string, Parser<any, any, any>>> = T[keyof T] extends Parser<infer M, any, any> ? M extends "async" ? "async" : "sync" : never; Option B: mode parameter with default value A variant of Option A, but place the mode parameter first with a defaultof "sync": interface Parser<M extends Mode = "sync", TValue, TState> { readonly $mode: M; // ...} The default value maintains backward compatibility—existing user code keepsworking without changes. Option C: separate interfaces Define completely separate Parser and AsyncParser interfaces withexplicit conversion: interface Parser<TValue, TState> { /* sync methods */ }interface AsyncParser<TValue, TState> { /* async methods */ }function toAsync<T, S>(parser: Parser<T, S>): AsyncParser<T, S>; Simpler to understand, but requires code duplication and explicit conversions. Option D: union return types for suggest() only The minimal approach. Only allow suggest() to be async: interface Parser<TValue, TState> { parse(context: ParserContext<TState>): ParserResult<TState>; // always sync suggest(context: ParserContext<TState>, prefix: string): Iterable<Suggestion> | AsyncIterable<Suggestion>; // can be either} This addresses the original use case but doesn't help if async parse() isever needed. Option E: fp-ts style HKT simulation Use the technique from fp-ts to simulate Higher-Kinded Types: interface URItoKind<A> { Identity: A; Promise: Promise<A>;}type Kind<F extends keyof URItoKind<any>, A> = URItoKind<A>[F];interface Parser<F extends keyof URItoKind<any>, TValue, TState> { parse(context: ParserContext<TState>): Kind<F, ParserResult<TState>>;} The most flexible approach, but with a steep learning curve. Testing the idea Rather than commit to an approach based on theoretical analysis, I createda prototype to test how well TypeScript handles the type inference in practice.I published my findings in the GitHub issue: Both approaches correctly handle the “any async → all async” rule at thetype level. (…) Complex conditional types likeModeValue<CombineParserModes<T>, ParserResult<TState>> sometimes requireexplicit type casting in the implementation. This only affects libraryinternals. The user-facing API remains clean. The prototype validated that Option B (explicit mode parameter with default)would work. I chose it for these reasons: Backward compatible: The default "sync" keeps existing code working Explicit: The mode is visible in both types and runtime (via a $modeproperty) Debuggable: Easy to inspect the current mode at runtime Better IDE support: Type information is more predictable How CombineModes works The CombineModes type computes whether a combined parser should be sync orasync: type CombineModes<T extends readonly Mode[]> = "async" extends T[number] ? "async" : "sync"; This type checks if "async" is present anywhere in the tuple of modes.If so, the result is "async"; otherwise, it's "sync". For combinators like object(), I needed to extract modes from parserobjects and combine them: // Extract the mode from a single parsertype ParserMode<T> = T extends Parser<infer M, unknown, unknown> ? M : never;// Combine modes from all values in a record of parserstype CombineObjectModes<T extends Record<string, Parser<Mode, unknown, unknown>>> = CombineModes<{ [K in keyof T]: ParserMode<T[K]> }[keyof T][]>; Runtime implementation The type system handles compile-time safety, but the implementation also needsruntime logic. Each parser has a $mode property that indicates its executionmode: const syncParser = option("-n", "--name", string());console.log(syncParser.$mode); // "sync"const asyncParser = option("-b", "--branch", asyncValueParser);console.log(asyncParser.$mode); // "async" Combinators compute their mode at construction time: function object<T extends Record<string, Parser<Mode, unknown, unknown>>>( parsers: T): Parser<CombineObjectModes<T>, ObjectValue<T>, ObjectState<T>> { const parserKeys = Reflect.ownKeys(parsers); const combinedMode: Mode = parserKeys.some( (k) => parsers[k as keyof T].$mode === "async" ) ? "async" : "sync"; // ... implementation} Refining the API Lucas suggested an important refinement during ourdiscussion. Instead of having run() automatically choose between sync andasync based on the parser mode, he proposed separate functions: Perhaps run(…) could be automatic, and runSync(…) and runAsync(…) couldenforce that the inferred type matches what is expected. So we ended up with: run(): automatic based on parser mode runSync(): enforces sync mode at compile time runAsync(): enforces async mode at compile time // Automatic: returns T for sync parsers, Promise<T> for asyncconst result1 = run(syncParser); // stringconst result2 = run(asyncParser); // Promise<string>// Explicit: compile-time enforcementconst result3 = runSync(syncParser); // stringconst result4 = runAsync(asyncParser); // Promise<string>// Compile error: can't use runSync with async parserconst result5 = runSync(asyncParser); // Type error! I applied the same pattern to parse()/parseSync()/parseAsync() andsuggest()/suggestSync()/suggestAsync() in the facade functions. Creating async value parsers With the new API, creating an async value parser for Git branches lookslike this: import type { Suggestion } from "@optique/core/parser";import type { ValueParser, ValueParserResult } from "@optique/core/valueparser";function gitRef(): ValueParser<"async", string> { return { $mode: "async", metavar: "REF", parse(input: string): Promise<ValueParserResult<string>> { return Promise.resolve({ success: true, value: input }); }, format(value: string): string { return value; }, async *suggest(prefix: string): AsyncIterable<Suggestion> { const { $ } = await import("bun"); const [branches, tags] = await Promise.all([ $`git for-each-ref --format='%(refname:short)' refs/heads/`.text(), $`git for-each-ref --format='%(refname:short)' refs/tags/`.text(), ]); for (const ref of [...branches.split("\n"), ...tags.split("\n")]) { const trimmed = ref.trim(); if (trimmed && trimmed.startsWith(prefix)) { yield { kind: "literal", text: trimmed }; } } }, };} Notice that parse() returns Promise.resolve() even though it's synchronous.This is because the ValueParser<"async", T> type requires all methods to useasync signatures. Lucas pointed out this is a minor ergonomic issue. If onlysuggest() needs to be async, you still have to wrap parse() in a Promise. I considered per-method mode granularity (e.g., ValueParser<ParseMode, SuggestMode, T>), but the implementation complexity would multiplysubstantially. For now, the workaround is simple enough: // Option 1: Use Promise.resolve()parse(input) { return Promise.resolve({ success: true, value: input });}// Option 2: Mark as async and suppress the linter// biome-ignore lint/suspicious/useAwait: sync implementation in async ValueParserasync parse(input) { return { success: true, value: input };} What it cost Supporting dual modes added significant complexity to Optique's internals.Every combinator needed updates: Type signatures grew more complex with mode parameters Mode propagation logic had to be added to every combinator Dual implementations were needed for sync and async code paths Type casts were sometimes necessary in the implementation to satisfyTypeScript For example, the object() combinator went from around 100 lines to around250 lines. The internal implementation uses conditional logic based on thecombined mode: if (combinedMode === "async") { return { $mode: "async" as M, // ... async implementation with Promise chains async parse(context) { // ... await each field's parse result }, };} else { return { $mode: "sync" as M, // ... sync implementation parse(context) { // ... directly call each field's parse }, };} This duplication is the cost of supporting both modes without runtime overheadfor sync-only use cases. Lessons learned Listen to users, but validate with prototypes My initial instinct was to resist async support. Lucas's persistence andconcrete examples changed my mind, but I validated the approach with aprototype before committing. The prototype revealed practical issues (likeTypeScript inference limits) that pure design analysis would have missed. Backward compatibility is worth the complexity Making "sync" the default mode meant existing code continued to workunchanged. This was a deliberate choice. Breaking changes should requireuser action, not break silently. Unified mode vs per-method granularity I chose unified mode (all methods share the same sync/async mode) overper-method granularity. This means users occasionally writePromise.resolve() for methods that don't actually need async, but thealternative was multiplicative complexity in the type system. Designing in public The entire design process happened in a public GitHub issue. Lucas, Giuseppe,and others contributed ideas that shaped the final API. TherunSync()/runAsync() distinction came directly from Lucas's feedback. Conclusion This was one of the more challenging features I've implemented in Optique.TypeScript's type system is powerful enough to encode the “any async means allasync” rule at compile time, but getting there required careful design work andprototyping. What made it work: conditional types like ModeValue<M, T> can bridge the gapbetween sync and async worlds. You pay for it with implementation complexity,but the user-facing API stays clean and type-safe. Optique 0.9.0 with async support is currently in pre-release testing. Ifyou'd like to try it, check out PR #70 or install the pre-release: npm add @optique/core@0.9.0-dev.212 @optique/run@0.9.0-dev.212deno add --jsr @optique/core@0.9.0-dev.212 @optique/run@0.9.0-dev.212 Feedback is welcome!

@hongminhee@hackers.pub

I recently added sync/async mode support to Optique, a type-safe CLI parser for TypeScript. It turned out to be one of the trickier features I've implemented—the object() combinator alone needed to compute a combined mode from all its child parsers, and TypeScript's inference kept hitting edge cases.

What is Optique?

Optique is a type-safe, combinatorial CLI parser for TypeScript, inspired by Haskell's optparse-applicative. Instead of decorators or builder patterns, you compose small parsers into larger ones using combinators, and TypeScript infers the result types.

Here's a quick taste:

import { object } from "@optique/core/constructs";
import { argument, option } from "@optique/core/primitives";
import { string, integer } from "@optique/core/valueparser";
import { run } from "@optique/run";

const cli = object({
  name: argument(string()),
  count: option("-n", "--count", integer()),
});

// TypeScript infers: { name: string; count: number | undefined }
const result = run(cli);  // sync by default

The type inference works through arbitrarily deep compositions—in most cases, you don't need explicit type annotations.

How it started

Lucas Garron (@lgarron) opened an issue requesting async support for shell completions. He wanted to provide Tab-completion suggestions by running shell commands like git for-each-ref to list branches and tags.

// Lucas's example: fetching Git branches and tags in parallel
const [branches, tags] = await Promise.all([
  $`git for-each-ref --format='%(refname:short)' refs/heads/`.text(),
  $`git for-each-ref --format='%(refname:short)' refs/tags/`.text(),
]);

At first, I didn't like the idea. Optique's entire API was synchronous, which made it simpler to reason about and avoided the “async infection” problem where one async function forces everything upstream to become async. I argued that shell completion should be near-instantaneous, and if you need async data, you should cache it at startup.

But Lucas pushed back. The filesystem is a database, and many useful completions inherently require async work—Git refs change constantly, and pre-caching everything at startup doesn't scale for large repos. Fair point.

What I needed to solve

So, how do you support both sync and async execution modes in a composable parser library while maintaining type safety?

The key requirements were:

  • parse() returns T or Promise<T>
  • complete() returns T or Promise<T>
  • suggest() returns Iterable<T> or AsyncIterable<T>
  • When combining parsers, if any parser is async, the combined result must be async
  • Existing sync code should continue to work unchanged

The fourth requirement is the tricky one. Consider this:

const syncParser = flag("--verbose");
const asyncParser = option("--branch", asyncValueParser);

// What's the type of this?
const combined = object({ verbose: syncParser, branch: asyncParser });

The combined parser should be async because one of its fields is async. This means we need type-level logic to compute the combined mode.

Five design options

I explored five different approaches, each with its own trade-offs.

Option A: conditional types with mode parameter

Add a mode type parameter to Parser and use conditional types:

type Mode = "sync" | "async";

type ModeValue<M extends Mode, T> = M extends "async" ? Promise<T> : T;

interface Parser<M extends Mode, TValue, TState> {
  parse(context: ParserContext<TState>): ModeValue<M, ParserResult<TState>>;
  // ...
}

The challenge is computing combined modes:

type CombineModes<T extends Record<string, Parser<any, any, any>>> =
  T[keyof T] extends Parser<infer M, any, any>
    ? M extends "async" ? "async" : "sync"
    : never;

Option B: mode parameter with default value

A variant of Option A, but place the mode parameter first with a default of "sync":

interface Parser<M extends Mode = "sync", TValue, TState> {
  readonly $mode: M;
  // ...
}

The default value maintains backward compatibility—existing user code keeps working without changes.

Option C: separate interfaces

Define completely separate Parser and AsyncParser interfaces with explicit conversion:

interface Parser<TValue, TState> { /* sync methods */ }
interface AsyncParser<TValue, TState> { /* async methods */ }

function toAsync<T, S>(parser: Parser<T, S>): AsyncParser<T, S>;

Simpler to understand, but requires code duplication and explicit conversions.

Option D: union return types for suggest() only

The minimal approach. Only allow suggest() to be async:

interface Parser<TValue, TState> {
  parse(context: ParserContext<TState>): ParserResult<TState>;  // always sync
  suggest(context: ParserContext<TState>, prefix: string):
    Iterable<Suggestion> | AsyncIterable<Suggestion>;  // can be either
}

This addresses the original use case but doesn't help if async parse() is ever needed.

Option E: fp-ts style HKT simulation

Use the technique from fp-ts to simulate Higher-Kinded Types:

interface URItoKind<A> {
  Identity: A;
  Promise: Promise<A>;
}

type Kind<F extends keyof URItoKind<any>, A> = URItoKind<A>[F];

interface Parser<F extends keyof URItoKind<any>, TValue, TState> {
  parse(context: ParserContext<TState>): Kind<F, ParserResult<TState>>;
}

The most flexible approach, but with a steep learning curve.

Testing the idea

Rather than commit to an approach based on theoretical analysis, I created a prototype to test how well TypeScript handles the type inference in practice. I published my findings in the GitHub issue:

Both approaches correctly handle the “any async → all async” rule at the type level. (…) Complex conditional types like ModeValue<CombineParserModes<T>, ParserResult<TState>> sometimes require explicit type casting in the implementation. This only affects library internals. The user-facing API remains clean.

The prototype validated that Option B (explicit mode parameter with default) would work. I chose it for these reasons:

  • Backward compatible: The default "sync" keeps existing code working
  • Explicit: The mode is visible in both types and runtime (via a $mode property)
  • Debuggable: Easy to inspect the current mode at runtime
  • Better IDE support: Type information is more predictable

How CombineModes works

The CombineModes type computes whether a combined parser should be sync or async:

type CombineModes<T extends readonly Mode[]> = "async" extends T[number]
  ? "async"
  : "sync";

This type checks if "async" is present anywhere in the tuple of modes. If so, the result is "async"; otherwise, it's "sync".

For combinators like object(), I needed to extract modes from parser objects and combine them:

// Extract the mode from a single parser
type ParserMode<T> = T extends Parser<infer M, unknown, unknown> ? M : never;

// Combine modes from all values in a record of parsers
type CombineObjectModes<T extends Record<string, Parser<Mode, unknown, unknown>>> =
  CombineModes<{ [K in keyof T]: ParserMode<T[K]> }[keyof T][]>;

Runtime implementation

The type system handles compile-time safety, but the implementation also needs runtime logic. Each parser has a $mode property that indicates its execution mode:

const syncParser = option("-n", "--name", string());
console.log(syncParser.$mode);  // "sync"

const asyncParser = option("-b", "--branch", asyncValueParser);
console.log(asyncParser.$mode);  // "async"

Combinators compute their mode at construction time:

function object<T extends Record<string, Parser<Mode, unknown, unknown>>>(
  parsers: T
): Parser<CombineObjectModes<T>, ObjectValue<T>, ObjectState<T>> {
  const parserKeys = Reflect.ownKeys(parsers);
  const combinedMode: Mode = parserKeys.some(
    (k) => parsers[k as keyof T].$mode === "async"
  ) ? "async" : "sync";

  // ... implementation
}

Refining the API

Lucas suggested an important refinement during our discussion. Instead of having run() automatically choose between sync and async based on the parser mode, he proposed separate functions:

Perhaps run(…) could be automatic, and runSync(…) and runAsync(…) could enforce that the inferred type matches what is expected.

So we ended up with:

  • run(): automatic based on parser mode
  • runSync(): enforces sync mode at compile time
  • runAsync(): enforces async mode at compile time
// Automatic: returns T for sync parsers, Promise<T> for async
const result1 = run(syncParser);  // string
const result2 = run(asyncParser);  // Promise<string>

// Explicit: compile-time enforcement
const result3 = runSync(syncParser);  // string
const result4 = runAsync(asyncParser);  // Promise<string>

// Compile error: can't use runSync with async parser
const result5 = runSync(asyncParser);  // Type error!

I applied the same pattern to parse()/parseSync()/parseAsync() and suggest()/suggestSync()/suggestAsync() in the facade functions.

Creating async value parsers

With the new API, creating an async value parser for Git branches looks like this:

import type { Suggestion } from "@optique/core/parser";
import type { ValueParser, ValueParserResult } from "@optique/core/valueparser";

function gitRef(): ValueParser<"async", string> {
  return {
    $mode: "async",
    metavar: "REF",
    parse(input: string): Promise<ValueParserResult<string>> {
      return Promise.resolve({ success: true, value: input });
    },
    format(value: string): string {
      return value;
    },
    async *suggest(prefix: string): AsyncIterable<Suggestion> {
      const { $ } = await import("bun");
      const [branches, tags] = await Promise.all([
        $`git for-each-ref --format='%(refname:short)' refs/heads/`.text(),
        $`git for-each-ref --format='%(refname:short)' refs/tags/`.text(),
      ]);
      for (const ref of [...branches.split("\n"), ...tags.split("\n")]) {
        const trimmed = ref.trim();
        if (trimmed && trimmed.startsWith(prefix)) {
          yield { kind: "literal", text: trimmed };
        }
      }
    },
  };
}

Notice that parse() returns Promise.resolve() even though it's synchronous. This is because the ValueParser<"async", T> type requires all methods to use async signatures. Lucas pointed out this is a minor ergonomic issue. If only suggest() needs to be async, you still have to wrap parse() in a Promise.

I considered per-method mode granularity (e.g., ValueParser<ParseMode, SuggestMode, T>), but the implementation complexity would multiply substantially. For now, the workaround is simple enough:

// Option 1: Use Promise.resolve()
parse(input) {
  return Promise.resolve({ success: true, value: input });
}

// Option 2: Mark as async and suppress the linter
// biome-ignore lint/suspicious/useAwait: sync implementation in async ValueParser
async parse(input) {
  return { success: true, value: input };
}

What it cost

Supporting dual modes added significant complexity to Optique's internals. Every combinator needed updates:

  • Type signatures grew more complex with mode parameters
  • Mode propagation logic had to be added to every combinator
  • Dual implementations were needed for sync and async code paths
  • Type casts were sometimes necessary in the implementation to satisfy TypeScript

For example, the object() combinator went from around 100 lines to around 250 lines. The internal implementation uses conditional logic based on the combined mode:

if (combinedMode === "async") {
  return {
    $mode: "async" as M,
    // ... async implementation with Promise chains
    async parse(context) {
      // ... await each field's parse result
    },
  };
} else {
  return {
    $mode: "sync" as M,
    // ... sync implementation
    parse(context) {
      // ... directly call each field's parse
    },
  };
}

This duplication is the cost of supporting both modes without runtime overhead for sync-only use cases.

Lessons learned

Listen to users, but validate with prototypes

My initial instinct was to resist async support. Lucas's persistence and concrete examples changed my mind, but I validated the approach with a prototype before committing. The prototype revealed practical issues (like TypeScript inference limits) that pure design analysis would have missed.

Backward compatibility is worth the complexity

Making "sync" the default mode meant existing code continued to work unchanged. This was a deliberate choice. Breaking changes should require user action, not break silently.

Unified mode vs per-method granularity

I chose unified mode (all methods share the same sync/async mode) over per-method granularity. This means users occasionally write Promise.resolve() for methods that don't actually need async, but the alternative was multiplicative complexity in the type system.

Designing in public

The entire design process happened in a public GitHub issue. Lucas, Giuseppe, and others contributed ideas that shaped the final API. The runSync()/runAsync() distinction came directly from Lucas's feedback.

Conclusion

This was one of the more challenging features I've implemented in Optique. TypeScript's type system is powerful enough to encode the “any async means all async” rule at compile time, but getting there required careful design work and prototyping.

What made it work: conditional types like ModeValue<M, T> can bridge the gap between sync and async worlds. You pay for it with implementation complexity, but the user-facing API stays clean and type-safe.

Optique 0.9.0 with async support is currently in pre-release testing. If you'd like to try it, check out PR #70 or install the pre-release:

npm  add       @optique/core@0.9.0-dev.212 @optique/run@0.9.0-dev.212
deno add --jsr @optique/core@0.9.0-dev.212 @optique/run@0.9.0-dev.212

Feedback is welcome!

github.com

Add sync/async mode support to `Parser` and `ValueParser` by dahlia · Pull Request #70 · dahlia/optique

Summary Implements sync/async mode support for Parser and ValueParser as discussed in #52. This allows async operations in value parsers, such as: Validating values against remote APIs Fetching co...

@lobsters@mastodon.social

hackers.pub

Designing type-safe sync/async mode support in TypeScript

I recently added sync/async mode support to Optique, a type-safe CLI parserfor TypeScript. It turned out to be one of the trickier features I'veimplemented—the object() combinator alone needed to compute a combined modefrom all its child parsers, and TypeScript's inference kept hitting edge cases. What is Optique? Optique is a type-safe, combinatorial CLI parser for TypeScript, inspired byHaskell's optparse-applicative. Instead of decorators or builder patterns,you compose small parsers into larger ones using combinators, and TypeScriptinfers the result types. Here's a quick taste: import { object } from "@optique/core/constructs";import { argument, option } from "@optique/core/primitives";import { string, integer } from "@optique/core/valueparser";import { run } from "@optique/run";const cli = object({ name: argument(string()), count: option("-n", "--count", integer()),});// TypeScript infers: { name: string; count: number | undefined }const result = run(cli); // sync by default The type inference works through arbitrarily deep compositions—in most cases,you don't need explicit type annotations. How it started Lucas Garron (@lgarron) opened an issue requestingasync support for shell completions. He wanted to provideTab-completion suggestions by running shell commands likegit for-each-ref to list branches and tags. // Lucas's example: fetching Git branches and tags in parallelconst [branches, tags] = await Promise.all([ $`git for-each-ref --format='%(refname:short)' refs/heads/`.text(), $`git for-each-ref --format='%(refname:short)' refs/tags/`.text(),]); At first, I didn't like the idea. Optique's entire API was synchronous, whichmade it simpler to reason about and avoided the “async infection” problem whereone async function forces everything upstream to become async. I argued thatshell completion should be near-instantaneous, and if you need async data, youshould cache it at startup. But Lucas pushed back. The filesystem is a database, and many usefulcompletions inherently require async work—Git refs change constantly, andpre-caching everything at startup doesn't scale for large repos. Fair point. What I needed to solve So, how do you support both sync and async execution modes in a composableparser library while maintaining type safety? The key requirements were: parse() returns T or Promise<T> complete() returns T or Promise<T> suggest() returns Iterable<T> or AsyncIterable<T> When combining parsers, if any parser is async, the combined resultmust be async Existing sync code should continue to work unchanged The fourth requirement is the tricky one. Consider this: const syncParser = flag("--verbose");const asyncParser = option("--branch", asyncValueParser);// What's the type of this?const combined = object({ verbose: syncParser, branch: asyncParser }); The combined parser should be async because one of its fields is async.This means we need type-level logic to compute the combined mode. Five design options I explored five different approaches, each with its own trade-offs. Option A: conditional types with mode parameter Add a mode type parameter to Parser and use conditional types: type Mode = "sync" | "async";type ModeValue<M extends Mode, T> = M extends "async" ? Promise<T> : T;interface Parser<M extends Mode, TValue, TState> { parse(context: ParserContext<TState>): ModeValue<M, ParserResult<TState>>; // ...} The challenge is computing combined modes: type CombineModes<T extends Record<string, Parser<any, any, any>>> = T[keyof T] extends Parser<infer M, any, any> ? M extends "async" ? "async" : "sync" : never; Option B: mode parameter with default value A variant of Option A, but place the mode parameter first with a defaultof "sync": interface Parser<M extends Mode = "sync", TValue, TState> { readonly $mode: M; // ...} The default value maintains backward compatibility—existing user code keepsworking without changes. Option C: separate interfaces Define completely separate Parser and AsyncParser interfaces withexplicit conversion: interface Parser<TValue, TState> { /* sync methods */ }interface AsyncParser<TValue, TState> { /* async methods */ }function toAsync<T, S>(parser: Parser<T, S>): AsyncParser<T, S>; Simpler to understand, but requires code duplication and explicit conversions. Option D: union return types for suggest() only The minimal approach. Only allow suggest() to be async: interface Parser<TValue, TState> { parse(context: ParserContext<TState>): ParserResult<TState>; // always sync suggest(context: ParserContext<TState>, prefix: string): Iterable<Suggestion> | AsyncIterable<Suggestion>; // can be either} This addresses the original use case but doesn't help if async parse() isever needed. Option E: fp-ts style HKT simulation Use the technique from fp-ts to simulate Higher-Kinded Types: interface URItoKind<A> { Identity: A; Promise: Promise<A>;}type Kind<F extends keyof URItoKind<any>, A> = URItoKind<A>[F];interface Parser<F extends keyof URItoKind<any>, TValue, TState> { parse(context: ParserContext<TState>): Kind<F, ParserResult<TState>>;} The most flexible approach, but with a steep learning curve. Testing the idea Rather than commit to an approach based on theoretical analysis, I createda prototype to test how well TypeScript handles the type inference in practice.I published my findings in the GitHub issue: Both approaches correctly handle the “any async → all async” rule at thetype level. (…) Complex conditional types likeModeValue<CombineParserModes<T>, ParserResult<TState>> sometimes requireexplicit type casting in the implementation. This only affects libraryinternals. The user-facing API remains clean. The prototype validated that Option B (explicit mode parameter with default)would work. I chose it for these reasons: Backward compatible: The default "sync" keeps existing code working Explicit: The mode is visible in both types and runtime (via a $modeproperty) Debuggable: Easy to inspect the current mode at runtime Better IDE support: Type information is more predictable How CombineModes works The CombineModes type computes whether a combined parser should be sync orasync: type CombineModes<T extends readonly Mode[]> = "async" extends T[number] ? "async" : "sync"; This type checks if "async" is present anywhere in the tuple of modes.If so, the result is "async"; otherwise, it's "sync". For combinators like object(), I needed to extract modes from parserobjects and combine them: // Extract the mode from a single parsertype ParserMode<T> = T extends Parser<infer M, unknown, unknown> ? M : never;// Combine modes from all values in a record of parserstype CombineObjectModes<T extends Record<string, Parser<Mode, unknown, unknown>>> = CombineModes<{ [K in keyof T]: ParserMode<T[K]> }[keyof T][]>; Runtime implementation The type system handles compile-time safety, but the implementation also needsruntime logic. Each parser has a $mode property that indicates its executionmode: const syncParser = option("-n", "--name", string());console.log(syncParser.$mode); // "sync"const asyncParser = option("-b", "--branch", asyncValueParser);console.log(asyncParser.$mode); // "async" Combinators compute their mode at construction time: function object<T extends Record<string, Parser<Mode, unknown, unknown>>>( parsers: T): Parser<CombineObjectModes<T>, ObjectValue<T>, ObjectState<T>> { const parserKeys = Reflect.ownKeys(parsers); const combinedMode: Mode = parserKeys.some( (k) => parsers[k as keyof T].$mode === "async" ) ? "async" : "sync"; // ... implementation} Refining the API Lucas suggested an important refinement during ourdiscussion. Instead of having run() automatically choose between sync andasync based on the parser mode, he proposed separate functions: Perhaps run(…) could be automatic, and runSync(…) and runAsync(…) couldenforce that the inferred type matches what is expected. So we ended up with: run(): automatic based on parser mode runSync(): enforces sync mode at compile time runAsync(): enforces async mode at compile time // Automatic: returns T for sync parsers, Promise<T> for asyncconst result1 = run(syncParser); // stringconst result2 = run(asyncParser); // Promise<string>// Explicit: compile-time enforcementconst result3 = runSync(syncParser); // stringconst result4 = runAsync(asyncParser); // Promise<string>// Compile error: can't use runSync with async parserconst result5 = runSync(asyncParser); // Type error! I applied the same pattern to parse()/parseSync()/parseAsync() andsuggest()/suggestSync()/suggestAsync() in the facade functions. Creating async value parsers With the new API, creating an async value parser for Git branches lookslike this: import type { Suggestion } from "@optique/core/parser";import type { ValueParser, ValueParserResult } from "@optique/core/valueparser";function gitRef(): ValueParser<"async", string> { return { $mode: "async", metavar: "REF", parse(input: string): Promise<ValueParserResult<string>> { return Promise.resolve({ success: true, value: input }); }, format(value: string): string { return value; }, async *suggest(prefix: string): AsyncIterable<Suggestion> { const { $ } = await import("bun"); const [branches, tags] = await Promise.all([ $`git for-each-ref --format='%(refname:short)' refs/heads/`.text(), $`git for-each-ref --format='%(refname:short)' refs/tags/`.text(), ]); for (const ref of [...branches.split("\n"), ...tags.split("\n")]) { const trimmed = ref.trim(); if (trimmed && trimmed.startsWith(prefix)) { yield { kind: "literal", text: trimmed }; } } }, };} Notice that parse() returns Promise.resolve() even though it's synchronous.This is because the ValueParser<"async", T> type requires all methods to useasync signatures. Lucas pointed out this is a minor ergonomic issue. If onlysuggest() needs to be async, you still have to wrap parse() in a Promise. I considered per-method mode granularity (e.g., ValueParser<ParseMode, SuggestMode, T>), but the implementation complexity would multiplysubstantially. For now, the workaround is simple enough: // Option 1: Use Promise.resolve()parse(input) { return Promise.resolve({ success: true, value: input });}// Option 2: Mark as async and suppress the linter// biome-ignore lint/suspicious/useAwait: sync implementation in async ValueParserasync parse(input) { return { success: true, value: input };} What it cost Supporting dual modes added significant complexity to Optique's internals.Every combinator needed updates: Type signatures grew more complex with mode parameters Mode propagation logic had to be added to every combinator Dual implementations were needed for sync and async code paths Type casts were sometimes necessary in the implementation to satisfyTypeScript For example, the object() combinator went from around 100 lines to around250 lines. The internal implementation uses conditional logic based on thecombined mode: if (combinedMode === "async") { return { $mode: "async" as M, // ... async implementation with Promise chains async parse(context) { // ... await each field's parse result }, };} else { return { $mode: "sync" as M, // ... sync implementation parse(context) { // ... directly call each field's parse }, };} This duplication is the cost of supporting both modes without runtime overheadfor sync-only use cases. Lessons learned Listen to users, but validate with prototypes My initial instinct was to resist async support. Lucas's persistence andconcrete examples changed my mind, but I validated the approach with aprototype before committing. The prototype revealed practical issues (likeTypeScript inference limits) that pure design analysis would have missed. Backward compatibility is worth the complexity Making "sync" the default mode meant existing code continued to workunchanged. This was a deliberate choice. Breaking changes should requireuser action, not break silently. Unified mode vs per-method granularity I chose unified mode (all methods share the same sync/async mode) overper-method granularity. This means users occasionally writePromise.resolve() for methods that don't actually need async, but thealternative was multiplicative complexity in the type system. Designing in public The entire design process happened in a public GitHub issue. Lucas, Giuseppe,and others contributed ideas that shaped the final API. TherunSync()/runAsync() distinction came directly from Lucas's feedback. Conclusion This was one of the more challenging features I've implemented in Optique.TypeScript's type system is powerful enough to encode the “any async means allasync” rule at compile time, but getting there required careful design work andprototyping. What made it work: conditional types like ModeValue<M, T> can bridge the gapbetween sync and async worlds. You pay for it with implementation complexity,but the user-facing API stays clean and type-safe. Optique 0.9.0 with async support is currently in pre-release testing. Ifyou'd like to try it, check out PR #70 or install the pre-release: npm add @optique/core@0.9.0-dev.212 @optique/run@0.9.0-dev.212deno add --jsr @optique/core@0.9.0-dev.212 @optique/run@0.9.0-dev.212 Feedback is welcome!

@chomu.dev@bsky.brid.gy

지인분이 그 밥 산 거 왔다면서 그 사진이랑 다 지우시고 올리셨길래 클로드한테 이걸 기반으로 SCP 문서 써달라고 하니까 맛있게 말아와줌

@hongminhee@hollo.social

Wrote about designing type-safe sync/async mode support in TypeScript. Making object({ sync: syncParser, async: asyncParser }) automatically infer as async turned out to be trickier than expected.

https://hackers.pub/@hongminhee/2026/typescript-sync-async-type-safety

hackers.pub

Designing type-safe sync/async mode support in TypeScript

I recently added sync/async mode support to Optique, a type-safe CLI parserfor TypeScript. It turned out to be one of the trickier features I'veimplemented—the object() combinator alone needed to compute a combined modefrom all its child parsers, and TypeScript's inference kept hitting edge cases. What is Optique? Optique is a type-safe, combinatorial CLI parser for TypeScript, inspired byHaskell's optparse-applicative. Instead of decorators or builder patterns,you compose small parsers into larger ones using combinators, and TypeScriptinfers the result types. Here's a quick taste: import { object } from "@optique/core/constructs";import { argument, option } from "@optique/core/primitives";import { string, integer } from "@optique/core/valueparser";import { run } from "@optique/run";const cli = object({ name: argument(string()), count: option("-n", "--count", integer()),});// TypeScript infers: { name: string; count: number | undefined }const result = run(cli); // sync by default The type inference works through arbitrarily deep compositions—in most cases,you don't need explicit type annotations. How it started Lucas Garron (@lgarron) opened an issue requestingasync support for shell completions. He wanted to provideTab-completion suggestions by running shell commands likegit for-each-ref to list branches and tags. // Lucas's example: fetching Git branches and tags in parallelconst [branches, tags] = await Promise.all([ $`git for-each-ref --format='%(refname:short)' refs/heads/`.text(), $`git for-each-ref --format='%(refname:short)' refs/tags/`.text(),]); At first, I didn't like the idea. Optique's entire API was synchronous, whichmade it simpler to reason about and avoided the “async infection” problem whereone async function forces everything upstream to become async. I argued thatshell completion should be near-instantaneous, and if you need async data, youshould cache it at startup. But Lucas pushed back. The filesystem is a database, and many usefulcompletions inherently require async work—Git refs change constantly, andpre-caching everything at startup doesn't scale for large repos. Fair point. What I needed to solve So, how do you support both sync and async execution modes in a composableparser library while maintaining type safety? The key requirements were: parse() returns T or Promise<T> complete() returns T or Promise<T> suggest() returns Iterable<T> or AsyncIterable<T> When combining parsers, if any parser is async, the combined resultmust be async Existing sync code should continue to work unchanged The fourth requirement is the tricky one. Consider this: const syncParser = flag("--verbose");const asyncParser = option("--branch", asyncValueParser);// What's the type of this?const combined = object({ verbose: syncParser, branch: asyncParser }); The combined parser should be async because one of its fields is async.This means we need type-level logic to compute the combined mode. Five design options I explored five different approaches, each with its own trade-offs. Option A: conditional types with mode parameter Add a mode type parameter to Parser and use conditional types: type Mode = "sync" | "async";type ModeValue<M extends Mode, T> = M extends "async" ? Promise<T> : T;interface Parser<M extends Mode, TValue, TState> { parse(context: ParserContext<TState>): ModeValue<M, ParserResult<TState>>; // ...} The challenge is computing combined modes: type CombineModes<T extends Record<string, Parser<any, any, any>>> = T[keyof T] extends Parser<infer M, any, any> ? M extends "async" ? "async" : "sync" : never; Option B: mode parameter with default value A variant of Option A, but place the mode parameter first with a defaultof "sync": interface Parser<M extends Mode = "sync", TValue, TState> { readonly $mode: M; // ...} The default value maintains backward compatibility—existing user code keepsworking without changes. Option C: separate interfaces Define completely separate Parser and AsyncParser interfaces withexplicit conversion: interface Parser<TValue, TState> { /* sync methods */ }interface AsyncParser<TValue, TState> { /* async methods */ }function toAsync<T, S>(parser: Parser<T, S>): AsyncParser<T, S>; Simpler to understand, but requires code duplication and explicit conversions. Option D: union return types for suggest() only The minimal approach. Only allow suggest() to be async: interface Parser<TValue, TState> { parse(context: ParserContext<TState>): ParserResult<TState>; // always sync suggest(context: ParserContext<TState>, prefix: string): Iterable<Suggestion> | AsyncIterable<Suggestion>; // can be either} This addresses the original use case but doesn't help if async parse() isever needed. Option E: fp-ts style HKT simulation Use the technique from fp-ts to simulate Higher-Kinded Types: interface URItoKind<A> { Identity: A; Promise: Promise<A>;}type Kind<F extends keyof URItoKind<any>, A> = URItoKind<A>[F];interface Parser<F extends keyof URItoKind<any>, TValue, TState> { parse(context: ParserContext<TState>): Kind<F, ParserResult<TState>>;} The most flexible approach, but with a steep learning curve. Testing the idea Rather than commit to an approach based on theoretical analysis, I createda prototype to test how well TypeScript handles the type inference in practice.I published my findings in the GitHub issue: Both approaches correctly handle the “any async → all async” rule at thetype level. (…) Complex conditional types likeModeValue<CombineParserModes<T>, ParserResult<TState>> sometimes requireexplicit type casting in the implementation. This only affects libraryinternals. The user-facing API remains clean. The prototype validated that Option B (explicit mode parameter with default)would work. I chose it for these reasons: Backward compatible: The default "sync" keeps existing code working Explicit: The mode is visible in both types and runtime (via a $modeproperty) Debuggable: Easy to inspect the current mode at runtime Better IDE support: Type information is more predictable How CombineModes works The CombineModes type computes whether a combined parser should be sync orasync: type CombineModes<T extends readonly Mode[]> = "async" extends T[number] ? "async" : "sync"; This type checks if "async" is present anywhere in the tuple of modes.If so, the result is "async"; otherwise, it's "sync". For combinators like object(), I needed to extract modes from parserobjects and combine them: // Extract the mode from a single parsertype ParserMode<T> = T extends Parser<infer M, unknown, unknown> ? M : never;// Combine modes from all values in a record of parserstype CombineObjectModes<T extends Record<string, Parser<Mode, unknown, unknown>>> = CombineModes<{ [K in keyof T]: ParserMode<T[K]> }[keyof T][]>; Runtime implementation The type system handles compile-time safety, but the implementation also needsruntime logic. Each parser has a $mode property that indicates its executionmode: const syncParser = option("-n", "--name", string());console.log(syncParser.$mode); // "sync"const asyncParser = option("-b", "--branch", asyncValueParser);console.log(asyncParser.$mode); // "async" Combinators compute their mode at construction time: function object<T extends Record<string, Parser<Mode, unknown, unknown>>>( parsers: T): Parser<CombineObjectModes<T>, ObjectValue<T>, ObjectState<T>> { const parserKeys = Reflect.ownKeys(parsers); const combinedMode: Mode = parserKeys.some( (k) => parsers[k as keyof T].$mode === "async" ) ? "async" : "sync"; // ... implementation} Refining the API Lucas suggested an important refinement during ourdiscussion. Instead of having run() automatically choose between sync andasync based on the parser mode, he proposed separate functions: Perhaps run(…) could be automatic, and runSync(…) and runAsync(…) couldenforce that the inferred type matches what is expected. So we ended up with: run(): automatic based on parser mode runSync(): enforces sync mode at compile time runAsync(): enforces async mode at compile time // Automatic: returns T for sync parsers, Promise<T> for asyncconst result1 = run(syncParser); // stringconst result2 = run(asyncParser); // Promise<string>// Explicit: compile-time enforcementconst result3 = runSync(syncParser); // stringconst result4 = runAsync(asyncParser); // Promise<string>// Compile error: can't use runSync with async parserconst result5 = runSync(asyncParser); // Type error! I applied the same pattern to parse()/parseSync()/parseAsync() andsuggest()/suggestSync()/suggestAsync() in the facade functions. Creating async value parsers With the new API, creating an async value parser for Git branches lookslike this: import type { Suggestion } from "@optique/core/parser";import type { ValueParser, ValueParserResult } from "@optique/core/valueparser";function gitRef(): ValueParser<"async", string> { return { $mode: "async", metavar: "REF", parse(input: string): Promise<ValueParserResult<string>> { return Promise.resolve({ success: true, value: input }); }, format(value: string): string { return value; }, async *suggest(prefix: string): AsyncIterable<Suggestion> { const { $ } = await import("bun"); const [branches, tags] = await Promise.all([ $`git for-each-ref --format='%(refname:short)' refs/heads/`.text(), $`git for-each-ref --format='%(refname:short)' refs/tags/`.text(), ]); for (const ref of [...branches.split("\n"), ...tags.split("\n")]) { const trimmed = ref.trim(); if (trimmed && trimmed.startsWith(prefix)) { yield { kind: "literal", text: trimmed }; } } }, };} Notice that parse() returns Promise.resolve() even though it's synchronous.This is because the ValueParser<"async", T> type requires all methods to useasync signatures. Lucas pointed out this is a minor ergonomic issue. If onlysuggest() needs to be async, you still have to wrap parse() in a Promise. I considered per-method mode granularity (e.g., ValueParser<ParseMode, SuggestMode, T>), but the implementation complexity would multiplysubstantially. For now, the workaround is simple enough: // Option 1: Use Promise.resolve()parse(input) { return Promise.resolve({ success: true, value: input });}// Option 2: Mark as async and suppress the linter// biome-ignore lint/suspicious/useAwait: sync implementation in async ValueParserasync parse(input) { return { success: true, value: input };} What it cost Supporting dual modes added significant complexity to Optique's internals.Every combinator needed updates: Type signatures grew more complex with mode parameters Mode propagation logic had to be added to every combinator Dual implementations were needed for sync and async code paths Type casts were sometimes necessary in the implementation to satisfyTypeScript For example, the object() combinator went from around 100 lines to around250 lines. The internal implementation uses conditional logic based on thecombined mode: if (combinedMode === "async") { return { $mode: "async" as M, // ... async implementation with Promise chains async parse(context) { // ... await each field's parse result }, };} else { return { $mode: "sync" as M, // ... sync implementation parse(context) { // ... directly call each field's parse }, };} This duplication is the cost of supporting both modes without runtime overheadfor sync-only use cases. Lessons learned Listen to users, but validate with prototypes My initial instinct was to resist async support. Lucas's persistence andconcrete examples changed my mind, but I validated the approach with aprototype before committing. The prototype revealed practical issues (likeTypeScript inference limits) that pure design analysis would have missed. Backward compatibility is worth the complexity Making "sync" the default mode meant existing code continued to workunchanged. This was a deliberate choice. Breaking changes should requireuser action, not break silently. Unified mode vs per-method granularity I chose unified mode (all methods share the same sync/async mode) overper-method granularity. This means users occasionally writePromise.resolve() for methods that don't actually need async, but thealternative was multiplicative complexity in the type system. Designing in public The entire design process happened in a public GitHub issue. Lucas, Giuseppe,and others contributed ideas that shaped the final API. TherunSync()/runAsync() distinction came directly from Lucas's feedback. Conclusion This was one of the more challenging features I've implemented in Optique.TypeScript's type system is powerful enough to encode the “any async means allasync” rule at compile time, but getting there required careful design work andprototyping. What made it work: conditional types like ModeValue<M, T> can bridge the gapbetween sync and async worlds. You pay for it with implementation complexity,but the user-facing API stays clean and type-safe. Optique 0.9.0 with async support is currently in pre-release testing. Ifyou'd like to try it, check out PR #70 or install the pre-release: npm add @optique/core@0.9.0-dev.212 @optique/run@0.9.0-dev.212deno add --jsr @optique/core@0.9.0-dev.212 @optique/run@0.9.0-dev.212 Feedback is welcome!

@hongminhee@hackers.pub

I recently added sync/async mode support to Optique, a type-safe CLI parser for TypeScript. It turned out to be one of the trickier features I've implemented—the object() combinator alone needed to compute a combined mode from all its child parsers, and TypeScript's inference kept hitting edge cases.

What is Optique?

Optique is a type-safe, combinatorial CLI parser for TypeScript, inspired by Haskell's optparse-applicative. Instead of decorators or builder patterns, you compose small parsers into larger ones using combinators, and TypeScript infers the result types.

Here's a quick taste:

import { object } from "@optique/core/constructs";
import { argument, option } from "@optique/core/primitives";
import { string, integer } from "@optique/core/valueparser";
import { run } from "@optique/run";

const cli = object({
  name: argument(string()),
  count: option("-n", "--count", integer()),
});

// TypeScript infers: { name: string; count: number | undefined }
const result = run(cli);  // sync by default

The type inference works through arbitrarily deep compositions—in most cases, you don't need explicit type annotations.

How it started

Lucas Garron (@lgarron) opened an issue requesting async support for shell completions. He wanted to provide Tab-completion suggestions by running shell commands like git for-each-ref to list branches and tags.

// Lucas's example: fetching Git branches and tags in parallel
const [branches, tags] = await Promise.all([
  $`git for-each-ref --format='%(refname:short)' refs/heads/`.text(),
  $`git for-each-ref --format='%(refname:short)' refs/tags/`.text(),
]);

At first, I didn't like the idea. Optique's entire API was synchronous, which made it simpler to reason about and avoided the “async infection” problem where one async function forces everything upstream to become async. I argued that shell completion should be near-instantaneous, and if you need async data, you should cache it at startup.

But Lucas pushed back. The filesystem is a database, and many useful completions inherently require async work—Git refs change constantly, and pre-caching everything at startup doesn't scale for large repos. Fair point.

What I needed to solve

So, how do you support both sync and async execution modes in a composable parser library while maintaining type safety?

The key requirements were:

  • parse() returns T or Promise<T>
  • complete() returns T or Promise<T>
  • suggest() returns Iterable<T> or AsyncIterable<T>
  • When combining parsers, if any parser is async, the combined result must be async
  • Existing sync code should continue to work unchanged

The fourth requirement is the tricky one. Consider this:

const syncParser = flag("--verbose");
const asyncParser = option("--branch", asyncValueParser);

// What's the type of this?
const combined = object({ verbose: syncParser, branch: asyncParser });

The combined parser should be async because one of its fields is async. This means we need type-level logic to compute the combined mode.

Five design options

I explored five different approaches, each with its own trade-offs.

Option A: conditional types with mode parameter

Add a mode type parameter to Parser and use conditional types:

type Mode = "sync" | "async";

type ModeValue<M extends Mode, T> = M extends "async" ? Promise<T> : T;

interface Parser<M extends Mode, TValue, TState> {
  parse(context: ParserContext<TState>): ModeValue<M, ParserResult<TState>>;
  // ...
}

The challenge is computing combined modes:

type CombineModes<T extends Record<string, Parser<any, any, any>>> =
  T[keyof T] extends Parser<infer M, any, any>
    ? M extends "async" ? "async" : "sync"
    : never;

Option B: mode parameter with default value

A variant of Option A, but place the mode parameter first with a default of "sync":

interface Parser<M extends Mode = "sync", TValue, TState> {
  readonly $mode: M;
  // ...
}

The default value maintains backward compatibility—existing user code keeps working without changes.

Option C: separate interfaces

Define completely separate Parser and AsyncParser interfaces with explicit conversion:

interface Parser<TValue, TState> { /* sync methods */ }
interface AsyncParser<TValue, TState> { /* async methods */ }

function toAsync<T, S>(parser: Parser<T, S>): AsyncParser<T, S>;

Simpler to understand, but requires code duplication and explicit conversions.

Option D: union return types for suggest() only

The minimal approach. Only allow suggest() to be async:

interface Parser<TValue, TState> {
  parse(context: ParserContext<TState>): ParserResult<TState>;  // always sync
  suggest(context: ParserContext<TState>, prefix: string):
    Iterable<Suggestion> | AsyncIterable<Suggestion>;  // can be either
}

This addresses the original use case but doesn't help if async parse() is ever needed.

Option E: fp-ts style HKT simulation

Use the technique from fp-ts to simulate Higher-Kinded Types:

interface URItoKind<A> {
  Identity: A;
  Promise: Promise<A>;
}

type Kind<F extends keyof URItoKind<any>, A> = URItoKind<A>[F];

interface Parser<F extends keyof URItoKind<any>, TValue, TState> {
  parse(context: ParserContext<TState>): Kind<F, ParserResult<TState>>;
}

The most flexible approach, but with a steep learning curve.

Testing the idea

Rather than commit to an approach based on theoretical analysis, I created a prototype to test how well TypeScript handles the type inference in practice. I published my findings in the GitHub issue:

Both approaches correctly handle the “any async → all async” rule at the type level. (…) Complex conditional types like ModeValue<CombineParserModes<T>, ParserResult<TState>> sometimes require explicit type casting in the implementation. This only affects library internals. The user-facing API remains clean.

The prototype validated that Option B (explicit mode parameter with default) would work. I chose it for these reasons:

  • Backward compatible: The default "sync" keeps existing code working
  • Explicit: The mode is visible in both types and runtime (via a $mode property)
  • Debuggable: Easy to inspect the current mode at runtime
  • Better IDE support: Type information is more predictable

How CombineModes works

The CombineModes type computes whether a combined parser should be sync or async:

type CombineModes<T extends readonly Mode[]> = "async" extends T[number]
  ? "async"
  : "sync";

This type checks if "async" is present anywhere in the tuple of modes. If so, the result is "async"; otherwise, it's "sync".

For combinators like object(), I needed to extract modes from parser objects and combine them:

// Extract the mode from a single parser
type ParserMode<T> = T extends Parser<infer M, unknown, unknown> ? M : never;

// Combine modes from all values in a record of parsers
type CombineObjectModes<T extends Record<string, Parser<Mode, unknown, unknown>>> =
  CombineModes<{ [K in keyof T]: ParserMode<T[K]> }[keyof T][]>;

Runtime implementation

The type system handles compile-time safety, but the implementation also needs runtime logic. Each parser has a $mode property that indicates its execution mode:

const syncParser = option("-n", "--name", string());
console.log(syncParser.$mode);  // "sync"

const asyncParser = option("-b", "--branch", asyncValueParser);
console.log(asyncParser.$mode);  // "async"

Combinators compute their mode at construction time:

function object<T extends Record<string, Parser<Mode, unknown, unknown>>>(
  parsers: T
): Parser<CombineObjectModes<T>, ObjectValue<T>, ObjectState<T>> {
  const parserKeys = Reflect.ownKeys(parsers);
  const combinedMode: Mode = parserKeys.some(
    (k) => parsers[k as keyof T].$mode === "async"
  ) ? "async" : "sync";

  // ... implementation
}

Refining the API

Lucas suggested an important refinement during our discussion. Instead of having run() automatically choose between sync and async based on the parser mode, he proposed separate functions:

Perhaps run(…) could be automatic, and runSync(…) and runAsync(…) could enforce that the inferred type matches what is expected.

So we ended up with:

  • run(): automatic based on parser mode
  • runSync(): enforces sync mode at compile time
  • runAsync(): enforces async mode at compile time
// Automatic: returns T for sync parsers, Promise<T> for async
const result1 = run(syncParser);  // string
const result2 = run(asyncParser);  // Promise<string>

// Explicit: compile-time enforcement
const result3 = runSync(syncParser);  // string
const result4 = runAsync(asyncParser);  // Promise<string>

// Compile error: can't use runSync with async parser
const result5 = runSync(asyncParser);  // Type error!

I applied the same pattern to parse()/parseSync()/parseAsync() and suggest()/suggestSync()/suggestAsync() in the facade functions.

Creating async value parsers

With the new API, creating an async value parser for Git branches looks like this:

import type { Suggestion } from "@optique/core/parser";
import type { ValueParser, ValueParserResult } from "@optique/core/valueparser";

function gitRef(): ValueParser<"async", string> {
  return {
    $mode: "async",
    metavar: "REF",
    parse(input: string): Promise<ValueParserResult<string>> {
      return Promise.resolve({ success: true, value: input });
    },
    format(value: string): string {
      return value;
    },
    async *suggest(prefix: string): AsyncIterable<Suggestion> {
      const { $ } = await import("bun");
      const [branches, tags] = await Promise.all([
        $`git for-each-ref --format='%(refname:short)' refs/heads/`.text(),
        $`git for-each-ref --format='%(refname:short)' refs/tags/`.text(),
      ]);
      for (const ref of [...branches.split("\n"), ...tags.split("\n")]) {
        const trimmed = ref.trim();
        if (trimmed && trimmed.startsWith(prefix)) {
          yield { kind: "literal", text: trimmed };
        }
      }
    },
  };
}

Notice that parse() returns Promise.resolve() even though it's synchronous. This is because the ValueParser<"async", T> type requires all methods to use async signatures. Lucas pointed out this is a minor ergonomic issue. If only suggest() needs to be async, you still have to wrap parse() in a Promise.

I considered per-method mode granularity (e.g., ValueParser<ParseMode, SuggestMode, T>), but the implementation complexity would multiply substantially. For now, the workaround is simple enough:

// Option 1: Use Promise.resolve()
parse(input) {
  return Promise.resolve({ success: true, value: input });
}

// Option 2: Mark as async and suppress the linter
// biome-ignore lint/suspicious/useAwait: sync implementation in async ValueParser
async parse(input) {
  return { success: true, value: input };
}

What it cost

Supporting dual modes added significant complexity to Optique's internals. Every combinator needed updates:

  • Type signatures grew more complex with mode parameters
  • Mode propagation logic had to be added to every combinator
  • Dual implementations were needed for sync and async code paths
  • Type casts were sometimes necessary in the implementation to satisfy TypeScript

For example, the object() combinator went from around 100 lines to around 250 lines. The internal implementation uses conditional logic based on the combined mode:

if (combinedMode === "async") {
  return {
    $mode: "async" as M,
    // ... async implementation with Promise chains
    async parse(context) {
      // ... await each field's parse result
    },
  };
} else {
  return {
    $mode: "sync" as M,
    // ... sync implementation
    parse(context) {
      // ... directly call each field's parse
    },
  };
}

This duplication is the cost of supporting both modes without runtime overhead for sync-only use cases.

Lessons learned

Listen to users, but validate with prototypes

My initial instinct was to resist async support. Lucas's persistence and concrete examples changed my mind, but I validated the approach with a prototype before committing. The prototype revealed practical issues (like TypeScript inference limits) that pure design analysis would have missed.

Backward compatibility is worth the complexity

Making "sync" the default mode meant existing code continued to work unchanged. This was a deliberate choice. Breaking changes should require user action, not break silently.

Unified mode vs per-method granularity

I chose unified mode (all methods share the same sync/async mode) over per-method granularity. This means users occasionally write Promise.resolve() for methods that don't actually need async, but the alternative was multiplicative complexity in the type system.

Designing in public

The entire design process happened in a public GitHub issue. Lucas, Giuseppe, and others contributed ideas that shaped the final API. The runSync()/runAsync() distinction came directly from Lucas's feedback.

Conclusion

This was one of the more challenging features I've implemented in Optique. TypeScript's type system is powerful enough to encode the “any async means all async” rule at compile time, but getting there required careful design work and prototyping.

What made it work: conditional types like ModeValue<M, T> can bridge the gap between sync and async worlds. You pay for it with implementation complexity, but the user-facing API stays clean and type-safe.

Optique 0.9.0 with async support is currently in pre-release testing. If you'd like to try it, check out PR #70 or install the pre-release:

npm  add       @optique/core@0.9.0-dev.212 @optique/run@0.9.0-dev.212
deno add --jsr @optique/core@0.9.0-dev.212 @optique/run@0.9.0-dev.212

Feedback is welcome!

github.com

Add sync/async mode support to `Parser` and `ValueParser` by dahlia · Pull Request #70 · dahlia/optique

Summary Implements sync/async mode support for Parser and ValueParser as discussed in #52. This allows async operations in value parsers, such as: Validating values against remote APIs Fetching co...

@hongminhee@hackers.pub

I recently added sync/async mode support to Optique, a type-safe CLI parser for TypeScript. It turned out to be one of the trickier features I've implemented—the object() combinator alone needed to compute a combined mode from all its child parsers, and TypeScript's inference kept hitting edge cases.

What is Optique?

Optique is a type-safe, combinatorial CLI parser for TypeScript, inspired by Haskell's optparse-applicative. Instead of decorators or builder patterns, you compose small parsers into larger ones using combinators, and TypeScript infers the result types.

Here's a quick taste:

import { object } from "@optique/core/constructs";
import { argument, option } from "@optique/core/primitives";
import { string, integer } from "@optique/core/valueparser";
import { run } from "@optique/run";

const cli = object({
  name: argument(string()),
  count: option("-n", "--count", integer()),
});

// TypeScript infers: { name: string; count: number | undefined }
const result = run(cli);  // sync by default

The type inference works through arbitrarily deep compositions—in most cases, you don't need explicit type annotations.

How it started

Lucas Garron (@lgarron) opened an issue requesting async support for shell completions. He wanted to provide Tab-completion suggestions by running shell commands like git for-each-ref to list branches and tags.

// Lucas's example: fetching Git branches and tags in parallel
const [branches, tags] = await Promise.all([
  $`git for-each-ref --format='%(refname:short)' refs/heads/`.text(),
  $`git for-each-ref --format='%(refname:short)' refs/tags/`.text(),
]);

At first, I didn't like the idea. Optique's entire API was synchronous, which made it simpler to reason about and avoided the “async infection” problem where one async function forces everything upstream to become async. I argued that shell completion should be near-instantaneous, and if you need async data, you should cache it at startup.

But Lucas pushed back. The filesystem is a database, and many useful completions inherently require async work—Git refs change constantly, and pre-caching everything at startup doesn't scale for large repos. Fair point.

What I needed to solve

So, how do you support both sync and async execution modes in a composable parser library while maintaining type safety?

The key requirements were:

  • parse() returns T or Promise<T>
  • complete() returns T or Promise<T>
  • suggest() returns Iterable<T> or AsyncIterable<T>
  • When combining parsers, if any parser is async, the combined result must be async
  • Existing sync code should continue to work unchanged

The fourth requirement is the tricky one. Consider this:

const syncParser = flag("--verbose");
const asyncParser = option("--branch", asyncValueParser);

// What's the type of this?
const combined = object({ verbose: syncParser, branch: asyncParser });

The combined parser should be async because one of its fields is async. This means we need type-level logic to compute the combined mode.

Five design options

I explored five different approaches, each with its own trade-offs.

Option A: conditional types with mode parameter

Add a mode type parameter to Parser and use conditional types:

type Mode = "sync" | "async";

type ModeValue<M extends Mode, T> = M extends "async" ? Promise<T> : T;

interface Parser<M extends Mode, TValue, TState> {
  parse(context: ParserContext<TState>): ModeValue<M, ParserResult<TState>>;
  // ...
}

The challenge is computing combined modes:

type CombineModes<T extends Record<string, Parser<any, any, any>>> =
  T[keyof T] extends Parser<infer M, any, any>
    ? M extends "async" ? "async" : "sync"
    : never;

Option B: mode parameter with default value

A variant of Option A, but place the mode parameter first with a default of "sync":

interface Parser<M extends Mode = "sync", TValue, TState> {
  readonly $mode: M;
  // ...
}

The default value maintains backward compatibility—existing user code keeps working without changes.

Option C: separate interfaces

Define completely separate Parser and AsyncParser interfaces with explicit conversion:

interface Parser<TValue, TState> { /* sync methods */ }
interface AsyncParser<TValue, TState> { /* async methods */ }

function toAsync<T, S>(parser: Parser<T, S>): AsyncParser<T, S>;

Simpler to understand, but requires code duplication and explicit conversions.

Option D: union return types for suggest() only

The minimal approach. Only allow suggest() to be async:

interface Parser<TValue, TState> {
  parse(context: ParserContext<TState>): ParserResult<TState>;  // always sync
  suggest(context: ParserContext<TState>, prefix: string):
    Iterable<Suggestion> | AsyncIterable<Suggestion>;  // can be either
}

This addresses the original use case but doesn't help if async parse() is ever needed.

Option E: fp-ts style HKT simulation

Use the technique from fp-ts to simulate Higher-Kinded Types:

interface URItoKind<A> {
  Identity: A;
  Promise: Promise<A>;
}

type Kind<F extends keyof URItoKind<any>, A> = URItoKind<A>[F];

interface Parser<F extends keyof URItoKind<any>, TValue, TState> {
  parse(context: ParserContext<TState>): Kind<F, ParserResult<TState>>;
}

The most flexible approach, but with a steep learning curve.

Testing the idea

Rather than commit to an approach based on theoretical analysis, I created a prototype to test how well TypeScript handles the type inference in practice. I published my findings in the GitHub issue:

Both approaches correctly handle the “any async → all async” rule at the type level. (…) Complex conditional types like ModeValue<CombineParserModes<T>, ParserResult<TState>> sometimes require explicit type casting in the implementation. This only affects library internals. The user-facing API remains clean.

The prototype validated that Option B (explicit mode parameter with default) would work. I chose it for these reasons:

  • Backward compatible: The default "sync" keeps existing code working
  • Explicit: The mode is visible in both types and runtime (via a $mode property)
  • Debuggable: Easy to inspect the current mode at runtime
  • Better IDE support: Type information is more predictable

How CombineModes works

The CombineModes type computes whether a combined parser should be sync or async:

type CombineModes<T extends readonly Mode[]> = "async" extends T[number]
  ? "async"
  : "sync";

This type checks if "async" is present anywhere in the tuple of modes. If so, the result is "async"; otherwise, it's "sync".

For combinators like object(), I needed to extract modes from parser objects and combine them:

// Extract the mode from a single parser
type ParserMode<T> = T extends Parser<infer M, unknown, unknown> ? M : never;

// Combine modes from all values in a record of parsers
type CombineObjectModes<T extends Record<string, Parser<Mode, unknown, unknown>>> =
  CombineModes<{ [K in keyof T]: ParserMode<T[K]> }[keyof T][]>;

Runtime implementation

The type system handles compile-time safety, but the implementation also needs runtime logic. Each parser has a $mode property that indicates its execution mode:

const syncParser = option("-n", "--name", string());
console.log(syncParser.$mode);  // "sync"

const asyncParser = option("-b", "--branch", asyncValueParser);
console.log(asyncParser.$mode);  // "async"

Combinators compute their mode at construction time:

function object<T extends Record<string, Parser<Mode, unknown, unknown>>>(
  parsers: T
): Parser<CombineObjectModes<T>, ObjectValue<T>, ObjectState<T>> {
  const parserKeys = Reflect.ownKeys(parsers);
  const combinedMode: Mode = parserKeys.some(
    (k) => parsers[k as keyof T].$mode === "async"
  ) ? "async" : "sync";

  // ... implementation
}

Refining the API

Lucas suggested an important refinement during our discussion. Instead of having run() automatically choose between sync and async based on the parser mode, he proposed separate functions:

Perhaps run(…) could be automatic, and runSync(…) and runAsync(…) could enforce that the inferred type matches what is expected.

So we ended up with:

  • run(): automatic based on parser mode
  • runSync(): enforces sync mode at compile time
  • runAsync(): enforces async mode at compile time
// Automatic: returns T for sync parsers, Promise<T> for async
const result1 = run(syncParser);  // string
const result2 = run(asyncParser);  // Promise<string>

// Explicit: compile-time enforcement
const result3 = runSync(syncParser);  // string
const result4 = runAsync(asyncParser);  // Promise<string>

// Compile error: can't use runSync with async parser
const result5 = runSync(asyncParser);  // Type error!

I applied the same pattern to parse()/parseSync()/parseAsync() and suggest()/suggestSync()/suggestAsync() in the facade functions.

Creating async value parsers

With the new API, creating an async value parser for Git branches looks like this:

import type { Suggestion } from "@optique/core/parser";
import type { ValueParser, ValueParserResult } from "@optique/core/valueparser";

function gitRef(): ValueParser<"async", string> {
  return {
    $mode: "async",
    metavar: "REF",
    parse(input: string): Promise<ValueParserResult<string>> {
      return Promise.resolve({ success: true, value: input });
    },
    format(value: string): string {
      return value;
    },
    async *suggest(prefix: string): AsyncIterable<Suggestion> {
      const { $ } = await import("bun");
      const [branches, tags] = await Promise.all([
        $`git for-each-ref --format='%(refname:short)' refs/heads/`.text(),
        $`git for-each-ref --format='%(refname:short)' refs/tags/`.text(),
      ]);
      for (const ref of [...branches.split("\n"), ...tags.split("\n")]) {
        const trimmed = ref.trim();
        if (trimmed && trimmed.startsWith(prefix)) {
          yield { kind: "literal", text: trimmed };
        }
      }
    },
  };
}

Notice that parse() returns Promise.resolve() even though it's synchronous. This is because the ValueParser<"async", T> type requires all methods to use async signatures. Lucas pointed out this is a minor ergonomic issue. If only suggest() needs to be async, you still have to wrap parse() in a Promise.

I considered per-method mode granularity (e.g., ValueParser<ParseMode, SuggestMode, T>), but the implementation complexity would multiply substantially. For now, the workaround is simple enough:

// Option 1: Use Promise.resolve()
parse(input) {
  return Promise.resolve({ success: true, value: input });
}

// Option 2: Mark as async and suppress the linter
// biome-ignore lint/suspicious/useAwait: sync implementation in async ValueParser
async parse(input) {
  return { success: true, value: input };
}

What it cost

Supporting dual modes added significant complexity to Optique's internals. Every combinator needed updates:

  • Type signatures grew more complex with mode parameters
  • Mode propagation logic had to be added to every combinator
  • Dual implementations were needed for sync and async code paths
  • Type casts were sometimes necessary in the implementation to satisfy TypeScript

For example, the object() combinator went from around 100 lines to around 250 lines. The internal implementation uses conditional logic based on the combined mode:

if (combinedMode === "async") {
  return {
    $mode: "async" as M,
    // ... async implementation with Promise chains
    async parse(context) {
      // ... await each field's parse result
    },
  };
} else {
  return {
    $mode: "sync" as M,
    // ... sync implementation
    parse(context) {
      // ... directly call each field's parse
    },
  };
}

This duplication is the cost of supporting both modes without runtime overhead for sync-only use cases.

Lessons learned

Listen to users, but validate with prototypes

My initial instinct was to resist async support. Lucas's persistence and concrete examples changed my mind, but I validated the approach with a prototype before committing. The prototype revealed practical issues (like TypeScript inference limits) that pure design analysis would have missed.

Backward compatibility is worth the complexity

Making "sync" the default mode meant existing code continued to work unchanged. This was a deliberate choice. Breaking changes should require user action, not break silently.

Unified mode vs per-method granularity

I chose unified mode (all methods share the same sync/async mode) over per-method granularity. This means users occasionally write Promise.resolve() for methods that don't actually need async, but the alternative was multiplicative complexity in the type system.

Designing in public

The entire design process happened in a public GitHub issue. Lucas, Giuseppe, and others contributed ideas that shaped the final API. The runSync()/runAsync() distinction came directly from Lucas's feedback.

Conclusion

This was one of the more challenging features I've implemented in Optique. TypeScript's type system is powerful enough to encode the “any async means all async” rule at compile time, but getting there required careful design work and prototyping.

What made it work: conditional types like ModeValue<M, T> can bridge the gap between sync and async worlds. You pay for it with implementation complexity, but the user-facing API stays clean and type-safe.

Optique 0.9.0 with async support is currently in pre-release testing. If you'd like to try it, check out PR #70 or install the pre-release:

npm  add       @optique/core@0.9.0-dev.212 @optique/run@0.9.0-dev.212
deno add --jsr @optique/core@0.9.0-dev.212 @optique/run@0.9.0-dev.212

Feedback is welcome!

github.com

Add sync/async mode support to `Parser` and `ValueParser` by dahlia · Pull Request #70 · dahlia/optique

Summary Implements sync/async mode support for Parser and ValueParser as discussed in #52. This allows async operations in value parsers, such as: Validating values against remote APIs Fetching co...

Optique 0.9.0プレリリース、テスト中です!

今回の目玉機能はsync/asyncモード対応です。非同期の値パースや補完に対応したCLIパーサーが作れるようになりました。Gitのブランチ/タグ一覧のように、シェルコマンドの実行が必要な補完にぴったりです。

Asyncモードはcombinatorを通じて自動的に伝播するので、開発者は末端のパーサーでだけsync/asyncを決めればOKです。

インストール:

npm  add       @optique/core@0.9.0-dev.212 @optique/run@0.9.0-dev.212
deno add --jsr @optique/core@0.9.0-dev.212 @optique/run@0.9.0-dev.212

マージ前にフィードバックいただけると助かります!特に気になる点:

  • APIの使い勝手
  • 見落としているエッジケース
  • TypeScriptの型推論の問題

ドキュメント:

PR: https://github.com/dahlia/optique/pull/70

github.com

Add sync/async mode support to `Parser` and `ValueParser` by dahlia · Pull Request #70 · dahlia/optique

Summary Implements sync/async mode support for Parser and ValueParser as discussed in #52. This allows async operations in value parsers, such as: Validating values against remote APIs Fetching co...

Optique 0.9.0 프리릴리스 테스트 중입니다!

이번 주요 기능은 동기/비동기 모드 지원입니다. 이제 비동기 값 파싱과 자동완성을 지원하는 CLI 파서를 만들 수 있습니다. Git 브랜치/태그 목록처럼 셸 명령 실행이 필요한 자동완성에 딱이에요.

컴비네이터를 통해 async 모드가 자동으로 전파되기 때문에, 개발자는 말단 파서에서만 동기/비동기를 결정하면 됩니다.

설치:

npm  add       @optique/core@0.9.0-dev.212 @optique/run@0.9.0-dev.212
deno add --jsr @optique/core@0.9.0-dev.212 @optique/run@0.9.0-dev.212

머지 전에 피드백 주시면 정말 감사하겠습니다! 특히 이런 부분이 궁금해요:

  • API 사용성
  • 에지 케이스
  • TypeScript 타입 추론 문제

문서:

PR: https://github.com/dahlia/optique/pull/70

github.com

Add sync/async mode support to `Parser` and `ValueParser` by dahlia · Pull Request #70 · dahlia/optique

Summary Implements sync/async mode support for Parser and ValueParser as discussed in #52. This allows async operations in value parsers, such as: Validating values against remote APIs Fetching co...

@hongminhee@hollo.social

Optique 0.9.0 pre-release is ready for testing!

The big new feature: sync/async mode support. You can now build CLI parsers with async value parsing and suggestions—perfect for shell completions that need to run commands (like listing Git branches/tags).

The API automatically propagates async mode through combinators, so you only decide sync vs async at the leaf level.

Try it:

npm  add       @optique/core@0.9.0-dev.212 @optique/run@0.9.0-dev.212
deno add --jsr @optique/core@0.9.0-dev.212 @optique/run@0.9.0-dev.212

I'd love feedback before merging! Especially interested in:

  • API ergonomics
  • Edge cases I might have missed
  • TypeScript inference issues

Docs:

PR: https://github.com/dahlia/optique/pull/70

github.com

Add sync/async mode support to `Parser` and `ValueParser` by dahlia · Pull Request #70 · dahlia/optique

Summary Implements sync/async mode support for Parser and ValueParser as discussed in #52. This allows async operations in value parsers, such as: Validating values against remote APIs Fetching co...

@hongminhee@hollo.social · Reply to Bart Louwers

@bart Thanks for sharing this! I hadn't seen this issue before—really interesting to learn that Node.js is exploring built-in structured logging.

Looking at the discussion, it seems like they're still in the early stages—lots of debate around API design and porting foundational pieces like SonicBoom. So it might be a while before anything lands, but exciting to see the progress.

Until then, LogTape is one option that tries to fill this gap. And if node:log eventually ships, hopefully the concepts are similar enough that migrating wouldn't be too painful!