npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@typetorch/framework

v0.5.0

Published

TypeTorch framework for roblox-ts: hot-swappable modules (dependency injection, lifecycle, troves), guarded networking, hot assets and the in-game dev menu. Ships inside every TypeTorch artifact.

Readme

@typetorch/framework

The roblox-ts framework of TypeTorch: hot-swappable modules (dependency injection, lifecycle, troves), guarded networking over the kernel's stable remotes, UI helpers and the in-game dev menu.

It ships inside every artifact, so each generation runs its own fresh copy and framework fixes hot-swap like game code. It needs the TypeTorch kernel in the place (@typetorch/kernel), which calls your Server/boot and Client/boot modules.

Install

npm i @typetorch/framework
npm i -D @typetorch/transformer

(bun add @typetorch/framework and bun add -d @typetorch/transformer work the same.) The framework is a roblox-ts 3 package; @typetorch/transformer is its compiler plugin: it generates the network guards, the constructor dependency ids of @Service / @Controller and your own macros. Nothing from Flamework is needed: Modding, Reflect and t come from this package. The starter game (template) has it all set up: clone it and run bun install.

tsconfig.json:

{
	"compilerOptions": {
		"experimentalDecorators": true,
		// Every npm scope the game imports from must be a type root (roblox-ts rule).
		"typeRoots": ["node_modules/@rbxts", "node_modules/@typetorch"],
		"types": ["types", "compiler-types"],
		"plugins": [
			// Optional, first when present: $print/$warn with file and line (what every TypeTorch repo uses).
			{ "transform": "rbxts-transform-debug", "environmentRequires": {} },
			{ "transform": "@typetorch/transformer" }
		]
	}
}

The payload is a Rojo Model project. Map only this package from the @typetorch scope (the transformer is Node code and the kernel lives in the place):

"include": {
	"$path": "include",
	"node_modules": {
		"$className": "Folder",
		"@rbxts": { "$path": "node_modules/@rbxts" },
		"@typetorch": { "$className": "Folder", "framework": { "$path": "node_modules/@typetorch/framework" } }
	}
}

Each generation requires its own copy of the payload, so the framework and its Reflect registry start fresh on every swap. It needs the TypeTorch kernel in the place (@typetorch/kernel).

Coming from Flamework

Game code only changes imports: @Service, @Controller, constructor injection, Dependency<T>(), the lifecycle interfaces and createNetwork are the same.

| Flamework | TypeTorch | |---|---| | rbxts-transformer-flamework plugin, node_modules/@flamework type root | @typetorch/transformer plugin, node_modules/@typetorch type root | | import { Modding, Reflect } from "@flamework/core" | import { Modding, Reflect } from "@typetorch/framework" | | import { Dependency } from "@flamework/core" | import { Dependency } from "@typetorch/framework" (from onInit/onStart on, not in constructors) | | import type + Dependency<T>() to break a cycle | the same, or Lazy<T> (below) | | ClientEvents.x.predict(...) | network.client.x.emit(...) | | invokeWithTimeout(timeout, ...) | invokeWithTimeout(seconds, ...) (seconds, 0.5 to 120) | | Observers.observeCharacter / observeLocalCharacter (@rbxts/observers) | still fine: put the stop function in the trove, this.trove.add(observeCharacter(...)) | | import { t } from "@rbxts/t" (still fine) | also import { t } from "@typetorch/framework" | | @metadata flamework:parameters keys, "flamework:parameters" metadata | @metadata typetorch:parameters, "typetorch:parameters" | | flamework.build, include/flamework, the @flamework Rojo mapping | gone; delete them | | Networking.createEvent / createFunction and their call sites | createFlameworkCompat (below) keeps every call site; createNetwork is the native API |

typetorch migrate --from flamework (CLI) does most of this, and the docs' guides/from-flamework.md has the whole mapping.

Usage

// src/server/boot.ts
import { startServer, type ServerKernel } from "@typetorch/framework";
import { BUILD } from "../shared/build";
export function boot(kernel: ServerKernel) {
	return startServer(kernel, { modules: [script.Parent!.FindFirstChild("services")!], build: BUILD });
}

// src/shared/net.ts
import { createNetwork, type ProperReturns } from "@typetorch/framework";
interface ClientToServer { coins: { collect(coinId: string): void; balance(): ProperReturns<number> } }
interface ServerToClient { coins: { changed(total: number): void } }
export const network = createNetwork<ClientToServer, ServerToClient>();

