@justai/atrium
v0.1.11
Published
@justai/atrium is a JavaScript library designed to facilitate communication between different services or components running in separate browser windows or frames. This project aims to simplify the integration of web applications that need to exchange mes
Readme
@justai/atrium
Introduction
@justai/atrium is a JavaScript library designed to facilitate communication between different services or components running in separate browser windows or frames. This project aims to simplify the integration of web applications that need to exchange messages or invoke functionalities from each other, efficiently creating a network of interconnected services within a browser environment.
How It Works
The library functions by establishing communication channels between services using the browser's messaging capabilities such as the postMessage API and MessageChannel. By associating unique identifiers with each service, it ensures that messages are accurately routed to their intended destination. It includes mechanisms to find available routes for communication dynamically, ensuring robust and reliable message exchanges even in complex multi-window setups.
Key Features
- Service Connection: Establishes connections to external services using unique service IDs, ensuring reliable routing of messages.
- Message Routing: Supports finding routers capable of directing communication to appropriate services or frames.
- Handler Registration: Allows services to register handlers for specific methods, enabling customized functionality exchange.
- Proxy Communication: Facilitates invoking methods on a service from another service without direct dependence.
- Event Handling: Built-in event emitter for managing event-driven interactions between services.
- Safety Checks: Includes checks to prevent self-connection and other potential misconfigurations.
Conclusion
@justai/atrium is valuable for developers looking to create interconnected web applications where components need to communicate efficiently across different environments. By abstracting and simplifying the communication process, it helps developers focus on building feature-rich applications without worrying about the intricacies of cross-window messaging.
Developer Guide for @justai/atrium
Overview
The @justai/atrium library provides a communication framework for connecting services running in different window contexts or frames. It facilitates message-passing between these services using the postMessage API, making it easier to build applications with multiple services communicating in a loosely-coupled manner. The library includes functionality for connecting services, proxying methods across services, and managing communication channels securely and efficiently.
Key Concepts
Before diving into the usage, it's important to understand some key concepts:
- Service: A JavaScript instance that can communicate with other services. Each service has a unique ID.
- Router: A service that can route messages between other services. A router is essential for communication between services in different windows/frames.
- Context: The window environment where a service runs. Each context has a unique ID.
- Handler: A function registered to a service that can be called by other services.
- Proxy: A method that forwards calls to another service.
Installation
To install this library, use npm or yarn. Simply run:
npm install @justai/atriumor
yarn add @justai/atriumBasic Usage
To get started with @justai/atrium, you need to initialize the library and create communication channels between services.
import atrium from '@justai/atrium';
async function setupService() {
// Initialize a service with a unique ID
// Set router: true to enable this service to act as a router
const service = await atrium({
id: 'my-service-id',
verbose: true, // Enable logging for debugging
router: true, // Enable router capabilities
});
// Example: Register a method that echoes the received message
service.register({
method: 'echo',
handler: (args) => {
console.log('Echo received:', args);
return args;
}
});
// Example: Connect to another service
try {
const result = await service.connect({
window: otherWindow,
serviceId: 'other-service-id'
});
console.log('Connected to service:', result);
} catch (error) {
console.error('Connection failed:', error.message);
}
}
setupService();Communication Flow
The typical communication flow between services follows these steps:
- Service Initialization: Each service is initialized with a unique ID.
- Router Discovery: Services find routers using the
findRoutermethod. - Connection Establishment: Services connect to routers using the
connectmethod. - Method Registration: Services register methods that can be called by other services.
- Method Invocation: Services call methods on other services using the
proxymethod or registered proxy methods.
API Reference
Service Initialization
const service = await atrium({
id: 'my-service-id', // Required: Unique service ID (lowercase with - or _)
verbose: true, // Optional: Enable logging (default: false)
router: true // Optional: Enable router capabilities (default: false)
});Core Methods
Register a Method
service.register({
method: 'methodName', // Required: Name of the method
handler: (args, context) => {
// args: Arguments passed to the method
// context: Additional information about the call
return result; // Return value will be sent back to the caller
},
configurable: false // Optional: Whether the method can be overwritten (default: false)
});Register a Proxy Method
service.registerProxy({
alias: 'localMethodName', // Required: Local name for the method
method: 'remoteMethodName', // Required: Name of the method on the remote service
service: 'remote-service-id', // Required: ID of the remote service
configurable: false // Optional: Whether the method can be overwritten (default: false)
});Call a Method on Another Service
const result = await service.proxy({
method: 'methodName', // Required: Name of the method to call
service: 'service-id', // Optional: ID of the target service
args: { /* arguments */ }, // Optional: Arguments to pass to the method
options: { // Optional: Additional options
callback: (event) => { // Optional: Callback for progress updates
console.log('Progress:', event);
},
timeout: 5000 // Optional: Custom timeout in milliseconds
}
});A call to a guest that has not connected yet WAITS for it. A host embeds a guest and calls it;
between those two things a whole document loads, and proxy does not require the caller to have
waited. If the named service is not connected and this service is the router, the call holds until
that service arrives and is sent the moment it does — bounded by the same timeout the call already
carries, not by a second one.
That guarantee is the difference between "embed it, then use it" being true and being a race. It used
to be a race, and the engines disagreed about who won it: Chromium boots an iframe fast enough to
connect before the call almost always, WebKit does not. The failure looked like
No router registered for <id> — an error about the router, raised where the router was fine and the
guest was merely still on its way.
If nothing connects under that name in time, the rejection now says so:
[IS] <id>: no service "files" connected within 1000msFind a Router
const router = await service.findRouter({
timeout: 2000, // Optional: Maximum time to wait (default: 1000ms)
interval: 100, // Optional: Interval between attempts (default: 100ms)
where: { // Optional: Criteria for finding a specific router
id: 'router-id', // Optional: Match by service ID
serviceId: 'service-id', // Optional: Match by internal service ID
contextId: 'context-id', // Optional: Match by context ID
scriptId: 'script-id', // Optional: Match by script ID
client: 'client-id' // Optional: Match by connected client ID
}
});Connect to a Service
const result = await service.connect({
window: targetWindow, // Required: Window object of the target service
serviceId: 'service-id' // Required: Internal service ID of the target
});Unregister a Method
service.unregister({
method: 'methodName' // Required: Name of the method to unregister
});Dispose a Service
service.dispose(); // Cleans up event listeners and resourcesEvent Handling
The library uses EventEmitter for event handling:
// Listen for connection events
service.on('connected', (client) => {
console.log('New client connected:', client);
});
// Remove event listener
service.off('connected', handlerFunction);
// Listen for an event only once
service.once('connected', handlerFunction);Advanced Usage
Using Callbacks for Progress Updates
You can use callbacks to receive progress updates during long-running operations:
const result = await service.proxy({
method: 'longOperation',
service: 'worker-service',
args: { /* arguments */ },
options: {
callback: (progressData) => {
console.log('Operation progress:', progressData);
updateProgressBar(progressData.percentage);
}
}
});Service Discovery with Filtering
You can find routers that match specific criteria:
// Find a router in a specific context
const router = await service.findRouter({
where: { contextId: specificContextId }
});
// Find a router with specific connected clients
const router = await service.findRouter({
where: { client: ['client1', 'client2'] }
});
// Find a router by ID
const router = await service.findRouter({
where: { id: 'main-router' }
});Creating a Multi-Service Architecture
For complex applications, you can create a network of services:
// Main application with router capabilities
const mainService = await atrium({
id: 'main-app',
router: true
});
// Feature-specific services
const authService = await atrium({ id: 'auth-service' });
const dataService = await atrium({ id: 'data-service' });
const uiService = await atrium({ id: 'ui-service' });
// Connect all services to the main router
const router = await authService.findRouter();
await authService.connect(router);
await dataService.connect(router);
await uiService.connect(router);
// Register cross-service methods
authService.register({
method: 'login',
handler: async (credentials) => {
// Authentication logic
return { success: true, token: 'abc123' };
}
});
// Create proxy methods for easier access
uiService.registerProxy({
alias: 'login',
method: 'login',
service: 'auth-service'
});
// Now UI service can call auth service methods directly
const loginResult = await uiService.login({
username: 'user',
password: 'pass'
});Best Practices
Use Descriptive Service IDs: Choose meaningful IDs for your services to make debugging easier.
Enable Verbose Mode During Development: Set
verbose: trueduring development to see detailed logs.Implement Error Handling: Always use try/catch blocks when calling methods on other services.
Set Appropriate Timeouts: Adjust timeouts based on the expected response time of operations.
Use Event Listeners for Connection Management: Listen for 'connected' events to track service connections.
Clean Up Resources: Call
dispose()when a service is no longer needed to prevent memory leaks.Structure Your Services Logically: Divide your application into services based on functionality.
Use Proxy Methods for Cleaner Code: Register proxy methods to make remote calls look like local calls.
Troubleshooting
Common Issues
Connection Failures:
- Ensure the target window is accessible
- Check that the service ID is correct
- Verify that the router is enabled on the target service
Method Not Found Errors:
- Ensure the method is registered on the target service
- Check that the service ID is correct in the proxy call
Timeout Errors:
- Increase the timeout value for long-running operations
- Check for network issues or high latency
Cross-Origin Issues:
- Ensure both windows are from the same origin or have appropriate CORS settings
Debugging Tips
Enable verbose mode to see detailed logs:
const service = await atrium({ id: 'service-id', verbose: true });Use browser developer tools to inspect postMessage events.
Add custom logging to your handlers to track method calls.
Acknowledgement
The development of @justai/atrium leverages the nanoid library for generating unique identifiers and the eventemitter3 for event handling. Special thanks to the developers and contributors of these libraries for providing essential functionality that enhances our library's capabilities.
Input Schema
$schema: https://json-schema.org/draft/2020-12/schema
type: object
properties:
id:
type: string
pattern: ^[a-z0-9]([a-z0-9._-]*[a-z0-9])?$
description: >
The service ID — a key, an address and a label at once. Lowercase letters
and digits, optionally separated by . _ or -, starting and ending with a
letter or digit. "/" is never allowed: it separates hops in a service path
(proxy({ service: "a/b/c" })).
verbose:
type: boolean
description: Enable verbose output for debugging
router:
type: boolean
description: Indicate if the service can act as a router
mount:
description: >
Router only. Decides the LOCAL NAME a connecting service is filed under,
and therefore the name `proxy({ service })` addresses it by. Called with {
sender, origin, serviceId, contextId, scriptId, source } — `source` is the
connecting Window, which is how a host tells one of its own iframes from
another. Return a name, or null to refuse the connection.
Omit it and a service is filed under the name it declares, which is the
original behaviour and is correct while every guest is distinct. It stops
being correct the moment a kernel composes two of the same kind — qr/files
and time/files both call themselves "files" — because a name is how the
router keys its clients. Naming the mount is the host's answer to that,
and it is the same answer an operating system gives: one device, two mount
points.
required:
- id
