@zuzjs/flare 0.2.4 → 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 CHANGED
@@ -1,58 +1,221 @@
1
- # 🔥 ZuzFlare Client
1
+ # ZuzFlare Client
2
2
 
3
- > Official JavaScript/TypeScript client for ZuzFlare Server
3
+ Official JavaScript/TypeScript client for ZuzFlare Server.
4
4
 
5
5
  [![npm version](https://badge.fury.io/js/%40zuzjs%2Fflare.svg)](https://www.npmjs.com/package/@zuzjs/flare)
6
6
  [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
7
7
 
8
- Real-time database client with Firebase-like API for your self-hosted ZuzFlare server.
9
-
10
- ## 📦 Installation
8
+ ## Installation
11
9
 
12
10
  ```bash
13
11
  npm install @zuzjs/flare
14
12
  ```
15
13
 
16
- ## 🚀 Quick Start
14
+ ## Maintainer Rule
17
15
 
18
- ```typescript
19
- import { FlareClient } from '@zuzjs/flare';
16
+ When adding or changing any public SDK API, update this README in the same commit and add a usage example for that API.
20
17
 
21
- const flare = new FlareClient({
22
- endpoint: 'http://localhost:5050',
23
- appId: 'my-app'
24
- });
18
+ ## Quick Start
25
19
 
26
- flare.connect();
20
+ ```ts
21
+ import { connectApp } from '@zuzjs/flare';
27
22
 
28
- // Write data
29
- await flare.collection('users').doc('alice').set({
23
+ const app = connectApp({
24
+ endpoint: 'https://flare.zuzcdn.net',
25
+ appId: 'my-app',
26
+ apiKey: 'app-api-key',
27
+ });
28
+
29
+ await app.collection('users').doc('alice').set({
30
30
  name: 'Alice',
31
- email: 'alice@example.com'
31
+ email: 'alice@example.com',
32
32
  });
33
33
 
34
- // Real-time updates
35
- flare.collection('users').onSnapshot((data) => {
36
- console.log('Users:', data);
34
+ app.collection('users').onSnapshot((snapshot) => {
35
+ console.log('snapshot', snapshot);
37
36
  });
38
37
  ```
39
38
 
40
- ## 📖 Full Documentation
39
+ ## Public API Usage Examples
40
+
41
+ ### Core Instance
42
+
43
+ ```ts
44
+ import { connectApp, getFlare, disconnectFlare } from '@zuzjs/flare';
45
+
46
+ const app = connectApp({ endpoint: 'https://flare.zuzcdn.net', appId: 'my-app', apiKey: 'ak' });
47
+ const same = getFlare();
48
+ disconnectFlare();
49
+ ```
50
+
51
+ ### Auth Config And State
52
+
53
+ ```ts
54
+ const app = connectApp({ endpoint: 'https://flare.zuzcdn.net', appId: 'my-app', apiKey: 'ak' });
55
+
56
+ await app.ensureCsrfProtection();
57
+ const config = await app.loadAuthConfig();
58
+
59
+ const offConfig = app.onAuthConfigLoaded((next) => {
60
+ console.log('auth config loaded', next.providers);
61
+ });
62
+
63
+ const offState = app.onAuthStateChanged((session) => {
64
+ console.log('auth state', session?.uid);
65
+ });
66
+
67
+ const legacyOffState = app.onAuthStateChange((session) => {
68
+ console.log('legacy listener', session?.uid);
69
+ });
70
+
71
+ console.log('csrf cookie name', app.getCsrfCookieName());
72
+ console.log('csrf token', app.getCsrfToken());
73
+ console.log('current user', app.getCurrentUser());
74
+
75
+ offConfig();
76
+ offState();
77
+ legacyOffState();
78
+ ```
79
+
80
+ ### Email Password Auth
81
+
82
+ ```ts
83
+ const app = connectApp({ endpoint: 'https://flare.zuzcdn.net', appId: 'my-app', apiKey: 'ak' });
84
+
85
+ await app.createUserWithEmail('alice@example.com', 'StrongPassword123!');
86
+ await app.createUserWithEmailAndPassword('bob@example.com', 'StrongPassword123!');
87
+
88
+ await app.signInWithEmail('alice@example.com', 'StrongPassword123!');
89
+ await app.signInWithEmailAndPassword('bob@example.com', 'StrongPassword123!');
90
+
91
+ await app.signInOrCreateWithEmail('carol@example.com', 'StrongPassword123!');
92
+ await app.signInOrCreateWithEmailAndPassword('dave@example.com', 'StrongPassword123!');
93
+
94
+ await app.auth('<access-token>');
95
+ await app.refreshAuthSession();
96
+ await app.signOut();
97
+ ```
98
+
99
+ ### Email Verification And Recovery
100
+
101
+ ```ts
102
+ const app = connectApp({ endpoint: 'https://flare.zuzcdn.net', appId: 'my-app', apiKey: 'ak' });
103
+
104
+ const verifySent = await app.sendEmailVerification('alice@example.com');
105
+ await app.verifyEmailWithCode('alice@example.com', '123456');
106
+ await app.confirmEmailLink('<link-token>', 'alice@example.com');
107
+
108
+ const recoverySent = await app.sendAccountRecovery('alice@example.com');
109
+ await app.recoverAccountWithCode('alice@example.com', '123456', 'NextStrongPassword123!');
110
+ await app.recoverAccountWithToken('<recovery-token>', 'NextStrongPassword123!');
111
+
112
+ console.log(verifySent, recoverySent);
113
+ ```
41
114
 
42
- See [complete documentation](https://flare.zuz.com.pk) for:
43
- - API Reference
44
- - Usage Examples
45
- - TypeScript Types
46
- - React/Vue/Svelte Integration
47
- - Authentication
48
- - Offline Support
115
+ ### OAuth Helpers
116
+
117
+ ```ts
118
+ const app = connectApp({ endpoint: 'https://flare.zuzcdn.net', appId: 'my-app', apiKey: 'ak' });
119
+
120
+ await app.signIn('google');
121
+ await app.signInWithGoogle();
122
+ await app.signInWithGitHub();
123
+ await app.signInWithFacebook();
124
+ await app.signInWithDropbox();
125
+
126
+ const redirectResult = await app.handleSignInRedirect();
127
+ console.log('oauth redirect result', redirectResult);
128
+ ```
129
+
130
+ ### SSR Token
131
+
132
+ ```ts
133
+ const app = connectApp({ endpoint: 'https://flare.zuzcdn.net', appId: 'my-app', apiKey: 'ak' });
134
+
135
+ const ssr = await app.issueSsrToken(120);
136
+ console.log(ssr.token, ssr.expires_in);
137
+ ```
138
+
139
+ ### Push APIs
140
+
141
+ ```ts
142
+ const app = connectApp({ endpoint: 'https://flare.zuzcdn.net', appId: 'my-app', apiKey: 'ak' });
143
+
144
+ await app.setupPushServiceWorker();
145
+ await app.requestPushPermission();
146
+
147
+ const { token } = await app.acquireBrowserPushToken();
148
+ await app.registerPushToken({ token, platform: 'web', topics: ['news'] });
149
+
150
+ await app.enableBrowserPush({ topics: ['marketing'] });
151
+
152
+ await app.sendPushNotification({
153
+ title: 'Hello',
154
+ body: 'Welcome back',
155
+ topic: 'news',
156
+ });
157
+
158
+ await app.unregisterPushToken(token);
159
+ ```
160
+
161
+ ### Template-Based Email APIs
162
+
163
+ Emails are sent only through app-level templates stored in `_flare_email_templates`.
164
+
165
+ Template placeholders use `{key}` syntax and are replaced from `values`.
166
+
167
+ If template has `includeVerificationLink: true`, server generates a link in `_flare_email_links` and injects:
168
+
169
+ - `{verificationLink}`
170
+ - `{verifyUrl}`
171
+ - `{verificationToken}`
172
+
173
+ ```ts
174
+ const app = connectApp({ endpoint: 'https://flare.zuzcdn.net', appId: 'my-app', apiKey: 'ak' });
175
+
176
+ const sendRes = await app.sendEmail({
177
+ to: 'alice@example.com',
178
+ tag: 'team_invite',
179
+ values: {
180
+ displayName: 'Alice',
181
+ inviterName: 'Bob',
182
+ teamName: 'Product',
183
+ },
184
+ });
185
+
186
+ console.log(sendRes.sent, sendRes.tag, sendRes.verifyUrl);
187
+
188
+ const verifyRes = await app.verifyEmailLink({
189
+ token: '<token-from-link>',
190
+ tag: 'team_invite',
191
+ email: 'alice@example.com',
192
+ });
193
+
194
+ console.log(verifyRes.verified, verifyRes.tag);
195
+ ```
196
+
197
+ ## Template Collection Example
198
+
199
+ Example document in `_flare_email_templates`:
200
+
201
+ ```json
202
+ {
203
+ "tag": "team_invite",
204
+ "enabled": true,
205
+ "subject": "Hi {displayName}, you are invited to {teamName}",
206
+ "text": "Hello {displayName},\n\n{inviterName} invited you.\n\nOpen: {verificationLink}",
207
+ "html": "<p>Hello {displayName}</p><p>{inviterName} invited you.</p><p><a href=\"{verificationLink}\">Accept</a></p>",
208
+ "includeVerificationLink": true,
209
+ "verifyUrl": "https://app.example.com/accept?token=__TOKEN__&appId=__APP_ID__&tag=__TAG__",
210
+ "verificationTtlHours": 72
211
+ }
212
+ ```
49
213
 
50
- ## 🔗 Links
214
+ ## Links
51
215
 
52
- - [Server Package](@zuzjs/flare-server)
53
- - [GitHub](https://github.com/zuzjs/flare-client)
54
- - [Documentation](https://flare.zuz.com.pk)
216
+ - Server package: @zuzjs/flare-server
217
+ - Documentation: https://flare.zuz.com.pk
55
218
 
56
- ## 📄 License
219
+ ## License
57
220
 
58
- MIT © Zuz.js Team
221
+ MIT
package/dist/index.cjs CHANGED
@@ -1,3 +1,3 @@
1
1
  'use strict';Object.defineProperty(exports,'__esModule',{value:true});var auth=require('@zuzjs/auth'),core=require('@zuzjs/core');/* ZuzFlare Client */
2
- var g=class extends Error{constructor(t,i,r){super(t);this.code=i;this.cause=r;this.name="ZuzFlareError";}};var Z={AuthenticationFailed:"AUTHENTICATION_FAILED",PermissionDenied:"PERMISSION_DENIED",WriteFailed:"WRITE_FAILED",QueryFailed:"QUERY_FAILED",ParseError:"PARSE_ERROR"},d=Z;var X=(c=>(c.SUBSCRIBE="subscribe",c.UNSUBSCRIBE="unsubscribe",c.WRITE="write",c.DELETE="delete",c.AUTH="auth",c.PING="ping",c.OFFLINE_SYNC="offline_sync",c.CALL="call",c.QUERY="query",c.PRESENCE_JOIN="presence_join",c.PRESENCE_LEAVE="presence_leave",c.PRESENCE_HEARTBEAT="presence_heartbeat",c))(X||{}),ee=(c=>(c.SNAPSHOT="snapshot",c.CHANGE="change",c.ERROR="error",c.ACK="ack",c.PONG="pong",c.AUTH_OK="auth_ok",c.OFFLINE_ACK="offline_ack",c.CALL_RESPONSE="call_response",c.QUERY_RESULT="query_result",c.PRESENCE_STATE="presence_state",c.PRESENCE_JOIN="presence_join",c.PRESENCE_LEAVE="presence_leave",c))(ee||{});function M(o){let e=[];for(let[t,i]of Object.entries(o))if(typeof i=="string"){let r=i.match(/^(>=|<=|!=|>|<|==)\s*(.+)$/);if(r){let[,n,s]=r;e.push({field:t,op:n,value:K(s.trim())});}else e.push({field:t,op:"==",value:i});}else Array.isArray(i)?e.push({field:t,op:"in",value:i}):e.push({field:t,op:"==",value:i});return e}function K(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 b=class{constructor(e,t,i){this.client=e;this.collection=t;this.legacyId=i;}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 g('Document ID not specified. Use .where({ id: "..." }) or doc(collection, id)',d.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=core.uuid2(18);return new Promise((i,r)=>{let n=this.client.subscribe(t,this.collection,e,void 0,s=>{s.type==="snapshot"&&(n(),i(s.data));});setTimeout(()=>{n(),r(new Error("Document fetch timeout"));},1e4);})}onSnapshot(e){let t=this.getDocId(),i=core.uuid2(18);return this.client.subscribe(i,this.collection,t,void 0,e)}};var Q=class{constructor(e,t,i){this.client=e;this.collection=t;this.id=i;}async get(){return new b(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=core.uuid2(18),i=()=>{};return i=this.client.subscribe(t,this.collection,this.id,void 0,r=>{r.type==="snapshot"&&(e(r),i());}),i}onDocUpdated(e){let t=core.uuid2(18);return this.client.subscribe(t,this.collection,this.id,void 0,i=>{i.type==="change"&&(i.operation==="update"||i.operation==="replace")&&i.data&&e(i.data,i.docId);},{skipSnapshot:true})}onDocModified(e){return this.onDocUpdated(e)}onDocChange(e){return this.onDocUpdated(e)}onDocDeleted(e){let t=core.uuid2(18);return this.client.subscribe(t,this.collection,this.id,void 0,i=>{i.type==="change"&&i.operation==="delete"&&e(i.docId);},{skipSnapshot:true})}onDocChanged(e){let t=core.uuid2(18);return this.client.subscribe(t,this.collection,this.id,void 0,i=>{i.type==="change"&&e(i.data??null,i.docId,i.operation);},{skipSnapshot:true})}},S=Q;var D=class o{constructor(e,t){this.client=e;this.collection=t;return new Proxy(this,{get:(i,r,n)=>{if(typeof r=="string"&&!(r in i)&&this.client.hasQueryPreset(r))return (a={})=>i.with(r,a);let s=Reflect.get(i,r,n);return typeof s=="function"?s.bind(i):s}})}sq={};promise;doc(e){return new S(this.client,this.collection,e)}clone(e){let t=new o(this.client,this.collection);return t.sq={...this.sq,...e},t}with(e,t={}){return this.client.applyQueryPreset(this,e,t)}where(e,t,i){let r;return typeof e=="string"?r=[{field:e,op:t,value:i}]:r=M(e),this.clone({where:[...this.sq.where??[],...r]})}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,i){return this.clone({having:[...this.sq.having??[],{field:e,op:t,value:i}]})}buildStructuredJoin(e,t){let r={from:String(e??""),localField:String(t?.source??""),foreignField:String(t?.target??""),as:String(t?.as??""),single:t?.single};return Array.isArray(t?.where)&&(r.where=t.where),Array.isArray(t?.orderBy)&&(r.orderBy=t.orderBy),typeof t?.limit=="number"&&(r.limit=t.limit),typeof t?.offset=="number"&&(r.offset=t.offset),t?.startAt&&(r.startAt=t.startAt),t?.startAfter&&(r.startAfter=t.startAfter),t?.endAt&&(r.endAt=t.endAt),t?.endBefore&&(r.endBefore=t.endBefore),Array.isArray(t?.aggregate)&&(r.aggregate=t.aggregate),t?.groupBy&&(r.groupBy=t.groupBy),Array.isArray(t?.having)&&(r.having=t.having),t?.vectorSearch&&(r.vectorSearch=t.vectorSearch),Array.isArray(t?.select)&&(r.select=t.select),typeof t?.distinctField=="string"&&(r.distinctField=t.distinctField),Array.isArray(t?.joins)&&(r.joins=t.joins.map(n=>this.buildStructuredJoin(String(n?.collection??""),n))),r}Join(e,t){let i=this.buildStructuredJoin(e,t);return this.clone({joins:[...this.sq.joins??[],i]})}join(e,t){if(typeof e=="string")return this.Join(e,t);let i=String(e.collection??e.from??""),r=this.buildStructuredJoin(i,e);return this.clone({joins:[...this.sq.joins??[],r]})}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=core.uuid2(18);return new Promise((t,i)=>{let r=Object.keys(this.sq).length>0?this.sq:void 0,n=this.client.subscribe(e,this.collection,void 0,r,s=>{s.type==="snapshot"&&(n(),t(s.data));});setTimeout(()=>{n(),i(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=core.uuid2(18),i=Object.keys(this.sq).length>0?this.sq:void 0,r=(()=>{});return r=this.client.subscribe(t,this.collection,void 0,i,n=>{n.type==="snapshot"&&(e(n),r());}),r}onDocAdded(e){let t=core.uuid2(18),i=Object.keys(this.sq).length>0?this.sq:void 0;return this.client.subscribe(t,this.collection,void 0,i,r=>{r.type==="change"&&r.operation==="insert"&&r.data!=null&&e(r.data,r.docId);},{skipSnapshot:true})}onDocUpdated(e){let t=core.uuid2(18),i=Object.keys(this.sq).length>0?this.sq:void 0;return this.client.subscribe(t,this.collection,void 0,i,r=>{r.type==="change"&&(r.operation==="update"||r.operation==="replace")&&r.data!=null&&e(r.data,r.docId);},{skipSnapshot:true})}onDocModified(e){return this.onDocUpdated(e)}onDocChange(e){return this.onDocUpdated(e)}onDocDeleted(e){let t=core.uuid2(18),i=Object.keys(this.sq).length>0?this.sq:void 0;return this.client.subscribe(t,this.collection,void 0,i,r=>{r.type==="change"&&r.operation==="delete"&&e(r.docId);},{skipSnapshot:true})}onDocChanged(e){let t=core.uuid2(18),i=Object.keys(this.sq).length>0?this.sq:void 0;return this.client.subscribe(t,this.collection,void 0,i,r=>{r.type==="change"&&e(r.data??null,r.docId,r.operation);},{skipSnapshot:true})}async add(e){let t=core.uuid2(18),i=this.doc(t);return await i.set(e),i}update(e){return new b(this.client,this.collection).update(e)}delete(){return new b(this.client,this.collection).delete()}},H=D;async function te(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"),i=new Uint8Array(t.length);for(let n=0;n<t.length;n++)i[n]=t.charCodeAt(n);return (globalThis.crypto??(await import('crypto')).webcrypto).subtle.importKey("spki",i.buffer,{name:"RSA-OAEP",hash:"SHA-256"},false,["encrypt"])}async function re(o,e){let t=await te(e),i=new TextEncoder().encode(JSON.stringify(o)),n=await(globalThis.crypto??(await import('crypto')).webcrypto).subtle.encrypt({name:"RSA-OAEP"},t,i),s=typeof btoa<"u"?btoa(String.fromCharCode(...new Uint8Array(n))):Buffer.from(n).toString("base64");return JSON.stringify({enc:"rsa",data:s})}var I=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=i=>{try{this.socket.send(i),this.log("Sent message",e);}catch(r){this.log("Send error",r),this.messageQueue.push(e);}};this.options.publicKey?re(e,this.options.publicKey).then(t).catch(i=>{this.log("RSA encrypt error \u2014 sending plaintext",i),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 ce={id:"_id",createdAt:"_createdAt",updatedAt:"_updatedAt"},W={_id:"id",_createdAt:"createdAt",_updatedAt:"updatedAt"},R=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,i){let r=e,n=typeof r?.error=="string"&&r.error.length>0?r.error:i,s=typeof r?.message=="string"&&r.message.length>0?r.message:t;throw new g(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((i,r)=>{t[r]=i;});else if(Array.isArray(e))for(let[i,r]of e)t[String(i)]=String(r);else for(let[i,r]of Object.entries(e))t[String(i)]=String(r);return t}redactHeaders(e){let t={...e};for(let i of Object.keys(t)){let r=i.toLowerCase();(r==="authorization"||r==="x-flare-csrf"||r==="x-csrf-token")&&(t[i]="[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(r=>this.stableStringify(r)).join(",")}]`;let t=e;return `{${Object.keys(t).sort().map(r=>`${r}:${this.stableStringify(t[r])}`).join(",")}}`}buildHttpCacheKey(e,t,i,r,n){let a=Object.entries(i).map(([l,p])=>[l.toLowerCase(),p]).sort(([l],[p])=>l.localeCompare(p)).map(([l,p])=>`${l}:${p}`).join("|"),u=this.stableStringify(r);return `${e}|${t}|${n??""}|${a}|${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 i=this.httpResponseCache.keys().next().value;i&&this.httpResponseCache.delete(i);}createTimedFetchTrace(e,t,i,r,n,s){return {response:{status:e.status,ok:e.status>=200&&e.status<300,headers:{get:a=>{let u=a.toLowerCase();for(let[l,p]of Object.entries(e.headers))if(l.toLowerCase()===u)return String(p);return null}},json:async()=>e.data??{}},requestId:t,startedAtMs:i,networkMs:s,method:r,url:n}}logHttpTiming(...e){this.requestTimingEnabled&&this.log("[FlareClient][http]",...e);}mergeHeaders(e,t){if(!e)return t;if(e instanceof Headers){let i=new Headers(e);for(let[r,n]of Object.entries(t))i.set(r,n);return i}return Array.isArray(e)?[...e,...Object.entries(t)]:{...e,...t}}toWireField(e){let t=String(e??"").trim();return t&&(ce[t]??t)}fromWireField(e){let t=String(e??"").trim();return t&&(W[t]?W[t]:t.startsWith("_")&&!t.startsWith("__")&&t.length>1?t.slice(1):t)}normalizeOutboundData(e){if(Array.isArray(e))return e.map(r=>this.normalizeOutboundData(r));if(!e||typeof e!="object")return e;let t=e,i={};for(let[r,n]of Object.entries(t))i[this.toWireField(r)]=this.normalizeOutboundData(n);return i}normalizeInboundData(e){if(Array.isArray(e))return e.map(r=>this.normalizeInboundData(r));if(!e||typeof e!="object")return e;let t=e,i={};for(let[r,n]of Object.entries(t))i[this.fromWireField(r)]=this.normalizeInboundData(n);return i}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,i={...t},r=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(a=>this.normalizeOutboundAnyFilter(a))),Array.isArray(n.orderBy)&&(s.orderBy=n.orderBy.map(a=>({...a,field:this.toWireField(String(a?.field??""))}))),n.groupBy&&typeof n.groupBy=="object"&&Array.isArray(n.groupBy.fields)&&(s.groupBy={...n.groupBy,fields:n.groupBy.fields.map(a=>this.toWireField(String(a??"")))}),Array.isArray(n.having)&&(s.having=n.having.map(a=>({...a,field:this.toWireField(String(a?.field??""))}))),Array.isArray(n.select)&&(s.select=n.select.map(a=>this.toWireField(String(a??"")))),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(a=>r(a))),s};return Array.isArray(t.where)&&(i.where=t.where.map(n=>this.normalizeOutboundAnyFilter(n))),Array.isArray(t.orderBy)&&(i.orderBy=t.orderBy.map(n=>({...n,field:this.toWireField(String(n?.field??""))}))),t.groupBy&&typeof t.groupBy=="object"&&Array.isArray(t.groupBy.fields)&&(i.groupBy={...t.groupBy,fields:t.groupBy.fields.map(n=>this.toWireField(String(n??"")))}),Array.isArray(t.having)&&(i.having=t.having.map(n=>({...n,field:this.toWireField(String(n?.field??""))}))),Array.isArray(t.select)&&(i.select=t.select.map(n=>this.toWireField(String(n??"")))),typeof t.distinctField=="string"&&(i.distinctField=this.toWireField(t.distinctField)),t.vectorSearch&&typeof t.vectorSearch=="object"&&(i.vectorSearch={...t.vectorSearch,field:this.toWireField(String(t.vectorSearch.field??""))}),Array.isArray(t.joins)&&(i.joins=t.joins.map(n=>r(n))),i}async timedFetch(e,t,i){let r=++this.requestTraceSeq,n=this.nowMs(),s=String(i?.method??"GET").toUpperCase(),a=this.normalizeHeaders(i?.headers),u=this.redactHeaders(a),l=i?.body,p=this.buildHttpCacheKey(s,t,a,l,i?.credentials),f=this.shouldCacheResponse(s,t);this.logHttpTiming(`#${r} ${e} start`,{method:s,url:t,headers:u,hasBody:!!i?.body});try{if(f){let k=this.httpResponseCache.get(p);if(k)return this.logHttpTiming(`#${r} ${e} cache-hit`,{method:s,url:t}),this.createTimedFetchTrace(k,r,n,s,t,0)}let c=this.httpInFlight.get(p);if(c){let k=await c,h=this.nowMs()-n;return this.logHttpTiming(`#${r} ${e} deduped`,{method:s,url:t,networkMs:Number(h.toFixed(2))}),this.createTimedFetchTrace(k,r,n,s,t,h)}let w=this.mergeHeaders(i?.headers,{"x-flare-request-id":String(r)}),T=this.normalizeHeaders(w),G=this.redactHeaders(T),A={timeout:Math.ceil((this.config.connectionTimeout??1e4)/1e3),ignoreKind:!0,headers:T,withCredentials:i?.credentials==="include",returnRawResponse:!0,appendCookiesToBody:!1,appendTimestamp:!1};this.logHttpTiming(`#${r} ${e} request`,{method:s,url:t,headers:G,hasBody:!!i?.body});let _=s.toUpperCase(),U=(async()=>{let k=_==="GET"?await core.withGet(t,A):_==="PUT"?await core.withPut(t,l,A):_==="PATCH"?await core.withPatch(t,l,A):await core.withPost(t,l,A),h={status:Number(k?.status??0),headers:Object.fromEntries(Object.entries(k?.headers??{}).map(([z,Y])=>[z,String(Y)])),data:k?.data??{}};return f&&this.rememberHttpResponse(p,h),h})();this.httpInFlight.set(p,U);let L=await U.finally(()=>{this.httpInFlight.delete(p);}),q=this.nowMs()-n;return this.logHttpTiming(`#${r} ${e} response`,{status:L.status,networkMs:Number(q.toFixed(2))}),this.createTimedFetchTrace(L,r,n,s,t,q)}catch(c){let w=this.nowMs()-n;throw this.logHttpTiming(`#${r} ${e} failed`,{networkMs:Number(w.toFixed(2)),message:c?.message??String(c)}),c}}async parseJsonWithTiming(e,t){let i=this.nowMs(),r=await t.response.json().catch(()=>({})),n=this.nowMs()-i,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))}),r}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:i,protocol:r}=new URL(this.config.endpoint),n=r==="https:",u=`${n?"wss":"ws"}://${t}:${i||(n?"443":"80")}/?appId=${this.config.appId}${this.config.apiKey?`&apiKey=${this.config.apiKey}`:""}`;this.transport=new I({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 H(this,e)}registerQueryPreset(e,t){let i=String(e??"").trim();if(!i)throw new g("Preset name is required",d.QueryFailed);if(typeof t!="function")throw new g(`Query preset "${i}" handler must be a function`,d.QueryFailed);return this.queryPresets.set(i,t),this}registerQueryPresets(e){for(let[t,i]of Object.entries(e??{}))this.registerQueryPreset(t,i);return this}hasQueryPreset(e){return this.queryPresets.has(String(e??"").trim())}applyQueryPreset(e,t,i={}){let r=String(t??"").trim(),n=this.queryPresets.get(r);if(!n)throw new g(`Unknown query preset "${r}"`,d.QueryFailed);let s=n(e,i??{});if(!s||typeof s.get!="function")throw new g(`Query preset "${r}" must return a CollectionReference`,d.QueryFailed);return s}doc(e,t){return t!==void 0?new S(this,e,t):new b(this,e)}async ping(){let e=Date.now();return await this.send("ping",{}),Date.now()-e}async call(e,t={}){let i=await this.send("call",{topic:e,payload:t});if(!i.success)throw new g(i.error??`CALL "${e}" failed`,d.QueryFailed);return i.result}async query(e,t={}){return (await this.send("query",{collection:e,query:t})).data??[]}setEmbedder(e){this.embedder=e;}markVectorField(e,t,i={dimensions:1536}){this.vectorSchema.has(e)||this.vectorSchema.set(e,new Map),this.vectorSchema.get(e).set(t,i);}async embedVectorFields(e,t){let i=this.vectorSchema.get(e);if(!i)return t;let r={...t};for(let[n,s]of i){let a=r[n];if(typeof a=="string"){let u=s.embed??this.embedder;if(!u){this.log(`[vector] No embedder for field "${n}" \u2014 storing raw text`);continue}r[n]=await u(a);}}return r}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 i=this.presenceCallbacks.get(e)??[];this.presenceCallbacks.set(e,i.filter(r=>r!==t));}}onPresenceJoin(e,t){return this.presenceJoinCbs.has(e)||this.presenceJoinCbs.set(e,[]),this.presenceJoinCbs.get(e).push(t),()=>{let i=this.presenceJoinCbs.get(e)??[];this.presenceJoinCbs.set(e,i.filter(r=>r!==t));}}onPresenceLeave(e,t){return this.presenceLeaveCbs.has(e)||this.presenceLeaveCbs.set(e,[]),this.presenceLeaveCbs.get(e).push(t),()=>{let i=this.presenceLeaveCbs.get(e)??[];this.presenceLeaveCbs.set(e,i.filter(r=>r!==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(i=>{let r=e.find(n=>n.id===i.operationId);r&&this.offlineQueue.push(r);}));}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 i=this.toSubscriptionError(t);this.emitSubscriptionError(e.baseId,i),this.log("Subscription failed",t);}}toSubscriptionError(e){let t=e instanceof Error?e.message:String(e??"Unknown subscription error"),i=t.match(/^\[([^\]]+)\]\s*(.*)$/),r=i?.[1],n=(i?.[2]??t).trim()||t,s=r===d.PermissionDenied||t.includes(d.PermissionDenied);return {code:r,message:n,permissionDenied:s,raw:e}}emitSubscriptionError(e,t){this.subscriptionLastErrors.set(e,t);let i=this.subscriptionErrorHandlers.get(e);if(i)for(let r of i)try{r(t);}catch(n){this.log("Subscription error callback failed",n);}if(t.permissionDenied){let r=this.subscriptionPermissionHandlers.get(e);if(r)for(let n of r)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 i=t.liveId;this.subscriptions.delete(i),t.liveId=t.baseId,i&&await this.send("unsubscribe",{subscriptionId:i}).catch(()=>{}),await this.activateSubscription(t);}}).catch(t=>{this.pendingSubscriptionReplay=true,this.log("Subscription replay failed",t);}),await this.subscriptionReplayPromise;}subscribe(e,t,i,r,n,s={}){this.log("Creating subscription",e,t,i);let a={baseId:e,liveId:e,collection:t,docId:i,query:r,callback:n,options:s};this.activeSubscriptions.set(e,a),this.subscriptionErrorHandlers.has(e)||this.subscriptionErrorHandlers.set(e,new Set),this.subscriptionPermissionHandlers.has(e)||this.subscriptionPermissionHandlers.set(e,new Set),this.activateSubscription(a).catch(p=>{this.log("Subscription activation failed",p);});let u=()=>{let f=this.activeSubscriptions.get(e)?.liveId??e;this.log("Unsubscribing",f),this.activeSubscriptions.delete(e),this.subscriptions.delete(f),this.subscriptionErrorHandlers.delete(e),this.subscriptionPermissionHandlers.delete(e),this.subscriptionLastErrors.delete(e),this.isConnected&&this.send("unsubscribe",{subscriptionId:f}).catch(c=>this.log("Unsubscribe failed",c));},l=u;return l.unsubscribe=u,l.onError=p=>{this.subscriptionErrorHandlers.get(e)?.add(p);let f=this.subscriptionLastErrors.get(e);if(f)try{p(f);}catch(c){this.log("Subscription error callback failed",c);}return l},l.onPermissionDenied=p=>{this.subscriptionPermissionHandlers.get(e)?.add(p);let f=this.subscriptionLastErrors.get(e);if(f?.permissionDenied)try{p(f);}catch(c){this.log("Subscription permission callback failed",c);}return l},l.catch=p=>l.onError(p),l}async send(e,t){if(e==="write"&&t.collection&&t.data){let i=await this.embedVectorFields(t.collection,t.data);t={...t,data:this.normalizeOutboundData(i)};}return (e==="subscribe"||e==="query")&&t?.query&&(t={...t,query:this.normalizeOutboundQuery(t.query)}),new Promise((i,r)=>{let n=core.uuid2(18),s={id:n,type:e,ts:Date.now(),...t};this.pendingAcks.set(n,a=>{a.type==="error"?r(new Error(`[${a.code}] ${a.message}`)):i(a);}),this.isConnected?this.transport.send(s):(this.log("Queueing message for offline",s),this.offlineQueue.push(s),r(new Error("Not connected - message queued"))),setTimeout(()=>{this.pendingAcks.has(n)&&(this.pendingAcks.delete(n),r(new Error("Request timeout")));},this.config.connectionTimeout);})}handleTransportError(e){this.log("Transport error",e),this.errorListeners.forEach(t=>{try{t(e);}catch(i){this.log("Error listener error",i);}});}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(i){this.log("Connection listener error",i);}}));}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(r=>{try{r(t);}catch(n){this.log("Error listener error",n);}});let i=Array.from(this.activeSubscriptions.values()).find(r=>r.liveId===e.correlationId||r.baseId===e.correlationId);if(i&&this.emitSubscriptionError(i.baseId,{code:typeof e.code=="string"?e.code:void 0,message:String(e.message??"Subscription error"),permissionDenied:e.code===d.PermissionDenied,raw:e}),e.correlationId){let r=this.pendingAcks.get(e.correlationId);r&&(r(e),this.pendingAcks.delete(e.correlationId));}return}if(e.type==="presence_state"){(this.presenceCallbacks.get(e.room)??[]).forEach(i=>{try{i(e.members);}catch{}});return}if(e.type==="presence_join"){(this.presenceJoinCbs.get(e.room)??[]).forEach(i=>{try{i(e);}catch{}});return}if(e.type==="presence_leave"){(this.presenceLeaveCbs.get(e.room)??[]).forEach(i=>{try{i(e.uid);}catch{}});return}if(e.type==="snapshot"){let t=this.subscriptions.get(e.subscriptionId);if(t){let i=this.normalizeInboundData(Array.isArray(e.data)?e.data:e.data!=null?[e.data]:[]),r={type:"snapshot",subscriptionId:e.subscriptionId,collection:e.collection,data:Array.isArray(i)?i:[]};try{t(r);}catch(n){this.log("Subscription callback error",n);}}return}if(e.type==="change"){let t=this.subscriptions.get(e.subscriptionId);if(t){let i={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(i);}catch(r){this.log("Subscription callback error",r);}}}}};var x=class extends R{authToken;userId;authGuard;authConfig;csrfToken;csrfInitPromise;csrfBootstrapAttempted=false;socketAuthSyncPromise;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(r=>r.trim()).find(r=>r.startsWith(`${e}=`)||r.startsWith(`${encodeURIComponent(e)}=`));if(!t)return null;let i=t.indexOf("=");return i>=0?decodeURIComponent(t.slice(i+1)):null}extractCsrfToken(e,t){let i=e,r=typeof i?.csrfToken=="string"?String(i.csrfToken):typeof i?.csrf_token=="string"?String(i.csrf_token):void 0;if(r)return r;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 i=`${e}/auth/config?${t.toString()}`,r=await this.timedFetch("loadAuthConfig",i,{credentials:"include",headers:this.config.apiKey?{"x-flare-api-key":this.config.apiKey}:{}}),n=await this.parseJsonWithTiming("loadAuthConfig",r);return r.response.ok||this.throwFetchFlareError(n,"Failed to load auth config",d.QueryFailed),this.authConfig=n,this.csrfToken=this.extractCsrfToken(n,r.response)??this.csrfToken,this.authConfigListeners.forEach(s=>{try{s(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);}}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(i=>{try{i(t);}catch(r){this.log("Auth state listener error",r);}});}onAuthStateChanged(e){this.authStateListeners.push(e);let t=this.authSession?{...this.authSession,...this.currentProfile??{}}:null;try{e(t);}catch(i){this.log("Auth state listener error during initialization",i);}return ()=>{this.authStateListeners=this.authStateListeners.filter(i=>i!==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 g("Socket auth sync failed",d.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 i=typeof e=="string"&&e.length>0?e:"anon",r=i!==this.socketAuthUid;this.socketAuthUid=i,(r||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(i=>{throw this.log("Socket auth sync failed before subscribe",i),i}).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,i=typeof e.uid=="string"?e.uid:void 0;this.updateSocketIdentity(i,this.pendingSubscriptionReplay).catch(r=>{this.log("Socket identity update failed",r);}),t&&i&&i!=="anon"&&i!=="__admin__"?this.fetchAuthMe(t).then(r=>{this.setAuthSession({uid:i,accessToken:t,refreshToken:this.authSession?.refreshToken??null,email:r?.email??null,emailVerified:r?.email_verified});}).catch(()=>{this.setAuthSession({uid:i,accessToken:t,refreshToken:this.authSession?.refreshToken??null});}):i==="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 i=t.token??e;this.authToken=i,this.userId=t.uid;let r=await this.fetchAuthMe(i).catch(()=>null);return this.setAuthSession({uid:t.uid??t.id,accessToken:i,refreshToken:this.authSession?.refreshToken??null,email:r?.email??null,emailVerified:r?.email_verified}),await this.updateSocketIdentity(t.uid),this.log("Authentication successful",t.uid),{uid:t.uid,token:t.token??e}}throw new g("Authentication failed",d.AuthenticationFailed)}async signInWithEmailAndPassword(e,t,i){try{let r=await this.requestEmailPasswordToken(e,t,i?.scope),n=await this.auth(r.access_token),s=await this.fetchAuthMe(r.access_token).catch(()=>null);return this.setAuthSession({uid:n.uid,accessToken:r.access_token,refreshToken:r.refresh_token,provider:r.provider,email:s?.email??e,emailVerified:s?.email_verified}),this.log("Credentials sign-in successful",n.uid),{...n,kind:r.kind,accessToken:r.access_token,refreshToken:r.refresh_token,authToken:r}}catch(r){let n=/invalid_email|user.not.found|no user/i.test(r?.message??"");if(i?.createIfMissing&&n){let s=await this.createUserWithEmail(e,t,{scope:i.scope,signInIfAllowed:true});if("verificationRequired"in s&&s.verificationRequired)throw new g("Email verification required before sign-in",d.AuthenticationFailed);return {uid:s.uid,token:s.token,accessToken:s.accessToken,refreshToken:s.refreshToken,authToken:s.authToken,created:true}}throw r instanceof g?r:new g(r instanceof Error?r.message:"Sign-in with email/password failed",r.error??r.code??d.AuthenticationFailed,r)}}async signInWithEmail(e,t,i){return this.signInWithEmailAndPassword(e,t,i)}async createUserWithEmail(e,t,i){let r=await this.registerWithEmail(e,t,i);if(r.verification_required)return {kind:r.kind,verificationRequired:true,emailSent:!!r.email_sent,preview:r.preview};let n=String(r.access_token??"");if(!n)throw new g("User created but no access token returned",d.AuthenticationFailed);let s={access_token:n,refresh_token:r.refresh_token?String(r.refresh_token):null,expires_in:r.expires_in?Number(r.expires_in):null,token_type:String(r.token_type??"Bearer"),scope:r.scope?String(r.scope):null,profile:null,provider:"credentials"},a=await this.auth(n),u=await this.fetchAuthMe(n).catch(()=>null);return this.setAuthSession({uid:a.uid,accessToken:n,refreshToken:s.refresh_token,provider:"credentials",email:u?.email??e,emailVerified:u?.email_verified}),{...a,accessToken:n,refreshToken:s.refresh_token,authToken:s,verificationRequired:false,emailSent:!!r.email_sent,preview:r.preview}}async createUserWithEmailAndPassword(e,t,i){return this.createUserWithEmail(e,t,i)}async signInOrCreateWithEmail(e,t,i){try{return {...await this.signInWithEmailAndPassword(e,t,{scope:i?.scope}),created:!1}}catch(r){if(!/invalid_email|user.not.found|no user/i.test(r?.message??""))throw r;let s=await this.createUserWithEmail(e,t,{scope:i?.scope,additionalParams:i?.additionalParams,signInIfAllowed:true});return "verificationRequired"in s&&s.verificationRequired?{...s,created:true}:{...s,created:true}}}async signInOrCreateWithEmailAndPassword(e,t,i){return this.signInOrCreateWithEmail(e,t,i)}async sendEmailVerification(e){let t=this.getHttpBase();await this.ensureCsrfProtection();let i=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})}),r=await this.parseJsonWithTiming("sendEmailVerification",i);return i.response.ok||this.throwFetchFlareError(r,"Failed to send verification email",d.AuthenticationFailed),r}async verifyEmailWithCode(e,t){let i=this.getHttpBase();await this.ensureCsrfProtection();let r=await this.timedFetch("verifyEmailWithCode",`${i}/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",r);return r.response.ok||this.throwFetchFlareError(n,"Email verification failed",d.AuthenticationFailed),n}async confirmEmailLink(e,t){let i=this.getHttpBase();await this.ensureCsrfProtection();let r=await this.timedFetch("confirmEmailLink",`${i}/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",r);return r.response.ok||this.throwFetchFlareError(n,"Email link verification failed",d.AuthenticationFailed),n}async sendAccountRecovery(e){let t=this.getHttpBase();await this.ensureCsrfProtection();let i=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})}),r=await this.parseJsonWithTiming("sendAccountRecovery",i);return i.response.ok||this.throwFetchFlareError(r,"Failed to send recovery email",d.AuthenticationFailed),r}async recoverAccountWithCode(e,t,i){let r=this.getHttpBase();await this.ensureCsrfProtection();let n=await this.timedFetch("recoverAccountWithCode",`${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({email:e,code:t,newPassword:i,appId:this.config.appId,apiKey:this.config.apiKey})}),s=await this.parseJsonWithTiming("recoverAccountWithCode",n);return n.response.ok||this.throwFetchFlareError(s,"Account recovery failed",d.AuthenticationFailed),s}async recoverAccountWithToken(e,t){let i=this.getHttpBase();await this.ensureCsrfProtection();let r=await this.timedFetch("recoverAccountWithToken",`${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({token:e,newPassword:t,appId:this.config.appId,apiKey:this.config.apiKey})}),n=await this.parseJsonWithTiming("recoverAccountWithToken",r);return r.response.ok||this.throwFetchFlareError(n,"Account recovery failed",d.AuthenticationFailed),n}async signIn(e,t,i){let r=typeof e?.signIn=="function",n=r?e:await this.getAuthGuard(),s=r?t:e,a=r?i:t;return n.signIn(s,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 i=typeof e?.handleRedirect=="function",r=i?e:await this.getAuthGuard(),n=i?t:typeof e=="boolean"?e:false,s=await r.handleRedirect(n);if(!s||!s.access_token||!s.provider)return null;let a=await this.exchangeProviderToken(s.provider,s.access_token),u=await this.auth(a.token),l=await this.fetchAuthMe(a.token).catch(()=>null);return this.setAuthSession({uid:u.uid,accessToken:a.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 i=`${this.getHttpBase()}/auth/exchange`;await this.ensureCsrfProtection();let r=await this.timedFetch("exchangeProviderToken",i,{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",r);if(r.response.ok||this.throwFetchFlareError(n,"OAuth token exchange failed",d.AuthenticationFailed),!n?.token)throw new g("OAuth token exchange failed",d.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 g("Authentication is disabled for this app",d.AuthenticationFailed);let t=this.getHttpBase(),i=`${t}/auth/oauth/token?appId=${encodeURIComponent(this.config.appId)}`,r=[],n=(s,a)=>({...a,token_url:i,tokenParams:{...a.tokenParams??{},provider:s}});if(e.providers.credentials?.enabled&&r.push({...auth.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&&r.push({...auth.Anonymous({clientId:this.config.apiKey}),token_url:`${t}/auth/token?appId=${encodeURIComponent(this.config.appId)}`}),e.providers.google?.enabled&&e.providers.google.clientId&&r.push(n("google",auth.Google({clientId:e.providers.google.clientId,scopes:e.providers.google.scopes}))),e.providers.github?.enabled&&e.providers.github.clientId&&r.push(n("github",auth.GitHub({clientId:e.providers.github.clientId,scopes:e.providers.github.scopes}))),e.providers.facebook?.enabled&&e.providers.facebook.clientId&&r.push(n("facebook",auth.Facebook({clientId:e.providers.facebook.clientId,scopes:e.providers.facebook.scopes}))),e.providers.dropbox?.enabled&&e.providers.dropbox.clientId&&r.push(n("dropbox",auth.Dropbox({clientId:e.providers.dropbox.clientId,scopes:e.providers.dropbox.scopes}))),e.providers.apple?.enabled&&e.providers.apple.clientId&&r.push(n("apple",auth.Apple({clientId:e.providers.apple.clientId,scopes:e.providers.apple.scopes}))),e.providers.twitter?.enabled&&e.providers.twitter.clientId&&r.push(n("twitter",auth.Twitter({clientId:e.providers.twitter.clientId,scopes:e.providers.twitter.scopes}))),r.length===0)throw new g("No authentication providers are enabled for this app",d.AuthenticationFailed);return this.authGuard=new auth.AuthGuard({providers:r,redirectUri:e.redirectUri}),this.authGuard}async refreshAuthSession(e){let t=this.getHttpBase();await this.ensureCsrfProtection();let i=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}:{}})}),r=await this.parseJsonWithTiming("refreshAuthSession",i);if(!i.response.ok){if(i.response.status===401)return this.setAuthSession(null),await this.syncSocketAuth(null).catch(()=>{}),null;this.throwFetchFlareError(r,"Failed to refresh auth session",d.AuthenticationFailed);}let n=String(r.access_token??"");if(!n)throw new g("Refresh succeeded but no access token was returned",d.ParseError);let s=await this.fetchAuthMe(n).catch(()=>null),a={uid:String(s?.id??this.authSession?.uid??this.userId??""),accessToken:n,refreshToken:r.refresh_token?String(r.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(a),await this.syncSocketAuth(n).catch(()=>{}),a}async issueSsrToken(e=120){let t=this.getHttpBase();await this.ensureCsrfProtection();let i=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})}),r=await this.parseJsonWithTiming("issueSsrToken",i);i.response.ok||this.throwFetchFlareError(r,"Failed to mint SSR token",d.AuthenticationFailed);let n=String(r.token??"");if(!n)throw new g("SSR token response is missing token",d.ParseError,r);return {token:n,token_type:String(r.token_type??"Bearer"),expires_in:Number(r.expires_in??0),uid:String(r.uid??""),role:String(r.role??"user"),...typeof r.email=="string"?{email:r.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,i){let r=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),i?.scope?.length&&n.set("scope",i.scope.join(" ")),i?.additionalParams&&n.set("additional_params",JSON.stringify(i.additionalParams));let s=await this.timedFetch("registerWithEmail",`${r}/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()}),a=await this.parseJsonWithTiming("registerWithEmail",s);return !s.response.ok&&s.response.status!==202&&this.throwFetchFlareError(a,"User creation failed",d.WriteFailed),a}async requestEmailPasswordToken(e,t,i){let r=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),i?.length&&n.set("scope",i.join(" "));let s=await this.timedFetch("requestEmailPasswordToken",`${r}/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()}),a=await this.parseJsonWithTiming("requestEmailPasswordToken",s);return s.response.ok||this.throwFetchFlareError(a,"Sign-in with email/password failed",d.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(),i=new URLSearchParams({appId:this.config.appId});this.config.apiKey&&i.set("apiKey",this.config.apiKey);let r=`${t}/auth/me?${i.toString()}`,n=await this.timedFetch("fetchAuthMe",r,{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",d.QueryFailed),s}};var O=class extends x{constructor(e){super(e),this.log("FlareClient initialized",e);}},N=O;function B(o){return `__flare_csrf_${o.replace(/[^a-zA-Z0-9_-]/g,"_")}`}function ke(o){return `__flare_csrf_${o.replace(/[^a-zA-Z0-9_-]/g,"_")}`}function E(o,e){let t=e.toLowerCase();for(let[i,r]of Object.entries(o??{}))if(i.toLowerCase()===t&&typeof r=="string")return r}function Ce(o){let e=E(o,"set-cookie");if(typeof e=="string"&&e.length>0)return [e];for(let[t,i]of Object.entries(o??{}))if(t.toLowerCase()==="set-cookie"&&Array.isArray(i))return i.filter(r=>typeof r=="string");return []}function Te(o,e){for(let t of o){let i=t.split(";").map(u=>u.trim()),[r]=i;if(!r)continue;let n=r.indexOf("=");if(n<=0)continue;let s=decodeURIComponent(r.slice(0,n)),a=r.slice(n+1);if(s===e)return decodeURIComponent(a)}}async function Se(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 core.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 j(o){let e=await Se(o),t=e?.data,i=e?.headers??{},r=E(i,"x-flare-csrf")??E(i,"x-csrf-token")??E(i,"csrf-token");if(typeof r=="string"&&r.length>0)return {csrfToken:r,...t};let n=t?.cookie?.csrfTokenName,s=n&&n.length>0?n:ke(o.appId),a=Ce(i),u=Te(a,s);if(typeof u=="string"&&u.length>0)return {csrfToken:u,...t}}function J(o,e,t){return `${encodeURIComponent(o)}=${encodeURIComponent(e)}; HttpOnly; SameSite=Strict; Path=/; Max-Age=${t}`}function Pe(o){let e=o.proxyCookieName??B(o.appId),t=o.proxyCookieMaxAge??3600;return async function(r){let n=await j(o),s=n?.csrfToken,a=new Headers({"Content-Type":"application/json"});return s&&a.set("Set-Cookie",J(e,s,t)),new Response(JSON.stringify({csrfToken:s??null,...n}),{status:200,headers:a})}}function we(o){let e=o.proxyCookieName??B(o.appId),t=o.proxyCookieMaxAge??3600;return async function(r,n){if(r.method!=="GET"&&r.method!=="HEAD"){n.status(405).json({error:"Method not allowed"});return}let a=(await j(o))?.csrfToken;a&&n.setHeader("Set-Cookie",J(e,a,t)),n.status(200).json({csrfToken:a??null});}}function Ae(o,e,t){let i=t??B(e);if(o instanceof Request){let s=(o.headers.get("cookie")??"").split(";").map(u=>u.trim()).find(u=>u.startsWith(`${encodeURIComponent(i)}=`)||u.startsWith(`${i}=`));if(!s)return null;let a=s.indexOf("=");return a>=0?decodeURIComponent(s.slice(a+1)):null}let{cookies:r}=o;return typeof r?.get=="function"?r.get(i)?.value??null:r&&typeof r=="object"?r[i]??null:null}function ve(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=o=>o==="guest"?"auth == null":o==="auth"?"auth != null":"true",Re=(o,e)=>{let t=String(e??"").trim();return t?o==="true"?t:`(${o}) && (${t})`:o},xe=o=>{let e=String(o??"").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:V(t[1]),condition:t[2].trim()};let i=e.match(/^(auth != null|auth == null|true)\s*&&\s*(.+)$/);return i?{auth:V(i[1]),condition:i[2].trim()}:{auth:"any",condition:e}},V=o=>{let e=String(o??"").trim();return e==="auth == null"?"guest":e==="auth != null"?"auth":"any"},It=o=>{let e={};for(let t of o){let i=String(t.collection||"").trim();if(!i)continue;let r=i==="any"?"*":i,n=Re(Ie(t.auth),t.condition);e[r]={".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},Rt=o=>Object.entries(o).map(([e,t],i)=>{let r=t?.[".read"],n=t?.[".create"],s=t?.[".update"],a=t?.[".delete"],u=t?.[".write"],l=[];typeof r=="string"&&r.trim()!=="false"&&l.push("read");let p=typeof n=="string"&&n.trim()!=="false"||typeof u=="string"&&u.trim()!=="false",f=typeof s=="string"&&s.trim()!=="false"||typeof u=="string"&&u.trim()!=="false",c=typeof a=="string"&&a.trim()!=="false"||typeof u=="string"&&u.trim()!=="false";p&&l.push("create"),f&&l.push("update"),c&&l.push("delete");let T=xe(r||n||s||a||u);return {id:`${e}-${i}`,name:e==="*"?"All Collections":e,auth:T.auth,collection:e==="*"?"any":e,condition:T.condition,permissions:l}});var Ee=(f=>(f.authEmailNotVerified="auth/email-not-verified",f.authEmailAlreadyVerified="auth/email-already-verified",f.authInvalidToken="auth/invalid-token",f.authUserDisabled="auth/user-disabled",f.authUserNotFound="auth/user-not-found",f.authWrongPassword="auth/wrong-password",f.authEmailAlreadyInUse="auth/email-already-in-use",f.authInvalidEmail="auth/invalid-email",f.authWeakPassword="auth/weak-password",f.authTooManyRequests="auth/too-many-requests",f.authInternalError="auth/internal-error",f))(Ee||{});var Fe=(h=>(h.health="health",h.authConfig="auth_config",h.authRegistration="auth/registration",h.authRegistrationVerificationRequired="auth/registration-verification-required",h.authSession="auth/session",h.authExchange="auth/exchange",h.authLogout="auth/logout",h.authSsrBridge="auth/ssr_bridge",h.authSsrVerify="auth/ssr_verify",h.accountRecovery="account/recovery",h.emailVerification="email/verification",h.verificationDispatch="verification/dispatch",h.authProfile="auth/profile",h.adminToken="admin/token",h.documentDelete="document/delete",h.documentsDelete="documents/delete",h.documents="documents",h.document="document",h.documentCreate="document/create",h.documentUpdate="document/update",h.oauthProviderResponse="oauth_provider_response",h.success="success",h.response="response",h))(Fe||{});var m=null,P=null,F=null,_e=o=>JSON.stringify({endpoint:o.endpoint,appId:o.appId,apiKey:o.apiKey,publicKey:o.publicKey,autoReconnect:o.autoReconnect,reconnectDelay:o.reconnectDelay,maxReconnectDelay:o.maxReconnectDelay}),Ht=o=>{let e=_e(o);if(m&&F!==e&&(m.disconnect(),m=null,P=null,F=null),!m){m=new N(o),F=e;let t=typeof window<"u"&&typeof document<"u",i=typeof process<"u"&&typeof process.env?.NEXT_RUNTIME=="string";(t||!i)&&m.connect(),P=new Proxy(m,{get(r,n,s){if(n==="onAuthStateChange")return r.onAuthStateChanged.bind(r);if(n==="onAuthConfigLoaded")return r.onAuthConfigLoaded.bind(r);let a=Reflect.get(r,n,s);return typeof a=="function"?a.bind(r):a}});}return P??m},Ot=()=>P??m,Nt=()=>{m&&(m.disconnect(),m=null,P=null,F=null);},Bt=N;
3
- Object.defineProperty(exports,"Anonymous",{enumerable:true,get:function(){return auth.Anonymous}});Object.defineProperty(exports,"Apple",{enumerable:true,get:function(){return auth.Apple}});Object.defineProperty(exports,"AuthGuard",{enumerable:true,get:function(){return auth.AuthGuard}});Object.defineProperty(exports,"Credentials",{enumerable:true,get:function(){return auth.Credentials}});Object.defineProperty(exports,"Dropbox",{enumerable:true,get:function(){return auth.Dropbox}});Object.defineProperty(exports,"Facebook",{enumerable:true,get:function(){return auth.Facebook}});Object.defineProperty(exports,"GitHub",{enumerable:true,get:function(){return auth.GitHub}});Object.defineProperty(exports,"Google",{enumerable:true,get:function(){return auth.Google}});Object.defineProperty(exports,"Providers",{enumerable:true,get:function(){return auth.Providers}});Object.defineProperty(exports,"Twitter",{enumerable:true,get:function(){return auth.Twitter}});Object.defineProperty(exports,"setupProvider",{enumerable:true,get:function(){return auth.setupProvider}});exports.CollectionReference=H;exports.DocumentQueryBuilder=b;exports.DocumentReference=S;exports.FlareAction=X;exports.FlareError=g;exports.FlareErrors=Ee;exports.FlareEvent=ee;exports.FlareResponseCodes=Fe;exports.buildFlareHeaders=ve;exports.connectApp=Ht;exports.createCsrfProxy=Pe;exports.createCsrfProxyHandler=we;exports.default=Bt;exports.disconnectFlare=Nt;exports.extractCsrfFromRequest=Ae;exports.flareRulesToSecurityMap=It;exports.getFlare=Ot;exports.parseValue=K;exports.parseWhereCondition=M;exports.securityMapToFlareRules=Rt;
2
+ var h=class extends Error{constructor(t,r,i){super(t);this.code=r;this.cause=i;this.name="ZuzFlareError";}};var Z={AuthenticationFailed:"AUTHENTICATION_FAILED",PermissionDenied:"PERMISSION_DENIED",WriteFailed:"WRITE_FAILED",QueryFailed:"QUERY_FAILED",ParseError:"PARSE_ERROR"},c=Z;var X=(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))(X||{}),ee=(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))(ee||{});function M(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:K(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 K(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 b=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=core.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=core.uuid2(18);return this.client.subscribe(r,this.collection,t,void 0,e)}};var B=class{constructor(e,t,r){this.client=e;this.collection=t;this.id=r;}async get(){return new b(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=core.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=core.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=core.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=core.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})}},C=B;var Q=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 C(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=M(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=core.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=core.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=core.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=core.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=core.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=core.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=core.uuid2(18),r=this.doc(t);return await r.set(e),r}update(e){return new b(this.client,this.collection).update(e)}delete(){return new b(this.client,this.collection).delete()}},N=Q;async function te(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 ie(a,e){let t=await te(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 A=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?ie(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 ce={id:"_id",createdAt:"_createdAt",updatedAt:"_updatedAt"},q={_id:"id",_createdAt:"createdAt",_updatedAt:"updatedAt"},R=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&&(ce[t]??t)}fromWireField(e){let t=String(e??"").trim();return t&&(q[t]?q[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 k=this.httpResponseCache.get(f);if(k)return this.logHttpTiming(`#${i} ${e} cache-hit`,{method:s,url:t}),this.createTimedFetchTrace(k,i,n,s,t,0)}let d=this.httpInFlight.get(f);if(d){let k=await d,p=this.nowMs()-n;return this.logHttpTiming(`#${i} ${e} deduped`,{method:s,url:t,networkMs:Number(p.toFixed(2))}),this.createTimedFetchTrace(k,i,n,s,t,p)}let P=this.mergeHeaders(r?.headers,{"x-flare-request-id":String(i)}),T=this.normalizeHeaders(P),z=this.redactHeaders(T),I={timeout:Math.ceil((this.config.connectionTimeout??1e4)/1e3),ignoreKind:!0,headers:T,withCredentials:r?.credentials==="include",returnRawResponse:!0,appendCookiesToBody:!1,appendTimestamp:!1};this.logHttpTiming(`#${i} ${e} request`,{method:s,url:t,headers:z,hasBody:!!r?.body});let _=s.toUpperCase(),U=(async()=>{let k=_==="GET"?await core.withGet(t,I):_==="PUT"?await core.withPut(t,l,I):_==="PATCH"?await core.withPatch(t,l,I):await core.withPost(t,l,I),p={status:Number(k?.status??0),headers:Object.fromEntries(Object.entries(k?.headers??{}).map(([G,Y])=>[G,String(Y)])),data:k?.data??{}};return g&&this.rememberHttpResponse(f,p),p})();this.httpInFlight.set(f,U);let W=await U.finally(()=>{this.httpInFlight.delete(f);}),L=this.nowMs()-n;return this.logHttpTiming(`#${i} ${e} response`,{status:W.status,networkMs:Number(L.toFixed(2))}),this.createTimedFetchTrace(W,i,n,s,t,L)}catch(d){let P=this.nowMs()-n;throw this.logHttpTiming(`#${i} ${e} failed`,{networkMs:Number(P.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 A({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 N(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 C(this,e,t):new b(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=core.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 E=class extends R{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({...auth.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({...auth.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",auth.Google({clientId:e.providers.google.clientId,scopes:e.providers.google.scopes}))),e.providers.github?.enabled&&e.providers.github.clientId&&i.push(n("github",auth.GitHub({clientId:e.providers.github.clientId,scopes:e.providers.github.scopes}))),e.providers.facebook?.enabled&&e.providers.facebook.clientId&&i.push(n("facebook",auth.Facebook({clientId:e.providers.facebook.clientId,scopes:e.providers.facebook.scopes}))),e.providers.dropbox?.enabled&&e.providers.dropbox.clientId&&i.push(n("dropbox",auth.Dropbox({clientId:e.providers.dropbox.clientId,scopes:e.providers.dropbox.scopes}))),e.providers.apple?.enabled&&e.providers.apple.clientId&&i.push(n("apple",auth.Apple({clientId:e.providers.apple.clientId,scopes:e.providers.apple.scopes}))),e.providers.twitter?.enabled&&e.providers.twitter.clientId&&i.push(n("twitter",auth.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 auth.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 O=class extends E{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]});}},H=O;function D(a){return `__flare_csrf_${a.replace(/[^a-zA-Z0-9_-]/g,"_")}`}function ke(a){return `__flare_csrf_${a.replace(/[^a-zA-Z0-9_-]/g,"_")}`}function x(a,e){let t=e.toLowerCase();for(let[r,i]of Object.entries(a??{}))if(r.toLowerCase()===t&&typeof i=="string")return i}function Se(a){let e=x(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 Te(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 Ce(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 core.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 Ce(a),t=e?.data,r=e?.headers??{},i=x(r,"x-flare-csrf")??x(r,"x-csrf-token")??x(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:ke(a.appId),o=Se(r),u=Te(o,s);if(typeof u=="string"&&u.length>0)return {csrfToken:u,...t}}function J(a,e,t){return `${encodeURIComponent(a)}=${encodeURIComponent(e)}; HttpOnly; SameSite=Strict; Path=/; Max-Age=${t}`}function we(a){let e=a.proxyCookieName??D(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",J(e,s,t)),new Response(JSON.stringify({csrfToken:s??null,...n}),{status:200,headers:o})}}function Pe(a){let e=a.proxyCookieName??D(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",J(e,o,t)),n.status(200).json({csrfToken:o??null});}}function Ie(a,e,t){let r=t??D(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 ve(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 Ae=a=>a==="guest"?"auth == null":a==="auth"?"auth != null":"true",Re=(a,e)=>{let t=String(e??"").trim();return t?a==="true"?t:`(${a}) && (${t})`:a},Ee=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:V(t[1]),condition:t[2].trim()};let r=e.match(/^(auth != null|auth == null|true)\s*&&\s*(.+)$/);return r?{auth:V(r[1]),condition:r[2].trim()}:{auth:"any",condition:e}},V=a=>{let e=String(a??"").trim();return e==="auth == null"?"guest":e==="auth != null"?"auth":"any"},At=a=>{let e={};for(let t of a){let r=String(t.collection||"").trim();if(!r)continue;let i=r==="any"?"*":r,n=Re(Ae(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},Rt=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 T=Ee(i||n||s||o||u);return {id:`${e}-${r}`,name:e==="*"?"All Collections":e,auth:T.auth,collection:e==="*"?"any":e,condition:T.condition,permissions:l}});var xe=(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))(xe||{});var Fe=(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))(Fe||{});var m=null,w=null,F=null,_e=a=>JSON.stringify({endpoint:a.endpoint,appId:a.appId,apiKey:a.apiKey,publicKey:a.publicKey,autoReconnect:a.autoReconnect,reconnectDelay:a.reconnectDelay,maxReconnectDelay:a.maxReconnectDelay}),Nt=a=>{let e=_e(a);if(m&&F!==e&&(m.disconnect(),m=null,w=null,F=null),!m){m=new H(a),F=e;let t=typeof window<"u"&&typeof document<"u",r=typeof process<"u"&&typeof process.env?.NEXT_RUNTIME=="string";(t||!r)&&m.connect(),t&&m.setupPushServiceWorker().catch(()=>{}),w=new Proxy(m,{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 w??m},Ot=()=>w??m,Ht=()=>{m&&(m.disconnect(),m=null,w=null,F=null);},Dt=H;
3
+ Object.defineProperty(exports,"Anonymous",{enumerable:true,get:function(){return auth.Anonymous}});Object.defineProperty(exports,"Apple",{enumerable:true,get:function(){return auth.Apple}});Object.defineProperty(exports,"AuthGuard",{enumerable:true,get:function(){return auth.AuthGuard}});Object.defineProperty(exports,"Credentials",{enumerable:true,get:function(){return auth.Credentials}});Object.defineProperty(exports,"Dropbox",{enumerable:true,get:function(){return auth.Dropbox}});Object.defineProperty(exports,"Facebook",{enumerable:true,get:function(){return auth.Facebook}});Object.defineProperty(exports,"GitHub",{enumerable:true,get:function(){return auth.GitHub}});Object.defineProperty(exports,"Google",{enumerable:true,get:function(){return auth.Google}});Object.defineProperty(exports,"Providers",{enumerable:true,get:function(){return auth.Providers}});Object.defineProperty(exports,"Twitter",{enumerable:true,get:function(){return auth.Twitter}});Object.defineProperty(exports,"setupProvider",{enumerable:true,get:function(){return auth.setupProvider}});exports.CollectionReference=N;exports.DocumentQueryBuilder=b;exports.DocumentReference=C;exports.FlareAction=X;exports.FlareError=h;exports.FlareErrors=xe;exports.FlareEvent=ee;exports.FlareResponseCodes=Fe;exports.buildFlareHeaders=ve;exports.connectApp=Nt;exports.createCsrfProxy=we;exports.createCsrfProxyHandler=Pe;exports.default=Dt;exports.disconnectFlare=Ht;exports.extractCsrfFromRequest=Ie;exports.flareRulesToSecurityMap=At;exports.getFlare=Ot;exports.parseValue=K;exports.parseWhereCondition=M;exports.securityMapToFlareRules=Rt;