@ax-hub/sdk 2.0.0 → 2.1.1

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.js CHANGED
@@ -1,2 +1,2 @@
1
- import {ulid}from'ulid';import {createHmac,timingSafeEqual}from'crypto';var p=class extends Error{code;category;httpStatus;retryable;requestId;resource;fields;retry;docUrl;constructor(e){super(e.message,e.cause?{cause:e.cause}:void 0),this.name=this.constructor.name,this.code=e.code,this.category=e.category,this.httpStatus=e.httpStatus,this.retryable=e.retryable,this.requestId=e.requestId,e.resource!==void 0&&(this.resource=e.resource),e.fields!==void 0&&(this.fields=e.fields),e.retry!==void 0&&(this.retry=e.retry),e.docUrl!==void 0&&(this.docUrl=e.docUrl);}toJSON(){return {name:this.name,message:this.message,code:this.code,category:this.category,httpStatus:this.httpStatus,retryable:this.retryable,requestId:this.requestId,resource:this.resource,fields:this.fields,retry:this.retry,docUrl:this.docUrl}}toString(){return Sn(this)}};function Sn(t){let e=[`${t.name}[${t.code}]`];return t.requestId&&e.push(`req=${t.requestId}`),e.push(`problem=${t.message}`),t.fields?.length&&e.push(`cause=${t.fields.map(n=>`${n.name}:${n.code}`).join(",")}`),t.retry?.afterMs!==void 0?e.push(`fix=retry_after_${t.retry.afterMs}ms`):t.retryable?e.push("fix=retry_with_backoff"):e.push("fix=inspect_input_or_permissions"),t.docUrl&&e.push(`docs=${t.docUrl}`),e.join(" ")}var d=class extends p{},k=class extends p{},T=class extends p{},f=class extends p{},g=class extends p{},ie=class extends p{},D=class extends p{},U=class extends p{},N=class extends p{},se=class extends g{},oe=class extends g{},ae=class extends g{},ue=class extends k{},ce=class extends k{},de=class extends k{},le=class extends T{},pe=class extends T{},me=class extends f{},ge=class extends f{},fe=class extends f{},ye=class extends g{},he=class extends g{},be=class extends g{},Re=class extends g{},we=class extends g{},ve=class extends g{},_e=class extends g{},xe=class extends g{},Ce=class extends g{},Ie=class extends g{},Se=class extends g{},Ae=class extends g{},ke=class extends d{},Te=class extends d{},S=class extends d{},Pe=class extends d{},Ee=class extends d{},qe=class extends T{},Oe=class extends T{},De=class extends N{},Ue=class extends p{},Le=class extends p{},Q=class extends p{},h=class extends p{},V=class extends p{},ft=class extends p{},Me=class extends p{},R=class extends p{},K=class extends p{},L=class extends k{},tn=class extends d{},M=class extends f{},$=class extends U{},_=class extends d{},v=class extends d{},$e=class extends K{},z=class extends U{},y=class extends p{description;uri;constructor(e){super({message:e.description??e.code,code:e.code,category:"oauth",httpStatus:e.httpStatus,retryable:e.retryable,requestId:e.requestId}),e.description!==void 0&&(this.description=e.description),e.uri!==void 0&&(this.uri=e.uri);}},Ge=class extends y{},W=class extends y{},G=class extends y{},B=class extends y{},X=class extends y{},nn=class extends W{},rn=class extends X{},Be=class extends y{},He=class extends y{},je=class extends y{},Fe=class extends y{},Ne=class extends y{},Qe=class extends y{},Ve=class extends y{},Ke=class extends y{},ze=class extends y{};var An={slug_taken:se,already_member:oe,already_deleted:ae,already_revoked:ye,already_settled:he,already_active:be,already_inactive:Re,already_accessed:we,not_deleted:ve,last_admin:_e,pending_exists:xe,invalid_state_transition:Ce,schema_name_taken:Ie,domain_taken:Se,duplicate:Ae,token_missing:ue,token_expired:ce,token_invalid:de,pool_stale:L,not_admin:le,forbidden:pe,not_member:qe,not_allowed:Oe,permanently_deleted:me,invitation_expired:ge,link_invalid:fe,invalid_value:ke,invalid_expiry:Te,required:S,empty:Pe,bad_request:Ee,app_unavailable:De},kn={validation:d,unauthenticated:k,permission_denied:T,not_found:f,conflict:g,precondition_failed:ie,rate_limited:D,internal:U,unavailable:N},Tn={invalid_grant:Ge,access_denied:W,authorization_pending:G,slow_down:B,expired_token:X,invalid_target:Be,invalid_client:He,invalid_request:je,invalid_scope:Fe,invalid_token:Ne,unauthorized_client:Qe,unsupported_grant_type:Ve,server_error:Ke,temporarily_unavailable:ze},Pn={authorization_pending:true,slow_down:true,access_denied:false,invalid_grant:false,expired_token:false,server_error:true,temporarily_unavailable:true};function Lr(t){if(typeof t!="object"||t===null)return false;let e=t.error;if(typeof e!="object"||e===null)return false;let n=e;return typeof n.code=="string"&&typeof n.category=="string"&&typeof n.retryable=="boolean"}function Mr(t){return typeof t!="object"||t===null?false:typeof t.error=="string"}function En(t){return t.startsWith("/oauth/")||t.startsWith("/auth/")}function sn(t){return En(t.path)&&Mr(t.body)?Gr(t):Lr(t.body)?$r(t):new Q({message:"Unexpected error response shape",code:"decode_failed",category:"decode",httpStatus:t.status,retryable:false,requestId:t.fallbackRequestId})}function $r(t){let n=t.body.error,r=n.retry?{afterMs:n.retry.after_ms}:void 0,i={message:n.message,code:n.code,category:n.category,httpStatus:t.status,retryable:n.retryable,requestId:n.request_id||t.fallbackRequestId,resource:n.resource,fields:n.fields,retry:r,docUrl:n.doc_url},s=An[n.code];if(s)return new s(i);let o=kn[n.category]??p;return new o(i)}function Gr(t){let e=t.body,n=Tn[e.error]??y,r=Pn[e.error]??false;return new n({code:e.error,description:e.error_description,uri:e.error_uri,httpStatus:t.status,retryable:r,requestId:t.fallbackRequestId})}function Br(t){return t}function Hr(t){return t}function jr(t){return t}function Fr(t){return t}function Nr(t){return t}function Qr(t){return t}function Vr(t){return t}function Kr(t){return t}var zr=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,qn=/^[a-z][a-z0-9-]{0,62}$/;function yt(t,e,n){return new d({message:t,code:n,category:"validation",httpStatus:0,retryable:false,requestId:"",fields:[{name:e,code:n}]})}function x(t,e){if(t.trim()==="")throw yt(`${e} must be non-empty`,e,"empty");if(!zr.test(t))throw yt(`${e} must be a UUID`,e,"invalid_uuid")}function On(t,e){if(t.trim()==="")throw yt(`${e} must be non-empty`,e,"empty");if(!qn.test(t))throw yt(`${e} must match ${qn.source}`,e,"invalid_slug")}var Wr={tenant(t){return x(t,"tenantId"),t},tenantSlug(t){return On(t,"tenantSlug"),t},app(t){return x(t,"appId"),t},appSlug(t){return On(t,"appSlug"),t},user(t){return x(t,"userId"),t},deployment(t){return x(t,"deploymentId"),t},pat(t){return x(t,"patId"),t},resource(t){return x(t,"resourceId"),t},connector(t){return x(t,"connectorId"),t},subject(t){return x(t,"subjectId"),t},grant(t){return x(t,"grantId"),t},tag(t){return x(t,"tagId"),t},auditEvent(t){return x(t,"auditEventId"),t},table(t){return x(t,"tableId"),t}};var We=class{token;tokenType;onRefresh;refreshing=null;constructor(e){this.token=e.token,this.tokenType=e.tokenType,this.onRefresh=e.onRefresh;}currentToken(){return this.token}headersFor(e){return e==="public"?{}:this.tokenType==="pat"?{"X-Api-Key":this.token}:{Authorization:`Bearer ${this.token}`}}async onUnauthorized(){return this.tokenType!=="jwt"||!this.onRefresh?false:this.refreshing?this.refreshing:(this.refreshing=(async()=>{try{let e=await this.onRefresh();return this.token=e,!0}catch{return false}finally{this.refreshing=null;}})(),this.refreshing)}},Xe=class{headersFor(e){return {}}async onUnauthorized(){return false}};var ht={debug(){},info(){},warn(){},error(){}};function on(t){if(!t)return 6e4;let e=t.trim();if(e==="")return 6e4;let n=Number(e);if(Number.isFinite(n))return n>=0?Math.floor(n*1e3):6e4;let r=Date.parse(e);return Number.isNaN(r)?6e4:Math.max(0,r-Date.now())}var Xr=new Set(["authorization","x-api-key","cookie","set-cookie","proxy-authorization"]),Zr="***REDACTED***";function Dn(t){let e={},n=(r,i)=>{e[r]=Xr.has(r.toLowerCase())?Zr:i;};if(typeof Headers<"u"&&t instanceof Headers)t.forEach((r,i)=>n(i,r));else for(let[r,i]of Object.entries(t))n(r,i);return e}var un={maxAttempts:3,baseMs:200,capMs:5e3,jitter:Math.random};function Yr(t){return t instanceof p?t.retryable:t instanceof TypeError}async function Un(t,e=un,n){let r;for(let i=0;i<e.maxAttempts;i++){if(n?.aborted)throw an("aborted before attempt",n.reason);try{return await t(i)}catch(s){if(r=s,!Yr(s)||i===e.maxAttempts-1)throw s;let o=Math.min(e.capMs,e.baseMs*2**i)*e.jitter();await cn(o,n);}}throw r}function cn(t,e){return new Promise((n,r)=>{if(e?.aborted){r(an("aborted before sleep",e.reason));return}let i=setTimeout(()=>{e?.removeEventListener("abort",s),n();},t),s=()=>{clearTimeout(i),r(an("aborted during sleep",e?.reason));};e?.addEventListener("abort",s,{once:true});})}function an(t,e){return new h({message:t,code:"aborted",category:"abort",httpStatus:0,retryable:false,requestId:"",cause:e})}var Jr=new Set(["GET","HEAD","OPTIONS"]),bt=class{baseUrl;auth;fetch;logger;debug;timeoutMs;idempotencyKey;retryPolicy;rateLimitStrategy;constructor(e){this.baseUrl=e.baseUrl.replace(/\/$/,""),this.auth=e.auth,this.fetch=e.fetch??globalThis.fetch,this.logger=e.logger??ht,this.debug=e.debug??false,this.timeoutMs=e.timeoutMs??3e4,this.idempotencyKey={autoGenerate:e.idempotencyKey?.autoGenerate??true,generator:e.idempotencyKey?.generator??ulid},this.retryPolicy=e.retryPolicy??un,this.rateLimitStrategy=e.rateLimitStrategy??"sleep";}async request(e,n,r){let i=Jr.has(e.toUpperCase()),s=this.withStableIdempotencyKey(r);return i||r.idempotent?Un(()=>this.requestOnce(e,n,s),this.retryPolicy,s.signal):this.requestOnce(e,n,s)}async requestOnce(e,n,r){let i=this.buildUrl(n,r.query),s=ulid(),o=this.buildHeaders(s,r);if(r.body!==void 0&&r.form!==void 0)throw new p({message:"body and form are mutually exclusive",code:"invalid_request_body",category:"validation",httpStatus:0,retryable:false,requestId:s});let c=r.form!==void 0?this.formBody(r.form):r.body!==void 0?JSON.stringify(r.body):void 0;c!==void 0&&(o["Content-Type"]=r.form!==void 0?"application/x-www-form-urlencoded":"application/json");let l=new AbortController,C=()=>l.abort(r.signal?.reason);r.signal?.addEventListener("abort",C,{once:true});let P=r.timeoutMs??this.timeoutMs,gt=setTimeout(()=>l.abort(new Error("timeout")),P),w;try{this.logRequest(e,i,o,s),w=await this.fetch(i,{method:e,headers:o,body:c,redirect:"manual",signal:l.signal});}catch(O){throw r.signal?.aborted?new h({message:"Request aborted",code:"aborted",category:"abort",httpStatus:0,retryable:false,requestId:s,cause:O}):l.signal.aborted?new Le({message:`Request timed out after ${P}ms`,code:"timeout",category:"timeout",httpStatus:0,retryable:true,requestId:s,cause:O}):new Ue({message:"Network error",code:"network",category:"network",httpStatus:0,retryable:true,requestId:s,cause:O})}finally{clearTimeout(gt),r.signal?.removeEventListener("abort",C);}if(w.status>=300&&w.status<400)return {status:w.status,location:w.headers.get("Location")??w.headers.get("location")};if(r.rawResponse&&w.ok)return {response:w,requestId:s};if(w.ok)return this.parseSuccess(w,r,s);let en=await this.safeParseJson(w);if(w.status===401&&r.ring==="admin"&&await this.auth.onUnauthorized())return this.requestOnce(e,n,r);if(w.status===429){let O=on(w.headers.get("Retry-After")),Ur=new D({message:ei(en)??"Rate limited",code:ti(en)??"rate_limited",category:"rate_limited",httpStatus:429,retryable:true,requestId:s,retry:{afterMs:O}});if(this.rateLimitStrategy==="sleep")return await cn(O,r.signal),this.requestOnce(e,n,r);throw Ur}throw sn({path:n,status:w.status,body:en,fallbackRequestId:s})}async parseSuccess(e,n,r){if(e.status===204||n.parseBody===false)return;let i=await e.text();if(i!=="")try{return JSON.parse(i)}catch{return i}}async safeParseJson(e){try{let n=await e.text();return n===""?void 0:JSON.parse(n)}catch{return}}buildUrl(e,n){let r=e.startsWith("/")?e:`/${e}`,i=this.baseUrl+r;if(!n)return i;let s=new URLSearchParams;for(let[c,l]of Object.entries(n))if(l!==void 0)if(Array.isArray(l))for(let C of l)s.append(c,String(C));else s.set(c,String(l));let o=s.toString();return o?`${i}?${o}`:i}buildHeaders(e,n){let r=this.resolveIdempotencyKey(n);return {"X-Request-Id":e,Accept:"application/json",...n.ring!=="public"?this.auth.headersFor(n.ring):{},...r?{"Idempotency-Key":r}:{},...n.headers??{}}}resolveIdempotencyKey(e){if(e.idempotencyKey!==false){if(typeof e.idempotencyKey=="string"){if(e.idempotencyKey.trim()==="")throw new p({message:"idempotencyKey must be non-empty",code:"invalid_idempotency_key",category:"validation",httpStatus:0,retryable:false,requestId:""});return e.idempotencyKey}if(!(!e.idempotent||!this.idempotencyKey.autoGenerate))return this.idempotencyKey.generator()}}formBody(e){let n=new URLSearchParams;for(let[r,i]of Object.entries(e))i!==void 0&&n.set(r,String(i));return n.toString()}withStableIdempotencyKey(e){return e.idempotencyKey!==void 0||!e.idempotent||!this.idempotencyKey.autoGenerate?e:{...e,idempotencyKey:this.idempotencyKey.generator()}}logRequest(e,n,r,i){this.debug&&this.logger.debug({method:e,url:n,headers:Dn(r),requestId:i},"http.request");}};function ei(t){if(typeof t!="object"||t===null)return;let e=t.error;if(typeof e=="object"&&e!==null){let n=e.message;if(typeof n=="string")return n}if(typeof e=="string")return e}function ti(t){if(typeof t!="object"||t===null)return;let e=t.error;if(typeof e=="object"&&e!==null){let n=e.code;if(typeof n=="string")return n}}var Ze=4096,Mn=false;function $n(t){return `v2:${Buffer.from(JSON.stringify(t),"utf8").toString("base64url")}`}function ni(t){if(t.length>Ze)throw new _({message:`Cursor token exceeds maximum size (${Ze} chars)`,code:"invalid_cursor",category:"validation",httpStatus:0,retryable:false,requestId:"",docUrl:"https://docs.axhub.dev/errors/validation/invalid-cursor"});if(t.startsWith("v1:"))throw new v({message:"Legacy v1: cursor token is not compatible with keyset pagination; restart pagination without cursor",code:"legacy_cursor",category:"validation",httpStatus:0,retryable:false,requestId:"",docUrl:"https://docs.axhub.dev/errors/validation/legacy-cursor"});if(!t.startsWith("v2:"))throw new v({message:"Cursor token is missing the v2: keyset prefix; restart pagination without cursor",code:"legacy_cursor",category:"validation",httpStatus:0,retryable:false,requestId:"",docUrl:"https://docs.axhub.dev/errors/validation/legacy-cursor"});try{let e=JSON.parse(Buffer.from(t.slice(3),"base64url").toString("utf8"));if(!si(e))throw new Error("invalid cursor shape");return e}catch(e){throw new _({message:"Malformed keyset cursor token",code:"invalid_cursor",category:"validation",httpStatus:0,retryable:false,requestId:"",cause:e,docUrl:"https://docs.axhub.dev/errors/validation/invalid-cursor"})}}function Rt(t,e){let n=typeof t=="string"?t.split(",").map(r=>{let i=r.trim();return i.startsWith("-")?{field:i.slice(1),dir:"desc"}:i.startsWith("+")?{field:i.slice(1),dir:"asc"}:{field:i,dir:"asc"}}).filter(r=>r.field.length>0):[...t??[]].map(r=>({field:r.field,dir:r.dir??"asc"}));return n.length>0&&!n.some(r=>r.field==="id")&&(e?.warnOnTiebreaker&&!Mn&&(Mn=true,console.warn("AX Hub SDK: orderBy is not unique; appending id ASC as keyset cursor tiebreaker")),n.push({field:"id",dir:"asc"})),n}function Gn(t){let e=Rt(t,{warnOnTiebreaker:true});return e.length===0?typeof t=="string"?t:void 0:e.map(n=>`${n.dir==="desc"?"-":""}${n.field}`).join(",")}function ri(t){return JSON.stringify(Bn(t))}function ii(t,e){if(!t)return null;let n=Bn(e?.orderBy,{warnOnTiebreaker:true}),r={};for(let c of n){let l=t[c.field];(l===null||typeof l=="string"||typeof l=="number"||typeof l=="boolean")&&(r[c.field]=l);}let i=t.id,s={values:r,direction:e?.direction??"forward",orderBy:n,orderByFingerprint:JSON.stringify(n)};(typeof i=="string"||typeof i=="number")&&(s.tiebreaker={field:"id",value:i});let o=e?.page;return typeof o=="number"&&Number.isInteger(o)&&o>0&&(s.page=o),e?.contextFingerprint&&(s.contextFingerprint=e.contextFingerprint),$n(s)}function Bn(t,e){let n=Rt(t,e);return n.length>0?n:[{field:"id",dir:"asc"}]}function Hn(t){return typeof t=="string"&&t.startsWith("v2:")}function si(t){return typeof t=="object"&&t!==null&&typeof t.values=="object"&&(t.direction==="forward"||t.direction==="backward")&&Array.isArray(t.orderBy)&&typeof t.orderByFingerprint=="string"}async function*A(t,e){let n=e?.cursor,r,i;for(;;){if(e?.signal?.aborted)throw new h({message:"listAll aborted",code:"aborted",category:"abort",httpStatus:0,retryable:false,requestId:""});let s=await t({pageSize:e?.pageSize,cursor:n});s.total!==void 0&&(r===void 0?(r=s.total,i=s.total):s.total>(i??r)&&(yield {type:"drift",addedSince:s.total-(i??r)},i=s.total));for(let o of s.items)yield {type:"item",value:o};if(s.nextCursor==null)return;n=s.nextCursor;}}function dn(t){return Buffer.isBuffer(t)?t:Buffer.from(t)}function ai(t){let e=t.startsWith("sha256=")?t.slice(7):t;return /^[0-9a-f]{64}$/i.test(e)?Buffer.from(e,"hex"):null}function ui(t,e,n){let r=n?Buffer.concat([Buffer.from(`${n}.`),dn(t)]):dn(t);return `sha256=${createHmac("sha256",e).update(r).digest("hex")}`}function ci(t){if(!t.secret)return {ok:false,reason:"missing_secret"};let e=ai(t.signature);if(!e)return {ok:false,reason:"malformed_signature"};let n=Math.floor((t.now?.()??Date.now())/1e3),r=dn(t.rawBody);if(t.timestamp!==void 0){let s=Number(t.timestamp);if(!Number.isFinite(s))return {ok:false,reason:"timestamp_skew"};let o=t.tolerance??300;if(Math.abs(n-s)>o)return {ok:false,reason:"timestamp_skew"};let c=`${t.timestamp}:${t.signature}`;if(t.replayCache?.has(c))return {ok:false,reason:"replay"};r=Buffer.concat([Buffer.from(`${t.timestamp}.`),r]);}let i=createHmac("sha256",t.secret).update(r).digest();return e.byteLength!==i.byteLength?{ok:false,reason:"signature_mismatch"}:timingSafeEqual(e,i)?(t.timestamp!==void 0&&t.replayCache?.add(`${t.timestamp}:${t.signature}`),{ok:true}):{ok:false,reason:"signature_mismatch"}}function a(t,e){return {...t,signal:e?.signal,timeoutMs:e?.timeoutMs,idempotencyKey:e?.idempotencyKey}}function E(t){let e={};return t?.pageSize!==void 0&&(e.limit=t.pageSize),t?.cursor!==void 0&&(e.cursor=t.cursor),e}function b(t,e){return {items:t.items.map(e),nextCursor:t.next_cursor,total:t.total}}function H(t){let e={};for(let[n,r]of Object.entries(t))r!==void 0&&(e[n]=r);return e}function u(t){return encodeURIComponent(t)}function Fn(t){return {id:t.id,appId:t.app_id,userId:t.user_id,grantedAt:t.granted_at}}var wt=class{constructor(e){this.http=e;}http;async grant(e){let n=await this.http.request("POST",`/api/v1/apps/${encodeURIComponent(e)}/access`,{ring:"admin",idempotent:false});return Fn(n)}async revoke(e){await this.http.request("DELETE",`/api/v1/apps/${encodeURIComponent(e)}/access`,{ring:"admin",idempotent:true});}async me(e){try{let n=await this.http.request("GET",`/api/v1/apps/${encodeURIComponent(e)}/access/me`,{ring:"admin"});return Fn(n)}catch(n){if(di(n))return null;throw n}}};function di(t){return typeof t=="object"&&t!==null&&"httpStatus"in t&&t.httpStatus===404}function Nn(t){let e={available:t.available};return t.reason!==void 0&&(e.reason=t.reason),e}var vt=class{constructor(e,n){this.http=e;this.defaultTenantId=n;}http;defaultTenantId;requireTenantId(e,n){if(this.defaultTenantId===void 0)throw new R({message:`apps.${e} requires a tenant UUID: set defaultTenantId on AxHubClient. Backend route ${n} takes a tenant UUID, not a slug.`,code:"tenant_id_required",category:"tenant_id_required",httpStatus:0,retryable:false,requestId:"",fields:[{name:"tenantId",code:"required"}]});return this.defaultTenantId}async checkAvailability(e){let n=this.requireTenantId("checkAvailability","GET /api/v1/tenants/{tenantID}/apps/check-availability"),r={};e.slug!==void 0&&(r.slug=e.slug),e.subdomain!==void 0&&(r.subdomain=e.subdomain);let i=await this.http.request("GET",`/api/v1/tenants/${encodeURIComponent(n)}/apps/check-availability`,{ring:"admin",query:r}),s={};return i.slug!==void 0&&(s.slug=Nn(i.slug)),i.subdomain!==void 0&&(s.subdomain=Nn(i.subdomain)),s}async iconPreCreateUrl(e){let n=this.requireTenantId("iconPreCreateUrl","POST /api/v1/tenants/{tenantID}/apps/icon/upload-url"),r={content_type:e.contentType,slug:e.slug};e.variant!==void 0&&(r.variant=e.variant);let i=await this.http.request("POST",`/api/v1/tenants/${encodeURIComponent(n)}/apps/icon/upload-url`,{ring:"admin",body:r,idempotent:false}),s={uploadUrl:i.put_url??"",getUrl:i.public_url??""};return i.expires_at!==void 0&&(s.expiresAt=i.expires_at),s}};var _t=class{constructor(e){this.http=e;}http;async list(e,n){let r=await this.http.request("GET",`/api/v1/tenants/${u(e)}/categories`,a({ring:"admin",query:E(n)},n));return b(r,i=>i)}get(e,n,r){return this.http.request("GET",`/api/v1/tenants/${u(e)}/categories/${u(n)}`,a({ring:"admin"},r))}};function Qn(t){return {id:t.id,appId:t.app_id,authorId:t.author_id,body:t.body,createdAt:t.created_at,updatedAt:t.updated_at,deletedAt:t.deleted_at}}var Vn=500;function li(t){if(typeof t!="string"||t.length===0)throw new d({message:"Comment body must be a non-empty string",code:"empty",category:"validation",httpStatus:0,retryable:false,requestId:"",fields:[{name:"body",code:"empty"}]});if(t.length>Vn)throw new d({message:`Comment body must be \u2264 ${Vn} characters (got ${t.length})`,code:"too_long",category:"validation",httpStatus:0,retryable:false,requestId:"",fields:[{name:"body",code:"too_long"}]})}var xt=class{constructor(e){this.http=e;}http;async add(e,n){li(n.body);let r=await this.http.request("POST",`/api/v1/apps/${encodeURIComponent(e)}/comments`,{ring:"admin",body:{body:n.body},idempotent:false});return Qn(r)}async list(e,n){let r={};n?.pageSize!==void 0&&(r.limit=n.pageSize),n?.cursor!==void 0&&(r.cursor=n.cursor);let i=await this.http.request("GET",`/api/v1/apps/${encodeURIComponent(e)}/comments`,{ring:"admin",query:r});return {items:i.items.map(Qn),nextCursor:i.next_cursor,total:i.total}}listAll(e,n){return A(r=>this.list(e,r),n)}async delete(e){await this.http.request("DELETE",`/api/v1/comments/${encodeURIComponent(e)}`,{ring:"admin",idempotent:true});}};var Kn=/^[a-z0-9-]+$/;function Wn(t,e){if(!t||!Kn.test(t))throw new V({message:`Invalid ${e}: must match ${Kn}`,code:"invalid_path",category:"invalid_path",httpStatus:0,retryable:false,requestId:""})}var zn=/^[a-z][a-z0-9]{0,62}$/;function I(t,e="name"){if(!t||!zn.test(t))throw new V({message:`Invalid ${e}: must match ${zn}`,code:"invalid_path",category:"invalid_path",httpStatus:0,retryable:false,requestId:""})}function Xn(t){if(t.publication_status!==void 0)return t.publication_status;switch(t.review_status){case "pending":return "pending_review";case "approved":return "approved";default:return "draft"}}function pi(t){let e={id:t.id??"",slug:t.slug??"",name:t.name??""};return t.tenant_id!==void 0&&(e.tenantId=t.tenant_id),t.description!==void 0&&(e.description=t.description),t.color!==void 0&&(e.color=t.color),t.icon_url!==void 0&&(e.iconUrl=t.icon_url),t.display_order!==void 0&&(e.displayOrder=t.display_order),t.apps_count!==void 0&&(e.appsCount=t.apps_count),t.discoverable_apps_count!==void 0&&(e.discoverableAppsCount=t.discoverable_apps_count),t.created_at!==void 0&&(e.createdAt=t.created_at),t.updated_at!==void 0&&(e.updatedAt=t.updated_at),e}function mi(t){let e={id:t.id??""};return t.name!==void 0&&(e.name=t.name),t.avatar_url!==void 0&&(e.avatarUrl=t.avatar_url),e}function m(t){let e={id:t.id??"",tenantId:t.tenant_id??"",ownerId:t.owner_id??"",slug:t.slug??"",name:t.name??"",schemaName:t.schema_name??"",status:t.status??"draft",visibility:t.visibility??"private",publicationStatus:Xn(t),likeCount:t.like_count??0,subscriberCount:t.subscriber_count??0,createdAt:t.created_at??"",updatedAt:t.updated_at??"",deletedAt:t.deleted_at??null};return t.description!==void 0&&(e.description=t.description),t.icon_url!==void 0&&(e.iconUrl=t.icon_url),t.icon_dark_url!==void 0&&(e.iconDarkUrl=t.icon_dark_url),t.review_status!==void 0&&(e.reviewStatus=t.review_status),t.auth_mode!==void 0&&(e.authMode=t.auth_mode),t.data_scopes!==void 0&&(e.dataScopes=t.data_scopes),t.deploy_method!==void 0&&(e.deployMethod=t.deploy_method),t.resource_tier!==void 0&&(e.resourceTier=t.resource_tier),t.subdomain!==void 0&&(e.subdomain=t.subdomain),t.access_url!==void 0&&(e.accessUrl=t.access_url),t.last_deployment_status!==void 0&&(e.lastDeploymentStatus=t.last_deployment_status),t.operating_status!==void 0&&(e.operatingStatus=t.operating_status),t.suspended_at!==void 0&&(e.suspendedAt=t.suspended_at),t.resumed_at!==void 0&&(e.resumedAt=t.resumed_at),t.category_id!==void 0&&(e.categoryId=t.category_id),t.cost_center!==void 0&&(e.costCenter=t.cost_center),t.category!==void 0&&(e.category=pi(t.category)),t.owner!==void 0&&(e.owner=mi(t.owner)),t.calls_count!==void 0&&(e.callsCount=t.calls_count),t.shared_tables_count!==void 0&&(e.sharedTablesCount=t.shared_tables_count),e}function It(t){let e={slug:t.slug,name:t.name};return t.description!==void 0&&(e.description=t.description),t.iconUrl!==void 0&&(e.icon_url=t.iconUrl),t.iconDarkUrl!==void 0&&(e.icon_dark_url=t.iconDarkUrl),t.categoryId!==void 0&&(e.category_id=t.categoryId),t.costCenter!==void 0&&(e.cost_center=t.costCenter),t.authMode!==void 0&&(e.auth_mode=t.authMode),t.dataScopes!==void 0&&(e.data_scopes=t.dataScopes),t.deployMethod!==void 0&&(e.deploy_method=t.deployMethod),t.resourceTier!==void 0&&(e.resource_tier=t.resourceTier),t.subdomain!==void 0&&(e.subdomain=t.subdomain),e}function St(t){let e={};return t.name!==void 0&&(e.name=t.name),t.description!==void 0&&(e.description=t.description),t.iconUrl!==void 0&&(e.icon_url=t.iconUrl),t.iconDarkUrl!==void 0&&(e.icon_dark_url=t.iconDarkUrl),t.visibility!==void 0&&(e.visibility=t.visibility),t.categoryId!==void 0&&(e.category_id=t.categoryId),t.clearCategory!==void 0&&(e.clear_category=t.clearCategory),t.costCenter!==void 0&&(e.cost_center=t.costCenter),t.clearCostCenter!==void 0&&(e.clear_cost_center=t.clearCostCenter),t.authMode!==void 0&&(e.auth_mode=t.authMode),t.dataScopes!==void 0&&(e.data_scopes=t.dataScopes),t.deployMethod!==void 0&&(e.deploy_method=t.deployMethod),t.resourceTier!==void 0&&(e.resource_tier=t.resourceTier),t.subdomain!==void 0&&(e.subdomain=t.subdomain),t.clearSubdomain!==void 0&&(e.clear_subdomain=t.clearSubdomain),e}function Zn(t,e,n){if(t===void 0)return null;let r=Number(e??1),i=Number(n??20);return r*i<t?String(r+1):null}var Ct=class{constructor(e,n,r,i){this.http=e;this.defaultTenantSlug=n;this.defaultTenantId=r;this.tenantResolver=i;}http;defaultTenantSlug;defaultTenantId;tenantResolver;async resolveTenantId(){if(this.defaultTenantId!==void 0)return this.defaultTenantId;if(this.defaultTenantSlug!==void 0&&this.tenantResolver!==void 0)return this.tenantResolver.resolveTenantId(this.defaultTenantSlug)}async create(e){Wn(e.slug,"slug");let n=await this.resolveTenantId();if(n===void 0)throw new R({message:"apps.create requires a tenant: set defaultTenantId or defaultTenantSlug on AxHubClient. Backend route POST /api/v1/tenants/{tenantID}/apps takes a tenant UUID, not a slug.",code:"tenant_id_required",category:"tenant_id_required",httpStatus:0,retryable:false,requestId:"",fields:[{name:"tenantId",code:"required"}]});let r=It(e),i=await this.http.request("POST",`/api/v1/tenants/${encodeURIComponent(n)}/apps`,{ring:"admin",body:r,idempotent:false});return m(i)}async list(e){let n={},r=e?.perPage??e?.pageSize;r!==void 0&&(n.per_page=r),e?.page!==void 0?n.page=e.page:e?.cursor!==void 0&&(n.page=e.cursor),e?.q!==void 0&&(n.q=e.q),e?.categoryId!==void 0&&(n.category_id=e.categoryId),e?.status!==void 0&&(n.status=e.status),e?.statusIn!==void 0&&(n.status_in=e.statusIn.join(",")),e?.reviewStatus!==void 0&&(n.review_status=e.reviewStatus),e?.reviewStatusIn!==void 0&&(n.review_status_in=e.reviewStatusIn.join(",")),e?.operatingStatus!==void 0&&(n.operating_status=e.operatingStatus),e?.operatingStatusIn!==void 0&&(n.operating_status_in=e.operatingStatusIn.join(",")),e?.sort!==void 0&&(n.sort=e.sort),e?.page!==void 0&&(n.page=e.page),e?.perPage!==void 0&&(n.per_page=e.perPage);let i=await this.resolveTenantId();if(i===void 0)throw new R({message:"apps.list requires a tenant: set defaultTenantId or defaultTenantSlug on AxHubClient. Use apps.listMine() for the caller workspace feed without tenant context.",code:"tenant_id_required",category:"tenant_id_required",httpStatus:0,retryable:false,requestId:"",fields:[{name:"tenantId",code:"required"}]});let s=await this.http.request("GET",`/api/v1/tenants/${encodeURIComponent(i)}/apps`,{ring:"admin",query:n});return {items:s.items.map(m),nextCursor:s.next_cursor??Zn(s.total,n.page,n.per_page),total:s.total,hasNext:(s.next_cursor??Zn(s.total,n.page,n.per_page))!==null,hasPrev:Number(n.page??1)>1}}listAll(e){return A(n=>this.list(n),e)}async get(e){let n=await this.http.request("GET",`/api/v1/apps/${encodeURIComponent(e)}`,{ring:"admin"});return m(n)}async update(e,n){let r=St(n),i=await this.http.request("PATCH",`/api/v1/apps/${encodeURIComponent(e)}`,{ring:"admin",body:r,idempotent:false});return m(i)}async delete(e){await this.http.request("DELETE",`/api/v1/apps/${encodeURIComponent(e)}`,{ring:"admin",idempotent:true});}async permanent(e){await this.http.request("DELETE",`/api/v1/apps/${encodeURIComponent(e)}/permanent`,{ring:"admin",idempotent:false});}async signIconUploadURL(e,n){return this.signIconImpl(e,n,"icon")}async signIconDarkUploadURL(e,n){return this.signIconImpl(e,n,"icon-dark")}async signIconImpl(e,n,r){let i=await this.http.request("POST",`/api/v1/apps/${encodeURIComponent(e)}/${r}/upload-url`,{ring:"admin",body:{content_type:n.contentType},idempotent:false}),s={uploadUrl:i.upload_url??i.put_url??"",getUrl:i.get_url??i.public_url??""};return i.expires_at!==void 0&&(s.expiresAt=i.expires_at),s}async listMine(){return (await this.http.request("GET","/api/v1/me/apps/workspace",{ring:"admin"})).items.map(m)}};var At=class{constructor(e,n,r){this.http=e;this.defaultTenantSlug=n;this.defaultTenantId=r;}http;defaultTenantSlug;defaultTenantId;async search(e){let n={...E(e),q:e?.q,category:e?.category,sort:e?.sort,visibility:e?.visibility,...this.defaultTenantSlug?{tenant_slug:this.defaultTenantSlug}:{}},r=await this.http.request("GET","/api/v1/apps/search",a({ring:"admin",query:n},e));return b(r,m)}feedQuery(e){let n={};return e?.q!==void 0&&(n.q=e.q),e?.category!==void 0&&(n.category=e.category),e?.sort!==void 0&&(n.sort=e.sort),e?.createdWithinDays!==void 0&&(n.created_within_days=e.createdWithinDays),e?.page!==void 0&&(n.page=e.page),e?.perPage!==void 0&&(n.per_page=e.perPage),n}async discoverGlobal(e){let n=await this.http.request("GET","/api/v1/apps/discover",a({ring:"admin",query:this.feedQuery(e)}));return b(n,m)}async discoverTenant(e){if(this.defaultTenantId===void 0)throw new R({message:"apps.discoverTenant requires a tenant UUID: set defaultTenantId on AxHubClient. Backend route GET /api/v1/tenants/{tenantID}/discover/apps takes a tenant UUID, not a slug.",code:"tenant_id_required",category:"tenant_id_required",httpStatus:0,retryable:false,requestId:"",fields:[{name:"tenantId",code:"required"}]});let n=await this.http.request("GET",`/api/v1/tenants/${encodeURIComponent(this.defaultTenantId)}/discover/apps`,a({ring:"admin",query:this.feedQuery(e)}));return b(n,m)}};function gi(t){return {key:t.key,value:t.value,createdAt:t.created_at,updatedAt:t.updated_at}}var Yn=/^[A-Z_][A-Z0-9_]*$/;function ln(t){if(!Yn.test(t))throw new d({message:`Env var key must match ${Yn}`,code:"validation_failed",category:"validation",httpStatus:0,retryable:false,requestId:"",fields:[{name:"key",code:"invalid_format"}]})}var kt=class{constructor(e){this.http=e;}http;async listEnvVars(e){return (await this.http.request("GET",`/api/v1/apps/${encodeURIComponent(e)}/env-vars`,{ring:"admin"})).items.map(gi)}async setEnvVar(e,n,r,i){ln(n);let s={key:n,value:r};i!==void 0&&(s.stage=i),await this.http.request("POST",`/api/v1/apps/${encodeURIComponent(e)}/env-vars`,{ring:"admin",body:s,idempotent:true});}async getEnvVar(e,n){ln(n);let r=(await this.listEnvVars(e)).find(i=>i.key===n);if(!r)throw new f({message:`Env var ${n} not found`,code:"not_found",category:"not_found",httpStatus:404,retryable:false,requestId:"",resource:"env_var"});return r}async deleteEnvVar(e,n){ln(n),await this.http.request("DELETE",`/api/v1/apps/${encodeURIComponent(e)}/env-vars/${encodeURIComponent(n)}`,{ring:"admin",idempotent:true});}};function pn(t){return {connected:true,...t.provider!==void 0?{provider:t.provider}:{},repoFullName:t.repo_full_name,branch:t.branch,installationId:t.installation_id}}function fi(t){return "connected"in t&&t.connected===false?{connected:false,installUrl:t.install_url}:pn(t)}var Tt=class{constructor(e){this.http=e;}http;async get(e){let n=await this.http.request("GET",`/api/v1/apps/${encodeURIComponent(e)}/git-connection`,{ring:"admin"});return fi(n)}async connect(e,n){let r=await this.http.request("POST",`/api/v1/apps/${encodeURIComponent(e)}/git-connection`,{ring:"admin",body:{repo_full_name:n.repoFullName,branch:n.branch,installation_id:n.installationId,state:n.state},idempotent:false});return pn(r)}async update(e,n){let r=await this.http.request("PATCH",`/api/v1/apps/${encodeURIComponent(e)}/git-connection`,{ring:"admin",body:{branch:n.branch},idempotent:false});return pn(r)}async disconnect(e){await this.http.request("DELETE",`/api/v1/apps/${encodeURIComponent(e)}/git-connection`,{ring:"admin",idempotent:true});}async installStart(e,n){let r=await this.http.request("GET",`/api/v1/apps/${encodeURIComponent(e)}/git/github/install/start`,{ring:"admin",query:void 0});if(typeof r=="string")return {redirectUrl:r};let i=r;return {redirectUrl:i.redirect_url??i.install_url??i.location??""}}};function yi(t){return {id:t.id,appId:t.app_id,userId:t.user_id,allowedScopes:t.allowed_scopes??[],grantedAt:t.granted_at??"",createdAt:t.created_at??""}}var Pt=class{constructor(e){this.http=e;}http;async create(e,n){let r=await this.http.request("POST",`/api/v1/apps/${encodeURIComponent(e)}/invitations`,{ring:"admin",body:{user_id:n.userId},idempotent:false});return yi(r)}async delete(e,n){await this.http.request("DELETE",`/api/v1/apps/${encodeURIComponent(e)}/invitations/${encodeURIComponent(n)}`,{ring:"admin",idempotent:true});}};var Et=class{constructor(e){this.http=e;}http;async suspend(e){let n=await this.http.request("POST",`/api/v1/apps/${encodeURIComponent(e)}/suspend`,{ring:"admin",body:{},idempotent:false});return m(n)}async resume(e){let n=await this.http.request("POST",`/api/v1/apps/${encodeURIComponent(e)}/resume`,{ring:"admin",body:{},idempotent:false});return m(n)}};var qt=class{constructor(e){this.http=e;}http;async like(e){return {inserted:(await this.http.request("POST",`/api/v1/apps/${encodeURIComponent(e)}/likes`,{ring:"admin",idempotent:true}))?.inserted??true}}async unlike(e){try{return {deleted:(await this.http.request("DELETE",`/api/v1/apps/${encodeURIComponent(e)}/likes`,{ring:"admin",idempotent:!0}))?.deleted??!0}}catch(n){if(hi(n))return {deleted:false};throw n}}async me(e){return {liked:(await this.http.request("GET",`/api/v1/apps/${encodeURIComponent(e)}/likes/me`,{ring:"admin"})).liked}}};function hi(t){return typeof t=="object"&&t!==null&&"httpStatus"in t&&t.httpStatus===404}function bi(t){let e={id:t.id,appId:t.app_id,userId:t.user_id,allowedScopes:t.allowed_scopes??[],grantedAt:t.granted_at??""};return t.email!==void 0&&(e.email=t.email),t.granted_by_id!==void 0&&(e.grantedById=t.granted_by_id),e}var Ot=class{constructor(e){this.http=e;}http;async list(e,n){let r={};n?.page!==void 0&&(r.page=n.page),n?.perPage!==void 0&&(r.per_page=n.perPage);let i=await this.http.request("GET",`/api/v1/apps/${encodeURIComponent(e)}/members`,a({ring:"admin",query:r},n));return b(i,bi)}};var Dt=class{constructor(e){this.http=e;}http;async owned(e){let n=await this.http.request("GET","/api/v1/me/apps/owned",a({ring:"admin"},e));return b(n,m)}async received(e){let n=await this.http.request("GET","/api/v1/me/apps/received",a({ring:"admin"},e));return b(n,m)}};function Jn(t){return {id:t.id,appId:t.app_id,name:t.name,clientId:t.client_id??t.id,redirectUris:t.redirect_uris,scopes:t.scopes??t.allowed_scopes??[],createdAt:t.created_at}}function Ri(t){return {...Jn(t),clientSecret:t.client_secret}}var Ut=class{constructor(e){this.http=e;}http;async create(e,n){if(!n.scopes||n.scopes.length===0)throw new d({message:"scopes must be a non-empty array",code:"empty",category:"validation",httpStatus:0,retryable:false,requestId:"",fields:[{name:"scopes",code:"empty"}]});let r=await this.http.request("POST",`/api/v1/apps/${encodeURIComponent(e)}/oauth-clients`,{ring:"admin",body:{name:n.name,type:n.type??"confidential",token_endpoint_auth_method:n.tokenEndpointAuthMethod??(n.type==="public"?"none":"client_secret_post"),redirect_uris:n.redirectUris,allowed_scopes:n.scopes,allowed_grant_types:n.allowedGrantTypes??["authorization_code","refresh_token"],...n.allowedResources!==void 0?{allowed_resources:n.allowedResources}:{}},idempotent:false});return Ri(r)}async get(e){let n=await this.http.request("GET",`/api/v1/oauth-clients/${encodeURIComponent(e)}`,{ring:"admin"});return Jn(n)}};function er(t){let e={id:t.id,appId:t.app_id,requesterId:t.requester_id,status:t.status,createdAt:t.created_at,updatedAt:t.updated_at};t.reason!==void 0&&(e.reason=t.reason),t.reviewer_id!==void 0&&(e.reviewerId=t.reviewer_id);let n=t.reviewer_comment??t.review_comment;return n!==void 0&&(e.reviewerComment=n),e}var Lt=class{constructor(e){this.http=e;}http;async submit(e,n){let r={};n?.reason!==void 0&&(r.reason=n.reason);let i=await this.http.request("POST",`/api/v1/apps/${encodeURIComponent(e)}/review-requests`,{ring:"admin",body:r,idempotent:false});return er(i)}async list(e,n){let r={};n?.pageSize!==void 0&&(r.limit=n.pageSize),n?.cursor!==void 0&&(r.cursor=n.cursor);let i=await this.http.request("GET",`/api/v1/apps/${encodeURIComponent(e)}/review-requests`,{ring:"admin",query:r});return {items:i.items.map(er),nextCursor:i.next_cursor,total:i.total}}async unpublish(e,n){let r={visibility:"private"};n?.comment!==void 0&&(r.review_comment=n.comment);let i=await this.http.request("PATCH",`/api/v1/apps/${encodeURIComponent(e)}`,{ring:"admin",body:r,idempotent:false});return m(i)}};function tr(t){switch(t){case "timestamp":return "timestamptz";case "json":return "jsonb";default:return t}}function nr(t){if(t!==void 0)return t===null?null:String(t)}function wi(t){switch(t){case "integer":return "int";case "timestamp with time zone":return "timestamptz";case "jsonb":return "jsonb";case "numeric":return "float";default:return t}}function vi(t){let e={name:t.name,type:wi(t.type)};return t.nullable!==void 0&&(e.nullable=t.nullable),t.default!==void 0&&(e.default=t.default),e}function mn(t){return {appId:t.app_id,schemaName:t.schema_name??"",tableName:t.table_name??t.name??"",ownerColumn:t.owner_column??"",columns:(t.columns??[]).map(vi),createdAt:t.created_at??"",updatedAt:t.updated_at??""}}function _i(t){return {...mn(t),indexes:t.indexes??[],constraints:t.constraints??[],rowCount:t.row_count,sizeBytes:t.size_bytes}}function rr(t,e=""){return {id:t.id,appId:t.app_id,tableName:t.table_name??e,principalType:t.principal_type,principalId:t.principal_id,scopes:t.scopes??t.actions??[],createdAt:t.granted_at??t.created_at??""}}var Mt=class{constructor(e){this.http=e;}http;async list(e){return (await this.http.request("GET",`/api/v1/apps/${encodeURIComponent(e)}/tables`,{ring:"admin"})).items.map(mn)}async create(e,n){I(n.name,"name");let r=await this.http.request("POST",`/api/v1/apps/${encodeURIComponent(e)}/tables`,{ring:"admin",body:{table_name:n.name,owner_column:n.ownerColumn,...n.description!==void 0?{description:n.description}:{},columns:n.columns.map(i=>({name:i.name,type:tr(i.type),...i.nullable!==void 0?{nullable:i.nullable}:{},...i.default!==void 0?{default:nr(i.default)}:{}}))},idempotent:false});return mn(r)}async delete(e,n){I(n,"tableName"),await this.http.request("DELETE",`/api/v1/apps/${encodeURIComponent(e)}/tables/${encodeURIComponent(n)}`,{ring:"admin",idempotent:true});}async addColumn(e,n,r){I(n,"tableName");let i={name:r.name,type:tr(r.type)};r.nullable!==void 0&&(i.nullable=r.nullable),r.default!==void 0&&(i.default=nr(r.default)),await this.http.request("POST",`/api/v1/apps/${encodeURIComponent(e)}/tables/${encodeURIComponent(n)}/columns`,{ring:"admin",body:{column:i},idempotent:false});}async dropColumn(e,n,r){I(n,"tableName"),await this.http.request("DELETE",`/api/v1/apps/${encodeURIComponent(e)}/tables/${encodeURIComponent(n)}/columns/${encodeURIComponent(r)}`,{ring:"admin",idempotent:true});}async listGrants(e,n){return I(n,"tableName"),(await this.http.request("GET",`/api/v1/apps/${encodeURIComponent(e)}/tables/${encodeURIComponent(n)}/grants`,{ring:"admin"})).items.map(i=>rr(i,n))}async addGrant(e,n,r){I(n,"tableName");let i=await this.http.request("POST",`/api/v1/apps/${encodeURIComponent(e)}/tables/${encodeURIComponent(n)}/grants`,{ring:"admin",body:{principal_type:r.principalType,principal_id:r.principalId,actions:r.scopes},idempotent:false});return rr(i,n)}async revokeGrant(e,n,r){I(n,"tableName"),await this.http.request("DELETE",`/api/v1/apps/${encodeURIComponent(e)}/tables/${encodeURIComponent(n)}/grants/${encodeURIComponent(r)}`,{ring:"admin",idempotent:true});}async inspect(e,n){I(n,"tableName");let r=await this.http.request("GET",`/api/v1/apps/${encodeURIComponent(e)}/tables/${encodeURIComponent(n)}`,{ring:"admin"});return _i(r)}async checkAvailability(e,n){I(n,"tableName");let r=await this.http.request("GET",`/api/v1/apps/${encodeURIComponent(e)}/tables/check-availability`,{ring:"admin",query:{table_name:n}});return {available:r.available,reason:r.reason??""}}async columnTypes(e){return ((await this.http.request("GET",`/api/v1/apps/${encodeURIComponent(e)}/tables/column-types`,{ring:"admin"})).types??[]).map(r=>({value:r.value,label:r.label}))}async browseRows(e,n,r){I(n,"tableName");let i={};r?.page!==void 0&&(i.page=r.page),r?.perPage!==void 0&&(i.per_page=r.perPage);let s=await this.http.request("GET",`/api/v1/apps/${encodeURIComponent(e)}/tables/${encodeURIComponent(n)}/rows`,a({ring:"admin",query:i},r));return {columns:(s.columns??[]).map(o=>({name:o.name,type:o.type,nullable:o.nullable})),rows:s.rows??[],meta:{page:s.meta?.page??1,perPage:s.meta?.per_page??0,total:s.meta?.total??0,totalPages:s.meta?.total_pages??0}}}};var $t=class{constructor(e,n){this.http=e;this.defaultTenantSlug=n;}http;defaultTenantSlug;async list(e){let n={...E(e),...this.defaultTenantSlug?{tenant_slug:this.defaultTenantSlug}:{}},r=await this.http.request("GET","/api/v1/templates",a({ring:"admin",query:n},e));return b(r,i=>i)}};var Ye=class{crud;lifecycle;availability;envVars;publication;access;invitations;members;me;categories;discover;likes;comments;oauthClients;git;tables;templates;constructor(e,n,r,i){this.crud=new Ct(e,n,r,i),this.lifecycle=new Et(e),this.availability=new vt(e,r),this.envVars=new kt(e),this.publication=new Lt(e),this.access=new wt(e),this.invitations=new Pt(e),this.members=new Ot(e),this.me=new Dt(e),this.categories=new _t(e),this.discover=new At(e,n,r),this.likes=new qt(e),this.comments=new xt(e),this.oauthClients=new Ut(e),this.git=new Tt(e),this.tables=new Mt(e),this.templates=new $t(e,n);}create=(...e)=>this.crud.create(...e);list=(...e)=>this.crud.list(...e);listAll=(...e)=>this.crud.listAll(...e);get=(...e)=>this.crud.get(...e);update=(...e)=>this.crud.update(...e);delete=(...e)=>this.crud.delete(...e);permanent=(...e)=>this.crud.permanent(...e);signIconUploadURL=(...e)=>this.crud.signIconUploadURL(...e);signIconDarkUploadURL=(...e)=>this.crud.signIconDarkUploadURL(...e);listMine=(...e)=>this.crud.listMine(...e);suspend=(...e)=>this.lifecycle.suspend(...e);resume=(...e)=>this.lifecycle.resume(...e);checkAvailability=(...e)=>this.availability.checkAvailability(...e);iconPreCreateUrl=(...e)=>this.availability.iconPreCreateUrl(...e);listEnvVars=(...e)=>this.envVars.listEnvVars(...e);setEnvVar=(...e)=>this.envVars.setEnvVar(...e);getEnvVar=(...e)=>this.envVars.getEnvVar(...e);deleteEnvVar=(...e)=>this.envVars.deleteEnvVar(...e)};var et=class{constructor(e,n,r){this.http=e;this.defaultTenantId=n;this.tenantResolver=r;}http;defaultTenantId;tenantResolver;tenant(e){return new j(this.http,e,this.tenantResolver)}summary(e){return this.defaultTenant().summary(e)}byCostCenter(e){return this.defaultTenant().byCostCenter(e)}byApp(e){return this.defaultTenant().byApp(e)}timeseries(e){return this.defaultTenant().timeseries(e)}export(e){return this.defaultTenant().export(e)}defaultTenant(){if(!this.defaultTenantId)throw new R({message:"sdk.cost requires defaultTenantId or sdk.cost.tenant(tenantIdOrSlug)",code:"tenant_id_required",category:"tenant_id_required",httpStatus:0,retryable:false,requestId:"",fields:[{name:"tenantId",code:"required"}]});return new j(this.http,this.defaultTenantId,this.tenantResolver)}},j=class{constructor(e,n,r){this.http=e;this.tenantIdOrSlug=n;this.tenantResolver=r;}http;tenantIdOrSlug;tenantResolver;async summary(e){let n=await this.http.request("GET",`${await this.base()}/summary`,a({ring:"admin",query:Je(e)},e));return xi(n)}async byCostCenter(e){let n=await this.http.request("GET",`${await this.base()}/by-cost-center`,a({ring:"admin",query:Je(e)},e));return {rows:(n.rows??[]).map(Ci),unassigned:{appCount:n.unassigned?.app_count??0,cost:n.unassigned?.cost??0}}}async byApp(e){return {rows:((await this.http.request("GET",`${await this.base()}/by-app`,a({ring:"admin",query:{...Je(e),...e?.sort?{sort:e.sort}:{}}},e))).rows??[]).map(Ii)}}async timeseries(e){return {series:((await this.http.request("GET",`${await this.base()}/timeseries`,a({ring:"admin",query:{...Je(e),...e?.appId?{app_id:e.appId}:{}}},e))).series??[]).map(r=>({date:r.date??"",total:r.total??0,byResource:r.by_resource??{}}))}}async export(e){return this.http.request("GET",`${await this.base()}/export`,a({ring:"admin",query:{...Je(e),format:e?.format??"csv"}},e))}async base(){let e=this.tenantResolver?await this.tenantResolver.resolveTenantId(this.tenantIdOrSlug):this.tenantIdOrSlug;return `/api/v1/tenants/${u(e)}/cost`}};function Je(t){return t?.month?{month:t.month}:{}}function xi(t){let e={month:t.month??"",currency:t.currency??"KRW",total:t.total??0,billedTotal:t.billed_total??0,forecastMonthEnd:t.forecast_month_end??0,partialMonth:t.partial_month??false};return t.top_driver&&(e.topDriver={resourceKind:t.top_driver.resource_kind??"",share:t.top_driver.share??0}),t.last_rolled_up_at!==void 0&&(e.lastRolledUpAt=t.last_rolled_up_at),e}function Ci(t){return {costCenter:t.cost_center??"",appCount:t.app_count??0,cost:t.cost??0,...t.budget!==void 0?{budget:t.budget}:{},...t.budget_pct!==void 0?{budgetPct:t.budget_pct}:{},...t.over!==void 0?{over:t.over}:{},byResource:t.by_resource??{},byResourceQty:t.by_resource_qty??{}}}function Ii(t){return {appId:t.app_id??"",name:t.name??"",...t.cost_center!==void 0?{costCenter:t.cost_center}:{},cost:t.cost??0,byResource:t.by_resource??{},byResourceQty:t.by_resource_qty??{}}}var tt=class{constructor(e,n){this.http=e;this.tenantResolver=n;}http;tenantResolver;tenant(e){return new Z(this.http,e,this.tenantResolver)}async preview(e,n){let r=await this.http.request("GET",`/api/v1/invite-links/${u(e)}`,a({ring:"public"},n));return Si(r)}async accept(e,n){let r=await this.http.request("POST",`/api/v1/invite-links/${u(e)}/accept`,a({ring:"admin",body:{},idempotent:true},n));return {tenantId:r.tenant_id??"",tenantSlug:r.tenant_slug??"",joined:r.joined??false,alreadyMember:r.already_member??false}}},Z=class{constructor(e,n,r){this.http=e;this.tenantIdOrSlug=n;this.tenantResolver=r;}http;tenantIdOrSlug;tenantResolver;async create(e,n){let r={};e?.expiresAt!==void 0&&(r.expires_at=e.expiresAt);let i=await this.http.request("POST",await this.base(),a({ring:"admin",body:r,idempotent:false},n));return ir(i)}async list(e){let n=await this.http.request("GET",await this.base(),a({ring:"admin"},e));return b({items:n.items,next_cursor:n.next_cursor??null,total:n.total??n.items.length},ir)}async revoke(e,n){await this.http.request("DELETE",`${await this.base()}/${u(e)}`,a({ring:"admin",idempotent:true},n));}async base(){let e=this.tenantResolver?await this.tenantResolver.resolveTenantId(this.tenantIdOrSlug):this.tenantIdOrSlug;return `/api/v1/tenants/${u(e)}/invite-links`}};function ir(t){return {id:t.id??"",tenantId:t.tenant_id??"",...t.url!==void 0?{url:t.url}:{},role:t.role??"",status:t.status??"",...t.expires_at!==void 0?{expiresAt:t.expires_at}:{},joinCount:t.join_count??0,createdAt:t.created_at??""}}function Si(t){let e={valid:t.valid??false};return t.tenant&&(e.tenant={name:t.tenant.name??"",...t.tenant.icon_url!==void 0?{iconUrl:t.tenant.icon_url}:{}}),e}var nt=class{constructor(e,n,r,i){this.slug=e;this.root=r;this.apps=new Gt(e,n.http,i),this.cost=new j(n.http,e,i),this.inviteLinks=new Z(n.http,e,i);}slug;root;apps;cost;inviteLinks;get gateway(){return this.root.gateway.scoped(this.slug)}app(e){return new Bt(this.slug,e,this.root)}},Gt=class{constructor(e,n,r){this.tenantSlug=e;this.http=n;this.tenantResolver=r;}tenantSlug;http;tenantResolver;async create(e,n){let r=await this.tenantResolver.resolveTenantId(this.tenantSlug,n),i=await this.http.request("POST",`/api/v1/tenants/${u(r)}/apps`,a({ring:"admin",body:It(e),idempotent:false},n));return m(i)}async list(e){let n=await this.tenantResolver.resolveTenantId(this.tenantSlug,e),r=await this.http.request("GET",`/api/v1/tenants/${u(n)}/apps`,a({ring:"admin",query:E(e)},e));return b(r,m)}listAll(e){return A(n=>this.list({...e,...n}),e)}async get(e,n){let r=await this.http.request("GET",`/api/v1/apps/${u(e)}`,a({ring:"admin"},n));return m(r)}async update(e,n,r){let i=await this.http.request("PATCH",`/api/v1/apps/${u(e)}`,a({ring:"admin",body:St(n),idempotent:false},r));return m(i)}async delete(e,n){await this.http.request("DELETE",`/api/v1/apps/${u(e)}`,a({ring:"admin",idempotent:true},n));}},Bt=class{constructor(e,n,r){this.tenantSlug=e;this.appSlug=n;this.root=r;this.data=new Ht(e,n,r.data);}tenantSlug;appSlug;root;data},Ht=class{constructor(e,n,r){this.tenantSlug=e;this.appSlug=n;this.rootData=r;}tenantSlug;appSlug;rootData;table(e){return this.rootData.table(this.tenantSlug,this.appSlug,e)}discover(e,n){return this.rootData.discover(this.tenantSlug,this.appSlug,e,n)}invalidateSchema(e){e===void 0?this.rootData.invalidateSchema():this.rootData.invalidateSchema(this.tenantSlug,this.appSlug,e);}};function Ai(t){let e={clientId:String(t.client_id??""),raw:t};return t.client_id_issued_at!==void 0&&(e.clientIdIssuedAt=t.client_id_issued_at),t.client_name!==void 0&&(e.clientName=t.client_name),t.redirect_uris!==void 0&&(e.redirectUris=t.redirect_uris),t.grant_types!==void 0&&(e.grantTypes=t.grant_types),t.response_types!==void 0&&(e.responseTypes=t.response_types),t.scope!==void 0&&(e.scope=t.scope),t.token_endpoint_auth_method!==void 0&&(e.tokenEndpointAuthMethod=t.token_endpoint_auth_method),e}function sr(t){return {...t,id:String(t.id),clientId:t.client_id??t.id,tenantId:t.tenant_id??t.tenantId,redirectUris:t.redirect_uris??t.redirectUris,scopes:t.scopes??t.allowed_scopes}}function jt(t){return {accessToken:String(t.access_token??""),tokenType:String(t.token_type??"Bearer"),expiresIn:t.expires_in,refreshToken:t.refresh_token,scope:t.scope,raw:t}}function ki(t){if(!t.name||t.name.trim()==="")throw new d({message:"name is required and must be non-empty",code:"validation_failed",category:"validation",httpStatus:0,retryable:false,requestId:"",fields:[{name:"name",code:"empty"}]});if(t.expiresInDays!==void 0&&t.expiresInDays<0)throw new d({message:"expiresInDays must be non-negative",code:"validation_failed",category:"validation",httpStatus:0,retryable:false,requestId:"",fields:[{name:"expiresInDays",code:"invalid_value"}]})}function Ti(t){if(typeof t!="object"||t===null)return false;let e=t.user;if(typeof e!="object"||e===null)return false;let n=e;return typeof n.id=="string"&&typeof n.email=="string"}var rt=class{constructor(e,n){this.http=e;this.pat=new Ft(e,n),this.meClient=new Y(e),this.oauth=new Nt(e,n),this.oidc=new Vt(e,n),this.deviceCode=new Kt(e,n),this.systemOAuthClients=new zt(e),this.invitations=new Qt(e);}http;pat;meClient;oauth;oidc;deviceCode;systemOAuthClients;invitations;issuePersonalAccessToken(e,n){return this.pat.issue(e,n)}listPersonalAccessTokens(e){return this.pat.list(e)}revokePersonalAccessToken(e,n){return this.pat.revoke(e,n)}me(e){return this.meClient.get(e)}},Ft=class{constructor(e,n){this.http=e;this.defaultTenantSlug=n;}http;defaultTenantSlug;tenantQuery(){return this.defaultTenantSlug?{tenant_slug:this.defaultTenantSlug}:void 0}async issue(e,n){ki(e);let r={name:e.name};e.expiresInDays!==void 0&&(r.expires_in_days=e.expiresInDays);let i=await this.http.request("POST","/api/v1/me/personal-access-tokens",a({ring:"admin",query:this.tenantQuery(),body:r,idempotent:false},n));return {patId:i.id,name:i.name,rawToken:i.raw_token,createdAt:i.created_at,expiresAt:i.expires_at}}async list(e){return (await this.http.request("GET","/api/v1/me/personal-access-tokens",a({ring:"admin",query:this.tenantQuery()},e))).items.map(r=>({id:r.id,name:r.name,createdAt:r.created_at,expiresAt:r.expires_at,lastUsedAt:r.last_used_at}))}async revoke(e,n){await this.http.request("DELETE",`/api/v1/me/personal-access-tokens/${u(e)}`,a({ring:"admin",query:this.tenantQuery(),idempotent:true},n));}},Y=class{constructor(e){this.http=e;}http;async get(e){let n=await this.http.request("GET","/api/v1/me",a({ring:"admin"},e));return Ti(n)?{...n,userId:n.user.id,email:n.user.email,name:n.user.name,platformAdmin:n.user.platform_admin,tenants:n.tenants?.map(i=>({tenantId:i.tenant_id,tenantSlug:i.tenant_slug,role:i.role,isActive:i.is_active,iconUrl:i.icon_url}))}:n}},Nt=class{constructor(e,n){this.http=e;this.defaultTenantSlug=n;}http;defaultTenantSlug;tenantQuery(e={}){let n=this.defaultTenantSlug?{...e,tenant_slug:this.defaultTenantSlug}:e;return Object.keys(n).length>0?n:void 0}authorizeUrl(e){let n=new URLSearchParams({response_type:"code",client_id:e.clientId,redirect_uri:e.redirectUri});return this.defaultTenantSlug&&n.set("tenant_slug",this.defaultTenantSlug),e.scope&&n.set("scope",e.scope),e.state&&n.set("state",e.state),e.codeChallenge&&n.set("code_challenge",e.codeChallenge),e.codeChallengeMethod&&n.set("code_challenge_method",e.codeChallengeMethod),e.resource&&n.set("resource",e.resource),`/oauth/authorize?${n.toString()}`}async exchangeCode(e,n){if(!e.codeVerifier)throw new d({message:"codeVerifier is required for PKCE",code:"required",category:"validation",httpStatus:0,retryable:false,requestId:"",fields:[{name:"codeVerifier",code:"required"}]});let r=await this.http.request("POST","/oauth/token",a({ring:"public",query:this.tenantQuery(),form:{grant_type:"authorization_code",code:e.code,client_id:e.clientId,redirect_uri:e.redirectUri,code_verifier:e.codeVerifier,client_secret:e.clientSecret,resource:e.resource},idempotent:false},n));return jt(r)}async refreshTokens(e,n){let r=await this.http.request("POST","/oauth/token",a({ring:"public",query:this.tenantQuery(),form:{grant_type:"refresh_token",refresh_token:e.refreshToken,client_id:e.clientId,client_secret:e.clientSecret,resource:e.resource},idempotent:false},n));return jt(r)}async revoke(e,n){await this.http.request("POST","/oauth/revoke",a({ring:"public",query:this.tenantQuery(),form:{token:e.token,token_type_hint:e.tokenTypeHint,client_id:e.clientId},idempotent:true},n));}userinfo(e){return this.http.request("GET","/oauth/userinfo",a({ring:"admin"},e))}async registerMcpClient(e,n){let r=H({client_name:e.clientName,client_uri:e.clientUri,redirect_uris:e.redirectUris,grant_types:e.grantTypes,response_types:e.responseTypes,scope:e.scope,token_endpoint_auth_method:e.tokenEndpointAuthMethod,resource:e.resource,resources:e.resources,software_id:e.softwareId,software_version:e.softwareVersion}),i=await this.http.request("POST","/oauth/register",a({ring:"public",body:r,idempotent:false},n));return Ai(i)}async selectTenant(e,n){return {redirectTo:(await this.http.request("POST","/oauth/authorize/tenant",a({ring:"admin",body:H({client_id:e.clientId,redirect_uri:e.redirectUri,tenant_id:e.tenantId,scope:e.scope,state:e.state,code_challenge:e.codeChallenge,code_challenge_method:e.codeChallengeMethod,nonce:e.nonce,resource:e.resource}),idempotent:false},n))).redirect_to??""}}async getClient(e,n){let r=await this.http.request("GET",`/api/v1/oauth-clients/${u(e)}`,a({ring:"admin"},n));return sr(r)}async revokeOwnGrant(e,n){await this.http.request("DELETE",`/api/v1/oauth/clients/${u(e)}/grants/me`,a({ring:"admin",idempotent:true},n));}},Qt=class{constructor(e){this.http=e;}http;async accept(e,n){await this.http.request("POST",`/api/v1/me/invitations/${u(e)}/accept`,a({ring:"admin",body:{},idempotent:false},n));}},Vt=class{constructor(e,n){this.http=e;this.defaultTenantSlug=n;}http;defaultTenantSlug;tenantQuery(e={}){let n=this.defaultTenantSlug?{...e,tenant_slug:this.defaultTenantSlug}:e;return Object.keys(n).length>0?n:void 0}discovery(e){return this.http.request("GET","/.well-known/openid-configuration",a({ring:"public"},e))}jwks(e){return this.http.request("GET","/.well-known/jwks.json",a({ring:"public"},e))}providers(e){return this.http.request("GET","/auth/providers",a({ring:"public",query:this.tenantQuery()},e))}async startURL(e,n,r){let i=await this.http.request("GET",`/auth/${u(e)}/start`,a({ring:"public",query:this.tenantQuery(H({redirect_to:n?.redirectTo,state:n?.state,return_origin:n?.returnOrigin})),parseBody:true},r));return i.url??i.redirect_url??`/auth/${u(e)}/start`}googleStartUrl(e){let n=new URLSearchParams;this.defaultTenantSlug&&n.set("tenant_slug",this.defaultTenantSlug),e?.returnTo&&n.set("return_to",e.returnTo),e?.returnOrigin&&n.set("return_origin",e.returnOrigin);let r=n.toString();return r?`/auth/google_oauth2/start?${r}`:"/auth/google_oauth2/start"}exchangeCallback(e,n){return this.http.request("GET",e.provider?`/auth/${u(e.provider)}/callback`:"/auth/oidc/callback",a({ring:"public",query:this.tenantQuery(H(e))},n)).then(jt)}githubStartUrl(e){let n=new URLSearchParams;this.defaultTenantSlug&&n.set("tenant_slug",this.defaultTenantSlug),e?.returnTo&&n.set("return_to",e.returnTo);let r=n.toString();return r?`/auth/github?${r}`:"/auth/github"}githubCallbackUrl(e){let n=new URLSearchParams;this.defaultTenantSlug&&n.set("tenant_slug",this.defaultTenantSlug),e.code&&n.set("code",e.code),e.state&&n.set("state",e.state),e.error&&n.set("error",e.error);let r=n.toString();return r?`/auth/github/callback?${r}`:"/auth/github/callback"}},Kt=class{constructor(e,n){this.http=e;this.defaultTenantSlug=n;}http;defaultTenantSlug;tenantQuery(){return this.defaultTenantSlug?{tenant_slug:this.defaultTenantSlug}:void 0}async request(e,n){let r=await this.http.request("POST","/oauth/device_authorization",a({ring:"public",query:this.tenantQuery(),form:{client_id:e.clientId,scope:e.scope},idempotent:false},n));return {deviceCode:r.device_code,userCode:r.user_code,verificationUri:r.verification_uri,verificationUriComplete:r.verification_uri_complete,expiresIn:r.expires_in,interval:r.interval??5,raw:r}}async poll(e,n){let r=e.intervalMs??5e3;for(;;)try{let i=await this.http.request("POST","/oauth/token",a({ring:"public",query:this.tenantQuery(),form:{grant_type:"urn:ietf:params:oauth:grant-type:device_code",device_code:e.deviceCode,client_id:e.clientId},idempotent:!1},{...n,signal:n?.signal??e.signal}));return jt(i)}catch(i){if(i instanceof B)r+=5e3;else if(!(i instanceof G))throw i;await new Promise((s,o)=>{let c=setTimeout(s,r);e.signal?.addEventListener("abort",()=>{clearTimeout(c),o(e.signal?.reason??i);},{once:true});});}}},zt=class{constructor(e){this.http=e;}http;async get(e,n){let r=await this.http.request("GET",`/api/v1/oauth-clients/${u(e)}`,a({ring:"admin"},n));return sr(r)}};var Pi=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,it=class{me;cache=new Map;constructor(e){this.me=new Y(e);}async resolveTenantId(e,n){if(Pi.test(e))return e;let r=this.cache.get(e);if(r!==void 0)return r;let i=await this.me.get(n);for(let o of i.tenants??[])this.cache.set(o.tenantSlug,o.tenantId);let s=this.cache.get(e);if(s===void 0)throw new R({message:`tenant slug "${e}" not found among your memberships; pass a tenant UUID or join the tenant. Backend route /api/v1/tenants/{tenantID}/apps parses {tenantID} as a UUID.`,code:"tenant_id_required",category:"tenant_id_required",httpStatus:0,retryable:false,requestId:"",fields:[{name:"tenantId",code:"required"}]});return s}};function gn(t,e){if(Ei(t))return {...t,...e?.validate!==void 0?{validate:e.validate}:{}};let n={};for(let[i,s]of Object.entries(t.columns))n[i]={table:t.table,name:i,def:s};let r={table:t.table,columns:t.columns,cols:n};return e?.validate!==void 0&&(r.validate=e.validate),r}function Ei(t){return typeof t=="object"&&t!==null&&"table"in t&&"columns"in t&&"cols"in t}var or=1024,qi=4,Oi=6;function Wt(t){return t.length===0?t:t.replace(/[\\%_]/g,e=>`\\${e}`)}function Di(t){if(t.length>or)throw new d({message:`LIKE pattern exceeds ${or} chars; refuse to compile`,code:"like_pattern_too_long",category:"validation",httpStatus:0,retryable:false,requestId:"",docUrl:"https://docs.axhub.dev/errors/validation/like-pattern"});let e=0,n=0;for(let r=0;r<t.length;r+=1){let i=t[r];if(i==="\\"){r+=1,e=0;continue}if(i==="%"){if(e+=1,e>=qi)throw new d({message:`LIKE pattern has ${e} consecutive '%'; refuse to compile (ReDoS guard)`,code:"like_pattern_redos",category:"validation",httpStatus:0,retryable:false,requestId:"",docUrl:"https://docs.axhub.dev/errors/validation/like-pattern"})}else e===1&&(n+=1),e=0;}if(n>Oi)throw new d({message:`LIKE pattern has ${n} '%X%' alternation segments; refuse to compile (ReDoS guard)`,code:"like_pattern_redos",category:"validation",httpStatus:0,retryable:false,requestId:"",docUrl:"https://docs.axhub.dev/errors/validation/like-pattern"})}function Ui(t,e){return e?{op:"raw",sql:t,params:e}:{op:"raw",sql:t}}function Li(...t){return {op:"and",clauses:t}}function Mi(...t){return {op:"or",clauses:t}}function $i(t){return {op:"not",clause:t}}function Gi(t){let e=typeof t=="string"?t:t.name,n=(r,i)=>({op:r,column:e,value:i});return {eq:r=>n("eq",r),ne:r=>n("ne",r),gt:r=>n("gt",r),gte:r=>n("gte",r),lt:r=>n("lt",r),lte:r=>n("lte",r),in:r=>({op:"in",column:e,values:r}),like:{contains:r=>n("like",`%${Wt(r)}%`),startsWith:r=>n("like",`${Wt(r)}%`),endsWith:r=>n("like",`%${Wt(r)}`),raw:r=>(Di(r),n("like",r))}}}function q(t,e,n){let r=t?.validate;if(r===void 0)return;if(!Bi(r))throw new K({message:"defineSchema validate option requires a Zod-compatible schema with safeParse()",code:"zod_missing",category:"configuration",httpStatus:0,retryable:false,requestId:"",resource:t?.table,docUrl:"https://docs.axhub.dev/errors/configuration/zod-missing"});let s=(n==="update"&&typeof r.partial=="function"?r.partial():r).safeParse(e);if(s.success)return;let o=s.error?.issues??[],c=o.map(l=>({name:l.path?.join(".")||"$",code:l.code??"invalid",message:l.message}));throw new d({message:`${o.length||1} validation failure${o.length===1?"":"s"} before network request`,code:"zod_validation_failed",category:"validation",httpStatus:0,retryable:false,requestId:"",resource:t?.table,fields:c,docUrl:"https://docs.axhub.dev/errors/validation/zod"})}function Bi(t){return typeof t=="object"&&t!==null&&typeof t.safeParse=="function"}var ar=100,ur=10,cr=5e3;async function lr(t,e,n,r,i){try{return await Hi(t,e,n,r,i)}catch(s){if(mr(s))try{return await ji(t,e,n,r,i)}catch(o){throw dr(o,e,n,r)}throw dr(s,e,n,r)}}async function Hi(t,e,n,r,i){let s=await t.request("GET",`/api/v1/tenants/${u(e)}/apps/${u(n)}/tables/${u(r)}/inspect`,a({ring:"admin"},i));return pr(r,s)}async function ji(t,e,n,r,i){let s=await Fi(t,e,n,i);if(!s)throw new M({message:`Dynamic data table '${r}' was not found`,code:"table_not_found",category:"not_found",httpStatus:404,retryable:false,requestId:"",resource:`${e}/${n}/${r}`,docUrl:"https://docs.axhub.dev/sdk/data#discover"});let o=await t.request("GET",`/api/v1/apps/${u(s)}/tables/${u(r)}`,a({ring:"admin"},i));return pr(r,o)}async function Fi(t,e,n,r){let i=Date.now(),s;for(let o=0;o<ur;o+=1){if(r?.signal?.aborted)throw new h({message:"discover aborted while resolving app id",code:"aborted",category:"abort",httpStatus:0,retryable:false,requestId:""});if(Date.now()-i>cr)throw new $({message:`app lookup budget exceeded (${cr}ms) while searching for slug '${n}' in tenant '${e}'`,code:"introspect_failed",category:"internal",httpStatus:0,retryable:false,requestId:"",resource:`${e}/${n}`,docUrl:"https://docs.axhub.dev/sdk/data#discover"});let c=await t.request("GET","/api/v1/apps",a({ring:"admin",query:{tenant_slug:e,limit:ar,cursor:s}},r)),l=c.items??[],C=l.find(P=>P.slug===n&&typeof P.id=="string");if(C?.id)return C.id;if(o===0&&l.length===0||!c.next_cursor)return;s=c.next_cursor;}throw new z({message:`App lookup exceeded ${ur} pages \xD7 ${ar} apps without finding slug '${n}'`,code:"scan_limit_exceeded",category:"internal",httpStatus:0,retryable:false,requestId:"",resource:`${e}/${n}`,docUrl:"https://docs.axhub.dev/errors/internal/scan-limit-exceeded"})}function dr(t,e,n,r){return t instanceof M||t instanceof $||t instanceof z||t instanceof h?t:mr(t)?new M({message:`Dynamic data table '${r}' was not found`,code:"table_not_found",category:"not_found",httpStatus:404,retryable:false,requestId:Ki(t),resource:`${e}/${n}/${r}`,cause:t,docUrl:"https://docs.axhub.dev/sdk/data#discover"}):fn(t)&&t.httpStatus>=500?new $({message:`Failed to introspect dynamic data table '${r}'`,code:"introspect_failed",category:"internal",httpStatus:t.httpStatus,retryable:t.retryable,requestId:t.requestId,resource:`${e}/${n}/${r}`,cause:t,docUrl:"https://docs.axhub.dev/sdk/data#discover"}):t instanceof Error?t:new Error(String(t))}var Ni=new Set(["__proto__","constructor","prototype"]),Qi=/^[A-Za-z_][A-Za-z0-9_]*$/;function pr(t,e){let n=e.columns??[],r=Object.create(null);for(let i of n)Ni.has(i.name)||Qi.test(i.name)&&(r[i.name]=Vi(i));return gn({table:e.tableName??e.table_name??e.name??t,columns:r})}function Vi(t){switch(t.type){case "uuid":return "uuid";case "int":case "integer":case "bigint":return "integer";case "float":case "numeric":case "double precision":case "real":return "number";case "bool":case "boolean":return "boolean";case "timestamp":case "timestamptz":case "timestamp with time zone":return "timestamp";case "json":case "jsonb":return "json";default:return "string"}}function mr(t){return t instanceof f||fn(t)&&t.httpStatus===404}function fn(t){return typeof t=="object"&&t!==null&&"httpStatus"in t&&"requestId"in t}function Ki(t){return fn(t)?t.requestId:""}function yn(t){if(t!==void 0)return [...t].join(",")}function J(t,e){if(e===void 0)return;if(e.length===0)throw new d({message:"select must include at least one column; omit select to fetch full rows",code:"select_empty",category:"validation",httpStatus:0,retryable:false,requestId:"",resource:t?.table,docUrl:"https://docs.axhub.dev/errors/validation/select-unknown-column"});if(!t)return;let n=new Set(Object.keys(t.columns)),r=e.filter(i=>!n.has(i));if(r.length!==0)throw new d({message:`select contains unknown column${r.length===1?"":"s"}: ${r.join(", ")}`,code:"select_unknown_column",category:"validation",httpStatus:0,retryable:false,requestId:"",resource:t.table,fields:r.map(i=>({name:i,code:"unknown_column"})),docUrl:"https://docs.axhub.dev/errors/validation/select-unknown-column"})}function st(t,e){if(e===void 0)return t;let n={};for(let r of e)r in t&&(n[r]=t[r]);return n}function Xt(t,e){return e===void 0?t:t.map(n=>st(n,e))}function zi(t){if(typeof t!="object"||t===null)return false;let e=t.httpStatus;return typeof e=="number"&&e>=500}var ee=class{store=new Map;inflight=new Map;maxEntries;ttlMs;negativeTtlMs;writeCounter=0;constructor(e){this.maxEntries=Math.max(1,e?.maxEntries??1e3),this.ttlMs=Math.max(1,e?.ttlMs??3e5),this.negativeTtlMs=Math.max(0,e?.negativeTtlMs??3e4);}get size(){return this.store.size}get(e){let n=this.store.get(e);return n?n.expiresAt<=Date.now()?(this.store.delete(e),null):(this.store.delete(e),this.store.set(e,n),n.schema):null}set(e,n,r){this.writeCounter+=1;let i=this.writeCounter;this.store.delete(e),this.store.set(e,{schema:n,expiresAt:Date.now()+Math.max(1,r?.ttlMs??this.ttlMs),writeToken:i}),this.evictOverflow();}invalidate(e){if(e===void 0){this.store.clear(),this.inflight.clear();return}this.store.delete(e),this.inflight.delete(e);}async getOrSet(e,n,r){if(!r?.fresh){let c=this.get(e);if(c)return c;let l=this.inflight.get(e);if(l)return l}let i=this.store.get(e),s=this.writeCounter+1,o=n().then(c=>{let l=this.store.get(e);return (!l||l.writeToken<s)&&this.set(e,c,r),this.inflight.get(e)===o&&this.inflight.delete(e),c},c=>{throw this.inflight.get(e)===o&&this.inflight.delete(e),i&&this.negativeTtlMs>0&&zi(c)&&(this.writeCounter+=1,this.store.delete(e),this.store.set(e,{schema:i.schema,expiresAt:Date.now()+this.negativeTtlMs,writeToken:this.writeCounter})),c});return this.inflight.set(e,o),o}evictOverflow(){for(;this.store.size>this.maxEntries;){let e=this.store.keys().next().value;if(e===void 0)return;this.store.delete(e);}}};function ot(t,e,n){return `${t}/${e}/${n}`}function hn(t){t!==void 0&&Rn(t,{allowAnd:true});}function bn(t){if(t===void 0)return {};let e={};for(let n of Rn(t,{allowAnd:true}))Wi(e,n.column,n.value);return e}function Wi(t,e,n){let r=t[e];r===void 0?t[e]=n:Array.isArray(r)?r.push(n):t[e]=[r,n];}function Rn(t,e){switch(t.op){case "eq":case "ne":case "gt":case "gte":case "lt":case "lte":case "like":return [{column:t.column,value:`${t.op}.${gr(t.value)}`}];case "in":{let n=t.values.map(i=>gr(i)),r=n.find(i=>i.includes(","));if(r!==void 0)throw fr(`IN filter values cannot contain commas because the live backend uses comma-separated IN lists (bad value: ${r})`,"filter_in_comma",t.column,"https://docs.axhub.dev/sdk/data#filter-in-comma");return [{column:t.column,value:`in.${n.join(",")}`}]}case "and":if(e.allowAnd)return t.clauses.flatMap(n=>Rn(n,{allowAnd:false}));break;}throw fr(`Data where clause '${t.op}' cannot be pushed to the live backend; use top-level and(eq/ne/gt/gte/lt/lte/in/like) only`,"unsupported_filter",void 0,"https://docs.axhub.dev/sdk/data#pushable-filters")}function gr(t){return t instanceof Date?t.toISOString():t===null?"null":typeof t=="string"||typeof t=="number"||typeof t=="boolean"||typeof t=="bigint"?String(t):JSON.stringify(t)}function fr(t,e,n,r){return new d({message:t,code:e,category:"validation",httpStatus:0,retryable:false,requestId:"",...n!==void 0?{resource:n}:{},...r!==void 0?{docUrl:r}:{}})}function ne(t,e){switch(e.op){case "eq":return e.value===null||t[e.column]===null||t[e.column]===void 0?false:t[e.column]===e.value;case "ne":return e.value===null||t[e.column]===null||t[e.column]===void 0?false:t[e.column]!==e.value;case "gt":{let n=t[e.column];return n==null||e.value===null||e.value===void 0?false:te(n,e.value)>0}case "gte":{let n=t[e.column];return n==null||e.value===null||e.value===void 0?false:te(n,e.value)>=0}case "lt":{let n=t[e.column];return n==null||e.value===null||e.value===void 0?false:te(n,e.value)<0}case "lte":{let n=t[e.column];return n==null||e.value===null||e.value===void 0?false:te(n,e.value)<=0}case "in":return t[e.column]===null||t[e.column]===void 0?false:e.values.filter(n=>n!==null).includes(t[e.column]);case "like":return Xi(t[e.column],String(e.value));case "and":return e.clauses.every(n=>ne(t,n));case "or":return e.clauses.some(n=>ne(t,n));case "not":return !ne(t,e.clause);case "raw":return true}}function te(t,e){return t==null||e===null||e===void 0?Number.NaN:typeof t=="number"&&typeof e=="number"?t-e:String(t).localeCompare(String(e))}function Xi(t,e){if(typeof t!="string")return false;let n="^";for(let r=0;r<e.length;r++){let i=e[r]??"";i==="\\"?(r+=1,n+=yr(e[r]??"")):i==="%"?n+=".*":i==="_"?n+=".":n+=yr(i);}return new RegExp(`${n}$`).test(t)}function yr(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Zi(t,e){let n=Rt(e);return n.length===0?[...t]:[...t].sort((r,i)=>{for(let s of n){let o=te(r[s.field],i[s.field]);if(!(Number.isNaN(o)||o===0))return s.dir==="desc"?-o:o}return 0})}function hr(t,e){let n=Zi(t,e?.orderBy);if(e?.after!==void 0||e?.before!==void 0)throw new v({message:"after/before keyset cursors are not supported by AX Hub offset pagination",code:"legacy_cursor",category:"validation",httpStatus:0,retryable:false,requestId:""});let r=Math.min(100,Math.max(1,Math.trunc(e?.pageSize??e?.limit??20))),i=e?.cursor===void 0?1:Yi(e.cursor),s=(i-1)*r,o=n.slice(s,s+r),c=s+r<n.length,l=i>1;return {items:o,nextCursor:c?String(i+1):null,firstCursor:l?String(i-1):null,hasNext:c,hasPrev:l}}function Yi(t){if(t.startsWith("v1:")||t.startsWith("v2:"))throw new v({message:"keyset cursor tokens are not supported by AX Hub offset pagination",code:"legacy_cursor",category:"validation",httpStatus:0,retryable:false,requestId:""});let e=Number(t);if(!Number.isInteger(e)||e<1)throw new _({message:"Plain mock cursor must be a positive integer page",code:"invalid_cursor",category:"validation",httpStatus:0,retryable:false,requestId:"",docUrl:"https://docs.axhub.dev/errors/validation/invalid-cursor"});return e}async function br(t,e){F(e?.signal),J(t.schema,e?.select),hn(e?.where);let n=t.store.list(t.key);e?.where&&(n=n.filter(s=>ne(s,e.where)));let r=hr(n,e);return {items:Xt(r.items,e?.select),nextCursor:r.nextCursor,firstCursor:r.firstCursor,hasNext:r.hasNext,hasPrev:r.hasPrev,total:n.length,totalIsExact:true}}async function Rr(t,e){F(e?.signal),hn(e?.where);let n=t.store.list(t.key);return e?.where?n.filter(r=>ne(r,e.where)).length:n.length}async function wr(t,e,n){F(n?.signal),J(t.schema,n?.select);let r=t.store.get(t.key,e);if(!r)throw new f({message:`Mock row not found: ${t.key}/${e}`,code:"row_not_found",category:"not_found",httpStatus:404,retryable:false,requestId:"",resource:`${t.key}/${e}`});return st(r,n?.select)}async function vr(t,e,n){return F(n?.signal),q(t.schema,e,"insert"),t.store.insert(t.key,e)}async function _r(t,e,n){F(n?.signal);for(let i of e)q(t.schema,i,"insert");let r=e.map(i=>t.store.insert(t.key,i));return {items:r,count:r.length}}async function xr(t,e,n,r){return F(r?.signal),q(t.schema,n,"update"),t.store.update(t.key,e,n)}async function Cr(t,e,n){F(n?.signal),t.store.delete(t.key,e);}function F(t){if(t?.aborted)throw new h({message:"Mock operation aborted",code:"aborted",category:"abort",httpStatus:0,retryable:false,requestId:""})}var at=class{constructor(e,n){this.http=e;this.schemaCache=n?.schemaCache instanceof ee?n.schemaCache:new ee(n?.schemaCache),this.mockStore=n?.mockStore;}http;schemaCache;mockStore;table(e,n,r){let i=typeof r=="string"?void 0:r,s=typeof r=="string"?r:r.table;return new re(this.http,e,n,s,i,this.mockStore?{store:this.mockStore,key:ot(e,n,s),schema:i}:void 0)}scoped(e){return new wn(this,e)}async discover(e,n,r,i){let s=ot(e,n,r);if(this.mockStore){let c=this.mockStore.schema(s)??es(r,this.mockStore.list(s));return new re(this.http,e,n,c.table,c,{store:this.mockStore,key:s,schema:c})}let o=await this.schemaCache.getOrSet(s,()=>lr(this.http,e,n,r,i),{fresh:i?.fresh,ttlMs:i?.ttlMs});return new re(this.http,e,n,o.table,o)}invalidateSchema(e,n,r){if(e!==void 0&&n!==void 0&&r!==void 0){this.schemaCache.invalidate(ot(e,n,r));return}this.schemaCache.invalidate();}},wn=class{constructor(e,n){this.data=e;this.tenantSlug=n;}data;tenantSlug;app(e){return new vn(this.data,this.tenantSlug,e)}},vn=class{constructor(e,n,r){this.data=e;this.tenantSlug=n;this.appSlug=r;}data;tenantSlug;appSlug;table(e){return this.data.table(this.tenantSlug,this.appSlug,e)}discover(e,n){return this.data.discover(this.tenantSlug,this.appSlug,e,n)}invalidateSchema(e){e===void 0?this.data.invalidateSchema():this.data.invalidateSchema(this.tenantSlug,this.appSlug,e);}},re=class{constructor(e,n,r,i,s,o){this.http=e;this.tenantSlug=n;this.appSlug=r;this.tableName=i;this.schema=s;this.mockRuntime=o;}http;tenantSlug;appSlug;tableName;schema;mockRuntime;path(e){let n=`/data/${u(this.tenantSlug)}/${u(this.appSlug)}/${u(this.tableName)}`;return e===void 0?n:`${n}/${u(e)}`}async list(e){if(this.mockRuntime)return br(this.mockRuntime,e);J(this.schema,e?.select),ns(e,this.tableName);let n=ts(e?.cursor,e?.page,this.tableName),r=rs(e?.pageSize??e?.limit),i={...bn(e?.where)};r!==void 0&&(i.per_page=r),n!==1&&(i.page=n);let s=Gn(e?.orderBy);s&&(i.sort=s);let o=yn(e?.select);o!==void 0&&(i._select=o);let c=await this.http.request("GET",this.path(),a({ring:"data",query:i},e)),l=Xt(c.items,e?.select),C=c.page??n,P=c.has_more??false,gt=C>1;return {items:l,nextCursor:P?String(C+1):null,firstCursor:gt?String(C-1):null,hasNext:P,hasPrev:gt,totalIsExact:false}}listAll(e){return A(n=>this.list({...e,...n}),e)}async count(e){return this.mockRuntime?Rr(this.mockRuntime,e):(await this.http.request("GET",`${this.path()}/_count`,a({ring:"data",query:bn(e?.where)},e))).count}async get(e,n){if(this.mockRuntime)return wr(this.mockRuntime,e,n);J(this.schema,n?.select);let r=yn(n?.select),i=await this.http.request("GET",this.path(e),a({ring:"data",query:r===void 0?void 0:{_select:r}},n));return st(i,n?.select)}async insert(e,n){return this.mockRuntime?vr(this.mockRuntime,e,n):(q(this.schema,e,"insert"),this.http.request("POST",this.path(),a({ring:"data",body:e,idempotent:false},n)))}async insertMany(e,n){if(this.mockRuntime)return _r(this.mockRuntime,e,n);for(let s of e)q(this.schema,s,"insert");let r=[],i=n?.signal;for(let s of e){if(i?.aborted)throw new h({message:`insertMany aborted after ${r.length} of ${e.length} rows`,code:"aborted",category:"abort",httpStatus:0,retryable:false,requestId:"",resource:this.tableName});r.push(await this.insert(s,n));}return {items:r,count:r.length}}async update(e,n,r){return this.mockRuntime?xr(this.mockRuntime,e,n,r):(q(this.schema,n,"update"),this.http.request("PATCH",this.path(e),a({ring:"data",body:n,idempotent:false},r)))}async delete(e,n){if(this.mockRuntime)return Cr(this.mockRuntime,e,n);await this.http.request("DELETE",this.path(e),a({ring:"data",idempotent:true},n));}},Ji=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function es(t,e){let n={},r=e[0]??{id:"mock_id"};for(let[s,o]of Object.entries(r))typeof o=="number"?n[s]="number":typeof o=="boolean"?n[s]="boolean":o!==null&&typeof o=="object"?n[s]="json":typeof o=="string"&&Ji.test(o)||s==="id"?n[s]="uuid":n[s]="string";let i=Object.fromEntries(Object.entries(n).map(([s,o])=>[s,{table:t,name:s,def:o}]));return {table:t,columns:n,cols:i}}function ts(t,e,n){if(t!==void 0)return is(t,n),Number(t);if(e===void 0)return 1;if(!Number.isInteger(e)||e<1)throw ss("page must be a positive integer",n);return e}function ns(t,e){let n=t;if(n?.after!==void 0||n?.before!==void 0||n?.direction!==void 0)throw new v({message:"after/before keyset cursors are not supported by the live AX Hub data API; use cursor/page numeric offset pagination",code:"legacy_cursor",category:"validation",httpStatus:0,retryable:false,requestId:"",resource:e,docUrl:"https://docs.axhub.dev/errors/validation/legacy-cursor"})}function rs(t){if(t!==void 0)return Number.isFinite(t)?Math.min(100,Math.max(1,Math.trunc(t))):100}function is(t,e){if(t.length>Ze)throw new _({message:`Cursor token exceeds maximum size (${Ze} chars)`,code:"invalid_cursor",category:"validation",httpStatus:0,retryable:false,requestId:"",resource:e,docUrl:"https://docs.axhub.dev/errors/validation/invalid-cursor"});if(t.startsWith("v1:"))throw new v({message:"Legacy v1: cursor token is not compatible with AX Hub offset-only pagination; restart pagination without cursor",code:"legacy_cursor",category:"validation",httpStatus:0,retryable:false,requestId:"",resource:e,docUrl:"https://docs.axhub.dev/errors/validation/legacy-cursor"});if(Hn(t))throw new v({message:"v2 keyset cursors are not supported by the live AX Hub data API; restart pagination and use the numeric cursor returned by list()",code:"legacy_cursor",category:"validation",httpStatus:0,retryable:false,requestId:"",resource:e,docUrl:"https://docs.axhub.dev/errors/validation/legacy-cursor"});let n=Number(t);if(!Number.isInteger(n)||n<1)throw new _({message:"Plain cursor must be a positive integer page or a v2: keyset token",code:"invalid_cursor",category:"validation",httpStatus:0,retryable:false,requestId:"",resource:e,docUrl:"https://docs.axhub.dev/errors/validation/invalid-cursor"})}function ss(t,e){return new _({message:t,code:"invalid_cursor",category:"validation",httpStatus:0,retryable:false,requestId:"",resource:e,docUrl:"https://docs.axhub.dev/errors/validation/invalid-cursor"})}function _n(t){return {id:t.id,appId:t.app_id,commitSha:t.commit_sha,status:t.status,currentStage:t.current_stage??null,imageUri:t.image_uri??null,triggerSource:t.trigger_source,startedAt:t.started_at??null,completedAt:t.completed_at??null,failureReason:t.failure_reason??null}}var ut=class{constructor(e,n){this.http=e;this.defaultTenantId=n;}http;defaultTenantId;async create(e,n){let r={};n?.commitSha!==void 0&&(r.commit_sha=n.commitSha),n?.forceRebuild!==void 0&&(r.force_rebuild=n.forceRebuild);let i=await this.http.request("POST",`/api/v1/apps/${encodeURIComponent(e)}/deployments`,{ring:"admin",body:r,idempotent:false});return _n(i)}async list(e,n){let r={};n?.pageSize!==void 0&&(r.per_page=n.pageSize),n?.cursor!==void 0&&(r.page=n.cursor);let i=await this.http.request("GET",`/api/v1/apps/${encodeURIComponent(e)}/deployments`,{ring:"admin",query:r});return {items:i.items.map(_n),nextCursor:i.next_cursor??(i.has_more??(i.page??Number(r.page??1))*(i.per_page??Number(r.per_page??20))<(i.total??0)?String((i.page??Number(r.page??1))+1):null),total:i.total}}listAll(e,n){return A(r=>this.list(e,r),n)}async get(e,n){let r=await this.http.request("GET",`/api/v1/apps/${encodeURIComponent(e)}/deployments/${encodeURIComponent(n)}`,{ring:"admin"});return _n(r)}async cancel(e,n){await this.http.request("POST",`/api/v1/apps/${encodeURIComponent(e)}/deployments/${encodeURIComponent(n)}/cancel`,{ring:"admin",body:{},idempotent:true});}async rollback(e,n){await this.http.request("POST",`/api/v1/apps/${encodeURIComponent(e)}/deployments/${encodeURIComponent(n)}/rollback`,{ring:"admin",body:{},idempotent:false});}async logs(e,n){let r={};n?.direction!==void 0&&(r.direction=n.direction),n?.cursor!==void 0&&(r.cursor=n.cursor),n?.since!==void 0&&(r.since=n.since),n?.until!==void 0&&(r.until=n.until),n?.limit!==void 0&&(r.limit=n.limit);let i=await this.http.request("GET",`/api/v1/apps/${encodeURIComponent(e)}/logs`,{ring:"admin",query:r});return {lines:(i.lines??[]).map(s=>({ts:s.ts??"",container:s.container??"",message:s.message??"",insertId:s.insert_id??""})),nextCursor:i.next_cursor??"",hasMore:i.has_more??false}}requireTenantId(e,n){if(this.defaultTenantId===void 0)throw new R({message:`deployments.${e} requires a tenant UUID: set defaultTenantId on AxHubClient. Backend route ${n} takes a tenant UUID, not a slug.`,code:"tenant_id_required",category:"tenant_id_required",httpStatus:0,retryable:false,requestId:"",fields:[{name:"tenantId",code:"required"}]});return this.defaultTenantId}async startBootstrap(e){let n=this.requireTenantId("startBootstrap","POST /api/v1/tenants/{tenantID}/app-bootstraps"),r={name:e.name,slug:e.slug,subdomain:e.subdomain,template_id:e.templateId,github_installation_id:e.githubInstallationId,github_owner:e.githubOwner,repo_name:e.repoName};e.repoPrivate!==void 0&&(r.repo_private=e.repoPrivate);let i=await this.http.request("POST",`/api/v1/tenants/${encodeURIComponent(n)}/app-bootstraps`,{ring:"admin",body:r,idempotent:false});return {bootstrapId:i.bootstrap_id,statusUrl:i.status_url}}async bootstrapStatus(e){let n=this.requireTenantId("bootstrapStatus","GET /api/v1/tenants/{tenantID}/app-bootstraps/{bootstrapID}"),r=await this.http.request("GET",`/api/v1/tenants/${encodeURIComponent(n)}/app-bootstraps/${encodeURIComponent(e)}`,{ring:"admin"}),i={id:r.id??e,stage:r.stage??"",status:r.status??""};return r.app_id&&(i.appId=r.app_id),r.deployment_id&&(i.deploymentId=r.deployment_id),r.repo_full_name&&(i.repoFullName=r.repo_full_name),r.error_code&&(i.errorCode=r.error_code),r.error_message&&(i.errorMessage=r.error_message),i}async githubAccounts(){return ((await this.http.request("GET","/api/v1/github/accounts",{ring:"admin"})).accounts??[]).map(n=>{let r={login:n.login??"",type:n.type??"",installed:n.installed??false};return n.installation_id!==void 0&&(r.installationId=n.installation_id),n.avatar_url!==void 0&&(r.avatarUrl=n.avatar_url),n.install_url!==void 0&&(r.installUrl=n.install_url),r})}async githubRepos(e,n){let r={};n?.page!==void 0&&(r.page=n.page),n?.perPage!==void 0&&(r.per_page=n.perPage);let i=await this.http.request("GET",`/api/v1/github/installations/${encodeURIComponent(String(e))}/repositories`,{ring:"admin",query:r});return {repositories:(i.repositories??[]).map(s=>({id:s.id??0,name:s.name??"",fullName:s.full_name??"",private:s.private??false,defaultBranch:s.default_branch??""})),totalCount:i.total_count??0}}};var ct=class{constructor(e,n){this.http=e;this.tenantResolver=n;}http;tenantResolver;scoped(e){return new Zt(this.http,e,this.tenantResolver)}async engines(e){return (await this.http.request("GET","/api/v1/engines",a({ring:"admin"},e))??[]).map(r=>({engine:r.engine??"",kind:r.kind??"",displayName:r.display_name??"",supportedActions:r.supported_actions??[],allowedEffects:r.allowed_effects??{}}))}},Zt=class{query;catalog;constructor(e,n,r){this.query=new xn(e,n,r),this.catalog=new Yt(e,n,r);}};function Ir(t,e){return new S({message:e,code:"required",category:"validation",httpStatus:0,retryable:false,requestId:"",fields:[{name:t,code:"required"}]})}function Ar(t){return (t??[]).map(e=>({name:e.name,dataType:e.data_type}))}function kr(t,e){return (e??[]).map(n=>{let r={};return t.forEach((i,s)=>{r[i.name]=n[s]??null;}),r})}var xn=class{constructor(e,n,r){this.http=e;this.tenantIdOrSlug=n;this.tenantResolver=r;}http;tenantIdOrSlug;tenantResolver;async run(e,n){try{let r=e.connectorId??e.resourceId;if(!r)throw Ir("connectorId","gateway.query.run requires connectorId (or legacy resourceId)");if(!e.path)throw Ir("path","gateway.query.run requires resource path");let i=await this.http.request("POST",await this.base(),a({ring:"admin",body:{connector_id:r,path:e.path,sql:e.sql,params:e.params,row_limit:e.rowLimit},idempotent:!0},n)),s=Ar(i.columns),o=kr(s,i.rows);return {allowed:i.allowed??!0,...i.deny_reason?{denyReason:i.deny_reason}:{},columns:s,rows:o,rowCount:o.length,...i.matched_policies?{matchedPolicies:i.matched_policies}:{}}}catch(r){throw typeof r=="object"&&r!==null&&"httpStatus"in r&&r.httpStatus===401?new L({message:"Gateway pool credentials are stale after refresh retry",code:"pool_stale",category:"unauthenticated",httpStatus:401,retryable:false,requestId:"requestId"in r?String(r.requestId):""}):r}}async base(){let e=this.tenantResolver?await this.tenantResolver.resolveTenantId(this.tenantIdOrSlug):this.tenantIdOrSlug;return `/api/v1/tenants/${u(e)}/gateway/query`}};function Tr(t){return {allowed:t.allowed,...t.deny_reason?{denyReason:t.deny_reason}:{},...t.row_filter?{rowFilter:t.row_filter}:{},...t.mask?{mask:t.mask}:{},...t.input_schema!==void 0?{inputSchema:t.input_schema}:{},...t.result_schema!==void 0?{resultSchema:t.result_schema}:{}}}function os(t){return {...Tr(t),...t.allowed_columns?{allowedColumns:t.allowed_columns}:{},...t.column_masks?{columnMasks:t.column_masks}:{}}}function Pr(t){return {id:t.id,connector:t.connector,connectorId:t.connector_id,path:t.path,url:t.url,...t.kind?{kind:t.kind}:{},type:t.type,name:t.name,attributes:t.attributes??{},tags:t.tags??[],permissions:{read:Tr(t.permissions.read)}}}function as(t){return {id:t.id,connector:t.connector,connectorId:t.connector_id,path:t.path,url:t.url,...t.kind?{kind:t.kind}:{},type:t.type,name:t.name,attributes:t.attributes??{},tags:t.tags??[],ancestors:t.ancestors??[],children:(t.children??[]).map(Pr),permissions:{read:os(t.permissions.read)}}}function Sr(t){return t.split("/").map(e=>u(e)).join("/")}var Yt=class{constructor(e,n,r){this.http=e;this.tenantIdOrSlug=n;this.tenantResolver=r;}http;tenantIdOrSlug;tenantResolver;async listKinds(e){return ((await this.http.request("GET","/api/v1/catalog/kinds",a({ring:"admin"},e))).items??[]).map(r=>({kind:r.kind,engine:r.engine,displayName:r.display_name,invokable:r.invokable,actions:Object.fromEntries(Object.entries(r.actions??{}).map(([i,s])=>[i,{allowedEffects:s.allowed_effects??[],...s.input_schema!==void 0?{inputSchema:s.input_schema}:{},...s.result_schema!==void 0?{resultSchema:s.result_schema}:{}}]))}))}async listConnectors(e){return ((await this.http.request("GET",`${await this.base()}/connectors`,a({ring:"admin"},e))).items??[]).map(r=>({id:r.id,name:r.name,engine:r.engine,url:r.url,...r.description?{description:r.description}:{}}))}async listResources(e,n){let r={};return e?.search&&(r.search=e.search),e?.kind&&(r.kind=e.kind),e?.connector&&(r.connector=e.connector),e?.connectorId&&(r.connector_id=e.connectorId),e?.limit!==void 0&&(r.limit=e.limit),((await this.http.request("GET",`${await this.base()}/resources`,a({ring:"admin",query:r},n))).items??[]).map(Pr)}async getResource(e,n,r){return this.http.request("GET",`${await this.base()}/resources/${u(e)}/${Sr(n)}`,a({ring:"admin"},r)).then(as)}async invoke(e,n,r,i){let s=await this.http.request("POST",`${await this.base()}/resources/${u(e)}/${Sr(n)}:read`,a({ring:"admin",body:H({sql:r.sql,params:r.params,row_limit:r.rowLimit}),idempotent:true},i)),o=Ar(s.result?.columns),c=kr(o,s.result?.rows);return {allowed:s.allowed??false,action:s.action,...s.deny_reason?{denyReason:s.deny_reason}:{},columns:o,rows:c,rowCount:c.length,...s.matched_policies?{matchedPolicies:s.matched_policies}:{}}}async hasAccess(e,n,r){try{return await this.getResource(e,n,r),!0}catch(i){if(i instanceof f)return false;throw i}}async base(){let e=this.tenantResolver?await this.tenantResolver.resolveTenantId(this.tenantIdOrSlug):this.tenantIdOrSlug;return `/api/v1/tenants/${u(e)}/catalog`}async listResourcesWithDetail(e,n){let r=await this.listResources(e,n);return Promise.all(r.map(i=>this.getResource(i.connector,i.path,n)))}};function us(t){return t.allowed===true}function Er(t){let e=t.denyReason??"";return t.allowed===false&&(e.startsWith("SQL \uD615\uC2DD \uC624\uB958:")||e.includes("safesql:"))}function cs(t){return t.allowed===false&&!Er(t)}function ds(t){return t.permissions.read.allowedColumns??[]}function ls(t,e){return t.permissions.read.columnMasks?.[e]??null}function ps(t){let e=t.split("/").filter(Boolean);return e[e.length-1]??""}function Jt(t){let e={id:t.id,appId:t.app_id,requesterId:t.requester_id,status:t.status,createdAt:t.created_at,updatedAt:t.updated_at};t.reason!==void 0&&(e.reason=t.reason),t.reviewer_id!==void 0&&(e.reviewerId=t.reviewer_id);let n=t.reviewer_comment??t.review_comment;return n!==void 0&&(e.reviewerComment=n),e}var dt=class{constructor(e){this.http=e;}http;async get(e){let n=await this.http.request("GET",`/api/v1/review-requests/${encodeURIComponent(e)}`,{ring:"admin"});return Jt(n)}async approve(e,n){return this.settle(e,"approve",n)}async reject(e,n){return this.settle(e,"reject",n)}async settle(e,n,r){let i={};r?.comment!==void 0&&(i.comment=r.comment);let s=await this.http.request("POST",`/api/v1/review-requests/${encodeURIComponent(e)}/${n}`,{ring:"admin",body:i,idempotent:false});return Jt(s)}async listPending(e,n){if(!e||e.trim()==="")throw new S({message:"tenantId is required: GET /api/v1/review-requests/pending needs a tenant_id query parameter",code:"required",category:"validation",httpStatus:0,retryable:false,requestId:"",fields:[{name:"tenantId",code:"required"}]});let r={tenant_id:e};n?.pageSize!==void 0&&(r.per_page=n.pageSize),n?.cursor!==void 0&&(r.page=n.cursor);let i=await this.http.request("GET","/api/v1/review-requests/pending",{ring:"admin",query:r});return {items:i.items.map(Jt),nextCursor:i.next_cursor,total:i.total}}async history(e,n){if(!e||e.trim()==="")throw new S({message:"tenantId is required: GET /api/v1/review-requests/history needs a tenant_id query parameter",code:"required",category:"validation",httpStatus:0,retryable:false,requestId:"",fields:[{name:"tenantId",code:"required"}]});let r={tenant_id:e};n?.pageSize!==void 0&&(r.per_page=n.pageSize),n?.cursor!==void 0&&(r.page=n.cursor);let i=await this.http.request("GET","/api/v1/review-requests/history",{ring:"admin",query:r});return {items:i.items.map(Jt),nextCursor:i.next_cursor,total:i.total}}};function ms(t){return {...t,id:String(t.id),slug:String(t.slug),name:String(t.name),createdAt:t.created_at??t.createdAt,updatedAt:t.updated_at??t.updatedAt}}var lt=class{constructor(e){this.http=e;}http;async get(e,n){let r=await this.http.request("GET",`/api/v1/tenants/${u(e)}`,a({ring:"admin"},n));return ms(r)}};var pt=class{constructor(e){this.http=e;}http;async public(e){let n=await this.http.request("GET","/config/public",a({ring:"public"},e));return {...n,baseDomain:n.base_domain??""}}};var mt=class{initialFixtures;tables=new Map;schemas;nextId=1;constructor(e,n){this.initialFixtures=gs(e??{}),this.schemas=n??{},this.reset();}keys(){return [...this.tables.keys()]}schema(e){return this.schemas[e]}list(e){return [...this.tables.get(e)?.values()??[]].map(n=>({...n}))}get(e,n){let r=this.tables.get(e)?.get(n);return r?{...r}:null}insert(e,n){let r=typeof n.id=="string"?n.id:`mock_${this.nextId++}`,i=this.ensureTable(e);if(i.has(r))throw new g({message:`Mock row already exists: ${e}/${r}`,code:"duplicate_key",category:"conflict",httpStatus:409,retryable:false,requestId:"",resource:`${e}/${r}`});let o={created_at:new Date().toISOString(),...n,id:r};return i.set(r,o),{...o}}update(e,n,r){let i=this.ensureTable(e),s=i.get(n);if(!s)throw new f({message:`Mock row not found: ${e}/${n}`,code:"row_not_found",category:"not_found",httpStatus:404,retryable:false,requestId:"",resource:`${e}/${n}`});let o={...s,...r,id:n,updated_at:new Date().toISOString()};return i.set(n,o),{...o}}delete(e,n){let r=this.tables.get(e);if(!r||!r.has(n))throw new f({message:`Mock row not found: ${e}/${n}`,code:"row_not_found",category:"not_found",httpStatus:404,retryable:false,requestId:"",resource:`${e}/${n}`});r.delete(n);}reset(e){if(e!==void 0){this.tables.set(e,qr(this.initialFixtures[e]??[]));return}this.tables=new Map;for(let[n,r]of Object.entries(this.initialFixtures))this.tables.set(n,qr(r));}ensureTable(e){let n=this.tables.get(e);return n||(n=new Map,this.tables.set(e,n)),n}};function qr(t){let e=new Map;for(let n of t){let r=typeof n.id=="string"?n.id:`mock_${e.size+1}`;e.set(r,{...n,id:r});}return e}function gs(t){return Object.fromEntries(Object.entries(t).map(([e,n])=>[e,n.map(r=>({...r}))]))}function Cn(t){if(t.mode==="mock")return Or(),new mt(t.fixtures,t.schemas)}var fs=new Set(["1","true","yes","on"]);function ys(t){return t?.trim().toLowerCase()==="production"}function hs(t){return t===void 0?false:fs.has(t.trim().toLowerCase())}function Or(){if(ys(process.env.NODE_ENV)){if(hs(process.env.AX_HUB_ALLOW_MOCK_IN_PROD)){console.warn("[@ax-hub/sdk] WARNING: mock mode active in production (AX_HUB_ALLOW_MOCK_IN_PROD opt-in).");return}throw new $e({message:"Mock mode active in production without explicit opt-in",code:"mock_in_production",category:"configuration",httpStatus:0,retryable:false,requestId:"",docUrl:"https://docs.axhub.dev/errors/mock-in-production"})}}var Dr="https://api.axhub.ai";function bs(t){return typeof t=="object"&&t!==null&&"__sharedHttp"in t}var In=class t{http;defaultTenantSlug;defaultTenantId;logger;schemaCacheOptions;mock;tenantResolver;n;r;i;s;o;a;u;c;d;l;constructor(e){if(bs(e)){this.http=e.__sharedHttp,this.defaultTenantSlug=e.defaultTenantSlug,this.defaultTenantId=e.defaultTenantId,this.logger=e.logger,this.schemaCacheOptions=e.schemaCacheOptions,this.mock=e.mockStore,this.tenantResolver=e.tenantResolver??new it(this.http);return}if(e.token!==void 0&&e.tokenType===void 0)throw new TypeError('AxHubClient requires tokenType when token is set ("pat" | "jwt")');let n=e.token!==void 0&&e.tokenType!==void 0?new We({token:e.token,tokenType:e.tokenType,onRefresh:e.onRefresh}):new Xe;this.http=new bt({baseUrl:e.baseUrl??Dr,auth:n,fetch:e.fetch,logger:e.logger,debug:e.debug,timeoutMs:e.timeoutMs,idempotencyKey:e.idempotencyKey,retryPolicy:e.retryPolicy,rateLimitStrategy:e.rateLimitStrategy}),this.defaultTenantSlug=e.defaultTenantSlug,this.defaultTenantId=e.defaultTenantId,this.logger=e.logger??ht,this.schemaCacheOptions=e.schemaCache,this.mock=Cn(e),this.tenantResolver=new it(this.http);}resolveTenantSlug(e){let n=e??this.defaultTenantSlug;if(!n)throw new Me({message:"tenantSlug is required: set defaultTenantSlug on AxHubClient or pass tenantSlug per-call",code:"tenant_slug_required",category:"tenant_slug_required",httpStatus:0,retryable:false,requestId:""});return n}get apps(){return this.n||(this.n=new Ye(this.http,this.defaultTenantSlug,this.defaultTenantId,this.tenantResolver)),this.n}get data(){return this.r||(this.r=new at(this.http,{schemaCache:this.schemaCacheOptions,mockStore:this.mock})),this.r}get deployments(){return this.i||(this.i=new ut(this.http,this.defaultTenantId)),this.i}get config(){return this.c||(this.c=new pt(this.http)),this.c}get gateway(){return this.s||(this.s=new ct(this.http,this.tenantResolver)),this.s}get identity(){return this.o||(this.o=new rt(this.http,this.defaultTenantSlug)),this.o}get tenants(){return this.u||(this.u=new lt(this.http)),this.u}get cost(){return this.d||(this.d=new et(this.http,this.defaultTenantId,this.tenantResolver)),this.d}get inviteLinks(){return this.l||(this.l=new tt(this.http,this.tenantResolver)),this.l}get publicationRequests(){return this.a||(this.a=new dt(this.http)),this.a}withTenant(e){return new t({__sharedHttp:this.http,defaultTenantSlug:e,defaultTenantId:e===this.defaultTenantSlug?this.defaultTenantId:void 0,logger:this.logger,schemaCacheOptions:this.schemaCacheOptions,mockStore:this.mock,tenantResolver:this.tenantResolver})}tenant(e){return new nt(e,this.withTenant(e),this,this.tenantResolver)}};
2
- export{h as AbortError,W as AccessDeniedError,we as AlreadyAccessedError,be as AlreadyActiveError,ae as AlreadyDeletedError,Re as AlreadyInactiveError,oe as AlreadyMemberError,ye as AlreadyRevokedError,he as AlreadySettledError,Bt as AppScopedClient,Ht as AppScopedDataClient,De as AppUnavailableError,Ye as AppsClient,G as AuthorizationPendingError,In as AxHubClient,p as AxHubError,Ee as BadRequestError,pt as ConfigClient,K as ConfigurationError,g as ConflictError,et as CostClient,Dr as DEFAULT_BASE_URL,at as DataClient,re as DataTableClient,Q as DecodeError,ut as DeploymentsClient,nn as DeviceFlowDeniedError,rn as DeviceFlowTimeoutError,Se as DomainTakenError,Ae as DuplicateError,Pe as EmptyError,X as ExpiredTokenError,pe as ForbiddenError,Yt as GatewayCatalogClient,ct as GatewayClient,rt as IdentityClient,Kt as IdentityDeviceCodeClient,Qt as IdentityInvitationsClient,Y as IdentityMeClient,Nt as IdentityOAuthClient,Vt as IdentityOIDCClient,Ft as IdentityPATClient,zt as IdentitySystemOAuthClientsClient,U as InternalServerError,$ as IntrospectFailedError,He as InvalidClientError,_ as InvalidCursorError,Te as InvalidExpiryError,Ge as InvalidGrantError,V as InvalidPathError,je as InvalidRequestError,Fe as InvalidScopeError,Ce as InvalidStateTransitionError,Be as InvalidTargetError,Ne as InvalidTokenError,ke as InvalidValueError,ge as InvitationExpiredError,tt as InviteLinksClient,_e as LastAdminError,v as LegacyCursorError,fe as LinkInvalidError,$e as MockInProductionError,mt as MockStore,Ue as NetworkError,Xe as NoAuth,le as NotAdminError,Oe as NotAllowedError,ve as NotDeletedError,f as NotFoundError,qe as NotMemberError,y as OAuthError,Ke as OAuthServerError,xe as PendingExistsError,me as PermanentlyDeletedError,T as PermissionDeniedError,L as PoolStaleError,ie as PreconditionFailedError,dt as PublicationRequestsClient,D as RateLimitedError,S as RequiredError,z as ScanLimitExceededError,ee as SchemaCache,Ie as SchemaNameTakenError,B as SlowDownError,se as SlugTakenError,We as StaticTokenAuth,ft as StreamConsumedError,M as TableNotFoundError,ze as TemporarilyUnavailableError,j as TenantCostClient,Zt as TenantGatewayClient,R as TenantIdRequiredError,Z as TenantInviteLinksClient,Gt as TenantScopedAppsClient,nt as TenantScopedClient,Me as TenantSlugRequiredError,lt as TenantsClient,Le as TimeoutError,ce as TokenExpiredError,de as TokenInvalidError,ue as TokenMissingError,k as UnauthenticatedError,Qe as UnauthorizedClientError,N as UnavailableError,Ve as UnsupportedGrantTypeError,d as ValidationError,tn as WebhookVerificationError,Li as and,Br as asAppId,Nr as asAppSlug,Hr as asDeploymentId,Qr as asPatId,Kr as asRequestId,jr as asTenantId,Fr as asTenantSlug,Vr as asUserId,Or as assertMockModeAllowed,Cn as createMockStore,ii as cursorFromRow,ni as decodeCursor,gn as defineSchema,$n as encodeCursor,Wt as escapeLike,Sn as formatErrorMessage,ds as getAccessibleColumns,ls as getMaskHint,Wr as id,us as isAllowed,cs as isPolicyDeny,Er as isSqlFormatError,$i as not,Mi as or,ri as orderByFingerprint,on as parseRetryAfter,Ui as raw,ot as schemaCacheKey,ui as signWebhook,ps as tableFromPath,ci as verifyWebhook,Gi as where};
1
+ import {ulid}from'ulid';import {createHmac,timingSafeEqual}from'crypto';var Lr=Object.defineProperty;var i=(t,e)=>Lr(t,"name",{value:e,configurable:true});var m=class extends Error{static{i(this,"AxHubError");}code;category;httpStatus;retryable;requestId;resource;fields;retry;docUrl;constructor(e){super(e.message,e.cause?{cause:e.cause}:void 0),this.name=this.constructor.name,this.code=e.code,this.category=e.category,this.httpStatus=e.httpStatus,this.retryable=e.retryable,this.requestId=e.requestId,e.resource!==void 0&&(this.resource=e.resource),e.fields!==void 0&&(this.fields=e.fields),e.retry!==void 0&&(this.retry=e.retry),e.docUrl!==void 0&&(this.docUrl=e.docUrl);}toJSON(){return {name:this.name,message:this.message,code:this.code,category:this.category,httpStatus:this.httpStatus,retryable:this.retryable,requestId:this.requestId,resource:this.resource,fields:this.fields,retry:this.retry,docUrl:this.docUrl}}toString(){return An(this)}};function An(t){let e=[`${t.name}[${t.code}]`];return t.requestId&&e.push(`req=${t.requestId}`),e.push(`problem=${t.message}`),t.fields?.length&&e.push(`cause=${t.fields.map(n=>`${n.name}:${n.code}`).join(",")}`),t.retry?.afterMs!==void 0?e.push(`fix=retry_after_${t.retry.afterMs}ms`):t.retryable?e.push("fix=retry_with_backoff"):e.push("fix=inspect_input_or_permissions"),t.docUrl&&e.push(`docs=${t.docUrl}`),e.join(" ")}i(An,"formatErrorMessage");var l=class extends m{static{i(this,"ValidationError");}},T=class extends m{static{i(this,"UnauthenticatedError");}},P=class extends m{static{i(this,"PermissionDeniedError");}},y=class extends m{static{i(this,"NotFoundError");}},f=class extends m{static{i(this,"ConflictError");}},se=class extends m{static{i(this,"PreconditionFailedError");}},U=class extends m{static{i(this,"RateLimitedError");}},L=class extends m{static{i(this,"InternalServerError");}},Q=class extends m{static{i(this,"UnavailableError");}},oe=class extends f{static{i(this,"SlugTakenError");}},ae=class extends f{static{i(this,"AlreadyMemberError");}},ue=class extends f{static{i(this,"AlreadyDeletedError");}},ce=class extends T{static{i(this,"TokenMissingError");}},de=class extends T{static{i(this,"TokenExpiredError");}},le=class extends T{static{i(this,"TokenInvalidError");}},pe=class extends P{static{i(this,"NotAdminError");}},me=class extends P{static{i(this,"ForbiddenError");}},ge=class extends y{static{i(this,"PermanentlyDeletedError");}},fe=class extends y{static{i(this,"InvitationExpiredError");}},ye=class extends y{static{i(this,"LinkInvalidError");}},he=class extends f{static{i(this,"AlreadyRevokedError");}},be=class extends f{static{i(this,"AlreadySettledError");}},Re=class extends f{static{i(this,"AlreadyActiveError");}},we=class extends f{static{i(this,"AlreadyInactiveError");}},ve=class extends f{static{i(this,"AlreadyAccessedError");}},_e=class extends f{static{i(this,"NotDeletedError");}},xe=class extends f{static{i(this,"LastAdminError");}},Ce=class extends f{static{i(this,"PendingExistsError");}},Ie=class extends f{static{i(this,"InvalidStateTransitionError");}},Se=class extends f{static{i(this,"SchemaNameTakenError");}},Ae=class extends f{static{i(this,"DomainTakenError");}},ke=class extends f{static{i(this,"DuplicateError");}},Te=class extends l{static{i(this,"InvalidValueError");}},Pe=class extends l{static{i(this,"InvalidExpiryError");}},A=class extends l{static{i(this,"RequiredError");}},Ee=class extends l{static{i(this,"EmptyError");}},qe=class extends l{static{i(this,"BadRequestError");}},Oe=class extends P{static{i(this,"NotMemberError");}},De=class extends P{static{i(this,"NotAllowedError");}},Ue=class extends Q{static{i(this,"AppUnavailableError");}},Le=class extends m{static{i(this,"NetworkError");}},Me=class extends m{static{i(this,"TimeoutError");}},V=class extends m{static{i(this,"DecodeError");}},b=class extends m{static{i(this,"AbortError");}},K=class extends m{static{i(this,"InvalidPathError");}},yt=class extends m{static{i(this,"StreamConsumedError");}},$e=class extends m{static{i(this,"TenantSlugRequiredError");}},w=class extends m{static{i(this,"TenantIdRequiredError");}},z=class extends m{static{i(this,"ConfigurationError");}},M=class extends T{static{i(this,"PoolStaleError");}},nn=class extends l{static{i(this,"WebhookVerificationError");}},$=class extends y{static{i(this,"TableNotFoundError");}},G=class extends L{static{i(this,"IntrospectFailedError");}},x=class extends l{static{i(this,"InvalidCursorError");}},_=class extends l{static{i(this,"LegacyCursorError");}},Ge=class extends z{static{i(this,"MockInProductionError");}},W=class extends L{static{i(this,"ScanLimitExceededError");}},h=class extends m{static{i(this,"OAuthError");}description;uri;constructor(e){super({message:e.description??e.code,code:e.code,category:"oauth",httpStatus:e.httpStatus,retryable:e.retryable,requestId:e.requestId}),e.description!==void 0&&(this.description=e.description),e.uri!==void 0&&(this.uri=e.uri);}},Be=class extends h{static{i(this,"InvalidGrantError");}},X=class extends h{static{i(this,"AccessDeniedError");}},B=class extends h{static{i(this,"AuthorizationPendingError");}},H=class extends h{static{i(this,"SlowDownError");}},Z=class extends h{static{i(this,"ExpiredTokenError");}},rn=class extends X{static{i(this,"DeviceFlowDeniedError");}},sn=class extends Z{static{i(this,"DeviceFlowTimeoutError");}},He=class extends h{static{i(this,"InvalidTargetError");}},je=class extends h{static{i(this,"InvalidClientError");}},Fe=class extends h{static{i(this,"InvalidRequestError");}},Ne=class extends h{static{i(this,"InvalidScopeError");}},Qe=class extends h{static{i(this,"InvalidTokenError");}},Ve=class extends h{static{i(this,"UnauthorizedClientError");}},Ke=class extends h{static{i(this,"UnsupportedGrantTypeError");}},ze=class extends h{static{i(this,"OAuthServerError");}},We=class extends h{static{i(this,"TemporarilyUnavailableError");}};var kn={slug_taken:oe,already_member:ae,already_deleted:ue,already_revoked:he,already_settled:be,already_active:Re,already_inactive:we,already_accessed:ve,not_deleted:_e,last_admin:xe,pending_exists:Ce,invalid_state_transition:Ie,schema_name_taken:Se,domain_taken:Ae,duplicate:ke,token_missing:ce,token_expired:de,token_invalid:le,pool_stale:M,not_admin:pe,forbidden:me,not_member:Oe,not_allowed:De,permanently_deleted:ge,invitation_expired:fe,link_invalid:ye,invalid_value:Te,invalid_expiry:Pe,required:A,empty:Ee,bad_request:qe,app_unavailable:Ue},Tn={validation:l,unauthenticated:T,permission_denied:P,not_found:y,conflict:f,precondition_failed:se,rate_limited:U,internal:L,unavailable:Q},Pn={invalid_grant:Be,access_denied:X,authorization_pending:B,slow_down:H,expired_token:Z,invalid_target:He,invalid_client:je,invalid_request:Fe,invalid_scope:Ne,invalid_token:Qe,unauthorized_client:Ve,unsupported_grant_type:Ke,server_error:ze,temporarily_unavailable:We},En={authorization_pending:true,slow_down:true,access_denied:false,invalid_grant:false,expired_token:false,server_error:true,temporarily_unavailable:true};function Mr(t){if(typeof t!="object"||t===null)return false;let e=t.error;if(typeof e!="object"||e===null)return false;let n=e;return typeof n.code=="string"&&typeof n.category=="string"&&typeof n.retryable=="boolean"}i(Mr,"isWrappedEnvelope");function $r(t){return typeof t!="object"||t===null?false:typeof t.error=="string"}i($r,"isOAuthErrorBody");function qn(t){return t.startsWith("/oauth/")||t.startsWith("/auth/")}i(qn,"isOAuthPath");function on(t){return qn(t.path)&&$r(t.body)?Br(t):Mr(t.body)?Gr(t):new V({message:"Unexpected error response shape",code:"decode_failed",category:"decode",httpStatus:t.status,retryable:false,requestId:t.fallbackRequestId})}i(on,"dispatch");function Gr(t){let n=t.body.error,r=n.retry?{afterMs:n.retry.after_ms}:void 0,s={message:n.message,code:n.code,category:n.category,httpStatus:t.status,retryable:n.retryable,requestId:n.request_id||t.fallbackRequestId,resource:n.resource,fields:n.fields,retry:r,docUrl:n.doc_url},o=kn[n.code];if(o)return new o(s);let a=Tn[n.category]??m;return new a(s)}i(Gr,"dispatchWrapped");function Br(t){let e=t.body,n=Pn[e.error]??h,r=En[e.error]??false;return new n({code:e.error,description:e.error_description,uri:e.error_uri,httpStatus:t.status,retryable:r,requestId:t.fallbackRequestId})}i(Br,"dispatchOAuth");function Hr(t){return t}i(Hr,"asAppId");function jr(t){return t}i(jr,"asDeploymentId");function Fr(t){return t}i(Fr,"asTenantId");function Nr(t){return t}i(Nr,"asTenantSlug");function Qr(t){return t}i(Qr,"asAppSlug");function Vr(t){return t}i(Vr,"asPatId");function Kr(t){return t}i(Kr,"asUserId");function zr(t){return t}i(zr,"asRequestId");var Wr=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,On=/^[a-z][a-z0-9-]{0,62}$/;function ht(t,e,n){return new l({message:t,code:n,category:"validation",httpStatus:0,retryable:false,requestId:"",fields:[{name:e,code:n}]})}i(ht,"validation");function C(t,e){if(t.trim()==="")throw ht(`${e} must be non-empty`,e,"empty");if(!Wr.test(t))throw ht(`${e} must be a UUID`,e,"invalid_uuid")}i(C,"requireUuid");function Dn(t,e){if(t.trim()==="")throw ht(`${e} must be non-empty`,e,"empty");if(!On.test(t))throw ht(`${e} must match ${On.source}`,e,"invalid_slug")}i(Dn,"requireSlug");var Xr={tenant(t){return C(t,"tenantId"),t},tenantSlug(t){return Dn(t,"tenantSlug"),t},app(t){return C(t,"appId"),t},appSlug(t){return Dn(t,"appSlug"),t},user(t){return C(t,"userId"),t},deployment(t){return C(t,"deploymentId"),t},pat(t){return C(t,"patId"),t},resource(t){return C(t,"resourceId"),t},connector(t){return C(t,"connectorId"),t},subject(t){return C(t,"subjectId"),t},grant(t){return C(t,"grantId"),t},tag(t){return C(t,"tagId"),t},auditEvent(t){return C(t,"auditEventId"),t},table(t){return C(t,"tableId"),t}};var Xe=class{static{i(this,"StaticTokenAuth");}token;tokenType;onRefresh;refreshing=null;constructor(e){this.token=e.token,this.tokenType=e.tokenType,this.onRefresh=e.onRefresh;}currentToken(){return this.token}headersFor(e){return e==="public"?{}:this.tokenType==="pat"?{"X-Api-Key":this.token}:{Authorization:`Bearer ${this.token}`}}async onUnauthorized(){return this.tokenType!=="jwt"||!this.onRefresh?false:this.refreshing?this.refreshing:(this.refreshing=(async()=>{try{let e=await this.onRefresh();return this.token=e,!0}catch{return false}finally{this.refreshing=null;}})(),this.refreshing)}},Ze=class{static{i(this,"NoAuth");}headersFor(e){return {}}async onUnauthorized(){return false}};var bt={debug(){},info(){},warn(){},error(){}};function an(t){if(!t)return 6e4;let e=t.trim();if(e==="")return 6e4;let n=Number(e);if(Number.isFinite(n))return n>=0?Math.floor(n*1e3):6e4;let r=Date.parse(e);return Number.isNaN(r)?6e4:Math.max(0,r-Date.now())}i(an,"parseRetryAfter");var Zr=new Set(["authorization","x-api-key","cookie","set-cookie","proxy-authorization"]),Yr="***REDACTED***";function Un(t){let e={},n=i((r,s)=>{e[r]=Zr.has(r.toLowerCase())?Yr:s;},"visit");if(typeof Headers<"u"&&t instanceof Headers)t.forEach((r,s)=>n(s,r));else for(let[r,s]of Object.entries(t))n(r,s);return e}i(Un,"redactHeaders");var cn={maxAttempts:3,baseMs:200,capMs:5e3,jitter:Math.random};function Jr(t){return t instanceof m?t.retryable:t instanceof TypeError}i(Jr,"isRetriable");async function Ln(t,e=cn,n){let r;for(let s=0;s<e.maxAttempts;s++){if(n?.aborted)throw un("aborted before attempt",n.reason);try{return await t(s)}catch(o){if(r=o,!Jr(o)||s===e.maxAttempts-1)throw o;let a=Math.min(e.capMs,e.baseMs*2**s)*e.jitter();await dn(a,n);}}throw r}i(Ln,"withRetry");function dn(t,e){return new Promise((n,r)=>{if(e?.aborted){r(un("aborted before sleep",e.reason));return}let s=setTimeout(()=>{e?.removeEventListener("abort",o),n();},t),o=i(()=>{clearTimeout(s),r(un("aborted during sleep",e?.reason));},"onAbort");e?.addEventListener("abort",o,{once:true});})}i(dn,"abortableSleep");function un(t,e){return new b({message:t,code:"aborted",category:"abort",httpStatus:0,retryable:false,requestId:"",cause:e})}i(un,"aborted");var ei=new Set(["GET","HEAD","OPTIONS"]),Rt=class{static{i(this,"HttpClient");}baseUrl;auth;fetch;logger;debug;timeoutMs;idempotencyKey;retryPolicy;rateLimitStrategy;constructor(e){this.baseUrl=e.baseUrl.replace(/\/$/,""),this.auth=e.auth,this.fetch=e.fetch??globalThis.fetch,this.logger=e.logger??bt,this.debug=e.debug??false,this.timeoutMs=e.timeoutMs??3e4,this.idempotencyKey={autoGenerate:e.idempotencyKey?.autoGenerate??true,generator:e.idempotencyKey?.generator??ulid},this.retryPolicy=e.retryPolicy??cn,this.rateLimitStrategy=e.rateLimitStrategy??"sleep";}async request(e,n,r){let s=ei.has(e.toUpperCase()),o=this.withStableIdempotencyKey(r);return s||r.idempotent?Ln(()=>this.requestOnce(e,n,o),this.retryPolicy,o.signal):this.requestOnce(e,n,o)}async requestOnce(e,n,r){let s=this.buildUrl(n,r.query),o=ulid(),a=this.buildHeaders(o,r);if(r.body!==void 0&&r.form!==void 0)throw new m({message:"body and form are mutually exclusive",code:"invalid_request_body",category:"validation",httpStatus:0,retryable:false,requestId:o});let d=r.form!==void 0?this.formBody(r.form):r.body!==void 0?JSON.stringify(r.body):void 0;d!==void 0&&(a["Content-Type"]=r.form!==void 0?"application/x-www-form-urlencoded":"application/json");let p=new AbortController,I=i(()=>p.abort(r.signal?.reason),"externalAbort");r.signal?.addEventListener("abort",I,{once:true});let E=r.timeoutMs??this.timeoutMs,ft=setTimeout(()=>p.abort(new Error("timeout")),E),v;try{this.logRequest(e,s,a,o),v=await this.fetch(s,{method:e,headers:a,body:d,redirect:"manual",signal:p.signal});}catch(D){throw r.signal?.aborted?new b({message:"Request aborted",code:"aborted",category:"abort",httpStatus:0,retryable:false,requestId:o,cause:D}):p.signal.aborted?new Me({message:`Request timed out after ${E}ms`,code:"timeout",category:"timeout",httpStatus:0,retryable:true,requestId:o,cause:D}):new Le({message:"Network error",code:"network",category:"network",httpStatus:0,retryable:true,requestId:o,cause:D})}finally{clearTimeout(ft),r.signal?.removeEventListener("abort",I);}if(v.status>=300&&v.status<400)return {status:v.status,location:v.headers.get("Location")??v.headers.get("location")};if(r.rawResponse&&v.ok)return {response:v,requestId:o};if(v.ok)return this.parseSuccess(v,r,o);let tn=await this.safeParseJson(v);if(v.status===401&&r.ring==="admin"&&await this.auth.onUnauthorized())return this.requestOnce(e,n,r);if(v.status===429){let D=an(v.headers.get("Retry-After")),Ur=new U({message:ti(tn)??"Rate limited",code:ni(tn)??"rate_limited",category:"rate_limited",httpStatus:429,retryable:true,requestId:o,retry:{afterMs:D}});if(this.rateLimitStrategy==="sleep")return await dn(D,r.signal),this.requestOnce(e,n,r);throw Ur}throw on({path:n,status:v.status,body:tn,fallbackRequestId:o})}async parseSuccess(e,n,r){if(e.status===204||n.parseBody===false)return;let s=await e.text();if(s!=="")try{return JSON.parse(s)}catch{return s}}async safeParseJson(e){try{let n=await e.text();return n===""?void 0:JSON.parse(n)}catch{return}}buildUrl(e,n){let r=e.startsWith("/")?e:`/${e}`,s=this.baseUrl+r;if(!n)return s;let o=new URLSearchParams;for(let[d,p]of Object.entries(n))if(p!==void 0)if(Array.isArray(p))for(let I of p)o.append(d,String(I));else o.set(d,String(p));let a=o.toString();return a?`${s}?${a}`:s}buildHeaders(e,n){let r=this.resolveIdempotencyKey(n);return {"X-Request-Id":e,Accept:"application/json",...n.ring!=="public"?this.auth.headersFor(n.ring):{},...r?{"Idempotency-Key":r}:{},...n.headers??{}}}resolveIdempotencyKey(e){if(e.idempotencyKey!==false){if(typeof e.idempotencyKey=="string"){if(e.idempotencyKey.trim()==="")throw new m({message:"idempotencyKey must be non-empty",code:"invalid_idempotency_key",category:"validation",httpStatus:0,retryable:false,requestId:""});return e.idempotencyKey}if(!(!e.idempotent||!this.idempotencyKey.autoGenerate))return this.idempotencyKey.generator()}}formBody(e){let n=new URLSearchParams;for(let[r,s]of Object.entries(e))s!==void 0&&n.set(r,String(s));return n.toString()}withStableIdempotencyKey(e){return e.idempotencyKey!==void 0||!e.idempotent||!this.idempotencyKey.autoGenerate?e:{...e,idempotencyKey:this.idempotencyKey.generator()}}logRequest(e,n,r,s){this.debug&&this.logger.debug({method:e,url:n,headers:Un(r),requestId:s},"http.request");}};function ti(t){if(typeof t!="object"||t===null)return;let e=t.error;if(typeof e=="object"&&e!==null){let n=e.message;if(typeof n=="string")return n}if(typeof e=="string")return e}i(ti,"getMessage");function ni(t){if(typeof t!="object"||t===null)return;let e=t.error;if(typeof e=="object"&&e!==null){let n=e.code;if(typeof n=="string")return n}}i(ni,"extractCode");var Ye=4096,$n=false;function Gn(t){return `v2:${Buffer.from(JSON.stringify(t),"utf8").toString("base64url")}`}i(Gn,"encodeCursor");function ri(t){if(t.length>Ye)throw new x({message:`Cursor token exceeds maximum size (${Ye} chars)`,code:"invalid_cursor",category:"validation",httpStatus:0,retryable:false,requestId:"",docUrl:"https://docs.axhub.dev/errors/validation/invalid-cursor"});if(t.startsWith("v1:"))throw new _({message:"Legacy v1: cursor token is not compatible with keyset pagination; restart pagination without cursor",code:"legacy_cursor",category:"validation",httpStatus:0,retryable:false,requestId:"",docUrl:"https://docs.axhub.dev/errors/validation/legacy-cursor"});if(!t.startsWith("v2:"))throw new _({message:"Cursor token is missing the v2: keyset prefix; restart pagination without cursor",code:"legacy_cursor",category:"validation",httpStatus:0,retryable:false,requestId:"",docUrl:"https://docs.axhub.dev/errors/validation/legacy-cursor"});try{let e=JSON.parse(Buffer.from(t.slice(3),"base64url").toString("utf8"));if(!oi(e))throw new Error("invalid cursor shape");return e}catch(e){throw new x({message:"Malformed keyset cursor token",code:"invalid_cursor",category:"validation",httpStatus:0,retryable:false,requestId:"",cause:e,docUrl:"https://docs.axhub.dev/errors/validation/invalid-cursor"})}}i(ri,"decodeCursor");function wt(t,e){let n=typeof t=="string"?t.split(",").map(r=>{let s=r.trim();return s.startsWith("-")?{field:s.slice(1),dir:"desc"}:s.startsWith("+")?{field:s.slice(1),dir:"asc"}:{field:s,dir:"asc"}}).filter(r=>r.field.length>0):[...t??[]].map(r=>({field:r.field,dir:r.dir??"asc"}));return n.length>0&&!n.some(r=>r.field==="id")&&(e?.warnOnTiebreaker&&!$n&&($n=true,console.warn("AX Hub SDK: orderBy is not unique; appending id ASC as keyset cursor tiebreaker")),n.push({field:"id",dir:"asc"})),n}i(wt,"normalizeOrderBy");function Bn(t){let e=wt(t,{warnOnTiebreaker:true});return e.length===0?typeof t=="string"?t:void 0:e.map(n=>`${n.dir==="desc"?"-":""}${n.field}`).join(",")}i(Bn,"serializeOrderBy");function ii(t){return JSON.stringify(Hn(t))}i(ii,"orderByFingerprint");function si(t,e){if(!t)return null;let n=Hn(e?.orderBy,{warnOnTiebreaker:true}),r={};for(let d of n){let p=t[d.field];(p===null||typeof p=="string"||typeof p=="number"||typeof p=="boolean")&&(r[d.field]=p);}let s=t.id,o={values:r,direction:e?.direction??"forward",orderBy:n,orderByFingerprint:JSON.stringify(n)};(typeof s=="string"||typeof s=="number")&&(o.tiebreaker={field:"id",value:s});let a=e?.page;return typeof a=="number"&&Number.isInteger(a)&&a>0&&(o.page=a),e?.contextFingerprint&&(o.contextFingerprint=e.contextFingerprint),Gn(o)}i(si,"cursorFromRow");function Hn(t,e){let n=wt(t,e);return n.length>0?n:[{field:"id",dir:"asc"}]}i(Hn,"effectiveCursorOrderBy");function jn(t){return typeof t=="string"&&t.startsWith("v2:")}i(jn,"isV2Cursor");function oi(t){return typeof t=="object"&&t!==null&&typeof t.values=="object"&&(t.direction==="forward"||t.direction==="backward")&&Array.isArray(t.orderBy)&&typeof t.orderByFingerprint=="string"}i(oi,"isKeysetCursor");async function*k(t,e){let n=e?.cursor,r,s;for(;;){if(e?.signal?.aborted)throw new b({message:"listAll aborted",code:"aborted",category:"abort",httpStatus:0,retryable:false,requestId:""});let o=await t({pageSize:e?.pageSize,cursor:n});o.total!==void 0&&(r===void 0?(r=o.total,s=o.total):o.total>(s??r)&&(yield {type:"drift",addedSince:o.total-(s??r)},s=o.total));for(let a of o.items)yield {type:"item",value:a};if(o.nextCursor==null)return;n=o.nextCursor;}}i(k,"listAll");function ln(t){return Buffer.isBuffer(t)?t:Buffer.from(t)}i(ln,"bodyBytes");function ui(t){let e=t.startsWith("sha256=")?t.slice(7):t;return /^[0-9a-f]{64}$/i.test(e)?Buffer.from(e,"hex"):null}i(ui,"parseSignature");function ci(t,e,n){let r=n?Buffer.concat([Buffer.from(`${n}.`),ln(t)]):ln(t);return `sha256=${createHmac("sha256",e).update(r).digest("hex")}`}i(ci,"signWebhook");function di(t){if(!t.secret)return {ok:false,reason:"missing_secret"};let e=ui(t.signature);if(!e)return {ok:false,reason:"malformed_signature"};let n=Math.floor((t.now?.()??Date.now())/1e3),r=ln(t.rawBody);if(t.timestamp!==void 0){let o=Number(t.timestamp);if(!Number.isFinite(o))return {ok:false,reason:"timestamp_skew"};let a=t.tolerance??300;if(Math.abs(n-o)>a)return {ok:false,reason:"timestamp_skew"};let d=`${t.timestamp}:${t.signature}`;if(t.replayCache?.has(d))return {ok:false,reason:"replay"};r=Buffer.concat([Buffer.from(`${t.timestamp}.`),r]);}let s=createHmac("sha256",t.secret).update(r).digest();return e.byteLength!==s.byteLength?{ok:false,reason:"signature_mismatch"}:timingSafeEqual(e,s)?(t.timestamp!==void 0&&t.replayCache?.add(`${t.timestamp}:${t.signature}`),{ok:true}):{ok:false,reason:"signature_mismatch"}}i(di,"verifyWebhook");function u(t,e){return {...t,signal:e?.signal,timeoutMs:e?.timeoutMs,idempotencyKey:e?.idempotencyKey}}i(u,"withRequestOptions");function q(t){let e={};return t?.pageSize!==void 0&&(e.limit=t.pageSize),t?.cursor!==void 0&&(e.cursor=t.cursor),e}i(q,"pageQuery");function R(t,e){return {items:t.items.map(e),nextCursor:t.next_cursor,total:t.total}}i(R,"toPaginatedList");function j(t){let e={};for(let[n,r]of Object.entries(t))r!==void 0&&(e[n]=r);return e}i(j,"compactBody");function c(t){return encodeURIComponent(t)}i(c,"encodePath");function Nn(t){return {id:t.id,appId:t.app_id,userId:t.user_id,grantedAt:t.granted_at}}i(Nn,"toAppAccess");var vt=class{constructor(e){this.http=e;}http;static{i(this,"AppsAccessMixin");}async grant(e){let n=await this.http.request("POST",`/api/v1/apps/${encodeURIComponent(e)}/access`,{ring:"admin",idempotent:false});return Nn(n)}async revoke(e){await this.http.request("DELETE",`/api/v1/apps/${encodeURIComponent(e)}/access`,{ring:"admin",idempotent:true});}async me(e){try{let n=await this.http.request("GET",`/api/v1/apps/${encodeURIComponent(e)}/access/me`,{ring:"admin"});return Nn(n)}catch(n){if(li(n))return null;throw n}}};function li(t){return typeof t=="object"&&t!==null&&"httpStatus"in t&&t.httpStatus===404}i(li,"isNotFound");function Qn(t){let e={available:t.available};return t.reason!==void 0&&(e.reason=t.reason),e}i(Qn,"toField");var _t=class{constructor(e,n){this.http=e;this.defaultTenantId=n;}http;defaultTenantId;static{i(this,"AppsAvailabilityMixin");}requireTenantId(e,n){if(this.defaultTenantId===void 0)throw new w({message:`apps.${e} requires a tenant UUID: set defaultTenantId on AxHubClient. Backend route ${n} takes a tenant UUID, not a slug.`,code:"tenant_id_required",category:"tenant_id_required",httpStatus:0,retryable:false,requestId:"",fields:[{name:"tenantId",code:"required"}]});return this.defaultTenantId}async checkAvailability(e){let n=this.requireTenantId("checkAvailability","GET /api/v1/tenants/{tenantID}/apps/check-availability"),r={};e.slug!==void 0&&(r.slug=e.slug),e.subdomain!==void 0&&(r.subdomain=e.subdomain);let s=await this.http.request("GET",`/api/v1/tenants/${encodeURIComponent(n)}/apps/check-availability`,{ring:"admin",query:r}),o={};return s.slug!==void 0&&(o.slug=Qn(s.slug)),s.subdomain!==void 0&&(o.subdomain=Qn(s.subdomain)),o}async iconPreCreateUrl(e){let n=this.requireTenantId("iconPreCreateUrl","POST /api/v1/tenants/{tenantID}/apps/icon/upload-url"),r={content_type:e.contentType,slug:e.slug};e.variant!==void 0&&(r.variant=e.variant);let s=await this.http.request("POST",`/api/v1/tenants/${encodeURIComponent(n)}/apps/icon/upload-url`,{ring:"admin",body:r,idempotent:false}),o={uploadUrl:s.put_url??"",getUrl:s.public_url??""};return s.expires_at!==void 0&&(o.expiresAt=s.expires_at),o}};var xt=class{constructor(e){this.http=e;}http;static{i(this,"AppsCategoriesMixin");}async list(e,n){let r=await this.http.request("GET",`/api/v1/tenants/${c(e)}/categories`,u({ring:"admin",query:q(n)},n));return R(r,s=>s)}get(e,n,r){return this.http.request("GET",`/api/v1/tenants/${c(e)}/categories/${c(n)}`,u({ring:"admin"},r))}};function Vn(t){return {id:t.id,appId:t.app_id,authorId:t.author_id,body:t.body,createdAt:t.created_at,updatedAt:t.updated_at,deletedAt:t.deleted_at}}i(Vn,"toComment");var Kn=500;function pi(t){if(typeof t!="string"||t.length===0)throw new l({message:"Comment body must be a non-empty string",code:"empty",category:"validation",httpStatus:0,retryable:false,requestId:"",fields:[{name:"body",code:"empty"}]});if(t.length>Kn)throw new l({message:`Comment body must be \u2264 ${Kn} characters (got ${t.length})`,code:"too_long",category:"validation",httpStatus:0,retryable:false,requestId:"",fields:[{name:"body",code:"too_long"}]})}i(pi,"validateCommentBody");var Ct=class{constructor(e){this.http=e;}http;static{i(this,"AppsCommentsMixin");}async add(e,n){pi(n.body);let r=await this.http.request("POST",`/api/v1/apps/${encodeURIComponent(e)}/comments`,{ring:"admin",body:{body:n.body},idempotent:false});return Vn(r)}async list(e,n){let r={};n?.pageSize!==void 0&&(r.limit=n.pageSize),n?.cursor!==void 0&&(r.cursor=n.cursor);let s=await this.http.request("GET",`/api/v1/apps/${encodeURIComponent(e)}/comments`,{ring:"admin",query:r});return {items:s.items.map(Vn),nextCursor:s.next_cursor,total:s.total}}listAll(e,n){return k(r=>this.list(e,r),n)}async delete(e){await this.http.request("DELETE",`/api/v1/comments/${encodeURIComponent(e)}`,{ring:"admin",idempotent:true});}};var zn=/^[a-z0-9-]+$/;function Xn(t,e){if(!t||!zn.test(t))throw new K({message:`Invalid ${e}: must match ${zn}`,code:"invalid_path",category:"invalid_path",httpStatus:0,retryable:false,requestId:""})}i(Xn,"validateSlug");var Wn=/^[a-z][a-z0-9]{0,62}$/;function S(t,e="name"){if(!t||!Wn.test(t))throw new K({message:`Invalid ${e}: must match ${Wn}`,code:"invalid_path",category:"invalid_path",httpStatus:0,retryable:false,requestId:""})}i(S,"validateTableName");function Zn(t){if(t.publication_status!==void 0)return t.publication_status;switch(t.review_status){case "pending":return "pending_review";case "approved":return "approved";default:return "draft"}}i(Zn,"toPublicationStatus");function mi(t){let e={id:t.id??"",slug:t.slug??"",name:t.name??""};return t.tenant_id!==void 0&&(e.tenantId=t.tenant_id),t.description!==void 0&&(e.description=t.description),t.color!==void 0&&(e.color=t.color),t.icon_url!==void 0&&(e.iconUrl=t.icon_url),t.display_order!==void 0&&(e.displayOrder=t.display_order),t.apps_count!==void 0&&(e.appsCount=t.apps_count),t.discoverable_apps_count!==void 0&&(e.discoverableAppsCount=t.discoverable_apps_count),t.created_at!==void 0&&(e.createdAt=t.created_at),t.updated_at!==void 0&&(e.updatedAt=t.updated_at),e}i(mi,"toAppCategory");function gi(t){let e={id:t.id??""};return t.name!==void 0&&(e.name=t.name),t.avatar_url!==void 0&&(e.avatarUrl=t.avatar_url),e}i(gi,"toAppOwner");function g(t){let e={id:t.id??"",tenantId:t.tenant_id??"",ownerId:t.owner_id??"",slug:t.slug??"",name:t.name??"",schemaName:t.schema_name??"",status:t.status??"draft",visibility:t.visibility??"private",publicationStatus:Zn(t),likeCount:t.like_count??0,subscriberCount:t.subscriber_count??0,createdAt:t.created_at??"",updatedAt:t.updated_at??"",deletedAt:t.deleted_at??null};return t.description!==void 0&&(e.description=t.description),t.icon_url!==void 0&&(e.iconUrl=t.icon_url),t.icon_dark_url!==void 0&&(e.iconDarkUrl=t.icon_dark_url),t.review_status!==void 0&&(e.reviewStatus=t.review_status),t.auth_mode!==void 0&&(e.authMode=t.auth_mode),t.data_scopes!==void 0&&(e.dataScopes=t.data_scopes),t.deploy_method!==void 0&&(e.deployMethod=t.deploy_method),t.resource_tier!==void 0&&(e.resourceTier=t.resource_tier),t.subdomain!==void 0&&(e.subdomain=t.subdomain),t.access_url!==void 0&&(e.accessUrl=t.access_url),t.last_deployment_status!==void 0&&(e.lastDeploymentStatus=t.last_deployment_status),t.operating_status!==void 0&&(e.operatingStatus=t.operating_status),t.suspended_at!==void 0&&(e.suspendedAt=t.suspended_at),t.resumed_at!==void 0&&(e.resumedAt=t.resumed_at),t.category_id!==void 0&&(e.categoryId=t.category_id),t.cost_center!==void 0&&(e.costCenter=t.cost_center),t.category!==void 0&&(e.category=mi(t.category)),t.owner!==void 0&&(e.owner=gi(t.owner)),t.calls_count!==void 0&&(e.callsCount=t.calls_count),t.shared_tables_count!==void 0&&(e.sharedTablesCount=t.shared_tables_count),e}i(g,"toApp");function St(t){let e={slug:t.slug,name:t.name};return t.description!==void 0&&(e.description=t.description),t.iconUrl!==void 0&&(e.icon_url=t.iconUrl),t.iconDarkUrl!==void 0&&(e.icon_dark_url=t.iconDarkUrl),t.categoryId!==void 0&&(e.category_id=t.categoryId),t.costCenter!==void 0&&(e.cost_center=t.costCenter),t.authMode!==void 0&&(e.auth_mode=t.authMode),t.dataScopes!==void 0&&(e.data_scopes=t.dataScopes),t.deployMethod!==void 0&&(e.deploy_method=t.deployMethod),t.resourceTier!==void 0&&(e.resource_tier=t.resourceTier),t.subdomain!==void 0&&(e.subdomain=t.subdomain),e}i(St,"buildCreateAppBody");function At(t){let e={};return t.name!==void 0&&(e.name=t.name),t.description!==void 0&&(e.description=t.description),t.iconUrl!==void 0&&(e.icon_url=t.iconUrl),t.iconDarkUrl!==void 0&&(e.icon_dark_url=t.iconDarkUrl),t.visibility!==void 0&&(e.visibility=t.visibility),t.categoryId!==void 0&&(e.category_id=t.categoryId),t.clearCategory!==void 0&&(e.clear_category=t.clearCategory),t.costCenter!==void 0&&(e.cost_center=t.costCenter),t.clearCostCenter!==void 0&&(e.clear_cost_center=t.clearCostCenter),t.authMode!==void 0&&(e.auth_mode=t.authMode),t.dataScopes!==void 0&&(e.data_scopes=t.dataScopes),t.deployMethod!==void 0&&(e.deploy_method=t.deployMethod),t.resourceTier!==void 0&&(e.resource_tier=t.resourceTier),t.subdomain!==void 0&&(e.subdomain=t.subdomain),t.clearSubdomain!==void 0&&(e.clear_subdomain=t.clearSubdomain),e}i(At,"buildUpdateAppBody");function Yn(t,e,n){if(t===void 0)return null;let r=Number(e??1),s=Number(n??20);return r*s<t?String(r+1):null}i(Yn,"synthesizeNextCursor");var It=class{constructor(e,n,r,s){this.http=e;this.defaultTenantSlug=n;this.defaultTenantId=r;this.tenantResolver=s;}http;defaultTenantSlug;defaultTenantId;tenantResolver;static{i(this,"AppsCrudMixin");}async resolveTenantId(){if(this.defaultTenantId!==void 0)return this.defaultTenantId;if(this.defaultTenantSlug!==void 0&&this.tenantResolver!==void 0)return this.tenantResolver.resolveTenantId(this.defaultTenantSlug)}async create(e){Xn(e.slug,"slug");let n=await this.resolveTenantId();if(n===void 0)throw new w({message:"apps.create requires a tenant: set defaultTenantId or defaultTenantSlug on AxHubClient. Backend route POST /api/v1/tenants/{tenantID}/apps takes a tenant UUID, not a slug.",code:"tenant_id_required",category:"tenant_id_required",httpStatus:0,retryable:false,requestId:"",fields:[{name:"tenantId",code:"required"}]});let r=St(e),s=await this.http.request("POST",`/api/v1/tenants/${encodeURIComponent(n)}/apps`,{ring:"admin",body:r,idempotent:false});return g(s)}async list(e){let n={},r=e?.perPage??e?.pageSize;r!==void 0&&(n.per_page=r),e?.page!==void 0?n.page=e.page:e?.cursor!==void 0&&(n.page=e.cursor),e?.q!==void 0&&(n.q=e.q),e?.categoryId!==void 0&&(n.category_id=e.categoryId),e?.status!==void 0&&(n.status=e.status),e?.statusIn!==void 0&&(n.status_in=e.statusIn.join(",")),e?.reviewStatus!==void 0&&(n.review_status=e.reviewStatus),e?.reviewStatusIn!==void 0&&(n.review_status_in=e.reviewStatusIn.join(",")),e?.operatingStatus!==void 0&&(n.operating_status=e.operatingStatus),e?.operatingStatusIn!==void 0&&(n.operating_status_in=e.operatingStatusIn.join(",")),e?.sort!==void 0&&(n.sort=e.sort),e?.page!==void 0&&(n.page=e.page),e?.perPage!==void 0&&(n.per_page=e.perPage);let s=await this.resolveTenantId();if(s===void 0)throw new w({message:"apps.list requires a tenant: set defaultTenantId or defaultTenantSlug on AxHubClient. Use apps.listMine() for the caller workspace feed without tenant context.",code:"tenant_id_required",category:"tenant_id_required",httpStatus:0,retryable:false,requestId:"",fields:[{name:"tenantId",code:"required"}]});let o=await this.http.request("GET",`/api/v1/tenants/${encodeURIComponent(s)}/apps`,{ring:"admin",query:n});return {items:o.items.map(g),nextCursor:o.next_cursor??Yn(o.total,n.page,n.per_page),total:o.total,hasNext:(o.next_cursor??Yn(o.total,n.page,n.per_page))!==null,hasPrev:Number(n.page??1)>1}}listAll(e){return k(n=>this.list(n),e)}async get(e){let n=await this.http.request("GET",`/api/v1/apps/${encodeURIComponent(e)}`,{ring:"admin"});return g(n)}async update(e,n){let r=At(n),s=await this.http.request("PATCH",`/api/v1/apps/${encodeURIComponent(e)}`,{ring:"admin",body:r,idempotent:false});return g(s)}async delete(e){await this.http.request("DELETE",`/api/v1/apps/${encodeURIComponent(e)}`,{ring:"admin",idempotent:true});}async permanent(e){await this.http.request("DELETE",`/api/v1/apps/${encodeURIComponent(e)}/permanent`,{ring:"admin",idempotent:false});}async signIconUploadURL(e,n){return this.signIconImpl(e,n,"icon")}async signIconDarkUploadURL(e,n){return this.signIconImpl(e,n,"icon-dark")}async signIconImpl(e,n,r){let s=await this.http.request("POST",`/api/v1/apps/${encodeURIComponent(e)}/${r}/upload-url`,{ring:"admin",body:{content_type:n.contentType},idempotent:false}),o={uploadUrl:s.upload_url??s.put_url??"",getUrl:s.get_url??s.public_url??""};return s.expires_at!==void 0&&(o.expiresAt=s.expires_at),o}async listMine(){return (await this.http.request("GET","/api/v1/me/apps/workspace",{ring:"admin"})).items.map(g)}};var kt=class{constructor(e,n,r){this.http=e;this.defaultTenantSlug=n;this.defaultTenantId=r;}http;defaultTenantSlug;defaultTenantId;static{i(this,"AppsDiscoverMixin");}async search(e){let n={...q(e),q:e?.q,category:e?.category,sort:e?.sort,visibility:e?.visibility,...this.defaultTenantSlug?{tenant_slug:this.defaultTenantSlug}:{}},r=await this.http.request("GET","/api/v1/apps/search",u({ring:"admin",query:n},e));return R(r,g)}feedQuery(e){let n={};return e?.q!==void 0&&(n.q=e.q),e?.category!==void 0&&(n.category=e.category),e?.sort!==void 0&&(n.sort=e.sort),e?.createdWithinDays!==void 0&&(n.created_within_days=e.createdWithinDays),e?.page!==void 0&&(n.page=e.page),e?.perPage!==void 0&&(n.per_page=e.perPage),n}async discoverGlobal(e){let n=await this.http.request("GET","/api/v1/apps/discover",u({ring:"admin",query:this.feedQuery(e)}));return R(n,g)}async discoverTenant(e){if(this.defaultTenantId===void 0)throw new w({message:"apps.discoverTenant requires a tenant UUID: set defaultTenantId on AxHubClient. Backend route GET /api/v1/tenants/{tenantID}/discover/apps takes a tenant UUID, not a slug.",code:"tenant_id_required",category:"tenant_id_required",httpStatus:0,retryable:false,requestId:"",fields:[{name:"tenantId",code:"required"}]});let n=await this.http.request("GET",`/api/v1/tenants/${encodeURIComponent(this.defaultTenantId)}/discover/apps`,u({ring:"admin",query:this.feedQuery(e)}));return R(n,g)}};function fi(t){return {key:t.key,value:t.value,createdAt:t.created_at,updatedAt:t.updated_at}}i(fi,"toEnvVar");var Jn=/^[A-Z_][A-Z0-9_]*$/;function pn(t){if(!Jn.test(t))throw new l({message:`Env var key must match ${Jn}`,code:"validation_failed",category:"validation",httpStatus:0,retryable:false,requestId:"",fields:[{name:"key",code:"invalid_format"}]})}i(pn,"validateEnvKey");var Tt=class{constructor(e){this.http=e;}http;static{i(this,"AppsEnvVarsMixin");}async listEnvVars(e){return (await this.http.request("GET",`/api/v1/apps/${encodeURIComponent(e)}/env-vars`,{ring:"admin"})).items.map(fi)}async setEnvVar(e,n,r,s){pn(n);let o={key:n,value:r};s!==void 0&&(o.stage=s),await this.http.request("POST",`/api/v1/apps/${encodeURIComponent(e)}/env-vars`,{ring:"admin",body:o,idempotent:true});}async getEnvVar(e,n){pn(n);let r=(await this.listEnvVars(e)).find(s=>s.key===n);if(!r)throw new y({message:`Env var ${n} not found`,code:"not_found",category:"not_found",httpStatus:404,retryable:false,requestId:"",resource:"env_var"});return r}async deleteEnvVar(e,n){pn(n),await this.http.request("DELETE",`/api/v1/apps/${encodeURIComponent(e)}/env-vars/${encodeURIComponent(n)}`,{ring:"admin",idempotent:true});}};function mn(t){return {connected:true,...t.provider!==void 0?{provider:t.provider}:{},repoFullName:t.repo_full_name,branch:t.branch,installationId:t.installation_id}}i(mn,"toGitConnection");function yi(t){return "connected"in t&&t.connected===false?{connected:false,installUrl:t.install_url}:mn(t)}i(yi,"toGitConnectionStatus");var Pt=class{constructor(e){this.http=e;}http;static{i(this,"AppsGitMixin");}async get(e){let n=await this.http.request("GET",`/api/v1/apps/${encodeURIComponent(e)}/git-connection`,{ring:"admin"});return yi(n)}async connect(e,n){let r=await this.http.request("POST",`/api/v1/apps/${encodeURIComponent(e)}/git-connection`,{ring:"admin",body:{repo_full_name:n.repoFullName,branch:n.branch,installation_id:n.installationId,state:n.state},idempotent:false});return mn(r)}async update(e,n){let r=await this.http.request("PATCH",`/api/v1/apps/${encodeURIComponent(e)}/git-connection`,{ring:"admin",body:{branch:n.branch},idempotent:false});return mn(r)}async disconnect(e){await this.http.request("DELETE",`/api/v1/apps/${encodeURIComponent(e)}/git-connection`,{ring:"admin",idempotent:true});}async installStart(e,n){let r=await this.http.request("GET",`/api/v1/apps/${encodeURIComponent(e)}/git/github/install/start`,{ring:"admin",query:void 0});if(typeof r=="string")return {redirectUrl:r};let s=r;return {redirectUrl:s.redirect_url??s.install_url??s.location??""}}};function hi(t){return {id:t.id,appId:t.app_id,userId:t.user_id,allowedScopes:t.allowed_scopes??[],grantedAt:t.granted_at??"",createdAt:t.created_at??""}}i(hi,"toInvitation");var Et=class{constructor(e){this.http=e;}http;static{i(this,"AppsInvitationsMixin");}async create(e,n){let r=await this.http.request("POST",`/api/v1/apps/${encodeURIComponent(e)}/invitations`,{ring:"admin",body:{user_id:n.userId},idempotent:false});return hi(r)}async delete(e,n){await this.http.request("DELETE",`/api/v1/apps/${encodeURIComponent(e)}/invitations/${encodeURIComponent(n)}`,{ring:"admin",idempotent:true});}};var qt=class{constructor(e){this.http=e;}http;static{i(this,"AppsLifecycleMixin");}async suspend(e){let n=await this.http.request("POST",`/api/v1/apps/${encodeURIComponent(e)}/suspend`,{ring:"admin",body:{},idempotent:false});return g(n)}async resume(e){let n=await this.http.request("POST",`/api/v1/apps/${encodeURIComponent(e)}/resume`,{ring:"admin",body:{},idempotent:false});return g(n)}};var Ot=class{constructor(e){this.http=e;}http;static{i(this,"AppsLikesMixin");}async like(e){return {inserted:(await this.http.request("POST",`/api/v1/apps/${encodeURIComponent(e)}/likes`,{ring:"admin",idempotent:true}))?.inserted??true}}async unlike(e){try{return {deleted:(await this.http.request("DELETE",`/api/v1/apps/${encodeURIComponent(e)}/likes`,{ring:"admin",idempotent:!0}))?.deleted??!0}}catch(n){if(bi(n))return {deleted:false};throw n}}async me(e){return {liked:(await this.http.request("GET",`/api/v1/apps/${encodeURIComponent(e)}/likes/me`,{ring:"admin"})).liked}}};function bi(t){return typeof t=="object"&&t!==null&&"httpStatus"in t&&t.httpStatus===404}i(bi,"isNotFound");function Ri(t){let e={id:t.id,appId:t.app_id,userId:t.user_id,allowedScopes:t.allowed_scopes??[],grantedAt:t.granted_at??""};return t.email!==void 0&&(e.email=t.email),t.granted_by_id!==void 0&&(e.grantedById=t.granted_by_id),e}i(Ri,"toMember");var Dt=class{constructor(e){this.http=e;}http;static{i(this,"AppsMembersMixin");}async list(e,n){let r={};n?.page!==void 0&&(r.page=n.page),n?.perPage!==void 0&&(r.per_page=n.perPage);let s=await this.http.request("GET",`/api/v1/apps/${encodeURIComponent(e)}/members`,u({ring:"admin",query:r},n));return R(s,Ri)}};var Ut=class{constructor(e){this.http=e;}http;static{i(this,"AppsMeMixin");}async owned(e){let n=await this.http.request("GET","/api/v1/me/apps/owned",u({ring:"admin"},e));return R(n,g)}async received(e){let n=await this.http.request("GET","/api/v1/me/apps/received",u({ring:"admin"},e));return R(n,g)}};function er(t){return {id:t.id,appId:t.app_id,name:t.name,clientId:t.client_id??t.id,redirectUris:t.redirect_uris,scopes:t.scopes??t.allowed_scopes??[],createdAt:t.created_at}}i(er,"toClient");function wi(t){return {...er(t),clientSecret:t.client_secret}}i(wi,"toClientWithSecret");var Lt=class{constructor(e){this.http=e;}http;static{i(this,"AppsOAuthClientsMixin");}async create(e,n){if(!n.scopes||n.scopes.length===0)throw new l({message:"scopes must be a non-empty array",code:"empty",category:"validation",httpStatus:0,retryable:false,requestId:"",fields:[{name:"scopes",code:"empty"}]});let r=await this.http.request("POST",`/api/v1/apps/${encodeURIComponent(e)}/oauth-clients`,{ring:"admin",body:{name:n.name,type:n.type??"confidential",token_endpoint_auth_method:n.tokenEndpointAuthMethod??(n.type==="public"?"none":"client_secret_post"),redirect_uris:n.redirectUris,allowed_scopes:n.scopes,allowed_grant_types:n.allowedGrantTypes??["authorization_code","refresh_token"],...n.allowedResources!==void 0?{allowed_resources:n.allowedResources}:{}},idempotent:false});return wi(r)}async get(e){let n=await this.http.request("GET",`/api/v1/oauth-clients/${encodeURIComponent(e)}`,{ring:"admin"});return er(n)}};function tr(t){let e={id:t.id,appId:t.app_id,requesterId:t.requester_id,status:t.status,createdAt:t.created_at,updatedAt:t.updated_at};t.reason!==void 0&&(e.reason=t.reason),t.reviewer_id!==void 0&&(e.reviewerId=t.reviewer_id);let n=t.reviewer_comment??t.review_comment;return n!==void 0&&(e.reviewerComment=n),e}i(tr,"toPublicationRequest");var Mt=class{constructor(e){this.http=e;}http;static{i(this,"AppsPublicationMixin");}async submit(e,n){let r={};n?.reason!==void 0&&(r.reason=n.reason);let s=await this.http.request("POST",`/api/v1/apps/${encodeURIComponent(e)}/review-requests`,{ring:"admin",body:r,idempotent:false});return tr(s)}async list(e,n){let r={};n?.pageSize!==void 0&&(r.limit=n.pageSize),n?.cursor!==void 0&&(r.cursor=n.cursor);let s=await this.http.request("GET",`/api/v1/apps/${encodeURIComponent(e)}/review-requests`,{ring:"admin",query:r});return {items:s.items.map(tr),nextCursor:s.next_cursor,total:s.total}}async unpublish(e,n){let r={visibility:"private"};n?.comment!==void 0&&(r.review_comment=n.comment);let s=await this.http.request("PATCH",`/api/v1/apps/${encodeURIComponent(e)}`,{ring:"admin",body:r,idempotent:false});return g(s)}};function nr(t){switch(t){case "timestamp":return "timestamptz";case "json":return "jsonb";default:return t}}i(nr,"toWireColumnType");function rr(t){if(t!==void 0)return t===null?null:String(t)}i(rr,"toWireDefault");function vi(t){switch(t){case "integer":return "int";case "timestamp with time zone":return "timestamptz";case "jsonb":return "jsonb";case "numeric":return "float";default:return t}}i(vi,"fromWireColumnType");function _i(t){let e={name:t.name,type:vi(t.type)};return t.nullable!==void 0&&(e.nullable=t.nullable),t.default!==void 0&&(e.default=t.default),e}i(_i,"toColumn");function gn(t){return {appId:t.app_id,schemaName:t.schema_name??"",tableName:t.table_name??t.name??"",ownerColumn:t.owner_column??"",columns:(t.columns??[]).map(_i),createdAt:t.created_at??"",updatedAt:t.updated_at??""}}i(gn,"toTable");function xi(t){return {...gn(t),indexes:t.indexes??[],constraints:t.constraints??[],rowCount:t.row_count,sizeBytes:t.size_bytes}}i(xi,"toTableSchema");function ir(t,e=""){return {id:t.id,appId:t.app_id,tableName:t.table_name??e,principalType:t.principal_type,principalId:t.principal_id,scopes:t.scopes??t.actions??[],createdAt:t.granted_at??t.created_at??""}}i(ir,"toGrant");var $t=class{constructor(e){this.http=e;}http;static{i(this,"AppsTablesMixin");}async list(e){return (await this.http.request("GET",`/api/v1/apps/${encodeURIComponent(e)}/tables`,{ring:"admin"})).items.map(gn)}async create(e,n){S(n.name,"name");let r=await this.http.request("POST",`/api/v1/apps/${encodeURIComponent(e)}/tables`,{ring:"admin",body:{table_name:n.name,owner_column:n.ownerColumn,...n.description!==void 0?{description:n.description}:{},columns:n.columns.map(s=>({name:s.name,type:nr(s.type),...s.nullable!==void 0?{nullable:s.nullable}:{},...s.default!==void 0?{default:rr(s.default)}:{}}))},idempotent:false});return gn(r)}async delete(e,n){S(n,"tableName"),await this.http.request("DELETE",`/api/v1/apps/${encodeURIComponent(e)}/tables/${encodeURIComponent(n)}`,{ring:"admin",idempotent:true});}async addColumn(e,n,r){S(n,"tableName");let s={name:r.name,type:nr(r.type)};r.nullable!==void 0&&(s.nullable=r.nullable),r.default!==void 0&&(s.default=rr(r.default)),await this.http.request("POST",`/api/v1/apps/${encodeURIComponent(e)}/tables/${encodeURIComponent(n)}/columns`,{ring:"admin",body:{column:s},idempotent:false});}async dropColumn(e,n,r){S(n,"tableName"),await this.http.request("DELETE",`/api/v1/apps/${encodeURIComponent(e)}/tables/${encodeURIComponent(n)}/columns/${encodeURIComponent(r)}`,{ring:"admin",idempotent:true});}async listGrants(e,n){return S(n,"tableName"),(await this.http.request("GET",`/api/v1/apps/${encodeURIComponent(e)}/tables/${encodeURIComponent(n)}/grants`,{ring:"admin"})).items.map(s=>ir(s,n))}async addGrant(e,n,r){S(n,"tableName");let s=await this.http.request("POST",`/api/v1/apps/${encodeURIComponent(e)}/tables/${encodeURIComponent(n)}/grants`,{ring:"admin",body:{principal_type:r.principalType,principal_id:r.principalId,actions:r.scopes},idempotent:false});return ir(s,n)}async revokeGrant(e,n,r){S(n,"tableName"),await this.http.request("DELETE",`/api/v1/apps/${encodeURIComponent(e)}/tables/${encodeURIComponent(n)}/grants/${encodeURIComponent(r)}`,{ring:"admin",idempotent:true});}async inspect(e,n){S(n,"tableName");let r=await this.http.request("GET",`/api/v1/apps/${encodeURIComponent(e)}/tables/${encodeURIComponent(n)}`,{ring:"admin"});return xi(r)}async checkAvailability(e,n){S(n,"tableName");let r=await this.http.request("GET",`/api/v1/apps/${encodeURIComponent(e)}/tables/check-availability`,{ring:"admin",query:{table_name:n}});return {available:r.available,reason:r.reason??""}}async columnTypes(e){return ((await this.http.request("GET",`/api/v1/apps/${encodeURIComponent(e)}/tables/column-types`,{ring:"admin"})).types??[]).map(r=>({value:r.value,label:r.label}))}async browseRows(e,n,r){S(n,"tableName");let s={};r?.page!==void 0&&(s.page=r.page),r?.perPage!==void 0&&(s.per_page=r.perPage);let o=await this.http.request("GET",`/api/v1/apps/${encodeURIComponent(e)}/tables/${encodeURIComponent(n)}/rows`,u({ring:"admin",query:s},r));return {columns:(o.columns??[]).map(a=>({name:a.name,type:a.type,nullable:a.nullable})),rows:o.rows??[],meta:{page:o.meta?.page??1,perPage:o.meta?.per_page??0,total:o.meta?.total??0,totalPages:o.meta?.total_pages??0}}}};var Gt=class{constructor(e,n){this.http=e;this.defaultTenantSlug=n;}http;defaultTenantSlug;static{i(this,"AppsTemplatesMixin");}async list(e){let n={...q(e),...this.defaultTenantSlug?{tenant_slug:this.defaultTenantSlug}:{}},r=await this.http.request("GET","/api/v1/templates",u({ring:"admin",query:n},e));return R(r,s=>s)}};var Je=class{static{i(this,"AppsClient");}crud;lifecycle;availability;envVars;publication;access;invitations;members;me;categories;discover;likes;comments;oauthClients;git;tables;templates;constructor(e,n,r,s){this.crud=new It(e,n,r,s),this.lifecycle=new qt(e),this.availability=new _t(e,r),this.envVars=new Tt(e),this.publication=new Mt(e),this.access=new vt(e),this.invitations=new Et(e),this.members=new Dt(e),this.me=new Ut(e),this.categories=new xt(e),this.discover=new kt(e,n,r),this.likes=new Ot(e),this.comments=new Ct(e),this.oauthClients=new Lt(e),this.git=new Pt(e),this.tables=new $t(e),this.templates=new Gt(e,n);}create=i((...e)=>this.crud.create(...e),"create");list=i((...e)=>this.crud.list(...e),"list");listAll=i((...e)=>this.crud.listAll(...e),"listAll");get=i((...e)=>this.crud.get(...e),"get");update=i((...e)=>this.crud.update(...e),"update");delete=i((...e)=>this.crud.delete(...e),"delete");permanent=i((...e)=>this.crud.permanent(...e),"permanent");signIconUploadURL=i((...e)=>this.crud.signIconUploadURL(...e),"signIconUploadURL");signIconDarkUploadURL=i((...e)=>this.crud.signIconDarkUploadURL(...e),"signIconDarkUploadURL");listMine=i((...e)=>this.crud.listMine(...e),"listMine");suspend=i((...e)=>this.lifecycle.suspend(...e),"suspend");resume=i((...e)=>this.lifecycle.resume(...e),"resume");checkAvailability=i((...e)=>this.availability.checkAvailability(...e),"checkAvailability");iconPreCreateUrl=i((...e)=>this.availability.iconPreCreateUrl(...e),"iconPreCreateUrl");listEnvVars=i((...e)=>this.envVars.listEnvVars(...e),"listEnvVars");setEnvVar=i((...e)=>this.envVars.setEnvVar(...e),"setEnvVar");getEnvVar=i((...e)=>this.envVars.getEnvVar(...e),"getEnvVar");deleteEnvVar=i((...e)=>this.envVars.deleteEnvVar(...e),"deleteEnvVar")};var tt=class{constructor(e,n,r){this.http=e;this.defaultTenantId=n;this.tenantResolver=r;}http;defaultTenantId;tenantResolver;static{i(this,"CostClient");}tenant(e){return new F(this.http,e,this.tenantResolver)}summary(e){return this.defaultTenant().summary(e)}byCostCenter(e){return this.defaultTenant().byCostCenter(e)}byApp(e){return this.defaultTenant().byApp(e)}timeseries(e){return this.defaultTenant().timeseries(e)}export(e){return this.defaultTenant().export(e)}defaultTenant(){if(!this.defaultTenantId)throw new w({message:"sdk.cost requires defaultTenantId or sdk.cost.tenant(tenantIdOrSlug)",code:"tenant_id_required",category:"tenant_id_required",httpStatus:0,retryable:false,requestId:"",fields:[{name:"tenantId",code:"required"}]});return new F(this.http,this.defaultTenantId,this.tenantResolver)}},F=class{constructor(e,n,r){this.http=e;this.tenantIdOrSlug=n;this.tenantResolver=r;}http;tenantIdOrSlug;tenantResolver;static{i(this,"TenantCostClient");}async summary(e){let n=await this.http.request("GET",`${await this.base()}/summary`,u({ring:"admin",query:et(e)},e));return Ci(n)}async byCostCenter(e){let n=await this.http.request("GET",`${await this.base()}/by-cost-center`,u({ring:"admin",query:et(e)},e));return {rows:(n.rows??[]).map(Ii),unassigned:{appCount:n.unassigned?.app_count??0,cost:n.unassigned?.cost??0}}}async byApp(e){return {rows:((await this.http.request("GET",`${await this.base()}/by-app`,u({ring:"admin",query:{...et(e),...e?.sort?{sort:e.sort}:{}}},e))).rows??[]).map(Si)}}async timeseries(e){return {series:((await this.http.request("GET",`${await this.base()}/timeseries`,u({ring:"admin",query:{...et(e),...e?.appId?{app_id:e.appId}:{}}},e))).series??[]).map(r=>({date:r.date??"",total:r.total??0,byResource:r.by_resource??{}}))}}async export(e){return this.http.request("GET",`${await this.base()}/export`,u({ring:"admin",query:{...et(e),format:e?.format??"csv"}},e))}async base(){let e=this.tenantResolver?await this.tenantResolver.resolveTenantId(this.tenantIdOrSlug):this.tenantIdOrSlug;return `/api/v1/tenants/${c(e)}/cost`}};function et(t){return t?.month?{month:t.month}:{}}i(et,"monthQuery");function Ci(t){let e={month:t.month??"",currency:t.currency??"KRW",total:t.total??0,billedTotal:t.billed_total??0,forecastMonthEnd:t.forecast_month_end??0,partialMonth:t.partial_month??false};return t.top_driver&&(e.topDriver={resourceKind:t.top_driver.resource_kind??"",share:t.top_driver.share??0}),t.last_rolled_up_at!==void 0&&(e.lastRolledUpAt=t.last_rolled_up_at),e}i(Ci,"toSummary");function Ii(t){return {costCenter:t.cost_center??"",appCount:t.app_count??0,cost:t.cost??0,...t.budget!==void 0?{budget:t.budget}:{},...t.budget_pct!==void 0?{budgetPct:t.budget_pct}:{},...t.over!==void 0?{over:t.over}:{},byResource:t.by_resource??{},byResourceQty:t.by_resource_qty??{}}}i(Ii,"toCostCenterRow");function Si(t){return {appId:t.app_id??"",name:t.name??"",...t.cost_center!==void 0?{costCenter:t.cost_center}:{},cost:t.cost??0,byResource:t.by_resource??{},byResourceQty:t.by_resource_qty??{}}}i(Si,"toCostByAppRow");var nt=class{constructor(e,n){this.http=e;this.tenantResolver=n;}http;tenantResolver;static{i(this,"InviteLinksClient");}tenant(e){return new Y(this.http,e,this.tenantResolver)}async preview(e,n){let r=await this.http.request("GET",`/api/v1/invite-links/${c(e)}`,u({ring:"public"},n));return Ai(r)}async accept(e,n){let r=await this.http.request("POST",`/api/v1/invite-links/${c(e)}/accept`,u({ring:"admin",body:{},idempotent:true},n));return {tenantId:r.tenant_id??"",tenantSlug:r.tenant_slug??"",joined:r.joined??false,alreadyMember:r.already_member??false}}},Y=class{constructor(e,n,r){this.http=e;this.tenantIdOrSlug=n;this.tenantResolver=r;}http;tenantIdOrSlug;tenantResolver;static{i(this,"TenantInviteLinksClient");}async create(e,n){let r={};e?.expiresAt!==void 0&&(r.expires_at=e.expiresAt);let s=await this.http.request("POST",await this.base(),u({ring:"admin",body:r,idempotent:false},n));return sr(s)}async list(e){let n=await this.http.request("GET",await this.base(),u({ring:"admin"},e));return R({items:n.items,next_cursor:n.next_cursor??null,total:n.total??n.items.length},sr)}async revoke(e,n){await this.http.request("DELETE",`${await this.base()}/${c(e)}`,u({ring:"admin",idempotent:true},n));}async base(){let e=this.tenantResolver?await this.tenantResolver.resolveTenantId(this.tenantIdOrSlug):this.tenantIdOrSlug;return `/api/v1/tenants/${c(e)}/invite-links`}};function sr(t){return {id:t.id??"",tenantId:t.tenant_id??"",...t.url!==void 0?{url:t.url}:{},role:t.role??"",status:t.status??"",...t.expires_at!==void 0?{expiresAt:t.expires_at}:{},joinCount:t.join_count??0,createdAt:t.created_at??""}}i(sr,"toInviteLink");function Ai(t){let e={valid:t.valid??false};return t.tenant&&(e.tenant={name:t.tenant.name??"",...t.tenant.icon_url!==void 0?{iconUrl:t.tenant.icon_url}:{}}),e}i(Ai,"toPreview");var rt=class{constructor(e,n,r,s){this.slug=e;this.root=r;this.apps=new Bt(e,n.http,s),this.cost=new F(n.http,e,s),this.inviteLinks=new Y(n.http,e,s);}slug;root;static{i(this,"TenantScopedClient");}apps;cost;inviteLinks;get gateway(){return this.root.gateway.scoped(this.slug)}app(e){return new Ht(this.slug,e,this.root)}},Bt=class{constructor(e,n,r){this.tenantSlug=e;this.http=n;this.tenantResolver=r;}tenantSlug;http;tenantResolver;static{i(this,"TenantScopedAppsClient");}async create(e,n){let r=await this.tenantResolver.resolveTenantId(this.tenantSlug,n),s=await this.http.request("POST",`/api/v1/tenants/${c(r)}/apps`,u({ring:"admin",body:St(e),idempotent:false},n));return g(s)}async list(e){let n=await this.tenantResolver.resolveTenantId(this.tenantSlug,e),r=await this.http.request("GET",`/api/v1/tenants/${c(n)}/apps`,u({ring:"admin",query:q(e)},e));return R(r,g)}listAll(e){return k(n=>this.list({...e,...n}),e)}async get(e,n){let r=await this.http.request("GET",`/api/v1/apps/${c(e)}`,u({ring:"admin"},n));return g(r)}async update(e,n,r){let s=await this.http.request("PATCH",`/api/v1/apps/${c(e)}`,u({ring:"admin",body:At(n),idempotent:false},r));return g(s)}async delete(e,n){await this.http.request("DELETE",`/api/v1/apps/${c(e)}`,u({ring:"admin",idempotent:true},n));}},Ht=class{constructor(e,n,r){this.tenantSlug=e;this.appSlug=n;this.root=r;this.data=new jt(e,n,r.data);}tenantSlug;appSlug;root;static{i(this,"AppScopedClient");}data},jt=class{constructor(e,n,r){this.tenantSlug=e;this.appSlug=n;this.rootData=r;}tenantSlug;appSlug;rootData;static{i(this,"AppScopedDataClient");}table(e){return this.rootData.table(this.tenantSlug,this.appSlug,e)}discover(e,n){return this.rootData.discover(this.tenantSlug,this.appSlug,e,n)}invalidateSchema(e){e===void 0?this.rootData.invalidateSchema():this.rootData.invalidateSchema(this.tenantSlug,this.appSlug,e);}};function ki(t){let e={clientId:String(t.client_id??""),raw:t};return t.client_id_issued_at!==void 0&&(e.clientIdIssuedAt=t.client_id_issued_at),t.client_name!==void 0&&(e.clientName=t.client_name),t.redirect_uris!==void 0&&(e.redirectUris=t.redirect_uris),t.grant_types!==void 0&&(e.grantTypes=t.grant_types),t.response_types!==void 0&&(e.responseTypes=t.response_types),t.scope!==void 0&&(e.scope=t.scope),t.token_endpoint_auth_method!==void 0&&(e.tokenEndpointAuthMethod=t.token_endpoint_auth_method),e}i(ki,"registerMcpResult");function or(t){return {...t,id:String(t.id),clientId:t.client_id??t.id,tenantId:t.tenant_id??t.tenantId,redirectUris:t.redirect_uris??t.redirectUris,scopes:t.scopes??t.allowed_scopes}}i(or,"toSystemOAuthClient");function Ft(t){return {accessToken:String(t.access_token??""),tokenType:String(t.token_type??"Bearer"),expiresIn:t.expires_in,refreshToken:t.refresh_token,scope:t.scope,raw:t}}i(Ft,"tokenResponse");function Ti(t){if(!t.name||t.name.trim()==="")throw new l({message:"name is required and must be non-empty",code:"validation_failed",category:"validation",httpStatus:0,retryable:false,requestId:"",fields:[{name:"name",code:"empty"}]});if(t.expiresInDays!==void 0&&t.expiresInDays<0)throw new l({message:"expiresInDays must be non-negative",code:"validation_failed",category:"validation",httpStatus:0,retryable:false,requestId:"",fields:[{name:"expiresInDays",code:"invalid_value"}]})}i(Ti,"validatePATInput");function Pi(t){if(typeof t!="object"||t===null)return false;let e=t.user;if(typeof e!="object"||e===null)return false;let n=e;return typeof n.id=="string"&&typeof n.email=="string"}i(Pi,"isWrappedMeResponse");var it=class{constructor(e,n){this.http=e;this.pat=new Nt(e,n),this.meClient=new J(e),this.oauth=new Qt(e,n),this.oidc=new Kt(e,n),this.deviceCode=new zt(e,n),this.systemOAuthClients=new Wt(e),this.invitations=new Vt(e);}http;static{i(this,"IdentityClient");}pat;meClient;oauth;oidc;deviceCode;systemOAuthClients;invitations;issuePersonalAccessToken(e,n){return this.pat.issue(e,n)}listPersonalAccessTokens(e){return this.pat.list(e)}revokePersonalAccessToken(e,n){return this.pat.revoke(e,n)}me(e){return this.meClient.get(e)}},Nt=class{constructor(e,n){this.http=e;this.defaultTenantSlug=n;}http;defaultTenantSlug;static{i(this,"IdentityPATClient");}tenantQuery(){return this.defaultTenantSlug?{tenant_slug:this.defaultTenantSlug}:void 0}async issue(e,n){Ti(e);let r={name:e.name};e.expiresInDays!==void 0&&(r.expires_in_days=e.expiresInDays);let s=await this.http.request("POST","/api/v1/me/personal-access-tokens",u({ring:"admin",query:this.tenantQuery(),body:r,idempotent:false},n));return {patId:s.id,name:s.name,rawToken:s.raw_token,createdAt:s.created_at,expiresAt:s.expires_at}}async list(e){return (await this.http.request("GET","/api/v1/me/personal-access-tokens",u({ring:"admin",query:this.tenantQuery()},e))).items.map(r=>({id:r.id,name:r.name,createdAt:r.created_at,expiresAt:r.expires_at,lastUsedAt:r.last_used_at}))}async revoke(e,n){await this.http.request("DELETE",`/api/v1/me/personal-access-tokens/${c(e)}`,u({ring:"admin",query:this.tenantQuery(),idempotent:true},n));}},J=class{constructor(e){this.http=e;}http;static{i(this,"IdentityMeClient");}async get(e){let n=await this.http.request("GET","/api/v1/me",u({ring:"admin"},e));return Pi(n)?{...n,userId:n.user.id,email:n.user.email,name:n.user.name,platformAdmin:n.user.platform_admin,tenants:n.tenants?.map(s=>({tenantId:s.tenant_id,tenantSlug:s.tenant_slug,role:s.role,isActive:s.is_active,iconUrl:s.icon_url}))}:n}},Qt=class{constructor(e,n){this.http=e;this.defaultTenantSlug=n;}http;defaultTenantSlug;static{i(this,"IdentityOAuthClient");}tenantQuery(e={}){let n=this.defaultTenantSlug?{...e,tenant_slug:this.defaultTenantSlug}:e;return Object.keys(n).length>0?n:void 0}authorizeUrl(e){let n=new URLSearchParams({response_type:"code",client_id:e.clientId,redirect_uri:e.redirectUri});return this.defaultTenantSlug&&n.set("tenant_slug",this.defaultTenantSlug),e.scope&&n.set("scope",e.scope),e.state&&n.set("state",e.state),e.codeChallenge&&n.set("code_challenge",e.codeChallenge),e.codeChallengeMethod&&n.set("code_challenge_method",e.codeChallengeMethod),e.resource&&n.set("resource",e.resource),`/oauth/authorize?${n.toString()}`}async exchangeCode(e,n){if(!e.codeVerifier)throw new l({message:"codeVerifier is required for PKCE",code:"required",category:"validation",httpStatus:0,retryable:false,requestId:"",fields:[{name:"codeVerifier",code:"required"}]});let r=await this.http.request("POST","/oauth/token",u({ring:"public",query:this.tenantQuery(),form:{grant_type:"authorization_code",code:e.code,client_id:e.clientId,redirect_uri:e.redirectUri,code_verifier:e.codeVerifier,client_secret:e.clientSecret,resource:e.resource},idempotent:false},n));return Ft(r)}async refreshTokens(e,n){let r=await this.http.request("POST","/oauth/token",u({ring:"public",query:this.tenantQuery(),form:{grant_type:"refresh_token",refresh_token:e.refreshToken,client_id:e.clientId,client_secret:e.clientSecret,resource:e.resource},idempotent:false},n));return Ft(r)}async revoke(e,n){await this.http.request("POST","/oauth/revoke",u({ring:"public",query:this.tenantQuery(),form:{token:e.token,token_type_hint:e.tokenTypeHint,client_id:e.clientId},idempotent:true},n));}userinfo(e){return this.http.request("GET","/oauth/userinfo",u({ring:"admin"},e))}async registerMcpClient(e,n){let r=j({client_name:e.clientName,client_uri:e.clientUri,redirect_uris:e.redirectUris,grant_types:e.grantTypes,response_types:e.responseTypes,scope:e.scope,token_endpoint_auth_method:e.tokenEndpointAuthMethod,resource:e.resource,resources:e.resources,software_id:e.softwareId,software_version:e.softwareVersion}),s=await this.http.request("POST","/oauth/register",u({ring:"public",body:r,idempotent:false},n));return ki(s)}async selectTenant(e,n){return {redirectTo:(await this.http.request("POST","/oauth/authorize/tenant",u({ring:"admin",body:j({client_id:e.clientId,redirect_uri:e.redirectUri,tenant_id:e.tenantId,scope:e.scope,state:e.state,code_challenge:e.codeChallenge,code_challenge_method:e.codeChallengeMethod,nonce:e.nonce,resource:e.resource}),idempotent:false},n))).redirect_to??""}}async getClient(e,n){let r=await this.http.request("GET",`/api/v1/oauth-clients/${c(e)}`,u({ring:"admin"},n));return or(r)}async revokeOwnGrant(e,n){await this.http.request("DELETE",`/api/v1/oauth/clients/${c(e)}/grants/me`,u({ring:"admin",idempotent:true},n));}},Vt=class{constructor(e){this.http=e;}http;static{i(this,"IdentityInvitationsClient");}async accept(e,n){await this.http.request("POST",`/api/v1/me/invitations/${c(e)}/accept`,u({ring:"admin",body:{},idempotent:false},n));}},Kt=class{constructor(e,n){this.http=e;this.defaultTenantSlug=n;}http;defaultTenantSlug;static{i(this,"IdentityOIDCClient");}tenantQuery(e={}){let n=this.defaultTenantSlug?{...e,tenant_slug:this.defaultTenantSlug}:e;return Object.keys(n).length>0?n:void 0}discovery(e){return this.http.request("GET","/.well-known/openid-configuration",u({ring:"public"},e))}jwks(e){return this.http.request("GET","/.well-known/jwks.json",u({ring:"public"},e))}providers(e){return this.http.request("GET","/auth/providers",u({ring:"public",query:this.tenantQuery()},e))}async startURL(e,n,r){let s=await this.http.request("GET",`/auth/${c(e)}/start`,u({ring:"public",query:this.tenantQuery(j({redirect_to:n?.redirectTo,state:n?.state,return_origin:n?.returnOrigin})),parseBody:true},r));return s.url??s.redirect_url??`/auth/${c(e)}/start`}googleStartUrl(e){let n=new URLSearchParams;this.defaultTenantSlug&&n.set("tenant_slug",this.defaultTenantSlug),e?.returnTo&&n.set("return_to",e.returnTo),e?.returnOrigin&&n.set("return_origin",e.returnOrigin);let r=n.toString();return r?`/auth/google_oauth2/start?${r}`:"/auth/google_oauth2/start"}exchangeCallback(e,n){return this.http.request("GET",e.provider?`/auth/${c(e.provider)}/callback`:"/auth/oidc/callback",u({ring:"public",query:this.tenantQuery(j(e))},n)).then(Ft)}githubStartUrl(e){let n=new URLSearchParams;this.defaultTenantSlug&&n.set("tenant_slug",this.defaultTenantSlug),e?.returnTo&&n.set("return_to",e.returnTo);let r=n.toString();return r?`/auth/github?${r}`:"/auth/github"}githubCallbackUrl(e){let n=new URLSearchParams;this.defaultTenantSlug&&n.set("tenant_slug",this.defaultTenantSlug),e.code&&n.set("code",e.code),e.state&&n.set("state",e.state),e.error&&n.set("error",e.error);let r=n.toString();return r?`/auth/github/callback?${r}`:"/auth/github/callback"}},zt=class{constructor(e,n){this.http=e;this.defaultTenantSlug=n;}http;defaultTenantSlug;static{i(this,"IdentityDeviceCodeClient");}tenantQuery(){return this.defaultTenantSlug?{tenant_slug:this.defaultTenantSlug}:void 0}async request(e,n){let r=await this.http.request("POST","/oauth/device_authorization",u({ring:"public",query:this.tenantQuery(),form:{client_id:e.clientId,scope:e.scope},idempotent:false},n));return {deviceCode:r.device_code,userCode:r.user_code,verificationUri:r.verification_uri,verificationUriComplete:r.verification_uri_complete,expiresIn:r.expires_in,interval:r.interval??5,raw:r}}async poll(e,n){let r=e.intervalMs??5e3;for(;;)try{let s=await this.http.request("POST","/oauth/token",u({ring:"public",query:this.tenantQuery(),form:{grant_type:"urn:ietf:params:oauth:grant-type:device_code",device_code:e.deviceCode,client_id:e.clientId},idempotent:!1},{...n,signal:n?.signal??e.signal}));return Ft(s)}catch(s){if(s instanceof H)r+=5e3;else if(!(s instanceof B))throw s;await new Promise((o,a)=>{let d=setTimeout(o,r);e.signal?.addEventListener("abort",()=>{clearTimeout(d),a(e.signal?.reason??s);},{once:true});});}}},Wt=class{constructor(e){this.http=e;}http;static{i(this,"IdentitySystemOAuthClientsClient");}async get(e,n){let r=await this.http.request("GET",`/api/v1/oauth-clients/${c(e)}`,u({ring:"admin"},n));return or(r)}};var Ei=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,st=class{static{i(this,"TenantResolver");}me;cache=new Map;constructor(e){this.me=new J(e);}async resolveTenantId(e,n){if(Ei.test(e))return e;let r=this.cache.get(e);if(r!==void 0)return r;let s=await this.me.get(n);for(let a of s.tenants??[])this.cache.set(a.tenantSlug,a.tenantId);let o=this.cache.get(e);if(o===void 0)throw new w({message:`tenant slug "${e}" not found among your memberships; pass a tenant UUID or join the tenant. Backend route /api/v1/tenants/{tenantID}/apps parses {tenantID} as a UUID.`,code:"tenant_id_required",category:"tenant_id_required",httpStatus:0,retryable:false,requestId:"",fields:[{name:"tenantId",code:"required"}]});return o}};function fn(t,e){if(qi(t))return {...t,...e?.validate!==void 0?{validate:e.validate}:{}};let n={};for(let[s,o]of Object.entries(t.columns))n[s]={table:t.table,name:s,def:o};let r={table:t.table,columns:t.columns,cols:n};return e?.validate!==void 0&&(r.validate=e.validate),r}i(fn,"defineSchema");function qi(t){return typeof t=="object"&&t!==null&&"table"in t&&"columns"in t&&"cols"in t}i(qi,"isDataTableSchema");var ar=1024,Oi=4,Di=6;function Xt(t){return t.length===0?t:t.replace(/[\\%_]/g,e=>`\\${e}`)}i(Xt,"escapeLike");function Ui(t){if(t.length>ar)throw new l({message:`LIKE pattern exceeds ${ar} chars; refuse to compile`,code:"like_pattern_too_long",category:"validation",httpStatus:0,retryable:false,requestId:"",docUrl:"https://docs.axhub.dev/errors/validation/like-pattern"});let e=0,n=0;for(let r=0;r<t.length;r+=1){let s=t[r];if(s==="\\"){r+=1,e=0;continue}if(s==="%"){if(e+=1,e>=Oi)throw new l({message:`LIKE pattern has ${e} consecutive '%'; refuse to compile (ReDoS guard)`,code:"like_pattern_redos",category:"validation",httpStatus:0,retryable:false,requestId:"",docUrl:"https://docs.axhub.dev/errors/validation/like-pattern"})}else e===1&&(n+=1),e=0;}if(n>Di)throw new l({message:`LIKE pattern has ${n} '%X%' alternation segments; refuse to compile (ReDoS guard)`,code:"like_pattern_redos",category:"validation",httpStatus:0,retryable:false,requestId:"",docUrl:"https://docs.axhub.dev/errors/validation/like-pattern"})}i(Ui,"assertSafeLikePattern");function Li(t,e){return e?{op:"raw",sql:t,params:e}:{op:"raw",sql:t}}i(Li,"raw");function Mi(...t){return {op:"and",clauses:t}}i(Mi,"and");function $i(...t){return {op:"or",clauses:t}}i($i,"or");function Gi(t){return {op:"not",clause:t}}i(Gi,"not");function Bi(t){let e=typeof t=="string"?t:t.name,n=i((r,s)=>({op:r,column:e,value:s}),"binary");return {eq:i(r=>n("eq",r),"eq"),ne:i(r=>n("ne",r),"ne"),gt:i(r=>n("gt",r),"gt"),gte:i(r=>n("gte",r),"gte"),lt:i(r=>n("lt",r),"lt"),lte:i(r=>n("lte",r),"lte"),in:i(r=>({op:"in",column:e,values:r}),"in"),like:{contains:i(r=>n("like",`%${Xt(r)}%`),"contains"),startsWith:i(r=>n("like",`${Xt(r)}%`),"startsWith"),endsWith:i(r=>n("like",`%${Xt(r)}`),"endsWith"),raw:i(r=>(Ui(r),n("like",r)),"raw")}}}i(Bi,"where");function O(t,e,n){let r=t?.validate;if(r===void 0)return;if(!Hi(r))throw new z({message:"defineSchema validate option requires a Zod-compatible schema with safeParse()",code:"zod_missing",category:"configuration",httpStatus:0,retryable:false,requestId:"",resource:t?.table,docUrl:"https://docs.axhub.dev/errors/configuration/zod-missing"});let o=(n==="update"&&typeof r.partial=="function"?r.partial():r).safeParse(e);if(o.success)return;let a=o.error?.issues??[],d=a.map(p=>({name:p.path?.join(".")||"$",code:p.code??"invalid",message:p.message}));throw new l({message:`${a.length||1} validation failure${a.length===1?"":"s"} before network request`,code:"zod_validation_failed",category:"validation",httpStatus:0,retryable:false,requestId:"",resource:t?.table,fields:d,docUrl:"https://docs.axhub.dev/errors/validation/zod"})}i(O,"runSchemaValidation");function Hi(t){return typeof t=="object"&&t!==null&&typeof t.safeParse=="function"}i(Hi,"isZodSchemaLike");var ur=100,cr=10,dr=5e3;async function lr(t,e,n,r,s){try{return await Fi(t,e,n,r,s)}catch(o){try{return await ji(t,e,n,r,s)}catch{throw Qi(o,e,n,r)}}}i(lr,"fetchDiscoveredSchema");async function ji(t,e,n,r,s){let o=await t.request("GET",`/api/v1/tenants/${c(e)}/apps/${c(n)}/tables/${c(r)}/inspect`,u({ring:"admin"},s));return pr(r,o)}i(ji,"fetchSlugInspect");async function Fi(t,e,n,r,s){let o=await Ni(t,e,n,s);if(!o)throw new $({message:`Dynamic data table '${r}' was not found`,code:"table_not_found",category:"not_found",httpStatus:404,retryable:false,requestId:"",resource:`${e}/${n}/${r}`,docUrl:"https://docs.axhub.dev/sdk/data#discover"});let a=await t.request("GET",`/api/v1/apps/${c(o)}/tables/${c(r)}`,u({ring:"admin"},s));return pr(r,a)}i(Fi,"fetchAppIdInspect");async function Ni(t,e,n,r){let s=Date.now(),o;for(let a=0;a<cr;a+=1){if(r?.signal?.aborted)throw new b({message:"discover aborted while resolving app id",code:"aborted",category:"abort",httpStatus:0,retryable:false,requestId:""});if(Date.now()-s>dr)throw new G({message:`app lookup budget exceeded (${dr}ms) while searching for slug '${n}' in tenant '${e}'`,code:"introspect_failed",category:"internal",httpStatus:0,retryable:false,requestId:"",resource:`${e}/${n}`,docUrl:"https://docs.axhub.dev/sdk/data#discover"});let d=await t.request("GET","/api/v1/apps",u({ring:"admin",query:{tenant_slug:e,limit:ur,cursor:o}},r)),p=d.items??[],I=p.find(E=>E.slug===n&&typeof E.id=="string");if(I?.id)return I.id;if(a===0&&p.length===0||!d.next_cursor)return;o=d.next_cursor;}throw new W({message:`App lookup exceeded ${cr} pages \xD7 ${ur} apps without finding slug '${n}'`,code:"scan_limit_exceeded",category:"internal",httpStatus:0,retryable:false,requestId:"",resource:`${e}/${n}`,docUrl:"https://docs.axhub.dev/errors/internal/scan-limit-exceeded"})}i(Ni,"resolveAppId");function Qi(t,e,n,r){return t instanceof $||t instanceof G||t instanceof W||t instanceof b?t:Wi(t)?new $({message:`Dynamic data table '${r}' was not found`,code:"table_not_found",category:"not_found",httpStatus:404,retryable:false,requestId:Xi(t),resource:`${e}/${n}/${r}`,cause:t,docUrl:"https://docs.axhub.dev/sdk/data#discover"}):yn(t)&&t.httpStatus>=500?new G({message:`Failed to introspect dynamic data table '${r}'`,code:"introspect_failed",category:"internal",httpStatus:t.httpStatus,retryable:t.retryable,requestId:t.requestId,resource:`${e}/${n}/${r}`,cause:t,docUrl:"https://docs.axhub.dev/sdk/data#discover"}):t instanceof Error?t:new Error(String(t))}i(Qi,"normalizeDiscoverError");var Vi=new Set(["__proto__","constructor","prototype"]),Ki=/^[A-Za-z_][A-Za-z0-9_]*$/;function pr(t,e){let n=e.columns??[],r=Object.create(null);for(let s of n)Vi.has(s.name)||Ki.test(s.name)&&(r[s.name]=zi(s));return fn({table:e.tableName??e.table_name??e.name??t,columns:r})}i(pr,"schemaFromInspectResult");function zi(t){switch(t.type){case "uuid":return "uuid";case "int":case "integer":case "bigint":return "integer";case "float":case "numeric":case "double precision":case "real":return "number";case "bool":case "boolean":return "boolean";case "timestamp":case "timestamptz":case "timestamp with time zone":return "timestamp";case "json":case "jsonb":return "json";default:return "string"}}i(zi,"columnTypeToDef");function Wi(t){return t instanceof y||yn(t)&&t.httpStatus===404}i(Wi,"isNotFound");function yn(t){return typeof t=="object"&&t!==null&&"httpStatus"in t&&"requestId"in t}i(yn,"isAxHubError");function Xi(t){return yn(t)?t.requestId:""}i(Xi,"getRequestId");function hn(t){if(t!==void 0)return [...t].join(",")}i(hn,"serializeSelect");function ee(t,e){if(e===void 0)return;if(e.length===0)throw new l({message:"select must include at least one column; omit select to fetch full rows",code:"select_empty",category:"validation",httpStatus:0,retryable:false,requestId:"",resource:t?.table,docUrl:"https://docs.axhub.dev/errors/validation/select-unknown-column"});if(!t)return;let n=new Set(Object.keys(t.columns)),r=e.filter(s=>!n.has(s));if(r.length!==0)throw new l({message:`select contains unknown column${r.length===1?"":"s"}: ${r.join(", ")}`,code:"select_unknown_column",category:"validation",httpStatus:0,retryable:false,requestId:"",resource:t.table,fields:r.map(s=>({name:s,code:"unknown_column"})),docUrl:"https://docs.axhub.dev/errors/validation/select-unknown-column"})}i(ee,"validateSelectColumns");function ot(t,e){if(e===void 0)return t;let n={};for(let r of e)r in t&&(n[r]=t[r]);return n}i(ot,"projectRow");function Zt(t,e){return e===void 0?t:t.map(n=>ot(n,e))}i(Zt,"projectRows");function Zi(t){if(typeof t!="object"||t===null)return false;let e=t.httpStatus;return typeof e=="number"&&e>=500}i(Zi,"isTransientServerError");var te=class{static{i(this,"SchemaCache");}store=new Map;inflight=new Map;maxEntries;ttlMs;negativeTtlMs;writeCounter=0;constructor(e){this.maxEntries=Math.max(1,e?.maxEntries??1e3),this.ttlMs=Math.max(1,e?.ttlMs??3e5),this.negativeTtlMs=Math.max(0,e?.negativeTtlMs??3e4);}get size(){return this.store.size}get(e){let n=this.store.get(e);return n?n.expiresAt<=Date.now()?(this.store.delete(e),null):(this.store.delete(e),this.store.set(e,n),n.schema):null}set(e,n,r){this.writeCounter+=1;let s=this.writeCounter;this.store.delete(e),this.store.set(e,{schema:n,expiresAt:Date.now()+Math.max(1,r?.ttlMs??this.ttlMs),writeToken:s}),this.evictOverflow();}invalidate(e){if(e===void 0){this.store.clear(),this.inflight.clear();return}this.store.delete(e),this.inflight.delete(e);}async getOrSet(e,n,r){if(!r?.fresh){let d=this.get(e);if(d)return d;let p=this.inflight.get(e);if(p)return p}let s=this.store.get(e),o=this.writeCounter+1,a=n().then(d=>{let p=this.store.get(e);return (!p||p.writeToken<o)&&this.set(e,d,r),this.inflight.get(e)===a&&this.inflight.delete(e),d},d=>{throw this.inflight.get(e)===a&&this.inflight.delete(e),s&&this.negativeTtlMs>0&&Zi(d)&&(this.writeCounter+=1,this.store.delete(e),this.store.set(e,{schema:s.schema,expiresAt:Date.now()+this.negativeTtlMs,writeToken:this.writeCounter})),d});return this.inflight.set(e,a),a}evictOverflow(){for(;this.store.size>this.maxEntries;){let e=this.store.keys().next().value;if(e===void 0)return;this.store.delete(e);}}};function at(t,e,n){return `${t}/${e}/${n}`}i(at,"schemaCacheKey");function bn(t){t!==void 0&&wn(t,{allowAnd:true});}i(bn,"assertPushableWhere");function Rn(t){if(t===void 0)return {};let e={};for(let n of wn(t,{allowAnd:true}))Yi(e,n.column,n.value);return e}i(Rn,"serializeWhere");function Yi(t,e,n){let r=t[e];r===void 0?t[e]=n:Array.isArray(r)?r.push(n):t[e]=[r,n];}i(Yi,"appendQuery");function wn(t,e){switch(t.op){case "eq":case "ne":case "gt":case "gte":case "lt":case "lte":case "like":return [{column:t.column,value:`${t.op}.${mr(t.value)}`}];case "in":{let n=t.values.map(s=>mr(s)),r=n.find(s=>s.includes(","));if(r!==void 0)throw gr(`IN filter values cannot contain commas because the live backend uses comma-separated IN lists (bad value: ${r})`,"filter_in_comma",t.column,"https://docs.axhub.dev/sdk/data#filter-in-comma");return [{column:t.column,value:`in.${n.join(",")}`}]}case "and":if(e.allowAnd)return t.clauses.flatMap(n=>wn(n,{allowAnd:false}));break;}throw gr(`Data where clause '${t.op}' cannot be pushed to the live backend; use top-level and(eq/ne/gt/gte/lt/lte/in/like) only`,"unsupported_filter",void 0,"https://docs.axhub.dev/sdk/data#pushable-filters")}i(wn,"collectPushableFilters");function mr(t){return t instanceof Date?t.toISOString():t===null?"null":typeof t=="string"||typeof t=="number"||typeof t=="boolean"||typeof t=="bigint"?String(t):JSON.stringify(t)}i(mr,"stringifyFilterValue");function gr(t,e,n,r){return new l({message:t,code:e,category:"validation",httpStatus:0,retryable:false,requestId:"",...n!==void 0?{resource:n}:{},...r!==void 0?{docUrl:r}:{}})}i(gr,"validationError");function re(t,e){switch(e.op){case "eq":return e.value===null||t[e.column]===null||t[e.column]===void 0?false:t[e.column]===e.value;case "ne":return e.value===null||t[e.column]===null||t[e.column]===void 0?false:t[e.column]!==e.value;case "gt":{let n=t[e.column];return n==null||e.value===null||e.value===void 0?false:ne(n,e.value)>0}case "gte":{let n=t[e.column];return n==null||e.value===null||e.value===void 0?false:ne(n,e.value)>=0}case "lt":{let n=t[e.column];return n==null||e.value===null||e.value===void 0?false:ne(n,e.value)<0}case "lte":{let n=t[e.column];return n==null||e.value===null||e.value===void 0?false:ne(n,e.value)<=0}case "in":return t[e.column]===null||t[e.column]===void 0?false:e.values.filter(n=>n!==null).includes(t[e.column]);case "like":return Ji(t[e.column],String(e.value));case "and":return e.clauses.every(n=>re(t,n));case "or":return e.clauses.some(n=>re(t,n));case "not":return !re(t,e.clause);case "raw":return true}}i(re,"evaluateWhere");function ne(t,e){return t==null||e===null||e===void 0?Number.NaN:typeof t=="number"&&typeof e=="number"?t-e:String(t).localeCompare(String(e))}i(ne,"compare");function Ji(t,e){if(typeof t!="string")return false;let n="^";for(let r=0;r<e.length;r++){let s=e[r]??"";s==="\\"?(r+=1,n+=fr(e[r]??"")):s==="%"?n+=".*":s==="_"?n+=".":n+=fr(s);}return new RegExp(`${n}$`).test(t)}i(Ji,"matchLike");function fr(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}i(fr,"escapeRegExp");function es(t,e){let n=wt(e);return n.length===0?[...t]:[...t].sort((r,s)=>{for(let o of n){let a=ne(r[o.field],s[o.field]);if(!(Number.isNaN(a)||a===0))return o.dir==="desc"?-a:a}return 0})}i(es,"sortRows");function yr(t,e){let n=es(t,e?.orderBy);if(e?.after!==void 0||e?.before!==void 0)throw new _({message:"after/before keyset cursors are not supported by AX Hub offset pagination",code:"legacy_cursor",category:"validation",httpStatus:0,retryable:false,requestId:""});let r=Math.min(100,Math.max(1,Math.trunc(e?.pageSize??e?.limit??20))),s=e?.cursor===void 0?1:ts(e.cursor),o=(s-1)*r,a=n.slice(o,o+r),d=o+r<n.length,p=s>1;return {items:a,nextCursor:d?String(s+1):null,firstCursor:p?String(s-1):null,hasNext:d,hasPrev:p}}i(yr,"paginateRows");function ts(t){if(t.startsWith("v1:")||t.startsWith("v2:"))throw new _({message:"keyset cursor tokens are not supported by AX Hub offset pagination",code:"legacy_cursor",category:"validation",httpStatus:0,retryable:false,requestId:""});let e=Number(t);if(!Number.isInteger(e)||e<1)throw new x({message:"Plain mock cursor must be a positive integer page",code:"invalid_cursor",category:"validation",httpStatus:0,retryable:false,requestId:"",docUrl:"https://docs.axhub.dev/errors/validation/invalid-cursor"});return e}i(ts,"parsePlainCursor");async function hr(t,e){N(e?.signal),ee(t.schema,e?.select),bn(e?.where);let n=t.store.list(t.key);e?.where&&(n=n.filter(o=>re(o,e.where)));let r=yr(n,e);return {items:Zt(r.items,e?.select),nextCursor:r.nextCursor,firstCursor:r.firstCursor,hasNext:r.hasNext,hasPrev:r.hasPrev,total:n.length,totalIsExact:true}}i(hr,"mockList");async function br(t,e){N(e?.signal),bn(e?.where);let n=t.store.list(t.key);return e?.where?n.filter(r=>re(r,e.where)).length:n.length}i(br,"mockCount");async function Rr(t,e,n){N(n?.signal),ee(t.schema,n?.select);let r=t.store.get(t.key,e);if(!r)throw new y({message:`Mock row not found: ${t.key}/${e}`,code:"row_not_found",category:"not_found",httpStatus:404,retryable:false,requestId:"",resource:`${t.key}/${e}`});return ot(r,n?.select)}i(Rr,"mockGet");async function wr(t,e,n){return N(n?.signal),O(t.schema,e,"insert"),t.store.insert(t.key,e)}i(wr,"mockInsert");async function vr(t,e,n){N(n?.signal);for(let s of e)O(t.schema,s,"insert");let r=e.map(s=>t.store.insert(t.key,s));return {items:r,count:r.length}}i(vr,"mockInsertMany");async function _r(t,e,n,r){return N(r?.signal),O(t.schema,n,"update"),t.store.update(t.key,e,n)}i(_r,"mockUpdate");async function xr(t,e,n){N(n?.signal),t.store.delete(t.key,e);}i(xr,"mockDelete");function N(t){if(t?.aborted)throw new b({message:"Mock operation aborted",code:"aborted",category:"abort",httpStatus:0,retryable:false,requestId:""})}i(N,"assertNotAborted");var ut=class{constructor(e,n){this.http=e;this.schemaCache=n?.schemaCache instanceof te?n.schemaCache:new te(n?.schemaCache),this.mockStore=n?.mockStore;}http;static{i(this,"DataClient");}schemaCache;mockStore;table(e,n,r){let s=typeof r=="string"?void 0:r,o=typeof r=="string"?r:r.table;return new ie(this.http,e,n,o,s,this.mockStore?{store:this.mockStore,key:at(e,n,o),schema:s}:void 0)}scoped(e){return new vn(this,e)}async discover(e,n,r,s){let o=at(e,n,r);if(this.mockStore){let d=this.mockStore.schema(o)??rs(r,this.mockStore.list(o));return new ie(this.http,e,n,d.table,d,{store:this.mockStore,key:o,schema:d})}let a=await this.schemaCache.getOrSet(o,()=>lr(this.http,e,n,r,s),{fresh:s?.fresh,ttlMs:s?.ttlMs});return new ie(this.http,e,n,a.table,a)}invalidateSchema(e,n,r){if(e!==void 0&&n!==void 0&&r!==void 0){this.schemaCache.invalidate(at(e,n,r));return}this.schemaCache.invalidate();}},vn=class{constructor(e,n){this.data=e;this.tenantSlug=n;}data;tenantSlug;static{i(this,"TenantDataFactory");}app(e){return new _n(this.data,this.tenantSlug,e)}},_n=class{constructor(e,n,r){this.data=e;this.tenantSlug=n;this.appSlug=r;}data;tenantSlug;appSlug;static{i(this,"AppDataFactory");}table(e){return this.data.table(this.tenantSlug,this.appSlug,e)}discover(e,n){return this.data.discover(this.tenantSlug,this.appSlug,e,n)}invalidateSchema(e){e===void 0?this.data.invalidateSchema():this.data.invalidateSchema(this.tenantSlug,this.appSlug,e);}},ie=class{constructor(e,n,r,s,o,a){this.http=e;this.tenantSlug=n;this.appSlug=r;this.tableName=s;this.schema=o;this.mockRuntime=a;}http;tenantSlug;appSlug;tableName;schema;mockRuntime;static{i(this,"DataTableClient");}path(e){let n=`/data/${c(this.tenantSlug)}/${c(this.appSlug)}/${c(this.tableName)}`;return e===void 0?n:`${n}/${c(e)}`}async list(e){if(this.mockRuntime)return hr(this.mockRuntime,e);ee(this.schema,e?.select),ss(e,this.tableName);let n=is(e?.cursor,e?.page,this.tableName),r=os(e?.pageSize??e?.limit);Cr(e?.where,this.tableName,"list");let s={...Rn(e?.where)};r!==void 0&&(s.per_page=r),n!==1&&(s.page=n);let o=Bn(e?.orderBy);o&&(s.sort=o);let a=hn(e?.select);a!==void 0&&(s._select=a);let d=await this.http.request("GET",this.path(),u({ring:"data",query:s},e)),p=Zt(d.items,e?.select),I=d.page??n,E=d.has_more??false,ft=I>1;return {items:p,nextCursor:E?String(I+1):null,firstCursor:ft?String(I-1):null,hasNext:E,hasPrev:ft,totalIsExact:false}}listAll(e){return k(n=>this.list({...e,...n}),e)}async count(e){return this.mockRuntime?br(this.mockRuntime,e):(Cr(e?.where,this.tableName,"count"),(await this.http.request("GET",`${this.path()}/_count`,u({ring:"data",query:Rn(e?.where)},e))).count)}async get(e,n){if(this.mockRuntime)return Rr(this.mockRuntime,e,n);ee(this.schema,n?.select);let r=hn(n?.select),s=await this.http.request("GET",this.path(e),u({ring:"data",query:r===void 0?void 0:{_select:r}},n));return ot(s,n?.select)}async insert(e,n){return this.mockRuntime?wr(this.mockRuntime,e,n):(O(this.schema,e,"insert"),this.http.request("POST",this.path(),u({ring:"data",body:e,idempotent:false},n)))}async insertMany(e,n){if(this.mockRuntime)return vr(this.mockRuntime,e,n);for(let o of e)O(this.schema,o,"insert");let r=[],s=n?.signal;for(let o of e){if(s?.aborted)throw new b({message:`insertMany aborted after ${r.length} of ${e.length} rows`,code:"aborted",category:"abort",httpStatus:0,retryable:false,requestId:"",resource:this.tableName});r.push(await this.insert(o,n));}return {items:r,count:r.length}}async update(e,n,r){return this.mockRuntime?_r(this.mockRuntime,e,n,r):(O(this.schema,n,"update"),this.http.request("PATCH",this.path(e),u({ring:"data",body:n,idempotent:false},r)))}async delete(e,n){if(this.mockRuntime)return xr(this.mockRuntime,e,n);await this.http.request("DELETE",this.path(e),u({ring:"data",idempotent:true},n));}},ns=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function rs(t,e){let n={},r=e[0]??{id:"mock_id"};for(let[o,a]of Object.entries(r))typeof a=="number"?n[o]="number":typeof a=="boolean"?n[o]="boolean":a!==null&&typeof a=="object"?n[o]="json":typeof a=="string"&&ns.test(a)||o==="id"?n[o]="uuid":n[o]="string";let s=Object.fromEntries(Object.entries(n).map(([o,a])=>[o,{table:t,name:o,def:a}]));return {table:t,columns:n,cols:s}}i(rs,"inferSchemaFromRows");function is(t,e,n){if(t!==void 0)return as(t,n),Number(t);if(e===void 0)return 1;if(!Number.isInteger(e)||e<1)throw us("page must be a positive integer",n);return e}i(is,"resolveOffsetPage");function Cr(t,e,n){if(t===void 0)throw new l({message:`AxHub data ${n} requires at least one WHERE filter (the backend rejects unfiltered scans). Pass \`where: ...\`.`,code:"where_required",category:"validation",httpStatus:0,retryable:false,requestId:"",resource:e,docUrl:"https://docs.axhub.dev/sdk/data#filters"})}i(Cr,"requireWhereFilter");function ss(t,e){let n=t;if(n?.after!==void 0||n?.before!==void 0||n?.direction!==void 0)throw new _({message:"after/before keyset cursors are not supported by the live AX Hub data API; use cursor/page numeric offset pagination",code:"legacy_cursor",category:"validation",httpStatus:0,retryable:false,requestId:"",resource:e,docUrl:"https://docs.axhub.dev/errors/validation/legacy-cursor"})}i(ss,"rejectLegacyPageOptions");function os(t){if(t!==void 0)return Number.isFinite(t)?Math.min(100,Math.max(1,Math.trunc(t))):100}i(os,"clampPerPage");function as(t,e){if(t.length>Ye)throw new x({message:`Cursor token exceeds maximum size (${Ye} chars)`,code:"invalid_cursor",category:"validation",httpStatus:0,retryable:false,requestId:"",resource:e,docUrl:"https://docs.axhub.dev/errors/validation/invalid-cursor"});if(t.startsWith("v1:"))throw new _({message:"Legacy v1: cursor token is not compatible with AX Hub offset-only pagination; restart pagination without cursor",code:"legacy_cursor",category:"validation",httpStatus:0,retryable:false,requestId:"",resource:e,docUrl:"https://docs.axhub.dev/errors/validation/legacy-cursor"});if(jn(t))throw new _({message:"v2 keyset cursors are not supported by the live AX Hub data API; restart pagination and use the numeric cursor returned by list()",code:"legacy_cursor",category:"validation",httpStatus:0,retryable:false,requestId:"",resource:e,docUrl:"https://docs.axhub.dev/errors/validation/legacy-cursor"});let n=Number(t);if(!Number.isInteger(n)||n<1)throw new x({message:"Plain cursor must be a positive integer page or a v2: keyset token",code:"invalid_cursor",category:"validation",httpStatus:0,retryable:false,requestId:"",resource:e,docUrl:"https://docs.axhub.dev/errors/validation/invalid-cursor"})}i(as,"validatePlainCursor");function us(t,e){return new x({message:t,code:"invalid_cursor",category:"validation",httpStatus:0,retryable:false,requestId:"",resource:e,docUrl:"https://docs.axhub.dev/errors/validation/invalid-cursor"})}i(us,"invalidCursor");function xn(t){return {id:t.id,appId:t.app_id,commitSha:t.commit_sha,status:t.status,currentStage:t.current_stage??null,imageUri:t.image_uri??null,triggerSource:t.trigger_source,startedAt:t.started_at??null,completedAt:t.completed_at??null,failureReason:t.failure_reason??null}}i(xn,"toDeployment");var ct=class{constructor(e,n){this.http=e;this.defaultTenantId=n;}http;defaultTenantId;static{i(this,"DeploymentsClient");}async create(e,n){let r={};n?.commitSha!==void 0&&(r.commit_sha=n.commitSha),n?.forceRebuild!==void 0&&(r.force_rebuild=n.forceRebuild);let s=await this.http.request("POST",`/api/v1/apps/${encodeURIComponent(e)}/deployments`,{ring:"admin",body:r,idempotent:false});return xn(s)}async list(e,n){let r={};n?.pageSize!==void 0&&(r.per_page=n.pageSize),n?.cursor!==void 0&&(r.page=n.cursor);let s=await this.http.request("GET",`/api/v1/apps/${encodeURIComponent(e)}/deployments`,{ring:"admin",query:r});return {items:s.items.map(xn),nextCursor:s.next_cursor??(s.has_more??(s.page??Number(r.page??1))*(s.per_page??Number(r.per_page??20))<(s.total??0)?String((s.page??Number(r.page??1))+1):null),total:s.total}}listAll(e,n){return k(r=>this.list(e,r),n)}async get(e,n){let r=await this.http.request("GET",`/api/v1/apps/${encodeURIComponent(e)}/deployments/${encodeURIComponent(n)}`,{ring:"admin"});return xn(r)}async cancel(e,n){await this.http.request("POST",`/api/v1/apps/${encodeURIComponent(e)}/deployments/${encodeURIComponent(n)}/cancel`,{ring:"admin",body:{},idempotent:true});}async rollback(e,n){await this.http.request("POST",`/api/v1/apps/${encodeURIComponent(e)}/deployments/${encodeURIComponent(n)}/rollback`,{ring:"admin",body:{},idempotent:false});}async logs(e,n){let r={};n?.direction!==void 0&&(r.direction=n.direction),n?.cursor!==void 0&&(r.cursor=n.cursor),n?.since!==void 0&&(r.since=n.since),n?.until!==void 0&&(r.until=n.until),n?.limit!==void 0&&(r.limit=n.limit);let s=await this.http.request("GET",`/api/v1/apps/${encodeURIComponent(e)}/logs`,{ring:"admin",query:r});return {lines:(s.lines??[]).map(o=>({ts:o.ts??"",container:o.container??"",message:o.message??"",insertId:o.insert_id??""})),nextCursor:s.next_cursor??"",hasMore:s.has_more??false}}requireTenantId(e,n){if(this.defaultTenantId===void 0)throw new w({message:`deployments.${e} requires a tenant UUID: set defaultTenantId on AxHubClient. Backend route ${n} takes a tenant UUID, not a slug.`,code:"tenant_id_required",category:"tenant_id_required",httpStatus:0,retryable:false,requestId:"",fields:[{name:"tenantId",code:"required"}]});return this.defaultTenantId}async startBootstrap(e){let n=this.requireTenantId("startBootstrap","POST /api/v1/tenants/{tenantID}/app-bootstraps"),r={name:e.name,slug:e.slug,subdomain:e.subdomain,template_id:e.templateId,github_installation_id:e.githubInstallationId,github_owner:e.githubOwner,repo_name:e.repoName};e.repoPrivate!==void 0&&(r.repo_private=e.repoPrivate);let s=await this.http.request("POST",`/api/v1/tenants/${encodeURIComponent(n)}/app-bootstraps`,{ring:"admin",body:r,idempotent:false});return {bootstrapId:s.bootstrap_id,statusUrl:s.status_url}}async bootstrapStatus(e){let n=this.requireTenantId("bootstrapStatus","GET /api/v1/tenants/{tenantID}/app-bootstraps/{bootstrapID}"),r=await this.http.request("GET",`/api/v1/tenants/${encodeURIComponent(n)}/app-bootstraps/${encodeURIComponent(e)}`,{ring:"admin"}),s={id:r.id??e,stage:r.stage??"",status:r.status??""};return r.app_id&&(s.appId=r.app_id),r.deployment_id&&(s.deploymentId=r.deployment_id),r.repo_full_name&&(s.repoFullName=r.repo_full_name),r.error_code&&(s.errorCode=r.error_code),r.error_message&&(s.errorMessage=r.error_message),s}async githubAccounts(){return ((await this.http.request("GET","/api/v1/github/accounts",{ring:"admin"})).accounts??[]).map(n=>{let r={login:n.login??"",type:n.type??"",installed:n.installed??false};return n.installation_id!==void 0&&(r.installationId=n.installation_id),n.avatar_url!==void 0&&(r.avatarUrl=n.avatar_url),n.install_url!==void 0&&(r.installUrl=n.install_url),r})}async githubRepos(e,n){let r={};n?.page!==void 0&&(r.page=n.page),n?.perPage!==void 0&&(r.per_page=n.perPage);let s=await this.http.request("GET",`/api/v1/github/installations/${encodeURIComponent(String(e))}/repositories`,{ring:"admin",query:r});return {repositories:(s.repositories??[]).map(o=>({id:o.id??0,name:o.name??"",fullName:o.full_name??"",private:o.private??false,defaultBranch:o.default_branch??""})),totalCount:s.total_count??0}}};var dt=class{constructor(e,n){this.http=e;this.tenantResolver=n;}http;tenantResolver;static{i(this,"GatewayClient");}scoped(e){return new Yt(this.http,e,this.tenantResolver)}async engines(e){return (await this.http.request("GET","/api/v1/engines",u({ring:"admin"},e))??[]).map(r=>({engine:r.engine??"",kind:r.kind??"",displayName:r.display_name??"",supportedActions:r.supported_actions??[],allowedEffects:r.allowed_effects??{}}))}},Yt=class{static{i(this,"TenantGatewayClient");}query;catalog;constructor(e,n,r){this.query=new Cn(e,n,r),this.catalog=new Jt(e,n,r);}};function Ir(t,e){return new A({message:e,code:"required",category:"validation",httpStatus:0,retryable:false,requestId:"",fields:[{name:t,code:"required"}]})}i(Ir,"required");function Ar(t){return (t??[]).map(e=>({name:e.name,dataType:e.data_type}))}i(Ar,"mapColumns");function kr(t,e){return (e??[]).map(n=>{let r={};return t.forEach((s,o)=>{r[s.name]=n[o]??null;}),r})}i(kr,"zipRows");var Cn=class{constructor(e,n,r){this.http=e;this.tenantIdOrSlug=n;this.tenantResolver=r;}http;tenantIdOrSlug;tenantResolver;static{i(this,"GatewayQueryClient");}async run(e,n){try{let r=e.connectorId??e.resourceId;if(!r)throw Ir("connectorId","gateway.query.run requires connectorId (or legacy resourceId)");if(!e.path)throw Ir("path","gateway.query.run requires resource path");let s=await this.http.request("POST",await this.base(),u({ring:"admin",body:{connector_id:r,path:e.path,sql:e.sql,params:e.params,row_limit:e.rowLimit},idempotent:!0},n)),o=Ar(s.columns),a=kr(o,s.rows);return {allowed:s.allowed??!0,...s.deny_reason?{denyReason:s.deny_reason}:{},columns:o,rows:a,rowCount:a.length,...s.matched_policies?{matchedPolicies:s.matched_policies}:{}}}catch(r){throw typeof r=="object"&&r!==null&&"httpStatus"in r&&r.httpStatus===401?new M({message:"Gateway pool credentials are stale after refresh retry",code:"pool_stale",category:"unauthenticated",httpStatus:401,retryable:false,requestId:"requestId"in r?String(r.requestId):""}):r}}async base(){let e=this.tenantResolver?await this.tenantResolver.resolveTenantId(this.tenantIdOrSlug):this.tenantIdOrSlug;return `/api/v1/tenants/${c(e)}/gateway/query`}};function Tr(t){return {allowed:t.allowed,...t.deny_reason?{denyReason:t.deny_reason}:{},...t.row_filter?{rowFilter:t.row_filter}:{},...t.mask?{mask:t.mask}:{},...t.input_schema!==void 0?{inputSchema:t.input_schema}:{},...t.result_schema!==void 0?{resultSchema:t.result_schema}:{}}}i(Tr,"mapReadList");function cs(t){return {...Tr(t),...t.allowed_columns?{allowedColumns:t.allowed_columns}:{},...t.column_masks?{columnMasks:t.column_masks}:{}}}i(cs,"mapReadDetail");function Pr(t){return {id:t.id,connector:t.connector,connectorId:t.connector_id,path:t.path,url:t.url,...t.kind?{kind:t.kind}:{},type:t.type,name:t.name,attributes:t.attributes??{},tags:t.tags??[],permissions:{read:Tr(t.permissions.read)}}}i(Pr,"mapView");function ds(t){return {id:t.id,connector:t.connector,connectorId:t.connector_id,path:t.path,url:t.url,...t.kind?{kind:t.kind}:{},type:t.type,name:t.name,attributes:t.attributes??{},tags:t.tags??[],ancestors:t.ancestors??[],children:(t.children??[]).map(Pr),permissions:{read:cs(t.permissions.read)}}}i(ds,"mapDetail");function Sr(t){return t.split("/").map(e=>c(e)).join("/")}i(Sr,"encodeResourcePath");var Jt=class{constructor(e,n,r){this.http=e;this.tenantIdOrSlug=n;this.tenantResolver=r;}http;tenantIdOrSlug;tenantResolver;static{i(this,"GatewayCatalogClient");}async listKinds(e){return ((await this.http.request("GET","/api/v1/catalog/kinds",u({ring:"admin"},e))).items??[]).map(r=>({kind:r.kind,engine:r.engine,displayName:r.display_name,invokable:r.invokable,actions:Object.fromEntries(Object.entries(r.actions??{}).map(([s,o])=>[s,{allowedEffects:o.allowed_effects??[],...o.input_schema!==void 0?{inputSchema:o.input_schema}:{},...o.result_schema!==void 0?{resultSchema:o.result_schema}:{}}]))}))}async listConnectors(e){return ((await this.http.request("GET",`${await this.base()}/connectors`,u({ring:"admin"},e))).items??[]).map(r=>({id:r.id,name:r.name,engine:r.engine,url:r.url,...r.description?{description:r.description}:{}}))}async listResources(e,n){let r={};return e?.search&&(r.search=e.search),e?.kind&&(r.kind=e.kind),e?.connector&&(r.connector=e.connector),e?.connectorId&&(r.connector_id=e.connectorId),e?.limit!==void 0&&(r.limit=e.limit),((await this.http.request("GET",`${await this.base()}/resources`,u({ring:"admin",query:r},n))).items??[]).map(Pr)}async getResource(e,n,r){return this.http.request("GET",`${await this.base()}/resources/${c(e)}/${Sr(n)}`,u({ring:"admin"},r)).then(ds)}async invoke(e,n,r,s){let o=await this.http.request("POST",`${await this.base()}/resources/${c(e)}/${Sr(n)}:read`,u({ring:"admin",body:j({sql:r.sql,params:r.params,row_limit:r.rowLimit}),idempotent:true},s)),a=Ar(o.result?.columns),d=kr(a,o.result?.rows);return {allowed:o.allowed??false,action:o.action,...o.deny_reason?{denyReason:o.deny_reason}:{},columns:a,rows:d,rowCount:d.length,...o.matched_policies?{matchedPolicies:o.matched_policies}:{}}}async hasAccess(e,n,r){try{return await this.getResource(e,n,r),!0}catch(s){if(s instanceof y)return false;throw s}}async base(){let e=this.tenantResolver?await this.tenantResolver.resolveTenantId(this.tenantIdOrSlug):this.tenantIdOrSlug;return `/api/v1/tenants/${c(e)}/catalog`}async listResourcesWithDetail(e,n){let r=await this.listResources(e,n);return Promise.all(r.map(s=>this.getResource(s.connector,s.path,n)))}};function ls(t){return t.allowed===true}i(ls,"isAllowed");function Er(t){let e=t.denyReason??"";return t.allowed===false&&(e.startsWith("SQL \uD615\uC2DD \uC624\uB958:")||e.includes("safesql:"))}i(Er,"isSqlFormatError");function ps(t){return t.allowed===false&&!Er(t)}i(ps,"isPolicyDeny");function ms(t){return t.permissions.read.allowedColumns??[]}i(ms,"getAccessibleColumns");function gs(t,e){return t.permissions.read.columnMasks?.[e]??null}i(gs,"getMaskHint");function fs(t){let e=t.split("/").filter(Boolean);return e[e.length-1]??""}i(fs,"tableFromPath");function en(t){let e={id:t.id,appId:t.app_id,requesterId:t.requester_id,status:t.status,createdAt:t.created_at,updatedAt:t.updated_at};t.reason!==void 0&&(e.reason=t.reason),t.reviewer_id!==void 0&&(e.reviewerId=t.reviewer_id);let n=t.reviewer_comment??t.review_comment;return n!==void 0&&(e.reviewerComment=n),e}i(en,"toPublicationRequest");var lt=class{constructor(e){this.http=e;}http;static{i(this,"PublicationRequestsClient");}async get(e){let n=await this.http.request("GET",`/api/v1/review-requests/${encodeURIComponent(e)}`,{ring:"admin"});return en(n)}async approve(e,n){return this.settle(e,"approve",n)}async reject(e,n){return this.settle(e,"reject",n)}async settle(e,n,r){let s={};r?.comment!==void 0&&(s.comment=r.comment);let o=await this.http.request("POST",`/api/v1/review-requests/${encodeURIComponent(e)}/${n}`,{ring:"admin",body:s,idempotent:false});return en(o)}async listPending(e,n){if(!e||e.trim()==="")throw new A({message:"tenantId is required: GET /api/v1/review-requests/pending needs a tenant_id query parameter",code:"required",category:"validation",httpStatus:0,retryable:false,requestId:"",fields:[{name:"tenantId",code:"required"}]});let r={tenant_id:e};n?.pageSize!==void 0&&(r.per_page=n.pageSize),n?.cursor!==void 0&&(r.page=n.cursor);let s=await this.http.request("GET","/api/v1/review-requests/pending",{ring:"admin",query:r});return {items:s.items.map(en),nextCursor:s.next_cursor,total:s.total}}async history(e,n){if(!e||e.trim()==="")throw new A({message:"tenantId is required: GET /api/v1/review-requests/history needs a tenant_id query parameter",code:"required",category:"validation",httpStatus:0,retryable:false,requestId:"",fields:[{name:"tenantId",code:"required"}]});let r={tenant_id:e};n?.pageSize!==void 0&&(r.per_page=n.pageSize),n?.cursor!==void 0&&(r.page=n.cursor);let s=await this.http.request("GET","/api/v1/review-requests/history",{ring:"admin",query:r});return {items:s.items.map(en),nextCursor:s.next_cursor,total:s.total}}};function ys(t){return {...t,id:String(t.id),slug:String(t.slug),name:String(t.name),createdAt:t.created_at??t.createdAt,updatedAt:t.updated_at??t.updatedAt}}i(ys,"toTenant");var pt=class{constructor(e){this.http=e;}http;static{i(this,"TenantsClient");}async get(e,n){let r=await this.http.request("GET",`/api/v1/tenants/${c(e)}`,u({ring:"admin"},n));return ys(r)}};var mt=class{constructor(e){this.http=e;}http;static{i(this,"ConfigClient");}async public(e){let n=await this.http.request("GET","/config/public",u({ring:"public"},e));return {...n,baseDomain:n.base_domain??""}}};var gt=class{static{i(this,"MockStore");}initialFixtures;tables=new Map;schemas;nextId=1;constructor(e,n){this.initialFixtures=hs(e??{}),this.schemas=n??{},this.reset();}keys(){return [...this.tables.keys()]}schema(e){return this.schemas[e]}list(e){return [...this.tables.get(e)?.values()??[]].map(n=>({...n}))}get(e,n){let r=this.tables.get(e)?.get(n);return r?{...r}:null}insert(e,n){let r=typeof n.id=="string"?n.id:`mock_${this.nextId++}`,s=this.ensureTable(e);if(s.has(r))throw new f({message:`Mock row already exists: ${e}/${r}`,code:"duplicate_key",category:"conflict",httpStatus:409,retryable:false,requestId:"",resource:`${e}/${r}`});let a={created_at:new Date().toISOString(),...n,id:r};return s.set(r,a),{...a}}update(e,n,r){let s=this.ensureTable(e),o=s.get(n);if(!o)throw new y({message:`Mock row not found: ${e}/${n}`,code:"row_not_found",category:"not_found",httpStatus:404,retryable:false,requestId:"",resource:`${e}/${n}`});let a={...o,...r,id:n,updated_at:new Date().toISOString()};return s.set(n,a),{...a}}delete(e,n){let r=this.tables.get(e);if(!r||!r.has(n))throw new y({message:`Mock row not found: ${e}/${n}`,code:"row_not_found",category:"not_found",httpStatus:404,retryable:false,requestId:"",resource:`${e}/${n}`});r.delete(n);}reset(e){if(e!==void 0){this.tables.set(e,qr(this.initialFixtures[e]??[]));return}this.tables=new Map;for(let[n,r]of Object.entries(this.initialFixtures))this.tables.set(n,qr(r));}ensureTable(e){let n=this.tables.get(e);return n||(n=new Map,this.tables.set(e,n)),n}};function qr(t){let e=new Map;for(let n of t){let r=typeof n.id=="string"?n.id:`mock_${e.size+1}`;e.set(r,{...n,id:r});}return e}i(qr,"rowsToMap");function hs(t){return Object.fromEntries(Object.entries(t).map(([e,n])=>[e,n.map(r=>({...r}))]))}i(hs,"cloneFixtures");function In(t){if(t.mode==="mock")return Or(),new gt(t.fixtures,t.schemas)}i(In,"createMockStore");var bs=new Set(["1","true","yes","on"]);function Rs(t){return t?.trim().toLowerCase()==="production"}i(Rs,"isProductionEnv");function ws(t){return t===void 0?false:bs.has(t.trim().toLowerCase())}i(ws,"isTruthyOptIn");function Or(){if(Rs(process.env.NODE_ENV)){if(ws(process.env.AX_HUB_ALLOW_MOCK_IN_PROD)){console.warn("[@ax-hub/sdk] WARNING: mock mode active in production (AX_HUB_ALLOW_MOCK_IN_PROD opt-in).");return}throw new Ge({message:"Mock mode active in production without explicit opt-in",code:"mock_in_production",category:"configuration",httpStatus:0,retryable:false,requestId:"",docUrl:"https://docs.axhub.dev/errors/mock-in-production"})}}i(Or,"assertMockModeAllowed");var Dr="https://api.axhub.ai";function vs(t){return typeof t=="object"&&t!==null&&"__sharedHttp"in t}i(vs,"isInternal");var Sn=class t{static{i(this,"AxHubClient");}http;defaultTenantSlug;defaultTenantId;logger;schemaCacheOptions;mock;tenantResolver;n;r;i;s;o;a;u;c;d;l;constructor(e){if(vs(e)){this.http=e.__sharedHttp,this.defaultTenantSlug=e.defaultTenantSlug,this.defaultTenantId=e.defaultTenantId,this.logger=e.logger,this.schemaCacheOptions=e.schemaCacheOptions,this.mock=e.mockStore,this.tenantResolver=e.tenantResolver??new st(this.http);return}if(e.token!==void 0&&e.tokenType===void 0)throw new TypeError('AxHubClient requires tokenType when token is set ("pat" | "jwt")');let n=e.token!==void 0&&e.tokenType!==void 0?new Xe({token:e.token,tokenType:e.tokenType,onRefresh:e.onRefresh}):new Ze;this.http=new Rt({baseUrl:e.baseUrl??Dr,auth:n,fetch:e.fetch,logger:e.logger,debug:e.debug,timeoutMs:e.timeoutMs,idempotencyKey:e.idempotencyKey,retryPolicy:e.retryPolicy,rateLimitStrategy:e.rateLimitStrategy}),this.defaultTenantSlug=e.defaultTenantSlug,this.defaultTenantId=e.defaultTenantId,this.logger=e.logger??bt,this.schemaCacheOptions=e.schemaCache,this.mock=In(e),this.tenantResolver=new st(this.http);}resolveTenantSlug(e){let n=e??this.defaultTenantSlug;if(!n)throw new $e({message:"tenantSlug is required: set defaultTenantSlug on AxHubClient or pass tenantSlug per-call",code:"tenant_slug_required",category:"tenant_slug_required",httpStatus:0,retryable:false,requestId:""});return n}get apps(){return this.n||(this.n=new Je(this.http,this.defaultTenantSlug,this.defaultTenantId,this.tenantResolver)),this.n}get data(){return this.r||(this.r=new ut(this.http,{schemaCache:this.schemaCacheOptions,mockStore:this.mock})),this.r}get deployments(){return this.i||(this.i=new ct(this.http,this.defaultTenantId)),this.i}get config(){return this.c||(this.c=new mt(this.http)),this.c}get gateway(){return this.s||(this.s=new dt(this.http,this.tenantResolver)),this.s}get identity(){return this.o||(this.o=new it(this.http,this.defaultTenantSlug)),this.o}get tenants(){return this.u||(this.u=new pt(this.http)),this.u}get cost(){return this.d||(this.d=new tt(this.http,this.defaultTenantId,this.tenantResolver)),this.d}get inviteLinks(){return this.l||(this.l=new nt(this.http,this.tenantResolver)),this.l}get publicationRequests(){return this.a||(this.a=new lt(this.http)),this.a}withTenant(e){return new t({__sharedHttp:this.http,defaultTenantSlug:e,defaultTenantId:e===this.defaultTenantSlug?this.defaultTenantId:void 0,logger:this.logger,schemaCacheOptions:this.schemaCacheOptions,mockStore:this.mock,tenantResolver:this.tenantResolver})}tenant(e){return new rt(e,this.withTenant(e),this,this.tenantResolver)}};
2
+ export{b as AbortError,X as AccessDeniedError,ve as AlreadyAccessedError,Re as AlreadyActiveError,ue as AlreadyDeletedError,we as AlreadyInactiveError,ae as AlreadyMemberError,he as AlreadyRevokedError,be as AlreadySettledError,Ht as AppScopedClient,jt as AppScopedDataClient,Ue as AppUnavailableError,Je as AppsClient,B as AuthorizationPendingError,Sn as AxHubClient,m as AxHubError,qe as BadRequestError,mt as ConfigClient,z as ConfigurationError,f as ConflictError,tt as CostClient,Dr as DEFAULT_BASE_URL,ut as DataClient,ie as DataTableClient,V as DecodeError,ct as DeploymentsClient,rn as DeviceFlowDeniedError,sn as DeviceFlowTimeoutError,Ae as DomainTakenError,ke as DuplicateError,Ee as EmptyError,Z as ExpiredTokenError,me as ForbiddenError,Jt as GatewayCatalogClient,dt as GatewayClient,it as IdentityClient,zt as IdentityDeviceCodeClient,Vt as IdentityInvitationsClient,J as IdentityMeClient,Qt as IdentityOAuthClient,Kt as IdentityOIDCClient,Nt as IdentityPATClient,Wt as IdentitySystemOAuthClientsClient,L as InternalServerError,G as IntrospectFailedError,je as InvalidClientError,x as InvalidCursorError,Pe as InvalidExpiryError,Be as InvalidGrantError,K as InvalidPathError,Fe as InvalidRequestError,Ne as InvalidScopeError,Ie as InvalidStateTransitionError,He as InvalidTargetError,Qe as InvalidTokenError,Te as InvalidValueError,fe as InvitationExpiredError,nt as InviteLinksClient,xe as LastAdminError,_ as LegacyCursorError,ye as LinkInvalidError,Ge as MockInProductionError,gt as MockStore,Le as NetworkError,Ze as NoAuth,pe as NotAdminError,De as NotAllowedError,_e as NotDeletedError,y as NotFoundError,Oe as NotMemberError,h as OAuthError,ze as OAuthServerError,Ce as PendingExistsError,ge as PermanentlyDeletedError,P as PermissionDeniedError,M as PoolStaleError,se as PreconditionFailedError,lt as PublicationRequestsClient,U as RateLimitedError,A as RequiredError,W as ScanLimitExceededError,te as SchemaCache,Se as SchemaNameTakenError,H as SlowDownError,oe as SlugTakenError,Xe as StaticTokenAuth,yt as StreamConsumedError,$ as TableNotFoundError,We as TemporarilyUnavailableError,F as TenantCostClient,Yt as TenantGatewayClient,w as TenantIdRequiredError,Y as TenantInviteLinksClient,Bt as TenantScopedAppsClient,rt as TenantScopedClient,$e as TenantSlugRequiredError,pt as TenantsClient,Me as TimeoutError,de as TokenExpiredError,le as TokenInvalidError,ce as TokenMissingError,T as UnauthenticatedError,Ve as UnauthorizedClientError,Q as UnavailableError,Ke as UnsupportedGrantTypeError,l as ValidationError,nn as WebhookVerificationError,Mi as and,Hr as asAppId,Qr as asAppSlug,jr as asDeploymentId,Vr as asPatId,zr as asRequestId,Fr as asTenantId,Nr as asTenantSlug,Kr as asUserId,Or as assertMockModeAllowed,In as createMockStore,si as cursorFromRow,ri as decodeCursor,fn as defineSchema,Gn as encodeCursor,Xt as escapeLike,An as formatErrorMessage,ms as getAccessibleColumns,gs as getMaskHint,Xr as id,ls as isAllowed,ps as isPolicyDeny,Er as isSqlFormatError,Gi as not,$i as or,ii as orderByFingerprint,an as parseRetryAfter,Li as raw,at as schemaCacheKey,ci as signWebhook,fs as tableFromPath,di as verifyWebhook,Bi as where};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ax-hub/sdk",
3
- "version": "2.0.0",
3
+ "version": "2.1.1",
4
4
  "description": "agent-first Node.js SDK for AX Hub. Designed for Claude, Codex, and other coding agents.",
5
5
  "keywords": [
6
6
  "ax-hub",