@villagehq/widget-sdk
v0.0.9
Published
A type‑safe, embeddable JavaScript widget for Village integrations, including a built‑in events SDK.
Readme
📦 Village Widget
A type‑safe, embeddable JavaScript widget for Village integrations, including a built‑in events SDK.
Table of Contents
- Installation
- Quick Start
- Authentication
- Usage
- Module Usage (ES6)
- Development
- API Reference
- Available Events
Installation
NPM/Yarn
npm install @villagehq/widget-sdk
# or
yarn add @villagehq/widget-sdkCDN (Script Tag)
<script src="https://unpkg.com/@villagehq/widget-sdk/dist/village-widget.js"></script>ES6 Module
import Village from '@villagehq/widget-sdk';Quick Start
// Initialize the SDK
Village.init('YOUR_PARTNER_KEY');
// Authenticate with token
const authResult = await Village.authorize('your-auth-token', 'yourdomain.com');
if (authResult.ok) {
console.log('Authenticated successfully!');
}Authentication
Token-based Authentication
For applications with existing authentication systems:
// Basic token authentication
const result = await Village.authorize(authToken, 'yourdomain.com');
// With automatic token refresh
const result = await Village.authorize(
authToken,
'yourdomain.com',
async () => {
// Your token refresh logic
const newToken = await refreshAuthToken();
return newToken;
}
);User Reference Authentication
For backwards compatibility with the identify system:
// Identify user with reference ID
await Village.authorize('user-123', {
email: '[email protected]',
name: 'John Doe'
});
// Or use the legacy identify method
await Village.identify('user-123', {
email: '[email protected]',
name: 'John Doe'
});Browser Extension Support
The SDK is fully CSP-compliant for Chrome and Firefox extensions:
// manifest.json (Chrome Extension Manifest V3)
{
"content_security_policy": {
"extension_pages": "script-src 'self'; object-src 'self'"
},
"host_permissions": ["https://yourdomain.com/*"]
}
// In your extension popup or content script
import Village from '@villagehq/widget-sdk';
Village.init('YOUR_PARTNER_KEY');
const result = await Village.authorize(token, 'yourdomain.com');Usage
Initializing the SDK
// Basic initialization
Village.init('YOUR_PARTNER_KEY');
// With configuration
Village.init('YOUR_PARTNER_KEY', {
paths_cta: [], // Custom CTAs (see below)
// other config options
});Custom CTAs
// external callback function
function alertUser() {
alert('This alert comes from an external callback!');
}
Village.init('YOUR_PUBLIC_KEY', {
paths_cta: [
{
label: 'Save to CRM',
// inline callback function
callback() {
// your save logic here
alert('Record saved to CRM!');
},
// simple style example
style: {
backgroundColor: '#007bff',
color: '#fff'
}
},
{
label: 'Alert me',
callback: alertUser,
style: {
backgroundColor: '#dc3545',
color: '#fff'
}
}
]
});Listening to Events
// Listen for widget ready
Village.on('village.widget.ready', (data) => {
console.log('Widget is ready!', data);
});
// Listen for CTA clicks
Village.on('village.path.cta.clicked', ({ index, cta, context }) => {
console.log('CTA clicked:', cta.label, context);
});
// Listen for OAuth success
Village.on('village.oauth.success', ({ token }) => {
console.log('OAuth successful, token received');
});
// Listen for paths CTA updates
Village.on('village.paths_cta.updated', (updatedCTAs) => {
console.log('CTAs updated:', updatedCTAs);
});Module Usage (ES6)
For modern JavaScript applications and bundlers:
// Import the module
import Village from '@villagehq/widget-sdk';
// Initialize
Village.init('YOUR_PARTNER_KEY');
// Use async/await for authentication
async function authenticate() {
try {
const result = await Village.authorize(token, 'yourdomain.com');
if (result.ok) {
console.log('Authentication successful!');
} else {
console.error('Authentication failed:', result.reason);
}
} catch (error) {
console.error('Error during authentication:', error);
}
}
// Dynamic CTA management
Village.updatePathsCTA([
{ label: 'Action 1', callback: () => console.log('Action 1') },
{ label: 'Action 2', callback: () => console.log('Action 2') }
]);
// Add single CTA on the fly
Village.addPathCTA({
label: 'New Action',
callback: (payload) => {
console.log('New action clicked', payload);
}
});Development
npm install
npm run dev # Watch mode (builds to development folder)
npm run build # Production build
npm run build:staging # Staging build
npm run lint # ESLint
npm run format # Prettier
npm run test # Vitest
npm run check:bundle # Build + JS syntax checkAPI Reference
Core Methods
Village.init(partnerKey, config?)
Initialize the Village SDK with your partner key.
Parameters:
partnerKey(string, required): Your Village partner keyconfig(object, optional): Configuration optionspaths_cta: Array of CTA objects
Returns: Village instance
Village.authorize(token, domain, refreshCallback?)
Authenticate a user with token or user reference.
Parameters:
token(string): Auth tokendomain(string): Domain for token authrefreshCallback(function, optional): Async function to refresh token when expired
Returns: Promise
{
ok: boolean,
status: 'authorized' | 'unauthorized',
domain?: string,
reason?: string
}Village.identify(userReference, details?)
Legacy method for user identification (backwards compatibility).
Parameters:
userReference(string): Unique user identifierdetails(object, optional): User details (email, name, etc.)
Returns: Promise
Village.logout()
Log out the current user and clear authentication.
Village.on(event, callback)
Subscribe to Village events.
Parameters:
event(string): Event namecallback(function): Event handler
Village.emit(event, data)
Emit custom events.
Parameters:
event(string): Event namedata(any): Event data
Village.updatePathsCTA(ctaList)
Replace the entire CTA list.
Parameters:
ctaList(array): Array of CTA objects
Village.addPathCTA(cta)
Add a single CTA to the existing list.
Parameters:
cta(object): CTA object with label and callback
Available Events
| Event | Description | Payload |
|-----------------------------|------------------------------------------------|------------------------------|
| village.widget.ready | Widget has initialized | void |
| village.path.cta.clicked | User clicked a configured CTA | { index, cta, context } |
| village.paths_cta.updated | CTA list was dynamically updated | PathCTA[] |
| village.user.synced | User graph sync completed | { userId, syncedAt } |
| village.oauth.success | OAuth flow succeeded with token | { token } |
| village.oauth.error | OAuth flow failed | { error } |
| village.widget.error | Internal widget error | { message, source, details } |
