Skip to content

TypeGPU (TypeScript → WGSL) ​

A WebGPU toolkit from Software Mansion in which buffer layouts, bind groups and shader functions are TypeScript values: schemas derive the WGSL memory layout and the byte-level serializers, and a function marked 'use gpu' is both a plain JavaScript function and the source of generated WGSL.

FieldValue
LanguageTypeScript / JavaScript (host and shader), WGSL (generated, or hand-written in template strings)
LicenseMIT (license field of packages/typegpu/package.json)
Repositorysoftware-mansion/TypeGPU
Documentationdocs.swmansion.com/TypeGPU
CategorySingle-source peer: embedded DSL with a build-time AST capture and a runtime code generator
Latest versiontypegpu 0.12.8, tag v0.12.8 = pinned commit 3e1efd44, 2026-10-16 (package.json); 0.12 announced 2026-08-12 (release post)
TargetsWGSL for WebGPU (browsers, Dawn/wgpu-backed runtimes, React Native); GLSL ES 3.00 for WebGL 2 through the experimental @typegpu/gl package (docs)
Build pluginunplugin-typegpu (Vite, webpack, Rollup, Rolldown, esbuild, Rspack, Farm, Bun, Babel)
Pinned sourcesoftware-mansion/TypeGPU at 3e1efd4437f55fb8ddac9c5bbc968a8eaa7fc8bf

Overview ​

What it solves ​

WebGPU programs share data with WGSL through raw bytes, and every struct must be padded to WGSL's alignment rules on both sides. TypeGPU's answer is to make the schema the single source of truth. The data-schema guide states the problem directly (apis/data-schemas.mdx):

"Any misalignments or misinterpretations of data can lead to faulty code that is difficult to debug. This is precisely what TypeGPU data schemas, like d.u32 or d.vec3f, help with."

The same schema object types a buffer (root.createBuffer(Schema)), types a bind-group entry ({ uniform: Schema }), constructs host values (Schema({ … })), and resolves to a WGSL struct. On top of that, shader functions are written in TypeScript and can be called on the CPU, emitted as WGSL, or dispatched on the GPU from the same definition.

Design philosophy ​

Three commitments recur through the source and docs:

  1. Mirror WGSL, do not abstract over it. The README says "The low-level nature of TypeGPU and it's mirroring of WGSL (WebGPU Shading Language) syntax in TypeScript means that learning TypeGPU helps to learn WebGPU itself", and that one can "granularly eject into vanilla WebGPU at any point" (README.md). Every abstraction has a WGSL escape hatch.
  2. Shaders written in JavaScript, not arbitrary JavaScript on the GPU. The functions guide: "Our aim with TypeGPU functions is not to allow arbitrary JavaScript to be supported in the context of shaders, rather to allow for shaders to be written in JavaScript" (apis/functions/index.mdx).
  3. CPU/GPU behavioural parity is a goal of the standard library. "Our goal is for all functions to have matching behavior on the CPU and GPU, which unlocks many possibilities (shader unit testing, shared business logic, and more...)" (apis/functions/index.mdx).

TypeScript types take no part in code generation: "TypeScript's types take no part in WGSL generation. TypeGPU works just as well in plain JavaScript" (advanced/explaining-the-magic.mdx). WGSL types are inferred by the generator from the runtime values and schemas at each call site.

How it works ​

The pipeline has two halves, split between build time and run time.

Build time — unplugin-typegpu. The plugin walks each bundled file and rewrites three things (explaining-the-magic.mdx):

  • auto-naming: const counter = root.createMutable(d.vec2u) is wrapped in globalThis.__TYPEGPU_AUTONAME__(…, "counter"), so generated identifiers follow source names;
  • function metadata: every function whose body starts with 'use gpu' (or that is passed directly to a tgpu.fn shell) is parsed by tinyest-for-wgsl into a compact array-encoded AST, the tinyest format, and attached to the function object in a globalThis.__TYPEGPU_META__ WeakMap together with an externals record of thunks for every captured outer-scope name;
  • operator overloading: +, *, … inside 'use gpu' bodies become __tsover_add-style calls so that vector arithmetic also works when the function runs as JavaScript. The AST keeps the original operators.

The doc shows the injected shape:

