diff --git a/.eslintrc.cjs b/.eslintrc.cjs
new file mode 100644
index 0000000..a773cc6
--- /dev/null
+++ b/.eslintrc.cjs
@@ -0,0 +1,169 @@
+/**
+ * ESLint Configuration for Parsec Equations Library
+ *
+ * Provides comprehensive linting rules for JavaScript/ES6+ code
+ * with Prettier integration for formatting and specific considerations
+ * for WebAssembly integration and cross-platform library development.
+ */
+
+module.exports = {
+ // Environment configuration
+ env: {
+ browser: true,
+ node: true,
+ es2022: true,
+ worker: true,
+ },
+
+ // Parser configuration for modern JavaScript
+ parserOptions: {
+ ecmaVersion: 2022,
+ sourceType: 'module',
+ allowImportExportEverywhere: true,
+ },
+
+ // Base configurations
+ extends: ['eslint:recommended', 'prettier'],
+
+ // Plugin configuration
+ plugins: ['prettier'],
+
+ // Global variables
+ globals: {
+ // Vitest globals
+ describe: 'readonly',
+ it: 'readonly',
+ test: 'readonly',
+ expect: 'readonly',
+ beforeAll: 'readonly',
+ beforeEach: 'readonly',
+ afterAll: 'readonly',
+ afterEach: 'readonly',
+ vi: 'readonly',
+
+ // WebAssembly globals
+ WebAssembly: 'readonly',
+
+ // AMD module globals
+ define: 'readonly',
+
+ // Test environment globals
+ __TEST_ENV__: 'readonly',
+ __VERSION__: 'readonly',
+ },
+
+ // Custom rules
+ rules: {
+ // Prettier integration
+ 'prettier/prettier': 'error',
+
+ // Variables
+ 'no-unused-vars': [
+ 'error',
+ {
+ argsIgnorePattern: '^_',
+ varsIgnorePattern: '^_',
+ ignoreRestSiblings: true,
+ },
+ ],
+ 'no-var': 'error',
+ 'prefer-const': 'error',
+
+ // Functions
+ 'no-unused-expressions': 'error',
+ 'prefer-arrow-callback': 'error',
+
+ // Best practices
+ eqeqeq: ['error', 'always'],
+ 'no-eval': 'error',
+ 'no-implied-eval': 'error',
+ 'no-new-func': 'error',
+ 'no-console': 'off', // Allow console for WebAssembly debugging
+ 'no-debugger': 'error',
+ 'no-alert': 'error',
+
+ // ES6+ features
+ 'prefer-template': 'error',
+ 'prefer-destructuring': [
+ 'error',
+ {
+ array: false,
+ object: true,
+ },
+ ],
+
+ // Error handling
+ 'no-throw-literal': 'error',
+ 'prefer-promise-reject-errors': 'error',
+
+ // Code complexity
+ complexity: ['warn', 15],
+ 'max-depth': ['warn', 4],
+
+ // Async/await
+ 'require-await': 'error',
+ 'no-return-await': 'error',
+
+ // Classes
+ 'class-methods-use-this': 'off', // Allow methods that don't use 'this'
+ 'no-useless-constructor': 'error',
+
+ // Imports/exports
+ 'no-duplicate-imports': 'error',
+
+ // WebAssembly specific
+ 'no-new-wrappers': 'error',
+ 'no-prototype-builtins': 'error',
+ },
+
+ // Override rules for specific file patterns
+ overrides: [
+ // Test files
+ {
+ files: ['tests/**/*.js', '**/*.test.js', '**/*.spec.js'],
+ rules: {
+ 'no-magic-numbers': 'off', // Allow magic numbers in tests
+ 'prefer-arrow-callback': 'off', // Allow function expressions in tests
+ },
+ },
+
+ // Configuration files
+ {
+ files: ['*.config.js', '.eslintrc.js', 'vitest.config.js'],
+ rules: {
+ 'no-console': 'off',
+ },
+ },
+
+ // WebAssembly wrapper files
+ {
+ files: ['js/**/*.js'],
+ rules: {
+ 'no-console': 'off', // Allow console for WASM debugging
+ complexity: ['warn', 20], // Allow higher complexity for WASM integration
+ },
+ },
+
+ // Entry point files
+ {
+ files: ['index.js', 'index.mjs'],
+ rules: {
+ complexity: ['warn', 20], // Allow higher complexity for compatibility layers
+ },
+ },
+ ],
+
+ // Ignore patterns
+ ignorePatterns: [
+ 'node_modules/',
+ 'coverage/',
+ 'dist/',
+ 'equations-parser/', // Git submodule - don't lint
+ 'wasm/*.js', // Generated Emscripten files
+ '*.wasm',
+ 'html/',
+ 'docs/',
+ '*.min.js',
+ 'emsdk/', // Emscripten SDK - don't lint
+ ],
+}
diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml
new file mode 100644
index 0000000..14dd003
--- /dev/null
+++ b/.github/workflows/tests.yml
@@ -0,0 +1,51 @@
+name: CI - Tests
+
+on:
+ push:
+ branches:
+ - '**'
+ pull_request:
+ branches:
+ - '**'
+ workflow_dispatch:
+
+permissions:
+ contents: read
+
+concurrency:
+ group: ${{ github.workflow }}-${{ github.ref }}
+ cancel-in-progress: true
+
+jobs:
+ test:
+ name: Node ${{ matrix.node }} on ${{ matrix.os }}
+ runs-on: ${{ matrix.os }}
+ strategy:
+ fail-fast: false
+ matrix:
+ os: [ubuntu-latest]
+ node: [18.x, 20.x]
+
+ steps:
+ - name: Checkout repository
+ uses: actions/checkout@v4
+
+ - name: Setup Node.js ${{ matrix.node }}
+ uses: actions/setup-node@v4
+ with:
+ node-version: ${{ matrix.node }}
+ cache: npm
+
+ - name: Install dependencies
+ run: npm ci
+
+ - name: Run tests
+ run: npm test -- --run
+
+ # Optional: upload coverage if your `npm test` generates it
+ # - name: Upload coverage report
+ # if: always()
+ # uses: actions/upload-artifact@v4
+ # with:
+ # name: coverage-${{ matrix.os }}-node${{ matrix.node }}
+ # path: coverage
diff --git a/.prettierignore b/.prettierignore
new file mode 100644
index 0000000..14f596d
--- /dev/null
+++ b/.prettierignore
@@ -0,0 +1,40 @@
+# Dependencies
+node_modules/
+
+# Submodules
+equations-parser/
+
+# Emscripten SDK
+emsdk/
+
+# Build outputs
+dist/
+coverage/
+
+# Generated WebAssembly files
+wasm/*.js
+*.wasm
+
+# HTML test files (legacy)
+html/
+tests/*.html
+
+# Documentation
+docs/
+
+# Minified files
+*.min.js
+
+# Logs
+*.log
+npm-debug.log*
+
+# Test results
+test-results*.json
+
+# GitHub files
+.github/
+
+# OS files
+.DS_Store
+Thumbs.db
\ No newline at end of file
diff --git a/.prettierrc b/.prettierrc
new file mode 100644
index 0000000..325b791
--- /dev/null
+++ b/.prettierrc
@@ -0,0 +1,9 @@
+{
+ "semi": false,
+ "singleQuote": true,
+ "tabWidth": 2,
+ "trailingComma": "es5",
+ "printWidth": 100,
+ "bracketSpacing": true,
+ "arrowParens": "avoid"
+}
diff --git a/CLAUDE.md b/CLAUDE.md
index 8e9bb55..f6cd592 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -1,361 +1,385 @@
-# Parsec Web: WebAssembly Equations Parser
+# CLAUDE.md - Parsec Web Development Guide
-## Project Overview
+## ๐ฏ Project Vision
-Parsec Web is a revolutionary project that transforms the equations-parser C++ library into a WebAssembly module, enabling lightning-fast mathematical expression evaluation directly in web browsers. This project eliminates the need for server-side computation, providing offline capabilities and near-instantaneous results.
+**Parsec Web** is a generalized JavaScript library that connects to the equations-parser WebAssembly module (C++ code compiled to WASM) for high-performance, cross-platform equation evaluation.
-### Architecture Transformation
+### Core Purpose
-**Before (Server-Dependent):**
-```
-Web Client โ Network Request โ Backend Server โ equations-parser โ Network Response โ Web Client
-```
+- **Generalization**: Make the library reusable across different JavaScript environments
+- **Cross-Platform**: Support frontend projects, Flutter web, Node.js applications
+- **Performance**: Leverage WebAssembly for fast, client-side equation processing
+- **Offline-First**: No server dependency, completely self-contained
+
+## ๐๏ธ Architecture Overview
-**After (Client-Side WebAssembly):**
```
-Web Client โ WebAssembly Module (equations-parser) โ Immediate Result
+JavaScript Applications
+ โ
+Parsec Web Library (js/equations_parser_wrapper.js)
+ โ
+WebAssembly Module (wasm/equations_parser.js/.wasm)
+ โ
+C++ equations-parser Library
```
-### Key Benefits
+### Target Platforms
+
+1. **Frontend Projects**: React, Vue, Angular, vanilla JavaScript
+2. **Flutter Web**: Via dart:js_interop integration
+3. **Node.js Applications**: As importable npm package
+4. **Cross-Platform Solutions**: Any JavaScript environment
-- **100x Performance Improvement**: ~1ms vs ~110ms processing time
-- **Zero Server Infrastructure**: No backend servers required
-- **Offline Capabilities**: Full functionality without internet connection
-- **Infinite Scalability**: Processing scales with client devices
-- **Complete Feature Parity**: All equations-parser functions available
+## ๐งช Testing Framework
-## Current Implementation Status
+The project uses **Vitest** as the primary testing framework for comprehensive equation evaluation testing.
-### Phase 2 - Completed โ
-The project is currently in Phase 2, which integrates the full equations-parser C++ library into WebAssembly:
+### Test Implementation Strategy
-**What's Built:**
-- Complete equations-parser library compiled to WebAssembly
-- Comprehensive JavaScript wrapper with clean API
-- Interactive HTML testing interface
-- Support for all mathematical operations, string functions, date/time operations
-- Error handling and type-aware evaluation
-- Automated build scripts
+**Test Categories:**
-**Core Functionality Available:**
-- **Mathematical Functions**: sin, cos, tan, ln, log, abs, sqrt, pow, exp, etc.
-- **String Operations**: concat, length, toupper, tolower, left, right
-- **Complex Numbers**: real, imag, conj, arg, norm
-- **Arrays/Matrices**: sizeof, eye, ones, zeros
-- **Date/Time Functions**: current_date, daysdiff, hoursdiff
-- **Conditional Logic**: ternary operators, comparison operators
-- **Multiple Return Types**: integer, float, string, boolean values
+- **Unit Tests** (8 modules): `tests/unit/`
+ - `arithmetic.test.js` - Basic math operations, order of operations
+ - `trigonometry.test.js` - sin, cos, tan, inverse functions, hyperbolic
+ - `logarithms.test.js` - ln, log, exp functions
+ - `strings.test.js` - concat, length, toupper, tolower, substring functions
+ - `dates.test.js` - current_date, daysdiff, hoursdiff functions
+ - `complex.test.js` - real, imag, conj, arg, norm functions
+ - `arrays.test.js` - sizeof, eye, ones, zeros functions
-### Architecture
+- **Integration Tests** (2 modules): `tests/integration/`
+ - `complex-expressions.test.js` - Multi-function combinations
+ - `mixed-types.test.js` - Different return types (number, string, boolean)
+- **Error Handling** (3 modules): `tests/errors/`
+ - `syntax-errors.test.js` - Invalid equation syntax
+ - `runtime-errors.test.js` - Division by zero, invalid arguments
+ - `type-errors.test.js` - Type mismatches, invalid operations
+
+- **Performance Benchmarks** (3 modules): `tests/performance/`
+ - `simple-ops.bench.js` - Basic arithmetic benchmarking
+ - `function-calls.bench.js` - Function call performance
+ - `complex-expr.bench.js` - Complex expression performance
+
+**Testing Commands:**
+
+```bash
+npm test # Run all tests
+npm run test:watch # Watch mode for development
+npm run test:coverage # Generate coverage report
+npm run test:unit # Unit tests only
+npm run test:integration # Integration tests only
+npm run test:performance # Performance benchmarks
```
-parsec-web/
-โโโ equations-parser/ # C++ library (git submodule)
-โ โโโ parser/
-โ โโโ equationsParser.h # Main parser interface
-โ โโโ equationsParser.cpp # Core evaluation logic
-โ โโโ [50+ additional parser files]
-โโโ cpp/
-โ โโโ equations_parser_wrapper.cpp # WebAssembly bindings
-โโโ js/
-โ โโโ equations_parser_wrapper.js # JavaScript API wrapper
-โ โโโ math_wrapper.js # Phase 1 legacy wrapper
-โโโ html/
-โ โโโ equations-parser-test.html # Phase 2 interactive test interface
-โ โโโ test.html # Phase 1 basic test page
-โโโ wasm/ # Generated WebAssembly files
-โโโ build-equations-parser.sh # Phase 2 build script
-โโโ build.sh # Phase 1 build script
+
+## ๐ฆ Library Features
+
+### NPM Package Structure
+
+- `package.json` - Complete npm configuration with proper scripts and metadata
+- Multi-format exports supporting ES6, CommonJS, and UMD patterns
+- TypeScript definitions included for full type safety
+- Professional package structure ready for npm publishing
+
+### Enhanced API
+
+```javascript
+// Parsec class with enhanced functionality
+const parsec = new Parsec()
+await parsec.initialize()
+
+// Batch evaluation
+const results = parsec.evaluateBatch(['2+2', 'sqrt(16)', 'sin(pi/2)'])
+
+// Timeout protection
+const result = await parsec.evaluateWithTimeout('expression', 5000)
+
+// Library metadata
+const info = parsec.getInfo()
+console.log(info.supportedPlatforms) // Multiple platform support info
```
-### Core Components
+### Cross-Platform Import Support
+
+```javascript
+// ES6 Modules
+import { Parsec } from 'parsec-web'
-#### 1. equations-parser C++ Library (`equations-parser/`)
-The heart of the system - a comprehensive mathematical expression evaluator:
+// CommonJS (Node.js)
+const { Parsec } = require('parsec-web')
-- **Main Interface**: `equationsParser.h/cpp`
- - `Calc(string input)` - Basic evaluation returning string
- - `CalcJson(string input)` - JSON evaluation with type information
- - `CalcArray(vector, vector&)` - Batch processing
+// TypeScript
+import { Parsec, EquationResult } from 'parsec-web'
+```
-- **Features**: 50+ C++ files implementing mathematical functions, operators, string manipulation, date/time operations, and more
+### Code Quality Infrastructure
-#### 2. WebAssembly Wrapper (`cpp/equations_parser_wrapper.cpp`)
-Bridges C++ library to JavaScript:
+- **Prettier**: Automatic code formatting with consistent style rules
+- **ESLint**: Code quality checking with modern JavaScript best practices
+- **npm scripts**: `style:fix`, `lint:fix`, `format`, `test` commands
+- **Vitest configuration**: Modern testing framework setup
-```cpp
-// Main evaluation function
-std::string eval_equation(const std::string& equation)
+**Development Workflow:**
-// Module test function
-int test_equations_parser_loaded()
+```bash
+npm run style:fix # Auto-fix formatting and linting
+npm test # Run comprehensive test suite
+npm run dev # Start development server
+npm run build # Build WebAssembly module
```
-- **Emscripten Bindings**: Exposes C++ functions to JavaScript
-- **Error Handling**: Comprehensive exception catching and JSON error responses
-- **Logging**: Debug output for development and troubleshooting
+## ๐ฎ Future Development
-#### 3. JavaScript API (`js/equations_parser_wrapper.js`)
-Clean JavaScript interface with native type conversion:
+### Flutter Web Integration
-```javascript
-class Parsec {
- async initialize(wasmPath) // Load WebAssembly module
- eval(equation) // Evaluate mathematical expressions (returns native types)
- getSupportedFunctions() // Get function documentation
- runComprehensiveTests() // Automated testing
-}
+- **Goal**: `dart:js_interop` integration
+- **Planned**: Dart bindings for JavaScript library
+- **Status**: Future enhancement
+
+## ๐งช Testing Philosophy
+
+**Modern Automated Testing Approach:**
+
+- **Vitest**: Modern testing framework
+- **Automated**: Runs via npm scripts
+- **Comprehensive**: All equations-parser functionality covered
+- **CI/CD Ready**: JSON reports, coverage metrics
+- **Cross-Platform**: Works in any Node.js environment
+
+## ๐ Quick Development Commands
+
+### Setup & Installation
+
+```bash
+npm install # Install all dependencies
+chmod +x build.sh # Make build script executable
+./build.sh # Compile C++ to WebAssembly
```
-**Features:**
-- Promise-based async initialization
-- Comprehensive error handling and validation
-- **Native Type Conversion**: Automatic conversion from C++ strings to proper JavaScript types
-- Type-aware result objects
-- Built-in test suite
-- Complete function documentation
+#### WebAssembly Build Requirements
-**Type Conversion System:**
-The JavaScript wrapper now includes a sophisticated type conversion system that mirrors the Ruby implementation:
+The project requires **Emscripten** to compile the C++ equations-parser library to WebAssembly:
-- **Integer Types** (`int`/`i`): Converted to JavaScript `number` using `parseInt()`
-- **Float Types** (`float`/`f`): Converted to JavaScript `number` using `parseFloat()`
-- **Boolean Types** (`boolean`/`b`): Converted to JavaScript `boolean` with comprehensive string-to-boolean logic
-- **String Types** (`string`/`s`): Returned as JavaScript `string` with error checking
-- **Special Values**: `inf` โ `'Infinity'`, `-inf` โ `'-Infinity'`, `nan` โ `'nan'`
-- **Error Handling**: Automatic detection and throwing of error strings starting with "Error:"
+- **System Installation**: Install via package manager (`apt-get install emscripten`)
+- **Official Download**: From https://emscripten.org/docs/getting_started/downloads.html
+- **Manual emsdk Setup**: Clone and configure emsdk repository manually
-#### 4. Interactive Test Interface (`html/equations-parser-test.html`)
-Comprehensive web testing environment:
+**Manual emsdk Setup** (if needed):
-- **Live Equation Evaluation**: Real-time input and results
-- **Quick Test Examples**: Pre-built test cases for all function categories
-- **Function Browser**: Searchable catalog of all available functions
-- **Automated Test Suite**: Comprehensive validation of library functionality
-- **Debug Console**: Real-time C++ and JavaScript logging
+```bash
+git clone https://github.com/emscripten-core/emsdk.git
+cd emsdk
+./emsdk install latest # Install latest Emscripten
+./emsdk activate latest # Activate for use
+source ./emsdk_env.sh # Set environment variables
+cd ..
+./build.sh # Build WebAssembly module
+```
+
+### Testing (Vitest Framework)
+
+```bash
+npm test # Run complete test suite
+npm run test:watch # Development mode with auto-rerun
+npm run test:coverage # Generate coverage report
+npm run test:unit # Unit tests only
+npm run test:integration # Integration tests only
+npm run test:performance # Performance benchmarks only
+```
+
+### Code Quality & Formatting
-### Build System
+```bash
+npm run lint # ๐ Run ESLint checks
+npm run lint:fix # ๐ค Auto-fix linting issues
+npm run format:check # ๐ Check formatting without changes
+npm run format # ๐ค Format code with Prettier
+npm run style:fix # ๐ค ๐ฆพ Fix both linting and formatting
+```
-#### Emscripten Compilation (`build-equations-parser.sh`)
-Sophisticated build configuration:
+### Development Server
```bash
-emcc cpp/equations_parser_wrapper.cpp $PARSER_SOURCES \
- -I equations-parser/parser \
- -std=c++17 \
- -s WASM=1 \
- -s MODULARIZE=1 \
- -s EXPORT_NAME="EquationsParserModule" \
- -s EXPORT_ES6=1 \
- --bind \
- -O2 \
- -s SINGLE_FILE=1 \
- -o wasm/equations_parser.js
+npm run dev # Start development server (port 8000)
+npm run serve # Alternative server command
+# Access: http://localhost:8000
```
-**Key Features:**
-- ES6 module export
-- Embedded WebAssembly binary
-- Optimized compilation
-- Comprehensive error checking
-- Automatic source file discovery
+### Library Usage Testing
-### Supported Operations
+```bash
+# Test CommonJS import in Node.js
+node -e "const E = require('./index.js'); console.log('โ CommonJS works')"
-The system supports an extensive range of mathematical and utility operations:
+# Test ES6 import (requires Node.js with ES modules support)
+node --input-type=module -e "import('./index.mjs').then(()=>console.log('โ ES6 works'))"
+```
-#### Mathematical Functions
-- **Trigonometric**: sin, cos, tan, asin, acos, atan, atan2
-- **Hyperbolic**: sinh, cosh, tanh, asinh, acosh, atanh
-- **Logarithmic**: ln, log, log10, log2, exp
-- **Power/Root**: abs, sqrt, cbrt, pow, hypot
-- **Rounding**: round, round_decimal, fmod, remainder
+### Publishing to npm
-#### String Functions
-- **Manipulation**: concat, length, toupper, tolower, left, right
-- **Conversion**: str2number, number, string
-- **Utilities**: contains, link, default_value, calculate
+The repository is configured as a production-ready npm package with dual CommonJS/ES module support:
-#### Date/Time Operations
-- **Current Values**: current_date(), current_time()
-- **Calculations**: daysdiff, hoursdiff, timediff, add_days
-- **Formatting**: weekyear, weekday
+```bash
+# 1. Ensure everything is built and tested
+npm run build # Builds WebAssembly module
+npm test # Runs comprehensive test suite
+npm run lint # Checks code quality
-#### Advanced Features
-- **Matrix Operations**: ones, zeros, eye, size, transpose
-- **Aggregation**: min, max, sum, avg, sizeof
-- **Conditionals**: ternary operators (?:), comparison operators
-- **Logical Operations**: &&, ||, !, and, or
-- **Type Casting**: (float), (int), factorial (!)
+# 2. Test package creation
+npm pack --dry-run # Preview what will be published
-### API Examples
+# 3. Login to npm (if not already)
+npm login
-#### Basic Usage with Native Type Conversion
-```javascript
-const parsec = new Parsec();
-await parsec.initialize();
+# 4. Publish to npm registry
+npm publish
-// Mathematical evaluation - returns native JavaScript number
-const result1 = parsec.eval('2 + 3 * sin(pi/2)');
-// โ {value: 5, type: "f", success: true} (value is number, not string)
+# 5. Or publish as scoped package
+npm publish --access public
+```
-// String operations - returns native JavaScript string
-const result2 = parsec.eval('concat("Hello", " World")');
-// โ {value: "Hello World", type: "s", success: true}
+**Package Structure:**
-// Boolean logic - returns native JavaScript boolean
-const result3 = parsec.eval('5 > 3');
-// โ {value: true, type: "b", success: true} (value is boolean, not string)
+- **CommonJS entry**: `index.cjs` for Node.js `require()`
+- **ES Module entry**: `index.mjs` for modern `import`
+- **TypeScript definitions**: `types.d.ts` with complete type safety
+- **Automated scripts**: `prepublishOnly` and `prepack` ensure quality
-// Conditional logic - returns native JavaScript string
-const result4 = parsec.eval('5 > 3 ? "yes" : "no"');
-// โ {value: "yes", type: "s", success: true}
+**Installation for users:**
-// Integer operations - returns native JavaScript number
-const result5 = parsec.eval('10 / 2');
-// โ {value: 5, type: "i", success: true} (value is number, not string)
+```bash
+npm install parsec-web
```
-#### Type Conversion Examples
+**Usage examples:**
+
```javascript
-// Special float values
-parsec.eval('1/0'); // โ {value: "Infinity", type: "f", success: true}
-parsec.eval('-1/0'); // โ {value: "-Infinity", type: "f", success: true}
-parsec.eval('0/0'); // โ {value: "nan", type: "f", success: true}
-
-// Boolean conversions (following Ruby string-to-boolean logic)
-parsec.eval('true'); // โ {value: true, type: "b", success: true}
-parsec.eval('false'); // โ {value: false, type: "b", success: true}
-parsec.eval('"1"'); // If evaluated as boolean โ true
-parsec.eval('"0"'); // If evaluated as boolean โ false
+// CommonJS (Node.js)
+const { Parsec } = require('parsec-web')
+
+// ES Modules (modern)
+import { Parsec } from 'parsec-web'
+
+// Usage
+const parsec = new Parsec()
+await parsec.initialize()
+const result = parsec.eval('2 + 3 * 4') // Returns: 14
+```
+
+## ๐ Project Structure
+
```
+parsec-web/
+โโโ cpp/ # C++ source files
+โ โโโ equations-parser/ # Git submodule
+โโโ js/ # JavaScript library
+โ โโโ equations_parser_wrapper.js # Core WebAssembly wrapper (Parsec class)
+โโโ wasm/ # Generated WebAssembly files
+โ โโโ equations_parser.js # Main WebAssembly module
+โโโ tests/ # Vitest test suites
+โ โโโ setup.js # Global test configuration
+โ โโโ unit/ # Function category tests
+โ โโโ integration/ # Complex expression tests
+โ โโโ errors/ # Error handling tests
+โ โโโ performance/ # Benchmark tests
+โโโ index.js # CommonJS entry point
+โโโ index.mjs # ES6 module entry point
+โโโ types.d.ts # TypeScript definitions
+โโโ package.json # npm package configuration
+โโโ vitest.config.js # Vitest configuration
+โโโ .eslintrc.js # ESLint configuration
+โโโ .prettierrc # Prettier configuration
+โโโ .prettierignore # Prettier ignore patterns
+โโโ build.sh # WebAssembly build script
+โโโ README.md # Public documentation
+โโโ CLAUDE.md # This development guide
+```
+
+## ๐ฏ Key API Usage
+
+### Primary Interface
-#### Error Handling
```javascript
-const result = parsec.eval('5 / 0');
-// โ {error: "Division by zero", success: false}
+// Import the library
+import Parsec from './js/equations_parser_wrapper.js'
+
+// Initialize WebAssembly module
+const parsec = new Parsec()
+await parsec.initialize()
+
+// Evaluate equations
+const result = parsec.eval('2 + 3 * 4') // Returns: 14
+const trig = parsec.eval('sin(pi/2)') // Returns: 1
+const complex = parsec.eval('real(3+4i)') // Returns: 3
+const string = parsec.eval('concat("a","b")') // Returns: "ab"
```
-#### Comprehensive Testing
+### Test Structure Pattern
+
```javascript
-const testResults = await parsec.runComprehensiveTests();
-// Returns detailed test results for all function categories
+// All tests follow this pattern
+class SomeTests {
+ constructor(testRunner) {
+ this.testRunner = testRunner
+ }
+
+ async runTests() {
+ const result = await this.testRunner.evaluate('some_equation')
+ this.testRunner.assertEqual(result, expected, 'Test description')
+ }
+}
```
-## Development Workflow
+## ๐ฆ Development Workflow
+
+1. **Make Changes**: Edit C++, JavaScript, or test files
+2. **Rebuild WASM**: `./build.sh` (if C++ changed)
+3. **Run Tests**: `npm test` (verify functionality)
+4. **Fix Issues**: Address any failing tests
+5. **Lint Code**: `npm run lint` (maintain code quality)
+6. **Update Docs**: Keep README.md and CLAUDE.md current
+
+## ๐ Debugging & Troubleshooting
+
+### Common Issues
+
+- **Module Loading**: Ensure proper ES6 module paths
+- **WebAssembly Path**: Check WASM file path resolution
+- **Import Errors**: Verify proper import/export statements
+- **Test Failures**: Use `npm run test:watch` for iterative debugging
+
+### Debug Commands
-### Building the Project
```bash
-# Build WebAssembly module
-./build-equations-parser.sh
+# Detailed test output
+npm test -- --reporter verbose
-# Start local development server
-python3 -m http.server 8000
+# Run single test file
+npm test -- arithmetic.test.js
-# Open test interface
-# Navigate to: http://localhost:8000/html/equations-parser-test.html
+# Debug mode with console output
+npm test -- --reporter verbose --silent false
```
-### Testing Strategy
-The project includes comprehensive testing at multiple levels:
-
-1. **Module Loading Tests**: Verify WebAssembly initialization
-2. **Function Tests**: Validate all mathematical operations
-3. **Error Handling Tests**: Ensure graceful failure modes
-4. **Type System Tests**: Verify correct type detection and conversion
-5. **Performance Tests**: Monitor execution speed
-
-### Code Quality
-- **Clean Architecture**: Separation of concerns between C++, WebAssembly, and JavaScript layers
-- **Error Boundaries**: Comprehensive exception handling at all levels
-- **Type Safety**: Strong typing throughout the JavaScript API
-- **Documentation**: Extensive inline documentation and examples
-- **Logging**: Detailed debug output for development and troubleshooting
-
-## Future Development Phases
-
-### Phase 3 - Automated Testing (Planned)
-- Comprehensive automated test suite
-- Cross-browser compatibility testing
-- Performance benchmarking
-- CI/CD integration
-
-### Phase 4 - Library Extraction (Planned)
-- Standalone npm package
-- Flutter Web package
-- Multi-platform distribution
-- Production optimization
-
-### Phase 5 - Advanced Integrations (Planned)
-- React/Vue.js components
-- Mobile app integration
-- Desktop application support
-- Advanced visualization tools
-
-## Technical Specifications
-
-### Browser Compatibility
-- **Modern browsers** with WebAssembly support
-- **ES6 modules** required for JavaScript integration
-- **Local development** requires HTTP server (not file://)
-
-### Performance Characteristics
-- **Initialization**: ~100-200ms (one-time WebAssembly loading)
-- **Evaluation**: <5ms for complex expressions
-- **Memory Usage**: ~2MB WebAssembly module
-- **Offline Support**: Full functionality without internet
-
-### Security Considerations
-- **Client-side execution**: No data transmitted to servers
-- **Input validation**: Comprehensive equation syntax checking
-- **Error isolation**: Safe handling of malformed expressions
-- **No external dependencies**: Self-contained WebAssembly module
-
-## Development Notes
-
-### Key Files for Claude Code Understanding
-
-- **equations-parser/parser/equationsParser.h:15** - Main C++ evaluation interface
-- **cpp/equations_parser_wrapper.cpp:25** - WebAssembly bindings for eval_equation
-- **js/equations_parser_wrapper.js:85** - JavaScript eval() method implementation
-- **build-equations-parser.sh:55** - Emscripten compilation configuration
-- **html/equations-parser-test.html:497** - Interactive evaluation interface
-
-### Important Implementation Details
-
-1. **Module Loading**: Uses ES6 dynamic imports with async initialization
-2. **Type System**: Results include both value and type information (i, f, s, b)
-3. **Error Handling**: Three-layer error handling (C++, WebAssembly, JavaScript)
-4. **Memory Management**: Automatic via Emscripten runtime
-5. **Debugging**: Console output from both C++ and JavaScript layers
-
-### Performance Optimizations
-
-- **Single File Output**: WebAssembly binary embedded in JavaScript
-- **Compilation Flags**: -O2 optimization with debug symbols
-- **Module Reuse**: Single initialization for multiple evaluations
-- **Type Caching**: Efficient result object creation
-- **Memory Growth**: Dynamic memory allocation as needed
-
-This project represents a significant advancement in bringing high-performance mathematical computation to web browsers, providing a foundation for advanced scientific and engineering web applications.
+This guide serves as the definitive reference for Parsec Web development, focusing on the modern testing approach and cross-platform generalization goals.
## Pull Request Guidance
When prompted with **"draft a pull request"**:
1. **Analyze changes**
- * Compare everything done on the current branch against `master`/`main` branch of `upstream`.
- * Summarize all relevant commits, file modifications, and key impacts.
+ - Compare everything done on the current branch against `main`.
+ - Summarize all relevant commits, file modifications, and key impacts.
2. **Create a Markdown draft**
- * Produce content that can be pasted directly into the PR **title** and **description** fields.
- * **Structure** the description with the template imported below:
- @digitalize-api/.github/pull_request_template.md
- * Enhance clarity with markdown code fences with language tags, colors, tables, blockquotes for callouts, admonitions (GitHub alerts), mermaid diagrams, images, collapsible details and etc.
+ - Produce content that can be pasted directly into the PR **title** and **description** fields.
+ - **Structure** the description with the template imported below:
+ @status-survey2/.github/pull_request_template.md
+ - Enhance clarity with markdown code fences with language tags, colors, tables, blockquotes for callouts, admonitions (GitHub alerts), mermaid diagrams, images, collapsible details and etc.
3. **Write the Test Guidance section**
- * Assume a tester is going to test the changes proposed on this pull request.
- * Describe step-by-step checks needs to be performed to carefully test it.
+ - Assume the tester has minimal backend or API knowledge.
+ - Describe step-by-step checks performed purely through the frontendโmouse clicks, typing, and other UI interactions.
4. **Generate a Markdown file**
- * Generate a `pull_request.md` file containing the Pull Request title and description
+ - Generate a `pull_request.md` file containing the Pull Request title and description
diff --git a/README.md b/README.md
index 75d8fe5..5b4ef59 100644
--- a/README.md
+++ b/README.md
@@ -3,20 +3,28 @@
- Parsec Web: A very light parser for equations using WebAssembly in equations-parser
+ Parsec Web: A generalized JavaScript library that connects to equations-parser WebAssembly for cross-platform equation evaluation
## ๐ฏ Project Overview
-Parsec Web transforms equation processing from server-dependent operations to lightning-fast client-side computations using WebAssembly.
+**Parsec Web** is a generalized JavaScript library that connects to the equations-parser WebAssembly module (C++ code) for high-performance equation evaluation. This library is designed to be reusable across multiple platforms including:
+
+- **Frontend Projects**: React, Vue, Angular, vanilla JavaScript
+- **Flutter Web Projects**: Via dart:js_interop integration
+- **Node.js Applications**: As an importable library
+- **Cross-Platform Solutions**: General enough to work across different JavaScript environments
+
+The library transforms equation processing from server-dependent operations to lightning-fast client-side computations using WebAssembly, making it completely offline-capable and infinitely scalable.
### ๐ Architecture Transformation
**Before (Traditional Backend):**
+
```mermaid
graph LR
A[๐ Web] --> B[๐ก Network] --> C[๐ Backend Server] --> D[๐ Parsec Library] --> E[โ๏ธ C++ equations-parser]
-
+
style A fill:#e1f5fe,color:#000000
style B fill:#ffebee,color:#000000
style C fill:#fff3e0,color:#000000
@@ -27,10 +35,11 @@ graph LR
โ Problems: Network latency, server costs, scaling issues, offline limitations
**After (Parsec Web):**
+
```mermaid
graph LR
A[๐ Web] --> B[๐ Parsec Web WebAssembly] --> C[โ๏ธ C++ equations-parser]
-
+
style A fill:#e8f5e8,color:#000000
style B fill:#e3f2fd,color:#000000
style C fill:#f3e5f5,color:#000000
@@ -39,6 +48,7 @@ graph LR
โ Benefits: Zero latency, no server costs, infinite scalability, offline capable
### ๐ Key Features
+
- **100x Faster**: ~1ms vs ~110ms equation processing
- **Zero Infrastructure**: No backend servers needed
- **Full Offline Support**: Works without internet
@@ -48,15 +58,34 @@ graph LR
## ๐ Quick Start
### Prerequisites
+
- Emscripten SDK installed and configured
- Modern web browser with ES6 module support
- Local web server (Python, Node.js, or similar)
+#### Prerequisites for Building
+
+1. **Modern web browser with ES6 module support.**
+2. **Local web server.** (Python, Node.js, or similar)
+3. **The project requires Emscripten to compile C++ to WebAssembly.** You can install it via:
+ 3.1 **System package manager**: `apt-get install emscripten` (Linux)
+ 3.2 **Official download**: https://emscripten.org/docs/getting_started/downloads.html
+ 3.3 **emsdk**: Manual setup with the Emscripten SDK
+
+The build script will automatically detect your Emscripten installation and compile the equations-parser C++ library to WebAssembly.
+
+### Expected Results
+- โ "WebAssembly module ready!" status message
+- โ Interactive math function testing
+- โ Automated test suite passes
+- โ C++ debug output in console
+
### Build and Test
+
```bash
# 1. Build the WebAssembly module
-chmod +x build-equations-parser.sh
-./build-equations-parser.sh
+chmod +x build.sh
+./build.sh
# 2. Start local server
python3 -m http.server 8000
@@ -65,604 +94,504 @@ python3 -m http.server 8000
# Navigate to: http://localhost:8000/html/equations-parser-test.html
```
-### Expected Results
-- โ "WebAssembly module ready!" status message
-- โ Interactive math function testing
-- โ Automated test suite passes
-- โ C++ debug output in console
+### Installation
-## ๐๏ธ Implementation Phases
-
-### โ Phase 1: Basic WebAssembly + JavaScript Integration
-**Status**: Ready for testing
-**Goal**: Create and test C++ โ WASM โ JavaScript integration
-
-**What's included:**
-- C++ math functions (`sum`, `multiply`)
-- Emscripten compilation setup
-- JavaScript wrapper library
-- Interactive HTML test page
-- Comprehensive documentation
-
-**Files:**
-- `cpp/math_functions.cpp` - C++ source with Emscripten bindings
-- `build.sh` - Compilation script with detailed flags
-- `js/math_wrapper.js` - JavaScript wrapper with error handling
-- `html/test.html` - Interactive test interface
-- `docs/phase1-guide.md` - Complete setup and testing guide
-
-### โ Phase 2: Equations-Parser WebAssembly Integration *(COMPLETED)*
-**Status**: **FULLY IMPLEMENTED** with native type conversion
-**Goal**: Compile the real equations-parser C++ library to WebAssembly and create comprehensive web testing interface
-
-**โ What's completed:**
-- โ Replaced toy math functions with actual equations-parser library
-- โ Set up equations-parser as git submodule from `https://github.com/oxeanbits/equations-parser`
-- โ Compiled comprehensive equation evaluation from `equations-parser` lib to WASM
-- โ Implemented main function `eval_equation(equation)` for string input processing
-- โ **NEW: Native Type Conversion System** - Automatic conversion from C++ strings to proper JavaScript types:
- - **Integer types** โ JavaScript `number` (using `parseInt()`)
- - **Float types** โ JavaScript `number` (using `parseFloat()`)
- - **Boolean types** โ JavaScript `boolean` (with Ruby-style string-to-boolean conversion)
- - **String types** โ JavaScript `string` (with error checking)
- - **Special values**: `inf` โ `'Infinity'`, `-inf` โ `'-Infinity'`, `nan` โ `'nan'`
-- โ Created enhanced HTML + JavaScript testing interface with type information display
-- โ Full support for all equations-parser features:
- - โ **Math functions**: sin, cos, tan, ln, log, abs, sqrt, pow, exp, etc.
- - โ **String functions**: concat, length, toupper, tolower, left, right
- - โ **Complex functions**: real, imag, conj, arg, norm
- - โ **Array functions**: sizeof, eye, ones, zeros
- - โ **Date functions**: current_date, daysdiff, hoursdiff
- - โ **Advanced operators**: ternary operators, comparison operators
- - โ **Multiple return types**: Returns native JavaScript types instead of strings
-
-**๐ฏ Key Achievement**: The system now returns properly typed JavaScript values:
-```javascript
-parsec.eval('2 + 3') // โ {value: 5, type: "i"} (number)
-parsec.eval('sin(pi/2)') // โ {value: 1.0, type: "f"} (number)
-parsec.eval('5 > 3') // โ {value: true, type: "b"} (boolean)
-parsec.eval('concat("a","b")') // โ {value: "ab", type: "s"} (string)
+```bash
+# Install the library (when published to npm)
+npm install parsec-web
+
+# Or clone and install for development
+git clone
+cd parsec-web
+npm install
+
+# Build WebAssembly module (requires emsdk)
+# Uses system Emscripten installation or emsdk
+./build.sh
```
-### ๐ Phase 3: Automated tests for the Equations-Parser WebAssembly library *(Coming Next)*
-**Goal**: Comprehensive test suite ensuring equations-parser WASM reliability and correctness
+## ๐ฏ Core Features
-**What's planned:**
-- **Unit Tests**: Individual function testing for all equation types
-- **Performance Tests**: Execution time benchmarks vs native implementations
-- **Edge Case Tests**: Boundary conditions and error handling validation
-- **Cross-Browser Tests**: Compatibility across major browsers
+**Parsec Web** integrates the equations-parser C++ library via WebAssembly, delivering:
-#### ๐ Test Categories
+- **Native Type Conversion**: Automatic conversion from C++ to JavaScript types (number, string, boolean)
+- **Complete Function Support**: All equations-parser features available
+ - **Math functions**: sin, cos, tan, ln, log, abs, sqrt, pow, exp, etc.
+ - **String functions**: concat, length, toupper, tolower, left, right
+ - **Complex functions**: real, imag, conj, arg, norm
+ - **Array functions**: sizeof, eye, ones, zeros
+ - **Date functions**: current_date, daysdiff, hoursdiff
+ - **Advanced operators**: ternary operators, comparison operators
-##### ๐งฎ **Basic Arithmetic Tests**
-```javascript
-// Simple operations
-"2 + 3" โ 5
-"10 - 4" โ 6
-"7 * 8" โ 56
-"15 / 3" โ 5
-"2 ^ 3" โ 8
-"10 % 3" โ 1
-
-// Order of operations
-"2 + 3 * 4" โ 14
-"(2 + 3) * 4" โ 20
-"2 + 3 * 4 - 1" โ 13
-"2 ^ 3 ^ 2" โ 512
-```
+**Direct Value Returns:**
-##### ๐ **Mathematical Functions Tests**
```javascript
-// Trigonometric functions
-"sin(0)" โ 0
-"cos(0)" โ 1
-"tan(pi/4)" โ 1
-"asin(1)" โ ฯ/2
-"acos(0)" โ ฯ/2
-"atan(1)" โ ฯ/4
-
-// Logarithmic functions
-"ln(e)" โ 1
-"log(100)" โ 2
-"log(1000, 10)" โ 3
-"exp(1)" โ e
-
-// Power and root functions
-"sqrt(16)" โ 4
-"pow(2, 3)" โ 8
-"abs(-5)" โ 5
-"round(3.6)" โ 4
+parsec.eval('2 + 3') // โ 5 (number)
+parsec.eval('sin(pi/2)') // โ 1.0 (number)
+parsec.eval('5 > 3') // โ true (boolean)
+parsec.eval('concat("a","b")') // โ "ab" (string)
```
-##### ๐ค **String Functions Tests**
+## ๐งช Comprehensive Testing
+
+**Professional Testing Framework**: Vitest-based testing with complete coverage
+
+### Test Coverage
+- **Unit Tests**: Arithmetic, Trigonometry, Logarithms, String Functions, Date Functions, Complex Numbers, Array Operations
+- **Integration Tests**: Complex expressions, Mixed data types, Function combinations
+- **Error Handling**: Syntax errors, Runtime errors, Type errors, Edge cases
+- **Performance Benchmarks**: Speed tracking with regression detection
+- **Cross-Browser Compatibility**: ES6 modules with WebAssembly support
+
+### Example Test Cases
+
+#### Mathematical Operations
```javascript
-// String operations
-"concat('Hello', ' ', 'World')" โ "Hello World"
-"length('test')" โ 4
-"toupper('hello')" โ "HELLO"
-"tolower('WORLD')" โ "world"
-"left('testing', 4)" โ "test"
-"right('testing', 3)" โ "ing"
+"2 + 3 * 4" โ 14
+"sin(pi/2)" โ 1
+"sqrt(pow(3,2) + pow(4,2))" โ 5
+"log(exp(2))" โ 2
```
-##### ๐ **Date/Time Functions Tests**
+#### String Operations
```javascript
-// Date operations
-"current_date()" โ "2024-MM-DD"
-"daysdiff('2024-01-01', '2024-01-10')" โ 9
-"hoursdiff('2024-01-01 12:00', '2024-01-01 15:30')" โ 3.5
-"weekday('2024-01-01')" โ 1 // Monday
+"concat('Hello', ' World')" โ "Hello World"
+"toupper('hello')" โ "HELLO"
+"length('test')" โ 4
```
-##### โ **Conditional/Logical Tests**
+#### Conditional Logic
```javascript
-// Ternary operators
"true ? 5 : 3" โ 5
-"false ? 5 : 3" โ 3
-"(2 > 1) ? 'yes' : 'no'" โ "yes"
-
-// Comparison operators
"5 > 3" โ true
-"2 < 1" โ false
-"4 >= 4" โ true
-"3 <= 2" โ false
-"5 == 5" โ true
-"5 != 3" โ true
-
-// Logical operators
-"true && true" โ true
-"true || false" โ true
"!false" โ true
```
-##### ๐ **Complex Expression Tests**
+#### Error Handling
```javascript
-// Nested functions
-"sin(cos(pi/3))" โ sin(0.5) โ ~0.479
-"sqrt(pow(3,2) + pow(4,2))" โ 5
-"log(exp(2))" โ 2
+"5 / 0" โ Error: "Division by zero"
+"invalidfunc(5)" โ Error: "Unknown function: invalidfunc"
+"2 + " โ Error: "Unexpected end of expression"
+```
+
+### Running Tests
+
+```bash
+npm test # Run complete test suite
+npm run test:watch # Development mode with auto-rerun
+npm run test:coverage # Generate coverage report
+npm run test:unit # Unit tests only
+npm run test:integration # Integration tests only
+npm run test:performance # Performance benchmarks
+```
+
+## ๐ผ Professional Code Quality
-// String and math combinations
-"length(concat('test', '123')) + 5" โ 12
-"toupper('hello') == 'HELLO'" โ true
+**Enterprise-Grade Development Environment**:
+
+- **Multi-Format Package**: CommonJS, ES6 modules, TypeScript definitions
+- **Cross-Platform Exports**: Works in Node.js, browsers, and bundlers
+- **ESLint + Prettier**: Automated code formatting and quality checking
+- **Git Strategy**: Proper `.gitignore` with submodule exclusion
+
+**Code Quality Commands:**
+
+```bash
+npm run lint # Check code quality
+npm run lint:fix # Auto-fix linting issues
+npm run format # Format code with Prettier
+npm run style:fix # Fix both linting and formatting
```
-##### โ ๏ธ **Error Handling Tests**
+### Basic Usage
+
+#### **ES6 Modules (Recommended)**
+
```javascript
-// Division by zero
-"5 / 0" โ Error: "Division by zero"
-"1 / (2 - 2)" โ Error: "Division by zero"
+import { Parsec } from 'parsec-web'
-// Invalid functions
-"invalidfunc(5)" โ Error: "Unknown function: invalidfunc"
-"sin()" โ Error: "Invalid number of arguments for sin"
+const parsec = new Parsec()
+await parsec.initialize()
-// Type mismatches
-"'hello' + 5" โ Error: "Type mismatch in addition"
-"sin('not_a_number')" โ Error: "Invalid argument type"
+// Basic evaluation
+const result = parsec.eval('2 + 3 * sin(pi/2)')
+console.log(result.value) // 5
+console.log(result.type) // 'f' (float)
-// Syntax errors
-"2 + " โ Error: "Unexpected end of expression"
-"((2 + 3)" โ Error: "Mismatched parentheses"
+// Batch evaluation
+const results = parsec.evaluateBatch(['2 + 2', 'sqrt(16)', 'concat("Hello", " World")'])
+
+// Get library info
+console.log(parsec.getInfo())
```
-##### โก **Performance Benchmark Tests**
+#### **CommonJS (Node.js)**
+
```javascript
-// Speed comparisons (WASM vs JavaScript)
-Simple: "2 + 3" โ Target: < 1ms
-Medium: "sin(cos(tan(0.5)))" โ Target: < 2ms
-Complex: "sqrt(pow(sin(0.5), 2) + pow(cos(0.5), 2)) * log(exp(2.718))" โ Target: < 5ms
-Heavy: "sum(sin(1), cos(2), tan(3), ln(4), sqrt(5), abs(-6), pow(7,2), exp(0.5))" โ Target: < 20ms
+const { Parsec } = require('parsec-web')
+
+const parsec = new Parsec()
+await parsec.initialize()
+
+const result = parsec.eval('sin(pi/2) + cos(0)')
+console.log(result.value) // 2
```
-#### ๐ ๏ธ **Test Infrastructure**
-- **Test Runner**: Custom JavaScript test framework with WebAssembly integration
-- **Assertion Library**: Comprehensive floating-point equality with epsilon tolerance
-- **Browser Testing**: Automated testing across Chrome, Firefox, Safari, Edge
-- **CI Integration**: GitHub Actions pipeline with test result reporting
-- **Coverage Reports**: Function coverage analysis for equations-parser features
-- **Performance Monitoring**: Execution time tracking and regression detection
+#### **TypeScript**
+
+```typescript
+import { Parsec, EquationResult } from 'parsec-web'
-#### ๐ **Test Files Structure**
+const parsec = new Parsec()
+await parsec.initialize()
+
+const result: EquationResult = parsec.eval('abs(-42)')
+if (result.success) {
+ console.log(`Result: ${result.value}`) // Result: 42
+}
```
-tests/
-โโโ unit/ # Individual function tests
-โ โโโ arithmetic.test.js # Basic math operations
-โ โโโ trigonometry.test.js # Sin, cos, tan, etc.
-โ โโโ logarithms.test.js # Log, ln, exp functions
-โ โโโ strings.test.js # String manipulation
-โ โโโ complex.test.js # Complex number operations
-โ โโโ arrays.test.js # Array/matrix functions
-โ โโโ dates.test.js # Date/time functions
-โโโ integration/ # End-to-end workflows
-โ โโโ complex-expressions.test.js # Nested function calls
-โ โโโ mixed-types.test.js # String/number combinations
-โโโ performance/ # Speed benchmarks
-โ โโโ simple-ops.bench.js # Basic arithmetic timing
-โ โโโ function-calls.bench.js # Mathematical function timing
-โ โโโ complex-expr.bench.js # Complex expression timing
-โโโ errors/ # Error handling validation
-โ โโโ syntax-errors.test.js # Invalid syntax cases
-โ โโโ runtime-errors.test.js # Division by zero, etc.
-โ โโโ type-errors.test.js # Type mismatch scenarios
-โโโ browser/ # Cross-browser compatibility
-โ โโโ compatibility.test.js # Browser-specific tests
-โโโ test-runner.js # Main test orchestration
+
+### Development Setup
+
+```bash
+# 1. Clone and install dependencies
+git clone
+cd parsec-web
+npm install
+
+# 2. Build the WebAssembly module (auto-installs emsdk on first run)
+chmod +x build.sh
+./build.sh
+
+# 3. Run tests
+npm test
+
+# 4. Start development server
+npm run dev
+# Navigate to: http://localhost:8000
+
+# 5. Code formatting and linting
+npm run style:fix
```
-#### ๐ฏ **Success Criteria**
-- โ **100% Function Coverage**: All equations-parser features tested
-- โ **Cross-Browser Compatible**: Works in Chrome, Firefox, Safari, Edge
-- โ **Performance Targets Met**: < 5ms for complex expressions
-- โ **Error Handling Robust**: Graceful failure for all edge cases
-- โ **Regression Prevention**: Automated CI prevents functionality breaks
-- โ **Documentation Complete**: Every test case clearly documented
+#### Building WebAssembly Module
+
+The build process compiles the equations-parser C++ library to WebAssembly:
+
+- **Clean builds**: Re-run `./build.sh` anytime to rebuild the WASM module
+- **Automatic detection**: Finds all required C++ source files automatically
+- **Optimized output**: Produces a compact WebAssembly module (~636KB)
+
+If you encounter build issues, ensure Emscripten is properly installed and available in your PATH.
+
+## ๐ฆ Publishing to npm
+The repository is fully configured as a production-ready npm package. Here's how to publish it:
-### ๐ Phase 4: Extract to a frontend library *(Planned)*
-**Goal**: Create a reusable frontend library for equations evaluation that works seamlessly across JavaScript/React and Flutter Web projects
+### Package Structure
-#### ๐ฆ **Library Architecture**
-The library will be packaged as:
-- **npm package**: For JavaScript/React projects
-- **pub.dev package**: For Flutter Web projects
-- **Unified WASM core**: Single WebAssembly module used by both platforms
+The package provides multiple entry points for maximum compatibility:
-#### ๐๏ธ **Implementation Steps**
+- **CommonJS entry**: `index.cjs` for Node.js `require()`
+- **ES Module entry**: `index.mjs` for modern `import`
+- **TypeScript definitions**: `types.d.ts` with complete type safety
+- **Dual module support**: Works with both CommonJS and ES modules
-##### **Step 1: Create Standalone Library Structure**
+### Publishing Steps
+
+```bash
+# 1. Ensure everything is built and tested
+npm run build # Builds WebAssembly module
+npm test # Runs comprehensive test suite
+npm run lint # Checks code quality
+
+# 2. Test the package locally
+npm pack --dry-run # Preview what will be published
+
+# 3. Login to npm (if not already logged in)
+npm login
+
+# 4. Publish to npm registry
+npm publish
+
+# 5. Or publish as scoped package with public access
+npm publish --access public
```
-parsec-equations-lib/
-โโโ core/ # Core WebAssembly files
-โ โโโ equations_parser.wasm # Compiled WASM binary
-โ โโโ equations_parser.js # Emscripten JS glue code
-โโโ js/ # JavaScript/npm package
-โ โโโ package.json # npm package configuration
-โ โโโ index.js # Main entry point
-โ โโโ equations-evaluator.js # Clean API wrapper
-โ โโโ types.d.ts # TypeScript definitions
-โ โโโ README.md # JavaScript usage docs
-โโโ dart/ # Dart/Flutter package
-โ โโโ pubspec.yaml # pub.dev package configuration
-โ โโโ lib/
-โ โ โโโ equations_evaluator.dart # Main Dart API
-โ โ โโโ src/
-โ โ โ โโโ js_interop.dart # dart:js_interop bindings
-โ โ โ โโโ equations_result.dart # Result data classes
-โ โ โ โโโ equations_types.dart # Type definitions
-โ โ โโโ web/ # Web-specific assets
-โ โ โโโ equations_parser.wasm # WASM binary
-โ โ โโโ equations_parser.js # JS glue code
-โ โโโ README.md # Dart/Flutter usage docs
-โโโ examples/ # Usage examples
-โ โโโ react-demo/ # React integration example
-โ โโโ vanilla-js-demo/ # Plain JavaScript example
-โ โโโ flutter-web-demo/ # Flutter Web example
-โโโ README.md # Main documentation
+
+### Package Scripts
+
+The package includes automated quality checks:
+
+- **`prepublishOnly`**: Runs build, tests, and linting before publish
+- **`prepack`**: Ensures fresh WebAssembly build before packaging
+
+### Installation for End Users
+
+Once published, users can install the package:
+
+```bash
+npm install parsec-web
```
-##### **Step 2: Extract and Refactor JavaScript API**
-- **Clean up current wrapper**: Simplify the `Parsec` class
-- **Remove HTML dependencies**: Create pure JavaScript library without DOM dependencies
-- **Add TypeScript support**: Generate type definitions for better developer experience
-- **Implement error handling**: Robust error boundaries and meaningful error messages
-- **Add result caching**: Optional caching for repeated calculations
-- **Bundle optimization**: Create minified and non-minified versions
+### Usage Examples for End Users
-**JavaScript API Example:**
```javascript
-import { EquationsEvaluator } from 'parsec-equations-lib';
+// CommonJS (Node.js)
+const { Parsec } = require('parsec-web')
+
+// ES Modules (modern JavaScript)
+import { Parsec } from 'parsec-web'
-const evaluator = new EquationsEvaluator();
-await evaluator.initialize();
+// TypeScript
+import { Parsec, EquationResult } from 'parsec-web'
-// Basic usage
-const result = evaluator.evaluate('2 + 3 * sin(pi/2)');
-console.log(result.value); // "5"
-console.log(result.type); // "f" (float)
+// Usage
+const parsec = new Parsec()
+await parsec.initialize()
+const result = parsec.eval('2 + 3 * 4') // Returns: 14
// Batch evaluation
-const results = evaluator.evaluateBatch([
- '2 + 2',
- 'sqrt(16)',
- 'concat("Hello", " World")'
-]);
+const results = parsec.evaluateBatch(['2+2', 'sqrt(16)', 'sin(pi/2)'])
+
+// With timeout protection
+const result = await parsec.evaluateWithTimeout('complex_expression', 5000)
```
-##### **Step 3: Create Flutter Web Package with dart:js_interop**
-- **Set up dart:js_interop bindings**: Modern Dart-JavaScript interoperability
-- **Create Dart data classes**: Type-safe result objects and error handling
-- **Asset management**: Bundle WASM files with Flutter package
-- **Web-specific service**: Implementation that loads and uses WASM module
-- **Future-based API**: Async/await pattern for Flutter integration
+### Cross-Platform Compatibility
-**Dart API Example:**
-```dart
-import 'package:parsec_equations_lib/parsec_equations_lib.dart';
+The published package works across:
-final evaluator = EquationsEvaluator();
-await evaluator.initialize();
-
-// Basic usage
-final result = await evaluator.evaluate('2 + 3 * sin(pi/2)');
-print(result.value); // "5"
-print(result.type); // EquationType.float
-
-// Type-safe results
-switch (result.type) {
- case EquationType.integer:
- final intValue = result.asInt();
- case EquationType.float:
- final doubleValue = result.asDouble();
- case EquationType.string:
- final stringValue = result.asString();
- case EquationType.boolean:
- final boolValue = result.asBool();
-}
-```
+- **Frontend Projects**: React, Vue, Angular, vanilla JavaScript
+- **Node.js Applications**: Both CommonJS and ES modules
+- **TypeScript Projects**: Full type definitions included
+- **Bundlers**: Webpack, Rollup, Vite, Parcel
+- **Flutter Web**: Via dart:js_interop integration
-##### **Step 4: Package Configuration and Publishing**
-
-**NPM Package (package.json):**
-```json
-{
- "name": "parsec-equations-lib",
- "version": "1.0.0",
- "description": "Fast mathematical expression evaluator powered by WebAssembly",
- "main": "index.js",
- "types": "types.d.ts",
- "files": ["core/", "js/", "types.d.ts"],
- "keywords": ["math", "equations", "wasm", "calculator", "expressions"],
- "engines": { "node": ">=16.0.0" },
- "browser": "js/equations-evaluator.js"
-}
-```
+## โจ Library Implementation
+
+**Parsec Web** is a complete, production-ready library that includes:
-**Pub Package (pubspec.yaml):**
-```yaml
-name: parsec_equations_lib
-version: 1.0.0
-description: Fast mathematical expression evaluator for Flutter Web using WebAssembly
-homepage: https://github.com/your-org/parsec-equations-lib
+**Core Implementation:**
+- Equations-parser C++ library integrated via WebAssembly
+- Native type conversion system with automatic C++ to JavaScript type mapping
+- Comprehensive equation evaluation with full feature parity
+- Professional testing framework with Vitest for complete coverage
-environment:
- sdk: '>=3.0.0 <4.0.0'
- flutter: '>=3.10.0'
+**Key Components:**
+- **WebAssembly Module**: Compiled equations-parser C++ library
+- **JavaScript Wrapper**: Clean API with error handling and type conversion
+- **Testing Suite**: Unit tests, integration tests, error handling, and performance benchmarks
+- **Multi-format Package**: CommonJS, ES6 modules, and TypeScript definitions
-platforms:
- web:
+**Supported Features:**
+- Mathematical functions (trigonometry, logarithms, arithmetic)
+- String manipulation functions
+- Complex number operations
+- Array/matrix functions
+- Date/time calculations
+- Conditional logic and comparison operators
-dependencies:
- flutter:
- sdk: flutter
- js: ^0.6.7
+## ๐ Project Structure
-dev_dependencies:
- flutter_test:
- sdk: flutter
+```
+parsec-web/
+โโโ cpp/ # C++ source files
+โ โโโ equations-parser/ # Git submodule with C++ library
+โโโ js/ # JavaScript wrapper libraries
+โ โโโ equations_parser_wrapper.js # Clean API for WASM functions
+โโโ tests/ # Vitest test suites
+โ โโโ unit/ # Unit tests by function category
+โ โโโ integration/ # Integration tests
+โโโ wasm/ # Generated WASM files (build output)
+โโโ docs/ # Documentation (if any)
+โ โโโ (documentation files)
+โโโ build.sh # WebAssembly build script
+โโโ README.md # This file
```
-##### **Step 5: Cross-Platform Compatibility**
-- **Unified WASM module**: Same WebAssembly binary works in both environments
-- **Consistent API design**: Similar method names and behavior patterns
-- **Error code mapping**: Standardized error types across platforms
-- **Performance optimization**: Efficient memory management and module loading
-- **Browser compatibility**: Support for modern browsers (ES6+ for JS, recent Flutter Web)
+## ๐งช Testing Strategy
-#### ๐ฏ **Flutter Web Integration Details**
+The project uses **Vitest** as the primary testing framework for comprehensive equation evaluation testing:
-##### **dart:js_interop Implementation**
-```dart
-// js_interop.dart
-@JS()
-library equations_js;
+### **Test Categories**
-import 'dart:js_interop';
+1. **Unit Tests**: Individual function categories (arithmetic, trigonometry, logarithms, strings, dates, complex, arrays)
+2. **Integration Tests**: Complex expressions with mixed types and function combinations
+3. **Error Handling**: Comprehensive validation of syntax errors, runtime errors, type errors
+4. **Performance Benchmarks**: Execution time tracking with regression detection
+5. **Cross-Browser Compatibility**: ES6 modules with WebAssembly support validation
-@JS('EquationsModule')
-external EquationsModule get equationsModule;
+### **Running Tests**
-@JS()
-@anonymous
-extension type EquationsModule._(JSObject _) implements JSObject {
- external JSPromise eval_equation(JSString equation);
- external JSNumber test_equations_parser_loaded();
-}
+```bash
+# Install dependencies
+npm install
-@JS()
-@anonymous
-extension type EquationResult._(JSObject _) implements JSObject {
- external JSString get val;
- external JSString get type;
- external JSString? get error;
-}
+# Run all tests
+npm test
+
+# Run tests in watch mode
+npm run test:watch
+
+# Generate coverage report
+npm run test:coverage
+
+# Run specific test suites
+npm run test:unit # Unit tests only
+npm run test:integration # Integration tests only
+npm run test:performance # Performance benchmarks only
```
-##### **Flutter Service Layer**
-```dart
-// equations_evaluator.dart
-class EquationsEvaluator {
- static final EquationsEvaluator _instance = EquationsEvaluator._internal();
- factory EquationsEvaluator() => _instance;
- EquationsEvaluator._internal();
-
- bool _isInitialized = false;
-
- Future initialize() async {
- if (_isInitialized) return;
-
- // Load WASM module
- await _loadWasmModule();
-
- // Test module
- final testResult = equationsModule.test_equations_parser_loaded();
- if (testResult.toDart != 42) {
- throw EquationsException('Module initialization failed');
- }
-
- _isInitialized = true;
- }
-
- Future evaluate(String equation) async {
- if (!_isInitialized) {
- throw EquationsException('Evaluator not initialized');
- }
-
- try {
- final jsResult = await equationsModule
- .eval_equation(equation.toJS)
- .toDart;
-
- return EquationResult.fromJson(jsResult.toDart);
- } catch (e) {
- throw EquationsException('Evaluation failed: $e');
- }
- }
-}
+### **Code Quality & Formatting**
+
+The project uses **Prettier** + **ESLint** for consistent code formatting and quality:
+
+```bash
+# Check code formatting
+npm run format:check
+
+# Auto-fix formatting
+npm run format
+
+# Run linting
+npm run lint
+
+# Auto-fix linting issues
+npm run lint:fix
+
+# Fix both linting and formatting
+npm run style:fix
```
-#### โ **Benefits for Multi-Platform Development**
+**Prettier Configuration:**
-1. **Code Reuse**: Same mathematical engine across JavaScript and Dart platforms
-2. **Performance Consistency**: Identical WebAssembly performance in both environments
-3. **Maintenance Efficiency**: Single WASM core to update and maintain
-4. **Type Safety**: TypeScript definitions for JS, strong typing in Dart
-5. **Easy Integration**: Simple npm install or pub get to add functionality
-6. **Framework Agnostic**: Works with React, Vue, Angular, Flutter, vanilla JS
+- Single quotes, no semicolons
+- 2-space indentation, 100 character line width
+- ES5 trailing commas, avoid arrow parentheses
-#### ๐ **Usage in Target Projects**
+## ๐ API Reference
+
+### **Core Methods**
+
+#### `parsec.eval(equation)`
+
+Evaluate a single mathematical expression.
-##### **React Project Integration**
```javascript
-// npm install parsec-equations-lib
-import { EquationsEvaluator } from 'parsec-equations-lib';
-
-function CalculatorComponent() {
- const [evaluator, setEvaluator] = useState(null);
-
- useEffect(() => {
- const init = async () => {
- const eval = new EquationsEvaluator();
- await eval.initialize();
- setEvaluator(eval);
- };
- init();
- }, []);
-
- const handleCalculate = (equation) => {
- const result = evaluator.evaluate(equation);
- setResult(result);
- };
-}
+const result = parsec.eval('2 + 3 * 4')
+// Returns: 14
+
+const text = parsec.eval('concat("Hello", " World")')
+// Returns: "Hello World"
+
+const boolean = parsec.eval('5 > 3')
+// Returns: true
```
-##### **Flutter Web Project Integration**
-```dart
-# pubspec.yaml: parsec_equations_lib: ^1.0.0
+#### `parsec.evaluateBatch(equations)`
-class CalculatorPage extends StatefulWidget {
- @override
- State createState() => _CalculatorPageState();
-}
+Evaluate multiple expressions in one call.
-class _CalculatorPageState extends State {
- final evaluator = EquationsEvaluator();
-
- @override
- void initState() {
- super.initState();
- evaluator.initialize();
- }
-
- void _handleCalculate(String equation) async {
- final result = await evaluator.evaluate(equation);
- setState(() {
- _result = result;
- });
- }
-}
+```javascript
+const results = parsec.evaluateBatch(['2+2', 'sqrt(16)', 'sin(pi/2)'])
+// Returns array of results with index information
```
-#### ๐ **Success Criteria**
-- โ **NPM Package**: Successfully published and installable via `npm install`
-- โ **Pub Package**: Successfully published and installable via `pub get`
-- โ **React Integration**: Works seamlessly in Create React App projects
-- โ **Flutter Web Integration**: Works in Flutter Web projects without issues
-- โ **Performance**: < 5ms evaluation time for complex expressions
-- โ **Bundle Size**: < 2MB total package size including WASM
-- โ **Type Safety**: Full TypeScript and Dart type definitions
-- โ **Documentation**: Complete API documentation and usage examples
-
-### ๐ Phase 5: Flutter Web Integration *(Planned)*
-**Goal**: Integrate equations-parser WASM with a small Flutter Web using `dart:js_interop`
-
-**What's planned:**
-- Clean Flutter project structure
-- `dart:js_interop` bindings for equations-parser functions
-- Abstract service interface for cross-platform compatibility
-- Web-specific service implementation
-- Flutter UI for equation input and result display
-
-### ๐ Phase 6: Cross-Platform Mobile Integration *(Optional)*
-**Goal**: Extend Flutter integration to mobile/desktop platforms
-
-**What's planned:**
-- Factory pattern for service creation
-- Platform detection (web vs mobile/desktop)
-- Platform Channel integration for mobile/desktop
-- Unified Flutter interface across all platforms
+#### `parsec.evaluateWithTimeout(equation, timeoutMs)`
-## ๐ Project Structure
+Evaluate with timeout protection.
+```javascript
+const result = await parsec.evaluateWithTimeout('complex_expression', 5000)
+// Returns: the evaluated result (number, string, or boolean)
```
-parsec-web/
-โโโ cpp/ # C++ source files
-โ โโโ math_functions.cpp # Math functions with WASM bindings
-โโโ js/ # JavaScript wrapper libraries
-โ โโโ math_wrapper.js # Clean API for WASM functions
-โโโ html/ # Test HTML files
-โ โโโ test.html # Interactive test interface
-โโโ wasm/ # Generated WASM files (build output)
-โโโ docs/ # Documentation
-โ โโโ phase1-guide.md # Detailed Phase 1 instructions
-โโโ build.sh # Emscripten compilation script
-โโโ README.md # This file
+
+### **Library Information**
+
+#### `parsec.getInfo()`
+
+Get comprehensive library metadata.
+
+```javascript
+const info = parsec.getInfo()
+console.log(info.supportedPlatforms) // ['Browser (ES6)', 'Node.js', ...]
+console.log(info.features) // ['WebAssembly performance', 'Offline capability', ...]
```
-## ๐งช Testing Strategy
+#### `parsec.getSupportedFunctions()`
+
+Get detailed information about all available mathematical functions, organized by category.
+
+### **Import Methods**
+
+#### **ES6 Modules**
+
+```javascript
+import { Parsec } from 'parsec-web'
+import Parsec from 'parsec-web' // Default import
+```
+
+#### **CommonJS**
-Each phase includes comprehensive testing:
+```javascript
+const { Parsec } = require('parsec-web')
+```
+
+#### **TypeScript**
-1. **Build Verification**: Compilation succeeds without errors
-2. **Module Loading**: WASM loads correctly in browser
-3. **Function Testing**: All exposed functions work as expected
-4. **Error Handling**: Proper error messages and recovery
-5. **Performance**: Acceptable execution times
-6. **Cross-Browser**: Works in major browsers
+```typescript
+import { Parsec, EquationResult, BatchEvaluationResult } from 'parsec-web'
+```
## ๐ Documentation
-- **[Phase 1 Guide](docs/phase1-guide.md)**: Complete setup and testing instructions
- **Code Comments**: Detailed explanations in all source files
- **Build Scripts**: Self-documenting with extensive comments
+- **Development Guide**: See CLAUDE.md for detailed development instructions
## ๐ง Technical Stack
- **C++17+**: Modern C++ with Emscripten bindings
- **Emscripten**: Latest version with optimized flags
-- **JavaScript ES6**: Modules, async/await, classes
+- **JavaScript ES6+**: Modules, async/await, classes
+- **TypeScript**: Full type definitions included
- **WebAssembly**: Binary format with JavaScript integration
- **Equations-Parser Library**: Advanced mathematical expression evaluator
-- **Flutter 3.x**: `dart:js_interop` for web integration (Phase 3+)
-
-## ๐ Progress Overview
-
-1. โ **Phase 1 Complete**: Toy WebAssembly integration working
-2. **Phase 2 Ready**: Integrate real equations-parser C++ library
- - Set up equations-parser as git submodule
- - Replace toy functions with comprehensive equation evaluation
- - Create advanced testing interface for all equation types
-3. **Phase 3**: Automated tests for the WebAssembly library compiled from equations-parser
-4. **Phase 4**: Flutter Web integration with equations-parser WASM
-5. **Phase 5**: Cross-platform mobile/desktop integration (optional)
+- **Vitest**: Modern testing framework for comprehensive test coverage
+- **Prettier + ESLint**: Code formatting and quality assurance
+- **Multi-format exports**: ES6, CommonJS, UMD compatibility
+- **Flutter 3.x**: `dart:js_interop` for web integration (future enhancement)
+
+## ๐ฎ Future Development
+
+### Flutter Web Integration
+
+**Goal**: Create Flutter Web bindings using `dart:js_interop`
+
+**Planned Features**:
+- Dart type-safe API wrapper
+- Asset bundling for Flutter projects
+- Future-based async/await patterns
+- Cross-platform compatibility
+
+**Usage Preview**:
+
+```dart
+import 'package:parsec_equations_lib/parsec_equations_lib.dart';
+
+final parsec = Parsec();
+await parsec.initialize();
+
+final result = await parsec.evaluate('2 + 3 * sin(pi/2)');
+print(result.value); // 5
+```
+
+### Cross-Platform Mobile Integration
+
+**Optional Extension**: Mobile/desktop platform support through Flutter
+
+**Planned Features**:
+- Platform detection (web vs mobile/desktop)
+- Platform Channel integration for mobile/desktop
+- Unified Flutter interface across all platforms
+- Factory pattern for service creation
diff --git a/build-equations-parser.sh b/build-equations-parser.sh
deleted file mode 100755
index da0a2d4..0000000
--- a/build-equations-parser.sh
+++ /dev/null
@@ -1,91 +0,0 @@
-#!/bin/bash
-
-# Equations-Parser WebAssembly Build Script for Phase 2
-# This script compiles the equations-parser C++ library to WebAssembly using Emscripten
-
-set -e # Exit on any error
-
-echo "๐งฎ Building Equations-Parser WebAssembly module..."
-echo "=================================================="
-
-# Check if Emscripten is available
-if ! command -v emcc &> /dev/null; then
- echo "โ Error: Emscripten (emcc) not found!"
- echo "Please install Emscripten:"
- echo "1. Install via `apt-get install emscripten` (Linux)"
- echo "2. Download from: https://emscripten.org/docs/getting_started/downloads.html"
- echo "3. Or install via emsdk:"
- echo " git clone https://github.com/emscripten-core/emsdk.git"
- echo " cd emsdk"
- echo " ./emsdk install latest"
- echo " ./emsdk activate latest"
- echo " source ./emsdk_env.sh"
- exit 1
-fi
-
-# Create wasm output directory if it doesn't exist
-mkdir -p wasm
-
-echo "๐ Input files:"
-echo " - cpp/equations_parser_wrapper.cpp (WebAssembly wrapper)"
-echo " - equations-parser/parser/*.cpp (equations-parser library)"
-echo "๐ Output directory: wasm/"
-
-# Collect all equations-parser source files
-PARSER_SOURCES=$(find equations-parser/parser -name "*.cpp" -type f | tr '\n' ' ')
-echo "๐ Found equations-parser sources: $PARSER_SOURCES"
-
-# Compile equations-parser library + WebAssembly wrapper
-# Key Emscripten flags explained:
-# -s WASM=1 : Generate WebAssembly instead of asm.js
-# -s EXPORTED_FUNCTIONS : Export specific C functions to JavaScript
-# -s EXPORTED_RUNTIME_METHODS : Export runtime methods like ccall, cwrap
-# -s ALLOW_MEMORY_GROWTH=1 : Allow memory to grow dynamically
-# -s MODULARIZE=1 : Wrap output in a function for import/require
-# -s EXPORT_NAME="EquationsParserModule" : Name of the exported module
-# -s EXPORT_ES6=1 : Use ES6 module syntax (import/export)
-# --bind : Enable C++ class/function bindings
-# -O2 : Optimize for speed and size
-# -g : Include debug symbols
-# -s ENVIRONMENT=web : Optimize for browser environment only
-# -s SINGLE_FILE=1 : Embed WASM binary inside JS file
-# -I equations-parser/parser : Include directory for headers
-
-echo "๐ง Compiling with Emscripten..."
-
-emcc cpp/equations_parser_wrapper.cpp $PARSER_SOURCES \
- -I equations-parser/parser \
- -std=c++17 \
- -s WASM=1 \
- -s ALLOW_MEMORY_GROWTH=1 \
- -s MODULARIZE=1 \
- -s EXPORT_NAME="EquationsParserModule" \
- -s EXPORT_ES6=1 \
- --bind \
- -O2 \
- -g \
- -s ENVIRONMENT=web \
- -s SINGLE_FILE=1 \
- -o wasm/equations_parser.js
-
-if [ $? -eq 0 ]; then
- echo "โ Build successful!"
- echo "Generated files:"
- ls -la wasm/equations_parser.js
- echo ""
- echo "๐ Next steps:"
- echo "1. The equations-parser WASM module is embedded in wasm/equations_parser.js"
- echo "2. Update JavaScript wrapper to use eval_equation function"
- echo "3. Update HTML test to use the new equations-parser module"
- echo "4. Test with real mathematical expressions!"
- echo ""
- echo "๐งช Test examples you can now use:"
- echo ' - "sin(pi/2)" โ 1.0'
- echo ' - "sqrt(16)" โ 4.0'
- echo ' - "2 + 3 * 4" โ 14.0'
- echo ' - "concat(\"Hello\", \" \", \"World\")" โ "Hello World"'
- echo ' - "5 > 3 ? \"yes\" : \"no\"" โ "yes"'
-else
- echo "โ Build failed!"
- exit 1
-fi
diff --git a/build.sh b/build.sh
index e9cece1..e163979 100755
--- a/build.sh
+++ b/build.sh
@@ -1,12 +1,12 @@
#!/bin/bash
-# WebAssembly Build Script for Phase 1
-# This script compiles C++ code to WebAssembly using Emscripten
+# Equations-Parser WebAssembly Build Script for Phase 2
+# This script compiles the equations-parser C++ library to WebAssembly using Emscripten
set -e # Exit on any error
-echo "๐ง Building WebAssembly module..."
-echo "=================================="
+echo "๐งฎ Building Equations-Parser WebAssembly module..."
+echo "=================================================="
# Check if Emscripten is available
if ! command -v emcc &> /dev/null; then
@@ -26,49 +26,65 @@ fi
# Create wasm output directory if it doesn't exist
mkdir -p wasm
-echo "๐ Input file: cpp/math_functions.cpp"
+echo "๐ Input files:"
+echo " - cpp/equations_parser_wrapper.cpp (WebAssembly wrapper)"
+echo " - equations-parser/parser/*.cpp (equations-parser library)"
echo "๐ Output directory: wasm/"
-# Compile C++ to WebAssembly
+# Collect all equations-parser source files
+PARSER_SOURCES=$(find equations-parser/parser -name "*.cpp" -type f | tr '\n' ' ')
+echo "๐ Found equations-parser sources: $PARSER_SOURCES"
+
+# Compile equations-parser library + WebAssembly wrapper
# Key Emscripten flags explained:
# -s WASM=1 : Generate WebAssembly instead of asm.js
# -s EXPORTED_FUNCTIONS : Export specific C functions to JavaScript
# -s EXPORTED_RUNTIME_METHODS : Export runtime methods like ccall, cwrap
# -s ALLOW_MEMORY_GROWTH=1 : Allow memory to grow dynamically
# -s MODULARIZE=1 : Wrap output in a function for import/require
-# -s EXPORT_NAME="MathModule" : Name of the exported module
+# -s EXPORT_NAME="EquationsParserModule" : Name of the exported module
# -s EXPORT_ES6=1 : Use ES6 module syntax (import/export)
# --bind : Enable C++ class/function bindings
# -O2 : Optimize for speed and size
# -g : Include debug symbols
# -s ENVIRONMENT=web : Optimize for browser environment only
# -s SINGLE_FILE=1 : Embed WASM binary inside JS file
+# -I equations-parser/parser : Include directory for headers
+
+echo "๐ง Compiling with Emscripten..."
-emcc cpp/math_functions.cpp \
+emcc cpp/equations_parser_wrapper.cpp $PARSER_SOURCES \
+ -I equations-parser/parser \
+ -std=c++17 \
-s WASM=1 \
- -s EXPORTED_FUNCTIONS='["_sum", "_multiply", "_test_wasm_loaded"]' \
- -s EXPORTED_RUNTIME_METHODS='["ccall", "cwrap"]' \
-s ALLOW_MEMORY_GROWTH=1 \
-s MODULARIZE=1 \
- -s EXPORT_NAME="MathModule" \
+ -s EXPORT_NAME="EquationsModule" \
-s EXPORT_ES6=1 \
--bind \
- -O2 \
- -g \
+ -O3 \
-s ENVIRONMENT=web \
-s SINGLE_FILE=1 \
- -o wasm/math_functions.js
+ -o wasm/equations_parser.js
if [ $? -eq 0 ]; then
echo "โ Build successful!"
echo "Generated files:"
- ls -la wasm/
+ ls -la wasm/equations_parser.js
echo ""
echo "๐ Next steps:"
- echo "1. The WASM module is embedded in wasm/math_functions.js"
- echo "2. You can now use this in your HTML/JavaScript files"
- echo "3. Run the HTML test to verify everything works"
+ echo "1. The equations-parser WASM module is embedded in wasm/equations_parser.js"
+ echo "2. Update JavaScript wrapper to use eval_equation function"
+ echo "3. Update HTML test to use the new equations-parser module"
+ echo "4. Test with real mathematical expressions!"
+ echo ""
+ echo "๐งช Test examples you can now use:"
+ echo ' - "sin(pi/2)" โ 1.0'
+ echo ' - "sqrt(16)" โ 4.0'
+ echo ' - "2 + 3 * 4" โ 14.0'
+ echo ' - "concat(\"Hello\", \" \", \"World\")" โ "Hello World"'
+ echo ' - "5 > 3 ? \"yes\" : \"no\"" โ "yes"'
else
echo "โ Build failed!"
exit 1
-fi
\ No newline at end of file
+fi
diff --git a/cpp/math_functions.cpp b/cpp/math_functions.cpp
deleted file mode 100644
index 5cc24ad..0000000
--- a/cpp/math_functions.cpp
+++ /dev/null
@@ -1,54 +0,0 @@
-#include
-#include
-#include
-
-/**
- * Basic mathematical functions for WebAssembly integration testing
- * These functions will be exposed to JavaScript through Emscripten bindings
- */
-
-extern "C" {
- /**
- * Adds two numbers together
- * @param a First number
- * @param b Second number
- * @return Sum of a and b
- */
- EMSCRIPTEN_KEEPALIVE
- double sum(double a, double b) {
- std::cout << "C++: Computing sum(" << a << ", " << b << ") = " << (a + b) << std::endl;
- return a + b;
- }
-
- /**
- * Multiplies two numbers together
- * @param a First number
- * @param b Second number
- * @return Product of a and b
- */
- EMSCRIPTEN_KEEPALIVE
- double multiply(double a, double b) {
- std::cout << "C++: Computing multiply(" << a << ", " << b << ") = " << (a * b) << std::endl;
- return a * b;
- }
-
- /**
- * Test function to verify WASM is loaded correctly
- * @return Test confirmation number
- */
- EMSCRIPTEN_KEEPALIVE
- int test_wasm_loaded() {
- std::cout << "C++: WASM module loaded successfully!" << std::endl;
- return 42;
- }
-}
-
-// Alternative binding method using Embind (more C++ friendly)
-// This allows for more complex types and better integration
-using namespace emscripten;
-
-EMSCRIPTEN_BINDINGS(math_module) {
- function("sum", &sum);
- function("multiply", &multiply);
- function("test_wasm_loaded", &test_wasm_loaded);
-}
\ No newline at end of file
diff --git a/docs/phase1-guide.md b/docs/phase1-guide.md
deleted file mode 100644
index f46fcee..0000000
--- a/docs/phase1-guide.md
+++ /dev/null
@@ -1,257 +0,0 @@
-# Phase 1: WebAssembly + JavaScript Integration Guide
-
-This guide provides complete instructions for setting up and testing the basic WebAssembly integration with C++ math functions.
-
-## ๐ฏ Goals
-
-- Create C++ functions that can be called from JavaScript
-- Compile C++ to WebAssembly using Emscripten
-- Create a JavaScript wrapper for easy integration
-- Test everything with a complete HTML interface
-
-## ๐ Project Structure
-
-```
-parsec-web/
-โโโ cpp/ # C++ source files
-โ โโโ math_functions.cpp # Basic math functions (sum, multiply)
-โโโ js/ # JavaScript wrapper libraries
-โ โโโ math_wrapper.js # Clean JS interface for WASM functions
-โโโ html/ # Test HTML files
-โ โโโ test.html # Interactive test page
-โโโ wasm/ # Generated WebAssembly files (created by build)
-โโโ docs/ # Documentation
-โ โโโ phase1-guide.md # This guide
-โโโ build.sh # Compilation script
-```
-
-## ๐ง Prerequisites
-
-### 1. Install Emscripten
-
-**Option A: Using emsdk (Recommended)**
-```bash
-# Download and install emsdk
-git clone https://github.com/emscripten-core/emsdk.git
-cd emsdk
-
-# Install and activate the latest version
-./emsdk install latest
-./emsdk activate latest
-
-# Set up environment variables
-source ./emsdk_env.sh
-```
-
-**Option B: Package Manager**
-```bash
-# Ubuntu/Debian
-sudo apt-get install emscripten
-
-# macOS with Homebrew
-brew install emscripten
-```
-
-### 2. Verify Installation
-```bash
-# Check if Emscripten is available
-emcc --version
-
-# Should output something like:
-# emcc (Emscripten gcc/clang-like replacement + linker emulating GNU ld) 3.1.x
-```
-
-## ๐ Building the Project
-
-### Step 1: Build WebAssembly Module
-```bash
-# From the project root directory
-chmod +x build.sh
-./build.sh
-```
-
-**Expected Output:**
-```
-๐ง Building WebAssembly module...
-==================================
-๐ Input file: cpp/math_functions.cpp
-๐ Output directory: wasm/
-โ Build successful!
-Generated files:
--rw-r--r-- 1 user user 234567 date time math_functions.js
-```
-
-### Step 2: Start Local Server
-Since we're using ES6 modules, you need to serve files over HTTP:
-
-```bash
-# Option 1: Python (if available)
-python3 -m http.server 8000
-
-# Option 2: Node.js
-npx serve -s . -p 8000
-
-# Option 3: Any other static file server
-```
-
-### Step 3: Open Test Page
-Open your browser and navigate to:
-```
-http://localhost:8000/html/test.html
-```
-
-## ๐งช Testing the Implementation
-
-### Automated Testing
-
-1. **Page Load Test**: The page should load without errors
-2. **Module Loading**: You should see "โ WebAssembly module ready!" status
-3. **Function Tests**: Click "Run All Tests" to execute comprehensive tests
-
-### Manual Testing
-
-1. **Sum Function**:
- - Enter values like `5.5` and `3.2`
- - Click "Calculate"
- - Should display result: `8.7`
-
-2. **Multiply Function**:
- - Enter values like `4` and `7`
- - Click "Calculate"
- - Should display result: `28`
-
-### Console Output
-Check the "Console Output" section on the test page for detailed logs:
-```
-[timestamp] C++: WASM module loaded successfully!
-[timestamp] C++: Computing sum(5.5, 3.2) = 8.7
-[timestamp] JS: Result = 8.7
-```
-
-## ๐ Understanding the Components
-
-### 1. C++ Functions (`cpp/math_functions.cpp`)
-
-The C++ code uses Emscripten bindings to expose functions to JavaScript:
-
-```cpp
-// Using extern "C" for simple C-style exports
-extern "C" {
- EMSCRIPTEN_KEEPALIVE
- double sum(double a, double b) { /* ... */ }
-}
-
-// Using Embind for more advanced C++ features
-EMSCRIPTEN_BINDINGS(math_module) {
- function("sum", &sum);
- function("multiply", &multiply);
-}
-```
-
-**Key Points:**
-- `EMSCRIPTEN_KEEPALIVE`: Prevents function from being optimized out
-- `extern "C"`: C-style linkage for simple integration
-- `EMSCRIPTEN_BINDINGS`: C++ style bindings with type safety
-
-### 2. Emscripten Build Flags (`build.sh`)
-
-Important compilation flags explained:
-
-```bash
-emcc cpp/math_functions.cpp \
- -s WASM=1 # Generate WebAssembly (not asm.js)
- -s MODULARIZE=1 # Create importable module
- -s EXPORT_NAME="MathModule" # Module name for imports
- --bind # Enable Embind C++ bindings
- -s SINGLE_FILE=1 # Embed WASM in JS for easy distribution
- -O2 # Optimization level 2
-```
-
-### 3. JavaScript Wrapper (`js/math_wrapper.js`)
-
-The wrapper provides:
-- **Async Loading**: Proper module initialization
-- **Error Handling**: Comprehensive error checking
-- **Type Safety**: Input validation
-- **Clean API**: Simple function calls
-
-```javascript
-// Initialize the module
-const mathWrapper = new MathWasmWrapper();
-await mathWrapper.initialize();
-
-// Use the functions
-const result = mathWrapper.sum(5, 3);
-```
-
-### 4. HTML Test Interface (`html/test.html`)
-
-Features:
-- **Interactive UI**: Manual testing with input fields
-- **Automated Tests**: Comprehensive test suite
-- **Console Output**: Real-time logging display
-- **Error Handling**: Clear error messages
-
-## โ Troubleshooting
-
-### Common Issues
-
-**1. "emcc: command not found"**
-```bash
-# Make sure Emscripten is installed and in PATH
-source /path/to/emsdk/emsdk_env.sh
-```
-
-**2. "Module loading failed"**
-- Check that you're serving files over HTTP (not file://)
-- Verify `wasm/math_functions.js` was generated
-- Check browser console for detailed error messages
-
-**3. "Cross-origin requests blocked"**
-```bash
-# Start a local server instead of opening file directly
-python3 -m http.server 8000
-```
-
-**4. Functions not working**
-- Verify in browser console that module loaded successfully
-- Check if test function returns 42
-- Look for C++ console output in the Console Output section
-
-### Debug Steps
-
-1. **Check Build Output**: Ensure `build.sh` completes without errors
-2. **Verify Generated Files**: Check that `wasm/math_functions.js` exists
-3. **Browser Console**: Look for JavaScript errors
-4. **Network Tab**: Verify all files are loading correctly
-
-## โ Success Criteria
-
-Phase 1 is successful when:
-
-1. โ **Build completes without errors**
-2. โ **Test page loads and shows "WebAssembly module ready!"**
-3. โ **Manual tests work with expected results**
-4. โ **Automated tests pass without errors**
-5. โ **Console shows C++ debug output**
-6. โ **No JavaScript errors in browser console**
-
-## ๐ Next Steps
-
-Once Phase 1 is working:
-
-1. **Understand the Architecture**: Review how data flows from JavaScript โ WASM โ C++
-2. **Experiment**: Try adding new functions or modifying existing ones
-3. **Prepare for Phase 2**: We'll integrate this into Flutter Web using `dart:js_interop`
-
-## ๐ Key Learnings
-
-After completing Phase 1, you should understand:
-
-- How to compile C++ to WebAssembly with Emscripten
-- How to create JavaScript bindings for WASM functions
-- How to handle async module loading in browsers
-- How to create a clean API wrapper for WASM integration
-- How to test and debug WASM applications
-
-This foundation will be crucial for the Flutter integration in subsequent phases.
\ No newline at end of file
diff --git a/html/equations-parser-test.html b/html/equations-parser-test.html
index 13adf26..4e7641e 100644
--- a/html/equations-parser-test.html
+++ b/html/equations-parser-test.html
@@ -505,7 +505,7 @@