bstp-agent-widget
v0.2.56
Published
`bstp-agent-widget` is an Agent Chat widget library that can be integrated into other React projects.
Readme
BSTP Agent Widget
bstp-agent-widget is an Agent Chat widget library that can be integrated into other React projects.
Library Build & Publish
1) Build the library
bun run build:lib2) Check package contents
bun run pack:check3) Publish to npm
npm publish --access publicNote:
prepublishOnlyautomatically runsbuild:lib.
Consumer Project Usage
bun add bstp-agent-widgetimport { AgentChatWidget } from 'bstp-agent-widget';
import 'bstp-agent-widget/style.css';
export function Page() {
return (
<AgentChatWidget
config={{
baseUrl: 'https://your-genai-api-url',
assistantId: 123,
genaiInit: {
email: '[email protected]',
clientSecret: 'secret',
},
}}
runtime={{
customerId: '590100010884',
customerToken: 'jwt-token',
language: 'tr-TR',
}}
/>
);
}Development Notes
reactandreact-domare defined aspeerDependencies.- Library outputs are generated under
dist/.
Angular Integration (Step by Step)
- Build the npm package in this repository:
bun run build:lib && npm pack- Install the generated tarball in your Angular app:
npm i /path/to/bstp-agent-widget-0.2.5.tgz- Add widget stylesheet once in Angular global styles (
src/styles.scss):
@import 'bstp-agent-widget/style.css';- Mount the widget from an Angular component:
import { AfterViewInit, Component, ElementRef, OnDestroy, ViewChild } from '@angular/core';
import { mountAgentChatWidgetFromEnvironment } from 'bstp-agent-widget';
@Component({
selector: 'app-agent-chat-widget',
template: '<div #widgetHost></div>',
})
export class AgentChatWidgetComponent implements AfterViewInit, OnDestroy {
@ViewChild('widgetHost', { static: true }) widgetHost!: ElementRef<HTMLDivElement>;
private cleanup: (() => void) | null = null;
async ngAfterViewInit(): Promise<void> {
this.cleanup = await mountAgentChatWidgetFromEnvironment(this.widgetHost.nativeElement, {
runtime: {
customerId: '590100010884',
customerToken: 'jwt-token',
language: 'en-US',
},
// Agent config can be supplied by host app.
// baseUrl and genai.init still come from environment.json.
config: {
assistantId: 220,
assistants: [
{ assistantKey: 'salesAgent', assistantId: 220, label: 'Sales Assistant' },
],
},
ui: {
zIndex: 12000,
withinPortal: true,
fabPosition: { bottom: 16, right: 16 },
},
// Optional. Default: /environment.json
// environmentUrl: '/environment.json',
});
}
ngOnDestroy(): void {
this.cleanup?.();
}
}- Provide GenAI configuration in Angular app
public/environment.json:
{
"url": {
"api": "https://...",
"apiPaths": {
"genai": "genai/api/v1"
}
},
"genai": {
"config": {
"assistantId": 220
}
}
}Base URL is resolved from url.api + url.apiPaths.genai.
React Starter Kit
A modern, enterprise-grade React Starter Kit built with TypeScript, providing a comprehensive foundation for building scalable web applications. This starter kit includes all the essential tools and configurations needed for modern React development.
Technical Stack
- Framework: React
- Language: TypeScript
- Build Tool: Vite
- Package Manager: Bun
Core Dependencies
- UI Framework: Mantine
- Routing: TanStack Router
- Server State Management: TanStack Query
- Client State Management: Zustand
- Authentication: Keycloak
- Internationalization: Lingui
- HTTP Client: Axios
- Form Management: TanStack React Form
- Validation: Valibot
- Virtual Scrolling: React Virtuoso
Prerequisites
Getting Started
Clone the repository
Install dependencies:
bun installStart the development server:
bun devThe application will be available at
http://localhost:4203
Available Scripts
bun dev- Start development serverbun run build- Build for productionbun preview- Preview production buildbun lint- Run oxlint and TypeScript type checkingbun lint:fix- Auto-fix linting issues with oxlintbun format- Format code with oxfmtbun storybook- Start Storybook development serverbun build:storybook- Build Storybook for productionbun intl:extract- Extract translation stringsbun intl:build- Build translations for productionbun script:build-metadata- Generate build metadata information
Building for Subpath Deployment
If you need to deploy the application under a specific subpath (e.g., https://example.com/my-app/), you need to set the BASE_URL environment variable during the build process. This ensures that all asset paths are correctly resolved relative to the deployment subpath.
Example:
# Build for production deployment under /my-app
BASE_URL=/my-app bun run build
# Build with sourcemaps for deployment under /my-app
BASE_URL=/my-app bun build:sourcemapAPI Documentation
The project includes an API documentation generator that creates a comprehensive list of all API endpoints used in the application. It:
- Lists all API endpoints grouped by service and HTTP method
- Detects and reports duplicate API endpoints
- Generates both human-readable (TXT) and machine-readable (JSON) documentation
- Includes endpoint details like HTTP method, full URL path, and service information
Example output:
Total API Count: 54
Date: 21-02-2025 16:37
=== RestCrmService ===
GET:
/crm/account/billingAccountHierarchyForLoggedInContact
/crm/contact/basicInfo?contactId={param}
...
POST:
/crm/contact/contactMedium
...The documentation is automatically generated and includes:
- Total API count
- Generation timestamp
- Service-based grouping
- Method-based subgrouping
- Duplicate API detection and reporting
- Parameter placeholders for dynamic URLs
Build Metadata
The project includes a build metadata system that generates a JSON file with build information:
{
"baseUrl": "/",
"buildTime": {
"date": "February 4, 2025",
"time": "11:46:50 Eastern European Time",
"timestamp": 1738658810111
},
"commitSha": "11bf88f",
"isDev": false,
"sourceMap": false
}This metadata includes:
- Build date and time in human-readable format
- Unix timestamp for programmatic use
- Git commit SHA
- Environment information (development/production)
- Build configuration (sourcemap status)
The metadata is automatically generated during the build process and stored in public/build-metadata.json.
Project Structure
src/
├── api/ # API integration
├── components/ # Reusable components
├── config/ # Configuration files
├── constant/ # Constants and enums
├── context/ # React contexts
├── hooks/ # Custom hooks
├── icons/ # SVG icons
├── locales/ # i18n translations
├── providers/ # Context providers
├── queries/ # TanStack Query definitions
├── theme/ # Mantine theme customization, styles, etc.
├── types/ # TypeScript types
│ ├── dto/ # Backend API DTOs (e.g., user-dto.ts)
│ └── models/ # Frontend-only interfaces (e.g., navigation-state.ts)
└── utils/ # Utility functionsTypes Organization
The types/ directory is organized into two categories:
DTO Types (
dto/)- Used for backend API interfaces
- Always suffixed with
-dto.ts - Example:
user-dto.ts,credential-dto.ts
Model Types (
models/)- Used for frontend-only interfaces
- No suffix needed
- Example:
navigation-state.ts,form-state.ts
Naming Conventions
- Interfaces: PascalCase
- Properties: camelCase
- Files: kebab-case
Features
- Modern React with TypeScript
- Component library based on Mantine
- Type-safe routing with TanStack Router
- Internationalization support (en, fr)
- Oxlint and Oxfmt configuration
- Storybook for component development
- Comprehensive build system with Vite
- Docker support for containerization
- Automated dependency management with Renovate
Theme Customization
The project includes a flexible theme override system using factory functions. See the Storybook Theme documentation for complete details.
Creating Custom Themes
Use createDesignTheme to override design tokens and/or Mantine theme settings:
import { createDesignTheme } from '@/theme/foundations/design-theme';
const CustomTheme = createDesignTheme({
tokens: {
color: { 'primary-default': '#1A1A2E' },
},
theme: {
fontFamily: 'Inter',
},
});Available Overrides
- tokens: Design tokens (colors, spacing, radius, shadows, borders, opacity)
- theme: Mantine theme settings (fonts, colors, breakpoints, component defaults)
Applying Custom Theme
To use your custom theme, update the MantineProvider in src/providers/AppProviders.tsx:
// src/providers/AppProviders.tsx
import { createDesignTheme } from '@/theme/foundations/design-theme';
const CustomTheme = createDesignTheme({
tokens: { color: { 'primary-default': '#1A1A2E' } },
theme: { fontFamily: 'Inter' },
});
// Then pass it to MantineProvider
<MantineProvider theme={CustomTheme}>
{/* ... */}
</MantineProvider>Development
The project uses several development tools:
- Oxlint for code linting
- Oxfmt for code formatting
- TypeScript for type checking
- PostCSS for CSS processing
- SCSS for styling
- Vite for fast development and building
- Husky for git hooks
- Lint-staged for pre-commit checks
Debug Tools
The application includes a comprehensive set of debug tools that can be accessed in two ways:
Development Mode: Debug tools are automatically enabled when running the application in development mode.
Production Mode: Debug tools can be enabled by setting
user-management-debugtotruein localStorage:localStorage.setItem('user-management-debug', 'true');
The debug tools panel includes:
- Authentication token inspection
- Build metadata inspection
- Network request monitoring
- HTTP error debugging
- Local storage inspection
- Environment configuration viewer
- Query cache inspection
- Route information
These tools are particularly useful for:
- Troubleshooting production issues
- Monitoring API requests
- Inspecting application state
- Debugging authentication flows
- Analyzing performance bottlenecks
Environment Configuration
Environment configuration is stored in /public/environment.json and includes:
- API endpoints
- Keycloak configuration
- Other environment-specific settings
Note: The public/environment.json file included in the repository is static and primarily configured for local development. During deployment, particularly when using Helm, these configurations are typically overridden by values defined in the Helm chart, ignoring the static file.
Browser Support
The application is built using modern web technologies and supports all modern browsers.
Storybook
The project includes Storybook for component development and documentation:
- Component story development
- Dark mode support
- Documentation generation
- Isolated component testing
Permission System
Declarative permission checking with component-based and HOC approaches.
// Component-based (recommended)
<PermissionGroup path="dashboard">
<PermissionGroup path="last-customers">
<Permission path="view-button">
<Button>View</Button> // Checks: dashboard.last-customers.view-button
</Permission>
</PermissionGroup>
</PermissionGroup>;
// Route-level protection with pre-fetching
const ProtectedRoute = withPermissionGuard(DashboardPage, {
guard: 'dashboard',
preload: ['settings', 'users'],
redirectTo: '/login',
});See Permission.mdx for detailed documentation.
Built-in support for multiple languages:
- English (en) and French (fr) support
- Automatic translation extraction
- PO file format support
- Runtime language switching
