@saasquatch/microsite-router 1.0.3 → 1.0.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.
- package/dist/bundle.js +1 -1
- package/package.json +2 -2
package/dist/bundle.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
function e(e){this.message=e}e.prototype=new Error,e.prototype.name="InvalidCharacterError";var t="undefined"!=typeof window&&window.atob&&window.atob.bind(window)||function(t){var n=String(t).replace(/=+$/,"");if(n.length%4==1)throw new e("'atob' failed: The string to be decoded is not correctly encoded.");for(var o,r,i=0,a=0,s="";r=n.charAt(a++);~r&&(o=i%4?64*o+r:r,i++%4)?s+=String.fromCharCode(255&o>>(-2*i&6)):0)r="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".indexOf(r);return s};function n(e){var n=e.replace(/-/g,"+").replace(/_/g,"/");switch(n.length%4){case 0:break;case 2:n+="==";break;case 3:n+="=";break;default:throw"Illegal base64url string!"}try{return function(e){return decodeURIComponent(t(e).replace(/(.)/g,(function(e,t){var n=t.charCodeAt(0).toString(16).toUpperCase();return n.length<2&&(n="0"+n),"%"+n})))}(n)}catch(e){return t(n)}}function o(e){this.message=e}function r(e,t){for(var n=0;n<t.length;n++){var o=t[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(e,o.key,o)}}function i(e,t,n){return t&&r(e.prototype,t),n&&r(e,n),e}o.prototype=new Error,o.prototype.name="InvalidTokenError";var a=function(){function e(e){var t=this,n=this;this._status="Initial",this.onChange=function(e){n.options.onChange&&n.options.onChange(e)},this.onConnect=function(e){try{return t.status="Connected",t.options.onChange&&t.options.onChange(e),Promise.resolve(new Promise((function(e){t.resolvePromise=e})))}catch(e){return Promise.reject(e)}},this.onDisconnect=function(){n.status="Connecting",n.start()},this.options=e}var t=e.prototype;return t.start=function(){var e=this,t=0;this.status="Connecting";var n=function(){return e.status},o=c(this.options.attempts)||10,r=function(){if("Connected"!==n()){var r=new CustomEvent(e.options.contextName,{bubbles:!0,cancelable:!0,composed:!0,detail:{onConnect:e.onConnect,onChange:e.onChange,onDisconnect:e.onDisconnect}});c(e.options.element).dispatchEvent(r),"Connected"!==n()?++t>=o&&(e._interval&&clearInterval(e._interval),e.status="Timeout"):"Connected"===n()&&e._interval&&clearInterval(e._interval)}};return(c(this.options.pollingMs)||100)>0&&o>1&&(this._interval=setInterval(r,c(this.options.pollingMs)||100)),r(),this},t.stop=function(){return this._interval&&clearInterval(this._interval),this.resolvePromise&&this.resolvePromise(),this.status="Initial",this},i(e,[{key:"status",set:function(e){this._status=e,this.options.onStatus&&this.options.onStatus(e)},get:function(){return this._status}}]),e}(),s=function(){function e(e){var t=this;this.__listeners=[],this.connectListener=function(e){try{e.stopPropagation(),t.__listeners=[].concat(t.__listeners,[e.detail]);var n=function(n,o){try{var r=Promise.resolve(e.detail.onConnect(t.__current)).then((function(){}))}catch(e){return o(!0,e)}return r&&r.then?r.then(o.bind(null,!1),o.bind(null,!0)):o(!1,r)}(0,(function(n,o){var r,i;if(t.__listeners=(i=(r=t.__listeners).indexOf(e.detail),r.slice(0,i).concat(r.slice(i+1,r.length))),n)throw o;return o}));return Promise.resolve(n&&n.then?n.then((function(){})):void 0)}catch(e){return Promise.reject(e)}},this.options=e,this.__current=c(e.initialState)}var t=e.prototype;return t.start=function(){return c(this.options.element).addEventListener(this.options.contextName,this.connectListener),this},t.stop=function(){return c(this.options.element).removeEventListener(this.options.contextName,this.connectListener),this.__listeners.map((function(e){e.onDisconnect()})),this.__listeners=[],this},i(e,[{key:"context",set:function(e){this.__current=e,this.__listeners.forEach((function(t){return t.onChange(e)}))},get:function(){return c(this.__current)}},{key:"listeners",get:function(){return Object.freeze([].concat(this.__listeners))}}]),e}();function c(e){return"function"==typeof typeof e?e():e}var l=Object.defineProperty,d=Object.defineProperties,u=Object.getOwnPropertyDescriptors,h=Object.getOwnPropertySymbols,w=Object.prototype.hasOwnProperty,p=Object.prototype.propertyIsEnumerable,f=(e,t,n)=>t in e?l(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,g=(e,t)=>{for(var n in t||(t={}))w.call(t,n)&&f(e,n,t[n]);if(h)for(var n of h(t))p.call(t,n)&&f(e,n,t[n]);return e},m=(e,t)=>d(e,u(t));function v(){var e,t,n;return window.SquatchAndroid?{type:"SquatchAndroid",android:window.SquatchAndroid,widgetIdent:window.widgetIdent}:window.SquatchPortal?{type:"SquatchPortal",env:window.SquatchPortal}:window.SquatchAdmin?{type:"SquatchAdmin",adminSDK:window.SquatchAdmin}:(window.widgetIdent||(null==(e=window.frameElement)?void 0:e.squatchJsApi))&&"demo"!==(null==(t=window.widgetIdent)?void 0:t.env)?{type:"SquatchJS2",api:null==(n=window.frameElement)?void 0:n.squatchJsApi,widgetIdent:window.widgetIdent}:{type:"None"}}function y(){var e;const t=v();switch(t.type){case"SquatchAndroid":case"SquatchIOS":case"SquatchJS2":return null==(e=t.widgetIdent)?void 0:e.tenantAlias;case"SquatchAdmin":case"None":return"demo";case"SquatchPortal":return t.env.tenantAlias}}var S="https://app.referralsaasquatch.com";function q(){var e,t;const n=v();switch(n.type){case"SquatchAndroid":case"SquatchIOS":case"SquatchJS2":return(null==(e=n.widgetIdent)?void 0:e.appDomain)||S;case"SquatchPortal":return(null==(t=n.env)?void 0:t.appDomain)||S;case"SquatchAdmin":case"None":return S}}var b=(()=>{var e;try{return null==(e=null==window?void 0:window.localStorage)?void 0:e.getItem("debug")}catch(e){return!1}})();function I(e,...t){b&&console.debug(`sq:environment:${e}`,...t)}var _=(...e)=>I("history",...e);function x(e){if("string"==typeof e)return e;const t=new URL(e.pathname,window.origin);return e.search&&(t.search=e.search),e.hash&&(t.hash=e.hash),t}function P(){if("SquatchPortal"===v().type){let e=function(e){const t=window.history[e];return function(...n){const o=t.apply(window.history,n),r=new Event(e);return window.dispatchEvent(r),o}};return window.history.pushState=e("pushState"),window.history.replaceState=e("replaceState"),new class{constructor(){this.listeners=new Set,window.addEventListener("popstate",this.notify.bind(this)),window.addEventListener("pushState",this.notify.bind(this)),window.addEventListener("replaceState",this.notify.bind(this))}listen(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}notify(){_("notifying listeners of route change",this.location),this.listeners&&this.listeners.forEach((e=>e()))}get location(){return{pathname:window.location.pathname,search:window.location.search,hash:window.location.hash,state:window.history.state}}back(){this.go(-1)}forward(){this.go(1)}go(e){window.history.go(e)}push(e,t){const n=x(e);window.history.pushState(t,"",n)}replace(e,t){const n=x(e);window.history.replaceState(t,"",n)}}}return new class{constructor(){this.history=[{pathname:"/",search:"",hash:""}],this.index=0,this.listeners=new Set}listen(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}current(){return this.history[this.index]}get state(){return this.current().state}notify(){_("notifying listeners of route change",this.location),this.listeners.forEach((e=>e()))}get location(){return this.history[this.index]}back(){this.go(-1)}forward(){this.go(1)}go(e){this.index+=e,this.index<0&&(this.index=0),this.index>=this.history.length&&(this.index=this.history.length-1),this.notify()}push(e,t){let n;n="string"==typeof e?{pathname:e,search:this.history[this.index].search,hash:this.history[this.index].hash,state:t}:m(g({},e),{state:t}),this.index++,this.history.splice(this.index,this.history.length,n),this.notify()}replace(e,t){this.history[this.index]="string"==typeof e?{pathname:e,search:"",hash:"",state:t}:m(g({},e),{state:t}),this.notify()}}}function C(){return window.squatchHistory=window.squatchHistory||P(),window.squatchHistory}var E=new class{get location(){return C().location}listen(e){return C().listen(e)}back(){C().back()}forward(){C().forward()}go(e){C().go(e)}push(e,t){C().push(e,t)}replace(e,t){C().replace(e,t)}};function $(e){if(e&&/^[a-z]{2}_(?:[A-Z]{2}|[0-9]{3})$/.test(e))return e}function k(){var e;let t=window.squatchLocale;if(!t){((...e)=>{I("sq:locale",...e)})("Creating locale context provider");const n=(null==(e=window.widgetIdent)?void 0:e.locale)??$(navigator.language.replaceAll("-","_"));t=new s({element:document.documentElement,initialState:n,contextName:"sq:locale"}).start(),window.squatchLocale=t}return t}function N(){var e;return null==(e=window.squatchLocale)?void 0:e.context}var L=(...e)=>I("sq:locale",...e);var A=(...e)=>I("sq:locale",...e),O=new a({contextName:"sq:user-identity",element:(()=>{const e="__environment_context_listener";let t=document.getElementById(e);return t||(t=document.createElement("div"),t.id=e,document.documentElement.appendChild(t)),t})(),onChange:async e=>{var t;const n=k(),o=(null==(t=window.widgetIdent)?void 0:t.locale)??$(navigator.language.replaceAll("-","_"));let r;if(e){A("User context changed, refetching locale");const e=await async function(){var e;L("Fetching locale from GraphQL for current user");try{const t=await fetch(`${q()}/api/v1/${y()}/graphql`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${null==(e=T())?void 0:e.jwt}`},body:JSON.stringify({query:"\n query {\n viewer {\n ... on User {\n locale\n }\n }\n }\n"})});if(!t.ok)throw new Error("Failed to fetch locale");const n=await t.json();if(n.errors)throw new Error(JSON.stringify(n.errors,null,2));return n.data.viewer.locale||void 0}catch(e){return void L("Failed to fetch locale for current user",e.message)}}();A(`New value fetched from GraphQL [${e}]`),r=e||o}else r=o;A(`Setting locale context to [${r}]`),n.context=r}});var j=(...e)=>I("sq:user-identity",...e);function R(){let e=window.squatchUserIdentity;return e||(j("Creating user context provider"),e=new s({element:document.documentElement,initialState:J(),contextName:"sq:user-identity"}).start(),window.squatchUserIdentity=e,A("Starting user context listener for locale updates"),O.start()),e}function U(e){if(e)try{const t=function(e,t){if("string"!=typeof e)throw new o("Invalid token specified");var r=!0===(t=t||{}).header?0:1;try{return JSON.parse(n(e.split(".")[r]))}catch(e){throw new o("Invalid token specified: "+e.message)}}(e),r=t.exp;let i,a;if(function(e){return e.sub&&/.*:.*@.*:users/.test(e.sub)}(t)){const e=t.sub.match(/(.*):(.*)@(.*):users/);(null==e?void 0:e[1])&&(a=atob(e[1])),(null==e?void 0:e[2])&&(i=atob(e[2]))}else(function(e){return e.user&&e.user.id&&e.user.accountId})(t)&&(a=t.user.accountId,i=t.user.id);return i&&a?r&&Date.now()>=1e3*r?void j("JWT has expired"):{id:i,accountId:a,jwt:e}:void j("No user information")}catch(e){return void j("Invalid JWT")}}function J(){const e=v();switch(e.type){case"SquatchIOS":case"SquatchAndroid":case"SquatchJS2":if(!e.widgetIdent)return;const{userId:t,accountId:n,token:o}=e.widgetIdent;if(!t||!n||!o)return;return{id:e.widgetIdent.userId,accountId:e.widgetIdent.accountId,jwt:e.widgetIdent.token};case"SquatchPortal":const r=new URLSearchParams(document.location.search);if(r.has("jwt"))return U(r.get("jwt"));const i=localStorage.getItem("sq:user-identity");if(!i)return;try{const e=JSON.parse(i),t=U(e.jwt);return t?g(g({},e),t):void 0}catch(e){return}case"SquatchAdmin":case"None":return}}function T(){var e;return null==(e=window.squatchUserIdentity)?void 0:e.context}const M=localStorage.getItem("debug");function D(e,...t){M&&console.debug(`sq:microsite:${e}`,...t)}const H={};let F=[];function B(e,t){var n;const o=[];let r=document.body;F.length>0&&(F[F.length-1].element.innerHTML=""),[...e.layouts].reverse().forEach(((e,n)=>{var i,a;if((null===(i=F[n])||void 0===i?void 0:i.key)===e.key&&(null===(a=F[n])||void 0===a?void 0:a.locale)===t)D("render",`reusing element for layout [${e.key}]`),r=F[n].element,o.push({key:e.key,locale:t,element:r});else{F.splice(n).forEach((e=>{D("render",`removing element for layout [${e.key}]`),e.element.remove()}));const i=document.createElement("div");i.style.display="contents",i.id=e.key,i.attachShadow({mode:"open"}),i.shadowRoot.innerHTML=e.values.html,r.appendChild(i),r=i,o.push({key:e.key,locale:t,element:i}),D("render",`created element for layout [${e.key}]`)}})),r.innerHTML=e.page.values.html,document.title=e.page.values.title,function(e){const t=document.head.querySelector('meta[name="description"]');if(t)t.content=e;else{const t=document.createElement("meta");t.name="description",t.content=e,document.head.append(t)}}(null!==(n=e.page.values.description)&&void 0!==n?n:""),F=o}var z;!function(e){e[e.Render=0]="Render",e[e.Redirect=1]="Redirect",e[e.NotAllowed=2]="NotAllowed"}(z||(z={}));async function G(e=E.location.pathname){var t;const n=N(),o=await async function(e,t){const n=`${e}${t?`_${t}`:""}`;if(H[n])return D("fetchPage",`avoiding GraphQL call in lieu of cache for [${e}]`),H[n];try{const n=await fetch(`${q()}/api/v1/${y()}/graphql`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({operationName:"RenderMicrositePage",query:"\n query RenderMicrositePage($urlPath: String!, $locale: RSLocale) {\n renderMicrositePage(urlPath: $urlPath, locale: $locale) {\n micrositePageConfig {\n urlPath\n values\n allowedUsers\n disallowedUrlPath\n }\n micrositeLayoutConfigs {\n key\n values\n }\n }\n }\n",variables:{urlPath:e,locale:t}})});if(!n.ok)throw new Error("Failed to fetch page");const o=await n.json();if(o.errors)throw new Error(JSON.stringify(o.errors,null,2));const r=o.data,i={page:r.renderMicrositePage.micrositePageConfig,layouts:r.renderMicrositePage.micrositeLayoutConfigs};return H[e]=i,i}catch(e){throw document.body.innerHTML=`\n <div style="padding: 12px;">\n <h3>Sorry, something went wrong</h3>\n <pre style="padding: 12px; font-family: monospace; font-size: 12px;">${e.message}</pre>\n </div>\n `,e}}(e,n),r=o.page.allowedUsers,i=o.page.disallowedUrlPath,a=T(),s=(null==a?void 0:a.jwt)?(null===(t=a.managedIdentity)||void 0===t?void 0:t.emailVerified)?"VERIFIED":"UNVERIFIED":"PUBLIC";let c=z.Render;s!=r&&(c=i?z.Redirect:"PUBLIC"===r?z.Render:z.NotAllowed);let l=`pathname[${e}] userType[${s}] allowedUsers[${r}]`;switch(c){case z.Render:D("router",`${l} user is allowed, rendering the page`),B(o,n);break;case z.Redirect:D("router",`${l} redirecting to ${i}`),E.push(i);break;case z.NotAllowed:D("router",`${l} user is not allowed, rendering an error page`),document.body.innerHTML='\n <div style="padding: 12px;">\n <h3>Not allowed.</h3>\n </div>\n'}}const Q=(()=>{const e="__context_listener";let t=document.getElementById(e);return t||(t=document.createElement("div"),t.id=e,document.documentElement.appendChild(t)),t})(),V=new a({contextName:"sq:user-identity",element:Q,onChange:e=>{D("user-context",`old[${JSON.stringify(T())}] new[${JSON.stringify(e)}]`)},onStatus:e=>{D("user-context",e)}}),W=new a({contextName:"sq:locale",element:Q,onChange:e=>{e&&(D("locale-context",`old[${N()}] new[${e}]`),G())},onStatus:e=>{D("locale-context",e)}});window.addEventListener("load",(function(){R(),k(),V.start(),W.start(),E.listen(G),G()}));
|
|
1
|
+
function e(e){this.message=e}e.prototype=new Error,e.prototype.name="InvalidCharacterError";var t="undefined"!=typeof window&&window.atob&&window.atob.bind(window)||function(t){var n=String(t).replace(/=+$/,"");if(n.length%4==1)throw new e("'atob' failed: The string to be decoded is not correctly encoded.");for(var o,i,r=0,a=0,s="";i=n.charAt(a++);~i&&(o=r%4?64*o+i:i,r++%4)?s+=String.fromCharCode(255&o>>(-2*r&6)):0)i="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".indexOf(i);return s};function n(e){var n=e.replace(/-/g,"+").replace(/_/g,"/");switch(n.length%4){case 0:break;case 2:n+="==";break;case 3:n+="=";break;default:throw"Illegal base64url string!"}try{return function(e){return decodeURIComponent(t(e).replace(/(.)/g,(function(e,t){var n=t.charCodeAt(0).toString(16).toUpperCase();return n.length<2&&(n="0"+n),"%"+n})))}(n)}catch(e){return t(n)}}function o(e){this.message=e}function i(e,t){for(var n=0;n<t.length;n++){var o=t[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(e,o.key,o)}}function r(e,t,n){return t&&i(e.prototype,t),n&&i(e,n),e}o.prototype=new Error,o.prototype.name="InvalidTokenError";var a=function(){function e(e){var t=this,n=this;this._status="Initial",this.onChange=function(e){n.options.onChange&&n.options.onChange(e)},this.onConnect=function(e){try{return t.status="Connected",t.options.onChange&&t.options.onChange(e),Promise.resolve(new Promise((function(e){t.resolvePromise=e})))}catch(e){return Promise.reject(e)}},this.onDisconnect=function(){n.status="Connecting",n.start()},this.options=e}var t=e.prototype;return t.start=function(){var e=this,t=0;this.status="Connecting";var n=function(){return e.status},o=c(this.options.attempts)||10,i=function(){if("Connected"!==n()){var i=new CustomEvent(e.options.contextName,{bubbles:!0,cancelable:!0,composed:!0,detail:{onConnect:e.onConnect,onChange:e.onChange,onDisconnect:e.onDisconnect}});c(e.options.element).dispatchEvent(i),"Connected"!==n()?++t>=o&&(e._interval&&clearInterval(e._interval),e.status="Timeout"):"Connected"===n()&&e._interval&&clearInterval(e._interval)}};return(c(this.options.pollingMs)||100)>0&&o>1&&(this._interval=setInterval(i,c(this.options.pollingMs)||100)),i(),this},t.stop=function(){return this._interval&&clearInterval(this._interval),this.resolvePromise&&this.resolvePromise(),this.status="Initial",this},r(e,[{key:"status",set:function(e){this._status=e,this.options.onStatus&&this.options.onStatus(e)},get:function(){return this._status}}]),e}(),s=function(){function e(e){var t=this;this.__listeners=[],this.connectListener=function(e){try{e.stopPropagation(),t.__listeners=[].concat(t.__listeners,[e.detail]);var n=function(n,o){try{var i=Promise.resolve(e.detail.onConnect(t.__current)).then((function(){}))}catch(e){return o(!0,e)}return i&&i.then?i.then(o.bind(null,!1),o.bind(null,!0)):o(!1,i)}(0,(function(n,o){var i,r;if(t.__listeners=(r=(i=t.__listeners).indexOf(e.detail),i.slice(0,r).concat(i.slice(r+1,i.length))),n)throw o;return o}));return Promise.resolve(n&&n.then?n.then((function(){})):void 0)}catch(e){return Promise.reject(e)}},this.options=e,this.__current=c(e.initialState)}var t=e.prototype;return t.start=function(){return c(this.options.element).addEventListener(this.options.contextName,this.connectListener),this},t.stop=function(){return c(this.options.element).removeEventListener(this.options.contextName,this.connectListener),this.__listeners.map((function(e){e.onDisconnect()})),this.__listeners=[],this},r(e,[{key:"context",set:function(e){this.__current=e,this.__listeners.forEach((function(t){return t.onChange(e)}))},get:function(){return c(this.__current)}},{key:"listeners",get:function(){return Object.freeze([].concat(this.__listeners))}}]),e}();function c(e){return"function"==typeof typeof e?e():e}var l=Object.defineProperty,d=Object.defineProperties,u=Object.getOwnPropertyDescriptors,h=Object.getOwnPropertySymbols,w=Object.prototype.hasOwnProperty,p=Object.prototype.propertyIsEnumerable,f=(e,t,n)=>t in e?l(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,g=(e,t)=>{for(var n in t||(t={}))w.call(t,n)&&f(e,n,t[n]);if(h)for(var n of h(t))p.call(t,n)&&f(e,n,t[n]);return e},m=(e,t)=>d(e,u(t));function v(){var e,t,n;return window.SquatchAndroid?{type:"SquatchAndroid",android:window.SquatchAndroid,widgetIdent:window.widgetIdent}:window.SquatchPortal?{type:"SquatchPortal",env:window.SquatchPortal}:window.SquatchAdmin?{type:"SquatchAdmin",adminSDK:window.SquatchAdmin}:(window.widgetIdent||(null==(e=window.frameElement)?void 0:e.squatchJsApi))&&"demo"!==(null==(t=window.widgetIdent)?void 0:t.env)?{type:"SquatchJS2",api:null==(n=window.frameElement)?void 0:n.squatchJsApi,widgetIdent:window.widgetIdent}:{type:"None"}}function y(){var e;const t=v();switch(t.type){case"SquatchAndroid":case"SquatchIOS":case"SquatchJS2":return null==(e=t.widgetIdent)?void 0:e.tenantAlias;case"SquatchAdmin":case"None":return"demo";case"SquatchPortal":return t.env.tenantAlias}}var S="https://app.referralsaasquatch.com";function q(){var e,t;const n=v();switch(n.type){case"SquatchAndroid":case"SquatchIOS":case"SquatchJS2":return(null==(e=n.widgetIdent)?void 0:e.appDomain)||S;case"SquatchPortal":return(null==(t=n.env)?void 0:t.appDomain)||S;case"SquatchAdmin":case"None":return S}}var b=(()=>{var e;try{return null==(e=null==window?void 0:window.localStorage)?void 0:e.getItem("debug")}catch(e){return!1}})();function I(e,...t){b&&console.debug(`sq:environment:${e}`,...t)}var _=(...e)=>I("history",...e);function x(e){if("string"==typeof e)return e;const t=new URL(e.pathname,window.origin);return e.search&&(t.search=e.search),e.hash&&(t.hash=e.hash),t}function P(){if("SquatchPortal"===v().type){let e=function(e){const t=window.history[e];return function(...n){const o=t.apply(window.history,n),i=new Event(e);return window.dispatchEvent(i),o}};return window.history.pushState=e("pushState"),window.history.replaceState=e("replaceState"),new class{constructor(){this.listeners=new Set,window.addEventListener("popstate",this.notify.bind(this)),window.addEventListener("pushState",this.notify.bind(this)),window.addEventListener("replaceState",this.notify.bind(this))}listen(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}notify(){_("notifying listeners of route change",this.location),this.listeners&&this.listeners.forEach((e=>e()))}get location(){return{pathname:window.location.pathname,search:window.location.search,hash:window.location.hash,state:window.history.state}}back(){this.go(-1)}forward(){this.go(1)}go(e){window.history.go(e)}push(e,t){const n=x(e);window.history.pushState(t,"",n)}replace(e,t){const n=x(e);window.history.replaceState(t,"",n)}}}return new class{constructor(){this.history=[{pathname:"/",search:"",hash:""}],this.index=0,this.listeners=new Set}listen(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}current(){return this.history[this.index]}get state(){return this.current().state}notify(){_("notifying listeners of route change",this.location),this.listeners.forEach((e=>e()))}get location(){return this.history[this.index]}back(){this.go(-1)}forward(){this.go(1)}go(e){this.index+=e,this.index<0&&(this.index=0),this.index>=this.history.length&&(this.index=this.history.length-1),this.notify()}push(e,t){let n;n="string"==typeof e?{pathname:e,search:this.history[this.index].search,hash:this.history[this.index].hash,state:t}:m(g({},e),{state:t}),this.index++,this.history.splice(this.index,this.history.length,n),this.notify()}replace(e,t){this.history[this.index]="string"==typeof e?{pathname:e,search:"",hash:"",state:t}:m(g({},e),{state:t}),this.notify()}}}function C(){return window.squatchHistory=window.squatchHistory||P(),window.squatchHistory}var E=new class{get location(){return C().location}listen(e){return C().listen(e)}back(){C().back()}forward(){C().forward()}go(e){C().go(e)}push(e,t){C().push(e,t)}replace(e,t){C().replace(e,t)}},$=(...e)=>I("sq:locale",...e);function k(e){if(e&&/^[a-z]{2}(_(?:[A-Z]{2}|[0-9]{3}))?$/.test(e))return e}function N(){var e;let t=window.squatchLocale;if(!t){$("Creating locale context provider");const n=(null==(e=window.widgetIdent)?void 0:e.locale)??k(navigator.language.replaceAll("-","_"));$("initializing with locale:",n),t=new s({element:document.documentElement,initialState:n,contextName:"sq:locale"}).start(),window.squatchLocale=t}return t}function L(){var e;return null==(e=window.squatchLocale)?void 0:e.context}var A=(...e)=>I("sq:locale",...e);var O=(...e)=>I("sq:locale",...e),j=new a({contextName:"sq:user-identity",element:(()=>{const e="__environment_context_listener";let t=document.getElementById(e);return t||(t=document.createElement("div"),t.id=e,document.documentElement.appendChild(t)),t})(),onChange:async e=>{var t;const n=N(),o=(null==(t=window.widgetIdent)?void 0:t.locale)??k(navigator.language.replaceAll("-","_"));let i;if(e){O("User context changed, refetching locale");const e=await async function(){var e;A("Fetching locale from GraphQL for current user");try{const t=await fetch(`${q()}/api/v1/${y()}/graphql`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${null==(e=M())?void 0:e.jwt}`},body:JSON.stringify({query:"\n query {\n viewer {\n ... on User {\n locale\n }\n }\n }\n"})});if(!t.ok)throw new Error("Failed to fetch locale");const n=await t.json();if(n.errors)throw new Error(JSON.stringify(n.errors,null,2));return n.data.viewer.locale||void 0}catch(e){return void A("Failed to fetch locale for current user",e.message)}}();O(`New value fetched from GraphQL [${e}]`),i=e||o}else i=o;O(`Setting locale context to [${i}]`),n.context=i}});var R=(...e)=>I("sq:user-identity",...e);function U(){let e=window.squatchUserIdentity;return e||(R("Creating user context provider"),e=new s({element:document.documentElement,initialState:T(),contextName:"sq:user-identity"}).start(),window.squatchUserIdentity=e,O("Starting user context listener for locale updates"),j.start()),e}function J(e){if(e)try{const t=function(e,t){if("string"!=typeof e)throw new o("Invalid token specified");var i=!0===(t=t||{}).header?0:1;try{return JSON.parse(n(e.split(".")[i]))}catch(e){throw new o("Invalid token specified: "+e.message)}}(e),i=t.exp;let r,a;if(function(e){return e.sub&&/.*:.*@.*:users/.test(e.sub)}(t)){const e=t.sub.match(/(.*):(.*)@(.*):users/);(null==e?void 0:e[1])&&(a=atob(e[1])),(null==e?void 0:e[2])&&(r=atob(e[2]))}else(function(e){return e.user&&e.user.id&&e.user.accountId})(t)&&(a=t.user.accountId,r=t.user.id);return r&&a?i&&Date.now()>=1e3*i?void R("JWT has expired"):{id:r,accountId:a,jwt:e}:void R("No user information")}catch(e){return void R("Invalid JWT")}}function T(){const e=v();switch(e.type){case"SquatchIOS":case"SquatchAndroid":case"SquatchJS2":if(!e.widgetIdent)return;const{userId:t,accountId:n,token:o}=e.widgetIdent;if(!t||!n||!o)return;return{id:e.widgetIdent.userId,accountId:e.widgetIdent.accountId,jwt:e.widgetIdent.token};case"SquatchPortal":const i=new URLSearchParams(document.location.search);if(i.has("jwt"))return J(i.get("jwt"));const r=localStorage.getItem("sq:user-identity");if(!r)return;try{const e=JSON.parse(r),t=J(e.jwt);return t?g(g({},e),t):void 0}catch(e){return}case"SquatchAdmin":case"None":return}}function M(){var e;return null==(e=window.squatchUserIdentity)?void 0:e.context}const D=localStorage.getItem("debug");function H(e,...t){D&&console.debug(`sq:microsite:${e}`,...t)}const F={};let z=[];function B(e,t){var n;const o=[];let i=document.body;z.length>0&&(z[z.length-1].element.innerHTML=""),[...e.layouts].reverse().forEach(((e,n)=>{var r,a;if((null===(r=z[n])||void 0===r?void 0:r.key)===e.key&&(null===(a=z[n])||void 0===a?void 0:a.locale)===t)H("render",`reusing element for layout [${e.key}]`),i=z[n].element,o.push({key:e.key,locale:t,element:i});else{z.splice(n).forEach((e=>{H("render",`removing element for layout [${e.key}]`),e.element.remove()}));const r=document.createElement("div");r.style.display="contents",r.id=e.key,r.attachShadow({mode:"open"}),r.shadowRoot.innerHTML=e.values.html,i.appendChild(r),i=r,o.push({key:e.key,locale:t,element:r}),H("render",`created element for layout [${e.key}]`)}})),i.innerHTML=e.page.values.html,document.title=e.page.values.title,function(e){const t=document.head.querySelector('meta[name="description"]');if(t)t.content=e;else{const t=document.createElement("meta");t.name="description",t.content=e,document.head.append(t)}}(null!==(n=e.page.values.description)&&void 0!==n?n:""),z=o}var G;!function(e){e[e.Render=0]="Render",e[e.Redirect=1]="Redirect",e[e.NotAllowed=2]="NotAllowed"}(G||(G={}));async function Q(e=E.location.pathname){var t;const n=L(),o=await async function(e,t){const n=`${e}${t?`_${t}`:""}`;if(F[n])return H("fetchPage",`avoiding GraphQL call in lieu of cache for [${e}]`),F[n];try{const n=await fetch(`${q()}/api/v1/${y()}/graphql`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({operationName:"RenderMicrositePage",query:"\n query RenderMicrositePage($urlPath: String!, $locale: RSLocale) {\n renderMicrositePage(urlPath: $urlPath, locale: $locale) {\n micrositePageConfig {\n urlPath\n values\n allowedUsers\n disallowedUrlPath\n }\n micrositeLayoutConfigs {\n key\n values\n }\n }\n }\n",variables:{urlPath:e,locale:t}})});if(!n.ok)throw new Error("Failed to fetch page");const o=await n.json();if(o.errors)throw new Error(JSON.stringify(o.errors,null,2));const i=o.data,r={page:i.renderMicrositePage.micrositePageConfig,layouts:i.renderMicrositePage.micrositeLayoutConfigs};return F[e]=r,r}catch(e){throw document.body.innerHTML=`\n <div style="padding: 12px;">\n <h3>Sorry, something went wrong</h3>\n <pre style="padding: 12px; font-family: monospace; font-size: 12px;">${e.message}</pre>\n </div>\n `,e}}(e,n),i=o.page.allowedUsers,r=o.page.disallowedUrlPath,a=M(),s=(null==a?void 0:a.jwt)?(null===(t=a.managedIdentity)||void 0===t?void 0:t.emailVerified)?"VERIFIED":"UNVERIFIED":"PUBLIC";let c=G.Render;s!=i&&(c=r?G.Redirect:"PUBLIC"===i?G.Render:G.NotAllowed);let l=`pathname[${e}] userType[${s}] allowedUsers[${i}]`;switch(c){case G.Render:H("router",`${l} user is allowed, rendering the page`),B(o,n);break;case G.Redirect:H("router",`${l} redirecting to ${r}`),E.push(r);break;case G.NotAllowed:H("router",`${l} user is not allowed, rendering an error page`),document.body.innerHTML='\n <div style="padding: 12px;">\n <h3>Not allowed.</h3>\n </div>\n'}}const V=(()=>{const e="__context_listener";let t=document.getElementById(e);return t||(t=document.createElement("div"),t.id=e,document.documentElement.appendChild(t)),t})(),W=new a({contextName:"sq:user-identity",element:V,onChange:e=>{H("user-context",`old[${JSON.stringify(M())}] new[${JSON.stringify(e)}]`)},onStatus:e=>{H("user-context",e)}}),K=new a({contextName:"sq:locale",element:V,onChange:e=>{e&&(H("locale-context",`old[${L()}] new[${e}]`),Q())},onStatus:e=>{H("locale-context",e)}});window.addEventListener("load",(function(){U(),N(),W.start(),K.start(),E.listen(Q),Q()}));
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@saasquatch/microsite-router",
|
|
3
|
-
"version": "1.0.
|
|
3
|
+
"version": "1.0.4",
|
|
4
4
|
"description": "SaaSquatch microsite client-side router and hierarchical layout renderer.",
|
|
5
5
|
"author": "ReferralSaaSquatch.com, Inc.",
|
|
6
6
|
"license": "SEE LICENSE IN LICENSE",
|
|
@@ -16,7 +16,7 @@
|
|
|
16
16
|
"test": "jest"
|
|
17
17
|
},
|
|
18
18
|
"dependencies": {
|
|
19
|
-
"@saasquatch/component-environment": "^1.0.
|
|
19
|
+
"@saasquatch/component-environment": "^1.0.6",
|
|
20
20
|
"dom-context": "^1.2.0"
|
|
21
21
|
},
|
|
22
22
|
"devDependencies": {
|