@framerauth/sdk 2.0.0-b

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/CHANGELOG.md ADDED
@@ -0,0 +1 @@
1
+ # FramerAuth
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2024 Joel Whitaker
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1 @@
1
+ # FramerAuth
@@ -0,0 +1 @@
1
+ "use strict";(()=>{var be=Object.defineProperty,ve=Object.defineProperties,Re=Object.getOwnPropertyDescriptors,z=Object.getOwnPropertySymbols,we=Object.prototype.hasOwnProperty,Pe=Object.prototype.propertyIsEnumerable,I=(t,e,r)=>e in t?be(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,L=(t,e)=>{for(var r in e||(e={}))we.call(e,r)&&I(t,r,e[r]);if(z)for(var r of z(e))Pe.call(e,r)&&I(t,r,e[r]);return t},E=(t,e)=>ve(t,Re(e)),Se=class extends Error{constructor(t,e,r){super(e||t.toString(),{cause:r}),this.status=t,this.statusText=e,this.error=r}},ke=async(t,e)=>{var r,o,s,n,a,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((n=u.hooks)==null?void 0:n.onSuccess),i.onError.push((a=u.hooks)==null?void 0:a.onError),i.onRetry.push((g=u.hooks)==null?void 0:g.onRetry)}return{url:t,options:p,hooks:i}},H=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}},Le=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 Ee(t){if(typeof t=="number")return new H({type:"linear",attempts:t,delay:1e3});switch(t.type){case"linear":return new H(t);case"exponential":return new Le(t);default:throw new Error("Invalid retry strategy")}}var Te=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},Ue=/^application\/(?:[\w!#$%&*.^`~-]*\+)?json(;.+)?$/i;function Ae(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 Ue.test(o)?"json":r.has(o)||o.startsWith("text/")?"text":"blob"}function Oe(t){try{return JSON.parse(t),!0}catch{return!1}}function K(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 q(t){try{return JSON.parse(t)}catch{return t}}function J(t){return typeof t=="function"}function xe(t){if(t?.customFetchImpl)return t.customFetchImpl;if(typeof globalThis<"u"&&J(globalThis.fetch))return globalThis.fetch;if(typeof window<"u"&&J(window.fetch))return window.fetch;throw new Error("No fetch implementation found")}async function De(t){let e=new Headers(t?.headers),r=await Te(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 K(t)?"application/json":null}function Ce(t){if(!t?.body)return null;let e=new Headers(t?.headers);if(K(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 Be(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 V.includes(o)?o.toUpperCase():e?.body?"POST":"GET"}return e?.body?"POST":"GET"}function Ne(t,e){let r;return!t?.signal&&t?.timeout&&(r=setTimeout(()=>e?.abort(),t?.timeout)),{abortTimeout:r,clearTimeout:()=>{r&&clearTimeout(r)}}}var je=class G extends Error{constructor(e,r){super(r||JSON.stringify(e,null,2)),this.issues=e,Object.setPrototypeOf(this,G.prototype)}};async function Fe(t,e){let r=await t["~standard"].validate(e);if(r.issues)throw new je(r.issues);return r.value}var V=["get","post","put","patch","delete"];function $e(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];V.includes(b)&&(t=t.replace(`@${b}/`,"/"))}n.endsWith("/")||(n+="/");let[a,g]=t.replace(n,"").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=a.split("/").filter(f=>f.startsWith(":"));for(let[f,N]of b.entries()){let U=o[f];a=a.replace(N,U)}}else for(let[b,f]of Object.entries(o))a=a.replace(`:${b}`,String(f));a=a.split("/").map(encodeURIComponent).join("/"),a.startsWith("/")&&(a=a.slice(1));let i=p.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,g,p,i;let{hooks:u,url:b,options:f}=await ke(t,e),N=xe(f),U=new AbortController,ce=(r=f.signal)!=null?r:U.signal,ue=$e(b,f),de=Ce(f),fe=await De(f),he=Be(b,f),d=E(L({},f),{url:ue,headers:fe,body:de,method:he,signal:ce});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:pe}=Ne(f,U),l=await N(d.url,d);pe();let W={response:l,request:d};for(let v of u.onResponse)if(v){let y=await v(E(L({},W),{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=Ae(l),P={data:"",response:l,request:d};if(y==="json"||y==="text"){let S=await l.text(),ye=await((n=d.jsonParser)!=null?n:q)(S);P.data=ye}else P.data=await l[y]();d?.output&&d.output&&!d.disableValidation&&(P.data=await Fe(d.output,P.data));for(let S of u.onSuccess)S&&await S(E(L({},P),{response:(a=e?.hookOptions)!=null&&a.cloneResponse?l.clone():l}));return e?.throw?P.data:{data:P.data,error:null}}let me=(g=e?.jsonParser)!=null?g:q,A=await l.text(),M=Oe(A),j=M?await me(A):null,ge={response:l,responseText:A,request:d,error:E(L({},j),{status:l.status,statusText:l.statusText})};for(let v of u.onError)v&&await v(E(L({},ge),{response:(p=e?.hookOptions)!=null&&p.cloneResponse?l.clone():l}));if(e?.retry){let v=Ee(e.retry),y=(i=e.retryAttempt)!=null?i:0;if(await v.shouldAttemptRetry(y,l)){for(let S of u.onRetry)S&&await S(W);let P=v.getDelay(y);return await new Promise(S=>setTimeout(S,P)),await c(t,E(L({},e),{retryAttempt:y+1}))}}if(e?.throw)throw new Se(l.status,l.statusText,M?j:A);return{data:null,error:E(L({},j),{status:l.status,statusText:l.statusText})}};var O=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});return o.data&&(setTimeout(()=>this.auth.getSession(),10),this.api.fetchTags().then(s=>{this.data.tags.set(s.data??[])})),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=r.provider||"social",s=await c(`${this.baseURL}/sign-in/${o}`,{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 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=[],k=0,x=4,We=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 n=k+x;n<R.length;)R[n]===o?R.splice(n,x):n+=x;let s=e.indexOf(o);~s&&(e.splice(s,1),--r.lc||r.off())}},notify(o,s){We++;let n=!R.length;for(let a of e)R.push(a,r.value,o,s);if(n){for(k=0;k<R.length;k+=x)R[k](R[k+1],R[k+2],R[k+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 Me=5,D=6,_=10,ze=(t,e,r,o)=>(t.events=t.events||{},t.events[r+_]||(t.events[r+_]=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+_](),delete t.events[r+_])});var Q=1e3,F=(t,e)=>ze(t,o=>{let s=e(o);s&&t.events[D].push(s)},Me,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[D]=[],t.off=()=>{n(),setTimeout(()=>{if(t.active&&!t.lc){t.active=!1;for(let a of t.events[D])a();t.events[D]=[]}},Q)},()=>{t.listen=s,t.off=n}});var C=(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 Y=t=>t,T={},$={addEventListener(){},removeEventListener(){}};function Ie(){try{return typeof localStorage<"u"}catch{return!1}}Ie()&&(T=localStorage);var He={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"&&($=He);function w(t,e=void 0,r={}){let o=r.encode||Y,s=r.decode||Y,n=h(e),a=n.set;n.set=i=>{let u=o(i);typeof u>"u"?delete T[t]:T[t]=u,a(i)};function g(i){i.key===t?i.newValue===null?a(e):a(s(i.newValue)):T[t]||a(e)}function p(){n.set(T[t]?s(T[t]):e)}return F(n,()=>{if(p(),r.listen!==!1)return $.addEventListener(t,g,p),()=>{$.removeEventListener(t,g,p)}}),n}var X=w("fa-project",null,{encode:JSON.stringify,decode:JSON.parse}),Z=h(!1);var ee=w("fa-tags",[],{encode:JSON.stringify,decode:JSON.parse}),te=h(!1);var re=w("fa-user",null,{encode:JSON.stringify,decode:JSON.parse}),oe=h(!1);var se=w("fa-session",null,{encode:JSON.stringify,decode:JSON.parse}),ne=h(!1);var ae=h(!0);var B=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 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),e.hideBody())}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),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 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),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 ie=w("fa-bookmarks",C(),{encode:JSON.stringify,decode:JSON.parse}),le=h(!1);var m=new O({data:{user:re,project:X,tags:ee,bookmarks:ie,session:se},state:{initializing:ae,userLoading:oe,projectLoading:Z,tagsLoading:te,bookmarksLoading:le,sessionLoading:ne}});window.FramerAuth=m;var qe=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:n,session:a}=o;if(m.data.user.set(n),m.data.session.set(a),n)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)}},Je=async()=>{try{let t=await qe();new B(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)}};Je();})();
@@ -0,0 +1 @@
1
+ var ie=()=>typeof window<"u",ue=()=>window.location.host.endsWith("framercanvas.com"),b=()=>!ie()||ue()||!window?.FramerAuth?null:window.FramerAuth;async function qe(){let t=b();if(!t)return{data:null,error:{message:"FramerAuth not available"}};try{return await t.auth.getSession()}catch(e){return{data:null,error:{message:e instanceof Error?e.message:"Unknown error"}}}}async function He(t){let e=b();if(!e)return{data:null,error:{message:"FramerAuth not available"}};try{return await e.auth.signUp(t)}catch(r){return{data:null,error:{message:r instanceof Error?r.message:"Unknown error"}}}}async function We(t){let e=b();if(!e)return{data:null,error:{message:"FramerAuth not available"}};try{return await e.auth.signIn(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:"FramerAuth not available"}};try{return await e.auth.signInOTP(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:"FramerAuth not available"}};try{return await e.auth.sendOTP(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:"FramerAuth not available"}};try{return await e.auth.signOut(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:"FramerAuth not available"}};try{return await e.auth.updateProfile(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:"FramerAuth not available"}};try{return await e.auth.updateProfilePicture(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:"FramerAuth not available"}};try{return await e.auth.sendForgotPasswordEmail(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:"FramerAuth not available"}};try{return await e.auth.resetPassword(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:"FramerAuth not available"}};try{return await e.auth.signInSocial(t)}catch(r){return{data:null,error:{message:r instanceof Error?r.message:"Unknown error"}}}}var ce=Object.defineProperty,le=Object.defineProperties,fe=Object.getOwnPropertyDescriptors,D=Object.getOwnPropertySymbols,de=Object.prototype.hasOwnProperty,me=Object.prototype.propertyIsEnumerable,z=(t,e,r)=>e in t?ce(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,F=(t,e)=>{for(var r in e||(e={}))de.call(e,r)&&z(t,r,e[r]);if(D)for(var r of D(e))me.call(e,r)&&z(t,r,e[r]);return t},R=(t,e)=>le(t,fe(e)),he=class extends Error{constructor(t,e,r){super(e||t.toString(),{cause:r}),this.status=t,this.statusText=e,this.error=r}},pe=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}},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 ge(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 we=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},ve=/^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 ve.test(n)?"json":r.has(n)||n.startsWith("text/")?"text":"blob"}function ke(t){try{return JSON.parse(t),!0}catch{return!1}}function G(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 K(t){return typeof t=="function"}function Te(t){if(t?.customFetchImpl)return t.customFetchImpl;if(typeof globalThis<"u"&&K(globalThis.fetch))return globalThis.fetch;if(typeof window<"u"&&K(window.fetch))return window.fetch;throw new Error("No fetch implementation found")}async function Pe(t){let e=new Headers(t?.headers),r=await we(t);for(let[n,o]of Object.entries(r||{}))e.set(n,o);if(!e.has("content-type")){let n=Se(t?.body);n&&e.set("content-type",n)}return e}function Se(t){return G(t)?"application/json":null}function Ae(t){if(!t?.body)return null;let e=new Headers(t?.headers);if(G(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 xe(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 Y.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 Re=class Q extends Error{constructor(e,r){super(r||JSON.stringify(e,null,2)),this.issues=e,Object.setPrototypeOf(this,Q.prototype)}};async function Oe(t,e){let r=await t["~standard"].validate(e);if(r.issues)throw new Re(r.issues);return r.value}var Y=["get","post","put","patch","delete"];function Ee(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];Y.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 g=n[m];s=s.replace(A,g)}}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 B=async(t,e)=>{var r,n,o,a,s,u,i,c;let{hooks:f,url:l,options:m}=await pe(t,e),A=Te(m),g=new AbortController,j=(r=m.signal)!=null?r:g.signal,C=Ee(l,m),ee=Ae(m),te=await Pe(m),re=xe(l,m),p=R(F({},m),{url:C,headers:te,body:ee,method:re,signal:j});for(let v of f.onRequest)if(v){let y=await v(p);y instanceof Object&&(p=y)}("pipeTo"in p&&typeof p.pipeTo=="function"||typeof((n=e?.body)==null?void 0:n.pipe)=="function")&&("duplex"in p||(p.duplex="half"));let{clearTimeout:ne}=Fe(m,g),d=await A(p.url,p);ne();let W={response:d,request:p};for(let v of f.onResponse)if(v){let y=await v(R(F({},W),{response:(o=e?.hookOptions)!=null&&o.cloneResponse?d.clone():d}));y instanceof Response?d=y:y instanceof Object&&(d=y.response)}if(d.ok){if(!(p.method!=="HEAD"))return{data:"",error:null};let y=be(d),P={data:"",response:d,request:p};if(y==="json"||y==="text"){let S=await d.text(),se=await((a=p.jsonParser)!=null?a:V)(S);P.data=se}else P.data=await d[y]();p?.output&&p.output&&!p.disableValidation&&(P.data=await Oe(p.output,P.data));for(let S of f.onSuccess)S&&await S(R(F({},P),{response:(s=e?.hookOptions)!=null&&s.cloneResponse?d.clone():d}));return e?.throw?P.data:{data:P.data,error:null}}let ae=(u=e?.jsonParser)!=null?u:V,L=await d.text(),N=ke(L),I=N?await ae(L):null,oe={response:d,responseText:L,request:p,error:R(F({},I),{status:d.status,statusText:d.statusText})};for(let v of f.onError)v&&await v(R(F({},oe),{response:(i=e?.hookOptions)!=null&&i.cloneResponse?d.clone():d}));if(e?.retry){let v=ge(e.retry),y=(c=e.retryAttempt)!=null?c:0;if(await v.shouldAttemptRetry(y,d)){for(let S of f.onRetry)S&&await S(W);let P=v.getDelay(y);return await new Promise(S=>setTimeout(S,P)),await B(t,R(F({},e),{retryAttempt:y+1}))}}if(e?.throw)throw new he(d.status,d.statusText,N?I:L);return{data:null,error:R(F({},I),{status:d.status,statusText:d.statusText})}};function $(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 Le}from"react";var M=(t,e)=>r=>{t.current!==r&&(t.current=r,e())};function k(t,{keys:e,deps:r=[t,e]}={}){let n=je();n.current=t.get();let o=Ue(s=>(M(n,s)(t.value),e?.length>0?$(t,e,M(n,s)):t.listen(M(n,s))),r),a=()=>n.current;return Le(o,a,a)}import{useState as X}from"react";var O=()=>typeof window<"u",E=()=>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{}},Ce=async()=>{let t=_e()||"";return await B("https://core.framerauth.com/v2/public/project/config",{headers:{"x-framer-project-id":t}})};function dt(){if(!O()||E()||!window?.FramerAuth)return{initializing:!0,setInitializing:()=>{}};let t=window.FramerAuth;return{initializing:k(t.state.initializing)}}function mt(){if(!O()||E()||!window?.FramerAuth)return{session:null,loading:!1,setSession:()=>{},setLoading:()=>{}};let t=window.FramerAuth,e=k(t.data.session),r=k(t.state.sessionLoading);return{session:e,loading:r,setSession:a=>t.data.session.set(a),setLoading:a=>t.state.sessionLoading.set(a)}}function T(){if(!O()||E()||!window?.FramerAuth)return{user:null,loading:!1,setUser:()=>{},setLoading:()=>{}};let t=window.FramerAuth,e=k(t.data.user),r=k(t.state.userLoading);return{user:e,loading:r,setUser:a=>t.data.user.set(a),setLoading:a=>t.state.userLoading.set(a)}}function ht(){let[t,e]=X(null),[r,n]=X(!1);if(!O())return{project:null,loading:!1,setProject:()=>{},setLoading:()=>{},fetchProject:async()=>({data:null,error:{message:"Browser not available"}})};if(E()&&!window?.FramerAuth){let l=g=>e(g),m=g=>n(g);return{project:t,loading:r,setProject:l,setLoading:m,fetchProject:async()=>{m(!0);let g=await Ce();return g.data&&l(g.data),m(!1),g}}}let a=window.FramerAuth,s=k(a.data.project),u=k(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 x(){if(!O()||E()||!window?.FramerAuth)return{tags:null,loading:!1,setTags:()=>{},setLoading:()=>{}};let t=window.FramerAuth,e=k(t.data.tags),r=k(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(!O()||E()||!window?.FramerAuth)return{bookmarks:null,loading:!1,createBookmark:a=>{},deleteBookmark:a=>{},setLoading:()=>{}};let e=window.FramerAuth;return{bookmarks:k(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 q,useMemo as w,useRef as H}from"react";import{useRouter as Ie,RenderTarget as Z,inferInitialRouteFromPath as Be}from"framer";import{jsx as h}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(u=>u.name===s)):a=o.every(s=>e.some(u=>u.name===s))),a}function kt(t){return e=>{let{user:r}=T();return r?h(t,{...e}):null}}function Tt(t){return e=>{let{user:r}=T();return r?null:h(t,{...e})}}function Pt(t){return e=>{let{user:r}=T(),n=r?.id?null:e?.variant;return h(t,{...e,variant:n})}}function St(t,e){return r=>{let{user:n}=T(),{tags:o}=x();return U(n,o,e)?h(t,{...r}):null}}function At(t,e){return r=>{let{user:n}=T(),{tags:o}=x();return U(n,o,e)?null:h(t,{...r})}}function xt(t){return e=>{let{user:r}=T(),{tags:n}=x(),o=H(null),a=e?.tags,s=w(()=>!a||typeof a!="string"?null:a.replaceAll(" ","").split(","),[a]),u=e?.require||"any",i=w(()=>s?U(r,n,{operator:u,tags:s}):!1,[r,n,s,u]);return q(()=>{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?h("div",{ref:o}):h(t,{ref:o,...e}),[e,i,void 0])}}function Ft(t){return e=>{let{user:r}=T(),{tags:n}=x(),o=H(null),a=e?.tags,s=w(()=>!a||typeof a!="string"?null:a.replaceAll(" ","").split(","),[a]),u=e?.require||"any",i=w(()=>s?U(r,n,{operator:u,tags:s}):!1,[r,n,s,u]);return q(()=>{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?h("div",{ref:o}):h(t,{ref:o,...e}),[e,i,void 0])}}function Rt(t){return e=>{let{user:r}=T(),{tags:n}=x(),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),h(t,{...e,variant:c})}let s=a.replaceAll(" ","").split(","),i=U(r,n,{operator:"any",tags:s})?null:o;return h(t,{...e,variant:i})}}function Ot(t,e){return r=>{let{tags:n}=x();return n&&e.every(a=>n.some(s=>s.name===a))?h(t,{...r}):null}}function Et(t,e){return r=>{let{tags:n}=x();return n&&e.some(a=>n.some(s=>s.name===a))?null:h(t,{...r})}}function Ut(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 h(t,{...r,variant:a})}}function jt(t,e="saved-for-later"){return r=>{let{bookmarks:n}=_(),o=H(null),a=w(()=>`${e}:${r?.slug}`,[r]),s=w(()=>$e()?!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?h("div",{ref:o}):h(t,{ref:o,...r}),[r,s,void 0])}}function Lt(t,e="saved-for-later"){return r=>{let n=Ie(),{user:o}=T(),{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,g]=r.link.split("#"),{routeId:j,pathVariables:C}=Be(n.routes,A);j&&n.navigate(j,g,C)}}catch(A){console.error(A)}},l=w(()=>c?r?.variant:void 0,[c,r?.variant]);return o?h(t,{...r,variant:l,onClick:f}):null}}function _t(t){return e=>h(t,{...e,onClick:async n=>{window?.FramerAuth.auth.signInSocial({provider:"github",callbackURL:window.location.origin+"/account"})}})}function Ct(t,e){return r=>{let{user:n}=T();return n?h(t,{...r,onClick:async a=>{window?.FramerAuth.auth.signOut({redirectTo:e.redirectTo})}}):null}}function It(t){return e=>{let{style:r,...n}=e;return h(t,{...n,style:{...r,gridAutoRows:"auto"}})}}function $e(){return Z.current()===Z.canvas}export{_t as buttonSignInSocial,Ct as buttonSignOut,qe as getSession,Ot as hasTagName,$e as isCanvas,Et as missingTagName,Ge as resetPassword,Ke as sendForgotPasswordEmail,De as sendOTP,St as showIfHasTags,At as showIfNotHasTags,kt as showIfSignedIn,Tt as showIfSignedOut,xt as showIfWithTag,Ft as showIfWithoutTag,We as signIn,Ne as signInOTP,Qe as signInSocial,ze as signOut,He as signUp,Pt as toggleVariant,Rt as toggleVariantIfWithTag,Je as updateProfile,Ve as updateProfilePicture,_ as useBookmarks,dt as useIsInitializing,ht as useProject,mt as useSession,x as useTags,T as useUser,Ut as withBookmarks,It as withDynamicGridHeight,jt as withIsBookmarked,Lt as withToggleBookmark};
package/package.json ADDED
@@ -0,0 +1,45 @@
1
+ {
2
+ "name": "@framerauth/sdk",
3
+ "license": "MIT",
4
+ "version": "2.0.0b",
5
+ "type": "module",
6
+ "types": "TODO:dist/framerauth.d.ts",
7
+ "files": [
8
+ "dist",
9
+ "package.json",
10
+ "LICENSE",
11
+ "README.md",
12
+ "CHANGELOG.md"
13
+ ],
14
+ "exports": {
15
+ ".": {
16
+ "import": "./dist/framerauth.js",
17
+ "types": "./dist/framerauth.d.ts"
18
+ }
19
+ },
20
+ "scripts": {
21
+ "dev": "vite",
22
+ "lint": "tsc -p tsconfig.extended.json && tsc",
23
+ "build": "npm run lint && tsup",
24
+ "release": "npm run build && changeset publish",
25
+ "preview": "vite preview"
26
+ },
27
+ "peerDependencies": {
28
+ "react": "^18.0.0 || ^19.0.0"
29
+ },
30
+ "devDependencies": {
31
+ "@types/react": "^19.1.5",
32
+ "nanostores": "^1.0.1",
33
+ "prettier": "3.6.2",
34
+ "react": "^19.1.0",
35
+ "tsup": "^8.5.0",
36
+ "typescript": "^5.8.3",
37
+ "vite": "^6.3.5"
38
+ },
39
+ "dependencies": {
40
+ "@better-fetch/fetch": "^1.1.18",
41
+ "@nanostores/persistent": "^1.0.0",
42
+ "@nanostores/react": "^1.0.0",
43
+ "better-auth": "^1.3.6"
44
+ }
45
+ }