@metapages/metapage 1.6.3 → 1.6.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (67) hide show
  1. package/dist/index.cjs +3 -0
  2. package/dist/index.cjs.map +1 -0
  3. package/dist/index.js +1512 -2
  4. package/dist/index.js.map +1 -1
  5. package/package.json +12 -12
  6. package/dist/index.d.ts +0 -19
  7. package/dist/index.d.ts.map +0 -1
  8. package/dist/metapage/Constants.d.ts +0 -6
  9. package/dist/metapage/Constants.d.ts.map +0 -1
  10. package/dist/metapage/Metaframe.d.ts +0 -79
  11. package/dist/metapage/Metaframe.d.ts.map +0 -1
  12. package/dist/metapage/Metapage.d.ts +0 -99
  13. package/dist/metapage/Metapage.d.ts.map +0 -1
  14. package/dist/metapage/MetapageIFrameRpcClient.d.ts +0 -64
  15. package/dist/metapage/MetapageIFrameRpcClient.d.ts.map +0 -1
  16. package/dist/metapage/MetapageTools.d.ts +0 -21
  17. package/dist/metapage/MetapageTools.d.ts.map +0 -1
  18. package/dist/metapage/Shared.d.ts +0 -16
  19. package/dist/metapage/Shared.d.ts.map +0 -1
  20. package/dist/metapage/conversions-metaframe.d.ts +0 -14
  21. package/dist/metapage/conversions-metaframe.d.ts.map +0 -1
  22. package/dist/metapage/conversions-metapage.d.ts +0 -9
  23. package/dist/metapage/conversions-metapage.d.ts.map +0 -1
  24. package/dist/metapage/core.d.ts +0 -6
  25. package/dist/metapage/core.d.ts.map +0 -1
  26. package/dist/metapage/data.d.ts +0 -25
  27. package/dist/metapage/data.d.ts.map +0 -1
  28. package/dist/metapage/errors/MissingMetaframeJson.d.ts +0 -10
  29. package/dist/metapage/errors/MissingMetaframeJson.d.ts.map +0 -1
  30. package/dist/metapage/errors/RootMetapageError.d.ts +0 -10
  31. package/dist/metapage/errors/RootMetapageError.d.ts.map +0 -1
  32. package/dist/metapage/events.d.ts +0 -24
  33. package/dist/metapage/events.d.ts.map +0 -1
  34. package/dist/metapage/jsonrpc.d.ts +0 -35
  35. package/dist/metapage/jsonrpc.d.ts.map +0 -1
  36. package/dist/metapage/jsonrpc2.d.ts +0 -35
  37. package/dist/metapage/jsonrpc2.d.ts.map +0 -1
  38. package/dist/metapage/util.d.ts +0 -8
  39. package/dist/metapage/util.d.ts.map +0 -1
  40. package/dist/metapage/v0_1_0/all.d.ts +0 -110
  41. package/dist/metapage/v0_1_0/all.d.ts.map +0 -1
  42. package/dist/metapage/v0_2/all.d.ts +0 -68
  43. package/dist/metapage/v0_2/all.d.ts.map +0 -1
  44. package/dist/metapage/v0_3/JsonRpcMethods.d.ts +0 -42
  45. package/dist/metapage/v0_3/JsonRpcMethods.d.ts.map +0 -1
  46. package/dist/metapage/v0_3/all.d.ts +0 -11
  47. package/dist/metapage/v0_3/all.d.ts.map +0 -1
  48. package/dist/metapage/v0_4/index.d.ts +0 -3
  49. package/dist/metapage/v0_4/index.d.ts.map +0 -1
  50. package/dist/metapage/v0_4/metaframe.d.ts +0 -136
  51. package/dist/metapage/v0_4/metaframe.d.ts.map +0 -1
  52. package/dist/metapage/v0_4/metapage.d.ts +0 -34
  53. package/dist/metapage/v0_4/metapage.d.ts.map +0 -1
  54. package/dist/metapage/v1/index.d.ts +0 -3
  55. package/dist/metapage/v1/index.d.ts.map +0 -1
  56. package/dist/metapage/v1/metaframe.d.ts +0 -59
  57. package/dist/metapage/v1/metaframe.d.ts.map +0 -1
  58. package/dist/metapage/v1/metapage.d.ts +0 -26
  59. package/dist/metapage/v1/metapage.d.ts.map +0 -1
  60. package/dist/metapage/v2/index.d.ts +0 -3
  61. package/dist/metapage/v2/index.d.ts.map +0 -1
  62. package/dist/metapage/v2/metaframe.d.ts +0 -24
  63. package/dist/metapage/v2/metaframe.d.ts.map +0 -1
  64. package/dist/metapage/v2/metapage.d.ts +0 -22
  65. package/dist/metapage/v2/metapage.d.ts.map +0 -1
  66. package/dist/metapage/versions.d.ts +0 -7
  67. package/dist/metapage/versions.d.ts.map +0 -1
