async-call-rpc
Advanced tools
Comparing version 6.2.1 to 6.3.0
@@ -400,4 +400,6 @@ /// <reference types="./base.d.ts" /> | ||
let isThisSideImplementationPending = true; | ||
let resolvedThisSideImplementationValue = undefined$1; | ||
let rejectedThisSideImplementation = undefined$1; | ||
let resolvedThisSideImplementationValue; | ||
let rejectedThisSideImplementation; | ||
let resolvedChannel; | ||
let channelPromise; | ||
// This promise should never fail | ||
@@ -414,2 +416,17 @@ const awaitThisSideImplementation = async ()=>{ | ||
}; | ||
const onChannelResolved = (channel)=>{ | ||
resolvedChannel = channel; | ||
if (isCallbackBasedChannel(channel)) { | ||
channel.setup((data)=>rawMessageReceiver(data).then(rawMessageSender), (data)=>{ | ||
const _ = deserialization(data); | ||
if (isJSONRPCObject(_)) return true; | ||
return Promise_resolve(_).then(isJSONRPCObject); | ||
}); | ||
} | ||
if (isEventBasedChannel(channel)) { | ||
const m = channel; | ||
m.on && m.on((_)=>rawMessageReceiver(_).then(rawMessageSender).then((x)=>x && m.send(x))); | ||
} | ||
return channel; | ||
}; | ||
const { serializer , key: logKey = 'rpc' , strict =true , log =true , parameterStructures ='by-position' , preferLocalImplementation =false , idGenerator =generateRandomID , mapError , logger , channel , thenable } = options; | ||
@@ -547,15 +564,4 @@ if (thisSideImplementation instanceof Promise) awaitThisSideImplementation(); | ||
const deserialization = serializer ? (x)=>serializer.deserialization(x) : Object; | ||
const isEventBasedChannel = (x)=>'send' in x && isFunction(x.send); | ||
const isCallbackBasedChannel = (x)=>'setup' in x && isFunction(x.setup); | ||
if (isCallbackBasedChannel(channel)) { | ||
channel.setup((data)=>rawMessageReceiver(data).then(rawMessageSender), (data)=>{ | ||
const _ = deserialization(data); | ||
if (isJSONRPCObject(_)) return true; | ||
return Promise_resolve(_).then(isJSONRPCObject); | ||
}); | ||
} | ||
if (isEventBasedChannel(channel)) { | ||
const m = channel; | ||
m.on && m.on((_)=>rawMessageReceiver(_).then(rawMessageSender).then((x)=>x && m.send(x))); | ||
} | ||
if (channel instanceof Promise) channelPromise = channel.then(onChannelResolved); | ||
else onChannelResolved(channel); | ||
const makeErrorObject = (e, frameworkStack, data)=>{ | ||
@@ -571,3 +577,3 @@ if (isObject(e) && 'stack' in e) e.stack = frameworkStack.split('\n').reduce((stack, fstack)=>stack.replace(fstack + '\n', ''), '' + e.stack); | ||
const data = await serialization(payload); | ||
return channel.send(data); | ||
return (resolvedChannel || await channelPromise).send(data); | ||
}; | ||
@@ -674,2 +680,4 @@ const rejectsQueue = (queue, error)=>{ | ||
} | ||
const isEventBasedChannel = (x)=>'send' in x && isFunction(x.send); | ||
const isCallbackBasedChannel = (x)=>'setup' in x && isFunction(x.setup); | ||
@@ -676,0 +684,0 @@ exports.AsyncCall = AsyncCall; |
!function(e,r){"object"==typeof exports&&"undefined"!=typeof module?r(exports):"function"==typeof define&&define.amd?define(["exports"],r):r((e="undefined"!=typeof globalThis?globalThis:e||self).AsyncCall={})}(this,function(e){"use strict";function r(e,r,t){return r in e?Object.defineProperty(e,r,{value:t,enumerable:!0,configurable:!0,writable:!0}):e[r]=t,e}class t extends Error{constructor(e,t,n,i){super(t),r(this,"name",void 0),r(this,"code",void 0),r(this,"stack",void 0),this.name=e,this.code=n,this.stack=i}}let n={},i={},o=[{},{},n,i],l=(e,r)=>{let t=o.indexOf(e);return r.message+=`Error ${t}: https://github.com/Jack-Works/async-call-rpc/wiki/Errors#`+t,r},a={__proto__:null,Error,EvalError,RangeError,ReferenceError,SyntaxError,TypeError,URIError},s="DOMException:",c=(e,r,n,i)=>{try{let o=f();if(e.startsWith(s)&&o){let t=e.slice(s.length);return new o(r,t)}if(!(e in a))return new t(e,r,n,i);{let t=new a[e](r);return t.stack=i,t.code=n,t}}catch(t){return Error(`E${n} ${e}: ${r} | ||
${i}`)}},u=e=>(e+"").replace(/^.+\n.+\n/,""),f=()=>{try{return DOMException}catch(e){}},p=e=>"string"==typeof e,y=e=>"boolean"==typeof e,d=e=>"function"==typeof e,h=e=>"object"==typeof e&&null!==e,g="Error",b=void 0,m=e=>Promise.resolve(e),w=Array.isArray,E=()=>"() => replay()",P=(e,r,t,n)=>{let i={jsonrpc:"2.0",id:e,method:r,params:t,remoteStack:n};return A(i,"id"),N(i,"remoteStack"),i},$=(e,r)=>{let t={jsonrpc:"2.0",id:e,result:r};return A(t,"id"),t},k=(e,r,t,n)=>{e===b&&(e=null),Number.isNaN(r=Math.floor(r))&&(r=-1);let i={jsonrpc:"2.0",id:e,error:{code:r,message:t,data:n}};return A(i.error,"data"),i},O=(e,r)=>{let t=v({},e,r),n=t.error;return n.code=-32700,n.message="Parse error",t},j=e=>k(e,-32600,"Invalid Request"),S=e=>k(e,-32601,"Method not found"),v=(e,r,t)=>{let{id:n}=e,{code:i,message:o,data:l}=t(r,e);return k(n,i,o,l)},x=(e="",r=-1)=>t=>{let n=z("",()=>t.message),i=z(g,(e=t.constructor)=>d(e)&&e.name),o=f();o&&t instanceof o&&(i=s+t.name),(p(t)||"number"==typeof t||y(t)||"bigint"==typeof t)&&(i=g,n=t+"");let l=e?{stack:e,type:i}:{type:i};return{code:r,message:n,data:l}},_=e=>{if(!h(e)||!("jsonrpc"in e)||"2.0"!==e.jsonrpc)return!1;if("params"in e){let r=e.params;if(!w(r)&&!h(r))return!1}return!0},z=(e,r)=>{try{let t=r();if(t===b)return e;return t+""}catch(r){return e}},A=(e,r)=>{e[r]===b&&delete e[r]},N=(e,r)=>{e[r]||delete e[r]},C=(e=[b,b],r,t="null")=>({serialization(n){if(t&&h(n)&&"result"in n&&n.result===b){let e={...n};e.result=null,"keep"===t&&(e.undef=!0),n=e}return JSON.stringify(n,e[0],r)},deserialization(r){let t=JSON.parse(r,e[1]);return h(t)&&"result"in t&&null===t.result&&"undef"in t&&!0===t.undef&&(t.result=b,delete t.undef),t}}),M="AsyncCall/",T=Symbol.for(M+"ignored"),R=Symbol.for(M+"notify"),W=Symbol.for(M+"batch"),D=(e,r)=>e[r][R],J=()=>Math.random().toString(36).slice(2),I=e=>void 0===e||e,q=e=>{if("all"===e)return[!0,!0,!0,!0,!0,!0];if(!y(e)){let{beCalled:r,localError:t,remoteError:n,type:i,requestReplay:o,sendLocalStack:l}=e;return[I(r),I(t),I(n),"basic"!==i,o,l]}return e?[!0,!0,!0,!0]:[]},F=e=>{if(!y(e)){let{methodNotFound:r,unknownMessage:t}=e;return[r,t]}return[e,e]};e.AsyncCall=function(e,r){let t=!0,o=b,a=b,s=async()=>{try{o=await e}catch(e){a=e,Z("AsyncCall failed to start",e)}finally{t=!1}},{serializer:f,key:y="rpc",strict:k=!0,log:z=!0,parameterStructures:A="by-position",preferLocalImplementation:N=!1,idGenerator:C=J,mapError:M,logger:D,channel:I,thenable:U}=r;e instanceof Promise?s():(o=e,t=!1);let[B,G]=F(k),[H,K,L,Q,V,X]=q(z),{log:Y,error:Z=Y,debug:ee=Y,groupCollapsed:er=Y,groupEnd:et=Y,warn:en=Y}=D||console,ei=new Map,eo=async e=>{if(t)await s();else if(a)return ef(a,"",e);let r="";try{let{params:t,method:n,id:i,remoteStack:l}=e,a=n.startsWith("rpc.")?Symbol.for(n):n,s=o&&o[a];if(!d(s)){if(B)return S(i);K&&ee("Missing method",a,e);return}let c=w(t)?t:[t];r=u(Error().stack);let f=new Promise(e=>e(s.apply(o,c)));if(H){if(Q){let e=[`${y}.%c${n}%c(${c.map(()=>"%o").join(", ")}%c) | ||
%o %c@${i}`,"color: #d2c057","",...c,"",f,"color: gray; font-style: italic;"];if(V){let r=()=>{debugger;return s.apply(o,c)};r.toString=E,e.push(r)}l?(er(...e),Y(l),et()):Y(...e)}else Y(`${y}.${n}(${[...c].toString()}) @${i}`)}let p=await f;if(p===T)return;return $(i,p)}catch(t){return ef(t,r,e)}},el=async e=>{let r="",t="",n=0,i=g;if("error"in e){let o=e.error;r=o.message,n=o.code;let l=o.data;t=h(l)&&"stack"in l&&p(l.stack)?l.stack:"<remote stack not available>",i=h(l)&&"type"in l&&p(l.type)?l.type:g,L&&(Q?Z(`${i}: ${r}(${n}) %c@${e.id} | ||
%c${t}`,"color: gray",""):Z(`${i}: ${r}(${n}) @${e.id} | ||
${t}`))}let{id:o}=e;if(null===o||o===b||!ei.has(o))return;let[l,a,s=""]=ei.get(o);ei.delete(o),"error"in e?a(c(i,r,n,t+"\n аt AsyncCall (rpc) \n"+s)):l(e.result)},ea=async e=>{let r;let t=b;try{if(r=await eu(e),_(r))return t=await ed(r);if(w(r)&&r.every(_)&&0!==r.length)return Promise.all(r.map(ed));if(!G)return b;{let e=r.id;return e===b&&(e=null),j(e)}}catch(e){return K&&Z(e,r,t),O(e,M||x(e&&e.stack))}},es=async e=>{if(e){if(!w(e))return ec(e);{let r=e.filter(e=>e&&"id"in e);if(0===r.length)return;return ec(r)}}},ec=f?e=>f.serialization(e):Object,eu=f?e=>f.deserialization(e):Object;"setup"in I&&d(I.setup)&&I.setup(e=>ea(e).then(es),e=>{let r=eu(e);return!!_(r)||m(r).then(_)}),"send"in I&&d(I.send)&&I.on&&I.on(e=>ea(e).then(es).then(e=>e&&I.send(e)));let ef=(e,r,t)=>(h(e)&&"stack"in e&&(e.stack=r.split("\n").reduce((e,r)=>e.replace(r+"\n",""),""+e.stack)),K&&Z(e),v(t,e,M||x(X?e.stack:b))),ep=async(e,r=!1)=>{r&&(e=[...e]);let t=await ec(e);return I.send(t)},ey=(e,r)=>{for(let t of e)if("id"in t){let e=ei.get(t.id);e&&e[1](r)}},ed=async e=>{if("method"in e){let r=eo(e);if("id"in e)return r;try{await r}catch(e){}return b}return el(e)},eh=(e,r,i,a=!1)=>new Promise((s,c)=>{let f=b;if(e===W&&(f=r.shift(),e=r.shift()),"symbol"==typeof e){let r=Symbol.keyFor(e)||e.description;if(r){if(r.startsWith("rpc."))e=r;else throw TypeError("Not start with rpc.")}}else if(e.startsWith("rpc."))throw l(n,TypeError());if(N&&!t&&p(e)){let t=o&&o[e];if(d(t))return s(t(...r))}let y=C();i=u(i);let g="by-name"===A&&1===r.length&&h(r[0])?r[0]:r,m=P(a?b:y,e,g,X?i:b);if(f?(f.push(m),f.r||(f.r=[()=>ep(f,!0),e=>ey(f,e)])):ep(m).catch(c),a)return s();ei.set(y,[s,c,i])}),eg=(e,r)=>{let t={[r]:(...e)=>eh(r,e,Error().stack)}[r],n={[r]:(...e)=>eh(r,e,Error().stack,!0)}[r];return t[R]=n[R]=n,p(r)&&Object.defineProperty(eb,r,{value:t,configurable:!0}),t},eb={__proto__:new Proxy({},{get:eg})};return!1===U?eb.then=b:U===b&&Object.defineProperty(eb,"then",{configurable:!0,get(){en(l(i,TypeError("RPC used as Promise: ")))}}),new Proxy(eb,{getPrototypeOf:()=>null,setPrototypeOf:(e,r)=>null===r,getOwnPropertyDescriptor:(e,r)=>(r in eb||eg(e,r),Object.getOwnPropertyDescriptor(eb,r))})},e.JSONSerialization=C,e.NoSerialization={serialization:e=>e,deserialization:e=>e},e.batch=function(e){let r=[],t=new Proxy({},{get(t,i){let o=(...t)=>e[W](r,i,...t);return o[R]=(...t)=>e[W][R](r,i,...t),o[R][R]=o[R],p(i)&&Object.defineProperty(n,i,{value:o,configurable:!0}),o}}),n={__proto__:t};return[new Proxy(n,{getPrototypeOf:()=>null,setPrototypeOf:(e,r)=>null===r}),()=>{r.length&&r.r[0](),r.length=0},(e=Error("Aborted"))=>{r.length&&r.r[1](e),r.length=0}]},e.notify=function(e){return d(e)?e[R]:new Proxy(e,{get:D})}}); | ||
${i}`)}},u=e=>(e+"").replace(/^.+\n.+\n/,""),f=()=>{try{return DOMException}catch(e){}},p=e=>"string"==typeof e,y=e=>"boolean"==typeof e,d=e=>"function"==typeof e,h=e=>"object"==typeof e&&null!==e,g="Error",b=void 0,m=e=>Promise.resolve(e),w=Array.isArray,E=()=>"() => replay()",P=(e,r,t,n)=>{let i={jsonrpc:"2.0",id:e,method:r,params:t,remoteStack:n};return A(i,"id"),N(i,"remoteStack"),i},$=(e,r)=>{let t={jsonrpc:"2.0",id:e,result:r};return A(t,"id"),t},k=(e,r,t,n)=>{e===b&&(e=null),Number.isNaN(r=Math.floor(r))&&(r=-1);let i={jsonrpc:"2.0",id:e,error:{code:r,message:t,data:n}};return A(i.error,"data"),i},O=(e,r)=>{let t=v({},e,r),n=t.error;return n.code=-32700,n.message="Parse error",t},j=e=>k(e,-32600,"Invalid Request"),S=e=>k(e,-32601,"Method not found"),v=(e,r,t)=>{let{id:n}=e,{code:i,message:o,data:l}=t(r,e);return k(n,i,o,l)},x=(e="",r=-1)=>t=>{let n=z("",()=>t.message),i=z(g,(e=t.constructor)=>d(e)&&e.name),o=f();o&&t instanceof o&&(i=s+t.name),(p(t)||"number"==typeof t||y(t)||"bigint"==typeof t)&&(i=g,n=t+"");let l=e?{stack:e,type:i}:{type:i};return{code:r,message:n,data:l}},_=e=>{if(!h(e)||!("jsonrpc"in e)||"2.0"!==e.jsonrpc)return!1;if("params"in e){let r=e.params;if(!w(r)&&!h(r))return!1}return!0},z=(e,r)=>{try{let t=r();if(t===b)return e;return t+""}catch(r){return e}},A=(e,r)=>{e[r]===b&&delete e[r]},N=(e,r)=>{e[r]||delete e[r]},C="AsyncCall/",M=Symbol.for(C+"ignored"),T=Symbol.for(C+"notify"),R=Symbol.for(C+"batch"),W=(e,r)=>e[r][T],D=()=>Math.random().toString(36).slice(2),J=e=>void 0===e||e,I=e=>{if("all"===e)return[!0,!0,!0,!0,!0,!0];if(!y(e)){let{beCalled:r,localError:t,remoteError:n,type:i,requestReplay:o,sendLocalStack:l}=e;return[J(r),J(t),J(n),"basic"!==i,o,l]}return e?[!0,!0,!0,!0]:[]},q=e=>{if(!y(e)){let{methodNotFound:r,unknownMessage:t}=e;return[r,t]}return[e,e]},F=e=>"send"in e&&d(e.send),U=e=>"setup"in e&&d(e.setup);e.AsyncCall=function(e,r){let t,o,a,s,f=!0,y=async()=>{try{t=await e}catch(e){o=e,ei("AsyncCall failed to start",e)}finally{f=!1}},k=e=>(a=e,U(e)&&e.setup(e=>ep(e).then(ey),e=>{let r=eh(e);return!!_(r)||m(r).then(_)}),F(e)&&e.on&&e.on(r=>ep(r).then(ey).then(r=>r&&e.send(r))),e),{serializer:z,key:A="rpc",strict:N=!0,log:C=!0,parameterStructures:W="by-position",preferLocalImplementation:J=!1,idGenerator:B=D,mapError:G,logger:H,channel:K,thenable:L}=r;e instanceof Promise?y():(t=e,f=!1);let[Q,V]=q(N),[X,Y,Z,ee,er,et]=I(C),{log:en,error:ei=en,debug:eo=en,groupCollapsed:el=en,groupEnd:ea=en,warn:es=en}=H||console,ec=new Map,eu=async e=>{if(f)await y();else if(o)return eg(o,"",e);let r="";try{let{params:n,method:i,id:o,remoteStack:l}=e,a=i.startsWith("rpc.")?Symbol.for(i):i,s=t&&t[a];if(!d(s)){if(Q)return S(o);Y&&eo("Missing method",a,e);return}let c=w(n)?n:[n];r=u(Error().stack);let f=new Promise(e=>e(s.apply(t,c)));if(X){if(ee){let e=[`${A}.%c${i}%c(${c.map(()=>"%o").join(", ")}%c) | ||
%o %c@${o}`,"color: #d2c057","",...c,"",f,"color: gray; font-style: italic;"];if(er){let r=()=>{debugger;return s.apply(t,c)};r.toString=E,e.push(r)}l?(el(...e),en(l),ea()):en(...e)}else en(`${A}.${i}(${[...c].toString()}) @${o}`)}let p=await f;if(p===M)return;return $(o,p)}catch(t){return eg(t,r,e)}},ef=async e=>{let r="",t="",n=0,i=g;if("error"in e){let o=e.error;r=o.message,n=o.code;let l=o.data;t=h(l)&&"stack"in l&&p(l.stack)?l.stack:"<remote stack not available>",i=h(l)&&"type"in l&&p(l.type)?l.type:g,Z&&(ee?ei(`${i}: ${r}(${n}) %c@${e.id} | ||
%c${t}`,"color: gray",""):ei(`${i}: ${r}(${n}) @${e.id} | ||
${t}`))}let{id:o}=e;if(null===o||o===b||!ec.has(o))return;let[l,a,s=""]=ec.get(o);ec.delete(o),"error"in e?a(c(i,r,n,t+"\n аt AsyncCall (rpc) \n"+s)):l(e.result)},ep=async e=>{let r;let t=b;try{if(r=await eh(e),_(r))return t=await ew(r);if(w(r)&&r.every(_)&&0!==r.length)return Promise.all(r.map(ew));if(!V)return b;{let e=r.id;return e===b&&(e=null),j(e)}}catch(e){return Y&&ei(e,r,t),O(e,G||x(e&&e.stack))}},ey=async e=>{if(e){if(!w(e))return ed(e);{let r=e.filter(e=>e&&"id"in e);if(0===r.length)return;return ed(r)}}},ed=z?e=>z.serialization(e):Object,eh=z?e=>z.deserialization(e):Object;K instanceof Promise?s=K.then(k):k(K);let eg=(e,r,t)=>(h(e)&&"stack"in e&&(e.stack=r.split("\n").reduce((e,r)=>e.replace(r+"\n",""),""+e.stack)),Y&&ei(e),v(t,e,G||x(et?e.stack:b))),eb=async(e,r=!1)=>{r&&(e=[...e]);let t=await ed(e);return(a||await s).send(t)},em=(e,r)=>{for(let t of e)if("id"in t){let e=ec.get(t.id);e&&e[1](r)}},ew=async e=>{if("method"in e){let r=eu(e);if("id"in e)return r;try{await r}catch(e){}return b}return ef(e)},eE=(e,r,i,o=!1)=>new Promise((a,s)=>{let c=b;if(e===R&&(c=r.shift(),e=r.shift()),"symbol"==typeof e){let r=Symbol.keyFor(e)||e.description;if(r){if(r.startsWith("rpc."))e=r;else throw TypeError("Not start with rpc.")}}else if(e.startsWith("rpc."))throw l(n,TypeError());if(J&&!f&&p(e)){let n=t&&t[e];if(d(n))return a(n(...r))}let y=B();i=u(i);let g="by-name"===W&&1===r.length&&h(r[0])?r[0]:r,m=P(o?b:y,e,g,et?i:b);if(c?(c.push(m),c.r||(c.r=[()=>eb(c,!0),e=>em(c,e)])):eb(m).catch(s),o)return a();ec.set(y,[a,s,i])}),eP=(e,r)=>{let t={[r]:(...e)=>eE(r,e,Error().stack)}[r],n={[r]:(...e)=>eE(r,e,Error().stack,!0)}[r];return t[T]=n[T]=n,p(r)&&Object.defineProperty(e$,r,{value:t,configurable:!0}),t},e$={__proto__:new Proxy({},{get:eP})};return!1===L?e$.then=b:L===b&&Object.defineProperty(e$,"then",{configurable:!0,get(){es(l(i,TypeError("RPC used as Promise: ")))}}),new Proxy(e$,{getPrototypeOf:()=>null,setPrototypeOf:(e,r)=>null===r,getOwnPropertyDescriptor:(e,r)=>(r in e$||eP(e,r),Object.getOwnPropertyDescriptor(e$,r))})},e.JSONSerialization=(e=[b,b],r,t="null")=>({serialization(n){if(t&&h(n)&&"result"in n&&n.result===b){let e={...n};e.result=null,"keep"===t&&(e.undef=!0),n=e}return JSON.stringify(n,e[0],r)},deserialization(r){let t=JSON.parse(r,e[1]);return h(t)&&"result"in t&&null===t.result&&"undef"in t&&!0===t.undef&&(t.result=b,delete t.undef),t}}),e.NoSerialization={serialization:e=>e,deserialization:e=>e},e.batch=function(e){let r=[],t=new Proxy({},{get(t,i){let o=(...t)=>e[R](r,i,...t);return o[T]=(...t)=>e[R][T](r,i,...t),o[T][T]=o[T],p(i)&&Object.defineProperty(n,i,{value:o,configurable:!0}),o}}),n={__proto__:t};return[new Proxy(n,{getPrototypeOf:()=>null,setPrototypeOf:(e,r)=>null===r}),()=>{r.length&&r.r[0](),r.length=0},(e=Error("Aborted"))=>{r.length&&r.r[1](e),r.length=0}]},e.notify=function(e){return d(e)?e[T]:new Proxy(e,{get:W})}}); | ||
//# sourceMappingURL=base.min.js.map |
@@ -401,4 +401,6 @@ /// <reference types="./full.d.ts" /> | ||
let isThisSideImplementationPending = true; | ||
let resolvedThisSideImplementationValue = undefined$1; | ||
let rejectedThisSideImplementation = undefined$1; | ||
let resolvedThisSideImplementationValue; | ||
let rejectedThisSideImplementation; | ||
let resolvedChannel; | ||
let channelPromise; | ||
// This promise should never fail | ||
@@ -415,2 +417,17 @@ const awaitThisSideImplementation = async ()=>{ | ||
}; | ||
const onChannelResolved = (channel)=>{ | ||
resolvedChannel = channel; | ||
if (isCallbackBasedChannel(channel)) { | ||
channel.setup((data)=>rawMessageReceiver(data).then(rawMessageSender), (data)=>{ | ||
const _ = deserialization(data); | ||
if (isJSONRPCObject(_)) return true; | ||
return Promise_resolve(_).then(isJSONRPCObject); | ||
}); | ||
} | ||
if (isEventBasedChannel(channel)) { | ||
const m = channel; | ||
m.on && m.on((_)=>rawMessageReceiver(_).then(rawMessageSender).then((x)=>x && m.send(x))); | ||
} | ||
return channel; | ||
}; | ||
const { serializer , key: logKey = 'rpc' , strict =true , log =true , parameterStructures ='by-position' , preferLocalImplementation =false , idGenerator =generateRandomID , mapError , logger , channel , thenable } = options; | ||
@@ -548,15 +565,4 @@ if (thisSideImplementation instanceof Promise) awaitThisSideImplementation(); | ||
const deserialization = serializer ? (x)=>serializer.deserialization(x) : Object; | ||
const isEventBasedChannel = (x)=>'send' in x && isFunction(x.send); | ||
const isCallbackBasedChannel = (x)=>'setup' in x && isFunction(x.setup); | ||
if (isCallbackBasedChannel(channel)) { | ||
channel.setup((data)=>rawMessageReceiver(data).then(rawMessageSender), (data)=>{ | ||
const _ = deserialization(data); | ||
if (isJSONRPCObject(_)) return true; | ||
return Promise_resolve(_).then(isJSONRPCObject); | ||
}); | ||
} | ||
if (isEventBasedChannel(channel)) { | ||
const m = channel; | ||
m.on && m.on((_)=>rawMessageReceiver(_).then(rawMessageSender).then((x)=>x && m.send(x))); | ||
} | ||
if (channel instanceof Promise) channelPromise = channel.then(onChannelResolved); | ||
else onChannelResolved(channel); | ||
const makeErrorObject = (e, frameworkStack, data)=>{ | ||
@@ -572,3 +578,3 @@ if (isObject(e) && 'stack' in e) e.stack = frameworkStack.split('\n').reduce((stack, fstack)=>stack.replace(fstack + '\n', ''), '' + e.stack); | ||
const data = await serialization(payload); | ||
return channel.send(data); | ||
return (resolvedChannel || await channelPromise).send(data); | ||
}; | ||
@@ -675,2 +681,4 @@ const rejectsQueue = (queue, error)=>{ | ||
} | ||
const isEventBasedChannel = (x)=>'send' in x && isFunction(x.send); | ||
const isCallbackBasedChannel = (x)=>'setup' in x && isFunction(x.setup); | ||
@@ -677,0 +685,0 @@ /** |
!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports):"function"==typeof define&&define.amd?define(["exports"],e):e((t="undefined"!=typeof globalThis?globalThis:t||self).AsyncCall={})}(this,function(t){"use strict";function e(t,e,r){return e in t?Object.defineProperty(t,e,{value:r,enumerable:!0,configurable:!0,writable:!0}):t[e]=r,t}class r extends Error{constructor(t,r,n,i){super(r),e(this,"name",void 0),e(this,"code",void 0),e(this,"stack",void 0),this.name=t,this.code=n,this.stack=i}}let n={},i={},o={},l={},s=[n,i,o,l],a=(t,e)=>{let r=s.indexOf(t);return e.message+=`Error ${r}: https://github.com/Jack-Works/async-call-rpc/wiki/Errors#`+r,e},c={__proto__:null,Error,EvalError,RangeError,ReferenceError,SyntaxError,TypeError,URIError},u="DOMException:",f=(t,e,n,i)=>{try{let o=p();if(t.startsWith(u)&&o){let r=t.slice(u.length);return new o(e,r)}if(!(t in c))return new r(t,e,n,i);{let r=new c[t](e);return r.stack=i,r.code=n,r}}catch(r){return Error(`E${n} ${t}: ${e} | ||
${i}`)}},y=t=>(t+"").replace(/^.+\n.+\n/,""),p=()=>{try{return DOMException}catch(t){}},d=t=>"string"==typeof t,h=t=>"boolean"==typeof t,g=t=>"function"==typeof t,b=t=>"object"==typeof t&&null!==t,w="Error",m=void 0,P=Object.setPrototypeOf,O=t=>Promise.resolve(t),E=Array.isArray,$=()=>"() => replay()",k=(t,e,r,n)=>{let i={jsonrpc:"2.0",id:t,method:e,params:r,remoteStack:n};return N(i,"id"),T(i,"remoteStack"),i},v=(t,e)=>{let r={jsonrpc:"2.0",id:t,result:e};return N(r,"id"),r},j=(t,e,r,n)=>{t===m&&(t=null),Number.isNaN(e=Math.floor(e))&&(e=-1);let i={jsonrpc:"2.0",id:t,error:{code:e,message:r,data:n}};return N(i.error,"data"),i},S=(t,e)=>{let r=A({},t,e),n=r.error;return n.code=-32700,n.message="Parse error",r},x=t=>j(t,-32600,"Invalid Request"),_=t=>j(t,-32601,"Method not found"),A=(t,e,r)=>{let{id:n}=t,{code:i,message:o,data:l}=r(e,t);return j(n,i,o,l)},z=(t="",e=-1)=>r=>{let n=M("",()=>r.message),i=M(w,(t=r.constructor)=>g(t)&&t.name),o=p();o&&r instanceof o&&(i=u+r.name),(d(r)||"number"==typeof r||h(r)||"bigint"==typeof r)&&(i=w,n=r+"");let l=t?{stack:t,type:i}:{type:i};return{code:e,message:n,data:l}},C=t=>{if(!b(t)||!("jsonrpc"in t)||"2.0"!==t.jsonrpc)return!1;if("params"in t){let e=t.params;if(!E(e)&&!b(e))return!1}return!0},M=(t,e)=>{try{let r=e();if(r===m)return t;return r+""}catch(e){return t}},N=(t,e)=>{t[e]===m&&delete t[e]},T=(t,e)=>{t[e]||delete t[e]},D=(t=[m,m],e,r="null")=>({serialization(n){if(r&&b(n)&&"result"in n&&n.result===m){let t={...n};t.result=null,"keep"===r&&(t.undef=!0),n=t}return JSON.stringify(n,t[0],e)},deserialization(e){let r=JSON.parse(e,t[1]);return b(r)&&"result"in r&&null===r.result&&"undef"in r&&!0===r.undef&&(r.result=m,delete r.undef),r}}),R="AsyncCall/",W=Symbol.for(R+"ignored"),J=Symbol.for(R+"notify"),I=Symbol.for(R+"batch"),q=(t,e)=>t[e][J],F=()=>Math.random().toString(36).slice(2),G=t=>void 0===t||t,U=t=>{if("all"===t)return[!0,!0,!0,!0,!0,!0];if(!h(t)){let{beCalled:e,localError:r,remoteError:n,type:i,requestReplay:o,sendLocalStack:l}=t;return[G(e),G(r),G(n),"basic"!==i,o,l]}return t?[!0,!0,!0,!0]:[]},B=t=>{if(!h(t)){let{methodNotFound:e,unknownMessage:r}=t;return[e,r]}return[t,t]};function H(t,e){let r=!0,n=m,i=m,s=async()=>{try{n=await t}catch(t){i=t,Z("AsyncCall failed to start",t)}finally{r=!1}},{serializer:c,key:u="rpc",strict:p=!0,log:h=!0,parameterStructures:P="by-position",preferLocalImplementation:j=!1,idGenerator:M=F,mapError:N,logger:T,channel:D,thenable:R}=e;t instanceof Promise?s():(n=t,r=!1);let[q,G]=B(p),[H,K,L,Q,V,X]=U(h),{log:Y,error:Z=Y,debug:tt=Y,groupCollapsed:te=Y,groupEnd:tr=Y,warn:tn=Y}=T||console,ti=new Map,to=async t=>{if(r)await s();else if(i)return tf(i,"",t);let e="";try{let{params:r,method:i,id:o,remoteStack:l}=t,s=i.startsWith("rpc.")?Symbol.for(i):i,a=n&&n[s];if(!g(a)){if(q)return _(o);K&&tt("Missing method",s,t);return}let c=E(r)?r:[r];e=y(Error().stack);let f=new Promise(t=>t(a.apply(n,c)));if(H){if(Q){let t=[`${u}.%c${i}%c(${c.map(()=>"%o").join(", ")}%c) | ||
%o %c@${o}`,"color: #d2c057","",...c,"",f,"color: gray; font-style: italic;"];if(V){let e=()=>{debugger;return a.apply(n,c)};e.toString=$,t.push(e)}l?(te(...t),Y(l),tr()):Y(...t)}else Y(`${u}.${i}(${[...c].toString()}) @${o}`)}let p=await f;if(p===W)return;return v(o,p)}catch(r){return tf(r,e,t)}},tl=async t=>{let e="",r="",n=0,i=w;if("error"in t){let o=t.error;e=o.message,n=o.code;let l=o.data;r=b(l)&&"stack"in l&&d(l.stack)?l.stack:"<remote stack not available>",i=b(l)&&"type"in l&&d(l.type)?l.type:w,L&&(Q?Z(`${i}: ${e}(${n}) %c@${t.id} | ||
%c${r}`,"color: gray",""):Z(`${i}: ${e}(${n}) @${t.id} | ||
${r}`))}let{id:o}=t;if(null===o||o===m||!ti.has(o))return;let[l,s,a=""]=ti.get(o);ti.delete(o),"error"in t?s(f(i,e,n,r+"\n аt AsyncCall (rpc) \n"+a)):l(t.result)},ts=async t=>{let e;let r=m;try{if(e=await tu(t),C(e))return r=await td(e);if(E(e)&&e.every(C)&&0!==e.length)return Promise.all(e.map(td));if(!G)return m;{let t=e.id;return t===m&&(t=null),x(t)}}catch(t){return K&&Z(t,e,r),S(t,N||z(t&&t.stack))}},ta=async t=>{if(t){if(!E(t))return tc(t);{let e=t.filter(t=>t&&"id"in t);if(0===e.length)return;return tc(e)}}},tc=c?t=>c.serialization(t):Object,tu=c?t=>c.deserialization(t):Object;"setup"in D&&g(D.setup)&&D.setup(t=>ts(t).then(ta),t=>{let e=tu(t);return!!C(e)||O(e).then(C)}),"send"in D&&g(D.send)&&D.on&&D.on(t=>ts(t).then(ta).then(t=>t&&D.send(t)));let tf=(t,e,r)=>(b(t)&&"stack"in t&&(t.stack=e.split("\n").reduce((t,e)=>t.replace(e+"\n",""),""+t.stack)),K&&Z(t),A(r,t,N||z(X?t.stack:m))),ty=async(t,e=!1)=>{e&&(t=[...t]);let r=await tc(t);return D.send(r)},tp=(t,e)=>{for(let r of t)if("id"in r){let t=ti.get(r.id);t&&t[1](e)}},td=async t=>{if("method"in t){let e=to(t);if("id"in t)return e;try{await e}catch(t){}return m}return tl(t)},th=(t,e,i,l=!1)=>new Promise((s,c)=>{let u=m;if(t===I&&(u=e.shift(),t=e.shift()),"symbol"==typeof t){let e=Symbol.keyFor(t)||t.description;if(e){if(e.startsWith("rpc."))t=e;else throw TypeError("Not start with rpc.")}}else if(t.startsWith("rpc."))throw a(o,TypeError());if(j&&!r&&d(t)){let r=n&&n[t];if(g(r))return s(r(...e))}let f=M();i=y(i);let p="by-name"===P&&1===e.length&&b(e[0])?e[0]:e,h=k(l?m:f,t,p,X?i:m);if(u?(u.push(h),u.r||(u.r=[()=>ty(u,!0),t=>tp(u,t)])):ty(h).catch(c),l)return s();ti.set(f,[s,c,i])}),tg=(t,e)=>{let r={[e]:(...t)=>th(e,t,Error().stack)}[e],n={[e]:(...t)=>th(e,t,Error().stack,!0)}[e];return r[J]=n[J]=n,d(e)&&Object.defineProperty(tb,e,{value:r,configurable:!0}),r},tb={__proto__:new Proxy({},{get:tg})};return!1===R?tb.then=m:R===m&&Object.defineProperty(tb,"then",{configurable:!0,get(){tn(a(l,TypeError("RPC used as Promise: ")))}}),new Proxy(tb,{getPrototypeOf:()=>null,setPrototypeOf:(t,e)=>null===e,getOwnPropertyDescriptor:(t,e)=>(e in tb||tg(t,e),Object.getOwnPropertyDescriptor(tb,e))})}function K(t,e,r){return e in t?Object.defineProperty(t,e,{value:r,enumerable:!0,configurable:!0,writable:!0}):t[e]=r,t}let L="rpc.async-iterator.",Q=Symbol.for(L+"start"),V=Symbol.for(L+"next"),X=Symbol.for(L+"return"),Y=Symbol.for(L+"throw");class Z{async return(t){return this.d?to(!0,t):this.c(this.r[X](await this.i,t))}async next(t){return this.d?to(!0):this.c(this.r[V](await this.i,t))}async throw(t){if(!this.d)return this.c(this.r[Y](await this.i,t));throw t}constructor(t,e){K(this,"r",void 0),K(this,"i",void 0),K(this,"d",void 0),K(this,"c",void 0),this.r=t,this.i=e,this.d=!1,this.c=async t=>(await ti(t,()=>this.d=!0),t)}}let tt=async function*(){},te=tt.constructor,tr=te.prototype;P(Z,tr);let tn=Object.getPrototypeOf(tt());P(Z.prototype,tn);let ti=async(t,e)=>{try{let r=await t;r&&r.done&&e()}catch(t){}},to=(t,e)=>({done:t,value:e});t.AsyncCall=H,t.AsyncGeneratorCall=function(t,e){var r;let o=new Map,[l]=B(null===(r=e.strict)||void 0===r||r),{idGenerator:s=F}=e,c=(t,e)=>{let r=o.get(t);if(!r){if(!l)return W;throw a(n,Error(`Iterator ${t}, `))}let i=e(r);return ti(i,()=>o.delete(t)),i},u=H({async [Q](e,r){let n=(await t)[e];if(!g(n)){if(!l)return W;throw TypeError(e+" is not a function")}let i=n(...r),a=s();return o.set(a,i),a},[V]:(t,e)=>c(t,t=>t.next(e)),[X]:(t,e)=>c(t,t=>g(t.return)&&t.return(e)),[Y]:(t,e)=>c(t,t=>g(t.throw)&&t.throw(e))},e),f=(t,e)=>{if(!d(e))throw a(i,TypeError(""));let r={[e]:(...t)=>{let r=u[Q](e,t);return new Z(u,r)}}[e];return Object.defineProperty(y,e,{value:r,configurable:!0}),r},y={__proto__:new Proxy({},{get:f})};return new Proxy(y,{getPrototypeOf:()=>null,setPrototypeOf:(t,e)=>null===e,getOwnPropertyDescriptor:(t,e)=>(e in y||f(t,e),Object.getOwnPropertyDescriptor(y,e))})},t.JSONSerialization=D,t.NoSerialization={serialization:t=>t,deserialization:t=>t},t.batch=function(t){let e=[],r=new Proxy({},{get(r,i){let o=(...r)=>t[I](e,i,...r);return o[J]=(...r)=>t[I][J](e,i,...r),o[J][J]=o[J],d(i)&&Object.defineProperty(n,i,{value:o,configurable:!0}),o}}),n={__proto__:r};return[new Proxy(n,{getPrototypeOf:()=>null,setPrototypeOf:(t,e)=>null===e}),()=>{e.length&&e.r[0](),e.length=0},(t=Error("Aborted"))=>{e.length&&e.r[1](t),e.length=0}]},t.notify=function(t){return g(t)?t[J]:new Proxy(t,{get:q})}}); | ||
${i}`)}},y=t=>(t+"").replace(/^.+\n.+\n/,""),p=()=>{try{return DOMException}catch(t){}},d=t=>"string"==typeof t,h=t=>"boolean"==typeof t,g=t=>"function"==typeof t,b=t=>"object"==typeof t&&null!==t,w="Error",m=void 0,P=Object.setPrototypeOf,O=t=>Promise.resolve(t),E=Array.isArray,$=()=>"() => replay()",k=(t,e,r,n)=>{let i={jsonrpc:"2.0",id:t,method:e,params:r,remoteStack:n};return N(i,"id"),T(i,"remoteStack"),i},v=(t,e)=>{let r={jsonrpc:"2.0",id:t,result:e};return N(r,"id"),r},j=(t,e,r,n)=>{t===m&&(t=null),Number.isNaN(e=Math.floor(e))&&(e=-1);let i={jsonrpc:"2.0",id:t,error:{code:e,message:r,data:n}};return N(i.error,"data"),i},S=(t,e)=>{let r=A({},t,e),n=r.error;return n.code=-32700,n.message="Parse error",r},x=t=>j(t,-32600,"Invalid Request"),_=t=>j(t,-32601,"Method not found"),A=(t,e,r)=>{let{id:n}=t,{code:i,message:o,data:l}=r(e,t);return j(n,i,o,l)},z=(t="",e=-1)=>r=>{let n=M("",()=>r.message),i=M(w,(t=r.constructor)=>g(t)&&t.name),o=p();o&&r instanceof o&&(i=u+r.name),(d(r)||"number"==typeof r||h(r)||"bigint"==typeof r)&&(i=w,n=r+"");let l=t?{stack:t,type:i}:{type:i};return{code:e,message:n,data:l}},C=t=>{if(!b(t)||!("jsonrpc"in t)||"2.0"!==t.jsonrpc)return!1;if("params"in t){let e=t.params;if(!E(e)&&!b(e))return!1}return!0},M=(t,e)=>{try{let r=e();if(r===m)return t;return r+""}catch(e){return t}},N=(t,e)=>{t[e]===m&&delete t[e]},T=(t,e)=>{t[e]||delete t[e]},D="AsyncCall/",R=Symbol.for(D+"ignored"),W=Symbol.for(D+"notify"),J=Symbol.for(D+"batch"),I=(t,e)=>t[e][W],q=()=>Math.random().toString(36).slice(2),F=t=>void 0===t||t,G=t=>{if("all"===t)return[!0,!0,!0,!0,!0,!0];if(!h(t)){let{beCalled:e,localError:r,remoteError:n,type:i,requestReplay:o,sendLocalStack:l}=t;return[F(e),F(r),F(n),"basic"!==i,o,l]}return t?[!0,!0,!0,!0]:[]},U=t=>{if(!h(t)){let{methodNotFound:e,unknownMessage:r}=t;return[e,r]}return[t,t]};function B(t,e){let r,n,i,s,c=!0,u=async()=>{try{r=await t}catch(t){n=t,ti("AsyncCall failed to start",t)}finally{c=!1}},p=t=>(i=t,K(t)&&t.setup(t=>ty(t).then(tp),t=>{let e=th(t);return!!C(e)||O(e).then(C)}),H(t)&&t.on&&t.on(e=>ty(e).then(tp).then(e=>e&&t.send(e))),t),{serializer:h,key:P="rpc",strict:j=!0,log:M=!0,parameterStructures:N="by-position",preferLocalImplementation:T=!1,idGenerator:D=q,mapError:I,logger:F,channel:B,thenable:L}=e;t instanceof Promise?u():(r=t,c=!1);let[Q,V]=U(j),[X,Y,Z,tt,te,tr]=G(M),{log:tn,error:ti=tn,debug:to=tn,groupCollapsed:tl=tn,groupEnd:ts=tn,warn:ta=tn}=F||console,tc=new Map,tu=async t=>{if(c)await u();else if(n)return tg(n,"",t);let e="";try{let{params:n,method:i,id:o,remoteStack:l}=t,s=i.startsWith("rpc.")?Symbol.for(i):i,a=r&&r[s];if(!g(a)){if(Q)return _(o);Y&&to("Missing method",s,t);return}let c=E(n)?n:[n];e=y(Error().stack);let u=new Promise(t=>t(a.apply(r,c)));if(X){if(tt){let t=[`${P}.%c${i}%c(${c.map(()=>"%o").join(", ")}%c) | ||
%o %c@${o}`,"color: #d2c057","",...c,"",u,"color: gray; font-style: italic;"];if(te){let e=()=>{debugger;return a.apply(r,c)};e.toString=$,t.push(e)}l?(tl(...t),tn(l),ts()):tn(...t)}else tn(`${P}.${i}(${[...c].toString()}) @${o}`)}let f=await u;if(f===R)return;return v(o,f)}catch(r){return tg(r,e,t)}},tf=async t=>{let e="",r="",n=0,i=w;if("error"in t){let o=t.error;e=o.message,n=o.code;let l=o.data;r=b(l)&&"stack"in l&&d(l.stack)?l.stack:"<remote stack not available>",i=b(l)&&"type"in l&&d(l.type)?l.type:w,Z&&(tt?ti(`${i}: ${e}(${n}) %c@${t.id} | ||
%c${r}`,"color: gray",""):ti(`${i}: ${e}(${n}) @${t.id} | ||
${r}`))}let{id:o}=t;if(null===o||o===m||!tc.has(o))return;let[l,s,a=""]=tc.get(o);tc.delete(o),"error"in t?s(f(i,e,n,r+"\n аt AsyncCall (rpc) \n"+a)):l(t.result)},ty=async t=>{let e;let r=m;try{if(e=await th(t),C(e))return r=await tm(e);if(E(e)&&e.every(C)&&0!==e.length)return Promise.all(e.map(tm));if(!V)return m;{let t=e.id;return t===m&&(t=null),x(t)}}catch(t){return Y&&ti(t,e,r),S(t,I||z(t&&t.stack))}},tp=async t=>{if(t){if(!E(t))return td(t);{let e=t.filter(t=>t&&"id"in t);if(0===e.length)return;return td(e)}}},td=h?t=>h.serialization(t):Object,th=h?t=>h.deserialization(t):Object;B instanceof Promise?s=B.then(p):p(B);let tg=(t,e,r)=>(b(t)&&"stack"in t&&(t.stack=e.split("\n").reduce((t,e)=>t.replace(e+"\n",""),""+t.stack)),Y&&ti(t),A(r,t,I||z(tr?t.stack:m))),tb=async(t,e=!1)=>{e&&(t=[...t]);let r=await td(t);return(i||await s).send(r)},tw=(t,e)=>{for(let r of t)if("id"in r){let t=tc.get(r.id);t&&t[1](e)}},tm=async t=>{if("method"in t){let e=tu(t);if("id"in t)return e;try{await e}catch(t){}return m}return tf(t)},tP=(t,e,n,i=!1)=>new Promise((l,s)=>{let u=m;if(t===J&&(u=e.shift(),t=e.shift()),"symbol"==typeof t){let e=Symbol.keyFor(t)||t.description;if(e){if(e.startsWith("rpc."))t=e;else throw TypeError("Not start with rpc.")}}else if(t.startsWith("rpc."))throw a(o,TypeError());if(T&&!c&&d(t)){let n=r&&r[t];if(g(n))return l(n(...e))}let f=D();n=y(n);let p="by-name"===N&&1===e.length&&b(e[0])?e[0]:e,h=k(i?m:f,t,p,tr?n:m);if(u?(u.push(h),u.r||(u.r=[()=>tb(u,!0),t=>tw(u,t)])):tb(h).catch(s),i)return l();tc.set(f,[l,s,n])}),tO=(t,e)=>{let r={[e]:(...t)=>tP(e,t,Error().stack)}[e],n={[e]:(...t)=>tP(e,t,Error().stack,!0)}[e];return r[W]=n[W]=n,d(e)&&Object.defineProperty(tE,e,{value:r,configurable:!0}),r},tE={__proto__:new Proxy({},{get:tO})};return!1===L?tE.then=m:L===m&&Object.defineProperty(tE,"then",{configurable:!0,get(){ta(a(l,TypeError("RPC used as Promise: ")))}}),new Proxy(tE,{getPrototypeOf:()=>null,setPrototypeOf:(t,e)=>null===e,getOwnPropertyDescriptor:(t,e)=>(e in tE||tO(t,e),Object.getOwnPropertyDescriptor(tE,e))})}let H=t=>"send"in t&&g(t.send),K=t=>"setup"in t&&g(t.setup);function L(t,e,r){return e in t?Object.defineProperty(t,e,{value:r,enumerable:!0,configurable:!0,writable:!0}):t[e]=r,t}let Q="rpc.async-iterator.",V=Symbol.for(Q+"start"),X=Symbol.for(Q+"next"),Y=Symbol.for(Q+"return"),Z=Symbol.for(Q+"throw");class tt{async return(t){return this.d?tl(!0,t):this.c(this.r[Y](await this.i,t))}async next(t){return this.d?tl(!0):this.c(this.r[X](await this.i,t))}async throw(t){if(!this.d)return this.c(this.r[Z](await this.i,t));throw t}constructor(t,e){L(this,"r",void 0),L(this,"i",void 0),L(this,"d",void 0),L(this,"c",void 0),this.r=t,this.i=e,this.d=!1,this.c=async t=>(await to(t,()=>this.d=!0),t)}}let te=async function*(){},tr=te.constructor,tn=tr.prototype;P(tt,tn);let ti=Object.getPrototypeOf(te());P(tt.prototype,ti);let to=async(t,e)=>{try{let r=await t;r&&r.done&&e()}catch(t){}},tl=(t,e)=>({done:t,value:e});t.AsyncCall=B,t.AsyncGeneratorCall=function(t,e){var r;let o=new Map,[l]=U(null===(r=e.strict)||void 0===r||r),{idGenerator:s=q}=e,c=(t,e)=>{let r=o.get(t);if(!r){if(!l)return R;throw a(n,Error(`Iterator ${t}, `))}let i=e(r);return to(i,()=>o.delete(t)),i},u=B({async [V](e,r){let n=(await t)[e];if(!g(n)){if(!l)return R;throw TypeError(e+" is not a function")}let i=n(...r),a=s();return o.set(a,i),a},[X]:(t,e)=>c(t,t=>t.next(e)),[Y]:(t,e)=>c(t,t=>g(t.return)&&t.return(e)),[Z]:(t,e)=>c(t,t=>g(t.throw)&&t.throw(e))},e),f=(t,e)=>{if(!d(e))throw a(i,TypeError(""));let r={[e]:(...t)=>{let r=u[V](e,t);return new tt(u,r)}}[e];return Object.defineProperty(y,e,{value:r,configurable:!0}),r},y={__proto__:new Proxy({},{get:f})};return new Proxy(y,{getPrototypeOf:()=>null,setPrototypeOf:(t,e)=>null===e,getOwnPropertyDescriptor:(t,e)=>(e in y||f(t,e),Object.getOwnPropertyDescriptor(y,e))})},t.JSONSerialization=(t=[m,m],e,r="null")=>({serialization(n){if(r&&b(n)&&"result"in n&&n.result===m){let t={...n};t.result=null,"keep"===r&&(t.undef=!0),n=t}return JSON.stringify(n,t[0],e)},deserialization(e){let r=JSON.parse(e,t[1]);return b(r)&&"result"in r&&null===r.result&&"undef"in r&&!0===r.undef&&(r.result=m,delete r.undef),r}}),t.NoSerialization={serialization:t=>t,deserialization:t=>t},t.batch=function(t){let e=[],r=new Proxy({},{get(r,i){let o=(...r)=>t[J](e,i,...r);return o[W]=(...r)=>t[J][W](e,i,...r),o[W][W]=o[W],d(i)&&Object.defineProperty(n,i,{value:o,configurable:!0}),o}}),n={__proto__:r};return[new Proxy(n,{getPrototypeOf:()=>null,setPrototypeOf:(t,e)=>null===e}),()=>{e.length&&e.r[0](),e.length=0},(t=Error("Aborted"))=>{e.length&&e.r[1](t),e.length=0}]},t.notify=function(t){return g(t)?t[W]:new Proxy(t,{get:I})}}); | ||
//# sourceMappingURL=full.min.js.map |
{ | ||
"name": "async-call-rpc", | ||
"packageManager": "pnpm@8.3.1", | ||
"version": "6.2.1", | ||
"version": "6.3.0", | ||
"description": "A lightweight JSON RPC server & client", | ||
@@ -68,24 +68,24 @@ "main": "out/base.js", | ||
"@changesets/cli": "^2.26.1", | ||
"@microsoft/api-documenter": "^7.21.7", | ||
"@microsoft/api-extractor": "^7.34.4", | ||
"@microsoft/api-documenter": "^7.22.5", | ||
"@microsoft/api-extractor": "^7.34.9", | ||
"@msgpack/msgpack": "3.0.0-beta2", | ||
"@swc/core": "^1.3.52", | ||
"@types/node": "^18.15.11", | ||
"@swc/core": "^1.3.59", | ||
"@types/node": "^20.2.1", | ||
"@types/ws": "^8.5.4", | ||
"@vitest/coverage-c8": "^0.30.1", | ||
"@vitest/ui": "^0.30.1", | ||
"@vitest/coverage-c8": "^0.31.1", | ||
"@vitest/ui": "^0.31.1", | ||
"async-call-rpc": "link:", | ||
"bson": "^5.2.0", | ||
"bson": "^5.3.0", | ||
"c8": "^7.13.0", | ||
"jest-file-snapshot": "^0.5.0", | ||
"npm-run-all": "^4.1.5", | ||
"prettier": "^2.8.7", | ||
"prettier": "^2.8.8", | ||
"pretty-format": "^29.5.0", | ||
"rimraf": "^5.0.0", | ||
"rollup": "^3.20.6", | ||
"rimraf": "^5.0.1", | ||
"rollup": "^3.22.0", | ||
"rollup-plugin-swc3": "^0.8.1", | ||
"serve": "^14.2.0", | ||
"typescript": "^5.0.4", | ||
"vite": "^4.2.2", | ||
"vitest": "^0.30.1", | ||
"vite": "^4.3.8", | ||
"vitest": "^0.31.1", | ||
"ws": "^8.13.0" | ||
@@ -92,0 +92,0 @@ }, |
@@ -6,3 +6,3 @@ # Async Call | ||
[![Code coverage](https://codecov.io/gh/Jack-Works/async-call-rpc/branch/main/graph/badge.svg)](https://codecov.io/gh/Jack-Works/async-call-rpc) | ||
[![GitHub Workflow Status](https://img.shields.io/github/workflow/status/Jack-Works/async-call-rpc/build)](https://github.com/Jack-Works/async-call-rpc/actions) | ||
[![GitHub Workflow Status](https://img.shields.io/github/actions/workflow/status/Jack-Works/async-call-rpc/build.yml?branch=main)](https://github.com/Jack-Works/async-call-rpc/actions) | ||
[![npm](https://img.shields.io/npm/v/async-call-rpc)](https://npmjs.org/async-call-rpc) | ||
@@ -9,0 +9,0 @@ ![ES2015+](https://img.shields.io/badge/ECMAScript-2015%2B-brightgreen) |
@@ -63,4 +63,7 @@ export * from './types.js' | ||
let isThisSideImplementationPending = true | ||
let resolvedThisSideImplementationValue: unknown = undefined | ||
let rejectedThisSideImplementation: unknown = undefined | ||
let resolvedThisSideImplementationValue: unknown | ||
let rejectedThisSideImplementation: unknown | ||
let resolvedChannel: EventBasedChannel | CallbackBasedChannel | undefined | ||
let channelPromise: Promise<EventBasedChannel | CallbackBasedChannel> | undefined | ||
// This promise should never fail | ||
@@ -77,2 +80,25 @@ const awaitThisSideImplementation = async () => { | ||
} | ||
const onChannelResolved = (channel: EventBasedChannel | CallbackBasedChannel) => { | ||
resolvedChannel = channel | ||
if (isCallbackBasedChannel(channel)) { | ||
channel.setup( | ||
(data) => rawMessageReceiver(data).then(rawMessageSender), | ||
(data) => { | ||
const _ = deserialization(data) | ||
if (isJSONRPCObject(_)) return true | ||
return Promise_resolve(_).then(isJSONRPCObject) | ||
}, | ||
) | ||
} | ||
if (isEventBasedChannel(channel)) { | ||
const m = channel | ||
m.on && | ||
m.on((_) => | ||
rawMessageReceiver(_) | ||
.then(rawMessageSender) | ||
.then((x) => x && m.send!(x)), | ||
) | ||
} | ||
return channel | ||
} | ||
@@ -248,24 +274,6 @@ const { | ||
const deserialization = serializer ? (x: unknown) => serializer.deserialization(x) : Object | ||
const isEventBasedChannel = (x: typeof channel): x is EventBasedChannel => 'send' in x && isFunction(x.send) | ||
const isCallbackBasedChannel = (x: typeof channel): x is CallbackBasedChannel => 'setup' in x && isFunction(x.setup) | ||
if (isCallbackBasedChannel(channel)) { | ||
channel.setup( | ||
(data) => rawMessageReceiver(data).then(rawMessageSender), | ||
(data) => { | ||
const _ = deserialization(data) | ||
if (isJSONRPCObject(_)) return true | ||
return Promise_resolve(_).then(isJSONRPCObject) | ||
}, | ||
) | ||
} | ||
if (isEventBasedChannel(channel)) { | ||
const m = channel as EventBasedChannel | CallbackBasedChannel | ||
m.on && | ||
m.on((_) => | ||
rawMessageReceiver(_) | ||
.then(rawMessageSender) | ||
.then((x) => x && m.send!(x)), | ||
) | ||
} | ||
if (channel instanceof Promise) channelPromise = channel.then(onChannelResolved) | ||
else onChannelResolved(channel) | ||
const makeErrorObject = (e: any, frameworkStack: string, data: Request) => { | ||
@@ -283,3 +291,3 @@ if (isObject(e) && 'stack' in e) | ||
const data = await serialization(payload) | ||
return channel.send!(data) | ||
return (resolvedChannel || (await channelPromise))!.send!(data) | ||
} | ||
@@ -386,1 +394,6 @@ const rejectsQueue = (queue: BatchQueue, error: unknown) => { | ||
declare const console: ConsoleInterface | ||
const isEventBasedChannel = (x: EventBasedChannel | CallbackBasedChannel): x is EventBasedChannel => | ||
'send' in x && isFunction(x.send) | ||
const isCallbackBasedChannel = (x: EventBasedChannel | CallbackBasedChannel): x is CallbackBasedChannel => | ||
'setup' in x && isFunction(x.setup) |
@@ -149,3 +149,3 @@ /** | ||
*/ | ||
channel: CallbackBasedChannel | EventBasedChannel | ||
channel: CallbackBasedChannel | EventBasedChannel | Promise<CallbackBasedChannel | EventBasedChannel> | ||
/** | ||
@@ -267,4 +267,4 @@ * Choose log level. | ||
export type _AsyncVersionOf<T> = { | ||
readonly // Explicitly exclude key called "then" because it will cause problem in promise auto-unwrap. | ||
[key in keyof T as key extends 'then' ? never : T[key] extends Function ? key : never]: T[key] extends ( | ||
// Explicitly exclude key called "then" because it will cause problem in promise auto-unwrap. | ||
readonly [key in keyof T as key extends 'then' ? never : T[key] extends Function ? key : never]: T[key] extends ( | ||
...args: any | ||
@@ -271,0 +271,0 @@ ) => Promise<any> |
@@ -18,3 +18,3 @@ class CustomError extends Error { | ||
// https://github.com/Jack-Works/async-call-rpc/wiki/Error-messages | ||
export const makeHostedMessage = (id: typeof Messages[number], error: Error) => { | ||
export const makeHostedMessage = (id: (typeof Messages)[number], error: Error) => { | ||
const n = Messages.indexOf(id) | ||
@@ -21,0 +21,0 @@ error.message += `Error ${n}: https://github.com/Jack-Works/async-call-rpc/wiki/Errors#` + n |
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
Major refactor
Supply chain riskPackage has recently undergone a major refactor. It may be unstable or indicate significant internal changes. Use caution when updating to versions that include significant changes.
Found 1 instance in 1 package
0
751704
74
4837