livecodes
Version:
A Code Playground That Just Works!
5 lines (4 loc) • 18.1 kB
JavaScript
;(()=>{var oe=Object.create;var G=Object.defineProperty;var se=Object.getOwnPropertyDescriptor;var ae=Object.getOwnPropertyNames;var le=Object.getPrototypeOf,ce=Object.prototype.hasOwnProperty;var de=(l,p)=>()=>(p||l((p={exports:{}}).exports,p),p.exports);var fe=(l,p,t,r)=>{if(p&&typeof p=="object"||typeof p=="function")for(let g of ae(p))!ce.call(l,g)&&g!==t&&G(l,g,{get:()=>p[g],enumerable:!(r=se(p,g))||r.enumerable});return l};var ue=(l,p,t)=>(t=l!=null?oe(le(l)):{},fe(p||!l||!l.__esModule?G(t,"default",{value:l,enumerable:!0}):t,l));var Y=de((Ce,K)=>{var pe=function(){var l=String.fromCharCode,p="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+-$",r={};function g(i,o){if(!r[i]){r[i]={};for(var e=0;e<i.length;e++)r[i][i.charAt(e)]=e}return r[i][o]}var f={compressToBase64:function(i){if(i==null)return"";var o=f._compress(i,6,function(e){return p.charAt(e)});switch(o.length%4){default:case 0:return o;case 1:return o+"===";case 2:return o+"==";case 3:return o+"="}},decompressFromBase64:function(i){return i==null?"":i==""?null:f._decompress(i.length,32,function(o){return g(p,i.charAt(o))})},compressToUTF16:function(i){return i==null?"":f._compress(i,15,function(o){return l(o+32)})+" "},decompressFromUTF16:function(i){return i==null?"":i==""?null:f._decompress(i.length,16384,function(o){return i.charCodeAt(o)-32})},compressToUint8Array:function(i){for(var o=f.compress(i),e=new Uint8Array(o.length*2),n=0,u=o.length;n<u;n++){var m=o.charCodeAt(n);e[n*2]=m>>>8,e[n*2+1]=m%256}return e},decompressFromUint8Array:function(i){if(i==null)return f.decompress(i);for(var o=new Array(i.length/2),e=0,n=o.length;e<n;e++)o[e]=i[e*2]*256+i[e*2+1];var u=[];return o.forEach(function(m){u.push(l(m))}),f.decompress(u.join(""))},compressToEncodedURIComponent:function(i){return i==null?"":f._compress(i,6,function(o){return t.charAt(o)})},decompressFromEncodedURIComponent:function(i){return i==null?"":i==""?null:(i=i.replace(/ /g,"+"),f._decompress(i.length,32,function(o){return g(t,i.charAt(o))}))},compress:function(i){return f._compress(i,16,function(o){return l(o)})},_compress:function(i,o,e){if(i==null)return"";var n,u,m={},b={},E="",O="",_="",A=2,x=3,h=2,w=[],s=0,a=0,P;for(P=0;P<i.length;P+=1)if(E=i.charAt(P),Object.prototype.hasOwnProperty.call(m,E)||(m[E]=x++,b[E]=!0),O=_+E,Object.prototype.hasOwnProperty.call(m,O))_=O;else{if(Object.prototype.hasOwnProperty.call(b,_)){if(_.charCodeAt(0)<256){for(n=0;n<h;n++)s=s<<1,a==o-1?(a=0,w.push(e(s)),s=0):a++;for(u=_.charCodeAt(0),n=0;n<8;n++)s=s<<1|u&1,a==o-1?(a=0,w.push(e(s)),s=0):a++,u=u>>1}else{for(u=1,n=0;n<h;n++)s=s<<1|u,a==o-1?(a=0,w.push(e(s)),s=0):a++,u=0;for(u=_.charCodeAt(0),n=0;n<16;n++)s=s<<1|u&1,a==o-1?(a=0,w.push(e(s)),s=0):a++,u=u>>1}A--,A==0&&(A=Math.pow(2,h),h++),delete b[_]}else for(u=m[_],n=0;n<h;n++)s=s<<1|u&1,a==o-1?(a=0,w.push(e(s)),s=0):a++,u=u>>1;A--,A==0&&(A=Math.pow(2,h),h++),m[O]=x++,_=String(E)}if(_!==""){if(Object.prototype.hasOwnProperty.call(b,_)){if(_.charCodeAt(0)<256){for(n=0;n<h;n++)s=s<<1,a==o-1?(a=0,w.push(e(s)),s=0):a++;for(u=_.charCodeAt(0),n=0;n<8;n++)s=s<<1|u&1,a==o-1?(a=0,w.push(e(s)),s=0):a++,u=u>>1}else{for(u=1,n=0;n<h;n++)s=s<<1|u,a==o-1?(a=0,w.push(e(s)),s=0):a++,u=0;for(u=_.charCodeAt(0),n=0;n<16;n++)s=s<<1|u&1,a==o-1?(a=0,w.push(e(s)),s=0):a++,u=u>>1}A--,A==0&&(A=Math.pow(2,h),h++),delete b[_]}else for(u=m[_],n=0;n<h;n++)s=s<<1|u&1,a==o-1?(a=0,w.push(e(s)),s=0):a++,u=u>>1;A--,A==0&&(A=Math.pow(2,h),h++)}for(u=2,n=0;n<h;n++)s=s<<1|u&1,a==o-1?(a=0,w.push(e(s)),s=0):a++,u=u>>1;for(;;)if(s=s<<1,a==o-1){w.push(e(s));break}else a++;return w.join("")},decompress:function(i){return i==null?"":i==""?null:f._decompress(i.length,32768,function(o){return i.charCodeAt(o)})},_decompress:function(i,o,e){var n=[],u,m=4,b=4,E=3,O="",_=[],A,x,h,w,s,a,P,d={val:e(0),position:o,index:1};for(A=0;A<3;A+=1)n[A]=A;for(h=0,s=Math.pow(2,2),a=1;a!=s;)w=d.val&d.position,d.position>>=1,d.position==0&&(d.position=o,d.val=e(d.index++)),h|=(w>0?1:0)*a,a<<=1;switch(u=h){case 0:for(h=0,s=Math.pow(2,8),a=1;a!=s;)w=d.val&d.position,d.position>>=1,d.position==0&&(d.position=o,d.val=e(d.index++)),h|=(w>0?1:0)*a,a<<=1;P=l(h);break;case 1:for(h=0,s=Math.pow(2,16),a=1;a!=s;)w=d.val&d.position,d.position>>=1,d.position==0&&(d.position=o,d.val=e(d.index++)),h|=(w>0?1:0)*a,a<<=1;P=l(h);break;case 2:return""}for(n[3]=P,x=P,_.push(P);;){if(d.index>i)return"";for(h=0,s=Math.pow(2,E),a=1;a!=s;)w=d.val&d.position,d.position>>=1,d.position==0&&(d.position=o,d.val=e(d.index++)),h|=(w>0?1:0)*a,a<<=1;switch(P=h){case 0:for(h=0,s=Math.pow(2,8),a=1;a!=s;)w=d.val&d.position,d.position>>=1,d.position==0&&(d.position=o,d.val=e(d.index++)),h|=(w>0?1:0)*a,a<<=1;n[b++]=l(h),P=b-1,m--;break;case 1:for(h=0,s=Math.pow(2,16),a=1;a!=s;)w=d.val&d.position,d.position>>=1,d.position==0&&(d.position=o,d.val=e(d.index++)),h|=(w>0?1:0)*a,a<<=1;n[b++]=l(h),P=b-1,m--;break;case 2:return _.join("")}if(m==0&&(m=Math.pow(2,E),E++),n[P])O=n[P];else if(P===b)O=x+x.charAt(0);else return null;_.push(O),n[b++]=x+O.charAt(0),m--,x=O,m==0&&(m=Math.pow(2,E),E++)}}};return f}();typeof K!="undefined"&&K!=null&&(K.exports=pe)});var z=ue(Y());var ge={chrome:["accelerometer","bluetooth","camera","clipboard-read","clipboard-write","display-capture","encrypted-media","geolocation","gyroscope","language-detector","language-model","local-network-access","microphone","midi","proofreader","rewriter","serial","summarizer","translator","web-share","writer","window-placement","xr-spatial-tracking"],firefox:["camera","display-capture","geolocation","microphone","web-share"],default:["accelerometer","ambient-light-sensor","camera","display-capture","encrypted-media","geolocation","gyroscope","microphone","midi","payment","serial","vr","web-share","xr-spatial-tracking"]},he=()=>{if(typeof navigator=="undefined")return"default";let l=navigator.userAgent;return/Firefox\//i.test(l)?"firefox":/Chrome\//i.test(l)?"chrome":"default"},X=()=>ge[he()].filter(l=>{var t,r,g;let p=(g=(r=(t=globalThis.document)==null?void 0:t.featurePolicy)==null?void 0:r.features)==null?void 0:g.call(r);return p?p.includes(l):!0}).join("; "),me={template:"markup",style:"style",script:"script"},ye={markup:"html",style:"css",script:"javascript"},ve=l=>{let t=l.replace(/^\n/,"").split(`
`);t.length>1&&t[t.length-1].trim()===""&&t.pop();let r=t.filter(f=>f.trim().length>0).map(f=>{let i=f.match(/^(\s*)/);return i?i[1].length:0}),g=r.length>0?Math.min(...r):0;return g===0?t.join(`
`):t.map(f=>f.slice(g)).join(`
`)},V=l=>{var t;let p;if(l instanceof HTMLTemplateElement){let r=l.ownerDocument.createElement("div");r.appendChild(l.content.cloneNode(!0)),p=r.innerHTML}else p=(t=l.textContent)!=null?t:"";return ve(p)},be=l=>{let p=l.split(".");if(!(p.length<2))return p[p.length-1]},W=l=>{let p=Array.from(l.children).find(f=>f instanceof HTMLTemplateElement&&!f.hasAttribute("lang")&&!f.hasAttribute("filename"));if(!p)return;let t=p.content,r=Array.from(t.children).filter(f=>f.tagName==="TEMPLATE"||f.tagName==="STYLE"||f.tagName==="SCRIPT");return r.length===0?void 0:r.some(f=>f.hasAttribute("filename"))?Ee(r):we(r)},we=l=>{let p={},t=new Set;for(let r of l){let g=r.tagName.toLowerCase(),f=me[g];if(!f||t.has(f))continue;t.add(f);let i=r.getAttribute("lang")||ye[f],o=V(r);p[f]={language:i,content:o},r.hasAttribute("active")&&(p.activeEditor=f)}return Object.keys(p).length>0?p:void 0},Ee=l=>{let p=[],t;for(let g of l){let f=g.getAttribute("filename");if(!f)continue;let i=V(g),e=g.getAttribute("lang")||be(f),n={filename:f,content:i};e&&(n.language=e),p.push(n),g.hasAttribute("active")&&(t=f)}if(p.length===0)return;let r={files:p};return t&&(r.activeEditor=t),r};async function ee(l,p={}){typeof l=="object"&&!(l instanceof HTMLElement)&&(l.headless||l.view==="headless")&&(p=l,l=null);let t=6e4,{config:r={},headless:g,loading:f="lazy",view:i}=p,o=g||i==="headless",e=null,n=null,u=c=>{c.style.position="absolute",c.style.top="0",c.style.visibility="hidden",c.style.opacity="0"};if(typeof l=="string")e=document.querySelector(l);else if(l instanceof HTMLElement)e=l;else if(!(o&&typeof l=="object"))throw new Error("A valid container element is required.");if(!e)if(o)e=document.createElement("div"),u(e),document.body.appendChild(e);else throw new Error(`Cannot find element: "${l}"`);let m=new URL(_e(p)),b=m.origin;m.searchParams.set("embed","true"),m.searchParams.set("loading",o?"eager":f),m.searchParams.set("sdkVersion","0.14.1"),typeof r=="object"&&Object.keys(r).length>0&&m.searchParams.set("config","sdk");let E=p.params;typeof E=="object"&&Object.keys(E).length>0&&JSON.stringify(E).length<1800&&Object.keys(E).forEach(c=>{m.searchParams.set(c,encodeURIComponent(String(E[c])))});let O=!1,_="Cannot call API methods after calling `destroy()`.",A=[],x=(c,y="message")=>{addEventListener(y,c),A.push(c)},h=(c,y="message")=>{removeEventListener(y,c);let C=A.indexOf(c);C>-1&&A.splice(C,1)},s=await new Promise(c=>{var T,U,L,R,I,H,q,$,Q;if(!e)return;let y=e.dataset.height||e.style.height;if(y&&!o){let D=isNaN(Number(y))?y:y+"px";e.style.height=D}e.dataset.defaultStyles!=="false"&&!o&&((T=e.style).backgroundColor||(T.backgroundColor="#fff"),(U=e.style).border||(U.border="1px solid black"),(L=e.style).borderRadius||(L.borderRadius="8px"),(R=e.style).boxSizing||(R.boxSizing="border-box"),(I=e.style).padding||(I.padding="0"),(H=e.style).width||(H.width="100%"),(q=e.style).height||(q.height=e.style.height||"300px"),e.style.minHeight="200px",e.style.flexGrow="1",($=e.style).overflow||($.overflow="hidden"),(Q=e.style).resize||(Q.resize="vertical"),getComputedStyle(e).getPropertyValue("display")==="inline"&&(e.style.display="block"));let C="livecodes",S=e.querySelector(`iframe.${C}`),v=S||document.createElement("iframe");v.classList.add(C),v.setAttribute("allow",X()),v.setAttribute("allowtransparency","true"),v.setAttribute("allowpaymentrequest","true"),v.setAttribute("allowfullscreen","true"),v.setAttribute("sandbox","allow-same-origin allow-downloads allow-forms allow-modals allow-orientation-lock allow-pointer-lock allow-popups allow-presentation allow-scripts");let k=f==="eager"?"eager":"lazy";v.setAttribute("loading",k),o?u(v):(v.style.height="100%",v.style.minHeight="200px",v.style.width="100%",v.style.margin="0",v.style.border="0",v.style.borderRadius=e.style.borderRadius),x(function D(j){var N;j.source!==v.contentWindow||j.origin!==b||((N=j.data)==null?void 0:N.type)!=="livecodes-init"||(h(D),n=Number(j.data.payload.appVersion.replace(/^v/,"")))}),(!n||n<46)&&x(function D(j){var N,Z;j.source!==v.contentWindow||j.origin!==b||((N=j.data)==null?void 0:N.type)!=="livecodes-get-config"||(h(D),(Z=v.contentWindow)==null||Z.postMessage({type:"livecodes-config",payload:r},b))}),v.onload=()=>{c(v)},v.src=m.href,S||e.appendChild(v)}),a=new Promise(c=>{x(function y(C){var S;C.source!==s.contentWindow||C.origin!==b||((S=C.data)==null?void 0:S.type)!=="livecodes-ready"||(h(y),c(),a.settled=!0)})}),P=()=>O?Promise.reject(_):new Promise(async c=>{var C;a.settled&&c();let y={type:"livecodes-load"};(C=s.contentWindow)==null||C.postMessage(y,b),await a,c()}),d=(c,y)=>new Promise(async(C,S)=>{var U;if(O)return S(_);await P();let v=re(),k=setTimeout(()=>{h(T),S(new Error(`SDK call "${c}" timed out after ${t}ms.`))},t);function T(L){var R,I;if(!(L.source!==s.contentWindow||L.origin!==b||((R=L.data)==null?void 0:R.type)!=="livecodes-api-response"||((I=L.data)==null?void 0:I.id)!==v)&&L.data.method===c){clearTimeout(k),h(T);let H=L.data.payload;H!=null&&H.error?S(H.error):C(H)}}x(T),(U=s.contentWindow)==null||U.postMessage({method:c,id:v,args:y},b)}),M={},te=["load","ready","code","console","tests","destroy"],J=(c,y)=>{var C;if(O)throw new Error(_);return te.includes(c)?(d("watch",[c]),M[c]||(M[c]=[]),(C=M[c])==null||C.push(y),{remove:()=>{var S,v;M[c]=(S=M[c])==null?void 0:S.filter(k=>k!==y),((v=M[c])==null?void 0:v.length)===0&&d("watch",[c,"unsubscribe"])}}):{remove:()=>{}}},ne=c=>({"livecodes-app-loaded":"load","livecodes-ready":"ready","livecodes-change":"code","livecodes-console":"console","livecodes-test-results":"tests","livecodes-destroy":"destroy"})[c];x(async function(y){var v,k,T,U;let C=ne((k=(v=y.data)==null?void 0:v.type)!=null?k:"");if(y.source!==s.contentWindow||y.origin!==b||!C||!M[C])return;let S=(T=y.data)==null?void 0:T.payload;(U=M[C])==null||U.forEach(L=>{L(S)})});let ie=()=>{var c;(c=s==null?void 0:s.remove)==null||c.call(s),Object.values(M).forEach(y=>{y.length=0}),A.forEach(y=>removeEventListener("message",y)),A.length=0,F&&e&&F.unobserve(e),O=!0},F;f==="lazy"&&"IntersectionObserver"in window&&(F=new IntersectionObserver((c,y)=>{c.forEach(async C=>{C.isIntersecting&&(await P(),y.unobserve(e))})},{rootMargin:"150px"}),F.observe(e));let re=()=>(String(Math.random())+Date.now().toFixed()).replace("0.","");return{load:()=>P(),run:()=>d("run"),format:c=>d("format",[c]),getShareUrl:c=>d("getShareUrl",[c]),getConfig:c=>d("getConfig",[c]),setConfig:c=>d("setConfig",[c]),getCode:()=>d("getCode"),show:(c,y)=>d("show",[c,y]),runTests:()=>d("runTests"),onChange:c=>J("code",c),watch:J,exec:(c,...y)=>d("exec",[c,...y]),destroy:()=>O?Promise.reject(_):(ie(),Promise.resolve())}}function _e(l={}){let{appUrl:p="https://livecodes.io",params:t={},config:r={},headless:g,import:f,lite:i,view:o,...e}=l,n;try{n=new URL(p)}catch(b){throw new Error(`${p} is not a valid URL.`)}let u=new URLSearchParams;Object.entries(e).forEach(([b,E])=>{E!==void 0&&n.searchParams.set(b,String(E))});let m=l.view==="headless"||g;if(i&&(console.warn(`Deprecation notice: "lite" option is deprecated. Use "config: { mode: 'lite' }" instead.`),typeof r=="object"&&r.mode==null?r.mode="lite":n.searchParams.set("lite","true")),o&&(console.warn('Deprecation notice: The "view" option has been moved to "config.view". For headless mode use "headless: true".'),typeof r=="object"&&r.view==null&&o!=="headless"?r.view=o:n.searchParams.set("view",o)),typeof r=="string")try{new URL(r),n.searchParams.set("config",encodeURIComponent(r))}catch(b){throw new Error('"config" is not a valid URL or configuration object.')}else r&&typeof r=="object"&&Object.keys(r).length>0&&(r.title&&r.title!=="Untitled Project"&&n.searchParams.set("title",r.title),r.description&&r.description.length>0&&n.searchParams.set("description",r.description),u.set("config","code/"+(0,z.compressToEncodedURIComponent)(JSON.stringify(r))));if(t&&typeof t=="object"&&Object.keys(t).length>0)try{u.set("params",(0,z.compressToEncodedURIComponent)(JSON.stringify(t)))}catch(b){Object.keys(t).forEach(E=>{n.searchParams.set(E,encodeURIComponent(String(t[E])))})}return f&&n.searchParams.set("x",encodeURIComponent(f)),m&&n.searchParams.set("headless","true"),u.toString().length>0&&(n.hash=u.toString()),n.href}var B=class extends HTMLElement{constructor(){super(...arguments);this._configCache="";this._otherOptionsCache="";this._connected=!1;this._updateScheduled=!1;this._generation=0}static get observedAttributes(){return["app-url","config","import","loading","params","template","view","height","headless","lite"]}connectedCallback(){this._connected=!0,this._observeChildren(),this._scheduleUpdate(),this.style.display="block"}disconnectedCallback(){var t,r;this._connected=!1,(t=this._childrenObserver)==null||t.disconnect(),this._childrenObserver=void 0,++this._generation,(r=this._playground)==null||r.destroy(),this._playground=void 0}attributeChangedCallback(t,r,g){r!==g&&this._connected&&this._scheduleUpdate()}get config(){return this._config}set config(t){this._config=t,this._connected&&this._scheduleUpdate()}get params(){return this._params}set params(t){this._params=t,this._connected&&this._scheduleUpdate()}get sdk(){return this._playground}destroy(){var t;++this._generation,(t=this._playground)==null||t.destroy(),this._playground=void 0}_observeChildren(){var r;(r=this._childrenObserver)==null||r.disconnect();let t=Array.from(this.children).find(g=>g instanceof HTMLTemplateElement&&!g.hasAttribute("lang")&&!g.hasAttribute("filename"));t&&(this._childrenObserver=new MutationObserver(()=>{if(!this._connected||!this._playground)return;let g=W(this);g&&this._playground.setConfig(g)}),this._childrenObserver.observe(t.content,{childList:!0,subtree:!0,characterData:!0}))}_scheduleUpdate(){this._updateScheduled||(this._updateScheduled=!0,queueMicrotask(()=>{this._updateScheduled=!1,this._connected&&this._update()}))}_getConfigAttribute(){let t=this.getAttribute("config");if(t!=null)try{return JSON.parse(t)}catch(r){return}}_getParamsAttribute(){let t=this.getAttribute("params");if(t!=null)try{return JSON.parse(t)}catch(r){return}}_getEmbedOptions(){let t={},r=this.getAttribute("app-url");r!=null&&(t.appUrl=r);let g=this.getAttribute("import");g!=null&&(t.import=g);let f=this.getAttribute("loading");f!=null&&(t.loading=f);let i=this.getAttribute("template");i!=null&&(t.template=i);let o=this.getAttribute("view");o!=null&&(t.view=o),this.hasAttribute("headless")&&(t.headless=!0),this.hasAttribute("lite")&&(t.lite=!0);let e=W(this),n=this._getConfigAttribute(),u=this._config;if(e||n||u!==void 0)if(typeof u=="string")t.config=u;else{let E={...n||{},...e||{},...u||{}};t.config=E}let m=this._getParamsAttribute(),b=this._params;return(m||b!==void 0)&&(t.params={...m||{},...b||{}}),t}_update(){var o;let{config:t,...r}=this._getEmbedOptions(),g=JSON.stringify(r),f=JSON.stringify(t||""),i=this.getAttribute("height");if(i!=null){let e=Number(i)?`${i}px`:i;this.dataset.height=e,this.style.height=e}if(!this._playground||this._otherOptionsCache!==g){let e=++this._generation;this._otherOptionsCache=g,this._configCache=f,(o=this._playground)==null||o.destroy(),this._playground=void 0,ee(this,{config:t,...r}).then(n=>{if(this._generation!==e){n.destroy();return}this._playground=n,this.dispatchEvent(new CustomEvent("sdkready",{detail:{sdk:n},bubbles:!0,composed:!0}))})}else{if(this._configCache===f)return;this._configCache=f,t&&this._playground.setConfig(t)}}};customElements.get("live-codes")||customElements.define("live-codes",B);})();