@mitway/sdk 0.10.0 → 0.10.2
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/dist/index.cjs +4 -4
- package/dist/index.d.cts +109 -19
- package/dist/index.d.ts +109 -19
- package/dist/index.js +4 -4
- package/package.json +2 -1
package/dist/index.cjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
'use strict';Object.defineProperty(exports,'__esModule',{value:true});var postgrestJs=require('@mitway/postgrest-js'),socket_ioClient=require('socket.io-client');var c=class
|
|
2
|
-
`));}logResponse(e,t,s,
|
|
1
|
+
'use strict';Object.defineProperty(exports,'__esModule',{value:true});var postgrestJs=require('@mitway/postgrest-js'),socket_ioClient=require('socket.io-client');var c=class n extends Error{statusCode;error;nextActions;constructor(e,t,r,s){super(e),this.name="MitwayBaasError",this.statusCode=t,this.error=r,this.nextActions=s;}static fromApiError(e){return new n(e.message,e.statusCode,e.error,e.nextActions)}};var ne=["authorization","x-api-key","cookie","set-cookie"],ie=["password","token","accesstoken","refreshtoken","authorization","secret","apikey","api_key","email","ssn","creditcard","credit_card"];function oe(n){let e={};for(let[t,r]of Object.entries(n))ne.includes(t.toLowerCase())?e[t]="***REDACTED***":e[t]=r;return e}function P(n){if(n==null)return n;if(typeof n=="string")try{let e=JSON.parse(n);return P(e)}catch{return n}if(Array.isArray(n))return n.map(P);if(typeof n=="object"){let e={};for(let[t,r]of Object.entries(n))ie.includes(t.toLowerCase().replace(/[-_]/g,""))?e[t]="***REDACTED***":e[t]=P(r);return e}return n}function X(n){if(n==null)return "";if(typeof n=="string")try{return JSON.stringify(JSON.parse(n),null,2)}catch{return n}if(typeof FormData<"u"&&n instanceof FormData)return "[FormData]";try{return JSON.stringify(n,null,2)}catch{return "[Unserializable body]"}}var R=class{enabled;customLog;constructor(e){typeof e=="function"?(this.enabled=true,this.customLog=e):(this.enabled=!!e,this.customLog=null);}log(e,...t){if(!this.enabled)return;let r=`[MITWAY-BaaS Debug] ${e}`;this.customLog?this.customLog(r,...t):console.log(r,...t);}warn(e,...t){if(!this.enabled)return;let r=`[MITWAY-BaaS Debug] ${e}`;this.customLog?this.customLog(r,...t):console.warn(r,...t);}error(e,...t){if(!this.enabled)return;let r=`[MITWAY-BaaS Debug] ${e}`;this.customLog?this.customLog(r,...t):console.error(r,...t);}logRequest(e,t,r,s){if(!this.enabled)return;let i=[`\u2192 ${e} ${t}`];r&&Object.keys(r).length>0&&i.push(` Headers: ${JSON.stringify(oe(r))}`);let o=X(P(s));if(o){let a=o.length>1e3?o.slice(0,1e3)+"... [truncated]":o;i.push(` Body: ${a}`);}this.log(i.join(`
|
|
2
|
+
`));}logResponse(e,t,r,s,i){if(!this.enabled)return;let o=[`\u2190 ${e} ${t} ${r} (${s}ms)`],a=X(P(i));if(a){let d=a.length>1e3?a.slice(0,1e3)+"... [truncated]":a;o.push(` Body: ${d}`);}r>=400?this.error(o.join(`
|
|
3
3
|
`)):this.log(o.join(`
|
|
4
|
-
`));}};var G="mitway_baas_csrf_token",ae="mitway_baas_session";function Z(){return typeof localStorage<"u"?{getItem:e=>{try{return localStorage.getItem(e)}catch{return null}},setItem:(e,t)=>{try{localStorage.setItem(e,t);}catch{}},removeItem:e=>{try{localStorage.removeItem(e);}catch{}}}:{getItem:()=>null,setItem:()=>{},removeItem:()=>{}}}var ce={getItem:()=>null,setItem:()=>{},removeItem:()=>{}};function ee(){if(typeof document>"u")return null;let r=document.cookie.split(";").find(e=>e.trim().startsWith(`${G}=`));return r&&r.split("=")[1]||null}function L(r){if(typeof document>"u")return;let e=10080*60,t=typeof window<"u"&&window.location.protocol==="https:"?"; Secure":"";document.cookie=`${G}=${encodeURIComponent(r)}; path=/; max-age=${e}; SameSite=Lax${t}`;}function j(){if(typeof document>"u")return;let r=typeof window<"u"&&window.location.protocol==="https:"?"; Secure":"";document.cookie=`${G}=; path=/; max-age=0; SameSite=Lax${r}`;}var S=class{accessToken=null;refreshToken=null;user=null;persistSession;storageKey;storage;onTokenChange=null;constructor(e){this.persistSession=e?.persistSession??true,this.storageKey=e?.storageKey??ae,this.storage=this.persistSession?e?.storage??Z():ce,(e?.multiTab??true)&&this.persistSession&&typeof window<"u"&&typeof localStorage<"u"&&window.addEventListener("storage",this.handleStorageEvent),this.restoreSession();}handleStorageEvent=e=>{e.key===this.storageKey&&(typeof localStorage<"u"&&e.storageArea!==localStorage||this.syncFromStorage(e.newValue));};syncFromStorage(e){let t=this.accessToken;if(e===null)this.accessToken=null,this.refreshToken=null,this.user=null;else try{let s=JSON.parse(e);if(!s.accessToken||!s.user)return;this.accessToken=s.accessToken,this.refreshToken=s.refreshToken??null,this.user=s.user;}catch{return}t!==this.accessToken&&this.onTokenChange&&this.onTokenChange();}saveSession(e){let t=e.accessToken!==this.accessToken;this.accessToken=e.accessToken,this.user=e.user,e.refreshToken!==void 0&&(this.refreshToken=e.refreshToken??null),this.persist(),t&&this.onTokenChange&&this.onTokenChange();}getSession(){return !this.accessToken||!this.user?null:{accessToken:this.accessToken,refreshToken:this.refreshToken??void 0,user:this.user}}getAccessToken(){return this.accessToken}setAccessToken(e){let t=e!==this.accessToken;this.accessToken=e,this.persist(),t&&this.onTokenChange&&this.onTokenChange();}getRefreshToken(){return this.refreshToken}setRefreshToken(e){this.refreshToken=e,this.persist();}getUser(){return this.user}setUser(e){this.user=e,this.persist();}clearSession(){let e=this.accessToken!==null;this.accessToken=null,this.refreshToken=null,this.user=null,this.removePersisted(),e&&this.onTokenChange&&this.onTokenChange();}restoreSession(){if(!this.persistSession)return false;try{let e=this.storage.getItem(this.storageKey);if(!e)return !1;let t=JSON.parse(e);return !t.accessToken||!t.user?!1:(this.accessToken=t.accessToken,this.refreshToken=t.refreshToken??null,this.user=t.user,!0)}catch{return false}}persist(){if(!this.persistSession||!this.accessToken||!this.user)return;let e={accessToken:this.accessToken,user:this.user};this.refreshToken&&(e.refreshToken=this.refreshToken),this.storage.setItem(this.storageKey,JSON.stringify(e));}removePersisted(){this.persistSession&&this.storage.removeItem(this.storageKey);}};function A(r){if(!r||typeof r!="object")return r;let e=r,t={...e},s=false;return "access_token"in e&&!("accessToken"in e)&&(t.accessToken=e.access_token,delete t.access_token,s=true),"csrf_token"in e&&!("csrfToken"in e)&&(t.csrfToken=e.csrf_token,delete t.csrf_token,s=true),"refresh_token"in e&&!("refreshToken"in e)&&(t.refreshToken=e.refresh_token,delete t.refresh_token,s=true),s?t:r}var le=new Set([500,502,503,504]),ue=new Set(["GET","HEAD","PUT","DELETE","OPTIONS"]),I=class{baseUrl;fetch;defaultHeaders;anonKey;userToken=null;logger;autoRefreshToken=true;isRefreshing=false;refreshPromise=null;tokenManager;refreshToken=null;timeout;retryCount;retryDelay;constructor(e,t,s){if(this.baseUrl=e.baseUrl||"http://localhost:7130",this.autoRefreshToken=e.autoRefreshToken??true,this.fetch=e.fetch||(globalThis.fetch?globalThis.fetch.bind(globalThis):void 0),this.anonKey=e.anonKey,this.defaultHeaders={...e.headers},this.tokenManager=t??new S,this.logger=s||new R(false),this.timeout=e.timeout??3e4,this.retryCount=e.retryCount??3,this.retryDelay=e.retryDelay??500,!this.fetch)throw new Error("Fetch is not available. Provide a fetch implementation in the SDK config.")}buildUrl(e,t){let s=new URL(e,this.baseUrl);return t&&Object.entries(t).forEach(([n,i])=>{if(n==="select"){let o=i.replace(/\s+/g," ").trim();o=o.replace(/\s*\(\s*/g,"(").replace(/\s*\)\s*/g,")").replace(/\(\s+/g,"(").replace(/\s+\)/g,")").replace(/,\s+(?=[^()]*\))/g,","),s.searchParams.append(n,o);}else s.searchParams.append(n,i);}),s.toString()}isRetryableStatus(e){return le.has(e)}computeRetryDelay(e){let s=this.retryDelay*Math.pow(2,e-1)*(.85+Math.random()*.3);return Math.round(s)}async handleRequest(e,t,s={}){let{params:n,headers:i={},body:o,signal:a,...d}=s,p=this.buildUrl(t,n),v=Date.now(),T=ue.has(e.toUpperCase())||s.idempotent===true?this.retryCount:0,b={...this.defaultHeaders},Q=this.userToken||this.anonKey;Q&&(b.Authorization=`Bearer ${Q}`);let N;o!==void 0&&(typeof FormData<"u"&&o instanceof FormData?N=o:(e!=="GET"&&(b["Content-Type"]="application/json;charset=UTF-8"),N=JSON.stringify(o))),i instanceof Headers?i.forEach((f,g)=>{b[g]=f;}):Array.isArray(i)?i.forEach(([f,g])=>{b[f]=g;}):Object.assign(b,i),this.logger.logRequest(e,p,b,N);let W;for(let f=0;f<=T;f++){if(f>0){let l=this.computeRetryDelay(f);if(this.logger.warn(`Retry ${f}/${T} for ${e} ${p} in ${l}ms`),a?.aborted)throw a.reason;await new Promise((u,J)=>{let y=()=>{clearTimeout(ne),J(a.reason);},ne=setTimeout(()=>{a&&a.removeEventListener("abort",y),u();},l);a&&a.addEventListener("abort",y,{once:true});});}let g,m;if((this.timeout>0||a)&&(g=new AbortController,this.timeout>0&&(m=setTimeout(()=>g.abort(),this.timeout)),a))if(a.aborted)g.abort(a.reason);else {let l=()=>g.abort(a.reason);a.addEventListener("abort",l,{once:true}),g.signal.addEventListener("abort",()=>{a.removeEventListener("abort",l);},{once:true});}try{let l=await this.fetch(p,{method:e,headers:b,body:N,...d,...g?{signal:g.signal}:{}});if(this.isRetryableStatus(l.status)&&f<T){m!==void 0&&clearTimeout(m),await l.body?.cancel(),W=new c(`Server error: ${l.status} ${l.statusText}`,l.status,"SERVER_ERROR");continue}if(l.status===204){m!==void 0&&clearTimeout(m);return}let u,J=l.headers.get("content-type");try{J?.includes("json")?u=await l.json():u=await l.text();}catch(y){throw m!==void 0&&clearTimeout(m),new c(`Failed to parse response body: ${y?.message||"Unknown error"}`,l.status,l.ok?"PARSE_ERROR":"REQUEST_FAILED")}if(m!==void 0&&clearTimeout(m),!l.ok){if(this.logger.logResponse(e,p,l.status,Date.now()-v,u),u&&typeof u=="object"&&"error"in u&&u.error!==null&&typeof u.error=="object"){let y=u.error;throw new c(y.message||l.statusText||"Request failed",y.statusCode||l.status,y.code||y.error||"REQUEST_FAILED",y.nextActions)}throw new c(`Request failed: ${l.statusText}`,l.status,"REQUEST_FAILED")}return this.logger.logResponse(e,p,l.status,Date.now()-v,u),u&&typeof u=="object"&&"data"in u&&"error"in u&&u.error===null?u.data:u}catch(l){if(m!==void 0&&clearTimeout(m),l?.name==="AbortError")throw g&&g.signal.aborted&&this.timeout>0&&!a?.aborted?new c(`Request timed out after ${this.timeout}ms`,408,"REQUEST_TIMEOUT"):l;if(l instanceof c)throw l;if(f<T){W=l;continue}throw new c(`Network request failed: ${l?.message||"Unknown error"}`,0,"NETWORK_ERROR")}}throw W||new c("Request failed after all retry attempts",0,"NETWORK_ERROR")}async request(e,t,s={}){try{return await this.handleRequest(e,t,{...s})}catch(n){if(n instanceof c&&n.statusCode===401&&this.autoRefreshToken&&this.refreshToken&&!t.includes("/api/auth/refresh"))try{let i=await this.handleTokenRefresh();this.setAuthToken(i.accessToken),i.refreshToken&&this.setRefreshToken(i.refreshToken),i.csrfToken&&L(i.csrfToken);let o=i.user??this.tokenManager.getUser();return o&&this.tokenManager.saveSession({accessToken:i.accessToken,refreshToken:i.refreshToken,user:o}),await this.handleRequest(e,t,{...s})}catch(i){throw this.tokenManager.clearSession(),this.userToken=null,this.refreshToken=null,j(),i}throw n}}async rawFetch(e,t={}){let s=this.buildUrl(e),n=new Headers(t.headers??{});for(let[i,o]of Object.entries(this.defaultHeaders))n.has(i)||n.set(i,o);if(!n.has("Authorization")){let i=this.userToken??this.anonKey;i&&n.set("Authorization",`Bearer ${i}`);}return this.fetch(s,{...t,headers:n})}get(e,t){return this.request("GET",e,t)}post(e,t,s){return this.request("POST",e,{...s,body:t})}put(e,t,s){return this.request("PUT",e,{...s,body:t})}patch(e,t,s){return this.request("PATCH",e,{...s,body:t})}delete(e,t){return this.request("DELETE",e,t)}setAuthToken(e){this.userToken=e;}setRefreshToken(e){this.refreshToken=e;}getHeaders(){let e={...this.defaultHeaders},t=this.userToken||this.anonKey;return t&&(e.Authorization=`Bearer ${t}`),e}async handleTokenRefresh(){return this.isRefreshing?this.refreshPromise:(this.isRefreshing=true,this.refreshPromise=(async()=>{try{let e=ee(),t=this.refreshToken?{refreshToken:this.refreshToken}:void 0,s=await this.handleRequest("POST","/api/auth/refresh",{body:t,headers:e?{"X-CSRF-Token":e}:{},credentials:"include"});return A(s)}finally{this.isRefreshing=false,this.refreshPromise=null;}})(),this.refreshPromise)}};function w(r,e){return r instanceof c?{data:null,error:r}:{data:null,error:new c(r instanceof Error?r.message:e,500,"AUTH_ERROR")}}var U=class{constructor(e,t){this.http=e;this.tokenManager=t;this.tokenManager.onTokenChange=()=>this._emitFromTokenChange();let s=this.tokenManager.getSession();if(s){this.http.setAuthToken(s.accessToken);let n=this.tokenManager.getRefreshToken();n&&this.http.setRefreshToken(n),this.lastEmittedUserId=s.user.id,this.lastEmittedAccessToken=s.accessToken;}}http;tokenManager;stateChangeListeners=new Set;lastEmittedUserId=null;lastEmittedAccessToken=null;onAuthStateChange(e){return this.stateChangeListeners.add(e),{unsubscribe:()=>{this.stateChangeListeners.delete(e);}}}emit(e,t){for(let s of this.stateChangeListeners)try{s(e,t);}catch{}}_emitFromTokenChange(){let e=this.tokenManager.getSession();e?(this.http.setAuthToken(e.accessToken),this.http.setRefreshToken(e.refreshToken??null)):(this.http.setAuthToken(null),this.http.setRefreshToken(null));let t=this.lastEmittedUserId,s=this.lastEmittedAccessToken;if(!e){t!==null&&(this.lastEmittedUserId=null,this.lastEmittedAccessToken=null,this.emit("SIGNED_OUT",null));return}let n=e.user.id;if(t===null){this.lastEmittedUserId=n,this.lastEmittedAccessToken=e.accessToken,this.emit("SIGNED_IN",e);return}if(t!==n){this.lastEmittedUserId=null,this.lastEmittedAccessToken=null,this.emit("SIGNED_OUT",null),this.lastEmittedUserId=n,this.lastEmittedAccessToken=e.accessToken,this.emit("SIGNED_IN",e);return}s!==e.accessToken&&(this.lastEmittedAccessToken=e.accessToken,this.emit("TOKEN_REFRESHED",e));}saveSessionFromResponse(e){let t={accessToken:e.accessToken,refreshToken:e.refreshToken,user:e.user};e.csrfToken&&L(e.csrfToken),this.tokenManager.saveSession(t),this.http.setAuthToken(e.accessToken),this.http.setRefreshToken(e.refreshToken??null);}async signUp(e){try{let t=await this.http.post("/api/auth/register",e,{credentials:"include"}),s=A(t);return s?.accessToken&&s.user&&this.saveSessionFromResponse(s),{data:s,error:null}}catch(t){return w(t,"Sign up failed")}}async signInWithPassword(e){try{let t=await this.http.post("/api/auth/login",e,{credentials:"include"}),s=A(t);return s?.accessToken&&s.user&&this.saveSessionFromResponse(s),{data:s,error:null}}catch(t){return w(t,"Sign in failed")}}async signOut(){try{try{await this.http.post("/api/auth/logout",void 0,{credentials:"include"});}catch{}return this.tokenManager.clearSession(),this.http.setAuthToken(null),this.http.setRefreshToken(null),j(),{error:null}}catch{return {error:new c("Failed to sign out",500,"SIGNOUT_ERROR")}}}async refreshSession(){try{let e=await this.http.handleTokenRefresh();if(e?.accessToken){let t=e.user??this.tokenManager.getUser();if(t){let s={...e,user:t};return this.saveSessionFromResponse(s),{data:s,error:null}}}return {data:e,error:null}}catch(e){return w(e,"Session refresh failed")}}async initialize(){let e=this.tokenManager.getSession();if(!e)return this.emit("INITIAL_SESSION",null),{data:null,error:new c("No persisted session",0,"NO_SESSION")};try{let t=await this.http.get("/api/auth/sessions/current");if(t?.user){this.tokenManager.setUser(t.user);let s=this.tokenManager.getSession();return this.emit("INITIAL_SESSION",s),{data:{user:t.user,accessToken:e.accessToken},error:null}}return this.tokenManager.clearSession(),this.http.setAuthToken(null),this.http.setRefreshToken(null),this.emit("INITIAL_SESSION",null),{data:null,error:new c("Invalid session",401,"INVALID_SESSION")}}catch(t){return this.tokenManager.clearSession(),this.http.setAuthToken(null),this.http.setRefreshToken(null),this.emit("INITIAL_SESSION",null),w(t,"Session restore failed")}}getSession(){return this.tokenManager.getSession()}getUser(){return this.tokenManager.getUser()}async getCurrentUser(){try{let e=await this.http.get("/api/auth/sessions/current");if(e?.user){let t={accessToken:this.tokenManager.getSession()?.accessToken??"",user:e.user};this.tokenManager.saveSession(t);}return {data:e,error:null}}catch(e){return w(e,"Failed to get current user")}}async getProfile(e){try{return {data:await this.http.get(`/api/auth/profiles/${encodeURIComponent(e)}`),error:null}}catch(t){return w(t,"Failed to get profile")}}async setProfile(e){try{let t=await this.http.patch("/api/auth/profiles/current",{profile:e}),s=this.tokenManager.getUser();if(t?.profile&&s){let n={...s,profile:t.profile};this.tokenManager.setUser(n),this.emit("USER_UPDATED",this.tokenManager.getSession());}return {data:t,error:null}}catch(t){return w(t,"Failed to update profile")}}};function he(r,e,t){return async(s,n)=>{let i=typeof s=="string"?s:s.toString(),o=new URL(i),a=o.pathname.startsWith("/")?o.pathname.slice(1):o.pathname,d=a.match(/^rpc\/(.+)$/),p=d?`/api/database/rpc/${d[1]}`:`/api/database/records/${a}`,v=`${r.baseUrl}${p}${o.search}`,F=new Headers(n?.headers);if(!F.has("Authorization")){let T=e.getAccessToken()??t;T&&F.set("Authorization",`Bearer ${T}`);}return fetch(v,{...n,headers:F})}}var O=class{postgrest;httpClient;constructor(e,t,s){this.httpClient=e,this.postgrest=new postgrestJs.PostgrestClient("http://dummy",{fetch:he(e,t,s),headers:{}});}from(e){if(!e||typeof e!="string")throw new c("Database.from(table) requires a non-empty string",400,"INVALID_TABLE_NAME");return this.postgrest.from(e)}rpc(e,t,s){return this.postgrest.rpc(e,t,s)}getUrl(){return this.httpClient.baseUrl}};var pe=2e4;function V(r,e){let t=new Error(e);return t.code=r,t}var fe=1e4,$=class{constructor(e,t,s={}){this.topic=e;this.realtime=t;this.options=s;}topic;realtime;bindings=[];state="closed";statusCallback=null;presence={};trackedState=null;presenceHeartbeat=null;lastBroadcastTimestamp=null;options;get isPrivate(){return this.options.config?.private===true}get presenceKey(){return this.options.config?.presence?.key}_state(){return this.state}async _rejoinAfterReconnect(){if(this.state!=="closed"){for(let e of this.bindings)e.type==="postgres_changes"&&(e.subscriptionId=void 0);this.state="joining";try{if(await this.registerAllBindings(),this.trackedState){let e=this.realtime._getSocket(),t=this.presenceKey;e?.emit("realtime:presence:track",t!==void 0?{channel:this.topic,state:this.trackedState,key:t}:{channel:this.topic,state:this.trackedState});}this.lastBroadcastTimestamp&&this.bindings.some(e=>e.type==="broadcast")&&this.replay({since:this.lastBroadcastTimestamp}).catch(()=>{}),this.state="joined",this.statusCallback?.("SUBSCRIBED");}catch(e){this.state="errored",this.statusCallback?.("CHANNEL_ERROR",V("REJOIN_FAILED",e instanceof Error?e.message:String(e)));}}}on(e,t,s){return e==="postgres_changes"?this.bindings.push({type:"postgres_changes",filter:t,callback:s}):e==="broadcast"?this.bindings.push({type:"broadcast",filter:t,callback:s}):this.bindings.push({type:"presence",filter:t,callback:s}),this}async track(e){let t=this.realtime._getSocket();if(!t)throw new c("Socket not connected",503,"NOT_CONNECTED");this.trackedState=e;let s=this.presenceKey;t.emit("realtime:presence:track",s!==void 0?{channel:this.topic,state:e,key:s}:{channel:this.topic,state:e}),this.presenceHeartbeat||(this.presenceHeartbeat=setInterval(()=>{let i=this.realtime._getSocket();i&&this.trackedState&&i.emit("realtime:presence:track",s!==void 0?{channel:this.topic,state:this.trackedState,key:s}:{channel:this.topic,state:this.trackedState});},pe),this.presenceHeartbeat.unref?.());}untrack(){this.trackedState=null,this.presenceHeartbeat&&(clearInterval(this.presenceHeartbeat),this.presenceHeartbeat=null),this.realtime._getSocket()?.emit("realtime:presence:untrack",{channel:this.topic});}presenceState(){return this.presence}subscribe(e){return this.statusCallback=e??null,this.state==="joining"||this.state==="joined"?this:(this.state="joining",this.realtime.connect().then(async()=>{try{await this.registerAllBindings(),this.state="joined",this.statusCallback?.("SUBSCRIBED");}catch(t){this.state="errored";let s=t instanceof Error?t.message:String(t);this.statusCallback?.("CHANNEL_ERROR",V("SUBSCRIBE_FAILED",s));}},t=>{this.state="errored",this.statusCallback?.("CHANNEL_ERROR",V("CONNECT_FAILED",t.message));}),this)}async unsubscribe(){if(this.state==="closed")return;let e=this.realtime._getSocket();if(this.presenceHeartbeat&&(clearInterval(this.presenceHeartbeat),this.presenceHeartbeat=null),!e){this.trackedState=null,this.state="closed";return}this.trackedState&&(e.emit("realtime:presence:untrack",{channel:this.topic}),this.trackedState=null);let t=this.bindings.filter(s=>s.type==="postgres_changes");for(let s of t)s.subscriptionId&&(e.emit("realtime:postgres_changes:unsubscribe",{subscription_id:s.subscriptionId}),s.subscriptionId=void 0);this.bindings.some(s=>s.type==="broadcast"||s.type==="presence")&&e.emit("realtime:unsubscribe",{channel:this.topic}),this.realtime._detachChannel(this),this.state="closed",this.statusCallback?.("CLOSED");}async send(e){if(e.type!=="broadcast")throw new c('Only "broadcast" sends are supported \u2014 DB changes flow via your DB writes, not channel.send()',400,"UNSUPPORTED_SEND_TYPE");if(new Set(["postgres_changes","presence_state","presence_join","presence_leave"]).has(e.event))throw new c(`"${e.event}" is a reserved event name \u2014 pick a different name for broadcast events`,400,"RESERVED_EVENT_NAME");let s=this.realtime._getSocket();if(!s)throw new c("Socket not connected",503,"NOT_CONNECTED");let n=this.options.config?.broadcast?.self,i={channel:this.topic,event:e.event,payload:e.payload};return n===false&&(i.self=false),await new Promise(o=>{s.emit("realtime:publish",i,a=>{o(a);});})}async replay(e){let t=this.realtime._getSocket();if(!t)throw new c("Socket not connected",503,"NOT_CONNECTED");t.emit("realtime:broadcast:replay",{channel:this.topic,since:e.since,limit:e.limit,private:this.isPrivate});}_dispatch(e,t){if(e==="postgres_changes"){let n=t;for(let i of this.bindings)if(!(i.type!=="postgres_changes"||!i.subscriptionId||!n.ids.includes(i.subscriptionId)||!(i.filter.event==="*"||i.filter.event===n.data.eventType)))try{i.callback(n.data);}catch{}return}if(e==="presence_state"||e==="presence_join"||e==="presence_leave"){let n=t;if(n.channel!==this.topic)return;if(e==="presence_state"&&n.state)this.presence={...n.state},this.firePresence({event:"sync",state:this.presence});else if(e==="presence_join"&&n.joins)Object.assign(this.presence,n.joins),this.firePresence({event:"join",joins:n.joins});else if(e==="presence_leave"&&n.leaves){for(let i of Object.keys(n.leaves))delete this.presence[i];this.firePresence({event:"leave",leaves:n.leaves});}return}let s=t.meta;s?.timestamp&&(!this.lastBroadcastTimestamp||s.timestamp>this.lastBroadcastTimestamp)&&(this.lastBroadcastTimestamp=s.timestamp);for(let n of this.bindings){if(n.type!=="broadcast"||n.filter.event!==e)continue;let{meta:i,...o}=t;try{n.callback({type:"broadcast",event:e,payload:o});}catch{}}}firePresence(e){for(let t of this.bindings)if(t.type==="presence"&&t.filter.event===e.event)try{e.event==="sync"?t.callback():(e.event,t.callback(e));}catch{}}async registerAllBindings(){let e=this.realtime._getSocket();if(!e)throw new Error("Socket not available");this.bindings.some(n=>n.type==="broadcast"||n.type==="presence")&&await new Promise((n,i)=>{e.emit("realtime:subscribe",{channel:this.topic,private:this.isPrivate},o=>{o.status==="ok"?n():i(new Error(o.error?.message??"subscribe failed"));});});let s=this.bindings.filter(n=>n.type==="postgres_changes");await Promise.all(s.map(n=>new Promise((i,o)=>{e.emit("realtime:postgres_changes:subscribe",{event:n.filter.event,schema:n.filter.schema??"public",table:n.filter.table,filter:n.filter.filter},a=>{a.status==="ok"&&a.subscription_id?(n.subscriptionId=a.subscription_id,i()):o(new Error(a.error?.message??"postgres_changes subscribe failed"));});})));}},B=class{socket=null;baseUrl;options;anonKey;tokenManager;channels=new Map;connecting=null;firstConnected=false;constructor(e,t,s,n={}){this.baseUrl=e,this.tokenManager=t,this.anonKey=s,this.options=n;}get isConnected(){return this.socket?.connected===true}get socketId(){return this.socket?.id}channel(e,t){let s=this.channels.get(e);if(s)return s;let n=new $(e,this,t);return this.channels.set(e,n),n}connect(){return this.isConnected?Promise.resolve():this.connecting?this.connecting:(this.connecting=this.openSocket(),this.connecting)}disconnect(){this.socket&&(this.socket.disconnect(),this.socket=null,this.firstConnected=false);}_getSocket(){return this.socket}_detachChannel(e){this.channels.delete(e.topic);}openSocket(){let e=this.tokenManager.getAccessToken()??this.anonKey;if(!e){let n=new c("Realtime requires an access token or anonKey",401,"AUTH_INVALID_API_KEY");return this.connecting=null,Promise.reject(n)}let t=this.options.timeoutMs??fe,s=socket_ioClient.io(this.baseUrl,{path:this.options.path,transports:this.options.transports??["websocket"],auth:{token:e,...this.options.extraAuth??{}},reconnection:true,timeout:t});return this.socket=s,s.onAny((n,...i)=>this.dispatch(n,i)),s.on("connect",()=>{if(this.firstConnected)for(let n of this.channels.values()){let i=n._state();(i==="joined"||i==="errored")&&n._rejoinAfterReconnect();}}),new Promise((n,i)=>{let o=setTimeout(()=>{s.off("connect",d),s.off("connect_error",p),this.connecting=null,i(new c(`Realtime connection timeout after ${t}ms`,408,"CONNECTION_TIMEOUT"));},t),a=()=>{clearTimeout(o),s.off("connect",d),s.off("connect_error",p);},d=()=>{a(),this.connecting=null,this.firstConnected=true,n();},p=v=>{a(),this.connecting=null,i(new c(v.message,0,"CONNECTION_FAILED"));};s.once("connect",d),s.once("connect_error",p);})}dispatch(e,t){if(e==="postgres_changes"){let n=t[0]??{};this.channels.forEach(i=>i._dispatch("postgres_changes",n));return}if(e==="connect"||e==="disconnect"||e==="connect_error"||e==="error"||e==="realtime:error"||e==="realtime:shutdown")return;let s=t[0]??{};this.channels.forEach(n=>n._dispatch(e,s));}};function H(r){return {id:r.id,name:r.name,public:r.public,fileSizeLimitBytes:r.file_size_limit_bytes,allowedMimeTypes:r.allowed_mime_types,createdAt:r.created_at,updatedAt:r.updated_at}}function q(r,e){return {id:r.id,bucket:e,key:r.key,size:r.size,mimeType:r.mime_type,etag:r.etag,cacheControl:r.cache_control,contentDisposition:r.content_disposition,uploadedBy:r.uploaded_by,uploadedAt:r.uploaded_at,updatedAt:r.updated_at}}function me(r){return {defaultFileSizeLimitBytes:r.default_file_size_limit_bytes,maxFileSizeLimitBytes:r.max_file_size_limit_bytes,tenantStorageQuotaBytes:r.tenant_storage_quota_bytes,reservedSpaceBytes:r.reserved_space_bytes,signedUrlDefaultTtlSec:r.signed_url_default_ttl_sec,signedUrlMaxTtlSec:r.signed_url_max_ttl_sec}}function ye(r){return r.split("/").map(encodeURIComponent).join("/")}function h(r,e){return r instanceof c?{data:null,error:r}:{data:null,error:new c(r instanceof Error?r.message:e,0,"STORAGE_ERROR")}}async function Y(r){let e="STORAGE_ERROR",t=`HTTP ${r.status}`;try{let s=await r.json();s&&s.error&&(e=s.error.code??e,t=s.error.message??t);}catch{}return new c(t,r.status,e)}var K=class{constructor(e,t){this.http=e;this.bucketName=t;}http;bucketName;bucketBase(){return `/api/storage/buckets/${encodeURIComponent(this.bucketName)}`}objectPath(e){return `${this.bucketBase()}/objects/${ye(e)}`}async upload(e,t,s={}){try{let n=s.upsert?"PUT":"POST",i={"Content-Type":s.contentType??"application/octet-stream"};s.cacheControl&&(i["Cache-Control"]=s.cacheControl),s.contentDisposition&&(i["Content-Disposition"]=s.contentDisposition);let o=await this.http.rawFetch(this.objectPath(e),{method:n,headers:i,body:t,signal:s.abortSignal});if(!o.ok)return {data:null,error:await Y(o)};let a=await o.json();return a.error||!a.data?{data:null,error:new c(a.error?.message??"Upload failed",o.status,a.error?.code??"STORAGE_ERROR")}:{data:q(a.data,this.bucketName),error:null}}catch(n){return h(n,"Upload failed")}}async download(e,t={}){try{let s={};t.range&&(s.Range=`bytes=${t.range.start}-${t.range.end}`);let n=await this.http.rawFetch(this.objectPath(e),{method:"GET",headers:s,signal:t.abortSignal});return n.ok?{data:await n.blob(),error:null}:{data:null,error:await Y(n)}}catch(s){return h(s,"Download failed")}}async getStream(e,t={}){try{let s={};t.range&&(s.Range=`bytes=${t.range.start}-${t.range.end}`);let n=await this.http.rawFetch(this.objectPath(e),{method:"GET",headers:s,signal:t.abortSignal});return n.ok?n.body?{data:n.body,error:null}:{data:null,error:new c("Response body is not a stream",n.status,"STORAGE_ERROR")}:{data:null,error:await Y(n)}}catch(s){return h(s,"Download failed")}}async remove(e){try{let t=await Promise.allSettled(e.map(i=>this.http.rawFetch(this.objectPath(i),{method:"DELETE"}))),s=[],n=[];for(let i=0;i<e.length;i++){let o=e[i],a=t[i];if(a.status==="fulfilled"&&a.value.ok)s.push(o);else if(a.status==="fulfilled")n.push(`${o}: HTTP ${a.value.status}`);else {let d=a.reason instanceof Error?a.reason.message:String(a.reason);n.push(`${o}: ${d}`);}}return n.length>0?{data:null,error:new c(`Failed to delete some objects: ${n.join("; ")}`,0,"STORAGE_ERROR")}:{data:{removed:s},error:null}}catch(t){return h(t,"Delete failed")}}async list(e={}){try{let t={};return e.prefix!==void 0&&(t.prefix=e.prefix),e.limit!==void 0&&(t.limit=String(e.limit)),e.startAfter!==void 0&&(t.start_after=e.startAfter),{data:(await this.http.get(`${this.bucketBase()}/objects`,{params:t})).map(n=>q(n,this.bucketName)),error:null}}catch(t){return h(t,"List failed")}}async copy(e,t,s){try{let n=await this.http.post(`${this.objectPath(e)}/copy`,{dest_bucket:s??this.bucketName,dest_key:t});return {data:q(n,s??this.bucketName),error:null}}catch(n){return h(n,"Copy failed")}}async move(e,t,s){try{let n=await this.http.post(`${this.objectPath(e)}/move`,{dest_bucket:s??this.bucketName,dest_key:t});return {data:q(n,s??this.bucketName),error:null}}catch(n){return h(n,"Move failed")}}async createSignedUrl(e,t={}){try{let s={};t.expiresIn!==void 0&&(s.expires_in=t.expiresIn);let n=await this.http.post(`${this.objectPath(e)}/sign`,s);return {data:{url:n.url,token:n.token,expiresAt:n.expiresAt},error:null}}catch(s){return h(s,"Sign failed")}}getPublicUrl(e){return {data:{url:`${this.http.baseUrl.replace(/\/$/,"")}${this.objectPath(e)}`}}}},x=class{constructor(e){this.http=e;}http;from(e){return new K(this.http,e)}async listBuckets(){try{return {data:(await this.http.get("/api/storage/buckets")).map(H),error:null}}catch(e){return h(e,"listBuckets failed")}}async getBucket(e){try{let t=await this.http.get(`/api/storage/buckets/${encodeURIComponent(e)}`);return {data:H(t),error:null}}catch(t){return h(t,"getBucket failed")}}async createBucket(e,t={}){try{let s={name:e};t.public!==void 0&&(s.public=t.public),t.fileSizeLimitBytes!==void 0&&(s.file_size_limit_bytes=t.fileSizeLimitBytes),t.allowedMimeTypes!==void 0&&(s.allowed_mime_types=t.allowedMimeTypes);let n=await this.http.post("/api/storage/buckets",s);return {data:H(n),error:null}}catch(s){return h(s,"createBucket failed")}}async updateBucket(e,t){try{let s={};t.public!==void 0&&(s.public=t.public),t.fileSizeLimitBytes!==void 0&&(s.file_size_limit_bytes=t.fileSizeLimitBytes),t.allowedMimeTypes!==void 0&&(s.allowed_mime_types=t.allowedMimeTypes);let n=await this.http.patch(`/api/storage/buckets/${encodeURIComponent(e)}`,s);return {data:H(n),error:null}}catch(s){return h(s,"updateBucket failed")}}async deleteBucket(e){try{return await this.http.delete(`/api/storage/buckets/${encodeURIComponent(e)}`),{data:null,error:null}}catch(t){return h(t,"deleteBucket failed")}}async emptyBucket(e){try{return {data:await this.http.post(`/api/storage/buckets/${encodeURIComponent(e)}/empty`,{}),error:null}}catch(t){return h(t,"emptyBucket failed")}}async getConfig(){try{let e=await this.http.get("/api/storage/config");return {data:me(e),error:null}}catch(e){return h(e,"getConfig failed")}}};function ke(r){return {key:r.key,digest:r.digest,updatedAt:r.updated_at}}function k(r,e){return r instanceof c?{data:null,error:r}:{data:null,error:new c(r instanceof Error?r.message:e,0,"FUNCTIONS_ERROR")}}function Te(r){return typeof r=="object"&&r!==null&&!ArrayBuffer.isView(r)&&!(r instanceof Blob)&&!(r instanceof FormData)&&!(r instanceof URLSearchParams)&&!(r instanceof ReadableStream)}var M=class{constructor(e){this.http=e;}http;async list(){try{return {data:await this.http.get("/api/functions"),error:null}}catch(e){return k(e,"list failed")}}async get(e){try{return {data:await this.http.get(`/api/functions/${encodeURIComponent(e)}`),error:null}}catch(t){return k(t,"get failed")}}async create(e){try{return {data:await this.http.post("/api/functions",e),error:null}}catch(t){return k(t,"create failed")}}async update(e,t){try{return {data:await this.http.put(`/api/functions/${encodeURIComponent(e)}`,t),error:null}}catch(s){return k(s,"update failed")}}async remove(e){try{return await this.http.delete(`/api/functions/${encodeURIComponent(e)}`),{data:{deleted:!0},error:null}}catch(t){return k(t,"remove failed")}}async invoke(e,t={}){try{let s=t.method??"POST",n={...t.headers},i;return t.body!==void 0&&t.body!==null&&(Te(t.body)?(i=JSON.stringify(t.body),n["Content-Type"]||(n["Content-Type"]="application/json")):i=t.body),{data:await this.http.rawFetch(`/api/invoke/${encodeURIComponent(e)}`,{method:s,headers:n,body:i}),error:null}}catch(s){return k(s,"invoke failed")}}async listSecrets(){try{return {data:(await this.http.get("/api/functions/secrets")).secrets.map(ke),error:null}}catch(e){return k(e,"listSecrets failed")}}async setSecrets(e){try{return await this.http.put("/api/functions/secrets",{secrets:e}),{data:{saved:!0},error:null}}catch(t){return k(t,"setSecrets failed")}}async deleteSecret(e){try{return await this.http.delete(`/api/functions/secrets/${encodeURIComponent(e)}`),{data:{deleted:!0},error:null}}catch(t){return k(t,"deleteSecret failed")}}};var C=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function te(r){let e=typeof r=="number"&&Number.isFinite(r)?r:50;return Math.max(1,Math.min(200,Math.trunc(e)))}function be(r){let e=typeof r=="number"&&Number.isFinite(r)?r:100;return Math.max(1,Math.min(500,Math.trunc(e)))}function z(){return {data:null,error:new c("agentId must be a valid UUID",400,"INVALID_INPUT")}}function se(){return {data:null,error:new c("sessionId must be a valid UUID",400,"INVALID_INPUT")}}function E(r,e){return r instanceof c?{data:null,error:r}:{data:null,error:new c(r instanceof Error?r.message:e,0,"AGENTS_ERROR")}}var D=class{constructor(e){this.http=e;}http;async list(e){try{let t=te(e?.limit);return {data:await this.http.get(`/api/agents?limit=${t}`),error:null}}catch(t){return E(t,"list failed")}}async invoke(e,t){if(typeof e!="string"||!C.test(e))return {data:null,error:new c("agentId must be a valid UUID",400,"INVALID_INPUT")};try{let s=t!==void 0?{input:t}:void 0;return {data:await this.http.post(`/api/agents/${encodeURIComponent(e)}/invoke`,s),error:null}}catch(s){return E(s,"invoke failed")}}async chat(e,t,s){if(typeof e!="string"||!C.test(e))return z();try{let n={message:t};s?.sessionId!==void 0&&(n.session_id=s.sessionId),s?.extraContext!==void 0&&(n.extra_context=s.extraContext);let i=await this.http.post(`/api/agents/${encodeURIComponent(e)}/chat`,n);return {data:{sessionId:i.session_id,runId:i.runId,status:i.status,output:i.output,text:i.text,totalTokens:i.totalTokens,totalCost:i.totalCost,error:i.error},error:null}}catch(n){return E(n,"chat failed")}}async listSessions(e,t){if(typeof e!="string"||!C.test(e))return z();try{let s=te(t?.limit);return {data:{sessions:((await this.http.get(`/api/agents/${encodeURIComponent(e)}/sessions?limit=${s}`)).sessions??[]).map(o=>({id:o.id,createdAt:o.created_at,lastActivityAt:o.last_activity_at,messageCount:o.message_count,lastMessagePreview:o.last_message_preview??null}))},error:null}}catch(s){return E(s,"listSessions failed")}}async getMessages(e,t,s){if(typeof e!="string"||!C.test(e))return z();if(typeof t!="string"||!C.test(t))return se();try{let n=be(s?.limit),i=new URLSearchParams;return i.set("limit",String(n)),s?.before!==void 0&&i.set("before",s.before),{data:{messages:((await this.http.get(`/api/agents/${encodeURIComponent(e)}/sessions/${encodeURIComponent(t)}/messages?${i.toString()}`)).messages??[]).map(d=>({id:d.id,role:d.role,content:d.content,createdAt:d.created_at}))},error:null}}catch(n){return E(n,"getMessages failed")}}async deleteSession(e,t){if(typeof e!="string"||!C.test(e))return z();if(typeof t!="string"||!C.test(t))return se();try{return await this.http.delete(`/api/agents/${encodeURIComponent(e)}/sessions/${encodeURIComponent(t)}`),{data:{ok:!0},error:null}}catch(s){return E(s,"deleteSession failed")}}};var _=class{http;tokenManager;auth;database;realtime;storage;functions;agents;constructor(e={}){let t=new R(e.debug);this.tokenManager=new S({persistSession:e.persistSession,storageKey:e.storageKey,storage:e.storage,multiTab:e.multiTab}),this.http=new I(e,this.tokenManager,t),this.auth=new U(this.http,this.tokenManager),this.database=new O(this.http,this.tokenManager,e.anonKey),this.realtime=new B(this.http.baseUrl,this.tokenManager,e.anonKey,e.realtime),this.storage=new x(this.http),this.functions=new M(this.http),this.agents=new D(this.http);}getHttpClient(){return this.http}};function at(r){return new _(r)}var ct=_;
|
|
5
|
-
exports.AgentsModule=
|
|
4
|
+
`));}};var G="mitway_baas_csrf_token",ae="mitway_baas_session";function Z(){return typeof localStorage<"u"?{getItem:e=>{try{return localStorage.getItem(e)}catch{return null}},setItem:(e,t)=>{try{localStorage.setItem(e,t);}catch{}},removeItem:e=>{try{localStorage.removeItem(e);}catch{}}}:{getItem:()=>null,setItem:()=>{},removeItem:()=>{}}}var ce={getItem:()=>null,setItem:()=>{},removeItem:()=>{}};function ee(){if(typeof document>"u")return null;let n=document.cookie.split(";").find(e=>e.trim().startsWith(`${G}=`));return n&&n.split("=")[1]||null}function L(n){if(typeof document>"u")return;let e=10080*60,t=typeof window<"u"&&window.location.protocol==="https:"?"; Secure":"";document.cookie=`${G}=${encodeURIComponent(n)}; path=/; max-age=${e}; SameSite=Lax${t}`;}function $(){if(typeof document>"u")return;let n=typeof window<"u"&&window.location.protocol==="https:"?"; Secure":"";document.cookie=`${G}=; path=/; max-age=0; SameSite=Lax${n}`;}var w=class{accessToken=null;refreshToken=null;user=null;persistSession;storageKey;storage;onTokenChange=null;constructor(e){this.persistSession=e?.persistSession??true,this.storageKey=e?.storageKey??ae,this.storage=this.persistSession?e?.storage??Z():ce,(e?.multiTab??true)&&this.persistSession&&typeof window<"u"&&typeof localStorage<"u"&&window.addEventListener("storage",this.handleStorageEvent),this.restoreSession();}handleStorageEvent=e=>{e.key===this.storageKey&&(typeof localStorage<"u"&&e.storageArea!==localStorage||this.syncFromStorage(e.newValue));};syncFromStorage(e){let t=this.accessToken;if(e===null)this.accessToken=null,this.refreshToken=null,this.user=null;else try{let r=JSON.parse(e);if(!r.accessToken||!r.user)return;this.accessToken=r.accessToken,this.refreshToken=r.refreshToken??null,this.user=r.user;}catch{return}t!==this.accessToken&&this.onTokenChange&&this.onTokenChange();}saveSession(e){let t=e.accessToken!==this.accessToken;this.accessToken=e.accessToken,this.user=e.user,e.refreshToken!==void 0&&(this.refreshToken=e.refreshToken??null),this.persist(),t&&this.onTokenChange&&this.onTokenChange();}getSession(){return !this.accessToken||!this.user?null:{accessToken:this.accessToken,refreshToken:this.refreshToken??void 0,user:this.user}}getAccessToken(){return this.accessToken}setAccessToken(e){let t=e!==this.accessToken;this.accessToken=e,this.persist(),t&&this.onTokenChange&&this.onTokenChange();}getRefreshToken(){return this.refreshToken}setRefreshToken(e){this.refreshToken=e,this.persist();}getUser(){return this.user}setUser(e){this.user=e,this.persist();}clearSession(){let e=this.accessToken!==null;this.accessToken=null,this.refreshToken=null,this.user=null,this.removePersisted(),e&&this.onTokenChange&&this.onTokenChange();}restoreSession(){if(!this.persistSession)return false;try{let e=this.storage.getItem(this.storageKey);if(!e)return !1;let t=JSON.parse(e);return !t.accessToken||!t.user?!1:(this.accessToken=t.accessToken,this.refreshToken=t.refreshToken??null,this.user=t.user,!0)}catch{return false}}persist(){if(!this.persistSession||!this.accessToken||!this.user)return;let e={accessToken:this.accessToken,user:this.user};this.refreshToken&&(e.refreshToken=this.refreshToken),this.storage.setItem(this.storageKey,JSON.stringify(e));}removePersisted(){this.persistSession&&this.storage.removeItem(this.storageKey);}};function A(n){if(!n||typeof n!="object")return n;let e=n,t={...e},r=false;return "access_token"in e&&!("accessToken"in e)&&(t.accessToken=e.access_token,delete t.access_token,r=true),"csrf_token"in e&&!("csrfToken"in e)&&(t.csrfToken=e.csrf_token,delete t.csrf_token,r=true),"refresh_token"in e&&!("refreshToken"in e)&&(t.refreshToken=e.refresh_token,delete t.refresh_token,r=true),r?t:n}var le=new Set([500,502,503,504]),ue=new Set(["GET","HEAD","PUT","DELETE","OPTIONS"]),O=class{baseUrl;fetch;defaultHeaders;anonKey;userToken=null;logger;autoRefreshToken=true;isRefreshing=false;refreshPromise=null;tokenManager;refreshToken=null;timeout;retryCount;retryDelay;constructor(e,t,r){if(this.baseUrl=e.baseUrl||"http://localhost:7130",this.autoRefreshToken=e.autoRefreshToken??true,this.fetch=e.fetch||(globalThis.fetch?globalThis.fetch.bind(globalThis):void 0),this.anonKey=e.anonKey,this.defaultHeaders={...e.headers},this.tokenManager=t??new w,this.logger=r||new R(false),this.timeout=e.timeout??3e4,this.retryCount=e.retryCount??3,this.retryDelay=e.retryDelay??500,!this.fetch)throw new Error("Fetch is not available. Provide a fetch implementation in the SDK config.")}buildUrl(e,t){let r=new URL(e,this.baseUrl);return t&&Object.entries(t).forEach(([s,i])=>{if(s==="select"){let o=i.replace(/\s+/g," ").trim();o=o.replace(/\s*\(\s*/g,"(").replace(/\s*\)\s*/g,")").replace(/\(\s+/g,"(").replace(/\s+\)/g,")").replace(/,\s+(?=[^()]*\))/g,","),r.searchParams.append(s,o);}else r.searchParams.append(s,i);}),r.toString()}isRetryableStatus(e){return le.has(e)}computeRetryDelay(e){let r=this.retryDelay*Math.pow(2,e-1)*(.85+Math.random()*.3);return Math.round(r)}async handleRequest(e,t,r={}){let{params:s,headers:i={},body:o,signal:a,...d}=r,p=this.buildUrl(t,s),C=Date.now(),b=ue.has(e.toUpperCase())||r.idempotent===true?this.retryCount:0,S={...this.defaultHeaders},Q=this.userToken||this.anonKey;Q&&(S.Authorization=`Bearer ${Q}`);let N;o!==void 0&&(typeof FormData<"u"&&o instanceof FormData?N=o:(e!=="GET"&&(S["Content-Type"]="application/json;charset=UTF-8"),N=JSON.stringify(o))),i instanceof Headers?i.forEach((f,g)=>{S[g]=f;}):Array.isArray(i)?i.forEach(([f,g])=>{S[f]=g;}):Object.assign(S,i),this.logger.logRequest(e,p,S,N);let W;for(let f=0;f<=b;f++){if(f>0){let l=this.computeRetryDelay(f);if(this.logger.warn(`Retry ${f}/${b} for ${e} ${p} in ${l}ms`),a?.aborted)throw a.reason;await new Promise((u,J)=>{let y=()=>{clearTimeout(se),J(a.reason);},se=setTimeout(()=>{a&&a.removeEventListener("abort",y),u();},l);a&&a.addEventListener("abort",y,{once:true});});}let g,m;if((this.timeout>0||a)&&(g=new AbortController,this.timeout>0&&(m=setTimeout(()=>g.abort(),this.timeout)),a))if(a.aborted)g.abort(a.reason);else {let l=()=>g.abort(a.reason);a.addEventListener("abort",l,{once:true}),g.signal.addEventListener("abort",()=>{a.removeEventListener("abort",l);},{once:true});}try{let l=await this.fetch(p,{method:e,headers:S,body:N,...d,...g?{signal:g.signal}:{}});if(this.isRetryableStatus(l.status)&&f<b){m!==void 0&&clearTimeout(m),await l.body?.cancel(),W=new c(`Server error: ${l.status} ${l.statusText}`,l.status,"SERVER_ERROR");continue}if(l.status===204){m!==void 0&&clearTimeout(m);return}let u,J=l.headers.get("content-type");try{J?.includes("json")?u=await l.json():u=await l.text();}catch(y){throw m!==void 0&&clearTimeout(m),new c(`Failed to parse response body: ${y?.message||"Unknown error"}`,l.status,l.ok?"PARSE_ERROR":"REQUEST_FAILED")}if(m!==void 0&&clearTimeout(m),!l.ok){if(this.logger.logResponse(e,p,l.status,Date.now()-C,u),u&&typeof u=="object"&&"error"in u&&u.error!==null&&typeof u.error=="object"){let y=u.error;throw new c(y.message||l.statusText||"Request failed",y.statusCode||l.status,y.code||y.error||"REQUEST_FAILED",y.nextActions)}throw new c(`Request failed: ${l.statusText}`,l.status,"REQUEST_FAILED")}return this.logger.logResponse(e,p,l.status,Date.now()-C,u),u&&typeof u=="object"&&"data"in u&&"error"in u&&u.error===null?u.data:u}catch(l){if(m!==void 0&&clearTimeout(m),l?.name==="AbortError")throw g&&g.signal.aborted&&this.timeout>0&&!a?.aborted?new c(`Request timed out after ${this.timeout}ms`,408,"REQUEST_TIMEOUT"):l;if(l instanceof c)throw l;if(f<b){W=l;continue}throw new c(`Network request failed: ${l?.message||"Unknown error"}`,0,"NETWORK_ERROR")}}throw W||new c("Request failed after all retry attempts",0,"NETWORK_ERROR")}async request(e,t,r={}){try{return await this.handleRequest(e,t,{...r})}catch(s){if(s instanceof c&&s.statusCode===401&&this.autoRefreshToken&&this.refreshToken&&!t.includes("/api/auth/refresh"))try{let i=await this.handleTokenRefresh();this.setAuthToken(i.accessToken),i.refreshToken&&this.setRefreshToken(i.refreshToken),i.csrfToken&&L(i.csrfToken);let o=i.user??this.tokenManager.getUser();return o&&this.tokenManager.saveSession({accessToken:i.accessToken,refreshToken:i.refreshToken,user:o}),await this.handleRequest(e,t,{...r})}catch(i){throw this.tokenManager.clearSession(),this.userToken=null,this.refreshToken=null,$(),i}throw s}}async rawFetch(e,t={}){let r=this.buildUrl(e),s=new Headers(t.headers??{});for(let[i,o]of Object.entries(this.defaultHeaders))s.has(i)||s.set(i,o);if(!s.has("Authorization")){let i=this.userToken??this.anonKey;i&&s.set("Authorization",`Bearer ${i}`);}return this.fetch(r,{...t,headers:s})}get(e,t){return this.request("GET",e,t)}post(e,t,r){return this.request("POST",e,{...r,body:t})}put(e,t,r){return this.request("PUT",e,{...r,body:t})}patch(e,t,r){return this.request("PATCH",e,{...r,body:t})}delete(e,t){return this.request("DELETE",e,t)}setAuthToken(e){this.userToken=e;}setRefreshToken(e){this.refreshToken=e;}getHeaders(){let e={...this.defaultHeaders},t=this.userToken||this.anonKey;return t&&(e.Authorization=`Bearer ${t}`),e}async handleTokenRefresh(){return this.isRefreshing?this.refreshPromise:(this.isRefreshing=true,this.refreshPromise=(async()=>{try{let e=ee(),t=this.refreshToken?{refreshToken:this.refreshToken}:void 0,r=await this.handleRequest("POST","/api/auth/refresh",{body:t,headers:e?{"X-CSRF-Token":e}:{},credentials:"include"});return A(r)}finally{this.isRefreshing=false,this.refreshPromise=null;}})(),this.refreshPromise)}};function k(n,e){return n instanceof c?{data:null,error:n}:{data:null,error:new c(n instanceof Error?n.message:e,500,"AUTH_ERROR")}}var I=class{constructor(e,t){this.http=e;this.tokenManager=t;this.tokenManager.onTokenChange=()=>this._emitFromTokenChange();let r=this.tokenManager.getSession();if(r){this.http.setAuthToken(r.accessToken);let s=this.tokenManager.getRefreshToken();s&&this.http.setRefreshToken(s),this.lastEmittedUserId=r.user.id,this.lastEmittedAccessToken=r.accessToken;}}http;tokenManager;stateChangeListeners=new Set;lastEmittedUserId=null;lastEmittedAccessToken=null;onAuthStateChange(e){return this.stateChangeListeners.add(e),{unsubscribe:()=>{this.stateChangeListeners.delete(e);}}}emit(e,t){for(let r of this.stateChangeListeners)try{r(e,t);}catch{}}_emitFromTokenChange(){let e=this.tokenManager.getSession();e?(this.http.setAuthToken(e.accessToken),this.http.setRefreshToken(e.refreshToken??null)):(this.http.setAuthToken(null),this.http.setRefreshToken(null));let t=this.lastEmittedUserId,r=this.lastEmittedAccessToken;if(!e){t!==null&&(this.lastEmittedUserId=null,this.lastEmittedAccessToken=null,this.emit("SIGNED_OUT",null));return}let s=e.user.id;if(t===null){this.lastEmittedUserId=s,this.lastEmittedAccessToken=e.accessToken,this.emit("SIGNED_IN",e);return}if(t!==s){this.lastEmittedUserId=null,this.lastEmittedAccessToken=null,this.emit("SIGNED_OUT",null),this.lastEmittedUserId=s,this.lastEmittedAccessToken=e.accessToken,this.emit("SIGNED_IN",e);return}r!==e.accessToken&&(this.lastEmittedAccessToken=e.accessToken,this.emit("TOKEN_REFRESHED",e));}saveSessionFromResponse(e){let t={accessToken:e.accessToken,refreshToken:e.refreshToken,user:e.user};e.csrfToken&&L(e.csrfToken),this.tokenManager.saveSession(t),this.http.setAuthToken(e.accessToken),this.http.setRefreshToken(e.refreshToken??null);}async signUp(e){try{let t=await this.http.post("/api/auth/register",e,{credentials:"include"}),r=A(t);return r?.accessToken&&r.user&&this.saveSessionFromResponse(r),{data:r,error:null}}catch(t){return k(t,"Sign up failed")}}async signInWithPassword(e){try{let t=await this.http.post("/api/auth/login",e,{credentials:"include"}),r=A(t);return r?.accessToken&&r.user&&this.saveSessionFromResponse(r),{data:r,error:null}}catch(t){return k(t,"Sign in failed")}}async setSession(e){let t={accessToken:e.access_token,refreshToken:e.refresh_token??void 0,user:e.user};return this.saveSessionFromResponse(t),{data:t,error:null}}async getSSOConfig(){try{return {data:await this.http.get("/api/auth/sso/config"),error:null}}catch(e){return k(e,"Failed to load SSO config")}}async signInWithSSO(e,t){try{if(typeof window>"u")throw new Error("signInWithSSO requires a browser");let{data:r,error:s}=await this.getSSOConfig();if(s||!r)return {data:null,error:s??new c("SSO config unavailable",500,"SSO_ERROR")};if(!r.broker_url)throw new Error("SSO broker not configured for this tenant");let i=r.providers.find(a=>a.provider===e);if(!i||!i.enabled)throw new Error(`Provider '${e}' is not enabled`);let o=new URL(`${r.broker_url.replace(/\/$/,"")}/api/oauth/${e}/login`);return r.tenant_slug&&o.searchParams.set("tenant",r.tenant_slug),r.tenant_env&&o.searchParams.set("env",r.tenant_env),o.searchParams.set("returnUrl",t.returnUrl),window.location.assign(o.toString()),{data:null,error:null}}catch(r){return k(r,"SSO sign-in failed")}}async completeSSO(){try{if(typeof globalThis.fetch>"u")throw new Error("completeSSO requires fetch");let{data:e,error:t}=await this.getSSOConfig();if(t||!e?.broker_url)throw new Error("SSO broker not configured");let r=await globalThis.fetch(`${e.broker_url.replace(/\/$/,"")}/api/oauth/microsoft/exchange`,{method:"POST",credentials:"include"}),s=await r.json().catch(()=>({}));if(!r.ok||s.error)throw new Error(s.error?.message??"SSO exchange failed");if(!s.data)throw new Error("SSO exchange returned no session");let{access_token:i,refresh_token:o,user:a}=s.data;return this.setSession({access_token:i,refresh_token:o,user:a})}catch(e){return k(e,"SSO completion failed")}}async signOut(){try{try{await this.http.post("/api/auth/logout",void 0,{credentials:"include"});}catch{}return this.tokenManager.clearSession(),this.http.setAuthToken(null),this.http.setRefreshToken(null),$(),{error:null}}catch{return {error:new c("Failed to sign out",500,"SIGNOUT_ERROR")}}}async refreshSession(){try{let e=await this.http.handleTokenRefresh();if(e?.accessToken){let t=e.user??this.tokenManager.getUser();if(t){let r={...e,user:t};return this.saveSessionFromResponse(r),{data:r,error:null}}}return {data:e,error:null}}catch(e){return k(e,"Session refresh failed")}}async initialize(){let e=this.tokenManager.getSession();if(!e)return this.emit("INITIAL_SESSION",null),{data:null,error:new c("No persisted session",0,"NO_SESSION")};try{let t=await this.http.get("/api/auth/sessions/current");if(t?.user){this.tokenManager.setUser(t.user);let r=this.tokenManager.getSession();return this.emit("INITIAL_SESSION",r),{data:{user:t.user,accessToken:e.accessToken},error:null}}return this.tokenManager.clearSession(),this.http.setAuthToken(null),this.http.setRefreshToken(null),this.emit("INITIAL_SESSION",null),{data:null,error:new c("Invalid session",401,"INVALID_SESSION")}}catch(t){return this.tokenManager.clearSession(),this.http.setAuthToken(null),this.http.setRefreshToken(null),this.emit("INITIAL_SESSION",null),k(t,"Session restore failed")}}getSession(){return this.tokenManager.getSession()}getUser(){return this.tokenManager.getUser()}async getCurrentUser(){try{let e=await this.http.get("/api/auth/sessions/current");if(e?.user){let t={accessToken:this.tokenManager.getSession()?.accessToken??"",user:e.user};this.tokenManager.saveSession(t);}return {data:e,error:null}}catch(e){return k(e,"Failed to get current user")}}async getProfile(e){try{return {data:await this.http.get(`/api/auth/profiles/${encodeURIComponent(e)}`),error:null}}catch(t){return k(t,"Failed to get profile")}}async setProfile(e){try{let t=await this.http.patch("/api/auth/profiles/current",{profile:e}),r=this.tokenManager.getUser();if(t?.profile&&r){let s={...r,profile:t.profile};this.tokenManager.setUser(s),this.emit("USER_UPDATED",this.tokenManager.getSession());}return {data:t,error:null}}catch(t){return k(t,"Failed to update profile")}}};function he(n,e,t){return async(r,s)=>{let i=typeof r=="string"?r:r.toString(),o=new URL(i),a=o.pathname.startsWith("/")?o.pathname.slice(1):o.pathname,d=a.match(/^rpc\/(.+)$/),p=d?`/api/database/rpc/${d[1]}`:`/api/database/records/${a}`,C=`${n.baseUrl}${p}${o.search}`,D=new Headers(s?.headers);if(!D.has("Authorization")){let b=e.getAccessToken()??t;b&&D.set("Authorization",`Bearer ${b}`);}return fetch(C,{...s,headers:D})}}var U=class{postgrest;httpClient;constructor(e,t,r){this.httpClient=e,this.postgrest=new postgrestJs.PostgrestClient("http://dummy",{fetch:he(e,t,r),headers:{}});}from(e){if(!e||typeof e!="string")throw new c("Database.from(table) requires a non-empty string",400,"INVALID_TABLE_NAME");return this.postgrest.from(e)}rpc(e,t,r){return this.postgrest.rpc(e,t,r)}getUrl(){return this.httpClient.baseUrl}};var pe=2e4;function V(n,e){let t=new Error(e);return t.code=n,t}var fe=1e4,j=class{constructor(e,t,r={}){this.topic=e;this.realtime=t;this.options=r;}topic;realtime;bindings=[];state="closed";statusCallback=null;presence={};trackedState=null;presenceHeartbeat=null;lastBroadcastTimestamp=null;options;get isPrivate(){return this.options.config?.private===true}get presenceKey(){return this.options.config?.presence?.key}_state(){return this.state}async _rejoinAfterReconnect(){if(this.state!=="closed"){for(let e of this.bindings)e.type==="postgres_changes"&&(e.subscriptionId=void 0);this.state="joining";try{if(await this.registerAllBindings(),this.trackedState){let e=this.realtime._getSocket(),t=this.presenceKey;e?.emit("realtime:presence:track",t!==void 0?{channel:this.topic,state:this.trackedState,key:t}:{channel:this.topic,state:this.trackedState});}this.lastBroadcastTimestamp&&this.bindings.some(e=>e.type==="broadcast")&&this.replay({since:this.lastBroadcastTimestamp}).catch(()=>{}),this.state="joined",this.statusCallback?.("SUBSCRIBED");}catch(e){this.state="errored",this.statusCallback?.("CHANNEL_ERROR",V("REJOIN_FAILED",e instanceof Error?e.message:String(e)));}}}on(e,t,r){return e==="postgres_changes"?this.bindings.push({type:"postgres_changes",filter:t,callback:r}):e==="broadcast"?this.bindings.push({type:"broadcast",filter:t,callback:r}):this.bindings.push({type:"presence",filter:t,callback:r}),this}async track(e){let t=this.realtime._getSocket();if(!t)throw new c("Socket not connected",503,"NOT_CONNECTED");this.trackedState=e;let r=this.presenceKey;t.emit("realtime:presence:track",r!==void 0?{channel:this.topic,state:e,key:r}:{channel:this.topic,state:e}),this.presenceHeartbeat||(this.presenceHeartbeat=setInterval(()=>{let i=this.realtime._getSocket();i&&this.trackedState&&i.emit("realtime:presence:track",r!==void 0?{channel:this.topic,state:this.trackedState,key:r}:{channel:this.topic,state:this.trackedState});},pe),this.presenceHeartbeat.unref?.());}untrack(){this.trackedState=null,this.presenceHeartbeat&&(clearInterval(this.presenceHeartbeat),this.presenceHeartbeat=null),this.realtime._getSocket()?.emit("realtime:presence:untrack",{channel:this.topic});}presenceState(){return this.presence}subscribe(e){return this.statusCallback=e??null,this.state==="joining"||this.state==="joined"?this:(this.state="joining",this.realtime.connect().then(async()=>{try{await this.registerAllBindings(),this.state="joined",this.statusCallback?.("SUBSCRIBED");}catch(t){this.state="errored";let r=t instanceof Error?t.message:String(t);this.statusCallback?.("CHANNEL_ERROR",V("SUBSCRIBE_FAILED",r));}},t=>{this.state="errored",this.statusCallback?.("CHANNEL_ERROR",V("CONNECT_FAILED",t.message));}),this)}async unsubscribe(){if(this.state==="closed")return;let e=this.realtime._getSocket();if(this.presenceHeartbeat&&(clearInterval(this.presenceHeartbeat),this.presenceHeartbeat=null),!e){this.trackedState=null,this.state="closed";return}this.trackedState&&(e.emit("realtime:presence:untrack",{channel:this.topic}),this.trackedState=null);let t=this.bindings.filter(r=>r.type==="postgres_changes");for(let r of t)r.subscriptionId&&(e.emit("realtime:postgres_changes:unsubscribe",{subscription_id:r.subscriptionId}),r.subscriptionId=void 0);this.bindings.some(r=>r.type==="broadcast"||r.type==="presence")&&e.emit("realtime:unsubscribe",{channel:this.topic}),this.realtime._detachChannel(this),this.state="closed",this.statusCallback?.("CLOSED");}async send(e){if(e.type!=="broadcast")throw new c('Only "broadcast" sends are supported \u2014 DB changes flow via your DB writes, not channel.send()',400,"UNSUPPORTED_SEND_TYPE");if(new Set(["postgres_changes","presence_state","presence_join","presence_leave"]).has(e.event))throw new c(`"${e.event}" is a reserved event name \u2014 pick a different name for broadcast events`,400,"RESERVED_EVENT_NAME");let r=this.realtime._getSocket();if(!r)throw new c("Socket not connected",503,"NOT_CONNECTED");let s=this.options.config?.broadcast?.self,i={channel:this.topic,event:e.event,payload:e.payload};return s===false&&(i.self=false),await new Promise(o=>{r.emit("realtime:publish",i,a=>{o(a);});})}async replay(e){let t=this.realtime._getSocket();if(!t)throw new c("Socket not connected",503,"NOT_CONNECTED");t.emit("realtime:broadcast:replay",{channel:this.topic,since:e.since,limit:e.limit,private:this.isPrivate});}_dispatch(e,t){if(e==="postgres_changes"){let s=t;for(let i of this.bindings)if(!(i.type!=="postgres_changes"||!i.subscriptionId||!s.ids.includes(i.subscriptionId)||!(i.filter.event==="*"||i.filter.event===s.data.eventType)))try{i.callback(s.data);}catch{}return}if(e==="presence_state"||e==="presence_join"||e==="presence_leave"){let s=t;if(s.channel!==this.topic)return;if(e==="presence_state"&&s.state)this.presence={...s.state},this.firePresence({event:"sync",state:this.presence});else if(e==="presence_join"&&s.joins)Object.assign(this.presence,s.joins),this.firePresence({event:"join",joins:s.joins});else if(e==="presence_leave"&&s.leaves){for(let i of Object.keys(s.leaves))delete this.presence[i];this.firePresence({event:"leave",leaves:s.leaves});}return}let r=t.meta;r?.timestamp&&(!this.lastBroadcastTimestamp||r.timestamp>this.lastBroadcastTimestamp)&&(this.lastBroadcastTimestamp=r.timestamp);for(let s of this.bindings){if(s.type!=="broadcast"||s.filter.event!==e)continue;let{meta:i,...o}=t;try{s.callback({type:"broadcast",event:e,payload:o});}catch{}}}firePresence(e){for(let t of this.bindings)if(t.type==="presence"&&t.filter.event===e.event)try{e.event==="sync"?t.callback():(e.event,t.callback(e));}catch{}}async registerAllBindings(){let e=this.realtime._getSocket();if(!e)throw new Error("Socket not available");this.bindings.some(s=>s.type==="broadcast"||s.type==="presence")&&await new Promise((s,i)=>{e.emit("realtime:subscribe",{channel:this.topic,private:this.isPrivate},o=>{o.status==="ok"?s():i(new Error(o.error?.message??"subscribe failed"));});});let r=this.bindings.filter(s=>s.type==="postgres_changes");await Promise.all(r.map(s=>new Promise((i,o)=>{e.emit("realtime:postgres_changes:subscribe",{event:s.filter.event,schema:s.filter.schema??"public",table:s.filter.table,filter:s.filter.filter},a=>{a.status==="ok"&&a.subscription_id?(s.subscriptionId=a.subscription_id,i()):o(new Error(a.error?.message??"postgres_changes subscribe failed"));});})));}},B=class{socket=null;baseUrl;options;anonKey;tokenManager;channels=new Map;connecting=null;firstConnected=false;constructor(e,t,r,s={}){this.baseUrl=e,this.tokenManager=t,this.anonKey=r,this.options=s;}get isConnected(){return this.socket?.connected===true}get socketId(){return this.socket?.id}channel(e,t){let r=this.channels.get(e);if(r)return r;let s=new j(e,this,t);return this.channels.set(e,s),s}connect(){return this.isConnected?Promise.resolve():this.connecting?this.connecting:(this.connecting=this.openSocket(),this.connecting)}disconnect(){this.socket&&(this.socket.disconnect(),this.socket=null,this.firstConnected=false);}_getSocket(){return this.socket}_detachChannel(e){this.channels.delete(e.topic);}openSocket(){let e=this.tokenManager.getAccessToken()??this.anonKey;if(!e){let s=new c("Realtime requires an access token or anonKey",401,"AUTH_INVALID_API_KEY");return this.connecting=null,Promise.reject(s)}let t=this.options.timeoutMs??fe,r=socket_ioClient.io(this.baseUrl,{path:this.options.path,transports:this.options.transports??["websocket"],auth:{token:e,...this.options.extraAuth??{}},reconnection:true,timeout:t});return this.socket=r,r.onAny((s,...i)=>this.dispatch(s,i)),r.on("connect",()=>{if(this.firstConnected)for(let s of this.channels.values()){let i=s._state();(i==="joined"||i==="errored")&&s._rejoinAfterReconnect();}}),new Promise((s,i)=>{let o=setTimeout(()=>{r.off("connect",d),r.off("connect_error",p),this.connecting=null,i(new c(`Realtime connection timeout after ${t}ms`,408,"CONNECTION_TIMEOUT"));},t),a=()=>{clearTimeout(o),r.off("connect",d),r.off("connect_error",p);},d=()=>{a(),this.connecting=null,this.firstConnected=true,s();},p=C=>{a(),this.connecting=null,i(new c(C.message,0,"CONNECTION_FAILED"));};r.once("connect",d),r.once("connect_error",p);})}dispatch(e,t){if(e==="postgres_changes"){let s=t[0]??{};this.channels.forEach(i=>i._dispatch("postgres_changes",s));return}if(e==="connect"||e==="disconnect"||e==="connect_error"||e==="error"||e==="realtime:error"||e==="realtime:shutdown")return;let r=t[0]??{};this.channels.forEach(s=>s._dispatch(e,r));}};function q(n){return {id:n.id,name:n.name,public:n.public,fileSizeLimitBytes:n.file_size_limit_bytes,allowedMimeTypes:n.allowed_mime_types,createdAt:n.created_at,updatedAt:n.updated_at}}function H(n,e){return {id:n.id,bucket:e,key:n.key,size:n.size,mimeType:n.mime_type,etag:n.etag,cacheControl:n.cache_control,contentDisposition:n.content_disposition,uploadedBy:n.uploaded_by,uploadedAt:n.uploaded_at,updatedAt:n.updated_at}}function me(n){return {defaultFileSizeLimitBytes:n.default_file_size_limit_bytes,maxFileSizeLimitBytes:n.max_file_size_limit_bytes,tenantStorageQuotaBytes:n.tenant_storage_quota_bytes,reservedSpaceBytes:n.reserved_space_bytes,signedUrlDefaultTtlSec:n.signed_url_default_ttl_sec,signedUrlMaxTtlSec:n.signed_url_max_ttl_sec}}function ye(n){return n.split("/").map(encodeURIComponent).join("/")}function h(n,e){return n instanceof c?{data:null,error:n}:{data:null,error:new c(n instanceof Error?n.message:e,0,"STORAGE_ERROR")}}async function Y(n){let e="STORAGE_ERROR",t=`HTTP ${n.status}`;try{let r=await n.json();r&&r.error&&(e=r.error.code??e,t=r.error.message??t);}catch{}return new c(t,n.status,e)}var K=class{constructor(e,t){this.http=e;this.bucketName=t;}http;bucketName;bucketBase(){return `/api/storage/buckets/${encodeURIComponent(this.bucketName)}`}objectPath(e){return `${this.bucketBase()}/objects/${ye(e)}`}async upload(e,t,r={}){try{let s=r.upsert?"PUT":"POST",i={"Content-Type":r.contentType??"application/octet-stream"};r.cacheControl&&(i["Cache-Control"]=r.cacheControl),r.contentDisposition&&(i["Content-Disposition"]=r.contentDisposition);let o=await this.http.rawFetch(this.objectPath(e),{method:s,headers:i,body:t,signal:r.abortSignal});if(!o.ok)return {data:null,error:await Y(o)};let a=await o.json();return a.error||!a.data?{data:null,error:new c(a.error?.message??"Upload failed",o.status,a.error?.code??"STORAGE_ERROR")}:{data:H(a.data,this.bucketName),error:null}}catch(s){return h(s,"Upload failed")}}async download(e,t={}){try{let r={};t.range&&(r.Range=`bytes=${t.range.start}-${t.range.end}`);let s=await this.http.rawFetch(this.objectPath(e),{method:"GET",headers:r,signal:t.abortSignal});return s.ok?{data:await s.blob(),error:null}:{data:null,error:await Y(s)}}catch(r){return h(r,"Download failed")}}async getStream(e,t={}){try{let r={};t.range&&(r.Range=`bytes=${t.range.start}-${t.range.end}`);let s=await this.http.rawFetch(this.objectPath(e),{method:"GET",headers:r,signal:t.abortSignal});return s.ok?s.body?{data:s.body,error:null}:{data:null,error:new c("Response body is not a stream",s.status,"STORAGE_ERROR")}:{data:null,error:await Y(s)}}catch(r){return h(r,"Download failed")}}async remove(e){try{let t=await Promise.allSettled(e.map(i=>this.http.rawFetch(this.objectPath(i),{method:"DELETE"}))),r=[],s=[];for(let i=0;i<e.length;i++){let o=e[i],a=t[i];if(a.status==="fulfilled"&&a.value.ok)r.push(o);else if(a.status==="fulfilled")s.push(`${o}: HTTP ${a.value.status}`);else {let d=a.reason instanceof Error?a.reason.message:String(a.reason);s.push(`${o}: ${d}`);}}return s.length>0?{data:null,error:new c(`Failed to delete some objects: ${s.join("; ")}`,0,"STORAGE_ERROR")}:{data:{removed:r},error:null}}catch(t){return h(t,"Delete failed")}}async list(e={}){try{let t={};return e.prefix!==void 0&&(t.prefix=e.prefix),e.limit!==void 0&&(t.limit=String(e.limit)),e.startAfter!==void 0&&(t.start_after=e.startAfter),{data:(await this.http.get(`${this.bucketBase()}/objects`,{params:t})).map(s=>H(s,this.bucketName)),error:null}}catch(t){return h(t,"List failed")}}async copy(e,t,r){try{let s=await this.http.post(`${this.objectPath(e)}/copy`,{dest_bucket:r??this.bucketName,dest_key:t});return {data:H(s,r??this.bucketName),error:null}}catch(s){return h(s,"Copy failed")}}async move(e,t,r){try{let s=await this.http.post(`${this.objectPath(e)}/move`,{dest_bucket:r??this.bucketName,dest_key:t});return {data:H(s,r??this.bucketName),error:null}}catch(s){return h(s,"Move failed")}}async createSignedUrl(e,t={}){try{let r={};t.expiresIn!==void 0&&(r.expires_in=t.expiresIn);let s=await this.http.post(`${this.objectPath(e)}/sign`,r);return {data:{url:s.url,token:s.token,expiresAt:s.expiresAt},error:null}}catch(r){return h(r,"Sign failed")}}getPublicUrl(e){return {data:{url:`${this.http.baseUrl.replace(/\/$/,"")}${this.objectPath(e)}`}}}},x=class{constructor(e){this.http=e;}http;from(e){return new K(this.http,e)}async listBuckets(){try{return {data:(await this.http.get("/api/storage/buckets")).map(q),error:null}}catch(e){return h(e,"listBuckets failed")}}async getBucket(e){try{let t=await this.http.get(`/api/storage/buckets/${encodeURIComponent(e)}`);return {data:q(t),error:null}}catch(t){return h(t,"getBucket failed")}}async createBucket(e,t={}){try{let r={name:e};t.public!==void 0&&(r.public=t.public),t.fileSizeLimitBytes!==void 0&&(r.file_size_limit_bytes=t.fileSizeLimitBytes),t.allowedMimeTypes!==void 0&&(r.allowed_mime_types=t.allowedMimeTypes);let s=await this.http.post("/api/storage/buckets",r);return {data:q(s),error:null}}catch(r){return h(r,"createBucket failed")}}async updateBucket(e,t){try{let r={};t.public!==void 0&&(r.public=t.public),t.fileSizeLimitBytes!==void 0&&(r.file_size_limit_bytes=t.fileSizeLimitBytes),t.allowedMimeTypes!==void 0&&(r.allowed_mime_types=t.allowedMimeTypes);let s=await this.http.patch(`/api/storage/buckets/${encodeURIComponent(e)}`,r);return {data:q(s),error:null}}catch(r){return h(r,"updateBucket failed")}}async deleteBucket(e){try{return await this.http.delete(`/api/storage/buckets/${encodeURIComponent(e)}`),{data:null,error:null}}catch(t){return h(t,"deleteBucket failed")}}async emptyBucket(e){try{return {data:await this.http.post(`/api/storage/buckets/${encodeURIComponent(e)}/empty`,{}),error:null}}catch(t){return h(t,"emptyBucket failed")}}async getConfig(){try{let e=await this.http.get("/api/storage/config");return {data:me(e),error:null}}catch(e){return h(e,"getConfig failed")}}};function ke(n){return {key:n.key,digest:n.digest,updatedAt:n.updated_at}}function T(n,e){return n instanceof c?{data:null,error:n}:{data:null,error:new c(n instanceof Error?n.message:e,0,"FUNCTIONS_ERROR")}}function Te(n){return typeof n=="object"&&n!==null&&!ArrayBuffer.isView(n)&&!(n instanceof Blob)&&!(n instanceof FormData)&&!(n instanceof URLSearchParams)&&!(n instanceof ReadableStream)}var M=class{constructor(e){this.http=e;}http;async list(){try{return {data:await this.http.get("/api/functions"),error:null}}catch(e){return T(e,"list failed")}}async get(e){try{return {data:await this.http.get(`/api/functions/${encodeURIComponent(e)}`),error:null}}catch(t){return T(t,"get failed")}}async create(e){try{return {data:await this.http.post("/api/functions",e),error:null}}catch(t){return T(t,"create failed")}}async update(e,t){try{return {data:await this.http.put(`/api/functions/${encodeURIComponent(e)}`,t),error:null}}catch(r){return T(r,"update failed")}}async remove(e){try{return await this.http.delete(`/api/functions/${encodeURIComponent(e)}`),{data:{deleted:!0},error:null}}catch(t){return T(t,"remove failed")}}async invoke(e,t={}){try{let r=t.method??"POST",s={...t.headers},i;return t.body!==void 0&&t.body!==null&&(Te(t.body)?(i=JSON.stringify(t.body),s["Content-Type"]||(s["Content-Type"]="application/json")):i=t.body),{data:await this.http.rawFetch(`/api/invoke/${encodeURIComponent(e)}`,{method:r,headers:s,body:i}),error:null}}catch(r){return T(r,"invoke failed")}}async listSecrets(){try{return {data:(await this.http.get("/api/functions/secrets")).secrets.map(ke),error:null}}catch(e){return T(e,"listSecrets failed")}}async setSecrets(e){try{return await this.http.put("/api/functions/secrets",{secrets:e}),{data:{saved:!0},error:null}}catch(t){return T(t,"setSecrets failed")}}async deleteSecret(e){try{return await this.http.delete(`/api/functions/secrets/${encodeURIComponent(e)}`),{data:{deleted:!0},error:null}}catch(t){return T(t,"deleteSecret failed")}}};var v=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function te(n){let e=typeof n=="number"&&Number.isFinite(n)?n:50;return Math.max(1,Math.min(200,Math.trunc(e)))}function be(n){let e=typeof n=="number"&&Number.isFinite(n)?n:100;return Math.max(1,Math.min(500,Math.trunc(e)))}function z(){return {data:null,error:new c("agentId must be a valid UUID",400,"INVALID_INPUT")}}function re(){return {data:null,error:new c("sessionId must be a valid UUID",400,"INVALID_INPUT")}}function E(n,e){return n instanceof c?{data:null,error:n}:{data:null,error:new c(n instanceof Error?n.message:e,0,"AGENTS_ERROR")}}var F=class{constructor(e){this.http=e;}http;async list(e){try{let t=te(e?.limit);return {data:await this.http.get(`/api/agents?limit=${t}`),error:null}}catch(t){return E(t,"list failed")}}async invoke(e,t){if(typeof e!="string"||!v.test(e))return {data:null,error:new c("agentId must be a valid UUID",400,"INVALID_INPUT")};try{let r=t!==void 0?{input:t}:void 0;return {data:await this.http.post(`/api/agents/${encodeURIComponent(e)}/invoke`,r),error:null}}catch(r){return E(r,"invoke failed")}}async chat(e,t,r){if(typeof e!="string"||!v.test(e))return z();try{let s={message:t};r?.sessionId!==void 0&&(s.session_id=r.sessionId),r?.extraContext!==void 0&&(s.extra_context=r.extraContext);let i=await this.http.post(`/api/agents/${encodeURIComponent(e)}/chat`,s);return {data:{sessionId:i.session_id,runId:i.runId,status:i.status,output:i.output,text:i.text,totalTokens:i.totalTokens,totalCost:i.totalCost,error:i.error},error:null}}catch(s){return E(s,"chat failed")}}async listSessions(e,t){if(typeof e!="string"||!v.test(e))return z();try{let r=te(t?.limit);return {data:{sessions:((await this.http.get(`/api/agents/${encodeURIComponent(e)}/sessions?limit=${r}`)).sessions??[]).map(o=>({id:o.id,createdAt:o.created_at,lastActivityAt:o.last_activity_at,messageCount:o.message_count,lastMessagePreview:o.last_message_preview??null}))},error:null}}catch(r){return E(r,"listSessions failed")}}async getMessages(e,t,r){if(typeof e!="string"||!v.test(e))return z();if(typeof t!="string"||!v.test(t))return re();try{let s=be(r?.limit),i=new URLSearchParams;return i.set("limit",String(s)),r?.before!==void 0&&i.set("before",r.before),{data:{messages:((await this.http.get(`/api/agents/${encodeURIComponent(e)}/sessions/${encodeURIComponent(t)}/messages?${i.toString()}`)).messages??[]).map(d=>({id:d.id,role:d.role,content:d.content,createdAt:d.created_at}))},error:null}}catch(s){return E(s,"getMessages failed")}}async deleteSession(e,t){if(typeof e!="string"||!v.test(e))return z();if(typeof t!="string"||!v.test(t))return re();try{return await this.http.delete(`/api/agents/${encodeURIComponent(e)}/sessions/${encodeURIComponent(t)}`),{data:{ok:!0},error:null}}catch(r){return E(r,"deleteSession failed")}}};var _=class{http;tokenManager;auth;database;realtime;storage;functions;agents;constructor(e={}){let t=new R(e.debug);this.tokenManager=new w({persistSession:e.persistSession,storageKey:e.storageKey,storage:e.storage,multiTab:e.multiTab}),this.http=new O(e,this.tokenManager,t),this.auth=new I(this.http,this.tokenManager),this.database=new U(this.http,this.tokenManager,e.anonKey),this.realtime=new B(this.http.baseUrl,this.tokenManager,e.anonKey,e.realtime),this.storage=new x(this.http),this.functions=new M(this.http),this.agents=new F(this.http);}getHttpClient(){return this.http}};function at(n){return new _(n)}var ct=_;
|
|
5
|
+
exports.AgentsModule=F;exports.Auth=I;exports.Database=U;exports.Functions=M;exports.HttpClient=O;exports.Logger=R;exports.MitwayBaasClient=_;exports.MitwayBaasError=c;exports.Realtime=B;exports.RealtimeChannel=j;exports.Storage=x;exports.StorageBucketClient=K;exports.TokenManager=w;exports.createClient=at;exports.createLocalStorageAdapter=Z;exports.default=ct;
|
package/dist/index.d.cts
CHANGED
|
@@ -2,32 +2,62 @@ import { Socket } from 'socket.io-client';
|
|
|
2
2
|
import * as _mitway_postgrest_js from '@mitway/postgrest-js';
|
|
3
3
|
|
|
4
4
|
/**
|
|
5
|
-
* User shape
|
|
5
|
+
* User shape carried on the `user` field of the MITWAY-BaaS auth responses.
|
|
6
6
|
*
|
|
7
|
-
*
|
|
8
|
-
*
|
|
9
|
-
* inlined here so this SDK has zero internal MITWAY-BaaS workspace
|
|
10
|
-
* dependencies and can be published to npm standalone.
|
|
7
|
+
* The backend emits the user object through TWO distinct projections, and
|
|
8
|
+
* `client.auth.getUser()` returns whichever one last populated the cache:
|
|
11
9
|
*
|
|
12
|
-
*
|
|
13
|
-
*
|
|
14
|
-
*
|
|
15
|
-
*
|
|
10
|
+
* 1. The **mint** endpoints — `POST /api/auth/register`, `POST /api/auth/login`,
|
|
11
|
+
* `POST /api/auth/refresh`, the OAuth `/oauth/session` hand-off, and admin
|
|
12
|
+
* `POST /api/auth/users` — return the backend's `formatUserResponse`
|
|
13
|
+
* projection: a Supabase-compatible shape with `role`, `user_metadata`,
|
|
14
|
+
* `app_metadata`. After `signUp` / `signInWithPassword` / `refreshSession`
|
|
15
|
+
* / `setSession`, the cached user has THESE fields.
|
|
16
|
+
* 2. `GET /api/auth/sessions/current` (driven by `getCurrentUser()` and
|
|
17
|
+
* `initialize()`) returns the raw `auth.users` DB record (minus password):
|
|
18
|
+
* `is_project_admin`, `profile`, `metadata`, `banned_until`. After those
|
|
19
|
+
* calls, the cached user has THESE fields instead.
|
|
20
|
+
*
|
|
21
|
+
* Only `id`, `email`, `created_at` and `updated_at` are present on every path.
|
|
22
|
+
* Every other field is path-dependent and therefore optional — reading one
|
|
23
|
+
* the current path did not send yields `undefined`. The previous version of
|
|
24
|
+
* this type declared only projection (2)'s fields as required, which silently
|
|
25
|
+
* returned `undefined` for `profile` / `is_project_admin` right after sign-in.
|
|
26
|
+
*
|
|
27
|
+
* The DB-record half mirrors the `User` zod schema in the BaaS workspace
|
|
28
|
+
* package `@mitway-baas/shared-schemas` (`src/auth.schema.ts`); the mint half
|
|
29
|
+
* mirrors `AuthService.formatUserResponse` in
|
|
30
|
+
* `backend/src/services/auth/auth.service.ts`. Both are inlined here so this
|
|
31
|
+
* SDK has zero internal MITWAY-BaaS workspace dependencies and can be
|
|
32
|
+
* published to npm standalone. If either changes, update this type to match.
|
|
33
|
+
* `access_status` is intentionally omitted — it is gate-internal.
|
|
16
34
|
*/
|
|
17
35
|
interface User {
|
|
18
36
|
id: string;
|
|
19
37
|
email: string;
|
|
20
|
-
/**
|
|
21
|
-
password?: string | null;
|
|
22
|
-
is_project_admin: boolean;
|
|
23
|
-
profile: Record<string, unknown>;
|
|
24
|
-
metadata: Record<string, unknown>;
|
|
25
|
-
/** ISO 8601 timestamp when the user was banned, or null. */
|
|
26
|
-
banned_until: string | null;
|
|
27
|
-
/** ISO 8601 timestamp. */
|
|
38
|
+
/** ISO 8601 timestamp. Present on every projection. */
|
|
28
39
|
created_at: string;
|
|
29
|
-
/** ISO 8601 timestamp. */
|
|
40
|
+
/** ISO 8601 timestamp. Present on every projection. */
|
|
30
41
|
updated_at: string;
|
|
42
|
+
/** `'service_role'` for project admins, else `'authenticated'`. Mint projection only. */
|
|
43
|
+
role?: 'service_role' | 'authenticated';
|
|
44
|
+
/** User-controlled profile data (the DB `profile` column). Mint projection only. */
|
|
45
|
+
user_metadata?: Record<string, unknown>;
|
|
46
|
+
/** App-controlled metadata (the DB `metadata` column). Mint projection only. */
|
|
47
|
+
app_metadata?: Record<string, unknown>;
|
|
48
|
+
/** Raw `auth.users` flag. Record projection only. */
|
|
49
|
+
is_project_admin?: boolean;
|
|
50
|
+
/** User-controlled profile data. Record projection only (mirrors `user_metadata`). */
|
|
51
|
+
profile?: Record<string, unknown>;
|
|
52
|
+
/** App-controlled metadata. Record projection only (mirrors `app_metadata`). */
|
|
53
|
+
metadata?: Record<string, unknown>;
|
|
54
|
+
/** ISO 8601 timestamp when the user was banned, or null. Record projection only. */
|
|
55
|
+
banned_until?: string | null;
|
|
56
|
+
/**
|
|
57
|
+
* Hashed password. Never sent on the wire today (`/sessions/current` strips
|
|
58
|
+
* it; the mint projection omits it). Kept optional for forward-compat.
|
|
59
|
+
*/
|
|
60
|
+
password?: string | null;
|
|
31
61
|
}
|
|
32
62
|
|
|
33
63
|
/**
|
|
@@ -708,6 +738,17 @@ interface SignInRequest {
|
|
|
708
738
|
email: string;
|
|
709
739
|
password: string;
|
|
710
740
|
}
|
|
741
|
+
/**
|
|
742
|
+
* Input for `auth.setSession` — a session minted out-of-band (e.g. the
|
|
743
|
+
* Entra OIDC broker's `/exchange` hand-off). Snake_case to mirror the
|
|
744
|
+
* broker's wire contract; the SDK converts to the camelCase
|
|
745
|
+
* `AuthResponse` internally.
|
|
746
|
+
*/
|
|
747
|
+
interface SetSessionRequest {
|
|
748
|
+
access_token: string;
|
|
749
|
+
refresh_token?: string | null;
|
|
750
|
+
user: User;
|
|
751
|
+
}
|
|
711
752
|
/**
|
|
712
753
|
* The shape the backend returns from /register, /login, and /refresh. Mirrors
|
|
713
754
|
* what the existing backend handlers send: `{ user, accessToken, refreshToken,
|
|
@@ -725,6 +766,24 @@ type AuthResult<T> = {
|
|
|
725
766
|
data: T | null;
|
|
726
767
|
error: MitwayBaasError | null;
|
|
727
768
|
};
|
|
769
|
+
/** SSO providers the platform broker can drive. */
|
|
770
|
+
type SsoProvider = 'microsoft';
|
|
771
|
+
/**
|
|
772
|
+
* Shape of `GET /api/auth/sso/config` — the public discovery endpoint a
|
|
773
|
+
* client app reads to do SSO knowing only its own BaaS URL. `broker_url`
|
|
774
|
+
* is the platform broker (a different origin than the BaaS `baseUrl`);
|
|
775
|
+
* `providers` advertises which sign-in methods are enabled for the tenant.
|
|
776
|
+
*/
|
|
777
|
+
interface SsoConfig {
|
|
778
|
+
broker_url: string | null;
|
|
779
|
+
tenant_slug: string | null;
|
|
780
|
+
tenant_env: string | null;
|
|
781
|
+
providers: {
|
|
782
|
+
provider: string;
|
|
783
|
+
enabled: boolean;
|
|
784
|
+
mode: 'broker' | 'credential';
|
|
785
|
+
}[];
|
|
786
|
+
}
|
|
728
787
|
/**
|
|
729
788
|
* Event names emitted by `auth.onAuthStateChange`.
|
|
730
789
|
*
|
|
@@ -796,6 +855,37 @@ declare class Auth {
|
|
|
796
855
|
* Sign in with email + password and start a session.
|
|
797
856
|
*/
|
|
798
857
|
signInWithPassword(request: SignInRequest): Promise<AuthResult<AuthResponse>>;
|
|
858
|
+
/**
|
|
859
|
+
* Adopt a session minted out-of-band (e.g. the Entra OIDC broker's
|
|
860
|
+
* `/exchange` hand-off). Writes in-memory + persisted state and fires
|
|
861
|
+
* `SIGNED_IN` / `TOKEN_REFRESHED` via the same path as a password
|
|
862
|
+
* sign-in (`saveSessionFromResponse`). Returns the adopted session in
|
|
863
|
+
* the standard `{ data, error }` envelope.
|
|
864
|
+
*/
|
|
865
|
+
setSession(request: SetSessionRequest): Promise<AuthResult<AuthResponse>>;
|
|
866
|
+
/**
|
|
867
|
+
* Discover the platform broker URL, this tenant's identity, and which
|
|
868
|
+
* SSO providers are enabled. Lets a client app drive SSO knowing only
|
|
869
|
+
* its own BaaS URL — no broker URL or topology baked into app code.
|
|
870
|
+
*/
|
|
871
|
+
getSSOConfig(): Promise<AuthResult<SsoConfig>>;
|
|
872
|
+
/**
|
|
873
|
+
* Begin SSO: redirect the browser to the platform broker. The broker
|
|
874
|
+
* handles the Entra round-trip and redirects back to `returnUrl` (this
|
|
875
|
+
* app's callback), where `completeSSO()` finishes. Browser-only — the
|
|
876
|
+
* broker lives on a different origin than `baseUrl`, so this builds the
|
|
877
|
+
* URL by hand and uses `window.location.assign` rather than `this.http`.
|
|
878
|
+
*/
|
|
879
|
+
signInWithSSO(provider: SsoProvider, opts: {
|
|
880
|
+
returnUrl: string;
|
|
881
|
+
}): Promise<AuthResult<never>>;
|
|
882
|
+
/**
|
|
883
|
+
* Finish SSO on the app's callback page: redeem the one-time hand-off at
|
|
884
|
+
* the broker's `/exchange` and adopt the tenant session. Browser-only —
|
|
885
|
+
* the broker lives on a different origin than `baseUrl`, so this uses a
|
|
886
|
+
* raw credentialed `fetch` rather than `this.http`.
|
|
887
|
+
*/
|
|
888
|
+
completeSSO(): Promise<AuthResult<AuthResponse>>;
|
|
799
889
|
/**
|
|
800
890
|
* End the current session. Clears in-memory state even if the backend
|
|
801
891
|
* call fails (network/offline).
|
|
@@ -1273,4 +1363,4 @@ declare class MitwayBaasClient {
|
|
|
1273
1363
|
*/
|
|
1274
1364
|
declare function createClient(config: MitwayBaasConfig): MitwayBaasClient;
|
|
1275
1365
|
|
|
1276
|
-
export { type Agent, type AgentInvokeResult, AgentsModule, type AgentsResult, type ApiError, Auth, type AuthChangeEvent, type AuthRefreshResponse, type AuthResponse, type AuthResult, type AuthSession, type AuthStateChangeCallback, type BroadcastFilter, type BroadcastPayload, type ChannelOptions, type ChannelStatus, type ChannelStatusCallback, type ChatMessage, type ChatSession, type ChatTurn, type CreateBucketOptions, type CreateFunctionRequest, Database, type DownloadOptions, type EdgeFunction, type FunctionSecret, Functions, type FunctionsResult, HttpClient, type InvokeOptions, type ListOptions, Logger, MitwayBaasClient, type MitwayBaasConfig, MitwayBaasError, type PostgresChangesDeletePayload, type PostgresChangesEventSelector, type PostgresChangesFilter, type PostgresChangesInsertPayload, type PostgresChangesPayload, type PostgresChangesUpdatePayload, type PresenceEventSelector, type PresenceFilter, type PresenceJoinPayload, type PresenceLeavePayload, type PresencePayload, type PresenceState, type PresenceSyncPayload, Realtime, RealtimeChannel, type RealtimeMessageMeta, type RealtimeOptions, type SignInRequest, type SignUpRequest, type SignedUrlOptions, type SignedUrlResult, Storage, type StorageAdapter, type StorageBucket, StorageBucketClient, type StorageConfig, type StorageObject, type StorageResult, type Subscription, TokenManager, type UpdateBucketOptions, type UpdateFunctionRequest, type UploadBody, type UploadOptions, type User, createClient, createLocalStorageAdapter, MitwayBaasClient as default };
|
|
1366
|
+
export { type Agent, type AgentInvokeResult, AgentsModule, type AgentsResult, type ApiError, Auth, type AuthChangeEvent, type AuthRefreshResponse, type AuthResponse, type AuthResult, type AuthSession, type AuthStateChangeCallback, type BroadcastFilter, type BroadcastPayload, type ChannelOptions, type ChannelStatus, type ChannelStatusCallback, type ChatMessage, type ChatSession, type ChatTurn, type CreateBucketOptions, type CreateFunctionRequest, Database, type DownloadOptions, type EdgeFunction, type FunctionSecret, Functions, type FunctionsResult, HttpClient, type InvokeOptions, type ListOptions, Logger, MitwayBaasClient, type MitwayBaasConfig, MitwayBaasError, type PostgresChangesDeletePayload, type PostgresChangesEventSelector, type PostgresChangesFilter, type PostgresChangesInsertPayload, type PostgresChangesPayload, type PostgresChangesUpdatePayload, type PresenceEventSelector, type PresenceFilter, type PresenceJoinPayload, type PresenceLeavePayload, type PresencePayload, type PresenceState, type PresenceSyncPayload, Realtime, RealtimeChannel, type RealtimeMessageMeta, type RealtimeOptions, type SetSessionRequest, type SignInRequest, type SignUpRequest, type SignedUrlOptions, type SignedUrlResult, type SsoConfig, type SsoProvider, Storage, type StorageAdapter, type StorageBucket, StorageBucketClient, type StorageConfig, type StorageObject, type StorageResult, type Subscription, TokenManager, type UpdateBucketOptions, type UpdateFunctionRequest, type UploadBody, type UploadOptions, type User, createClient, createLocalStorageAdapter, MitwayBaasClient as default };
|
package/dist/index.d.ts
CHANGED
|
@@ -2,32 +2,62 @@ import { Socket } from 'socket.io-client';
|
|
|
2
2
|
import * as _mitway_postgrest_js from '@mitway/postgrest-js';
|
|
3
3
|
|
|
4
4
|
/**
|
|
5
|
-
* User shape
|
|
5
|
+
* User shape carried on the `user` field of the MITWAY-BaaS auth responses.
|
|
6
6
|
*
|
|
7
|
-
*
|
|
8
|
-
*
|
|
9
|
-
* inlined here so this SDK has zero internal MITWAY-BaaS workspace
|
|
10
|
-
* dependencies and can be published to npm standalone.
|
|
7
|
+
* The backend emits the user object through TWO distinct projections, and
|
|
8
|
+
* `client.auth.getUser()` returns whichever one last populated the cache:
|
|
11
9
|
*
|
|
12
|
-
*
|
|
13
|
-
*
|
|
14
|
-
*
|
|
15
|
-
*
|
|
10
|
+
* 1. The **mint** endpoints — `POST /api/auth/register`, `POST /api/auth/login`,
|
|
11
|
+
* `POST /api/auth/refresh`, the OAuth `/oauth/session` hand-off, and admin
|
|
12
|
+
* `POST /api/auth/users` — return the backend's `formatUserResponse`
|
|
13
|
+
* projection: a Supabase-compatible shape with `role`, `user_metadata`,
|
|
14
|
+
* `app_metadata`. After `signUp` / `signInWithPassword` / `refreshSession`
|
|
15
|
+
* / `setSession`, the cached user has THESE fields.
|
|
16
|
+
* 2. `GET /api/auth/sessions/current` (driven by `getCurrentUser()` and
|
|
17
|
+
* `initialize()`) returns the raw `auth.users` DB record (minus password):
|
|
18
|
+
* `is_project_admin`, `profile`, `metadata`, `banned_until`. After those
|
|
19
|
+
* calls, the cached user has THESE fields instead.
|
|
20
|
+
*
|
|
21
|
+
* Only `id`, `email`, `created_at` and `updated_at` are present on every path.
|
|
22
|
+
* Every other field is path-dependent and therefore optional — reading one
|
|
23
|
+
* the current path did not send yields `undefined`. The previous version of
|
|
24
|
+
* this type declared only projection (2)'s fields as required, which silently
|
|
25
|
+
* returned `undefined` for `profile` / `is_project_admin` right after sign-in.
|
|
26
|
+
*
|
|
27
|
+
* The DB-record half mirrors the `User` zod schema in the BaaS workspace
|
|
28
|
+
* package `@mitway-baas/shared-schemas` (`src/auth.schema.ts`); the mint half
|
|
29
|
+
* mirrors `AuthService.formatUserResponse` in
|
|
30
|
+
* `backend/src/services/auth/auth.service.ts`. Both are inlined here so this
|
|
31
|
+
* SDK has zero internal MITWAY-BaaS workspace dependencies and can be
|
|
32
|
+
* published to npm standalone. If either changes, update this type to match.
|
|
33
|
+
* `access_status` is intentionally omitted — it is gate-internal.
|
|
16
34
|
*/
|
|
17
35
|
interface User {
|
|
18
36
|
id: string;
|
|
19
37
|
email: string;
|
|
20
|
-
/**
|
|
21
|
-
password?: string | null;
|
|
22
|
-
is_project_admin: boolean;
|
|
23
|
-
profile: Record<string, unknown>;
|
|
24
|
-
metadata: Record<string, unknown>;
|
|
25
|
-
/** ISO 8601 timestamp when the user was banned, or null. */
|
|
26
|
-
banned_until: string | null;
|
|
27
|
-
/** ISO 8601 timestamp. */
|
|
38
|
+
/** ISO 8601 timestamp. Present on every projection. */
|
|
28
39
|
created_at: string;
|
|
29
|
-
/** ISO 8601 timestamp. */
|
|
40
|
+
/** ISO 8601 timestamp. Present on every projection. */
|
|
30
41
|
updated_at: string;
|
|
42
|
+
/** `'service_role'` for project admins, else `'authenticated'`. Mint projection only. */
|
|
43
|
+
role?: 'service_role' | 'authenticated';
|
|
44
|
+
/** User-controlled profile data (the DB `profile` column). Mint projection only. */
|
|
45
|
+
user_metadata?: Record<string, unknown>;
|
|
46
|
+
/** App-controlled metadata (the DB `metadata` column). Mint projection only. */
|
|
47
|
+
app_metadata?: Record<string, unknown>;
|
|
48
|
+
/** Raw `auth.users` flag. Record projection only. */
|
|
49
|
+
is_project_admin?: boolean;
|
|
50
|
+
/** User-controlled profile data. Record projection only (mirrors `user_metadata`). */
|
|
51
|
+
profile?: Record<string, unknown>;
|
|
52
|
+
/** App-controlled metadata. Record projection only (mirrors `app_metadata`). */
|
|
53
|
+
metadata?: Record<string, unknown>;
|
|
54
|
+
/** ISO 8601 timestamp when the user was banned, or null. Record projection only. */
|
|
55
|
+
banned_until?: string | null;
|
|
56
|
+
/**
|
|
57
|
+
* Hashed password. Never sent on the wire today (`/sessions/current` strips
|
|
58
|
+
* it; the mint projection omits it). Kept optional for forward-compat.
|
|
59
|
+
*/
|
|
60
|
+
password?: string | null;
|
|
31
61
|
}
|
|
32
62
|
|
|
33
63
|
/**
|
|
@@ -708,6 +738,17 @@ interface SignInRequest {
|
|
|
708
738
|
email: string;
|
|
709
739
|
password: string;
|
|
710
740
|
}
|
|
741
|
+
/**
|
|
742
|
+
* Input for `auth.setSession` — a session minted out-of-band (e.g. the
|
|
743
|
+
* Entra OIDC broker's `/exchange` hand-off). Snake_case to mirror the
|
|
744
|
+
* broker's wire contract; the SDK converts to the camelCase
|
|
745
|
+
* `AuthResponse` internally.
|
|
746
|
+
*/
|
|
747
|
+
interface SetSessionRequest {
|
|
748
|
+
access_token: string;
|
|
749
|
+
refresh_token?: string | null;
|
|
750
|
+
user: User;
|
|
751
|
+
}
|
|
711
752
|
/**
|
|
712
753
|
* The shape the backend returns from /register, /login, and /refresh. Mirrors
|
|
713
754
|
* what the existing backend handlers send: `{ user, accessToken, refreshToken,
|
|
@@ -725,6 +766,24 @@ type AuthResult<T> = {
|
|
|
725
766
|
data: T | null;
|
|
726
767
|
error: MitwayBaasError | null;
|
|
727
768
|
};
|
|
769
|
+
/** SSO providers the platform broker can drive. */
|
|
770
|
+
type SsoProvider = 'microsoft';
|
|
771
|
+
/**
|
|
772
|
+
* Shape of `GET /api/auth/sso/config` — the public discovery endpoint a
|
|
773
|
+
* client app reads to do SSO knowing only its own BaaS URL. `broker_url`
|
|
774
|
+
* is the platform broker (a different origin than the BaaS `baseUrl`);
|
|
775
|
+
* `providers` advertises which sign-in methods are enabled for the tenant.
|
|
776
|
+
*/
|
|
777
|
+
interface SsoConfig {
|
|
778
|
+
broker_url: string | null;
|
|
779
|
+
tenant_slug: string | null;
|
|
780
|
+
tenant_env: string | null;
|
|
781
|
+
providers: {
|
|
782
|
+
provider: string;
|
|
783
|
+
enabled: boolean;
|
|
784
|
+
mode: 'broker' | 'credential';
|
|
785
|
+
}[];
|
|
786
|
+
}
|
|
728
787
|
/**
|
|
729
788
|
* Event names emitted by `auth.onAuthStateChange`.
|
|
730
789
|
*
|
|
@@ -796,6 +855,37 @@ declare class Auth {
|
|
|
796
855
|
* Sign in with email + password and start a session.
|
|
797
856
|
*/
|
|
798
857
|
signInWithPassword(request: SignInRequest): Promise<AuthResult<AuthResponse>>;
|
|
858
|
+
/**
|
|
859
|
+
* Adopt a session minted out-of-band (e.g. the Entra OIDC broker's
|
|
860
|
+
* `/exchange` hand-off). Writes in-memory + persisted state and fires
|
|
861
|
+
* `SIGNED_IN` / `TOKEN_REFRESHED` via the same path as a password
|
|
862
|
+
* sign-in (`saveSessionFromResponse`). Returns the adopted session in
|
|
863
|
+
* the standard `{ data, error }` envelope.
|
|
864
|
+
*/
|
|
865
|
+
setSession(request: SetSessionRequest): Promise<AuthResult<AuthResponse>>;
|
|
866
|
+
/**
|
|
867
|
+
* Discover the platform broker URL, this tenant's identity, and which
|
|
868
|
+
* SSO providers are enabled. Lets a client app drive SSO knowing only
|
|
869
|
+
* its own BaaS URL — no broker URL or topology baked into app code.
|
|
870
|
+
*/
|
|
871
|
+
getSSOConfig(): Promise<AuthResult<SsoConfig>>;
|
|
872
|
+
/**
|
|
873
|
+
* Begin SSO: redirect the browser to the platform broker. The broker
|
|
874
|
+
* handles the Entra round-trip and redirects back to `returnUrl` (this
|
|
875
|
+
* app's callback), where `completeSSO()` finishes. Browser-only — the
|
|
876
|
+
* broker lives on a different origin than `baseUrl`, so this builds the
|
|
877
|
+
* URL by hand and uses `window.location.assign` rather than `this.http`.
|
|
878
|
+
*/
|
|
879
|
+
signInWithSSO(provider: SsoProvider, opts: {
|
|
880
|
+
returnUrl: string;
|
|
881
|
+
}): Promise<AuthResult<never>>;
|
|
882
|
+
/**
|
|
883
|
+
* Finish SSO on the app's callback page: redeem the one-time hand-off at
|
|
884
|
+
* the broker's `/exchange` and adopt the tenant session. Browser-only —
|
|
885
|
+
* the broker lives on a different origin than `baseUrl`, so this uses a
|
|
886
|
+
* raw credentialed `fetch` rather than `this.http`.
|
|
887
|
+
*/
|
|
888
|
+
completeSSO(): Promise<AuthResult<AuthResponse>>;
|
|
799
889
|
/**
|
|
800
890
|
* End the current session. Clears in-memory state even if the backend
|
|
801
891
|
* call fails (network/offline).
|
|
@@ -1273,4 +1363,4 @@ declare class MitwayBaasClient {
|
|
|
1273
1363
|
*/
|
|
1274
1364
|
declare function createClient(config: MitwayBaasConfig): MitwayBaasClient;
|
|
1275
1365
|
|
|
1276
|
-
export { type Agent, type AgentInvokeResult, AgentsModule, type AgentsResult, type ApiError, Auth, type AuthChangeEvent, type AuthRefreshResponse, type AuthResponse, type AuthResult, type AuthSession, type AuthStateChangeCallback, type BroadcastFilter, type BroadcastPayload, type ChannelOptions, type ChannelStatus, type ChannelStatusCallback, type ChatMessage, type ChatSession, type ChatTurn, type CreateBucketOptions, type CreateFunctionRequest, Database, type DownloadOptions, type EdgeFunction, type FunctionSecret, Functions, type FunctionsResult, HttpClient, type InvokeOptions, type ListOptions, Logger, MitwayBaasClient, type MitwayBaasConfig, MitwayBaasError, type PostgresChangesDeletePayload, type PostgresChangesEventSelector, type PostgresChangesFilter, type PostgresChangesInsertPayload, type PostgresChangesPayload, type PostgresChangesUpdatePayload, type PresenceEventSelector, type PresenceFilter, type PresenceJoinPayload, type PresenceLeavePayload, type PresencePayload, type PresenceState, type PresenceSyncPayload, Realtime, RealtimeChannel, type RealtimeMessageMeta, type RealtimeOptions, type SignInRequest, type SignUpRequest, type SignedUrlOptions, type SignedUrlResult, Storage, type StorageAdapter, type StorageBucket, StorageBucketClient, type StorageConfig, type StorageObject, type StorageResult, type Subscription, TokenManager, type UpdateBucketOptions, type UpdateFunctionRequest, type UploadBody, type UploadOptions, type User, createClient, createLocalStorageAdapter, MitwayBaasClient as default };
|
|
1366
|
+
export { type Agent, type AgentInvokeResult, AgentsModule, type AgentsResult, type ApiError, Auth, type AuthChangeEvent, type AuthRefreshResponse, type AuthResponse, type AuthResult, type AuthSession, type AuthStateChangeCallback, type BroadcastFilter, type BroadcastPayload, type ChannelOptions, type ChannelStatus, type ChannelStatusCallback, type ChatMessage, type ChatSession, type ChatTurn, type CreateBucketOptions, type CreateFunctionRequest, Database, type DownloadOptions, type EdgeFunction, type FunctionSecret, Functions, type FunctionsResult, HttpClient, type InvokeOptions, type ListOptions, Logger, MitwayBaasClient, type MitwayBaasConfig, MitwayBaasError, type PostgresChangesDeletePayload, type PostgresChangesEventSelector, type PostgresChangesFilter, type PostgresChangesInsertPayload, type PostgresChangesPayload, type PostgresChangesUpdatePayload, type PresenceEventSelector, type PresenceFilter, type PresenceJoinPayload, type PresenceLeavePayload, type PresencePayload, type PresenceState, type PresenceSyncPayload, Realtime, RealtimeChannel, type RealtimeMessageMeta, type RealtimeOptions, type SetSessionRequest, type SignInRequest, type SignUpRequest, type SignedUrlOptions, type SignedUrlResult, type SsoConfig, type SsoProvider, Storage, type StorageAdapter, type StorageBucket, StorageBucketClient, type StorageConfig, type StorageObject, type StorageResult, type Subscription, TokenManager, type UpdateBucketOptions, type UpdateFunctionRequest, type UploadBody, type UploadOptions, type User, createClient, createLocalStorageAdapter, MitwayBaasClient as default };
|
package/dist/index.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import {PostgrestClient}from'@mitway/postgrest-js';import {io}from'socket.io-client';var c=class
|
|
2
|
-
`));}logResponse(e,t,s,
|
|
1
|
+
import {PostgrestClient}from'@mitway/postgrest-js';import {io}from'socket.io-client';var c=class n extends Error{statusCode;error;nextActions;constructor(e,t,r,s){super(e),this.name="MitwayBaasError",this.statusCode=t,this.error=r,this.nextActions=s;}static fromApiError(e){return new n(e.message,e.statusCode,e.error,e.nextActions)}};var ne=["authorization","x-api-key","cookie","set-cookie"],ie=["password","token","accesstoken","refreshtoken","authorization","secret","apikey","api_key","email","ssn","creditcard","credit_card"];function oe(n){let e={};for(let[t,r]of Object.entries(n))ne.includes(t.toLowerCase())?e[t]="***REDACTED***":e[t]=r;return e}function P(n){if(n==null)return n;if(typeof n=="string")try{let e=JSON.parse(n);return P(e)}catch{return n}if(Array.isArray(n))return n.map(P);if(typeof n=="object"){let e={};for(let[t,r]of Object.entries(n))ie.includes(t.toLowerCase().replace(/[-_]/g,""))?e[t]="***REDACTED***":e[t]=P(r);return e}return n}function X(n){if(n==null)return "";if(typeof n=="string")try{return JSON.stringify(JSON.parse(n),null,2)}catch{return n}if(typeof FormData<"u"&&n instanceof FormData)return "[FormData]";try{return JSON.stringify(n,null,2)}catch{return "[Unserializable body]"}}var R=class{enabled;customLog;constructor(e){typeof e=="function"?(this.enabled=true,this.customLog=e):(this.enabled=!!e,this.customLog=null);}log(e,...t){if(!this.enabled)return;let r=`[MITWAY-BaaS Debug] ${e}`;this.customLog?this.customLog(r,...t):console.log(r,...t);}warn(e,...t){if(!this.enabled)return;let r=`[MITWAY-BaaS Debug] ${e}`;this.customLog?this.customLog(r,...t):console.warn(r,...t);}error(e,...t){if(!this.enabled)return;let r=`[MITWAY-BaaS Debug] ${e}`;this.customLog?this.customLog(r,...t):console.error(r,...t);}logRequest(e,t,r,s){if(!this.enabled)return;let i=[`\u2192 ${e} ${t}`];r&&Object.keys(r).length>0&&i.push(` Headers: ${JSON.stringify(oe(r))}`);let o=X(P(s));if(o){let a=o.length>1e3?o.slice(0,1e3)+"... [truncated]":o;i.push(` Body: ${a}`);}this.log(i.join(`
|
|
2
|
+
`));}logResponse(e,t,r,s,i){if(!this.enabled)return;let o=[`\u2190 ${e} ${t} ${r} (${s}ms)`],a=X(P(i));if(a){let d=a.length>1e3?a.slice(0,1e3)+"... [truncated]":a;o.push(` Body: ${d}`);}r>=400?this.error(o.join(`
|
|
3
3
|
`)):this.log(o.join(`
|
|
4
|
-
`));}};var G="mitway_baas_csrf_token",ae="mitway_baas_session";function Z(){return typeof localStorage<"u"?{getItem:e=>{try{return localStorage.getItem(e)}catch{return null}},setItem:(e,t)=>{try{localStorage.setItem(e,t);}catch{}},removeItem:e=>{try{localStorage.removeItem(e);}catch{}}}:{getItem:()=>null,setItem:()=>{},removeItem:()=>{}}}var ce={getItem:()=>null,setItem:()=>{},removeItem:()=>{}};function ee(){if(typeof document>"u")return null;let r=document.cookie.split(";").find(e=>e.trim().startsWith(`${G}=`));return r&&r.split("=")[1]||null}function L(r){if(typeof document>"u")return;let e=10080*60,t=typeof window<"u"&&window.location.protocol==="https:"?"; Secure":"";document.cookie=`${G}=${encodeURIComponent(r)}; path=/; max-age=${e}; SameSite=Lax${t}`;}function j(){if(typeof document>"u")return;let r=typeof window<"u"&&window.location.protocol==="https:"?"; Secure":"";document.cookie=`${G}=; path=/; max-age=0; SameSite=Lax${r}`;}var S=class{accessToken=null;refreshToken=null;user=null;persistSession;storageKey;storage;onTokenChange=null;constructor(e){this.persistSession=e?.persistSession??true,this.storageKey=e?.storageKey??ae,this.storage=this.persistSession?e?.storage??Z():ce,(e?.multiTab??true)&&this.persistSession&&typeof window<"u"&&typeof localStorage<"u"&&window.addEventListener("storage",this.handleStorageEvent),this.restoreSession();}handleStorageEvent=e=>{e.key===this.storageKey&&(typeof localStorage<"u"&&e.storageArea!==localStorage||this.syncFromStorage(e.newValue));};syncFromStorage(e){let t=this.accessToken;if(e===null)this.accessToken=null,this.refreshToken=null,this.user=null;else try{let s=JSON.parse(e);if(!s.accessToken||!s.user)return;this.accessToken=s.accessToken,this.refreshToken=s.refreshToken??null,this.user=s.user;}catch{return}t!==this.accessToken&&this.onTokenChange&&this.onTokenChange();}saveSession(e){let t=e.accessToken!==this.accessToken;this.accessToken=e.accessToken,this.user=e.user,e.refreshToken!==void 0&&(this.refreshToken=e.refreshToken??null),this.persist(),t&&this.onTokenChange&&this.onTokenChange();}getSession(){return !this.accessToken||!this.user?null:{accessToken:this.accessToken,refreshToken:this.refreshToken??void 0,user:this.user}}getAccessToken(){return this.accessToken}setAccessToken(e){let t=e!==this.accessToken;this.accessToken=e,this.persist(),t&&this.onTokenChange&&this.onTokenChange();}getRefreshToken(){return this.refreshToken}setRefreshToken(e){this.refreshToken=e,this.persist();}getUser(){return this.user}setUser(e){this.user=e,this.persist();}clearSession(){let e=this.accessToken!==null;this.accessToken=null,this.refreshToken=null,this.user=null,this.removePersisted(),e&&this.onTokenChange&&this.onTokenChange();}restoreSession(){if(!this.persistSession)return false;try{let e=this.storage.getItem(this.storageKey);if(!e)return !1;let t=JSON.parse(e);return !t.accessToken||!t.user?!1:(this.accessToken=t.accessToken,this.refreshToken=t.refreshToken??null,this.user=t.user,!0)}catch{return false}}persist(){if(!this.persistSession||!this.accessToken||!this.user)return;let e={accessToken:this.accessToken,user:this.user};this.refreshToken&&(e.refreshToken=this.refreshToken),this.storage.setItem(this.storageKey,JSON.stringify(e));}removePersisted(){this.persistSession&&this.storage.removeItem(this.storageKey);}};function A(r){if(!r||typeof r!="object")return r;let e=r,t={...e},s=false;return "access_token"in e&&!("accessToken"in e)&&(t.accessToken=e.access_token,delete t.access_token,s=true),"csrf_token"in e&&!("csrfToken"in e)&&(t.csrfToken=e.csrf_token,delete t.csrf_token,s=true),"refresh_token"in e&&!("refreshToken"in e)&&(t.refreshToken=e.refresh_token,delete t.refresh_token,s=true),s?t:r}var le=new Set([500,502,503,504]),ue=new Set(["GET","HEAD","PUT","DELETE","OPTIONS"]),I=class{baseUrl;fetch;defaultHeaders;anonKey;userToken=null;logger;autoRefreshToken=true;isRefreshing=false;refreshPromise=null;tokenManager;refreshToken=null;timeout;retryCount;retryDelay;constructor(e,t,s){if(this.baseUrl=e.baseUrl||"http://localhost:7130",this.autoRefreshToken=e.autoRefreshToken??true,this.fetch=e.fetch||(globalThis.fetch?globalThis.fetch.bind(globalThis):void 0),this.anonKey=e.anonKey,this.defaultHeaders={...e.headers},this.tokenManager=t??new S,this.logger=s||new R(false),this.timeout=e.timeout??3e4,this.retryCount=e.retryCount??3,this.retryDelay=e.retryDelay??500,!this.fetch)throw new Error("Fetch is not available. Provide a fetch implementation in the SDK config.")}buildUrl(e,t){let s=new URL(e,this.baseUrl);return t&&Object.entries(t).forEach(([n,i])=>{if(n==="select"){let o=i.replace(/\s+/g," ").trim();o=o.replace(/\s*\(\s*/g,"(").replace(/\s*\)\s*/g,")").replace(/\(\s+/g,"(").replace(/\s+\)/g,")").replace(/,\s+(?=[^()]*\))/g,","),s.searchParams.append(n,o);}else s.searchParams.append(n,i);}),s.toString()}isRetryableStatus(e){return le.has(e)}computeRetryDelay(e){let s=this.retryDelay*Math.pow(2,e-1)*(.85+Math.random()*.3);return Math.round(s)}async handleRequest(e,t,s={}){let{params:n,headers:i={},body:o,signal:a,...d}=s,p=this.buildUrl(t,n),v=Date.now(),T=ue.has(e.toUpperCase())||s.idempotent===true?this.retryCount:0,b={...this.defaultHeaders},Q=this.userToken||this.anonKey;Q&&(b.Authorization=`Bearer ${Q}`);let N;o!==void 0&&(typeof FormData<"u"&&o instanceof FormData?N=o:(e!=="GET"&&(b["Content-Type"]="application/json;charset=UTF-8"),N=JSON.stringify(o))),i instanceof Headers?i.forEach((f,g)=>{b[g]=f;}):Array.isArray(i)?i.forEach(([f,g])=>{b[f]=g;}):Object.assign(b,i),this.logger.logRequest(e,p,b,N);let W;for(let f=0;f<=T;f++){if(f>0){let l=this.computeRetryDelay(f);if(this.logger.warn(`Retry ${f}/${T} for ${e} ${p} in ${l}ms`),a?.aborted)throw a.reason;await new Promise((u,J)=>{let y=()=>{clearTimeout(ne),J(a.reason);},ne=setTimeout(()=>{a&&a.removeEventListener("abort",y),u();},l);a&&a.addEventListener("abort",y,{once:true});});}let g,m;if((this.timeout>0||a)&&(g=new AbortController,this.timeout>0&&(m=setTimeout(()=>g.abort(),this.timeout)),a))if(a.aborted)g.abort(a.reason);else {let l=()=>g.abort(a.reason);a.addEventListener("abort",l,{once:true}),g.signal.addEventListener("abort",()=>{a.removeEventListener("abort",l);},{once:true});}try{let l=await this.fetch(p,{method:e,headers:b,body:N,...d,...g?{signal:g.signal}:{}});if(this.isRetryableStatus(l.status)&&f<T){m!==void 0&&clearTimeout(m),await l.body?.cancel(),W=new c(`Server error: ${l.status} ${l.statusText}`,l.status,"SERVER_ERROR");continue}if(l.status===204){m!==void 0&&clearTimeout(m);return}let u,J=l.headers.get("content-type");try{J?.includes("json")?u=await l.json():u=await l.text();}catch(y){throw m!==void 0&&clearTimeout(m),new c(`Failed to parse response body: ${y?.message||"Unknown error"}`,l.status,l.ok?"PARSE_ERROR":"REQUEST_FAILED")}if(m!==void 0&&clearTimeout(m),!l.ok){if(this.logger.logResponse(e,p,l.status,Date.now()-v,u),u&&typeof u=="object"&&"error"in u&&u.error!==null&&typeof u.error=="object"){let y=u.error;throw new c(y.message||l.statusText||"Request failed",y.statusCode||l.status,y.code||y.error||"REQUEST_FAILED",y.nextActions)}throw new c(`Request failed: ${l.statusText}`,l.status,"REQUEST_FAILED")}return this.logger.logResponse(e,p,l.status,Date.now()-v,u),u&&typeof u=="object"&&"data"in u&&"error"in u&&u.error===null?u.data:u}catch(l){if(m!==void 0&&clearTimeout(m),l?.name==="AbortError")throw g&&g.signal.aborted&&this.timeout>0&&!a?.aborted?new c(`Request timed out after ${this.timeout}ms`,408,"REQUEST_TIMEOUT"):l;if(l instanceof c)throw l;if(f<T){W=l;continue}throw new c(`Network request failed: ${l?.message||"Unknown error"}`,0,"NETWORK_ERROR")}}throw W||new c("Request failed after all retry attempts",0,"NETWORK_ERROR")}async request(e,t,s={}){try{return await this.handleRequest(e,t,{...s})}catch(n){if(n instanceof c&&n.statusCode===401&&this.autoRefreshToken&&this.refreshToken&&!t.includes("/api/auth/refresh"))try{let i=await this.handleTokenRefresh();this.setAuthToken(i.accessToken),i.refreshToken&&this.setRefreshToken(i.refreshToken),i.csrfToken&&L(i.csrfToken);let o=i.user??this.tokenManager.getUser();return o&&this.tokenManager.saveSession({accessToken:i.accessToken,refreshToken:i.refreshToken,user:o}),await this.handleRequest(e,t,{...s})}catch(i){throw this.tokenManager.clearSession(),this.userToken=null,this.refreshToken=null,j(),i}throw n}}async rawFetch(e,t={}){let s=this.buildUrl(e),n=new Headers(t.headers??{});for(let[i,o]of Object.entries(this.defaultHeaders))n.has(i)||n.set(i,o);if(!n.has("Authorization")){let i=this.userToken??this.anonKey;i&&n.set("Authorization",`Bearer ${i}`);}return this.fetch(s,{...t,headers:n})}get(e,t){return this.request("GET",e,t)}post(e,t,s){return this.request("POST",e,{...s,body:t})}put(e,t,s){return this.request("PUT",e,{...s,body:t})}patch(e,t,s){return this.request("PATCH",e,{...s,body:t})}delete(e,t){return this.request("DELETE",e,t)}setAuthToken(e){this.userToken=e;}setRefreshToken(e){this.refreshToken=e;}getHeaders(){let e={...this.defaultHeaders},t=this.userToken||this.anonKey;return t&&(e.Authorization=`Bearer ${t}`),e}async handleTokenRefresh(){return this.isRefreshing?this.refreshPromise:(this.isRefreshing=true,this.refreshPromise=(async()=>{try{let e=ee(),t=this.refreshToken?{refreshToken:this.refreshToken}:void 0,s=await this.handleRequest("POST","/api/auth/refresh",{body:t,headers:e?{"X-CSRF-Token":e}:{},credentials:"include"});return A(s)}finally{this.isRefreshing=false,this.refreshPromise=null;}})(),this.refreshPromise)}};function w(r,e){return r instanceof c?{data:null,error:r}:{data:null,error:new c(r instanceof Error?r.message:e,500,"AUTH_ERROR")}}var U=class{constructor(e,t){this.http=e;this.tokenManager=t;this.tokenManager.onTokenChange=()=>this._emitFromTokenChange();let s=this.tokenManager.getSession();if(s){this.http.setAuthToken(s.accessToken);let n=this.tokenManager.getRefreshToken();n&&this.http.setRefreshToken(n),this.lastEmittedUserId=s.user.id,this.lastEmittedAccessToken=s.accessToken;}}http;tokenManager;stateChangeListeners=new Set;lastEmittedUserId=null;lastEmittedAccessToken=null;onAuthStateChange(e){return this.stateChangeListeners.add(e),{unsubscribe:()=>{this.stateChangeListeners.delete(e);}}}emit(e,t){for(let s of this.stateChangeListeners)try{s(e,t);}catch{}}_emitFromTokenChange(){let e=this.tokenManager.getSession();e?(this.http.setAuthToken(e.accessToken),this.http.setRefreshToken(e.refreshToken??null)):(this.http.setAuthToken(null),this.http.setRefreshToken(null));let t=this.lastEmittedUserId,s=this.lastEmittedAccessToken;if(!e){t!==null&&(this.lastEmittedUserId=null,this.lastEmittedAccessToken=null,this.emit("SIGNED_OUT",null));return}let n=e.user.id;if(t===null){this.lastEmittedUserId=n,this.lastEmittedAccessToken=e.accessToken,this.emit("SIGNED_IN",e);return}if(t!==n){this.lastEmittedUserId=null,this.lastEmittedAccessToken=null,this.emit("SIGNED_OUT",null),this.lastEmittedUserId=n,this.lastEmittedAccessToken=e.accessToken,this.emit("SIGNED_IN",e);return}s!==e.accessToken&&(this.lastEmittedAccessToken=e.accessToken,this.emit("TOKEN_REFRESHED",e));}saveSessionFromResponse(e){let t={accessToken:e.accessToken,refreshToken:e.refreshToken,user:e.user};e.csrfToken&&L(e.csrfToken),this.tokenManager.saveSession(t),this.http.setAuthToken(e.accessToken),this.http.setRefreshToken(e.refreshToken??null);}async signUp(e){try{let t=await this.http.post("/api/auth/register",e,{credentials:"include"}),s=A(t);return s?.accessToken&&s.user&&this.saveSessionFromResponse(s),{data:s,error:null}}catch(t){return w(t,"Sign up failed")}}async signInWithPassword(e){try{let t=await this.http.post("/api/auth/login",e,{credentials:"include"}),s=A(t);return s?.accessToken&&s.user&&this.saveSessionFromResponse(s),{data:s,error:null}}catch(t){return w(t,"Sign in failed")}}async signOut(){try{try{await this.http.post("/api/auth/logout",void 0,{credentials:"include"});}catch{}return this.tokenManager.clearSession(),this.http.setAuthToken(null),this.http.setRefreshToken(null),j(),{error:null}}catch{return {error:new c("Failed to sign out",500,"SIGNOUT_ERROR")}}}async refreshSession(){try{let e=await this.http.handleTokenRefresh();if(e?.accessToken){let t=e.user??this.tokenManager.getUser();if(t){let s={...e,user:t};return this.saveSessionFromResponse(s),{data:s,error:null}}}return {data:e,error:null}}catch(e){return w(e,"Session refresh failed")}}async initialize(){let e=this.tokenManager.getSession();if(!e)return this.emit("INITIAL_SESSION",null),{data:null,error:new c("No persisted session",0,"NO_SESSION")};try{let t=await this.http.get("/api/auth/sessions/current");if(t?.user){this.tokenManager.setUser(t.user);let s=this.tokenManager.getSession();return this.emit("INITIAL_SESSION",s),{data:{user:t.user,accessToken:e.accessToken},error:null}}return this.tokenManager.clearSession(),this.http.setAuthToken(null),this.http.setRefreshToken(null),this.emit("INITIAL_SESSION",null),{data:null,error:new c("Invalid session",401,"INVALID_SESSION")}}catch(t){return this.tokenManager.clearSession(),this.http.setAuthToken(null),this.http.setRefreshToken(null),this.emit("INITIAL_SESSION",null),w(t,"Session restore failed")}}getSession(){return this.tokenManager.getSession()}getUser(){return this.tokenManager.getUser()}async getCurrentUser(){try{let e=await this.http.get("/api/auth/sessions/current");if(e?.user){let t={accessToken:this.tokenManager.getSession()?.accessToken??"",user:e.user};this.tokenManager.saveSession(t);}return {data:e,error:null}}catch(e){return w(e,"Failed to get current user")}}async getProfile(e){try{return {data:await this.http.get(`/api/auth/profiles/${encodeURIComponent(e)}`),error:null}}catch(t){return w(t,"Failed to get profile")}}async setProfile(e){try{let t=await this.http.patch("/api/auth/profiles/current",{profile:e}),s=this.tokenManager.getUser();if(t?.profile&&s){let n={...s,profile:t.profile};this.tokenManager.setUser(n),this.emit("USER_UPDATED",this.tokenManager.getSession());}return {data:t,error:null}}catch(t){return w(t,"Failed to update profile")}}};function he(r,e,t){return async(s,n)=>{let i=typeof s=="string"?s:s.toString(),o=new URL(i),a=o.pathname.startsWith("/")?o.pathname.slice(1):o.pathname,d=a.match(/^rpc\/(.+)$/),p=d?`/api/database/rpc/${d[1]}`:`/api/database/records/${a}`,v=`${r.baseUrl}${p}${o.search}`,F=new Headers(n?.headers);if(!F.has("Authorization")){let T=e.getAccessToken()??t;T&&F.set("Authorization",`Bearer ${T}`);}return fetch(v,{...n,headers:F})}}var O=class{postgrest;httpClient;constructor(e,t,s){this.httpClient=e,this.postgrest=new PostgrestClient("http://dummy",{fetch:he(e,t,s),headers:{}});}from(e){if(!e||typeof e!="string")throw new c("Database.from(table) requires a non-empty string",400,"INVALID_TABLE_NAME");return this.postgrest.from(e)}rpc(e,t,s){return this.postgrest.rpc(e,t,s)}getUrl(){return this.httpClient.baseUrl}};var pe=2e4;function V(r,e){let t=new Error(e);return t.code=r,t}var fe=1e4,$=class{constructor(e,t,s={}){this.topic=e;this.realtime=t;this.options=s;}topic;realtime;bindings=[];state="closed";statusCallback=null;presence={};trackedState=null;presenceHeartbeat=null;lastBroadcastTimestamp=null;options;get isPrivate(){return this.options.config?.private===true}get presenceKey(){return this.options.config?.presence?.key}_state(){return this.state}async _rejoinAfterReconnect(){if(this.state!=="closed"){for(let e of this.bindings)e.type==="postgres_changes"&&(e.subscriptionId=void 0);this.state="joining";try{if(await this.registerAllBindings(),this.trackedState){let e=this.realtime._getSocket(),t=this.presenceKey;e?.emit("realtime:presence:track",t!==void 0?{channel:this.topic,state:this.trackedState,key:t}:{channel:this.topic,state:this.trackedState});}this.lastBroadcastTimestamp&&this.bindings.some(e=>e.type==="broadcast")&&this.replay({since:this.lastBroadcastTimestamp}).catch(()=>{}),this.state="joined",this.statusCallback?.("SUBSCRIBED");}catch(e){this.state="errored",this.statusCallback?.("CHANNEL_ERROR",V("REJOIN_FAILED",e instanceof Error?e.message:String(e)));}}}on(e,t,s){return e==="postgres_changes"?this.bindings.push({type:"postgres_changes",filter:t,callback:s}):e==="broadcast"?this.bindings.push({type:"broadcast",filter:t,callback:s}):this.bindings.push({type:"presence",filter:t,callback:s}),this}async track(e){let t=this.realtime._getSocket();if(!t)throw new c("Socket not connected",503,"NOT_CONNECTED");this.trackedState=e;let s=this.presenceKey;t.emit("realtime:presence:track",s!==void 0?{channel:this.topic,state:e,key:s}:{channel:this.topic,state:e}),this.presenceHeartbeat||(this.presenceHeartbeat=setInterval(()=>{let i=this.realtime._getSocket();i&&this.trackedState&&i.emit("realtime:presence:track",s!==void 0?{channel:this.topic,state:this.trackedState,key:s}:{channel:this.topic,state:this.trackedState});},pe),this.presenceHeartbeat.unref?.());}untrack(){this.trackedState=null,this.presenceHeartbeat&&(clearInterval(this.presenceHeartbeat),this.presenceHeartbeat=null),this.realtime._getSocket()?.emit("realtime:presence:untrack",{channel:this.topic});}presenceState(){return this.presence}subscribe(e){return this.statusCallback=e??null,this.state==="joining"||this.state==="joined"?this:(this.state="joining",this.realtime.connect().then(async()=>{try{await this.registerAllBindings(),this.state="joined",this.statusCallback?.("SUBSCRIBED");}catch(t){this.state="errored";let s=t instanceof Error?t.message:String(t);this.statusCallback?.("CHANNEL_ERROR",V("SUBSCRIBE_FAILED",s));}},t=>{this.state="errored",this.statusCallback?.("CHANNEL_ERROR",V("CONNECT_FAILED",t.message));}),this)}async unsubscribe(){if(this.state==="closed")return;let e=this.realtime._getSocket();if(this.presenceHeartbeat&&(clearInterval(this.presenceHeartbeat),this.presenceHeartbeat=null),!e){this.trackedState=null,this.state="closed";return}this.trackedState&&(e.emit("realtime:presence:untrack",{channel:this.topic}),this.trackedState=null);let t=this.bindings.filter(s=>s.type==="postgres_changes");for(let s of t)s.subscriptionId&&(e.emit("realtime:postgres_changes:unsubscribe",{subscription_id:s.subscriptionId}),s.subscriptionId=void 0);this.bindings.some(s=>s.type==="broadcast"||s.type==="presence")&&e.emit("realtime:unsubscribe",{channel:this.topic}),this.realtime._detachChannel(this),this.state="closed",this.statusCallback?.("CLOSED");}async send(e){if(e.type!=="broadcast")throw new c('Only "broadcast" sends are supported \u2014 DB changes flow via your DB writes, not channel.send()',400,"UNSUPPORTED_SEND_TYPE");if(new Set(["postgres_changes","presence_state","presence_join","presence_leave"]).has(e.event))throw new c(`"${e.event}" is a reserved event name \u2014 pick a different name for broadcast events`,400,"RESERVED_EVENT_NAME");let s=this.realtime._getSocket();if(!s)throw new c("Socket not connected",503,"NOT_CONNECTED");let n=this.options.config?.broadcast?.self,i={channel:this.topic,event:e.event,payload:e.payload};return n===false&&(i.self=false),await new Promise(o=>{s.emit("realtime:publish",i,a=>{o(a);});})}async replay(e){let t=this.realtime._getSocket();if(!t)throw new c("Socket not connected",503,"NOT_CONNECTED");t.emit("realtime:broadcast:replay",{channel:this.topic,since:e.since,limit:e.limit,private:this.isPrivate});}_dispatch(e,t){if(e==="postgres_changes"){let n=t;for(let i of this.bindings)if(!(i.type!=="postgres_changes"||!i.subscriptionId||!n.ids.includes(i.subscriptionId)||!(i.filter.event==="*"||i.filter.event===n.data.eventType)))try{i.callback(n.data);}catch{}return}if(e==="presence_state"||e==="presence_join"||e==="presence_leave"){let n=t;if(n.channel!==this.topic)return;if(e==="presence_state"&&n.state)this.presence={...n.state},this.firePresence({event:"sync",state:this.presence});else if(e==="presence_join"&&n.joins)Object.assign(this.presence,n.joins),this.firePresence({event:"join",joins:n.joins});else if(e==="presence_leave"&&n.leaves){for(let i of Object.keys(n.leaves))delete this.presence[i];this.firePresence({event:"leave",leaves:n.leaves});}return}let s=t.meta;s?.timestamp&&(!this.lastBroadcastTimestamp||s.timestamp>this.lastBroadcastTimestamp)&&(this.lastBroadcastTimestamp=s.timestamp);for(let n of this.bindings){if(n.type!=="broadcast"||n.filter.event!==e)continue;let{meta:i,...o}=t;try{n.callback({type:"broadcast",event:e,payload:o});}catch{}}}firePresence(e){for(let t of this.bindings)if(t.type==="presence"&&t.filter.event===e.event)try{e.event==="sync"?t.callback():(e.event,t.callback(e));}catch{}}async registerAllBindings(){let e=this.realtime._getSocket();if(!e)throw new Error("Socket not available");this.bindings.some(n=>n.type==="broadcast"||n.type==="presence")&&await new Promise((n,i)=>{e.emit("realtime:subscribe",{channel:this.topic,private:this.isPrivate},o=>{o.status==="ok"?n():i(new Error(o.error?.message??"subscribe failed"));});});let s=this.bindings.filter(n=>n.type==="postgres_changes");await Promise.all(s.map(n=>new Promise((i,o)=>{e.emit("realtime:postgres_changes:subscribe",{event:n.filter.event,schema:n.filter.schema??"public",table:n.filter.table,filter:n.filter.filter},a=>{a.status==="ok"&&a.subscription_id?(n.subscriptionId=a.subscription_id,i()):o(new Error(a.error?.message??"postgres_changes subscribe failed"));});})));}},B=class{socket=null;baseUrl;options;anonKey;tokenManager;channels=new Map;connecting=null;firstConnected=false;constructor(e,t,s,n={}){this.baseUrl=e,this.tokenManager=t,this.anonKey=s,this.options=n;}get isConnected(){return this.socket?.connected===true}get socketId(){return this.socket?.id}channel(e,t){let s=this.channels.get(e);if(s)return s;let n=new $(e,this,t);return this.channels.set(e,n),n}connect(){return this.isConnected?Promise.resolve():this.connecting?this.connecting:(this.connecting=this.openSocket(),this.connecting)}disconnect(){this.socket&&(this.socket.disconnect(),this.socket=null,this.firstConnected=false);}_getSocket(){return this.socket}_detachChannel(e){this.channels.delete(e.topic);}openSocket(){let e=this.tokenManager.getAccessToken()??this.anonKey;if(!e){let n=new c("Realtime requires an access token or anonKey",401,"AUTH_INVALID_API_KEY");return this.connecting=null,Promise.reject(n)}let t=this.options.timeoutMs??fe,s=io(this.baseUrl,{path:this.options.path,transports:this.options.transports??["websocket"],auth:{token:e,...this.options.extraAuth??{}},reconnection:true,timeout:t});return this.socket=s,s.onAny((n,...i)=>this.dispatch(n,i)),s.on("connect",()=>{if(this.firstConnected)for(let n of this.channels.values()){let i=n._state();(i==="joined"||i==="errored")&&n._rejoinAfterReconnect();}}),new Promise((n,i)=>{let o=setTimeout(()=>{s.off("connect",d),s.off("connect_error",p),this.connecting=null,i(new c(`Realtime connection timeout after ${t}ms`,408,"CONNECTION_TIMEOUT"));},t),a=()=>{clearTimeout(o),s.off("connect",d),s.off("connect_error",p);},d=()=>{a(),this.connecting=null,this.firstConnected=true,n();},p=v=>{a(),this.connecting=null,i(new c(v.message,0,"CONNECTION_FAILED"));};s.once("connect",d),s.once("connect_error",p);})}dispatch(e,t){if(e==="postgres_changes"){let n=t[0]??{};this.channels.forEach(i=>i._dispatch("postgres_changes",n));return}if(e==="connect"||e==="disconnect"||e==="connect_error"||e==="error"||e==="realtime:error"||e==="realtime:shutdown")return;let s=t[0]??{};this.channels.forEach(n=>n._dispatch(e,s));}};function H(r){return {id:r.id,name:r.name,public:r.public,fileSizeLimitBytes:r.file_size_limit_bytes,allowedMimeTypes:r.allowed_mime_types,createdAt:r.created_at,updatedAt:r.updated_at}}function q(r,e){return {id:r.id,bucket:e,key:r.key,size:r.size,mimeType:r.mime_type,etag:r.etag,cacheControl:r.cache_control,contentDisposition:r.content_disposition,uploadedBy:r.uploaded_by,uploadedAt:r.uploaded_at,updatedAt:r.updated_at}}function me(r){return {defaultFileSizeLimitBytes:r.default_file_size_limit_bytes,maxFileSizeLimitBytes:r.max_file_size_limit_bytes,tenantStorageQuotaBytes:r.tenant_storage_quota_bytes,reservedSpaceBytes:r.reserved_space_bytes,signedUrlDefaultTtlSec:r.signed_url_default_ttl_sec,signedUrlMaxTtlSec:r.signed_url_max_ttl_sec}}function ye(r){return r.split("/").map(encodeURIComponent).join("/")}function h(r,e){return r instanceof c?{data:null,error:r}:{data:null,error:new c(r instanceof Error?r.message:e,0,"STORAGE_ERROR")}}async function Y(r){let e="STORAGE_ERROR",t=`HTTP ${r.status}`;try{let s=await r.json();s&&s.error&&(e=s.error.code??e,t=s.error.message??t);}catch{}return new c(t,r.status,e)}var K=class{constructor(e,t){this.http=e;this.bucketName=t;}http;bucketName;bucketBase(){return `/api/storage/buckets/${encodeURIComponent(this.bucketName)}`}objectPath(e){return `${this.bucketBase()}/objects/${ye(e)}`}async upload(e,t,s={}){try{let n=s.upsert?"PUT":"POST",i={"Content-Type":s.contentType??"application/octet-stream"};s.cacheControl&&(i["Cache-Control"]=s.cacheControl),s.contentDisposition&&(i["Content-Disposition"]=s.contentDisposition);let o=await this.http.rawFetch(this.objectPath(e),{method:n,headers:i,body:t,signal:s.abortSignal});if(!o.ok)return {data:null,error:await Y(o)};let a=await o.json();return a.error||!a.data?{data:null,error:new c(a.error?.message??"Upload failed",o.status,a.error?.code??"STORAGE_ERROR")}:{data:q(a.data,this.bucketName),error:null}}catch(n){return h(n,"Upload failed")}}async download(e,t={}){try{let s={};t.range&&(s.Range=`bytes=${t.range.start}-${t.range.end}`);let n=await this.http.rawFetch(this.objectPath(e),{method:"GET",headers:s,signal:t.abortSignal});return n.ok?{data:await n.blob(),error:null}:{data:null,error:await Y(n)}}catch(s){return h(s,"Download failed")}}async getStream(e,t={}){try{let s={};t.range&&(s.Range=`bytes=${t.range.start}-${t.range.end}`);let n=await this.http.rawFetch(this.objectPath(e),{method:"GET",headers:s,signal:t.abortSignal});return n.ok?n.body?{data:n.body,error:null}:{data:null,error:new c("Response body is not a stream",n.status,"STORAGE_ERROR")}:{data:null,error:await Y(n)}}catch(s){return h(s,"Download failed")}}async remove(e){try{let t=await Promise.allSettled(e.map(i=>this.http.rawFetch(this.objectPath(i),{method:"DELETE"}))),s=[],n=[];for(let i=0;i<e.length;i++){let o=e[i],a=t[i];if(a.status==="fulfilled"&&a.value.ok)s.push(o);else if(a.status==="fulfilled")n.push(`${o}: HTTP ${a.value.status}`);else {let d=a.reason instanceof Error?a.reason.message:String(a.reason);n.push(`${o}: ${d}`);}}return n.length>0?{data:null,error:new c(`Failed to delete some objects: ${n.join("; ")}`,0,"STORAGE_ERROR")}:{data:{removed:s},error:null}}catch(t){return h(t,"Delete failed")}}async list(e={}){try{let t={};return e.prefix!==void 0&&(t.prefix=e.prefix),e.limit!==void 0&&(t.limit=String(e.limit)),e.startAfter!==void 0&&(t.start_after=e.startAfter),{data:(await this.http.get(`${this.bucketBase()}/objects`,{params:t})).map(n=>q(n,this.bucketName)),error:null}}catch(t){return h(t,"List failed")}}async copy(e,t,s){try{let n=await this.http.post(`${this.objectPath(e)}/copy`,{dest_bucket:s??this.bucketName,dest_key:t});return {data:q(n,s??this.bucketName),error:null}}catch(n){return h(n,"Copy failed")}}async move(e,t,s){try{let n=await this.http.post(`${this.objectPath(e)}/move`,{dest_bucket:s??this.bucketName,dest_key:t});return {data:q(n,s??this.bucketName),error:null}}catch(n){return h(n,"Move failed")}}async createSignedUrl(e,t={}){try{let s={};t.expiresIn!==void 0&&(s.expires_in=t.expiresIn);let n=await this.http.post(`${this.objectPath(e)}/sign`,s);return {data:{url:n.url,token:n.token,expiresAt:n.expiresAt},error:null}}catch(s){return h(s,"Sign failed")}}getPublicUrl(e){return {data:{url:`${this.http.baseUrl.replace(/\/$/,"")}${this.objectPath(e)}`}}}},x=class{constructor(e){this.http=e;}http;from(e){return new K(this.http,e)}async listBuckets(){try{return {data:(await this.http.get("/api/storage/buckets")).map(H),error:null}}catch(e){return h(e,"listBuckets failed")}}async getBucket(e){try{let t=await this.http.get(`/api/storage/buckets/${encodeURIComponent(e)}`);return {data:H(t),error:null}}catch(t){return h(t,"getBucket failed")}}async createBucket(e,t={}){try{let s={name:e};t.public!==void 0&&(s.public=t.public),t.fileSizeLimitBytes!==void 0&&(s.file_size_limit_bytes=t.fileSizeLimitBytes),t.allowedMimeTypes!==void 0&&(s.allowed_mime_types=t.allowedMimeTypes);let n=await this.http.post("/api/storage/buckets",s);return {data:H(n),error:null}}catch(s){return h(s,"createBucket failed")}}async updateBucket(e,t){try{let s={};t.public!==void 0&&(s.public=t.public),t.fileSizeLimitBytes!==void 0&&(s.file_size_limit_bytes=t.fileSizeLimitBytes),t.allowedMimeTypes!==void 0&&(s.allowed_mime_types=t.allowedMimeTypes);let n=await this.http.patch(`/api/storage/buckets/${encodeURIComponent(e)}`,s);return {data:H(n),error:null}}catch(s){return h(s,"updateBucket failed")}}async deleteBucket(e){try{return await this.http.delete(`/api/storage/buckets/${encodeURIComponent(e)}`),{data:null,error:null}}catch(t){return h(t,"deleteBucket failed")}}async emptyBucket(e){try{return {data:await this.http.post(`/api/storage/buckets/${encodeURIComponent(e)}/empty`,{}),error:null}}catch(t){return h(t,"emptyBucket failed")}}async getConfig(){try{let e=await this.http.get("/api/storage/config");return {data:me(e),error:null}}catch(e){return h(e,"getConfig failed")}}};function ke(r){return {key:r.key,digest:r.digest,updatedAt:r.updated_at}}function k(r,e){return r instanceof c?{data:null,error:r}:{data:null,error:new c(r instanceof Error?r.message:e,0,"FUNCTIONS_ERROR")}}function Te(r){return typeof r=="object"&&r!==null&&!ArrayBuffer.isView(r)&&!(r instanceof Blob)&&!(r instanceof FormData)&&!(r instanceof URLSearchParams)&&!(r instanceof ReadableStream)}var M=class{constructor(e){this.http=e;}http;async list(){try{return {data:await this.http.get("/api/functions"),error:null}}catch(e){return k(e,"list failed")}}async get(e){try{return {data:await this.http.get(`/api/functions/${encodeURIComponent(e)}`),error:null}}catch(t){return k(t,"get failed")}}async create(e){try{return {data:await this.http.post("/api/functions",e),error:null}}catch(t){return k(t,"create failed")}}async update(e,t){try{return {data:await this.http.put(`/api/functions/${encodeURIComponent(e)}`,t),error:null}}catch(s){return k(s,"update failed")}}async remove(e){try{return await this.http.delete(`/api/functions/${encodeURIComponent(e)}`),{data:{deleted:!0},error:null}}catch(t){return k(t,"remove failed")}}async invoke(e,t={}){try{let s=t.method??"POST",n={...t.headers},i;return t.body!==void 0&&t.body!==null&&(Te(t.body)?(i=JSON.stringify(t.body),n["Content-Type"]||(n["Content-Type"]="application/json")):i=t.body),{data:await this.http.rawFetch(`/api/invoke/${encodeURIComponent(e)}`,{method:s,headers:n,body:i}),error:null}}catch(s){return k(s,"invoke failed")}}async listSecrets(){try{return {data:(await this.http.get("/api/functions/secrets")).secrets.map(ke),error:null}}catch(e){return k(e,"listSecrets failed")}}async setSecrets(e){try{return await this.http.put("/api/functions/secrets",{secrets:e}),{data:{saved:!0},error:null}}catch(t){return k(t,"setSecrets failed")}}async deleteSecret(e){try{return await this.http.delete(`/api/functions/secrets/${encodeURIComponent(e)}`),{data:{deleted:!0},error:null}}catch(t){return k(t,"deleteSecret failed")}}};var C=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function te(r){let e=typeof r=="number"&&Number.isFinite(r)?r:50;return Math.max(1,Math.min(200,Math.trunc(e)))}function be(r){let e=typeof r=="number"&&Number.isFinite(r)?r:100;return Math.max(1,Math.min(500,Math.trunc(e)))}function z(){return {data:null,error:new c("agentId must be a valid UUID",400,"INVALID_INPUT")}}function se(){return {data:null,error:new c("sessionId must be a valid UUID",400,"INVALID_INPUT")}}function E(r,e){return r instanceof c?{data:null,error:r}:{data:null,error:new c(r instanceof Error?r.message:e,0,"AGENTS_ERROR")}}var D=class{constructor(e){this.http=e;}http;async list(e){try{let t=te(e?.limit);return {data:await this.http.get(`/api/agents?limit=${t}`),error:null}}catch(t){return E(t,"list failed")}}async invoke(e,t){if(typeof e!="string"||!C.test(e))return {data:null,error:new c("agentId must be a valid UUID",400,"INVALID_INPUT")};try{let s=t!==void 0?{input:t}:void 0;return {data:await this.http.post(`/api/agents/${encodeURIComponent(e)}/invoke`,s),error:null}}catch(s){return E(s,"invoke failed")}}async chat(e,t,s){if(typeof e!="string"||!C.test(e))return z();try{let n={message:t};s?.sessionId!==void 0&&(n.session_id=s.sessionId),s?.extraContext!==void 0&&(n.extra_context=s.extraContext);let i=await this.http.post(`/api/agents/${encodeURIComponent(e)}/chat`,n);return {data:{sessionId:i.session_id,runId:i.runId,status:i.status,output:i.output,text:i.text,totalTokens:i.totalTokens,totalCost:i.totalCost,error:i.error},error:null}}catch(n){return E(n,"chat failed")}}async listSessions(e,t){if(typeof e!="string"||!C.test(e))return z();try{let s=te(t?.limit);return {data:{sessions:((await this.http.get(`/api/agents/${encodeURIComponent(e)}/sessions?limit=${s}`)).sessions??[]).map(o=>({id:o.id,createdAt:o.created_at,lastActivityAt:o.last_activity_at,messageCount:o.message_count,lastMessagePreview:o.last_message_preview??null}))},error:null}}catch(s){return E(s,"listSessions failed")}}async getMessages(e,t,s){if(typeof e!="string"||!C.test(e))return z();if(typeof t!="string"||!C.test(t))return se();try{let n=be(s?.limit),i=new URLSearchParams;return i.set("limit",String(n)),s?.before!==void 0&&i.set("before",s.before),{data:{messages:((await this.http.get(`/api/agents/${encodeURIComponent(e)}/sessions/${encodeURIComponent(t)}/messages?${i.toString()}`)).messages??[]).map(d=>({id:d.id,role:d.role,content:d.content,createdAt:d.created_at}))},error:null}}catch(n){return E(n,"getMessages failed")}}async deleteSession(e,t){if(typeof e!="string"||!C.test(e))return z();if(typeof t!="string"||!C.test(t))return se();try{return await this.http.delete(`/api/agents/${encodeURIComponent(e)}/sessions/${encodeURIComponent(t)}`),{data:{ok:!0},error:null}}catch(s){return E(s,"deleteSession failed")}}};var _=class{http;tokenManager;auth;database;realtime;storage;functions;agents;constructor(e={}){let t=new R(e.debug);this.tokenManager=new S({persistSession:e.persistSession,storageKey:e.storageKey,storage:e.storage,multiTab:e.multiTab}),this.http=new I(e,this.tokenManager,t),this.auth=new U(this.http,this.tokenManager),this.database=new O(this.http,this.tokenManager,e.anonKey),this.realtime=new B(this.http.baseUrl,this.tokenManager,e.anonKey,e.realtime),this.storage=new x(this.http),this.functions=new M(this.http),this.agents=new D(this.http);}getHttpClient(){return this.http}};function at(r){return new _(r)}var ct=_;
|
|
5
|
-
export{
|
|
4
|
+
`));}};var G="mitway_baas_csrf_token",ae="mitway_baas_session";function Z(){return typeof localStorage<"u"?{getItem:e=>{try{return localStorage.getItem(e)}catch{return null}},setItem:(e,t)=>{try{localStorage.setItem(e,t);}catch{}},removeItem:e=>{try{localStorage.removeItem(e);}catch{}}}:{getItem:()=>null,setItem:()=>{},removeItem:()=>{}}}var ce={getItem:()=>null,setItem:()=>{},removeItem:()=>{}};function ee(){if(typeof document>"u")return null;let n=document.cookie.split(";").find(e=>e.trim().startsWith(`${G}=`));return n&&n.split("=")[1]||null}function L(n){if(typeof document>"u")return;let e=10080*60,t=typeof window<"u"&&window.location.protocol==="https:"?"; Secure":"";document.cookie=`${G}=${encodeURIComponent(n)}; path=/; max-age=${e}; SameSite=Lax${t}`;}function $(){if(typeof document>"u")return;let n=typeof window<"u"&&window.location.protocol==="https:"?"; Secure":"";document.cookie=`${G}=; path=/; max-age=0; SameSite=Lax${n}`;}var w=class{accessToken=null;refreshToken=null;user=null;persistSession;storageKey;storage;onTokenChange=null;constructor(e){this.persistSession=e?.persistSession??true,this.storageKey=e?.storageKey??ae,this.storage=this.persistSession?e?.storage??Z():ce,(e?.multiTab??true)&&this.persistSession&&typeof window<"u"&&typeof localStorage<"u"&&window.addEventListener("storage",this.handleStorageEvent),this.restoreSession();}handleStorageEvent=e=>{e.key===this.storageKey&&(typeof localStorage<"u"&&e.storageArea!==localStorage||this.syncFromStorage(e.newValue));};syncFromStorage(e){let t=this.accessToken;if(e===null)this.accessToken=null,this.refreshToken=null,this.user=null;else try{let r=JSON.parse(e);if(!r.accessToken||!r.user)return;this.accessToken=r.accessToken,this.refreshToken=r.refreshToken??null,this.user=r.user;}catch{return}t!==this.accessToken&&this.onTokenChange&&this.onTokenChange();}saveSession(e){let t=e.accessToken!==this.accessToken;this.accessToken=e.accessToken,this.user=e.user,e.refreshToken!==void 0&&(this.refreshToken=e.refreshToken??null),this.persist(),t&&this.onTokenChange&&this.onTokenChange();}getSession(){return !this.accessToken||!this.user?null:{accessToken:this.accessToken,refreshToken:this.refreshToken??void 0,user:this.user}}getAccessToken(){return this.accessToken}setAccessToken(e){let t=e!==this.accessToken;this.accessToken=e,this.persist(),t&&this.onTokenChange&&this.onTokenChange();}getRefreshToken(){return this.refreshToken}setRefreshToken(e){this.refreshToken=e,this.persist();}getUser(){return this.user}setUser(e){this.user=e,this.persist();}clearSession(){let e=this.accessToken!==null;this.accessToken=null,this.refreshToken=null,this.user=null,this.removePersisted(),e&&this.onTokenChange&&this.onTokenChange();}restoreSession(){if(!this.persistSession)return false;try{let e=this.storage.getItem(this.storageKey);if(!e)return !1;let t=JSON.parse(e);return !t.accessToken||!t.user?!1:(this.accessToken=t.accessToken,this.refreshToken=t.refreshToken??null,this.user=t.user,!0)}catch{return false}}persist(){if(!this.persistSession||!this.accessToken||!this.user)return;let e={accessToken:this.accessToken,user:this.user};this.refreshToken&&(e.refreshToken=this.refreshToken),this.storage.setItem(this.storageKey,JSON.stringify(e));}removePersisted(){this.persistSession&&this.storage.removeItem(this.storageKey);}};function A(n){if(!n||typeof n!="object")return n;let e=n,t={...e},r=false;return "access_token"in e&&!("accessToken"in e)&&(t.accessToken=e.access_token,delete t.access_token,r=true),"csrf_token"in e&&!("csrfToken"in e)&&(t.csrfToken=e.csrf_token,delete t.csrf_token,r=true),"refresh_token"in e&&!("refreshToken"in e)&&(t.refreshToken=e.refresh_token,delete t.refresh_token,r=true),r?t:n}var le=new Set([500,502,503,504]),ue=new Set(["GET","HEAD","PUT","DELETE","OPTIONS"]),O=class{baseUrl;fetch;defaultHeaders;anonKey;userToken=null;logger;autoRefreshToken=true;isRefreshing=false;refreshPromise=null;tokenManager;refreshToken=null;timeout;retryCount;retryDelay;constructor(e,t,r){if(this.baseUrl=e.baseUrl||"http://localhost:7130",this.autoRefreshToken=e.autoRefreshToken??true,this.fetch=e.fetch||(globalThis.fetch?globalThis.fetch.bind(globalThis):void 0),this.anonKey=e.anonKey,this.defaultHeaders={...e.headers},this.tokenManager=t??new w,this.logger=r||new R(false),this.timeout=e.timeout??3e4,this.retryCount=e.retryCount??3,this.retryDelay=e.retryDelay??500,!this.fetch)throw new Error("Fetch is not available. Provide a fetch implementation in the SDK config.")}buildUrl(e,t){let r=new URL(e,this.baseUrl);return t&&Object.entries(t).forEach(([s,i])=>{if(s==="select"){let o=i.replace(/\s+/g," ").trim();o=o.replace(/\s*\(\s*/g,"(").replace(/\s*\)\s*/g,")").replace(/\(\s+/g,"(").replace(/\s+\)/g,")").replace(/,\s+(?=[^()]*\))/g,","),r.searchParams.append(s,o);}else r.searchParams.append(s,i);}),r.toString()}isRetryableStatus(e){return le.has(e)}computeRetryDelay(e){let r=this.retryDelay*Math.pow(2,e-1)*(.85+Math.random()*.3);return Math.round(r)}async handleRequest(e,t,r={}){let{params:s,headers:i={},body:o,signal:a,...d}=r,p=this.buildUrl(t,s),C=Date.now(),b=ue.has(e.toUpperCase())||r.idempotent===true?this.retryCount:0,S={...this.defaultHeaders},Q=this.userToken||this.anonKey;Q&&(S.Authorization=`Bearer ${Q}`);let N;o!==void 0&&(typeof FormData<"u"&&o instanceof FormData?N=o:(e!=="GET"&&(S["Content-Type"]="application/json;charset=UTF-8"),N=JSON.stringify(o))),i instanceof Headers?i.forEach((f,g)=>{S[g]=f;}):Array.isArray(i)?i.forEach(([f,g])=>{S[f]=g;}):Object.assign(S,i),this.logger.logRequest(e,p,S,N);let W;for(let f=0;f<=b;f++){if(f>0){let l=this.computeRetryDelay(f);if(this.logger.warn(`Retry ${f}/${b} for ${e} ${p} in ${l}ms`),a?.aborted)throw a.reason;await new Promise((u,J)=>{let y=()=>{clearTimeout(se),J(a.reason);},se=setTimeout(()=>{a&&a.removeEventListener("abort",y),u();},l);a&&a.addEventListener("abort",y,{once:true});});}let g,m;if((this.timeout>0||a)&&(g=new AbortController,this.timeout>0&&(m=setTimeout(()=>g.abort(),this.timeout)),a))if(a.aborted)g.abort(a.reason);else {let l=()=>g.abort(a.reason);a.addEventListener("abort",l,{once:true}),g.signal.addEventListener("abort",()=>{a.removeEventListener("abort",l);},{once:true});}try{let l=await this.fetch(p,{method:e,headers:S,body:N,...d,...g?{signal:g.signal}:{}});if(this.isRetryableStatus(l.status)&&f<b){m!==void 0&&clearTimeout(m),await l.body?.cancel(),W=new c(`Server error: ${l.status} ${l.statusText}`,l.status,"SERVER_ERROR");continue}if(l.status===204){m!==void 0&&clearTimeout(m);return}let u,J=l.headers.get("content-type");try{J?.includes("json")?u=await l.json():u=await l.text();}catch(y){throw m!==void 0&&clearTimeout(m),new c(`Failed to parse response body: ${y?.message||"Unknown error"}`,l.status,l.ok?"PARSE_ERROR":"REQUEST_FAILED")}if(m!==void 0&&clearTimeout(m),!l.ok){if(this.logger.logResponse(e,p,l.status,Date.now()-C,u),u&&typeof u=="object"&&"error"in u&&u.error!==null&&typeof u.error=="object"){let y=u.error;throw new c(y.message||l.statusText||"Request failed",y.statusCode||l.status,y.code||y.error||"REQUEST_FAILED",y.nextActions)}throw new c(`Request failed: ${l.statusText}`,l.status,"REQUEST_FAILED")}return this.logger.logResponse(e,p,l.status,Date.now()-C,u),u&&typeof u=="object"&&"data"in u&&"error"in u&&u.error===null?u.data:u}catch(l){if(m!==void 0&&clearTimeout(m),l?.name==="AbortError")throw g&&g.signal.aborted&&this.timeout>0&&!a?.aborted?new c(`Request timed out after ${this.timeout}ms`,408,"REQUEST_TIMEOUT"):l;if(l instanceof c)throw l;if(f<b){W=l;continue}throw new c(`Network request failed: ${l?.message||"Unknown error"}`,0,"NETWORK_ERROR")}}throw W||new c("Request failed after all retry attempts",0,"NETWORK_ERROR")}async request(e,t,r={}){try{return await this.handleRequest(e,t,{...r})}catch(s){if(s instanceof c&&s.statusCode===401&&this.autoRefreshToken&&this.refreshToken&&!t.includes("/api/auth/refresh"))try{let i=await this.handleTokenRefresh();this.setAuthToken(i.accessToken),i.refreshToken&&this.setRefreshToken(i.refreshToken),i.csrfToken&&L(i.csrfToken);let o=i.user??this.tokenManager.getUser();return o&&this.tokenManager.saveSession({accessToken:i.accessToken,refreshToken:i.refreshToken,user:o}),await this.handleRequest(e,t,{...r})}catch(i){throw this.tokenManager.clearSession(),this.userToken=null,this.refreshToken=null,$(),i}throw s}}async rawFetch(e,t={}){let r=this.buildUrl(e),s=new Headers(t.headers??{});for(let[i,o]of Object.entries(this.defaultHeaders))s.has(i)||s.set(i,o);if(!s.has("Authorization")){let i=this.userToken??this.anonKey;i&&s.set("Authorization",`Bearer ${i}`);}return this.fetch(r,{...t,headers:s})}get(e,t){return this.request("GET",e,t)}post(e,t,r){return this.request("POST",e,{...r,body:t})}put(e,t,r){return this.request("PUT",e,{...r,body:t})}patch(e,t,r){return this.request("PATCH",e,{...r,body:t})}delete(e,t){return this.request("DELETE",e,t)}setAuthToken(e){this.userToken=e;}setRefreshToken(e){this.refreshToken=e;}getHeaders(){let e={...this.defaultHeaders},t=this.userToken||this.anonKey;return t&&(e.Authorization=`Bearer ${t}`),e}async handleTokenRefresh(){return this.isRefreshing?this.refreshPromise:(this.isRefreshing=true,this.refreshPromise=(async()=>{try{let e=ee(),t=this.refreshToken?{refreshToken:this.refreshToken}:void 0,r=await this.handleRequest("POST","/api/auth/refresh",{body:t,headers:e?{"X-CSRF-Token":e}:{},credentials:"include"});return A(r)}finally{this.isRefreshing=false,this.refreshPromise=null;}})(),this.refreshPromise)}};function k(n,e){return n instanceof c?{data:null,error:n}:{data:null,error:new c(n instanceof Error?n.message:e,500,"AUTH_ERROR")}}var I=class{constructor(e,t){this.http=e;this.tokenManager=t;this.tokenManager.onTokenChange=()=>this._emitFromTokenChange();let r=this.tokenManager.getSession();if(r){this.http.setAuthToken(r.accessToken);let s=this.tokenManager.getRefreshToken();s&&this.http.setRefreshToken(s),this.lastEmittedUserId=r.user.id,this.lastEmittedAccessToken=r.accessToken;}}http;tokenManager;stateChangeListeners=new Set;lastEmittedUserId=null;lastEmittedAccessToken=null;onAuthStateChange(e){return this.stateChangeListeners.add(e),{unsubscribe:()=>{this.stateChangeListeners.delete(e);}}}emit(e,t){for(let r of this.stateChangeListeners)try{r(e,t);}catch{}}_emitFromTokenChange(){let e=this.tokenManager.getSession();e?(this.http.setAuthToken(e.accessToken),this.http.setRefreshToken(e.refreshToken??null)):(this.http.setAuthToken(null),this.http.setRefreshToken(null));let t=this.lastEmittedUserId,r=this.lastEmittedAccessToken;if(!e){t!==null&&(this.lastEmittedUserId=null,this.lastEmittedAccessToken=null,this.emit("SIGNED_OUT",null));return}let s=e.user.id;if(t===null){this.lastEmittedUserId=s,this.lastEmittedAccessToken=e.accessToken,this.emit("SIGNED_IN",e);return}if(t!==s){this.lastEmittedUserId=null,this.lastEmittedAccessToken=null,this.emit("SIGNED_OUT",null),this.lastEmittedUserId=s,this.lastEmittedAccessToken=e.accessToken,this.emit("SIGNED_IN",e);return}r!==e.accessToken&&(this.lastEmittedAccessToken=e.accessToken,this.emit("TOKEN_REFRESHED",e));}saveSessionFromResponse(e){let t={accessToken:e.accessToken,refreshToken:e.refreshToken,user:e.user};e.csrfToken&&L(e.csrfToken),this.tokenManager.saveSession(t),this.http.setAuthToken(e.accessToken),this.http.setRefreshToken(e.refreshToken??null);}async signUp(e){try{let t=await this.http.post("/api/auth/register",e,{credentials:"include"}),r=A(t);return r?.accessToken&&r.user&&this.saveSessionFromResponse(r),{data:r,error:null}}catch(t){return k(t,"Sign up failed")}}async signInWithPassword(e){try{let t=await this.http.post("/api/auth/login",e,{credentials:"include"}),r=A(t);return r?.accessToken&&r.user&&this.saveSessionFromResponse(r),{data:r,error:null}}catch(t){return k(t,"Sign in failed")}}async setSession(e){let t={accessToken:e.access_token,refreshToken:e.refresh_token??void 0,user:e.user};return this.saveSessionFromResponse(t),{data:t,error:null}}async getSSOConfig(){try{return {data:await this.http.get("/api/auth/sso/config"),error:null}}catch(e){return k(e,"Failed to load SSO config")}}async signInWithSSO(e,t){try{if(typeof window>"u")throw new Error("signInWithSSO requires a browser");let{data:r,error:s}=await this.getSSOConfig();if(s||!r)return {data:null,error:s??new c("SSO config unavailable",500,"SSO_ERROR")};if(!r.broker_url)throw new Error("SSO broker not configured for this tenant");let i=r.providers.find(a=>a.provider===e);if(!i||!i.enabled)throw new Error(`Provider '${e}' is not enabled`);let o=new URL(`${r.broker_url.replace(/\/$/,"")}/api/oauth/${e}/login`);return r.tenant_slug&&o.searchParams.set("tenant",r.tenant_slug),r.tenant_env&&o.searchParams.set("env",r.tenant_env),o.searchParams.set("returnUrl",t.returnUrl),window.location.assign(o.toString()),{data:null,error:null}}catch(r){return k(r,"SSO sign-in failed")}}async completeSSO(){try{if(typeof globalThis.fetch>"u")throw new Error("completeSSO requires fetch");let{data:e,error:t}=await this.getSSOConfig();if(t||!e?.broker_url)throw new Error("SSO broker not configured");let r=await globalThis.fetch(`${e.broker_url.replace(/\/$/,"")}/api/oauth/microsoft/exchange`,{method:"POST",credentials:"include"}),s=await r.json().catch(()=>({}));if(!r.ok||s.error)throw new Error(s.error?.message??"SSO exchange failed");if(!s.data)throw new Error("SSO exchange returned no session");let{access_token:i,refresh_token:o,user:a}=s.data;return this.setSession({access_token:i,refresh_token:o,user:a})}catch(e){return k(e,"SSO completion failed")}}async signOut(){try{try{await this.http.post("/api/auth/logout",void 0,{credentials:"include"});}catch{}return this.tokenManager.clearSession(),this.http.setAuthToken(null),this.http.setRefreshToken(null),$(),{error:null}}catch{return {error:new c("Failed to sign out",500,"SIGNOUT_ERROR")}}}async refreshSession(){try{let e=await this.http.handleTokenRefresh();if(e?.accessToken){let t=e.user??this.tokenManager.getUser();if(t){let r={...e,user:t};return this.saveSessionFromResponse(r),{data:r,error:null}}}return {data:e,error:null}}catch(e){return k(e,"Session refresh failed")}}async initialize(){let e=this.tokenManager.getSession();if(!e)return this.emit("INITIAL_SESSION",null),{data:null,error:new c("No persisted session",0,"NO_SESSION")};try{let t=await this.http.get("/api/auth/sessions/current");if(t?.user){this.tokenManager.setUser(t.user);let r=this.tokenManager.getSession();return this.emit("INITIAL_SESSION",r),{data:{user:t.user,accessToken:e.accessToken},error:null}}return this.tokenManager.clearSession(),this.http.setAuthToken(null),this.http.setRefreshToken(null),this.emit("INITIAL_SESSION",null),{data:null,error:new c("Invalid session",401,"INVALID_SESSION")}}catch(t){return this.tokenManager.clearSession(),this.http.setAuthToken(null),this.http.setRefreshToken(null),this.emit("INITIAL_SESSION",null),k(t,"Session restore failed")}}getSession(){return this.tokenManager.getSession()}getUser(){return this.tokenManager.getUser()}async getCurrentUser(){try{let e=await this.http.get("/api/auth/sessions/current");if(e?.user){let t={accessToken:this.tokenManager.getSession()?.accessToken??"",user:e.user};this.tokenManager.saveSession(t);}return {data:e,error:null}}catch(e){return k(e,"Failed to get current user")}}async getProfile(e){try{return {data:await this.http.get(`/api/auth/profiles/${encodeURIComponent(e)}`),error:null}}catch(t){return k(t,"Failed to get profile")}}async setProfile(e){try{let t=await this.http.patch("/api/auth/profiles/current",{profile:e}),r=this.tokenManager.getUser();if(t?.profile&&r){let s={...r,profile:t.profile};this.tokenManager.setUser(s),this.emit("USER_UPDATED",this.tokenManager.getSession());}return {data:t,error:null}}catch(t){return k(t,"Failed to update profile")}}};function he(n,e,t){return async(r,s)=>{let i=typeof r=="string"?r:r.toString(),o=new URL(i),a=o.pathname.startsWith("/")?o.pathname.slice(1):o.pathname,d=a.match(/^rpc\/(.+)$/),p=d?`/api/database/rpc/${d[1]}`:`/api/database/records/${a}`,C=`${n.baseUrl}${p}${o.search}`,D=new Headers(s?.headers);if(!D.has("Authorization")){let b=e.getAccessToken()??t;b&&D.set("Authorization",`Bearer ${b}`);}return fetch(C,{...s,headers:D})}}var U=class{postgrest;httpClient;constructor(e,t,r){this.httpClient=e,this.postgrest=new PostgrestClient("http://dummy",{fetch:he(e,t,r),headers:{}});}from(e){if(!e||typeof e!="string")throw new c("Database.from(table) requires a non-empty string",400,"INVALID_TABLE_NAME");return this.postgrest.from(e)}rpc(e,t,r){return this.postgrest.rpc(e,t,r)}getUrl(){return this.httpClient.baseUrl}};var pe=2e4;function V(n,e){let t=new Error(e);return t.code=n,t}var fe=1e4,j=class{constructor(e,t,r={}){this.topic=e;this.realtime=t;this.options=r;}topic;realtime;bindings=[];state="closed";statusCallback=null;presence={};trackedState=null;presenceHeartbeat=null;lastBroadcastTimestamp=null;options;get isPrivate(){return this.options.config?.private===true}get presenceKey(){return this.options.config?.presence?.key}_state(){return this.state}async _rejoinAfterReconnect(){if(this.state!=="closed"){for(let e of this.bindings)e.type==="postgres_changes"&&(e.subscriptionId=void 0);this.state="joining";try{if(await this.registerAllBindings(),this.trackedState){let e=this.realtime._getSocket(),t=this.presenceKey;e?.emit("realtime:presence:track",t!==void 0?{channel:this.topic,state:this.trackedState,key:t}:{channel:this.topic,state:this.trackedState});}this.lastBroadcastTimestamp&&this.bindings.some(e=>e.type==="broadcast")&&this.replay({since:this.lastBroadcastTimestamp}).catch(()=>{}),this.state="joined",this.statusCallback?.("SUBSCRIBED");}catch(e){this.state="errored",this.statusCallback?.("CHANNEL_ERROR",V("REJOIN_FAILED",e instanceof Error?e.message:String(e)));}}}on(e,t,r){return e==="postgres_changes"?this.bindings.push({type:"postgres_changes",filter:t,callback:r}):e==="broadcast"?this.bindings.push({type:"broadcast",filter:t,callback:r}):this.bindings.push({type:"presence",filter:t,callback:r}),this}async track(e){let t=this.realtime._getSocket();if(!t)throw new c("Socket not connected",503,"NOT_CONNECTED");this.trackedState=e;let r=this.presenceKey;t.emit("realtime:presence:track",r!==void 0?{channel:this.topic,state:e,key:r}:{channel:this.topic,state:e}),this.presenceHeartbeat||(this.presenceHeartbeat=setInterval(()=>{let i=this.realtime._getSocket();i&&this.trackedState&&i.emit("realtime:presence:track",r!==void 0?{channel:this.topic,state:this.trackedState,key:r}:{channel:this.topic,state:this.trackedState});},pe),this.presenceHeartbeat.unref?.());}untrack(){this.trackedState=null,this.presenceHeartbeat&&(clearInterval(this.presenceHeartbeat),this.presenceHeartbeat=null),this.realtime._getSocket()?.emit("realtime:presence:untrack",{channel:this.topic});}presenceState(){return this.presence}subscribe(e){return this.statusCallback=e??null,this.state==="joining"||this.state==="joined"?this:(this.state="joining",this.realtime.connect().then(async()=>{try{await this.registerAllBindings(),this.state="joined",this.statusCallback?.("SUBSCRIBED");}catch(t){this.state="errored";let r=t instanceof Error?t.message:String(t);this.statusCallback?.("CHANNEL_ERROR",V("SUBSCRIBE_FAILED",r));}},t=>{this.state="errored",this.statusCallback?.("CHANNEL_ERROR",V("CONNECT_FAILED",t.message));}),this)}async unsubscribe(){if(this.state==="closed")return;let e=this.realtime._getSocket();if(this.presenceHeartbeat&&(clearInterval(this.presenceHeartbeat),this.presenceHeartbeat=null),!e){this.trackedState=null,this.state="closed";return}this.trackedState&&(e.emit("realtime:presence:untrack",{channel:this.topic}),this.trackedState=null);let t=this.bindings.filter(r=>r.type==="postgres_changes");for(let r of t)r.subscriptionId&&(e.emit("realtime:postgres_changes:unsubscribe",{subscription_id:r.subscriptionId}),r.subscriptionId=void 0);this.bindings.some(r=>r.type==="broadcast"||r.type==="presence")&&e.emit("realtime:unsubscribe",{channel:this.topic}),this.realtime._detachChannel(this),this.state="closed",this.statusCallback?.("CLOSED");}async send(e){if(e.type!=="broadcast")throw new c('Only "broadcast" sends are supported \u2014 DB changes flow via your DB writes, not channel.send()',400,"UNSUPPORTED_SEND_TYPE");if(new Set(["postgres_changes","presence_state","presence_join","presence_leave"]).has(e.event))throw new c(`"${e.event}" is a reserved event name \u2014 pick a different name for broadcast events`,400,"RESERVED_EVENT_NAME");let r=this.realtime._getSocket();if(!r)throw new c("Socket not connected",503,"NOT_CONNECTED");let s=this.options.config?.broadcast?.self,i={channel:this.topic,event:e.event,payload:e.payload};return s===false&&(i.self=false),await new Promise(o=>{r.emit("realtime:publish",i,a=>{o(a);});})}async replay(e){let t=this.realtime._getSocket();if(!t)throw new c("Socket not connected",503,"NOT_CONNECTED");t.emit("realtime:broadcast:replay",{channel:this.topic,since:e.since,limit:e.limit,private:this.isPrivate});}_dispatch(e,t){if(e==="postgres_changes"){let s=t;for(let i of this.bindings)if(!(i.type!=="postgres_changes"||!i.subscriptionId||!s.ids.includes(i.subscriptionId)||!(i.filter.event==="*"||i.filter.event===s.data.eventType)))try{i.callback(s.data);}catch{}return}if(e==="presence_state"||e==="presence_join"||e==="presence_leave"){let s=t;if(s.channel!==this.topic)return;if(e==="presence_state"&&s.state)this.presence={...s.state},this.firePresence({event:"sync",state:this.presence});else if(e==="presence_join"&&s.joins)Object.assign(this.presence,s.joins),this.firePresence({event:"join",joins:s.joins});else if(e==="presence_leave"&&s.leaves){for(let i of Object.keys(s.leaves))delete this.presence[i];this.firePresence({event:"leave",leaves:s.leaves});}return}let r=t.meta;r?.timestamp&&(!this.lastBroadcastTimestamp||r.timestamp>this.lastBroadcastTimestamp)&&(this.lastBroadcastTimestamp=r.timestamp);for(let s of this.bindings){if(s.type!=="broadcast"||s.filter.event!==e)continue;let{meta:i,...o}=t;try{s.callback({type:"broadcast",event:e,payload:o});}catch{}}}firePresence(e){for(let t of this.bindings)if(t.type==="presence"&&t.filter.event===e.event)try{e.event==="sync"?t.callback():(e.event,t.callback(e));}catch{}}async registerAllBindings(){let e=this.realtime._getSocket();if(!e)throw new Error("Socket not available");this.bindings.some(s=>s.type==="broadcast"||s.type==="presence")&&await new Promise((s,i)=>{e.emit("realtime:subscribe",{channel:this.topic,private:this.isPrivate},o=>{o.status==="ok"?s():i(new Error(o.error?.message??"subscribe failed"));});});let r=this.bindings.filter(s=>s.type==="postgres_changes");await Promise.all(r.map(s=>new Promise((i,o)=>{e.emit("realtime:postgres_changes:subscribe",{event:s.filter.event,schema:s.filter.schema??"public",table:s.filter.table,filter:s.filter.filter},a=>{a.status==="ok"&&a.subscription_id?(s.subscriptionId=a.subscription_id,i()):o(new Error(a.error?.message??"postgres_changes subscribe failed"));});})));}},B=class{socket=null;baseUrl;options;anonKey;tokenManager;channels=new Map;connecting=null;firstConnected=false;constructor(e,t,r,s={}){this.baseUrl=e,this.tokenManager=t,this.anonKey=r,this.options=s;}get isConnected(){return this.socket?.connected===true}get socketId(){return this.socket?.id}channel(e,t){let r=this.channels.get(e);if(r)return r;let s=new j(e,this,t);return this.channels.set(e,s),s}connect(){return this.isConnected?Promise.resolve():this.connecting?this.connecting:(this.connecting=this.openSocket(),this.connecting)}disconnect(){this.socket&&(this.socket.disconnect(),this.socket=null,this.firstConnected=false);}_getSocket(){return this.socket}_detachChannel(e){this.channels.delete(e.topic);}openSocket(){let e=this.tokenManager.getAccessToken()??this.anonKey;if(!e){let s=new c("Realtime requires an access token or anonKey",401,"AUTH_INVALID_API_KEY");return this.connecting=null,Promise.reject(s)}let t=this.options.timeoutMs??fe,r=io(this.baseUrl,{path:this.options.path,transports:this.options.transports??["websocket"],auth:{token:e,...this.options.extraAuth??{}},reconnection:true,timeout:t});return this.socket=r,r.onAny((s,...i)=>this.dispatch(s,i)),r.on("connect",()=>{if(this.firstConnected)for(let s of this.channels.values()){let i=s._state();(i==="joined"||i==="errored")&&s._rejoinAfterReconnect();}}),new Promise((s,i)=>{let o=setTimeout(()=>{r.off("connect",d),r.off("connect_error",p),this.connecting=null,i(new c(`Realtime connection timeout after ${t}ms`,408,"CONNECTION_TIMEOUT"));},t),a=()=>{clearTimeout(o),r.off("connect",d),r.off("connect_error",p);},d=()=>{a(),this.connecting=null,this.firstConnected=true,s();},p=C=>{a(),this.connecting=null,i(new c(C.message,0,"CONNECTION_FAILED"));};r.once("connect",d),r.once("connect_error",p);})}dispatch(e,t){if(e==="postgres_changes"){let s=t[0]??{};this.channels.forEach(i=>i._dispatch("postgres_changes",s));return}if(e==="connect"||e==="disconnect"||e==="connect_error"||e==="error"||e==="realtime:error"||e==="realtime:shutdown")return;let r=t[0]??{};this.channels.forEach(s=>s._dispatch(e,r));}};function q(n){return {id:n.id,name:n.name,public:n.public,fileSizeLimitBytes:n.file_size_limit_bytes,allowedMimeTypes:n.allowed_mime_types,createdAt:n.created_at,updatedAt:n.updated_at}}function H(n,e){return {id:n.id,bucket:e,key:n.key,size:n.size,mimeType:n.mime_type,etag:n.etag,cacheControl:n.cache_control,contentDisposition:n.content_disposition,uploadedBy:n.uploaded_by,uploadedAt:n.uploaded_at,updatedAt:n.updated_at}}function me(n){return {defaultFileSizeLimitBytes:n.default_file_size_limit_bytes,maxFileSizeLimitBytes:n.max_file_size_limit_bytes,tenantStorageQuotaBytes:n.tenant_storage_quota_bytes,reservedSpaceBytes:n.reserved_space_bytes,signedUrlDefaultTtlSec:n.signed_url_default_ttl_sec,signedUrlMaxTtlSec:n.signed_url_max_ttl_sec}}function ye(n){return n.split("/").map(encodeURIComponent).join("/")}function h(n,e){return n instanceof c?{data:null,error:n}:{data:null,error:new c(n instanceof Error?n.message:e,0,"STORAGE_ERROR")}}async function Y(n){let e="STORAGE_ERROR",t=`HTTP ${n.status}`;try{let r=await n.json();r&&r.error&&(e=r.error.code??e,t=r.error.message??t);}catch{}return new c(t,n.status,e)}var K=class{constructor(e,t){this.http=e;this.bucketName=t;}http;bucketName;bucketBase(){return `/api/storage/buckets/${encodeURIComponent(this.bucketName)}`}objectPath(e){return `${this.bucketBase()}/objects/${ye(e)}`}async upload(e,t,r={}){try{let s=r.upsert?"PUT":"POST",i={"Content-Type":r.contentType??"application/octet-stream"};r.cacheControl&&(i["Cache-Control"]=r.cacheControl),r.contentDisposition&&(i["Content-Disposition"]=r.contentDisposition);let o=await this.http.rawFetch(this.objectPath(e),{method:s,headers:i,body:t,signal:r.abortSignal});if(!o.ok)return {data:null,error:await Y(o)};let a=await o.json();return a.error||!a.data?{data:null,error:new c(a.error?.message??"Upload failed",o.status,a.error?.code??"STORAGE_ERROR")}:{data:H(a.data,this.bucketName),error:null}}catch(s){return h(s,"Upload failed")}}async download(e,t={}){try{let r={};t.range&&(r.Range=`bytes=${t.range.start}-${t.range.end}`);let s=await this.http.rawFetch(this.objectPath(e),{method:"GET",headers:r,signal:t.abortSignal});return s.ok?{data:await s.blob(),error:null}:{data:null,error:await Y(s)}}catch(r){return h(r,"Download failed")}}async getStream(e,t={}){try{let r={};t.range&&(r.Range=`bytes=${t.range.start}-${t.range.end}`);let s=await this.http.rawFetch(this.objectPath(e),{method:"GET",headers:r,signal:t.abortSignal});return s.ok?s.body?{data:s.body,error:null}:{data:null,error:new c("Response body is not a stream",s.status,"STORAGE_ERROR")}:{data:null,error:await Y(s)}}catch(r){return h(r,"Download failed")}}async remove(e){try{let t=await Promise.allSettled(e.map(i=>this.http.rawFetch(this.objectPath(i),{method:"DELETE"}))),r=[],s=[];for(let i=0;i<e.length;i++){let o=e[i],a=t[i];if(a.status==="fulfilled"&&a.value.ok)r.push(o);else if(a.status==="fulfilled")s.push(`${o}: HTTP ${a.value.status}`);else {let d=a.reason instanceof Error?a.reason.message:String(a.reason);s.push(`${o}: ${d}`);}}return s.length>0?{data:null,error:new c(`Failed to delete some objects: ${s.join("; ")}`,0,"STORAGE_ERROR")}:{data:{removed:r},error:null}}catch(t){return h(t,"Delete failed")}}async list(e={}){try{let t={};return e.prefix!==void 0&&(t.prefix=e.prefix),e.limit!==void 0&&(t.limit=String(e.limit)),e.startAfter!==void 0&&(t.start_after=e.startAfter),{data:(await this.http.get(`${this.bucketBase()}/objects`,{params:t})).map(s=>H(s,this.bucketName)),error:null}}catch(t){return h(t,"List failed")}}async copy(e,t,r){try{let s=await this.http.post(`${this.objectPath(e)}/copy`,{dest_bucket:r??this.bucketName,dest_key:t});return {data:H(s,r??this.bucketName),error:null}}catch(s){return h(s,"Copy failed")}}async move(e,t,r){try{let s=await this.http.post(`${this.objectPath(e)}/move`,{dest_bucket:r??this.bucketName,dest_key:t});return {data:H(s,r??this.bucketName),error:null}}catch(s){return h(s,"Move failed")}}async createSignedUrl(e,t={}){try{let r={};t.expiresIn!==void 0&&(r.expires_in=t.expiresIn);let s=await this.http.post(`${this.objectPath(e)}/sign`,r);return {data:{url:s.url,token:s.token,expiresAt:s.expiresAt},error:null}}catch(r){return h(r,"Sign failed")}}getPublicUrl(e){return {data:{url:`${this.http.baseUrl.replace(/\/$/,"")}${this.objectPath(e)}`}}}},x=class{constructor(e){this.http=e;}http;from(e){return new K(this.http,e)}async listBuckets(){try{return {data:(await this.http.get("/api/storage/buckets")).map(q),error:null}}catch(e){return h(e,"listBuckets failed")}}async getBucket(e){try{let t=await this.http.get(`/api/storage/buckets/${encodeURIComponent(e)}`);return {data:q(t),error:null}}catch(t){return h(t,"getBucket failed")}}async createBucket(e,t={}){try{let r={name:e};t.public!==void 0&&(r.public=t.public),t.fileSizeLimitBytes!==void 0&&(r.file_size_limit_bytes=t.fileSizeLimitBytes),t.allowedMimeTypes!==void 0&&(r.allowed_mime_types=t.allowedMimeTypes);let s=await this.http.post("/api/storage/buckets",r);return {data:q(s),error:null}}catch(r){return h(r,"createBucket failed")}}async updateBucket(e,t){try{let r={};t.public!==void 0&&(r.public=t.public),t.fileSizeLimitBytes!==void 0&&(r.file_size_limit_bytes=t.fileSizeLimitBytes),t.allowedMimeTypes!==void 0&&(r.allowed_mime_types=t.allowedMimeTypes);let s=await this.http.patch(`/api/storage/buckets/${encodeURIComponent(e)}`,r);return {data:q(s),error:null}}catch(r){return h(r,"updateBucket failed")}}async deleteBucket(e){try{return await this.http.delete(`/api/storage/buckets/${encodeURIComponent(e)}`),{data:null,error:null}}catch(t){return h(t,"deleteBucket failed")}}async emptyBucket(e){try{return {data:await this.http.post(`/api/storage/buckets/${encodeURIComponent(e)}/empty`,{}),error:null}}catch(t){return h(t,"emptyBucket failed")}}async getConfig(){try{let e=await this.http.get("/api/storage/config");return {data:me(e),error:null}}catch(e){return h(e,"getConfig failed")}}};function ke(n){return {key:n.key,digest:n.digest,updatedAt:n.updated_at}}function T(n,e){return n instanceof c?{data:null,error:n}:{data:null,error:new c(n instanceof Error?n.message:e,0,"FUNCTIONS_ERROR")}}function Te(n){return typeof n=="object"&&n!==null&&!ArrayBuffer.isView(n)&&!(n instanceof Blob)&&!(n instanceof FormData)&&!(n instanceof URLSearchParams)&&!(n instanceof ReadableStream)}var M=class{constructor(e){this.http=e;}http;async list(){try{return {data:await this.http.get("/api/functions"),error:null}}catch(e){return T(e,"list failed")}}async get(e){try{return {data:await this.http.get(`/api/functions/${encodeURIComponent(e)}`),error:null}}catch(t){return T(t,"get failed")}}async create(e){try{return {data:await this.http.post("/api/functions",e),error:null}}catch(t){return T(t,"create failed")}}async update(e,t){try{return {data:await this.http.put(`/api/functions/${encodeURIComponent(e)}`,t),error:null}}catch(r){return T(r,"update failed")}}async remove(e){try{return await this.http.delete(`/api/functions/${encodeURIComponent(e)}`),{data:{deleted:!0},error:null}}catch(t){return T(t,"remove failed")}}async invoke(e,t={}){try{let r=t.method??"POST",s={...t.headers},i;return t.body!==void 0&&t.body!==null&&(Te(t.body)?(i=JSON.stringify(t.body),s["Content-Type"]||(s["Content-Type"]="application/json")):i=t.body),{data:await this.http.rawFetch(`/api/invoke/${encodeURIComponent(e)}`,{method:r,headers:s,body:i}),error:null}}catch(r){return T(r,"invoke failed")}}async listSecrets(){try{return {data:(await this.http.get("/api/functions/secrets")).secrets.map(ke),error:null}}catch(e){return T(e,"listSecrets failed")}}async setSecrets(e){try{return await this.http.put("/api/functions/secrets",{secrets:e}),{data:{saved:!0},error:null}}catch(t){return T(t,"setSecrets failed")}}async deleteSecret(e){try{return await this.http.delete(`/api/functions/secrets/${encodeURIComponent(e)}`),{data:{deleted:!0},error:null}}catch(t){return T(t,"deleteSecret failed")}}};var v=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function te(n){let e=typeof n=="number"&&Number.isFinite(n)?n:50;return Math.max(1,Math.min(200,Math.trunc(e)))}function be(n){let e=typeof n=="number"&&Number.isFinite(n)?n:100;return Math.max(1,Math.min(500,Math.trunc(e)))}function z(){return {data:null,error:new c("agentId must be a valid UUID",400,"INVALID_INPUT")}}function re(){return {data:null,error:new c("sessionId must be a valid UUID",400,"INVALID_INPUT")}}function E(n,e){return n instanceof c?{data:null,error:n}:{data:null,error:new c(n instanceof Error?n.message:e,0,"AGENTS_ERROR")}}var F=class{constructor(e){this.http=e;}http;async list(e){try{let t=te(e?.limit);return {data:await this.http.get(`/api/agents?limit=${t}`),error:null}}catch(t){return E(t,"list failed")}}async invoke(e,t){if(typeof e!="string"||!v.test(e))return {data:null,error:new c("agentId must be a valid UUID",400,"INVALID_INPUT")};try{let r=t!==void 0?{input:t}:void 0;return {data:await this.http.post(`/api/agents/${encodeURIComponent(e)}/invoke`,r),error:null}}catch(r){return E(r,"invoke failed")}}async chat(e,t,r){if(typeof e!="string"||!v.test(e))return z();try{let s={message:t};r?.sessionId!==void 0&&(s.session_id=r.sessionId),r?.extraContext!==void 0&&(s.extra_context=r.extraContext);let i=await this.http.post(`/api/agents/${encodeURIComponent(e)}/chat`,s);return {data:{sessionId:i.session_id,runId:i.runId,status:i.status,output:i.output,text:i.text,totalTokens:i.totalTokens,totalCost:i.totalCost,error:i.error},error:null}}catch(s){return E(s,"chat failed")}}async listSessions(e,t){if(typeof e!="string"||!v.test(e))return z();try{let r=te(t?.limit);return {data:{sessions:((await this.http.get(`/api/agents/${encodeURIComponent(e)}/sessions?limit=${r}`)).sessions??[]).map(o=>({id:o.id,createdAt:o.created_at,lastActivityAt:o.last_activity_at,messageCount:o.message_count,lastMessagePreview:o.last_message_preview??null}))},error:null}}catch(r){return E(r,"listSessions failed")}}async getMessages(e,t,r){if(typeof e!="string"||!v.test(e))return z();if(typeof t!="string"||!v.test(t))return re();try{let s=be(r?.limit),i=new URLSearchParams;return i.set("limit",String(s)),r?.before!==void 0&&i.set("before",r.before),{data:{messages:((await this.http.get(`/api/agents/${encodeURIComponent(e)}/sessions/${encodeURIComponent(t)}/messages?${i.toString()}`)).messages??[]).map(d=>({id:d.id,role:d.role,content:d.content,createdAt:d.created_at}))},error:null}}catch(s){return E(s,"getMessages failed")}}async deleteSession(e,t){if(typeof e!="string"||!v.test(e))return z();if(typeof t!="string"||!v.test(t))return re();try{return await this.http.delete(`/api/agents/${encodeURIComponent(e)}/sessions/${encodeURIComponent(t)}`),{data:{ok:!0},error:null}}catch(r){return E(r,"deleteSession failed")}}};var _=class{http;tokenManager;auth;database;realtime;storage;functions;agents;constructor(e={}){let t=new R(e.debug);this.tokenManager=new w({persistSession:e.persistSession,storageKey:e.storageKey,storage:e.storage,multiTab:e.multiTab}),this.http=new O(e,this.tokenManager,t),this.auth=new I(this.http,this.tokenManager),this.database=new U(this.http,this.tokenManager,e.anonKey),this.realtime=new B(this.http.baseUrl,this.tokenManager,e.anonKey,e.realtime),this.storage=new x(this.http),this.functions=new M(this.http),this.agents=new F(this.http);}getHttpClient(){return this.http}};function at(n){return new _(n)}var ct=_;
|
|
5
|
+
export{F as AgentsModule,I as Auth,U as Database,M as Functions,O as HttpClient,R as Logger,_ as MitwayBaasClient,c as MitwayBaasError,B as Realtime,j as RealtimeChannel,x as Storage,K as StorageBucketClient,w as TokenManager,at as createClient,Z as createLocalStorageAdapter,ct as default};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@mitway/sdk",
|
|
3
|
-
"version": "0.10.
|
|
3
|
+
"version": "0.10.2",
|
|
4
4
|
"description": "TypeScript/JavaScript client for MITWAY-BaaS — auth + database for end-user apps",
|
|
5
5
|
"main": "./dist/index.cjs",
|
|
6
6
|
"module": "./dist/index.js",
|
|
@@ -26,6 +26,7 @@
|
|
|
26
26
|
"typecheck": "tsc --noEmit",
|
|
27
27
|
"prepublishOnly": "pnpm build"
|
|
28
28
|
},
|
|
29
|
+
"packageManager": "pnpm@11.4.0+sha512.f0febc7e37552ab485494a914241b338e0b3580b93d54ce31f00933015880863129038a1b4ae4e414a0ee63ac35bf21197e990172c4a68256450b5636310968f",
|
|
29
30
|
"keywords": [
|
|
30
31
|
"mitway",
|
|
31
32
|
"mitway-baas",
|