@framerauth/sdk 2.0.4 → 2.0.6
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/dist/framerauth.mjs +1 -1
- package/package.json +11 -8
package/dist/framerauth.js
CHANGED
|
@@ -1 +1 @@
|
|
|
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();})();
|
|
1
|
+
"use strict";(()=>{var Ee=Object.defineProperty,Te=Object.defineProperties,Le=Object.getOwnPropertyDescriptors,K=Object.getOwnPropertySymbols,Ae=Object.prototype.hasOwnProperty,Ue=Object.prototype.propertyIsEnumerable,V=(t,e,r)=>e in t?Ee(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,L=(t,e)=>{for(var r in e||(e={}))Ae.call(e,r)&&V(t,r,e[r]);if(K)for(var r of K(e))Ue.call(e,r)&&V(t,r,e[r]);return t},A=(t,e)=>Te(t,Le(e)),Oe=class extends Error{constructor(t,e,r){super(e||t.toString(),{cause:r}),this.status=t,this.statusText=e,this.error=r}},_e=async(t,e)=>{var r,s,o,a,n,g;let c=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:c,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));c=b.options||c,t=b.url}i.onRequest.push((s=d.hooks)==null?void 0:s.onRequest),i.onResponse.push((o=d.hooks)==null?void 0:o.onResponse),i.onSuccess.push((a=d.hooks)==null?void 0:a.onSuccess),i.onError.push((n=d.hooks)==null?void 0:n.onError),i.onRetry.push((g=d.hooks)==null?void 0:g.onRetry)}return{url:t,options:c,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}},xe=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 De(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 xe(t);default:throw new Error("Invalid retry strategy")}}var Ce=async t=>{let e={},r=async s=>typeof s=="function"?await s():s;if(t?.auth){if(t.auth.type==="Bearer"){let s=await r(t.auth.token);if(!s)return e;e.authorization=`Bearer ${s}`}else if(t.auth.type==="Basic"){let s=r(t.auth.username),o=r(t.auth.password);if(!s||!o)return e;e.authorization=`Basic ${btoa(`${s}:${o}`)}`}else if(t.auth.type==="Custom"){let s=r(t.auth.value);if(!s)return e;e.authorization=`${r(t.auth.prefix)} ${s}`}}return e},Be=/^application\/(?:[\w!#$%&*.^`~-]*\+)?json(;.+)?$/i;function Ne(t){let e=t.headers.get("content-type"),r=new Set(["image/svg","application/xml","application/xhtml","application/html"]);if(!e)return"json";let s=e.split(";").shift()||"";return Be.test(s)?"json":r.has(s)||s.startsWith("text/")?"text":"blob"}function je(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 G(t){try{return JSON.parse(t)}catch{return t}}function Q(t){return typeof t=="function"}function Fe(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 $e(t){let e=new Headers(t?.headers),r=await Ce(t);for(let[s,o]of Object.entries(r||{}))e.set(s,o);if(!e.has("content-type")){let s=Me(t?.body);s&&e.set("content-type",s)}return e}function Me(t){return Y(t)?"application/json":null}function We(t){if(!t?.body)return null;let e=new Headers(t?.headers);if(Y(t.body)&&!e.has("content-type")){for(let[r,s]of Object.entries(t?.body))s instanceof Date&&(t.body[r]=s.toISOString());return JSON.stringify(t.body)}return t.body}function Ie(t,e){var r;if(e?.method)return e.method.toUpperCase();if(t.startsWith("@")){let s=(r=t.split("@")[1])==null?void 0:r.split("/")[0];return Z.includes(s)?s.toUpperCase():e?.body?"POST":"GET"}return e?.body?"POST":"GET"}function ze(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 Ke(t,e){let{baseURL:r,params:s,query:o}=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];Z.includes(b)&&(t=t.replace(`@${b}/`,"/"))}a.endsWith("/")||(a+="/");let[n,g]=t.replace(a,"").split("?"),c=new URLSearchParams(g);for(let[b,h]of Object.entries(o||{}))h!=null&&c.set(b,String(h));if(s)if(Array.isArray(s)){let b=n.split("/").filter(h=>h.startsWith(":"));for(let[h,M]of b.entries()){let x=s[h];n=n.replace(M,x)}}else for(let[b,h]of Object.entries(s))n=n.replace(`:${b}`,String(h));n=n.split("/").map(encodeURIComponent).join("/"),n.startsWith("/")&&(n=n.slice(1));let i=c.toString();return i=i.length>0?`?${i}`.replace(/\+/g,"%20"):"",a.startsWith("http")?new URL(`${n}${i}`,a):`${a}${n}${i}`}var u=async(t,e)=>{var r,s,o,a,n,g,c,i;let{hooks:d,url:b,options:h}=await _e(t,e),M=Fe(h),x=new AbortController,ge=(r=h.signal)!=null?r:x.signal,ye=Ke(b,h),be=We(h),ve=await $e(h),Re=Ie(b,h),f=A(L({},h),{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((s=e?.body)==null?void 0:s.pipe)=="function")&&("duplex"in f||(f.duplex="half"));let{clearTimeout:Pe}=ze(h,x),l=await M(f.url,f);Pe();let H={response:l,request:f};for(let v of d.onResponse)if(v){let y=await v(A(L({},H),{response:(o=e?.hookOptions)!=null&&o.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=Ne(l),k={data:"",response:l,request:f};if(y==="json"||y==="text"){let E=await l.text(),ke=await((a=f.jsonParser)!=null?a:G)(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(A(L({},k),{response:(n=e?.hookOptions)!=null&&n.cloneResponse?l.clone():l}));return e?.throw?k.data:{data:k.data,error:null}}let we=(g=e?.jsonParser)!=null?g:G,D=await l.text(),q=je(D),W=q?await we(D):null,Se={response:l,responseText:D,request:f,error:A(L({},W),{status:l.status,statusText:l.statusText})};for(let v of d.onError)v&&await v(A(L({},Se),{response:(c=e?.hookOptions)!=null&&c.cloneResponse?l.clone():l}));if(e?.retry){let v=De(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 u(t,A(L({},e),{retryAttempt:y+1}))}}if(e?.throw)throw new Oe(l.status,l.statusText,q?W:D);return{data:null,error:A(L({},W),{status:l.status,statusText:l.statusText})}};var Ve="https://core.framerauth.com/v2",C=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 u(`${this.baseURL}/profile/tags`,{credentials:"include"})},fetchBookmarks:async()=>{if(!this.baseURL)throw new Error("Auth client not initialized");let r=await u(`${this.baseURL}/profile/bookmarks`,{credentials:"include"});if(!r.data)return r;let s=new Set(r.data),o={};for(let a of s)o[a]=!0;return{data:o,error:null}},fetchProject:async()=>await u(`${Ve}/public/project/config`)},this.auth={getSession:async()=>{if(!this.baseURL)throw new Error("Auth client not initialized");let r=await u(`${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 s=await u(`${this.baseURL}/sign-up/email`,{method:"POST",credentials:"include",body:r});return s.error||(this.data.user.set(s.data.user),this.auth.getSession(),this.api.fetchTags().then(o=>{this.data.tags.set(o.data??[])}),this.api.fetchBookmarks().then(o=>{this.data.bookmarks.set(o.data??{})})),s},signIn:async r=>{if(!this.baseURL)throw new Error("Auth client not initialized");let s=await u(`${this.baseURL}/sign-in/email`,{method:"POST",credentials:"include",body:r});return s.error||(this.data.user.set(s.data.user),this.auth.getSession(),this.api.fetchTags().then(o=>{this.data.tags.set(o.data??[])}),this.api.fetchBookmarks().then(o=>{this.data.bookmarks.set(o.data??{})})),s},signInSocial:async r=>{if(!this.baseURL)throw new Error("Auth client not initialized");let s=await u(`${this.baseURL}/sign-in/social`,{method:"POST",credentials:"include",body:r});return s.data?.url&&(window.location.href=s.data.url),s},signOut:async r=>{if(!this.baseURL)throw new Error("Auth client not initialized");let s=await u(`${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),s},sendOTP:async r=>{if(!this.baseURL)throw new Error("Auth client not initialized");let s=`${this.baseURL}/email-otp/send-verification-otp`;return await u(s,{body:r,credentials:"include",method:"POST"})},signInOTP:async r=>{if(!this.baseURL)throw new Error("Auth client not initialized");let s=`${this.baseURL}/sign-in/email-otp`,o=await u(s,{body:r,credentials:"include",method:"POST"});return o.error||(this.data.user.set(o.data.user),this.auth.getSession(),this.api.fetchTags().then(a=>{this.data.tags.set(a.data??[])}),this.api.fetchBookmarks().then(a=>{this.data.bookmarks.set(a.data??{})})),o},updateProfile:async r=>{if(!this.baseURL)throw new Error("Auth client not initialized");let s=`${this.baseURL}/profile`;return await u(s,{body:r,credentials:"include",method:"PATCH"})},updateProfilePicture:async r=>{if(!this.baseURL)throw new Error("Auth client not initialized");let s=`${this.baseURL}/profile/avatar`;return await u(s,{method:"POST",body:r,credentials:"include"})},createBookmark:async r=>{if(!this.baseURL)throw new Error("Auth client not initialized");let s=`${this.baseURL}/profile/bookmarks`;return await u(s,{body:r,credentials:"include",method:"POST"})},deleteBookmark:async r=>{if(!this.baseURL)throw new Error("Auth client not initialized");let s=`${this.baseURL}/profile/bookmarks/${r.bookmark_type}/${r.id}`;return await u(s,{credentials:"include",method:"DELETE"})},sendForgotPasswordEmail:async r=>{if(!this.baseURL)throw new Error("Auth client not initialized");let s=`${this.baseURL}/forget-password`;return await u(s,{body:r,credentials:"include",method:"POST"})},resetPassword:async r=>{if(!this.baseURL)throw new Error("Auth client not initialized");let s=`${this.baseURL}/reset-password`;return await u(s,{body:r,credentials:"include",method:"POST"})},storeCheckout:async r=>{if(!this.baseURL)throw new Error("Auth client not initialized");let s=`${this.baseURL}/store/checkout/session`;return await u(s,{body:r,credentials:"include",method:"POST"})}}}updateBaseURL(e){this.baseURL=e}};var R=[],T=0,B=4,Je=0,p=t=>{let e=[],r={get(){return r.lc||r.listen(()=>{})(),r.value},lc:0,listen(s){return r.lc=e.push(s),()=>{for(let a=T+B;a<R.length;)R[a]===s?R.splice(a,B):a+=B;let o=e.indexOf(s);~o&&(e.splice(o,1),--r.lc||r.off())}},notify(s,o){Je++;let a=!R.length;for(let n of e)R.push(n,r.value,s,o);if(a){for(T=0;T<R.length;T+=B)R[T](R[T+1],R[T+2],R[T+3]);R.length=0}},off(){},set(s){let o=r.value;o!==s&&(r.value=s,r.notify(o))},subscribe(s){let o=r.listen(s);return s(r.value),o},value:t};return r};var Ge=5,N=6,j=10,Qe=(t,e,r,s)=>(t.events=t.events||{},t.events[r+j]||(t.events[r+j]=s(o=>{t.events[r].reduceRight((a,n)=>(n(a),a),{shared:{},...o})})),t.events[r]=t.events[r]||[],t.events[r].push(e),()=>{let o=t.events[r],a=o.indexOf(e);o.splice(a,1),o.length||(delete t.events[r],t.events[r+j](),delete t.events[r+j])});var ee=1e3,I=(t,e)=>Qe(t,s=>{let o=e(s);o&&t.events[N].push(o)},Ge,s=>{let o=t.listen;t.listen=(...n)=>(!t.lc&&!t.active&&(t.active=!0,s()),o(...n));let a=t.off;return t.events[N]=[],t.off=()=>{a(),setTimeout(()=>{if(t.active&&!t.lc){t.active=!1;for(let n of t.events[N])n();t.events[N]=[]}},ee)},()=>{t.listen=o,t.off=a}});var F=(t={})=>{let e=p(t);return e.setKey=function(r,s){let o=e.value;typeof s>"u"&&r in e.value?(e.value={...e.value},delete e.value[r],e.notify(o,r)):e.value[r]!==s&&(e.value={...e.value,[r]:s},e.notify(o,r))},e};var te=t=>t,U={},z={addEventListener(){},removeEventListener(){}};function Ye(){try{return typeof localStorage<"u"}catch{return!1}}Ye()&&(U=localStorage);var Xe={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"&&(z=Xe);function P(t,e=void 0,r={}){let s=r.encode||te,o=r.decode||te,a=p(e),n=a.set;a.set=i=>{let d=s(i);typeof d>"u"?delete U[t]:U[t]=d,n(i)};function g(i){i.key===t?i.newValue===null?n(e):n(o(i.newValue)):U[t]||n(e)}function c(){a.set(U[t]?o(U[t]):e)}return I(a,()=>{if(c(),r.listen!==!1)return z.addEventListener(t,g,c),()=>{z.removeEventListener(t,g,c)}}),a}var re="1f8cXd6c7b4a3vL4z5746oUgQ28190adbef";function se(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 w(t){let e=JSON.stringify(t),r=se(e);return btoa(r)}function S(t){try{let e=atob(t),r=se(e);return JSON.parse(r)}catch{return{}}}var oe=P("fa-project",null,{encode:w,decode:S}),ae=p(!1);var ne=P("fa-tags",[],{encode:w,decode:S}),ie=p(!1);var le=P("fa-user",null,{encode:w,decode:S}),ce=p(!1);var ue=P("fa-session",null,{encode:w,decode:S}),de=p(!1);var fe=p(!0);function O(){document.body.style.visibility="hidden"}function _(){document.body.style.visibility="visible"}var $=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){try{return await this.hasAccess(e)}catch(r){return console.error("[Router] Error checking access:",r),!1}}redirectToError(){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,s,o){if(o){let a=e.normalizeToPath(o);await e.checkAccess(a)||O()}return e.originalPushState.call(this,r,s,o)},history.replaceState=async function(r,s,o){if(o){let a=e.normalizeToPath(o);await e.checkAccess(a)||(console.warn("Access denied to:",a),O())}return e.originalReplaceState.call(this,r,s,o)},this.isMonkeyPatched=!0}restoreHistory(){this.isMonkeyPatched&&(history.pushState=this.originalPushState,history.replaceState=this.originalReplaceState,this.isMonkeyPatched=!1)}start(){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()}stop(){this.observer&&(this.observer.disconnect(),this.observer=null),this.restoreHistory(),_()}handleMutations(e){let r=!1;for(let s of e){if(s.type==="childList"){let o=[...Array.from(s.addedNodes),...Array.from(s.removedNodes)];for(let a of o)if(a.nodeType===Node.ELEMENT_NODE){let n=a;if(this.isCanonicalLink(n)){r=!0;break}}}else if(s.type==="attributes"){let o=s.target;(this.isCanonicalLink(o)||s.oldValue==="canonical")&&(r=!0)}if(r)break}r&&this.checkCanonicalChange().catch(s=>{console.error("Error checking canonical change:",s),_()})}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}_()}catch(s){this.handleAccessDenied(s instanceof Error?s:new Error(String(s)))}}else _()}};var he=P("fa-bookmarks",F(),{encode:w,decode:S}),pe=p(!1);var me=async(t,e)=>{let r=t.data.session.get(),s=t.data.tags.get(),{pages:o}=t.data.project.get();if(!o.hasOwnProperty(e))return!0;if(!r)return!1;let n=o[e];return n.length===0?!0:n.some(g=>s.find(c=>c.id===g))};console.log("FramerAuth SDK: 2.0.6");var Ze="/v2",et="framerauth.io",m=new C({data:{user:le,project:oe,tags:ne,bookmarks:he,session:ue},state:{initializing:fe,userLoading:ce,projectLoading:ae,tagsLoading:ie,bookmarksLoading:pe,sessionLoading:de}});window.FramerAuth=m;var tt=async()=>{O(),m.state.initializing.set(!0);try{let{data:t,error:e}=await m.api.fetchProject();if(e||!t)throw alert(e?.message||"Unable to load FramerAuth project!"),new Error(`Failed to fetch project: ${e?.message||"Project data is null"}`);m.data.project.set(t);let r=`${t.slug}.${et}`,s=t.customDomain||r;m.updateBaseURL(`https://${s}${Ze}`);let{data:o,error:a}=await m.auth.getSession();if(!a&&o!==null){let{user:n,session:g}=o;if(m.data.user.set(n),m.data.session.set(g),n)try{let[c,i]=await Promise.all([m.api.fetchTags(),m.api.fetchBookmarks()]);m.data.tags.set(c.data??[]),m.data.bookmarks.set(i.data??{})}catch(c){console.warn("Failed to fetch tags or bookmarks:",c),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)}},rt=async()=>{try{let t=await tt(),e=new $({hasAccess:s=>me(t,s),errorUrl:"/sign-in",onError:s=>{console.error("[Router] Error in router:",s)}});if(!await e.checkAccess(window.location.pathname)){e.redirectToError();return}e.start()}catch(t){console.error("Failed to initialize app:",t)}};rt();})();
|
package/dist/framerauth.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
var ue=()=>typeof window<"u",ce=()=>window.location.host.endsWith("framercanvas.com"),k="FramerAuth snippet missing from start of <body>",b=()=>!ue()||ce()||!window?.FramerAuth?null:window.FramerAuth;async function He(){let t=b();if(!t)return{data:null,error:{message:k}};try{return await t.auth.getSession()}catch(e){return{data:null,error:{message:e instanceof Error?e.message:"Unknown error"}}}}async function We(t){let e=b();if(!e)return{data:null,error:{message:k}};try{return await e.auth.signUp(t)}catch(r){return{data:null,error:{message:r instanceof Error?r.message:"Unknown error"}}}}async function Ne(t){let e=b();if(!e)return{data:null,error:{message:k}};try{return await e.auth.signIn(t)}catch(r){return{data:null,error:{message:r instanceof Error?r.message:"Unknown error"}}}}async function De(t){let e=b();if(!e)return{data:null,error:{message:k}};try{return await e.auth.signInOTP(t)}catch(r){return{data:null,error:{message:r instanceof Error?r.message:"Unknown error"}}}}async function ze(t){let e=b();if(!e)return{data:null,error:{message:k}};try{return await e.auth.sendOTP(t)}catch(r){return{data:null,error:{message:r instanceof Error?r.message:"Unknown error"}}}}async function Je(t){let e=b();if(!e)return{data:null,error:{message:k}};try{return await e.auth.signOut(t)}catch(r){return{data:null,error:{message:r instanceof Error?r.message:"Unknown error"}}}}async function Ve(t){let e=b();if(!e)return{data:null,error:{message:k}};try{return await e.auth.updateProfile(t)}catch(r){return{data:null,error:{message:r instanceof Error?r.message:"Unknown error"}}}}async function Ke(t){let e=b();if(!e)return{data:null,error:{message:k}};try{return await e.auth.updateProfilePicture(t)}catch(r){return{data:null,error:{message:r instanceof Error?r.message:"Unknown error"}}}}async function Ge(t){let e=b();if(!e)return{data:null,error:{message:k}};try{return await e.auth.sendForgotPasswordEmail(t)}catch(r){return{data:null,error:{message:r instanceof Error?r.message:"Unknown error"}}}}async function Qe(t){let e=b();if(!e)return{data:null,error:{message:k}};try{return await e.auth.resetPassword(t)}catch(r){return{data:null,error:{message:r instanceof Error?r.message:"Unknown error"}}}}async function Ye(t){let e=b();if(!e)return{data:null,error:{message:k}};try{return await e.auth.signInSocial(t)}catch(r){return{data:null,error:{message:r instanceof Error?r.message:"Unknown error"}}}}async function Xe(t){let e=b();if(!e)return{data:null,error:{message:k}};try{return await e.auth.storeCheckout(t)}catch(r){return{data:null,error:{message:r instanceof Error?r.message:"Unknown error"}}}}var le=Object.defineProperty,fe=Object.defineProperties,de=Object.getOwnPropertyDescriptors,z=Object.getOwnPropertySymbols,me=Object.prototype.hasOwnProperty,pe=Object.prototype.propertyIsEnumerable,J=(t,e,r)=>e in t?le(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,F=(t,e)=>{for(var r in e||(e={}))me.call(e,r)&&J(t,r,e[r]);if(z)for(var r of z(e))pe.call(e,r)&&J(t,r,e[r]);return t},O=(t,e)=>fe(t,de(e)),he=class extends Error{constructor(t,e,r){super(e||t.toString(),{cause:r}),this.status=t,this.statusText=e,this.error=r}},ge=async(t,e)=>{var r,n,o,a,s,u;let i=e||{},c={onRequest:[e?.onRequest],onResponse:[e?.onResponse],onSuccess:[e?.onSuccess],onError:[e?.onError],onRetry:[e?.onRetry]};if(!e||!e?.plugins)return{url:t,options:i,hooks:c};for(let f of e?.plugins||[]){if(f.init){let l=await((r=f.init)==null?void 0:r.call(f,t.toString(),e));i=l.options||i,t=l.url}c.onRequest.push((n=f.hooks)==null?void 0:n.onRequest),c.onResponse.push((o=f.hooks)==null?void 0:o.onResponse),c.onSuccess.push((a=f.hooks)==null?void 0:a.onSuccess),c.onError.push((s=f.hooks)==null?void 0:s.onError),c.onRetry.push((u=f.hooks)==null?void 0:u.onRetry)}return{url:t,options:i,hooks:c}},V=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}},ye=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 we(t){if(typeof t=="number")return new V({type:"linear",attempts:t,delay:1e3});switch(t.type){case"linear":return new V(t);case"exponential":return new ye(t);default:throw new Error("Invalid retry strategy")}}var ve=async t=>{let e={},r=async n=>typeof n=="function"?await n():n;if(t?.auth){if(t.auth.type==="Bearer"){let n=await r(t.auth.token);if(!n)return e;e.authorization=`Bearer ${n}`}else if(t.auth.type==="Basic"){let n=r(t.auth.username),o=r(t.auth.password);if(!n||!o)return e;e.authorization=`Basic ${btoa(`${n}:${o}`)}`}else if(t.auth.type==="Custom"){let n=r(t.auth.value);if(!n)return e;e.authorization=`${r(t.auth.prefix)} ${n}`}}return e},ke=/^application\/(?:[\w!#$%&*.^`~-]*\+)?json(;.+)?$/i;function be(t){let e=t.headers.get("content-type"),r=new Set(["image/svg","application/xml","application/xhtml","application/html"]);if(!e)return"json";let n=e.split(";").shift()||"";return ke.test(n)?"json":r.has(n)||n.startsWith("text/")?"text":"blob"}function Te(t){try{return JSON.parse(t),!0}catch{return!1}}function Q(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 Pe(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 Se(t){let e=new Headers(t?.headers),r=await ve(t);for(let[n,o]of Object.entries(r||{}))e.set(n,o);if(!e.has("content-type")){let n=xe(t?.body);n&&e.set("content-type",n)}return e}function xe(t){return Q(t)?"application/json":null}function Ae(t){if(!t?.body)return null;let e=new Headers(t?.headers);if(Q(t.body)&&!e.has("content-type")){for(let[r,n]of Object.entries(t?.body))n instanceof Date&&(t.body[r]=n.toISOString());return JSON.stringify(t.body)}return t.body}function Re(t,e){var r;if(e?.method)return e.method.toUpperCase();if(t.startsWith("@")){let n=(r=t.split("@")[1])==null?void 0:r.split("/")[0];return X.includes(n)?n.toUpperCase():e?.body?"POST":"GET"}return e?.body?"POST":"GET"}function Fe(t,e){let r;return!t?.signal&&t?.timeout&&(r=setTimeout(()=>e?.abort(),t?.timeout)),{abortTimeout:r,clearTimeout:()=>{r&&clearTimeout(r)}}}var Oe=class Y extends Error{constructor(e,r){super(r||JSON.stringify(e,null,2)),this.issues=e,Object.setPrototypeOf(this,Y.prototype)}};async function Ee(t,e){let r=await t["~standard"].validate(e);if(r.issues)throw new Oe(r.issues);return r.value}var X=["get","post","put","patch","delete"];function Ue(t,e){let{baseURL:r,params:n,query:o}=e||{query:{},params:{},baseURL:""},a=t.startsWith("http")?t.split("/").slice(0,3).join("/"):r||"";if(t.startsWith("@")){let l=t.toString().split("@")[1].split("/")[0];X.includes(l)&&(t=t.replace(`@${l}/`,"/"))}a.endsWith("/")||(a+="/");let[s,u]=t.replace(a,"").split("?"),i=new URLSearchParams(u);for(let[l,m]of Object.entries(o||{}))m!=null&&i.set(l,String(m));if(n)if(Array.isArray(n)){let l=s.split("/").filter(m=>m.startsWith(":"));for(let[m,A]of l.entries()){let y=n[m];s=s.replace(A,y)}}else for(let[l,m]of Object.entries(n))s=s.replace(`:${l}`,String(m));s=s.split("/").map(encodeURIComponent).join("/"),s.startsWith("/")&&(s=s.slice(1));let c=i.toString();return c=c.length>0?`?${c}`.replace(/\+/g,"%20"):"",a.startsWith("http")?new URL(`${s}${c}`,a):`${a}${s}${c}`}var $=async(t,e)=>{var r,n,o,a,s,u,i,c;let{hooks:f,url:l,options:m}=await ge(t,e),A=Pe(m),y=new AbortController,C=(r=m.signal)!=null?r:y.signal,I=Ue(l,m),te=Ae(m),re=await Se(m),ne=Re(l,m),h=O(F({},m),{url:I,headers:re,body:te,method:ne,signal:C});for(let v of f.onRequest)if(v){let g=await v(h);g instanceof Object&&(h=g)}("pipeTo"in h&&typeof h.pipeTo=="function"||typeof((n=e?.body)==null?void 0:n.pipe)=="function")&&("duplex"in h||(h.duplex="half"));let{clearTimeout:ae}=Fe(m,y),d=await A(h.url,h);ae();let N={response:d,request:h};for(let v of f.onResponse)if(v){let g=await v(O(F({},N),{response:(o=e?.hookOptions)!=null&&o.cloneResponse?d.clone():d}));g instanceof Response?d=g:g instanceof Object&&(d=g.response)}if(d.ok){if(!(h.method!=="HEAD"))return{data:"",error:null};let g=be(d),S={data:"",response:d,request:h};if(g==="json"||g==="text"){let x=await d.text(),ie=await((a=h.jsonParser)!=null?a:K)(x);S.data=ie}else S.data=await d[g]();h?.output&&h.output&&!h.disableValidation&&(S.data=await Ee(h.output,S.data));for(let x of f.onSuccess)x&&await x(O(F({},S),{response:(s=e?.hookOptions)!=null&&s.cloneResponse?d.clone():d}));return e?.throw?S.data:{data:S.data,error:null}}let oe=(u=e?.jsonParser)!=null?u:K,L=await d.text(),D=Te(L),B=D?await oe(L):null,se={response:d,responseText:L,request:h,error:O(F({},B),{status:d.status,statusText:d.statusText})};for(let v of f.onError)v&&await v(O(F({},se),{response:(i=e?.hookOptions)!=null&&i.cloneResponse?d.clone():d}));if(e?.retry){let v=we(e.retry),g=(c=e.retryAttempt)!=null?c:0;if(await v.shouldAttemptRetry(g,d)){for(let x of f.onRetry)x&&await x(N);let S=v.getDelay(g);return await new Promise(x=>setTimeout(x,S)),await $(t,O(F({},e),{retryAttempt:g+1}))}}if(e?.throw)throw new he(d.status,d.statusText,D?B:L);return{data:null,error:O(F({},B),{status:d.status,statusText:d.statusText})}};function M(t,e,r){let n=new Set(e).add(void 0);return t.listen((o,a,s)=>{n.has(s)&&r(o,a,s)})}import{useCallback as je,useRef as Ce,useSyncExternalStore as Le}from"react";var q=(t,e)=>r=>{t.current!==r&&(t.current=r,e())};function T(t,{keys:e,deps:r=[t,e]}={}){let n=Ce();n.current=t.get();let o=je(s=>(q(n,s)(t.value),e?.length>0?M(t,e,q(n,s)):t.listen(q(n,s))),r),a=()=>n.current;return Le(o,a,a)}import{useState as Z}from"react";var E=()=>typeof window<"u",U=()=>window.location.host.endsWith("framercanvas.com"),_e=()=>{let t=Object.keys(window.parent);for(let e=t.length-1;e>=0;e--)try{let r=new URLSearchParams(window.parent[t[e]].location.search).get("siteId");if(r)return r}catch{}},Ie=async()=>{let t=_e()||"";return await $("https://core.framerauth.com/v2/public/project/config",{headers:{"x-framer-project-id":t}})};function pt(){if(!E()||U()||!window?.FramerAuth)return{initializing:!0,setInitializing:()=>{}};let t=window.FramerAuth;return{initializing:T(t.state.initializing)}}function ht(){if(!E()||U()||!window?.FramerAuth)return{session:null,loading:!1,setSession:()=>{},setLoading:()=>{}};let t=window.FramerAuth,e=T(t.data.session),r=T(t.state.sessionLoading);return{session:e,loading:r,setSession:a=>t.data.session.set(a),setLoading:a=>t.state.sessionLoading.set(a)}}function P(){if(!E()||U()||!window?.FramerAuth)return{user:null,loading:!1,setUser:()=>{},setLoading:()=>{}};let t=window.FramerAuth,e=T(t.data.user),r=T(t.state.userLoading);return{user:e,loading:r,setUser:a=>t.data.user.set(a),setLoading:a=>t.state.userLoading.set(a)}}function gt(){let[t,e]=Z(null),[r,n]=Z(!1);if(!E())return{project:null,loading:!1,setProject:()=>{},setLoading:()=>{},fetchProject:async()=>({data:null,error:{message:"Browser not available"}})};if(U()&&!window?.FramerAuth){let l=y=>e(y),m=y=>n(y);return{project:t,loading:r,setProject:l,setLoading:m,fetchProject:async()=>{m(!0);let y=await Ie();return y.data&&l(y.data),m(!1),y}}}let a=window.FramerAuth,s=T(a.data.project),u=T(a.state.projectLoading),i=l=>a.data.project.set(l),c=l=>a.state.projectLoading.set(l);return{project:s,loading:u,setProject:i,setLoading:c,fetchProject:async()=>{c(!0);let l=await a.api.fetchProject();return l.data&&i(l.data),c(!1),l}}}function R(){if(!E()||U()||!window?.FramerAuth)return{tags:null,loading:!1,setTags:()=>{},setLoading:()=>{}};let t=window.FramerAuth,e=T(t.data.tags),r=T(t.state.tagsLoading);return{tags:e,loading:r,setTags:a=>t.data.tags.set(a),setLoading:a=>t.state.tagsLoading.set(a)}}function _(t){if(!E()||U()||!window?.FramerAuth)return{bookmarks:null,loading:!1,createBookmark:a=>{},deleteBookmark:a=>{},setLoading:()=>{}};let e=window.FramerAuth;return{bookmarks:T(e.data.bookmarks,{keys:t}),createBookmark:a=>{let u={...e.data.bookmarks.get(),[a]:!0};e.data.bookmarks.set(u)},deleteBookmark:a=>{let u={...e.data.bookmarks.get()};delete u[a],e.data.bookmarks.set(u)}}}import{useEffect as H,useMemo as w,useRef as W}from"react";import{useRouter as Be,RenderTarget as ee,inferInitialRouteFromPath as $e}from"framer";import{jsx as p}from"react/jsx-runtime";function j(t,e,r){let{operator:n="all",tags:o}=r,a=!1;return t&&Array.isArray(e)&&Array.isArray(o)&&(n==="any"?a=o.some(s=>e.some(u=>u.name===s)):a=o.every(s=>e.some(u=>u.name===s))),a}function Pt(t){return e=>{let{user:r}=P();return r?p(t,{...e}):null}}function St(t){return e=>{let{user:r}=P();return r?null:p(t,{...e})}}function xt(t){return e=>{let{user:r}=P(),n=r?.id?null:e?.variant;return p(t,{...e,variant:n})}}function At(t,e){return r=>{let{user:n}=P(),{tags:o}=R();return j(n,o,e)?p(t,{...r}):null}}function Rt(t,e){return r=>{let{user:n}=P(),{tags:o}=R();return j(n,o,e)?null:p(t,{...r})}}function Ft(t){return e=>{let{user:r}=P(),{tags:n}=R(),o=W(null),a=e?.tags,s=w(()=>!a||typeof a!="string"?null:a.replaceAll(" ","").split(","),[a]),u=e?.require||"any",i=w(()=>s?j(r,n,{operator:u,tags:s}):!1,[r,n,s,u]);return H(()=>{if(o.current){let f=o.current.parentElement;if(!f)return;i?f.style.display="":f.style.display="none"}},[o.current,i]),w(()=>i!==!0?p("div",{ref:o}):p(t,{ref:o,...e}),[e,i,void 0])}}function Ot(t){return e=>{let{user:r}=P(),{tags:n}=R(),o=W(null),a=e?.tags,s=w(()=>!a||typeof a!="string"?null:a.replaceAll(" ","").split(","),[a]),u=e?.require||"any",i=w(()=>s?j(r,n,{operator:u,tags:s}):!1,[r,n,s,u]);return H(()=>{if(o.current){let f=o.current.parentElement;if(!f)return;i?f.style.display="none":f.style.display=""}},[o.current,i]),w(()=>i===!0?p("div",{ref:o}):p(t,{ref:o,...e}),[e,i,void 0])}}function Et(t){return e=>{let{user:r}=P(),{tags:n}=R(),o=e?.variant,a=e?.tags;if(!a||typeof a!="string"||a.replaceAll(" ","").trim().length===0){let c=null;return(!n||n.length===0)&&(c=o),p(t,{...e,variant:c})}let s=a.replaceAll(" ","").split(","),i=j(r,n,{operator:"any",tags:s})?null:o;return p(t,{...e,variant:i})}}function Ut(t,e){return r=>{let{tags:n}=R();return n&&e.every(a=>n.some(s=>s.name===a))?p(t,{...r}):null}}function jt(t,e){return r=>{let{tags:n}=R();return n&&e.some(a=>n.some(s=>s.name===a))?null:p(t,{...r})}}function Ct(t,e="saved-for-later"){return r=>{let{bookmarks:n}=_(),a=w(()=>n?Object.keys(n).some(u=>u.startsWith(`${e}:`))===!0:!1,[n])?null:"Empty State";return p(t,{...r,variant:a})}}function Lt(t,e="saved-for-later"){return r=>{let{bookmarks:n}=_(),o=W(null),a=w(()=>`${e}:${r?.slug}`,[r]),s=w(()=>Me()?!0:n?a in n:!1,[n?.[a],a]);return H(()=>{if(o.current){let i=o.current.parentElement;if(!i)return;s?i.style.display="":i.style.display="none"}},[o.current,s]),w(()=>s!==!0?p("div",{ref:o}):p(t,{ref:o,...r}),[r,s,void 0])}}function _t(t,e="saved-for-later"){return r=>{let n=Be(),{user:o}=P(),{bookmarks:a,createBookmark:s,deleteBookmark:u}=_([`${e}:${r?.slug}`]),i=w(()=>`${e}:${r?.slug}`,[r]),c=w(()=>a?i in a:!1,[a?.[i],i]),f=async m=>{try{if(c)u(i),window?.FramerAuth.auth.deleteBookmark({id:r?.slug,bookmark_type:e});else if(s(i),window?.FramerAuth.auth.createBookmark({id:r?.slug,bookmark_type:e}),r?.link){let[A,y]=r.link.split("#"),{routeId:C,pathVariables:I}=$e(n.routes,A);C&&n.navigate(C,y,I)}}catch(A){console.error(A)}},l=w(()=>c?r?.variant:void 0,[c,r?.variant]);return o?p(t,{...r,variant:l,onClick:f}):null}}function It(t){return e=>p(t,{...e,onClick:async n=>{window?.FramerAuth.auth.signInSocial({provider:"github",callbackURL:window.location.origin+"/account"})}})}function Bt(t,e){return r=>{let{user:n}=P();return n?p(t,{...r,onClick:async a=>{window?.FramerAuth.auth.signOut({redirectTo:e.redirectTo})}}):null}}function $t(t){return e=>{let{style:r,...n}=e;return p(t,{...n,style:{...r,gridAutoRows:"auto"}})}}function Me(){return ee.current()===ee.canvas}export{It as buttonSignInSocial,Bt as buttonSignOut,He as getSession,Ut as hasTagName,Me as isCanvas,jt as missingTagName,Qe as resetPassword,Ge as sendForgotPasswordEmail,ze as sendOTP,At as showIfHasTags,Rt as showIfNotHasTags,Pt as showIfSignedIn,St as showIfSignedOut,Ft as showIfWithTag,Ot as showIfWithoutTag,Ne as signIn,De as signInOTP,Ye as signInSocial,Je as signOut,We as signUp,Xe as storeCheckout,xt as toggleVariant,Et as toggleVariantIfWithTag,Ve as updateProfile,Ke as updateProfilePicture,_ as useBookmarks,pt as useIsInitializing,gt as useProject,ht as useSession,R as useTags,P as useUser,Ct as withBookmarks,$t as withDynamicGridHeight,Lt as withIsBookmarked,_t as withToggleBookmark};
|
|
1
|
+
var ue=()=>typeof window<"u",ce=()=>window.location.host.endsWith("framercanvas.com"),k="FramerAuth snippet missing from start of <body>",b=()=>!ue()||ce()||!window?.FramerAuth?null:window.FramerAuth;async function We(){let t=b();if(!t)return{data:null,error:{message:k}};try{return await t.auth.getSession()}catch(e){return{data:null,error:{message:e instanceof Error?e.message:"Unknown error"}}}}async function Ne(t){let e=b();if(!e)return{data:null,error:{message:k}};try{return await e.auth.signUp(t)}catch(r){return{data:null,error:{message:r instanceof Error?r.message:"Unknown error"}}}}async function De(t){let e=b();if(!e)return{data:null,error:{message:k}};try{return await e.auth.signIn(t)}catch(r){return{data:null,error:{message:r instanceof Error?r.message:"Unknown error"}}}}async function Ve(t){let e=b();if(!e)return{data:null,error:{message:k}};try{return await e.auth.signInOTP(t)}catch(r){return{data:null,error:{message:r instanceof Error?r.message:"Unknown error"}}}}async function ze(t){let e=b();if(!e)return{data:null,error:{message:k}};try{return await e.auth.sendOTP(t)}catch(r){return{data:null,error:{message:r instanceof Error?r.message:"Unknown error"}}}}async function Je(t){let e=b();if(!e)return{data:null,error:{message:k}};try{return await e.auth.signOut(t)}catch(r){return{data:null,error:{message:r instanceof Error?r.message:"Unknown error"}}}}async function Ke(t){let e=b();if(!e)return{data:null,error:{message:k}};try{return await e.auth.updateProfile(t)}catch(r){return{data:null,error:{message:r instanceof Error?r.message:"Unknown error"}}}}async function Ge(t){let e=b();if(!e)return{data:null,error:{message:k}};try{return await e.auth.updateProfilePicture(t)}catch(r){return{data:null,error:{message:r instanceof Error?r.message:"Unknown error"}}}}async function Qe(t){let e=b();if(!e)return{data:null,error:{message:k}};try{return await e.auth.sendForgotPasswordEmail(t)}catch(r){return{data:null,error:{message:r instanceof Error?r.message:"Unknown error"}}}}async function Ye(t){let e=b();if(!e)return{data:null,error:{message:k}};try{return await e.auth.resetPassword(t)}catch(r){return{data:null,error:{message:r instanceof Error?r.message:"Unknown error"}}}}async function Xe(t){let e=b();if(!e)return{data:null,error:{message:k}};try{return await e.auth.signInSocial(t)}catch(r){return{data:null,error:{message:r instanceof Error?r.message:"Unknown error"}}}}async function Ze(t){let e=b();if(!e)return{data:null,error:{message:k}};try{return await e.auth.storeCheckout(t)}catch(r){return{data:null,error:{message:r instanceof Error?r.message:"Unknown error"}}}}var le=Object.defineProperty,fe=Object.defineProperties,de=Object.getOwnPropertyDescriptors,V=Object.getOwnPropertySymbols,me=Object.prototype.hasOwnProperty,pe=Object.prototype.propertyIsEnumerable,z=(t,e,r)=>e in t?le(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,F=(t,e)=>{for(var r in e||(e={}))me.call(e,r)&&z(t,r,e[r]);if(V)for(var r of V(e))pe.call(e,r)&&z(t,r,e[r]);return t},E=(t,e)=>fe(t,de(e)),he=class extends Error{constructor(t,e,r){super(e||t.toString(),{cause:r}),this.status=t,this.statusText=e,this.error=r}},ge=async(t,e)=>{var r,n,o,a,s,c;let i=e||{},u={onRequest:[e?.onRequest],onResponse:[e?.onResponse],onSuccess:[e?.onSuccess],onError:[e?.onError],onRetry:[e?.onRetry]};if(!e||!e?.plugins)return{url:t,options:i,hooks:u};for(let l of e?.plugins||[]){if(l.init){let f=await((r=l.init)==null?void 0:r.call(l,t.toString(),e));i=f.options||i,t=f.url}u.onRequest.push((n=l.hooks)==null?void 0:n.onRequest),u.onResponse.push((o=l.hooks)==null?void 0:o.onResponse),u.onSuccess.push((a=l.hooks)==null?void 0:a.onSuccess),u.onError.push((s=l.hooks)==null?void 0:s.onError),u.onRetry.push((c=l.hooks)==null?void 0:c.onRetry)}return{url:t,options:i,hooks:u}},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}},ye=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 we(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 ye(t);default:throw new Error("Invalid retry strategy")}}var ve=async t=>{let e={},r=async n=>typeof n=="function"?await n():n;if(t?.auth){if(t.auth.type==="Bearer"){let n=await r(t.auth.token);if(!n)return e;e.authorization=`Bearer ${n}`}else if(t.auth.type==="Basic"){let n=r(t.auth.username),o=r(t.auth.password);if(!n||!o)return e;e.authorization=`Basic ${btoa(`${n}:${o}`)}`}else if(t.auth.type==="Custom"){let n=r(t.auth.value);if(!n)return e;e.authorization=`${r(t.auth.prefix)} ${n}`}}return e},ke=/^application\/(?:[\w!#$%&*.^`~-]*\+)?json(;.+)?$/i;function be(t){let e=t.headers.get("content-type"),r=new Set(["image/svg","application/xml","application/xhtml","application/html"]);if(!e)return"json";let n=e.split(";").shift()||"";return ke.test(n)?"json":r.has(n)||n.startsWith("text/")?"text":"blob"}function Te(t){try{return JSON.parse(t),!0}catch{return!1}}function Q(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 Pe(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 Se(t){let e=new Headers(t?.headers),r=await ve(t);for(let[n,o]of Object.entries(r||{}))e.set(n,o);if(!e.has("content-type")){let n=xe(t?.body);n&&e.set("content-type",n)}return e}function xe(t){return Q(t)?"application/json":null}function Ae(t){if(!t?.body)return null;let e=new Headers(t?.headers);if(Q(t.body)&&!e.has("content-type")){for(let[r,n]of Object.entries(t?.body))n instanceof Date&&(t.body[r]=n.toISOString());return JSON.stringify(t.body)}return t.body}function Re(t,e){var r;if(e?.method)return e.method.toUpperCase();if(t.startsWith("@")){let n=(r=t.split("@")[1])==null?void 0:r.split("/")[0];return X.includes(n)?n.toUpperCase():e?.body?"POST":"GET"}return e?.body?"POST":"GET"}function Fe(t,e){let r;return!t?.signal&&t?.timeout&&(r=setTimeout(()=>e?.abort(),t?.timeout)),{abortTimeout:r,clearTimeout:()=>{r&&clearTimeout(r)}}}var Ee=class Y extends Error{constructor(e,r){super(r||JSON.stringify(e,null,2)),this.issues=e,Object.setPrototypeOf(this,Y.prototype)}};async function Oe(t,e){let r=await t["~standard"].validate(e);if(r.issues)throw new Ee(r.issues);return r.value}var X=["get","post","put","patch","delete"];function _e(t,e){let{baseURL:r,params:n,query:o}=e||{query:{},params:{},baseURL:""},a=t.startsWith("http")?t.split("/").slice(0,3).join("/"):r||"";if(t.startsWith("@")){let f=t.toString().split("@")[1].split("/")[0];X.includes(f)&&(t=t.replace(`@${f}/`,"/"))}a.endsWith("/")||(a+="/");let[s,c]=t.replace(a,"").split("?"),i=new URLSearchParams(c);for(let[f,m]of Object.entries(o||{}))m!=null&&i.set(f,String(m));if(n)if(Array.isArray(n)){let f=s.split("/").filter(m=>m.startsWith(":"));for(let[m,A]of f.entries()){let y=n[m];s=s.replace(A,y)}}else for(let[f,m]of Object.entries(n))s=s.replace(`:${f}`,String(m));s=s.split("/").map(encodeURIComponent).join("/"),s.startsWith("/")&&(s=s.slice(1));let u=i.toString();return u=u.length>0?`?${u}`.replace(/\+/g,"%20"):"",a.startsWith("http")?new URL(`${s}${u}`,a):`${a}${s}${u}`}var $=async(t,e)=>{var r,n,o,a,s,c,i,u;let{hooks:l,url:f,options:m}=await ge(t,e),A=Pe(m),y=new AbortController,j=(r=m.signal)!=null?r:y.signal,I=_e(f,m),te=Ae(m),re=await Se(m),ne=Re(f,m),h=E(F({},m),{url:I,headers:re,body:te,method:ne,signal:j});for(let v of l.onRequest)if(v){let g=await v(h);g instanceof Object&&(h=g)}("pipeTo"in h&&typeof h.pipeTo=="function"||typeof((n=e?.body)==null?void 0:n.pipe)=="function")&&("duplex"in h||(h.duplex="half"));let{clearTimeout:ae}=Fe(m,y),d=await A(h.url,h);ae();let N={response:d,request:h};for(let v of l.onResponse)if(v){let g=await v(E(F({},N),{response:(o=e?.hookOptions)!=null&&o.cloneResponse?d.clone():d}));g instanceof Response?d=g:g instanceof Object&&(d=g.response)}if(d.ok){if(!(h.method!=="HEAD"))return{data:"",error:null};let g=be(d),S={data:"",response:d,request:h};if(g==="json"||g==="text"){let x=await d.text(),ie=await((a=h.jsonParser)!=null?a:K)(x);S.data=ie}else S.data=await d[g]();h?.output&&h.output&&!h.disableValidation&&(S.data=await Oe(h.output,S.data));for(let x of l.onSuccess)x&&await x(E(F({},S),{response:(s=e?.hookOptions)!=null&&s.cloneResponse?d.clone():d}));return e?.throw?S.data:{data:S.data,error:null}}let oe=(c=e?.jsonParser)!=null?c:K,C=await d.text(),D=Te(C),B=D?await oe(C):null,se={response:d,responseText:C,request:h,error:E(F({},B),{status:d.status,statusText:d.statusText})};for(let v of l.onError)v&&await v(E(F({},se),{response:(i=e?.hookOptions)!=null&&i.cloneResponse?d.clone():d}));if(e?.retry){let v=we(e.retry),g=(u=e.retryAttempt)!=null?u:0;if(await v.shouldAttemptRetry(g,d)){for(let x of l.onRetry)x&&await x(N);let S=v.getDelay(g);return await new Promise(x=>setTimeout(x,S)),await $(t,E(F({},e),{retryAttempt:g+1}))}}if(e?.throw)throw new he(d.status,d.statusText,D?B:C);return{data:null,error:E(F({},B),{status:d.status,statusText:d.statusText})}};function M(t,e,r){let n=new Set(e).add(void 0);return t.listen((o,a,s)=>{n.has(s)&&r(o,a,s)})}import{useCallback as Ue,useRef as je,useSyncExternalStore as Ce}from"react";var H=(t,e)=>r=>{t.current!==r&&(t.current=r,e())};function T(t,{keys:e,deps:r=[t,e]}={}){let n=je();n.current=t.get();let o=Ue(s=>(H(n,s)(t.value),e?.length>0?M(t,e,H(n,s)):t.listen(H(n,s))),r),a=()=>n.current;return Ce(o,a,a)}import{useState as Z}from"react";var Le="https://core.framerauth.com/v2",O=()=>typeof window<"u",_=()=>window.location.host.endsWith("framercanvas.com"),Ie=()=>{let t=Object.keys(window.parent);for(let e=t.length-1;e>=0;e--)try{let r=new URLSearchParams(window.parent[t[e]].location.search).get("siteId");if(r)return r}catch{}},Be=async()=>{let t=Ie()||"";return await $(`${Le}/public/project/config`,{headers:{"x-framer-project-id":t}})};function ht(){if(!O()||_()||!window?.FramerAuth)return{initializing:!0,setInitializing:()=>{}};let t=window.FramerAuth;return{initializing:T(t.state.initializing)}}function gt(){if(!O()||_()||!window?.FramerAuth)return{session:null,loading:!1,setSession:()=>{},setLoading:()=>{}};let t=window.FramerAuth,e=T(t.data.session),r=T(t.state.sessionLoading);return{session:e,loading:r,setSession:a=>t.data.session.set(a),setLoading:a=>t.state.sessionLoading.set(a)}}function P(){if(!O()||_()||!window?.FramerAuth)return{user:null,loading:!1,setUser:()=>{},setLoading:()=>{}};let t=window.FramerAuth,e=T(t.data.user),r=T(t.state.userLoading);return{user:e,loading:r,setUser:a=>t.data.user.set(a),setLoading:a=>t.state.userLoading.set(a)}}function yt(){let[t,e]=Z(null),[r,n]=Z(!1);if(!O())return{project:null,loading:!1,setProject:()=>{},setLoading:()=>{},fetchProject:async()=>({data:null,error:{message:"Browser not available"}})};if(_()&&!window?.FramerAuth){let f=y=>e(y),m=y=>n(y);return{project:t,loading:r,setProject:f,setLoading:m,fetchProject:async()=>{m(!0);let y=await Be();return y.data&&f(y.data),m(!1),y}}}let a=window.FramerAuth,s=T(a.data.project),c=T(a.state.projectLoading),i=f=>a.data.project.set(f),u=f=>a.state.projectLoading.set(f);return{project:s,loading:c,setProject:i,setLoading:u,fetchProject:async()=>{u(!0);let f=await a.api.fetchProject();return f.data&&i(f.data),u(!1),f}}}function R(){if(!O()||_()||!window?.FramerAuth)return{tags:null,loading:!1,setTags:()=>{},setLoading:()=>{}};let t=window.FramerAuth,e=T(t.data.tags),r=T(t.state.tagsLoading);return{tags:e,loading:r,setTags:a=>t.data.tags.set(a),setLoading:a=>t.state.tagsLoading.set(a)}}function L(t){if(!O()||_()||!window?.FramerAuth)return{bookmarks:null,loading:!1,createBookmark:a=>{},deleteBookmark:a=>{},setLoading:()=>{}};let e=window.FramerAuth;return{bookmarks:T(e.data.bookmarks,{keys:t}),createBookmark:a=>{let c={...e.data.bookmarks.get(),[a]:!0};e.data.bookmarks.set(c)},deleteBookmark:a=>{let c={...e.data.bookmarks.get()};delete c[a],e.data.bookmarks.set(c)}}}import{useEffect as q,useMemo as w,useRef as W}from"react";import{useRouter as $e,RenderTarget as ee,inferInitialRouteFromPath as Me}from"framer";import{jsx as p}from"react/jsx-runtime";function U(t,e,r){let{operator:n="all",tags:o}=r,a=!1;return t&&Array.isArray(e)&&Array.isArray(o)&&(n==="any"?a=o.some(s=>e.some(c=>c.name===s)):a=o.every(s=>e.some(c=>c.name===s))),a}function St(t){return e=>{let{user:r}=P();return r?p(t,{...e}):null}}function xt(t){return e=>{let{user:r}=P();return r?null:p(t,{...e})}}function At(t){return e=>{let{user:r}=P(),n=r?.id?null:e?.variant;return p(t,{...e,variant:n})}}function Rt(t,e){return r=>{let{user:n}=P(),{tags:o}=R();return U(n,o,e)?p(t,{...r}):null}}function Ft(t,e){return r=>{let{user:n}=P(),{tags:o}=R();return U(n,o,e)?null:p(t,{...r})}}function Et(t){return e=>{let{user:r}=P(),{tags:n}=R(),o=W(null),a=e?.tags,s=w(()=>!a||typeof a!="string"?null:a.split(",").map(l=>l.trim()).filter(Boolean),[a]),c=e?.require||"any",i=w(()=>s?U(r,n,{operator:c,tags:s}):n&&n.length>0,[r,n,s,c]);return q(()=>{if(o.current){let l=s?o.current.parentElement:o.current;if(!l)return;i?l.style.display="":l.style.display="none"}},[o.current,i]),w(()=>i!==!0?p("div",{ref:o}):p(t,{ref:o,...e}),[e,i,void 0])}}function Ot(t){return e=>{let{user:r}=P(),{tags:n}=R(),o=W(null),a=e?.tags,s=w(()=>!a||typeof a!="string"?null:a.split(",").map(l=>l.trim()).filter(Boolean),[a]),c=e?.require||"any",i=w(()=>s?U(r,n,{operator:c,tags:s}):n&&n.length>0,[r,n,s,c]);return q(()=>{if(o.current){let l=s?o.current.parentElement:o.current;if(!l)return;i?l.style.display="none":l.style.display=""}},[o.current,i]),w(()=>i===!0?p("div",{ref:o}):p(t,{ref:o,...e}),[e,i,void 0])}}function _t(t){return e=>{let{user:r}=P(),{tags:n}=R(),o=e?.variant,a=e?.tags;if(!a||typeof a!="string"||a.replaceAll(" ","").trim().length===0){let u=null;return(!n||n.length===0)&&(u=o),p(t,{...e,variant:u})}let s=a.split(",").map(u=>u.trim()).filter(Boolean),i=U(r,n,{operator:"any",tags:s})?null:o;return p(t,{...e,variant:i})}}function Ut(t,e){return r=>{let{tags:n}=R();return n&&e.every(a=>n.some(s=>s.name===a))?p(t,{...r}):null}}function jt(t,e){return r=>{let{tags:n}=R();return n&&e.some(a=>n.some(s=>s.name===a))?null:p(t,{...r})}}function Ct(t,e="saved-for-later"){return r=>{let{bookmarks:n}=L(),a=w(()=>n?Object.keys(n).some(c=>c.startsWith(`${e}:`))===!0:!1,[n])?null:"Empty State";return p(t,{...r,variant:a})}}function Lt(t,e="saved-for-later"){return r=>{let{bookmarks:n}=L(),o=W(null),a=w(()=>`${e}:${r?.slug}`,[r]),s=w(()=>He()?!0:n?a in n:!1,[n?.[a],a]);return q(()=>{if(o.current){let i=o.current.parentElement;if(!i)return;s?i.style.display="":i.style.display="none"}},[o.current,s]),w(()=>s!==!0?p("div",{ref:o}):p(t,{ref:o,...r}),[r,s,void 0])}}function It(t,e="saved-for-later"){return r=>{let n=$e(),{user:o}=P(),{bookmarks:a,createBookmark:s,deleteBookmark:c}=L([`${e}:${r?.slug}`]),i=w(()=>`${e}:${r?.slug}`,[r]),u=w(()=>a?i in a:!1,[a?.[i],i]),l=async m=>{try{if(u)c(i),window?.FramerAuth.auth.deleteBookmark({id:r?.slug,bookmark_type:e});else if(s(i),window?.FramerAuth.auth.createBookmark({id:r?.slug,bookmark_type:e}),r?.link){let[A,y]=r.link.split("#"),{routeId:j,pathVariables:I}=Me(n.routes,A);j&&n.navigate(j,y,I)}}catch(A){console.error(A)}},f=w(()=>u?r?.variant:void 0,[u,r?.variant]);return o?p(t,{...r,variant:f,onClick:l}):null}}function Bt(t){return e=>p(t,{...e,onClick:async n=>{window?.FramerAuth.auth.signInSocial({provider:"github",callbackURL:window.location.origin+"/account"})}})}function $t(t,e){return r=>{let{user:n}=P();return n?p(t,{...r,onClick:async a=>{window?.FramerAuth.auth.signOut({redirectTo:e.redirectTo})}}):null}}function Mt(t){return e=>{let{style:r,...n}=e;return p(t,{...n,style:{...r,gridAutoRows:"auto"}})}}function He(){return ee.current()===ee.canvas}export{Bt as buttonSignInSocial,$t as buttonSignOut,We as getSession,Ut as hasTagName,He as isCanvas,jt as missingTagName,Ye as resetPassword,Qe as sendForgotPasswordEmail,ze as sendOTP,Rt as showIfHasTags,Ft as showIfNotHasTags,St as showIfSignedIn,xt as showIfSignedOut,Et as showIfWithTag,Ot as showIfWithoutTag,De as signIn,Ve as signInOTP,Xe as signInSocial,Je as signOut,Ne as signUp,Ze as storeCheckout,At as toggleVariant,_t as toggleVariantIfWithTag,Ke as updateProfile,Ge as updateProfilePicture,L as useBookmarks,ht as useIsInitializing,yt as useProject,gt as useSession,R as useTags,P as useUser,Ct as withBookmarks,Mt as withDynamicGridHeight,Lt as withIsBookmarked,It as withToggleBookmark};
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@framerauth/sdk",
|
|
3
3
|
"license": "MIT",
|
|
4
|
-
"version": "2.0.
|
|
4
|
+
"version": "2.0.6",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"files": [
|
|
7
7
|
"dist",
|
|
@@ -19,27 +19,30 @@
|
|
|
19
19
|
"scripts": {
|
|
20
20
|
"dev": "vite",
|
|
21
21
|
"lint": "tsc -p tsconfig.extended.json && tsc",
|
|
22
|
-
"build": "
|
|
23
|
-
"
|
|
24
|
-
"release:
|
|
22
|
+
"build:dev": "pnpm run lint && tsup --env.VITE_API_URL https://core.framerauth.local:8000 --env.VITE_TENANT_HOSTNAME framerauth.local:8000 --env.VITE_BASE_PATH /v2",
|
|
23
|
+
"build:prod": "pnpm run lint && tsup --env.VITE_API_URL https://core.framerauth.com --env.VITE_TENANT_HOSTNAME framerauth.io --env.VITE_BASE_PATH /v2",
|
|
24
|
+
"release:beta": "pnpm run build:prod && npm publish --access public --tag beta",
|
|
25
|
+
"release:latest": "pnpm run build:prod && npm publish --access public",
|
|
25
26
|
"preview": "vite preview"
|
|
26
27
|
},
|
|
27
28
|
"peerDependencies": {
|
|
28
29
|
"react": "^18.0.0 || ^19.0.0"
|
|
29
30
|
},
|
|
30
31
|
"devDependencies": {
|
|
32
|
+
"@types/node": "^24.10.1",
|
|
31
33
|
"@types/react": "^19.1.5",
|
|
34
|
+
"dotenv": "^17.2.3",
|
|
32
35
|
"nanostores": "^1.0.1",
|
|
33
36
|
"prettier": "3.6.2",
|
|
34
37
|
"react": "^19.1.0",
|
|
35
|
-
"tsup": "^8.5.
|
|
36
|
-
"typescript": "^5.
|
|
37
|
-
"vite": "^6.
|
|
38
|
+
"tsup": "^8.5.1",
|
|
39
|
+
"typescript": "^5.9.3",
|
|
40
|
+
"vite": "^6.4.1"
|
|
38
41
|
},
|
|
39
42
|
"dependencies": {
|
|
40
43
|
"@better-fetch/fetch": "^1.1.18",
|
|
41
44
|
"@nanostores/persistent": "^1.0.0",
|
|
42
45
|
"@nanostores/react": "^1.0.0",
|
|
43
|
-
"better-auth": "^1.3.
|
|
46
|
+
"better-auth": "^1.3.14"
|
|
44
47
|
}
|
|
45
48
|
}
|