@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.
package/dist/index.mjs CHANGED
@@ -1,8 +1,8 @@
1
- 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 v=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 j(this,e)}},Y=/^[a-zA-Z_][a-zA-Z0-9_]*$/,j=class{constructor(e,t){this.db=e;this.tableName=t;this._filters=[];this._orders=[];this._columns="*";this.ident(t)}ident(e){if(!Y.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(!Y.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 k=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 T=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 Z(){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 le(){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 Z();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 D={getItem:()=>null,setItem:()=>{},removeItem:()=>{}},ce={getItem:n=>{try{return N()?.getItem(n)??null}catch{return null}},setItem:(n,e)=>{try{N()?.setItem(n,e)}catch{}},removeItem:n=>{try{N()?.removeItem(n)}catch{}}};function N(){try{return globalThis.localStorage??null}catch{return null}}function X(n){return!!n&&typeof n=="object"&&n.mfa_required===!0}var ue="nestcore.session",de="orbitnest.session",he=30,pe={data:null,error:{message:"No active session",code:"NO_SESSION"}},w=class{constructor(e,t={}){this.client=e;this._session=null;this.refreshing=null;this.listeners=new Set;this.storage=t.storage??D,this.storageKey=`${ue}.${this.client.getProjectSlug()}`;let s=this.storage.getItem(this.storageKey);if(s===null){let r=`${de}.${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=me(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-he<=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):pe}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&&!X(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 me(n){return!n||n.expires_at||!n.expires_in?n:{...n,expires_at:Math.floor(Date.now()/1e3)+n.expires_in}}var S=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 _=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 ee(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 y(n,e="path"){let t=ee(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 ge(n){return n.replace(/\\/g,"/").split("/").filter(e=>e!==".."&&e!==""&&e!==".").join("/")}function te(n){return n.split("/").filter(e=>e.length>0).map(e=>encodeURIComponent(e)).join("/")}function ye(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 fe={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 be(n){let e=n.split(".").pop()?.toLowerCase()??"";return fe[e]}function M(n){if(n.error)return n;let e=n.data;return{data:e?.data??e,error:null}}var C=class{constructor(e){this.client=e}from(e){return new L(this.client,e)}},L=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=y(e);if(r)return r;let i=new FormData,o=s?.contentType||t instanceof Blob&&t.type||be(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=y(e);if(t)return t;let s=this.absoluteUrl(`${this.basePath}/download/${te(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=y(t);if(s)return s}return M(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 M(await this.client.request(`${this.basePath}${r}`))}getPublicUrl(e,t){let s=y(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}/${te(e)}`,a=ye(t?.transform);return a&&(o+=`?${a}`),{data:{publicUrl:o}}}async createBucket(e={}){return M(await this.client.request(`${this.basePath}/create`,{method:"POST",body:e.public===void 0?void 0:{public:e.public}}))}};var F=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})}},B=class{constructor(e,t){this.name=e;this.client=t;this.handlers=[];this._joined=!1;this.presence=new F(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]=ne(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=re(r.event);!i.includes(e.op)&&!i.includes("*")||r.table&&r.table!==e.table||r.schema&&r.schema!==e.schema||ke(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??{})}},Ae=0,f=1,se=1e3,Pe=1e4,Re=6e4,ve=4029,E=class{constructor(e,t={}){this.url=e;this.options=t;this.ws=null;this.channels=new Map;this.reconnectDelay=se;this.maxReconnectDelay=Re;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 B(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===Ae){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=se,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===ve||c===1008||c===1013)&&(this.reconnectDelay=Math.max(this.reconnectDelay,Pe));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=>re(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]=ne(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 re(n){if(n==="*")return["INSERT","UPDATE","DELETE"];let e=Array.isArray(n)?n:[n];return e.includes("*")?["INSERT","UPDATE","DELETE"]:e}function ne(n){let e=n.indexOf(".");return[n.slice(0,e),n.slice(e+1)]}function ke(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 W="nestcore_anonymous_id",J="nestcore_session_id",K="nestcore_session_last_activity",Te={[W]:"orbitnest_anonymous_id",[J]:"orbitnest_session_id",[K]:"orbitnest_session_last_activity"},we=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 Se(){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 H(n,e){let t=n.getItem(e);if(t!==null)return t;let s=Te[e],r=s?n.getItem(s):null;return r===null||!s?null:(n.setItem(e,r),n.removeItem(s),r)}function _e(){return typeof window<"u"&&typeof document<"u"?"web":"node"}function Ce(n){if(!n)return b();try{let e=H(n,W);return e||(e=b(),n.setItem(W,e)),e}catch{return b()}}function Ee(n,e){if(!n)return e;try{let t=Date.now(),s=parseInt(H(n,K)??"0",10)||0,r=H(n,J);return(!r||t-s>we)&&(r=b(),n.setItem(J,r)),n.setItem(K,String(t)),r}catch{return e}}var $=class{constructor(e,t={}){this.client=e;this.queue=[];this.flushTimer=null;this.storage=Se(),this.anonymousId=Ce(this.storage),this.fallbackSessionId=b(),this.platform=t.platform??_e(),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:Ee(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*O(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 I=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(A(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${A(e)}`))}reembed(e={}){return this.client.request(this.path("/reembed"),{method:"POST",body:e})}},V=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${A(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"))}},x=class{constructor(e){this.client=e}path(e=""){return`/api/project/${this.client.getProjectSlug()}/ai/v1/collections${e}`}from(e){return new V(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"})}},z=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${A(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 O(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})}},q=class{constructor(e){this.client=e}path(e=""){return`/api/project/${this.client.getProjectSlug()}/ai/v1/threads${e}`}from(e){return new z(this.client,e)}create(e={}){return this.client.request(this.path(),{method:"POST",body:e})}list(e={}){return this.client.request(this.path(A(e)))}get(e){return this.from(e).get()}delete(e){return this.from(e).delete()}};function A(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 q(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 O(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 $e={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 Q(n){let e=(n||"").toLowerCase().trim();return e?e.endsWith("[]")?`${Q(e.slice(0,-2))}[]`:e.startsWith("_")?`${Q(e.slice(1))}[]`:$e[e]??"unknown":"unknown"}function Oe(n){return n.replace(/(^|[_\- ])([a-zA-Z0-9])/g,(e,t,s)=>s.toUpperCase()).replace(/[^a-zA-Z0-9]/g,"")}function Ie(n){return/^[a-zA-Z_$][\w$]*$/.test(n)?n:JSON.stringify(n)}async function xe(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(g=>g.table_name===u)?.columns??[];if(p.length===0)continue;let ie=p.map(g=>{let oe=g.is_nullable?"?":"",ae=g.is_nullable?" | null":"";return` ${Ie(g.column_name)}${oe}: ${Q(g.data_type)}${ae};`}),G=Oe(u);o.push(`export interface ${G} {
3
- ${ie.join(`
1
+ 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 T=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 j(this,e)}},X=/^[a-zA-Z_][a-zA-Z0-9_]*$/,j=class{constructor(e,t){this.db=e;this.tableName=t;this._filters=[];this._orders=[];this._columns="*";this.ident(t)}ident(e){if(!X.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(!X.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 Z(){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 ue(){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 Z();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 D={getItem:()=>null,setItem:()=>{},removeItem:()=>{}},de={getItem:n=>{try{return M()?.getItem(n)??null}catch{return null}},setItem:(n,e)=>{try{M()?.setItem(n,e)}catch{}},removeItem:n=>{try{M()?.removeItem(n)}catch{}}};function M(){try{return globalThis.localStorage??null}catch{return null}}function ee(n){return!!n&&typeof n=="object"&&n.mfa_required===!0}var he="nestcore.session",pe="orbitnest.session",me=30,ge={data:null,error:{message:"No active session",code:"NO_SESSION"}},w=class{constructor(e,t={}){this.client=e;this._session=null;this.refreshing=null;this.listeners=new Set;this.storage=t.storage??D,this.storageKey=`${he}.${this.client.getProjectSlug()}`;let s=this.storage.getItem(this.storageKey);if(s===null){let r=`${pe}.${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=ye(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-me<=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):ge}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&&!ee(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 ye(n){return!n||n.expires_at||!n.expires_in?n:{...n,expires_at:Math.floor(Date.now()/1e3)+n.expires_in}}var S=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 _=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 te(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 y(n,e="path"){let t=te(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 fe(n){return n.replace(/\\/g,"/").split("/").filter(e=>e!==".."&&e!==""&&e!==".").join("/")}function se(n){return n.split("/").filter(e=>e.length>0).map(e=>encodeURIComponent(e)).join("/")}function be(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 Ae={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 Re(n){let e=n.split(".").pop()?.toLowerCase()??"";return Ae[e]}function N(n){if(n.error)return n;let e=n.data;return{data:e?.data??e,error:null}}var C=class{constructor(e){this.client=e}from(e){return new L(this.client,e)}},L=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=y(e);if(r)return r;let i=new FormData,o=s?.contentType||t instanceof Blob&&t.type||Re(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=y(e);if(t)return t;let s=this.absoluteUrl(`${this.basePath}/download/${se(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=y(t);if(s)return s}return N(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 N(await this.client.request(`${this.basePath}${r}`))}getPublicUrl(e,t){let s=y(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}/${se(e)}`,a=be(t?.transform);return a&&(o+=`?${a}`),{data:{publicUrl:o}}}async createBucket(e={}){return N(await this.client.request(`${this.basePath}/create`,{method:"POST",body:e.public===void 0?void 0:{public:e.public}}))}};var F=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})}},B=class{constructor(e,t){this.name=e;this.client=t;this.handlers=[];this._joined=!1;this.presence=new F(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]=ie(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=ne(r.event);!i.includes(e.op)&&!i.includes("*")||r.table&&r.table!==e.table||r.schema&&r.schema!==e.schema||we(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??{})}},Pe=0,f=1,re=1e3,Te=1e4,ve=6e4,ke=4029,E=class{constructor(e,t={}){this.url=e;this.options=t;this.ws=null;this.channels=new Map;this.reconnectDelay=re;this.maxReconnectDelay=ve;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 B(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===Pe){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=re,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===ke||c===1008||c===1013)&&(this.reconnectDelay=Math.max(this.reconnectDelay,Te));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=>ne(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]=ie(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 ne(n){if(n==="*")return["INSERT","UPDATE","DELETE"];let e=Array.isArray(n)?n:[n];return e.includes("*")?["INSERT","UPDATE","DELETE"]:e}function ie(n){let e=n.indexOf(".");return[n.slice(0,e),n.slice(e+1)]}function we(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 J="nestcore_anonymous_id",W="nestcore_session_id",K="nestcore_session_last_activity",Se={[J]:"orbitnest_anonymous_id",[W]:"orbitnest_session_id",[K]:"orbitnest_session_last_activity"},_e=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 Ce(){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 H(n,e){let t=n.getItem(e);if(t!==null)return t;let s=Se[e],r=s?n.getItem(s):null;return r===null||!s?null:(n.setItem(e,r),n.removeItem(s),r)}function Ee(){return typeof window<"u"&&typeof document<"u"?"web":"node"}function Oe(n){if(!n)return b();try{let e=H(n,J);return e||(e=b(),n.setItem(J,e)),e}catch{return b()}}function $e(n,e){if(!n)return e;try{let t=Date.now(),s=parseInt(H(n,K)??"0",10)||0,r=H(n,W);return(!r||t-s>_e)&&(r=b(),n.setItem(W,r)),n.setItem(K,String(t)),r}catch{return e}}var O=class{constructor(e,t={}){this.client=e;this.queue=[];this.flushTimer=null;this.storage=Ce(),this.anonymousId=Oe(this.storage),this.fallbackSessionId=b(),this.platform=t.platform??Ee(),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:$e(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){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 x=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:oe(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(A(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${A(e)}`))}reembed(e={}){return this.client.request(this.path("/reembed"),{method:"POST",body:e})}},V=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:oe(e,t)})}listDocuments(e={}){return this.client.request(this.path(`/documents${A(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"))}},I=class{constructor(e){this.client=e}path(e=""){return`/api/project/${this.client.getProjectSlug()}/ai/v1/collections${e}`}from(e){return new V(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"})}},z=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${A(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 $(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})}},U=class{constructor(e){this.client=e}path(e=""){return`/api/project/${this.client.getProjectSlug()}/ai/v1/threads${e}`}from(e){return new z(this.client,e)}create(e={}){return this.client.request(this.path(),{method:"POST",body:e})}list(e={}){return this.client.request(this.path(A(e)))}get(e){return this.from(e).get()}delete(e){return this.from(e).delete()}};function oe(n,e){return n!==null&&typeof n=="object"?{...n}:typeof n=="string"?{query:n,...e}:{...e}}function A(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 U(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 $(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 xe={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 Q(n){let e=(n||"").toLowerCase().trim();return e?e.endsWith("[]")?`${Q(e.slice(0,-2))}[]`:e.startsWith("_")?`${Q(e.slice(1))}[]`:xe[e]??"unknown":"unknown"}function Ie(n){return n.replace(/(^|[_\- ])([a-zA-Z0-9])/g,(e,t,s)=>s.toUpperCase()).replace(/[^a-zA-Z0-9]/g,"")}function Ue(n){return/^[a-zA-Z_$][\w$]*$/.test(n)?n:JSON.stringify(n)}async function qe(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(g=>g.table_name===u)?.columns??[];if(p.length===0)continue;let ae=p.map(g=>{let le=g.is_nullable?"?":"",ce=g.is_nullable?" | null":"";return` ${Ue(g.column_name)}${le}: ${Q(g.data_type)}${ce};`}),Y=Ie(u);o.push(`export interface ${Y} {
3
+ ${ae.join(`
4
4
  `)}
5
- }`),a.push(` ${JSON.stringify(u)}: ${G};`)}let l=`// Generated by @nestcorehq/node generateTypes \u2014 do not edit by hand.
5
+ }`),a.push(` ${JSON.stringify(u)}: ${Y};`)}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,5 +13,5 @@ ${o.join(`
13
13
  `)}
14
14
 
15
15
  ${c}
16
- `}var P=class extends Error{constructor(e,t={}){super(e),this.name="NestCoreError",this.code=t.code,this.status=t.status}},qe=P;function Ue(n){if(n.error)throw new P(n.error.message,{code:n.error.code,status:n.error.status});return n.data}var je={OTP_RATE_LIMITED:"OTP_RATE_LIMITED",OTP_REQUEST_LIMIT:"OTP_REQUEST_LIMIT",ACCOUNT_LOCKED:"ACCOUNT_LOCKED"};var Ne="https://api.nestcore.io";function De(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 _t(n){if(!n.apiKey)throw new Error("NestCore: apiKey is required");let e=n.projectSlug??De(n.apiKey),t=(n.baseUrl??Ne).replace(/\/$/,""),s=new R({...n,projectSlug:e,baseUrl:t}),r=`${t.replace(/^http/,"ws")}/realtime/v1/ws?project=${encodeURIComponent(e)}`,i=new w(s,{storage:n.storage});s.setAccessTokenProvider(()=>i.getAccessToken(),c=>i.refreshAccessToken(c));let o=!n.realtimeOptions?.userJwt,a=new E(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 v(s),functions:new k(s),jobs:new T(s),auth:i,logs:new S(s),env:new _(s),storage:new C(s),channel:c=>a.channel(c),realtime:a,analytics:new $(s),ai:new U(s),memory:new I(s),collections:new x(s)}}export{U as AiClient,$ as AnalyticsClient,w as AuthClient,je as AuthLimitCodes,V as CollectionRef,x as CollectionsClient,v as DatabaseClient,_ as EnvironmentClient,k as FunctionsClient,R as HttpClient,T as JobsClient,S as LoggingClient,I as MemoryClient,P as NestCoreError,qe as OrbitNestError,F as PresenceManager,B as RealtimeChannel,E as RealtimeClient,L as StorageBucket,C as StorageClient,z as ThreadRef,q as ThreadsClient,_t as createClient,le as createLocalStorageAdapter,Z as createMemoryAdapter,xe as generateTypes,X as isMfaChallenge,ce as localStorageAdapter,D as memoryAdapter,ge as sanitizePath,Ue as unwrap,y as validatePath,ee as validateRequired};
16
+ `}var R=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===G.PROJECT_PAUSED}get upgradeUrl(){let e=this.details?.upgradeUrl;return typeof e=="string"?e:void 0}get isCreditsExhausted(){return this.code===G.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}},je=R;function Me(n){if(n.error)throw new R(n.error.message,{code:n.error.code,status:n.error.status,details:n.error.details});return n.data}var De={OTP_RATE_LIMITED:"OTP_RATE_LIMITED",OTP_REQUEST_LIMIT:"OTP_REQUEST_LIMIT",ACCOUNT_LOCKED:"ACCOUNT_LOCKED"},G={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 Ne="https://api.nestcore.io";function Le(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 Et(n){if(!n.apiKey)throw new Error("NestCore: apiKey is required");let e=n.projectSlug??Le(n.apiKey),t=(n.baseUrl??Ne).replace(/\/$/,""),s=new P({...n,projectSlug:e,baseUrl:t}),r=`${t.replace(/^http/,"ws")}/realtime/v1/ws?project=${encodeURIComponent(e)}`,i=new w(s,{storage:n.storage});s.setAccessTokenProvider(()=>i.getAccessToken(),c=>i.refreshAccessToken(c));let o=!n.realtimeOptions?.userJwt,a=new E(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 T(s),functions:new v(s),jobs:new k(s),auth:i,logs:new S(s),env:new _(s),storage:new C(s),channel:c=>a.channel(c),realtime:a,analytics:new O(s),ai:new q(s),memory:new x(s),collections:new I(s)}}export{q as AiClient,O as AnalyticsClient,w as AuthClient,De as AuthLimitCodes,V as CollectionRef,I as CollectionsClient,T as DatabaseClient,_ as EnvironmentClient,v as FunctionsClient,P as HttpClient,k as JobsClient,S as LoggingClient,x as MemoryClient,R as NestCoreError,je as OrbitNestError,F as PresenceManager,G as ProjectErrorCodes,B as RealtimeChannel,E as RealtimeClient,L as StorageBucket,C as StorageClient,z as ThreadRef,U as ThreadsClient,Et as createClient,ue as createLocalStorageAdapter,Z as createMemoryAdapter,qe as generateTypes,ee as isMfaChallenge,de as localStorageAdapter,D as memoryAdapter,fe as sanitizePath,Me as unwrap,y as validatePath,te as validateRequired};
17
17
  //# sourceMappingURL=index.mjs.map