### Getting Started Guide Structure
Source: https://github.com/wippyai/docs/blob/main/context/writerside-llm-guide.md
Example structure for a 'Getting Started' guide, including prerequisites, installation, and next steps.
```APIDOC
# Getting Started with %product_name%
Install %product_name%, configure your API key, and make your first API call in under 5 minutes.
## Prerequisites
Before you begin, you'll need:
- A valid API key (get one [here](https://example.com/api-keys))
- Node.js 16 or higher
- Basic knowledge of REST APIs
## Quick Installation
Install via npm:
```bash
npm install @example/sdk
```
Set your API key:
```bash
export API_KEY="your_api_key_here"
```
Test the connection:
```javascript
const client = new ExampleClient(process.env.API_KEY);
await client.test();
```
## Next Steps
Now that you're set up, try these common tasks:
- [Make your first API call](first-api-call.md)
- [Explore the dashboard](dashboard-guide.md)
- [Set up webhooks](webhooks.md)
```
--------------------------------
### Install SDK and Set API Key (Bash)
Source: https://github.com/wippyai/docs/blob/main/context/writerside-llm-guide.md
Installs the example SDK using npm and sets the API key as an environment variable. Requires Node.js and npm to be installed.
```bash
npm install @example/sdk
export API_KEY="your_api_key_here"
```
--------------------------------
### Query Parameters Example
Source: https://github.com/wippyai/docs/blob/main/docs/topics/lua-httpclient.md
Demonstrates how to send query parameters with a GET request.
```APIDOC
## Query Parameters Example
### Description
This example shows how to include query parameters in a GET request.
### Method
GET
### Endpoint
`GET /search`
### Parameters
#### Query Parameters
- **q** (string) - The search query.
- **page** (string) - The page number.
- **limit** (string) - The number of results per page.
### Request Example
```lua
local resp, err = http_client.get("https://api.example.com/search", {
query = {
q = "lua programming",
page = "1",
limit = "20"
}
})
```
### Response
#### Success Response (200)
- **status_code** (number) - The HTTP status code of the response.
- **body** (string) - The response body.
#### Response Example
```json
{
"status_code": 200,
"body": "response body"
}
```
```
--------------------------------
### HTTP Endpoint: GET /hello
Source: https://github.com/wippyai/docs/blob/main/docs/topics/getting-started-quickstart.md
This endpoint provides a greeting message. It accepts an optional 'name' query parameter to customize the greeting.
```APIDOC
## GET /hello
### Description
Returns a personalized greeting message. If a 'name' query parameter is provided, it will be used in the greeting; otherwise, it defaults to 'World'.
### Method
GET
### Endpoint
/hello
### Query Parameters
- **name** (string) - Optional - The name to include in the greeting.
### Request Example
```bash
curl "http://localhost:8080/hello?name=Wippy"
```
### Response
#### Success Response (200)
- **message** (string) - The greeting message.
#### Response Example
```json
{
"message": "Hello, Wippy!"
}
```
```
--------------------------------
### Run Wippy Application
Source: https://github.com/wippyai/docs/blob/main/docs/topics/getting-started-quickstart.md
Runs the Wippy application. This command compiles and starts the services defined in the Wippy configuration.
```bash
wippy run
```
--------------------------------
### Build Wippy from Source
Source: https://github.com/wippyai/docs/blob/main/docs/topics/getting-started-installation.md
Clones the Wippy repository, navigates into the directory, and builds the Wippy binary using Go. Requires Git, Go 1.22+, and a C compiler (for SQLite).
```bash
git clone https://github.com/wippyai/wippy.git
cd wippy
go build -o wippy ./cmd/wippy/
```
--------------------------------
### Run Wippy Project Commands (Bash)
Source: https://github.com/wippyai/docs/blob/main/docs/topics/auth.md
These bash commands are used to initialize and run the Wippy project. `wippy init` is typically used for project setup, while `wippy run` starts the application. After running, the application can be accessed via `http://localhost:8081` using the demo API key shown in the logs.
```bash
wippy init
wippy run
```
--------------------------------
### Example Configuration Structure (Go)
Source: https://github.com/wippyai/docs/blob/main/docs/topics/internal-kinds.md
Provides an example of a typical configuration structure for entry data, including ID, Meta, Name, and Timeout. It also includes InitDefaults and Validate methods for initialization and validation.
```go
type ComponentConfig struct {
ID registry.ID `json:"id"`
Meta attrs.Bag `json:"meta"`
Name string `json:"name"`
Timeout int `json:"timeout,omitempty"`
}
func (c *ComponentConfig) InitDefaults() {
if c.Timeout == 0 {
c.Timeout = 30
}
}
func (c *ComponentConfig) Validate() error {
if c.Name == "" {
return fmt.Errorf("name is required")
}
return nil
}
```
--------------------------------
### Pure Markdown Document Start
Source: https://github.com/wippyai/docs/blob/main/context/writerside-llm-guide.md
Example of starting a document with pure Markdown, focusing on readability and standard formatting before introducing any semantic XML.
```markdown
# Quick Start Guide
Welcome to our application! This guide will get you up and running in 5 minutes.
## What You'll Need
- A modern web browser
- An internet connection
- 10 minutes of your time
## Step 1: Create Account
Go to our signup page and create your account...
```
--------------------------------
### Install Wippy to PATH
Source: https://github.com/wippyai/docs/blob/main/docs/topics/getting-started-installation.md
Moves the downloaded Wippy binary to a directory included in the system's PATH for global access. Requires `sudo` for system-wide installation or user-level permissions for user-local installation.
```bash
# Linux/macOS
sudo mv wippy /usr/local/bin/
# Or user-local
mv wippy ~/.local/bin/
```
--------------------------------
### Lifecycle Configuration Example
Source: https://github.com/wippyai/docs/blob/main/docs/topics/guide-entry-kinds.md
Illustrates how to configure lifecycle settings for an entry, including automatic starting, startup and shutdown timeouts, stability thresholds, and restart policies with backoff. It also shows dependency management using `depends_on`.
```yaml
- name: service
kind: some.kind
lifecycle:
auto_start: true # Start automatically
start_timeout: 10s # Max startup time
stop_timeout: 10s # Max shutdown time
stable_threshold: 5s # Time to consider stable
depends_on:
- app:database
restart:
initial_delay: 1s
max_delay: 90s
backoff_factor: 2.0
max_attempts: 0 # 0 = infinite
```
--------------------------------
### Troubleshooting Guide Structure
Source: https://github.com/wippyai/docs/blob/main/context/writerside-llm-guide.md
Example structure for a 'Troubleshooting' guide, including common issues and solutions.
```APIDOC
# Troubleshooting
## Common Issues
### Connection Timeouts
If you're experiencing connection timeouts:
Check your internet connection
Verify the API endpoint URL
Test with a simple curl command:
```bash
curl -I https://api.example.com/health
```
Check our [status page](https://status.example.com) for outages
Most connection issues are resolved by checking your API key and network configuration.
### Authentication Errors
**Error**: `401 Unauthorized`
**Solution**: Your API key may be invalid or expired.
1. Verify your API key in the dashboard
2. Check that it has the required permissions
3. Regenerate the key if necessary
Regenerating your API key will invalidate the old one immediately.
```
--------------------------------
### Initialize Wippy Project
Source: https://github.com/wippyai/docs/blob/main/docs/topics/getting-started-quickstart.md
Initializes a new Wippy project in the current directory. This command creates essential project files and directories like `wippy.lock`, `src/`, and `.wippy/`.
```bash
mkdir myapp && cd myapp
wippy init
```
--------------------------------
### Configure HTTP Endpoint and Service
Source: https://github.com/wippyai/docs/blob/main/docs/topics/getting-started-quickstart.md
Extends the Wippy application configuration to include an HTTP service, a router, and an endpoint. This allows the 'hello' function to be accessed via a GET request at the `/hello` path on port 8080.
```yaml
version: "1.0"
namespace: app
entries:
# Function that handles the request
- name: hello
kind: function.lua
source: file://hello.lua
method: handler
modules:
- json
- http
# HTTP server
- name: gateway
kind: http.service
addr: ":8080"
lifecycle:
auto_start: true
# Router attached to the server
- name: api
kind: http.router
meta:
server: gateway
prefix: /
# Endpoint attached to the router
- name: hello_endpoint
kind: http.endpoint
meta:
router: app:api
method: GET
path: /hello
func: hello
```
--------------------------------
### Configure Wippy Runtime Settings
Source: https://github.com/wippyai/docs/blob/main/docs/topics/getting-started-quickstart.md
Configures runtime settings for the Wippy application using a `.wippy.yaml` file. This example sets the logger level to 'info' in 'development' mode and specifies the HTTP server address.
```yaml
logger:
level: info
mode: development
http:
address: :8080
```
--------------------------------
### Headers and Authentication Examples
Source: https://github.com/wippyai/docs/blob/main/docs/topics/lua-httpclient.md
Illustrates how to set custom headers and use authentication methods.
```APIDOC
## Headers and Authentication Examples
### Description
Examples demonstrating the use of custom headers and basic authentication.
### Method
GET
### Endpoint
`GET /data`
### Parameters
#### Request Body (Headers and Auth)
- **headers** (table, optional) - Custom headers like `Authorization` and `Accept`.
- **auth** (table, optional) - Basic authentication credentials (`{user = "name", pass = "secret"}`).
### Request Example (Headers)
```lua
local resp, err = http_client.get("https://api.example.com/data", {
headers = {
["Authorization"] = "Bearer " .. token,
["Accept"] = "application/json"
}
})
```
### Request Example (Basic Auth)
```lua
local resp, err = http_client.get("https://api.example.com/data", {
auth = {user = "admin", pass = "secret"}
})
```
### Response
#### Success Response (200)
- **status_code** (number) - The HTTP status code of the response.
- **body** (string) - The response body.
#### Response Example
```json
{
"status_code": 200,
"body": "response body"
}
```
```
--------------------------------
### Testing the API with cURL (Bash)
Source: https://github.com/wippyai/docs/blob/main/docs/topics/task-queue.md
Examples of using cURL to interact with the task management API. This demonstrates how to create a task via POST request and list tasks via GET request, including filtering by status. These examples are useful for verifying service functionality.
```bash
# Create a task
curl -X POST http://localhost:8080/tasks \
-H "Content-Type: application/json" \
-d '{"action": "uppercase", "data": {"text": "hello world"}}'
# Response: {"id": "550e8400-...", "status": "queued"}
# Wait a moment for processing, then list tasks
curl http://localhost:8080/tasks
# Response: {"tasks": [...], "count": 1}
# Filter by status
curl "http://localhost:8080/tasks?status=completed"
```
--------------------------------
### Markdown Tables for Comparison
Source: https://github.com/wippyai/docs/blob/main/context/writerside-llm-guide.md
Provides an example of creating a comparison table using pure Markdown syntax, demonstrating column alignment and row structure.
```markdown
## Comparison
| Feature | Basic Plan | Pro Plan | Enterprise |
|---------|------------|----------|------------|
| Users | 5 | 50 | Unlimited |
| Storage | 10GB | 100GB | 1TB |
| Support | Email | Phone | Dedicated |
```
--------------------------------
### Verify Wippy Installation
Source: https://github.com/wippyai/docs/blob/main/docs/topics/getting-started-installation.md
Checks if the Wippy installation was successful by running the `wippy version` command. Requires the Wippy binary to be in the system's PATH.
```bash
wippy version
```
--------------------------------
### Router Configuration Example (YAML)
Source: https://github.com/wippyai/docs/blob/main/docs/topics/http-router.md
Example configuration for an HTTP router, defining its name, kind, parent server, URL prefix, pre-match middleware, options, and post-match middleware.
```yaml
- name: api
kind: http.router
meta:
server: gateway
prefix: /api/v1
middleware:
- cors
- compress
options:
cors.allow.origins: "*"
post_middleware:
- endpoint_firewall
```
--------------------------------
### Lua: Execute Tree-sitter Query
Source: https://github.com/wippyai/docs/blob/main/docs/topics/lua-treesitter.md
Provides Lua examples for executing a Tree-sitter query against a syntax tree. It covers how to get all flattened captures and how to get matches grouped by pattern, including details about capture names, text, and nodes.
```lua
-- Get all captures (flattened)
local captures = query:captures(root, source_code)
for _, capture in ipairs(captures) do
print(capture.name) -- "@func_name"
print(capture.text) -- actual text
print(capture.index) -- capture index
-- capture.node is the Node object
end
-- Get matches (grouped by pattern)
local matches = query:matches(root, source_code)
for _, match in ipairs(matches) do
print(match.id, match.pattern)
for _, capture in ipairs(match.captures) do
print(capture.name, capture.node:text())
end
end
```
--------------------------------
### UI Instructions
Source: https://github.com/wippyai/docs/blob/main/context/writerside-llm-guide.md
Shows how to guide users through UI interactions using standard Markdown for steps and semantic XML for elements like shortcuts.
```APIDOC
## UI Instructions
```markdown
## User Interface Guide
To create a new project:
1. Click **File** → **New Project**
2. Select your project type
3. Choose a location and click **Create**
When the dialog appears, make sure to check the **Include sample files** option.
You can also use the keyboard shortcut Ctrl+Shift+N to quickly create a new project.
```
```
--------------------------------
### File Upload Example
Source: https://github.com/wippyai/docs/blob/main/docs/topics/lua-httpclient.md
Provides an example of uploading files along with form data.
```APIDOC
## File Upload Example
### Description
This example shows how to upload files using the `files` option, often combined with `form` data.
### Method
POST
### Endpoint
`POST /upload`
### Parameters
#### Request Body
- **form** (table, optional) - Additional form fields.
- **files** (table) - An array of file definitions. Each definition is a table with:
- **name** (string) - Required. The name of the form field for the file.
- **filename** (string, optional) - The original filename.
- **content** (string, required*) - The file content as a string.
- **reader** (userdata, required*) - Alternative to `content`: an `io.Reader` for the file content.
- **content_type** (string, optional) - MIME type of the file (defaults to `application/octet-stream`).
*Either `content` or `reader` must be provided.
### Request Example
```lua
local resp, err = http_client.post("https://api.example.com/upload", {
form = {title = "My Document"},
files = {
{
name = "attachment", -- form field name
filename = "report.pdf", -- original filename
content = pdf_data, -- file content
content_type = "application/pdf"
}
}
})
```
### Response
#### Success Response (200)
- **status_code** (number) - The HTTP status code of the response.
- **body** (string) - The response body.
#### Response Example
```json
{
"status_code": 200,
"body": "response body"
}
```
```
--------------------------------
### Real-Time Chat Example
Source: https://github.com/wippyai/docs/blob/main/docs/topics/lua-websocket.md
An example of establishing a WebSocket connection to a chat server, joining a specific room, and processing incoming messages. It includes sending a 'join' message and entering a loop to receive and display messages.
```lua
local function connect_chat(room_id, on_message)
local client, err = websocket.connect("wss://chat.example.com/ws", {
headers = {["Authorization"] = "Bearer " .. token}
})
if err then
return nil, err
end
-- Join room
client:send(json.encode({
type = "join",
room = room_id
}))
-- Message loop
local ch = client:channel()
while true do
local msg, ok = ch:receive()
if not ok then break end
local data = json.decode(msg.data)
on_message(data)
end
client:close()
end
```
--------------------------------
### Download Wippy Binary for Linux
Source: https://github.com/wippyai/docs/blob/main/docs/topics/getting-started-installation.md
Downloads the Wippy binary for Linux (AMD64 and ARM64 architectures) using curl and makes it executable. Requires `curl` and standard shell utilities.
```bash
# AMD64
curl -L https://github.com/wippyai/wippy/releases/latest/download/wippy-linux-amd64 -o wippy
chmod +x wippy
# ARM64
curl -L https://github.com/wippyai/wippy/releases/latest/download/wippy-linux-arm64 -o wippy
chmod +x wippy
```
--------------------------------
### Download Wippy Binary for macOS
Source: https://github.com/wippyai/docs/blob/main/docs/topics/getting-started-installation.md
Downloads the Wippy binary for macOS (Apple Silicon and Intel architectures) using curl and makes it executable. Requires `curl` and standard shell utilities.
```bash
# Apple Silicon (M1/M2/M3)
curl -L https://github.com/wippyai/wippy/releases/latest/download/wippy-darwin-arm64 -o wippy
chmod +x wippy
# Intel
curl -L https://github.com/wippyai/wippy/releases/latest/download/wippy-darwin-amd64 -o wippy
chmod +x wippy
```
--------------------------------
### Define Lua Entry Point
Source: https://github.com/wippyai/docs/blob/main/docs/topics/getting-started-quickstart.md
Defines a basic Lua function as an entry point for the Wippy application. It specifies the version, namespace, entry name, kind, source file, method to execute, and required modules.
```yaml
version: "1.0"
namespace: app
entries:
- name: hello
kind: function.lua
source: file://hello.lua
method: main
modules:
- json
```
--------------------------------
### YAML for Application Registry Entry Example
Source: https://github.com/wippyai/docs/blob/main/docs/topics/getting-started-structure.md
Demonstrates defining an application-level configuration entry using the 'registry.entry' kind. This example includes metadata like 'title' and 'type', along with environment-specific features.
```yaml
- name: config
kind: registry.entry
meta:
title: Application Settings
type: application
environment: production
features:
dark_mode: true
beta_access: false
```
--------------------------------
### Starting and Waiting for Process Completion in Lua
Source: https://github.com/wippyai/docs/blob/main/docs/topics/lua-exec.md
This code demonstrates the lifecycle of a process: starting it and then waiting for its execution to complete. It includes error handling for the start operation and checks the exit code upon completion to determine success or failure.
```lua
local proc = executor:exec("./build.sh")
local ok, err = proc:start()
if err then
return nil, err
end
local exit_code, err = proc:wait()
if err then
return nil, err
end
if exit_code ~= 0 then
return nil, errors.new("INTERNAL", "Build failed with exit code: " .. exit_code)
end
```
--------------------------------
### Endpoint Configuration Example (YAML)
Source: https://github.com/wippyai/docs/blob/main/docs/topics/http-router.md
Example configuration for an HTTP endpoint, specifying its name, kind, parent router, HTTP method, URL path pattern, and the handler function.
```yaml
- name: get_user
kind: http.endpoint
meta:
router: api
method: GET
path: /users/{id}
func: app.users:get_user
```
--------------------------------
### Performing GET Request (Lua)
Source: https://github.com/wippyai/docs/blob/main/docs/topics/lua-httpclient.md
Shows how to perform a basic HTTP GET request using the http_client library. It includes error handling and accessing response status and body.
```lua
local resp, err = http_client.get("https://api.example.com/users")
if err then
return nil, err
end
print(resp.status_code) -- 200
print(resp.body) -- response body
```
--------------------------------
### Wippy Configuration File Example
Source: https://github.com/wippyai/docs/blob/main/docs/topics/guide-cli.md
An example of a .wippy.yaml configuration file, demonstrating settings for logger, log manager, profiler, and overrides.
```yaml
logger:
mode: development
level: debug
encoding: console
logmanager:
min_level: -1 # debug
profiler:
enabled: true
address: localhost:6060
override:
app:gateway:addr: ":9090"
app:db:host: "localhost"
```
--------------------------------
### Form Data Example
Source: https://github.com/wippyai/docs/blob/main/docs/topics/lua-httpclient.md
Shows how to send form data in a POST request.
```APIDOC
## Form Data Example
### Description
This example demonstrates sending form data using the `form` option in a POST request.
### Method
POST
### Endpoint
`POST /login`
### Parameters
#### Request Body
- **form** (table) - Form data fields (`{username = "alice", password = "secret123"}`). The `Content-Type` header will be set automatically.
### Request Example
```lua
local resp, err = http_client.post("https://api.example.com/login", {
form = {
username = "alice",
password = "secret123"
}
})
```
### Response
#### Success Response (200)
- **status_code** (number) - The HTTP status code of the response.
- **body** (string) - The response body.
#### Response Example
```json
{
"status_code": 200,
"body": "response body"
}
```
```
--------------------------------
### Wippy Configuration File (.wippy.yaml) Example
Source: https://github.com/wippyai/docs/blob/main/docs/topics/getting-started-structure.md
Demonstrates the structure of the main Wippy runtime configuration file. This example shows settings for logging level and mode, worker count, and HTTP server address.
```yaml
logger:
level: info
mode: production
host:
worker_count: 16
http:
address: :8080
```
--------------------------------
### Upload and Get Presigned URL for S3 Object (Lua)
Source: https://github.com/wippyai/docs/blob/main/docs/topics/guide-entry-kinds.md
Demonstrates how to interact with the cloud storage module in Lua. It shows how to get a storage client, upload an object, and generate a presigned URL for accessing the object.
```lua
local cloudstorage = require("cloudstorage")
local storage, err = cloudstorage.get("app:uploads")
storage:upload_object("files/doc.pdf", file_content)
local url = storage:presigned_get_url("files/doc.pdf", {expires = "1h"})
```
--------------------------------
### Get User Profile API Request (HTTP)
Source: https://github.com/wippyai/docs/blob/main/context/writerside-llm-guide.md
An example HTTP GET request to retrieve a user's profile information. Requires a valid Bearer token for authorization.
```http
GET /api/v1/users/{userId}
Authorization: Bearer {token}
```
--------------------------------
### Create Project Directory and Source Folder
Source: https://github.com/wippyai/docs/blob/main/docs/topics/hello-world.md
This bash script creates a new directory for the project named 'hello-world' and navigates into it. It then creates a 'src' subdirectory to hold the application source files.
```bash
mkdir hello-world && cd hello-world
mkdir src
```
--------------------------------
### Test HTTP Endpoint with Curl
Source: https://github.com/wippyai/docs/blob/main/docs/topics/getting-started-quickstart.md
Tests the deployed HTTP endpoint using `curl`. It sends a GET request to the `/hello` path with a 'name' query parameter and displays the JSON response.
```bash
curl "http://localhost:8080/hello?name=Wippy"
```
--------------------------------
### Initialize and Run Wippy Project
Source: https://context7.com/wippyai/docs/llms.txt
Initializes a new Wippy project using the CLI and configures application entry points and services using YAML.
```bash
mkdir myapp && cd myapp
wippy init
wippy run
```
--------------------------------
### Loading HTTP Client Library (Lua)
Source: https://github.com/wippyai/docs/blob/main/docs/topics/lua-httpclient.md
Demonstrates how to load the http_client library in Lua. This is the initial step before making any HTTP requests.
```lua
local http_client = require("http_client")
```
--------------------------------
### Test SDK Connection (JavaScript)
Source: https://github.com/wippyai/docs/blob/main/context/writerside-llm-guide.md
Initializes an ExampleClient with an API key and tests the connection. This snippet assumes the API_KEY environment variable is set.
```javascript
const client = new ExampleClient(process.env.API_KEY);
await client.test();
```
--------------------------------
### Initialize and Run Wippy Application
Source: https://github.com/wippyai/docs/blob/main/docs/topics/hello-world.md
These bash commands are used to manage the Wippy application. 'wippy init' generates a lock file from the source code, and 'wippy run -c' starts the application runtime with colorful console output.
```bash
# Generate lock file from source
wippy init
# Start the runtime (-c for colorful console output)
wippy run -c
```
--------------------------------
### Code Documentation
Source: https://github.com/wippyai/docs/blob/main/context/writerside-llm-guide.md
Provides an example of documenting an API endpoint using a titled code block with a specified language (bash) and including a JSON response example.
```APIDOC
## Code Documentation
```markdown
## API Reference
### Authentication
All API requests require authentication using Bearer tokens.
curl -X GET "https://api.example.com/users" \
-H "Authorization: Bearer YOUR_TOKEN" \
-H "Content-Type: application/json"
The response will include user data:
```json
{
"users": [
{
"id": 1,
"name": "John Doe",
"email": "john@example.com"
}
]
}
```
```
--------------------------------
### Setting Headers and Authentication (Lua)
Source: https://github.com/wippyai/docs/blob/main/docs/topics/lua-httpclient.md
Demonstrates how to set custom request headers, including authorization tokens, and how to use basic authentication with the http_client.
```lua
local resp, err = http_client.get("https://api.example.com/data", {
headers = {
["Authorization"] = "Bearer " .. token,
["Accept"] = "application/json"
}
})
-- Or use basic auth
local resp, err = http_client.get("https://api.example.com/data", {
auth = {user = "admin", pass = "secret"}
})
```
--------------------------------
### Create API Keys Table and Demo Key (Lua)
Source: https://github.com/wippyai/docs/blob/main/docs/topics/auth.md
The `migrate.lua` script handles database schema migration by creating an `api_keys` table if it doesn't exist. It also generates and inserts a demo API key if one is not already present. This ensures a functional starting state for API key management. Dependencies include `sql`, `logger`, and `crypto` modules.
```lua
local sql = require("sql")
local logger = require("logger")
local crypto = require("crypto")
local function main()
local db, err = sql.get("app:db")
if err then
logger:error("failed to connect", {error = tostring(err)})
return 1
end
local _, exec_err = db:execute([[
CREATE TABLE IF NOT EXISTS api_keys (
id INTEGER PRIMARY KEY AUTOINCREMENT,
api_key TEXT UNIQUE NOT NULL,
user_id TEXT NOT NULL,
role TEXT NOT NULL DEFAULT 'user',
created_at INTEGER NOT NULL
)
]])
if exec_err then
db:release()
logger:error("migration failed", {error = tostring(exec_err)})
return 1
end
-- Check if demo key exists
local rows, _ = db:query("SELECT api_key FROM api_keys WHERE user_id = ?", {"demo"})
if #rows == 0 then
local demo_key, key_err = crypto.random.string(32)
if key_err then
db:release()
return 1
end
db:execute(
"INSERT INTO api_keys (api_key, user_id, role, created_at) VALUES (?, ?, ?, ?)",
{demo_key, "demo", "user", os.time()}
)
logger:info("demo API key created", {api_key = demo_key})
else
logger:info("demo API key exists", {api_key = rows[1].api_key})
end
db:release()
return 0
end
return { main = main }
```
--------------------------------
### Lua: Get Node Position Information
Source: https://github.com/wippyai/docs/blob/main/docs/topics/lua-treesitter.md
Provides Lua code examples for retrieving position information of a Tree-sitter node, including byte offsets and row/column coordinates. It also shows how to get the source text associated with a node.
```lua
-- Byte offsets
local start = node:start_byte()
local end_ = node:end_byte()
-- Row/column positions (0-based)
local start_pt = node:start_point() -- {row = 0, column = 0}
local end_pt = node:end_point() -- {row = 0, column = 12}
-- Source text
local text = node:text()
```
--------------------------------
### Initialize Token Store with Lua
Source: https://github.com/wippyai/docs/blob/main/docs/topics/lua-security.md
Provides an example of initializing a TokenStore in Lua. It includes error handling for cases where the store might be invalid or not found.
```lua
local store, err = security.token_store("app:tokens")
if err then
if errors.is(err, errors.INVALID) then
print("Invalid request:", err:message())
end
return nil, err
end
```
--------------------------------
### Users API - Get User Profile
Source: https://github.com/wippyai/docs/blob/main/context/writerside-llm-guide.md
Retrieves detailed information for a specific user using their unique identifier.
```APIDOC
## GET /api/v1/users/{userId}
### Description
Returns detailed information about a specific user.
### Method
GET
### Endpoint
/api/v1/users/{userId}
### Parameters
#### Path Parameters
- **userId** (string) - Required - The unique user identifier
### Request Example
```http
GET /api/v1/users/user_123 HTTP/1.1
Host: api.example.com
Authorization: Bearer {token}
```
### Response
#### Success Response (200)
- **id** (string) - The unique identifier of the user
- **name** (string) - The full name of the user
- **email** (string) - The email address of the user
- **created_at** (string) - The timestamp when the user was created
#### Response Example (200)
```json
{
"id": "user_123",
"name": "John Doe",
"email": "john@example.com",
"created_at": "2023-01-15T10:30:00Z"
}
```
#### Error Response (404)
- **error** (string) - A message indicating the error
- **code** (string) - An error code
#### Response Example (404)
```json
{
"error": "User not found",
"code": "USER_NOT_FOUND"
}
```
```
--------------------------------
### Configure Multiple Databases
Source: https://github.com/wippyai/docs/blob/main/docs/topics/system-database.md
Example demonstrating how to configure multiple databases for an application, including PostgreSQL, MySQL, and SQLite. Each database has its own connection details and lifecycle settings.
```yaml
entries:
# Primary database
- name: users_db
kind: db.sql.postgres
host_env: "USERS_DB_HOST"
port: 5432
database: "users"
username_env: "USERS_DB_USER"
password_env: "USERS_DB_PASSWORD"
lifecycle:
auto_start: true
# Analytics database
- name: analytics_db
kind: db.sql.mysql
host_env: "ANALYTICS_DB_HOST"
port: 3306
database: "analytics"
username_env: "ANALYTICS_DB_USER"
password_env: "ANALYTICS_DB_PASSWORD"
lifecycle:
auto_start: true
# Local cache
- name: cache
kind: db.sql.sqlite
file: "/var/cache/app.db"
lifecycle:
auto_start: true
```
--------------------------------
### Add a Lua Process
Source: https://github.com/wippyai/docs/blob/main/docs/topics/getting-started-quickstart.md
Adds a background process to the Wippy application, defined in `src/worker.lua`. This process continuously listens for messages on its inbox and prints received payloads.
```yaml
- name: worker
kind: process.lua
source: file://worker.lua
method: main
modules:
- process
lifecycle:
auto_start: true
```
--------------------------------
### Dispatcher Implementation and Registration (Go)
Source: https://github.com/wippyai/docs/blob/main/docs/topics/internal-dispatch.md
Shows how to implement a dispatcher, which groups related handlers. It defines the Handler and ResultReceiver interfaces and provides an example of registering a custom command handler and integrating the dispatcher into the boot process.
```go
type Handler interface {
Handle(ctx context.Context, cmd Command, tag uint64, receiver ResultReceiver) error
}
type ResultReceiver interface {
CompleteYield(tag uint64, data any, err error)
}
type Dispatcher struct {
// service state
}
func (d *Dispatcher) RegisterAll(register func(id dispatcher.CommandID, h dispatcher.Handler)) {
register(myapi.MyCommand, dispatcher.HandlerFunc(d.handleMyCommand))
}
func (d *Dispatcher) handleMyCommand(ctx context.Context, cmd Command, tag uint64, receiver ResultReceiver) error {
c := cmd.(*myapi.MyCmd)
go func() {
result := doWork(c)
if ctx.Err() == nil {
receiver.CompleteYield(tag, result, nil)
}
}()
return nil
}
func MyDispatcher() boot.Component {
return boot.New(boot.P{
Name: "dispatcher.myservice",
DependsOn: []boot.Name{DispatcherName},
Load: func(ctx context.Context) (context.Context, error) {
reg := dispatcher.GetRegistrar(ctx)
svc := myservice.NewDispatcher()
svc.RegisterAll(reg.Register)
return ctx, nil
},
})
}
```
--------------------------------
### Pre-Match vs Post-Match Middleware Example (YAML)
Source: https://github.com/wippyai/docs/blob/main/docs/topics/http-router.md
YAML configuration illustrating the placement and purpose of pre-match (middleware) and post-match (post_middleware) directives.
```yaml
middleware: # Pre-match: all requests to this router
- cors
- compress
- token_auth # Enriches context with actor/scope
post_middleware: # Post-match: matched routes only
- endpoint_firewall # Uses actor from token_auth
```
--------------------------------
### Code Documentation with XML Code-Block
Source: https://github.com/wippyai/docs/blob/main/context/writerside-llm-guide.md
Illustrates documenting API references and providing code examples using the `` semantic XML element, specifying language and title.
```markdown
## API Reference
### Authentication
All API requests require authentication using Bearer tokens.
curl -X GET "https://api.example.com/users" \
-H "Authorization: Bearer YOUR_TOKEN" \
-H "Content-Type: application/json"
The response will include user data:
```json
{
"users": [
{
"id": 1,
"name": "John Doe",
"email": "john@example.com"
}
]
}
```
```
--------------------------------
### Service Initialization and Running (Bash)
Source: https://github.com/wippyai/docs/blob/main/docs/topics/task-queue.md
Commands to initialize and run the Wippy.ai service. This includes creating a data directory, initializing the service, and starting it. These commands are essential for deploying and operating the task management service.
```bash
mkdir -p data
wippy init
wippy run
```
--------------------------------
### Create Token with Lua
Source: https://github.com/wippyai/docs/blob/main/docs/topics/lua-security.md
Demonstrates creating an authentication token using the TokenStore in Lua. It shows how to define an actor, scope, and token options including expiration and metadata.
```lua
local actor = security.new_actor("user:123", {role = "user"})
local scope = security.named_scope("app:default")
local token, err = store:create(actor, scope, {
expiration = "24h", -- or milliseconds
meta = {
login_ip = request_ip,
user_agent = user_agent
}
})
```
--------------------------------
### Implement Lua Process Function
Source: https://github.com/wippyai/docs/blob/main/docs/topics/getting-started-quickstart.md
Implements a Lua background process that continuously receives messages from its inbox. It prints each received payload to the console. The loop breaks if the inbox is closed.
```lua
local process = require("process")
local function main()
local inbox = process.inbox()
while true do
local payload, ok = inbox:receive()
if not ok then break end
print("Received:", payload)
end
end
return main
```
--------------------------------
### Real-Time Chat Example
Source: https://github.com/wippyai/docs/blob/main/docs/topics/lua-websocket.md
Demonstrates how to establish a WebSocket connection for a real-time chat application, including joining a room and receiving messages.
```APIDOC
## Real-Time Chat Example
This example illustrates how to connect to a real-time chat service, join a specific room, and process incoming messages.
### Connection Establishment
- **Method**: `websocket.connect`
- **Endpoint**: `wss://chat.example.com/ws`
- **Headers**: Includes an `Authorization` header with a Bearer token.
### Joining a Room
After connecting, a JSON message with `type = "join"` and the `room_id` is sent to join the desired chat room.
### Message Handling
Incoming messages are received through a channel and decoded from JSON. A callback function `on_message` is used to process each message.
### Code Example
```lua
local function connect_chat(room_id, on_message)
local client, err = websocket.connect("wss://chat.example.com/ws", {
headers = {["Authorization"] = "Bearer " .. token}
})
if err then
return nil, err
end
-- Join room
client:send(json.encode({
type = "join",
room = room_id
}))
-- Message loop
local ch = client:channel()
while true do
local msg, ok = ch:receive()
if not ok then break end
local data = json.decode(msg.data)
on_message(data)
end
client:close()
end
```
```
--------------------------------
### Get Structured Call Stack
Source: https://github.com/wippyai/docs/blob/main/docs/topics/lua-errors.md
Provides an example of retrieving a structured call stack for an error using `errors.call_stack`. The output includes the thread and a list of frames, each with source file, line number, and function name.
```lua
local stack = errors.call_stack(err)
if stack then
print("Thread:", stack.thread)
for _, frame in ipairs(stack.frames) do
print(frame.source .. ":" .. frame.line, frame.name)
end
end
```
--------------------------------
### Creating a Process with Options in Lua
Source: https://github.com/wippyai/docs/blob/main/docs/topics/lua-exec.md
This section illustrates various ways to create a new process using an executor. It covers executing simple commands, specifying a working directory, setting environment variables, and running shell scripts with custom environments. The 'options' table is key for these configurations.
```lua
-- Simple command
local proc, err = executor:exec("echo 'Hello, World!'")
-- With working directory
local proc = executor:exec("npm install", {
work_dir = "/app/project"
})
-- With environment variables
local proc = executor:exec("python script.py", {
work_dir = "/scripts",
env = {
PYTHONPATH = "/app/lib",
DEBUG = "true",
API_KEY = api_key
}
})
-- Run shell script
local proc = executor:exec("./deploy.sh production", {
work_dir = "/app/scripts",
env = {
DEPLOY_ENV = "production"
}
})
```
--------------------------------
### Spawn Process and Monitor for EXIT Events
Source: https://github.com/wippyai/docs/blob/main/docs/topics/processes.md
Spawns a new process designated for monitoring and waits for an EXIT event. It uses `process.events()` to get an event channel and `process.spawn_monitored()` to start the process. Includes timeout handling.
```lua
local events_ch = process.events()
local worker_pid, err = process.spawn_monitored(
"app.test.process:events_exit_worker",
"app:processes"
)
if err then
return false, "spawn failed: " .. err
end
-- Wait for EXIT event
local timeout = time.after("3s")
local result = channel.select {
events_ch:case_receive(),
timeout:case_receive(),
}
if result.channel == timeout then
return false, "timeout waiting for EXIT event"
end
local event = result.value
if event.kind == process.event.EXIT then
print("Worker exited:", event.from)
if event.error then
print("Exit error:", event.error)
end
-- Access return value via event.result
end
```
--------------------------------
### Registering a Service Handler (Go)
Source: https://github.com/wippyai/docs/blob/main/docs/topics/internal-kinds.md
Shows how to register a custom service handler, 'myservice', within the application's boot sequence. This handler subscribes to entries matching the 'myservice.*' pattern.
```go
func MyService() boot.Component {
return boot.New(boot.P{
Name: "myservice",
DependsOn: []boot.Name{core.RegistryName},
Load: func(ctx context.Context) (context.Context, error) {
handlers := bootpkg.GetHandlerRegistry(ctx)
handlers.RegisterListener("myservice.*", manager)
return ctx, nil
},
})
}
```
--------------------------------
### Get Environment Variable Value in Lua
Source: https://github.com/wippyai/docs/blob/main/docs/topics/lua-env.md
Retrieves the value of a specific environment variable. It can be used to fetch configuration, secrets, or runtime settings. Includes examples for handling missing variables and providing default values.
```lua
-- Get database connection string
local db_url = env.get("DATABASE_URL")
if not db_url then
return nil, errors.new("INVALID", "DATABASE_URL not configured")
end
-- Get with fallback
local port = env.get("PORT") or "8080"
local host = env.get("HOST") or "localhost"
-- Get secrets
local api_key = env.get("API_SECRET_KEY")
local jwt_secret = env.get("JWT_SECRET")
-- Configuration
local log_level = env.get("LOG_LEVEL") or "info"
local debug_mode = env.get("DEBUG") == "true"
```
--------------------------------
### Command Line Test Execution
Source: https://github.com/wippyai/docs/blob/main/docs/topics/testing.md
Provides examples of how to run Wippy tests from the command line. It shows the basic command to run all tests and how to filter tests by providing patterns as arguments after the test runner specification.
```bash
wippy run app:test_runner app:terminal
```
```bash
# Run tests containing "errors"
wippy run app:test_runner app:terminal -- errors
```
```bash
# Run tests containing "channel" or "time"
wippy run app:test_runner app:terminal -- channel time
```
--------------------------------
### Wippy CLI Reference
Source: https://github.com/wippyai/docs/blob/main/docs/topics/hello-world.md
This table lists common Wippy command-line interface commands and their descriptions. It includes commands for initialization, running the application with various options (color, verbose, silent), and generating the lock file.
```markdown
| Command | Description |
|---------|-------------|
| `wippy init` | Generate lock file from `src/` |
| `wippy run` | Start runtime from lock file |
| `wippy run -c` | Start with colorful console output |
| `wippy run -v` | Start with verbose debug logging |
| `wippy run -s` | Start in silent mode (no console logs) |
```
--------------------------------
### Configure MySQL Read Replica
Source: https://github.com/wippyai/docs/blob/main/docs/topics/system-database.md
Example of configuring a MySQL read replica. This setup specifies connection details for a read-only user, including host, port, database name, and password retrieval via environment variable.
```yaml
- name: mysql_replica
kind: db.sql.mysql
host: "replica.db.example.com"
port: 3306
database: "app"
username: "readonly"
password_env: "REPLICA_PASSWORD"
pool:
max_open: 20
max_idle: 5
max_lifetime: "30m"
options:
charset: "utf8mb4"
parseTime: "true"
readTimeout: "30s"
```
--------------------------------
### Lua: Get Language Metadata
Source: https://github.com/wippyai/docs/blob/main/docs/topics/lua-treesitter.md
Shows Lua examples for retrieving language-specific metadata from Tree-sitter, including ABI version, node kind count, field count, and methods for looking up node kinds and fields by ID or name.
```lua
local lang = treesitter.language("go")
print(lang:version()) -- ABI version
print(lang:node_kind_count()) -- number of node types
print(lang:field_count()) -- number of fields
-- Node kind lookup
local kind = lang:node_kind_for_id(1)
local id = lang:id_for_node_kind("identifier", true)
local is_named = lang:node_kind_is_named(1)
-- Field lookup
local field_name = lang:field_name_for_id(1)
local field_id = lang:field_id_for_name("name")
```
--------------------------------
### Initialize Cloud Storage Client (Lua)
Source: https://github.com/wippyai/docs/blob/main/docs/topics/lua-cloudstorage.md
Loads the cloud storage module to prepare for interaction with S3-compatible storage services.
```lua
local cloudstorage = require("cloudstorage")
```
--------------------------------
### Lua API for Command Execution
Source: https://github.com/wippyai/docs/blob/main/docs/topics/system-exec.md
Demonstrates using the Lua Exec Module to get an executor instance and execute a command. It shows how to capture standard output, start the process, read its output, wait for completion, and clean up resources.
```lua
local exec = require("exec")
local executor, err = exec.get("app:shell")
if err then return nil, err end
local proc = executor:exec("git status", {
work_dir = "/app/repo"
})
local stdout = proc:stdout_stream()
proc:start()
local output = stdout:read()
proc:wait()
stdout:close()
executor:release()
```
--------------------------------
### Configure Standard SQL Databases (YAML)
Source: https://github.com/wippyai/docs/blob/main/docs/topics/system-database.md
This YAML configuration snippet demonstrates how to set up standard SQL databases like PostgreSQL, MySQL, MSSQL, and Oracle. It includes connection details, pooling settings, and lifecycle management. Ensure sensitive information like passwords are not hardcoded.
```yaml
# src/data/_index.yaml
version: "1.0"
namespace: app.data
entries:
- name: main_db
kind: db.sql.postgres
host: "localhost"
port: 5432
database: "myapp"
username: "dbuser"
password: "dbpass"
pool:
max_open: 25
max_idle: 5
max_lifetime: "1h"
options:
sslmode: "disable"
lifecycle:
auto_start: true
```
--------------------------------
### Uploading Files (Lua)
Source: https://github.com/wippyai/docs/blob/main/docs/topics/lua-httpclient.md
Illustrates how to upload files using an HTTP POST request. This example includes setting form data alongside the file upload.
```lua
local resp, err = http_client.post("https://api.example.com/upload", {
form = {title = "My Document"},
files = {
{
name = "attachment", -- form field name
filename = "report.pdf", -- original filename
content = pdf_data, -- file content
content_type = "application/pdf"
}
}
})
```
--------------------------------
### Implement HTTP Handler Function
Source: https://github.com/wippyai/docs/blob/main/docs/topics/getting-started-quickstart.md
Implements a Lua handler function for an HTTP endpoint. It retrieves the 'name' query parameter from the incoming request, constructs an HTTP response with a JSON payload containing a greeting, and sets the appropriate headers.
```lua
local http = require("http")
local json = require("json")
local function handler()
local req = http.request()
local name = req:query("name") or "World"
local res = http.response()
res:set_status(200)
res:set_header("Content-Type", "application/json")
res:write(json.encode({
message = string.format("Hello, %s!", name)
}))
return res
end
return { handler = handler }
```
--------------------------------
### Implement Lua Entry Point Function
Source: https://github.com/wippyai/docs/blob/main/docs/topics/getting-started-quickstart.md
Implements a simple Lua function named `main` that takes an input, extracts a 'name' parameter (defaulting to 'World'), and returns a JSON-encodable table with a greeting message. It requires the 'json' module.
```lua
local json = require("json")
local function main(input)
local name = input and input.name or "World"
return {
message = string.format("Hello, %s!", name)
}
end
return main
```