ts
// unplugin output (abridged), explaining-the-magic.mdx
(($.f = () => {
  'use gpu';
  counter.$ = __tsover_add(counter.$, incrementBy.allModifier.$);
}),
  {
    v: 2,
    ast: {
      params: [],
      body: [
        0,
        [[2, [7, 'counter', '$'], '+=', [7, 'incrementBy.allModifier', '$']]],
      ],
    },
    externals: {
      counter: () => counter,
      'incrementBy.allModifier': () => incrementBy.allModifier,
    },
  });

tinyest encodes nodes as tuples tagged by small integers from NodeTypeCatalog (block: 0, binaryExpr: 1, … forOf: 18, switch: 19; nodes.ts). The externals are thunks, not values, because a resource may be reassigned after the function is defined and because a resource's .$ getter returns a different object while resolving.

Run time — resolution. tgpu.resolve([items]) is described as "essentially a dedicated TypeGPU linker" (apis/resolve.mdx). A ResolutionCtxImpl (resolutionCtx.ts) walks the item graph: each resolvable object implements a $resolve symbol, functions are emitted by the WgslGenerator (wgslGenerator.ts) walking the tinyest AST, and every external the generator touches pulls its own definition (struct, @group/@binding variable, helper fn) into the output exactly once. A Namespace (namespace.ts) owns the global identifier set (pre-seeded with WGSL keywords, builtins and template enumerants), memoizes resolutions per slot-binding map, and offers 'strict' or 'random' naming.

Execution model and stages ​

Entry points are built by dedicated shell constructors rather than attributes: tgpu.computeFn({ workgroupSize, in }), tgpu.vertexFn({ in, out }) and tgpu.fragmentFn({ in, out }) (tgpu.ts; tgpuComputeFn.ts, tgpuVertexFn.ts, tgpuFragmentFn.ts). Stage I/O is an IORecord — a plain object mapping names to schemas or to d.builtin.* markers — from which the generator synthesizes the …_Input/…_Output structs, assigns @location indices automatically (overridable with d.location) and, for shell-less render pipelines, adds @interpolate(flat) to integer varyings. The builtin set is WGSL's: compute IDs and subgroup IDs, vertexIndex/instanceIndex, position, frontFacing, sampleIndex/sampleMask, fragDepth, clipDistances (apis/functions/index.mdx).

The stage set is exactly WebGPU's: compute, vertex, fragment. There is no geometry, tessellation, mesh or ray-tracing stage because WGSL has none. createGuardedComputePipeline(callback) is a convenience that wraps a 0–3 argument callback in a compute entry with a fixed workgroup size and a bounds check against a vec3u size uniform, so the user dispatches threads rather than workgroups (init.ts).

Type system and generic programming ​

Schemas are the type system. d.f32, d.i32, d.u32, d.f16, d.bool, d.vec{2,3,4}{f,i,u,h,b}, d.mat2x2f/mat3x3f/mat4x4f, d.struct, d.arrayOf, d.atomic, pointer schemas and the texture/sampler schemas are callable objects (data/). Calling a scalar schema casts with WGSL semantics on the CPU (d.u32(-1) is 4294967295); calling a struct schema builds a value; d.Infer<typeof S> yields the host TypeScript type. Matrices are limited to the three square f32 shapes, and f16 matrices are not supported (data-schemas.mdx).

Polymorphism by call-site specialization. An unshelled 'use gpu' function is generic: the generator infers argument types at each call and emits one WGSL function per distinct signature (neighborhood, neighborhood2, …); return types that cannot be unified are an error (apis/functions/index.mdx; shellless.ts). A tgpu.fn([argSchemas], returnSchema) shell pins the signature instead.

Numeric literal typing is a value heuristic. Because JavaScript has one number, integer-valued literals become i32 and others f32 (1.0 → 1i); the docs ask users to wrap literals in schemas, and the generator wraps every / in an f32 cast so JS and GPU agree. The ESLint plugin ships rules for exactly these hazards (noIntegerDivision, noMath, noUninitializedVariables, eslint-plugin/src/rules/).

Compile-time generic programming is runtime JavaScript. Four mechanisms substitute for templates:

MechanismWhat it is
tgpu.slot<T>(default?)A typed hole filled before shader compilation via .with(slot, value) on a function, root or pipeline; any JS value, even a function (slots.mdx)
tgpu.accessor(schema)A slot constrained to a schema, filled by any value or resource of that type — buffer, variable, constant, function (accessors.mdx)
tgpu.lazy(() => …)A value computed during resolution, memoized per slot-binding map; derived is its deprecated alias (lazy.ts, tgpuUnstable.ts)
tgpu.comptime(fn) / tgpu.unrollRun arbitrary JS at shader-generation time and inject the result; mark a for…of for unrolling (comptime.ts, tgpuUnroll.ts)

