WGSL minifier for WebGPU shaders - WebAssembly build
npm install minirayWGSL minifier for WebGPU shaders - WebAssembly build.
This package provides a WASM build of the miniray that runs in browsers and Node.js.
``bash`
npm install miniray
`html`
`javascript
import { initialize, minify } from 'miniray';
await initialize({ wasmURL: '/path/to/miniray.wasm' });
const result = minify(source, {
minifyWhitespace: true,
minifyIdentifiers: true,
minifySyntax: true,
});
`
`javascript
const { initialize, minify } = require('miniray');
await initialize(); // Automatically finds miniray.wasm
const result = minify(source);
console.log(result.code);
`
Initialize the WASM module. Must be called before minify(), reflect(), or validate().
`typescript`
interface InitializeOptions {
wasmURL?: string | URL; // Path or URL to miniray.wasm
wasmModule?: WebAssembly.Module; // Pre-compiled module
}
Minify WGSL source code.
`typescript
interface MinifyOptions {
minifyWhitespace?: boolean; // Remove whitespace (default: true)
minifyIdentifiers?: boolean; // Rename identifiers (default: true)
minifySyntax?: boolean; // Optimize syntax (default: true)
mangleExternalBindings?: boolean; // Mangle uniform/storage names (default: false)
treeShaking?: boolean; // Remove unused declarations (default: true)
preserveUniformStructTypes?: boolean; // Keep struct types used in uniforms (default: false)
keepNames?: string[]; // Names to preserve from renaming
sourceMap?: boolean; // Generate source map (default: false)
sourceMapSources?: boolean; // Include source in sourcesContent (default: false)
}
interface MinifyResult {
code: string; // Minified code
errors: MinifyError[]; // Parse/minification errors
originalSize: number; // Input size in bytes
minifiedSize: number; // Output size in bytes
sourceMap?: string; // Source map JSON (if sourceMap: true)
}
`
Extract binding information, struct layouts, and entry points from WGSL source.
`typescript
interface ReflectResult {
bindings: BindingInfo[];
structs: Record
entryPoints: EntryPointInfo[];
errors: string[];
}
interface BindingInfo {
group: number;
binding: number;
name: string;
addressSpace: string; // "uniform", "storage", "handle"
accessMode?: string; // "read", "write", "read_write" (for storage)
type: string;
layout: StructLayout | null; // null for textures/samplers
}
interface StructLayout {
size: number;
alignment: number;
fields: FieldInfo[];
}
interface FieldInfo {
name: string;
type: string;
offset: number;
size: number;
alignment: number;
layout?: StructLayout; // for nested structs
}
interface EntryPointInfo {
name: string;
stage: string; // "vertex", "fragment", "compute"
workgroupSize: number[] | null; // [x, y, z] for compute, null otherwise
}
`
Example:
`javascript
const result = reflect(
struct Uniforms { time: f32, resolution: vec2
@group(0) @binding(0) var
@compute @workgroup_size(8, 8) fn main() {});
console.log(result.bindings[0]);
// {
// group: 0, binding: 0, name: "u",
// addressSpace: "uniform", type: "Uniforms",
// layout: {
// size: 16, alignment: 8,
// fields: [
// { name: "time", type: "f32", offset: 0, size: 4, alignment: 4 },
// { name: "resolution", type: "vec2
// ]
// }
// }
console.log(result.entryPoints[0]);
// { name: "main", stage: "compute", workgroupSize: [8, 8, 1] }
`
Memory layouts follow the WGSL specification:
- vec3 has alignment=16 but size=12
- Struct members are aligned to their natural alignment
- Struct size is rounded up to struct alignment
Validate WGSL source for semantic errors, type mismatches, and uniformity violations.
`typescript
interface ValidateOptions {
strictMode?: boolean; // Treat warnings as errors
diagnosticFilters?: Record
}
interface ValidateResult {
valid: boolean; // true if no errors
diagnostics: DiagnosticInfo[];
errorCount: number;
warningCount: number;
}
interface DiagnosticInfo {
severity: 'error' | 'warning' | 'info' | 'note';
code?: string; // e.g., "E0200"
message: string;
line: number; // 1-based
column: number; // 1-based
endLine?: number;
endColumn?: number;
specRef?: string; // WGSL spec reference
}
`
Example:
`javascript
const result = validate(
fn foo() -> f32 {
var x: i32 = 1;
return x; // Error: returning i32 from f32 function
});
console.log(result.valid); // false
console.log(result.errorCount); // 1
console.log(result.diagnostics[0]);
// {
// severity: "error",
// code: "E0200",
// message: "cannot return 'i32' from function returning 'f32'",
// line: 4,
// column: 5
// }
`
With options:
`javascript`
const result = validate(source, {
strictMode: true, // Treat warnings as errors
diagnosticFilters: {
derivative_uniformity: 'off', // Disable uniformity warnings
},
});
Validation checks:
- Type mismatches (assignments, returns, function calls)
- Undefined symbols (variables, functions, types)
- Invalid operations (operators, indexing, member access)
- Entry point requirements
- Uniformity analysis (textureSample, derivatives)
- WGSL spec compliance
Returns true if the WASM module is initialized.
The version of the minifier.
Remove unnecessary whitespace and newlines.
Rename local variables, function parameters, and helper functions to shorter names. Entry points and API-facing declarations are preserved.
Apply syntax-level optimizations like numeric literal shortening.
Control how var and var names are handled:
- false (default): Original names are preserved in declarations, short aliases are used internally. This maintains compatibility with WebGPU's binding reflection APIs.true
- : Names are mangled directly for smaller output, but breaks binding reflection.
`javascript
// Input
const shader =
@group(0) @binding(0) var
fn getValue() -> f32 { return uniforms * 2.0; };
// With mangleExternalBindings: false (default)
// Output: "@group(0) @binding(0) var
// With mangleExternalBindings: true
// Output: "@group(0) @binding(0) var
`
Enable dead code elimination to remove unused declarations (default: true):
`javascript`
minify(source, {
treeShaking: true, // Remove unreachable code
});
Automatically preserve struct type names that are used in var or var declarations (default: false):
`javascript
// Input
const shader =
struct MyUniforms { time: f32 }
@group(0) @binding(0) var
@fragment fn main() -> @location(0) vec4f { return vec4f(u.time); };
// With preserveUniformStructTypes: false (default)
// struct MyUniforms -> struct a
// With preserveUniformStructTypes: true
// struct MyUniforms preserved
minify(source, {
preserveUniformStructTypes: true,
});
`
This is particularly useful for frameworks like PNGine that detect builtin uniforms by struct type name.
Array of identifier names that should not be renamed:
`javascript`
minify(source, {
minifyIdentifiers: true,
keepNames: ['myHelper', 'computeValue'],
});
Generate a source map to debug minified shaders by mapping back to original source:
`javascript
const result = minify(source, {
minifyIdentifiers: true,
sourceMap: true,
});
console.log(result.code);
// "const a=42;fn b()->i32{return a;}"
console.log(result.sourceMap);
// '{"version":3,"sources":[],"names":["longVariable","myFunction"],"mappings":"MAAAA,..."}'
`
The source map follows the Source Map v3 specification and includes:
- version: Always 3names
- : Original names of renamed identifiersmappings
- : VLQ-encoded position mappings
Include the original source code in the source map's sourcesContent field for self-contained debugging:
`javascript
const result = minify(source, {
sourceMap: true,
sourceMapSources: true, // Embed original source
});
const map = JSON.parse(result.sourceMap);
console.log(map.sourcesContent);
// ["const longVariable = 42;\nfn myFunction() -> i32 { return longVariable; }"]
`
`javascript
import { initialize, minify } from 'miniray';
await initialize({ wasmURL: '/miniray.wasm' });
const source =
const longVariableName = 42;
fn helperFunction(value: i32) -> i32 {
return value * 2;
}
@compute @workgroup_size(1)
fn main() {
let result = helperFunction(longVariableName);
};
const result = minify(source, {
minifyWhitespace: true,
minifyIdentifiers: true,
sourceMap: true,
sourceMapSources: true,
});
console.log('Minified code:');
console.log(result.code);
// "const a=42;fn b(c:i32)->i32{return c*2;}@compute @workgroup_size(1) fn main(){let d=b(a);}"
console.log('\nSource map:');
const map = JSON.parse(result.sourceMap);
console.log('Names:', map.names);
// Names: ["longVariableName", "helperFunction", "value", "result"]
// To use the source map inline:
const codeWithSourceMap = result.code +
'\n//# sourceMappingURL=data:application/json;base64,' +
btoa(result.sourceMap);
`
`javascript
import { initialize, minify } from 'miniray';
import wasmURL from 'miniray/miniray.wasm?url';
await initialize({ wasmURL });
`
`javascript
import { initialize, minify } from 'miniray';
// Configure webpack to handle .wasm files
await initialize({ wasmURL: new URL('miniray/miniray.wasm', import.meta.url) });
`
For better performance when creating multiple instances:
`javascript
const wasmModule = await WebAssembly.compileStreaming(
fetch('/miniray.wasm')
);
// Share module across workers
await initialize({ wasmModule });
``
- WASM binary: ~3.6MB
- Initialization: ~100ms (first load)
- Transform: <1ms for typical shaders
MIT