@dnotifier-realtime/dnotifier 1.0.12 → 1.0.13
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/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
|
@@ -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:_0x5f965b,secret:_0x25d4eb,transport:_0x6711ad,userId:_0x101fe2,onConnected:_0x558a58,onMessage:_0x206501,onDisconnected:_0x3504b9,WebSocketImpl:_0x20aba5}){if(!(_0x5f965b&&_0x25d4eb&&_0x6711ad&&_0x101fe2))throw new Error('appId,\x20secret,\x20transport,\x20and\x20userId\x20are\x20required');this['appId']=_0x5f965b,this['secret']=_0x25d4eb,this['userId']=_0x101fe2,this['url']='wss://link.dchatter.com/ws',this['onConnectedCallback']=_0x558a58||(()=>{}),this['onMessageCallback']=_0x206501||(()=>{}),this['onDisconnectedCallback']=_0x3504b9||(()=>{}),this['isConnected']=!0x1,this['transport']='ws'===_0x6711ad?new websocketTransport_js_1['WebsocketTransport'](_0x20aba5):new httpTransport_js_1['HttpTransport']();}async['connect'](){const _0x32d591=new httpTransport_js_1['HttpTransport']({'url':'https://link.dchatter.com/api/v1/sdk/auth'}),_0x2632dc=await _0x32d591['send']({'appId':this['appId'],'appSecret':this['secret'],'userID':this['userId']});if(0xc8!==_0x2632dc['_responseCode'])throw new Error('Authentication\x20Failed.');this['authToken']=_0x2632dc['_responseData'],await this['transport']['connect'](this['url']);const _0x297dfd={'type':'text','code':0x65,'appId':this['appId'],'sender':(0x0,id_js_1['prefixId'])(this['appId'],this['userId']),'timestamp':Date['now'](),'token':this['authToken']},_0x455265=(0x0,buffer_js_1['toUint8'])(JSON['stringify']({'token':this['authToken']})),_0x445347=(0x0,frame_js_1['framePacket'])(_0x297dfd,_0x455265);this['transport']['sendBinary'](_0x445347);let _0x1e9f9f=!0x1;this['transport']['on']('message',_0x4e0b55=>{try{const {metadata:_0x111019,data:_0x260cc0}=_0x4e0b55;if(!_0x1e9f9f&&'102'===_0x111019['packet']['code']&&_0x111019['packet']['sender']['includes']((0x0,id_js_1['prefixId'])(this['appId'],this['userId'])))return _0x1e9f9f=!0x0,this['isConnected']=!0x0,void this['onConnectedCallback']();_0x1e9f9f&&this['onMessageCallback']({'metadata':{'sender':_0x111019['packet']['sender'],'timestamp':_0x111019['packet']['timestamp']},'payload':new payload_js_1['Payload'](_0x260cc0)});}catch(_0x125bcd){console['error']('Packet\x20error:',_0x125bcd);}}),this['transport']['on']('close',({code:_0x4f598f,reason:_0x1be067})=>{this['isConnected']&&(this['isConnected']=!0x1,this['onDisconnectedCallback']({'code':_0x4f598f,'reason':_0x1be067||'Disconnected'}));}),this['transport']['on']('error',_0x56e7b5=>{this['isConnected']=!0x1,this['onDisconnectedCallback']({'code':0x1f4,'reason':(null==_0x56e7b5?void 0x0:_0x56e7b5['message'])||'Transport\x20error'});});}['send']({senderId:_0x34ad50,receiverId:_0x102c28,receiverIds:_0x8c785c,data:_0x122ce3}){if(!_0x34ad50)throw new Error('senderId\x20required');if(!_0x102c28&&!_0x8c785c)throw new Error('receiverId\x20or\x20receiverIds\x20required');const _0x41ebe3=null!=_0x8c785c?_0x8c785c:[_0x102c28],_0x246c9b={'type':'text','code':0xc8,'appId':this['appId'],'sender':(0x0,id_js_1['prefixId'])(this['appId'],_0x34ad50),'receivers':_0x41ebe3['map'](_0x1603a5=>(0x0,id_js_1['prefixId'])(this['appId'],_0x1603a5)),'timestamp':Date['now'](),'token':this['authToken']},_0x2c9b4a=(0x0,buffer_js_1['toUint8'])(JSON['stringify'](_0x122ce3)),_0x153386=(0x0,frame_js_1['framePacket'])(_0x246c9b,_0x2c9b4a);this['transport']['sendBinary'](_0x153386);}['sendBinary']({senderId:_0x16eb06,receiverIds:_0x24dfc9,buffer:_0x3ebcd0,type:_0x3f1dcd='binary'}){if(!_0x16eb06)throw new Error('senderId\x20required');if(!_0x3ebcd0)throw new Error('buffer\x20is\x20required');const _0x13e823={'type':_0x3f1dcd,'code':0xca,'appId':this['appId'],'sender':(0x0,id_js_1['prefixId'])(this['appId'],_0x16eb06),'receivers':_0x24dfc9['map'](_0x40c030=>(0x0,id_js_1['prefixId'])(this['appId'],_0x40c030)),'timestamp':Date['now'](),'token':this['authToken']},_0x48fca8=(0x0,frame_js_1['framePacket'])(_0x13e823,_0x3ebcd0);this['transport']['sendBinary'](_0x48fca8);}async['sendWithOpenAI']({senderId:_0x1c0a8e,message:_0x357932,openaiApiKey:_0x4acd54,model:_0x23a8ec,baseUrl:_0x52184e}){if(!_0x1c0a8e)throw new Error('senderId\x20is\x20required');if(!_0x357932)throw new Error('message\x20is\x20required');if(!_0x4acd54)throw new Error('openaiApiKey\x20is\x20required');const {content:_0x64ed05}=await(0x0,openai_js_1['chatStream'])({'apiKey':_0x4acd54,'model':_0x23a8ec,'messages':_0x357932,'baseUrl':_0x52184e}),_0x5e065c={'type':'openai','content':_0x64ed05,'ts':Date['now']()};return this['onMessageCallback']({'metadata':{'sender':(0x0,id_js_1['prefixId'])(this['appId'],_0x1c0a8e),'timestamp':Date['now']()},'payload':new payload_js_1['Payload']((0x0,buffer_js_1['toUint8'])(JSON['stringify'](_0x5e065c)))}),{'content':_0x64ed05};}}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(_0x342720){if('string'==typeof _0x342720)return[{'role':'user','content':_0x342720}];if(Array['isArray'](_0x342720)&&_0x342720['length']>0x0)return _0x342720['map'](_0x5dd1f2=>({'role':_0x5dd1f2['role']||'user','content':'string'==typeof _0x5dd1f2['content']?_0x5dd1f2['content']:String(_0x5dd1f2['content'])}));throw new Error('message\x20must\x20be\x20a\x20non-empty\x20string\x20or\x20array\x20of\x20{\x20role,\x20content\x20}');}async function chat(_0x2c6f7e){var _0x47170d,_0x230042,_0x3351bc,_0x16bed9,_0x354060,_0x84f06d;const {apiKey:_0x4718a6,model:_0x3d9944=DEFAULT_MODEL,messages:_0x29e3ae,baseUrl:_0x4e905f=DEFAULT_BASE_URL}=_0x2c6f7e;if(!_0x4718a6||!_0x29e3ae)throw new Error('openai.chat:\x20apiKey\x20and\x20messages\x20are\x20required');const _0x588eaf=_0x4e905f['replace'](/\/$/,'')+'/v1/chat/completions',_0x4455a7={'model':_0x3d9944,'messages':normalizeMessages(_0x29e3ae),'stream':!0x1},_0x22d8a1=await fetch(_0x588eaf,{'method':'POST','headers':{'Content-Type':'application/json','Authorization':'Bearer\x20'+_0x4718a6},'body':JSON['stringify'](_0x4455a7)}),_0x411554=await _0x22d8a1['json']();if(!_0x22d8a1['ok']){const _0x47e189=new Error((null===(_0x47170d=null==_0x411554?void 0x0:_0x411554['error'])||void 0x0===_0x47170d?void 0x0:_0x47170d['message'])||'OpenAI\x20API\x20error:\x20'+_0x22d8a1['status']);throw _0x47e189['status']=_0x22d8a1['status'],_0x47e189['code']=null===(_0x230042=null==_0x411554?void 0x0:_0x411554['error'])||void 0x0===_0x230042?void 0x0:_0x230042['code'],_0x47e189;}return{'content':null!==(_0x84f06d=null===(_0x354060=null===(_0x16bed9=null===(_0x3351bc=null==_0x411554?void 0x0:_0x411554['choices'])||void 0x0===_0x3351bc?void 0x0:_0x3351bc[0x0])||void 0x0===_0x16bed9?void 0x0:_0x16bed9['message'])||void 0x0===_0x354060?void 0x0:_0x354060['content'])&&void 0x0!==_0x84f06d?_0x84f06d:'','usage':null==_0x411554?void 0x0:_0x411554['usage'],'raw':_0x411554};}async function chatStream(_0x2a7749){var _0x228b85,_0x29ba26,_0x25d34d,_0x4df1e8,_0xbb77ee;const {apiKey:_0x1abce2,model:_0x16255b=DEFAULT_MODEL,messages:_0x21928c,baseUrl:_0x3d0fb1=DEFAULT_BASE_URL,onChunk:_0x351dd8}=_0x2a7749;if(!_0x1abce2||!_0x21928c)throw new Error('openai.chatStream:\x20apiKey\x20and\x20messages\x20are\x20required');const _0x47a4a5=_0x3d0fb1['replace'](/\/$/,'')+'/v1/chat/completions',_0x2b5d16={'model':_0x16255b,'messages':normalizeMessages(_0x21928c),'stream':!0x0},_0x480bd9=await fetch(_0x47a4a5,{'method':'POST','headers':{'Content-Type':'application/json','Authorization':'Bearer\x20'+_0x1abce2},'body':JSON['stringify'](_0x2b5d16)});if(!_0x480bd9['ok']){const _0x194746=await _0x480bd9['json']()['catch'](()=>({})),_0x11d70a=new Error((null===(_0x228b85=null==_0x194746?void 0x0:_0x194746['error'])||void 0x0===_0x228b85?void 0x0:_0x228b85['message'])||'OpenAI\x20API\x20error:\x20'+_0x480bd9['status']);throw _0x11d70a['status']=_0x480bd9['status'],_0x11d70a['code']=null===(_0x29ba26=null==_0x194746?void 0x0:_0x194746['error'])||void 0x0===_0x29ba26?void 0x0:_0x29ba26['code'],_0x11d70a;}const _0x1be199=_0x480bd9['body']['getReader'](),_0x44ee47=new TextDecoder();let _0x766171='',_0x4deaae='';for(;;){const {done:_0x1b5d82,value:_0x1a9ec6}=await _0x1be199['read']();if(_0x1b5d82)break;_0x4deaae+=_0x44ee47['decode'](_0x1a9ec6,{'stream':!0x0});const _0x3a672d=_0x4deaae['split']('\x0a');_0x4deaae=_0x3a672d['pop']()||'';for(const _0xfd903c of _0x3a672d){const _0x27e8e0=_0xfd903c['trim']();if(''!==_0x27e8e0&&'data:\x20[DONE]'!==_0x27e8e0&&_0x27e8e0['startsWith']('data:\x20'))try{const _0x21c7ab=JSON['parse'](_0x27e8e0['slice'](0x6)),_0x547864=null===(_0xbb77ee=null===(_0x4df1e8=null===(_0x25d34d=null==_0x21c7ab?void 0x0:_0x21c7ab['choices'])||void 0x0===_0x25d34d?void 0x0:_0x25d34d[0x0])||void 0x0===_0x4df1e8?void 0x0:_0x4df1e8['delta'])||void 0x0===_0xbb77ee?void 0x0:_0xbb77ee['content'];'string'==typeof _0x547864&&(_0x766171+=_0x547864,_0x351dd8&&_0x351dd8(_0x547864));}catch(_0x1ef5c1){}}}return{'content':_0x766171};}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
'use strict';Object['defineProperty'](exports,'__esModule',{'value':!0x0}),exports['HttpTransport']=void 0x0;class HttpTransport{constructor({url:_0x50955a}){this['url']=_0x50955a;}async['send'](_0x11213b){const _0x95c6ed=await fetch(''+this['url'],{'method':'POST','headers':{'Content-Type':'application/json'},'body':JSON['stringify'](_0x11213b)});if(!_0x95c6ed['ok']){const _0x280430=await _0x95c6ed['text']();throw new Error('DNotifier\x20HTTP\x20error:\x20'+_0x280430);}return await _0x95c6ed['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(_0x87e545=null){if(super(),this['socket']=null,this['WebSocketImpl']=_0x87e545||('undefined'!=typeof window?window['WebSocket']:null),!this['WebSocketImpl'])throw new Error('No\x20WebSocket\x20implementation\x20provided');}['connect'](_0x1e1b48){return new Promise((_0x38e5c6,_0x422b7)=>{this['socket']=new this['WebSocketImpl'](_0x1e1b48),'undefined'!=typeof window&&(this['socket']['binaryType']='arrayBuffer'),this['_on']('open',()=>_0x38e5c6(!0x0)),this['_on']('error',_0xa0242b=>{console['error']('WS\x20error',_0xa0242b),_0x422b7(_0xa0242b);}),this['_on']('close',_0x3c3459=>{const _0x2b4997=null==_0x3c3459?void 0x0:_0x3c3459['code'],_0x29d4af=null==_0x3c3459?void 0x0:_0x3c3459['reason'];this['emit']('close',{'code':_0x2b4997,'reason':_0x29d4af});}),this['_on']('message',async(_0x2b4dec,_0x559da7)=>{var _0xe52f05,_0x44bc57=null!==(_0xe52f05=null==_0x2b4dec?void 0x0:_0x2b4dec['data'])&&void 0x0!==_0xe52f05?_0xe52f05:_0x2b4dec;'undefined'!=typeof Blob&&_0x44bc57 instanceof Blob&&(_0x44bc57=await _0x44bc57['arrayBuffer']());const _0x59c4f1=(0x0,frame_js_1['decodePacket'])(_0x44bc57);_0x59c4f1&&this['emit']('message',_0x59c4f1,_0x559da7);});});}['_on'](_0x460ce4,_0x24fb27){this['socket']['on']?this['socket']['on'](_0x460ce4,_0x24fb27):this['socket']['on'+_0x460ce4]=_0x24fb27;}['send'](_0x15ac86){if(!this['isOpen']())throw new Error('WebSocket\x20not\x20connected');this['socket']['send'](_0x15ac86);}['sendBinary'](_0x19fb6a){if(!this['isOpen']())throw new Error('WebSocket\x20not\x20connected');this['socket']['send'](_0x19fb6a);}['isOpen'](){return this['socket']&&this['socket']['readyState']===this['WebSocketImpl']['OPEN'];}['close'](){var _0x24c8ff;null===(_0x24c8ff=this['socket'])||void 0x0===_0x24c8ff||_0x24c8ff['close']();}}exports['WebsocketTransport']=WebsocketTransport;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
'use strict';function toUint8(_0x42d905){return'undefined'!=typeof Buffer?Buffer['from'](_0x42d905,'utf8'):new TextEncoder()['encode'](_0x42d905);}Object['defineProperty'](exports,'__esModule',{'value':!0x0}),exports['toUint8']=toUint8;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
'use strict';function framePacket(_0x19be5f,_0x309d73){const _0x471ad3=Buffer['from'](JSON['stringify'](_0x19be5f)),_0x19ae08=Buffer['isBuffer'](_0x309d73)?_0x309d73:Buffer['from'](_0x309d73),_0x5f352b=Buffer['alloc'](0x4+_0x471ad3['length']+0x4+_0x19ae08['length']);let _0x399d46=0x0;return _0x5f352b['writeUInt32BE'](_0x471ad3['length'],_0x399d46),_0x399d46+=0x4,_0x471ad3['copy'](_0x5f352b,_0x399d46),_0x399d46+=_0x471ad3['length'],_0x5f352b['writeUInt32BE'](_0x19ae08['length'],_0x399d46),_0x399d46+=0x4,_0x19ae08['copy'](_0x5f352b,_0x399d46),_0x5f352b;}Object['defineProperty'](exports,'__esModule',{'value':!0x0}),exports['framePacket']=framePacket,exports['decodePacket']=decodePacket;let internalBuffer=Buffer['alloc'](0x0);function decodePacket(_0x1cb87e){try{Buffer['isBuffer'](_0x1cb87e)||(_0x1cb87e=Buffer['from'](_0x1cb87e)),internalBuffer=Buffer['concat']([internalBuffer,_0x1cb87e]);let _0x1234f1=0x0;if(internalBuffer['length']<0x4)return null;const _0x3aa875=internalBuffer['readUInt32BE'](_0x1234f1);if(_0x1234f1+=0x4,internalBuffer['length']<_0x1234f1+_0x3aa875)return null;const _0x349cd2=internalBuffer['slice'](_0x1234f1,_0x1234f1+_0x3aa875),_0x28447a=JSON['parse'](_0x349cd2['toString']());if(_0x1234f1+=_0x3aa875,internalBuffer['length']<_0x1234f1+0x4)return null;const _0x3f5007=internalBuffer['readUInt32BE'](_0x1234f1);if(_0x1234f1+=0x4,internalBuffer['length']<_0x1234f1+_0x3f5007)return null;const _0x129e15=internalBuffer['slice'](_0x1234f1,_0x1234f1+_0x3f5007);_0x1234f1+=_0x3f5007,internalBuffer=internalBuffer['slice'](_0x1234f1);let _0x2bfec3=_0x129e15;if('text'===_0x28447a['type'])try{_0x2bfec3=JSON['parse'](_0x129e15['toString']('utf8'));}catch{_0x2bfec3=_0x129e15;}return{'metadata':_0x28447a,'data':_0x2bfec3};}catch(_0x71af17){return console['error']('decodePacket\x20error:',_0x71af17),null;}}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
'use strict';Object['defineProperty'](exports,'__esModule',{'value':!0x0}),exports['prefixId']=void 0x0;const prefixId=(_0x1ca23b,_0x2bbae0)=>_0x2bbae0['includes'](':')?_0x2bbae0:_0x1ca23b+':'+_0x2bbae0;exports['prefixId']=prefixId;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
'use strict';Object['defineProperty'](exports,'__esModule',{'value':!0x0}),exports['Payload']=void 0x0;class Payload{constructor(_0x205d98){this['buffer']=_0x205d98;}['raw'](){return this['buffer'];}['toString'](_0x236d5d='utf8'){return this['buffer']['toString'](_0x236d5d);}['toJSON'](_0x5a3338='utf8'){try{return JSON['parse'](this['buffer']['toString'](_0x5a3338));}catch(_0x25b3bf){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 _0x40b91e}from'./providers/openai.js';export class DNotifier{constructor({appId:_0x2fce8d,secret:_0x56bda7,transport:_0x157d3c,userId:_0x4da631,onConnected:_0x34e7f4,onMessage:_0x45ec95,onDisconnected:_0x143ed9,WebSocketImpl:_0x16bf84}){if(!(_0x2fce8d&&_0x56bda7&&_0x157d3c&&_0x4da631))throw new Error('appId,\x20secret,\x20transport,\x20and\x20userId\x20are\x20required');this['appId']=_0x2fce8d,this['secret']=_0x56bda7,this['userId']=_0x4da631,this['url']='wss://link.dchatter.com/ws',this['onConnectedCallback']=_0x34e7f4||(()=>{}),this['onMessageCallback']=_0x45ec95||(()=>{}),this['onDisconnectedCallback']=_0x143ed9||(()=>{}),this['isConnected']=!0x1,this['transport']='ws'===_0x157d3c?new WebsocketTransport(_0x16bf84):new HttpTransport();}async['connect'](){const _0x389d5c=new HttpTransport({'url':'https://link.dchatter.com/api/v1/sdk/auth'}),_0x31d969=await _0x389d5c['send']({'appId':this['appId'],'appSecret':this['secret'],'userID':this['userId']});if(0xc8!==_0x31d969['_responseCode'])throw new Error('Authentication\x20Failed.');this['authToken']=_0x31d969['_responseData'],await this['transport']['connect'](this['url']);const _0x54b4c6={'type':'text','code':0x65,'appId':this['appId'],'sender':prefixId(this['appId'],this['userId']),'timestamp':Date['now'](),'token':this['authToken']},_0x120968=toUint8(JSON['stringify']({'token':this['authToken']})),_0x31d603=framePacket(_0x54b4c6,_0x120968);this['transport']['sendBinary'](_0x31d603);let _0x36a9b2=!0x1;this['transport']['on']('message',_0x3afa72=>{try{const {metadata:_0x12f247,data:_0xc0a822}=_0x3afa72;if(!_0x36a9b2&&'102'===_0x12f247['packet']['code']&&_0x12f247['packet']['sender']['includes'](prefixId(this['appId'],this['userId'])))return _0x36a9b2=!0x0,this['isConnected']=!0x0,void this['onConnectedCallback']();_0x36a9b2&&this['onMessageCallback']({'metadata':{'sender':_0x12f247['packet']['sender'],'timestamp':_0x12f247['packet']['timestamp']},'payload':new Payload(_0xc0a822)});}catch(_0x5b5c6e){console['error']('Packet\x20error:',_0x5b5c6e);}}),this['transport']['on']('close',({code:_0x4e9555,reason:_0x87c324})=>{this['isConnected']&&(this['isConnected']=!0x1,this['onDisconnectedCallback']({'code':_0x4e9555,'reason':_0x87c324||'Disconnected'}));}),this['transport']['on']('error',_0x3beef4=>{this['isConnected']=!0x1,this['onDisconnectedCallback']({'code':0x1f4,'reason':(null==_0x3beef4?void 0x0:_0x3beef4['message'])||'Transport\x20error'});});}['send']({senderId:_0x50f6a6,receiverId:_0x55926a,receiverIds:_0xae7add,data:_0xe7f9a6}){if(!_0x50f6a6)throw new Error('senderId\x20required');if(!_0x55926a&&!_0xae7add)throw new Error('receiverId\x20or\x20receiverIds\x20required');const _0x55b8a3=null!=_0xae7add?_0xae7add:[_0x55926a],_0x2f501b={'type':'text','code':0xc8,'appId':this['appId'],'sender':prefixId(this['appId'],_0x50f6a6),'receivers':_0x55b8a3['map'](_0x1223ff=>prefixId(this['appId'],_0x1223ff)),'timestamp':Date['now'](),'token':this['authToken']},_0x393560=toUint8(JSON['stringify'](_0xe7f9a6)),_0x29cce4=framePacket(_0x2f501b,_0x393560);this['transport']['sendBinary'](_0x29cce4);}['sendBinary']({senderId:_0x1cc927,receiverIds:_0x190f57,buffer:_0x3759b4,type:_0x3bac5e='binary'}){if(!_0x1cc927)throw new Error('senderId\x20required');if(!_0x3759b4)throw new Error('buffer\x20is\x20required');const _0x39e620={'type':_0x3bac5e,'code':0xca,'appId':this['appId'],'sender':prefixId(this['appId'],_0x1cc927),'receivers':_0x190f57['map'](_0x388727=>prefixId(this['appId'],_0x388727)),'timestamp':Date['now'](),'token':this['authToken']},_0x17afe4=framePacket(_0x39e620,_0x3759b4);this['transport']['sendBinary'](_0x17afe4);}async['sendWithOpenAI']({senderId:_0x7d7b80,message:_0x3845e3,openaiApiKey:_0x461b45,model:_0x36fed7,baseUrl:_0x4b4640}){if(!_0x7d7b80)throw new Error('senderId\x20is\x20required');if(!_0x3845e3)throw new Error('message\x20is\x20required');if(!_0x461b45)throw new Error('openaiApiKey\x20is\x20required');const {content:_0x403f73}=await _0x40b91e({'apiKey':_0x461b45,'model':_0x36fed7,'messages':_0x3845e3,'baseUrl':_0x4b4640}),_0x322b14={'type':'openai','content':_0x403f73,'ts':Date['now']()};return this['onMessageCallback']({'metadata':{'sender':prefixId(this['appId'],_0x7d7b80),'timestamp':Date['now']()},'payload':new Payload(toUint8(JSON['stringify'](_0x322b14)))}),{'content':_0x403f73};}}
|
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(_0x549b45){if('string'==typeof _0x549b45)return[{'role':'user','content':_0x549b45}];if(Array['isArray'](_0x549b45)&&_0x549b45['length']>0x0)return _0x549b45['map'](_0x1bd942=>({'role':_0x1bd942['role']||'user','content':'string'==typeof _0x1bd942['content']?_0x1bd942['content']:String(_0x1bd942['content'])}));throw new Error('message\x20must\x20be\x20a\x20non-empty\x20string\x20or\x20array\x20of\x20{\x20role,\x20content\x20}');}export async function chat(_0x4135ff){var _0x35b38b,_0x3194f9,_0x24bb43,_0x49fa82,_0x3a1f5e,_0x211fa8;const {apiKey:_0x27f479,model:_0x5f2294=DEFAULT_MODEL,messages:_0x91dd46,baseUrl:_0x9bb085=DEFAULT_BASE_URL}=_0x4135ff;if(!_0x27f479||!_0x91dd46)throw new Error('openai.chat:\x20apiKey\x20and\x20messages\x20are\x20required');const _0x37bbf4=_0x9bb085['replace'](/\/$/,'')+'/v1/chat/completions',_0x47f799={'model':_0x5f2294,'messages':normalizeMessages(_0x91dd46),'stream':!0x1},_0x4c2fd8=await fetch(_0x37bbf4,{'method':'POST','headers':{'Content-Type':'application/json','Authorization':'Bearer\x20'+_0x27f479},'body':JSON['stringify'](_0x47f799)}),_0xc7c0a2=await _0x4c2fd8['json']();if(!_0x4c2fd8['ok']){const _0x433651=new Error((null===(_0x35b38b=null==_0xc7c0a2?void 0x0:_0xc7c0a2['error'])||void 0x0===_0x35b38b?void 0x0:_0x35b38b['message'])||'OpenAI\x20API\x20error:\x20'+_0x4c2fd8['status']);throw _0x433651['status']=_0x4c2fd8['status'],_0x433651['code']=null===(_0x3194f9=null==_0xc7c0a2?void 0x0:_0xc7c0a2['error'])||void 0x0===_0x3194f9?void 0x0:_0x3194f9['code'],_0x433651;}return{'content':null!==(_0x211fa8=null===(_0x3a1f5e=null===(_0x49fa82=null===(_0x24bb43=null==_0xc7c0a2?void 0x0:_0xc7c0a2['choices'])||void 0x0===_0x24bb43?void 0x0:_0x24bb43[0x0])||void 0x0===_0x49fa82?void 0x0:_0x49fa82['message'])||void 0x0===_0x3a1f5e?void 0x0:_0x3a1f5e['content'])&&void 0x0!==_0x211fa8?_0x211fa8:'','usage':null==_0xc7c0a2?void 0x0:_0xc7c0a2['usage'],'raw':_0xc7c0a2};}export async function chatStream(_0x54c1e4){var _0x25bd39,_0x4ae253,_0x37f353,_0xc8738c,_0x12d798;const {apiKey:_0x116852,model:_0x18ed51=DEFAULT_MODEL,messages:_0x135785,baseUrl:_0x4bb9b7=DEFAULT_BASE_URL,onChunk:_0x3d1ed9}=_0x54c1e4;if(!_0x116852||!_0x135785)throw new Error('openai.chatStream:\x20apiKey\x20and\x20messages\x20are\x20required');const _0x54d48=_0x4bb9b7['replace'](/\/$/,'')+'/v1/chat/completions',_0x594c34={'model':_0x18ed51,'messages':normalizeMessages(_0x135785),'stream':!0x0},_0x4642a6=await fetch(_0x54d48,{'method':'POST','headers':{'Content-Type':'application/json','Authorization':'Bearer\x20'+_0x116852},'body':JSON['stringify'](_0x594c34)});if(!_0x4642a6['ok']){const _0x3118a0=await _0x4642a6['json']()['catch'](()=>({})),_0x423ffc=new Error((null===(_0x25bd39=null==_0x3118a0?void 0x0:_0x3118a0['error'])||void 0x0===_0x25bd39?void 0x0:_0x25bd39['message'])||'OpenAI\x20API\x20error:\x20'+_0x4642a6['status']);throw _0x423ffc['status']=_0x4642a6['status'],_0x423ffc['code']=null===(_0x4ae253=null==_0x3118a0?void 0x0:_0x3118a0['error'])||void 0x0===_0x4ae253?void 0x0:_0x4ae253['code'],_0x423ffc;}const _0x51b0f3=_0x4642a6['body']['getReader'](),_0x5c9bbe=new TextDecoder();let _0x1fff73='',_0x5deedf='';for(;;){const {done:_0x23da21,value:_0x35f779}=await _0x51b0f3['read']();if(_0x23da21)break;_0x5deedf+=_0x5c9bbe['decode'](_0x35f779,{'stream':!0x0});const _0x27050b=_0x5deedf['split']('\x0a');_0x5deedf=_0x27050b['pop']()||'';for(const _0x1e2709 of _0x27050b){const _0x20d2a1=_0x1e2709['trim']();if(''!==_0x20d2a1&&'data:\x20[DONE]'!==_0x20d2a1&&_0x20d2a1['startsWith']('data:\x20'))try{const _0x26e2c1=JSON['parse'](_0x20d2a1['slice'](0x6)),_0x4368ce=null===(_0x12d798=null===(_0xc8738c=null===(_0x37f353=null==_0x26e2c1?void 0x0:_0x26e2c1['choices'])||void 0x0===_0x37f353?void 0x0:_0x37f353[0x0])||void 0x0===_0xc8738c?void 0x0:_0xc8738c['delta'])||void 0x0===_0x12d798?void 0x0:_0x12d798['content'];'string'==typeof _0x4368ce&&(_0x1fff73+=_0x4368ce,_0x3d1ed9&&_0x3d1ed9(_0x4368ce));}catch(_0x132412){}}}return{'content':_0x1fff73};}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
|
|
1
|
+
export class HttpTransport{constructor({url:_0xe79b9a}){this['url']=_0xe79b9a;}async['send'](_0x5ec065){const _0x212ac0=await fetch(''+this['url'],{'method':'POST','headers':{'Content-Type':'application/json'},'body':JSON['stringify'](_0x5ec065)});if(!_0x212ac0['ok']){const _0x3f213d=await _0x212ac0['text']();throw new Error('DNotifier\x20HTTP\x20error:\x20'+_0x3f213d);}return await _0x212ac0['json']();}['sendBinary'](){throw new Error('Binary\x20is\x20not\x20supported\x20over\x20HTTP\x20yet');}}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
|
|
1
|
+
import _0x14f923 from'events';import{decodePacket}from'../utils/frame.js';export class WebsocketTransport extends _0x14f923{constructor(_0x4641bf=null){if(super(),this['socket']=null,this['WebSocketImpl']=_0x4641bf||('undefined'!=typeof window?window['WebSocket']:null),!this['WebSocketImpl'])throw new Error('No\x20WebSocket\x20implementation\x20provided');}['connect'](_0x4eff3b){return new Promise((_0x5e50a0,_0x5e0e7c)=>{this['socket']=new this['WebSocketImpl'](_0x4eff3b),'undefined'!=typeof window&&(this['socket']['binaryType']='arrayBuffer'),this['_on']('open',()=>_0x5e50a0(!0x0)),this['_on']('error',_0x298a94=>{console['error']('WS\x20error',_0x298a94),_0x5e0e7c(_0x298a94);}),this['_on']('close',_0x184ba0=>{const _0x358d94=null==_0x184ba0?void 0x0:_0x184ba0['code'],_0x1a6f9e=null==_0x184ba0?void 0x0:_0x184ba0['reason'];this['emit']('close',{'code':_0x358d94,'reason':_0x1a6f9e});}),this['_on']('message',async(_0x5a8ffb,_0x20775d)=>{var _0x4bbb48,_0x201c19=null!==(_0x4bbb48=null==_0x5a8ffb?void 0x0:_0x5a8ffb['data'])&&void 0x0!==_0x4bbb48?_0x4bbb48:_0x5a8ffb;'undefined'!=typeof Blob&&_0x201c19 instanceof Blob&&(_0x201c19=await _0x201c19['arrayBuffer']());const _0x2a406f=decodePacket(_0x201c19);_0x2a406f&&this['emit']('message',_0x2a406f,_0x20775d);});});}['_on'](_0xed9eb6,_0x1667dc){this['socket']['on']?this['socket']['on'](_0xed9eb6,_0x1667dc):this['socket']['on'+_0xed9eb6]=_0x1667dc;}['send'](_0x2febdc){if(!this['isOpen']())throw new Error('WebSocket\x20not\x20connected');this['socket']['send'](_0x2febdc);}['sendBinary'](_0x1377a4){if(!this['isOpen']())throw new Error('WebSocket\x20not\x20connected');this['socket']['send'](_0x1377a4);}['isOpen'](){return this['socket']&&this['socket']['readyState']===this['WebSocketImpl']['OPEN'];}['close'](){var _0x55a9da;null===(_0x55a9da=this['socket'])||void 0x0===_0x55a9da||_0x55a9da['close']();}}
|
package/dist/utils/buffer.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
|
|
1
|
+
export function toUint8(_0x3ffda9){return'undefined'!=typeof Buffer?Buffer['from'](_0x3ffda9,'utf8'):new TextEncoder()['encode'](_0x3ffda9);}
|
package/dist/utils/frame.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
|
|
1
|
+
export function framePacket(_0x53f370,_0x30bd4c){const _0x3bf3c1=Buffer['from'](JSON['stringify'](_0x53f370)),_0x232671=Buffer['isBuffer'](_0x30bd4c)?_0x30bd4c:Buffer['from'](_0x30bd4c),_0x352e91=Buffer['alloc'](0x4+_0x3bf3c1['length']+0x4+_0x232671['length']);let _0x413781=0x0;return _0x352e91['writeUInt32BE'](_0x3bf3c1['length'],_0x413781),_0x413781+=0x4,_0x3bf3c1['copy'](_0x352e91,_0x413781),_0x413781+=_0x3bf3c1['length'],_0x352e91['writeUInt32BE'](_0x232671['length'],_0x413781),_0x413781+=0x4,_0x232671['copy'](_0x352e91,_0x413781),_0x352e91;}let internalBuffer=Buffer['alloc'](0x0);export function decodePacket(_0x22224a){try{Buffer['isBuffer'](_0x22224a)||(_0x22224a=Buffer['from'](_0x22224a)),internalBuffer=Buffer['concat']([internalBuffer,_0x22224a]);let _0x3628d8=0x0;if(internalBuffer['length']<0x4)return null;const _0xa39f12=internalBuffer['readUInt32BE'](_0x3628d8);if(_0x3628d8+=0x4,internalBuffer['length']<_0x3628d8+_0xa39f12)return null;const _0x52cbb1=internalBuffer['slice'](_0x3628d8,_0x3628d8+_0xa39f12),_0x12ea81=JSON['parse'](_0x52cbb1['toString']());if(_0x3628d8+=_0xa39f12,internalBuffer['length']<_0x3628d8+0x4)return null;const _0xeaf509=internalBuffer['readUInt32BE'](_0x3628d8);if(_0x3628d8+=0x4,internalBuffer['length']<_0x3628d8+_0xeaf509)return null;const _0x10a53d=internalBuffer['slice'](_0x3628d8,_0x3628d8+_0xeaf509);_0x3628d8+=_0xeaf509,internalBuffer=internalBuffer['slice'](_0x3628d8);let _0x51887f=_0x10a53d;if('text'===_0x12ea81['type'])try{_0x51887f=JSON['parse'](_0x10a53d['toString']('utf8'));}catch{_0x51887f=_0x10a53d;}return{'metadata':_0x12ea81,'data':_0x51887f};}catch(_0x35e765){return console['error']('decodePacket\x20error:',_0x35e765),null;}}
|
package/dist/utils/id.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
|
|
1
|
+
export const prefixId=(_0x208123,_0x26fc3e)=>_0x26fc3e['includes'](':')?_0x26fc3e:_0x208123+':'+_0x26fc3e;
|
package/dist/utils/payload.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
|
|
1
|
+
export class Payload{constructor(_0x376e7a){this['buffer']=_0x376e7a;}['raw'](){return this['buffer'];}['toString'](_0x4ce4ae='utf8'){return this['buffer']['toString'](_0x4ce4ae);}['toJSON'](_0x328f7f='utf8'){try{return JSON['parse'](this['buffer']['toString'](_0x328f7f));}catch(_0x2a7b85){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.13",
|
|
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"
|