Using LUMOS with npm
Use LUMOS in your JavaScript/TypeScript projects without installing Rust. The @getlumos/cli npm package provides the full LUMOS functionality via WebAssembly.
Why Use the npm Package?
Section titled “Why Use the npm Package?”- ✅ No Rust Toolchain Required - Works with Node.js only
- ✅ Cross-Platform - Single package for all platforms
- ✅ Programmatic API - Use LUMOS in build scripts
- ✅ TypeScript Support - Full type definitions included
- ✅ Lightweight - 261 KB compressed (~750 KB unpacked)
Installation
Section titled “Installation”Global Installation
Section titled “Global Installation”Install globally to use the lumos command everywhere:
npm install -g @getlumos/cli# oryarn global add @getlumos/cli# orpnpm add -g @getlumos/cliVerify installation:
lumos --version# Output: 0.1.0Project Installation
Section titled “Project Installation”Install as a dev dependency in your project:
npm install --save-dev @getlumos/cli# oryarn add --dev @getlumos/cli# orpnpm add -D @getlumos/cliNo Installation (npx)
Section titled “No Installation (npx)”Run directly without installing:
npx @getlumos/cli generate schema.lumosCLI Usage
Section titled “CLI Usage”The npm package provides the same CLI commands as the Rust version.
Generate Code
Section titled “Generate Code”# Basic usagelumos generate schema.lumos
# With custom output pathslumos generate schema.lumos \\ --output-rust src/generated.rs \\ --output-typescript src/generated.ts
# Using npxnpx @getlumos/cli generate schema.lumosValidate Schema
Section titled “Validate Schema”lumos validate schema.lumos# Output: ✓ Schema is validAdd to package.json Scripts
Section titled “Add to package.json Scripts”{ "scripts": { "codegen": "lumos generate schema.lumos", "validate": "lumos validate schema.lumos", "prebuild": "npm run codegen" }}Then run:
npm run codegenProgrammatic API
Section titled “Programmatic API”Use LUMOS in your JavaScript/TypeScript code.
Generate Code
Section titled “Generate Code”import { generate } from '@getlumos/cli';
const result = await generate('schema.lumos', { outputRust: 'src/generated.rs', outputTypeScript: 'src/generated.ts'});
console.log('Generated Rust code:', result.rust);console.log('Generated TypeScript code:', result.typescript);API Signature:
function generate( schemaPath: string, options?: { outputRust?: string; outputTypeScript?: string; }): Promise<{ rust: string; typescript: string;}>;Validate Schema
Section titled “Validate Schema”import { validate } from '@getlumos/cli';
const result = await validate('schema.lumos');
if (result.valid) { console.log('✓ Schema is valid');} else { console.error('✗ Schema validation failed'); console.error(result.errors); process.exit(1);}API Signature:
function validate(schemaPath: string): Promise<{ valid: boolean; errors?: string[];}>;Error Handling
Section titled “Error Handling”import { generate } from '@getlumos/cli';
try { await generate('schema.lumos');} catch (error) { if (error instanceof Error) { console.error('Generation failed:', error.message); } process.exit(1);}Build Tool Integration
Section titled “Build Tool Integration”Create a Vite plugin for automatic code generation:
import { Plugin } from 'vite';import { generate } from '@getlumos/cli';import { watch } from 'fs';
export function lumosPlugin(schemaPath: string): Plugin { return { name: 'vite-plugin-lumos',
async buildStart() { // Generate on build start await generate(schemaPath); },
configureServer(server) { // Watch schema file for changes watch(schemaPath, async () => { await generate(schemaPath); server.ws.send({ type: 'full-reload' }); }); } };}Usage in vite.config.ts:
import { defineConfig } from 'vite';import { lumosPlugin } from './vite-plugin-lumos';
export default defineConfig({ plugins: [ lumosPlugin('schema.lumos') ]});Webpack
Section titled “Webpack”Create a Webpack plugin:
const { generate } = require('@getlumos/cli');
class LumosPlugin { constructor(schemaPath) { this.schemaPath = schemaPath; }
apply(compiler) { compiler.hooks.beforeCompile.tapPromise('LumosPlugin', async () => { await generate(this.schemaPath); }); }}
module.exports = LumosPlugin;Usage in webpack.config.js:
const LumosPlugin = require('./webpack-plugin-lumos');
module.exports = { plugins: [ new LumosPlugin('schema.lumos') ]};Rollup
Section titled “Rollup”import { generate } from '@getlumos/cli';
export default { input: 'src/index.ts', plugins: [ { name: 'lumos', async buildStart() { await generate('schema.lumos'); } } ]};esbuild
Section titled “esbuild”import { build } from 'esbuild';import { generate } from '@getlumos/cli';
// Generate before buildingawait generate('schema.lumos');
await build({ entryPoints: ['src/index.ts'], bundle: true, outfile: 'dist/index.js'});CI/CD Integration
Section titled “CI/CD Integration”GitHub Actions
Section titled “GitHub Actions”name: Generate LUMOS Code
on: [push, pull_request]
jobs: generate: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4
- uses: actions/setup-node@v4 with: node-version: '20'
- name: Install dependencies run: npm install
- name: Generate LUMOS code run: npx @getlumos/cli generate schema.lumos
- name: Validate generated files run: | git diff --exit-code generated.rs generated.ts || \\ (echo "Generated files are outdated!" && exit 1)GitLab CI
Section titled “GitLab CI”generate-code: image: node:20 script: - npm install - npx @getlumos/cli generate schema.lumos - git diff --exit-code generated.rs generated.ts only: - merge_requests - mainCircleCI
Section titled “CircleCI”version: 2.1
jobs: generate: docker: - image: cimg/node:20.0 steps: - checkout - run: npm install - run: npx @getlumos/cli generate schema.lumos - run: git diff --exit-code
workflows: validate: jobs: - generateWatch Mode (Custom Implementation)
Section titled “Watch Mode (Custom Implementation)”The npm package doesn’t have built-in watch mode, but you can create one:
import { watch } from 'fs';import { generate } from '@getlumos/cli';
const schemaPath = 'schema.lumos';
console.log(`👀 Watching ${schemaPath}...`);
watch(schemaPath, async (eventType) => { if (eventType === 'change') { console.log('🔄 Schema changed, regenerating...'); try { await generate(schemaPath); console.log('✓ Code regenerated'); } catch (error) { console.error('✗ Generation failed:', error.message); } }});Run with:
node watch.jsOr use nodemon:
npm install --save-dev nodemon
# package.json{ "scripts": { "watch": "nodemon --watch schema.lumos --exec 'npm run codegen'" }}Monorepo Usage
Section titled “Monorepo Usage”Nx Workspace
Section titled “Nx Workspace”{ "targets": { "codegen": { "executor": "nx:run-commands", "options": { "command": "lumos generate schema.lumos", "cwd": "apps/my-app" } }, "build": { "dependsOn": ["codegen"] } }}Turborepo
Section titled “Turborepo”{ "pipeline": { "codegen": { "outputs": ["generated.rs", "generated.ts"] }, "build": { "dependsOn": ["codegen"] } }}TypeScript Configuration
Section titled “TypeScript Configuration”Type Definitions
Section titled “Type Definitions”The package includes full TypeScript type definitions:
import type { GenerateOptions, GeneratedCode, ValidationResult } from '@getlumos/cli';
const options: GenerateOptions = { outputRust: 'src/generated.rs', outputTypeScript: 'src/generated.ts'};
const result: GeneratedCode = await generate('schema.lumos', options);const validation: ValidationResult = await validate('schema.lumos');tsconfig.json
Section titled “tsconfig.json”Ensure proper module resolution:
{ "compilerOptions": { "moduleResolution": "node", "esModuleInterop": true, "types": ["node"] }}Comparison: npm vs Rust CLI
Section titled “Comparison: npm vs Rust CLI”| Feature | npm (@getlumos/cli) | Rust (lumos-cli) |
|---|---|---|
| Installation | npm install -g | cargo install |
| Requirements | Node.js 16+ | Rust toolchain |
| Size | 261 KB (compressed) | ~10 MB (native binary) |
| Speed | WASM (~10-20% slower) | Native (fastest) |
| Platform | Cross-platform (single package) | Platform-specific binaries |
| Programmatic API | ✅ JavaScript/TypeScript | ❌ Rust only |
| CLI Commands | ✅ All commands | ✅ All commands |
| Watch Mode | ❌ Custom implementation | ❌ Not yet |
| LSP Support | ❌ Use Rust LSP | ✅ Via lumos-lsp |
Choose npm if:
- You don’t have Rust installed
- You want programmatic API access
- You’re building JavaScript/TypeScript projects
- You need cross-platform compatibility
Choose Rust if:
- You want maximum performance
- You’re building Rust/Anchor projects
- You need LSP integration
- You prefer native binaries
Troubleshooting
Section titled “Troubleshooting”WASM Initialization Error
Section titled “WASM Initialization Error”Error:
Failed to load LUMOS WASM moduleFix: Ensure you’re using Node.js 16 or higher:
node --version # Should be >= 16.0.0Module Not Found
Section titled “Module Not Found”Error:
Cannot find module '@getlumos/cli'Fix: Reinstall the package:
npm install --save-dev @getlumos/cliPermission Denied
Section titled “Permission Denied”Error:
EACCES: permission deniedFix:
Use npx instead of global install, or fix npm permissions:
npx @getlumos/cli generate schema.lumosGenerated Files Missing
Section titled “Generated Files Missing”Error:
Cannot write to file: generated.rsFix: Ensure output directory exists and is writable:
mkdir -p src/generatedlumos generate schema.lumos --output-rust src/generated/types.rsPerformance Tips
Section titled “Performance Tips”Cache Generated Files
Section titled “Cache Generated Files”Add to .gitignore if regenerating in CI:
generated.rsgenerated.tsUse npx for CI
Section titled “Use npx for CI”Avoid installing globally in CI:
npx @getlumos/cli generate schema.lumosParallel Generation
Section titled “Parallel Generation”Generate multiple schemas in parallel:
import { generate } from '@getlumos/cli';
await Promise.all([ generate('schemas/accounts.lumos'), generate('schemas/instructions.lumos'), generate('schemas/events.lumos')]);Examples
Section titled “Examples”Basic Node.js Script
Section titled “Basic Node.js Script”import { generate, validate } from '@getlumos/cli';
async function main() { // Validate first const validation = await validate('schema.lumos'); if (!validation.valid) { console.error('Schema validation failed'); process.exit(1); }
// Generate await generate('schema.lumos', { outputRust: 'src/generated.rs', outputTypeScript: 'src/types.ts' });
console.log('✓ Code generated successfully');}
main().catch(console.error);Pre-build Hook
Section titled “Pre-build Hook”{ "scripts": { "prebuild": "node codegen.js", "build": "tsc" }}Multi-Schema Generation
Section titled “Multi-Schema Generation”import { generate } from '@getlumos/cli';import { readdirSync } from 'fs';import { join } from 'path';
const schemasDir = './schemas';const schemas = readdirSync(schemasDir) .filter(file => file.endsWith('.lumos'));
for (const schema of schemas) { const schemaPath = join(schemasDir, schema); const name = schema.replace('.lumos', '');
await generate(schemaPath, { outputRust: `src/generated/${name}.rs`, outputTypeScript: `src/types/${name}.ts` });
console.log(`✓ Generated ${name}`);}Next Steps
Section titled “Next Steps”- CLI Commands Reference - Detailed command documentation
- Type System - Understanding LUMOS types
- Generated Code - Working with generated files
- GitHub Action - Automate in CI/CD
Package Information
Section titled “Package Information”- npm Registry: https://www.npmjs.com/package/@getlumos/cli
- GitHub: https://github.com/getlumos/lumos/tree/main/packages/npm
- Issues: https://github.com/getlumos/lumos/issues
- License: MIT OR Apache-2.0