UNPKG

hyperscript.org

Version:

a small scripting language for the web

4 lines (3 loc) 6.33 kB
var p=class t{errors=[];collectErrors(e){if(e||(e=new Set),e.has(this))return[];e.add(this);var a=[...this.errors];for(var r of Object.keys(this))for(var n of[this[r]].flat())n instanceof t&&a.push(...n.collectErrors(e));return a}sourceFor(){return this.programSource.substring(this.startToken.start,this.endToken.end)}lineFor(){return this.programSource.split(` `)[this.startToken.line-1]}static parseEventArgs(e){var a=[];if(e.token(0).value==="("&&(e.token(1).value===")"||e.token(2).value===","||e.token(2).value===")")){e.matchOpToken("(");do a.push(e.requireTokenType("IDENTIFIER"));while(e.matchOpToken(","));e.requireOpToken(")")}return a}};var k=class extends p{isFeature=!0;constructor(){super(),this.constructor.keyword&&(this.type=this.constructor.keyword+"Feature")}install(e,a,r,n){}static parseErrorAndFinally(e){var a,r,n;return e.matchToken("catch")&&(a=e.requireTokenType("IDENTIFIER").value,r=e.requireElement("commandList"),e.ensureTerminated(r)),e.matchToken("finally")&&(n=e.requireElement("commandList"),e.ensureTerminated(n)),{errorHandler:r,errorSymbol:a,finallyHandler:n}}};async function*w(t){var e=new TextDecoder,a="",r=!1,n={data:"",event:"",id:"",retry:null},o=!0;try{for(;;){var{done:i,value:f}=await t.read();if(i)break;var d=e.decode(f,{stream:!0});o&&(d.charCodeAt(0)===65279&&(d=d.slice(1)),o=!1),a+=d;var l=a.split(/\r\n|\r|\n/);a=l.pop()||"";for(var c=0;c<l.length;c++){var u=l[c];if(!u){r&&(yield n,r=!1,n={data:"",event:"",id:"",retry:null});continue}var v=u.indexOf(":");if(v!==0){var h,s;if(v<0?(h=u,s=""):(h=u.slice(0,v),s=u.slice(v+1),s[0]===" "&&(s=s.slice(1))),h==="data")n.data+=(r?` `:"")+s,r=!0;else if(h==="event")n.event=s;else if(h==="id")s.includes("\0")||(n.id=s);else if(h==="retry"){var m=parseInt(s,10);isNaN(m)||(n.retry=m)}}}}}finally{t.releaseLock()}}function N(t,e){if(t===e)return!0;if(!t.includes("*"))return!1;var a=new RegExp("^"+t.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*")+"$");return a.test(e)}var y=class t extends k{static keyword="eventsource";constructor(e,a,r){super(),this.eventSourceName=e,this.nameSpace=a,this.stub=r}install(e,a,r,n){this.runtime=n,n.assignToNamespace(e,this.nameSpace,this.eventSourceName,this.stub)}static parse(e){if(e.matchToken("eventsource")){var a,r=!1,n="GET",o=null,i=e.requireElement("dotOrColonPath"),f=i.evalStatically(),d=f.split("."),l=d.pop();for(e.matchToken("from")&&(a=e.parseURLOrExpression());e.matchToken("with");)e.matchToken("credentials")?r=!0:e.matchToken("method")?n=e.requireElement("stringLike").evalStatically().toUpperCase():e.matchToken("headers")?o=e.requireElement("objectLiteral"):e.raiseExpected("credentials","method","headers");var c=null;if(o){c={};for(var u=0;u<o.keyExpressions.length;u++){var v=o.keyExpressions[u].evalStatically(),h=o.valueExpressions[u].evalStatically();c[v]=h}}for(var s=L(r,n,c),m=new t(l,d,s);e.matchToken("on");){var I=e.requireElement("stringLike").evalStatically(),T="";e.matchToken("as")&&(T=e.requireElement("stringLike").evalStatically());var g=e.requireElement("commandList");e.ensureTerminated(g),e.requireToken("end"),s.listeners.push({type:I,handler:O(T,g,s,m)})}return e.requireToken("end"),a!=null&&s.open(a.evalStatically()),m}}};function L(t,e,a){var r={listeners:[],retryCount:0,closed:!1,abortController:null,reader:null,lastEventId:null,reconnectTimeout:null,url:null,withCredentials:t,method:e,headers:a,open:function(n){if(n==null)if(r.url!=null)n=r.url;else throw new Error("no url defined for EventSource.");r.url===n&&r.abortController&&!r.abortController.signal.aborted||(r.abortController&&r.abortController.abort(),r.closed=!1,r.url=n,S(r))},close:function(){r.closed=!0,r.reconnectTimeout&&(clearTimeout(r.reconnectTimeout),r.reconnectTimeout=null),r.abortController&&(r.abortController.abort(),r.abortController=null),r.retryCount=0,E(r,"close",{type:"close"})},addEventListener:function(n,o,i){r.listeners.push({type:n,handler:o,options:i})}};return r}function S(t){var e=new AbortController;t.abortController=e;var a={method:t.method,signal:e.signal,headers:Object.assign({},t.headers||{})};t.withCredentials&&(a.credentials="include"),t.lastEventId&&(a.headers["Last-Event-ID"]=t.lastEventId),fetch(t.url,a).then(function(r){if(!e.signal.aborted){if(!r.ok)throw new Error("SSE connection failed with status "+r.status);return t.retryCount=0,E(t,"open",{type:"open"}),F(t,r.body.getReader(),e)}}).catch(function(r){e.signal.aborted||(E(t,"error",{type:"error",error:r}),C(t))})}async function F(t,e,a){t.reader=e;var r=500;try{for await(var n of w(e)){if(a.signal.aborted)break;n.id&&(t.lastEventId=n.id),n.retry!=null&&(r=n.retry);var o=n.event||"message",i={type:o,data:n.data,lastEventId:n.id||t.lastEventId||""};E(t,o,i)}}catch(f){a.signal.aborted||E(t,"error",{type:"error",error:f})}t.reader=null,!t.closed&&!a.signal.aborted&&C(t,r)}function C(t,e){if(!t.closed){e=e||500,t.retryCount=Math.min(7,t.retryCount+1);var a=Math.random()*2**t.retryCount*e;t.reconnectTimeout=setTimeout(function(){t.reconnectTimeout=null,t.closed||S(t)},a)}}function E(t,e,a){for(var r=0;r<t.listeners.length;r++){var n=t.listeners[r];if(N(n.type,e))try{n.handler(a)}catch(o){console.error("Error in SSE handler for '"+n.type+"':",o)}}}function O(t,e,a,r){return function(n){var o=b(n.data,t),i=r.runtime.makeContext(a,r,a);i.event=n,i.result=o,e.execute(i)}}function b(t,e){return e.toLowerCase()==="json"?JSON.parse(t):t}function R(t,e,a){var r=a.me,n=t.body.getReader(),o=[],i=null,f=!1;(async function(){try{for await(var l of w(n)){var c=l.event||"message";l.event?e.triggerEvent(r,c,{data:l.data,lastEventId:l.id||""}):(o.push(l.data),i&&(i.resolve({value:l.data,done:!1}),i=null))}}catch(u){e.triggerEvent(r,"stream-error",{error:u})}f=!0,i&&(i.resolve({value:void 0,done:!0}),i=null),e.triggerEvent(r,"streamEnd",{})})();var d={element:r,[Symbol.asyncIterator]:function(){var l=0;return{next:function(){return l<o.length?Promise.resolve({value:o[l++],done:!1}):f?Promise.resolve({value:void 0,done:!0}):new Promise(function(c){i={resolve:c}}).then(function(c){return c.done||l++,c})}}}};return d}var x=function(t,e,a){return R(t,e,a)};x._rawResponse=!0;function q(t){t.addFeature(y.keyword,y.parse.bind(y)),t.config.conversions.Stream=x}typeof self<"u"&&self._hyperscript&&self._hyperscript.use(q);export{y as EventSourceFeature,q as default};