Captured outer-scope values are inlined as constants and constant-folded (std.mix(from, to, 0.5) becomes vec3f(0.5, 0.5, 0)), and the docs warn that such values "are assumed to be constant": mutating them later does not recompile the shader (apis/functions/index.mdx).

Resources, interfaces and memory layout ​

Layout derivation. alignmentOf uses a fixed table for WGSL's built-in types (vec3f: 16, vec2h: 4, mat3x3f: 16, bool: 4) and computes structs as the maximum member alignment and arrays as the element alignment (alignmentOf.ts); sizeOf/offsets complete the picture, and d.align(n, T) / d.size(n, T) mirror WGSL's @align/@size (padding before, padding after). Structs are laid out once, by WGSL's storage rules.

Uniform-buffer rules are warnings, not a second layout. WGSL's uniform address space adds 16-byte constraints on array strides and struct alignment. TypeGPU checks them in warnIfNotUniformAligned and logs a uniform-schema-misaligned warning that suggests the exact d.align/d.size fix, citing the WGSL spec section (webgpuLimitations.ts). It does not silently re-layout the struct for uniforms.

Packed vertex data. d.unstruct and d.disarray describe loose layouts with no implicit padding — vertex formats such as unorm8x4 — distinct from WGSL-host-shareable structs (unstruct.ts).

Serialization. compiledIO.ts JIT-compiles a per-schema writer (new Function(…) over a DataView) and caches it in a WeakMap; where eval is forbidden (EVAL_ALLOWED_IN_ENV), it falls back to an interpreted writer with a one-time warning (compiledIO.ts).

Bindings. tgpu.bindGroupLayout({ name: { uniform: S } | { storage: S, access } | { texture: d.texture2d(d.f32) } | { sampler } | … }) assigns binding indices by property order; root.createBindGroup(layout, {…}) validates the resources against it (bind-groups.mdx; tgpuBindGroupLayout.ts). Alternatively, fixed resources referenced directly inside a shader (root.createUniform, root.createMutable, createReadonly) are given automatic @group/@binding slots during resolution, as the resolved pipelines in the docs show. tgpu.privateVar and tgpu.workgroupVar declare module-scope var<private> / var<workgroup> (tgpuVariable.ts).

Built-in library and intrinsics ​

typegpu/std (std/) covers WGSL's builtin functions: numeric (abs, mix, clamp, fma, …), boolean and comparison (eq, lt, all, any, select), matrix, packing, bitcast, texture (textureSample, textureStore, …), derivatives, atomics and barriers, subgroups, discard, and range/array helpers. Vector arithmetic is available as std.add etc., as fluent methods (v.mul(w)), or as operators via tsover.

Each builtin is a dual implementation built by dualImpl (dualImpl.ts): a normalImpl (JS, used on the CPU), a codegenImpl (WGSL text), a signature that converts arguments, and a sideEffects flag. When every argument is known at generation time, the generator calls normalImpl and emits the constant — so the CPU twin is the constant folder. A builtin whose normalImpl is a string throws MissingCpuImplError on the CPU:

ts
// std/derivative.ts
export const dpdx = dualImpl<DerivativeSignature>({
  name: 'dpdx',
  normalImpl: 'Derivative builtins are not allowed on the CPU',
  signature: derivativeSignature,
  codegenImpl: (ctx, [value]) => ctx.gen.emitCall('dpdx', [], [value]),
  sideEffects: false,
});

The same is true of workgroupBarrier, storageBarrier, all atomic* operations (atomic.ts), every subgroup operation (subgroup.ts) and discard (discard.ts). Everything that needs more than one invocation has no CPU semantics.

Shells also accept WGSL bodies as tagged templates, with dependencies injected through $uses:

ts
const getGradientColor = tgpu.fn([d.f32], d.vec4f)`(ratio) {
  return mix(purple, get_blue(), ratio);
}`.$uses({ purple, get_blue: getBlue });

Resolution renames get_blue to the callee's final identifier and inlines purple as a literal (apis/functions/index.mdx). JS and WGSL functions can call each other freely; tgpu.resolve({ template, externals }) extends an existing WGSL file the same way (resolve.mdx).

Control flow, memory model and restrictions ​

