@tencent-ai/workbuddy-cloud-sdk 0.1.0-dev.bb3f1dd.202609071252
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 +9338 -0
- package/lib/index.cjs.map +1 -0
- package/lib/index.d.cts +6677 -0
- package/lib/index.d.ts +6677 -0
- package/lib/index.global.js +7 -0
- package/lib/index.global.js.map +1 -0
- package/lib/index.js +9293 -0
- package/lib/index.js.map +1 -0
- package/lib/miniprogram.cjs +9641 -0
- package/lib/miniprogram.cjs.map +1 -0
- package/lib/miniprogram.d.cts +6693 -0
- package/lib/miniprogram.d.ts +6693 -0
- package/lib/miniprogram.js +9611 -0
- package/lib/miniprogram.js.map +1 -0
- package/package.json +126 -0
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
var WorkBuddyCloud=(()=>{var we=Object.defineProperty;var _t=Object.getOwnPropertyDescriptor;var At=Object.getOwnPropertyNames;var Rt=Object.prototype.hasOwnProperty;var i=(r,e)=>we(r,"name",{value:e,configurable:!0});var Ut=(r,e)=>{for(var t in e)we(r,t,{get:e[t],enumerable:!0})},It=(r,e,t,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of At(e))!Rt.call(r,n)&&n!==t&&we(r,n,{get:()=>e[n],enumerable:!(s=_t(e,n))||s.enumerable});return r};var Ct=r=>It(we({},"__esModule",{value:!0}),r);var hr={};Ut(hr,{AuthModule:()=>K,CLOUD_MODULE_PATHS:()=>U,CLOUD_PATH_PREFIX:()=>G,CloudOpenAIError:()=>w,CloudStoragePathError:()=>b,DEFAULT_SIGNED_URL_TTL_SECONDS:()=>Re,LlmModule:()=>J,MAX_SIGNED_URL_TTL_SECONDS:()=>Ue,PUBLISHABLE_KEY_HEADER:()=>Ie,RUNTIME_STORAGE_BUCKET:()=>Q,WorkBuddyCloudClient:()=>be,WorkBuddyCloudConfigError:()=>$,WorkBuddyDatabaseModule:()=>ne,WorkBuddyStorageBucket:()=>Z,WorkBuddyStorageDownload:()=>ye,WorkBuddyStorageModule:()=>ge,anonymousTokenProvider:()=>xe,createMemoryStorage:()=>Ne,createWorkBuddyCloud:()=>Pt,getModelCapability:()=>qe,getModelDisplayName:()=>Be,shouldClearCredentials:()=>$t});var $=class extends Error{static{i(this,"WorkBuddyCloudConfigError")}constructor(e){super(e),this.name="WorkBuddyCloudConfigError"}};var Lt=/^wbpk_/;function Ge(r,e){if(typeof r!="string"||r.trim()==="")throw new $(`${e} is required and must be a non-empty string.`);let t=r.trim(),s;try{s=new URL(t)}catch{throw new $(`${e} must be an absolute URL, received: ${t}`)}if(s.protocol!=="https:"&&s.protocol!=="http:")throw new $(`${e} must use http(s), received protocol: ${s.protocol}`);return t.replace(/\/+$/,"")}i(Ge,"normalizeHttpUrl");function Nt(r){if(r!=null&&r!=="")return Ge(r,"endpoint");let e=globalThis.location?.origin;if(typeof e!="string"||e==="")throw new $("endpoint is required outside browsers (no location.origin to fall back to).");return e.replace(/\/+$/,"")}i(Nt,"resolveEndpoint");function Dt(r){if(typeof r!="string"||r.trim()==="")throw new $("publishableKey is required and must be a non-empty string.");let e=r.trim();if(!Lt.test(e))throw new $('publishableKey must start with "wbpk_".');return e}i(Dt,"normalizePublishableKey");function jt(r){if(r)return r;if(typeof globalThis.fetch!="function")throw new $("Global fetch is unavailable in this runtime; pass options.fetch explicitly.");return globalThis.fetch.bind(globalThis)}i(jt,"resolveFetch");function Ke(r){if(!r||typeof r!="object")throw new $("createWorkBuddyCloud requires oauthRelayBaseUrl and publishableKey.");return Object.freeze({endpoint:Nt(r.endpoint),oauthRelayBaseUrl:Ge(r.oauthRelayBaseUrl,"oauthRelayBaseUrl"),publishableKey:Dt(r.publishableKey),fetch:jt(r.fetch)})}i(Ke,"resolveRuntimeConfig");var Ie="x-wb-webapp-access-key";function Ce(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(Ce,"createCloudFetch");var xe=i(()=>Promise.resolve(void 0),"anonymousTokenProvider");var G="/.cloud",U=Object.freeze({auth:`${G}/auth`,database:`${G}/database/rest`,storage:`${G}/storage`,llm:`${G}/llm`});var T={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 Le(r,e){let t=r??{},s=typeof t.access_token=="string"?t.access_token:"";if(!s)throw Ft("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:Bt(t)}}i(Le,"parseSession");function Bt(r){let e=r.is_anonymous===!0;return{id:typeof r.sub=="string"?r.sub:"",isAnonymous:e,raw:r}}i(Bt,"userFromSessionPayload");function We(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:F(e.email)??F(s.email),phone:F(e.phone_number)??F(e.phone),isAnonymous:e.is_anonymous===!0||e.scope==="anonymous",raw:e}}i(We,"parseUser");function F(r){return typeof r=="string"&&r!==""?r:void 0}i(F,"pickString");function Je(r,e){let t=e??{},s=typeof t.error=="string"?t.error:void 0,n=F(t.error_description)??F(t.message)??F(t.msg)??`HTTP ${r}`;return{kind:qt(r,s),message:n,status:r,code:s,cause:e}}i(Je,"normalizeHttpError");function qt(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(qt,"errorKind");function ee(r){return{kind:"network",message:`request failed before a response was received: ${r instanceof Error?r.message:String(r)}`,status:0,cause:r}}i(ee,"normalizeNetworkError");function Ft(r){let e=new Error(`workbuddy-cloud auth: ${r}`);return e.kind="unknown",e.status=0,e}i(Ft,"sessionShapeError");var Se=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 Mt="workbuddy-cloud.session.";function Ne(){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(Ne,"createMemoryStorage");function Xe(r){if(r)return r;try{let e="__workbuddy_probe__";return globalThis.localStorage.setItem(e,"1"),globalThis.localStorage.removeItem(e),globalThis.localStorage}catch{return Ne()}}i(Xe,"resolveStorage");var Te=class{static{i(this,"SessionStore")}storage;key;constructor(e,t){this.storage=e,this.key=Mt+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 Ht(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 Ht(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(Ht,"isStoredSession");var K=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}${U.auth}`,this.oauthRelayBaseUrl=e.oauthRelayBaseUrl,this.storage=Xe(s.storage),this.sessions=new Se({store:new Te(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)&&Ye(n),"isCredentialsRejected")})}async getAccessToken(){return(await this.sessions.ensure())?.accessToken}async signInWithPassword(e){return!e.email||!e.password?f(x("signInWithPassword requires email and password")):this.postForSession(T.signIn,{username:e.email,password:e.password})}async signUp(e){if(!e.email)return f(x("signUp requires email"));if(!e.verificationToken)return f(x("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(T.signUp,t)}async sendOtp(e){if(!e.email)return f(x("sendOtp requires email"));let t={email:e.email,usage:"EMAIL"};e.emailRedirectTo&&(t.email_redirect_to=e.emailRedirectTo);let s=await this.request(T.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(x("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(x("verifyOtp requires verificationId, token and email"));let t=await this.request(T.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(T.signIn,{username:e.email,verification_token:n}):this.signUp({email:e.email,password:e.password??"",verificationToken:n}):f(x("provider returned no verification_token"))}async signInWithOAuth(e){if(e.provider!=="google")return f(x("signInWithOAuth currently supports only google"));let t=e.redirectTo??zt();return t?this.startRelayOAuth(e,t):f(x("signInWithOAuth requires redirectTo outside a browser environment"))}async handleOAuthCallback(e){let t=e??Gt(),s=t;try{/^https?:\/\//i.test(t)&&(s=new URL(t).search)}catch{return f(x("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")??"",h=n.get("provider_id");if(h!=="custom-oauth")return f(x("oauth callback requires provider_id=custom-oauth"));if(!c)return f(x("oauth callback requires state"));let u={provider_id:h,provider_code:o,state:c,provider_params:{state:c}};return this.postForSession(T.signInWithProvider,u)}async resetPasswordForEmail(e){if(!e)return f(x("resetPasswordForEmail requires email"));let t=await this.request(T.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(T.verificationVerify,{method:"POST",body:{verification_id:n,verification_code:a}});if(c.error)return f(c.error);let h=c.data??{},u=typeof h.verification_token=="string"?h.verification_token:"";if(!u)return f(x("provider returned no verification_token"));let l=await this.request(T.resetPassword,{method:"POST",body:{email:e,new_password:o,verification_token:u}});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(x("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(T.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(x("provider returned no sudo_token"));let o=await this.request(T.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:ee(e))}}async refreshSession(){try{return _(await this.sessions.forceRefresh())}catch(e){return f(Ee(e)?e:ee(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(T.userMe,{method:"GET",token:e});return t.error?(Ye(t.error)&&this.sessions.clear(),f(t.error)):_(We(t.data))}async signOut(){let e=this.sessions.peek();return e?.accessToken&&await this.request(T.signOut,{method:"POST",body:{},token:e.accessToken}),this.sessions.clear(),_(null)}onAuthStateChange(e){let t=this.nextListenerId++;return this.listeners.set(t,e),Qe(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(T.token,{method:"POST",body:{grant_type:"refresh_token",refresh_token:e}});if(t.error)throw t.error;return Le(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(Le(n.data,Date.now())))}catch(a){return f(Ee(a)?a:ee(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(ee(o))}let a=await Vt(n);return n.ok?_(a):f(Je(n.status,a))}notify(e,t){for(let s of this.listeners.values())Qe(s,e,t)}};function _(r){return{data:r,error:null}}i(_,"ok");function f(r){return{data:null,error:r}}i(f,"fail");function x(r){return{kind:"invalid-request",message:r,status:0}}i(x,"badRequest");function Ee(r){return!!r&&typeof r=="object"&&typeof r.kind=="string"}i(Ee,"isCloudError");function Ye(r){return r.kind==="unauthenticated"||r.code==="invalid_grant"}i(Ye,"rejectedCredentials");async function Vt(r){let e=await r.text();if(!e)return null;try{return JSON.parse(e)}catch{return{message:e}}}i(Vt,"readBody");function Qe(r,e,t){try{r(e,t)}catch{}}i(Qe,"safeInvoke");function zt(){let r=globalThis.location;return r?r.origin+r.pathname:""}i(zt,"currentPageUrl");function Gt(){return globalThis.location?.search??""}i(Gt,"currentPageSearch");var De=i(r=>Math.min(1e3*2**r,3e4),"getRetryDelay"),Ze=[520,503],je=["GET","HEAD","OPTIONS"];var M=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 et(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(et,"sleep");function Kt(r,e,t,s){return!(!s||t>=3||!je.includes(r)||!Ze.includes(e))}i(Kt,"shouldRetry");var te=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((u,l)=>{c[l]=u}),o>0&&(c["X-Retry-Count"]=String(o));let h;try{h=await s(this.url.toString(),{method:this.method,headers:c,body:JSON.stringify(this.body,(u,l)=>typeof l=="bigint"?l.toString():l),signal:this.signal})}catch(u){if(u?.name==="AbortError"||u?.code==="ABORT_ERR"||!je.includes(this.method))throw u;if(this.retryEnabled&&o<3){let l=De(o);o++,await et(l,this.signal);continue}throw u}if(Kt(this.method,h.status,o,this.retryEnabled)){let u=h.headers?.get("Retry-After")??null,l=u!==null?Math.max(0,parseInt(u,10)||0)*1e3:De(o);await h.text(),o++,await et(l,this.signal);continue}return await this.processResponse(h)}},"executeWithRetry")();return this.shouldThrowOnError||(a=a.catch(o=>{let c="",h="",u="",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"?(u="",h="Request was aborted (timeout or manual cancellation)",d>this.urlLengthLimit&&(h+=`. 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")&&(u="",h="HTTP headers exceeded server limits (typically 16KB)",d>this.urlLengthLimit&&(h+=`. 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:h,code:u},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 u=await e.text();if(u!=="")if(this.headers.get("Accept")==="text/csv")s=u;else if(this.headers.get("Accept")&&this.headers.get("Accept")?.includes("application/vnd.pgrst.plan+text"))s=u;else try{s=JSON.parse(u)}catch{if(t={message:u},s=null,this.shouldThrowOnError)throw new M({message:u,details:"",hint:"",code:""})}}let c=this.headers.get("Prefer")?.match(/count=(exact|planned|estimated)/),h=e.headers.get("content-range")?.split("/");if(c&&h&&h.length>1&&(n=parseInt(h[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 M({...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 M(t)}return{success:t===null,error:t,data:s,count:n,status:a,statusText:o}}returns(){return this}overrideTypes(){return this}};var re=class extends te{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("|"),h=this.headers.get("Accept")??"application/json";return this.headers.set("Accept",`application/vnd.pgrst.plan+${o}; for="${h}"; 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 rt=new RegExp("[,()]"),A=class extends re{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"&&rt.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"&&rt.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 se=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:h,headers:u}=this.cloneRequestState();return h.searchParams.set("select",c),n&&u.append("Prefer",`count=${n}`),new A({method:a,url:h,headers:u,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((h,u)=>h.concat(Object.keys(u)),[]);if(c.length>0){let h=[...new Set(c)].map(u=>`"${u}"`);a.searchParams.set("columns",h.join(","))}}return new A({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:h}=this.cloneRequestState();if(h.append("Prefer",`resolution=${s?"ignore":"merge"}-duplicates`),t!==void 0&&c.searchParams.set("on_conflict",t),n&&h.append("Prefer",`count=${n}`),a||h.append("Prefer","missing=default"),Array.isArray(e)){let u=e.reduce((l,d)=>l.concat(Object.keys(d)),[]);if(u.length>0){let l=[...new Set(u)].map(d=>`"${d}"`);c.searchParams.set("columns",l.join(","))}}return new A({method:o,url:c,headers:h,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 A({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 A({method:t,url:s,headers:n,schema:this.schema,fetch:this.fetch??fetch,urlLengthLimit:this.urlLengthLimit,retry:this.retry})}};var W=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 h=n??globalThis.fetch;a!==void 0&&a>0?this.fetch=(u,l)=>{let d=new AbortController,m=setTimeout(()=>d.abort(),a),p=l?.signal;if(p){if(p.aborted)return clearTimeout(m),h(u,l);let R=i(()=>{clearTimeout(m),d.abort()},"abortHandler");return p.addEventListener("abort",R,{once:!0}),h(u,{...l,signal:d.signal}).finally(()=>{clearTimeout(m),p.removeEventListener("abort",R)})}return h(u,{...l,signal:d.signal}).finally(()=>clearTimeout(m))}:this.fetch=h,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 se(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}`),h,u=i(m=>m!==null&&typeof m=="object"&&(!Array.isArray(m)||m.some(u)),"_isObject"),l=s&&Object.values(t).some(u);l?(o="POST",h=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",h=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 A({method:o,url:c,headers:d,schema:this.schemaName,body:h,fetch:this.fetch??fetch,urlLengthLimit:this.urlLengthLimit,retry:this.retry})}};var ne=class{static{i(this,"WorkBuddyDatabaseModule")}client;constructor(e,t){this.client=new W(`${e.endpoint}${U.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 st(r,e){return new ne(r,e)}i(st,"createDatabaseModule");var w=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 nt(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(nt,"parseRetryAfter");function y(...r){return r.find(e=>typeof e=="string"&&e.length>0)}i(y,"stringField");function g(...r){return r.find(e=>typeof e=="number"&&Number.isFinite(e))}i(g,"numberField");function E(...r){return r.find(e=>typeof e=="boolean")}i(E,"booleanField");function at(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(at,"modalitiesField");function it(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(it,"capabilitiesField");function ot(r){if(!r||typeof r!="object")return;let e=r,t={...y(e.currency)?{currency:e.currency}:{},...g(e.inputPerMillionTokens)!==void 0?{inputPerMillionTokens:e.inputPerMillionTokens}:{},...g(e.outputPerMillionTokens)!==void 0?{outputPerMillionTokens:e.outputPerMillionTokens}:{},...y(e.displayText)?{displayText:e.displayText}:{}};return Object.keys(t).length?t:void 0}i(ot,"pricingField");function ct(r){if(!r||typeof r!="object")return;let e=r,t={},s=y(e.effort);s!==void 0&&(t.effort=s);let n=y(e.defaultEffort);n!==void 0&&(t.defaultEffort=n),Array.isArray(e.supportedEfforts)&&(t.supportedEfforts=e.supportedEfforts.filter(c=>typeof c=="string"));let a=y(e.summary);a!==void 0&&(a==="auto"||a==="concise"||a==="detailed")&&(t.summary=a);let o=E(e.canDisableThinking);return o!==void 0&&(t.canDisableThinking=o),Object.keys(t).length>0?t:void 0}i(ct,"reasoningField");function Wt(r){let e=y(r.id,r.ID);if(!e)return null;let t=E(r.enabled,r.Enabled),s=E(r.disabled,r.Disabled),n,a;return t!==void 0?(n=t,s!==void 0&&(a=s)):s!==void 0?(a=s,n=!s):n=!0,{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)}:{},...g(r.contextWindow,r.ContextWindow)!==void 0?{contextWindow:g(r.contextWindow,r.ContextWindow)}:{},...g(r.maxInputTokens,r.MaxInputTokens)!==void 0?{maxInputTokens:g(r.maxInputTokens,r.MaxInputTokens)}:{},...g(r.maxOutputTokens,r.MaxOutputTokens)!==void 0?{maxOutputTokens:g(r.maxOutputTokens,r.MaxOutputTokens)}:{},...at(r.modalities??r.Modalities)?{modalities:at(r.modalities??r.Modalities)}:{},...it(r.capabilities??r.Capabilities)?{capabilities:it(r.capabilities??r.Capabilities)}:{},enabled:n,...a!==void 0?{disabled:a}:{},...E(r.isDefault,r.IsDefault)!==void 0?{isDefault:E(r.isDefault,r.IsDefault)}:{},...g(r.sortOrder,r.SortOrder)!==void 0?{sortOrder:g(r.sortOrder,r.SortOrder)}:{},...ot(r.pricing??r.Pricing)?{pricing:ot(r.pricing??r.Pricing)}:{},...y(r.credits,r.Credits)?{credits:y(r.credits,r.Credits)}:{},...g(r.maxAllowedSize,r.MaxAllowedSize)!==void 0?{maxAllowedSize:g(r.maxAllowedSize,r.MaxAllowedSize)}:{},...E(r.disabledMultimodal,r.DisabledMultimodal)!==void 0?{disabledMultimodal:E(r.disabledMultimodal,r.DisabledMultimodal)}:{},...E(r.supportsImages,r.SupportsImages)!==void 0?{supportsImages:E(r.supportsImages,r.SupportsImages)}:{},...E(r.supportsToolCall,r.SupportsToolCall)!==void 0?{supportsToolCall:E(r.supportsToolCall,r.SupportsToolCall)}:{},...E(r.supportsReasoning,r.SupportsReasoning)!==void 0?{supportsReasoning:E(r.supportsReasoning,r.SupportsReasoning)}:{},...E(r.onlyReasoning,r.OnlyReasoning)!==void 0?{onlyReasoning:E(r.onlyReasoning,r.OnlyReasoning)}:{},...ct(r.reasoning??r.Reasoning)?{reasoning:ct(r.reasoning??r.Reasoning)}:{},...g(r.temperature,r.Temperature)!==void 0?{temperature:g(r.temperature,r.Temperature)}:{},...g(r.top_k,r.Top_K)!==void 0?{top_k:g(r.top_k,r.Top_K)}:{},...g(r.top_p,r.Top_P)!==void 0?{top_p:g(r.top_p,r.Top_P)}:{},...g(r.repetition_penalty,r.Repetition_Penalty)!==void 0?{repetition_penalty:g(r.repetition_penalty,r.Repetition_Penalty)}:{}}}i(Wt,"normalizeModel");function Be(r){return r.name||r.id}i(Be,"getModelDisplayName");function qe(r,e){return r.capabilities?.[e]}i(qe,"getModelCapability");var Oe=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 w({message:`Network error: ${c?.message??"unknown"}`,type:"server_error",param:null,code:"gateway_network_error"},{cause:c})}if(!t.ok)throw await Fe(t);let s=await t.text(),n;try{n=JSON.parse(s)}catch{throw new w({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 h=Wt(c);h&&o.push(h)}return o}};async function Fe(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=nt(r.headers.get("retry-after"));return new w(t,{status:r.status,requestId:s,retryAfterMs:n})}i(Fe,"httpError");var Jt=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}},Xt=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]:[]}},ut="[DONE]";async function*ht(r,e){let t=new Jt,s=new Xt,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 h;try{h=await n.read()}catch(d){if(a||d instanceof Error&&d.name==="AbortError")return;throw d}let{done:u,value:l}=h;if(u)break;for(let d of s.decode(l)){let m=t.decode(d);m&&(yield m)}}for(let h of s.flush()){let u=t.decode(h);u&&(yield u)}let c=t.flush();c&&(yield c)}finally{e&&e.removeEventListener("abort",o);try{n.releaseLock()}catch{}}}i(ht,"iterSSEEvents");function Yt(r,e){let t=e?{requestId:e}:{};try{let s=JSON.parse(r);if(s&&typeof s=="object"){let n=s.error??s;if(n&&typeof n=="object")return new w({message:typeof n.message=="string"?n.message:"Stream error",type:typeof n.type=="string"?n.type:"server_error",param:n.param===void 0?null:n.param,code:n.code===void 0?null:n.code},t)}}catch{}return new w({message:r||"Stream error",type:"server_error",param:null,code:null},t)}i(Yt,"extractSSEError");var ve=class{static{i(this,"ChatCompletionsAPI")}baseUrl;fetch;constructor(e,t){this.baseUrl=e,this.fetch=t}create(e){if(e.stream!==!0)throw new w({message:"stream must be true; non-streaming chat completions are not supported",type:"invalid_request_error",param:"stream",code:"request_stream_required"});return this.createStreaming(e)}async*createStreaming(e){let{signal:t,conversationId:s,...n}=e;n.stream=!0;let a;try{a=await this.fetch(`${this.baseUrl}/chat/completions`,{method:"POST",headers:{Accept:"text/event-stream","Content-Type":"application/json",...s!==void 0?{"X-Conversation-ID":s}:{}},body:JSON.stringify(n),signal:t})}catch(u){if(u instanceof Error&&u.name==="AbortError")return;throw new w({message:`Network error: ${u?.message??"unknown"}`,type:"server_error",param:null,code:"gateway_network_error"},{cause:u})}if(!a.ok)throw await Fe(a);if(!a.body)throw new w({message:"Response body is empty \u2014 streaming not supported",type:"server_error",param:null,code:"gateway_invalid_response"},{requestId:a.headers.get("x-request-id")??void 0});let o=a.headers.get("x-request-id")??void 0,c=!1,h=!1;try{for await(let u of ht(a.body,t)){if(u.event==="error")throw h=!0,Yt(u.data,o);if(u.event===null||u.event===""){if(u.data===ut){c=!0;return}if(!u.data)continue;let l;try{l=JSON.parse(u.data)}catch{throw h=!0,new w({message:`Failed to parse SSE data: ${u.data}`,type:"server_error",param:null,code:"gateway_invalid_response"},{requestId:o})}if(l&&typeof l=="object"&&"error"in l){h=!0;let d=l.error;throw new w({message:typeof d?.message=="string"?d.message:"Stream error",type:typeof d?.type=="string"?d.type:"server_error",param:d?.param===void 0?null:d.param,code:d?.code===void 0?null:d.code},{requestId:o})}yield l}}}catch(u){if(u instanceof Error&&u.name==="AbortError")return;throw h=!0,u}if(!c&&!h&&!t?.aborted)throw new w({message:"\u6D41\u5F0F\u54CD\u5E94\u4E2D\u65AD\u3002",type:"server_error",param:null,code:"gateway_stream_interrupted"},{requestId:o})}};var J=class{static{i(this,"LlmModule")}fetch;baseUrl;models;chat;constructor(e,t){this.fetch=t,this.baseUrl=`${e.endpoint}${U.llm}`,this.models=new Oe(this.baseUrl,this.fetch),this.chat={completions:new ve(this.baseUrl,this.fetch)}}};var C=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 C{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}}},X=class extends C{static{i(this,"StorageUnknownError")}originalError;constructor(e,t,s="storage"){super(e,s),this.name=s==="vectors"?"StorageVectorsUnknownError":"StorageUnknownError",this.originalError=t}};function V(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(V,"setHeader");function lt(r){let e={};for(let[t,s]of Object.entries(r))e[t.toLowerCase()]=s;return e}i(lt,"normalizeHeaders");var dt=i(r=>r?(...e)=>r(...e):(...e)=>fetch(...e),"resolveFetch");var ft=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"),pt=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 Pe=i(r=>r.split("/").map(encodeURIComponent).join("/"),"encodeStoragePath");var mt=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"),Qt=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 h=c?.statusCode||c?.code||o+"";e(new H(mt(c),o,h,s,c?.code))}).catch(()=>{let c=o+"",h=a.statusText||`HTTP ${o} error`;e(new H(h,o,c,s))})}else e(new X(mt(r),r,s))},"handleError"),Zt=i((r,e,t,s)=>{let n={method:r,headers:e?.headers||{}};if(r==="GET"||r==="HEAD"||!s)return{...n,...t};if(ft(s)){let a=e?.headers||{},o;for(let[c,h]of Object.entries(a))c.toLowerCase()==="content-type"&&(o=h);n.headers=V(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 ae(r,e,t,s,n,a,o){return new Promise((c,h)=>{r(t,Zt(e,s,n,a)).then(u=>{if(!u.ok)throw u;if(s?.noResolveJson)return u;if(o==="vectors"){let l=u.headers.get("content-type");if(u.headers.get("content-length")==="0"||u.status===204)return{};if(!l||!l.includes("application/json"))return{}}return u.json()}).then(u=>c(u)).catch(u=>Qt(u,h,s,o))})}i(ae,"_handleRequest");function yt(r="storage"){return{get:i(async(e,t,s,n)=>ae(e,"GET",t,s,n,void 0,r),"get"),post:i(async(e,t,s,n,a)=>ae(e,"POST",t,n,a,s,r),"post"),put:i(async(e,t,s,n,a)=>ae(e,"PUT",t,n,a,s,r),"put"),head:i(async(e,t,s,n)=>ae(e,"HEAD",t,{...s,noResolveJson:!0},n,void 0,r),"head"),remove:i(async(e,t,s,n,a)=>ae(e,"DELETE",t,n,a,s,r),"remove")}}i(yt,"createFetchApi");var er=yt("storage"),{get:N,post:k,put:ie,head:gt,remove:D}=er,S=yt("vectors");var O=class{static{i(this,"BaseApiClient")}url;headers;fetch;shouldThrowOnError=!1;namespace;constructor(e,t={},s,n="storage"){this.url=e,this.headers=lt(t),this.fetch=dt(s),this.namespace=n}throwOnError(){return this.shouldThrowOnError=!0,this}setHeader(e,t){return this.headers=V(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 oe=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 ce=class{static{i(this,"BlobDownloadBuilder")}downloadFn;shouldThrowOnError;[Symbol.toStringTag]="BlobDownloadBuilder";promise=null;constructor(e,t){this.downloadFn=e,this.shouldThrowOnError=t}asStream(){return new oe(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 Me={limit:100,offset:0,sortBy:{column:"name",order:"asc"}},bt={cacheControl:"3600",contentType:"text/plain;charset=UTF-8",upsert:!1},ue=class extends O{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={...bt,...n},c={...this.headers,...e==="POST"&&{"x-upsert":String(o.upsert)}},h=o.metadata;if(typeof Blob<"u"&&s instanceof Blob?(a=new FormData,a.append("cacheControl",o.cacheControl),h&&a.append("metadata",this.encodeMetadata(h)),a.append("",s)):typeof FormData<"u"&&s instanceof FormData?(a=s,a.has("cacheControl")||a.append("cacheControl",o.cacheControl),h&&!a.has("metadata")&&a.append("metadata",this.encodeMetadata(h))):(a=s,c["cache-control"]=`max-age=${o.cacheControl}`,c["content-type"]=o.contentType,h&&(c["x-metadata"]=this.toBase64(this.encodeMetadata(h))),(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=V(c,m,p);let u=this._removeEmptyFolders(t),l=this._getFinalPath(u),d=await(e=="PUT"?ie:k)(this.fetch,`${this.url}/object/${l}`,a,{headers:c,...o?.duplex?{duplex:o.duplex}:{}});return{path:u,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 h,u={...bt,...n},l={...this.headers,"x-upsert":String(u.upsert)},d=u.metadata;if(typeof Blob<"u"&&s instanceof Blob?(h=new FormData,h.append("cacheControl",u.cacheControl),d&&h.append("metadata",this.encodeMetadata(d)),h.append("",s)):typeof FormData<"u"&&s instanceof FormData?(h=s,h.has("cacheControl")||h.append("cacheControl",u.cacheControl),d&&!h.has("metadata")&&h.append("metadata",this.encodeMetadata(d))):(h=s,l["cache-control"]=`max-age=${u.cacheControl}`,l["content-type"]=u.contentType,d&&(l["x-metadata"]=this.toBase64(this.encodeMetadata(d))),(typeof ReadableStream<"u"&&h instanceof ReadableStream||h&&typeof h=="object"&&"pipe"in h&&typeof h.pipe=="function")&&!u.duplex&&(u.duplex="half")),n?.headers)for(let[p,R]of Object.entries(n.headers))l=V(l,p,R);let m=await ie(this.fetch,c.toString(),h,{headers:l,...u?.duplex?{duplex:u.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 k(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 C("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 k(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 k(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 k(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 h=c.toString();return{signedUrl:encodeURI(`${this.url}${o.signedURL}${h?`&${h}`:""}`)}})}async createSignedUrls(e,t,s){return this.handleOperation(async()=>{let n=await k(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(),h=this._getFinalPath(e),u=i(()=>N(this.fetch,`${this.url}/${a}/${h}${c?`?${c}`:""}`,{headers:this.headers,noResolveJson:!0},s),"downloadFn");return new ce(u,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 gt(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 X?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 D(this.fetch,`${this.url}/object/${this.bucketId}`,{prefixes:e},{headers:this.headers}))}async purgeCache(e,t,s){return this.handleOperation(async()=>{let n=Pe(this._getFinalPath(e)),a=new URLSearchParams;t?.transformations&&a.set("transformations","true");let o=a.toString();return await D(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?{...Me.sortBy,...t.sortBy}:Me.sortBy,a={...Me,...t,sortBy:n,prefix:e||""};return await k(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 k(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 wt="2.112.3";var I={"X-Client-Info":`storage-js/${wt}`};var he=class extends O{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={...I,...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 k(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 ie(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 k(this.fetch,`${this.url}/bucket/${e}/empty`,{},{headers:this.headers}))}async deleteBucket(e){return this.handleOperation(async()=>await D(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 D(this.fetch,`${this.url}/cdn/${Pe(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 q=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 tr(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(tr,"buildUrl");async function rr(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(rr,"buildAuthHeaders");function sr(r){let e=r.fetchImpl??globalThis.fetch;return{async request({method:t,path:s,query:n,body:a,headers:o}){let c=tr(r.baseUrl,s,n),h=await rr(r.auth),u;try{u=await e(c,{method:t,headers:{...a?{"Content-Type":"application/json"}:{},...h,...o},body:a?JSON.stringify(a):void 0})}catch(p){if(p instanceof q)throw p;let R=p instanceof Error?p.message:String(p);throw new q(`Network request failed: ${R}`,{status:0,details:p})}if(u.status===304)return{status:304,headers:u.headers,data:void 0};let l=await u.text(),d=(u.headers.get("content-type")||"").includes("application/json"),m=d&&l?JSON.parse(l):l;if(!u.ok){let p=d?m:void 0,R=p?.error;throw new q(R?.message??`Request failed with status ${u.status}`,{status:u.status,icebergType:R?.type,icebergCode:R?.code,details:p})}return{status:u.status,headers:u.headers,data:m}}}}i(sr,"createFetchClient");function B(){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 ar(t),e.set(t,6),e[6]=e[6]&15|112,e[8]=e[8]&63|128,nr(e)}i(B,"generateIdempotencyKey");function nr(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(nr,"formatUUID");function ar(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(ar,"cryptoRandom");function $e(r){return r.map(encodeURIComponent).join("%1F")}i($e,"namespaceToPath");function ir(r){return r.join("")}i(ir,"namespaceToParentQuery");async function Y(r){return typeof r=="string"?r:r()}i(Y,"resolvePrefix");var or=class{static{i(this,"NamespaceOperations")}constructor(r,e=""){this.client=r,this.prefix=e}async listNamespaces(r={}){let e=await Y(this.prefix),t={};r.parent&&(t.parent=ir(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 Y(this.prefix),s={namespace:r.namespace,properties:e?.properties};return(await this.client.request({method:"POST",path:`${t}/namespaces`,body:s,headers:{"Idempotency-Key":B()}})).data}async dropNamespace(r){let e=await Y(this.prefix);await this.client.request({method:"DELETE",path:`${e}/namespaces/${$e(r.namespace)}`,headers:{"Idempotency-Key":B()}})}async loadNamespaceMetadata(r){let e=await Y(this.prefix);return{properties:(await this.client.request({method:"GET",path:`${e}/namespaces/${$e(r.namespace)}`})).data.properties??{}}}async namespaceExists(r){let e=await Y(this.prefix);try{return await this.client.request({method:"HEAD",path:`${e}/namespaces/${$e(r.namespace)}`}),!0}catch(t){if(t instanceof q&&t.status===404)return!1;throw t}}async updateNamespaceProperties(r,e){let t=await Y(this.prefix);return(await this.client.request({method:"POST",path:`${t}/namespaces/${$e(r.namespace)}/properties`,body:e,headers:{"Idempotency-Key":B()}})).data}async createNamespaceIfNotExists(r,e){try{return await this.createNamespace(r,e)}catch(t){if(t instanceof q&&t.status===409)return;throw t}}};function z(r){return r.map(encodeURIComponent).join("%1F")}i(z,"namespaceToPath2");function _e(r){return encodeURIComponent(r)}i(_e,"tableSegment");async function j(r){return typeof r=="string"?r:r()}i(j,"resolvePrefix2");var cr=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/${z(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":B()};this.accessDelegation&&(s["X-Iceberg-Access-Delegation"]=this.accessDelegation);let n=await this.client.request({method:"POST",path:`${t}/namespaces/${z(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/${z(r.namespace)}/tables/${_e(r.name)}`,body:e,headers:{"Idempotency-Key":B()}}),n=s.data["metadata-location"];if(!n)throw new q("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/${z(r.namespace)}/tables/${_e(r.name)}`,query:{purgeRequested:String(e?.purge??!1)},headers:{"Idempotency-Key":B()}})}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/${z(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/${z(r.namespace)}/tables/${_e(r.name)}`,headers:t}),!0}catch(s){if(s instanceof q&&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":B()};this.accessDelegation&&(s["X-Iceberg-Access-Delegation"]=this.accessDelegation);let n=await this.client.request({method:"POST",path:`${t}/namespaces/${z(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":B()}})}async createTableIfNotExists(r,e){try{return await this.createTable(r,e)}catch(t){if(t instanceof q&&t.status===409)return await this.loadTable({namespace:r.namespace,name:e.name});throw t}}},xt=class{static{i(this,"IcebergRestCatalog")}constructor(r){let e=r.baseUrl.endsWith("/")?r.baseUrl:`${r.baseUrl}/`;this.warehouse=r.warehouse??r.catalogName,this.client=sr({baseUrl:e,auth:r.auth,fetchImpl:r.fetch}),this.accessDelegation=r.accessDelegation?.join(",");let t=i(()=>this.resolvePrefix(),"getPrefix");this.namespaceOps=new or(this.client,t),this.tableOps=new cr(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 St={tag:"apache-iceberg-1.11.0-rc1"},dn=St.tag,fn=`https://raw.githubusercontent.com/apache/iceberg/${St.tag}/open-api/rest-catalog-open-api.yaml`;var le=class extends O{static{i(this,"StorageAnalyticsClient")}constructor(e,t={},s){let n=e.replace(/\/$/,""),a={...I,...t};super(n,a,s,"storage")}async createBucket(e){return this.handleOperation(async()=>await k(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 D(this.fetch,`${this.url}/bucket/${e}`,{},{headers:this.headers}))}from(e){if(!pt(e))throw new C("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 xt({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(...h)=>{try{return{data:await c.apply(a,h),error:null}}catch(u){if(s)throw u;return{data:null,error:u}}}}})}};var de=class extends O{static{i(this,"VectorIndexApi")}constructor(e,t={},s){let n=e.replace(/\/$/,""),a={...I,"Content-Type":"application/json",...t};super(n,a,s,"vectors")}async createIndex(e){return this.handleOperation(async()=>await S.post(this.fetch,`${this.url}/CreateIndex`,e,{headers:this.headers})||{})}async getIndex(e,t){return this.handleOperation(async()=>await S.post(this.fetch,`${this.url}/GetIndex`,{vectorBucketName:e,indexName:t},{headers:this.headers}))}async listIndexes(e){return this.handleOperation(async()=>await S.post(this.fetch,`${this.url}/ListIndexes`,e,{headers:this.headers}))}async deleteIndex(e,t){return this.handleOperation(async()=>await S.post(this.fetch,`${this.url}/DeleteIndex`,{vectorBucketName:e,indexName:t},{headers:this.headers})||{})}};var fe=class extends O{static{i(this,"VectorDataApi")}constructor(e,t={},s){let n=e.replace(/\/$/,""),a={...I,"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 S.post(this.fetch,`${this.url}/PutVectors`,e,{headers:this.headers})||{})}async getVectors(e){return this.handleOperation(async()=>await S.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 S.post(this.fetch,`${this.url}/ListVectors`,e,{headers:this.headers}))}async queryVectors(e){return this.handleOperation(async()=>await S.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 S.post(this.fetch,`${this.url}/DeleteVectors`,e,{headers:this.headers})||{})}};var pe=class extends O{static{i(this,"VectorBucketApi")}constructor(e,t={},s){let n=e.replace(/\/$/,""),a={...I,"Content-Type":"application/json",...t};super(n,a,s,"vectors")}async createBucket(e){return this.handleOperation(async()=>await S.post(this.fetch,`${this.url}/CreateVectorBucket`,{vectorBucketName:e},{headers:this.headers})||{})}async getBucket(e){return this.handleOperation(async()=>await S.post(this.fetch,`${this.url}/GetVectorBucket`,{vectorBucketName:e},{headers:this.headers}))}async listBuckets(e={}){return this.handleOperation(async()=>await S.post(this.fetch,`${this.url}/ListVectorBuckets`,e,{headers:this.headers}))}async deleteBucket(e){return this.handleOperation(async()=>await S.post(this.fetch,`${this.url}/DeleteVectorBucket`,{vectorBucketName:e},{headers:this.headers})||{})}};var Ae=class extends pe{static{i(this,"StorageVectorsClient")}constructor(e,t={}){super(e,t.headers||{},t.fetch)}from(e){return new He(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)}},He=class extends de{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 Ve(this.url,this.headers,this.vectorBucketName,e,this.fetch)}},Ve=class extends fe{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 me=class extends he{static{i(this,"StorageClient")}constructor(e,t={},s,n){super(e,t,s,n)}from(e){return new ue(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 le(this.url+"/iceberg",this.headers,this.fetch)}};var Q="runtime",Re=600,Ue=3600,b=class extends Error{static{i(this,"CloudStoragePathError")}constructor(e){super(e),this.name="CloudStoragePathError"}},ye=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)}},Z=class{static{i(this,"WorkBuddyStorageBucket")}fileApi;constructor(e){this.fileApi=e}upload(e,t,s){return P(this.fileApi.upload(v(e),t,s))}update(e,t,s){return P(this.fileApi.update(v(e),t,s))}list(e="",t){return P(this.fileApi.list(Et(e),t))}listPage(e){return P(this.fileApi.listV2({...e,prefix:Et(e?.prefix??"")}))}info(e){return P(this.fileApi.info(v(e)))}async exists(e){let t=await this.fileApi.exists(v(e));return t.error?{data:null,error:kt(t.error)}:{data:t.data,error:null}}download(e){let t=this.fileApi.download(v(e));return new ye(()=>P(t),()=>P(t.asStream()))}remove(e){if(e.length===0)throw new b("remove requires at least one object path.");return P(this.fileApi.remove(e.map(v)))}copy(e,t){return P(this.fileApi.copy(v(e),v(t)))}move(e,t){return P(this.fileApi.move(v(e),v(t)))}createSignedUrl(e,t=Re){return P(this.fileApi.createSignedUrl(v(e),Ot(t)))}createSignedUrls(e,t=Re){if(e.length===0)throw new b("createSignedUrls requires at least one object path.");return P(this.fileApi.createSignedUrls(e.map(v),Ot(t)))}createSignedUploadUrl(e,t){return P(this.fileApi.createSignedUploadUrl(v(e),{upsert:t?.upsert??!1}))}uploadToSignedUrl(e,t,s,n){if(!t)throw new b("signed upload token is required.");return P(this.fileApi.uploadToSignedUrl(v(e),t,s,n))}},ge=class extends Z{static{i(this,"WorkBuddyStorageModule")}runtime;constructor(e){let s=e.from(Q);super(s),this.runtime=new Z(s)}from(e=Q){if(e!==Q)throw new b(`Only the "${Q}" storage bucket is available.`);return this.runtime}userPath(e,t){return Tt("users",e,t)}sharedPath(e,t){return Tt("shared",e,t)}};function vt(r,e){let t=new me(`${r.endpoint}${U.storage}`,{},e);return new ge(t)}i(vt,"createStorageModule");function Tt(r,e,t){let s=ur(e,"owner/user id"),n=ze(t,!1);return v(`${r}/${s}/${n}`)}i(Tt,"scopedPath");function v(r){let e=ze(r,!1);if(!e.includes("/"))throw new b("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 b("Object paths must use users/<uid>/... or shared/<ownerUid>/....");return e}i(v,"validateObjectPath");function Et(r){if(r==="")return"";let e=ze(r,!0),[t,s]=e.split("/");if(t==="shared"&&!s)return"shared";if(t!=="users"&&t!=="shared"||!s)throw new b("List prefixes must start with users/<uid> or shared/<ownerUid>.");return e}i(Et,"validateObjectPrefix");function ze(r,e){if(typeof r!="string"||r.trim()==="")throw new b("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 b("Storage path contains invalid URL encoding.")}if(t.startsWith("/")||t.includes("\\")||t.includes("\0")||t.includes("//")||!e&&t.endsWith("/"))throw new b("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 b("Storage path traversal is not allowed.");return s}i(ze,"validatePath");function ur(r,e){if(!r)throw new b(`${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 b(`${e} contains invalid URL encoding.`)}if(t.includes("/")||t.includes("\\")||t.includes("\0")||t==="."||t==="..")throw new b(`${e} is not a valid storage path segment.`);return t}i(ur,"validatePathSegment");function Ot(r){if(!Number.isInteger(r)||r<=0||r>Ue)throw new b(`Signed URL expiry must be an integer between 1 and ${Ue} seconds.`);return r}i(Ot,"validateSignedURLTTL");async function P(r){let e=await r;return e.error?{data:null,error:kt(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(P,"mapStorageResult");function kt(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(kt,"normalizeStorageError");var be=class{static{i(this,"WorkBuddyCloudClient")}config;database;auth;storage;llm;constructor(e,t={}){this.config=e,this.auth=new K(e,Ce(e,xe),{storage:t.storage});let s=Ce(e,()=>this.auth.getAccessToken());this.database=st(e,s),this.storage=vt(e,s),this.llm=new J(e,s)}get endpoint(){return this.config.endpoint}get oauthRelayBaseUrl(){return this.config.oauthRelayBaseUrl}};function Pt(r){return new be(Ke(r),{storage:r.storage})}i(Pt,"createWorkBuddyCloud");function $t(r){return r.kind==="unauthenticated"||r.code==="invalid_grant"}i($t,"shouldClearCredentials");return Ct(hr);})();
|
|
7
|
+
//# sourceMappingURL=index.global.js.map
|