@framerauth/sdk 2.0.3-b → 2.0.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/framerauth.js +1 -1
- package/package.json +3 -3
package/dist/framerauth.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";(()=>{var Pe=Object.defineProperty,Se=Object.defineProperties,ke=Object.getOwnPropertyDescriptors,H=Object.getOwnPropertySymbols,Ee=Object.prototype.hasOwnProperty,Le=Object.prototype.propertyIsEnumerable,q=(t,e,r)=>e in t?Pe(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,T=(t,e)=>{for(var r in e||(e={}))Ee.call(e,r)&&q(t,r,e[r]);if(H)for(var r of H(e))Le.call(e,r)&&q(t,r,e[r]);return t},U=(t,e)=>Se(t,ke(e)),Te=class extends Error{constructor(t,e,r){super(e||t.toString(),{cause:r}),this.status=t,this.statusText=e,this.error=r}},Ue=async(t,e)=>{var r,o,s,a,n,g;let p=e||{},i={onRequest:[e?.onRequest],onResponse:[e?.onResponse],onSuccess:[e?.onSuccess],onError:[e?.onError],onRetry:[e?.onRetry]};if(!e||!e?.plugins)return{url:t,options:p,hooks:i};for(let u of e?.plugins||[]){if(u.init){let b=await((r=u.init)==null?void 0:r.call(u,t.toString(),e));p=b.options||p,t=b.url}i.onRequest.push((o=u.hooks)==null?void 0:o.onRequest),i.onResponse.push((s=u.hooks)==null?void 0:s.onResponse),i.onSuccess.push((a=u.hooks)==null?void 0:a.onSuccess),i.onError.push((n=u.hooks)==null?void 0:n.onError),i.onRetry.push((g=u.hooks)==null?void 0:g.onRetry)}return{url:t,options:p,hooks:i}},J=class{constructor(t){this.options=t}shouldAttemptRetry(t,e){return this.options.shouldRetry?Promise.resolve(t<this.options.attempts&&this.options.shouldRetry(e)):Promise.resolve(t<this.options.attempts)}getDelay(){return this.options.delay}},Ae=class{constructor(t){this.options=t}shouldAttemptRetry(t,e){return this.options.shouldRetry?Promise.resolve(t<this.options.attempts&&this.options.shouldRetry(e)):Promise.resolve(t<this.options.attempts)}getDelay(t){return Math.min(this.options.maxDelay,this.options.baseDelay*2**t)}};function Oe(t){if(typeof t=="number")return new J({type:"linear",attempts:t,delay:1e3});switch(t.type){case"linear":return new J(t);case"exponential":return new Ae(t);default:throw new Error("Invalid retry strategy")}}var xe=async t=>{let e={},r=async o=>typeof o=="function"?await o():o;if(t?.auth){if(t.auth.type==="Bearer"){let o=await r(t.auth.token);if(!o)return e;e.authorization=`Bearer ${o}`}else if(t.auth.type==="Basic"){let o=r(t.auth.username),s=r(t.auth.password);if(!o||!s)return e;e.authorization=`Basic ${btoa(`${o}:${s}`)}`}else if(t.auth.type==="Custom"){let o=r(t.auth.value);if(!o)return e;e.authorization=`${r(t.auth.prefix)} ${o}`}}return e},De=/^application\/(?:[\w!#$%&*.^`~-]*\+)?json(;.+)?$/i;function Ce(t){let e=t.headers.get("content-type"),r=new Set(["image/svg","application/xml","application/xhtml","application/html"]);if(!e)return"json";let o=e.split(";").shift()||"";return De.test(o)?"json":r.has(o)||o.startsWith("text/")?"text":"blob"}function _e(t){try{return JSON.parse(t),!0}catch{return!1}}function V(t){if(t===void 0)return!1;let e=typeof t;return e==="string"||e==="number"||e==="boolean"||e===null?!0:e!=="object"?!1:Array.isArray(t)?!0:t.buffer?!1:t.constructor&&t.constructor.name==="Object"||typeof t.toJSON=="function"}function K(t){try{return JSON.parse(t)}catch{return t}}function G(t){return typeof t=="function"}function Be(t){if(t?.customFetchImpl)return t.customFetchImpl;if(typeof globalThis<"u"&&G(globalThis.fetch))return globalThis.fetch;if(typeof window<"u"&&G(window.fetch))return window.fetch;throw new Error("No fetch implementation found")}async function je(t){let e=new Headers(t?.headers),r=await xe(t);for(let[o,s]of Object.entries(r||{}))e.set(o,s);if(!e.has("content-type")){let o=Fe(t?.body);o&&e.set("content-type",o)}return e}function Fe(t){return V(t)?"application/json":null}function Ne(t){if(!t?.body)return null;let e=new Headers(t?.headers);if(V(t.body)&&!e.has("content-type")){for(let[r,o]of Object.entries(t?.body))o instanceof Date&&(t.body[r]=o.toISOString());return JSON.stringify(t.body)}return t.body}function We(t,e){var r;if(e?.method)return e.method.toUpperCase();if(t.startsWith("@")){let o=(r=t.split("@")[1])==null?void 0:r.split("/")[0];return Y.includes(o)?o.toUpperCase():e?.body?"POST":"GET"}return e?.body?"POST":"GET"}function $e(t,e){let r;return!t?.signal&&t?.timeout&&(r=setTimeout(()=>e?.abort(),t?.timeout)),{abortTimeout:r,clearTimeout:()=>{r&&clearTimeout(r)}}}var Me=class Q extends Error{constructor(e,r){super(r||JSON.stringify(e,null,2)),this.issues=e,Object.setPrototypeOf(this,Q.prototype)}};async function ze(t,e){let r=await t["~standard"].validate(e);if(r.issues)throw new Me(r.issues);return r.value}var Y=["get","post","put","patch","delete"];function Ie(t,e){let{baseURL:r,params:o,query:s}=e||{query:{},params:{},baseURL:""},a=t.startsWith("http")?t.split("/").slice(0,3).join("/"):r||"";if(t.startsWith("@")){let b=t.toString().split("@")[1].split("/")[0];Y.includes(b)&&(t=t.replace(`@${b}/`,"/"))}a.endsWith("/")||(a+="/");let[n,g]=t.replace(a,"").split("?"),p=new URLSearchParams(g);for(let[b,f]of Object.entries(s||{}))f!=null&&p.set(b,String(f));if(o)if(Array.isArray(o)){let b=n.split("/").filter(f=>f.startsWith(":"));for(let[f,N]of b.entries()){let O=o[f];n=n.replace(N,O)}}else for(let[b,f]of Object.entries(o))n=n.replace(`:${b}`,String(f));n=n.split("/").map(encodeURIComponent).join("/"),n.startsWith("/")&&(n=n.slice(1));let i=p.toString();return i=i.length>0?`?${i}`.replace(/\+/g,"%20"):"",a.startsWith("http")?new URL(`${n}${i}`,a):`${a}${n}${i}`}var c=async(t,e)=>{var r,o,s,a,n,g,p,i;let{hooks:u,url:b,options:f}=await Ue(t,e),N=Be(f),O=new AbortController,he=(r=f.signal)!=null?r:O.signal,pe=Ie(b,f),me=Ne(f),ge=await je(f),ye=We(b,f),d=U(T({},f),{url:pe,headers:ge,body:me,method:ye,signal:he});for(let v of u.onRequest)if(v){let y=await v(d);y instanceof Object&&(d=y)}("pipeTo"in d&&typeof d.pipeTo=="function"||typeof((o=e?.body)==null?void 0:o.pipe)=="function")&&("duplex"in d||(d.duplex="half"));let{clearTimeout:be}=$e(f,O),l=await N(d.url,d);be();let z={response:l,request:d};for(let v of u.onResponse)if(v){let y=await v(U(T({},z),{response:(s=e?.hookOptions)!=null&&s.cloneResponse?l.clone():l}));y instanceof Response?l=y:y instanceof Object&&(l=y.response)}if(l.ok){if(!(d.method!=="HEAD"))return{data:"",error:null};let y=Ce(l),k={data:"",response:l,request:d};if(y==="json"||y==="text"){let E=await l.text(),we=await((a=d.jsonParser)!=null?a:K)(E);k.data=we}else k.data=await l[y]();d?.output&&d.output&&!d.disableValidation&&(k.data=await ze(d.output,k.data));for(let E of u.onSuccess)E&&await E(U(T({},k),{response:(n=e?.hookOptions)!=null&&n.cloneResponse?l.clone():l}));return e?.throw?k.data:{data:k.data,error:null}}let ve=(g=e?.jsonParser)!=null?g:K,x=await l.text(),I=_e(x),W=I?await ve(x):null,Re={response:l,responseText:x,request:d,error:U(T({},W),{status:l.status,statusText:l.statusText})};for(let v of u.onError)v&&await v(U(T({},Re),{response:(p=e?.hookOptions)!=null&&p.cloneResponse?l.clone():l}));if(e?.retry){let v=Oe(e.retry),y=(i=e.retryAttempt)!=null?i:0;if(await v.shouldAttemptRetry(y,l)){for(let E of u.onRetry)E&&await E(z);let k=v.getDelay(y);return await new Promise(E=>setTimeout(E,k)),await c(t,U(T({},e),{retryAttempt:y+1}))}}if(e?.throw)throw new Te(l.status,l.statusText,I?W:x);return{data:null,error:U(T({},W),{status:l.status,statusText:l.statusText})}};var D=class{baseURL=null;data;state;api;auth;constructor(e){this.baseURL=null,this.data=e.data,this.state=e.state,this.api={fetchTags:async()=>{if(!this.baseURL)throw new Error("Auth client not initialized");return await c(`${this.baseURL}/profile/tags`,{credentials:"include"})},fetchBookmarks:async()=>{if(!this.baseURL)throw new Error("Auth client not initialized");let r=await c(`${this.baseURL}/profile/bookmarks`,{credentials:"include"});if(!r.data)return r;let o=new Set(r.data),s={};for(let a of o)s[a]=!0;return{data:s,error:null}},fetchProject:async()=>await c("https://core.framerauth.com/v2/public/project/config")},this.auth={getSession:async()=>{if(!this.baseURL)throw new Error("Auth client not initialized");let r=await c(`${this.baseURL}/get-session`,{method:"GET",credentials:"include",query:{disableCookieCache:!0}});return r.data&&(this.data.user.set(r.data.user),this.data.session.set(r.data.session)),r},signUp:async r=>{if(!this.baseURL)throw new Error("Auth client not initialized");let o=await c(`${this.baseURL}/sign-up/email`,{method:"POST",credentials:"include",body:r});if(o.data){await new Promise(n=>setTimeout(n,50)),await this.auth.getSession();let[s,a]=await Promise.all([this.api.fetchTags(),this.api.fetchBookmarks()]);this.data.tags.set(s.data??[]),this.data.bookmarks.set(a.data??{})}return o},signIn:async r=>{if(!this.baseURL)throw new Error("Auth client not initialized");let o=await c(`${this.baseURL}/sign-in/email`,{method:"POST",credentials:"include",body:r});return o.data&&(setTimeout(()=>this.auth.getSession(),10),this.api.fetchTags().then(s=>{this.data.tags.set(s.data??[])}),this.api.fetchBookmarks().then(s=>{this.data.bookmarks.set(s.data??{})})),o},signInSocial:async r=>{if(!this.baseURL)throw new Error("Auth client not initialized");let o=await c(`${this.baseURL}/sign-in/social`,{method:"POST",credentials:"include",body:r});return o.data?.url&&(window.location.href=o.data.url),o},signOut:async r=>{if(!this.baseURL)throw new Error("Auth client not initialized");let o=await c(`${this.baseURL}/sign-out`,{method:"POST",credentials:"include",body:{}});return this.data.user.set(null),this.data.session.set(null),this.data.tags.set([]),this.data.bookmarks.set({}),r?.redirectTo&&(window.location.href=r.redirectTo),o},sendOTP:async r=>{if(!this.baseURL)throw new Error("Auth client not initialized");let o=`${this.baseURL}/email-otp/send-verification-otp`;return await c(o,{body:r,credentials:"include",method:"POST"})},signInOTP:async r=>{if(!this.baseURL)throw new Error("Auth client not initialized");let o=`${this.baseURL}/sign-in/email-otp`,s=await c(o,{body:r,credentials:"include",method:"POST"});return s.error||(this.data.user.set(s.data.user),this.auth.getSession()),s},updateProfile:async r=>{if(!this.baseURL)throw new Error("Auth client not initialized");let o=`${this.baseURL}/profile`;return await c(o,{body:r,credentials:"include",method:"PATCH"})},updateProfilePicture:async r=>{if(!this.baseURL)throw new Error("Auth client not initialized");let o=`${this.baseURL}/profile/avatar`;return await c(o,{method:"POST",body:r,credentials:"include"})},createBookmark:async r=>{if(!this.baseURL)throw new Error("Auth client not initialized");let o=`${this.baseURL}/profile/bookmarks`;return await c(o,{body:r,credentials:"include",method:"POST"})},deleteBookmark:async r=>{if(!this.baseURL)throw new Error("Auth client not initialized");let o=`${this.baseURL}/profile/bookmarks/${r.bookmark_type}/${r.id}`;return await c(o,{credentials:"include",method:"DELETE"})},sendForgotPasswordEmail:async r=>{if(!this.baseURL)throw new Error("Auth client not initialized");let o=`${this.baseURL}/forget-password`;return await c(o,{body:r,credentials:"include",method:"POST"})},resetPassword:async r=>{if(!this.baseURL)throw new Error("Auth client not initialized");let o=`${this.baseURL}/reset-password`;return await c(o,{body:r,credentials:"include",method:"POST"})},storeCheckout:async r=>{if(!this.baseURL)throw new Error("Auth client not initialized");let o=`${this.baseURL}/store/checkout/session`;return await c(o,{body:r,credentials:"include",method:"POST"})}}}updateBaseURL(e){this.baseURL=e}};var R=[],L=0,C=4,He=0,h=t=>{let e=[],r={get(){return r.lc||r.listen(()=>{})(),r.value},lc:0,listen(o){return r.lc=e.push(o),()=>{for(let a=L+C;a<R.length;)R[a]===o?R.splice(a,C):a+=C;let s=e.indexOf(o);~s&&(e.splice(s,1),--r.lc||r.off())}},notify(o,s){He++;let a=!R.length;for(let n of e)R.push(n,r.value,o,s);if(a){for(L=0;L<R.length;L+=C)R[L](R[L+1],R[L+2],R[L+3]);R.length=0}},off(){},set(o){let s=r.value;s!==o&&(r.value=o,r.notify(s))},subscribe(o){let s=r.listen(o);return o(r.value),s},value:t};return r};var qe=5,_=6,B=10,Je=(t,e,r,o)=>(t.events=t.events||{},t.events[r+B]||(t.events[r+B]=o(s=>{t.events[r].reduceRight((a,n)=>(n(a),a),{shared:{},...s})})),t.events[r]=t.events[r]||[],t.events[r].push(e),()=>{let s=t.events[r],a=s.indexOf(e);s.splice(a,1),s.length||(delete t.events[r],t.events[r+B](),delete t.events[r+B])});var X=1e3,$=(t,e)=>Je(t,o=>{let s=e(o);s&&t.events[_].push(s)},qe,o=>{let s=t.listen;t.listen=(...n)=>(!t.lc&&!t.active&&(t.active=!0,o()),s(...n));let a=t.off;return t.events[_]=[],t.off=()=>{a(),setTimeout(()=>{if(t.active&&!t.lc){t.active=!1;for(let n of t.events[_])n();t.events[_]=[]}},X)},()=>{t.listen=s,t.off=a}});var j=(t={})=>{let e=h(t);return e.setKey=function(r,o){let s=e.value;typeof o>"u"&&r in e.value?(e.value={...e.value},delete e.value[r],e.notify(s,r)):e.value[r]!==o&&(e.value={...e.value,[r]:o},e.notify(s,r))},e};var Z=t=>t,A={},M={addEventListener(){},removeEventListener(){}};function Ke(){try{return typeof localStorage<"u"}catch{return!1}}Ke()&&(A=localStorage);var Ge={addEventListener(t,e,r){window.addEventListener("storage",e),window.addEventListener("pageshow",r)},removeEventListener(t,e,r){window.removeEventListener("storage",e),window.removeEventListener("pageshow",r)}};typeof window<"u"&&(M=Ge);function w(t,e=void 0,r={}){let o=r.encode||Z,s=r.decode||Z,a=h(e),n=a.set;a.set=i=>{let u=o(i);typeof u>"u"?delete A[t]:A[t]=u,n(i)};function g(i){i.key===t?i.newValue===null?n(e):n(s(i.newValue)):A[t]||n(e)}function p(){a.set(A[t]?s(A[t]):e)}return $(a,()=>{if(p(),r.listen!==!1)return M.addEventListener(t,g,p),()=>{M.removeEventListener(t,g,p)}}),a}var ee="1f8cXd6c7b4a3vL4z5746oUgQ28190adbef";function te(t){let e="";for(let r=0;r<t.length;r++)e+=String.fromCharCode(t.charCodeAt(r)^ee.charCodeAt(r%ee.length));return e}function P(t){let e=JSON.stringify(t),r=te(e);return btoa(r)}function S(t){try{let e=atob(t),r=te(e);return JSON.parse(r)}catch{return{}}}var re=w("fa-project",null,{encode:P,decode:S}),oe=h(!1);var se=w("fa-tags",[],{encode:P,decode:S}),ae=h(!1);var ne=w("fa-user",null,{encode:P,decode:S}),ie=h(!1);var le=w("fa-session",null,{encode:P,decode:S}),ce=h(!1);var ue=h(!0);var F=class{hasAccess;errorUrl;onError;observer=null;currentCanonical;originalPushState;originalReplaceState;isMonkeyPatched=!1;constructor(e,r,o){this.hasAccess=e,this.errorUrl=r,this.onError=o,this.currentCanonical=this.getCurrentCanonical(),this.originalPushState=history.pushState.bind(history),this.originalReplaceState=history.replaceState.bind(history)}getCurrentCanonical(){return document.querySelector('link[rel="canonical"]')?.href??null}hideBody(){console.log("[Router] Hiding body"),document.body.style.visibility="hidden"}showBody(){console.log("[Router] Showing body"),document.body.style.visibility="visible"}normalizeToPath(e){if(e instanceof URL)return e.pathname;if(e.startsWith("./"))return e.slice(1);if(e.startsWith("/"))return e;try{return new URL(e).pathname}catch{return e.startsWith("/")?e:"/"+e}}async checkAccess(e){console.log("[Router] Checking access for path:",e);try{return await this.hasAccess(e)}catch(r){return console.error("[Router] Error checking access:",r),!1}}redirectToError(){console.log("[Router] Access denied, redirecting to:",this.errorUrl),window.location.replace(this.errorUrl)}handleAccessDenied(e){e&&this.onError&&this.onError(new Error(String(e))),this.redirectToError()}monkeyPatchHistory(){if(this.isMonkeyPatched)return;let e=this;history.pushState=async function(r,o,s){if(s){let a=e.normalizeToPath(s);console.log("[Router] Push state to path:",a);let n=await e.checkAccess(a);console.log("[Router] [push state] Has access:",n),n||(console.warn("Access denied to:",a),e.hideBody())}return e.originalPushState.call(this,r,o,s)},history.replaceState=async function(r,o,s){if(s){let a=e.normalizeToPath(s);console.log("[Router] Replace state with path:",a);let n=await e.checkAccess(a);console.log("[Router] [replace state] Has access:",n),n||(console.warn("Access denied to:",a),e.hideBody())}return e.originalReplaceState.call(this,r,o,s)},this.isMonkeyPatched=!0}restoreHistory(){this.isMonkeyPatched&&(history.pushState=this.originalPushState,history.replaceState=this.originalReplaceState,this.isMonkeyPatched=!1)}start(){console.log("[Router] Starting router"),this.stop(),this.observer=new MutationObserver(e=>{this.handleMutations(e)}),this.observer.observe(document.head,{childList:!0,attributes:!0,attributeFilter:["rel","href"],subtree:!0}),this.monkeyPatchHistory(),console.log("[Router] Router started")}stop(){console.log("[Router] Stopping router"),this.observer&&(this.observer.disconnect(),this.observer=null,console.log("[Router] Router stopped")),this.restoreHistory(),this.showBody()}handleMutations(e){let r=!1;for(let o of e){if(o.type==="childList"){let s=[...Array.from(o.addedNodes),...Array.from(o.removedNodes)];for(let a of s)if(a.nodeType===Node.ELEMENT_NODE){let n=a;if(this.isCanonicalLink(n)){r=!0;break}}}else if(o.type==="attributes"){let s=o.target;(this.isCanonicalLink(s)||o.oldValue==="canonical")&&(r=!0)}if(r)break}r&&this.checkCanonicalChange().catch(o=>{console.error("Error checking canonical change:",o),this.showBody()})}isCanonicalLink(e){return e.tagName==="LINK"&&e.getAttribute("rel")==="canonical"}async checkCanonicalChange(){let e=this.getCurrentCanonical();if(e!==this.currentCanonical)if(this.currentCanonical=e,e){let r=this.normalizeToPath(e);try{if(!await this.checkAccess(r)){console.warn("Access denied to canonical URL:",r),this.redirectToError();return}console.log("[Router] Access granted for:",r),this.showBody()}catch(o){this.handleAccessDenied(o instanceof Error?o:new Error(String(o)))}}else this.showBody()}};var de=w("fa-bookmarks",j(),{encode:P,decode:S}),fe=h(!1);var m=new D({data:{user:ne,project:re,tags:se,bookmarks:de,session:le},state:{initializing:ue,userLoading:ie,projectLoading:oe,tagsLoading:ae,bookmarksLoading:fe,sessionLoading:ce}});window.FramerAuth=m;var Ve=async()=>{m.state.initializing.set(!0);try{let{data:t,error:e}=await m.api.fetchProject();if(e||!t)throw new Error(`Failed to fetch project: ${e?.message||"Project data is null"}`);m.data.project.set(t);let r=`https://${t.slug}.framerauth.io/v2`;m.updateBaseURL(r);let{data:o,error:s}=await m.auth.getSession();if(!s&&o!==null){let{user:a,session:n}=o;if(m.data.user.set(a),m.data.session.set(n),a)try{let[g,p]=await Promise.all([m.api.fetchTags(),m.api.fetchBookmarks()]);m.data.tags.set(g.data??[]),m.data.bookmarks.set(p.data??{})}catch(g){console.warn("Failed to fetch tags or bookmarks:",g),m.data.tags.set([]),m.data.bookmarks.set({})}}return window.dispatchEvent(new CustomEvent("framerauth:initialized")),m}catch(t){throw console.error("Failed to initialize FramerAuth:",t),window.dispatchEvent(new CustomEvent("framerauth:initialization-failed",{detail:{error:t}})),t}finally{m.state.initializing.set(!1)}},Qe=async()=>{try{let t=await Ve();new F(async r=>(console.log("[Router] [Callback] Checking access for:",r),!(!t.data.user.get()&&(r==="/locked"||r==="/blog/diversify-then-focus"))),"/sign-in",r=>{console.error("[Router] Error in router:",r)}).start()}catch(t){console.error("Failed to initialize app:",t)}};Qe();})();
|
|
1
|
+
"use strict";(()=>{var Ee=Object.defineProperty,Le=Object.defineProperties,Te=Object.getOwnPropertyDescriptors,J=Object.getOwnPropertySymbols,Ue=Object.prototype.hasOwnProperty,Ae=Object.prototype.propertyIsEnumerable,K=(t,e,r)=>e in t?Ee(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,T=(t,e)=>{for(var r in e||(e={}))Ue.call(e,r)&&K(t,r,e[r]);if(J)for(var r of J(e))Ae.call(e,r)&&K(t,r,e[r]);return t},U=(t,e)=>Le(t,Te(e)),Oe=class extends Error{constructor(t,e,r){super(e||t.toString(),{cause:r}),this.status=t,this.statusText=e,this.error=r}},xe=async(t,e)=>{var r,o,s,n,a,h;let u=e||{},i={onRequest:[e?.onRequest],onResponse:[e?.onResponse],onSuccess:[e?.onSuccess],onError:[e?.onError],onRetry:[e?.onRetry]};if(!e||!e?.plugins)return{url:t,options:u,hooks:i};for(let d of e?.plugins||[]){if(d.init){let b=await((r=d.init)==null?void 0:r.call(d,t.toString(),e));u=b.options||u,t=b.url}i.onRequest.push((o=d.hooks)==null?void 0:o.onRequest),i.onResponse.push((s=d.hooks)==null?void 0:s.onResponse),i.onSuccess.push((n=d.hooks)==null?void 0:n.onSuccess),i.onError.push((a=d.hooks)==null?void 0:a.onError),i.onRetry.push((h=d.hooks)==null?void 0:h.onRetry)}return{url:t,options:u,hooks:i}},G=class{constructor(t){this.options=t}shouldAttemptRetry(t,e){return this.options.shouldRetry?Promise.resolve(t<this.options.attempts&&this.options.shouldRetry(e)):Promise.resolve(t<this.options.attempts)}getDelay(){return this.options.delay}},De=class{constructor(t){this.options=t}shouldAttemptRetry(t,e){return this.options.shouldRetry?Promise.resolve(t<this.options.attempts&&this.options.shouldRetry(e)):Promise.resolve(t<this.options.attempts)}getDelay(t){return Math.min(this.options.maxDelay,this.options.baseDelay*2**t)}};function Ce(t){if(typeof t=="number")return new G({type:"linear",attempts:t,delay:1e3});switch(t.type){case"linear":return new G(t);case"exponential":return new De(t);default:throw new Error("Invalid retry strategy")}}var _e=async t=>{let e={},r=async o=>typeof o=="function"?await o():o;if(t?.auth){if(t.auth.type==="Bearer"){let o=await r(t.auth.token);if(!o)return e;e.authorization=`Bearer ${o}`}else if(t.auth.type==="Basic"){let o=r(t.auth.username),s=r(t.auth.password);if(!o||!s)return e;e.authorization=`Basic ${btoa(`${o}:${s}`)}`}else if(t.auth.type==="Custom"){let o=r(t.auth.value);if(!o)return e;e.authorization=`${r(t.auth.prefix)} ${o}`}}return e},Be=/^application\/(?:[\w!#$%&*.^`~-]*\+)?json(;.+)?$/i;function je(t){let e=t.headers.get("content-type"),r=new Set(["image/svg","application/xml","application/xhtml","application/html"]);if(!e)return"json";let o=e.split(";").shift()||"";return Be.test(o)?"json":r.has(o)||o.startsWith("text/")?"text":"blob"}function Fe(t){try{return JSON.parse(t),!0}catch{return!1}}function Y(t){if(t===void 0)return!1;let e=typeof t;return e==="string"||e==="number"||e==="boolean"||e===null?!0:e!=="object"?!1:Array.isArray(t)?!0:t.buffer?!1:t.constructor&&t.constructor.name==="Object"||typeof t.toJSON=="function"}function V(t){try{return JSON.parse(t)}catch{return t}}function Q(t){return typeof t=="function"}function Ne(t){if(t?.customFetchImpl)return t.customFetchImpl;if(typeof globalThis<"u"&&Q(globalThis.fetch))return globalThis.fetch;if(typeof window<"u"&&Q(window.fetch))return window.fetch;throw new Error("No fetch implementation found")}async function We(t){let e=new Headers(t?.headers),r=await _e(t);for(let[o,s]of Object.entries(r||{}))e.set(o,s);if(!e.has("content-type")){let o=$e(t?.body);o&&e.set("content-type",o)}return e}function $e(t){return Y(t)?"application/json":null}function Me(t){if(!t?.body)return null;let e=new Headers(t?.headers);if(Y(t.body)&&!e.has("content-type")){for(let[r,o]of Object.entries(t?.body))o instanceof Date&&(t.body[r]=o.toISOString());return JSON.stringify(t.body)}return t.body}function ze(t,e){var r;if(e?.method)return e.method.toUpperCase();if(t.startsWith("@")){let o=(r=t.split("@")[1])==null?void 0:r.split("/")[0];return Z.includes(o)?o.toUpperCase():e?.body?"POST":"GET"}return e?.body?"POST":"GET"}function Ie(t,e){let r;return!t?.signal&&t?.timeout&&(r=setTimeout(()=>e?.abort(),t?.timeout)),{abortTimeout:r,clearTimeout:()=>{r&&clearTimeout(r)}}}var He=class X extends Error{constructor(e,r){super(r||JSON.stringify(e,null,2)),this.issues=e,Object.setPrototypeOf(this,X.prototype)}};async function qe(t,e){let r=await t["~standard"].validate(e);if(r.issues)throw new He(r.issues);return r.value}var Z=["get","post","put","patch","delete"];function Je(t,e){let{baseURL:r,params:o,query:s}=e||{query:{},params:{},baseURL:""},n=t.startsWith("http")?t.split("/").slice(0,3).join("/"):r||"";if(t.startsWith("@")){let b=t.toString().split("@")[1].split("/")[0];Z.includes(b)&&(t=t.replace(`@${b}/`,"/"))}n.endsWith("/")||(n+="/");let[a,h]=t.replace(n,"").split("?"),u=new URLSearchParams(h);for(let[b,p]of Object.entries(s||{}))p!=null&&u.set(b,String(p));if(o)if(Array.isArray(o)){let b=a.split("/").filter(p=>p.startsWith(":"));for(let[p,$]of b.entries()){let D=o[p];a=a.replace($,D)}}else for(let[b,p]of Object.entries(o))a=a.replace(`:${b}`,String(p));a=a.split("/").map(encodeURIComponent).join("/"),a.startsWith("/")&&(a=a.slice(1));let i=u.toString();return i=i.length>0?`?${i}`.replace(/\+/g,"%20"):"",n.startsWith("http")?new URL(`${a}${i}`,n):`${n}${a}${i}`}var c=async(t,e)=>{var r,o,s,n,a,h,u,i;let{hooks:d,url:b,options:p}=await xe(t,e),$=Ne(p),D=new AbortController,ge=(r=p.signal)!=null?r:D.signal,ye=Je(b,p),be=Me(p),ve=await We(p),Re=ze(b,p),f=U(T({},p),{url:ye,headers:ve,body:be,method:Re,signal:ge});for(let v of d.onRequest)if(v){let y=await v(f);y instanceof Object&&(f=y)}("pipeTo"in f&&typeof f.pipeTo=="function"||typeof((o=e?.body)==null?void 0:o.pipe)=="function")&&("duplex"in f||(f.duplex="half"));let{clearTimeout:we}=Ie(p,D),l=await $(f.url,f);we();let H={response:l,request:f};for(let v of d.onResponse)if(v){let y=await v(U(T({},H),{response:(s=e?.hookOptions)!=null&&s.cloneResponse?l.clone():l}));y instanceof Response?l=y:y instanceof Object&&(l=y.response)}if(l.ok){if(!(f.method!=="HEAD"))return{data:"",error:null};let y=je(l),k={data:"",response:l,request:f};if(y==="json"||y==="text"){let E=await l.text(),ke=await((n=f.jsonParser)!=null?n:V)(E);k.data=ke}else k.data=await l[y]();f?.output&&f.output&&!f.disableValidation&&(k.data=await qe(f.output,k.data));for(let E of d.onSuccess)E&&await E(U(T({},k),{response:(a=e?.hookOptions)!=null&&a.cloneResponse?l.clone():l}));return e?.throw?k.data:{data:k.data,error:null}}let Pe=(h=e?.jsonParser)!=null?h:V,C=await l.text(),q=Fe(C),M=q?await Pe(C):null,Se={response:l,responseText:C,request:f,error:U(T({},M),{status:l.status,statusText:l.statusText})};for(let v of d.onError)v&&await v(U(T({},Se),{response:(u=e?.hookOptions)!=null&&u.cloneResponse?l.clone():l}));if(e?.retry){let v=Ce(e.retry),y=(i=e.retryAttempt)!=null?i:0;if(await v.shouldAttemptRetry(y,l)){for(let E of d.onRetry)E&&await E(H);let k=v.getDelay(y);return await new Promise(E=>setTimeout(E,k)),await c(t,U(T({},e),{retryAttempt:y+1}))}}if(e?.throw)throw new Oe(l.status,l.statusText,q?M:C);return{data:null,error:U(T({},M),{status:l.status,statusText:l.statusText})}};var _=class{baseURL=null;data;state;api;auth;constructor(e){this.baseURL=null,this.data=e.data,this.state=e.state,this.api={fetchTags:async()=>{if(!this.baseURL)throw new Error("Auth client not initialized");return await c(`${this.baseURL}/profile/tags`,{credentials:"include"})},fetchBookmarks:async()=>{if(!this.baseURL)throw new Error("Auth client not initialized");let r=await c(`${this.baseURL}/profile/bookmarks`,{credentials:"include"});if(!r.data)return r;let o=new Set(r.data),s={};for(let n of o)s[n]=!0;return{data:s,error:null}},fetchProject:async()=>await c("https://core.framerauth.com/v2/public/project/config")},this.auth={getSession:async()=>{if(!this.baseURL)throw new Error("Auth client not initialized");let r=await c(`${this.baseURL}/get-session`,{method:"GET",credentials:"include",query:{disableCookieCache:!0}});return r.data&&(this.data.user.set(r.data.user),this.data.session.set(r.data.session)),r},signUp:async r=>{if(!this.baseURL)throw new Error("Auth client not initialized");let o=await c(`${this.baseURL}/sign-up/email`,{method:"POST",credentials:"include",body:r});if(o.data){await new Promise(a=>setTimeout(a,50)),await this.auth.getSession();let[s,n]=await Promise.all([this.api.fetchTags(),this.api.fetchBookmarks()]);this.data.tags.set(s.data??[]),this.data.bookmarks.set(n.data??{})}return o},signIn:async r=>{if(!this.baseURL)throw new Error("Auth client not initialized");let o=await c(`${this.baseURL}/sign-in/email`,{method:"POST",credentials:"include",body:r});return o.data&&(setTimeout(()=>this.auth.getSession(),10),this.api.fetchTags().then(s=>{this.data.tags.set(s.data??[])}),this.api.fetchBookmarks().then(s=>{this.data.bookmarks.set(s.data??{})})),o},signInSocial:async r=>{if(!this.baseURL)throw new Error("Auth client not initialized");let o=await c(`${this.baseURL}/sign-in/social`,{method:"POST",credentials:"include",body:r});return o.data?.url&&(window.location.href=o.data.url),o},signOut:async r=>{if(!this.baseURL)throw new Error("Auth client not initialized");let o=await c(`${this.baseURL}/sign-out`,{method:"POST",credentials:"include",body:{}});return this.data.user.set(null),this.data.session.set(null),this.data.tags.set([]),this.data.bookmarks.set({}),r?.redirectTo&&(window.location.href=r.redirectTo),o},sendOTP:async r=>{if(!this.baseURL)throw new Error("Auth client not initialized");let o=`${this.baseURL}/email-otp/send-verification-otp`;return await c(o,{body:r,credentials:"include",method:"POST"})},signInOTP:async r=>{if(!this.baseURL)throw new Error("Auth client not initialized");let o=`${this.baseURL}/sign-in/email-otp`,s=await c(o,{body:r,credentials:"include",method:"POST"});return s.error||(this.data.user.set(s.data.user),this.auth.getSession()),s},updateProfile:async r=>{if(!this.baseURL)throw new Error("Auth client not initialized");let o=`${this.baseURL}/profile`;return await c(o,{body:r,credentials:"include",method:"PATCH"})},updateProfilePicture:async r=>{if(!this.baseURL)throw new Error("Auth client not initialized");let o=`${this.baseURL}/profile/avatar`;return await c(o,{method:"POST",body:r,credentials:"include"})},createBookmark:async r=>{if(!this.baseURL)throw new Error("Auth client not initialized");let o=`${this.baseURL}/profile/bookmarks`;return await c(o,{body:r,credentials:"include",method:"POST"})},deleteBookmark:async r=>{if(!this.baseURL)throw new Error("Auth client not initialized");let o=`${this.baseURL}/profile/bookmarks/${r.bookmark_type}/${r.id}`;return await c(o,{credentials:"include",method:"DELETE"})},sendForgotPasswordEmail:async r=>{if(!this.baseURL)throw new Error("Auth client not initialized");let o=`${this.baseURL}/forget-password`;return await c(o,{body:r,credentials:"include",method:"POST"})},resetPassword:async r=>{if(!this.baseURL)throw new Error("Auth client not initialized");let o=`${this.baseURL}/reset-password`;return await c(o,{body:r,credentials:"include",method:"POST"})},storeCheckout:async r=>{if(!this.baseURL)throw new Error("Auth client not initialized");let o=`${this.baseURL}/store/checkout/session`;return await c(o,{body:r,credentials:"include",method:"POST"})}}}updateBaseURL(e){this.baseURL=e}};var R=[],L=0,B=4,Ke=0,m=t=>{let e=[],r={get(){return r.lc||r.listen(()=>{})(),r.value},lc:0,listen(o){return r.lc=e.push(o),()=>{for(let n=L+B;n<R.length;)R[n]===o?R.splice(n,B):n+=B;let s=e.indexOf(o);~s&&(e.splice(s,1),--r.lc||r.off())}},notify(o,s){Ke++;let n=!R.length;for(let a of e)R.push(a,r.value,o,s);if(n){for(L=0;L<R.length;L+=B)R[L](R[L+1],R[L+2],R[L+3]);R.length=0}},off(){},set(o){let s=r.value;s!==o&&(r.value=o,r.notify(s))},subscribe(o){let s=r.listen(o);return o(r.value),s},value:t};return r};var Ge=5,j=6,F=10,Ve=(t,e,r,o)=>(t.events=t.events||{},t.events[r+F]||(t.events[r+F]=o(s=>{t.events[r].reduceRight((n,a)=>(a(n),n),{shared:{},...s})})),t.events[r]=t.events[r]||[],t.events[r].push(e),()=>{let s=t.events[r],n=s.indexOf(e);s.splice(n,1),s.length||(delete t.events[r],t.events[r+F](),delete t.events[r+F])});var ee=1e3,z=(t,e)=>Ve(t,o=>{let s=e(o);s&&t.events[j].push(s)},Ge,o=>{let s=t.listen;t.listen=(...a)=>(!t.lc&&!t.active&&(t.active=!0,o()),s(...a));let n=t.off;return t.events[j]=[],t.off=()=>{n(),setTimeout(()=>{if(t.active&&!t.lc){t.active=!1;for(let a of t.events[j])a();t.events[j]=[]}},ee)},()=>{t.listen=s,t.off=n}});var N=(t={})=>{let e=m(t);return e.setKey=function(r,o){let s=e.value;typeof o>"u"&&r in e.value?(e.value={...e.value},delete e.value[r],e.notify(s,r)):e.value[r]!==o&&(e.value={...e.value,[r]:o},e.notify(s,r))},e};var te=t=>t,A={},I={addEventListener(){},removeEventListener(){}};function Qe(){try{return typeof localStorage<"u"}catch{return!1}}Qe()&&(A=localStorage);var Ye={addEventListener(t,e,r){window.addEventListener("storage",e),window.addEventListener("pageshow",r)},removeEventListener(t,e,r){window.removeEventListener("storage",e),window.removeEventListener("pageshow",r)}};typeof window<"u"&&(I=Ye);function w(t,e=void 0,r={}){let o=r.encode||te,s=r.decode||te,n=m(e),a=n.set;n.set=i=>{let d=o(i);typeof d>"u"?delete A[t]:A[t]=d,a(i)};function h(i){i.key===t?i.newValue===null?a(e):a(s(i.newValue)):A[t]||a(e)}function u(){n.set(A[t]?s(A[t]):e)}return z(n,()=>{if(u(),r.listen!==!1)return I.addEventListener(t,h,u),()=>{I.removeEventListener(t,h,u)}}),n}var re="1f8cXd6c7b4a3vL4z5746oUgQ28190adbef";function oe(t){let e="";for(let r=0;r<t.length;r++)e+=String.fromCharCode(t.charCodeAt(r)^re.charCodeAt(r%re.length));return e}function P(t){let e=JSON.stringify(t),r=oe(e);return btoa(r)}function S(t){try{let e=atob(t),r=oe(e);return JSON.parse(r)}catch{return{}}}var se=w("fa-project",null,{encode:P,decode:S}),ne=m(!1);var ae=w("fa-tags",[],{encode:P,decode:S}),ie=m(!1);var le=w("fa-user",null,{encode:P,decode:S}),ce=m(!1);var ue=w("fa-session",null,{encode:P,decode:S}),de=m(!1);var fe=m(!0);function O(){console.log("[Router] Hiding body"),document.body.style.visibility="hidden"}function x(){console.log("[Router] Showing body"),document.body.style.visibility="visible"}var W=class{hasAccess;errorUrl;onError;observer=null;currentCanonical;originalPushState;originalReplaceState;isMonkeyPatched=!1;constructor(e){this.hasAccess=e.hasAccess,this.errorUrl=e.errorUrl,this.onError=e.onError,this.currentCanonical=this.getCurrentCanonical(),this.originalPushState=history.pushState.bind(history),this.originalReplaceState=history.replaceState.bind(history)}getCurrentCanonical(){return document.querySelector('link[rel="canonical"]')?.href??null}normalizeToPath(e){if(e instanceof URL)return e.pathname;if(e.startsWith("./"))return e.slice(1);if(e.startsWith("/"))return e;try{return new URL(e).pathname}catch{return e.startsWith("/")?e:"/"+e}}async checkAccess(e){console.log("[Router] Checking access for path:",e);try{return await this.hasAccess(e)}catch(r){return console.error("[Router] Error checking access:",r),!1}}redirectToError(){console.log("[Router] Access denied, redirecting to:",this.errorUrl),window.location.replace(this.errorUrl)}handleAccessDenied(e){e&&this.onError&&this.onError(new Error(String(e))),this.redirectToError()}monkeyPatchHistory(){if(this.isMonkeyPatched)return;let e=this;history.pushState=async function(r,o,s){if(s){let n=e.normalizeToPath(s);console.log("[Router] Push state to path:",n);let a=await e.checkAccess(n);console.log("[Router] [push state] Has access:",a),a||(console.warn("Access denied to:",n),O())}return e.originalPushState.call(this,r,o,s)},history.replaceState=async function(r,o,s){if(s){let n=e.normalizeToPath(s);console.log("[Router] Replace state with path:",n);let a=await e.checkAccess(n);console.log("[Router] [replace state] Has access:",a),a||(console.warn("Access denied to:",n),O())}return e.originalReplaceState.call(this,r,o,s)},this.isMonkeyPatched=!0}restoreHistory(){this.isMonkeyPatched&&(history.pushState=this.originalPushState,history.replaceState=this.originalReplaceState,this.isMonkeyPatched=!1)}start(){console.log("[Router] Starting router"),this.stop(),this.observer=new MutationObserver(e=>{this.handleMutations(e)}),this.observer.observe(document.head,{childList:!0,attributes:!0,attributeFilter:["rel","href"],subtree:!0}),this.monkeyPatchHistory(),console.log("[Router] Router started")}stop(){console.log("[Router] Stopping router"),this.observer&&(this.observer.disconnect(),this.observer=null,console.log("[Router] Router stopped")),this.restoreHistory(),x()}handleMutations(e){let r=!1;for(let o of e){if(o.type==="childList"){let s=[...Array.from(o.addedNodes),...Array.from(o.removedNodes)];for(let n of s)if(n.nodeType===Node.ELEMENT_NODE){let a=n;if(this.isCanonicalLink(a)){r=!0;break}}}else if(o.type==="attributes"){let s=o.target;(this.isCanonicalLink(s)||o.oldValue==="canonical")&&(r=!0)}if(r)break}r&&this.checkCanonicalChange().catch(o=>{console.error("Error checking canonical change:",o),x()})}isCanonicalLink(e){return e.tagName==="LINK"&&e.getAttribute("rel")==="canonical"}async checkCanonicalChange(){let e=this.getCurrentCanonical();if(e!==this.currentCanonical)if(this.currentCanonical=e,e){let r=this.normalizeToPath(e);try{if(!await this.checkAccess(r)){console.warn("Access denied to canonical URL:",r),this.redirectToError();return}console.log("[Router] Access granted for:",r),x()}catch(o){this.handleAccessDenied(o instanceof Error?o:new Error(String(o)))}}else x()}};var he=w("fa-bookmarks",N(),{encode:P,decode:S}),pe=m(!1);var me=async(t,e)=>{let r=t.data.session.get(),o=t.data.tags.get(),{pages:s}=t.data.project.get();if(!s.hasOwnProperty(e))return!0;if(!r)return!1;let a=s[e];return a.length===0?!0:a.some(h=>o.find(u=>u.id===h))};var g=new _({data:{user:le,project:se,tags:ae,bookmarks:he,session:ue},state:{initializing:fe,userLoading:ce,projectLoading:ne,tagsLoading:ie,bookmarksLoading:pe,sessionLoading:de}});window.FramerAuth=g;var Xe=async()=>{O(),g.state.initializing.set(!0);try{let{data:t,error:e}=await g.api.fetchProject();if(e||!t)throw new Error(`Failed to fetch project: ${e?.message||"Project data is null"}`);g.data.project.set(t);let r=`https://${t.slug}.framerauth.io/v2`;g.updateBaseURL(r);let{data:o,error:s}=await g.auth.getSession();if(!s&&o!==null){let{user:n,session:a}=o;if(g.data.user.set(n),g.data.session.set(a),n)try{let[h,u]=await Promise.all([g.api.fetchTags(),g.api.fetchBookmarks()]);g.data.tags.set(h.data??[]),g.data.bookmarks.set(u.data??{})}catch(h){console.warn("Failed to fetch tags or bookmarks:",h),g.data.tags.set([]),g.data.bookmarks.set({})}}return window.dispatchEvent(new CustomEvent("framerauth:initialized")),g}catch(t){throw console.error("Failed to initialize FramerAuth:",t),window.dispatchEvent(new CustomEvent("framerauth:initialization-failed",{detail:{error:t}})),t}finally{g.state.initializing.set(!1)}},Ze=async()=>{try{let t=await Xe(),e=new W({hasAccess:o=>me(t,o),errorUrl:"/sign-in",onError:o=>{console.error("[Router] Error in router:",o)}});if(!await e.checkAccess(window.location.pathname)){e.redirectToError();return}e.start()}catch(t){console.error("Failed to initialize app:",t)}};Ze();})();
|
package/package.json
CHANGED
|
@@ -1,9 +1,8 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@framerauth/sdk",
|
|
3
3
|
"license": "MIT",
|
|
4
|
-
"version": "2.0.
|
|
4
|
+
"version": "2.0.4",
|
|
5
5
|
"type": "module",
|
|
6
|
-
"types": "TODO:dist/framerauth.d.ts",
|
|
7
6
|
"files": [
|
|
8
7
|
"dist",
|
|
9
8
|
"package.json",
|
|
@@ -21,7 +20,8 @@
|
|
|
21
20
|
"dev": "vite",
|
|
22
21
|
"lint": "tsc -p tsconfig.extended.json && tsc",
|
|
23
22
|
"build": "npm run lint && tsup",
|
|
24
|
-
"release": "npm run build &&
|
|
23
|
+
"release:beta": "npm run build && npm publish --access public --tag beta",
|
|
24
|
+
"release:latest": "npm run build && npm publish --access public",
|
|
25
25
|
"preview": "vite preview"
|
|
26
26
|
},
|
|
27
27
|
"peerDependencies": {
|