@jokio/sdk 0.3.4 → 0.3.5
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/jokio.sdk.es.js +6 -5
- package/dist/jokio.sdk.umd.js +1 -1
- package/package.json +1 -1
package/dist/jokio.sdk.es.js
CHANGED
|
@@ -8351,23 +8351,24 @@ class Tr {
|
|
|
8351
8351
|
});
|
|
8352
8352
|
o.reply && o.respond(
|
|
8353
8353
|
$e.encode({
|
|
8354
|
-
ok: !0,
|
|
8355
8354
|
data: x
|
|
8356
8355
|
})
|
|
8357
8356
|
);
|
|
8358
8357
|
} catch (x) {
|
|
8359
8358
|
console.error("[nats] handle", x), o.reply && o.respond(
|
|
8360
8359
|
$e.encode({
|
|
8361
|
-
|
|
8362
|
-
|
|
8360
|
+
error: {
|
|
8361
|
+
message: x.message
|
|
8362
|
+
}
|
|
8363
8363
|
})
|
|
8364
8364
|
);
|
|
8365
8365
|
}
|
|
8366
8366
|
} catch (a) {
|
|
8367
8367
|
console.error("[nats] handle", a), o.reply && o.respond(
|
|
8368
8368
|
$e.encode({
|
|
8369
|
-
|
|
8370
|
-
|
|
8369
|
+
error: {
|
|
8370
|
+
message: a.message
|
|
8371
|
+
}
|
|
8371
8372
|
})
|
|
8372
8373
|
);
|
|
8373
8374
|
}
|
package/dist/jokio.sdk.umd.js
CHANGED
|
@@ -26,7 +26,7 @@ ${d}`),y(I);return}a(null,T),s.strategy===Oe.Count&&(p--,p===0&&y()),s.strategy=
|
|
|
26
26
|
|
|
27
27
|
${a.stack}`),d.unsubscribe(),o.reject(p)):(p=fr(g),p?(a&&(p.stack+=`
|
|
28
28
|
|
|
29
|
-
${a.stack}`),o.reject(p)):o.resolve(g))}});return d.requestSubject=e,this.protocol.publish(e,t,{reply:n,headers:s.headers}),o}else{const n=new Sr(this.protocol.muxSubscriptions,e,s,i);this.protocol.request(n);try{this.publish(e,t,{reply:`${this.protocol.muxSubscriptions.baseInbox}${n.token}`,headers:s.headers})}catch(a){n.cancel(a)}const o=Promise.race([n.timer,n.deferred]);return o.catch(()=>{n.cancel()}),o}}flush(){return this.isClosed()?Promise.reject(N.errorForCode(O.ConnectionClosed)):this.protocol.flush()}drain(){return this.isClosed()?Promise.reject(N.errorForCode(O.ConnectionClosed)):this.isDraining()?Promise.reject(N.errorForCode(O.ConnectionDraining)):(this.draining=!0,this.protocol.drain())}isClosed(){return this.protocol.isClosed()}isDraining(){return this.draining}getServer(){const e=this.protocol.getServer();return e?e.listen:""}status(){const e=new re;return e.iterClosed.then(()=>{const t=this.listeners.indexOf(e);this.listeners.splice(t,1)}),this.listeners.push(e),e}get info(){return this.protocol.isClosed()?void 0:this.protocol.info}async context(){return(await this.request("$SYS.REQ.USER.INFO")).json((t,s)=>t==="time"?new Date(Date.parse(s)):s)}stats(){return{inBytes:this.protocol.inBytes,outBytes:this.protocol.outBytes,inMsgs:this.protocol.inMsgs,outMsgs:this.protocol.outMsgs}}async jetstreamManager(e={}){const t=new so(this,e);if(e.checkAPI!==!1)try{await t.getAccountInfo()}catch(s){const i=s;throw i.code===O.NoResponders&&(i.code=O.JetStreamNotEnabled),i}return t}jetstream(e={}){return new Us(this,e)}getServerVersion(){const e=this.info;return e?Ke(e.version):void 0}async rtt(){if(!this.protocol._closed&&!this.protocol.connected)throw N.errorForCode(O.Disconnect);const e=Date.now();return await this.flush(),Date.now()-e}get features(){return this.protocol.features}get services(){return this._services||(this._services=new oo(this)),this._services}reconnect(){return this.isClosed()?Promise.reject(N.errorForCode(O.ConnectionClosed)):this.isDraining()?Promise.reject(N.errorForCode(O.ConnectionDraining)):this.protocol.reconnect()}}class oo{constructor(e){h(this,"nc");this.nc=e}add(e){try{return new xt(this.nc,e).start()}catch(t){return Promise.reject(t)}}client(e,t){return new qn(this.nc,e,t)}}class ao{constructor(e,t,s){h(this,"bucket");h(this,"sm");h(this,"prefixLen");this.bucket=e,this.prefixLen=t,this.sm=s}get key(){return this.sm.subject.substring(this.prefixLen)}get value(){return this.sm.data}get delta(){return 0}get created(){return this.sm.time}get revision(){return this.sm.seq}get operation(){return this.sm.header.get(zt)||"PUT"}get length(){const e=this.sm.header.get(fe.MessageSizeHdr)||"";return e!==""?parseInt(e,10):this.sm.data.length}json(){return this.sm.json()}string(){return this.sm.string()}}class co{constructor(e,t,s){h(this,"bucket");h(this,"key");h(this,"sm");this.bucket=e,this.key=t,this.sm=s}get value(){return this.sm.data}get created(){return new Date(ls(this.sm.info.timestampNanos))}get revision(){return this.sm.seq}get operation(){var e;return((e=this.sm.headers)==null?void 0:e.get(zt))||"PUT"}get delta(){return this.sm.info.pending}get length(){var t;const e=((t=this.sm.headers)==null?void 0:t.get(fe.MessageSizeHdr))||"";return e!==""?parseInt(e,10):this.sm.data.length}json(){return this.sm.json()}string(){return this.sm.string()}}class Hr extends Yi{constructor(t,s,i){super(t.nc,s,i);h(this,"js");h(this,"monitor");this.js=t,this.monitor=null,this.sub.closed.then(()=>{this.monitor&&this.monitor.cancel()})}set info(t){this.sub.info=t}get info(){return this.sub.info}_resetOrderedConsumer(t){if(this.info===null||this.sub.isClosed())return;const s=Ue(this.js.nc.options.inboxPrefix);this.js.nc._resub(this.sub,s);const n=this.info;n.config.name=qe.next(),n.ordered_consumer_sequence.delivery_seq=0,n.flow_control.heartbeat_count=0,n.flow_control.fc_count=0,n.flow_control.consumer_restarts++,n.deliver=s,n.config.deliver_subject=s,n.config.deliver_policy=Z.StartSequence,n.config.opt_start_seq=t;const o={};o.stream_name=this.info.stream,o.config=n.config;const a=`${n.api.prefix}.CONSUMER.CREATE.${n.stream}`;this.js._request(a,o,{retries:-1}).then(d=>{const p=d,g=this.sub.info;g.last=p,this.info.config=p.config,this.info.name=p.name}).catch(d=>{const p=new N(`unable to recreate ordered consumer ${n.stream} at seq ${t}`,O.RequestError,d);this.sub.callback(p,{})})}_maybeSetupHbMonitoring(){var s,i;const t=((i=(s=this.info)==null?void 0:s.config)==null?void 0:i.idle_heartbeat)||0;t&&this._setupHbMonitoring(ls(t))}_setupHbMonitoring(t,s=0){const i={cancelAfter:0,maxOut:2};s&&(i.cancelAfter=s);const n=this.sub,o=a=>{var g,y,x,P;const d=Ii(409,`${Ee.IdleHeartbeatMissed}: ${a}`,this.sub.subject);if(!((g=this.info)==null?void 0:g.ordered))this.sub.callback(null,d);else{if(!this.js.nc.protocol.connected)return!1;const I=((x=(y=this.info)==null?void 0:y.ordered_consumer_sequence)==null?void 0:x.stream_seq)||0;return this._resetOrderedConsumer(I+1),(P=this.monitor)==null||P.restart(),!1}return!n.noIterator};this.monitor=new bs(t,o,i)}_checkHbOrderConsumer(t){const s=t.headers.get(fe.ConsumerStalledHdr);s!==""&&this.js.nc.publish(s);const i=parseInt(t.headers.get(fe.LastConsumerSeqHdr),10),n=this.info.ordered_consumer_sequence;return this.info.flow_control.heartbeat_count++,i!==n.delivery_seq&&this._resetOrderedConsumer(n.stream_seq+1),!1}_checkOrderedConsumer(t){const s=this.info.ordered_consumer_sequence,i=t.info.streamSequence,n=t.info.deliverySequence;return n!=s.delivery_seq+1?(this._resetOrderedConsumer(s.stream_seq+1),!1):(s.delivery_seq=n,s.stream_seq=i,!0)}async destroy(){this.isClosed()||await this.drain();const t=this.sub.info,s=t.config.durable_name||t.name,i=`${t.api.prefix}.CONSUMER.DELETE.${t.stream}.${s}`;await t.api._request(i)}async consumerInfo(){const t=this.sub.info,s=t.config.durable_name||t.name,i=`${t.api.prefix}.CONSUMER.INFO.${t.stream}.${s}`,n=await t.api._request(i);return t.last=n,n}}class ho extends Hr{constructor(e,t,s){super(e,t,s)}pull(e={batch:1}){const{stream:t,config:s,name:i}=this.sub.info,n=s.durable_name??i,o={};if(o.batch=e.batch||1,o.no_wait=e.no_wait||!1,(e.max_bytes??0)>0){const p=this.js.nc.features.get(H.JS_PULL_MAX_BYTES);if(!p.ok)throw new Error(`max_bytes is only supported on servers ${p.min} or better`);o.max_bytes=e.max_bytes}let a=0;e.expires&&e.expires>0&&(a=e.expires,o.expires=G(a));let d=0;if(e.idle_heartbeat&&e.idle_heartbeat>0&&(d=e.idle_heartbeat,o.idle_heartbeat=G(d)),d&&a===0)throw new Error("idle_heartbeat requires expires");if(d>a)throw new Error("expires must be greater than idle_heartbeat");if(this.info){this.monitor&&this.monitor.cancel(),a&&d&&(this.monitor?this.monitor._change(d,a):this._setupHbMonitoring(d,a));const p=this.info.api,g=`${p.prefix}.CONSUMER.MSG.NEXT.${t}.${n}`,y=this.sub.subject;p.nc.publish(g,p.jc.encode(o),{reply:y})}}}function uo(r,e){return r?fo(e):lo(e)}function lo(r){return(e,t)=>e?[e,null]:(e=et(t),e?[e,null]:[null,Et(t,r)])}function fo(r){return(e,t)=>{if(e)return[e,null];const s=et(t);return s!==null?[Jr(s),null]:[null,Et(t,r)]}}function Jr(r){if(r!==null)switch(r.code){case O.JetStream404NoMessages:case O.JetStream408RequestTimeout:return null;case O.JetStream409:return ji(r)?r:null;default:return r}return null}function po(r){r&&r.ack()}function mo(r){const e=r.split(".");if(e.length===9&&e.splice(2,0,"_",""),e.length<11||e[0]!=="$JS"||e[1]!=="ACK")throw new Error("not js message");const t={};return t.domain=e[2]==="_"?"":e[2],t.account_hash=e[3],t.stream=e[4],t.consumer=e[5],t.deliveryCount=parseInt(e[6],10),t.redeliveryCount=t.deliveryCount,t.redelivered=t.deliveryCount>1,t.streamSequence=parseInt(e[7],10),t.deliverySequence=parseInt(e[8],10),t.timestampNanos=parseInt(e[9],10),t.pending=parseInt(e[10],10),t}class bo{constructor(e,t){h(this,"msg");h(this,"di");h(this,"didAck");h(this,"timeout");this.msg=e,this.didAck=!1,this.timeout=t}get subject(){return this.msg.subject}get sid(){return this.msg.sid}get data(){return this.msg.data}get headers(){return this.msg.headers}get info(){return this.di||(this.di=mo(this.reply)),this.di}get redelivered(){return this.info.deliveryCount>1}get reply(){return this.msg.reply||""}get seq(){return this.info.streamSequence}doAck(e){this.didAck||(this.didAck=!this.isWIP(e),this.msg.respond(e))}isWIP(e){return e.length===4&&e[0]===vt[0]&&e[1]===vt[1]&&e[2]===vt[2]&&e[3]===vt[3]}async ackAck(e){var s;e=e||{},e.timeout=e.timeout||this.timeout;const t=z();if(this.didAck)t.resolve(!1);else if(this.didAck=!0,this.msg.reply){const n=this.msg.publisher,o=!((s=n.options)!=null&&s.noAsyncTraces),a=new Sr(n.muxSubscriptions,this.msg.reply,{timeout:e.timeout},o);n.request(a);try{n.publish(this.msg.reply,Fr,{reply:`${n.muxSubscriptions.baseInbox}${a.token}`})}catch(d){a.cancel(d)}try{await Promise.race([a.timer,a.deferred]),t.resolve(!0)}catch(d){a.cancel(d),t.reject(d)}}else t.resolve(!1);return t}ack(){this.doAck(Fr)}nak(e){let t=Wn;e&&(t=lr().encode(`-NAK ${JSON.stringify({delay:G(e)})}`)),this.doAck(t)}working(){this.doAck(vt)}next(e,t={batch:1}){const s={};s.batch=t.batch||1,s.no_wait=t.no_wait||!1,t.expires&&t.expires>0&&(s.expires=G(t.expires));const i=ve().encode(s),n=it.concat(Yn,Zn,i),o=e?{reply:e}:void 0;this.msg.respond(n,o)}term(e=""){let t=Xn;(e==null?void 0:e.length)>0&&(t=lr().encode(`+TERM ${e}`)),this.doAck(t)}json(){return this.msg.json()}string(){return this.msg.string()}}const go="1.30.3",_o="nats.ws";class yo{constructor(){h(this,"version");h(this,"lang");h(this,"closeError");h(this,"connected");h(this,"done");h(this,"socket");h(this,"options");h(this,"socketClosed");h(this,"encrypted");h(this,"peeked");h(this,"yields");h(this,"signal");h(this,"closedNotification");this.version=go,this.lang=_o,this.connected=!1,this.done=!1,this.socketClosed=!1,this.encrypted=!1,this.peeked=!1,this.yields=[],this.signal=z(),this.closedNotification=z()}async connect(e,t){const s=z();if(t.tls)return s.reject(new N("tls",O.InvalidOption)),s;this.options=t;const i=e.src;if(t.wsFactory){const{socket:n,encrypted:o}=await t.wsFactory(e.src,t);this.socket=n,this.encrypted=o}else this.encrypted=i.indexOf("wss://")===0,this.socket=new WebSocket(i);return this.socket.binaryType="arraybuffer",this.socket.onopen=()=>{this.isDiscarded()},this.socket.onmessage=n=>{if(this.isDiscarded())return;if(this.yields.push(new Uint8Array(n.data)),this.peeked){this.signal.resolve();return}const o=it.concat(...this.yields),a=sn(o);if(a!==""){const d=jn.exec(a);if(!d){t.debug&&console.error("!!!",Mt(o)),s.reject(new Error("unexpected response from server"));return}try{const p=JSON.parse(d[1]);Cn(p,this.options),this.peeked=!0,this.connected=!0,this.signal.resolve(),s.resolve()}catch(p){s.reject(p);return}}},this.socket.onclose=n=>{if(this.isDiscarded())return;this.socketClosed=!0;let o;this.done||(n.wasClean||(o=new Error(n.reason)),this._closed(o))},this.socket.onerror=n=>{if(this.isDiscarded())return;const o=n,a=new N(o.message,O.Unknown,new Error(o.error));s.reject(a)},s}disconnect(){this._closed(void 0,!0)}async _closed(e,t=!0){if(!this.isDiscarded()&&this.connected&&!this.done){if(this.closeError=e,!e)for(;!this.socketClosed&&this.socket.bufferedAmount>0;)await Ze(100);this.done=!0;try{this.socket.close(e?1002:1e3,e?e.message:void 0)}catch{}t&&this.closedNotification.resolve(e)}}get isClosed(){return this.done}[Symbol.asyncIterator](){return this.iterate()}async*iterate(){for(;;){if(this.isDiscarded())return;this.yields.length===0&&await this.signal;const e=this.yields;this.yields=[];for(let t=0;t<e.length;t++)this.options.debug&&console.info(`> ${Mt(e[t])}`),yield e[t];if(this.done)break;this.yields.length===0&&(e.length=0,this.yields=e,this.signal=z())}}isEncrypted(){return this.connected&&this.encrypted}send(e){if(!this.isDiscarded())try{this.socket.send(e.buffer),this.options.debug&&console.info(`< ${Mt(e)}`);return}catch(t){this.options.debug&&console.error(`!!! ${Mt(e)}: ${t}`)}}close(e){return this._closed(e,!1)}closed(){return this.closedNotification}isDiscarded(){return this.done?(this.discard(),!0):!1}discard(){var e;this.done=!0;try{(e=this.socket)==null||e.close()}catch{}}}function wo(r,e){/^(.*:\/\/)(.*)/.test(r)||(typeof e=="boolean"?r=`${e===!0?"https":"http"}://${r}`:r=`https://${r}`);let s=new URL(r);const i=s.protocol.toLowerCase();i==="ws:"&&(e=!1),i==="wss:"&&(e=!0),i!=="https:"&&i!=="http"&&(r=r.replace(/^(.*:\/\/)(.*)/gm,"$2"),s=new URL(`http://${r}`));let n,o;const a=s.hostname,d=s.pathname,p=s.search||"";switch(i){case"http:":case"ws:":case"nats:":o=s.port||"80",n="ws:";break;case"https:":case"wss:":case"tls:":o=s.port||"443",n="wss:";break;default:o=s.port||e===!0?"443":"80",n=e===!0?"wss:":"ws:";break}return`${n}//${a}:${o}${d}${p}`}function xo(r={}){return Xi({defaultPort:443,urlParseFn:wo,factory:()=>new yo}),$s.connect(r)}const ze=ve();class Ls{constructor(e){h(this,"onStatusChange");h(this,"nc");h(this,"sessionId","");h(this,"userId","");h(this,"globalPrefix","");h(this,"resolveConnected",e=>{});h(this,"isConnected",new Promise(e=>this.resolveConnected=e));this.config=e}get url(){return this.config.natsUrl}async connect(e={}){var a;const{natsWsServerUrls:t,user:s,prefix:i}=e,n=t??[this.config.natsUrl];this.nc=await xo({servers:n});const o=s??await this.config.auth.getLastLoginData();if(!o)throw new Error("Please authenticate first by calling `auth` apis");this.userId=o.userId,this.sessionId=o.sessionId,this.globalPrefix=i??"",this.resolveConnected(!0),(a=this.onStatusChange)==null||a.call(this,!0),console.log("[nats] connected.",this.globalPrefix?`(prefix: ${this.globalPrefix})`:""),(async()=>{var d,p;for await(const g of this.nc.status())switch(g.type!==Fe.PingTimer&&console.log("[nats] connection status:",g.type),g.type){case Se.Reconnect:(d=this.onStatusChange)==null||d.call(this,!0);break;case Se.Disconnect:case Se.Error:case Fe.Reconnecting:(p=this.onStatusChange)==null||p.call(this,!1);break}})()}async disconnect(){var e,t;await((e=this.nc)==null?void 0:e.drain()),await((t=this.nc)==null?void 0:t.close())}async publish(e,t){if(await this.isConnected,!this.nc)throw new Error("[nats] not connected");try{const s=this.buildSubject(e);console.debug("[nats]>>",s),this.nc.publish(s,ze.encode(t))}catch(s){throw console.error("[nats] publish failed:",s),s}}async call(e,t,s){var a;if(await this.isConnected,!this.nc)throw new Error("[nats] not connected");const i=this.buildSubject(e);console.debug("[nats]>>",i);const n=await this.nc.request(i,ze.encode(t),{timeout:(s==null?void 0:s.timeoutInMs)??5e3}),o=ze.decode(n.data);if(o.error)throw new Error(o.error.message);if((a=o.payload)!=null&&a.errorData)throw new Error(o.payload.errorData.message);return o.data??o.payload}async on(e,t){if(await this.isConnected,!this.nc)throw new Error("[nats] not connected");const i=(this.globalPrefix?`${this.globalPrefix}.`:"")+e+".>",n=this.nc.subscribe(i);return(async()=>{for await(const o of n)try{console.debug("[nats]<<",o.subject);const a=o.subject.split(".");if(this.globalPrefix&&a[0]!==this.globalPrefix){console.log("[nats]","Skipped - "+o.subject);continue}a[0]==="dev"&&a.shift();const d=a.slice(0,a.length-2).join("."),p=a[a.length-2],g=a[a.length-1],y=ze.decode(o.data);t(y,{subject:d,userId:p,sessionId:g})}catch(a){console.error("[nats] subscribe error",a)}})(),()=>n.unsubscribe()}async handler(e,t){if(await this.isConnected,!this.nc)throw new Error("[nats] not connected");const i=(this.globalPrefix?`${this.globalPrefix}.`:"")+e+".>",n=this.nc.subscribe(i);return(async()=>{for await(const o of n)try{console.debug("[nats]<<",o.subject);const a=o.subject.split(".");if(this.globalPrefix&&a[0]!==this.globalPrefix){console.log("[nats]","Skipped - "+o.subject);continue}a[0]==="dev"&&a.shift();const d=a.slice(0,a.length-2).join("."),p=a[a.length-2],g=a[a.length-1],y=ze.decode(o.data);try{const x=await t(y,{subject:d,userId:p,sessionId:g});o.reply&&o.respond(ze.encode({ok:!0,data:x}))}catch(x){console.error("[nats] handle",x),o.reply&&o.respond(ze.encode({ok:!1,message:x.message}))}}catch(a){console.error("[nats] handle",a),o.reply&&o.respond(ze.encode({ok:!1,message:a.message}))}})(),()=>n.unsubscribe()}buildSubject(e){return[this.globalPrefix,e,this.userId,this.sessionId].filter(t=>t).join(".")}}class zr{async setItem(e,t){if(!t)return this.removeItem(e);localStorage.setItem(e,JSON.stringify(t))}async getItem(e){const t=localStorage.getItem(e);if(!t)return null;try{return JSON.parse(t)}catch{return null}}async removeItem(e){localStorage.removeItem(e)}}function Gr(r){const e=new Blob([r],{type:"audio/mpeg"}),t=URL.createObjectURL(e),s=new Audio;return s.src=t,s.onended=()=>{URL.revokeObjectURL(t)},s}class So{async getAudioBuffer(e,t,s){const i=[],n=crypto.randomUUID();return new Promise((o,a)=>{const d=new WebSocket(`${Wt.WSS_URL}?trustedclienttoken=${Wt.TRUSTED_CLIENT_TOKEN}&ConnectionId=${n}`);d.binaryType="arraybuffer";const p=Eo(e,t,s);d.addEventListener("open",()=>{const g=vo();d.send(g);const y=`X-RequestId:${n}\r
|
|
29
|
+
${a.stack}`),o.reject(p)):o.resolve(g))}});return d.requestSubject=e,this.protocol.publish(e,t,{reply:n,headers:s.headers}),o}else{const n=new Sr(this.protocol.muxSubscriptions,e,s,i);this.protocol.request(n);try{this.publish(e,t,{reply:`${this.protocol.muxSubscriptions.baseInbox}${n.token}`,headers:s.headers})}catch(a){n.cancel(a)}const o=Promise.race([n.timer,n.deferred]);return o.catch(()=>{n.cancel()}),o}}flush(){return this.isClosed()?Promise.reject(N.errorForCode(O.ConnectionClosed)):this.protocol.flush()}drain(){return this.isClosed()?Promise.reject(N.errorForCode(O.ConnectionClosed)):this.isDraining()?Promise.reject(N.errorForCode(O.ConnectionDraining)):(this.draining=!0,this.protocol.drain())}isClosed(){return this.protocol.isClosed()}isDraining(){return this.draining}getServer(){const e=this.protocol.getServer();return e?e.listen:""}status(){const e=new re;return e.iterClosed.then(()=>{const t=this.listeners.indexOf(e);this.listeners.splice(t,1)}),this.listeners.push(e),e}get info(){return this.protocol.isClosed()?void 0:this.protocol.info}async context(){return(await this.request("$SYS.REQ.USER.INFO")).json((t,s)=>t==="time"?new Date(Date.parse(s)):s)}stats(){return{inBytes:this.protocol.inBytes,outBytes:this.protocol.outBytes,inMsgs:this.protocol.inMsgs,outMsgs:this.protocol.outMsgs}}async jetstreamManager(e={}){const t=new so(this,e);if(e.checkAPI!==!1)try{await t.getAccountInfo()}catch(s){const i=s;throw i.code===O.NoResponders&&(i.code=O.JetStreamNotEnabled),i}return t}jetstream(e={}){return new Us(this,e)}getServerVersion(){const e=this.info;return e?Ke(e.version):void 0}async rtt(){if(!this.protocol._closed&&!this.protocol.connected)throw N.errorForCode(O.Disconnect);const e=Date.now();return await this.flush(),Date.now()-e}get features(){return this.protocol.features}get services(){return this._services||(this._services=new oo(this)),this._services}reconnect(){return this.isClosed()?Promise.reject(N.errorForCode(O.ConnectionClosed)):this.isDraining()?Promise.reject(N.errorForCode(O.ConnectionDraining)):this.protocol.reconnect()}}class oo{constructor(e){h(this,"nc");this.nc=e}add(e){try{return new xt(this.nc,e).start()}catch(t){return Promise.reject(t)}}client(e,t){return new qn(this.nc,e,t)}}class ao{constructor(e,t,s){h(this,"bucket");h(this,"sm");h(this,"prefixLen");this.bucket=e,this.prefixLen=t,this.sm=s}get key(){return this.sm.subject.substring(this.prefixLen)}get value(){return this.sm.data}get delta(){return 0}get created(){return this.sm.time}get revision(){return this.sm.seq}get operation(){return this.sm.header.get(zt)||"PUT"}get length(){const e=this.sm.header.get(fe.MessageSizeHdr)||"";return e!==""?parseInt(e,10):this.sm.data.length}json(){return this.sm.json()}string(){return this.sm.string()}}class co{constructor(e,t,s){h(this,"bucket");h(this,"key");h(this,"sm");this.bucket=e,this.key=t,this.sm=s}get value(){return this.sm.data}get created(){return new Date(ls(this.sm.info.timestampNanos))}get revision(){return this.sm.seq}get operation(){var e;return((e=this.sm.headers)==null?void 0:e.get(zt))||"PUT"}get delta(){return this.sm.info.pending}get length(){var t;const e=((t=this.sm.headers)==null?void 0:t.get(fe.MessageSizeHdr))||"";return e!==""?parseInt(e,10):this.sm.data.length}json(){return this.sm.json()}string(){return this.sm.string()}}class Hr extends Yi{constructor(t,s,i){super(t.nc,s,i);h(this,"js");h(this,"monitor");this.js=t,this.monitor=null,this.sub.closed.then(()=>{this.monitor&&this.monitor.cancel()})}set info(t){this.sub.info=t}get info(){return this.sub.info}_resetOrderedConsumer(t){if(this.info===null||this.sub.isClosed())return;const s=Ue(this.js.nc.options.inboxPrefix);this.js.nc._resub(this.sub,s);const n=this.info;n.config.name=qe.next(),n.ordered_consumer_sequence.delivery_seq=0,n.flow_control.heartbeat_count=0,n.flow_control.fc_count=0,n.flow_control.consumer_restarts++,n.deliver=s,n.config.deliver_subject=s,n.config.deliver_policy=Z.StartSequence,n.config.opt_start_seq=t;const o={};o.stream_name=this.info.stream,o.config=n.config;const a=`${n.api.prefix}.CONSUMER.CREATE.${n.stream}`;this.js._request(a,o,{retries:-1}).then(d=>{const p=d,g=this.sub.info;g.last=p,this.info.config=p.config,this.info.name=p.name}).catch(d=>{const p=new N(`unable to recreate ordered consumer ${n.stream} at seq ${t}`,O.RequestError,d);this.sub.callback(p,{})})}_maybeSetupHbMonitoring(){var s,i;const t=((i=(s=this.info)==null?void 0:s.config)==null?void 0:i.idle_heartbeat)||0;t&&this._setupHbMonitoring(ls(t))}_setupHbMonitoring(t,s=0){const i={cancelAfter:0,maxOut:2};s&&(i.cancelAfter=s);const n=this.sub,o=a=>{var g,y,x,P;const d=Ii(409,`${Ee.IdleHeartbeatMissed}: ${a}`,this.sub.subject);if(!((g=this.info)==null?void 0:g.ordered))this.sub.callback(null,d);else{if(!this.js.nc.protocol.connected)return!1;const I=((x=(y=this.info)==null?void 0:y.ordered_consumer_sequence)==null?void 0:x.stream_seq)||0;return this._resetOrderedConsumer(I+1),(P=this.monitor)==null||P.restart(),!1}return!n.noIterator};this.monitor=new bs(t,o,i)}_checkHbOrderConsumer(t){const s=t.headers.get(fe.ConsumerStalledHdr);s!==""&&this.js.nc.publish(s);const i=parseInt(t.headers.get(fe.LastConsumerSeqHdr),10),n=this.info.ordered_consumer_sequence;return this.info.flow_control.heartbeat_count++,i!==n.delivery_seq&&this._resetOrderedConsumer(n.stream_seq+1),!1}_checkOrderedConsumer(t){const s=this.info.ordered_consumer_sequence,i=t.info.streamSequence,n=t.info.deliverySequence;return n!=s.delivery_seq+1?(this._resetOrderedConsumer(s.stream_seq+1),!1):(s.delivery_seq=n,s.stream_seq=i,!0)}async destroy(){this.isClosed()||await this.drain();const t=this.sub.info,s=t.config.durable_name||t.name,i=`${t.api.prefix}.CONSUMER.DELETE.${t.stream}.${s}`;await t.api._request(i)}async consumerInfo(){const t=this.sub.info,s=t.config.durable_name||t.name,i=`${t.api.prefix}.CONSUMER.INFO.${t.stream}.${s}`,n=await t.api._request(i);return t.last=n,n}}class ho extends Hr{constructor(e,t,s){super(e,t,s)}pull(e={batch:1}){const{stream:t,config:s,name:i}=this.sub.info,n=s.durable_name??i,o={};if(o.batch=e.batch||1,o.no_wait=e.no_wait||!1,(e.max_bytes??0)>0){const p=this.js.nc.features.get(H.JS_PULL_MAX_BYTES);if(!p.ok)throw new Error(`max_bytes is only supported on servers ${p.min} or better`);o.max_bytes=e.max_bytes}let a=0;e.expires&&e.expires>0&&(a=e.expires,o.expires=G(a));let d=0;if(e.idle_heartbeat&&e.idle_heartbeat>0&&(d=e.idle_heartbeat,o.idle_heartbeat=G(d)),d&&a===0)throw new Error("idle_heartbeat requires expires");if(d>a)throw new Error("expires must be greater than idle_heartbeat");if(this.info){this.monitor&&this.monitor.cancel(),a&&d&&(this.monitor?this.monitor._change(d,a):this._setupHbMonitoring(d,a));const p=this.info.api,g=`${p.prefix}.CONSUMER.MSG.NEXT.${t}.${n}`,y=this.sub.subject;p.nc.publish(g,p.jc.encode(o),{reply:y})}}}function uo(r,e){return r?fo(e):lo(e)}function lo(r){return(e,t)=>e?[e,null]:(e=et(t),e?[e,null]:[null,Et(t,r)])}function fo(r){return(e,t)=>{if(e)return[e,null];const s=et(t);return s!==null?[Jr(s),null]:[null,Et(t,r)]}}function Jr(r){if(r!==null)switch(r.code){case O.JetStream404NoMessages:case O.JetStream408RequestTimeout:return null;case O.JetStream409:return ji(r)?r:null;default:return r}return null}function po(r){r&&r.ack()}function mo(r){const e=r.split(".");if(e.length===9&&e.splice(2,0,"_",""),e.length<11||e[0]!=="$JS"||e[1]!=="ACK")throw new Error("not js message");const t={};return t.domain=e[2]==="_"?"":e[2],t.account_hash=e[3],t.stream=e[4],t.consumer=e[5],t.deliveryCount=parseInt(e[6],10),t.redeliveryCount=t.deliveryCount,t.redelivered=t.deliveryCount>1,t.streamSequence=parseInt(e[7],10),t.deliverySequence=parseInt(e[8],10),t.timestampNanos=parseInt(e[9],10),t.pending=parseInt(e[10],10),t}class bo{constructor(e,t){h(this,"msg");h(this,"di");h(this,"didAck");h(this,"timeout");this.msg=e,this.didAck=!1,this.timeout=t}get subject(){return this.msg.subject}get sid(){return this.msg.sid}get data(){return this.msg.data}get headers(){return this.msg.headers}get info(){return this.di||(this.di=mo(this.reply)),this.di}get redelivered(){return this.info.deliveryCount>1}get reply(){return this.msg.reply||""}get seq(){return this.info.streamSequence}doAck(e){this.didAck||(this.didAck=!this.isWIP(e),this.msg.respond(e))}isWIP(e){return e.length===4&&e[0]===vt[0]&&e[1]===vt[1]&&e[2]===vt[2]&&e[3]===vt[3]}async ackAck(e){var s;e=e||{},e.timeout=e.timeout||this.timeout;const t=z();if(this.didAck)t.resolve(!1);else if(this.didAck=!0,this.msg.reply){const n=this.msg.publisher,o=!((s=n.options)!=null&&s.noAsyncTraces),a=new Sr(n.muxSubscriptions,this.msg.reply,{timeout:e.timeout},o);n.request(a);try{n.publish(this.msg.reply,Fr,{reply:`${n.muxSubscriptions.baseInbox}${a.token}`})}catch(d){a.cancel(d)}try{await Promise.race([a.timer,a.deferred]),t.resolve(!0)}catch(d){a.cancel(d),t.reject(d)}}else t.resolve(!1);return t}ack(){this.doAck(Fr)}nak(e){let t=Wn;e&&(t=lr().encode(`-NAK ${JSON.stringify({delay:G(e)})}`)),this.doAck(t)}working(){this.doAck(vt)}next(e,t={batch:1}){const s={};s.batch=t.batch||1,s.no_wait=t.no_wait||!1,t.expires&&t.expires>0&&(s.expires=G(t.expires));const i=ve().encode(s),n=it.concat(Yn,Zn,i),o=e?{reply:e}:void 0;this.msg.respond(n,o)}term(e=""){let t=Xn;(e==null?void 0:e.length)>0&&(t=lr().encode(`+TERM ${e}`)),this.doAck(t)}json(){return this.msg.json()}string(){return this.msg.string()}}const go="1.30.3",_o="nats.ws";class yo{constructor(){h(this,"version");h(this,"lang");h(this,"closeError");h(this,"connected");h(this,"done");h(this,"socket");h(this,"options");h(this,"socketClosed");h(this,"encrypted");h(this,"peeked");h(this,"yields");h(this,"signal");h(this,"closedNotification");this.version=go,this.lang=_o,this.connected=!1,this.done=!1,this.socketClosed=!1,this.encrypted=!1,this.peeked=!1,this.yields=[],this.signal=z(),this.closedNotification=z()}async connect(e,t){const s=z();if(t.tls)return s.reject(new N("tls",O.InvalidOption)),s;this.options=t;const i=e.src;if(t.wsFactory){const{socket:n,encrypted:o}=await t.wsFactory(e.src,t);this.socket=n,this.encrypted=o}else this.encrypted=i.indexOf("wss://")===0,this.socket=new WebSocket(i);return this.socket.binaryType="arraybuffer",this.socket.onopen=()=>{this.isDiscarded()},this.socket.onmessage=n=>{if(this.isDiscarded())return;if(this.yields.push(new Uint8Array(n.data)),this.peeked){this.signal.resolve();return}const o=it.concat(...this.yields),a=sn(o);if(a!==""){const d=jn.exec(a);if(!d){t.debug&&console.error("!!!",Mt(o)),s.reject(new Error("unexpected response from server"));return}try{const p=JSON.parse(d[1]);Cn(p,this.options),this.peeked=!0,this.connected=!0,this.signal.resolve(),s.resolve()}catch(p){s.reject(p);return}}},this.socket.onclose=n=>{if(this.isDiscarded())return;this.socketClosed=!0;let o;this.done||(n.wasClean||(o=new Error(n.reason)),this._closed(o))},this.socket.onerror=n=>{if(this.isDiscarded())return;const o=n,a=new N(o.message,O.Unknown,new Error(o.error));s.reject(a)},s}disconnect(){this._closed(void 0,!0)}async _closed(e,t=!0){if(!this.isDiscarded()&&this.connected&&!this.done){if(this.closeError=e,!e)for(;!this.socketClosed&&this.socket.bufferedAmount>0;)await Ze(100);this.done=!0;try{this.socket.close(e?1002:1e3,e?e.message:void 0)}catch{}t&&this.closedNotification.resolve(e)}}get isClosed(){return this.done}[Symbol.asyncIterator](){return this.iterate()}async*iterate(){for(;;){if(this.isDiscarded())return;this.yields.length===0&&await this.signal;const e=this.yields;this.yields=[];for(let t=0;t<e.length;t++)this.options.debug&&console.info(`> ${Mt(e[t])}`),yield e[t];if(this.done)break;this.yields.length===0&&(e.length=0,this.yields=e,this.signal=z())}}isEncrypted(){return this.connected&&this.encrypted}send(e){if(!this.isDiscarded())try{this.socket.send(e.buffer),this.options.debug&&console.info(`< ${Mt(e)}`);return}catch(t){this.options.debug&&console.error(`!!! ${Mt(e)}: ${t}`)}}close(e){return this._closed(e,!1)}closed(){return this.closedNotification}isDiscarded(){return this.done?(this.discard(),!0):!1}discard(){var e;this.done=!0;try{(e=this.socket)==null||e.close()}catch{}}}function wo(r,e){/^(.*:\/\/)(.*)/.test(r)||(typeof e=="boolean"?r=`${e===!0?"https":"http"}://${r}`:r=`https://${r}`);let s=new URL(r);const i=s.protocol.toLowerCase();i==="ws:"&&(e=!1),i==="wss:"&&(e=!0),i!=="https:"&&i!=="http"&&(r=r.replace(/^(.*:\/\/)(.*)/gm,"$2"),s=new URL(`http://${r}`));let n,o;const a=s.hostname,d=s.pathname,p=s.search||"";switch(i){case"http:":case"ws:":case"nats:":o=s.port||"80",n="ws:";break;case"https:":case"wss:":case"tls:":o=s.port||"443",n="wss:";break;default:o=s.port||e===!0?"443":"80",n=e===!0?"wss:":"ws:";break}return`${n}//${a}:${o}${d}${p}`}function xo(r={}){return Xi({defaultPort:443,urlParseFn:wo,factory:()=>new yo}),$s.connect(r)}const ze=ve();class Ls{constructor(e){h(this,"onStatusChange");h(this,"nc");h(this,"sessionId","");h(this,"userId","");h(this,"globalPrefix","");h(this,"resolveConnected",e=>{});h(this,"isConnected",new Promise(e=>this.resolveConnected=e));this.config=e}get url(){return this.config.natsUrl}async connect(e={}){var a;const{natsWsServerUrls:t,user:s,prefix:i}=e,n=t??[this.config.natsUrl];this.nc=await xo({servers:n});const o=s??await this.config.auth.getLastLoginData();if(!o)throw new Error("Please authenticate first by calling `auth` apis");this.userId=o.userId,this.sessionId=o.sessionId,this.globalPrefix=i??"",this.resolveConnected(!0),(a=this.onStatusChange)==null||a.call(this,!0),console.log("[nats] connected.",this.globalPrefix?`(prefix: ${this.globalPrefix})`:""),(async()=>{var d,p;for await(const g of this.nc.status())switch(g.type!==Fe.PingTimer&&console.log("[nats] connection status:",g.type),g.type){case Se.Reconnect:(d=this.onStatusChange)==null||d.call(this,!0);break;case Se.Disconnect:case Se.Error:case Fe.Reconnecting:(p=this.onStatusChange)==null||p.call(this,!1);break}})()}async disconnect(){var e,t;await((e=this.nc)==null?void 0:e.drain()),await((t=this.nc)==null?void 0:t.close())}async publish(e,t){if(await this.isConnected,!this.nc)throw new Error("[nats] not connected");try{const s=this.buildSubject(e);console.debug("[nats]>>",s),this.nc.publish(s,ze.encode(t))}catch(s){throw console.error("[nats] publish failed:",s),s}}async call(e,t,s){var a;if(await this.isConnected,!this.nc)throw new Error("[nats] not connected");const i=this.buildSubject(e);console.debug("[nats]>>",i);const n=await this.nc.request(i,ze.encode(t),{timeout:(s==null?void 0:s.timeoutInMs)??5e3}),o=ze.decode(n.data);if(o.error)throw new Error(o.error.message);if((a=o.payload)!=null&&a.errorData)throw new Error(o.payload.errorData.message);return o.data??o.payload}async on(e,t){if(await this.isConnected,!this.nc)throw new Error("[nats] not connected");const i=(this.globalPrefix?`${this.globalPrefix}.`:"")+e+".>",n=this.nc.subscribe(i);return(async()=>{for await(const o of n)try{console.debug("[nats]<<",o.subject);const a=o.subject.split(".");if(this.globalPrefix&&a[0]!==this.globalPrefix){console.log("[nats]","Skipped - "+o.subject);continue}a[0]==="dev"&&a.shift();const d=a.slice(0,a.length-2).join("."),p=a[a.length-2],g=a[a.length-1],y=ze.decode(o.data);t(y,{subject:d,userId:p,sessionId:g})}catch(a){console.error("[nats] subscribe error",a)}})(),()=>n.unsubscribe()}async handler(e,t){if(await this.isConnected,!this.nc)throw new Error("[nats] not connected");const i=(this.globalPrefix?`${this.globalPrefix}.`:"")+e+".>",n=this.nc.subscribe(i);return(async()=>{for await(const o of n)try{console.debug("[nats]<<",o.subject);const a=o.subject.split(".");if(this.globalPrefix&&a[0]!==this.globalPrefix){console.log("[nats]","Skipped - "+o.subject);continue}a[0]==="dev"&&a.shift();const d=a.slice(0,a.length-2).join("."),p=a[a.length-2],g=a[a.length-1],y=ze.decode(o.data);try{const x=await t(y,{subject:d,userId:p,sessionId:g});o.reply&&o.respond(ze.encode({data:x}))}catch(x){console.error("[nats] handle",x),o.reply&&o.respond(ze.encode({error:{message:x.message}}))}}catch(a){console.error("[nats] handle",a),o.reply&&o.respond(ze.encode({error:{message:a.message}}))}})(),()=>n.unsubscribe()}buildSubject(e){return[this.globalPrefix,e,this.userId,this.sessionId].filter(t=>t).join(".")}}class zr{async setItem(e,t){if(!t)return this.removeItem(e);localStorage.setItem(e,JSON.stringify(t))}async getItem(e){const t=localStorage.getItem(e);if(!t)return null;try{return JSON.parse(t)}catch{return null}}async removeItem(e){localStorage.removeItem(e)}}function Gr(r){const e=new Blob([r],{type:"audio/mpeg"}),t=URL.createObjectURL(e),s=new Audio;return s.src=t,s.onended=()=>{URL.revokeObjectURL(t)},s}class So{async getAudioBuffer(e,t,s){const i=[],n=crypto.randomUUID();return new Promise((o,a)=>{const d=new WebSocket(`${Wt.WSS_URL}?trustedclienttoken=${Wt.TRUSTED_CLIENT_TOKEN}&ConnectionId=${n}`);d.binaryType="arraybuffer";const p=Eo(e,t,s);d.addEventListener("open",()=>{const g=vo();d.send(g);const y=`X-RequestId:${n}\r
|
|
30
30
|
Content-Type:application/ssml+xml\r
|
|
31
31
|
X-Timestamp:${new Date().toISOString()}Z\r
|
|
32
32
|
Path:ssml\r
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@jokio/sdk",
|
|
3
3
|
"description": "pure js/ts sdk for building decentralised localfirst web apps. Provides tts ai model integrations, realtime p2p communication & crypto encryptions.",
|
|
4
|
-
"version": "0.3.
|
|
4
|
+
"version": "0.3.5",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"main": "dist/jokio.sdk.umd.js",
|
|
7
7
|
"module": "dist/jokio.sdk.es.js",
|