@dnotifier-realtime/dnotifier 1.0.12 → 1.0.14
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/README.md +5 -60
- package/dist/cjs/dnotifier.js +1 -0
- package/dist/cjs/providers/openai.js +1 -0
- package/dist/cjs/transport/httpTransport.js +1 -0
- package/dist/cjs/transport/websocketTransport.js +1 -0
- package/dist/cjs/utils/buffer.js +1 -0
- package/dist/cjs/utils/frame.js +1 -0
- package/dist/cjs/utils/id.js +1 -0
- package/dist/cjs/utils/payload.js +1 -0
- package/dist/dnotifier.cjs +488 -0
- package/dist/dnotifier.js +1 -1
- package/dist/providers/openai.js +1 -1
- package/dist/transport/httpTransport.js +1 -1
- package/dist/transport/websocketTransport.js +1 -1
- package/dist/utils/buffer.js +1 -1
- package/dist/utils/frame.js +1 -1
- package/dist/utils/id.js +1 -1
- package/dist/utils/payload.js +1 -1
- package/package.json +11 -2
package/README.md
CHANGED
|
@@ -21,66 +21,11 @@
|
|
|
21
21
|
|
|
22
22
|
```bash
|
|
23
23
|
npm i @dnotifier-realtime/dnotifier
|
|
24
|
+
```
|
|
24
25
|
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
const notifier = new DNotifier({
|
|
28
|
-
appId: "YOUR-APP-ID",
|
|
29
|
-
secret: "YOUR-APP-SECRET",
|
|
30
|
-
transport: "ws", // or "http"
|
|
31
|
-
userId: "YOUR-UNIQUE-USERID",
|
|
32
|
-
onConnected: () => {
|
|
33
|
-
console.log("✅ Connected successfully.");
|
|
34
|
-
},
|
|
35
|
-
onMessage: (data) => {
|
|
36
|
-
console.log("📩 Incoming message:");
|
|
37
|
-
console.log("Metadata:", data.metadata);
|
|
38
|
-
console.log("Message:", data.payload.toJSON());
|
|
39
|
-
console.log("Message:", data.payload.toString());
|
|
40
|
-
console.log("Message:", data.payload.raw());
|
|
41
|
-
}
|
|
42
|
-
});
|
|
43
|
-
|
|
44
|
-
await notifier.connect();
|
|
45
|
-
|
|
46
|
-
// Send single message
|
|
47
|
-
notifier.send({
|
|
48
|
-
senderId: "YOUR-UNIQUE-USERID",
|
|
49
|
-
receiverId: "RECEIVER-UNIQUE-USERID",
|
|
50
|
-
code: 200,
|
|
51
|
-
data: {
|
|
52
|
-
text: "Hello from DNotifier SDK 🚀"
|
|
53
|
-
}
|
|
54
|
-
});
|
|
55
|
-
|
|
56
|
-
// Broadcast message
|
|
57
|
-
notifier.send({
|
|
58
|
-
senderId: "YOUR-UNIQUE-USERID",
|
|
59
|
-
receiverIds: ["user_2", "user_3"],
|
|
60
|
-
code: 200,
|
|
61
|
-
data: "Broadcast test message"
|
|
62
|
-
});
|
|
63
|
-
|
|
64
|
-
// Send Binary Data (files, images , media)
|
|
65
|
-
const buffer = Buffer.from("Hello Binary");
|
|
66
|
-
|
|
67
|
-
notifier.sendBinary({
|
|
68
|
-
senderId: "YOUR-UNIQUE-USERID",
|
|
69
|
-
receiverIds: ["user_1"],
|
|
70
|
-
buffer
|
|
71
|
-
});
|
|
72
|
-
|
|
73
|
-
// --- OpenAI (and compatible APIs) ---
|
|
74
|
-
// Send a message to OpenAI; the model response is delivered to receivers via onMessage.
|
|
75
|
-
// No OpenAI SDK or integration needed on the receiver side.
|
|
76
|
-
|
|
77
|
-
await notifier.sendWithOpenAI({
|
|
78
|
-
senderId: "YOUR-UNIQUE-USERID",
|
|
79
|
-
message: "What is 2 + 2?", // or messages: [{ role: "user", content: "..." }]
|
|
80
|
-
openaiApiKey: process.env.OPENAI_API_KEY,
|
|
81
|
-
model: "gpt-4o-mini", // optional, default gpt-4o-mini
|
|
82
|
-
});
|
|
26
|
+
---
|
|
83
27
|
|
|
84
|
-
|
|
85
|
-
// { type: "openai", content: "...", ts: 1234567890 }
|
|
28
|
+
## 📖 How to use
|
|
86
29
|
|
|
30
|
+
- **Product website:** [dnotifier.com](https://www.dnotifier.com)
|
|
31
|
+
- **Documentation:** [Product docs](https://dnotifier.gitbook.io/product-docs) — setup, integration, and full API usage
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
'use strict';Object['defineProperty'](exports,'__esModule',{'value':!0x0}),exports['DNotifier']=void 0x0;const httpTransport_js_1=require('./transport/httpTransport.js'),websocketTransport_js_1=require('./transport/websocketTransport.js'),id_js_1=require('./utils/id.js'),frame_js_1=require('./utils/frame.js'),payload_js_1=require('./utils/payload.js'),buffer_js_1=require('./utils/buffer.js'),openai_js_1=require('./providers/openai.js');class DNotifier{constructor({appId:_0x24ebe4,secret:_0x278fe9,transport:_0x231977,userId:_0x30148d,onConnected:_0x1e9cd0,onMessage:_0xff7604,onDisconnected:_0x3caf45,WebSocketImpl:_0x5da024}){if(!(_0x24ebe4&&_0x278fe9&&_0x231977&&_0x30148d))throw new Error('appId,\x20secret,\x20transport,\x20and\x20userId\x20are\x20required');this['appId']=_0x24ebe4,this['secret']=_0x278fe9,this['userId']=_0x30148d,this['url']='wss://link.dchatter.com/ws',this['onConnectedCallback']=_0x1e9cd0||(()=>{}),this['onMessageCallback']=_0xff7604||(()=>{}),this['onDisconnectedCallback']=_0x3caf45||(()=>{}),this['isConnected']=!0x1,this['transport']='ws'===_0x231977?new websocketTransport_js_1['WebsocketTransport'](_0x5da024):new httpTransport_js_1['HttpTransport']();}async['connect'](){const _0x195d02=new httpTransport_js_1['HttpTransport']({'url':'https://link.dchatter.com/api/v1/sdk/auth'}),_0x3bbde3=await _0x195d02['send']({'appId':this['appId'],'appSecret':this['secret'],'userID':this['userId']});if(0xc8!==_0x3bbde3['_responseCode'])throw new Error('Authentication\x20Failed.');this['authToken']=_0x3bbde3['_responseData'],await this['transport']['connect'](this['url']);const _0x32eec1={'type':'text','code':0x65,'appId':this['appId'],'sender':(0x0,id_js_1['prefixId'])(this['appId'],this['userId']),'timestamp':Date['now'](),'token':this['authToken']},_0x5c634e=(0x0,buffer_js_1['toUint8'])(JSON['stringify']({'token':this['authToken']})),_0x3ae51e=(0x0,frame_js_1['framePacket'])(_0x32eec1,_0x5c634e);this['transport']['sendBinary'](_0x3ae51e);let _0x4cc45a=!0x1;this['transport']['on']('message',_0xa7d26c=>{try{const {metadata:_0x38fd1a,data:_0x2f36c1}=_0xa7d26c;if(!_0x4cc45a&&'102'===_0x38fd1a['packet']['code']&&_0x38fd1a['packet']['sender']['includes']((0x0,id_js_1['prefixId'])(this['appId'],this['userId'])))return _0x4cc45a=!0x0,this['isConnected']=!0x0,void this['onConnectedCallback']();_0x4cc45a&&this['onMessageCallback']({'metadata':{'sender':_0x38fd1a['packet']['sender'],'timestamp':_0x38fd1a['packet']['timestamp']},'payload':new payload_js_1['Payload'](_0x2f36c1)});}catch(_0x110a94){console['error']('Packet\x20error:',_0x110a94);}}),this['transport']['on']('close',({code:_0x178256,reason:_0x59b09f})=>{this['isConnected']&&(this['isConnected']=!0x1,this['onDisconnectedCallback']({'code':_0x178256,'reason':_0x59b09f||'Disconnected'}));}),this['transport']['on']('error',_0x4dafd0=>{this['isConnected']=!0x1,this['onDisconnectedCallback']({'code':0x1f4,'reason':(null==_0x4dafd0?void 0x0:_0x4dafd0['message'])||'Transport\x20error'});});}['send']({senderId:_0x242272,receiverId:_0x2dc996,receiverIds:_0xb628fb,data:_0x26ecfd}){if(!_0x242272)throw new Error('senderId\x20required');if(!_0x2dc996&&!_0xb628fb)throw new Error('receiverId\x20or\x20receiverIds\x20required');const _0x1b7dcb=null!=_0xb628fb?_0xb628fb:[_0x2dc996],_0x22c5e0={'type':'text','code':0xc8,'appId':this['appId'],'sender':(0x0,id_js_1['prefixId'])(this['appId'],_0x242272),'receivers':_0x1b7dcb['map'](_0x268332=>(0x0,id_js_1['prefixId'])(this['appId'],_0x268332)),'timestamp':Date['now'](),'token':this['authToken']},_0x40f32c=(0x0,buffer_js_1['toUint8'])(JSON['stringify'](_0x26ecfd)),_0x20efaf=(0x0,frame_js_1['framePacket'])(_0x22c5e0,_0x40f32c);this['transport']['sendBinary'](_0x20efaf);}['sendBinary']({senderId:_0x5290ee,receiverIds:_0x3c078c,buffer:_0xa510f9,type:_0x28f532='binary'}){if(!_0x5290ee)throw new Error('senderId\x20required');if(!_0xa510f9)throw new Error('buffer\x20is\x20required');const _0x5b89fe={'type':_0x28f532,'code':0xca,'appId':this['appId'],'sender':(0x0,id_js_1['prefixId'])(this['appId'],_0x5290ee),'receivers':_0x3c078c['map'](_0xd80805=>(0x0,id_js_1['prefixId'])(this['appId'],_0xd80805)),'timestamp':Date['now'](),'token':this['authToken']},_0x9976e6=(0x0,frame_js_1['framePacket'])(_0x5b89fe,_0xa510f9);this['transport']['sendBinary'](_0x9976e6);}async['sendWithOpenAI']({senderId:_0x615445,message:_0x4492df,openaiApiKey:_0x22f9dd,model:_0xaf43df,baseUrl:_0x1d35e3}){if(!_0x615445)throw new Error('senderId\x20is\x20required');if(!_0x4492df)throw new Error('message\x20is\x20required');if(!_0x22f9dd)throw new Error('openaiApiKey\x20is\x20required');const {content:_0x3a5c0c}=await(0x0,openai_js_1['chatStream'])({'apiKey':_0x22f9dd,'model':_0xaf43df,'messages':_0x4492df,'baseUrl':_0x1d35e3}),_0x38e27c={'type':'openai','content':_0x3a5c0c,'ts':Date['now']()};return this['onMessageCallback']({'metadata':{'sender':(0x0,id_js_1['prefixId'])(this['appId'],_0x615445),'timestamp':Date['now']()},'payload':new payload_js_1['Payload']((0x0,buffer_js_1['toUint8'])(JSON['stringify'](_0x38e27c)))}),{'content':_0x3a5c0c};}}exports['DNotifier']=DNotifier;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
'use strict';Object['defineProperty'](exports,'__esModule',{'value':!0x0}),exports['chat']=chat,exports['chatStream']=chatStream;const DEFAULT_BASE_URL='https://api.openai.com',DEFAULT_MODEL='gpt-4o-mini';function normalizeMessages(_0x509a25){if('string'==typeof _0x509a25)return[{'role':'user','content':_0x509a25}];if(Array['isArray'](_0x509a25)&&_0x509a25['length']>0x0)return _0x509a25['map'](_0x3add00=>({'role':_0x3add00['role']||'user','content':'string'==typeof _0x3add00['content']?_0x3add00['content']:String(_0x3add00['content'])}));throw new Error('message\x20must\x20be\x20a\x20non-empty\x20string\x20or\x20array\x20of\x20{\x20role,\x20content\x20}');}async function chat(_0x4655ef){var _0x45b83b,_0x162329,_0x95cbb6,_0x2efd92,_0x40e584,_0x5e7313;const {apiKey:_0x5bd896,model:_0x3d5330=DEFAULT_MODEL,messages:_0x943596,baseUrl:_0x4614cd=DEFAULT_BASE_URL}=_0x4655ef;if(!_0x5bd896||!_0x943596)throw new Error('openai.chat:\x20apiKey\x20and\x20messages\x20are\x20required');const _0x421cd2=_0x4614cd['replace'](/\/$/,'')+'/v1/chat/completions',_0x5d50fe={'model':_0x3d5330,'messages':normalizeMessages(_0x943596),'stream':!0x1},_0x461f25=await fetch(_0x421cd2,{'method':'POST','headers':{'Content-Type':'application/json','Authorization':'Bearer\x20'+_0x5bd896},'body':JSON['stringify'](_0x5d50fe)}),_0x57df6e=await _0x461f25['json']();if(!_0x461f25['ok']){const _0x30c4ee=new Error((null===(_0x45b83b=null==_0x57df6e?void 0x0:_0x57df6e['error'])||void 0x0===_0x45b83b?void 0x0:_0x45b83b['message'])||'OpenAI\x20API\x20error:\x20'+_0x461f25['status']);throw _0x30c4ee['status']=_0x461f25['status'],_0x30c4ee['code']=null===(_0x162329=null==_0x57df6e?void 0x0:_0x57df6e['error'])||void 0x0===_0x162329?void 0x0:_0x162329['code'],_0x30c4ee;}return{'content':null!==(_0x5e7313=null===(_0x40e584=null===(_0x2efd92=null===(_0x95cbb6=null==_0x57df6e?void 0x0:_0x57df6e['choices'])||void 0x0===_0x95cbb6?void 0x0:_0x95cbb6[0x0])||void 0x0===_0x2efd92?void 0x0:_0x2efd92['message'])||void 0x0===_0x40e584?void 0x0:_0x40e584['content'])&&void 0x0!==_0x5e7313?_0x5e7313:'','usage':null==_0x57df6e?void 0x0:_0x57df6e['usage'],'raw':_0x57df6e};}async function chatStream(_0x1e1097){var _0x315aad,_0x2087ec,_0x15b731,_0x1a0eec,_0x263c4c;const {apiKey:_0x48205f,model:_0x5b1896=DEFAULT_MODEL,messages:_0x3bd65b,baseUrl:_0xbfcf32=DEFAULT_BASE_URL,onChunk:_0x49d45f}=_0x1e1097;if(!_0x48205f||!_0x3bd65b)throw new Error('openai.chatStream:\x20apiKey\x20and\x20messages\x20are\x20required');const _0x2c42d7=_0xbfcf32['replace'](/\/$/,'')+'/v1/chat/completions',_0x49dae4={'model':_0x5b1896,'messages':normalizeMessages(_0x3bd65b),'stream':!0x0},_0x55f4d7=await fetch(_0x2c42d7,{'method':'POST','headers':{'Content-Type':'application/json','Authorization':'Bearer\x20'+_0x48205f},'body':JSON['stringify'](_0x49dae4)});if(!_0x55f4d7['ok']){const _0x363a12=await _0x55f4d7['json']()['catch'](()=>({})),_0x2f5f90=new Error((null===(_0x315aad=null==_0x363a12?void 0x0:_0x363a12['error'])||void 0x0===_0x315aad?void 0x0:_0x315aad['message'])||'OpenAI\x20API\x20error:\x20'+_0x55f4d7['status']);throw _0x2f5f90['status']=_0x55f4d7['status'],_0x2f5f90['code']=null===(_0x2087ec=null==_0x363a12?void 0x0:_0x363a12['error'])||void 0x0===_0x2087ec?void 0x0:_0x2087ec['code'],_0x2f5f90;}const _0x33fbbf=_0x55f4d7['body']['getReader'](),_0xc57bee=new TextDecoder();let _0x5aafa1='',_0x2b4f73='';for(;;){const {done:_0x13830f,value:_0x41ed36}=await _0x33fbbf['read']();if(_0x13830f)break;_0x2b4f73+=_0xc57bee['decode'](_0x41ed36,{'stream':!0x0});const _0x1d0cd1=_0x2b4f73['split']('\x0a');_0x2b4f73=_0x1d0cd1['pop']()||'';for(const _0x3a206e of _0x1d0cd1){const _0x2ad8cc=_0x3a206e['trim']();if(''!==_0x2ad8cc&&'data:\x20[DONE]'!==_0x2ad8cc&&_0x2ad8cc['startsWith']('data:\x20'))try{const _0x27a5b1=JSON['parse'](_0x2ad8cc['slice'](0x6)),_0x492ea7=null===(_0x263c4c=null===(_0x1a0eec=null===(_0x15b731=null==_0x27a5b1?void 0x0:_0x27a5b1['choices'])||void 0x0===_0x15b731?void 0x0:_0x15b731[0x0])||void 0x0===_0x1a0eec?void 0x0:_0x1a0eec['delta'])||void 0x0===_0x263c4c?void 0x0:_0x263c4c['content'];'string'==typeof _0x492ea7&&(_0x5aafa1+=_0x492ea7,_0x49d45f&&_0x49d45f(_0x492ea7));}catch(_0x778ba0){}}}return{'content':_0x5aafa1};}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
'use strict';Object['defineProperty'](exports,'__esModule',{'value':!0x0}),exports['HttpTransport']=void 0x0;class HttpTransport{constructor({url:_0x354268}){this['url']=_0x354268;}async['send'](_0x3015fe){const _0x13cee9=await fetch(''+this['url'],{'method':'POST','headers':{'Content-Type':'application/json'},'body':JSON['stringify'](_0x3015fe)});if(!_0x13cee9['ok']){const _0xaa55dd=await _0x13cee9['text']();throw new Error('DNotifier\x20HTTP\x20error:\x20'+_0xaa55dd);}return await _0x13cee9['json']();}['sendBinary'](){throw new Error('Binary\x20is\x20not\x20supported\x20over\x20HTTP\x20yet');}}exports['HttpTransport']=HttpTransport;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
'use strict';Object['defineProperty'](exports,'__esModule',{'value':!0x0}),exports['WebsocketTransport']=void 0x0;const events_1=require('events'),frame_js_1=require('../utils/frame.js');class WebsocketTransport extends events_1['default']{constructor(_0xaf0979=null){if(super(),this['socket']=null,this['WebSocketImpl']=_0xaf0979||('undefined'!=typeof window?window['WebSocket']:null),!this['WebSocketImpl'])throw new Error('No\x20WebSocket\x20implementation\x20provided');}['connect'](_0x469566){return new Promise((_0x581715,_0x8ee448)=>{this['socket']=new this['WebSocketImpl'](_0x469566),'undefined'!=typeof window&&(this['socket']['binaryType']='arrayBuffer'),this['_on']('open',()=>_0x581715(!0x0)),this['_on']('error',_0x18e01a=>{console['error']('WS\x20error',_0x18e01a),_0x8ee448(_0x18e01a);}),this['_on']('close',_0x29948e=>{const _0x20633f=null==_0x29948e?void 0x0:_0x29948e['code'],_0x2f281e=null==_0x29948e?void 0x0:_0x29948e['reason'];this['emit']('close',{'code':_0x20633f,'reason':_0x2f281e});}),this['_on']('message',async(_0x355caa,_0x2e1b62)=>{var _0x8b18f0,_0x9111f5=null!==(_0x8b18f0=null==_0x355caa?void 0x0:_0x355caa['data'])&&void 0x0!==_0x8b18f0?_0x8b18f0:_0x355caa;'undefined'!=typeof Blob&&_0x9111f5 instanceof Blob&&(_0x9111f5=await _0x9111f5['arrayBuffer']());const _0x2a7417=(0x0,frame_js_1['decodePacket'])(_0x9111f5);_0x2a7417&&this['emit']('message',_0x2a7417,_0x2e1b62);});});}['_on'](_0x394884,_0x554de1){this['socket']['on']?this['socket']['on'](_0x394884,_0x554de1):this['socket']['on'+_0x394884]=_0x554de1;}['send'](_0x22314a){if(!this['isOpen']())throw new Error('WebSocket\x20not\x20connected');this['socket']['send'](_0x22314a);}['sendBinary'](_0x4c19a3){if(!this['isOpen']())throw new Error('WebSocket\x20not\x20connected');this['socket']['send'](_0x4c19a3);}['isOpen'](){return this['socket']&&this['socket']['readyState']===this['WebSocketImpl']['OPEN'];}['close'](){var _0x2c8271;null===(_0x2c8271=this['socket'])||void 0x0===_0x2c8271||_0x2c8271['close']();}}exports['WebsocketTransport']=WebsocketTransport;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
'use strict';function toUint8(_0x9f2866){return'undefined'!=typeof Buffer?Buffer['from'](_0x9f2866,'utf8'):new TextEncoder()['encode'](_0x9f2866);}Object['defineProperty'](exports,'__esModule',{'value':!0x0}),exports['toUint8']=toUint8;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
'use strict';function framePacket(_0xfbbea9,_0x552a2b){const _0x591d3c=Buffer['from'](JSON['stringify'](_0xfbbea9)),_0x140f96=Buffer['isBuffer'](_0x552a2b)?_0x552a2b:Buffer['from'](_0x552a2b),_0x379029=Buffer['alloc'](0x4+_0x591d3c['length']+0x4+_0x140f96['length']);let _0x318d22=0x0;return _0x379029['writeUInt32BE'](_0x591d3c['length'],_0x318d22),_0x318d22+=0x4,_0x591d3c['copy'](_0x379029,_0x318d22),_0x318d22+=_0x591d3c['length'],_0x379029['writeUInt32BE'](_0x140f96['length'],_0x318d22),_0x318d22+=0x4,_0x140f96['copy'](_0x379029,_0x318d22),_0x379029;}Object['defineProperty'](exports,'__esModule',{'value':!0x0}),exports['framePacket']=framePacket,exports['decodePacket']=decodePacket;let internalBuffer=Buffer['alloc'](0x0);function decodePacket(_0x5a4457){try{Buffer['isBuffer'](_0x5a4457)||(_0x5a4457=Buffer['from'](_0x5a4457)),internalBuffer=Buffer['concat']([internalBuffer,_0x5a4457]);let _0x595e3e=0x0;if(internalBuffer['length']<0x4)return null;const _0x5e7ff8=internalBuffer['readUInt32BE'](_0x595e3e);if(_0x595e3e+=0x4,internalBuffer['length']<_0x595e3e+_0x5e7ff8)return null;const _0x583eec=internalBuffer['slice'](_0x595e3e,_0x595e3e+_0x5e7ff8),_0xbd87b0=JSON['parse'](_0x583eec['toString']());if(_0x595e3e+=_0x5e7ff8,internalBuffer['length']<_0x595e3e+0x4)return null;const _0x7d7b0e=internalBuffer['readUInt32BE'](_0x595e3e);if(_0x595e3e+=0x4,internalBuffer['length']<_0x595e3e+_0x7d7b0e)return null;const _0x57e4ec=internalBuffer['slice'](_0x595e3e,_0x595e3e+_0x7d7b0e);_0x595e3e+=_0x7d7b0e,internalBuffer=internalBuffer['slice'](_0x595e3e);let _0x57ed48=_0x57e4ec;if('text'===_0xbd87b0['type'])try{_0x57ed48=JSON['parse'](_0x57e4ec['toString']('utf8'));}catch{_0x57ed48=_0x57e4ec;}return{'metadata':_0xbd87b0,'data':_0x57ed48};}catch(_0x4e05f8){return console['error']('decodePacket\x20error:',_0x4e05f8),null;}}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
'use strict';Object['defineProperty'](exports,'__esModule',{'value':!0x0}),exports['prefixId']=void 0x0;const prefixId=(_0x180c25,_0x592714)=>_0x592714['includes'](':')?_0x592714:_0x180c25+':'+_0x592714;exports['prefixId']=prefixId;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
'use strict';Object['defineProperty'](exports,'__esModule',{'value':!0x0}),exports['Payload']=void 0x0;class Payload{constructor(_0x156f0c){this['buffer']=_0x156f0c;}['raw'](){return this['buffer'];}['toString'](_0x138181='utf8'){return this['buffer']['toString'](_0x138181);}['toJSON'](_0x40e2cc='utf8'){try{return JSON['parse'](this['buffer']['toString'](_0x40e2cc));}catch(_0x46206e){return null;}}['toBase64'](){return this['buffer']['toString']('base64');}}exports['Payload']=Payload;
|
|
@@ -0,0 +1,488 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __create = Object.create;
|
|
3
|
+
var __defProp = Object.defineProperty;
|
|
4
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
5
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
6
|
+
var __getProtoOf = Object.getPrototypeOf;
|
|
7
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
8
|
+
var __export = (target, all) => {
|
|
9
|
+
for (var name in all)
|
|
10
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
11
|
+
};
|
|
12
|
+
var __copyProps = (to, from, except, desc) => {
|
|
13
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
14
|
+
for (let key of __getOwnPropNames(from))
|
|
15
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
16
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
17
|
+
}
|
|
18
|
+
return to;
|
|
19
|
+
};
|
|
20
|
+
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
|
|
21
|
+
// If the importer is in node compatibility mode or this is not an ESM
|
|
22
|
+
// file that has been converted to a CommonJS file using a Babel-
|
|
23
|
+
// compatible transform (i.e. "__esModule" has not been set), then set
|
|
24
|
+
// "default" to the CommonJS "module.exports" for node compatibility.
|
|
25
|
+
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
|
|
26
|
+
mod
|
|
27
|
+
));
|
|
28
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
29
|
+
|
|
30
|
+
// src/dnotifier.js
|
|
31
|
+
var dnotifier_exports = {};
|
|
32
|
+
__export(dnotifier_exports, {
|
|
33
|
+
DNotifier: () => DNotifier
|
|
34
|
+
});
|
|
35
|
+
module.exports = __toCommonJS(dnotifier_exports);
|
|
36
|
+
|
|
37
|
+
// src/transport/httpTransport.js
|
|
38
|
+
var HttpTransport = class {
|
|
39
|
+
// constructor({ url, appId, secret, userId }) {
|
|
40
|
+
// this.url = url;
|
|
41
|
+
// this.appId = appId;
|
|
42
|
+
// this.appSecret = secret;
|
|
43
|
+
// this.userId = userId;
|
|
44
|
+
// }
|
|
45
|
+
constructor({ url }) {
|
|
46
|
+
this.url = url;
|
|
47
|
+
}
|
|
48
|
+
async send(payload) {
|
|
49
|
+
const res = await fetch(`${this.url}`, {
|
|
50
|
+
method: "POST",
|
|
51
|
+
headers: {
|
|
52
|
+
"Content-Type": "application/json"
|
|
53
|
+
},
|
|
54
|
+
body: JSON.stringify(payload)
|
|
55
|
+
});
|
|
56
|
+
if (!res.ok) {
|
|
57
|
+
const text = await res.text();
|
|
58
|
+
throw new Error(`DNotifier HTTP error: ${text}`);
|
|
59
|
+
}
|
|
60
|
+
return await res.json();
|
|
61
|
+
}
|
|
62
|
+
sendBinary() {
|
|
63
|
+
throw new Error("Binary is not supported over HTTP yet");
|
|
64
|
+
}
|
|
65
|
+
};
|
|
66
|
+
|
|
67
|
+
// src/transport/websocketTransport.js
|
|
68
|
+
var import_events = __toESM(require("events"), 1);
|
|
69
|
+
|
|
70
|
+
// src/utils/frame.js
|
|
71
|
+
function framePacket(metadata, dataBuffer) {
|
|
72
|
+
const metaBuf = Buffer.from(JSON.stringify(metadata));
|
|
73
|
+
const dataBuf = Buffer.isBuffer(dataBuffer) ? dataBuffer : Buffer.from(dataBuffer);
|
|
74
|
+
const frame = Buffer.alloc(
|
|
75
|
+
4 + metaBuf.length + 4 + dataBuf.length
|
|
76
|
+
);
|
|
77
|
+
let offset = 0;
|
|
78
|
+
frame.writeUInt32BE(metaBuf.length, offset);
|
|
79
|
+
offset += 4;
|
|
80
|
+
metaBuf.copy(frame, offset);
|
|
81
|
+
offset += metaBuf.length;
|
|
82
|
+
frame.writeUInt32BE(dataBuf.length, offset);
|
|
83
|
+
offset += 4;
|
|
84
|
+
dataBuf.copy(frame, offset);
|
|
85
|
+
return frame;
|
|
86
|
+
}
|
|
87
|
+
var internalBuffer = Buffer.alloc(0);
|
|
88
|
+
function decodePacket(chunk) {
|
|
89
|
+
try {
|
|
90
|
+
if (!Buffer.isBuffer(chunk)) {
|
|
91
|
+
chunk = Buffer.from(chunk);
|
|
92
|
+
}
|
|
93
|
+
internalBuffer = Buffer.concat([internalBuffer, chunk]);
|
|
94
|
+
let offset = 0;
|
|
95
|
+
if (internalBuffer.length < 4) {
|
|
96
|
+
return null;
|
|
97
|
+
}
|
|
98
|
+
const metaLength = internalBuffer.readUInt32BE(offset);
|
|
99
|
+
offset += 4;
|
|
100
|
+
if (internalBuffer.length < offset + metaLength) {
|
|
101
|
+
return null;
|
|
102
|
+
}
|
|
103
|
+
const metaBuf = internalBuffer.slice(offset, offset + metaLength);
|
|
104
|
+
const metadata = JSON.parse(metaBuf.toString());
|
|
105
|
+
offset += metaLength;
|
|
106
|
+
if (internalBuffer.length < offset + 4) {
|
|
107
|
+
return null;
|
|
108
|
+
}
|
|
109
|
+
const dataLength = internalBuffer.readUInt32BE(offset);
|
|
110
|
+
offset += 4;
|
|
111
|
+
if (internalBuffer.length < offset + dataLength) {
|
|
112
|
+
return null;
|
|
113
|
+
}
|
|
114
|
+
const dataBuf = internalBuffer.slice(offset, offset + dataLength);
|
|
115
|
+
offset += dataLength;
|
|
116
|
+
internalBuffer = internalBuffer.slice(offset);
|
|
117
|
+
let data = dataBuf;
|
|
118
|
+
if (metadata.type === "text") {
|
|
119
|
+
try {
|
|
120
|
+
data = JSON.parse(dataBuf.toString("utf8"));
|
|
121
|
+
} catch {
|
|
122
|
+
data = dataBuf;
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
return { metadata, data };
|
|
126
|
+
} catch (err) {
|
|
127
|
+
console.error("decodePacket error:", err);
|
|
128
|
+
return null;
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
// src/transport/websocketTransport.js
|
|
133
|
+
var WebsocketTransport = class extends import_events.default {
|
|
134
|
+
constructor(WebSocketImpl = null) {
|
|
135
|
+
super();
|
|
136
|
+
this.socket = null;
|
|
137
|
+
this.WebSocketImpl = WebSocketImpl || (typeof window !== "undefined" ? window.WebSocket : null);
|
|
138
|
+
if (!this.WebSocketImpl) {
|
|
139
|
+
throw new Error("No WebSocket implementation provided");
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
connect(url) {
|
|
143
|
+
return new Promise((resolve, reject) => {
|
|
144
|
+
this.socket = new this.WebSocketImpl(url);
|
|
145
|
+
if (typeof window !== "undefined") {
|
|
146
|
+
this.socket.binaryType = "arrayBuffer";
|
|
147
|
+
}
|
|
148
|
+
this._on("open", () => resolve(true));
|
|
149
|
+
this._on("error", (err) => {
|
|
150
|
+
console.error("WS error", err);
|
|
151
|
+
reject(err);
|
|
152
|
+
});
|
|
153
|
+
this._on("close", (event) => {
|
|
154
|
+
const code = event?.code;
|
|
155
|
+
const reason = event?.reason;
|
|
156
|
+
this.emit("close", { code, reason });
|
|
157
|
+
});
|
|
158
|
+
this._on("message", async (event, isBinary) => {
|
|
159
|
+
var data = event?.data ?? event;
|
|
160
|
+
if (typeof Blob !== "undefined" && data instanceof Blob) {
|
|
161
|
+
data = await data.arrayBuffer();
|
|
162
|
+
}
|
|
163
|
+
const chunk = decodePacket(data);
|
|
164
|
+
if (chunk) {
|
|
165
|
+
this.emit("message", chunk, isBinary);
|
|
166
|
+
}
|
|
167
|
+
});
|
|
168
|
+
});
|
|
169
|
+
}
|
|
170
|
+
_on(event, handler) {
|
|
171
|
+
if (this.socket.on) {
|
|
172
|
+
this.socket.on(event, handler);
|
|
173
|
+
} else {
|
|
174
|
+
this.socket[`on${event}`] = handler;
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
send(data) {
|
|
178
|
+
if (!this.isOpen()) {
|
|
179
|
+
throw new Error("WebSocket not connected");
|
|
180
|
+
}
|
|
181
|
+
this.socket.send(data);
|
|
182
|
+
}
|
|
183
|
+
sendBinary(buffer) {
|
|
184
|
+
if (!this.isOpen()) {
|
|
185
|
+
throw new Error("WebSocket not connected");
|
|
186
|
+
}
|
|
187
|
+
this.socket.send(buffer);
|
|
188
|
+
}
|
|
189
|
+
isOpen() {
|
|
190
|
+
return this.socket && this.socket.readyState === this.WebSocketImpl.OPEN;
|
|
191
|
+
}
|
|
192
|
+
close() {
|
|
193
|
+
this.socket?.close();
|
|
194
|
+
}
|
|
195
|
+
};
|
|
196
|
+
|
|
197
|
+
// src/utils/id.js
|
|
198
|
+
var prefixId = (appId, id) => {
|
|
199
|
+
if (id.includes(":")) return id;
|
|
200
|
+
return `${appId}:${id}`;
|
|
201
|
+
};
|
|
202
|
+
|
|
203
|
+
// src/utils/payload.js
|
|
204
|
+
var Payload = class {
|
|
205
|
+
constructor(buffer) {
|
|
206
|
+
this.buffer = buffer;
|
|
207
|
+
}
|
|
208
|
+
/** Raw Buffer */
|
|
209
|
+
raw() {
|
|
210
|
+
return this.buffer;
|
|
211
|
+
}
|
|
212
|
+
/** Convert buffer to string */
|
|
213
|
+
toString(encoding = "utf8") {
|
|
214
|
+
return this.buffer.toString(encoding);
|
|
215
|
+
}
|
|
216
|
+
/** Safely parse JSON */
|
|
217
|
+
toJSON(encoding = "utf8") {
|
|
218
|
+
try {
|
|
219
|
+
return JSON.parse(this.buffer.toString(encoding));
|
|
220
|
+
} catch (err) {
|
|
221
|
+
return null;
|
|
222
|
+
}
|
|
223
|
+
}
|
|
224
|
+
/** Base64 if needed */
|
|
225
|
+
toBase64() {
|
|
226
|
+
return this.buffer.toString("base64");
|
|
227
|
+
}
|
|
228
|
+
};
|
|
229
|
+
|
|
230
|
+
// src/utils/buffer.js
|
|
231
|
+
function toUint8(data) {
|
|
232
|
+
if (typeof Buffer !== "undefined") {
|
|
233
|
+
return Buffer.from(data, "utf8");
|
|
234
|
+
}
|
|
235
|
+
return new TextEncoder().encode(data);
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
// src/providers/openai.js
|
|
239
|
+
var DEFAULT_BASE_URL = "https://api.openai.com";
|
|
240
|
+
var DEFAULT_MODEL = "gpt-4o-mini";
|
|
241
|
+
function normalizeMessages(message) {
|
|
242
|
+
if (typeof message === "string") {
|
|
243
|
+
return [{ role: "user", content: message }];
|
|
244
|
+
}
|
|
245
|
+
if (Array.isArray(message) && message.length > 0) {
|
|
246
|
+
return message.map((m) => ({
|
|
247
|
+
role: m.role || "user",
|
|
248
|
+
content: typeof m.content === "string" ? m.content : String(m.content)
|
|
249
|
+
}));
|
|
250
|
+
}
|
|
251
|
+
throw new Error("message must be a non-empty string or array of { role, content }");
|
|
252
|
+
}
|
|
253
|
+
async function chatStream(options) {
|
|
254
|
+
const {
|
|
255
|
+
apiKey,
|
|
256
|
+
model = DEFAULT_MODEL,
|
|
257
|
+
messages,
|
|
258
|
+
baseUrl = DEFAULT_BASE_URL,
|
|
259
|
+
onChunk
|
|
260
|
+
} = options;
|
|
261
|
+
if (!apiKey || !messages) {
|
|
262
|
+
throw new Error("openai.chatStream: apiKey and messages are required");
|
|
263
|
+
}
|
|
264
|
+
const url = `${baseUrl.replace(/\/$/, "")}/v1/chat/completions`;
|
|
265
|
+
const body = {
|
|
266
|
+
model,
|
|
267
|
+
messages: normalizeMessages(messages),
|
|
268
|
+
stream: true
|
|
269
|
+
};
|
|
270
|
+
const res = await fetch(url, {
|
|
271
|
+
method: "POST",
|
|
272
|
+
headers: {
|
|
273
|
+
"Content-Type": "application/json",
|
|
274
|
+
Authorization: `Bearer ${apiKey}`
|
|
275
|
+
},
|
|
276
|
+
body: JSON.stringify(body)
|
|
277
|
+
});
|
|
278
|
+
if (!res.ok) {
|
|
279
|
+
const raw = await res.json().catch(() => ({}));
|
|
280
|
+
const err = new Error(raw?.error?.message || `OpenAI API error: ${res.status}`);
|
|
281
|
+
err.status = res.status;
|
|
282
|
+
err.code = raw?.error?.code;
|
|
283
|
+
throw err;
|
|
284
|
+
}
|
|
285
|
+
const reader = res.body.getReader();
|
|
286
|
+
const decoder = new TextDecoder();
|
|
287
|
+
let content = "";
|
|
288
|
+
let buffer = "";
|
|
289
|
+
while (true) {
|
|
290
|
+
const { done, value } = await reader.read();
|
|
291
|
+
if (done) break;
|
|
292
|
+
buffer += decoder.decode(value, { stream: true });
|
|
293
|
+
const lines = buffer.split("\n");
|
|
294
|
+
buffer = lines.pop() || "";
|
|
295
|
+
for (const line of lines) {
|
|
296
|
+
const trimmed = line.trim();
|
|
297
|
+
if (trimmed === "" || trimmed === "data: [DONE]") continue;
|
|
298
|
+
if (!trimmed.startsWith("data: ")) continue;
|
|
299
|
+
try {
|
|
300
|
+
const json = JSON.parse(trimmed.slice(6));
|
|
301
|
+
const delta = json?.choices?.[0]?.delta?.content;
|
|
302
|
+
if (typeof delta === "string") {
|
|
303
|
+
content += delta;
|
|
304
|
+
if (onChunk) onChunk(delta);
|
|
305
|
+
}
|
|
306
|
+
} catch (_) {
|
|
307
|
+
}
|
|
308
|
+
}
|
|
309
|
+
}
|
|
310
|
+
return { content };
|
|
311
|
+
}
|
|
312
|
+
|
|
313
|
+
// src/dnotifier.js
|
|
314
|
+
var DNotifier = class {
|
|
315
|
+
constructor({
|
|
316
|
+
appId,
|
|
317
|
+
secret,
|
|
318
|
+
transport,
|
|
319
|
+
userId,
|
|
320
|
+
onConnected,
|
|
321
|
+
onMessage,
|
|
322
|
+
onDisconnected,
|
|
323
|
+
WebSocketImpl
|
|
324
|
+
// 👈 OPTIONAL injection
|
|
325
|
+
}) {
|
|
326
|
+
if (!appId || !secret || !transport || !userId) {
|
|
327
|
+
throw new Error("appId, secret, transport, and userId are required");
|
|
328
|
+
}
|
|
329
|
+
this.appId = appId;
|
|
330
|
+
this.secret = secret;
|
|
331
|
+
this.userId = userId;
|
|
332
|
+
this.url = "wss://link.dchatter.com/ws";
|
|
333
|
+
this.onConnectedCallback = onConnected || (() => {
|
|
334
|
+
});
|
|
335
|
+
this.onMessageCallback = onMessage || (() => {
|
|
336
|
+
});
|
|
337
|
+
this.onDisconnectedCallback = onDisconnected || (() => {
|
|
338
|
+
});
|
|
339
|
+
this.isConnected = false;
|
|
340
|
+
this.transport = transport === "ws" ? new WebsocketTransport(WebSocketImpl) : new HttpTransport();
|
|
341
|
+
}
|
|
342
|
+
async connect() {
|
|
343
|
+
const authServer = new HttpTransport({
|
|
344
|
+
url: "https://link.dchatter.com/api/v1/sdk/auth"
|
|
345
|
+
});
|
|
346
|
+
const res = await authServer.send({
|
|
347
|
+
appId: this.appId,
|
|
348
|
+
appSecret: this.secret,
|
|
349
|
+
userID: this.userId
|
|
350
|
+
});
|
|
351
|
+
if (res._responseCode !== 200) {
|
|
352
|
+
throw new Error("Authentication Failed.");
|
|
353
|
+
}
|
|
354
|
+
this.authToken = res._responseData;
|
|
355
|
+
await this.transport.connect(this.url);
|
|
356
|
+
const metadata = {
|
|
357
|
+
type: "text",
|
|
358
|
+
code: 101,
|
|
359
|
+
appId: this.appId,
|
|
360
|
+
sender: prefixId(this.appId, this.userId),
|
|
361
|
+
timestamp: Date.now(),
|
|
362
|
+
token: this.authToken
|
|
363
|
+
};
|
|
364
|
+
const payloadBuffer = toUint8(
|
|
365
|
+
JSON.stringify({ token: this.authToken })
|
|
366
|
+
);
|
|
367
|
+
const frame = framePacket(metadata, payloadBuffer);
|
|
368
|
+
this.transport.sendBinary(frame);
|
|
369
|
+
let handshakeDone = false;
|
|
370
|
+
this.transport.on("message", (chunk) => {
|
|
371
|
+
try {
|
|
372
|
+
const { metadata: metadata2, data } = chunk;
|
|
373
|
+
if (!handshakeDone && metadata2.packet.code === "102" && metadata2.packet.sender.includes(
|
|
374
|
+
prefixId(this.appId, this.userId)
|
|
375
|
+
)) {
|
|
376
|
+
handshakeDone = true;
|
|
377
|
+
this.isConnected = true;
|
|
378
|
+
this.onConnectedCallback();
|
|
379
|
+
return;
|
|
380
|
+
}
|
|
381
|
+
if (handshakeDone) {
|
|
382
|
+
this.onMessageCallback({
|
|
383
|
+
metadata: {
|
|
384
|
+
sender: metadata2.packet.sender,
|
|
385
|
+
timestamp: metadata2.packet.timestamp
|
|
386
|
+
},
|
|
387
|
+
payload: new Payload(data)
|
|
388
|
+
});
|
|
389
|
+
}
|
|
390
|
+
} catch (err) {
|
|
391
|
+
console.error("Packet error:", err);
|
|
392
|
+
}
|
|
393
|
+
});
|
|
394
|
+
this.transport.on("close", ({ code, reason }) => {
|
|
395
|
+
if (this.isConnected) {
|
|
396
|
+
this.isConnected = false;
|
|
397
|
+
this.onDisconnectedCallback({
|
|
398
|
+
code,
|
|
399
|
+
reason: reason || "Disconnected"
|
|
400
|
+
});
|
|
401
|
+
}
|
|
402
|
+
});
|
|
403
|
+
this.transport.on("error", (err) => {
|
|
404
|
+
this.isConnected = false;
|
|
405
|
+
this.onDisconnectedCallback({
|
|
406
|
+
code: 500,
|
|
407
|
+
reason: err?.message || "Transport error"
|
|
408
|
+
});
|
|
409
|
+
});
|
|
410
|
+
}
|
|
411
|
+
send({ senderId, receiverId, receiverIds, data }) {
|
|
412
|
+
if (!senderId) throw new Error("senderId required");
|
|
413
|
+
if (!receiverId && !receiverIds)
|
|
414
|
+
throw new Error("receiverId or receiverIds required");
|
|
415
|
+
const receivers = receiverIds ?? [receiverId];
|
|
416
|
+
const metadata = {
|
|
417
|
+
type: "text",
|
|
418
|
+
code: 200,
|
|
419
|
+
appId: this.appId,
|
|
420
|
+
sender: prefixId(this.appId, senderId),
|
|
421
|
+
receivers: receivers.map(
|
|
422
|
+
(id) => prefixId(this.appId, id)
|
|
423
|
+
),
|
|
424
|
+
timestamp: Date.now(),
|
|
425
|
+
token: this.authToken
|
|
426
|
+
};
|
|
427
|
+
const payloadBuffer = toUint8(JSON.stringify(data));
|
|
428
|
+
const frame = framePacket(metadata, payloadBuffer);
|
|
429
|
+
this.transport.sendBinary(frame);
|
|
430
|
+
}
|
|
431
|
+
sendBinary({ senderId, receiverIds, buffer, type = "binary" }) {
|
|
432
|
+
if (!senderId) throw new Error("senderId required");
|
|
433
|
+
if (!buffer) throw new Error("buffer is required");
|
|
434
|
+
const metadata = {
|
|
435
|
+
type,
|
|
436
|
+
code: 202,
|
|
437
|
+
appId: this.appId,
|
|
438
|
+
sender: prefixId(this.appId, senderId),
|
|
439
|
+
receivers: receiverIds.map(
|
|
440
|
+
(id) => prefixId(this.appId, id)
|
|
441
|
+
),
|
|
442
|
+
timestamp: Date.now(),
|
|
443
|
+
token: this.authToken
|
|
444
|
+
};
|
|
445
|
+
const frame = framePacket(metadata, buffer);
|
|
446
|
+
this.transport.sendBinary(frame);
|
|
447
|
+
}
|
|
448
|
+
/**
|
|
449
|
+
* Send a message to OpenAI; the SDK streams the response internally and calls onMessageCallback
|
|
450
|
+
* once with the full response as JSON (no stream option exposed).
|
|
451
|
+
*
|
|
452
|
+
* @param {Object} options
|
|
453
|
+
* @param {string} options.senderId - Sender user id.
|
|
454
|
+
* @param {string | Array<{role: string, content: string}>} options.message - User message or chat messages array.
|
|
455
|
+
* @param {string} options.openaiApiKey - OpenAI API key (or compatible endpoint key).
|
|
456
|
+
* @param {string} [options.model] - Model name (default: gpt-4o-mini).
|
|
457
|
+
* @param {string} [options.baseUrl] - OpenAI-compatible API base URL (e.g. Azure/custom).
|
|
458
|
+
* @returns {Promise<{ content: string }>} Resolves with the full assistant content when done.
|
|
459
|
+
*/
|
|
460
|
+
async sendWithOpenAI({ senderId, message, openaiApiKey, model, baseUrl }) {
|
|
461
|
+
if (!senderId) throw new Error("senderId is required");
|
|
462
|
+
if (!message) throw new Error("message is required");
|
|
463
|
+
if (!openaiApiKey) throw new Error("openaiApiKey is required");
|
|
464
|
+
const { content } = await chatStream({
|
|
465
|
+
apiKey: openaiApiKey,
|
|
466
|
+
model,
|
|
467
|
+
messages: message,
|
|
468
|
+
baseUrl
|
|
469
|
+
});
|
|
470
|
+
const data = {
|
|
471
|
+
type: "openai",
|
|
472
|
+
content,
|
|
473
|
+
ts: Date.now()
|
|
474
|
+
};
|
|
475
|
+
this.onMessageCallback({
|
|
476
|
+
metadata: {
|
|
477
|
+
sender: prefixId(this.appId, senderId),
|
|
478
|
+
timestamp: Date.now()
|
|
479
|
+
},
|
|
480
|
+
payload: new Payload(toUint8(JSON.stringify(data)))
|
|
481
|
+
});
|
|
482
|
+
return { content };
|
|
483
|
+
}
|
|
484
|
+
};
|
|
485
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
486
|
+
0 && (module.exports = {
|
|
487
|
+
DNotifier
|
|
488
|
+
});
|
package/dist/dnotifier.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
|
|
1
|
+
import{HttpTransport}from'./transport/httpTransport.js';import{WebsocketTransport}from'./transport/websocketTransport.js';import{prefixId}from'./utils/id.js';import{framePacket}from'./utils/frame.js';import{Payload}from'./utils/payload.js';import{toUint8}from'./utils/buffer.js';import{chatStream as _0x7f9287}from'./providers/openai.js';export class DNotifier{constructor({appId:_0x457799,secret:_0x461bd9,transport:_0x2c2a17,userId:_0x1b1e0c,onConnected:_0x5eb3db,onMessage:_0x4b34c7,onDisconnected:_0x2d96bd,WebSocketImpl:_0x3222a4}){if(!(_0x457799&&_0x461bd9&&_0x2c2a17&&_0x1b1e0c))throw new Error('appId,\x20secret,\x20transport,\x20and\x20userId\x20are\x20required');this['appId']=_0x457799,this['secret']=_0x461bd9,this['userId']=_0x1b1e0c,this['url']='wss://link.dchatter.com/ws',this['onConnectedCallback']=_0x5eb3db||(()=>{}),this['onMessageCallback']=_0x4b34c7||(()=>{}),this['onDisconnectedCallback']=_0x2d96bd||(()=>{}),this['isConnected']=!0x1,this['transport']='ws'===_0x2c2a17?new WebsocketTransport(_0x3222a4):new HttpTransport();}async['connect'](){const _0x54721a=new HttpTransport({'url':'https://link.dchatter.com/api/v1/sdk/auth'}),_0x4e298f=await _0x54721a['send']({'appId':this['appId'],'appSecret':this['secret'],'userID':this['userId']});if(0xc8!==_0x4e298f['_responseCode'])throw new Error('Authentication\x20Failed.');this['authToken']=_0x4e298f['_responseData'],await this['transport']['connect'](this['url']);const _0x3637c9={'type':'text','code':0x65,'appId':this['appId'],'sender':prefixId(this['appId'],this['userId']),'timestamp':Date['now'](),'token':this['authToken']},_0x14a53a=toUint8(JSON['stringify']({'token':this['authToken']})),_0x585865=framePacket(_0x3637c9,_0x14a53a);this['transport']['sendBinary'](_0x585865);let _0x554646=!0x1;this['transport']['on']('message',_0x381235=>{try{const {metadata:_0x93f303,data:_0x5735ed}=_0x381235;if(!_0x554646&&'102'===_0x93f303['packet']['code']&&_0x93f303['packet']['sender']['includes'](prefixId(this['appId'],this['userId'])))return _0x554646=!0x0,this['isConnected']=!0x0,void this['onConnectedCallback']();_0x554646&&this['onMessageCallback']({'metadata':{'sender':_0x93f303['packet']['sender'],'timestamp':_0x93f303['packet']['timestamp']},'payload':new Payload(_0x5735ed)});}catch(_0x58e800){console['error']('Packet\x20error:',_0x58e800);}}),this['transport']['on']('close',({code:_0x4079c0,reason:_0x23219a})=>{this['isConnected']&&(this['isConnected']=!0x1,this['onDisconnectedCallback']({'code':_0x4079c0,'reason':_0x23219a||'Disconnected'}));}),this['transport']['on']('error',_0x242df1=>{this['isConnected']=!0x1,this['onDisconnectedCallback']({'code':0x1f4,'reason':(null==_0x242df1?void 0x0:_0x242df1['message'])||'Transport\x20error'});});}['send']({senderId:_0x8c7afc,receiverId:_0x283630,receiverIds:_0x2ba291,data:_0x28706c}){if(!_0x8c7afc)throw new Error('senderId\x20required');if(!_0x283630&&!_0x2ba291)throw new Error('receiverId\x20or\x20receiverIds\x20required');const _0x4465b3=null!=_0x2ba291?_0x2ba291:[_0x283630],_0x4ec0dd={'type':'text','code':0xc8,'appId':this['appId'],'sender':prefixId(this['appId'],_0x8c7afc),'receivers':_0x4465b3['map'](_0x244919=>prefixId(this['appId'],_0x244919)),'timestamp':Date['now'](),'token':this['authToken']},_0x40399d=toUint8(JSON['stringify'](_0x28706c)),_0xb56706=framePacket(_0x4ec0dd,_0x40399d);this['transport']['sendBinary'](_0xb56706);}['sendBinary']({senderId:_0x260871,receiverIds:_0x1ca882,buffer:_0x5cce6d,type:_0x19c9f7='binary'}){if(!_0x260871)throw new Error('senderId\x20required');if(!_0x5cce6d)throw new Error('buffer\x20is\x20required');const _0x1d0df2={'type':_0x19c9f7,'code':0xca,'appId':this['appId'],'sender':prefixId(this['appId'],_0x260871),'receivers':_0x1ca882['map'](_0x22822c=>prefixId(this['appId'],_0x22822c)),'timestamp':Date['now'](),'token':this['authToken']},_0x1925db=framePacket(_0x1d0df2,_0x5cce6d);this['transport']['sendBinary'](_0x1925db);}async['sendWithOpenAI']({senderId:_0x57a1be,message:_0x56f77e,openaiApiKey:_0x595c66,model:_0x3dca85,baseUrl:_0x2af08d}){if(!_0x57a1be)throw new Error('senderId\x20is\x20required');if(!_0x56f77e)throw new Error('message\x20is\x20required');if(!_0x595c66)throw new Error('openaiApiKey\x20is\x20required');const {content:_0x70f236}=await _0x7f9287({'apiKey':_0x595c66,'model':_0x3dca85,'messages':_0x56f77e,'baseUrl':_0x2af08d}),_0x1c2077={'type':'openai','content':_0x70f236,'ts':Date['now']()};return this['onMessageCallback']({'metadata':{'sender':prefixId(this['appId'],_0x57a1be),'timestamp':Date['now']()},'payload':new Payload(toUint8(JSON['stringify'](_0x1c2077)))}),{'content':_0x70f236};}}
|
package/dist/providers/openai.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
|
|
1
|
+
const DEFAULT_BASE_URL='https://api.openai.com',DEFAULT_MODEL='gpt-4o-mini';function normalizeMessages(_0x3d9fa0){if('string'==typeof _0x3d9fa0)return[{'role':'user','content':_0x3d9fa0}];if(Array['isArray'](_0x3d9fa0)&&_0x3d9fa0['length']>0x0)return _0x3d9fa0['map'](_0x23d188=>({'role':_0x23d188['role']||'user','content':'string'==typeof _0x23d188['content']?_0x23d188['content']:String(_0x23d188['content'])}));throw new Error('message\x20must\x20be\x20a\x20non-empty\x20string\x20or\x20array\x20of\x20{\x20role,\x20content\x20}');}export async function chat(_0x47bc48){var _0x1ea4ee,_0x468771,_0x5af955,_0xe21ec9,_0x4616a9,_0x45695d;const {apiKey:_0x3446a3,model:_0x3090ea=DEFAULT_MODEL,messages:_0x31caea,baseUrl:_0x19da9a=DEFAULT_BASE_URL}=_0x47bc48;if(!_0x3446a3||!_0x31caea)throw new Error('openai.chat:\x20apiKey\x20and\x20messages\x20are\x20required');const _0x6986b3=_0x19da9a['replace'](/\/$/,'')+'/v1/chat/completions',_0x1589c8={'model':_0x3090ea,'messages':normalizeMessages(_0x31caea),'stream':!0x1},_0x1a00ab=await fetch(_0x6986b3,{'method':'POST','headers':{'Content-Type':'application/json','Authorization':'Bearer\x20'+_0x3446a3},'body':JSON['stringify'](_0x1589c8)}),_0x314227=await _0x1a00ab['json']();if(!_0x1a00ab['ok']){const _0x4a73b4=new Error((null===(_0x1ea4ee=null==_0x314227?void 0x0:_0x314227['error'])||void 0x0===_0x1ea4ee?void 0x0:_0x1ea4ee['message'])||'OpenAI\x20API\x20error:\x20'+_0x1a00ab['status']);throw _0x4a73b4['status']=_0x1a00ab['status'],_0x4a73b4['code']=null===(_0x468771=null==_0x314227?void 0x0:_0x314227['error'])||void 0x0===_0x468771?void 0x0:_0x468771['code'],_0x4a73b4;}return{'content':null!==(_0x45695d=null===(_0x4616a9=null===(_0xe21ec9=null===(_0x5af955=null==_0x314227?void 0x0:_0x314227['choices'])||void 0x0===_0x5af955?void 0x0:_0x5af955[0x0])||void 0x0===_0xe21ec9?void 0x0:_0xe21ec9['message'])||void 0x0===_0x4616a9?void 0x0:_0x4616a9['content'])&&void 0x0!==_0x45695d?_0x45695d:'','usage':null==_0x314227?void 0x0:_0x314227['usage'],'raw':_0x314227};}export async function chatStream(_0x24845c){var _0x1a2cdd,_0x1dffcc,_0x240789,_0x2246f9,_0x3cc7e0;const {apiKey:_0x7947e4,model:_0x4095c6=DEFAULT_MODEL,messages:_0x3252a9,baseUrl:_0x1d913d=DEFAULT_BASE_URL,onChunk:_0x1e3b24}=_0x24845c;if(!_0x7947e4||!_0x3252a9)throw new Error('openai.chatStream:\x20apiKey\x20and\x20messages\x20are\x20required');const _0x34625e=_0x1d913d['replace'](/\/$/,'')+'/v1/chat/completions',_0x3b5723={'model':_0x4095c6,'messages':normalizeMessages(_0x3252a9),'stream':!0x0},_0x55db18=await fetch(_0x34625e,{'method':'POST','headers':{'Content-Type':'application/json','Authorization':'Bearer\x20'+_0x7947e4},'body':JSON['stringify'](_0x3b5723)});if(!_0x55db18['ok']){const _0x28c404=await _0x55db18['json']()['catch'](()=>({})),_0x47f48f=new Error((null===(_0x1a2cdd=null==_0x28c404?void 0x0:_0x28c404['error'])||void 0x0===_0x1a2cdd?void 0x0:_0x1a2cdd['message'])||'OpenAI\x20API\x20error:\x20'+_0x55db18['status']);throw _0x47f48f['status']=_0x55db18['status'],_0x47f48f['code']=null===(_0x1dffcc=null==_0x28c404?void 0x0:_0x28c404['error'])||void 0x0===_0x1dffcc?void 0x0:_0x1dffcc['code'],_0x47f48f;}const _0x4a19ae=_0x55db18['body']['getReader'](),_0x4a1756=new TextDecoder();let _0x39ddf3='',_0x4c83ba='';for(;;){const {done:_0x105c1d,value:_0x541b56}=await _0x4a19ae['read']();if(_0x105c1d)break;_0x4c83ba+=_0x4a1756['decode'](_0x541b56,{'stream':!0x0});const _0x289288=_0x4c83ba['split']('\x0a');_0x4c83ba=_0x289288['pop']()||'';for(const _0x4e3fcc of _0x289288){const _0x273131=_0x4e3fcc['trim']();if(''!==_0x273131&&'data:\x20[DONE]'!==_0x273131&&_0x273131['startsWith']('data:\x20'))try{const _0x2fc15a=JSON['parse'](_0x273131['slice'](0x6)),_0x2293a5=null===(_0x3cc7e0=null===(_0x2246f9=null===(_0x240789=null==_0x2fc15a?void 0x0:_0x2fc15a['choices'])||void 0x0===_0x240789?void 0x0:_0x240789[0x0])||void 0x0===_0x2246f9?void 0x0:_0x2246f9['delta'])||void 0x0===_0x3cc7e0?void 0x0:_0x3cc7e0['content'];'string'==typeof _0x2293a5&&(_0x39ddf3+=_0x2293a5,_0x1e3b24&&_0x1e3b24(_0x2293a5));}catch(_0x469f9b){}}}return{'content':_0x39ddf3};}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
|
|
1
|
+
export class HttpTransport{constructor({url:_0x7b6748}){this['url']=_0x7b6748;}async['send'](_0x4e921c){const _0xda1a5c=await fetch(''+this['url'],{'method':'POST','headers':{'Content-Type':'application/json'},'body':JSON['stringify'](_0x4e921c)});if(!_0xda1a5c['ok']){const _0x14e176=await _0xda1a5c['text']();throw new Error('DNotifier\x20HTTP\x20error:\x20'+_0x14e176);}return await _0xda1a5c['json']();}['sendBinary'](){throw new Error('Binary\x20is\x20not\x20supported\x20over\x20HTTP\x20yet');}}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
|
|
1
|
+
import _0x364bfe from'events';import{decodePacket}from'../utils/frame.js';export class WebsocketTransport extends _0x364bfe{constructor(_0x5f00f6=null){if(super(),this['socket']=null,this['WebSocketImpl']=_0x5f00f6||('undefined'!=typeof window?window['WebSocket']:null),!this['WebSocketImpl'])throw new Error('No\x20WebSocket\x20implementation\x20provided');}['connect'](_0x46ef9c){return new Promise((_0x17f80b,_0x45a83c)=>{this['socket']=new this['WebSocketImpl'](_0x46ef9c),'undefined'!=typeof window&&(this['socket']['binaryType']='arrayBuffer'),this['_on']('open',()=>_0x17f80b(!0x0)),this['_on']('error',_0x11356d=>{console['error']('WS\x20error',_0x11356d),_0x45a83c(_0x11356d);}),this['_on']('close',_0x58bf51=>{const _0xe8af6=null==_0x58bf51?void 0x0:_0x58bf51['code'],_0x1fe47d=null==_0x58bf51?void 0x0:_0x58bf51['reason'];this['emit']('close',{'code':_0xe8af6,'reason':_0x1fe47d});}),this['_on']('message',async(_0x547a4a,_0x35c170)=>{var _0xf8f4b9,_0x5da1dc=null!==(_0xf8f4b9=null==_0x547a4a?void 0x0:_0x547a4a['data'])&&void 0x0!==_0xf8f4b9?_0xf8f4b9:_0x547a4a;'undefined'!=typeof Blob&&_0x5da1dc instanceof Blob&&(_0x5da1dc=await _0x5da1dc['arrayBuffer']());const _0x443026=decodePacket(_0x5da1dc);_0x443026&&this['emit']('message',_0x443026,_0x35c170);});});}['_on'](_0x646853,_0xb7c42c){this['socket']['on']?this['socket']['on'](_0x646853,_0xb7c42c):this['socket']['on'+_0x646853]=_0xb7c42c;}['send'](_0x15b8b8){if(!this['isOpen']())throw new Error('WebSocket\x20not\x20connected');this['socket']['send'](_0x15b8b8);}['sendBinary'](_0x16341d){if(!this['isOpen']())throw new Error('WebSocket\x20not\x20connected');this['socket']['send'](_0x16341d);}['isOpen'](){return this['socket']&&this['socket']['readyState']===this['WebSocketImpl']['OPEN'];}['close'](){var _0x1365c4;null===(_0x1365c4=this['socket'])||void 0x0===_0x1365c4||_0x1365c4['close']();}}
|
package/dist/utils/buffer.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
|
|
1
|
+
export function toUint8(_0x48be0b){return'undefined'!=typeof Buffer?Buffer['from'](_0x48be0b,'utf8'):new TextEncoder()['encode'](_0x48be0b);}
|
package/dist/utils/frame.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
|
|
1
|
+
export function framePacket(_0x4e771f,_0x354af5){const _0x2d6e8d=Buffer['from'](JSON['stringify'](_0x4e771f)),_0xcfa549=Buffer['isBuffer'](_0x354af5)?_0x354af5:Buffer['from'](_0x354af5),_0x2a3dda=Buffer['alloc'](0x4+_0x2d6e8d['length']+0x4+_0xcfa549['length']);let _0x511691=0x0;return _0x2a3dda['writeUInt32BE'](_0x2d6e8d['length'],_0x511691),_0x511691+=0x4,_0x2d6e8d['copy'](_0x2a3dda,_0x511691),_0x511691+=_0x2d6e8d['length'],_0x2a3dda['writeUInt32BE'](_0xcfa549['length'],_0x511691),_0x511691+=0x4,_0xcfa549['copy'](_0x2a3dda,_0x511691),_0x2a3dda;}let internalBuffer=Buffer['alloc'](0x0);export function decodePacket(_0x3302e5){try{Buffer['isBuffer'](_0x3302e5)||(_0x3302e5=Buffer['from'](_0x3302e5)),internalBuffer=Buffer['concat']([internalBuffer,_0x3302e5]);let _0x58c119=0x0;if(internalBuffer['length']<0x4)return null;const _0x346bec=internalBuffer['readUInt32BE'](_0x58c119);if(_0x58c119+=0x4,internalBuffer['length']<_0x58c119+_0x346bec)return null;const _0x13d4ce=internalBuffer['slice'](_0x58c119,_0x58c119+_0x346bec),_0x4854ec=JSON['parse'](_0x13d4ce['toString']());if(_0x58c119+=_0x346bec,internalBuffer['length']<_0x58c119+0x4)return null;const _0x2bd773=internalBuffer['readUInt32BE'](_0x58c119);if(_0x58c119+=0x4,internalBuffer['length']<_0x58c119+_0x2bd773)return null;const _0x4e041f=internalBuffer['slice'](_0x58c119,_0x58c119+_0x2bd773);_0x58c119+=_0x2bd773,internalBuffer=internalBuffer['slice'](_0x58c119);let _0x16d9b0=_0x4e041f;if('text'===_0x4854ec['type'])try{_0x16d9b0=JSON['parse'](_0x4e041f['toString']('utf8'));}catch{_0x16d9b0=_0x4e041f;}return{'metadata':_0x4854ec,'data':_0x16d9b0};}catch(_0x410fe3){return console['error']('decodePacket\x20error:',_0x410fe3),null;}}
|
package/dist/utils/id.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
|
|
1
|
+
export const prefixId=(_0x18d37d,_0x446d14)=>_0x446d14['includes'](':')?_0x446d14:_0x18d37d+':'+_0x446d14;
|
package/dist/utils/payload.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
|
|
1
|
+
export class Payload{constructor(_0x132bd4){this['buffer']=_0x132bd4;}['raw'](){return this['buffer'];}['toString'](_0x2bd784='utf8'){return this['buffer']['toString'](_0x2bd784);}['toJSON'](_0x289105='utf8'){try{return JSON['parse'](this['buffer']['toString'](_0x289105));}catch(_0x1cd97c){return null;}}['toBase64'](){return this['buffer']['toString']('base64');}}
|
package/package.json
CHANGED
|
@@ -1,9 +1,17 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@dnotifier-realtime/dnotifier",
|
|
3
|
-
"version": "1.0.
|
|
3
|
+
"version": "1.0.14",
|
|
4
4
|
"description": "Real-time notification & messaging SDK",
|
|
5
5
|
"main": "dist/dnotifier.js",
|
|
6
6
|
"types": "dist/dnotifier.d.ts",
|
|
7
|
+
"exports": {
|
|
8
|
+
".": {
|
|
9
|
+
"types": "./dist/dnotifier.d.ts",
|
|
10
|
+
"import": "./dist/dnotifier.js",
|
|
11
|
+
"require": "./dist/dnotifier.cjs",
|
|
12
|
+
"default": "./dist/dnotifier.js"
|
|
13
|
+
}
|
|
14
|
+
},
|
|
7
15
|
"files": [
|
|
8
16
|
"dist"
|
|
9
17
|
],
|
|
@@ -27,6 +35,7 @@
|
|
|
27
35
|
"ws": "^8.19.0"
|
|
28
36
|
},
|
|
29
37
|
"devDependencies": {
|
|
38
|
+
"esbuild": "^0.24.0",
|
|
30
39
|
"javascript-obfuscator": "^4.1.1",
|
|
31
40
|
"terser": "^5.36.0",
|
|
32
41
|
"typescript": "^5.9.3"
|
|
@@ -34,7 +43,7 @@
|
|
|
34
43
|
"scripts": {
|
|
35
44
|
"test": "echo \"Error: no test specified\" && exit 1",
|
|
36
45
|
"start": "node index.js",
|
|
37
|
-
"build": "tsc",
|
|
46
|
+
"build": "tsc && npx esbuild src/dnotifier.js --bundle --format=cjs --platform=node --outfile=dist/dnotifier.cjs --external:ws",
|
|
38
47
|
"publishprod": "node scripts/publish-prod.js"
|
|
39
48
|
},
|
|
40
49
|
"homepage": "https://dnotifier.com"
|