@getdevintern/pm 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js ADDED
@@ -0,0 +1,277 @@
1
+ #!/usr/bin/env bun
2
+ // @bun
3
+ var GX=Object.create;var{getPrototypeOf:zX,defineProperty:m1,getOwnPropertyNames:HX}=Object;var WX=Object.prototype.hasOwnProperty;var qX=(Z,Q,X)=>{X=Z!=null?GX(zX(Z)):{};let J=Q||!Z||!Z.__esModule?m1(X,"default",{value:Z,enumerable:!0}):X;for(let G of HX(Z))if(!WX.call(J,G))m1(J,G,{get:()=>Z[G],enumerable:!0});return J};var OX=(Z,Q)=>()=>(Q||Z((Q={exports:{}}).exports,Q),Q.exports);var B8=OX((nJ,yZ)=>{var u1,d1,c1,l1,p1,i1,n1,a1,s1,o1,t1,r1,e1,fZ,xQ,Z8,Q8,X8,y0,J8,Y8,G8,z8,H8,W8,q8,O8,M8,bZ,U8,K8,$8;(function(Z){var Q=typeof global==="object"?global:typeof self==="object"?self:typeof this==="object"?this:{};if(typeof define==="function"&&define.amd)define("tslib",["exports"],function(J){Z(X(Q,X(J)))});else if(typeof yZ==="object"&&typeof nJ==="object")Z(X(Q,X(nJ)));else Z(X(Q));function X(J,G){if(J!==Q)if(typeof Object.create==="function")Object.defineProperty(J,"__esModule",{value:!0});else J.__esModule=!0;return function(Y,z){return J[Y]=G?G(Y,z):z}}})(function(Z){var Q=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(Y,z){Y.__proto__=z}||function(Y,z){for(var H in z)if(Object.prototype.hasOwnProperty.call(z,H))Y[H]=z[H]};u1=function(Y,z){if(typeof z!=="function"&&z!==null)throw new TypeError("Class extends value "+String(z)+" is not a constructor or null");Q(Y,z);function H(){this.constructor=Y}Y.prototype=z===null?Object.create(z):(H.prototype=z.prototype,new H)},d1=Object.assign||function(Y){for(var z,H=1,W=arguments.length;H<W;H++){z=arguments[H];for(var q in z)if(Object.prototype.hasOwnProperty.call(z,q))Y[q]=z[q]}return Y},c1=function(Y,z){var H={};for(var W in Y)if(Object.prototype.hasOwnProperty.call(Y,W)&&z.indexOf(W)<0)H[W]=Y[W];if(Y!=null&&typeof Object.getOwnPropertySymbols==="function"){for(var q=0,W=Object.getOwnPropertySymbols(Y);q<W.length;q++)if(z.indexOf(W[q])<0&&Object.prototype.propertyIsEnumerable.call(Y,W[q]))H[W[q]]=Y[W[q]]}return H},l1=function(Y,z,H,W){var q=arguments.length,O=q<3?z:W===null?W=Object.getOwnPropertyDescriptor(z,H):W,M;if(typeof Reflect==="object"&&typeof Reflect.decorate==="function")O=Reflect.decorate(Y,z,H,W);else for(var U=Y.length-1;U>=0;U--)if(M=Y[U])O=(q<3?M(O):q>3?M(z,H,O):M(z,H))||O;return q>3&&O&&Object.defineProperty(z,H,O),O},p1=function(Y,z){return function(H,W){z(H,W,Y)}},i1=function(Y,z,H,W,q,O){function M(T){if(T!==void 0&&typeof T!=="function")throw new TypeError("Function expected");return T}var U=W.kind,$=U==="getter"?"get":U==="setter"?"set":"value",K=!z&&Y?W.static?Y:Y.prototype:null,w=z||(K?Object.getOwnPropertyDescriptor(K,W.name):{}),V,B=!1;for(var F=H.length-1;F>=0;F--){var D={};for(var b in W)D[b]=b==="access"?{}:W[b];for(var b in W.access)D.access[b]=W.access[b];D.addInitializer=function(T){if(B)throw new TypeError("Cannot add initializers after decoration has completed");O.push(M(T||null))};var j=H[F](U==="accessor"?{get:w.get,set:w.set}:w[$],D);if(U==="accessor"){if(j===void 0)continue;if(j===null||typeof j!=="object")throw new TypeError("Object expected");if(V=M(j.get))w.get=V;if(V=M(j.set))w.set=V;if(V=M(j.init))q.unshift(V)}else if(V=M(j))if(U==="field")q.unshift(V);else w[$]=V}if(K)Object.defineProperty(K,W.name,w);B=!0},n1=function(Y,z,H){var W=arguments.length>2;for(var q=0;q<z.length;q++)H=W?z[q].call(Y,H):z[q].call(Y);return W?H:void 0},a1=function(Y){return typeof Y==="symbol"?Y:"".concat(Y)},s1=function(Y,z,H){if(typeof z==="symbol")z=z.description?"[".concat(z.description,"]"):"";return Object.defineProperty(Y,"name",{configurable:!0,value:H?"".concat(H," ",z):z})},o1=function(Y,z){if(typeof Reflect==="object"&&typeof Reflect.metadata==="function")return Reflect.metadata(Y,z)},t1=function(Y,z,H,W){function q(O){return O instanceof H?O:new H(function(M){M(O)})}return new(H||(H=Promise))(function(O,M){function U(w){try{K(W.next(w))}catch(V){M(V)}}function $(w){try{K(W.throw(w))}catch(V){M(V)}}function K(w){w.done?O(w.value):q(w.value).then(U,$)}K((W=W.apply(Y,z||[])).next())})},r1=function(Y,z){var H={label:0,sent:function(){if(O[0]&1)throw O[1];return O[1]},trys:[],ops:[]},W,q,O,M=Object.create((typeof Iterator==="function"?Iterator:Object).prototype);return M.next=U(0),M.throw=U(1),M.return=U(2),typeof Symbol==="function"&&(M[Symbol.iterator]=function(){return this}),M;function U(K){return function(w){return $([K,w])}}function $(K){if(W)throw new TypeError("Generator is already executing.");while(M&&(M=0,K[0]&&(H=0)),H)try{if(W=1,q&&(O=K[0]&2?q.return:K[0]?q.throw||((O=q.return)&&O.call(q),0):q.next)&&!(O=O.call(q,K[1])).done)return O;if(q=0,O)K=[K[0]&2,O.value];switch(K[0]){case 0:case 1:O=K;break;case 4:return H.label++,{value:K[1],done:!1};case 5:H.label++,q=K[1],K=[0];continue;case 7:K=H.ops.pop(),H.trys.pop();continue;default:if((O=H.trys,!(O=O.length>0&&O[O.length-1]))&&(K[0]===6||K[0]===2)){H=0;continue}if(K[0]===3&&(!O||K[1]>O[0]&&K[1]<O[3])){H.label=K[1];break}if(K[0]===6&&H.label<O[1]){H.label=O[1],O=K;break}if(O&&H.label<O[2]){H.label=O[2],H.ops.push(K);break}if(O[2])H.ops.pop();H.trys.pop();continue}K=z.call(Y,H)}catch(w){K=[6,w],q=0}finally{W=O=0}if(K[0]&5)throw K[1];return{value:K[0]?K[1]:void 0,done:!0}}},e1=function(Y,z){for(var H in Y)if(H!=="default"&&!Object.prototype.hasOwnProperty.call(z,H))bZ(z,Y,H)},bZ=Object.create?function(Y,z,H,W){if(W===void 0)W=H;var q=Object.getOwnPropertyDescriptor(z,H);if(!q||("get"in q?!z.__esModule:q.writable||q.configurable))q={enumerable:!0,get:function(){return z[H]}};Object.defineProperty(Y,W,q)}:function(Y,z,H,W){if(W===void 0)W=H;Y[W]=z[H]},fZ=function(Y){var z=typeof Symbol==="function"&&Symbol.iterator,H=z&&Y[z],W=0;if(H)return H.call(Y);if(Y&&typeof Y.length==="number")return{next:function(){if(Y&&W>=Y.length)Y=void 0;return{value:Y&&Y[W++],done:!Y}}};throw new TypeError(z?"Object is not iterable.":"Symbol.iterator is not defined.")},xQ=function(Y,z){var H=typeof Symbol==="function"&&Y[Symbol.iterator];if(!H)return Y;var W=H.call(Y),q,O=[],M;try{while((z===void 0||z-- >0)&&!(q=W.next()).done)O.push(q.value)}catch(U){M={error:U}}finally{try{if(q&&!q.done&&(H=W.return))H.call(W)}finally{if(M)throw M.error}}return O},Z8=function(){for(var Y=[],z=0;z<arguments.length;z++)Y=Y.concat(xQ(arguments[z]));return Y},Q8=function(){for(var Y=0,z=0,H=arguments.length;z<H;z++)Y+=arguments[z].length;for(var W=Array(Y),q=0,z=0;z<H;z++)for(var O=arguments[z],M=0,U=O.length;M<U;M++,q++)W[q]=O[M];return W},X8=function(Y,z,H){if(H||arguments.length===2){for(var W=0,q=z.length,O;W<q;W++)if(O||!(W in z)){if(!O)O=Array.prototype.slice.call(z,0,W);O[W]=z[W]}}return Y.concat(O||Array.prototype.slice.call(z))},y0=function(Y){return this instanceof y0?(this.v=Y,this):new y0(Y)},J8=function(Y,z,H){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var W=H.apply(Y,z||[]),q,O=[];return q=Object.create((typeof AsyncIterator==="function"?AsyncIterator:Object).prototype),U("next"),U("throw"),U("return",M),q[Symbol.asyncIterator]=function(){return this},q;function M(F){return function(D){return Promise.resolve(D).then(F,V)}}function U(F,D){if(W[F]){if(q[F]=function(b){return new Promise(function(j,T){O.push([F,b,j,T])>1||$(F,b)})},D)q[F]=D(q[F])}}function $(F,D){try{K(W[F](D))}catch(b){B(O[0][3],b)}}function K(F){F.value instanceof y0?Promise.resolve(F.value.v).then(w,V):B(O[0][2],F)}function w(F){$("next",F)}function V(F){$("throw",F)}function B(F,D){if(F(D),O.shift(),O.length)$(O[0][0],O[0][1])}},Y8=function(Y){var z,H;return z={},W("next"),W("throw",function(q){throw q}),W("return"),z[Symbol.iterator]=function(){return this},z;function W(q,O){z[q]=Y[q]?function(M){return(H=!H)?{value:y0(Y[q](M)),done:!1}:O?O(M):M}:O}},G8=function(Y){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var z=Y[Symbol.asyncIterator],H;return z?z.call(Y):(Y=typeof fZ==="function"?fZ(Y):Y[Symbol.iterator](),H={},W("next"),W("throw"),W("return"),H[Symbol.asyncIterator]=function(){return this},H);function W(O){H[O]=Y[O]&&function(M){return new Promise(function(U,$){M=Y[O](M),q(U,$,M.done,M.value)})}}function q(O,M,U,$){Promise.resolve($).then(function(K){O({value:K,done:U})},M)}},z8=function(Y,z){if(Object.defineProperty)Object.defineProperty(Y,"raw",{value:z});else Y.raw=z;return Y};var X=Object.create?function(Y,z){Object.defineProperty(Y,"default",{enumerable:!0,value:z})}:function(Y,z){Y.default=z},J=function(Y){return J=Object.getOwnPropertyNames||function(z){var H=[];for(var W in z)if(Object.prototype.hasOwnProperty.call(z,W))H[H.length]=W;return H},J(Y)};H8=function(Y){if(Y&&Y.__esModule)return Y;var z={};if(Y!=null){for(var H=J(Y),W=0;W<H.length;W++)if(H[W]!=="default")bZ(z,Y,H[W])}return X(z,Y),z},W8=function(Y){return Y&&Y.__esModule?Y:{default:Y}},q8=function(Y,z,H,W){if(H==="a"&&!W)throw new TypeError("Private accessor was defined without a getter");if(typeof z==="function"?Y!==z||!W:!z.has(Y))throw new TypeError("Cannot read private member from an object whose class did not declare it");return H==="m"?W:H==="a"?W.call(Y):W?W.value:z.get(Y)},O8=function(Y,z,H,W,q){if(W==="m")throw new TypeError("Private method is not writable");if(W==="a"&&!q)throw new TypeError("Private accessor was defined without a setter");if(typeof z==="function"?Y!==z||!q:!z.has(Y))throw new TypeError("Cannot write private member to an object whose class did not declare it");return W==="a"?q.call(Y,H):q?q.value=H:z.set(Y,H),H},M8=function(Y,z){if(z===null||typeof z!=="object"&&typeof z!=="function")throw new TypeError("Cannot use 'in' operator on non-object");return typeof Y==="function"?z===Y:Y.has(z)},U8=function(Y,z,H){if(z!==null&&z!==void 0){if(typeof z!=="object"&&typeof z!=="function")throw new TypeError("Object expected.");var W,q;if(H){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");W=z[Symbol.asyncDispose]}if(W===void 0){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");if(W=z[Symbol.dispose],H)q=W}if(typeof W!=="function")throw new TypeError("Object not disposable.");if(q)W=function(){try{q.call(this)}catch(O){return Promise.reject(O)}};Y.stack.push({value:z,dispose:W,async:H})}else if(H)Y.stack.push({async:!0});return z};var G=typeof SuppressedError==="function"?SuppressedError:function(Y,z,H){var W=new Error(H);return W.name="SuppressedError",W.error=Y,W.suppressed=z,W};K8=function(Y){function z(O){Y.error=Y.hasError?new G(O,Y.error,"An error was suppressed during disposal."):O,Y.hasError=!0}var H,W=0;function q(){while(H=Y.stack.pop())try{if(!H.async&&W===1)return W=0,Y.stack.push(H),Promise.resolve().then(q);if(H.dispose){var O=H.dispose.call(H.value);if(H.async)return W|=2,Promise.resolve(O).then(q,function(M){return z(M),q()})}else W|=1}catch(M){z(M)}if(W===1)return Y.hasError?Promise.reject(Y.error):Promise.resolve();if(Y.hasError)throw Y.error}return q()},$8=function(Y,z){if(typeof Y==="string"&&/^\.\.?\//.test(Y))return Y.replace(/\.(tsx)$|((?:\.d)?)((?:\.[^./]+?)?)\.([cm]?)ts$/i,function(H,W,q,O,M){return W?z?".jsx":".js":q&&(!O||!M)?H:q+O+"."+M.toLowerCase()+"js"});return Y},Z("__extends",u1),Z("__assign",d1),Z("__rest",c1),Z("__decorate",l1),Z("__param",p1),Z("__esDecorate",i1),Z("__runInitializers",n1),Z("__propKey",a1),Z("__setFunctionName",s1),Z("__metadata",o1),Z("__awaiter",t1),Z("__generator",r1),Z("__exportStar",e1),Z("__createBinding",bZ),Z("__values",fZ),Z("__read",xQ),Z("__spread",Z8),Z("__spreadArrays",Q8),Z("__spreadArray",X8),Z("__await",y0),Z("__asyncGenerator",J8),Z("__asyncDelegator",Y8),Z("__asyncValues",G8),Z("__makeTemplateObject",z8),Z("__importStar",H8),Z("__importDefault",W8),Z("__classPrivateFieldGet",q8),Z("__classPrivateFieldSet",O8),Z("__classPrivateFieldIn",M8),Z("__addDisposableResource",U8),Z("__disposeResources",K8),Z("__rewriteRelativeImportExtension",$8)})});import{join as e6}from"path";import{join as v0}from"path";import{rename as XJ}from"fs/promises";import{dirname as r9}from"path";var F8=qX(B8(),1),{__extends:aJ,__assign:sJ,__rest:C0,__decorate:oJ,__param:tJ,__esDecorate:rJ,__runInitializers:eJ,__propKey:ZY,__setFunctionName:QY,__metadata:XY,__awaiter:V8,__generator:JY,__exportStar:YY,__createBinding:GY,__values:zY,__read:HY,__spread:WY,__spreadArrays:qY,__spreadArray:OY,__await:MY,__asyncGenerator:UY,__asyncDelegator:KY,__asyncValues:$Y,__makeTemplateObject:BY,__importStar:FY,__importDefault:VY,__classPrivateFieldGet:LY,__classPrivateFieldSet:wY,__classPrivateFieldIn:NY,__addDisposableResource:DY,__disposeResources:RY,__rewriteRelativeImportExtension:IY}=F8.default;var L8=(Z)=>{if(Z)return(...Q)=>Z(...Q);return(...Q)=>fetch(...Q)};class r0 extends Error{constructor(Z,Q="FunctionsError",X){super(Z);this.name=Q,this.context=X}toJSON(){return{name:this.name,message:this.message,context:this.context}}}class gZ extends r0{constructor(Z){super("Failed to send a request to the Edge Function","FunctionsFetchError",Z)}}class e0 extends r0{constructor(Z){super("Relay Error invoking the Edge Function","FunctionsRelayError",Z)}}class ZZ extends r0{constructor(Z){super("Edge Function returned a non-2xx status code","FunctionsHttpError",Z)}}var t0;(function(Z){Z.Any="any",Z.ApNortheast1="ap-northeast-1",Z.ApNortheast2="ap-northeast-2",Z.ApSouth1="ap-south-1",Z.ApSoutheast1="ap-southeast-1",Z.ApSoutheast2="ap-southeast-2",Z.CaCentral1="ca-central-1",Z.EuCentral1="eu-central-1",Z.EuWest1="eu-west-1",Z.EuWest2="eu-west-2",Z.EuWest3="eu-west-3",Z.SaEast1="sa-east-1",Z.UsEast1="us-east-1",Z.UsWest1="us-west-1",Z.UsWest2="us-west-2"})(t0||(t0={}));class _Z{constructor(Z,{headers:Q={},customFetch:X,region:J=t0.Any}={}){this.url=Z,this.headers=Q,this.region=J,this.fetch=L8(X)}setAuth(Z){this.headers.Authorization=`Bearer ${Z}`}invoke(Z){return V8(this,arguments,void 0,function*(Q,X={}){var J;let G,Y;try{let{headers:z,method:H,body:W,signal:q,timeout:O}=X,M={},{region:U}=X;if(!U)U=this.region;let $=new URL(`${this.url}/${Q}`);if(U&&U!=="any")M["x-region"]=U,$.searchParams.set("forceFunctionRegion",U);let K;if(W&&(z&&!Object.prototype.hasOwnProperty.call(z,"Content-Type")||!z))if(typeof Blob!=="undefined"&&W instanceof Blob||W instanceof ArrayBuffer)M["Content-Type"]="application/octet-stream",K=W;else if(typeof W==="string")M["Content-Type"]="text/plain",K=W;else if(typeof FormData!=="undefined"&&W instanceof FormData)K=W;else M["Content-Type"]="application/json",K=JSON.stringify(W);else if(W&&typeof W!=="string"&&!(typeof Blob!=="undefined"&&W instanceof Blob)&&!(W instanceof ArrayBuffer)&&!(typeof FormData!=="undefined"&&W instanceof FormData))K=JSON.stringify(W);else K=W;let w=q;if(O)if(Y=new AbortController,G=setTimeout(()=>Y.abort(),O),q)w=Y.signal,q.addEventListener("abort",()=>Y.abort());else w=Y.signal;let V=yield this.fetch($.toString(),{method:H||"POST",headers:Object.assign(Object.assign(Object.assign({},M),this.headers),z),body:K,signal:w}).catch((b)=>{throw new gZ(b)}),B=V.headers.get("x-relay-error");if(B&&B==="true")throw new e0(V);if(!V.ok)throw new ZZ(V);let F=((J=V.headers.get("Content-Type"))!==null&&J!==void 0?J:"text/plain").split(";")[0].trim(),D;if(F==="application/json")D=yield V.json();else if(F==="application/octet-stream"||F==="application/pdf")D=yield V.blob();else if(F==="text/event-stream")D=V;else if(F==="multipart/form-data")D=yield V.formData();else D=yield V.text();return{data:D,error:null,response:V}}catch(z){return{data:null,error:z,response:z instanceof ZZ||z instanceof e0?z.context:void 0}}finally{if(G)clearTimeout(G)}})}}var w8=(Z)=>Math.min(1000*2**Z,30000),MX=[520,503],I8=["GET","HEAD","OPTIONS"],C8=class extends Error{constructor(Z){super(Z.message);this.name="PostgrestError",this.details=Z.details,this.hint=Z.hint,this.code=Z.code}toJSON(){return{name:this.name,message:this.message,details:this.details,hint:this.hint,code:this.code}}};function N8(Z,Q){return new Promise((X)=>{if(Q===null||Q===void 0?void 0:Q.aborted){X();return}let J=setTimeout(()=>{Q===null||Q===void 0||Q.removeEventListener("abort",G),X()},Z);function G(){clearTimeout(J),X()}Q===null||Q===void 0||Q.addEventListener("abort",G)})}function UX(Z,Q,X,J){if(!J||X>=3)return!1;if(!I8.includes(Z))return!1;if(!MX.includes(Q))return!1;return!0}var KX=class{constructor(Z){var Q,X,J,G,Y;if(this.shouldThrowOnError=!1,this.retryEnabled=!0,this.method=Z.method,this.url=Z.url,this.headers=new Headers(Z.headers),this.schema=Z.schema,this.body=Z.body,this.shouldThrowOnError=(Q=Z.shouldThrowOnError)!==null&&Q!==void 0?Q:!1,this.signal=Z.signal,this.isMaybeSingle=(X=Z.isMaybeSingle)!==null&&X!==void 0?X:!1,this.shouldStripNulls=(J=Z.shouldStripNulls)!==null&&J!==void 0?J:!1,this.urlLengthLimit=(G=Z.urlLengthLimit)!==null&&G!==void 0?G:8000,this.retryEnabled=(Y=Z.retry)!==null&&Y!==void 0?Y:!0,Z.fetch)this.fetch=Z.fetch;else this.fetch=fetch}throwOnError(){return this.shouldThrowOnError=!0,this}stripNulls(){if(this.headers.get("Accept")==="text/csv")throw new Error("stripNulls() cannot be used with csv()");return this.shouldStripNulls=!0,this}setHeader(Z,Q){return this.headers=new Headers(this.headers),this.headers.set(Z,Q),this}retry(Z){return this.retryEnabled=Z,this}then(Z,Q){var X=this;if(this.schema===void 0);else if(["GET","HEAD"].includes(this.method))this.headers.set("Accept-Profile",this.schema);else this.headers.set("Content-Profile",this.schema);if(this.method!=="GET"&&this.method!=="HEAD")this.headers.set("Content-Type","application/json");if(this.shouldStripNulls){let z=this.headers.get("Accept");if(z==="application/vnd.pgrst.object+json")this.headers.set("Accept","application/vnd.pgrst.object+json;nulls=stripped");else if(!z||z==="application/json")this.headers.set("Accept","application/vnd.pgrst.array+json;nulls=stripped")}let J=this.fetch,Y=(async()=>{let z=0;while(!0){let q=new Headers(X.headers);if(z>0)q.set("X-Retry-Count",String(z));let O;try{O=await J(X.url.toString(),{method:X.method,headers:q,body:JSON.stringify(X.body,(M,U)=>typeof U==="bigint"?U.toString():U),signal:X.signal})}catch(M){if((M===null||M===void 0?void 0:M.name)==="AbortError"||(M===null||M===void 0?void 0:M.code)==="ABORT_ERR")throw M;if(!I8.includes(X.method))throw M;if(X.retryEnabled&&z<3){let U=w8(z);z++,await N8(U,X.signal);continue}throw M}if(UX(X.method,O.status,z,X.retryEnabled)){var H,W;let M=(H=(W=O.headers)===null||W===void 0?void 0:W.get("Retry-After"))!==null&&H!==void 0?H:null,U=M!==null?Math.max(0,parseInt(M,10)||0)*1000:w8(z);await O.text(),z++,await N8(U,X.signal);continue}return await X.processResponse(O)}})();if(!this.shouldThrowOnError)Y=Y.catch((z)=>{var H;let W="",q="",O="",M=z===null||z===void 0?void 0:z.cause;if(M){var U,$,K,w;let F=(U=M===null||M===void 0?void 0:M.message)!==null&&U!==void 0?U:"",D=($=M===null||M===void 0?void 0:M.code)!==null&&$!==void 0?$:"";if(W=`${(K=z===null||z===void 0?void 0:z.name)!==null&&K!==void 0?K:"FetchError"}: ${z===null||z===void 0?void 0:z.message}`,W+=`
4
+
5
+ Caused by: ${(w=M===null||M===void 0?void 0:M.name)!==null&&w!==void 0?w:"Error"}: ${F}`,D)W+=` (${D})`;if(M===null||M===void 0?void 0:M.stack)W+=`
6
+ ${M.stack}`}else{var V;W=(V=z===null||z===void 0?void 0:z.stack)!==null&&V!==void 0?V:""}let B=this.url.toString().length;if((z===null||z===void 0?void 0:z.name)==="AbortError"||(z===null||z===void 0?void 0:z.code)==="ABORT_ERR"){if(O="",q="Request was aborted (timeout or manual cancellation)",B>this.urlLengthLimit)q+=`. Note: Your request URL is ${B} characters, which may exceed server limits. If selecting many fields, consider using views. If filtering with large arrays (e.g., .in('id', [many IDs])), consider using an RPC function to pass values server-side.`}else if((M===null||M===void 0?void 0:M.name)==="HeadersOverflowError"||(M===null||M===void 0?void 0:M.code)==="UND_ERR_HEADERS_OVERFLOW"){if(O="",q="HTTP headers exceeded server limits (typically 16KB)",B>this.urlLengthLimit)q+=`. Your request URL is ${B} characters. If selecting many fields, consider using views. If filtering with large arrays (e.g., .in('id', [200+ IDs])), consider using an RPC function instead.`}return{success:!1,error:{message:`${(H=z===null||z===void 0?void 0:z.name)!==null&&H!==void 0?H:"FetchError"}: ${z===null||z===void 0?void 0:z.message}`,details:W,hint:q,code:O},data:null,count:null,status:0,statusText:""}});return Y.then(Z,Q)}async processResponse(Z){var Q=this;let X=null,J=null,G=null,Y=Z.status,z=Z.statusText;if(Z.ok){var H,W;if(Q.method!=="HEAD"){var q;let U=await Z.text();if(U==="");else if(Q.headers.get("Accept")==="text/csv")J=U;else if(Q.headers.get("Accept")&&((q=Q.headers.get("Accept"))===null||q===void 0?void 0:q.includes("application/vnd.pgrst.plan+text")))J=U;else J=JSON.parse(U)}let O=(H=Q.headers.get("Prefer"))===null||H===void 0?void 0:H.match(/count=(exact|planned|estimated)/),M=(W=Z.headers.get("content-range"))===null||W===void 0?void 0:W.split("/");if(O&&M&&M.length>1)G=parseInt(M[1]);if(Q.isMaybeSingle&&Array.isArray(J))if(J.length>1)X={code:"PGRST116",details:`Results contain ${J.length} rows, application/vnd.pgrst.object+json requires 1 row`,hint:null,message:"JSON object requested, multiple (or no) rows returned"},J=null,G=null,Y=406,z="Not Acceptable";else if(J.length===1)J=J[0];else J=null}else{let O=await Z.text();try{if(X=JSON.parse(O),Array.isArray(X)&&Z.status===404)J=[],X=null,Y=200,z="OK"}catch(M){if(Z.status===404&&O==="")Y=204,z="No Content";else X={message:O}}if(X&&Q.shouldThrowOnError)throw new C8(X)}return{success:X===null,error:X,data:J,count:G,status:Y,statusText:z}}returns(){return this}overrideTypes(){return this}},$X=class extends KX{select(Z){let Q=!1,X=(Z!==null&&Z!==void 0?Z:"*").split("").map((J)=>{if(/\s/.test(J)&&!Q)return"";if(J==='"')Q=!Q;return J}).join("");return this.url.searchParams.set("select",X),this.headers.append("Prefer","return=representation"),this}order(Z,{ascending:Q=!0,nullsFirst:X,foreignTable:J,referencedTable:G=J}={}){let Y=G?`${G}.order`:"order",z=this.url.searchParams.get(Y);return this.url.searchParams.set(Y,`${z?`${z},`:""}${Z}.${Q?"asc":"desc"}${X===void 0?"":X?".nullsfirst":".nullslast"}`),this}limit(Z,{foreignTable:Q,referencedTable:X=Q}={}){let J=typeof X==="undefined"?"limit":`${X}.limit`;return this.url.searchParams.set(J,`${Z}`),this}range(Z,Q,{foreignTable:X,referencedTable:J=X}={}){let G=typeof J==="undefined"?"offset":`${J}.offset`,Y=typeof J==="undefined"?"limit":`${J}.limit`;return this.url.searchParams.set(G,`${Z}`),this.url.searchParams.set(Y,`${Q-Z+1}`),this}abortSignal(Z){return this.signal=Z,this}single(){return this.headers.set("Accept","application/vnd.pgrst.object+json"),this}maybeSingle(){return this.isMaybeSingle=!0,this}csv(){return this.headers.set("Accept","text/csv"),this}geojson(){return this.headers.set("Accept","application/geo+json"),this}explain({analyze:Z=!1,verbose:Q=!1,settings:X=!1,buffers:J=!1,wal:G=!1,format:Y="text"}={}){var z;let H=[Z?"analyze":null,Q?"verbose":null,X?"settings":null,J?"buffers":null,G?"wal":null].filter(Boolean).join("|"),W=(z=this.headers.get("Accept"))!==null&&z!==void 0?z:"application/json";if(this.headers.set("Accept",`application/vnd.pgrst.plan+${Y}; for="${W}"; options=${H};`),Y==="json")return this;else return this}rollback(){return this.headers.append("Prefer","tx=rollback"),this}returns(){return this}maxAffected(Z){return this.headers.append("Prefer","handling=strict"),this.headers.append("Prefer",`max-affected=${Z}`),this}},D8=new RegExp("[,()]"),g0=class extends $X{eq(Z,Q){return this.url.searchParams.append(Z,`eq.${Q}`),this}neq(Z,Q){return this.url.searchParams.append(Z,`neq.${Q}`),this}gt(Z,Q){return this.url.searchParams.append(Z,`gt.${Q}`),this}gte(Z,Q){return this.url.searchParams.append(Z,`gte.${Q}`),this}lt(Z,Q){return this.url.searchParams.append(Z,`lt.${Q}`),this}lte(Z,Q){return this.url.searchParams.append(Z,`lte.${Q}`),this}like(Z,Q){return this.url.searchParams.append(Z,`like.${Q}`),this}likeAllOf(Z,Q){return this.url.searchParams.append(Z,`like(all).{${Q.join(",")}}`),this}likeAnyOf(Z,Q){return this.url.searchParams.append(Z,`like(any).{${Q.join(",")}}`),this}ilike(Z,Q){return this.url.searchParams.append(Z,`ilike.${Q}`),this}ilikeAllOf(Z,Q){return this.url.searchParams.append(Z,`ilike(all).{${Q.join(",")}}`),this}ilikeAnyOf(Z,Q){return this.url.searchParams.append(Z,`ilike(any).{${Q.join(",")}}`),this}regexMatch(Z,Q){return this.url.searchParams.append(Z,`match.${Q}`),this}regexIMatch(Z,Q){return this.url.searchParams.append(Z,`imatch.${Q}`),this}is(Z,Q){return this.url.searchParams.append(Z,`is.${Q}`),this}isDistinct(Z,Q){return this.url.searchParams.append(Z,`isdistinct.${Q}`),this}in(Z,Q){let X=Array.from(new Set(Q)).map((J)=>{if(typeof J==="string"&&D8.test(J))return`"${J}"`;else return`${J}`}).join(",");return this.url.searchParams.append(Z,`in.(${X})`),this}notIn(Z,Q){let X=Array.from(new Set(Q)).map((J)=>{if(typeof J==="string"&&D8.test(J))return`"${J}"`;else return`${J}`}).join(",");return this.url.searchParams.append(Z,`not.in.(${X})`),this}contains(Z,Q){if(typeof Q==="string")this.url.searchParams.append(Z,`cs.${Q}`);else if(Array.isArray(Q))this.url.searchParams.append(Z,`cs.{${Q.join(",")}}`);else this.url.searchParams.append(Z,`cs.${JSON.stringify(Q)}`);return this}containedBy(Z,Q){if(typeof Q==="string")this.url.searchParams.append(Z,`cd.${Q}`);else if(Array.isArray(Q))this.url.searchParams.append(Z,`cd.{${Q.join(",")}}`);else this.url.searchParams.append(Z,`cd.${JSON.stringify(Q)}`);return this}rangeGt(Z,Q){return this.url.searchParams.append(Z,`sr.${Q}`),this}rangeGte(Z,Q){return this.url.searchParams.append(Z,`nxl.${Q}`),this}rangeLt(Z,Q){return this.url.searchParams.append(Z,`sl.${Q}`),this}rangeLte(Z,Q){return this.url.searchParams.append(Z,`nxr.${Q}`),this}rangeAdjacent(Z,Q){return this.url.searchParams.append(Z,`adj.${Q}`),this}overlaps(Z,Q){if(typeof Q==="string")this.url.searchParams.append(Z,`ov.${Q}`);else this.url.searchParams.append(Z,`ov.{${Q.join(",")}}`);return this}textSearch(Z,Q,{config:X,type:J}={}){let G="";if(J==="plain")G="pl";else if(J==="phrase")G="ph";else if(J==="websearch")G="w";let Y=X===void 0?"":`(${X})`;return this.url.searchParams.append(Z,`${G}fts${Y}.${Q}`),this}match(Z){return Object.entries(Z).filter(([Q,X])=>X!==void 0).forEach(([Q,X])=>{this.url.searchParams.append(Q,`eq.${X}`)}),this}not(Z,Q,X){return this.url.searchParams.append(Z,`not.${Q}.${X}`),this}or(Z,{foreignTable:Q,referencedTable:X=Q}={}){let J=X?`${X}.or`:"or";return this.url.searchParams.append(J,`(${Z})`),this}filter(Z,Q,X){return this.url.searchParams.append(Z,`${Q}.${X}`),this}},BX=class{constructor(Z,{headers:Q={},schema:X,fetch:J,urlLengthLimit:G=8000,retry:Y}){this.url=Z,this.headers=new Headers(Q),this.schema=X,this.fetch=J,this.urlLengthLimit=G,this.retry=Y}cloneRequestState(){return{url:new URL(this.url.toString()),headers:new Headers(this.headers)}}select(Z,Q){let{head:X=!1,count:J}=Q!==null&&Q!==void 0?Q:{},G=X?"HEAD":"GET",Y=!1,z=(Z!==null&&Z!==void 0?Z:"*").split("").map((q)=>{if(/\s/.test(q)&&!Y)return"";if(q==='"')Y=!Y;return q}).join(""),{url:H,headers:W}=this.cloneRequestState();if(H.searchParams.set("select",z),J)W.append("Prefer",`count=${J}`);return new g0({method:G,url:H,headers:W,schema:this.schema,fetch:this.fetch,urlLengthLimit:this.urlLengthLimit,retry:this.retry})}insert(Z,{count:Q,defaultToNull:X=!0}={}){var J;let G="POST",{url:Y,headers:z}=this.cloneRequestState();if(Q)z.append("Prefer",`count=${Q}`);if(!X)z.append("Prefer","missing=default");if(Array.isArray(Z)){let H=Z.reduce((W,q)=>W.concat(Object.keys(q)),[]);if(H.length>0){let W=[...new Set(H)].map((q)=>`"${q}"`);Y.searchParams.set("columns",W.join(","))}}return new g0({method:"POST",url:Y,headers:z,schema:this.schema,body:Z,fetch:(J=this.fetch)!==null&&J!==void 0?J:fetch,urlLengthLimit:this.urlLengthLimit,retry:this.retry})}upsert(Z,{onConflict:Q,ignoreDuplicates:X=!1,count:J,defaultToNull:G=!0}={}){var Y;let z="POST",{url:H,headers:W}=this.cloneRequestState();if(W.append("Prefer",`resolution=${X?"ignore":"merge"}-duplicates`),Q!==void 0)H.searchParams.set("on_conflict",Q);if(J)W.append("Prefer",`count=${J}`);if(!G)W.append("Prefer","missing=default");if(Array.isArray(Z)){let q=Z.reduce((O,M)=>O.concat(Object.keys(M)),[]);if(q.length>0){let O=[...new Set(q)].map((M)=>`"${M}"`);H.searchParams.set("columns",O.join(","))}}return new g0({method:"POST",url:H,headers:W,schema:this.schema,body:Z,fetch:(Y=this.fetch)!==null&&Y!==void 0?Y:fetch,urlLengthLimit:this.urlLengthLimit,retry:this.retry})}update(Z,{count:Q}={}){var X;let J="PATCH",{url:G,headers:Y}=this.cloneRequestState();if(Q)Y.append("Prefer",`count=${Q}`);return new g0({method:"PATCH",url:G,headers:Y,schema:this.schema,body:Z,fetch:(X=this.fetch)!==null&&X!==void 0?X:fetch,urlLengthLimit:this.urlLengthLimit,retry:this.retry})}delete({count:Z}={}){var Q;let X="DELETE",{url:J,headers:G}=this.cloneRequestState();if(Z)G.append("Prefer",`count=${Z}`);return new g0({method:"DELETE",url:J,headers:G,schema:this.schema,fetch:(Q=this.fetch)!==null&&Q!==void 0?Q:fetch,urlLengthLimit:this.urlLengthLimit,retry:this.retry})}};function QZ(Z){return QZ=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(Q){return typeof Q}:function(Q){return Q&&typeof Symbol=="function"&&Q.constructor===Symbol&&Q!==Symbol.prototype?"symbol":typeof Q},QZ(Z)}function FX(Z,Q){if(QZ(Z)!="object"||!Z)return Z;var X=Z[Symbol.toPrimitive];if(X!==void 0){var J=X.call(Z,Q||"default");if(QZ(J)!="object")return J;throw new TypeError("@@toPrimitive must return a primitive value.")}return(Q==="string"?String:Number)(Z)}function VX(Z){var Q=FX(Z,"string");return QZ(Q)=="symbol"?Q:Q+""}function LX(Z,Q,X){return(Q=VX(Q))in Z?Object.defineProperty(Z,Q,{value:X,enumerable:!0,configurable:!0,writable:!0}):Z[Q]=X,Z}function R8(Z,Q){var X=Object.keys(Z);if(Object.getOwnPropertySymbols){var J=Object.getOwnPropertySymbols(Z);Q&&(J=J.filter(function(G){return Object.getOwnPropertyDescriptor(Z,G).enumerable})),X.push.apply(X,J)}return X}function hZ(Z){for(var Q=1;Q<arguments.length;Q++){var X=arguments[Q]!=null?arguments[Q]:{};Q%2?R8(Object(X),!0).forEach(function(J){LX(Z,J,X[J])}):Object.getOwnPropertyDescriptors?Object.defineProperties(Z,Object.getOwnPropertyDescriptors(X)):R8(Object(X)).forEach(function(J){Object.defineProperty(Z,J,Object.getOwnPropertyDescriptor(X,J))})}return Z}var P8=class Z{constructor(Q,{headers:X={},schema:J,fetch:G,timeout:Y,urlLengthLimit:z=8000,retry:H}={}){this.url=Q,this.headers=new Headers(X),this.schemaName=J,this.urlLengthLimit=z;let W=G!==null&&G!==void 0?G:globalThis.fetch;if(Y!==void 0&&Y>0)this.fetch=(q,O)=>{let M=new AbortController,U=setTimeout(()=>M.abort(),Y),$=O===null||O===void 0?void 0:O.signal;if($){if($.aborted)return clearTimeout(U),W(q,O);let K=()=>{clearTimeout(U),M.abort()};return $.addEventListener("abort",K,{once:!0}),W(q,hZ(hZ({},O),{},{signal:M.signal})).finally(()=>{clearTimeout(U),$.removeEventListener("abort",K)})}return W(q,hZ(hZ({},O),{},{signal:M.signal})).finally(()=>clearTimeout(U))};else this.fetch=W;this.retry=H}from(Q){if(!Q||typeof Q!=="string"||Q.trim()==="")throw new Error("Invalid relation name: relation must be a non-empty string.");return new BX(new URL(`${this.url}/${Q}`),{headers:new Headers(this.headers),schema:this.schemaName,fetch:this.fetch,urlLengthLimit:this.urlLengthLimit,retry:this.retry})}schema(Q){return new Z(this.url,{headers:this.headers,schema:Q,fetch:this.fetch,urlLengthLimit:this.urlLengthLimit,retry:this.retry})}rpc(Q,X={},{head:J=!1,get:G=!1,count:Y}={}){var z;let H,W=new URL(`${this.url}/rpc/${Q}`),q,O=($)=>$!==null&&typeof $==="object"&&(!Array.isArray($)||$.some(O)),M=J&&Object.values(X).some(O);if(M)H="POST",q=X;else if(J||G)H=J?"HEAD":"GET",Object.entries(X).filter(([$,K])=>K!==void 0).map(([$,K])=>[$,Array.isArray(K)?`{${K.join(",")}}`:`${K}`]).forEach(([$,K])=>{W.searchParams.append($,K)});else H="POST",q=X;let U=new Headers(this.headers);if(M)U.set("Prefer",Y?`count=${Y},return=minimal`:"return=minimal");else if(Y)U.set("Prefer",`count=${Y}`);return new g0({method:H,url:W,headers:U,schema:this.schemaName,body:q,fetch:(z=this.fetch)!==null&&z!==void 0?z:fetch,urlLengthLimit:this.urlLengthLimit,retry:this.retry})}};class A8{constructor(){}static detectEnvironment(){var Z;if(typeof WebSocket!=="undefined")return{type:"native",constructor:WebSocket};if(typeof globalThis!=="undefined"&&typeof globalThis.WebSocket!=="undefined")return{type:"native",constructor:globalThis.WebSocket};if(typeof global!=="undefined"&&typeof global.WebSocket!=="undefined")return{type:"native",constructor:global.WebSocket};if(typeof globalThis!=="undefined"&&typeof globalThis.WebSocketPair!=="undefined"&&typeof globalThis.WebSocket==="undefined")return{type:"cloudflare",error:"Cloudflare Workers detected. WebSocket clients are not supported in Cloudflare Workers.",workaround:"Use Cloudflare Workers WebSocket API for server-side WebSocket handling, or deploy to a different runtime."};if(typeof globalThis!=="undefined"&&globalThis.EdgeRuntime||typeof navigator!=="undefined"&&((Z=navigator.userAgent)===null||Z===void 0?void 0:Z.includes("Vercel-Edge")))return{type:"unsupported",error:"Edge runtime detected (Vercel Edge/Netlify Edge). WebSockets are not supported in edge functions.",workaround:"Use serverless functions or a different deployment target for WebSocket functionality."};let Q=globalThis.process;if(Q){let X=Q.versions;if(X&&X.node){let J=X.node,G=parseInt(J.replace(/^v/,"").split(".")[0]);if(G>=22){if(typeof globalThis.WebSocket!=="undefined")return{type:"native",constructor:globalThis.WebSocket};return{type:"unsupported",error:`Node.js ${G} detected but native WebSocket not found.`,workaround:"Provide a WebSocket implementation via the transport option."}}return{type:"unsupported",error:`Node.js ${G} detected without native WebSocket support.`,workaround:`For Node.js < 22, install "ws" package and provide it via the transport option:
7
+ import ws from "ws"
8
+ new RealtimeClient(url, { transport: ws })`}}}return{type:"unsupported",error:"Unknown JavaScript runtime without WebSocket support.",workaround:"Ensure you're running in a supported environment (browser, Node.js, Deno) or provide a custom WebSocket implementation."}}static getWebSocketConstructor(){let Z=this.detectEnvironment();if(Z.constructor)return Z.constructor;let Q=Z.error||"WebSocket not supported in this environment.";if(Z.workaround)Q+=`
9
+
10
+ Suggested solution: ${Z.workaround}`;throw new Error(Q)}static isWebSocketSupported(){try{let Z=this.detectEnvironment();return Z.type==="native"||Z.type==="ws"}catch(Z){return!1}}}var SQ=A8;var j8="2.105.0";var x8=`realtime-js/${j8}`,S8="1.0.0",TQ="2.0.0",T8=TQ;var k8=1e4;var E8=100;var q0={closed:"closed",errored:"errored",joined:"joined",joining:"joining",leaving:"leaving"},mZ={close:"phx_close",error:"phx_error",join:"phx_join",reply:"phx_reply",leave:"phx_leave",access_token:"access_token"};var XZ={connecting:"connecting",open:"open",closing:"closing",closed:"closed"};class uZ{constructor(Z){this.HEADER_LENGTH=1,this.USER_BROADCAST_PUSH_META_LENGTH=6,this.KINDS={userBroadcastPush:3,userBroadcast:4},this.BINARY_ENCODING=0,this.JSON_ENCODING=1,this.BROADCAST_EVENT="broadcast",this.allowedMetadataKeys=[],this.allowedMetadataKeys=Z!==null&&Z!==void 0?Z:[]}encode(Z,Q){if(Z.event===this.BROADCAST_EVENT&&!(Z.payload instanceof ArrayBuffer)&&typeof Z.payload.event==="string")return Q(this._binaryEncodeUserBroadcastPush(Z));let X=[Z.join_ref,Z.ref,Z.topic,Z.event,Z.payload];return Q(JSON.stringify(X))}_binaryEncodeUserBroadcastPush(Z){var Q;if(this._isArrayBuffer((Q=Z.payload)===null||Q===void 0?void 0:Q.payload))return this._encodeBinaryUserBroadcastPush(Z);else return this._encodeJsonUserBroadcastPush(Z)}_encodeBinaryUserBroadcastPush(Z){var Q,X;let J=(X=(Q=Z.payload)===null||Q===void 0?void 0:Q.payload)!==null&&X!==void 0?X:new ArrayBuffer(0);return this._encodeUserBroadcastPush(Z,this.BINARY_ENCODING,J)}_encodeJsonUserBroadcastPush(Z){var Q,X;let J=(X=(Q=Z.payload)===null||Q===void 0?void 0:Q.payload)!==null&&X!==void 0?X:{},Y=new TextEncoder().encode(JSON.stringify(J)).buffer;return this._encodeUserBroadcastPush(Z,this.JSON_ENCODING,Y)}_encodeUserBroadcastPush(Z,Q,X){var J,G;let Y=Z.topic,z=(J=Z.ref)!==null&&J!==void 0?J:"",H=(G=Z.join_ref)!==null&&G!==void 0?G:"",W=Z.payload.event,q=this.allowedMetadataKeys?this._pick(Z.payload,this.allowedMetadataKeys):{},O=Object.keys(q).length===0?"":JSON.stringify(q);if(H.length>255)throw new Error(`joinRef length ${H.length} exceeds maximum of 255`);if(z.length>255)throw new Error(`ref length ${z.length} exceeds maximum of 255`);if(Y.length>255)throw new Error(`topic length ${Y.length} exceeds maximum of 255`);if(W.length>255)throw new Error(`userEvent length ${W.length} exceeds maximum of 255`);if(O.length>255)throw new Error(`metadata length ${O.length} exceeds maximum of 255`);let M=this.USER_BROADCAST_PUSH_META_LENGTH+H.length+z.length+Y.length+W.length+O.length,U=new ArrayBuffer(this.HEADER_LENGTH+M),$=new DataView(U),K=0;$.setUint8(K++,this.KINDS.userBroadcastPush),$.setUint8(K++,H.length),$.setUint8(K++,z.length),$.setUint8(K++,Y.length),$.setUint8(K++,W.length),$.setUint8(K++,O.length),$.setUint8(K++,Q),Array.from(H,(V)=>$.setUint8(K++,V.charCodeAt(0))),Array.from(z,(V)=>$.setUint8(K++,V.charCodeAt(0))),Array.from(Y,(V)=>$.setUint8(K++,V.charCodeAt(0))),Array.from(W,(V)=>$.setUint8(K++,V.charCodeAt(0))),Array.from(O,(V)=>$.setUint8(K++,V.charCodeAt(0)));var w=new Uint8Array(U.byteLength+X.byteLength);return w.set(new Uint8Array(U),0),w.set(new Uint8Array(X),U.byteLength),w.buffer}decode(Z,Q){if(this._isArrayBuffer(Z)){let X=this._binaryDecode(Z);return Q(X)}if(typeof Z==="string"){let X=JSON.parse(Z),[J,G,Y,z,H]=X;return Q({join_ref:J,ref:G,topic:Y,event:z,payload:H})}return Q({})}_binaryDecode(Z){let Q=new DataView(Z),X=Q.getUint8(0),J=new TextDecoder;switch(X){case this.KINDS.userBroadcast:return this._decodeUserBroadcast(Z,Q,J)}}_decodeUserBroadcast(Z,Q,X){let J=Q.getUint8(1),G=Q.getUint8(2),Y=Q.getUint8(3),z=Q.getUint8(4),H=this.HEADER_LENGTH+4,W=X.decode(Z.slice(H,H+J));H=H+J;let q=X.decode(Z.slice(H,H+G));H=H+G;let O=X.decode(Z.slice(H,H+Y));H=H+Y;let M=Z.slice(H,Z.byteLength),U=z===this.JSON_ENCODING?JSON.parse(X.decode(M)):M,$={type:this.BROADCAST_EVENT,event:q,payload:U};if(Y>0)$.meta=JSON.parse(O);return{join_ref:null,ref:null,topic:W,event:this.BROADCAST_EVENT,payload:$}}_isArrayBuffer(Z){var Q;return Z instanceof ArrayBuffer||((Q=Z===null||Z===void 0?void 0:Z.constructor)===null||Q===void 0?void 0:Q.name)==="ArrayBuffer"}_pick(Z,Q){if(!Z||typeof Z!=="object")return{};return Object.fromEntries(Object.entries(Z).filter(([X])=>Q.includes(X)))}}var y;(function(Z){Z.abstime="abstime",Z.bool="bool",Z.date="date",Z.daterange="daterange",Z.float4="float4",Z.float8="float8",Z.int2="int2",Z.int4="int4",Z.int4range="int4range",Z.int8="int8",Z.int8range="int8range",Z.json="json",Z.jsonb="jsonb",Z.money="money",Z.numeric="numeric",Z.oid="oid",Z.reltime="reltime",Z.text="text",Z.time="time",Z.timestamp="timestamp",Z.timestamptz="timestamptz",Z.timetz="timetz",Z.tsrange="tsrange",Z.tstzrange="tstzrange"})(y||(y={}));var EQ=(Z,Q,X={})=>{var J;let G=(J=X.skipTypes)!==null&&J!==void 0?J:[];if(!Q)return{};return Object.keys(Q).reduce((Y,z)=>{return Y[z]=wX(z,Z,Q,G),Y},{})},wX=(Z,Q,X,J)=>{let G=Q.find((H)=>H.name===Z),Y=G===null||G===void 0?void 0:G.type,z=X[Z];if(Y&&!J.includes(Y))return v8(Y,z);return kQ(z)},v8=(Z,Q)=>{if(Z.charAt(0)==="_"){let X=Z.slice(1,Z.length);return IX(Q,X)}switch(Z){case y.bool:return NX(Q);case y.float4:case y.float8:case y.int2:case y.int4:case y.int8:case y.numeric:case y.oid:return DX(Q);case y.json:case y.jsonb:return RX(Q);case y.timestamp:return CX(Q);case y.abstime:case y.date:case y.daterange:case y.int4range:case y.int8range:case y.money:case y.reltime:case y.text:case y.time:case y.timestamptz:case y.timetz:case y.tsrange:case y.tstzrange:return kQ(Q);default:return kQ(Q)}},kQ=(Z)=>{return Z},NX=(Z)=>{switch(Z){case"t":return!0;case"f":return!1;default:return Z}},DX=(Z)=>{if(typeof Z==="string"){let Q=parseFloat(Z);if(!Number.isNaN(Q))return Q}return Z},RX=(Z)=>{if(typeof Z==="string")try{return JSON.parse(Z)}catch(Q){return Z}return Z},IX=(Z,Q)=>{if(typeof Z!=="string")return Z;let X=Z.length-1,J=Z[X];if(Z[0]==="{"&&J==="}"){let Y,z=Z.slice(1,X);try{Y=JSON.parse("["+z+"]")}catch(H){Y=z?z.split(","):[]}return Y.map((H)=>v8(Q,H))}return Z},CX=(Z)=>{if(typeof Z==="string")return Z.replace(" ","T");return Z},dZ=(Z)=>{let Q=new URL(Z);if(Q.protocol=Q.protocol.replace(/^ws/i,"http"),Q.pathname=Q.pathname.replace(/\/+$/,"").replace(/\/socket\/websocket$/i,"").replace(/\/socket$/i,"").replace(/\/websocket$/i,""),Q.pathname===""||Q.pathname==="/")Q.pathname="/api/broadcast";else Q.pathname=Q.pathname+"/api/broadcast";return Q.href};var JZ=(Z)=>{if(typeof Z==="function")return Z;else return function(){return Z}},AX=typeof self!=="undefined"?self:null,h0=typeof window!=="undefined"?window:null,O0=AX||h0||globalThis,jX="2.0.0",xX=1e4,SX=1000,M0={connecting:0,open:1,closing:2,closed:3},o={closed:"closed",errored:"errored",joined:"joined",joining:"joining",leaving:"leaving"},F0={close:"phx_close",error:"phx_error",join:"phx_join",reply:"phx_reply",leave:"phx_leave"},vQ={longpoll:"longpoll",websocket:"websocket"},TX={complete:4},fQ="base64url.bearer.phx.",cZ=class{constructor(Z,Q,X,J){this.channel=Z,this.event=Q,this.payload=X||function(){return{}},this.receivedResp=null,this.timeout=J,this.timeoutTimer=null,this.recHooks=[],this.sent=!1,this.ref=void 0}resend(Z){this.timeout=Z,this.reset(),this.send()}send(){if(this.hasReceived("timeout"))return;this.startTimeout(),this.sent=!0,this.channel.socket.push({topic:this.channel.topic,event:this.event,payload:this.payload(),ref:this.ref,join_ref:this.channel.joinRef()})}receive(Z,Q){if(this.hasReceived(Z))Q(this.receivedResp.response);return this.recHooks.push({status:Z,callback:Q}),this}reset(){this.cancelRefEvent(),this.ref=null,this.refEvent=null,this.receivedResp=null,this.sent=!1}destroy(){this.cancelRefEvent(),this.cancelTimeout()}matchReceive({status:Z,response:Q,_ref:X}){this.recHooks.filter((J)=>J.status===Z).forEach((J)=>J.callback(Q))}cancelRefEvent(){if(!this.refEvent)return;this.channel.off(this.refEvent)}cancelTimeout(){clearTimeout(this.timeoutTimer),this.timeoutTimer=null}startTimeout(){if(this.timeoutTimer)this.cancelTimeout();this.ref=this.channel.socket.makeRef(),this.refEvent=this.channel.replyEventName(this.ref),this.channel.on(this.refEvent,(Z)=>{this.cancelRefEvent(),this.cancelTimeout(),this.receivedResp=Z,this.matchReceive(Z)}),this.timeoutTimer=setTimeout(()=>{this.trigger("timeout",{})},this.timeout)}hasReceived(Z){return this.receivedResp&&this.receivedResp.status===Z}trigger(Z,Q){this.channel.trigger(this.refEvent,{status:Z,response:Q})}},f8=class{constructor(Z,Q){this.callback=Z,this.timerCalc=Q,this.timer=void 0,this.tries=0}reset(){this.tries=0,clearTimeout(this.timer)}scheduleTimeout(){clearTimeout(this.timer),this.timer=setTimeout(()=>{this.tries=this.tries+1,this.callback()},this.timerCalc(this.tries+1))}},kX=class{constructor(Z,Q,X){this.state=o.closed,this.topic=Z,this.params=JZ(Q||{}),this.socket=X,this.bindings=[],this.bindingRef=0,this.timeout=this.socket.timeout,this.joinedOnce=!1,this.joinPush=new cZ(this,F0.join,this.params,this.timeout),this.pushBuffer=[],this.stateChangeRefs=[],this.rejoinTimer=new f8(()=>{if(this.socket.isConnected())this.rejoin()},this.socket.rejoinAfterMs),this.stateChangeRefs.push(this.socket.onError(()=>this.rejoinTimer.reset())),this.stateChangeRefs.push(this.socket.onOpen(()=>{if(this.rejoinTimer.reset(),this.isErrored())this.rejoin()})),this.joinPush.receive("ok",()=>{this.state=o.joined,this.rejoinTimer.reset(),this.pushBuffer.forEach((J)=>J.send()),this.pushBuffer=[]}),this.joinPush.receive("error",(J)=>{if(this.state=o.errored,this.socket.hasLogger())this.socket.log("channel",`error ${this.topic}`,J);if(this.socket.isConnected())this.rejoinTimer.scheduleTimeout()}),this.onClose(()=>{if(this.rejoinTimer.reset(),this.socket.hasLogger())this.socket.log("channel",`close ${this.topic}`);this.state=o.closed,this.socket.remove(this)}),this.onError((J)=>{if(this.socket.hasLogger())this.socket.log("channel",`error ${this.topic}`,J);if(this.isJoining())this.joinPush.reset();if(this.state=o.errored,this.socket.isConnected())this.rejoinTimer.scheduleTimeout()}),this.joinPush.receive("timeout",()=>{if(this.socket.hasLogger())this.socket.log("channel",`timeout ${this.topic}`,this.joinPush.timeout);if(new cZ(this,F0.leave,JZ({}),this.timeout).send(),this.state=o.errored,this.joinPush.reset(),this.socket.isConnected())this.rejoinTimer.scheduleTimeout()}),this.on(F0.reply,(J,G)=>{this.trigger(this.replyEventName(G),J)})}join(Z=this.timeout){if(this.joinedOnce)throw new Error("tried to join multiple times. 'join' can only be called a single time per channel instance");else return this.timeout=Z,this.joinedOnce=!0,this.rejoin(),this.joinPush}teardown(){this.pushBuffer.forEach((Z)=>Z.destroy()),this.pushBuffer=[],this.rejoinTimer.reset(),this.joinPush.destroy(),this.state=o.closed,this.bindings=[]}onClose(Z){this.on(F0.close,Z)}onError(Z){return this.on(F0.error,(Q)=>Z(Q))}on(Z,Q){let X=this.bindingRef++;return this.bindings.push({event:Z,ref:X,callback:Q}),X}off(Z,Q){this.bindings=this.bindings.filter((X)=>{return!(X.event===Z&&(typeof Q==="undefined"||Q===X.ref))})}canPush(){return this.socket.isConnected()&&this.isJoined()}push(Z,Q,X=this.timeout){if(Q=Q||{},!this.joinedOnce)throw new Error(`tried to push '${Z}' to '${this.topic}' before joining. Use channel.join() before pushing events`);let J=new cZ(this,Z,function(){return Q},X);if(this.canPush())J.send();else J.startTimeout(),this.pushBuffer.push(J);return J}leave(Z=this.timeout){this.rejoinTimer.reset(),this.joinPush.cancelTimeout(),this.state=o.leaving;let Q=()=>{if(this.socket.hasLogger())this.socket.log("channel",`leave ${this.topic}`);this.trigger(F0.close,"leave")},X=new cZ(this,F0.leave,JZ({}),Z);if(X.receive("ok",()=>Q()).receive("timeout",()=>Q()),X.send(),!this.canPush())X.trigger("ok",{});return X}onMessage(Z,Q,X){return Q}filterBindings(Z,Q,X){return!0}isMember(Z,Q,X,J){if(this.topic!==Z)return!1;if(J&&J!==this.joinRef()){if(this.socket.hasLogger())this.socket.log("channel","dropping outdated message",{topic:Z,event:Q,payload:X,joinRef:J});return!1}else return!0}joinRef(){return this.joinPush.ref}rejoin(Z=this.timeout){if(this.isLeaving())return;this.socket.leaveOpenTopic(this.topic),this.state=o.joining,this.joinPush.resend(Z)}trigger(Z,Q,X,J){let G=this.onMessage(Z,Q,X,J);if(Q&&!G)throw new Error("channel onMessage callbacks must return the payload, modified or unmodified");let Y=this.bindings.filter((z)=>z.event===Z&&this.filterBindings(z,Q,X));for(let z=0;z<Y.length;z++)Y[z].callback(G,X,J||this.joinRef())}replyEventName(Z){return`chan_reply_${Z}`}isClosed(){return this.state===o.closed}isErrored(){return this.state===o.errored}isJoined(){return this.state===o.joined}isJoining(){return this.state===o.joining}isLeaving(){return this.state===o.leaving}},pZ=class{static request(Z,Q,X,J,G,Y,z){if(O0.XDomainRequest){let H=new O0.XDomainRequest;return this.xdomainRequest(H,Z,Q,J,G,Y,z)}else if(O0.XMLHttpRequest){let H=new O0.XMLHttpRequest;return this.xhrRequest(H,Z,Q,X,J,G,Y,z)}else if(O0.fetch&&O0.AbortController)return this.fetchRequest(Z,Q,X,J,G,Y,z);else throw new Error("No suitable XMLHttpRequest implementation found")}static fetchRequest(Z,Q,X,J,G,Y,z){let H={method:Z,headers:X,body:J},W=null;if(G){W=new AbortController;let q=setTimeout(()=>W.abort(),G);H.signal=W.signal}return O0.fetch(Q,H).then((q)=>q.text()).then((q)=>this.parseJSON(q)).then((q)=>z&&z(q)).catch((q)=>{if(q.name==="AbortError"&&Y)Y();else z&&z(null)}),W}static xdomainRequest(Z,Q,X,J,G,Y,z){if(Z.timeout=G,Z.open(Q,X),Z.onload=()=>{let H=this.parseJSON(Z.responseText);z&&z(H)},Y)Z.ontimeout=Y;return Z.onprogress=()=>{},Z.send(J),Z}static xhrRequest(Z,Q,X,J,G,Y,z,H){Z.open(Q,X,!0),Z.timeout=Y;for(let[W,q]of Object.entries(J))Z.setRequestHeader(W,q);if(Z.onerror=()=>H&&H(null),Z.onreadystatechange=()=>{if(Z.readyState===TX.complete&&H){let W=this.parseJSON(Z.responseText);H(W)}},z)Z.ontimeout=z;return Z.send(G),Z}static parseJSON(Z){if(!Z||Z==="")return null;try{return JSON.parse(Z)}catch{return console&&console.log("failed to parse JSON response",Z),null}}static serialize(Z,Q){let X=[];for(var J in Z){if(!Object.prototype.hasOwnProperty.call(Z,J))continue;let G=Q?`${Q}[${J}]`:J,Y=Z[J];if(typeof Y==="object")X.push(this.serialize(Y,G));else X.push(encodeURIComponent(G)+"="+encodeURIComponent(Y))}return X.join("&")}static appendParams(Z,Q){if(Object.keys(Q).length===0)return Z;let X=Z.match(/\?/)?"&":"?";return`${Z}${X}${this.serialize(Q)}`}},EX=(Z)=>{let Q="",X=new Uint8Array(Z),J=X.byteLength;for(let G=0;G<J;G++)Q+=String.fromCharCode(X[G]);return btoa(Q)},_0=class{constructor(Z,Q){if(Q&&Q.length===2&&Q[1].startsWith(fQ))this.authToken=atob(Q[1].slice(fQ.length));this.endPoint=null,this.token=null,this.skipHeartbeat=!0,this.reqs=new Set,this.awaitingBatchAck=!1,this.currentBatch=null,this.currentBatchTimer=null,this.batchBuffer=[],this.onopen=function(){},this.onerror=function(){},this.onmessage=function(){},this.onclose=function(){},this.pollEndpoint=this.normalizeEndpoint(Z),this.readyState=M0.connecting,setTimeout(()=>this.poll(),0)}normalizeEndpoint(Z){return Z.replace("ws://","http://").replace("wss://","https://").replace(new RegExp("(.*)/"+vQ.websocket),"$1/"+vQ.longpoll)}endpointURL(){return pZ.appendParams(this.pollEndpoint,{token:this.token})}closeAndRetry(Z,Q,X){this.close(Z,Q,X),this.readyState=M0.connecting}ontimeout(){this.onerror("timeout"),this.closeAndRetry(1005,"timeout",!1)}isActive(){return this.readyState===M0.open||this.readyState===M0.connecting}poll(){let Z={Accept:"application/json"};if(this.authToken)Z["X-Phoenix-AuthToken"]=this.authToken;this.ajax("GET",Z,null,()=>this.ontimeout(),(Q)=>{if(Q){var{status:X,token:J,messages:G}=Q;if(X===410&&this.token!==null){this.onerror(410),this.closeAndRetry(3410,"session_gone",!1);return}this.token=J}else X=0;switch(X){case 200:G.forEach((Y)=>{setTimeout(()=>this.onmessage({data:Y}),0)}),this.poll();break;case 204:this.poll();break;case 410:this.readyState=M0.open,this.onopen({}),this.poll();break;case 403:this.onerror(403),this.close(1008,"forbidden",!1);break;case 0:case 500:this.onerror(500),this.closeAndRetry(1011,"internal server error",500);break;default:throw new Error(`unhandled poll status ${X}`)}})}send(Z){if(typeof Z!=="string")Z=EX(Z);if(this.currentBatch)this.currentBatch.push(Z);else if(this.awaitingBatchAck)this.batchBuffer.push(Z);else this.currentBatch=[Z],this.currentBatchTimer=setTimeout(()=>{this.batchSend(this.currentBatch),this.currentBatch=null},0)}batchSend(Z){this.awaitingBatchAck=!0,this.ajax("POST",{"Content-Type":"application/x-ndjson"},Z.join(`
11
+ `),()=>this.onerror("timeout"),(Q)=>{if(this.awaitingBatchAck=!1,!Q||Q.status!==200)this.onerror(Q&&Q.status),this.closeAndRetry(1011,"internal server error",!1);else if(this.batchBuffer.length>0)this.batchSend(this.batchBuffer),this.batchBuffer=[]})}close(Z,Q,X){for(let G of this.reqs)G.abort();this.readyState=M0.closed;let J=Object.assign({code:1000,reason:void 0,wasClean:!0},{code:Z,reason:Q,wasClean:X});if(this.batchBuffer=[],clearTimeout(this.currentBatchTimer),this.currentBatchTimer=null,typeof CloseEvent!=="undefined")this.onclose(new CloseEvent("close",J));else this.onclose(J)}ajax(Z,Q,X,J,G){let Y,z=()=>{this.reqs.delete(Y),J()};Y=pZ.request(Z,this.endpointURL(),Q,X,this.timeout,z,(H)=>{if(this.reqs.delete(Y),this.isActive())G(H)}),this.reqs.add(Y)}},b8=class Z{constructor(Q,X={}){let J=X.events||{state:"presence_state",diff:"presence_diff"};this.state={},this.pendingDiffs=[],this.channel=Q,this.joinRef=null,this.caller={onJoin:function(){},onLeave:function(){},onSync:function(){}},this.channel.on(J.state,(G)=>{let{onJoin:Y,onLeave:z,onSync:H}=this.caller;this.joinRef=this.channel.joinRef(),this.state=Z.syncState(this.state,G,Y,z),this.pendingDiffs.forEach((W)=>{this.state=Z.syncDiff(this.state,W,Y,z)}),this.pendingDiffs=[],H()}),this.channel.on(J.diff,(G)=>{let{onJoin:Y,onLeave:z,onSync:H}=this.caller;if(this.inPendingSyncState())this.pendingDiffs.push(G);else this.state=Z.syncDiff(this.state,G,Y,z),H()})}onJoin(Q){this.caller.onJoin=Q}onLeave(Q){this.caller.onLeave=Q}onSync(Q){this.caller.onSync=Q}list(Q){return Z.list(this.state,Q)}inPendingSyncState(){return!this.joinRef||this.joinRef!==this.channel.joinRef()}static syncState(Q,X,J,G){let Y=this.clone(Q),z={},H={};return this.map(Y,(W,q)=>{if(!X[W])H[W]=q}),this.map(X,(W,q)=>{let O=Y[W];if(O){let M=q.metas.map((w)=>w.phx_ref),U=O.metas.map((w)=>w.phx_ref),$=q.metas.filter((w)=>U.indexOf(w.phx_ref)<0),K=O.metas.filter((w)=>M.indexOf(w.phx_ref)<0);if($.length>0)z[W]=q,z[W].metas=$;if(K.length>0)H[W]=this.clone(O),H[W].metas=K}else z[W]=q}),this.syncDiff(Y,{joins:z,leaves:H},J,G)}static syncDiff(Q,X,J,G){let{joins:Y,leaves:z}=this.clone(X);if(!J)J=function(){};if(!G)G=function(){};return this.map(Y,(H,W)=>{let q=Q[H];if(Q[H]=this.clone(W),q){let O=Q[H].metas.map((U)=>U.phx_ref),M=q.metas.filter((U)=>O.indexOf(U.phx_ref)<0);Q[H].metas.unshift(...M)}J(H,q,W)}),this.map(z,(H,W)=>{let q=Q[H];if(!q)return;let O=W.metas.map((M)=>M.phx_ref);if(q.metas=q.metas.filter((M)=>{return O.indexOf(M.phx_ref)<0}),G(H,q,W),q.metas.length===0)delete Q[H]}),Q}static list(Q,X){if(!X)X=function(J,G){return G};return this.map(Q,(J,G)=>{return X(J,G)})}static map(Q,X){return Object.getOwnPropertyNames(Q).map((J)=>X(J,Q[J]))}static clone(Q){return JSON.parse(JSON.stringify(Q))}},lZ={HEADER_LENGTH:1,META_LENGTH:4,KINDS:{push:0,reply:1,broadcast:2},encode(Z,Q){if(Z.payload.constructor===ArrayBuffer)return Q(this.binaryEncode(Z));else{let X=[Z.join_ref,Z.ref,Z.topic,Z.event,Z.payload];return Q(JSON.stringify(X))}},decode(Z,Q){if(Z.constructor===ArrayBuffer)return Q(this.binaryDecode(Z));else{let[X,J,G,Y,z]=JSON.parse(Z);return Q({join_ref:X,ref:J,topic:G,event:Y,payload:z})}},binaryEncode(Z){let{join_ref:Q,ref:X,event:J,topic:G,payload:Y}=Z,z=this.META_LENGTH+Q.length+X.length+G.length+J.length,H=new ArrayBuffer(this.HEADER_LENGTH+z),W=new DataView(H),q=0;W.setUint8(q++,this.KINDS.push),W.setUint8(q++,Q.length),W.setUint8(q++,X.length),W.setUint8(q++,G.length),W.setUint8(q++,J.length),Array.from(Q,(M)=>W.setUint8(q++,M.charCodeAt(0))),Array.from(X,(M)=>W.setUint8(q++,M.charCodeAt(0))),Array.from(G,(M)=>W.setUint8(q++,M.charCodeAt(0))),Array.from(J,(M)=>W.setUint8(q++,M.charCodeAt(0)));var O=new Uint8Array(H.byteLength+Y.byteLength);return O.set(new Uint8Array(H),0),O.set(new Uint8Array(Y),H.byteLength),O.buffer},binaryDecode(Z){let Q=new DataView(Z),X=Q.getUint8(0),J=new TextDecoder;switch(X){case this.KINDS.push:return this.decodePush(Z,Q,J);case this.KINDS.reply:return this.decodeReply(Z,Q,J);case this.KINDS.broadcast:return this.decodeBroadcast(Z,Q,J)}},decodePush(Z,Q,X){let J=Q.getUint8(1),G=Q.getUint8(2),Y=Q.getUint8(3),z=this.HEADER_LENGTH+this.META_LENGTH-1,H=X.decode(Z.slice(z,z+J));z=z+J;let W=X.decode(Z.slice(z,z+G));z=z+G;let q=X.decode(Z.slice(z,z+Y));z=z+Y;let O=Z.slice(z,Z.byteLength);return{join_ref:H,ref:null,topic:W,event:q,payload:O}},decodeReply(Z,Q,X){let J=Q.getUint8(1),G=Q.getUint8(2),Y=Q.getUint8(3),z=Q.getUint8(4),H=this.HEADER_LENGTH+this.META_LENGTH,W=X.decode(Z.slice(H,H+J));H=H+J;let q=X.decode(Z.slice(H,H+G));H=H+G;let O=X.decode(Z.slice(H,H+Y));H=H+Y;let M=X.decode(Z.slice(H,H+z));H=H+z;let U=Z.slice(H,Z.byteLength),$={status:M,response:U};return{join_ref:W,ref:q,topic:O,event:F0.reply,payload:$}},decodeBroadcast(Z,Q,X){let J=Q.getUint8(1),G=Q.getUint8(2),Y=this.HEADER_LENGTH+2,z=X.decode(Z.slice(Y,Y+J));Y=Y+J;let H=X.decode(Z.slice(Y,Y+G));Y=Y+G;let W=Z.slice(Y,Z.byteLength);return{join_ref:null,ref:null,topic:z,event:H,payload:W}}},y8=class{constructor(Z,Q={}){if(this.stateChangeCallbacks={open:[],close:[],error:[],message:[]},this.channels=[],this.sendBuffer=[],this.ref=0,this.fallbackRef=null,this.timeout=Q.timeout||xX,this.transport=Q.transport||O0.WebSocket||_0,this.conn=void 0,this.primaryPassedHealthCheck=!1,this.longPollFallbackMs=Q.longPollFallbackMs,this.fallbackTimer=null,this.sessionStore=Q.sessionStorage||O0&&O0.sessionStorage,this.establishedConnections=0,this.defaultEncoder=lZ.encode.bind(lZ),this.defaultDecoder=lZ.decode.bind(lZ),this.closeWasClean=!0,this.disconnecting=!1,this.binaryType=Q.binaryType||"arraybuffer",this.connectClock=1,this.pageHidden=!1,this.encode=void 0,this.decode=void 0,this.transport!==_0)this.encode=Q.encode||this.defaultEncoder,this.decode=Q.decode||this.defaultDecoder;else this.encode=this.defaultEncoder,this.decode=this.defaultDecoder;let X=null;if(h0&&h0.addEventListener)h0.addEventListener("pagehide",(J)=>{if(this.conn)this.disconnect(),X=this.connectClock}),h0.addEventListener("pageshow",(J)=>{if(X===this.connectClock)X=null,this.connect()}),h0.addEventListener("visibilitychange",()=>{if(document.visibilityState==="hidden")this.pageHidden=!0;else if(this.pageHidden=!1,!this.isConnected()&&!this.closeWasClean)this.teardown(()=>this.connect())});if(this.heartbeatIntervalMs=Q.heartbeatIntervalMs||30000,this.autoSendHeartbeat=Q.autoSendHeartbeat??!0,this.heartbeatCallback=Q.heartbeatCallback??(()=>{}),this.rejoinAfterMs=(J)=>{if(Q.rejoinAfterMs)return Q.rejoinAfterMs(J);else return[1000,2000,5000][J-1]||1e4},this.reconnectAfterMs=(J)=>{if(Q.reconnectAfterMs)return Q.reconnectAfterMs(J);else return[10,50,100,150,200,250,500,1000,2000][J-1]||5000},this.logger=Q.logger||null,!this.logger&&Q.debug)this.logger=(J,G,Y)=>{console.log(`${J}: ${G}`,Y)};this.longpollerTimeout=Q.longpollerTimeout||20000,this.params=JZ(Q.params||{}),this.endPoint=`${Z}/${vQ.websocket}`,this.vsn=Q.vsn||jX,this.heartbeatTimeoutTimer=null,this.heartbeatTimer=null,this.heartbeatSentAt=null,this.pendingHeartbeatRef=null,this.reconnectTimer=new f8(()=>{if(this.pageHidden){this.log("Not reconnecting as page is hidden!"),this.teardown();return}this.teardown(async()=>{if(Q.beforeReconnect)await Q.beforeReconnect();this.connect()})},this.reconnectAfterMs),this.authToken=Q.authToken}getLongPollTransport(){return _0}replaceTransport(Z){if(this.connectClock++,this.closeWasClean=!0,clearTimeout(this.fallbackTimer),this.reconnectTimer.reset(),this.conn)this.conn.close(),this.conn=null;this.transport=Z}protocol(){return location.protocol.match(/^https/)?"wss":"ws"}endPointURL(){let Z=pZ.appendParams(pZ.appendParams(this.endPoint,this.params()),{vsn:this.vsn});if(Z.charAt(0)!=="/")return Z;if(Z.charAt(1)==="/")return`${this.protocol()}:${Z}`;return`${this.protocol()}://${location.host}${Z}`}disconnect(Z,Q,X){this.connectClock++,this.disconnecting=!0,this.closeWasClean=!0,clearTimeout(this.fallbackTimer),this.reconnectTimer.reset(),this.teardown(()=>{this.disconnecting=!1,Z&&Z()},Q,X)}connect(Z){if(Z)console&&console.log("passing params to connect is deprecated. Instead pass :params to the Socket constructor"),this.params=JZ(Z);if(this.conn&&!this.disconnecting)return;if(this.longPollFallbackMs&&this.transport!==_0)this.connectWithFallback(_0,this.longPollFallbackMs);else this.transportConnect()}log(Z,Q,X){this.logger&&this.logger(Z,Q,X)}hasLogger(){return this.logger!==null}onOpen(Z){let Q=this.makeRef();return this.stateChangeCallbacks.open.push([Q,Z]),Q}onClose(Z){let Q=this.makeRef();return this.stateChangeCallbacks.close.push([Q,Z]),Q}onError(Z){let Q=this.makeRef();return this.stateChangeCallbacks.error.push([Q,Z]),Q}onMessage(Z){let Q=this.makeRef();return this.stateChangeCallbacks.message.push([Q,Z]),Q}onHeartbeat(Z){this.heartbeatCallback=Z}ping(Z){if(!this.isConnected())return!1;let Q=this.makeRef(),X=Date.now();this.push({topic:"phoenix",event:"heartbeat",payload:{},ref:Q});let J=this.onMessage((G)=>{if(G.ref===Q)this.off([J]),Z(Date.now()-X)});return!0}transportName(Z){switch(Z){case _0:return"LongPoll";default:return Z.name}}transportConnect(){this.connectClock++,this.closeWasClean=!1;let Z=void 0;if(this.authToken)Z=["phoenix",`${fQ}${btoa(this.authToken).replace(/=/g,"")}`];this.conn=new this.transport(this.endPointURL(),Z),this.conn.binaryType=this.binaryType,this.conn.timeout=this.longpollerTimeout,this.conn.onopen=()=>this.onConnOpen(),this.conn.onerror=(Q)=>this.onConnError(Q),this.conn.onmessage=(Q)=>this.onConnMessage(Q),this.conn.onclose=(Q)=>this.onConnClose(Q)}getSession(Z){return this.sessionStore&&this.sessionStore.getItem(Z)}storeSession(Z,Q){this.sessionStore&&this.sessionStore.setItem(Z,Q)}connectWithFallback(Z,Q=2500){clearTimeout(this.fallbackTimer);let X=!1,J=!0,G,Y,z=this.transportName(Z),H=(W)=>{this.log("transport",`falling back to ${z}...`,W),this.off([G,Y]),J=!1,this.replaceTransport(Z),this.transportConnect()};if(this.getSession(`phx:fallback:${z}`))return H("memorized");if(this.fallbackTimer=setTimeout(H,Q),Y=this.onError((W)=>{if(this.log("transport","error",W),J&&!X)clearTimeout(this.fallbackTimer),H(W)}),this.fallbackRef)this.off([this.fallbackRef]);this.fallbackRef=this.onOpen(()=>{if(X=!0,!J){let W=this.transportName(Z);if(!this.primaryPassedHealthCheck)this.storeSession(`phx:fallback:${W}`,"true");return this.log("transport",`established ${W} fallback`)}clearTimeout(this.fallbackTimer),this.fallbackTimer=setTimeout(H,Q),this.ping((W)=>{this.log("transport","connected to primary after",W),this.primaryPassedHealthCheck=!0,clearTimeout(this.fallbackTimer)})}),this.transportConnect()}clearHeartbeats(){clearTimeout(this.heartbeatTimer),clearTimeout(this.heartbeatTimeoutTimer)}onConnOpen(){if(this.hasLogger())this.log("transport",`connected to ${this.endPointURL()}`);if(this.closeWasClean=!1,this.disconnecting=!1,this.establishedConnections++,this.flushSendBuffer(),this.reconnectTimer.reset(),this.autoSendHeartbeat)this.resetHeartbeat();this.triggerStateCallbacks("open")}heartbeatTimeout(){if(this.pendingHeartbeatRef){if(this.pendingHeartbeatRef=null,this.heartbeatSentAt=null,this.hasLogger())this.log("transport","heartbeat timeout. Attempting to re-establish connection");try{this.heartbeatCallback("timeout")}catch(Z){this.log("error","error in heartbeat callback",Z)}this.triggerChanError(),this.closeWasClean=!1,this.teardown(()=>this.reconnectTimer.scheduleTimeout(),SX,"heartbeat timeout")}}resetHeartbeat(){if(this.conn&&this.conn.skipHeartbeat)return;this.pendingHeartbeatRef=null,this.clearHeartbeats(),this.heartbeatTimer=setTimeout(()=>this.sendHeartbeat(),this.heartbeatIntervalMs)}teardown(Z,Q,X){if(!this.conn)return Z&&Z();let J=this.conn;this.waitForBufferDone(J,()=>{if(Q)J.close(Q,X||"");else J.close();this.waitForSocketClosed(J,()=>{if(this.conn===J)this.conn.onopen=function(){},this.conn.onerror=function(){},this.conn.onmessage=function(){},this.conn.onclose=function(){},this.conn=null;Z&&Z()})})}waitForBufferDone(Z,Q,X=1){if(X===5||!Z.bufferedAmount){Q();return}setTimeout(()=>{this.waitForBufferDone(Z,Q,X+1)},150*X)}waitForSocketClosed(Z,Q,X=1){if(X===5||Z.readyState===M0.closed){Q();return}setTimeout(()=>{this.waitForSocketClosed(Z,Q,X+1)},150*X)}onConnClose(Z){if(this.conn)this.conn.onclose=()=>{};if(this.hasLogger())this.log("transport","close",Z);if(this.triggerChanError(),this.clearHeartbeats(),!this.closeWasClean)this.reconnectTimer.scheduleTimeout();this.triggerStateCallbacks("close",Z)}onConnError(Z){if(this.hasLogger())this.log("transport",Z);let Q=this.transport,X=this.establishedConnections;if(this.triggerStateCallbacks("error",Z,Q,X),Q===this.transport||X>0)this.triggerChanError()}triggerChanError(){this.channels.forEach((Z)=>{if(!(Z.isErrored()||Z.isLeaving()||Z.isClosed()))Z.trigger(F0.error)})}connectionState(){switch(this.conn&&this.conn.readyState){case M0.connecting:return"connecting";case M0.open:return"open";case M0.closing:return"closing";default:return"closed"}}isConnected(){return this.connectionState()==="open"}remove(Z){this.off(Z.stateChangeRefs),this.channels=this.channels.filter((Q)=>Q!==Z)}off(Z){for(let Q in this.stateChangeCallbacks)this.stateChangeCallbacks[Q]=this.stateChangeCallbacks[Q].filter(([X])=>{return Z.indexOf(X)===-1})}channel(Z,Q={}){let X=new kX(Z,Q,this);return this.channels.push(X),X}push(Z){if(this.hasLogger()){let{topic:Q,event:X,payload:J,ref:G,join_ref:Y}=Z;this.log("push",`${Q} ${X} (${Y}, ${G})`,J)}if(this.isConnected())this.encode(Z,(Q)=>this.conn.send(Q));else this.sendBuffer.push(()=>this.encode(Z,(Q)=>this.conn.send(Q)))}makeRef(){let Z=this.ref+1;if(Z===this.ref)this.ref=0;else this.ref=Z;return this.ref.toString()}sendHeartbeat(){if(!this.isConnected()){try{this.heartbeatCallback("disconnected")}catch(Z){this.log("error","error in heartbeat callback",Z)}return}if(this.pendingHeartbeatRef){this.heartbeatTimeout();return}this.pendingHeartbeatRef=this.makeRef(),this.heartbeatSentAt=Date.now(),this.push({topic:"phoenix",event:"heartbeat",payload:{},ref:this.pendingHeartbeatRef});try{this.heartbeatCallback("sent")}catch(Z){this.log("error","error in heartbeat callback",Z)}this.heartbeatTimeoutTimer=setTimeout(()=>this.heartbeatTimeout(),this.heartbeatIntervalMs)}flushSendBuffer(){if(this.isConnected()&&this.sendBuffer.length>0)this.sendBuffer.forEach((Z)=>Z()),this.sendBuffer=[]}onConnMessage(Z){this.decode(Z.data,(Q)=>{let{topic:X,event:J,payload:G,ref:Y,join_ref:z}=Q;if(Y&&Y===this.pendingHeartbeatRef){let H=this.heartbeatSentAt?Date.now()-this.heartbeatSentAt:void 0;this.clearHeartbeats();try{this.heartbeatCallback(G.status==="ok"?"ok":"error",H)}catch(W){this.log("error","error in heartbeat callback",W)}if(this.pendingHeartbeatRef=null,this.heartbeatSentAt=null,this.autoSendHeartbeat)this.heartbeatTimer=setTimeout(()=>this.sendHeartbeat(),this.heartbeatIntervalMs)}if(this.hasLogger())this.log("receive",`${G.status||""} ${X} ${J} ${Y&&"("+Y+")"||""}`.trim(),G);for(let H=0;H<this.channels.length;H++){let W=this.channels[H];if(!W.isMember(X,J,G,z))continue;W.trigger(J,G,Y,z)}this.triggerStateCallbacks("message",Q)})}triggerStateCallbacks(Z,...Q){try{this.stateChangeCallbacks[Z].forEach(([X,J])=>{try{J(...Q)}catch(G){this.log("error",`error in ${Z} callback`,G)}})}catch(X){this.log("error",`error triggering ${Z} callbacks`,X)}}leaveOpenTopic(Z){let Q=this.channels.find((X)=>X.topic===Z&&(X.isJoined()||X.isJoining()));if(Q){if(this.hasLogger())this.log("transport",`leaving duplicate topic "${Z}"`);Q.leave()}}};class P0{constructor(Z,Q){let X=fX(Q);this.presence=new b8(Z.getChannel(),X),this.presence.onJoin((J,G,Y)=>{let z=P0.onJoinPayload(J,G,Y);Z.getChannel().trigger("presence",z)}),this.presence.onLeave((J,G,Y)=>{let z=P0.onLeavePayload(J,G,Y);Z.getChannel().trigger("presence",z)}),this.presence.onSync(()=>{Z.getChannel().trigger("presence",{event:"sync"})})}get state(){return P0.transformState(this.presence.state)}static transformState(Z){return Z=vX(Z),Object.getOwnPropertyNames(Z).reduce((Q,X)=>{let J=Z[X];return Q[X]=iZ(J),Q},{})}static onJoinPayload(Z,Q,X){let J=g8(Q),G=iZ(X);return{event:"join",key:Z,currentPresences:J,newPresences:G}}static onLeavePayload(Z,Q,X){let J=g8(Q),G=iZ(X);return{event:"leave",key:Z,currentPresences:J,leftPresences:G}}}function iZ(Z){return Z.metas.map((Q)=>{return Q.presence_ref=Q.phx_ref,delete Q.phx_ref,delete Q.phx_ref_prev,Q})}function vX(Z){return JSON.parse(JSON.stringify(Z))}function fX(Z){return(Z===null||Z===void 0?void 0:Z.events)&&{events:Z.events}}function g8(Z){return(Z===null||Z===void 0?void 0:Z.metas)?iZ(Z):[]}var bQ;(function(Z){Z.SYNC="sync",Z.JOIN="join",Z.LEAVE="leave"})(bQ||(bQ={}));class YZ{get state(){return this.presenceAdapter.state}constructor(Z,Q){this.channel=Z,this.presenceAdapter=new P0(this.channel.channelAdapter,Q)}}class nZ{constructor(Z,Q,X){let J=bX(X);this.channel=Z.getSocket().channel(Q,J),this.socket=Z}get state(){return this.channel.state}set state(Z){this.channel.state=Z}get joinedOnce(){return this.channel.joinedOnce}get joinPush(){return this.channel.joinPush}get rejoinTimer(){return this.channel.rejoinTimer}on(Z,Q){return this.channel.on(Z,Q)}off(Z,Q){this.channel.off(Z,Q)}subscribe(Z){return this.channel.join(Z)}unsubscribe(Z){return this.channel.leave(Z)}teardown(){this.channel.teardown()}onClose(Z){this.channel.onClose(Z)}onError(Z){return this.channel.onError(Z)}push(Z,Q,X){let J;try{J=this.channel.push(Z,Q,X)}catch(G){throw new Error(`tried to push '${Z}' to '${this.channel.topic}' before joining. Use channel.subscribe() before pushing events`)}if(this.channel.pushBuffer.length>E8){let G=this.channel.pushBuffer.shift();G.cancelTimeout(),this.socket.log("channel",`discarded push due to buffer overflow: ${G.event}`,G.payload())}return J}updateJoinPayload(Z){let Q=this.channel.joinPush.payload();this.channel.joinPush.payload=()=>Object.assign(Object.assign({},Q),Z)}canPush(){return this.socket.isConnected()&&this.state===q0.joined}isJoined(){return this.state===q0.joined}isJoining(){return this.state===q0.joining}isClosed(){return this.state===q0.closed}isLeaving(){return this.state===q0.leaving}updateFilterBindings(Z){this.channel.filterBindings=Z}updatePayloadTransform(Z){this.channel.onMessage=Z}getChannel(){return this.channel}}function bX(Z){return{config:Object.assign({broadcast:{ack:!1,self:!1},presence:{key:"",enabled:!1},private:!1},Z.config)}}var yQ;(function(Z){Z.ALL="*",Z.INSERT="INSERT",Z.UPDATE="UPDATE",Z.DELETE="DELETE"})(yQ||(yQ={}));var A0;(function(Z){Z.BROADCAST="broadcast",Z.PRESENCE="presence",Z.POSTGRES_CHANGES="postgres_changes",Z.SYSTEM="system"})(A0||(A0={}));var U0;(function(Z){Z.SUBSCRIBED="SUBSCRIBED",Z.TIMED_OUT="TIMED_OUT",Z.CLOSED="CLOSED",Z.CHANNEL_ERROR="CHANNEL_ERROR"})(U0||(U0={}));class L0{get state(){return this.channelAdapter.state}set state(Z){this.channelAdapter.state=Z}get joinedOnce(){return this.channelAdapter.joinedOnce}get timeout(){return this.socket.timeout}get joinPush(){return this.channelAdapter.joinPush}get rejoinTimer(){return this.channelAdapter.rejoinTimer}constructor(Z,Q={config:{}},X){var J,G;if(this.topic=Z,this.params=Q,this.socket=X,this.bindings={},this.subTopic=Z.replace(/^realtime:/i,""),this.params.config=Object.assign({broadcast:{ack:!1,self:!1},presence:{key:"",enabled:!1},private:!1},Q.config),this.channelAdapter=new nZ(this.socket.socketAdapter,Z,this.params),this.presence=new YZ(this),this._onClose(()=>{this.socket._remove(this)}),this._updateFilterTransform(),this.broadcastEndpointURL=dZ(this.socket.socketAdapter.endPointURL()),this.private=this.params.config.private||!1,!this.private&&((G=(J=this.params.config)===null||J===void 0?void 0:J.broadcast)===null||G===void 0?void 0:G.replay))throw new Error(`tried to use replay on public channel '${this.topic}'. It must be a private channel.`)}subscribe(Z,Q=this.timeout){var X,J,G;if(!this.socket.isConnected())this.socket.connect();if(this.channelAdapter.isClosed()){let{config:{broadcast:Y,presence:z,private:H}}=this.params,W=(J=(X=this.bindings.postgres_changes)===null||X===void 0?void 0:X.map((U)=>U.filter))!==null&&J!==void 0?J:[],q=!!this.bindings[A0.PRESENCE]&&this.bindings[A0.PRESENCE].length>0||((G=this.params.config.presence)===null||G===void 0?void 0:G.enabled)===!0,O={},M={broadcast:Y,presence:Object.assign(Object.assign({},z),{enabled:q}),postgres_changes:W,private:H};if(this.socket.accessTokenValue)O.access_token=this.socket.accessTokenValue;this._onError((U)=>{Z===null||Z===void 0||Z(U0.CHANNEL_ERROR,U)}),this._onClose(()=>Z===null||Z===void 0?void 0:Z(U0.CLOSED)),this.updateJoinPayload(Object.assign({config:M},O)),this._updateFilterMessage(),this.channelAdapter.subscribe(Q).receive("ok",async({postgres_changes:U})=>{if(!this.socket._isManualToken())this.socket.setAuth();if(U===void 0){Z===null||Z===void 0||Z(U0.SUBSCRIBED);return}this._updatePostgresBindings(U,Z)}).receive("error",(U)=>{this.state=q0.errored,Z===null||Z===void 0||Z(U0.CHANNEL_ERROR,new Error(JSON.stringify(Object.values(U).join(", ")||"error")))}).receive("timeout",()=>{Z===null||Z===void 0||Z(U0.TIMED_OUT)})}return this}_updatePostgresBindings(Z,Q){var X;let J=this.bindings.postgres_changes,G=(X=J===null||J===void 0?void 0:J.length)!==null&&X!==void 0?X:0,Y=[];for(let z=0;z<G;z++){let H=J[z],{filter:{event:W,schema:q,table:O,filter:M}}=H,U=Z&&Z[z];if(U&&U.event===W&&L0.isFilterValueEqual(U.schema,q)&&L0.isFilterValueEqual(U.table,O)&&L0.isFilterValueEqual(U.filter,M))Y.push(Object.assign(Object.assign({},H),{id:U.id}));else{this.unsubscribe(),this.state=q0.errored,Q===null||Q===void 0||Q(U0.CHANNEL_ERROR,new Error("mismatch between server and client bindings for postgres changes"));return}}if(this.bindings.postgres_changes=Y,this.state!=q0.errored&&Q)Q(U0.SUBSCRIBED)}presenceState(){return this.presence.state}async track(Z,Q={}){return await this.send({type:"presence",event:"track",payload:Z},Q.timeout||this.timeout)}async untrack(Z={}){return await this.send({type:"presence",event:"untrack"},Z)}on(Z,Q,X){let J=this.channelAdapter.isJoined()||this.channelAdapter.isJoining(),G=Z===A0.PRESENCE||Z===A0.POSTGRES_CHANGES;if(J&&G)throw this.socket.log("channel",`cannot add \`${Z}\` callbacks for ${this.topic} after \`subscribe()\`.`),new Error(`cannot add \`${Z}\` callbacks for ${this.topic} after \`subscribe()\`.`);return this._on(Z,Q,X)}async httpSend(Z,Q,X={}){var J;if(Q===void 0||Q===null)return Promise.reject(new Error("Payload is required for httpSend()"));let G={apikey:this.socket.apiKey?this.socket.apiKey:"","Content-Type":"application/json"};if(this.socket.accessTokenValue)G.Authorization=`Bearer ${this.socket.accessTokenValue}`;let Y={method:"POST",headers:G,body:JSON.stringify({messages:[{topic:this.subTopic,event:Z,payload:Q,private:this.private}]})},z=await this._fetchWithTimeout(this.broadcastEndpointURL,Y,(J=X.timeout)!==null&&J!==void 0?J:this.timeout);if(z.status===202)return{success:!0};let H=z.statusText;try{let W=await z.json();H=W.error||W.message||H}catch(W){}return Promise.reject(new Error(H))}async send(Z,Q={}){var X,J;if(!this.channelAdapter.canPush()&&Z.type==="broadcast"){console.warn("Realtime send() is automatically falling back to REST API. This behavior will be deprecated in the future. Please use httpSend() explicitly for REST delivery.");let{event:G,payload:Y}=Z,z={apikey:this.socket.apiKey?this.socket.apiKey:"","Content-Type":"application/json"};if(this.socket.accessTokenValue)z.Authorization=`Bearer ${this.socket.accessTokenValue}`;let H={method:"POST",headers:z,body:JSON.stringify({messages:[{topic:this.subTopic,event:G,payload:Y,private:this.private}]})};try{let W=await this._fetchWithTimeout(this.broadcastEndpointURL,H,(X=Q.timeout)!==null&&X!==void 0?X:this.timeout);return await((J=W.body)===null||J===void 0?void 0:J.cancel()),W.ok?"ok":"error"}catch(W){if(W.name==="AbortError")return"timed out";else return"error"}}else return new Promise((G)=>{var Y,z,H;let W=this.channelAdapter.push(Z.type,Z,Q.timeout||this.timeout);if(Z.type==="broadcast"&&!((H=(z=(Y=this.params)===null||Y===void 0?void 0:Y.config)===null||z===void 0?void 0:z.broadcast)===null||H===void 0?void 0:H.ack))G("ok");W.receive("ok",()=>G("ok")),W.receive("error",()=>G("error")),W.receive("timeout",()=>G("timed out"))})}updateJoinPayload(Z){this.channelAdapter.updateJoinPayload(Z)}async unsubscribe(Z=this.timeout){return new Promise((Q)=>{this.channelAdapter.unsubscribe(Z).receive("ok",()=>Q("ok")).receive("timeout",()=>Q("timed out")).receive("error",()=>Q("error"))})}teardown(){this.channelAdapter.teardown()}async _fetchWithTimeout(Z,Q,X){let J=new AbortController,G=setTimeout(()=>J.abort(),X),Y=await this.socket.fetch(Z,Object.assign(Object.assign({},Q),{signal:J.signal}));return clearTimeout(G),Y}_on(Z,Q,X){let J=Z.toLocaleLowerCase(),G=this.channelAdapter.on(Z,X),Y={type:J,filter:Q,callback:X,ref:G};if(this.bindings[J])this.bindings[J].push(Y);else this.bindings[J]=[Y];return this._updateFilterMessage(),this}_onClose(Z){this.channelAdapter.onClose(Z)}_onError(Z){this.channelAdapter.onError(Z)}_updateFilterMessage(){this.channelAdapter.updateFilterBindings((Z,Q,X)=>{var J,G,Y,z,H,W,q;let O=Z.event.toLocaleLowerCase();if(this._notThisChannelEvent(O,X))return!1;let M=(J=this.bindings[O])===null||J===void 0?void 0:J.find((U)=>U.ref===Z.ref);if(!M)return!0;if(["broadcast","presence","postgres_changes"].includes(O))if("id"in M){let U=M.id,$=(G=M.filter)===null||G===void 0?void 0:G.event;return U&&((Y=Q.ids)===null||Y===void 0?void 0:Y.includes(U))&&($==="*"||($===null||$===void 0?void 0:$.toLocaleLowerCase())===((z=Q.data)===null||z===void 0?void 0:z.type.toLocaleLowerCase()))}else{let U=(W=(H=M===null||M===void 0?void 0:M.filter)===null||H===void 0?void 0:H.event)===null||W===void 0?void 0:W.toLocaleLowerCase();return U==="*"||U===((q=Q===null||Q===void 0?void 0:Q.event)===null||q===void 0?void 0:q.toLocaleLowerCase())}else return M.type.toLocaleLowerCase()===O})}_notThisChannelEvent(Z,Q){let{close:X,error:J,leave:G,join:Y}=mZ;return Q&&[X,J,G,Y].includes(Z)&&Q!==this.joinPush.ref}_updateFilterTransform(){this.channelAdapter.updatePayloadTransform((Z,Q,X)=>{if(typeof Q==="object"&&"ids"in Q){let J=Q.data,{schema:G,table:Y,commit_timestamp:z,type:H,errors:W}=J;return Object.assign(Object.assign({},{schema:G,table:Y,commit_timestamp:z,eventType:H,new:{},old:{},errors:W}),this._getPayloadRecords(J))}return Q})}copyBindings(Z){if(this.joinedOnce)throw new Error("cannot copy bindings into joined channel");for(let Q in Z.bindings)for(let X of Z.bindings[Q])this._on(X.type,X.filter,X.callback)}static isFilterValueEqual(Z,Q){return(Z!==null&&Z!==void 0?Z:void 0)===(Q!==null&&Q!==void 0?Q:void 0)}_getPayloadRecords(Z){let Q={new:{},old:{}};if(Z.type==="INSERT"||Z.type==="UPDATE")Q.new=EQ(Z.columns,Z.record);if(Z.type==="UPDATE"||Z.type==="DELETE")Q.old=EQ(Z.columns,Z.old_record);return Q}}class aZ{constructor(Z,Q){this.socket=new y8(Z,Q)}get timeout(){return this.socket.timeout}get endPoint(){return this.socket.endPoint}get transport(){return this.socket.transport}get heartbeatIntervalMs(){return this.socket.heartbeatIntervalMs}get heartbeatCallback(){return this.socket.heartbeatCallback}set heartbeatCallback(Z){this.socket.heartbeatCallback=Z}get heartbeatTimer(){return this.socket.heartbeatTimer}get pendingHeartbeatRef(){return this.socket.pendingHeartbeatRef}get reconnectTimer(){return this.socket.reconnectTimer}get vsn(){return this.socket.vsn}get encode(){return this.socket.encode}get decode(){return this.socket.decode}get reconnectAfterMs(){return this.socket.reconnectAfterMs}get sendBuffer(){return this.socket.sendBuffer}get stateChangeCallbacks(){return this.socket.stateChangeCallbacks}connect(){this.socket.connect()}disconnect(Z,Q,X,J=1e4){return new Promise((G)=>{setTimeout(()=>G("timeout"),J),this.socket.disconnect(()=>{Z(),G("ok")},Q,X)})}push(Z){this.socket.push(Z)}log(Z,Q,X){this.socket.log(Z,Q,X)}makeRef(){return this.socket.makeRef()}onOpen(Z){this.socket.onOpen(Z)}onClose(Z){this.socket.onClose(Z)}onError(Z){this.socket.onError(Z)}onMessage(Z){this.socket.onMessage(Z)}isConnected(){return this.socket.isConnected()}isConnecting(){return this.socket.connectionState()==XZ.connecting}isDisconnecting(){return this.socket.connectionState()==XZ.closing}connectionState(){return this.socket.connectionState()}endPointURL(){return this.socket.endPointURL()}sendHeartbeat(){this.socket.sendHeartbeat()}getSocket(){return this.socket}}var _8={HEARTBEAT_INTERVAL:25000,RECONNECT_DELAY:10,HEARTBEAT_TIMEOUT_FALLBACK:100},yX=[1000,2000,5000,1e4],gX=1e4,_X=`
12
+ addEventListener("message", (e) => {
13
+ if (e.data.event === "start") {
14
+ setInterval(() => postMessage({ event: "keepAlive" }), e.data.interval);
15
+ }
16
+ });`;class GZ{get endPoint(){return this.socketAdapter.endPoint}get timeout(){return this.socketAdapter.timeout}get transport(){return this.socketAdapter.transport}get heartbeatCallback(){return this.socketAdapter.heartbeatCallback}get heartbeatIntervalMs(){return this.socketAdapter.heartbeatIntervalMs}get heartbeatTimer(){if(this.worker)return this._workerHeartbeatTimer;return this.socketAdapter.heartbeatTimer}get pendingHeartbeatRef(){if(this.worker)return this._pendingWorkerHeartbeatRef;return this.socketAdapter.pendingHeartbeatRef}get reconnectTimer(){return this.socketAdapter.reconnectTimer}get vsn(){return this.socketAdapter.vsn}get encode(){return this.socketAdapter.encode}get decode(){return this.socketAdapter.decode}get reconnectAfterMs(){return this.socketAdapter.reconnectAfterMs}get sendBuffer(){return this.socketAdapter.sendBuffer}get stateChangeCallbacks(){return this.socketAdapter.stateChangeCallbacks}constructor(Z,Q){var X;if(this.channels=new Array,this.accessTokenValue=null,this.accessToken=null,this.apiKey=null,this.httpEndpoint="",this.headers={},this.params={},this.ref=0,this.serializer=new uZ,this._manuallySetToken=!1,this._authPromise=null,this._workerHeartbeatTimer=void 0,this._pendingWorkerHeartbeatRef=null,this._pendingDisconnectTimer=null,this._disconnectOnEmptyChannelsAfterMs=0,this._resolveFetch=(G)=>{if(G)return(...Y)=>G(...Y);return(...Y)=>fetch(...Y)},!((X=Q===null||Q===void 0?void 0:Q.params)===null||X===void 0?void 0:X.apikey))throw new Error("API key is required to connect to Realtime");this.apiKey=Q.params.apikey;let J=this._initializeOptions(Q);this.socketAdapter=new aZ(Z,J),this.httpEndpoint=dZ(Z),this.fetch=this._resolveFetch(Q===null||Q===void 0?void 0:Q.fetch)}connect(){if(this.isConnecting()||this.isDisconnecting()||this.isConnected())return;if(this.accessToken&&!this._authPromise)this._setAuthSafely("connect");this._setupConnectionHandlers();try{this.socketAdapter.connect()}catch(Z){let Q=Z.message;if(Q.includes("Node.js"))throw new Error(`${Q}
17
+
18
+ To use Realtime in Node.js, you need to provide a WebSocket implementation:
19
+
20
+ Option 1: Use Node.js 22+ which has native WebSocket support
21
+ Option 2: Install and provide the "ws" package:
22
+
23
+ npm install ws
24
+
25
+ import ws from "ws"
26
+ const client = new RealtimeClient(url, {
27
+ ...options,
28
+ transport: ws
29
+ })`);throw new Error(`WebSocket not available: ${Q}`)}this._handleNodeJsRaceCondition()}endpointURL(){return this.socketAdapter.endPointURL()}async disconnect(Z,Q){if(this._cancelPendingDisconnect(),this.isDisconnecting())return"ok";return await this.socketAdapter.disconnect(()=>{clearInterval(this._workerHeartbeatTimer),this._terminateWorker()},Z,Q)}getChannels(){return this.channels}async removeChannel(Z){let Q=await Z.unsubscribe();if(Q==="ok")Z.teardown();return Q}async removeAllChannels(){let Z=this.channels.map(async(X)=>{let J=await X.unsubscribe();return X.teardown(),J}),Q=await Promise.all(Z);return await this.disconnect(),Q}log(Z,Q,X){this.socketAdapter.log(Z,Q,X)}connectionState(){return this.socketAdapter.connectionState()||XZ.closed}isConnected(){return this.socketAdapter.isConnected()}isConnecting(){return this.socketAdapter.isConnecting()}isDisconnecting(){return this.socketAdapter.isDisconnecting()}channel(Z,Q={config:{}}){let X=`realtime:${Z}`,J=this.getChannels().find((G)=>G.topic===X);if(!J){let G=new L0(`realtime:${Z}`,Q,this);return this._cancelPendingDisconnect(),this.channels.push(G),G}else return J}push(Z){this.socketAdapter.push(Z)}async setAuth(Z=null){this._authPromise=this._performAuth(Z);try{await this._authPromise}finally{this._authPromise=null}}_isManualToken(){return this._manuallySetToken}async sendHeartbeat(){this.socketAdapter.sendHeartbeat()}onHeartbeat(Z){this.socketAdapter.heartbeatCallback=this._wrapHeartbeatCallback(Z)}_makeRef(){return this.socketAdapter.makeRef()}_remove(Z){if(this.channels=this.channels.filter((Q)=>Q.topic!==Z.topic),this.channels.length===0)this.log("transport","no channels remaining, scheduling disconnect"),this._schedulePendingDisconnect()}_schedulePendingDisconnect(){if(this._cancelPendingDisconnect(),this._disconnectOnEmptyChannelsAfterMs===0){this.log("transport","disconnecting immediately - no channels"),this.disconnect();return}this._pendingDisconnectTimer=setTimeout(()=>{if(this._pendingDisconnectTimer=null,this.channels.length===0)this.log("transport","deferred disconnect fired - no channels, disconnecting"),this.disconnect()},this._disconnectOnEmptyChannelsAfterMs),this.log("transport",`deferred disconnect scheduled in ${this._disconnectOnEmptyChannelsAfterMs}ms`)}_cancelPendingDisconnect(){if(this._pendingDisconnectTimer!==null)this.log("transport","pending disconnect cancelled - channel activity detected"),clearTimeout(this._pendingDisconnectTimer),this._pendingDisconnectTimer=null}async _performAuth(Z=null){let Q,X=!1;if(Z)Q=Z,X=!0;else if(this.accessToken)try{Q=await this.accessToken()}catch(J){this.log("error","Error fetching access token from callback",J),Q=this.accessTokenValue}else Q=this.accessTokenValue;if(X)this._manuallySetToken=!0;else if(this.accessToken)this._manuallySetToken=!1;if(this.accessTokenValue!=Q)this.accessTokenValue=Q,this.channels.forEach((J)=>{let G={access_token:Q,version:x8};if(Q&&J.updateJoinPayload(G),J.joinedOnce&&J.channelAdapter.isJoined())J.channelAdapter.push(mZ.access_token,{access_token:Q})})}async _waitForAuthIfNeeded(){if(this._authPromise)await this._authPromise}_setAuthSafely(Z="general"){if(!this._isManualToken())this.setAuth().catch((Q)=>{this.log("error",`Error setting auth in ${Z}`,Q)})}_setupConnectionHandlers(){this.socketAdapter.onOpen(()=>{if((this._authPromise||(this.accessToken&&!this.accessTokenValue?this.setAuth():Promise.resolve())).catch((Q)=>{this.log("error","error waiting for auth on connect",Q)}),this.worker&&!this.workerRef)this._startWorkerHeartbeat()}),this.socketAdapter.onClose(()=>{if(this.worker&&this.workerRef)this._terminateWorker()}),this.socketAdapter.onMessage((Z)=>{if(Z.ref&&Z.ref===this._pendingWorkerHeartbeatRef)this._pendingWorkerHeartbeatRef=null})}_handleNodeJsRaceCondition(){if(this.socketAdapter.isConnected())this.socketAdapter.getSocket().onConnOpen()}_wrapHeartbeatCallback(Z){return(Q,X)=>{if(Q=="sent")this._setAuthSafely();if(Z)Z(Q,X)}}_startWorkerHeartbeat(){if(this.workerUrl)this.log("worker",`starting worker for from ${this.workerUrl}`);else this.log("worker","starting default worker");let Z=this._workerObjectUrl(this.workerUrl);this.workerRef=new Worker(Z),this.workerRef.onerror=(Q)=>{this.log("worker","worker error",Q.message),this._terminateWorker(),this.disconnect()},this.workerRef.onmessage=(Q)=>{if(Q.data.event==="keepAlive")this.sendHeartbeat()},this.workerRef.postMessage({event:"start",interval:this.heartbeatIntervalMs})}_terminateWorker(){if(this.workerRef)this.log("worker","terminating worker"),this.workerRef.terminate(),this.workerRef=void 0}_workerObjectUrl(Z){let Q;if(Z)Q=Z;else{let X=new Blob([_X],{type:"application/javascript"});Q=URL.createObjectURL(X)}return Q}_initializeOptions(Z){var Q,X,J,G,Y,z,H,W,q,O,M;this.worker=(Q=Z===null||Z===void 0?void 0:Z.worker)!==null&&Q!==void 0?Q:!1,this.accessToken=(X=Z===null||Z===void 0?void 0:Z.accessToken)!==null&&X!==void 0?X:null;let U={};U.timeout=(J=Z===null||Z===void 0?void 0:Z.timeout)!==null&&J!==void 0?J:k8,U.heartbeatIntervalMs=(G=Z===null||Z===void 0?void 0:Z.heartbeatIntervalMs)!==null&&G!==void 0?G:_8.HEARTBEAT_INTERVAL,this._disconnectOnEmptyChannelsAfterMs=(Y=Z===null||Z===void 0?void 0:Z.disconnectOnEmptyChannelsAfterMs)!==null&&Y!==void 0?Y:2*((z=Z===null||Z===void 0?void 0:Z.heartbeatIntervalMs)!==null&&z!==void 0?z:_8.HEARTBEAT_INTERVAL),U.transport=(H=Z===null||Z===void 0?void 0:Z.transport)!==null&&H!==void 0?H:SQ.getWebSocketConstructor(),U.params=Z===null||Z===void 0?void 0:Z.params,U.logger=Z===null||Z===void 0?void 0:Z.logger,U.heartbeatCallback=this._wrapHeartbeatCallback(Z===null||Z===void 0?void 0:Z.heartbeatCallback),U.reconnectAfterMs=(W=Z===null||Z===void 0?void 0:Z.reconnectAfterMs)!==null&&W!==void 0?W:(V)=>{return yX[V-1]||gX};let $,K,w=(q=Z===null||Z===void 0?void 0:Z.vsn)!==null&&q!==void 0?q:T8;switch(w){case S8:$=(V,B)=>{return B(JSON.stringify(V))},K=(V,B)=>{return B(JSON.parse(V))};break;case TQ:$=this.serializer.encode.bind(this.serializer),K=this.serializer.decode.bind(this.serializer);break;default:throw new Error(`Unsupported serializer version: ${U.vsn}`)}if(U.vsn=w,U.encode=(O=Z===null||Z===void 0?void 0:Z.encode)!==null&&O!==void 0?O:$,U.decode=(M=Z===null||Z===void 0?void 0:Z.decode)!==null&&M!==void 0?M:K,U.beforeReconnect=this._reconnectAuth.bind(this),(Z===null||Z===void 0?void 0:Z.logLevel)||(Z===null||Z===void 0?void 0:Z.log_level))this.logLevel=Z.logLevel||Z.log_level,U.params=Object.assign(Object.assign({},U.params),{log_level:this.logLevel});if(this.worker){if(typeof window!=="undefined"&&!window.Worker)throw new Error("Web Worker is not supported");this.workerUrl=Z===null||Z===void 0?void 0:Z.workerUrl,U.autoSendHeartbeat=!this.worker}return U}async _reconnectAuth(){if(await this._waitForAuthIfNeeded(),!this.isConnected())this.connect()}}var zZ=class extends Error{constructor(Z,Q){super(Z);this.name="IcebergError",this.status=Q.status,this.icebergType=Q.icebergType,this.icebergCode=Q.icebergCode,this.details=Q.details,this.isCommitStateUnknown=Q.icebergType==="CommitStateUnknownException"||[500,502,504].includes(Q.status)&&Q.icebergType?.includes("CommitState")===!0}isNotFound(){return this.status===404}isConflict(){return this.status===409}isAuthenticationTimeout(){return this.status===419}};function hX(Z,Q,X){let J=new URL(Q,Z);if(X){for(let[G,Y]of Object.entries(X))if(Y!==void 0)J.searchParams.set(G,Y)}return J.toString()}async function mX(Z){if(!Z||Z.type==="none")return{};if(Z.type==="bearer")return{Authorization:`Bearer ${Z.token}`};if(Z.type==="header")return{[Z.name]:Z.value};if(Z.type==="custom")return await Z.getHeaders();return{}}function uX(Z){let Q=Z.fetchImpl??globalThis.fetch;return{async request({method:X,path:J,query:G,body:Y,headers:z}){let H=hX(Z.baseUrl,J,G),W=await mX(Z.auth),q=await Q(H,{method:X,headers:{...Y?{"Content-Type":"application/json"}:{},...W,...z},body:Y?JSON.stringify(Y):void 0}),O=await q.text(),M=(q.headers.get("content-type")||"").includes("application/json"),U=M&&O?JSON.parse(O):O;if(!q.ok){let $=M?U:void 0,K=$?.error;throw new zZ(K?.message??`Request failed with status ${q.status}`,{status:q.status,icebergType:K?.type,icebergCode:K?.code,details:$})}return{status:q.status,headers:q.headers,data:U}}}}function sZ(Z){return Z.join("\x1F")}var dX=class{constructor(Z,Q=""){this.client=Z,this.prefix=Q}async listNamespaces(Z){let Q=Z?{parent:sZ(Z.namespace)}:void 0;return(await this.client.request({method:"GET",path:`${this.prefix}/namespaces`,query:Q})).data.namespaces.map((J)=>({namespace:J}))}async createNamespace(Z,Q){let X={namespace:Z.namespace,properties:Q?.properties};return(await this.client.request({method:"POST",path:`${this.prefix}/namespaces`,body:X})).data}async dropNamespace(Z){await this.client.request({method:"DELETE",path:`${this.prefix}/namespaces/${sZ(Z.namespace)}`})}async loadNamespaceMetadata(Z){return{properties:(await this.client.request({method:"GET",path:`${this.prefix}/namespaces/${sZ(Z.namespace)}`})).data.properties}}async namespaceExists(Z){try{return await this.client.request({method:"HEAD",path:`${this.prefix}/namespaces/${sZ(Z.namespace)}`}),!0}catch(Q){if(Q instanceof zZ&&Q.status===404)return!1;throw Q}}async createNamespaceIfNotExists(Z,Q){try{return await this.createNamespace(Z,Q)}catch(X){if(X instanceof zZ&&X.status===409)return;throw X}}};function m0(Z){return Z.join("\x1F")}var cX=class{constructor(Z,Q="",X){this.client=Z,this.prefix=Q,this.accessDelegation=X}async listTables(Z){return(await this.client.request({method:"GET",path:`${this.prefix}/namespaces/${m0(Z.namespace)}/tables`})).data.identifiers}async createTable(Z,Q){let X={};if(this.accessDelegation)X["X-Iceberg-Access-Delegation"]=this.accessDelegation;return(await this.client.request({method:"POST",path:`${this.prefix}/namespaces/${m0(Z.namespace)}/tables`,body:Q,headers:X})).data.metadata}async updateTable(Z,Q){let X=await this.client.request({method:"POST",path:`${this.prefix}/namespaces/${m0(Z.namespace)}/tables/${Z.name}`,body:Q});return{"metadata-location":X.data["metadata-location"],metadata:X.data.metadata}}async dropTable(Z,Q){await this.client.request({method:"DELETE",path:`${this.prefix}/namespaces/${m0(Z.namespace)}/tables/${Z.name}`,query:{purgeRequested:String(Q?.purge??!1)}})}async loadTable(Z){let Q={};if(this.accessDelegation)Q["X-Iceberg-Access-Delegation"]=this.accessDelegation;return(await this.client.request({method:"GET",path:`${this.prefix}/namespaces/${m0(Z.namespace)}/tables/${Z.name}`,headers:Q})).data.metadata}async tableExists(Z){let Q={};if(this.accessDelegation)Q["X-Iceberg-Access-Delegation"]=this.accessDelegation;try{return await this.client.request({method:"HEAD",path:`${this.prefix}/namespaces/${m0(Z.namespace)}/tables/${Z.name}`,headers:Q}),!0}catch(X){if(X instanceof zZ&&X.status===404)return!1;throw X}}async createTableIfNotExists(Z,Q){try{return await this.createTable(Z,Q)}catch(X){if(X instanceof zZ&&X.status===409)return await this.loadTable({namespace:Z.namespace,name:Q.name});throw X}}},h8=class{constructor(Z){let Q="v1";if(Z.catalogName)Q+=`/${Z.catalogName}`;let X=Z.baseUrl.endsWith("/")?Z.baseUrl:`${Z.baseUrl}/`;this.client=uX({baseUrl:X,auth:Z.auth,fetchImpl:Z.fetch}),this.accessDelegation=Z.accessDelegation?.join(","),this.namespaceOps=new dX(this.client,Q),this.tableOps=new cX(this.client,Q,this.accessDelegation)}async listNamespaces(Z){return this.namespaceOps.listNamespaces(Z)}async createNamespace(Z,Q){return this.namespaceOps.createNamespace(Z,Q)}async dropNamespace(Z){await this.namespaceOps.dropNamespace(Z)}async loadNamespaceMetadata(Z){return this.namespaceOps.loadNamespaceMetadata(Z)}async listTables(Z){return this.tableOps.listTables(Z)}async createTable(Z,Q){return this.tableOps.createTable(Z,Q)}async updateTable(Z,Q){return this.tableOps.updateTable(Z,Q)}async dropTable(Z,Q){await this.tableOps.dropTable(Z,Q)}async loadTable(Z){return this.tableOps.loadTable(Z)}async namespaceExists(Z){return this.namespaceOps.namespaceExists(Z)}async tableExists(Z){return this.tableOps.tableExists(Z)}async createNamespaceIfNotExists(Z,Q){return this.namespaceOps.createNamespaceIfNotExists(Z,Q)}async createTableIfNotExists(Z,Q){return this.tableOps.createTableIfNotExists(Z,Q)}};function WZ(Z){return WZ=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(Q){return typeof Q}:function(Q){return Q&&typeof Symbol=="function"&&Q.constructor===Symbol&&Q!==Symbol.prototype?"symbol":typeof Q},WZ(Z)}function lX(Z,Q){if(WZ(Z)!="object"||!Z)return Z;var X=Z[Symbol.toPrimitive];if(X!==void 0){var J=X.call(Z,Q||"default");if(WZ(J)!="object")return J;throw new TypeError("@@toPrimitive must return a primitive value.")}return(Q==="string"?String:Number)(Z)}function pX(Z){var Q=lX(Z,"string");return WZ(Q)=="symbol"?Q:Q+""}function iX(Z,Q,X){return(Q=pX(Q))in Z?Object.defineProperty(Z,Q,{value:X,enumerable:!0,configurable:!0,writable:!0}):Z[Q]=X,Z}function m8(Z,Q){var X=Object.keys(Z);if(Object.getOwnPropertySymbols){var J=Object.getOwnPropertySymbols(Z);Q&&(J=J.filter(function(G){return Object.getOwnPropertyDescriptor(Z,G).enumerable})),X.push.apply(X,J)}return X}function S(Z){for(var Q=1;Q<arguments.length;Q++){var X=arguments[Q]!=null?arguments[Q]:{};Q%2?m8(Object(X),!0).forEach(function(J){iX(Z,J,X[J])}):Object.getOwnPropertyDescriptors?Object.defineProperties(Z,Object.getOwnPropertyDescriptors(X)):m8(Object(X)).forEach(function(J){Object.defineProperty(Z,J,Object.getOwnPropertyDescriptor(X,J))})}return Z}var rZ=class extends Error{constructor(Z,Q="storage",X,J){super(Z);this.__isStorageError=!0,this.namespace=Q,this.name=Q==="vectors"?"StorageVectorsError":"StorageError",this.status=X,this.statusCode=J}toJSON(){return{name:this.name,message:this.message,status:this.status,statusCode:this.statusCode}}};function eZ(Z){return typeof Z==="object"&&Z!==null&&"__isStorageError"in Z}var oZ=class extends rZ{constructor(Z,Q,X,J="storage"){super(Z,J,Q,X);this.name=J==="vectors"?"StorageVectorsApiError":"StorageApiError",this.status=Q,this.statusCode=X}toJSON(){return S({},super.toJSON())}},c8=class extends rZ{constructor(Z,Q,X="storage"){super(Z,X);this.name=X==="vectors"?"StorageVectorsUnknownError":"StorageUnknownError",this.originalError=Q}};function tZ(Z,Q,X){let J=S({},Z),G=Q.toLowerCase();for(let Y of Object.keys(J))if(Y.toLowerCase()===G)delete J[Y];return J[G]=X,J}function nX(Z){let Q={};for(let[X,J]of Object.entries(Z))Q[X.toLowerCase()]=J;return Q}var aX=(Z)=>{if(Z)return(...Q)=>Z(...Q);return(...Q)=>fetch(...Q)},sX=(Z)=>{if(typeof Z!=="object"||Z===null)return!1;let Q=Object.getPrototypeOf(Z);return(Q===null||Q===Object.prototype||Object.getPrototypeOf(Q)===null)&&!(Symbol.toStringTag in Z)&&!(Symbol.iterator in Z)},gQ=(Z)=>{if(Array.isArray(Z))return Z.map((X)=>gQ(X));else if(typeof Z==="function"||Z!==Object(Z))return Z;let Q={};return Object.entries(Z).forEach(([X,J])=>{let G=X.replace(/([-_][a-z])/gi,(Y)=>Y.toUpperCase().replace(/[-_]/g,""));Q[G]=gQ(J)}),Q},oX=(Z)=>{if(!Z||typeof Z!=="string")return!1;if(Z.length===0||Z.length>100)return!1;if(Z.trim()!==Z)return!1;if(Z.includes("/")||Z.includes("\\"))return!1;return/^[\w!.\*'() &$@=;:+,?-]+$/.test(Z)},u8=(Z)=>{var Q;return Z.msg||Z.message||Z.error_description||(typeof Z.error==="string"?Z.error:(Q=Z.error)===null||Q===void 0?void 0:Q.message)||JSON.stringify(Z)},tX=async(Z,Q,X,J)=>{if(Z!==null&&typeof Z==="object"&&typeof Z.json==="function"){let G=Z,Y=parseInt(G.status,10);if(!Number.isFinite(Y))Y=500;G.json().then((z)=>{let H=(z===null||z===void 0?void 0:z.statusCode)||(z===null||z===void 0?void 0:z.code)||Y+"";Q(new oZ(u8(z),Y,H,J))}).catch(()=>{let z=Y+"";Q(new oZ(G.statusText||`HTTP ${Y} error`,Y,z,J))})}else Q(new c8(u8(Z),Z,J))},rX=(Z,Q,X,J)=>{let G={method:Z,headers:(Q===null||Q===void 0?void 0:Q.headers)||{}};if(Z==="GET"||Z==="HEAD"||!J)return S(S({},G),X);if(sX(J)){var Y;let z=(Q===null||Q===void 0?void 0:Q.headers)||{},H;for(let[W,q]of Object.entries(z))if(W.toLowerCase()==="content-type")H=q;G.headers=tZ(z,"Content-Type",(Y=H)!==null&&Y!==void 0?Y:"application/json"),G.body=JSON.stringify(J)}else G.body=J;if(Q===null||Q===void 0?void 0:Q.duplex)G.duplex=Q.duplex;return S(S({},G),X)};async function HZ(Z,Q,X,J,G,Y,z){return new Promise((H,W)=>{Z(X,rX(Q,J,G,Y)).then((q)=>{if(!q.ok)throw q;if(J===null||J===void 0?void 0:J.noResolveJson)return q;if(z==="vectors"){let O=q.headers.get("content-type");if(q.headers.get("content-length")==="0"||q.status===204)return{};if(!O||!O.includes("application/json"))return{}}return q.json()}).then((q)=>H(q)).catch((q)=>tX(q,W,J,z))})}function l8(Z="storage"){return{get:async(Q,X,J,G)=>{return HZ(Q,"GET",X,J,G,void 0,Z)},post:async(Q,X,J,G,Y)=>{return HZ(Q,"POST",X,G,Y,J,Z)},put:async(Q,X,J,G,Y)=>{return HZ(Q,"PUT",X,G,Y,J,Z)},head:async(Q,X,J,G)=>{return HZ(Q,"HEAD",X,S(S({},J),{},{noResolveJson:!0}),G,void 0,Z)},remove:async(Q,X,J,G,Y)=>{return HZ(Q,"DELETE",X,G,Y,J,Z)}}}var eX=l8("storage"),{get:qZ,post:Y0,put:_Q,head:Z9,remove:hQ}=eX,r=l8("vectors"),u0=class{constructor(Z,Q={},X,J="storage"){this.shouldThrowOnError=!1,this.url=Z,this.headers=nX(Q),this.fetch=aX(X),this.namespace=J}throwOnError(){return this.shouldThrowOnError=!0,this}setHeader(Z,Q){return this.headers=tZ(this.headers,Z,Q),this}async handleOperation(Z){var Q=this;try{return{data:await Z(),error:null}}catch(X){if(Q.shouldThrowOnError)throw X;if(eZ(X))return{data:null,error:X};throw X}}},Q9=class{constructor(Z,Q){this.downloadFn=Z,this.shouldThrowOnError=Q}then(Z,Q){return this.execute().then(Z,Q)}async execute(){var Z=this;try{return{data:(await Z.downloadFn()).body,error:null}}catch(Q){if(Z.shouldThrowOnError)throw Q;if(eZ(Q))return{data:null,error:Q};throw Q}}},p8;p8=Symbol.toStringTag;var X9=class{constructor(Z,Q){this.downloadFn=Z,this.shouldThrowOnError=Q,this[p8]="BlobDownloadBuilder",this.promise=null}asStream(){return new Q9(this.downloadFn,this.shouldThrowOnError)}then(Z,Q){return this.getPromise().then(Z,Q)}catch(Z){return this.getPromise().catch(Z)}finally(Z){return this.getPromise().finally(Z)}getPromise(){if(!this.promise)this.promise=this.execute();return this.promise}async execute(){var Z=this;try{return{data:await(await Z.downloadFn()).blob(),error:null}}catch(Q){if(Z.shouldThrowOnError)throw Q;if(eZ(Q))return{data:null,error:Q};throw Q}}},J9={limit:100,offset:0,sortBy:{column:"name",order:"asc"}},d8={cacheControl:"3600",contentType:"text/plain;charset=UTF-8",upsert:!1},Y9=class extends u0{constructor(Z,Q={},X,J){super(Z,Q,J,"storage");this.bucketId=X}async uploadOrUpdate(Z,Q,X,J){var G=this;return G.handleOperation(async()=>{let Y,z=S(S({},d8),J),H=S(S({},G.headers),Z==="POST"&&{"x-upsert":String(z.upsert)}),W=z.metadata;if(typeof Blob!=="undefined"&&X instanceof Blob){if(Y=new FormData,Y.append("cacheControl",z.cacheControl),W)Y.append("metadata",G.encodeMetadata(W));Y.append("",X)}else if(typeof FormData!=="undefined"&&X instanceof FormData){if(Y=X,!Y.has("cacheControl"))Y.append("cacheControl",z.cacheControl);if(W&&!Y.has("metadata"))Y.append("metadata",G.encodeMetadata(W))}else{if(Y=X,H["cache-control"]=`max-age=${z.cacheControl}`,H["content-type"]=z.contentType,W)H["x-metadata"]=G.toBase64(G.encodeMetadata(W));if((typeof ReadableStream!=="undefined"&&Y instanceof ReadableStream||Y&&typeof Y==="object"&&("pipe"in Y)&&typeof Y.pipe==="function")&&!z.duplex)z.duplex="half"}if(J===null||J===void 0?void 0:J.headers)for(let[U,$]of Object.entries(J.headers))H=tZ(H,U,$);let q=G._removeEmptyFolders(Q),O=G._getFinalPath(q),M=await(Z=="PUT"?_Q:Y0)(G.fetch,`${G.url}/object/${O}`,Y,S({headers:H},(z===null||z===void 0?void 0:z.duplex)?{duplex:z.duplex}:{}));return{path:q,id:M.Id,fullPath:M.Key}})}async upload(Z,Q,X){return this.uploadOrUpdate("POST",Z,Q,X)}async uploadToSignedUrl(Z,Q,X,J){var G=this;let Y=G._removeEmptyFolders(Z),z=G._getFinalPath(Y),H=new URL(G.url+`/object/upload/sign/${z}`);return H.searchParams.set("token",Q),G.handleOperation(async()=>{let W,q=S(S({},d8),J),O=S(S({},G.headers),{"x-upsert":String(q.upsert)}),M=q.metadata;if(typeof Blob!=="undefined"&&X instanceof Blob){if(W=new FormData,W.append("cacheControl",q.cacheControl),M)W.append("metadata",G.encodeMetadata(M));W.append("",X)}else if(typeof FormData!=="undefined"&&X instanceof FormData){if(W=X,!W.has("cacheControl"))W.append("cacheControl",q.cacheControl);if(M&&!W.has("metadata"))W.append("metadata",G.encodeMetadata(M))}else{if(W=X,O["cache-control"]=`max-age=${q.cacheControl}`,O["content-type"]=q.contentType,M)O["x-metadata"]=G.toBase64(G.encodeMetadata(M));if((typeof ReadableStream!=="undefined"&&W instanceof ReadableStream||W&&typeof W==="object"&&("pipe"in W)&&typeof W.pipe==="function")&&!q.duplex)q.duplex="half"}if(J===null||J===void 0?void 0:J.headers)for(let[U,$]of Object.entries(J.headers))O=tZ(O,U,$);return{path:Y,fullPath:(await _Q(G.fetch,H.toString(),W,S({headers:O},(q===null||q===void 0?void 0:q.duplex)?{duplex:q.duplex}:{}))).Key}})}async createSignedUploadUrl(Z,Q){var X=this;return X.handleOperation(async()=>{let J=X._getFinalPath(Z),G=S({},X.headers);if(Q===null||Q===void 0?void 0:Q.upsert)G["x-upsert"]="true";let Y=await Y0(X.fetch,`${X.url}/object/upload/sign/${J}`,{},{headers:G}),z=new URL(X.url+Y.url),H=z.searchParams.get("token");if(!H)throw new rZ("No token returned by API");return{signedUrl:z.toString(),path:Z,token:H}})}async update(Z,Q,X){return this.uploadOrUpdate("PUT",Z,Q,X)}async move(Z,Q,X){var J=this;return J.handleOperation(async()=>{return await Y0(J.fetch,`${J.url}/object/move`,{bucketId:J.bucketId,sourceKey:Z,destinationKey:Q,destinationBucket:X===null||X===void 0?void 0:X.destinationBucket},{headers:J.headers})})}async copy(Z,Q,X){var J=this;return J.handleOperation(async()=>{return{path:(await Y0(J.fetch,`${J.url}/object/copy`,{bucketId:J.bucketId,sourceKey:Z,destinationKey:Q,destinationBucket:X===null||X===void 0?void 0:X.destinationBucket},{headers:J.headers})).Key}})}async createSignedUrl(Z,Q,X){var J=this;return J.handleOperation(async()=>{let G=J._getFinalPath(Z),Y=typeof(X===null||X===void 0?void 0:X.transform)==="object"&&X.transform!==null&&Object.keys(X.transform).length>0,z=await Y0(J.fetch,`${J.url}/object/sign/${G}`,S({expiresIn:Q},Y?{transform:X.transform}:{}),{headers:J.headers}),H=new URLSearchParams;if(X===null||X===void 0?void 0:X.download)H.set("download",X.download===!0?"":X.download);if((X===null||X===void 0?void 0:X.cacheNonce)!=null)H.set("cacheNonce",String(X.cacheNonce));let W=H.toString();return{signedUrl:encodeURI(`${J.url}${z.signedURL}${W?`&${W}`:""}`)}})}async createSignedUrls(Z,Q,X){var J=this;return J.handleOperation(async()=>{let G=await Y0(J.fetch,`${J.url}/object/sign/${J.bucketId}`,{expiresIn:Q,paths:Z},{headers:J.headers}),Y=new URLSearchParams;if(X===null||X===void 0?void 0:X.download)Y.set("download",X.download===!0?"":X.download);if((X===null||X===void 0?void 0:X.cacheNonce)!=null)Y.set("cacheNonce",String(X.cacheNonce));let z=Y.toString();return G.map((H)=>S(S({},H),{},{signedUrl:H.signedURL?encodeURI(`${J.url}${H.signedURL}${z?`&${z}`:""}`):null}))})}download(Z,Q,X){let J=typeof(Q===null||Q===void 0?void 0:Q.transform)==="object"&&Q.transform!==null&&Object.keys(Q.transform).length>0?"render/image/authenticated":"object",G=new URLSearchParams;if(Q===null||Q===void 0?void 0:Q.transform)this.applyTransformOptsToQuery(G,Q.transform);if((Q===null||Q===void 0?void 0:Q.cacheNonce)!=null)G.set("cacheNonce",String(Q.cacheNonce));let Y=G.toString(),z=this._getFinalPath(Z);return new X9(()=>qZ(this.fetch,`${this.url}/${J}/${z}${Y?`?${Y}`:""}`,{headers:this.headers,noResolveJson:!0},X),this.shouldThrowOnError)}async info(Z){var Q=this;let X=Q._getFinalPath(Z);return Q.handleOperation(async()=>{return gQ(await qZ(Q.fetch,`${Q.url}/object/info/${X}`,{headers:Q.headers}))})}async exists(Z){var Q=this;let X=Q._getFinalPath(Z);try{return await Z9(Q.fetch,`${Q.url}/object/${X}`,{headers:Q.headers}),{data:!0,error:null}}catch(G){if(Q.shouldThrowOnError)throw G;if(eZ(G)){var J;let Y=G instanceof oZ?G.status:G instanceof c8?(J=G.originalError)===null||J===void 0?void 0:J.status:void 0;if(Y!==void 0&&[400,404].includes(Y))return{data:!1,error:G}}throw G}}getPublicUrl(Z,Q){let X=this._getFinalPath(Z),J=new URLSearchParams;if(Q===null||Q===void 0?void 0:Q.download)J.set("download",Q.download===!0?"":Q.download);if(Q===null||Q===void 0?void 0:Q.transform)this.applyTransformOptsToQuery(J,Q.transform);if((Q===null||Q===void 0?void 0:Q.cacheNonce)!=null)J.set("cacheNonce",String(Q.cacheNonce));let G=J.toString(),Y=typeof(Q===null||Q===void 0?void 0:Q.transform)==="object"&&Q.transform!==null&&Object.keys(Q.transform).length>0?"render/image":"object";return{data:{publicUrl:encodeURI(`${this.url}/${Y}/public/${X}`)+(G?`?${G}`:"")}}}async remove(Z){var Q=this;return Q.handleOperation(async()=>{return await hQ(Q.fetch,`${Q.url}/object/${Q.bucketId}`,{prefixes:Z},{headers:Q.headers})})}async list(Z,Q,X){var J=this;return J.handleOperation(async()=>{let G=S(S(S({},J9),Q),{},{prefix:Z||""});return await Y0(J.fetch,`${J.url}/object/list/${J.bucketId}`,G,{headers:J.headers},X)})}async listV2(Z,Q){var X=this;return X.handleOperation(async()=>{let J=S({},Z);return await Y0(X.fetch,`${X.url}/object/list-v2/${X.bucketId}`,J,{headers:X.headers},Q)})}encodeMetadata(Z){return JSON.stringify(Z)}toBase64(Z){if(typeof Buffer!=="undefined")return Buffer.from(Z).toString("base64");return btoa(Z)}_getFinalPath(Z){return`${this.bucketId}/${Z.replace(/^\/+/,"")}`}_removeEmptyFolders(Z){return Z.replace(/^\/|\/$/g,"").replace(/\/+/g,"/")}applyTransformOptsToQuery(Z,Q){if(Q.width)Z.set("width",Q.width.toString());if(Q.height)Z.set("height",Q.height.toString());if(Q.resize)Z.set("resize",Q.resize);if(Q.format)Z.set("format",Q.format);if(Q.quality)Z.set("quality",Q.quality.toString());return Z}},G9="2.105.0",OZ={"X-Client-Info":`storage-js/${G9}`},z9=class extends u0{constructor(Z,Q={},X,J){let G=new URL(Z);if(J===null||J===void 0?void 0:J.useNewHostname){if(/supabase\.(co|in|red)$/.test(G.hostname)&&!G.hostname.includes("storage.supabase."))G.hostname=G.hostname.replace("supabase.","storage.supabase.")}let Y=G.href.replace(/\/$/,""),z=S(S({},OZ),Q);super(Y,z,X,"storage")}async listBuckets(Z){var Q=this;return Q.handleOperation(async()=>{let X=Q.listBucketOptionsToQueryString(Z);return await qZ(Q.fetch,`${Q.url}/bucket${X}`,{headers:Q.headers})})}async getBucket(Z){var Q=this;return Q.handleOperation(async()=>{return await qZ(Q.fetch,`${Q.url}/bucket/${Z}`,{headers:Q.headers})})}async createBucket(Z,Q={public:!1}){var X=this;return X.handleOperation(async()=>{return await Y0(X.fetch,`${X.url}/bucket`,{id:Z,name:Z,type:Q.type,public:Q.public,file_size_limit:Q.fileSizeLimit,allowed_mime_types:Q.allowedMimeTypes},{headers:X.headers})})}async updateBucket(Z,Q){var X=this;return X.handleOperation(async()=>{return await _Q(X.fetch,`${X.url}/bucket/${Z}`,{id:Z,name:Z,public:Q.public,file_size_limit:Q.fileSizeLimit,allowed_mime_types:Q.allowedMimeTypes},{headers:X.headers})})}async emptyBucket(Z){var Q=this;return Q.handleOperation(async()=>{return await Y0(Q.fetch,`${Q.url}/bucket/${Z}/empty`,{},{headers:Q.headers})})}async deleteBucket(Z){var Q=this;return Q.handleOperation(async()=>{return await hQ(Q.fetch,`${Q.url}/bucket/${Z}`,{},{headers:Q.headers})})}listBucketOptionsToQueryString(Z){let Q={};if(Z){if("limit"in Z)Q.limit=String(Z.limit);if("offset"in Z)Q.offset=String(Z.offset);if(Z.search)Q.search=Z.search;if(Z.sortColumn)Q.sortColumn=Z.sortColumn;if(Z.sortOrder)Q.sortOrder=Z.sortOrder}return Object.keys(Q).length>0?"?"+new URLSearchParams(Q).toString():""}},H9=class extends u0{constructor(Z,Q={},X){let J=Z.replace(/\/$/,""),G=S(S({},OZ),Q);super(J,G,X,"storage")}async createBucket(Z){var Q=this;return Q.handleOperation(async()=>{return await Y0(Q.fetch,`${Q.url}/bucket`,{name:Z},{headers:Q.headers})})}async listBuckets(Z){var Q=this;return Q.handleOperation(async()=>{let X=new URLSearchParams;if((Z===null||Z===void 0?void 0:Z.limit)!==void 0)X.set("limit",Z.limit.toString());if((Z===null||Z===void 0?void 0:Z.offset)!==void 0)X.set("offset",Z.offset.toString());if(Z===null||Z===void 0?void 0:Z.sortColumn)X.set("sortColumn",Z.sortColumn);if(Z===null||Z===void 0?void 0:Z.sortOrder)X.set("sortOrder",Z.sortOrder);if(Z===null||Z===void 0?void 0:Z.search)X.set("search",Z.search);let J=X.toString(),G=J?`${Q.url}/bucket?${J}`:`${Q.url}/bucket`;return await qZ(Q.fetch,G,{headers:Q.headers})})}async deleteBucket(Z){var Q=this;return Q.handleOperation(async()=>{return await hQ(Q.fetch,`${Q.url}/bucket/${Z}`,{},{headers:Q.headers})})}from(Z){var Q=this;if(!oX(Z))throw new rZ("Invalid bucket name: File, folder, and bucket names must follow AWS object key naming guidelines and should avoid the use of any other characters.");let X=new h8({baseUrl:this.url,catalogName:Z,auth:{type:"custom",getHeaders:async()=>Q.headers},fetch:this.fetch}),J=this.shouldThrowOnError;return new Proxy(X,{get(G,Y){let z=G[Y];if(typeof z!=="function")return z;return async(...H)=>{try{return{data:await z.apply(G,H),error:null}}catch(W){if(J)throw W;return{data:null,error:W}}}}})}},W9=class extends u0{constructor(Z,Q={},X){let J=Z.replace(/\/$/,""),G=S(S({},OZ),{},{"Content-Type":"application/json"},Q);super(J,G,X,"vectors")}async createIndex(Z){var Q=this;return Q.handleOperation(async()=>{return await r.post(Q.fetch,`${Q.url}/CreateIndex`,Z,{headers:Q.headers})||{}})}async getIndex(Z,Q){var X=this;return X.handleOperation(async()=>{return await r.post(X.fetch,`${X.url}/GetIndex`,{vectorBucketName:Z,indexName:Q},{headers:X.headers})})}async listIndexes(Z){var Q=this;return Q.handleOperation(async()=>{return await r.post(Q.fetch,`${Q.url}/ListIndexes`,Z,{headers:Q.headers})})}async deleteIndex(Z,Q){var X=this;return X.handleOperation(async()=>{return await r.post(X.fetch,`${X.url}/DeleteIndex`,{vectorBucketName:Z,indexName:Q},{headers:X.headers})||{}})}},q9=class extends u0{constructor(Z,Q={},X){let J=Z.replace(/\/$/,""),G=S(S({},OZ),{},{"Content-Type":"application/json"},Q);super(J,G,X,"vectors")}async putVectors(Z){var Q=this;if(Z.vectors.length<1||Z.vectors.length>500)throw new Error("Vector batch size must be between 1 and 500 items");return Q.handleOperation(async()=>{return await r.post(Q.fetch,`${Q.url}/PutVectors`,Z,{headers:Q.headers})||{}})}async getVectors(Z){var Q=this;return Q.handleOperation(async()=>{return await r.post(Q.fetch,`${Q.url}/GetVectors`,Z,{headers:Q.headers})})}async listVectors(Z){var Q=this;if(Z.segmentCount!==void 0){if(Z.segmentCount<1||Z.segmentCount>16)throw new Error("segmentCount must be between 1 and 16");if(Z.segmentIndex!==void 0){if(Z.segmentIndex<0||Z.segmentIndex>=Z.segmentCount)throw new Error(`segmentIndex must be between 0 and ${Z.segmentCount-1}`)}}return Q.handleOperation(async()=>{return await r.post(Q.fetch,`${Q.url}/ListVectors`,Z,{headers:Q.headers})})}async queryVectors(Z){var Q=this;return Q.handleOperation(async()=>{return await r.post(Q.fetch,`${Q.url}/QueryVectors`,Z,{headers:Q.headers})})}async deleteVectors(Z){var Q=this;if(Z.keys.length<1||Z.keys.length>500)throw new Error("Keys batch size must be between 1 and 500 items");return Q.handleOperation(async()=>{return await r.post(Q.fetch,`${Q.url}/DeleteVectors`,Z,{headers:Q.headers})||{}})}},O9=class extends u0{constructor(Z,Q={},X){let J=Z.replace(/\/$/,""),G=S(S({},OZ),{},{"Content-Type":"application/json"},Q);super(J,G,X,"vectors")}async createBucket(Z){var Q=this;return Q.handleOperation(async()=>{return await r.post(Q.fetch,`${Q.url}/CreateVectorBucket`,{vectorBucketName:Z},{headers:Q.headers})||{}})}async getBucket(Z){var Q=this;return Q.handleOperation(async()=>{return await r.post(Q.fetch,`${Q.url}/GetVectorBucket`,{vectorBucketName:Z},{headers:Q.headers})})}async listBuckets(Z={}){var Q=this;return Q.handleOperation(async()=>{return await r.post(Q.fetch,`${Q.url}/ListVectorBuckets`,Z,{headers:Q.headers})})}async deleteBucket(Z){var Q=this;return Q.handleOperation(async()=>{return await r.post(Q.fetch,`${Q.url}/DeleteVectorBucket`,{vectorBucketName:Z},{headers:Q.headers})||{}})}},M9=class extends O9{constructor(Z,Q={}){super(Z,Q.headers||{},Q.fetch)}from(Z){return new U9(this.url,this.headers,Z,this.fetch)}async createBucket(Z){var Q=()=>super.createBucket,X=this;return Q().call(X,Z)}async getBucket(Z){var Q=()=>super.getBucket,X=this;return Q().call(X,Z)}async listBuckets(Z={}){var Q=()=>super.listBuckets,X=this;return Q().call(X,Z)}async deleteBucket(Z){var Q=()=>super.deleteBucket,X=this;return Q().call(X,Z)}},U9=class extends W9{constructor(Z,Q,X,J){super(Z,Q,J);this.vectorBucketName=X}async createIndex(Z){var Q=()=>super.createIndex,X=this;return Q().call(X,S(S({},Z),{},{vectorBucketName:X.vectorBucketName}))}async listIndexes(Z={}){var Q=()=>super.listIndexes,X=this;return Q().call(X,S(S({},Z),{},{vectorBucketName:X.vectorBucketName}))}async getIndex(Z){var Q=()=>super.getIndex,X=this;return Q().call(X,X.vectorBucketName,Z)}async deleteIndex(Z){var Q=()=>super.deleteIndex,X=this;return Q().call(X,X.vectorBucketName,Z)}index(Z){return new K9(this.url,this.headers,this.vectorBucketName,Z,this.fetch)}},K9=class extends q9{constructor(Z,Q,X,J,G){super(Z,Q,G);this.vectorBucketName=X,this.indexName=J}async putVectors(Z){var Q=()=>super.putVectors,X=this;return Q().call(X,S(S({},Z),{},{vectorBucketName:X.vectorBucketName,indexName:X.indexName}))}async getVectors(Z){var Q=()=>super.getVectors,X=this;return Q().call(X,S(S({},Z),{},{vectorBucketName:X.vectorBucketName,indexName:X.indexName}))}async listVectors(Z={}){var Q=()=>super.listVectors,X=this;return Q().call(X,S(S({},Z),{},{vectorBucketName:X.vectorBucketName,indexName:X.indexName}))}async queryVectors(Z){var Q=()=>super.queryVectors,X=this;return Q().call(X,S(S({},Z),{},{vectorBucketName:X.vectorBucketName,indexName:X.indexName}))}async deleteVectors(Z){var Q=()=>super.deleteVectors,X=this;return Q().call(X,S(S({},Z),{},{vectorBucketName:X.vectorBucketName,indexName:X.indexName}))}},i8=class extends z9{constructor(Z,Q={},X,J){super(Z,Q,X,J)}from(Z){return new Y9(this.url,this.headers,Z,this.fetch)}get vectors(){return new M9(this.url+"/vector",{headers:this.headers,fetch:this.fetch})}get analytics(){return new H9(this.url+"/iceberg",this.headers,this.fetch)}};var ZQ="2.105.0";var j0=30000,QQ=3,XQ=QQ*j0,n8="http://localhost:9999",a8="supabase.auth.token";var s8={"X-Client-Info":`gotrue-js/${ZQ}`};var MZ="X-Supabase-Api-Version",mQ={"2024-01-01":{timestamp:Date.parse("2024-01-01T00:00:00.0Z"),name:"2024-01-01"}},o8=/^([a-z0-9_-]{4})*($|[a-z0-9_-]{3}$|[a-z0-9_-]{2}$)$/i,t8=600000;class x0 extends Error{constructor(Z,Q,X){super(Z);this.__isAuthError=!0,this.name="AuthError",this.status=Q,this.code=X}toJSON(){return{name:this.name,message:this.message,status:this.status,code:this.code}}}function N(Z){return typeof Z==="object"&&Z!==null&&"__isAuthError"in Z}class uQ extends x0{constructor(Z,Q,X){super(Z,Q,X);this.name="AuthApiError",this.status=Q,this.code=X}}function r8(Z){return N(Z)&&Z.name==="AuthApiError"}class s extends x0{constructor(Z,Q){super(Z);this.name="AuthUnknownError",this.originalError=Q}}class K0 extends x0{constructor(Z,Q,X,J){super(Z,X,J);this.name=Q,this.status=X}}class c extends K0{constructor(){super("Auth session missing!","AuthSessionMissingError",400,void 0)}}function UZ(Z){return N(Z)&&Z.name==="AuthSessionMissingError"}class w0 extends K0{constructor(){super("Auth session or user missing","AuthInvalidTokenResponseError",500,void 0)}}class d0 extends K0{constructor(Z){super(Z,"AuthInvalidCredentialsError",400,void 0)}}class c0 extends K0{constructor(Z,Q=null){super(Z,"AuthImplicitGrantRedirectError",500,void 0);this.details=null,this.details=Q}toJSON(){return Object.assign(Object.assign({},super.toJSON()),{details:this.details})}}function e8(Z){return N(Z)&&Z.name==="AuthImplicitGrantRedirectError"}class JQ extends K0{constructor(Z,Q=null){super(Z,"AuthPKCEGrantCodeExchangeError",500,void 0);this.details=null,this.details=Q}toJSON(){return Object.assign(Object.assign({},super.toJSON()),{details:this.details})}}class dQ extends K0{constructor(){super("PKCE code verifier not found in storage. This can happen if the auth flow was initiated in a different browser or device, or if the storage was cleared. For SSR frameworks (Next.js, SvelteKit, etc.), use @supabase/ssr on both the server and client to store the code verifier in cookies.","AuthPKCECodeVerifierMissingError",400,"pkce_code_verifier_not_found")}}class KZ extends K0{constructor(Z,Q){super(Z,"AuthRetryableFetchError",Q,void 0)}}function YQ(Z){return N(Z)&&Z.name==="AuthRetryableFetchError"}class GQ extends K0{constructor(Z,Q,X){super(Z,"AuthWeakPasswordError",Q,"weak_password");this.reasons=X}toJSON(){return Object.assign(Object.assign({},super.toJSON()),{reasons:this.reasons})}}class l0 extends K0{constructor(Z){super(Z,"AuthInvalidJwtError",400,"invalid_jwt")}}var zQ="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_".split(""),Z6=`
30
+ \r=`.split(""),$9=(()=>{let Z=new Array(128);for(let Q=0;Q<Z.length;Q+=1)Z[Q]=-1;for(let Q=0;Q<Z6.length;Q+=1)Z[Z6[Q].charCodeAt(0)]=-2;for(let Q=0;Q<zQ.length;Q+=1)Z[zQ[Q].charCodeAt(0)]=Q;return Z})();function Q6(Z,Q,X){if(Z!==null){Q.queue=Q.queue<<8|Z,Q.queuedBits+=8;while(Q.queuedBits>=6){let J=Q.queue>>Q.queuedBits-6&63;X(zQ[J]),Q.queuedBits-=6}}else if(Q.queuedBits>0){Q.queue=Q.queue<<6-Q.queuedBits,Q.queuedBits=6;while(Q.queuedBits>=6){let J=Q.queue>>Q.queuedBits-6&63;X(zQ[J]),Q.queuedBits-=6}}}function X6(Z,Q,X){let J=$9[Z];if(J>-1){Q.queue=Q.queue<<6|J,Q.queuedBits+=6;while(Q.queuedBits>=8)X(Q.queue>>Q.queuedBits-8&255),Q.queuedBits-=8}else if(J===-2)return;else throw new Error(`Invalid Base64-URL character "${String.fromCharCode(Z)}"`)}function cQ(Z){let Q=[],X=(z)=>{Q.push(String.fromCodePoint(z))},J={utf8seq:0,codepoint:0},G={queue:0,queuedBits:0},Y=(z)=>{V9(z,J,X)};for(let z=0;z<Z.length;z+=1)X6(Z.charCodeAt(z),G,Y);return Q.join("")}function B9(Z,Q){if(Z<=127){Q(Z);return}else if(Z<=2047){Q(192|Z>>6),Q(128|Z&63);return}else if(Z<=65535){Q(224|Z>>12),Q(128|Z>>6&63),Q(128|Z&63);return}else if(Z<=1114111){Q(240|Z>>18),Q(128|Z>>12&63),Q(128|Z>>6&63),Q(128|Z&63);return}throw new Error(`Unrecognized Unicode codepoint: ${Z.toString(16)}`)}function F9(Z,Q){for(let X=0;X<Z.length;X+=1){let J=Z.charCodeAt(X);if(J>55295&&J<=56319){let G=(J-55296)*1024&65535;J=(Z.charCodeAt(X+1)-56320&65535|G)+65536,X+=1}B9(J,Q)}}function V9(Z,Q,X){if(Q.utf8seq===0){if(Z<=127){X(Z);return}for(let J=1;J<6;J+=1)if((Z>>7-J&1)===0){Q.utf8seq=J;break}if(Q.utf8seq===2)Q.codepoint=Z&31;else if(Q.utf8seq===3)Q.codepoint=Z&15;else if(Q.utf8seq===4)Q.codepoint=Z&7;else throw new Error("Invalid UTF-8 sequence");Q.utf8seq-=1}else if(Q.utf8seq>0){if(Z<=127)throw new Error("Invalid UTF-8 sequence");if(Q.codepoint=Q.codepoint<<6|Z&63,Q.utf8seq-=1,Q.utf8seq===0)X(Q.codepoint)}}function N0(Z){let Q=[],X={queue:0,queuedBits:0},J=(G)=>{Q.push(G)};for(let G=0;G<Z.length;G+=1)X6(Z.charCodeAt(G),X,J);return new Uint8Array(Q)}function J6(Z){let Q=[];return F9(Z,(X)=>Q.push(X)),new Uint8Array(Q)}function V0(Z){let Q=[],X={queue:0,queuedBits:0},J=(G)=>{Q.push(G)};return Z.forEach((G)=>Q6(G,X,J)),Q6(null,X,J),Q.join("")}function Y6(Z){return Math.round(Date.now()/1000)+Z}function G6(){return Symbol("auth-callback")}var i=()=>typeof window!=="undefined"&&typeof document!=="undefined",S0={tested:!1,writable:!1},HQ=()=>{if(!i())return!1;try{if(typeof globalThis.localStorage!=="object")return!1}catch(Q){return!1}if(S0.tested)return S0.writable;let Z=`lswt-${Math.random()}${Math.random()}`;try{globalThis.localStorage.setItem(Z,Z),globalThis.localStorage.removeItem(Z),S0.tested=!0,S0.writable=!0}catch(Q){S0.tested=!0,S0.writable=!1}return S0.writable};function z6(Z){let Q={},X=new URL(Z);if(X.hash&&X.hash[0]==="#")try{new URLSearchParams(X.hash.substring(1)).forEach((G,Y)=>{Q[Y]=G})}catch(J){}return X.searchParams.forEach((J,G)=>{Q[G]=J}),Q}var WQ=(Z)=>{if(Z)return(...Q)=>Z(...Q);return(...Q)=>fetch(...Q)},H6=(Z)=>{return typeof Z==="object"&&Z!==null&&"status"in Z&&"ok"in Z&&"json"in Z&&typeof Z.json==="function"},T0=async(Z,Q,X)=>{await Z.setItem(Q,JSON.stringify(X))},D0=async(Z,Q)=>{let X=await Z.getItem(Q);if(!X)return null;try{return JSON.parse(X)}catch(J){return X}},n=async(Z,Q)=>{await Z.removeItem(Q)};class $Z{constructor(){this.promise=new $Z.promiseConstructor((Z,Q)=>{this.resolve=Z,this.reject=Q})}}$Z.promiseConstructor=Promise;function BZ(Z){let Q=Z.split(".");if(Q.length!==3)throw new l0("Invalid JWT structure");for(let J=0;J<Q.length;J++)if(!o8.test(Q[J]))throw new l0("JWT not in base64url format");return{header:JSON.parse(cQ(Q[0])),payload:JSON.parse(cQ(Q[1])),signature:N0(Q[2]),raw:{header:Q[0],payload:Q[1]}}}async function W6(Z){return await new Promise((Q)=>{setTimeout(()=>Q(null),Z)})}function q6(Z,Q){return new Promise((J,G)=>{(async()=>{for(let Y=0;Y<1/0;Y++)try{let z=await Z(Y);if(!Q(Y,null,z)){J(z);return}}catch(z){if(!Q(Y,z)){G(z);return}}})()})}function L9(Z){return("0"+Z.toString(16)).substr(-2)}function w9(){let Q=new Uint32Array(56);if(typeof crypto==="undefined"){let G="";for(let Y=0;Y<56;Y++)G+="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~".charAt(Math.floor(Math.random()*66));return G}return crypto.getRandomValues(Q),Array.from(Q,L9).join("")}async function N9(Z){let X=new TextEncoder().encode(Z),J=await crypto.subtle.digest("SHA-256",X),G=new Uint8Array(J);return Array.from(G).map((Y)=>String.fromCharCode(Y)).join("")}async function D9(Z){if(!(typeof crypto!=="undefined"&&typeof crypto.subtle!=="undefined"&&typeof TextEncoder!=="undefined"))return console.warn("WebCrypto API is not supported. Code challenge method will default to use plain instead of sha256."),Z;let X=await N9(Z);return btoa(X).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function k0(Z,Q,X=!1){let J=w9(),G=J;if(X)G+="/recovery";await T0(Z,`${Q}-code-verifier`,G);let Y=await D9(J);return[Y,J===Y?"plain":"s256"]}var R9=/^2[0-9]{3}-(0[1-9]|1[0-2])-(0[1-9]|1[0-9]|2[0-9]|3[0-1])$/i;function O6(Z){let Q=Z.headers.get(MZ);if(!Q)return null;if(!Q.match(R9))return null;try{return new Date(`${Q}T00:00:00.0Z`)}catch(X){return null}}function M6(Z){if(!Z)throw new Error("Missing exp claim");let Q=Math.floor(Date.now()/1000);if(Z<=Q)throw new Error("JWT has expired")}function U6(Z){switch(Z){case"RS256":return{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}};case"ES256":return{name:"ECDSA",namedCurve:"P-256",hash:{name:"SHA-256"}};default:throw new Error("Invalid alg claim")}}var I9=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;function $0(Z){if(!I9.test(Z))throw new Error("@supabase/auth-js: Expected parameter to be UUID but is not")}function e(Z){if(!Z.passkey)throw new Error("@supabase/auth-js: the passkey API is experimental and disabled by default. Enable it by passing `auth: { experimental: { passkey: true } }` to createClient (or to the GoTrueClient constructor).")}function qQ(){return new Proxy({},{get:(Q,X)=>{if(X==="__isUserNotAvailableProxy")return!0;if(typeof X==="symbol"){let J=X.toString();if(J==="Symbol(Symbol.toPrimitive)"||J==="Symbol(Symbol.toStringTag)"||J==="Symbol(util.inspect.custom)")return}throw new Error(`@supabase/auth-js: client was created with userStorage option and there was no user stored in the user storage. Accessing the "${X}" property of the session object is not supported. Please use getUser() instead.`)},set:(Q,X)=>{throw new Error(`@supabase/auth-js: client was created with userStorage option and there was no user stored in the user storage. Setting the "${X}" property of the session object is not supported. Please use getUser() to fetch a user object you can manipulate.`)},deleteProperty:(Q,X)=>{throw new Error(`@supabase/auth-js: client was created with userStorage option and there was no user stored in the user storage. Deleting the "${X}" property of the session object is not supported. Please use getUser() to fetch a user object you can manipulate.`)}})}function K6(Z,Q){return new Proxy(Z,{get:(X,J,G)=>{if(J==="__isInsecureUserWarningProxy")return!0;if(typeof J==="symbol"){let Y=J.toString();if(Y==="Symbol(Symbol.toPrimitive)"||Y==="Symbol(Symbol.toStringTag)"||Y==="Symbol(util.inspect.custom)"||Y==="Symbol(nodejs.util.inspect.custom)")return Reflect.get(X,J,G)}if(!Q.value&&typeof J==="string")console.warn("Using the user object as returned from supabase.auth.getSession() or from some supabase.auth.onAuthStateChange() events could be insecure! This value comes directly from the storage medium (usually cookies on the server) and may not be authentic. Use supabase.auth.getUser() instead which authenticates the data by contacting the Supabase Auth server."),Q.value=!0;return Reflect.get(X,J,G)}})}function lQ(Z){return JSON.parse(JSON.stringify(Z))}var E0=(Z)=>Z.msg||Z.message||Z.error_description||Z.error||JSON.stringify(Z),C9=[502,503,504,520,521,522,523,524,530];async function $6(Z){var Q;if(!H6(Z))throw new KZ(E0(Z),0);if(C9.includes(Z.status))throw new KZ(E0(Z),Z.status);let X;try{X=await Z.json()}catch(Y){throw new s(E0(Y),Y)}let J=void 0,G=O6(Z);if(G&&G.getTime()>=mQ["2024-01-01"].timestamp&&typeof X==="object"&&X&&typeof X.code==="string")J=X.code;else if(typeof X==="object"&&X&&typeof X.error_code==="string")J=X.error_code;if(!J){if(typeof X==="object"&&X&&typeof X.weak_password==="object"&&X.weak_password&&Array.isArray(X.weak_password.reasons)&&X.weak_password.reasons.length&&X.weak_password.reasons.reduce((Y,z)=>Y&&typeof z==="string",!0))throw new GQ(E0(X),Z.status,X.weak_password.reasons)}else if(J==="weak_password")throw new GQ(E0(X),Z.status,((Q=X.weak_password)===null||Q===void 0?void 0:Q.reasons)||[]);else if(J==="session_not_found")throw new c;throw new uQ(E0(X),Z.status||500,J)}var P9=(Z,Q,X,J)=>{let G={method:Z,headers:(Q===null||Q===void 0?void 0:Q.headers)||{}};if(Z==="GET")return G;return G.headers=Object.assign({"Content-Type":"application/json;charset=UTF-8"},Q===null||Q===void 0?void 0:Q.headers),G.body=JSON.stringify(J),Object.assign(Object.assign({},G),X)};async function C(Z,Q,X,J){var G;let Y=Object.assign({},J===null||J===void 0?void 0:J.headers);if(!Y[MZ])Y[MZ]=mQ["2024-01-01"].name;if(J===null||J===void 0?void 0:J.jwt)Y.Authorization=`Bearer ${J.jwt}`;let z=(G=J===null||J===void 0?void 0:J.query)!==null&&G!==void 0?G:{};if(J===null||J===void 0?void 0:J.redirectTo)z.redirect_to=J.redirectTo;let H=Object.keys(z).length?"?"+new URLSearchParams(z).toString():"",W=await A9(Z,Q,X+H,{headers:Y,noResolveJson:J===null||J===void 0?void 0:J.noResolveJson},{},J===null||J===void 0?void 0:J.body);return(J===null||J===void 0?void 0:J.xform)?J===null||J===void 0?void 0:J.xform(W):{data:Object.assign({},W),error:null}}async function A9(Z,Q,X,J,G,Y){let z=P9(Q,J,G,Y),H;try{H=await Z(X,Object.assign({},z))}catch(W){throw console.error(W),new KZ(E0(W),0)}if(!H.ok)await $6(H);if(J===null||J===void 0?void 0:J.noResolveJson)return H;try{return await H.json()}catch(W){await $6(W)}}function Z0(Z){var Q;let X=null;if(j9(Z)){if(X=Object.assign({},Z),!Z.expires_at)X.expires_at=Y6(Z.expires_in)}let J=(Q=Z.user)!==null&&Q!==void 0?Q:Z;return{data:{session:X,user:J},error:null}}function pQ(Z){let Q=Z0(Z);if(!Q.error&&Z.weak_password&&typeof Z.weak_password==="object"&&Array.isArray(Z.weak_password.reasons)&&Z.weak_password.reasons.length&&Z.weak_password.message&&typeof Z.weak_password.message==="string"&&Z.weak_password.reasons.reduce((X,J)=>X&&typeof J==="string",!0))Q.data.weak_password=Z.weak_password;return Q}function B0(Z){var Q;return{data:{user:(Q=Z.user)!==null&&Q!==void 0?Q:Z},error:null}}function B6(Z){return{data:Z,error:null}}function F6(Z){let{action_link:Q,email_otp:X,hashed_token:J,redirect_to:G,verification_type:Y}=Z,z=C0(Z,["action_link","email_otp","hashed_token","redirect_to","verification_type"]),H={action_link:Q,email_otp:X,hashed_token:J,redirect_to:G,verification_type:Y},W=Object.assign({},z);return{data:{properties:H,user:W},error:null}}function iQ(Z){return Z}function j9(Z){return Z.access_token&&Z.refresh_token&&Z.expires_in}var OQ=["global","local","others"];class p0{constructor({url:Z="",headers:Q={},fetch:X,experimental:J}){this.url=Z,this.headers=Q,this.fetch=WQ(X),this.experimental=J!==null&&J!==void 0?J:{},this.mfa={listFactors:this._listFactors.bind(this),deleteFactor:this._deleteFactor.bind(this)},this.oauth={listClients:this._listOAuthClients.bind(this),createClient:this._createOAuthClient.bind(this),getClient:this._getOAuthClient.bind(this),updateClient:this._updateOAuthClient.bind(this),deleteClient:this._deleteOAuthClient.bind(this),regenerateClientSecret:this._regenerateOAuthClientSecret.bind(this)},this.customProviders={listProviders:this._listCustomProviders.bind(this),createProvider:this._createCustomProvider.bind(this),getProvider:this._getCustomProvider.bind(this),updateProvider:this._updateCustomProvider.bind(this),deleteProvider:this._deleteCustomProvider.bind(this)},this.passkey={listPasskeys:this._adminListPasskeys.bind(this),deletePasskey:this._adminDeletePasskey.bind(this)}}async signOut(Z,Q=OQ[0]){if(OQ.indexOf(Q)<0)throw new Error(`@supabase/auth-js: Parameter scope must be one of ${OQ.join(", ")}`);try{return await C(this.fetch,"POST",`${this.url}/logout?scope=${Q}`,{headers:this.headers,jwt:Z,noResolveJson:!0}),{data:null,error:null}}catch(X){if(N(X))return{data:null,error:X};throw X}}async inviteUserByEmail(Z,Q={}){try{return await C(this.fetch,"POST",`${this.url}/invite`,{body:{email:Z,data:Q.data},headers:this.headers,redirectTo:Q.redirectTo,xform:B0})}catch(X){if(N(X))return{data:{user:null},error:X};throw X}}async generateLink(Z){try{let{options:Q}=Z,X=C0(Z,["options"]),J=Object.assign(Object.assign({},X),Q);if("newEmail"in X)J.new_email=X===null||X===void 0?void 0:X.newEmail,delete J.newEmail;return await C(this.fetch,"POST",`${this.url}/admin/generate_link`,{body:J,headers:this.headers,xform:F6,redirectTo:Q===null||Q===void 0?void 0:Q.redirectTo})}catch(Q){if(N(Q))return{data:{properties:null,user:null},error:Q};throw Q}}async createUser(Z){try{return await C(this.fetch,"POST",`${this.url}/admin/users`,{body:Z,headers:this.headers,xform:B0})}catch(Q){if(N(Q))return{data:{user:null},error:Q};throw Q}}async listUsers(Z){var Q,X,J,G,Y,z,H;try{let W={nextPage:null,lastPage:0,total:0},q=await C(this.fetch,"GET",`${this.url}/admin/users`,{headers:this.headers,noResolveJson:!0,query:{page:(X=(Q=Z===null||Z===void 0?void 0:Z.page)===null||Q===void 0?void 0:Q.toString())!==null&&X!==void 0?X:"",per_page:(G=(J=Z===null||Z===void 0?void 0:Z.perPage)===null||J===void 0?void 0:J.toString())!==null&&G!==void 0?G:""},xform:iQ});if(q.error)throw q.error;let O=await q.json(),M=(Y=q.headers.get("x-total-count"))!==null&&Y!==void 0?Y:0,U=(H=(z=q.headers.get("link"))===null||z===void 0?void 0:z.split(","))!==null&&H!==void 0?H:[];if(U.length>0)U.forEach(($)=>{let K=parseInt($.split(";")[0].split("=")[1].substring(0,1)),w=JSON.parse($.split(";")[1].split("=")[1]);W[`${w}Page`]=K}),W.total=parseInt(M);return{data:Object.assign(Object.assign({},O),W),error:null}}catch(W){if(N(W))return{data:{users:[]},error:W};throw W}}async getUserById(Z){$0(Z);try{return await C(this.fetch,"GET",`${this.url}/admin/users/${Z}`,{headers:this.headers,xform:B0})}catch(Q){if(N(Q))return{data:{user:null},error:Q};throw Q}}async updateUserById(Z,Q){$0(Z);try{return await C(this.fetch,"PUT",`${this.url}/admin/users/${Z}`,{body:Q,headers:this.headers,xform:B0})}catch(X){if(N(X))return{data:{user:null},error:X};throw X}}async deleteUser(Z,Q=!1){$0(Z);try{return await C(this.fetch,"DELETE",`${this.url}/admin/users/${Z}`,{headers:this.headers,body:{should_soft_delete:Q},xform:B0})}catch(X){if(N(X))return{data:{user:null},error:X};throw X}}async _listFactors(Z){$0(Z.userId);try{let{data:Q,error:X}=await C(this.fetch,"GET",`${this.url}/admin/users/${Z.userId}/factors`,{headers:this.headers,xform:(J)=>{return{data:{factors:J},error:null}}});return{data:Q,error:X}}catch(Q){if(N(Q))return{data:null,error:Q};throw Q}}async _deleteFactor(Z){$0(Z.userId),$0(Z.id);try{return{data:await C(this.fetch,"DELETE",`${this.url}/admin/users/${Z.userId}/factors/${Z.id}`,{headers:this.headers}),error:null}}catch(Q){if(N(Q))return{data:null,error:Q};throw Q}}async _listOAuthClients(Z){var Q,X,J,G,Y,z,H;try{let W={nextPage:null,lastPage:0,total:0},q=await C(this.fetch,"GET",`${this.url}/admin/oauth/clients`,{headers:this.headers,noResolveJson:!0,query:{page:(X=(Q=Z===null||Z===void 0?void 0:Z.page)===null||Q===void 0?void 0:Q.toString())!==null&&X!==void 0?X:"",per_page:(G=(J=Z===null||Z===void 0?void 0:Z.perPage)===null||J===void 0?void 0:J.toString())!==null&&G!==void 0?G:""},xform:iQ});if(q.error)throw q.error;let O=await q.json(),M=(Y=q.headers.get("x-total-count"))!==null&&Y!==void 0?Y:0,U=(H=(z=q.headers.get("link"))===null||z===void 0?void 0:z.split(","))!==null&&H!==void 0?H:[];if(U.length>0)U.forEach(($)=>{let K=parseInt($.split(";")[0].split("=")[1].substring(0,1)),w=JSON.parse($.split(";")[1].split("=")[1]);W[`${w}Page`]=K}),W.total=parseInt(M);return{data:Object.assign(Object.assign({},O),W),error:null}}catch(W){if(N(W))return{data:{clients:[]},error:W};throw W}}async _createOAuthClient(Z){try{return await C(this.fetch,"POST",`${this.url}/admin/oauth/clients`,{body:Z,headers:this.headers,xform:(Q)=>{return{data:Q,error:null}}})}catch(Q){if(N(Q))return{data:null,error:Q};throw Q}}async _getOAuthClient(Z){try{return await C(this.fetch,"GET",`${this.url}/admin/oauth/clients/${Z}`,{headers:this.headers,xform:(Q)=>{return{data:Q,error:null}}})}catch(Q){if(N(Q))return{data:null,error:Q};throw Q}}async _updateOAuthClient(Z,Q){try{return await C(this.fetch,"PUT",`${this.url}/admin/oauth/clients/${Z}`,{body:Q,headers:this.headers,xform:(X)=>{return{data:X,error:null}}})}catch(X){if(N(X))return{data:null,error:X};throw X}}async _deleteOAuthClient(Z){try{return await C(this.fetch,"DELETE",`${this.url}/admin/oauth/clients/${Z}`,{headers:this.headers,noResolveJson:!0}),{data:null,error:null}}catch(Q){if(N(Q))return{data:null,error:Q};throw Q}}async _regenerateOAuthClientSecret(Z){try{return await C(this.fetch,"POST",`${this.url}/admin/oauth/clients/${Z}/regenerate_secret`,{headers:this.headers,xform:(Q)=>{return{data:Q,error:null}}})}catch(Q){if(N(Q))return{data:null,error:Q};throw Q}}async _listCustomProviders(Z){try{let Q={};if(Z===null||Z===void 0?void 0:Z.type)Q.type=Z.type;return await C(this.fetch,"GET",`${this.url}/admin/custom-providers`,{headers:this.headers,query:Q,xform:(X)=>{var J;return{data:{providers:(J=X===null||X===void 0?void 0:X.providers)!==null&&J!==void 0?J:[]},error:null}}})}catch(Q){if(N(Q))return{data:{providers:[]},error:Q};throw Q}}async _createCustomProvider(Z){try{return await C(this.fetch,"POST",`${this.url}/admin/custom-providers`,{body:Z,headers:this.headers,xform:(Q)=>{return{data:Q,error:null}}})}catch(Q){if(N(Q))return{data:null,error:Q};throw Q}}async _getCustomProvider(Z){try{return await C(this.fetch,"GET",`${this.url}/admin/custom-providers/${Z}`,{headers:this.headers,xform:(Q)=>{return{data:Q,error:null}}})}catch(Q){if(N(Q))return{data:null,error:Q};throw Q}}async _updateCustomProvider(Z,Q){try{return await C(this.fetch,"PUT",`${this.url}/admin/custom-providers/${Z}`,{body:Q,headers:this.headers,xform:(X)=>{return{data:X,error:null}}})}catch(X){if(N(X))return{data:null,error:X};throw X}}async _deleteCustomProvider(Z){try{return await C(this.fetch,"DELETE",`${this.url}/admin/custom-providers/${Z}`,{headers:this.headers,noResolveJson:!0}),{data:null,error:null}}catch(Q){if(N(Q))return{data:null,error:Q};throw Q}}async _adminListPasskeys(Z){e(this.experimental),$0(Z.userId);try{return await C(this.fetch,"GET",`${this.url}/admin/users/${Z.userId}/passkeys`,{headers:this.headers,xform:(Q)=>({data:Q,error:null})})}catch(Q){if(N(Q))return{data:null,error:Q};throw Q}}async _adminDeletePasskey(Z){e(this.experimental),$0(Z.userId),$0(Z.passkeyId);try{return await C(this.fetch,"DELETE",`${this.url}/admin/users/${Z.userId}/passkeys/${Z.passkeyId}`,{headers:this.headers,noResolveJson:!0}),{data:null,error:null}}catch(Q){if(N(Q))return{data:null,error:Q};throw Q}}}function nQ(Z={}){return{getItem:(Q)=>{return Z[Q]||null},setItem:(Q,X)=>{Z[Q]=X},removeItem:(Q)=>{delete Z[Q]}}}var G0={debug:!!(globalThis&&HQ()&&globalThis.localStorage&&globalThis.localStorage.getItem("supabase.gotrue-js.locks.debug")==="true")};class UQ extends Error{constructor(Z){super(Z);this.isAcquireTimeout=!0}}class MQ extends UQ{}async function aQ(Z,Q,X){if(G0.debug)console.log("@supabase/gotrue-js: navigatorLock: acquire lock",Z,Q);let J=new globalThis.AbortController,G;if(Q>0)G=setTimeout(()=>{if(J.abort(),G0.debug)console.log("@supabase/gotrue-js: navigatorLock acquire timed out",Z)},Q);await Promise.resolve();try{return await globalThis.navigator.locks.request(Z,Q===0?{mode:"exclusive",ifAvailable:!0}:{mode:"exclusive",signal:J.signal},async(Y)=>{if(Y){if(clearTimeout(G),G0.debug)console.log("@supabase/gotrue-js: navigatorLock: acquired",Z,Y.name);try{return await X()}finally{if(G0.debug)console.log("@supabase/gotrue-js: navigatorLock: released",Z,Y.name)}}else if(Q===0){if(G0.debug)console.log("@supabase/gotrue-js: navigatorLock: not immediately available",Z);throw new MQ(`Acquiring an exclusive Navigator LockManager lock "${Z}" immediately failed`)}else{if(G0.debug)try{let z=await globalThis.navigator.locks.query();console.log("@supabase/gotrue-js: Navigator LockManager state",JSON.stringify(z,null," "))}catch(z){console.warn("@supabase/gotrue-js: Error when querying Navigator LockManager state",z)}return console.warn("@supabase/gotrue-js: Navigator LockManager returned a null lock when using #request without ifAvailable set to true, it appears this browser is not following the LockManager spec https://developer.mozilla.org/en-US/docs/Web/API/LockManager/request"),clearTimeout(G),await X()}})}catch(Y){if(Q>0)clearTimeout(G);if((Y===null||Y===void 0?void 0:Y.name)==="AbortError"&&Q>0)if(J.signal.aborted){if(G0.debug)console.log("@supabase/gotrue-js: navigatorLock: acquire timeout, recovering by stealing lock",Z);return console.warn(`@supabase/gotrue-js: Lock "${Z}" was not released within ${Q}ms. This may indicate an orphaned lock from a component unmount (e.g., React Strict Mode). Forcefully acquiring the lock to recover.`),await Promise.resolve().then(()=>globalThis.navigator.locks.request(Z,{mode:"exclusive",steal:!0},async(z)=>{if(z){if(G0.debug)console.log("@supabase/gotrue-js: navigatorLock: recovered (stolen)",Z,z.name);try{return await X()}finally{if(G0.debug)console.log("@supabase/gotrue-js: navigatorLock: released (stolen)",Z,z.name)}}else return console.warn("@supabase/gotrue-js: Navigator LockManager returned null lock even with steal: true"),await X()}))}else{if(G0.debug)console.log("@supabase/gotrue-js: navigatorLock: lock was stolen by another request",Z);throw new MQ(`Lock "${Z}" was released because another request stole it`)}throw Y}}function V6(){if(typeof globalThis==="object")return;try{Object.defineProperty(Object.prototype,"__magic__",{get:function(){return this},configurable:!0}),__magic__.globalThis=__magic__,delete Object.prototype.__magic__}catch(Z){if(typeof self!=="undefined")self.globalThis=self}}function sQ(Z){if(!/^0x[a-fA-F0-9]{40}$/.test(Z))throw new Error(`@supabase/auth-js: Address "${Z}" is invalid.`);return Z.toLowerCase()}function L6(Z){return parseInt(Z,16)}function w6(Z){let Q=new TextEncoder().encode(Z);return"0x"+Array.from(Q,(J)=>J.toString(16).padStart(2,"0")).join("")}function N6(Z){var Q;let{chainId:X,domain:J,expirationTime:G,issuedAt:Y=new Date,nonce:z,notBefore:H,requestId:W,resources:q,scheme:O,uri:M,version:U}=Z;{if(!Number.isInteger(X))throw new Error(`@supabase/auth-js: Invalid SIWE message field "chainId". Chain ID must be a EIP-155 chain ID. Provided value: ${X}`);if(!J)throw new Error('@supabase/auth-js: Invalid SIWE message field "domain". Domain must be provided.');if(z&&z.length<8)throw new Error(`@supabase/auth-js: Invalid SIWE message field "nonce". Nonce must be at least 8 characters. Provided value: ${z}`);if(!M)throw new Error('@supabase/auth-js: Invalid SIWE message field "uri". URI must be provided.');if(U!=="1")throw new Error(`@supabase/auth-js: Invalid SIWE message field "version". Version must be '1'. Provided value: ${U}`);if((Q=Z.statement)===null||Q===void 0?void 0:Q.includes(`
31
+ `))throw new Error(`@supabase/auth-js: Invalid SIWE message field "statement". Statement must not include '\\n'. Provided value: ${Z.statement}`)}let $=sQ(Z.address),K=O?`${O}://${J}`:J,w=Z.statement?`${Z.statement}
32
+ `:"",V=`${K} wants you to sign in with your Ethereum account:
33
+ ${$}
34
+
35
+ ${w}`,B=`URI: ${M}
36
+ Version: ${U}
37
+ Chain ID: ${X}${z?`
38
+ Nonce: ${z}`:""}
39
+ Issued At: ${Y.toISOString()}`;if(G)B+=`
40
+ Expiration Time: ${G.toISOString()}`;if(H)B+=`
41
+ Not Before: ${H.toISOString()}`;if(W)B+=`
42
+ Request ID: ${W}`;if(q){let F=`
43
+ Resources:`;for(let D of q){if(!D||typeof D!=="string")throw new Error(`@supabase/auth-js: Invalid SIWE message field "resources". Every resource must be a valid string. Provided value: ${D}`);F+=`
44
+ - ${D}`}B+=F}return`${V}
45
+ ${B}`}class h extends Error{constructor({message:Z,code:Q,cause:X,name:J}){var G;super(Z,{cause:X});this.__isWebAuthnError=!0,this.name=(G=J!==null&&J!==void 0?J:X instanceof Error?X.name:void 0)!==null&&G!==void 0?G:"Unknown Error",this.code=Q}}class i0 extends h{constructor(Z,Q){super({code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:Q,message:Z});this.name="WebAuthnUnknownError",this.originalError=Q}}function D6({error:Z,options:Q}){var X,J,G;let{publicKey:Y}=Q;if(!Y)throw Error("options was missing required publicKey property");if(Z.name==="AbortError"){if(Q.signal instanceof AbortSignal)return new h({message:"Registration ceremony was sent an abort signal",code:"ERROR_CEREMONY_ABORTED",cause:Z})}else if(Z.name==="ConstraintError"){if(((X=Y.authenticatorSelection)===null||X===void 0?void 0:X.requireResidentKey)===!0)return new h({message:"Discoverable credentials were required but no available authenticator supported it",code:"ERROR_AUTHENTICATOR_MISSING_DISCOVERABLE_CREDENTIAL_SUPPORT",cause:Z});else if(Q.mediation==="conditional"&&((J=Y.authenticatorSelection)===null||J===void 0?void 0:J.userVerification)==="required")return new h({message:"User verification was required during automatic registration but it could not be performed",code:"ERROR_AUTO_REGISTER_USER_VERIFICATION_FAILURE",cause:Z});else if(((G=Y.authenticatorSelection)===null||G===void 0?void 0:G.userVerification)==="required")return new h({message:"User verification was required but no available authenticator supported it",code:"ERROR_AUTHENTICATOR_MISSING_USER_VERIFICATION_SUPPORT",cause:Z})}else if(Z.name==="InvalidStateError")return new h({message:"The authenticator was previously registered",code:"ERROR_AUTHENTICATOR_PREVIOUSLY_REGISTERED",cause:Z});else if(Z.name==="NotAllowedError")return new h({message:Z.message,code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:Z});else if(Z.name==="NotSupportedError"){if(Y.pubKeyCredParams.filter((H)=>H.type==="public-key").length===0)return new h({message:'No entry in pubKeyCredParams was of type "public-key"',code:"ERROR_MALFORMED_PUBKEYCREDPARAMS",cause:Z});return new h({message:"No available authenticator supported any of the specified pubKeyCredParams algorithms",code:"ERROR_AUTHENTICATOR_NO_SUPPORTED_PUBKEYCREDPARAMS_ALG",cause:Z})}else if(Z.name==="SecurityError"){let z=window.location.hostname;if(!oQ(z))return new h({message:`${window.location.hostname} is an invalid domain`,code:"ERROR_INVALID_DOMAIN",cause:Z});else if(Y.rp.id!==z)return new h({message:`The RP ID "${Y.rp.id}" is invalid for this domain`,code:"ERROR_INVALID_RP_ID",cause:Z})}else if(Z.name==="TypeError"){if(Y.user.id.byteLength<1||Y.user.id.byteLength>64)return new h({message:"User ID was not between 1 and 64 characters",code:"ERROR_INVALID_USER_ID_LENGTH",cause:Z})}else if(Z.name==="UnknownError")return new h({message:"The authenticator was unable to process the specified options, or could not create a new credential",code:"ERROR_AUTHENTICATOR_GENERAL_ERROR",cause:Z});return new h({message:"a Non-Webauthn related error has occurred",code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:Z})}function R6({error:Z,options:Q}){let{publicKey:X}=Q;if(!X)throw Error("options was missing required publicKey property");if(Z.name==="AbortError"){if(Q.signal instanceof AbortSignal)return new h({message:"Authentication ceremony was sent an abort signal",code:"ERROR_CEREMONY_ABORTED",cause:Z})}else if(Z.name==="NotAllowedError")return new h({message:Z.message,code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:Z});else if(Z.name==="SecurityError"){let J=window.location.hostname;if(!oQ(J))return new h({message:`${window.location.hostname} is an invalid domain`,code:"ERROR_INVALID_DOMAIN",cause:Z});else if(X.rpId!==J)return new h({message:`The RP ID "${X.rpId}" is invalid for this domain`,code:"ERROR_INVALID_RP_ID",cause:Z})}else if(Z.name==="UnknownError")return new h({message:"The authenticator was unable to process the specified options, or could not create a new assertion signature",code:"ERROR_AUTHENTICATOR_GENERAL_ERROR",cause:Z});return new h({message:"a Non-Webauthn related error has occurred",code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:Z})}class I6{createNewAbortSignal(){if(this.controller){let Q=new Error("Cancelling existing WebAuthn API call for new one");Q.name="AbortError",this.controller.abort(Q)}let Z=new AbortController;return this.controller=Z,Z.signal}cancelCeremony(){if(this.controller){let Z=new Error("Manually cancelling existing WebAuthn API call");Z.name="AbortError",this.controller.abort(Z),this.controller=void 0}}}var $Q=new I6;function tQ(Z){if(!Z)throw new Error("Credential creation options are required");if(typeof PublicKeyCredential!=="undefined"&&"parseCreationOptionsFromJSON"in PublicKeyCredential&&typeof PublicKeyCredential.parseCreationOptionsFromJSON==="function")return PublicKeyCredential.parseCreationOptionsFromJSON(Z);let{challenge:Q,user:X,excludeCredentials:J}=Z,G=C0(Z,["challenge","user","excludeCredentials"]),Y=N0(Q).buffer,z=Object.assign(Object.assign({},X),{id:N0(X.id).buffer}),H=Object.assign(Object.assign({},G),{challenge:Y,user:z});if(J&&J.length>0){H.excludeCredentials=new Array(J.length);for(let W=0;W<J.length;W++){let q=J[W];H.excludeCredentials[W]=Object.assign(Object.assign({},q),{id:N0(q.id).buffer,type:q.type||"public-key",transports:q.transports})}}return H}function rQ(Z){if(!Z)throw new Error("Credential request options are required");if(typeof PublicKeyCredential!=="undefined"&&"parseRequestOptionsFromJSON"in PublicKeyCredential&&typeof PublicKeyCredential.parseRequestOptionsFromJSON==="function")return PublicKeyCredential.parseRequestOptionsFromJSON(Z);let{challenge:Q,allowCredentials:X}=Z,J=C0(Z,["challenge","allowCredentials"]),G=N0(Q).buffer,Y=Object.assign(Object.assign({},J),{challenge:G});if(X&&X.length>0){Y.allowCredentials=new Array(X.length);for(let z=0;z<X.length;z++){let H=X[z];Y.allowCredentials[z]=Object.assign(Object.assign({},H),{id:N0(H.id).buffer,type:H.type||"public-key",transports:H.transports})}}return Y}function eQ(Z){var Q;if("toJSON"in Z&&typeof Z.toJSON==="function")return Z.toJSON();let X=Z;return{id:Z.id,rawId:Z.id,response:{attestationObject:V0(new Uint8Array(Z.response.attestationObject)),clientDataJSON:V0(new Uint8Array(Z.response.clientDataJSON))},type:"public-key",clientExtensionResults:Z.getClientExtensionResults(),authenticatorAttachment:(Q=X.authenticatorAttachment)!==null&&Q!==void 0?Q:void 0}}function Z1(Z){var Q;if("toJSON"in Z&&typeof Z.toJSON==="function")return Z.toJSON();let X=Z,J=Z.getClientExtensionResults(),G=Z.response;return{id:Z.id,rawId:Z.id,response:{authenticatorData:V0(new Uint8Array(G.authenticatorData)),clientDataJSON:V0(new Uint8Array(G.clientDataJSON)),signature:V0(new Uint8Array(G.signature)),userHandle:G.userHandle?V0(new Uint8Array(G.userHandle)):void 0},type:"public-key",clientExtensionResults:J,authenticatorAttachment:(Q=X.authenticatorAttachment)!==null&&Q!==void 0?Q:void 0}}function oQ(Z){return Z==="localhost"||/^([a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,}$/i.test(Z)}function FZ(){var Z,Q;return!!(i()&&("PublicKeyCredential"in window)&&window.PublicKeyCredential&&("credentials"in navigator)&&typeof((Z=navigator===null||navigator===void 0?void 0:navigator.credentials)===null||Z===void 0?void 0:Z.create)==="function"&&typeof((Q=navigator===null||navigator===void 0?void 0:navigator.credentials)===null||Q===void 0?void 0:Q.get)==="function")}async function Q1(Z){try{let Q=await navigator.credentials.create(Z);if(!Q)return{data:null,error:new i0("Empty credential response",Q)};if(!(Q instanceof PublicKeyCredential))return{data:null,error:new i0("Browser returned unexpected credential type",Q)};return{data:Q,error:null}}catch(Q){return{data:null,error:D6({error:Q,options:Z})}}}async function X1(Z){try{let Q=await navigator.credentials.get(Z);if(!Q)return{data:null,error:new i0("Empty credential response",Q)};if(!(Q instanceof PublicKeyCredential))return{data:null,error:new i0("Browser returned unexpected credential type",Q)};return{data:Q,error:null}}catch(Q){return{data:null,error:R6({error:Q,options:Z})}}}var x9={hints:["security-key"],authenticatorSelection:{authenticatorAttachment:"cross-platform",requireResidentKey:!1,userVerification:"preferred",residentKey:"discouraged"},attestation:"direct"},S9={userVerification:"preferred",hints:["security-key"],attestation:"direct"};function KQ(...Z){let Q=(G)=>G!==null&&typeof G==="object"&&!Array.isArray(G),X=(G)=>G instanceof ArrayBuffer||ArrayBuffer.isView(G),J={};for(let G of Z){if(!G)continue;for(let Y in G){let z=G[Y];if(z===void 0)continue;if(Array.isArray(z))J[Y]=z;else if(X(z))J[Y]=z;else if(Q(z)){let H=J[Y];if(Q(H))J[Y]=KQ(H,z);else J[Y]=KQ(z)}else J[Y]=z}}return J}function T9(Z,Q){return KQ(x9,Z,Q||{})}function k9(Z,Q){return KQ(S9,Z,Q||{})}class J1{constructor(Z){this.client=Z,this.enroll=this._enroll.bind(this),this.challenge=this._challenge.bind(this),this.verify=this._verify.bind(this),this.authenticate=this._authenticate.bind(this),this.register=this._register.bind(this)}async _enroll(Z){return this.client.mfa.enroll(Object.assign(Object.assign({},Z),{factorType:"webauthn"}))}async _challenge({factorId:Z,webauthn:Q,friendlyName:X,signal:J},G){var Y;try{let{data:z,error:H}=await this.client.mfa.challenge({factorId:Z,webauthn:Q});if(!z)return{data:null,error:H};let W=J!==null&&J!==void 0?J:$Q.createNewAbortSignal();if(z.webauthn.type==="create"){let{user:q}=z.webauthn.credential_options.publicKey;if(!q.name){let O=X;if(!O){let U=(await this.client.getUser()).data.user,$=((Y=U===null||U===void 0?void 0:U.user_metadata)===null||Y===void 0?void 0:Y.name)||(U===null||U===void 0?void 0:U.email)||(U===null||U===void 0?void 0:U.id)||"User";q.name=`${q.id}:${$}`}else q.name=`${q.id}:${O}`}if(!q.displayName)q.displayName=q.name}switch(z.webauthn.type){case"create":{let q=T9(z.webauthn.credential_options.publicKey,G===null||G===void 0?void 0:G.create),{data:O,error:M}=await Q1({publicKey:q,signal:W});if(O)return{data:{factorId:Z,challengeId:z.id,webauthn:{type:z.webauthn.type,credential_response:O}},error:null};return{data:null,error:M}}case"request":{let q=k9(z.webauthn.credential_options.publicKey,G===null||G===void 0?void 0:G.request),{data:O,error:M}=await X1(Object.assign(Object.assign({},z.webauthn.credential_options),{publicKey:q,signal:W}));if(O)return{data:{factorId:Z,challengeId:z.id,webauthn:{type:z.webauthn.type,credential_response:O}},error:null};return{data:null,error:M}}}}catch(z){if(N(z))return{data:null,error:z};return{data:null,error:new s("Unexpected error in challenge",z)}}}async _verify({challengeId:Z,factorId:Q,webauthn:X}){return this.client.mfa.verify({factorId:Q,challengeId:Z,webauthn:X})}async _authenticate({factorId:Z,webauthn:{rpId:Q=typeof window!=="undefined"?window.location.hostname:void 0,rpOrigins:X=typeof window!=="undefined"?[window.location.origin]:void 0,signal:J}={}},G){if(!Q)return{data:null,error:new x0("rpId is required for WebAuthn authentication")};try{if(!FZ())return{data:null,error:new s("Browser does not support WebAuthn",null)};let{data:Y,error:z}=await this.challenge({factorId:Z,webauthn:{rpId:Q,rpOrigins:X},signal:J},{request:G});if(!Y)return{data:null,error:z};let{webauthn:H}=Y;return this._verify({factorId:Z,challengeId:Y.challengeId,webauthn:{type:H.type,rpId:Q,rpOrigins:X,credential_response:H.credential_response}})}catch(Y){if(N(Y))return{data:null,error:Y};return{data:null,error:new s("Unexpected error in authenticate",Y)}}}async _register({friendlyName:Z,webauthn:{rpId:Q=typeof window!=="undefined"?window.location.hostname:void 0,rpOrigins:X=typeof window!=="undefined"?[window.location.origin]:void 0,signal:J}={}},G){if(!Q)return{data:null,error:new x0("rpId is required for WebAuthn registration")};try{if(!FZ())return{data:null,error:new s("Browser does not support WebAuthn",null)};let{data:Y,error:z}=await this._enroll({friendlyName:Z});if(!Y)return await this.client.mfa.listFactors().then((q)=>{var O;return(O=q.data)===null||O===void 0?void 0:O.all.find((M)=>M.factor_type==="webauthn"&&M.friendly_name===Z&&M.status!=="unverified")}).then((q)=>q?this.client.mfa.unenroll({factorId:q===null||q===void 0?void 0:q.id}):void 0),{data:null,error:z};let{data:H,error:W}=await this._challenge({factorId:Y.id,friendlyName:Y.friendly_name,webauthn:{rpId:Q,rpOrigins:X},signal:J},{create:G});if(!H)return{data:null,error:W};return this._verify({factorId:Y.id,challengeId:H.challengeId,webauthn:{rpId:Q,rpOrigins:X,type:H.webauthn.type,credential_response:H.webauthn.credential_response}})}catch(Y){if(N(Y))return{data:null,error:Y};return{data:null,error:new s("Unexpected error in register",Y)}}}}V6();var E9={url:n8,storageKey:a8,autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,headers:s8,flowType:"implicit",debug:!1,hasCustomAuthorizationHeader:!1,throwOnError:!1,lockAcquireTimeout:5000,skipAutoInitialize:!1,experimental:{}};async function C6(Z,Q,X){return await X()}var n0={};class VZ{get jwks(){var Z,Q;return(Q=(Z=n0[this.storageKey])===null||Z===void 0?void 0:Z.jwks)!==null&&Q!==void 0?Q:{keys:[]}}set jwks(Z){n0[this.storageKey]=Object.assign(Object.assign({},n0[this.storageKey]),{jwks:Z})}get jwks_cached_at(){var Z,Q;return(Q=(Z=n0[this.storageKey])===null||Z===void 0?void 0:Z.cachedAt)!==null&&Q!==void 0?Q:Number.MIN_SAFE_INTEGER}set jwks_cached_at(Z){n0[this.storageKey]=Object.assign(Object.assign({},n0[this.storageKey]),{cachedAt:Z})}constructor(Z){var Q,X,J,G;this.userStorage=null,this.memoryStorage=null,this.stateChangeEmitters=new Map,this.autoRefreshTicker=null,this.autoRefreshTickTimeout=null,this.visibilityChangedCallback=null,this.refreshingDeferred=null,this.initializePromise=null,this.detectSessionInUrl=!0,this.hasCustomAuthorizationHeader=!1,this.suppressGetSessionWarning=!1,this.lockAcquired=!1,this.pendingInLock=[],this.broadcastChannel=null,this.logger=console.log;let Y=Object.assign(Object.assign({},E9),Z);if(this.storageKey=Y.storageKey,this.instanceID=(Q=VZ.nextInstanceID[this.storageKey])!==null&&Q!==void 0?Q:0,VZ.nextInstanceID[this.storageKey]=this.instanceID+1,this.logDebugMessages=!!Y.debug,typeof Y.debug==="function")this.logger=Y.debug;if(this.instanceID>0&&i()){let z=`${this._logPrefix()} Multiple GoTrueClient instances detected in the same browser context. It is not an error, but this should be avoided as it may produce undefined behavior when used concurrently under the same storage key.`;if(console.warn(z),this.logDebugMessages)console.trace(z)}if(this.persistSession=Y.persistSession,this.autoRefreshToken=Y.autoRefreshToken,this.experimental=(X=Y.experimental)!==null&&X!==void 0?X:{},this.admin=new p0({url:Y.url,headers:Y.headers,fetch:Y.fetch,experimental:this.experimental}),this.url=Y.url,this.headers=Y.headers,this.fetch=WQ(Y.fetch),this.lock=Y.lock||C6,this.detectSessionInUrl=Y.detectSessionInUrl,this.flowType=Y.flowType,this.hasCustomAuthorizationHeader=Y.hasCustomAuthorizationHeader,this.throwOnError=Y.throwOnError,this.lockAcquireTimeout=Y.lockAcquireTimeout,Y.lock)this.lock=Y.lock;else if(this.persistSession&&i()&&((J=globalThis===null||globalThis===void 0?void 0:globalThis.navigator)===null||J===void 0?void 0:J.locks))this.lock=aQ;else this.lock=C6;if(!this.jwks)this.jwks={keys:[]},this.jwks_cached_at=Number.MIN_SAFE_INTEGER;if(this.mfa={verify:this._verify.bind(this),enroll:this._enroll.bind(this),unenroll:this._unenroll.bind(this),challenge:this._challenge.bind(this),listFactors:this._listFactors.bind(this),challengeAndVerify:this._challengeAndVerify.bind(this),getAuthenticatorAssuranceLevel:this._getAuthenticatorAssuranceLevel.bind(this),webauthn:new J1(this)},this.oauth={getAuthorizationDetails:this._getAuthorizationDetails.bind(this),approveAuthorization:this._approveAuthorization.bind(this),denyAuthorization:this._denyAuthorization.bind(this),listGrants:this._listOAuthGrants.bind(this),revokeGrant:this._revokeOAuthGrant.bind(this)},this.passkey={startRegistration:this._startPasskeyRegistration.bind(this),verifyRegistration:this._verifyPasskeyRegistration.bind(this),startAuthentication:this._startPasskeyAuthentication.bind(this),verifyAuthentication:this._verifyPasskeyAuthentication.bind(this),list:this._listPasskeys.bind(this),update:this._updatePasskey.bind(this),delete:this._deletePasskey.bind(this)},this.persistSession){if(Y.storage)this.storage=Y.storage;else if(HQ())this.storage=globalThis.localStorage;else this.memoryStorage={},this.storage=nQ(this.memoryStorage);if(Y.userStorage)this.userStorage=Y.userStorage}else this.memoryStorage={},this.storage=nQ(this.memoryStorage);if(i()&&globalThis.BroadcastChannel&&this.persistSession&&this.storageKey){try{this.broadcastChannel=new globalThis.BroadcastChannel(this.storageKey)}catch(z){console.error("Failed to create a new BroadcastChannel, multi-tab state changes will not be available",z)}(G=this.broadcastChannel)===null||G===void 0||G.addEventListener("message",async(z)=>{this._debug("received broadcast notification from other tab or client",z);try{await this._notifyAllSubscribers(z.data.event,z.data.session,!1)}catch(H){this._debug("#broadcastChannel","error",H)}})}if(!Y.skipAutoInitialize)this.initialize().catch((z)=>{this._debug("#initialize()","error",z)})}isThrowOnErrorEnabled(){return this.throwOnError}_returnResult(Z){if(this.throwOnError&&Z&&Z.error)throw Z.error;return Z}_logPrefix(){return`GoTrueClient@${this.storageKey}:${this.instanceID} (${ZQ}) ${new Date().toISOString()}`}_debug(...Z){if(this.logDebugMessages)this.logger(this._logPrefix(),...Z);return this}async initialize(){if(this.initializePromise)return await this.initializePromise;return this.initializePromise=(async()=>{return await this._acquireLock(this.lockAcquireTimeout,async()=>{return await this._initialize()})})(),await this.initializePromise}async _initialize(){var Z;try{let Q={},X="none";if(i()){if(Q=z6(window.location.href),this._isImplicitGrantCallback(Q))X="implicit";else if(await this._isPKCECallback(Q))X="pkce"}if(i()&&this.detectSessionInUrl&&X!=="none"){let{data:J,error:G}=await this._getSessionFromURL(Q,X);if(G){if(this._debug("#_initialize()","error detecting session from URL",G),e8(G)){let H=(Z=G.details)===null||Z===void 0?void 0:Z.code;if(H==="identity_already_exists"||H==="identity_not_found"||H==="single_identity_not_deletable")return{error:G}}return{error:G}}let{session:Y,redirectType:z}=J;return this._debug("#_initialize()","detected session in URL",Y,"redirect type",z),await this._saveSession(Y),setTimeout(async()=>{if(z==="recovery")await this._notifyAllSubscribers("PASSWORD_RECOVERY",Y);else await this._notifyAllSubscribers("SIGNED_IN",Y)},0),{error:null}}return await this._recoverAndRefresh(),{error:null}}catch(Q){if(N(Q))return this._returnResult({error:Q});return this._returnResult({error:new s("Unexpected error during initialization",Q)})}finally{await this._handleVisibilityChange(),this._debug("#_initialize()","end")}}async signInAnonymously(Z){var Q,X,J;try{let G=await C(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{data:(X=(Q=Z===null||Z===void 0?void 0:Z.options)===null||Q===void 0?void 0:Q.data)!==null&&X!==void 0?X:{},gotrue_meta_security:{captcha_token:(J=Z===null||Z===void 0?void 0:Z.options)===null||J===void 0?void 0:J.captchaToken}},xform:Z0}),{data:Y,error:z}=G;if(z||!Y)return this._returnResult({data:{user:null,session:null},error:z});let{session:H,user:W}=Y;if(Y.session)await this._saveSession(Y.session),await this._notifyAllSubscribers("SIGNED_IN",H);return this._returnResult({data:{user:W,session:H},error:null})}catch(G){if(N(G))return this._returnResult({data:{user:null,session:null},error:G});throw G}}async signUp(Z){var Q,X,J;try{let G;if("email"in Z){let{email:q,password:O,options:M}=Z,U=null,$=null;if(this.flowType==="pkce")[U,$]=await k0(this.storage,this.storageKey);G=await C(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,redirectTo:M===null||M===void 0?void 0:M.emailRedirectTo,body:{email:q,password:O,data:(Q=M===null||M===void 0?void 0:M.data)!==null&&Q!==void 0?Q:{},gotrue_meta_security:{captcha_token:M===null||M===void 0?void 0:M.captchaToken},code_challenge:U,code_challenge_method:$},xform:Z0})}else if("phone"in Z){let{phone:q,password:O,options:M}=Z;G=await C(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{phone:q,password:O,data:(X=M===null||M===void 0?void 0:M.data)!==null&&X!==void 0?X:{},channel:(J=M===null||M===void 0?void 0:M.channel)!==null&&J!==void 0?J:"sms",gotrue_meta_security:{captcha_token:M===null||M===void 0?void 0:M.captchaToken}},xform:Z0})}else throw new d0("You must provide either an email or phone number and a password");let{data:Y,error:z}=G;if(z||!Y)return await n(this.storage,`${this.storageKey}-code-verifier`),this._returnResult({data:{user:null,session:null},error:z});let{session:H,user:W}=Y;if(Y.session)await this._saveSession(Y.session),await this._notifyAllSubscribers("SIGNED_IN",H);return this._returnResult({data:{user:W,session:H},error:null})}catch(G){if(await n(this.storage,`${this.storageKey}-code-verifier`),N(G))return this._returnResult({data:{user:null,session:null},error:G});throw G}}async signInWithPassword(Z){try{let Q;if("email"in Z){let{email:G,password:Y,options:z}=Z;Q=await C(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{email:G,password:Y,gotrue_meta_security:{captcha_token:z===null||z===void 0?void 0:z.captchaToken}},xform:pQ})}else if("phone"in Z){let{phone:G,password:Y,options:z}=Z;Q=await C(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{phone:G,password:Y,gotrue_meta_security:{captcha_token:z===null||z===void 0?void 0:z.captchaToken}},xform:pQ})}else throw new d0("You must provide either an email or phone number and a password");let{data:X,error:J}=Q;if(J)return this._returnResult({data:{user:null,session:null},error:J});else if(!X||!X.session||!X.user){let G=new w0;return this._returnResult({data:{user:null,session:null},error:G})}if(X.session)await this._saveSession(X.session),await this._notifyAllSubscribers("SIGNED_IN",X.session);return this._returnResult({data:Object.assign({user:X.user,session:X.session},X.weak_password?{weakPassword:X.weak_password}:null),error:J})}catch(Q){if(N(Q))return this._returnResult({data:{user:null,session:null},error:Q});throw Q}}async signInWithOAuth(Z){var Q,X,J,G;return await this._handleProviderSignIn(Z.provider,{redirectTo:(Q=Z.options)===null||Q===void 0?void 0:Q.redirectTo,scopes:(X=Z.options)===null||X===void 0?void 0:X.scopes,queryParams:(J=Z.options)===null||J===void 0?void 0:J.queryParams,skipBrowserRedirect:(G=Z.options)===null||G===void 0?void 0:G.skipBrowserRedirect})}async exchangeCodeForSession(Z){return await this.initializePromise,this._acquireLock(this.lockAcquireTimeout,async()=>{return this._exchangeCodeForSession(Z)})}async signInWithWeb3(Z){let{chain:Q}=Z;switch(Q){case"ethereum":return await this.signInWithEthereum(Z);case"solana":return await this.signInWithSolana(Z);default:throw new Error(`@supabase/auth-js: Unsupported chain "${Q}"`)}}async signInWithEthereum(Z){var Q,X,J,G,Y,z,H,W,q,O,M;let U,$;if("message"in Z)U=Z.message,$=Z.signature;else{let{chain:K,wallet:w,statement:V,options:B}=Z,F;if(!i()){if(typeof w!=="object"||!(B===null||B===void 0?void 0:B.url))throw new Error("@supabase/auth-js: Both wallet and url must be specified in non-browser environments.");F=w}else if(typeof w==="object")F=w;else{let k=window;if("ethereum"in k&&typeof k.ethereum==="object"&&"request"in k.ethereum&&typeof k.ethereum.request==="function")F=k.ethereum;else throw new Error("@supabase/auth-js: No compatible Ethereum wallet interface on the window object (window.ethereum) detected. Make sure the user already has a wallet installed and connected for this app. Prefer passing the wallet interface object directly to signInWithWeb3({ chain: 'ethereum', wallet: resolvedUserWallet }) instead.")}let D=new URL((Q=B===null||B===void 0?void 0:B.url)!==null&&Q!==void 0?Q:window.location.href),b=await F.request({method:"eth_requestAccounts"}).then((k)=>k).catch(()=>{throw new Error("@supabase/auth-js: Wallet method eth_requestAccounts is missing or invalid")});if(!b||b.length===0)throw new Error("@supabase/auth-js: No accounts available. Please ensure the wallet is connected.");let j=sQ(b[0]),T=(X=B===null||B===void 0?void 0:B.signInWithEthereum)===null||X===void 0?void 0:X.chainId;if(!T){let k=await F.request({method:"eth_chainId"});T=L6(k)}let I={domain:D.host,address:j,statement:V,uri:D.href,version:"1",chainId:T,nonce:(J=B===null||B===void 0?void 0:B.signInWithEthereum)===null||J===void 0?void 0:J.nonce,issuedAt:(Y=(G=B===null||B===void 0?void 0:B.signInWithEthereum)===null||G===void 0?void 0:G.issuedAt)!==null&&Y!==void 0?Y:new Date,expirationTime:(z=B===null||B===void 0?void 0:B.signInWithEthereum)===null||z===void 0?void 0:z.expirationTime,notBefore:(H=B===null||B===void 0?void 0:B.signInWithEthereum)===null||H===void 0?void 0:H.notBefore,requestId:(W=B===null||B===void 0?void 0:B.signInWithEthereum)===null||W===void 0?void 0:W.requestId,resources:(q=B===null||B===void 0?void 0:B.signInWithEthereum)===null||q===void 0?void 0:q.resources};U=N6(I),$=await F.request({method:"personal_sign",params:[w6(U),j]})}try{let{data:K,error:w}=await C(this.fetch,"POST",`${this.url}/token?grant_type=web3`,{headers:this.headers,body:Object.assign({chain:"ethereum",message:U,signature:$},((O=Z.options)===null||O===void 0?void 0:O.captchaToken)?{gotrue_meta_security:{captcha_token:(M=Z.options)===null||M===void 0?void 0:M.captchaToken}}:null),xform:Z0});if(w)throw w;if(!K||!K.session||!K.user){let V=new w0;return this._returnResult({data:{user:null,session:null},error:V})}if(K.session)await this._saveSession(K.session),await this._notifyAllSubscribers("SIGNED_IN",K.session);return this._returnResult({data:Object.assign({},K),error:w})}catch(K){if(N(K))return this._returnResult({data:{user:null,session:null},error:K});throw K}}async signInWithSolana(Z){var Q,X,J,G,Y,z,H,W,q,O,M,U;let $,K;if("message"in Z)$=Z.message,K=Z.signature;else{let{chain:w,wallet:V,statement:B,options:F}=Z,D;if(!i()){if(typeof V!=="object"||!(F===null||F===void 0?void 0:F.url))throw new Error("@supabase/auth-js: Both wallet and url must be specified in non-browser environments.");D=V}else if(typeof V==="object")D=V;else{let j=window;if("solana"in j&&typeof j.solana==="object"&&(("signIn"in j.solana)&&typeof j.solana.signIn==="function"||("signMessage"in j.solana)&&typeof j.solana.signMessage==="function"))D=j.solana;else throw new Error("@supabase/auth-js: No compatible Solana wallet interface on the window object (window.solana) detected. Make sure the user already has a wallet installed and connected for this app. Prefer passing the wallet interface object directly to signInWithWeb3({ chain: 'solana', wallet: resolvedUserWallet }) instead.")}let b=new URL((Q=F===null||F===void 0?void 0:F.url)!==null&&Q!==void 0?Q:window.location.href);if("signIn"in D&&D.signIn){let j=await D.signIn(Object.assign(Object.assign(Object.assign({issuedAt:new Date().toISOString()},F===null||F===void 0?void 0:F.signInWithSolana),{version:"1",domain:b.host,uri:b.href}),B?{statement:B}:null)),T;if(Array.isArray(j)&&j[0]&&typeof j[0]==="object")T=j[0];else if(j&&typeof j==="object"&&"signedMessage"in j&&"signature"in j)T=j;else throw new Error("@supabase/auth-js: Wallet method signIn() returned unrecognized value");if("signedMessage"in T&&"signature"in T&&(typeof T.signedMessage==="string"||T.signedMessage instanceof Uint8Array)&&T.signature instanceof Uint8Array)$=typeof T.signedMessage==="string"?T.signedMessage:new TextDecoder().decode(T.signedMessage),K=T.signature;else throw new Error("@supabase/auth-js: Wallet method signIn() API returned object without signedMessage and signature fields")}else{if(!("signMessage"in D)||typeof D.signMessage!=="function"||!("publicKey"in D)||typeof D!=="object"||!D.publicKey||!("toBase58"in D.publicKey)||typeof D.publicKey.toBase58!=="function")throw new Error("@supabase/auth-js: Wallet does not have a compatible signMessage() and publicKey.toBase58() API");$=[`${b.host} wants you to sign in with your Solana account:`,D.publicKey.toBase58(),...B?["",B,""]:[""],"Version: 1",`URI: ${b.href}`,`Issued At: ${(J=(X=F===null||F===void 0?void 0:F.signInWithSolana)===null||X===void 0?void 0:X.issuedAt)!==null&&J!==void 0?J:new Date().toISOString()}`,...((G=F===null||F===void 0?void 0:F.signInWithSolana)===null||G===void 0?void 0:G.notBefore)?[`Not Before: ${F.signInWithSolana.notBefore}`]:[],...((Y=F===null||F===void 0?void 0:F.signInWithSolana)===null||Y===void 0?void 0:Y.expirationTime)?[`Expiration Time: ${F.signInWithSolana.expirationTime}`]:[],...((z=F===null||F===void 0?void 0:F.signInWithSolana)===null||z===void 0?void 0:z.chainId)?[`Chain ID: ${F.signInWithSolana.chainId}`]:[],...((H=F===null||F===void 0?void 0:F.signInWithSolana)===null||H===void 0?void 0:H.nonce)?[`Nonce: ${F.signInWithSolana.nonce}`]:[],...((W=F===null||F===void 0?void 0:F.signInWithSolana)===null||W===void 0?void 0:W.requestId)?[`Request ID: ${F.signInWithSolana.requestId}`]:[],...((O=(q=F===null||F===void 0?void 0:F.signInWithSolana)===null||q===void 0?void 0:q.resources)===null||O===void 0?void 0:O.length)?["Resources",...F.signInWithSolana.resources.map((T)=>`- ${T}`)]:[]].join(`
46
+ `);let j=await D.signMessage(new TextEncoder().encode($),"utf8");if(!j||!(j instanceof Uint8Array))throw new Error("@supabase/auth-js: Wallet signMessage() API returned an recognized value");K=j}}try{let{data:w,error:V}=await C(this.fetch,"POST",`${this.url}/token?grant_type=web3`,{headers:this.headers,body:Object.assign({chain:"solana",message:$,signature:V0(K)},((M=Z.options)===null||M===void 0?void 0:M.captchaToken)?{gotrue_meta_security:{captcha_token:(U=Z.options)===null||U===void 0?void 0:U.captchaToken}}:null),xform:Z0});if(V)throw V;if(!w||!w.session||!w.user){let B=new w0;return this._returnResult({data:{user:null,session:null},error:B})}if(w.session)await this._saveSession(w.session),await this._notifyAllSubscribers("SIGNED_IN",w.session);return this._returnResult({data:Object.assign({},w),error:V})}catch(w){if(N(w))return this._returnResult({data:{user:null,session:null},error:w});throw w}}async _exchangeCodeForSession(Z){let Q=await D0(this.storage,`${this.storageKey}-code-verifier`),[X,J]=(Q!==null&&Q!==void 0?Q:"").split("/");try{if(!X&&this.flowType==="pkce")throw new dQ;let{data:G,error:Y}=await C(this.fetch,"POST",`${this.url}/token?grant_type=pkce`,{headers:this.headers,body:{auth_code:Z,code_verifier:X},xform:Z0});if(await n(this.storage,`${this.storageKey}-code-verifier`),Y)throw Y;if(!G||!G.session||!G.user){let z=new w0;return this._returnResult({data:{user:null,session:null,redirectType:null},error:z})}if(G.session)await this._saveSession(G.session),await this._notifyAllSubscribers(J==="recovery"?"PASSWORD_RECOVERY":"SIGNED_IN",G.session);return this._returnResult({data:Object.assign(Object.assign({},G),{redirectType:J!==null&&J!==void 0?J:null}),error:Y})}catch(G){if(await n(this.storage,`${this.storageKey}-code-verifier`),N(G))return this._returnResult({data:{user:null,session:null,redirectType:null},error:G});throw G}}async signInWithIdToken(Z){try{let{options:Q,provider:X,token:J,access_token:G,nonce:Y}=Z,z=await C(this.fetch,"POST",`${this.url}/token?grant_type=id_token`,{headers:this.headers,body:{provider:X,id_token:J,access_token:G,nonce:Y,gotrue_meta_security:{captcha_token:Q===null||Q===void 0?void 0:Q.captchaToken}},xform:Z0}),{data:H,error:W}=z;if(W)return this._returnResult({data:{user:null,session:null},error:W});else if(!H||!H.session||!H.user){let q=new w0;return this._returnResult({data:{user:null,session:null},error:q})}if(H.session)await this._saveSession(H.session),await this._notifyAllSubscribers("SIGNED_IN",H.session);return this._returnResult({data:H,error:W})}catch(Q){if(N(Q))return this._returnResult({data:{user:null,session:null},error:Q});throw Q}}async signInWithOtp(Z){var Q,X,J,G,Y;try{if("email"in Z){let{email:z,options:H}=Z,W=null,q=null;if(this.flowType==="pkce")[W,q]=await k0(this.storage,this.storageKey);let{error:O}=await C(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{email:z,data:(Q=H===null||H===void 0?void 0:H.data)!==null&&Q!==void 0?Q:{},create_user:(X=H===null||H===void 0?void 0:H.shouldCreateUser)!==null&&X!==void 0?X:!0,gotrue_meta_security:{captcha_token:H===null||H===void 0?void 0:H.captchaToken},code_challenge:W,code_challenge_method:q},redirectTo:H===null||H===void 0?void 0:H.emailRedirectTo});return this._returnResult({data:{user:null,session:null},error:O})}if("phone"in Z){let{phone:z,options:H}=Z,{data:W,error:q}=await C(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{phone:z,data:(J=H===null||H===void 0?void 0:H.data)!==null&&J!==void 0?J:{},create_user:(G=H===null||H===void 0?void 0:H.shouldCreateUser)!==null&&G!==void 0?G:!0,gotrue_meta_security:{captcha_token:H===null||H===void 0?void 0:H.captchaToken},channel:(Y=H===null||H===void 0?void 0:H.channel)!==null&&Y!==void 0?Y:"sms"}});return this._returnResult({data:{user:null,session:null,messageId:W===null||W===void 0?void 0:W.message_id},error:q})}throw new d0("You must provide either an email or phone number.")}catch(z){if(await n(this.storage,`${this.storageKey}-code-verifier`),N(z))return this._returnResult({data:{user:null,session:null},error:z});throw z}}async verifyOtp(Z){var Q,X;try{let J=void 0,G=void 0;if("options"in Z)J=(Q=Z.options)===null||Q===void 0?void 0:Q.redirectTo,G=(X=Z.options)===null||X===void 0?void 0:X.captchaToken;let{data:Y,error:z}=await C(this.fetch,"POST",`${this.url}/verify`,{headers:this.headers,body:Object.assign(Object.assign({},Z),{gotrue_meta_security:{captcha_token:G}}),redirectTo:J,xform:Z0});if(z)throw z;if(!Y)throw new Error("An error occurred on token verification.");let{session:H,user:W}=Y;if(H===null||H===void 0?void 0:H.access_token)await this._saveSession(H),await this._notifyAllSubscribers(Z.type=="recovery"?"PASSWORD_RECOVERY":"SIGNED_IN",H);return this._returnResult({data:{user:W,session:H},error:null})}catch(J){if(N(J))return this._returnResult({data:{user:null,session:null},error:J});throw J}}async signInWithSSO(Z){var Q,X,J,G,Y;try{let z=null,H=null;if(this.flowType==="pkce")[z,H]=await k0(this.storage,this.storageKey);let W=await C(this.fetch,"POST",`${this.url}/sso`,{body:Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},"providerId"in Z?{provider_id:Z.providerId}:null),"domain"in Z?{domain:Z.domain}:null),{redirect_to:(X=(Q=Z.options)===null||Q===void 0?void 0:Q.redirectTo)!==null&&X!==void 0?X:void 0}),((J=Z===null||Z===void 0?void 0:Z.options)===null||J===void 0?void 0:J.captchaToken)?{gotrue_meta_security:{captcha_token:Z.options.captchaToken}}:null),{skip_http_redirect:!0,code_challenge:z,code_challenge_method:H}),headers:this.headers,xform:B6});if(((G=W.data)===null||G===void 0?void 0:G.url)&&i()&&!((Y=Z.options)===null||Y===void 0?void 0:Y.skipBrowserRedirect))window.location.assign(W.data.url);return this._returnResult(W)}catch(z){if(await n(this.storage,`${this.storageKey}-code-verifier`),N(z))return this._returnResult({data:null,error:z});throw z}}async reauthenticate(){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>{return await this._reauthenticate()})}async _reauthenticate(){try{return await this._useSession(async(Z)=>{let{data:{session:Q},error:X}=Z;if(X)throw X;if(!Q)throw new c;let{error:J}=await C(this.fetch,"GET",`${this.url}/reauthenticate`,{headers:this.headers,jwt:Q.access_token});return this._returnResult({data:{user:null,session:null},error:J})})}catch(Z){if(N(Z))return this._returnResult({data:{user:null,session:null},error:Z});throw Z}}async resend(Z){try{let Q=`${this.url}/resend`;if("email"in Z){let{email:X,type:J,options:G}=Z,{error:Y}=await C(this.fetch,"POST",Q,{headers:this.headers,body:{email:X,type:J,gotrue_meta_security:{captcha_token:G===null||G===void 0?void 0:G.captchaToken}},redirectTo:G===null||G===void 0?void 0:G.emailRedirectTo});return this._returnResult({data:{user:null,session:null},error:Y})}else if("phone"in Z){let{phone:X,type:J,options:G}=Z,{data:Y,error:z}=await C(this.fetch,"POST",Q,{headers:this.headers,body:{phone:X,type:J,gotrue_meta_security:{captcha_token:G===null||G===void 0?void 0:G.captchaToken}}});return this._returnResult({data:{user:null,session:null,messageId:Y===null||Y===void 0?void 0:Y.message_id},error:z})}throw new d0("You must provide either an email or phone number and a type")}catch(Q){if(N(Q))return this._returnResult({data:{user:null,session:null},error:Q});throw Q}}async getSession(){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>{return this._useSession(async(Q)=>{return Q})})}async _acquireLock(Z,Q){this._debug("#_acquireLock","begin",Z);try{if(this.lockAcquired){let X=this.pendingInLock.length?this.pendingInLock[this.pendingInLock.length-1]:Promise.resolve(),J=(async()=>{return await X,await Q()})();return this.pendingInLock.push((async()=>{try{await J}catch(G){}})()),J}return await this.lock(`lock:${this.storageKey}`,Z,async()=>{this._debug("#_acquireLock","lock acquired for storage key",this.storageKey);try{this.lockAcquired=!0;let X=Q();this.pendingInLock.push((async()=>{try{await X}catch(J){}})()),await X;while(this.pendingInLock.length){let J=[...this.pendingInLock];await Promise.all(J),this.pendingInLock.splice(0,J.length)}return await X}finally{this._debug("#_acquireLock","lock released for storage key",this.storageKey),this.lockAcquired=!1}})}finally{this._debug("#_acquireLock","end")}}async _useSession(Z){this._debug("#_useSession","begin");try{let Q=await this.__loadSession();return await Z(Q)}finally{this._debug("#_useSession","end")}}async __loadSession(){if(this._debug("#__loadSession()","begin"),!this.lockAcquired)this._debug("#__loadSession()","used outside of an acquired lock!",new Error().stack);try{let Z=null,Q=await D0(this.storage,this.storageKey);if(this._debug("#getSession()","session from storage",Q),Q!==null)if(this._isValidSession(Q))Z=Q;else this._debug("#getSession()","session from storage is not valid"),await this._removeSession();if(!Z)return{data:{session:null},error:null};let X=Z.expires_at?Z.expires_at*1000-Date.now()<XQ:!1;if(this._debug("#__loadSession()",`session has${X?"":" not"} expired`,"expires_at",Z.expires_at),!X){if(this.userStorage){let Y=await D0(this.userStorage,this.storageKey+"-user");if(Y===null||Y===void 0?void 0:Y.user)Z.user=Y.user;else Z.user=qQ()}if(this.storage.isServer&&Z.user&&!Z.user.__isUserNotAvailableProxy){let Y={value:this.suppressGetSessionWarning};if(Z.user=K6(Z.user,Y),Y.value)this.suppressGetSessionWarning=!0}return{data:{session:Z},error:null}}let{data:J,error:G}=await this._callRefreshToken(Z.refresh_token);if(G)return this._returnResult({data:{session:null},error:G});return this._returnResult({data:{session:J},error:null})}finally{this._debug("#__loadSession()","end")}}async getUser(Z){if(Z)return await this._getUser(Z);await this.initializePromise;let Q=await this._acquireLock(this.lockAcquireTimeout,async()=>{return await this._getUser()});if(Q.data.user)this.suppressGetSessionWarning=!0;return Q}async _getUser(Z){try{if(Z)return await C(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:Z,xform:B0});return await this._useSession(async(Q)=>{var X,J,G;let{data:Y,error:z}=Q;if(z)throw z;if(!((X=Y.session)===null||X===void 0?void 0:X.access_token)&&!this.hasCustomAuthorizationHeader)return{data:{user:null},error:new c};return await C(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:(G=(J=Y.session)===null||J===void 0?void 0:J.access_token)!==null&&G!==void 0?G:void 0,xform:B0})})}catch(Q){if(N(Q)){if(UZ(Q))await this._removeSession(),await n(this.storage,`${this.storageKey}-code-verifier`);return this._returnResult({data:{user:null},error:Q})}throw Q}}async updateUser(Z,Q={}){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>{return await this._updateUser(Z,Q)})}async _updateUser(Z,Q={}){try{return await this._useSession(async(X)=>{let{data:J,error:G}=X;if(G)throw G;if(!J.session)throw new c;let Y=J.session,z=null,H=null;if(this.flowType==="pkce"&&Z.email!=null)[z,H]=await k0(this.storage,this.storageKey);let{data:W,error:q}=await C(this.fetch,"PUT",`${this.url}/user`,{headers:this.headers,redirectTo:Q===null||Q===void 0?void 0:Q.emailRedirectTo,body:Object.assign(Object.assign({},Z),{code_challenge:z,code_challenge_method:H}),jwt:Y.access_token,xform:B0});if(q)throw q;return Y.user=W.user,await this._saveSession(Y),await this._notifyAllSubscribers("USER_UPDATED",Y),this._returnResult({data:{user:Y.user},error:null})})}catch(X){if(await n(this.storage,`${this.storageKey}-code-verifier`),N(X))return this._returnResult({data:{user:null},error:X});throw X}}async setSession(Z){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>{return await this._setSession(Z)})}async _setSession(Z){try{if(!Z.access_token||!Z.refresh_token)throw new c;let Q=Date.now()/1000,X=Q,J=!0,G=null,{payload:Y}=BZ(Z.access_token);if(Y.exp)X=Y.exp,J=X<=Q;if(J){let{data:z,error:H}=await this._callRefreshToken(Z.refresh_token);if(H)return this._returnResult({data:{user:null,session:null},error:H});if(!z)return{data:{user:null,session:null},error:null};G=z}else{let{data:z,error:H}=await this._getUser(Z.access_token);if(H)return this._returnResult({data:{user:null,session:null},error:H});G={access_token:Z.access_token,refresh_token:Z.refresh_token,user:z.user,token_type:"bearer",expires_in:X-Q,expires_at:X},await this._saveSession(G),await this._notifyAllSubscribers("SIGNED_IN",G)}return this._returnResult({data:{user:G.user,session:G},error:null})}catch(Q){if(N(Q))return this._returnResult({data:{session:null,user:null},error:Q});throw Q}}async refreshSession(Z){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>{return await this._refreshSession(Z)})}async _refreshSession(Z){try{return await this._useSession(async(Q)=>{var X;if(!Z){let{data:Y,error:z}=Q;if(z)throw z;Z=(X=Y.session)!==null&&X!==void 0?X:void 0}if(!(Z===null||Z===void 0?void 0:Z.refresh_token))throw new c;let{data:J,error:G}=await this._callRefreshToken(Z.refresh_token);if(G)return this._returnResult({data:{user:null,session:null},error:G});if(!J)return this._returnResult({data:{user:null,session:null},error:null});return this._returnResult({data:{user:J.user,session:J},error:null})})}catch(Q){if(N(Q))return this._returnResult({data:{user:null,session:null},error:Q});throw Q}}async _getSessionFromURL(Z,Q){var X;try{if(!i())throw new c0("No browser detected.");if(Z.error||Z.error_description||Z.error_code)throw new c0(Z.error_description||"Error in URL with unspecified error_description",{error:Z.error||"unspecified_error",code:Z.error_code||"unspecified_code"});switch(Q){case"implicit":if(this.flowType==="pkce")throw new JQ("Not a valid PKCE flow url.");break;case"pkce":if(this.flowType==="implicit")throw new c0("Not a valid implicit grant flow url.");break;default:}if(Q==="pkce"){if(this._debug("#_initialize()","begin","is PKCE flow",!0),!Z.code)throw new JQ("No code detected.");let{data:F,error:D}=await this._exchangeCodeForSession(Z.code);if(D)throw D;let b=new URL(window.location.href);return b.searchParams.delete("code"),window.history.replaceState(window.history.state,"",b.toString()),{data:{session:F.session,redirectType:(X=F.redirectType)!==null&&X!==void 0?X:null},error:null}}let{provider_token:J,provider_refresh_token:G,access_token:Y,refresh_token:z,expires_in:H,expires_at:W,token_type:q}=Z;if(!Y||!H||!z||!q)throw new c0("No session defined in URL");let O=Math.round(Date.now()/1000),M=parseInt(H),U=O+M;if(W)U=parseInt(W);let $=U-O;if($*1000<=j0)console.warn(`@supabase/gotrue-js: Session as retrieved from URL expires in ${$}s, should have been closer to ${M}s`);let K=U-M;if(O-K>=120)console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued over 120s ago, URL could be stale",K,U,O);else if(O-K<0)console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued in the future? Check the device clock for skew",K,U,O);let{data:w,error:V}=await this._getUser(Y);if(V)throw V;let B={provider_token:J,provider_refresh_token:G,access_token:Y,expires_in:M,expires_at:U,refresh_token:z,token_type:q,user:w.user};return window.location.hash="",this._debug("#_getSessionFromURL()","clearing window.location.hash"),this._returnResult({data:{session:B,redirectType:Z.type},error:null})}catch(J){if(N(J))return this._returnResult({data:{session:null,redirectType:null},error:J});throw J}}_isImplicitGrantCallback(Z){if(typeof this.detectSessionInUrl==="function")return this.detectSessionInUrl(new URL(window.location.href),Z);return Boolean(Z.access_token||Z.error_description)}async _isPKCECallback(Z){let Q=await D0(this.storage,`${this.storageKey}-code-verifier`);return!!(Z.code&&Q)}async signOut(Z={scope:"global"}){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>{return await this._signOut(Z)})}async _signOut({scope:Z}={scope:"global"}){return await this._useSession(async(Q)=>{var X;let{data:J,error:G}=Q;if(G&&!UZ(G))return this._returnResult({error:G});let Y=(X=J.session)===null||X===void 0?void 0:X.access_token;if(Y){let{error:z}=await this.admin.signOut(Y,Z);if(z){if(!(r8(z)&&(z.status===404||z.status===401||z.status===403)||UZ(z)))return this._returnResult({error:z})}}if(Z!=="others")await this._removeSession(),await n(this.storage,`${this.storageKey}-code-verifier`);return this._returnResult({error:null})})}onAuthStateChange(Z){let Q=G6(),X={id:Q,callback:Z,unsubscribe:()=>{this._debug("#unsubscribe()","state change callback with id removed",Q),this.stateChangeEmitters.delete(Q)}};return this._debug("#onAuthStateChange()","registered callback with id",Q),this.stateChangeEmitters.set(Q,X),(async()=>{await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>{this._emitInitialSession(Q)})})(),{data:{subscription:X}}}async _emitInitialSession(Z){return await this._useSession(async(Q)=>{var X,J;try{let{data:{session:G},error:Y}=Q;if(Y)throw Y;await((X=this.stateChangeEmitters.get(Z))===null||X===void 0?void 0:X.callback("INITIAL_SESSION",G)),this._debug("INITIAL_SESSION","callback id",Z,"session",G)}catch(G){if(await((J=this.stateChangeEmitters.get(Z))===null||J===void 0?void 0:J.callback("INITIAL_SESSION",null)),this._debug("INITIAL_SESSION","callback id",Z,"error",G),UZ(G))console.warn(G);else console.error(G)}})}async resetPasswordForEmail(Z,Q={}){let X=null,J=null;if(this.flowType==="pkce")[X,J]=await k0(this.storage,this.storageKey,!0);try{return await C(this.fetch,"POST",`${this.url}/recover`,{body:{email:Z,code_challenge:X,code_challenge_method:J,gotrue_meta_security:{captcha_token:Q.captchaToken}},headers:this.headers,redirectTo:Q.redirectTo})}catch(G){if(await n(this.storage,`${this.storageKey}-code-verifier`),N(G))return this._returnResult({data:null,error:G});throw G}}async getUserIdentities(){var Z;try{let{data:Q,error:X}=await this.getUser();if(X)throw X;return this._returnResult({data:{identities:(Z=Q.user.identities)!==null&&Z!==void 0?Z:[]},error:null})}catch(Q){if(N(Q))return this._returnResult({data:null,error:Q});throw Q}}async linkIdentity(Z){if("token"in Z)return this.linkIdentityIdToken(Z);return this.linkIdentityOAuth(Z)}async linkIdentityOAuth(Z){var Q;try{let{data:X,error:J}=await this._useSession(async(G)=>{var Y,z,H,W,q;let{data:O,error:M}=G;if(M)throw M;let U=await this._getUrlForProvider(`${this.url}/user/identities/authorize`,Z.provider,{redirectTo:(Y=Z.options)===null||Y===void 0?void 0:Y.redirectTo,scopes:(z=Z.options)===null||z===void 0?void 0:z.scopes,queryParams:(H=Z.options)===null||H===void 0?void 0:H.queryParams,skipBrowserRedirect:!0});return await C(this.fetch,"GET",U,{headers:this.headers,jwt:(q=(W=O.session)===null||W===void 0?void 0:W.access_token)!==null&&q!==void 0?q:void 0})});if(J)throw J;if(i()&&!((Q=Z.options)===null||Q===void 0?void 0:Q.skipBrowserRedirect))window.location.assign(X===null||X===void 0?void 0:X.url);return this._returnResult({data:{provider:Z.provider,url:X===null||X===void 0?void 0:X.url},error:null})}catch(X){if(N(X))return this._returnResult({data:{provider:Z.provider,url:null},error:X});throw X}}async linkIdentityIdToken(Z){return await this._useSession(async(Q)=>{var X;try{let{error:J,data:{session:G}}=Q;if(J)throw J;let{options:Y,provider:z,token:H,access_token:W,nonce:q}=Z,O=await C(this.fetch,"POST",`${this.url}/token?grant_type=id_token`,{headers:this.headers,jwt:(X=G===null||G===void 0?void 0:G.access_token)!==null&&X!==void 0?X:void 0,body:{provider:z,id_token:H,access_token:W,nonce:q,link_identity:!0,gotrue_meta_security:{captcha_token:Y===null||Y===void 0?void 0:Y.captchaToken}},xform:Z0}),{data:M,error:U}=O;if(U)return this._returnResult({data:{user:null,session:null},error:U});else if(!M||!M.session||!M.user)return this._returnResult({data:{user:null,session:null},error:new w0});if(M.session)await this._saveSession(M.session),await this._notifyAllSubscribers("USER_UPDATED",M.session);return this._returnResult({data:M,error:U})}catch(J){if(await n(this.storage,`${this.storageKey}-code-verifier`),N(J))return this._returnResult({data:{user:null,session:null},error:J});throw J}})}async unlinkIdentity(Z){try{return await this._useSession(async(Q)=>{var X,J;let{data:G,error:Y}=Q;if(Y)throw Y;return await C(this.fetch,"DELETE",`${this.url}/user/identities/${Z.identity_id}`,{headers:this.headers,jwt:(J=(X=G.session)===null||X===void 0?void 0:X.access_token)!==null&&J!==void 0?J:void 0})})}catch(Q){if(N(Q))return this._returnResult({data:null,error:Q});throw Q}}async _refreshAccessToken(Z){let Q=`#_refreshAccessToken(${Z.substring(0,5)}...)`;this._debug(Q,"begin");try{let X=Date.now();return await q6(async(J)=>{if(J>0)await W6(200*Math.pow(2,J-1));return this._debug(Q,"refreshing attempt",J),await C(this.fetch,"POST",`${this.url}/token?grant_type=refresh_token`,{body:{refresh_token:Z},headers:this.headers,xform:Z0})},(J,G)=>{let Y=200*Math.pow(2,J);return G&&YQ(G)&&Date.now()+Y-X<j0})}catch(X){if(this._debug(Q,"error",X),N(X))return this._returnResult({data:{session:null,user:null},error:X});throw X}finally{this._debug(Q,"end")}}_isValidSession(Z){return typeof Z==="object"&&Z!==null&&"access_token"in Z&&"refresh_token"in Z&&"expires_at"in Z}async _handleProviderSignIn(Z,Q){let X=await this._getUrlForProvider(`${this.url}/authorize`,Z,{redirectTo:Q.redirectTo,scopes:Q.scopes,queryParams:Q.queryParams});if(this._debug("#_handleProviderSignIn()","provider",Z,"options",Q,"url",X),i()&&!Q.skipBrowserRedirect)window.location.assign(X);return{data:{provider:Z,url:X},error:null}}async _recoverAndRefresh(){var Z,Q;let X="#_recoverAndRefresh()";this._debug("#_recoverAndRefresh()","begin");try{let J=await D0(this.storage,this.storageKey);if(J&&this.userStorage){let Y=await D0(this.userStorage,this.storageKey+"-user");if(!this.storage.isServer&&Object.is(this.storage,this.userStorage)&&!Y)Y={user:J.user},await T0(this.userStorage,this.storageKey+"-user",Y);J.user=(Z=Y===null||Y===void 0?void 0:Y.user)!==null&&Z!==void 0?Z:qQ()}else if(J&&!J.user){if(!J.user){let Y=await D0(this.storage,this.storageKey+"-user");if(Y&&(Y===null||Y===void 0?void 0:Y.user))J.user=Y.user,await n(this.storage,this.storageKey+"-user"),await T0(this.storage,this.storageKey,J);else J.user=qQ()}}if(this._debug("#_recoverAndRefresh()","session from storage",J),!this._isValidSession(J)){if(this._debug("#_recoverAndRefresh()","session is not valid"),J!==null)await this._removeSession();return}let G=((Q=J.expires_at)!==null&&Q!==void 0?Q:1/0)*1000-Date.now()<XQ;if(this._debug("#_recoverAndRefresh()",`session has${G?"":" not"} expired with margin of ${XQ}s`),G){if(this.autoRefreshToken&&J.refresh_token){let{error:Y}=await this._callRefreshToken(J.refresh_token);if(Y){if(console.error(Y),!YQ(Y))this._debug("#_recoverAndRefresh()","refresh failed with a non-retryable error, removing the session",Y),await this._removeSession()}}}else if(J.user&&J.user.__isUserNotAvailableProxy===!0)try{let{data:Y,error:z}=await this._getUser(J.access_token);if(!z&&(Y===null||Y===void 0?void 0:Y.user))J.user=Y.user,await this._saveSession(J),await this._notifyAllSubscribers("SIGNED_IN",J);else this._debug("#_recoverAndRefresh()","could not get user data, skipping SIGNED_IN notification")}catch(Y){console.error("Error getting user data:",Y),this._debug("#_recoverAndRefresh()","error getting user data, skipping SIGNED_IN notification",Y)}else await this._notifyAllSubscribers("SIGNED_IN",J)}catch(J){this._debug("#_recoverAndRefresh()","error",J),console.error(J);return}finally{this._debug("#_recoverAndRefresh()","end")}}async _callRefreshToken(Z){var Q,X;if(!Z)throw new c;if(this.refreshingDeferred)return this.refreshingDeferred.promise;let J=`#_callRefreshToken(${Z.substring(0,5)}...)`;this._debug(J,"begin");try{this.refreshingDeferred=new $Z;let{data:G,error:Y}=await this._refreshAccessToken(Z);if(Y)throw Y;if(!G.session)throw new c;await this._saveSession(G.session),await this._notifyAllSubscribers("TOKEN_REFRESHED",G.session);let z={data:G.session,error:null};return this.refreshingDeferred.resolve(z),z}catch(G){if(this._debug(J,"error",G),N(G)){let Y={data:null,error:G};if(!YQ(G))await this._removeSession();return(Q=this.refreshingDeferred)===null||Q===void 0||Q.resolve(Y),Y}throw(X=this.refreshingDeferred)===null||X===void 0||X.reject(G),G}finally{this.refreshingDeferred=null,this._debug(J,"end")}}async _notifyAllSubscribers(Z,Q,X=!0){let J=`#_notifyAllSubscribers(${Z})`;this._debug(J,"begin",Q,`broadcast = ${X}`);try{if(this.broadcastChannel&&X)this.broadcastChannel.postMessage({event:Z,session:Q});let G=[],Y=Array.from(this.stateChangeEmitters.values()).map(async(z)=>{try{await z.callback(Z,Q)}catch(H){G.push(H)}});if(await Promise.all(Y),G.length>0){for(let z=0;z<G.length;z+=1)console.error(G[z]);throw G[0]}}finally{this._debug(J,"end")}}async _saveSession(Z){this._debug("#_saveSession()",Z),this.suppressGetSessionWarning=!0,await n(this.storage,`${this.storageKey}-code-verifier`);let Q=Object.assign({},Z),X=Q.user&&Q.user.__isUserNotAvailableProxy===!0;if(this.userStorage){if(!X&&Q.user)await T0(this.userStorage,this.storageKey+"-user",{user:Q.user});let J=Object.assign({},Q);delete J.user;let G=lQ(J);await T0(this.storage,this.storageKey,G)}else{let J=lQ(Q);await T0(this.storage,this.storageKey,J)}}async _removeSession(){if(this._debug("#_removeSession()"),this.suppressGetSessionWarning=!1,await n(this.storage,this.storageKey),await n(this.storage,this.storageKey+"-code-verifier"),await n(this.storage,this.storageKey+"-user"),this.userStorage)await n(this.userStorage,this.storageKey+"-user");await this._notifyAllSubscribers("SIGNED_OUT",null)}_removeVisibilityChangedCallback(){this._debug("#_removeVisibilityChangedCallback()");let Z=this.visibilityChangedCallback;this.visibilityChangedCallback=null;try{if(Z&&i()&&(window===null||window===void 0?void 0:window.removeEventListener))window.removeEventListener("visibilitychange",Z)}catch(Q){console.error("removing visibilitychange callback failed",Q)}}async _startAutoRefresh(){await this._stopAutoRefresh(),this._debug("#_startAutoRefresh()");let Z=setInterval(()=>this._autoRefreshTokenTick(),j0);if(this.autoRefreshTicker=Z,Z&&typeof Z==="object"&&typeof Z.unref==="function")Z.unref();else if(typeof Deno!=="undefined"&&typeof Deno.unrefTimer==="function")Deno.unrefTimer(Z);let Q=setTimeout(async()=>{await this.initializePromise,await this._autoRefreshTokenTick()},0);if(this.autoRefreshTickTimeout=Q,Q&&typeof Q==="object"&&typeof Q.unref==="function")Q.unref();else if(typeof Deno!=="undefined"&&typeof Deno.unrefTimer==="function")Deno.unrefTimer(Q)}async _stopAutoRefresh(){this._debug("#_stopAutoRefresh()");let Z=this.autoRefreshTicker;if(this.autoRefreshTicker=null,Z)clearInterval(Z);let Q=this.autoRefreshTickTimeout;if(this.autoRefreshTickTimeout=null,Q)clearTimeout(Q)}async startAutoRefresh(){this._removeVisibilityChangedCallback(),await this._startAutoRefresh()}async stopAutoRefresh(){this._removeVisibilityChangedCallback(),await this._stopAutoRefresh()}async _autoRefreshTokenTick(){this._debug("#_autoRefreshTokenTick()","begin");try{await this._acquireLock(0,async()=>{try{let Z=Date.now();try{return await this._useSession(async(Q)=>{let{data:{session:X}}=Q;if(!X||!X.refresh_token||!X.expires_at){this._debug("#_autoRefreshTokenTick()","no session");return}let J=Math.floor((X.expires_at*1000-Z)/j0);if(this._debug("#_autoRefreshTokenTick()",`access token expires in ${J} ticks, a tick lasts ${j0}ms, refresh threshold is ${QQ} ticks`),J<=QQ)await this._callRefreshToken(X.refresh_token)})}catch(Q){console.error("Auto refresh tick failed with error. This is likely a transient error.",Q)}}finally{this._debug("#_autoRefreshTokenTick()","end")}})}catch(Z){if(Z.isAcquireTimeout||Z instanceof UQ)this._debug("auto refresh token tick lock not available");else throw Z}}async _handleVisibilityChange(){if(this._debug("#_handleVisibilityChange()"),!i()||!(window===null||window===void 0?void 0:window.addEventListener)){if(this.autoRefreshToken)this.startAutoRefresh();return!1}try{this.visibilityChangedCallback=async()=>{try{await this._onVisibilityChanged(!1)}catch(Z){this._debug("#visibilityChangedCallback","error",Z)}},window===null||window===void 0||window.addEventListener("visibilitychange",this.visibilityChangedCallback),await this._onVisibilityChanged(!0)}catch(Z){console.error("_handleVisibilityChange",Z)}}async _onVisibilityChanged(Z){let Q=`#_onVisibilityChanged(${Z})`;if(this._debug(Q,"visibilityState",document.visibilityState),document.visibilityState==="visible"){if(this.autoRefreshToken)this._startAutoRefresh();if(!Z)await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>{if(document.visibilityState!=="visible"){this._debug(Q,"acquired the lock to recover the session, but the browser visibilityState is no longer visible, aborting");return}await this._recoverAndRefresh()})}else if(document.visibilityState==="hidden"){if(this.autoRefreshToken)this._stopAutoRefresh()}}async _getUrlForProvider(Z,Q,X){let J=[`provider=${encodeURIComponent(Q)}`];if(X===null||X===void 0?void 0:X.redirectTo)J.push(`redirect_to=${encodeURIComponent(X.redirectTo)}`);if(X===null||X===void 0?void 0:X.scopes)J.push(`scopes=${encodeURIComponent(X.scopes)}`);if(this.flowType==="pkce"){let[G,Y]=await k0(this.storage,this.storageKey),z=new URLSearchParams({code_challenge:`${encodeURIComponent(G)}`,code_challenge_method:`${encodeURIComponent(Y)}`});J.push(z.toString())}if(X===null||X===void 0?void 0:X.queryParams){let G=new URLSearchParams(X.queryParams);J.push(G.toString())}if(X===null||X===void 0?void 0:X.skipBrowserRedirect)J.push(`skip_http_redirect=${X.skipBrowserRedirect}`);return`${Z}?${J.join("&")}`}async _unenroll(Z){try{return await this._useSession(async(Q)=>{var X;let{data:J,error:G}=Q;if(G)return this._returnResult({data:null,error:G});return await C(this.fetch,"DELETE",`${this.url}/factors/${Z.factorId}`,{headers:this.headers,jwt:(X=J===null||J===void 0?void 0:J.session)===null||X===void 0?void 0:X.access_token})})}catch(Q){if(N(Q))return this._returnResult({data:null,error:Q});throw Q}}async _enroll(Z){try{return await this._useSession(async(Q)=>{var X,J;let{data:G,error:Y}=Q;if(Y)return this._returnResult({data:null,error:Y});let z=Object.assign({friendly_name:Z.friendlyName,factor_type:Z.factorType},Z.factorType==="phone"?{phone:Z.phone}:Z.factorType==="totp"?{issuer:Z.issuer}:{}),{data:H,error:W}=await C(this.fetch,"POST",`${this.url}/factors`,{body:z,headers:this.headers,jwt:(X=G===null||G===void 0?void 0:G.session)===null||X===void 0?void 0:X.access_token});if(W)return this._returnResult({data:null,error:W});if(Z.factorType==="totp"&&H.type==="totp"&&((J=H===null||H===void 0?void 0:H.totp)===null||J===void 0?void 0:J.qr_code))H.totp.qr_code=`data:image/svg+xml;utf-8,${H.totp.qr_code}`;return this._returnResult({data:H,error:null})})}catch(Q){if(N(Q))return this._returnResult({data:null,error:Q});throw Q}}async _verify(Z){return this._acquireLock(this.lockAcquireTimeout,async()=>{try{return await this._useSession(async(Q)=>{var X;let{data:J,error:G}=Q;if(G)return this._returnResult({data:null,error:G});let Y=Object.assign({challenge_id:Z.challengeId},"webauthn"in Z?{webauthn:Object.assign(Object.assign({},Z.webauthn),{credential_response:Z.webauthn.type==="create"?eQ(Z.webauthn.credential_response):Z1(Z.webauthn.credential_response)})}:{code:Z.code}),{data:z,error:H}=await C(this.fetch,"POST",`${this.url}/factors/${Z.factorId}/verify`,{body:Y,headers:this.headers,jwt:(X=J===null||J===void 0?void 0:J.session)===null||X===void 0?void 0:X.access_token});if(H)return this._returnResult({data:null,error:H});return await this._saveSession(Object.assign({expires_at:Math.round(Date.now()/1000)+z.expires_in},z)),await this._notifyAllSubscribers("MFA_CHALLENGE_VERIFIED",z),this._returnResult({data:z,error:H})})}catch(Q){if(N(Q))return this._returnResult({data:null,error:Q});throw Q}})}async _challenge(Z){return this._acquireLock(this.lockAcquireTimeout,async()=>{try{return await this._useSession(async(Q)=>{var X;let{data:J,error:G}=Q;if(G)return this._returnResult({data:null,error:G});let Y=await C(this.fetch,"POST",`${this.url}/factors/${Z.factorId}/challenge`,{body:Z,headers:this.headers,jwt:(X=J===null||J===void 0?void 0:J.session)===null||X===void 0?void 0:X.access_token});if(Y.error)return Y;let{data:z}=Y;if(z.type!=="webauthn")return{data:z,error:null};switch(z.webauthn.type){case"create":return{data:Object.assign(Object.assign({},z),{webauthn:Object.assign(Object.assign({},z.webauthn),{credential_options:Object.assign(Object.assign({},z.webauthn.credential_options),{publicKey:tQ(z.webauthn.credential_options.publicKey)})})}),error:null};case"request":return{data:Object.assign(Object.assign({},z),{webauthn:Object.assign(Object.assign({},z.webauthn),{credential_options:Object.assign(Object.assign({},z.webauthn.credential_options),{publicKey:rQ(z.webauthn.credential_options.publicKey)})})}),error:null}}})}catch(Q){if(N(Q))return this._returnResult({data:null,error:Q});throw Q}})}async _challengeAndVerify(Z){let{data:Q,error:X}=await this._challenge({factorId:Z.factorId});if(X)return this._returnResult({data:null,error:X});return await this._verify({factorId:Z.factorId,challengeId:Q.id,code:Z.code})}async _listFactors(){var Z;let{data:{user:Q},error:X}=await this.getUser();if(X)return{data:null,error:X};let J={all:[],phone:[],totp:[],webauthn:[]};for(let G of(Z=Q===null||Q===void 0?void 0:Q.factors)!==null&&Z!==void 0?Z:[])if(J.all.push(G),G.status==="verified")J[G.factor_type].push(G);return{data:J,error:null}}async _getAuthenticatorAssuranceLevel(Z){var Q,X,J,G;if(Z)try{let{payload:U}=BZ(Z),$=null;if(U.aal)$=U.aal;let K=$,{data:{user:w},error:V}=await this.getUser(Z);if(V)return this._returnResult({data:null,error:V});if(((X=(Q=w===null||w===void 0?void 0:w.factors)===null||Q===void 0?void 0:Q.filter((D)=>D.status==="verified"))!==null&&X!==void 0?X:[]).length>0)K="aal2";let F=U.amr||[];return{data:{currentLevel:$,nextLevel:K,currentAuthenticationMethods:F},error:null}}catch(U){if(N(U))return this._returnResult({data:null,error:U});throw U}let{data:{session:Y},error:z}=await this.getSession();if(z)return this._returnResult({data:null,error:z});if(!Y)return{data:{currentLevel:null,nextLevel:null,currentAuthenticationMethods:[]},error:null};let{payload:H}=BZ(Y.access_token),W=null;if(H.aal)W=H.aal;let q=W;if(((G=(J=Y.user.factors)===null||J===void 0?void 0:J.filter((U)=>U.status==="verified"))!==null&&G!==void 0?G:[]).length>0)q="aal2";let M=H.amr||[];return{data:{currentLevel:W,nextLevel:q,currentAuthenticationMethods:M},error:null}}async _getAuthorizationDetails(Z){try{return await this._useSession(async(Q)=>{let{data:{session:X},error:J}=Q;if(J)return this._returnResult({data:null,error:J});if(!X)return this._returnResult({data:null,error:new c});return await C(this.fetch,"GET",`${this.url}/oauth/authorizations/${Z}`,{headers:this.headers,jwt:X.access_token,xform:(G)=>({data:G,error:null})})})}catch(Q){if(N(Q))return this._returnResult({data:null,error:Q});throw Q}}async _approveAuthorization(Z,Q){try{return await this._useSession(async(X)=>{let{data:{session:J},error:G}=X;if(G)return this._returnResult({data:null,error:G});if(!J)return this._returnResult({data:null,error:new c});let Y=await C(this.fetch,"POST",`${this.url}/oauth/authorizations/${Z}/consent`,{headers:this.headers,jwt:J.access_token,body:{action:"approve"},xform:(z)=>({data:z,error:null})});if(Y.data&&Y.data.redirect_url){if(i()&&!(Q===null||Q===void 0?void 0:Q.skipBrowserRedirect))window.location.assign(Y.data.redirect_url)}return Y})}catch(X){if(N(X))return this._returnResult({data:null,error:X});throw X}}async _denyAuthorization(Z,Q){try{return await this._useSession(async(X)=>{let{data:{session:J},error:G}=X;if(G)return this._returnResult({data:null,error:G});if(!J)return this._returnResult({data:null,error:new c});let Y=await C(this.fetch,"POST",`${this.url}/oauth/authorizations/${Z}/consent`,{headers:this.headers,jwt:J.access_token,body:{action:"deny"},xform:(z)=>({data:z,error:null})});if(Y.data&&Y.data.redirect_url){if(i()&&!(Q===null||Q===void 0?void 0:Q.skipBrowserRedirect))window.location.assign(Y.data.redirect_url)}return Y})}catch(X){if(N(X))return this._returnResult({data:null,error:X});throw X}}async _listOAuthGrants(){try{return await this._useSession(async(Z)=>{let{data:{session:Q},error:X}=Z;if(X)return this._returnResult({data:null,error:X});if(!Q)return this._returnResult({data:null,error:new c});return await C(this.fetch,"GET",`${this.url}/user/oauth/grants`,{headers:this.headers,jwt:Q.access_token,xform:(J)=>({data:J,error:null})})})}catch(Z){if(N(Z))return this._returnResult({data:null,error:Z});throw Z}}async _revokeOAuthGrant(Z){try{return await this._useSession(async(Q)=>{let{data:{session:X},error:J}=Q;if(J)return this._returnResult({data:null,error:J});if(!X)return this._returnResult({data:null,error:new c});return await C(this.fetch,"DELETE",`${this.url}/user/oauth/grants`,{headers:this.headers,jwt:X.access_token,query:{client_id:Z.clientId},noResolveJson:!0}),{data:{},error:null}})}catch(Q){if(N(Q))return this._returnResult({data:null,error:Q});throw Q}}async fetchJwk(Z,Q={keys:[]}){let X=Q.keys.find((z)=>z.kid===Z);if(X)return X;let J=Date.now();if(X=this.jwks.keys.find((z)=>z.kid===Z),X&&this.jwks_cached_at+t8>J)return X;let{data:G,error:Y}=await C(this.fetch,"GET",`${this.url}/.well-known/jwks.json`,{headers:this.headers});if(Y)throw Y;if(!G.keys||G.keys.length===0)return null;if(this.jwks=G,this.jwks_cached_at=J,X=G.keys.find((z)=>z.kid===Z),!X)return null;return X}async getClaims(Z,Q={}){try{let X=Z;if(!X){let{data:U,error:$}=await this.getSession();if($||!U.session)return this._returnResult({data:null,error:$});X=U.session.access_token}let{header:J,payload:G,signature:Y,raw:{header:z,payload:H}}=BZ(X);if(!(Q===null||Q===void 0?void 0:Q.allowExpired))M6(G.exp);let W=!J.alg||J.alg.startsWith("HS")||!J.kid||!(("crypto"in globalThis)&&("subtle"in globalThis.crypto))?null:await this.fetchJwk(J.kid,(Q===null||Q===void 0?void 0:Q.keys)?{keys:Q.keys}:Q===null||Q===void 0?void 0:Q.jwks);if(!W){let{error:U}=await this.getUser(X);if(U)throw U;return{data:{claims:G,header:J,signature:Y},error:null}}let q=U6(J.alg),O=await crypto.subtle.importKey("jwk",W,q,!0,["verify"]);if(!await crypto.subtle.verify(q,O,Y,J6(`${z}.${H}`)))throw new l0("Invalid JWT signature");return{data:{claims:G,header:J,signature:Y},error:null}}catch(X){if(N(X))return this._returnResult({data:null,error:X});throw X}}async signInWithPasskey(Z){var Q,X,J;e(this.experimental);try{if(!FZ())return this._returnResult({data:null,error:new s("Browser does not support WebAuthn",null)});let{data:G,error:Y}=await this._startPasskeyAuthentication({options:{captchaToken:(Q=Z===null||Z===void 0?void 0:Z.options)===null||Q===void 0?void 0:Q.captchaToken}});if(Y||!G)return this._returnResult({data:null,error:Y});let z=rQ(G.options),H=(J=(X=Z===null||Z===void 0?void 0:Z.options)===null||X===void 0?void 0:X.signal)!==null&&J!==void 0?J:$Q.createNewAbortSignal(),{data:W,error:q}=await X1({publicKey:z,signal:H});if(q||!W)return this._returnResult({data:null,error:q!==null&&q!==void 0?q:new s("WebAuthn ceremony failed",null)});let O=Z1(W);return this._verifyPasskeyAuthentication({challengeId:G.challenge_id,credential:O})}catch(G){if(N(G))return this._returnResult({data:null,error:G});throw G}}async registerPasskey(Z){var Q,X;e(this.experimental);try{if(!FZ())return this._returnResult({data:null,error:new s("Browser does not support WebAuthn",null)});let{data:J,error:G}=await this._startPasskeyRegistration();if(G||!J)return this._returnResult({data:null,error:G});let Y=tQ(J.options),z=(X=(Q=Z===null||Z===void 0?void 0:Z.options)===null||Q===void 0?void 0:Q.signal)!==null&&X!==void 0?X:$Q.createNewAbortSignal(),{data:H,error:W}=await Q1({publicKey:Y,signal:z});if(W||!H)return this._returnResult({data:null,error:W!==null&&W!==void 0?W:new s("WebAuthn ceremony failed",null)});let q=eQ(H);return this._verifyPasskeyRegistration({challengeId:J.challenge_id,credential:q})}catch(J){if(N(J))return this._returnResult({data:null,error:J});throw J}}async _startPasskeyRegistration(){e(this.experimental);try{return await this._useSession(async(Z)=>{let{data:{session:Q},error:X}=Z;if(X)return this._returnResult({data:null,error:X});if(!Q)return this._returnResult({data:null,error:new c});let{data:J,error:G}=await C(this.fetch,"POST",`${this.url}/passkeys/registration/options`,{headers:this.headers,jwt:Q.access_token,body:{}});if(G)return this._returnResult({data:null,error:G});return this._returnResult({data:J,error:null})})}catch(Z){if(N(Z))return this._returnResult({data:null,error:Z});throw Z}}async _verifyPasskeyRegistration(Z){e(this.experimental);try{return await this._useSession(async(Q)=>{let{data:{session:X},error:J}=Q;if(J)return this._returnResult({data:null,error:J});if(!X)return this._returnResult({data:null,error:new c});let{data:G,error:Y}=await C(this.fetch,"POST",`${this.url}/passkeys/registration/verify`,{headers:this.headers,jwt:X.access_token,body:{challenge_id:Z.challengeId,credential:Z.credential}});if(Y)return this._returnResult({data:null,error:Y});return this._returnResult({data:G,error:null})})}catch(Q){if(N(Q))return this._returnResult({data:null,error:Q});throw Q}}async _startPasskeyAuthentication(Z){var Q;e(this.experimental);try{let{data:X,error:J}=await C(this.fetch,"POST",`${this.url}/passkeys/authentication/options`,{headers:this.headers,body:{gotrue_meta_security:{captcha_token:(Q=Z===null||Z===void 0?void 0:Z.options)===null||Q===void 0?void 0:Q.captchaToken}}});if(J)return this._returnResult({data:null,error:J});return this._returnResult({data:X,error:null})}catch(X){if(N(X))return this._returnResult({data:null,error:X});throw X}}async _verifyPasskeyAuthentication(Z){e(this.experimental);try{let{data:Q,error:X}=await C(this.fetch,"POST",`${this.url}/passkeys/authentication/verify`,{headers:this.headers,body:{challenge_id:Z.challengeId,credential:Z.credential},xform:Z0});if(X)return this._returnResult({data:null,error:X});if(Q.session)await this._saveSession(Q.session),await this._notifyAllSubscribers("SIGNED_IN",Q.session);return this._returnResult({data:Q,error:null})}catch(Q){if(N(Q))return this._returnResult({data:null,error:Q});throw Q}}async _listPasskeys(){e(this.experimental);try{return await this._useSession(async(Z)=>{let{data:{session:Q},error:X}=Z;if(X)return this._returnResult({data:null,error:X});if(!Q)return this._returnResult({data:null,error:new c});let{data:J,error:G}=await C(this.fetch,"GET",`${this.url}/passkeys`,{headers:this.headers,jwt:Q.access_token,xform:(Y)=>({data:Y,error:null})});if(G)return this._returnResult({data:null,error:G});return this._returnResult({data:J,error:null})})}catch(Z){if(N(Z))return this._returnResult({data:null,error:Z});throw Z}}async _updatePasskey(Z){e(this.experimental);try{return await this._useSession(async(Q)=>{let{data:{session:X},error:J}=Q;if(J)return this._returnResult({data:null,error:J});if(!X)return this._returnResult({data:null,error:new c});let{data:G,error:Y}=await C(this.fetch,"PATCH",`${this.url}/passkeys/${Z.passkeyId}`,{headers:this.headers,jwt:X.access_token,body:{friendly_name:Z.friendlyName}});if(Y)return this._returnResult({data:null,error:Y});return this._returnResult({data:G,error:null})})}catch(Q){if(N(Q))return this._returnResult({data:null,error:Q});throw Q}}async _deletePasskey(Z){e(this.experimental);try{return await this._useSession(async(Q)=>{let{data:{session:X},error:J}=Q;if(J)return this._returnResult({data:null,error:J});if(!X)return this._returnResult({data:null,error:new c});let{error:G}=await C(this.fetch,"DELETE",`${this.url}/passkeys/${Z.passkeyId}`,{headers:this.headers,jwt:X.access_token,noResolveJson:!0});if(G)return this._returnResult({data:null,error:G});return this._returnResult({data:null,error:null})})}catch(Q){if(N(Q))return this._returnResult({data:null,error:Q});throw Q}}}VZ.nextInstanceID={};var Y1=VZ;var v9=Y1,G1=v9;var f9="2.105.0",LZ="";if(typeof Deno!=="undefined")LZ="deno";else if(typeof document!=="undefined")LZ="web";else if(typeof navigator!=="undefined"&&navigator.product==="ReactNative")LZ="react-native";else LZ="node";var b9={"X-Client-Info":`supabase-js-${LZ}/${f9}`},y9={headers:b9},g9={schema:"public"},_9={autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,flowType:"implicit"},h9={};function wZ(Z){return wZ=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(Q){return typeof Q}:function(Q){return Q&&typeof Symbol=="function"&&Q.constructor===Symbol&&Q!==Symbol.prototype?"symbol":typeof Q},wZ(Z)}function m9(Z,Q){if(wZ(Z)!="object"||!Z)return Z;var X=Z[Symbol.toPrimitive];if(X!==void 0){var J=X.call(Z,Q||"default");if(wZ(J)!="object")return J;throw new TypeError("@@toPrimitive must return a primitive value.")}return(Q==="string"?String:Number)(Z)}function u9(Z){var Q=m9(Z,"string");return wZ(Q)=="symbol"?Q:Q+""}function d9(Z,Q,X){return(Q=u9(Q))in Z?Object.defineProperty(Z,Q,{value:X,enumerable:!0,configurable:!0,writable:!0}):Z[Q]=X,Z}function P6(Z,Q){var X=Object.keys(Z);if(Object.getOwnPropertySymbols){var J=Object.getOwnPropertySymbols(Z);Q&&(J=J.filter(function(G){return Object.getOwnPropertyDescriptor(Z,G).enumerable})),X.push.apply(X,J)}return X}function m(Z){for(var Q=1;Q<arguments.length;Q++){var X=arguments[Q]!=null?arguments[Q]:{};Q%2?P6(Object(X),!0).forEach(function(J){d9(Z,J,X[J])}):Object.getOwnPropertyDescriptors?Object.defineProperties(Z,Object.getOwnPropertyDescriptors(X)):P6(Object(X)).forEach(function(J){Object.defineProperty(Z,J,Object.getOwnPropertyDescriptor(X,J))})}return Z}var c9=(Z)=>{if(Z)return(...Q)=>Z(...Q);return(...Q)=>fetch(...Q)},l9=()=>{return Headers},p9=(Z,Q,X)=>{let J=c9(X),G=l9();return async(Y,z)=>{var H;let W=(H=await Q())!==null&&H!==void 0?H:Z,q=new G(z===null||z===void 0?void 0:z.headers);if(!q.has("apikey"))q.set("apikey",Z);if(!q.has("Authorization"))q.set("Authorization",`Bearer ${W}`);return J(Y,m(m({},z),{},{headers:q}))}};function i9(Z){return Z.endsWith("/")?Z:Z+"/"}function n9(Z,Q){var X,J;let{db:G,auth:Y,realtime:z,global:H}=Z,{db:W,auth:q,realtime:O,global:M}=Q,U={db:m(m({},W),G),auth:m(m({},q),Y),realtime:m(m({},O),z),storage:{},global:m(m(m({},M),H),{},{headers:m(m({},(X=M===null||M===void 0?void 0:M.headers)!==null&&X!==void 0?X:{}),(J=H===null||H===void 0?void 0:H.headers)!==null&&J!==void 0?J:{})}),accessToken:async()=>""};if(Z.accessToken)U.accessToken=Z.accessToken;else delete U.accessToken;return U}function a9(Z){let Q=Z===null||Z===void 0?void 0:Z.trim();if(!Q)throw new Error("supabaseUrl is required.");if(!Q.match(/^https?:\/\//i))throw new Error("Invalid supabaseUrl: Must be a valid HTTP or HTTPS URL.");try{return new URL(i9(Q))}catch(X){throw Error("Invalid supabaseUrl: Provided URL is malformed.")}}var s9=class extends G1{constructor(Z){super(Z)}},o9=class{constructor(Z,Q,X){var J,G;this.supabaseUrl=Z,this.supabaseKey=Q;let Y=a9(Z);if(!Q)throw new Error("supabaseKey is required.");this.realtimeUrl=new URL("realtime/v1",Y),this.realtimeUrl.protocol=this.realtimeUrl.protocol.replace("http","ws"),this.authUrl=new URL("auth/v1",Y),this.storageUrl=new URL("storage/v1",Y),this.functionsUrl=new URL("functions/v1",Y);let z=`sb-${Y.hostname.split(".")[0]}-auth-token`,H={db:g9,realtime:h9,auth:m(m({},_9),{},{storageKey:z}),global:y9},W=n9(X!==null&&X!==void 0?X:{},H);if(this.storageKey=(J=W.auth.storageKey)!==null&&J!==void 0?J:"",this.headers=(G=W.global.headers)!==null&&G!==void 0?G:{},!W.accessToken){var q;this.auth=this._initSupabaseAuthClient((q=W.auth)!==null&&q!==void 0?q:{},this.headers,W.global.fetch)}else this.accessToken=W.accessToken,this.auth=new Proxy({},{get:(O,M)=>{throw new Error(`@supabase/supabase-js: Supabase Client is configured with the accessToken option, accessing supabase.auth.${String(M)} is not possible`)}});if(this.fetch=p9(Q,this._getAccessToken.bind(this),W.global.fetch),this.realtime=this._initRealtimeClient(m({headers:this.headers,accessToken:this._getAccessToken.bind(this),fetch:this.fetch},W.realtime)),this.accessToken)Promise.resolve(this.accessToken()).then((O)=>this.realtime.setAuth(O)).catch((O)=>console.warn("Failed to set initial Realtime auth token:",O));if(this.rest=new P8(new URL("rest/v1",Y).href,{headers:this.headers,schema:W.db.schema,fetch:this.fetch,timeout:W.db.timeout,urlLengthLimit:W.db.urlLengthLimit}),this.storage=new i8(this.storageUrl.href,this.headers,this.fetch,X===null||X===void 0?void 0:X.storage),!W.accessToken)this._listenForAuthEvents()}get functions(){return new _Z(this.functionsUrl.href,{headers:this.headers,customFetch:this.fetch})}from(Z){return this.rest.from(Z)}schema(Z){return this.rest.schema(Z)}rpc(Z,Q={},X={head:!1,get:!1,count:void 0}){return this.rest.rpc(Z,Q,X)}channel(Z,Q={config:{}}){return this.realtime.channel(Z,Q)}getChannels(){return this.realtime.getChannels()}removeChannel(Z){return this.realtime.removeChannel(Z)}removeAllChannels(){return this.realtime.removeAllChannels()}async _getAccessToken(){var Z=this,Q,X;if(Z.accessToken)return await Z.accessToken();let{data:J}=await Z.auth.getSession();return(Q=(X=J.session)===null||X===void 0?void 0:X.access_token)!==null&&Q!==void 0?Q:Z.supabaseKey}_initSupabaseAuthClient({autoRefreshToken:Z,persistSession:Q,detectSessionInUrl:X,storage:J,userStorage:G,storageKey:Y,flowType:z,lock:H,debug:W,throwOnError:q,experimental:O},M,U){let $={Authorization:`Bearer ${this.supabaseKey}`,apikey:`${this.supabaseKey}`};return new s9({url:this.authUrl.href,headers:m(m({},$),M),storageKey:Y,autoRefreshToken:Z,persistSession:Q,detectSessionInUrl:X,storage:J,userStorage:G,flowType:z,lock:H,debug:W,throwOnError:q,experimental:O,fetch:U,hasCustomAuthorizationHeader:Object.keys(this.headers).some((K)=>K.toLowerCase()==="authorization")})}_initRealtimeClient(Z){return new GZ(this.realtimeUrl.href,m(m({},Z),{},{params:m(m({},{apikey:this.supabaseKey}),Z===null||Z===void 0?void 0:Z.params)}))}_listenForAuthEvents(){return this.auth.onAuthStateChange((Z,Q)=>{this._handleTokenChanged(Z,"CLIENT",Q===null||Q===void 0?void 0:Q.access_token)})}_handleTokenChanged(Z,Q,X){if((Z==="TOKEN_REFRESHED"||Z==="SIGNED_IN")&&this.changedAccessToken!==X)this.changedAccessToken=X,this.realtime.setAuth(X);else if(Z==="SIGNED_OUT"){if(this.realtime.setAuth(),Q=="STORAGE")this.auth.signOut();this.changedAccessToken=void 0}}},BQ=(Z,Q,X)=>{return new o9(Z,Q,X)};function t9(){if(typeof window!=="undefined")return!1;let Z=globalThis.process;if(!Z)return!1;let Q=Z.version;if(Q===void 0||Q===null)return!1;let X=Q.match(/^v(\d+)\./);if(!X)return!1;return parseInt(X[1],10)<=18}if(t9())console.warn("\u26A0\uFE0F Node.js 18 and below are deprecated and will no longer be supported in future versions of @supabase/supabase-js. Please upgrade to Node.js 20 or later. For more information, visit: https://github.com/orgs/supabase/discussions/37217");function A6(Z,Q){return BQ(Z.url,Z.publishableKey,{auth:{flowType:"pkce",autoRefreshToken:!1,persistSession:!1,detectSessionInUrl:!1},global:{headers:{Authorization:`Bearer ${Q}`}}})}async function z1(Z,Q,X){let J=A6(Z,X),{error:G}=await J.from("user_trials").insert({user_id:Q});if(G&&G.code!=="23505")throw new Error(`Failed to start trial: ${G.message}`)}async function FQ(Z,Q){let X=A6(Z,Q),{data:J,error:G}=await X.from("user_trials").select("started_at").maybeSingle();if(G)return null;return J?.started_at??null}var e9="https://robbzuhuqcgpfevaorux.supabase.co",ZJ="sb_publishable_E31lRt1Z8hq3XuJIutiB3g_Y2sSEc5D";function W1(Z){return{url:e9,publishableKey:ZJ,sessionFilePath:Z}}function q1(Z){return BQ(Z.url,Z.publishableKey,{auth:{flowType:"pkce",autoRefreshToken:!1,persistSession:!1,detectSessionInUrl:!1}})}async function QJ(Z){let Q=process.platform,X=Q==="darwin"?["open",Z]:Q==="win32"?["cmd","/c","start","",Z]:["xdg-open",Z];await Bun.spawn(X,{stdout:"ignore",stderr:"ignore"}).exited}async function j6(Z){let Q=Bun.file(Z.sessionFilePath);if(!await Q.exists())return null;try{let X=JSON.parse(await Q.text());if(!X.accessToken||!X.refreshToken)return null;return X}catch{return null}}async function x6(Z,Q){let X=r9(Z.sessionFilePath);await Bun.$`mkdir -p ${X}`,await Bun.write(Z.sessionFilePath,JSON.stringify(Q,null,2))}function H1(Z,Q){return`<!doctype html><html><head><meta charset="utf-8"><title>${Z}</title></head><body><h2>${Z}</h2><p>${Q}</p><p>You can close this tab and return to your terminal.</p></body></html>`}async function S6(Z){let Q=q1(Z),X=null,J=null,G=new Promise((H,W)=>{X=H,J=W}),Y=Bun.serve({hostname:"127.0.0.1",port:0,fetch(H){let W=new URL(H.url);if(W.pathname!=="/auth/callback")return new Response("Not Found",{status:404});let q=W.searchParams.get("error_description");if(q)return J?.(new Error(q)),new Response(H1("Authentication failed",`Error: ${q}`),{headers:{"content-type":"text/html; charset=utf-8"}});let O=W.searchParams.get("code");if(!O)return J?.(new Error("Missing OAuth code in callback URL.")),new Response(H1("Authentication failed","Missing authorization code."),{headers:{"content-type":"text/html; charset=utf-8"}});return X?.(O),new Response(H1("Authentication successful","Login completed."),{headers:{"content-type":"text/html; charset=utf-8"}})}}),z=`http://127.0.0.1:${Y.port}/auth/callback`;try{let{data:H,error:W}=await Q.auth.signInWithOAuth({provider:"github",options:{redirectTo:z}});if(W)throw new Error(`Could not start GitHub login: ${W.message}`);if(!H.url)throw new Error("Supabase did not return an OAuth URL.");console.log("Opening GitHub login in your browser..."),await QJ(H.url),console.log("Waiting for authentication callback...");let q=await Promise.race([G,new Promise((U,$)=>setTimeout(()=>$(new Error("Timed out waiting for OAuth callback.")),180000))]),{data:O,error:M}=await Q.auth.exchangeCodeForSession(q);if(M||!O.session||!O.user)throw new Error(M?.message||"Failed to exchange OAuth code for session.");return await x6(Z,{accessToken:O.session.access_token,refreshToken:O.session.refresh_token,expiresAt:O.session.expires_at??null,user:{id:O.user.id,email:O.user.email??null,createdAt:O.user.created_at??null}}),await z1(Z,O.user.id,O.session.access_token),{id:O.user.id,email:O.user.email??null,createdAt:O.user.created_at??null,accessToken:O.session.access_token}}finally{Y.stop(!0)}}async function T6(Z){let Q=await j6(Z);if(!Q)return;let X=q1(Z);await X.auth.setSession({access_token:Q.accessToken,refresh_token:Q.refreshToken}),await X.auth.signOut(),await Bun.$`rm -f ${Z.sessionFilePath}`}async function VQ(Z){let Q=await j6(Z);if(!Q)return null;let X=q1(Z),{data:J,error:G}=await X.auth.setSession({access_token:Q.accessToken,refresh_token:Q.refreshToken});if(G||!J.session)return null;let Y=J.session,{data:z,error:H}=await X.auth.getUser();if(H||!z.user)return null;return await x6(Z,{accessToken:Y.access_token,refreshToken:Y.refresh_token,expiresAt:Y.expires_at??null,user:{id:z.user.id,email:z.user.email??null,createdAt:z.user.created_at??null}}),{id:z.user.id,email:z.user.email??null,createdAt:z.user.created_at??null,accessToken:Y.access_token}}class NZ{name="claude-code";displayName="Claude Code";defaultPath="claude";promptFlag="-p";buildArgs(Z){let Q=[];if(Z.skipPermissions)Q.push("--dangerously-skip-permissions");if(Z.model)Q.push("--model",Z.model);if(Z.maxTurns!==void 0)Q.push("--max-turns",String(Z.maxTurns));return Q}}class DZ{name="cline";displayName="Cline";defaultPath="cline";buildArgs(Z){let Q=["task"];if(Z.skipPermissions)Q.push("--yolo");if(Z.model)Q.push("--model",Z.model);return Q}}class RZ{name="codex";displayName="Codex";defaultPath="codex";buildArgs(Z){let Q=["exec"];if(Z.skipPermissions)Q.push("--sandbox","workspace-write","--ask-for-approval","never");if(Z.model)Q.push("--model",Z.model);return Q}}class IZ{name="cursor";displayName="Cursor";defaultPath="agent";promptFlag="-p";buildArgs(Z){let Q=[];if(Z.skipPermissions)Q.push("--force");if(Z.model)Q.push("--model",Z.model);return Q}}class CZ{name="gemini";displayName="Gemini CLI";defaultPath="gemini";promptFlag="-p";buildArgs(Z){let Q=[];if(Z.skipPermissions)Q.push("--approval-mode=yolo");if(Z.model)Q.push("--model",Z.model);return Q}}class PZ{name="goose";displayName="Goose";defaultPath="goose";promptFlag="-t";buildArgs(Z){let Q=["run"];if(Z.skipPermissions)Q.push("--no-session");if(Z.model)Q.push("--model",Z.model);return Q}}class AZ{name="kilo-code";displayName="Kilo Code";defaultPath="kilo";buildArgs(Z){let Q=["run"];if(Z.skipPermissions)Q.push("--auto");if(Z.model)Q.push("--model",Z.model);return Q}}class jZ{name="kimi";displayName="Kimi CLI";defaultPath="kimi";promptFlag="--prompt";buildArgs(Z){let Q=["--print"];if(Z.skipPermissions)Q.push("--yolo");if(Z.model)Q.push("--model",Z.model);return Q}}class xZ{name="opencode";displayName="Opencode";defaultPath="opencode";buildArgs(Z){let Q=["run"];if(Z.skipPermissions)Q.push("--dangerously-skip-permissions");if(Z.model)Q.push("--model",Z.model);return Q}}class SZ{name="pi";displayName="Pi";defaultPath="pi";promptFlag="-p";buildArgs(Z){return[]}}class TZ{name="qwen";displayName="Qwen Code";defaultPath="qwen";promptFlag="-p";buildArgs(Z){let Q=[];if(Z.skipPermissions)Q.push("--yolo");return Q}}var O1=new Map;function X0(Z){O1.set(Z.name,Z)}function M1(Z){return O1.get(Z)}function U1(){return Array.from(O1.values())}X0(new NZ);X0(new DZ);X0(new RZ);X0(new IZ);X0(new CZ);X0(new PZ);X0(new AZ);X0(new jZ);X0(new xZ);X0(new SZ);X0(new TZ);function K1(Z){let Q=process.env,X=Z?.harnessName;if(!X)X=Q.AGENT_HARNESS;if(!X)X="claude-code";let J=M1(X);if(!J){let Y=U1().map((z)=>`"${z.name}"`).join(", ");throw new Error(`Unknown agent harness: "${X}". Available harnesses: ${Y}. Set AGENT_HARNESS or pass harnessName explicitly.`)}let G=Z?.cliPath;if(!G){let Y=Z?.envPrefix??J.name.toUpperCase().replace(/-/g,"_");G=Q.AGENT_CLI_PATH||Q[`${Y}_CLI_PATH`]||Q.CLAUDE_CLI_PATH}if(!G)G=J.defaultPath;return{harness:J,path:G}}async function $1(Z,Q,X,J={}){let G=J.inputMethod??"arg",Y=Z.buildArgs(J);if(G==="arg")if(Z.promptFlag)Y.push(Z.promptFlag,X);else Y.push(X);if(!J.silent)console.log(`
47
+ \uD83E\uDD16 Running ${Z.displayName}...
48
+ `);let z=Bun.spawn([Q,...Y],{stdout:"pipe",stderr:"pipe",stdin:G==="stdin"?"pipe":void 0});if(G==="stdin"&&z.stdin)z.stdin.write(X),z.stdin.end();let[H,W]=await Promise.all([new Response(z.stdout).text(),new Response(z.stderr).text()]),q=await z.exited;return{stdout:H,stderr:W,exitCode:q}}function JJ(Z){return Z.replace(/^https?:\/\//,"").replace(/\/+$/,"")}async function k6(){let Z=process.cwd(),Q=v0(Z,".devintern-pm"),X=v0(Z,".claude-pm");if(await Bun.file(v0(Q,".")).exists().catch(()=>!1))return;if(await Bun.file(v0(X,".")).exists().catch(()=>!1))try{await XJ(X,Q),console.log("\u2139\uFE0F Migrated legacy config directory: .claude-pm \u2192 .devintern-pm")}catch(Y){console.warn(`\u26A0\uFE0F Failed to migrate legacy config directory .claude-pm: ${Y instanceof Error?Y.message:Y}`)}}async function YJ(){let Z=v0(process.cwd(),".devintern-pm",".env");try{let Q=Bun.file(Z);if(await Q.exists()){let X=await Q.text();for(let J of X.split(`
49
+ `)){let G=J.trim();if(G&&!G.startsWith("#")){let[Y,...z]=G.split("=");if(Y&&z.length>0){let H=z.join("=").trim();if(H.startsWith('"')&&H.endsWith('"')||H.startsWith("'")&&H.endsWith("'"))H=H.slice(1,-1);process.env[Y.trim()]=H}}}}}catch{}}async function LQ(){return W1(v0(process.cwd(),".devintern-pm",".auth-session.json"))}async function E6(){await YJ();let Z=process.env.TASK_TRACKER||"jira",Q={type:Z,directory:process.env.MARKDOWN_TASKS_DIR},X,J,G,Y,z,H;if(Z==="jira"){let O=["JIRA_BASE_URL","JIRA_EMAIL","JIRA_API_TOKEN","JIRA_DEFAULT_PROJECT_KEY"].filter((w)=>!process.env[w]);if(O.length>0)throw new Error(`Missing required environment variables: ${O.join(", ")}
50
+ Please copy .env.example to .env and fill in the values.`);let M=process.env.JIRA_BASE_URL,U=process.env.JIRA_EMAIL,$=process.env.JIRA_API_TOKEN,K=process.env.JIRA_DEFAULT_PROJECT_KEY;if(!M||!U||!$||!K)throw new Error("Configuration was expected but missing after validation.");X={domain:JJ(M),email:U,apiToken:$,defaultProjectKey:K}}if(Z==="linear"){let q=process.env.LINEAR_API_KEY;if(!q)throw new Error("Linear backend selected but LINEAR_API_KEY is missing. Please set LINEAR_API_KEY in your environment.");J={apiKey:q,defaultTeamKey:process.env.LINEAR_DEFAULT_TEAM_KEY}}if(Z==="trello"){let O=["TRELLO_API_KEY","TRELLO_API_TOKEN"].filter(($)=>!process.env[$]);if(O.length>0)throw new Error(`Missing required environment variables: ${O.join(", ")}
51
+ Please set TRELLO_API_KEY and TRELLO_API_TOKEN in your environment.`);let M=process.env.TRELLO_API_KEY,U=process.env.TRELLO_API_TOKEN;if(!M||!U)throw new Error("Trello configuration was expected but missing after validation.");G={apiKey:M,apiToken:U,defaultBoardId:process.env.TRELLO_DEFAULT_BOARD_ID,defaultListId:process.env.TRELLO_DEFAULT_LIST_ID}}if(Z==="azure-devops"){let O=["AZURE_DEVOPS_ORG","AZURE_DEVOPS_PAT","AZURE_DEVOPS_PROJECT"].filter((K)=>!process.env[K]);if(O.length>0)throw new Error(`Missing required environment variables: ${O.join(", ")}
52
+ Please set AZURE_DEVOPS_ORG, AZURE_DEVOPS_PAT, and AZURE_DEVOPS_PROJECT in your environment.`);let M=process.env.AZURE_DEVOPS_ORG,U=process.env.AZURE_DEVOPS_PAT,$=process.env.AZURE_DEVOPS_PROJECT;if(!M||!U||!$)throw new Error("Azure DevOps configuration was expected but missing after validation.");Y={organization:M,pat:U,defaultProject:$}}if(Z==="asana"){let q=process.env.ASANA_API_TOKEN;if(!q)throw new Error("Asana backend selected but ASANA_API_TOKEN is missing. Please set ASANA_API_TOKEN in your environment.");z={apiToken:q,defaultProjectGid:process.env.ASANA_DEFAULT_PROJECT_GID}}if(Z==="github"){let O=["GITHUB_TOKEN","GITHUB_OWNER","GITHUB_REPO"].filter((K)=>!process.env[K]);if(O.length>0)throw new Error(`Missing required environment variables: ${O.join(", ")}
53
+ Please set GITHUB_TOKEN, GITHUB_OWNER, and GITHUB_REPO in your environment.`);let M=process.env.GITHUB_TOKEN,U=process.env.GITHUB_OWNER,$=process.env.GITHUB_REPO;if(!M||!U||!$)throw new Error("GitHub configuration was expected but missing after validation.");H={token:M,owner:U,repo:$}}let W=K1();return{backend:Q,jira:X,linear:J,trello:G,azureDevOps:Y,asana:z,github:H,agent:W,supabase:W1(v0(process.cwd(),".devintern-pm",".auth-session.json"))}}class B1{apiToken;baseUrl="https://app.asana.com/api/1.0";constructor(Z){this.apiToken=Z.apiToken}async request(Z,Q="GET",X){let J=`${this.baseUrl}${Z}`,G={Authorization:`Bearer ${this.apiToken}`,Accept:"application/json"},Y={method:Q,headers:G};if(X&&Q!=="GET")G["Content-Type"]="application/json",Y.body=JSON.stringify(X);let z=await fetch(J,Y);if(!z.ok){let W=await z.text();throw new Error(`Asana API error (${z.status}): ${W}`)}return(await z.json()).data}async getProjects(){return this.request("/projects")}async getTask(Z){return this.request(`/tasks/${Z}`)}async createTask(Z,Q,X){let J={name:Z,notes:Q};if(X)J.projects=[X];return this.request("/tasks","POST",{data:J})}async createSubtask(Z,Q,X){let J={name:Q};if(X)J.notes=X;return this.request(`/tasks/${Z}/subtasks`,"POST",{data:J})}async setParent(Z,Q){return this.request(`/tasks/${Z}`,"PUT",{data:{parent:Q}})}async addTaskToProject(Z,Q){await this.request(`/tasks/${Z}/addProject`,"POST",{data:{project:Q}})}}class F1{name="Asana";client;defaultProjectGid;constructor(Z){this.client=new B1({apiToken:Z.apiToken}),this.defaultProjectGid=Z.defaultProjectGid}async resolveProjectGid(Z){if(Z)return Z;return this.defaultProjectGid}async createTask(Z,Q,X,J){let G=await this.resolveProjectGid(J),Y=await this.client.createTask(Z,Q,G);return{key:Y.gid,url:Y.permalink_url}}async createSubtask(Z,Q,X,J){try{await this.client.getTask(Z)}catch{throw new Error(`Parent task not found: ${Z}`)}let G=await this.client.createSubtask(Z,Q,X);return{key:G.gid,url:G.permalink_url}}async linkToEpic(Z,Q){await this.client.setParent(Z,Q)}async getProjects(){return(await this.client.getProjects()).map((Q)=>({key:Q.gid,name:Q.name}))}async getIssueTypes(){return["Task","Milestone"]}}class V1{organization;pat;auth;defaultProject;projectsCache=null;workItemTypesCache=new Map;workItemCache=new Map;constructor(Z){this.organization=Z.organization,this.pat=Z.pat,this.defaultProject=Z.defaultProject,this.auth=Buffer.from(`:${Z.pat}`).toString("base64")}get baseUrl(){return`https://dev.azure.com/${this.organization}`}async request(Z,Q="GET",X,J="application/json"){let G={Authorization:`Basic ${this.auth}`,Accept:"application/json"};if(X&&J==="application/json")G["Content-Type"]="application/json";else if(X)G["Content-Type"]=J;let Y=await fetch(Z,{method:Q,headers:G,body:X?typeof X==="string"?X:JSON.stringify(X):void 0});if(!Y.ok){let z=await Y.text();throw new Error(`Azure DevOps API error (${Y.status}): ${z}`)}return Y.json()}async createWorkItem(Z,Q,X,J){let G=J||this.defaultProject,Y=`${this.baseUrl}/${encodeURIComponent(G)}/_apis/wit/workitems/$${encodeURIComponent(X)}?api-version=7.0`,z=[{op:"add",path:"/fields/System.Title",value:Z},{op:"add",path:"/fields/System.Description",value:Q}],H=await this.request(Y,"POST",z,"application/json-patch+json"),W={id:H.id,url:`${this.baseUrl}/${encodeURIComponent(G)}/_workitems/edit/${H.id}`};return this.workItemCache.set(String(H.id),W),W}async createSubtask(Z,Q,X,J){let G=J||this.defaultProject,Y=`${this.baseUrl}/${encodeURIComponent(G)}/_apis/wit/workitems/$Task?api-version=7.0`,z=[{op:"add",path:"/fields/System.Title",value:Q}];if(X)z.push({op:"add",path:"/fields/System.Description",value:X});z.push({op:"add",path:"/relations/-",value:{rel:"System.LinkTypes.Hierarchy-Reverse",url:`${this.baseUrl}/_apis/wit/workItems/${Z}`}});let H=await this.request(Y,"POST",z,"application/json-patch+json");return{id:H.id,url:`${this.baseUrl}/${encodeURIComponent(G)}/_workitems/edit/${H.id}`}}async linkToParent(Z,Q){let X=`${this.baseUrl}/_apis/wit/workitems/${Z}?api-version=7.0`,J=[{op:"add",path:"/relations/-",value:{rel:"System.LinkTypes.Hierarchy-Reverse",url:`${this.baseUrl}/_apis/wit/workItems/${Q}`}}];await this.request(X,"PATCH",J,"application/json-patch+json")}async getWorkItemIdByKey(Z){let Q=parseInt(Z,10);if(!isNaN(Q))return Q;return}async getWorkItem(Z){let Q=this.workItemCache.get(Z);if(Q)return Q;let X=await this.getWorkItemIdByKey(Z);if(!X)throw new Error(`Invalid work item key: ${Z}`);let J=await this.request(`${this.baseUrl}/_apis/wit/workitems/${X}?api-version=7.0`),G={id:J.id,url:`${this.baseUrl}/${encodeURIComponent(this.defaultProject)}/_workitems/edit/${J.id}`};return this.workItemCache.set(Z,G),G}async getProjects(){if(this.projectsCache)return this.projectsCache;let Q=(await this.request(`${this.baseUrl}/_apis/projects?api-version=7.0`)).value?.map((X)=>({id:X.id,name:X.name}))||[];return this.projectsCache=Q,Q}async getWorkItemTypes(Z){let Q=Z||this.defaultProject,X=this.workItemTypesCache.get(Q);if(X)return X;let G=(await this.request(`${this.baseUrl}/${encodeURIComponent(Q)}/_apis/wit/workitemtypes?api-version=7.0`)).value?.map((Y)=>({name:Y.name,description:Y.description}))||[];return this.workItemTypesCache.set(Q,G),G}}class L1{name="Azure DevOps";client;defaultProject;constructor(Z){this.client=new V1({organization:Z.organization,pat:Z.pat,defaultProject:Z.defaultProject}),this.defaultProject=Z.defaultProject}async createTask(Z,Q,X,J){let G=await this.client.createWorkItem(Z,Q,X,J);return{key:String(G.id),url:G.url}}async createSubtask(Z,Q,X,J){let G=await this.client.getWorkItemIdByKey(Z);if(!G)throw new Error(`Parent work item not found: ${Z}`);let Y=await this.client.createSubtask(G,Q,X,J);return{key:String(Y.id),url:Y.url}}async linkToEpic(Z,Q){let X=await this.client.getWorkItemIdByKey(Z),J=await this.client.getWorkItemIdByKey(Q);if(!X||!J)throw new Error("Work item not found");await this.client.linkToParent(X,J)}async getProjects(){return(await this.client.getProjects()).map((Q)=>({key:Q.name,name:Q.name}))}async getIssueTypes(Z){return(await this.client.getWorkItemTypes(Z)).map((X)=>X.name)}}class w1{token;owner;repo;baseUrl="https://api.github.com";constructor(Z){this.token=Z.token,this.owner=Z.owner,this.repo=Z.repo}async request(Z,Q="GET",X){let J=`${this.baseUrl}${Z}`,G={Authorization:`Bearer ${this.token}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28"},Y={method:Q,headers:G};if(X&&Q!=="GET")G["Content-Type"]="application/json",Y.body=JSON.stringify(X);let z=await fetch(J,Y);if(!z.ok){let H=await z.text();throw new Error(`GitHub API error (${z.status}): ${H}`)}return z.json()}async createIssue(Z,Q,X){let J={title:Z,body:Q};if(X&&X.length>0)J.labels=X;return this.request(`/repos/${this.owner}/${this.repo}/issues`,"POST",J)}async getIssue(Z){return this.request(`/repos/${this.owner}/${this.repo}/issues/${Z}`)}async updateIssue(Z,Q){return this.request(`/repos/${this.owner}/${this.repo}/issues/${Z}`,"PATCH",Q)}async createSubtask(Z,Q,X){let J=await this.createIssue(Q,X||""),Y=(await this.getIssue(Z)).body||"",z=`- [ ] #${J.number}`,H="## Subtasks",W;if(Y.includes("## Subtasks"))W=Y.replace("## Subtasks",`## Subtasks
54
+ ${z}`);else W=Y?`${Y}
55
+
56
+ ## Subtasks
57
+ ${z}`:`## Subtasks
58
+ ${z}`;return await this.updateIssue(Z,{body:W}),J}async linkToEpic(Z,Q){let J=(await this.getIssue(Z)).body||"",G=`Part of #${Q}`;if(J.includes(G))return;let Y=J?`${J}
59
+
60
+ ${G}`:G;await this.updateIssue(Z,{body:Y})}async getRepositories(){return this.request("/user/repos?per_page=100")}async getLabels(){return this.request(`/repos/${this.owner}/${this.repo}/labels?per_page=100`)}async addLabels(Z,Q){await this.request(`/repos/${this.owner}/${this.repo}/issues/${Z}/labels`,"POST",{labels:Q})}}class N1{name="GitHub";client;constructor(Z){this.client=new w1({token:Z.token,owner:Z.owner,repo:Z.repo})}async createTask(Z,Q,X,J){let G=[],z={Story:"enhancement",Bug:"bug",Task:"task",Epic:"epic"}[X];if(z)G.push(z);let H=await this.client.createIssue(Z,Q,G);return{key:String(H.number),url:H.html_url}}async createSubtask(Z,Q,X,J){let G=parseInt(Z,10);if(isNaN(G))throw new Error(`Invalid parent issue number: ${Z}`);let Y=await this.client.createSubtask(G,Q,X);return{key:String(Y.number),url:Y.html_url}}async linkToEpic(Z,Q){let X=parseInt(Z,10),J=parseInt(Q,10);if(isNaN(X)||isNaN(J))throw new Error("Invalid issue number");await this.client.linkToEpic(X,J)}async getProjects(){return(await this.client.getRepositories()).map((Q)=>({key:Q.full_name,name:Q.name}))}async getIssueTypes(){return["Story","Bug","Task","Epic"]}}function f0(Z){let Q=[],X="",J=0,G=()=>{if(X)Q.push({type:"text",text:X}),X=""};while(J<Z.length){if(Z[J]==="`"&&Z[J+1]!=="`"){G();let Y=J+1,z=Z.indexOf("`",Y);if(z===-1)z=Z.length;Q.push({type:"text",text:Z.substring(Y,z),marks:[{type:"code"}]}),J=z+1;continue}if(Z.substring(J,J+2)==="**"){G();let Y=J+2,z=Z.indexOf("**",Y);if(z!==-1){Q.push({type:"text",text:Z.substring(Y,z),marks:[{type:"strong"}]}),J=z+2;continue}}if(Z[J]==="*"&&Z[J+1]!=="*"){G();let Y=J+1,z=Z.indexOf("*",Y);if(z!==-1){Q.push({type:"text",text:Z.substring(Y,z),marks:[{type:"em"}]}),J=z+1;continue}}X+=Z[J]??"",J++}return G(),Q.length>0?Q:[{type:"text",text:Z}]}function GJ(Z){if(Z.length===0)return null;let Q=(z)=>{return z.trim().replace(/^\|/,"").replace(/\|$/,"").split("|").map((W)=>W.trim())},X=Q(Z[0]??""),J=X.length,G={type:"tableRow",content:X.map((z)=>({type:"tableHeader",attrs:{},content:[{type:"paragraph",content:f0(z)}]}))},Y=Z.slice(1).map((z)=>{let H=Q(z);while(H.length<J)H.push("");return{type:"tableRow",content:H.slice(0,J).map((W)=>({type:"tableCell",attrs:{},content:[{type:"paragraph",content:f0(W)}]}))}});return{type:"table",attrs:{isNumberColumnEnabled:!1,layout:"default"},content:[G,...Y]}}function D1(Z,Q){let X=Q?.includeTables??!0,J=Q?.paragraphJoinWith??" ",G=[],Y=Z.split(`
61
+ `),z=[],H=!1,W=[],q="",O=()=>{if(z.length===0)return;let U=z.join(J).trim();if(U)G.push({type:"paragraph",content:f0(U)});z=[]},M=()=>{if(W.length===0)return;G.push({type:"codeBlock",attrs:{language:q||"text"},content:[{type:"text",text:W.join(`
62
+ `)}]}),W=[],q=""};for(let U=0;U<Y.length;U++){let $=Y[U]??"",K=$.trim();if(K.startsWith("```")){if(H)M(),H=!1;else O(),H=!0,q=K.substring(3).trim();continue}if(H){W.push($);continue}if(K.startsWith("#")){O();let w=Math.min(6,(K.match(/^#+/)||[""])[0].length),V=K.replace(/^#+\s*/,"");G.push({type:"heading",attrs:{level:w},content:[{type:"text",text:V}]});continue}if(K.match(/^[-*+]\s/)){O();let w=[],V=U;while(V<Y.length&&(Y[V]??"").trim().match(/^[-*+]\s/)){let B=(Y[V]??"").trim().replace(/^[-*+]\s/,"");w.push({type:"listItem",content:[{type:"paragraph",content:f0(B)}]}),V++}G.push({type:"bulletList",content:w}),U=V-1;continue}if(K.match(/^\d+\.\s/)){O();let w=[],V=U;while(V<Y.length&&(Y[V]??"").trim().match(/^\d+\.\s/)){let B=(Y[V]??"").trim().replace(/^\d+\.\s/,"");w.push({type:"listItem",content:[{type:"paragraph",content:f0(B)}]}),V++}G.push({type:"orderedList",content:w}),U=V-1;continue}if(X&&K.includes("|")){O();let w=[],V=U;while(V<Y.length&&(Y[V]??"").trim().includes("|")){let B=(Y[V]??"").trim();if(!B.match(/^\|[\s\-:|]+\|$/))w.push(B);V++}if(w.length>0){let B=GJ(w);if(B)G.push(B)}U=V-1;continue}if(K===""){O();continue}z.push($)}return O(),M(),G}function v6(Z,Q){let X=D1(Z,Q);return{type:"doc",version:1,content:X.length>0?X:[{type:"paragraph",content:[{type:"text",text:""}]}]}}function f6(Z,Q){if(Z==null)return"";if(typeof Z==="string")return Z;let X=Q?.arrayJoinWith??"",J=Q?.topLevelParagraphNewline??!1,G=Q?.topLevelHeadingNewline??!1,Y=(z,H=!1,W=0,q=0)=>{if(z==null)return"";if(typeof z==="string")return z;if(Array.isArray(z))return z.map((M,U)=>Y(M,H,U,z.length)).join(X);if(typeof z!=="object")return"";let O=z;if(O.type==="text")return typeof O.text==="string"?O.text:"";if(O.type==="paragraph"){let M=Y(O.content??[],!1);if(H&&J&&W<q-1)return`${M}
63
+ `;return M}if(O.type==="heading"){let M=Y(O.content??[],!1);if(H&&G)return`${M}
64
+ `;return M}if("content"in O)return Y(O.content??[],!1);return""};if(typeof Z==="object"&&Z!==null&&"content"in Z){let z=Z.content;if(Array.isArray(z))return z.map((H,W)=>Y(H,!0,W,z.length)).join(X);return Y(z,!0,0,1)}return Y(Z,!0,0,1)}class wQ{static textToADF(Z){return v6(Z)}static parseTextToADFContent(Z){let Q=D1(Z,{includeTables:!0,paragraphJoinWith:`
65
+ `});return Q.length>0?Q:[{type:"paragraph",content:[{type:"text",text:""}]}]}static parseInlineFormatting(Z){return f0(Z)}}class R1{baseUrl;auth;config;issueTypesCacheByProject=new Map;projectsCache=null;constructor(Z){this.config=Z,this.baseUrl=`https://${Z.domain}/rest/api/3`,this.auth=Buffer.from(`${Z.email}:${Z.apiToken}`).toString("base64")}async request(Z,Q="GET",X){let J=`${this.baseUrl}${Z}`,G={Authorization:`Basic ${this.auth}`,"Content-Type":"application/json",Accept:"application/json"},Y=await fetch(J,{method:Q,headers:G,body:X?JSON.stringify(X):void 0});if(!Y.ok){let z=await Y.text();throw new Error(`Jira API error (${Y.status}): ${z}`)}return Y.json()}async createStory(Z,Q,X="Story",J){let G=wQ.textToADF(Q),Y={fields:{project:{key:J||this.config.defaultProjectKey},summary:Z,description:G,issuetype:{name:X}}},z=await this.request("/issue","POST",Y);return{key:z.key,id:z.id,url:`https://${this.config.domain}/browse/${z.key}`}}async createSubtask(Z,Q,X,J){let G=X?wQ.textToADF(X):void 0,Y={fields:{project:{key:J||this.config.defaultProjectKey},parent:{key:Z},summary:Q,description:G,issuetype:{name:"Subtask"}}},z=await this.request("/issue","POST",Y);return{key:z.key,url:`https://${this.config.domain}/browse/${z.key}`}}async linkIssues(Z,Q,X="Relates"){await this.request("/issueLink","POST",{type:{name:X},inwardIssue:{key:Z},outwardIssue:{key:Q}})}async linkToEpic(Z,Q){await this.request(`/issue/${Z}`,"PUT",{fields:{parent:{key:Q}}})}async getIssue(Z){let Q=await this.request(`/issue/${Z}?fields=summary,description,issuetype,status`),X=Q.fields.description?f6(Q.fields.description,{arrayJoinWith:" "}):"";return{key:Q.key,summary:Q.fields.summary,description:X,issueType:Q.fields.issuetype.name,status:Q.fields.status.name,url:`https://${this.config.domain}/browse/${Q.key}`}}async getProjects(){if(this.projectsCache)return this.projectsCache;let Q=(await this.request("/project/search?maxResults=100")).values?.map((X)=>({id:X.id,key:X.key,name:X.name,projectTypeKey:X.projectTypeKey}))||[];return this.projectsCache=Q,Q}async getIssueTypes(Z){let Q=Z||this.config.defaultProjectKey,X=this.issueTypesCacheByProject.get(Q);if(X)return X;let G=(await this.request(`/project/${Q}`)).issueTypes?.filter((Y)=>!Y.subtask).map((Y)=>({id:Y.id,name:Y.name,description:Y.description,subtask:Y.subtask}))||[];return this.issueTypesCacheByProject.set(Q,G),G}}class I1{name="Jira";client;constructor(Z){this.client=new R1({domain:Z.domain,email:Z.email,apiToken:Z.apiToken,defaultProjectKey:Z.defaultProjectKey})}async createTask(Z,Q,X,J){return this.client.createStory(Z,Q,X,J)}async createSubtask(Z,Q,X,J){return this.client.createSubtask(Z,Q,X,J)}async linkToEpic(Z,Q){return this.client.linkToEpic(Z,Q)}async getProjects(){return(await this.client.getProjects()).map((Q)=>({key:Q.key,name:Q.name}))}async getIssueTypes(Z){return(await this.client.getIssueTypes(Z)).map((X)=>X.name)}}class C1{apiKey;baseUrl="https://api.linear.app/graphql";teamsCache=null;issueIdCache=new Map;constructor(Z){this.apiKey=Z.apiKey}async request(Z,Q){let X=await fetch(this.baseUrl,{method:"POST",headers:{"Content-Type":"application/json",Authorization:this.apiKey},body:JSON.stringify({query:Z,variables:Q})});if(!X.ok){let G=await X.text();throw new Error(`Linear API error (${X.status}): ${G}`)}let J=await X.json();if(J.errors&&J.errors.length>0)throw new Error(`Linear GraphQL error: ${J.errors[0]?.message}`);return J.data}cacheIssueId(Z,Q){this.issueIdCache.set(Z,Q)}async getIssueIdByIdentifier(Z){let Q=this.issueIdCache.get(Z);if(Q)return Q;let J=(await this.request(`
66
+ query IssuesByIdentifier($identifier: String!) {
67
+ issues(filter: { identifier: { eq: $identifier } }) {
68
+ nodes {
69
+ id
70
+ identifier
71
+ }
72
+ }
73
+ }
74
+ `,{identifier:Z})).issues.nodes[0];if(J)return this.cacheIssueId(J.identifier,J.id),J.id;return}async createIssue(Z,Q,X){let J=await this.request(`
75
+ mutation IssueCreate($input: IssueCreateInput!) {
76
+ issueCreate(input: $input) {
77
+ success
78
+ issue {
79
+ id
80
+ identifier
81
+ url
82
+ }
83
+ }
84
+ }
85
+ `,{input:{title:Z,description:Q,teamId:X}});if(!J.issueCreate.success)throw new Error("Failed to create Linear issue");let G=J.issueCreate.issue;return this.cacheIssueId(G.identifier,G.id),{id:G.id,identifier:G.identifier,url:G.url}}async createSubIssue(Z,Q,X,J){let G=await this.request(`
86
+ mutation IssueCreate($input: IssueCreateInput!) {
87
+ issueCreate(input: $input) {
88
+ success
89
+ issue {
90
+ id
91
+ identifier
92
+ url
93
+ }
94
+ }
95
+ }
96
+ `,{input:{title:Q,description:X,teamId:J,parentId:Z}});if(!G.issueCreate.success)throw new Error("Failed to create Linear sub-issue");let Y=G.issueCreate.issue;return this.cacheIssueId(Y.identifier,Y.id),{id:Y.id,identifier:Y.identifier,url:Y.url}}async linkToParent(Z,Q){if(!(await this.request(`
97
+ mutation IssueUpdate($id: String!, $input: IssueUpdateInput!) {
98
+ issueUpdate(id: $id, input: $input) {
99
+ success
100
+ }
101
+ }
102
+ `,{id:Z,input:{parentId:Q}})).issueUpdate.success)throw new Error("Failed to link issue to parent")}async getTeams(){if(this.teamsCache)return this.teamsCache;let Q=(await this.request(`
103
+ query Teams {
104
+ teams {
105
+ nodes {
106
+ id
107
+ key
108
+ name
109
+ }
110
+ }
111
+ }
112
+ `)).teams.nodes;return this.teamsCache=Q,Q}async getTeamIdByKey(Z){return(await this.getTeams()).find((X)=>X.key===Z)?.id}}class P1{name="Linear";client;defaultTeamKey;constructor(Z){this.client=new C1({apiKey:Z.apiKey}),this.defaultTeamKey=Z.defaultTeamKey}async resolveTeamId(Z){let Q=Z||this.defaultTeamKey,X;if(Q)X=await this.client.getTeamIdByKey(Q);if(!X){let J=await this.client.getTeams();if(J.length===0)throw new Error("No Linear teams found. Please create a team first.");X=J[0].id}return X}async createTask(Z,Q,X,J){let G=await this.resolveTeamId(J),Y=await this.client.createIssue(Z,Q,G);return{key:Y.identifier,url:Y.url}}async createSubtask(Z,Q,X,J){let G=await this.client.getIssueIdByIdentifier(Z);if(!G)throw new Error(`Parent issue not found: ${Z}`);let Y=await this.resolveTeamId(J),z=await this.client.createSubIssue(G,Q,X||"",Y);return{key:z.identifier,url:z.url}}async linkToEpic(Z,Q){let X=await this.client.getIssueIdByIdentifier(Z),J=await this.client.getIssueIdByIdentifier(Q);if(!X||!J)throw new Error("Issue not found");await this.client.linkToParent(X,J)}async getProjects(){return(await this.client.getTeams()).map((Q)=>({key:Q.key,name:Q.name}))}async getIssueTypes(){return["Story","Bug","Task","Epic","Feature","Improvement"]}}import{join as A1,resolve as zJ}from"path";class j1{name="Markdown";dir;constructor(Z){this.dir=zJ(Z.directory)}sanitizeFilename(Z){return Z.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"").substring(0,50)}generateKey(){let Q=new Date().toISOString().replace(/[:.]/g,"-").substring(0,19),X=Math.random().toString(36).substring(2,6);return`${Q}-${X}`}async ensureDir(){await Bun.$`mkdir -p ${this.dir}`}filePath(Z){return A1(this.dir,`${Z}.md`)}async createTask(Z,Q,X,J){await this.ensureDir();let G=this.generateKey(),Y=`${G}-${this.sanitizeFilename(Z)}`,z=this.filePath(Y),H=new Date().toISOString(),W=`---
113
+ key: ${G}
114
+ type: ${X}
115
+ created_at: ${H}
116
+ ---
117
+
118
+ # ${Z}
119
+
120
+ ${Q}
121
+ `;return await Bun.write(z,W),{key:Y,url:z}}async createSubtask(Z,Q,X,J){await this.ensureDir();let G=A1(this.dir,`${Z}.md`),Y=Bun.file(G);if(!await Y.exists())throw new Error(`Parent task not found: ${Z}`);let z=await Y.text(),H=`
122
+ ## Subtasks
123
+
124
+ `;if(!z.includes(H))z+=H;let W=X?`- [ ] **${Q}**: ${X.split(`
125
+ `)[0]}
126
+ `:`- [ ] **${Q}**
127
+ `;return z+=W,await Bun.write(G,z),{key:`${Z}-subtask`,url:G}}async linkToEpic(Z,Q){let X=A1(this.dir,`${Z}.md`),J=Bun.file(X);if(!await J.exists())throw new Error(`Task not found: ${Z}`);let G=await J.text();if(G.startsWith("---")){let Y=G.indexOf("---",3);if(Y!==-1){let z=G.substring(0,Y+3),H=G.substring(Y+3),W;if(z.includes("epic:"))W=z.replace(/epic: .*/,`epic: ${Q}`);else{let q=z.split(`
128
+ `);q.splice(q.length-1,0,`epic: ${Q}`),W=q.join(`
129
+ `)}G=W+H,await Bun.write(X,G);return}}G=`> Epic: ${Q}
130
+
131
+ ${G}`,await Bun.write(X,G)}async getProjects(){return[]}async getIssueTypes(){return["Story","Task","Bug","Epic"]}}class x1{apiKey;apiToken;baseUrl="https://api.trello.com/1";constructor(Z){this.apiKey=Z.apiKey,this.apiToken=Z.apiToken}buildUrl(Z,Q){let X=new URL(`${this.baseUrl}${Z}`);if(X.searchParams.set("key",this.apiKey),X.searchParams.set("token",this.apiToken),Q)for(let[J,G]of Object.entries(Q))X.searchParams.set(J,G);return X.toString()}async request(Z,Q="GET",X){let J=this.buildUrl(Z),G={method:Q};if(X&&Q!=="GET"){let z=new URLSearchParams;for(let[H,W]of Object.entries(X))z.append(H,W);G.body=z.toString(),G.headers={"Content-Type":"application/x-www-form-urlencoded"}}let Y=await fetch(J,G);if(!Y.ok){let z=await Y.text();throw new Error(`Trello API error (${Y.status}): ${z}`)}return Y.json()}async getBoards(){return this.request("/members/me/boards")}async getLists(Z){return this.request(`/boards/${Z}/lists`)}async getCard(Z){return this.request(`/cards/${Z}`)}async createCard(Z,Q,X){return this.request("/cards","POST",{idList:X,name:Z,desc:Q})}async createChecklistItem(Z,Q,X){let J=await this.request(`/cards/${Z}/checklists`),G;if(J.length===0)G=(await this.request("/checklists","POST",{idCard:Z,name:"Subtasks"})).id;else G=J[0].id;let Y=X?`${Q}: ${X}`:Q;return await this.request(`/checklists/${G}/checkItems`,"POST",{name:Y})}async addAttachment(Z,Q,X){await this.request(`/cards/${Z}/attachments`,"POST",{url:Q,name:X||"Linked issue"})}}class S1{name="Trello";client;defaultBoardId;defaultListId;listsCache=new Map;constructor(Z){this.client=new x1({apiKey:Z.apiKey,apiToken:Z.apiToken}),this.defaultBoardId=Z.defaultBoardId,this.defaultListId=Z.defaultListId}async resolveListId(Z){let Q=Z||this.defaultBoardId;if(!Q){let X=await this.client.getBoards();if(X.length===0)throw new Error("No Trello boards found. Please create a board first.");let J=X[0];return this.resolveListForBoard(J.id)}if(this.defaultListId&&!Z)return this.defaultListId;return this.resolveListForBoard(Q)}async resolveListForBoard(Z){let Q=this.listsCache.get(Z);if(Q&&Q.length>0)return Q[0].id;let X=await this.client.getLists(Z);if(X.length===0)throw new Error(`No lists found on Trello board ${Z}`);return this.listsCache.set(Z,X),X[0].id}async createTask(Z,Q,X,J){let G=await this.resolveListId(J),Y=await this.client.createCard(Z,Q,G);return{key:Y.shortLink,url:Y.url}}async createSubtask(Z,Q,X,J){let G=await this.client.getCard(Z),Y=await this.client.createChecklistItem(G.id,Q,X);return{key:`${Z}-${Y.id}`,url:G.url}}async linkToEpic(Z,Q){let X=await this.client.getCard(Z),J=await this.client.getCard(Q);await this.client.addAttachment(X.id,J.url,"Epic")}async getProjects(){return(await this.client.getBoards()).map((Q)=>({key:Q.id,name:Q.name}))}async getIssueTypes(){return["Story","Bug","Task","Epic"]}}async function T1(Z){switch(Z.backend.type){case"jira":{if(!Z.jira)throw new Error("Jira backend selected but Jira configuration is missing. Please set JIRA_BASE_URL, JIRA_EMAIL, JIRA_API_TOKEN, and JIRA_DEFAULT_PROJECT_KEY.");return new I1(Z.jira)}case"linear":{if(!Z.linear)throw new Error("Linear backend selected but Linear configuration is missing. Please set LINEAR_API_KEY.");return new P1(Z.linear)}case"trello":{if(!Z.trello)throw new Error("Trello backend selected but Trello configuration is missing. Please set TRELLO_API_KEY and TRELLO_API_TOKEN.");return new S1(Z.trello)}case"azure-devops":{if(!Z.azureDevOps)throw new Error("Azure DevOps backend selected but Azure DevOps configuration is missing. Please set AZURE_DEVOPS_ORG, AZURE_DEVOPS_PAT, and AZURE_DEVOPS_PROJECT.");return new L1(Z.azureDevOps)}case"asana":{if(!Z.asana)throw new Error("Asana backend selected but Asana configuration is missing. Please set ASANA_API_TOKEN.");return new F1(Z.asana)}case"github":{if(!Z.github)throw new Error("GitHub backend selected but GitHub configuration is missing. Please set GITHUB_TOKEN, GITHUB_OWNER, and GITHUB_REPO.");return new N1(Z.github)}case"markdown":return new j1({directory:Z.backend.directory||".devintern-pm/tasks"});default:throw new Error(`Unknown backend type: ${Z.backend.type}. Supported: jira, linear, trello, azure-devops, asana, github, markdown`)}}async function NQ(Z,Q,X,J){return $1(Z,Q,X,J)}import _1,{useState as PQ,useRef as n6}from"react";import{render as kJ,Box as f,Text as A,useInput as EJ,useApp as vJ}from"ink";import{ScrollView as a6}from"ink-scroll-view";import DQ from"react";import{Text as z0,Box as RQ}from"ink";import{jsxDEV as l,Fragment as HJ}from"react/jsx-dev-runtime";var E1=({children:Z})=>{let Q=Z.split(`
132
+ `),X=[],J=!1,G=[];for(let Y=0;Y<Q.length;Y++){let z=Q[Y]??"";if(z.trim().startsWith("```")){if(J)X.push(l(RQ,{flexDirection:"column",paddingLeft:2,children:G.map((W,q)=>l(z0,{color:"gray",children:W},q,!1,void 0,this))},`code-${Y}`,!1,void 0,this)),G=[],J=!1;else J=!0;continue}if(J){G.push(z);continue}if(z.startsWith("### ")){X.push(l(z0,{bold:!0,color:"cyan",children:z.substring(4)},Y,!1,void 0,this));continue}if(z.startsWith("## ")){X.push(l(z0,{bold:!0,color:"cyan",children:z.substring(3)},Y,!1,void 0,this));continue}if(z.startsWith("# ")){X.push(l(z0,{bold:!0,color:"cyan",children:z.substring(2)},Y,!1,void 0,this));continue}if(z.trim().startsWith("- ")||z.trim().startsWith("* ")){let W=z.search(/[*-]/),q=z.substring(W+2);X.push(l(RQ,{paddingLeft:Math.floor(W/2),children:l(z0,{children:["\u2022 ",k1(q)]},void 0,!0,void 0,this)},Y,!1,void 0,this));continue}let H=z.match(/^(\s*)(\d+)\.\s(.+)$/);if(H){let W=H[1]?.length??0,q=H[2],O=H[3]??"";X.push(l(RQ,{paddingLeft:Math.floor(W/2),children:l(z0,{children:[q,". ",k1(O)]},void 0,!0,void 0,this)},Y,!1,void 0,this));continue}if(z.trim()===""){X.push(l(z0,{children:" "},Y,!1,void 0,this));continue}X.push(l(z0,{children:k1(z)},Y,!1,void 0,this))}return l(RQ,{flexDirection:"column",children:X},void 0,!1,void 0,this)};function k1(Z){let Q=[],X=Z,J=0;while(X.length>0){let G=X.match(/^(.*?)(\*\*|__)(.+?)\2/);if(G&&G[1]!==void 0&&G[3]!==void 0){if(G[1])Q.push(l(DQ.Fragment,{children:G[1]},J++,!1,void 0,this));Q.push(l(z0,{bold:!0,children:G[3]},J++,!1,void 0,this)),X=X.substring((G[1]?.length??0)+(G[2]?.length??0)*2+(G[3]?.length??0));continue}let Y=X.match(/^(.*?)([*_])(.+?)\2/);if(Y&&Y[1]!==void 0&&Y[3]!==void 0){if(Y[1])Q.push(l(DQ.Fragment,{children:Y[1]},J++,!1,void 0,this));Q.push(l(z0,{italic:!0,children:Y[3]},J++,!1,void 0,this)),X=X.substring((Y[1]?.length??0)+(Y[2]?.length??0)*2+(Y[3]?.length??0));continue}let z=X.match(/^(.*?)`(.+?)`/);if(z&&z[1]!==void 0&&z[2]!==void 0){if(z[1])Q.push(l(DQ.Fragment,{children:z[1]},J++,!1,void 0,this));Q.push(l(z0,{color:"gray",children:z[2]},J++,!1,void 0,this)),X=X.substring((z[1]?.length??0)+2+(z[2]?.length??0));continue}Q.push(l(DQ.Fragment,{children:X},J++,!1,void 0,this));break}return l(HJ,{children:Q},void 0,!1,void 0,this)}import{Box as SJ,Text as TJ}from"ink";import IJ,{useState as CJ,useEffect as PJ}from"react";import{Text as AJ,useInput as jJ}from"ink";var b6=(Z=0)=>(Q)=>`\x1B[${Q+Z}m`,y6=(Z=0)=>(Q)=>`\x1B[${38+Z};5;${Q}m`,g6=(Z=0)=>(Q,X,J)=>`\x1B[${38+Z};2;${Q};${X};${J}m`,g={modifier:{reset:[0,0],bold:[1,22],dim:[2,22],italic:[3,23],underline:[4,24],overline:[53,55],inverse:[7,27],hidden:[8,28],strikethrough:[9,29]},color:{black:[30,39],red:[31,39],green:[32,39],yellow:[33,39],blue:[34,39],magenta:[35,39],cyan:[36,39],white:[37,39],blackBright:[90,39],gray:[90,39],grey:[90,39],redBright:[91,39],greenBright:[92,39],yellowBright:[93,39],blueBright:[94,39],magentaBright:[95,39],cyanBright:[96,39],whiteBright:[97,39]},bgColor:{bgBlack:[40,49],bgRed:[41,49],bgGreen:[42,49],bgYellow:[43,49],bgBlue:[44,49],bgMagenta:[45,49],bgCyan:[46,49],bgWhite:[47,49],bgBlackBright:[100,49],bgGray:[100,49],bgGrey:[100,49],bgRedBright:[101,49],bgGreenBright:[102,49],bgYellowBright:[103,49],bgBlueBright:[104,49],bgMagentaBright:[105,49],bgCyanBright:[106,49],bgWhiteBright:[107,49]}},Xz=Object.keys(g.modifier),WJ=Object.keys(g.color),qJ=Object.keys(g.bgColor),Jz=[...WJ,...qJ];function OJ(){let Z=new Map;for(let[Q,X]of Object.entries(g)){for(let[J,G]of Object.entries(X))g[J]={open:`\x1B[${G[0]}m`,close:`\x1B[${G[1]}m`},X[J]=g[J],Z.set(G[0],G[1]);Object.defineProperty(g,Q,{value:X,enumerable:!1})}return Object.defineProperty(g,"codes",{value:Z,enumerable:!1}),g.color.close="\x1B[39m",g.bgColor.close="\x1B[49m",g.color.ansi=b6(),g.color.ansi256=y6(),g.color.ansi16m=g6(),g.bgColor.ansi=b6(10),g.bgColor.ansi256=y6(10),g.bgColor.ansi16m=g6(10),Object.defineProperties(g,{rgbToAnsi256:{value(Q,X,J){if(Q===X&&X===J){if(Q<8)return 16;if(Q>248)return 231;return Math.round((Q-8)/247*24)+232}return 16+36*Math.round(Q/255*5)+6*Math.round(X/255*5)+Math.round(J/255*5)},enumerable:!1},hexToRgb:{value(Q){let X=/[a-f\d]{6}|[a-f\d]{3}/i.exec(Q.toString(16));if(!X)return[0,0,0];let[J]=X;if(J.length===3)J=[...J].map((Y)=>Y+Y).join("");let G=Number.parseInt(J,16);return[G>>16&255,G>>8&255,G&255]},enumerable:!1},hexToAnsi256:{value:(Q)=>g.rgbToAnsi256(...g.hexToRgb(Q)),enumerable:!1},ansi256ToAnsi:{value(Q){if(Q<8)return 30+Q;if(Q<16)return 90+(Q-8);let X,J,G;if(Q>=232)X=((Q-232)*10+8)/255,J=X,G=X;else{Q-=16;let H=Q%36;X=Math.floor(Q/36)/5,J=Math.floor(H/6)/5,G=H%6/5}let Y=Math.max(X,J,G)*2;if(Y===0)return 30;let z=30+(Math.round(G)<<2|Math.round(J)<<1|Math.round(X));if(Y===2)z+=60;return z},enumerable:!1},rgbToAnsi:{value:(Q,X,J)=>g.ansi256ToAnsi(g.rgbToAnsi256(Q,X,J)),enumerable:!1},hexToAnsi:{value:(Q)=>g.ansi256ToAnsi(g.hexToAnsi256(Q)),enumerable:!1}}),g}var MJ=OJ(),H0=MJ;import v1 from"process";import UJ from"os";import _6 from"tty";function J0(Z,Q=globalThis.Deno?globalThis.Deno.args:v1.argv){let X=Z.startsWith("-")?"":Z.length===1?"-":"--",J=Q.indexOf(X+Z),G=Q.indexOf("--");return J!==-1&&(G===-1||J<G)}var{env:_}=v1,IQ;if(J0("no-color")||J0("no-colors")||J0("color=false")||J0("color=never"))IQ=0;else if(J0("color")||J0("colors")||J0("color=true")||J0("color=always"))IQ=1;function KJ(){if("FORCE_COLOR"in _){if(_.FORCE_COLOR==="true")return 1;if(_.FORCE_COLOR==="false")return 0;return _.FORCE_COLOR.length===0?1:Math.min(Number.parseInt(_.FORCE_COLOR,10),3)}}function $J(Z){if(Z===0)return!1;return{level:Z,hasBasic:!0,has256:Z>=2,has16m:Z>=3}}function BJ(Z,{streamIsTTY:Q,sniffFlags:X=!0}={}){let J=KJ();if(J!==void 0)IQ=J;let G=X?IQ:J;if(G===0)return 0;if(X){if(J0("color=16m")||J0("color=full")||J0("color=truecolor"))return 3;if(J0("color=256"))return 2}if("TF_BUILD"in _&&"AGENT_NAME"in _)return 1;if(Z&&!Q&&G===void 0)return 0;let Y=G||0;if(_.TERM==="dumb")return Y;if(v1.platform==="win32"){let z=UJ.release().split(".");if(Number(z[0])>=10&&Number(z[2])>=10586)return Number(z[2])>=14931?3:2;return 1}if("CI"in _){if(["GITHUB_ACTIONS","GITEA_ACTIONS","CIRCLECI"].some((z)=>(z in _)))return 3;if(["TRAVIS","APPVEYOR","GITLAB_CI","BUILDKITE","DRONE"].some((z)=>(z in _))||_.CI_NAME==="codeship")return 1;return Y}if("TEAMCITY_VERSION"in _)return/^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(_.TEAMCITY_VERSION)?1:0;if(_.COLORTERM==="truecolor")return 3;if(_.TERM==="xterm-kitty")return 3;if(_.TERM==="xterm-ghostty")return 3;if(_.TERM==="wezterm")return 3;if("TERM_PROGRAM"in _){let z=Number.parseInt((_.TERM_PROGRAM_VERSION||"").split(".")[0],10);switch(_.TERM_PROGRAM){case"iTerm.app":return z>=3?3:2;case"Apple_Terminal":return 2}}if(/-256(color)?$/i.test(_.TERM))return 2;if(/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(_.TERM))return 1;if("COLORTERM"in _)return 1;return Y}function h6(Z,Q={}){let X=BJ(Z,{streamIsTTY:Z&&Z.isTTY,...Q});return $J(X)}var FJ={stdout:h6({isTTY:_6.isatty(1)}),stderr:h6({isTTY:_6.isatty(2)})},m6=FJ;function u6(Z,Q,X){let J=Z.indexOf(Q);if(J===-1)return Z;let G=Q.length,Y=0,z="";do z+=Z.slice(Y,J)+Q+X,Y=J+G,J=Z.indexOf(Q,Y);while(J!==-1);return z+=Z.slice(Y),z}function d6(Z,Q,X,J){let G=0,Y="";do{let z=Z[J-1]==="\r";Y+=Z.slice(G,z?J-1:J)+Q+(z?`\r
133
+ `:`
134
+ `)+X,G=J+1,J=Z.indexOf(`
135
+ `,G)}while(J!==-1);return Y+=Z.slice(G),Y}var{stdout:c6,stderr:l6}=m6,f1=Symbol("GENERATOR"),a0=Symbol("STYLER"),kZ=Symbol("IS_EMPTY"),p6=["ansi","ansi","ansi256","ansi16m"],s0=Object.create(null),VJ=(Z,Q={})=>{if(Q.level&&!(Number.isInteger(Q.level)&&Q.level>=0&&Q.level<=3))throw new Error("The `level` option should be an integer from 0 to 3");let X=c6?c6.level:0;Z.level=Q.level===void 0?X:Q.level};var LJ=(Z)=>{let Q=(...X)=>X.join(" ");return VJ(Q,Z),Object.setPrototypeOf(Q,EZ.prototype),Q};function EZ(Z){return LJ(Z)}Object.setPrototypeOf(EZ.prototype,Function.prototype);for(let[Z,Q]of Object.entries(H0))s0[Z]={get(){let X=CQ(this,y1(Q.open,Q.close,this[a0]),this[kZ]);return Object.defineProperty(this,Z,{value:X}),X}};s0.visible={get(){let Z=CQ(this,this[a0],!0);return Object.defineProperty(this,"visible",{value:Z}),Z}};var b1=(Z,Q,X,...J)=>{if(Z==="rgb"){if(Q==="ansi16m")return H0[X].ansi16m(...J);if(Q==="ansi256")return H0[X].ansi256(H0.rgbToAnsi256(...J));return H0[X].ansi(H0.rgbToAnsi(...J))}if(Z==="hex")return b1("rgb",Q,X,...H0.hexToRgb(...J));return H0[X][Z](...J)},wJ=["rgb","hex","ansi256"];for(let Z of wJ){s0[Z]={get(){let{level:X}=this;return function(...J){let G=y1(b1(Z,p6[X],"color",...J),H0.color.close,this[a0]);return CQ(this,G,this[kZ])}}};let Q="bg"+Z[0].toUpperCase()+Z.slice(1);s0[Q]={get(){let{level:X}=this;return function(...J){let G=y1(b1(Z,p6[X],"bgColor",...J),H0.bgColor.close,this[a0]);return CQ(this,G,this[kZ])}}}}var NJ=Object.defineProperties(()=>{},{...s0,level:{enumerable:!0,get(){return this[f1].level},set(Z){this[f1].level=Z}}}),y1=(Z,Q,X)=>{let J,G;if(X===void 0)J=Z,G=Q;else J=X.openAll+Z,G=Q+X.closeAll;return{open:Z,close:Q,openAll:J,closeAll:G,parent:X}},CQ=(Z,Q,X)=>{let J=(...G)=>DJ(J,G.length===1?""+G[0]:G.join(" "));return Object.setPrototypeOf(J,NJ),J[f1]=Z,J[a0]=Q,J[kZ]=X,J},DJ=(Z,Q)=>{if(Z.level<=0||!Q)return Z[kZ]?"":Q;let X=Z[a0];if(X===void 0)return Q;let{openAll:J,closeAll:G}=X;if(Q.includes("\x1B"))while(X!==void 0)Q=u6(Q,X.close,X.open),X=X.parent;let Y=Q.indexOf(`
136
+ `);if(Y!==-1)Q=d6(Q,G,J,Y);return J+Q+G};Object.defineProperties(EZ.prototype,s0);var RJ=EZ(),Kz=EZ({level:l6?l6.level:0});var R0=RJ;function xJ({value:Z,placeholder:Q="",focus:X=!0,mask:J,highlightPastedText:G=!1,showCursor:Y=!0,onChange:z,onSubmit:H}){let[W,q]=CJ({cursorOffset:(Z||"").length,cursorWidth:0}),{cursorOffset:O,cursorWidth:M}=W;PJ(()=>{q((V)=>{if(!X||!Y)return V;let B=Z||"";if(V.cursorOffset>B.length-1)return{cursorOffset:B.length,cursorWidth:0};return V})},[Z,X,Y]);let U=G?M:0,$=J?J.repeat(Z.length):Z,K=$,w=Q?R0.grey(Q):void 0;if(Y&&X){w=Q.length>0?R0.inverse(Q[0])+R0.grey(Q.slice(1)):R0.inverse(" "),K=$.length>0?"":R0.inverse(" ");let V=0;for(let B of $)K+=V>=O-U&&V<=O?R0.inverse(B):B,V++;if($.length>0&&O===$.length)K+=R0.inverse(" ")}return jJ((V,B)=>{if(B.upArrow||B.downArrow||B.ctrl&&V==="c"||B.tab||B.shift&&B.tab)return;if(B.return){if(H)H(Z);return}let F=O,D=Z,b=0;if(B.leftArrow){if(Y)F--}else if(B.rightArrow){if(Y)F++}else if(B.backspace||B.delete){if(O>0)D=Z.slice(0,O-1)+Z.slice(O,Z.length),F--}else if(D=Z.slice(0,O)+V+Z.slice(O,Z.length),F+=V.length,V.length>1)b=V.length;if(O<0)F=0;if(O>Z.length)F=Z.length;if(q({cursorOffset:F,cursorWidth:b}),D!==Z)z(D)},{isActive:X}),IJ.createElement(AJ,null,Q?$.length>0?K:w:K)}var i6=xJ;import{jsxDEV as g1}from"react/jsx-dev-runtime";function o0({value:Z,onChange:Q,marginTop:X}){return g1(SJ,{borderStyle:"single",borderColor:"gray",paddingX:1,marginTop:X,children:[g1(TJ,{color:"cyan",children:"> "},void 0,!1,void 0,this),g1(i6,{value:Z,onChange:Q},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}import{jsxDEV as L}from"react/jsx-dev-runtime";async function s6(Z){return new Promise((Q,X)=>{let J=!1,G=null,Y=null,z=null,H=null,W=Z?.projects||[],q=Z?.defaultProjectKey,O=q?[...W.filter((T)=>T.key===q),...W.filter((T)=>T.key!==q)]:W,M=Z?.issueTypes&&Z.issueTypes.length>0?Z.issueTypes:["Story","Task","Bug","Epic"],U=()=>{let{exit:T}=vJ(),[I,k]=PQ({step:"source-type",projectKey:q,promptStyle:"pm",issueType:"Story",decompose:!1,tasks:[]}),[E,P]=PQ(""),[u,p]=PQ(M),[a,t]=PQ(!1),W0=n6(null),jQ=n6(new Map);_1.useEffect(()=>{if(q&&M.length>0)jQ.current.set(q,M)},[]),_1.useEffect(()=>{G=(R)=>{k((x)=>({...x,...R}))}},[]),_1.useEffect(()=>{(async()=>{if(!I.projectKey)return;let x=jQ.current.get(I.projectKey);if(x&&x.length>0){if(p(x),!x.includes(I.issueType))k((d)=>({...d,issueType:x[0]||"Story"}));return}if(!Z?.fetchIssueTypes)return;t(!0);try{let d=await Z.fetchIssueTypes(I.projectKey);if(d.length>0){if(jQ.current.set(I.projectKey,d),p(d),!d.includes(I.issueType))k((v)=>({...v,issueType:d[0]||"Story"}))}}catch{p(M)}finally{t(!1)}})()},[I.projectKey,I.issueType]),EJ((R,x)=>{let d=["project","source-input","custom","epic","edit-prompt"].includes(I.step);if(x.ctrl&&R==="c"){T();return}if(x.ctrl&&R==="p"&&O.length>0){if(I.step!=="generating"&&I.step!=="regenerating"&&I.step!=="done"&&I.step!=="success"){k((v)=>({...v,step:"project"})),P("");return}}if(I.step==="success"){if(k({step:"source-type",projectKey:q,promptStyle:"pm",issueType:"Story",decompose:!1,tasks:[]}),P(""),H)H(),H=null;return}if(I.step==="preview"||I.step==="edit-prompt"){if(x.upArrow){W0.current?.scrollBy(-1);return}if(x.downArrow){let v=W0.current;if(v){let Q0=v.getScrollOffset(),b0=v.getBottomOffset();if(Q0<b0)v.scrollBy(1)}return}if(x.pageUp){let v=W0.current;if(v){let Q0=v.getViewportHeight()||1;v.scrollBy(-Q0)}return}if(x.pageDown){let v=W0.current;if(v){let Q0=v.getViewportHeight()||1,b0=v.getScrollOffset(),h1=v.getBottomOffset();if(b0<h1)v.scrollBy(Math.min(Q0,h1-b0))}return}}if(x.escape){QX();return}if(x.return){XX();return}if(!x.ctrl&&!x.meta&&R){if(I.step==="source-type"&&["1","2","3"].includes(R)){let v=R==="1"?"figma":R==="2"?"log":"prompt";k((Q0)=>({...Q0,sourceType:v,step:"source-input"})),P("");return}if(I.step==="issue-type"){let v=parseInt(R)-1;if(v>=0&&v<u.length){let Q0=u[v];if(Q0){k((b0)=>({...b0,issueType:Q0,step:"style"})),P("");return}}}if(I.step==="style"&&["1","2"].includes(R)){let v=R==="1"?"pm":"technical";k((Q0)=>({...Q0,promptStyle:v,decompose:!1,step:"confirm"})),P("");return}if(I.step==="confirm"&&["y","n"].includes(R.toLowerCase())){if(R.toLowerCase()==="y"){if(k((v)=>({...v,step:"generating"})),Y)J=!0,Y(I)}else k((v)=>({...v,step:"source-type"})),P("");return}if(I.step==="preview"){if(R.toLowerCase()==="e"){k((v)=>({...v,step:"edit-prompt"})),P("");return}if(["y","n"].includes(R.toLowerCase())){if(R.toLowerCase()==="y"){if(k((v)=>({...v,step:"done"})),Y)J=!0,Y(I)}else k((v)=>({...v,step:"source-type",previewData:void 0})),P("");return}}if(!d)return}});let QX=()=>{switch(I.step){case"source-type":break;case"project":P(""),k((R)=>({...R,step:"source-type"}));break;case"source-input":P(""),k((R)=>({...R,step:"source-type"}));break;case"custom":P(I.sourceContent||""),k((R)=>({...R,step:"source-input"}));break;case"epic":P(I.customInstructions||""),k((R)=>({...R,step:"custom"}));break;case"issue-type":P(I.epicKey||""),k((R)=>({...R,step:"epic"}));break;case"style":P(""),k((R)=>({...R,step:"issue-type"}));break;case"confirm":P(""),k((R)=>({...R,step:"style"}));break;case"preview":break;case"edit-prompt":P(""),k((R)=>({...R,step:"preview"}));break}},XX=()=>{let R=E.trim();switch(I.step){case"project":{if(R===""&&q){k((d)=>({...d,projectKey:q,step:"source-type"})),P("");break}let x=parseInt(R)-1;if(x>=0&&x<O.length){let d=O[x];if(d)k((v)=>({...v,projectKey:d.key,step:"source-type"})),P("")}break}case"source-type":if(["1","2","3"].includes(R)){let x=R==="1"?"figma":R==="2"?"log":"prompt";k((d)=>({...d,sourceType:x,step:"source-input"})),P("")}break;case"source-input":if(R)k((x)=>({...x,sourceContent:R,step:"custom"})),P("");break;case"custom":k((x)=>({...x,customInstructions:R||void 0,step:"epic"})),P("");break;case"epic":k((x)=>({...x,epicKey:R||void 0,step:"issue-type"})),P("");break;case"issue-type":{let x=parseInt(R)-1;if(x>=0&&x<u.length){let d=u[x];if(d)k((v)=>({...v,issueType:d,step:"style"})),P("")}break}case"style":if(["1","2"].includes(R)){let x=R==="1"?"pm":"technical";k((d)=>({...d,promptStyle:x,decompose:!1,step:"confirm"})),P("")}break;case"confirm":if(["y","n",""].includes(R.toLowerCase()))if(R.toLowerCase()==="y"||R===""){if(k((x)=>({...x,step:"generating"})),Y)J=!0,Y(I)}else k((x)=>({...x,step:"source-type"})),P("");break;case"preview":if(["y","n",""].includes(R.toLowerCase()))if(R.toLowerCase()==="y"||R===""){if(k((x)=>({...x,step:"done"})),Y)J=!0,Y(I)}else k((x)=>({...x,step:"source-type",previewData:void 0})),P("");break;case"edit-prompt":if(R){if(k((x)=>({...x,editPrompt:R,step:"regenerating"})),z&&I.previewData)z({editPrompt:R,currentSummary:I.previewData.summary,currentDescription:I.previewData.description});P("")}break}},JX=()=>{switch(I.step){case"project":return L(f,{flexDirection:"column",paddingY:1,children:[L(A,{bold:!0,children:"Select project:"},void 0,!1,void 0,this),O.map((R,x)=>L(A,{children:[x+1,". ",R.name," (",R.key,")",R.key===q?" (default)":""]},R.key,!0,void 0,this)),q&&L(A,{dimColor:!0,children:"Press Enter to use default project, or type number and press Enter"},void 0,!1,void 0,this),L(o0,{value:E,onChange:P,marginTop:1},void 0,!1,void 0,this)]},void 0,!0,void 0,this);case"source-type":return L(f,{flexDirection:"column",paddingY:1,children:[L(A,{bold:!0,children:"Select source type:"},void 0,!1,void 0,this),L(A,{children:"1. Figma design URL"},void 0,!1,void 0,this),L(A,{children:"2. Error log / Bug report"},void 0,!1,void 0,this),L(A,{children:"3. Free-form prompt"},void 0,!1,void 0,this)]},void 0,!0,void 0,this);case"source-input":{let R=I.sourceType==="figma"?"Enter Figma URL:":I.sourceType==="log"?"Enter error log or bug description:":"Enter your requirements:";return L(f,{flexDirection:"column",paddingY:1,children:[L(A,{bold:!0,children:R},void 0,!1,void 0,this),L(o0,{value:E,onChange:P},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}case"custom":return L(f,{flexDirection:"column",paddingY:1,children:[L(A,{bold:!0,children:"Custom instructions (optional, press Enter to skip):"},void 0,!1,void 0,this),L(A,{dimColor:!0,children:"Additional requirements or focus areas"},void 0,!1,void 0,this),L(A,{dimColor:!0,children:'Example: "Focus on accessibility" or "Prioritize performance"'},void 0,!1,void 0,this),L(o0,{value:E,onChange:P},void 0,!1,void 0,this)]},void 0,!0,void 0,this);case"epic":return L(f,{flexDirection:"column",paddingY:1,children:[L(A,{bold:!0,children:"Epic key (optional, press Enter to skip):"},void 0,!1,void 0,this),L(A,{dimColor:!0,children:"Example: PROJ-123"},void 0,!1,void 0,this),L(o0,{value:E,onChange:P},void 0,!1,void 0,this)]},void 0,!0,void 0,this);case"issue-type":return L(f,{flexDirection:"column",paddingY:1,children:[L(A,{bold:!0,children:"Select issue type:"},void 0,!1,void 0,this),u.map((R,x)=>L(A,{children:[x+1,". ",R,x===0?" (default)":""]},R,!0,void 0,this))]},void 0,!0,void 0,this);case"style":return L(f,{flexDirection:"column",paddingY:1,children:[L(A,{bold:!0,children:"Select prompt style:"},void 0,!1,void 0,this),L(A,{children:"1. PM style (user stories, acceptance criteria)"},void 0,!1,void 0,this),L(A,{children:"2. Technical style (includes technical considerations)"},void 0,!1,void 0,this)]},void 0,!0,void 0,this);case"confirm":{let R=I.sourceType==="figma"?"URL":I.sourceType==="log"?"Error Log":"Requirements";return L(f,{flexDirection:"column",paddingY:1,children:[L(A,{bold:!0,color:"green",children:"Review your configuration:"},void 0,!1,void 0,this),L(f,{paddingLeft:2,flexDirection:"column",paddingY:1,children:[I.projectKey&&L(f,{flexDirection:"column",paddingBottom:1,children:[L(A,{bold:!0,children:"Project:"},void 0,!1,void 0,this),L(A,{color:"cyan",children:I.projectKey},void 0,!1,void 0,this)]},void 0,!0,void 0,this),L(A,{bold:!0,children:"Source Type:"},void 0,!1,void 0,this),L(A,{color:"cyan",children:I.sourceType},void 0,!1,void 0,this),I.sourceContent&&L(f,{flexDirection:"column",paddingTop:1,children:[L(A,{bold:!0,children:[R,":"]},void 0,!0,void 0,this),L(A,{color:"cyan",children:I.sourceContent},void 0,!1,void 0,this)]},void 0,!0,void 0,this),I.customInstructions&&L(f,{flexDirection:"column",paddingTop:1,children:[L(A,{bold:!0,children:"Custom Instructions:"},void 0,!1,void 0,this),L(A,{color:"cyan",children:I.customInstructions},void 0,!1,void 0,this)]},void 0,!0,void 0,this),I.epicKey&&L(f,{flexDirection:"column",paddingTop:1,children:[L(A,{bold:!0,children:"Epic:"},void 0,!1,void 0,this),L(A,{color:"cyan",children:I.epicKey},void 0,!1,void 0,this)]},void 0,!0,void 0,this),L(f,{flexDirection:"column",paddingTop:1,children:[L(A,{bold:!0,children:"Issue Type:"},void 0,!1,void 0,this),L(A,{color:"cyan",children:I.issueType},void 0,!1,void 0,this)]},void 0,!0,void 0,this),L(f,{flexDirection:"column",paddingTop:1,children:[L(A,{bold:!0,children:"Prompt Style:"},void 0,!1,void 0,this),L(A,{color:"cyan",children:I.promptStyle},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),L(A,{bold:!0,children:"Continue? (Y/n)"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}case"generating":return L(f,{flexDirection:"column",paddingY:1,children:[L(A,{bold:!0,color:"cyan",children:"\uD83E\uDD16 Generating task..."},void 0,!1,void 0,this),L(A,{dimColor:!0,children:"This may take a moment"},void 0,!1,void 0,this)]},void 0,!0,void 0,this);case"preview":{if(!I.previewData)return L(f,{flexDirection:"column",paddingY:1,children:L(A,{bold:!0,color:"yellow",children:"Waiting for task preview..."},void 0,!1,void 0,this)},void 0,!1,void 0,this);return L(f,{flexDirection:"column",paddingY:1,children:[L(f,{paddingY:1,flexDirection:"column",children:[L(A,{bold:!0,children:"\uD83D\uDCCC Title:"},void 0,!1,void 0,this),L(f,{paddingLeft:2,children:L(A,{color:"green",children:I.previewData.summary},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this),L(f,{flexDirection:"column",children:[L(A,{bold:!0,children:"\uD83D\uDCDD Description:"},void 0,!1,void 0,this),L(A,{dimColor:!0,children:"(Use arrow keys \u2191\u2193 to scroll, PgUp/PgDn for fast scroll)"},void 0,!1,void 0,this),L(f,{borderStyle:"single",borderColor:"gray",paddingX:1,paddingY:1,flexDirection:"column",height:25,children:L(a6,{ref:W0,children:L(E1,{children:I.previewData.description},void 0,!1,void 0,this)},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this),L(f,{paddingTop:1,children:L(A,{bold:!0,children:["Create this ",I.issueType.toLowerCase()," in"," ",Z?.backendName||"task tracker","? (Y/n) \u2022 Press E to edit"]},void 0,!0,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}case"edit-prompt":return L(f,{flexDirection:"column",paddingY:1,children:[L(f,{paddingY:1,flexDirection:"column",children:[L(A,{bold:!0,children:"\uD83D\uDCCC Title:"},void 0,!1,void 0,this),L(f,{paddingLeft:2,children:L(A,{color:"green",children:I.previewData?.summary},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this),L(f,{flexDirection:"column",children:[L(A,{bold:!0,children:"\uD83D\uDCDD Current Description:"},void 0,!1,void 0,this),L(A,{dimColor:!0,children:"(Use arrow keys \u2191\u2193 to scroll, PgUp/PgDn for fast scroll)"},void 0,!1,void 0,this),L(f,{borderStyle:"single",borderColor:"gray",paddingX:1,paddingY:1,flexDirection:"column",height:15,children:L(a6,{ref:W0,children:L(E1,{children:I.previewData?.description||""},void 0,!1,void 0,this)},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this),L(f,{paddingTop:1,flexDirection:"column",children:[L(A,{bold:!0,color:"cyan",children:"What would you like to change?"},void 0,!1,void 0,this),L(A,{dimColor:!0,children:'Example: "Add more details about error handling" or "Make it more concise"'},void 0,!1,void 0,this),L(o0,{value:E,onChange:P,marginTop:1},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this);case"regenerating":return L(f,{flexDirection:"column",paddingY:1,children:[L(A,{bold:!0,color:"cyan",children:"\uD83E\uDD16 Updating task description..."},void 0,!1,void 0,this),L(A,{dimColor:!0,children:"This may take a moment"},void 0,!1,void 0,this)]},void 0,!0,void 0,this);case"done":return L(f,{flexDirection:"column",paddingY:1,children:[L(A,{bold:!0,color:"green",children:"\u2713 Ready to create!"},void 0,!1,void 0,this),L(A,{dimColor:!0,children:["Creating task in ",Z?.backendName||"task tracker","..."]},void 0,!0,void 0,this)]},void 0,!0,void 0,this);case"success":return L(f,{flexDirection:"column",paddingY:1,children:[L(f,{borderStyle:"round",borderColor:"green",paddingX:2,paddingY:1,children:L(f,{flexDirection:"column",children:[L(A,{bold:!0,color:"green",children:"\u2713 Success!"},void 0,!1,void 0,this),I.successMessage&&L(A,{color:"green",children:I.successMessage},void 0,!1,void 0,this)]},void 0,!0,void 0,this)},void 0,!1,void 0,this),L(f,{paddingTop:1,children:L(A,{dimColor:!0,children:"Press any key to create another task..."},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this);default:return null}},YX=O.find((R)=>R.key===I.projectKey)?.name||I.projectKey||"N/A";return L(f,{flexDirection:"column",children:[L(f,{flexDirection:"column",borderStyle:"round",borderColor:"cyan",paddingX:1,children:[L(A,{bold:!0,color:"cyan",children:"\uD83D\uDCCB @devintern/pm - Interactive Mode"},void 0,!1,void 0,this),L(f,{flexDirection:"row",gap:1,children:[L(A,{dimColor:!0,children:"Project: "},void 0,!1,void 0,this),L(A,{color:"cyan",children:YX},void 0,!1,void 0,this),O.length>0&&L(A,{dimColor:!0,children:" \u2022 Ctrl+P: Change Project"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),L(A,{dimColor:!0,children:"ESC: Back \u2022 Ctrl+C: Exit"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),JX()]},void 0,!0,void 0,this)},{waitUntilExit:$,unmount:K}=kJ(L(U,{},void 0,!1,void 0,this));$().then(()=>{if(!J)X(new Error("Interactive mode cancelled"))}),Q({setGenerating:()=>{if(G)G({step:"generating"})},setPreviewData:(T,I)=>{if(G)G({previewData:{summary:T,description:I},step:"preview"})},waitForCompletion:()=>{return new Promise((T)=>{Y=(I)=>{T(I)}})},waitForEdit:()=>{return new Promise((T)=>{z=T})},showSuccess:(T)=>{if(G)G({successMessage:T,step:"success"})},waitForRestart:()=>{return new Promise((T)=>{H=T})},restart:()=>{if(G)G({step:"source-type",projectKey:q,sourceType:void 0,sourceContent:void 0,customInstructions:void 0,epicKey:void 0,previewData:void 0,successMessage:void 0})},cleanup:()=>{K()}})})}import{join as I0}from"path";async function o6(){let Z=process.cwd(),Q=I0(Z,".devintern-pm"),X=I0(Q,".env");console.log(`\uD83D\uDE80 Initializing @devintern/pm in current directory...
137
+ `);try{if(await Bun.file(I0(Q,".")).exists()){if(console.log("\u26A0\uFE0F .devintern-pm directory already exists"),!await fJ("Overwrite existing configuration?"))console.log("\u274C Initialization cancelled"),process.exit(0)}}catch{}await Bun.$`mkdir -p ${Q}`,console.log("\u2705 Created .devintern-pm directory");let G=I0(import.meta.dir,".."),Y=I0(G,".env.example"),z=await Bun.file(Y).text(),H=I0(Z,".devintern-code"),W=I0(H,".env"),q="",O="",M="",U="",$="";try{let B=Bun.file(W);if(await B.exists()){console.log("\uD83D\uDCCB Found existing .devintern-code configuration");let D=(await B.text()).split(`
138
+ `);for(let b of D){let j=b.trim();if(j&&!j.startsWith("#")){if(j.startsWith("JIRA_BASE_URL="))q=j.split("=",2)[1]?.trim()||"";else if(j.startsWith("JIRA_EMAIL="))O=j.split("=",2)[1]?.trim()||"";else if(j.startsWith("JIRA_API_TOKEN="))M=j.split("=",2)[1]?.trim()||"";else if(j.startsWith("AGENT_HARNESS="))U=j.split("=",2)[1]?.trim()||"";else if(j.startsWith("AGENT_CLI_PATH="))$=j.split("=",2)[1]?.trim()||"";else if(j.startsWith("CLAUDE_CLI_PATH="))$=j.split("=",2)[1]?.trim()||""}}if(q||O||M||$)console.log("\u2705 Migrating configuration from .devintern-code")}}catch{}let K=z;if(q)K=K.replace(/JIRA_BASE_URL=.*/,`JIRA_BASE_URL=${q}`);if(O)K=K.replace(/JIRA_EMAIL=.*/,`JIRA_EMAIL=${O}`);if(M)K=K.replace(/JIRA_API_TOKEN=.*/,`JIRA_API_TOKEN=${M}`);if(U)K=K.replace(/AGENT_HARNESS=.*/,`AGENT_HARNESS=${U}`);if($)K=K.replace(/AGENT_CLI_PATH=.*/,`AGENT_CLI_PATH=${$}`),K=K.replace(/CLAUDE_CLI_PATH=.*/,`CLAUDE_CLI_PATH=${$}`);await Bun.write(X,K),console.log("\u2705 Created .env configuration file");let w=I0(Z,".gitignore"),V=Bun.file(w);try{if(await V.exists()){let B=await V.text(),F=B.includes(".devintern-pm/.env"),D=B.includes(".devintern-pm/.auth-session.json");if(!F||!D){if(!B.endsWith(`
139
+ `))B+=`
140
+ `;B+=`
141
+ # devintern-pm configuration (contains secrets)
142
+ .devintern-pm/.env
143
+ .devintern-pm/.auth-session.json
144
+ `,await Bun.write(w,B),console.log("\u2705 Updated .gitignore to exclude @devintern/pm secret files")}else console.log("\u2139\uFE0F .gitignore already contains .devintern-pm")}else await Bun.write(w,`# devintern-pm configuration (contains secrets)
145
+ .devintern-pm/.env
146
+ .devintern-pm/.auth-session.json
147
+ `),console.log("\u2705 Created .gitignore with @devintern/pm secret files")}catch(B){console.warn("\u26A0\uFE0F Could not update .gitignore:",B instanceof Error?B.message:B)}console.log(`
148
+ \u2728 Initialization complete!`),console.log(`
149
+ Next steps:`),console.log("1. Edit .devintern-pm/.env with your configuration"),console.log("2. Run devpm login to sign in"),console.log("3. Run devpm --interactive to create your first task")}async function fJ(Z){while(!0){process.stdout.write(`${Z} (Y/n): `);try{let Q=Bun.spawn(["bash","-c",'read line && echo "$line"'],{stdin:"inherit",stdout:"pipe",stderr:"inherit"}),X=await new Response(Q.stdout).text();await Q.exited;let J=X.trim().toLowerCase();if(J===""||J==="y"||J==="yes")return!0;else if(J==="n"||J==="no")return!1;else{process.stdout.write("Please answer 'y' or 'n' (default: y): ");continue}}catch(Q){return console.error(`
150
+ Error reading input:`,Q),!1}}}var bJ="https://api.polar.sh/v1",yJ="64a2bf56-c294-40f7-8971-39d32da0c254",gJ="https://devintern.com",vZ=14;async function _J(Z){let Q=await fetch(`${bJ}/customer-portal/license-keys/validate`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({key:Z,organization_id:yJ})});if(Q.status===404)return{valid:!1};if(!Q.ok)throw new Error(`Polar license validation failed (${Q.status})`);let X=await Q.json();return{valid:X.status==="granted",benefitId:X.benefit_id}}var hJ={"devintern/pm":[{id:"9c15467a-fbba-4da9-a3dd-7be38a832457",source:"individual"},{id:"e7cf3b7a-ee91-4140-ac0a-1ff0e50c9f77",source:"team-seat"}],"devintern/code":[{id:"00387324-f348-4893-adbc-9d1b6d302b93",source:"individual"},{id:"8785d79b-3d72-4952-95bb-856f81d41348",source:"team-seat"},{id:"edd8b324-c200-47d7-8dda-ef2b1101374a",source:"addon"},{id:"905265d5-4299-494e-a7c8-1d39bf5d410c",source:"addon"},{id:"8d22faf5-8a32-4947-95fe-2583a115ba15",source:"addon"},{id:"0db73ccd-a88a-46ae-966a-c7947fc6d638",source:"addon"},{id:"6d969971-9431-40ed-9c28-2bd8081144f6",source:"addon"}]};function mJ(Z){return hJ[Z.toLowerCase().trim()]??[]}async function uJ(Z,Q,X){let J=process.env.DEVINTERN_API_BASE||gJ,G=new URLSearchParams({productKey:Z});if(X)G.set("server","1");let Y=`${J}/api/license/check?${G.toString()}`;try{let z=await fetch(Y,{headers:{Authorization:`Bearer ${Q}`}});if(!z.ok)return null;return await z.json()}catch{return null}}function dJ(Z){if(!Z)return null;let Q=new Date(Z),G=(new Date().getTime()-Q.getTime())/86400000,Y=Math.max(0,vZ-G);return Y>0?Math.ceil(Y):0}async function t6(Z){let{productKey:Q,licenseKey:X,supabaseConfig:J,allowTrial:G=!0,requireServerAddon:Y=!1}=Z;if(process.env.DEVINTERN_SKIP_LICENSE_CHECK==="1")return{valid:!0,source:"license-key",message:"License check skipped (DEVINTERN_SKIP_LICENSE_CHECK=1)."};let z=X||process.env.LICENSE_KEY;if(z)try{let q=await _J(z);if(!q.valid)return{valid:!1,source:"license-key",message:"License key is invalid or revoked."};let O=mJ(Q),M=q.benefitId?O.find((U)=>U.id===q.benefitId):void 0;if(O.length>0&&!M&&q.benefitId)return{valid:!1,source:"license-key",message:"License key is valid but does not match this product."};if(Y&&M?.source!=="addon")return{valid:!1,source:"license-key",message:"Automated execution requires a server-automation addon license. Purchase one at https://devintern.com/pricing#server-automation."};return{valid:!0,source:"license-key",entitlementSource:M?.source,message:"License key is valid."}}catch(q){return{valid:!1,source:"license-key",message:`License validation failed: ${q instanceof Error?q.message:String(q)}`}}let H=null;try{H=await VQ(J)}catch{}if(H?.accessToken){let q=await uJ(Q,H.accessToken,Y);if(q?.entitled){let O=q.productName||"your purchased license";return{valid:!0,source:"entitlement",entitlementSource:q.source,message:`Entitlement confirmed via ${O}.`}}}if(G&&H?.accessToken){let q=await FQ(J,H.accessToken);if(q){let O=dJ(q);if(O&&O>0)return{valid:!0,source:"trial",message:`No license found. Using ${vZ}-day trial (${O} days remaining).`,trialDaysRemaining:O}}}let W=[];if(Y){if(W.push("Automated execution detected (CI / systemd / cron) but no server-automation addon was found."),W.push("Set LICENSE_KEY to a server-automation addon license key from https://devintern.com/account, or purchase one at https://devintern.com/pricing#server-automation."),!H)W.push("Alternatively, sign in if your account already holds an addon.")}else{if(!H)W.push("No LICENSE_KEY is set and you are not signed in.");else W.push("Your account has no matching license for this product.");if(W.push("Set LICENSE_KEY to a license key from https://devintern.com/account, or purchase one at https://devintern.com/pricing."),G){if(!H)W.push(`Alternatively, sign in to start your ${vZ}-day trial.`);else if(H.accessToken)if(await FQ(J,H.accessToken))W.push(`Your ${vZ}-day trial has expired.`);else W.push(`Your trial has not started. Run the login command to begin your ${vZ}-day trial.`)}}return{valid:!1,source:"none",message:W.join(" ")}}function r6(Z){if(!Z.valid)console.error(`
151
+ \u274C License check failed`),console.error(` ${Z.message}
152
+ `),process.exit(1);if(Z.source==="trial"&&Z.trialDaysRemaining)console.log(`\u23F3 Trial mode: ${Z.trialDaysRemaining} day${Z.trialDaysRemaining===1?"":"s"} remaining. Purchase at https://devintern.com/pricing
153
+ `);else if(Z.source==="license-key"||Z.source==="entitlement")console.log(`\u2705 ${Z.message}
154
+ `)}async function ZX(Z,Q,X,J){let Y=import.meta.dir.endsWith("/dist")||import.meta.dir.endsWith("\\dist")?e6(import.meta.dir,".."):import.meta.dir,z=e6(Y,"prompts",Z,Q,X),W=await Bun.file(z).text();for(let[q,O]of Object.entries(J))W=W.replace(new RegExp(`{{${q}}}`,"g"),O);return W.trim()}async function cJ(Z){while(!0){process.stdout.write(`${Z} (Y/n): `);try{let Q=Bun.spawn(["bash","-c",'read line && echo "$line"'],{stdin:"inherit",stdout:"pipe",stderr:"inherit"}),X=await new Response(Q.stdout).text();await Q.exited;let J=X.trim().toLowerCase();if(J===""||J==="y"||J==="yes")return!0;else if(J==="n"||J==="no")return!1;else{process.stdout.write("Please answer 'y' or 'n' (default: y): ");continue}}catch(Q){return console.error(`
155
+ Error reading input:`,Q),!1}}}function lJ(){let Z=Bun.argv.slice(2);if(Z.includes("init")||Z.includes("--init"))return"init";if(Z.includes("login"))return"login";if(Z.includes("logout"))return"logout";if(Z.includes("whoami"))return"whoami";if(Z.includes("--interactive"))return null;if(Z.length===0||Z.includes("--help")||Z.includes("-h"))console.log(`
156
+ Usage: devpm init
157
+ devpm login
158
+ devpm logout
159
+ devpm whoami
160
+ devpm --figma <url> [options]
161
+ devpm --log <text> [options]
162
+ devpm --prompt <text> [options]
163
+ devpm --interactive
164
+
165
+ Commands:
166
+ init Initialize .devintern-pm configuration in current directory
167
+ login Sign in to your devintern account
168
+ logout Clear local auth session
169
+ whoami Show current authenticated user
170
+
171
+ Modes:
172
+ --interactive Interactive mode - step-by-step task creation (recommended)
173
+
174
+ Source (one required for non-interactive mode):
175
+ --figma <url> Figma design node URL to analyze
176
+ --log <text> Error log or bug report text to analyze
177
+ --prompt <text> Free-form text describing requirements or features
178
+
179
+ Options:
180
+ --epic, -e <key> Epic key to link the story to (e.g., PROJ-100)
181
+ --type, -t <type> Issue type (default: "Story")
182
+ Common types: Story, Task, Bug, Epic
183
+ --custom, -c <text> Additional custom instructions for the requirements
184
+ --style, -s <type> Prompt style: "pm" (default) or "technical"
185
+ - pm: Focuses on user stories and acceptance criteria
186
+ - technical: Includes Technical Considerations section
187
+ --model, -m <model> Model to use (agent-specific, e.g., "sonnet", "opus", or provider/model)
188
+ --decompose Decompose the story into subtasks (default: off)
189
+ --confirm Interactively confirm each subtask before creating
190
+ --help, -h Show this help message
191
+
192
+ Environment variables (set in .env):
193
+ TASK_TRACKER Task tracker to use: jira | linear | trello | azure-devops | asana | github | markdown (default: jira)
194
+ MARKDOWN_TASKS_DIR Directory for markdown tasks (default: .devintern-pm/tasks)
195
+ JIRA_BASE_URL Your JIRA instance URL (e.g., https://your-org.atlassian.net)
196
+ JIRA_EMAIL Your Jira email
197
+ JIRA_API_TOKEN Your Jira API token
198
+ JIRA_DEFAULT_PROJECT_KEY Your Jira project key (e.g., PROJ)
199
+ LINEAR_API_KEY Your Linear API token (create at https://linear.app/settings/api)
200
+ LINEAR_DEFAULT_TEAM_KEY Default Linear team key (e.g., ENG)
201
+ TRELLO_API_KEY Your Trello API key (create at https://trello.com/app-key)
202
+ TRELLO_API_TOKEN Your Trello API token (generated from app-key page)
203
+ TRELLO_DEFAULT_BOARD_ID Default Trello board ID (optional)
204
+ TRELLO_DEFAULT_LIST_ID Default Trello list ID (optional)
205
+ AZURE_DEVOPS_ORG Your Azure DevOps organization name
206
+ AZURE_DEVOPS_PAT Your Azure DevOps Personal Access Token
207
+ AZURE_DEVOPS_PROJECT Default Azure DevOps project name
208
+ ASANA_API_TOKEN Your Asana Personal Access Token
209
+ ASANA_DEFAULT_PROJECT_GID Default Asana project GID (optional)
210
+ GITHUB_TOKEN Your GitHub Personal Access Token
211
+ GITHUB_OWNER GitHub repository owner (username or org)
212
+ GITHUB_REPO GitHub repository name
213
+ LICENSE_KEY Your license key (optional, skips trial)
214
+
215
+ Examples:
216
+ # Interactive mode (recommended)
217
+ devpm --interactive # Step-by-step task creation
218
+
219
+ # Figma designs
220
+ devpm --figma "https://www.figma.com/design/abc/file?node-id=123-456"
221
+ devpm --figma "https://..." --epic PROJ-100
222
+ devpm --figma "https://..." -c "Focus on accessibility"
223
+ devpm --figma "https://..." --style technical --decompose
224
+ devpm --figma "https://..." --type Task
225
+
226
+ # Error logs
227
+ devpm --log "Error: Cannot read property 'id' of undefined at line 42"
228
+ devpm --log "$(cat error.log)" --epic PROJ-200 --type Bug
229
+ devpm --log "Stack trace..." --style technical --model opus
230
+
231
+ # Free-form prompts
232
+ devpm --prompt "Add user profile settings page with theme preferences"
233
+ devpm --prompt "$(cat requirements.txt)" --epic PROJ-300
234
+ devpm --prompt "Implement OAuth login" --style technical --decompose
235
+ `),process.exit(0);let Q,X,J,G="pm",Y=!1,z=!1,H,W="Story";for(let q=0;q<Z.length;q++){let O=Z[q];if(!O)continue;if(O==="--figma"){if(q+1>=Z.length)console.error("Error: --figma requires a URL"),process.exit(1);if(Q)console.error("Error: Cannot specify multiple source types (--figma, --log, --prompt)"),process.exit(1);Q={type:"figma",content:Z[q+1]},q++}else if(O==="--log"){if(q+1>=Z.length)console.error("Error: --log requires text content"),process.exit(1);if(Q)console.error("Error: Cannot specify multiple source types (--figma, --log, --prompt)"),process.exit(1);Q={type:"log",content:Z[q+1]},q++}else if(O==="--prompt"){if(q+1>=Z.length)console.error("Error: --prompt requires text content"),process.exit(1);if(Q)console.error("Error: Cannot specify multiple source types (--figma, --log, --prompt)"),process.exit(1);Q={type:"prompt",content:Z[q+1]},q++}else if(O==="--epic"||O==="-e"){if(q+1>=Z.length)console.error("Error: --epic requires a value"),process.exit(1);X=Z[q+1],q++}else if(O==="--type"||O==="-t"){if(q+1>=Z.length)console.error("Error: --type requires a value"),process.exit(1);W=Z[q+1],q++}else if(O==="--custom"||O==="-c"){if(q+1>=Z.length)console.error("Error: --custom requires a value"),process.exit(1);J=Z[q+1],q++}else if(O==="--style"||O==="-s"){if(q+1>=Z.length)console.error("Error: --style requires a value"),process.exit(1);let M=Z[q+1];if(M!=="technical"&&M!=="pm")console.error('Error: --style must be either "technical" or "pm"'),process.exit(1);G=M,q++}else if(O==="--model"||O==="-m"){if(q+1>=Z.length)console.error("Error: --model requires a value"),process.exit(1);H=Z[q+1],q++}else if(O==="--decompose")Y=!0;else if(O==="--confirm")z=!0;else console.error(`Error: Unknown argument "${O}"`),console.error("Use --help to see available options"),process.exit(1)}if(!Q)console.error("Error: Source is required (use --figma, --log, or --prompt)"),process.exit(1);return{source:Q,epicKey:X,promptStyle:G,decompose:Y,confirm:z,model:H,issueType:W,extraInstructions:J}}async function pJ(Z){let Q=await t6({productKey:"devintern/pm",supabaseConfig:Z.supabase});r6(Q)}async function AQ(){await k6();let Z=lJ();if(Z==="init"){await o6();return}if(Z==="login"){let U=await LQ(),$=await S6(U);console.log(`\u2705 Signed in as ${$.email||$.id}`),process.exit(0)}if(Z==="logout"){let U=await LQ();await T6(U),console.log("\u2705 Signed out");return}if(Z==="whoami"){let U=await LQ(),$=await VQ(U);if(!$){console.log("Not signed in. Run `devpm login`.");return}console.log(`Signed in as ${$.email||$.id}`);return}let Q,X,J,G,Y,z,H,W,q,O=null,M;try{if(M=await E6(),await pJ(M),Z===null){console.clear();let E=await T1(M),P;try{if(E.getProjects)P=(await E.getProjects()).map((W0)=>({key:W0.key,name:W0.name}))}catch{console.error(`\u26A0\uFE0F Warning: Could not fetch projects from ${E.name}`)}let u=M.jira?.defaultProjectKey||M.linear?.defaultTeamKey||M.trello?.defaultBoardId||M.azureDevOps?.defaultProject||M.asana?.defaultProjectGid||M.github?.owner+"/"+M.github?.repo||(P&&P.length>0?P[0]?.key:void 0),p;try{if(E.getIssueTypes)p=await E.getIssueTypes(u)}catch{console.error(`\u26A0\uFE0F Warning: Could not fetch issue types from ${E.name}, using defaults`)}try{O=await s6({projects:P,defaultProjectKey:M.jira?.defaultProjectKey||M.linear?.defaultTeamKey||M.trello?.defaultBoardId||M.azureDevOps?.defaultProject||M.asana?.defaultProjectGid||(M.github?M.github.owner+"/"+M.github.repo:void 0),issueTypes:p,fetchIssueTypes:E.getIssueTypes?async(t)=>{return await E.getIssueTypes(t)}:void 0,backendName:E.name})}catch{console.log(`
236
+ Bye!`),process.exit(0)}let a=await O.waitForCompletion();if(!a.sourceType||!a.sourceContent)console.error("\u274C Interactive mode was cancelled or incomplete"),process.exit(1);Q={type:a.sourceType,content:a.sourceContent},X=a.epicKey,J=a.customInstructions,G=a.promptStyle,Y=a.decompose,z=!1,H=void 0,W=a.issueType,q=a.projectKey}else Q=Z.source,X=Z.epicKey,J=Z.extraInstructions,G=Z.promptStyle,Y=Z.decompose,z=Z.confirm,H=Z.model,W=Z.issueType,q=void 0;let U=M,$=await T1(U),K=Q.type==="figma"?"Figma design":Q.type==="log"?"error log":"free-form prompt";if(!O){if(console.log(`Step 1: Creating ${$.name} story from ${K}
237
+ `),console.log(`Source type: ${Q.type}`),Q.type==="figma")console.log(`Figma URL: ${Q.content}`);else{let E=Q.content.length>100?Q.content.substring(0,100)+"...":Q.content,P=Q.type==="log"?"Log preview":"Prompt preview";console.log(`${P}: ${E}`)}if(console.log(`Prompt style: ${G}`),console.log(`Issue type: ${W}`),H)console.log(`Model: ${H}`);if(X)console.log(`Epic: ${X}`);if(J)console.log(`Custom instructions: ${J}`)}let w={epicContext:X?`
238
+ This story will be part of epic: ${X}`:"",extraInstructions:J?`
239
+ Additional instructions: ${J}`:""};if(Q.type==="figma")w.figmaUrl=Q.content;else if(Q.type==="log")w.logContent=Q.content;else if(Q.type==="prompt")w.promptContent=Q.content;let V=await ZX(Q.type,G,"story-generation.txt",w);if(O)O.setGenerating();let B=await NQ(U.agent.harness,U.agent.path,V,{maxTurns:100,skipPermissions:!0,model:H,silent:!!O});if(B.exitCode!==0)console.error(`\u274C Failed to analyze ${K}`),console.error(B.stderr),process.exit(1);let F;try{let E=B.stdout.trim(),P=E.match(/```(?:json)?\s*(\{[\s\S]*?\})\s*```/);if(P?.[1])E=P[1];if(F=JSON.parse(E),!F.summary||!F.description)throw new Error("Missing required fields: summary and description")}catch(E){console.error(`
240
+ \u274C Failed to parse story requirements from Agent output`),console.error("Error:",E instanceof Error?E.message:E),console.error("Output:",B.stdout),process.exit(1)}if(O){O.setPreviewData(F.summary,F.description);while(!0){let E=await Promise.race([O.waitForCompletion().then(()=>null),O.waitForEdit()]);if(!E)break;let P=`You are helping revise a ${W.toLowerCase()} description.
241
+
242
+ Current Title: ${E.currentSummary}
243
+
244
+ Current Description:
245
+ ${E.currentDescription}
246
+
247
+ User's edit request: ${E.editPrompt}
248
+
249
+ Please update the description based on the user's feedback. Keep the same title unless the user specifically asks to change it. Return ONLY valid JSON in this exact format:
250
+
251
+ \`\`\`json
252
+ {
253
+ "summary": "Updated or same title",
254
+ "description": "Updated description in markdown format"
255
+ }
256
+ \`\`\``,u=await NQ(U.agent.harness,U.agent.path,P,{maxTurns:100,skipPermissions:!0,model:H,silent:!0});if(u.exitCode!==0){console.error("\u274C Failed to update task description"),console.error(u.stderr);continue}try{let p=u.stdout.trim(),a=p.match(/```(?:json)?\s*(\{[\s\S]*?\})\s*```/);if(a?.[1])p=a[1];let t=JSON.parse(p);if(!t.summary||!t.description)throw new Error("Missing required fields in update");F=t,O.setPreviewData(F.summary,F.description)}catch(p){console.error("\u274C Failed to parse updated task from Agent"),console.error("Error:",p instanceof Error?p.message:p)}}}if(!O)console.log(`
257
+ \uD83D\uDCDD Creating ${$.name} ${W.toLowerCase()}...`),console.log(` Title: ${F.summary}`);let D=await $.createTask(F.summary,F.description,W,q);if(!O)console.log(`
258
+ \u2705 ${$.name} ${W.toLowerCase()} created: ${D.url}`);if(X&&$.linkToEpic){if(!O)console.log(`\uD83D\uDD17 Linking story to epic ${X}...`);try{if(await $.linkToEpic(D.key,X),!O)console.log(`\u2705 Story linked to epic ${X}`)}catch(E){if(console.error(`\u26A0\uFE0F Warning: Failed to link to epic: ${E instanceof Error?E.message:E}`),!O)console.log("Continuing with task decomposition...")}}if(!O)console.log();if(!Y){if(!O){if(console.log(`\u2705 ${W} created successfully!
259
+ `),console.log("Summary:"),console.log(` ${W}: ${D.url}`),X)console.log(` Epic: ${X}`);console.log(`
260
+ \uD83C\uDF89 Done!`)}if(O)return O.showSuccess(`Task created: ${D.url}`),await O.waitForRestart(),AQ();return}console.log(`Step 2: Decomposing story into tasks
261
+ `);let b=await ZX(Q.type,G,"decomposition.txt",{storySummary:F.summary,storyDescription:F.description}),j=await NQ(U.agent.harness,U.agent.path,b,{maxTurns:100,skipPermissions:!0,model:H});if(j.exitCode!==0)console.error("\u274C Failed to decompose story"),console.error(j.stderr),process.exit(1);let T;try{let E=j.stdout.trim(),P=E.match(/```(?:json)?\s*(\{[\s\S]*?\})\s*```/);if(P?.[1])E=P[1];if(T=JSON.parse(E),!T.subtasks||!Array.isArray(T.subtasks))throw new Error("Expected subtasks array in response")}catch(E){console.error(`
262
+ \u274C Failed to parse subtasks from Agent output`),console.error("Error:",E instanceof Error?E.message:E),console.error("Output:",j.stdout),process.exit(1)}if(console.log(`
263
+ \u2705 Agent suggested ${T.subtasks.length} subtasks
264
+ `),z)console.log(`\uD83D\uDCDD Review and confirm each subtask:
265
+ `);else console.log(`\uD83D\uDCDD Creating subtasks in ${$.name}...
266
+ `);let I=[],k=[];for(let E=0;E<T.subtasks.length;E++){let P=T.subtasks[E];if(!P)continue;if(z){if(console.log(`
267
+ `+"\u2500".repeat(80)),console.log(`
268
+ \uD83D\uDCCB Task ${E+1}/${T.subtasks.length}`),console.log(` ${P.summary}
269
+ `),P.description){let a=P.description.substring(0,300).split(`
270
+ `);for(let t of a)if(t.trim())console.log(` ${t}`);if(P.description.length>300)console.log(" ...");console.log("")}if(!await cJ("Create this subtask?")){k.push(P.summary),console.log(`\u23ED\uFE0F Skipped
271
+ `);continue}}try{let u=P.description?.trim()||P.summary,p=await $.createSubtask(D.key,P.summary,u,q);if(I.push(p),z)console.log(`\u2705 Created: ${p.key}
272
+ `);else console.log(` \u2705 ${p.key}: ${P.summary}`)}catch(u){if(z)console.error(`\u26A0\uFE0F Failed to create subtask: ${P.summary}`),console.error(` Error: ${u instanceof Error?u.message:u}
273
+ `);else console.error(` \u26A0\uFE0F Failed to create subtask: ${P.summary}`),console.error(` Error: ${u instanceof Error?u.message:u}`)}}if(console.log(`
274
+ \u2705 ${W} decomposed into tasks successfully!
275
+ `),console.log("Summary:"),console.log(` ${W}: ${D.url}`),console.log(` Created: ${I.length} subtasks`),k.length>0)console.log(` Skipped: ${k.length} subtasks`);if(X)console.log(` Epic: ${X}`);if(console.log(`
276
+ \uD83C\uDF89 Done!`),O)return O.showSuccess(`Task created: ${D.url}`),await O.waitForRestart(),AQ()}catch(U){if(console.error(`
277
+ \u274C Error:`,U instanceof Error?U.message:U),O)return O.showSuccess(`Error: ${U instanceof Error?U.message:"Unknown error"}`),await O.waitForRestart(),AQ();process.exit(1)}}AQ();