### Install ZEN Engine for Go Source: https://docs.gorules.io/developers/sdks/go Installs the ZEN Engine Go package using the go get command. This is the first step to integrating the rules engine into your Go application. ```bash go get github.com/gorules/zen-go ``` -------------------------------- ### Making HTTP Requests with the 'http' Library in JavaScript Source: https://docs.gorules.io/learn/authoring/function-nodes Demonstrates how to make asynchronous HTTP GET requests to external APIs using the built-in `http` library. This example fetches exchange rates based on a provided currency. ```javascript import http from 'http'; export const handler = async (input) => { const response = await http.get('https://api.example.com/rates', { params: { currency: input.currency } }); return { exchangeRate: response.data.rate, updatedAt: response.data.timestamp }; }; ``` -------------------------------- ### Get Start and End of Date Periods (JavaScript) Source: https://docs.gorules.io/learn/zen-language/dates Demonstrates how to get the start and end of various time periods (day, month, year, week, quarter) using the `startOf` and `endOf` methods. Assumes a `d` function for date instantiation. ```javascript d("2024-01-15").startOf("day") // 2024-01-15T00:00:00 d("2024-01-15").endOf("day") // 2024-01-15T23:59:59 d("2024-01-15").startOf("month") // 2024-01-01T00:00:00 d("2024-01-15").endOf("month") // 2024-01-31T23:59:59 d("2024-01-15").startOf("year") // 2024-01-01T00:00:00 d("2024-01-15").endOf("year") // 2024-12-31T23:59:59 d("2024-01-15").startOf("week") // 2024-01-15T00:00:00 (Monday) d("2024-01-15").endOf("week") // 2024-01-21T23:59:59 (Sunday) d("2024-05-15").startOf("quarter") // 2024-04-01T00:00:00 d("2024-05-15").endOf("quarter") // 2024-06-30T23:59:59 ``` -------------------------------- ### Install Zen Engine and PySpark Source: https://docs.gorules.io/developers/integrations/pyspark Installs the necessary libraries, zen-engine and pyspark, using pip. This is the first step to using the PySpark Rules Engine. ```bash pip install zen-engine pyspark ``` -------------------------------- ### ZEN Expression Examples Source: https://docs.gorules.io/learn/authoring/expressions Demonstrates common ZEN expression patterns for calculations, data access, and conditional logic. These examples illustrate arithmetic, comparison, logical operators, ternary expressions, null handling, and range checks. ```zen sum(map(items, #.price * #.quantity)) ``` ```zen subtotal * taxRate ``` ```zen subtotal > 100 ? 0 : 9.99 ``` ```zen subtotal + tax + shipping ``` ```zen customer.name ``` ```zen order.items[0].price ``` ```zen $nodes.CreditCheck.rating ``` ```zen $nodes.RiskScore.value ``` ```zen $nodes["My Node"].field ``` ```zen price * quantity ``` ```zen total / count ``` ```zen base + bonus ``` ```zen gross - deductions ``` ```zen amount % 100 ``` ```zen 2 ^ 10 ``` ```zen age >= 18 ``` ```zen status == "active" ``` ```zen tier != "basic" ``` ```zen score < threshold ``` ```zen isActive and hasPermission ``` ```zen isAdmin or isOwner ``` ```zen not isBlocked ``` ```zen score > 70 ? "pass" : "fail" ``` ```zen age >= 18 ? "adult" : age >= 13 ? "teen" : "child" ``` ```zen user.nickname ?? user.name ?? "Anonymous" ``` ```zen age in [18..65] ``` ```zen score in (0..100) ``` ```zen value not in [1..10] ``` -------------------------------- ### JDM Metadata Example (JSON) Source: https://docs.gorules.io/developers/jdm/standard Provides an example of the optional metadata section in a JDM file. This section can include 'version', 'author', 'description', and 'tags' to provide context and manage the decision model. ```json { "metadata": { "version": "1.0.0", "author": "team@example.com", "description": "Customer discount calculation", "tags": ["pricing", "discounts"] } } ``` -------------------------------- ### Bundled Decision Files Example (JSON) Source: https://docs.gorules.io/developers/sdks/mobile Example of decision files (pricing.json, eligibility.json) bundled within an application's assets folder. This pattern is suitable for rules that change infrequently. ```json { "version": "1.2.3", "updated": "2024-01-15T10:30:00Z", "decisions": ["pricing.json", "eligibility.json"] } ``` -------------------------------- ### Download and Load Decisions from Google Cloud Storage (Go) Source: https://docs.gorules.io/developers/sdks/go This Go code snippet demonstrates how to initialize the Zen engine by downloading and extracting decision files from a Google Cloud Storage bucket. It reads a zip file containing decisions, loads them into memory, and configures the engine's loader to retrieve them. Dependencies include the 'cloud.google.com/go/storage' and 'github.com/gorules/zen-go' packages. ```go package main import ( "archive/zip" "bytes" "context" "errors" "fmt" "io" "cloud.google.com/go/storage" zen "github.com/gorules/zen-go" ) var rules = make(map[string][]byte) func main() { // Download and extract all decisions at startup client, _ := storage.NewClient(context.TODO()) bucket := client.Bucket("my-rules-bucket") reader, _ := bucket.Object("decisions.zip").NewReader(context.TODO()) defer reader.Close() zipBytes, _ := io.ReadAll(reader) zipReader, _ := zip.NewReader(bytes.NewReader(zipBytes), int64(len(zipBytes))) for _, file := range zipReader.File { if !file.FileInfo().IsDir() { rc, _ := file.Open() content, _ := io.ReadAll(rc) rc.Close() rules[file.Name] = content } } engine := zen.NewEngine(zen.EngineConfig{ Loader: func(key string) ([]byte, error) { if data, ok := rules[key]; ok { return data, nil } return nil, errors.New("decision not found: " + key) }, }) defer engine.Dispose() response, _ := engine.Evaluate("pricing.json", map[string]any{"amount": 100}) fmt.Println(string(response.Result)) } ``` -------------------------------- ### Zen Engine Initialization and Resource Management (Go) Source: https://docs.gorules.io/developers/sdks/go This Go code snippet illustrates best practices for initializing the Zen engine and managing its resources. It emphasizes creating a single engine instance for reuse and calling 'Dispose()' upon application termination to release resources. A loader function is also shown for dynamic decision loading. ```go engine := zen.NewEngine(zen.EngineConfig{Loader: loader}) defers engine.Dispose() ``` -------------------------------- ### POST /api/onboarding/finalize Source: https://docs.gorules.io/api-reference/brms/templates/finalize-onboarding-process-with-template Completes the onboarding process by creating a new project with the selected template, including a default document and test event. ```APIDOC ## POST /api/onboarding/finalize ### Description Completes the onboarding process by creating a new project with the selected template, including a default document and test event. ### Method POST ### Endpoint /api/onboarding/finalize ### Parameters #### Request Body - **templateKey** (string) - Required - Key of the template to use for the new project ### Request Example ```json { "templateKey": "your_template_key" } ``` ### Response #### Success Response (200) - **project** (object) - The created project - **id** (string) - Unique identifier of the project - **name** (string) - Name of the project - **key** (string) - URL-friendly key of the project - **organisationId** (string) - Organisation the project belongs to - **createdAt** (string) - Timestamp when the project was created - **updatedAt** (string) - Timestamp when the project was last updated - **document** (object) - Details of the created document #### Response Example ```json { "project": { "id": "a1b2c3d4-e5f6-7890-1234-567890abcdef", "name": "New Project Name", "key": "new-project-name", "organisationId": "f0e9d8c7-b6a5-4321-0987-654321fedcba", "createdAt": "2023-10-27T10:00:00Z", "updatedAt": "2023-10-27T10:00:00Z" }, "document": { "id": "document-id-123", "name": "Default Document", "key": "default-document" } } ``` ``` -------------------------------- ### GET /api/projects/{projectId}/documents/{documentId}/ancestors Source: https://docs.gorules.io/api-reference/brms/document/list-document-ancestors Retrieves the ancestor hierarchy of a document, starting from the root and going down to the specified document. ```APIDOC ## GET /api/projects/{projectId}/documents/{documentId}/ancestors ### Description Retrieve the ancestor hierarchy of a document from root to the specified document. ### Method GET ### Endpoint /api/projects/{projectId}/documents/{documentId}/ancestors ### Parameters #### Path Parameters - **projectId** (string) - Required - Project unique identifier - **documentId** (string) - Required - Document unique identifier ### Request Example ```json { "example": "No request body for this endpoint." } ``` ### Response #### Success Response (200) - **id** (string) - Document unique identifier - **key** (string) - Document key path - **name** (string) - Document name - **parentId** (string) - Parent document ID (nullable) - **originalPath** (string) - Original path before deletion (nullable) #### Response Example ```json [ { "id": "a1b2c3d4-e5f6-7890-1234-567890abcdef", "key": "/", "name": "Root", "parentId": null, "originalPath": null }, { "id": "b2c3d4e5-f6a7-8901-2345-67890abcdef0", "key": "/folder1", "name": "Folder 1", "parentId": "a1b2c3d4-e5f6-7890-1234-567890abcdef", "originalPath": null }, { "id": "c3d4e5f6-a7b8-9012-3456-7890abcdef01", "key": "/folder1/document1.json", "name": "Document 1", "parentId": "b2c3d4e5-f6a7-8901-2345-67890abcdef0", "originalPath": null } ] ``` ``` -------------------------------- ### Install GoRules BRMS on Kubernetes using Helm Source: https://docs.gorules.io/developers/platform-guides/kubernetes Installs the GoRules BRMS application on a Kubernetes cluster using Helm. Requires Helm 3.8+ and a configured `my-values.yaml` file with application and database details. ```bash helm install my-gorules-brms oci://registry-1.docker.io/gorulescharts/gorules-brms -f my-values.yaml ``` -------------------------------- ### Basic Decision Evaluation in Go Source: https://docs.gorules.io/developers/sdks/go Demonstrates how to initialize the ZEN Engine, load decision rules from a JSON file, and evaluate a decision with provided input data. It shows how to create an engine, load rules, and get a decision response. ```go package main import ( "fmt" "os" zen "github.com/gorules/zen-go" ) func main() { content, _ := os.ReadFile("./pricing-rules.json") engine := zen.NewEngine(zen.EngineConfig{}) defer engine.Dispose() decision, _ := engine.CreateDecision(content) defer decision.Dispose() response, _ := decision.Evaluate(map[string]any{ "customer": map[string]any{"tier": "gold", "yearsActive": 3}, "order": map[string]any{"subtotal": 150, "items": 5}, }) fmt.Println(string(response.Result)) // => {"discount":0.15,"freeShipping":true} } ``` -------------------------------- ### POST /api/onboarding/skip Source: https://docs.gorules.io/api-reference/brms/templates/skip-onboarding-process Marks the onboarding process as complete without creating a project from a template. This endpoint is useful for skipping the initial project setup and proceeding directly to rule development. ```APIDOC ## POST /api/onboarding/skip ### Description Marks the onboarding process as complete without creating a project from a template. ### Method POST ### Endpoint /api/onboarding/skip ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) - **description** (string) - Onboarding skipped successfully #### Response Example { "message": "Onboarding skipped successfully" } ``` -------------------------------- ### Test GoRules BRMS Installation via Port Forwarding Source: https://docs.gorules.io/developers/platform-guides/kubernetes Forwards a local port to the GoRules BRMS service in Kubernetes for testing. This allows access to the BRMS at http://localhost:4200. ```bash kubectl port-forward services/my-gorules-brms 4200:80 ``` -------------------------------- ### Get ZEN Date Components (Getters) Source: https://docs.gorules.io/learn/zen-language/dates Provides examples of using getter methods like `.year()`, `.month()`, `.day()`, etc., to extract specific components from a ZEN date object. These methods allow for granular access to date and time parts. ```ZEN // Getters d("2024-01-15").year() // 2024 d("2024-01-15").month() // 1 d("2024-01-15").day() // 15 d("2024-01-15").weekday() // 1 (Monday) d("2024-01-15 14:30").hour() // 14 d("2024-01-15 14:30").minute() // 30 d("2024-01-15 14:30:45").second() // 45 d("2024-01-15").dayOfYear() // 15 d("2024-01-15").quarter() // 1 d("2024-01-15").timestamp() // 1705276800000 ``` -------------------------------- ### Initialize ZenEngine Once in Swift Source: https://docs.gorules.io/developers/sdks/ios Illustrates the best practice of initializing a `ZenEngine` instance once and reusing it throughout the application lifecycle in Swift. This is achieved using a singleton pattern within a `RulesEngine` class. ```swift import ZenUniffi class RulesEngine { static let shared = RulesEngine() private let engine: ZenEngine private init() { engine = ZenEngine(loader: nil, customNode: nil) } func evaluate(decision: Data, context: Data) async throws -> Data { let dec = try engine.createDecision(content: decision) let response = try await dec.evaluate(context: context, options: nil) return response.result } } ``` -------------------------------- ### Docker Compose Deployment for GoRules Agent Source: https://docs.gorules.io/developers/deployment/agent/deployment Defines a Docker Compose setup for the GoRules Agent. This example configures the agent to pull rules from an S3 bucket with a specified prefix and polling interval. It also includes commented-out volume mounts for AWS credentials. ```yaml version: '3.8' services: gorules-agent: image: gorules/agent:latest ports: - "8080:8080" environment: PROVIDER__TYPE: S3 PROVIDER__BUCKET: my-rules-bucket PROVIDER__PREFIX: production/ POLL_INTERVAL: 10000 # For AWS credentials, use IAM roles or mount credentials # volumes: # - ~/.aws:/root/.aws:ro ``` -------------------------------- ### Standalone Code Editor Component Source: https://docs.gorules.io/developers/jdm/jdm-editor This snippet demonstrates the usage of the standalone `CodeEditor` component from '@gorules/jdm-editor' for custom integrations. It allows for expression editing with syntax highlighting and validation. The `JdmConfigProvider` is required for its proper functioning. The example shows a basic setup for a 'unary' type expression. ```tsx import { useState } from 'react'; import { JdmConfigProvider, CodeEditor } from '@gorules/jdm-editor'; function ExpressionEditor() { const [expression, setExpression] = useState('customer.age >= 18'); return ( ); } ``` -------------------------------- ### List Environments Source: https://docs.gorules.io/api-reference/brms/environment/list-environments Retrieves all environments for a project, including their deployment status and pending change requests. ```APIDOC ## GET /websites/gorules_io/environments ### Description Retrieves all environments for a project, including their deployment status and pending change requests. ### Method GET ### Endpoint /websites/gorules_io/environments ### Parameters #### Query Parameters - **project_id** (string) - Required - The ID of the project to list environments for. ### Response #### Success Response (200) - **environments** (array) - A list of environment objects. - **name** (string) - The name of the environment. - **status** (string) - The deployment status of the environment (e.g., 'deployed', 'pending'). - **change_requests** (integer) - The number of pending change requests for the environment. #### Response Example ```json { "environments": [ { "name": "production", "status": "deployed", "change_requests": 0 }, { "name": "staging", "status": "pending", "change_requests": 2 } ] } ``` ``` -------------------------------- ### Install Gorules JDM Editor using npm Source: https://docs.gorules.io/learn/getting-started/playground This command installs the @gorules/jdm-editor package, which is a React component for the visual editor. Ensure you have Node.js and npm installed. ```bash npm install @gorules/jdm-editor ``` -------------------------------- ### Create Environment Source: https://docs.gorules.io/api-reference/brms/environment/create-environment Creates a new environment within a specified project. ```APIDOC ## POST /projects/{projectId}/environments ### Description Creates a new environment within a specified project. ### Method POST ### Endpoint /projects/{projectId}/environments ### Parameters #### Path Parameters - **projectId** (string) - Required - The unique identifier of the project. #### Request Body - **name** (string) - Required - Name of the environment. - **type** (string) - Required - Type of the environment. - **reviewers** (array) - Optional - List of members assigned as reviewers. - **id** (string) - Required - Unique identifier of the member. - **requiredReviewers** (boolean) - Required - Whether reviewers are required. - **addToWorkflow** (boolean) - Required - Whether the environment is part of the deployment workflow. - **workflowOrder** (number) - Optional - Order position in the deployment workflow. - **approvalGroups** (array) - Required - Groups that can approve deployments. - **id** (string) - Required - Unique identifier of the group. - **name** (string) - Required - Name of the group. - **description** (string) - Optional - Description of the group. - **projectId** (string) - Required - ID of the project the group belongs to. - **roleId** (string) - Required - ID of the role assigned to the group. - **approvalMode** (string) - Optional - Approval mode for deployments to this environment. Enum: [require_one_per_team, none_create_request, require_any, none]. - **metadata** (object) - Optional - Additional metadata from the deployment provider. ### Request Example ```json { "name": "Staging", "type": "staging", "reviewers": [ { "id": "member-abc" } ], "requiredReviewers": false, "addToWorkflow": true, "workflowOrder": 2, "approvalGroups": [ { "id": "group-xyz", "name": "QA Team", "projectId": "proj-abc", "roleId": "role-123" } ], "approvalMode": "require_one_per_team", "metadata": { "provider": "gcp", "region": "us-central1" } } ``` ### Response #### Success Response (201) - **id** (string) - Unique identifier of the created environment. - **name** (string) - Name of the environment. - **type** (string) - Type of the environment. - **projectId** (string) - Unique identifier of the project the environment belongs to. - **createdAt** (string) - Timestamp when the environment was created. - **updatedAt** (string) - Timestamp when the environment was last updated. #### Response Example ```json { "id": "env-456", "name": "Staging", "type": "staging", "projectId": "proj-abc", "createdAt": "2023-01-02T11:00:00Z", "updatedAt": "2023-01-02T11:00:00Z" } ``` ``` -------------------------------- ### Node.js SDK Overview Source: https://docs.gorules.io/developers/deployment/embedded Displays a list of available SDKs for embedded deployment, including Node.js, Python, Go, Rust, Java, Kotlin, Swift, and WASM. Each SDK is presented with its name, link, icon, and color. ```javascript export const SdkOverview = () => { const sdks = [{ name: 'Node.js', href: '/developers/sdks/nodejs', icon: 'node-js', color: '#68a063' }, { name: 'Python', href: '/developers/sdks/python', icon: 'python', color: '#3776ab' }, { name: 'Go', href: '/developers/sdks/go', icon: 'golang', color: '#00add8' }, { name: 'Rust', href: '/developers/sdks/rust', icon: 'rust', color: '#ce422b' }, { name: 'Java', href: '/developers/sdks/java', icon: 'java', color: '#e76f00' }, { name: 'Kotlin', href: '/developers/sdks/kotlin', icon: '/images/kotlin.svg', color: '#7f52ff' }, { name: 'Swift', href: '/developers/sdks/swift', icon: 'swift', color: '#f05138' }, { name: 'WASM', href: '/developers/sdks/wasm', icon: '/images/wasm.svg', color: '#654ff0' }]; return
{sdks.map(sdk => {sdk.name} )}
; }; ``` -------------------------------- ### Install ZEN Engine for Python (pip, poetry, uv) Source: https://docs.gorules.io/developers/sdks/python Installs the ZEN Engine library for Python using different package managers. Ensure you have Python and your chosen package manager installed. ```bash pip install zen-engine ``` ```bash poetry add zen-engine ``` ```bash uv add zen-engine ``` -------------------------------- ### Install GoRules ZEN Engine with pnpm Source: https://docs.gorules.io/developers/sdks/wasm Installs the @gorules/zen-engine package using pnpm. Configure supported architectures in pnpm-workspace.yaml. ```yaml supportedArchitectures: cpu: - current - wasm32 ``` ```bash pnpm add @gorules/zen-engine ``` -------------------------------- ### Token Creation and Details Source: https://docs.gorules.io/api-reference/brms/personal-access-token/regenerate-token-1 This section details the API endpoint for creating new tokens and the structure of the response, which includes token details, associated project permissions, and user information. ```APIDOC ## POST /api/tokens ### Description Creates a new API token with specified permissions and project access. Returns the generated token along with its associated details. ### Method POST ### Endpoint /api/tokens ### Parameters #### Query Parameters - **description** (string) - Optional - Description of the token. - **allProjects** (boolean) - Optional - Whether the token has access to all projects. - **projects** (array) - Optional - List of project IDs the token should have access to. - **expiresAt** (string) - Optional - Timestamp for token expiration (ISO 8601 format). #### Request Body (No request body is typically sent for token creation, parameters are usually in query or path) ### Request Example (Example for a POST request to create a token with specific permissions) ``` POST /api/tokens?description=My%20Project%20Token&allProjects=false&expiresAt=2024-12-31T23:59:59Z HTTP/1.1 Host: api.gorules.io Content-Type: application/json { "permissions": [ "releases:deploy", "documents:view-content" ], "projects": [ "project-id-1", "project-id-2" ] } ``` ### Response #### Success Response (201 Created) - **id** (string) - Unique identifier of the token. - **description** (string) - Description of the token. - **permissions** (array) - List of permissions granted to this token. - **allProjects** (boolean) - Whether the token has access to all projects. - **projects** (array) - List of projects the token has access to. - **id** (string) - Unique identifier of the project. - **name** (string) - Name of the project. - **key** (string) - Project key. - **organisationId** (string) - Organisation ID the project belongs to. - **version** (string) - Project version. - **createdAt** (string) - Timestamp when the project was created. - **updatedAt** (string) - Timestamp when the project was last updated. - **protected** (boolean) - Whether the project is protected. - **user** (object) - User who owns the token. - **id** (string) - Unique identifier of the user. - **email** (string) - Email address of the user. - **firstName** (string) - First name of the user. - **lastName** (string) - Last name of the user. - **type** (string) - User type. - **status** (string) - User status. - **isService** (boolean) - Whether the user is a service account. - **createdAt** (string) - Timestamp when the user was created. - **updatedAt** (string) - Timestamp when the user was last updated. - **createdAt** (string) - Timestamp when the token was created. - **updatedAt** (string) - Timestamp when the token was last updated. - **expiresAt** (string) - Timestamp when the token expires, null if indefinite. - **token** (string) - The generated token value. #### Response Example ```json { "id": "token-uuid-1234", "description": "My Project Token", "permissions": [ "releases:deploy", "documents:view-content" ], "allProjects": false, "projects": [ { "id": "project-uuid-abc", "name": "Project Alpha", "key": "PA", "organisationId": "org-uuid-xyz", "version": "1.0.0", "createdAt": "2023-01-15T10:00:00Z", "updatedAt": "2023-01-15T10:00:00Z", "protected": false } ], "user": { "id": "user-uuid-789", "email": "user@example.com", "firstName": "John", "lastName": "Doe", "type": "member", "status": "active", "isService": false, "createdAt": "2022-05-20T08:30:00Z", "updatedAt": "2023-03-10T11:00:00Z" }, "createdAt": "2023-10-27T14:30:00Z", "updatedAt": "2023-10-27T14:30:00Z", "expiresAt": "2024-12-31T23:59:59Z", "token": "generated-secret-token-value" } ``` #### Error Response (400 Bad Request) - **error** (string) - Description of the error. #### Error Response Example ```json { "error": "Invalid permissions specified." } ``` ``` -------------------------------- ### POST /api/deployments Source: https://docs.gorules.io/api-reference/brms/deployments/create-deployment Creates a new deployment with the specified cloud storage provider configuration. ```APIDOC ## POST /api/deployments ### Description Create a new deployment with the specified cloud storage provider configuration. ### Method POST ### Endpoint /api/deployments ### Parameters #### Request Body - **name** (string) - Required - Name of the deployment - **description** (string) - Optional - Description of the deployment - **provider** (string) - Required - Cloud storage provider type (aws_s3, azure_storage, google_cloud_storage) - **configuration** (object) - Required - Provider-specific configuration settings - **secrets** (object) - Optional - Provider-specific secrets (e.g., access keys, credentials) ### Request Example ```json { "name": "my-deployment", "description": "Production deployment", "provider": "aws_s3", "configuration": { "bucket_name": "my-bucket" }, "secrets": { "access_key_id": "YOUR_ACCESS_KEY", "secret_access_key": "YOUR_SECRET_KEY" } } ``` ### Response #### Success Response (200) - **id** (string) - Unique identifier of the deployment - **name** (string) - Name of the deployment - **description** (string) - Description of the deployment - **provider** (string) - Cloud storage provider type (aws_s3, azure_storage, google_cloud_storage) #### Response Example ```json { "id": "a1b2c3d4-e5f6-7890-1234-567890abcdef", "name": "my-deployment", "description": "Production deployment", "provider": "aws_s3" } ``` ``` -------------------------------- ### Install GoRules ZEN Engine with npm Source: https://docs.gorules.io/developers/sdks/wasm Installs the @gorules/zen-engine package for WASM 32-bit architecture using npm. Ensure your environment supports WASM. ```bash npm install @gorules/zen-engine --cpu=wasm32 ``` -------------------------------- ### Manage ZenEngine Resources with Java Source: https://docs.gorules.io/developers/sdks/java Demonstrates the best practice of using try-with-resources for managing ZenEngine instances, ensuring native resources are properly released. The ZenEngine implements AutoCloseable. ```java import io.gorules.zen_engine.ZenEngine; try (var engine = new ZenEngine(null, null)) { // use engine } ``` -------------------------------- ### Get Current ZEN Date/Time Source: https://docs.gorules.io/learn/zen-language/dates Illustrates how to obtain the current date and time in ZEN using the `d()` function. It also shows how to get the current time in a specified timezone. ```ZEN d() // Current date and time d("America/Los_Angeles") // Current time in LA timezone ``` -------------------------------- ### Install GoRules ZEN Engine (Node.js) Source: https://docs.gorules.io/developers/sdks/nodejs Install the GoRules ZEN Engine package in your Node.js project using npm, yarn, or pnpm. This is the first step to integrating GoRules into your application. ```bash npm install @gorules/zen-engine ``` ```bash yarn add @gorules/zen-engine ``` ```bash pnpm add @gorules/zen-engine ``` -------------------------------- ### List Integrations Source: https://docs.gorules.io/api-reference/brms/integration/list-integrations Retrieve a paginated list of integrations for the specified project. ```APIDOC ## GET /websites/gorules_io/integrations ### Description Retrieve a paginated list of integrations for the specified project. ### Method GET ### Endpoint /websites/gorules_io/integrations ### Parameters #### Query Parameters - **page** (integer) - Optional - The page number to retrieve. - **limit** (integer) - Optional - The number of integrations to return per page. ### Request Example ``` GET /websites/gorules_io/integrations?page=1&limit=20 ``` ### Response #### Success Response (200) - **integrations** (array) - A list of integration objects. - **id** (string) - The unique identifier of the integration. - **name** (string) - The name of the integration. - **status** (string) - The current status of the integration. #### Response Example ```json { "integrations": [ { "id": "integration_123", "name": "Example Integration", "status": "active" } ] } ``` ``` -------------------------------- ### Install ZEN Engine and Polars Source: https://docs.gorules.io/developers/integrations/polars Installs the necessary Python packages, zen-engine and polars, using pip. This is the first step to using the ZEN Engine with Polars DataFrames. ```bash pip install zen-engine polars ``` -------------------------------- ### Create Environment Source: https://docs.gorules.io/api-reference/brms/environment/create-environment Creates a new environment within a project. This environment can be of type 'brms' or 'deployment'. ```APIDOC ## POST /websites/gorules_io/environments ### Description Creates a new environment. Environments are used to manage different deployment stages or configurations for a project. ### Method POST ### Endpoint /websites/gorules_io/environments ### Parameters #### Query Parameters - **projectId** (string) - Required - The ID of the project to which the environment will belong. #### Request Body - **name** (string) - Required - The name of the environment. - **type** (string) - Required - The type of environment. Must be one of: `brms`, `deployment`. - **accessToken** (string) - Optional - An access token for the environment. - **key** (string) - Optional - A unique key for BRMS type environments. - **releaseId** (string) - Optional - The ID of the release to associate with the environment. - **deploymentId** (string) - Optional - The ID of the deployment to associate with the environment. ### Request Example ```json { "name": "Production Environment", "type": "deployment", "accessToken": "your_access_token", "releaseId": "a1b2c3d4-e5f6-7890-1234-567890abcdef", "deploymentId": "f0e9d8c7-b6a5-4321-0987-fedcba098765" } ``` ### Response #### Success Response (200 or 201) - **id** (string) - Unique identifier of the environment. - **name** (string) - Name of the environment. - **accessToken** (string) - Access token for the environment. - **type** (string) - Type of environment (`brms` or `deployment`). - **key** (string) - Unique key for BRMS type environments. - **release** (object) - Currently deployed release information. - **id** (string) - Unique identifier of the release. - **name** (string) - Name of the release. - **version** (number) - Version number of the release (legacy). - **semanticVersion** (string) - Semantic version string of the release. - **status** (string) - Status of the release. - **createdAt** (string) - Timestamp when the release was created. - **releaseId** (string) - ID of the currently deployed release. - **deploymentId** (string) - ID of the associated deployment. - **deployment** (object) - Deployment configuration for the environment. - **id** (string) - Unique identifier of the deployment. - **name** (string) - Name of the deployment. - **description** (string) - Description of the deployment. - **provider** (string) - Cloud provider for the deployment. - **configuration** (object) - Provider-specific configuration. - **organisationId** (string) - ID of the organisation. - **createdAt** (string) - Timestamp when the deployment was created. - **updatedAt** (string) - Timestamp when the deployment was last updated. - **deletedAt** (string) - Timestamp when the deployment was deleted. - **projectId** (string) - ID of the project. - **project** (object) - Project details. - **id** (string) - Unique identifier of the project. #### Response Example ```json { "id": "123e4567-e89b-12d3-a456-426614174000", "name": "Production Environment", "accessToken": "your_access_token", "type": "deployment", "key": null, "release": { "id": "a1b2c3d4-e5f6-7890-1234-567890abcdef", "name": "v1.0.0", "version": 1, "semanticVersion": "1.0.0", "status": "deployed", "createdAt": "2023-10-27T10:00:00Z" }, "releaseId": "a1b2c3d4-e5f6-7890-1234-567890abcdef", "deploymentId": "f0e9d8c7-b6a5-4321-0987-fedcba098765", "deployment": { "id": "f0e9d8c7-b6a5-4321-0987-fedcba098765", "name": "AWS Deployment", "description": "Production deployment on AWS", "provider": "aws", "configuration": { "region": "us-east-1" }, "organisationId": "09876543-21fe-dcba-0987-654321fedcba", "createdAt": "2023-10-26T09:00:00Z", "updatedAt": "2023-10-26T09:00:00Z", "deletedAt": null }, "projectId": "abcdef12-3456-7890-abcd-ef1234567890", "project": { "id": "abcdef12-3456-7890-abcd-ef1234567890" } } ``` ``` -------------------------------- ### Evaluate First Decision in Kotlin Source: https://docs.gorules.io/developers/sdks/kotlin Demonstrates how to initialize the ZenEngine, load a pricing rule, and evaluate a decision with sample input data. It uses coroutines for asynchronous operations and prints the decision result. ```kotlin import io.gorules.zen_engine.kotlin.ZenEngine import io.gorules.zen_engine.kotlin.JsonBuffer import kotlinx.coroutines.runBlocking fun main() = runBlocking { val ruleJson = object {}.javaClass.getResourceAsStream("/rules/pricing.json")!!.readBytes() ZenEngine(null, null).use { engine -> val decision = engine.createDecision(JsonBuffer(ruleJson)) val input = JsonBuffer(""" { "customer": { "tier": "gold", "yearsActive": 3 }, "order": { "subtotal": 150, "items": 5 } } """) val response = decision.evaluate(input, null) println(response.result) // => {"discount":0.15,"freeShipping":true} } } ``` -------------------------------- ### Disabling Pass-through Behavior Example Source: https://docs.gorules.io/learn/getting-started/key-concepts Demonstrates how to disable pass-through mode on a node to return only that node's output fields. The example shows the input and the final output after the data has flowed through the graph. ```javascript // Input { "customer": { "tier": "gold", "yearsActive": 3 }, "order": { "subtotal": 150, "items": 5 } } // Output (after flowing through the graph) { "discount": 15, "freeShipping": true, "loyaltyBonus": 225 } ``` -------------------------------- ### Create Integration Source: https://docs.gorules.io/api-reference/brms/integration/list-integrations Creates a new integration for the specified project. ```APIDOC ## POST /websites/gorules_io/integrations ### Description Creates a new integration for the specified project. You need to provide the integration type, configuration, name, and kind. ### Method POST ### Endpoint /websites/gorules_io/integrations ### Request Body - **type** (string) - Required - The type of the integration (e.g., 'webhook', 'api'). - **config** (object) - Required - Configuration details specific to the integration type. - **name** (string) - Required - A user-defined name for the integration. - **kind** (string) - Required - The kind of integration (e.g., 'source', 'destination'). ### Request Example ```json { "type": "webhook", "config": { "url": "https://example.com/new_webhook", "method": "POST" }, "name": "New Notification Hook", "kind": "destination" } ``` ### Response #### Success Response (201 Created) - **id** (string) - Unique identifier for the newly created integration. - **type** (string) - The type of the integration. - **config** (object) - Configuration details specific to the integration type. - **name** (string) - A user-defined name for the integration. - **kind** (string) - The kind of integration. - **projectId** (string) - The ID of the project this integration belongs to. - **createdAt** (string) - Timestamp when the integration was created. - **updatedAt** (string) - Timestamp when the integration was last updated. #### Response Example ```json { "id": "int_def456", "type": "webhook", "config": { "url": "https://example.com/new_webhook", "method": "POST" }, "name": "New Notification Hook", "kind": "destination", "projectId": "proj_xyz789", "createdAt": "2023-10-27T11:00:00Z", "updatedAt": "2023-10-27T11:00:00Z" } ``` ``` -------------------------------- ### Git Commit Example (Bash) Source: https://docs.gorules.io/developers/jdm/standard An example of a Git commit message for updating a JDM file. It emphasizes the importance of meaningful commit messages that clearly describe the changes made to the business rules. ```bash git commit -m "Add enterprise tier discount (20% for orders > $10k)" ``` -------------------------------- ### Example Applicant Input Data (JSON) Source: https://docs.gorules.io/learn/tutorials/eligibility Provides a sample JSON object representing applicant data, including age, income, employment history, credit score, and loan details. This structure is used as input for eligibility rule evaluation. ```json { "applicant": { "age": 32, "income": 75000, "employmentYears": 4, "creditScore": 720 }, "loan": { "amount": 25000, "purpose": "home_improvement" } } ```