@smart-cloud/gatey-core 1.0.14 → 2.0.0

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 CHANGED
@@ -1 +1 @@
1
- "use strict";var P=Object.defineProperty;var J=Object.getOwnPropertyDescriptor;var Y=Object.getOwnPropertyNames;var q=Object.prototype.hasOwnProperty;var H=(e,t)=>{for(var n in t)P(e,n,{get:t[n],enumerable:!0})},$=(e,t,n,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of Y(t))!q.call(e,r)&&r!==n&&P(e,r,{get:()=>t[r],enumerable:!(o=J(t,r))||o.enumerable});return e};var Q=e=>$(P({},"__esModule",{value:!0}),e);var ce={};H(ce,{TEXT_DOMAIN:()=>D,clearMfaPreferences:()=>O,configureAmplify:()=>A,getAmplifyConfig:()=>h,getGroups:()=>C,getMfaPreferences:()=>w,getPreferredRole:()=>_,getRoles:()=>F,getScopes:()=>L,getStoreDispatch:()=>l,getStoreSelect:()=>x,getUserAttributes:()=>R,isAuthenticated:()=>N,isInGroup:()=>G,loadAuthSession:()=>p,loadMFAPreferences:()=>I,loadUserAttributes:()=>E,login:()=>K,logout:()=>S,observeStore:()=>f,store:()=>j});module.exports=Q(ce);var s=require("aws-amplify/api");var U=require("aws-amplify"),i=require("aws-amplify/auth");var k=require("aws-amplify/auth"),T=require("aws-amplify/utils"),c=require("@wordpress/data"),v=require("@smart-cloud/wpsuite-core");var y="gatey_account",D="gatey";var b;typeof WpSuite<"u"?b=WpSuite.siteSettings:b={};var m=e=>{e?.username?window.localStorage.setItem(y,JSON.stringify(e)):window.localStorage.removeItem(y)},d=async e=>{let t=JSON.parse(window.localStorage.getItem(y)??"{}"),n=!1;if(t?.username)try{let o=await(0,k.fetchAuthSession)();o?.tokens?.accessToken?.payload?.exp&&o.tokens.accessToken.payload.exp>new Date().getTime()/1e3&&(n=!0)}catch(o){console.error(o)}else try{t=await V(!1),t?.username&&(m(t),t.loaded=!0,n=!0)}catch(o){console.error(o)}return!n&&t?.username&&(m({}),Gatey.cognito.store.then(async o=>{await S(e?.signOutHook),l(o).clearAccount()})),t},Z=async e=>{let t=window.location.hostname.toLowerCase().split(":")[0],n=Gatey.settings?.secondaryUserPoolDomains&&t.toLowerCase().match(Gatey.settings.secondaryUserPoolDomains.toLowerCase())&&Gatey.settings?.userPoolConfigurations.secondary?.Auth?.Cognito?.userPoolId?Gatey.settings?.userPoolConfigurations.secondary:Gatey.settings?.userPoolConfigurations.default,o={Auth:{Cognito:{userPoolClientId:"",userPoolId:"",identityPoolId:"",...n.Auth?.Cognito,loginWith:{oauth:{domain:"",scopes:[],responseType:"code",...n.Auth?.Cognito?.loginWith?.oauth,redirectSignIn:[window.location.origin+Gatey?.settings?.signInPage],redirectSignOut:[window.location.origin+Gatey?.settings?.signInPage]}}}},API:{...n.API,REST:{...n.API?.REST,admin:{endpoint:Gatey.restUrl}}}},r=e?.apiConfigurations?.secondary?.domains&&t.toLowerCase().match(e.apiConfigurations.secondary?.domains.toLowerCase())&&e.apiConfigurations?.secondary?.apis?.length?e.apiConfigurations.secondary:e?.apiConfigurations?.default;r?.apis?.forEach(u=>{let g=o.API?.REST;g&&(g[u.name]={endpoint:u.endpoint,region:u.region})}),A(o,{API:{REST:{headers:async u=>{let g=r?.apis?.find(a=>a.name===u.apiName);if(u.apiName==="admin"||g?.authorization==="ID_TOKEN"||g?.authorization==="ACCESS_TOKEN")try{let a=await p();if(a?.tokens?.idToken&&a?.tokens?.accessToken)return{Authorization:`Bearer ${u.apiName==="admin"||g?.authorization==="ID_TOKEN"?a.tokens.idToken.toString():a.tokens.accessToken.toString()}`}}catch(a){console.error(a),Gatey.cognito.store.then(X=>{l(X).clearAccount()})}return{}}}}})},ee=async()=>{let e=null;return Gatey.settings.customTranslationsUrl&&(e=await fetch(Gatey.settings.customTranslationsUrl+(Gatey.settings.customTranslationsUrl.includes("?")?"&":"?")+"t="+b.lastUpdate).then(t=>t.ok?t.text():null).then(t=>t?JSON.parse(t):null).catch(()=>null)),e??null},te=async()=>{let e=await(0,v.getConfig)("gatey");Z(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,o=await d(n),r=await ee();return{config:e,amplifyConfig:{},account:o,signedIn:!!o?.username&&!o.loaded,nextUrl:void 0,language:void 0,direction:void 0,customTranslations:r,reloadAuthSession:0,reloadUserAttributes:0,reloadMFAPreferences:0}},ne={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"?T.I18n.setLanguage(""):T.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"}}},oe={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={},l=e=>(0,c.dispatch)(e),x=e=>(0,c.select)(e),W=async()=>{let e=await te(),t=(0,c.createReduxStore)("wpsuite/gatey",{reducer(n=e,o){switch(o.type){case"SET_AMPLIFY_CONFIG":return{...n,amplifyConfig:o.amplifyConfig};case"SET_ACCOUNT":return m(o.account),{...n,account:o.account};case"CLEAR_ACCOUNT":return m({}),{...n,account:{}};case"RELOAD_AUTH_SESSION":{let r=Math.random();return{...n,reloadAuthSession:n.reloadAuthSession!==r?r:r+1}}case"RELOAD_USER_ATTRIBUTES":{let r=Math.random();return{...n,reloadUserAttributes:n.reloadUserAttributes!==r?r:r+1}}case"RELOAD_MFA_PREFERENCE":{let r=Math.random();return{...n,reloadMFAPreferences:n.reloadMFAPreferences!==r?r:r+1}}case"SET_SIGNED_IN":return{...n,signedIn:o.signedIn};case"SET_NEXT_URL":return{...n,nextUrl:o.nextUrl};case"SET_LANGUAGE":return{...n,language:o.language};case"SET_DIRECTION":return{...n,direction:o.direction}}return n},actions:ne,selectors:oe,resolvers:re});return(0,c.register)(t),t},f=(e,t,n)=>{let o;function r(){let u=x(e).getState(),g=t(u);if(g!==o){let a=o;o=g,n(o,a)}}let M=(0,c.subscribe)(r,e);return r(),M};var h=()=>U.Amplify.getConfig(),A=(e,t)=>{U.Amplify.configure(e,t)},p=e=>(0,i.fetchAuthSession)(e),E=()=>(0,i.fetchUserAttributes)(),I=()=>(0,i.fetchMFAPreference)(),V=async(e=!0)=>{let t=e?await d():{};if(t?.username)return t;try{if((await(0,i.fetchAuthSession)()).tokens)return{username:(await(0,i.getCurrentUser)()).username,userAttributes:await E(),mfaPreferences:await I()}}catch(n){console.error(n);try{await(0,i.signOut)()}catch{}}return{}},O=async()=>{await(0,i.updateMFAPreference)({totp:"DISABLED"})},z=()=>d().then(e=>e?.username),R=()=>d().then(e=>e?.userAttributes),w=()=>d().then(e=>e?.mfaPreferences),N=()=>d().then(e=>!!e?.username),G=e=>C().then(t=>t?.includes(e)||!1),C=()=>p().then(e=>e.tokens?.idToken?.payload["cognito:groups"]instanceof Array?e.tokens.idToken.payload["cognito:groups"].map(t=>t):[]).catch(e=>{console.error(e)}),F=async()=>p().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)}),_=async()=>p().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)}),L=()=>p().then(e=>e.tokens?.accessToken.payload.scope?.split(" ")??[]).catch(e=>{console.error(e)}),K=async e=>{let t;return Gatey.settings.integrateWpLogin&&Gatey.restUrl?.startsWith("http")&&(t=await Gatey.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 Gatey.cognito.get({apiName:e.apiName,path:e.path,options:e.options}).response.catch(n=>console.error(n)),Gatey.settings.redirectSignIn??t},S=async e=>{let t;Gatey.settings.integrateWpLogin&&(t=await Gatey.cognito.get({apiName:"admin",path:"/logout"}).response.then(n=>n.body.json()).then(n=>{if(n instanceof Object&&"redirect"in n)return n?.redirect}).catch(n=>{console.error(n)})),e&&await Gatey.cognito.get({apiName:e.apiName,path:e.path,options:e.options}).response.catch(n=>console.error(n));try{await(0,i.signOut)()}catch{}return Gatey.settings.redirectSignOut??t};var ie=()=>{Gatey.cognito.store.then(e=>{f(e,t=>t.nextUrl,async t=>{t&&window.location.assign(t)}),l(e).clearAccount()})},se=e=>{Gatey.cognito.store.then(t=>{l(t).setLanguage(e??"en")})},ae=e=>{Gatey.cognito.store.then(t=>{l(t).setDirection(e??"auto")})};var B=!!Gatey.cognito?.store,j=Gatey.cognito?.store??W();B||(Gatey.cognito={store:j,observeStore:f,setLanguage:se,setDirection:ae,getAmplifyConfig:h,isAuthenticated:N,isInGroup:G,getUsername:z,getUserAttributes:R,getMfaPreferences:w,clearMfaPreferences:O,getGroups:C,getRoles:F,getPreferredRole:_,getScopes:L,signOut:ie,get:s.get,post:s.post,put:s.put,del:s.del,head:s.head,patch:s.patch});B=!0;0&&(module.exports={TEXT_DOMAIN,clearMfaPreferences,configureAmplify,getAmplifyConfig,getGroups,getMfaPreferences,getPreferredRole,getRoles,getScopes,getStoreDispatch,getStoreSelect,getUserAttributes,isAuthenticated,isInGroup,loadAuthSession,loadMFAPreferences,loadUserAttributes,login,logout,observeStore,store});
1
+ "use strict";var b=Object.defineProperty;var q=Object.getOwnPropertyDescriptor;var H=Object.getOwnPropertyNames;var $=Object.prototype.hasOwnProperty;var Q=(e,t)=>{for(var n in t)b(e,n,{get:t[n],enumerable:!0})},Z=(e,t,n,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of H(t))!$.call(e,r)&&r!==n&&b(e,r,{get:()=>t[r],enumerable:!(o=q(t,r))||o.enumerable});return e};var ee=e=>Z(b({},"__esModule",{value:!0}),e);var le={};Q(le,{TEXT_DOMAIN:()=>B,clearMfaPreferences:()=>N,configureAmplify:()=>P,getAmplifyConfig:()=>T,getGateyPlugin:()=>c,getGroups:()=>E,getMfaPreferences:()=>L,getPreferredRole:()=>k,getRoles:()=>M,getScopes:()=>W,getStore:()=>p,getStoreDispatch:()=>d,getStoreSelect:()=>I,getUserAttributes:()=>v,initializeGatey:()=>ge,isAuthenticated:()=>_,isInGroup:()=>D,loadAuthSession:()=>f,loadMFAPreferences:()=>F,loadUserAttributes:()=>G,login:()=>J,logout:()=>w,observeStore:()=>S,waitForGateyReady:()=>x});module.exports=ee(le);var a=require("aws-amplify/api");function c(){return globalThis.WpSuite?.plugins?.gatey}async function x(e=8e3){let t=c();if(t?.status!=="available"){if(t?.status==="error")throw new Error("Gatey failed");await new Promise((n,o)=>{let r=()=>A(n),y=()=>A(()=>o(new Error("Gatey failed"))),A=u=>{window.removeEventListener("wpsuite:gatey:ready",r),window.removeEventListener("wpsuite:gatey:error",y),s&&clearTimeout(s),u()};window.addEventListener("wpsuite:gatey:ready",r,{once:!0}),window.addEventListener("wpsuite:gatey:error",y,{once:!0});let s=e?window.setTimeout(()=>A(()=>o(new Error("Gatey timeout"))),e):0})}}async function p(e=1e4){await x(e);let n=c()?.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 V=require("aws-amplify/auth"),R=require("aws-amplify/utils"),g=require("@wordpress/data"),z=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 o=await(0,V.fetchAuthSession)();o?.tokens?.accessToken?.payload?.exp&&o.tokens.accessToken.payload.exp>new Date().getTime()/1e3&&(n=!0)}catch(o){console.error(o)}else try{t=await X(!1),t?.username&&(C(t),t.loaded=!0,n=!0)}catch(o){console.error(o)}return!n&&t?.username&&(C({}),p().then(async o=>{await w(e?.signOutHook),d(o).clearAccount()})),t},te=async e=>{let t=window.location.hostname.toLowerCase().split(":")[0],n=c();if(!n)throw new Error("Gatey plugin is not available");let o=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,r={Auth:{Cognito:{userPoolClientId:"",userPoolId:"",identityPoolId:"",...o.Auth?.Cognito,loginWith:{oauth:{domain:"",scopes:[],responseType:"code",...o.Auth?.Cognito?.loginWith?.oauth,redirectSignIn:[window.location.origin+n.settings?.signInPage],redirectSignOut:[window.location.origin+n.settings?.signInPage]}}}},API:{...o.API,REST:{...o.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 u=r.API?.REST;u&&(u[s.name]={endpoint:s.endpoint,region:s.region})}),P(r,{API:{REST:{headers:async s=>{let u=y?.apis?.find(l=>l.name===s.apiName);if(s.apiName==="admin"||u?.authorization==="ID_TOKEN"||u?.authorization==="ACCESS_TOKEN")try{let l=await f();if(l?.tokens?.idToken&&l?.tokens?.accessToken)return{Authorization:`Bearer ${s.apiName==="admin"||u?.authorization==="ID_TOKEN"?l.tokens.idToken.toString():l.tokens.accessToken.toString()}`}}catch(l){console.error(l),p().then(Y=>{d(Y).clearAccount()})}return{}}}}})},ne=async()=>{let e=c();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,z.getConfig)("gatey");te(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,o=await m(n),r=await ne();return{config:e,amplifyConfig:{},account:o,signedIn:!!o?.username&&!o.loaded,nextUrl:void 0,language:void 0,direction:void 0,customTranslations:r,reloadAuthSession:0,reloadUserAttributes:0,reloadMFAPreferences:0}},re={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"}}},ie={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}},se={},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,o){switch(o.type){case"SET_AMPLIFY_CONFIG":return{...n,amplifyConfig:o.amplifyConfig};case"SET_ACCOUNT":return C(o.account),{...n,account:o.account};case"CLEAR_ACCOUNT":return C({}),{...n,account:{}};case"RELOAD_AUTH_SESSION":{let r=Math.random();return{...n,reloadAuthSession:n.reloadAuthSession!==r?r:r+1}}case"RELOAD_USER_ATTRIBUTES":{let r=Math.random();return{...n,reloadUserAttributes:n.reloadUserAttributes!==r?r:r+1}}case"RELOAD_MFA_PREFERENCE":{let r=Math.random();return{...n,reloadMFAPreferences:n.reloadMFAPreferences!==r?r:r+1}}case"SET_SIGNED_IN":return{...n,signedIn:o.signedIn};case"SET_NEXT_URL":return{...n,nextUrl:o.nextUrl};case"SET_LANGUAGE":return{...n,language:o.language};case"SET_DIRECTION":return{...n,direction:o.direction}}return n},actions:re,selectors:ie,resolvers:se});return(0,g.register)(t),t},S=(e,t,n)=>{let o;function r(){let A=I(e).getState(),s=t(A);if(s!==o){let u=o;o=s,n(o,u)}}let y=(0,g.subscribe)(r,e);return r(),y};var T=()=>O.Amplify.getConfig(),P=(e,t)=>{O.Amplify.configure(e,t)},f=e=>(0,i.fetchAuthSession)(e),G=()=>(0,i.fetchUserAttributes)(),F=()=>(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 F()}}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),v=()=>m().then(e=>e?.userAttributes),L=()=>m().then(e=>e?.mfaPreferences),_=()=>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)}),k=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=c();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(r=>r.body.json()).then(r=>{if(r instanceof Object&&"redirect"in r)return r?.redirect}).catch(r=>{console.error(r)})),e&&await n.cognito.get({apiName:e.apiName,path:e.path,options:e.options}).response.catch(o=>console.error(o)),n.settings.redirectSignIn??t},w=async e=>{let t=c();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(o=>o.body.json()).then(o=>{if(o instanceof Object&&"redirect"in o)return o?.redirect}).catch(o=>{console.error(o)})),e&&await t.cognito.get({apiName:e.apiName,path:e.path,options:e.options}).response.catch(o=>console.error(o));try{await(0,i.signOut)()}catch{}return t.settings.redirectSignOut??n};var ae=()=>{p().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=>{p().then(t=>{d(t).setLanguage(e??"en")}).catch(t=>{console.error("Gatey setLanguage error:",t)})},ue=e=>{p().then(t=>{d(t).setDirection(e??"auto")}).catch(t=>{console.error("Gatey setDirection error:",t)})};var ge=()=>{c().cognito={store:K(),observeStore:S,setLanguage:ce,setDirection:ue,getAmplifyConfig:T,isAuthenticated:_,isInGroup:D,getUsername:j,getUserAttributes:v,getMfaPreferences:L,clearMfaPreferences:N,getGroups:E,getRoles:M,getPreferredRole:k,getScopes:W,signOut:ae,get:a.get,post:a.post,put:a.put,del:a.del,head:a.head,patch:a.patch}};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,waitForGateyReady});
package/dist/index.d.cts CHANGED
@@ -1,9 +1,63 @@
1
1
  import { FormFieldOptionValue, LoginMechanism, SignUpAttribute, SocialProvider } from '@aws-amplify/ui';
2
2
  import { ResourcesConfig } from 'aws-amplify';
3
3
  import { get, post, put, del, head, patch } from 'aws-amplify/api';
4
- import { FetchMFAPreferenceOutput, FetchUserAttributesOutput, FetchAuthSessionOptions, AuthSession } from 'aws-amplify/auth';
4
+ import { WpSuitePluginBase, SubscriptionType } from '@smart-cloud/wpsuite-core';
5
+ import { FetchUserAttributesOutput, FetchMFAPreferenceOutput, FetchAuthSessionOptions, AuthSession } from 'aws-amplify/auth';
5
6
  import { CustomProvider } from '@aws-amplify/ui-react';
6
- import { StoreDescriptor } from '@wordpress/data';
7
+ import { StoreDescriptor as StoreDescriptor$1 } from '@wordpress/data';
8
+
9
+ /**
10
+ * External dependencies
11
+ */
12
+
13
+ type MapOf<T> = {
14
+ [name: string]: T;
15
+ };
16
+ type ActionCreator = (...args: any[]) => any | Generator;
17
+ type Resolver = Function | Generator;
18
+ type AnyConfig = ReduxStoreConfig<any, any, any>;
19
+ interface StoreInstance<Config extends AnyConfig> {
20
+ getSelectors: () => SelectorsOf<Config>;
21
+ getActions: () => ActionCreatorsOf<Config>;
22
+ subscribe: (listener: () => void) => () => void;
23
+ }
24
+ interface StoreDescriptor<Config extends AnyConfig> {
25
+ /**
26
+ * Store Name
27
+ */
28
+ name: string;
29
+ /**
30
+ * Creates a store instance
31
+ */
32
+ instantiate: (registry: DataRegistry) => StoreInstance<Config>;
33
+ }
34
+ interface ReduxStoreConfig<State, ActionCreators extends MapOf<ActionCreator>, Selectors> {
35
+ initialState?: State;
36
+ reducer: (state: any, action: any) => any;
37
+ actions?: ActionCreators;
38
+ resolvers?: MapOf<Resolver>;
39
+ selectors?: Selectors;
40
+ controls?: MapOf<Function>;
41
+ }
42
+ interface DataRegistry {
43
+ register: (store: StoreDescriptor<any>) => void;
44
+ }
45
+ type ActionCreatorsOf<Config extends AnyConfig> = Config extends ReduxStoreConfig<any, infer ActionCreators, any> ? PromisifiedActionCreators<ActionCreators> : never;
46
+ type PromisifiedActionCreators<ActionCreators extends MapOf<ActionCreator>> = {
47
+ [Action in keyof ActionCreators]: PromisifyActionCreator<ActionCreators[Action]>;
48
+ };
49
+ type PromisifyActionCreator<Action extends ActionCreator> = (...args: Parameters<Action>) => Promise<ReturnType<Action> extends (..._args: any[]) => any ? ThunkReturnType<Action> : ReturnType<Action>>;
50
+ type ThunkReturnType<Action extends ActionCreator> = Awaited<ReturnType<ReturnType<Action>>>;
51
+ type SelectorsOf<Config extends AnyConfig> = Config extends ReduxStoreConfig<any, any, infer Selectors> ? {
52
+ [name in keyof Selectors]: Function;
53
+ } : never;
54
+
55
+ type GateyReadyEvent = "wpsuite:gatey:ready";
56
+ type GateyErrorEvent = "wpsuite:gatey:error";
57
+ type GateyPlugin = WpSuitePluginBase & Gatey;
58
+ declare function getGateyPlugin(): GateyPlugin;
59
+ declare function waitForGateyReady(timeoutMs?: number): Promise<void>;
60
+ declare function getStore(timeoutMs?: number): Promise<StoreDescriptor<any>>;
7
61
 
8
62
  declare const actions: {
9
63
  setAmplifyConfig(amplifyConfig: ResourcesConfig): {
@@ -99,8 +153,7 @@ interface State {
99
153
  reloadUserAttributes: number;
100
154
  reloadMFAPreferences: number;
101
155
  }
102
- type SubscriptionType = "PROFESSIONAL" | "AGENCY";
103
- type Store = StoreDescriptor;
156
+ type Store = StoreDescriptor$1;
104
157
  type StoreSelectors = {
105
158
  getAmplifyConfig(): ResourcesConfig;
106
159
  getAccount(): Account;
@@ -143,9 +196,6 @@ declare const logout: (signOutHook: ApiConfiguration["signOutHook"]) => Promise<
143
196
 
144
197
  declare const TEXT_DOMAIN = "gatey";
145
198
 
146
- declare global {
147
- const Gatey: Gatey;
148
- }
149
199
  interface RoleMapping {
150
200
  cognitoGroup?: string;
151
201
  wordpressRole?: string;
@@ -208,6 +258,6 @@ interface Gatey {
208
258
  restUrl: string;
209
259
  }
210
260
 
211
- declare const store: Promise<Store>;
261
+ declare const initializeGatey: () => void;
212
262
 
213
- export { type Account, type AuthenticatorConfig, type Cognito, type CustomTranslations, type FormField, Gatey, type RoleMapping, type Settings, type State, type Store, type SubscriptionType, TEXT_DOMAIN, clearMfaPreferences, configureAmplify, getAmplifyConfig, getGroups, getMfaPreferences, getPreferredRole, getRoles, getScopes, getStoreDispatch, getStoreSelect, getUserAttributes, isAuthenticated, isInGroup, loadAuthSession, loadMFAPreferences, loadUserAttributes, login, logout, observeStore, store };
263
+ 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, waitForGateyReady };
package/dist/index.d.ts CHANGED
@@ -1,9 +1,63 @@
1
1
  import { FormFieldOptionValue, LoginMechanism, SignUpAttribute, SocialProvider } from '@aws-amplify/ui';
2
2
  import { ResourcesConfig } from 'aws-amplify';
3
3
  import { get, post, put, del, head, patch } from 'aws-amplify/api';
4
- import { FetchMFAPreferenceOutput, FetchUserAttributesOutput, FetchAuthSessionOptions, AuthSession } from 'aws-amplify/auth';
4
+ import { WpSuitePluginBase, SubscriptionType } from '@smart-cloud/wpsuite-core';
5
+ import { FetchUserAttributesOutput, FetchMFAPreferenceOutput, FetchAuthSessionOptions, AuthSession } from 'aws-amplify/auth';
5
6
  import { CustomProvider } from '@aws-amplify/ui-react';
6
- import { StoreDescriptor } from '@wordpress/data';
7
+ import { StoreDescriptor as StoreDescriptor$1 } from '@wordpress/data';
8
+
9
+ /**
10
+ * External dependencies
11
+ */
12
+
13
+ type MapOf<T> = {
14
+ [name: string]: T;
15
+ };
16
+ type ActionCreator = (...args: any[]) => any | Generator;
17
+ type Resolver = Function | Generator;
18
+ type AnyConfig = ReduxStoreConfig<any, any, any>;
19
+ interface StoreInstance<Config extends AnyConfig> {
20
+ getSelectors: () => SelectorsOf<Config>;
21
+ getActions: () => ActionCreatorsOf<Config>;
22
+ subscribe: (listener: () => void) => () => void;
23
+ }
24
+ interface StoreDescriptor<Config extends AnyConfig> {
25
+ /**
26
+ * Store Name
27
+ */
28
+ name: string;
29
+ /**
30
+ * Creates a store instance
31
+ */
32
+ instantiate: (registry: DataRegistry) => StoreInstance<Config>;
33
+ }
34
+ interface ReduxStoreConfig<State, ActionCreators extends MapOf<ActionCreator>, Selectors> {
35
+ initialState?: State;
36
+ reducer: (state: any, action: any) => any;
37
+ actions?: ActionCreators;
38
+ resolvers?: MapOf<Resolver>;
39
+ selectors?: Selectors;
40
+ controls?: MapOf<Function>;
41
+ }
42
+ interface DataRegistry {
43
+ register: (store: StoreDescriptor<any>) => void;
44
+ }
45
+ type ActionCreatorsOf<Config extends AnyConfig> = Config extends ReduxStoreConfig<any, infer ActionCreators, any> ? PromisifiedActionCreators<ActionCreators> : never;
46
+ type PromisifiedActionCreators<ActionCreators extends MapOf<ActionCreator>> = {
47
+ [Action in keyof ActionCreators]: PromisifyActionCreator<ActionCreators[Action]>;
48
+ };
49
+ type PromisifyActionCreator<Action extends ActionCreator> = (...args: Parameters<Action>) => Promise<ReturnType<Action> extends (..._args: any[]) => any ? ThunkReturnType<Action> : ReturnType<Action>>;
50
+ type ThunkReturnType<Action extends ActionCreator> = Awaited<ReturnType<ReturnType<Action>>>;
51
+ type SelectorsOf<Config extends AnyConfig> = Config extends ReduxStoreConfig<any, any, infer Selectors> ? {
52
+ [name in keyof Selectors]: Function;
53
+ } : never;
54
+
55
+ type GateyReadyEvent = "wpsuite:gatey:ready";
56
+ type GateyErrorEvent = "wpsuite:gatey:error";
57
+ type GateyPlugin = WpSuitePluginBase & Gatey;
58
+ declare function getGateyPlugin(): GateyPlugin;
59
+ declare function waitForGateyReady(timeoutMs?: number): Promise<void>;
60
+ declare function getStore(timeoutMs?: number): Promise<StoreDescriptor<any>>;
7
61
 
8
62
  declare const actions: {
9
63
  setAmplifyConfig(amplifyConfig: ResourcesConfig): {
@@ -99,8 +153,7 @@ interface State {
99
153
  reloadUserAttributes: number;
100
154
  reloadMFAPreferences: number;
101
155
  }
102
- type SubscriptionType = "PROFESSIONAL" | "AGENCY";
103
- type Store = StoreDescriptor;
156
+ type Store = StoreDescriptor$1;
104
157
  type StoreSelectors = {
105
158
  getAmplifyConfig(): ResourcesConfig;
106
159
  getAccount(): Account;
@@ -143,9 +196,6 @@ declare const logout: (signOutHook: ApiConfiguration["signOutHook"]) => Promise<
143
196
 
144
197
  declare const TEXT_DOMAIN = "gatey";
145
198
 
146
- declare global {
147
- const Gatey: Gatey;
148
- }
149
199
  interface RoleMapping {
150
200
  cognitoGroup?: string;
151
201
  wordpressRole?: string;
@@ -208,6 +258,6 @@ interface Gatey {
208
258
  restUrl: string;
209
259
  }
210
260
 
211
- declare const store: Promise<Store>;
261
+ declare const initializeGatey: () => void;
212
262
 
213
- export { type Account, type AuthenticatorConfig, type Cognito, type CustomTranslations, type FormField, Gatey, type RoleMapping, type Settings, type State, type Store, type SubscriptionType, TEXT_DOMAIN, clearMfaPreferences, configureAmplify, getAmplifyConfig, getGroups, getMfaPreferences, getPreferredRole, getRoles, getScopes, getStoreDispatch, getStoreSelect, getUserAttributes, isAuthenticated, isInGroup, loadAuthSession, loadMFAPreferences, loadUserAttributes, login, logout, observeStore, store };
263
+ 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, waitForGateyReady };
package/dist/index.js CHANGED
@@ -1 +1 @@
1
- import{del as ie,get as se,head as ae,patch as ce,post as ue,put as ge}from"aws-amplify/api";import{Amplify as x}from"aws-amplify";import{fetchAuthSession as U,fetchUserAttributes as ee,fetchMFAPreference as te,getCurrentUser as ne,signOut as E,updateMFAPreference as oe}from"aws-amplify/auth";import{fetchAuthSession as V}from"aws-amplify/auth";import{I18n as C}from"aws-amplify/utils";import{createReduxStore as z,dispatch as K,register as B,select as j,subscribe as X}from"@wordpress/data";import{getConfig as J}from"@smart-cloud/wpsuite-core";var l="gatey_account",W="gatey";var f;typeof WpSuite<"u"?f=WpSuite.siteSettings:f={};var p=e=>{e?.username?window.localStorage.setItem(l,JSON.stringify(e)):window.localStorage.removeItem(l)},c=async e=>{let t=JSON.parse(window.localStorage.getItem(l)??"{}"),n=!1;if(t?.username)try{let o=await V();o?.tokens?.accessToken?.payload?.exp&&o.tokens.accessToken.payload.exp>new Date().getTime()/1e3&&(n=!0)}catch(o){console.error(o)}else try{t=await b(!1),t?.username&&(p(t),t.loaded=!0,n=!0)}catch(o){console.error(o)}return!n&&t?.username&&(p({}),Gatey.cognito.store.then(async o=>{await m(e?.signOutHook),u(o).clearAccount()})),t},Y=async e=>{let t=window.location.hostname.toLowerCase().split(":")[0],n=Gatey.settings?.secondaryUserPoolDomains&&t.toLowerCase().match(Gatey.settings.secondaryUserPoolDomains.toLowerCase())&&Gatey.settings?.userPoolConfigurations.secondary?.Auth?.Cognito?.userPoolId?Gatey.settings?.userPoolConfigurations.secondary:Gatey.settings?.userPoolConfigurations.default,o={Auth:{Cognito:{userPoolClientId:"",userPoolId:"",identityPoolId:"",...n.Auth?.Cognito,loginWith:{oauth:{domain:"",scopes:[],responseType:"code",...n.Auth?.Cognito?.loginWith?.oauth,redirectSignIn:[window.location.origin+Gatey?.settings?.signInPage],redirectSignOut:[window.location.origin+Gatey?.settings?.signInPage]}}}},API:{...n.API,REST:{...n.API?.REST,admin:{endpoint:Gatey.restUrl}}}},r=e?.apiConfigurations?.secondary?.domains&&t.toLowerCase().match(e.apiConfigurations.secondary?.domains.toLowerCase())&&e.apiConfigurations?.secondary?.apis?.length?e.apiConfigurations.secondary:e?.apiConfigurations?.default;r?.apis?.forEach(s=>{let a=o.API?.REST;a&&(a[s.name]={endpoint:s.endpoint,region:s.region})}),y(o,{API:{REST:{headers:async s=>{let a=r?.apis?.find(i=>i.name===s.apiName);if(s.apiName==="admin"||a?.authorization==="ID_TOKEN"||a?.authorization==="ACCESS_TOKEN")try{let i=await g();if(i?.tokens?.idToken&&i?.tokens?.accessToken)return{Authorization:`Bearer ${s.apiName==="admin"||a?.authorization==="ID_TOKEN"?i.tokens.idToken.toString():i.tokens.accessToken.toString()}`}}catch(i){console.error(i),Gatey.cognito.store.then(v=>{u(v).clearAccount()})}return{}}}}})},q=async()=>{let e=null;return Gatey.settings.customTranslationsUrl&&(e=await fetch(Gatey.settings.customTranslationsUrl+(Gatey.settings.customTranslationsUrl.includes("?")?"&":"?")+"t="+f.lastUpdate).then(t=>t.ok?t.text():null).then(t=>t?JSON.parse(t):null).catch(()=>null)),e??null},H=async()=>{let e=await J("gatey");Y(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,o=await c(n),r=await q();return{config:e,amplifyConfig:{},account:o,signedIn:!!o?.username&&!o.loaded,nextUrl:void 0,language:void 0,direction:void 0,customTranslations:r,reloadAuthSession:0,reloadUserAttributes:0,reloadMFAPreferences:0}},$={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"?C.setLanguage(""):C.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"}}},Q={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}},Z={},u=e=>K(e),P=e=>j(e),T=async()=>{let e=await H(),t=z("wpsuite/gatey",{reducer(n=e,o){switch(o.type){case"SET_AMPLIFY_CONFIG":return{...n,amplifyConfig:o.amplifyConfig};case"SET_ACCOUNT":return p(o.account),{...n,account:o.account};case"CLEAR_ACCOUNT":return p({}),{...n,account:{}};case"RELOAD_AUTH_SESSION":{let r=Math.random();return{...n,reloadAuthSession:n.reloadAuthSession!==r?r:r+1}}case"RELOAD_USER_ATTRIBUTES":{let r=Math.random();return{...n,reloadUserAttributes:n.reloadUserAttributes!==r?r:r+1}}case"RELOAD_MFA_PREFERENCE":{let r=Math.random();return{...n,reloadMFAPreferences:n.reloadMFAPreferences!==r?r:r+1}}case"SET_SIGNED_IN":return{...n,signedIn:o.signedIn};case"SET_NEXT_URL":return{...n,nextUrl:o.nextUrl};case"SET_LANGUAGE":return{...n,language:o.language};case"SET_DIRECTION":return{...n,direction:o.direction}}return n},actions:$,selectors:Q,resolvers:Z});return B(t),t},d=(e,t,n)=>{let o;function r(){let s=P(e).getState(),a=t(s);if(a!==o){let i=o;o=a,n(o,i)}}let h=X(r,e);return r(),h};var A=()=>x.getConfig(),y=(e,t)=>{x.configure(e,t)},g=e=>U(e),I=()=>ee(),O=()=>te(),b=async(e=!0)=>{let t=e?await c():{};if(t?.username)return t;try{if((await U()).tokens)return{username:(await ne()).username,userAttributes:await I(),mfaPreferences:await O()}}catch(n){console.error(n);try{await E()}catch{}}return{}},R=async()=>{await oe({totp:"DISABLED"})},w=()=>c().then(e=>e?.username),N=()=>c().then(e=>e?.userAttributes),G=()=>c().then(e=>e?.mfaPreferences),F=()=>c().then(e=>!!e?.username),_=e=>S().then(t=>t?.includes(e)||!1),S=()=>g().then(e=>e.tokens?.idToken?.payload["cognito:groups"]instanceof Array?e.tokens.idToken.payload["cognito:groups"].map(t=>t):[]).catch(e=>{console.error(e)}),L=async()=>g().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()=>g().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)}),D=()=>g().then(e=>e.tokens?.accessToken.payload.scope?.split(" ")??[]).catch(e=>{console.error(e)}),re=async e=>{let t;return Gatey.settings.integrateWpLogin&&Gatey.restUrl?.startsWith("http")&&(t=await Gatey.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 Gatey.cognito.get({apiName:e.apiName,path:e.path,options:e.options}).response.catch(n=>console.error(n)),Gatey.settings.redirectSignIn??t},m=async e=>{let t;Gatey.settings.integrateWpLogin&&(t=await Gatey.cognito.get({apiName:"admin",path:"/logout"}).response.then(n=>n.body.json()).then(n=>{if(n instanceof Object&&"redirect"in n)return n?.redirect}).catch(n=>{console.error(n)})),e&&await Gatey.cognito.get({apiName:e.apiName,path:e.path,options:e.options}).response.catch(n=>console.error(n));try{await E()}catch{}return Gatey.settings.redirectSignOut??t};var le=()=>{Gatey.cognito.store.then(e=>{d(e,t=>t.nextUrl,async t=>{t&&window.location.assign(t)}),u(e).clearAccount()})},pe=e=>{Gatey.cognito.store.then(t=>{u(t).setLanguage(e??"en")})},de=e=>{Gatey.cognito.store.then(t=>{u(t).setDirection(e??"auto")})};var k=!!Gatey.cognito?.store,fe=Gatey.cognito?.store??T();k||(Gatey.cognito={store:fe,observeStore:d,setLanguage:pe,setDirection:de,getAmplifyConfig:A,isAuthenticated:F,isInGroup:_,getUsername:w,getUserAttributes:N,getMfaPreferences:G,clearMfaPreferences:R,getGroups:S,getRoles:L,getPreferredRole:M,getScopes:D,signOut:le,get:se,post:ue,put:ge,del:ie,head:ae,patch:ce});k=!0;export{W as TEXT_DOMAIN,R as clearMfaPreferences,y as configureAmplify,A as getAmplifyConfig,S as getGroups,G as getMfaPreferences,M as getPreferredRole,L as getRoles,D as getScopes,u as getStoreDispatch,P as getStoreSelect,N as getUserAttributes,F as isAuthenticated,_ as isInGroup,g as loadAuthSession,O as loadMFAPreferences,I as loadUserAttributes,re as login,m as logout,d as observeStore,fe as store};
1
+ import{del as ce,get as ue,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,o)=>{let r=()=>f(n),u=()=>f(()=>o(new Error("Gatey failed"))),f=s=>{window.removeEventListener("wpsuite:gatey:ready",r),window.removeEventListener("wpsuite:gatey:error",u),i&&clearTimeout(i),s()};window.addEventListener("wpsuite:gatey:ready",r,{once:!0}),window.addEventListener("wpsuite:gatey:error",u,{once:!0});let i=e?window.setTimeout(()=>f(()=>o(new Error("Gatey timeout"))),e):0})}}async function g(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 oe,fetchUserAttributes as re,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",z="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 o=await K();o?.tokens?.accessToken?.payload?.exp&&o.tokens.accessToken.payload.exp>new Date().getTime()/1e3&&(n=!0)}catch(o){console.error(o)}else try{t=await R(!1),t?.username&&(m(t),t.loaded=!0,n=!0)}catch(o){console.error(o)}return!n&&t?.username&&(m({}),g().then(async o=>{await C(e?.signOutHook),p(o).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 o=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,r={Auth:{Cognito:{userPoolClientId:"",userPoolId:"",identityPoolId:"",...o.Auth?.Cognito,loginWith:{oauth:{domain:"",scopes:[],responseType:"code",...o.Auth?.Cognito?.loginWith?.oauth,redirectSignIn:[window.location.origin+n.settings?.signInPage],redirectSignOut:[window.location.origin+n.settings?.signInPage]}}}},API:{...o.API,REST:{...o.API?.REST,admin:{endpoint:n.restUrl}}}},u=e?.apiConfigurations?.secondary?.domains&&t.toLowerCase().match(e.apiConfigurations.secondary?.domains.toLowerCase())&&e.apiConfigurations?.secondary?.apis?.length?e.apiConfigurations.secondary:e?.apiConfigurations?.default;u?.apis?.forEach(i=>{let s=r.API?.REST;s&&(s[i.name]={endpoint:i.endpoint,region:i.region})}),h(r,{API:{REST:{headers:async i=>{let s=u?.apis?.find(c=>c.name===i.apiName);if(i.apiName==="admin"||s?.authorization==="ID_TOKEN"||s?.authorization==="ACCESS_TOKEN")try{let c=await d();if(c?.tokens?.idToken&&c?.tokens?.accessToken)return{Authorization:`Bearer ${i.apiName==="admin"||s?.authorization==="ID_TOKEN"?c.tokens.idToken.toString():c.tokens.accessToken.toString()}`}}catch(c){console.error(c),g().then(V=>{p(V).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,o=await l(n),r=await Q();return{config:e,amplifyConfig:{},account:o,signedIn:!!o?.username&&!o.loaded,nextUrl:void 0,language:void 0,direction:void 0,customTranslations:r,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,o){switch(o.type){case"SET_AMPLIFY_CONFIG":return{...n,amplifyConfig:o.amplifyConfig};case"SET_ACCOUNT":return m(o.account),{...n,account:o.account};case"CLEAR_ACCOUNT":return m({}),{...n,account:{}};case"RELOAD_AUTH_SESSION":{let r=Math.random();return{...n,reloadAuthSession:n.reloadAuthSession!==r?r:r+1}}case"RELOAD_USER_ATTRIBUTES":{let r=Math.random();return{...n,reloadUserAttributes:n.reloadUserAttributes!==r?r:r+1}}case"RELOAD_MFA_PREFERENCE":{let r=Math.random();return{...n,reloadMFAPreferences:n.reloadMFAPreferences!==r?r:r+1}}case"SET_SIGNED_IN":return{...n,signedIn:o.signedIn};case"SET_NEXT_URL":return{...n,nextUrl:o.nextUrl};case"SET_LANGUAGE":return{...n,language:o.language};case"SET_DIRECTION":return{...n,direction:o.direction}}return n},actions:ee,selectors:te,resolvers:ne});return J(t),t},A=(e,t,n)=>{let o;function r(){let f=b(e).getState(),i=t(f);if(i!==o){let s=o;o=i,n(o,s)}}let u=q(r,e);return r(),u};var P=()=>U.getConfig(),h=(e,t)=>{U.configure(e,t)},d=e=>I(e),G=()=>re(),F=()=>oe(),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 F()}}catch(n){console.error(n);try{await O()}catch{}}return{}},N=async()=>{await se({totp:"DISABLED"})},v=()=>l().then(e=>e?.username),L=()=>l().then(e=>e?.userAttributes),_=()=>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)}),k=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)}),B=()=>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(r=>r.body.json()).then(r=>{if(r instanceof Object&&"redirect"in r)return r?.redirect}).catch(r=>{console.error(r)})),e&&await n.cognito.get({apiName:e.apiName,path:e.path,options:e.options}).response.catch(o=>console.error(o)),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(o=>o.body.json()).then(o=>{if(o instanceof Object&&"redirect"in o)return o?.redirect}).catch(o=>{console.error(o)})),e&&await t.cognito.get({apiName:e.apiName,path:e.path,options:e.options}).response.catch(o=>console.error(o));try{await O()}catch{}return t.settings.redirectSignOut??n};var fe=()=>{g().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)})},ye=e=>{g().then(t=>{p(t).setLanguage(e??"en")}).catch(t=>{console.error("Gatey setLanguage error:",t)})},me=e=>{g().then(t=>{p(t).setDirection(e??"auto")}).catch(t=>{console.error("Gatey setDirection error:",t)})};var De=()=>{a().cognito={store:x(),observeStore:A,setLanguage:ye,setDirection:me,getAmplifyConfig:P,isAuthenticated:D,isInGroup:M,getUsername:v,getUserAttributes:L,getMfaPreferences:_,clearMfaPreferences:N,getGroups:w,getRoles:k,getPreferredRole:W,getScopes:B,signOut:fe,get:ue,post:pe,put:de,del:ce,head:ge,patch:le}};export{z as TEXT_DOMAIN,N as clearMfaPreferences,h as configureAmplify,P as getAmplifyConfig,a as getGateyPlugin,w as getGroups,_ as getMfaPreferences,W as getPreferredRole,k as getRoles,B as getScopes,g as getStore,p as getStoreDispatch,b as getStoreSelect,L as getUserAttributes,De as initializeGatey,D as isAuthenticated,M as isInGroup,d as loadAuthSession,F as loadMFAPreferences,G as loadUserAttributes,ae as login,C as logout,A as observeStore,T as waitForGateyReady};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@smart-cloud/gatey-core",
3
- "version": "1.0.14",
3
+ "version": "2.0.0",
4
4
  "description": "Login & SSO with Amazon Cognito",
5
5
  "author": "Smart Cloud Solutions Inc.",
6
6
  "license": "MIT",
@@ -22,7 +22,7 @@
22
22
  "scope": "@smart-cloud/gatey-core"
23
23
  },
24
24
  "dependencies": {
25
- "@smart-cloud/wpsuite-core": "^1.0.9"
25
+ "@smart-cloud/wpsuite-core": "^2.0.0"
26
26
  },
27
27
  "peerDependencies": {
28
28
  "@aws-amplify/ui-react": "^6.13.2",
@@ -31,6 +31,7 @@
31
31
  },
32
32
  "devDependencies": {
33
33
  "@aws-amplify/ui-react": "^6.13.2",
34
+ "@eslint/js": "^9.39.2",
34
35
  "@types/node": "^25.0.2",
35
36
  "@typescript-eslint/eslint-plugin": "^8.50.0",
36
37
  "@typescript-eslint/parser": "^8.50.0",