@zuzjs/flare 0.2.2 → 0.2.5
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 +196 -33
- package/dist/index.cjs +2 -2
- package/dist/index.d.cts +351 -41
- package/dist/index.d.ts +351 -41
- package/dist/index.js +2 -2
- package/package.json +2 -2
package/dist/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import {Credentials,Anonymous,Google,GitHub,Facebook,Dropbox,Apple,Twitter,AuthGuard}from'@zuzjs/auth';export{Anonymous,Apple,AuthGuard,Credentials,Dropbox,Facebook,GitHub,Google,Providers,Twitter,setupProvider}from'@zuzjs/auth';import {uuid2,withGet,withPut,withPatch,withPost}from'@zuzjs/core';var l=class extends Error{constructor(t,n,i){super(t);this.code=n;this.cause=i;this.name="ZuzFlareError";}};var V={AuthenticationFailed:"AUTHENTICATION_FAILED",WriteFailed:"WRITE_FAILED",QueryFailed:"QUERY_FAILED",ParseError:"PARSE_ERROR"},h=V;var z=(d=>(d.SUBSCRIBE="subscribe",d.UNSUBSCRIBE="unsubscribe",d.WRITE="write",d.DELETE="delete",d.AUTH="auth",d.PING="ping",d.OFFLINE_SYNC="offline_sync",d.CALL="call",d.QUERY="query",d.PRESENCE_JOIN="presence_join",d.PRESENCE_LEAVE="presence_leave",d.PRESENCE_HEARTBEAT="presence_heartbeat",d))(z||{}),Y=(d=>(d.SNAPSHOT="snapshot",d.CHANGE="change",d.ERROR="error",d.ACK="ack",d.PONG="pong",d.AUTH_OK="auth_ok",d.OFFLINE_ACK="offline_ack",d.CALL_RESPONSE="call_response",d.QUERY_RESULT="query_result",d.PRESENCE_STATE="presence_state",d.PRESENCE_JOIN="presence_join",d.PRESENCE_LEAVE="presence_leave",d))(Y||{});function _(o){let e=[];for(let[t,n]of Object.entries(o))if(typeof n=="string"){let i=n.match(/^(>=|<=|!=|>|<|==)\s*(.+)$/);if(i){let[,s,r]=i;e.push({field:t,op:s,value:B(r.trim())});}else e.push({field:t,op:"==",value:n});}else Array.isArray(n)?e.push({field:t,op:"in",value:n}):e.push({field:t,op:"==",value:n});return e}function B(o){if(!isNaN(Number(o)))return Number(o);if(o==="true")return true;if(o==="false")return false;if(o==="null")return null;if(o!=="undefined")return o}var k=class{constructor(e,t,n){this.client=e;this.collection=t;this.legacyId=n;}whereCondition;updateData;setData;deleteOp=false;promise;where(e){return this.whereCondition=e,this}update(e){return this.updateData=e,this}set(e){return this.setData=e,this}delete(){return this.deleteOp=true,this}getDocId(){if(this.legacyId)return this.legacyId;if(this.whereCondition&&this.whereCondition.id){let e=this.whereCondition.id;if(typeof e=="string")return e}throw new l('Document ID not specified. Use .where({ id: "..." }) or doc(collection, id)',h.QueryFailed)}async execute(){return this._execute()}async _execute(){let e=this.getDocId();if(this.deleteOp){await this.client.send("delete",{collection:this.collection,docId:e});return}if(this.updateData){await this.client.send("write",{collection:this.collection,docId:e,data:this.updateData,merge:true});return}if(this.setData){await this.client.send("write",{collection:this.collection,docId:e,data:this.setData,merge:false});return}return this.get()}then(e,t){return this.promise||(this.promise=this._execute()),this.promise.then(e,t)}async get(){let e=this.getDocId(),t=uuid2(18);return new Promise((n,i)=>{let s=this.client.subscribe(t,this.collection,e,void 0,r=>{r.type==="snapshot"&&(s(),n(r.data));});setTimeout(()=>{s(),i(new Error("Document fetch timeout"));},1e4);})}onSnapshot(e){let t=this.getDocId(),n=uuid2(18);return this.client.subscribe(n,this.collection,t,void 0,e)}};var F=class{constructor(e,t,n){this.client=e;this.collection=t;this.id=n;}async get(){return new k(this.client,this.collection,this.id).get()}async set(e){await this.client.send("write",{collection:this.collection,docId:this.id,data:e,merge:false});}async update(e){await this.client.send("write",{collection:this.collection,docId:this.id,data:e,merge:true});}async delete(){await this.client.send("delete",{collection:this.collection,docId:this.id});}onSnapshot(e){let t=uuid2(18),n=()=>{};return n=this.client.subscribe(t,this.collection,this.id,void 0,i=>{i.type==="snapshot"&&(e(i),n());}),n}onDocUpdated(e){let t=uuid2(18);return this.client.subscribe(t,this.collection,this.id,void 0,n=>{n.type==="change"&&(n.operation==="update"||n.operation==="replace")&&n.data&&e(n.data,n.docId);},{skipSnapshot:true})}onDocModified(e){return this.onDocUpdated(e)}onDocChange(e){return this.onDocUpdated(e)}onDocDeleted(e){let t=uuid2(18);return this.client.subscribe(t,this.collection,this.id,void 0,n=>{n.type==="change"&&n.operation==="delete"&&e(n.docId);},{skipSnapshot:true})}onDocChanged(e){let t=uuid2(18);return this.client.subscribe(t,this.collection,this.id,void 0,n=>{n.type==="change"&&e(n.data??null,n.docId,n.operation);},{skipSnapshot:true})}},T=F;var D=class o{constructor(e,t){this.client=e;this.collection=t;}sq={};promise;doc(e){return new T(this.client,this.collection,e)}clone(e){let t=new o(this.client,this.collection);return t.sq={...this.sq,...e},t}where(e,t,n){let i;return typeof e=="string"?i=[{field:e,op:t,value:n}]:i=_(e),this.clone({where:[...this.sq.where??[],...i]})}orWhere(e){return this.clone({where:[...this.sq.where??[],{or:e}]})}orderBy(e,t="asc"){return this.clone({orderBy:[...this.sq.orderBy??[],{field:e,dir:t}]})}limit(e){return this.clone({limit:e})}offset(e){return this.clone({offset:e})}startAt(...e){return this.clone({startAt:{values:e}})}startAfter(...e){return this.clone({startAfter:{values:e}})}endAt(...e){return this.clone({endAt:{values:e}})}endBefore(...e){return this.clone({endBefore:{values:e}})}aggregate(...e){return this.clone({aggregate:[...this.sq.aggregate??[],...e]})}count(e="count"){return this.aggregate({fn:"count",alias:e})}sum(e,t){return this.aggregate({fn:"sum",field:e,alias:t??`sum_${e}`})}avg(e,t){return this.aggregate({fn:"avg",field:e,alias:t??`avg_${e}`})}min(e,t){return this.aggregate({fn:"min",field:e,alias:t??`min_${e}`})}max(e,t){return this.aggregate({fn:"max",field:e,alias:t??`max_${e}`})}distinct(e,t){return this.aggregate({fn:"distinct",field:e,alias:t??`distinct_${e}`})}groupBy(...e){return this.clone({groupBy:{fields:e}})}having(e,t,n){return this.clone({having:[...this.sq.having??[],{field:e,op:t,value:n}]})}join(e){return this.clone({joins:[...this.sq.joins??[],e]})}select(...e){return this.clone({select:e})}distinctField(e){return this.clone({distinctField:e})}vectorSearch(e){return this.clone({vectorSearch:e})}async get(){return this._execute()}_isStructured(){return !!(this.sq.orderBy?.length||this.sq.aggregate?.length||this.sq.groupBy||this.sq.having?.length||this.sq.joins?.length||this.sq.vectorSearch||this.sq.distinctField||this.sq.offset||this.sq.startAt||this.sq.startAfter||this.sq.endAt||this.sq.endBefore||this.sq.select?.length)}async _execute(){return this._isStructured()?this._executeQuery():this._executeSubscribe()}async _executeQuery(){return (await this.client.send("query",{collection:this.collection,query:this.sq})).data??[]}async _executeSubscribe(){let e=uuid2(18);return new Promise((t,n)=>{let i=Object.keys(this.sq).length>0?this.sq:void 0,s=this.client.subscribe(e,this.collection,void 0,i,r=>{r.type==="snapshot"&&(s(),t(r.data));});setTimeout(()=>{s(),n(new Error("Collection fetch timeout"));},1e4);})}then(e,t){return this.promise||(this.promise=this._execute()),this.promise.then(e,t)}onSnapshot(e){let t=uuid2(18),n=Object.keys(this.sq).length>0?this.sq:void 0,i=()=>{};return i=this.client.subscribe(t,this.collection,void 0,n,s=>{s.type==="snapshot"&&(e(s),i());}),i}onDocAdded(e){let t=uuid2(18),n=Object.keys(this.sq).length>0?this.sq:void 0;return this.client.subscribe(t,this.collection,void 0,n,i=>{i.type==="change"&&i.operation==="insert"&&i.data!=null&&e(i.data,i.docId);},{skipSnapshot:true})}onDocUpdated(e){let t=uuid2(18),n=Object.keys(this.sq).length>0?this.sq:void 0;return this.client.subscribe(t,this.collection,void 0,n,i=>{i.type==="change"&&(i.operation==="update"||i.operation==="replace")&&i.data!=null&&e(i.data,i.docId);},{skipSnapshot:true})}onDocModified(e){return this.onDocUpdated(e)}onDocChange(e){return this.onDocUpdated(e)}onDocDeleted(e){let t=uuid2(18),n=Object.keys(this.sq).length>0?this.sq:void 0;return this.client.subscribe(t,this.collection,void 0,n,i=>{i.type==="change"&&i.operation==="delete"&&e(i.docId);},{skipSnapshot:true})}onDocChanged(e){let t=uuid2(18),n=Object.keys(this.sq).length>0?this.sq:void 0;return this.client.subscribe(t,this.collection,void 0,n,i=>{i.type==="change"&&e(i.data??null,i.docId,i.operation);},{skipSnapshot:true})}async add(e){let t=uuid2(18),n=this.doc(t);return await n.set(e),n}update(e){return new k(this.client,this.collection).update(e)}delete(){return new k(this.client,this.collection).delete()}},N=D;async function Z(o){let e=o.replace(/-----BEGIN PUBLIC KEY-----/,"").replace(/-----END PUBLIC KEY-----/,"").replace(/\s+/g,""),t=typeof atob<"u"?atob(e):Buffer.from(e,"base64").toString("binary"),n=new Uint8Array(t.length);for(let s=0;s<t.length;s++)n[s]=t.charCodeAt(s);return (globalThis.crypto??(await import('crypto')).webcrypto).subtle.importKey("spki",n.buffer,{name:"RSA-OAEP",hash:"SHA-256"},false,["encrypt"])}async function X(o,e){let t=await Z(e),n=new TextEncoder().encode(JSON.stringify(o)),s=await(globalThis.crypto??(await import('crypto')).webcrypto).subtle.encrypt({name:"RSA-OAEP"},t,n),r=typeof btoa<"u"?btoa(String.fromCharCode(...new Uint8Array(s))):Buffer.from(s).toString("base64");return JSON.stringify({enc:"rsa",data:r})}var w=class{socket=null;reconnectInterval;maxReconnectDelay;isConnected=false;shouldReconnect=true;options;messageQueue=[];heartbeatInterval=null;connectionTimeout=null;constructor(e){this.options=e,this.reconnectInterval=e.reconnectDelay||2,this.maxReconnectDelay=e.maxReconnectDelay||60,this.log("Transport initialized",e.url);}connect(){if(this.socket){this.log("Socket already exists, skipping connection");return}this.log("Connecting to",this.options.url),this.socket=new WebSocket(this.options.url),this.connectionTimeout=setTimeout(()=>{this.isConnected||(this.log("Connection timeout"),this.socket?.close(),this.handleReconnect());},1e4),this.socket.onopen=()=>{this.connectionTimeout&&(clearTimeout(this.connectionTimeout),this.connectionTimeout=null),this.isConnected=true,this.reconnectInterval=this.options.reconnectDelay||2,this.log("Connected to server"),this.options.onOpen?.(),this.startHeartbeat(),this.flushQueue();},this.socket.onmessage=e=>{try{let t=JSON.parse(e.data);this.options.onMessage(t);}catch(t){this.log("Parse error",t),this.options.onError?.(t);}},this.socket.onerror=e=>{this.log("WebSocket error",e),this.options.onError?.(new Error("WebSocket error"));},this.socket.onclose=e=>{this.connectionTimeout&&(clearTimeout(this.connectionTimeout),this.connectionTimeout=null),this.isConnected=false,this.socket=null,this.stopHeartbeat(),this.log("Connection closed",e.code,e.reason),this.options.onClose?.(),e.code!==1e3&&this.shouldReconnect&&this.options.autoReconnect&&this.handleReconnect();};}handleReconnect(){let e=this.reconnectInterval*1e3;this.log(`Reconnecting in ${this.reconnectInterval}s...`),setTimeout(()=>{this.reconnectInterval=Math.min(this.reconnectInterval*2,this.maxReconnectDelay),this.connect();},e);}startHeartbeat(){this.heartbeatInterval=setInterval(()=>{this.isConnected&&this.send({type:"ping",id:Date.now().toString(),ts:Date.now()});},3e4);}stopHeartbeat(){this.heartbeatInterval&&(clearInterval(this.heartbeatInterval),this.heartbeatInterval=null);}flushQueue(){for(this.log("Flushing message queue",this.messageQueue.length);this.messageQueue.length>0;){let e=this.messageQueue.shift();e&&this.send(e);}}send(e){if(this.socket&&this.socket.readyState===WebSocket.OPEN){let t=n=>{try{this.socket.send(n),this.log("Sent message",e);}catch(i){this.log("Send error",i),this.messageQueue.push(e);}};this.options.publicKey?X(e,this.options.publicKey).then(t).catch(n=>{this.log("RSA encrypt error \u2014 sending plaintext",n),t(JSON.stringify(e));}):t(JSON.stringify(e));}else this.log("Socket not ready, queueing message"),this.messageQueue.push(e);}disconnect(){this.shouldReconnect=false,this.stopHeartbeat(),this.socket&&(this.socket.close(1e3,"Client disconnect"),this.socket=null),this.isConnected=false,this.log("Disconnected");}get connected(){return this.isConnected}log(...e){this.options.debug&&console.log("[FlareTransport]",...e);}};var v=class{transport;config;pendingAcks=new Map;subscriptions=new Map;activeSubscriptions=new Map;offlineQueue=[];currentState="disconnected";connectionListeners=[];errorListeners=[];isDebug=false;socketAuthUid="anon";pendingSubscriptionReplay=false;subscriptionReplayPromise=Promise.resolve();requestTraceSeq=0;requestTimingEnabled=true;presenceCallbacks=new Map;presenceJoinCbs=new Map;presenceLeaveCbs=new Map;presenceHeartbeatTimer;embedder;vectorSchema=new Map;throwFetchFlareError(e,t,n){let i=e,s=typeof i?.error=="string"&&i.error.length>0?i.error:n,r=typeof i?.message=="string"&&i.message.length>0?i.message:t;throw new l(r,s,e)}nowMs(){return typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now()}normalizeHeaders(e){if(!e)return {};let t={};if(e instanceof Headers)e.forEach((n,i)=>{t[i]=n;});else if(Array.isArray(e))for(let[n,i]of e)t[String(n)]=String(i);else for(let[n,i]of Object.entries(e))t[String(n)]=String(i);return t}redactHeaders(e){let t={...e};for(let n of Object.keys(t)){let i=n.toLowerCase();(i==="authorization"||i==="x-flare-csrf"||i==="x-csrf-token")&&(t[n]="[redacted]");}return t}logHttpTiming(...e){this.requestTimingEnabled&&this.log("[FlareClient][http]",...e);}mergeHeaders(e,t){if(!e)return t;if(e instanceof Headers){let n=new Headers(e);for(let[i,s]of Object.entries(t))n.set(i,s);return n}return Array.isArray(e)?[...e,...Object.entries(t)]:{...e,...t}}async timedFetch(e,t,n){let i=++this.requestTraceSeq,s=this.nowMs(),r=String(n?.method??"GET").toUpperCase(),a=this.redactHeaders(this.normalizeHeaders(n?.headers));this.logHttpTiming(`#${i} ${e} start`,{method:r,url:t,headers:a,hasBody:!!n?.body});try{let c=this.mergeHeaders(n?.headers,{"x-flare-request-id":String(i)}),f=this.normalizeHeaders(c),E=this.redactHeaders(f),p={timeout:Math.ceil((this.config.connectionTimeout??1e4)/1e3),ignoreKind:!0,headers:f,withCredentials:n?.credentials==="include",returnRawResponse:!0,appendCookiesToBody:!1,appendTimestamp:!1};this.logHttpTiming(`#${i} ${e} request`,{method:r,url:t,headers:E,hasBody:!!n?.body});let d=n?.body,x=r.toUpperCase(),C=x==="GET"?await withGet(t,p):x==="PUT"?await withPut(t,d,p):x==="PATCH"?await withPatch(t,d,p):await withPost(t,d,p),M=C?.headers??{},H={status:Number(C?.status??0),ok:Number(C?.status??0)>=200&&Number(C?.status??0)<300,headers:{get:j=>{let Q=j.toLowerCase();for(let[J,G]of Object.entries(M))if(J.toLowerCase()===Q)return String(G);return null}},json:async()=>C?.data??{}},q=this.nowMs()-s;return this.logHttpTiming(`#${i} ${e} response`,{status:H.status,networkMs:Number(q.toFixed(2))}),{response:H,requestId:i,startedAtMs:s,networkMs:q,method:r,url:t}}catch(c){let f=this.nowMs()-s;throw this.logHttpTiming(`#${i} ${e} failed`,{networkMs:Number(f.toFixed(2)),message:c?.message??String(c)}),c}}async parseJsonWithTiming(e,t){let n=this.nowMs(),i=await t.response.json().catch(()=>({})),s=this.nowMs()-n,r=this.nowMs()-t.startedAtMs;return this.logHttpTiming(`#${t.requestId} ${e} complete`,{method:t.method,url:t.url,status:t.response.status,networkMs:Number(t.networkMs.toFixed(2)),parseMs:Number(s.toFixed(2)),totalMs:Number(r.toFixed(2))}),i}getHttpBase(){if(this.config.httpBase)return this.config.httpBase.replace(/\/$/,"");let e=new URL(this.config.endpoint);return `${e.protocol}//${e.host}`}log(...e){this.isDebug&&console.log("[FlareClient]",...e);}constructor(e){this.config={autoReconnect:true,reconnectDelay:2,maxReconnectDelay:60,debug:false,connectionTimeout:1e4,...e},this.isDebug=this.config.debug||false,this.requestTimingEnabled=this.config.requestTiming??true;let{hostname:t,port:n,protocol:i}=new URL(this.config.endpoint),s=i==="https:",c=`${s?"wss":"ws"}://${t}:${n||(s?"443":"80")}/?appId=${this.config.appId}${this.config.apiKey?`&apiKey=${this.config.apiKey}`:""}`;this.transport=new w({url:c,publicKey:this.config.publicKey,autoReconnect:this.config.autoReconnect,reconnectDelay:this.config.reconnectDelay,maxReconnectDelay:this.config.maxReconnectDelay,onMessage:f=>this.handleIncoming(f),onOpen:()=>this.onConnected(),onClose:()=>this.onDisconnected(),onError:f=>this.handleTransportError(f),debug:this.isDebug});}connect(){this.setState("connecting"),this.transport.connect();}disconnect(){this.transport.disconnect(),this.setState("disconnected");}get connectionState(){return this.currentState}get isConnected(){return this.currentState==="connected"}onConnectionStateChange(e){return this.connectionListeners.push(e),()=>{this.connectionListeners=this.connectionListeners.filter(t=>t!==e);}}onError(e){return this.errorListeners.push(e),()=>{this.errorListeners=this.errorListeners.filter(t=>t!==e);}}collection(e){return new N(this,e)}doc(e,t){return t!==void 0?new T(this,e,t):new k(this,e)}async ping(){let e=Date.now();return await this.send("ping",{}),Date.now()-e}async call(e,t={}){let n=await this.send("call",{topic:e,payload:t});if(!n.success)throw new l(n.error??`CALL "${e}" failed`,h.QueryFailed);return n.result}async query(e,t={}){return (await this.send("query",{collection:e,query:t})).data??[]}setEmbedder(e){this.embedder=e;}markVectorField(e,t,n={dimensions:1536}){this.vectorSchema.has(e)||this.vectorSchema.set(e,new Map),this.vectorSchema.get(e).set(t,n);}async embedVectorFields(e,t){let n=this.vectorSchema.get(e);if(!n)return t;let i={...t};for(let[s,r]of n){let a=i[s];if(typeof a=="string"){let c=r.embed??this.embedder;if(!c){this.log(`[vector] No embedder for field "${s}" \u2014 storing raw text`);continue}i[s]=await c(a);}}return i}async joinPresence(e,t){return await this.send("presence_join",{room:e,meta:t}),this._startPresenceHeartbeat(e,t),()=>this.leavePresence(e)}async leavePresence(e){await this.send("presence_leave",{room:e}),this._stopPresenceHeartbeat();}onPresenceState(e,t){return this.presenceCallbacks.has(e)||this.presenceCallbacks.set(e,[]),this.presenceCallbacks.get(e).push(t),()=>{let n=this.presenceCallbacks.get(e)??[];this.presenceCallbacks.set(e,n.filter(i=>i!==t));}}onPresenceJoin(e,t){return this.presenceJoinCbs.has(e)||this.presenceJoinCbs.set(e,[]),this.presenceJoinCbs.get(e).push(t),()=>{let n=this.presenceJoinCbs.get(e)??[];this.presenceJoinCbs.set(e,n.filter(i=>i!==t));}}onPresenceLeave(e,t){return this.presenceLeaveCbs.has(e)||this.presenceLeaveCbs.set(e,[]),this.presenceLeaveCbs.get(e).push(t),()=>{let n=this.presenceLeaveCbs.get(e)??[];this.presenceLeaveCbs.set(e,n.filter(i=>i!==t));}}_startPresenceHeartbeat(e,t){this.presenceHeartbeatTimer||(this.presenceHeartbeatTimer=setInterval(()=>{this.isConnected&&this.send("presence_heartbeat",{meta:t}).catch(()=>{});},2e4));}_stopPresenceHeartbeat(){this.presenceHeartbeatTimer&&(clearInterval(this.presenceHeartbeatTimer),this.presenceHeartbeatTimer=void 0);}async syncOffline(){if(this.offlineQueue.length===0)return;this.log("Syncing offline operations",this.offlineQueue.length);let e=[...this.offlineQueue];this.offlineQueue.length=0;let t=await this.send("offline_sync",{operations:e});t.conflicts&&t.conflicts.length>0&&(this.log("Offline sync conflicts",t.conflicts),t.conflicts.forEach(n=>{let i=e.find(s=>s.id===n.operationId);i&&this.offlineQueue.push(i);}));}async activateSubscription(e){if(!this.isConnected){this.pendingSubscriptionReplay=true;return}this.subscriptions.set(e.liveId,e.callback);try{let t=await this.send("subscribe",{collection:e.collection,docId:e.docId,query:e.query,skipSnapshot:e.options.skipSnapshot});if(!this.activeSubscriptions.has(e.baseId)){this.subscriptions.delete(e.liveId);return}t.subscriptionId&&t.subscriptionId!==e.liveId&&(this.subscriptions.delete(e.liveId),e.liveId=t.subscriptionId,this.subscriptions.set(e.liveId,e.callback),this.log("Subscription remapped",e.baseId,"\u2192",e.liveId));}catch(t){this.subscriptions.delete(e.liveId),this.pendingSubscriptionReplay=true,this.log("Subscription failed",t);}}async replayActiveSubscriptions(){if(!this.isConnected){this.pendingSubscriptionReplay=true;return}let e=Array.from(this.activeSubscriptions.values());if(e.length===0){this.pendingSubscriptionReplay=false;return}this.pendingSubscriptionReplay=false,this.subscriptionReplayPromise=this.subscriptionReplayPromise.then(async()=>{for(let t of e){if(!this.activeSubscriptions.has(t.baseId))continue;let n=t.liveId;this.subscriptions.delete(n),t.liveId=t.baseId,n&&await this.send("unsubscribe",{subscriptionId:n}).catch(()=>{}),await this.activateSubscription(t);}}).catch(t=>{this.pendingSubscriptionReplay=true,this.log("Subscription replay failed",t);}),await this.subscriptionReplayPromise;}subscribe(e,t,n,i,s,r={}){this.log("Creating subscription",e,t,n);let a={baseId:e,liveId:e,collection:t,docId:n,query:i,callback:s,options:r};return this.activeSubscriptions.set(e,a),this.activateSubscription(a).catch(c=>{this.log("Subscription activation failed",c);}),()=>{let f=this.activeSubscriptions.get(e)?.liveId??e;this.log("Unsubscribing",f),this.activeSubscriptions.delete(e),this.subscriptions.delete(f),this.isConnected&&this.send("unsubscribe",{subscriptionId:f}).catch(E=>this.log("Unsubscribe failed",E));}}async send(e,t){return e==="write"&&t.collection&&t.data&&(t={...t,data:await this.embedVectorFields(t.collection,t.data)}),new Promise((n,i)=>{let s=uuid2(18),r={id:s,type:e,ts:Date.now(),...t};this.pendingAcks.set(s,a=>{a.type==="error"?i(new Error(`[${a.code}] ${a.message}`)):n(a);}),this.isConnected?this.transport.send(r):(this.log("Queueing message for offline",r),this.offlineQueue.push(r),i(new Error("Not connected - message queued"))),setTimeout(()=>{this.pendingAcks.has(s)&&(this.pendingAcks.delete(s),i(new Error("Request timeout")));},this.config.connectionTimeout);})}handleTransportError(e){this.log("Transport error",e),this.errorListeners.forEach(t=>{try{t(e);}catch(n){this.log("Error listener error",n);}});}onConnected(){this.setState("connected"),this.log("Connected to FlareServer"),this.activeSubscriptions.size>0&&(this.pendingSubscriptionReplay=true),this.offlineQueue.length>0&&this.syncOffline().catch(e=>{this.log("Offline sync failed",e);});}onDisconnected(){this.currentState!=="disconnected"&&this.setState("reconnecting"),this.activeSubscriptions.size>0&&(this.pendingSubscriptionReplay=true),this.log("Disconnected from FlareServer");}setState(e){this.currentState!==e&&(this.currentState=e,this.log("Connection state changed",e),this.connectionListeners.forEach(t=>{try{t(e);}catch(n){this.log("Connection listener error",n);}}));}handleIncoming(e){if(this.log("Received message",e.type,e),e.type==="ack"||e.type==="pong"||e.type==="auth_ok"||e.type==="call_response"||e.type==="query_result"){let t=this.pendingAcks.get(e.correlationId||e.id);t&&(t(e),this.pendingAcks.delete(e.correlationId||e.id));return}if(e.type==="error"){this.log("Server error",e.code,e.message);let t=new Error(`[${e.code}] ${e.message}`);if(this.errorListeners.forEach(n=>{try{n(t);}catch(i){this.log("Error listener error",i);}}),e.correlationId){let n=this.pendingAcks.get(e.correlationId);n&&(n(e),this.pendingAcks.delete(e.correlationId));}return}if(e.type==="presence_state"){(this.presenceCallbacks.get(e.room)??[]).forEach(n=>{try{n(e.members);}catch{}});return}if(e.type==="presence_join"){(this.presenceJoinCbs.get(e.room)??[]).forEach(n=>{try{n(e);}catch{}});return}if(e.type==="presence_leave"){(this.presenceLeaveCbs.get(e.room)??[]).forEach(n=>{try{n(e.uid);}catch{}});return}if(e.type==="snapshot"){let t=this.subscriptions.get(e.subscriptionId);if(t){let n={type:"snapshot",subscriptionId:e.subscriptionId,collection:e.collection,data:Array.isArray(e.data)?e.data:e.data!=null?[e.data]:[]};try{t(n);}catch(i){this.log("Subscription callback error",i);}}return}if(e.type==="change"){let t=this.subscriptions.get(e.subscriptionId);if(t){let n={type:"change",subscriptionId:e.subscriptionId,collection:e.collection,docId:e.docId,operation:e.operation,data:e.operation==="delete"?null:e.data};try{t(n);}catch(i){this.log("Subscription callback error",i);}}}}};var A=class extends v{authToken;userId;authGuard;authConfig;csrfToken;csrfInitPromise;csrfBootstrapAttempted=false;authSession=null;authStateListeners=[];authConfigListeners=[];getDefaultCsrfCookieName(){return `__flare_csrf_${this.config.appId.replace(/[^a-zA-Z0-9_-]/g,"_")}`}getCsrfCookieName(){return this.authConfig?.cookie?.csrfTokenName??this.getDefaultCsrfCookieName()}getCsrfToken(){return this.getCookieValue(this.getCsrfCookieName())??this.csrfToken??null}getCookieValue(e){if(typeof document>"u")return null;let t=document.cookie.split(";").map(i=>i.trim()).find(i=>i.startsWith(`${e}=`)||i.startsWith(`${encodeURIComponent(e)}=`));if(!t)return null;let n=t.indexOf("=");return n>=0?decodeURIComponent(t.slice(n+1)):null}extractCsrfToken(e,t){let n=e,i=typeof n?.csrfToken=="string"?String(n.csrfToken):typeof n?.csrf_token=="string"?String(n.csrf_token):void 0;if(i)return i;if(!t)return;let s=t.headers.get("x-flare-csrf")??t.headers.get("x-csrf-token")??t.headers.get("csrf-token");return typeof s=="string"&&s.length>0?s:void 0}getCsrfHeaders(){let e=this.getCsrfToken();return e?{"x-flare-csrf":e}:{}}setCsrfToken(e){this.csrfToken=e,this.csrfBootstrapAttempted=true,this.log("CSRF token injected",{length:e.length});}async ensureCsrfProtection(){if(this.getCsrfToken()){this.csrfBootstrapAttempted=true;return}if(this.config.httpBase){this.csrfBootstrapAttempted=true;return}this.csrfBootstrapAttempted||(this.csrfInitPromise||(this.csrfBootstrapAttempted=true,this.csrfInitPromise=this.loadAuthConfig().then(()=>{}).finally(()=>{this.csrfInitPromise=void 0;})),await this.csrfInitPromise,this.getCsrfToken()||this.log("CSRF token unavailable after auth config load",{hasAuthConfig:!!this.authConfig,csrfCookieName:this.getCsrfCookieName()}));}async loadAuthConfig(){let e=this.getHttpBase(),t=new URLSearchParams({appId:this.config.appId});this.config.apiKey&&t.set("apiKey",this.config.apiKey);let n=`${e}/auth/config?${t.toString()}`,i=await this.timedFetch("loadAuthConfig",n,{credentials:"include",headers:this.config.apiKey?{"x-flare-api-key":this.config.apiKey}:{}}),s=await this.parseJsonWithTiming("loadAuthConfig",i);return i.response.ok||this.throwFetchFlareError(s,"Failed to load auth config",h.QueryFailed),this.authConfig=s,this.csrfToken=this.extractCsrfToken(s,i.response)??this.csrfToken,this.authConfigListeners.forEach(r=>{try{r(this.authConfig);}catch(a){this.log("Auth config listener error",a);}}),this.authConfig}async fetchAuthConfig(){return this.authConfig?this.authConfig:this.loadAuthConfig()}onAuthConfigLoaded(e){return this.authConfigListeners.push(e),this.authConfig&&e(this.authConfig),()=>{this.authConfigListeners=this.authConfigListeners.filter(t=>t!==e);}}setAuthSession(e){this.authSession=e,e?(this.authToken=e.accessToken,this.userId=e.uid):(this.authToken=void 0,this.userId=void 0),this.authStateListeners.forEach(t=>{try{t(this.authSession);}catch(n){this.log("Auth state listener error",n);}});}onAuthStateChanged(e){this.authStateListeners.push(e);try{e(this.authSession);}catch(t){this.log("Auth state listener error during initialization",t);}return ()=>{this.authStateListeners=this.authStateListeners.filter(t=>t!==e);}}onAuthStateChange(e){return this.onAuthStateChanged(e)}get currentUser(){return this.userId}getCurrentUser(){return this.currentUser}async syncSocketAuth(e){if(!this.isConnected)return;let t=await this.send("auth",e?{token:e}:{});if(t.type!=="auth_ok")throw new l("Socket auth sync failed",h.AuthenticationFailed);if(!e||t.uid==="anon"){this.authToken=void 0,this.userId=void 0,await this.updateSocketIdentity("anon");return}this.authToken=typeof t.token=="string"?t.token:e,this.userId=typeof t.uid=="string"?t.uid:this.userId,await this.updateSocketIdentity(typeof t.uid=="string"?t.uid:this.userId);}async updateSocketIdentity(e,t=false){let n=typeof e=="string"&&e.length>0?e:"anon",i=n!==this.socketAuthUid;this.socketAuthUid=n,(i||t||this.pendingSubscriptionReplay)&&this.activeSubscriptions.size>0&&await this.replayActiveSubscriptions();}onConnected(){super.onConnected(),this.authSession?.accessToken&&this.syncSocketAuth(this.authSession.accessToken).catch(e=>{this.log("Socket auth sync failed after connect",e);});}handleIncoming(e){if(e.type==="auth_ok"&&!e.correlationId){let t=typeof e.token=="string"?e.token:void 0,n=typeof e.uid=="string"?e.uid:void 0;this.updateSocketIdentity(n,this.pendingSubscriptionReplay).catch(i=>{this.log("Socket identity update failed",i);}),t&&n&&n!=="anon"&&n!=="__admin__"?this.fetchAuthMe(t).then(i=>{this.setAuthSession({uid:n,accessToken:t,refreshToken:this.authSession?.refreshToken??null,email:i?.email??null,emailVerified:i?.email_verified});}).catch(()=>{this.setAuthSession({uid:n,accessToken:t,refreshToken:this.authSession?.refreshToken??null});}):n==="anon"&&this.authSession&&this.setAuthSession(null);}super.handleIncoming(e);}async auth(e){let t=await this.send("auth",{token:e});if(t.type==="auth_ok"){let n=t.token??e;this.authToken=n,this.userId=t.uid;let i=await this.fetchAuthMe(n).catch(()=>null);return console.log("--profile",i),this.setAuthSession({uid:t.uid??t.id,accessToken:n,refreshToken:this.authSession?.refreshToken??null,email:i?.email??null,emailVerified:i?.email_verified}),await this.updateSocketIdentity(t.uid),this.log("Authentication successful",t.uid),{uid:t.uid,token:t.token??e}}throw new l("Authentication failed",h.AuthenticationFailed)}async signInWithEmailAndPassword(e,t,n){try{let i=await this.requestEmailPasswordToken(e,t,n?.scope),s=await this.auth(i.access_token),r=await this.fetchAuthMe(i.access_token).catch(()=>null);return this.setAuthSession({uid:s.uid,accessToken:i.access_token,refreshToken:i.refresh_token,provider:i.provider,email:r?.email??e,emailVerified:r?.email_verified}),this.log("Credentials sign-in successful",s.uid),{...s,kind:i.kind,accessToken:i.access_token,refreshToken:i.refresh_token,authToken:i}}catch(i){let s=/invalid_email|user.not.found|no user/i.test(i?.message??"");if(n?.createIfMissing&&s){let r=await this.createUserWithEmail(e,t,{scope:n.scope,signInIfAllowed:true});if("verificationRequired"in r&&r.verificationRequired)throw new l("Email verification required before sign-in",h.AuthenticationFailed);return {uid:r.uid,token:r.token,accessToken:r.accessToken,refreshToken:r.refreshToken,authToken:r.authToken,created:true}}throw i instanceof l?i:new l(i instanceof Error?i.message:"Sign-in with email/password failed",i.error??i.code??h.AuthenticationFailed,i)}}async signInWithEmail(e,t,n){return this.signInWithEmailAndPassword(e,t,n)}async createUserWithEmail(e,t,n){let i=await this.registerWithEmail(e,t,n);if(i.verification_required)return {kind:i.kind,verificationRequired:true,emailSent:!!i.email_sent,preview:i.preview};let s=String(i.access_token??"");if(!s)throw new l("User created but no access token returned",h.AuthenticationFailed);let r={access_token:s,refresh_token:i.refresh_token?String(i.refresh_token):null,expires_in:i.expires_in?Number(i.expires_in):null,token_type:String(i.token_type??"Bearer"),scope:i.scope?String(i.scope):null,profile:null,provider:"credentials"},a=await this.auth(s),c=await this.fetchAuthMe(s).catch(()=>null);return this.setAuthSession({uid:a.uid,accessToken:s,refreshToken:r.refresh_token,provider:"credentials",email:c?.email??e,emailVerified:c?.email_verified}),{...a,accessToken:s,refreshToken:r.refresh_token,authToken:r,verificationRequired:false,emailSent:!!i.email_sent,preview:i.preview}}async createUserWithEmailAndPassword(e,t,n){return this.createUserWithEmail(e,t,n)}async signInOrCreateWithEmail(e,t,n){try{return {...await this.signInWithEmailAndPassword(e,t,{scope:n?.scope}),created:!1}}catch(i){if(!/invalid_email|user.not.found|no user/i.test(i?.message??""))throw i;let r=await this.createUserWithEmail(e,t,{scope:n?.scope,additionalParams:n?.additionalParams,signInIfAllowed:true});return "verificationRequired"in r&&r.verificationRequired?{...r,created:true}:{...r,created:true}}}async signInOrCreateWithEmailAndPassword(e,t,n){return this.signInOrCreateWithEmail(e,t,n)}async sendEmailVerification(e){let t=this.getHttpBase();await this.ensureCsrfProtection();let n=await this.timedFetch("sendEmailVerification",`${t}/auth/verify/send?appId=${encodeURIComponent(this.config.appId)}`,{method:"POST",credentials:"include",headers:{"Content-Type":"application/json",...this.getCsrfHeaders(),...this.config.apiKey?{"x-flare-api-key":this.config.apiKey}:{}},body:JSON.stringify({email:e,appId:this.config.appId,apiKey:this.config.apiKey})}),i=await this.parseJsonWithTiming("sendEmailVerification",n);return n.response.ok||this.throwFetchFlareError(i,"Failed to send verification email",h.AuthenticationFailed),i}async verifyEmailWithCode(e,t){let n=this.getHttpBase();await this.ensureCsrfProtection();let i=await this.timedFetch("verifyEmailWithCode",`${n}/auth/verify/confirm?appId=${encodeURIComponent(this.config.appId)}`,{method:"POST",credentials:"include",headers:{"Content-Type":"application/json",...this.getCsrfHeaders(),...this.config.apiKey?{"x-flare-api-key":this.config.apiKey}:{}},body:JSON.stringify({email:e,code:t,appId:this.config.appId,apiKey:this.config.apiKey})}),s=await this.parseJsonWithTiming("verifyEmailWithCode",i);return i.response.ok||this.throwFetchFlareError(s,"Email verification failed",h.AuthenticationFailed),s}async confirmEmailLink(e,t){let n=this.getHttpBase();await this.ensureCsrfProtection();let i=await this.timedFetch("confirmEmailLink",`${n}/auth/verify/confirm?appId=${encodeURIComponent(this.config.appId)}`,{method:"POST",credentials:"include",headers:{"Content-Type":"application/json",...this.getCsrfHeaders(),...this.config.apiKey?{"x-flare-api-key":this.config.apiKey}:{}},body:JSON.stringify({token:e,email:t,appId:this.config.appId,apiKey:this.config.apiKey})}),s=await this.parseJsonWithTiming("confirmEmailLink",i);return i.response.ok||this.throwFetchFlareError(s,"Email link verification failed",h.AuthenticationFailed),s}async sendAccountRecovery(e){let t=this.getHttpBase();await this.ensureCsrfProtection();let n=await this.timedFetch("sendAccountRecovery",`${t}/auth/recover/send?appId=${encodeURIComponent(this.config.appId)}`,{method:"POST",credentials:"include",headers:{"Content-Type":"application/json",...this.getCsrfHeaders(),...this.config.apiKey?{"x-flare-api-key":this.config.apiKey}:{}},body:JSON.stringify({email:e,appId:this.config.appId,apiKey:this.config.apiKey})}),i=await this.parseJsonWithTiming("sendAccountRecovery",n);return n.response.ok||this.throwFetchFlareError(i,"Failed to send recovery email",h.AuthenticationFailed),i}async recoverAccountWithCode(e,t,n){let i=this.getHttpBase();await this.ensureCsrfProtection();let s=await this.timedFetch("recoverAccountWithCode",`${i}/auth/recover/confirm?appId=${encodeURIComponent(this.config.appId)}`,{method:"POST",credentials:"include",headers:{"Content-Type":"application/json",...this.getCsrfHeaders(),...this.config.apiKey?{"x-flare-api-key":this.config.apiKey}:{}},body:JSON.stringify({email:e,code:t,newPassword:n,appId:this.config.appId,apiKey:this.config.apiKey})}),r=await this.parseJsonWithTiming("recoverAccountWithCode",s);return s.response.ok||this.throwFetchFlareError(r,"Account recovery failed",h.AuthenticationFailed),r}async recoverAccountWithToken(e,t){let n=this.getHttpBase();await this.ensureCsrfProtection();let i=await this.timedFetch("recoverAccountWithToken",`${n}/auth/recover/confirm?appId=${encodeURIComponent(this.config.appId)}`,{method:"POST",credentials:"include",headers:{"Content-Type":"application/json",...this.getCsrfHeaders(),...this.config.apiKey?{"x-flare-api-key":this.config.apiKey}:{}},body:JSON.stringify({token:e,newPassword:t,appId:this.config.appId,apiKey:this.config.apiKey})}),s=await this.parseJsonWithTiming("recoverAccountWithToken",i);return i.response.ok||this.throwFetchFlareError(s,"Account recovery failed",h.AuthenticationFailed),s}async signIn(e,t,n){let i=typeof e?.signIn=="function",s=i?e:await this.getAuthGuard(),r=i?t:e,a=i?n:t;return s.signIn(r,a)}async signInWithGoogle(e){return this.signIn("google",e)}async signInWithGitHub(e){return this.signIn("github",e)}async signInWithFacebook(e){return this.signIn("facebook",e)}async signInWithDropbox(e){return this.signIn("dropbox",e)}async handleSignInRedirect(e,t=false){let n=typeof e?.handleRedirect=="function",i=n?e:await this.getAuthGuard(),s=n?t:typeof e=="boolean"?e:false,r=await i.handleRedirect(s);if(!r||!r.access_token||!r.provider)return null;let a=await this.exchangeProviderToken(r.provider,r.access_token),c=await this.auth(a.token),f=await this.fetchAuthMe(a.token).catch(()=>null);return this.setAuthSession({uid:c.uid,accessToken:a.token,refreshToken:r.refresh_token,provider:r.provider,email:f?.email??null,emailVerified:f?.email_verified}),{...c,authToken:r,provider:r.provider}}async exchangeProviderToken(e,t){let n=`${this.getHttpBase()}/auth/exchange`;await this.ensureCsrfProtection();let i=await this.timedFetch("exchangeProviderToken",n,{method:"POST",credentials:"include",headers:{"Content-Type":"application/json",...this.getCsrfHeaders()},body:JSON.stringify({appId:this.config.appId,client_id:this.config.apiKey,provider:e,access_token:t})}),s=await this.parseJsonWithTiming("exchangeProviderToken",i);if(i.response.ok||this.throwFetchFlareError(s,"OAuth token exchange failed",h.AuthenticationFailed),!s?.token)throw new l("OAuth token exchange failed",h.ParseError,s);return {token:String(s.token)}}async getAuthGuard(){if(this.authGuard)return this.authGuard;let e=await this.fetchAuthConfig();if(!e.enabled)throw new l("Authentication is disabled for this app",h.AuthenticationFailed);let t=this.getHttpBase(),n=`${t}/auth/oauth/token?appId=${encodeURIComponent(this.config.appId)}`,i=[],s=(r,a)=>({...a,token_url:n,tokenParams:{...a.tokenParams??{},provider:r}});if(e.providers.credentials?.enabled&&i.push({...Credentials({clientId:this.config.apiKey}),token_url:`${t}/auth/token?appId=${encodeURIComponent(this.config.appId)}`,createUserUrl:`${t}/auth/register?appId=${encodeURIComponent(this.config.appId)}`,createUserGrantType:"create_user"}),e.providers.anonymous?.enabled&&i.push({...Anonymous({clientId:this.config.apiKey}),token_url:`${t}/auth/token?appId=${encodeURIComponent(this.config.appId)}`}),e.providers.google?.enabled&&e.providers.google.clientId&&i.push(s("google",Google({clientId:e.providers.google.clientId,scopes:e.providers.google.scopes}))),e.providers.github?.enabled&&e.providers.github.clientId&&i.push(s("github",GitHub({clientId:e.providers.github.clientId,scopes:e.providers.github.scopes}))),e.providers.facebook?.enabled&&e.providers.facebook.clientId&&i.push(s("facebook",Facebook({clientId:e.providers.facebook.clientId,scopes:e.providers.facebook.scopes}))),e.providers.dropbox?.enabled&&e.providers.dropbox.clientId&&i.push(s("dropbox",Dropbox({clientId:e.providers.dropbox.clientId,scopes:e.providers.dropbox.scopes}))),e.providers.apple?.enabled&&e.providers.apple.clientId&&i.push(s("apple",Apple({clientId:e.providers.apple.clientId,scopes:e.providers.apple.scopes}))),e.providers.twitter?.enabled&&e.providers.twitter.clientId&&i.push(s("twitter",Twitter({clientId:e.providers.twitter.clientId,scopes:e.providers.twitter.scopes}))),i.length===0)throw new l("No authentication providers are enabled for this app",h.AuthenticationFailed);return this.authGuard=new AuthGuard({providers:i,redirectUri:e.redirectUri}),this.authGuard}async refreshAuthSession(e){let t=this.getHttpBase();await this.ensureCsrfProtection();let n=await this.timedFetch("refreshAuthSession",`${t}/auth/refresh?appId=${encodeURIComponent(this.config.appId)}`,{method:"POST",credentials:"include",headers:{"Content-Type":"application/json",...this.getCsrfHeaders(),...this.config.apiKey?{"x-flare-api-key":this.config.apiKey}:{}},body:JSON.stringify({appId:this.config.appId,apiKey:this.config.apiKey,...e?{refresh_token:e}:{}})}),i=await this.parseJsonWithTiming("refreshAuthSession",n);if(!n.response.ok){if(n.response.status===401)return this.setAuthSession(null),await this.syncSocketAuth(null).catch(()=>{}),null;this.throwFetchFlareError(i,"Failed to refresh auth session",h.AuthenticationFailed);}let s=String(i.access_token??"");if(!s)throw new l("Refresh succeeded but no access token was returned",h.ParseError);await this.fetchAuthMe(s).catch(c=>{console.log("--fetchAuthMe error",c);});let r=await this.fetchAuthMe(s).catch(()=>null),a={uid:String(r?.id??this.authSession?.uid??this.userId??""),accessToken:s,refreshToken:i.refresh_token?String(i.refresh_token):this.authSession?.refreshToken??null,provider:this.authSession?.provider,email:r?.email??this.authSession?.email??null,emailVerified:r?.email_verified};return this.setAuthSession(a),await this.syncSocketAuth(s).catch(()=>{}),a}async issueSsrToken(e=120){let t=this.getHttpBase();await this.ensureCsrfProtection();let n=await this.timedFetch("issueSsrToken",`${t}/auth/ssr/token?appId=${encodeURIComponent(this.config.appId)}`,{method:"POST",credentials:"include",headers:{"Content-Type":"application/json",...this.getCsrfHeaders(),...this.config.apiKey?{"x-flare-api-key":this.config.apiKey}:{}},body:JSON.stringify({appId:this.config.appId,apiKey:this.config.apiKey,ttlSeconds:e})}),i=await this.parseJsonWithTiming("issueSsrToken",n);n.response.ok||this.throwFetchFlareError(i,"Failed to mint SSR token",h.AuthenticationFailed);let s=String(i.token??"");if(!s)throw new l("SSR token response is missing token",h.ParseError,i);return {token:s,token_type:String(i.token_type??"Bearer"),expires_in:Number(i.expires_in??0),uid:String(i.uid??""),role:String(i.role??"user"),...typeof i.email=="string"?{email:i.email}:{}}}async signOut(){try{if(this.authSession?.accessToken||this.authSession?.refreshToken){let e=this.getHttpBase();await this.ensureCsrfProtection(),await this.timedFetch("signOut",`${e}/auth/logout?appId=${encodeURIComponent(this.config.appId)}`,{method:"POST",credentials:"include",headers:{"Content-Type":"application/json",...this.getCsrfHeaders(),...this.config.apiKey?{"x-flare-api-key":this.config.apiKey}:{},...this.authSession?.accessToken?{Authorization:`Bearer ${this.authSession.accessToken}`}:{}},body:JSON.stringify({appId:this.config.appId,apiKey:this.config.apiKey,refresh_token:this.authSession?.refreshToken})}).catch(()=>{});}}finally{this.setAuthSession(null),await this.syncSocketAuth(null).catch(()=>{});}this.log("Signed out");}async registerWithEmail(e,t,n){let i=this.getHttpBase();await this.ensureCsrfProtection();let s=new URLSearchParams;s.set("appId",this.config.appId),s.set("client_id",this.config.apiKey??""),s.set("grant_type","create_user"),s.set("email",e),s.set("password",t),n?.scope?.length&&s.set("scope",n.scope.join(" ")),n?.additionalParams&&s.set("additional_params",JSON.stringify(n.additionalParams));let r=await this.timedFetch("registerWithEmail",`${i}/auth/register?appId=${encodeURIComponent(this.config.appId)}`,{method:"POST",credentials:"include",headers:{"Content-Type":"application/x-www-form-urlencoded",...this.getCsrfHeaders(),...this.config.apiKey?{"x-flare-api-key":this.config.apiKey}:{}},body:s.toString()}),a=await this.parseJsonWithTiming("registerWithEmail",r);return !r.response.ok&&r.response.status!==202&&this.throwFetchFlareError(a,"User creation failed",h.WriteFailed),a}async requestEmailPasswordToken(e,t,n){let i=this.getHttpBase();await this.ensureCsrfProtection();let s=new URLSearchParams;s.set("appId",this.config.appId),s.set("client_id",this.config.apiKey??""),s.set("grant_type","password"),s.set("email",e),s.set("password",t),n?.length&&s.set("scope",n.join(" "));let r=await this.timedFetch("requestEmailPasswordToken",`${i}/auth/token?appId=${encodeURIComponent(this.config.appId)}`,{method:"POST",credentials:"include",headers:{"Content-Type":"application/x-www-form-urlencoded",...this.getCsrfHeaders(),...this.config.apiKey?{"x-flare-api-key":this.config.apiKey}:{}},body:s.toString()}),a=await this.parseJsonWithTiming("requestEmailPasswordToken",r);return r.response.ok||this.throwFetchFlareError(a,"Sign-in with email/password failed",h.AuthenticationFailed),{kind:String(a.kind),access_token:String(a.access_token??""),refresh_token:a.refresh_token?String(a.refresh_token):null,expires_in:a.expires_in?Number(a.expires_in):null,token_type:String(a.token_type??"Bearer"),scope:a.scope?String(a.scope):null,profile:null,provider:"credentials"}}async fetchAuthMe(e){let t=this.getHttpBase(),n=new URLSearchParams({appId:this.config.appId});this.config.apiKey&&n.set("apiKey",this.config.apiKey);let i=`${t}/auth/me?${n.toString()}`,s=await this.timedFetch("fetchAuthMe",i,{credentials:"include",headers:{Authorization:`Bearer ${e}`,...this.config.apiKey?{"x-flare-api-key":this.config.apiKey}:{}}}),r=await this.parseJsonWithTiming("fetchAuthMe",s);return s.response.ok||this.throwFetchFlareError(r,"Failed to fetch profile",h.QueryFailed),r}};var O=class extends A{constructor(e){super(e),this.log("FlareClient initialized",e);}},U=O;function L(o){return `__flare_csrf_${o.replace(/[^a-zA-Z0-9_-]/g,"_")}`}function ge(o){return `__flare_csrf_${o.replace(/[^a-zA-Z0-9_-]/g,"_")}`}function P(o,e){let t=e.toLowerCase();for(let[n,i]of Object.entries(o??{}))if(n.toLowerCase()===t&&typeof i=="string")return i}function me(o){let e=P(o,"set-cookie");if(typeof e=="string"&&e.length>0)return [e];for(let[t,n]of Object.entries(o??{}))if(t.toLowerCase()==="set-cookie"&&Array.isArray(n))return n.filter(i=>typeof i=="string");return []}function ye(o,e){for(let t of o){let n=t.split(";").map(c=>c.trim()),[i]=n;if(!i)continue;let s=i.indexOf("=");if(s<=0)continue;let r=decodeURIComponent(i.slice(0,s)),a=i.slice(s+1);if(r===e)return decodeURIComponent(a)}}async function ke(o){let e=new URL("/auth/config",o.endpoint);return e.searchParams.set("appId",o.appId),o.apiKey&&e.searchParams.set("apiKey",o.apiKey),await withGet(e.toString(),{ignoreKind:true,withCredentials:true,returnRawResponse:true,headers:o.apiKey?{"x-flare-api-key":o.apiKey}:{},appendCookiesToBody:false,appendTimestamp:false}).catch(()=>null)}async function $(o){let e=await ke(o),t=e?.data,n=e?.headers??{},i=P(n,"x-flare-csrf")??P(n,"x-csrf-token")??P(n,"csrf-token");if(typeof i=="string"&&i.length>0)return {csrfToken:i,...t};let s=t?.cookie?.csrfTokenName,r=s&&s.length>0?s:ge(o.appId),a=me(n),c=ye(a,r);if(typeof c=="string"&&c.length>0)return {csrfToken:c,...t}}function W(o,e,t){return `${encodeURIComponent(o)}=${encodeURIComponent(e)}; HttpOnly; SameSite=Strict; Path=/; Max-Age=${t}`}function be(o){let e=o.proxyCookieName??L(o.appId),t=o.proxyCookieMaxAge??3600;return async function(i){let s=await $(o),r=s?.csrfToken,a=new Headers({"Content-Type":"application/json"});return r&&a.set("Set-Cookie",W(e,r,t)),new Response(JSON.stringify({csrfToken:r??null,...s}),{status:200,headers:a})}}function Ce(o){let e=o.proxyCookieName??L(o.appId),t=o.proxyCookieMaxAge??3600;return async function(i,s){if(i.method!=="GET"&&i.method!=="HEAD"){s.status(405).json({error:"Method not allowed"});return}let a=(await $(o))?.csrfToken;a&&s.setHeader("Set-Cookie",W(e,a,t)),s.status(200).json({csrfToken:a??null});}}function Te(o,e,t){let n=t??L(e);if(o instanceof Request){let r=(o.headers.get("cookie")??"").split(";").map(c=>c.trim()).find(c=>c.startsWith(`${encodeURIComponent(n)}=`)||c.startsWith(`${n}=`));if(!r)return null;let a=r.indexOf("=");return a>=0?decodeURIComponent(r.slice(a+1)):null}let{cookies:i}=o;return typeof i?.get=="function"?i.get(n)?.value??null:i&&typeof i=="object"?i[n]??null:null}function Se(o,e){let t={};return o&&(t["x-flare-csrf"]=o),e?.accessToken&&(t.Authorization=`Bearer ${e.accessToken}`),e?.apiKey&&(t["x-flare-api-key"]=e.apiKey),t}var Ie=(p=>(p.authEmailNotVerified="auth/email-not-verified",p.authEmailAlreadyVerified="auth/email-already-verified",p.authInvalidToken="auth/invalid-token",p.authUserDisabled="auth/user-disabled",p.authUserNotFound="auth/user-not-found",p.authWrongPassword="auth/wrong-password",p.authEmailAlreadyInUse="auth/email-already-in-use",p.authInvalidEmail="auth/invalid-email",p.authWeakPassword="auth/weak-password",p.authTooManyRequests="auth/too-many-requests",p.authInternalError="auth/internal-error",p))(Ie||{});var we=(u=>(u.health="health",u.authConfig="auth_config",u.authRegistration="auth/registration",u.authRegistrationVerificationRequired="auth/registration-verification-required",u.authSession="auth/session",u.authExchange="auth/exchange",u.authLogout="auth/logout",u.authSsrBridge="auth/ssr_bridge",u.authSsrVerify="auth/ssr_verify",u.accountRecovery="account/recovery",u.emailVerification="email/verification",u.verificationDispatch="verification/dispatch",u.authProfile="auth/profile",u.adminToken="admin/token",u.documentDelete="document/delete",u.documentsDelete="documents/delete",u.documents="documents",u.document="document",u.documentCreate="document/create",u.documentUpdate="document/update",u.oauthProviderResponse="oauth_provider_response",u.success="success",u.response="response",u))(we||{});var y=null,S=null,R=null,ve=o=>JSON.stringify({endpoint:o.endpoint,appId:o.appId,apiKey:o.apiKey,publicKey:o.publicKey,autoReconnect:o.autoReconnect,reconnectDelay:o.reconnectDelay,maxReconnectDelay:o.maxReconnectDelay}),It=o=>{let e=ve(o);return y&&R!==e&&(y.disconnect(),y=null,S=null,R=null),y||(y=new U(o),R=e,y.connect(),S=new Proxy(y,{get(t,n,i){if(n==="onAuthStateChange")return t.onAuthStateChanged.bind(t);if(n==="onAuthConfigLoaded")return t.onAuthConfigLoaded.bind(t);let s=Reflect.get(t,n,i);return typeof s=="function"?s.bind(t):s}})),S??y},wt=()=>S??y,vt=()=>{y&&(y.disconnect(),y=null,S=null,R=null);},At=U;
|
|
2
|
-
export{
|
|
1
|
+
import {Credentials,Anonymous,Google,GitHub,Facebook,Dropbox,Apple,Twitter,AuthGuard}from'@zuzjs/auth';export{Anonymous,Apple,AuthGuard,Credentials,Dropbox,Facebook,GitHub,Google,Providers,Twitter,setupProvider}from'@zuzjs/auth';import {uuid2,withGet,withPut,withPatch,withPost}from'@zuzjs/core';var h=class extends Error{constructor(t,r,i){super(t);this.code=r;this.cause=i;this.name="ZuzFlareError";}};var X={AuthenticationFailed:"AUTHENTICATION_FAILED",PermissionDenied:"PERMISSION_DENIED",WriteFailed:"WRITE_FAILED",QueryFailed:"QUERY_FAILED",ParseError:"PARSE_ERROR"},c=X;var ee=(d=>(d.SUBSCRIBE="subscribe",d.UNSUBSCRIBE="unsubscribe",d.WRITE="write",d.DELETE="delete",d.AUTH="auth",d.PING="ping",d.OFFLINE_SYNC="offline_sync",d.CALL="call",d.QUERY="query",d.PRESENCE_JOIN="presence_join",d.PRESENCE_LEAVE="presence_leave",d.PRESENCE_HEARTBEAT="presence_heartbeat",d))(ee||{}),te=(d=>(d.SNAPSHOT="snapshot",d.CHANGE="change",d.ERROR="error",d.ACK="ack",d.PONG="pong",d.AUTH_OK="auth_ok",d.OFFLINE_ACK="offline_ack",d.CALL_RESPONSE="call_response",d.QUERY_RESULT="query_result",d.PRESENCE_STATE="presence_state",d.PRESENCE_JOIN="presence_join",d.PRESENCE_LEAVE="presence_leave",d))(te||{});function B(a){let e=[];for(let[t,r]of Object.entries(a))if(typeof r=="string"){let i=r.match(/^(>=|<=|!=|>|<|==)\s*(.+)$/);if(i){let[,n,s]=i;e.push({field:t,op:n,value:q(s.trim())});}else e.push({field:t,op:"==",value:r});}else Array.isArray(r)?e.push({field:t,op:"in",value:r}):e.push({field:t,op:"==",value:r});return e}function q(a){if(!isNaN(Number(a)))return Number(a);if(a==="true")return true;if(a==="false")return false;if(a==="null")return null;if(a!=="undefined")return a}var k=class{constructor(e,t,r){this.client=e;this.collection=t;this.legacyId=r;}whereCondition;updateData;setData;deleteOp=false;promise;where(e){return this.whereCondition=e,this}update(e){return this.updateData=e,this}set(e){return this.setData=e,this}delete(){return this.deleteOp=true,this}getDocId(){if(this.legacyId)return this.legacyId;if(this.whereCondition&&(this.whereCondition.id||this.whereCondition._id)){let e=this.whereCondition.id??this.whereCondition._id;if(typeof e=="string")return e}throw new h('Document ID not specified. Use .where({ id: "..." }) or doc(collection, id)',c.QueryFailed)}async execute(){return this._execute()}async _execute(){let e=this.getDocId();if(this.deleteOp){await this.client.send("delete",{collection:this.collection,docId:e});return}if(this.updateData){await this.client.send("write",{collection:this.collection,docId:e,data:this.updateData,merge:true});return}if(this.setData){await this.client.send("write",{collection:this.collection,docId:e,data:this.setData,merge:false});return}return this.get()}then(e,t){return this.promise||(this.promise=this._execute()),this.promise.then(e,t)}async get(){let e=this.getDocId(),t=uuid2(18);return new Promise((r,i)=>{let n=this.client.subscribe(t,this.collection,e,void 0,s=>{s.type==="snapshot"&&(n(),r(s.data));});setTimeout(()=>{n(),i(new Error("Document fetch timeout"));},1e4);})}onSnapshot(e){let t=this.getDocId(),r=uuid2(18);return this.client.subscribe(r,this.collection,t,void 0,e)}};var Q=class{constructor(e,t,r){this.client=e;this.collection=t;this.id=r;}async get(){return new k(this.client,this.collection,this.id).get()}async set(e){await this.client.send("write",{collection:this.collection,docId:this.id,data:e,merge:false});}async update(e){await this.client.send("write",{collection:this.collection,docId:this.id,data:e,merge:true});}async delete(){await this.client.send("delete",{collection:this.collection,docId:this.id});}onSnapshot(e){let t=uuid2(18),r=()=>{};return r=this.client.subscribe(t,this.collection,this.id,void 0,i=>{i.type==="snapshot"&&(e(i),r());}),r}onDocUpdated(e){let t=uuid2(18);return this.client.subscribe(t,this.collection,this.id,void 0,r=>{r.type==="change"&&(r.operation==="update"||r.operation==="replace")&&r.data&&e(r.data,r.docId);},{skipSnapshot:true})}onDocModified(e){return this.onDocUpdated(e)}onDocChange(e){return this.onDocUpdated(e)}onDocDeleted(e){let t=uuid2(18);return this.client.subscribe(t,this.collection,this.id,void 0,r=>{r.type==="change"&&r.operation==="delete"&&e(r.docId);},{skipSnapshot:true})}onDocChanged(e){let t=uuid2(18);return this.client.subscribe(t,this.collection,this.id,void 0,r=>{r.type==="change"&&e(r.data??null,r.docId,r.operation);},{skipSnapshot:true})}},w=Q;var N=class a{constructor(e,t){this.client=e;this.collection=t;return new Proxy(this,{get:(r,i,n)=>{if(typeof i=="string"&&!(i in r)&&this.client.hasQueryPreset(i))return (o={})=>r.with(i,o);let s=Reflect.get(r,i,n);return typeof s=="function"?s.bind(r):s}})}sq={};promise;doc(e){return new w(this.client,this.collection,e)}clone(e){let t=new a(this.client,this.collection);return t.sq={...this.sq,...e},t}with(e,t={}){return this.client.applyQueryPreset(this,e,t)}where(e,t,r){let i;return typeof e=="string"?i=[{field:e,op:t,value:r}]:i=B(e),this.clone({where:[...this.sq.where??[],...i]})}orWhere(e){return this.clone({where:[...this.sq.where??[],{or:e}]})}latest(){return this.clone({orderBy:[...this.sq.orderBy??[],{field:"_seq",dir:"desc"}]})}oldest(){return this.clone({orderBy:[...this.sq.orderBy??[],{field:"_seq",dir:"asc"}]})}orderBy(e,t="asc"){return this.clone({orderBy:[...this.sq.orderBy??[],{field:e,dir:t}]})}limit(e){return this.clone({limit:e})}offset(e){return this.clone({offset:e})}startAt(...e){return this.clone({startAt:{values:e}})}startAfter(...e){return this.clone({startAfter:{values:e}})}endAt(...e){return this.clone({endAt:{values:e}})}endBefore(...e){return this.clone({endBefore:{values:e}})}aggregate(...e){return this.clone({aggregate:[...this.sq.aggregate??[],...e]})}count(e="count"){return this.aggregate({fn:"count",alias:e})}sum(e,t){return this.aggregate({fn:"sum",field:e,alias:t??`sum_${e}`})}avg(e,t){return this.aggregate({fn:"avg",field:e,alias:t??`avg_${e}`})}min(e,t){return this.aggregate({fn:"min",field:e,alias:t??`min_${e}`})}max(e,t){return this.aggregate({fn:"max",field:e,alias:t??`max_${e}`})}distinct(e,t){return this.aggregate({fn:"distinct",field:e,alias:t??`distinct_${e}`})}groupBy(...e){return this.clone({groupBy:{fields:e}})}having(e,t,r){return this.clone({having:[...this.sq.having??[],{field:e,op:t,value:r}]})}buildStructuredJoin(e,t){let i={from:String(e??""),localField:String(t?.source??""),foreignField:String(t?.target??""),as:String(t?.as??""),single:t?.single};return Array.isArray(t?.where)&&(i.where=t.where),Array.isArray(t?.orderBy)&&(i.orderBy=t.orderBy),typeof t?.limit=="number"&&(i.limit=t.limit),typeof t?.offset=="number"&&(i.offset=t.offset),t?.startAt&&(i.startAt=t.startAt),t?.startAfter&&(i.startAfter=t.startAfter),t?.endAt&&(i.endAt=t.endAt),t?.endBefore&&(i.endBefore=t.endBefore),Array.isArray(t?.aggregate)&&(i.aggregate=t.aggregate),t?.groupBy&&(i.groupBy=t.groupBy),Array.isArray(t?.having)&&(i.having=t.having),t?.vectorSearch&&(i.vectorSearch=t.vectorSearch),Array.isArray(t?.select)&&(i.select=t.select),typeof t?.distinctField=="string"&&(i.distinctField=t.distinctField),Array.isArray(t?.joins)&&(i.joins=t.joins.map(n=>this.buildStructuredJoin(String(n?.collection??""),n))),i}Join(e,t){let r=this.buildStructuredJoin(e,t);return this.clone({joins:[...this.sq.joins??[],r]})}join(e,t){if(typeof e=="string")return this.Join(e,t);let r=String(e.collection??e.from??""),i=this.buildStructuredJoin(r,e);return this.clone({joins:[...this.sq.joins??[],i]})}select(...e){return this.clone({select:e})}distinctField(e){return this.clone({distinctField:e})}vectorSearch(e){return this.clone({vectorSearch:e})}async get(){return this._execute()}_isStructured(){return !!(this.sq.orderBy?.length||this.sq.aggregate?.length||this.sq.groupBy||this.sq.having?.length||this.sq.joins?.length||this.sq.vectorSearch||this.sq.distinctField||this.sq.offset||this.sq.startAt||this.sq.startAfter||this.sq.endAt||this.sq.endBefore||this.sq.select?.length)}async _execute(){return this._isStructured()?this._executeQuery():this._executeSubscribe()}async _executeQuery(){return (await this.client.send("query",{collection:this.collection,query:this.sq})).data??[]}async _executeSubscribe(){let e=uuid2(18);return new Promise((t,r)=>{let i=Object.keys(this.sq).length>0?this.sq:void 0,n=this.client.subscribe(e,this.collection,void 0,i,s=>{s.type==="snapshot"&&(n(),t(s.data));});setTimeout(()=>{n(),r(new Error("Collection fetch timeout"));},1e4);})}then(e,t){return this.promise||(this.promise=this._execute()),this.promise.then(e,t)}onSnapshot(e){let t=uuid2(18),r=Object.keys(this.sq).length>0?this.sq:void 0,i=(()=>{});return i=this.client.subscribe(t,this.collection,void 0,r,n=>{n.type==="snapshot"&&(e(n),i());}),i}onDocAdded(e){let t=uuid2(18),r=Object.keys(this.sq).length>0?this.sq:void 0;return this.client.subscribe(t,this.collection,void 0,r,i=>{i.type==="change"&&i.operation==="insert"&&i.data!=null&&e(i.data,i.docId);},{skipSnapshot:true})}onDocUpdated(e){let t=uuid2(18),r=Object.keys(this.sq).length>0?this.sq:void 0;return this.client.subscribe(t,this.collection,void 0,r,i=>{i.type==="change"&&(i.operation==="update"||i.operation==="replace")&&i.data!=null&&e(i.data,i.docId);},{skipSnapshot:true})}onDocModified(e){return this.onDocUpdated(e)}onDocChange(e){return this.onDocUpdated(e)}onDocDeleted(e){let t=uuid2(18),r=Object.keys(this.sq).length>0?this.sq:void 0;return this.client.subscribe(t,this.collection,void 0,r,i=>{i.type==="change"&&i.operation==="delete"&&e(i.docId);},{skipSnapshot:true})}onDocChanged(e){let t=uuid2(18),r=Object.keys(this.sq).length>0?this.sq:void 0;return this.client.subscribe(t,this.collection,void 0,r,i=>{i.type==="change"&&e(i.data??null,i.docId,i.operation);},{skipSnapshot:true})}async add(e){let t=uuid2(18),r=this.doc(t);return await r.set(e),r}update(e){return new k(this.client,this.collection).update(e)}delete(){return new k(this.client,this.collection).delete()}},O=N;async function ie(a){let e=a.replace(/-----BEGIN PUBLIC KEY-----/,"").replace(/-----END PUBLIC KEY-----/,"").replace(/\s+/g,""),t=typeof atob<"u"?atob(e):Buffer.from(e,"base64").toString("binary"),r=new Uint8Array(t.length);for(let n=0;n<t.length;n++)r[n]=t.charCodeAt(n);return (globalThis.crypto??(await import('crypto')).webcrypto).subtle.importKey("spki",r.buffer,{name:"RSA-OAEP",hash:"SHA-256"},false,["encrypt"])}async function re(a,e){let t=await ie(e),r=new TextEncoder().encode(JSON.stringify(a)),n=await(globalThis.crypto??(await import('crypto')).webcrypto).subtle.encrypt({name:"RSA-OAEP"},t,r),s=typeof btoa<"u"?btoa(String.fromCharCode(...new Uint8Array(n))):Buffer.from(n).toString("base64");return JSON.stringify({enc:"rsa",data:s})}var R=class{socket=null;reconnectInterval;maxReconnectDelay;isConnected=false;shouldReconnect=true;options;messageQueue=[];heartbeatInterval=null;connectionTimeout=null;constructor(e){this.options=e,this.reconnectInterval=e.reconnectDelay||2,this.maxReconnectDelay=e.maxReconnectDelay||60,this.log("Transport initialized",e.url);}connect(){if(this.socket){this.log("Socket already exists, skipping connection");return}this.log("Connecting to",this.options.url),this.socket=new WebSocket(this.options.url),this.connectionTimeout=setTimeout(()=>{this.isConnected||(this.log("Connection timeout"),this.socket?.close(),this.handleReconnect());},1e4),this.socket.onopen=()=>{this.connectionTimeout&&(clearTimeout(this.connectionTimeout),this.connectionTimeout=null),this.isConnected=true,this.reconnectInterval=this.options.reconnectDelay||2,this.log("Connected to server"),this.options.onOpen?.(),this.startHeartbeat(),this.flushQueue();},this.socket.onmessage=e=>{try{let t=JSON.parse(e.data);this.options.onMessage(t);}catch(t){this.log("Parse error",t),this.options.onError?.(t);}},this.socket.onerror=e=>{this.log("WebSocket error",e),this.options.onError?.(new Error("WebSocket error"));},this.socket.onclose=e=>{this.connectionTimeout&&(clearTimeout(this.connectionTimeout),this.connectionTimeout=null),this.isConnected=false,this.socket=null,this.stopHeartbeat(),this.log("Connection closed",e.code,e.reason),this.options.onClose?.(),e.code!==1e3&&this.shouldReconnect&&this.options.autoReconnect&&this.handleReconnect();};}handleReconnect(){let e=this.reconnectInterval*1e3;this.log(`Reconnecting in ${this.reconnectInterval}s...`),setTimeout(()=>{this.reconnectInterval=Math.min(this.reconnectInterval*2,this.maxReconnectDelay),this.connect();},e);}startHeartbeat(){this.heartbeatInterval=setInterval(()=>{this.isConnected&&this.send({type:"ping",id:Date.now().toString(),ts:Date.now()});},3e4);}stopHeartbeat(){this.heartbeatInterval&&(clearInterval(this.heartbeatInterval),this.heartbeatInterval=null);}flushQueue(){for(this.log("Flushing message queue",this.messageQueue.length);this.messageQueue.length>0;){let e=this.messageQueue.shift();e&&this.send(e);}}send(e){if(this.socket&&this.socket.readyState===WebSocket.OPEN){let t=r=>{try{this.socket.send(r),this.log("Sent message",e);}catch(i){this.log("Send error",i),this.messageQueue.push(e);}};this.options.publicKey?re(e,this.options.publicKey).then(t).catch(r=>{this.log("RSA encrypt error \u2014 sending plaintext",r),t(JSON.stringify(e));}):t(JSON.stringify(e));}else this.log("Socket not ready, queueing message"),this.messageQueue.push(e);}disconnect(){this.shouldReconnect=false,this.stopHeartbeat(),this.socket&&(this.socket.close(1e3,"Client disconnect"),this.socket=null),this.isConnected=false,this.log("Disconnected");}get connected(){return this.isConnected}log(...e){this.options.debug&&console.log("[FlareTransport]",...e);}};var ue={id:"_id",createdAt:"_createdAt",updatedAt:"_updatedAt"},j={_id:"id",_createdAt:"createdAt",_updatedAt:"updatedAt"},E=class{transport;config;pendingAcks=new Map;subscriptions=new Map;activeSubscriptions=new Map;queryPresets=new Map;subscriptionErrorHandlers=new Map;subscriptionPermissionHandlers=new Map;subscriptionLastErrors=new Map;offlineQueue=[];currentState="disconnected";connectionListeners=[];errorListeners=[];isDebug=false;socketAuthUid="anon";pendingSubscriptionReplay=false;subscriptionReplayPromise=Promise.resolve();requestTraceSeq=0;requestTimingEnabled=true;httpInFlight=new Map;httpResponseCache=new Map;maxHttpCacheEntries=200;presenceCallbacks=new Map;presenceJoinCbs=new Map;presenceLeaveCbs=new Map;presenceHeartbeatTimer;embedder;vectorSchema=new Map;throwFetchFlareError(e,t,r){let i=e,n=typeof i?.error=="string"&&i.error.length>0?i.error:r,s=typeof i?.message=="string"&&i.message.length>0?i.message:t;throw new h(s,n,e)}nowMs(){return typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now()}normalizeHeaders(e){if(!e)return {};let t={};if(e instanceof Headers)e.forEach((r,i)=>{t[i]=r;});else if(Array.isArray(e))for(let[r,i]of e)t[String(r)]=String(i);else for(let[r,i]of Object.entries(e))t[String(r)]=String(i);return t}redactHeaders(e){let t={...e};for(let r of Object.keys(t)){let i=r.toLowerCase();(i==="authorization"||i==="x-flare-csrf"||i==="x-csrf-token")&&(t[r]="[redacted]");}return t}stableStringify(e){if(e==null)return "";if(typeof e=="string")return e;if(typeof URLSearchParams<"u"&&e instanceof URLSearchParams)return e.toString();if(typeof e!="object")return String(e);if(Array.isArray(e))return `[${e.map(i=>this.stableStringify(i)).join(",")}]`;let t=e;return `{${Object.keys(t).sort().map(i=>`${i}:${this.stableStringify(t[i])}`).join(",")}}`}buildHttpCacheKey(e,t,r,i,n){let o=Object.entries(r).map(([l,f])=>[l.toLowerCase(),f]).sort(([l],[f])=>l.localeCompare(f)).map(([l,f])=>`${l}:${f}`).join("|"),u=this.stableStringify(i);return `${e}|${t}|${n??""}|${o}|${u}`}shouldCacheResponse(e,t){return !!(e==="GET"||e==="POST"&&/\/auth\/refresh(?:\?|$)/.test(t))}rememberHttpResponse(e,t){if(this.httpResponseCache.set(e,t),this.httpResponseCache.size<=this.maxHttpCacheEntries)return;let r=this.httpResponseCache.keys().next().value;r&&this.httpResponseCache.delete(r);}createTimedFetchTrace(e,t,r,i,n,s){return {response:{status:e.status,ok:e.status>=200&&e.status<300,headers:{get:o=>{let u=o.toLowerCase();for(let[l,f]of Object.entries(e.headers))if(l.toLowerCase()===u)return String(f);return null}},json:async()=>e.data??{}},requestId:t,startedAtMs:r,networkMs:s,method:i,url:n}}logHttpTiming(...e){this.requestTimingEnabled&&this.log("[FlareClient][http]",...e);}mergeHeaders(e,t){if(!e)return t;if(e instanceof Headers){let r=new Headers(e);for(let[i,n]of Object.entries(t))r.set(i,n);return r}return Array.isArray(e)?[...e,...Object.entries(t)]:{...e,...t}}toWireField(e){let t=String(e??"").trim();return t&&(ue[t]??t)}fromWireField(e){let t=String(e??"").trim();return t&&(j[t]?j[t]:t.startsWith("_")&&!t.startsWith("__")&&t.length>1?t.slice(1):t)}normalizeOutboundData(e){if(Array.isArray(e))return e.map(i=>this.normalizeOutboundData(i));if(!e||typeof e!="object")return e;let t=e,r={};for(let[i,n]of Object.entries(t))r[this.toWireField(i)]=this.normalizeOutboundData(n);return r}normalizeInboundData(e){if(Array.isArray(e))return e.map(i=>this.normalizeInboundData(i));if(!e||typeof e!="object")return e;let t=e,r={};for(let[i,n]of Object.entries(t))r[this.fromWireField(i)]=this.normalizeInboundData(n);return r}normalizeOutboundAnyFilter(e){return Array.isArray(e.or)?{...e,or:e.or.map(t=>this.normalizeOutboundAnyFilter(t))}:typeof e.field=="string"?{...e,field:this.toWireField(e.field)}:{...e}}normalizeOutboundQuery(e){if(!e)return e;if(typeof e=="object"&&e!==null&&!Array.isArray(e)&&typeof e.field=="string")return this.normalizeOutboundAnyFilter(e);if(Array.isArray(e))return e.map(n=>this.normalizeOutboundAnyFilter(n));if(typeof e!="object")return e;let t=e,r={...t},i=n=>{let s={...n};return s.localField=this.toWireField(String(n?.localField??"")),s.foreignField=this.toWireField(String(n?.foreignField??"")),Array.isArray(n.where)&&(s.where=n.where.map(o=>this.normalizeOutboundAnyFilter(o))),Array.isArray(n.orderBy)&&(s.orderBy=n.orderBy.map(o=>({...o,field:this.toWireField(String(o?.field??""))}))),n.groupBy&&typeof n.groupBy=="object"&&Array.isArray(n.groupBy.fields)&&(s.groupBy={...n.groupBy,fields:n.groupBy.fields.map(o=>this.toWireField(String(o??"")))}),Array.isArray(n.having)&&(s.having=n.having.map(o=>({...o,field:this.toWireField(String(o?.field??""))}))),Array.isArray(n.select)&&(s.select=n.select.map(o=>this.toWireField(String(o??"")))),typeof n.distinctField=="string"&&(s.distinctField=this.toWireField(n.distinctField)),n.vectorSearch&&typeof n.vectorSearch=="object"&&(s.vectorSearch={...n.vectorSearch,field:this.toWireField(String(n.vectorSearch.field??""))}),Array.isArray(n.joins)&&(s.joins=n.joins.map(o=>i(o))),s};return Array.isArray(t.where)&&(r.where=t.where.map(n=>this.normalizeOutboundAnyFilter(n))),Array.isArray(t.orderBy)&&(r.orderBy=t.orderBy.map(n=>({...n,field:this.toWireField(String(n?.field??""))}))),t.groupBy&&typeof t.groupBy=="object"&&Array.isArray(t.groupBy.fields)&&(r.groupBy={...t.groupBy,fields:t.groupBy.fields.map(n=>this.toWireField(String(n??"")))}),Array.isArray(t.having)&&(r.having=t.having.map(n=>({...n,field:this.toWireField(String(n?.field??""))}))),Array.isArray(t.select)&&(r.select=t.select.map(n=>this.toWireField(String(n??"")))),typeof t.distinctField=="string"&&(r.distinctField=this.toWireField(t.distinctField)),t.vectorSearch&&typeof t.vectorSearch=="object"&&(r.vectorSearch={...t.vectorSearch,field:this.toWireField(String(t.vectorSearch.field??""))}),Array.isArray(t.joins)&&(r.joins=t.joins.map(n=>i(n))),r}async timedFetch(e,t,r){let i=++this.requestTraceSeq,n=this.nowMs(),s=String(r?.method??"GET").toUpperCase(),o=this.normalizeHeaders(r?.headers),u=this.redactHeaders(o),l=r?.body,f=this.buildHttpCacheKey(s,t,o,l,r?.credentials),g=this.shouldCacheResponse(s,t);this.logHttpTiming(`#${i} ${e} start`,{method:s,url:t,headers:u,hasBody:!!r?.body});try{if(g){let S=this.httpResponseCache.get(f);if(S)return this.logHttpTiming(`#${i} ${e} cache-hit`,{method:s,url:t}),this.createTimedFetchTrace(S,i,n,s,t,0)}let d=this.httpInFlight.get(f);if(d){let S=await d,p=this.nowMs()-n;return this.logHttpTiming(`#${i} ${e} deduped`,{method:s,url:t,networkMs:Number(p.toFixed(2))}),this.createTimedFetchTrace(S,i,n,s,t,p)}let I=this.mergeHeaders(r?.headers,{"x-flare-request-id":String(i)}),C=this.normalizeHeaders(I),G=this.redactHeaders(C),v={timeout:Math.ceil((this.config.connectionTimeout??1e4)/1e3),ignoreKind:!0,headers:C,withCredentials:r?.credentials==="include",returnRawResponse:!0,appendCookiesToBody:!1,appendTimestamp:!1};this.logHttpTiming(`#${i} ${e} request`,{method:s,url:t,headers:G,hasBody:!!r?.body});let M=s.toUpperCase(),W=(async()=>{let S=M==="GET"?await withGet(t,v):M==="PUT"?await withPut(t,l,v):M==="PATCH"?await withPatch(t,l,v):await withPost(t,l,v),p={status:Number(S?.status??0),headers:Object.fromEntries(Object.entries(S?.headers??{}).map(([Y,Z])=>[Y,String(Z)])),data:S?.data??{}};return g&&this.rememberHttpResponse(f,p),p})();this.httpInFlight.set(f,W);let L=await W.finally(()=>{this.httpInFlight.delete(f);}),$=this.nowMs()-n;return this.logHttpTiming(`#${i} ${e} response`,{status:L.status,networkMs:Number($.toFixed(2))}),this.createTimedFetchTrace(L,i,n,s,t,$)}catch(d){let I=this.nowMs()-n;throw this.logHttpTiming(`#${i} ${e} failed`,{networkMs:Number(I.toFixed(2)),message:d?.message??String(d)}),d}}async parseJsonWithTiming(e,t){let r=this.nowMs(),i=await t.response.json().catch(()=>({})),n=this.nowMs()-r,s=this.nowMs()-t.startedAtMs;return this.logHttpTiming(`#${t.requestId} ${e} complete`,{method:t.method,url:t.url,status:t.response.status,networkMs:Number(t.networkMs.toFixed(2)),parseMs:Number(n.toFixed(2)),totalMs:Number(s.toFixed(2))}),i}getHttpBase(){if(this.config.httpBase)return this.config.httpBase.replace(/\/$/,"");let e=new URL(this.config.endpoint);return `${e.protocol}//${e.host}`}log(...e){this.isDebug&&console.log("[FlareClient]",...e);}constructor(e){this.config={autoReconnect:true,reconnectDelay:2,maxReconnectDelay:60,debug:false,connectionTimeout:1e4,...e},this.isDebug=this.config.debug||false,this.requestTimingEnabled=this.config.requestTiming??true;let{hostname:t,port:r,protocol:i}=new URL(this.config.endpoint),n=i==="https:",u=`${n?"wss":"ws"}://${t}:${r||(n?"443":"80")}/?appId=${this.config.appId}${this.config.apiKey?`&apiKey=${this.config.apiKey}`:""}`;this.transport=new R({url:u,publicKey:this.config.publicKey,autoReconnect:this.config.autoReconnect,reconnectDelay:this.config.reconnectDelay,maxReconnectDelay:this.config.maxReconnectDelay,onMessage:l=>this.handleIncoming(l),onOpen:()=>this.onConnected(),onClose:()=>this.onDisconnected(),onError:l=>this.handleTransportError(l),debug:this.isDebug});}connect(){this.setState("connecting"),this.transport.connect();}disconnect(){this.transport.disconnect(),this.setState("disconnected");}get connectionState(){return this.currentState}get isConnected(){return this.currentState==="connected"}onConnectionStateChange(e){return this.connectionListeners.push(e),()=>{this.connectionListeners=this.connectionListeners.filter(t=>t!==e);}}onError(e){return this.errorListeners.push(e),()=>{this.errorListeners=this.errorListeners.filter(t=>t!==e);}}collection(e){return new O(this,e)}registerQueryPreset(e,t){let r=String(e??"").trim();if(!r)throw new h("Preset name is required",c.QueryFailed);if(typeof t!="function")throw new h(`Query preset "${r}" handler must be a function`,c.QueryFailed);return this.queryPresets.set(r,t),this}registerQueryPresets(e){for(let[t,r]of Object.entries(e??{}))this.registerQueryPreset(t,r);return this}hasQueryPreset(e){return this.queryPresets.has(String(e??"").trim())}applyQueryPreset(e,t,r={}){let i=String(t??"").trim(),n=this.queryPresets.get(i);if(!n)throw new h(`Unknown query preset "${i}"`,c.QueryFailed);let s=n(e,r??{});if(!s||typeof s.get!="function")throw new h(`Query preset "${i}" must return a CollectionReference`,c.QueryFailed);return s}doc(e,t){return t!==void 0?new w(this,e,t):new k(this,e)}async ping(){let e=Date.now();return await this.send("ping",{}),Date.now()-e}async call(e,t={}){let r=await this.send("call",{topic:e,payload:t});if(!r.success)throw new h(r.error??`CALL "${e}" failed`,c.QueryFailed);return r.result}async query(e,t={}){return (await this.send("query",{collection:e,query:t})).data??[]}setEmbedder(e){this.embedder=e;}markVectorField(e,t,r={dimensions:1536}){this.vectorSchema.has(e)||this.vectorSchema.set(e,new Map),this.vectorSchema.get(e).set(t,r);}async embedVectorFields(e,t){let r=this.vectorSchema.get(e);if(!r)return t;let i={...t};for(let[n,s]of r){let o=i[n];if(typeof o=="string"){let u=s.embed??this.embedder;if(!u){this.log(`[vector] No embedder for field "${n}" \u2014 storing raw text`);continue}i[n]=await u(o);}}return i}async joinPresence(e,t){return await this.send("presence_join",{room:e,meta:t}),this._startPresenceHeartbeat(e,t),()=>this.leavePresence(e)}async leavePresence(e){await this.send("presence_leave",{room:e}),this._stopPresenceHeartbeat();}onPresenceState(e,t){return this.presenceCallbacks.has(e)||this.presenceCallbacks.set(e,[]),this.presenceCallbacks.get(e).push(t),()=>{let r=this.presenceCallbacks.get(e)??[];this.presenceCallbacks.set(e,r.filter(i=>i!==t));}}onPresenceJoin(e,t){return this.presenceJoinCbs.has(e)||this.presenceJoinCbs.set(e,[]),this.presenceJoinCbs.get(e).push(t),()=>{let r=this.presenceJoinCbs.get(e)??[];this.presenceJoinCbs.set(e,r.filter(i=>i!==t));}}onPresenceLeave(e,t){return this.presenceLeaveCbs.has(e)||this.presenceLeaveCbs.set(e,[]),this.presenceLeaveCbs.get(e).push(t),()=>{let r=this.presenceLeaveCbs.get(e)??[];this.presenceLeaveCbs.set(e,r.filter(i=>i!==t));}}_startPresenceHeartbeat(e,t){this.presenceHeartbeatTimer||(this.presenceHeartbeatTimer=setInterval(()=>{this.isConnected&&this.send("presence_heartbeat",{meta:t}).catch(()=>{});},2e4));}_stopPresenceHeartbeat(){this.presenceHeartbeatTimer&&(clearInterval(this.presenceHeartbeatTimer),this.presenceHeartbeatTimer=void 0);}async syncOffline(){if(this.offlineQueue.length===0)return;this.log("Syncing offline operations",this.offlineQueue.length);let e=[...this.offlineQueue];this.offlineQueue.length=0;let t=await this.send("offline_sync",{operations:e});t.conflicts&&t.conflicts.length>0&&(this.log("Offline sync conflicts",t.conflicts),t.conflicts.forEach(r=>{let i=e.find(n=>n.id===r.operationId);i&&this.offlineQueue.push(i);}));}async beforeActivateSubscription(e){}async activateSubscription(e){if(!this.isConnected){this.pendingSubscriptionReplay=true;return}await this.beforeActivateSubscription(e),this.subscriptions.set(e.liveId,e.callback);try{let t=await this.send("subscribe",{collection:e.collection,docId:e.docId,query:e.query,skipSnapshot:e.options.skipSnapshot});if(!this.activeSubscriptions.has(e.baseId)){this.subscriptions.delete(e.liveId);return}t.subscriptionId&&t.subscriptionId!==e.liveId&&(this.subscriptions.delete(e.liveId),e.liveId=t.subscriptionId,this.subscriptions.set(e.liveId,e.callback),this.log("Subscription remapped",e.baseId,"\u2192",e.liveId));}catch(t){this.subscriptions.delete(e.liveId),this.pendingSubscriptionReplay=true;let r=this.toSubscriptionError(t);this.emitSubscriptionError(e.baseId,r),this.log("Subscription failed",t);}}toSubscriptionError(e){let t=e instanceof Error?e.message:String(e??"Unknown subscription error"),r=t.match(/^\[([^\]]+)\]\s*(.*)$/),i=r?.[1],n=(r?.[2]??t).trim()||t,s=i===c.PermissionDenied||t.includes(c.PermissionDenied);return {code:i,message:n,permissionDenied:s,raw:e}}emitSubscriptionError(e,t){this.subscriptionLastErrors.set(e,t);let r=this.subscriptionErrorHandlers.get(e);if(r)for(let i of r)try{i(t);}catch(n){this.log("Subscription error callback failed",n);}if(t.permissionDenied){let i=this.subscriptionPermissionHandlers.get(e);if(i)for(let n of i)try{n(t);}catch(s){this.log("Subscription permission callback failed",s);}}}async replayActiveSubscriptions(){if(!this.isConnected){this.pendingSubscriptionReplay=true;return}let e=Array.from(this.activeSubscriptions.values());if(e.length===0){this.pendingSubscriptionReplay=false;return}this.pendingSubscriptionReplay=false,this.subscriptionReplayPromise=this.subscriptionReplayPromise.then(async()=>{for(let t of e){if(!this.activeSubscriptions.has(t.baseId))continue;let r=t.liveId;this.subscriptions.delete(r),t.liveId=t.baseId,r&&await this.send("unsubscribe",{subscriptionId:r}).catch(()=>{}),await this.activateSubscription(t);}}).catch(t=>{this.pendingSubscriptionReplay=true,this.log("Subscription replay failed",t);}),await this.subscriptionReplayPromise;}subscribe(e,t,r,i,n,s={}){this.log("Creating subscription",e,t,r);let o={baseId:e,liveId:e,collection:t,docId:r,query:i,callback:n,options:s};this.activeSubscriptions.set(e,o),this.subscriptionErrorHandlers.has(e)||this.subscriptionErrorHandlers.set(e,new Set),this.subscriptionPermissionHandlers.has(e)||this.subscriptionPermissionHandlers.set(e,new Set),this.activateSubscription(o).catch(f=>{this.log("Subscription activation failed",f);});let u=()=>{let g=this.activeSubscriptions.get(e)?.liveId??e;this.log("Unsubscribing",g),this.activeSubscriptions.delete(e),this.subscriptions.delete(g),this.subscriptionErrorHandlers.delete(e),this.subscriptionPermissionHandlers.delete(e),this.subscriptionLastErrors.delete(e),this.isConnected&&this.send("unsubscribe",{subscriptionId:g}).catch(d=>this.log("Unsubscribe failed",d));},l=u;return l.unsubscribe=u,l.onError=f=>{this.subscriptionErrorHandlers.get(e)?.add(f);let g=this.subscriptionLastErrors.get(e);if(g)try{f(g);}catch(d){this.log("Subscription error callback failed",d);}return l},l.onPermissionDenied=f=>{this.subscriptionPermissionHandlers.get(e)?.add(f);let g=this.subscriptionLastErrors.get(e);if(g?.permissionDenied)try{f(g);}catch(d){this.log("Subscription permission callback failed",d);}return l},l.catch=f=>l.onError(f),l}async send(e,t){if(e==="write"&&t.collection&&t.data){let r=await this.embedVectorFields(t.collection,t.data);t={...t,data:this.normalizeOutboundData(r)};}return (e==="subscribe"||e==="query")&&t?.query&&(t={...t,query:this.normalizeOutboundQuery(t.query)}),new Promise((r,i)=>{let n=uuid2(18),s={id:n,type:e,ts:Date.now(),...t};this.pendingAcks.set(n,o=>{o.type==="error"?i(new Error(`[${o.code}] ${o.message}`)):r(o);}),this.isConnected?this.transport.send(s):(this.log("Queueing message for offline",s),this.offlineQueue.push(s),i(new Error("Not connected - message queued"))),setTimeout(()=>{this.pendingAcks.has(n)&&(this.pendingAcks.delete(n),i(new Error("Request timeout")));},this.config.connectionTimeout);})}handleTransportError(e){this.log("Transport error",e),this.errorListeners.forEach(t=>{try{t(e);}catch(r){this.log("Error listener error",r);}});}onConnected(){this.setState("connected"),this.log("Connected to FlareServer"),this.activeSubscriptions.size>0&&(this.pendingSubscriptionReplay=true),this.offlineQueue.length>0&&this.syncOffline().catch(e=>{this.log("Offline sync failed",e);});}onDisconnected(){this.currentState!=="disconnected"&&this.setState("reconnecting"),this.activeSubscriptions.size>0&&(this.pendingSubscriptionReplay=true),this.log("Disconnected from FlareServer");}setState(e){this.currentState!==e&&(this.currentState=e,this.log("Connection state changed",e),this.connectionListeners.forEach(t=>{try{t(e);}catch(r){this.log("Connection listener error",r);}}));}handleIncoming(e){if(this.log("Received message",e.type,e),e.type==="query_result"&&Array.isArray(e.data)&&(e={...e,data:this.normalizeInboundData(e.data)}),e.type==="ack"||e.type==="pong"||e.type==="auth_ok"||e.type==="call_response"||e.type==="query_result"){let t=this.pendingAcks.get(e.correlationId||e.id);t&&(t(e),this.pendingAcks.delete(e.correlationId||e.id));return}if(e.type==="error"){this.log("Server error",e.code,e.message);let t=new Error(`[${e.code}] ${e.message}`);this.errorListeners.forEach(i=>{try{i(t);}catch(n){this.log("Error listener error",n);}});let r=Array.from(this.activeSubscriptions.values()).find(i=>i.liveId===e.correlationId||i.baseId===e.correlationId);if(r&&this.emitSubscriptionError(r.baseId,{code:typeof e.code=="string"?e.code:void 0,message:String(e.message??"Subscription error"),permissionDenied:e.code===c.PermissionDenied,raw:e}),e.correlationId){let i=this.pendingAcks.get(e.correlationId);i&&(i(e),this.pendingAcks.delete(e.correlationId));}return}if(e.type==="presence_state"){(this.presenceCallbacks.get(e.room)??[]).forEach(r=>{try{r(e.members);}catch{}});return}if(e.type==="presence_join"){(this.presenceJoinCbs.get(e.room)??[]).forEach(r=>{try{r(e);}catch{}});return}if(e.type==="presence_leave"){(this.presenceLeaveCbs.get(e.room)??[]).forEach(r=>{try{r(e.uid);}catch{}});return}if(e.type==="snapshot"){let t=this.subscriptions.get(e.subscriptionId);if(t){let r=this.normalizeInboundData(Array.isArray(e.data)?e.data:e.data!=null?[e.data]:[]),i={type:"snapshot",subscriptionId:e.subscriptionId,collection:e.collection,data:Array.isArray(r)?r:[]};try{t(i);}catch(n){this.log("Subscription callback error",n);}}return}if(e.type==="change"){let t=this.subscriptions.get(e.subscriptionId);if(t){let r={type:"change",subscriptionId:e.subscriptionId,collection:e.collection,docId:e.docId,operation:e.operation,data:e.operation==="delete"?null:this.normalizeInboundData(e.data)};try{t(r);}catch(i){this.log("Subscription callback error",i);}}}}};var x=class extends E{authToken;userId;authGuard;authConfig;csrfToken;csrfInitPromise;csrfBootstrapAttempted=false;socketAuthSyncPromise;pushServiceWorkerInitPromise;authSession=null;authStateListeners=[];authConfigListeners=[];currentProfile=void 0;getDefaultCsrfCookieName(){return `__flare_csrf_${this.config.appId.replace(/[^a-zA-Z0-9_-]/g,"_")}`}getCsrfCookieName(){return this.authConfig?.cookie?.csrfTokenName??this.getDefaultCsrfCookieName()}getCsrfToken(){return this.getCookieValue(this.getCsrfCookieName())??this.csrfToken??null}getCookieValue(e){if(typeof document>"u")return null;let t=document.cookie.split(";").map(i=>i.trim()).find(i=>i.startsWith(`${e}=`)||i.startsWith(`${encodeURIComponent(e)}=`));if(!t)return null;let r=t.indexOf("=");return r>=0?decodeURIComponent(t.slice(r+1)):null}extractCsrfToken(e,t){let r=e,i=typeof r?.csrfToken=="string"?String(r.csrfToken):typeof r?.csrf_token=="string"?String(r.csrf_token):void 0;if(i)return i;if(!t)return;let n=t.headers.get("x-flare-csrf")??t.headers.get("x-csrf-token")??t.headers.get("csrf-token");return typeof n=="string"&&n.length>0?n:void 0}getCsrfHeaders(){let e=this.getCsrfToken();return e?{"x-flare-csrf":e}:{}}setCsrfToken(e){this.csrfToken=e,this.csrfBootstrapAttempted=true,this.log("CSRF token injected",{length:e.length});}async ensureCsrfProtection(){if(this.getCsrfToken()){this.csrfBootstrapAttempted=true;return}if(this.config.httpBase){this.csrfBootstrapAttempted=true;return}this.csrfBootstrapAttempted||(this.csrfInitPromise||(this.csrfBootstrapAttempted=true,this.csrfInitPromise=this.loadAuthConfig().then(()=>{}).finally(()=>{this.csrfInitPromise=void 0;})),await this.csrfInitPromise,this.getCsrfToken()||this.log("CSRF token unavailable after auth config load",{hasAuthConfig:!!this.authConfig,csrfCookieName:this.getCsrfCookieName()}));}async loadAuthConfig(){let e=this.getHttpBase(),t=new URLSearchParams({appId:this.config.appId});this.config.apiKey&&t.set("apiKey",this.config.apiKey);let r=`${e}/auth/config?${t.toString()}`,i=await this.timedFetch("loadAuthConfig",r,{credentials:"include",headers:this.config.apiKey?{"x-flare-api-key":this.config.apiKey}:{}}),n=await this.parseJsonWithTiming("loadAuthConfig",i);return i.response.ok||this.throwFetchFlareError(n,"Failed to load auth config",c.QueryFailed),this.authConfig=n,this.csrfToken=this.extractCsrfToken(n,i.response)??this.csrfToken,this.authConfigListeners.forEach(s=>{try{s(this.authConfig);}catch(o){this.log("Auth config listener error",o);}}),this.authConfig}async fetchAuthConfig(){return this.authConfig?this.authConfig:this.loadAuthConfig()}onAuthConfigLoaded(e){return this.authConfigListeners.push(e),this.authConfig&&e(this.authConfig),()=>{this.authConfigListeners=this.authConfigListeners.filter(t=>t!==e);}}setProfile(e){this.currentProfile=e;}setAuthSession(e){this.authSession=e,e?(this.authToken=e.accessToken,this.userId=e.uid):(this.authToken=void 0,this.userId=void 0,this.currentProfile=void 0,this.httpResponseCache.clear(),this.httpInFlight.clear());let t=this.authSession?{...this.authSession,...this.currentProfile??{}}:null;this.authStateListeners.forEach(r=>{try{r(t);}catch(i){this.log("Auth state listener error",i);}});}onAuthStateChanged(e){this.authStateListeners.push(e);let t=this.authSession?{...this.authSession,...this.currentProfile??{}}:null;try{e(t);}catch(r){this.log("Auth state listener error during initialization",r);}return ()=>{this.authStateListeners=this.authStateListeners.filter(r=>r!==e);}}onAuthStateChange(e){return this.onAuthStateChanged(e)}get currentUser(){return this.currentProfile}getCurrentUser(){return this.currentUser}async syncSocketAuth(e){if(!this.isConnected)return;let t=await this.send("auth",e?{token:e}:{});if(t.type!=="auth_ok")throw new h("Socket auth sync failed",c.AuthenticationFailed);if(!e||t.uid==="anon"){this.authToken=void 0,this.userId=void 0,await this.updateSocketIdentity("anon");return}this.authToken=typeof t.token=="string"?t.token:e,this.userId=typeof t.uid=="string"?t.uid:this.userId,await this.updateSocketIdentity(typeof t.uid=="string"?t.uid:this.userId);}async updateSocketIdentity(e,t=false){let r=typeof e=="string"&&e.length>0?e:"anon",i=r!==this.socketAuthUid;this.socketAuthUid=r,(i||t||this.pendingSubscriptionReplay)&&this.activeSubscriptions.size>0&&await this.replayActiveSubscriptions();}async beforeActivateSubscription(e){if(!this.isConnected)return;let t=this.authSession;!t?.accessToken||!t.uid||this.socketAuthUid!==t.uid&&(this.socketAuthSyncPromise||(this.socketAuthSyncPromise=this.syncSocketAuth(t.accessToken).catch(r=>{throw this.log("Socket auth sync failed before subscribe",r),r}).finally(()=>{this.socketAuthSyncPromise=void 0;})),await this.socketAuthSyncPromise);}onConnected(){super.onConnected(),this.authSession?.accessToken&&this.syncSocketAuth(this.authSession.accessToken).catch(e=>{this.log("Socket auth sync failed after connect",e);});}handleIncoming(e){if(e.type==="auth_ok"&&!e.correlationId){let t=typeof e.token=="string"?e.token:void 0,r=typeof e.uid=="string"?e.uid:void 0;this.updateSocketIdentity(r,this.pendingSubscriptionReplay).catch(i=>{this.log("Socket identity update failed",i);}),t&&r&&r!=="anon"&&r!=="__admin__"?this.fetchAuthMe(t).then(i=>{this.setAuthSession({uid:r,accessToken:t,refreshToken:this.authSession?.refreshToken??null,email:i?.email??null,emailVerified:i?.email_verified});}).catch(()=>{this.setAuthSession({uid:r,accessToken:t,refreshToken:this.authSession?.refreshToken??null});}):r==="anon"&&this.authSession&&this.setAuthSession(null);}super.handleIncoming(e);}async auth(e){let t=await this.send("auth",{token:e});if(t.type==="auth_ok"){let r=t.token??e;this.authToken=r,this.userId=t.uid;let i=await this.fetchAuthMe(r).catch(()=>null);return this.setAuthSession({uid:t.uid??t.id,accessToken:r,refreshToken:this.authSession?.refreshToken??null,email:i?.email??null,emailVerified:i?.email_verified}),await this.updateSocketIdentity(t.uid),this.log("Authentication successful",t.uid),{uid:t.uid,token:t.token??e}}throw new h("Authentication failed",c.AuthenticationFailed)}async signInWithEmailAndPassword(e,t,r){try{let i=await this.requestEmailPasswordToken(e,t,r?.scope),n=await this.auth(i.access_token),s=await this.fetchAuthMe(i.access_token).catch(()=>null);return this.setAuthSession({uid:n.uid,accessToken:i.access_token,refreshToken:i.refresh_token,provider:i.provider,email:s?.email??e,emailVerified:s?.email_verified}),this.log("Credentials sign-in successful",n.uid),{...n,kind:i.kind,accessToken:i.access_token,refreshToken:i.refresh_token,authToken:i}}catch(i){let n=/invalid_email|user.not.found|no user/i.test(i?.message??"");if(r?.createIfMissing&&n){let s=await this.createUserWithEmail(e,t,{scope:r.scope,signInIfAllowed:true});if("verificationRequired"in s&&s.verificationRequired)throw new h("Email verification required before sign-in",c.AuthenticationFailed);return {uid:s.uid,token:s.token,accessToken:s.accessToken,refreshToken:s.refreshToken,authToken:s.authToken,created:true}}throw i instanceof h?i:new h(i instanceof Error?i.message:"Sign-in with email/password failed",i.error??i.code??c.AuthenticationFailed,i)}}async signInWithEmail(e,t,r){return this.signInWithEmailAndPassword(e,t,r)}async createUserWithEmail(e,t,r){let i=await this.registerWithEmail(e,t,r);if(i.verification_required)return {kind:i.kind,verificationRequired:true,emailSent:!!i.email_sent,preview:i.preview};let n=String(i.access_token??"");if(!n)throw new h("User created but no access token returned",c.AuthenticationFailed);let s={access_token:n,refresh_token:i.refresh_token?String(i.refresh_token):null,expires_in:i.expires_in?Number(i.expires_in):null,token_type:String(i.token_type??"Bearer"),scope:i.scope?String(i.scope):null,profile:null,provider:"credentials"},o=await this.auth(n),u=await this.fetchAuthMe(n).catch(()=>null);return this.setAuthSession({uid:o.uid,accessToken:n,refreshToken:s.refresh_token,provider:"credentials",email:u?.email??e,emailVerified:u?.email_verified}),{...o,accessToken:n,refreshToken:s.refresh_token,authToken:s,verificationRequired:false,emailSent:!!i.email_sent,preview:i.preview}}async createUserWithEmailAndPassword(e,t,r){return this.createUserWithEmail(e,t,r)}async signInOrCreateWithEmail(e,t,r){try{return {...await this.signInWithEmailAndPassword(e,t,{scope:r?.scope}),created:!1}}catch(i){if(!/invalid_email|user.not.found|no user/i.test(i?.message??""))throw i;let s=await this.createUserWithEmail(e,t,{scope:r?.scope,additionalParams:r?.additionalParams,signInIfAllowed:true});return "verificationRequired"in s&&s.verificationRequired?{...s,created:true}:{...s,created:true}}}async signInOrCreateWithEmailAndPassword(e,t,r){return this.signInOrCreateWithEmail(e,t,r)}async sendEmailVerification(e){let t=this.getHttpBase();await this.ensureCsrfProtection();let r=await this.timedFetch("sendEmailVerification",`${t}/auth/verify/send?appId=${encodeURIComponent(this.config.appId)}`,{method:"POST",credentials:"include",headers:{"Content-Type":"application/json",...this.getCsrfHeaders(),...this.config.apiKey?{"x-flare-api-key":this.config.apiKey}:{}},body:JSON.stringify({email:e,appId:this.config.appId,apiKey:this.config.apiKey})}),i=await this.parseJsonWithTiming("sendEmailVerification",r);return r.response.ok||this.throwFetchFlareError(i,"Failed to send verification email",c.AuthenticationFailed),i}async verifyEmailWithCode(e,t){let r=this.getHttpBase();await this.ensureCsrfProtection();let i=await this.timedFetch("verifyEmailWithCode",`${r}/auth/verify/confirm?appId=${encodeURIComponent(this.config.appId)}`,{method:"POST",credentials:"include",headers:{"Content-Type":"application/json",...this.getCsrfHeaders(),...this.config.apiKey?{"x-flare-api-key":this.config.apiKey}:{}},body:JSON.stringify({email:e,code:t,appId:this.config.appId,apiKey:this.config.apiKey})}),n=await this.parseJsonWithTiming("verifyEmailWithCode",i);return i.response.ok||this.throwFetchFlareError(n,"Email verification failed",c.AuthenticationFailed),n}async confirmEmailLink(e,t){let r=this.getHttpBase();await this.ensureCsrfProtection();let i=await this.timedFetch("confirmEmailLink",`${r}/auth/verify/confirm?appId=${encodeURIComponent(this.config.appId)}`,{method:"POST",credentials:"include",headers:{"Content-Type":"application/json",...this.getCsrfHeaders(),...this.config.apiKey?{"x-flare-api-key":this.config.apiKey}:{}},body:JSON.stringify({token:e,email:t,appId:this.config.appId,apiKey:this.config.apiKey})}),n=await this.parseJsonWithTiming("confirmEmailLink",i);return i.response.ok||this.throwFetchFlareError(n,"Email link verification failed",c.AuthenticationFailed),n}async sendAccountRecovery(e){let t=this.getHttpBase();await this.ensureCsrfProtection();let r=await this.timedFetch("sendAccountRecovery",`${t}/auth/recover/send?appId=${encodeURIComponent(this.config.appId)}`,{method:"POST",credentials:"include",headers:{"Content-Type":"application/json",...this.getCsrfHeaders(),...this.config.apiKey?{"x-flare-api-key":this.config.apiKey}:{}},body:JSON.stringify({email:e,appId:this.config.appId,apiKey:this.config.apiKey})}),i=await this.parseJsonWithTiming("sendAccountRecovery",r);return r.response.ok||this.throwFetchFlareError(i,"Failed to send recovery email",c.AuthenticationFailed),i}async recoverAccountWithCode(e,t,r){let i=this.getHttpBase();await this.ensureCsrfProtection();let n=await this.timedFetch("recoverAccountWithCode",`${i}/auth/recover/confirm?appId=${encodeURIComponent(this.config.appId)}`,{method:"POST",credentials:"include",headers:{"Content-Type":"application/json",...this.getCsrfHeaders(),...this.config.apiKey?{"x-flare-api-key":this.config.apiKey}:{}},body:JSON.stringify({email:e,code:t,newPassword:r,appId:this.config.appId,apiKey:this.config.apiKey})}),s=await this.parseJsonWithTiming("recoverAccountWithCode",n);return n.response.ok||this.throwFetchFlareError(s,"Account recovery failed",c.AuthenticationFailed),s}async recoverAccountWithToken(e,t){let r=this.getHttpBase();await this.ensureCsrfProtection();let i=await this.timedFetch("recoverAccountWithToken",`${r}/auth/recover/confirm?appId=${encodeURIComponent(this.config.appId)}`,{method:"POST",credentials:"include",headers:{"Content-Type":"application/json",...this.getCsrfHeaders(),...this.config.apiKey?{"x-flare-api-key":this.config.apiKey}:{}},body:JSON.stringify({token:e,newPassword:t,appId:this.config.appId,apiKey:this.config.apiKey})}),n=await this.parseJsonWithTiming("recoverAccountWithToken",i);return i.response.ok||this.throwFetchFlareError(n,"Account recovery failed",c.AuthenticationFailed),n}toUint8ArrayFromBase64Url(e){let t=e.replace(/-/g,"+").replace(/_/g,"/"),r="=".repeat((4-t.length%4)%4),i=t+r,n=atob(i),s=new Uint8Array(n.length);for(let o=0;o<n.length;o+=1)s[o]=n.charCodeAt(o);return s}encodePushTokenFromSubscription(e){let t=e.toJSON(),r=String(t.endpoint??"").trim(),i=String(t.keys?.p256dh??"").trim(),n=String(t.keys?.auth??"").trim(),s=JSON.stringify({endpoint:r,p256dh:i,auth:n});return `webpush:${btoa(s)}`}async fetchPushSetupConfig(){let e=this.getHttpBase(),t=new URLSearchParams({appId:this.config.appId});this.config.apiKey&&t.set("apiKey",this.config.apiKey);let r=`${e}/push/config?${t.toString()}`,i=await this.timedFetch("fetchPushSetupConfig",r,{method:"GET",credentials:"include",headers:this.config.apiKey?{"x-flare-api-key":this.config.apiKey}:{}}),n=await this.parseJsonWithTiming("fetchPushSetupConfig",i);i.response.ok||this.throwFetchFlareError(n,"Failed to fetch push setup config",c.QueryFailed);let s=String(n.vapidPublicKey??"").trim(),o=String(n.serviceWorkerPath??"").trim();if(o.startsWith("/"))try{let l=new URL(e,typeof window<"u"?window.location.origin:"http://localhost").pathname.replace(/\/+$/,"");l&&l!=="/"&&!o.startsWith(`${l}/`)&&(o=`${l}${o}`);}catch{}if(!s||!o)throw new h("Push setup response is missing vapidPublicKey or serviceWorkerPath",c.ParseError,n);return {vapidPublicKey:s,serviceWorkerPath:o}}async setupPushServiceWorker(){return typeof window>"u"||typeof navigator>"u"||!("serviceWorker"in navigator)?null:(this.pushServiceWorkerInitPromise||(this.pushServiceWorkerInitPromise=(async()=>{let e=await this.fetchPushSetupConfig(),t=new URL(e.serviceWorkerPath,window.location.origin);if(t.origin!==window.location.origin)throw new h("Service worker URL must be same-origin with the app",c.WriteFailed);return await navigator.serviceWorker.register(t.pathname+t.search,{scope:"/"})})().catch(e=>{throw this.log("Push service worker setup failed",e),e})),this.pushServiceWorkerInitPromise)}async requestPushPermission(){if(typeof window>"u"||typeof Notification>"u")throw new h("Push permission can only be requested in browser runtime",c.WriteFailed);let e=await Notification.requestPermission();if(e!=="granted")throw new h(`Push permission is ${e}`,c.PermissionDenied);return e}async acquireBrowserPushToken(e={}){if(typeof window>"u"||typeof navigator>"u")throw new h("Push token acquisition can only run in browser runtime",c.WriteFailed);if(!("serviceWorker"in navigator))throw new h("Service worker is not supported in this browser",c.WriteFailed);if(!("PushManager"in window))throw new h("Push manager is not supported in this browser",c.WriteFailed);await this.requestPushPermission();let t=e.applicationServerKey?null:await this.fetchPushSetupConfig(),r=e.serviceWorkerRegistration??await this.setupPushServiceWorker()??await navigator.serviceWorker.ready,i=e.subscription??await r.pushManager.getSubscription();if(e.forceResubscribe&&i&&(await i.unsubscribe().catch(()=>{}),i=null),!i){let s=e.applicationServerKey??t?.vapidPublicKey;if(!s)throw new h("No VAPID public key available for push subscription",c.WriteFailed);i=await r.pushManager.subscribe({userVisibleOnly:true,applicationServerKey:this.toUint8ArrayFromBase64Url(s)});}return {token:this.encodePushTokenFromSubscription(i),subscription:i}}async enableBrowserPush(e={}){let{token:t,subscription:r}=await this.acquireBrowserPushToken(e);return {...await this.registerPushToken({token:t,platform:e.platform??"web",deviceId:e.deviceId,topics:e.topics,authAppId:e.authAppId}),subscription:r}}async registerPushToken(e){let t=this.getHttpBase();await this.ensureCsrfProtection();let r=String(e.token??"").trim();if(!r)throw new h("Push token is required",c.WriteFailed);let i=await this.timedFetch("registerPushToken",`${t}/notify/token?appId=${encodeURIComponent(this.config.appId)}`,{method:"POST",credentials:"include",headers:{"Content-Type":"application/json",...this.getCsrfHeaders(),...this.config.apiKey?{"x-flare-api-key":this.config.apiKey}:{},...this.authSession?.accessToken?{Authorization:`Bearer ${this.authSession.accessToken}`}:{}},body:JSON.stringify({appId:this.config.appId,token:r,platform:e.platform,deviceId:e.deviceId,topics:e.topics,...e.authAppId?{authAppId:e.authAppId}:{}})}),n=await this.parseJsonWithTiming("registerPushToken",i);return i.response.ok||this.throwFetchFlareError(n,"Failed to register push token",c.WriteFailed),{registered:!!n.registered,appId:String(n.appId??this.config.appId),uid:String(n.uid??this.authSession?.uid??""),token:String(n.token??r),...typeof n.platform=="string"?{platform:n.platform}:{}}}async unregisterPushToken(e,t){let r=this.getHttpBase();await this.ensureCsrfProtection();let i=String(e??"").trim();if(!i)throw new h("Push token is required",c.WriteFailed);let n=await this.timedFetch("unregisterPushToken",`${r}/notify/token?appId=${encodeURIComponent(this.config.appId)}`,{method:"DELETE",credentials:"include",headers:{"Content-Type":"application/json",...this.getCsrfHeaders(),...this.config.apiKey?{"x-flare-api-key":this.config.apiKey}:{},...this.authSession?.accessToken?{Authorization:`Bearer ${this.authSession.accessToken}`}:{}},body:JSON.stringify({appId:this.config.appId,token:i,...t?{authAppId:t}:{}})}),s=await this.parseJsonWithTiming("unregisterPushToken",n);return n.response.ok||this.throwFetchFlareError(s,"Failed to unregister push token",c.WriteFailed),{unregistered:!!s.unregistered,appId:String(s.appId??this.config.appId),token:String(s.token??i),removed:!!s.removed}}async sendPushNotification(e){let t=this.getHttpBase();await this.ensureCsrfProtection();let r=await this.timedFetch("sendPushNotification",`${t}/system/apps/${encodeURIComponent(this.config.appId)}/notifications/send`,{method:"POST",credentials:"include",headers:{"Content-Type":"application/json",...this.getCsrfHeaders(),...this.authSession?.accessToken?{Authorization:`Bearer ${this.authSession.accessToken}`}:{},...e.authAppId?{"x-flare-auth-app-id":e.authAppId}:{}},body:JSON.stringify({...e,appId:this.config.appId})}),i=await this.parseJsonWithTiming("sendPushNotification",r);return r.response.ok||this.throwFetchFlareError(i,"Failed to send push notification",c.WriteFailed),{sent:!!i.sent,appId:String(i.appId??this.config.appId),targetCount:Number(i.targetCount??0),successCount:Number(i.successCount??0),failureCount:Number(i.failureCount??0),invalidatedTokenCount:Number(i.invalidatedTokenCount??0),dryRun:!!i.dryRun}}async sendEmail(e){let t=this.getHttpBase();await this.ensureCsrfProtection();let r=await this.timedFetch("sendEmail",`${t}/system/apps/${encodeURIComponent(this.config.appId)}/email/send`,{method:"POST",credentials:"include",headers:{"Content-Type":"application/json",...this.getCsrfHeaders(),...this.authSession?.accessToken?{Authorization:`Bearer ${this.authSession.accessToken}`}:{},...e.authAppId?{"x-flare-auth-app-id":e.authAppId}:{}},body:JSON.stringify({...e,appId:this.config.appId})}),i=await this.parseJsonWithTiming("sendEmail",r);return r.response.ok||this.throwFetchFlareError(i,"Failed to send template email",c.WriteFailed),{sent:!!i.sent,appId:String(i.appId??this.config.appId),tag:String(i.tag??e.tag??""),recipientCount:Number(i.recipientCount??0),acceptedCount:Number(i.acceptedCount??0),rejectedCount:Number(i.rejectedCount??0),...typeof i.includeVerificationLink=="boolean"?{includeVerificationLink:i.includeVerificationLink}:{},...typeof i.linkId=="string"?{linkId:i.linkId}:{},...typeof i.verifyUrl=="string"?{verifyUrl:i.verifyUrl}:{},...typeof i.messageId=="string"?{messageId:i.messageId}:{}}}async verifyEmailLink(e){let t=this.getHttpBase(),r=String(e.token??"").trim();if(!r)throw new h("Verification token is required",c.WriteFailed);let i=await this.timedFetch("verifyEmailLink",`${t}/email/link/verify?appId=${encodeURIComponent(this.config.appId)}`,{method:"POST",credentials:"include",headers:{"Content-Type":"application/json",...this.config.apiKey?{"x-flare-api-key":this.config.apiKey}:{},...this.authSession?.accessToken?{Authorization:`Bearer ${this.authSession.accessToken}`}:{},...e.authAppId?{"x-flare-auth-app-id":e.authAppId}:{}},body:JSON.stringify({appId:this.config.appId,apiKey:this.config.apiKey,token:r,...e.tag?{tag:e.tag}:{},...e.email?{email:e.email}:{},...e.authAppId?{authAppId:e.authAppId}:{}})}),n=await this.parseJsonWithTiming("verifyEmailLink",i);return i.response.ok||this.throwFetchFlareError(n,"Failed to verify email link",c.WriteFailed),{verified:!!(n.verified??n.accepted),alreadyVerified:!!(n.alreadyVerified??n.alreadyAccepted),appId:String(n.appId??this.config.appId),linkId:String(n.linkId??""),email:String(n.email??""),tag:String(n.tag??e.tag??""),...typeof n.verifiedAt=="string"?{verifiedAt:n.verifiedAt}:{},...typeof n.acceptedByUid=="string"?{acceptedByUid:n.acceptedByUid}:{}}}async signIn(e,t,r){let i=typeof e?.signIn=="function",n=i?e:await this.getAuthGuard(),s=i?t:e,o=i?r:t;return n.signIn(s,o)}async signInWithGoogle(e){return this.signIn("google",e)}async signInWithGitHub(e){return this.signIn("github",e)}async signInWithFacebook(e){return this.signIn("facebook",e)}async signInWithDropbox(e){return this.signIn("dropbox",e)}async handleSignInRedirect(e,t=false){let r=typeof e?.handleRedirect=="function",i=r?e:await this.getAuthGuard(),n=r?t:typeof e=="boolean"?e:false,s=await i.handleRedirect(n);if(!s||!s.access_token||!s.provider)return null;let o=await this.exchangeProviderToken(s.provider,s.access_token),u=await this.auth(o.token),l=await this.fetchAuthMe(o.token).catch(()=>null);return this.setAuthSession({uid:u.uid,accessToken:o.token,refreshToken:s.refresh_token,provider:s.provider,email:l?.email??null,emailVerified:l?.email_verified}),{...u,authToken:s,provider:s.provider}}async exchangeProviderToken(e,t){let r=`${this.getHttpBase()}/auth/exchange`;await this.ensureCsrfProtection();let i=await this.timedFetch("exchangeProviderToken",r,{method:"POST",credentials:"include",headers:{"Content-Type":"application/json",...this.getCsrfHeaders()},body:JSON.stringify({appId:this.config.appId,client_id:this.config.apiKey,provider:e,access_token:t})}),n=await this.parseJsonWithTiming("exchangeProviderToken",i);if(i.response.ok||this.throwFetchFlareError(n,"OAuth token exchange failed",c.AuthenticationFailed),!n?.token)throw new h("OAuth token exchange failed",c.ParseError,n);return {token:String(n.token)}}async getAuthGuard(){if(this.authGuard)return this.authGuard;let e=await this.fetchAuthConfig();if(!e.enabled)throw new h("Authentication is disabled for this app",c.AuthenticationFailed);let t=this.getHttpBase(),r=`${t}/auth/oauth/token?appId=${encodeURIComponent(this.config.appId)}`,i=[],n=(s,o)=>({...o,token_url:r,tokenParams:{...o.tokenParams??{},provider:s}});if(e.providers.credentials?.enabled&&i.push({...Credentials({clientId:this.config.apiKey}),token_url:`${t}/auth/token?appId=${encodeURIComponent(this.config.appId)}`,createUserUrl:`${t}/auth/register?appId=${encodeURIComponent(this.config.appId)}`,createUserGrantType:"create_user"}),e.providers.anonymous?.enabled&&i.push({...Anonymous({clientId:this.config.apiKey}),token_url:`${t}/auth/token?appId=${encodeURIComponent(this.config.appId)}`}),e.providers.google?.enabled&&e.providers.google.clientId&&i.push(n("google",Google({clientId:e.providers.google.clientId,scopes:e.providers.google.scopes}))),e.providers.github?.enabled&&e.providers.github.clientId&&i.push(n("github",GitHub({clientId:e.providers.github.clientId,scopes:e.providers.github.scopes}))),e.providers.facebook?.enabled&&e.providers.facebook.clientId&&i.push(n("facebook",Facebook({clientId:e.providers.facebook.clientId,scopes:e.providers.facebook.scopes}))),e.providers.dropbox?.enabled&&e.providers.dropbox.clientId&&i.push(n("dropbox",Dropbox({clientId:e.providers.dropbox.clientId,scopes:e.providers.dropbox.scopes}))),e.providers.apple?.enabled&&e.providers.apple.clientId&&i.push(n("apple",Apple({clientId:e.providers.apple.clientId,scopes:e.providers.apple.scopes}))),e.providers.twitter?.enabled&&e.providers.twitter.clientId&&i.push(n("twitter",Twitter({clientId:e.providers.twitter.clientId,scopes:e.providers.twitter.scopes}))),i.length===0)throw new h("No authentication providers are enabled for this app",c.AuthenticationFailed);return this.authGuard=new AuthGuard({providers:i,redirectUri:e.redirectUri}),this.authGuard}async refreshAuthSession(e){let t=this.getHttpBase();await this.ensureCsrfProtection();let r=await this.timedFetch("refreshAuthSession",`${t}/auth/refresh?appId=${encodeURIComponent(this.config.appId)}`,{method:"POST",credentials:"include",headers:{"Content-Type":"application/json",...this.getCsrfHeaders(),...this.config.apiKey?{"x-flare-api-key":this.config.apiKey}:{}},body:JSON.stringify({appId:this.config.appId,apiKey:this.config.apiKey,...e?{refresh_token:e}:{}})}),i=await this.parseJsonWithTiming("refreshAuthSession",r);if(!r.response.ok){if(r.response.status===401)return this.setAuthSession(null),await this.syncSocketAuth(null).catch(()=>{}),null;this.throwFetchFlareError(i,"Failed to refresh auth session",c.AuthenticationFailed);}let n=String(i.access_token??"");if(!n)throw new h("Refresh succeeded but no access token was returned",c.ParseError);let s=await this.fetchAuthMe(n).catch(()=>null),o={uid:String(s?.id??this.authSession?.uid??this.userId??""),accessToken:n,refreshToken:i.refresh_token?String(i.refresh_token):this.authSession?.refreshToken??null,provider:this.authSession?.provider,email:s?.email??this.authSession?.email??null,emailVerified:s?.email_verified};if(s){try{delete s.kind,s.uid=s.id??s.uid,delete s.id;}catch{}this.setProfile(s);}return this.setAuthSession(o),await this.syncSocketAuth(n).catch(()=>{}),o}async issueSsrToken(e=120){let t=this.getHttpBase();await this.ensureCsrfProtection();let r=await this.timedFetch("issueSsrToken",`${t}/auth/ssr/token?appId=${encodeURIComponent(this.config.appId)}`,{method:"POST",credentials:"include",headers:{"Content-Type":"application/json",...this.getCsrfHeaders(),...this.config.apiKey?{"x-flare-api-key":this.config.apiKey}:{}},body:JSON.stringify({appId:this.config.appId,apiKey:this.config.apiKey,ttlSeconds:e})}),i=await this.parseJsonWithTiming("issueSsrToken",r);r.response.ok||this.throwFetchFlareError(i,"Failed to mint SSR token",c.AuthenticationFailed);let n=String(i.token??"");if(!n)throw new h("SSR token response is missing token",c.ParseError,i);return {token:n,token_type:String(i.token_type??"Bearer"),expires_in:Number(i.expires_in??0),uid:String(i.uid??""),role:String(i.role??"user"),...typeof i.email=="string"?{email:i.email}:{}}}async signOut(){try{if(this.authSession?.accessToken||this.authSession?.refreshToken||this.config.httpBase){let t=this.getHttpBase();await this.ensureCsrfProtection(),await this.timedFetch("signOut",`${t}/auth/logout?appId=${encodeURIComponent(this.config.appId)}`,{method:"POST",credentials:"include",headers:{"Content-Type":"application/json",...this.getCsrfHeaders(),...this.config.apiKey?{"x-flare-api-key":this.config.apiKey}:{},...this.authSession?.accessToken?{Authorization:`Bearer ${this.authSession.accessToken}`}:{}},body:JSON.stringify({appId:this.config.appId,apiKey:this.config.apiKey,refresh_token:this.authSession?.refreshToken})}).catch(()=>{});}}finally{this.setAuthSession(null),await this.syncSocketAuth(null).catch(()=>{});}this.log("Signed out");}async registerWithEmail(e,t,r){let i=this.getHttpBase();await this.ensureCsrfProtection();let n=new URLSearchParams;n.set("appId",this.config.appId),n.set("client_id",this.config.apiKey??""),n.set("grant_type","create_user"),n.set("email",e),n.set("password",t),r?.scope?.length&&n.set("scope",r.scope.join(" ")),r?.additionalParams&&n.set("additional_params",JSON.stringify(r.additionalParams));let s=await this.timedFetch("registerWithEmail",`${i}/auth/register?appId=${encodeURIComponent(this.config.appId)}`,{method:"POST",credentials:"include",headers:{"Content-Type":"application/x-www-form-urlencoded",...this.getCsrfHeaders(),...this.config.apiKey?{"x-flare-api-key":this.config.apiKey}:{}},body:n.toString()}),o=await this.parseJsonWithTiming("registerWithEmail",s);return !s.response.ok&&s.response.status!==202&&this.throwFetchFlareError(o,"User creation failed",c.WriteFailed),o}async requestEmailPasswordToken(e,t,r){let i=this.getHttpBase();await this.ensureCsrfProtection();let n=new URLSearchParams;n.set("appId",this.config.appId),n.set("client_id",this.config.apiKey??""),n.set("grant_type","password"),n.set("email",e),n.set("password",t),r?.length&&n.set("scope",r.join(" "));let s=await this.timedFetch("requestEmailPasswordToken",`${i}/auth/token?appId=${encodeURIComponent(this.config.appId)}`,{method:"POST",credentials:"include",headers:{"Content-Type":"application/x-www-form-urlencoded",...this.getCsrfHeaders(),...this.config.apiKey?{"x-flare-api-key":this.config.apiKey}:{}},body:n.toString()}),o=await this.parseJsonWithTiming("requestEmailPasswordToken",s);return s.response.ok||this.throwFetchFlareError(o,"Sign-in with email/password failed",c.AuthenticationFailed),{kind:String(o.kind),access_token:String(o.access_token??""),refresh_token:o.refresh_token?String(o.refresh_token):null,expires_in:o.expires_in?Number(o.expires_in):null,token_type:String(o.token_type??"Bearer"),scope:o.scope?String(o.scope):null,profile:null,provider:"credentials"}}async fetchAuthMe(e){let t=this.getHttpBase(),r=new URLSearchParams({appId:this.config.appId});this.config.apiKey&&r.set("apiKey",this.config.apiKey);let i=`${t}/auth/me?${r.toString()}`,n=await this.timedFetch("fetchAuthMe",i,{credentials:"include",headers:{Authorization:`Bearer ${e}`,...this.config.apiKey?{"x-flare-api-key":this.config.apiKey}:{}}}),s=await this.parseJsonWithTiming("fetchAuthMe",n);return n.response.ok||this.throwFetchFlareError(s,"Failed to fetch profile",c.QueryFailed),s}};var H=class extends x{autoPushRegisteredIdentity;constructor(e){super(e),this.log("FlareClient initialized",e),e.pushNotifications===true&&this.enableAutoPushNotificationsAfterAuth();}enableAutoPushNotificationsAfterAuth(){let e=async()=>{let t=this.authSession,r=String(t?.uid??"").trim()||"anon",i=String(t?.accessToken??"").trim(),n=r!=="anon"&&i?r:"anon";if(this.autoPushRegisteredIdentity!==n)try{await this.autoEnablePushNotifications(),this.autoPushRegisteredIdentity=n;}catch(s){this.log("Auto push enable failed",s);}};this.onAuthStateChanged(()=>{e().catch(()=>{});}),e().catch(()=>{});}async autoEnablePushNotifications(){await this.setupPushServiceWorker().catch(()=>{}),await this.requestPushPermission();let{token:e}=await this.acquireBrowserPushToken();await this.registerPushToken({token:e,platform:"web",topics:[this.config.appId]});}},D=H;function U(a){return `__flare_csrf_${a.replace(/[^a-zA-Z0-9_-]/g,"_")}`}function Se(a){return `__flare_csrf_${a.replace(/[^a-zA-Z0-9_-]/g,"_")}`}function F(a,e){let t=e.toLowerCase();for(let[r,i]of Object.entries(a??{}))if(r.toLowerCase()===t&&typeof i=="string")return i}function Te(a){let e=F(a,"set-cookie");if(typeof e=="string"&&e.length>0)return [e];for(let[t,r]of Object.entries(a??{}))if(t.toLowerCase()==="set-cookie"&&Array.isArray(r))return r.filter(i=>typeof i=="string");return []}function Ce(a,e){for(let t of a){let r=t.split(";").map(u=>u.trim()),[i]=r;if(!i)continue;let n=i.indexOf("=");if(n<=0)continue;let s=decodeURIComponent(i.slice(0,n)),o=i.slice(n+1);if(s===e)return decodeURIComponent(o)}}async function we(a){let e=new URL("/auth/config",a.endpoint);return e.searchParams.set("appId",a.appId),a.apiKey&&e.searchParams.set("apiKey",a.apiKey),await withGet(e.toString(),{ignoreKind:true,withCredentials:true,returnRawResponse:true,headers:a.apiKey?{"x-flare-api-key":a.apiKey}:{},appendCookiesToBody:false,appendTimestamp:false}).catch(()=>null)}async function J(a){let e=await we(a),t=e?.data,r=e?.headers??{},i=F(r,"x-flare-csrf")??F(r,"x-csrf-token")??F(r,"csrf-token");if(typeof i=="string"&&i.length>0)return {csrfToken:i,...t};let n=t?.cookie?.csrfTokenName,s=n&&n.length>0?n:Se(a.appId),o=Te(r),u=Ce(o,s);if(typeof u=="string"&&u.length>0)return {csrfToken:u,...t}}function V(a,e,t){return `${encodeURIComponent(a)}=${encodeURIComponent(e)}; HttpOnly; SameSite=Strict; Path=/; Max-Age=${t}`}function Pe(a){let e=a.proxyCookieName??U(a.appId),t=a.proxyCookieMaxAge??3600;return async function(i){let n=await J(a),s=n?.csrfToken,o=new Headers({"Content-Type":"application/json"});return s&&o.set("Set-Cookie",V(e,s,t)),new Response(JSON.stringify({csrfToken:s??null,...n}),{status:200,headers:o})}}function Ie(a){let e=a.proxyCookieName??U(a.appId),t=a.proxyCookieMaxAge??3600;return async function(i,n){if(i.method!=="GET"&&i.method!=="HEAD"){n.status(405).json({error:"Method not allowed"});return}let o=(await J(a))?.csrfToken;o&&n.setHeader("Set-Cookie",V(e,o,t)),n.status(200).json({csrfToken:o??null});}}function ve(a,e,t){let r=t??U(e);if(a instanceof Request){let s=(a.headers.get("cookie")??"").split(";").map(u=>u.trim()).find(u=>u.startsWith(`${encodeURIComponent(r)}=`)||u.startsWith(`${r}=`));if(!s)return null;let o=s.indexOf("=");return o>=0?decodeURIComponent(s.slice(o+1)):null}let{cookies:i}=a;return typeof i?.get=="function"?i.get(r)?.value??null:i&&typeof i=="object"?i[r]??null:null}function Ae(a,e){let t={};return a&&(t["x-flare-csrf"]=a),e?.accessToken&&(t.Authorization=`Bearer ${e.accessToken}`),e?.apiKey&&(t["x-flare-api-key"]=e.apiKey),t}var Re=a=>a==="guest"?"auth == null":a==="auth"?"auth != null":"true",Ee=(a,e)=>{let t=String(e??"").trim();return t?a==="true"?t:`(${a}) && (${t})`:a},xe=a=>{let e=String(a??"").trim();if(!e||e==="false")return {auth:"any"};if(e==="auth != null")return {auth:"auth"};if(e==="auth == null")return {auth:"guest"};if(e==="true")return {auth:"any"};let t=e.match(/^\((auth != null|auth == null|true)\)\s*&&\s*\((.+)\)$/);if(t)return {auth:z(t[1]),condition:t[2].trim()};let r=e.match(/^(auth != null|auth == null|true)\s*&&\s*(.+)$/);return r?{auth:z(r[1]),condition:r[2].trim()}:{auth:"any",condition:e}},z=a=>{let e=String(a??"").trim();return e==="auth == null"?"guest":e==="auth != null"?"auth":"any"},Rt=a=>{let e={};for(let t of a){let r=String(t.collection||"").trim();if(!r)continue;let i=r==="any"?"*":r,n=Ee(Re(t.auth),t.condition);e[i]={".read":t.permissions.includes("read")?n:"false",".create":t.permissions.includes("create")?n:"false",".update":t.permissions.includes("update")?n:"false",".delete":t.permissions.includes("delete")?n:"false"};}return e},Et=a=>Object.entries(a).map(([e,t],r)=>{let i=t?.[".read"],n=t?.[".create"],s=t?.[".update"],o=t?.[".delete"],u=t?.[".write"],l=[];typeof i=="string"&&i.trim()!=="false"&&l.push("read");let f=typeof n=="string"&&n.trim()!=="false"||typeof u=="string"&&u.trim()!=="false",g=typeof s=="string"&&s.trim()!=="false"||typeof u=="string"&&u.trim()!=="false",d=typeof o=="string"&&o.trim()!=="false"||typeof u=="string"&&u.trim()!=="false";f&&l.push("create"),g&&l.push("update"),d&&l.push("delete");let C=xe(i||n||s||o||u);return {id:`${e}-${r}`,name:e==="*"?"All Collections":e,auth:C.auth,collection:e==="*"?"any":e,condition:C.condition,permissions:l}});var Fe=(g=>(g.authEmailNotVerified="auth/email-not-verified",g.authEmailAlreadyVerified="auth/email-already-verified",g.authInvalidToken="auth/invalid-token",g.authUserDisabled="auth/user-disabled",g.authUserNotFound="auth/user-not-found",g.authWrongPassword="auth/wrong-password",g.authEmailAlreadyInUse="auth/email-already-in-use",g.authInvalidEmail="auth/invalid-email",g.authWeakPassword="auth/weak-password",g.authTooManyRequests="auth/too-many-requests",g.authInternalError="auth/internal-error",g))(Fe||{});var _e=(p=>(p.health="health",p.authConfig="auth_config",p.authRegistration="auth/registration",p.authRegistrationVerificationRequired="auth/registration-verification-required",p.authSession="auth/session",p.authExchange="auth/exchange",p.authLogout="auth/logout",p.authSsrBridge="auth/ssr_bridge",p.authSsrVerify="auth/ssr_verify",p.accountRecovery="account/recovery",p.emailVerification="email/verification",p.verificationDispatch="verification/dispatch",p.authProfile="auth/profile",p.adminToken="admin/token",p.documentDelete="document/delete",p.documentsDelete="documents/delete",p.documents="documents",p.document="document",p.documentCreate="document/create",p.documentUpdate="document/update",p.oauthProviderResponse="oauth_provider_response",p.success="success",p.response="response",p))(_e||{});var b=null,P=null,_=null,Me=a=>JSON.stringify({endpoint:a.endpoint,appId:a.appId,apiKey:a.apiKey,publicKey:a.publicKey,autoReconnect:a.autoReconnect,reconnectDelay:a.reconnectDelay,maxReconnectDelay:a.maxReconnectDelay}),Ot=a=>{let e=Me(a);if(b&&_!==e&&(b.disconnect(),b=null,P=null,_=null),!b){b=new D(a),_=e;let t=typeof window<"u"&&typeof document<"u",r=typeof process<"u"&&typeof process.env?.NEXT_RUNTIME=="string";(t||!r)&&b.connect(),t&&b.setupPushServiceWorker().catch(()=>{}),P=new Proxy(b,{get(i,n,s){if(n==="onAuthStateChange")return i.onAuthStateChanged.bind(i);if(n==="onAuthConfigLoaded")return i.onAuthConfigLoaded.bind(i);let o=Reflect.get(i,n,s);return typeof o=="function"?o.bind(i):o}});}return P??b},Ht=()=>P??b,Dt=()=>{b&&(b.disconnect(),b=null,P=null,_=null);},Ut=D;
|
|
2
|
+
export{O as CollectionReference,k as DocumentQueryBuilder,w as DocumentReference,ee as FlareAction,h as FlareError,Fe as FlareErrors,te as FlareEvent,_e as FlareResponseCodes,Ae as buildFlareHeaders,Ot as connectApp,Pe as createCsrfProxy,Ie as createCsrfProxyHandler,Ut as default,Dt as disconnectFlare,ve as extractCsrfFromRequest,Rt as flareRulesToSecurityMap,Ht as getFlare,q as parseValue,B as parseWhereCondition,Et as securityMapToFlareRules};
|
package/package.json
CHANGED