var f1=Object.defineProperty;var h1=(Z)=>Z;function d1(Z,G){this[Z]=h1.bind(null,G)}var c1=(Z,G)=>{for(var J in G)f1(Z,J,{get:G[J],enumerable:!0,configurable:!0,set:d1.bind(G,J)})};var j1=(Z,G)=>()=>(Z&&(G=Z(Z=0)),G);var q1=()=>{};var R1={};c1(R1,{wrapPublicKey:()=>y,unwrapPublicKey:()=>l1,sign:()=>U1,generateKeyPair:()=>D1,browserFingerprint:()=>f});function i1(Z,G){let J=new Uint8Array(Z.length+G.length);return J.set(Z),J.set(G,Z.length),J}function k(Z){let G="";for(let J=0;J<Z.length;J++)G+=String.fromCharCode(Z[J]);return btoa(G)}function V1(Z){let G=atob(Z),J=new Uint8Array(G.length);for(let $=0;$<G.length;$++)J[$]=G.charCodeAt($);return J}function p1(Z){return Array.from(Z).map((G)=>G.toString(16).padStart(2,"0")).join("")}function y(Z){return i1(N1,Z)}function l1(Z){return Z.slice(N1.length)}async function D1(){let Z=(void 0).randomSecretKey(),G=await(void 0)(Z),J=y(G),$=await f(k(J));return{publicKeyBase64:k(J),privateKeyBase64:k(Z),fingerprint:$}}async function U1(Z,G){let J=V1(G),$=new TextEncoder().encode(Z),z=await(void 0)($,J);return k(z)}async function f(Z){let G=V1(Z),J=new ArrayBuffer(G.byteLength);new Uint8Array(J).set(G);let $=await crypto.subtle.digest("SHA-256",J);return p1(new Uint8Array($))}var N1,AZ;var h=j1(()=>{q1();N1=new Uint8Array([48,42,48,5,6,3,43,101,112,3,33,0]),AZ=new Uint8Array([48,46,2,1,0,48,5,6,3,43,101,112,4,34,4,32])});var x=1;function M1(Z){let G=Z.lastIndexOf("/");return G>=0?Z.slice(G+1):Z}function d(Z){let G="";for(let J=0;J<Z.length;J++)G+=String.fromCharCode(Z[J]);return btoa(G)}function o1(Z){let G=atob(Z),J=new Uint8Array(G.length);for(let $=0;$<G.length;$++)J[$]=G.charCodeAt($);return J}function r1(){if(typeof window<"u"&&window.location)return`${window.location.protocol==="https:"?"wss":"ws"}://${window.location.host}/db`;let Z=globalThis.process;if(Z?.env?.BODDB_URL)return Z.env.BODDB_URL.replace(/^http/,"ws");return"ws://localhost:4460"}class c{url=r1();auth;keyAuth;autoAuth;reconnect=!0;reconnectInterval=1000;maxReconnectInterval=30000;requestTimeout=30000;onVersionMismatch;offlineQueue=!1;offlineQueueCap=100}class _{options;ws=null;msgId=0;pending=new Map;valueCbs=new Map;childCbs=new Map;activeSubs=new Set;streamCbs=new Map;activeStreamSubs=new Set;vfsDownloadCbs=new Map;closed=!1;_browserAuth=null;reconnectTimer=null;reconnectDelay;connectPromise=null;_authToken=null;_deviceFingerprint=null;_welcomeListeners=new Set;_pendingWelcome=null;_authComplete=!1;_offlineQueue=[];_rec=null;_recCap=5000;serverInfo=null;onOfflineQueue;onOfflineFlush;auth;constructor(Z){if(this.options={...new c,...Z},this.reconnectDelay=this.options.reconnectInterval,this.auth=new i(this),typeof localStorage<"u")try{let G=localStorage.getItem("BOD_WS_RECORD");if(G){let J=Number(G);this._recCap=Number.isFinite(J)&&J>0?J:5000,this._rec=[]}}catch{}}_recPush(Z,G,J=!1){if(!this._rec)return;if(this._rec.push(J?{t:Date.now(),dir:Z,data:G,parseError:J}:{t:Date.now(),dir:Z,data:G}),this._rec.length>this._recCap)this._rec.splice(0,this._rec.length-this._recCap)}startRecording(Z=5000){this._recCap=Z,this._rec=this._rec??[]}stopRecording(){let Z=this._rec??[];return this._rec=null,Z}getRecording(){return this._rec??[]}clearRecording(){if(this._rec)this._rec.length=0}dumpRecording(Z="array"){let G=this.getRecording();return Z==="json"?JSON.stringify(G,null,2):G}onWelcome(Z){return this._welcomeListeners.add(Z),()=>{this._welcomeListeners.delete(Z)}}get deviceFingerprint(){return this._deviceFingerprint}get authToken(){return this._authToken}async connect(){if(this.ws?.readyState===WebSocket.OPEN)return;if(this.connectPromise)return this.connectPromise;return this.closed=!1,this.connectPromise=new Promise((Z,G)=>{let J=new WebSocket(this.options.url);J.onopen=async()=>{this._recPush("open",{url:this.options.url}),this.ws=J,this.reconnectDelay=this.options.reconnectInterval,this.onStatusChange?.(!0);try{if(await this.onConnect?.(),this.options.autoAuth&&!this.options.keyAuth){let $=await this._ensureDeviceKeys();this.options.keyAuth={publicKey:$.publicKey,signFn:$.signFn},await this.send("auth-register-device",{publicKey:$.publicKey,displayName:typeof this.options.autoAuth==="object"?this.options.autoAuth.displayName:void 0})}if(this.options.keyAuth){if(this._authToken)try{await this.send("auth",{token:this._authToken})}catch{this._authToken=null}if(!this._authToken){let $=await this.send("auth-challenge",{}),z=await this.options.keyAuth.signFn($.nonce),H=await this.send("auth-verify",{publicKey:this.options.keyAuth.publicKey,signature:z,nonce:$.nonce});this._authToken=H.token}}else if(this.options.auth){let $=await this.options.auth();if($)await this.send("auth",{token:$})}if(this._authComplete=!0,this._pendingWelcome){this.serverInfo=this._pendingWelcome;for(let $ of this._welcomeListeners)$(this.serverInfo);this._pendingWelcome=null}if(this.activeSubs.size>0){let $=[...this.activeSubs].map((z)=>{let H=z.indexOf(":"),X=z.slice(0,H),Y=z.slice(H+1),L=X.endsWith("-shallow"),T=L?X.slice(0,-8):X;return{path:Y,event:T,...L?{shallow:!0}:{}}});try{await this.send("batch-sub",{subscriptions:$})}catch{for(let z of $)await this.send("sub",z)}}for(let $ of this.activeStreamSubs){let[z,H]=this.splitStreamKey($);await this.send("stream-sub",{path:z,groupId:H})}await this._flushOfflineQueue(),this.connectPromise=null,Z()}catch($){this.connectPromise=null,G($)}},J.onmessage=($)=>{let z;try{z=JSON.parse(typeof $.data==="string"?$.data:$.data.toString()),this._recPush("recv",z)}catch(X){throw this._recPush("recv",$.data,!0),X}if(z.type==="welcome"){let X={protocolVersion:z.protocolVersion,serverVersion:z.serverVersion};if(this._authComplete){this.serverInfo=X;for(let Y of this._welcomeListeners)Y(this.serverInfo)}else this._pendingWelcome=X;if(z.protocolVersion!==x)console.warn(`[BodClient] Protocol mismatch: client=${x} server=${z.protocolVersion} (v${z.serverVersion})`),this.options.onVersionMismatch?.({clientProtocol:x,serverProtocol:z.protocolVersion,serverVersion:z.serverVersion});return}if(z.type==="value"){let X=new B(z.path,z.data,z.updatedAt),Y=this.valueCbs.get(z.path);if(Y)for(let T of Y)T(X);let L=this.valueCbs.get(`${z.path}\x00shallow`);if(L)for(let T of L)T(X);return}if(z.type==="stream"){let X=`${z.path}:${z.groupId}`,Y=this.streamCbs.get(X);if(Y)for(let L of Y)L(z.events);return}if(z.type==="child"){let X={type:z.event,key:z.key,path:z.path+"/"+z.key,val:()=>z.data},Y=this.childCbs.get(z.path);if(Y)for(let T of Y)T(X);let L=this.childCbs.get(`${z.path}\x00shallow`);if(L)for(let T of L)T(X);return}if(z.type==="vfs-download-chunk"){let X=this.vfsDownloadCbs.get(z.transferId);if(X)for(let Y of X)Y(z);return}let H=this.pending.get(z.id);if(H)if(this.pending.delete(z.id),z.ok)H.resolve(z);else H.reject(Error(z.error||"Unknown error"))},J.onclose=($)=>{this._recPush("close",{code:$?.code,reason:$?.reason}),this.ws=null,this.serverInfo=null,this._pendingWelcome=null,this._authComplete=!1,this.onStatusChange?.(!1);for(let[,z]of this.pending)z.reject(Error("Connection closed"));if(this.pending.clear(),!this.closed&&this.options.reconnect)this.scheduleReconnect();if(this.connectPromise)this.connectPromise=null,G(Error(`WebSocket connection failed (${this.options.url})`))},J.onerror=()=>{this._recPush("error","ws error")}}),this.connectPromise}disconnect(){if(this.closed=!0,this.reconnectTimer)clearTimeout(this.reconnectTimer),this.reconnectTimer=null;this.ws?.close(),this.ws=null,this.pending.clear();for(let Z of this._offlineQueue)Z.reject(Error("Client disconnected"));this._offlineQueue=[]}scheduleReconnect(){if(this.closed)return;this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=null,this.connect().catch(()=>{this.reconnectDelay=Math.min(this.reconnectDelay*2,this.options.maxReconnectInterval)})},this.reconnectDelay)}_enqueueWrite(Z,G){return new Promise((J,$)=>{let z=this._writeDedupKey(Z,G);if(z){let H=this._offlineQueue.findIndex((X)=>X.dedupKey===z);if(H!==-1)this._offlineQueue[H].resolve({ok:!0,data:null}),this._offlineQueue.splice(H,1)}if(this._offlineQueue.length>=this.options.offlineQueueCap)this._offlineQueue.shift().reject(Error("Offline queue full — dropped"));this._offlineQueue.push({op:Z,params:G,resolve:J,reject:$,dedupKey:z}),this.onOfflineQueue?.(this._offlineQueue.length)})}_writeDedupKey(Z,G){if(Z==="push"||Z==="batch")return null;if(Z==="update"&&G.updates)return null;let J=G.path;if(!J)return null;return`${Z}:${J}`}async _flushOfflineQueue(){if(this._offlineQueue.length===0)return;let Z=this._offlineQueue.splice(0);this.onOfflineFlush?.(Z.length);for(let G of Z)try{let J=await this.sendRaw(G.op,G.params);G.resolve(J)}catch(J){G.reject(J instanceof Error?J:Error(String(J)))}}nextId(){return String(++this.msgId)}async sendRaw(Z,G={},J=!1){if(J&&this.options.offlineQueue&&(!this.ws||this.ws.readyState!==WebSocket.OPEN)&&!this.closed)return this._enqueueWrite(Z,G);if(!this.ws||this.ws.readyState!==WebSocket.OPEN)await this.connect();return new Promise(($,z)=>{if(!this.ws||this.ws.readyState!==WebSocket.OPEN)return z(Error("Not connected"));let H=this.nextId(),X=null,Y=()=>{if(X)clearTimeout(X),X=null};if(this.pending.set(H,{resolve:(L)=>{Y(),$(L)},reject:(L)=>{Y(),z(L)}}),this.options.requestTimeout>0)X=setTimeout(()=>{this.pending.delete(H),z(Error(`Request timeout after ${this.options.requestTimeout}ms (op=${Z}${G.path?` path=${String(G.path)}`:""})`))},this.options.requestTimeout);this._recPush("send",{id:H,op:Z,...G}),this.ws.send(JSON.stringify({id:H,op:Z,...G}))})}async send(Z,G={},J=!1){return(await this.sendRaw(Z,G,J)).data??null}async get(Z){return this.send("get",{path:Z})}async getSnapshot(Z){let G=await this.sendRaw("get",{path:Z});return new B(Z,G.data??null,G.updatedAt)}async getShallow(Z,G,J,$){return this.send("get",{path:Z??"",shallow:!0,...G!==void 0?{limit:G}:{},...J!==void 0?{offset:J}:{},...$?.values===!1?{values:!1}:{}})}async stats(Z){return this.send("stats",{path:Z})}async statsChildren(Z){return this.send("stats-children",{path:Z})}async set(Z,G,J){await this.send("set",{path:Z,value:G,...J?.ttl?{ttl:J.ttl}:{},...J?.flatten!==void 0?{flatten:J.flatten}:{}},!0)}async update(Z,G,J){await this.send("update",{path:Z,value:G,...J?.ttl?{ttl:J.ttl}:{},...J?.flatten!==void 0?{flatten:J.flatten}:{}},!0)}async updateMulti(Z){await this.send("update",{updates:Z},!0)}async delete(Z){await this.send("delete",{path:Z},!0)}async batch(Z){return this.send("batch",{operations:Z},!0)}async push(Z,G,J){return this.send("push",{path:Z,value:G,idempotencyKey:J?.idempotencyKey,ttl:J?.ttl},!0)}query(Z){return new l(this,Z)}_query(Z,G,J,$,z){return this.send("query",{path:Z,filters:G,order:J,limit:$,offset:z})}on(Z,G,J){let $=!(J?.deep??!1),z=`value${$?"-shallow":""}:${Z}`,H=$?`${Z}\x00shallow`:Z;if(!this.valueCbs.has(H))this.valueCbs.set(H,new Set);if(this.valueCbs.get(H).add(G),!this.activeSubs.has(z)){if(this.activeSubs.add(z),this.ws?.readyState===WebSocket.OPEN)this.send("sub",{path:Z,event:"value",...$?{shallow:!0}:{}}).catch(()=>{})}return()=>{if(this.valueCbs.get(H)?.delete(G),this.valueCbs.get(H)?.size===0){if(this.valueCbs.delete(H),this.activeSubs.delete(z),this.ws?.readyState===WebSocket.OPEN)this.send("unsub",{path:Z,event:"value",...$?{shallow:!0}:{}}).catch(()=>{})}}}onChild(Z,G,J){let $=!(J?.deep??!1),z=J?.values===!1,H=`child${$?"-shallow":""}${z?"-novalues":""}:${Z}`,X=$?`${Z}\x00shallow`:Z;if(!this.childCbs.has(X))this.childCbs.set(X,new Set);if(this.childCbs.get(X).add(G),!this.activeSubs.has(H)){if(this.activeSubs.add(H),this.ws?.readyState===WebSocket.OPEN)this.send("sub",{path:Z,event:"child",...$?{shallow:!0}:{},...z?{values:!1}:{}}).catch(()=>{})}return()=>{if(this.childCbs.get(X)?.delete(G),this.childCbs.get(X)?.size===0){if(this.childCbs.delete(X),this.activeSubs.delete(H),this.ws?.readyState===WebSocket.OPEN)this.send("unsub",{path:Z,event:"child",...$?{shallow:!0}:{},...z?{values:!1}:{}}).catch(()=>{})}}}mq(Z){return new r(this,Z)}_mqSend(Z,G){return this.send(Z,G)}stream(Z,G){return new p(this,Z,G)}_streamOn(Z,G,J){let $=`${Z}:${G}`;if(!this.streamCbs.has($))this.streamCbs.set($,new Set);if(this.streamCbs.get($).add(J),!this.activeStreamSubs.has($)){if(this.activeStreamSubs.add($),this.ws?.readyState===WebSocket.OPEN)this.send("stream-sub",{path:Z,groupId:G}).catch(()=>{})}return()=>{if(this.streamCbs.get($)?.delete(J),this.streamCbs.get($)?.size===0){if(this.streamCbs.delete($),this.activeStreamSubs.delete($),this.ws?.readyState===WebSocket.OPEN)this.send("stream-unsub",{path:Z,groupId:G}).catch(()=>{})}}}_streamRead(Z,G,J){return this.send("stream-read",{path:Z,groupId:G,limit:J})}_streamAck(Z,G,J){return this.send("stream-ack",{path:Z,groupId:G,key:J})}splitStreamKey(Z){let G=Z.lastIndexOf(":");return[Z.slice(0,G),Z.slice(G+1)]}async search(Z){return this.send("fts-search",Z)}async index(Z,G){let J={path:Z};if(Array.isArray(G))J.fields=G;else J.content=G;await this.send("fts-index",J)}async vectorSearch(Z){return this.send("vector-search",Z)}async vectorStore(Z,G){await this.send("vector-store",{path:Z,embedding:G})}async streamSnapshot(Z){return this.send("stream-snapshot",{path:Z})}async streamMaterialize(Z,G){return this.send("stream-materialize",{path:Z,...G})}async streamCompact(Z,G){return this.send("stream-compact",{path:Z,...G})}async streamReset(Z){await this.send("stream-reset",{path:Z})}get connected(){return this.ws?.readyState===WebSocket.OPEN}onStatusChange;onConnect;onDisconnect(Z){return new S1(this,Z)}reconnect(){this.closed=!1,this.connect()}_sendRaw(Z,G={}){return this.sendRaw(Z,G)}get httpUrl(){return this.options.url.replace(/^ws(s?):\/\//,"http$1://")}vfs(){return new o(this)}_send(Z,G={}){return this.send(Z,G)}_onDownloadChunk(Z,G){if(!this.vfsDownloadCbs.has(Z))this.vfsDownloadCbs.set(Z,new Set);return this.vfsDownloadCbs.get(Z).add(G),()=>{if(this.vfsDownloadCbs.get(Z)?.delete(G),this.vfsDownloadCbs.get(Z)?.size===0)this.vfsDownloadCbs.delete(Z)}}async _ensureDeviceKeys(){this._browserAuth??=await Promise.resolve().then(() => (h(),R1));let Z=this._browserAuth,G=this._getStorage(),J=G.get("boddb-device-pubkey");if(J){let z=G.get("boddb-device-privkey");return this._deviceFingerprint=G.get("boddb-device-fp")??null,{publicKey:J,signFn:(H)=>Z.sign(H,z)}}let $=await Z.generateKeyPair();return G.set("boddb-device-pubkey",$.publicKeyBase64),G.set("boddb-device-privkey",$.privateKeyBase64),G.set("boddb-device-fp",$.fingerprint),this._deviceFingerprint=$.fingerprint,{publicKey:$.publicKeyBase64,signFn:(z)=>Z.sign(z,$.privateKeyBase64)}}_getStorage(){if(typeof this.options.autoAuth==="object"&&this.options.autoAuth.storage)return this.options.autoAuth.storage;if(typeof localStorage<"u")return{get:(Z)=>localStorage.getItem(Z),set:(Z,G)=>localStorage.setItem(Z,G),remove:(Z)=>localStorage.removeItem(Z)};if(!this._memStorage)this._memStorage=new Map;return{get:(Z)=>this._memStorage.get(Z)??null,set:(Z,G)=>this._memStorage.set(Z,G),remove:(Z)=>this._memStorage.delete(Z)}}_memStorage=null}class i{client;constructor(Z){this.client=Z}async registerDevice(Z,G){return this.client._send("auth-register-device",{publicKey:Z,displayName:G})}async authenticate(Z,G){let J=await this.client._send("auth-challenge",{}),$=await G(J.nonce);return this.client._send("auth-verify",{publicKey:Z,signature:$,nonce:J.nonce})}async linkDevice(Z,G,J,$){return this.client._send("auth-link-device",{accountFingerprint:Z,password:G,devicePublicKey:J,deviceName:$})}async linkDeviceByName(Z,G,J,$){return this.client._send("auth-link-device",{displayName:Z,password:G,devicePublicKey:J,deviceName:$})}async revokeSession(Z){await this.client._send("auth-revoke-session",{sid:Z})}async revokeDevice(Z,G){await this.client._send("auth-revoke-device",{accountFingerprint:Z,deviceFingerprint:G})}async changePassword(Z,G,J){await this.client._send("auth-change-password",{fingerprint:Z,oldPassword:G,newPassword:J})}async createAccount(Z,G,J,$){return this.client._send("auth-create-account",{password:Z,roles:G,displayName:J,devicePublicKey:$})}async createRole(Z){await this.client._send("auth-create-role",{role:Z})}async deleteRole(Z){await this.client._send("auth-delete-role",{roleId:Z})}async updateRoles(Z,G){await this.client._send("auth-update-roles",{accountFingerprint:Z,roles:G})}async listAccounts(){return this.client._send("auth-list-accounts",{})}async listRoles(){return this.client._send("auth-list-roles",{})}async listDevices(Z){return this.client._send("auth-list-devices",{accountFingerprint:Z})}async listSessions(Z){return this.client._send("auth-list-sessions",{accountFingerprint:Z})}async requestApproval(Z){return this.client._send("auth-request-approval",{publicKey:Z})}async approveDevice(Z){return this.client._send("auth-approve-device",{requestId:Z})}async listAccountFingerprints(){return this.client._send("auth-list-account-fingerprints",{})}async hasAccounts(){return(await this.client._send("auth-has-accounts",{})).hasAccounts}async getAccountInfo(Z){return this.client._send("auth-account-info",{accountFingerprint:Z})}async pollApproval(Z){return this.client._send("auth-poll-approval",{requestId:Z})}}class B{path;data;updatedAt;constructor(Z,G,J){this.path=Z;this.data=G;this.updatedAt=J}val(){return this.data}get key(){return M1(this.path)}exists(){return this.data!==null&&this.data!==void 0}}class p{client;path;groupId;constructor(Z,G,J){this.client=Z;this.path=G;this.groupId=J}on(Z){return this.client._streamOn(this.path,this.groupId,(G)=>{Z(G.map((J)=>({key:J.key,val:()=>J.data})))})}async read(Z){return(await this.client._streamRead(this.path,this.groupId,Z)).map((J)=>({key:J.key,val:()=>J.data}))}async ack(Z){return this.client._streamAck(this.path,this.groupId,Z)}}class l{client;basePath;filters=[];orderClause;limitVal;offsetVal;constructor(Z,G){this.client=Z;this.basePath=G}where(Z,G,J){return this.filters.push({field:Z,op:G,value:J}),this}order(Z,G="asc"){return this.orderClause={field:Z,dir:G},this}limit(Z){return this.limitVal=Z,this}offset(Z){return this.offsetVal=Z,this}get(){return this.client._query(this.basePath,this.filters.length?this.filters:void 0,this.orderClause,this.limitVal,this.offsetVal)}}class I{key;path;deliveryCount;status;data;constructor(Z,G,J,$,z){this.key=Z;this.path=G;this.deliveryCount=J;this.status=$;this.data=z}val(){return this.data}exists(){return this.data!==null&&this.data!==void 0}}class o{client;constructor(Z){this.client=Z}async upload(Z,G,J){let $=`${this.client.httpUrl}/files/${Z}`,H=await(await fetch($,{method:"POST",body:new Blob([G]),headers:{"Content-Type":J||"application/octet-stream"}})).json();if(!H.ok)throw Error(H.error||"Upload failed");return H.data}async download(Z){let G=`${this.client.httpUrl}/files/${Z}`,J=await fetch(G);if(!J.ok)throw Error("Download failed");return new Uint8Array(await J.arrayBuffer())}async uploadWS(Z,G,J){let $=await this.client._send("vfs-upload-init",{path:Z,size:G.byteLength,mime:J}),z=d(G),H=48000,X=Math.ceil(z.length/48000)||1;for(let Y=0;Y<X;Y++){let L=z.slice(Y*48000,(Y+1)*48000);await this.client._send("vfs-upload-chunk",{transferId:$,data:L,seq:Y})}return await this.client._send("vfs-upload-done",{transferId:$})}async downloadWS(Z){let G=await this.client._send("vfs-download-init",{path:Z}),J=[];return new Promise(($,z)=>{let H=setTimeout(()=>{X(),z(Error("Download timeout"))},30000),X=this.client._onDownloadChunk(G.transferId,(Y)=>{if(J[Y.seq]=Y.data,Y.done)clearTimeout(H),X(),$(o1(J.join("")))})})}async stat(Z){return await this.client._send("vfs-stat",{path:Z})}async list(Z){return await this.client._send("vfs-list",{path:Z})}async tree(Z,G){return await this.client._send("vfs-tree",{path:Z,...G})}async delete(Z){await this.client._send("vfs-delete",{path:Z})}async mkdir(Z){return await this.client._send("vfs-mkdir",{path:Z})}async move(Z,G){return await this.client._send("vfs-move",{path:Z,dst:G})}async uploadResumable(Z,G,J){let $=J?.chunkSize||262144,z=G.byteLength,X=(await this.client._send("vfs-resumable-init",{path:Z,totalSize:z,mime:J?.mime})).sessionId,Y=0;while(Y<z){let L=Math.min(Y+$,z),T=G.slice(Y,L),M=d(T);Y=(await this.client._send("vfs-resumable-chunk",{sessionId:X,offset:Y,data:M})).receivedBytes,J?.onProgress?.(Y,z)}return await this.client._send("vfs-resumable-done",{sessionId:X})}async resumeUpload(Z,G,J){let $=J?.chunkSize||262144,z=await this.client._send("vfs-resumable-status",{sessionId:Z}),H=z.receivedBytes,X=z.totalSize;while(H<X){let Y=Math.min(H+$,X),L=G.slice(H,Y),T=d(L);H=(await this.client._send("vfs-resumable-chunk",{sessionId:Z,offset:H,data:T})).receivedBytes,J?.onProgress?.(H,X)}return await this.client._send("vfs-resumable-done",{sessionId:Z})}async getUploadStatus(Z){return await this.client._send("vfs-resumable-status",{sessionId:Z})}async updateMetadata(Z,G){return await this.client._send("vfs-update-metadata",{path:Z,...G})}async presign(Z,G){let J=G?.method||"GET",$=await this.client._send("vfs-presign",{path:Z,expiresIn:G?.expiresIn,method:J});return`${this.client.httpUrl}/files/${Z}?sig=${$.sig}&exp=${$.exp}`}}class r{client;queue;constructor(Z,G){this.client=Z;this.queue=G}async push(Z,G){return this.client._mqSend("mq-push",{path:this.queue,value:Z,idempotencyKey:G?.idempotencyKey})}async fetch(Z){return(await this.client._mqSend("mq-fetch",{path:this.queue,count:Z})).map((J)=>new I(J.key,J.path,J.deliveryCount,J.status,J.data))}async ack(Z){await this.client._mqSend("mq-ack",{path:this.queue,key:Z})}async nack(Z){await this.client._mqSend("mq-nack",{path:this.queue,key:Z})}async peek(Z){return(await this.client._mqSend("mq-peek",{path:this.queue,count:Z})).map((J)=>new I(J.key,J.path,J.deliveryCount,J.status,J.data))}async dlq(){return(await this.client._mqSend("mq-dlq",{path:this.queue})).map((G)=>new I(G.key,G.path,G.deliveryCount,G.status,G.data))}async purge(Z){return this.client._mqSend("mq-purge",{path:this.queue,all:Z?.all})}}class S1{client;path;constructor(Z,G){this.client=Z;this.path=G}async set(Z){await this.client._send("on-disconnect-set",{path:this.path,value:Z})}async update(Z){await this.client._send("on-disconnect-update",{path:this.path,value:Z})}async delete(){await this.client._send("on-disconnect-delete",{path:this.path})}async cancel(){await this.client._send("on-disconnect-cancel",{path:this.path})}}h();function s1(Z){let G=2166136261;for(let J=0;J<Z.length;J++)G^=Z.charCodeAt(J),G=G+((G<<1)+(G<<4)+(G<<7)+(G<<8)+(G<<24))>>>0;return G>>>0}function F1(Z,G,J){return s1(`${Z}::${G??J}`)%1e4}function t1(Z){return Z.sticky??Z.userId??Z.accountId??""}function a1(Z,G,J){if(!Z.variants||Z.variants.length===0)return null;let $=Z.variants.reduce((X,Y)=>X+Y.weight,0);if($<=0)return null;let z=F1(G,Z.salt,J)%$,H=0;for(let X of Z.variants)if(H+=X.weight,z<H)return{variantKey:X.key};return{variantKey:Z.variants[Z.variants.length-1].key}}function s(Z,G){let J=Z.variants?.find(($)=>$.key===G);return J?J.value:Z.defaultValue}function e1(Z,G){if(Z.emails?.length&&G.email){let J=G.email.toLowerCase();if(Z.emails.some(($)=>$.toLowerCase()===J))return"email"}if(Z.tags?.length&&G.tags?.length){let J=new Set(G.tags);if(Z.tags.some(($)=>J.has($)))return"tag"}return null}function ZZ(Z,G){if(G.variant)return{value:s(Z,G.variant),variant:G.variant};if(G.value!==void 0){if(Z.kind==="variant"&&typeof G.value==="string")return{value:s(Z,G.value),variant:G.value};return{value:G.value}}if(Z.kind==="boolean")return{value:!0};let J=Z.variants?.[0];return J?{value:J.value,variant:J.key}:{value:Z.defaultValue}}function b(Z,G,J){let $=Z?.key??G?.key??"";if(J.cookieOverrides&&$ in J.cookieOverrides)return{key:$,value:J.cookieOverrides[$],reason:"cookie_override"};if(!Z)return{key:$,value:void 0,reason:"unregistered"};if(G&&G.enabled===!1)return{key:$,value:Z.defaultValue,reason:"kill_switch"};let z=G&&(!G.branch||G.branch===J.branch);if(z&&G.targeting){let H=e1(G.targeting,J);if(H){let{value:X,variant:Y}=ZZ(Z,G.targeting);return{key:$,value:X,...Y?{variant:Y}:{},reason:H==="email"?"targeting_email":"targeting_tag"}}}if(z&&G.value!==void 0)return{key:$,value:G.value,reason:"override_value"};if(z&&G.rollout){let H=t1(J);if(Z.kind==="variant"&&G.rollout.variants?.length){let X=a1(G.rollout,H,Z.key);if(X)return{key:$,value:s(Z,X.variantKey),variant:X.variantKey,reason:"rollout"}}else if(Z.kind==="boolean"){let X=F1(H,G.rollout.salt,Z.key),Y=Math.max(0,Math.min(1e4,Math.round(G.rollout.percent*100)));return{key:$,value:X<Y,reason:"rollout"}}}return{key:$,value:Z.defaultValue,reason:"default",...Z.kind==="variant"&&typeof Z.defaultValue==="string"?{variant:Z.defaultValue}:{}}}function t(){try{let Z=globalThis;if(Z.__APPWRAP__?.native)return"native";if(Z.appwrap||Z.nativeKit||Z.nsWebViewBridge||Z.Capacitor)return"native";if(typeof navigator<"u"&&/Appwrap|NativeScript|Capacitor/i.test(navigator.userAgent))return"native";if(typeof navigator<"u"&&navigator.standalone===!0)return"pwa";if(typeof matchMedia==="function"&&matchMedia("(display-mode: standalone)").matches)return"pwa"}catch{}return"web"}function a(){try{let Z=globalThis.__APPWRAP__?.platform;return Z==="ios"||Z==="android"?Z:void 0}catch{return}}function C1(Z){if(Z)return Z;try{return document.querySelector('meta[name="app-version"]')?.getAttribute("content")||void 0}catch{return}}function A1(Z){try{return localStorage.getItem(Z)}catch{return null}}function w1(Z,G){try{localStorage.setItem(Z,G)}catch{}}function O1(Z={}){let G=t(),J=a(),$=C1(Z.version),z=[],X=!A1("bodify_installed_at");if(X){w1("bodify_installed_at",String(Date.now()));let L;try{L=document.referrer||void 0}catch{}z.push({name:"$install",type:"lifecycle",properties:{platform:G,nativePlatform:J,version:$,referrer:L}})}let Y=A1("bodify_app_version");if($&&Y!==$){if(w1("bodify_app_version",$),Y)z.push({name:"$app_update",type:"lifecycle",properties:{platform:G,nativePlatform:J,from:Y,to:$}})}if(Z.newSession)z.push({name:"$session_start",type:"lifecycle",properties:{platform:G,nativePlatform:J,version:$}});return z.push({name:"$app_open",type:"lifecycle",properties:{platform:G,nativePlatform:J,version:$,firstOpen:X}}),z}function K1(){return{name:"$pwa_install",type:"lifecycle",properties:{platform:t(),nativePlatform:a()}}}function GZ(Z){try{let G=new URL(Z,typeof location<"u"?location.href:void 0).hostname;if(/(^|\.)(apps|itunes)\.apple\.com$/i.test(G))return"ios";if(/(^|\.)play\.google\.com$/i.test(G))return"android";return null}catch{return null}}function g1(Z,G){for(let J of Z??[]){let $=J?.href;if(typeof $!=="string"||!$)continue;let z=GZ($);if(!z)return null;return{name:"$store_click",type:"lifecycle",properties:{platform:t(),nativePlatform:a(),store:z,target:$,version:C1(G)}}}return null}var m=[],Q=null,e=null,b1="bodify_outbox",JZ=100,E1=!1;function H1(){try{return JSON.parse(localStorage.getItem(b1)||"[]")}catch{return[]}}function W1(Z){try{localStorage.setItem(b1,JSON.stringify(Z.slice(-JZ)))}catch{}}function Z1(Z){let G=H1();G.push(Z),W1(G)}async function x1(){if(typeof navigator<"u"&&navigator.onLine===!1)return;let Z=H1();if(!Z.length)return;W1([]);let G=[];for(let J of Z)try{if(!(await fetch(J.url,{method:"POST",headers:J.headers,body:J.body,keepalive:!0})).ok)G.push(J)}catch{G.push(J)}if(G.length)W1([...H1(),...G])}function m1(Z,G,J,$){let z=typeof navigator<"u"&&navigator.onLine===!1;if(!z&&$&&typeof navigator<"u"&&navigator.sendBeacon){if(navigator.sendBeacon(Z,new Blob([G],{type:"application/json"})))return}if(z){Z1({url:Z,body:G,headers:J});return}fetch(Z,{method:"POST",headers:J,body:G,keepalive:!0}).then((H)=>{if(!H.ok)Z1({url:Z,body:G,headers:J})}).catch(()=>Z1({url:Z,body:G,headers:J}))}var S=new Map,K=new Map,F=new Set,U=null,v=null,X1=null,I1=new Map,$Z=60000,u="bodify.flags.override",P1="bodify_anon_id",G1="bodify_session_id",zZ=1800000,P=!1,g,Y1,D,n=[],Q1=null,w=[],R={};function v1(){return crypto.randomUUID?.()??Math.random().toString(36).slice(2)+Date.now().toString(36)}function HZ(){try{let G=localStorage.getItem(P1);if(G)return G}catch{}let Z=v1();try{localStorage.setItem(P1,Z)}catch{}return Z}var k1="bodify_anon_uid";function WZ(){try{let J=localStorage.getItem(k1);if(J)return J}catch{}let G="anon_"+(crypto.randomUUID?.().replace(/-/g,"")??Math.random().toString(16).slice(2)+Date.now().toString(16)).slice(0,32);try{localStorage.setItem(k1,G)}catch{}return G}var J1=null,$1=null;function B1(Z){if(Q)Q.userId=Z;for(let G of F)G()}function T1(){try{let G=sessionStorage.getItem(G1);if(G){let{id:J,ts:$}=JSON.parse(G);if(Date.now()-$<zZ)return sessionStorage.setItem(G1,JSON.stringify({id:J,ts:Date.now()})),J}}catch{}let Z=v1();L1=!0;try{sessionStorage.setItem(G1,JSON.stringify({id:Z,ts:Date.now()}))}catch{}return Z}function XZ(){let Z=L1;return L1=!1,Z}var L1=!1;function u1(){if(!Q)return"";return`${Q.ingestUrl.replace(/\/apps\/[^/]+\/ingest$/,"")}/analytics/${Q.appId}`}function N(Z,G,J){let $=Object.keys(R).length?{...R,...J}:J;return{anonymousId:D,sessionId:T1(),userId:Y1,name:Z,type:G,properties:$,source:{url:location.href,referrer:document.referrer||void 0,userAgent:navigator.userAgent},ts:Date.now()}}function O(){if(n.length===0)return;let Z=n.splice(0),G=`${u1()}/events`,J=JSON.stringify({events:Z}),$={"Content-Type":"application/json"};if(g)$["x-analytics-token"]=g;m1(G,J,$,!g)}function V(Z){if(n.push(Z),n.length>=10)O()}function YZ(Z){let G=typeof Z.analytics==="object"?Z.analytics:{};if(P=!0,g=G.secret,D=HZ(),Q1=setInterval(O,5000),!G.disableLifecycleEvents){T1();let X=XZ();for(let T of O1({version:G.appVersion,newSession:X}))V(N(T.name,T.type,T.properties));let Y=()=>{let T=K1();V(N(T.name,T.type,T.properties))};window.addEventListener("appinstalled",Y),w.push(()=>window.removeEventListener("appinstalled",Y));let L=(T)=>{let M=g1(T.composedPath?.(),G.appVersion);if(!M)return;V(N(M.name,M.type,M.properties)),O()};document.addEventListener("click",L,!0),w.push(()=>document.removeEventListener("click",L,!0))}if(!G.disableAutoPageViews){let X=()=>{try{let j=new URL(location.href);return j.searchParams.sort(),`${j.pathname}${j.search}${j.hash}`}catch{return`${Math.random()}`}},Y=null,L=()=>{let j=X();if(j===Y)return;Y=j,V(N("$pageview","page_view",{path:location.pathname,title:document.title}))};L();let T=history.pushState.bind(history),M=history.replaceState.bind(history);history.pushState=function(...j){T(...j),L()},history.replaceState=function(...j){M(...j),L()};let E=()=>L();window.addEventListener("popstate",E),window.addEventListener("hashchange",E),w.push(()=>{history.pushState=T,history.replaceState=M,window.removeEventListener("popstate",E),window.removeEventListener("hashchange",E)})}let J=(X)=>V(N("$error","error",{message:X.message,filename:X.filename,line:X.lineno,col:X.colno,stack:X.error?.stack})),$=(X)=>{let Y=X.reason instanceof Error?X.reason:Error(String(X.reason));V(N("$error","error",{message:Y.message,stack:Y.stack}))};window.addEventListener("error",J),window.addEventListener("unhandledrejection",$),w.push(()=>{window.removeEventListener("error",J),window.removeEventListener("unhandledrejection",$)});let z=()=>{if(document.visibilityState==="hidden")O()},H=()=>O();document.addEventListener("visibilitychange",z),window.addEventListener("beforeunload",H),w.push(()=>{document.removeEventListener("visibilitychange",z),window.removeEventListener("beforeunload",H)})}function QZ(){if(typeof document>"u")return;let Z=document.cookie.split(";").map((G)=>G.trim()).find((G)=>G.startsWith(`${u}=`));if(!Z)return;try{let G=decodeURIComponent(Z.slice(u.length+1));return JSON.parse(G).flags}catch{return}}function LZ(Z){if(!Z)return;for(let G of Z.definitions??[])if(G?.key)S.set(G.key,G);for(let G of Z.overrides??[])if(G?.key)K.set(G.key,G)}function TZ(Z){try{let G=new URL(Z,typeof location<"u"?location.href:void 0);return`${G.protocol==="https:"?"wss:":"ws:"}//${G.host}/db`}catch{return null}}function n1(){if(U)return U;if(!Q)throw Error("Bodify SDK not initialized");let Z=TZ(Q.ingestUrl);if(!Z)throw Error("Cannot derive DB WS URL from ingestUrl");return U=new _({url:Z,reconnect:!0,offlineQueue:!0,offlineQueueCap:100,auth:()=>W.auth._token??""}),U.connect().catch(()=>{}),U}function jZ(){if(v||!Q)return;let Z;try{Z=n1()}catch{return}let G=Q.appId,J=`flags/${G}/definitions`,$=`flags/${G}/overrides`;v=Z.on(J,(z)=>{let H=z.val();if(!H&&S.size>0)return;let X=new Map;if(H){for(let Y of Object.values(H))if(Y?.key)X.set(Y.key,Y)}S=X;for(let Y of F)Y(void 0)},{deep:!0}),X1=Z.on($,(z)=>{let H=z.val();if(!H&&K.size>0)return;let X=new Map;if(H){for(let Y of Object.values(H))if(Y?.key)X.set(Y.key,Y)}K=X;for(let Y of F)Y(void 0)},{deep:!0})}function MZ(){v?.(),X1?.(),v=null,X1=null}function z1(Z){return{userId:Z?.userId??Q?.userId,accountId:Z?.accountId,email:Z?.email??Q?.email,tags:Z?.tags??Q?.tags,branch:Z?.branch??Q?.branch,sticky:Z?.sticky,cookieOverrides:QZ()}}function _1(Z,G,J,$,z){if(!Q)return;let H=z.sticky??z.userId??z.accountId??"",X=`${Z}::${G??String(J)}::${H}`,Y=Date.now(),L=I1.get(X);if(L&&Y-L<$Z)return;I1.set(X,Y),q({kind:"event",event:"flag.exposure",message:`flag.exposure ${Z}=${G??String(J)}`,meta:{flagKey:Z,value:J,variant:G,reason:$,branch:z.branch,...D?{anonymousId:D}:{},...z.userId?{userId:z.userId}:{}}})}function C(){if(!Q||m.length===0)return;let Z=m.splice(0),G={"Content-Type":"application/json"};if(Q.apiKey)G.Authorization=`Bearer ${Q.apiKey}`;let J=JSON.stringify({signals:Z});m1(Q.ingestUrl,J,G,!Q.apiKey)}function qZ(Z){if(m.push(Z),Q&&m.length>=(Q.maxBatchSize??20))C()}function q(Z){qZ({kind:Z.kind,level:Z.level??"info",source:"sdk",message:Z.message,ts:Date.now(),deployId:Q?.deployId,event:Z.event,metric:Z.metric,value:Z.value,unit:Z.unit,meta:{...Q?.userId?{userId:Q.userId}:{},...Z.meta}})}var W={init(Z){Q=Z;let G={errors:!0,rejections:!0,console:!1,...Z.capture};if(e=setInterval(C,Z.flushIntervalMs??2000),G.errors)window.addEventListener("error",(J)=>{q({kind:"log",level:"error",message:J.message||"Unknown error",meta:{filename:J.filename,lineno:J.lineno,colno:J.colno,stack:J.error?.stack}})});if(G.rejections)window.addEventListener("unhandledrejection",(J)=>{let $=J.reason instanceof Error?J.reason:Error(String(J.reason));q({kind:"log",level:"error",message:$.message,meta:{stack:$.stack}})});if(document.addEventListener("visibilitychange",()=>{if(document.visibilityState==="hidden")C()}),window.addEventListener("beforeunload",C),W.auth.restore(),LZ(Z.flags),jZ(),!E1&&typeof window<"u")window.addEventListener("online",()=>{x1()}),E1=!0;if(x1(),Z.analytics!==!1&&!NZ(Z.ingestUrl)&&!DZ())YZ(Z)},event(Z,G){let J=P?{anonymousId:D,sessionId:T1(),userId:Y1,...R,...G}:{...R,...G};q({kind:"event",message:Z,event:Z,meta:J})},metric(Z,G,J){let{unit:$,...z}=J??{};q({kind:"metric",message:`${Z}=${G}`,metric:Z,value:G,unit:$,meta:Object.keys(z).length>0?z:void 0})},log:{debug:(Z,G)=>q({kind:"log",level:"debug",message:Z,meta:G}),info:(Z,G)=>q({kind:"log",level:"info",message:Z,meta:G}),warn:(Z,G)=>q({kind:"log",level:"warn",message:Z,meta:G}),error:(Z,G)=>q({kind:"log",level:"error",message:Z,meta:G})},leads:{async collect(Z){if(!Q)throw Error("Bodify SDK not initialized");let J=`${Q.ingestUrl.replace(/\/apps\/[^/]+\/ingest$/,"")}/leads/${Q.appId}/collect`,$={"Content-Type":"application/json"};if(Q.apiKey)$.Authorization=`Bearer ${Q.apiKey}`;let z=await fetch(J,{method:"POST",headers:$,body:JSON.stringify(Z)});if(!z.ok)throw Error(`Leads collect failed: ${z.status}`);return z.json()}},storage:{_baseUrl(){if(!Q)throw Error("Bodify SDK not initialized");return Q.ingestUrl.replace(/\/apps\/[^/]+\/ingest$/,"")+`/apps/${Q.appId}/storage`},_headers(){let Z={"Content-Type":"application/json"};if(Q?.apiKey)Z.Authorization=`Bearer ${Q.apiKey}`;return Z},async upload(Z,G){let J=W.storage._baseUrl(),$=G?.path??Z.name,z=await fetch(`${J}/upload`,{method:"POST",headers:W.storage._headers(),body:JSON.stringify({path:$,contentType:Z.type||"application/octet-stream",size:Z.size,public:G?.public})});if(!z.ok)throw Error(`Upload init failed: ${z.status}`);let H=await z.json();if(H.uploadUrl){let Y=await fetch(H.uploadUrl,{method:"PUT",body:Z,headers:{"Content-Type":Z.type||"application/octet-stream"}});if(!Y.ok)throw Error(`Upload to storage failed: ${Y.status}`)}else{let Y=await fetch(`${J}/upload/${H.fileId}?sessionId=${H.sessionId}`,{method:"PUT",body:Z,headers:{...W.storage._headers(),"Content-Type":Z.type||"application/octet-stream"}});if(!Y.ok)throw Error(`Local upload failed: ${Y.status}`)}let X=await fetch(`${J}/upload/${H.fileId}/finalize`,{method:"POST",headers:W.storage._headers(),body:JSON.stringify({sessionId:H.sessionId})});if(!X.ok)throw Error(`Finalize failed: ${X.status}`);return await X.json().catch(()=>({})),{fileId:H.fileId}},async getUrl(Z){let G=await fetch(`${W.storage._baseUrl()}/files/${Z}/url`,{headers:W.storage._headers()});if(!G.ok)throw Error(`Get URL failed: ${G.status}`);return(await G.json()).url},async delete(Z){let G=await fetch(`${W.storage._baseUrl()}/files/${Z}`,{method:"DELETE",headers:W.storage._headers()});if(!G.ok)throw Error(`Delete failed: ${G.status}`)},async list(Z){let G=new URLSearchParams;if(Z?.prefix)G.set("prefix",Z.prefix);if(Z?.limit)G.set("limit",String(Z.limit));let J=await fetch(`${W.storage._baseUrl()}/files?${G}`,{headers:W.storage._headers()});if(!J.ok)throw Error(`List failed: ${J.status}`);return J.json()},publicUrl(Z){if(!Q)throw Error("Bodify SDK not initialized");return`${Q.ingestUrl.replace(/\/apps\/[^/]+\/ingest$/,"")}/apps/${Q.appId}/storage/public/${Z}`}},auth:{_token:null,_user:null,_pendingVerification:null,_listeners:[],_baseUrl(){if(!Q)throw Error("Bodify SDK not initialized");return Q.ingestUrl.replace(/\/apps\/[^/]+\/ingest$/,"")+`/apps/${Q.appId}/auth`},async _fetch(Z,G){let J={"Content-Type":"application/json",...G?.headers};if(W.auth._token)J.Authorization=`Bearer ${W.auth._token}`;return fetch(`${W.auth._baseUrl()}${Z}`,{...G,headers:J})},_setToken(Z){if(W.auth._token=Z,Z)localStorage.setItem("bodify_auth_token",Z);else localStorage.removeItem("bodify_auth_token")},_notify(){W.auth._listeners.forEach((Z)=>Z(W.auth._user,W.auth._pendingVerification))},_handleAuthResponse(Z){if(W.auth._setToken(Z.token),Z.emailVerificationRequired)W.auth._user=null,W.auth._pendingVerification=Z.user;else W.auth._user=Z.user,W.auth._pendingVerification=null;W.auth._notify()},async signUp(Z){let G=await W.auth._fetch("/signup",{method:"POST",body:JSON.stringify(Z)});if(!G.ok){let $=await G.json().catch(()=>({}));throw Error($.error??`Signup failed: ${G.status}`)}let J=await G.json();return W.auth._handleAuthResponse(J),J},async signIn(Z){let G=await W.auth._fetch("/login",{method:"POST",body:JSON.stringify(Z)});if(!G.ok){let $=await G.json().catch(()=>({}));throw Error($.error??`Login failed: ${G.status}`)}let J=await G.json();return W.auth._handleAuthResponse(J),J},signInWithOAuth(Z,G){let J=G?.returnTo??window.location.href;window.location.href=`${W.auth._baseUrl()}/oauth/${Z}?returnTo=${encodeURIComponent(J)}`},adoptAnonIdentity(){if(W.auth._user?.isAnonymous)return W.auth._user.id;let Z=WZ();if(!W.auth._user)W.auth._user={id:Z,isAnonymous:!0},B1(Z),W.auth._notify();return Z},whenTokenReady(){if(W.auth._token)return Promise.resolve();return J1??Promise.resolve()},async signInAnonymously(){let Z=W.auth.adoptAnonIdentity();if(!W.auth._token&&!J1)J1=new Promise(($)=>{$1=$});let G=await W.auth._fetch("/anonymous",{method:"POST",body:JSON.stringify({uid:Z})});if(!G.ok){let $=await G.json().catch(()=>({}));throw Error($.error??`Anonymous signin failed: ${G.status}`)}let J=await G.json();return W.auth._setToken(J.token),W.auth._user=J.user,W.auth._pendingVerification=null,B1(J.user.id),W.auth._notify(),$1?.(),$1=null,J},async attachEmail(Z){let G=await W.auth._fetch("/email/attach",{method:"POST",body:JSON.stringify({email:Z})});if(!G.ok){let $=await G.json().catch(()=>({}));throw Error($.error??"Attach failed")}let{user:J}=await G.json();return W.auth._user=J,W.auth._notify(),J},async linkEmail(Z,G){let J=await W.auth._fetch("/link",{method:"POST",body:JSON.stringify({provider:"email",email:Z,password:G})});if(!J.ok){let z=await J.json().catch(()=>({}));throw Error(z.error??"Link failed")}let{user:$}=await J.json();return W.auth._user=$,W.auth._notify(),$},async linkPhone(Z,G){let J=await W.auth._fetch("/link",{method:"POST",body:JSON.stringify({provider:"phone",phone:Z,otp:G})});if(!J.ok){let z=await J.json().catch(()=>({}));throw Error(z.error??"Link failed")}let{user:$}=await J.json();return W.auth._user=$,W.auth._notify(),$},async startPhoneSignIn(Z){let G=await W.auth._fetch("/phone/start",{method:"POST",body:JSON.stringify({phone:Z})});if(!G.ok){let J=await G.json().catch(()=>({}));throw Error(J.error??"Failed to send OTP")}return G.json()},async linkOAuth(Z,G){let J=G?.returnTo??window.location.href,$=await W.auth._fetch(`/link-oauth/${Z}`,{method:"POST",body:JSON.stringify({returnTo:J})});if(!$.ok){let H=await $.json().catch(()=>({}));throw Error(H.error??"Link failed")}let{redirectUrl:z}=await $.json();window.location.href=z},async mergeFromAnonymous(Z){let G=await W.auth._fetch("/merge",{method:"POST",body:JSON.stringify({sourceId:Z})});if(!G.ok){let J=await G.json().catch(()=>({}));throw Error(J.error??"Merge failed")}return G.json()},async listAudit(){let Z=await W.auth._fetch("/audit");if(!Z.ok)throw Error("Audit list failed");return Z.json()},async signInWithPhone(Z,G){let J=await W.auth._fetch("/phone/verify",{method:"POST",body:JSON.stringify({phone:Z,code:G})});if(!J.ok){let z=await J.json().catch(()=>({}));throw Error(z.error??"Phone verify failed")}let $=await J.json();return W.auth._setToken($.token),W.auth._user=$.user,W.auth._pendingVerification=null,W.auth._notify(),$},async signOut(){await W.auth._fetch("/logout",{method:"POST"}).catch(()=>{}),W.auth._setToken(null),W.auth._user=null,W.auth._pendingVerification=null,W.auth._notify()},async verifyEmail(Z){let G=await W.auth._fetch("/verify-email",{method:"POST",body:JSON.stringify({code:Z})});if(!G.ok){let $=await G.json().catch(()=>({}));throw Error($.error??"Verification failed")}let J=await G.json();return W.auth._setToken(J.token),W.auth._user=J.user,W.auth._pendingVerification=null,W.auth._notify(),J},async resendVerification(){let Z=await W.auth._fetch("/resend-verification",{method:"POST"});if(!Z.ok){let G=await Z.json().catch(()=>({}));throw Error(G.error??"Resend failed")}},async signInWithMagicLink(Z){let G=await W.auth._fetch("/magic-link/verify",{method:"POST",body:JSON.stringify({token:Z})});if(!G.ok){let $=await G.json().catch(()=>({}));throw Error($.error??"Invalid or expired link")}let J=await G.json();return W.auth._setToken(J.token),W.auth._user=J.user,W.auth._pendingVerification=null,W.auth._notify(),J},async getProviders(){return(await fetch(`${W.auth._baseUrl()}/providers`)).json()},async getUser(){if(!W.auth._token)return null;let Z=3;for(let G=0;G<Z;G++){let J=null;try{J=await W.auth._fetch("/me")}catch{}if(J){if(J.ok){let $=await J.json();return W.auth._user=$,$}if(J.status===401)return W.auth._user=null,null}if(G<Z-1)await new Promise(($)=>setTimeout($,400*(G+1)))}return W.auth._user},async updateProfile(Z){let G=await W.auth._fetch("/me",{method:"PATCH",body:JSON.stringify(Z)});if(!G.ok)throw Error("Update failed");let J=await G.json();return W.auth._user=J,W.auth._notify(),J},onAuthStateChange(Z){return W.auth._listeners.push(Z),()=>{W.auth._listeners=W.auth._listeners.filter((G)=>G!==Z)}},restore(){let Z=localStorage.getItem("bodify_auth_token");if(Z)W.auth._token=Z}},flags:{get(Z,G){let J=z1(G),$=S.get(Z),z=K.get(Z),H=b($,z,J);return _1(Z,H.variant,H.value,H.reason,J),H.value},isEnabled(Z,G){return W.flags.get(Z,G)===!0},variant(Z,G){let J=z1(G),$=S.get(Z),z=K.get(Z),H=b($,z,J);return _1(Z,H.variant,H.value,H.reason,J),H.variant??""},all(Z){let G=z1(Z),J={};for(let[$,z]of S){let H=K.get($),X=b(z,H,G);J[$]=X.value}return J},subscribe(Z){return F.add(Z),()=>F.delete(Z)},keys(){return[...S.keys()].sort()},setCookieOverride(Z,G){if(typeof document>"u")return;let J=encodeURIComponent(JSON.stringify({flags:Z})),$=G?.maxAgeSec??86400;document.cookie=`${u}=${J}; path=/; max-age=${$}; samesite=lax`;for(let z of F)z()},clearCookieOverride(){if(typeof document>"u")return;document.cookie=`${u}=; path=/; max-age=0`;for(let Z of F)Z()}},analytics:{identify(Z,G){if(Y1=Z||void 0,!P||!D)return;let J=`${u1()}/identify`,$={"Content-Type":"application/json"};if(g)$["x-analytics-token"]=g;fetch(J,{method:"POST",headers:$,body:JSON.stringify({anonymousId:D,userId:Z,traits:G}),keepalive:!0}).catch(()=>{})},track(Z,G){if(!P)return;V(N(Z,"custom",G))},page(Z){if(!P)return;V(N("$pageview","page_view",{path:location.pathname,title:document.title,...Z}))},getAnonymousId(){return D??""},register(Z){R={...R,...Z}},unregister(...Z){for(let G of Z)delete R[G]}},get db(){return n1()},flush:C,destroy(){if(e)clearInterval(e);if(Q1)clearInterval(Q1);w.forEach((Z)=>Z()),O(),MZ(),U?.disconnect(),U=null,C()}};function NZ(Z){try{let G=new URL(Z,typeof location<"u"?location.href:void 0).hostname;return G==="localhost"||G==="0.0.0.0"||G==="::1"||G==="[::1]"||G.endsWith(".local")||/^127\./.test(G)||/^10\./.test(G)||/^192\.168\./.test(G)||/^172\.(1[6-9]|2\d|3[01])\./.test(G)||/^169\.254\./.test(G)}catch{return!1}}function y1(){if(typeof location>"u")return!1;try{return new URL(location.href).searchParams.get("__bodify_render")==="1"}catch{return!1}}var VZ=y1();function DZ(){return VZ||y1()}function UZ(Z,G){let J=typeof location<"u"?location.origin:"";try{if(Z?.src){let $=new URL(Z.src,typeof location<"u"?location.href:void 0);if($.protocol==="http:"||$.protocol==="https:")J=$.origin}}catch{}return`${J}/api/apps/${G}/ingest`}if(typeof window<"u"){let Z=window.__BODIFY_CONFIG__;if(Z)W.init(Z);else{let G=document.currentScript;if(G?.dataset.appId){let J=window.__BODIFY_FLAGS__;W.init({appId:G.dataset.appId,ingestUrl:G.dataset.ingestUrl||UZ(G,G.dataset.appId),apiKey:G.dataset.apiKey,deployId:G.dataset.deployId,branch:G.dataset.branch,userId:G.dataset.userId,flags:J,analytics:G.dataset.analytics==="false"?!1:!0})}}}window.Bodify=W;