// src/server/services/coin.service.ts
@Service()
export class CoinService extends Module implements OnStart {
	constructor(private readonly score: ScoreService) { // injected
		super();
	}
	onStart() {
		this.trove.add(network.server.coins.collect.on((player, coinId) => this.score.add(player, 1)));
	}
}
  • Modules: @Service() (server) and @Controller() (client) classes extending Module. Constructor parameters are other modules, injected by type. Lifecycle: OnInit (sequential, dependencies first), OnStart (spawned), OnStop (reverse order), OnTick, OnPhysics, OnRender, OnPlayerAdded (replays players already in the server).
  • Modules outside the constructor: Dependency<T>() (or TypeTorch.module<T>()) returns the running module of type T from anywhere: a method, a plain class a module built, a command handler. TypeTorch.tryModule<T>() returns undefined instead of throwing. They work once every module is constructed (from onInit on); in a constructor, a field initializer or module top-level code they throw "ShopService isn't constructed yet: ...". Only this realm's modules, and per generation: after a swap they return the new generation's instance. An import type of the class is enough (no require cycle).
  • Cycles: two modules that need each other take one side as Lazy<T>, resolved on first use: constructor(private readonly team: Lazy<TeamService>) (needs @typetorch/transformer 0.2.1+) or a field, private readonly team = Lazy<TeamService>() (any transformer). this.team.get() works from onInit on (in a constructor it throws), and the start order ignores lazy edges. A cycle error names the cycle and suggests this.
  • Per-player state: this.ctx.playerState("cooldowns.v1", (player) => init) (or TypeTorch.playerState) returns { get, set, has, delete } keyed by UserId. It survives swaps (persist), and a player's entry goes when they really leave, never on a swap. The dev menu shows it under Modules > State > persist, __playerState.
  • Bad deploys roll back (kernel 0.3.2): a server onStart that throws is reported to the kernel, which rolls the server back to its last known good artifact when it happens within 30 s of start (so do 3 errors from the new code's scripts in that time). On a real shutdown every module's onStop runs too (the kernel's BindToClose).
  • Troves: every module gets this.trove; everything it creates or connects goes there, so a swap leaves nothing behind. TypeTorch.persist(key, init) (or this.ctx.persist) keeps plain data across swaps.
  • Network: createNetwork<C2S, S2C>() with nested namespaces. The server checks rate limits, shape limits and the generated type guard on every client message. setNetworkLimits({ "chat.say": { maxString: 200 } }) tunes a leaf. Requests wait 15 s for the answer: invokeWithTimeout(5, ...args) sets it per call, and a leaf's timeout (setNetworkLimits({ "vc.spawn": { timeout: 30 } }), read by the client, so set it in shared code) per leaf; both in seconds, 0.5 to 120. network.client.x.emit(...args) runs this client's own on handlers for a server -> client leaf right away, with no traffic (Flamework's predict); network.server.x.emit(player, ...args) does the same on the server, for tests. A request handler may return a Promise: the answer waits for it.
  • Flamework networking names: createFlameworkCompat<C2SEvents, S2CEvents, C2SFunctions, S2CFunctions>() returns { ServerEvents, ClientEvents, ServerFunctions, ClientFunctions, GlobalEvents, GlobalFunctions } with @flamework/networking 1.x's methods (connect returning a connection, fire(player | players), broadcast, except, predict, setCallback, invoke, invokeWithTimeout, calling a leaf directly) on this same network: same guards, limits and swap rules, so a Flamework game's call sites compile unchanged. Listeners run on their own thread each, like Flamework's, and belong to the running generation (no trove needed). Not carried over: server -> client requests, middleware, Networking.Unreliable. typetorch build notes a game still using it. Across a swap (0.3.0): what the server sends a player waits until that player's client runs the new generation (reliable messages are queued, unreliable ones dropped), and on kernel 0.3.2 a request the server can no longer answer fails at once ("The game is updating, try again.") instead of timing out.
  • Macros: Modding (from this package) declares compile-time macros that @typetorch/transformer fills in: /** @metadata macro */ export function guardOf<T>(guard?: Modding.Generic<T, "guard">) { return guard!; } makes guardOf<Shape>() compile to a t guard. Modding.Generic<T, "id" | "text">, Many, Caller and TupleLabels work the same way; see the transformer's README.
  • UI: observeElement(trove, tag, (instance, elementTrove) => ...), isRealFrame, popIn / popOut / bump (UIScale, never Size tweens) and PopupQueue (one modal at a time).
  • Dev menu: devs (Studio, project members, dev badge) get a DEV button, Ctrl+Shift+D and /tt dev: artifact (with how long the server and client generations have run, the server's uptime and the build's age), server status, logs (server, own client, other players' clients), client and server dex, network stats, module state, a branch and build picker (Server > Branch) and a Claude prompt. The sidebar, top to bottom: Artifact, Server, Network, Modules, Manage, Logs, Dex, Claude. The window can be dragged by its header and resized from its corner (double-tap the header to reset).
  • Server TPS (framework 0.4.2, kernel 0.4.2): Server > Status has a TPS line next to Memory and Lua heap: the last minute's average, its slowest second and the physics FPS (59.9 avg, 52.0 min, physics 60; the warning colour under 50 on average). Older kernels show needs kernel 0.4.2. The same numbers ride on fleet heartbeats (the explorer's fleet table).
  • Dev-only tools (framework 0.4.1, devtools/access.ts): Claude, Logs > Upload, Dex edits on the server, Network packet blocking and the hot-swap sound work under dev rules (private, reserved and Studio servers on a dev branch) for every dev, and on a public server an owner switched to a dev branch (Server > Branch) for owners only. Everywhere else the menu is read-only, with a short reason: "Dev branch only", "Owners only on public servers", "Owner-switched servers only". The rules themselves don't change (TypeTorch.channel, signatures, owner-only rollbacks).
  • Panes and windows (dev menu): every page shows in a pane with a small header: tap the title to pick another page, or use Split right, Split down, Open in new window and Close. Drag the line between two panes to resize them. The sidebar opens pages in the focused pane (the highlighted one; tap a pane to focus it). Floating windows move by their title bar and resize from their corner (double-tap the title bar to maximise); their title bar also has Minimise, Dock (back into the main panel) and Close. Windows can be split too. The layout, the windows and each pane's own settings (for example the open nodes of two Modules > State panes) survive swaps; a fresh join starts with one pane. Claude, Server > Branch and the Manage pages open once (picking them again focuses their pane); every other page can be open several times. Panes nobody sees (menu closed, window minimised) stop refreshing, and panes on the same data share one request (Status, Overview, Assets, Network > Stats, server Logs, Packets); State panes share one query budget. On phones and small screens panes only stack (two at most), and windows open maximised with one pane each.
  • State explorer (Modules > State, Server | Client): every live module of the running generation (services on the server, controllers on the client) and the persist store. Tap a row to open it: the module's own fields (not its methods), then tables, arrays, Maps and Sets, 100 entries per page (Prev / Next). Each value has a short preview: strings (cut), numbers, booleans, nil, datatypes through tostring, an Instance as its full path, a Player as its name, function, thread, buffer sizes. Nothing is ever called (raw reads only: no metamethods, no getters); a value that is its own ancestor shows as a cycle. A key filter (open nodes stay listed), Refresh and Auto (every 2 s). Server state comes from the op state.inspect (rate-limited, size-capped): owners everywhere, other devs where the dev-only tools are open to them, since server state can hold player data.
  • Logs > Upload: sends the logs shown (Server: this server's log ring; Client: your own client's; Others: the picked player's client) to the dev PC paired in the Claude tab, which saves them under <repo>/.typetorch/logs/. No Claude run, no prompt quota. Not paired: "Pair in the Claude tab first".
  • Switch a live server (kernel 0.3.4): owners switch any server and load builds on it, public and prod ones too: Server > Branch, "Switch" on a branch or "Load here" on a build, then the green Confirm. Everyone stays. These are ordinary switches and pins: Reload and Rollback keep working, and going back to prod is Switch on the prod row (its verified head). A public switch lasts for that server's lifetime and is never stored, so new servers still boot the signed prod head. Others see "Join", which moves only them to a reserved server. Manage > Servers "Load a build..." does the same for this server, the ticked servers or a share of one branch (A/B pins), with one status line under the list. A public server an owner switched to a dev branch opens the dev-only tools (Claude too) to owners.
  • Owners and devs: two roles (no admins: an older kernel's or typetorch.json's "admin" counts as a dev). The Manage group (Players, Servers, Bans) is for owners only.
  • Remote Claude (a dev-only tool: dev rules, or owners on a public server an owner switched to a dev branch): while typetorch remote-claude (@typetorch/dev-server) runs on a dev's machine, allowlisted devs prompt Claude Code from the Claude tab. Each dev pairs once by pasting the pairing code printed by typetorch-dev-server; the game server keeps the session URL and the tokens in memory and never sends them to clients. No Roblox secret is needed.

Runtime API: TypeTorch

import { TypeTorch } from "@typetorch/framework" works on the server and the client. It describes the running generation and raises events that belong to it: every listener is dropped when the generation stops, so a swap never leaves one behind. Each on* returns a disconnect function, which a trove can own.

// Identity
TypeTorch.artifact; // { id, commit, commitHash, branch, channel, builtAt, seq, assetId }
TypeTorch.generation; // 1, 2, 3... per server (or client)
TypeTorch.branch; TypeTorch.channel; TypeTorch.serverType; // "public" | "private" | "reserved" | "studio"
// Kernel 0.3.9: `channel` is the RULES this server runs under ("prod" on every public server; split data stores by it);
// `branchChannel` is what the branch IS ("prod" for the default branch or one configured prod, else "dev");
// `rules` is the same as `channel`, by name.
TypeTorch.branchChannel; TypeTorch.rules;
TypeTorch.isPinned(); TypeTorch.kernelVersion; TypeTorch.kernelApi; TypeTorch.jobId; TypeTorch.isStudio;

// How this generation started: a branch change starts a new generation.
const start = TypeTorch.startInfo; // { kind: "boot" | "swap", reason, previous?, branchChanged, requestedBy?, loadSeconds? }
if (start.reason === "auto_rollback") warn("the last deploy failed to start");
this.trove.add(TypeTorch.onBranchChanged(({ from, to }) => resetBranchData(from, to)));

// Before this generation stops (runs before every onStop; keep it short)
this.trove.add(TypeTorch.onSwapOut((info) => this.saveRound(info.reason)));

// A swap is coming: show a small hint, hide it if it's called off
this.trove.add(TypeTorch.onUpdatePending((update) => (hint.Visible = !update.cancelled)));

// State that survives swaps (plain data only)
const scores = TypeTorch.persist("scores.v1", () => new Map<number, number>());
// Per player, removed when the player really leaves (same as this.ctx.playerState)
const cooldowns = TypeTorch.playerState("cooldowns.v1", () => ({ lastUse: 0 }));
cooldowns.get(player).lastUse = os.clock();

// The running module of a type (same as Dependency<T>()), from onInit/onStart on
TypeTorch.module<ShopService>().open(player);
TypeTorch.tryModule<ShopService>()?.open(player); // undefined instead of an error

// Dev and roles (server: the kernel decides; client: only the local player, cosmetic)
if (TypeTorch.isOwner(player)) showOwnerPanel(player);
TypeTorch.onPlayerDevChanged((player, info) => setDevTools(player, info.dev));

// Server only
TypeTorch.status(); // uptime, players, memory, history: cheap
TypeTorch.branches(); TypeTorch.artifacts(); // registry reads, cached ~30 s: may yield, don't call per frame
TypeTorch.requestReload(player); // owners only, checked by the kernel

// Logs (the kernel's ring buffer)
TypeTorch.logs(0, 50);
TypeTorch.onLog((entry) => errors.push(entry)); // don't print from inside it

// Hot assets (below): same as hotAsset(...)
const shop = TypeTorch.asset("ui/shop");

// Live values, server only (kernel 0.3.8): the signed settings record's `game` field (`typetorch settings set game.<key> <json>`).
const price = TypeTorch.liveConfig("shop.price", { default: 50, parse: (raw) => (typeIs(raw, "number") ? raw : 50) });
price.get();
this.trove.add(price.onChanged((value) => this.reprice(value)));

// Cross-server, server only. Kernel 0.3.8: game topics over ONE kernel-held MessagingService topic; listeners hear
// prod servers and this branch by default (dev branches never reach prod); publish queues and retries, max 1 KiB.
this.trove.add(TypeTorch.messaging.subscribe<Ban>("1guard", (ban, meta) => applyBan(ban, meta.jobId)));
TypeTorch.messaging.publish("1guard", { kind: "ban", userId }, { to: "prod" });

// The universe's live servers (the roll call; cached per server, yields up to ~3 s when stale) and this server's public fields
TypeTorch.setServerInfo({ region: "eu", vc: true }); // JSON, at most 400 bytes, kept across swaps
const list = TypeTorch.servers(); // [{ jobId, placeVersion, players, maxPlayers, serverType, branch, channel, uptime, here, info }]

// A library call a swap must not cut off halfway (kernel 0.3.8): runs on a kernel thread; write what must survive into persist.
TypeTorch.runDetached(() => store.StartSessionAsync(`Player_${userId}`)).then((profile) => attach(player, profile));
  • startInfo.reason: boot, deploy, rollback, branch, pin, reload, server_rollback, auto_rollback or unknown. A client's first generation is always boot. requestedBy (a user id), loadSeconds, stopSeconds and swapSeconds are server-only; swapSeconds appears once the swap has finished.
  • persist(key, init) keeps a table in the kernel's memory for the server's lifetime; every later generation gets the same table back. Store plain data only: tables, arrays, Maps and Sets of strings, numbers, booleans, and Players. Never store functions, class instances, Promises, threads, connections, charm atoms or instances this generation created: they keep the old generation's code alive or are destroyed by its trove. Version the key when the shape changes. Keys starting with __ are reserved.
  • onSwapOut runs synchronously before every module's onStop, so modules can still save into persist. It doesn't run on server shutdown (kernel 0.3.2 runs onStop then; on older kernels use game.BindToClose).
  • Kernel versions: TypeTorch.features says what the running kernel supports. Kernel 0.2.2 adds the start reason and timings, the next artifact in onSwapOut, onUpdatePending, server-side onPlayerDevChanged and requestReload. On older kernels startInfo still knows boot vs swap, the previous artifact and branch (the framework records them), onBranchChanged still fires, and the reason of a swap is unknown.
  • messaging (kernel 0.3.8): subscribe(topic, (data, meta) => ...) returns a disconnect; meta = { channel, branch, jobId, serverType, placeVersion, sentAt, self, replayed? }; { from: "all" | "prod" | "branch" } changes who it hears. publish(topic, data, { to }) throws on a bad topic, non-JSON data or a message over 1 KiB (with its size), returns false when dropped at once (queue full). Studio loops back; the cloud test publishes nothing; older kernels throw "needs kernel 0.3.8". servers() works on every kernel (0.3.8 holds the roll call topic, so a swap doesn't subscribe again).
  • liveConfig(key, { default, parse? }) (kernel 0.3.8, plans/20): reads game[key] of the signed settings record the kernel verified (signed by both prod keys, so game code can't forge it); get() and onChanged(fn) (only on real changes; generation-scoped). The default without a record or key, when parse throws (warned per value), and on older kernels (warned once: "needs kernel 0.3.8"; no ConfigService fallback). TypeTorch.settings() is the whole copy (seq, at, game, analytics, fleet, ...): server only, it holds tokens.
  • runDetached(fn) (kernel 0.3.8, server only): runs fn on a thread the kernel owns, so a deploy's hard stop (which kills this generation's threads mid-call) can't cut it off: for ProfileStore / ProfileService loads, saves and releases. Returns a Promise that settles while this generation runs; after a swap the result is dropped, so a job whose result must survive writes it into persist itself. The job keeps this generation's closures alive until it ends. Errors reject it and go to the kernel's log with the generation's name (never the health window); at most 256 run at once per server (then it throws); one past 60 s is logged and flagged in Server > Status. Older kernels throw "needs kernel 0.3.8; use the DataHost job queue (Player data guide)": the other option, which works on every kernel. features.runDetached tells which one this server has.
  • Edit mode (UI Labs stories, no kernel): running is false, identity has defaults, persist keeps a local table, events never fire, and the server-only reads throw.

Player data

Saving player data is game code: pick any library (ProfileStore, DataStore2, your own). TypeTorch only gives you the pieces that keep it safe across swaps:

  • The library lives in the place, outside the payload, and a small place Script requires it first. Its open sessions, autosave loop and shutdown hook then survive every swap (a swap stops the generation's scripts).
  • Session handles live in persist, keyed by UserId. onPlayerAdded replays everyone after a swap, so it re-attaches to the open session instead of loading again.
  • Release only on Players.PlayerRemoving, never in onStop or onSwapOut.
  • Library calls can't be cut off by a swap: run them as DataHost jobs (any kernel) or with TypeTorch.runDetached (kernel 0.3.8).
  • Split store names by channel (TypeTorch.channel === "prod" ? "PlayerData" : "PlayerData_dev").

Full example with ProfileStore: Player data guide.

Hot assets: hotAsset

Builders mark models and UI templates in the place with the attribute TypeTorchAsset (a key such as "ui/shop"), typetorch assets sync uploads them, and the deploy puts the asset manifest in the artifact. Running servers then get new versions live, with no restart.

import { hotAsset } from "@typetorch/framework"; // or TypeTorch.asset("ui/shop")

// In a controller's onStart: rebuild clones the template.
const shop = hotAsset("ui/shop");
shop.changed(rebuild, this.trove); // a new version went live
rebuild(shop.get());
  • hotAsset(keyOrId, fallback?) works on the server and the client. A number is the Roblox asset id, resolved through the manifest (server) or the live copy's TypeTorchAssetId attribute (client).

    • get() returns the live copy now. With none, it returns fallback (an instance you already hold, such as the template in the place) if it is still parented, else undefined. Clone it; don't parent or edit it: a new version destroys it.
    • wait(timeout?) is get() that waits for a live copy (forever without a timeout).
    • changed(fn, trove?) calls fn(instance) each time a new copy replaces the live one: a new version, a rollback, or the first copy reaching a client. It returns a disconnect function. Pass the module's trove so the connection ends with it (shop.changed(rebuild, this.trove) or this.trove.add(shop.changed(rebuild))). Without a trove it ends when the generation stops.
    • key and version (the live copy's TypeTorchAssetVersion, an assetVersionId).
  • Clients never request anything. They read the CollectionService tag __typetorch_asset:<key>, and replicated assets arrive through replication. Assets under ServerStorage stay server-only.

  • AssetSync is a server built-in. It runs on every generation start, before any module loads (top-level code included). For each manifest key:

    1. it keeps the live copy that already has the manifest's version;
    2. else it adopts the place's own copy, if its TypeTorchAssetHash matches (or if the manifest's optional placeVersion is this server's place version);
    3. else it runs InsertService:LoadAssetVersion(ver) (all loads in parallel), strips any scripts, places the copy at its path (creating missing Folders), tags it, then destroys the copy it replaces.

    It holds the start for at most 8 s. Loads still running after that keep going, swap in when done and fire changed. A failed load keeps the old copy (on a new server, the place's copy) and shows under Server > Status > Attention.

  • Hot assets persist across swaps. They aren't in any trove. A swap changes them only when the manifest changes, and a rollback brings back the older versions. Keys the manifest doesn't name are left as they are: AssetSync never deletes builders' content. A key dropped from the manifest keeps its last live copy.

  • Clones never count. A clone keeps the tag and the attributes, but only the copy whose parent is its TypeTorchAssetPath (stamped by AssetSync) is the live one. So a template cloned into PlayerGui never shows up in get(), and AssetSync never destroys it.

  • Dev menu: Modules > Assets (Server | Client) lists each key's source (kept, baked, loaded, failed), version, load time and last error.

Analytics: AnalyticsEngine

Optional, and all ours: the game server sends rows to the backend the dev picked (Cloudflare Basin streams, or a self-hosted DuckDB analytics server). Nothing runs until an engine is created: no connections, threads or requests.

import { AnalyticsEngine } from "@typetorch/framework";

// A server module (onInit): the sink comes from the signed settings' `analytics` (kernel 0.3.8).
const analytics = new AnalyticsEngine();
analytics.track(player, "quest_done", { quest: "tutorial" }); // custom
analytics.step(player, "onboarding", 3, "opened_shop"); // funnels
analytics.purchase(player, { product: 1234, robux: 99, where: "shop" }); // after the receipt is granted
analytics.currency(player, "coins", 50, "round_reward"); // economy in (+) and out (-)
analytics.state("round"); // every player's activity; analytics.state(player, "shop") for one
const variant = analytics.experiment(player, "onboarding", ["short", "long"]); // first = control

// A client controller (onStart): everything goes through the server, never to the internet.
const analytics = new AnalyticsEngine();
analytics.track("opened_map");
analytics.screen("Inventory"); // for UIs that aren't separate ScreenGuis
const variant = analytics.experiment("onboarding", ["short", "long"]); // same answer as the server's
  • One engine per generation and realm. Every new AnalyticsEngine() joins the one already running (the first one's options win), so any module can create its own. It stops with the generation; its unsent rows wait in persist and the next generation sends them. In edit mode (UI Labs) it is inert.
  • Server calls take the player first (track(player, ...)); without one an event is server-only (no player id). Client calls are always about the local player and are marked src = "client" (a client can lie). The server checks their shape, size (props at most 4 KB) and rate. purchase and currency are server-only (revenue and the economy are server-authoritative): on the client they warn once and send nothing, and the server refuses them from clients.
  • Options (all on by default): sessions (joins, leaves, device, join source, account age bucket, Premium, country, friends in the server, first-ever vs returning, days since the last visit), tech (FPS, ping, memory, load time, client and server errors, swaps and rollbacks, leaves within 60 s of a swap), zones (parts or models tagged TTZone, named by a Name attribute or the instance name), screens (ScreenGuis in PlayerGui, GuiObjects tagged TTScreen), recording (the first-ever session in detail), fleet (kernel 0.3.2 heartbeats and deploy reports), identity (one { pid, uid } row per session to the dev's own server, below). settings (server only) replaces the signed settings' analytics, for tests, Studio and kernels before 0.3.8.
  • Every row carries the time (server clock), a random player id (never the UserId), the session, the server (JobId, type, place), the artifact (id, seq, branch, channel), the device, new vs returning, the player's state (zone:Lobby|screen:Shop|activity:round) and experiment variants. The exact rows: src/analytics/SCHEMA.md.
  • Experiments: experiment(...) is deterministic per player and name (they keep their variant in every session), may yield briefly the first time (until the player's id loads), and stamps the variant on the player's later events. The settings turn one off (active: false: everyone gets the first variant), sets weights or forces a variant, live.
  • First-ever session: for new players (a share of them, recordShare), the client records character and camera about 10 times a second, every input (never while a TextBox or the chat has focus; text boxes only say which box was used), buttons pressed and hovered, screens, prompts and deaths, from the join until 60 s after the first input. Packed into small binary chunks (10-20 KB a player) and sent through the server.
  • Never collected: chat or anything typed, usernames and display names (error texts have them replaced). No event row carries a UserId.
  • Identities (option identity, default on): once the pid is known, one row { pid, uid, t } (the UserId, nothing else) per session goes to the dev's own server only, never into the events: duckdb games in the batch body, Basin games to the fleet API (the settings' fleet url + /v1/identity, or the identity / identityToken settings). The analytics server keeps pid -> UserId in a deletable table (support lookups, Right to Erasure).
  • Player ids: DataStore TypeTorchAnalytics, key p/<UserId> -> { pid, first, last }: one read per join, a write on the first join and at leave. Deleting the key (Right to Erasure) leaves that player's rows anonymous.
  • Sending: one queue on the server (10,000 events; over that the oldest are dropped and counted), a flush every flushSeconds (15) or at 500 rows, at most ~10 HttpService requests a minute, retries with backoff, and a last flush on shutdown (kernel 0.3.2). Delivery is at least once (a swap mid-request sends that batch again). analytics.stats() (server) has the counters; flush() sends soon.
  • When uploads fail (a stale quick-tunnel URL, the dev PC's server or tunnel down, a wrong token, HttpService off; Roblox reports most network problems as HttpError: NetFail, DnsResolve or ConnectFail): the server backs off with jitter (5, 10, 20 ... 300 s, spread +-25% so a fleet of servers doesn't retry in step; a wrong token or URL waits about 5 minutes, and a settings change retries at once), keeps the rows, and logs at most ONE line a minute: the reason and the fix (analytics upload failed 5 times in a row: NetFail: the connection broke mid-request. ... Retrying in 80 s., with "(+N more in the last minute)" for the lines it held back) and one line when uploads work again. stats() also has failures (in a row), failed (since the server started), lastError, lastStatus (0 = no answer), lastErrorAt / lastOkAt (os.time()), retryIn, and, while failing, reason and fix. The dev menu shows them: Server > Status has an Analytics line (queued, sent, FAILING x5: ... retry in 80 s) and a Fleet API line (the kernel's sender: sent, failed, last error and its age), and Attention lists the reason and the fix; typetorch doctor tests the address and token in the settings record.
  • The cloud test sends nothing. typetorch test --cloud boots the payload headless in a Luau Execution task where HttpService works; there the engine (stub kernel test = true, or workspace:GetAttribute("TypeTorchTest")) collects as usual but never uploads: no event rows, no identity rows, no HTTP request, so a prod deploy never puts a fake server session into your analytics.
  • Bounds on what a client can cause: at most 32 experiments per session (each is stamped on every later row), and a client's exp messages count against its event budget (120 a minute, 5,000 a session). Clients can't send purchase or currency rows; the analytics server's ingest also refuses client-marked ones (older engines) and its revenue queries count purchase rows the server sent.
  • Friends in the server (the join's friends): one Players:GetFriendsAsync per join (at most 10 pages, none when the player is alone) intersected with the players there, not a web call per player.

Settings, framework 0.4.0 / kernel 0.4.0 (plans/21): the record's backend = { url, key, analytics?: { flushSeconds, recordShare } } (typetorch backend setup) is the whole sink: DuckDB at <url>/v1/ingest with the one key (Basin identities to <url>/v1/identity). The old analytics value below is read while backend is missing, and stays the way to a Basin sink. The engine also tells the kernel each player's pid (setAnalyticsId: the kernel's error reports count affected players by pid, never by name) and counts its own DataStore and HTTP requests for the budget view (dev menu Server > Budget: bars per Roblox limit for the player count, who spends it, the DataStore budget left, memory).

Settings (server only, never sent to clients): the signed settings record's analytics field (kernel 0.3.8, plans/20), written with typetorch settings set analytics - (JSON on stdin; @typetorch/analytics' writeSettings() and bun run local call it). Every new copy applies live within seconds (the CLI pings servers). Before kernel 0.3.8 there are no settings unless the game passes new AnalyticsEngine({ settings }):

{ "backend": "basin", "events": "https://<stream-id>.ingest.cloudflare.com",
  "recordings": "https://<stream-id>.ingest.cloudflare.com", "token": "<write-only token>",
  "flushSeconds": 15, "recordShare": 1, "techEvery": 60,
  "experiments": { "onboarding": { "weights": [1, 1] } } }
  • basin: a JSON array per stream (events, recordings), Authorization: Bearer <token> when set (a token with Basin Pipelines Send permission, if the stream requires authentication). Without recordings nothing is recorded. The streams' schemas must match SCHEMA.md exactly: Basin drops rows that don't, silently.
  • duckdb: one POST <events> with {"events":[...],"recordings":[...]}, gzip, Authorization: Bearer <token>.
  • The token is write-only and never logged. Needs Allow HTTP Requests (Game Settings > Security). No key: the engine collects but keeps only the newest 1,000 rows until settings appear. Removing the key stops sending, live.

Develop

bun install
bun run build   # rbxtsc --type package -> out/
  • Runtime of the transformer: src/reflection/ (Reflect, Modding, t) is a copy of @typetorch/transformer's runtime-kit/; keep the two identical.

  • Tests (Lune, offline): scripts/test-*.luau; each file's header has its command (Lune is pinned in the kernel's and the template's rokit.toml). scripts/test-generations.luau takes a game's built payload: cd ../template && bun run payload && lune run ../framework/scripts/test-generations.luau build/payload.rbxm boots two generations in one VM and checks fresh registries, DI and generated guards, then runs the real startServer with stub kernels (onStart failures reported to kernel 0.3.2, raised on older ones; onClose), the health lines and the Branch tab / "Load a build" rules (devtools/build-actions.ts). To test framework changes before the template takes them, build the payload from a copy of the template whose node_modules/@typetorch/framework/out is this repo's out/. scripts/test-state-inspect.luau checks the state explorer's core (previews, raw reads only, cycles, paging, Maps/Sets with Instance keys, the depth limit, filters, request validation) and that src/version.ts matches package.json. scripts/test-layout.luau checks the dev menu's pane layout core (devtools/layout.ts: splits and their limits, closing, pop out and dock, singleton pages, ratios, focus, and cleaning a remembered layout). scripts/test-modules.luau runs the real startServer/startClient of out/ (with RuntimeLib, Promise, trove and t from node_modules) over several generations that share a persist store: Dependency<T>(), TypeTorch.module / tryModule and their errors, Lazy<T> (parameters and fields, cycles, start order), network emit and request timeouts and playerState (swaps, leaves). scripts/test-flamework-compat.luau (same harness) drives createFlameworkCompat through each generation's dispatcher: connect (one thread per call, guards, Disconnect, troves), fire / except / broadcast / the call shorthand, setCallback with values and Promises, predict, a swap, and the client side (invoke, invokeWithTimeout, createClient({ defaultTimeout })). scripts/test-analytics.luau checks the analytics engine's pure parts (experiment assignment, settings, the queue and HTTP budget, tt-rec-1, the sink request bodies, the failure help); test-analytics-server.luau and test-analytics-client.luau run the compiled server and client cores against mocked services (sessions, intake, retries, a NetFail streak and its one log line a minute, a swap with a request in flight, shutdown; the recorder, screens, batching). scripts/test-net-health.luau checks the dev menu's Fleet API / Analytics status lines and Attention issues.

  • Publishing: npm publish runs prepublishOnly (clean + build). The package ships only out/ (no .tsbuildinfo), README.md and LICENSE; check with bun pm pack --dry-run.

  • Explorer class icons: assets/class-icons.png (kept locally, not in the repo: it is Roblox's own texture) is the client's content/textures/ClassImages.PNG (a 2352x16 strip) repacked into a 32-column grid, because live clients downscale textures wider than 1024 px: ffmpeg -i ClassImages.PNG -vf "untile=147x1,tile=32x5:color=0x00000000" class-icons.png. It is uploaded as image rbxassetid://97389585475400; scripts/gen-explorer-icons.ts generates the index table.

MIT licensed.