package/dist/index.cjs ADDED
@@ -0,0 +1,3 @@
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const c=require("compare-versions"),H=require("fetch-retry"),h=require("mutative"),g=require("base64-arraybuffer"),J=require("eventemitter3"),l=require("@metapages/hash-query"),Q=require("fast-json-stable-stringify"),ge=require("picomatch-browser"),j=["0.3","0.4","0.5","0.6","1","2"],B=["0.2","0.3","1","2"],C="2",P="2",_e="metaframe.json",ye="metapage/definition",be="metapage/state",W=B[B.length-1],X=j[j.length-1],Ie=H(fetch),z=async(s,e)=>{if(!s)throw"Metapage definition null";if(s.version||(s=h.create(s,i=>{i.version="0.3"})),!e)throw'Missing "version" argument';if(c.compareVersions(e,P)>0)try{return await(await Ie(`https://module.metapage.io/conversion/metapage/${e}`,{redirect:"follow",retries:3,retryDelay:1e3,method:"POST",body:JSON.stringify(s),headers:{"Content-Type":"application/json"}})).json()}catch(i){throw`Error converting metapage definition to version ${e}: ${i}`}return Me(s,e)},Z=async s=>z(s,P),Me=(s,e)=>{if(!s)throw"Metapage definition null";if(!s.version)throw'Missing "version" key in metapage definition';let t=I(s.version);if(t===e)return s;let i=s;for(;t!==e;)switch(t){case"0.2":{if(c.compareVersions(e,t)>0)i=we(i),t=I(i.version);else throw`Cannot convert from version ${t} to ${e}`;break}case"0.3":{c.compareVersions(e,t)>0?(i=Oe(i),t=I(i.version)):(i=ve(i),t=I(i.version));break}case"1":{c.compareVersions(e,t)>0?(i=Ee(i),t=I(i.version)):(i=Se(i),t=I(i.version));break}case"2":{if(c.compareVersions(e,t)>0)throw`Cannot convert from version ${t} to ${e}, 1 is the latest version`;i=Re(i),t=I(i.version);break}default:throw`Unknow version ${t} to ${e}`}return i},we=s=>h.create(s,e=>{e.version="0.3"}),ve=s=>h.create(s,e=>{e.version="0.2"}),Oe=s=>h.create(s,e=>{const t=e;delete t.plugins,t.version="1"}),Se=s=>h.create(s,e=>(e.version="0.3",e)),Re=s=>h.create(s,e=>{var t,i;return e.version="1",(t=e==null?void 0:e.meta)!=null&&t.tags&&(e.meta.keywords=e.meta.tags,delete e.meta.tags),(i=e==null?void 0:e.meta)!=null&&i.authors&&(e.meta.author=e.meta.authors[0],delete e.meta.authors),e}),Ee=s=>h.create(s,e=>{var t,i;return e.version="2",(t=e==null?void 0:e.meta)!=null&&t.keywords&&(e.meta.tags=e.meta.keywords,delete e.meta.keywords),(i=e==null?void 0:e.meta)!=null&&i.author&&(e.meta.authors=[e.meta.author],delete e.meta.author),e}),I=s=>{if(s==="latest")return P;if(c.compareVersions(s,"0.2")<0)throw`Unknown version: ${s}`;if(c.compareVersions(s,"0.2")<=0&&c.compareVersions(s,"0.3")<0)return"0.2";if(c.compareVersions(s,"0.3")<=0)return"0.3";if(c.compareVersions(s,"1")<=0)return"1";if(s==="2")return"2";throw`Unknown version: ${s}`},Pe=H(fetch),q=async(s,e)=>{if(!s)throw"Metapage definition null";if(!s.version)throw'Missing "version" key in metapage definition';if(!e)throw'Missing "version" argument';if(c.compareVersions(e,C)>0)try{return await(await Pe(`https://module.metapage.io/conversion/metaframe/${e}`,{redirect:"follow",retries:3,retryDelay:1e3,method:"POST",body:JSON.stringify(s),headers:{"Content-Type":"application/json"}})).json()}catch(i){throw`Error converting metapage definition to version ${e}: ${i}`}return De(s,e)},ee=async s=>q(s,C),De=(s,e)=>{if(!s)throw"Metaframe definition null";s.version||(s=h.create(s,n=>{n.version="0.3"}));let t=d(s.version);if(t===e)return s;let i=s;for(;t!==e;)switch(t){case"0.3":{if(c.compareVersions(e,t)>0)i=ke(i),t=d(i.version);else throw`Cannot convert from version ${t} to ${e}`;break}case"0.4":{c.compareVersions(e,t)>0?(i=Le(i),t=d(i.version)):(i=Ae(i),t=d(i.version));break}case"0.5":{c.compareVersions(e,t)>0?(i=Fe(i),t=d(i.version)):(i=Ue(i),t=d(i.version));break}case"0.6":{c.compareVersions(e,t)>0?(i=Ce(i),t=d(i.version)):(i=je(i),t=d(i.version));break}case"1":{c.compareVersions(e,t)>0?(i=$e(i),t=d(i.version)):(i=Te(i),t=d(i.version));break}case"2":{if(c.compareVersions(e,t)>0)throw`Cannot convert from version ${t} to ${e}`;i=Ve(i),t=d(i.version);break}default:throw`Unknow version ${t} to ${e}`}return i},te=async(s,e)=>{if(s)return ee(s)},Ae=s=>h.create(s,e=>{e.version="0.3",delete e.allow}),ke=s=>h.create(s,e=>{e.version="0.4"}),Le=s=>h.create(s,e=>{if(e.version="0.5",!(e!=null&&e.metadata))return;const t=e.metadata.title;delete e.metadata.title,e.metadata.name=t;const i=e.metadata.descriptionUrl;delete e.metadata.descriptionUrl,e.metadata.description=i;const n=e.metadata.keywords;delete e.metadata.keywords,e.metadata.tags=n}),Ue=s=>h.create(s,e=>{if(e.version="0.4",!(e!=null&&e.metadata))return;const t=e.metadata.name;delete e.metadata.name,e.metadata.title=t;const i=e.metadata.description;delete e.metadata.description,e.metadata.descriptionUrl=i;const n=e.metadata.tags;delete e.metadata.tags,e.metadata.keywords=n}),Ce=s=>h.create(s,e=>{var t;e.version="1",(t=e==null?void 0:e.metadata)!=null&&t.operations&&delete e.metadata.operations}),Te=s=>h.create(s,e=>{var t;e.version="0.6",(t=e==null?void 0:e.metadata)!=null&&t.operations&&delete e.metadata.operations}),Ve=s=>h.create(s,e=>{var t,i;return e.version="1",(t=e==null?void 0:e.metadata)!=null&&t.authors&&(e.metadata.author=(i=e==null?void 0:e.metadata)==null?void 0:i.authors[0],delete e.metadata.authors),e}),$e=s=>h.create(s,e=>{var t;return e.version="2",(t=e==null?void 0:e.metadata)!=null&&t.author&&(e.metadata.authors=[e.metadata.author],delete e.metadata.author),e}),Fe=s=>h.create(s,e=>{var t;e.version="0.6",(t=e==null?void 0:e.metadata)!=null&&t.operations&&delete e.metadata.operations}),je=s=>h.create(s,e=>{var t;e.version="0.5",(t=e==null?void 0:e.metadata)!=null&&t.operations&&delete e.metadata.operations}),d=s=>{if(s==="latest")return C;if(c.compareVersions(s,"0.3")<0)throw`Unknown version: ${s}`;if(c.compareVersions(s,"0.3")<=0)return"0.3";if(c.compareVersions(s,"0.4")<=0)return"0.4";if(c.compareVersions(s,"0.5")<=0)return"0.5";if(c.compareVersions(s,"0.6")<=0)return"0.6";if(c.compareVersions(s,"1")<=0)return"1";if(s==="2")return"2";throw`Unknown version: ${s}`},D=async s=>h.create(s,async e=>{for(const t of Object.keys(s)){const i=await se(s[t]);return e[t]=i,e}}),R=async s=>h.create(s,async e=>{for(const t of Object.keys(s)){const i=await G(s[t]);return e[t]=i,e}}),Be=async(s,e,t)=>{if(s=G(s),t=t||{},t.type||(t.type="application/octet-stream"),s instanceof ArrayBuffer)return new File([s],e,t);if(s instanceof File||s instanceof Blob){const n=await s.arrayBuffer();return s instanceof File&&(t.type=s.type),new File([n],e,t)}if(s instanceof Int8Array||s instanceof Uint8Array||s instanceof Uint8ClampedArray||s instanceof Int16Array||s instanceof Uint16Array||s instanceof Int32Array||s instanceof Uint32Array||s instanceof Float32Array||s instanceof Float64Array){const n=s;return new File([n.buffer],e,t)}if(typeof s=="string"){var i=new Blob([s],{type:"text/plain"});return t.type="text/plain",new File([i],e,t)}if(typeof s=="object"){const n=new Blob([JSON.stringify(s)],{type:"application/json"});return t.type="application/json",new File([n],e,t)}var i=new Blob([s],{type:"text/plain"});return t.type="text/plain",new File([i],e,t)},se=async s=>{if(s instanceof Int8Array||s instanceof Uint8Array||s instanceof Uint8ClampedArray||s instanceof Int16Array||s instanceof Uint16Array||s instanceof Int32Array||s instanceof Uint32Array||s instanceof Float32Array||s instanceof Float64Array){const e=s,t={_s:!0,_c:s.constructor.name,value:g.encode(e.buffer),byteLength:e.byteLength,byteOffset:e.byteOffset,size:e.byteLength};return Promise.resolve(t)}else if(s instanceof File){const e=s,t=await e.arrayBuffer();return{_s:!0,_c:File.name,value:g.encode(t),name:e.name,fileType:e.type,lastModified:e.lastModified,size:t.byteLength}}else if(s instanceof Blob){const e=s,t=await e.arrayBuffer();return{_s:!0,_c:Blob.name,value:g.encode(t),fileType:e.type,size:t.byteLength}}else if(s instanceof ArrayBuffer){const e=s,t={_s:!0,_c:ArrayBuffer.name,value:g.encode(e),size:e.byteLength};return Promise.resolve(t)}return Promise.resolve(s)},G=s=>{if(!(s&&typeof s=="object"&&s._s===!0))return s;const e=s,t=e._c;if(t===Blob.name){const r=s;return new Blob([g.decode(e.value)],{type:r.fileType})}else if(t===File.name){const r=s;return new File([g.decode(e.value)],r.name,{type:r.fileType,lastModified:r.lastModified})}else if(t===ArrayBuffer.name)return g.decode(e.value);const i=s,n=g.decode(i.value),a=i._c;try{return new globalThis[a](n)}catch{}return s},Ne=s=>{if(!(s&&typeof s=="object"&&s._s===!0))return;const e=s,t=e._c;if(t===Blob.name){const r=s,o=new Blob([g.decode(e.value)],{type:r.fileType});return new File([o],"file",{type:o.type})}else if(t===File.name){const r=s;return new File([g.decode(e.value)],r.name,{type:r.fileType,lastModified:r.lastModified})}else if(t===ArrayBuffer.name){const r=g.decode(e.value);return new File([r],"file",{type:"application/octet-stream"})}const i=s,n=g.decode(i.value),a=i._c;try{const r=new globalThis[a](n);return new File([r],"file",{type:"application/octet-stream"})}catch{}};var u=(s=>(s.Inputs="inputs",s.Outputs="outputs",s.State="state",s.Definition="definition",s.Error="error",s.Warning="warning",s.UrlHashUpdate="urlhashupdate",s.Message="Message",s))(u||{}),f=(s=>(s.InputsUpdate="InputsUpdate",s.OutputsUpdate="OutputsUpdate",s.SetupIframeClientRequest="SetupIframeClientRequest",s.SetupIframeServerResponseAck="SetupIframeServerResponseAck",s.HashParamsUpdate="HashParamsUpdate",s))(f||{}),M=(s=>(s.InputsUpdate="InputsUpdate",s.MessageAck="MessageAck",s.SetupIframeServerResponse="SetupIframeServerResponse",s))(M||{});const He=-32700,Je=-32600,We=-32601,ze=-32602,qe=-32603;function Ge(s){switch(typeof s){case"string":return!0;case"number":return s%1!=0;case"object":return s===null?(console.warn("Use of null ID in JSONRPC 2.0 is discouraged."),!0):!1;default:return!1}}var A=(s=>(s.mp_debug="mp_debug",s))(A||{});const ie=()=>{try{return window!==window.top}catch{return!1}},x={version:P,metaframes:{}};class ne extends J.EventEmitter{constructor(){super(),this._definition=x,this.getDefinition=this.getDefinition.bind(this)}error(e){throw"Subclass should implement"}getDefinition(){return this._definition}}const E=(s,e)=>e?h.create(s,t=>{Object.keys(e).forEach(i=>{e[i]===void 0?delete t[i]:t[i]=e[i]})}):s,xe=s=>window.location.search?new URLSearchParams(window.location.search).get(s):null,Ke=()=>new URLSearchParams(window.location.search).has(A.mp_debug),U=()=>{const s=new URLSearchParams(window.location.search).get(A.mp_debug);return s==="true"||s==="1"},Ye=(s=8)=>T(s),ae=(s=8)=>T(s),Qe=(s=8)=>T(s),Y="abcdefghijklmnopqrstuvwxyz0123456789",T=(s=8)=>{for(var e="",t=Y.length,i=0;i<s;i++)e+=Y.charAt(Math.floor(Math.random()*t));return e},V=(s,e,t)=>{e=e||"000",e&&e.trim()==""&&(e=void 0);let i;if(typeof s=="string"?i=s:typeof s=="number"?i=s+"":i=JSON.stringify(s,null," "),e&&e.trim()!=""){var n=`color: #${e}`;t&&(n=`${n}; background: #${t}`),i=`%c${i}`,window.console.log(i,n)}else window.console.log(i)},K=s=>oe(re(s)),re=s=>{var e=0;for(let t=0;t<s.length;t++)e=s.charCodeAt(t)+((e<<5)-e);return e},oe=s=>{var e=(s&16777215).toString(16).toUpperCase();return"00000".substring(0,6-e.length)+e},L=()=>document.readyState=="complete"||document.readyState=="interactive",$=async()=>L()?Promise.resolve():new Promise(s=>{if(L()){s();return}let e=!1;window.addEventListener("load",()=>{e||(e=!0,s())}),setTimeout(()=>{!e&&L()&&(e=!0,s())},200)}),Xe=async s=>{const e=Q(s);return await he(e)},Ze=async s=>{const e=Q({version:s.version,metaframes:s.metaframes});return await he(e)};async function he(s){const t=new TextEncoder().encode(s),i=await crypto.subtle.digest("SHA-256",t);return btoa(String.fromCharCode(...new Uint8Array(i)))}var ue=(s=>(s.WaitingForPageLoad="WaitingForPageLoad",s.SentSetupIframeClientRequest="SentSetupIframeClientRequest",s.Ready="Ready",s))(ue||{}),pe=(s=>(s.Connected="connected",s.Error="error",s.Input="input",s.Inputs="inputs",s.Message="message",s))(pe||{});const w=class N extends J.EventEmitter{constructor(e){if(super(),this._inputPipeValues={},this._outputPipeValues={},this._state="WaitingForPageLoad",this._messageSendCount=0,this.debug=U(),this.isInputOutputBlobSerialization=!0,this.id=window.name,this.debug=U(),this._isIframe=ie(),this.addListener=this.addListener.bind(this),this.dispose=this.dispose.bind(this),this.error=this.error.bind(this),this.getInput=this.getInput.bind(this),this.getInputs=this.getInputs.bind(this),this.log=this.log.bind(this),this.logInternal=this.logInternal.bind(this),this.onInput=this.onInput.bind(this),this.onInputs=this.onInputs.bind(this),this.onMessage=this.onMessage.bind(this),this.sendRpc=this.sendRpc.bind(this),this.setInput=this.setInput.bind(this),this.setInputs=this.setInputs.bind(this),this.setInternalInputsAndNotify=this.setInternalInputsAndNotify.bind(this),this.setOutput=this.setOutput.bind(this),this.setOutputs=this.setOutputs.bind(this),this.warn=this.warn.bind(this),this._resolveSetupIframeServerResponse=this._resolveSetupIframeServerResponse.bind(this),this.addListenerReturnDisposer=this.addListenerReturnDisposer.bind(this),this.connected=this.connected.bind(this),this.isConnected=this.isConnected.bind(this),this.disableNotifyOnHashUrlChange=this.disableNotifyOnHashUrlChange.bind(this),this._onHashUrlChange=this._onHashUrlChange.bind(this),this.setParameter=this.setParameter.bind(this),this.setParameterBoolean=this.setParameterBoolean.bind(this),this.setParameterJson=this.setParameterJson.bind(this),this.setParameterBase64=this.setParameterBase64.bind(this),this.setParameterFloat=this.setParameterFloat.bind(this),this.setParameterInt=this.setParameterInt.bind(this),this.getParameter=this.getParameter.bind(this),this.getParameterBoolean=this.getParameterBoolean.bind(this),this.getParameterJson=this.getParameterJson.bind(this),this.getParameterBase64=this.getParameterBase64.bind(this),this.getParameterFloat=this.getParameterFloat.bind(this),this.getParameterInt=this.getParameterInt.bind(this),this.deleteParameter=this.deleteParameter.bind(this),!this._isIframe){this.log("Not an iframe, metaframe code disabled");return}const t=this;$().then(()=>{this.log("pageLoaded"),window.addEventListener("message",this.onMessage),t.sendRpc(f.SetupIframeClientRequest,{version:N.version}),t._state="SentSetupIframeClientRequest"}),e&&e.disableHashChangeEvent||window.addEventListener("hashchange",this._onHashUrlChange)}_resolveSetupIframeServerResponse(e){if(this._state==="WaitingForPageLoad")throw"Got message but page has not finished loading, we should never get in this state";(async()=>this._parentId?this.log("Got JsonRpcMethods.SetupIframeServerResponse but already resolved"):(this._parentVersion=e.version,this.color=K(this.id),this._parentId=e.parentId,this.log(`metapage[${this._parentId}](v${this._parentVersion?this._parentVersion:"unknown"}) registered`),e.state&&e.state.inputs&&(this.isInputOutputBlobSerialization?this._inputPipeValues=await R(e.state.inputs):this._inputPipeValues=e.state.inputs),this._state="Ready",this.sendRpc(f.SetupIframeServerResponseAck,{version:N.version}),this._inputPipeValues&&Object.keys(this._inputPipeValues).length>0&&(this.emit("inputs",this._inputPipeValues),this.listenerCount("input")>0&&Object.keys(this._inputPipeValues).forEach(t=>this.emit("input",t,this._inputPipeValues[t]))),this.emit("connected"),this.sendRpc(f.OutputsUpdate,this._outputPipeValues)))()}isConnected(){return this._state==="Ready"}async connected(){return new Promise((e,t)=>{if(this._state==="Ready"){e();return}let i;i=this.addListenerReturnDisposer("connected",()=>{e(),i()})})}addListenerReturnDisposer(e,t){return super.addListener(e,t),()=>{super.removeListener(e,t)}}log(e,t,i){this.debug&&this.logInternal(e,t||this.color)}warn(e){this.debug&&this.logInternal(e,"000",this.color)}error(e){this.logInternal(e,this.color,"f00")}logInternal(e,t,i){let n;typeof e=="string"?n=e:typeof e=="number"?n=e+"":n=JSON.stringify(e),t=t&&t+"",n=(this.id?`Metaframe[${this.id}] `:"")+`${n}`,V(n,t,i)}dispose(){super.removeAllListeners(),window.removeEventListener("message",this.onMessage),this.disableNotifyOnHashUrlChange(),this._inputPipeValues=void 0,this._outputPipeValues=void 0}addListener(e,t){return super.addListener(e,t),e==="inputs"&&window.setTimeout(()=>{this._inputPipeValues&&t(this._inputPipeValues)},0),this}onInput(e,t){return this.addListenerReturnDisposer("input",(i,n)=>{e===i&&t(n)})}onInputs(e){return this.addListenerReturnDisposer("inputs",e)}setInput(e,t){var i={};i[e]=t,this.setInputs(i)}async setInputs(e){this.isInputOutputBlobSerialization&&(e=await R(e)),this.sendRpc(f.InputsUpdate,e)}async setInternalInputsAndNotify(e){this.isInputOutputBlobSerialization&&(e=await R(e));const t=e;if(this._inputPipeValues=E(this._inputPipeValues,e),this._inputPipeValues!==t){Object.keys(e).forEach(i=>{try{this.emit("input",i,e[i])}catch(n){console.error(`Error emitting input ${i}: ${n}`),this.emit("error",`Error emitting input ${i}: ${n}`)}});try{this.emit("inputs",e)}catch(i){console.error(`Error emitting inputs: ${i}`),this.emit("error",`Error emitting inputs: ${i}`)}}}getInput(e){return console.assert(!!e),this._inputPipeValues[e]}getInputs(){return this._inputPipeValues}setOutput(e,t){console.assert(!!e);var i={};i[e]=t,this.setOutputs(i)}async setOutputs(e){this.isInputOutputBlobSerialization&&(e=await D(e));const t=e;this._outputPipeValues=E(this._outputPipeValues,e),this._outputPipeValues!==t&&this._state==="Ready"&&this.sendRpc(f.OutputsUpdate,e)}disableNotifyOnHashUrlChange(){window.removeEventListener("hashchange",this._onHashUrlChange)}_onHashUrlChange(e){const t={hash:window.location.hash,metaframe:this.id};this.sendRpc(f.HashParamsUpdate,t)}sendRpc(e,t){if(this._isIframe){const i={jsonrpc:"2.0",id:++this._messageSendCount,method:e,params:t,iframeId:this.id,parentId:this._parentId};window.parent&&window.parent.postMessage(i,"*")}else this.log("Cannot send JSON-RPC window message: there is no window.parent which means we are not an iframe")}onMessage(e){if(typeof e.data=="object"){let i=e.data;if(i.jsonrpc==="2.0"){var t=i.method;if(!(t==M.SetupIframeServerResponse||i.parentId==this._parentId&&i.iframeId==this.id)){this.log(`window.message: received message but jsonrpc.parentId=${i.parentId} _parentId=${this._parentId} jsonrpc.iframeId=${i.iframeId} id=${this.id}`);return}switch(t){case M.SetupIframeServerResponse:this._resolveSetupIframeServerResponse(i.params);break;case M.InputsUpdate:if(this._state!=="Ready")throw"Got InputsUpdate but metaframe is not MetaframeLoadingState.Ready";this.setInternalInputsAndNotify(i.params.inputs);break;case M.MessageAck:this.debug&&this.log(`ACK: ${JSON.stringify(i)}`);break;default:this.debug&&this.log(`window.message: unknown JSON-RPC method: ${JSON.stringify(i)}`);break}this.listenerCount("message")>0&&this.emit("message",i)}}}setParameter(e,t){l.setHashParamInWindow(e,t)}getParameter(e){return l.getHashParamFromWindow(e)}setParameterBoolean(e,t){l.setHashParamValueBooleanInWindow(e,t)}getParameterBoolean(e){return l.getHashParamValueBooleanFromWindow(e)}setParameterJson(e,t){l.setHashParamValueJsonInWindow(e,t)}getParameterJson(e){return l.getHashParamValueJsonFromWindow(e)}setParameterBase64(e,t){l.setHashParamValueBase64EncodedInWindow(e,t)}getParameterBase64(e){return l.getHashParamValueBase64DecodedFromWindow(e)}setParameterFloat(e,t){l.setHashParamValueFloatInWindow(e,t)}getParameterFloat(e){return l.getHashParamValueFloatFromWindow(e)}setParameterInt(e,t){l.setHashParamValueIntInWindow(e,t)}getParameterInt(e){return l.getHashParamValueIntFromWindow(e)}deleteParameter(e){l.setHashParamInWindow(e,void 0)}};w.version=X;w.ERROR="error";w.CONNECTED="connected";w.INPUT="input";w.INPUTS="inputs";w.MESSAGE="message";w.deserializeInputs=R;w.serializeInputs=D;let et=w;const ce=H(fetch),tt=async(s,e)=>{const t=new URL(s);t.pathname=t.pathname+(t.pathname.endsWith("/")?"metapage.json":"/metapage.json");const n=await(await ce(t.href,{redirect:"follow",retries:3,retryDelay:1e3})).json();return await z(n,e||"1")},le=async(s,e)=>{const t=new URL(s);t.pathname=t.pathname+(t.pathname.endsWith("/")?"metaframe.json":"/metaframe.json");const n=await(await ce(t.href,{redirect:"follow",retries:3,retryDelay:1e3})).json();return await q(n,e||"1")},st=s=>s?!(s!=null&&s.inputs&&Object.keys(s.inputs).length>0||s!=null&&s.outputs&&Object.keys(s.outputs).length>0||s!=null&&s.allow||s!=null&&s.metadata&&Object.keys(s.metadata).length>0):!0;class fe extends J.EventEmitter{constructor(e,t,i,n,a,r=!1){if(super(),this.inputs={},this.outputs={},this._disposables=[],this._rpcListeners=[],this._loaded=!1,this._onLoaded=[],this._sendInputsAfterRegistration=!1,this._cachedEventInputsUpdate={iframeId:void 0,inputs:void 0},this._cachedEventOutputsUpdate={iframeId:null,inputs:null},!t.startsWith("http")){for(;t.startsWith("/");)t=t.substring(1);t=window.location.protocol+"//"+window.location.hostname+(window.location.port&&window.location.port!=""?":"+window.location.port:"")+"/"+t}if(this.url=t,this._metapage=e,this._debug=r,r){var o=new URL(this.url);o.searchParams.set(A.mp_debug,"true"),this.url=o.href}this.id=i,this._parentId=n,this._color=K(this.id),this._consoleBackgroundColor=a,this._iframe=document.createElement("iframe"),this._iframe.name=this.id;const p=this;this.iframe=new Promise(v=>{$().then(async()=>{var b,m,_,F;if(p._iframe){if((F=(_=(m=(b=this._metapage)==null?void 0:b._definition)==null?void 0:m.metaframes)==null?void 0:_[this.id])!=null&&F.allow)p._iframe.allow=this._metapage._definition.metaframes[this.id].allow;else{const S=await p.getDefinition();if(!p._iframe)return;S&&S.allow&&(p._iframe.allow=S.allow)}p._iframe.src=this.url,v(p._iframe)}})}),this.ack=this.ack.bind(this),this.dispose=this.dispose.bind(this),this.getDefinition=this.getDefinition.bind(this),this.getDefinitionUrl=this.getDefinitionUrl.bind(this),this.log=this.log.bind(this),this.logInternal=this.logInternal.bind(this),this.onInput=this.onInput.bind(this),this.onInputs=this.onInputs.bind(this),this.onOutput=this.onOutput.bind(this),this.onOutputs=this.onOutputs.bind(this),this.register=this.register.bind(this),this.registered=this.registered.bind(this),this.sendInputs=this.sendInputs.bind(this),this.sendOrBufferPostMessage=this.sendOrBufferPostMessage.bind(this),this.sendRpc=this.sendRpc.bind(this),this.sendRpcInternal=this.sendRpcInternal.bind(this),this.setInput=this.setInput.bind(this),this.setInputs=this.setInputs.bind(this),this.setMetapage=this.setMetapage.bind(this),this.setOutput=this.setOutput.bind(this),this.setOutputs=this.setOutputs.bind(this),this.addListenerReturnDisposer=this.addListenerReturnDisposer.bind(this),this.isDisposed=this.isDisposed.bind(this)}addListenerReturnDisposer(e,t){return super.addListener(e,t),()=>{super.removeListener(e,t)}}setMetapage(e){return this._metapage=e,this}getDefinitionUrl(){var e=new URL(this.url);return e.pathname=e.pathname+(e.pathname.endsWith("/")?"metaframe.json":"/metaframe.json"),e.href}async getDefinition(){if(this._definition)return this._definition;try{const t=l.getHashParamValueJsonFromUrl(this.url,"definition");if(t){const i=await te(t);return this._definition=i,this._definition}}catch(t){this.emit(u.Warning,`Failed to convert metaframe definition from hash params. Error: ${t!=null&&t.message?t==null?void 0:t.message:"unknown error"}`);return}var e=this.getDefinitionUrl();try{const t=await le(this.url);if(t)return this._definition=t,this._definition}catch(t){this.emit(u.Warning,`Failed to fetch or convert: ${e}
2
+ Error: ${t!=null&&t.message?t==null?void 0:t.message:t==null?void 0:t.toString()}`)}}setInput(e,t){console.assert(!!e);var i={};i[e]=t,this.setInputs(i)}setInputs(e){this.log({m:"MetapageIFrameRpcClient",inputs:e});const t=e;if(this.inputs=E(this.inputs,e),this.inputs===t)return this;if(this._loaded||(this._sendInputsAfterRegistration=!0),this._iframe.parentNode&&this._loaded&&this.sendInputs(e),this.emit(u.Inputs,this.inputs),this._metapage.listenerCount(u.Inputs)>0){var i={};i[this.id]=e,this._metapage.emit(u.Inputs,i)}return this}setOutput(e,t){console.assert(!!e);var i={};i[e]=t,this.setOutputs(i)}setOutputs(e){const t=e;if(this.outputs=E(this.outputs,e),this.outputs===t)return this;if(this.emit(u.Outputs,e),this._metapage.listenerCount(u.Outputs)>0){var i={};i[this.id]=this.outputs,this._metapage.emit(u.Outputs,i)}}onInputs(e){return this.addListenerReturnDisposer(u.Inputs,e)}onInput(e,t){var i=function(n){n.hasOwnProperty(e)&&t(n[e])};return this.addListenerReturnDisposer(u.Inputs,i)}onOutputs(e){return this.addListenerReturnDisposer(u.Outputs,e)}onOutput(e,t){var i=function(n){n.hasOwnProperty(e)&&t(n[e])};return this.addListenerReturnDisposer(u.Outputs,i)}isDisposed(){return this.inputs===void 0}dispose(){for(super.removeAllListeners();this._disposables&&this._disposables.length>0;){const e=this._disposables.pop();e&&e()}this._rpcListeners=void 0,this.inputs=void 0,this.outputs=void 0,this._iframe&&this._iframe.parentNode&&this._iframe.parentNode.removeChild(this._iframe),this._iframe=void 0,this._bufferMessages=void 0,this._bufferTimeout&&(window.clearInterval(this._bufferTimeout),this._bufferTimeout=void 0),this._metapage=void 0}register(){var e={iframeId:this.id,parentId:this._parentId,state:{inputs:this.inputs},version:W};this.sendRpcInternal(M.SetupIframeServerResponse,e)}registered(e){if(this.log({m:"MetapageIFrameRpcClient.registered",inputs:this.inputs}),!this._loaded){if(!e)throw"Cannot register without a version";for(this.version=e,this._loaded=!0;this._onLoaded&&this._onLoaded.length>0;)this._onLoaded.pop()();this._sendInputsAfterRegistration&&this.sendInputs(this.inputs)}}async sendInputs(e){e&&(e=await D(e),!this.isDisposed()&&this.sendRpc(M.InputsUpdate,{inputs:e,parentId:this._parentId}))}sendRpc(e,t){var i,n;if((i=this==null?void 0:this._iframe)!=null&&i.parentNode&&this._loaded)this.sendRpcInternal(e,t);else{(n=this==null?void 0:this._metapage)==null||n.error("sending rpc later");const a=this;this==null||this._onLoaded.push(()=>{a.sendRpcInternal(e,t)})}}ack(e){if(this._debug){this.log("⚒ ⚒ ⚒ sending ack from client to frame");var t={message:e};this.sendRpc(M.MessageAck,t)}}log(e){this._debug&&this.logInternal(e)}logInternal(e){let t;typeof e=="string"?t=e:typeof e=="string"?t=e+"":t=JSON.stringify(e),V(`Metapage[${this._parentId}] Metaframe[${this.id}] ${t}`,this._color,this._consoleBackgroundColor)}sendRpcInternal(e,t){const i={id:"_",iframeId:this.id,jsonrpc:"2.0",method:e,params:t,parentId:this._parentId};this._iframe?this.sendOrBufferPostMessage(i):this._metapage?this._metapage.error(`Cannot send to child iframe messageJSON=${JSON.stringify(i).substring(0,200)}`):console.error(`Cannot send to child iframe messageJSON=${JSON.stringify(i).substring(0,200)}`)}sendOrBufferPostMessage(e){if(this._iframe&&this._iframe.contentWindow)this._iframe.contentWindow.postMessage(e,this.url);else if(this._bufferMessages)this._bufferMessages.push(e);else{this._bufferMessages=[e];const t=this;this._bufferTimeout=window.setInterval(function(){t._iframe&&t._iframe.contentWindow&&(t._bufferMessages.forEach(i=>t._iframe.contentWindow.postMessage(i,t.url)),window.clearInterval(t._bufferTimeout),t._bufferTimeout=void 0,t._bufferMessages=void 0)},0)}}}const O=h.create({metaframes:{inputs:{},outputs:{}}},s=>s),it=s=>I(s),me=(s,e)=>!!(!e||e==="**"||s===e||ge.isMatch(s,e)),nt="bcbcbc",y=class de extends ne{constructor(e){super(),this._state=O,this._metaframes=h.create({},t=>t),this.debug=U(),this._internalReceivedMessageCounter=0,this._cachedInputLookupMap=h.create({},t=>t),this._inputMap={},this._id=e&&e.id?e.id:ae(),this._consoleBackgroundColor=e&&e.color?e.color:nt,this.addPipe=this.addPipe.bind(this),this.dispose=this.dispose.bind(this),this.addMetaframe=this.addMetaframe.bind(this),this.getInputsFromOutput=this.getInputsFromOutput.bind(this),this.getMetaframe=this.getMetaframe.bind(this),this.getMetaframeIds=this.getMetaframeIds.bind(this),this.getMetaframe=this.getMetaframe.bind(this),this.getMetaframes=this.getMetaframes.bind(this),this.getState=this.getState.bind(this),this.getStateMetaframes=this.getStateMetaframes.bind(this),this.isValidJSONRpcMessage=this.isValidJSONRpcMessage.bind(this),this.log=this.log.bind(this),this.logInternal=this.logInternal.bind(this),this.metaframeIds=this.metaframeIds.bind(this),this.metaframes=this.metaframes.bind(this),this.onMessage=this.onMessage.bind(this),this.removeAll=this.removeAll.bind(this),this.removeMetaframe=this.removeMetaframe.bind(this),this.setDebugFromUrlParams=this.setDebugFromUrlParams.bind(this),this.setDefinition=this.setDefinition.bind(this),this.setInput=this.setInput.bind(this),this.setInputs=this.setInputs.bind(this),this.setInputStateOnlyMetaframeInputValue=this.setInputStateOnlyMetaframeInputValue.bind(this),this.setInputStateOnlyMetaframeInputMap=this.setInputStateOnlyMetaframeInputMap.bind(this),this.setInputStateOnlyMetapageInstanceInputs=this.setInputStateOnlyMetapageInstanceInputs.bind(this),this.setOutputStateOnlyMetaframeInputValue=this.setOutputStateOnlyMetaframeInputValue.bind(this),this.setOutputStateOnlyMetaframeInputMap=this.setOutputStateOnlyMetaframeInputMap.bind(this),this.setOutputStateOnlyMetapageInstanceInputs=this.setOutputStateOnlyMetapageInstanceInputs.bind(this),this.setMetadata=this.setMetadata.bind(this),this.setMetaframeClientInputAndSentClientEvent=this.setMetaframeClientInputAndSentClientEvent.bind(this),this.setState=this.setState.bind(this),this.isDisposed=this.isDisposed.bind(this),this._emitDefinitionEvent=this._emitDefinitionEvent.bind(this),$().then(()=>{this.isDisposed()||(window.addEventListener("message",this.onMessage),this.log("Initialized"))})}static async from(e,t){if(e==null)throw"Metapage definition cannot be null";if(typeof e=="string")try{e=JSON.parse(e)}catch{throw"Cannot parse into JSON:\n${metaPageDef}"}var i=new de;return i.setDefinition(e)}isDisposed(){return this._metaframes===void 0}addListenerReturnDisposer(e,t){return super.addListener(e,t),()=>{super.removeListener(e,t)}}setDebugFromUrlParams(){const e=new URL(window.location.href);return this.debug=["debug","mp_debug"].reduce((t,i)=>t||e.searchParams.get(i)==="true"||e.searchParams.get(i)==="1",!1),this}getState(){return this._state}setState(e){this._state=h.create(e,t=>t),this.getMetaframeIds().forEach(t=>{this.getMetaframe(t).setInputs(this._state.metaframes.inputs[t]),this.getMetaframe(t).setOutputs(this._state.metaframes.outputs[t])}),this.listenerCount(u.State)>0&&O!==this._state&&this.emit(u.State,this._state)}getStateMetaframes(){return this._state.metaframes}getDefinition(){return this._definition}async setDefinition(e,t){if(!e.version)throw"Metapage definition must have a version";const i=await Z(e);if(this.isDisposed())return this;i.metaframes&&Object.keys(i.metaframes).forEach(a=>{var r=i.metaframes[a];if(typeof r!="object")throw this.emitErrorMessage(`Metaframe "${a}" is not an object`),`Metaframe "${a}" is not an object`;if(!r.url)throw this.emitErrorMessage(`Metaframe "${a}" missing field: url`),`Metaframe "${a}" missing field: url`});const n=this._definition;return this._definition=i,Object.keys(this._metaframes).forEach(a=>{(!i.metaframes||!i.metaframes[a])&&this.removeMetaframe(a)}),t&&(this._state=h.create(t,a=>a)),i.metaframes&&Object.keys(i.metaframes).forEach(a=>{if(!this._metaframes.hasOwnProperty(a)){const r=i.metaframes[a];this.addMetaframe(a,r)}}),n!==x&&window.setTimeout(()=>{!this.isDisposed()&&i===this._definition&&(this._emitDefinitionEvent(),t&&this.listenerCount(u.State)>0&&O!==this._state&&this.emit(u.State,this._state))},0),this}setMetadata(e){this._definition=h.create(this._definition,t=>{t.meta=e}),this._emitDefinitionEvent()}_emitDefinitionEvent(){if(this.listenerCount(u.Definition)>0){const e={definition:this._definition,metaframes:this._metaframes};this.emit(u.Definition,e)}}addPipe(e,t){this._inputMap=h.create(this._inputMap,i=>{i[e]||(i[e]=[]),i[e].push(t)})}removeMetaframe(e){this._metaframes[e]&&(this._metaframes[e].dispose(),this._metaframes=h.create(this._metaframes,t=>{delete t[e]}),this._state=h.create(this._state,t=>{delete t.metaframes.inputs[e],delete t.metaframes.outputs[e]}),this._inputMap=h.create(this._inputMap,t=>{delete t[e],Object.keys(t).forEach(i=>{const n=t[i];let a=0;for(;a<=n.length;)n[a]&&n[a].metaframe===e?n.splice(a,1):a++})}),this._cachedInputLookupMap=h.create({},t=>t))}removeAll(){Object.keys(this._metaframes).forEach(e=>this._metaframes[e].dispose()),this._metaframes=h.create({},e=>e),this._state=O,this._inputMap=h.create({},e=>e),this._cachedInputLookupMap=h.create({},e=>e)}metaframes(){return this.getMetaframes()}metaframeIds(){return this.getMetaframeIds()}getMetaframeIds(){return Object.keys(this._metaframes)}getMetaframes(){return this._metaframes}getMetaframe(e){return this==null?void 0:this._metaframes[e]}addMetaframe(e,t){if(!e)throw"addMetaframe missing metaframeId";if(!t)throw"addMetaframe missing definition";if(this._metaframes[e])throw this.emitErrorMessage(`Existing metaframe for id=${e}`),`Existing metaframe for id=${e}`;if(!t.url)throw this.emitErrorMessage(`Metaframe definition missing url id=${e}`),`Metaframe definition missing url id=${e}`;var i=new fe(this,t.url,e,this._id,this._consoleBackgroundColor,this.debug).setMetapage(this);return this._metaframes=h.create(this._metaframes,n=>{n[e]=i}),i.addListener(u.Error,n=>{this.emit(u.Error,{metaframeId:i.id,metaframeUrl:i.url,error:n})}),t.inputs&&t.inputs.forEach(n=>this.addPipe(e,n)),i.setInputs(this._state.metaframes.inputs[e]),i}dispose(){this.log("disposing"),super.removeAllListeners(),window.removeEventListener("message",this.onMessage),this._metaframes&&Object.keys(this._metaframes).forEach(e=>this._metaframes[e].dispose()),this._id=void 0,this._metaframes=void 0,this._state=void 0,this._cachedInputLookupMap=void 0,this._inputMap=void 0}log(e,t,i){this.debug&&this.logInternal(e,t,i)}error(e){this.logInternal(e,"f00",this._consoleBackgroundColor),this.emitErrorMessage(`${e}`)}emitErrorMessage(e){this.emit(u.Error,e)}getInputsFromOutput(e,t){return this._cachedInputLookupMap[e]||(this._cachedInputLookupMap=h.create(this._cachedInputLookupMap,i=>{i[e]=h.create({},n=>n)})),this._cachedInputLookupMap[e][t]||(this._cachedInputLookupMap=h.create(this._cachedInputLookupMap,i=>{var n=[];i[e][t]=n,Object.keys(this._inputMap).forEach(a=>{a!==e&&this._inputMap[a].forEach(r=>{if(r.metaframe===e&&me(t,r.source)){var o=r.target||"";!r.target||r.target.startsWith("*")||r.target===""?o=t:o&&o.endsWith("/")&&(o=o+t),n.push({metaframe:a,pipe:o})}})})})),this._cachedInputLookupMap[e][t]}isValidJSONRpcMessage(e){if(e.jsonrpc!=="2.0")return!1;switch(e.method){case f.SetupIframeClientRequest:return!0;default:var i=e.iframeId;return!(i&&!(e.parentId===this._id&&this._metaframes[i]))}}setInput(e,t,i){var n,a;typeof e=="object"?this.setInputStateOnlyMetapageInstanceInputs(e):typeof t=="string"?this.setInputStateOnlyMetaframeInputValue(e,t,i):this.setInputStateOnlyMetaframeInputMap(e,t||{}),this.setMetaframeClientInputAndSentClientEvent(e,t,i),(this.listenerCount(u.State)>0||this.listenerCount(u.Inputs)>0)&&O!==this._state&&(this.emit(u.State,this._state),this.emit(u.Inputs,(a=(n=this._state)==null?void 0:n.metaframes)==null?void 0:a.inputs))}setMetaframeClientInputAndSentClientEvent(e,t,i){if(typeof e=="object"){if(t||i)throw"bad arguments, see API docs";const n=e;Object.keys(n).forEach(a=>{var r=a,o=n[r];if(typeof o!="object")throw"bad arguments, see API docs";var p=this._metaframes[r];p?p.setInputs(o):this.error("No iframe id=$metaframeId")})}else if(typeof e=="string"){const n=this._metaframes[e];if(n==null&&this.error(`No iframe id=${e}`),typeof t=="string")n.setInput(t,i);else if(typeof t=="object")n.setInputs(t);else throw"bad arguments, see API docs"}else throw"bad arguments, see API docs"}setInputs(e,t,i){this.setInput(e,t,i)}setOutputStateOnlyMetapageInstanceInputs(e){this._setStateOnlyMetaframes(!1,e)}setOutputStateOnlyMetaframeInputValue(e,t,i){this._setStateOnlyMetaframeInputValue(!1,e,t,i)}setOutputStateOnlyMetaframeInputMap(e,t){this._setStateOnlyMetaframeInputMap(!1,e,t)}setInputStateOnlyMetapageInstanceInputs(e){this._setStateOnlyMetaframes(!0,e)}setInputStateOnlyMetaframeInputValue(e,t,i){this._setStateOnlyMetaframeInputValue(!0,e,t,i)}setInputStateOnlyMetaframeInputMap(e,t){this._setStateOnlyMetaframeInputMap(!0,e,t)}_setStateOnlyMetaframeInputValue(e,t,i,n){this._state=h.create(this._state,a=>{if(!this._metaframes.hasOwnProperty(t))throw`No metaframe: ${t}`;a.metaframes||(a.metaframes={inputs:{},outputs:{}}),e?a.metaframes.inputs||(a.metaframes.inputs={}):a.metaframes.outputs||(a.metaframes.outputs={});let o=e?a.metaframes.inputs:a.metaframes.outputs;o=o||{},o[t]=o[t]?o[t]:{},n===void 0?delete o[t][i]:o[t][i]=n})}_setStateOnlyMetaframeInputMap(e,t,i){!i||Object.keys(i).length===0||(this._state=h.create(this._state,n=>{if(!this._metaframes.hasOwnProperty(t))throw`No metaframe: ${t}`;let r=e?n.metaframes.inputs:n.metaframes.outputs;r[t]=r[t]?r[t]:{},Object.keys(i).forEach(o=>{i[o]===void 0?delete r[t][o]:r[t][o]=i[o]})}))}_setStateOnlyMetaframes(e,t){!t||Object.keys(t).length===0||(this._state=h.create(this._state,i=>{Object.keys(t).forEach(n=>{var a=t[n];if(typeof a!="object")throw"Object values must be objects";if(!this._metaframes.hasOwnProperty(n))throw"No metaframe: ${metaframeId}";const o=e?i.metaframes.inputs:i.metaframes.outputs;o[n]=o[n]?o[n]:{},Object.keys(a).forEach(p=>{a[p]===void 0?delete o[n][p]:o[n][p]=a[p]})})}))}onMessage(e){if(typeof e.data=="object"){const r=e.data;if(!this.isValidJSONRpcMessage(r))return;var t=r.method;const o=r.iframeId;if(!o)return;const p=this.getMetaframe(o);if(!p){this.error(`💥 onMessage no metaframe id=${o}`);return}switch(r._messageCount=++this._internalReceivedMessageCounter,this.debug&&this.log(`processing ${JSON.stringify(r,null," ").substring(0,500)}`),t){case f.SetupIframeClientRequest:p.register();break;case f.SetupIframeServerResponseAck:if(p){const b=r.params;p.registered(b.version)}break;case f.OutputsUpdate:const v=r.params;if(!v||Object.keys(v).length===0)break;if(this._metaframes[o]){var i=this._metaframes[o];this.setOutputStateOnlyMetaframeInputMap(o,v),i.setOutputs(v);var n=!1;const b=Object.keys(v),m={};b.forEach((_,F)=>{const S=this.getInputsFromOutput(o,_);S.length>0&&S.forEach(k=>{m[k.metaframe]||(m[k.metaframe]={}),m[k.metaframe][k.pipe]=v[_],n=!0})}),n&&(this.setInputStateOnlyMetapageInstanceInputs(m),Object.keys(m).forEach(_=>{this._metaframes[_].setInputs(m[_])})),this.listenerCount(u.State)>0&&O!==this._state&&this.emit(u.State,this._state),this.debug&&i.ack({jsonrpc:r,state:this._state})}else this.error(`missing metaframe=${o}`);break;case f.InputsUpdate:var a=r.params;this.debug&&this.log(`inputs ${JSON.stringify(a)} from ${o}`),this._metaframes[o]?(this.setInputStateOnlyMetaframeInputMap(o,a),this._metaframes[o].setInputs(a),this.listenerCount(u.State)>0&&O!==this._state&&this.emit(u.State,this._state),this.debug&&this._metaframes[o].ack({jsonrpc:r,state:this._state})):(console.error(`InputsUpdate failed no metaframe id: "${o}"`),this.error(`InputsUpdate failed no metaframe id: "${o}"`));break;case f.HashParamsUpdate:if(p){const b=r.params,m=new URL(p.url);m.hash=b.hash,p.url=m.href,this._definition=h.create(this._definition,_=>{_.metaframes[b.metaframe].url=m.href}),this._emitDefinitionEvent()}break;default:this.debug&&this.log(`Unknown RPC method: "${t}"`)}this.listenerCount(u.Message)>0&&this.emit(u.Message,r)}}logInternal(e,t,i){i=i||this._consoleBackgroundColor;let n;typeof e=="string"?n=e:typeof e=="number"?n=e+"":n=JSON.stringify(e),n=this._id?`Metapage[${this._id}] ${n}`:n,V(n,t,i)}};y.version=W;y.DEFINITION=u.Definition;y.ERROR=u.Error;y.INPUTS=u.Inputs;y.MESSAGE=u.Message;y.OUTPUTS=u.Outputs;y.STATE=u.State;y.deserializeInputs=R;y.serializeInputs=D;let at=y;exports.INITIAL_NULL_METAPAGE_DEFINITION=x;exports.INTERNAL_ERROR=qe;exports.INVALID_PARAMS=ze;exports.INVALID_REQUEST=Je;exports.JsonRpcMethodsFromChild=f;exports.JsonRpcMethodsFromParent=M;exports.METAFRAME_JSON_FILE=_e;exports.METAPAGE_KEY_DEFINITION=ye;exports.METAPAGE_KEY_STATE=be;exports.METHOD_NOT_FOUND=We;exports.Metaframe=et;exports.MetaframeEvents=pe;exports.MetaframeLoadingState=ue;exports.MetaframeVersionCurrent=C;exports.MetaframeVersionsAll=j;exports.Metapage=at;exports.MetapageEvents=u;exports.MetapageHashParams=A;exports.MetapageIFrameRpcClient=fe;exports.MetapageShared=ne;exports.MetapageVersionCurrent=P;exports.MetapageVersionsAll=B;exports.PARSE_ERROR=He;exports.VERSION_METAFRAME=X;exports.VERSION_METAPAGE=W;exports.convertMetaframeDefinitionToCurrentVersion=ee;exports.convertMetaframeDefinitionToVersion=q;exports.convertMetaframeJsonToCurrentVersion=te;exports.convertMetapageDefinitionToCurrentVersion=Z;exports.convertMetapageDefinitionToVersion=z;exports.deserializeInputs=R;exports.generateId=T;exports.generateMetaframeId=Ye;exports.generateMetapageId=ae;exports.generateNonce=Qe;exports.getLibraryVersionMatching=it;exports.getMatchingMetaframeVersion=d;exports.getMatchingMetapageVersion=I;exports.getMetaframeDefinitionFromUrl=le;exports.getMetapageDefinitionFromUrl=tt;exports.getUrlParam=xe;exports.getUrlParamDebug=Ke;exports.hashCode=re;exports.intToRGB=oe;exports.isDebugFromUrlsParams=U;exports.isEmptyMetaframeDefinition=st;exports.isIframe=ie;exports.isJsonRpcId=Ge;exports.isPageLoaded=L;exports.log=V;exports.matchPipe=me;exports.merge=E;exports.metapageAllSha256Hash=Xe;exports.metapageOnlyEssentailSha256Hash=Ze;exports.pageLoaded=$;exports.possiblyDeserializeDatarefToFile=Ne;exports.possiblyDeserializeDatarefToValue=G;exports.possiblySerializeValueToDataref=se;exports.serializeInputs=D;exports.stringToRgb=K;exports.valueToFile=Be;
3
+ //# sourceMappingURL=index.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.cjs","sources":["../src/metapage/versions.ts","../src/metapage/Constants.ts","../src/metapage/conversions-metapage.ts","../src/metapage/conversions-metaframe.ts","../src/metapage/data.ts","../src/metapage/events.ts","../src/metapage/jsonrpc.ts","../src/metapage/jsonrpc2.ts","../src/metapage/Shared.ts","../src/metapage/MetapageTools.ts","../src/metapage/Metaframe.ts","../src/metapage/util.ts","../src/metapage/MetapageIFrameRpcClient.ts","../src/metapage/Metapage.ts"],"sourcesContent":["// There used to be a single version, but there's no reason to upgrade both versions\n// simultaneously. Same versions are an ideal, but forcing it is also bad\n\nexport const MetaframeVersionsAll = [\"0.3\", \"0.4\", \"0.5\", \"0.6\", \"1\", \"2\"] as const;\n// Create the type from the array\nexport type VersionsMetaframe = (typeof MetaframeVersionsAll)[number];\n\nexport const MetapageVersionsAll = [\"0.2\", \"0.3\", \"1\", \"2\"] as const;\n// Create the type from the array\nexport type VersionsMetapage = (typeof MetapageVersionsAll)[number];\n\nexport const MetaframeVersionCurrent :VersionsMetaframe = \"2\";\nexport const MetapageVersionCurrent :VersionsMetapage = \"2\";\n","import {\n MetaframeVersionsAll,\n MetapageVersionsAll,\n} from './versions';\n\nexport const METAFRAME_JSON_FILE = \"metaframe.json\";\n/**\n * TODO: obsolete? This was used by plugins, which have been removed.\n */\nexport const METAPAGE_KEY_DEFINITION = \"metapage/definition\";\n/**\n * TODO: obsolete? This was used by plugins, which have been removed.\n */\nexport const METAPAGE_KEY_STATE = \"metapage/state\";\n\nexport const VERSION_METAPAGE = MetapageVersionsAll[MetapageVersionsAll.length - 1];\nexport const VERSION_METAFRAME = MetaframeVersionsAll[MetaframeVersionsAll.length - 1];\n","import { compareVersions } from 'compare-versions';\nimport fetchRetryWrapper from \"fetch-retry\";\nimport { create } from 'mutative';\n\nimport { MetapageDefinitionV02 } from './v0_2/all.js';\nimport { MetapageDefinitionV03 } from './v0_3/all.js';\nimport {\n MetapageDefinitionV1\n} from './v1/index.js';\nimport {\n MetapageVersionCurrent,\n VersionsMetapage,\n} from './versions.js';\nimport { MetapageDefinitionV2 } from './v2/metapage.js';\n\nconst fetchRetry = fetchRetryWrapper(fetch);\n\nexport const convertMetapageDefinitionToVersion = async (\n def: any | MetapageDefinitionV02 | MetapageDefinitionV03 | MetapageDefinitionV1 | MetapageDefinitionV2,\n targetVersion: VersionsMetapage\n): Promise<any> => {\n if (!def) {\n throw \"Metapage definition null\";\n }\n\n if (!def.version) {\n def = create(def, (draft :MetapageDefinitionV03) => {\n draft.version = \"0.3\";\n }) as MetapageDefinitionV03;\n }\n if (!targetVersion) {\n throw 'Missing \"version\" argument';\n }\n\n if (compareVersions(targetVersion, MetapageVersionCurrent) > 0) {\n // The version we are given is from the future, so we need the API to convert it\n try {\n const resp = await fetchRetry(`https://module.metapage.io/conversion/metapage/${targetVersion}`, \n {\n redirect: \"follow\",\n retries: 3,\n retryDelay: 1000,\n method: \"POST\",\n body: JSON.stringify(def),\n headers: {\n \"Content-Type\": \"application/json\",\n },\n }\n );\n const respBody = await resp.json();\n return respBody as MetapageDefinitionV1;\n } catch(err) {\n throw `Error converting metapage definition to version ${targetVersion}: ${err}`;\n }\n \n }\n\n const targetDefinition = convertMetapageDefinitionToTargetVersionInternal(def, targetVersion);\n return targetDefinition;\n};\n\nexport const convertMetapageDefinitionToCurrentVersion = async (\n def: any | MetapageDefinitionV02 | MetapageDefinitionV03 | MetapageDefinitionV1 | MetapageDefinitionV2\n): Promise<MetapageDefinitionV1> => {\n\n return convertMetapageDefinitionToVersion(def, MetapageVersionCurrent);\n};\n\nconst convertMetapageDefinitionToTargetVersionInternal = (\n def: any | MetapageDefinitionV02 | MetapageDefinitionV03 | MetapageDefinitionV1 | MetapageDefinitionV2,\n targetVersion: VersionsMetapage\n): MetapageDefinitionV02 | MetapageDefinitionV03 | MetapageDefinitionV1 | MetapageDefinitionV2 => {\n if (!def) {\n throw \"Metapage definition null\";\n }\n\n if (!def.version) {\n throw 'Missing \"version\" key in metapage definition';\n }\n\n let currentVersion = getMatchingMetapageVersion(def.version);\n if (currentVersion === targetVersion) {\n return def;\n }\n\n let currentDefinition: MetapageDefinitionV02 | MetapageDefinitionV03 | MetapageDefinitionV1 | MetapageDefinitionV2 = def;\n\n while (currentVersion !== targetVersion) {\n switch (currentVersion) {\n case \"0.2\": {\n if (compareVersions(targetVersion, currentVersion) > 0) {\n currentDefinition = definition_v0_2_to_v0_3(currentDefinition as MetapageDefinitionV02);\n currentVersion = getMatchingMetapageVersion(currentDefinition.version);\n } else {\n throw `Cannot convert from version ${currentVersion} to ${targetVersion}`;\n }\n break;\n }\n case \"0.3\": {\n if (compareVersions(targetVersion, currentVersion) > 0) {\n currentDefinition = definition_v0_3_to_v1(currentDefinition as MetapageDefinitionV03);\n currentVersion = getMatchingMetapageVersion(currentDefinition.version);\n } else {\n currentDefinition = definition_v0_3_to_v0_2(currentDefinition as MetapageDefinitionV03);\n currentVersion = getMatchingMetapageVersion(currentDefinition.version);\n }\n break;\n }\n case \"1\": {\n if (compareVersions(targetVersion, currentVersion) > 0) {\n currentDefinition = definition_v1_to_v2(currentDefinition as MetapageDefinitionV1);\n currentVersion = getMatchingMetapageVersion(currentDefinition.version);\n } else {\n currentDefinition = definition_v1_to_v0_3(currentDefinition as MetapageDefinitionV1);\n currentVersion = getMatchingMetapageVersion(currentDefinition.version);\n }\n break;\n }\n case \"2\": {\n if (compareVersions(targetVersion, currentVersion) > 0) {\n throw `Cannot convert from version ${currentVersion} to ${targetVersion}, 1 is the latest version`;\n } else {\n currentDefinition = definition_v2_to_v1(currentDefinition as MetapageDefinitionV2);\n currentVersion = getMatchingMetapageVersion(currentDefinition.version);\n }\n break;\n }\n default:\n throw `Unknow version ${currentVersion} to ${targetVersion}`; // Latest\n }\n\n }\n return currentDefinition;\n};\n\n\nconst definition_v0_2_to_v0_3 = (\n old: MetapageDefinitionV02\n): MetapageDefinitionV03 => {\n return create<MetapageDefinitionV03>(old, (draft: MetapageDefinitionV02) => {\n // Exactly the same except v0.3 has plugins\n draft.version = \"0.3\";\n });\n};\n\nconst definition_v0_3_to_v0_2 = (\n old: MetapageDefinitionV03\n): MetapageDefinitionV02 => {\n return create<MetapageDefinitionV02>(old, (draft: MetapageDefinitionV03) => {\n // Exactly the same except v0.3 has plugins\n draft.version = \"0.2\";\n });\n};\n\n\nconst definition_v0_3_to_v1 = (\n def: MetapageDefinitionV03\n): MetapageDefinitionV1 => {\n\n return create<MetapageDefinitionV1>(def, (draft) => {\n // We removed plugins in v1\n const castV1 = draft as MetapageDefinitionV03;\n delete castV1.plugins;\n castV1.version = \"1\";\n });\n};\n\nconst definition_v1_to_v0_3 = (\n def: MetapageDefinitionV1\n): MetapageDefinitionV03 => {\n\n return create(def, (draft:MetapageDefinitionV1) => {\n // We removed plugins in v1, but we don't need to add them back\n draft.version = \"0.3\";\n return draft;\n }) as MetapageDefinitionV03;\n};\n\n\nconst definition_v2_to_v1 = (\n def: MetapageDefinitionV2\n): MetapageDefinitionV1 => {\n\n return create(def, (draft:MetapageDefinitionV2) => {\n // keywords -> tags\n // author -> authors\n draft.version = \"1\";\n if (draft?.meta?.tags) {\n (draft as MetapageDefinitionV1).meta!.keywords = draft.meta.tags;\n delete draft.meta!.tags;\n }\n if (draft?.meta?.authors) {\n (draft as MetapageDefinitionV1).meta!.author = draft.meta.authors[0];\n delete (draft as MetapageDefinitionV2).meta!.authors;\n }\n return draft;\n }) as MetapageDefinitionV1;\n};\n\nconst definition_v1_to_v2 = (\n def: MetapageDefinitionV1\n): MetapageDefinitionV2 => {\n\n return create(def, (draft:MetapageDefinitionV1) => {\n // tags -> keywords\n // authors -> author\n draft.version = \"2\";\n \n if (draft?.meta?.keywords) {\n (draft as MetapageDefinitionV2).meta!.tags = draft.meta.keywords;\n delete (draft as MetapageDefinitionV1).meta!.keywords;\n }\n if (draft?.meta?.author) {\n (draft as MetapageDefinitionV2).meta!.authors = [draft.meta.author];\n delete (draft as MetapageDefinitionV1).meta!.author;\n }\n \n return draft;\n }) as MetapageDefinitionV2;\n};\n\nexport const getMatchingMetapageVersion = (version: string): VersionsMetapage => {\n if (version === \"latest\") {\n return MetapageVersionCurrent;\n } else if (compareVersions(version, \"0.2\") < 0) {\n throw `Unknown version: ${version}`;\n } else if (\n compareVersions(version, \"0.2\") <= 0 &&\n compareVersions(version, \"0.3\") < 0\n ) {\n return \"0.2\";\n } else if (compareVersions(version, \"0.3\") <= 0) {\n return \"0.3\";\n } else if (compareVersions(version, \"1\") <= 0) {\n return \"1\";\n } else if (version === \"2\") {\n return \"2\";\n } else {\n // Return something, assume latest\n throw `Unknown version: ${version}`;\n }\n};\n","import { compareVersions } from 'compare-versions';\nimport { create } from 'mutative';\nimport fetchRetryWrapper from \"fetch-retry\";\nimport { type MetaframeDefinitionV03 } from './v0_3/all.js';\nimport {\n MetaframeDefinitionV4,\n MetaframeDefinitionV5,\n MetaframeDefinitionV6,\n} from './v0_4/index.js';\nimport {\n MetaframeDefinitionV1,\n} from './v1/index.js';\nimport {\nMetaframeVersionCurrent,\n type VersionsMetaframe,\n} from './versions.js';\nimport { MetaframeDefinitionV2 } from './v2/metaframe.js';\n\nconst fetchRetry = fetchRetryWrapper(fetch);\n\ntype AnyMetaframeDefinition = MetaframeDefinitionV03 | MetaframeDefinitionV4 | MetaframeDefinitionV5 | MetaframeDefinitionV6 | MetaframeDefinitionV1 | MetaframeDefinitionV2;\n\nexport const convertMetaframeDefinitionToVersion = async (\n def: any | AnyMetaframeDefinition,\n targetVersion: VersionsMetaframe\n): Promise<any> => {\n if (!def) {\n throw \"Metapage definition null\";\n }\n\n if (!def.version) {\n throw 'Missing \"version\" key in metapage definition';\n }\n if (!targetVersion) {\n throw 'Missing \"version\" argument';\n }\n\n if (compareVersions(targetVersion, MetaframeVersionCurrent) > 0) {\n // The version we are given is from the future, so we need the API to convert it\n try {\n const resp = await fetchRetry(`https://module.metapage.io/conversion/metaframe/${targetVersion}`, \n {\n redirect: \"follow\",\n retries: 3,\n retryDelay: 1000,\n method: \"POST\",\n body: JSON.stringify(def),\n headers: {\n \"Content-Type\": \"application/json\",\n },\n }\n );\n const respBody = await resp.json();\n return respBody as MetaframeDefinitionV2;\n } catch(err) {\n throw `Error converting metapage definition to version ${targetVersion}: ${err}`;\n }\n \n }\n\n const targetDefinition = convertMetaframeDefinitionToTargetVersionInternal(def, targetVersion);\n return targetDefinition;\n};\n\nexport const convertMetaframeDefinitionToCurrentVersion = async (\n def: any | AnyMetaframeDefinition\n): Promise<MetaframeDefinitionV1> => {\n return convertMetaframeDefinitionToVersion(def, MetaframeVersionCurrent);\n};\n\nconst convertMetaframeDefinitionToTargetVersionInternal = (\n def: any | AnyMetaframeDefinition,\n targetVersion: VersionsMetaframe\n): AnyMetaframeDefinition => {\n if (!def) {\n throw \"Metaframe definition null\";\n }\n\n if (!def.version) {\n // we assume this is an older version of the definition\n // that does not have the version key\n def = create(def, (draft :MetaframeDefinitionV03) => {\n draft.version = \"0.3\";\n }) as MetaframeDefinitionV6;\n }\n\n let currentVersion = getMatchingMetaframeVersion(def.version);\n if (currentVersion === targetVersion) {\n return def;\n }\n\n let currentDefinition:AnyMetaframeDefinition = def;\n\n // [\"0.3\", \"0.4\", \"0.5\", \"0.6\", \"1\", \"2\"]\n while (currentVersion !== targetVersion) {\n switch (currentVersion) {\n case \"0.3\": {\n if (compareVersions(targetVersion, currentVersion) > 0) {\n currentDefinition = definition_v0_3_to_v0_4(currentDefinition as MetaframeDefinitionV03);\n currentVersion = getMatchingMetaframeVersion(currentDefinition.version);\n } else {\n throw `Cannot convert from version ${currentVersion} to ${targetVersion}`;\n }\n break;\n }\n case \"0.4\": {\n if (compareVersions(targetVersion, currentVersion) > 0) {\n currentDefinition = definition_v0_4_to_v0_5(currentDefinition as MetaframeDefinitionV4);\n currentVersion = getMatchingMetaframeVersion(currentDefinition.version);\n } else {\n currentDefinition = definition_v0_4_to_v0_3(currentDefinition as MetaframeDefinitionV4);\n currentVersion = getMatchingMetaframeVersion(currentDefinition.version);\n }\n break;\n }\n case \"0.5\": {\n if (compareVersions(targetVersion, currentVersion) > 0) {\n currentDefinition = definition_v0_5_to_v0_6(currentDefinition as MetaframeDefinitionV5);\n currentVersion = getMatchingMetaframeVersion(currentDefinition.version);\n } else {\n currentDefinition = definition_v0_5_to_v0_4(currentDefinition as MetaframeDefinitionV5);\n currentVersion = getMatchingMetaframeVersion(currentDefinition.version);\n }\n break;\n }\n case \"0.6\": {\n if (compareVersions(targetVersion, currentVersion) > 0) {\n currentDefinition = definition_v0_6_to_v1(currentDefinition as MetaframeDefinitionV6);\n currentVersion = getMatchingMetaframeVersion(currentDefinition.version);\n } else {\n currentDefinition = definition_v0_6_to_v0_5(currentDefinition as MetaframeDefinitionV6);\n currentVersion = getMatchingMetaframeVersion(currentDefinition.version);\n }\n break;\n }\n case \"1\": {\n if (compareVersions(targetVersion, currentVersion) > 0) {\n currentDefinition = definition_v1_to_v2(currentDefinition as MetaframeDefinitionV1);\n currentVersion = getMatchingMetaframeVersion(currentDefinition.version);\n } else {\n currentDefinition = definition_v1_to_v0_6(currentDefinition as MetaframeDefinitionV1);\n currentVersion = getMatchingMetaframeVersion(currentDefinition.version);\n }\n break;\n }\n case \"2\": {\n if (compareVersions(targetVersion, currentVersion) > 0) {\n throw `Cannot convert from version ${currentVersion} to ${targetVersion}`;\n } else {\n currentDefinition = definition_v2_to_v1(currentDefinition as MetaframeDefinitionV2);\n currentVersion = getMatchingMetaframeVersion(currentDefinition.version);\n }\n break;\n }\n default:\n throw `Unknow version ${currentVersion} to ${targetVersion}`; // Latest\n }\n\n }\n return currentDefinition;\n};\n\nexport const convertMetaframeJsonToCurrentVersion = async (\n m: AnyMetaframeDefinition | undefined,\n // deprecated\n opts?: { errorIfUnknownVersion?: boolean }\n): Promise<MetaframeDefinitionV2 | undefined> => {\n if (!m) {\n return;\n }\n return convertMetaframeDefinitionToCurrentVersion(m);\n};\n\nconst definition_v0_4_to_v0_3 = (def: MetaframeDefinitionV4) => {\n return create(def, (draft :MetaframeDefinitionV4) => {\n draft.version = \"0.3\";\n delete draft.allow;\n }) as MetaframeDefinitionV03;\n};\n\nconst definition_v0_3_to_v0_4 = (def: MetaframeDefinitionV03) => {\n return create(def, (draft :MetaframeDefinitionV03) => {\n draft.version = \"0.4\";\n }) as MetaframeDefinitionV4;\n};\n\nconst definition_v0_4_to_v0_5 = (def: MetaframeDefinitionV4) => {\n return create(def, (draft :MetaframeDefinitionV4) => {\n draft.version = \"0.5\";\n if (!draft?.metadata) {\n return;\n }\n const title = draft.metadata.title;\n delete draft.metadata.title;\n (draft as MetaframeDefinitionV5).metadata!.name = title;\n\n const descriptionUrl = draft.metadata.descriptionUrl;\n delete draft.metadata.descriptionUrl;\n (draft as MetaframeDefinitionV5).metadata!.description = descriptionUrl;\n\n const keywords = draft.metadata.keywords;\n delete draft.metadata.keywords;\n (draft as MetaframeDefinitionV5).metadata!.tags = keywords;\n\n }) as MetaframeDefinitionV1;\n};\n\nconst definition_v0_5_to_v0_4 = (def: MetaframeDefinitionV5) => {\n return create(def, (draft :MetaframeDefinitionV5) => {\n draft.version = \"0.4\";\n if (!draft?.metadata) {\n return;\n }\n const name = draft.metadata.name;\n delete draft.metadata.name;\n (draft as MetaframeDefinitionV4).metadata.title = name;\n\n const decription = draft.metadata.description;\n delete draft.metadata.description;\n (draft as MetaframeDefinitionV4).metadata.descriptionUrl = decription;\n\n const tags = draft.metadata.tags;\n delete draft.metadata.tags;\n (draft as MetaframeDefinitionV4).metadata.keywords = tags;\n\n }) as MetaframeDefinitionV4;\n};\n\n// v0.6 and v1 are identical, but remove the operations field\nconst definition_v0_6_to_v1 = (def: MetaframeDefinitionV6) :MetaframeDefinitionV1 => {\n return create(def, (draft: MetaframeDefinitionV6) => {\n draft.version = \"1\";\n if (draft?.metadata?.operations) {\n delete draft.metadata.operations;\n }\n }) as MetaframeDefinitionV1;\n}\n\n// v0.6 and v1 are identical\nconst definition_v1_to_v0_6 = (def: MetaframeDefinitionV1) :MetaframeDefinitionV6 => {\n return create(def, (draft: MetaframeDefinitionV1) => {\n draft.version = \"0.6\";\n if (draft?.metadata?.operations) {\n delete draft.metadata.operations;\n }\n }) as MetaframeDefinitionV6;\n}\n\nconst definition_v2_to_v1 = (def: MetaframeDefinitionV2) :MetaframeDefinitionV1 => {\n return create(def, (draft: MetaframeDefinitionV2) => {\n draft.version = \"1\";\n if (draft?.metadata?.authors) {\n // ugh we lose information here, but it's the best we can do\n (draft as MetaframeDefinitionV1).metadata.author = draft?.metadata?.authors[0];\n delete draft.metadata.authors;\n }\n return draft;\n }) as MetaframeDefinitionV1;\n}\n\nconst definition_v1_to_v2 = (def: MetaframeDefinitionV1) :MetaframeDefinitionV2 => {\n return create(def, (draft: MetaframeDefinitionV1) => {\n draft.version = \"2\";\n if (draft?.metadata?.author) {\n // ugh we lose information here, but it's the best we can do\n (draft as MetaframeDefinitionV2).metadata.authors = [draft.metadata.author];\n delete draft.metadata.author;\n }\n return draft;\n }) as MetaframeDefinitionV2;\n}\n\n// The only difference between v5 and v6 is the metadata operations field\n// which we are not using in any of those versions, its too new and not stable\n// and not documented.\nconst definition_v0_5_to_v0_6 = (source: MetaframeDefinitionV5) :MetaframeDefinitionV6 => {\n return create(source, (draft: MetaframeDefinitionV5) => {\n draft.version = \"0.6\";\n if ((draft as MetaframeDefinitionV6)?.metadata?.operations) {\n delete (draft as MetaframeDefinitionV6).metadata!.operations;\n }\n }) as MetaframeDefinitionV6;\n};\n\n// The only difference between v5 and v6 is the metadata operations field\n// which we are not using in any of those versions, its too new and not stable\n// and not documented.\nconst definition_v0_6_to_v0_5 = (source: MetaframeDefinitionV6) :MetaframeDefinitionV5 => {\n return create<MetaframeDefinitionV5>(source, (draft: MetaframeDefinitionV6) => {\n draft.version = \"0.5\";\n if (draft?.metadata?.operations) {\n delete draft.metadata.operations;\n }\n });\n};\n\n// [\"0.3\", \"0.4\", \"0.5\", \"0.6\", \"1\"]\nexport const getMatchingMetaframeVersion = (version: string): VersionsMetaframe => {\n if (version === \"latest\") {\n return MetaframeVersionCurrent;\n } else if (compareVersions(version, \"0.3\") < 0) {\n throw `Unknown version: ${version}`;\n } else if (compareVersions(version, \"0.3\") <= 0) {\n return \"0.3\";\n } else if (compareVersions(version, \"0.4\") <= 0) {\n return \"0.4\";\n } else if (compareVersions(version, \"0.5\") <= 0) {\n return \"0.5\";\n } else if (compareVersions(version, \"0.6\") <= 0) {\n return \"0.6\";\n } else if (compareVersions(version, \"1\") <= 0) {\n return \"1\";\n } else if (version === \"2\") {\n return \"2\";\n } else {\n // Return something, assume latest\n throw `Unknown version: ${version}`;\n }\n};\n","import { MetaframeInputMap } from \"./v0_4\";\nimport { encode, decode } from \"base64-arraybuffer\";\nimport { create } from 'mutative';\n\n/**\n * Modifies in place!!!\n * @param inputs\n * @returns\n */\nexport const serializeInputs = async (\n inputs: MetaframeInputMap\n): Promise<MetaframeInputMap> => {\n // only serialize one level deep\n return create<MetaframeInputMap>(inputs, async (draft: MetaframeInputMap) => {\n for (const key of Object.keys(inputs)) {\n const maybeNewObject = await possiblySerializeValueToDataref(inputs[key]);\n draft[key] = maybeNewObject;\n return draft;\n }\n });\n};\n\n/**\n * Modifies in place!!!\n * @param inputs\n * @returns\n */\nexport const deserializeInputs = async (\n inputs: MetaframeInputMap\n): Promise<MetaframeInputMap> => {\n // only deserialize one level deep\n return create<MetaframeInputMap>(inputs, async (draft: MetaframeInputMap) => {\n for (const key of Object.keys(inputs)) {\n const maybeNewObject = await possiblyDeserializeDatarefToValue(inputs[key]);\n draft[key] = maybeNewObject;\n return draft;\n }\n });\n};\n\nexport type DataRefSerialized = {\n // This means it's a serialized DataRef\n _s: true;\n // constructor\n _c: string;\n // value is base64 encoded\n value: string;\n size: number;\n};\n\nexport type DataRefSerializedTypedArray = DataRefSerialized & {\n // Typed arrays are from ArrayBufferView\n byteLength: number;\n byteOffset: number;\n};\n\nexport type DataRefSerializedBlob = DataRefSerialized & {\n fileType?: string;\n};\n\nexport type DataRefSerializedFile = DataRefSerializedBlob & {\n name: string;\n lastModified?: number;\n};\n\nexport const valueToFile = async (value: any, fileName: string, options?: FilePropertyBag): Promise<File> => {\n value = possiblyDeserializeDatarefToValue(value);\n options = options || {};\n if (!options.type) {\n options.type = \"application/octet-stream\";\n }\n\n if (value instanceof ArrayBuffer) {\n return new File([value], fileName, options);\n }\n if (value instanceof File || value instanceof Blob) {\n const buffer = await value.arrayBuffer();\n if (value instanceof File) {\n options.type = (value as File).type;\n }\n return new File([buffer], fileName, options);\n }\n if (\n value instanceof Int8Array ||\n value instanceof Uint8Array ||\n value instanceof Uint8ClampedArray ||\n value instanceof Int16Array ||\n value instanceof Uint16Array ||\n value instanceof Int32Array ||\n value instanceof Uint32Array ||\n value instanceof Float32Array ||\n value instanceof Float64Array\n ) {\n const typedValue = value as ArrayBufferView;\n return new File([typedValue.buffer], fileName, options);\n }\n if (typeof(value) === \"string\") {\n var blob = new Blob([value], { type: 'text/plain' });\n options.type = \"text/plain\";\n return new File([blob], fileName, options);\n }\n if (typeof(value) === \"object\") {\n const blob = new Blob([JSON.stringify(value)], {\n type: 'application/json',\n });\n options.type = \"application/json\";\n return new File([blob], fileName, options);\n }\n\n // assume it's a string\n var blob = new Blob([value as string], { type: 'text/plain' });\n options.type = \"text/plain\";\n return new File([blob], fileName, options);\n};\n\nexport const possiblySerializeValueToDataref = async <T>(\n value: T\n): Promise<T | DataRefSerialized> => {\n if (\n value instanceof Int8Array ||\n value instanceof Uint8Array ||\n value instanceof Uint8ClampedArray ||\n value instanceof Int16Array ||\n value instanceof Uint16Array ||\n value instanceof Int32Array ||\n value instanceof Uint32Array ||\n value instanceof Float32Array ||\n value instanceof Float64Array\n ) {\n const typedValue = value as ArrayBufferView;\n const replacement: DataRefSerializedTypedArray = {\n _s: true,\n _c: value.constructor.name,\n value: encode(typedValue.buffer),\n byteLength: typedValue.byteLength,\n byteOffset: typedValue.byteOffset,\n size: typedValue.byteLength,\n };\n return Promise.resolve(replacement);\n } else if (value instanceof File) {\n const typedValue = value as File;\n const arrayBuffer = await typedValue.arrayBuffer();\n const replacement: DataRefSerializedFile = {\n _s: true,\n _c: File.name,\n value: encode(arrayBuffer),\n name: typedValue.name,\n fileType: typedValue.type,\n lastModified: typedValue.lastModified,\n size: arrayBuffer.byteLength,\n };\n return replacement;\n } else if (value instanceof Blob) {\n const typedValue = value as Blob;\n const arrayBuffer = await typedValue.arrayBuffer();\n const replacement: DataRefSerializedBlob = {\n _s: true,\n _c: Blob.name,\n value: encode(arrayBuffer),\n fileType: typedValue.type,\n size: arrayBuffer.byteLength,\n };\n return replacement;\n } else if (value instanceof ArrayBuffer) {\n const typedValue = value as ArrayBuffer;\n const replacement: DataRefSerialized = {\n _s: true,\n _c: ArrayBuffer.name,\n value: encode(typedValue),\n size: typedValue.byteLength,\n };\n return Promise.resolve(replacement);\n }\n return Promise.resolve(value);\n};\n\nexport const possiblyDeserializeDatarefToValue = (value: any): any => {\n if (\n !(\n value &&\n typeof value === \"object\" &&\n (value as DataRefSerialized)._s === true\n )\n ) {\n return value;\n }\n const serializedRef = value as DataRefSerialized;\n const _c: string = serializedRef._c;\n if (_c === Blob.name) {\n const serializedRefBlob = value as DataRefSerializedBlob;\n const blob = new Blob(\n [decode(serializedRef.value)],\n {\n type: serializedRefBlob.fileType,\n }\n );\n return blob;\n } else if (_c === File.name) {\n const serializedRefFile = value as DataRefSerializedFile;\n const file = new File(\n [decode(serializedRef.value)],\n serializedRefFile.name,\n {\n type: serializedRefFile.fileType,\n lastModified: serializedRefFile.lastModified,\n }\n );\n return file;\n } else if (_c === ArrayBuffer.name) {\n const arrayBuffer: ArrayBuffer = decode(serializedRef.value);\n return arrayBuffer;\n }\n // Assume typed array\n const serializedRefTypedArray = value as DataRefSerializedTypedArray;\n\n const arrayBuffer: ArrayBuffer = decode(\n serializedRefTypedArray.value\n );\n const constructorName: string = serializedRefTypedArray._c;\n\n try {\n // @ts-ignore\n const typedArray: ArrayBufferView = new globalThis[constructorName](\n arrayBuffer,\n // serializedRefTypedArray.byteOffset,\n // serializedRefTypedArray.byteLength\n );\n return typedArray;\n } catch (e) {}\n return value;\n};\n\nexport const possiblyDeserializeDatarefToFile = (value: any): File | undefined => {\n if (\n !(\n value &&\n typeof value === \"object\" &&\n (value as DataRefSerialized)._s === true\n )\n ) {\n return undefined;\n }\n const serializedRef = value as DataRefSerialized;\n const _c: string = serializedRef._c;\n if (_c === Blob.name) {\n const serializedRefBlob = value as DataRefSerializedBlob;\n const blob = new Blob(\n [decode(serializedRef.value)],\n {\n type: serializedRefBlob.fileType,\n }\n );\n return new File([blob], 'file', {\n type: blob.type,\n });\n } else if (_c === File.name) {\n const serializedRefFile = value as DataRefSerializedFile;\n const file = new File(\n [decode(serializedRef.value)],\n serializedRefFile.name,\n {\n type: serializedRefFile.fileType,\n lastModified: serializedRefFile.lastModified,\n }\n );\n return file;\n } else if (_c === ArrayBuffer.name) {\n const arrayBuffer: ArrayBuffer = decode(serializedRef.value);\n return new File(\n [arrayBuffer],\n \"file\",\n {\n type: \"application/octet-stream\",\n }\n );\n }\n // Assume typed array\n const serializedRefTypedArray = value as DataRefSerializedTypedArray;\n const arrayBuffer: ArrayBuffer = decode(\n serializedRefTypedArray.value\n );\n const constructorName: string = serializedRefTypedArray._c;\n\n try {\n // @ts-ignore\n const typedArray: ArrayBufferView = new globalThis[constructorName](\n arrayBuffer,\n );\n return new File(\n [typedArray],\n \"file\",\n {\n type: \"application/octet-stream\",\n }\n );\n } catch (e) {}\n return undefined;\n};\n","import { MetaframeId } from \"./core\";\nimport { MetapageDefinitionV2 } from \"./v2\";\nimport { MetapageIFrameRpcClient } from \"./MetapageIFrameRpcClient\";\n\nexport enum MetapageEvents {\n Inputs = \"inputs\",\n Outputs = \"outputs\",\n State = \"state\",\n // The definition has already changed e.g. a metaframe changes its hash params\n // so the current definition now contains that change\n Definition = \"definition\",\n Error = \"error\",\n Warning = \"warning\",\n // when a metaframe wants to tell the metapage of the new URL (for saving state/config)\n UrlHashUpdate = \"urlhashupdate\",\n // general event, all events are emitted in their raw form to this namespace\n Message = \"Message\",\n}\n\nexport interface MetapageEventDefinition {\n definition: MetapageDefinitionV2;\n metaframes: {\n [key: string]: MetapageIFrameRpcClient;\n };\n}\n\nexport type MetapageEventUrlHashUpdate = {\n metaframe: MetaframeId;\n hash: string;\n};\n","import { JsonRpcRequest } from './jsonrpc2.js';\n\nimport {\n MetaframeId,\n MetapageId,\n} from './core.js';\nimport {\n VersionsMetaframe,\n VersionsMetapage,\n} from './versions.js';\nimport { MetaframeInputMap } from './v0_4/index.js';\n\nexport enum JsonRpcMethodsFromChild {\n InputsUpdate = \"InputsUpdate\",\n OutputsUpdate = \"OutputsUpdate\",\n SetupIframeClientRequest = \"SetupIframeClientRequest\",\n SetupIframeServerResponseAck = \"SetupIframeServerResponseAck\",\n // Experimental feature\n HashParamsUpdate = \"HashParamsUpdate\",\n}\n\nexport enum JsonRpcMethodsFromParent {\n InputsUpdate = \"InputsUpdate\",\n MessageAck = \"MessageAck\",\n SetupIframeServerResponse = \"SetupIframeServerResponse\"\n}\n\nexport interface SetupIframeServerResponseData {\n iframeId: MetaframeId;\n parentId: MetapageId;\n state: {\n inputs: MetaframeInputMap\n };\n // Allow newer metaframes to handle older metapage versions\n version: VersionsMetapage;\n}\n\nexport interface MinimumClientMessage<T> extends JsonRpcRequest<T> {\n iframeId: MetaframeId | undefined;\n parentId: MetapageId | undefined;\n}\n\nexport interface SetupIframeClientAckData<T> extends MinimumClientMessage<T> {\n version: VersionsMetaframe;\n}\n\nexport interface ClientMessageRecievedAck<T> {\n message: MinimumClientMessage<T>;\n}\n","// https://gist.github.com/RickCarlino/41b8ddd36e41e381c132bbfcd1c31f3a\n\n/** A string specifying the version of the JSON-RPC protocol. MUST be exactly \"2.0\". */\nexport type JsonRpcVersion = \"2.0\";\n\n/** Method names that begin with the word rpc followed by a period character\n * (U+002E or ASCII 46) are reserved for rpc-internal methods and extensions\n * and MUST NOT be used for anything else. */\nexport type JsonRpcReservedMethod = string;\n\n/** An identifier established by the Client that MUST contain a string, Number,\n * or NULL value if included. If it is not included it is assumed to be a\n * notification. The value SHOULD normally not be Null and Numbers SHOULD\n * NOT contain fractional parts [2] */\nexport type JsonRpcId = number | string | void;\n\nexport interface JsonRpcRequest<T> {\n jsonrpc: JsonRpcVersion;\n method: string;\n id: JsonRpcId;\n params?: T;\n}\n\nexport interface JsonRpcNotification<T> extends JsonRpcResponse<T> {\n jsonrpc: JsonRpcVersion;\n params?: T;\n}\n\nexport interface JsonRpcResponse<T> {\n jsonrpc: JsonRpcVersion;\n id: JsonRpcId;\n}\n\nexport interface JsonRpcSuccess<T> extends JsonRpcResponse<T> {\n result: T;\n}\n\nexport interface JsonRpcFailure<T> extends JsonRpcResponse<T> {\n error: JsonRpcError<T>;\n}\n\nexport interface JsonRpcError<T> {\n /** Must be an integer */\n code: number;\n message: string;\n data?: T;\n}\n\n//\n// PRE-DEFINED ERROR CODES\n//\n//\n/** An error occurred on the server while parsing the JSON text. */\nexport const PARSE_ERROR = -32700;\n/** The JSON sent is not a valid Request object. */\nexport const INVALID_REQUEST = -32600;\n/** The method does not exist / is not available. */\nexport const METHOD_NOT_FOUND = -32601;\n/** Invalid method parameter(s). */\nexport const INVALID_PARAMS = -32602;\n/** Internal JSON-RPC error. */\nexport const INTERNAL_ERROR = -32603;\n\n//\n// TYPE GUARDS (for convinience)\n//\n//\n/** Determine if data is a properly formatted JSONRPC 2.0 ID. */\nexport function isJsonRpcId(input: JsonRpcId | any): input is JsonRpcId {\n switch (typeof input) {\n case \"string\":\n return true;\n case \"number\":\n return input % 1 != 0;\n case \"object\":\n let isNull = input === null;\n if (isNull) {\n console.warn(\"Use of null ID in JSONRPC 2.0 is discouraged.\");\n return true;\n } else {\n return false;\n }\n default:\n return false;\n }\n}\n","import { EventEmitter } from 'eventemitter3';\n\nimport { MetapageEvents } from './events.js';\nimport { JsonRpcMethodsFromParent } from './jsonrpc.js';\nimport { MetapageDefinitionV2 } from './v2/index.js';\nimport { MetapageVersionCurrent } from './versions.js';\n\nexport enum MetapageHashParams {\n mp_debug = \"mp_debug\",\n}\n\nexport const isIframe = (): boolean => {\n //http://stackoverflow.com/questions/326069/how-to-identify-if-a-webpage-is-being-loaded-inside-an-iframe-or-directly-into-t\n try {\n return window !== window.top;\n } catch (ignored) {\n return false;\n }\n};\n\nexport const INITIAL_NULL_METAPAGE_DEFINITION: MetapageDefinitionV2 = {\n version: MetapageVersionCurrent,\n metaframes: {},\n};\n\nexport class MetapageShared extends EventEmitter<\n MetapageEvents | JsonRpcMethodsFromParent\n> {\n // Easier to ensure this value is never null|undefined\n _definition: MetapageDefinitionV2 = INITIAL_NULL_METAPAGE_DEFINITION;\n\n constructor() {\n super();\n this.getDefinition = this.getDefinition.bind(this);\n }\n\n public error(err: any) {\n throw \"Subclass should implement\";\n }\n public getDefinition(): MetapageDefinitionV2 {\n return this._definition;\n }\n}\n","import stringify from 'fast-json-stable-stringify';\nimport { create } from 'mutative';\nimport { MetapageHashParams } from './Shared.js';\nimport {\n MetaframeId,\n MetapageId,\n} from './core.js';\nimport {\n MetaframeInputMap,\n} from './v0_4/index.js';\nimport { MetapageDefinitionV2 } from './v2/metapage.js';\n/**\n * Merges new values into the a new object.\n * Does NOT check if there are actually new keys.\n * Does NOT check values against each other. This means you\n * can keep sending the same value, and the message will\n * be passed in.\n * Returns the original map if nothing modified.\n */\nexport const merge = (\n current: MetaframeInputMap,\n newInputs: MetaframeInputMap\n): MetaframeInputMap => {\n if (!newInputs) {\n return current;\n }\n return create<MetaframeInputMap>(current, (draft: MetaframeInputMap) => {\n Object.keys(newInputs).forEach((pipeId: string) => {\n // undefined means remove the key\n // null means keep the key, but set to null\n if (newInputs[pipeId] === undefined) {\n delete draft[pipeId];\n } else {\n draft[pipeId] = newInputs[pipeId];\n }\n });\n });\n};\n\nexport const getUrlParam = (key: MetapageHashParams): string | null => {\n if (!window.location.search) {\n return null;\n }\n return new URLSearchParams(window.location.search).get(key);\n};\n\nexport const getUrlParamDebug = (): boolean => {\n return new URLSearchParams(window.location.search).has(\n MetapageHashParams.mp_debug\n );\n};\n\nexport const isDebugFromUrlsParams = (): boolean => {\n const param = new URLSearchParams(window.location.search).get(\n MetapageHashParams.mp_debug\n );\n return param === \"true\" || param === \"1\";\n};\n\nexport const generateMetaframeId = (length: number = 8): MetaframeId => {\n return generateId(length);\n};\n\nexport const generateMetapageId = (length: number = 8): MetapageId => {\n return generateId(length);\n};\n\nexport const generateNonce = (length: number = 8): string => {\n return generateId(length);\n};\n\nconst LETTERS = \"abcdefghijklmnopqrstuvwxyz0123456789\";\nexport const generateId = (length: number = 8): string => {\n var result = \"\";\n var charactersLength = LETTERS.length;\n for (var i = 0; i < length; i++) {\n result += LETTERS.charAt(Math.floor(Math.random() * charactersLength));\n }\n return result;\n};\n\nexport const log = (o: any, color?: string, backgroundColor?: string) => {\n color = color ? color : \"000\";\n if (color && color.trim() == \"\") {\n color = undefined;\n }\n let s: string;\n if (typeof o === \"string\") {\n s = o as string;\n } else if (typeof o === \"number\") {\n s = o + \"\";\n } else {\n s = JSON.stringify(o, null, \" \");\n }\n\n if (color && color.trim() != \"\") {\n var cssstring = `color: #${color}`;\n if (backgroundColor) {\n cssstring = `${cssstring}; background: #${backgroundColor}`;\n }\n s = `%c${s}`;\n window.console.log(s, cssstring);\n } else {\n window.console.log(s);\n }\n};\n\nexport const stringToRgb = (str: string): string => {\n return intToRGB(hashCode(str));\n};\n\nexport const hashCode = (str: string): number => {\n // java string#hashCode\n var hash = 0;\n for (let i = 0; i < str.length; i++) {\n hash = str.charCodeAt(i) + ((hash << 5) - hash);\n }\n return hash;\n};\n\nexport const intToRGB = (i: number): string => {\n var c = (i & 0x00ffffff).toString(16).toUpperCase();\n return \"00000\".substring(0, 6 - c.length) + c;\n};\n\nexport const isPageLoaded = (): boolean => {\n return (\n document.readyState == \"complete\" || document.readyState == \"interactive\"\n );\n // https://stackoverflow.com/questions/13364613/how-to-know-if-window-load-event-was-fired-already/28093606\n // // TODO ugh casting here but I can't seem to get the right type with the loadEventEnd\n // return window.performance.getEntriesByType(\"navigation\").every((e) => { return (e as PerformanceNavigationTiming).loadEventEnd > 0 });\n};\n\nexport const pageLoaded = async (): Promise<void> => {\n if (isPageLoaded()) {\n return Promise.resolve();\n }\n return new Promise((resolve) => {\n if (isPageLoaded()) {\n resolve();\n return;\n }\n let loaded = false;\n window.addEventListener(\"load\", () => {\n if (loaded) {\n return;\n }\n loaded = true;\n resolve();\n });\n // tiny chance of missing the document.readyState === \"loaded\"\n const timer = setTimeout(() => {\n if (!loaded && isPageLoaded()) {\n loaded = true;\n resolve();\n }\n }, 200);\n });\n};\n\nexport const metapageAllSha256Hash = async (metapage: MetapageDefinitionV2) => {\n const metapageStr = stringify(metapage);\n return await sha256ToBase64(metapageStr);\n}\n\nexport const metapageOnlyEssentailSha256Hash = async (metapage: Pick<MetapageDefinitionV2, \"metaframes\" | \"version\">) => {\n const metapageStr = stringify({\n version: metapage.version,\n metaframes: metapage.metaframes,\n });\n return await sha256ToBase64(metapageStr);\n}\n\nasync function sha256ToBase64(str: string) {\n const encoder = new TextEncoder();\n const data = encoder.encode(str);\n const hash = await crypto.subtle.digest('SHA-256', data);\n return btoa(String.fromCharCode(...new Uint8Array(hash)));\n}\n","import {\n EventEmitter,\n ListenerFn,\n} from 'eventemitter3';\nimport { \n setHashParamInWindow,\n getHashParamFromWindow,\n setHashParamValueBooleanInWindow,\n getHashParamValueBooleanFromWindow,\n setHashParamValueJsonInWindow,\n getHashParamValueJsonFromWindow,\n setHashParamValueBase64EncodedInWindow,\n getHashParamValueBase64DecodedFromWindow,\n setHashParamValueFloatInWindow,\n getHashParamValueFloatFromWindow,\n setHashParamValueIntInWindow,\n getHashParamValueIntFromWindow,\n} from '@metapages/hash-query';\nimport { VERSION_METAFRAME } from './Constants';\nimport {\n deserializeInputs,\n serializeInputs,\n} from './data';\nimport {\n isDebugFromUrlsParams,\n log as MetapageToolsLog,\n merge,\n pageLoaded,\n stringToRgb,\n} from './MetapageTools';\nimport { isIframe } from './Shared';\nimport {\n MetaframeInputMap,\n} from './v0_4';\nimport {\n MetaframeId,\n MetaframePipeId,\n MetapageId,\n} from './core';\nimport { MetapageEventUrlHashUpdate } from './events';\nimport { JsonRpcMethodsFromChild, JsonRpcMethodsFromParent, MinimumClientMessage, SetupIframeServerResponseData } from './jsonrpc';\nimport { VersionsMetapage } from './versions';\n\n// TODO combine/unify MetaframeEvents and MetaframeLoadingState\nexport enum MetaframeLoadingState {\n WaitingForPageLoad = \"WaitingForPageLoad\",\n SentSetupIframeClientRequest = \"SentSetupIframeClientRequest\",\n Ready = \"Ready\",\n}\n\nexport enum MetaframeEvents {\n Connected = \"connected\",\n Error = \"error\",\n Input = \"input\",\n Inputs = \"inputs\",\n Message = \"message\",\n}\n\nexport type MetaframeOptions = {\n disableHashChangeEvent?: boolean;\n};\n\nexport class Metaframe extends EventEmitter<\n MetaframeEvents | JsonRpcMethodsFromChild\n> {\n public static readonly version = VERSION_METAFRAME;\n\n public static readonly ERROR = MetaframeEvents.Error;\n public static readonly CONNECTED = MetaframeEvents.Connected;\n public static readonly INPUT = MetaframeEvents.Input;\n public static readonly INPUTS = MetaframeEvents.Inputs;\n public static readonly MESSAGE = MetaframeEvents.Message;\n\n public static deserializeInputs = deserializeInputs;\n public static serializeInputs = serializeInputs;\n\n _inputPipeValues: MetaframeInputMap = {};\n _outputPipeValues: MetaframeInputMap = {};\n _parentId: MetapageId | undefined;\n _parentVersion: VersionsMetapage | undefined;\n _isIframe: boolean;\n _state: MetaframeLoadingState = MetaframeLoadingState.WaitingForPageLoad;\n _messageSendCount = 0;\n\n debug: boolean = isDebugFromUrlsParams();\n color: string | undefined;\n /**\n * If this is false, Files and Blobs will not be automatically serialized and deserialized\n * This is useful to avoid the overhead of serialization/deserialization if you know you won't be using it\n */\n isInputOutputBlobSerialization: boolean = true;\n\n /**\n * This is the (locally) unique id that the parent metapage\n * assigns to the metaframe via iframe.name which we get here as window.name\n */\n id: string = window.name;\n\n constructor(options?: MetaframeOptions) {\n super();\n this.debug = isDebugFromUrlsParams();\n this._isIframe = isIframe();\n\n this.addListener = this.addListener.bind(this);\n this.dispose = this.dispose.bind(this);\n this.error = this.error.bind(this);\n this.getInput = this.getInput.bind(this);\n this.getInputs = this.getInputs.bind(this);\n this.log = this.log.bind(this);\n this.logInternal = this.logInternal.bind(this);\n this.onInput = this.onInput.bind(this);\n this.onInputs = this.onInputs.bind(this);\n this.onMessage = this.onMessage.bind(this);\n this.sendRpc = this.sendRpc.bind(this);\n this.setInput = this.setInput.bind(this);\n this.setInputs = this.setInputs.bind(this);\n this.setInternalInputsAndNotify =\n this.setInternalInputsAndNotify.bind(this);\n this.setOutput = this.setOutput.bind(this);\n this.setOutputs = this.setOutputs.bind(this);\n this.warn = this.warn.bind(this);\n this._resolveSetupIframeServerResponse =\n this._resolveSetupIframeServerResponse.bind(this);\n this.addListenerReturnDisposer = this.addListenerReturnDisposer.bind(this);\n this.connected = this.connected.bind(this);\n this.isConnected = this.isConnected.bind(this);\n this.disableNotifyOnHashUrlChange =\n this.disableNotifyOnHashUrlChange.bind(this);\n this._onHashUrlChange = this._onHashUrlChange.bind(this);\n\n this.setParameter = this.setParameter.bind(this);\n this.setParameterBoolean = this.setParameterBoolean.bind(this);\n this.setParameterJson = this.setParameterJson.bind(this);\n this.setParameterBase64 = this.setParameterBase64.bind(this);\n this.setParameterFloat = this.setParameterFloat.bind(this);\n this.setParameterInt = this.setParameterInt.bind(this);\n this.getParameter = this.getParameter.bind(this);\n this.getParameterBoolean = this.getParameterBoolean.bind(this);\n this.getParameterJson = this.getParameterJson.bind(this);\n this.getParameterBase64 = this.getParameterBase64.bind(this);\n this.getParameterFloat = this.getParameterFloat.bind(this);\n this.getParameterInt = this.getParameterInt.bind(this);\n this.deleteParameter = this.deleteParameter.bind(this);\n\n\n if (!this._isIframe) {\n //Don't add any of the machinery, it only works if we're iframes.\n //This will never return\n // this.ready = new Promise((_) => {});\n this.log(\"Not an iframe, metaframe code disabled\");\n return;\n }\n\n const thisRef = this;\n // Do no listen or send messages until the page is loaded\n // This iframe is not created UNTIL the parent page is loaded and listening to messages\n pageLoaded().then(() => {\n this.log(\"pageLoaded\");\n window.addEventListener(\"message\", this.onMessage);\n // Now that we're listening, request to the parent to register us so we can talk\n thisRef.sendRpc(JsonRpcMethodsFromChild.SetupIframeClientRequest, {\n version: Metaframe.version,\n });\n thisRef._state = MetaframeLoadingState.SentSetupIframeClientRequest;\n });\n\n if (!(options && options.disableHashChangeEvent)) {\n window.addEventListener(\"hashchange\", this._onHashUrlChange);\n }\n }\n\n _resolveSetupIframeServerResponse(params: SetupIframeServerResponseData) {\n if (this._state === MetaframeLoadingState.WaitingForPageLoad) {\n throw \"Got message but page has not finished loading, we should never get in this state\";\n }\n\n (async () => {\n\n if (!this._parentId) {\n this._parentVersion = params.version;\n this.color = stringToRgb(this.id);\n this._parentId = params.parentId;\n this.log(\n `metapage[${this._parentId}](v${\n this._parentVersion ? this._parentVersion : \"unknown\"\n }) registered`\n );\n\n\n if (params.state && params.state.inputs) {\n if (this.isInputOutputBlobSerialization) {\n this._inputPipeValues = await deserializeInputs(params.state.inputs);\n } else {\n this._inputPipeValues = params.state.inputs;\n }\n }\n\n // this._inputPipeValues =\n // params.state && params.state.inputs\n // ? this.isInputOutputBlobSerialization\n // ? deserializeInputs(params.state.inputs)\n // : params.state.inputs\n // : this._inputPipeValues;\n\n // Tell the parent we have registered.\n this._state = MetaframeLoadingState.Ready;\n // TODO why do we need Metaframe.version here? It was sent in the initial SetupIframeClientRequest\n this.sendRpc(JsonRpcMethodsFromChild.SetupIframeServerResponseAck, {\n version: Metaframe.version,\n });\n\n //Send notifications of initial inputs (if non-null)\n //so you don't have to listen to the ready event if you don't want to\n if (\n this._inputPipeValues &&\n Object.keys(this._inputPipeValues).length > 0\n ) {\n this.emit(MetaframeEvents.Inputs, this._inputPipeValues);\n if (this.listenerCount(MetaframeEvents.Input) > 0) {\n Object.keys(this._inputPipeValues).forEach((pipeId) =>\n this.emit(\n MetaframeEvents.Input,\n pipeId,\n this._inputPipeValues[pipeId]\n )\n );\n }\n }\n\n // this.emit(MetaframeEvents.Inputs, this._inputPipeValues);\n\n //Resolve AFTER sending inputs. This way consumers can either:\n //1) Just listen to inputs updates. The first will be when the metaframe is ready\n //2) Listen to the ready event, get the inputs if desired, and listen to subsequent\n // inputs updates. You may not wish to respond to the first updates but you might\n // want to know when the metaframe is ready\n //*** Does this distinction make sense?\n this.emit(MetaframeEvents.Connected);\n\n // Send the initial outputs to the parent, we have been accumulating them\n this.sendRpc(JsonRpcMethodsFromChild.OutputsUpdate, this._outputPipeValues);\n\n } else {\n this.log(\n \"Got JsonRpcMethods.SetupIframeServerResponse but already resolved\"\n );\n }\n })();\n }\n\n isConnected(): boolean {\n return this._state === MetaframeLoadingState.Ready;\n }\n\n async connected(): Promise<void> {\n return new Promise((resolve, _) => {\n if (this._state === MetaframeLoadingState.Ready) {\n resolve();\n return;\n }\n let disposer: () => void;\n disposer = this.addListenerReturnDisposer(\n MetaframeEvents.Connected,\n () => {\n resolve();\n disposer();\n }\n );\n });\n }\n\n addListenerReturnDisposer(\n event: MetaframeEvents | JsonRpcMethodsFromChild,\n listener: ListenerFn<any[]>\n ): () => void {\n super.addListener(event, listener);\n const disposer = () => {\n super.removeListener(event, listener);\n };\n return disposer;\n }\n\n public log(o: any, color?: string, backgroundColor?: string) {\n if (!this.debug) {\n return;\n }\n this.logInternal(o, color ? color : this.color);\n }\n\n public warn(o: any) {\n if (!this.debug) {\n return;\n }\n this.logInternal(o, \"000\", this.color);\n }\n\n public error(err: any) {\n this.logInternal(err, this.color, \"f00\");\n }\n\n logInternal(o: any, color?: string, backgroundColor?: string) {\n let s: string;\n if (typeof o === \"string\") {\n s = o as string;\n } else if (typeof o === \"number\") {\n s = o + \"\";\n } else {\n s = JSON.stringify(o);\n }\n\n color = color ? color + \"\" : color;\n\n s = (this.id ? `Metaframe[${this.id}] ` : \"\") + `${s}`;\n MetapageToolsLog(s, color, backgroundColor);\n }\n\n public dispose() {\n super.removeAllListeners();\n window.removeEventListener(\"message\", this.onMessage);\n this.disableNotifyOnHashUrlChange();\n // @ts-ignore\n this._inputPipeValues = undefined;\n // @ts-ignore\n this._outputPipeValues = undefined;\n }\n\n public addListener(\n event: MetaframeEvents | JsonRpcMethodsFromChild,\n listener: ListenerFn<any[]>\n ) {\n super.addListener(event, listener);\n\n //If it is an input or output, set the current input/output values when\n //attaching a listener on the next tick to ensure that the listener\n //will always get a value if it exists\n if (event === MetaframeEvents.Inputs) {\n window.setTimeout(() => {\n if (this._inputPipeValues) {\n listener(this._inputPipeValues);\n }\n }, 0);\n }\n return this;\n }\n\n public onInput(pipeId: MetaframePipeId, listener: any): () => void {\n return this.addListenerReturnDisposer(\n MetaframeEvents.Input,\n (pipe: MetaframePipeId, value: any) => {\n if (pipeId === pipe) {\n listener(value);\n }\n }\n );\n }\n\n public onInputs(listener: (m: MetaframeInputMap) => void): () => void {\n const disposer = this.addListenerReturnDisposer(\n MetaframeEvents.Inputs,\n listener\n );\n return disposer;\n }\n\n /**\n * This is a particular use case: metapage inputs are saved outside\n * the iframe, so when this iframe is restarted in the same metapage\n * it will start with this value. So in a way, it can be used for\n * state storage, by the metaframe itself.\n */\n public setInput(pipeId: MetaframePipeId, blob: any) {\n var inputs: MetaframeInputMap = {};\n inputs[pipeId] = blob;\n this.setInputs(inputs);\n }\n\n /**\n * This does NOT directly update internal inputs. It tells\n * the metapage parent, which then updates back. So if there\n * is no metapage parent, this will do nothing.\n *\n * @param inputs\n */\n public async setInputs(inputs: MetaframeInputMap) {\n if (this.isInputOutputBlobSerialization) {\n inputs = await deserializeInputs(inputs);\n }\n this.sendRpc(JsonRpcMethodsFromChild.InputsUpdate, inputs);\n }\n\n async setInternalInputsAndNotify(inputs: MetaframeInputMap) {\n // this is where we deserialize the inputs\n if (this.isInputOutputBlobSerialization) {\n inputs = await deserializeInputs(inputs);\n }\n\n const originalInputs = inputs;\n this._inputPipeValues = merge(this._inputPipeValues, inputs);\n if (this._inputPipeValues === originalInputs) {\n return;\n }\n\n Object.keys(inputs).forEach((pipeId) => {\n try {\n // if we don't actually need this event, we should remove it\n this.emit(MetaframeEvents.Input, pipeId, inputs[pipeId])\n } catch(err) {\n console.error(`Error emitting input ${pipeId}: ${err}`)\n this.emit(MetaframeEvents.Error, `Error emitting input ${pipeId}: ${err}`);\n }\n });\n try {\n this.emit(MetaframeEvents.Inputs, inputs);\n } catch(err) {\n console.error(`Error emitting inputs: ${err}`)\n this.emit(MetaframeEvents.Error, `Error emitting inputs: ${err}`);\n }\n }\n\n public getInput(pipeId: MetaframePipeId): any {\n console.assert(!!pipeId);\n return this._inputPipeValues[pipeId];\n }\n\n public getInputs(): MetaframeInputMap {\n return this._inputPipeValues;\n }\n\n /**\n * What does setting this to null mean?\n * @param pipeId :MetaframePipeId [description]\n * @param updateBlob :any [description]\n */\n public setOutput(pipeId: MetaframePipeId, updateBlob: any): void {\n console.assert(!!pipeId);\n\n var outputs: MetaframeInputMap = {};\n outputs[pipeId] = updateBlob;\n\n this.setOutputs(outputs);\n }\n\n public async setOutputs(outputs: MetaframeInputMap): Promise<void> {\n if (this.isInputOutputBlobSerialization) {\n outputs = await serializeInputs(outputs);\n }\n\n const originalOutputs = outputs;\n this._outputPipeValues = merge(this._outputPipeValues, outputs);\n if (this._outputPipeValues === originalOutputs) {\n return;\n }\n\n // If we are not ready/connected, outputs will be sent when connected\n if (this._state === MetaframeLoadingState.Ready) {\n this.sendRpc(JsonRpcMethodsFromChild.OutputsUpdate, outputs);\n }\n }\n\n /**\n * If the hash params of our URL changes, e.g. from updating because\n * our state changed, then notify the parent metapage so that the\n * parent metapage can save the state\n */\n public disableNotifyOnHashUrlChange(): void {\n window.removeEventListener(\"hashchange\", this._onHashUrlChange);\n }\n\n // public getHashParam(key:string): string {\n // window.removeEventListener(\"hashchange\", this._onHashUrlChange);\n // }\n\n\n\n /** Tell the parent metapage our hash params changed */\n _onHashUrlChange(_: any): void {\n const payload: MetapageEventUrlHashUpdate = {\n hash: window.location.hash,\n metaframe: this.id as MetaframeId,\n };\n this.sendRpc(JsonRpcMethodsFromChild.HashParamsUpdate, payload);\n }\n\n sendRpc(method: JsonRpcMethodsFromChild, params: any) {\n if (this._isIframe) {\n const message: MinimumClientMessage<any> = {\n jsonrpc: \"2.0\",\n id: ++this._messageSendCount, // just increment the counter for the id\n method: method,\n params: params,\n iframeId: this.id,\n parentId: this._parentId, // TODO this is likely not actually needed ? iframes cannot send to anyone but the parent? But the parent does not automatically know where a message comes from\n };\n if (window.parent) {\n window.parent.postMessage(message, \"*\");\n }\n } else {\n this.log(\n \"Cannot send JSON-RPC window message: there is no window.parent which means we are not an iframe\"\n );\n }\n }\n\n onMessage(e: MessageEvent) {\n if (typeof e.data === \"object\") {\n let jsonrpc: MinimumClientMessage<any> = e.data;\n if (jsonrpc.jsonrpc === \"2.0\") {\n //Make sure this is a jsonrpc object\n var method = jsonrpc.method as JsonRpcMethodsFromParent;\n if (\n !(\n method == JsonRpcMethodsFromParent.SetupIframeServerResponse ||\n (jsonrpc.parentId == this._parentId && jsonrpc.iframeId == this.id)\n )\n ) {\n this.log(\n `window.message: received message but jsonrpc.parentId=${jsonrpc.parentId} _parentId=${this._parentId} jsonrpc.iframeId=${jsonrpc.iframeId} id=${this.id}`\n );\n return;\n }\n\n switch (method) {\n case JsonRpcMethodsFromParent.SetupIframeServerResponse:\n this._resolveSetupIframeServerResponse(jsonrpc.params);\n break; //Handled elsewhere\n case JsonRpcMethodsFromParent.InputsUpdate:\n if (this._state !== MetaframeLoadingState.Ready) {\n throw \"Got InputsUpdate but metaframe is not MetaframeLoadingState.Ready\";\n }\n this.setInternalInputsAndNotify(jsonrpc.params.inputs);\n break;\n case JsonRpcMethodsFromParent.MessageAck:\n if (this.debug) this.log(`ACK: ${JSON.stringify(jsonrpc)}`);\n break;\n default:\n if (this.debug)\n this.log(\n `window.message: unknown JSON-RPC method: ${JSON.stringify(\n jsonrpc\n )}`\n );\n break;\n }\n\n if (this.listenerCount(MetaframeEvents.Message) > 0) {\n this.emit(MetaframeEvents.Message, jsonrpc);\n }\n }\n }\n }\n\n setParameter(key: string, value: any) {\n setHashParamInWindow(key, value);\n }\n\n getParameter(key: string) :string | undefined {\n return getHashParamFromWindow(key);\n }\n\n setParameterBoolean(key: string, value: boolean | undefined) {\n setHashParamValueBooleanInWindow(key, value);\n }\n\n getParameterBoolean(key: string) :boolean | undefined {\n return getHashParamValueBooleanFromWindow(key);\n }\n\n setParameterJson(key: string, value: any) {\n setHashParamValueJsonInWindow(key, value);\n }\n\n getParameterJson<T>(key: string) :T|undefined {\n return getHashParamValueJsonFromWindow<T>(key);\n }\n\n setParameterBase64(key: string, value: string | undefined) {\n setHashParamValueBase64EncodedInWindow(key, value);\n }\n\n getParameterBase64(key: string) :string | undefined {\n return getHashParamValueBase64DecodedFromWindow(key);\n }\n\n setParameterFloat(key: string, value: number | undefined) {\n setHashParamValueFloatInWindow(key, value);\n }\n\n getParameterFloat(key: string) :number | undefined {\n return getHashParamValueFloatFromWindow(key);\n }\n\n setParameterInt(key: string, value: number | undefined) {\n setHashParamValueIntInWindow(key, value);\n }\n\n getParameterInt(key: string) :number | undefined {\n return getHashParamValueIntFromWindow(key);\n }\n\n deleteParameter(key: string) {\n setHashParamInWindow(key, undefined);\n }\n}","import fetchRetryWrapper from \"fetch-retry\";\nimport { convertMetapageDefinitionToVersion } from \"./conversions-metapage\";\nimport { MetaframeDefinitionV1, MetapageDefinitionV1 } from \"./v1\";\nimport { VersionsMetaframe, VersionsMetapage } from \"./versions\";\nimport { MetaframeDefinitionV4, MetapageDefinitionV3 } from \"./v0_4\";\nimport { convertMetaframeDefinitionToVersion } from \"./conversions-metaframe\";\nimport { MetaframeDefinitionV2, MetapageDefinitionV2 } from \"./v2\";\n\nconst fetchRetry = fetchRetryWrapper(fetch);\n\nexport const getMetapageDefinitionFromUrl = async (url: string, version?: VersionsMetapage): Promise<MetapageDefinitionV2|MetapageDefinitionV1|MetapageDefinitionV3> => {\n const metapageUrl = new URL(url);\n metapageUrl.pathname = metapageUrl.pathname + (metapageUrl.pathname.endsWith(\"/\") ? \"metapage.json\" : \"/metapage.json\");\n const response = await fetchRetry(metapageUrl.href, {\n redirect: \"follow\",\n retries: 3,\n retryDelay: 1000,\n });\n const definition = await response.json();\n const convertedDefinition = await convertMetapageDefinitionToVersion(definition, version || \"1\");\n return convertedDefinition;\n};\n\nexport const getMetaframeDefinitionFromUrl = async (url: string, version?: VersionsMetaframe): Promise<MetaframeDefinitionV2|MetaframeDefinitionV1|MetaframeDefinitionV4> => {\n const metaframeUrl = new URL(url);\n metaframeUrl.pathname = metaframeUrl.pathname + (metaframeUrl.pathname.endsWith(\"/\") ? \"metaframe.json\" : \"/metaframe.json\");\n const response = await fetchRetry(metaframeUrl.href, {\n redirect: \"follow\",\n retries: 3,\n retryDelay: 1000,\n });\n const definition = await response.json();\n const convertedDefinition = await convertMetaframeDefinitionToVersion(definition, version || \"1\");\n return convertedDefinition;\n};\n\nexport const isEmptyMetaframeDefinition = (definition?: MetaframeDefinitionV1|MetaframeDefinitionV2|MetaframeDefinitionV4): boolean => {\n if (!definition) {\n return true;\n }\n if (definition?.inputs && Object.keys(definition.inputs).length > 0) {\n return false;\n }\n if (definition?.outputs && Object.keys(definition.outputs).length > 0) {\n return false;\n }\n if (definition?.allow) {\n return false;\n }\n if (definition?.metadata && Object.keys(definition.metadata).length > 0) {\n return false;\n }\n return true;\n};\n","import { EventEmitter, ListenerFn } from \"eventemitter3\";\n\nimport { VERSION_METAPAGE } from \"./Constants\";\nimport { serializeInputs } from \"./data\";\nimport { JsonRpcRequest } from \"./jsonrpc2\";\nimport {\n log as MetapageToolsLog,\n merge,\n pageLoaded,\n stringToRgb,\n} from \"./MetapageTools\";\nimport { MetapageHashParams, MetapageShared } from \"./Shared\";\nimport { MetaframeDefinitionV2 } from \"./v2\";\nimport { MetaframeInputMap, MetapageInstanceInputs } from \"./v0_4\";\nimport { MetaframeId, MetaframePipeId, MetapageId } from \"./core\";\nimport { convertMetaframeJsonToCurrentVersion } from \"./conversions-metaframe\";\nimport { MetapageEvents } from \"./events\";\nimport {\n ClientMessageRecievedAck,\n JsonRpcMethodsFromParent,\n MinimumClientMessage,\n SetupIframeServerResponseData,\n} from \"./jsonrpc\";\nimport { VersionsMetaframe, VersionsMetapage } from \"./versions\";\nimport { getHashParamValueJsonFromUrl } from \"@metapages/hash-query\";\nimport { getMetaframeDefinitionFromUrl } from \"./util\";\n\n/**\n * This class runs in the parent metapage, and connects the communication pipes\n * from the child metaframe iframe to the parent metapage.\n *\n * Initialization sequence:\n * 1. the child iframe object waits until its page loads\n * 2. the child iframe object sends SetupIframeClientRequest\n * - this marks the iframe as ready\n */\nexport class MetapageIFrameRpcClient extends EventEmitter<\n JsonRpcMethodsFromParent | MetapageEvents\n> {\n iframe: Promise<HTMLIFrameElement>;\n _iframe: HTMLIFrameElement;\n id: MetaframeId;\n version: VersionsMetaframe | undefined;\n // Used for securing postMessage\n url: string;\n _color: string;\n _consoleBackgroundColor: string;\n inputs: MetaframeInputMap = {};\n outputs: MetaframeInputMap = {};\n _disposables: (() => void)[] = [];\n _rpcListeners: ((r: JsonRpcRequest<any>) => void)[] = [];\n _loaded: boolean = false;\n _onLoaded: (() => void)[] = [];\n _parentId: MetapageId;\n _debug: boolean;\n _sendInputsAfterRegistration: boolean = false;\n _definition: MetaframeDefinitionV2 | undefined;\n\n _metapage: MetapageShared;\n\n constructor(\n metapage: MetapageShared,\n url: string,\n iframeId: MetaframeId,\n parentId: MetapageId,\n consoleBackgroundColor: string,\n debug: boolean = false\n ) {\n super();\n // Url sanitation\n // Urls can be relative paths, if so, turn them into absolute URLs\n // Also local development often skips the \"http:\" part, so add that\n // on so the origin is valid\n if (!url.startsWith(\"http\")) {\n while (url.startsWith(\"/\")) {\n url = url.substring(1);\n }\n url =\n window.location.protocol +\n \"//\" +\n window.location.hostname +\n (window.location.port && window.location.port != \"\"\n ? \":\" + window.location.port\n : \"\") +\n \"/\" +\n url;\n }\n this.url = url;\n this._metapage = metapage;\n this._debug = debug;\n // Add the custom URL params\n if (debug) {\n var urlBlob = new URL(this.url);\n urlBlob.searchParams.set(MetapageHashParams.mp_debug, \"true\");\n this.url = urlBlob.href;\n }\n\n this.id = iframeId;\n this._parentId = parentId;\n this._color = stringToRgb(this.id);\n this._consoleBackgroundColor = consoleBackgroundColor;\n\n // Create but do not attach to the dom until the src attribute is set https://github.com/metapages/metapage/issues/91\n this._iframe = document.createElement(\"iframe\");\n this._iframe.name = this.id;\n const selfThis = this;\n this.iframe = new Promise((resolve) => {\n // wait until the metapage page is loaded, otherwise\n // communication errors will likely occur\n pageLoaded().then(async () => {\n // parent page loaded, set the iframe src to start loading\n // get the definition in case we need to set allow permissions\n if (selfThis._iframe) {\n // check because possibly already disposed\n\n // iframe permissions (the \"allow\" attribute)\n // https://developer.mozilla.org/en-US/docs/Web/API/HTMLIFrameElement/allow\n // If there is an \"allow\" field in the frame definition in the metapage use that first\n if (this._metapage?._definition?.metaframes?.[this.id]?.allow) {\n selfThis._iframe.allow =\n this._metapage._definition.metaframes[this.id].allow!;\n } else {\n // Otherwise use whatever is in the metaframe.json\n const metaframeDef = await selfThis.getDefinition();\n if (!selfThis._iframe) {\n // possibly already disposed\n return;\n }\n if (metaframeDef && metaframeDef.allow) {\n selfThis._iframe.allow = metaframeDef.allow;\n }\n }\n // set the src after the allow attribute is set\n selfThis._iframe.src = this.url;\n resolve(selfThis._iframe);\n }\n });\n });\n\n this.ack = this.ack.bind(this);\n this.dispose = this.dispose.bind(this);\n this.getDefinition = this.getDefinition.bind(this);\n this.getDefinitionUrl = this.getDefinitionUrl.bind(this);\n this.log = this.log.bind(this);\n this.logInternal = this.logInternal.bind(this);\n this.onInput = this.onInput.bind(this);\n this.onInputs = this.onInputs.bind(this);\n this.onOutput = this.onOutput.bind(this);\n this.onOutputs = this.onOutputs.bind(this);\n this.register = this.register.bind(this);\n this.registered = this.registered.bind(this);\n this.sendInputs = this.sendInputs.bind(this);\n this.sendOrBufferPostMessage = this.sendOrBufferPostMessage.bind(this);\n this.sendRpc = this.sendRpc.bind(this);\n this.sendRpcInternal = this.sendRpcInternal.bind(this);\n this.setInput = this.setInput.bind(this);\n this.setInputs = this.setInputs.bind(this);\n this.setMetapage = this.setMetapage.bind(this);\n this.setOutput = this.setOutput.bind(this);\n this.setOutputs = this.setOutputs.bind(this);\n this.addListenerReturnDisposer = this.addListenerReturnDisposer.bind(this);\n this.isDisposed = this.isDisposed.bind(this);\n }\n\n addListenerReturnDisposer(\n event: JsonRpcMethodsFromParent | MetapageEvents,\n listener: ListenerFn<any[]>\n ): () => void {\n super.addListener(event, listener);\n const disposer = () => {\n super.removeListener(event, listener);\n };\n return disposer;\n }\n\n public setMetapage(metapage: MetapageShared): MetapageIFrameRpcClient {\n this._metapage = metapage;\n return this;\n }\n\n public getDefinitionUrl(): string {\n var url = new URL(this.url);\n url.pathname =\n url.pathname +\n (url.pathname.endsWith(\"/\") ? \"metaframe.json\" : \"/metaframe.json\");\n return url.href;\n }\n\n /**\n * Cached in memory. Fetches <metaframe url>/metaframe.json\n * metaframe.json defines inputs/outputs and other metadata\n * (how to operate and connect the metaframe)\n * It is optional in that the metaframe will still work without it\n * but advanced features e.g. allow permissions won't work and\n * anything relying on metadata.\n */\n public async getDefinition(): Promise<MetaframeDefinitionV2 | undefined> {\n if (this._definition) {\n return this._definition;\n }\n\n try {\n const definitionFromHashParams: MetaframeDefinitionV2 | undefined =\n getHashParamValueJsonFromUrl(this.url, \"definition\");\n if (definitionFromHashParams) {\n const metaframeDefCurrent = await convertMetaframeJsonToCurrentVersion(\n definitionFromHashParams\n );\n this._definition = metaframeDefCurrent;\n return this._definition;\n }\n } catch (err) {\n this.emit(\n MetapageEvents.Warning,\n `Failed to convert metaframe definition from hash params. Error: ${\n (err as Error)?.message ? (err as Error)?.message : \"unknown error\"\n }`\n );\n return;\n }\n\n // TODO: this should be retried?\n var url = this.getDefinitionUrl();\n try {\n const metaframeDef = await getMetaframeDefinitionFromUrl(this.url);\n if (metaframeDef) {\n this._definition = metaframeDef;\n return this._definition;\n }\n } catch (err: unknown) {\n // hmm silent on failures to load the metaframe.json?\n this.emit(\n MetapageEvents.Warning,\n `Failed to fetch or convert: ${url}\\nError: ${\n (err as Error)?.message ? (err as Error)?.message : err?.toString()\n }`\n );\n }\n }\n\n public setInput(name: MetaframePipeId, inputBlob: any) {\n console.assert(!!name);\n var inputs: MetaframeInputMap = {};\n inputs[name] = inputBlob;\n this.setInputs(inputs);\n }\n\n /**\n * Sends the updated inputs to the iframe\n */\n _cachedEventInputsUpdate: {\n iframeId: string | undefined;\n inputs: MetaframeInputMap | undefined;\n } = {\n iframeId: undefined,\n inputs: undefined,\n };\n public setInputs(maybeNewInputs: MetaframeInputMap): MetapageIFrameRpcClient {\n this.log({ m: \"MetapageIFrameRpcClient\", inputs: maybeNewInputs });\n\n const originalInputs = maybeNewInputs;\n this.inputs = merge(this.inputs, maybeNewInputs);\n if (this.inputs === originalInputs) {\n return this;\n }\n\n if (!this._loaded) {\n this._sendInputsAfterRegistration = true;\n }\n // Only send the new inputs to the actual metaframe iframe\n // if it's not registered, don't worry, inputs are merged,\n // and when the metaframe is registered, current inputs will\n // be sent\n if (this._iframe.parentNode && this._loaded) {\n this.sendInputs(maybeNewInputs);\n }\n\n // Notify\n this.emit(MetapageEvents.Inputs, this.inputs);\n if (this._metapage.listenerCount(MetapageEvents.Inputs) > 0) {\n var inputUpdate: MetapageInstanceInputs = {};\n inputUpdate[this.id] = maybeNewInputs;\n this._metapage.emit(MetapageEvents.Inputs, inputUpdate);\n }\n\n return this;\n }\n\n public setOutput(pipeId: MetaframePipeId, updateBlob: any) {\n console.assert(!!pipeId);\n var outputs: MetaframeInputMap = {};\n outputs[pipeId] = updateBlob;\n this.setOutputs(outputs);\n }\n\n _cachedEventOutputsUpdate = {\n iframeId: null,\n inputs: null,\n };\n public setOutputs(maybeNewOutputs: MetaframeInputMap) {\n const originalOutputs = maybeNewOutputs;\n this.outputs = merge(this.outputs, maybeNewOutputs);\n if (this.outputs === originalOutputs) {\n return this;\n }\n\n this.emit(MetapageEvents.Outputs, maybeNewOutputs);\n\n if (this._metapage.listenerCount(MetapageEvents.Outputs) > 0) {\n var outputsUpdate: MetapageInstanceInputs = {};\n outputsUpdate[this.id] = this.outputs;\n this._metapage.emit(MetapageEvents.Outputs, outputsUpdate);\n }\n }\n\n public onInputs(f: (m: MetaframeInputMap) => void): () => void {\n return this.addListenerReturnDisposer(MetapageEvents.Inputs, f);\n }\n\n public onInput(pipeName: MetaframePipeId, f: (_: any) => void): () => void {\n var fWrap = function (inputs: MetaframeInputMap) {\n if (inputs.hasOwnProperty(pipeName)) {\n f(inputs[pipeName]);\n }\n };\n return this.addListenerReturnDisposer(MetapageEvents.Inputs, fWrap);\n }\n\n public onOutputs(f: (m: MetaframeInputMap) => void): () => void {\n return this.addListenerReturnDisposer(MetapageEvents.Outputs, f);\n }\n\n public onOutput(pipeName: MetaframePipeId, f: (_: any) => void): () => void {\n var fWrap = function (outputs: MetaframeInputMap) {\n if (outputs.hasOwnProperty(pipeName)) {\n f(outputs[pipeName]);\n }\n };\n return this.addListenerReturnDisposer(MetapageEvents.Outputs, fWrap);\n }\n\n public isDisposed() {\n return this.inputs === undefined;\n }\n\n public dispose() {\n super.removeAllListeners();\n while (this._disposables && this._disposables.length > 0) {\n const val = this._disposables.pop();\n if (val) {\n val();\n }\n }\n // @ts-ignore\n this._rpcListeners = undefined;\n // @ts-ignore\n this.inputs = undefined;\n // @ts-ignore\n this.outputs = undefined;\n // @ts-ignore\n if (this._iframe && this._iframe.parentNode) {\n this._iframe.parentNode.removeChild(this._iframe);\n }\n // @ts-ignore\n this._iframe = undefined;\n // @ts-ignore\n this._bufferMessages = undefined;\n if (this._bufferTimeout) {\n window.clearInterval(this._bufferTimeout);\n // @ts-ignore\n this._bufferTimeout = undefined;\n }\n // @ts-ignore\n this._metapage = undefined;\n }\n\n /**\n * Request that the parent metapage tell us what our id is.\n * The iframe might send this message more than once (it reloads for some reason)\n * so we can't gate this request if we think the metaframe\n * is already registered.\n */\n public register() {\n var response: SetupIframeServerResponseData = {\n iframeId: this.id,\n parentId: this._parentId,\n state: {\n inputs: this.inputs,\n },\n version: VERSION_METAPAGE as VersionsMetapage,\n };\n this.sendRpcInternal(\n JsonRpcMethodsFromParent.SetupIframeServerResponse,\n response\n );\n }\n\n public registered(version: VersionsMetaframe) {\n this.log({ m: \"MetapageIFrameRpcClient.registered\", inputs: this.inputs });\n if (this._loaded) {\n return;\n }\n if (!version) {\n throw \"Cannot register without a version\";\n }\n this.version = version;\n this._loaded = true;\n while (this._onLoaded && this._onLoaded.length > 0) {\n this._onLoaded.pop()!();\n }\n // You still need to set the inputs even though they\n // may have been set initially, because the inputs may\n // have been been updated before the metaframe internal\n // returned its server ack.\n if (this._sendInputsAfterRegistration) {\n this.sendInputs(this.inputs);\n }\n }\n\n async sendInputs(inputs: MetaframeInputMap) {\n if (!inputs) {\n return;\n }\n inputs = await serializeInputs(inputs);\n if (this.isDisposed()) {\n return;\n }\n this.sendRpc(JsonRpcMethodsFromParent.InputsUpdate, {\n inputs: inputs,\n parentId: this._parentId,\n });\n }\n\n public sendRpc(method: string, params: any) {\n if (this?._iframe?.parentNode && this._loaded) {\n this.sendRpcInternal(method, params);\n } else {\n this?._metapage?.error(\"sending rpc later\");\n const thing = this;\n this?._onLoaded.push(() => {\n thing.sendRpcInternal(method, params);\n });\n }\n }\n\n public ack(message: any) {\n if (this._debug) {\n this.log(\"⚒ ⚒ ⚒ sending ack from client to frame\");\n var payload: ClientMessageRecievedAck<any> = {\n message: message,\n };\n this.sendRpc(JsonRpcMethodsFromParent.MessageAck, payload);\n }\n }\n\n public log(o: any) {\n if (!this._debug) {\n return;\n }\n this.logInternal(o);\n }\n\n logInternal(o: any) {\n let s: string;\n if (typeof o === \"string\") {\n s = o as string;\n } else if (typeof o === \"string\") {\n s = o + \"\";\n } else {\n s = JSON.stringify(o);\n }\n MetapageToolsLog(\n `Metapage[${this._parentId}] Metaframe[${this.id}] ${s}`,\n this._color,\n this._consoleBackgroundColor\n );\n }\n\n sendRpcInternal(method: string, params: any) {\n const messageJSON: MinimumClientMessage<any> = {\n id: \"_\",\n iframeId: this.id,\n jsonrpc: \"2.0\",\n method: method,\n params: params,\n parentId: this._parentId,\n };\n if (this._iframe) {\n this.sendOrBufferPostMessage(messageJSON);\n } else {\n if (this._metapage) {\n this._metapage.error(\n `Cannot send to child iframe messageJSON=${JSON.stringify(\n messageJSON\n ).substring(0, 200)}`\n );\n } else {\n console.error(\n `Cannot send to child iframe messageJSON=${JSON.stringify(\n messageJSON\n ).substring(0, 200)}`\n );\n }\n }\n }\n\n _bufferMessages: any[] | undefined;\n _bufferTimeout: number | undefined;\n sendOrBufferPostMessage(message: any) {\n if (this._iframe && this._iframe.contentWindow) {\n this._iframe.contentWindow.postMessage(message, this.url);\n } else {\n if (!this._bufferMessages) {\n this._bufferMessages = [message];\n const thing = this;\n this._bufferTimeout = window.setInterval(function () {\n if (thing._iframe && thing._iframe.contentWindow) {\n thing._bufferMessages!.forEach((m) =>\n thing._iframe!.contentWindow!.postMessage(m, thing.url)\n );\n window.clearInterval(thing._bufferTimeout);\n thing._bufferTimeout = undefined;\n thing._bufferMessages = undefined;\n }\n }, 0);\n } else {\n this._bufferMessages.push(message);\n }\n }\n }\n}\n","import { ListenerFn } from 'eventemitter3';\nimport { create } from 'mutative';\nimport picomatch from 'picomatch-browser';\n\nimport { VERSION_METAPAGE } from './Constants';\nimport {\n convertMetapageDefinitionToCurrentVersion,\n getMatchingMetapageVersion,\n} from './conversions-metapage';\nimport {\n MetaframeId,\n MetaframePipeId,\n MetapageId,\n} from './core';\nimport {\n deserializeInputs,\n serializeInputs,\n} from './data';\nimport {\n MetapageEventDefinition,\n MetapageEvents,\n MetapageEventUrlHashUpdate,\n} from './events';\nimport {\n JsonRpcMethodsFromChild,\n MinimumClientMessage,\n SetupIframeClientAckData,\n} from './jsonrpc';\nimport { MetapageIFrameRpcClient } from './MetapageIFrameRpcClient';\nimport {\n generateMetapageId,\n isDebugFromUrlsParams,\n log as MetapageToolsLog,\n pageLoaded,\n} from './MetapageTools';\nimport {\n INITIAL_NULL_METAPAGE_DEFINITION,\n MetapageShared,\n} from './Shared';\nimport {\n MetaframeInputMap,\n MetaframeInstance,\n MetapageInstanceInputs,\n PipeInput,\n PipeUpdateBlob,\n} from './v0_4';\nimport {\n MetapageOptionsV1,\n} from './v1';\nimport {\n MetapageDefinitionV2,\n MetapageMetadataV2,\n} from './v2';\nimport { VersionsMetapage } from './versions';\n\ninterface MetapageStatePartial {\n inputs: MetapageInstanceInputs;\n outputs: MetapageInstanceInputs;\n}\n\nexport interface MetapageState {\n metaframes: MetapageStatePartial;\n}\n\nconst emptyState :MetapageState= create<MetapageState>({\n metaframes: {\n inputs: {},\n outputs: {},\n },\n}, draft => draft);\n\nexport const getLibraryVersionMatching = (\n version: string\n): VersionsMetapage => {\n return getMatchingMetapageVersion(version);\n};\n\nexport const matchPipe = (\n outputName: string,\n source?: string,\n): boolean => {\n // console.log(`❓❓ matchPipe: metapage.getState().metaframes=${outputName} source=${source} `);\n\n if ((!source || source === \"**\")) { // && (!target || target === \"*\")\n // console.log(`❓matchPipe 1: ✅`);\n return true;\n }\n\n if (outputName === source) {\n // console.log(`❓matchPipe 1.1: ✅`);\n return true;\n }\n\n if (picomatch.isMatch(outputName, source)) {\n // console.log(`❓matchPipe 2: ✅`);\n return true;\n }\n\n // if (!target || target === \"*\" || target.endsWith(\"/\")) {\n // console.log(`❓matchPipe 3: ✅`);\n // return true;\n // }\n\n // if (picomatch.isMatch(outputName, target)) {\n // console.log(`❓matchPipe 4: ✅`);\n // return true;\n // }\n\n // console.log(`❓matchPipe 5: ❌`);\n return false;\n};\n\ntype MetaframeInputTargetsFromOutput = {\n metaframe: MetaframeId;\n pipe: MetaframePipeId;\n};\n\ntype CachedInputLookupMap = {\n [key: string]: {\n [key: MetaframeId]: MetaframeInputTargetsFromOutput[]; // <metaframeId, MetaframeInputTargetsFromOutput[]>\n };\n};\n\ntype MetaframeClients = {\n [key: MetaframeId]: MetapageIFrameRpcClient;\n};\n\nconst CONSOLE_BACKGROUND_COLOR_DEFAULT = \"bcbcbc\";\n\nexport class Metapage extends MetapageShared {\n // The current version is always the latest\n public static readonly version = VERSION_METAPAGE;\n\n // Event literals for users to listen to events\n public static readonly DEFINITION = MetapageEvents.Definition;\n public static readonly ERROR = MetapageEvents.Error;\n public static readonly INPUTS = MetapageEvents.Inputs;\n public static readonly MESSAGE = MetapageEvents.Message;\n public static readonly OUTPUTS = MetapageEvents.Outputs;\n public static readonly STATE = MetapageEvents.State;\n\n public static deserializeInputs = deserializeInputs;\n public static serializeInputs = serializeInputs;\n\n public static async from(metaPageDef: any, inputs?: any): Promise<Metapage> {\n if (metaPageDef == null) {\n throw \"Metapage definition cannot be null\";\n }\n if (typeof metaPageDef === \"string\") {\n try {\n metaPageDef = JSON.parse(metaPageDef);\n } catch (err) {\n throw \"Cannot parse into JSON:\\n${metaPageDef}\";\n }\n }\n\n var metapage = new Metapage();\n return metapage.setDefinition(metaPageDef);\n }\n\n _id: MetapageId;\n _state: MetapageState = emptyState;\n _metaframes: MetaframeClients = create({}, draft => draft); //<MetaframeId, MetapageIFrameRpcClient>\n\n debug: boolean = isDebugFromUrlsParams();\n _consoleBackgroundColor: string;\n\n // Useful for debugging duplicate messages\n _internalReceivedMessageCounter: number = 0;\n\n // for caching input lookups\n _cachedInputLookupMap: CachedInputLookupMap = create<CachedInputLookupMap>({}, draft => draft);\n _inputMap: {\n [key: string]: PipeInput[];\n } = {};\n // Example:\n // \t{\n // \"version\": \"1\",\n // \"metaframes\": {\n // \"metaframe1\": {\n // \"url\": \"{{site.baseurl}}/metaframes/example00_iframe1/\",\n // \"inputs\": [\n // {\n // \"metaframe\":\"metaframe2\",\n // \"source\": \"barOut\",\n // \"target\": \"barIn\",\n // }\n // ]\n // },\n // \"metaframe2\": {\n // \"url\": \"{{site.baseurl}}/metaframes/example00_iframe2/\",\n // \"inputs\": [\n // {\n // \"metaframe\":\"metaframe1\",\n // \"source\": \"fooOut\",\n // \"target\": \"fooIn\",\n // }\n // ]\n // }\n // }\n // }\n\n constructor(opts?: MetapageOptionsV1) {\n super();\n this._id = opts && opts.id ? opts.id : generateMetapageId();\n this._consoleBackgroundColor =\n opts && opts.color ? opts.color : CONSOLE_BACKGROUND_COLOR_DEFAULT;\n\n this.addPipe = this.addPipe.bind(this);\n this.dispose = this.dispose.bind(this);\n // this.getDefinition = this.getDefinition.bind(this);\n this.addMetaframe = this.addMetaframe.bind(this);\n this.getInputsFromOutput = this.getInputsFromOutput.bind(this);\n this.getMetaframe = this.getMetaframe.bind(this);\n this.getMetaframeIds = this.getMetaframeIds.bind(this);\n this.getMetaframe = this.getMetaframe.bind(this);\n this.getMetaframes = this.getMetaframes.bind(this);\n this.getState = this.getState.bind(this);\n this.getStateMetaframes = this.getStateMetaframes.bind(this);\n this.isValidJSONRpcMessage = this.isValidJSONRpcMessage.bind(this);\n this.log = this.log.bind(this);\n this.logInternal = this.logInternal.bind(this);\n this.metaframeIds = this.metaframeIds.bind(this);\n this.metaframes = this.metaframes.bind(this);\n this.onMessage = this.onMessage.bind(this);\n this.removeAll = this.removeAll.bind(this);\n this.removeMetaframe = this.removeMetaframe.bind(this);\n this.setDebugFromUrlParams = this.setDebugFromUrlParams.bind(this);\n this.setDefinition = this.setDefinition.bind(this);\n this.setInput = this.setInput.bind(this);\n this.setInputs = this.setInputs.bind(this);\n this.setInputStateOnlyMetaframeInputValue = this.setInputStateOnlyMetaframeInputValue.bind(this);\n this.setInputStateOnlyMetaframeInputMap = this.setInputStateOnlyMetaframeInputMap.bind(this);\n this.setInputStateOnlyMetapageInstanceInputs = this.setInputStateOnlyMetapageInstanceInputs.bind(this);\n this.setOutputStateOnlyMetaframeInputValue = this.setOutputStateOnlyMetaframeInputValue.bind(this);\n this.setOutputStateOnlyMetaframeInputMap = this.setOutputStateOnlyMetaframeInputMap.bind(this);\n this.setOutputStateOnlyMetapageInstanceInputs = this.setOutputStateOnlyMetapageInstanceInputs.bind(this);\n this.setMetadata = this.setMetadata.bind(this);\n this.setMetaframeClientInputAndSentClientEvent =\n this.setMetaframeClientInputAndSentClientEvent.bind(this);\n this.setState = this.setState.bind(this);\n this.isDisposed = this.isDisposed.bind(this);\n this._emitDefinitionEvent = this._emitDefinitionEvent.bind(this);\n\n // see ARCHITECTURE.md\n // when the page is loaded, only then start listening to messages from metaframes\n pageLoaded().then(() => {\n if (this.isDisposed()) {\n return;\n }\n window.addEventListener(\"message\", this.onMessage);\n this.log(\"Initialized\");\n });\n }\n\n public isDisposed() {\n return this._metaframes === undefined;\n }\n\n addListenerReturnDisposer(\n event: MetapageEvents,\n listener: ListenerFn<any[]>\n ): () => void {\n super.addListener(event, listener);\n const disposer = () => {\n super.removeListener(event, listener);\n };\n return disposer;\n }\n\n public setDebugFromUrlParams(): Metapage {\n const url = new URL(window.location.href);\n this.debug = [\"debug\", \"mp_debug\"].reduce((exists, flag) => {\n return exists || url.searchParams.get(flag) === \"true\" || url.searchParams.get(flag) === \"1\"\n }, false)\n return this;\n }\n\n public getState(): MetapageState {\n return this._state;\n }\n\n public setState(newState: MetapageState) {\n this._state = create<MetapageState>(newState, (draft) => draft);\n this.getMetaframeIds().forEach((metaframeId) => {\n this.getMetaframe(metaframeId).setInputs(\n this._state.metaframes.inputs[metaframeId]\n );\n this.getMetaframe(metaframeId).setOutputs(\n this._state.metaframes.outputs[metaframeId]\n );\n });\n\n if (this.listenerCount(MetapageEvents.State) > 0 && emptyState !== this._state) {\n this.emit(MetapageEvents.State, this._state);\n }\n }\n\n public getStateMetaframes(): MetapageStatePartial {\n return this._state.metaframes;\n }\n\n public getDefinition(): MetapageDefinitionV2 {\n return this._definition;\n }\n\n public async setDefinition(def: any, state?: MetapageState): Promise<Metapage> {\n // Some validation\n if (!def.version) {\n throw \"Metapage definition must have a version\";\n }\n\n const newDefinition: MetapageDefinitionV2 = await\n convertMetapageDefinitionToCurrentVersion(def);\n\n if (this.isDisposed()) {\n // we got disposed while converting\n return this;\n }\n\n if (newDefinition.metaframes) {\n Object.keys(newDefinition.metaframes).forEach((metaframeId) => {\n var metaframeDefinition = newDefinition.metaframes[metaframeId];\n if (typeof metaframeDefinition !== \"object\") {\n this.emitErrorMessage(`Metaframe \"${metaframeId}\" is not an object`);\n throw `Metaframe \"${metaframeId}\" is not an object`;\n }\n\n if (!metaframeDefinition.url) {\n this.emitErrorMessage(\n `Metaframe \"${metaframeId}\" missing field: url`\n );\n throw `Metaframe \"${metaframeId}\" missing field: url`;\n }\n });\n }\n\n // TODO: revisit this assumption?\n // If there is not an earlier definition, we don't fire an event\n const previousDefinition = this._definition;\n\n this._definition = newDefinition;\n // try to be efficient with the new definition.\n // destroy any metaframes not in the new definition\n Object.keys(this._metaframes).forEach((metaframeId) => {\n // Doesn't exist? Destroy it\n if (!newDefinition.metaframes || !newDefinition.metaframes[metaframeId]) {\n // this removes the metaframe, pipes, inputs, caches\n this.removeMetaframe(metaframeId);\n }\n });\n\n // if the state is updated, set that now\n if (state) {\n this._state = create<MetapageState>(state, (draft) => draft);\n }\n\n // Create any new metaframes needed\n if (newDefinition.metaframes) {\n Object.keys(newDefinition.metaframes).forEach((newMetaframeId) => {\n if (!this._metaframes.hasOwnProperty(newMetaframeId)) {\n const metaframeDefinition = newDefinition.metaframes[newMetaframeId];\n // this will also set the inputs from our state\n this.addMetaframe(newMetaframeId, metaframeDefinition);\n }\n });\n }\n\n // TODO: fire the event anyway, but use immutable state so we \n // can do a quick compare\n // Only fire a definition update event IF this is not the first\n // time the definition is externally set\n if (previousDefinition !== INITIAL_NULL_METAPAGE_DEFINITION) {\n // Send the event on the next loop to give listeners time to re-add\n // after this method returns.\n window.setTimeout(() => {\n if (!this.isDisposed() && newDefinition === this._definition) {\n this._emitDefinitionEvent();\n if (state && this.listenerCount(MetapageEvents.State) > 0 && emptyState !== this._state) {\n this.emit(MetapageEvents.State, this._state);\n }\n }\n }, 0);\n }\n\n return this;\n }\n\n setMetadata(metadata: MetapageMetadataV2) {\n this._definition = create(this._definition, (draft) => {\n draft.meta = metadata;\n });\n this._emitDefinitionEvent();\n }\n\n // Convenience method\n _emitDefinitionEvent() {\n if (this.listenerCount(MetapageEvents.Definition) > 0) {\n const event: MetapageEventDefinition = {\n definition: this._definition,\n metaframes: this._metaframes,\n };\n this.emit(MetapageEvents.Definition, event);\n }\n }\n\n // do not expose, change definition instead\n addPipe(target: MetaframeId, input: PipeInput) {\n // Do all the cache checking\n this._inputMap = create(this._inputMap, (draft) => {\n if (!draft[target]) {\n draft[target] = [];\n }\n draft[target].push(input);\n });\n }\n\n // do not expose, change definition instead\n removeMetaframe(metaframeId: MetaframeId) {\n if (!this._metaframes[metaframeId]) {\n return;\n }\n\n this._metaframes[metaframeId].dispose();\n\n this._metaframes = create(this._metaframes, (draft) => {\n delete draft[metaframeId];\n });\n\n this._state = create(this._state, (draft) => {\n delete draft.metaframes.inputs[metaframeId];\n delete draft.metaframes.outputs[metaframeId];\n });\n\n this._inputMap = create(this._inputMap, (draft) => {\n delete draft[metaframeId];\n Object.keys(draft).forEach((otherMetaframeId) => {\n const inputPipes = draft[otherMetaframeId];\n let index = 0;\n while (index <= inputPipes.length) {\n if (inputPipes[index] && inputPipes[index].metaframe === metaframeId) {\n inputPipes.splice(index, 1);\n } else {\n index++;\n }\n }\n });\n });\n\n // This will regenerate, simpler than surgery\n this._cachedInputLookupMap = create({}, draft => draft);\n }\n\n // do not expose, change definition instead\n // to add/remove\n removeAll(): void {\n Object.keys(this._metaframes).forEach((id) =>\n this._metaframes[id].dispose()\n );\n this._metaframes = create({}, draft => draft);\n this._state = emptyState;\n this._inputMap = create({}, draft => draft);\n this._cachedInputLookupMap = create({}, draft => draft);\n }\n\n public metaframes() {\n return this.getMetaframes();\n }\n\n public metaframeIds(): MetaframeId[] {\n return this.getMetaframeIds();\n }\n\n public getMetaframeIds(): MetaframeId[] {\n return Object.keys(this._metaframes);\n }\n\n public getMetaframes(): {\n [key: string]: MetapageIFrameRpcClient;\n } {\n return this._metaframes;\n }\n\n public getMetaframe(id: MetaframeId): MetapageIFrameRpcClient {\n return this?._metaframes[id];\n }\n\n // do not expose, change definition instead\n addMetaframe(\n metaframeId: MetaframeId,\n definition: MetaframeInstance\n ): MetapageIFrameRpcClient {\n if (!metaframeId) {\n throw \"addMetaframe missing metaframeId\";\n }\n\n if (!definition) {\n throw \"addMetaframe missing definition\";\n }\n\n if (this._metaframes[metaframeId]) {\n this.emitErrorMessage(`Existing metaframe for id=${metaframeId}`);\n throw `Existing metaframe for id=${metaframeId}`;\n }\n\n if (!definition.url) {\n this.emitErrorMessage(\n `Metaframe definition missing url id=${metaframeId}`\n );\n throw `Metaframe definition missing url id=${metaframeId}`;\n }\n\n var iframeClient = new MetapageIFrameRpcClient(\n this,\n definition.url,\n metaframeId,\n this._id,\n this._consoleBackgroundColor,\n this.debug\n ).setMetapage(this);\n this._metaframes = create<MetaframeClients>(this._metaframes, (draft: MetaframeClients) => {\n draft[metaframeId] = iframeClient;\n });\n\n iframeClient.addListener(MetapageEvents.Error, (err) => {\n // These can be displayed\n this.emit(MetapageEvents.Error, {\n metaframeId: iframeClient.id,\n metaframeUrl: iframeClient.url,\n error: err,\n });\n });\n\n // add the pipes\n if (definition.inputs) {\n definition.inputs.forEach((input) => this.addPipe(metaframeId, input));\n }\n\n // set the initial inputs\n iframeClient.setInputs(this._state.metaframes.inputs[metaframeId]);\n\n return iframeClient;\n }\n\n public dispose() {\n this.log(\"disposing\");\n super.removeAllListeners();\n window.removeEventListener(\"message\", this.onMessage);\n if (this._metaframes) {\n Object.keys(this._metaframes).forEach((metaframeId) =>\n this._metaframes[metaframeId].dispose()\n );\n }\n\n // help the gc remove references but ignore the TS warnings as this object is now gone so don't touch it\n // @ts-ignore\n this._id = undefined;\n // @ts-ignore\n this._metaframes = undefined;\n // @ts-ignore\n this._state = undefined;\n // @ts-ignore\n this._cachedInputLookupMap = undefined;\n // @ts-ignore\n this._inputMap = undefined;\n }\n\n public log(o: any, color?: string, backgroundColor?: string) {\n if (!this.debug) {\n return;\n }\n this.logInternal(o, color, backgroundColor);\n }\n\n public error(err: any) {\n this.logInternal(err, \"f00\", this._consoleBackgroundColor);\n this.emitErrorMessage(`${err}`);\n }\n\n public emitErrorMessage(err: string) {\n this.emit(MetapageEvents.Error, err);\n }\n\n // This call is cached\n getInputsFromOutput(\n source: MetaframeId,\n // the pipe id is simply the name of the output file/object/thing\n outputPipeId: MetaframePipeId\n ): MetaframeInputTargetsFromOutput[] {\n // Do all the cache checking\n if (!this._cachedInputLookupMap[source]) {\n this._cachedInputLookupMap = create(this._cachedInputLookupMap, (draft: CachedInputLookupMap) => {\n draft[source] = create({}, __ => __);\n });\n }\n\n if (!this._cachedInputLookupMap[source][outputPipeId]) {\n\n this._cachedInputLookupMap = create(this._cachedInputLookupMap, (draft: CachedInputLookupMap) => {\n var targets: MetaframeInputTargetsFromOutput[] = [];\n draft[source][outputPipeId] = targets;\n // Go through the data structure, getting all the matching inputs that match this output\n Object.keys(this._inputMap).forEach((metaframeId) => {\n if (metaframeId === source) {\n // No self pipes, does not make sense\n return;\n }\n \n this._inputMap[metaframeId].forEach((inputPipe) => {\n // At least the source metaframe matches, now check pipes\n if (inputPipe.metaframe === source) {\n // Check the kind of source string\n // it could be a basic string, or a glob?\n if (matchPipe(outputPipeId, inputPipe.source)) {\n // console.log(\"✅ matches\");\n // A match, now figure out the actual input pipe name\n // since it might be * or absent meaning that the input\n // field name is the same as the incoming\n var targetName :string = inputPipe.target || \"\";\n if (\n !inputPipe.target ||\n inputPipe.target.startsWith(\"*\") ||\n inputPipe.target === \"\"\n ) {\n targetName = outputPipeId;\n } else if (targetName && targetName.endsWith(\"/\")) {\n targetName = targetName + outputPipeId;\n }\n targets.push({ metaframe: metaframeId, pipe: targetName });\n }\n }\n });\n });\n });\n }\n\n return this._cachedInputLookupMap[source][outputPipeId];\n }\n\n isValidJSONRpcMessage(message: MinimumClientMessage<any>) {\n if (message.jsonrpc !== \"2.0\") {\n // do not even log messages that we do not recogize. We cannot control random scripts sending messages on\n // the only communications channel\n return false;\n }\n const method = message.method as JsonRpcMethodsFromChild;\n switch (method) {\n case JsonRpcMethodsFromChild.SetupIframeClientRequest:\n //No validation possible here\n return true;\n default:\n // TODO: check origin+source\n var iframeId: MetaframeId | undefined = message.iframeId;\n if (\n iframeId &&\n !(\n message.parentId === this._id &&\n (this._metaframes[iframeId])\n )\n ) {\n return false;\n }\n return true;\n }\n }\n\n /**\n * Sets inputs\n * First update internal state, so any events that check get the new value\n * Then update the metaframe clients\n * Fire events\n * @param iframeId Can be an object of {metaframeId:{pipeId:value}} or the metaframe id\n * @param inputPipeId If the above is a string id, then inputPipeId can be the pipe id or an object {pipeId:value}\n * @param value If the above is a pipe id, then the is the value.\n */\n public setInput(iframeId: MetaframeId | MetapageInstanceInputs,\n inputPipeId?: MetaframePipeId | MetaframeInputMap,\n value?: PipeUpdateBlob) {\n\n if (typeof iframeId === \"object\") {\n this.setInputStateOnlyMetapageInstanceInputs(iframeId);\n } else if (typeof inputPipeId === \"string\") {\n this.setInputStateOnlyMetaframeInputValue(iframeId, inputPipeId, value);\n } else {\n this.setInputStateOnlyMetaframeInputMap(iframeId, inputPipeId || {});\n }\n\n this.setMetaframeClientInputAndSentClientEvent(\n iframeId,\n inputPipeId,\n value\n );\n // finally send the main events\n if (\n this.listenerCount(MetapageEvents.State) > 0 ||\n this.listenerCount(MetapageEvents.Inputs) > 0\n ) {\n if (emptyState !== this._state) {\n this.emit(MetapageEvents.State, this._state);\n this.emit(MetapageEvents.Inputs, this._state?.metaframes?.inputs);\n }\n }\n }\n\n setMetaframeClientInputAndSentClientEvent(\n iframeId: MetaframeId | MetapageInstanceInputs,\n inputPipeId?: MetaframePipeId | MetaframeInputMap,\n value?: PipeUpdateBlob\n ) {\n if (typeof iframeId === \"object\") {\n if (inputPipeId || value) {\n throw \"bad arguments, see API docs\";\n }\n const inputs: any = iframeId;\n Object.keys(inputs).forEach((id) => {\n var metaframeId: MetaframeId = id;\n var metaframeInputs = inputs[metaframeId];\n if (typeof metaframeInputs !== \"object\") {\n throw \"bad arguments, see API docs\";\n }\n var iframeClient = this._metaframes[metaframeId];\n if (iframeClient) {\n iframeClient.setInputs(metaframeInputs);\n } else {\n this.error(\"No iframe id=$metaframeId\");\n }\n });\n } else if (typeof iframeId === \"string\") {\n const iframeClient = this._metaframes[iframeId];\n if (iframeClient == null) {\n this.error(`No iframe id=${iframeId}`);\n }\n if (typeof inputPipeId === \"string\") {\n iframeClient.setInput(inputPipeId, value);\n } else if (typeof inputPipeId === \"object\") {\n iframeClient.setInputs(inputPipeId);\n } else {\n throw \"bad arguments, see API docs\";\n }\n } else {\n throw \"bad arguments, see API docs\";\n }\n }\n\n public setInputs(iframeId: MetaframeId | MetapageInstanceInputs, inputPipeId?: MetaframePipeId | MetaframeInputMap, value?: PipeUpdateBlob) {\n this.setInput(iframeId, inputPipeId, value);\n }\n\n setOutputStateOnlyMetapageInstanceInputs(metapageInputs: MetapageInstanceInputs) {\n this._setStateOnlyMetaframes(false, metapageInputs);\n }\n\n setOutputStateOnlyMetaframeInputValue(metaframeId: MetaframeId, inputPipeId: MetaframePipeId, value?: PipeUpdateBlob) {\n this._setStateOnlyMetaframeInputValue(false, metaframeId, inputPipeId, value);\n }\n\n setOutputStateOnlyMetaframeInputMap(metaframeId: MetaframeId, metaframeValuesNew: MetaframeInputMap) {\n this._setStateOnlyMetaframeInputMap(false, metaframeId, metaframeValuesNew);\n }\n\n setInputStateOnlyMetapageInstanceInputs(metapageInputs: MetapageInstanceInputs) {\n this._setStateOnlyMetaframes(true, metapageInputs);\n }\n\n setInputStateOnlyMetaframeInputValue(metaframeId: MetaframeId, inputPipeId: MetaframePipeId, value?: PipeUpdateBlob) {\n this._setStateOnlyMetaframeInputValue(true, metaframeId, inputPipeId, value);\n }\n\n setInputStateOnlyMetaframeInputMap(metaframeId: MetaframeId, metaframeValuesNew: MetaframeInputMap) {\n this._setStateOnlyMetaframeInputMap(true, metaframeId, metaframeValuesNew);\n }\n\n _setStateOnlyMetaframeInputValue(\n isInputs: boolean,\n metaframeId: MetaframeId,\n metaframePipeId: MetaframePipeId,\n value?: PipeUpdateBlob\n ): void {\n\n this._state = create(this._state, (draft: MetapageState) => {\n\n const isMetaframe = this._metaframes.hasOwnProperty(metaframeId);\n if (!isMetaframe) {\n throw `No metaframe: ${metaframeId}`;\n }\n if (!draft.metaframes) {\n draft.metaframes = { inputs: {}, outputs: {} };\n }\n\n if (isInputs) {\n if (!draft.metaframes.inputs) {\n draft.metaframes.inputs = {};\n }\n } else {\n if (!draft.metaframes.outputs) {\n draft.metaframes.outputs = {};\n }\n }\n\n let inputOrOutputState = isInputs\n ? draft.metaframes.inputs\n : draft.metaframes.outputs\n\n // Ensure a map\n inputOrOutputState = inputOrOutputState || {};\n inputOrOutputState[metaframeId] = !!inputOrOutputState[metaframeId]\n ? inputOrOutputState[metaframeId]\n : ({} as MetaframeInstance);\n\n // A key with a value of undefined means remove the key from the state object\n if (value === undefined) {\n delete inputOrOutputState[metaframeId][metaframePipeId];\n } else {\n // otherwise set the new value\n inputOrOutputState[metaframeId][metaframePipeId] = value;\n }\n });\n }\n\n\n\n _setStateOnlyMetaframeInputMap(\n isInputs: boolean,\n metaframeId: MetaframeId,\n metaframeValuesNew: MetaframeInputMap\n ): void {\n\n if (!metaframeValuesNew || Object.keys(metaframeValuesNew).length === 0) {\n return;\n }\n\n this._state = create(this._state, (draft: MetapageState) => {\n\n const isMetaframe = this._metaframes.hasOwnProperty(metaframeId);\n if (!isMetaframe) {\n throw `No metaframe: ${metaframeId}`;\n }\n\n let inputOrOutputState = isInputs\n ? draft.metaframes.inputs\n : draft.metaframes.outputs\n\n // Ensure a map\n inputOrOutputState[metaframeId] = inputOrOutputState[metaframeId]\n ? inputOrOutputState[metaframeId]\n : ({} as MetaframeInstance);\n\n Object.keys(metaframeValuesNew).forEach((metaframePipedId) => {\n // A key with a value of undefined means remove the key from the state object\n if (metaframeValuesNew[metaframePipedId] === undefined) {\n delete inputOrOutputState[metaframeId][metaframePipedId];\n } else {\n // otherwise set the new value\n inputOrOutputState[metaframeId][metaframePipedId] =\n metaframeValuesNew[metaframePipedId];\n }\n });\n\n });\n }\n\n _setStateOnlyMetaframes(\n isInputs: boolean,\n inputsMetaframesNew: MetapageInstanceInputs,\n ): void {\n\n if (!inputsMetaframesNew || Object.keys(inputsMetaframesNew).length === 0) {\n return;\n }\n\n this._state = create(this._state, (draft: MetapageState) => {\n Object.keys(inputsMetaframesNew).forEach((metaframeId) => {\n var metaframeValuesNew: MetaframeInputMap =\n inputsMetaframesNew[metaframeId];\n if (typeof metaframeValuesNew !== \"object\") {\n throw \"Object values must be objects\";\n }\n\n const isMetaframe = this._metaframes.hasOwnProperty(metaframeId);\n if (!isMetaframe) {\n throw \"No metaframe: ${metaframeId}\";\n }\n\n const inputOrOutputState = isInputs\n ? draft.metaframes.inputs\n : draft.metaframes.outputs\n\n // Ensure a map\n inputOrOutputState[metaframeId] = inputOrOutputState[metaframeId]\n ? inputOrOutputState[metaframeId]\n : ({} as MetaframeInstance);\n\n Object.keys(metaframeValuesNew).forEach((metaframePipedId) => {\n // A key with a value of undefined means remove the key from the state object\n if (metaframeValuesNew[metaframePipedId] === undefined) {\n delete inputOrOutputState[metaframeId][metaframePipedId];\n } else {\n // otherwise set the new value\n inputOrOutputState[metaframeId][metaframePipedId] =\n metaframeValuesNew[metaframePipedId];\n }\n });\n })\n });\n }\n\n onMessage(e: MessageEvent) {\n // any other type of messages are ignored\n // maybe in the future we can pass around strings or ArrayBuffers\n if (typeof e.data === \"object\") {\n const jsonrpc = e.data as MinimumClientMessage<any>;\n if (!this.isValidJSONRpcMessage(jsonrpc)) {\n return;\n }\n //Verify here\n var method = jsonrpc.method as JsonRpcMethodsFromChild;\n const metaframeId = jsonrpc.iframeId;\n // The metaframe gets its id from the window.name field so the iframe knows\n // its id from the very beginning\n if (!metaframeId) {\n // so if it's missing, bail early\n return;\n }\n\n const metaframe = this.getMetaframe(metaframeId);\n if (!metaframe) {\n this.error(`💥 onMessage no metaframe id=${metaframeId}`);\n return;\n }\n\n // debugging: track messsages internally\n (jsonrpc as any)[\"_messageCount\"] = ++this\n ._internalReceivedMessageCounter;\n\n if (this.debug) {\n this.log(\n `processing ${JSON.stringify(jsonrpc, null, \" \").substring(0, 500)}`\n );\n }\n\n switch (method) {\n /**\n * An iframe is sending a connection request.\n * Here we register it to set up a secure\n * communication channel.\n */\n case JsonRpcMethodsFromChild.SetupIframeClientRequest:\n metaframe.register();\n break;\n\n /* A client iframe responded */\n case JsonRpcMethodsFromChild.SetupIframeServerResponseAck:\n /* Send all inputs when a client has registered. */\n if (metaframe) {\n const params = jsonrpc.params as SetupIframeClientAckData<any>;\n metaframe.registered(params.version);\n }\n break;\n\n case JsonRpcMethodsFromChild.OutputsUpdate:\n const outputs: MetaframeInputMap = jsonrpc.params;\n if (!outputs || Object.keys(outputs).length === 0) {\n break;\n }\n\n if (this._metaframes[metaframeId]) {\n var iframe = this._metaframes[metaframeId];\n\n // set the internal state, no event yet, nor downstream inputs update (yet)\n this.setOutputStateOnlyMetaframeInputMap(metaframeId, outputs);\n // iframe outputs, metaframe only event sent\n iframe.setOutputs(outputs);\n // let's not send the state event until AFTER\n // cached lookup of where those outputs are going\n // Multiple outputs going to multiple inputs on the same metaframe must\n // arrive as a single blob\n var modified = false;\n const outputKeys = Object.keys(outputs);\n const collectedOutputs: { [key in string]: MetaframeInputMap } = {};\n outputKeys.forEach((outputKey, i) => {\n const targets: MetaframeInputTargetsFromOutput[] =\n this.getInputsFromOutput(metaframeId!, outputKey);\n\n if (targets.length > 0) {\n targets.forEach((target) => {\n if (!collectedOutputs[target.metaframe]) {\n collectedOutputs[target.metaframe] = {};\n }\n collectedOutputs[target.metaframe][target.pipe] =\n outputs[outputKey];\n modified = true;\n });\n }\n });\n if (modified) {\n this.setInputStateOnlyMetapageInstanceInputs(collectedOutputs);\n Object.keys(collectedOutputs).forEach((metaframeId) => {\n this._metaframes[metaframeId].setInputs(\n collectedOutputs[metaframeId]\n // then actually set the inputs once collected\n );\n });\n }\n // only send a state event if downstream inputs were modified\n if (this.listenerCount(MetapageEvents.State) > 0 && emptyState !== this._state) {\n this.emit(MetapageEvents.State, this._state);\n }\n if (this.debug) {\n iframe.ack({ jsonrpc: jsonrpc, state: this._state });\n }\n } else {\n this.error(`missing metaframe=${metaframeId}`);\n }\n\n break;\n\n case JsonRpcMethodsFromChild.InputsUpdate:\n // This is triggered by the metaframe itself, meaning the metaframe\n // decided to save this state info.\n // We store it in the local state, then send it back so\n // the metaframe is notified of its input state.\n var inputs: MetaframeInputMap = jsonrpc.params;\n if (this.debug)\n this.log(`inputs ${JSON.stringify(inputs)} from ${metaframeId}`);\n if (this._metaframes[metaframeId]) {\n // Set the internal inputs state first so that anything that\n // responds to events will get the updated state if requested\n // Currently on for setting metaframe inputs that haven't loaded yet\n this.setInputStateOnlyMetaframeInputMap(metaframeId, inputs);\n this._metaframes[metaframeId].setInputs(inputs);\n if (this.listenerCount(MetapageEvents.State) > 0 && emptyState !== this._state) {\n this.emit(MetapageEvents.State, this._state);\n }\n\n if (this.debug) {\n this._metaframes[metaframeId].ack({\n jsonrpc: jsonrpc,\n state: this._state,\n });\n }\n } else {\n console.error(\n `InputsUpdate failed no metaframe id: \"${metaframeId}\"`\n );\n this.error(\n `InputsUpdate failed no metaframe id: \"${metaframeId}\"`\n );\n }\n break;\n case JsonRpcMethodsFromChild.HashParamsUpdate:\n // Not really sure how to \"automatically\" process this right here\n // It's a potential automatic security concern, IF we want to put credentials\n // in the hash params (and we do)\n // So for now, just emit an event, and let the parent context handle it\n // In the current use case this app: https://github.com/metapages/metapage-app\n // will listen for the event and update the definition accordingly\n if (metaframe) {\n // Update in place the local references to the new metaframe URL with the\n // new hash params:\n // - if you call metapage.getDefinition() it will include the new URL\n // - compare metapage.getDefinition() with any updates outside of this\n // context to decide wether to re-render or recreate\n const hashParamsUpdatePayload: MetapageEventUrlHashUpdate =\n jsonrpc.params;\n const url = new URL(metaframe.url);\n url.hash = hashParamsUpdatePayload.hash;\n // Update the local metaframe client reference\n metaframe.url = url.href;\n // Update the definition in place\n this._definition = create<MetapageDefinitionV2>(\n this._definition,\n (draft) => {\n draft.metaframes[hashParamsUpdatePayload.metaframe].url = url.href;\n }\n );\n\n this._emitDefinitionEvent();\n }\n break;\n default:\n if (this.debug) {\n this.log(`Unknown RPC method: \"${method}\"`);\n }\n }\n if (this.listenerCount(MetapageEvents.Message) > 0) {\n this.emit(MetapageEvents.Message, jsonrpc);\n }\n }\n }\n\n logInternal(o: any, color?: string, backgroundColor?: string) {\n backgroundColor = backgroundColor\n ? backgroundColor\n : this._consoleBackgroundColor;\n let s: string;\n if (typeof o === \"string\") {\n s = o as string;\n } else if (typeof o === \"number\") {\n s = o + \"\";\n } else {\n s = JSON.stringify(o);\n }\n s = this._id ? `Metapage[${this._id}] ${s}` : s;\n MetapageToolsLog(s, color, backgroundColor);\n }\n}\n"],"names":["MetaframeVersionsAll","MetapageVersionsAll","MetaframeVersionCurrent","MetapageVersionCurrent","METAFRAME_JSON_FILE","METAPAGE_KEY_DEFINITION","METAPAGE_KEY_STATE","VERSION_METAPAGE","VERSION_METAFRAME","fetchRetry","fetchRetryWrapper","convertMetapageDefinitionToVersion","def","targetVersion","create","draft","compareVersions","err","convertMetapageDefinitionToTargetVersionInternal","convertMetapageDefinitionToCurrentVersion","currentVersion","getMatchingMetapageVersion","currentDefinition","definition_v0_2_to_v0_3","definition_v0_3_to_v1","definition_v0_3_to_v0_2","definition_v1_to_v2","definition_v1_to_v0_3","definition_v2_to_v1","old","castV1","_a","_b","version","convertMetaframeDefinitionToVersion","convertMetaframeDefinitionToTargetVersionInternal","convertMetaframeDefinitionToCurrentVersion","getMatchingMetaframeVersion","definition_v0_3_to_v0_4","definition_v0_4_to_v0_5","definition_v0_4_to_v0_3","definition_v0_5_to_v0_6","definition_v0_5_to_v0_4","definition_v0_6_to_v1","definition_v0_6_to_v0_5","definition_v1_to_v0_6","convertMetaframeJsonToCurrentVersion","m","opts","title","descriptionUrl","keywords","name","decription","tags","source","serializeInputs","inputs","key","maybeNewObject","possiblySerializeValueToDataref","deserializeInputs","possiblyDeserializeDatarefToValue","valueToFile","value","fileName","options","buffer","typedValue","blob","replacement","encode","arrayBuffer","serializedRef","_c","serializedRefBlob","decode","serializedRefFile","serializedRefTypedArray","constructorName","possiblyDeserializeDatarefToFile","typedArray","MetapageEvents","JsonRpcMethodsFromChild","JsonRpcMethodsFromParent","PARSE_ERROR","INVALID_REQUEST","METHOD_NOT_FOUND","INVALID_PARAMS","INTERNAL_ERROR","isJsonRpcId","input","MetapageHashParams","isIframe","INITIAL_NULL_METAPAGE_DEFINITION","MetapageShared","EventEmitter","merge","current","newInputs","pipeId","getUrlParam","getUrlParamDebug","isDebugFromUrlsParams","param","generateMetaframeId","length","generateId","generateMetapageId","generateNonce","LETTERS","result","charactersLength","log","o","color","backgroundColor","s","cssstring","stringToRgb","str","intToRGB","hashCode","hash","i","c","isPageLoaded","pageLoaded","resolve","loaded","metapageAllSha256Hash","metapage","metapageStr","stringify","sha256ToBase64","metapageOnlyEssentailSha256Hash","data","MetaframeLoadingState","MetaframeEvents","_Metaframe","thisRef","params","_","disposer","event","listener","MetapageToolsLog","pipe","originalInputs","updateBlob","outputs","originalOutputs","payload","method","message","jsonrpc","setHashParamInWindow","getHashParamFromWindow","setHashParamValueBooleanInWindow","getHashParamValueBooleanFromWindow","setHashParamValueJsonInWindow","getHashParamValueJsonFromWindow","setHashParamValueBase64EncodedInWindow","getHashParamValueBase64DecodedFromWindow","setHashParamValueFloatInWindow","getHashParamValueFloatFromWindow","setHashParamValueIntInWindow","getHashParamValueIntFromWindow","Metaframe","getMetapageDefinitionFromUrl","url","metapageUrl","definition","getMetaframeDefinitionFromUrl","metaframeUrl","isEmptyMetaframeDefinition","MetapageIFrameRpcClient","iframeId","parentId","consoleBackgroundColor","debug","urlBlob","selfThis","_d","metaframeDef","definitionFromHashParams","getHashParamValueJsonFromUrl","metaframeDefCurrent","inputBlob","maybeNewInputs","inputUpdate","maybeNewOutputs","outputsUpdate","f","pipeName","fWrap","val","response","thing","messageJSON","emptyState","getLibraryVersionMatching","matchPipe","outputName","picomatch","CONSOLE_BACKGROUND_COLOR_DEFAULT","_Metapage","metaPageDef","exists","flag","newState","metaframeId","state","newDefinition","metaframeDefinition","previousDefinition","newMetaframeId","metadata","target","otherMetaframeId","inputPipes","index","id","iframeClient","outputPipeId","__","targets","inputPipe","targetName","inputPipeId","metaframeInputs","metapageInputs","metaframeValuesNew","isInputs","metaframePipeId","inputOrOutputState","metaframePipedId","inputsMetaframesNew","metaframe","iframe","modified","outputKeys","collectedOutput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