Repository navigation
Description
Is there an existing issue or pull request for this?
- I have searched the existing issues and pull requests
Feature description
Context
WolfStar used to run two processes. projects/gateway connected the shards with @discordjs/ws. It wrote every dispatch into a Redis cache and forwarded the events to the bot over a Redis stream broker. The bot built on @wolfstar/http-framework consumed those events. We are replacing all of that with @wolfstar/plugin-gateway 0.1.1 and @wolfstar/plugin-cache 0.2.0. The bot now builds a GatewayClient with createRedisCache({ redis }) and calls start(), and the dedicated gateway project is deleted.
The migration surfaced one blocking issue and several gaps. This RFC lists them, ordered by impact, with a proposed solution for each. Most can be split into separate PRs.
1. Blocking: no register entrypoint, but the Stars CLI imports one
The Stars CLI (@wolfstar/cli 2.x, the stars:plugin-registrations transform in @wolfstar/vite-server) injects import "<name>/register" into the entry for every dependency matching /^@wolfstar\/plugin-[^/]+$/. Neither @wolfstar/plugin-gateway nor @wolfstar/plugin-cache exports ./register: their exports only has ".". A project that depends on them builds fine, then crashes at startup:
Error [ERR_PACKAGE_PATH_NOT_EXPORTED]: Package subpath './register' is not defined by "exports" in .../node_modules/@wolfstar/plugin-cache/package.json imported from .../dist/main.mjs
Reproduction: a Stars project with @wolfstar/plugin-gateway in dependencies, then stars build and node dist/main.mjs. The emitted entry starts with:
import '@wolfstar/plugin-api/register';
import '@wolfstar/plugin-cache/register';
import '@wolfstar/plugin-gateway/register';A plain alias does not work around it: the tsdown defaults set deps.neverBundle: true, so the specifier is externalized before any alias plugin sees it. Our current workaround is an alias to an empty module, plus deps: { neverBundle: true, alwaysBundle: ['@wolfstar/plugin-cache/register', '@wolfstar/plugin-gateway/register'] } in stars.config.ts.
2. No way to request guild members over the gateway
There is no REQUEST_GUILD_MEMBERS (opcode 8) helper and no guildMembersChunk event. @wolfstar/plugin-cache already hydrates GUILD_MEMBERS_CHUNK into the cache in applyGatewayDispatch, but nothing can ask for the chunks. client.members only lists members through REST, one page at a time. Bots that keep a full member cache for moderation or logging (member counts, role checks, the GuildMembers intent) need the gateway request. The old WolfStar gateway handled it.
3. Sessions are not resumed across restarts
With a separate gateway process, restarting the bot never touched the shards. With GatewayClient, every deploy or crash re-identifies every shard: it spends identify quota, misses events, and triggers a full GUILD_CREATE burst. @discordjs/ws already supports resuming through retrieveSessionInfo/updateSessionInfo, but each application has to wire it by hand.
4. README documents subpaths that are not exported
The README lists @wolfstar/plugin-gateway/rest (@discordjs/rest) and @wolfstar/plugin-gateway/ws (@discordjs/ws), but package.json#exports only has ".". Importing either fails with ERR_PACKAGE_PATH_NOT_EXPORTED.
5. container.client stays typed as Client
getGatewayClient() exists, but container.client (what pieces use through this.container.client) is still typed as the base Client. Every piece that needs guilds, members, gateway & co. has to call the helper or cast.
6. Production dependency on a @discordjs/structures dev snapshot
@discordjs/structures is pinned to 1.0.0-dev.1790035407-dbb749062. That snapshot forces engines.node >= 24.17.0 on every consumer and can disappear or change under us, since dev tags are not immutable releases in practice.
7. Published peer ranges lag behind main
On main, every plugin accepts @wolfstar/http-framework ^3.x || ^5.0.0, but the npm releases do not. plugin-api 1.1.6 declares ^3.0.0, plugin-subcommands-advanced 2.0.4 ^3.1.0, and plugin-logger 0.2.0 ^3.4.0. A v5 project that uses GatewayClient (which does accept ^5) together with those plugins gets peer warnings. pnpm may also resolve a second http-framework copy for the plugins, so their ClientOptions augmentations (e.g. subcommandsAdvanced) do not apply to GatewayClientOptions: TS2353: 'subcommandsAdvanced' does not exist in type 'GatewayClientOptions'.
8. Every cache read is async, even in memory
The README explains why: the same code has to work with Redis. Still, porting a discord.js codebase means rewriting every synchronous guild.members.cache.get(id) into an awaited call, including in hot paths such as message filters, where the in-memory store could answer synchronously.
Desired solution
registerentrypoints. Either option works, and doing both is the safest:- Ship a no-op
./registerinplugin-gatewayandplugin-cache, as the other plugins do.plugin-gatewaycould also use it to register something useful, such as agatewayClientOptionsaugmentation. - Make the Stars transform only inject
<name>/registerwhen the package'sexportsactually defines./register. Also,@wolfstar/plugin-cacheis a library rather than a framework plugin. Renaming it (e.g.@wolfstar/cache) would keep it out of theplugin-*convention altogether.
- Ship a no-op
- Guild member requests. Add
client.members.request(guildId, { query?, limit?, userIds?, presences?, nonce? })(orguild.members.fetchAll()), resolving once everyGUILD_MEMBERS_CHUNKwith the matchingnoncehas arrived. Send it on the guild's shard viaclient.gateway.send(shardId, { op: GatewayOpcodes.RequestGuildMembers, d }), with a timeout, and respect the per-shard gateway rate limit. Also emitguildMembersChunk(members,guild | null,data) like discord.js. - Session persistence. Add an option such as
sessionStore: { get(shardId), set(shardId, info | null) }, wired intoretrieveSessionInfo/updateSessionInfo. Ship a Redis implementation next tocreateRedisCache(e.g.createRedisSessionStore({ redis, prefix })) so the sameioredisclient covers both. - Subpath exports. Either add
./restand./wstoexports, re-exporting@discordjs/restand@discordjs/ws, or remove them from the README. container.clienttyping. Add an opt-in module augmentation, e.g.import "@wolfstar/plugin-gateway/augment", that declarescontainer.clientasGatewayClient. Or document the recommended pattern for pieces.- Structures dependency. Drop the
@discordjs/structuresruntime dependency until it has a stable release: copy the small base (Structure,kData/kPatch/kCloneviaSymbol.for) into the package. Or make it an optional peer and relaxengines. - Peer ranges. Publish the plugins whose
^5peer range is only onmain(plugin-api,plugin-subcommands-advanced,plugin-logger). Add a CI check that fails when a plugin's peer range excludes the latest@wolfstar/http-frameworkmajor. - Synchronous reads. Add an optional synchronous path for in-memory caches, e.g.
client.members.cached(guildId, userId)returningGuildMember | undefinedwhen the cache is synchronous andundefined(or a throw) otherwise. Or exposecache.isSynchronousso callers can branch.
Alternatives considered
- Keep a dedicated gateway process feeding the bot over a Redis stream, as before. It avoids items 3 and 8, but duplicates what
plugin-gateway+plugin-cachenow provide, and the broker/cache protocol lives only in our repo.plugin-shardercovers multi-process sharding, so the separate process no longer pays for itself. - Work around item 1 in every application with aliases and
deps.alwaysBundle, as we do now. It works, but every Stars user hits the crash at runtime, not at build time, so it has to be fixed upstream. - Use
client.members.list()(REST) instead of item 2. It works for small guilds, but it costs one REST call per 1000 members and does not scale to large guilds.
Additional context
- Migration in WolfStar:
projects/bot/src/lib/Client.tsbuilds theGatewayClient. The workaround for item 1 lives inprojects/bot/scripts/aliases.ts(missingPluginRegisters) andprojects/bot/stars.config.ts(deps.alwaysBundle). - Related RFCs: RFC:
GatewayClient— Gateway (WebSocket) support for@wolfstar/http-framework#54 (GatewayClient), RFC: Pluggable cache layer for@wolfstar/plugin-gateway(Cache,EntityCache,CachedManager) #55 (pluggable cache layer), plugin-i18next: latest release does not accept @wolfstar/http-framework v5 as a peer #115 (peer ranges forplugin-i18next). - Versions:
@wolfstar/plugin-gateway0.1.1,@wolfstar/plugin-cache0.2.0,@wolfstar/http-framework5.1.0,@wolfstar/cli2.0.1, Node.js 24.19.
Activity
pullfrog commentedon Sep 26, 2026
Assessment
Issue #121 is well-scoped and actionable — the author already reproduced the blocking bug, and the RFC's "Desired solution" section names concrete APIs to add. I verified every claim against the current
mainsource (not just trusting the issue text); details and one correction below.Verified as accurate:
packages/plugin-gateway/package.jsonandpackages/plugin-cache/package.jsononly export"."— no./register, noregister.ts.plugin-api,plugin-i18next,plugin-logger,plugin-subcommands-advancedall havesrc/register.ts+ a matchingexports["./register"]entry.plugin-sharder(also@wolfstar/plugin-[^/]+) has the same gap and would hit the same crash — worth covering in the Stars-transform fix even though the issue doesn't name it.RequestGuildMembersopcode helper and noguildMembersChunkevent anywhere inplugin-gateway/src.plugin-cache/src/lib/operations.ts(hydrateGuildMembersChunk, line ~953) already hydratesGUILD_MEMBERS_CHUNKinto themembers/usersstores — the write path exists, only the request+correlation path is missing.sessionStore/retrieveSessionInfo/updateSessionInforeference anywhere in the repo.GatewayClient'sWebSocketManagerconstruction (GatewayClient.ts:190) doesn't set either hook.README.mddocuments@wolfstar/plugin-gateway/restand/ws(lines ~489–497), butpackage.json#exportsonly has".". Confirmed mismatch.container.clienttyping): confirmed via source read —plugin-gateway/src/index.tshas nodeclare moduleaugmentingClientOptionsorcontainer.client(onlyevents.tsaugmentsClientEvents, unrelated). Compareplugin-subcommands-advanced/src/index.ts:30-37, which does augmentClientOptions— that's the pattern to follow, but forcontainer.clientinstead.@discordjs/structuresis pinned to1.0.0-dev.1790035407-dbb749062withengines.node >= 24.17.0forced by it.plugin-cache'sEntityCache<Raw>interface already types every method asAwaitable<T>(T | Promise<T>), andMemoryEntityCache.get()(plugin-cache/src/lib/memory.ts) already returns synchronously. The gap is one layer up:CachedManager/GuildMemberManagerinplugin-gatewaydeclare every methodasync, so callers alwaysawaiteven against an in-memory cache. A sync path is aplugin-gateway-side addition, not aplugin-cacheone.One correction to the issue — #7 (peer ranges) is already resolved for two of the three named packages:
plugin-logger(0.2.0),plugin-api(1.1.6), andplugin-subcommands-advanced(2.0.4) all already publish@wolfstar/http-frameworkpeer ranges including^5.0.0— this shipped via a generic "update all non-major dependencies" Renovate PR whose changelog entry doesn't call out the peer bump, which is likely why it read as unfixed. No.changeset/entries are pending for any of this. The only real remaining work here is the CI check the issue itself proposes (fail when a plugin's peer range excludes the latest@wolfstar/http-frameworkmajor), to stop this from silently regressing again.Proposed plan (mirrors the issue's own impact ordering; each numbered item ships as its own PR)
registerentrypoints (blocking). Two changes:src/register.ts+exports["./register"]toplugin-gatewayandplugin-cache, matching the existing pattern inplugin-api/plugin-logger/plugin-subcommands-advanced(sideEffects: ["./dist/esm/register.js"],attwEntrypointsupdated per thecreateTsdownOptionsconvention noted inplugin-api's changelog).stars:plugin-registrationstransform (in@wolfstar/cli, a separate repo/package — flag as a cross-repo dependency) to only injectimport "<name>/register"whenexports["./register"]is actually declared. This is the durable fix; the no-op export is the immediate unblock. Also coversplugin-sharder, which has the same gap today.@wolfstar/plugin-cache(e.g.@wolfstar/cache) since it's a library, not anhttp-frameworkplugin — larger, separate discussion; don't bundle into this PR.Guild member requests. Add to
GuildMemberManager:request(guildId, { query?, limit?, userIds?, presences?, nonce? })sendingGatewayOpcodes.RequestGuildMembersviaclient.gateway.send(shardId, payload), resolving once everyGUILD_MEMBERS_CHUNKwith the matchingnoncearrives (track pending requests in a map keyed by nonce, matchingchunk_index === chunk_count - 1), with a timeout mirroringDispatchTimeoutError's pattern. Add aGuildMembersChunkentry toDispatchHandlers(util/dispatch.ts) emittingguildMembersChunk(members,guild | null,data) — this is a normalDispatchHandleraddition, no different in shape from the existing ones.Session persistence. Add
sessionStore?: { get(shardId): Awaitable<SessionInfo | null>, set(shardId, info): Awaitable<void> }toGatewayClientOptions, wired into theWebSocketManagerconstructor'sretrieveSessionInfo/updateSessionInfo. ShipcreateRedisSessionStore({ redis, prefix })inplugin-cachenext tocreateRedisCache, reusing the sameioredisclient.Subpath exports vs. README. Either add
./restand./wstoplugin-gateway'sexports(thin re-export modules) or trim the README's "Subpath exports" table to match reality — recommend the former since the README already sells this as a@discordjs/next-style convenience.container.clienttyping. Add an opt-in@wolfstar/plugin-gateway/augmententrypoint withdeclare module "@wolfstar/http-framework" { interface Container { client: GatewayClient } }(mirroringplugin-subcommands-advanced'sClientOptionsaugmentation pattern, applied to the client type instead).Drop the
@discordjs/structuresdev-snapshot runtime dependency. Copy the small base (Structureclass,kData/kPatch/kCloneviaSymbol.for) intoplugin-gateway/src/structures/Structure.tsdirectly (it already re-exports these symbols) so a stable Node engine range can be restored; or make it an optional peer if copying the base is judged too invasive.Peer ranges + CI guard. No package fix needed (see correction above). Add a CI check (probably a
pnpmscript run in the existing typecheck/lint workflow) that fails when any plugin'speerDependencies["@wolfstar/http-framework"]range excludes whatever majorplugin-gateway's own peer range accepts, to catch regressions like this early.Synchronous cache reads. Add an opt-in sync path to
CachedManager/GuildMemberManager, e.g.cached(...args): Value | undefined, usable only whenclient.cacheexposes a synchronousEntityCache(detectable via acache.isSynchronousflag added to theCache/EntityCachecontract inplugin-cache, sinceAwaitablealone can't be checked at runtime). Throws or returnsundefinedagainst a Redis-backed cache.Each item is independently shippable and none blocks the others except that #1 is the one actively breaking consumers today and should land first. Ready to start on #1 whenever you'd like — say the word and I'll open the PR.
Claude Sonnet| 𝕏pullfrog commentedon Sep 26, 2026
Implemented item #1 of the plan for #121 — the blocking
./registerentrypoint bug.Opened PR #122: adds a no-op
./registersubpath export to@wolfstar/plugin-gateway,@wolfstar/plugin-cache, and@wolfstar/plugin-sharder(all three match the@wolfstar/plugin-*pattern that@wolfstar/cli's Stars transform unconditionally injectsimport "<name>/register"for, so they were crashing consumers withERR_PACKAGE_PATH_NOT_EXPORTED). Each package getssrc/register.ts, anexports["./register"]entry,sideEffectsarray, and updatedtsdown.config.ts/attwEntrypoints, plus a patch changeset for all three.Verified: builds pass with
attw/publintclean for all three packages,tsc --noEmitpasses,oxlint/oxfmt --checkclean, and a fresh-eyes self-review found no defects.The remaining 7 items from the plan (member requests, session persistence,
container.clienttyping, README subpath drift, dropping the@discordjs/structuresdev dependency, peer-range CI guard, synchronous cache reads) are separate follow-up PRs — #121 is left open for those.Claude Sonnet| 𝕏fix(plugin-gateway,plugin-cache,plugin-sharder): add a no-op `./regis…
fix(plugin-gateway): treat an empty `userIds` as omitted in members r…
fix(plugin-gateway): join a concurrent `destroy` instead of racing it…
RedStar071 commentedon Sep 27, 2026
Every item in this RFC is now handled on
main:registerentrypoints./registerinplugin-gateway,plugin-cacheandplugin-sharder. None of them needs aPluginhook. A workspace test fails if any@wolfstar/plugin-*package lacks the subpath. The Stars transform side was already fixed instars-components#222 and released in@wolfstar/vite-server0.2.2: it only injects/registerwhen the package exports it.client.members.request(guildId, options),Guild#requestMembers, and theguildMembersChunkevent. It rejects on timeout or onRATE_LIMITED.sessionStore/sessionStoreTimeoutoptions, pluscreateRedisSessionStoreinplugin-cache.destroy({ resumable: true })closes the shards with 4200 and keeps their sessions.@discordjs/restand@discordjs/wsdirectly. #129 had added the subpaths; #134 reverted it.container.clienttypingcontainer.gatewayClient: GatewayClient. Retypingcontainer.clientisn't possible: it fails with TS2717, and underskipLibCheckthe framework's declaration still takes precedence.@discordjs/structuresplugin-api,plugin-loggerandplugin-subcommands-advanced, so the^5ranges already onmainget published. A test guards the peer ranges from now on.EntityCache.synchronous, andmanager.cached(...)on every manager. It throws on an asynchronous cache instead of returning a false miss.The changes ship with the next release.
Generated by Claude Code