@tencentcloud/web-push 1.0.2 → 1.0.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +8 -0
- package/README.md +23 -88
- package/index.d.ts +186 -37
- package/index.esm.js +1118 -158
- package/index.umd.js +1 -1
- package/package.json +1 -1
- package/src/components/message-popup.d.ts +63 -0
- package/src/core/web-push-sdk.d.ts +23 -1
- package/src/index.d.ts +1 -0
- package/src/types/inner.d.ts +2 -10
- package/src/types/outer.d.ts +90 -36
- package/src/utils/logger.d.ts +6 -0
- package/src/utils/validator.d.ts +0 -13
- package/sw.js +1 -1
package/package.json
CHANGED
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
import { StandardMessage, HtmlMessage } from '../types';
|
|
2
|
+
export interface PopupConfig {
|
|
3
|
+
/** 是否启用弹窗 */
|
|
4
|
+
enabled?: boolean;
|
|
5
|
+
/** 弹窗显示时长(毫秒),0 表示不自动关闭 */
|
|
6
|
+
duration?: number;
|
|
7
|
+
/** 弹窗位置 */
|
|
8
|
+
position?: 'center' | 'top-left' | 'top-center' | 'top-right' | 'right-center' | 'bottom-right' | 'bottom-center' | 'bottom-left' | 'left-center';
|
|
9
|
+
/** 最大显示数量 */
|
|
10
|
+
maxCount?: number;
|
|
11
|
+
/** 是否显示关闭按钮 */
|
|
12
|
+
showCloseButton?: boolean;
|
|
13
|
+
/** 是否允许点击弹窗 */
|
|
14
|
+
clickable?: boolean;
|
|
15
|
+
/** 自定义渲染函数 */
|
|
16
|
+
customRender?: (message: any, container: HTMLElement) => HTMLElement;
|
|
17
|
+
/** 点击回调 */
|
|
18
|
+
onClick?: (message: any, popup: HTMLElement) => void;
|
|
19
|
+
/** 关闭回调 */
|
|
20
|
+
onClose?: (message: any, popup: HTMLElement) => void;
|
|
21
|
+
}
|
|
22
|
+
export declare class MessagePopup {
|
|
23
|
+
private container;
|
|
24
|
+
private popups;
|
|
25
|
+
private timers;
|
|
26
|
+
private messageHandlers;
|
|
27
|
+
private animationTimers;
|
|
28
|
+
private adjustHeightTimers;
|
|
29
|
+
private config;
|
|
30
|
+
private readonly defaultConfig;
|
|
31
|
+
constructor(config?: PopupConfig);
|
|
32
|
+
private init;
|
|
33
|
+
private createContainer;
|
|
34
|
+
private injectStyles;
|
|
35
|
+
show(message: StandardMessage | HtmlMessage): void;
|
|
36
|
+
private createStandardPopup;
|
|
37
|
+
private createHtmlPopup;
|
|
38
|
+
private addPopup;
|
|
39
|
+
private removeOldestPopup;
|
|
40
|
+
close(messageId: string): void;
|
|
41
|
+
/**
|
|
42
|
+
* 检查指定消息是否正在显示弹窗
|
|
43
|
+
* @param messageId 消息ID
|
|
44
|
+
* @returns 是否正在显示
|
|
45
|
+
*/
|
|
46
|
+
hasMessage(messageId: string): boolean;
|
|
47
|
+
closeAll(): void;
|
|
48
|
+
updateConfig(newConfig: Partial<PopupConfig>): void;
|
|
49
|
+
destroy(): void;
|
|
50
|
+
/**
|
|
51
|
+
* 根据 Placement 值应用容器位置
|
|
52
|
+
* 0-中间,1-左上,2-上中,3-右上,4-右中,5-右下,6-下中,7-左下,8-左中
|
|
53
|
+
*/
|
|
54
|
+
private applyPlacement;
|
|
55
|
+
/**
|
|
56
|
+
* 调整iframe高度以适应内容
|
|
57
|
+
*/
|
|
58
|
+
private adjustIframeHeight;
|
|
59
|
+
/**
|
|
60
|
+
* 创建iframe的完整HTML文档
|
|
61
|
+
*/
|
|
62
|
+
private createIframeHtml;
|
|
63
|
+
}
|
|
@@ -3,12 +3,14 @@ export declare class WebPushSDK implements IWebPushSDK {
|
|
|
3
3
|
static instance: WebPushSDK;
|
|
4
4
|
private eventEmitter;
|
|
5
5
|
private serviceWorkerManager;
|
|
6
|
+
private messagePopup;
|
|
6
7
|
private isRegistered;
|
|
7
8
|
private registrationID;
|
|
8
9
|
private chat;
|
|
9
10
|
private SDKAppID;
|
|
10
11
|
private appKey;
|
|
11
12
|
private vapidPublicKey;
|
|
13
|
+
private pendingMessages;
|
|
12
14
|
EVENT: typeof EVENT;
|
|
13
15
|
VERSION: string;
|
|
14
16
|
constructor();
|
|
@@ -16,16 +18,36 @@ export declare class WebPushSDK implements IWebPushSDK {
|
|
|
16
18
|
registerPush(options?: RegisterPushOptions): Promise<string>;
|
|
17
19
|
unRegisterPush(): Promise<boolean>;
|
|
18
20
|
addPushListener(eventName: EVENT, listener: Function): string;
|
|
21
|
+
/**
|
|
22
|
+
* 内部方法:向 Service Worker 发送日志级别配置
|
|
23
|
+
* @param logLevel 日志级别 0-4
|
|
24
|
+
*/
|
|
25
|
+
private sendLogLevelToServiceWorker;
|
|
19
26
|
removePushListener(eventName: EVENT, listener: Function): boolean;
|
|
20
27
|
private checkBrowserSupport;
|
|
21
28
|
private requestNotificationPermission;
|
|
22
|
-
private
|
|
29
|
+
private pushLogin;
|
|
30
|
+
private onMessageReceived;
|
|
31
|
+
private onMessageRevoked;
|
|
32
|
+
private addChatListener;
|
|
33
|
+
private removeChatListener;
|
|
23
34
|
private getSystemPermissionMessage;
|
|
24
35
|
private showSystemPermissionAlert;
|
|
25
36
|
private getBrowserInstType;
|
|
26
37
|
private setToken;
|
|
27
38
|
private initializeBrowserCompatibility;
|
|
39
|
+
private setupVisibilityChangeListener;
|
|
28
40
|
private setupInternalListeners;
|
|
29
41
|
private pushStatistics;
|
|
30
42
|
private clearState;
|
|
43
|
+
/**
|
|
44
|
+
* 向 service-worker 发送通知消息,使用与 push 事件相同的数据格式
|
|
45
|
+
* @param webpushInfo webpush 信息,格式与 SW push 事件接收的数据一致
|
|
46
|
+
*/
|
|
47
|
+
private sendNotificationToServiceWorker;
|
|
48
|
+
/**
|
|
49
|
+
* 向 service-worker 发送消息撤回请求
|
|
50
|
+
* @param messageID 要撤回的消息ID
|
|
51
|
+
*/
|
|
52
|
+
private sendMessageRevokeToServiceWorker;
|
|
31
53
|
}
|
package/src/index.d.ts
CHANGED
package/src/types/inner.d.ts
CHANGED
|
@@ -1,14 +1,6 @@
|
|
|
1
|
-
|
|
2
|
-
messageID: string;
|
|
3
|
-
title: string;
|
|
4
|
-
body: string;
|
|
5
|
-
icon?: string;
|
|
6
|
-
tag?: string;
|
|
7
|
-
data?: any;
|
|
8
|
-
timestamp: number;
|
|
9
|
-
}
|
|
1
|
+
import { NotificationMessage } from "./outer";
|
|
10
2
|
export interface NotificationClickData {
|
|
11
|
-
notification:
|
|
3
|
+
notification: NotificationMessage;
|
|
12
4
|
action?: string;
|
|
13
5
|
}
|
|
14
6
|
export interface StatisticsData {
|
package/src/types/outer.d.ts
CHANGED
|
@@ -1,3 +1,15 @@
|
|
|
1
|
+
export type LogLevel = 0 | 1 | 2 | 3 | 4;
|
|
2
|
+
export declare enum Placement {
|
|
3
|
+
CENTER = 0,// 中间
|
|
4
|
+
TOP_LEFT = 1,// 左上
|
|
5
|
+
TOP_CENTER = 2,// 上中
|
|
6
|
+
TOP_RIGHT = 3,// 右上
|
|
7
|
+
MIDDLE_RIGHT = 4,// 右中
|
|
8
|
+
BOTTOM_RIGHT = 5,// 右下
|
|
9
|
+
BOTTOM_CENTER = 6,// 下中
|
|
10
|
+
BOTTOM_LEFT = 7,// 左下
|
|
11
|
+
MIDDLE_LEFT = 8
|
|
12
|
+
}
|
|
1
13
|
export interface WebPushSDK {
|
|
2
14
|
registerPush(options?: RegisterPushOptions): Promise<any>;
|
|
3
15
|
unRegisterPush(): Promise<any>;
|
|
@@ -10,50 +22,92 @@ export interface RegisterPushOptions {
|
|
|
10
22
|
userID: string;
|
|
11
23
|
serviceWorkerPath?: string;
|
|
12
24
|
chat?: any;
|
|
25
|
+
/**
|
|
26
|
+
* 日志级别:
|
|
27
|
+
* 0 - 普通级别,日志量较多,接入时建议使用
|
|
28
|
+
* 1 - release级别,SDK 输出关键信息,生产环境时建议使用(默认)
|
|
29
|
+
* 2 - 告警级别,SDK 只输出告警和错误级别的日志
|
|
30
|
+
* 3 - 错误级别,SDK 只输出错误级别的日志
|
|
31
|
+
* 4 - 无日志级别,SDK 将不打印任何日志
|
|
32
|
+
*/
|
|
33
|
+
logLevel?: LogLevel;
|
|
13
34
|
}
|
|
14
35
|
export declare enum EVENT {
|
|
15
36
|
MESSAGE_RECEIVED = "message_received",
|
|
16
37
|
MESSAGE_REVOKED = "message_revoked",
|
|
17
|
-
NOTIFICATION_CLICKED = "notification_clicked"
|
|
38
|
+
NOTIFICATION_CLICKED = "notification_clicked",
|
|
39
|
+
CUSTOM_MESSAGE_RECEIVED = "custom_message_received"
|
|
40
|
+
}
|
|
41
|
+
export interface NotificationMessage {
|
|
42
|
+
messageID: string;
|
|
43
|
+
title: string;
|
|
44
|
+
body: string;
|
|
45
|
+
icon?: string;
|
|
46
|
+
tag?: string;
|
|
47
|
+
data?: any;
|
|
48
|
+
timestamp: number;
|
|
18
49
|
}
|
|
19
|
-
export interface
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
needReadReceipt: Boolean;
|
|
40
|
-
readReceiptInfo: any;
|
|
41
|
-
isBroadcastMessage: Boolean;
|
|
42
|
-
isSupportExtension: Boolean;
|
|
43
|
-
receiverList?: String[];
|
|
44
|
-
revoker: String;
|
|
45
|
-
sequence: Number;
|
|
46
|
-
progress: Number;
|
|
47
|
-
revokerInfo: {
|
|
48
|
-
userID: String;
|
|
49
|
-
nick: String;
|
|
50
|
-
avatar: String;
|
|
50
|
+
export interface StandardMessage {
|
|
51
|
+
id: string;
|
|
52
|
+
MsgType: 'standard';
|
|
53
|
+
MsgContent: {
|
|
54
|
+
Text: {
|
|
55
|
+
Title: string;
|
|
56
|
+
Desc: string;
|
|
57
|
+
};
|
|
58
|
+
Image?: {
|
|
59
|
+
URL: string;
|
|
60
|
+
LinkURL: string;
|
|
61
|
+
};
|
|
62
|
+
Close: 0 | 1;
|
|
63
|
+
Placement?: Placement;
|
|
64
|
+
Duration?: number;
|
|
65
|
+
Button?: Array<{
|
|
66
|
+
Text: string;
|
|
67
|
+
Icon?: string;
|
|
68
|
+
Url: string;
|
|
69
|
+
}>;
|
|
51
70
|
};
|
|
52
|
-
|
|
53
|
-
|
|
71
|
+
Ext?: string;
|
|
72
|
+
}
|
|
73
|
+
export interface HtmlMessage {
|
|
74
|
+
id: string;
|
|
75
|
+
MsgType: 'html';
|
|
76
|
+
MsgContent: {
|
|
77
|
+
Placement?: Placement;
|
|
78
|
+
Duration?: number;
|
|
79
|
+
Html: string;
|
|
80
|
+
};
|
|
81
|
+
Ext?: string;
|
|
82
|
+
}
|
|
83
|
+
export interface CustomMessage {
|
|
84
|
+
id: string;
|
|
85
|
+
MsgType: 'custom';
|
|
86
|
+
MsgContent: {
|
|
87
|
+
Data: string | object;
|
|
88
|
+
};
|
|
89
|
+
Ext?: string;
|
|
90
|
+
}
|
|
91
|
+
export interface WebPushInfo {
|
|
92
|
+
Title: string;
|
|
93
|
+
Desc: string;
|
|
94
|
+
Icon: string;
|
|
95
|
+
Image: string;
|
|
96
|
+
URL: string;
|
|
97
|
+
}
|
|
98
|
+
export interface WebPushExt {
|
|
99
|
+
WebpushReportUrl: string;
|
|
100
|
+
OnlineClickExt: string;
|
|
101
|
+
TaskId: string;
|
|
102
|
+
}
|
|
103
|
+
export type PushMessage = StandardMessage | HtmlMessage | CustomMessage;
|
|
104
|
+
export interface MessageReceivedData {
|
|
105
|
+
content: string;
|
|
106
|
+
info: WebPushInfo;
|
|
107
|
+
extension: WebPushExt;
|
|
54
108
|
}
|
|
55
109
|
export interface MessageReceivedResult {
|
|
56
|
-
message:
|
|
110
|
+
message: PushMessage | NotificationMessage;
|
|
57
111
|
}
|
|
58
112
|
export interface MessageRevokedResult {
|
|
59
113
|
messageID: String;
|
package/src/utils/logger.d.ts
CHANGED
|
@@ -1,10 +1,16 @@
|
|
|
1
|
+
import { LogLevel } from '../types/outer';
|
|
1
2
|
export declare class Logger {
|
|
2
3
|
private static instance;
|
|
4
|
+
private logLevel;
|
|
3
5
|
private constructor();
|
|
4
6
|
static getInstance(): Logger;
|
|
7
|
+
setLogLevel(level: LogLevel): void;
|
|
8
|
+
getLogLevel(): LogLevel;
|
|
9
|
+
private shouldLog;
|
|
5
10
|
log(message: string, ...args: any[]): void;
|
|
6
11
|
warn(message: string, ...args: any[]): void;
|
|
7
12
|
error(message: string, ...args: any[]): void;
|
|
8
13
|
info(message: string, ...args: any[]): void;
|
|
14
|
+
debug(message: string, ...args: any[]): void;
|
|
9
15
|
}
|
|
10
16
|
export declare const logger: Logger;
|
package/src/utils/validator.d.ts
CHANGED
|
@@ -37,21 +37,8 @@ export declare class Validator {
|
|
|
37
37
|
static validateEventType(eventType: any): void;
|
|
38
38
|
static validateListener(listener: any): void;
|
|
39
39
|
static validateRegisterPushOptions(options: any): void;
|
|
40
|
-
static validatePushMessage(message: any): void;
|
|
41
|
-
/**
|
|
42
|
-
* Validate URL format
|
|
43
|
-
*/
|
|
44
|
-
static validateURL(url: any, fieldName?: string): void;
|
|
45
40
|
/**
|
|
46
41
|
* Validate Service Worker path
|
|
47
42
|
*/
|
|
48
43
|
static validateServiceWorkerPath(path: any): void;
|
|
49
44
|
}
|
|
50
|
-
/**
|
|
51
|
-
* Parameter validation decorator
|
|
52
|
-
*/
|
|
53
|
-
export declare function validateParams(schema: ValidationSchema): (_target: any, _propertyName: string, descriptor: PropertyDescriptor) => PropertyDescriptor;
|
|
54
|
-
/**
|
|
55
|
-
* Single parameter validation decorator
|
|
56
|
-
*/
|
|
57
|
-
export declare function validateParam(paramIndex: number, rule: ValidationRule): (_target: any, _propertyName: string, descriptor: PropertyDescriptor) => PropertyDescriptor;
|
package/sw.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
!function(){"use strict";function t(t,...e)
|
|
1
|
+
!function(){"use strict";let t=1;function e(e){return 4!==t&&e>=t}function a(t,...a){e(1)&&console.log(`[WebPush SW] ${t}`,...a)}function i(t,...a){e(2)&&console.warn(`[WebPush SW] ${t}`,...a)}function n(t,...a){e(3)&&console.error(`[WebPush SW] ${t}`,...a)}async function o(t,e={}){const{shouldReport:a=!0,clickEventType:i=2}=e,n={messageID:t.id||Date.now().toString(36)+Math.random().toString(36).substring(2),title:t.title||"New Message",body:t.desc||"You have a new message",icon:t.icon||"",tag:t.tag||t?.id?.slice(-100)||"push-"+Date.now()+"-"+Math.random().toString(36).substring(2,7),data:{url:t.url,image:t.image,rptExt:t.rptExt,rptURL:t.rptURL,clickEventType:i},timestamp:Date.now()},o=self.registration.showNotification(n.title,{body:n.body,icon:n.icon,image:t.image,tag:n.tag,data:n,requireInteraction:!1}),l=r({type:"MESSAGE_RECEIVED",data:s(n)}),d=a&&t.rptURL&&t.rptExt?c({id:t.id,rptURL:t.rptURL,rptExt:t.rptExt,eventType:1}):Promise.resolve();await Promise.all([o,l,d])}function s(t){return{messageID:t.messageID,title:t.title,body:t.body,icon:t.icon,tag:t.tag,data:{url:t.data?.url,image:t.data?.image},timestamp:t.timestamp}}async function r(t){try{(await self.clients.matchAll({includeUncontrolled:!0,type:"window"})).forEach(e=>{e.postMessage(t)})}catch(e){n("Failed to send message to clients",e)}}async function c(t){try{if(!t.rptURL||!t.rptExt)return void i("Missing rptURL or rptExt, skipping report");const e={webpushEvents:[{id:t.id,EventType:t.eventType||1,EventTime:Math.floor(Date.now()/1e3),rptExt:t.rptExt}]};a("Reporting WebPush event",{rptURL:t.rptURL,reportData:e});const n=await fetch(t.rptURL,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});n.ok?a("WebPush event reported successfully"):i("Failed to report WebPush event",n.status,n.statusText)}catch(e){n("Error reporting WebPush event",e)}}self.addEventListener("install",t=>{a("Service Worker installing..."),self.skipWaiting()}),self.addEventListener("activate",t=>{a("Service Worker activating..."),t.waitUntil(self.clients.claim())}),self.addEventListener("push",t=>{if(a("Push message received",t),t.data)try{const e=function(t){if(!t)throw new Error("No push data available");try{const e=t.json();return a("Push message data (JSON):",e),e}catch{const e=t.text();return a("Push message data (Text):",e),{id:"",title:"WebPush Notification",desc:e||"You have a new message",url:"/",icon:"",tag:"",image:"",rptExt:"",rptURL:""}}}(t.data);t.waitUntil(o(e))}catch(e){n("Failed to process push message",e),t.waitUntil(self.registration.showNotification("WebPush Notification",{body:"You have a new message",tag:"fallback"}))}else i("Push message has no data")}),self.addEventListener("notificationclick",t=>{a("Notification clicked",t);const e=t.notification,o=t.action,l=e.data;if(e.close(),"close"===o)return;const d=r({type:"NOTIFICATION_CLICKED",data:{notification:s(l),action:o}}),u=async function(t="/"){try{a("Attempting to open or focus window with URL:",t);const n=await self.clients.matchAll({type:"window",includeUncontrolled:!0});let o;a("Found clients:",n.length);try{o=t.startsWith("http://")||t.startsWith("https://")?t:new URL(t,self.location.origin).href}catch(e){i("Invalid URL, using origin:",t,e),o=self.location.origin}a("Full target URL:",o);for(const t of n)if(t.url===o&&"focus"in t)return void(await t.focus());self.clients.openWindow&&await self.clients.openWindow(o)}catch(e){n("Failed to open or focus window",e)}}(l?.data?.url||"/"),p=l?.data?.clickEventType||2,f=l?.data?.rptURL&&l?.data?.rptExt?c({id:l.messageID,rptURL:l.data.rptURL,rptExt:l.data.rptExt,eventType:p}):Promise.resolve();t.waitUntil(Promise.all([d,u,f]))}),self.addEventListener("notificationclose",t=>{a("Notification closed",t)}),self.addEventListener("message",e=>{a("Message received from main thread",e.data);const{type:i,payload:s}=e.data;switch(i){case"SHOW_NOTIFICATION":!async function(t){try{const{eventType:e,data:i,options:n}=t;a("Handling show notification request",{eventType:e,data:i,options:n}),await self.registration.showNotification(n.title,{body:n.body,icon:n.icon,badge:n.badge,tag:n.tag,requireInteraction:n.requireInteraction,silent:n.silent,data:n.data}),a("Notification shown successfully",n.title)}catch(e){n("Failed to handle show notification",e)}}(s);break;case"PROCESS_WEBPUSH_DATA":!async function(t){try{a("Handling webpush data from main thread",t),await o(t,{shouldReport:!1,clickEventType:3}),a("WebPush notification processed successfully")}catch(e){n("Failed to handle webpush data",e);try{await self.registration.showNotification("WebPush Notification",{body:"You have a new message",tag:"fallback"})}catch(i){n("Failed to show fallback notification",i)}}}(s);break;case"REVOKE_MESSAGE":!async function(t){try{(await self.registration.getNotifications()).forEach(e=>{e.data&&e.data.messageID===t&&e.close()}),await r({type:"MESSAGE_REVOKED",data:{messageID:t}})}catch(e){n("Failed to handle message revocation",e)}}(s.messageID);break;case"SET_LOG_LEVEL":l=s.logLevel,t=l,a("Log level updated to:",l);break;case"REPORT_WEBPUSH_EVENT":c(s)}var l}),self.addEventListener("error",t=>{n("Service Worker error",t.error)}),self.addEventListener("unhandledrejection",t=>{n("Service Worker unhandled promise rejection",t.reason)})}();
|