### Rip API Basic Usage Example Source: https://github.com/shreeve/rip-lang/blob/main/packages/api/README.md Demonstrates the basic setup and usage of the Rip API framework, including defining routes for GET and POST requests, handling path parameters, and form validation using the `read()` function. It also shows how to start the server. ```coffee import { get, post, use, read, start } from '@rip-lang/api' # Context-free handlers — just return data! # Note: In Rip, the comma after a string/regex is optional when immediately # followed by an arrow function. So `get '/', ->` can be `get '/' ->` get '/' -> 'Hello, World!' get '/json' -> { message: 'It works!', timestamp: Date.now() } # Path parameters get '/users/:id' -> id = read 'id', 'id!' { user: { id, name: "User #{id}" } } # Form validation post '/signup' -> email = read 'email', 'email!' phone = read 'phone', 'phone' age = read 'age', 'int', [18, 120] { success: true, email, phone, age } start port: 3000 ``` -------------------------------- ### Rip Web Framework API Example Source: https://github.com/shreeve/rip-lang/blob/main/AGENT.md Shows a basic example of using the @rip-lang/api package for web development. It demonstrates setting up routes for GET requests, serving static files, handling not found errors, and starting the server. ```coffee import { get, use, start, notFound } from '@rip-lang/api' get '/', -> { message: 'Hello!' } get '/css/*', -> @send "public/#{@req.path.slice(5)}" notFound -> @send 'index.html', 'text/html; charset=UTF-8' start port: 3000 ``` -------------------------------- ### Rip Installation and Usage Source: https://github.com/shreeve/rip-lang/blob/main/README.md Provides commands for installing Rip globally using Bun and for running the interactive REPL or compiling Rip files to JavaScript. These are essential commands for getting started with Rip. ```bash bun add -g rip-lang # Install globally ``` ```bash rip # Interactive REPL rip file.rip # Run a file rip -c file.rip # Compile to JavaScript ``` -------------------------------- ### Start a Rip-Lang Server Source: https://github.com/shreeve/rip-lang/blob/main/packages/api/README.md Provides examples for starting a Rip-Lang server using the `start` function from `@rip-lang/api`. Shows how to specify the port and host address. ```coffee import { start } from '@rip-lang/api' start port: 3000 start port: 3000, host: '0.0.0.0' ``` -------------------------------- ### Schema Class: Creating Model Instances (JavaScript) Source: https://github.com/shreeve/rip-lang/blob/main/packages/schema/GUIDE.md Illustrates the `schema.create()` method for instantiating models with default values applied. The example shows creating a 'User' object and highlights that default properties might be added. ```javascript const schema = new Schema() const user = schema.create('User', { name: 'John', email: 'j@x.com' }) // Returns: { name: 'John', email: 'j@x.com', role: 'user', active: true, ... } ``` -------------------------------- ### Rip API Example App Configuration Source: https://github.com/shreeve/rip-lang/blob/main/packages/api/README.md Provides a complete example of an `app.rip` file for the Rip API framework. It includes importing necessary functions, setting up middleware (sessions), defining request handlers for various routes (including session management and dynamic routes), and starting the server. ```coffee import { get, post, read, session, start, use, before } from '@rip-lang/api' import { sessions } from '@rip-lang/api/middleware' use sessions() # Add secret: 'your-secret' for production before -> session.views ?= 0 session.views += 1 get '/' -> 'Hello, World!' get '/json' -> { message: 'It works!', timestamp: Date.now() } get '/users/:id' -> { user: { id: read('id', 'id!') } } get '/session' -> { views: session.views, loggedIn: session.userId? } get '/login' -> session.userId = 123; { loggedIn: true, userId: 123 } get '/logout' -> delete session.userId; { loggedOut: true } start port: 3000 ``` -------------------------------- ### Schema Definition and Instance Creation (JavaScript) Source: https://github.com/shreeve/rip-lang/blob/main/packages/schema/GUIDE.md Shows how to define a schema for a 'Patient' model, including enums, nested types, and field constraints, and then create a new 'Patient' instance using this schema. The example includes a call to validate the created instance. ```javascript // Define once in .schema const medicalSchema = parse(` @enum Gender: male, female, other, unknown @type ContactInfo phone?: phone email?: email @model Patient mrn!#: string, [6, 10] name!: string, [1, 100] dob!: date gender!: Gender ssn?: string, [9, 9] contact?: ContactInfo active: boolean, [true] @timestamps `) schema.register(medicalSchema) // Use everywhere const patient = schema.create('Patient', { mrn: 'P12345', name: 'John Doe', dob: new Date('1985-03-15'), gender: 'male', contact: { phone: '555-1234', email: 'john@example.com' } }) patient.$validate() // null = valid! ``` -------------------------------- ### Install Component Support in Compiler (JavaScript) Source: https://github.com/shreeve/rip-lang/blob/main/docs/RIP-TYPES.md Example of how to install component support by modifying the CodeGenerator prototype. This pattern is mirrored for type support. ```javascript // src/components.js — existing sidecar for the compiler export function installComponentSupport(CodeGenerator) { const proto = CodeGenerator.prototype; proto.generateComponent = function(head, rest, context) { ... }; proto.generateRender = function(head, rest, context, sexpr) { ... }; proto.buildRender = function(body) { ... }; // ... } // src/compiler.js — existing wiring import { installComponentSupport } from './components.js'; installComponentSupport(CodeGenerator); // at module level, after class definition ``` -------------------------------- ### Initialize Rip UI Application and Start Development Server Source: https://github.com/shreeve/rip-lang/blob/main/packages/ui/demo/index.html This JavaScript code snippet demonstrates how to import the Rip compiler and UI framework, create a new application instance with specified configurations (target element, compiler, state, transitions, navigation handlers), load a bundle, start the application's routing and rendering, and connect to a development server for hot reloading. It also exposes the app instance for debugging and logs initialization details. ```javascript import { compileToJS } from '/rip-ui/compiler.js'; import { createApp } from '/rip-ui/ui.js'; async function boot() { const app = createApp({ target: '#app', compile: compileToJS, state: { appName: 'Rip UI Demo', version: '0.1.0', theme: 'light' }, transition: { duration: 150 }, onNavigate: ({ path }) => console.log(`[Router] ${path}`), onError: (err) => console.error('[App]', err) }); await app.loadBundle('/rip-ui/manifest.json'); app.start(); app.watch('/rip-ui/watch'); window.app = app; console.log(`Rip UI Demo booted — ${app.fs.size} files in VFS`); console.log('Routes:', app.router.routes.map(r => r.pattern)); console.log('Try: app.set("theme", "dark") or app.go("/counter")'); } boot().catch(console.error); ``` -------------------------------- ### Real-World Example: Downloading Test Definitions with Swarm Source: https://github.com/shreeve/rip-lang/blob/main/packages/swarm/README.md This example demonstrates using Swarm to download 15,000 lab test definitions from an API concurrently using 40 workers. It includes setting up the environment, defining tasks, performing the download, and handling potential errors. The `setup` function initializes Swarm, reads input from a file, and prepares the output directory and authentication headers. The `perform` function handles the actual API request and file writing for each task. ```coffeescript import { swarm, args, init, retry, todo } from '@rip-lang/swarm' import { isMainThread } from 'worker_threads' import { readFileSync, existsSync, mkdirSync } from 'fs' import { join, resolve } from 'path' TESTS_FILE = null if isMainThread TESTS_FILE = args()[0] setup = -> unless retry() init() lines = readFileSync(TESTS_FILE, 'utf-8').trim().split('\n') for code in lines then todo(code.trim()) if code.trim() outDir = resolve('../data/tests') mkdirSync(outDir, { recursive: true }) auth = readFileSync(resolve('.auth'), 'utf-8') xibm = auth.match(/^X-IBM-Client-Id=(.*)$/m)?[1] cook = auth.match(/^lch-authorization_ACC=.*$/m)?[0] { xibm, cook, outDir } perform = (task, ctx) -> code = task.split('/').pop() return if existsSync(join(ctx.outDir, "#{code}.json")) resp = await fetch "https://api.example.com/tests/#{code}", method: 'POST' headers: { 'Cookie': ctx.cook } body: JSON.stringify { testCode: code } throw new Error("HTTP #{resp.status}") unless resp.ok await Bun.write(join(ctx.outDir, "#{code}.json"), await resp.text()) swarm { setup, perform } ``` -------------------------------- ### Rip Web Framework API Usage Source: https://github.com/shreeve/rip-lang/blob/main/packages/README.md Example of using the @rip-lang/api package for web development. It demonstrates setting up routes for GET requests, handling dynamic routes with parameters, serving static files, and starting the web server. ```coffee import { get, post, start } from '@rip-lang/api' get '/', -> { message: 'Hello, Rip!' } get '/users/:id', -> User.find!(read 'id') get '/css/*', -> @send "public/#{@req.path.slice(5)}" start port: 3000 ``` -------------------------------- ### Schema Class: Registering Schemas (JavaScript) Source: https://github.com/shreeve/rip-lang/blob/main/packages/schema/GUIDE.md Demonstrates the usage of the `schema.register()` method to add schema definitions to the Schema instance. It shows parsing a schema source string into an Abstract Syntax Tree (AST) before registration. ```javascript const schema = new Schema() const ast = parse(schemaSource) schema.register(ast) ``` -------------------------------- ### UI Rendering with Validated State (JavaScript) Source: https://github.com/shreeve/rip-lang/blob/main/packages/schema/GUIDE.md Demonstrates how UI components can directly render state without defensive checks when the state is guaranteed to be schema-validated. This simplifies component logic by assuming data integrity. ```javascript function PatientCard({ patient }) { return (

