@thefittingroom/sdk 0.0.5 → 0.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/README.md +94 -0
- package/dist/esm/api/fetcher.d.ts +1 -1
- package/dist/esm/api/shop.d.ts +1 -1
- package/dist/esm/helpers/async.d.ts +1 -0
- package/dist/esm/helpers/config.d.ts +2 -2
- package/dist/esm/index.js +19 -8
- package/dist/esm/index.js.map +1 -1
- package/dist/esm/index.min.js +3 -3
- package/dist/esm/index.min.js.map +1 -1
- package/package.json +3 -2
package/dist/esm/index.min.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/*!
|
|
2
|
-
* thefittingroom v0.0.
|
|
2
|
+
* thefittingroom v0.0.6 (2023-07-18T23:18:09.529Z)
|
|
3
3
|
* Copyright 2022-present, TheFittingRoom, Inc. All rights reserved.
|
|
4
4
|
*/
|
|
5
5
|
/**
|
|
@@ -1967,7 +1967,7 @@ class Th{constructor(t){this._methodName=t}}
|
|
|
1967
1967
|
* See the License for the specific language governing permissions and
|
|
1968
1968
|
* limitations under the License.
|
|
1969
1969
|
*/
|
|
1970
|
-
ut("firebase","9.15.0","app");class el{constructor(){}static getInstance(){return el.instance||(el.instance=new el),el.instance}setEnv(t){switch(t){case"production":case"prod":this.env="prod";break;default:this.env="dev"}}get firebase(){return"prod"===this.env?rl.firebase:nl.firebase}get api(){return"prod"===this.env?rl.api:nl.api}get config(){return"prod"===this.env?rl.config:nl.config}}const nl={firebase:{apiKey:"AIzaSyDfjBWzpmzb-mhGN8VSURxzLg6nkzmKUD8",authDomain:"fittingroom-dev-5d248.firebaseapp.com",projectId:"fittingroom-dev-5d248",storageBucket:"fittingroom-dev-5d248.appspot.com",messagingSenderId:"2298664147",appId:"1:2298664147:web:340bda75cd5d25f3997026"},api:{url:"https://tfr.dev.thefittingroom.xyz"},config:{avatarTimeout:"120000",vtoTimeout:"120000"}},rl={firebase:{apiKey:"AIzaSyA3kQ6w1vkA9l9lgY0nNACVPXe-QmP5T1Y",authDomain:"fittingroom-prod.firebaseapp.com",projectId:"fittingroom-prod",storageBucket:"fittingroom-prod.appspot.com",messagingSenderId:"965656825574",appId:"1:965656825574:web:933493cddc73213bd43527"},api:{url:"https://tfr.p.thefittingroom.xyz"},config:{avatarTimeout:"120000",vtoTimeout:"120000"}};function sl(t,e){var n={};for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&e.indexOf(r)<0&&(n[r]=t[r]);if(null!=t&&"function"==typeof Object.getOwnPropertySymbols){var s=0;for(r=Object.getOwnPropertySymbols(t);s<r.length;s++)e.indexOf(r[s])<0&&Object.prototype.propertyIsEnumerable.call(t,r[s])&&(n[r[s]]=t[r[s]])}return n}function il(){return{"dependent-sdk-initialized-before-auth":"Another Firebase SDK was initialized and is trying to use Auth before Auth is initialized. Please be sure to call `initializeAuth` or `getAuth` before starting any other Firebase SDK."}}const ol=il,al=new l("auth","Firebase",{"dependent-sdk-initialized-before-auth":"Another Firebase SDK was initialized and is trying to use Auth before Auth is initialized. Please be sure to call `initializeAuth` or `getAuth` before starting any other Firebase SDK."}),cl="auth/user-disabled",ul=new D("@firebase/auth");function hl(t,...e){ul.logLevel<=S.ERROR&&ul.error(`Auth (${ot}): ${t}`,...e)}
|
|
1970
|
+
ut("firebase","9.15.0","app");class el{constructor(){}static getInstance(){return el.instance||(el.instance=new el),el.instance}setEnv(t){switch(t){case"production":case"prod":this.env="prod";break;default:this.env="dev"}}get firebase(){return"prod"===this.env?rl.firebase:nl.firebase}get api(){return"prod"===this.env?rl.api:nl.api}get config(){return"prod"===this.env?rl.config:nl.config}}const nl={firebase:{apiKey:"AIzaSyDfjBWzpmzb-mhGN8VSURxzLg6nkzmKUD8",authDomain:"fittingroom-dev-5d248.firebaseapp.com",projectId:"fittingroom-dev-5d248",storageBucket:"fittingroom-dev-5d248.appspot.com",messagingSenderId:"2298664147",appId:"1:2298664147:web:340bda75cd5d25f3997026"},api:{url:"https://tfr.dev.thefittingroom.xyz"},config:{avatarTimeout:Number("120000"),vtoTimeout:Number("120000")}},rl={firebase:{apiKey:"AIzaSyA3kQ6w1vkA9l9lgY0nNACVPXe-QmP5T1Y",authDomain:"fittingroom-prod.firebaseapp.com",projectId:"fittingroom-prod",storageBucket:"fittingroom-prod.appspot.com",messagingSenderId:"965656825574",appId:"1:965656825574:web:933493cddc73213bd43527"},api:{url:"https://tfr.p.thefittingroom.xyz"},config:{avatarTimeout:Number("120000"),vtoTimeout:Number("120000")}};function sl(t,e){var n={};for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&e.indexOf(r)<0&&(n[r]=t[r]);if(null!=t&&"function"==typeof Object.getOwnPropertySymbols){var s=0;for(r=Object.getOwnPropertySymbols(t);s<r.length;s++)e.indexOf(r[s])<0&&Object.prototype.propertyIsEnumerable.call(t,r[s])&&(n[r[s]]=t[r[s]])}return n}function il(){return{"dependent-sdk-initialized-before-auth":"Another Firebase SDK was initialized and is trying to use Auth before Auth is initialized. Please be sure to call `initializeAuth` or `getAuth` before starting any other Firebase SDK."}}const ol=il,al=new l("auth","Firebase",{"dependent-sdk-initialized-before-auth":"Another Firebase SDK was initialized and is trying to use Auth before Auth is initialized. Please be sure to call `initializeAuth` or `getAuth` before starting any other Firebase SDK."}),cl="auth/user-disabled",ul=new D("@firebase/auth");function hl(t,...e){ul.logLevel<=S.ERROR&&ul.error(`Auth (${ot}): ${t}`,...e)}
|
|
1971
1971
|
/**
|
|
1972
1972
|
* @license
|
|
1973
1973
|
* Copyright 2020 Google LLC
|
|
@@ -3164,5 +3164,5 @@ class jf{constructor(t){this.auth=t,this.internalListeners=new Map}getUid(){var
|
|
|
3164
3164
|
* See the License for the specific language governing permissions and
|
|
3165
3165
|
* limitations under the License.
|
|
3166
3166
|
*/
|
|
3167
|
-
const Bf=c("authIdTokenMaxAge")||300;let zf=null;function $f(t=ct()){const e=rt(t,"auth");if(e.isInitialized())return e.getImmediate();const n=function(t,e){const n=rt(t,"auth");if(n.isInitialized()){const t=n.getImmediate();if(f(n.getOptions(),null!=e?e:{}))return t;ll(t,"already-initialized")}return n.initialize({options:e})}(t,{popupRedirectResolver:Ff,persistence:[tf,Ud,Vd]}),r=c("authTokenSyncURL");if(r){const t=(s=r,async t=>{const e=t&&await t.getIdTokenResult(),n=e&&((new Date).getTime()-Date.parse(e.issuedAtTime))/1e3;if(n&&n>Bf)return;const r=null==e?void 0:e.token;zf!==r&&(zf=r,await fetch(s,{method:r?"POST":"DELETE",headers:r?{Authorization:`Bearer ${r}`}:{}}))});!function(t,e,n){I(t).beforeAuthStateChanged(e,n)}(n,t,(()=>t(n.currentUser))),function(t,e,n,r){I(t).onIdTokenChanged(e,n,r)}(n,(e=>t(e)))}var s;const i=a("auth");return i&&hd(n,`http://${i}`),n}var Kf;Kf="Browser",nt(new b("auth",((t,{options:e})=>{const n=t.getProvider("app").getImmediate(),r=t.getProvider("heartbeat"),{apiKey:s,authDomain:i}=n.options;return((t,n)=>{pl(s&&!s.includes(":"),"invalid-api-key",{appName:t.name}),pl(!(null==i?void 0:i.includes(":")),"argument-error",{appName:t.name});const r={apiKey:s,authDomain:i,clientPlatform:Kf,apiHost:"identitytoolkit.googleapis.com",tokenApiHost:"securetoken.googleapis.com",apiScheme:"https",sdkClientVersion:id(Kf)},o=new ad(t,n,r);return function(t,e){const n=(null==e?void 0:e.persistence)||[],r=(Array.isArray(n)?n:[n]).map(vl);(null==e?void 0:e.errorMap)&&t._updateErrorMap(e.errorMap),t._initializeWithPersistence(r,null==e?void 0:e.popupRedirectResolver)}(o,e),o})(n,r)}),"PUBLIC").setInstantiationMode("EXPLICIT").setInstanceCreatedCallback(((t,e,n)=>{t.getProvider("auth-internal").initialize()}))),nt(new b("auth-internal",(t=>(t=>new jf(t))(cd(t.getProvider("auth").getImmediate()))),"PRIVATE").setInstantiationMode("EXPLICIT")),ut(Vf,qf,function(t){switch(t){case"Node":return"node";case"ReactNative":return"rn";case"Worker":return"webworker";case"Cordova":return"cordova";default:return}}(Kf)),ut(Vf,qf,"esm2017");class Hf extends Error{constructor(){super("no frames found"),this.name="NoFramesFoundError"}}class Gf extends Error{constructor(){super("request timeout"),this.name="RequestTimeoutError"}}class Wf extends Error{constructor(){super("user not logged in"),this.name="UserNotLoggedInError"}}class Qf extends Error{constructor(){super("no colorway size assets found"),this.name="NoColorwaySizeAssetsFoundError"}}class Yf extends Error{constructor(){super("no styles found"),this.name="NoStylesFoundError"}}class Xf extends Error{constructor(t,e){super("recommended available sizes error"),this.name="RecommendedAvailableSizesError",this.recommended_size=t,this.available_sizes=e}}var Jf=Object.freeze({__proto__:null,NoFramesFoundError:Hf,RequestTimeoutError:Gf,UserNotLoggedInError:Wf,NoColorwaySizeAssetsFoundError:Qf,NoStylesFoundError:Yf,RecommendedAvailableSizesError:Xf});class Zf{constructor(t,e){this.firestore=t,this.auth=$f(e),this.auth.setPersistence(Ud)}get id(){var t;return null===(t=this.user)||void 0===t?void 0:t.uid}onInit(){return new Promise((t=>{const e=this.auth.onAuthStateChanged((n=>{this.setUser(n),t(Boolean(n)),e()}))}))}setUser(t){this.user=t}async getToken(){var t;if(!(null===(t=this.user)||void 0===t?void 0:t.uid))throw new Wf;return await this.user.getIdToken()}async getUserProfile(){var t;if(!(null===(t=this.user)||void 0===t?void 0:t.uid))throw new Wf;const e=await Xh(function(t,e,...n){if(t=I(t),1===arguments.length&&(e=Ys.R()),Xu("doc","path",e),t instanceof sh){const r=ni.fromString(e,...n);return Ju(r),new oh(t,null,new ii(r))}{if(!(t instanceof oh||t instanceof ch))throw new Vs(Fs.INVALID_ARGUMENT,"Expected first argument to collection() to be a CollectionReference, a DocumentReference or FirebaseFirestore");const r=t._path.child(ni.fromString(e,...n));return Ju(r),new oh(t.firestore,t instanceof ch?t.converter:null,new ii(r))}}(this.firestore,"users",this.id));return e.data()}async login(t,e){this.auth.currentUser&&await this.auth.signOut();const n=await Ld(this.auth,t,e);this.setUser(n.user)}async logout(){await this.auth.signOut(),this.setUser(null)}async sendPasswordResetEmail(t){await Rd(this.auth,t)}async confirmPasswordReset(t,e){await Od(this.auth,t,e)}}class tp{constructor(){this.promisefyOnSnapshot=t=>{let e;const n=new Promise((n=>e=function(t,...e){var n,r,s;t=I(t);let i={includeMetadataChanges:!1},o=0;"object"!=typeof e[o]||gh(e[o])||(i=e[o],o++);const a={includeMetadataChanges:i.includeMetadataChanges};if(gh(e[o])){const t=e[o];e[o]=null===(n=t.next)||void 0===n?void 0:n.bind(t),e[o+1]=null===(r=t.error)||void 0===r?void 0:r.bind(t),e[o+2]=null===(s=t.complete)||void 0===s?void 0:s.bind(t)}let c,u,h;if(t instanceof oh)u=eh(t.firestore,mh),h=Co(t._key.path),c={next:n=>{e[o]&&e[o](tl(u,t,n))},error:e[o+1],complete:e[o+2]};else{const n=eh(t,ah);u=eh(n.firestore,mh),h=n._query;const r=new Jh(u);c={next:t=>{e[o]&&e[o](new Qh(u,r,n,t))},error:e[o+1],complete:e[o+2]},Mh(t._query)}return function(t,e,n,r){const s=new hh(r),i=new Nu(e,s,n);return t.asyncQueue.enqueueAndForget((async()=>_u(await fh(t),i))),()=>{s.bc(),t.asyncQueue.enqueueAndForget((async()=>Su(await fh(t),i)))}}(vh(u),h,a,c)}(t,(t=>n(t)))));return{promise:n,unsubscribe:()=>e()}};const t=at(el.getInstance().firebase);this.firestore=yh(t),this.user=new Zf(this.firestore,t)}onInit(){return this.user.onInit()}query(t,e){const n=Fh(uh(this.firestore,t),e);return this.promisefyOnSnapshot(n)}getDocs(t,e){return Zh(Fh(uh(this.firestore,t),...e))}}const ep=t=>{if(t.code===cl)throw new Error("account has been disabled");throw new Error(t.message)};class np{static endpoint(){return el.getInstance().api.url}static async Fetch({user:t,endpointPath:e,method:n,body:r,useToken:s=!0}){const i=this.getUrl(e,s),o={method:n,headers:await this.getHeaders(t,s),credentials:"include"};r&&(o.body=JSON.stringify(r));const a=await fetch(i,o);if(a.ok)return a;if(500===a.status)throw new Error(a.statusText);const c=await a.json();return Promise.reject(c)}static getUrl(t,e){return e?`${this.endpoint}/v1${t}`:this.endpoint+t}static async getHeaders(t,e){if(!e)return{"Content-Type":"application/json"};return{"Content-Type":"application/json",Authorization:`Bearer ${await t.getToken()}`}}static Get(t,e,n){return this.Fetch({user:t,endpointPath:e,method:"GET",body:null,useToken:n})}static Post(t,e,n=null,r){return this.Fetch({user:t,endpointPath:e,method:"POST",body:n,useToken:r})}static Put(t,e,n,r){return this.Fetch({user:t,endpointPath:e,method:"PUT",body:n,useToken:r})}static Patch(t,e,n,r){return this.Fetch({user:t,endpointPath:e,method:"PATCH",body:n,useToken:r})}static Delete(t,e,n,r){return this.Fetch({user:t,endpointPath:e,method:"DELETE",body:n,useToken:r})}}class rp{constructor(t,e){this.brandId=t,this.firebase=e;const n=el.getInstance().config;rp.avatarTimeout=n.avatarTimeout?Number(n.avatarTimeout):12e4,rp.vtoTimeout=n.vtoTimeout?Number(n.vtoTimeout):12e4}get user(){return this.firebase.user}get isLoggedIn(){return!this.firebase||Boolean(this.user.id)}onInit(){return this.firebase.onInit()}async tryOn(t){if(!this.isLoggedIn)throw new Wf;try{return await this.getColorwaySizeAssetFrames(t)}catch(e){if(!(e instanceof Hf))throw e;return this.requestThenGetColorwaySizeAssetFrames(t)}}async awaitAvatarCreated(){if(!this.isLoggedIn)throw new Wf;const{promise:t,unsubscribe:e}=this.firebase.query("users",qh(new bh("__name__"),"==",this.user.id)),n=setTimeout((()=>{throw e(),new Gf}),rp.avatarTimeout),r=await t;clearTimeout(n);return"CREATED"===r.docs[0].data().avatar_status}async getRecommendedSizes(t){if(!this.isLoggedIn)throw new Wf;const e=await np.Get(this.user,`/styles/${t}/recommendation`);return await e.json()}async getStyles(t,e){const n=[qh("brand_id","==",this.brandId)];(null==t?void 0:t.length)>0&&n.push(qh("id","in",t)),(null==e?void 0:e.length)>0&&n.push(qh("brand_style_id","in",e));try{const t=await this.firebase.getDocs("styles",n),e=new Map;return t.forEach((t=>{const n=t.data();e.set(n.id,n)})),e}catch(t){return ep(t)}}async submitTelephoneNumber(t){const e=t.replace(/[^\+0-9]/g,""),n=await np.Post(this.user,"/ios-app-link",{phone_number:e},!1);console.log(n)}awaitColorwaySizeAssetFrames(t){if(!this.isLoggedIn)throw new Wf;return this.getColorwaySizeAssetFrames(t)}async requestThenGetColorwaySizeAssetFrames(t){var e,n;const[r,s]=await(i=this.getColorwaySizeAssetFromSku(t),i.then((t=>[null,t])).catch((t=>[t])));var i;if(r)throw r;try{return await this.requestColorwaySizeAssetFrames(s.id),this.awaitColorwaySizeAssetFrames(t)}catch(r){if(!r.recommended_size_id)throw new Error(r);const t=r,i=(await this.getStyles([s.style_id],null)).get(s.style_id);if(!(null==i?void 0:i.sizes))throw new Yf;const o=(null===(e=i.sizes[t.recommended_size_id])||void 0===e?void 0:e.label)||(null===(n=i.sizes[t.recommended_size_id])||void 0===n?void 0:n.size),a=t.available_size_ids.filter((t=>{var e;return(null===(e=i.sizes[t])||void 0===e?void 0:e.size)!==o})).map((t=>{var e,n;return(null===(e=i.sizes[t])||void 0===e?void 0:e.label)||(null===(n=i.sizes[t])||void 0===n?void 0:n.size)}));throw new Xf(o,a)}}async getColorwaySizeAssetFromSku(t){const e=await this.getColorwaySizeAssets(null,[t]);if(!(null==e?void 0:e.size))throw new Qf;return Array.from(e.values())[0]}async getColorwaySizeAssets(t,e){const n=[qh("brand_id","==",this.brandId)];t&&n.push(qh("style_id","==",t)),(null==e?void 0:e.length)>0&&n.push(qh("sku","in",e));try{const t=await this.firebase.getDocs("colorway_size_assets",n),e=new Map;return t.forEach((t=>{const n=t.data();e.set(n.id,n)})),e}catch(t){return ep(t)}}async requestColorwaySizeAssetFrames(t){if(!this.isLoggedIn)throw new Wf;await np.Post(this.user,`/colorway-size-assets/${t}/frames`)}async getColorwaySizeAssetFrames(t){var e,n,r;const s=await this.user.getUserProfile(),i=(null===(r=null===(n=null===(e=null==s?void 0:s.vto)||void 0===e?void 0:e[this.brandId])||void 0===n?void 0:n[t])||void 0===r?void 0:r.frames)||[];if(!i.length)throw new Hf;if(!await(t=>{const e=new Image;return e.src=t,new Promise((t=>{e.onerror=()=>t(!1),e.onload=()=>t(!0)}))})(i[0]))throw new Hf;return i}}const sp=(t,e="dev")=>("dev"!==e&&"development"!==e||console.warn("TfrShop is in development mode"),el.getInstance().setEnv(e),new rp(t,new tp));var ip,op=Object.freeze({__proto__:null}),ap=Object.freeze({__proto__:null});!function(t){t.NOT_CREATED="NOT_CREATED",t.CREATED="CREATED",t.PENDING="PENDING"}(ip||(ip={}));var cp=Object.freeze({__proto__:null,get AvatarState(){return ip}});const up=rp.vtoTimeout;export{Jf as Errors,up as VTO_TIMEOUT_MS,sp as initShop,op as requests,ap as responses,cp as types};
|
|
3167
|
+
const Bf=c("authIdTokenMaxAge")||300;let zf=null;function $f(t=ct()){const e=rt(t,"auth");if(e.isInitialized())return e.getImmediate();const n=function(t,e){const n=rt(t,"auth");if(n.isInitialized()){const t=n.getImmediate();if(f(n.getOptions(),null!=e?e:{}))return t;ll(t,"already-initialized")}return n.initialize({options:e})}(t,{popupRedirectResolver:Ff,persistence:[tf,Ud,Vd]}),r=c("authTokenSyncURL");if(r){const t=(s=r,async t=>{const e=t&&await t.getIdTokenResult(),n=e&&((new Date).getTime()-Date.parse(e.issuedAtTime))/1e3;if(n&&n>Bf)return;const r=null==e?void 0:e.token;zf!==r&&(zf=r,await fetch(s,{method:r?"POST":"DELETE",headers:r?{Authorization:`Bearer ${r}`}:{}}))});!function(t,e,n){I(t).beforeAuthStateChanged(e,n)}(n,t,(()=>t(n.currentUser))),function(t,e,n,r){I(t).onIdTokenChanged(e,n,r)}(n,(e=>t(e)))}var s;const i=a("auth");return i&&hd(n,`http://${i}`),n}var Kf;Kf="Browser",nt(new b("auth",((t,{options:e})=>{const n=t.getProvider("app").getImmediate(),r=t.getProvider("heartbeat"),{apiKey:s,authDomain:i}=n.options;return((t,n)=>{pl(s&&!s.includes(":"),"invalid-api-key",{appName:t.name}),pl(!(null==i?void 0:i.includes(":")),"argument-error",{appName:t.name});const r={apiKey:s,authDomain:i,clientPlatform:Kf,apiHost:"identitytoolkit.googleapis.com",tokenApiHost:"securetoken.googleapis.com",apiScheme:"https",sdkClientVersion:id(Kf)},o=new ad(t,n,r);return function(t,e){const n=(null==e?void 0:e.persistence)||[],r=(Array.isArray(n)?n:[n]).map(vl);(null==e?void 0:e.errorMap)&&t._updateErrorMap(e.errorMap),t._initializeWithPersistence(r,null==e?void 0:e.popupRedirectResolver)}(o,e),o})(n,r)}),"PUBLIC").setInstantiationMode("EXPLICIT").setInstanceCreatedCallback(((t,e,n)=>{t.getProvider("auth-internal").initialize()}))),nt(new b("auth-internal",(t=>(t=>new jf(t))(cd(t.getProvider("auth").getImmediate()))),"PRIVATE").setInstantiationMode("EXPLICIT")),ut(Vf,qf,function(t){switch(t){case"Node":return"node";case"ReactNative":return"rn";case"Worker":return"webworker";case"Cordova":return"cordova";default:return}}(Kf)),ut(Vf,qf,"esm2017");class Hf extends Error{constructor(){super("no frames found"),this.name="NoFramesFoundError"}}class Gf extends Error{constructor(){super("request timeout"),this.name="RequestTimeoutError"}}class Wf extends Error{constructor(){super("user not logged in"),this.name="UserNotLoggedInError"}}class Qf extends Error{constructor(){super("no colorway size assets found"),this.name="NoColorwaySizeAssetsFoundError"}}class Yf extends Error{constructor(){super("no styles found"),this.name="NoStylesFoundError"}}class Xf extends Error{constructor(t,e){super("recommended available sizes error"),this.name="RecommendedAvailableSizesError",this.recommended_size=t,this.available_sizes=e}}var Jf=Object.freeze({__proto__:null,NoFramesFoundError:Hf,RequestTimeoutError:Gf,UserNotLoggedInError:Wf,NoColorwaySizeAssetsFoundError:Qf,NoStylesFoundError:Yf,RecommendedAvailableSizesError:Xf});class Zf{constructor(t,e){this.firestore=t,this.auth=$f(e),this.auth.setPersistence(Ud)}get id(){var t;return null===(t=this.user)||void 0===t?void 0:t.uid}onInit(){return new Promise((t=>{const e=this.auth.onAuthStateChanged((n=>{this.setUser(n),t(Boolean(n)),e()}))}))}setUser(t){this.user=t}async getToken(){var t;if(!(null===(t=this.user)||void 0===t?void 0:t.uid))throw new Wf;return await this.user.getIdToken()}async getUserProfile(){var t;if(!(null===(t=this.user)||void 0===t?void 0:t.uid))throw new Wf;const e=await Xh(function(t,e,...n){if(t=I(t),1===arguments.length&&(e=Ys.R()),Xu("doc","path",e),t instanceof sh){const r=ni.fromString(e,...n);return Ju(r),new oh(t,null,new ii(r))}{if(!(t instanceof oh||t instanceof ch))throw new Vs(Fs.INVALID_ARGUMENT,"Expected first argument to collection() to be a CollectionReference, a DocumentReference or FirebaseFirestore");const r=t._path.child(ni.fromString(e,...n));return Ju(r),new oh(t.firestore,t instanceof ch?t.converter:null,new ii(r))}}(this.firestore,"users",this.id));return e.data()}async login(t,e){this.auth.currentUser&&await this.auth.signOut();const n=await Ld(this.auth,t,e);this.setUser(n.user)}async logout(){await this.auth.signOut(),this.setUser(null)}async sendPasswordResetEmail(t){await Rd(this.auth,t)}async confirmPasswordReset(t,e){await Od(this.auth,t,e)}}class tp{constructor(){this.promisefyOnSnapshot=t=>{let e;const n=new Promise((n=>e=function(t,...e){var n,r,s;t=I(t);let i={includeMetadataChanges:!1},o=0;"object"!=typeof e[o]||gh(e[o])||(i=e[o],o++);const a={includeMetadataChanges:i.includeMetadataChanges};if(gh(e[o])){const t=e[o];e[o]=null===(n=t.next)||void 0===n?void 0:n.bind(t),e[o+1]=null===(r=t.error)||void 0===r?void 0:r.bind(t),e[o+2]=null===(s=t.complete)||void 0===s?void 0:s.bind(t)}let c,u,h;if(t instanceof oh)u=eh(t.firestore,mh),h=Co(t._key.path),c={next:n=>{e[o]&&e[o](tl(u,t,n))},error:e[o+1],complete:e[o+2]};else{const n=eh(t,ah);u=eh(n.firestore,mh),h=n._query;const r=new Jh(u);c={next:t=>{e[o]&&e[o](new Qh(u,r,n,t))},error:e[o+1],complete:e[o+2]},Mh(t._query)}return function(t,e,n,r){const s=new hh(r),i=new Nu(e,s,n);return t.asyncQueue.enqueueAndForget((async()=>_u(await fh(t),i))),()=>{s.bc(),t.asyncQueue.enqueueAndForget((async()=>Su(await fh(t),i)))}}(vh(u),h,a,c)}(t,(t=>n(t)))));return{promise:n,unsubscribe:()=>e()}};const t=at(el.getInstance().firebase);this.firestore=yh(t),this.user=new Zf(this.firestore,t)}onInit(){return this.user.onInit()}query(t,e){const n=Fh(uh(this.firestore,t),e);return this.promisefyOnSnapshot(n)}getDocs(t,e){return Zh(Fh(uh(this.firestore,t),...e))}}const ep=t=>{if(t.code===cl)throw new Error("account has been disabled");throw new Error(t.message)};class np{static get endpoint(){return el.getInstance().api.url}static async Fetch({user:t,endpointPath:e,method:n,body:r,useToken:s=!0}){const i=this.getUrl(e,s),o={method:n,headers:await this.getHeaders(t,s),credentials:"include"};r&&(o.body=JSON.stringify(r));const a=await fetch(i,o);if(a.ok)return a;if(500===a.status)throw new Error(a.statusText);const c=await a.json();return Promise.reject(c)}static getUrl(t,e){return e?`${this.endpoint}/v1${t}`:this.endpoint+t}static async getHeaders(t,e){if(!e)return{"Content-Type":"application/json"};return{"Content-Type":"application/json",Authorization:`Bearer ${await t.getToken()}`}}static Get(t,e,n){return this.Fetch({user:t,endpointPath:e,method:"GET",body:null,useToken:n})}static Post(t,e,n=null,r){return this.Fetch({user:t,endpointPath:e,method:"POST",body:n,useToken:r})}static Put(t,e,n,r){return this.Fetch({user:t,endpointPath:e,method:"PUT",body:n,useToken:r})}static Patch(t,e,n,r){return this.Fetch({user:t,endpointPath:e,method:"PATCH",body:n,useToken:r})}static Delete(t,e,n,r){return this.Fetch({user:t,endpointPath:e,method:"DELETE",body:n,useToken:r})}}class rp{constructor(t,e){this.brandId=t,this.firebase=e;const n=el.getInstance().config;rp.avatarTimeout=n.avatarTimeout?Number(n.avatarTimeout):12e4,rp.vtoTimeout=n.vtoTimeout?Number(n.vtoTimeout):12e4}get user(){return this.firebase.user}get isLoggedIn(){return!this.firebase||Boolean(this.user.id)}onInit(){return this.firebase.onInit()}async tryOn(t){if(!this.isLoggedIn)throw new Wf;try{return await this.getColorwaySizeAssetFrames(t)}catch(e){if(!(e instanceof Hf))throw e;return this.requestThenGetColorwaySizeAssetFrames(t)}}async awaitAvatarCreated(){if(!this.isLoggedIn)throw new Wf;const{promise:t,unsubscribe:e}=this.firebase.query("users",qh(new bh("__name__"),"==",this.user.id)),n=setTimeout((()=>{throw e(),new Gf}),rp.avatarTimeout),r=await t;clearTimeout(n);return"CREATED"===r.docs[0].data().avatar_status}async getRecommendedSizes(t){if(!this.isLoggedIn)throw new Wf;const e=await np.Get(this.user,`/styles/${t}/recommendation`);return await e.json()}async getStyles(t,e){const n=[qh("brand_id","==",this.brandId)];(null==t?void 0:t.length)>0&&n.push(qh("id","in",t)),(null==e?void 0:e.length)>0&&n.push(qh("brand_style_id","in",e));try{const t=await this.firebase.getDocs("styles",n),e=new Map;return t.forEach((t=>{const n=t.data();e.set(n.id,n)})),e}catch(t){return ep(t)}}async submitTelephoneNumber(t){const e=t.replace(/[^\+0-9]/g,""),n=await np.Post(this.user,"/ios-app-link",{phone_number:e},!1);console.log(n)}async awaitColorwaySizeAssetFrames(t){if(!this.isLoggedIn)throw new Wf;console.log("polling");try{return await this.getColorwaySizeAssetFrames(t)}catch(e){return await(t=>new Promise((e=>setTimeout(e,t))))(1500),this.awaitColorwaySizeAssetFrames(t)}}async requestThenGetColorwaySizeAssetFrames(t){var e,n;const[r,s]=await(i=this.getColorwaySizeAssetFromSku(t),i.then((t=>[null,t])).catch((t=>[t])));var i;if(r)throw r;try{return await this.requestColorwaySizeAssetFrames(s.id),this.awaitColorwaySizeAssetFrames(t)}catch(r){if(!r.recommended_size_id)throw new Error(r);const t=r,i=(await this.getStyles([s.style_id],null)).get(s.style_id);if(!(null==i?void 0:i.sizes))throw new Yf;const o=(null===(e=i.sizes[t.recommended_size_id])||void 0===e?void 0:e.label)||(null===(n=i.sizes[t.recommended_size_id])||void 0===n?void 0:n.size),a=t.available_size_ids.filter((t=>{var e;return(null===(e=i.sizes[t])||void 0===e?void 0:e.size)!==o})).map((t=>{var e,n;return(null===(e=i.sizes[t])||void 0===e?void 0:e.label)||(null===(n=i.sizes[t])||void 0===n?void 0:n.size)}));throw new Xf(o,a)}}async getColorwaySizeAssetFromSku(t){const e=await this.getColorwaySizeAssets(null,[t]);if(!(null==e?void 0:e.size))throw new Qf;return Array.from(e.values())[0]}async getColorwaySizeAssets(t,e){const n=[qh("brand_id","==",this.brandId)];t&&n.push(qh("style_id","==",t)),(null==e?void 0:e.length)>0&&n.push(qh("sku","in",e));try{const t=await this.firebase.getDocs("colorway_size_assets",n),e=new Map;return t.forEach((t=>{const n=t.data();e.set(n.id,n)})),e}catch(t){return ep(t)}}async requestColorwaySizeAssetFrames(t){if(!this.isLoggedIn)throw new Wf;await np.Post(this.user,`/colorway-size-assets/${t}/frames`)}async getColorwaySizeAssetFrames(t){var e,n,r;const s=await this.user.getUserProfile(),i=(null===(r=null===(n=null===(e=null==s?void 0:s.vto)||void 0===e?void 0:e[this.brandId])||void 0===n?void 0:n[t])||void 0===r?void 0:r.frames)||[];if(!i.length)throw new Hf;if(!await(t=>{const e=new Image;return e.src=t,new Promise((t=>{e.onerror=()=>t(!1),e.onload=()=>t(!0)}))})(i[0]))throw new Hf;return i}}rp.avatarTimeout=12e4,rp.vtoTimeout=12e4;const sp=(t,e="dev")=>("dev"!==e&&"development"!==e||console.warn("TfrShop is in development mode"),el.getInstance().setEnv(e),new rp(t,new tp));var ip,op=Object.freeze({__proto__:null}),ap=Object.freeze({__proto__:null});!function(t){t.NOT_CREATED="NOT_CREATED",t.CREATED="CREATED",t.PENDING="PENDING"}(ip||(ip={}));var cp=Object.freeze({__proto__:null,get AvatarState(){return ip}});const up=rp.vtoTimeout;export{Jf as Errors,up as VTO_TIMEOUT_MS,sp as initShop,op as requests,ap as responses,cp as types};
|
|
3168
3168
|
//# sourceMappingURL=index.min.js.map
|