@tencent-ai/workbuddy-cloud-sdk 0.1.0-dev.dee063d.202608201621
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/LICENSE +58 -0
- package/lib/index.cjs +9271 -0
- package/lib/index.cjs.map +1 -0
- package/lib/index.d.cts +6499 -0
- package/lib/index.d.ts +6499 -0
- package/lib/index.global.js +7 -0
- package/lib/index.global.js.map +1 -0
- package/lib/index.js +9228 -0
- package/lib/index.js.map +1 -0
- package/package.json +102 -0
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
var WorkBuddyCloud=(()=>{var we=Object.defineProperty;var kt=Object.getOwnPropertyDescriptor;var $t=Object.getOwnPropertyNames;var Pt=Object.prototype.hasOwnProperty;var i=(r,e)=>we(r,"name",{value:e,configurable:!0});var _t=(r,e)=>{for(var t in e)we(r,t,{get:e[t],enumerable:!0})},At=(r,e,t,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of $t(e))!Pt.call(r,n)&&n!==t&&we(r,n,{get:()=>e[n],enumerable:!(s=kt(e,n))||s.enumerable});return r};var Rt=r=>At(we({},"__esModule",{value:!0}),r);var ir={};_t(ir,{AuthModule:()=>G,CLOUD_MODULE_PATHS:()=>A,CLOUD_PATH_PREFIX:()=>z,CloudOpenAIError:()=>g,CloudStoragePathError:()=>w,DEFAULT_SIGNED_URL_TTL_SECONDS:()=>Re,LlmModule:()=>W,MAX_SIGNED_URL_TTL_SECONDS:()=>Ue,PUBLISHABLE_KEY_HEADER:()=>Ie,RUNTIME_STORAGE_BUCKET:()=>Y,WorkBuddyCloudClient:()=>ge,WorkBuddyCloudConfigError:()=>k,WorkBuddyDatabaseModule:()=>se,WorkBuddyStorageBucket:()=>Q,WorkBuddyStorageDownload:()=>me,WorkBuddyStorageModule:()=>ye,anonymousTokenProvider:()=>be,createMemoryStorage:()=>Ce,createWorkBuddyCloud:()=>vt,shouldClearCredentials:()=>Ot});var k=class extends Error{static{i(this,"WorkBuddyCloudConfigError")}constructor(e){super(e),this.name="WorkBuddyCloudConfigError"}};var Ut=/^wbpk_/;function Ve(r,e){if(typeof r!="string"||r.trim()==="")throw new k(`${e} is required and must be a non-empty string.`);let t=r.trim(),s;try{s=new URL(t)}catch{throw new k(`${e} must be an absolute URL, received: ${t}`)}if(s.protocol!=="https:"&&s.protocol!=="http:")throw new k(`${e} must use http(s), received protocol: ${s.protocol}`);return t.replace(/\/+$/,"")}i(Ve,"normalizeHttpUrl");function It(r){if(typeof r!="string"||r.trim()==="")throw new k("publishableKey is required and must be a non-empty string.");let e=r.trim();if(!Ut.test(e))throw new k('publishableKey must start with "wbpk_".');return e}i(It,"normalizePublishableKey");function Lt(r){if(r)return r;if(typeof globalThis.fetch!="function")throw new k("Global fetch is unavailable in this runtime; pass options.fetch explicitly.");return globalThis.fetch.bind(globalThis)}i(Lt,"resolveFetch");function ze(r){if(!r||typeof r!="object")throw new k("createWorkBuddyCloud requires endpoint, oauthRelayBaseUrl and publishableKey.");return Object.freeze({endpoint:Ve(r.endpoint,"endpoint"),oauthRelayBaseUrl:Ve(r.oauthRelayBaseUrl,"oauthRelayBaseUrl"),publishableKey:It(r.publishableKey),fetch:Lt(r.fetch)})}i(ze,"resolveRuntimeConfig");var Ie="x-wb-webapp-access-key";function Le(r,e){return async(t,s)=>{let n=new Headers(s?.headers);if(n.set(Ie,r.publishableKey),!n.has("Authorization")){let a=await e();a&&n.set("Authorization",`Bearer ${a}`)}return r.fetch(t,{...s,headers:n})}}i(Le,"createCloudFetch");var be=i(()=>Promise.resolve(void 0),"anonymousTokenProvider");var z="/.cloud",A=Object.freeze({auth:`${z}/auth`,database:`${z}/database/rest`,storage:`${z}/storage`,llm:`${z}/llm`});var S={signUp:"/v1/signup",signIn:"/v1/signin",signInWithProvider:"/v1/signin/with/provider",token:"/v1/token",signOut:"/v1/user/signout",userMe:"/v1/user/me",verification:"/v1/verification",verificationVerify:"/v1/verification/verify",resetPassword:"/v1/reset",sudo:"/v1/user/sudo",userPassword:"/v1/user/password"};function Ne(r,e){let t=r??{},s=typeof t.access_token=="string"?t.access_token:"";if(!s)throw jt("response has no access_token");let n=typeof t.refresh_token=="string"?t.refresh_token:"",a=typeof t.expires_in=="number"?t.expires_in:0;return{accessToken:s,refreshToken:n,expiresAt:e+a*1e3,user:Nt(t)}}i(Ne,"parseSession");function Nt(r){let e=r.is_anonymous===!0;return{id:typeof r.sub=="string"?r.sub:"",isAnonymous:e,raw:r}}i(Nt,"userFromSessionPayload");function Ge(r){let e=r??{},t=typeof e.sub=="string"?e.sub:typeof e.uid=="string"?e.uid:"",s=e.user_metadata??{};return{id:t,email:q(e.email)??q(s.email),phone:q(e.phone_number)??q(e.phone),isAnonymous:e.is_anonymous===!0||e.scope==="anonymous",raw:e}}i(Ge,"parseUser");function q(r){return typeof r=="string"&&r!==""?r:void 0}i(q,"pickString");function Ke(r,e){let t=e??{},s=typeof t.error=="string"?t.error:void 0,n=q(t.error_description)??q(t.message)??q(t.msg)??`HTTP ${r}`;return{kind:Ct(r,s),message:n,status:r,code:s,cause:e}}i(Ke,"normalizeHttpError");function Ct(r,e){if(e==="invalid_grant")return"unauthenticated";switch(r){case 400:return"invalid-request";case 401:return"unauthenticated";case 403:return"permission-denied";case 404:return"not-found";case 429:return"rate-limited";case 501:return"unimplemented";case 503:return"backend-unavailable";default:return r>=500?"backend-unavailable":"unknown"}}i(Ct,"errorKind");function Z(r){return{kind:"network",message:`request failed before a response was received: ${r instanceof Error?r.message:String(r)}`,status:0,cause:r}}i(Z,"normalizeNetworkError");function jt(r){let e=new Error(`workbuddy-cloud auth: ${r}`);return e.kind="unknown",e.status=0,e}i(jt,"sessionShapeError");var xe=class{static{i(this,"SessionManager")}store;refresh;emit;isCredentialsRejected;now;inflight=null;signOutEpoch=0;lastFailure=null;constructor(e){this.store=e.store,this.refresh=e.refresh,this.emit=e.emit,this.isCredentialsRejected=e.isCredentialsRejected,this.now=e.now??Date.now}peek(){return this.store.read()}async ensure(){let e=this.store.read();return e?this.isExpiring(e)?e.refreshToken?this.refreshOnce(e):this.abandon():e:null}async forceRefresh(){let e=this.store.read();return e?.refreshToken?this.refreshOnce(e,{ignoreCooldown:!0}):null}commitSignIn(e){return this.lastFailure=null,this.store.write(e),this.emit("SIGNED_IN",e),e}commitUserUpdate(e){return this.store.write(e),this.emit("USER_UPDATED",e),e}clear(){this.signOutEpoch+=1,this.lastFailure=null,this.inflight=null,this.store.clear(),this.emit("SIGNED_OUT",null)}isExpiring(e){return typeof e.expiresAt!="number"?!0:e.expiresAt-this.now()<9e4}refreshOnce(e,t={}){if(this.inflight)return this.inflight;if(!t.ignoreCooldown&&this.inCooldown(e.refreshToken))return Promise.resolve(null);let s=this.doRefresh(e).finally(()=>{this.inflight=null});return this.inflight=s,s}inCooldown(e){let t=this.lastFailure;return t!==null&&t.token===e&&this.now()-t.at<6e4}async doRefresh(e){let t=this.signOutEpoch,s=e.refreshToken,n;try{n=await this.refresh(s)}catch(o){return this.onRefreshFailed(s,o)}if(this.signOutEpoch!==t)return this.store.clear(),null;let a=this.store.read();return a&&a.refreshToken!==s?a:(this.lastFailure=null,this.store.write(n),this.emit("TOKEN_REFRESHED",n),n)}onRefreshFailed(e,t){return this.isCredentialsRejected(t)?this.abandon():(this.lastFailure={token:e,at:this.now()},null)}abandon(){return this.store.clear(),this.lastFailure=null,this.emit("SIGNED_OUT",null),null}};var Dt="workbuddy-cloud.session.";function Ce(){let r=new Map;return{getItem:i(e=>r.get(e)??null,"getItem"),setItem:i((e,t)=>{r.set(e,t)},"setItem"),removeItem:i(e=>{r.delete(e)},"removeItem")}}i(Ce,"createMemoryStorage");function We(r){if(r)return r;try{let e="__workbuddy_probe__";return globalThis.localStorage.setItem(e,"1"),globalThis.localStorage.removeItem(e),globalThis.localStorage}catch{return Ce()}}i(We,"resolveStorage");var Se=class{static{i(this,"SessionStore")}storage;key;constructor(e,t){this.storage=e,this.key=Dt+t}read(){let e;try{e=this.storage.getItem(this.key)}catch{return null}if(!e)return null;try{let t=JSON.parse(e);return Bt(t)?t:this.discard()}catch{return this.discard()}}write(e){try{this.storage.setItem(this.key,JSON.stringify(e))}catch{}}clear(){try{this.storage.removeItem(this.key)}catch{}}discard(){return this.clear(),null}};function Bt(r){if(!r||typeof r!="object")return!1;let e=r;return typeof e.accessToken=="string"&&e.accessToken!==""&&typeof e.refreshToken=="string"&&typeof e.expiresAt=="number"&&!!e.user&&typeof e.user=="object"}i(Bt,"isStoredSession");var G=class{static{i(this,"AuthModule")}fetch;baseUrl;sessions;storage;oauthRelayBaseUrl;listeners=new Map;nextListenerId=1;constructor(e,t,s={}){this.fetch=t,this.baseUrl=`${e.endpoint}${A.auth}`,this.oauthRelayBaseUrl=e.oauthRelayBaseUrl,this.storage=We(s.storage),this.sessions=new xe({store:new Se(this.storage,e.publishableKey),refresh:i(n=>this.exchangeRefreshHandle(n),"refresh"),emit:i((n,a)=>this.notify(n,a),"emit"),isCredentialsRejected:i(n=>Ee(n)&&Je(n),"isCredentialsRejected")})}async getAccessToken(){return(await this.sessions.ensure())?.accessToken}async signInWithPassword(e){return!e.email||!e.password?f(b("signInWithPassword requires email and password")):this.postForSession(S.signIn,{username:e.email,password:e.password})}async signUp(e){if(!e.email)return f(b("signUp requires email"));if(!e.verificationToken)return f(b("signUp requires a verificationToken; run sendOtp + verifyOtp first (the provider rejects username+password-only signup)"));let t={verification_token:e.verificationToken};return t.email=e.email,e.password&&(t.password=e.password),this.postForSession(S.signUp,t)}async sendOtp(e){if(!e.email)return f(b("sendOtp requires email"));let t={email:e.email,usage:"EMAIL"};e.emailRedirectTo&&(t.email_redirect_to=e.emailRedirectTo);let s=await this.request(S.verification,{method:"POST",body:t});if(s.error)return f(s.error);let n=s.data??{},a=typeof n.verification_id=="string"?n.verification_id:"";return a?$({verificationId:a,isExistingUser:n.is_user===!0}):f(b("provider returned no verification_id"))}async signInWithOtp(e){let t=await this.sendOtp(e);if(t.error)return f(t.error);let{verificationId:s,isExistingUser:n}=t.data;return $({verificationId:s,isExistingUser:n,isUser:n,verify:i(({token:a})=>this.verifyOtp({verificationId:s,token:a,email:e.email,isExistingUser:n}),"verify")})}async verifyOtp(e){if(!e.verificationId||!e.token||!e.email)return f(b("verifyOtp requires verificationId, token and email"));let t=await this.request(S.verificationVerify,{method:"POST",body:{verification_id:e.verificationId,verification_code:e.token}});if(t.error)return f(t.error);let s=t.data??{},n=typeof s.verification_token=="string"?s.verification_token:"";return n?e.isExistingUser?this.postForSession(S.signIn,{username:e.email,verification_token:n}):this.signUp({email:e.email,password:e.password??"",verificationToken:n}):f(b("provider returned no verification_token"))}async signInWithOAuth(e){if(e.provider!=="google")return f(b("signInWithOAuth currently supports only google"));let t=e.redirectTo??Ft();return t?this.startRelayOAuth(e,t):f(b("signInWithOAuth requires redirectTo outside a browser environment"))}async handleOAuthCallback(e){let t=e??Ht(),s=t;try{/^https?:\/\//i.test(t)&&(s=new URL(t).search)}catch{return f(b("oauth callback URL is invalid"))}let n=new URLSearchParams(s),a=n.get("error")??n.get("error_description");if(a)return f({kind:"unauthenticated",message:`oauth provider rejected the request: ${a}`,status:0});let o=n.get("code");if(!o)return $(null);let c=n.get("state")??"",u=n.get("provider_id");if(u!=="custom-oauth")return f(b("oauth callback requires provider_id=custom-oauth"));if(!c)return f(b("oauth callback requires state"));let h={provider_id:u,provider_code:o,state:c,provider_params:{state:c}};return this.postForSession(S.signInWithProvider,h)}async resetPasswordForEmail(e){if(!e)return f(b("resetPasswordForEmail requires email"));let t=await this.request(S.verification,{method:"POST",body:{email:e,usage:"PASSWORD_RESET",target:"USER"}});if(t.error)return f(t.error);let s=t.data??{},n=typeof s.verification_id=="string"?s.verification_id:"";return n?$({updateUser:i(async({nonce:a,password:o})=>{let c=await this.request(S.verificationVerify,{method:"POST",body:{verification_id:n,verification_code:a}});if(c.error)return f(c.error);let u=c.data??{},h=typeof u.verification_token=="string"?u.verification_token:"";if(!h)return f(b("provider returned no verification_token"));let l=await this.request(S.resetPassword,{method:"POST",body:{email:e,new_password:o,verification_token:h}});if(l.error)return f(l.error);let d=await this.signInWithPassword({email:e,password:o});return d.error||this.notify("PASSWORD_RECOVERY",d.data),d},"updateUser")}):f(b("provider returned no verification_id"))}async resetPasswordForOld(e){let t=await this.getAccessToken();if(!t)return f({kind:"unauthenticated",message:"no active session",status:0});let s=await this.request(S.sudo,{method:"POST",token:t,body:{password:e.oldPassword}});if(s.error)return f(s.error);let n=s.data??{},a=typeof n.sudo_token=="string"?n.sudo_token:"";if(!a)return f(b("provider returned no sudo_token"));let o=await this.request(S.userPassword,{method:"PATCH",token:t,body:{sudo_token:a,new_password:e.newPassword}});if(o.error)return f(o.error);let c=await this.getSession();return c.data?(this.notify("USER_UPDATED",c.data),$(c.data)):f(c.error??{kind:"unauthenticated",message:"no active session",status:0})}async getSession(){try{return $(await this.sessions.ensure())}catch(e){return f(Ee(e)?e:Z(e))}}async refreshSession(){try{return $(await this.sessions.forceRefresh())}catch(e){return f(Ee(e)?e:Z(e))}}async getUser(){let e=await this.getAccessToken();if(!e)return f({kind:"unauthenticated",message:"no active session",status:0});let t=await this.request(S.userMe,{method:"GET",token:e});return t.error?(Je(t.error)&&this.sessions.clear(),f(t.error)):$(Ge(t.data))}async signOut(){let e=this.sessions.peek();return e?.accessToken&&await this.request(S.signOut,{method:"POST",body:{},token:e.accessToken}),this.sessions.clear(),$(null)}onAuthStateChange(e){let t=this.nextListenerId++;return this.listeners.set(t,e),Xe(e,"INITIAL_SESSION",this.sessions.peek()),()=>{this.listeners.delete(t)}}async startRelayOAuth(e,t){let s=new URL(t),n=new URL(`${this.oauthRelayBaseUrl}/authorize`);return n.searchParams.set("provider",e.provider),n.searchParams.set("callback_url",s.toString()),$({url:n.toString()})}async exchangeRefreshHandle(e){let t=await this.request(S.token,{method:"POST",body:{grant_type:"refresh_token",refresh_token:e}});if(t.error)throw t.error;return Ne(t.data,Date.now())}async postForSession(e,t,s={}){let n=await this.request(e,{method:"POST",body:t,headers:s.headers});if(n.error)return f(n.error);try{return $(this.sessions.commitSignIn(Ne(n.data,Date.now())))}catch(a){return f(Ee(a)?a:Z(a))}}async request(e,t){let s={...t.headers};t.body!==void 0&&(s["Content-Type"]="application/json"),t.token&&(s.Authorization=`Bearer ${t.token}`);let n;try{n=await this.fetch(this.baseUrl+e,{method:t.method,headers:s,body:t.body===void 0?void 0:JSON.stringify(t.body)})}catch(o){return f(Z(o))}let a=await qt(n);return n.ok?$(a):f(Ke(n.status,a))}notify(e,t){for(let s of this.listeners.values())Xe(s,e,t)}};function $(r){return{data:r,error:null}}i($,"ok");function f(r){return{data:null,error:r}}i(f,"fail");function b(r){return{kind:"invalid-request",message:r,status:0}}i(b,"badRequest");function Ee(r){return!!r&&typeof r=="object"&&typeof r.kind=="string"}i(Ee,"isCloudError");function Je(r){return r.kind==="unauthenticated"||r.code==="invalid_grant"}i(Je,"rejectedCredentials");async function qt(r){let e=await r.text();if(!e)return null;try{return JSON.parse(e)}catch{return{message:e}}}i(qt,"readBody");function Xe(r,e,t){try{r(e,t)}catch{}}i(Xe,"safeInvoke");function Ft(){let r=globalThis.location;return r?r.origin+r.pathname:""}i(Ft,"currentPageUrl");function Ht(){return globalThis.location?.search??""}i(Ht,"currentPageSearch");var je=i(r=>Math.min(1e3*2**r,3e4),"getRetryDelay"),Ye=[520,503],De=["GET","HEAD","OPTIONS"];var F=class extends Error{static{i(this,"PostgrestError")}details;hint;code;constructor(e){super(e.message),this.name="PostgrestError",this.details=e.details,this.hint=e.hint,this.code=e.code}toJSON(){return{name:this.name,message:this.message,details:this.details,hint:this.hint,code:this.code}}};function Qe(r,e){return new Promise(t=>{if(e?.aborted){t();return}let s=setTimeout(()=>{e?.removeEventListener("abort",n),t()},r);function n(){clearTimeout(s),t()}i(n,"onAbort"),e?.addEventListener("abort",n)})}i(Qe,"sleep");function Mt(r,e,t,s){return!(!s||t>=3||!De.includes(r)||!Ye.includes(e))}i(Mt,"shouldRetry");var ee=class{static{i(this,"PostgrestBuilder")}method;url;headers;schema;body;shouldThrowOnError=!1;signal;fetch;isMaybeSingle;shouldStripNulls;urlLengthLimit;retryEnabled=!0;constructor(e){this.method=e.method,this.url=e.url,this.headers=new Headers(e.headers),this.schema=e.schema,this.body=e.body,this.shouldThrowOnError=e.shouldThrowOnError??!1,this.signal=e.signal,this.isMaybeSingle=e.isMaybeSingle??!1,this.shouldStripNulls=e.shouldStripNulls??!1,this.urlLengthLimit=e.urlLengthLimit??8e3,this.retryEnabled=e.retry??!0,e.fetch?this.fetch=e.fetch:this.fetch=fetch}throwOnError(){return this.shouldThrowOnError=!0,this}stripNulls(){if(this.headers.get("Accept")==="text/csv")throw new Error("stripNulls() cannot be used with csv()");return this.shouldStripNulls=!0,this}setHeader(e,t){return this.headers=new Headers(this.headers),this.headers.set(e,t),this}retry(e){return this.retryEnabled=e,this}then(e,t){if(this.schema===void 0||(["GET","HEAD"].includes(this.method)?this.headers.set("Accept-Profile",this.schema):this.headers.set("Content-Profile",this.schema)),this.method!=="GET"&&this.method!=="HEAD"&&this.headers.set("Content-Type","application/json"),this.shouldStripNulls){let o=this.headers.get("Accept");o==="application/vnd.pgrst.object+json"?this.headers.set("Accept","application/vnd.pgrst.object+json;nulls=stripped"):(!o||o==="application/json")&&this.headers.set("Accept","application/vnd.pgrst.array+json;nulls=stripped")}let s=this.fetch,a=i(async()=>{let o=0;for(;;){let c={};this.headers.forEach((h,l)=>{c[l]=h}),o>0&&(c["X-Retry-Count"]=String(o));let u;try{u=await s(this.url.toString(),{method:this.method,headers:c,body:JSON.stringify(this.body,(h,l)=>typeof l=="bigint"?l.toString():l),signal:this.signal})}catch(h){if(h?.name==="AbortError"||h?.code==="ABORT_ERR"||!De.includes(this.method))throw h;if(this.retryEnabled&&o<3){let l=je(o);o++,await Qe(l,this.signal);continue}throw h}if(Mt(this.method,u.status,o,this.retryEnabled)){let h=u.headers?.get("Retry-After")??null,l=h!==null?Math.max(0,parseInt(h,10)||0)*1e3:je(o);await u.text(),o++,await Qe(l,this.signal);continue}return await this.processResponse(u)}},"executeWithRetry")();return this.shouldThrowOnError||(a=a.catch(o=>{let c="",u="",h="",l=o?.cause;if(l){let m=l?.message??"",p=l?.code??"";c=`${o?.name??"FetchError"}: ${o?.message}`,c+=`
|
|
2
|
+
|
|
3
|
+
Caused by: ${l?.name??"Error"}: ${m}`,p&&(c+=` (${p})`),l?.stack&&(c+=`
|
|
4
|
+
${l.stack}`)}else c=o?.stack??"";let d=this.url.toString().length;return o?.name==="AbortError"||o?.code==="ABORT_ERR"?(h="",u="Request was aborted (timeout or manual cancellation)",d>this.urlLengthLimit&&(u+=`. Note: Your request URL is ${d} characters, which may exceed server limits. If selecting many fields, consider using views. If filtering with large arrays (e.g., .in('id', [many IDs])), consider using an RPC function to pass values server-side.`)):(l?.name==="HeadersOverflowError"||l?.code==="UND_ERR_HEADERS_OVERFLOW")&&(h="",u="HTTP headers exceeded server limits (typically 16KB)",d>this.urlLengthLimit&&(u+=`. Your request URL is ${d} characters. If selecting many fields, consider using views. If filtering with large arrays (e.g., .in('id', [200+ IDs])), consider using an RPC function instead.`)),{success:!1,error:{message:`${o?.name??"FetchError"}: ${o?.message}`,details:c,hint:u,code:h},data:null,count:null,status:0,statusText:""}})),a.then(e,t)}async processResponse(e){let t=null,s=null,n=null,a=e.status,o=e.statusText;if(e.ok){if(this.method!=="HEAD"){let h=await e.text();if(h!=="")if(this.headers.get("Accept")==="text/csv")s=h;else if(this.headers.get("Accept")&&this.headers.get("Accept")?.includes("application/vnd.pgrst.plan+text"))s=h;else try{s=JSON.parse(h)}catch{if(t={message:h},s=null,this.shouldThrowOnError)throw new F({message:h,details:"",hint:"",code:""})}}let c=this.headers.get("Prefer")?.match(/count=(exact|planned|estimated)/),u=e.headers.get("content-range")?.split("/");if(c&&u&&u.length>1&&(n=parseInt(u[1])),this.isMaybeSingle&&Array.isArray(s))if(s.length>1){if(t={code:"PGRST116",details:`Results contain ${s.length} rows, application/vnd.pgrst.object+json requires 1 row`,hint:null,message:"JSON object requested, multiple (or no) rows returned"},s=null,n=null,a=406,o="Not Acceptable",this.shouldThrowOnError)throw new F({...t,hint:t.hint??""})}else s.length===1?s=s[0]:s=null}else{let c=await e.text();try{t=JSON.parse(c),Array.isArray(t)&&e.status===404&&(s=[],t=null,a=200,o="OK")}catch{e.status===404&&c===""?(a=204,o="No Content"):t={message:c}}if(t&&this.shouldThrowOnError)throw new F(t)}return{success:t===null,error:t,data:s,count:n,status:a,statusText:o}}returns(){return this}overrideTypes(){return this}};var te=class extends ee{static{i(this,"PostgrestTransformBuilder")}throwOnError(){return super.throwOnError()}select(e){let t=!1,s=(e??"*").split("").map(n=>/\s/.test(n)&&!t?"":(n==='"'&&(t=!t),n)).join("");return this.url.searchParams.set("select",s),this.headers.append("Prefer","return=representation"),this}order(e,{ascending:t=!0,nullsFirst:s,foreignTable:n,referencedTable:a=n}={}){let o=a?`${a}.order`:"order",c=this.url.searchParams.get(o);return this.url.searchParams.set(o,`${c?`${c},`:""}${e}.${t?"asc":"desc"}${s===void 0?"":s?".nullsfirst":".nullslast"}`),this}limit(e,{foreignTable:t,referencedTable:s=t}={}){let n=typeof s>"u"?"limit":`${s}.limit`;return this.url.searchParams.set(n,`${e}`),this}range(e,t,{foreignTable:s,referencedTable:n=s}={}){let a=typeof n>"u"?"offset":`${n}.offset`,o=typeof n>"u"?"limit":`${n}.limit`;return this.url.searchParams.set(a,`${e}`),this.url.searchParams.set(o,`${t-e+1}`),this}abortSignal(e){return this.signal=e,this}single(){return this.headers.set("Accept","application/vnd.pgrst.object+json"),this}maybeSingle(){return this.isMaybeSingle=!0,this}csv(){return this.headers.set("Accept","text/csv"),this}geojson(){return this.headers.set("Accept","application/geo+json"),this}explain({analyze:e=!1,verbose:t=!1,settings:s=!1,buffers:n=!1,wal:a=!1,format:o="text"}={}){let c=[e?"analyze":null,t?"verbose":null,s?"settings":null,n?"buffers":null,a?"wal":null].filter(Boolean).join("|"),u=this.headers.get("Accept")??"application/json";return this.headers.set("Accept",`application/vnd.pgrst.plan+${o}; for="${u}"; options=${c};`),o==="json"?this:this}rollback(){return this.headers.append("Prefer","tx=rollback"),this}returns(){return this}maxAffected(e){return this.headers.append("Prefer","handling=strict"),this.headers.append("Prefer",`max-affected=${e}`),this}};var et=new RegExp("[,()]"),P=class extends te{static{i(this,"PostgrestFilterBuilder")}throwOnError(){return super.throwOnError()}eq(e,t){return this.url.searchParams.append(e,`eq.${t}`),this}neq(e,t){return this.url.searchParams.append(e,`neq.${t}`),this}gt(e,t){return this.url.searchParams.append(e,`gt.${t}`),this}gte(e,t){return this.url.searchParams.append(e,`gte.${t}`),this}lt(e,t){return this.url.searchParams.append(e,`lt.${t}`),this}lte(e,t){return this.url.searchParams.append(e,`lte.${t}`),this}like(e,t){return this.url.searchParams.append(e,`like.${t}`),this}likeAllOf(e,t){return this.url.searchParams.append(e,`like(all).{${t.join(",")}}`),this}likeAnyOf(e,t){return this.url.searchParams.append(e,`like(any).{${t.join(",")}}`),this}ilike(e,t){return this.url.searchParams.append(e,`ilike.${t}`),this}ilikeAllOf(e,t){return this.url.searchParams.append(e,`ilike(all).{${t.join(",")}}`),this}ilikeAnyOf(e,t){return this.url.searchParams.append(e,`ilike(any).{${t.join(",")}}`),this}regexMatch(e,t){return this.url.searchParams.append(e,`match.${t}`),this}regexIMatch(e,t){return this.url.searchParams.append(e,`imatch.${t}`),this}is(e,t){return this.url.searchParams.append(e,`is.${t}`),this}isDistinct(e,t){return this.url.searchParams.append(e,`isdistinct.${t}`),this}in(e,t){let s=Array.from(new Set(t)).map(n=>typeof n=="string"&&et.test(n)?`"${n}"`:`${n}`).join(",");return this.url.searchParams.append(e,`in.(${s})`),this}notIn(e,t){let s=Array.from(new Set(t)).map(n=>typeof n=="string"&&et.test(n)?`"${n}"`:`${n}`).join(",");return this.url.searchParams.append(e,`not.in.(${s})`),this}contains(e,t){return typeof t=="string"?this.url.searchParams.append(e,`cs.${t}`):Array.isArray(t)?this.url.searchParams.append(e,`cs.{${t.join(",")}}`):this.url.searchParams.append(e,`cs.${JSON.stringify(t)}`),this}containedBy(e,t){return typeof t=="string"?this.url.searchParams.append(e,`cd.${t}`):Array.isArray(t)?this.url.searchParams.append(e,`cd.{${t.join(",")}}`):this.url.searchParams.append(e,`cd.${JSON.stringify(t)}`),this}rangeGt(e,t){return this.url.searchParams.append(e,`sr.${t}`),this}rangeGte(e,t){return this.url.searchParams.append(e,`nxl.${t}`),this}rangeLt(e,t){return this.url.searchParams.append(e,`sl.${t}`),this}rangeLte(e,t){return this.url.searchParams.append(e,`nxr.${t}`),this}rangeAdjacent(e,t){return this.url.searchParams.append(e,`adj.${t}`),this}overlaps(e,t){return typeof t=="string"?this.url.searchParams.append(e,`ov.${t}`):this.url.searchParams.append(e,`ov.{${t.join(",")}}`),this}textSearch(e,t,{config:s,type:n}={}){let a="";n==="plain"?a="pl":n==="phrase"?a="ph":n==="websearch"&&(a="w");let o=s===void 0?"":`(${s})`;return this.url.searchParams.append(e,`${a}fts${o}.${t}`),this}match(e){return Object.entries(e).filter(([t,s])=>s!==void 0).forEach(([t,s])=>{this.url.searchParams.append(t,`eq.${s}`)}),this}not(e,t,s){return this.url.searchParams.append(e,`not.${t}.${s}`),this}or(e,{foreignTable:t,referencedTable:s=t}={}){let n=s?`${s}.or`:"or";return this.url.searchParams.append(n,`(${e})`),this}filter(e,t,s){return this.url.searchParams.append(e,`${t}.${s}`),this}};var re=class{static{i(this,"PostgrestQueryBuilder")}url;headers;schema;signal;fetch;urlLengthLimit;retry;constructor(e,{headers:t={},schema:s,fetch:n,urlLengthLimit:a=8e3,retry:o}){this.url=e,this.headers=new Headers(t),this.schema=s,this.fetch=n,this.urlLengthLimit=a,this.retry=o}cloneRequestState(){return{url:new URL(this.url.toString()),headers:new Headers(this.headers)}}select(e,t){let{head:s=!1,count:n}=t??{},a=s?"HEAD":"GET",o=!1,c=(e??"*").split("").map(l=>/\s/.test(l)&&!o?"":(l==='"'&&(o=!o),l)).join(""),{url:u,headers:h}=this.cloneRequestState();return u.searchParams.set("select",c),n&&h.append("Prefer",`count=${n}`),new P({method:a,url:u,headers:h,schema:this.schema,fetch:this.fetch,urlLengthLimit:this.urlLengthLimit,retry:this.retry})}insert(e,{count:t,defaultToNull:s=!0}={}){let n="POST",{url:a,headers:o}=this.cloneRequestState();if(t&&o.append("Prefer",`count=${t}`),s||o.append("Prefer","missing=default"),Array.isArray(e)){let c=e.reduce((u,h)=>u.concat(Object.keys(h)),[]);if(c.length>0){let u=[...new Set(c)].map(h=>`"${h}"`);a.searchParams.set("columns",u.join(","))}}return new P({method:n,url:a,headers:o,schema:this.schema,body:e,fetch:this.fetch??fetch,urlLengthLimit:this.urlLengthLimit,retry:this.retry})}upsert(e,{onConflict:t,ignoreDuplicates:s=!1,count:n,defaultToNull:a=!0}={}){let o="POST",{url:c,headers:u}=this.cloneRequestState();if(u.append("Prefer",`resolution=${s?"ignore":"merge"}-duplicates`),t!==void 0&&c.searchParams.set("on_conflict",t),n&&u.append("Prefer",`count=${n}`),a||u.append("Prefer","missing=default"),Array.isArray(e)){let h=e.reduce((l,d)=>l.concat(Object.keys(d)),[]);if(h.length>0){let l=[...new Set(h)].map(d=>`"${d}"`);c.searchParams.set("columns",l.join(","))}}return new P({method:o,url:c,headers:u,schema:this.schema,body:e,fetch:this.fetch??fetch,urlLengthLimit:this.urlLengthLimit,retry:this.retry})}update(e,{count:t}={}){let s="PATCH",{url:n,headers:a}=this.cloneRequestState();return t&&a.append("Prefer",`count=${t}`),new P({method:s,url:n,headers:a,schema:this.schema,body:e,fetch:this.fetch??fetch,urlLengthLimit:this.urlLengthLimit,retry:this.retry})}delete({count:e}={}){let t="DELETE",{url:s,headers:n}=this.cloneRequestState();return e&&n.append("Prefer",`count=${e}`),new P({method:t,url:s,headers:n,schema:this.schema,fetch:this.fetch??fetch,urlLengthLimit:this.urlLengthLimit,retry:this.retry})}};var K=class r{static{i(this,"PostgrestClient")}url;headers;schemaName;fetch;urlLengthLimit;retry;constructor(e,{headers:t={},schema:s,fetch:n,timeout:a,urlLengthLimit:o=8e3,retry:c}={}){this.url=e,this.headers=new Headers(t),this.schemaName=s,this.urlLengthLimit=o;let u=n??globalThis.fetch;a!==void 0&&a>0?this.fetch=(h,l)=>{let d=new AbortController,m=setTimeout(()=>d.abort(),a),p=l?.signal;if(p){if(p.aborted)return clearTimeout(m),u(h,l);let _=i(()=>{clearTimeout(m),d.abort()},"abortHandler");return p.addEventListener("abort",_,{once:!0}),u(h,{...l,signal:d.signal}).finally(()=>{clearTimeout(m),p.removeEventListener("abort",_)})}return u(h,{...l,signal:d.signal}).finally(()=>clearTimeout(m))}:this.fetch=u,this.retry=c}from(e){if(!e||typeof e!="string"||e.trim()==="")throw new Error("Invalid relation name: relation must be a non-empty string.");let t=new URL(`${this.url}/${e}`);return new re(t,{headers:new Headers(this.headers),schema:this.schemaName,fetch:this.fetch,urlLengthLimit:this.urlLengthLimit,retry:this.retry})}schema(e){return new r(this.url,{headers:this.headers,schema:e,fetch:this.fetch,urlLengthLimit:this.urlLengthLimit,retry:this.retry})}rpc(e,t={},{head:s=!1,get:n=!1,count:a}={}){let o,c=new URL(`${this.url}/rpc/${e}`),u,h=i(m=>m!==null&&typeof m=="object"&&(!Array.isArray(m)||m.some(h)),"_isObject"),l=s&&Object.values(t).some(h);l?(o="POST",u=t):s||n?(o=s?"HEAD":"GET",Object.entries(t).filter(([m,p])=>p!==void 0).map(([m,p])=>[m,Array.isArray(p)?`{${p.join(",")}}`:`${p}`]).forEach(([m,p])=>{c.searchParams.append(m,p)})):(o="POST",u=t);let d=new Headers(this.headers);return l?d.set("Prefer",a?`count=${a},return=minimal`:"return=minimal"):a&&d.set("Prefer",`count=${a}`),new P({method:o,url:c,headers:d,schema:this.schemaName,body:u,fetch:this.fetch??fetch,urlLengthLimit:this.urlLengthLimit,retry:this.retry})}};var se=class{static{i(this,"WorkBuddyDatabaseModule")}client;constructor(e,t){this.client=new K(`${e.endpoint}${A.database}`,{fetch:t}),this.from=this.client.from.bind(this.client),this.rpc=this.client.rpc.bind(this.client)}from;rpc;get url(){return this.client.url}};function tt(r,e){return new se(r,e)}i(tt,"createDatabaseModule");var g=class extends Error{static{i(this,"CloudOpenAIError")}error;status;requestId;retryAfterMs;constructor(e,t={}){let s=typeof e=="string"?{message:e,type:"server_error",param:null,code:null}:e;super(s.message),this.name="CloudOpenAIError",this.error=s,this.status=t.status,this.requestId=t.requestId,this.retryAfterMs=t.retryAfterMs,t.cause!==void 0&&("cause"in this||Object.defineProperty(this,"cause",{value:t.cause,writable:!1,enumerable:!1,configurable:!1}))}};function rt(r){if(!r)return;let e=r.trim(),t=Number(e);if(!isNaN(t)&&t>=0&&Number.isInteger(t))return t*1e3;let s=Date.parse(e);if(!isNaN(s)){let n=s-Date.now();return n>0?n:0}}i(rt,"parseRetryAfter");function y(...r){return r.find(e=>typeof e=="string"&&e.length>0)}i(y,"stringField");function R(...r){return r.find(e=>typeof e=="number"&&Number.isFinite(e))}i(R,"numberField");function Be(...r){return r.find(e=>typeof e=="boolean")}i(Be,"booleanField");function st(r){if(!r||typeof r!="object")return;let e=r,t=Array.isArray(e.input)?e.input.filter(n=>typeof n=="string"):void 0,s=Array.isArray(e.output)?e.output.filter(n=>typeof n=="string"):void 0;return t?.length||s?.length?{...t?.length?{input:t}:{},...s?.length?{output:s}:{}}:void 0}i(st,"modalitiesField");function nt(r){if(!r||typeof r!="object")return;let t=Object.entries(r).filter(([,s])=>typeof s=="boolean");return t.length?Object.fromEntries(t):void 0}i(nt,"capabilitiesField");function at(r){if(!r||typeof r!="object")return;let e=r,t={...y(e.currency)?{currency:e.currency}:{},...R(e.inputPerMillionTokens)!==void 0?{inputPerMillionTokens:e.inputPerMillionTokens}:{},...R(e.outputPerMillionTokens)!==void 0?{outputPerMillionTokens:e.outputPerMillionTokens}:{},...y(e.displayText)?{displayText:e.displayText}:{}};return Object.keys(t).length?t:void 0}i(at,"pricingField");function Vt(r){let e=y(r.id,r.ID);return e?{id:e,name:y(r.name,r.Name)??e,...y(r.provider,r.Provider)?{provider:y(r.provider,r.Provider)}:{},...y(r.vendor,r.Vendor)?{vendor:y(r.vendor,r.Vendor)}:{},...y(r.family,r.Family)?{family:y(r.family,r.Family)}:{},...y(r.version,r.Version)?{version:y(r.version,r.Version)}:{},...y(r.description,r.Description)?{description:y(r.description,r.Description)}:{},...y(r.descriptionZh,r.DescriptionZh)?{descriptionZh:y(r.descriptionZh,r.DescriptionZh)}:{},...y(r.descriptionEn,r.DescriptionEn)?{descriptionEn:y(r.descriptionEn,r.DescriptionEn)}:{},...y(r.iconUrl,r.IconURL)?{iconUrl:y(r.iconUrl,r.IconURL)}:{},...R(r.contextWindow,r.ContextWindow)!==void 0?{contextWindow:R(r.contextWindow,r.ContextWindow)}:{},...R(r.maxInputTokens,r.MaxInputTokens)!==void 0?{maxInputTokens:R(r.maxInputTokens,r.MaxInputTokens)}:{},...R(r.maxOutputTokens,r.MaxOutputTokens)!==void 0?{maxOutputTokens:R(r.maxOutputTokens,r.MaxOutputTokens)}:{},...st(r.modalities??r.Modalities)?{modalities:st(r.modalities??r.Modalities)}:{},...nt(r.capabilities??r.Capabilities)?{capabilities:nt(r.capabilities??r.Capabilities)}:{},enabled:Be(r.enabled,r.Enabled)??!0,...Be(r.isDefault,r.IsDefault)!==void 0?{isDefault:Be(r.isDefault,r.IsDefault)}:{},...R(r.sortOrder,r.SortOrder)!==void 0?{sortOrder:R(r.sortOrder,r.SortOrder)}:{},...at(r.pricing??r.Pricing)?{pricing:at(r.pricing??r.Pricing)}:{}}:null}i(Vt,"normalizeModel");var Te=class{static{i(this,"ModelsAPI")}baseUrl;fetch;constructor(e,t){this.baseUrl=e,this.fetch=t}async list(e){let t;try{t=await this.fetch(`${this.baseUrl}/models`,{method:"GET",headers:{Accept:"application/json"},signal:e})}catch(c){throw c instanceof Error&&c.name==="AbortError"?c:new g({message:`Network error: ${c?.message??"unknown"}`,type:"server_error",param:null,code:"gateway_network_error"},{cause:c})}if(!t.ok)throw await ve(t);let s=await t.text(),n;try{n=JSON.parse(s)}catch{throw new g({message:"Failed to parse models response: invalid JSON",type:"server_error",param:null,code:"gateway_invalid_response"})}let a=Array.isArray(n)?n:Array.isArray(n?.data)?n.data:[],o=[];for(let c of a){let u=Vt(c);u&&o.push(u)}return o}};async function ve(r){let e=await r.text().catch(()=>""),t;try{let a=JSON.parse(e);if(a&&typeof a=="object"&&a.error){let o=a.error;t={message:typeof o.message=="string"?o.message:`HTTP ${r.status}`,type:typeof o.type=="string"?o.type:"server_error",param:o.param===void 0?null:o.param,code:o.code===void 0?null:o.code}}else t={message:typeof a=="string"?a:`HTTP ${r.status}`,type:"server_error",param:null,code:null}}catch{t={message:e||`HTTP ${r.status}`,type:"server_error",param:null,code:null}}let s=r.headers.get("x-request-id")??void 0,n=rt(r.headers.get("retry-after"));return new g(t,{status:r.status,requestId:s,retryAfterMs:n})}i(ve,"httpError");var zt=class{static{i(this,"SSEDecoder")}event=null;dataParts=[];decode(e){let t=e;if(t.endsWith("\r")&&(t=t.slice(0,-1)),t===""){if(this.event===null&&this.dataParts.length===0)return null;let o={event:this.event,data:this.dataParts.join(`
|
|
5
|
+
`)};return this.event=null,this.dataParts=[],o}if(t.startsWith(":"))return null;let s=t.indexOf(":"),n,a;if(s===-1)n=t,a="";else{n=t.slice(0,s);let o=t.slice(s+1);o.startsWith(" ")&&(o=o.slice(1)),a=o}return n==="event"?this.event=a:n==="data"&&this.dataParts.push(a),null}flush(){if(this.event===null&&this.dataParts.length===0)return null;let e={event:this.event,data:this.dataParts.join(`
|
|
6
|
+
`)};return this.event=null,this.dataParts=[],e}},Gt=class{static{i(this,"LineDecoder")}buffer=new Uint8Array;decoder;constructor(){this.decoder=new TextDecoder("utf-8")}decode(e){let t=new Uint8Array(this.buffer.length+e.length);t.set(this.buffer),t.set(e,this.buffer.length),this.buffer=t;let s=[],n=0;for(let a=0;a<this.buffer.length;a++)if(this.buffer[a]===10||this.buffer[a]===13){let o=this.buffer.subarray(n,a),c=this.decoder.decode(o,{stream:!0});s.push(c),this.buffer[a]===13&&a+1<this.buffer.length&&this.buffer[a+1]===10&&a++,n=a+1}return n>0&&(this.buffer=this.buffer.slice(n)),s}flush(){if(this.buffer.length===0){let t=this.decoder.decode();return t?[t]:[]}let e=this.decoder.decode(this.buffer,{stream:!1});return this.buffer=new Uint8Array,e?[e]:[]}},it="[DONE]";async function*ot(r,e){let t=new zt,s=new Gt,n=r.getReader(),a=!1,o=i(()=>{a=!0,n.cancel().catch(()=>{})},"onAbort");if(e){if(e.aborted)return;e.addEventListener("abort",o,{once:!0})}try{for(;;){if(a)return;let u;try{u=await n.read()}catch(d){if(a||d instanceof Error&&d.name==="AbortError")return;throw d}let{done:h,value:l}=u;if(h)break;for(let d of s.decode(l)){let m=t.decode(d);m&&(yield m)}}for(let u of s.flush()){let h=t.decode(u);h&&(yield h)}let c=t.flush();c&&(yield c)}finally{e&&e.removeEventListener("abort",o);try{n.releaseLock()}catch{}}}i(ot,"iterSSEEvents");function Kt(r){try{let e=JSON.parse(r);if(e&&typeof e=="object"){let t=e.error??e;if(t&&typeof t=="object")return new g({message:typeof t.message=="string"?t.message:"Stream error",type:typeof t.type=="string"?t.type:"server_error",param:t.param===void 0?null:t.param,code:t.code===void 0?null:t.code})}}catch{}return new g({message:r||"Stream error",type:"server_error",param:null,code:null})}i(Kt,"extractSSEError");var Oe=class{static{i(this,"ChatCompletionsAPI")}baseUrl;fetch;constructor(e,t){this.baseUrl=e,this.fetch=t}create(e){return e.stream===!0?this.createStreaming(e):this.createNonStreaming(e)}async createNonStreaming(e){if(e.stream_options)throw new g({message:"stream_options can only be used with stream=true",type:"invalid_request_error",param:"stream_options",code:"request_invalid_parameter"});let{signal:t,...s}=e;s.stream===void 0?delete s.stream:s.stream=!1;let n;try{n=await this.fetch(`${this.baseUrl}/chat/completions`,{method:"POST",headers:{Accept:"application/json","Content-Type":"application/json"},body:JSON.stringify(s),signal:t})}catch(o){throw o instanceof Error&&o.name==="AbortError"?o:new g({message:`Network error: ${o?.message??"unknown"}`,type:"server_error",param:null,code:"gateway_network_error"},{cause:o})}if(!n.ok)throw await ve(n);let a=await n.text();try{return JSON.parse(a)}catch{throw new g({message:"Failed to parse chat completion response: invalid JSON",type:"server_error",param:null,code:"gateway_invalid_response"})}}async*createStreaming(e){let{signal:t,...s}=e;s.stream=!0;let n;try{n=await this.fetch(`${this.baseUrl}/chat/completions`,{method:"POST",headers:{Accept:"text/event-stream","Content-Type":"application/json"},body:JSON.stringify(s),signal:t})}catch(c){if(c instanceof Error&&c.name==="AbortError")return;throw new g({message:`Network error: ${c?.message??"unknown"}`,type:"server_error",param:null,code:"gateway_network_error"},{cause:c})}if(!n.ok)throw await ve(n);if(!n.body)throw new g({message:"Response body is empty \u2014 streaming not supported",type:"server_error",param:null,code:"gateway_invalid_response"});let a=!1,o=!1;try{for await(let c of ot(n.body,t)){if(c.event==="error")throw o=!0,Kt(c.data);if(c.event===null||c.event===""){if(c.data===it){a=!0;return}if(!c.data)continue;let u;try{u=JSON.parse(c.data)}catch{throw o=!0,new g({message:`Failed to parse SSE data: ${c.data}`,type:"server_error",param:null,code:"gateway_invalid_response"})}if(u&&typeof u=="object"&&"error"in u){o=!0;let h=u.error;throw new g({message:typeof h?.message=="string"?h.message:"Stream error",type:typeof h?.type=="string"?h.type:"server_error",param:h?.param===void 0?null:h.param,code:h?.code===void 0?null:h.code})}yield u}}}catch(c){if(c instanceof Error&&c.name==="AbortError")return;throw o=!0,c}if(!a&&!o&&!t?.aborted)throw new g({message:"\u6D41\u5F0F\u54CD\u5E94\u4E2D\u65AD\u3002",type:"server_error",param:null,code:"gateway_stream_interrupted"})}};var W=class{static{i(this,"LlmModule")}fetch;baseUrl;models;chat;constructor(e,t){this.fetch=t,this.baseUrl=`${e.endpoint}${A.llm}`,this.models=new Te(this.baseUrl,this.fetch),this.chat={completions:new Oe(this.baseUrl,this.fetch)}}};var I=class extends Error{static{i(this,"StorageError")}__isStorageError=!0;namespace;status;statusCode;constructor(e,t="storage",s,n){super(e),this.namespace=t,this.name=t==="vectors"?"StorageVectorsError":"StorageError",this.status=s,this.statusCode=n}toJSON(){return{name:this.name,message:this.message,status:this.status,statusCode:this.statusCode}}};function L(r){return typeof r=="object"&&r!==null&&"__isStorageError"in r}i(L,"isStorageError");var H=class extends I{static{i(this,"StorageApiError")}status;statusCode;code;constructor(e,t,s,n="storage",a){super(e,n,t,s),this.name=n==="vectors"?"StorageVectorsApiError":"StorageApiError",this.status=t,this.statusCode=s,this.code=a}toJSON(){return{...super.toJSON(),code:this.code}}},J=class extends I{static{i(this,"StorageUnknownError")}originalError;constructor(e,t,s="storage"){super(e,s),this.name=s==="vectors"?"StorageVectorsUnknownError":"StorageUnknownError",this.originalError=t}};function M(r,e,t){let s={...r},n=e.toLowerCase();for(let a of Object.keys(s))a.toLowerCase()===n&&delete s[a];return s[n]=t,s}i(M,"setHeader");function ct(r){let e={};for(let[t,s]of Object.entries(r))e[t.toLowerCase()]=s;return e}i(ct,"normalizeHeaders");var ht=i(r=>r?(...e)=>r(...e):(...e)=>fetch(...e),"resolveFetch");var ut=i(r=>{if(typeof r!="object"||r===null)return!1;let e=Object.getPrototypeOf(r);return(e===null||e===Object.prototype||Object.getPrototypeOf(e)===null)&&!(Symbol.toStringTag in r)&&!(Symbol.iterator in r)},"isPlainObject"),ke=i(r=>{if(Array.isArray(r))return r.map(t=>ke(t));if(typeof r=="function"||r!==Object(r))return r;let e={};return Object.entries(r).forEach(([t,s])=>{let n=t.replace(/([-_][a-z])/gi,a=>a.toUpperCase().replace(/[-_]/g,""));e[n]=ke(s)}),e},"recursiveToCamel"),lt=i(r=>!r||typeof r!="string"||r.length===0||r.length>100||r.trim()!==r||r.includes("/")||r.includes("\\")?!1:/^[\w!.\*'() &$@=;:+,?-]+$/.test(r),"isValidBucketName");var $e=i(r=>r.split("/").map(encodeURIComponent).join("/"),"encodeStoragePath");var dt=i(r=>{if(typeof r=="object"&&r!==null){let e=r;if(typeof e.msg=="string")return e.msg;if(typeof e.message=="string")return e.message;if(typeof e.error_description=="string")return e.error_description;if(typeof e.error=="string")return e.error;if(typeof e.error=="object"&&e.error!==null){let t=e.error;if(typeof t.message=="string")return t.message}}return JSON.stringify(r)},"_getErrorMessage"),Wt=i(async(r,e,t,s)=>{if(r!==null&&typeof r=="object"&&"json"in r&&typeof r.json=="function"){let a=r,o=parseInt(String(a.status),10);Number.isFinite(o)||(o=500),a.json().then(c=>{let u=c?.statusCode||c?.code||o+"";e(new H(dt(c),o,u,s,c?.code))}).catch(()=>{let c=o+"",u=a.statusText||`HTTP ${o} error`;e(new H(u,o,c,s))})}else e(new J(dt(r),r,s))},"handleError"),Jt=i((r,e,t,s)=>{let n={method:r,headers:e?.headers||{}};if(r==="GET"||r==="HEAD"||!s)return{...n,...t};if(ut(s)){let a=e?.headers||{},o;for(let[c,u]of Object.entries(a))c.toLowerCase()==="content-type"&&(o=u);n.headers=M(a,"Content-Type",o??"application/json"),n.body=JSON.stringify(s)}else n.body=s;return e?.duplex&&(n.duplex=e.duplex),{...n,...t}},"_getRequestParams");async function ne(r,e,t,s,n,a,o){return new Promise((c,u)=>{r(t,Jt(e,s,n,a)).then(h=>{if(!h.ok)throw h;if(s?.noResolveJson)return h;if(o==="vectors"){let l=h.headers.get("content-type");if(h.headers.get("content-length")==="0"||h.status===204)return{};if(!l||!l.includes("application/json"))return{}}return h.json()}).then(h=>c(h)).catch(h=>Wt(h,u,s,o))})}i(ne,"_handleRequest");function ft(r="storage"){return{get:i(async(e,t,s,n)=>ne(e,"GET",t,s,n,void 0,r),"get"),post:i(async(e,t,s,n,a)=>ne(e,"POST",t,n,a,s,r),"post"),put:i(async(e,t,s,n,a)=>ne(e,"PUT",t,n,a,s,r),"put"),head:i(async(e,t,s,n)=>ne(e,"HEAD",t,{...s,noResolveJson:!0},n,void 0,r),"head"),remove:i(async(e,t,s,n,a)=>ne(e,"DELETE",t,n,a,s,r),"remove")}}i(ft,"createFetchApi");var Xt=ft("storage"),{get:N,post:v,put:ae,head:pt,remove:C}=Xt,x=ft("vectors");var E=class{static{i(this,"BaseApiClient")}url;headers;fetch;shouldThrowOnError=!1;namespace;constructor(e,t={},s,n="storage"){this.url=e,this.headers=ct(t),this.fetch=ht(s),this.namespace=n}throwOnError(){return this.shouldThrowOnError=!0,this}setHeader(e,t){return this.headers=M(this.headers,e,t),this}async handleOperation(e){try{return{data:await e(),error:null}}catch(t){if(this.shouldThrowOnError)throw t;if(L(t))return{data:null,error:t};throw t}}};var ie=class{static{i(this,"StreamDownloadBuilder")}downloadFn;shouldThrowOnError;[Symbol.toStringTag]="StreamDownloadBuilder";promise=null;constructor(e,t){this.downloadFn=e,this.shouldThrowOnError=t}then(e,t){return this.getPromise().then(e,t)}catch(e){return this.getPromise().catch(e)}finally(e){return this.getPromise().finally(e)}getPromise(){return this.promise||(this.promise=this.execute()),this.promise}async execute(){try{return{data:(await this.downloadFn()).body,error:null}}catch(e){if(this.shouldThrowOnError)throw e;if(L(e))return{data:null,error:e};throw e}}};var oe=class{static{i(this,"BlobDownloadBuilder")}downloadFn;shouldThrowOnError;[Symbol.toStringTag]="BlobDownloadBuilder";promise=null;constructor(e,t){this.downloadFn=e,this.shouldThrowOnError=t}asStream(){return new ie(this.downloadFn,this.shouldThrowOnError)}then(e,t){return this.getPromise().then(e,t)}catch(e){return this.getPromise().catch(e)}finally(e){return this.getPromise().finally(e)}getPromise(){return this.promise||(this.promise=this.execute()),this.promise}async execute(){try{return{data:await(await this.downloadFn()).blob(),error:null}}catch(e){if(this.shouldThrowOnError)throw e;if(L(e))return{data:null,error:e};throw e}}};var qe={limit:100,offset:0,sortBy:{column:"name",order:"asc"}},mt={cacheControl:"3600",contentType:"text/plain;charset=UTF-8",upsert:!1},ce=class extends E{static{i(this,"StorageFileApi")}bucketId;constructor(e,t={},s,n){super(e,t,n,"storage"),this.bucketId=s}async uploadOrUpdate(e,t,s,n){return this.handleOperation(async()=>{let a,o={...mt,...n},c={...this.headers,...e==="POST"&&{"x-upsert":String(o.upsert)}},u=o.metadata;if(typeof Blob<"u"&&s instanceof Blob?(a=new FormData,a.append("cacheControl",o.cacheControl),u&&a.append("metadata",this.encodeMetadata(u)),a.append("",s)):typeof FormData<"u"&&s instanceof FormData?(a=s,a.has("cacheControl")||a.append("cacheControl",o.cacheControl),u&&!a.has("metadata")&&a.append("metadata",this.encodeMetadata(u))):(a=s,c["cache-control"]=`max-age=${o.cacheControl}`,c["content-type"]=o.contentType,u&&(c["x-metadata"]=this.toBase64(this.encodeMetadata(u))),(typeof ReadableStream<"u"&&a instanceof ReadableStream||a&&typeof a=="object"&&"pipe"in a&&typeof a.pipe=="function")&&!o.duplex&&(o.duplex="half")),n?.headers)for(let[m,p]of Object.entries(n.headers))c=M(c,m,p);let h=this._removeEmptyFolders(t),l=this._getFinalPath(h),d=await(e=="PUT"?ae:v)(this.fetch,`${this.url}/object/${l}`,a,{headers:c,...o?.duplex?{duplex:o.duplex}:{}});return{path:h,id:d.Id,fullPath:d.Key}})}async upload(e,t,s){return this.uploadOrUpdate("POST",e,t,s)}async uploadToSignedUrl(e,t,s,n){let a=this._removeEmptyFolders(e),o=this._getFinalPath(a),c=new URL(this.url+`/object/upload/sign/${o}`);return c.searchParams.set("token",t),this.handleOperation(async()=>{let u,h={...mt,...n},l={...this.headers,"x-upsert":String(h.upsert)},d=h.metadata;if(typeof Blob<"u"&&s instanceof Blob?(u=new FormData,u.append("cacheControl",h.cacheControl),d&&u.append("metadata",this.encodeMetadata(d)),u.append("",s)):typeof FormData<"u"&&s instanceof FormData?(u=s,u.has("cacheControl")||u.append("cacheControl",h.cacheControl),d&&!u.has("metadata")&&u.append("metadata",this.encodeMetadata(d))):(u=s,l["cache-control"]=`max-age=${h.cacheControl}`,l["content-type"]=h.contentType,d&&(l["x-metadata"]=this.toBase64(this.encodeMetadata(d))),(typeof ReadableStream<"u"&&u instanceof ReadableStream||u&&typeof u=="object"&&"pipe"in u&&typeof u.pipe=="function")&&!h.duplex&&(h.duplex="half")),n?.headers)for(let[p,_]of Object.entries(n.headers))l=M(l,p,_);let m=await ae(this.fetch,c.toString(),u,{headers:l,...h?.duplex?{duplex:h.duplex}:{}});return{path:a,fullPath:m.Key}})}async createSignedUploadUrl(e,t){return this.handleOperation(async()=>{let s=this._getFinalPath(e),n={...this.headers};t?.upsert&&(n["x-upsert"]="true");let a=await v(this.fetch,`${this.url}/object/upload/sign/${s}`,{},{headers:n}),o=new URL(this.url+a.url),c=o.searchParams.get("token");if(!c)throw new I("No token returned by API");return{signedUrl:o.toString(),path:e,token:c}})}async update(e,t,s){return this.uploadOrUpdate("PUT",e,t,s)}async move(e,t,s){return this.handleOperation(async()=>await v(this.fetch,`${this.url}/object/move`,{bucketId:this.bucketId,sourceKey:e,destinationKey:t,destinationBucket:s?.destinationBucket},{headers:this.headers}))}async copy(e,t,s){return this.handleOperation(async()=>({path:(await v(this.fetch,`${this.url}/object/copy`,{bucketId:this.bucketId,sourceKey:e,destinationKey:t,destinationBucket:s?.destinationBucket},{headers:this.headers})).Key}))}async createSignedUrl(e,t,s){return this.handleOperation(async()=>{let n=this._getFinalPath(e),a=typeof s?.transform=="object"&&s.transform!==null&&Object.keys(s.transform).length>0,o=await v(this.fetch,`${this.url}/object/sign/${n}`,{expiresIn:t,...a?{transform:s.transform}:{}},{headers:this.headers}),c=new URLSearchParams;s?.download&&c.set("download",s.download===!0?"":s.download),s?.cacheNonce!=null&&c.set("cacheNonce",String(s.cacheNonce));let u=c.toString();return{signedUrl:encodeURI(`${this.url}${o.signedURL}${u?`&${u}`:""}`)}})}async createSignedUrls(e,t,s){return this.handleOperation(async()=>{let n=await v(this.fetch,`${this.url}/object/sign/${this.bucketId}`,{expiresIn:t,paths:e},{headers:this.headers}),a=new URLSearchParams;s?.download&&a.set("download",s.download===!0?"":s.download),s?.cacheNonce!=null&&a.set("cacheNonce",String(s.cacheNonce));let o=a.toString();return n.map(c=>({...c,signedUrl:c.signedURL?encodeURI(`${this.url}${c.signedURL}${o?`&${o}`:""}`):null}))})}download(e,t,s){let a=typeof t?.transform=="object"&&t.transform!==null&&Object.keys(t.transform).length>0?"render/image/authenticated":"object",o=new URLSearchParams;t?.transform&&this.applyTransformOptsToQuery(o,t.transform),t?.cacheNonce!=null&&o.set("cacheNonce",String(t.cacheNonce));let c=o.toString(),u=this._getFinalPath(e),h=i(()=>N(this.fetch,`${this.url}/${a}/${u}${c?`?${c}`:""}`,{headers:this.headers,noResolveJson:!0},s),"downloadFn");return new oe(h,this.shouldThrowOnError)}async info(e){let t=this._getFinalPath(e);return this.handleOperation(async()=>{let s=await N(this.fetch,`${this.url}/object/info/${t}`,{headers:this.headers});return ke(s)})}async exists(e){let t=this._getFinalPath(e);try{return await pt(this.fetch,`${this.url}/object/${t}`,{headers:this.headers}),{data:!0,error:null}}catch(s){if(this.shouldThrowOnError)throw s;if(L(s)){let n=s instanceof H?s.status:s instanceof J?s.originalError?.status:void 0;if(n!==void 0&&[400,404].includes(n))return{data:!1,error:s}}throw s}}getPublicUrl(e,t){let s=this._getFinalPath(e),n=new URLSearchParams;t?.download&&n.set("download",t.download===!0?"":t.download),t?.transform&&this.applyTransformOptsToQuery(n,t.transform),t?.cacheNonce!=null&&n.set("cacheNonce",String(t.cacheNonce));let a=n.toString(),c=typeof t?.transform=="object"&&t.transform!==null&&Object.keys(t.transform).length>0?"render/image":"object";return{data:{publicUrl:encodeURI(`${this.url}/${c}/public/${s}`)+(a?`?${a}`:"")}}}async remove(e){return this.handleOperation(async()=>await C(this.fetch,`${this.url}/object/${this.bucketId}`,{prefixes:e},{headers:this.headers}))}async purgeCache(e,t,s){return this.handleOperation(async()=>{let n=$e(this._getFinalPath(e)),a=new URLSearchParams;t?.transformations&&a.set("transformations","true");let o=a.toString();return await C(this.fetch,`${this.url}/cdn/${n}${o?`?${o}`:""}`,{},{headers:this.headers},s)})}async list(e,t,s){return this.handleOperation(async()=>{let n=t?.sortBy?{...qe.sortBy,...t.sortBy}:qe.sortBy,a={...qe,...t,sortBy:n,prefix:e||""};return await v(this.fetch,`${this.url}/object/list/${this.bucketId}`,a,{headers:this.headers},s)})}async listV2(e,t){return this.handleOperation(async()=>{let s={...e};return await v(this.fetch,`${this.url}/object/list-v2/${this.bucketId}`,s,{headers:this.headers},t)})}encodeMetadata(e){return JSON.stringify(e)}toBase64(e){return typeof Buffer<"u"?Buffer.from(e).toString("base64"):btoa(e)}_getFinalPath(e){return`${this.bucketId}/${e.replace(/^\/+/,"")}`}_removeEmptyFolders(e){return e.replace(/^\/|\/$/g,"").replace(/\/+/g,"/")}applyTransformOptsToQuery(e,t){return t.width&&e.set("width",t.width.toString()),t.height&&e.set("height",t.height.toString()),t.resize&&e.set("resize",t.resize),t.format&&e.set("format",t.format),t.quality&&e.set("quality",t.quality.toString()),e}};var yt="2.112.3";var U={"X-Client-Info":`storage-js/${yt}`};var he=class extends E{static{i(this,"StorageBucketApi")}constructor(e,t={},s,n){let a=new URL(e);n?.useNewHostname&&/supabase\.(co|in|red)$/.test(a.hostname)&&!a.hostname.includes("storage.supabase.")&&(a.hostname=a.hostname.replace("supabase.","storage.supabase."));let o=a.href.replace(/\/$/,""),c={...U,...t};super(o,c,s,"storage")}async listBuckets(e){return this.handleOperation(async()=>{let t=this.listBucketOptionsToQueryString(e);return await N(this.fetch,`${this.url}/bucket${t}`,{headers:this.headers})})}async getBucket(e){return this.handleOperation(async()=>await N(this.fetch,`${this.url}/bucket/${e}`,{headers:this.headers}))}async createBucket(e,t={public:!1}){return this.handleOperation(async()=>await v(this.fetch,`${this.url}/bucket`,{id:e,name:e,type:t.type,public:t.public,file_size_limit:t.fileSizeLimit,allowed_mime_types:t.allowedMimeTypes},{headers:this.headers}))}async updateBucket(e,t){return this.handleOperation(async()=>await ae(this.fetch,`${this.url}/bucket/${e}`,{id:e,name:e,public:t.public,file_size_limit:t.fileSizeLimit,allowed_mime_types:t.allowedMimeTypes},{headers:this.headers}))}async emptyBucket(e){return this.handleOperation(async()=>await v(this.fetch,`${this.url}/bucket/${e}/empty`,{},{headers:this.headers}))}async deleteBucket(e){return this.handleOperation(async()=>await C(this.fetch,`${this.url}/bucket/${e}`,{},{headers:this.headers}))}async purgeBucketCache(e,t,s){return this.handleOperation(async()=>{let n=new URLSearchParams;t?.transformations&&n.set("transformations","true");let a=n.toString();return await C(this.fetch,`${this.url}/cdn/${$e(e)}${a?`?${a}`:""}`,{},{headers:this.headers},s)})}listBucketOptionsToQueryString(e){let t={};return e&&("limit"in e&&(t.limit=String(e.limit)),"offset"in e&&(t.offset=String(e.offset)),e.search&&(t.search=e.search),e.sortColumn&&(t.sortColumn=e.sortColumn),e.sortOrder&&(t.sortOrder=e.sortOrder)),Object.keys(t).length>0?"?"+new URLSearchParams(t).toString():""}};var B=class extends Error{static{i(this,"IcebergError")}constructor(r,e){super(r),this.name="IcebergError",this.status=e.status,this.icebergType=e.icebergType,this.icebergCode=e.icebergCode,this.details=e.details,this.isCommitStateUnknown=e.icebergType==="CommitStateUnknownException"}isNotFound(){return this.status===404}isConflict(){return this.status===409}isAuthenticationTimeout(){return this.status===419}};function Yt(r,e,t){let s=new URL(e,r);if(t)for(let[n,a]of Object.entries(t))a!==void 0&&s.searchParams.set(n,a);return s.toString()}i(Yt,"buildUrl");async function Qt(r){return!r||r.type==="none"?{}:r.type==="bearer"?{Authorization:`Bearer ${r.token}`}:r.type==="header"?{[r.name]:r.value}:r.type==="custom"?await r.getHeaders():{}}i(Qt,"buildAuthHeaders");function Zt(r){let e=r.fetchImpl??globalThis.fetch;return{async request({method:t,path:s,query:n,body:a,headers:o}){let c=Yt(r.baseUrl,s,n),u=await Qt(r.auth),h;try{h=await e(c,{method:t,headers:{...a?{"Content-Type":"application/json"}:{},...u,...o},body:a?JSON.stringify(a):void 0})}catch(p){if(p instanceof B)throw p;let _=p instanceof Error?p.message:String(p);throw new B(`Network request failed: ${_}`,{status:0,details:p})}if(h.status===304)return{status:304,headers:h.headers,data:void 0};let l=await h.text(),d=(h.headers.get("content-type")||"").includes("application/json"),m=d&&l?JSON.parse(l):l;if(!h.ok){let p=d?m:void 0,_=p?.error;throw new B(_?.message??`Request failed with status ${h.status}`,{status:h.status,icebergType:_?.type,icebergCode:_?.code,details:p})}return{status:h.status,headers:h.headers,data:m}}}}i(Zt,"createFetchClient");function D(){let r=BigInt(Date.now()),e=new Uint8Array(16);e[0]=Number(r>>40n&0xffn),e[1]=Number(r>>32n&0xffn),e[2]=Number(r>>24n&0xffn),e[3]=Number(r>>16n&0xffn),e[4]=Number(r>>8n&0xffn),e[5]=Number(r&0xffn);let t=new Uint8Array(10);return tr(t),e.set(t,6),e[6]=e[6]&15|112,e[8]=e[8]&63|128,er(e)}i(D,"generateIdempotencyKey");function er(r){let e=[];for(let t=0;t<16;t++)e.push(r[t].toString(16).padStart(2,"0"));return`${e.slice(0,4).join("")}-${e.slice(4,6).join("")}-${e.slice(6,8).join("")}-${e.slice(8,10).join("")}-${e.slice(10,16).join("")}`}i(er,"formatUUID");function tr(r){let e=typeof globalThis.crypto<"u"&&typeof globalThis.crypto.getRandomValues=="function"?globalThis.crypto:void 0;if(e){e.getRandomValues(r);return}for(let t=0;t<r.length;t++)r[t]=Math.floor(Math.random()*256)}i(tr,"cryptoRandom");function Pe(r){return r.map(encodeURIComponent).join("%1F")}i(Pe,"namespaceToPath");function rr(r){return r.join("")}i(rr,"namespaceToParentQuery");async function X(r){return typeof r=="string"?r:r()}i(X,"resolvePrefix");var sr=class{static{i(this,"NamespaceOperations")}constructor(r,e=""){this.client=r,this.prefix=e}async listNamespaces(r={}){let e=await X(this.prefix),t={};r.parent&&(t.parent=rr(r.parent.namespace)),r.pageToken!==void 0&&(t.pageToken=r.pageToken),r.pageSize!==void 0&&(t.pageSize=String(r.pageSize));let s=Object.keys(t).some(a=>t[a]!==void 0),n=await this.client.request({method:"GET",path:`${e}/namespaces`,query:s?t:void 0});return{namespaces:(n.data.namespaces??[]).map(a=>({namespace:a})),nextPageToken:n.data["next-page-token"]??void 0}}async createNamespace(r,e){let t=await X(this.prefix),s={namespace:r.namespace,properties:e?.properties};return(await this.client.request({method:"POST",path:`${t}/namespaces`,body:s,headers:{"Idempotency-Key":D()}})).data}async dropNamespace(r){let e=await X(this.prefix);await this.client.request({method:"DELETE",path:`${e}/namespaces/${Pe(r.namespace)}`,headers:{"Idempotency-Key":D()}})}async loadNamespaceMetadata(r){let e=await X(this.prefix);return{properties:(await this.client.request({method:"GET",path:`${e}/namespaces/${Pe(r.namespace)}`})).data.properties??{}}}async namespaceExists(r){let e=await X(this.prefix);try{return await this.client.request({method:"HEAD",path:`${e}/namespaces/${Pe(r.namespace)}`}),!0}catch(t){if(t instanceof B&&t.status===404)return!1;throw t}}async updateNamespaceProperties(r,e){let t=await X(this.prefix);return(await this.client.request({method:"POST",path:`${t}/namespaces/${Pe(r.namespace)}/properties`,body:e,headers:{"Idempotency-Key":D()}})).data}async createNamespaceIfNotExists(r,e){try{return await this.createNamespace(r,e)}catch(t){if(t instanceof B&&t.status===409)return;throw t}}};function V(r){return r.map(encodeURIComponent).join("%1F")}i(V,"namespaceToPath2");function _e(r){return encodeURIComponent(r)}i(_e,"tableSegment");async function j(r){return typeof r=="string"?r:r()}i(j,"resolvePrefix2");var nr=class{static{i(this,"TableOperations")}constructor(r,e="",t){this.client=r,this.prefix=e,this.accessDelegation=t}async listTables(r,e={}){let t=await j(this.prefix),s={};e.pageToken!==void 0&&(s.pageToken=e.pageToken),e.pageSize!==void 0&&(s.pageSize=String(e.pageSize));let n=Object.keys(s).some(o=>s[o]!==void 0),a=await this.client.request({method:"GET",path:`${t}/namespaces/${V(r.namespace)}/tables`,query:n?s:void 0});return{identifiers:a.data.identifiers??[],nextPageToken:a.data["next-page-token"]??void 0}}async createTable(r,e){return(await this.createTableResult(r,e)).metadata}async createTableResult(r,e){let t=await j(this.prefix),s={"Idempotency-Key":D()};this.accessDelegation&&(s["X-Iceberg-Access-Delegation"]=this.accessDelegation);let n=await this.client.request({method:"POST",path:`${t}/namespaces/${V(r.namespace)}/tables`,body:e,headers:s});return{...n.data,etag:n.headers.get("etag")}}async updateTable(r,e){let t=await j(this.prefix),s=await this.client.request({method:"POST",path:`${t}/namespaces/${V(r.namespace)}/tables/${_e(r.name)}`,body:e,headers:{"Idempotency-Key":D()}}),n=s.data["metadata-location"];if(!n)throw new B("Server returned 200 without required `metadata-location` field on CommitTableResponse",{status:s.status,details:s.data});return{"metadata-location":n,metadata:s.data.metadata}}async commitTable(r,e){return this.updateTable(r,e)}async dropTable(r,e){let t=await j(this.prefix);await this.client.request({method:"DELETE",path:`${t}/namespaces/${V(r.namespace)}/tables/${_e(r.name)}`,query:{purgeRequested:String(e?.purge??!1)},headers:{"Idempotency-Key":D()}})}async loadTable(r,e){let t=await this.loadTableResult(r,e);return t?t.metadata:null}async loadTableResult(r,e){let t=await j(this.prefix),s={};this.accessDelegation&&(s["X-Iceberg-Access-Delegation"]=this.accessDelegation),e?.ifNoneMatch&&(s["If-None-Match"]=e.ifNoneMatch);let n={};e?.snapshots&&(n.snapshots=e.snapshots);let a=await this.client.request({method:"GET",path:`${t}/namespaces/${V(r.namespace)}/tables/${_e(r.name)}`,headers:s,query:Object.keys(n).length?n:void 0});return a.status===304?null:{...a.data,etag:a.headers.get("etag")}}async tableExists(r){let e=await j(this.prefix),t={};this.accessDelegation&&(t["X-Iceberg-Access-Delegation"]=this.accessDelegation);try{return await this.client.request({method:"HEAD",path:`${e}/namespaces/${V(r.namespace)}/tables/${_e(r.name)}`,headers:t}),!0}catch(s){if(s instanceof B&&s.status===404)return!1;throw s}}async registerTable(r,e){return(await this.registerTableResult(r,e)).metadata}async registerTableResult(r,e){let t=await j(this.prefix),s={"Idempotency-Key":D()};this.accessDelegation&&(s["X-Iceberg-Access-Delegation"]=this.accessDelegation);let n=await this.client.request({method:"POST",path:`${t}/namespaces/${V(r.namespace)}/register`,body:e,headers:s});return{...n.data,etag:n.headers.get("etag")}}async renameTable(r){let e=await j(this.prefix);await this.client.request({method:"POST",path:`${e}/tables/rename`,body:r,headers:{"Idempotency-Key":D()}})}async createTableIfNotExists(r,e){try{return await this.createTable(r,e)}catch(t){if(t instanceof B&&t.status===409)return await this.loadTable({namespace:r.namespace,name:e.name});throw t}}},gt=class{static{i(this,"IcebergRestCatalog")}constructor(r){let e=r.baseUrl.endsWith("/")?r.baseUrl:`${r.baseUrl}/`;this.warehouse=r.warehouse??r.catalogName,this.client=Zt({baseUrl:e,auth:r.auth,fetchImpl:r.fetch}),this.accessDelegation=r.accessDelegation?.join(",");let t=i(()=>this.resolvePrefix(),"getPrefix");this.namespaceOps=new sr(this.client,t),this.tableOps=new nr(this.client,t,this.accessDelegation)}async loadConfig(){if(!this.cachedConfigPromise){let r={};this.warehouse!==void 0&&(r.warehouse=this.warehouse),this.cachedConfigPromise=this.client.request({method:"GET",path:"v1/config",query:Object.keys(r).length?r:void 0}).then(e=>e.data).catch(e=>{throw this.cachedConfigPromise=void 0,e})}return this.cachedConfigPromise}async resolvePrefix(){return this.prefixPromise||(this.prefixPromise=this.computePrefix()),this.prefixPromise}async computePrefix(){if(this.warehouse===void 0)return"v1";try{let r=await this.loadConfig(),e=r.overrides?.prefix??r.defaults?.prefix;return e?`v1/${e}`:`v1/${this.warehouse}`}catch{return`v1/${this.warehouse}`}}async listNamespaces(r={}){return this.namespaceOps.listNamespaces(r)}async createNamespace(r,e){return this.namespaceOps.createNamespace(r,e)}async dropNamespace(r){await this.namespaceOps.dropNamespace(r)}async loadNamespaceMetadata(r){return this.namespaceOps.loadNamespaceMetadata(r)}async updateNamespaceProperties(r,e){return this.namespaceOps.updateNamespaceProperties(r,e)}async listTables(r,e={}){return this.tableOps.listTables(r,e)}async createTable(r,e){return this.tableOps.createTable(r,e)}async createTableResult(r,e){return this.tableOps.createTableResult(r,e)}async updateTable(r,e){return this.tableOps.updateTable(r,e)}async commitTable(r,e){return this.tableOps.commitTable(r,e)}async dropTable(r,e){await this.tableOps.dropTable(r,e)}async loadTable(r,e){return e?this.tableOps.loadTable(r,e):this.tableOps.loadTable(r)}async loadTableResult(r,e){return this.tableOps.loadTableResult(r,e)}async namespaceExists(r){return this.namespaceOps.namespaceExists(r)}async tableExists(r){return this.tableOps.tableExists(r)}async createNamespaceIfNotExists(r,e){return this.namespaceOps.createNamespaceIfNotExists(r,e)}async createTableIfNotExists(r,e){return this.tableOps.createTableIfNotExists(r,e)}async registerTable(r,e){return this.tableOps.registerTable(r,e)}async registerTableResult(r,e){return this.tableOps.registerTableResult(r,e)}async renameTable(r){return this.tableOps.renameTable(r)}};var wt={tag:"apache-iceberg-1.11.0-rc1"},on=wt.tag,cn=`https://raw.githubusercontent.com/apache/iceberg/${wt.tag}/open-api/rest-catalog-open-api.yaml`;var ue=class extends E{static{i(this,"StorageAnalyticsClient")}constructor(e,t={},s){let n=e.replace(/\/$/,""),a={...U,...t};super(n,a,s,"storage")}async createBucket(e){return this.handleOperation(async()=>await v(this.fetch,`${this.url}/bucket`,{name:e},{headers:this.headers}))}async listBuckets(e){return this.handleOperation(async()=>{let t=new URLSearchParams;e?.limit!==void 0&&t.set("limit",e.limit.toString()),e?.offset!==void 0&&t.set("offset",e.offset.toString()),e?.sortColumn&&t.set("sortColumn",e.sortColumn),e?.sortOrder&&t.set("sortOrder",e.sortOrder),e?.search&&t.set("search",e.search);let s=t.toString(),n=s?`${this.url}/bucket?${s}`:`${this.url}/bucket`;return await N(this.fetch,n,{headers:this.headers})})}async deleteBucket(e){return this.handleOperation(async()=>await C(this.fetch,`${this.url}/bucket/${e}`,{},{headers:this.headers}))}from(e){if(!lt(e))throw new I("Invalid bucket name: File, folder, and bucket names must follow AWS object key naming guidelines and should avoid the use of any other characters.");let t=new gt({baseUrl:this.url,catalogName:e,auth:{type:"custom",getHeaders:i(async()=>this.headers,"getHeaders")},fetch:this.fetch}),s=this.shouldThrowOnError;return new Proxy(t,{get(a,o){let c=a[o];return typeof c!="function"?c:async(...u)=>{try{return{data:await c.apply(a,u),error:null}}catch(h){if(s)throw h;return{data:null,error:h}}}}})}};var le=class extends E{static{i(this,"VectorIndexApi")}constructor(e,t={},s){let n=e.replace(/\/$/,""),a={...U,"Content-Type":"application/json",...t};super(n,a,s,"vectors")}async createIndex(e){return this.handleOperation(async()=>await x.post(this.fetch,`${this.url}/CreateIndex`,e,{headers:this.headers})||{})}async getIndex(e,t){return this.handleOperation(async()=>await x.post(this.fetch,`${this.url}/GetIndex`,{vectorBucketName:e,indexName:t},{headers:this.headers}))}async listIndexes(e){return this.handleOperation(async()=>await x.post(this.fetch,`${this.url}/ListIndexes`,e,{headers:this.headers}))}async deleteIndex(e,t){return this.handleOperation(async()=>await x.post(this.fetch,`${this.url}/DeleteIndex`,{vectorBucketName:e,indexName:t},{headers:this.headers})||{})}};var de=class extends E{static{i(this,"VectorDataApi")}constructor(e,t={},s){let n=e.replace(/\/$/,""),a={...U,"Content-Type":"application/json",...t};super(n,a,s,"vectors")}async putVectors(e){if(e.vectors.length<1||e.vectors.length>500)throw new Error("Vector batch size must be between 1 and 500 items");return this.handleOperation(async()=>await x.post(this.fetch,`${this.url}/PutVectors`,e,{headers:this.headers})||{})}async getVectors(e){return this.handleOperation(async()=>await x.post(this.fetch,`${this.url}/GetVectors`,e,{headers:this.headers}))}async listVectors(e){if(e.segmentCount!==void 0){if(e.segmentCount<1||e.segmentCount>16)throw new Error("segmentCount must be between 1 and 16");if(e.segmentIndex!==void 0&&(e.segmentIndex<0||e.segmentIndex>=e.segmentCount))throw new Error(`segmentIndex must be between 0 and ${e.segmentCount-1}`)}return this.handleOperation(async()=>await x.post(this.fetch,`${this.url}/ListVectors`,e,{headers:this.headers}))}async queryVectors(e){return this.handleOperation(async()=>await x.post(this.fetch,`${this.url}/QueryVectors`,e,{headers:this.headers}))}async deleteVectors(e){if(e.keys.length<1||e.keys.length>500)throw new Error("Keys batch size must be between 1 and 500 items");return this.handleOperation(async()=>await x.post(this.fetch,`${this.url}/DeleteVectors`,e,{headers:this.headers})||{})}};var fe=class extends E{static{i(this,"VectorBucketApi")}constructor(e,t={},s){let n=e.replace(/\/$/,""),a={...U,"Content-Type":"application/json",...t};super(n,a,s,"vectors")}async createBucket(e){return this.handleOperation(async()=>await x.post(this.fetch,`${this.url}/CreateVectorBucket`,{vectorBucketName:e},{headers:this.headers})||{})}async getBucket(e){return this.handleOperation(async()=>await x.post(this.fetch,`${this.url}/GetVectorBucket`,{vectorBucketName:e},{headers:this.headers}))}async listBuckets(e={}){return this.handleOperation(async()=>await x.post(this.fetch,`${this.url}/ListVectorBuckets`,e,{headers:this.headers}))}async deleteBucket(e){return this.handleOperation(async()=>await x.post(this.fetch,`${this.url}/DeleteVectorBucket`,{vectorBucketName:e},{headers:this.headers})||{})}};var Ae=class extends fe{static{i(this,"StorageVectorsClient")}constructor(e,t={}){super(e,t.headers||{},t.fetch)}from(e){return new Fe(this.url,this.headers,e,this.fetch)}async createBucket(e){return super.createBucket(e)}async getBucket(e){return super.getBucket(e)}async listBuckets(e={}){return super.listBuckets(e)}async deleteBucket(e){return super.deleteBucket(e)}},Fe=class extends le{static{i(this,"VectorBucketScope")}vectorBucketName;constructor(e,t,s,n){super(e,t,n),this.vectorBucketName=s}async createIndex(e){return super.createIndex({...e,vectorBucketName:this.vectorBucketName})}async listIndexes(e={}){return super.listIndexes({...e,vectorBucketName:this.vectorBucketName})}async getIndex(e){return super.getIndex(this.vectorBucketName,e)}async deleteIndex(e){return super.deleteIndex(this.vectorBucketName,e)}index(e){return new He(this.url,this.headers,this.vectorBucketName,e,this.fetch)}},He=class extends de{static{i(this,"VectorIndexScope")}vectorBucketName;indexName;constructor(e,t,s,n,a){super(e,t,a),this.vectorBucketName=s,this.indexName=n}async putVectors(e){return super.putVectors({...e,vectorBucketName:this.vectorBucketName,indexName:this.indexName})}async getVectors(e){return super.getVectors({...e,vectorBucketName:this.vectorBucketName,indexName:this.indexName})}async listVectors(e={}){return super.listVectors({...e,vectorBucketName:this.vectorBucketName,indexName:this.indexName})}async queryVectors(e){return super.queryVectors({...e,vectorBucketName:this.vectorBucketName,indexName:this.indexName})}async deleteVectors(e){return super.deleteVectors({...e,vectorBucketName:this.vectorBucketName,indexName:this.indexName})}};var pe=class extends he{static{i(this,"StorageClient")}constructor(e,t={},s,n){super(e,t,s,n)}from(e){return new ce(this.url,this.headers,e,this.fetch)}get vectors(){return new Ae(this.url+"/vector",{headers:this.headers,fetch:this.fetch})}get analytics(){return new ue(this.url+"/iceberg",this.headers,this.fetch)}};var Y="runtime",Re=600,Ue=3600,w=class extends Error{static{i(this,"CloudStoragePathError")}constructor(e){super(e),this.name="CloudStoragePathError"}},me=class{static{i(this,"WorkBuddyStorageDownload")}blob;stream;[Symbol.toStringTag]="WorkBuddyStorageDownload";constructor(e,t){this.blob=e,this.stream=t}asStream(){return this.stream()}then(e,t){return this.blob().then(e,t)}catch(e){return this.blob().catch(e)}finally(e){return this.blob().finally(e)}},Q=class{static{i(this,"WorkBuddyStorageBucket")}fileApi;constructor(e){this.fileApi=e}upload(e,t,s){return O(this.fileApi.upload(T(e),t,s))}update(e,t,s){return O(this.fileApi.update(T(e),t,s))}list(e="",t){return O(this.fileApi.list(xt(e),t))}listPage(e){return O(this.fileApi.listV2({...e,prefix:xt(e?.prefix??"")}))}info(e){return O(this.fileApi.info(T(e)))}async exists(e){let t=await this.fileApi.exists(T(e));return t.error?{data:null,error:Tt(t.error)}:{data:t.data,error:null}}download(e){let t=this.fileApi.download(T(e));return new me(()=>O(t),()=>O(t.asStream()))}remove(e){if(e.length===0)throw new w("remove requires at least one object path.");return O(this.fileApi.remove(e.map(T)))}copy(e,t){return O(this.fileApi.copy(T(e),T(t)))}move(e,t){return O(this.fileApi.move(T(e),T(t)))}createSignedUrl(e,t=Re){return O(this.fileApi.createSignedUrl(T(e),St(t)))}createSignedUrls(e,t=Re){if(e.length===0)throw new w("createSignedUrls requires at least one object path.");return O(this.fileApi.createSignedUrls(e.map(T),St(t)))}createSignedUploadUrl(e,t){return O(this.fileApi.createSignedUploadUrl(T(e),{upsert:t?.upsert??!1}))}uploadToSignedUrl(e,t,s,n){if(!t)throw new w("signed upload token is required.");return O(this.fileApi.uploadToSignedUrl(T(e),t,s,n))}},ye=class extends Q{static{i(this,"WorkBuddyStorageModule")}runtime;constructor(e){let s=e.from(Y);super(s),this.runtime=new Q(s)}from(e=Y){if(e!==Y)throw new w(`Only the "${Y}" storage bucket is available.`);return this.runtime}userPath(e,t){return bt("users",e,t)}sharedPath(e,t){return bt("shared",e,t)}};function Et(r,e){let t=new pe(`${r.endpoint}${A.storage}`,{},e);return new ye(t)}i(Et,"createStorageModule");function bt(r,e,t){let s=ar(e,"owner/user id"),n=Me(t,!1);return T(`${r}/${s}/${n}`)}i(bt,"scopedPath");function T(r){let e=Me(r,!1);if(!e.includes("/"))throw new w("Object paths must use users/<uid>/... or shared/<ownerUid>/....");let[t,s,...n]=e.split("/");if(t!=="users"&&t!=="shared"||!s||n.length===0)throw new w("Object paths must use users/<uid>/... or shared/<ownerUid>/....");return e}i(T,"validateObjectPath");function xt(r){if(r==="")return"";let e=Me(r,!0),[t,s]=e.split("/");if(t==="shared"&&!s)return"shared";if(t!=="users"&&t!=="shared"||!s)throw new w("List prefixes must start with users/<uid> or shared/<ownerUid>.");return e}i(xt,"validateObjectPrefix");function Me(r,e){if(typeof r!="string"||r.trim()==="")throw new w("Storage path must be a non-empty relative path.");let t=r.trim();for(let a=0;a<3;a+=1)try{let o=decodeURIComponent(t);if(o===t)break;t=o}catch{throw new w("Storage path contains invalid URL encoding.")}if(t.startsWith("/")||t.includes("\\")||t.includes("\0")||t.includes("//")||!e&&t.endsWith("/"))throw new w("Storage path is not a safe relative object path.");let s=e?t.replace(/\/+$/,""):t;if(s.split("/").some(a=>a===""||a==="."||a===".."))throw new w("Storage path traversal is not allowed.");return s}i(Me,"validatePath");function ar(r,e){if(!r)throw new w(`${e} is not a valid storage path segment.`);let t=r;for(let s=0;s<3;s+=1)try{let n=decodeURIComponent(t);if(n===t)break;t=n}catch{throw new w(`${e} contains invalid URL encoding.`)}if(t.includes("/")||t.includes("\\")||t.includes("\0")||t==="."||t==="..")throw new w(`${e} is not a valid storage path segment.`);return t}i(ar,"validatePathSegment");function St(r){if(!Number.isInteger(r)||r<=0||r>Ue)throw new w(`Signed URL expiry must be an integer between 1 and ${Ue} seconds.`);return r}i(St,"validateSignedURLTTL");async function O(r){let e=await r;return e.error?{data:null,error:Tt(e.error)}:e.data===null?{data:null,error:{name:"CloudStorageResponseError",message:"Storage API returned neither data nor an error."}}:{data:e.data,error:null}}i(O,"mapStorageResult");function Tt(r){if(r instanceof Error){let e=r;return{name:e.name,message:e.message,status:e.status,statusCode:e.statusCode,code:e.code,cause:r}}return{name:"CloudStorageError",message:String(r),cause:r}}i(Tt,"normalizeStorageError");var ge=class{static{i(this,"WorkBuddyCloudClient")}config;database;auth;storage;llm;constructor(e,t={}){this.config=e,this.auth=new G(e,Le(e,be),{storage:t.storage});let s=Le(e,()=>this.auth.getAccessToken());this.database=tt(e,s),this.storage=Et(e,s),this.llm=new W(e,s)}get endpoint(){return this.config.endpoint}get oauthRelayBaseUrl(){return this.config.oauthRelayBaseUrl}};function vt(r){return new ge(ze(r),{storage:r.storage})}i(vt,"createWorkBuddyCloud");function Ot(r){return r.kind==="unauthenticated"||r.code==="invalid_grant"}i(Ot,"shouldClearCredentials");return Rt(ir);})();
|
|
7
|
+
//# sourceMappingURL=index.global.js.map
|