{patient.name}

{/* Guaranteed string, 1-100 chars */}

{patient.email}

{/* Guaranteed valid email */} {patient.role} {/* Guaranteed valid enum */}
) } ``` -------------------------------- ### Rip Swarm Job Script Example Source: https://github.com/shreeve/rip-lang/blob/main/packages/swarm/README.md A basic example of a Rip Swarm job script written in CoffeeScript. It defines setup and perform functions, initializes tasks, and configures the swarm. The setup function initializes the swarm and creates 100 tasks. The perform function simulates work with random delays and occasional errors. ```coffee import { swarm, init, retry, todo } from '@rip-lang/swarm' setup = -> unless retry() init() for i in [1..100] then todo(i) { startedAt: Date.now() } perform = (task, ctx) -> await Bun.sleep(Math.random() * 1000) throw new Error("boom") if Math.random() < 0.03 swarm { setup, perform } ``` -------------------------------- ### Installing Rip Stack Packages Source: https://github.com/shreeve/rip-lang/blob/main/README.md Demonstrates the command to install all Rip stack packages, including the database package, globally using Bun. This command installs Rip-lang, api, and db. ```Bash bun add -g @rip-lang/db # Installs everything (rip-lang + api + db) ``` -------------------------------- ### Example Rip API Application Source: https://github.com/shreeve/rip-lang/blob/main/packages/server/README.md A simple 'Hello World' style API application written in Rip, demonstrating GET routes for basic responses, JSON data, and dynamic route parameters. This app is designed to be run by Rip Server. ```coffee import { get, read, start } from '@rip-lang/api' get '/', -> 'Hello from Rip Server!' get '/json', -> { message: 'It works!', timestamp: Date.now() } get '/users/:id', -> id = read 'id', 'id!' { user: { id, name: "User #{id}" } } start() ``` -------------------------------- ### Instance Method: Validating Model Instances (JavaScript) Source: https://github.com/shreeve/rip-lang/blob/main/packages/schema/GUIDE.md Demonstrates the `$validate()` instance method available on objects created by `schema.create()`. This method performs validation on the instance itself and returns any validation errors. ```javascript const user = schema.create('User', data) const errors = user.$validate() ``` -------------------------------- ### Schema Class: Listing Registered Definitions (JavaScript) Source: https://github.com/shreeve/rip-lang/blob/main/packages/schema/GUIDE.md Illustrates the methods `listModels`, `listTypes`, and `listEnums` for obtaining arrays of all registered model, type, and enum names within the Schema instance. ```javascript const schema = new Schema() schema.listModels() // ['User', 'Patient', 'Post', ...] ``` -------------------------------- ### Install Rip Packages Source: https://github.com/shreeve/rip-lang/blob/main/packages/README.md This snippet shows how to install the core Rip language and its various optional packages using Bun. These packages extend Rip for full-stack development, covering web frameworks, UI, process management, databases, ORMs, job runners, and CSV handling. ```bash bun add rip-lang # Core language (required) bun add @rip-lang/api # Web framework bun add @rip-lang/ui # Reactive web UI framework bun add @rip-lang/server # Process manager bun add @rip-lang/db # DuckDB server bun add @rip-lang/schema # ORM + validation bun add @rip-lang/swarm # Parallel job runner bun add @rip-lang/csv # CSV parser + writer ``` -------------------------------- ### Rip UI App Serving Example with Rip Server Source: https://github.com/shreeve/rip-lang/blob/main/packages/server/README.md This CoffeeScript example demonstrates how to serve a Rip UI application using `rip-server` and the `@rip-lang/ui/serve` middleware. It configures the server to handle framework files, page manifests, hot reloading, and static assets. ```coffeescript import { get, use, start, notFound } from '@rip-lang/api' import { ripUI } from '@rip-lang/ui/serve' dir = import.meta.dir use ripUI pages: "#{dir}/pages", watch: true get '/css/*', -> @send "#{dir}/css/#{@req.path.slice(5)}" notFound -> @send "#{dir}/index.html", 'text/html; charset=UTF-8' start() ``` -------------------------------- ### Config File Validation with Rip.js Source: https://github.com/shreeve/rip-lang/blob/main/packages/schema/GUIDE.md Demonstrates validating application configuration files using Rip.js. It shows parsing a configuration schema, registering it, creating a configuration object from a file, and validating it against the schema. ```javascript // Validate app configuration const configSchema = parse(` @type AppConfig port!: integer host: string, ["localhost"] debug: boolean, [false] database!: DatabaseConfig @type DatabaseConfig url!: string pool: integer, [10] `) schema.register(configSchema) const config = schema.create('AppConfig', loadConfig('./config.json')) const errors = config.$validate() if (errors) throw new Error(`Invalid config: ${JSON.stringify(errors)}`) ``` -------------------------------- ### Define and Validate Schema with Rip.js Source: https://github.com/shreeve/rip-lang/blob/main/packages/schema/GUIDE.md Demonstrates how to define a schema using Rip's parsing capabilities, create a schema runtime, register the schema, and then create and validate instances of a 'User' model. This is the foundational step for using Rip. ```javascript import { parse, Schema } from '@rip-lang/schema' // Define your schema const ast = parse(` @enum Role: admin, user, guest @model User name!: string, [1, 100] email!#: email role: Role, [user] active: boolean, [true] @timestamps `) // Create runtime const schema = new Schema() schema.register(ast) // Create validated instances const user = schema.create('User', { name: 'John Doe', email: 'john@example.com', }) // Validate const errors = user.$validate() // null = valid ``` -------------------------------- ### Frontend Form Validation with Rip.js Source: https://github.com/shreeve/rip-lang/blob/main/packages/schema/GUIDE.md Illustrates how to perform form validation on the frontend using Rip.js. The example shows creating a schema instance from form data, validating it, and displaying errors next to the relevant fields if validation fails. ```javascript // Validate form data before submit function handleSubmit(formData) { const patient = schema.create('Patient', formData) const errors = patient.$validate() if (errors) { // Show errors next to fields errors.forEach(e => showFieldError(e.field, e.message)) return } await api.savePatient(patient) } ``` -------------------------------- ### Install and Run Rip Language Source: https://github.com/shreeve/rip-lang/blob/main/docs/RIP-LANG.md Instructions for installing Rip using Bun and common commands for running and compiling Rip files. It also mentions the file extension `.rip`. ```bash # Install Bun first (if needed) curl -fsSL https://bun.sh/install | bash # Install Rip globally bun add -g rip-lang rip # Interactive REPL rip app.rip # Run a file rip -c app.rip # Compile to JavaScript (stdout) rip -o app.js app.rip # Compile to file rip -t app.rip # Show tokens (debug) rip -s app.rip # Show S-expressions (debug) bun app.rip # Direct execution with Bun loader All Rip files use the .rip extension. ``` -------------------------------- ### Install Rip Server Source: https://github.com/shreeve/rip-lang/blob/main/packages/server/README.md Installs the Rip Server package either locally for a specific project or globally for command-line use. Uses the 'bun' package manager. ```bash # Local (per-project) bun add @rip-lang/server # Global (use rip-server from anywhere) bun add -g rip-lang @rip-lang/server ``` -------------------------------- ### Rip API Installation via Bun Source: https://github.com/shreeve/rip-lang/blob/main/packages/api/README.md Shows the command to install the Rip API package using Bun, the JavaScript runtime. This is the first step to using the framework in a project. ```bash bun add @rip-lang/api ``` -------------------------------- ### Test Data Factories with Rip.js Source: https://github.com/shreeve/rip-lang/blob/main/packages/schema/GUIDE.md Shows how Rip.js can be used to automatically generate valid test data, contrasting it with manual object construction. It demonstrates creating single instances with defaults and generating arrays of test data. ```javascript // Before: Manually construct test objects const user = { name: 'Test', email: 'test@x.com', role: 'user', active: true, ... } // NOW: Get valid defaults automatically const user = schema.create('User', { name: 'Test', email: 'test@x.com' }) // → { name: 'Test', email: 'test@x.com', role: 'user', active: true, createdAt: Date } // Create 100 test users const users = Array.from({ length: 100 }, (_, i) => schema.create('User', { name: `User ${i}`, email: `user${i}@test.com` }) ) ``` -------------------------------- ### Rip Build Commands Source: https://github.com/shreeve/rip-lang/blob/main/AGENT.md A set of commands for building and testing the Rip language project using Bun. These commands cover running tests, rebuilding the parser, creating a browser bundle, and starting a development server. ```bash bun run test # Run all tests bun run parser # Rebuild parser from grammar bun run browser # Build browser bundle bun run serve # Start dev server (localhost:3000) ``` -------------------------------- ### Install and Use Rip CLI Source: https://context7.com/shreeve/rip-lang/llms.txt Instructions for installing the Rip language globally using Bun and common CLI commands for REPL, execution, compilation, and debugging. ```bash # Install Bun runtime (if needed) curl -fsSL https://bun.sh/install | bash # Install Rip globally bun add -g rip-lang # Run interactive REPL rip # Execute a Rip file rip app.rip # Compile to JavaScript (stdout) rip -c app.rip # Compile to file rip -o app.js app.rip # Show tokens (debug) rip -t app.rip # Show S-expressions (debug) rip -s app.rip # Direct execution with Bun loader bun app.rip ``` -------------------------------- ### Start Rip-Lang Server with Handler Only Source: https://github.com/shreeve/rip-lang/blob/main/packages/api/README.md Demonstrates how to use `startHandler` from `@rip-lang/api` to start a Rip-Lang server that only exports a handler, typically used with `@rip-lang/server`. ```coffee import { startHandler } from '@rip-lang/api' export default startHandler() ``` -------------------------------- ### Install Type Support in Lexer (JavaScript) Source: https://github.com/shreeve/rip-lang/blob/main/docs/RIP-TYPES.md Demonstrates the parallel pattern for installing type support in the lexer, mirroring the component support installation. ```javascript // src/types.js — new sidecar for the lexer export function installTypeSupport(Lexer) { Lexer.prototype.rewriteTypes = function() { ... }; // Uses this.scanTokens() } export function emitTypes(tokens) { ... } // Annotated tokens -> .d.ts string export function generateEnum(head, rest, ctx) { ... } // Enum -> runtime JS object // src/lexer.js — wiring (mirrors compiler.js wiring for components) import { installTypeSupport } from './types.js'; installTypeSupport(Lexer); // src/compiler.js — wiring import { emitTypes, generateEnum } from './types.js'; CodeGenerator.prototype.generateEnum = generateEnum; CodeGenerator.GENERATORS['enum'] = 'generateEnum'; // In compile(): let dts = emitTypes(tokens); ``` -------------------------------- ### Rip App Fetch Handler using @rip-lang/api start() Source: https://github.com/shreeve/rip-lang/blob/main/packages/server/README.md This CoffeeScript code snippet demonstrates the recommended pattern for defining an application fetch handler using the `@rip-lang/api` module. The `start()` function automatically registers the handler when running under `rip-server`. ```coffeescript import { get, start } from '@rip-lang/api' get '/', -> 'Hello!' start() ``` -------------------------------- ### Rip UI Server Middleware Setup (CoffeeScript) Source: https://github.com/shreeve/rip-lang/blob/main/AGENT.md Sets up the ripUI middleware for serving framework files, generating a page manifest, and enabling SSE hot-reloading. It configures routes and a 404 handler for a basic HTML file. Requires @rip-lang/api and @rip-lang/ui/serve. ```CoffeeScript import { get, use, start, notFound } from '@rip-lang/api' import { ripUI } from '@rip-lang/ui/serve' dir = import.meta.dir use ripUI pages: "#{dir}/pages", watch: true notFound -> @send "#{dir}/index.html", 'text/html; charset=UTF-8' start port: 3000 ``` -------------------------------- ### Component Rendering with Rip Renderer Source: https://github.com/shreeve/rip-lang/blob/main/packages/ui/README.md Illustrates the setup and usage of the `createRenderer` function from `@rip-lang/ui/renderer` to manage the rendering of components based on route changes. It takes configuration options like the router, file system, state management, compiler, DOM target, and transitions. The renderer can be started to watch for route changes and mount components, or stopped to clean up. ```javascript import { createRenderer } from '@rip-lang/ui/renderer' const renderer = createRenderer({ router, fs, stash: appState, compile: compileToJS, target: '#app', transition: { duration: 200 } }) renderer.start() // Watch for route changes, mount components renderer.stop() // Unmount everything, clean up ``` -------------------------------- ### Server Options Source: https://github.com/shreeve/rip-lang/blob/main/packages/api/README.md Configuration options for starting the Rip-Lang server. ```APIDOC ## Server Options ### Basic Server Starts the server on a specified port, optionally binding to a host. #### Example ```coffee import { start } from '@rip-lang/api' start port: 3000 start port: 3000, host: '0.0.0.0' ``` ### Handler Only (for @rip-lang/server) Exports a handler function for use with `@rip-lang/server`. #### Example ```coffee import { startHandler } from '@rip-lang/api' export default startHandler() ``` ### App Pattern Defines routes using an App function, allowing for modular route definitions. #### Example ```coffee import { App, get, post } from '@rip-lang/api' export default App -> get '/', -> 'Hello' post '/echo', -> read() ``` ``` -------------------------------- ### Rip UI Component Example Source: https://github.com/shreeve/rip-lang/blob/main/README.md Illustrates how to define a UI component in Rip using the `component` and `render` keywords. This example shows a simple counter component with state management and event handling for incrementing and decrementing the count. ```CoffeeScript Counter = component @count := 0 render div.counter h1 "Count: #{@count}" button @click: (-> @count++), "+" button @click: (-> @count--), "-" ``` -------------------------------- ### Rip Language Syntax Examples Source: https://github.com/shreeve/rip-lang/blob/main/README.md Demonstrates various Rip language features including operators, constructors, list comprehensions, regex matching, and API endpoint definitions. These examples showcase the concise and expressive nature of Rip. ```coffee data = fetchUsers! # Dammit operator (call + await) user = User.new name: "Alice" # Ruby-style constructor squares = (x * x for x in [1..10]) # List comprehension str =~ /Hello, (\w+)/ # Regex match log "Found: #{_[1]}" # Captures in _[1], _[2], etc. get '/users/:id' -> # RESTful API endpoint, comma-less name = read 'name', 'string!' # Required string age = read 'age' , [0, 105] # Simple numeric validation ``` -------------------------------- ### Install Rip Swarm Source: https://github.com/shreeve/rip-lang/blob/main/packages/swarm/README.md Installs the @rip-lang/swarm package using Bun. This is the first step to using Rip Swarm in your project. ```bash bun add @rip-lang/swarm ``` -------------------------------- ### Solar Parser Generator Grammar Syntax Examples (Coffeescript) Source: https://github.com/shreeve/rip-lang/blob/main/docs/RIP-INTERNALS.md Examples demonstrating the syntax for defining grammar rules in the Solar parser generator using Coffeescript. It shows three styles: pass-through, s-expression, and advanced with conditional logic using pattern matching. ```coffeescript o = (pattern, action, options) -> pattern = pattern.trim().replace /\s{2,}/g, ' ' [pattern, action ? 1, options] ``` ```coffeescript Expression: [ o 'Value' o 'Operation' ] ``` ```coffeescript For: [ o 'FOR ForVariables FOROF Expression Block', '["for-of", 2, 4, null, 5]' ] ``` ```coffeescript Parenthetical: [ o '( Body )', '$2.length === 1 ? $2[0] : $2' ] ``` -------------------------------- ### Full API Example with @rip-lang/api Source: https://github.com/shreeve/rip-lang/blob/main/packages/api/README.md A comprehensive example showcasing the @rip-lang/api framework for building a full-featured API. It includes middleware, request filters (before/after), error handling, and CRUD operations for users. ```coffeescript import { get, post, put, del, use, read, start, before, after, onError } from '@rip-lang/api' import { logger } from '@rip-lang/api/middleware' # Middleware use logger() # Filters before -> @start = Date.now() after -> console.log "#{@req.method} #{@req.path} - #{Date.now() - @start}ms" # Error handling onError (err) -> @json { error: err.message }, err.status or 500 # Routes get '/', -> { name: 'My API', version: '1.0' } get '/users', -> page = read 'page', 'int', [1, 100] limit = read 'limit', 'int', [1, 50] users = db.listUsers! page or 1, limit or 10 { users, page, limit } get '/users/:id', -> id = read 'id', 'id!' user = db.getUser!(id) unless user throw { message: 'User not found', status: 404 } { user } post '/users', -> email = read 'email', 'email!' name = read 'name', 'string', [1, 100] phone = read 'phone', 'phone' user = db.createUser! { email, name, phone } { user, created: true } put '/users/:id', -> id = read 'id', 'id!' email = read 'email', 'email' name = read 'name', 'string', [1, 100] user = db.updateUser! id, { email, name } { user, updated: true } del '/users/:id', -> id = read 'id', 'id!' db.deleteUser!(id) { deleted: true } start port: 3000 ``` -------------------------------- ### Data Import Validation with Rip.js Source: https://github.com/shreeve/rip-lang/blob/main/packages/schema/GUIDE.md Explains how to validate imported data, such as from CSV files, using Rip.js. The example iterates through rows, creates schema instances, validates each, and categorizes them into valid and invalid results. ```javascript // Validate CSV/JSON imports async function importPatients(csvFile) { const rows = parseCSV(csvFile) const results = { valid: [], invalid: [] } for (const row of rows) { const patient = schema.create('Patient', row) const errors = patient.$validate() if (errors) { results.invalid.push({ row, errors }) } else { results.valid.push(patient) } } console.log(`Valid: ${results.valid.length}, Invalid: ${results.invalid.length}`) return results } ``` -------------------------------- ### Schema Class: Retrieving Schema Definitions (JavaScript) Source: https://github.com/shreeve/rip-lang/blob/main/packages/schema/GUIDE.md Shows how to retrieve specific schema definitions (models, types, enums) using methods like `getModel`, `getType`, and `getEnum`. The example retrieves a 'User' model and accesses its fields. ```javascript const schema = new Schema() const userModel = schema.getModel('User') console.log(userModel.fields) // Map of field definitions ``` -------------------------------- ### File-Based Router Initialization in JavaScript Source: https://github.com/shreeve/rip-lang/blob/main/packages/ui/README.md Demonstrates how to create a file-based router using the '@rip-lang/ui/router' module. It requires the VFS instance and a configuration object specifying the root directory for page components. ```javascript import { createRouter } from '@rip-lang/ui/router' const router = createRouter(fs, { root: 'pages' }) ``` -------------------------------- ### Rip Server Command-Line Usage (Bash) Source: https://context7.com/shreeve/rip-lang/llms.txt Provides examples of how to run the rip-server for development and production. Covers basic usage, development with watching, named applications, HTTP-only mode, custom ports, and production configurations. ```bash # Basic usage (uses ./index.rip) rip-server # Development with file watching rip-server -w # Named app (accessible at myapp.local via mDNS) rip-server myapp # With aliases (myapp.local, api.local, backend.local) rip-server myapp@api,backend # HTTP only mode rip-server http # Custom port rip-server http:3000 # Production mode rip-server --env=prod --static w:8 # Auto TLS with mkcert rip-server --auto-tls # Watch TypeScript files rip-server -w=*.ts # Worker and restart configuration rip-server w:auto r:5000,3600s ``` -------------------------------- ### Rip Process Manager CLI Source: https://github.com/shreeve/rip-lang/blob/main/packages/README.md Command-line usage for the @rip-lang/server package, a process manager. This example shows how to start the server with worker threads enabled and hot-reloading. ```bash rip-server -w # Start with workers + hot-reload ``` -------------------------------- ### Rip DuckDB Server CLI Source: https://github.com/shreeve/rip-lang/blob/main/packages/README.md Command-line usage for the @rip-lang/db package, an HTTP server for DuckDB queries. This example shows how to start a DuckDB server instance for a specific database file and port. ```bash rip-db mydata.duckdb --port=4000 ``` -------------------------------- ### Rip Server CLI Hot Reload (Bash) Source: https://github.com/shreeve/rip-lang/blob/main/AGENT.md Starts the @rip-lang/server process manager with file watching and hot-reloading enabled. This command is used for development to automatically restart the server when files change. ```bash rip-server -w # Start with file watching + hot-reload ``` -------------------------------- ### Validation Error Format (JavaScript) Source: https://github.com/shreeve/rip-lang/blob/main/packages/schema/GUIDE.md Presents the structure of the error objects returned by validation functions. It details common error types such as 'required', 'min', 'enum', and 'nested', including nested error structures. ```javascript [ { field: 'email', error: 'required', message: 'email is required' }, { field: 'name', error: 'min', message: 'name must be at least 1' }, { field: 'role', error: 'enum', message: 'role must be one of: admin, user, guest' }, { field: 'address', error: 'nested', errors: [...] } // Nested type errors ] ``` -------------------------------- ### Schema Class: Validating Single Field Values (JavaScript) Source: https://github.com/shreeve/rip-lang/blob/main/packages/schema/GUIDE.md Demonstrates the `schema.isValid()` method for checking if a specific value conforms to the constraints of a particular field within a model. This is useful for real-time input validation. ```javascript const schema = new Schema() schema.isValid('User', 'email', 'test@example.com') // true schema.isValid('User', 'email', 'not-an-email') // false ``` -------------------------------- ### Loading Application Bundle (JavaScript) Source: https://github.com/shreeve/rip-lang/blob/main/packages/ui/README.md Fetches a JSON manifest containing all page sources and loads them into the Virtual File System (VFS) in a single request. This method returns the app instance, allowing for chaining. ```javascript await app.loadBundle('/rip-ui/manifest.json'); ``` -------------------------------- ### Schema Class: Validating Objects (JavaScript) Source: https://github.com/shreeve/rip-lang/blob/main/packages/schema/GUIDE.md Explains the `schema.validate()` method, which checks an entire object against a registered model schema. It returns `null` if the object is valid or an array of error objects if validation fails. ```javascript const schema = new Schema() const errors = schema.validate('User', userData) // Returns: null (valid) or [{ field, error, message }, ...] ``` -------------------------------- ### Server-Side Rip UI Middleware Setup Source: https://github.com/shreeve/rip-lang/blob/main/packages/ui/README.md Shows how to integrate Rip UI into a server using the `ripUI` middleware from `@rip-lang/ui/serve`. This middleware registers routes for serving framework files, page manifests, and hot-reloading. It's used with `@rip-lang/api`'s `use()` function and accepts options like `pages` directory and `watch` for enabling hot-reloading. ```coffeescript import { use } from '@rip-lang/api' import { ripUI } from '@rip-lang/ui/serve' use ripUI pages: 'pages', watch: true ``` -------------------------------- ### Running a Rip API Application Source: https://github.com/shreeve/rip-lang/blob/main/packages/api/README.md Demonstrates the command-line instruction to execute a Rip API application file. This assumes the Rip runtime is installed and the application file (e.g., `app.rip`) is present. ```bash rip app.rip ``` -------------------------------- ### Router Navigation and Reactive State in JavaScript Source: https://github.com/shreeve/rip-lang/blob/main/packages/ui/README.md Illustrates programmatic navigation using the router's 'push', 'replace', and 'back' methods. It also shows how to access reactive route state like 'path' and 'params' within an 'effect' callback. ```javascript // Navigate router.push('/users/42') router.replace('/login') router.back() // Reactive route state effect(() => { console.log(router.path) // '/users/42' console.log(router.params) // { id: '42' } }) ``` -------------------------------- ### Self-Documenting APIs with Rip.js Schema Source: https://github.com/shreeve/rip-lang/blob/main/packages/schema/GUIDE.md Highlights how Rip.js schemas can serve as API documentation. It shows retrieving model information from the schema and outlines a function to generate OpenAPI/Swagger specifications based on the defined models and their fields. ```javascript // Schema IS the documentation const userModel = schema.getModel('User') // Generate OpenAPI/Swagger from schema function generateOpenAPI() { const models = schema.listModels() return models.map(name => { const model = schema.getModel(name) return { name, fields: [...model.fields.entries()].map(([k, v]) => ({ name: k, type: v.type, required: v.required, constraints: v.constraints, })) } }) } ``` -------------------------------- ### API Request Validation with Rip.js Source: https://github.com/shreeve/rip-lang/blob/main/packages/schema/GUIDE.md Compares manual, verbose API request validation with a concise, one-line validation using Rip.js. It shows how Rip simplifies backend validation by creating a schema instance and checking for errors. ```javascript // Before: Manual validation everywhere app.post('/users', (req, res) => { if (!req.body.name) return res.status(400).json({ error: 'name required' }) if (!req.body.email) return res.status(400).json({ error: 'email required' }) if (!isValidEmail(req.body.email)) return res.status(400).json({ error: 'invalid email' }) // ... 50 more lines of validation }) // NOW: One line app.post('/users', (req, res) => { const user = schema.create('User', req.body) const errors = user.$validate() if (errors) return res.status(400).json({ errors }) // Save user... }) ``` -------------------------------- ### Rip Lang UI Zero-Build Web Framework Components Source: https://context7.com/shreeve/rip-lang/llms.txt Illustrates how to create reactive web components using the Rip Lang UI framework. It demonstrates defining component state with signals (`:=`), props, computed values (`~=`), lifecycle methods (`mounted`), and rendering JSX-like templates. Examples include a counter component and a todo list component. ```CoffeeScript # Counter component Counter = component @count := 0 # Reactive state (signal) @step = 1 # Plain prop doubled ~= @count * 2 # Computed value increment: -> @count += @step decrement: -> @count -= @step mounted: -> console.log "Counter mounted" render div.counter h1 "Count: #{@count}" p "Doubled: #{doubled}" button @click: @increment, "+#{@step}" button @click: @decrement, "-#{@step}" # TodoList with computed values TodoList = component @todos := [] remaining ~= @todos.filter((t) -> not t.done).length total ~= @todos.length ~> console.log "#{remaining} of #{total} remaining" render div h2 "Todos (#{remaining}/#{total})" ul for todo in @todos li todo.name ``` -------------------------------- ### Rip Command-Line Interface (CLI) Quick Reference Source: https://github.com/shreeve/rip-lang/blob/main/README.md This snippet outlines common commands for the Rip CLI, including running the REPL, executing files, compiling, and generating tokens or S-expressions. It also includes commands for rebuilding the parser and building browser bundles using Bun. ```bash rip # REPL rip file.rip # Run rip -c file.rip # Compile rip -t file.rip # Tokens rip -s file.rip # S-expressions bun run test # 1073 tests bun run parser # Rebuild parser bun run browser # Build browser bundle ``` -------------------------------- ### Rip Parallel Job Runner Swarm Source: https://github.com/shreeve/rip-lang/blob/main/packages/README.md Example of using the @rip-lang/swarm package for parallel job execution. It defines setup logic for initialization and task creation, and a perform function to execute individual tasks, including asynchronous operations and random delays. ```coffee import { swarm, init, retry, todo } from '@rip-lang/swarm' setup = -> unless retry() init() for i in [1..100] then todo(i) perform = (task, ctx) -> await Bun.sleep(Math.random() * 1000) swarm { setup, perform } ``` -------------------------------- ### Determine MIME Type with Rip-Lang's mimeType Utility Source: https://github.com/shreeve/rip-lang/blob/main/packages/api/README.md Provides an example of using the exported `mimeType(path)` utility function to get the MIME type for a given file path based on its extension. It falls back to `application/octet-stream` for unknown types. ```coffee import { mimeType } from '@rip-lang/api' mimeType 'style.css' # 'text/css; charset=UTF-8' mimeType 'app.js' # 'application/javascript' mimeType 'photo.png' # 'image/png' mimeType 'data.xyz' # 'application/octet-stream' ``` -------------------------------- ### Rip Reactive Web UI Framework Server Integration Source: https://github.com/shreeve/rip-lang/blob/main/packages/README.md Example of integrating the @rip-lang/ui package with the @rip-lang/api web framework. It shows how to use the `ripUI` middleware to serve Rip UI components, handle static CSS files, and define a custom 404 Not Found response. ```coffee import { get, use, start, notFound } from '@rip-lang/api' import { ripUI } from '@rip-lang/ui/serve' dir = import.meta.dir use ripUI pages: "#{dir}/pages", watch: true get '/css/*', -> @send "#{dir}/css/#{@req.path.slice(5)}" notFound -> @send "#{dir}/index.html", 'text/html; charset=UTF-8' start port: 3000 ``` -------------------------------- ### Rip-Lang Interface Example Source: https://github.com/shreeve/rip-lang/blob/main/docs/RIP-TYPES.md An example of interface definitions in Rip-Lang, including inheritance. These are processed by the rewriter and emitted as TypeScript interfaces. ```coffeescript interface Animal name: string interface Dog extends Animal breed: string bark: () => void ```