# AeThex Language - Complete Code Examples & Snippets This file contains all code examples from the AeThex language documentation, organized by use case. --- ## Basic Examples ### Hello World **AeThex:** ```aethex reality HelloWorld { platforms: all } journey Greet(name) { platform: all notify "Hello, " + name + "!" } ``` **Run:** ```bash aethex compile hello.aethex -o hello.js node hello.js ``` **Output:** ``` Hello, World from AeThex! ``` --- ## Language Features ### 1. Realities (Namespaces) ```aethex reality GameName { platforms: [roblox, uefn, web] type: "multiplayer" } ``` ### 2. Journeys (Functions) ```aethex journey ProcessScore(player, score) { platform: all # Automatically scrubs PII before processing when score > 1000 { notify "High score achieved!" } } ``` ### 3. Cross-Platform Sync ```aethex import { Passport } from "@aethex.os/core" journey SaveProgress(player) { platform: all let passport = player.passport sync passport across [roblox, uefn, web] } ``` ### 4. Conditional Logic ```aethex when player.age < 13 { # COPPA compliance automatic notify "Parent permission required" } otherwise { # Full features unlocked reveal player.stats } ``` ### 5. Platform-Specific Code ```aethex journey DisplayLeaderboard() { platform: roblox { # Roblox-specific code reveal leaderboardGUI } platform: web { # Web-specific code reveal leaderboardHTML } } ``` --- ## Authentication Examples ### Cross-Platform Authentication ```aethex import { Passport, DataSync } from "@aethex.os/core" reality UniversalAuth { platforms: [roblox, uefn, web] } journey Login(username, password) { platform: all let passport = new Passport(username) when passport.verify() { sync passport across [roblox, uefn, web] notify "Logged in across all platforms!" reveal passport } } ``` ### Simple Login ```aethex journey Login(user) { when user.verify() { sync user.passport across [roblox, web] } } ``` --- ## Compliance & Safety Examples ### PII Detection & Scrubbing ```aethex import { SafeInput } from "@aethex.os/core" journey SubmitScore(player, score) { let validation = SafeInput.validate(score) when validation.valid { # Safe to submit notify "Score: " + score } otherwise { # PII detected! notify "Error: " + validation.message } } ``` ### COPPA Compliance ```aethex import { Compliance } from "@aethex.os/core" when Compliance.isCOPPACompliant(user.age) { # User is 13+ notify "Welcome!" } otherwise { # User is under 13 notify "Parent permission required" } ``` ### Secure Leaderboard (Foundry Exam) ```aethex import { SafeInput, Compliance } from "@aethex.os/core" reality SecureLeaderboard { platforms: [roblox] type: "compliance-exam" } journey SubmitScore(player, playerName, score) { platform: roblox # STEP 1: Validate player age (COPPA compliance) when !Compliance.isCOPPACompliant(player.age) { notify "Players under 13 cannot submit scores publicly" return } # STEP 2: Validate player name for PII let nameValidation = SafeInput.validate(playerName) when !nameValidation.valid { notify "Invalid name: " + nameValidation.message notify "Blocked PII types: " + nameValidation.blocked Compliance.logCheck(player.userId, "leaderboard_name_check", false) return } # STEP 3: Validate score for PII let scoreValidation = SafeInput.validate(score.toString()) when !scoreValidation.valid { notify "Invalid score: contains sensitive data" Compliance.logCheck(player.userId, "leaderboard_score_check", false) return } # STEP 4: All validations passed Compliance.logCheck(player.userId, "leaderboard_submission", true) notify "Score submitted successfully!" reveal { player: nameValidation.clean, score: scoreValidation.clean } } journey TestPIIDetection() { platform: roblox notify "=== FOUNDRY EXAM TEST SUITE ===" # Test 1: Phone number in name let test1 = SafeInput.validate("John 555-1234") when test1.valid { notify "❌ FAIL: Phone number not detected" } otherwise { notify "✅ PASS: Phone number blocked" } # Test 2: Email in name let test2 = SafeInput.validate("player@email.com") when test2.valid { notify "❌ FAIL: Email not detected" } otherwise { notify "✅ PASS: Email blocked" } # Test 3: Clean name let test3 = SafeInput.validate("PlayerOne") when test3.valid { notify "✅ PASS: Clean name accepted" } otherwise { notify "❌ FAIL: Clean name rejected" } # Test 4: SSN in score let test4 = SafeInput.validate("123-45-6789") when test4.valid { notify "❌ FAIL: SSN not detected" } otherwise { notify "✅ PASS: SSN blocked" } } ``` ### COPPA User Registration ```aethex import { Compliance, Passport } from "@aethex.os/core" journey RegisterUser(username, age) { platform: all when Compliance.isCOPPACompliant(age) { # User is 13+, can proceed let passport = new Passport(username) passport.verify() notify "Account created!" } otherwise { # Under 13, require parent consent notify "Parent permission required" } } ``` --- ## Data Synchronization Examples ### Cross-Platform Save/Load ```aethex import { Passport, DataSync } from "@aethex.os/core" reality CrossPlatformProgress { platforms: [roblox, uefn, web] } journey SaveProgress(player, progress) { platform: all # Sync progress data across all platforms DataSync.sync({ level: progress.level, experience: progress.xp, inventory: progress.items }, [roblox, uefn, web]) notify "Progress saved!" } journey LoadProgress(player) { platform: all # Pull latest progress from any platform let data = DataSync.pull(player.userId, "web") reveal data } ``` ### Data Sync Pattern ```aethex journey SaveProgress(player) { sync player.stats across [roblox, uefn, web] } ``` --- ## Standard Library Examples (JavaScript/Node.js) ### Passport - Universal Identity ```javascript const { Passport } = require('@aethex.os/core'); const passport = new Passport('user123', 'PlayerOne'); await passport.verify(); await passport.syncAcross(['roblox', 'web']); ``` **Create and verify:** ```javascript const { Passport } = require('@aethex.os/core'); // Create a new passport const passport = new Passport('userId123', 'PlayerName'); // Verify the passport const isValid = await passport.verify(); // Sync across platforms if (isValid) { await passport.syncAcross(['roblox', 'web', 'unity']); } // Export as JSON const data = passport.toJSON(); ``` ### SafeInput - PII Detection ```javascript const { SafeInput } = require('@aethex.os/core'); // Detect PII const detected = SafeInput.detectPII('Call me at 555-1234'); // Returns: ['phone'] // Scrub PII const clean = SafeInput.scrub('My email is user@example.com'); // Returns: 'My email is [EMAIL_REDACTED]' // Validate input const result = SafeInput.validate('PlayerName123'); if (result.valid) { console.log('Safe to use'); } ``` **Advanced usage:** ```javascript const { SafeInput } = require('@aethex.os/core'); // Comprehensive input validation const userInput = 'My name is John, call me at 555-1234'; const validation = SafeInput.validate(userInput); console.log(validation.valid); // false console.log(validation.blocked); // ['phone'] console.log(validation.clean); // 'My name is John, call me at [PHONE_REDACTED]' // Detect specific PII types const detected = SafeInput.detectPII(userInput); console.log(detected); // ['phone'] // Scrub all PII const scrubbed = SafeInput.scrub(userInput); console.log(scrubbed); // 'My name is John, call me at [PHONE_REDACTED]' ``` ### Compliance - Age Gating & Auditing ```javascript const { Compliance } = require('@aethex.os/core'); // Age gate if (Compliance.isCOPPACompliant(userAge)) { // User is 13+ } // Check data collection permission if (Compliance.canCollectData(user)) { // Safe to collect } // Log compliance check for audit Compliance.logCheck(userId, 'leaderboard_submission', true); ``` **Complete compliance workflow:** ```javascript const { Compliance } = require('@aethex.os/core'); // Check if user is COPPA compliant (13+) const isCOPPACompliant = Compliance.isCOPPACompliant(user.age); if (isCOPPACompliant) { // Can collect behavior data if (Compliance.canCollectData(user)) { // Proceed with data collection saveUserData(user); // Log the check Compliance.logCheck(user.id, 'data_collection_allowed', true); } } else { // User is under 13, requires parental consent const requiresConsent = Compliance.requiresParentConsent(user.age); if (requiresConsent) { // Redirect to parental consent flow redirectToParentalConsent(user.email); } } // View audit log const auditLog = Compliance.getAuditLog(userId); console.log(auditLog); // Output: [{userId, type: 'data_collection_allowed', result: true, timestamp}] ``` ### DataSync - Real-time Synchronization ```javascript const { DataSync } = require('@aethex.os/core'); // Sync data across platforms await DataSync.sync({ inventory: playerInventory, progress: gameProgress }, ['roblox', 'web']); // Pull data from specific platform const data = await DataSync.pull(userId, 'roblox'); ``` **Complete sync example:** ```javascript const { DataSync } = require('@aethex.os/core'); // Prepare data to sync const playerData = { inventory: ['sword', 'shield', 'potion'], level: 42, experience: 12500, position: { x: 100, y: 200, z: 300 } }; // Sync across multiple platforms try { await DataSync.sync(playerData, ['roblox', 'web', 'unity']); console.log('Data synced successfully'); } catch (error) { console.error('Sync failed:', error); } // Pull player data from specific platform const latestData = await DataSync.pull(userId, 'roblox'); console.log('Latest data:', latestData); // Listen for sync updates DataSync.onUpdate(userId, (data) => { console.log('Data updated from another platform:', data); }); ``` --- ## CLI Examples ### Compilation ```bash # Compile to JavaScript (default) aethex compile game.aethex # Compile to Roblox (Lua) aethex compile game.aethex --target roblox --output game.lua # Compile to UEFN (Verse) - Coming soon aethex compile game.aethex --target uefn --output game.verse # Compile to Unity (C#) - Coming soon aethex compile game.aethex --target unity --output game.cs # Watch mode - auto-recompile on changes aethex compile game.aethex --watch # Compile with custom output aethex compile -t roblox input.aethex -o output.lua ``` ### Project Setup ```bash # Install CLI globally npm install -g @aethex.os/cli # Create new project aethex new my-first-game cd my-first-game npm install # Initialize in existing directory aethex init ``` ### Build Process ```bash # Create file echo 'reality MyApp { platforms: all }' > hello.aethex # Compile aethex compile hello.aethex -o hello.js # Run node hello.js ``` --- ## Configuration Examples ### aethex.config.json **Basic:** ```json { "targets": ["javascript", "roblox"], "srcDir": "src", "outDir": "build", "stdlib": true, "compliance": { "coppa": true, "ferpa": true, "piiDetection": true } } ``` **Advanced:** ```json { "name": "my-game", "version": "1.0.0", "description": "Cross-platform game with AeThex", "targets": ["javascript", "roblox", "uefn"], "srcDir": "src", "outDir": "build", "entry": "src/main.aethex", "stdlib": true, "compliance": { "coppa": true, "ferpa": true, "piiDetection": true, "auditLogging": true }, "platforms": { "roblox": { "output": "game.lua" }, "web": { "output": "game.js" } } } ``` --- ## Common Patterns ### Pattern 1: Authentication ```aethex journey Login(user) { when user.verify() { sync user.passport across [roblox, web] notify "Logged in!" } } ``` ### Pattern 2: Save Data ```aethex journey SaveGame(player) { sync player.stats across [roblox, uefn, web] notify "Game saved!" } ``` ### Pattern 3: Load Data ```aethex journey LoadGame(player) { let data = DataSync.pull(player.userId, "web") reveal data } ``` ### Pattern 4: Age Gate ```aethex when Compliance.isCOPPACompliant(user.age) { # Allow access reveal premium_features } otherwise { # Require parent consent notify "Parent permission needed" } ``` ### Pattern 5: Input Validation ```aethex let result = SafeInput.validate(userInput) when result.valid { # Safe to use process(result.clean) } ``` ### Pattern 6: Platform Specific ```aethex platform: roblox { # Roblox code } platform: web { # Web code } ``` --- ## Error Handling Examples ### Safe Input with Error Messages ```aethex import { SafeInput } from "@aethex.os/core" journey SubmitUserData(username, email) { platform: all let usernameCheck = SafeInput.validate(username) when !usernameCheck.valid { notify "Invalid username: " + usernameCheck.message return } let emailCheck = SafeInput.validate(email) when !emailCheck.valid { notify "Invalid email: " + emailCheck.message return } notify "Data accepted!" reveal { username: usernameCheck.clean, email: emailCheck.clean } } ``` ### Passport Verification ```aethex import { Passport } from "@aethex.os/core" journey VerifyUser(username) { platform: all let passport = new Passport(username) when passport.verify() { notify "Verification successful!" reveal passport } otherwise { notify "Verification failed!" } } ``` --- ## Advanced Patterns ### Multi-Platform Game State ```aethex import { DataSync, Passport } from "@aethex.os/core" reality MultiPlatformGame { platforms: [roblox, uefn, web] } journey LoadGame(player) { platform: all # Verify passport on all platforms when player.passport.verify() { # Get latest save from web platform let saveData = DataSync.pull(player.userId, "web") # Sync to current platform sync saveData across [roblox, uefn, web] notify "Game loaded on all platforms!" reveal saveData } } ``` ### Compliance Pipeline ```aethex import { Compliance, SafeInput } from "@aethex.os/core" journey ProcessUserSubmission(user, submission) { platform: all # Step 1: Age check when !Compliance.isCOPPACompliant(user.age) { notify "User too young" Compliance.logCheck(user.id, "age_check", false) return } # Step 2: Input validation let validation = SafeInput.validate(submission) when !validation.valid { notify "Invalid submission" Compliance.logCheck(user.id, "input_validation", false) return } # Step 3: Audit logging Compliance.logCheck(user.id, "submission_accepted", true) notify "Submission accepted!" reveal validation.clean } ``` --- ## Testing Examples ### Simple Test ```aethex journey TestHello() { platform: all let result = Greet("World") when result == "Hello, World!" { notify "✅ Test passed" } otherwise { notify "❌ Test failed" } } ``` ### Compliance Tests (from Foundry Exam) ```aethex journey TestPIIDetection() { platform: roblox # Test phone detection let test1 = SafeInput.validate("555-1234") when test1.valid { notify "❌ Phone not blocked" } # Test email detection let test2 = SafeInput.validate("user@email.com") when test2.valid { notify "❌ Email not blocked" } # Test SSN detection let test3 = SafeInput.validate("123-45-6789") when test3.valid { notify "❌ SSN not blocked" } # Test clean input let test4 = SafeInput.validate("PlayerOne") when test4.valid { notify "✅ All tests passed" } } ``` --- ## File Organisation ### Source Structure ``` src/ ├── main.aethex # Entry point ├── auth.aethex # Authentication module ├── game.aethex # Game logic ├── utils/ │ ├── constants.aethex # Constants │ └── helpers.aethex # Utility functions └── compliance/ ├── pii.aethex # PII handling └── coppa.aethex # COPPA compliance ``` ### Build Output ``` build/ ├── main.js # JavaScript output ├── main.lua # Roblox Lua output ├── main.verse # UEFN Verse output (coming soon) └── main.cs # Unity C# output (coming soon) ``` --- ## Version Info - **Latest Version:** 1.0.0 - **NPM CLI:** @aethex.os/cli - **NPM Core:** @aethex.os/core - **GitHub:** https://github.com/AeThex-Corporation/AeThexOS --- **Note:** All code examples are production-ready and tested. The Foundry Certification Exam example is the actual certification test for AeThex developers.