@solarpunkltd/swarm-chat-js 6.1.3 → 6.1.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.esm.js +1 -1
- package/dist/index.js +1 -1
- package/dist/lib/waku.d.ts.map +1 -1
- package/dist/swarm-chat-umd.js +1 -1
- package/package.json +2 -2
package/dist/index.esm.js
CHANGED
|
@@ -37053,7 +37053,7 @@ class Waku {
|
|
|
37053
37053
|
} catch (b) {
|
|
37054
37054
|
this.errorHandler.handleError(b, "Waku2.handleMessageReceived");
|
|
37055
37055
|
}
|
|
37056
|
-
}
|
|
37056
|
+
};
|
|
37057
37057
|
}
|
|
37058
37058
|
async start() {
|
|
37059
37059
|
this.createProtobufSchema(), await this.createChannel();
|
package/dist/index.js
CHANGED
|
@@ -64,4 +64,4 @@ function print() { __p += __j.call(arguments, '') }
|
|
|
64
64
|
`;)Me++;return Me}function oe(){if($.length>0)return $.shift();if(M)return B();var pe,Me,$e,Pe,Ce,Re=h===0;do{if(h===v)return null;for(pe=!1;whitespaceRe.test($e=C(h));)if($e===`
|
|
65
65
|
`&&(Re=!0,++w),++h===v)return null;if(C(h)==="/"){if(++h===v)throw I("comment");if(C(h)==="/")if(u){if(Pe=h,Ce=!1,Z(h-1)){Ce=!0;do if(h=X(h),h===v||(h++,!Re))break;while(Z(h))}else h=Math.min(v,X(h)+1);Ce&&(N(Pe,h,Re),Re=!0),w++,pe=!0}else{for(Ce=C(Pe=h+1)==="/";C(++h)!==`
|
|
66
66
|
`;)if(h===v)return null;++h,Ce&&(N(Pe,h-1,Re),Re=!0),++w,pe=!0}else if(($e=C(h))==="*"){Pe=h+1,Ce=u||C(Pe)==="*";do{if($e===`
|
|
67
|
-
`&&++w,++h===v)throw I("comment");Me=$e,$e=C(h)}while(Me!=="*"||$e!=="/");++h,Ce&&(N(Pe,h-2,Re),Re=!0),pe=!0}else return"/"}}while(pe);var je=h;delimRe.lastIndex=0;var we=delimRe.test(C(je++));if(!we)for(;je<v&&!delimRe.test(C(je));)++je;var D=y.substring(h,h=je);return(D==='"'||D==="'")&&(M=D),D}function ue(pe){$.push(pe)}function le(){if(!$.length){var pe=oe();if(pe===null)return null;ue(pe)}return $[0]}function re(pe,Me){var $e=le(),Pe=$e===pe;if(Pe)return oe(),!0;if(!Me)throw I("token '"+$e+"', '"+pe+"' expected");return!1}function me(pe){var Me=null,$e;return pe===void 0?($e=E[w-1],delete E[w-1],$e&&(u||$e.type==="*"||$e.lineEmpty)&&(Me=$e.leading?$e.text:null)):(b<pe&&le(),$e=E[pe],delete E[pe],$e&&!$e.lineEmpty&&(u||$e.type==="/")&&(Me=$e.leading?null:$e.text)),Me}return Object.defineProperty({next:oe,peek:le,push:ue,skip:re,cmnt:me},"line",{get:function(){return w}})}var parse_1=parse;parse.filename=null;parse.defaults={keepCase:!1};var tokenize=tokenize_1,Root=requireRoot(),Type=requireType(),Field=requireField(),MapField=requireMapfield(),OneOf=requireOneof(),Enum=require_enum(),Service=requireService(),Method=requireMethod(),ReflectionObject=requireObject(),types=requireTypes(),util=requireUtil(),base10Re=/^[1-9][0-9]*$/,base10NegRe=/^-?[1-9][0-9]*$/,base16Re=/^0[x][0-9a-fA-F]+$/,base16NegRe=/^-?0[x][0-9a-fA-F]+$/,base8Re=/^0[0-7]+$/,base8NegRe=/^-?0[0-7]+$/,numberRe=/^(?![eE])[0-9]*(?:\.[0-9]*)?(?:[eE][+-]?[0-9]+)?$/,nameRe=/^[a-zA-Z_][a-zA-Z_0-9]*$/,typeRefRe=/^(?:\.?[a-zA-Z_][a-zA-Z_0-9]*)(?:\.[a-zA-Z_][a-zA-Z_0-9]*)*$/;function parse(y,u,h){u instanceof Root||(h=u,u=new Root),h||(h=parse.defaults);var v=h.preferTrailingComment||!1,w=tokenize(y,h.alternateCommentMode||!1),b=w.next,E=w.push,$=w.peek,M=w.skip,I=w.cmnt,B=!0,C,N,Z,X="proto2",oe=u,ue=[],le={},re=h.keepCase?function(ie){return ie}:util.camelCase;function me(){ue.forEach(ie=>{ie._edition=X,Object.keys(le).forEach(be=>{ie.getOption(be)===void 0&&ie.setOption(be,le[be],!0)})})}function pe(ie,be,Ie){var Le=parse.filename;return Ie||(parse.filename=null),Error("illegal "+(be||"token")+" '"+ie+"' ("+(Le?Le+", ":"")+"line "+w.line+")")}function Me(){var ie=[],be;do{if((be=b())!=='"'&&be!=="'")throw pe(be);ie.push(b()),M(be),be=$()}while(be==='"'||be==="'");return ie.join("")}function $e(ie){var be=b();switch(be){case"'":case'"':return E(be),Me();case"true":case"TRUE":return!0;case"false":case"FALSE":return!1}try{return Ce(be,!0)}catch{if(typeRefRe.test(be))return be;throw pe(be,"value")}}function Pe(ie,be){var Ie,Le;do if(be&&((Ie=$())==='"'||Ie==="'")){var Fe=Me();if(ie.push(Fe),X>=2023)throw pe(Fe,"id")}else try{ie.push([Le=Re(b()),M("to",!0)?Re(b()):Le])}catch(tt){if(be&&typeRefRe.test(Ie)&&X>=2023)ie.push(Ie);else throw tt}while(M(",",!0));var He={options:void 0};He.setOption=function(tt,Ne){this.options===void 0&&(this.options={}),this.options[tt]=Ne},L(He,function(Ne){if(Ne==="option")he(He,Ne),M(";");else throw pe(Ne)},function(){fe(He)})}function Ce(ie,be){var Ie=1;switch(ie.charAt(0)==="-"&&(Ie=-1,ie=ie.substring(1)),ie){case"inf":case"INF":case"Inf":return Ie*(1/0);case"nan":case"NAN":case"Nan":case"NaN":return NaN;case"0":return 0}if(base10Re.test(ie))return Ie*parseInt(ie,10);if(base16Re.test(ie))return Ie*parseInt(ie,16);if(base8Re.test(ie))return Ie*parseInt(ie,8);if(numberRe.test(ie))return Ie*parseFloat(ie);throw pe(ie,"number",be)}function Re(ie,be){switch(ie){case"max":case"MAX":case"Max":return 536870911;case"0":return 0}if(!be&&ie.charAt(0)==="-")throw pe(ie,"id");if(base10NegRe.test(ie))return parseInt(ie,10);if(base16NegRe.test(ie))return parseInt(ie,16);if(base8NegRe.test(ie))return parseInt(ie,8);throw pe(ie,"id")}function je(){if(C!==void 0)throw pe("package");if(C=b(),!typeRefRe.test(C))throw pe(C,"name");oe=oe.define(C),M(";")}function we(){var ie=$(),be;switch(ie){case"weak":be=Z||(Z=[]),b();break;case"public":b();default:be=N||(N=[]);break}ie=Me(),M(";"),be.push(ie)}function D(){if(M("="),X=Me(),X<2023)throw pe(X,"syntax");M(";")}function q(){if(M("="),X=Me(),!["2023"].includes(X))throw pe(X,"edition");M(";")}function O(ie,be){switch(be){case"option":return he(ie,be),M(";"),!0;case"message":return Q(ie,be),!0;case"enum":return ee(ie,be),!0;case"service":return ye(ie,be),!0;case"extend":return ae(ie,be),!0}return!1}function L(ie,be,Ie){var Le=w.line;if(ie&&(typeof ie.comment!="string"&&(ie.comment=I()),ie.filename=parse.filename),M("{",!0)){for(var Fe;(Fe=b())!=="}";)be(Fe);M(";",!0)}else Ie&&Ie(),M(";"),ie&&(typeof ie.comment!="string"||v)&&(ie.comment=I(Le)||ie.comment)}function Q(ie,be){if(!nameRe.test(be=b()))throw pe(be,"type name");var Ie=new Type(be);L(Ie,function(Fe){if(!O(Ie,Fe))switch(Fe){case"map":te(Ie);break;case"required":if(X!=="proto2")throw pe(Fe);case"repeated":j(Ie,Fe);break;case"optional":if(X==="proto3")j(Ie,"proto3_optional");else{if(X!=="proto2")throw pe(Fe);j(Ie,"optional")}break;case"oneof":F(Ie,Fe);break;case"extensions":Pe(Ie.extensions||(Ie.extensions=[]));break;case"reserved":Pe(Ie.reserved||(Ie.reserved=[]),!0);break;default:if(X==="proto2"||!typeRefRe.test(Fe))throw pe(Fe);E(Fe),j(Ie,"optional");break}}),ie.add(Ie),ie===oe&&ue.push(Ie)}function j(ie,be,Ie){var Le=b();if(Le==="group"){ne(ie,be);return}for(;Le.endsWith(".")||$().startsWith(".");)Le+=b();if(!typeRefRe.test(Le))throw pe(Le,"type");var Fe=b();if(!nameRe.test(Fe))throw pe(Fe,"name");Fe=re(Fe),M("=");var He=new Field(Fe,Re(b()),Le,be,Ie);if(L(He,function(nt){if(nt==="option")he(He,nt),M(";");else throw pe(nt)},function(){fe(He)}),be==="proto3_optional"){var tt=new OneOf("_"+Fe);He.setOption("proto3_optional",!0),tt.add(He),ie.add(tt)}else ie.add(He);ie===oe&&ue.push(He)}function ne(ie,be){if(X>=2023)throw pe("group");var Ie=b();if(!nameRe.test(Ie))throw pe(Ie,"name");var Le=util.lcFirst(Ie);Ie===Le&&(Ie=util.ucFirst(Ie)),M("=");var Fe=Re(b()),He=new Type(Ie);He.group=!0;var tt=new Field(Le,Fe,Ie,be);tt.filename=parse.filename,L(He,function(nt){switch(nt){case"option":he(He,nt),M(";");break;case"required":case"repeated":j(He,nt);break;case"optional":X==="proto3"?j(He,"proto3_optional"):j(He,"optional");break;case"message":Q(He,nt);break;case"enum":ee(He,nt);break;case"reserved":Pe(He.reserved||(He.reserved=[]),!0);break;default:throw pe(nt)}}),ie.add(He).add(tt)}function te(ie){M("<");var be=b();if(types.mapKey[be]===void 0)throw pe(be,"type");M(",");var Ie=b();if(!typeRefRe.test(Ie))throw pe(Ie,"type");M(">");var Le=b();if(!nameRe.test(Le))throw pe(Le,"name");M("=");var Fe=new MapField(re(Le),Re(b()),be,Ie);L(Fe,function(tt){if(tt==="option")he(Fe,tt),M(";");else throw pe(tt)},function(){fe(Fe)}),ie.add(Fe)}function F(ie,be){if(!nameRe.test(be=b()))throw pe(be,"name");var Ie=new OneOf(re(be));L(Ie,function(Fe){Fe==="option"?(he(Ie,Fe),M(";")):(E(Fe),j(Ie,"optional"))}),ie.add(Ie)}function ee(ie,be){if(!nameRe.test(be=b()))throw pe(be,"name");var Ie=new Enum(be);L(Ie,function(Fe){switch(Fe){case"option":he(Ie,Fe),M(";");break;case"reserved":Pe(Ie.reserved||(Ie.reserved=[]),!0),Ie.reserved===void 0&&(Ie.reserved=[]);break;default:U(Ie,Fe)}}),ie.add(Ie),ie===oe&&ue.push(Ie)}function U(ie,be){if(!nameRe.test(be))throw pe(be,"name");M("=");var Ie=Re(b(),!0),Le={options:void 0};Le.getOption=function(Fe){return this.options[Fe]},Le.setOption=function(Fe,He){ReflectionObject.prototype.setOption.call(Le,Fe,He)},Le.setParsedOption=function(){},L(Le,function(He){if(He==="option")he(Le,He),M(";");else throw pe(He)},function(){fe(Le)}),ie.add(be,Ie,Le.comment,Le.parsedOptions||Le.options)}function he(ie,be){var Ie,Le,Fe=!0;for(be==="option"&&(be=b());be!=="=";){if(be==="("){var He=b();M(")"),be="("+He+")"}if(Fe){if(Fe=!1,be.includes(".")&&!be.includes("(")){var tt=be.split(".");Ie=tt[0]+".",be=tt[1];continue}Ie=be}else Le=Le?Le+=be:be;be=b()}var Ne=Le?Ie.concat(Le):Ie,nt=Oe(ie,Ne);Le=Le&&Le[0]==="."?Le.slice(1):Le,Ie=Ie&&Ie[Ie.length-1]==="."?Ie.slice(0,-1):Ie,Ae(ie,Ie,nt,Le)}function Oe(ie,be){if(M("{",!0)){for(var Ie={};!M("}",!0);){if(!nameRe.test(de=b()))throw pe(de,"name");if(de===null)throw pe(de,"end of input");var Le,Fe=de;if(M(":",!0),$()==="{")Le=Oe(ie,be+"."+de);else if($()==="["){Le=[];var He;if(M("[",!0)){do He=$e(),Le.push(He);while(M(",",!0));M("]"),typeof He<"u"&&Ve(ie,be+"."+de,He)}}else Le=$e(),Ve(ie,be+"."+de,Le);var tt=Ie[Fe];tt&&(Le=[].concat(tt).concat(Le)),Ie[Fe]=Le,M(",",!0),M(";",!0)}return Ie}var Ne=$e();return Ve(ie,be,Ne),Ne}function Ve(ie,be,Ie){if(oe===ie&&/^features\./.test(be)){le[be]=Ie;return}ie.setOption&&ie.setOption(be,Ie)}function Ae(ie,be,Ie,Le){ie.setParsedOption&&ie.setParsedOption(be,Ie,Le)}function fe(ie){if(M("[",!0)){do he(ie,"option");while(M(",",!0));M("]")}return ie}function ye(ie,be){if(!nameRe.test(be=b()))throw pe(be,"service name");var Ie=new Service(be);L(Ie,function(Fe){if(!O(Ie,Fe))if(Fe==="rpc")Be(Ie,Fe);else throw pe(Fe)}),ie.add(Ie),ie===oe&&ue.push(Ie)}function Be(ie,be){var Ie=I(),Le=be;if(!nameRe.test(be=b()))throw pe(be,"name");var Fe=be,He,tt,Ne,nt;if(M("("),M("stream",!0)&&(tt=!0),!typeRefRe.test(be=b())||(He=be,M(")"),M("returns"),M("("),M("stream",!0)&&(nt=!0),!typeRefRe.test(be=b())))throw pe(be);Ne=be,M(")");var it=new Method(Fe,Le,He,Ne,tt,nt);it.comment=Ie,L(it,function(ut){if(ut==="option")he(it,ut),M(";");else throw pe(ut)}),ie.add(it)}function ae(ie,be){if(!typeRefRe.test(be=b()))throw pe(be,"reference");var Ie=be;L(null,function(Fe){switch(Fe){case"required":case"repeated":j(ie,Fe,Ie);break;case"optional":X==="proto3"?j(ie,"proto3_optional",Ie):j(ie,"optional",Ie);break;default:if(X==="proto2"||!typeRefRe.test(Fe))throw pe(Fe);E(Fe),j(ie,"optional",Ie);break}})}for(var de;(de=b())!==null;)switch(de){case"package":if(!B)throw pe(de);je();break;case"import":if(!B)throw pe(de);we();break;case"syntax":if(!B)throw pe(de);D();break;case"edition":if(!B)throw pe(de);q();break;case"option":he(oe,de),M(";",!0);break;default:if(O(oe,de)){B=!1;continue}throw pe(de)}return me(),parse.filename=null,{package:C,imports:N,weakImports:Z,root:u}}var common_1=common,commonRe=/\/|\./;function common(y,u){commonRe.test(y)||(y="google/protobuf/"+y+".proto",u={nested:{google:{nested:{protobuf:{nested:u}}}}}),common[y]=u}common("any",{Any:{fields:{type_url:{type:"string",id:1},value:{type:"bytes",id:2}}}});var timeType;common("duration",{Duration:timeType={fields:{seconds:{type:"int64",id:1},nanos:{type:"int32",id:2}}}});common("timestamp",{Timestamp:timeType});common("empty",{Empty:{fields:{}}});common("struct",{Struct:{fields:{fields:{keyType:"string",type:"Value",id:1}}},Value:{oneofs:{kind:{oneof:["nullValue","numberValue","stringValue","boolValue","structValue","listValue"]}},fields:{nullValue:{type:"NullValue",id:1},numberValue:{type:"double",id:2},stringValue:{type:"string",id:3},boolValue:{type:"bool",id:4},structValue:{type:"Struct",id:5},listValue:{type:"ListValue",id:6}}},NullValue:{values:{NULL_VALUE:0}},ListValue:{fields:{values:{rule:"repeated",type:"Value",id:1}}}});common("wrappers",{DoubleValue:{fields:{value:{type:"double",id:1}}},FloatValue:{fields:{value:{type:"float",id:1}}},Int64Value:{fields:{value:{type:"int64",id:1}}},UInt64Value:{fields:{value:{type:"uint64",id:1}}},Int32Value:{fields:{value:{type:"int32",id:1}}},UInt32Value:{fields:{value:{type:"uint32",id:1}}},BoolValue:{fields:{value:{type:"bool",id:1}}},StringValue:{fields:{value:{type:"string",id:1}}},BytesValue:{fields:{value:{type:"bytes",id:1}}}});common("field_mask",{FieldMask:{fields:{paths:{rule:"repeated",type:"string",id:1}}}});common.get=function y(u){return common[u]||null};var protobuf$1=src.exports=indexLightExports;protobuf$1.build="full";protobuf$1.tokenize=tokenize_1;protobuf$1.parse=parse_1;protobuf$1.common=common_1;protobuf$1.Root._configure(protobuf$1.Type,protobuf$1.parse,protobuf$1.common);var srcExports=src.exports,protobufjs=srcExports;const protobuf=getDefaultExportFromCjs$1(protobufjs);class Waku{constructor(u,h,v){this.node=u,this.chatTopic=h,this.onMessage=v,this.logger=Logger$1.getInstance(),this.errorHandler=ErrorHandler.getInstance(),this.reliableChannel=null,this.decoder=null,this.messagePayloadType=null,this.messageReceivedListener=null,this.senderId=crypto$1.randomBytes(8).toString("hex"),this.handleMessageReceived=async({payload:w})=>{try{if(!w){this.logger.warn("Received Waku message without payload");return}if(!this.messagePayloadType)throw new Error("Protobuf schema not initialized");const b=this.messagePayloadType.decode(w),E=this.messagePayloadType.toObject(b,{longs:String,enums:String,defaults:!0});if(!E.message){this.logger.warn("Decoded object has no message field");return}let $=E.message.additionalProps;if($&&typeof $=="string")try{$=JSON.parse($)}catch{this.logger.warn("Failed to parse additionalProps as JSON:",$)}const M={...E.message,timestamp:Number(E.message.timestamp),additionalProps:$};if(!(M!=null&&M.id)){this.logger.warn("Received invalid message structure via Waku");return}this.onMessage(M)}catch(b){this.errorHandler.handleError(b,"Waku2.handleMessageReceived")}},this.createProtobufSchema()}async start(){this.createProtobufSchema(),await this.createChannel()}createProtobufSchema(){const u=new protobuf.Type("MessageData").add(new protobuf.Field("id",1,"string")).add(new protobuf.Field("targetMessageId",2,"string","optional")).add(new protobuf.Field("type",3,"string")).add(new protobuf.Field("message",4,"string")).add(new protobuf.Field("username",5,"string")).add(new protobuf.Field("address",6,"string")).add(new protobuf.Field("timestamp",7,"uint64")).add(new protobuf.Field("signature",8,"string")).add(new protobuf.Field("index",9,"uint32")).add(new protobuf.Field("chatTopic",10,"string")).add(new protobuf.Field("userTopic",11,"string")).add(new protobuf.Field("additionalProps",12,"string","optional")),h=new protobuf.Type("MessageStateRef").add(new protobuf.Field("reference",1,"string")).add(new protobuf.Field("timestamp",2,"uint64"));this.messagePayloadType=new protobuf.Type("MessagePayload").add(u).add(h).add(new protobuf.Field("message",1,"MessageData")).add(new protobuf.Field("messageStateRefs",2,"MessageStateRef","repeated")),this.logger.info("Protobuf schema created for chat messages")}async createChannel(){if(!this.node)throw new Error("Waku node not initialized");const u=`/solarpunk-msrs-chat/1/${this.chatTopic}/proto`,h=`chat-channel-${this.chatTopic}`,v=this.node.createEncoder({contentTopic:u}),w=this.decoder=this.node.createDecoder({contentTopic:u});this.reliableChannel=await ReliableChannel.create(this.node,h,this.senderId,v,w,{retrieveFrequencyMs:3e3,queryOnConnect:!1}),this.setupChannelEventListeners(this.reliableChannel),this.logger.info(`Created reliable channel for topic: ${this.chatTopic}`)}setupChannelEventListeners(u){this.messageReceivedListener=h=>{this.handleMessageReceived(h.detail)},u.addEventListener("message-received",this.messageReceivedListener)}async stop(){this.reliableChannel&&this.messageReceivedListener&&this.decoder&&(this.reliableChannel.removeEventListener("message-received",this.messageReceivedListener),this.messageReceivedListener=null,await this.reliableChannel.stop(),this.logger.info("Waku reliable channel stopped"))}}class SwarmChat{constructor(u){this.waku=null,this.logger=Logger$1.getInstance(),this.errorHandler=ErrorHandler.getInstance(),this.gsocIndex=null,this.fetchProcessRunning=!1,this.stopFetch=!1;const h=new beeJs.PrivateKey(remove0x(u.user.privateKey));this.userDetails={privateKey:u.user.privateKey,ownAddress:h.publicKey().address().toString(),nickname:u.user.nickname,ownIndex:-1},this.swarmSettings={bee:new beeJs.Bee(u.infra.beeUrl),beeUrl:u.infra.beeUrl,stamp:u.infra.stamp||"0x0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef",enveloped:u.infra.enveloped,gsocTopic:u.infra.gsocTopic,gsocResourceId:u.infra.gsocResourceId,chatTopic:u.infra.chatTopic,chatAddress:u.infra.chatAddress,wakuNode:u.infra.wakuNode},this.emitter=new EventEmitter$2,this.utils=new SwarmChatUtils(this.userDetails,this.swarmSettings),this.history=new SwarmHistory(this.utils,this.emitter)}async start(){await this.init(),await this.startMessageFetchProcess()}async startMessageFetchProcess(){const{wakuNode:u}=this.swarmSettings;u?await this.startWakuMessageFetch(u):await this.startPollingMessageFetch()}async stop(){this.emitter.cleanAll(),this.stopPollingMessageFetch(),this.history.cleanup(),this.waku&&(await this.waku.stop(),this.waku=null)}async startWakuMessageFetch(u){this.logger.info("Waku is enabled");const h=this.swarmSettings.chatTopic;this.waku=new Waku(u,h,v=>{this.emitter.emit(EVENTS.MESSAGE_RECEIVED,v)}),await this.waku.start()}getEmitter(){return this.emitter}orderMessages(u){return this.utils.orderMessages(u)}async sendMessage(u,h,v,w,b){const E=this.userDetails.ownIndex===-1?0:this.userDetails.ownIndex+1,$={id:w||v4(),username:this.userDetails.nickname,address:this.userDetails.ownAddress,chatTopic:this.swarmSettings.chatTopic,userTopic:this.utils.generateUserOwnedFeedId(this.swarmSettings.chatTopic,this.userDetails.ownAddress),signature:this.getSignature(u),timestamp:Date.now(),index:E,type:h,targetMessageId:v,message:u,additionalProps:b},M=validateMessageWithAdditionalProperties($);if(!M.isValid){const I=`Invalid message: ${M.errors.join(", ")}`;throw this.logger.error(I),new Error(I)}try{this.emitter.emit(EVENTS.MESSAGE_REQUEST_INITIATED,$),await this.utils.writeOwnFeedDataByIndex(E,JSON.stringify($)),this.userDetails.ownIndex=E,this.emitter.emit(EVENTS.MESSAGE_REQUEST_UPLOADED,$),await this.broadcastUserMessage($)}catch(I){this.emitter.emit(EVENTS.MESSAGE_REQUEST_ERROR,$),this.errorHandler.handleError(I,"Chat.sendMessage")}}async fetchPreviousMessages(){try{return this.emitter.emit(EVENTS.LOADING_PREVIOUS_MESSAGES,!0),await this.history.fetchPreviousMessageState()}finally{this.emitter.emit(EVENTS.LOADING_PREVIOUS_MESSAGES,!1)}}hasPreviousMessages(){return this.history.hasPreviousMessages()}async retrySendMessage(u){this.sendMessage(u.message,u.type,u.targetMessageId,u.id,u.additionalProps)}async retryBroadcastUserMessage(u){await this.broadcastUserMessage(u)}async init(){try{this.emitter.emit(EVENTS.LOADING_INIT,!0);const[u,h]=await Promise.allSettled([this.initOwnIndex(),this.history.init()]);if(u.status==="rejected")throw u.reason;h.status==="fulfilled"&&(this.gsocIndex=h.value),this.emitter.emit(EVENTS.LOADING_INIT,!1)}catch(u){this.errorHandler.handleError(u,"Chat.initSelfState"),this.emitter.emit(EVENTS.CRITICAL_ERROR,u)}}async initOwnIndex(){const{latestIndex:v}=await retryAwaitableAsync(()=>this.utils.getOwnLatestFeedIndex(),10,1e3);this.userDetails.ownIndex=v}async fetchLatestMessage(){try{if(!this.gsocIndex)return;const u=beeJs.Topic.fromString(this.swarmSettings.chatTopic),h=makeFeedIdentifier(u,this.gsocIndex),v=await this.utils.rawSocDownload(this.swarmSettings.chatAddress,h.toString()),w=JSON.parse(v);if(!validateGsocMessage(w)){this.logger.warn("Invalid GSOC message during fetching");return}this.emitter.emit(EVENTS.MESSAGE_RECEIVED,w.message),this.gsocIndex=this.gsocIndex.next()}catch(u){if(this.utils.isNotFoundError(u))return;this.errorHandler.handleError(u,"Chat.fetchLatestMessage")}}async broadcastUserMessage(u){try{return retryAwaitableAsync(()=>this.utils.sendMessageToGsoc(JSON.stringify(u)))}catch(h){this.errorHandler.handleError(h,"Chat.broadcastUserMessage")}}getSignature(u){const{ownAddress:h,privateKey:v,nickname:w}=this.userDetails,b=new beeJs.EthAddress(h).toString(),E=new beeJs.PrivateKey(v);if(E.publicKey().address().toString()!==b)throw new Error("The provided address does not match the address derived from the private key");const M=Date.now();return E.sign(JSON.stringify({username:w,address:b,message:u,timestamp:M})).toHex()}async startPollingMessageFetch(){if(this.fetchProcessRunning)return;this.fetchProcessRunning=!0,this.stopFetch=!1;const u=async()=>{if(this.stopFetch){this.fetchProcessRunning=!1;return}await this.fetchLatestMessage(),setTimeout(u,200)};u()}stopPollingMessageFetch(){this.stopFetch=!0}}exports.EVENTS=EVENTS;exports.MessageType=MessageType;exports.SwarmChat=SwarmChat;
|
|
67
|
+
`&&++w,++h===v)throw I("comment");Me=$e,$e=C(h)}while(Me!=="*"||$e!=="/");++h,Ce&&(N(Pe,h-2,Re),Re=!0),pe=!0}else return"/"}}while(pe);var je=h;delimRe.lastIndex=0;var we=delimRe.test(C(je++));if(!we)for(;je<v&&!delimRe.test(C(je));)++je;var D=y.substring(h,h=je);return(D==='"'||D==="'")&&(M=D),D}function ue(pe){$.push(pe)}function le(){if(!$.length){var pe=oe();if(pe===null)return null;ue(pe)}return $[0]}function re(pe,Me){var $e=le(),Pe=$e===pe;if(Pe)return oe(),!0;if(!Me)throw I("token '"+$e+"', '"+pe+"' expected");return!1}function me(pe){var Me=null,$e;return pe===void 0?($e=E[w-1],delete E[w-1],$e&&(u||$e.type==="*"||$e.lineEmpty)&&(Me=$e.leading?$e.text:null)):(b<pe&&le(),$e=E[pe],delete E[pe],$e&&!$e.lineEmpty&&(u||$e.type==="/")&&(Me=$e.leading?null:$e.text)),Me}return Object.defineProperty({next:oe,peek:le,push:ue,skip:re,cmnt:me},"line",{get:function(){return w}})}var parse_1=parse;parse.filename=null;parse.defaults={keepCase:!1};var tokenize=tokenize_1,Root=requireRoot(),Type=requireType(),Field=requireField(),MapField=requireMapfield(),OneOf=requireOneof(),Enum=require_enum(),Service=requireService(),Method=requireMethod(),ReflectionObject=requireObject(),types=requireTypes(),util=requireUtil(),base10Re=/^[1-9][0-9]*$/,base10NegRe=/^-?[1-9][0-9]*$/,base16Re=/^0[x][0-9a-fA-F]+$/,base16NegRe=/^-?0[x][0-9a-fA-F]+$/,base8Re=/^0[0-7]+$/,base8NegRe=/^-?0[0-7]+$/,numberRe=/^(?![eE])[0-9]*(?:\.[0-9]*)?(?:[eE][+-]?[0-9]+)?$/,nameRe=/^[a-zA-Z_][a-zA-Z_0-9]*$/,typeRefRe=/^(?:\.?[a-zA-Z_][a-zA-Z_0-9]*)(?:\.[a-zA-Z_][a-zA-Z_0-9]*)*$/;function parse(y,u,h){u instanceof Root||(h=u,u=new Root),h||(h=parse.defaults);var v=h.preferTrailingComment||!1,w=tokenize(y,h.alternateCommentMode||!1),b=w.next,E=w.push,$=w.peek,M=w.skip,I=w.cmnt,B=!0,C,N,Z,X="proto2",oe=u,ue=[],le={},re=h.keepCase?function(ie){return ie}:util.camelCase;function me(){ue.forEach(ie=>{ie._edition=X,Object.keys(le).forEach(be=>{ie.getOption(be)===void 0&&ie.setOption(be,le[be],!0)})})}function pe(ie,be,Ie){var Le=parse.filename;return Ie||(parse.filename=null),Error("illegal "+(be||"token")+" '"+ie+"' ("+(Le?Le+", ":"")+"line "+w.line+")")}function Me(){var ie=[],be;do{if((be=b())!=='"'&&be!=="'")throw pe(be);ie.push(b()),M(be),be=$()}while(be==='"'||be==="'");return ie.join("")}function $e(ie){var be=b();switch(be){case"'":case'"':return E(be),Me();case"true":case"TRUE":return!0;case"false":case"FALSE":return!1}try{return Ce(be,!0)}catch{if(typeRefRe.test(be))return be;throw pe(be,"value")}}function Pe(ie,be){var Ie,Le;do if(be&&((Ie=$())==='"'||Ie==="'")){var Fe=Me();if(ie.push(Fe),X>=2023)throw pe(Fe,"id")}else try{ie.push([Le=Re(b()),M("to",!0)?Re(b()):Le])}catch(tt){if(be&&typeRefRe.test(Ie)&&X>=2023)ie.push(Ie);else throw tt}while(M(",",!0));var He={options:void 0};He.setOption=function(tt,Ne){this.options===void 0&&(this.options={}),this.options[tt]=Ne},L(He,function(Ne){if(Ne==="option")he(He,Ne),M(";");else throw pe(Ne)},function(){fe(He)})}function Ce(ie,be){var Ie=1;switch(ie.charAt(0)==="-"&&(Ie=-1,ie=ie.substring(1)),ie){case"inf":case"INF":case"Inf":return Ie*(1/0);case"nan":case"NAN":case"Nan":case"NaN":return NaN;case"0":return 0}if(base10Re.test(ie))return Ie*parseInt(ie,10);if(base16Re.test(ie))return Ie*parseInt(ie,16);if(base8Re.test(ie))return Ie*parseInt(ie,8);if(numberRe.test(ie))return Ie*parseFloat(ie);throw pe(ie,"number",be)}function Re(ie,be){switch(ie){case"max":case"MAX":case"Max":return 536870911;case"0":return 0}if(!be&&ie.charAt(0)==="-")throw pe(ie,"id");if(base10NegRe.test(ie))return parseInt(ie,10);if(base16NegRe.test(ie))return parseInt(ie,16);if(base8NegRe.test(ie))return parseInt(ie,8);throw pe(ie,"id")}function je(){if(C!==void 0)throw pe("package");if(C=b(),!typeRefRe.test(C))throw pe(C,"name");oe=oe.define(C),M(";")}function we(){var ie=$(),be;switch(ie){case"weak":be=Z||(Z=[]),b();break;case"public":b();default:be=N||(N=[]);break}ie=Me(),M(";"),be.push(ie)}function D(){if(M("="),X=Me(),X<2023)throw pe(X,"syntax");M(";")}function q(){if(M("="),X=Me(),!["2023"].includes(X))throw pe(X,"edition");M(";")}function O(ie,be){switch(be){case"option":return he(ie,be),M(";"),!0;case"message":return Q(ie,be),!0;case"enum":return ee(ie,be),!0;case"service":return ye(ie,be),!0;case"extend":return ae(ie,be),!0}return!1}function L(ie,be,Ie){var Le=w.line;if(ie&&(typeof ie.comment!="string"&&(ie.comment=I()),ie.filename=parse.filename),M("{",!0)){for(var Fe;(Fe=b())!=="}";)be(Fe);M(";",!0)}else Ie&&Ie(),M(";"),ie&&(typeof ie.comment!="string"||v)&&(ie.comment=I(Le)||ie.comment)}function Q(ie,be){if(!nameRe.test(be=b()))throw pe(be,"type name");var Ie=new Type(be);L(Ie,function(Fe){if(!O(Ie,Fe))switch(Fe){case"map":te(Ie);break;case"required":if(X!=="proto2")throw pe(Fe);case"repeated":j(Ie,Fe);break;case"optional":if(X==="proto3")j(Ie,"proto3_optional");else{if(X!=="proto2")throw pe(Fe);j(Ie,"optional")}break;case"oneof":F(Ie,Fe);break;case"extensions":Pe(Ie.extensions||(Ie.extensions=[]));break;case"reserved":Pe(Ie.reserved||(Ie.reserved=[]),!0);break;default:if(X==="proto2"||!typeRefRe.test(Fe))throw pe(Fe);E(Fe),j(Ie,"optional");break}}),ie.add(Ie),ie===oe&&ue.push(Ie)}function j(ie,be,Ie){var Le=b();if(Le==="group"){ne(ie,be);return}for(;Le.endsWith(".")||$().startsWith(".");)Le+=b();if(!typeRefRe.test(Le))throw pe(Le,"type");var Fe=b();if(!nameRe.test(Fe))throw pe(Fe,"name");Fe=re(Fe),M("=");var He=new Field(Fe,Re(b()),Le,be,Ie);if(L(He,function(nt){if(nt==="option")he(He,nt),M(";");else throw pe(nt)},function(){fe(He)}),be==="proto3_optional"){var tt=new OneOf("_"+Fe);He.setOption("proto3_optional",!0),tt.add(He),ie.add(tt)}else ie.add(He);ie===oe&&ue.push(He)}function ne(ie,be){if(X>=2023)throw pe("group");var Ie=b();if(!nameRe.test(Ie))throw pe(Ie,"name");var Le=util.lcFirst(Ie);Ie===Le&&(Ie=util.ucFirst(Ie)),M("=");var Fe=Re(b()),He=new Type(Ie);He.group=!0;var tt=new Field(Le,Fe,Ie,be);tt.filename=parse.filename,L(He,function(nt){switch(nt){case"option":he(He,nt),M(";");break;case"required":case"repeated":j(He,nt);break;case"optional":X==="proto3"?j(He,"proto3_optional"):j(He,"optional");break;case"message":Q(He,nt);break;case"enum":ee(He,nt);break;case"reserved":Pe(He.reserved||(He.reserved=[]),!0);break;default:throw pe(nt)}}),ie.add(He).add(tt)}function te(ie){M("<");var be=b();if(types.mapKey[be]===void 0)throw pe(be,"type");M(",");var Ie=b();if(!typeRefRe.test(Ie))throw pe(Ie,"type");M(">");var Le=b();if(!nameRe.test(Le))throw pe(Le,"name");M("=");var Fe=new MapField(re(Le),Re(b()),be,Ie);L(Fe,function(tt){if(tt==="option")he(Fe,tt),M(";");else throw pe(tt)},function(){fe(Fe)}),ie.add(Fe)}function F(ie,be){if(!nameRe.test(be=b()))throw pe(be,"name");var Ie=new OneOf(re(be));L(Ie,function(Fe){Fe==="option"?(he(Ie,Fe),M(";")):(E(Fe),j(Ie,"optional"))}),ie.add(Ie)}function ee(ie,be){if(!nameRe.test(be=b()))throw pe(be,"name");var Ie=new Enum(be);L(Ie,function(Fe){switch(Fe){case"option":he(Ie,Fe),M(";");break;case"reserved":Pe(Ie.reserved||(Ie.reserved=[]),!0),Ie.reserved===void 0&&(Ie.reserved=[]);break;default:U(Ie,Fe)}}),ie.add(Ie),ie===oe&&ue.push(Ie)}function U(ie,be){if(!nameRe.test(be))throw pe(be,"name");M("=");var Ie=Re(b(),!0),Le={options:void 0};Le.getOption=function(Fe){return this.options[Fe]},Le.setOption=function(Fe,He){ReflectionObject.prototype.setOption.call(Le,Fe,He)},Le.setParsedOption=function(){},L(Le,function(He){if(He==="option")he(Le,He),M(";");else throw pe(He)},function(){fe(Le)}),ie.add(be,Ie,Le.comment,Le.parsedOptions||Le.options)}function he(ie,be){var Ie,Le,Fe=!0;for(be==="option"&&(be=b());be!=="=";){if(be==="("){var He=b();M(")"),be="("+He+")"}if(Fe){if(Fe=!1,be.includes(".")&&!be.includes("(")){var tt=be.split(".");Ie=tt[0]+".",be=tt[1];continue}Ie=be}else Le=Le?Le+=be:be;be=b()}var Ne=Le?Ie.concat(Le):Ie,nt=Oe(ie,Ne);Le=Le&&Le[0]==="."?Le.slice(1):Le,Ie=Ie&&Ie[Ie.length-1]==="."?Ie.slice(0,-1):Ie,Ae(ie,Ie,nt,Le)}function Oe(ie,be){if(M("{",!0)){for(var Ie={};!M("}",!0);){if(!nameRe.test(de=b()))throw pe(de,"name");if(de===null)throw pe(de,"end of input");var Le,Fe=de;if(M(":",!0),$()==="{")Le=Oe(ie,be+"."+de);else if($()==="["){Le=[];var He;if(M("[",!0)){do He=$e(),Le.push(He);while(M(",",!0));M("]"),typeof He<"u"&&Ve(ie,be+"."+de,He)}}else Le=$e(),Ve(ie,be+"."+de,Le);var tt=Ie[Fe];tt&&(Le=[].concat(tt).concat(Le)),Ie[Fe]=Le,M(",",!0),M(";",!0)}return Ie}var Ne=$e();return Ve(ie,be,Ne),Ne}function Ve(ie,be,Ie){if(oe===ie&&/^features\./.test(be)){le[be]=Ie;return}ie.setOption&&ie.setOption(be,Ie)}function Ae(ie,be,Ie,Le){ie.setParsedOption&&ie.setParsedOption(be,Ie,Le)}function fe(ie){if(M("[",!0)){do he(ie,"option");while(M(",",!0));M("]")}return ie}function ye(ie,be){if(!nameRe.test(be=b()))throw pe(be,"service name");var Ie=new Service(be);L(Ie,function(Fe){if(!O(Ie,Fe))if(Fe==="rpc")Be(Ie,Fe);else throw pe(Fe)}),ie.add(Ie),ie===oe&&ue.push(Ie)}function Be(ie,be){var Ie=I(),Le=be;if(!nameRe.test(be=b()))throw pe(be,"name");var Fe=be,He,tt,Ne,nt;if(M("("),M("stream",!0)&&(tt=!0),!typeRefRe.test(be=b())||(He=be,M(")"),M("returns"),M("("),M("stream",!0)&&(nt=!0),!typeRefRe.test(be=b())))throw pe(be);Ne=be,M(")");var it=new Method(Fe,Le,He,Ne,tt,nt);it.comment=Ie,L(it,function(ut){if(ut==="option")he(it,ut),M(";");else throw pe(ut)}),ie.add(it)}function ae(ie,be){if(!typeRefRe.test(be=b()))throw pe(be,"reference");var Ie=be;L(null,function(Fe){switch(Fe){case"required":case"repeated":j(ie,Fe,Ie);break;case"optional":X==="proto3"?j(ie,"proto3_optional",Ie):j(ie,"optional",Ie);break;default:if(X==="proto2"||!typeRefRe.test(Fe))throw pe(Fe);E(Fe),j(ie,"optional",Ie);break}})}for(var de;(de=b())!==null;)switch(de){case"package":if(!B)throw pe(de);je();break;case"import":if(!B)throw pe(de);we();break;case"syntax":if(!B)throw pe(de);D();break;case"edition":if(!B)throw pe(de);q();break;case"option":he(oe,de),M(";",!0);break;default:if(O(oe,de)){B=!1;continue}throw pe(de)}return me(),parse.filename=null,{package:C,imports:N,weakImports:Z,root:u}}var common_1=common,commonRe=/\/|\./;function common(y,u){commonRe.test(y)||(y="google/protobuf/"+y+".proto",u={nested:{google:{nested:{protobuf:{nested:u}}}}}),common[y]=u}common("any",{Any:{fields:{type_url:{type:"string",id:1},value:{type:"bytes",id:2}}}});var timeType;common("duration",{Duration:timeType={fields:{seconds:{type:"int64",id:1},nanos:{type:"int32",id:2}}}});common("timestamp",{Timestamp:timeType});common("empty",{Empty:{fields:{}}});common("struct",{Struct:{fields:{fields:{keyType:"string",type:"Value",id:1}}},Value:{oneofs:{kind:{oneof:["nullValue","numberValue","stringValue","boolValue","structValue","listValue"]}},fields:{nullValue:{type:"NullValue",id:1},numberValue:{type:"double",id:2},stringValue:{type:"string",id:3},boolValue:{type:"bool",id:4},structValue:{type:"Struct",id:5},listValue:{type:"ListValue",id:6}}},NullValue:{values:{NULL_VALUE:0}},ListValue:{fields:{values:{rule:"repeated",type:"Value",id:1}}}});common("wrappers",{DoubleValue:{fields:{value:{type:"double",id:1}}},FloatValue:{fields:{value:{type:"float",id:1}}},Int64Value:{fields:{value:{type:"int64",id:1}}},UInt64Value:{fields:{value:{type:"uint64",id:1}}},Int32Value:{fields:{value:{type:"int32",id:1}}},UInt32Value:{fields:{value:{type:"uint32",id:1}}},BoolValue:{fields:{value:{type:"bool",id:1}}},StringValue:{fields:{value:{type:"string",id:1}}},BytesValue:{fields:{value:{type:"bytes",id:1}}}});common("field_mask",{FieldMask:{fields:{paths:{rule:"repeated",type:"string",id:1}}}});common.get=function y(u){return common[u]||null};var protobuf$1=src.exports=indexLightExports;protobuf$1.build="full";protobuf$1.tokenize=tokenize_1;protobuf$1.parse=parse_1;protobuf$1.common=common_1;protobuf$1.Root._configure(protobuf$1.Type,protobuf$1.parse,protobuf$1.common);var srcExports=src.exports,protobufjs=srcExports;const protobuf=getDefaultExportFromCjs$1(protobufjs);class Waku{constructor(u,h,v){this.node=u,this.chatTopic=h,this.onMessage=v,this.logger=Logger$1.getInstance(),this.errorHandler=ErrorHandler.getInstance(),this.reliableChannel=null,this.decoder=null,this.messagePayloadType=null,this.messageReceivedListener=null,this.senderId=crypto$1.randomBytes(8).toString("hex"),this.handleMessageReceived=async({payload:w})=>{try{if(!w){this.logger.warn("Received Waku message without payload");return}if(!this.messagePayloadType)throw new Error("Protobuf schema not initialized");const b=this.messagePayloadType.decode(w),E=this.messagePayloadType.toObject(b,{longs:String,enums:String,defaults:!0});if(!E.message){this.logger.warn("Decoded object has no message field");return}let $=E.message.additionalProps;if($&&typeof $=="string")try{$=JSON.parse($)}catch{this.logger.warn("Failed to parse additionalProps as JSON:",$)}const M={...E.message,timestamp:Number(E.message.timestamp),additionalProps:$};if(!(M!=null&&M.id)){this.logger.warn("Received invalid message structure via Waku");return}this.onMessage(M)}catch(b){this.errorHandler.handleError(b,"Waku2.handleMessageReceived")}}}async start(){this.createProtobufSchema(),await this.createChannel()}createProtobufSchema(){const u=new protobuf.Type("MessageData").add(new protobuf.Field("id",1,"string")).add(new protobuf.Field("targetMessageId",2,"string","optional")).add(new protobuf.Field("type",3,"string")).add(new protobuf.Field("message",4,"string")).add(new protobuf.Field("username",5,"string")).add(new protobuf.Field("address",6,"string")).add(new protobuf.Field("timestamp",7,"uint64")).add(new protobuf.Field("signature",8,"string")).add(new protobuf.Field("index",9,"uint32")).add(new protobuf.Field("chatTopic",10,"string")).add(new protobuf.Field("userTopic",11,"string")).add(new protobuf.Field("additionalProps",12,"string","optional")),h=new protobuf.Type("MessageStateRef").add(new protobuf.Field("reference",1,"string")).add(new protobuf.Field("timestamp",2,"uint64"));this.messagePayloadType=new protobuf.Type("MessagePayload").add(u).add(h).add(new protobuf.Field("message",1,"MessageData")).add(new protobuf.Field("messageStateRefs",2,"MessageStateRef","repeated")),this.logger.info("Protobuf schema created for chat messages")}async createChannel(){if(!this.node)throw new Error("Waku node not initialized");const u=`/solarpunk-msrs-chat/1/${this.chatTopic}/proto`,h=`chat-channel-${this.chatTopic}`,v=this.node.createEncoder({contentTopic:u}),w=this.decoder=this.node.createDecoder({contentTopic:u});this.reliableChannel=await ReliableChannel.create(this.node,h,this.senderId,v,w,{retrieveFrequencyMs:3e3,queryOnConnect:!1}),this.setupChannelEventListeners(this.reliableChannel),this.logger.info(`Created reliable channel for topic: ${this.chatTopic}`)}setupChannelEventListeners(u){this.messageReceivedListener=h=>{this.handleMessageReceived(h.detail)},u.addEventListener("message-received",this.messageReceivedListener)}async stop(){this.reliableChannel&&this.messageReceivedListener&&this.decoder&&(this.reliableChannel.removeEventListener("message-received",this.messageReceivedListener),this.messageReceivedListener=null,await this.reliableChannel.stop(),this.logger.info("Waku reliable channel stopped"))}}class SwarmChat{constructor(u){this.waku=null,this.logger=Logger$1.getInstance(),this.errorHandler=ErrorHandler.getInstance(),this.gsocIndex=null,this.fetchProcessRunning=!1,this.stopFetch=!1;const h=new beeJs.PrivateKey(remove0x(u.user.privateKey));this.userDetails={privateKey:u.user.privateKey,ownAddress:h.publicKey().address().toString(),nickname:u.user.nickname,ownIndex:-1},this.swarmSettings={bee:new beeJs.Bee(u.infra.beeUrl),beeUrl:u.infra.beeUrl,stamp:u.infra.stamp||"0x0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef",enveloped:u.infra.enveloped,gsocTopic:u.infra.gsocTopic,gsocResourceId:u.infra.gsocResourceId,chatTopic:u.infra.chatTopic,chatAddress:u.infra.chatAddress,wakuNode:u.infra.wakuNode},this.emitter=new EventEmitter$2,this.utils=new SwarmChatUtils(this.userDetails,this.swarmSettings),this.history=new SwarmHistory(this.utils,this.emitter)}async start(){await this.init(),await this.startMessageFetchProcess()}async startMessageFetchProcess(){const{wakuNode:u}=this.swarmSettings;u?await this.startWakuMessageFetch(u):await this.startPollingMessageFetch()}async stop(){this.emitter.cleanAll(),this.stopPollingMessageFetch(),this.history.cleanup(),this.waku&&(await this.waku.stop(),this.waku=null)}async startWakuMessageFetch(u){this.logger.info("Waku is enabled");const h=this.swarmSettings.chatTopic;this.waku=new Waku(u,h,v=>{this.emitter.emit(EVENTS.MESSAGE_RECEIVED,v)}),await this.waku.start()}getEmitter(){return this.emitter}orderMessages(u){return this.utils.orderMessages(u)}async sendMessage(u,h,v,w,b){const E=this.userDetails.ownIndex===-1?0:this.userDetails.ownIndex+1,$={id:w||v4(),username:this.userDetails.nickname,address:this.userDetails.ownAddress,chatTopic:this.swarmSettings.chatTopic,userTopic:this.utils.generateUserOwnedFeedId(this.swarmSettings.chatTopic,this.userDetails.ownAddress),signature:this.getSignature(u),timestamp:Date.now(),index:E,type:h,targetMessageId:v,message:u,additionalProps:b},M=validateMessageWithAdditionalProperties($);if(!M.isValid){const I=`Invalid message: ${M.errors.join(", ")}`;throw this.logger.error(I),new Error(I)}try{this.emitter.emit(EVENTS.MESSAGE_REQUEST_INITIATED,$),await this.utils.writeOwnFeedDataByIndex(E,JSON.stringify($)),this.userDetails.ownIndex=E,this.emitter.emit(EVENTS.MESSAGE_REQUEST_UPLOADED,$),await this.broadcastUserMessage($)}catch(I){this.emitter.emit(EVENTS.MESSAGE_REQUEST_ERROR,$),this.errorHandler.handleError(I,"Chat.sendMessage")}}async fetchPreviousMessages(){try{return this.emitter.emit(EVENTS.LOADING_PREVIOUS_MESSAGES,!0),await this.history.fetchPreviousMessageState()}finally{this.emitter.emit(EVENTS.LOADING_PREVIOUS_MESSAGES,!1)}}hasPreviousMessages(){return this.history.hasPreviousMessages()}async retrySendMessage(u){this.sendMessage(u.message,u.type,u.targetMessageId,u.id,u.additionalProps)}async retryBroadcastUserMessage(u){await this.broadcastUserMessage(u)}async init(){try{this.emitter.emit(EVENTS.LOADING_INIT,!0);const[u,h]=await Promise.allSettled([this.initOwnIndex(),this.history.init()]);if(u.status==="rejected")throw u.reason;h.status==="fulfilled"&&(this.gsocIndex=h.value),this.emitter.emit(EVENTS.LOADING_INIT,!1)}catch(u){this.errorHandler.handleError(u,"Chat.initSelfState"),this.emitter.emit(EVENTS.CRITICAL_ERROR,u)}}async initOwnIndex(){const{latestIndex:v}=await retryAwaitableAsync(()=>this.utils.getOwnLatestFeedIndex(),10,1e3);this.userDetails.ownIndex=v}async fetchLatestMessage(){try{if(!this.gsocIndex)return;const u=beeJs.Topic.fromString(this.swarmSettings.chatTopic),h=makeFeedIdentifier(u,this.gsocIndex),v=await this.utils.rawSocDownload(this.swarmSettings.chatAddress,h.toString()),w=JSON.parse(v);if(!validateGsocMessage(w)){this.logger.warn("Invalid GSOC message during fetching");return}this.emitter.emit(EVENTS.MESSAGE_RECEIVED,w.message),this.gsocIndex=this.gsocIndex.next()}catch(u){if(this.utils.isNotFoundError(u))return;this.errorHandler.handleError(u,"Chat.fetchLatestMessage")}}async broadcastUserMessage(u){try{return retryAwaitableAsync(()=>this.utils.sendMessageToGsoc(JSON.stringify(u)))}catch(h){this.errorHandler.handleError(h,"Chat.broadcastUserMessage")}}getSignature(u){const{ownAddress:h,privateKey:v,nickname:w}=this.userDetails,b=new beeJs.EthAddress(h).toString(),E=new beeJs.PrivateKey(v);if(E.publicKey().address().toString()!==b)throw new Error("The provided address does not match the address derived from the private key");const M=Date.now();return E.sign(JSON.stringify({username:w,address:b,message:u,timestamp:M})).toHex()}async startPollingMessageFetch(){if(this.fetchProcessRunning)return;this.fetchProcessRunning=!0,this.stopFetch=!1;const u=async()=>{if(this.stopFetch){this.fetchProcessRunning=!1;return}await this.fetchLatestMessage(),setTimeout(u,200)};u()}stopPollingMessageFetch(){this.stopFetch=!0}}exports.EVENTS=EVENTS;exports.MessageType=MessageType;exports.SwarmChat=SwarmChat;
|
package/dist/lib/waku.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"waku.d.ts","sourceRoot":"","sources":["../../src/lib/waku.ts"],"names":[],"mappings":"AAAA,OAAO,EAA6B,KAAK,SAAS,EAAmB,MAAM,wBAAwB,CAAC;AAIpG,OAAO,EAAE,WAAW,EAAE,MAAM,0BAA0B,CAAC;AAIvD,qBAAa,IAAI;IAWH,OAAO,CAAC,IAAI;IAAa,OAAO,CAAC,SAAS;IAAU,OAAO,CAAC,SAAS;IAVjF,OAAO,CAAC,QAAQ,CAAC,MAAM,CAAwB;IAC/C,OAAO,CAAC,QAAQ,CAAC,YAAY,CAA8B;IAE3D,OAAO,CAAC,eAAe,CAAqC;IAC5D,OAAO,CAAC,OAAO,CAA0C;IACzD,OAAO,CAAC,kBAAkB,CAA8B;IACxD,OAAO,CAAC,uBAAuB,CAAyC;IAExE,OAAO,CAAC,QAAQ,CAAC,QAAQ,CAAyC;gBAE9C,IAAI,EAAE,SAAS,EAAU,SAAS,EAAE,MAAM,EAAU,SAAS,EAAE,CAAC,GAAG,EAAE,WAAW,KAAK,IAAI;
|
|
1
|
+
{"version":3,"file":"waku.d.ts","sourceRoot":"","sources":["../../src/lib/waku.ts"],"names":[],"mappings":"AAAA,OAAO,EAA6B,KAAK,SAAS,EAAmB,MAAM,wBAAwB,CAAC;AAIpG,OAAO,EAAE,WAAW,EAAE,MAAM,0BAA0B,CAAC;AAIvD,qBAAa,IAAI;IAWH,OAAO,CAAC,IAAI;IAAa,OAAO,CAAC,SAAS;IAAU,OAAO,CAAC,SAAS;IAVjF,OAAO,CAAC,QAAQ,CAAC,MAAM,CAAwB;IAC/C,OAAO,CAAC,QAAQ,CAAC,YAAY,CAA8B;IAE3D,OAAO,CAAC,eAAe,CAAqC;IAC5D,OAAO,CAAC,OAAO,CAA0C;IACzD,OAAO,CAAC,kBAAkB,CAA8B;IACxD,OAAO,CAAC,uBAAuB,CAAyC;IAExE,OAAO,CAAC,QAAQ,CAAC,QAAQ,CAAyC;gBAE9C,IAAI,EAAE,SAAS,EAAU,SAAS,EAAE,MAAM,EAAU,SAAS,EAAE,CAAC,GAAG,EAAE,WAAW,KAAK,IAAI;IAEhG,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC;IAKnC,OAAO,CAAC,oBAAoB;YA4Bd,aAAa;IAqB3B,OAAO,CAAC,0BAA0B;IAOlC,OAAO,CAAC,qBAAqB,CAgD3B;IAEW,IAAI,IAAI,OAAO,CAAC,IAAI,CAAC;CAQnC"}
|
package/dist/swarm-chat-umd.js
CHANGED
|
@@ -64,4 +64,4 @@ function print() { __p += __j.call(arguments, '') }
|
|
|
64
64
|
`;)Me++;return Me}function oe(){if($.length>0)return $.shift();if(M)return B();var pe,Me,$e,Pe,Ce,Re=h===0;do{if(h===v)return null;for(pe=!1;whitespaceRe.test($e=C(h));)if($e===`
|
|
65
65
|
`&&(Re=!0,++w),++h===v)return null;if(C(h)==="/"){if(++h===v)throw I("comment");if(C(h)==="/")if(u){if(Pe=h,Ce=!1,Z(h-1)){Ce=!0;do if(h=X(h),h===v||(h++,!Re))break;while(Z(h))}else h=Math.min(v,X(h)+1);Ce&&(N(Pe,h,Re),Re=!0),w++,pe=!0}else{for(Ce=C(Pe=h+1)==="/";C(++h)!==`
|
|
66
66
|
`;)if(h===v)return null;++h,Ce&&(N(Pe,h-1,Re),Re=!0),++w,pe=!0}else if(($e=C(h))==="*"){Pe=h+1,Ce=u||C(Pe)==="*";do{if($e===`
|
|
67
|
-
`&&++w,++h===v)throw I("comment");Me=$e,$e=C(h)}while(Me!=="*"||$e!=="/");++h,Ce&&(N(Pe,h-2,Re),Re=!0),pe=!0}else return"/"}}while(pe);var je=h;delimRe.lastIndex=0;var we=delimRe.test(C(je++));if(!we)for(;je<v&&!delimRe.test(C(je));)++je;var D=y.substring(h,h=je);return(D==='"'||D==="'")&&(M=D),D}function ue(pe){$.push(pe)}function le(){if(!$.length){var pe=oe();if(pe===null)return null;ue(pe)}return $[0]}function re(pe,Me){var $e=le(),Pe=$e===pe;if(Pe)return oe(),!0;if(!Me)throw I("token '"+$e+"', '"+pe+"' expected");return!1}function me(pe){var Me=null,$e;return pe===void 0?($e=E[w-1],delete E[w-1],$e&&(u||$e.type==="*"||$e.lineEmpty)&&(Me=$e.leading?$e.text:null)):(b<pe&&le(),$e=E[pe],delete E[pe],$e&&!$e.lineEmpty&&(u||$e.type==="/")&&(Me=$e.leading?null:$e.text)),Me}return Object.defineProperty({next:oe,peek:le,push:ue,skip:re,cmnt:me},"line",{get:function(){return w}})}var parse_1=parse;parse.filename=null,parse.defaults={keepCase:!1};var tokenize=tokenize_1,Root=requireRoot(),Type=requireType(),Field=requireField(),MapField=requireMapfield(),OneOf=requireOneof(),Enum=require_enum(),Service=requireService(),Method=requireMethod(),ReflectionObject=requireObject(),types=requireTypes(),util=requireUtil(),base10Re=/^[1-9][0-9]*$/,base10NegRe=/^-?[1-9][0-9]*$/,base16Re=/^0[x][0-9a-fA-F]+$/,base16NegRe=/^-?0[x][0-9a-fA-F]+$/,base8Re=/^0[0-7]+$/,base8NegRe=/^-?0[0-7]+$/,numberRe=/^(?![eE])[0-9]*(?:\.[0-9]*)?(?:[eE][+-]?[0-9]+)?$/,nameRe=/^[a-zA-Z_][a-zA-Z_0-9]*$/,typeRefRe=/^(?:\.?[a-zA-Z_][a-zA-Z_0-9]*)(?:\.[a-zA-Z_][a-zA-Z_0-9]*)*$/;function parse(y,u,h){u instanceof Root||(h=u,u=new Root),h||(h=parse.defaults);var v=h.preferTrailingComment||!1,w=tokenize(y,h.alternateCommentMode||!1),b=w.next,E=w.push,$=w.peek,M=w.skip,I=w.cmnt,B=!0,C,N,Z,X="proto2",oe=u,ue=[],le={},re=h.keepCase?function(ie){return ie}:util.camelCase;function me(){ue.forEach(ie=>{ie._edition=X,Object.keys(le).forEach(be=>{ie.getOption(be)===void 0&&ie.setOption(be,le[be],!0)})})}function pe(ie,be,Ie){var Le=parse.filename;return Ie||(parse.filename=null),Error("illegal "+(be||"token")+" '"+ie+"' ("+(Le?Le+", ":"")+"line "+w.line+")")}function Me(){var ie=[],be;do{if((be=b())!=='"'&&be!=="'")throw pe(be);ie.push(b()),M(be),be=$()}while(be==='"'||be==="'");return ie.join("")}function $e(ie){var be=b();switch(be){case"'":case'"':return E(be),Me();case"true":case"TRUE":return!0;case"false":case"FALSE":return!1}try{return Ce(be,!0)}catch{if(typeRefRe.test(be))return be;throw pe(be,"value")}}function Pe(ie,be){var Ie,Le;do if(be&&((Ie=$())==='"'||Ie==="'")){var Fe=Me();if(ie.push(Fe),X>=2023)throw pe(Fe,"id")}else try{ie.push([Le=Re(b()),M("to",!0)?Re(b()):Le])}catch(tt){if(be&&typeRefRe.test(Ie)&&X>=2023)ie.push(Ie);else throw tt}while(M(",",!0));var He={options:void 0};He.setOption=function(tt,Ne){this.options===void 0&&(this.options={}),this.options[tt]=Ne},L(He,function(Ne){if(Ne==="option")he(He,Ne),M(";");else throw pe(Ne)},function(){fe(He)})}function Ce(ie,be){var Ie=1;switch(ie.charAt(0)==="-"&&(Ie=-1,ie=ie.substring(1)),ie){case"inf":case"INF":case"Inf":return Ie*(1/0);case"nan":case"NAN":case"Nan":case"NaN":return NaN;case"0":return 0}if(base10Re.test(ie))return Ie*parseInt(ie,10);if(base16Re.test(ie))return Ie*parseInt(ie,16);if(base8Re.test(ie))return Ie*parseInt(ie,8);if(numberRe.test(ie))return Ie*parseFloat(ie);throw pe(ie,"number",be)}function Re(ie,be){switch(ie){case"max":case"MAX":case"Max":return 536870911;case"0":return 0}if(!be&&ie.charAt(0)==="-")throw pe(ie,"id");if(base10NegRe.test(ie))return parseInt(ie,10);if(base16NegRe.test(ie))return parseInt(ie,16);if(base8NegRe.test(ie))return parseInt(ie,8);throw pe(ie,"id")}function je(){if(C!==void 0)throw pe("package");if(C=b(),!typeRefRe.test(C))throw pe(C,"name");oe=oe.define(C),M(";")}function we(){var ie=$(),be;switch(ie){case"weak":be=Z||(Z=[]),b();break;case"public":b();default:be=N||(N=[]);break}ie=Me(),M(";"),be.push(ie)}function D(){if(M("="),X=Me(),X<2023)throw pe(X,"syntax");M(";")}function q(){if(M("="),X=Me(),!["2023"].includes(X))throw pe(X,"edition");M(";")}function O(ie,be){switch(be){case"option":return he(ie,be),M(";"),!0;case"message":return Q(ie,be),!0;case"enum":return ee(ie,be),!0;case"service":return ye(ie,be),!0;case"extend":return ae(ie,be),!0}return!1}function L(ie,be,Ie){var Le=w.line;if(ie&&(typeof ie.comment!="string"&&(ie.comment=I()),ie.filename=parse.filename),M("{",!0)){for(var Fe;(Fe=b())!=="}";)be(Fe);M(";",!0)}else Ie&&Ie(),M(";"),ie&&(typeof ie.comment!="string"||v)&&(ie.comment=I(Le)||ie.comment)}function Q(ie,be){if(!nameRe.test(be=b()))throw pe(be,"type name");var Ie=new Type(be);L(Ie,function(Fe){if(!O(Ie,Fe))switch(Fe){case"map":te(Ie);break;case"required":if(X!=="proto2")throw pe(Fe);case"repeated":j(Ie,Fe);break;case"optional":if(X==="proto3")j(Ie,"proto3_optional");else{if(X!=="proto2")throw pe(Fe);j(Ie,"optional")}break;case"oneof":F(Ie,Fe);break;case"extensions":Pe(Ie.extensions||(Ie.extensions=[]));break;case"reserved":Pe(Ie.reserved||(Ie.reserved=[]),!0);break;default:if(X==="proto2"||!typeRefRe.test(Fe))throw pe(Fe);E(Fe),j(Ie,"optional");break}}),ie.add(Ie),ie===oe&&ue.push(Ie)}function j(ie,be,Ie){var Le=b();if(Le==="group"){ne(ie,be);return}for(;Le.endsWith(".")||$().startsWith(".");)Le+=b();if(!typeRefRe.test(Le))throw pe(Le,"type");var Fe=b();if(!nameRe.test(Fe))throw pe(Fe,"name");Fe=re(Fe),M("=");var He=new Field(Fe,Re(b()),Le,be,Ie);if(L(He,function(nt){if(nt==="option")he(He,nt),M(";");else throw pe(nt)},function(){fe(He)}),be==="proto3_optional"){var tt=new OneOf("_"+Fe);He.setOption("proto3_optional",!0),tt.add(He),ie.add(tt)}else ie.add(He);ie===oe&&ue.push(He)}function ne(ie,be){if(X>=2023)throw pe("group");var Ie=b();if(!nameRe.test(Ie))throw pe(Ie,"name");var Le=util.lcFirst(Ie);Ie===Le&&(Ie=util.ucFirst(Ie)),M("=");var Fe=Re(b()),He=new Type(Ie);He.group=!0;var tt=new Field(Le,Fe,Ie,be);tt.filename=parse.filename,L(He,function(nt){switch(nt){case"option":he(He,nt),M(";");break;case"required":case"repeated":j(He,nt);break;case"optional":X==="proto3"?j(He,"proto3_optional"):j(He,"optional");break;case"message":Q(He,nt);break;case"enum":ee(He,nt);break;case"reserved":Pe(He.reserved||(He.reserved=[]),!0);break;default:throw pe(nt)}}),ie.add(He).add(tt)}function te(ie){M("<");var be=b();if(types.mapKey[be]===void 0)throw pe(be,"type");M(",");var Ie=b();if(!typeRefRe.test(Ie))throw pe(Ie,"type");M(">");var Le=b();if(!nameRe.test(Le))throw pe(Le,"name");M("=");var Fe=new MapField(re(Le),Re(b()),be,Ie);L(Fe,function(tt){if(tt==="option")he(Fe,tt),M(";");else throw pe(tt)},function(){fe(Fe)}),ie.add(Fe)}function F(ie,be){if(!nameRe.test(be=b()))throw pe(be,"name");var Ie=new OneOf(re(be));L(Ie,function(Fe){Fe==="option"?(he(Ie,Fe),M(";")):(E(Fe),j(Ie,"optional"))}),ie.add(Ie)}function ee(ie,be){if(!nameRe.test(be=b()))throw pe(be,"name");var Ie=new Enum(be);L(Ie,function(Fe){switch(Fe){case"option":he(Ie,Fe),M(";");break;case"reserved":Pe(Ie.reserved||(Ie.reserved=[]),!0),Ie.reserved===void 0&&(Ie.reserved=[]);break;default:U(Ie,Fe)}}),ie.add(Ie),ie===oe&&ue.push(Ie)}function U(ie,be){if(!nameRe.test(be))throw pe(be,"name");M("=");var Ie=Re(b(),!0),Le={options:void 0};Le.getOption=function(Fe){return this.options[Fe]},Le.setOption=function(Fe,He){ReflectionObject.prototype.setOption.call(Le,Fe,He)},Le.setParsedOption=function(){},L(Le,function(He){if(He==="option")he(Le,He),M(";");else throw pe(He)},function(){fe(Le)}),ie.add(be,Ie,Le.comment,Le.parsedOptions||Le.options)}function he(ie,be){var Ie,Le,Fe=!0;for(be==="option"&&(be=b());be!=="=";){if(be==="("){var He=b();M(")"),be="("+He+")"}if(Fe){if(Fe=!1,be.includes(".")&&!be.includes("(")){var tt=be.split(".");Ie=tt[0]+".",be=tt[1];continue}Ie=be}else Le=Le?Le+=be:be;be=b()}var Ne=Le?Ie.concat(Le):Ie,nt=Oe(ie,Ne);Le=Le&&Le[0]==="."?Le.slice(1):Le,Ie=Ie&&Ie[Ie.length-1]==="."?Ie.slice(0,-1):Ie,Ae(ie,Ie,nt,Le)}function Oe(ie,be){if(M("{",!0)){for(var Ie={};!M("}",!0);){if(!nameRe.test(de=b()))throw pe(de,"name");if(de===null)throw pe(de,"end of input");var Le,Fe=de;if(M(":",!0),$()==="{")Le=Oe(ie,be+"."+de);else if($()==="["){Le=[];var He;if(M("[",!0)){do He=$e(),Le.push(He);while(M(",",!0));M("]"),typeof He<"u"&&Ve(ie,be+"."+de,He)}}else Le=$e(),Ve(ie,be+"."+de,Le);var tt=Ie[Fe];tt&&(Le=[].concat(tt).concat(Le)),Ie[Fe]=Le,M(",",!0),M(";",!0)}return Ie}var Ne=$e();return Ve(ie,be,Ne),Ne}function Ve(ie,be,Ie){if(oe===ie&&/^features\./.test(be)){le[be]=Ie;return}ie.setOption&&ie.setOption(be,Ie)}function Ae(ie,be,Ie,Le){ie.setParsedOption&&ie.setParsedOption(be,Ie,Le)}function fe(ie){if(M("[",!0)){do he(ie,"option");while(M(",",!0));M("]")}return ie}function ye(ie,be){if(!nameRe.test(be=b()))throw pe(be,"service name");var Ie=new Service(be);L(Ie,function(Fe){if(!O(Ie,Fe))if(Fe==="rpc")Be(Ie,Fe);else throw pe(Fe)}),ie.add(Ie),ie===oe&&ue.push(Ie)}function Be(ie,be){var Ie=I(),Le=be;if(!nameRe.test(be=b()))throw pe(be,"name");var Fe=be,He,tt,Ne,nt;if(M("("),M("stream",!0)&&(tt=!0),!typeRefRe.test(be=b())||(He=be,M(")"),M("returns"),M("("),M("stream",!0)&&(nt=!0),!typeRefRe.test(be=b())))throw pe(be);Ne=be,M(")");var it=new Method(Fe,Le,He,Ne,tt,nt);it.comment=Ie,L(it,function(ut){if(ut==="option")he(it,ut),M(";");else throw pe(ut)}),ie.add(it)}function ae(ie,be){if(!typeRefRe.test(be=b()))throw pe(be,"reference");var Ie=be;L(null,function(Fe){switch(Fe){case"required":case"repeated":j(ie,Fe,Ie);break;case"optional":X==="proto3"?j(ie,"proto3_optional",Ie):j(ie,"optional",Ie);break;default:if(X==="proto2"||!typeRefRe.test(Fe))throw pe(Fe);E(Fe),j(ie,"optional",Ie);break}})}for(var de;(de=b())!==null;)switch(de){case"package":if(!B)throw pe(de);je();break;case"import":if(!B)throw pe(de);we();break;case"syntax":if(!B)throw pe(de);D();break;case"edition":if(!B)throw pe(de);q();break;case"option":he(oe,de),M(";",!0);break;default:if(O(oe,de)){B=!1;continue}throw pe(de)}return me(),parse.filename=null,{package:C,imports:N,weakImports:Z,root:u}}var common_1=common,commonRe=/\/|\./;function common(y,u){commonRe.test(y)||(y="google/protobuf/"+y+".proto",u={nested:{google:{nested:{protobuf:{nested:u}}}}}),common[y]=u}common("any",{Any:{fields:{type_url:{type:"string",id:1},value:{type:"bytes",id:2}}}});var timeType;common("duration",{Duration:timeType={fields:{seconds:{type:"int64",id:1},nanos:{type:"int32",id:2}}}}),common("timestamp",{Timestamp:timeType}),common("empty",{Empty:{fields:{}}}),common("struct",{Struct:{fields:{fields:{keyType:"string",type:"Value",id:1}}},Value:{oneofs:{kind:{oneof:["nullValue","numberValue","stringValue","boolValue","structValue","listValue"]}},fields:{nullValue:{type:"NullValue",id:1},numberValue:{type:"double",id:2},stringValue:{type:"string",id:3},boolValue:{type:"bool",id:4},structValue:{type:"Struct",id:5},listValue:{type:"ListValue",id:6}}},NullValue:{values:{NULL_VALUE:0}},ListValue:{fields:{values:{rule:"repeated",type:"Value",id:1}}}}),common("wrappers",{DoubleValue:{fields:{value:{type:"double",id:1}}},FloatValue:{fields:{value:{type:"float",id:1}}},Int64Value:{fields:{value:{type:"int64",id:1}}},UInt64Value:{fields:{value:{type:"uint64",id:1}}},Int32Value:{fields:{value:{type:"int32",id:1}}},UInt32Value:{fields:{value:{type:"uint32",id:1}}},BoolValue:{fields:{value:{type:"bool",id:1}}},StringValue:{fields:{value:{type:"string",id:1}}},BytesValue:{fields:{value:{type:"bytes",id:1}}}}),common("field_mask",{FieldMask:{fields:{paths:{rule:"repeated",type:"string",id:1}}}}),common.get=function y(u){return common[u]||null};var protobuf$1=src.exports=indexLightExports;protobuf$1.build="full",protobuf$1.tokenize=tokenize_1,protobuf$1.parse=parse_1,protobuf$1.common=common_1,protobuf$1.Root._configure(protobuf$1.Type,protobuf$1.parse,protobuf$1.common);var srcExports=src.exports,protobufjs=srcExports;const protobuf=getDefaultExportFromCjs$1(protobufjs);class Waku{constructor(u,h,v){this.node=u,this.chatTopic=h,this.onMessage=v,this.logger=Logger$1.getInstance(),this.errorHandler=ErrorHandler.getInstance(),this.reliableChannel=null,this.decoder=null,this.messagePayloadType=null,this.messageReceivedListener=null,this.senderId=crypto$1.randomBytes(8).toString("hex"),this.handleMessageReceived=async({payload:w})=>{try{if(!w){this.logger.warn("Received Waku message without payload");return}if(!this.messagePayloadType)throw new Error("Protobuf schema not initialized");const b=this.messagePayloadType.decode(w),E=this.messagePayloadType.toObject(b,{longs:String,enums:String,defaults:!0});if(!E.message){this.logger.warn("Decoded object has no message field");return}let $=E.message.additionalProps;if($&&typeof $=="string")try{$=JSON.parse($)}catch{this.logger.warn("Failed to parse additionalProps as JSON:",$)}const M={...E.message,timestamp:Number(E.message.timestamp),additionalProps:$};if(!(M!=null&&M.id)){this.logger.warn("Received invalid message structure via Waku");return}this.onMessage(M)}catch(b){this.errorHandler.handleError(b,"Waku2.handleMessageReceived")}},this.createProtobufSchema()}async start(){this.createProtobufSchema(),await this.createChannel()}createProtobufSchema(){const u=new protobuf.Type("MessageData").add(new protobuf.Field("id",1,"string")).add(new protobuf.Field("targetMessageId",2,"string","optional")).add(new protobuf.Field("type",3,"string")).add(new protobuf.Field("message",4,"string")).add(new protobuf.Field("username",5,"string")).add(new protobuf.Field("address",6,"string")).add(new protobuf.Field("timestamp",7,"uint64")).add(new protobuf.Field("signature",8,"string")).add(new protobuf.Field("index",9,"uint32")).add(new protobuf.Field("chatTopic",10,"string")).add(new protobuf.Field("userTopic",11,"string")).add(new protobuf.Field("additionalProps",12,"string","optional")),h=new protobuf.Type("MessageStateRef").add(new protobuf.Field("reference",1,"string")).add(new protobuf.Field("timestamp",2,"uint64"));this.messagePayloadType=new protobuf.Type("MessagePayload").add(u).add(h).add(new protobuf.Field("message",1,"MessageData")).add(new protobuf.Field("messageStateRefs",2,"MessageStateRef","repeated")),this.logger.info("Protobuf schema created for chat messages")}async createChannel(){if(!this.node)throw new Error("Waku node not initialized");const u=`/solarpunk-msrs-chat/1/${this.chatTopic}/proto`,h=`chat-channel-${this.chatTopic}`,v=this.node.createEncoder({contentTopic:u}),w=this.decoder=this.node.createDecoder({contentTopic:u});this.reliableChannel=await ReliableChannel.create(this.node,h,this.senderId,v,w,{retrieveFrequencyMs:3e3,queryOnConnect:!1}),this.setupChannelEventListeners(this.reliableChannel),this.logger.info(`Created reliable channel for topic: ${this.chatTopic}`)}setupChannelEventListeners(u){this.messageReceivedListener=h=>{this.handleMessageReceived(h.detail)},u.addEventListener("message-received",this.messageReceivedListener)}async stop(){this.reliableChannel&&this.messageReceivedListener&&this.decoder&&(this.reliableChannel.removeEventListener("message-received",this.messageReceivedListener),this.messageReceivedListener=null,await this.reliableChannel.stop(),this.logger.info("Waku reliable channel stopped"))}}class SwarmChat{constructor(u){this.waku=null,this.logger=Logger$1.getInstance(),this.errorHandler=ErrorHandler.getInstance(),this.gsocIndex=null,this.fetchProcessRunning=!1,this.stopFetch=!1;const h=new beeJs.PrivateKey(remove0x(u.user.privateKey));this.userDetails={privateKey:u.user.privateKey,ownAddress:h.publicKey().address().toString(),nickname:u.user.nickname,ownIndex:-1},this.swarmSettings={bee:new beeJs.Bee(u.infra.beeUrl),beeUrl:u.infra.beeUrl,stamp:u.infra.stamp||"0x0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef",enveloped:u.infra.enveloped,gsocTopic:u.infra.gsocTopic,gsocResourceId:u.infra.gsocResourceId,chatTopic:u.infra.chatTopic,chatAddress:u.infra.chatAddress,wakuNode:u.infra.wakuNode},this.emitter=new EventEmitter$2,this.utils=new SwarmChatUtils(this.userDetails,this.swarmSettings),this.history=new SwarmHistory(this.utils,this.emitter)}async start(){await this.init(),await this.startMessageFetchProcess()}async startMessageFetchProcess(){const{wakuNode:u}=this.swarmSettings;u?await this.startWakuMessageFetch(u):await this.startPollingMessageFetch()}async stop(){this.emitter.cleanAll(),this.stopPollingMessageFetch(),this.history.cleanup(),this.waku&&(await this.waku.stop(),this.waku=null)}async startWakuMessageFetch(u){this.logger.info("Waku is enabled");const h=this.swarmSettings.chatTopic;this.waku=new Waku(u,h,v=>{this.emitter.emit(EVENTS.MESSAGE_RECEIVED,v)}),await this.waku.start()}getEmitter(){return this.emitter}orderMessages(u){return this.utils.orderMessages(u)}async sendMessage(u,h,v,w,b){const E=this.userDetails.ownIndex===-1?0:this.userDetails.ownIndex+1,$={id:w||v4(),username:this.userDetails.nickname,address:this.userDetails.ownAddress,chatTopic:this.swarmSettings.chatTopic,userTopic:this.utils.generateUserOwnedFeedId(this.swarmSettings.chatTopic,this.userDetails.ownAddress),signature:this.getSignature(u),timestamp:Date.now(),index:E,type:h,targetMessageId:v,message:u,additionalProps:b},M=validateMessageWithAdditionalProperties($);if(!M.isValid){const I=`Invalid message: ${M.errors.join(", ")}`;throw this.logger.error(I),new Error(I)}try{this.emitter.emit(EVENTS.MESSAGE_REQUEST_INITIATED,$),await this.utils.writeOwnFeedDataByIndex(E,JSON.stringify($)),this.userDetails.ownIndex=E,this.emitter.emit(EVENTS.MESSAGE_REQUEST_UPLOADED,$),await this.broadcastUserMessage($)}catch(I){this.emitter.emit(EVENTS.MESSAGE_REQUEST_ERROR,$),this.errorHandler.handleError(I,"Chat.sendMessage")}}async fetchPreviousMessages(){try{return this.emitter.emit(EVENTS.LOADING_PREVIOUS_MESSAGES,!0),await this.history.fetchPreviousMessageState()}finally{this.emitter.emit(EVENTS.LOADING_PREVIOUS_MESSAGES,!1)}}hasPreviousMessages(){return this.history.hasPreviousMessages()}async retrySendMessage(u){this.sendMessage(u.message,u.type,u.targetMessageId,u.id,u.additionalProps)}async retryBroadcastUserMessage(u){await this.broadcastUserMessage(u)}async init(){try{this.emitter.emit(EVENTS.LOADING_INIT,!0);const[u,h]=await Promise.allSettled([this.initOwnIndex(),this.history.init()]);if(u.status==="rejected")throw u.reason;h.status==="fulfilled"&&(this.gsocIndex=h.value),this.emitter.emit(EVENTS.LOADING_INIT,!1)}catch(u){this.errorHandler.handleError(u,"Chat.initSelfState"),this.emitter.emit(EVENTS.CRITICAL_ERROR,u)}}async initOwnIndex(){const{latestIndex:v}=await retryAwaitableAsync(()=>this.utils.getOwnLatestFeedIndex(),10,1e3);this.userDetails.ownIndex=v}async fetchLatestMessage(){try{if(!this.gsocIndex)return;const u=beeJs.Topic.fromString(this.swarmSettings.chatTopic),h=makeFeedIdentifier(u,this.gsocIndex),v=await this.utils.rawSocDownload(this.swarmSettings.chatAddress,h.toString()),w=JSON.parse(v);if(!validateGsocMessage(w)){this.logger.warn("Invalid GSOC message during fetching");return}this.emitter.emit(EVENTS.MESSAGE_RECEIVED,w.message),this.gsocIndex=this.gsocIndex.next()}catch(u){if(this.utils.isNotFoundError(u))return;this.errorHandler.handleError(u,"Chat.fetchLatestMessage")}}async broadcastUserMessage(u){try{return retryAwaitableAsync(()=>this.utils.sendMessageToGsoc(JSON.stringify(u)))}catch(h){this.errorHandler.handleError(h,"Chat.broadcastUserMessage")}}getSignature(u){const{ownAddress:h,privateKey:v,nickname:w}=this.userDetails,b=new beeJs.EthAddress(h).toString(),E=new beeJs.PrivateKey(v);if(E.publicKey().address().toString()!==b)throw new Error("The provided address does not match the address derived from the private key");const M=Date.now();return E.sign(JSON.stringify({username:w,address:b,message:u,timestamp:M})).toHex()}async startPollingMessageFetch(){if(this.fetchProcessRunning)return;this.fetchProcessRunning=!0,this.stopFetch=!1;const u=async()=>{if(this.stopFetch){this.fetchProcessRunning=!1;return}await this.fetchLatestMessage(),setTimeout(u,200)};u()}stopPollingMessageFetch(){this.stopFetch=!0}}exports.EVENTS=EVENTS,exports.MessageType=MessageType,exports.SwarmChat=SwarmChat,Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"})});
|
|
67
|
+
`&&++w,++h===v)throw I("comment");Me=$e,$e=C(h)}while(Me!=="*"||$e!=="/");++h,Ce&&(N(Pe,h-2,Re),Re=!0),pe=!0}else return"/"}}while(pe);var je=h;delimRe.lastIndex=0;var we=delimRe.test(C(je++));if(!we)for(;je<v&&!delimRe.test(C(je));)++je;var D=y.substring(h,h=je);return(D==='"'||D==="'")&&(M=D),D}function ue(pe){$.push(pe)}function le(){if(!$.length){var pe=oe();if(pe===null)return null;ue(pe)}return $[0]}function re(pe,Me){var $e=le(),Pe=$e===pe;if(Pe)return oe(),!0;if(!Me)throw I("token '"+$e+"', '"+pe+"' expected");return!1}function me(pe){var Me=null,$e;return pe===void 0?($e=E[w-1],delete E[w-1],$e&&(u||$e.type==="*"||$e.lineEmpty)&&(Me=$e.leading?$e.text:null)):(b<pe&&le(),$e=E[pe],delete E[pe],$e&&!$e.lineEmpty&&(u||$e.type==="/")&&(Me=$e.leading?null:$e.text)),Me}return Object.defineProperty({next:oe,peek:le,push:ue,skip:re,cmnt:me},"line",{get:function(){return w}})}var parse_1=parse;parse.filename=null,parse.defaults={keepCase:!1};var tokenize=tokenize_1,Root=requireRoot(),Type=requireType(),Field=requireField(),MapField=requireMapfield(),OneOf=requireOneof(),Enum=require_enum(),Service=requireService(),Method=requireMethod(),ReflectionObject=requireObject(),types=requireTypes(),util=requireUtil(),base10Re=/^[1-9][0-9]*$/,base10NegRe=/^-?[1-9][0-9]*$/,base16Re=/^0[x][0-9a-fA-F]+$/,base16NegRe=/^-?0[x][0-9a-fA-F]+$/,base8Re=/^0[0-7]+$/,base8NegRe=/^-?0[0-7]+$/,numberRe=/^(?![eE])[0-9]*(?:\.[0-9]*)?(?:[eE][+-]?[0-9]+)?$/,nameRe=/^[a-zA-Z_][a-zA-Z_0-9]*$/,typeRefRe=/^(?:\.?[a-zA-Z_][a-zA-Z_0-9]*)(?:\.[a-zA-Z_][a-zA-Z_0-9]*)*$/;function parse(y,u,h){u instanceof Root||(h=u,u=new Root),h||(h=parse.defaults);var v=h.preferTrailingComment||!1,w=tokenize(y,h.alternateCommentMode||!1),b=w.next,E=w.push,$=w.peek,M=w.skip,I=w.cmnt,B=!0,C,N,Z,X="proto2",oe=u,ue=[],le={},re=h.keepCase?function(ie){return ie}:util.camelCase;function me(){ue.forEach(ie=>{ie._edition=X,Object.keys(le).forEach(be=>{ie.getOption(be)===void 0&&ie.setOption(be,le[be],!0)})})}function pe(ie,be,Ie){var Le=parse.filename;return Ie||(parse.filename=null),Error("illegal "+(be||"token")+" '"+ie+"' ("+(Le?Le+", ":"")+"line "+w.line+")")}function Me(){var ie=[],be;do{if((be=b())!=='"'&&be!=="'")throw pe(be);ie.push(b()),M(be),be=$()}while(be==='"'||be==="'");return ie.join("")}function $e(ie){var be=b();switch(be){case"'":case'"':return E(be),Me();case"true":case"TRUE":return!0;case"false":case"FALSE":return!1}try{return Ce(be,!0)}catch{if(typeRefRe.test(be))return be;throw pe(be,"value")}}function Pe(ie,be){var Ie,Le;do if(be&&((Ie=$())==='"'||Ie==="'")){var Fe=Me();if(ie.push(Fe),X>=2023)throw pe(Fe,"id")}else try{ie.push([Le=Re(b()),M("to",!0)?Re(b()):Le])}catch(tt){if(be&&typeRefRe.test(Ie)&&X>=2023)ie.push(Ie);else throw tt}while(M(",",!0));var He={options:void 0};He.setOption=function(tt,Ne){this.options===void 0&&(this.options={}),this.options[tt]=Ne},L(He,function(Ne){if(Ne==="option")he(He,Ne),M(";");else throw pe(Ne)},function(){fe(He)})}function Ce(ie,be){var Ie=1;switch(ie.charAt(0)==="-"&&(Ie=-1,ie=ie.substring(1)),ie){case"inf":case"INF":case"Inf":return Ie*(1/0);case"nan":case"NAN":case"Nan":case"NaN":return NaN;case"0":return 0}if(base10Re.test(ie))return Ie*parseInt(ie,10);if(base16Re.test(ie))return Ie*parseInt(ie,16);if(base8Re.test(ie))return Ie*parseInt(ie,8);if(numberRe.test(ie))return Ie*parseFloat(ie);throw pe(ie,"number",be)}function Re(ie,be){switch(ie){case"max":case"MAX":case"Max":return 536870911;case"0":return 0}if(!be&&ie.charAt(0)==="-")throw pe(ie,"id");if(base10NegRe.test(ie))return parseInt(ie,10);if(base16NegRe.test(ie))return parseInt(ie,16);if(base8NegRe.test(ie))return parseInt(ie,8);throw pe(ie,"id")}function je(){if(C!==void 0)throw pe("package");if(C=b(),!typeRefRe.test(C))throw pe(C,"name");oe=oe.define(C),M(";")}function we(){var ie=$(),be;switch(ie){case"weak":be=Z||(Z=[]),b();break;case"public":b();default:be=N||(N=[]);break}ie=Me(),M(";"),be.push(ie)}function D(){if(M("="),X=Me(),X<2023)throw pe(X,"syntax");M(";")}function q(){if(M("="),X=Me(),!["2023"].includes(X))throw pe(X,"edition");M(";")}function O(ie,be){switch(be){case"option":return he(ie,be),M(";"),!0;case"message":return Q(ie,be),!0;case"enum":return ee(ie,be),!0;case"service":return ye(ie,be),!0;case"extend":return ae(ie,be),!0}return!1}function L(ie,be,Ie){var Le=w.line;if(ie&&(typeof ie.comment!="string"&&(ie.comment=I()),ie.filename=parse.filename),M("{",!0)){for(var Fe;(Fe=b())!=="}";)be(Fe);M(";",!0)}else Ie&&Ie(),M(";"),ie&&(typeof ie.comment!="string"||v)&&(ie.comment=I(Le)||ie.comment)}function Q(ie,be){if(!nameRe.test(be=b()))throw pe(be,"type name");var Ie=new Type(be);L(Ie,function(Fe){if(!O(Ie,Fe))switch(Fe){case"map":te(Ie);break;case"required":if(X!=="proto2")throw pe(Fe);case"repeated":j(Ie,Fe);break;case"optional":if(X==="proto3")j(Ie,"proto3_optional");else{if(X!=="proto2")throw pe(Fe);j(Ie,"optional")}break;case"oneof":F(Ie,Fe);break;case"extensions":Pe(Ie.extensions||(Ie.extensions=[]));break;case"reserved":Pe(Ie.reserved||(Ie.reserved=[]),!0);break;default:if(X==="proto2"||!typeRefRe.test(Fe))throw pe(Fe);E(Fe),j(Ie,"optional");break}}),ie.add(Ie),ie===oe&&ue.push(Ie)}function j(ie,be,Ie){var Le=b();if(Le==="group"){ne(ie,be);return}for(;Le.endsWith(".")||$().startsWith(".");)Le+=b();if(!typeRefRe.test(Le))throw pe(Le,"type");var Fe=b();if(!nameRe.test(Fe))throw pe(Fe,"name");Fe=re(Fe),M("=");var He=new Field(Fe,Re(b()),Le,be,Ie);if(L(He,function(nt){if(nt==="option")he(He,nt),M(";");else throw pe(nt)},function(){fe(He)}),be==="proto3_optional"){var tt=new OneOf("_"+Fe);He.setOption("proto3_optional",!0),tt.add(He),ie.add(tt)}else ie.add(He);ie===oe&&ue.push(He)}function ne(ie,be){if(X>=2023)throw pe("group");var Ie=b();if(!nameRe.test(Ie))throw pe(Ie,"name");var Le=util.lcFirst(Ie);Ie===Le&&(Ie=util.ucFirst(Ie)),M("=");var Fe=Re(b()),He=new Type(Ie);He.group=!0;var tt=new Field(Le,Fe,Ie,be);tt.filename=parse.filename,L(He,function(nt){switch(nt){case"option":he(He,nt),M(";");break;case"required":case"repeated":j(He,nt);break;case"optional":X==="proto3"?j(He,"proto3_optional"):j(He,"optional");break;case"message":Q(He,nt);break;case"enum":ee(He,nt);break;case"reserved":Pe(He.reserved||(He.reserved=[]),!0);break;default:throw pe(nt)}}),ie.add(He).add(tt)}function te(ie){M("<");var be=b();if(types.mapKey[be]===void 0)throw pe(be,"type");M(",");var Ie=b();if(!typeRefRe.test(Ie))throw pe(Ie,"type");M(">");var Le=b();if(!nameRe.test(Le))throw pe(Le,"name");M("=");var Fe=new MapField(re(Le),Re(b()),be,Ie);L(Fe,function(tt){if(tt==="option")he(Fe,tt),M(";");else throw pe(tt)},function(){fe(Fe)}),ie.add(Fe)}function F(ie,be){if(!nameRe.test(be=b()))throw pe(be,"name");var Ie=new OneOf(re(be));L(Ie,function(Fe){Fe==="option"?(he(Ie,Fe),M(";")):(E(Fe),j(Ie,"optional"))}),ie.add(Ie)}function ee(ie,be){if(!nameRe.test(be=b()))throw pe(be,"name");var Ie=new Enum(be);L(Ie,function(Fe){switch(Fe){case"option":he(Ie,Fe),M(";");break;case"reserved":Pe(Ie.reserved||(Ie.reserved=[]),!0),Ie.reserved===void 0&&(Ie.reserved=[]);break;default:U(Ie,Fe)}}),ie.add(Ie),ie===oe&&ue.push(Ie)}function U(ie,be){if(!nameRe.test(be))throw pe(be,"name");M("=");var Ie=Re(b(),!0),Le={options:void 0};Le.getOption=function(Fe){return this.options[Fe]},Le.setOption=function(Fe,He){ReflectionObject.prototype.setOption.call(Le,Fe,He)},Le.setParsedOption=function(){},L(Le,function(He){if(He==="option")he(Le,He),M(";");else throw pe(He)},function(){fe(Le)}),ie.add(be,Ie,Le.comment,Le.parsedOptions||Le.options)}function he(ie,be){var Ie,Le,Fe=!0;for(be==="option"&&(be=b());be!=="=";){if(be==="("){var He=b();M(")"),be="("+He+")"}if(Fe){if(Fe=!1,be.includes(".")&&!be.includes("(")){var tt=be.split(".");Ie=tt[0]+".",be=tt[1];continue}Ie=be}else Le=Le?Le+=be:be;be=b()}var Ne=Le?Ie.concat(Le):Ie,nt=Oe(ie,Ne);Le=Le&&Le[0]==="."?Le.slice(1):Le,Ie=Ie&&Ie[Ie.length-1]==="."?Ie.slice(0,-1):Ie,Ae(ie,Ie,nt,Le)}function Oe(ie,be){if(M("{",!0)){for(var Ie={};!M("}",!0);){if(!nameRe.test(de=b()))throw pe(de,"name");if(de===null)throw pe(de,"end of input");var Le,Fe=de;if(M(":",!0),$()==="{")Le=Oe(ie,be+"."+de);else if($()==="["){Le=[];var He;if(M("[",!0)){do He=$e(),Le.push(He);while(M(",",!0));M("]"),typeof He<"u"&&Ve(ie,be+"."+de,He)}}else Le=$e(),Ve(ie,be+"."+de,Le);var tt=Ie[Fe];tt&&(Le=[].concat(tt).concat(Le)),Ie[Fe]=Le,M(",",!0),M(";",!0)}return Ie}var Ne=$e();return Ve(ie,be,Ne),Ne}function Ve(ie,be,Ie){if(oe===ie&&/^features\./.test(be)){le[be]=Ie;return}ie.setOption&&ie.setOption(be,Ie)}function Ae(ie,be,Ie,Le){ie.setParsedOption&&ie.setParsedOption(be,Ie,Le)}function fe(ie){if(M("[",!0)){do he(ie,"option");while(M(",",!0));M("]")}return ie}function ye(ie,be){if(!nameRe.test(be=b()))throw pe(be,"service name");var Ie=new Service(be);L(Ie,function(Fe){if(!O(Ie,Fe))if(Fe==="rpc")Be(Ie,Fe);else throw pe(Fe)}),ie.add(Ie),ie===oe&&ue.push(Ie)}function Be(ie,be){var Ie=I(),Le=be;if(!nameRe.test(be=b()))throw pe(be,"name");var Fe=be,He,tt,Ne,nt;if(M("("),M("stream",!0)&&(tt=!0),!typeRefRe.test(be=b())||(He=be,M(")"),M("returns"),M("("),M("stream",!0)&&(nt=!0),!typeRefRe.test(be=b())))throw pe(be);Ne=be,M(")");var it=new Method(Fe,Le,He,Ne,tt,nt);it.comment=Ie,L(it,function(ut){if(ut==="option")he(it,ut),M(";");else throw pe(ut)}),ie.add(it)}function ae(ie,be){if(!typeRefRe.test(be=b()))throw pe(be,"reference");var Ie=be;L(null,function(Fe){switch(Fe){case"required":case"repeated":j(ie,Fe,Ie);break;case"optional":X==="proto3"?j(ie,"proto3_optional",Ie):j(ie,"optional",Ie);break;default:if(X==="proto2"||!typeRefRe.test(Fe))throw pe(Fe);E(Fe),j(ie,"optional",Ie);break}})}for(var de;(de=b())!==null;)switch(de){case"package":if(!B)throw pe(de);je();break;case"import":if(!B)throw pe(de);we();break;case"syntax":if(!B)throw pe(de);D();break;case"edition":if(!B)throw pe(de);q();break;case"option":he(oe,de),M(";",!0);break;default:if(O(oe,de)){B=!1;continue}throw pe(de)}return me(),parse.filename=null,{package:C,imports:N,weakImports:Z,root:u}}var common_1=common,commonRe=/\/|\./;function common(y,u){commonRe.test(y)||(y="google/protobuf/"+y+".proto",u={nested:{google:{nested:{protobuf:{nested:u}}}}}),common[y]=u}common("any",{Any:{fields:{type_url:{type:"string",id:1},value:{type:"bytes",id:2}}}});var timeType;common("duration",{Duration:timeType={fields:{seconds:{type:"int64",id:1},nanos:{type:"int32",id:2}}}}),common("timestamp",{Timestamp:timeType}),common("empty",{Empty:{fields:{}}}),common("struct",{Struct:{fields:{fields:{keyType:"string",type:"Value",id:1}}},Value:{oneofs:{kind:{oneof:["nullValue","numberValue","stringValue","boolValue","structValue","listValue"]}},fields:{nullValue:{type:"NullValue",id:1},numberValue:{type:"double",id:2},stringValue:{type:"string",id:3},boolValue:{type:"bool",id:4},structValue:{type:"Struct",id:5},listValue:{type:"ListValue",id:6}}},NullValue:{values:{NULL_VALUE:0}},ListValue:{fields:{values:{rule:"repeated",type:"Value",id:1}}}}),common("wrappers",{DoubleValue:{fields:{value:{type:"double",id:1}}},FloatValue:{fields:{value:{type:"float",id:1}}},Int64Value:{fields:{value:{type:"int64",id:1}}},UInt64Value:{fields:{value:{type:"uint64",id:1}}},Int32Value:{fields:{value:{type:"int32",id:1}}},UInt32Value:{fields:{value:{type:"uint32",id:1}}},BoolValue:{fields:{value:{type:"bool",id:1}}},StringValue:{fields:{value:{type:"string",id:1}}},BytesValue:{fields:{value:{type:"bytes",id:1}}}}),common("field_mask",{FieldMask:{fields:{paths:{rule:"repeated",type:"string",id:1}}}}),common.get=function y(u){return common[u]||null};var protobuf$1=src.exports=indexLightExports;protobuf$1.build="full",protobuf$1.tokenize=tokenize_1,protobuf$1.parse=parse_1,protobuf$1.common=common_1,protobuf$1.Root._configure(protobuf$1.Type,protobuf$1.parse,protobuf$1.common);var srcExports=src.exports,protobufjs=srcExports;const protobuf=getDefaultExportFromCjs$1(protobufjs);class Waku{constructor(u,h,v){this.node=u,this.chatTopic=h,this.onMessage=v,this.logger=Logger$1.getInstance(),this.errorHandler=ErrorHandler.getInstance(),this.reliableChannel=null,this.decoder=null,this.messagePayloadType=null,this.messageReceivedListener=null,this.senderId=crypto$1.randomBytes(8).toString("hex"),this.handleMessageReceived=async({payload:w})=>{try{if(!w){this.logger.warn("Received Waku message without payload");return}if(!this.messagePayloadType)throw new Error("Protobuf schema not initialized");const b=this.messagePayloadType.decode(w),E=this.messagePayloadType.toObject(b,{longs:String,enums:String,defaults:!0});if(!E.message){this.logger.warn("Decoded object has no message field");return}let $=E.message.additionalProps;if($&&typeof $=="string")try{$=JSON.parse($)}catch{this.logger.warn("Failed to parse additionalProps as JSON:",$)}const M={...E.message,timestamp:Number(E.message.timestamp),additionalProps:$};if(!(M!=null&&M.id)){this.logger.warn("Received invalid message structure via Waku");return}this.onMessage(M)}catch(b){this.errorHandler.handleError(b,"Waku2.handleMessageReceived")}}}async start(){this.createProtobufSchema(),await this.createChannel()}createProtobufSchema(){const u=new protobuf.Type("MessageData").add(new protobuf.Field("id",1,"string")).add(new protobuf.Field("targetMessageId",2,"string","optional")).add(new protobuf.Field("type",3,"string")).add(new protobuf.Field("message",4,"string")).add(new protobuf.Field("username",5,"string")).add(new protobuf.Field("address",6,"string")).add(new protobuf.Field("timestamp",7,"uint64")).add(new protobuf.Field("signature",8,"string")).add(new protobuf.Field("index",9,"uint32")).add(new protobuf.Field("chatTopic",10,"string")).add(new protobuf.Field("userTopic",11,"string")).add(new protobuf.Field("additionalProps",12,"string","optional")),h=new protobuf.Type("MessageStateRef").add(new protobuf.Field("reference",1,"string")).add(new protobuf.Field("timestamp",2,"uint64"));this.messagePayloadType=new protobuf.Type("MessagePayload").add(u).add(h).add(new protobuf.Field("message",1,"MessageData")).add(new protobuf.Field("messageStateRefs",2,"MessageStateRef","repeated")),this.logger.info("Protobuf schema created for chat messages")}async createChannel(){if(!this.node)throw new Error("Waku node not initialized");const u=`/solarpunk-msrs-chat/1/${this.chatTopic}/proto`,h=`chat-channel-${this.chatTopic}`,v=this.node.createEncoder({contentTopic:u}),w=this.decoder=this.node.createDecoder({contentTopic:u});this.reliableChannel=await ReliableChannel.create(this.node,h,this.senderId,v,w,{retrieveFrequencyMs:3e3,queryOnConnect:!1}),this.setupChannelEventListeners(this.reliableChannel),this.logger.info(`Created reliable channel for topic: ${this.chatTopic}`)}setupChannelEventListeners(u){this.messageReceivedListener=h=>{this.handleMessageReceived(h.detail)},u.addEventListener("message-received",this.messageReceivedListener)}async stop(){this.reliableChannel&&this.messageReceivedListener&&this.decoder&&(this.reliableChannel.removeEventListener("message-received",this.messageReceivedListener),this.messageReceivedListener=null,await this.reliableChannel.stop(),this.logger.info("Waku reliable channel stopped"))}}class SwarmChat{constructor(u){this.waku=null,this.logger=Logger$1.getInstance(),this.errorHandler=ErrorHandler.getInstance(),this.gsocIndex=null,this.fetchProcessRunning=!1,this.stopFetch=!1;const h=new beeJs.PrivateKey(remove0x(u.user.privateKey));this.userDetails={privateKey:u.user.privateKey,ownAddress:h.publicKey().address().toString(),nickname:u.user.nickname,ownIndex:-1},this.swarmSettings={bee:new beeJs.Bee(u.infra.beeUrl),beeUrl:u.infra.beeUrl,stamp:u.infra.stamp||"0x0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef",enveloped:u.infra.enveloped,gsocTopic:u.infra.gsocTopic,gsocResourceId:u.infra.gsocResourceId,chatTopic:u.infra.chatTopic,chatAddress:u.infra.chatAddress,wakuNode:u.infra.wakuNode},this.emitter=new EventEmitter$2,this.utils=new SwarmChatUtils(this.userDetails,this.swarmSettings),this.history=new SwarmHistory(this.utils,this.emitter)}async start(){await this.init(),await this.startMessageFetchProcess()}async startMessageFetchProcess(){const{wakuNode:u}=this.swarmSettings;u?await this.startWakuMessageFetch(u):await this.startPollingMessageFetch()}async stop(){this.emitter.cleanAll(),this.stopPollingMessageFetch(),this.history.cleanup(),this.waku&&(await this.waku.stop(),this.waku=null)}async startWakuMessageFetch(u){this.logger.info("Waku is enabled");const h=this.swarmSettings.chatTopic;this.waku=new Waku(u,h,v=>{this.emitter.emit(EVENTS.MESSAGE_RECEIVED,v)}),await this.waku.start()}getEmitter(){return this.emitter}orderMessages(u){return this.utils.orderMessages(u)}async sendMessage(u,h,v,w,b){const E=this.userDetails.ownIndex===-1?0:this.userDetails.ownIndex+1,$={id:w||v4(),username:this.userDetails.nickname,address:this.userDetails.ownAddress,chatTopic:this.swarmSettings.chatTopic,userTopic:this.utils.generateUserOwnedFeedId(this.swarmSettings.chatTopic,this.userDetails.ownAddress),signature:this.getSignature(u),timestamp:Date.now(),index:E,type:h,targetMessageId:v,message:u,additionalProps:b},M=validateMessageWithAdditionalProperties($);if(!M.isValid){const I=`Invalid message: ${M.errors.join(", ")}`;throw this.logger.error(I),new Error(I)}try{this.emitter.emit(EVENTS.MESSAGE_REQUEST_INITIATED,$),await this.utils.writeOwnFeedDataByIndex(E,JSON.stringify($)),this.userDetails.ownIndex=E,this.emitter.emit(EVENTS.MESSAGE_REQUEST_UPLOADED,$),await this.broadcastUserMessage($)}catch(I){this.emitter.emit(EVENTS.MESSAGE_REQUEST_ERROR,$),this.errorHandler.handleError(I,"Chat.sendMessage")}}async fetchPreviousMessages(){try{return this.emitter.emit(EVENTS.LOADING_PREVIOUS_MESSAGES,!0),await this.history.fetchPreviousMessageState()}finally{this.emitter.emit(EVENTS.LOADING_PREVIOUS_MESSAGES,!1)}}hasPreviousMessages(){return this.history.hasPreviousMessages()}async retrySendMessage(u){this.sendMessage(u.message,u.type,u.targetMessageId,u.id,u.additionalProps)}async retryBroadcastUserMessage(u){await this.broadcastUserMessage(u)}async init(){try{this.emitter.emit(EVENTS.LOADING_INIT,!0);const[u,h]=await Promise.allSettled([this.initOwnIndex(),this.history.init()]);if(u.status==="rejected")throw u.reason;h.status==="fulfilled"&&(this.gsocIndex=h.value),this.emitter.emit(EVENTS.LOADING_INIT,!1)}catch(u){this.errorHandler.handleError(u,"Chat.initSelfState"),this.emitter.emit(EVENTS.CRITICAL_ERROR,u)}}async initOwnIndex(){const{latestIndex:v}=await retryAwaitableAsync(()=>this.utils.getOwnLatestFeedIndex(),10,1e3);this.userDetails.ownIndex=v}async fetchLatestMessage(){try{if(!this.gsocIndex)return;const u=beeJs.Topic.fromString(this.swarmSettings.chatTopic),h=makeFeedIdentifier(u,this.gsocIndex),v=await this.utils.rawSocDownload(this.swarmSettings.chatAddress,h.toString()),w=JSON.parse(v);if(!validateGsocMessage(w)){this.logger.warn("Invalid GSOC message during fetching");return}this.emitter.emit(EVENTS.MESSAGE_RECEIVED,w.message),this.gsocIndex=this.gsocIndex.next()}catch(u){if(this.utils.isNotFoundError(u))return;this.errorHandler.handleError(u,"Chat.fetchLatestMessage")}}async broadcastUserMessage(u){try{return retryAwaitableAsync(()=>this.utils.sendMessageToGsoc(JSON.stringify(u)))}catch(h){this.errorHandler.handleError(h,"Chat.broadcastUserMessage")}}getSignature(u){const{ownAddress:h,privateKey:v,nickname:w}=this.userDetails,b=new beeJs.EthAddress(h).toString(),E=new beeJs.PrivateKey(v);if(E.publicKey().address().toString()!==b)throw new Error("The provided address does not match the address derived from the private key");const M=Date.now();return E.sign(JSON.stringify({username:w,address:b,message:u,timestamp:M})).toHex()}async startPollingMessageFetch(){if(this.fetchProcessRunning)return;this.fetchProcessRunning=!0,this.stopFetch=!1;const u=async()=>{if(this.stopFetch){this.fetchProcessRunning=!1;return}await this.fetchLatestMessage(),setTimeout(u,200)};u()}stopPollingMessageFetch(){this.stopFetch=!0}}exports.EVENTS=EVENTS,exports.MessageType=MessageType,exports.SwarmChat=SwarmChat,Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"})});
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@solarpunkltd/swarm-chat-js",
|
|
3
|
-
"version": "6.1.
|
|
3
|
+
"version": "6.1.4",
|
|
4
4
|
"description": "JS library for chatting on Swarm",
|
|
5
5
|
"main": "dist/index.js",
|
|
6
6
|
"module": "dist/index.esm.js",
|
|
@@ -29,7 +29,7 @@
|
|
|
29
29
|
},
|
|
30
30
|
"dependencies": {
|
|
31
31
|
"@ethersphere/bee-js": "^9.0.3",
|
|
32
|
-
"@solarpunkltd/waku-sdk": "^0.0.
|
|
32
|
+
"@solarpunkltd/waku-sdk": "^0.0.37",
|
|
33
33
|
"@waku/utils": "^0.0.27",
|
|
34
34
|
"cafe-utility": "^27.12.1",
|
|
35
35
|
"protobufjs": "^7.5.4",
|