Supported syntax is what tinyest encodes: blocks, if, for, while, for…of (over arrays, std.range, or tgpu.unroll), switch, break, continue, return, let/const, the conditional operator, object and array literals (lowered to struct and array constructors) (nodes.ts). Calls are allowed only to 'use gpu' functions, std, most Math.* (mapped to std), schemas and console.log, which is implemented by serializing arguments into a GPU buffer and decoding them on the host (tgsl/consoleLog/). WGSL's restrictions (no recursion, no undefined/null, uniform-control-flow requirements for barriers and derivatives) are inherited and checked by the WebGPU implementation's WGSL compiler, not by TypeGPU; the data-schema guide warns that relying on undefined from an out-of-range read is "undefined behavior in WGSL" (data-schemas.mdx).

The memory model is WGSL's, unmodified: address spaces function, private, workgroup, uniform, storage, handle; atomics on i32/u32; barriers as above. TypeGPU models pointers in the generator (d.ptrFn/d.ptrPrivate/d.ptrWorkgroup, ptr.ts; implicit-pointer dereferencing in dualImpl), while JavaScript itself has value semantics for numbers and reference semantics for objects. The ESLint rule noInvalidAssignment ("Disallow assignments that will generate invalid WGSL") rejects the two assignments whose JS meaning has no WGSL counterpart: to an immutable WGSL parameter, and to a captured outer-scope JS variable (noInvalidAssignment.ts).

Compilation pipeline and targets ​

text
TS source ──unplugin (build)──▶ JS + __TYPEGPU_META__ {tinyest AST, externals thunks}
                                   │
                       tgpu.resolve / pipeline creation (run time, in the app)
                                   ▼
             ResolutionCtx + WgslGenerator ──▶ WGSL text ──▶ GPUDevice.createShaderModule
                                   └── @typegpu/gl GlslGenerator ──▶ GLSL ES 3.00 (WebGL 2)

Code generation happens in the application at run time, lazily, the first time a pipeline is created or drawn (resolve.mdx). The docs suggest combining unplugin-macros with tgpu.resolve to precompute variants at build time. The generator sits behind a ShaderGenerator interface (shaderGenerator.ts) with FunctionDefinitionOptions, VariableDefinitionOptions and statement-level control-flow facts (endsWithControlFlow); @typegpu/gl implements it as glslGenerator.ts (typegpu-gl/src/) for a vertex/fragment subset without compute, storage buffers or bind groups (typegpu-gl docs). There is no SPIR-V, DXIL or MSL output; the browser's WebGPU implementation (Tint in Chromium, naga in Firefox) performs that translation. A minifier (minify.ts) shortens production WGSL.

Host integration and CPU execution ​

Host integration is the library's centre: tgpu.init() returns a root that creates typed buffers (write/read serialize through the schema), textures, samplers, bind groups and pipelines, and root.unwrap(x) exposes the raw WebGPU object at any point (init.ts). Pipelines carry their slot bindings (root.with(slot, v).createComputePipeline(…)).

CPU execution has three levels, none of them a parallel simulator:

  1. Direct calls. A 'use gpu' function is ordinary JavaScript; calling it runs the tsover-rewritten body with std's normalImpls. This is the basis of the "shader unit testing" claim.
  2. Generation-time evaluation. dualImpl, tgpu.comptime and tgpu.lazy run JS during resolution to fold constants.
  3. tgpu['~unstable'].simulate(callback). Runs a callback with access to buffers, privateVars and workgroupVars "as if it were running on the GPU", returning the final values without touching GPU state. The implementation allocates per-thread and per-workgroup variable maps over a 3-D grid but is "Statically locked to one "thread" for now" (workgroups = [1,1,1], workgroupSize = [1,1,1]) (tgpuSimulate.ts).

Because barriers, atomics, subgroup operations and derivatives all throw MissingCpuImplError on the CPU, the CPU path validates only single-invocation arithmetic. JavaScript's number is an f64, so f32/f16 rounding is not reproduced unless a schema cast is applied; the docs note that "the type of any number remains a number regardless of casts" (data-schemas.mdx).

