j-queue-sdk-web
Advanced tools
Comparing version
{ | ||
"name": "j-queue-sdk-web", | ||
"version": "1.4.2", | ||
"version": "1.4.5", | ||
"description": "A TypeScript package to check WebSocket connection status and control web access with a popup", | ||
@@ -5,0 +5,0 @@ "main": "dist/j-queue-sdk-web.js", |
223
README.md
@@ -1,8 +0,18 @@ | ||
# j-queue-sdk-web | ||
## J-Queue SDK Web | ||
A TypeScript package for managing Socket.IO connections and controlling web access by displaying a customizable full-screen popup when users are in a queue. It integrates with a Socket.IO server to handle queue status updates and navigation restrictions. | ||
The J-Queue SDK Web is a JavaScript library for managing online queue systems in web applications. It provides a seamless integration with a WebSocket-based queue service, displaying a customizable popup UI to inform users about their queue status. | ||
## Features | ||
- **Real-time Queue Management**: Connects to a WebSocket server to receive real-time updates on queue position and status. | ||
- **Customizable Popup UI**: Displays a loading or queue position popup with customizable styles, colors, and languages (English and Korean). | ||
- **Navigation Control**: Prevents navigation during queue wait to ensure users don't lose their place. | ||
- **Session Storage**: Persists queue tokens and connect keys in `sessionStorage` for continuity. | ||
- **Script Tag Configuration**: Supports initialization via `data-*` attributes on the script tag for easy setup. | ||
- **Event Listeners**: Allows adding listeners for queue status updates. | ||
- **Custom Events**: Supports handling custom WebSocket events with utility functions. | ||
## Installation | ||
Install the package via npm: | ||
Install the SDK via npm: | ||
@@ -13,6 +23,6 @@ ```bash | ||
For browser usage, include the `j-queue-sdk-web` script, which bundles the required Socket.IO client: | ||
Or include it directly in your HTML using a CDN (replace `x.x.x` with the desired version): | ||
```html | ||
<script src="https://unpkg.com/j-queue-sdk-web@latest/dist/j-queue-sdk-web.js"></script> | ||
<script src="https://unpkg.com/j-queue-sdk-web@<version>/dist/j-queue-sdk-web.js"></script> | ||
``` | ||
@@ -22,112 +32,119 @@ | ||
### Usage in Browser with `<script>` | ||
### Programmatic Initialization | ||
Initialize the SDK after including the script: | ||
Import and initialize the SDK in your JavaScript/TypeScript code: | ||
```html | ||
<script src="https://unpkg.com/j-queue-sdk-web@latest/dist/j-queue-sdk-web.js"></script> | ||
<script> | ||
try { | ||
// Handle default export | ||
const JQueueSdk = window.ConnectionJQueueSdkWeb.default || window.ConnectionJQueueSdkWeb; | ||
const connection = JQueueSdk.init({ | ||
wsUrl: 'wss://queue-server.example.com', // Socket.IO server URL | ||
apiUrl: 'https://api.example.com', // API server URL (optional) | ||
option: { | ||
storageTokenKey: 'queue_token', | ||
storageConnectKey: 'connect_key' | ||
}, | ||
socketConfig: { | ||
query: { | ||
connect_key: 'CONNECT_KEY' // Replace with actual connect key | ||
}, | ||
transports: ['websocket'], | ||
reconnectionAttempts: 3, | ||
reconnectionDelay: 1000, | ||
}, | ||
popupConfig: { | ||
language: 'en', // 'en' or 'ko' | ||
textColor: '#276bff', | ||
loaderGradientStart: '#276bff', | ||
loaderGradientEnd: 'rgba(39,107,255,0.05)', | ||
isShowLoadingOnConnect: true // Show loading popup before connection | ||
}, | ||
customEvents: { | ||
'online-queue:status': (data, utils) => { | ||
console.log('Queue status:', data); | ||
}, | ||
}, | ||
}); | ||
```typescript | ||
import ConnectionJQueueSdkWeb from 'j-queue-sdk-web'; | ||
// Clean up on page unload | ||
window.addEventListener('beforeunload', () => { | ||
connection.disconnect(); | ||
}); | ||
} catch (error) { | ||
console.error('Error initializing j-queue-sdk-web:', error); | ||
} | ||
</script> | ||
const config = { | ||
wsUrl: 'https://api-extra-queue.pressai.kr', | ||
apiUrl: 'https://api-extra-queue.pressai.kr', | ||
socketConfig: { | ||
query: { connect_key: 'your_connect_key' }, | ||
}, | ||
popupConfig: { | ||
isShowLoadingOnConnect: true, | ||
language: 'en', | ||
textColor: '#276bff', | ||
loaderGradientStart: '#276bff', | ||
loaderGradientEnd: 'rgba(39,107,255,0.05)', | ||
}, | ||
}; | ||
ConnectionJQueueSdkWeb.init(config) | ||
.then(({ disconnect }) => { | ||
console.log('J-Queue SDK initialized'); | ||
// Store disconnect function for later use | ||
}) | ||
.catch((error) => { | ||
console.error('Initialization failed:', error); | ||
}); | ||
// Add a status listener | ||
ConnectionJQueueSdkWeb.addStatusListener((status) => { | ||
console.log('Queue status:', status); | ||
}); | ||
``` | ||
### Notes | ||
- **Default Export**: The script exports `ConnectionJQueueSdkWeb` as `ConnectionJQueueSdkWeb.default`. The code handles both cases for compatibility. | ||
- **Error Handling**: Use `onerror` on the script tag and try-catch to handle initialization errors. | ||
- **Leave Request**: If `apiUrl` is provided, the SDK sends a `navigator.sendBeacon` request to the `/leave` endpoint with a JSON payload (`{"uuid": "..."}`) on disconnect or navigation. | ||
- **Session Storage**: The SDK stores the queue UUID in `sessionStorage` using `storageTokenKey` and the `connect_key` (from `socketConfig.query`) using `storageConnectKey` to ensure continuity across page reloads. | ||
### Script Tag Initialization | ||
## Configuration Options | ||
Include the SDK script with `data-*` attributes to auto-initialize: | ||
- `wsUrl` (string, required): Socket.IO server URL (e.g., `wss://queue-server.example.com`). | ||
- `apiUrl` (string, optional): API server URL for HTTP requests (e.g., `https://api.example.com`). Required for sending `/leave` requests. Defaults to an empty string. | ||
- `option` (object, optional): Additional configuration options for the SDK. | ||
- `storageTokenKey` (string): Key used to store the queue UUID in `sessionStorage` (default: `'queue_token'`). | ||
- `storageConnectKey` (string): Key used to store the `connect_key` from `socketConfig.query` in `sessionStorage` (default: `'connect_key'`). | ||
- `socketConfig` (object, optional): | ||
- `query` (object): Additional query parameters sent to the Socket.IO server (e.g., `{ connect_key: 'CONNECT_KEY' }`). | ||
- `transports` (string[]): Transport methods (e.g., `['websocket']`). Defaults to `['websocket']`. | ||
- `reconnectionAttempts` (number): Number of reconnection attempts (default: `3`). | ||
- `reconnectionDelay` (number): Delay between reconnection attempts in milliseconds (default: `1000`). | ||
- `popupConfig` (object, optional): | ||
- `language` ('en' | 'ko'): Language for default popup content (default: `'ko'`). | ||
- `style` (string): Custom CSS for the popup. | ||
- `content` (string | (position: number) => string): Custom HTML content for the popup, either as a static string or a function that takes `position` and returns HTML. | ||
- `textColor` (string): Color for the popup text (default: `'#276bff'`). | ||
- `loaderGradientStart` (string): Starting color of the loader (default: `'#276bff'`). | ||
- `loaderGradientEnd` (string): Ending color of the loader gradient (default: `'rgba(39,107,255,0.05)'`). | ||
- `isShowLoadingOnConnect` (boolean): If `true`, displays a loading popup before establishing the socket connection (default: `false`). | ||
- `customEvents` (object, optional): Key-value pairs where the key is the event name and the value is a handler function. The handler receives event `data` and utilities `{ createPopup, removePopup, preventNavigation, allowNavigation }`. | ||
```html | ||
<script | ||
src="https://unpkg.com/j-queue-sdk-web@<version>/dist/j-queue-sdk-web.js" | ||
data-ws-url="https://api-extra-queue.pressai.kr" | ||
data-api-url="https://api-extra-queue.pressai.kr" | ||
data-connect-key="your_connect_key" | ||
data-show-loading="true" | ||
data-language="ko" | ||
data-mode="prod" | ||
data-text-color="#276bff" | ||
data-loader-gradient-start="#276bff" | ||
data-loader-gradient-end="rgba(39,107,255,0.05)" | ||
></script> | ||
``` | ||
## Features | ||
The SDK will automatically initialize using these attributes when the script loads. | ||
- Connects to a Socket.IO server to monitor queue status. | ||
- Receives `{ uuid: string, position: number, status: OnlineQueueStatus }` from the Socket.IO server via the `online-queue:status` event. | ||
- Handles queue status updates: | ||
- `ACTIVE`: Removes the popup, allows navigation, and emits `online-queue:check-disconnected` every 30 seconds to maintain connection status. | ||
- `WAITING`: Displays a customizable full-screen popup with the queue `position`, prevents navigation, and emits `online-queue:status` at an interval of 2000ms (adjusted by `(position / 100) * 1000ms` for positions >= 100). | ||
- `EMPTY`: Displays an alert (`'[J Queue] - Connect key does not exist!'`) and clears any active intervals, taking no further UI or navigation actions. | ||
- Supports pre-connection loading popup if `popupConfig.isShowLoadingOnConnect` is `true`, shown before the socket connects and removed on connection success or failure. | ||
- Supports custom Socket.IO events via `customEvents`. | ||
- Provides utilities (`createPopup`, `removePopup`, `preventNavigation`, `allowNavigation`) for custom event handlers. | ||
- Handles connection errors and disconnections with reconnection logic (default: 3 attempts, 1000ms delay). | ||
- Includes default popup styling with a loading animation and multilingual support (English and Korean). | ||
- Sends periodic `online-queue:status` messages for `WAITING` state to maintain queue position. | ||
- Stores `connect_key` in `sessionStorage` for continuity. | ||
- Uses `navigator.sendBeacon` to notify the server with a JSON payload when leaving the queue (if `apiUrl` is provided). | ||
### Configuration Options | ||
The `InitConfig` interface defines the configuration options: | ||
- `wsUrl`: WebSocket URL (default: `https://api-extra-queue.pressai.kr` for prod, `https://dev-api-extra-queue.pressai.kr` for dev). | ||
- `apiUrl`: API URL for operations like leaving the queue. | ||
- `socketConfig`: Socket.IO configuration. | ||
- `query`: Query parameters (e.g., `{ connect_key: 'your_key' }`). | ||
- `transports`: Transport methods (default: `['websocket']`). | ||
- `reconnectionAttempts`: Number of reconnection attempts (default: 3). | ||
- `reconnectionDelay`: Delay between reconnections (default: 1000ms). | ||
- `popupConfig`: Popup UI configuration. | ||
- `content`: Custom HTML or a function returning HTML based on queue position. | ||
- `language`: `'en'` or `'ko'` (default: `'ko'`). | ||
- `textColor`: Text color for popup content. | ||
- `loaderGradientStart`: Starting color for loader gradient. | ||
- `loaderGradientEnd`: Ending color for loader gradient. | ||
- `style`: Custom CSS for the popup. | ||
- `isShowLoadingOnConnect`: Show loading popup during connection (default: `false`). | ||
- `customEvents`: Handlers for custom WebSocket events. | ||
- `option`: Storage key settings. | ||
- `storageTokenKey`: `sessionStorage` key for queue token (default: `'queue_token'`). | ||
- `storageConnectKey`: `sessionStorage` key for connect key (default: `'connect_key'`). | ||
### Methods | ||
- `init(config: InitConfig)`: Initializes the SDK. Returns a promise resolving to an object with a `disconnect` method. | ||
- `addStatusListener(listener)`: Adds a callback to receive queue status updates. | ||
- `removeStatusListener(listener)`: Removes a status listener. | ||
- `getQueueStatus()`: Returns the current queue status (`{ uuid, position, status }` or `null`). | ||
- `initFromScriptAttributes()`: Initializes the SDK using script tag attributes (called automatically on load). | ||
### Queue Statuses | ||
Defined in the `OnlineQueueStatus` enum: | ||
- `WAITING` (1): User is waiting in the queue. | ||
- `ACTIVE` (2): User is active and can proceed. | ||
- `EMPTY` (3): Queue is empty or connect key is invalid. | ||
## Development | ||
### Build | ||
### Prerequisites | ||
Compile TypeScript and bundle the package using Webpack: | ||
- Node.js >= 14 | ||
- npm >= 6 | ||
### Setup | ||
```bash | ||
npm run build | ||
git clone <repository-url> | ||
cd j-queue-sdk-web | ||
npm install | ||
``` | ||
This generates `dist/j-queue-sdk-web.js`, which includes the Socket.IO client. | ||
### Running Tests | ||
### Test | ||
The SDK includes unit tests using Jest. Run them with: | ||
Run tests using Jest in a jsdom environment: | ||
```bash | ||
@@ -137,8 +154,14 @@ npm test | ||
Tests are located in the `tests` directory and cover initialization, status handling, socket events, disconnection, listener management, and loading popup behavior, with mocked Socket.IO connections. | ||
### Building | ||
## Security | ||
To build the SDK: | ||
The default popup content uses direct HTML injection (`innerHTML`). For production use, consider integrating a library like `DOMPurify` to sanitize HTML and prevent XSS attacks. | ||
```bash | ||
npm run build | ||
``` | ||
## Contributing | ||
Contributions are welcome! Please submit a pull request or open an issue to discuss changes. | ||
## License | ||
@@ -152,3 +175,1 @@ | ||
- **Issues**: [https://github.com/joing-sdk-web/j-queue-sdk-web/issues](https://github.com/joing-sdk/j-queue-sdk-web/issues) | ||
</xaiSchema> | ||
172
13.91%474932
-0.37%