@smart-cloud/gatey-core 2.0.9 → 2.0.10
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/index.cjs +1 -1
- package/dist/index.d.cts +8 -1
- package/dist/index.d.ts +8 -1
- package/dist/index.js +1 -1
- package/package.json +1 -1
package/dist/index.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var b=Object.defineProperty;var H=Object.getOwnPropertyDescriptor;var $=Object.getOwnPropertyNames;var Q=Object.prototype.hasOwnProperty;var Z=(e,t)=>{for(var n in t)b(e,n,{get:t[n],enumerable:!0})},ee=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of $(t))!Q.call(e,o)&&o!==n&&b(e,o,{get:()=>t[o],enumerable:!(r=H(t,o))||r.enumerable});return e};var te=e=>ee(b({},"__esModule",{value:!0}),e);var de={};Z(de,{TEXT_DOMAIN:()=>z,clearMfaPreferences:()=>F,configureAmplify:()=>P,getAmplifyConfig:()=>T,getGateyPlugin:()=>u,getGroups:()=>E,getMfaPreferences:()=>L,getPreferredRole:()=>M,getRoles:()=>D,getScopes:()=>W,getStore:()=>l,getStoreDispatch:()=>d,getStoreSelect:()=>I,getUserAttributes:()=>N,initializeGatey:()=>pe,isAuthenticated:()=>_,isInGroup:()=>k,loadAuthSession:()=>f,loadMFAPreferences:()=>v,loadUserAttributes:()=>G,login:()=>J,logout:()=>w,observeStore:()=>S,store:()=>le,waitForGateyReady:()=>x});module.exports=te(de);var a=require("aws-amplify/api");function u(){return globalThis.WpSuite?.plugins?.gatey}async function x(e=8e3){let t=u();if(t?.status!=="available"){if(t?.status==="error")throw new Error("Gatey failed");await new Promise((n,r)=>{let o=()=>A(n),y=()=>A(()=>r(new Error("Gatey failed"))),A=c=>{window.removeEventListener("wpsuite:gatey:ready",o),window.removeEventListener("wpsuite:gatey:error",y),s&&clearTimeout(s),c()};window.addEventListener("wpsuite:gatey:ready",o,{once:!0}),window.addEventListener("wpsuite:gatey:error",y,{once:!0});let s=e?window.setTimeout(()=>A(()=>r(new Error("Gatey timeout"))),e):0})}}async function l(e=1e4){await x(e);let n=u()?.cognito?.store;if(!n)throw new Error("Gatey store is not available");return n}var O=require("aws-amplify"),i=require("aws-amplify/auth");var B=require("aws-amplify/auth"),R=require("aws-amplify/utils"),g=require("@wordpress/data"),V=require("@smart-cloud/wpsuite-core");var h="gatey_account",z="gatey";var U;typeof WpSuite<"u"?U=WpSuite.siteSettings:U={};var C=e=>{e?.username?window.localStorage.setItem(h,JSON.stringify(e)):window.localStorage.removeItem(h)},m=async e=>{let t=JSON.parse(window.localStorage.getItem(h)??"{}"),n=!1;if(t?.username)try{let r=await(0,B.fetchAuthSession)();r?.tokens?.accessToken?.payload?.exp&&r.tokens.accessToken.payload.exp>new Date().getTime()/1e3&&(n=!0)}catch(r){console.error(r)}else try{t=await X(!1),t?.username&&(C(t),t.loaded=!0,n=!0)}catch(r){console.error(r)}return!n&&t?.username&&(C({}),l().then(async r=>{await w(e?.signOutHook),d(r).clearAccount()})),t},ne=async e=>{let t=window.location.hostname.toLowerCase().split(":")[0],n=u();if(!n)throw new Error("Gatey plugin is not available");let r=n.settings?.secondaryUserPoolDomains&&t.toLowerCase().match(n.settings.secondaryUserPoolDomains.toLowerCase())&&n.settings?.userPoolConfigurations.secondary?.Auth?.Cognito?.userPoolId?n.settings?.userPoolConfigurations.secondary:n.settings?.userPoolConfigurations.default,o={Auth:{Cognito:{userPoolClientId:"",userPoolId:"",identityPoolId:"",...r.Auth?.Cognito,loginWith:{oauth:{domain:"",scopes:[],responseType:"code",...r.Auth?.Cognito?.loginWith?.oauth,redirectSignIn:[window.location.origin+n.settings?.signInPage],redirectSignOut:[window.location.origin+n.settings?.signInPage]}}}},API:{...r.API,REST:{...r.API?.REST,admin:{endpoint:n.restUrl}}}},y=e?.apiConfigurations?.secondary?.domains&&t.toLowerCase().match(e.apiConfigurations.secondary?.domains.toLowerCase())&&e.apiConfigurations?.secondary?.apis?.length?e.apiConfigurations.secondary:e?.apiConfigurations?.default;y?.apis?.forEach(s=>{let c=o.API?.REST;c&&(c[s.name]={endpoint:s.endpoint,region:s.region})}),P(o,{API:{REST:{headers:async s=>{let c=y?.apis?.find(p=>p.name===s.apiName);if(s.apiName==="admin"||c?.authorization==="ID_TOKEN"||c?.authorization==="ACCESS_TOKEN")try{let p=await f();if(p?.tokens?.idToken&&p?.tokens?.accessToken)return{Authorization:`Bearer ${s.apiName==="admin"||c?.authorization==="ID_TOKEN"?p.tokens.idToken.toString():p.tokens.accessToken.toString()}`}}catch(p){console.error(p),l().then(q=>{d(q).clearAccount()})}return{}}}}})},re=async()=>{let e=u();if(!e)throw new Error("Gatey plugin is not available");let t=null;return e.settings.customTranslationsUrl&&(t=await fetch(e.settings.customTranslationsUrl+(e.settings.customTranslationsUrl.includes("?")?"&":"?")+"t="+U.lastUpdate).then(n=>n.ok?n.text():null).then(n=>n?JSON.parse(n):null).catch(()=>null)),t??null},oe=async()=>{let e=await(0,V.getConfig)("gatey");ne(e);let t=window.location.hostname.toLowerCase().split(":")[0],n=e?.apiConfigurations?.secondary?.domains&&t.toLowerCase().match(e.apiConfigurations.secondary?.domains.toLowerCase())&&e.apiConfigurations?.secondary?.apis?.length?e.apiConfigurations.secondary:e?.apiConfigurations?.default,r=await m(n),o=await re();return{config:e,amplifyConfig:{},account:r,signedIn:!!r?.username&&!r.loaded,nextUrl:void 0,language:void 0,direction:void 0,customTranslations:o,reloadAuthSession:0,reloadUserAttributes:0,reloadMFAPreferences:0}},ie={setAmplifyConfig(e){return{type:"SET_AMPLIFY_CONFIG",amplifyConfig:e}},setAccount(e){return{type:"SET_ACCOUNT",account:e}},clearAccount(){return{type:"CLEAR_ACCOUNT"}},setSignedIn(e){return{type:"SET_SIGNED_IN",signedIn:e}},setNextUrl(e){return{type:"SET_NEXT_URL",nextUrl:e}},setLanguage(e){return!e||e==="system"?R.I18n.setLanguage(""):R.I18n.setLanguage(e),{type:"SET_LANGUAGE",language:e}},setDirection(e){return{type:"SET_DIRECTION",direction:e}},reloadAuthSession(){return{type:"RELOAD_AUTH_SESSION"}},reloadUserAttributes(){return{type:"RELOAD_USER_ATTRIBUTES"}},reloadMFAPreferences(){return{type:"RELOAD_MFA_PREFERENCE"}}},se={getAmplifyConfig(e){return e.amplifyConfig},getAccount(e){return e.account},getNextUrl(e){return e.nextUrl},isSignedIn(e){return e.signedIn},getConfig(e){return e.config},getCustomTranslations(e){return e.customTranslations},getLanguage(e){return e.language},getDirection(e){return e.direction},getState(e){return e}},ae={},d=e=>(0,g.dispatch)(e),I=e=>(0,g.select)(e),K=async()=>{let e=await oe(),t=(0,g.createReduxStore)("wpsuite/gatey",{reducer(n=e,r){switch(r.type){case"SET_AMPLIFY_CONFIG":return{...n,amplifyConfig:r.amplifyConfig};case"SET_ACCOUNT":return C(r.account),{...n,account:r.account};case"CLEAR_ACCOUNT":return C({}),{...n,account:{}};case"RELOAD_AUTH_SESSION":{let o=Math.random();return{...n,reloadAuthSession:n.reloadAuthSession!==o?o:o+1}}case"RELOAD_USER_ATTRIBUTES":{let o=Math.random();return{...n,reloadUserAttributes:n.reloadUserAttributes!==o?o:o+1}}case"RELOAD_MFA_PREFERENCE":{let o=Math.random();return{...n,reloadMFAPreferences:n.reloadMFAPreferences!==o?o:o+1}}case"SET_SIGNED_IN":return{...n,signedIn:r.signedIn};case"SET_NEXT_URL":return{...n,nextUrl:r.nextUrl};case"SET_LANGUAGE":return{...n,language:r.language};case"SET_DIRECTION":return{...n,direction:r.direction}}return n},actions:ie,selectors:se,resolvers:ae});return(0,g.register)(t),t},S=(e,t,n)=>{let r;function o(){let A=I(e).getState(),s=t(A);if(s!==r){let c=r;r=s,n(r,c)}}let y=(0,g.subscribe)(o,e);return o(),y};var T=()=>O.Amplify.getConfig(),P=(e,t)=>{O.Amplify.configure(e,t)},f=e=>(0,i.fetchAuthSession)(e),G=()=>(0,i.fetchUserAttributes)(),v=()=>(0,i.fetchMFAPreference)(),X=async(e=!0)=>{let t=e?await m():{};if(t?.username)return t;try{if((await(0,i.fetchAuthSession)()).tokens)return{username:(await(0,i.getCurrentUser)()).username,userAttributes:await G(),mfaPreferences:await v()}}catch(n){console.error(n);try{await(0,i.signOut)()}catch{}}return{}},F=async()=>{await(0,i.updateMFAPreference)({totp:"DISABLED"})},j=()=>m().then(e=>e?.username),N=()=>m().then(e=>e?.userAttributes),L=()=>m().then(e=>e?.mfaPreferences),_=()=>m().then(e=>!!e?.username),k=e=>E().then(t=>t?.includes(e)||!1),E=()=>f().then(e=>e.tokens?.idToken?.payload["cognito:groups"]instanceof Array?e.tokens.idToken.payload["cognito:groups"].map(t=>t):[]).catch(e=>{console.error(e)}),D=async()=>f().then(e=>e.tokens?.idToken?.payload["cognito:roles"]instanceof Array?e.tokens.idToken.payload["cognito:roles"].map(t=>t).map(t=>t.substring(t.indexOf("/")+1)):[]).catch(e=>{console.error(e)}),M=async()=>f().then(e=>{if(!e.tokens?.idToken?.payload["cognito:preferred_role"])return;let t=e.tokens.idToken.payload["cognito:preferred_role"];return t.substring(t.indexOf("/")+1)}).catch(e=>{console.error(e)}),W=()=>f().then(e=>e.tokens?.accessToken.payload.scope?.split(" ")??[]).catch(e=>{console.error(e)}),J=async e=>{let t,n=u();if(!n)throw new Error("Gatey plugin is not available");return n.settings.integrateWpLogin&&n.restUrl?.startsWith("http")&&(t=await n.cognito.post({apiName:"admin",path:"/login"}).response.then(o=>o.body.json()).then(o=>{if(o instanceof Object&&"redirect"in o)return o?.redirect}).catch(o=>{console.error(o)})),e&&await n.cognito.get({apiName:e.apiName,path:e.path,options:e.options}).response.catch(r=>console.error(r)),n.settings.redirectSignIn??t},w=async e=>{let t=u();if(!t)throw new Error("Gatey plugin is not available");let n;t.settings.integrateWpLogin&&(n=await t.cognito.get({apiName:"admin",path:"/logout"}).response.then(r=>r.body.json()).then(r=>{if(r instanceof Object&&"redirect"in r)return r?.redirect}).catch(r=>{console.error(r)})),e&&await t.cognito.get({apiName:e.apiName,path:e.path,options:e.options}).response.catch(r=>console.error(r));try{await(0,i.signOut)()}catch{}return t.settings.redirectSignOut??n};var Y=require("@smart-cloud/wpsuite-core"),ue=()=>{l().then(e=>{S(e,t=>t.nextUrl,async t=>{t&&window.location.assign(t)}),d(e).clearAccount()}).catch(e=>{console.error("Gatey signOut error:",e)})},ce=e=>{l().then(t=>{d(t).setLanguage(e??"en")}).catch(t=>{console.error("Gatey setLanguage error:",t)})},ge=e=>{l().then(t=>{d(t).setDirection(e??"auto")}).catch(t=>{console.error("Gatey setDirection error:",t)})};var le=async()=>l(),pe=()=>{let e=globalThis.WpSuite,t=u();if(!t)throw new Error("Gatey plugin is not available");(0,Y.attachDefaultPluginRuntime)(t),t.status=t.status??"initializing";let n=K();return t.cognito={store:n,observeStore:S,setLanguage:ce,setDirection:ge,getAmplifyConfig:T,isAuthenticated:_,isInGroup:k,getUsername:j,getUserAttributes:N,getMfaPreferences:L,clearMfaPreferences:F,getGroups:E,getRoles:D,getPreferredRole:M,getScopes:W,signOut:ue,get:a.get,post:a.post,put:a.put,del:a.del,head:a.head,patch:a.patch},n.then(()=>{t.status="available",e?.events?.emit("wpsuite:gatey:ready",{key:t.key,version:t.version})}).catch(r=>{t.status="error",e?.events?.emit("wpsuite:gatey:error",{key:t.key,error:String(r)})}),t};0&&(module.exports={TEXT_DOMAIN,clearMfaPreferences,configureAmplify,getAmplifyConfig,getGateyPlugin,getGroups,getMfaPreferences,getPreferredRole,getRoles,getScopes,getStore,getStoreDispatch,getStoreSelect,getUserAttributes,initializeGatey,isAuthenticated,isInGroup,loadAuthSession,loadMFAPreferences,loadUserAttributes,login,logout,observeStore,store,waitForGateyReady});
|
|
1
|
+
"use strict";var b=Object.defineProperty;var $=Object.getOwnPropertyDescriptor;var Q=Object.getOwnPropertyNames;var Z=Object.prototype.hasOwnProperty;var ee=(e,t)=>{for(var n in t)b(e,n,{get:t[n],enumerable:!0})},te=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of Q(t))!Z.call(e,o)&&o!==n&&b(e,o,{get:()=>t[o],enumerable:!(r=$(t,o))||r.enumerable});return e};var ne=e=>te(b({},"__esModule",{value:!0}),e);var fe={};ee(fe,{TEXT_DOMAIN:()=>B,clearMfaPreferences:()=>N,configureAmplify:()=>P,getAmplifyConfig:()=>T,getGateyPlugin:()=>u,getGroups:()=>E,getMfaPreferences:()=>_,getPreferredRole:()=>W,getRoles:()=>M,getScopes:()=>z,getStore:()=>l,getStoreDispatch:()=>d,getStoreSelect:()=>O,getUserAttributes:()=>L,initializeGatey:()=>de,isAuthenticated:()=>k,isInGroup:()=>D,loadAuthSession:()=>f,loadMFAPreferences:()=>G,loadUserAttributes:()=>F,login:()=>Y,logout:()=>w,observeStore:()=>S,sanitizeAuthenticatorConfig:()=>I,store:()=>pe,waitForGateyReady:()=>x});module.exports=ne(fe);var a=require("aws-amplify/api");function u(){return globalThis.WpSuite?.plugins?.gatey}async function x(e=8e3){let t=u();if(t?.status!=="available"){if(t?.status==="error")throw new Error("Gatey failed");await new Promise((n,r)=>{let o=()=>A(n),y=()=>A(()=>r(new Error("Gatey failed"))),A=c=>{window.removeEventListener("wpsuite:gatey:ready",o),window.removeEventListener("wpsuite:gatey:error",y),s&&clearTimeout(s),c()};window.addEventListener("wpsuite:gatey:ready",o,{once:!0}),window.addEventListener("wpsuite:gatey:error",y,{once:!0});let s=e?window.setTimeout(()=>A(()=>r(new Error("Gatey timeout"))),e):0})}}async function l(e=1e4){await x(e);let n=u()?.cognito?.store;if(!n)throw new Error("Gatey store is not available");return n}var v=require("aws-amplify"),i=require("aws-amplify/auth");var V=require("aws-amplify/auth"),R=require("aws-amplify/utils"),g=require("@wordpress/data"),K=require("@smart-cloud/wpsuite-core");var h="gatey_account",B="gatey";var U;typeof WpSuite<"u"?U=WpSuite.siteSettings:U={};var C=e=>{e?.username?window.localStorage.setItem(h,JSON.stringify(e)):window.localStorage.removeItem(h)},m=async e=>{let t=JSON.parse(window.localStorage.getItem(h)??"{}"),n=!1;if(t?.username)try{let r=await(0,V.fetchAuthSession)();r?.tokens?.accessToken?.payload?.exp&&r.tokens.accessToken.payload.exp>new Date().getTime()/1e3&&(n=!0)}catch(r){console.error(r)}else try{t=await X(!1),t?.username&&(C(t),t.loaded=!0,n=!0)}catch(r){console.error(r)}return!n&&t?.username&&(C({}),l().then(async r=>{await w(e?.signOutHook),d(r).clearAccount()})),t},re=async e=>{let t=window.location.hostname.toLowerCase().split(":")[0],n=u();if(!n)throw new Error("Gatey plugin is not available");let r=n.settings?.secondaryUserPoolDomains&&t.toLowerCase().match(n.settings.secondaryUserPoolDomains.toLowerCase())&&n.settings?.userPoolConfigurations.secondary?.Auth?.Cognito?.userPoolId?n.settings?.userPoolConfigurations.secondary:n.settings?.userPoolConfigurations.default,o={Auth:{Cognito:{userPoolClientId:"",userPoolId:"",identityPoolId:"",...r.Auth?.Cognito,loginWith:{oauth:{domain:"",scopes:[],responseType:"code",...r.Auth?.Cognito?.loginWith?.oauth,redirectSignIn:[window.location.origin+n.settings?.signInPage],redirectSignOut:[window.location.origin+n.settings?.signInPage]}}}},API:{...r.API,REST:{...r.API?.REST,admin:{endpoint:n.restUrl}}}},y=e?.apiConfigurations?.secondary?.domains&&t.toLowerCase().match(e.apiConfigurations.secondary?.domains.toLowerCase())&&e.apiConfigurations?.secondary?.apis?.length?e.apiConfigurations.secondary:e?.apiConfigurations?.default;y?.apis?.forEach(s=>{let c=o.API?.REST;c&&(c[s.name]={endpoint:s.endpoint,region:s.region})}),P(o,{API:{REST:{headers:async s=>{let c=y?.apis?.find(p=>p.name===s.apiName);if(s.apiName==="admin"||c?.authorization==="ID_TOKEN"||c?.authorization==="ACCESS_TOKEN")try{let p=await f();if(p?.tokens?.idToken&&p?.tokens?.accessToken)return{Authorization:`Bearer ${s.apiName==="admin"||c?.authorization==="ID_TOKEN"?p.tokens.idToken.toString():p.tokens.accessToken.toString()}`}}catch(p){console.error(p),l().then(H=>{d(H).clearAccount()})}return{}}}}})},oe=async()=>{let e=u();if(!e)throw new Error("Gatey plugin is not available");let t=null;return e.settings.customTranslationsUrl&&(t=await fetch(e.settings.customTranslationsUrl+(e.settings.customTranslationsUrl.includes("?")?"&":"?")+"t="+U.lastUpdate).then(n=>n.ok?n.text():null).then(n=>n?JSON.parse(n):null).catch(()=>null)),t??null},I=e=>{let t=e&&typeof e=="object"?e:{},n={customProviders:Array.isArray(t.customProviders)?t.customProviders:[],formFields:Array.isArray(t.formFields)?t.formFields:[],apiConfigurations:typeof t.apiConfigurations=="object"&&t.apiConfigurations?t.apiConfigurations:{default:{apis:[]}}};return typeof t.subscriptionType=="string"&&(n.subscriptionType=t.subscriptionType),n},ie=async()=>{let e=I(await(0,K.getConfig)("gatey"));re(e);let t=window.location.hostname.toLowerCase().split(":")[0],n=e?.apiConfigurations?.secondary?.domains&&t.toLowerCase().match(e.apiConfigurations.secondary?.domains.toLowerCase())&&e.apiConfigurations?.secondary?.apis?.length?e.apiConfigurations.secondary:e?.apiConfigurations?.default,r=await m(n),o=await oe();return{config:e,amplifyConfig:{},account:r,signedIn:!!r?.username&&!r.loaded,nextUrl:void 0,language:void 0,direction:void 0,customTranslations:o,reloadAuthSession:0,reloadUserAttributes:0,reloadMFAPreferences:0}},se={setAmplifyConfig(e){return{type:"SET_AMPLIFY_CONFIG",amplifyConfig:e}},setAccount(e){return{type:"SET_ACCOUNT",account:e}},clearAccount(){return{type:"CLEAR_ACCOUNT"}},setSignedIn(e){return{type:"SET_SIGNED_IN",signedIn:e}},setNextUrl(e){return{type:"SET_NEXT_URL",nextUrl:e}},setLanguage(e){return!e||e==="system"?R.I18n.setLanguage(""):R.I18n.setLanguage(e),{type:"SET_LANGUAGE",language:e}},setDirection(e){return{type:"SET_DIRECTION",direction:e}},reloadAuthSession(){return{type:"RELOAD_AUTH_SESSION"}},reloadUserAttributes(){return{type:"RELOAD_USER_ATTRIBUTES"}},reloadMFAPreferences(){return{type:"RELOAD_MFA_PREFERENCE"}}},ae={getAmplifyConfig(e){return e.amplifyConfig},getAccount(e){return e.account},getNextUrl(e){return e.nextUrl},isSignedIn(e){return e.signedIn},getConfig(e){return e.config},getCustomTranslations(e){return e.customTranslations},getLanguage(e){return e.language},getDirection(e){return e.direction},getState(e){return e}},ue={},d=e=>(0,g.dispatch)(e),O=e=>(0,g.select)(e),j=async()=>{let e=await ie(),t=(0,g.createReduxStore)("wpsuite/gatey",{reducer(n=e,r){switch(r.type){case"SET_AMPLIFY_CONFIG":return{...n,amplifyConfig:r.amplifyConfig};case"SET_ACCOUNT":return C(r.account),{...n,account:r.account};case"CLEAR_ACCOUNT":return C({}),{...n,account:{}};case"RELOAD_AUTH_SESSION":{let o=Math.random();return{...n,reloadAuthSession:n.reloadAuthSession!==o?o:o+1}}case"RELOAD_USER_ATTRIBUTES":{let o=Math.random();return{...n,reloadUserAttributes:n.reloadUserAttributes!==o?o:o+1}}case"RELOAD_MFA_PREFERENCE":{let o=Math.random();return{...n,reloadMFAPreferences:n.reloadMFAPreferences!==o?o:o+1}}case"SET_SIGNED_IN":return{...n,signedIn:r.signedIn};case"SET_NEXT_URL":return{...n,nextUrl:r.nextUrl};case"SET_LANGUAGE":return{...n,language:r.language};case"SET_DIRECTION":return{...n,direction:r.direction}}return n},actions:se,selectors:ae,resolvers:ue});return(0,g.register)(t),t},S=(e,t,n)=>{let r;function o(){let A=O(e).getState(),s=t(A);if(s!==r){let c=r;r=s,n(r,c)}}let y=(0,g.subscribe)(o,e);return o(),y};var T=()=>v.Amplify.getConfig(),P=(e,t)=>{v.Amplify.configure(e,t)},f=e=>(0,i.fetchAuthSession)(e),F=()=>(0,i.fetchUserAttributes)(),G=()=>(0,i.fetchMFAPreference)(),X=async(e=!0)=>{let t=e?await m():{};if(t?.username)return t;try{if((await(0,i.fetchAuthSession)()).tokens)return{username:(await(0,i.getCurrentUser)()).username,userAttributes:await F(),mfaPreferences:await G()}}catch(n){console.error(n);try{await(0,i.signOut)()}catch{}}return{}},N=async()=>{await(0,i.updateMFAPreference)({totp:"DISABLED"})},J=()=>m().then(e=>e?.username),L=()=>m().then(e=>e?.userAttributes),_=()=>m().then(e=>e?.mfaPreferences),k=()=>m().then(e=>!!e?.username),D=e=>E().then(t=>t?.includes(e)||!1),E=()=>f().then(e=>e.tokens?.idToken?.payload["cognito:groups"]instanceof Array?e.tokens.idToken.payload["cognito:groups"].map(t=>t):[]).catch(e=>{console.error(e)}),M=async()=>f().then(e=>e.tokens?.idToken?.payload["cognito:roles"]instanceof Array?e.tokens.idToken.payload["cognito:roles"].map(t=>t).map(t=>t.substring(t.indexOf("/")+1)):[]).catch(e=>{console.error(e)}),W=async()=>f().then(e=>{if(!e.tokens?.idToken?.payload["cognito:preferred_role"])return;let t=e.tokens.idToken.payload["cognito:preferred_role"];return t.substring(t.indexOf("/")+1)}).catch(e=>{console.error(e)}),z=()=>f().then(e=>e.tokens?.accessToken.payload.scope?.split(" ")??[]).catch(e=>{console.error(e)}),Y=async e=>{let t,n=u();if(!n)throw new Error("Gatey plugin is not available");return n.settings.integrateWpLogin&&n.restUrl?.startsWith("http")&&(t=await n.cognito.post({apiName:"admin",path:"/login"}).response.then(o=>o.body.json()).then(o=>{if(o instanceof Object&&"redirect"in o)return o?.redirect}).catch(o=>{console.error(o)})),e&&await n.cognito.get({apiName:e.apiName,path:e.path,options:e.options}).response.catch(r=>console.error(r)),n.settings.redirectSignIn??t},w=async e=>{let t=u();if(!t)throw new Error("Gatey plugin is not available");let n;t.settings.integrateWpLogin&&(n=await t.cognito.get({apiName:"admin",path:"/logout"}).response.then(r=>r.body.json()).then(r=>{if(r instanceof Object&&"redirect"in r)return r?.redirect}).catch(r=>{console.error(r)})),e&&await t.cognito.get({apiName:e.apiName,path:e.path,options:e.options}).response.catch(r=>console.error(r));try{await(0,i.signOut)()}catch{}return t.settings.redirectSignOut??n};var q=require("@smart-cloud/wpsuite-core");var ce=()=>{l().then(e=>{S(e,t=>t.nextUrl,async t=>{t&&window.location.assign(t)}),d(e).clearAccount()}).catch(e=>{console.error("Gatey signOut error:",e)})},ge=e=>{l().then(t=>{d(t).setLanguage(e??"en")}).catch(t=>{console.error("Gatey setLanguage error:",t)})},le=e=>{l().then(t=>{d(t).setDirection(e??"auto")}).catch(t=>{console.error("Gatey setDirection error:",t)})};var pe=async()=>l(),de=()=>{let e=globalThis.WpSuite,t=u();if(!t)throw new Error("Gatey plugin is not available");(0,q.attachDefaultPluginRuntime)(t),t.status=t.status??"initializing";let n=j();return t.cognito={store:n,observeStore:S,setLanguage:ge,setDirection:le,getAmplifyConfig:T,isAuthenticated:k,isInGroup:D,getUsername:J,getUserAttributes:L,getMfaPreferences:_,clearMfaPreferences:N,getGroups:E,getRoles:M,getPreferredRole:W,getScopes:z,signOut:ce,get:a.get,post:a.post,put:a.put,del:a.del,head:a.head,patch:a.patch},n.then(()=>{t.status="available",e?.events?.emit("wpsuite:gatey:ready",{key:t.key,version:t.version})}).catch(r=>{t.status="error",e?.events?.emit("wpsuite:gatey:error",{key:t.key,error:String(r)})}),t};0&&(module.exports={TEXT_DOMAIN,clearMfaPreferences,configureAmplify,getAmplifyConfig,getGateyPlugin,getGroups,getMfaPreferences,getPreferredRole,getRoles,getScopes,getStore,getStoreDispatch,getStoreSelect,getUserAttributes,initializeGatey,isAuthenticated,isInGroup,loadAuthSession,loadMFAPreferences,loadUserAttributes,login,logout,observeStore,sanitizeAuthenticatorConfig,store,waitForGateyReady});
|
package/dist/index.d.cts
CHANGED
|
@@ -30,6 +30,13 @@ declare const getScopes: () => Promise<string[] | undefined>;
|
|
|
30
30
|
declare const login: (signInHook: ApiConfiguration["signInHook"]) => Promise<string | undefined>;
|
|
31
31
|
declare const logout: (signOutHook: ApiConfiguration["signOutHook"]) => Promise<string | undefined>;
|
|
32
32
|
|
|
33
|
+
/**
|
|
34
|
+
* Ensures we only keep runtime keys that are part of AuthenticatorConfig.
|
|
35
|
+
*
|
|
36
|
+
* Defensive: upstream getConfig("gatey") or persisted site.settings may include
|
|
37
|
+
* additional keys, but the admin UI and core should only operate on AuthenticatorConfig.
|
|
38
|
+
*/
|
|
39
|
+
declare const sanitizeAuthenticatorConfig: (input: unknown) => AuthenticatorConfig;
|
|
33
40
|
declare const actions: {
|
|
34
41
|
setAmplifyConfig(amplifyConfig: ResourcesConfig): {
|
|
35
42
|
type: string;
|
|
@@ -219,4 +226,4 @@ declare const store: () => Promise<Store>;
|
|
|
219
226
|
|
|
220
227
|
declare const initializeGatey: () => GateyPlugin;
|
|
221
228
|
|
|
222
|
-
export { type Account, type AuthenticatorConfig, type Cognito, type CustomTranslations, type FormField, type Gatey, type GateyErrorEvent, type GateyPlugin, type GateyReadyEvent, type RoleMapping, type Settings, type State, type Store, TEXT_DOMAIN, clearMfaPreferences, configureAmplify, getAmplifyConfig, getGateyPlugin, getGroups, getMfaPreferences, getPreferredRole, getRoles, getScopes, getStore, getStoreDispatch, getStoreSelect, getUserAttributes, initializeGatey, isAuthenticated, isInGroup, loadAuthSession, loadMFAPreferences, loadUserAttributes, login, logout, observeStore, store, waitForGateyReady };
|
|
229
|
+
export { type Account, type AuthenticatorConfig, type Cognito, type CustomTranslations, type FormField, type Gatey, type GateyErrorEvent, type GateyPlugin, type GateyReadyEvent, type RoleMapping, type Settings, type State, type Store, TEXT_DOMAIN, clearMfaPreferences, configureAmplify, getAmplifyConfig, getGateyPlugin, getGroups, getMfaPreferences, getPreferredRole, getRoles, getScopes, getStore, getStoreDispatch, getStoreSelect, getUserAttributes, initializeGatey, isAuthenticated, isInGroup, loadAuthSession, loadMFAPreferences, loadUserAttributes, login, logout, observeStore, sanitizeAuthenticatorConfig, store, waitForGateyReady };
|
package/dist/index.d.ts
CHANGED
|
@@ -30,6 +30,13 @@ declare const getScopes: () => Promise<string[] | undefined>;
|
|
|
30
30
|
declare const login: (signInHook: ApiConfiguration["signInHook"]) => Promise<string | undefined>;
|
|
31
31
|
declare const logout: (signOutHook: ApiConfiguration["signOutHook"]) => Promise<string | undefined>;
|
|
32
32
|
|
|
33
|
+
/**
|
|
34
|
+
* Ensures we only keep runtime keys that are part of AuthenticatorConfig.
|
|
35
|
+
*
|
|
36
|
+
* Defensive: upstream getConfig("gatey") or persisted site.settings may include
|
|
37
|
+
* additional keys, but the admin UI and core should only operate on AuthenticatorConfig.
|
|
38
|
+
*/
|
|
39
|
+
declare const sanitizeAuthenticatorConfig: (input: unknown) => AuthenticatorConfig;
|
|
33
40
|
declare const actions: {
|
|
34
41
|
setAmplifyConfig(amplifyConfig: ResourcesConfig): {
|
|
35
42
|
type: string;
|
|
@@ -219,4 +226,4 @@ declare const store: () => Promise<Store>;
|
|
|
219
226
|
|
|
220
227
|
declare const initializeGatey: () => GateyPlugin;
|
|
221
228
|
|
|
222
|
-
export { type Account, type AuthenticatorConfig, type Cognito, type CustomTranslations, type FormField, type Gatey, type GateyErrorEvent, type GateyPlugin, type GateyReadyEvent, type RoleMapping, type Settings, type State, type Store, TEXT_DOMAIN, clearMfaPreferences, configureAmplify, getAmplifyConfig, getGateyPlugin, getGroups, getMfaPreferences, getPreferredRole, getRoles, getScopes, getStore, getStoreDispatch, getStoreSelect, getUserAttributes, initializeGatey, isAuthenticated, isInGroup, loadAuthSession, loadMFAPreferences, loadUserAttributes, login, logout, observeStore, store, waitForGateyReady };
|
|
229
|
+
export { type Account, type AuthenticatorConfig, type Cognito, type CustomTranslations, type FormField, type Gatey, type GateyErrorEvent, type GateyPlugin, type GateyReadyEvent, type RoleMapping, type Settings, type State, type Store, TEXT_DOMAIN, clearMfaPreferences, configureAmplify, getAmplifyConfig, getGateyPlugin, getGroups, getMfaPreferences, getPreferredRole, getRoles, getScopes, getStore, getStoreDispatch, getStoreSelect, getUserAttributes, initializeGatey, isAuthenticated, isInGroup, loadAuthSession, loadMFAPreferences, loadUserAttributes, login, logout, observeStore, sanitizeAuthenticatorConfig, store, waitForGateyReady };
|
package/dist/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{del as ue,get as ce,head as ge,patch as le,post as pe,put as de}from"aws-amplify/api";function a(){return globalThis.WpSuite?.plugins?.gatey}async function T(e=8e3){let t=a();if(t?.status!=="available"){if(t?.status==="error")throw new Error("Gatey failed");await new Promise((n,r)=>{let o=()=>f(n),g=()=>f(()=>r(new Error("Gatey failed"))),f=s=>{window.removeEventListener("wpsuite:gatey:ready",o),window.removeEventListener("wpsuite:gatey:error",g),i&&clearTimeout(i),s()};window.addEventListener("wpsuite:gatey:ready",o,{once:!0}),window.addEventListener("wpsuite:gatey:error",g,{once:!0});let i=e?window.setTimeout(()=>f(()=>r(new Error("Gatey timeout"))),e):0})}}async function c(e=1e4){await T(e);let n=a()?.cognito?.store;if(!n)throw new Error("Gatey store is not available");return n}import{Amplify as U}from"aws-amplify";import{fetchAuthSession as I,fetchMFAPreference as re,fetchUserAttributes as oe,getCurrentUser as ie,signOut as O,updateMFAPreference as se}from"aws-amplify/auth";import{fetchAuthSession as K}from"aws-amplify/auth";import{I18n as E}from"aws-amplify/utils";import{createReduxStore as X,dispatch as j,register as J,select as Y,subscribe as q}from"@wordpress/data";import{getConfig as H}from"@smart-cloud/wpsuite-core";var y="gatey_account",V="gatey";var S;typeof WpSuite<"u"?S=WpSuite.siteSettings:S={};var m=e=>{e?.username?window.localStorage.setItem(y,JSON.stringify(e)):window.localStorage.removeItem(y)},l=async e=>{let t=JSON.parse(window.localStorage.getItem(y)??"{}"),n=!1;if(t?.username)try{let r=await K();r?.tokens?.accessToken?.payload?.exp&&r.tokens.accessToken.payload.exp>new Date().getTime()/1e3&&(n=!0)}catch(r){console.error(r)}else try{t=await R(!1),t?.username&&(m(t),t.loaded=!0,n=!0)}catch(r){console.error(r)}return!n&&t?.username&&(m({}),c().then(async r=>{await C(e?.signOutHook),p(r).clearAccount()})),t},$=async e=>{let t=window.location.hostname.toLowerCase().split(":")[0],n=a();if(!n)throw new Error("Gatey plugin is not available");let r=n.settings?.secondaryUserPoolDomains&&t.toLowerCase().match(n.settings.secondaryUserPoolDomains.toLowerCase())&&n.settings?.userPoolConfigurations.secondary?.Auth?.Cognito?.userPoolId?n.settings?.userPoolConfigurations.secondary:n.settings?.userPoolConfigurations.default,o={Auth:{Cognito:{userPoolClientId:"",userPoolId:"",identityPoolId:"",...r.Auth?.Cognito,loginWith:{oauth:{domain:"",scopes:[],responseType:"code",...r.Auth?.Cognito?.loginWith?.oauth,redirectSignIn:[window.location.origin+n.settings?.signInPage],redirectSignOut:[window.location.origin+n.settings?.signInPage]}}}},API:{...r.API,REST:{...r.API?.REST,admin:{endpoint:n.restUrl}}}},g=e?.apiConfigurations?.secondary?.domains&&t.toLowerCase().match(e.apiConfigurations.secondary?.domains.toLowerCase())&&e.apiConfigurations?.secondary?.apis?.length?e.apiConfigurations.secondary:e?.apiConfigurations?.default;g?.apis?.forEach(i=>{let s=o.API?.REST;s&&(s[i.name]={endpoint:i.endpoint,region:i.region})}),h(o,{API:{REST:{headers:async i=>{let s=g?.apis?.find(u=>u.name===i.apiName);if(i.apiName==="admin"||s?.authorization==="ID_TOKEN"||s?.authorization==="ACCESS_TOKEN")try{let u=await d();if(u?.tokens?.idToken&&u?.tokens?.accessToken)return{Authorization:`Bearer ${i.apiName==="admin"||s?.authorization==="ID_TOKEN"?u.tokens.idToken.toString():u.tokens.accessToken.toString()}`}}catch(u){console.error(u),c().then(B=>{p(B).clearAccount()})}return{}}}}})},Q=async()=>{let e=a();if(!e)throw new Error("Gatey plugin is not available");let t=null;return e.settings.customTranslationsUrl&&(t=await fetch(e.settings.customTranslationsUrl+(e.settings.customTranslationsUrl.includes("?")?"&":"?")+"t="+S.lastUpdate).then(n=>n.ok?n.text():null).then(n=>n?JSON.parse(n):null).catch(()=>null)),t??null},Z=async()=>{let e=await H("gatey");$(e);let t=window.location.hostname.toLowerCase().split(":")[0],n=e?.apiConfigurations?.secondary?.domains&&t.toLowerCase().match(e.apiConfigurations.secondary?.domains.toLowerCase())&&e.apiConfigurations?.secondary?.apis?.length?e.apiConfigurations.secondary:e?.apiConfigurations?.default,r=await l(n),o=await Q();return{config:e,amplifyConfig:{},account:r,signedIn:!!r?.username&&!r.loaded,nextUrl:void 0,language:void 0,direction:void 0,customTranslations:o,reloadAuthSession:0,reloadUserAttributes:0,reloadMFAPreferences:0}},ee={setAmplifyConfig(e){return{type:"SET_AMPLIFY_CONFIG",amplifyConfig:e}},setAccount(e){return{type:"SET_ACCOUNT",account:e}},clearAccount(){return{type:"CLEAR_ACCOUNT"}},setSignedIn(e){return{type:"SET_SIGNED_IN",signedIn:e}},setNextUrl(e){return{type:"SET_NEXT_URL",nextUrl:e}},setLanguage(e){return!e||e==="system"?E.setLanguage(""):E.setLanguage(e),{type:"SET_LANGUAGE",language:e}},setDirection(e){return{type:"SET_DIRECTION",direction:e}},reloadAuthSession(){return{type:"RELOAD_AUTH_SESSION"}},reloadUserAttributes(){return{type:"RELOAD_USER_ATTRIBUTES"}},reloadMFAPreferences(){return{type:"RELOAD_MFA_PREFERENCE"}}},te={getAmplifyConfig(e){return e.amplifyConfig},getAccount(e){return e.account},getNextUrl(e){return e.nextUrl},isSignedIn(e){return e.signedIn},getConfig(e){return e.config},getCustomTranslations(e){return e.customTranslations},getLanguage(e){return e.language},getDirection(e){return e.direction},getState(e){return e}},ne={},p=e=>j(e),b=e=>Y(e),x=async()=>{let e=await Z(),t=X("wpsuite/gatey",{reducer(n=e,r){switch(r.type){case"SET_AMPLIFY_CONFIG":return{...n,amplifyConfig:r.amplifyConfig};case"SET_ACCOUNT":return m(r.account),{...n,account:r.account};case"CLEAR_ACCOUNT":return m({}),{...n,account:{}};case"RELOAD_AUTH_SESSION":{let o=Math.random();return{...n,reloadAuthSession:n.reloadAuthSession!==o?o:o+1}}case"RELOAD_USER_ATTRIBUTES":{let o=Math.random();return{...n,reloadUserAttributes:n.reloadUserAttributes!==o?o:o+1}}case"RELOAD_MFA_PREFERENCE":{let o=Math.random();return{...n,reloadMFAPreferences:n.reloadMFAPreferences!==o?o:o+1}}case"SET_SIGNED_IN":return{...n,signedIn:r.signedIn};case"SET_NEXT_URL":return{...n,nextUrl:r.nextUrl};case"SET_LANGUAGE":return{...n,language:r.language};case"SET_DIRECTION":return{...n,direction:r.direction}}return n},actions:ee,selectors:te,resolvers:ne});return J(t),t},A=(e,t,n)=>{let r;function o(){let f=b(e).getState(),i=t(f);if(i!==r){let s=r;r=i,n(r,s)}}let g=q(o,e);return o(),g};var P=()=>U.getConfig(),h=(e,t)=>{U.configure(e,t)},d=e=>I(e),G=()=>oe(),v=()=>re(),R=async(e=!0)=>{let t=e?await l():{};if(t?.username)return t;try{if((await I()).tokens)return{username:(await ie()).username,userAttributes:await G(),mfaPreferences:await v()}}catch(n){console.error(n);try{await O()}catch{}}return{}},F=async()=>{await se({totp:"DISABLED"})},N=()=>l().then(e=>e?.username),L=()=>l().then(e=>e?.userAttributes),_=()=>l().then(e=>e?.mfaPreferences),k=()=>l().then(e=>!!e?.username),D=e=>w().then(t=>t?.includes(e)||!1),w=()=>d().then(e=>e.tokens?.idToken?.payload["cognito:groups"]instanceof Array?e.tokens.idToken.payload["cognito:groups"].map(t=>t):[]).catch(e=>{console.error(e)}),M=async()=>d().then(e=>e.tokens?.idToken?.payload["cognito:roles"]instanceof Array?e.tokens.idToken.payload["cognito:roles"].map(t=>t).map(t=>t.substring(t.indexOf("/")+1)):[]).catch(e=>{console.error(e)}),W=async()=>d().then(e=>{if(!e.tokens?.idToken?.payload["cognito:preferred_role"])return;let t=e.tokens.idToken.payload["cognito:preferred_role"];return t.substring(t.indexOf("/")+1)}).catch(e=>{console.error(e)}),z=()=>d().then(e=>e.tokens?.accessToken.payload.scope?.split(" ")??[]).catch(e=>{console.error(e)}),ae=async e=>{let t,n=a();if(!n)throw new Error("Gatey plugin is not available");return n.settings.integrateWpLogin&&n.restUrl?.startsWith("http")&&(t=await n.cognito.post({apiName:"admin",path:"/login"}).response.then(o=>o.body.json()).then(o=>{if(o instanceof Object&&"redirect"in o)return o?.redirect}).catch(o=>{console.error(o)})),e&&await n.cognito.get({apiName:e.apiName,path:e.path,options:e.options}).response.catch(r=>console.error(r)),n.settings.redirectSignIn??t},C=async e=>{let t=a();if(!t)throw new Error("Gatey plugin is not available");let n;t.settings.integrateWpLogin&&(n=await t.cognito.get({apiName:"admin",path:"/logout"}).response.then(r=>r.body.json()).then(r=>{if(r instanceof Object&&"redirect"in r)return r?.redirect}).catch(r=>{console.error(r)})),e&&await t.cognito.get({apiName:e.apiName,path:e.path,options:e.options}).response.catch(r=>console.error(r));try{await O()}catch{}return t.settings.redirectSignOut??n};import{attachDefaultPluginRuntime as fe}from"@smart-cloud/wpsuite-core";var ye=()=>{c().then(e=>{A(e,t=>t.nextUrl,async t=>{t&&window.location.assign(t)}),p(e).clearAccount()}).catch(e=>{console.error("Gatey signOut error:",e)})},me=e=>{c().then(t=>{p(t).setLanguage(e??"en")}).catch(t=>{console.error("Gatey setLanguage error:",t)})},Ae=e=>{c().then(t=>{p(t).setDirection(e??"auto")}).catch(t=>{console.error("Gatey setDirection error:",t)})};var Me=async()=>c(),We=()=>{let e=globalThis.WpSuite,t=a();if(!t)throw new Error("Gatey plugin is not available");fe(t),t.status=t.status??"initializing";let n=x();return t.cognito={store:n,observeStore:A,setLanguage:me,setDirection:Ae,getAmplifyConfig:P,isAuthenticated:k,isInGroup:D,getUsername:N,getUserAttributes:L,getMfaPreferences:_,clearMfaPreferences:F,getGroups:w,getRoles:M,getPreferredRole:W,getScopes:z,signOut:ye,get:ce,post:pe,put:de,del:ue,head:ge,patch:le},n.then(()=>{t.status="available",e?.events?.emit("wpsuite:gatey:ready",{key:t.key,version:t.version})}).catch(r=>{t.status="error",e?.events?.emit("wpsuite:gatey:error",{key:t.key,error:String(r)})}),t};export{V as TEXT_DOMAIN,F as clearMfaPreferences,h as configureAmplify,P as getAmplifyConfig,a as getGateyPlugin,w as getGroups,_ as getMfaPreferences,W as getPreferredRole,M as getRoles,z as getScopes,c as getStore,p as getStoreDispatch,b as getStoreSelect,L as getUserAttributes,We as initializeGatey,k as isAuthenticated,D as isInGroup,d as loadAuthSession,v as loadMFAPreferences,G as loadUserAttributes,ae as login,C as logout,A as observeStore,Me as store,T as waitForGateyReady};
|
|
1
|
+
import{del as ce,get as ge,head as le,patch as pe,post as de,put as fe}from"aws-amplify/api";function a(){return globalThis.WpSuite?.plugins?.gatey}async function T(e=8e3){let t=a();if(t?.status!=="available"){if(t?.status==="error")throw new Error("Gatey failed");await new Promise((n,r)=>{let o=()=>f(n),g=()=>f(()=>r(new Error("Gatey failed"))),f=s=>{window.removeEventListener("wpsuite:gatey:ready",o),window.removeEventListener("wpsuite:gatey:error",g),i&&clearTimeout(i),s()};window.addEventListener("wpsuite:gatey:ready",o,{once:!0}),window.addEventListener("wpsuite:gatey:error",g,{once:!0});let i=e?window.setTimeout(()=>f(()=>r(new Error("Gatey timeout"))),e):0})}}async function c(e=1e4){await T(e);let n=a()?.cognito?.store;if(!n)throw new Error("Gatey store is not available");return n}import{Amplify as I}from"aws-amplify";import{fetchAuthSession as O,fetchMFAPreference as oe,fetchUserAttributes as ie,getCurrentUser as se,signOut as v,updateMFAPreference as ae}from"aws-amplify/auth";import{fetchAuthSession as j}from"aws-amplify/auth";import{I18n as E}from"aws-amplify/utils";import{createReduxStore as X,dispatch as J,register as Y,select as q,subscribe as H}from"@wordpress/data";import{getConfig as $}from"@smart-cloud/wpsuite-core";var y="gatey_account",K="gatey";var S;typeof WpSuite<"u"?S=WpSuite.siteSettings:S={};var m=e=>{e?.username?window.localStorage.setItem(y,JSON.stringify(e)):window.localStorage.removeItem(y)},l=async e=>{let t=JSON.parse(window.localStorage.getItem(y)??"{}"),n=!1;if(t?.username)try{let r=await j();r?.tokens?.accessToken?.payload?.exp&&r.tokens.accessToken.payload.exp>new Date().getTime()/1e3&&(n=!0)}catch(r){console.error(r)}else try{t=await U(!1),t?.username&&(m(t),t.loaded=!0,n=!0)}catch(r){console.error(r)}return!n&&t?.username&&(m({}),c().then(async r=>{await C(e?.signOutHook),p(r).clearAccount()})),t},Q=async e=>{let t=window.location.hostname.toLowerCase().split(":")[0],n=a();if(!n)throw new Error("Gatey plugin is not available");let r=n.settings?.secondaryUserPoolDomains&&t.toLowerCase().match(n.settings.secondaryUserPoolDomains.toLowerCase())&&n.settings?.userPoolConfigurations.secondary?.Auth?.Cognito?.userPoolId?n.settings?.userPoolConfigurations.secondary:n.settings?.userPoolConfigurations.default,o={Auth:{Cognito:{userPoolClientId:"",userPoolId:"",identityPoolId:"",...r.Auth?.Cognito,loginWith:{oauth:{domain:"",scopes:[],responseType:"code",...r.Auth?.Cognito?.loginWith?.oauth,redirectSignIn:[window.location.origin+n.settings?.signInPage],redirectSignOut:[window.location.origin+n.settings?.signInPage]}}}},API:{...r.API,REST:{...r.API?.REST,admin:{endpoint:n.restUrl}}}},g=e?.apiConfigurations?.secondary?.domains&&t.toLowerCase().match(e.apiConfigurations.secondary?.domains.toLowerCase())&&e.apiConfigurations?.secondary?.apis?.length?e.apiConfigurations.secondary:e?.apiConfigurations?.default;g?.apis?.forEach(i=>{let s=o.API?.REST;s&&(s[i.name]={endpoint:i.endpoint,region:i.region})}),h(o,{API:{REST:{headers:async i=>{let s=g?.apis?.find(u=>u.name===i.apiName);if(i.apiName==="admin"||s?.authorization==="ID_TOKEN"||s?.authorization==="ACCESS_TOKEN")try{let u=await d();if(u?.tokens?.idToken&&u?.tokens?.accessToken)return{Authorization:`Bearer ${i.apiName==="admin"||s?.authorization==="ID_TOKEN"?u.tokens.idToken.toString():u.tokens.accessToken.toString()}`}}catch(u){console.error(u),c().then(V=>{p(V).clearAccount()})}return{}}}}})},Z=async()=>{let e=a();if(!e)throw new Error("Gatey plugin is not available");let t=null;return e.settings.customTranslationsUrl&&(t=await fetch(e.settings.customTranslationsUrl+(e.settings.customTranslationsUrl.includes("?")?"&":"?")+"t="+S.lastUpdate).then(n=>n.ok?n.text():null).then(n=>n?JSON.parse(n):null).catch(()=>null)),t??null},b=e=>{let t=e&&typeof e=="object"?e:{},n={customProviders:Array.isArray(t.customProviders)?t.customProviders:[],formFields:Array.isArray(t.formFields)?t.formFields:[],apiConfigurations:typeof t.apiConfigurations=="object"&&t.apiConfigurations?t.apiConfigurations:{default:{apis:[]}}};return typeof t.subscriptionType=="string"&&(n.subscriptionType=t.subscriptionType),n},ee=async()=>{let e=b(await $("gatey"));Q(e);let t=window.location.hostname.toLowerCase().split(":")[0],n=e?.apiConfigurations?.secondary?.domains&&t.toLowerCase().match(e.apiConfigurations.secondary?.domains.toLowerCase())&&e.apiConfigurations?.secondary?.apis?.length?e.apiConfigurations.secondary:e?.apiConfigurations?.default,r=await l(n),o=await Z();return{config:e,amplifyConfig:{},account:r,signedIn:!!r?.username&&!r.loaded,nextUrl:void 0,language:void 0,direction:void 0,customTranslations:o,reloadAuthSession:0,reloadUserAttributes:0,reloadMFAPreferences:0}},te={setAmplifyConfig(e){return{type:"SET_AMPLIFY_CONFIG",amplifyConfig:e}},setAccount(e){return{type:"SET_ACCOUNT",account:e}},clearAccount(){return{type:"CLEAR_ACCOUNT"}},setSignedIn(e){return{type:"SET_SIGNED_IN",signedIn:e}},setNextUrl(e){return{type:"SET_NEXT_URL",nextUrl:e}},setLanguage(e){return!e||e==="system"?E.setLanguage(""):E.setLanguage(e),{type:"SET_LANGUAGE",language:e}},setDirection(e){return{type:"SET_DIRECTION",direction:e}},reloadAuthSession(){return{type:"RELOAD_AUTH_SESSION"}},reloadUserAttributes(){return{type:"RELOAD_USER_ATTRIBUTES"}},reloadMFAPreferences(){return{type:"RELOAD_MFA_PREFERENCE"}}},ne={getAmplifyConfig(e){return e.amplifyConfig},getAccount(e){return e.account},getNextUrl(e){return e.nextUrl},isSignedIn(e){return e.signedIn},getConfig(e){return e.config},getCustomTranslations(e){return e.customTranslations},getLanguage(e){return e.language},getDirection(e){return e.direction},getState(e){return e}},re={},p=e=>J(e),x=e=>q(e),R=async()=>{let e=await ee(),t=X("wpsuite/gatey",{reducer(n=e,r){switch(r.type){case"SET_AMPLIFY_CONFIG":return{...n,amplifyConfig:r.amplifyConfig};case"SET_ACCOUNT":return m(r.account),{...n,account:r.account};case"CLEAR_ACCOUNT":return m({}),{...n,account:{}};case"RELOAD_AUTH_SESSION":{let o=Math.random();return{...n,reloadAuthSession:n.reloadAuthSession!==o?o:o+1}}case"RELOAD_USER_ATTRIBUTES":{let o=Math.random();return{...n,reloadUserAttributes:n.reloadUserAttributes!==o?o:o+1}}case"RELOAD_MFA_PREFERENCE":{let o=Math.random();return{...n,reloadMFAPreferences:n.reloadMFAPreferences!==o?o:o+1}}case"SET_SIGNED_IN":return{...n,signedIn:r.signedIn};case"SET_NEXT_URL":return{...n,nextUrl:r.nextUrl};case"SET_LANGUAGE":return{...n,language:r.language};case"SET_DIRECTION":return{...n,direction:r.direction}}return n},actions:te,selectors:ne,resolvers:re});return Y(t),t},A=(e,t,n)=>{let r;function o(){let f=x(e).getState(),i=t(f);if(i!==r){let s=r;r=i,n(r,s)}}let g=H(o,e);return o(),g};var P=()=>I.getConfig(),h=(e,t)=>{I.configure(e,t)},d=e=>O(e),F=()=>ie(),G=()=>oe(),U=async(e=!0)=>{let t=e?await l():{};if(t?.username)return t;try{if((await O()).tokens)return{username:(await se()).username,userAttributes:await F(),mfaPreferences:await G()}}catch(n){console.error(n);try{await v()}catch{}}return{}},N=async()=>{await ae({totp:"DISABLED"})},L=()=>l().then(e=>e?.username),_=()=>l().then(e=>e?.userAttributes),k=()=>l().then(e=>e?.mfaPreferences),D=()=>l().then(e=>!!e?.username),M=e=>w().then(t=>t?.includes(e)||!1),w=()=>d().then(e=>e.tokens?.idToken?.payload["cognito:groups"]instanceof Array?e.tokens.idToken.payload["cognito:groups"].map(t=>t):[]).catch(e=>{console.error(e)}),W=async()=>d().then(e=>e.tokens?.idToken?.payload["cognito:roles"]instanceof Array?e.tokens.idToken.payload["cognito:roles"].map(t=>t).map(t=>t.substring(t.indexOf("/")+1)):[]).catch(e=>{console.error(e)}),z=async()=>d().then(e=>{if(!e.tokens?.idToken?.payload["cognito:preferred_role"])return;let t=e.tokens.idToken.payload["cognito:preferred_role"];return t.substring(t.indexOf("/")+1)}).catch(e=>{console.error(e)}),B=()=>d().then(e=>e.tokens?.accessToken.payload.scope?.split(" ")??[]).catch(e=>{console.error(e)}),ue=async e=>{let t,n=a();if(!n)throw new Error("Gatey plugin is not available");return n.settings.integrateWpLogin&&n.restUrl?.startsWith("http")&&(t=await n.cognito.post({apiName:"admin",path:"/login"}).response.then(o=>o.body.json()).then(o=>{if(o instanceof Object&&"redirect"in o)return o?.redirect}).catch(o=>{console.error(o)})),e&&await n.cognito.get({apiName:e.apiName,path:e.path,options:e.options}).response.catch(r=>console.error(r)),n.settings.redirectSignIn??t},C=async e=>{let t=a();if(!t)throw new Error("Gatey plugin is not available");let n;t.settings.integrateWpLogin&&(n=await t.cognito.get({apiName:"admin",path:"/logout"}).response.then(r=>r.body.json()).then(r=>{if(r instanceof Object&&"redirect"in r)return r?.redirect}).catch(r=>{console.error(r)})),e&&await t.cognito.get({apiName:e.apiName,path:e.path,options:e.options}).response.catch(r=>console.error(r));try{await v()}catch{}return t.settings.redirectSignOut??n};import{attachDefaultPluginRuntime as ye}from"@smart-cloud/wpsuite-core";var me=()=>{c().then(e=>{A(e,t=>t.nextUrl,async t=>{t&&window.location.assign(t)}),p(e).clearAccount()}).catch(e=>{console.error("Gatey signOut error:",e)})},Ae=e=>{c().then(t=>{p(t).setLanguage(e??"en")}).catch(t=>{console.error("Gatey setLanguage error:",t)})},Se=e=>{c().then(t=>{p(t).setDirection(e??"auto")}).catch(t=>{console.error("Gatey setDirection error:",t)})};var We=async()=>c(),ze=()=>{let e=globalThis.WpSuite,t=a();if(!t)throw new Error("Gatey plugin is not available");ye(t),t.status=t.status??"initializing";let n=R();return t.cognito={store:n,observeStore:A,setLanguage:Ae,setDirection:Se,getAmplifyConfig:P,isAuthenticated:D,isInGroup:M,getUsername:L,getUserAttributes:_,getMfaPreferences:k,clearMfaPreferences:N,getGroups:w,getRoles:W,getPreferredRole:z,getScopes:B,signOut:me,get:ge,post:de,put:fe,del:ce,head:le,patch:pe},n.then(()=>{t.status="available",e?.events?.emit("wpsuite:gatey:ready",{key:t.key,version:t.version})}).catch(r=>{t.status="error",e?.events?.emit("wpsuite:gatey:error",{key:t.key,error:String(r)})}),t};export{K as TEXT_DOMAIN,N as clearMfaPreferences,h as configureAmplify,P as getAmplifyConfig,a as getGateyPlugin,w as getGroups,k as getMfaPreferences,z as getPreferredRole,W as getRoles,B as getScopes,c as getStore,p as getStoreDispatch,x as getStoreSelect,_ as getUserAttributes,ze as initializeGatey,D as isAuthenticated,M as isInGroup,d as loadAuthSession,G as loadMFAPreferences,F as loadUserAttributes,ue as login,C as logout,A as observeStore,b as sanitizeAuthenticatorConfig,We as store,T as waitForGateyReady};
|