{"_id":"@databridges/apifront-proxy","_rev":"4-5291a9582758e1d521e0f3403810aa9a","name":"@databridges/apifront-proxy","dist-tags":{"latest":"1.0.4"},"versions":{"1.0.0":{"name":"@databridges/apifront-proxy","version":"1.0.0","keywords":["optomate","databridges","apifront","api","authentication","realtime","real-time"],"author":{"url":"https://www.optomate.io","name":"Optomate Technologies Private Limited.","email":"tech@optomate.io"},"license":"Apache-2.0","_id":"@databridges/apifront-proxy@1.0.0","maintainers":[{"name":"optomate.tech","email":"tech@optomate.io"}],"homepage":"https://github.com/databridges-io/lib.js.node.apifront.proxy","bugs":{"url":"https://github.com/databridges-io/lib.js.node.apifront.proxy/issues"},"dist":{"shasum":"2d32c16b61a865f8cbb92d871163b71393a132b4","tarball":"https://registry.npmjs.org/@databridges/apifront-proxy/-/apifront-proxy-1.0.0.tgz","fileCount":6,"integrity":"sha512-/jKz3jnkJ+rVBdXvG/bH2RaUCp0UA5OA2XR1IYH6MeVIbEdKZ0PDVZN+pAYjXKz95BOTuuiNn9Hgtw7qAIYbxw==","signatures":[{"sig":"MEUCIBI55bEvtbsDGEGytgDTc1WmtO0UyFSYeTsoMunPFRbFAiEA2RmWg8O+jgd6iyProfCPMk4lwKczBeVrftqoEZJJUKA=","keyid":"SHA256:DhQ8wR5APBvFHLF/+Tc+AYvPOdTpcIDqOhxsBHRwC7U"}],"unpackedSize":94468},"main":"src/apifront_proxy.js","engines":{"node":">=14.0.0"},"gitHead":"53c9655067350b4a0ba9c2db065d86609a1ac78f","private":false,"_npmUser":{"name":"optomate.tech","email":"tech@optomate.io"},"deprecated":false,"repository":{"url":"git+https://github.com/databridges-io/lib.js.node.apifront.proxy.git","type":"git"},"_npmVersion":"10.8.2","description":"APIFront proxy client for dataBridges ecosystem - Node.js implementation","directories":{},"_nodeVersion":"20.19.4","dependencies":{"delay":"^5.0.0","nanoid":"^3.1.23","databridges-sio-client-lib":"^2.0.4","databridges-sio-server-lib":"^2.0.4"},"publishConfig":{"access":"public"},"_hasShrinkwrap":false,"bundleDependencies":[],"_npmOperationalInternal":{"tmp":"tmp/apifront-proxy_1.0.0_1752691058002_0.4400566853933443","host":"s3://npm-registry-packages-npm-production"}},"1.0.1":{"name":"@databridges/apifront-proxy","version":"1.0.1","keywords":["optomate","databridges","apifront","api","authentication","realtime","real-time"],"author":{"url":"https://www.optomate.io","name":"Optomate Technologies Private Limited.","email":"tech@optomate.io"},"license":"Apache-2.0","_id":"@databridges/apifront-proxy@1.0.1","maintainers":[{"name":"optomate.tech","email":"tech@optomate.io"}],"homepage":"https://github.com/databridges-io/lib.js.node.apifront.proxy","bugs":{"url":"https://github.com/databridges-io/lib.js.node.apifront.proxy/issues"},"dist":{"shasum":"17495f73756ababf5e758d7c827e4a192b584387","tarball":"https://registry.npmjs.org/@databridges/apifront-proxy/-/apifront-proxy-1.0.1.tgz","fileCount":6,"integrity":"sha512-nJTnSB6kfMxRkAoPRhv7I+dOja2Ca+GPQj/e/2/08Anrzs5fyr28cNdPJsZQ2hlybAw9Y45JW+atLyzChG9pLA==","signatures":[{"sig":"MEYCIQCU0c1qOmFgIMnHgeIv5K98Z3rZKF62gln6HdGzY2ObgAIhAIA63731j1ncP1f/ieXixwljfJzAPQAeUHQrrnZ6qiMg","keyid":"SHA256:DhQ8wR5APBvFHLF/+Tc+AYvPOdTpcIDqOhxsBHRwC7U"}],"unpackedSize":94468},"main":"src/apifront_proxy.js","engines":{"node":">=14.0.0"},"gitHead":"959bb5d2febefe34d3b459bdcae22b2f41adccdf","private":false,"_npmUser":{"name":"optomate.tech","email":"tech@optomate.io"},"deprecated":false,"repository":{"url":"git+https://github.com/databridges-io/lib.js.node.apifront.proxy.git","type":"git"},"_npmVersion":"10.8.2","description":"APIFront proxy client for dataBridges ecosystem - Node.js implementation","directories":{},"_nodeVersion":"20.19.4","dependencies":{"delay":"^5.0.0","nanoid":"^3.1.23","databridges-sio-client-lib":"^2.0.4","databridges-sio-server-lib":"^2.0.4"},"publishConfig":{"access":"public"},"_hasShrinkwrap":false,"bundleDependencies":[],"_npmOperationalInternal":{"tmp":"tmp/apifront-proxy_1.0.1_1752692372111_0.14335672886765738","host":"s3://npm-registry-packages-npm-production"}},"1.0.2":{"name":"@databridges/apifront-proxy","version":"1.0.2","keywords":["optomate","databridges","apifront","api","authentication","realtime","real-time"],"author":{"url":"https://www.optomate.io","name":"Optomate Technologies Private Limited.","email":"tech@optomate.io"},"license":"Apache-2.0","_id":"@databridges/apifront-proxy@1.0.2","maintainers":[{"name":"optomate.tech","email":"tech@optomate.io"}],"homepage":"https://github.com/databridges-io/lib.js.node.apifront.proxy","bugs":{"url":"https://github.com/databridges-io/lib.js.node.apifront.proxy/issues"},"dist":{"shasum":"48ec8f4aad1afb50523a97add6acc586a91831f5","tarball":"https://registry.npmjs.org/@databridges/apifront-proxy/-/apifront-proxy-1.0.2.tgz","fileCount":6,"integrity":"sha512-IPZ/LRzrd4iAQQblZvGyCWRvtof092+pCSgjVy6zZCo5tJqBSBY04ClDGwcullebNiHXkbecIg8qLM1FQ6LAaQ==","signatures":[{"sig":"MEUCIQC3bb3+z8UHLQYyNCbW+JSnutHMUsTRIDewUShA+ovVuAIgWHBpkrCGtQkC0q6sBJAVM2jOXXSg5wVdK0Bgr58wLnY=","keyid":"SHA256:DhQ8wR5APBvFHLF/+Tc+AYvPOdTpcIDqOhxsBHRwC7U"}],"unpackedSize":94497},"main":"src/apifront_proxy.js","engines":{"node":">=14.0.0"},"gitHead":"36cf150a09bd1f7c57b349a00d2f804936272dfd","private":false,"_npmUser":{"name":"optomate.tech","email":"tech@optomate.io"},"deprecated":false,"repository":{"url":"git+https://github.com/databridges-io/lib.js.node.apifront.proxy.git","type":"git"},"_npmVersion":"10.8.2","description":"APIFront proxy client for dataBridges ecosystem - Node.js implementation","directories":{},"_nodeVersion":"20.19.4","dependencies":{"delay":"^5.0.0","nanoid":"^3.1.23","databridges-sio-client-lib":"^2.0.4","databridges-sio-server-lib":"^2.0.4"},"publishConfig":{"access":"public"},"_hasShrinkwrap":false,"bundleDependencies":[],"_npmOperationalInternal":{"tmp":"tmp/apifront-proxy_1.0.2_1754509311957_0.6881465139541507","host":"s3://npm-registry-packages-npm-production"}},"1.0.4":{"name":"@databridges/apifront-proxy","version":"1.0.4","description":"APIFront proxy client for dataBridges ecosystem - Node.js implementation","keywords":["optomate","databridges","apifront","api","authentication","realtime","real-time"],"private":false,"publishConfig":{"access":"public"},"engines":{"node":">=14.0.0"},"author":{"name":"Optomate Technologies Private Limited.","email":"tech@optomate.io","url":"https://www.optomate.io"},"main":"src/apifront_proxy.js","license":"Apache-2.0","repository":{"type":"git","url":"git+https://github.com/databridges-io/lib.js.node.apifront.proxy.git"},"exports":{".":"./src/apifront_proxy.js","./kiss_logger":"./src/kiss_logger.js"},"homepage":"https://github.com/databridges-io/lib.js.node.apifront.proxy","bundleDependencies":[],"deprecated":false,"dependencies":{"databridges-sio-server-lib":"^2.0.4","delay":"^5.0.0","nanoid":"^3.1.23"},"_id":"@databridges/apifront-proxy@1.0.4","gitHead":"8bd1f86991dbb6004b002f2651350497392c3978","bugs":{"url":"https://github.com/databridges-io/lib.js.node.apifront.proxy/issues"},"_nodeVersion":"20.19.4","_npmVersion":"10.8.2","dist":{"integrity":"sha512-B+1NwSxvbgwznDQ47VWbZRjOQQENOr3x4uTHwzU7nlWGZ8TsGXRUwHpn8jtDgTFEzZOtEELHKmpYHznFETCp9A==","shasum":"1f74294954dd4a9bc25e5076e6232dd7d27f0212","tarball":"https://registry.npmjs.org/@databridges/apifront-proxy/-/apifront-proxy-1.0.4.tgz","fileCount":7,"unpackedSize":100900,"signatures":[{"keyid":"SHA256:DhQ8wR5APBvFHLF/+Tc+AYvPOdTpcIDqOhxsBHRwC7U","sig":"MEUCIB2UQhKUEzd3pmC/28biXm6pgE44LcKD7IRmpbYtFllPAiEA3yjk7Pc6WWamBwwddRDcCNSUYLR/Q2L548whz1C8G54="}]},"_npmUser":{"name":"optomate.tech","email":"tech@optomate.io"},"directories":{},"maintainers":[{"name":"optomate.tech","email":"tech@optomate.io"}],"_npmOperationalInternal":{"host":"s3://npm-registry-packages-npm-production","tmp":"tmp/apifront-proxy_1.0.4_1763059044493_0.3762637240718534"},"_hasShrinkwrap":false}},"time":{"created":"2025-07-16T18:37:37.923Z","modified":"2025-11-13T18:37:24.902Z","1.0.0":"2025-07-16T18:37:38.204Z","1.0.1":"2025-07-16T18:59:32.291Z","1.0.2":"2025-08-06T19:41:52.167Z","1.0.4":"2025-11-13T18:37:24.675Z"},"bugs":{"url":"https://github.com/databridges-io/lib.js.node.apifront.proxy/issues"},"author":{"name":"Optomate Technologies Private Limited.","email":"tech@optomate.io","url":"https://www.optomate.io"},"license":"Apache-2.0","homepage":"https://github.com/databridges-io/lib.js.node.apifront.proxy","keywords":["optomate","databridges","apifront","api","authentication","realtime","real-time"],"repository":{"type":"git","url":"git+https://github.com/databridges-io/lib.js.node.apifront.proxy.git"},"description":"APIFront proxy client for dataBridges ecosystem - Node.js implementation","maintainers":[{"name":"optomate.tech","email":"tech@optomate.io"}],"readme":"![](https://img.shields.io/badge/Licence-Apache%202.0-green.svg) ![](https://shields.io/badge/node.js-%3E=14.0%20LTS-blue)\n\n# APIFront Node.js Proxy\n\n**Transform your internal functions into enterprise-grade REST APIs instantly - no additional infrastructure required.**\n\nAPIFront solves the fundamental challenge of exposing deep networked functions as secure, scalable APIs. Whether you're building microservices, integrating AI systems, or creating API-first architectures, APIFront provides the fastest path from function to production-ready API.\n\n## 🌟 What is APIFront?\n\nAPIFront is an advanced API infrastructure platform that transforms any backend function into secure, real-time, enterprise-class APIs with OAuth2 protection, rate limiting, and monetization capabilities - all without requiring additional web infrastructure.\n\n### ⚡ Key Benefits\n\n- **🚀 Instant API Creation**: Transform functions to APIs in minutes, not months\n- **🔒 Enterprise Security**: Built-in OAuth2, IP whitelisting, and access controls\n- **⚖️ Auto Load Balancing**: Automatic horizontal scaling without configuration\n- **🌐 Global Access**: Functions behind firewalls become globally accessible APIs\n- **💰 Built-in Monetization**: Integrated payment processing and API credit management\n- **🤖 AI-Ready**: Perfect for LLM function calling and AI agent integration\n\n## 📋 Table of Contents\n\n- [How APIFront Works](#how-apifront-works)\n- [Installation](#installation)\n- [Quick Start](#quick-start)\n- [Configuration](#configuration)\n- [Function Definition](#function-definition)\n- [API Registration](#api-registration)\n- [Advanced Features](#advanced-features)\n- [Production Deployment](#production-deployment)\n- [Integration Examples](#integration-examples)\n\n## 🔧 How APIFront Works\n\n### Architecture Overview\n\nAPIFront creates a secure bridge between your internal functions and the global internet:\n\n**🏠 Your Functions** *(Internal Logic)*\n↓ *Secure outbound connection*\n**🔗 APIFront Proxy** *(Establishes secure tunnel)*\n↓ *Encrypted communication*\n**🌐 APIFront Network** *(OAuth2 authentication & intelligent routing)*\n↓ *Public access*\n**🌍 Global REST APIs** *(Accessible worldwide)*\n\n**Key Benefits:**\n\n- **No inbound ports required** - Works with existing firewalls\n- **Enterprise security** - OAuth2, IP whitelisting, rate limiting\n- **Automatic scaling** - Load balancing across multiple instances\n- **Global accessibility** - Functions become REST APIs instantly\n\n### API Path Structure\n\nYour functions become accessible via this URL pattern:\n\n[https://gateway.apifront.io/api/v1/{gateway_id}/{service_version}/{service_name}/{function_name}](https://gateway.apifront.io/api/v1/{gateway_id}/{service_version}/{service_name}/{function_name})\n\n**Example URLs:**\n\n- `https://gateway.apifront.io/api/v1/gw123/v1/user-service/create-user`\n- `https://gateway.apifront.io/api/v1/gw123/v1/analytics/generate-report`\n- `https://gateway.apifront.io/api/v1/gw123/v2/ai-tools/process-image`\n\n### Service Organization\n\n| Feature | Description | Benefit |\n|---------|-------------|---------|\n| 📦 **Logical Grouping** | Group related functions under service names | Clean API structure |\n| 🔄 **Single Deployment** | All functions in a service deployed together | Version consistency |\n| ⚖️ **Auto Load Balancing** | Multiple instances automatically balanced | High availability |\n| 🛡️ **Service Integrity** | Consistent deployment per service | Reliable performance |\n\n## 📦 Installation\n\n```bash\nnpm install @databridges/apifront-proxy --save\n```\n\n**Requirements:** Node.js version 14 or newer (LTS recommended)\n\n## 🚀 Quick Start\n\n### 1. Initialize and Configure\n\n```javascript\nconst ApiProxy = require('@databridges/apifront-proxy');\nconst apifront = new ApiProxy();\n\n// Configure with credentials from APIFront Dashboard\napifront.config({\n    apifront_gatewayId: 'YOUR_GATEWAY_ID',\n    apifront_clientId: 'YOUR_CLIENT_ID', \n    apifront_clientSecret: 'YOUR_CLIENT_SECRET',\n    apifront_authUrl: 'YOUR_AUTH_URL'\n});\n```\n\n### 2. Define Your Functions\n\n```javascript\n// User creation function\nasync function createUser(inparameter, response, proxyPath) {\n    try {\n        const userData = JSON.parse(inparameter.inparam);\n        const headerInfo = JSON.parse(inparameter.info);\n        \n        // Validation\n        if (!userData.name || !userData.email) {\n            throw new Error(\"Missing required fields: name or email\");\n        }\n        // Your business logic here\n        const newUser = {\n            id: generateUserId(),\n            name: userData.name,\n            email: userData.email,\n            created: new Date().toISOString()\n        };\n        \n        // Save to database\n        await database.users.create(newUser);\n        \n        // Return success response\n        response.end(JSON.stringify({\n            status: 'SUCCESS',\n            user: newUser\n        }));\n    } catch (error) {\n        response.end(JSON.stringify({\n            status: 'ERROR',\n            message: error.message\n        }));\n    }\n}\n\n// Analytics report function\nasync function generateReport(inparameter, response, proxyPath) {\n    try {\n        const params = JSON.parse(inparameter.inparam);\n        // Validate input\n        if (!params.reportType || !params.dateRange) {\n            throw new Error(\"Missing required parameters: reportType or dateRange\");\n        }\n        // Generate analytics report\n        const report = await analyticsEngine.generateReport({\n            type: params.reportType,\n            dateRange: params.dateRange,\n            filters: params.filters\n        });\n        \n        response.end(JSON.stringify({\n            status: 'SUCCESS',\n            report: report\n        }));\n    } catch (error) {\n        response.end(JSON.stringify({\n            status: 'ERROR',\n            message: error.message\n        }));\n    }\n}\n```\n\n### 3. Register API Endpoints\n\n```javascript\n// Register functions as API endpoints\napifront.proxy('user-service/create-user', createUser);\napifront.proxy('user-service/get-profile', getUserProfile);\napifront.proxy('analytics/generate-report', generateReport);\napifront.proxy('analytics/get-metrics', getMetrics);\n```\n\n### 4. Start the Proxy\n\n```javascript\napifront.start()\n    .then(() => {\n        console.log('🚀 APIFront proxy is online!');\n        console.log('Your APIs are now accessible globally');\n    })\n    .catch(err => {\n        console.error('❌ Startup error:', err);\n    });\n```\n\n### 5. Monitor Status\n\n```javascript\n// Event listeners for monitoring\napifront.on('connected', () => {\n    console.log('✅ Connected to APIFront network');\n});\n\napifront.on('disconnected', () => {\n    console.log('⚠️ Disconnected from APIFront network');\n});\n\napifront.on('status', (status) => {\n    console.log('📊 Status:', status);\n});\n```\n\n## ⚙️ Configuration\n\n### Configuration Options\n\n| Property                | Type     | Required | Description                        |\n| ----------------------- | -------- | -------- | ---------------------------------- |\n| `apifront_gatewayId`    | `string` | ✅        | Gateway ID from APIFront Dashboard |\n| `apifront_clientId`     | `string` | ✅        | Client ID for authentication       |\n| `apifront_clientSecret` | `string` | ✅        | Client secret for authentication   |\n| `apifront_authUrl`      | `string` | ✅        | Authentication URL from dashboard  |\n\n### Configuration Methods\n\n**Method 1: Object Configuration**\n\n```javascript\napifront.config({\n    apifront_gatewayId: 'gw123',\n    apifront_clientId: 'client456', \n    apifront_clientSecret: 'secret789',\n    apifront_authUrl: 'https://auth.apifront.io'\n});\n```\n\n**Method 2: Property Assignment**\n\n```javascript\napifront.config.apifront_gatewayId = 'gw123';\napifront.config.apifront_clientId = 'client456';\napifront.config.apifront_clientSecret = 'secret789';\napifront.config.apifront_authUrl = 'https://auth.apifront.io';\n```\n\n## 🔨 Function Definition\n\n### Function Signature\n\nEvery API handler receives three parameters:\n\n```javascript\nfunction handlerName(inparameter, response, proxyPath) {\n    // Function implementation\n}\n```\n\n### Parameter Details\n\n#### `inparameter` Object\n\n| Property     | Type     | Description                          |\n| ------------ | -------- | ------------------------------------ |\n| `inparam`    | `string` | JSON-encoded input from client       |\n| `info`       | `string` | JSON-encoded metadata and headers    |\n| `sessionid`  | `string` | Unique client session identifier     |\n| `libtype`    | `string` | Client library type (e.g., \"nodejs\") |\n| `sourceipv4` | `string` | Client's IPv4 address                |\n\n#### `info` Field Structure\n\n```javascript\nconst headerInfo = JSON.parse(inparameter.info);\n/*\n{\n    \"sysid\": \"user@example.com\",\n    \"sysinfo\": {\n        \"keyid\": \"key123\",\n        \"apiResourceOwner\": \"owner456\", \n        \"apiClient\": \"MyApp\",\n        \"scope\": \"*\"\n    },\n    \"http-header\": {\n\t\t//... Standard http headers.\n    }\n}\n`headerInfo` structure:\n   - sysid: System identity or user ID of the caller.\n   - sysinfo:\n       - keyid: Authentication key ID.\n       - apiResourceOwner: Resource owner's identity.\n       - apiClient: Identity of the calling client.\n       - scope: Permissions or access scope (e.g. \"*\", \"read write\",\"user_read user-profile analytics_write\").\n*/\n```\n\nBelow are few examples of `http-header`\n\n✅ **Example 1 – Postman Request**\n\n```json\n\"http-header\": {\n      \"content-type\": \"text/plain\",\n      \"user-agent\": \"PostmanRuntime/7.42.0\",\n      \"accept\": \"*/*\",\n      \"cache-control\": \"no-cache\",\n      \"postman-token\": \"cf3b320b-6d6a-416a-a688-b082f52eabc4\",\n      \"host\": \"eu-api-apigw02.databridges.io\",\n      \"accept-encoding\": \"gzip, deflate, br\",\n      \"connection\": \"keep-alive\",\n      \"content-length\": \"2\"\n    }\n```\n\n✅ **Example 2 – Web Browser Client (Single-Page App)**\n\n```json\n\"http-header\": {\n      \"host\": \"eu-api-apigw02.databridges.io\",\n      \"user-agent\": \"Mozilla/5.0 (Windows NT 10.0; Win64; x64)\",\n      \"accept-language\": \"en-US,en;q=0.9\",\n      \"origin\": \"https://client.myapp.com\",\n      \"referer\": \"https://client.myapp.com/dashboard\",\n      \"content-type\": \"application/json\"\n    }\n```\n\n✅ **Example 3 – Backend Microservice Call**\n\n```json\n\"http-header\": {\n      \"user-agent\": \"order-service/1.4.2\",\n      \"x-correlation-id\": \"12b3f9ee-7812-4f8d-b918-2a000e41a345\",\n      \"content-type\": \"application/json\",\n      \"host\": \"eu-api-apigw02.databridges.io\",\n    }\n```\n\n✅ **Example 4 – Mobile App (iOS or Android)**\n\n```json\n\"http-header\": {\n      \"user-agent\": \"MyApp/3.2.1 (iOS; iPhone14,2)\",\n      \"content-type\": \"application/json\",\n      \"x-device-id\": \"dev-12345-ios\",\n      \"host\": \"eu-api-apigw02.databridges.io\",\n    }\n```\n\n\n\n#### `response` Object\n\n| Method      | Description                              |\n| ----------- | ---------------------------------------- |\n| `end(data)` | Send final response and close connection |\n\n#### `proxyPath` String\n\nContains the full API path being called (e.g., `\"v1/user-service/create-user\"`)\n\n### Example Function Implementation\n\n```javascript\nasync function processPayment(inparameter, response, proxyPath) {\n    try {\n        // Parse input data\n        const paymentData = JSON.parse(inparameter.inparam);\n        const clientInfo = JSON.parse(inparameter.info);\n        \n        // Validate request\n        if (!paymentData.amount || !paymentData.currency || !paymentData.source) {\n            return response.end(JSON.stringify({\n                status: 'ERROR',\n                message: 'Amount and currency are required'\n            }));\n        }\n        \n        // Process payment\n        const result = await paymentProcessor.charge({\n            amount: paymentData.amount,\n            currency: paymentData.currency,\n            source: paymentData.source,\n            description: paymentData.description\n        });\n        \n        // Log transaction\n        logger.info('Payment processed', {\n            sessionId: inparameter.sessionid,\n            clientId: clientInfo.sysinfo.apiClient,\n            amount: paymentData.amount,\n            result: result.id\n        });\n        \n        // Return success\n        response.end(JSON.stringify({\n            status: 'SUCCESS',\n            transactionId: result.id,\n            amount: result.amount,\n            currency: result.currency\n        }));\n        \n    } catch (error) {\n        logger.error('Payment processing failed', {\n            error: error.message,\n            sessionId: inparameter.sessionid\n        });\n        \n        response.end(JSON.stringify({\n            status: 'ERROR',\n            message: 'Payment processing failed',\n            errorCode: 'PAYMENT_ERROR'\n        }));\n    }\n}\n```\n\n## 📡 API Registration\n\n### Basic Registration\n\n```javascript\napifront.proxy('service-name/function-name', functionHandler);\n```\n\n### With Function Metadata\n\n```javascript\napifront.proxy('user-service/create-user', createUser, {\n    mcp: {\n        description: \"Create a new user account\",\n        permissions: [\"user:create\"],\n        rateLimit: 100\n    },\n    openapi: {\n        summary: \"Create User\",\n        description: \"Creates a new user account in the system\",\n        tags: [\"Users\", \"Authentication\"],\n        parameters: {\n            name: { type: \"string\", required: true },\n            email: { type: \"string\", required: true },\n            password: { type: \"string\", required: true }\n        }\n    }\n});\n```\n\n### Versioned APIs\n\n```javascript\n// Version 1\napifront.proxy('v1/user-service/create-user', createUserV1);\n\n// Version 2 with enhanced features\napifront.proxy('v2/user-service/create-user', createUserV2);\n```\n\n> **Note :**  If no version is specified during proxy configuration, the default version `\"v1\"` will be automatically applied to the API route.\n\n### Service Organization Best Practices\n\n```javascript\n// ✅ Recommended: Keep all functions of the same service within a single deployment\napifront.proxy('user-service/create-user', createUser);\napifront.proxy('user-service/update-user', updateUser);\napifront.proxy('user-service/delete-user', deleteUser);\napifront.proxy('user-service/get-user', getUser);\n\n// ✅ Recommended: Group related functionalities in dedicated deployments\napifront.proxy('analytics/generate-report', generateReport);\napifront.proxy('analytics/get-metrics', getMetrics);\napifront.proxy('analytics/export-data', exportData);\n\n// ❌ Not Allowed: Registering functions from the same service across multiple deployments is not allowed\n// Example — Do NOT split service registration across separate scripts:\n// Script A:\napifront.proxy('user-service/create-user', createUser);\n// Script B:\napifront.proxy('user-service/delete-user', deleteUser);\n```\n\n\n\n## 🔐 Security & Access Control\n\nAPIFront provides enterprise-grade security with comprehensive OAuth2 protection and fine-grained access controls.\n\n### Security Architecture\n\n| Feature | Description | Benefit |\n|---------|-------------|---------|\n| 🔐 **Outbound-Only Connectivity** | All connections initiated from your environment, no inbound ports required | Maintains existing security posture |\n| 🛡️ **Comprehensive Authentication** | Complete OAuth2 implementation with JWT token management | Enterprise-grade authorization |\n| 🔍 **Granular Access Control** | Function-level permissions, IP whitelisting, usage quotas | Fine-grained security control |\n| 🔒 **Secure Communication** | End-to-end encryption with TLS 1.3 and strong cipher suites | Data protection in transit |\n\n### 🔐 OAuth2 Implementation\n\nAPIFront implements OAuth2 as a **gateway-level security layer**, protecting your entire API gateway. All exposed functions automatically inherit this protection without requiring individual security implementation.\n\n#### Supported Grant Types\n\n| Grant Type | Description | Best For |\n|------------|-------------|----------|\n| 🔑 **Authorization Code Flow** | Traditional OAuth2 web flow with user authentication | Web applications, server-side applications |\n| 🔐 **Authorization Code with PKCE** | Enhanced flow with Proof Key for Code Exchange | Mobile apps, Single Page Applications |\n| 🤖 **Client Credentials Flow** | Machine-to-machine authorization without user interaction | Microservices, backend services, APIs |\n| 🎫 **Bearer Token Support** | Simple token-based authentication | Simple integrations, legacy systems, testing |\n\n#### Authorization Code Flow - Resource Owner Context\n\nFor **Authorization Code Flow**, the `apiResourceOwner` field is critical as it identifies the user who authorized the client application to access APIs on their behalf:\n\n```javascript\nasync function processUserData(inparameter, response, proxyPath) {\n    try {\n        const clientInfo = JSON.parse(inparameter.info);\n        const requestData = JSON.parse(inparameter.inparam);\n        \n        // In Authorization Code Flow, apiResourceOwner is the authorizing user\n        const authorizingUser = clientInfo.sysinfo.apiResourceOwner;\n        const clientApp = clientInfo.sysinfo.apiClient;\n        \n        if (authorizingUser) {\n        \t// Basic validation\n            if (!requestData.userId) {\n                return response.end(JSON.stringify({\n                    status: 'ERROR',\n                    message: 'Missing required field: userId'\n                }));\n            }\n            // Process data on behalf of the authorizing user\n            console.log(`Processing request for ${authorizingUser} via ${clientApp}`);\n            \n            // Ensure the request is for the correct user\n            if (requestData.userId !== authorizingUser) {\n                return response.end(JSON.stringify({\n                    status: 'ERROR',\n                    message: 'Cannot access data for different user',\n                    errorCode: 'UNAUTHORIZED_USER_ACCESS'\n                }));\n            }\n            \n            const userData = await processUserSpecificData(authorizingUser, requestData);\n            \n            response.end(JSON.stringify({\n                status: 'SUCCESS',\n                data: userData,\n                processed_for: authorizingUser,\n                via_client: clientApp\n            }));\n        } else {\n            // Client Credentials Flow - no specific user context\n            const systemData = await processSystemData(requestData);\n            response.end(JSON.stringify({\n                status: 'SUCCESS',\n                data: systemData,\n                flow_type: 'client_credentials'\n            }));\n        }\n        \n    } catch (error) {\n        response.end(JSON.stringify({\n            status: 'ERROR',\n            message: error.message\n        }));\n    }\n}\n```\n\n\n\n### 🔐 OAuth2 Client Example\n\nThis example demonstrates how to securely invoke your protected API using **OAuth2 authentication with the `client_credentials` grant type**.\n\n------\n\n#### ✅ Step-by-Step Overview\n\n1. **Obtain an access token** from the OAuth2 authorization server using your `client_id` and `client_secret`.\n2. **Use the access token** to call your secured API endpoint.\n\n```javascript\nconst axios = require('axios');\nconst qs = require('querystring');\n\n// ----------------------\n// CONFIGURATION SECTION\n// ----------------------\nconst config = {\n    tokenUrl: 'TokenURL',\n    clientId: 'ClientID',\n    clientSecret: 'ClientSecret',\n    scope: '', \n    apiUrl: 'Valid API URL'\n};\n\n// ----------------------\n// STEP 1: Get Access Token\n// ----------------------\nasync function getOAuthAccessToken() {\n    const basicAuth = Buffer.from(`${config.clientId}:${config.clientSecret}`).toString('base64');\n\n    try {\n        const response = await axios.post(\n            config.tokenUrl,\n            qs.stringify({\n                grant_type: 'client_credentials',\n                scope: config.scope\n            }),\n            {\n                headers: {\n                    'Content-Type': 'application/x-www-form-urlencoded',\n                    'Authorization': `Basic ${basicAuth}`\n                }\n            }\n        );\n\n        return response.data.access_token;\n    } catch (err) {\n        console.error('❌ Failed to get access token:', err.response?.data || err.message);\n        throw new Error('Token retrieval failed');\n    }\n}\n\n// ----------------------\n// STEP 2: Call Protected API\n// ----------------------\nasync function callProtectedAPI(accessToken) {\n    try {\n        const response = await axios.post(\n            config.apiUrl,\n            { message: \"Hello from Node.js\" }, // Replace with your actual payload\n            {\n                headers: {\n                    'Authorization': `Bearer ${accessToken}`,\n                    'Content-Type': 'application/json'\n                }\n            }\n        );\n\n        console.log('✅ Protected API response:', response.data);\n        return response.data;\n    } catch (err) {\n        console.error('❌ Error calling protected API:', err.response?.data || err.message);\n    }\n}\n\n// ----------------------\n// MAIN EXECUTION\n// ----------------------\n(async () => {\n    try {\n        const token = await getOAuthAccessToken();\n        await callProtectedAPI(token);\n    } catch (e) {\n        console.error('💥 Script failed:', e.message);\n    }\n})(); \n```\n\n\n\n## 🚀 Advanced Features\n\n### Scopes and Permissions\n\nScopes are defined when creating OAuth2 client application keys in the APIFront Dashboard using JSON format:\n\n#### Scope Definition Structure\n\n```json\n{\n    \"scopes\": [\n        {\n            \"name\": \"user_read\",\n            \"description\": \"Allows read access to user data.\",\n            \"selectable\": true\n        },\n        {\n            \"name\": \"user-profile\",\n            \"description\": \"Access to user profile information.\",\n            \"selectable\": true\n        },\n        {\n            \"name\": \"analytics_write\",\n            \"description\": \"Permission to create and modify analytics data.\",\n            \"selectable\": false\n        }\n    ]\n}\n```\n\n#### Field Definitions\n\n| Field         | Required | Description                                                  |\n| ------------- | -------- | ------------------------------------------------------------ |\n| `name`        | ✅        | Scope identifier using lowercase/uppercase letters, numbers, underscores (`_`), and hyphens (`-`) only |\n| `description` | ❌        | Brief explanation of scope permissions for developers and users |\n| `selectable`  | ✅        | Whether end users can opt-in/opt-out during authorization process |\n\n#### Validation Rules\n\n- **No spaces or special characters** except underscores (`_`) and hyphens (`-`)\n- **Case-sensitive** matching required during authorization requests\n- **`selectable` flag** must be explicitly set for user authorization control\n\n#### Using Scopes in Your Functions\n\nAccess granted scopes and user authorization information through the `info` parameter:\n\n```javascript\nfunction secureUserFunction(inparameter, response, proxyPath) {\n    try {\n        const clientInfo = JSON.parse(inparameter.info);\n        const userData = JSON.parse(inparameter.inparam);\n        \n        // Extract authorization information\n        const grantedScopes = clientInfo.sysinfo.scope; // e.g., \"user_read user-profile\"\n        const apiResourceOwner = clientInfo.sysinfo.apiResourceOwner; // User who authorized access\n        const apiClient = clientInfo.sysinfo.apiClient; // Client application name\n        \n        // Check if required scope is granted\n        const hasUserReadScope = grantedScopes.includes('user_read');\n        const hasUserProfileScope = grantedScopes.includes('user-profile');\n        \n        if (!hasUserReadScope) {\n            return response.end(JSON.stringify({\n                status: 'ERROR',\n                message: 'Insufficient permissions: user_read scope required',\n                errorCode: 'SCOPE_INSUFFICIENT'\n            }));\n        }\n        \n        // For Authorization Code Flow: apiResourceOwner contains the user who authorized access\n        if (apiResourceOwner) {\n            console.log(`API access authorized by user: ${apiResourceOwner}`);\n            console.log(`Client application: ${apiClient}`);\n        }\n        \n        // Implement scope-based logic\n        let resultData = getUserBasicInfo(inparameter.sessionid);\n        \n        if (hasUserProfileScope) {\n            // Add detailed profile information if scope permits\n            resultData = { ...resultData, ...getUserDetailedProfile(inparameter.sessionid) };\n        }\n        \n        response.end(JSON.stringify({\n            status: 'SUCCESS',\n            data: resultData,\n            authorized_by: apiResourceOwner,\n            granted_scopes: grantedScopes.split(' ')\n        }));\n        \n    } catch (error) {\n        response.end(JSON.stringify({\n            status: 'ERROR',\n            message: error.message\n        }));\n    }\n}\n```\n\n### Load Balancing and Scaling\n\nAPIFront automatically load balances multiple instances:\n\n```javascript\n// Instance 1: Registers 'user-service/create-user' handler\nconst apifront1 = new ApiProxy();\napifront1.config(config);\napifront1.proxy('user-service/create-user', createUser);\napifront1.start();\n\n// Instance 2: Registers the same 'user-service/create-user' handler\nconst apifront2 = new ApiProxy();\napifront2.config(config);\napifront2.proxy('user-service/create-user', createUser);\napifront2.start();\n\n// APIFront Load Balancing:\n// Multiple instances can register the same service function.\n// APIFront automatically distributes incoming requests across these instances,\n// enabling horizontal scaling and fault tolerance.\n```\n\n### Environment-Specific Deployment\n\n```javascript\n// Build APIFront configuration using environment variables\nconst config = {\n    apifront_gatewayId: process.env.APIFRONT_GATEWAY_ID,\n    apifront_clientId: process.env.APIFRONT_CLIENT_ID,\n    apifront_clientSecret: process.env.APIFRONT_CLIENT_SECRET,\n    apifront_authUrl: process.env.APIFRONT_AUTH_URL\n};\n\n// Override with production-specific gateway ID if applicable\nif (process.env.NODE_ENV === 'production' && process.env.PROD_GATEWAY_ID) {\n    config.apifront_gatewayId = process.env.PROD_GATEWAY_ID;\n}\n\n// Apply configuration to APIFront\napifront.config(config);\n```\n\n### Access Control Features\n\n#### IP Whitelisting\n\nConfigure IP restrictions per OAuth2 client application key in the APIFront Dashboard:\n\n```javascript\n// IP whitelisting is configured per client application key\n// Access the client information in your functions:\nfunction restrictedFunction(inparameter, response, proxyPath) {\n    const clientInfo = JSON.parse(inparameter.info);\n    const sourceIP = inparameter.sourceipv4;\n    \n    console.log(`Request from IP: ${sourceIP}`);\n    console.log(`Client Key ID: ${clientInfo.sysinfo.keyid}`);\n    \n    // APIFront automatically validates IP whitelist before reaching your function\n    // If you reach this point, IP validation has already passed\n    \n    response.end(JSON.stringify({\n        status: 'SUCCESS',\n        message: 'Access granted from authorized IP',\n        source_ip: sourceIP\n    }));\n}\n```\n\n#### Rate Limiting\n\nConfigure maximum API call limits per OAuth2 client application key:\n\n```javascript\nasync function rateLimitedFunction(inparameter, response, proxyPath) {\n    try {\n        const clientInfo = JSON.parse(inparameter.info);\n        \n        // APIFront handles rate limiting automatically\n        // Your function receives calls only if under the limit\n        \n        console.log(`Processing request from client: ${clientInfo.sysinfo.apiClient}`);\n        \n        // Business logic execution\n        const result = await processBusinessLogic(JSON.parse(inparameter.inparam));\n        \n        response.end(JSON.stringify({\n            status: 'SUCCESS',\n            data: result\n        }));\n        \n    } catch (error) {\n        response.end(JSON.stringify({\n            status: 'ERROR',\n            message: error.message\n        }));\n    }\n}\n```\n\n> **Note**: Rate limiting is automatically enforced by APIFront based on the maximum API calls configured for each client application key. Functions receive requests only if the client is within their allowed limits.\n\n\n\n## 🏭 Production Deployment\n\n### Graceful Shutdown\n\n```javascript\n// Graceful shutdown handling\nprocess.on('SIGTERM', async () => {\n    console.log('🛑 SIGTERM received, shutting down gracefully...');\n    \n    try {\n        await apifront.stop();\n        console.log('✅ APIFront proxy stopped successfully');\n        process.exit(0);\n    } catch (error) {\n        console.error('❌ Error during shutdown:', error);\n        process.exit(1);\n    }\n});\n\nprocess.on('SIGINT', async () => {\n    console.log('🛑 SIGINT received, shutting down gracefully...');\n    \n    try {\n        await apifront.stop();\n        console.log('✅ APIFront proxy stopped successfully');\n        process.exit(0);\n    } catch (error) {\n        console.error('❌ Error during shutdown:', error);\n        process.exit(1);\n    }\n});\n// Handle uncaught exceptions\nprocess.on('uncaughtException', async (err) => {\n    console.error('💥 Uncaught Exception:', err);\n\n    try {\n        await apifront.stop();\n        console.log('✅ APIFront proxy stopped successfully');\n    } catch (shutdownErr) {\n        console.error('❌ Error during shutdown:', shutdownErr);\n    } finally {\n        // Ensure process exits after handling the exception\n        process.exit(1);\n    }\n});\n```\n\n\n\n## 📊 Event Listeners & Monitoring\n\nAPIFront provides comprehensive event monitoring capabilities to help you track the health and status of your API proxy in real-time.\n\n### Event Listener Registration\n\nThe `apifront` instance emits several events during its lifecycle. You can listen to these events to monitor status changes, debug logs, and network connectivity updates.\n\n#### Supported Events\n\n| Event Name           | Trigger               | Parameters       | Description                                                 |\n| -------------------- | --------------------- | ---------------- | ----------------------------------------------------------- |\n| 📊 **`status`**       | Status changes        | `state` (string) | API proxy status changes (ONLINE/OFFLINE, connecting, etc.) |\n| ✅ **`connected`**    | Network connection    | None             | Successful connection to dataBridges network established    |\n| ❌ **`disconnected`** | Network disconnection | None             | Connection lost or intentionally closed                     |\n\n### Basic Event Monitoring\n\n**Essential monitoring setup - copy this into your code:**\n\n```javascript\n// Essential event monitoring for all APIFront applications\napifront.on(\"status\", (state) => {\n    const timestamp = new Date().toISOString();\n    console.log(`📊 [${timestamp}] APIFront Status: ${state}`);\n    \n    // You can add custom logic based on status\n    switch (state) {\n        case 'ONLINE':\n            console.log('🚀 APIs are ready to serve requests');\n            break;\n        case 'OFFLINE':\n            console.warn('⚠️ APIs may be temporarily unavailable');\n            break;\n        default:\n            console.log(`ℹ️ Unknown status: ${state}`);\n    }\n});\n\napifront.on(\"connected\", () => {\n    console.log('🚀 APIFront: Connected and ready to serve APIs');\n\n    // Optional: Trigger actions after successful connection\n    // startHealthChecks();\n    // notifyOtherServices();\n});\n\napifront.on(\"disconnected\", () => {\n    console.error('⚠️ APIFront: Disconnected - APIs may be unavailable');\n\n    // Optional: Handle fallback/alerting logic\n    // stopHealthChecks();\n    // sendAlert('APIFront disconnected');\n});\n```\n\n### Production Monitoring\n\n**Advanced monitoring for production environments:**\n\n```javascript\n// Production-ready monitoring with health tracking and alerting\nlet healthStatus = {\n    status: 'UNHEALTHY',\n    lastConnected: null,\n    lastDisconnected: null,\n    connectionCount: 0,\n    errors: []\n};\n\n// Simple health monitor\nconst healthMonitor = {\n    isHealthy: () => healthStatus.status === 'HEALTHY',\n    \n    getStatus: () => ({\n        status: healthStatus.status,\n        service: 'apifront-proxy',\n        timestamp: new Date().toISOString(),\n        connectionCount: healthStatus.connectionCount,\n        lastConnected: healthStatus.lastConnected,\n        recentErrors: healthStatus.errors.slice(-3)\n    }),\n    \n    logStatus: () => {\n        const health = healthMonitor.getStatus();\n        console.log(`[HEALTH] ${health.status} - Connections: ${health.connectionCount}`);\n    }\n};\n\n// Simple alerting function - customize for your needs\nasync function sendAlert(message, level = 'error') {\n    const alertData = {\n        message,\n        level,\n        service: 'apifront-proxy',\n        timestamp: new Date().toISOString()\n    };\n    \n    console.error(`🚨 ALERT [${level.toUpperCase()}]: ${message}`);\n    \n    // Add your preferred alerting method here:\n    // Slack webhook:\n    // await fetch(process.env.SLACK_WEBHOOK_URL, { method: 'POST', ... });\n    \n    // Email service:\n    // await emailService.send({ subject: 'APIFront Alert', body: message });\n    \n    // Monitoring service:\n    // await monitoringService.alert(alertData);\n}\n\n// Track health status from events\napifront.on(\"connected\", () => {\n    healthStatus = {\n        ...healthStatus,\n        status: 'HEALTHY',\n        lastConnected: new Date().toISOString(),\n        connectionCount: healthStatus.connectionCount + 1\n    };\n    \n    console.log('✅ APIFront: Service is healthy');\n    \n    // Send recovery notification if we were previously down\n    if (healthStatus.connectionCount > 1) {\n        sendAlert(`APIFront reconnected after ${healthStatus.connectionCount} attempts`, 'info');\n    }\n});\n\napifront.on(\"disconnected\", () => {\n    healthStatus = {\n        ...healthStatus,\n        status: 'UNHEALTHY',\n        lastDisconnected: new Date().toISOString()\n    };\n    \n    console.error('❌ APIFront: Service is unhealthy');\n    sendAlert('APIFront proxy disconnected - APIs may be unavailable');\n});\n\n// Enhanced startup with error handling and retry logic\nconst startProxy = () => {\n    apifront.start()\n        .then(() => {\n            console.log('🚀 APIFront started successfully');\n        })\n        .catch(error => {\n            console.error('❌ APIFront startup failed:', {\n                code: error.code,\n                message: error.message\n            });\n\n            // Send startup failure alert\n            sendAlert(`APIFront startup failed: ${error.message} (${error.code})`);\n\n            // Implement retry logic for recoverable errors\n            const recoverableErrors = ['DBNET_DISCONNECT', 'DBAPP_REGISTRATION'];\n            if (recoverableErrors.includes(error.code)) {\n                console.log('🔄 Retrying startup in 5 seconds...');\n                setTimeout(() => {\n                    console.log('🔄 Attempting restart...');\n                    startProxy();\n                }, 5000);\n            }\n        });\n}\nstartProxy()\n\n// Optional: Periodic health status logging\nsetInterval(() => {\n    healthMonitor.logStatus();\n    \n    // Check for extended downtime\n    if (!healthMonitor.isHealthy() && healthStatus.lastDisconnected) {\n        const offlineTime = Date.now() - new Date(healthStatus.lastDisconnected).getTime();\n        if (offlineTime > 300000) { // 5 minutes\n            sendAlert(`APIFront has been offline for ${Math.floor(offlineTime / 60000)} minutes`);\n        }\n    }\n}, 60000); // Check every minute\n\n// Graceful shutdown monitoring\nprocess.on('SIGTERM', async () => {\n    console.log('🛑 Received SIGTERM, shutting down gracefully...');\n    try {\n        await apifront.stop();\n        console.log('✅ APIFront stopped successfully');\n        process.exit(0);\n    } catch (error) {\n        console.error('❌ Error during shutdown:', error);\n        process.exit(1);\n    }\n});\n```\n## 🤖 Integration Examples\n\n### AI/LLM Function Calling\n\n```javascript\n// Expose AI-callable functions\nfunction analyzeUserSentiment(inparameter, response, proxyPath) {\n    try {\n        const { text, options } = JSON.parse(inparameter.inparam);\n        \n        const analysis = sentimentAnalyzer.analyze(text, {\n            language: options?.language || 'en',\n            detailed: options?.detailed || false\n        });\n        \n        response.end(JSON.stringify({\n            status: 'SUCCESS',\n            sentiment: analysis.sentiment,\n            confidence: analysis.confidence,\n            emotions: analysis.emotions\n        }));\n    } catch (error) {\n        response.end(JSON.stringify({\n            status: 'ERROR',\n            message: error.message\n        }));\n    }\n}\n\nfunction generateUserInsights(inparameter, response, proxyPath) {\n    try {\n        const { userId, timeframe } = JSON.parse(inparameter.inparam);\n        \n        const insights = analyticsEngine.generateUserInsights(userId, timeframe);\n        \n        response.end(JSON.stringify({\n            status: 'SUCCESS',\n            insights: insights,\n            generatedAt: new Date().toISOString()\n        }));\n    } catch (error) {\n        response.end(JSON.stringify({\n            status: 'ERROR', \n            message: error.message\n        }));\n    }\n}\n\n// Register AI-callable functions with metadata\napifront.proxy('ai-tools/analyze-sentiment', analyzeUserSentiment, {\n    mcp: {\n        description: \"Analyze sentiment of given text\",\n        parameters: {\n            text: { type: \"string\", required: true, description: \"Text to analyze\" },\n            options: {\n                type: \"object\",\n                properties: {\n                    language: { type: \"string\", default: \"en\" },\n                    detailed: { type: \"boolean\", default: false }\n                }\n            }\n        }\n    }\n});\n\napifront.proxy('ai-tools/user-insights', generateUserInsights, {\n    mcp: {\n        description: \"Generate insights for a specific user\",\n        parameters: {\n            userId: { type: \"string\", required: true },\n            timeframe: { type: \"string\", enum: [\"7d\", \"30d\", \"90d\"], default: \"30d\" }\n        }\n    }\n});\n```\n\n### Microservices Integration\n\n```javascript\n// -------------------- User Service --------------------\nconst userService = new ApiProxy();\nuserService.config(userServiceConfig);\n\n// Register user-related RPC endpoints\nuserService.proxy('user-service/create', createUser);\nuserService.proxy('user-service/authenticate', authenticateUser);\nuserService.proxy('user-service/profile', getUserProfile);\n\n// Start user service\nuserService.start()\n    .then(() => console.log('✅ User Service started'))\n    .catch(err => console.error('❌ Failed to start User Service:', err));\n\n// -------------------- Order Service --------------------\nconst orderService = new ApiProxy();\norderService.config(orderServiceConfig);\n\n// Register order-related RPC endpoints\norderService.proxy('order-service/create', createOrder);\norderService.proxy('order-service/status', getOrderStatus);\norderService.proxy('order-service/cancel', cancelOrder);\n\n// Start order service\norderService.start()\n    .then(() => console.log('✅ Order Service started'))\n    .catch(err => console.error('❌ Failed to start Order Service:', err));\n\n\n// -------------------- Notification Service --------------------\nconst notificationService = new ApiProxy();\nnotificationService.config(notificationServiceConfig);\n\n// Register notification-related RPC endpoints\nnotificationService.proxy('notification-service/send', sendNotification);\nnotificationService.proxy('notification-service/preferences', getNotificationPreferences);\n\n// Start notification service\nnotificationService.start()\n    .then(() => console.log('✅ Notification Service started'))\n    .catch(err => console.error('❌ Failed to start Notification Service:', err));\n```\n\n### External API Integration\n\n```javascript\n// Weather service that integrates with external APIs\nasync function getCurrentWeather(inparameter, response, proxyPath) {\n    try {\n        const { location, units } = JSON.parse(inparameter.inparam);\n        \n        // Validate input\n        if (!location) {\n            return response.end(JSON.stringify({\n                status: 'ERROR',\n                message: 'Missing required parameter: location',\n                errorCode: 'INVALID_INPUT'\n            }));\n        }\n        \n        const apiKey = process.env.WEATHER_API_KEY;\n        if (!apiKey) {\n            throw new Error('WEATHER_API_KEY not set');\n        }\n\n        const url = `https://api.weather.com/v1/current?location=${encodeURIComponent(location)}&units=${units}`;\n\n        const weatherRes = await fetch(url, {\n            headers: {\n                'Authorization': `Bearer ${apiKey}`\n            }\n        });\n        if (!weatherRes.ok) {\n            throw new Error(`Weather API error: ${weatherRes.status} ${weatherRes.statusText}`);\n        }\n        const weatherData = await weatherRes.json();\n        \n        // Transform and return data\n        response.end(JSON.stringify({\n            status: 'SUCCESS',\n            weather: {\n                location: weatherData.location,\n                temperature: weatherData.current.temp,\n                condition: weatherData.current.condition,\n                humidity: weatherData.current.humidity,\n                windSpeed: weatherData.current.wind_speed,\n                lastUpdated: weatherData.current.last_updated\n            }\n        }));\n    } catch (error) {\n        response.end(JSON.stringify({\n            status: 'ERROR',\n            message: 'Unable to fetch weather data',\n            errorCode: 'WEATHER_API_ERROR'\n        }));\n    }\n}\n\n// Register as an APIFront proxy endpoint\napifront.proxy('weather-service/current', getCurrentWeather);\n```\n\n## 💰 API Monetization\n\nTransform your internal functions into profitable API products with APIFront's complete monetization infrastructure.\n\n### Monetization Models\n\nAPIFront provides flexible credit-based monetization with multiple billing approaches:\n\n| Model                          | Description                                     | Best For                                         |\n| ------------------------------ | ----------------------------------------------- | ------------------------------------------------ |\n| 💰 **API Credit Top-Up**        | Adds credits to existing balance, no expiration | Usage-based billing, pay-as-you-go customers     |\n| 🔄 **API Credit Refresh**       | Replaces existing balance with fixed amount     | Subscription services, predictable monthly costs |\n| ⏱️ **Time-Bound Credit Bundle** | Adds credits with expiration (hourly/daily)     | Promotional offers, trial periods, campaigns     |\n| 📅 **Periodic Service Plan**    | Regular renewal with time-limited credits       | True subscriptions, enterprise customers         |\n\n### Monetization Features\n\n#### Automated Payment Processing\n\n- **Stripe Integration**: Direct integration with Stripe Payment Links\n- **Automatic Credit Allocation**: Credits added immediately after successful payment\n- **Zero Manual Intervention**: Complete automation from purchase to API access\n- **Multiple Payment Methods**: Support for all Stripe-enabled payment options\n\n#### Customer Management\n\n- **Self-Service Onboarding**: Customers can sign up and start using APIs immediately\n- **Usage Analytics**: Real-time tracking of API consumption and costs\n- **Flexible Billing**: Support for prepaid credits, subscriptions, and hybrid models\n- **Customer Portal**: Self-service account management and billing history\n\n### Implementation Example\n\n```javascript\n// Example: API monetization configuration in APIFront\n// This would typically be configured through the APIFront dashboard\n\n// 1. Create API User\nconst apiUser = {\n    email: \"customer@example.com\",\n    name: \"Example Customer\",\n    initial_credits: 1000,  \t// Starting credits\n    access_level: \"standard\"\n};\n\n// 2. Configure Stripe Product with APIFront\nconst stripeProduct = {\n    name: \"Enterprise AI API Access\",\n    description: \"Access to enterprise data functions for AI processing\",\n    credit_model: \"time_bound_addition\", \t// Add credits with expiration\n    credit_amount: 10000,\n    expiration_hours: 720, \t\t\t\t\t// 30 days\n    stripe_payment_link: \"https://buy.stripe.com/your_payment_link\"\n};\n\n// 3. When customer purchases through Stripe:\n// - Stripe sends webhook notification to APIFront\n// - APIFront automatically adds 10,000 credits to the customer's account\n// - Credits are set to expire in 30 days\n// - No manual intervention required\n\n// 4. Your API functions automatically consume credits\nasync function createUser(inparameter, response, proxyPath) {\n    try {\n        const userData = JSON.parse(inparameter.inparam);\n        const clientInfo = JSON.parse(inparameter.info);\n        \n        // APIFront automatically deducts credits based on configuration\n        // Your function just needs to process the request\n        \n        const newUser = await userService.create(userData);\n        \n        response.end(JSON.stringify({\n            status: 'SUCCESS',\n            user: newUser,\n            client: clientInfo.sysinfo.apiClient  // Credit information is available in client info if needed\n        }));\n    } catch (error) {\n        response.end(JSON.stringify({\n            status: 'ERROR',\n            message: error.message\n        }));\n    }\n}\n```\n\n\n\n## 📚 Resources\n\n### Links\n\n- **🌐 [APIFront Dashboard](https://dashboard.apifront.io/)** - Manage gateways and credentials\n- **📖 [Technical Guide](https://apifront.databridges.io/technical-guide)** - Complete technical documentation\n- **💡 [Examples Repository](https://github.com/databridges-io/apifront-examples)** - Sample implementations\n- **🤝 [Support](mailto:tech@optomate.io)** - Technical support and questions\n\n### Related Packages\n\n- **`databridges-sio-server-lib`** - DataBridges server library\n\n## 📄 License\n\nAPIFront Node.js Proxy is released under the [Apache 2.0 license](LICENSE).\n\n```\nCopyright 2022 Optomate Technologies Private Limited.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n```\n\n------\n\n**Ready to transform your functions into enterprise APIs?** Get started with APIFront today and join the function-native API revolution! 🚀","readmeFilename":"README.md"}