Lessons for sparkles:shaders ​

  • Adopt: one layout description drives host serialization, the device struct and validation. TypeGPU's schema computes alignmentOf/sizeOf once and reuses it for writers, WGSL structs and uniform-rule warnings. In D, the struct type is the schema: a static assert-backed layoutOf!(T, Std140) / layoutOf!(T, Std430) / layoutOf!(T, Scalar) at compile time can generate the padded device struct and a host writeTo(ref Buffer) from the same declaration — at zero run-time cost, which TypeGPU pays for with new Function JIT.
  • Match: a WGSL-uniform-rules check that names the fix. The uniform-schema-misaligned message ("wrap the property in d.align(16, …)") is the right diagnostic shape for sparkles' std140/WGSL-uniform targets; in D it should be a compile-time error per target dialect, not a log line.
  • Adopt: every built-in is a dual implementation with an explicit "no CPU semantics" state. dualImpl's normalImpl/codegenImpl/ sideEffects triple maps directly onto sparkles' SHV7 CPU twin requirement (SPEC); make the "unavailable on the CPU" case a typed, compile-time-visible property of the intrinsic, not a thrown string.
  • Avoid: inferring numeric types from literal values. 1.0 → i32 and the blanket f32 cast on / are workarounds for JavaScript's single number. D has float, int, uint, half-as-a-type questions answered by the language; keep D's static types authoritative.
  • Take, but statically: slots, accessors, lazy, comptime. These are TypeGPU's templates, CTFE and dependency injection, all resolved at shader generation. D's template parameters, alias parameters and CTFE do the same at compile time with type checking; the accessor idea — "any resource of this element type" — is worth keeping as a D concept constraint over uniform/storage/constant/push-constant sources.
  • Avoid: a CPU path that is single-invocation only. simulate is pinned to one thread, and barriers/atomics/subgroups throw. sparkles' planned simulator should treat workgroups, barriers and subgroup operations as the core of the CPU model (see ILGPU), not an afterthought.
  • Match: an escape hatch to raw target code at function granularity. TypeGPU's WGSL template bodies with $uses renaming are what lets it trail WGSL features without blocking users; sparkles needs the equivalent for SPIR-V intrinsics not yet in the vocabulary (pragma(LDC_intrinsic, …) today, see dcompute).
  • Avoid: run-time code generation as the only mode. TypeGPU resolves in the application; sparkles generates offline and validates with spirv-val in the build step, which is strictly stronger evidence. Keep it.

Strengths ​

  • One schema object types buffers, bind groups, host values and WGSL structs; layout bugs between host and shader are structurally excluded.
  • Seamless mixing of TypeScript and WGSL at function granularity, with a linker (tgpu.resolve) that deduplicates and names dependencies.
  • Expressive generation-time metaprogramming (slots, accessors, lazy, comptime, unroll) that libraries use for inversion of control.
  • Constant folding reuses the CPU implementations, so the CPU twin is exercised on every resolution.
  • Works in plain JavaScript; the build plugin covers nine bundlers.

Weaknesses ​

  • WGSL-only semantics: WebGPU's three stages and WGSL's feature set are the ceiling; the GLSL backend is an experimental subset.
  • Type inference from runtime values: integer-vs-float literal heuristics, f64 arithmetic on the CPU, and value/reference divergence between JS and WGSL need lint rules to contain.
  • The CPU path cannot execute barriers, atomics, subgroup operations or derivatives, and simulate runs one invocation.
  • Errors surface at run time (resolution or createShaderModule), not at build time; unfilled slots are a runtime error (slots.mdx).
  • Depends on a build-time AST transform; without the plugin only WGSL template functions work.

Key design decisions and trade-offs ​

DecisionRationaleTrade-off
Schemas as runtime values (Zod-style)One object drives types, layout, serialization and WGSLLayout is computed and JIT-compiled at run time; eval-free environments get a slow path
Capture the AST at build time (tinyest), generate at run timeNo JS parser shipped; externals captured precisely; values known at generation are foldedRequires a bundler plugin; shader errors appear when the app runs
Ignore TypeScript types; infer WGSL types per callWorks in JS; generic functions specialize for freeLiteral-value type heuristics; types can differ between CPU run and GPU run
dualImpl for every builtinCPU parity, constant folding and codegen from one definitionMulti-invocation builtins have no CPU meaning and throw
Slots/accessors/lazy instead of language genericsDependency injection across packages; any JS value can parameterize a shaderUnchecked until resolution; resolution is memoized per slot map to stay affordable
WGSL template strings as a first-class body formNever blocked on unsupported features; easy migration from WGSLTwo languages per project; WGSL bodies have no CPU implementation
Uniform rules as warningsOne layout for all address spaces, as in WGSLA misaligned uniform still ships unless the user reads the log

Sources ​