@nestcorehq/js 0.9.0 → 0.10.0

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.
@@ -1,8 +1,8 @@
1
- "use strict";var NestCore=(()=>{var B=Object.defineProperty;var ye=Object.getOwnPropertyDescriptor;var fe=Object.getOwnPropertyNames;var be=Object.prototype.hasOwnProperty;var Ae=(n,e)=>{for(var t in e)B(n,t,{get:e[t],enumerable:!0})},Pe=(n,e,t,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of fe(e))!be.call(n,r)&&r!==t&&B(n,r,{get:()=>e[r],enumerable:!(s=ye(e,r))||s.enumerable});return n};var Re=n=>Pe(B({},"__esModule",{value:!0}),n);var Ve={};Ae(Ve,{AiClient:()=>q,AnalyticsClient:()=>E,AuthClient:()=>T,AuthLimitCodes:()=>he,CollectionRef:()=>L,CollectionsClient:()=>O,DatabaseClient:()=>R,EnvironmentClient:()=>S,FunctionsClient:()=>v,HttpClient:()=>P,JobsClient:()=>k,LoggingClient:()=>w,MemoryClient:()=>$,NestCoreError:()=>A,OrbitNestError:()=>ue,PresenceManager:()=>N,RealtimeChannel:()=>D,RealtimeClient:()=>C,StorageBucket:()=>j,StorageClient:()=>_,ThreadRef:()=>F,ThreadsClient:()=>I,createClient:()=>He,createLocalStorageAdapter:()=>se,createMemoryAdapter:()=>K,generateTypes:()=>ce,isMfaChallenge:()=>H,localStorageAdapter:()=>re,memoryAdapter:()=>U,sanitizePath:()=>ne,unwrap:()=>de,validatePath:()=>g,validateRequired:()=>V});var P=class{constructor(e){this.baseUrl=(e.baseUrl||"https://api.nestcore.io").replace(/\/$/,""),this.apiKey=e.apiKey,this.projectSlug=e.projectSlug,this.timeout=e.timeout||3e4,this.analyticsToken=e.analyticsToken,this.clientIp=e.clientIp}getProjectSlug(){return this.projectSlug}getBaseUrl(){return this.baseUrl}getTimeout(){return this.timeout}getApiKey(){return this.apiKey}setAccessTokenProvider(e,t){this.accessTokenProvider=e,this.tokenRefresher=t}async authHeaders(){return this.headersFor(this.accessTokenProvider?await this.accessTokenProvider():null)}async authFetch(e,t,s=!0){let r=s&&this.accessTokenProvider?await this.accessTokenProvider():null,i=l=>fetch(e,{...t,headers:{...this.headersFor(l),...t.headers}}),o=await i(r);if(o.status!==401||!r||!this.tokenRefresher)return o;let a=await this.tokenRefresher(r);return!a||a===r?o:(await o.body?.cancel().catch(()=>{}),i(a))}async request(e,t={}){return this._fetch(e,t,!0)}async requestPublic(e,t={}){return this._fetch(e,t,!1)}async requestForAnalytics(e,t={}){let s=this.analyticsToken?{"x-analytics-token":this.analyticsToken}:void 0;return this._fetch(e,{...t,headers:{...s,...t.headers}},!1)}async requestWithToken(e,t,s={}){return this._fetch(e,{...s,headers:{Authorization:`Bearer ${t}`,...s.headers}},!1)}headersFor(e){return{apikey:this.apiKey,Authorization:`Bearer ${e||this.apiKey}`,...this.clientIp?{"X-NestCore-Client-IP":this.clientIp}:{}}}async _fetch(e,t,s){let r=`${this.baseUrl}${e}`,i=new AbortController,o=setTimeout(()=>i.abort(),t.timeout||this.timeout);try{let a=await this.authFetch(r,{method:t.method||"GET",headers:{"Content-Type":"application/json",...t.headers},body:t.body?JSON.stringify(t.body):void 0,signal:i.signal,keepalive:t.keepalive,redirect:"error"},s);clearTimeout(o);let l=await a.json().catch(()=>null);return a.ok?{data:l,error:null}:{data:null,error:{message:m(l,a.status),code:l?.code||l?.statusCode?.toString(),status:a.status,details:l??void 0}}}catch(a){return clearTimeout(o),a instanceof Error&&a.name==="AbortError"?{data:null,error:{message:"Request timeout",code:"TIMEOUT"}}:{data:null,error:{message:a instanceof Error?a.message:"Unknown error",code:"NETWORK_ERROR"}}}}};function m(n,e,t){let s=n,r=s?.message??s?.error;if(Array.isArray(r))return r.join("; ");if(typeof r=="string"&&r)return r;let i=r?.message;return typeof i=="string"&&i?i:t??`Request failed with status ${e}`}function d(n){return{data:null,error:{message:`NestCore: ${n} requires a NestCore console admin token and is not available with a project API key. Manage it in the NestCore console, the NestCore CLI or the MCP server.`,code:"ADMIN_ONLY"}}}var R=class{constructor(e){this.client=e}get basePath(){return`/api/project/${this.client.getProjectSlug()}/database`}async semantic(e,t,s,r={}){return this.client.request(`${this.basePath}/semantic`,{method:"POST",body:{table:e,column:t,query:s,...r}})}async query(e,t){let s=await this.client.request(`${this.basePath}/sql`,{method:"POST",body:t&&t.length>0?{sql:e,params:t}:{sql:e}});return s.error?s:{data:{rows:s.data.data||[],rowCount:s.data.rows_affected||0,fields:s.data.columns?.map(r=>({name:r.name,dataType:r.type}))},error:null}}async listTables(){return this.client.request(`${this.basePath}/tables/list`)}async getTableMetadata(e){let t=new URLSearchParams({table:e});return this.client.request(`${this.basePath}/tables?${t.toString()}`)}async getTableData(e,t={}){let s=new URLSearchParams;t.page&&s.set("page",t.page.toString()),t.limit&&s.set("limit",t.limit.toString()),t.sortBy&&s.set("sortBy",t.sortBy),t.sortOrder&&s.set("sortOrder",t.sortOrder);let r=s.toString()?`?${s.toString()}`:"",i=await this.client.request(`${this.basePath}/tables/${encodeURIComponent(e)}/data${r}`);return i.error?i:{data:{rows:i.data.data??[],total:i.data.total_rows??0},error:null}}async insert(e,t){let s=await this.client.request(`${this.basePath}/tables/${encodeURIComponent(e)}/rows`,{method:"POST",body:t});return s.error?s:{data:s.data.data?.[0]||s.data,error:null}}async update(e,t,s){let r=await this.client.request(`${this.basePath}/tables/${encodeURIComponent(e)}/rows/${encodeURIComponent(String(t))}`,{method:"PUT",body:s});return r.error?r:{data:r.data.data?.[0]??r.data,error:null}}async delete(e,t){return this.client.request(`${this.basePath}/tables/${encodeURIComponent(e)}/rows/${encodeURIComponent(String(t))}`,{method:"DELETE"})}async bulkInsert(e,t){let s=await this.client.request(`${this.basePath}/tables/${encodeURIComponent(e)}/rows/bulk`,{method:"POST",body:t});return s.error?s:{data:s.data.data??[],error:null}}async bulkUpdate(e,t){let s=await this.client.request(`${this.basePath}/tables/${encodeURIComponent(e)}/rows/bulk`,{method:"PUT",body:t});return s.error?s:{data:{updated:s.data.rows_affected??0},error:null}}async bulkDelete(e,t){let s=await this.client.request(`${this.basePath}/tables/${encodeURIComponent(e)}/rows/bulk`,{method:"DELETE",body:t});return s.error?s:{data:{deleted:s.data.rows_affected??0},error:null}}async enableRls(e){return this.client.request(`${this.basePath}/tables/${encodeURIComponent(e)}/rls/enable`,{method:"POST"})}async disableRls(e){return this.client.request(`${this.basePath}/tables/${encodeURIComponent(e)}/rls/disable`,{method:"POST"})}async createPolicy(e,t){return this.client.request(`${this.basePath}/tables/${encodeURIComponent(e)}/policies`,{method:"POST",body:t})}async listPolicies(e){let t=await this.client.request(`${this.basePath}/tables/${encodeURIComponent(e)}/policies`);return t.error?t:{data:(t.data.policies??[]).map(r=>({name:r.name,command:r.command,definition:r.using??"",...r.with_check?{check:r.with_check}:{},roles:String(r.role??"").replace(/[{}]/g,"").split(",").map(i=>i.trim()).filter(Boolean)})),error:null}}async deletePolicy(e,t){return this.client.request(`${this.basePath}/tables/${encodeURIComponent(e)}/policies/${encodeURIComponent(t)}`,{method:"DELETE"})}from(e){return new W(this,e)}},te=/^[a-zA-Z_][a-zA-Z0-9_]*$/,W=class{constructor(e,t){this.db=e;this.tableName=t;this._filters=[];this._orders=[];this._columns="*";this.ident(t)}ident(e){if(!te.test(e))throw new Error(`NestCore: unsafe SQL identifier "${e}"`);return`"${e}"`}eq(e,t){return this.push(e,"eq",t)}neq(e,t){return this.push(e,"neq",t)}gt(e,t){return this.push(e,"gt",t)}gte(e,t){return this.push(e,"gte",t)}lt(e,t){return this.push(e,"lt",t)}lte(e,t){return this.push(e,"lte",t)}like(e,t){return this.push(e,"like",t)}ilike(e,t){return this.push(e,"ilike",t)}in(e,t){return this.push(e,"in",t)}is(e,t){return this.push(e,"is",t)}textSearch(e,t,s){this.ident(e);let r=s?.config??"english";if(!te.test(r))throw new Error(`NestCore: unsafe text-search config "${r}"`);return this._filters.push({col:e,op:"fts",value:t,ftsType:s?.type??"websearch",config:r}),this}nearest(e,t,s){if(this.ident(e),!Array.isArray(t)||!t.every(i=>typeof i=="number"&&Number.isFinite(i)))throw new Error("NestCore: nearest() vector must be an array of finite numbers");let r=s?.metric==="cosine"?"<=>":s?.metric==="ip"?"<#>":"<->";return this._vectorOrder={col:e,vec:`[${t.join(",")}]`,op:r},s?.limit!=null&&(this._limit=s.limit),this}push(e,t,s){return this.ident(e),this._filters.push({col:e,op:t,value:s}),this}order(e,t){return this.ident(e),this._orders.push({col:e,asc:t?.ascending!==!1}),this}orderBy(e,t="ASC"){return this.order(e,{ascending:t==="ASC"})}limit(e){return this._limit=e,this}range(e,t){return this._offset=e,this._limit=t-e+1,this}page(e,t=20){return this._limit=t,this._offset=Math.max(0,(e-1)*t),this}build(){let e=[],s=`SELECT ${this._columns==="*"?"*":this._columns.split(",").map(o=>this.ident(o.trim())).join(", ")} FROM ${this.ident(this.tableName)}`,r=[];for(let o of this._filters){let a=this.ident(o.col);switch(o.op){case"eq":r.push(`${a} = $${e.push(o.value)}`);break;case"neq":r.push(`${a} != $${e.push(o.value)}`);break;case"gt":r.push(`${a} > $${e.push(o.value)}`);break;case"gte":r.push(`${a} >= $${e.push(o.value)}`);break;case"lt":r.push(`${a} < $${e.push(o.value)}`);break;case"lte":r.push(`${a} <= $${e.push(o.value)}`);break;case"like":r.push(`${a} LIKE $${e.push(o.value)}`);break;case"ilike":r.push(`${a} ILIKE $${e.push(o.value)}`);break;case"in":{let l=o.value??[];if(l.length===0){r.push("FALSE");break}r.push(`${a} IN (${l.map(c=>`$${e.push(c)}`).join(", ")})`);break}case"is":o.value===null?r.push(`${a} IS NULL`):r.push(`${a} = $${e.push(o.value)}`);break;case"fts":{let l=o.config??"english",c=o.ftsType==="plain"?"plainto_tsquery":o.ftsType==="phrase"?"phraseto_tsquery":"websearch_to_tsquery";r.push(`to_tsvector('${l}', ${a}::text) @@ ${c}('${l}', $${e.push(o.value)})`);break}}}r.length&&(s+=` WHERE ${r.join(" AND ")}`);let i=[];this._vectorOrder&&i.push(`${this.ident(this._vectorOrder.col)} ${this._vectorOrder.op} $${e.push(this._vectorOrder.vec)}::vector`);for(let o of this._orders)i.push(`${this.ident(o.col)} ${o.asc?"ASC":"DESC"}`);return i.length&&(s+=` ORDER BY ${i.join(", ")}`),this._limit!=null&&(s+=` LIMIT $${e.push(this._limit)}`),this._offset!=null&&(s+=` OFFSET $${e.push(this._offset)}`),{sql:s,params:e}}async select(e="*"){this._columns=e;let{sql:t,params:s}=this.build(),r=await this.db.query(t,s);return r.error?r:{data:{rows:r.data.rows,total:r.data.rows.length},error:null}}async single(e="*"){this._limit=1;let t=await this.select(e);if(t.error)return t;let s=t.data.rows[0];return s?{data:s,error:null}:{data:null,error:{message:"No rows found",code:"NOT_FOUND"}}}async maybeSingle(e="*"){this._limit=1;let t=await this.select(e);return t.error?t:{data:t.data.rows[0]??null,error:null}}async semantic(e,t,s={}){if(this.ident(e),this._vectorOrder||this._filters.some(i=>i.op==="fts"))return{data:null,error:{message:"semantic() cannot be combined with textSearch() or nearest(); use hybridColumn for keyword ranking",code:"INVALID_QUERY"}};let r=this._filters.map(i=>({column:i.col,op:i.op,value:i.value}));return this.db.semantic(this.tableName,e,t,{k:this._limit,...s,...r.length?{filters:r}:{}})}async insert(e){return this.db.insert(this.tableName,e)}async update(e,t){return this.db.update(this.tableName,e,t)}async delete(e){return this.db.delete(this.tableName,e)}};var v=class{constructor(e){this.client=e}async invoke(e,t={}){let s=`${this.client.getBaseUrl()}/api/projects/${this.client.getProjectSlug()}/functions/v1/${encodeURIComponent(e)}`,r=t.method||"POST",i=new AbortController,o=setTimeout(()=>i.abort(),this.client.getTimeout());try{let a=await this.client.authFetch(s,{method:r,headers:{"Content-Type":"application/json",...t.headers},body:t.body!==void 0&&r!=="GET"?JSON.stringify(t.body):void 0,signal:i.signal,redirect:"error"});clearTimeout(o);let l=a.headers.get("content-type")??"",c=l.includes("json")?await a.json().catch(()=>null):l.startsWith("text/")?await a.text():await a.blob(),u={};return a.headers.forEach((h,p)=>{u[p]=h}),a.ok?{data:{data:c,status:a.status,headers:u},error:null}:{data:null,error:{message:m(c,a.status),code:c?.code,status:a.status,details:c}}}catch(a){return clearTimeout(o),a instanceof Error&&a.name==="AbortError"?{data:null,error:{message:"Request timeout",code:"TIMEOUT"}}:{data:null,error:{message:a instanceof Error?a.message:"Unknown error",code:"NETWORK_ERROR"}}}}};var k=class{constructor(e){this.client=e}async create(e){return d("client.jobs")}async list(){return d("client.jobs")}async get(e){return d("client.jobs")}async update(e,t){return d("client.jobs")}async delete(e){return d("client.jobs")}async trigger(e){return d("client.jobs")}async getRuns(e,t){return d("client.jobs")}};function K(){let n=new Map;return{getItem:e=>n.has(e)?n.get(e):null,setItem:(e,t)=>{n.set(e,t)},removeItem:e=>{n.delete(e)}}}function se(){let n=null;try{if(n=typeof globalThis<"u"?globalThis.localStorage??null:null,n){let t="__nestcore_probe__";n.setItem(t,"1"),n.removeItem(t)}}catch{n=null}if(!n)return K();let e=n;return{getItem:t=>{try{return e.getItem(t)}catch{return null}},setItem:(t,s)=>{try{e.setItem(t,s)}catch{}},removeItem:t=>{try{e.removeItem(t)}catch{}}}}var U={getItem:()=>null,setItem:()=>{},removeItem:()=>{}},re={getItem:n=>{try{return J()?.getItem(n)??null}catch{return null}},setItem:(n,e)=>{try{J()?.setItem(n,e)}catch{}},removeItem:n=>{try{J()?.removeItem(n)}catch{}}};function J(){try{return globalThis.localStorage??null}catch{return null}}function H(n){return!!n&&typeof n=="object"&&n.mfa_required===!0}var ve="nestcore.session",ke="orbitnest.session",Te=30,we={data:null,error:{message:"No active session",code:"NO_SESSION"}},T=class{constructor(e,t={}){this.client=e;this._session=null;this.refreshing=null;this.listeners=new Set;this.storage=t.storage??U,this.storageKey=`${ve}.${this.client.getProjectSlug()}`;let s=this.storage.getItem(this.storageKey);if(s===null){let r=`${ke}.${this.client.getProjectSlug()}`;try{s=this.storage.getItem(r),s!==null&&(this.storage.setItem(this.storageKey,s),this.storage.removeItem(r))}catch{}}if(s)try{this._session=JSON.parse(s)}catch{this.storage.removeItem(this.storageKey)}}get session(){return this._session}set session(e){this._session=Se(e);try{e?this.storage.setItem(this.storageKey,JSON.stringify(this._session)):this.storage.removeItem(this.storageKey)}catch{}for(let t of this.listeners)try{t(this._session)}catch{}}onAuthStateChange(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}async getAccessToken(){let e=this.session;return e?.access_token?e.expires_at&&e.expires_at-Te<=Date.now()/1e3?(await this.refreshSession()).data?.access_token??this.session?.access_token??null:e.access_token:null}async refreshAccessToken(e){let t=this.session?.access_token;return t?t!==e?t:(await this.refreshSession()).data?.access_token??null:null}async withToken(e){let t=await this.getAccessToken();return t?e(t):we}get basePath(){return`/api/projects/${this.client.getProjectSlug()}/auth`}getSession(){return this.session}getUser(){return this.session?.user||null}async signUp(e){return await this.client.requestPublic(`${this.basePath}/signup`,{method:"POST",body:{email:e.email,password:e.password,user_metadata:e.metadata}})}async verifySignUp(e){let t=await this.client.requestPublic(`${this.basePath}/verify-signup`,{method:"POST",body:{email:e.email,code:e.code}});return t.data&&(this.session=t.data),t}async signIn(e){let t=await this.client.requestPublic(`${this.basePath}/signin`,{method:"POST",body:{email:e.email,password:e.password}});return t.data&&!H(t.data)&&(this.session=t.data),t}async verifyMfa(e,t){let s=await this.client.requestPublic(`${this.basePath}/verify-mfa`,{method:"POST",body:{challenge_token:e,code:t}});return s.data&&(this.session=s.data),s}async signInWithSms(e){return this.client.requestPublic(`${this.basePath}/sms/send-otp`,{method:"POST",body:{phone:e}})}async verifySmsOtp(e,t){let s=await this.client.requestPublic(`${this.basePath}/sms/verify-otp`,{method:"POST",body:{phone:e,code:t}});return s.data&&(this.session=s.data),s}async signOut(){let e=await this.getAccessToken(),t=e?await this.client.requestWithToken(`${this.basePath}/signout`,e,{method:"POST"}):{data:{success:!0},error:null};return this.session=null,t}async refreshSession(){let e=this.session?.refresh_token;return e?(this.refreshing??(this.refreshing=this.client.requestPublic(`${this.basePath}/refresh`,{method:"POST",body:{refresh_token:e}}).then(t=>(t.data?this.session=t.data:t.error.status===401&&(this.session=null),t)).finally(()=>{this.refreshing=null})),this.refreshing):{data:null,error:{message:"No refresh token available",code:"NO_SESSION"}}}async resetPasswordForEmail(e){return this.client.requestPublic(`${this.basePath}/recover-password`,{method:"POST",body:{email:e.email}})}async updatePassword(e){return this.client.requestPublic(`${this.basePath}/reset-password`,{method:"POST",body:{email:e.email,code:e.token,new_password:e.password}})}async getProfile(){return this.withToken(e=>this.client.requestWithToken(`${this.basePath}/user`,e))}async updateUser(e){let{metadata:t,...s}=e,r=await this.withToken(o=>this.client.requestWithToken(`${this.basePath}/user`,o,{method:"PUT",body:t===void 0?s:{...s,data:t}}));if(r.error)return r;let i=r.data.user;return this.session&&i&&(this.session={...this.session,user:i}),{data:i,error:null}}async verifyEmailChange(e){let t=await this.withToken(r=>this.client.requestWithToken(`${this.basePath}/user/email/verify`,r,{method:"POST",body:{code:e}}));if(t.error)return t;let s=t.data.user;return this.session&&s&&(this.session={...this.session,user:s}),{data:s,error:null}}async deleteUser(){let e=await this.withToken(t=>this.client.requestWithToken(`${this.basePath}/user`,t,{method:"DELETE"}));return e.data&&(this.session=null),e}setSession(e){this.session=e}async registerPasskeyOptions(e={}){return this.withToken(t=>this.client.requestWithToken(`${this.basePath}/passkey/register/options`,t,{method:"POST",body:{device_name:e.device_name}}))}async registerPasskeyVerify(e){return this.withToken(t=>this.client.requestWithToken(`${this.basePath}/passkey/register/verify`,t,{method:"POST",body:e}))}async signUpWithPasskeyOptions(e){return this.client.requestPublic(`${this.basePath}/passkey/signup/options`,{method:"POST",body:e})}async signUpWithPasskeyVerify(e){let t=await this.client.requestPublic(`${this.basePath}/passkey/signup/verify`,{method:"POST",body:e});return t.data&&(this.session=t.data),t}async signInWithPasskeyOptions(e={}){return this.client.requestPublic(`${this.basePath}/passkey/login/options`,{method:"POST",body:e.identifier?{identifier:e.identifier}:{}})}async signInWithPasskeyVerify(e){let t=await this.client.requestPublic(`${this.basePath}/passkey/login/verify`,{method:"POST",body:e});return t.data&&(this.session=t.data),t}async listPasskeys(){return this.withToken(e=>this.client.requestWithToken(`${this.basePath}/passkey/devices`,e))}async renamePasskey(e,t){return this.withToken(s=>this.client.requestWithToken(`${this.basePath}/passkey/devices/${encodeURIComponent(e)}`,s,{method:"PATCH",body:{device_name:t}}))}async revokePasskey(e){return this.withToken(t=>this.client.requestWithToken(`${this.basePath}/passkey/devices/${encodeURIComponent(e)}`,t,{method:"DELETE"}))}async enrollMfaTotp(e,t){return this.withToken(s=>this.client.requestWithToken(`${this.basePath}/mfa/totp/enroll`,s,{method:"POST",body:{friendly_name:e,code:t}}))}async verifyMfaEnrollment(e,t){return this.withToken(s=>this.client.requestWithToken(`${this.basePath}/mfa/totp/verify`,s,{method:"POST",body:{factor_id:e,code:t}}))}async regenerateMfaRecoveryCodes(e){return this.withToken(t=>this.client.requestWithToken(`${this.basePath}/mfa/recovery-codes`,t,{method:"POST",body:{code:e}}))}async listMfaFactors(){return this.withToken(e=>this.client.requestWithToken(`${this.basePath}/mfa/factors`,e))}async unenrollMfa(e,t){return this.withToken(s=>this.client.requestWithToken(`${this.basePath}/mfa/factors/${encodeURIComponent(e)}`,s,{method:"DELETE",body:{code:t}}))}};function Se(n){return!n||n.expires_at||!n.expires_in?n:{...n,expires_at:Math.floor(Date.now()/1e3)+n.expires_in}}var w=class{constructor(e){this.client=e}async getLogs(e={}){return d("client.logs")}async getDatabaseLogs(e={}){return d("client.logs")}async getSlowQueryLogs(e={}){return d("client.logs")}async getAuthLogs(e={}){return d("client.logs")}async getAuthFailures(e={}){return d("client.logs")}async getEdgeFunctionLogs(e,t={}){return d("client.logs")}};var S=class{constructor(e){this.client=e}async list(){return d("client.env")}async get(e){return d("client.env")}async set(e,t,s={}){return d("client.env")}async create(e,t,s={}){return d("client.env")}async bulkCreate(e){return d("client.env")}async delete(e){return d("client.env")}};function V(n,e){return!n||typeof n!="string"||n.trim().length===0?{data:null,error:{message:`${e} is required and must be a non-empty string`,code:"VALIDATION_ERROR"}}:null}function g(n,e="path"){let t=V(n,e);if(t)return t;if(n.includes("\0"))return{data:null,error:{message:`${e} must not contain null bytes`,code:"VALIDATION_ERROR"}};let s=n.split("/");for(let r of s)if(r==="..")return{data:null,error:{message:`${e} must not contain path traversal sequences`,code:"VALIDATION_ERROR"}};return null}function ne(n){return n.replace(/\\/g,"/").split("/").filter(e=>e!==".."&&e!==""&&e!==".").join("/")}function ie(n){return n.split("/").filter(e=>e.length>0).map(e=>encodeURIComponent(e)).join("/")}function _e(n){if(!n)return"";let e=new URLSearchParams;return n.width&&e.set("width",String(n.width)),n.height&&e.set("height",String(n.height)),n.format&&e.set("format",n.format),n.quality&&e.set("quality",String(n.quality)),n.fit&&e.set("fit",n.fit),e.toString()}var Ce={png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif",webp:"image/webp",avif:"image/avif",svg:"image/svg+xml",ico:"image/x-icon",pdf:"application/pdf",json:"application/json",txt:"text/plain",csv:"text/csv",html:"text/html",css:"text/css",js:"text/javascript",mp4:"video/mp4",webm:"video/webm",mp3:"audio/mpeg",wav:"audio/wav",zip:"application/zip"};function Ee(n){let e=n.split(".").pop()?.toLowerCase()??"";return Ce[e]}function z(n){if(n.error)return n;let e=n.data;return{data:e?.data??e,error:null}}var _=class{constructor(e){this.client=e}from(e){return new j(this.client,e)}},j=class{constructor(e,t){this.client=e;this.bucket=t}get basePath(){return`/api/project/${this.client.getProjectSlug()}/storage/${this.bucket}`}absoluteUrl(e){return`${this.client.getBaseUrl()}${e}`}async upload(e,t,s){let r=g(e);if(r)return r;let i=new FormData,o=s?.contentType||t instanceof Blob&&t.type||Ee(e)||"application/octet-stream",a=new Blob([t],{type:o});i.append("file",a,e.split("/").pop()||"file"),i.append("path",e),s?.upsert&&i.append("upsert","true");let l=this.absoluteUrl(`${this.basePath}/upload`),c=new AbortController,u=setTimeout(()=>c.abort(),3e4);try{let h=await this.client.authFetch(l,{method:"POST",body:i,redirect:"error",signal:c.signal});clearTimeout(u);let p=await h.json().catch(()=>null);return h.ok?{data:p?.data??p,error:null}:{data:null,error:{message:m(p,h.status,"Upload failed"),code:p?.code,status:h.status,details:p??void 0}}}catch(h){return clearTimeout(u),h instanceof Error&&h.name==="AbortError"?{data:null,error:{message:"Upload timeout",code:"TIMEOUT"}}:{data:null,error:{message:h instanceof Error?h.message:"Upload failed",code:"UPLOAD_ERROR"}}}}async download(e){let t=g(e);if(t)return t;let s=this.absoluteUrl(`${this.basePath}/download/${ie(e)}`),r=new AbortController,i=setTimeout(()=>r.abort(),3e4);try{let o=await this.client.authFetch(s,{redirect:"error",signal:r.signal});if(clearTimeout(i),!o.ok){let l=await o.json().catch(()=>null);return{data:null,error:{message:m(l,o.status,"Download failed"),code:l?.code,status:o.status,details:l??void 0}}}return{data:await o.blob(),error:null}}catch(o){return clearTimeout(i),o instanceof Error&&o.name==="AbortError"?{data:null,error:{message:"Download timeout",code:"TIMEOUT"}}:{data:null,error:{message:o instanceof Error?o.message:"Download failed",code:"DOWNLOAD_ERROR"}}}}async remove(e){for(let t of e){let s=g(t);if(s)return s}return z(await this.client.request(this.basePath,{method:"DELETE",body:{paths:e}}))}async list(e,t){let s=new URLSearchParams;e&&s.set("prefix",e),t?.limit&&s.set("limit",t.limit.toString());let r=s.toString()?`?${s.toString()}`:"";return z(await this.client.request(`${this.basePath}${r}`))}getPublicUrl(e,t){let s=g(e);if(s)throw new Error(`NestCore: ${s.error?.message??"invalid storage path"}`);let r=this.client.getBaseUrl(),i=this.client.getProjectSlug(),o=`${r}/api/public/${i}/storage/${this.bucket}/${ie(e)}`,a=_e(t?.transform);return a&&(o+=`?${a}`),{data:{publicUrl:o}}}async createBucket(e={}){return z(await this.client.request(`${this.basePath}/create`,{method:"POST",body:e.public===void 0?void 0:{public:e.public}}))}};var N=class{constructor(e,t){this.channelName=e;this.client=t;this.state={};this.syncCbs=[];this.joinCbs=[];this.leaveCbs=[]}async track(e){await this.client.sendPresenceTrack(this.channelName,e)}async untrack(){this.client.sendPresenceUntrack(this.channelName)}getState(){return{...this.state}}_hasListeners(){return this.syncCbs.length+this.joinCbs.length+this.leaveCbs.length>0}onSync(e){return this.syncCbs.push(e),this}onJoin(e){return this.joinCbs.push(e),this}onLeave(e){return this.leaveCbs.push(e),this}_handleStateUpdate(e){let t=this.state;for(let[s,r]of Object.entries(e))if(!t[s])for(let i of this.joinCbs)i(s,r);for(let[s,r]of Object.entries(t))if(!e[s])for(let i of this.leaveCbs)i(s,r);this.state={...e};for(let s of this.syncCbs)s({...this.state})}},D=class{constructor(e,t){this.name=e;this.client=t;this.handlers=[];this._joined=!1;this.presence=new N(e,t)}on(e,t,s){return this.handlers.push({type:e,opts:t,callback:s}),this}subscribe(e){return this.statusCb=e,this._joined=!0,this.client.registerChannel(this),this}async send(e,t){await this.client.sendBroadcast(this.name,e,t)}async unsubscribe(){await this.client.unregisterChannel(this.name)}get channelName(){return this.name}_activate(e){for(let t of this._tableKeys()){let[s,r]=le(t);this.client.syncTable(e,s,r)}this._hasBroadcast()&&e.send(JSON.stringify({id:`${this.name}-bc-${Math.random().toString(36).slice(2)}`,type:"subscribe",channel:`broadcast:${this.name}`})),this.statusCb?.("connected")}_tableKeys(){if(!this._joined)return[];let e=this.handlers.filter(t=>t.type==="postgres_changes").map(t=>`${t.opts.schema??"public"}.${t.opts.table}`);return[...new Set(e)]}_tableHandlers(e,t){return this._joined?this.handlers.filter(s=>s.type==="postgres_changes").map(s=>s.opts).filter(s=>(s.schema??"public")===e&&s.table===t):[]}_hasBroadcast(){return this.handlers.some(e=>e.type==="broadcast")||this.presence._hasListeners()||!this.handlers.some(e=>e.type==="postgres_changes")}_setStatus(e,t){this.statusCb?.(e,t)}_dispatch(e){if(e.type==="db_event"){let t={op:e.op,schema:e.schema,table:e.table,new:e.new,old:e.old,commit_ts:e.commit_ts};for(let s of this.handlers){if(s.type!=="postgres_changes")continue;let r=s.opts,i=ae(r.event);!i.includes(e.op)&&!i.includes("*")||r.table&&r.table!==e.table||r.schema&&r.schema!==e.schema||qe(e.op==="DELETE"?e.old:e.new,r.filter)&&s.callback(t)}}else if(e.type==="broadcast"){let t={event:e.event,payload:e.payload};for(let s of this.handlers){if(s.type!=="broadcast")continue;let r=s.opts;r.event!=="*"&&r.event!==e.event||s.callback(t)}}else e.type==="presence.state"&&this.presence._handleStateUpdate(e.presences??{})}},$e=0,f=1,oe=1e3,Oe=1e4,Ie=6e4,xe=4029,C=class{constructor(e,t={}){this.url=e;this.options=t;this.ws=null;this.channels=new Map;this.reconnectDelay=oe;this.maxReconnectDelay=Ie;this.shouldReconnect=!0;this.connectPromise=null;this.reconnectTimer=null;this.authChanged=!1;this.authRetried=!1}channel(e){return this.channels.has(e)||this.channels.set(e,new D(e,this)),this.channels.get(e)}setAuth(e){if(this.options.accessToken||(this.options.userJwt=e??void 0),!((e??void 0)===this.socketJwt||!this.ws)){if(this.ws.readyState===$e){this.authChanged=!0;return}this.reopen()}}disconnect(){this.shouldReconnect=!1,this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null),this.ws?.close(1e3,"client disconnect"),this.ws=null,this.channels.clear()}connect(){return this.connectPromise?this.connectPromise:this.ws?.readyState===f?Promise.resolve():(this.connectPromise=this.resolveUserJwt().then(e=>new Promise((t,s)=>{let r=this.options.WebSocket??globalThis.WebSocket;if(!r){s(new Error('No WebSocket implementation found. On Node.js < 22, pass a WebSocket constructor via options.WebSocket (e.g. from the "ws" package).'));return}let i=["orbitnest-realtime-v1"];this.socketJwt=e,e&&i.push(`orbitnest.user-jwt.${e}`);let o;this.options.apiKey&&(i.push(`orbitnest.apikey.${this.options.apiKey}`),o={headers:{Authorization:`Bearer ${this.options.apiKey}`}});let a=new r(this.url,i,o);a.onopen=()=>{if(this.reconnectDelay=oe,this.connectPromise=null,t(),this.authChanged){this.authChanged=!1,this.reopen();return}for(let l of this.channels.values())l._joined&&l._activate(a)},a.onmessage=l=>{try{let c=JSON.parse(typeof l.data=="string"?l.data:l.data.toString());this.route(c)}catch{}},a.onerror=l=>{let c=new Error(l?.message??"WebSocket error");for(let u of this.channels.values())u._setStatus("error",c);this.connectPromise=null,s(c)},a.onclose=l=>{this.connectPromise=null;for(let u of this.channels.values())u._setStatus("disconnected");let c=l?.code;if((c===1e3||c===1001||c===4001)&&(this.shouldReconnect=!1),c===4001&&this.socketJwt&&!this.authRetried&&this.options.onAuthRejected&&(this.authRetried=!0,this.options.onAuthRejected(this.socketJwt)),this.shouldReconnect){(c===xe||c===1008||c===1013)&&(this.reconnectDelay=Math.max(this.reconnectDelay,Oe));let u=Math.floor(Math.random()*500),h=Math.min(this.reconnectDelay+u,this.maxReconnectDelay);this.reconnectTimer&&clearTimeout(this.reconnectTimer),this.reconnectTimer=setTimeout(()=>this.reconnect(),h),this.reconnectDelay=Math.min(this.reconnectDelay*2,this.maxReconnectDelay)}},this.ws=a})),this.connectPromise)}async resolveUserJwt(){if(!this.options.accessToken)return this.options.userJwt;try{return await this.options.accessToken()??void 0}catch{return}}reopen(){let e=this.ws;e&&(e.onclose=null,e.onerror=null,e.onmessage=null,e.close(1e3,"auth changed")),this.ws=null,this.connectPromise=null,[...this.channels.values()].some(t=>t._joined)&&(this.shouldReconnect=!0,this.connect().catch(()=>{}))}syncTable(e,t,s){let r=[...this.channels.values()].flatMap(a=>a._tableHandlers(t,s));if(r.length===0)return;let i=[...new Set(r.flatMap(a=>ae(a.event)))],o=new Set(r.map(a=>JSON.stringify(a.filter??null))).size===1;e.send(JSON.stringify({id:`rt-${Math.random().toString(36).slice(2)}`,type:"subscribe",channel:`table:${t}.${s}`,events:i,filter:o?r[0].filter:void 0}))}reconnect(){this.reconnectTimer=null,this.connectPromise=null,this.ws=null,this.shouldReconnect&&[...this.channels.values()].some(e=>e._joined)&&this.connect().catch(()=>{})}route(e){if(e.type==="system"&&e.event==="connected"&&(this.authRetried=!1),e.type==="db_event")for(let t of this.channels.values())t._dispatch(e);else if(e.type==="broadcast")for(let t of this.channels.values())`broadcast:${t.channelName}`===e.channel&&t._dispatch(e);else if(e.type==="presence.state"){let t=e.channel?.replace(/^broadcast:/,"");if(t){let s=this.channels.get(t);s&&s._dispatch(e)}}}registerChannel(e){if(this.channels.set(e.channelName,e),this.shouldReconnect=!0,e._setStatus("connecting"),this.ws?.readyState===f){e._activate(this.ws);return}this.connect().catch(t=>e._setStatus("error",t))}async unregisterChannel(e){let t=this.channels.get(e);if(!t)return;let s=t._tableKeys();t._joined=!1,this.channels.delete(e);let r=this.ws;if(r?.readyState===f){let i=o=>r.send(JSON.stringify({id:`unsub-${Math.random().toString(36).slice(2)}`,type:"unsubscribe",channel:o}));for(let o of s){let[a,l]=le(o);[...this.channels.values()].some(u=>u._tableHandlers(a,l).length>0)?this.syncTable(r,a,l):i(`table:${o}`)}t._hasBroadcast()&&i(`broadcast:${e}`)}[...this.channels.values()].some(i=>i._joined)||this.ws?.close(1e3,"no channels")}async sendBroadcast(e,t,s){if(await this.connect(),this.ws?.readyState!==f)throw new Error("Not connected");this.ws.send(JSON.stringify({id:`bc-${Math.random().toString(36).slice(2)}`,type:"broadcast",channel:`broadcast:${e}`,event:t,payload:s}))}async sendPresenceTrack(e,t){if(await this.connect(),this.ws?.readyState!==f)throw new Error("Not connected");this.ws.send(JSON.stringify({id:`pt-${Math.random().toString(36).slice(2)}`,type:"presence.track",channel:`broadcast:${e}`,state:t}))}sendPresenceUntrack(e){this.ws?.readyState===f&&this.ws.send(JSON.stringify({id:`pu-${Math.random().toString(36).slice(2)}`,type:"presence.untrack",channel:`broadcast:${e}`}))}};function ae(n){if(n==="*")return["INSERT","UPDATE","DELETE"];let e=Array.isArray(n)?n:[n];return e.includes("*")?["INSERT","UPDATE","DELETE"]:e}function le(n){let e=n.indexOf(".");return[n.slice(0,e),n.slice(e+1)]}function qe(n,e){if(!e||!n)return!0;for(let[t,s]of Object.entries(e)){let r=n[t];if(s.eq!==void 0&&r!=s.eq||s.neq!==void 0&&r==s.neq||s.in!==void 0&&!s.in.some(i=>i==r)||s.gt!==void 0&&!(r>s.gt)||s.lt!==void 0&&!(r<s.lt))return!1;if(s.like!==void 0){let i=s.like.replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace(/%/g,".*").replace(/_/g,".");if(!new RegExp(`^${i}$`,"s").test(String(r)))return!1}}return!0}var Q="nestcore_anonymous_id",G="nestcore_session_id",Y="nestcore_session_last_activity",Ue={[Q]:"orbitnest_anonymous_id",[G]:"orbitnest_session_id",[Y]:"orbitnest_session_last_activity"},je=1800*1e3;function b(){if(typeof crypto<"u"&&typeof crypto.randomUUID=="function")return crypto.randomUUID();if(typeof crypto<"u"&&typeof crypto.getRandomValues=="function"){let n=new Uint8Array(16);crypto.getRandomValues(n),n[6]=n[6]&15|64,n[8]=n[8]&63|128;let e=Array.from(n,t=>t.toString(16).padStart(2,"0")).join("");return`${e.slice(0,8)}-${e.slice(8,12)}-${e.slice(12,16)}-${e.slice(16,20)}-${e.slice(20)}`}return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,n=>{let e=Math.random()*16|0;return(n==="x"?e:e&3|8).toString(16)})}function Ne(){try{if(typeof localStorage>"u")return null;let n="__on_ls_probe__";return localStorage.setItem(n,"1"),localStorage.removeItem(n),localStorage}catch{return null}}function Z(n,e){let t=n.getItem(e);if(t!==null)return t;let s=Ue[e],r=s?n.getItem(s):null;return r===null||!s?null:(n.setItem(e,r),n.removeItem(s),r)}function De(){return typeof window<"u"&&typeof document<"u"?"web":"node"}function Me(n){if(!n)return b();try{let e=Z(n,Q);return e||(e=b(),n.setItem(Q,e)),e}catch{return b()}}function Le(n,e){if(!n)return e;try{let t=Date.now(),s=parseInt(Z(n,Y)??"0",10)||0,r=Z(n,G);return(!r||t-s>je)&&(r=b(),n.setItem(G,r)),n.setItem(Y,String(t)),r}catch{return e}}var E=class{constructor(e,t={}){this.client=e;this.queue=[];this.flushTimer=null;this.storage=Ne(),this.anonymousId=Me(this.storage),this.fallbackSessionId=b(),this.platform=t.platform??De(),this.appVersion=t.appVersion,this.flushInterval=t.flushInterval??5e3,this.maxBatchSize=Math.min(t.maxBatchSize??50,500),typeof window<"u"&&typeof document<"u"&&window.addEventListener&&(window.addEventListener("pagehide",()=>this.flushInBackground(!0)),document.addEventListener("visibilitychange",()=>{document.visibilityState==="hidden"&&this.flushInBackground(!0)}))}identify(e,t){this.userId=e,this.enqueue("identify",t)}track(e,t){this.enqueue(e,t)}screen(e,t){this.enqueue("screen_view",{screen:e,...t})}crash(e,t){let s=e instanceof Error?e.message:e,r=e instanceof Error?e.stack:void 0;this.enqueue("crash",{...e instanceof Error?{error_type:e.name}:{},error_message:s,...r?{stack_trace:r}:{},...t})}async flush(e=!1){if(this.clearFlushTimer(),this.queue.length===0)return{data:{accepted:0,rejected:0,errors:[]},error:null};let t=this.queue.splice(0,this.queue.length),s=await this.client.requestForAnalytics("/api/analytics/events",{method:"POST",body:{events:t},keepalive:e}),r=s.error?.status;return s.error&&(r===void 0||r===429||r>=500)&&(this.queue=[...t,...this.queue].slice(-1e3),e||this.scheduleFlush()),s}flushInBackground(e=!1){this.flush(e).then(t=>{let s=t.error?.status;t.error&&s!==void 0&&s!==429&&s<500&&console.warn(`[nestcore] analytics events rejected (${s}): ${t.error.message}`)})}enqueue(e,t){let s={event_id:b(),event:e,anonymous_id:this.anonymousId,platform:this.platform,timestamp:new Date().toISOString(),session_id:Le(this.storage,this.fallbackSessionId),...this.userId?{user_id:this.userId}:{},...this.appVersion?{app_version:this.appVersion}:{},...t?{properties:t}:{}};this.queue.push(s),this.queue.length>=this.maxBatchSize?this.flushInBackground():this.scheduleFlush()}scheduleFlush(){this.flushTimer===null&&(this.flushTimer=setTimeout(()=>{this.flushTimer=null,this.flushInBackground()},this.flushInterval))}clearFlushTimer(){this.flushTimer!==null&&(clearTimeout(this.flushTimer),this.flushTimer=null)}};async function*M(n){let e=n.getReader(),t=new TextDecoder,s="";try{for(;;){let{value:r,done:i}=await e.read();if(i)break;s+=t.decode(r,{stream:!0});let o;for(;(o=s.indexOf(`
2
- `))>=0;){let a=s.slice(0,o).replace(/\r$/,"");s=s.slice(o+1),a.startsWith("data:")&&(yield a.slice(5).trimStart())}}s.startsWith("data:")&&(yield s.slice(5).trimStart())}finally{await e.cancel().catch(()=>{})}}var $=class{constructor(e){this.client=e}path(e=""){return`/api/project/${this.client.getProjectSlug()}/ai/v1/memory${e}`}add(e,t={}){return this.client.request(this.path(),{method:"POST",body:{content:e,...t}})}search(e,t={}){return this.client.request(this.path("/search"),{method:"POST",body:{query:e,...t}})}list(e={}){return this.client.request(this.path(x(e)))}get(e){return this.client.request(this.path(`/${encodeURIComponent(e)}`))}update(e,t){return this.client.request(this.path(`/${encodeURIComponent(e)}`),{method:"PATCH",body:t})}remove(e){return this.client.request(this.path(`/${encodeURIComponent(e)}`),{method:"DELETE"})}forget(e){return this.client.request(this.path("/forget"),{method:"POST",body:e?{subject:e}:{}})}subjects(e={}){return this.client.request(this.path(`/subjects${x(e)}`))}reembed(e={}){return this.client.request(this.path("/reembed"),{method:"POST",body:e})}},L=class{constructor(e,t){this.client=e;this.name=t}path(e=""){return`/api/project/${this.client.getProjectSlug()}/ai/v1/collections/${encodeURIComponent(this.name)}${e}`}async ingest(e,t={}){let{wait:s,...r}=t,i=await this.client.request(this.path("/documents"),{method:"POST",body:{...e,...r}});return i.error||!s?i:this.waitFor(i.data.id,typeof s=="object"?s:{})}async waitFor(e,{timeoutMs:t=12e4,intervalMs:s=1e3}={}){let r=Date.now()+t;for(;;){let i=await this.getDocument(e);if(i.error||i.data.status==="ready"||i.data.status==="failed")return i;if(Date.now()>r)return{data:null,error:{message:`Document ${e} is still ${i.data.status}`,code:"TIMEOUT"}};await new Promise(o=>setTimeout(o,s))}}search(e,t={}){return this.client.request(this.path("/search"),{method:"POST",body:{query:e,...t}})}listDocuments(e={}){return this.client.request(this.path(`/documents${x(e)}`))}getDocument(e){return this.client.request(this.path(`/documents/${encodeURIComponent(e)}`))}remove(e){return this.client.request(this.path(`/documents/${encodeURIComponent(e)}`),{method:"DELETE"})}stats(){return this.client.request(this.path("/stats"))}},O=class{constructor(e){this.client=e}path(e=""){return`/api/project/${this.client.getProjectSlug()}/ai/v1/collections${e}`}from(e){return new L(this.client,e)}create(e){return this.client.request(this.path(),{method:"POST",body:e})}list(){return this.client.request(this.path())}get(e){return this.client.request(this.path(`/${encodeURIComponent(e)}`))}update(e,t){return this.client.request(this.path(`/${encodeURIComponent(e)}`),{method:"PATCH",body:t})}delete(e){return this.client.request(this.path(`/${encodeURIComponent(e)}`),{method:"DELETE"})}},F=class{constructor(e,t){this.client=e;this.id=t}path(e=""){return`/api/project/${this.client.getProjectSlug()}/ai/v1/threads/${encodeURIComponent(this.id)}${e}`}get(){return this.client.request(this.path())}update(e){return this.client.request(this.path(),{method:"PATCH",body:e})}delete(){return this.client.request(this.path(),{method:"DELETE"})}messages(e={}){return this.client.request(this.path(`/messages${x(e)}`))}append(e,t={}){return this.client.request(this.path("/messages"),{method:"POST",body:{content:e,...t}})}async*run(e={},{signal:t}={}){let s;try{s=await this.client.authFetch(`${this.client.getBaseUrl()}${this.path("/run")}`,{method:"POST",headers:{"Content-Type":"application/json",Accept:"text/event-stream"},body:JSON.stringify({...e,stream:!0}),signal:t,redirect:"error"})}catch(r){yield{type:"error",code:"NETWORK_ERROR",message:r instanceof Error?r.message:"Network error"};return}if(!s.ok||!s.body){let r=await s.json().catch(()=>null);yield{type:"error",code:r?.code,message:m(r,s.status),status:s.status};return}try{for await(let r of M(s.body))yield JSON.parse(r)}catch(r){yield{type:"error",code:"STREAM_ERROR",message:r instanceof Error?r.message:"Stream interrupted"}}}runOnce(e={}){return this.client.request(this.path("/run"),{method:"POST",body:{...e,stream:!1},timeout:18e4})}},I=class{constructor(e){this.client=e}path(e=""){return`/api/project/${this.client.getProjectSlug()}/ai/v1/threads${e}`}from(e){return new F(this.client,e)}create(e={}){return this.client.request(this.path(),{method:"POST",body:e})}list(e={}){return this.client.request(this.path(x(e)))}get(e){return this.from(e).get()}delete(e){return this.from(e).delete()}};function x(n){let e=Object.entries(n).filter(([,t])=>t!=null).map(([t,s])=>`${encodeURIComponent(t)}=${encodeURIComponent(String(s))}`);return e.length?`?${e.join("&")}`:""}var q=class{constructor(e){this.client=e;this.threads=new I(e)}path(e){return`/api/project/${this.client.getProjectSlug()}/ai/v1/${e}`}body(e,t){return{model:e.model,provider:e.provider,messages:e.messages.map(s=>({role:s.role,content:s.content,...s.toolCalls?{tool_calls:s.toolCalls}:{},...s.toolCallId?{tool_call_id:s.toolCallId}:{}})),temperature:e.temperature,max_tokens:e.maxTokens,tools:e.tools,tool_choice:e.toolChoice,stream:t}}async chat(e){return this.client.request(this.path("chat"),{method:"POST",body:this.body(e,!1),timeout:12e4})}async*chatStream(e,{signal:t}={}){let s;try{s=await this.client.authFetch(`${this.client.getBaseUrl()}${this.path("chat")}`,{method:"POST",headers:{"Content-Type":"application/json",Accept:"text/event-stream"},body:JSON.stringify(this.body(e,!0)),signal:t,redirect:"error"})}catch(r){yield{type:"error",code:"NETWORK_ERROR",message:r instanceof Error?r.message:"Network error"};return}if(!s.ok||!s.body){let r=await s.json().catch(()=>null);yield{type:"error",code:r?.code,message:m(r,s.status),status:s.status};return}try{for await(let r of M(s.body))yield JSON.parse(r)}catch(r){yield{type:"error",code:"STREAM_ERROR",message:r instanceof Error?r.message:"Stream interrupted"}}}async embed(e,t={}){return this.client.request(this.path("embeddings"),{method:"POST",body:{input:e,...t}})}async models(){return this.client.request(this.path("models"))}async traces(e={}){let t=Object.entries(e).filter(([,s])=>s!==void 0).map(([s,r])=>`${s}=${encodeURIComponent(String(r))}`).join("&");return this.client.request(this.path(`traces${t?`?${t}`:""}`))}};var Fe={int2:"number",int4:"number",int8:"number",smallint:"number",integer:"number",bigint:"number",serial:"number",bigserial:"number",numeric:"number",decimal:"number",real:"number",float4:"number",float8:"number","double precision":"number",bool:"boolean",boolean:"boolean",text:"string",varchar:"string","character varying":"string",char:"string",character:"string",bpchar:"string",citext:"string",uuid:"string",name:"string",date:"string",timestamp:"string",timestamptz:"string","timestamp with time zone":"string","timestamp without time zone":"string",time:"string",timetz:"string",interval:"string","time without time zone":"string","time with time zone":"string",json:"Record<string, unknown>",jsonb:"Record<string, unknown>",bytea:"string",vector:"string"};function X(n){let e=(n||"").toLowerCase().trim();return e?e.endsWith("[]")?`${X(e.slice(0,-2))}[]`:e.startsWith("_")?`${X(e.slice(1))}[]`:Fe[e]??"unknown":"unknown"}function Be(n){return n.replace(/(^|[_\- ])([a-zA-Z0-9])/g,(e,t,s)=>s.toUpperCase()).replace(/[^a-zA-Z0-9]/g,"")}function We(n){return/^[a-zA-Z_$][\w$]*$/.test(n)?n:JSON.stringify(n)}async function ce(n,e={}){let t=await n.listTables();if(t.error)throw new Error(`generateTypes: could not list tables: ${t.error.message}`);let s=t.data,r=Array.isArray(s)?s.map(u=>typeof u=="string"?u:u?.name).filter(u=>!!u):s?.tables??[],i=e.exclude??/^(auth_|_)/;r=e.tables?r.filter(u=>e.tables.includes(u)):r.filter(u=>!i.test(u)),r=Array.from(new Set(r)).sort();let o=[],a=[];for(let u of r){let h=await n.getTableMetadata(u);if(h.error)continue;let p=h.data.find(y=>y.table_name===u)?.columns??[];if(p.length===0)continue;let pe=p.map(y=>{let me=y.is_nullable?"?":"",ge=y.is_nullable?" | null":"";return` ${We(y.column_name)}${me}: ${X(y.data_type)}${ge};`}),ee=Be(u);o.push(`export interface ${ee} {
3
- ${pe.join(`
1
+ "use strict";var NestCore=(()=>{var J=Object.defineProperty;var be=Object.getOwnPropertyDescriptor;var Ae=Object.getOwnPropertyNames;var Re=Object.prototype.hasOwnProperty;var Pe=(n,e)=>{for(var t in e)J(n,t,{get:e[t],enumerable:!0})},Te=(n,e,t,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of Ae(e))!Re.call(n,r)&&r!==t&&J(n,r,{get:()=>e[r],enumerable:!(s=be(e,r))||s.enumerable});return n};var ve=n=>Te(J({},"__esModule",{value:!0}),n);var Qe={};Pe(Qe,{AiClient:()=>U,AnalyticsClient:()=>E,AuthClient:()=>k,AuthLimitCodes:()=>me,CollectionRef:()=>L,CollectionsClient:()=>$,DatabaseClient:()=>P,EnvironmentClient:()=>S,FunctionsClient:()=>T,HttpClient:()=>R,JobsClient:()=>v,LoggingClient:()=>w,MemoryClient:()=>O,NestCoreError:()=>A,OrbitNestError:()=>he,PresenceManager:()=>M,ProjectErrorCodes:()=>B,RealtimeChannel:()=>D,RealtimeClient:()=>C,StorageBucket:()=>j,StorageClient:()=>_,ThreadRef:()=>F,ThreadsClient:()=>x,createClient:()=>ze,createLocalStorageAdapter:()=>re,createMemoryAdapter:()=>H,generateTypes:()=>de,isMfaChallenge:()=>V,localStorageAdapter:()=>ne,memoryAdapter:()=>q,sanitizePath:()=>ie,unwrap:()=>pe,validatePath:()=>g,validateRequired:()=>z});var R=class{constructor(e){this.baseUrl=(e.baseUrl||"https://api.nestcore.io").replace(/\/$/,""),this.apiKey=e.apiKey,this.projectSlug=e.projectSlug,this.timeout=e.timeout||3e4,this.analyticsToken=e.analyticsToken,this.clientIp=e.clientIp}getProjectSlug(){return this.projectSlug}getBaseUrl(){return this.baseUrl}getTimeout(){return this.timeout}getApiKey(){return this.apiKey}setAccessTokenProvider(e,t){this.accessTokenProvider=e,this.tokenRefresher=t}async authHeaders(){return this.headersFor(this.accessTokenProvider?await this.accessTokenProvider():null)}async authFetch(e,t,s=!0){let r=s&&this.accessTokenProvider?await this.accessTokenProvider():null,i=l=>fetch(e,{...t,headers:{...this.headersFor(l),...t.headers}}),o=await i(r);if(o.status!==401||!r||!this.tokenRefresher)return o;let a=await this.tokenRefresher(r);return!a||a===r?o:(await o.body?.cancel().catch(()=>{}),i(a))}async request(e,t={}){return this._fetch(e,t,!0)}async requestPublic(e,t={}){return this._fetch(e,t,!1)}async requestForAnalytics(e,t={}){let s=this.analyticsToken?{"x-analytics-token":this.analyticsToken}:void 0;return this._fetch(e,{...t,headers:{...s,...t.headers}},!1)}async requestWithToken(e,t,s={}){return this._fetch(e,{...s,headers:{Authorization:`Bearer ${t}`,...s.headers}},!1)}headersFor(e){return{apikey:this.apiKey,Authorization:`Bearer ${e||this.apiKey}`,...this.clientIp?{"X-NestCore-Client-IP":this.clientIp}:{}}}async _fetch(e,t,s){let r=`${this.baseUrl}${e}`,i=new AbortController,o=setTimeout(()=>i.abort(),t.timeout||this.timeout);try{let a=await this.authFetch(r,{method:t.method||"GET",headers:{"Content-Type":"application/json",...t.headers},body:t.body?JSON.stringify(t.body):void 0,signal:i.signal,keepalive:t.keepalive,redirect:"error"},s);clearTimeout(o);let l=await a.json().catch(()=>null);return a.ok?{data:l,error:null}:{data:null,error:{message:m(l,a.status),code:l?.code||l?.statusCode?.toString(),status:a.status,details:l??void 0}}}catch(a){return clearTimeout(o),a instanceof Error&&a.name==="AbortError"?{data:null,error:{message:"Request timeout",code:"TIMEOUT"}}:{data:null,error:{message:a instanceof Error?a.message:"Unknown error",code:"NETWORK_ERROR"}}}}};function m(n,e,t){let s=n,r=s?.message??s?.error;if(Array.isArray(r))return r.join("; ");if(typeof r=="string"&&r)return r;let i=r?.message;return typeof i=="string"&&i?i:t??`Request failed with status ${e}`}function d(n){return{data:null,error:{message:`NestCore: ${n} requires a NestCore console admin token and is not available with a project API key. Manage it in the NestCore console, the NestCore CLI or the MCP server.`,code:"ADMIN_ONLY"}}}var P=class{constructor(e){this.client=e}get basePath(){return`/api/project/${this.client.getProjectSlug()}/database`}async semantic(e,t,s,r={}){return this.client.request(`${this.basePath}/semantic`,{method:"POST",body:{table:e,column:t,query:s,...r}})}async query(e,t){let s=await this.client.request(`${this.basePath}/sql`,{method:"POST",body:t&&t.length>0?{sql:e,params:t}:{sql:e}});return s.error?s:{data:{rows:s.data.data||[],rowCount:s.data.rows_affected||0,fields:s.data.columns?.map(r=>({name:r.name,dataType:r.type}))},error:null}}async listTables(){return this.client.request(`${this.basePath}/tables/list`)}async getTableMetadata(e){let t=new URLSearchParams({table:e});return this.client.request(`${this.basePath}/tables?${t.toString()}`)}async getTableData(e,t={}){let s=new URLSearchParams;t.page&&s.set("page",t.page.toString()),t.limit&&s.set("limit",t.limit.toString()),t.sortBy&&s.set("sortBy",t.sortBy),t.sortOrder&&s.set("sortOrder",t.sortOrder);let r=s.toString()?`?${s.toString()}`:"",i=await this.client.request(`${this.basePath}/tables/${encodeURIComponent(e)}/data${r}`);return i.error?i:{data:{rows:i.data.data??[],total:i.data.total_rows??0},error:null}}async insert(e,t){let s=await this.client.request(`${this.basePath}/tables/${encodeURIComponent(e)}/rows`,{method:"POST",body:t});return s.error?s:{data:s.data.data?.[0]||s.data,error:null}}async update(e,t,s){let r=await this.client.request(`${this.basePath}/tables/${encodeURIComponent(e)}/rows/${encodeURIComponent(String(t))}`,{method:"PUT",body:s});return r.error?r:{data:r.data.data?.[0]??r.data,error:null}}async delete(e,t){return this.client.request(`${this.basePath}/tables/${encodeURIComponent(e)}/rows/${encodeURIComponent(String(t))}`,{method:"DELETE"})}async bulkInsert(e,t){let s=await this.client.request(`${this.basePath}/tables/${encodeURIComponent(e)}/rows/bulk`,{method:"POST",body:t});return s.error?s:{data:s.data.data??[],error:null}}async bulkUpdate(e,t){let s=await this.client.request(`${this.basePath}/tables/${encodeURIComponent(e)}/rows/bulk`,{method:"PUT",body:t});return s.error?s:{data:{updated:s.data.rows_affected??0},error:null}}async bulkDelete(e,t){let s=await this.client.request(`${this.basePath}/tables/${encodeURIComponent(e)}/rows/bulk`,{method:"DELETE",body:t});return s.error?s:{data:{deleted:s.data.rows_affected??0},error:null}}async enableRls(e){return this.client.request(`${this.basePath}/tables/${encodeURIComponent(e)}/rls/enable`,{method:"POST"})}async disableRls(e){return this.client.request(`${this.basePath}/tables/${encodeURIComponent(e)}/rls/disable`,{method:"POST"})}async createPolicy(e,t){return this.client.request(`${this.basePath}/tables/${encodeURIComponent(e)}/policies`,{method:"POST",body:t})}async listPolicies(e){let t=await this.client.request(`${this.basePath}/tables/${encodeURIComponent(e)}/policies`);return t.error?t:{data:(t.data.policies??[]).map(r=>({name:r.name,command:r.command,definition:r.using??"",...r.with_check?{check:r.with_check}:{},roles:String(r.role??"").replace(/[{}]/g,"").split(",").map(i=>i.trim()).filter(Boolean)})),error:null}}async deletePolicy(e,t){return this.client.request(`${this.basePath}/tables/${encodeURIComponent(e)}/policies/${encodeURIComponent(t)}`,{method:"DELETE"})}from(e){return new W(this,e)}},se=/^[a-zA-Z_][a-zA-Z0-9_]*$/,W=class{constructor(e,t){this.db=e;this.tableName=t;this._filters=[];this._orders=[];this._columns="*";this.ident(t)}ident(e){if(!se.test(e))throw new Error(`NestCore: unsafe SQL identifier "${e}"`);return`"${e}"`}eq(e,t){return this.push(e,"eq",t)}neq(e,t){return this.push(e,"neq",t)}gt(e,t){return this.push(e,"gt",t)}gte(e,t){return this.push(e,"gte",t)}lt(e,t){return this.push(e,"lt",t)}lte(e,t){return this.push(e,"lte",t)}like(e,t){return this.push(e,"like",t)}ilike(e,t){return this.push(e,"ilike",t)}in(e,t){return this.push(e,"in",t)}is(e,t){return this.push(e,"is",t)}textSearch(e,t,s){this.ident(e);let r=s?.config??"english";if(!se.test(r))throw new Error(`NestCore: unsafe text-search config "${r}"`);return this._filters.push({col:e,op:"fts",value:t,ftsType:s?.type??"websearch",config:r}),this}nearest(e,t,s){if(this.ident(e),!Array.isArray(t)||!t.every(i=>typeof i=="number"&&Number.isFinite(i)))throw new Error("NestCore: nearest() vector must be an array of finite numbers");let r=s?.metric==="cosine"?"<=>":s?.metric==="ip"?"<#>":"<->";return this._vectorOrder={col:e,vec:`[${t.join(",")}]`,op:r},s?.limit!=null&&(this._limit=s.limit),this}push(e,t,s){return this.ident(e),this._filters.push({col:e,op:t,value:s}),this}order(e,t){return this.ident(e),this._orders.push({col:e,asc:t?.ascending!==!1}),this}orderBy(e,t="ASC"){return this.order(e,{ascending:t==="ASC"})}limit(e){return this._limit=e,this}range(e,t){return this._offset=e,this._limit=t-e+1,this}page(e,t=20){return this._limit=t,this._offset=Math.max(0,(e-1)*t),this}build(){let e=[],s=`SELECT ${this._columns==="*"?"*":this._columns.split(",").map(o=>this.ident(o.trim())).join(", ")} FROM ${this.ident(this.tableName)}`,r=[];for(let o of this._filters){let a=this.ident(o.col);switch(o.op){case"eq":r.push(`${a} = $${e.push(o.value)}`);break;case"neq":r.push(`${a} != $${e.push(o.value)}`);break;case"gt":r.push(`${a} > $${e.push(o.value)}`);break;case"gte":r.push(`${a} >= $${e.push(o.value)}`);break;case"lt":r.push(`${a} < $${e.push(o.value)}`);break;case"lte":r.push(`${a} <= $${e.push(o.value)}`);break;case"like":r.push(`${a} LIKE $${e.push(o.value)}`);break;case"ilike":r.push(`${a} ILIKE $${e.push(o.value)}`);break;case"in":{let l=o.value??[];if(l.length===0){r.push("FALSE");break}r.push(`${a} IN (${l.map(c=>`$${e.push(c)}`).join(", ")})`);break}case"is":o.value===null?r.push(`${a} IS NULL`):r.push(`${a} = $${e.push(o.value)}`);break;case"fts":{let l=o.config??"english",c=o.ftsType==="plain"?"plainto_tsquery":o.ftsType==="phrase"?"phraseto_tsquery":"websearch_to_tsquery";r.push(`to_tsvector('${l}', ${a}::text) @@ ${c}('${l}', $${e.push(o.value)})`);break}}}r.length&&(s+=` WHERE ${r.join(" AND ")}`);let i=[];this._vectorOrder&&i.push(`${this.ident(this._vectorOrder.col)} ${this._vectorOrder.op} $${e.push(this._vectorOrder.vec)}::vector`);for(let o of this._orders)i.push(`${this.ident(o.col)} ${o.asc?"ASC":"DESC"}`);return i.length&&(s+=` ORDER BY ${i.join(", ")}`),this._limit!=null&&(s+=` LIMIT $${e.push(this._limit)}`),this._offset!=null&&(s+=` OFFSET $${e.push(this._offset)}`),{sql:s,params:e}}async select(e="*"){this._columns=e;let{sql:t,params:s}=this.build(),r=await this.db.query(t,s);return r.error?r:{data:{rows:r.data.rows,total:r.data.rows.length},error:null}}async single(e="*"){this._limit=1;let t=await this.select(e);if(t.error)return t;let s=t.data.rows[0];return s?{data:s,error:null}:{data:null,error:{message:"No rows found",code:"NOT_FOUND"}}}async maybeSingle(e="*"){this._limit=1;let t=await this.select(e);return t.error?t:{data:t.data.rows[0]??null,error:null}}async semantic(e,t,s={}){if(this.ident(e),this._vectorOrder||this._filters.some(i=>i.op==="fts"))return{data:null,error:{message:"semantic() cannot be combined with textSearch() or nearest(); use hybridColumn for keyword ranking",code:"INVALID_QUERY"}};let r=this._filters.map(i=>({column:i.col,op:i.op,value:i.value}));return this.db.semantic(this.tableName,e,t,{k:this._limit,...s,...r.length?{filters:r}:{}})}async insert(e){return this.db.insert(this.tableName,e)}async update(e,t){return this.db.update(this.tableName,e,t)}async delete(e){return this.db.delete(this.tableName,e)}};var T=class{constructor(e){this.client=e}async invoke(e,t={}){let s=`${this.client.getBaseUrl()}/api/projects/${this.client.getProjectSlug()}/functions/v1/${encodeURIComponent(e)}`,r=t.method||"POST",i=new AbortController,o=setTimeout(()=>i.abort(),this.client.getTimeout());try{let a=await this.client.authFetch(s,{method:r,headers:{"Content-Type":"application/json",...t.headers},body:t.body!==void 0&&r!=="GET"?JSON.stringify(t.body):void 0,signal:i.signal,redirect:"error"});clearTimeout(o);let l=a.headers.get("content-type")??"",c=l.includes("json")?await a.json().catch(()=>null):l.startsWith("text/")?await a.text():await a.blob(),u={};return a.headers.forEach((h,p)=>{u[p]=h}),a.ok?{data:{data:c,status:a.status,headers:u},error:null}:{data:null,error:{message:m(c,a.status),code:c?.code,status:a.status,details:c}}}catch(a){return clearTimeout(o),a instanceof Error&&a.name==="AbortError"?{data:null,error:{message:"Request timeout",code:"TIMEOUT"}}:{data:null,error:{message:a instanceof Error?a.message:"Unknown error",code:"NETWORK_ERROR"}}}}};var v=class{constructor(e){this.client=e}async create(e){return d("client.jobs")}async list(){return d("client.jobs")}async get(e){return d("client.jobs")}async update(e,t){return d("client.jobs")}async delete(e){return d("client.jobs")}async trigger(e){return d("client.jobs")}async getRuns(e,t){return d("client.jobs")}};function H(){let n=new Map;return{getItem:e=>n.has(e)?n.get(e):null,setItem:(e,t)=>{n.set(e,t)},removeItem:e=>{n.delete(e)}}}function re(){let n=null;try{if(n=typeof globalThis<"u"?globalThis.localStorage??null:null,n){let t="__nestcore_probe__";n.setItem(t,"1"),n.removeItem(t)}}catch{n=null}if(!n)return H();let e=n;return{getItem:t=>{try{return e.getItem(t)}catch{return null}},setItem:(t,s)=>{try{e.setItem(t,s)}catch{}},removeItem:t=>{try{e.removeItem(t)}catch{}}}}var q={getItem:()=>null,setItem:()=>{},removeItem:()=>{}},ne={getItem:n=>{try{return K()?.getItem(n)??null}catch{return null}},setItem:(n,e)=>{try{K()?.setItem(n,e)}catch{}},removeItem:n=>{try{K()?.removeItem(n)}catch{}}};function K(){try{return globalThis.localStorage??null}catch{return null}}function V(n){return!!n&&typeof n=="object"&&n.mfa_required===!0}var ke="nestcore.session",we="orbitnest.session",Se=30,_e={data:null,error:{message:"No active session",code:"NO_SESSION"}},k=class{constructor(e,t={}){this.client=e;this._session=null;this.refreshing=null;this.listeners=new Set;this.storage=t.storage??q,this.storageKey=`${ke}.${this.client.getProjectSlug()}`;let s=this.storage.getItem(this.storageKey);if(s===null){let r=`${we}.${this.client.getProjectSlug()}`;try{s=this.storage.getItem(r),s!==null&&(this.storage.setItem(this.storageKey,s),this.storage.removeItem(r))}catch{}}if(s)try{this._session=JSON.parse(s)}catch{this.storage.removeItem(this.storageKey)}}get session(){return this._session}set session(e){this._session=Ce(e);try{e?this.storage.setItem(this.storageKey,JSON.stringify(this._session)):this.storage.removeItem(this.storageKey)}catch{}for(let t of this.listeners)try{t(this._session)}catch{}}onAuthStateChange(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}async getAccessToken(){let e=this.session;return e?.access_token?e.expires_at&&e.expires_at-Se<=Date.now()/1e3?(await this.refreshSession()).data?.access_token??this.session?.access_token??null:e.access_token:null}async refreshAccessToken(e){let t=this.session?.access_token;return t?t!==e?t:(await this.refreshSession()).data?.access_token??null:null}async withToken(e){let t=await this.getAccessToken();return t?e(t):_e}get basePath(){return`/api/projects/${this.client.getProjectSlug()}/auth`}getSession(){return this.session}getUser(){return this.session?.user||null}async signUp(e){return await this.client.requestPublic(`${this.basePath}/signup`,{method:"POST",body:{email:e.email,password:e.password,user_metadata:e.metadata}})}async verifySignUp(e){let t=await this.client.requestPublic(`${this.basePath}/verify-signup`,{method:"POST",body:{email:e.email,code:e.code}});return t.data&&(this.session=t.data),t}async signIn(e){let t=await this.client.requestPublic(`${this.basePath}/signin`,{method:"POST",body:{email:e.email,password:e.password}});return t.data&&!V(t.data)&&(this.session=t.data),t}async verifyMfa(e,t){let s=await this.client.requestPublic(`${this.basePath}/verify-mfa`,{method:"POST",body:{challenge_token:e,code:t}});return s.data&&(this.session=s.data),s}async signInWithSms(e){return this.client.requestPublic(`${this.basePath}/sms/send-otp`,{method:"POST",body:{phone:e}})}async verifySmsOtp(e,t){let s=await this.client.requestPublic(`${this.basePath}/sms/verify-otp`,{method:"POST",body:{phone:e,code:t}});return s.data&&(this.session=s.data),s}async signOut(){let e=await this.getAccessToken(),t=e?await this.client.requestWithToken(`${this.basePath}/signout`,e,{method:"POST"}):{data:{success:!0},error:null};return this.session=null,t}async refreshSession(){let e=this.session?.refresh_token;return e?(this.refreshing??(this.refreshing=this.client.requestPublic(`${this.basePath}/refresh`,{method:"POST",body:{refresh_token:e}}).then(t=>(t.data?this.session=t.data:t.error.status===401&&(this.session=null),t)).finally(()=>{this.refreshing=null})),this.refreshing):{data:null,error:{message:"No refresh token available",code:"NO_SESSION"}}}async resetPasswordForEmail(e){return this.client.requestPublic(`${this.basePath}/recover-password`,{method:"POST",body:{email:e.email}})}async updatePassword(e){return this.client.requestPublic(`${this.basePath}/reset-password`,{method:"POST",body:{email:e.email,code:e.token,new_password:e.password}})}async getProfile(){return this.withToken(e=>this.client.requestWithToken(`${this.basePath}/user`,e))}async updateUser(e){let{metadata:t,...s}=e,r=await this.withToken(o=>this.client.requestWithToken(`${this.basePath}/user`,o,{method:"PUT",body:t===void 0?s:{...s,data:t}}));if(r.error)return r;let i=r.data.user;return this.session&&i&&(this.session={...this.session,user:i}),{data:i,error:null}}async verifyEmailChange(e){let t=await this.withToken(r=>this.client.requestWithToken(`${this.basePath}/user/email/verify`,r,{method:"POST",body:{code:e}}));if(t.error)return t;let s=t.data.user;return this.session&&s&&(this.session={...this.session,user:s}),{data:s,error:null}}async deleteUser(){let e=await this.withToken(t=>this.client.requestWithToken(`${this.basePath}/user`,t,{method:"DELETE"}));return e.data&&(this.session=null),e}setSession(e){this.session=e}async registerPasskeyOptions(e={}){return this.withToken(t=>this.client.requestWithToken(`${this.basePath}/passkey/register/options`,t,{method:"POST",body:{device_name:e.device_name}}))}async registerPasskeyVerify(e){return this.withToken(t=>this.client.requestWithToken(`${this.basePath}/passkey/register/verify`,t,{method:"POST",body:e}))}async signUpWithPasskeyOptions(e){return this.client.requestPublic(`${this.basePath}/passkey/signup/options`,{method:"POST",body:e})}async signUpWithPasskeyVerify(e){let t=await this.client.requestPublic(`${this.basePath}/passkey/signup/verify`,{method:"POST",body:e});return t.data&&(this.session=t.data),t}async signInWithPasskeyOptions(e={}){return this.client.requestPublic(`${this.basePath}/passkey/login/options`,{method:"POST",body:e.identifier?{identifier:e.identifier}:{}})}async signInWithPasskeyVerify(e){let t=await this.client.requestPublic(`${this.basePath}/passkey/login/verify`,{method:"POST",body:e});return t.data&&(this.session=t.data),t}async listPasskeys(){return this.withToken(e=>this.client.requestWithToken(`${this.basePath}/passkey/devices`,e))}async renamePasskey(e,t){return this.withToken(s=>this.client.requestWithToken(`${this.basePath}/passkey/devices/${encodeURIComponent(e)}`,s,{method:"PATCH",body:{device_name:t}}))}async revokePasskey(e){return this.withToken(t=>this.client.requestWithToken(`${this.basePath}/passkey/devices/${encodeURIComponent(e)}`,t,{method:"DELETE"}))}async enrollMfaTotp(e,t){return this.withToken(s=>this.client.requestWithToken(`${this.basePath}/mfa/totp/enroll`,s,{method:"POST",body:{friendly_name:e,code:t}}))}async verifyMfaEnrollment(e,t){return this.withToken(s=>this.client.requestWithToken(`${this.basePath}/mfa/totp/verify`,s,{method:"POST",body:{factor_id:e,code:t}}))}async regenerateMfaRecoveryCodes(e){return this.withToken(t=>this.client.requestWithToken(`${this.basePath}/mfa/recovery-codes`,t,{method:"POST",body:{code:e}}))}async listMfaFactors(){return this.withToken(e=>this.client.requestWithToken(`${this.basePath}/mfa/factors`,e))}async unenrollMfa(e,t){return this.withToken(s=>this.client.requestWithToken(`${this.basePath}/mfa/factors/${encodeURIComponent(e)}`,s,{method:"DELETE",body:{code:t}}))}};function Ce(n){return!n||n.expires_at||!n.expires_in?n:{...n,expires_at:Math.floor(Date.now()/1e3)+n.expires_in}}var w=class{constructor(e){this.client=e}async getLogs(e={}){return d("client.logs")}async getDatabaseLogs(e={}){return d("client.logs")}async getSlowQueryLogs(e={}){return d("client.logs")}async getAuthLogs(e={}){return d("client.logs")}async getAuthFailures(e={}){return d("client.logs")}async getEdgeFunctionLogs(e,t={}){return d("client.logs")}};var S=class{constructor(e){this.client=e}async list(){return d("client.env")}async get(e){return d("client.env")}async set(e,t,s={}){return d("client.env")}async create(e,t,s={}){return d("client.env")}async bulkCreate(e){return d("client.env")}async delete(e){return d("client.env")}};function z(n,e){return!n||typeof n!="string"||n.trim().length===0?{data:null,error:{message:`${e} is required and must be a non-empty string`,code:"VALIDATION_ERROR"}}:null}function g(n,e="path"){let t=z(n,e);if(t)return t;if(n.includes("\0"))return{data:null,error:{message:`${e} must not contain null bytes`,code:"VALIDATION_ERROR"}};let s=n.split("/");for(let r of s)if(r==="..")return{data:null,error:{message:`${e} must not contain path traversal sequences`,code:"VALIDATION_ERROR"}};return null}function ie(n){return n.replace(/\\/g,"/").split("/").filter(e=>e!==".."&&e!==""&&e!==".").join("/")}function oe(n){return n.split("/").filter(e=>e.length>0).map(e=>encodeURIComponent(e)).join("/")}function Ee(n){if(!n)return"";let e=new URLSearchParams;return n.width&&e.set("width",String(n.width)),n.height&&e.set("height",String(n.height)),n.format&&e.set("format",n.format),n.quality&&e.set("quality",String(n.quality)),n.fit&&e.set("fit",n.fit),e.toString()}var Oe={png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif",webp:"image/webp",avif:"image/avif",svg:"image/svg+xml",ico:"image/x-icon",pdf:"application/pdf",json:"application/json",txt:"text/plain",csv:"text/csv",html:"text/html",css:"text/css",js:"text/javascript",mp4:"video/mp4",webm:"video/webm",mp3:"audio/mpeg",wav:"audio/wav",zip:"application/zip"};function $e(n){let e=n.split(".").pop()?.toLowerCase()??"";return Oe[e]}function Q(n){if(n.error)return n;let e=n.data;return{data:e?.data??e,error:null}}var _=class{constructor(e){this.client=e}from(e){return new j(this.client,e)}},j=class{constructor(e,t){this.client=e;this.bucket=t}get basePath(){return`/api/project/${this.client.getProjectSlug()}/storage/${this.bucket}`}absoluteUrl(e){return`${this.client.getBaseUrl()}${e}`}async upload(e,t,s){let r=g(e);if(r)return r;let i=new FormData,o=s?.contentType||t instanceof Blob&&t.type||$e(e)||"application/octet-stream",a=new Blob([t],{type:o});i.append("file",a,e.split("/").pop()||"file"),i.append("path",e),s?.upsert&&i.append("upsert","true");let l=this.absoluteUrl(`${this.basePath}/upload`),c=new AbortController,u=setTimeout(()=>c.abort(),3e4);try{let h=await this.client.authFetch(l,{method:"POST",body:i,redirect:"error",signal:c.signal});clearTimeout(u);let p=await h.json().catch(()=>null);return h.ok?{data:p?.data??p,error:null}:{data:null,error:{message:m(p,h.status,"Upload failed"),code:p?.code,status:h.status,details:p??void 0}}}catch(h){return clearTimeout(u),h instanceof Error&&h.name==="AbortError"?{data:null,error:{message:"Upload timeout",code:"TIMEOUT"}}:{data:null,error:{message:h instanceof Error?h.message:"Upload failed",code:"UPLOAD_ERROR"}}}}async download(e){let t=g(e);if(t)return t;let s=this.absoluteUrl(`${this.basePath}/download/${oe(e)}`),r=new AbortController,i=setTimeout(()=>r.abort(),3e4);try{let o=await this.client.authFetch(s,{redirect:"error",signal:r.signal});if(clearTimeout(i),!o.ok){let l=await o.json().catch(()=>null);return{data:null,error:{message:m(l,o.status,"Download failed"),code:l?.code,status:o.status,details:l??void 0}}}return{data:await o.blob(),error:null}}catch(o){return clearTimeout(i),o instanceof Error&&o.name==="AbortError"?{data:null,error:{message:"Download timeout",code:"TIMEOUT"}}:{data:null,error:{message:o instanceof Error?o.message:"Download failed",code:"DOWNLOAD_ERROR"}}}}async remove(e){for(let t of e){let s=g(t);if(s)return s}return Q(await this.client.request(this.basePath,{method:"DELETE",body:{paths:e}}))}async list(e,t){let s=new URLSearchParams;e&&s.set("prefix",e),t?.limit&&s.set("limit",t.limit.toString());let r=s.toString()?`?${s.toString()}`:"";return Q(await this.client.request(`${this.basePath}${r}`))}getPublicUrl(e,t){let s=g(e);if(s)throw new Error(`NestCore: ${s.error?.message??"invalid storage path"}`);let r=this.client.getBaseUrl(),i=this.client.getProjectSlug(),o=`${r}/api/public/${i}/storage/${this.bucket}/${oe(e)}`,a=Ee(t?.transform);return a&&(o+=`?${a}`),{data:{publicUrl:o}}}async createBucket(e={}){return Q(await this.client.request(`${this.basePath}/create`,{method:"POST",body:e.public===void 0?void 0:{public:e.public}}))}};var M=class{constructor(e,t){this.channelName=e;this.client=t;this.state={};this.syncCbs=[];this.joinCbs=[];this.leaveCbs=[]}async track(e){await this.client.sendPresenceTrack(this.channelName,e)}async untrack(){this.client.sendPresenceUntrack(this.channelName)}getState(){return{...this.state}}_hasListeners(){return this.syncCbs.length+this.joinCbs.length+this.leaveCbs.length>0}onSync(e){return this.syncCbs.push(e),this}onJoin(e){return this.joinCbs.push(e),this}onLeave(e){return this.leaveCbs.push(e),this}_handleStateUpdate(e){let t=this.state;for(let[s,r]of Object.entries(e))if(!t[s])for(let i of this.joinCbs)i(s,r);for(let[s,r]of Object.entries(t))if(!e[s])for(let i of this.leaveCbs)i(s,r);this.state={...e};for(let s of this.syncCbs)s({...this.state})}},D=class{constructor(e,t){this.name=e;this.client=t;this.handlers=[];this._joined=!1;this.presence=new M(e,t)}on(e,t,s){return this.handlers.push({type:e,opts:t,callback:s}),this}subscribe(e){return this.statusCb=e,this._joined=!0,this.client.registerChannel(this),this}async send(e,t){await this.client.sendBroadcast(this.name,e,t)}async unsubscribe(){await this.client.unregisterChannel(this.name)}get channelName(){return this.name}_activate(e){for(let t of this._tableKeys()){let[s,r]=ce(t);this.client.syncTable(e,s,r)}this._hasBroadcast()&&e.send(JSON.stringify({id:`${this.name}-bc-${Math.random().toString(36).slice(2)}`,type:"subscribe",channel:`broadcast:${this.name}`})),this.statusCb?.("connected")}_tableKeys(){if(!this._joined)return[];let e=this.handlers.filter(t=>t.type==="postgres_changes").map(t=>`${t.opts.schema??"public"}.${t.opts.table}`);return[...new Set(e)]}_tableHandlers(e,t){return this._joined?this.handlers.filter(s=>s.type==="postgres_changes").map(s=>s.opts).filter(s=>(s.schema??"public")===e&&s.table===t):[]}_hasBroadcast(){return this.handlers.some(e=>e.type==="broadcast")||this.presence._hasListeners()||!this.handlers.some(e=>e.type==="postgres_changes")}_setStatus(e,t){this.statusCb?.(e,t)}_dispatch(e){if(e.type==="db_event"){let t={op:e.op,schema:e.schema,table:e.table,new:e.new,old:e.old,commit_ts:e.commit_ts};for(let s of this.handlers){if(s.type!=="postgres_changes")continue;let r=s.opts,i=le(r.event);!i.includes(e.op)&&!i.includes("*")||r.table&&r.table!==e.table||r.schema&&r.schema!==e.schema||je(e.op==="DELETE"?e.old:e.new,r.filter)&&s.callback(t)}}else if(e.type==="broadcast"){let t={event:e.event,payload:e.payload};for(let s of this.handlers){if(s.type!=="broadcast")continue;let r=s.opts;r.event!=="*"&&r.event!==e.event||s.callback(t)}}else e.type==="presence.state"&&this.presence._handleStateUpdate(e.presences??{})}},xe=0,f=1,ae=1e3,Ie=1e4,Ue=6e4,qe=4029,C=class{constructor(e,t={}){this.url=e;this.options=t;this.ws=null;this.channels=new Map;this.reconnectDelay=ae;this.maxReconnectDelay=Ue;this.shouldReconnect=!0;this.connectPromise=null;this.reconnectTimer=null;this.authChanged=!1;this.authRetried=!1}channel(e){return this.channels.has(e)||this.channels.set(e,new D(e,this)),this.channels.get(e)}setAuth(e){if(this.options.accessToken||(this.options.userJwt=e??void 0),!((e??void 0)===this.socketJwt||!this.ws)){if(this.ws.readyState===xe){this.authChanged=!0;return}this.reopen()}}disconnect(){this.shouldReconnect=!1,this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null),this.ws?.close(1e3,"client disconnect"),this.ws=null,this.channels.clear()}connect(){return this.connectPromise?this.connectPromise:this.ws?.readyState===f?Promise.resolve():(this.connectPromise=this.resolveUserJwt().then(e=>new Promise((t,s)=>{let r=this.options.WebSocket??globalThis.WebSocket;if(!r){s(new Error('No WebSocket implementation found. On Node.js < 22, pass a WebSocket constructor via options.WebSocket (e.g. from the "ws" package).'));return}let i=["orbitnest-realtime-v1"];this.socketJwt=e,e&&i.push(`orbitnest.user-jwt.${e}`);let o;this.options.apiKey&&(i.push(`orbitnest.apikey.${this.options.apiKey}`),o={headers:{Authorization:`Bearer ${this.options.apiKey}`}});let a=new r(this.url,i,o);a.onopen=()=>{if(this.reconnectDelay=ae,this.connectPromise=null,t(),this.authChanged){this.authChanged=!1,this.reopen();return}for(let l of this.channels.values())l._joined&&l._activate(a)},a.onmessage=l=>{try{let c=JSON.parse(typeof l.data=="string"?l.data:l.data.toString());this.route(c)}catch{}},a.onerror=l=>{let c=new Error(l?.message??"WebSocket error");for(let u of this.channels.values())u._setStatus("error",c);this.connectPromise=null,s(c)},a.onclose=l=>{this.connectPromise=null;for(let u of this.channels.values())u._setStatus("disconnected");let c=l?.code;if((c===1e3||c===1001||c===4001)&&(this.shouldReconnect=!1),c===4001&&this.socketJwt&&!this.authRetried&&this.options.onAuthRejected&&(this.authRetried=!0,this.options.onAuthRejected(this.socketJwt)),this.shouldReconnect){(c===qe||c===1008||c===1013)&&(this.reconnectDelay=Math.max(this.reconnectDelay,Ie));let u=Math.floor(Math.random()*500),h=Math.min(this.reconnectDelay+u,this.maxReconnectDelay);this.reconnectTimer&&clearTimeout(this.reconnectTimer),this.reconnectTimer=setTimeout(()=>this.reconnect(),h),this.reconnectDelay=Math.min(this.reconnectDelay*2,this.maxReconnectDelay)}},this.ws=a})),this.connectPromise)}async resolveUserJwt(){if(!this.options.accessToken)return this.options.userJwt;try{return await this.options.accessToken()??void 0}catch{return}}reopen(){let e=this.ws;e&&(e.onclose=null,e.onerror=null,e.onmessage=null,e.close(1e3,"auth changed")),this.ws=null,this.connectPromise=null,[...this.channels.values()].some(t=>t._joined)&&(this.shouldReconnect=!0,this.connect().catch(()=>{}))}syncTable(e,t,s){let r=[...this.channels.values()].flatMap(a=>a._tableHandlers(t,s));if(r.length===0)return;let i=[...new Set(r.flatMap(a=>le(a.event)))],o=new Set(r.map(a=>JSON.stringify(a.filter??null))).size===1;e.send(JSON.stringify({id:`rt-${Math.random().toString(36).slice(2)}`,type:"subscribe",channel:`table:${t}.${s}`,events:i,filter:o?r[0].filter:void 0}))}reconnect(){this.reconnectTimer=null,this.connectPromise=null,this.ws=null,this.shouldReconnect&&[...this.channels.values()].some(e=>e._joined)&&this.connect().catch(()=>{})}route(e){if(e.type==="system"&&e.event==="connected"&&(this.authRetried=!1),e.type==="db_event")for(let t of this.channels.values())t._dispatch(e);else if(e.type==="broadcast")for(let t of this.channels.values())`broadcast:${t.channelName}`===e.channel&&t._dispatch(e);else if(e.type==="presence.state"){let t=e.channel?.replace(/^broadcast:/,"");if(t){let s=this.channels.get(t);s&&s._dispatch(e)}}}registerChannel(e){if(this.channels.set(e.channelName,e),this.shouldReconnect=!0,e._setStatus("connecting"),this.ws?.readyState===f){e._activate(this.ws);return}this.connect().catch(t=>e._setStatus("error",t))}async unregisterChannel(e){let t=this.channels.get(e);if(!t)return;let s=t._tableKeys();t._joined=!1,this.channels.delete(e);let r=this.ws;if(r?.readyState===f){let i=o=>r.send(JSON.stringify({id:`unsub-${Math.random().toString(36).slice(2)}`,type:"unsubscribe",channel:o}));for(let o of s){let[a,l]=ce(o);[...this.channels.values()].some(u=>u._tableHandlers(a,l).length>0)?this.syncTable(r,a,l):i(`table:${o}`)}t._hasBroadcast()&&i(`broadcast:${e}`)}[...this.channels.values()].some(i=>i._joined)||this.ws?.close(1e3,"no channels")}async sendBroadcast(e,t,s){if(await this.connect(),this.ws?.readyState!==f)throw new Error("Not connected");this.ws.send(JSON.stringify({id:`bc-${Math.random().toString(36).slice(2)}`,type:"broadcast",channel:`broadcast:${e}`,event:t,payload:s}))}async sendPresenceTrack(e,t){if(await this.connect(),this.ws?.readyState!==f)throw new Error("Not connected");this.ws.send(JSON.stringify({id:`pt-${Math.random().toString(36).slice(2)}`,type:"presence.track",channel:`broadcast:${e}`,state:t}))}sendPresenceUntrack(e){this.ws?.readyState===f&&this.ws.send(JSON.stringify({id:`pu-${Math.random().toString(36).slice(2)}`,type:"presence.untrack",channel:`broadcast:${e}`}))}};function le(n){if(n==="*")return["INSERT","UPDATE","DELETE"];let e=Array.isArray(n)?n:[n];return e.includes("*")?["INSERT","UPDATE","DELETE"]:e}function ce(n){let e=n.indexOf(".");return[n.slice(0,e),n.slice(e+1)]}function je(n,e){if(!e||!n)return!0;for(let[t,s]of Object.entries(e)){let r=n[t];if(s.eq!==void 0&&r!=s.eq||s.neq!==void 0&&r==s.neq||s.in!==void 0&&!s.in.some(i=>i==r)||s.gt!==void 0&&!(r>s.gt)||s.lt!==void 0&&!(r<s.lt))return!1;if(s.like!==void 0){let i=s.like.replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace(/%/g,".*").replace(/_/g,".");if(!new RegExp(`^${i}$`,"s").test(String(r)))return!1}}return!0}var G="nestcore_anonymous_id",Y="nestcore_session_id",X="nestcore_session_last_activity",Me={[G]:"orbitnest_anonymous_id",[Y]:"orbitnest_session_id",[X]:"orbitnest_session_last_activity"},De=1800*1e3;function b(){if(typeof crypto<"u"&&typeof crypto.randomUUID=="function")return crypto.randomUUID();if(typeof crypto<"u"&&typeof crypto.getRandomValues=="function"){let n=new Uint8Array(16);crypto.getRandomValues(n),n[6]=n[6]&15|64,n[8]=n[8]&63|128;let e=Array.from(n,t=>t.toString(16).padStart(2,"0")).join("");return`${e.slice(0,8)}-${e.slice(8,12)}-${e.slice(12,16)}-${e.slice(16,20)}-${e.slice(20)}`}return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,n=>{let e=Math.random()*16|0;return(n==="x"?e:e&3|8).toString(16)})}function Ne(){try{if(typeof localStorage>"u")return null;let n="__on_ls_probe__";return localStorage.setItem(n,"1"),localStorage.removeItem(n),localStorage}catch{return null}}function Z(n,e){let t=n.getItem(e);if(t!==null)return t;let s=Me[e],r=s?n.getItem(s):null;return r===null||!s?null:(n.setItem(e,r),n.removeItem(s),r)}function Le(){return typeof window<"u"&&typeof document<"u"?"web":"node"}function Fe(n){if(!n)return b();try{let e=Z(n,G);return e||(e=b(),n.setItem(G,e)),e}catch{return b()}}function Be(n,e){if(!n)return e;try{let t=Date.now(),s=parseInt(Z(n,X)??"0",10)||0,r=Z(n,Y);return(!r||t-s>De)&&(r=b(),n.setItem(Y,r)),n.setItem(X,String(t)),r}catch{return e}}var E=class{constructor(e,t={}){this.client=e;this.queue=[];this.flushTimer=null;this.storage=Ne(),this.anonymousId=Fe(this.storage),this.fallbackSessionId=b(),this.platform=t.platform??Le(),this.appVersion=t.appVersion,this.flushInterval=t.flushInterval??5e3,this.maxBatchSize=Math.min(t.maxBatchSize??50,500),typeof window<"u"&&typeof document<"u"&&window.addEventListener&&(window.addEventListener("pagehide",()=>this.flushInBackground(!0)),document.addEventListener("visibilitychange",()=>{document.visibilityState==="hidden"&&this.flushInBackground(!0)}))}identify(e,t){this.userId=e,this.enqueue("identify",t)}track(e,t){this.enqueue(e,t)}screen(e,t){this.enqueue("screen_view",{screen:e,...t})}crash(e,t){let s=e instanceof Error?e.message:e,r=e instanceof Error?e.stack:void 0;this.enqueue("crash",{...e instanceof Error?{error_type:e.name}:{},error_message:s,...r?{stack_trace:r}:{},...t})}async flush(e=!1){if(this.clearFlushTimer(),this.queue.length===0)return{data:{accepted:0,rejected:0,errors:[]},error:null};let t=this.queue.splice(0,this.queue.length),s=await this.client.requestForAnalytics("/api/analytics/events",{method:"POST",body:{events:t},keepalive:e}),r=s.error?.status;return s.error&&(r===void 0||r===429||r>=500)&&(this.queue=[...t,...this.queue].slice(-1e3),e||this.scheduleFlush()),s}flushInBackground(e=!1){this.flush(e).then(t=>{let s=t.error?.status;t.error&&s!==void 0&&s!==429&&s<500&&console.warn(`[nestcore] analytics events rejected (${s}): ${t.error.message}`)})}enqueue(e,t){let s={event_id:b(),event:e,anonymous_id:this.anonymousId,platform:this.platform,timestamp:new Date().toISOString(),session_id:Be(this.storage,this.fallbackSessionId),...this.userId?{user_id:this.userId}:{},...this.appVersion?{app_version:this.appVersion}:{},...t?{properties:t}:{}};this.queue.push(s),this.queue.length>=this.maxBatchSize?this.flushInBackground():this.scheduleFlush()}scheduleFlush(){this.flushTimer===null&&(this.flushTimer=setTimeout(()=>{this.flushTimer=null,this.flushInBackground()},this.flushInterval))}clearFlushTimer(){this.flushTimer!==null&&(clearTimeout(this.flushTimer),this.flushTimer=null)}};async function*N(n){let e=n.getReader(),t=new TextDecoder,s="";try{for(;;){let{value:r,done:i}=await e.read();if(i)break;s+=t.decode(r,{stream:!0});let o;for(;(o=s.indexOf(`
2
+ `))>=0;){let a=s.slice(0,o).replace(/\r$/,"");s=s.slice(o+1),a.startsWith("data:")&&(yield a.slice(5).trimStart())}}s.startsWith("data:")&&(yield s.slice(5).trimStart())}finally{await e.cancel().catch(()=>{})}}var O=class{constructor(e){this.client=e}path(e=""){return`/api/project/${this.client.getProjectSlug()}/ai/v1/memory${e}`}add(e,t={}){return this.client.request(this.path(),{method:"POST",body:{content:e,...t}})}search(e,t={}){return this.client.request(this.path("/search"),{method:"POST",body:ue(e,t)})}addMany(e){return this.client.request(this.path("/batch/add"),{method:"POST",body:{items:e}})}searchMany(e){return this.client.request(this.path("/batch/search"),{method:"POST",body:{queries:e}})}forgetMany(e){return this.client.request(this.path("/batch/forget"),{method:"POST",body:e})}list(e={}){return this.client.request(this.path(I(e)))}get(e){return this.client.request(this.path(`/${encodeURIComponent(e)}`))}update(e,t){return this.client.request(this.path(`/${encodeURIComponent(e)}`),{method:"PATCH",body:t})}remove(e){return this.client.request(this.path(`/${encodeURIComponent(e)}`),{method:"DELETE"})}forget(e){return this.client.request(this.path("/forget"),{method:"POST",body:e?{subject:e}:{}})}subjects(e={}){return this.client.request(this.path(`/subjects${I(e)}`))}reembed(e={}){return this.client.request(this.path("/reembed"),{method:"POST",body:e})}},L=class{constructor(e,t){this.client=e;this.name=t}path(e=""){return`/api/project/${this.client.getProjectSlug()}/ai/v1/collections/${encodeURIComponent(this.name)}${e}`}async ingest(e,t={}){let{wait:s,...r}=t,i=await this.client.request(this.path("/documents"),{method:"POST",body:{...e,...r}});return i.error||!s?i:this.waitFor(i.data.id,typeof s=="object"?s:{})}addChunks(e,t){return this.client.request(this.path("/documents"),{method:"POST",body:{chunks:e,...t}})}async waitFor(e,{timeoutMs:t=12e4,intervalMs:s=1e3}={}){let r=Date.now()+t;for(;;){let i=await this.getDocument(e);if(i.error||i.data.status==="ready"||i.data.status==="failed")return i;if(Date.now()>r)return{data:null,error:{message:`Document ${e} is still ${i.data.status}`,code:"TIMEOUT"}};await new Promise(o=>setTimeout(o,s))}}search(e,t={}){return this.client.request(this.path("/search"),{method:"POST",body:ue(e,t)})}listDocuments(e={}){return this.client.request(this.path(`/documents${I(e)}`))}getDocument(e){return this.client.request(this.path(`/documents/${encodeURIComponent(e)}`))}remove(e){return this.client.request(this.path(`/documents/${encodeURIComponent(e)}`),{method:"DELETE"})}stats(){return this.client.request(this.path("/stats"))}},$=class{constructor(e){this.client=e}path(e=""){return`/api/project/${this.client.getProjectSlug()}/ai/v1/collections${e}`}from(e){return new L(this.client,e)}create(e){return this.client.request(this.path(),{method:"POST",body:e})}list(){return this.client.request(this.path())}get(e){return this.client.request(this.path(`/${encodeURIComponent(e)}`))}update(e,t){return this.client.request(this.path(`/${encodeURIComponent(e)}`),{method:"PATCH",body:t})}delete(e){return this.client.request(this.path(`/${encodeURIComponent(e)}`),{method:"DELETE"})}},F=class{constructor(e,t){this.client=e;this.id=t}path(e=""){return`/api/project/${this.client.getProjectSlug()}/ai/v1/threads/${encodeURIComponent(this.id)}${e}`}get(){return this.client.request(this.path())}update(e){return this.client.request(this.path(),{method:"PATCH",body:e})}delete(){return this.client.request(this.path(),{method:"DELETE"})}messages(e={}){return this.client.request(this.path(`/messages${I(e)}`))}append(e,t={}){return this.client.request(this.path("/messages"),{method:"POST",body:{content:e,...t}})}async*run(e={},{signal:t}={}){let s;try{s=await this.client.authFetch(`${this.client.getBaseUrl()}${this.path("/run")}`,{method:"POST",headers:{"Content-Type":"application/json",Accept:"text/event-stream"},body:JSON.stringify({...e,stream:!0}),signal:t,redirect:"error"})}catch(r){yield{type:"error",code:"NETWORK_ERROR",message:r instanceof Error?r.message:"Network error"};return}if(!s.ok||!s.body){let r=await s.json().catch(()=>null);yield{type:"error",code:r?.code,message:m(r,s.status),status:s.status,...r&&typeof r=="object"?{details:r}:{}};return}try{for await(let r of N(s.body))yield JSON.parse(r)}catch(r){yield{type:"error",code:"STREAM_ERROR",message:r instanceof Error?r.message:"Stream interrupted"}}}runOnce(e={}){return this.client.request(this.path("/run"),{method:"POST",body:{...e,stream:!1},timeout:18e4})}},x=class{constructor(e){this.client=e}path(e=""){return`/api/project/${this.client.getProjectSlug()}/ai/v1/threads${e}`}from(e){return new F(this.client,e)}create(e={}){return this.client.request(this.path(),{method:"POST",body:e})}list(e={}){return this.client.request(this.path(I(e)))}get(e){return this.from(e).get()}delete(e){return this.from(e).delete()}};function ue(n,e){return n!==null&&typeof n=="object"?{...n}:typeof n=="string"?{query:n,...e}:{...e}}function I(n){let e=Object.entries(n).filter(([,t])=>t!=null).map(([t,s])=>`${encodeURIComponent(t)}=${encodeURIComponent(String(s))}`);return e.length?`?${e.join("&")}`:""}var U=class{constructor(e){this.client=e;this.threads=new x(e)}path(e){return`/api/project/${this.client.getProjectSlug()}/ai/v1/${e}`}get openaiBaseUrl(){return`${this.client.getBaseUrl()}/api/project/${this.client.getProjectSlug()}/ai/openai/v1`}body(e,t){return{model:e.model,provider:e.provider,messages:e.messages.map(s=>({role:s.role,content:s.content,...s.toolCalls?{tool_calls:s.toolCalls}:{},...s.toolCallId?{tool_call_id:s.toolCallId}:{}})),temperature:e.temperature,max_tokens:e.maxTokens,tools:e.tools,tool_choice:e.toolChoice,stream:t}}async chat(e){return this.client.request(this.path("chat"),{method:"POST",body:this.body(e,!1),timeout:12e4})}async*chatStream(e,{signal:t}={}){let s;try{s=await this.client.authFetch(`${this.client.getBaseUrl()}${this.path("chat")}`,{method:"POST",headers:{"Content-Type":"application/json",Accept:"text/event-stream"},body:JSON.stringify(this.body(e,!0)),signal:t,redirect:"error"})}catch(r){yield{type:"error",code:"NETWORK_ERROR",message:r instanceof Error?r.message:"Network error"};return}if(!s.ok||!s.body){let r=await s.json().catch(()=>null);yield{type:"error",code:r?.code,message:m(r,s.status),status:s.status,...r&&typeof r=="object"?{details:r}:{}};return}try{for await(let r of N(s.body))yield JSON.parse(r)}catch(r){yield{type:"error",code:"STREAM_ERROR",message:r instanceof Error?r.message:"Stream interrupted"}}}async embed(e,t={}){return this.client.request(this.path("embeddings"),{method:"POST",body:{input:e,...t}})}async credits(){return this.client.request(this.path("credits"))}async models(){return this.client.request(this.path("models"))}async traces(e={}){let t=Object.entries(e).filter(([,s])=>s!==void 0).map(([s,r])=>`${s}=${encodeURIComponent(String(r))}`).join("&");return this.client.request(this.path(`traces${t?`?${t}`:""}`))}};var Je={int2:"number",int4:"number",int8:"number",smallint:"number",integer:"number",bigint:"number",serial:"number",bigserial:"number",numeric:"number",decimal:"number",real:"number",float4:"number",float8:"number","double precision":"number",bool:"boolean",boolean:"boolean",text:"string",varchar:"string","character varying":"string",char:"string",character:"string",bpchar:"string",citext:"string",uuid:"string",name:"string",date:"string",timestamp:"string",timestamptz:"string","timestamp with time zone":"string","timestamp without time zone":"string",time:"string",timetz:"string",interval:"string","time without time zone":"string","time with time zone":"string",json:"Record<string, unknown>",jsonb:"Record<string, unknown>",bytea:"string",vector:"string"};function ee(n){let e=(n||"").toLowerCase().trim();return e?e.endsWith("[]")?`${ee(e.slice(0,-2))}[]`:e.startsWith("_")?`${ee(e.slice(1))}[]`:Je[e]??"unknown":"unknown"}function We(n){return n.replace(/(^|[_\- ])([a-zA-Z0-9])/g,(e,t,s)=>s.toUpperCase()).replace(/[^a-zA-Z0-9]/g,"")}function Ke(n){return/^[a-zA-Z_$][\w$]*$/.test(n)?n:JSON.stringify(n)}async function de(n,e={}){let t=await n.listTables();if(t.error)throw new Error(`generateTypes: could not list tables: ${t.error.message}`);let s=t.data,r=Array.isArray(s)?s.map(u=>typeof u=="string"?u:u?.name).filter(u=>!!u):s?.tables??[],i=e.exclude??/^(auth_|_)/;r=e.tables?r.filter(u=>e.tables.includes(u)):r.filter(u=>!i.test(u)),r=Array.from(new Set(r)).sort();let o=[],a=[];for(let u of r){let h=await n.getTableMetadata(u);if(h.error)continue;let p=h.data.find(y=>y.table_name===u)?.columns??[];if(p.length===0)continue;let ge=p.map(y=>{let ye=y.is_nullable?"?":"",fe=y.is_nullable?" | null":"";return` ${Ke(y.column_name)}${ye}: ${ee(y.data_type)}${fe};`}),te=We(u);o.push(`export interface ${te} {
3
+ ${ge.join(`
4
4
  `)}
5
- }`),a.push(` ${JSON.stringify(u)}: ${ee};`)}let l=`// Generated by @nestcorehq/node generateTypes \u2014 do not edit by hand.
5
+ }`),a.push(` ${JSON.stringify(u)}: ${te};`)}let l=`// Generated by @nestcorehq/node generateTypes \u2014 do not edit by hand.
6
6
  // Re-run after schema changes to keep types in sync.
7
7
  `,c=`export interface Database {
8
8
  ${a.join(`
@@ -13,6 +13,6 @@ ${o.join(`
13
13
  `)}
14
14
 
15
15
  ${c}
16
- `}var A=class extends Error{constructor(e,t={}){super(e),this.name="NestCoreError",this.code=t.code,this.status=t.status}},ue=A;function de(n){if(n.error)throw new A(n.error.message,{code:n.error.code,status:n.error.status});return n.data}var he={OTP_RATE_LIMITED:"OTP_RATE_LIMITED",OTP_REQUEST_LIMIT:"OTP_REQUEST_LIMIT",ACCOUNT_LOCKED:"ACCOUNT_LOCKED"};var Je="https://api.nestcore.io";function Ke(n){let e=n.split(".");if(e.length!==3)throw new Error("NestCore: apiKey is not a valid JWT (expected 3 segments)");let t=e[1];switch(t=t.replace(/-/g,"+").replace(/_/g,"/"),t.length%4){case 2:t+="==";break;case 3:t+="=";break}let s;try{let i=typeof atob<"u"?atob(t):Buffer.from(t,"base64").toString("utf8");s=JSON.parse(i)}catch{throw new Error("NestCore: could not decode apiKey JWT payload")}let r=s.project_slug;if(typeof r!="string"||r.length===0)throw new Error("NestCore: apiKey JWT does not contain a project_slug claim");return r}function He(n){if(!n.apiKey)throw new Error("NestCore: apiKey is required");let e=n.projectSlug??Ke(n.apiKey),t=(n.baseUrl??Je).replace(/\/$/,""),s=new P({...n,projectSlug:e,baseUrl:t}),r=`${t.replace(/^http/,"ws")}/realtime/v1/ws?project=${encodeURIComponent(e)}`,i=new T(s,{storage:n.storage});s.setAccessTokenProvider(()=>i.getAccessToken(),c=>i.refreshAccessToken(c));let o=!n.realtimeOptions?.userJwt,a=new C(r,{...n.realtimeOptions,apiKey:n.apiKey,...o?{accessToken:()=>i.getAccessToken(),onAuthRejected:c=>{i.refreshAccessToken(c)}}:{}});return o&&i.onAuthStateChange(c=>a.setAuth(c?.access_token??null)),{db:new R(s),functions:new v(s),jobs:new k(s),auth:i,logs:new w(s),env:new S(s),storage:new _(s),channel:c=>a.channel(c),realtime:a,analytics:new E(s),ai:new q(s),memory:new $(s),collections:new O(s)}}return Re(Ve);})();
16
+ `}var A=class extends Error{constructor(e,t={}){super(e),this.name="NestCoreError",this.code=t.code,this.status=t.status,this.details=t.details}get isProjectPaused(){return this.code===B.PROJECT_PAUSED}get upgradeUrl(){let e=this.details?.upgradeUrl;return typeof e=="string"?e:void 0}get isCreditsExhausted(){return this.code===B.CREDITS_EXHAUSTED}get reason(){let e=this.details?.reason;return typeof e=="string"?e:void 0}get buyUrl(){let e=this.details?.buyUrl;return typeof e=="string"?e:void 0}},he=A;function pe(n){if(n.error)throw new A(n.error.message,{code:n.error.code,status:n.error.status,details:n.error.details});return n.data}var me={OTP_RATE_LIMITED:"OTP_RATE_LIMITED",OTP_REQUEST_LIMIT:"OTP_REQUEST_LIMIT",ACCOUNT_LOCKED:"ACCOUNT_LOCKED"},B={QUOTA_EXCEEDED:"QUOTA_EXCEEDED",CREDITS_EXHAUSTED:"CREDITS_EXHAUSTED",PROJECT_PAUSED:"PROJECT_PAUSED",AGENT_PROJECT_RESTRICTED:"AGENT_PROJECT_RESTRICTED",NOT_AN_AGENT_PROJECT:"NOT_AN_AGENT_PROJECT"};var He="https://api.nestcore.io";function Ve(n){let e=n.split(".");if(e.length!==3)throw new Error("NestCore: apiKey is not a valid JWT (expected 3 segments)");let t=e[1];switch(t=t.replace(/-/g,"+").replace(/_/g,"/"),t.length%4){case 2:t+="==";break;case 3:t+="=";break}let s;try{let i=typeof atob<"u"?atob(t):Buffer.from(t,"base64").toString("utf8");s=JSON.parse(i)}catch{throw new Error("NestCore: could not decode apiKey JWT payload")}let r=s.project_slug;if(typeof r!="string"||r.length===0)throw new Error("NestCore: apiKey JWT does not contain a project_slug claim");return r}function ze(n){if(!n.apiKey)throw new Error("NestCore: apiKey is required");let e=n.projectSlug??Ve(n.apiKey),t=(n.baseUrl??He).replace(/\/$/,""),s=new R({...n,projectSlug:e,baseUrl:t}),r=`${t.replace(/^http/,"ws")}/realtime/v1/ws?project=${encodeURIComponent(e)}`,i=new k(s,{storage:n.storage});s.setAccessTokenProvider(()=>i.getAccessToken(),c=>i.refreshAccessToken(c));let o=!n.realtimeOptions?.userJwt,a=new C(r,{...n.realtimeOptions,apiKey:n.apiKey,...o?{accessToken:()=>i.getAccessToken(),onAuthRejected:c=>{i.refreshAccessToken(c)}}:{}});return o&&i.onAuthStateChange(c=>a.setAuth(c?.access_token??null)),{db:new P(s),functions:new T(s),jobs:new v(s),auth:i,logs:new w(s),env:new S(s),storage:new _(s),channel:c=>a.channel(c),realtime:a,analytics:new E(s),ai:new U(s),memory:new O(s),collections:new $(s)}}return ve(Qe);})();
17
17
  var OrbitNest=NestCore;
18
18
  //# sourceMappingURL=index.global.js.map