@pathrule/cli 0.0.8 → 0.0.10

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.
Files changed (2) hide show
  1. package/dist/index.js +37 -37
  2. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -1,15 +1,15 @@
1
1
  #!/usr/bin/env node
2
2
  import {randomUUID,randomBytes,createHash}from'crypto';import {homedir,tmpdir}from'os';import Xe,{dirname,join,basename,normalize,resolve,relative,isAbsolute,sep,posix,win32}from'path';import {rm as rm$1,mkdir,chmod,appendFile,writeFile,unlink,readFile,stat,rename,access,mkdtemp,readdir,open,realpath,rmdir}from'fs/promises';import {createServer}from'http';import {execFile,spawn,execFileSync}from'child_process';import {createRequire}from'module';import {emitKeypressEvents}from'readline';import {createInterface}from'readline/promises';import {promisify}from'util';import {constants,promises}from'fs';import {fileURLToPath}from'url';var ef=Object.create;var Gi=Object.defineProperty;var tf=Object.getOwnPropertyDescriptor;var rf=Object.getOwnPropertyNames;var nf=Object.getPrototypeOf,sf=Object.prototype.hasOwnProperty;var R=(t,e)=>()=>(t&&(e=t(t=0)),e);var of=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),af=(t,e)=>{for(var r in e)Gi(t,r,{get:e[r],enumerable:true});},lf=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of rf(e))!sf.call(t,i)&&i!==r&&Gi(t,i,{get:()=>e[i],enumerable:!(n=tf(e,i))||n.enumerable});return t};var cf=(t,e,r)=>(r=t!=null?ef(nf(t)):{},lf(Gi(r,"default",{value:t,enumerable:true}),t));var La=of((LE,Ma)=>{var{hasOwnProperty:Yi}=Object.prototype,Xi=(t,e={})=>{typeof e=="string"&&(e={section:e}),e.align=e.align===true,e.newline=e.newline===true,e.sort=e.sort===true,e.whitespace=e.whitespace===true||e.align===true,e.platform=e.platform||typeof process<"u"&&process.platform,e.bracketedArray=e.bracketedArray!==false;let r=e.platform==="win32"?`\r
3
3
  `:`
4
- `,n=e.whitespace?" = ":"=",i=[],s=e.sort?Object.keys(t).sort():Object.keys(t),o=0;e.align&&(o=Oe(s.filter(c=>t[c]===null||Array.isArray(t[c])||typeof t[c]!="object").map(c=>Array.isArray(t[c])?`${c}[]`:c).concat([""]).reduce((c,u)=>Oe(c).length>=Oe(u).length?c:u)).length);let a="",l=e.bracketedArray?"[]":"";for(let c of s){let u=t[c];if(u&&Array.isArray(u))for(let d of u)a+=Oe(`${c}${l}`).padEnd(o," ")+n+Oe(d)+r;else u&&typeof u=="object"?i.push(c):a+=Oe(c).padEnd(o," ")+n+Oe(u)+r;}e.section&&a.length&&(a="["+Oe(e.section)+"]"+(e.newline?r+r:r)+a);for(let c of i){let u=ja(c,".").join("\\."),d=(e.section?e.section+".":"")+u,p=Xi(t[c],{...e,section:d});a.length&&p.length&&(a+=r),a+=p;}return a};function ja(t,e){var r=0,n=0,i=0,s=[];do if(i=t.indexOf(e,r),i!==-1){if(r=i+e.length,i>0&&t[i-1]==="\\")continue;s.push(t.slice(n,i)),n=i+e.length;}while(i!==-1);return s.push(t.slice(n)),s}var Na=(t,e={})=>{e.bracketedArray=e.bracketedArray!==false;let r=Object.create(null),n=r,i=null,s=/^\[([^\]]*)\]\s*$|^([^=]+)(=(.*))?$/i,o=t.split(/[\r\n]+/g),a={};for(let c of o){if(!c||c.match(/^\s*[;#]/)||c.match(/^\s*$/))continue;let u=c.match(s);if(!u)continue;if(u[1]!==void 0){if(i=bn(u[1]),i==="__proto__"){n=Object.create(null);continue}n=r[i]=r[i]||Object.create(null);continue}let d=bn(u[2]),p;e.bracketedArray?p=d.length>2&&d.slice(-2)==="[]":(a[d]=(a?.[d]||0)+1,p=a[d]>1);let h=p&&d.endsWith("[]")?d.slice(0,-2):d;if(h==="__proto__")continue;let f=u[3]?bn(u[4]):true,m=f==="true"||f==="false"||f==="null"?JSON.parse(f):f;p&&(Yi.call(n,h)?Array.isArray(n[h])||(n[h]=[n[h]]):n[h]=[]),Array.isArray(n[h])?n[h].push(m):n[h]=m;}let l=[];for(let c of Object.keys(r)){if(!Yi.call(r,c)||typeof r[c]!="object"||Array.isArray(r[c]))continue;let u=ja(c,".");n=r;let d=u.pop(),p=d.replace(/\\\./g,".");for(let h of u)h!=="__proto__"&&((!Yi.call(n,h)||typeof n[h]!="object")&&(n[h]=Object.create(null)),n=n[h]);n===r&&p===d||(n[p]=r[c],l.push(c));}for(let c of l)delete r[c];return r},Da=t=>t.startsWith('"')&&t.endsWith('"')||t.startsWith("'")&&t.endsWith("'"),Oe=t=>typeof t!="string"||t.match(/[=\r\n]/)||t.match(/^\[/)||t.length>1&&Da(t)||t!==t.trim()?JSON.stringify(t):t.split(";").join("\\;").split("#").join("\\#"),bn=t=>{if(t=(t||"").trim(),Da(t)){t.charAt(0)==="'"&&(t=t.slice(1,-1));try{t=JSON.parse(t);}catch{}}else {let e=false,r="";for(let n=0,i=t.length;n<i;n++){let s=t.charAt(n);if(e)"\\;#".indexOf(s)!==-1?r+=s:r+="\\"+s,e=false;else {if(";#".indexOf(s)!==-1)break;s==="\\"?e=true:r+=s;}}return e&&(r+="\\"),r.trim()}return t};Ma.exports={parse:Na,decode:Na,stringify:Xi,encode:Xi,safe:Oe,unsafe:bn};});function ug(t){return createHash("sha256").update(t,"utf8").digest("hex").slice(0,32)}function xl(t=process.env){return t.PATHRULE_HOME&&t.PATHRULE_HOME.trim()!==""?t.PATHRULE_HOME:join(homedir(),".pathrule")}function A(t=process.env){let e=xl(t);return {home:e,activeUserFile:join(e,"active-user"),credentialsFile:join(e,"credentials.json"),desktopFile:join(e,"desktop.json"),daemonFile:join(e,"daemon.json"),bridgePairFile:join(e,"bridge-pair.json"),tokenLockFile:join(e,".token-lock"),logsDir:join(e,"logs"),supportDir:join(e,"support")}}function it(t,e=0,r=process.env){let n=xl(r),i=ug(t),s=join(n,"config","users",i),o=join(n,"cache","users",i),a=join(o,`epoch-${e}`);return {userHash:i,userConfigDir:s,userConfigFile:join(s,"config.json"),userCacheDir:o,epochCacheDir:a}}var D,O,K=R(()=>{D=448,O=384;});function st(t=process.env){let e=A(t);async function r(){try{let i=await readFile(e.credentialsFile,"utf8"),s=JSON.parse(i);return s&&typeof s=="object"&&!Array.isArray(s)?s:{}}catch(i){if(i.code==="ENOENT")return {};throw i}}async function n(i){let s=dirname(e.credentialsFile);await mkdir(s,{recursive:true,mode:D}),await chmod(s,D).catch(()=>{});let o=`${e.credentialsFile}.tmp`;await writeFile(o,JSON.stringify(i),{encoding:"utf8",mode:O}),await chmod(o,O).catch(()=>{}),await rename(o,e.credentialsFile);}return {paths:e,async set(i,s){let o=await r();o[i]=s,await n(o);},async get(i){return (await r())[i]??null},async delete(i){let s=await r();return i in s?(delete s[i],Object.keys(s).length===0?await rm$1(e.credentialsFile,{force:true}):await n(s),true):false},async findAll(){let i=await r();return Object.entries(i).map(([s,o])=>({account:s,value:o}))}}}var _s=R(()=>{K();});function ot(t,e){var r={};for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&e.indexOf(n)<0&&(r[n]=t[n]);if(t!=null&&typeof Object.getOwnPropertySymbols=="function")for(var i=0,n=Object.getOwnPropertySymbols(t);i<n.length;i++)e.indexOf(n[i])<0&&Object.prototype.propertyIsEnumerable.call(t,n[i])&&(r[n[i]]=t[n[i]]);return r}function Tl(t,e,r,n){function i(s){return s instanceof r?s:new r(function(o){o(s);})}return new(r||(r=Promise))(function(s,o){function a(u){try{c(n.next(u));}catch(d){o(d);}}function l(u){try{c(n.throw(u));}catch(d){o(d);}}function c(u){u.done?s(u.value):i(u.value).then(a,l);}c((n=n.apply(t,e||[])).next());})}var kr=R(()=>{});var Al,Il=R(()=>{Al=t=>t?(...e)=>t(...e):(...e)=>fetch(...e);});var Wt,br,Bt,Ft,vr,Ol=R(()=>{Wt=class extends Error{constructor(e,r="FunctionsError",n){super(e),this.name=r,this.context=n;}toJSON(){return {name:this.name,message:this.message,context:this.context}}},br=class extends Wt{constructor(e){super("Failed to send a request to the Edge Function","FunctionsFetchError",e);}},Bt=class extends Wt{constructor(e){super("Relay Error invoking the Edge Function","FunctionsRelayError",e);}},Ft=class extends Wt{constructor(e){super("Edge Function returned a non-2xx status code","FunctionsHttpError",e);}};(function(t){t.Any="any",t.ApNortheast1="ap-northeast-1",t.ApNortheast2="ap-northeast-2",t.ApSouth1="ap-south-1",t.ApSoutheast1="ap-southeast-1",t.ApSoutheast2="ap-southeast-2",t.CaCentral1="ca-central-1",t.EuCentral1="eu-central-1",t.EuWest1="eu-west-1",t.EuWest2="eu-west-2",t.EuWest3="eu-west-3",t.SaEast1="sa-east-1",t.UsEast1="us-east-1",t.UsWest1="us-west-1",t.UsWest2="us-west-2";})(vr||(vr={}));});var Sr,$l=R(()=>{kr();Il();Ol();Sr=class{constructor(e,{headers:r={},customFetch:n,region:i=vr.Any}={}){this.url=e,this.headers=r,this.region=i,this.fetch=Al(n);}setAuth(e){this.headers.Authorization=`Bearer ${e}`;}invoke(e){return Tl(this,arguments,void 0,function*(r,n={}){var i;let s,o;try{let{headers:a,method:l,body:c,signal:u,timeout:d}=n,p={},{region:h}=n;h||(h=this.region);let f=new URL(`${this.url}/${r}`);h&&h!=="any"&&(p["x-region"]=h,f.searchParams.set("forceFunctionRegion",h));let m;c&&(a&&!Object.prototype.hasOwnProperty.call(a,"Content-Type")||!a)?typeof Blob<"u"&&c instanceof Blob||c instanceof ArrayBuffer?(p["Content-Type"]="application/octet-stream",m=c):typeof c=="string"?(p["Content-Type"]="text/plain",m=c):typeof FormData<"u"&&c instanceof FormData?m=c:(p["Content-Type"]="application/json",m=JSON.stringify(c)):c&&typeof c!="string"&&!(typeof Blob<"u"&&c instanceof Blob)&&!(c instanceof ArrayBuffer)&&!(typeof FormData<"u"&&c instanceof FormData)?m=JSON.stringify(c):m=c;let _=u;d&&(o=new AbortController,s=setTimeout(()=>o.abort(),d),u?(_=o.signal,u.addEventListener("abort",()=>o.abort())):_=o.signal);let b=yield this.fetch(f.toString(),{method:l||"POST",headers:Object.assign(Object.assign(Object.assign({},p),this.headers),a),body:m,signal:_}).catch(Z=>{throw new br(Z)}),w=b.headers.get("x-relay-error");if(w&&w==="true")throw new Bt(b);if(!b.ok)throw new Ft(b);let y=((i=b.headers.get("Content-Type"))!==null&&i!==void 0?i:"text/plain").split(";")[0].trim(),I;return y==="application/json"?I=yield b.json():y==="application/octet-stream"||y==="application/pdf"?I=yield b.blob():y==="text/event-stream"?I=b:y==="multipart/form-data"?I=yield b.formData():I=yield b.text(),{data:I,error:null,response:b}}catch(a){return {data:null,error:a,response:a instanceof Ft||a instanceof Bt?a.context:void 0}}finally{s&&clearTimeout(s);}})}};});var Nl=R(()=>{$l();});function Dl(t,e){return new Promise(r=>{if(e?.aborted){r();return}let n=setTimeout(()=>{e?.removeEventListener("abort",i),r();},t);function i(){clearTimeout(n),r();}e?.addEventListener("abort",i);})}function Sg(t,e,r,n){return !(!n||r>=3||!Ul.includes(t)||!vg.includes(e))}function Cr(t){"@babel/helpers - typeof";return Cr=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(e){return typeof e}:function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},Cr(t)}function xg(t,e){if(Cr(t)!="object"||!t)return t;var r=t[Symbol.toPrimitive];if(r!==void 0){var n=r.call(t,e);if(Cr(n)!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return (e==="string"?String:Number)(t)}function Pg(t){var e=xg(t,"string");return Cr(e)=="symbol"?e:e+""}function Tg(t,e,r){return (e=Pg(e))in t?Object.defineProperty(t,e,{value:r,enumerable:true,configurable:true,writable:true}):t[e]=r,t}function Ll(t,e){var r=Object.keys(t);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(t);e&&(n=n.filter(function(i){return Object.getOwnPropertyDescriptor(t,i).enumerable})),r.push.apply(r,n);}return r}function On(t){for(var e=1;e<arguments.length;e++){var r=arguments[e]!=null?arguments[e]:{};e%2?Ll(Object(r),true).forEach(function(n){Tg(t,n,r[n]);}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(r)):Ll(Object(r)).forEach(function(n){Object.defineProperty(t,n,Object.getOwnPropertyDescriptor(r,n));});}return t}var jl,vg,Ul,Wl,Cg,Eg,Ml,Ht,Rg,Bl,Hl=R(()=>{jl=t=>Math.min(1e3*2**t,3e4),vg=[520,503],Ul=["GET","HEAD","OPTIONS"],Wl=class extends Error{constructor(t){super(t.message),this.name="PostgrestError",this.details=t.details,this.hint=t.hint,this.code=t.code;}toJSON(){return {name:this.name,message:this.message,details:this.details,hint:this.hint,code:this.code}}};Cg=class{constructor(t){var e,r,n,i,s;this.shouldThrowOnError=false,this.retryEnabled=true,this.method=t.method,this.url=t.url,this.headers=new Headers(t.headers),this.schema=t.schema,this.body=t.body,this.shouldThrowOnError=(e=t.shouldThrowOnError)!==null&&e!==void 0?e:false,this.signal=t.signal,this.isMaybeSingle=(r=t.isMaybeSingle)!==null&&r!==void 0?r:false,this.shouldStripNulls=(n=t.shouldStripNulls)!==null&&n!==void 0?n:false,this.urlLengthLimit=(i=t.urlLengthLimit)!==null&&i!==void 0?i:8e3,this.retryEnabled=(s=t.retry)!==null&&s!==void 0?s:true,t.fetch?this.fetch=t.fetch:this.fetch=fetch;}throwOnError(){return this.shouldThrowOnError=true,this}stripNulls(){if(this.headers.get("Accept")==="text/csv")throw new Error("stripNulls() cannot be used with csv()");return this.shouldStripNulls=true,this}setHeader(t,e){return this.headers=new Headers(this.headers),this.headers.set(t,e),this}retry(t){return this.retryEnabled=t,this}then(t,e){var r=this;if(this.schema===void 0||(["GET","HEAD"].includes(this.method)?this.headers.set("Accept-Profile",this.schema):this.headers.set("Content-Profile",this.schema)),this.method!=="GET"&&this.method!=="HEAD"&&this.headers.set("Content-Type","application/json"),this.shouldStripNulls){let o=this.headers.get("Accept");o==="application/vnd.pgrst.object+json"?this.headers.set("Accept","application/vnd.pgrst.object+json;nulls=stripped"):(!o||o==="application/json")&&this.headers.set("Accept","application/vnd.pgrst.array+json;nulls=stripped");}let n=this.fetch,s=(async()=>{let o=0;for(;;){let c=new Headers(r.headers);o>0&&c.set("X-Retry-Count",String(o));let u;try{u=await n(r.url.toString(),{method:r.method,headers:c,body:JSON.stringify(r.body,(d,p)=>typeof p=="bigint"?p.toString():p),signal:r.signal});}catch(d){if(d?.name==="AbortError"||d?.code==="ABORT_ERR"||!Ul.includes(r.method))throw d;if(r.retryEnabled&&o<3){let p=jl(o);o++,await Dl(p,r.signal);continue}throw d}if(Sg(r.method,u.status,o,r.retryEnabled)){var a,l;let d=(a=(l=u.headers)===null||l===void 0?void 0:l.get("Retry-After"))!==null&&a!==void 0?a:null,p=d!==null?Math.max(0,parseInt(d,10)||0)*1e3:jl(o);await u.text(),o++,await Dl(p,r.signal);continue}return await r.processResponse(u)}})();return this.shouldThrowOnError||(s=s.catch(o=>{var a;let l="",c="",u="",d=o?.cause;if(d){var p,h,f,m;let w=(p=d?.message)!==null&&p!==void 0?p:"",y=(h=d?.code)!==null&&h!==void 0?h:"";l=`${(f=o?.name)!==null&&f!==void 0?f:"FetchError"}: ${o?.message}`,l+=`
4
+ `,n=e.whitespace?" = ":"=",i=[],s=e.sort?Object.keys(t).sort():Object.keys(t),o=0;e.align&&(o=Oe(s.filter(c=>t[c]===null||Array.isArray(t[c])||typeof t[c]!="object").map(c=>Array.isArray(t[c])?`${c}[]`:c).concat([""]).reduce((c,u)=>Oe(c).length>=Oe(u).length?c:u)).length);let a="",l=e.bracketedArray?"[]":"";for(let c of s){let u=t[c];if(u&&Array.isArray(u))for(let d of u)a+=Oe(`${c}${l}`).padEnd(o," ")+n+Oe(d)+r;else u&&typeof u=="object"?i.push(c):a+=Oe(c).padEnd(o," ")+n+Oe(u)+r;}e.section&&a.length&&(a="["+Oe(e.section)+"]"+(e.newline?r+r:r)+a);for(let c of i){let u=Da(c,".").join("\\."),d=(e.section?e.section+".":"")+u,p=Xi(t[c],{...e,section:d});a.length&&p.length&&(a+=r),a+=p;}return a};function Da(t,e){var r=0,n=0,i=0,s=[];do if(i=t.indexOf(e,r),i!==-1){if(r=i+e.length,i>0&&t[i-1]==="\\")continue;s.push(t.slice(n,i)),n=i+e.length;}while(i!==-1);return s.push(t.slice(n)),s}var Na=(t,e={})=>{e.bracketedArray=e.bracketedArray!==false;let r=Object.create(null),n=r,i=null,s=/^\[([^\]]*)\]\s*$|^([^=]+)(=(.*))?$/i,o=t.split(/[\r\n]+/g),a={};for(let c of o){if(!c||c.match(/^\s*[;#]/)||c.match(/^\s*$/))continue;let u=c.match(s);if(!u)continue;if(u[1]!==void 0){if(i=bn(u[1]),i==="__proto__"){n=Object.create(null);continue}n=r[i]=r[i]||Object.create(null);continue}let d=bn(u[2]),p;e.bracketedArray?p=d.length>2&&d.slice(-2)==="[]":(a[d]=(a?.[d]||0)+1,p=a[d]>1);let h=p&&d.endsWith("[]")?d.slice(0,-2):d;if(h==="__proto__")continue;let f=u[3]?bn(u[4]):true,m=f==="true"||f==="false"||f==="null"?JSON.parse(f):f;p&&(Yi.call(n,h)?Array.isArray(n[h])||(n[h]=[n[h]]):n[h]=[]),Array.isArray(n[h])?n[h].push(m):n[h]=m;}let l=[];for(let c of Object.keys(r)){if(!Yi.call(r,c)||typeof r[c]!="object"||Array.isArray(r[c]))continue;let u=Da(c,".");n=r;let d=u.pop(),p=d.replace(/\\\./g,".");for(let h of u)h!=="__proto__"&&((!Yi.call(n,h)||typeof n[h]!="object")&&(n[h]=Object.create(null)),n=n[h]);n===r&&p===d||(n[p]=r[c],l.push(c));}for(let c of l)delete r[c];return r},ja=t=>t.startsWith('"')&&t.endsWith('"')||t.startsWith("'")&&t.endsWith("'"),Oe=t=>typeof t!="string"||t.match(/[=\r\n]/)||t.match(/^\[/)||t.length>1&&ja(t)||t!==t.trim()?JSON.stringify(t):t.split(";").join("\\;").split("#").join("\\#"),bn=t=>{if(t=(t||"").trim(),ja(t)){t.charAt(0)==="'"&&(t=t.slice(1,-1));try{t=JSON.parse(t);}catch{}}else {let e=false,r="";for(let n=0,i=t.length;n<i;n++){let s=t.charAt(n);if(e)"\\;#".indexOf(s)!==-1?r+=s:r+="\\"+s,e=false;else {if(";#".indexOf(s)!==-1)break;s==="\\"?e=true:r+=s;}}return e&&(r+="\\"),r.trim()}return t};Ma.exports={parse:Na,decode:Na,stringify:Xi,encode:Xi,safe:Oe,unsafe:bn};});function ug(t){return createHash("sha256").update(t,"utf8").digest("hex").slice(0,32)}function xl(t=process.env){return t.PATHRULE_HOME&&t.PATHRULE_HOME.trim()!==""?t.PATHRULE_HOME:join(homedir(),".pathrule")}function A(t=process.env){let e=xl(t);return {home:e,activeUserFile:join(e,"active-user"),credentialsFile:join(e,"credentials.json"),desktopFile:join(e,"desktop.json"),daemonFile:join(e,"daemon.json"),bridgePairFile:join(e,"bridge-pair.json"),tokenLockFile:join(e,".token-lock"),logsDir:join(e,"logs"),supportDir:join(e,"support")}}function it(t,e=0,r=process.env){let n=xl(r),i=ug(t),s=join(n,"config","users",i),o=join(n,"cache","users",i),a=join(o,`epoch-${e}`);return {userHash:i,userConfigDir:s,userConfigFile:join(s,"config.json"),userCacheDir:o,epochCacheDir:a}}var j,O,K=R(()=>{j=448,O=384;});function st(t=process.env){let e=A(t);async function r(){try{let i=await readFile(e.credentialsFile,"utf8"),s=JSON.parse(i);return s&&typeof s=="object"&&!Array.isArray(s)?s:{}}catch(i){if(i.code==="ENOENT")return {};throw i}}async function n(i){let s=dirname(e.credentialsFile);await mkdir(s,{recursive:true,mode:j}),await chmod(s,j).catch(()=>{});let o=`${e.credentialsFile}.tmp`;await writeFile(o,JSON.stringify(i),{encoding:"utf8",mode:O}),await chmod(o,O).catch(()=>{}),await rename(o,e.credentialsFile);}return {paths:e,async set(i,s){let o=await r();o[i]=s,await n(o);},async get(i){return (await r())[i]??null},async delete(i){let s=await r();return i in s?(delete s[i],Object.keys(s).length===0?await rm$1(e.credentialsFile,{force:true}):await n(s),true):false},async findAll(){let i=await r();return Object.entries(i).map(([s,o])=>({account:s,value:o}))}}}var _s=R(()=>{K();});function ot(t,e){var r={};for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&e.indexOf(n)<0&&(r[n]=t[n]);if(t!=null&&typeof Object.getOwnPropertySymbols=="function")for(var i=0,n=Object.getOwnPropertySymbols(t);i<n.length;i++)e.indexOf(n[i])<0&&Object.prototype.propertyIsEnumerable.call(t,n[i])&&(r[n[i]]=t[n[i]]);return r}function Tl(t,e,r,n){function i(s){return s instanceof r?s:new r(function(o){o(s);})}return new(r||(r=Promise))(function(s,o){function a(u){try{c(n.next(u));}catch(d){o(d);}}function l(u){try{c(n.throw(u));}catch(d){o(d);}}function c(u){u.done?s(u.value):i(u.value).then(a,l);}c((n=n.apply(t,e||[])).next());})}var kr=R(()=>{});var Al,Il=R(()=>{Al=t=>t?(...e)=>t(...e):(...e)=>fetch(...e);});var Wt,br,Bt,Ft,vr,Ol=R(()=>{Wt=class extends Error{constructor(e,r="FunctionsError",n){super(e),this.name=r,this.context=n;}toJSON(){return {name:this.name,message:this.message,context:this.context}}},br=class extends Wt{constructor(e){super("Failed to send a request to the Edge Function","FunctionsFetchError",e);}},Bt=class extends Wt{constructor(e){super("Relay Error invoking the Edge Function","FunctionsRelayError",e);}},Ft=class extends Wt{constructor(e){super("Edge Function returned a non-2xx status code","FunctionsHttpError",e);}};(function(t){t.Any="any",t.ApNortheast1="ap-northeast-1",t.ApNortheast2="ap-northeast-2",t.ApSouth1="ap-south-1",t.ApSoutheast1="ap-southeast-1",t.ApSoutheast2="ap-southeast-2",t.CaCentral1="ca-central-1",t.EuCentral1="eu-central-1",t.EuWest1="eu-west-1",t.EuWest2="eu-west-2",t.EuWest3="eu-west-3",t.SaEast1="sa-east-1",t.UsEast1="us-east-1",t.UsWest1="us-west-1",t.UsWest2="us-west-2";})(vr||(vr={}));});var Sr,$l=R(()=>{kr();Il();Ol();Sr=class{constructor(e,{headers:r={},customFetch:n,region:i=vr.Any}={}){this.url=e,this.headers=r,this.region=i,this.fetch=Al(n);}setAuth(e){this.headers.Authorization=`Bearer ${e}`;}invoke(e){return Tl(this,arguments,void 0,function*(r,n={}){var i;let s,o;try{let{headers:a,method:l,body:c,signal:u,timeout:d}=n,p={},{region:h}=n;h||(h=this.region);let f=new URL(`${this.url}/${r}`);h&&h!=="any"&&(p["x-region"]=h,f.searchParams.set("forceFunctionRegion",h));let m;c&&(a&&!Object.prototype.hasOwnProperty.call(a,"Content-Type")||!a)?typeof Blob<"u"&&c instanceof Blob||c instanceof ArrayBuffer?(p["Content-Type"]="application/octet-stream",m=c):typeof c=="string"?(p["Content-Type"]="text/plain",m=c):typeof FormData<"u"&&c instanceof FormData?m=c:(p["Content-Type"]="application/json",m=JSON.stringify(c)):c&&typeof c!="string"&&!(typeof Blob<"u"&&c instanceof Blob)&&!(c instanceof ArrayBuffer)&&!(typeof FormData<"u"&&c instanceof FormData)?m=JSON.stringify(c):m=c;let _=u;d&&(o=new AbortController,s=setTimeout(()=>o.abort(),d),u?(_=o.signal,u.addEventListener("abort",()=>o.abort())):_=o.signal);let b=yield this.fetch(f.toString(),{method:l||"POST",headers:Object.assign(Object.assign(Object.assign({},p),this.headers),a),body:m,signal:_}).catch(Z=>{throw new br(Z)}),w=b.headers.get("x-relay-error");if(w&&w==="true")throw new Bt(b);if(!b.ok)throw new Ft(b);let y=((i=b.headers.get("Content-Type"))!==null&&i!==void 0?i:"text/plain").split(";")[0].trim(),I;return y==="application/json"?I=yield b.json():y==="application/octet-stream"||y==="application/pdf"?I=yield b.blob():y==="text/event-stream"?I=b:y==="multipart/form-data"?I=yield b.formData():I=yield b.text(),{data:I,error:null,response:b}}catch(a){return {data:null,error:a,response:a instanceof Ft||a instanceof Bt?a.context:void 0}}finally{s&&clearTimeout(s);}})}};});var Nl=R(()=>{$l();});function jl(t,e){return new Promise(r=>{if(e?.aborted){r();return}let n=setTimeout(()=>{e?.removeEventListener("abort",i),r();},t);function i(){clearTimeout(n),r();}e?.addEventListener("abort",i);})}function Sg(t,e,r,n){return !(!n||r>=3||!Ul.includes(t)||!vg.includes(e))}function Cr(t){"@babel/helpers - typeof";return Cr=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(e){return typeof e}:function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},Cr(t)}function xg(t,e){if(Cr(t)!="object"||!t)return t;var r=t[Symbol.toPrimitive];if(r!==void 0){var n=r.call(t,e);if(Cr(n)!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return (e==="string"?String:Number)(t)}function Pg(t){var e=xg(t,"string");return Cr(e)=="symbol"?e:e+""}function Tg(t,e,r){return (e=Pg(e))in t?Object.defineProperty(t,e,{value:r,enumerable:true,configurable:true,writable:true}):t[e]=r,t}function Ll(t,e){var r=Object.keys(t);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(t);e&&(n=n.filter(function(i){return Object.getOwnPropertyDescriptor(t,i).enumerable})),r.push.apply(r,n);}return r}function On(t){for(var e=1;e<arguments.length;e++){var r=arguments[e]!=null?arguments[e]:{};e%2?Ll(Object(r),true).forEach(function(n){Tg(t,n,r[n]);}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(r)):Ll(Object(r)).forEach(function(n){Object.defineProperty(t,n,Object.getOwnPropertyDescriptor(r,n));});}return t}var Dl,vg,Ul,Wl,Cg,Eg,Ml,Ht,Rg,Bl,Hl=R(()=>{Dl=t=>Math.min(1e3*2**t,3e4),vg=[520,503],Ul=["GET","HEAD","OPTIONS"],Wl=class extends Error{constructor(t){super(t.message),this.name="PostgrestError",this.details=t.details,this.hint=t.hint,this.code=t.code;}toJSON(){return {name:this.name,message:this.message,details:this.details,hint:this.hint,code:this.code}}};Cg=class{constructor(t){var e,r,n,i,s;this.shouldThrowOnError=false,this.retryEnabled=true,this.method=t.method,this.url=t.url,this.headers=new Headers(t.headers),this.schema=t.schema,this.body=t.body,this.shouldThrowOnError=(e=t.shouldThrowOnError)!==null&&e!==void 0?e:false,this.signal=t.signal,this.isMaybeSingle=(r=t.isMaybeSingle)!==null&&r!==void 0?r:false,this.shouldStripNulls=(n=t.shouldStripNulls)!==null&&n!==void 0?n:false,this.urlLengthLimit=(i=t.urlLengthLimit)!==null&&i!==void 0?i:8e3,this.retryEnabled=(s=t.retry)!==null&&s!==void 0?s:true,t.fetch?this.fetch=t.fetch:this.fetch=fetch;}throwOnError(){return this.shouldThrowOnError=true,this}stripNulls(){if(this.headers.get("Accept")==="text/csv")throw new Error("stripNulls() cannot be used with csv()");return this.shouldStripNulls=true,this}setHeader(t,e){return this.headers=new Headers(this.headers),this.headers.set(t,e),this}retry(t){return this.retryEnabled=t,this}then(t,e){var r=this;if(this.schema===void 0||(["GET","HEAD"].includes(this.method)?this.headers.set("Accept-Profile",this.schema):this.headers.set("Content-Profile",this.schema)),this.method!=="GET"&&this.method!=="HEAD"&&this.headers.set("Content-Type","application/json"),this.shouldStripNulls){let o=this.headers.get("Accept");o==="application/vnd.pgrst.object+json"?this.headers.set("Accept","application/vnd.pgrst.object+json;nulls=stripped"):(!o||o==="application/json")&&this.headers.set("Accept","application/vnd.pgrst.array+json;nulls=stripped");}let n=this.fetch,s=(async()=>{let o=0;for(;;){let c=new Headers(r.headers);o>0&&c.set("X-Retry-Count",String(o));let u;try{u=await n(r.url.toString(),{method:r.method,headers:c,body:JSON.stringify(r.body,(d,p)=>typeof p=="bigint"?p.toString():p),signal:r.signal});}catch(d){if(d?.name==="AbortError"||d?.code==="ABORT_ERR"||!Ul.includes(r.method))throw d;if(r.retryEnabled&&o<3){let p=Dl(o);o++,await jl(p,r.signal);continue}throw d}if(Sg(r.method,u.status,o,r.retryEnabled)){var a,l;let d=(a=(l=u.headers)===null||l===void 0?void 0:l.get("Retry-After"))!==null&&a!==void 0?a:null,p=d!==null?Math.max(0,parseInt(d,10)||0)*1e3:Dl(o);await u.text(),o++,await jl(p,r.signal);continue}return await r.processResponse(u)}})();return this.shouldThrowOnError||(s=s.catch(o=>{var a;let l="",c="",u="",d=o?.cause;if(d){var p,h,f,m;let w=(p=d?.message)!==null&&p!==void 0?p:"",y=(h=d?.code)!==null&&h!==void 0?h:"";l=`${(f=o?.name)!==null&&f!==void 0?f:"FetchError"}: ${o?.message}`,l+=`
5
5
 
6
6
  Caused by: ${(m=d?.name)!==null&&m!==void 0?m:"Error"}: ${w}`,y&&(l+=` (${y})`),d?.stack&&(l+=`
7
7
  ${d.stack}`);}else {var _;l=(_=o?.stack)!==null&&_!==void 0?_:"";}let b=this.url.toString().length;return o?.name==="AbortError"||o?.code==="ABORT_ERR"?(u="",c="Request was aborted (timeout or manual cancellation)",b>this.urlLengthLimit&&(c+=`. 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.`)):(d?.name==="HeadersOverflowError"||d?.code==="UND_ERR_HEADERS_OVERFLOW")&&(u="",c="HTTP headers exceeded server limits (typically 16KB)",b>this.urlLengthLimit&&(c+=`. 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.`)),{success:false,error:{message:`${(a=o?.name)!==null&&a!==void 0?a:"FetchError"}: ${o?.message}`,details:l,hint:c,code:u},data:null,count:null,status:0,statusText:""}})),s.then(t,e)}async processResponse(t){var e=this;let r=null,n=null,i=null,s=t.status,o=t.statusText;if(t.ok){var a,l;if(e.method!=="HEAD"){var c;let p=await t.text();p===""||(e.headers.get("Accept")==="text/csv"||e.headers.get("Accept")&&(!((c=e.headers.get("Accept"))===null||c===void 0)&&c.includes("application/vnd.pgrst.plan+text"))?n=p:n=JSON.parse(p));}let u=(a=e.headers.get("Prefer"))===null||a===void 0?void 0:a.match(/count=(exact|planned|estimated)/),d=(l=t.headers.get("content-range"))===null||l===void 0?void 0:l.split("/");u&&d&&d.length>1&&(i=parseInt(d[1])),e.isMaybeSingle&&Array.isArray(n)&&(n.length>1?(r={code:"PGRST116",details:`Results contain ${n.length} rows, application/vnd.pgrst.object+json requires 1 row`,hint:null,message:"JSON object requested, multiple (or no) rows returned"},n=null,i=null,s=406,o="Not Acceptable"):n.length===1?n=n[0]:n=null);}else {let u=await t.text();try{r=JSON.parse(u),Array.isArray(r)&&t.status===404&&(n=[],r=null,s=200,o="OK");}catch{t.status===404&&u===""?(s=204,o="No Content"):r={message:u};}if(r&&e.shouldThrowOnError)throw new Wl(r)}return {success:r===null,error:r,data:n,count:i,status:s,statusText:o}}returns(){return this}overrideTypes(){return this}},Eg=class extends Cg{select(t){let e=false,r=(t??"*").split("").map(n=>/\s/.test(n)&&!e?"":(n==='"'&&(e=!e),n)).join("");return this.url.searchParams.set("select",r),this.headers.append("Prefer","return=representation"),this}order(t,{ascending:e=true,nullsFirst:r,foreignTable:n,referencedTable:i=n}={}){let s=i?`${i}.order`:"order",o=this.url.searchParams.get(s);return this.url.searchParams.set(s,`${o?`${o},`:""}${t}.${e?"asc":"desc"}${r===void 0?"":r?".nullsfirst":".nullslast"}`),this}limit(t,{foreignTable:e,referencedTable:r=e}={}){let n=typeof r>"u"?"limit":`${r}.limit`;return this.url.searchParams.set(n,`${t}`),this}range(t,e,{foreignTable:r,referencedTable:n=r}={}){let i=typeof n>"u"?"offset":`${n}.offset`,s=typeof n>"u"?"limit":`${n}.limit`;return this.url.searchParams.set(i,`${t}`),this.url.searchParams.set(s,`${e-t+1}`),this}abortSignal(t){return this.signal=t,this}single(){return this.headers.set("Accept","application/vnd.pgrst.object+json"),this}maybeSingle(){return this.isMaybeSingle=true,this}csv(){return this.headers.set("Accept","text/csv"),this}geojson(){return this.headers.set("Accept","application/geo+json"),this}explain({analyze:t=false,verbose:e=false,settings:r=false,buffers:n=false,wal:i=false,format:s="text"}={}){var o;let a=[t?"analyze":null,e?"verbose":null,r?"settings":null,n?"buffers":null,i?"wal":null].filter(Boolean).join("|"),l=(o=this.headers.get("Accept"))!==null&&o!==void 0?o:"application/json";return this.headers.set("Accept",`application/vnd.pgrst.plan+${s}; for="${l}"; options=${a};`),s==="json"?this:this}rollback(){return this.headers.append("Prefer","tx=rollback"),this}returns(){return this}maxAffected(t){return this.headers.append("Prefer","handling=strict"),this.headers.append("Prefer",`max-affected=${t}`),this}},Ml=new RegExp("[,()]"),Ht=class extends Eg{eq(t,e){return this.url.searchParams.append(t,`eq.${e}`),this}neq(t,e){return this.url.searchParams.append(t,`neq.${e}`),this}gt(t,e){return this.url.searchParams.append(t,`gt.${e}`),this}gte(t,e){return this.url.searchParams.append(t,`gte.${e}`),this}lt(t,e){return this.url.searchParams.append(t,`lt.${e}`),this}lte(t,e){return this.url.searchParams.append(t,`lte.${e}`),this}like(t,e){return this.url.searchParams.append(t,`like.${e}`),this}likeAllOf(t,e){return this.url.searchParams.append(t,`like(all).{${e.join(",")}}`),this}likeAnyOf(t,e){return this.url.searchParams.append(t,`like(any).{${e.join(",")}}`),this}ilike(t,e){return this.url.searchParams.append(t,`ilike.${e}`),this}ilikeAllOf(t,e){return this.url.searchParams.append(t,`ilike(all).{${e.join(",")}}`),this}ilikeAnyOf(t,e){return this.url.searchParams.append(t,`ilike(any).{${e.join(",")}}`),this}regexMatch(t,e){return this.url.searchParams.append(t,`match.${e}`),this}regexIMatch(t,e){return this.url.searchParams.append(t,`imatch.${e}`),this}is(t,e){return this.url.searchParams.append(t,`is.${e}`),this}isDistinct(t,e){return this.url.searchParams.append(t,`isdistinct.${e}`),this}in(t,e){let r=Array.from(new Set(e)).map(n=>typeof n=="string"&&Ml.test(n)?`"${n}"`:`${n}`).join(",");return this.url.searchParams.append(t,`in.(${r})`),this}notIn(t,e){let r=Array.from(new Set(e)).map(n=>typeof n=="string"&&Ml.test(n)?`"${n}"`:`${n}`).join(",");return this.url.searchParams.append(t,`not.in.(${r})`),this}contains(t,e){return typeof e=="string"?this.url.searchParams.append(t,`cs.${e}`):Array.isArray(e)?this.url.searchParams.append(t,`cs.{${e.join(",")}}`):this.url.searchParams.append(t,`cs.${JSON.stringify(e)}`),this}containedBy(t,e){return typeof e=="string"?this.url.searchParams.append(t,`cd.${e}`):Array.isArray(e)?this.url.searchParams.append(t,`cd.{${e.join(",")}}`):this.url.searchParams.append(t,`cd.${JSON.stringify(e)}`),this}rangeGt(t,e){return this.url.searchParams.append(t,`sr.${e}`),this}rangeGte(t,e){return this.url.searchParams.append(t,`nxl.${e}`),this}rangeLt(t,e){return this.url.searchParams.append(t,`sl.${e}`),this}rangeLte(t,e){return this.url.searchParams.append(t,`nxr.${e}`),this}rangeAdjacent(t,e){return this.url.searchParams.append(t,`adj.${e}`),this}overlaps(t,e){return typeof e=="string"?this.url.searchParams.append(t,`ov.${e}`):this.url.searchParams.append(t,`ov.{${e.join(",")}}`),this}textSearch(t,e,{config:r,type:n}={}){let i="";n==="plain"?i="pl":n==="phrase"?i="ph":n==="websearch"&&(i="w");let s=r===void 0?"":`(${r})`;return this.url.searchParams.append(t,`${i}fts${s}.${e}`),this}match(t){return Object.entries(t).filter(([e,r])=>r!==void 0).forEach(([e,r])=>{this.url.searchParams.append(e,`eq.${r}`);}),this}not(t,e,r){return this.url.searchParams.append(t,`not.${e}.${r}`),this}or(t,{foreignTable:e,referencedTable:r=e}={}){let n=r?`${r}.or`:"or";return this.url.searchParams.append(n,`(${t})`),this}filter(t,e,r){return this.url.searchParams.append(t,`${e}.${r}`),this}},Rg=class{constructor(t,{headers:e={},schema:r,fetch:n,urlLengthLimit:i=8e3,retry:s}){this.url=t,this.headers=new Headers(e),this.schema=r,this.fetch=n,this.urlLengthLimit=i,this.retry=s;}cloneRequestState(){return {url:new URL(this.url.toString()),headers:new Headers(this.headers)}}select(t,e){let{head:r=false,count:n}=e??{},i=r?"HEAD":"GET",s=false,o=(t??"*").split("").map(c=>/\s/.test(c)&&!s?"":(c==='"'&&(s=!s),c)).join(""),{url:a,headers:l}=this.cloneRequestState();return a.searchParams.set("select",o),n&&l.append("Prefer",`count=${n}`),new Ht({method:i,url:a,headers:l,schema:this.schema,fetch:this.fetch,urlLengthLimit:this.urlLengthLimit,retry:this.retry})}insert(t,{count:e,defaultToNull:r=true}={}){var n;let i="POST",{url:s,headers:o}=this.cloneRequestState();if(e&&o.append("Prefer",`count=${e}`),r||o.append("Prefer","missing=default"),Array.isArray(t)){let a=t.reduce((l,c)=>l.concat(Object.keys(c)),[]);if(a.length>0){let l=[...new Set(a)].map(c=>`"${c}"`);s.searchParams.set("columns",l.join(","));}}return new Ht({method:i,url:s,headers:o,schema:this.schema,body:t,fetch:(n=this.fetch)!==null&&n!==void 0?n:fetch,urlLengthLimit:this.urlLengthLimit,retry:this.retry})}upsert(t,{onConflict:e,ignoreDuplicates:r=false,count:n,defaultToNull:i=true}={}){var s;let o="POST",{url:a,headers:l}=this.cloneRequestState();if(l.append("Prefer",`resolution=${r?"ignore":"merge"}-duplicates`),e!==void 0&&a.searchParams.set("on_conflict",e),n&&l.append("Prefer",`count=${n}`),i||l.append("Prefer","missing=default"),Array.isArray(t)){let c=t.reduce((u,d)=>u.concat(Object.keys(d)),[]);if(c.length>0){let u=[...new Set(c)].map(d=>`"${d}"`);a.searchParams.set("columns",u.join(","));}}return new Ht({method:o,url:a,headers:l,schema:this.schema,body:t,fetch:(s=this.fetch)!==null&&s!==void 0?s:fetch,urlLengthLimit:this.urlLengthLimit,retry:this.retry})}update(t,{count:e}={}){var r;let n="PATCH",{url:i,headers:s}=this.cloneRequestState();return e&&s.append("Prefer",`count=${e}`),new Ht({method:n,url:i,headers:s,schema:this.schema,body:t,fetch:(r=this.fetch)!==null&&r!==void 0?r:fetch,urlLengthLimit:this.urlLengthLimit,retry:this.retry})}delete({count:t}={}){var e;let r="DELETE",{url:n,headers:i}=this.cloneRequestState();return t&&i.append("Prefer",`count=${t}`),new Ht({method:r,url:n,headers:i,schema:this.schema,fetch:(e=this.fetch)!==null&&e!==void 0?e:fetch,urlLengthLimit:this.urlLengthLimit,retry:this.retry})}};Bl=class Fl{constructor(e,{headers:r={},schema:n,fetch:i,timeout:s,urlLengthLimit:o=8e3,retry:a}={}){this.url=e,this.headers=new Headers(r),this.schemaName=n,this.urlLengthLimit=o;let l=i??globalThis.fetch;s!==void 0&&s>0?this.fetch=(c,u)=>{let d=new AbortController,p=setTimeout(()=>d.abort(),s),h=u?.signal;if(h){if(h.aborted)return clearTimeout(p),l(c,u);let f=()=>{clearTimeout(p),d.abort();};return h.addEventListener("abort",f,{once:true}),l(c,On(On({},u),{},{signal:d.signal})).finally(()=>{clearTimeout(p),h.removeEventListener("abort",f);})}return l(c,On(On({},u),{},{signal:d.signal})).finally(()=>clearTimeout(p))}:this.fetch=l,this.retry=a;}from(e){if(!e||typeof e!="string"||e.trim()==="")throw new Error("Invalid relation name: relation must be a non-empty string.");return new Rg(new URL(`${this.url}/${e}`),{headers:new Headers(this.headers),schema:this.schemaName,fetch:this.fetch,urlLengthLimit:this.urlLengthLimit,retry:this.retry})}schema(e){return new Fl(this.url,{headers:this.headers,schema:e,fetch:this.fetch,urlLengthLimit:this.urlLengthLimit,retry:this.retry})}rpc(e,r={},{head:n=false,get:i=false,count:s}={}){var o;let a,l=new URL(`${this.url}/rpc/${e}`),c,u=h=>h!==null&&typeof h=="object"&&(!Array.isArray(h)||h.some(u)),d=n&&Object.values(r).some(u);d?(a="POST",c=r):n||i?(a=n?"HEAD":"GET",Object.entries(r).filter(([h,f])=>f!==void 0).map(([h,f])=>[h,Array.isArray(f)?`{${f.join(",")}}`:`${f}`]).forEach(([h,f])=>{l.searchParams.append(h,f);})):(a="POST",c=r);let p=new Headers(this.headers);return d?p.set("Prefer",s?`count=${s},return=minimal`:"return=minimal"):s&&p.set("Prefer",`count=${s}`),new Ht({method:a,url:l,headers:p,schema:this.schemaName,body:c,fetch:(o=this.fetch)!==null&&o!==void 0?o:fetch,urlLengthLimit:this.urlLengthLimit,retry:this.retry})}};});var ws,ys,ks=R(()=>{ws=class{constructor(){}static detectEnvironment(){var e;if(typeof WebSocket<"u")return {type:"native",constructor:WebSocket};if(typeof globalThis<"u"&&typeof globalThis.WebSocket<"u")return {type:"native",constructor:globalThis.WebSocket};if(typeof global<"u"&&typeof global.WebSocket<"u")return {type:"native",constructor:global.WebSocket};if(typeof globalThis<"u"&&typeof globalThis.WebSocketPair<"u"&&typeof globalThis.WebSocket>"u")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<"u"&&globalThis.EdgeRuntime||typeof navigator<"u"&&(!((e=navigator.userAgent)===null||e===void 0)&&e.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 r=globalThis.process;if(r){let n=r.versions;if(n&&n.node){let i=n.node,s=parseInt(i.replace(/^v/,"").split(".")[0]);return s>=22?typeof globalThis.WebSocket<"u"?{type:"native",constructor:globalThis.WebSocket}:{type:"unsupported",error:`Node.js ${s} detected but native WebSocket not found.`,workaround:"Provide a WebSocket implementation via the transport option."}:{type:"unsupported",error:`Node.js ${s} detected without native WebSocket support.`,workaround:`For Node.js < 22, install "ws" package and provide it via the transport option:
8
8
  import ws from "ws"
9
9
  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 e=this.detectEnvironment();if(e.constructor)return e.constructor;let r=e.error||"WebSocket not supported in this environment.";throw e.workaround&&(r+=`
10
10
 
11
- Suggested solution: ${e.workaround}`),new Error(r)}static isWebSocketSupported(){try{let e=this.detectEnvironment();return e.type==="native"||e.type==="ws"}catch{return false}}},ys=ws;});var ql,zl=R(()=>{ql="2.103.2";});var Jl,Kl,bs,Vl,Gl,Yl,ye,$n,Er,Rr=R(()=>{zl();Jl=`realtime-js/${ql}`,Kl="1.0.0",bs="2.0.0",Vl=bs,Gl=1e4,Yl=100,ye={closed:"closed",errored:"errored",joined:"joined",joining:"joining",leaving:"leaving"},$n={close:"phx_close",error:"phx_error",join:"phx_join",reply:"phx_reply",leave:"phx_leave",access_token:"access_token"},Er={connecting:"connecting",open:"open",closing:"closing",closed:"closed"};});var xr,Xl=R(()=>{xr=class{constructor(e){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=e??[];}encode(e,r){if(e.event===this.BROADCAST_EVENT&&!(e.payload instanceof ArrayBuffer)&&typeof e.payload.event=="string")return r(this._binaryEncodeUserBroadcastPush(e));let n=[e.join_ref,e.ref,e.topic,e.event,e.payload];return r(JSON.stringify(n))}_binaryEncodeUserBroadcastPush(e){var r;return this._isArrayBuffer((r=e.payload)===null||r===void 0?void 0:r.payload)?this._encodeBinaryUserBroadcastPush(e):this._encodeJsonUserBroadcastPush(e)}_encodeBinaryUserBroadcastPush(e){var r,n;let i=(n=(r=e.payload)===null||r===void 0?void 0:r.payload)!==null&&n!==void 0?n:new ArrayBuffer(0);return this._encodeUserBroadcastPush(e,this.BINARY_ENCODING,i)}_encodeJsonUserBroadcastPush(e){var r,n;let i=(n=(r=e.payload)===null||r===void 0?void 0:r.payload)!==null&&n!==void 0?n:{},o=new TextEncoder().encode(JSON.stringify(i)).buffer;return this._encodeUserBroadcastPush(e,this.JSON_ENCODING,o)}_encodeUserBroadcastPush(e,r,n){var i,s;let o=e.topic,a=(i=e.ref)!==null&&i!==void 0?i:"",l=(s=e.join_ref)!==null&&s!==void 0?s:"",c=e.payload.event,u=this.allowedMetadataKeys?this._pick(e.payload,this.allowedMetadataKeys):{},d=Object.keys(u).length===0?"":JSON.stringify(u);if(l.length>255)throw new Error(`joinRef length ${l.length} exceeds maximum of 255`);if(a.length>255)throw new Error(`ref length ${a.length} exceeds maximum of 255`);if(o.length>255)throw new Error(`topic length ${o.length} exceeds maximum of 255`);if(c.length>255)throw new Error(`userEvent length ${c.length} exceeds maximum of 255`);if(d.length>255)throw new Error(`metadata length ${d.length} exceeds maximum of 255`);let p=this.USER_BROADCAST_PUSH_META_LENGTH+l.length+a.length+o.length+c.length+d.length,h=new ArrayBuffer(this.HEADER_LENGTH+p),f=new DataView(h),m=0;f.setUint8(m++,this.KINDS.userBroadcastPush),f.setUint8(m++,l.length),f.setUint8(m++,a.length),f.setUint8(m++,o.length),f.setUint8(m++,c.length),f.setUint8(m++,d.length),f.setUint8(m++,r),Array.from(l,b=>f.setUint8(m++,b.charCodeAt(0))),Array.from(a,b=>f.setUint8(m++,b.charCodeAt(0))),Array.from(o,b=>f.setUint8(m++,b.charCodeAt(0))),Array.from(c,b=>f.setUint8(m++,b.charCodeAt(0))),Array.from(d,b=>f.setUint8(m++,b.charCodeAt(0)));var _=new Uint8Array(h.byteLength+n.byteLength);return _.set(new Uint8Array(h),0),_.set(new Uint8Array(n),h.byteLength),_.buffer}decode(e,r){if(this._isArrayBuffer(e)){let n=this._binaryDecode(e);return r(n)}if(typeof e=="string"){let n=JSON.parse(e),[i,s,o,a,l]=n;return r({join_ref:i,ref:s,topic:o,event:a,payload:l})}return r({})}_binaryDecode(e){let r=new DataView(e),n=r.getUint8(0),i=new TextDecoder;if(n===this.KINDS.userBroadcast)return this._decodeUserBroadcast(e,r,i)}_decodeUserBroadcast(e,r,n){let i=r.getUint8(1),s=r.getUint8(2),o=r.getUint8(3),a=r.getUint8(4),l=this.HEADER_LENGTH+4,c=n.decode(e.slice(l,l+i));l=l+i;let u=n.decode(e.slice(l,l+s));l=l+s;let d=n.decode(e.slice(l,l+o));l=l+o;let p=e.slice(l,e.byteLength),h=a===this.JSON_ENCODING?JSON.parse(n.decode(p)):p,f={type:this.BROADCAST_EVENT,event:u,payload:h};return o>0&&(f.meta=JSON.parse(d)),{join_ref:null,ref:null,topic:c,event:this.BROADCAST_EVENT,payload:f}}_isArrayBuffer(e){var r;return e instanceof ArrayBuffer||((r=e?.constructor)===null||r===void 0?void 0:r.name)==="ArrayBuffer"}_pick(e,r){return !e||typeof e!="object"?{}:Object.fromEntries(Object.entries(e).filter(([n])=>r.includes(n)))}};});var N,Ss,Ag,Zl,vs,Ig,Og,$g,Ng,jg,Nn,jn=R(()=>{(function(t){t.abstime="abstime",t.bool="bool",t.date="date",t.daterange="daterange",t.float4="float4",t.float8="float8",t.int2="int2",t.int4="int4",t.int4range="int4range",t.int8="int8",t.int8range="int8range",t.json="json",t.jsonb="jsonb",t.money="money",t.numeric="numeric",t.oid="oid",t.reltime="reltime",t.text="text",t.time="time",t.timestamp="timestamp",t.timestamptz="timestamptz",t.timetz="timetz",t.tsrange="tsrange",t.tstzrange="tstzrange";})(N||(N={}));Ss=(t,e,r={})=>{var n;let i=(n=r.skipTypes)!==null&&n!==void 0?n:[];return e?Object.keys(e).reduce((s,o)=>(s[o]=Ag(o,t,e,i),s),{}):{}},Ag=(t,e,r,n)=>{let i=e.find(a=>a.name===t),s=i?.type,o=r[t];return s&&!n.includes(s)?Zl(s,o):vs(o)},Zl=(t,e)=>{if(t.charAt(0)==="_"){let r=t.slice(1,t.length);return Ng(e,r)}switch(t){case N.bool:return Ig(e);case N.float4:case N.float8:case N.int2:case N.int4:case N.int8:case N.numeric:case N.oid:return Og(e);case N.json:case N.jsonb:return $g(e);case N.timestamp:return jg(e);case N.abstime:case N.date:case N.daterange:case N.int4range:case N.int8range:case N.money:case N.reltime:case N.text:case N.time:case N.timestamptz:case N.timetz:case N.tsrange:case N.tstzrange:return vs(e);default:return vs(e)}},vs=t=>t,Ig=t=>{switch(t){case "t":return true;case "f":return false;default:return t}},Og=t=>{if(typeof t=="string"){let e=parseFloat(t);if(!Number.isNaN(e))return e}return t},$g=t=>{if(typeof t=="string")try{return JSON.parse(t)}catch{return t}return t},Ng=(t,e)=>{if(typeof t!="string")return t;let r=t.length-1,n=t[r];if(t[0]==="{"&&n==="}"){let s,o=t.slice(1,r);try{s=JSON.parse("["+o+"]");}catch{s=o?o.split(","):[];}return s.map(a=>Zl(e,a))}return t},jg=t=>typeof t=="string"?t.replace(" ","T"):t,Nn=t=>{let e=new URL(t);return e.protocol=e.protocol.replace(/^ws/i,"http"),e.pathname=e.pathname.replace(/\/+$/,"").replace(/\/socket\/websocket$/i,"").replace(/\/socket$/i,"").replace(/\/websocket$/i,""),e.pathname===""||e.pathname==="/"?e.pathname="/api/broadcast":e.pathname=e.pathname+"/api/broadcast",e.href};});var Tr,Mg,zt,ke,Lg,Ug,Wg,be,Q,$e,Cs,Bg,Es,Dn,Ql,Fg,Ln,Hg,qt,ec,Mn,tc,Rs=R(()=>{Tr=t=>typeof t=="function"?t:function(){return t},Mg=typeof self<"u"?self:null,zt=typeof window<"u"?window:null,ke=Mg||zt||globalThis,Lg="2.0.0",Ug=1e4,Wg=1e3,be={connecting:0,open:1,closing:2,closed:3},Q={closed:"closed",errored:"errored",joined:"joined",joining:"joining",leaving:"leaving"},$e={close:"phx_close",error:"phx_error",join:"phx_join",reply:"phx_reply",leave:"phx_leave"},Cs={longpoll:"longpoll",websocket:"websocket"},Bg={complete:4},Es="base64url.bearer.phx.",Dn=class{constructor(t,e,r,n){this.channel=t,this.event=e,this.payload=r||function(){return {}},this.receivedResp=null,this.timeout=n,this.timeoutTimer=null,this.recHooks=[],this.sent=false,this.ref=void 0;}resend(t){this.timeout=t,this.reset(),this.send();}send(){this.hasReceived("timeout")||(this.startTimeout(),this.sent=true,this.channel.socket.push({topic:this.channel.topic,event:this.event,payload:this.payload(),ref:this.ref,join_ref:this.channel.joinRef()}));}receive(t,e){return this.hasReceived(t)&&e(this.receivedResp.response),this.recHooks.push({status:t,callback:e}),this}reset(){this.cancelRefEvent(),this.ref=null,this.refEvent=null,this.receivedResp=null,this.sent=false;}destroy(){this.cancelRefEvent(),this.cancelTimeout();}matchReceive({status:t,response:e,_ref:r}){this.recHooks.filter(n=>n.status===t).forEach(n=>n.callback(e));}cancelRefEvent(){this.refEvent&&this.channel.off(this.refEvent);}cancelTimeout(){clearTimeout(this.timeoutTimer),this.timeoutTimer=null;}startTimeout(){this.timeoutTimer&&this.cancelTimeout(),this.ref=this.channel.socket.makeRef(),this.refEvent=this.channel.replyEventName(this.ref),this.channel.on(this.refEvent,t=>{this.cancelRefEvent(),this.cancelTimeout(),this.receivedResp=t,this.matchReceive(t);}),this.timeoutTimer=setTimeout(()=>{this.trigger("timeout",{});},this.timeout);}hasReceived(t){return this.receivedResp&&this.receivedResp.status===t}trigger(t,e){this.channel.trigger(this.refEvent,{status:t,response:e});}},Ql=class{constructor(t,e){this.callback=t,this.timerCalc=e,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));}},Fg=class{constructor(t,e,r){this.state=Q.closed,this.topic=t,this.params=Tr(e||{}),this.socket=r,this.bindings=[],this.bindingRef=0,this.timeout=this.socket.timeout,this.joinedOnce=false,this.joinPush=new Dn(this,$e.join,this.params,this.timeout),this.pushBuffer=[],this.stateChangeRefs=[],this.rejoinTimer=new Ql(()=>{this.socket.isConnected()&&this.rejoin();},this.socket.rejoinAfterMs),this.stateChangeRefs.push(this.socket.onError(()=>this.rejoinTimer.reset())),this.stateChangeRefs.push(this.socket.onOpen(()=>{this.rejoinTimer.reset(),this.isErrored()&&this.rejoin();})),this.joinPush.receive("ok",()=>{this.state=Q.joined,this.rejoinTimer.reset(),this.pushBuffer.forEach(n=>n.send()),this.pushBuffer=[];}),this.joinPush.receive("error",n=>{this.state=Q.errored,this.socket.hasLogger()&&this.socket.log("channel",`error ${this.topic}`,n),this.socket.isConnected()&&this.rejoinTimer.scheduleTimeout();}),this.onClose(()=>{this.rejoinTimer.reset(),this.socket.hasLogger()&&this.socket.log("channel",`close ${this.topic}`),this.state=Q.closed,this.socket.remove(this);}),this.onError(n=>{this.socket.hasLogger()&&this.socket.log("channel",`error ${this.topic}`,n),this.isJoining()&&this.joinPush.reset(),this.state=Q.errored,this.socket.isConnected()&&this.rejoinTimer.scheduleTimeout();}),this.joinPush.receive("timeout",()=>{this.socket.hasLogger()&&this.socket.log("channel",`timeout ${this.topic}`,this.joinPush.timeout),new Dn(this,$e.leave,Tr({}),this.timeout).send(),this.state=Q.errored,this.joinPush.reset(),this.socket.isConnected()&&this.rejoinTimer.scheduleTimeout();}),this.on($e.reply,(n,i)=>{this.trigger(this.replyEventName(i),n);});}join(t=this.timeout){if(this.joinedOnce)throw new Error("tried to join multiple times. 'join' can only be called a single time per channel instance");return this.timeout=t,this.joinedOnce=true,this.rejoin(),this.joinPush}teardown(){this.pushBuffer.forEach(t=>t.destroy()),this.pushBuffer=[],this.rejoinTimer.reset(),this.joinPush.destroy(),this.state=Q.closed,this.bindings=[];}onClose(t){this.on($e.close,t);}onError(t){return this.on($e.error,e=>t(e))}on(t,e){let r=this.bindingRef++;return this.bindings.push({event:t,ref:r,callback:e}),r}off(t,e){this.bindings=this.bindings.filter(r=>!(r.event===t&&(typeof e>"u"||e===r.ref)));}canPush(){return this.socket.isConnected()&&this.isJoined()}push(t,e,r=this.timeout){if(e=e||{},!this.joinedOnce)throw new Error(`tried to push '${t}' to '${this.topic}' before joining. Use channel.join() before pushing events`);let n=new Dn(this,t,function(){return e},r);return this.canPush()?n.send():(n.startTimeout(),this.pushBuffer.push(n)),n}leave(t=this.timeout){this.rejoinTimer.reset(),this.joinPush.cancelTimeout(),this.state=Q.leaving;let e=()=>{this.socket.hasLogger()&&this.socket.log("channel",`leave ${this.topic}`),this.trigger($e.close,"leave");},r=new Dn(this,$e.leave,Tr({}),t);return r.receive("ok",()=>e()).receive("timeout",()=>e()),r.send(),this.canPush()||r.trigger("ok",{}),r}onMessage(t,e,r){return e}filterBindings(t,e,r){return true}isMember(t,e,r,n){return this.topic!==t?false:n&&n!==this.joinRef()?(this.socket.hasLogger()&&this.socket.log("channel","dropping outdated message",{topic:t,event:e,payload:r,joinRef:n}),false):true}joinRef(){return this.joinPush.ref}rejoin(t=this.timeout){this.isLeaving()||(this.socket.leaveOpenTopic(this.topic),this.state=Q.joining,this.joinPush.resend(t));}trigger(t,e,r,n){let i=this.onMessage(t,e,r,n);if(e&&!i)throw new Error("channel onMessage callbacks must return the payload, modified or unmodified");let s=this.bindings.filter(o=>o.event===t&&this.filterBindings(o,e,r));for(let o=0;o<s.length;o++)s[o].callback(i,r,n||this.joinRef());}replyEventName(t){return `chan_reply_${t}`}isClosed(){return this.state===Q.closed}isErrored(){return this.state===Q.errored}isJoined(){return this.state===Q.joined}isJoining(){return this.state===Q.joining}isLeaving(){return this.state===Q.leaving}},Ln=class{static request(t,e,r,n,i,s,o){if(ke.XDomainRequest){let a=new ke.XDomainRequest;return this.xdomainRequest(a,t,e,n,i,s,o)}else if(ke.XMLHttpRequest){let a=new ke.XMLHttpRequest;return this.xhrRequest(a,t,e,r,n,i,s,o)}else {if(ke.fetch&&ke.AbortController)return this.fetchRequest(t,e,r,n,i,s,o);throw new Error("No suitable XMLHttpRequest implementation found")}}static fetchRequest(t,e,r,n,i,s,o){let a={method:t,headers:r,body:n},l=null;if(i){l=new AbortController;setTimeout(()=>l.abort(),i);a.signal=l.signal;}return ke.fetch(e,a).then(c=>c.text()).then(c=>this.parseJSON(c)).then(c=>o&&o(c)).catch(c=>{c.name==="AbortError"&&s?s():o&&o(null);}),l}static xdomainRequest(t,e,r,n,i,s,o){return t.timeout=i,t.open(e,r),t.onload=()=>{let a=this.parseJSON(t.responseText);o&&o(a);},s&&(t.ontimeout=s),t.onprogress=()=>{},t.send(n),t}static xhrRequest(t,e,r,n,i,s,o,a){t.open(e,r,true),t.timeout=s;for(let[l,c]of Object.entries(n))t.setRequestHeader(l,c);return t.onerror=()=>a&&a(null),t.onreadystatechange=()=>{if(t.readyState===Bg.complete&&a){let l=this.parseJSON(t.responseText);a(l);}},o&&(t.ontimeout=o),t.send(i),t}static parseJSON(t){if(!t||t==="")return null;try{return JSON.parse(t)}catch{return console&&console.log("failed to parse JSON response",t),null}}static serialize(t,e){let r=[];for(var n in t){if(!Object.prototype.hasOwnProperty.call(t,n))continue;let i=e?`${e}[${n}]`:n,s=t[n];typeof s=="object"?r.push(this.serialize(s,i)):r.push(encodeURIComponent(i)+"="+encodeURIComponent(s));}return r.join("&")}static appendParams(t,e){if(Object.keys(e).length===0)return t;let r=t.match(/\?/)?"&":"?";return `${t}${r}${this.serialize(e)}`}},Hg=t=>{let e="",r=new Uint8Array(t),n=r.byteLength;for(let i=0;i<n;i++)e+=String.fromCharCode(r[i]);return btoa(e)},qt=class{constructor(t,e){e&&e.length===2&&e[1].startsWith(Es)&&(this.authToken=atob(e[1].slice(Es.length))),this.endPoint=null,this.token=null,this.skipHeartbeat=true,this.reqs=new Set,this.awaitingBatchAck=false,this.currentBatch=null,this.currentBatchTimer=null,this.batchBuffer=[],this.onopen=function(){},this.onerror=function(){},this.onmessage=function(){},this.onclose=function(){},this.pollEndpoint=this.normalizeEndpoint(t),this.readyState=be.connecting,setTimeout(()=>this.poll(),0);}normalizeEndpoint(t){return t.replace("ws://","http://").replace("wss://","https://").replace(new RegExp("(.*)/"+Cs.websocket),"$1/"+Cs.longpoll)}endpointURL(){return Ln.appendParams(this.pollEndpoint,{token:this.token})}closeAndRetry(t,e,r){this.close(t,e,r),this.readyState=be.connecting;}ontimeout(){this.onerror("timeout"),this.closeAndRetry(1005,"timeout",false);}isActive(){return this.readyState===be.open||this.readyState===be.connecting}poll(){let t={Accept:"application/json"};this.authToken&&(t["X-Phoenix-AuthToken"]=this.authToken),this.ajax("GET",t,null,()=>this.ontimeout(),e=>{if(e){var{status:r,token:n,messages:i}=e;if(r===410&&this.token!==null){this.onerror(410),this.closeAndRetry(3410,"session_gone",false);return}this.token=n;}else r=0;switch(r){case 200:i.forEach(s=>{setTimeout(()=>this.onmessage({data:s}),0);}),this.poll();break;case 204:this.poll();break;case 410:this.readyState=be.open,this.onopen({}),this.poll();break;case 403:this.onerror(403),this.close(1008,"forbidden",false);break;case 0:case 500:this.onerror(500),this.closeAndRetry(1011,"internal server error",500);break;default:throw new Error(`unhandled poll status ${r}`)}});}send(t){typeof t!="string"&&(t=Hg(t)),this.currentBatch?this.currentBatch.push(t):this.awaitingBatchAck?this.batchBuffer.push(t):(this.currentBatch=[t],this.currentBatchTimer=setTimeout(()=>{this.batchSend(this.currentBatch),this.currentBatch=null;},0));}batchSend(t){this.awaitingBatchAck=true,this.ajax("POST",{"Content-Type":"application/x-ndjson"},t.join(`
12
- `),()=>this.onerror("timeout"),e=>{this.awaitingBatchAck=false,!e||e.status!==200?(this.onerror(e&&e.status),this.closeAndRetry(1011,"internal server error",false)):this.batchBuffer.length>0&&(this.batchSend(this.batchBuffer),this.batchBuffer=[]);});}close(t,e,r){for(let i of this.reqs)i.abort();this.readyState=be.closed;let n=Object.assign({code:1e3,reason:void 0,wasClean:true},{code:t,reason:e,wasClean:r});this.batchBuffer=[],clearTimeout(this.currentBatchTimer),this.currentBatchTimer=null,typeof CloseEvent<"u"?this.onclose(new CloseEvent("close",n)):this.onclose(n);}ajax(t,e,r,n,i){let s,o=()=>{this.reqs.delete(s),n();};s=Ln.request(t,this.endpointURL(),e,r,this.timeout,o,a=>{this.reqs.delete(s),this.isActive()&&i(a);}),this.reqs.add(s);}},ec=class Pr{constructor(e,r={}){let n=r.events||{state:"presence_state",diff:"presence_diff"};this.state={},this.pendingDiffs=[],this.channel=e,this.joinRef=null,this.caller={onJoin:function(){},onLeave:function(){},onSync:function(){}},this.channel.on(n.state,i=>{let{onJoin:s,onLeave:o,onSync:a}=this.caller;this.joinRef=this.channel.joinRef(),this.state=Pr.syncState(this.state,i,s,o),this.pendingDiffs.forEach(l=>{this.state=Pr.syncDiff(this.state,l,s,o);}),this.pendingDiffs=[],a();}),this.channel.on(n.diff,i=>{let{onJoin:s,onLeave:o,onSync:a}=this.caller;this.inPendingSyncState()?this.pendingDiffs.push(i):(this.state=Pr.syncDiff(this.state,i,s,o),a());});}onJoin(e){this.caller.onJoin=e;}onLeave(e){this.caller.onLeave=e;}onSync(e){this.caller.onSync=e;}list(e){return Pr.list(this.state,e)}inPendingSyncState(){return !this.joinRef||this.joinRef!==this.channel.joinRef()}static syncState(e,r,n,i){let s=this.clone(e),o={},a={};return this.map(s,(l,c)=>{r[l]||(a[l]=c);}),this.map(r,(l,c)=>{let u=s[l];if(u){let d=c.metas.map(m=>m.phx_ref),p=u.metas.map(m=>m.phx_ref),h=c.metas.filter(m=>p.indexOf(m.phx_ref)<0),f=u.metas.filter(m=>d.indexOf(m.phx_ref)<0);h.length>0&&(o[l]=c,o[l].metas=h),f.length>0&&(a[l]=this.clone(u),a[l].metas=f);}else o[l]=c;}),this.syncDiff(s,{joins:o,leaves:a},n,i)}static syncDiff(e,r,n,i){let{joins:s,leaves:o}=this.clone(r);return n||(n=function(){}),i||(i=function(){}),this.map(s,(a,l)=>{let c=e[a];if(e[a]=this.clone(l),c){let u=e[a].metas.map(p=>p.phx_ref),d=c.metas.filter(p=>u.indexOf(p.phx_ref)<0);e[a].metas.unshift(...d);}n(a,c,l);}),this.map(o,(a,l)=>{let c=e[a];if(!c)return;let u=l.metas.map(d=>d.phx_ref);c.metas=c.metas.filter(d=>u.indexOf(d.phx_ref)<0),i(a,c,l),c.metas.length===0&&delete e[a];}),e}static list(e,r){return r||(r=function(n,i){return i}),this.map(e,(n,i)=>r(n,i))}static map(e,r){return Object.getOwnPropertyNames(e).map(n=>r(n,e[n]))}static clone(e){return JSON.parse(JSON.stringify(e))}},Mn={HEADER_LENGTH:1,META_LENGTH:4,KINDS:{push:0,reply:1,broadcast:2},encode(t,e){if(t.payload.constructor===ArrayBuffer)return e(this.binaryEncode(t));{let r=[t.join_ref,t.ref,t.topic,t.event,t.payload];return e(JSON.stringify(r))}},decode(t,e){if(t.constructor===ArrayBuffer)return e(this.binaryDecode(t));{let[r,n,i,s,o]=JSON.parse(t);return e({join_ref:r,ref:n,topic:i,event:s,payload:o})}},binaryEncode(t){let{join_ref:e,ref:r,event:n,topic:i,payload:s}=t,o=this.META_LENGTH+e.length+r.length+i.length+n.length,a=new ArrayBuffer(this.HEADER_LENGTH+o),l=new DataView(a),c=0;l.setUint8(c++,this.KINDS.push),l.setUint8(c++,e.length),l.setUint8(c++,r.length),l.setUint8(c++,i.length),l.setUint8(c++,n.length),Array.from(e,d=>l.setUint8(c++,d.charCodeAt(0))),Array.from(r,d=>l.setUint8(c++,d.charCodeAt(0))),Array.from(i,d=>l.setUint8(c++,d.charCodeAt(0))),Array.from(n,d=>l.setUint8(c++,d.charCodeAt(0)));var u=new Uint8Array(a.byteLength+s.byteLength);return u.set(new Uint8Array(a),0),u.set(new Uint8Array(s),a.byteLength),u.buffer},binaryDecode(t){let e=new DataView(t),r=e.getUint8(0),n=new TextDecoder;switch(r){case this.KINDS.push:return this.decodePush(t,e,n);case this.KINDS.reply:return this.decodeReply(t,e,n);case this.KINDS.broadcast:return this.decodeBroadcast(t,e,n)}},decodePush(t,e,r){let n=e.getUint8(1),i=e.getUint8(2),s=e.getUint8(3),o=this.HEADER_LENGTH+this.META_LENGTH-1,a=r.decode(t.slice(o,o+n));o=o+n;let l=r.decode(t.slice(o,o+i));o=o+i;let c=r.decode(t.slice(o,o+s));o=o+s;let u=t.slice(o,t.byteLength);return {join_ref:a,ref:null,topic:l,event:c,payload:u}},decodeReply(t,e,r){let n=e.getUint8(1),i=e.getUint8(2),s=e.getUint8(3),o=e.getUint8(4),a=this.HEADER_LENGTH+this.META_LENGTH,l=r.decode(t.slice(a,a+n));a=a+n;let c=r.decode(t.slice(a,a+i));a=a+i;let u=r.decode(t.slice(a,a+s));a=a+s;let d=r.decode(t.slice(a,a+o));a=a+o;let p=t.slice(a,t.byteLength),h={status:d,response:p};return {join_ref:l,ref:c,topic:u,event:$e.reply,payload:h}},decodeBroadcast(t,e,r){let n=e.getUint8(1),i=e.getUint8(2),s=this.HEADER_LENGTH+2,o=r.decode(t.slice(s,s+n));s=s+n;let a=r.decode(t.slice(s,s+i));s=s+i;let l=t.slice(s,t.byteLength);return {join_ref:null,ref:null,topic:o,event:a,payload:l}}},tc=class{constructor(t,e={}){this.stateChangeCallbacks={open:[],close:[],error:[],message:[]},this.channels=[],this.sendBuffer=[],this.ref=0,this.fallbackRef=null,this.timeout=e.timeout||Ug,this.transport=e.transport||ke.WebSocket||qt,this.conn=void 0,this.primaryPassedHealthCheck=false,this.longPollFallbackMs=e.longPollFallbackMs,this.fallbackTimer=null,this.sessionStore=e.sessionStorage||ke&&ke.sessionStorage,this.establishedConnections=0,this.defaultEncoder=Mn.encode.bind(Mn),this.defaultDecoder=Mn.decode.bind(Mn),this.closeWasClean=true,this.disconnecting=false,this.binaryType=e.binaryType||"arraybuffer",this.connectClock=1,this.pageHidden=false,this.encode=void 0,this.decode=void 0,this.transport!==qt?(this.encode=e.encode||this.defaultEncoder,this.decode=e.decode||this.defaultDecoder):(this.encode=this.defaultEncoder,this.decode=this.defaultDecoder);let r=null;zt&&zt.addEventListener&&(zt.addEventListener("pagehide",n=>{this.conn&&(this.disconnect(),r=this.connectClock);}),zt.addEventListener("pageshow",n=>{r===this.connectClock&&(r=null,this.connect());}),zt.addEventListener("visibilitychange",()=>{document.visibilityState==="hidden"?this.pageHidden=true:(this.pageHidden=false,!this.isConnected()&&!this.closeWasClean&&this.teardown(()=>this.connect()));})),this.heartbeatIntervalMs=e.heartbeatIntervalMs||3e4,this.autoSendHeartbeat=e.autoSendHeartbeat??true,this.heartbeatCallback=e.heartbeatCallback??(()=>{}),this.rejoinAfterMs=n=>e.rejoinAfterMs?e.rejoinAfterMs(n):[1e3,2e3,5e3][n-1]||1e4,this.reconnectAfterMs=n=>e.reconnectAfterMs?e.reconnectAfterMs(n):[10,50,100,150,200,250,500,1e3,2e3][n-1]||5e3,this.logger=e.logger||null,!this.logger&&e.debug&&(this.logger=(n,i,s)=>{console.log(`${n}: ${i}`,s);}),this.longpollerTimeout=e.longpollerTimeout||2e4,this.params=Tr(e.params||{}),this.endPoint=`${t}/${Cs.websocket}`,this.vsn=e.vsn||Lg,this.heartbeatTimeoutTimer=null,this.heartbeatTimer=null,this.heartbeatSentAt=null,this.pendingHeartbeatRef=null,this.reconnectTimer=new Ql(()=>{if(this.pageHidden){this.log("Not reconnecting as page is hidden!"),this.teardown();return}this.teardown(async()=>{e.beforeReconnect&&await e.beforeReconnect(),this.connect();});},this.reconnectAfterMs),this.authToken=e.authToken;}getLongPollTransport(){return qt}replaceTransport(t){this.connectClock++,this.closeWasClean=true,clearTimeout(this.fallbackTimer),this.reconnectTimer.reset(),this.conn&&(this.conn.close(),this.conn=null),this.transport=t;}protocol(){return location.protocol.match(/^https/)?"wss":"ws"}endPointURL(){let t=Ln.appendParams(Ln.appendParams(this.endPoint,this.params()),{vsn:this.vsn});return t.charAt(0)!=="/"?t:t.charAt(1)==="/"?`${this.protocol()}:${t}`:`${this.protocol()}://${location.host}${t}`}disconnect(t,e,r){this.connectClock++,this.disconnecting=true,this.closeWasClean=true,clearTimeout(this.fallbackTimer),this.reconnectTimer.reset(),this.teardown(()=>{this.disconnecting=false,t&&t();},e,r);}connect(t){t&&(console&&console.log("passing params to connect is deprecated. Instead pass :params to the Socket constructor"),this.params=Tr(t)),!(this.conn&&!this.disconnecting)&&(this.longPollFallbackMs&&this.transport!==qt?this.connectWithFallback(qt,this.longPollFallbackMs):this.transportConnect());}log(t,e,r){this.logger&&this.logger(t,e,r);}hasLogger(){return this.logger!==null}onOpen(t){let e=this.makeRef();return this.stateChangeCallbacks.open.push([e,t]),e}onClose(t){let e=this.makeRef();return this.stateChangeCallbacks.close.push([e,t]),e}onError(t){let e=this.makeRef();return this.stateChangeCallbacks.error.push([e,t]),e}onMessage(t){let e=this.makeRef();return this.stateChangeCallbacks.message.push([e,t]),e}onHeartbeat(t){this.heartbeatCallback=t;}ping(t){if(!this.isConnected())return false;let e=this.makeRef(),r=Date.now();this.push({topic:"phoenix",event:"heartbeat",payload:{},ref:e});let n=this.onMessage(i=>{i.ref===e&&(this.off([n]),t(Date.now()-r));});return true}transportName(t){return t===qt?"LongPoll":t.name}transportConnect(){this.connectClock++,this.closeWasClean=false;let t;this.authToken&&(t=["phoenix",`${Es}${btoa(this.authToken).replace(/=/g,"")}`]),this.conn=new this.transport(this.endPointURL(),t),this.conn.binaryType=this.binaryType,this.conn.timeout=this.longpollerTimeout,this.conn.onopen=()=>this.onConnOpen(),this.conn.onerror=e=>this.onConnError(e),this.conn.onmessage=e=>this.onConnMessage(e),this.conn.onclose=e=>this.onConnClose(e);}getSession(t){return this.sessionStore&&this.sessionStore.getItem(t)}storeSession(t,e){this.sessionStore&&this.sessionStore.setItem(t,e);}connectWithFallback(t,e=2500){clearTimeout(this.fallbackTimer);let r=false,n=true,i,s,o=this.transportName(t),a=l=>{this.log("transport",`falling back to ${o}...`,l),this.off([i,s]),n=false,this.replaceTransport(t),this.transportConnect();};if(this.getSession(`phx:fallback:${o}`))return a("memorized");this.fallbackTimer=setTimeout(a,e),s=this.onError(l=>{this.log("transport","error",l),n&&!r&&(clearTimeout(this.fallbackTimer),a(l));}),this.fallbackRef&&this.off([this.fallbackRef]),this.fallbackRef=this.onOpen(()=>{if(r=true,!n){let l=this.transportName(t);return this.primaryPassedHealthCheck||this.storeSession(`phx:fallback:${l}`,"true"),this.log("transport",`established ${l} fallback`)}clearTimeout(this.fallbackTimer),this.fallbackTimer=setTimeout(a,e),this.ping(l=>{this.log("transport","connected to primary after",l),this.primaryPassedHealthCheck=true,clearTimeout(this.fallbackTimer);});}),this.transportConnect();}clearHeartbeats(){clearTimeout(this.heartbeatTimer),clearTimeout(this.heartbeatTimeoutTimer);}onConnOpen(){this.hasLogger()&&this.log("transport",`connected to ${this.endPointURL()}`),this.closeWasClean=false,this.disconnecting=false,this.establishedConnections++,this.flushSendBuffer(),this.reconnectTimer.reset(),this.autoSendHeartbeat&&this.resetHeartbeat(),this.triggerStateCallbacks("open");}heartbeatTimeout(){if(this.pendingHeartbeatRef){this.pendingHeartbeatRef=null,this.heartbeatSentAt=null,this.hasLogger()&&this.log("transport","heartbeat timeout. Attempting to re-establish connection");try{this.heartbeatCallback("timeout");}catch(t){this.log("error","error in heartbeat callback",t);}this.triggerChanError(),this.closeWasClean=false,this.teardown(()=>this.reconnectTimer.scheduleTimeout(),Wg,"heartbeat timeout");}}resetHeartbeat(){this.conn&&this.conn.skipHeartbeat||(this.pendingHeartbeatRef=null,this.clearHeartbeats(),this.heartbeatTimer=setTimeout(()=>this.sendHeartbeat(),this.heartbeatIntervalMs));}teardown(t,e,r){if(!this.conn)return t&&t();let n=this.conn;this.waitForBufferDone(n,()=>{e?n.close(e,r||""):n.close(),this.waitForSocketClosed(n,()=>{this.conn===n&&(this.conn.onopen=function(){},this.conn.onerror=function(){},this.conn.onmessage=function(){},this.conn.onclose=function(){},this.conn=null),t&&t();});});}waitForBufferDone(t,e,r=1){if(r===5||!t.bufferedAmount){e();return}setTimeout(()=>{this.waitForBufferDone(t,e,r+1);},150*r);}waitForSocketClosed(t,e,r=1){if(r===5||t.readyState===be.closed){e();return}setTimeout(()=>{this.waitForSocketClosed(t,e,r+1);},150*r);}onConnClose(t){this.conn&&(this.conn.onclose=()=>{}),this.hasLogger()&&this.log("transport","close",t),this.triggerChanError(),this.clearHeartbeats(),this.closeWasClean||this.reconnectTimer.scheduleTimeout(),this.triggerStateCallbacks("close",t);}onConnError(t){this.hasLogger()&&this.log("transport",t);let e=this.transport,r=this.establishedConnections;this.triggerStateCallbacks("error",t,e,r),(e===this.transport||r>0)&&this.triggerChanError();}triggerChanError(){this.channels.forEach(t=>{t.isErrored()||t.isLeaving()||t.isClosed()||t.trigger($e.error);});}connectionState(){switch(this.conn&&this.conn.readyState){case be.connecting:return "connecting";case be.open:return "open";case be.closing:return "closing";default:return "closed"}}isConnected(){return this.connectionState()==="open"}remove(t){this.off(t.stateChangeRefs),this.channels=this.channels.filter(e=>e!==t);}off(t){for(let e in this.stateChangeCallbacks)this.stateChangeCallbacks[e]=this.stateChangeCallbacks[e].filter(([r])=>t.indexOf(r)===-1);}channel(t,e={}){let r=new Fg(t,e,this);return this.channels.push(r),r}push(t){if(this.hasLogger()){let{topic:e,event:r,payload:n,ref:i,join_ref:s}=t;this.log("push",`${e} ${r} (${s}, ${i})`,n);}this.isConnected()?this.encode(t,e=>this.conn.send(e)):this.sendBuffer.push(()=>this.encode(t,e=>this.conn.send(e)));}makeRef(){let t=this.ref+1;return t===this.ref?this.ref=0:this.ref=t,this.ref.toString()}sendHeartbeat(){if(!this.isConnected()){try{this.heartbeatCallback("disconnected");}catch(t){this.log("error","error in heartbeat callback",t);}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(t){this.log("error","error in heartbeat callback",t);}this.heartbeatTimeoutTimer=setTimeout(()=>this.heartbeatTimeout(),this.heartbeatIntervalMs);}flushSendBuffer(){this.isConnected()&&this.sendBuffer.length>0&&(this.sendBuffer.forEach(t=>t()),this.sendBuffer=[]);}onConnMessage(t){this.decode(t.data,e=>{let{topic:r,event:n,payload:i,ref:s,join_ref:o}=e;if(s&&s===this.pendingHeartbeatRef){let a=this.heartbeatSentAt?Date.now()-this.heartbeatSentAt:void 0;this.clearHeartbeats();try{this.heartbeatCallback(i.status==="ok"?"ok":"error",a);}catch(l){this.log("error","error in heartbeat callback",l);}this.pendingHeartbeatRef=null,this.heartbeatSentAt=null,this.autoSendHeartbeat&&(this.heartbeatTimer=setTimeout(()=>this.sendHeartbeat(),this.heartbeatIntervalMs));}this.hasLogger()&&this.log("receive",`${i.status||""} ${r} ${n} ${s&&"("+s+")"||""}`.trim(),i);for(let a=0;a<this.channels.length;a++){let l=this.channels[a];l.isMember(r,n,i,o)&&l.trigger(n,i,s,o);}this.triggerStateCallbacks("message",e);});}triggerStateCallbacks(t,...e){try{this.stateChangeCallbacks[t].forEach(([r,n])=>{try{n(...e);}catch(i){this.log("error",`error in ${t} callback`,i);}});}catch(r){this.log("error",`error triggering ${t} callbacks`,r);}}leaveOpenTopic(t){let e=this.channels.find(r=>r.topic===t&&(r.isJoined()||r.isJoining()));e&&(this.hasLogger()&&this.log("transport",`leaving duplicate topic "${t}"`),e.leave());}};});function Un(t){return t.metas.map(e=>(e.presence_ref=e.phx_ref,delete e.phx_ref,delete e.phx_ref_prev,e))}function qg(t){return JSON.parse(JSON.stringify(t))}function zg(t){return t?.events&&{events:t.events}}function rc(t){return t?.metas?Un(t):[]}var Ar,nc=R(()=>{Rs();Ar=class t{constructor(e,r){let n=zg(r);this.presence=new ec(e.getChannel(),n),this.presence.onJoin((i,s,o)=>{let a=t.onJoinPayload(i,s,o);e.getChannel().trigger("presence",a);}),this.presence.onLeave((i,s,o)=>{let a=t.onLeavePayload(i,s,o);e.getChannel().trigger("presence",a);}),this.presence.onSync(()=>{e.getChannel().trigger("presence",{event:"sync"});});}get state(){return t.transformState(this.presence.state)}static transformState(e){return e=qg(e),Object.getOwnPropertyNames(e).reduce((r,n)=>{let i=e[n];return r[n]=Un(i),r},{})}static onJoinPayload(e,r,n){let i=rc(r),s=Un(n);return {event:"join",key:e,currentPresences:i,newPresences:s}}static onLeavePayload(e,r,n){let i=rc(r),s=Un(n);return {event:"leave",key:e,currentPresences:i,leftPresences:s}}};});var xs,Jt,Ps=R(()=>{nc();(function(t){t.SYNC="sync",t.JOIN="join",t.LEAVE="leave";})(xs||(xs={}));Jt=class{get state(){return this.presenceAdapter.state}constructor(e,r){this.channel=e,this.presenceAdapter=new Ar(this.channel.channelAdapter,r);}};});function Jg(t){return {config:Object.assign({broadcast:{ack:false,self:false},presence:{key:"",enabled:false},private:false},t.config)}}var Ir,ic=R(()=>{Rr();Ir=class{constructor(e,r,n){let i=Jg(n);this.channel=e.getSocket().channel(r,i),this.socket=e;}get state(){return this.channel.state}set state(e){this.channel.state=e;}get joinedOnce(){return this.channel.joinedOnce}get joinPush(){return this.channel.joinPush}get rejoinTimer(){return this.channel.rejoinTimer}on(e,r){return this.channel.on(e,r)}off(e,r){this.channel.off(e,r);}subscribe(e){return this.channel.join(e)}unsubscribe(e){return this.channel.leave(e)}teardown(){this.channel.teardown();}onClose(e){this.channel.onClose(e);}onError(e){return this.channel.onError(e)}push(e,r,n){let i;try{i=this.channel.push(e,r,n);}catch{throw `tried to push '${e}' to '${this.channel.topic}' before joining. Use channel.subscribe() before pushing events`}if(this.channel.pushBuffer.length>Yl){let s=this.channel.pushBuffer.shift();s.cancelTimeout(),this.socket.log("channel",`discarded push due to buffer overflow: ${s.event}`,s.payload());}return i}updateJoinPayload(e){let r=this.channel.joinPush.payload();this.channel.joinPush.payload=()=>Object.assign(Object.assign({},r),e);}canPush(){return this.socket.isConnected()&&this.state===ye.joined}isJoined(){return this.state===ye.joined}isJoining(){return this.state===ye.joining}isClosed(){return this.state===ye.closed}isLeaving(){return this.state===ye.leaving}updateFilterBindings(e){this.channel.filterBindings=e;}updatePayloadTransform(e){this.channel.onMessage=e;}getChannel(){return this.channel}};});var Ts,at,ve,Kt,As=R(()=>{Rr();Ps();jn();jn();ic();(function(t){t.ALL="*",t.INSERT="INSERT",t.UPDATE="UPDATE",t.DELETE="DELETE";})(Ts||(Ts={}));(function(t){t.BROADCAST="broadcast",t.PRESENCE="presence",t.POSTGRES_CHANGES="postgres_changes",t.SYSTEM="system";})(at||(at={}));(function(t){t.SUBSCRIBED="SUBSCRIBED",t.TIMED_OUT="TIMED_OUT",t.CLOSED="CLOSED",t.CHANNEL_ERROR="CHANNEL_ERROR";})(ve||(ve={}));Kt=class t{get state(){return this.channelAdapter.state}set state(e){this.channelAdapter.state=e;}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(e,r={config:{}},n){var i,s;if(this.topic=e,this.params=r,this.socket=n,this.bindings={},this.subTopic=e.replace(/^realtime:/i,""),this.params.config=Object.assign({broadcast:{ack:false,self:false},presence:{key:"",enabled:false},private:false},r.config),this.channelAdapter=new Ir(this.socket.socketAdapter,e,this.params),this.presence=new Jt(this),this._onClose(()=>{this.socket._remove(this);}),this._updateFilterTransform(),this.broadcastEndpointURL=Nn(this.socket.socketAdapter.endPointURL()),this.private=this.params.config.private||false,!this.private&&(!((s=(i=this.params.config)===null||i===void 0?void 0:i.broadcast)===null||s===void 0)&&s.replay))throw `tried to use replay on public channel '${this.topic}'. It must be a private channel.`}subscribe(e,r=this.timeout){var n,i,s;if(this.socket.isConnected()||this.socket.connect(),this.channelAdapter.isClosed()){let{config:{broadcast:o,presence:a,private:l}}=this.params,c=(i=(n=this.bindings.postgres_changes)===null||n===void 0?void 0:n.map(h=>h.filter))!==null&&i!==void 0?i:[],u=!!this.bindings[at.PRESENCE]&&this.bindings[at.PRESENCE].length>0||((s=this.params.config.presence)===null||s===void 0?void 0:s.enabled)===true,d={},p={broadcast:o,presence:Object.assign(Object.assign({},a),{enabled:u}),postgres_changes:c,private:l};this.socket.accessTokenValue&&(d.access_token=this.socket.accessTokenValue),this._onError(h=>{e?.(ve.CHANNEL_ERROR,h);}),this._onClose(()=>e?.(ve.CLOSED)),this.updateJoinPayload(Object.assign({config:p},d)),this._updateFilterMessage(),this.channelAdapter.subscribe(r).receive("ok",async({postgres_changes:h})=>{if(this.socket._isManualToken()||this.socket.setAuth(),h===void 0){e?.(ve.SUBSCRIBED);return}this._updatePostgresBindings(h,e);}).receive("error",h=>{this.state=ye.errored,e?.(ve.CHANNEL_ERROR,new Error(JSON.stringify(Object.values(h).join(", ")||"error")));}).receive("timeout",()=>{e?.(ve.TIMED_OUT);});}return this}_updatePostgresBindings(e,r){var n;let i=this.bindings.postgres_changes,s=(n=i?.length)!==null&&n!==void 0?n:0,o=[];for(let a=0;a<s;a++){let l=i[a],{filter:{event:c,schema:u,table:d,filter:p}}=l,h=e&&e[a];if(h&&h.event===c&&t.isFilterValueEqual(h.schema,u)&&t.isFilterValueEqual(h.table,d)&&t.isFilterValueEqual(h.filter,p))o.push(Object.assign(Object.assign({},l),{id:h.id}));else {this.unsubscribe(),this.state=ye.errored,r?.(ve.CHANNEL_ERROR,new Error("mismatch between server and client bindings for postgres changes"));return}}this.bindings.postgres_changes=o,this.state!=ye.errored&&r&&r(ve.SUBSCRIBED);}presenceState(){return this.presence.state}async track(e,r={}){return await this.send({type:"presence",event:"track",payload:e},r.timeout||this.timeout)}async untrack(e={}){return await this.send({type:"presence",event:"untrack"},e)}on(e,r,n){let i=this.channelAdapter.isJoined()||this.channelAdapter.isJoining(),s=e===at.PRESENCE||e===at.POSTGRES_CHANGES;if(i&&s)throw this.socket.log("channel",`cannot add \`${e}\` callbacks for ${this.topic} after \`subscribe()\`.`),new Error(`cannot add \`${e}\` callbacks for ${this.topic} after \`subscribe()\`.`);return this._on(e,r,n)}async httpSend(e,r,n={}){var i;if(r==null)return Promise.reject("Payload is required for httpSend()");let s={apikey:this.socket.apiKey?this.socket.apiKey:"","Content-Type":"application/json"};this.socket.accessTokenValue&&(s.Authorization=`Bearer ${this.socket.accessTokenValue}`);let o={method:"POST",headers:s,body:JSON.stringify({messages:[{topic:this.subTopic,event:e,payload:r,private:this.private}]})},a=await this._fetchWithTimeout(this.broadcastEndpointURL,o,(i=n.timeout)!==null&&i!==void 0?i:this.timeout);if(a.status===202)return {success:true};let l=a.statusText;try{let c=await a.json();l=c.error||c.message||l;}catch{}return Promise.reject(new Error(l))}async send(e,r={}){var n,i;if(!this.channelAdapter.canPush()&&e.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:s,payload:o}=e,a={apikey:this.socket.apiKey?this.socket.apiKey:"","Content-Type":"application/json"};this.socket.accessTokenValue&&(a.Authorization=`Bearer ${this.socket.accessTokenValue}`);let l={method:"POST",headers:a,body:JSON.stringify({messages:[{topic:this.subTopic,event:s,payload:o,private:this.private}]})};try{let c=await this._fetchWithTimeout(this.broadcastEndpointURL,l,(n=r.timeout)!==null&&n!==void 0?n:this.timeout);return await((i=c.body)===null||i===void 0?void 0:i.cancel()),c.ok?"ok":"error"}catch(c){return c.name==="AbortError"?"timed out":"error"}}else return new Promise(s=>{var o,a,l;let c=this.channelAdapter.push(e.type,e,r.timeout||this.timeout);e.type==="broadcast"&&!(!((l=(a=(o=this.params)===null||o===void 0?void 0:o.config)===null||a===void 0?void 0:a.broadcast)===null||l===void 0)&&l.ack)&&s("ok"),c.receive("ok",()=>s("ok")),c.receive("error",()=>s("error")),c.receive("timeout",()=>s("timed out"));})}updateJoinPayload(e){this.channelAdapter.updateJoinPayload(e);}async unsubscribe(e=this.timeout){return new Promise(r=>{this.channelAdapter.unsubscribe(e).receive("ok",()=>r("ok")).receive("timeout",()=>r("timed out")).receive("error",()=>r("error"));})}teardown(){this.channelAdapter.teardown();}async _fetchWithTimeout(e,r,n){let i=new AbortController,s=setTimeout(()=>i.abort(),n),o=await this.socket.fetch(e,Object.assign(Object.assign({},r),{signal:i.signal}));return clearTimeout(s),o}_on(e,r,n){let i=e.toLocaleLowerCase(),s=this.channelAdapter.on(e,n),o={type:i,filter:r,callback:n,ref:s};return this.bindings[i]?this.bindings[i].push(o):this.bindings[i]=[o],this._updateFilterMessage(),this}_onClose(e){this.channelAdapter.onClose(e);}_onError(e){this.channelAdapter.onError(e);}_updateFilterMessage(){this.channelAdapter.updateFilterBindings((e,r,n)=>{var i,s,o,a,l,c,u;let d=e.event.toLocaleLowerCase();if(this._notThisChannelEvent(d,n))return false;let p=(i=this.bindings[d])===null||i===void 0?void 0:i.find(h=>h.ref===e.ref);if(!p)return true;if(["broadcast","presence","postgres_changes"].includes(d))if("id"in p){let h=p.id,f=(s=p.filter)===null||s===void 0?void 0:s.event;return h&&((o=r.ids)===null||o===void 0?void 0:o.includes(h))&&(f==="*"||f?.toLocaleLowerCase()===((a=r.data)===null||a===void 0?void 0:a.type.toLocaleLowerCase()))}else {let h=(c=(l=p?.filter)===null||l===void 0?void 0:l.event)===null||c===void 0?void 0:c.toLocaleLowerCase();return h==="*"||h===((u=r?.event)===null||u===void 0?void 0:u.toLocaleLowerCase())}else return p.type.toLocaleLowerCase()===d});}_notThisChannelEvent(e,r){let{close:n,error:i,leave:s,join:o}=$n;return r&&[n,i,s,o].includes(e)&&r!==this.joinPush.ref}_updateFilterTransform(){this.channelAdapter.updatePayloadTransform((e,r,n)=>{if(typeof r=="object"&&"ids"in r){let i=r.data,{schema:s,table:o,commit_timestamp:a,type:l,errors:c}=i;return Object.assign(Object.assign({},{schema:s,table:o,commit_timestamp:a,eventType:l,new:{},old:{},errors:c}),this._getPayloadRecords(i))}return r});}copyBindings(e){if(this.joinedOnce)throw new Error("cannot copy bindings into joined channel");for(let r in e.bindings)for(let n of e.bindings[r])this._on(n.type,n.filter,n.callback);}static isFilterValueEqual(e,r){return (e??void 0)===(r??void 0)}_getPayloadRecords(e){let r={new:{},old:{}};return (e.type==="INSERT"||e.type==="UPDATE")&&(r.new=Ss(e.columns,e.record)),(e.type==="UPDATE"||e.type==="DELETE")&&(r.old=Ss(e.columns,e.old_record)),r}};});var Or,sc=R(()=>{Rs();Rr();Or=class{constructor(e,r){this.socket=new tc(e,r);}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(e){this.socket.heartbeatCallback=e;}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(e,r,n,i=1e4){return new Promise(s=>{setTimeout(()=>s("timeout"),i),this.socket.disconnect(()=>{e(),s("ok");},r,n);})}push(e){this.socket.push(e);}log(e,r,n){this.socket.log(e,r,n);}makeRef(){return this.socket.makeRef()}onOpen(e){this.socket.onOpen(e);}onClose(e){this.socket.onClose(e);}onError(e){this.socket.onError(e);}onMessage(e){this.socket.onMessage(e);}isConnected(){return this.socket.isConnected()}isConnecting(){return this.socket.connectionState()==Er.connecting}isDisconnecting(){return this.socket.connectionState()==Er.closing}connectionState(){return this.socket.connectionState()}endPointURL(){return this.socket.endPointURL()}sendHeartbeat(){this.socket.sendHeartbeat();}getSocket(){return this.socket}};});var Kg,Vg,Gg,Yg,Vt,oc=R(()=>{ks();Rr();Xl();jn();As();sc();Kg={HEARTBEAT_INTERVAL:25e3,RECONNECT_DELAY:10,HEARTBEAT_TIMEOUT_FALLBACK:100},Vg=[1e3,2e3,5e3,1e4],Gg=1e4,Yg=`
11
+ Suggested solution: ${e.workaround}`),new Error(r)}static isWebSocketSupported(){try{let e=this.detectEnvironment();return e.type==="native"||e.type==="ws"}catch{return false}}},ys=ws;});var ql,zl=R(()=>{ql="2.103.2";});var Jl,Kl,bs,Vl,Gl,Yl,ye,$n,Er,Rr=R(()=>{zl();Jl=`realtime-js/${ql}`,Kl="1.0.0",bs="2.0.0",Vl=bs,Gl=1e4,Yl=100,ye={closed:"closed",errored:"errored",joined:"joined",joining:"joining",leaving:"leaving"},$n={close:"phx_close",error:"phx_error",join:"phx_join",reply:"phx_reply",leave:"phx_leave",access_token:"access_token"},Er={connecting:"connecting",open:"open",closing:"closing",closed:"closed"};});var xr,Xl=R(()=>{xr=class{constructor(e){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=e??[];}encode(e,r){if(e.event===this.BROADCAST_EVENT&&!(e.payload instanceof ArrayBuffer)&&typeof e.payload.event=="string")return r(this._binaryEncodeUserBroadcastPush(e));let n=[e.join_ref,e.ref,e.topic,e.event,e.payload];return r(JSON.stringify(n))}_binaryEncodeUserBroadcastPush(e){var r;return this._isArrayBuffer((r=e.payload)===null||r===void 0?void 0:r.payload)?this._encodeBinaryUserBroadcastPush(e):this._encodeJsonUserBroadcastPush(e)}_encodeBinaryUserBroadcastPush(e){var r,n;let i=(n=(r=e.payload)===null||r===void 0?void 0:r.payload)!==null&&n!==void 0?n:new ArrayBuffer(0);return this._encodeUserBroadcastPush(e,this.BINARY_ENCODING,i)}_encodeJsonUserBroadcastPush(e){var r,n;let i=(n=(r=e.payload)===null||r===void 0?void 0:r.payload)!==null&&n!==void 0?n:{},o=new TextEncoder().encode(JSON.stringify(i)).buffer;return this._encodeUserBroadcastPush(e,this.JSON_ENCODING,o)}_encodeUserBroadcastPush(e,r,n){var i,s;let o=e.topic,a=(i=e.ref)!==null&&i!==void 0?i:"",l=(s=e.join_ref)!==null&&s!==void 0?s:"",c=e.payload.event,u=this.allowedMetadataKeys?this._pick(e.payload,this.allowedMetadataKeys):{},d=Object.keys(u).length===0?"":JSON.stringify(u);if(l.length>255)throw new Error(`joinRef length ${l.length} exceeds maximum of 255`);if(a.length>255)throw new Error(`ref length ${a.length} exceeds maximum of 255`);if(o.length>255)throw new Error(`topic length ${o.length} exceeds maximum of 255`);if(c.length>255)throw new Error(`userEvent length ${c.length} exceeds maximum of 255`);if(d.length>255)throw new Error(`metadata length ${d.length} exceeds maximum of 255`);let p=this.USER_BROADCAST_PUSH_META_LENGTH+l.length+a.length+o.length+c.length+d.length,h=new ArrayBuffer(this.HEADER_LENGTH+p),f=new DataView(h),m=0;f.setUint8(m++,this.KINDS.userBroadcastPush),f.setUint8(m++,l.length),f.setUint8(m++,a.length),f.setUint8(m++,o.length),f.setUint8(m++,c.length),f.setUint8(m++,d.length),f.setUint8(m++,r),Array.from(l,b=>f.setUint8(m++,b.charCodeAt(0))),Array.from(a,b=>f.setUint8(m++,b.charCodeAt(0))),Array.from(o,b=>f.setUint8(m++,b.charCodeAt(0))),Array.from(c,b=>f.setUint8(m++,b.charCodeAt(0))),Array.from(d,b=>f.setUint8(m++,b.charCodeAt(0)));var _=new Uint8Array(h.byteLength+n.byteLength);return _.set(new Uint8Array(h),0),_.set(new Uint8Array(n),h.byteLength),_.buffer}decode(e,r){if(this._isArrayBuffer(e)){let n=this._binaryDecode(e);return r(n)}if(typeof e=="string"){let n=JSON.parse(e),[i,s,o,a,l]=n;return r({join_ref:i,ref:s,topic:o,event:a,payload:l})}return r({})}_binaryDecode(e){let r=new DataView(e),n=r.getUint8(0),i=new TextDecoder;if(n===this.KINDS.userBroadcast)return this._decodeUserBroadcast(e,r,i)}_decodeUserBroadcast(e,r,n){let i=r.getUint8(1),s=r.getUint8(2),o=r.getUint8(3),a=r.getUint8(4),l=this.HEADER_LENGTH+4,c=n.decode(e.slice(l,l+i));l=l+i;let u=n.decode(e.slice(l,l+s));l=l+s;let d=n.decode(e.slice(l,l+o));l=l+o;let p=e.slice(l,e.byteLength),h=a===this.JSON_ENCODING?JSON.parse(n.decode(p)):p,f={type:this.BROADCAST_EVENT,event:u,payload:h};return o>0&&(f.meta=JSON.parse(d)),{join_ref:null,ref:null,topic:c,event:this.BROADCAST_EVENT,payload:f}}_isArrayBuffer(e){var r;return e instanceof ArrayBuffer||((r=e?.constructor)===null||r===void 0?void 0:r.name)==="ArrayBuffer"}_pick(e,r){return !e||typeof e!="object"?{}:Object.fromEntries(Object.entries(e).filter(([n])=>r.includes(n)))}};});var N,Ss,Ag,Zl,vs,Ig,Og,$g,Ng,Dg,Nn,Dn=R(()=>{(function(t){t.abstime="abstime",t.bool="bool",t.date="date",t.daterange="daterange",t.float4="float4",t.float8="float8",t.int2="int2",t.int4="int4",t.int4range="int4range",t.int8="int8",t.int8range="int8range",t.json="json",t.jsonb="jsonb",t.money="money",t.numeric="numeric",t.oid="oid",t.reltime="reltime",t.text="text",t.time="time",t.timestamp="timestamp",t.timestamptz="timestamptz",t.timetz="timetz",t.tsrange="tsrange",t.tstzrange="tstzrange";})(N||(N={}));Ss=(t,e,r={})=>{var n;let i=(n=r.skipTypes)!==null&&n!==void 0?n:[];return e?Object.keys(e).reduce((s,o)=>(s[o]=Ag(o,t,e,i),s),{}):{}},Ag=(t,e,r,n)=>{let i=e.find(a=>a.name===t),s=i?.type,o=r[t];return s&&!n.includes(s)?Zl(s,o):vs(o)},Zl=(t,e)=>{if(t.charAt(0)==="_"){let r=t.slice(1,t.length);return Ng(e,r)}switch(t){case N.bool:return Ig(e);case N.float4:case N.float8:case N.int2:case N.int4:case N.int8:case N.numeric:case N.oid:return Og(e);case N.json:case N.jsonb:return $g(e);case N.timestamp:return Dg(e);case N.abstime:case N.date:case N.daterange:case N.int4range:case N.int8range:case N.money:case N.reltime:case N.text:case N.time:case N.timestamptz:case N.timetz:case N.tsrange:case N.tstzrange:return vs(e);default:return vs(e)}},vs=t=>t,Ig=t=>{switch(t){case "t":return true;case "f":return false;default:return t}},Og=t=>{if(typeof t=="string"){let e=parseFloat(t);if(!Number.isNaN(e))return e}return t},$g=t=>{if(typeof t=="string")try{return JSON.parse(t)}catch{return t}return t},Ng=(t,e)=>{if(typeof t!="string")return t;let r=t.length-1,n=t[r];if(t[0]==="{"&&n==="}"){let s,o=t.slice(1,r);try{s=JSON.parse("["+o+"]");}catch{s=o?o.split(","):[];}return s.map(a=>Zl(e,a))}return t},Dg=t=>typeof t=="string"?t.replace(" ","T"):t,Nn=t=>{let e=new URL(t);return e.protocol=e.protocol.replace(/^ws/i,"http"),e.pathname=e.pathname.replace(/\/+$/,"").replace(/\/socket\/websocket$/i,"").replace(/\/socket$/i,"").replace(/\/websocket$/i,""),e.pathname===""||e.pathname==="/"?e.pathname="/api/broadcast":e.pathname=e.pathname+"/api/broadcast",e.href};});var Tr,Mg,zt,ke,Lg,Ug,Wg,be,Q,$e,Cs,Bg,Es,jn,Ql,Fg,Ln,Hg,qt,ec,Mn,tc,Rs=R(()=>{Tr=t=>typeof t=="function"?t:function(){return t},Mg=typeof self<"u"?self:null,zt=typeof window<"u"?window:null,ke=Mg||zt||globalThis,Lg="2.0.0",Ug=1e4,Wg=1e3,be={connecting:0,open:1,closing:2,closed:3},Q={closed:"closed",errored:"errored",joined:"joined",joining:"joining",leaving:"leaving"},$e={close:"phx_close",error:"phx_error",join:"phx_join",reply:"phx_reply",leave:"phx_leave"},Cs={longpoll:"longpoll",websocket:"websocket"},Bg={complete:4},Es="base64url.bearer.phx.",jn=class{constructor(t,e,r,n){this.channel=t,this.event=e,this.payload=r||function(){return {}},this.receivedResp=null,this.timeout=n,this.timeoutTimer=null,this.recHooks=[],this.sent=false,this.ref=void 0;}resend(t){this.timeout=t,this.reset(),this.send();}send(){this.hasReceived("timeout")||(this.startTimeout(),this.sent=true,this.channel.socket.push({topic:this.channel.topic,event:this.event,payload:this.payload(),ref:this.ref,join_ref:this.channel.joinRef()}));}receive(t,e){return this.hasReceived(t)&&e(this.receivedResp.response),this.recHooks.push({status:t,callback:e}),this}reset(){this.cancelRefEvent(),this.ref=null,this.refEvent=null,this.receivedResp=null,this.sent=false;}destroy(){this.cancelRefEvent(),this.cancelTimeout();}matchReceive({status:t,response:e,_ref:r}){this.recHooks.filter(n=>n.status===t).forEach(n=>n.callback(e));}cancelRefEvent(){this.refEvent&&this.channel.off(this.refEvent);}cancelTimeout(){clearTimeout(this.timeoutTimer),this.timeoutTimer=null;}startTimeout(){this.timeoutTimer&&this.cancelTimeout(),this.ref=this.channel.socket.makeRef(),this.refEvent=this.channel.replyEventName(this.ref),this.channel.on(this.refEvent,t=>{this.cancelRefEvent(),this.cancelTimeout(),this.receivedResp=t,this.matchReceive(t);}),this.timeoutTimer=setTimeout(()=>{this.trigger("timeout",{});},this.timeout);}hasReceived(t){return this.receivedResp&&this.receivedResp.status===t}trigger(t,e){this.channel.trigger(this.refEvent,{status:t,response:e});}},Ql=class{constructor(t,e){this.callback=t,this.timerCalc=e,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));}},Fg=class{constructor(t,e,r){this.state=Q.closed,this.topic=t,this.params=Tr(e||{}),this.socket=r,this.bindings=[],this.bindingRef=0,this.timeout=this.socket.timeout,this.joinedOnce=false,this.joinPush=new jn(this,$e.join,this.params,this.timeout),this.pushBuffer=[],this.stateChangeRefs=[],this.rejoinTimer=new Ql(()=>{this.socket.isConnected()&&this.rejoin();},this.socket.rejoinAfterMs),this.stateChangeRefs.push(this.socket.onError(()=>this.rejoinTimer.reset())),this.stateChangeRefs.push(this.socket.onOpen(()=>{this.rejoinTimer.reset(),this.isErrored()&&this.rejoin();})),this.joinPush.receive("ok",()=>{this.state=Q.joined,this.rejoinTimer.reset(),this.pushBuffer.forEach(n=>n.send()),this.pushBuffer=[];}),this.joinPush.receive("error",n=>{this.state=Q.errored,this.socket.hasLogger()&&this.socket.log("channel",`error ${this.topic}`,n),this.socket.isConnected()&&this.rejoinTimer.scheduleTimeout();}),this.onClose(()=>{this.rejoinTimer.reset(),this.socket.hasLogger()&&this.socket.log("channel",`close ${this.topic}`),this.state=Q.closed,this.socket.remove(this);}),this.onError(n=>{this.socket.hasLogger()&&this.socket.log("channel",`error ${this.topic}`,n),this.isJoining()&&this.joinPush.reset(),this.state=Q.errored,this.socket.isConnected()&&this.rejoinTimer.scheduleTimeout();}),this.joinPush.receive("timeout",()=>{this.socket.hasLogger()&&this.socket.log("channel",`timeout ${this.topic}`,this.joinPush.timeout),new jn(this,$e.leave,Tr({}),this.timeout).send(),this.state=Q.errored,this.joinPush.reset(),this.socket.isConnected()&&this.rejoinTimer.scheduleTimeout();}),this.on($e.reply,(n,i)=>{this.trigger(this.replyEventName(i),n);});}join(t=this.timeout){if(this.joinedOnce)throw new Error("tried to join multiple times. 'join' can only be called a single time per channel instance");return this.timeout=t,this.joinedOnce=true,this.rejoin(),this.joinPush}teardown(){this.pushBuffer.forEach(t=>t.destroy()),this.pushBuffer=[],this.rejoinTimer.reset(),this.joinPush.destroy(),this.state=Q.closed,this.bindings=[];}onClose(t){this.on($e.close,t);}onError(t){return this.on($e.error,e=>t(e))}on(t,e){let r=this.bindingRef++;return this.bindings.push({event:t,ref:r,callback:e}),r}off(t,e){this.bindings=this.bindings.filter(r=>!(r.event===t&&(typeof e>"u"||e===r.ref)));}canPush(){return this.socket.isConnected()&&this.isJoined()}push(t,e,r=this.timeout){if(e=e||{},!this.joinedOnce)throw new Error(`tried to push '${t}' to '${this.topic}' before joining. Use channel.join() before pushing events`);let n=new jn(this,t,function(){return e},r);return this.canPush()?n.send():(n.startTimeout(),this.pushBuffer.push(n)),n}leave(t=this.timeout){this.rejoinTimer.reset(),this.joinPush.cancelTimeout(),this.state=Q.leaving;let e=()=>{this.socket.hasLogger()&&this.socket.log("channel",`leave ${this.topic}`),this.trigger($e.close,"leave");},r=new jn(this,$e.leave,Tr({}),t);return r.receive("ok",()=>e()).receive("timeout",()=>e()),r.send(),this.canPush()||r.trigger("ok",{}),r}onMessage(t,e,r){return e}filterBindings(t,e,r){return true}isMember(t,e,r,n){return this.topic!==t?false:n&&n!==this.joinRef()?(this.socket.hasLogger()&&this.socket.log("channel","dropping outdated message",{topic:t,event:e,payload:r,joinRef:n}),false):true}joinRef(){return this.joinPush.ref}rejoin(t=this.timeout){this.isLeaving()||(this.socket.leaveOpenTopic(this.topic),this.state=Q.joining,this.joinPush.resend(t));}trigger(t,e,r,n){let i=this.onMessage(t,e,r,n);if(e&&!i)throw new Error("channel onMessage callbacks must return the payload, modified or unmodified");let s=this.bindings.filter(o=>o.event===t&&this.filterBindings(o,e,r));for(let o=0;o<s.length;o++)s[o].callback(i,r,n||this.joinRef());}replyEventName(t){return `chan_reply_${t}`}isClosed(){return this.state===Q.closed}isErrored(){return this.state===Q.errored}isJoined(){return this.state===Q.joined}isJoining(){return this.state===Q.joining}isLeaving(){return this.state===Q.leaving}},Ln=class{static request(t,e,r,n,i,s,o){if(ke.XDomainRequest){let a=new ke.XDomainRequest;return this.xdomainRequest(a,t,e,n,i,s,o)}else if(ke.XMLHttpRequest){let a=new ke.XMLHttpRequest;return this.xhrRequest(a,t,e,r,n,i,s,o)}else {if(ke.fetch&&ke.AbortController)return this.fetchRequest(t,e,r,n,i,s,o);throw new Error("No suitable XMLHttpRequest implementation found")}}static fetchRequest(t,e,r,n,i,s,o){let a={method:t,headers:r,body:n},l=null;if(i){l=new AbortController;setTimeout(()=>l.abort(),i);a.signal=l.signal;}return ke.fetch(e,a).then(c=>c.text()).then(c=>this.parseJSON(c)).then(c=>o&&o(c)).catch(c=>{c.name==="AbortError"&&s?s():o&&o(null);}),l}static xdomainRequest(t,e,r,n,i,s,o){return t.timeout=i,t.open(e,r),t.onload=()=>{let a=this.parseJSON(t.responseText);o&&o(a);},s&&(t.ontimeout=s),t.onprogress=()=>{},t.send(n),t}static xhrRequest(t,e,r,n,i,s,o,a){t.open(e,r,true),t.timeout=s;for(let[l,c]of Object.entries(n))t.setRequestHeader(l,c);return t.onerror=()=>a&&a(null),t.onreadystatechange=()=>{if(t.readyState===Bg.complete&&a){let l=this.parseJSON(t.responseText);a(l);}},o&&(t.ontimeout=o),t.send(i),t}static parseJSON(t){if(!t||t==="")return null;try{return JSON.parse(t)}catch{return console&&console.log("failed to parse JSON response",t),null}}static serialize(t,e){let r=[];for(var n in t){if(!Object.prototype.hasOwnProperty.call(t,n))continue;let i=e?`${e}[${n}]`:n,s=t[n];typeof s=="object"?r.push(this.serialize(s,i)):r.push(encodeURIComponent(i)+"="+encodeURIComponent(s));}return r.join("&")}static appendParams(t,e){if(Object.keys(e).length===0)return t;let r=t.match(/\?/)?"&":"?";return `${t}${r}${this.serialize(e)}`}},Hg=t=>{let e="",r=new Uint8Array(t),n=r.byteLength;for(let i=0;i<n;i++)e+=String.fromCharCode(r[i]);return btoa(e)},qt=class{constructor(t,e){e&&e.length===2&&e[1].startsWith(Es)&&(this.authToken=atob(e[1].slice(Es.length))),this.endPoint=null,this.token=null,this.skipHeartbeat=true,this.reqs=new Set,this.awaitingBatchAck=false,this.currentBatch=null,this.currentBatchTimer=null,this.batchBuffer=[],this.onopen=function(){},this.onerror=function(){},this.onmessage=function(){},this.onclose=function(){},this.pollEndpoint=this.normalizeEndpoint(t),this.readyState=be.connecting,setTimeout(()=>this.poll(),0);}normalizeEndpoint(t){return t.replace("ws://","http://").replace("wss://","https://").replace(new RegExp("(.*)/"+Cs.websocket),"$1/"+Cs.longpoll)}endpointURL(){return Ln.appendParams(this.pollEndpoint,{token:this.token})}closeAndRetry(t,e,r){this.close(t,e,r),this.readyState=be.connecting;}ontimeout(){this.onerror("timeout"),this.closeAndRetry(1005,"timeout",false);}isActive(){return this.readyState===be.open||this.readyState===be.connecting}poll(){let t={Accept:"application/json"};this.authToken&&(t["X-Phoenix-AuthToken"]=this.authToken),this.ajax("GET",t,null,()=>this.ontimeout(),e=>{if(e){var{status:r,token:n,messages:i}=e;if(r===410&&this.token!==null){this.onerror(410),this.closeAndRetry(3410,"session_gone",false);return}this.token=n;}else r=0;switch(r){case 200:i.forEach(s=>{setTimeout(()=>this.onmessage({data:s}),0);}),this.poll();break;case 204:this.poll();break;case 410:this.readyState=be.open,this.onopen({}),this.poll();break;case 403:this.onerror(403),this.close(1008,"forbidden",false);break;case 0:case 500:this.onerror(500),this.closeAndRetry(1011,"internal server error",500);break;default:throw new Error(`unhandled poll status ${r}`)}});}send(t){typeof t!="string"&&(t=Hg(t)),this.currentBatch?this.currentBatch.push(t):this.awaitingBatchAck?this.batchBuffer.push(t):(this.currentBatch=[t],this.currentBatchTimer=setTimeout(()=>{this.batchSend(this.currentBatch),this.currentBatch=null;},0));}batchSend(t){this.awaitingBatchAck=true,this.ajax("POST",{"Content-Type":"application/x-ndjson"},t.join(`
12
+ `),()=>this.onerror("timeout"),e=>{this.awaitingBatchAck=false,!e||e.status!==200?(this.onerror(e&&e.status),this.closeAndRetry(1011,"internal server error",false)):this.batchBuffer.length>0&&(this.batchSend(this.batchBuffer),this.batchBuffer=[]);});}close(t,e,r){for(let i of this.reqs)i.abort();this.readyState=be.closed;let n=Object.assign({code:1e3,reason:void 0,wasClean:true},{code:t,reason:e,wasClean:r});this.batchBuffer=[],clearTimeout(this.currentBatchTimer),this.currentBatchTimer=null,typeof CloseEvent<"u"?this.onclose(new CloseEvent("close",n)):this.onclose(n);}ajax(t,e,r,n,i){let s,o=()=>{this.reqs.delete(s),n();};s=Ln.request(t,this.endpointURL(),e,r,this.timeout,o,a=>{this.reqs.delete(s),this.isActive()&&i(a);}),this.reqs.add(s);}},ec=class Pr{constructor(e,r={}){let n=r.events||{state:"presence_state",diff:"presence_diff"};this.state={},this.pendingDiffs=[],this.channel=e,this.joinRef=null,this.caller={onJoin:function(){},onLeave:function(){},onSync:function(){}},this.channel.on(n.state,i=>{let{onJoin:s,onLeave:o,onSync:a}=this.caller;this.joinRef=this.channel.joinRef(),this.state=Pr.syncState(this.state,i,s,o),this.pendingDiffs.forEach(l=>{this.state=Pr.syncDiff(this.state,l,s,o);}),this.pendingDiffs=[],a();}),this.channel.on(n.diff,i=>{let{onJoin:s,onLeave:o,onSync:a}=this.caller;this.inPendingSyncState()?this.pendingDiffs.push(i):(this.state=Pr.syncDiff(this.state,i,s,o),a());});}onJoin(e){this.caller.onJoin=e;}onLeave(e){this.caller.onLeave=e;}onSync(e){this.caller.onSync=e;}list(e){return Pr.list(this.state,e)}inPendingSyncState(){return !this.joinRef||this.joinRef!==this.channel.joinRef()}static syncState(e,r,n,i){let s=this.clone(e),o={},a={};return this.map(s,(l,c)=>{r[l]||(a[l]=c);}),this.map(r,(l,c)=>{let u=s[l];if(u){let d=c.metas.map(m=>m.phx_ref),p=u.metas.map(m=>m.phx_ref),h=c.metas.filter(m=>p.indexOf(m.phx_ref)<0),f=u.metas.filter(m=>d.indexOf(m.phx_ref)<0);h.length>0&&(o[l]=c,o[l].metas=h),f.length>0&&(a[l]=this.clone(u),a[l].metas=f);}else o[l]=c;}),this.syncDiff(s,{joins:o,leaves:a},n,i)}static syncDiff(e,r,n,i){let{joins:s,leaves:o}=this.clone(r);return n||(n=function(){}),i||(i=function(){}),this.map(s,(a,l)=>{let c=e[a];if(e[a]=this.clone(l),c){let u=e[a].metas.map(p=>p.phx_ref),d=c.metas.filter(p=>u.indexOf(p.phx_ref)<0);e[a].metas.unshift(...d);}n(a,c,l);}),this.map(o,(a,l)=>{let c=e[a];if(!c)return;let u=l.metas.map(d=>d.phx_ref);c.metas=c.metas.filter(d=>u.indexOf(d.phx_ref)<0),i(a,c,l),c.metas.length===0&&delete e[a];}),e}static list(e,r){return r||(r=function(n,i){return i}),this.map(e,(n,i)=>r(n,i))}static map(e,r){return Object.getOwnPropertyNames(e).map(n=>r(n,e[n]))}static clone(e){return JSON.parse(JSON.stringify(e))}},Mn={HEADER_LENGTH:1,META_LENGTH:4,KINDS:{push:0,reply:1,broadcast:2},encode(t,e){if(t.payload.constructor===ArrayBuffer)return e(this.binaryEncode(t));{let r=[t.join_ref,t.ref,t.topic,t.event,t.payload];return e(JSON.stringify(r))}},decode(t,e){if(t.constructor===ArrayBuffer)return e(this.binaryDecode(t));{let[r,n,i,s,o]=JSON.parse(t);return e({join_ref:r,ref:n,topic:i,event:s,payload:o})}},binaryEncode(t){let{join_ref:e,ref:r,event:n,topic:i,payload:s}=t,o=this.META_LENGTH+e.length+r.length+i.length+n.length,a=new ArrayBuffer(this.HEADER_LENGTH+o),l=new DataView(a),c=0;l.setUint8(c++,this.KINDS.push),l.setUint8(c++,e.length),l.setUint8(c++,r.length),l.setUint8(c++,i.length),l.setUint8(c++,n.length),Array.from(e,d=>l.setUint8(c++,d.charCodeAt(0))),Array.from(r,d=>l.setUint8(c++,d.charCodeAt(0))),Array.from(i,d=>l.setUint8(c++,d.charCodeAt(0))),Array.from(n,d=>l.setUint8(c++,d.charCodeAt(0)));var u=new Uint8Array(a.byteLength+s.byteLength);return u.set(new Uint8Array(a),0),u.set(new Uint8Array(s),a.byteLength),u.buffer},binaryDecode(t){let e=new DataView(t),r=e.getUint8(0),n=new TextDecoder;switch(r){case this.KINDS.push:return this.decodePush(t,e,n);case this.KINDS.reply:return this.decodeReply(t,e,n);case this.KINDS.broadcast:return this.decodeBroadcast(t,e,n)}},decodePush(t,e,r){let n=e.getUint8(1),i=e.getUint8(2),s=e.getUint8(3),o=this.HEADER_LENGTH+this.META_LENGTH-1,a=r.decode(t.slice(o,o+n));o=o+n;let l=r.decode(t.slice(o,o+i));o=o+i;let c=r.decode(t.slice(o,o+s));o=o+s;let u=t.slice(o,t.byteLength);return {join_ref:a,ref:null,topic:l,event:c,payload:u}},decodeReply(t,e,r){let n=e.getUint8(1),i=e.getUint8(2),s=e.getUint8(3),o=e.getUint8(4),a=this.HEADER_LENGTH+this.META_LENGTH,l=r.decode(t.slice(a,a+n));a=a+n;let c=r.decode(t.slice(a,a+i));a=a+i;let u=r.decode(t.slice(a,a+s));a=a+s;let d=r.decode(t.slice(a,a+o));a=a+o;let p=t.slice(a,t.byteLength),h={status:d,response:p};return {join_ref:l,ref:c,topic:u,event:$e.reply,payload:h}},decodeBroadcast(t,e,r){let n=e.getUint8(1),i=e.getUint8(2),s=this.HEADER_LENGTH+2,o=r.decode(t.slice(s,s+n));s=s+n;let a=r.decode(t.slice(s,s+i));s=s+i;let l=t.slice(s,t.byteLength);return {join_ref:null,ref:null,topic:o,event:a,payload:l}}},tc=class{constructor(t,e={}){this.stateChangeCallbacks={open:[],close:[],error:[],message:[]},this.channels=[],this.sendBuffer=[],this.ref=0,this.fallbackRef=null,this.timeout=e.timeout||Ug,this.transport=e.transport||ke.WebSocket||qt,this.conn=void 0,this.primaryPassedHealthCheck=false,this.longPollFallbackMs=e.longPollFallbackMs,this.fallbackTimer=null,this.sessionStore=e.sessionStorage||ke&&ke.sessionStorage,this.establishedConnections=0,this.defaultEncoder=Mn.encode.bind(Mn),this.defaultDecoder=Mn.decode.bind(Mn),this.closeWasClean=true,this.disconnecting=false,this.binaryType=e.binaryType||"arraybuffer",this.connectClock=1,this.pageHidden=false,this.encode=void 0,this.decode=void 0,this.transport!==qt?(this.encode=e.encode||this.defaultEncoder,this.decode=e.decode||this.defaultDecoder):(this.encode=this.defaultEncoder,this.decode=this.defaultDecoder);let r=null;zt&&zt.addEventListener&&(zt.addEventListener("pagehide",n=>{this.conn&&(this.disconnect(),r=this.connectClock);}),zt.addEventListener("pageshow",n=>{r===this.connectClock&&(r=null,this.connect());}),zt.addEventListener("visibilitychange",()=>{document.visibilityState==="hidden"?this.pageHidden=true:(this.pageHidden=false,!this.isConnected()&&!this.closeWasClean&&this.teardown(()=>this.connect()));})),this.heartbeatIntervalMs=e.heartbeatIntervalMs||3e4,this.autoSendHeartbeat=e.autoSendHeartbeat??true,this.heartbeatCallback=e.heartbeatCallback??(()=>{}),this.rejoinAfterMs=n=>e.rejoinAfterMs?e.rejoinAfterMs(n):[1e3,2e3,5e3][n-1]||1e4,this.reconnectAfterMs=n=>e.reconnectAfterMs?e.reconnectAfterMs(n):[10,50,100,150,200,250,500,1e3,2e3][n-1]||5e3,this.logger=e.logger||null,!this.logger&&e.debug&&(this.logger=(n,i,s)=>{console.log(`${n}: ${i}`,s);}),this.longpollerTimeout=e.longpollerTimeout||2e4,this.params=Tr(e.params||{}),this.endPoint=`${t}/${Cs.websocket}`,this.vsn=e.vsn||Lg,this.heartbeatTimeoutTimer=null,this.heartbeatTimer=null,this.heartbeatSentAt=null,this.pendingHeartbeatRef=null,this.reconnectTimer=new Ql(()=>{if(this.pageHidden){this.log("Not reconnecting as page is hidden!"),this.teardown();return}this.teardown(async()=>{e.beforeReconnect&&await e.beforeReconnect(),this.connect();});},this.reconnectAfterMs),this.authToken=e.authToken;}getLongPollTransport(){return qt}replaceTransport(t){this.connectClock++,this.closeWasClean=true,clearTimeout(this.fallbackTimer),this.reconnectTimer.reset(),this.conn&&(this.conn.close(),this.conn=null),this.transport=t;}protocol(){return location.protocol.match(/^https/)?"wss":"ws"}endPointURL(){let t=Ln.appendParams(Ln.appendParams(this.endPoint,this.params()),{vsn:this.vsn});return t.charAt(0)!=="/"?t:t.charAt(1)==="/"?`${this.protocol()}:${t}`:`${this.protocol()}://${location.host}${t}`}disconnect(t,e,r){this.connectClock++,this.disconnecting=true,this.closeWasClean=true,clearTimeout(this.fallbackTimer),this.reconnectTimer.reset(),this.teardown(()=>{this.disconnecting=false,t&&t();},e,r);}connect(t){t&&(console&&console.log("passing params to connect is deprecated. Instead pass :params to the Socket constructor"),this.params=Tr(t)),!(this.conn&&!this.disconnecting)&&(this.longPollFallbackMs&&this.transport!==qt?this.connectWithFallback(qt,this.longPollFallbackMs):this.transportConnect());}log(t,e,r){this.logger&&this.logger(t,e,r);}hasLogger(){return this.logger!==null}onOpen(t){let e=this.makeRef();return this.stateChangeCallbacks.open.push([e,t]),e}onClose(t){let e=this.makeRef();return this.stateChangeCallbacks.close.push([e,t]),e}onError(t){let e=this.makeRef();return this.stateChangeCallbacks.error.push([e,t]),e}onMessage(t){let e=this.makeRef();return this.stateChangeCallbacks.message.push([e,t]),e}onHeartbeat(t){this.heartbeatCallback=t;}ping(t){if(!this.isConnected())return false;let e=this.makeRef(),r=Date.now();this.push({topic:"phoenix",event:"heartbeat",payload:{},ref:e});let n=this.onMessage(i=>{i.ref===e&&(this.off([n]),t(Date.now()-r));});return true}transportName(t){return t===qt?"LongPoll":t.name}transportConnect(){this.connectClock++,this.closeWasClean=false;let t;this.authToken&&(t=["phoenix",`${Es}${btoa(this.authToken).replace(/=/g,"")}`]),this.conn=new this.transport(this.endPointURL(),t),this.conn.binaryType=this.binaryType,this.conn.timeout=this.longpollerTimeout,this.conn.onopen=()=>this.onConnOpen(),this.conn.onerror=e=>this.onConnError(e),this.conn.onmessage=e=>this.onConnMessage(e),this.conn.onclose=e=>this.onConnClose(e);}getSession(t){return this.sessionStore&&this.sessionStore.getItem(t)}storeSession(t,e){this.sessionStore&&this.sessionStore.setItem(t,e);}connectWithFallback(t,e=2500){clearTimeout(this.fallbackTimer);let r=false,n=true,i,s,o=this.transportName(t),a=l=>{this.log("transport",`falling back to ${o}...`,l),this.off([i,s]),n=false,this.replaceTransport(t),this.transportConnect();};if(this.getSession(`phx:fallback:${o}`))return a("memorized");this.fallbackTimer=setTimeout(a,e),s=this.onError(l=>{this.log("transport","error",l),n&&!r&&(clearTimeout(this.fallbackTimer),a(l));}),this.fallbackRef&&this.off([this.fallbackRef]),this.fallbackRef=this.onOpen(()=>{if(r=true,!n){let l=this.transportName(t);return this.primaryPassedHealthCheck||this.storeSession(`phx:fallback:${l}`,"true"),this.log("transport",`established ${l} fallback`)}clearTimeout(this.fallbackTimer),this.fallbackTimer=setTimeout(a,e),this.ping(l=>{this.log("transport","connected to primary after",l),this.primaryPassedHealthCheck=true,clearTimeout(this.fallbackTimer);});}),this.transportConnect();}clearHeartbeats(){clearTimeout(this.heartbeatTimer),clearTimeout(this.heartbeatTimeoutTimer);}onConnOpen(){this.hasLogger()&&this.log("transport",`connected to ${this.endPointURL()}`),this.closeWasClean=false,this.disconnecting=false,this.establishedConnections++,this.flushSendBuffer(),this.reconnectTimer.reset(),this.autoSendHeartbeat&&this.resetHeartbeat(),this.triggerStateCallbacks("open");}heartbeatTimeout(){if(this.pendingHeartbeatRef){this.pendingHeartbeatRef=null,this.heartbeatSentAt=null,this.hasLogger()&&this.log("transport","heartbeat timeout. Attempting to re-establish connection");try{this.heartbeatCallback("timeout");}catch(t){this.log("error","error in heartbeat callback",t);}this.triggerChanError(),this.closeWasClean=false,this.teardown(()=>this.reconnectTimer.scheduleTimeout(),Wg,"heartbeat timeout");}}resetHeartbeat(){this.conn&&this.conn.skipHeartbeat||(this.pendingHeartbeatRef=null,this.clearHeartbeats(),this.heartbeatTimer=setTimeout(()=>this.sendHeartbeat(),this.heartbeatIntervalMs));}teardown(t,e,r){if(!this.conn)return t&&t();let n=this.conn;this.waitForBufferDone(n,()=>{e?n.close(e,r||""):n.close(),this.waitForSocketClosed(n,()=>{this.conn===n&&(this.conn.onopen=function(){},this.conn.onerror=function(){},this.conn.onmessage=function(){},this.conn.onclose=function(){},this.conn=null),t&&t();});});}waitForBufferDone(t,e,r=1){if(r===5||!t.bufferedAmount){e();return}setTimeout(()=>{this.waitForBufferDone(t,e,r+1);},150*r);}waitForSocketClosed(t,e,r=1){if(r===5||t.readyState===be.closed){e();return}setTimeout(()=>{this.waitForSocketClosed(t,e,r+1);},150*r);}onConnClose(t){this.conn&&(this.conn.onclose=()=>{}),this.hasLogger()&&this.log("transport","close",t),this.triggerChanError(),this.clearHeartbeats(),this.closeWasClean||this.reconnectTimer.scheduleTimeout(),this.triggerStateCallbacks("close",t);}onConnError(t){this.hasLogger()&&this.log("transport",t);let e=this.transport,r=this.establishedConnections;this.triggerStateCallbacks("error",t,e,r),(e===this.transport||r>0)&&this.triggerChanError();}triggerChanError(){this.channels.forEach(t=>{t.isErrored()||t.isLeaving()||t.isClosed()||t.trigger($e.error);});}connectionState(){switch(this.conn&&this.conn.readyState){case be.connecting:return "connecting";case be.open:return "open";case be.closing:return "closing";default:return "closed"}}isConnected(){return this.connectionState()==="open"}remove(t){this.off(t.stateChangeRefs),this.channels=this.channels.filter(e=>e!==t);}off(t){for(let e in this.stateChangeCallbacks)this.stateChangeCallbacks[e]=this.stateChangeCallbacks[e].filter(([r])=>t.indexOf(r)===-1);}channel(t,e={}){let r=new Fg(t,e,this);return this.channels.push(r),r}push(t){if(this.hasLogger()){let{topic:e,event:r,payload:n,ref:i,join_ref:s}=t;this.log("push",`${e} ${r} (${s}, ${i})`,n);}this.isConnected()?this.encode(t,e=>this.conn.send(e)):this.sendBuffer.push(()=>this.encode(t,e=>this.conn.send(e)));}makeRef(){let t=this.ref+1;return t===this.ref?this.ref=0:this.ref=t,this.ref.toString()}sendHeartbeat(){if(!this.isConnected()){try{this.heartbeatCallback("disconnected");}catch(t){this.log("error","error in heartbeat callback",t);}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(t){this.log("error","error in heartbeat callback",t);}this.heartbeatTimeoutTimer=setTimeout(()=>this.heartbeatTimeout(),this.heartbeatIntervalMs);}flushSendBuffer(){this.isConnected()&&this.sendBuffer.length>0&&(this.sendBuffer.forEach(t=>t()),this.sendBuffer=[]);}onConnMessage(t){this.decode(t.data,e=>{let{topic:r,event:n,payload:i,ref:s,join_ref:o}=e;if(s&&s===this.pendingHeartbeatRef){let a=this.heartbeatSentAt?Date.now()-this.heartbeatSentAt:void 0;this.clearHeartbeats();try{this.heartbeatCallback(i.status==="ok"?"ok":"error",a);}catch(l){this.log("error","error in heartbeat callback",l);}this.pendingHeartbeatRef=null,this.heartbeatSentAt=null,this.autoSendHeartbeat&&(this.heartbeatTimer=setTimeout(()=>this.sendHeartbeat(),this.heartbeatIntervalMs));}this.hasLogger()&&this.log("receive",`${i.status||""} ${r} ${n} ${s&&"("+s+")"||""}`.trim(),i);for(let a=0;a<this.channels.length;a++){let l=this.channels[a];l.isMember(r,n,i,o)&&l.trigger(n,i,s,o);}this.triggerStateCallbacks("message",e);});}triggerStateCallbacks(t,...e){try{this.stateChangeCallbacks[t].forEach(([r,n])=>{try{n(...e);}catch(i){this.log("error",`error in ${t} callback`,i);}});}catch(r){this.log("error",`error triggering ${t} callbacks`,r);}}leaveOpenTopic(t){let e=this.channels.find(r=>r.topic===t&&(r.isJoined()||r.isJoining()));e&&(this.hasLogger()&&this.log("transport",`leaving duplicate topic "${t}"`),e.leave());}};});function Un(t){return t.metas.map(e=>(e.presence_ref=e.phx_ref,delete e.phx_ref,delete e.phx_ref_prev,e))}function qg(t){return JSON.parse(JSON.stringify(t))}function zg(t){return t?.events&&{events:t.events}}function rc(t){return t?.metas?Un(t):[]}var Ar,nc=R(()=>{Rs();Ar=class t{constructor(e,r){let n=zg(r);this.presence=new ec(e.getChannel(),n),this.presence.onJoin((i,s,o)=>{let a=t.onJoinPayload(i,s,o);e.getChannel().trigger("presence",a);}),this.presence.onLeave((i,s,o)=>{let a=t.onLeavePayload(i,s,o);e.getChannel().trigger("presence",a);}),this.presence.onSync(()=>{e.getChannel().trigger("presence",{event:"sync"});});}get state(){return t.transformState(this.presence.state)}static transformState(e){return e=qg(e),Object.getOwnPropertyNames(e).reduce((r,n)=>{let i=e[n];return r[n]=Un(i),r},{})}static onJoinPayload(e,r,n){let i=rc(r),s=Un(n);return {event:"join",key:e,currentPresences:i,newPresences:s}}static onLeavePayload(e,r,n){let i=rc(r),s=Un(n);return {event:"leave",key:e,currentPresences:i,leftPresences:s}}};});var xs,Jt,Ps=R(()=>{nc();(function(t){t.SYNC="sync",t.JOIN="join",t.LEAVE="leave";})(xs||(xs={}));Jt=class{get state(){return this.presenceAdapter.state}constructor(e,r){this.channel=e,this.presenceAdapter=new Ar(this.channel.channelAdapter,r);}};});function Jg(t){return {config:Object.assign({broadcast:{ack:false,self:false},presence:{key:"",enabled:false},private:false},t.config)}}var Ir,ic=R(()=>{Rr();Ir=class{constructor(e,r,n){let i=Jg(n);this.channel=e.getSocket().channel(r,i),this.socket=e;}get state(){return this.channel.state}set state(e){this.channel.state=e;}get joinedOnce(){return this.channel.joinedOnce}get joinPush(){return this.channel.joinPush}get rejoinTimer(){return this.channel.rejoinTimer}on(e,r){return this.channel.on(e,r)}off(e,r){this.channel.off(e,r);}subscribe(e){return this.channel.join(e)}unsubscribe(e){return this.channel.leave(e)}teardown(){this.channel.teardown();}onClose(e){this.channel.onClose(e);}onError(e){return this.channel.onError(e)}push(e,r,n){let i;try{i=this.channel.push(e,r,n);}catch{throw `tried to push '${e}' to '${this.channel.topic}' before joining. Use channel.subscribe() before pushing events`}if(this.channel.pushBuffer.length>Yl){let s=this.channel.pushBuffer.shift();s.cancelTimeout(),this.socket.log("channel",`discarded push due to buffer overflow: ${s.event}`,s.payload());}return i}updateJoinPayload(e){let r=this.channel.joinPush.payload();this.channel.joinPush.payload=()=>Object.assign(Object.assign({},r),e);}canPush(){return this.socket.isConnected()&&this.state===ye.joined}isJoined(){return this.state===ye.joined}isJoining(){return this.state===ye.joining}isClosed(){return this.state===ye.closed}isLeaving(){return this.state===ye.leaving}updateFilterBindings(e){this.channel.filterBindings=e;}updatePayloadTransform(e){this.channel.onMessage=e;}getChannel(){return this.channel}};});var Ts,at,ve,Kt,As=R(()=>{Rr();Ps();Dn();Dn();ic();(function(t){t.ALL="*",t.INSERT="INSERT",t.UPDATE="UPDATE",t.DELETE="DELETE";})(Ts||(Ts={}));(function(t){t.BROADCAST="broadcast",t.PRESENCE="presence",t.POSTGRES_CHANGES="postgres_changes",t.SYSTEM="system";})(at||(at={}));(function(t){t.SUBSCRIBED="SUBSCRIBED",t.TIMED_OUT="TIMED_OUT",t.CLOSED="CLOSED",t.CHANNEL_ERROR="CHANNEL_ERROR";})(ve||(ve={}));Kt=class t{get state(){return this.channelAdapter.state}set state(e){this.channelAdapter.state=e;}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(e,r={config:{}},n){var i,s;if(this.topic=e,this.params=r,this.socket=n,this.bindings={},this.subTopic=e.replace(/^realtime:/i,""),this.params.config=Object.assign({broadcast:{ack:false,self:false},presence:{key:"",enabled:false},private:false},r.config),this.channelAdapter=new Ir(this.socket.socketAdapter,e,this.params),this.presence=new Jt(this),this._onClose(()=>{this.socket._remove(this);}),this._updateFilterTransform(),this.broadcastEndpointURL=Nn(this.socket.socketAdapter.endPointURL()),this.private=this.params.config.private||false,!this.private&&(!((s=(i=this.params.config)===null||i===void 0?void 0:i.broadcast)===null||s===void 0)&&s.replay))throw `tried to use replay on public channel '${this.topic}'. It must be a private channel.`}subscribe(e,r=this.timeout){var n,i,s;if(this.socket.isConnected()||this.socket.connect(),this.channelAdapter.isClosed()){let{config:{broadcast:o,presence:a,private:l}}=this.params,c=(i=(n=this.bindings.postgres_changes)===null||n===void 0?void 0:n.map(h=>h.filter))!==null&&i!==void 0?i:[],u=!!this.bindings[at.PRESENCE]&&this.bindings[at.PRESENCE].length>0||((s=this.params.config.presence)===null||s===void 0?void 0:s.enabled)===true,d={},p={broadcast:o,presence:Object.assign(Object.assign({},a),{enabled:u}),postgres_changes:c,private:l};this.socket.accessTokenValue&&(d.access_token=this.socket.accessTokenValue),this._onError(h=>{e?.(ve.CHANNEL_ERROR,h);}),this._onClose(()=>e?.(ve.CLOSED)),this.updateJoinPayload(Object.assign({config:p},d)),this._updateFilterMessage(),this.channelAdapter.subscribe(r).receive("ok",async({postgres_changes:h})=>{if(this.socket._isManualToken()||this.socket.setAuth(),h===void 0){e?.(ve.SUBSCRIBED);return}this._updatePostgresBindings(h,e);}).receive("error",h=>{this.state=ye.errored,e?.(ve.CHANNEL_ERROR,new Error(JSON.stringify(Object.values(h).join(", ")||"error")));}).receive("timeout",()=>{e?.(ve.TIMED_OUT);});}return this}_updatePostgresBindings(e,r){var n;let i=this.bindings.postgres_changes,s=(n=i?.length)!==null&&n!==void 0?n:0,o=[];for(let a=0;a<s;a++){let l=i[a],{filter:{event:c,schema:u,table:d,filter:p}}=l,h=e&&e[a];if(h&&h.event===c&&t.isFilterValueEqual(h.schema,u)&&t.isFilterValueEqual(h.table,d)&&t.isFilterValueEqual(h.filter,p))o.push(Object.assign(Object.assign({},l),{id:h.id}));else {this.unsubscribe(),this.state=ye.errored,r?.(ve.CHANNEL_ERROR,new Error("mismatch between server and client bindings for postgres changes"));return}}this.bindings.postgres_changes=o,this.state!=ye.errored&&r&&r(ve.SUBSCRIBED);}presenceState(){return this.presence.state}async track(e,r={}){return await this.send({type:"presence",event:"track",payload:e},r.timeout||this.timeout)}async untrack(e={}){return await this.send({type:"presence",event:"untrack"},e)}on(e,r,n){let i=this.channelAdapter.isJoined()||this.channelAdapter.isJoining(),s=e===at.PRESENCE||e===at.POSTGRES_CHANGES;if(i&&s)throw this.socket.log("channel",`cannot add \`${e}\` callbacks for ${this.topic} after \`subscribe()\`.`),new Error(`cannot add \`${e}\` callbacks for ${this.topic} after \`subscribe()\`.`);return this._on(e,r,n)}async httpSend(e,r,n={}){var i;if(r==null)return Promise.reject("Payload is required for httpSend()");let s={apikey:this.socket.apiKey?this.socket.apiKey:"","Content-Type":"application/json"};this.socket.accessTokenValue&&(s.Authorization=`Bearer ${this.socket.accessTokenValue}`);let o={method:"POST",headers:s,body:JSON.stringify({messages:[{topic:this.subTopic,event:e,payload:r,private:this.private}]})},a=await this._fetchWithTimeout(this.broadcastEndpointURL,o,(i=n.timeout)!==null&&i!==void 0?i:this.timeout);if(a.status===202)return {success:true};let l=a.statusText;try{let c=await a.json();l=c.error||c.message||l;}catch{}return Promise.reject(new Error(l))}async send(e,r={}){var n,i;if(!this.channelAdapter.canPush()&&e.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:s,payload:o}=e,a={apikey:this.socket.apiKey?this.socket.apiKey:"","Content-Type":"application/json"};this.socket.accessTokenValue&&(a.Authorization=`Bearer ${this.socket.accessTokenValue}`);let l={method:"POST",headers:a,body:JSON.stringify({messages:[{topic:this.subTopic,event:s,payload:o,private:this.private}]})};try{let c=await this._fetchWithTimeout(this.broadcastEndpointURL,l,(n=r.timeout)!==null&&n!==void 0?n:this.timeout);return await((i=c.body)===null||i===void 0?void 0:i.cancel()),c.ok?"ok":"error"}catch(c){return c.name==="AbortError"?"timed out":"error"}}else return new Promise(s=>{var o,a,l;let c=this.channelAdapter.push(e.type,e,r.timeout||this.timeout);e.type==="broadcast"&&!(!((l=(a=(o=this.params)===null||o===void 0?void 0:o.config)===null||a===void 0?void 0:a.broadcast)===null||l===void 0)&&l.ack)&&s("ok"),c.receive("ok",()=>s("ok")),c.receive("error",()=>s("error")),c.receive("timeout",()=>s("timed out"));})}updateJoinPayload(e){this.channelAdapter.updateJoinPayload(e);}async unsubscribe(e=this.timeout){return new Promise(r=>{this.channelAdapter.unsubscribe(e).receive("ok",()=>r("ok")).receive("timeout",()=>r("timed out")).receive("error",()=>r("error"));})}teardown(){this.channelAdapter.teardown();}async _fetchWithTimeout(e,r,n){let i=new AbortController,s=setTimeout(()=>i.abort(),n),o=await this.socket.fetch(e,Object.assign(Object.assign({},r),{signal:i.signal}));return clearTimeout(s),o}_on(e,r,n){let i=e.toLocaleLowerCase(),s=this.channelAdapter.on(e,n),o={type:i,filter:r,callback:n,ref:s};return this.bindings[i]?this.bindings[i].push(o):this.bindings[i]=[o],this._updateFilterMessage(),this}_onClose(e){this.channelAdapter.onClose(e);}_onError(e){this.channelAdapter.onError(e);}_updateFilterMessage(){this.channelAdapter.updateFilterBindings((e,r,n)=>{var i,s,o,a,l,c,u;let d=e.event.toLocaleLowerCase();if(this._notThisChannelEvent(d,n))return false;let p=(i=this.bindings[d])===null||i===void 0?void 0:i.find(h=>h.ref===e.ref);if(!p)return true;if(["broadcast","presence","postgres_changes"].includes(d))if("id"in p){let h=p.id,f=(s=p.filter)===null||s===void 0?void 0:s.event;return h&&((o=r.ids)===null||o===void 0?void 0:o.includes(h))&&(f==="*"||f?.toLocaleLowerCase()===((a=r.data)===null||a===void 0?void 0:a.type.toLocaleLowerCase()))}else {let h=(c=(l=p?.filter)===null||l===void 0?void 0:l.event)===null||c===void 0?void 0:c.toLocaleLowerCase();return h==="*"||h===((u=r?.event)===null||u===void 0?void 0:u.toLocaleLowerCase())}else return p.type.toLocaleLowerCase()===d});}_notThisChannelEvent(e,r){let{close:n,error:i,leave:s,join:o}=$n;return r&&[n,i,s,o].includes(e)&&r!==this.joinPush.ref}_updateFilterTransform(){this.channelAdapter.updatePayloadTransform((e,r,n)=>{if(typeof r=="object"&&"ids"in r){let i=r.data,{schema:s,table:o,commit_timestamp:a,type:l,errors:c}=i;return Object.assign(Object.assign({},{schema:s,table:o,commit_timestamp:a,eventType:l,new:{},old:{},errors:c}),this._getPayloadRecords(i))}return r});}copyBindings(e){if(this.joinedOnce)throw new Error("cannot copy bindings into joined channel");for(let r in e.bindings)for(let n of e.bindings[r])this._on(n.type,n.filter,n.callback);}static isFilterValueEqual(e,r){return (e??void 0)===(r??void 0)}_getPayloadRecords(e){let r={new:{},old:{}};return (e.type==="INSERT"||e.type==="UPDATE")&&(r.new=Ss(e.columns,e.record)),(e.type==="UPDATE"||e.type==="DELETE")&&(r.old=Ss(e.columns,e.old_record)),r}};});var Or,sc=R(()=>{Rs();Rr();Or=class{constructor(e,r){this.socket=new tc(e,r);}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(e){this.socket.heartbeatCallback=e;}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(e,r,n,i=1e4){return new Promise(s=>{setTimeout(()=>s("timeout"),i),this.socket.disconnect(()=>{e(),s("ok");},r,n);})}push(e){this.socket.push(e);}log(e,r,n){this.socket.log(e,r,n);}makeRef(){return this.socket.makeRef()}onOpen(e){this.socket.onOpen(e);}onClose(e){this.socket.onClose(e);}onError(e){this.socket.onError(e);}onMessage(e){this.socket.onMessage(e);}isConnected(){return this.socket.isConnected()}isConnecting(){return this.socket.connectionState()==Er.connecting}isDisconnecting(){return this.socket.connectionState()==Er.closing}connectionState(){return this.socket.connectionState()}endPointURL(){return this.socket.endPointURL()}sendHeartbeat(){this.socket.sendHeartbeat();}getSocket(){return this.socket}};});var Kg,Vg,Gg,Yg,Vt,oc=R(()=>{ks();Rr();Xl();Dn();As();sc();Kg={HEARTBEAT_INTERVAL:25e3,RECONNECT_DELAY:10,HEARTBEAT_TIMEOUT_FALLBACK:100},Vg=[1e3,2e3,5e3,1e4],Gg=1e4,Yg=`
13
13
  addEventListener("message", (e) => {
14
14
  if (e.data.event === "start") {
15
15
  setInterval(() => postMessage({ event: "keepAlive" }), e.data.interval);
@@ -27,8 +27,8 @@ Option 2: Install and provide the "ws" package:
27
27
  const client = new RealtimeClient(url, {
28
28
  ...options,
29
29
  transport: ws
30
- })`):new Error(`WebSocket not available: ${r}`)}this._handleNodeJsRaceCondition();}}endpointURL(){return this.socketAdapter.endPointURL()}async disconnect(e,r){return this.isDisconnecting()?"ok":await this.socketAdapter.disconnect(()=>{clearInterval(this._workerHeartbeatTimer),this._terminateWorker();},e,r)}getChannels(){return this.channels}async removeChannel(e){let r=await e.unsubscribe();return r==="ok"&&e.teardown(),this.channels.length===0&&this.disconnect(),r}async removeAllChannels(){let e=this.channels.map(async n=>{let i=await n.unsubscribe();return n.teardown(),i}),r=await Promise.all(e);return this.disconnect(),r}log(e,r,n){this.socketAdapter.log(e,r,n);}connectionState(){return this.socketAdapter.connectionState()||Er.closed}isConnected(){return this.socketAdapter.isConnected()}isConnecting(){return this.socketAdapter.isConnecting()}isDisconnecting(){return this.socketAdapter.isDisconnecting()}channel(e,r={config:{}}){let n=`realtime:${e}`,i=this.getChannels().find(s=>s.topic===n);if(i)return i;{let s=new Kt(`realtime:${e}`,r,this);return this.channels.push(s),s}}push(e){this.socketAdapter.push(e);}async setAuth(e=null){this._authPromise=this._performAuth(e);try{await this._authPromise;}finally{this._authPromise=null;}}_isManualToken(){return this._manuallySetToken}async sendHeartbeat(){this.socketAdapter.sendHeartbeat();}onHeartbeat(e){this.socketAdapter.heartbeatCallback=this._wrapHeartbeatCallback(e);}_makeRef(){return this.socketAdapter.makeRef()}_remove(e){this.channels=this.channels.filter(r=>r.topic!==e.topic);}async _performAuth(e=null){let r,n=false;if(e)r=e,n=true;else if(this.accessToken)try{r=await this.accessToken();}catch(i){this.log("error","Error fetching access token from callback",i),r=this.accessTokenValue;}else r=this.accessTokenValue;n?this._manuallySetToken=true:this.accessToken&&(this._manuallySetToken=false),this.accessTokenValue!=r&&(this.accessTokenValue=r,this.channels.forEach(i=>{let s={access_token:r,version:Jl};r&&i.updateJoinPayload(s),i.joinedOnce&&i.channelAdapter.isJoined()&&i.channelAdapter.push($n.access_token,{access_token:r});}));}async _waitForAuthIfNeeded(){this._authPromise&&await this._authPromise;}_setAuthSafely(e="general"){this._isManualToken()||this.setAuth().catch(r=>{this.log("error",`Error setting auth in ${e}`,r);});}_setupConnectionHandlers(){this.socketAdapter.onOpen(()=>{(this._authPromise||(this.accessToken&&!this.accessTokenValue?this.setAuth():Promise.resolve())).catch(r=>{this.log("error","error waiting for auth on connect",r);}),this.worker&&!this.workerRef&&this._startWorkerHeartbeat();}),this.socketAdapter.onClose(()=>{this.worker&&this.workerRef&&this._terminateWorker();}),this.socketAdapter.onMessage(e=>{e.ref&&e.ref===this._pendingWorkerHeartbeatRef&&(this._pendingWorkerHeartbeatRef=null);});}_handleNodeJsRaceCondition(){this.socketAdapter.isConnected()&&this.socketAdapter.getSocket().onConnOpen();}_wrapHeartbeatCallback(e){return (r,n)=>{r=="sent"&&this._setAuthSafely(),e&&e(r,n);}}_startWorkerHeartbeat(){this.workerUrl?this.log("worker",`starting worker for from ${this.workerUrl}`):this.log("worker","starting default worker");let e=this._workerObjectUrl(this.workerUrl);this.workerRef=new Worker(e),this.workerRef.onerror=r=>{this.log("worker","worker error",r.message),this._terminateWorker(),this.disconnect();},this.workerRef.onmessage=r=>{r.data.event==="keepAlive"&&this.sendHeartbeat();},this.workerRef.postMessage({event:"start",interval:this.heartbeatIntervalMs});}_terminateWorker(){this.workerRef&&(this.log("worker","terminating worker"),this.workerRef.terminate(),this.workerRef=void 0);}_workerObjectUrl(e){let r;if(e)r=e;else {let n=new Blob([Yg],{type:"application/javascript"});r=URL.createObjectURL(n);}return r}_initializeOptions(e){var r,n,i,s,o,a,l,c,u;this.worker=(r=e?.worker)!==null&&r!==void 0?r:false,this.accessToken=(n=e?.accessToken)!==null&&n!==void 0?n:null;let d={};d.timeout=(i=e?.timeout)!==null&&i!==void 0?i:Gl,d.heartbeatIntervalMs=(s=e?.heartbeatIntervalMs)!==null&&s!==void 0?s:Kg.HEARTBEAT_INTERVAL,d.transport=(o=e?.transport)!==null&&o!==void 0?o:ys.getWebSocketConstructor(),d.params=e?.params,d.logger=e?.logger,d.heartbeatCallback=this._wrapHeartbeatCallback(e?.heartbeatCallback),d.reconnectAfterMs=(a=e?.reconnectAfterMs)!==null&&a!==void 0?a:(m=>Vg[m-1]||Gg);let p,h,f=(l=e?.vsn)!==null&&l!==void 0?l:Vl;switch(f){case Kl:p=(m,_)=>_(JSON.stringify(m)),h=(m,_)=>_(JSON.parse(m));break;case bs:p=this.serializer.encode.bind(this.serializer),h=this.serializer.decode.bind(this.serializer);break;default:throw new Error(`Unsupported serializer version: ${d.vsn}`)}if(d.vsn=f,d.encode=(c=e?.encode)!==null&&c!==void 0?c:p,d.decode=(u=e?.decode)!==null&&u!==void 0?u:h,d.beforeReconnect=this._reconnectAuth.bind(this),(e?.logLevel||e?.log_level)&&(this.logLevel=e.logLevel||e.log_level,d.params=Object.assign(Object.assign({},d.params),{log_level:this.logLevel})),this.worker){if(typeof window<"u"&&!window.Worker)throw new Error("Web Worker is not supported");this.workerUrl=e?.workerUrl,d.autoSendHeartbeat=!this.worker;}return d}async _reconnectAuth(){await this._waitForAuthIfNeeded(),this.isConnected()||this.connect();}};});var Is=R(()=>{oc();As();Ps();ks();});function Xg(t,e,r){let n=new URL(e,t);if(r)for(let[i,s]of Object.entries(r))s!==void 0&&n.searchParams.set(i,s);return n.toString()}async function Zg(t){return !t||t.type==="none"?{}:t.type==="bearer"?{Authorization:`Bearer ${t.token}`}:t.type==="header"?{[t.name]:t.value}:t.type==="custom"?await t.getHeaders():{}}function Qg(t){let e=t.fetchImpl??globalThis.fetch;return {async request({method:r,path:n,query:i,body:s,headers:o}){let a=Xg(t.baseUrl,n,i),l=await Zg(t.auth),c=await e(a,{method:r,headers:{...s?{"Content-Type":"application/json"}:{},...l,...o},body:s?JSON.stringify(s):void 0}),u=await c.text(),d=(c.headers.get("content-type")||"").includes("application/json"),p=d&&u?JSON.parse(u):u;if(!c.ok){let h=d?p:void 0,f=h?.error;throw new $r(f?.message??`Request failed with status ${c.status}`,{status:c.status,icebergType:f?.type,icebergCode:f?.code,details:h})}return {status:c.status,headers:c.headers,data:p}}}}function Wn(t){return t.join("")}function Gt(t){return t.join("")}var $r,em,tm,ac,lc=R(()=>{$r=class extends Error{constructor(t,e){super(t),this.name="IcebergError",this.status=e.status,this.icebergType=e.icebergType,this.icebergCode=e.icebergCode,this.details=e.details,this.isCommitStateUnknown=e.icebergType==="CommitStateUnknownException"||[500,502,504].includes(e.status)&&e.icebergType?.includes("CommitState")===true;}isNotFound(){return this.status===404}isConflict(){return this.status===409}isAuthenticationTimeout(){return this.status===419}};em=class{constructor(t,e=""){this.client=t,this.prefix=e;}async listNamespaces(t){let e=t?{parent:Wn(t.namespace)}:void 0;return (await this.client.request({method:"GET",path:`${this.prefix}/namespaces`,query:e})).data.namespaces.map(n=>({namespace:n}))}async createNamespace(t,e){let r={namespace:t.namespace,properties:e?.properties};return (await this.client.request({method:"POST",path:`${this.prefix}/namespaces`,body:r})).data}async dropNamespace(t){await this.client.request({method:"DELETE",path:`${this.prefix}/namespaces/${Wn(t.namespace)}`});}async loadNamespaceMetadata(t){return {properties:(await this.client.request({method:"GET",path:`${this.prefix}/namespaces/${Wn(t.namespace)}`})).data.properties}}async namespaceExists(t){try{return await this.client.request({method:"HEAD",path:`${this.prefix}/namespaces/${Wn(t.namespace)}`}),!0}catch(e){if(e instanceof $r&&e.status===404)return false;throw e}}async createNamespaceIfNotExists(t,e){try{return await this.createNamespace(t,e)}catch(r){if(r instanceof $r&&r.status===409)return;throw r}}};tm=class{constructor(t,e="",r){this.client=t,this.prefix=e,this.accessDelegation=r;}async listTables(t){return (await this.client.request({method:"GET",path:`${this.prefix}/namespaces/${Gt(t.namespace)}/tables`})).data.identifiers}async createTable(t,e){let r={};return this.accessDelegation&&(r["X-Iceberg-Access-Delegation"]=this.accessDelegation),(await this.client.request({method:"POST",path:`${this.prefix}/namespaces/${Gt(t.namespace)}/tables`,body:e,headers:r})).data.metadata}async updateTable(t,e){let r=await this.client.request({method:"POST",path:`${this.prefix}/namespaces/${Gt(t.namespace)}/tables/${t.name}`,body:e});return {"metadata-location":r.data["metadata-location"],metadata:r.data.metadata}}async dropTable(t,e){await this.client.request({method:"DELETE",path:`${this.prefix}/namespaces/${Gt(t.namespace)}/tables/${t.name}`,query:{purgeRequested:String(e?.purge??false)}});}async loadTable(t){let e={};return this.accessDelegation&&(e["X-Iceberg-Access-Delegation"]=this.accessDelegation),(await this.client.request({method:"GET",path:`${this.prefix}/namespaces/${Gt(t.namespace)}/tables/${t.name}`,headers:e})).data.metadata}async tableExists(t){let e={};this.accessDelegation&&(e["X-Iceberg-Access-Delegation"]=this.accessDelegation);try{return await this.client.request({method:"HEAD",path:`${this.prefix}/namespaces/${Gt(t.namespace)}/tables/${t.name}`,headers:e}),!0}catch(r){if(r instanceof $r&&r.status===404)return false;throw r}}async createTableIfNotExists(t,e){try{return await this.createTable(t,e)}catch(r){if(r instanceof $r&&r.status===409)return await this.loadTable({namespace:t.namespace,name:e.name});throw r}}},ac=class{constructor(t){let e="v1";t.catalogName&&(e+=`/${t.catalogName}`);let r=t.baseUrl.endsWith("/")?t.baseUrl:`${t.baseUrl}/`;this.client=Qg({baseUrl:r,auth:t.auth,fetchImpl:t.fetch}),this.accessDelegation=t.accessDelegation?.join(","),this.namespaceOps=new em(this.client,e),this.tableOps=new tm(this.client,e,this.accessDelegation);}async listNamespaces(t){return this.namespaceOps.listNamespaces(t)}async createNamespace(t,e){return this.namespaceOps.createNamespace(t,e)}async dropNamespace(t){await this.namespaceOps.dropNamespace(t);}async loadNamespaceMetadata(t){return this.namespaceOps.loadNamespaceMetadata(t)}async listTables(t){return this.tableOps.listTables(t)}async createTable(t,e){return this.tableOps.createTable(t,e)}async updateTable(t,e){return this.tableOps.updateTable(t,e)}async dropTable(t,e){await this.tableOps.dropTable(t,e);}async loadTable(t){return this.tableOps.loadTable(t)}async namespaceExists(t){return this.namespaceOps.namespaceExists(t)}async tableExists(t){return this.tableOps.tableExists(t)}async createNamespaceIfNotExists(t,e){return this.namespaceOps.createNamespaceIfNotExists(t,e)}async createTableIfNotExists(t,e){return this.tableOps.createTableIfNotExists(t,e)}};});function jr(t){"@babel/helpers - typeof";return jr=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(e){return typeof e}:function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},jr(t)}function rm(t,e){if(jr(t)!="object"||!t)return t;var r=t[Symbol.toPrimitive];if(r!==void 0){var n=r.call(t,e);if(jr(n)!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return (e==="string"?String:Number)(t)}function nm(t){var e=rm(t,"string");return jr(e)=="symbol"?e:e+""}function im(t,e,r){return (e=nm(e))in t?Object.defineProperty(t,e,{value:r,enumerable:true,configurable:true,writable:true}):t[e]=r,t}function cc(t,e){var r=Object.keys(t);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(t);e&&(n=n.filter(function(i){return Object.getOwnPropertyDescriptor(t,i).enumerable})),r.push.apply(r,n);}return r}function E(t){for(var e=1;e<arguments.length;e++){var r=arguments[e]!=null?arguments[e]:{};e%2?cc(Object(r),true).forEach(function(n){im(t,n,r[n]);}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(r)):cc(Object(r)).forEach(function(n){Object.defineProperty(t,n,Object.getOwnPropertyDescriptor(r,n));});}return t}function Hn(t){return typeof t=="object"&&t!==null&&"__isStorageError"in t}function um(t,e,r){let n=E({},t);for(let i of Object.keys(n))i.toLowerCase()===e.toLowerCase()&&delete n[i];return n[e]=r,n}async function Nr(t,e,r,n,i,s,o){return new Promise((a,l)=>{t(r,cm(e,n,i,s)).then(c=>{if(!c.ok)throw c;if(n?.noResolveJson)return c;if(o==="vectors"){let u=c.headers.get("content-type");if(c.headers.get("content-length")==="0"||c.status===204)return {};if(!u||!u.includes("application/json"))return {}}return c.json()}).then(c=>a(c)).catch(c=>lm(c,l,n,o));})}function hc(t="storage"){return {get:async(e,r,n,i)=>Nr(e,"GET",r,n,i,void 0,t),post:async(e,r,n,i,s)=>Nr(e,"POST",r,i,s,n,t),put:async(e,r,n,i,s)=>Nr(e,"PUT",r,i,s,n,t),head:async(e,r,n,i)=>Nr(e,"HEAD",r,E(E({},n),{},{noResolveJson:true}),i,void 0,t),remove:async(e,r,n,i,s)=>Nr(e,"DELETE",r,i,s,n,t)}}var Fn,Bn,pc,sm,om,Os,am,uc,lm,cm,dm,Dr,ge,$s,pm,Ns,re,Yt,hm,fc,fm,gm,dc,mm,_m,Mr,wm,ym,km,bm,vm,Sm,Cm,Em,gc,mc=R(()=>{lc();Fn=class extends Error{constructor(t,e="storage",r,n){super(t),this.__isStorageError=true,this.namespace=e,this.name=e==="vectors"?"StorageVectorsError":"StorageError",this.status=r,this.statusCode=n;}toJSON(){return {name:this.name,message:this.message,status:this.status,statusCode:this.statusCode}}};Bn=class extends Fn{constructor(t,e,r,n="storage"){super(t,n,e,r),this.name=n==="vectors"?"StorageVectorsApiError":"StorageApiError",this.status=e,this.statusCode=r;}toJSON(){return E({},super.toJSON())}},pc=class extends Fn{constructor(t,e,r="storage"){super(t,r),this.name=r==="vectors"?"StorageVectorsUnknownError":"StorageUnknownError",this.originalError=e;}},sm=t=>t?(...e)=>t(...e):(...e)=>fetch(...e),om=t=>{if(typeof t!="object"||t===null)return false;let e=Object.getPrototypeOf(t);return (e===null||e===Object.prototype||Object.getPrototypeOf(e)===null)&&!(Symbol.toStringTag in t)&&!(Symbol.iterator in t)},Os=t=>{if(Array.isArray(t))return t.map(r=>Os(r));if(typeof t=="function"||t!==Object(t))return t;let e={};return Object.entries(t).forEach(([r,n])=>{let i=r.replace(/([-_][a-z])/gi,s=>s.toUpperCase().replace(/[-_]/g,""));e[i]=Os(n);}),e},am=t=>!t||typeof t!="string"||t.length===0||t.length>100||t.trim()!==t||t.includes("/")||t.includes("\\")?false:/^[\w!.\*'() &$@=;:+,?-]+$/.test(t),uc=t=>{var e;return t.msg||t.message||t.error_description||(typeof t.error=="string"?t.error:(e=t.error)===null||e===void 0?void 0:e.message)||JSON.stringify(t)},lm=async(t,e,r,n)=>{if(t!==null&&typeof t=="object"&&typeof t.json=="function"){let i=t,s=parseInt(i.status,10);Number.isFinite(s)||(s=500),i.json().then(o=>{let a=o?.statusCode||o?.code||s+"";e(new Bn(uc(o),s,a,n));}).catch(()=>{let o=s+"";e(new Bn(i.statusText||`HTTP ${s} error`,s,o,n));});}else e(new pc(uc(t),t,n));},cm=(t,e,r,n)=>{let i={method:t,headers:e?.headers||{}};if(t==="GET"||t==="HEAD"||!n)return E(E({},i),r);if(om(n)){var s;let o=e?.headers||{},a;for(let[l,c]of Object.entries(o))l.toLowerCase()==="content-type"&&(a=c);i.headers=um(o,"Content-Type",(s=a)!==null&&s!==void 0?s:"application/json"),i.body=JSON.stringify(n);}else i.body=n;return e?.duplex&&(i.duplex=e.duplex),E(E({},i),r)};dm=hc("storage"),{get:Dr,post:ge,put:$s,head:pm,remove:Ns}=dm,re=hc("vectors"),Yt=class{constructor(t,e={},r,n="storage"){this.shouldThrowOnError=false,this.url=t,this.headers=Object.fromEntries(Object.entries(e).map(([i,s])=>[i.toLowerCase(),s])),this.fetch=sm(r),this.namespace=n;}throwOnError(){return this.shouldThrowOnError=true,this}setHeader(t,e){return this.headers=E(E({},this.headers),{},{[t.toLowerCase()]:e}),this}async handleOperation(t){var e=this;try{return {data:await t(),error:null}}catch(r){if(e.shouldThrowOnError)throw r;if(Hn(r))return {data:null,error:r};throw r}}},hm=class{constructor(t,e){this.downloadFn=t,this.shouldThrowOnError=e;}then(t,e){return this.execute().then(t,e)}async execute(){var t=this;try{return {data:(await t.downloadFn()).body,error:null}}catch(e){if(t.shouldThrowOnError)throw e;if(Hn(e))return {data:null,error:e};throw e}}};fc=Symbol.toStringTag;fm=class{constructor(t,e){this.downloadFn=t,this.shouldThrowOnError=e,this[fc]="BlobDownloadBuilder",this.promise=null;}asStream(){return new hm(this.downloadFn,this.shouldThrowOnError)}then(t,e){return this.getPromise().then(t,e)}catch(t){return this.getPromise().catch(t)}finally(t){return this.getPromise().finally(t)}getPromise(){return this.promise||(this.promise=this.execute()),this.promise}async execute(){var t=this;try{return {data:await(await t.downloadFn()).blob(),error:null}}catch(e){if(t.shouldThrowOnError)throw e;if(Hn(e))return {data:null,error:e};throw e}}},gm={limit:100,offset:0,sortBy:{column:"name",order:"asc"}},dc={cacheControl:"3600",contentType:"text/plain;charset=UTF-8",upsert:false},mm=class extends Yt{constructor(t,e={},r,n){super(t,e,n,"storage"),this.bucketId=r;}async uploadOrUpdate(t,e,r,n){var i=this;return i.handleOperation(async()=>{let s,o=E(E({},dc),n),a=E(E({},i.headers),t==="POST"&&{"x-upsert":String(o.upsert)}),l=o.metadata;typeof Blob<"u"&&r instanceof Blob?(s=new FormData,s.append("cacheControl",o.cacheControl),l&&s.append("metadata",i.encodeMetadata(l)),s.append("",r)):typeof FormData<"u"&&r instanceof FormData?(s=r,s.has("cacheControl")||s.append("cacheControl",o.cacheControl),l&&!s.has("metadata")&&s.append("metadata",i.encodeMetadata(l))):(s=r,a["cache-control"]=`max-age=${o.cacheControl}`,a["content-type"]=o.contentType,l&&(a["x-metadata"]=i.toBase64(i.encodeMetadata(l))),(typeof ReadableStream<"u"&&s instanceof ReadableStream||s&&typeof s=="object"&&"pipe"in s&&typeof s.pipe=="function")&&!o.duplex&&(o.duplex="half")),n?.headers&&(a=E(E({},a),n.headers));let c=i._removeEmptyFolders(e),u=i._getFinalPath(c),d=await(t=="PUT"?$s:ge)(i.fetch,`${i.url}/object/${u}`,s,E({headers:a},o?.duplex?{duplex:o.duplex}:{}));return {path:c,id:d.Id,fullPath:d.Key}})}async upload(t,e,r){return this.uploadOrUpdate("POST",t,e,r)}async uploadToSignedUrl(t,e,r,n){var i=this;let s=i._removeEmptyFolders(t),o=i._getFinalPath(s),a=new URL(i.url+`/object/upload/sign/${o}`);return a.searchParams.set("token",e),i.handleOperation(async()=>{let l,c=E(E({},dc),n),u=E(E({},i.headers),{"x-upsert":String(c.upsert)});return typeof Blob<"u"&&r instanceof Blob?(l=new FormData,l.append("cacheControl",c.cacheControl),l.append("",r)):typeof FormData<"u"&&r instanceof FormData?(l=r,l.append("cacheControl",c.cacheControl)):(l=r,u["cache-control"]=`max-age=${c.cacheControl}`,u["content-type"]=c.contentType),{path:s,fullPath:(await $s(i.fetch,a.toString(),l,{headers:u})).Key}})}async createSignedUploadUrl(t,e){var r=this;return r.handleOperation(async()=>{let n=r._getFinalPath(t),i=E({},r.headers);e?.upsert&&(i["x-upsert"]="true");let s=await ge(r.fetch,`${r.url}/object/upload/sign/${n}`,{},{headers:i}),o=new URL(r.url+s.url),a=o.searchParams.get("token");if(!a)throw new Fn("No token returned by API");return {signedUrl:o.toString(),path:t,token:a}})}async update(t,e,r){return this.uploadOrUpdate("PUT",t,e,r)}async move(t,e,r){var n=this;return n.handleOperation(async()=>await ge(n.fetch,`${n.url}/object/move`,{bucketId:n.bucketId,sourceKey:t,destinationKey:e,destinationBucket:r?.destinationBucket},{headers:n.headers}))}async copy(t,e,r){var n=this;return n.handleOperation(async()=>({path:(await ge(n.fetch,`${n.url}/object/copy`,{bucketId:n.bucketId,sourceKey:t,destinationKey:e,destinationBucket:r?.destinationBucket},{headers:n.headers})).Key}))}async createSignedUrl(t,e,r){var n=this;return n.handleOperation(async()=>{let i=n._getFinalPath(t),s=typeof r?.transform=="object"&&r.transform!==null&&Object.keys(r.transform).length>0,o=await ge(n.fetch,`${n.url}/object/sign/${i}`,E({expiresIn:e},s?{transform:r.transform}:{}),{headers:n.headers}),a=new URLSearchParams;r?.download&&a.set("download",r.download===true?"":r.download),r?.cacheNonce!=null&&a.set("cacheNonce",String(r.cacheNonce));let l=a.toString();return {signedUrl:encodeURI(`${n.url}${o.signedURL}${l?`&${l}`:""}`)}})}async createSignedUrls(t,e,r){var n=this;return n.handleOperation(async()=>{let i=await ge(n.fetch,`${n.url}/object/sign/${n.bucketId}`,{expiresIn:e,paths:t},{headers:n.headers}),s=new URLSearchParams;r?.download&&s.set("download",r.download===true?"":r.download),r?.cacheNonce!=null&&s.set("cacheNonce",String(r.cacheNonce));let o=s.toString();return i.map(a=>E(E({},a),{},{signedUrl:a.signedURL?encodeURI(`${n.url}${a.signedURL}${o?`&${o}`:""}`):null}))})}download(t,e,r){let n=typeof e?.transform=="object"&&e.transform!==null&&Object.keys(e.transform).length>0?"render/image/authenticated":"object",i=new URLSearchParams;e?.transform&&this.applyTransformOptsToQuery(i,e.transform),e?.cacheNonce!=null&&i.set("cacheNonce",String(e.cacheNonce));let s=i.toString(),o=this._getFinalPath(t),a=()=>Dr(this.fetch,`${this.url}/${n}/${o}${s?`?${s}`:""}`,{headers:this.headers,noResolveJson:true},r);return new fm(a,this.shouldThrowOnError)}async info(t){var e=this;let r=e._getFinalPath(t);return e.handleOperation(async()=>Os(await Dr(e.fetch,`${e.url}/object/info/${r}`,{headers:e.headers})))}async exists(t){var e=this;let r=e._getFinalPath(t);try{return await pm(e.fetch,`${e.url}/object/${r}`,{headers:e.headers}),{data:!0,error:null}}catch(i){if(e.shouldThrowOnError)throw i;if(Hn(i)){var n;let s=i instanceof Bn?i.status:i instanceof pc?(n=i.originalError)===null||n===void 0?void 0:n.status:void 0;if(s!==void 0&&[400,404].includes(s))return {data:false,error:i}}throw i}}getPublicUrl(t,e){let r=this._getFinalPath(t),n=new URLSearchParams;e?.download&&n.set("download",e.download===true?"":e.download),e?.transform&&this.applyTransformOptsToQuery(n,e.transform),e?.cacheNonce!=null&&n.set("cacheNonce",String(e.cacheNonce));let i=n.toString(),s=typeof e?.transform=="object"&&e.transform!==null&&Object.keys(e.transform).length>0?"render/image":"object";return {data:{publicUrl:encodeURI(`${this.url}/${s}/public/${r}`)+(i?`?${i}`:"")}}}async remove(t){var e=this;return e.handleOperation(async()=>await Ns(e.fetch,`${e.url}/object/${e.bucketId}`,{prefixes:t},{headers:e.headers}))}async list(t,e,r){var n=this;return n.handleOperation(async()=>{let i=E(E(E({},gm),e),{},{prefix:t||""});return await ge(n.fetch,`${n.url}/object/list/${n.bucketId}`,i,{headers:n.headers},r)})}async listV2(t,e){var r=this;return r.handleOperation(async()=>{let n=E({},t);return await ge(r.fetch,`${r.url}/object/list-v2/${r.bucketId}`,n,{headers:r.headers},e)})}encodeMetadata(t){return JSON.stringify(t)}toBase64(t){return typeof Buffer<"u"?Buffer.from(t).toString("base64"):btoa(t)}_getFinalPath(t){return `${this.bucketId}/${t.replace(/^\/+/,"")}`}_removeEmptyFolders(t){return t.replace(/^\/|\/$/g,"").replace(/\/+/g,"/")}applyTransformOptsToQuery(t,e){return e.width&&t.set("width",e.width.toString()),e.height&&t.set("height",e.height.toString()),e.resize&&t.set("resize",e.resize),e.format&&t.set("format",e.format),e.quality&&t.set("quality",e.quality.toString()),t}},_m="2.103.2",Mr={"X-Client-Info":`storage-js/${_m}`},wm=class extends Yt{constructor(t,e={},r,n){let i=new URL(t);n?.useNewHostname&&/supabase\.(co|in|red)$/.test(i.hostname)&&!i.hostname.includes("storage.supabase.")&&(i.hostname=i.hostname.replace("supabase.","storage.supabase."));let s=i.href.replace(/\/$/,""),o=E(E({},Mr),e);super(s,o,r,"storage");}async listBuckets(t){var e=this;return e.handleOperation(async()=>{let r=e.listBucketOptionsToQueryString(t);return await Dr(e.fetch,`${e.url}/bucket${r}`,{headers:e.headers})})}async getBucket(t){var e=this;return e.handleOperation(async()=>await Dr(e.fetch,`${e.url}/bucket/${t}`,{headers:e.headers}))}async createBucket(t,e={public:false}){var r=this;return r.handleOperation(async()=>await ge(r.fetch,`${r.url}/bucket`,{id:t,name:t,type:e.type,public:e.public,file_size_limit:e.fileSizeLimit,allowed_mime_types:e.allowedMimeTypes},{headers:r.headers}))}async updateBucket(t,e){var r=this;return r.handleOperation(async()=>await $s(r.fetch,`${r.url}/bucket/${t}`,{id:t,name:t,public:e.public,file_size_limit:e.fileSizeLimit,allowed_mime_types:e.allowedMimeTypes},{headers:r.headers}))}async emptyBucket(t){var e=this;return e.handleOperation(async()=>await ge(e.fetch,`${e.url}/bucket/${t}/empty`,{},{headers:e.headers}))}async deleteBucket(t){var e=this;return e.handleOperation(async()=>await Ns(e.fetch,`${e.url}/bucket/${t}`,{},{headers:e.headers}))}listBucketOptionsToQueryString(t){let e={};return t&&("limit"in t&&(e.limit=String(t.limit)),"offset"in t&&(e.offset=String(t.offset)),t.search&&(e.search=t.search),t.sortColumn&&(e.sortColumn=t.sortColumn),t.sortOrder&&(e.sortOrder=t.sortOrder)),Object.keys(e).length>0?"?"+new URLSearchParams(e).toString():""}},ym=class extends Yt{constructor(t,e={},r){let n=t.replace(/\/$/,""),i=E(E({},Mr),e);super(n,i,r,"storage");}async createBucket(t){var e=this;return e.handleOperation(async()=>await ge(e.fetch,`${e.url}/bucket`,{name:t},{headers:e.headers}))}async listBuckets(t){var e=this;return e.handleOperation(async()=>{let r=new URLSearchParams;t?.limit!==void 0&&r.set("limit",t.limit.toString()),t?.offset!==void 0&&r.set("offset",t.offset.toString()),t?.sortColumn&&r.set("sortColumn",t.sortColumn),t?.sortOrder&&r.set("sortOrder",t.sortOrder),t?.search&&r.set("search",t.search);let n=r.toString(),i=n?`${e.url}/bucket?${n}`:`${e.url}/bucket`;return await Dr(e.fetch,i,{headers:e.headers})})}async deleteBucket(t){var e=this;return e.handleOperation(async()=>await Ns(e.fetch,`${e.url}/bucket/${t}`,{},{headers:e.headers}))}from(t){var e=this;if(!am(t))throw new Fn("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 r=new ac({baseUrl:this.url,catalogName:t,auth:{type:"custom",getHeaders:async()=>e.headers},fetch:this.fetch}),n=this.shouldThrowOnError;return new Proxy(r,{get(i,s){let o=i[s];return typeof o!="function"?o:async(...a)=>{try{return {data:await o.apply(i,a),error:null}}catch(l){if(n)throw l;return {data:null,error:l}}}}})}},km=class extends Yt{constructor(t,e={},r){let n=t.replace(/\/$/,""),i=E(E({},Mr),{},{"Content-Type":"application/json"},e);super(n,i,r,"vectors");}async createIndex(t){var e=this;return e.handleOperation(async()=>await re.post(e.fetch,`${e.url}/CreateIndex`,t,{headers:e.headers})||{})}async getIndex(t,e){var r=this;return r.handleOperation(async()=>await re.post(r.fetch,`${r.url}/GetIndex`,{vectorBucketName:t,indexName:e},{headers:r.headers}))}async listIndexes(t){var e=this;return e.handleOperation(async()=>await re.post(e.fetch,`${e.url}/ListIndexes`,t,{headers:e.headers}))}async deleteIndex(t,e){var r=this;return r.handleOperation(async()=>await re.post(r.fetch,`${r.url}/DeleteIndex`,{vectorBucketName:t,indexName:e},{headers:r.headers})||{})}},bm=class extends Yt{constructor(t,e={},r){let n=t.replace(/\/$/,""),i=E(E({},Mr),{},{"Content-Type":"application/json"},e);super(n,i,r,"vectors");}async putVectors(t){var e=this;if(t.vectors.length<1||t.vectors.length>500)throw new Error("Vector batch size must be between 1 and 500 items");return e.handleOperation(async()=>await re.post(e.fetch,`${e.url}/PutVectors`,t,{headers:e.headers})||{})}async getVectors(t){var e=this;return e.handleOperation(async()=>await re.post(e.fetch,`${e.url}/GetVectors`,t,{headers:e.headers}))}async listVectors(t){var e=this;if(t.segmentCount!==void 0){if(t.segmentCount<1||t.segmentCount>16)throw new Error("segmentCount must be between 1 and 16");if(t.segmentIndex!==void 0&&(t.segmentIndex<0||t.segmentIndex>=t.segmentCount))throw new Error(`segmentIndex must be between 0 and ${t.segmentCount-1}`)}return e.handleOperation(async()=>await re.post(e.fetch,`${e.url}/ListVectors`,t,{headers:e.headers}))}async queryVectors(t){var e=this;return e.handleOperation(async()=>await re.post(e.fetch,`${e.url}/QueryVectors`,t,{headers:e.headers}))}async deleteVectors(t){var e=this;if(t.keys.length<1||t.keys.length>500)throw new Error("Keys batch size must be between 1 and 500 items");return e.handleOperation(async()=>await re.post(e.fetch,`${e.url}/DeleteVectors`,t,{headers:e.headers})||{})}},vm=class extends Yt{constructor(t,e={},r){let n=t.replace(/\/$/,""),i=E(E({},Mr),{},{"Content-Type":"application/json"},e);super(n,i,r,"vectors");}async createBucket(t){var e=this;return e.handleOperation(async()=>await re.post(e.fetch,`${e.url}/CreateVectorBucket`,{vectorBucketName:t},{headers:e.headers})||{})}async getBucket(t){var e=this;return e.handleOperation(async()=>await re.post(e.fetch,`${e.url}/GetVectorBucket`,{vectorBucketName:t},{headers:e.headers}))}async listBuckets(t={}){var e=this;return e.handleOperation(async()=>await re.post(e.fetch,`${e.url}/ListVectorBuckets`,t,{headers:e.headers}))}async deleteBucket(t){var e=this;return e.handleOperation(async()=>await re.post(e.fetch,`${e.url}/DeleteVectorBucket`,{vectorBucketName:t},{headers:e.headers})||{})}},Sm=class extends vm{constructor(t,e={}){super(t,e.headers||{},e.fetch);}from(t){return new Cm(this.url,this.headers,t,this.fetch)}async createBucket(t){var e=()=>super.createBucket,r=this;return e().call(r,t)}async getBucket(t){var e=()=>super.getBucket,r=this;return e().call(r,t)}async listBuckets(t={}){var e=()=>super.listBuckets,r=this;return e().call(r,t)}async deleteBucket(t){var e=()=>super.deleteBucket,r=this;return e().call(r,t)}},Cm=class extends km{constructor(t,e,r,n){super(t,e,n),this.vectorBucketName=r;}async createIndex(t){var e=()=>super.createIndex,r=this;return e().call(r,E(E({},t),{},{vectorBucketName:r.vectorBucketName}))}async listIndexes(t={}){var e=()=>super.listIndexes,r=this;return e().call(r,E(E({},t),{},{vectorBucketName:r.vectorBucketName}))}async getIndex(t){var e=()=>super.getIndex,r=this;return e().call(r,r.vectorBucketName,t)}async deleteIndex(t){var e=()=>super.deleteIndex,r=this;return e().call(r,r.vectorBucketName,t)}index(t){return new Em(this.url,this.headers,this.vectorBucketName,t,this.fetch)}},Em=class extends bm{constructor(t,e,r,n,i){super(t,e,i),this.vectorBucketName=r,this.indexName=n;}async putVectors(t){var e=()=>super.putVectors,r=this;return e().call(r,E(E({},t),{},{vectorBucketName:r.vectorBucketName,indexName:r.indexName}))}async getVectors(t){var e=()=>super.getVectors,r=this;return e().call(r,E(E({},t),{},{vectorBucketName:r.vectorBucketName,indexName:r.indexName}))}async listVectors(t={}){var e=()=>super.listVectors,r=this;return e().call(r,E(E({},t),{},{vectorBucketName:r.vectorBucketName,indexName:r.indexName}))}async queryVectors(t){var e=()=>super.queryVectors,r=this;return e().call(r,E(E({},t),{},{vectorBucketName:r.vectorBucketName,indexName:r.indexName}))}async deleteVectors(t){var e=()=>super.deleteVectors,r=this;return e().call(r,E(E({},t),{},{vectorBucketName:r.vectorBucketName,indexName:r.indexName}))}},gc=class extends wm{constructor(t,e={},r,n){super(t,e,r,n);}from(t){return new mm(this.url,this.headers,t,this.fetch)}get vectors(){return new Sm(this.url+"/vector",{headers:this.headers,fetch:this.fetch})}get analytics(){return new ym(this.url+"/iceberg",this.headers,this.fetch)}};});var qn,js=R(()=>{qn="2.103.2";});var lt,zn,Jn,_c,wc,yc,Lr,Ds,kc,bc,Kn=R(()=>{js();lt=30*1e3,zn=3,Jn=zn*lt,_c="http://localhost:9999",wc="supabase.auth.token",yc={"X-Client-Info":`gotrue-js/${qn}`},Lr="X-Supabase-Api-Version",Ds={"2024-01-01":{timestamp:Date.parse("2024-01-01T00:00:00.0Z"),name:"2024-01-01"}},kc=/^([a-z0-9_-]{4})*($|[a-z0-9_-]{3}$|[a-z0-9_-]{2}$)$/i,bc=600*1e3;});function v(t){return typeof t=="object"&&t!==null&&"__isAuthError"in t}function vc(t){return v(t)&&t.name==="AuthApiError"}function Br(t){return v(t)&&t.name==="AuthSessionMissingError"}function Sc(t){return v(t)&&t.name==="AuthImplicitGrantRedirectError"}function Yn(t){return v(t)&&t.name==="AuthRetryableFetchError"}var Je,Vn,ue,me,J,Ne,ct,ut,Ur,Gn,Xt,Wr,dt,pt=R(()=>{Je=class extends Error{constructor(e,r,n){super(e),this.__isAuthError=true,this.name="AuthError",this.status=r,this.code=n;}toJSON(){return {name:this.name,message:this.message,status:this.status,code:this.code}}};Vn=class extends Je{constructor(e,r,n){super(e,r,n),this.name="AuthApiError",this.status=r,this.code=n;}};ue=class extends Je{constructor(e,r){super(e),this.name="AuthUnknownError",this.originalError=r;}},me=class extends Je{constructor(e,r,n,i){super(e,n,i),this.name=r,this.status=n;}},J=class extends me{constructor(){super("Auth session missing!","AuthSessionMissingError",400,void 0);}};Ne=class extends me{constructor(){super("Auth session or user missing","AuthInvalidTokenResponseError",500,void 0);}},ct=class extends me{constructor(e){super(e,"AuthInvalidCredentialsError",400,void 0);}},ut=class extends me{constructor(e,r=null){super(e,"AuthImplicitGrantRedirectError",500,void 0),this.details=null,this.details=r;}toJSON(){return Object.assign(Object.assign({},super.toJSON()),{details:this.details})}};Ur=class extends me{constructor(e,r=null){super(e,"AuthPKCEGrantCodeExchangeError",500,void 0),this.details=null,this.details=r;}toJSON(){return Object.assign(Object.assign({},super.toJSON()),{details:this.details})}},Gn=class extends me{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");}},Xt=class extends me{constructor(e,r){super(e,"AuthRetryableFetchError",r,void 0);}};Wr=class extends me{constructor(e,r,n){super(e,"AuthWeakPasswordError",r,"weak_password"),this.reasons=n;}toJSON(){return Object.assign(Object.assign({},super.toJSON()),{reasons:this.reasons})}},dt=class extends me{constructor(e){super(e,"AuthInvalidJwtError",400,"invalid_jwt");}};});function Ec(t,e,r){if(t!==null)for(e.queue=e.queue<<8|t,e.queuedBits+=8;e.queuedBits>=6;){let n=e.queue>>e.queuedBits-6&63;r(Xn[n]),e.queuedBits-=6;}else if(e.queuedBits>0)for(e.queue=e.queue<<6-e.queuedBits,e.queuedBits=6;e.queuedBits>=6;){let n=e.queue>>e.queuedBits-6&63;r(Xn[n]),e.queuedBits-=6;}}function Rc(t,e,r){let n=Rm[t];if(n>-1)for(e.queue=e.queue<<6|n,e.queuedBits+=6;e.queuedBits>=8;)r(e.queue>>e.queuedBits-8&255),e.queuedBits-=8;else {if(n===-2)return;throw new Error(`Invalid Base64-URL character "${String.fromCharCode(t)}"`)}}function Ms(t){let e=[],r=o=>{e.push(String.fromCodePoint(o));},n={utf8seq:0,codepoint:0},i={queue:0,queuedBits:0},s=o=>{Tm(o,n,r);};for(let o=0;o<t.length;o+=1)Rc(t.charCodeAt(o),i,s);return e.join("")}function xm(t,e){if(t<=127){e(t);return}else if(t<=2047){e(192|t>>6),e(128|t&63);return}else if(t<=65535){e(224|t>>12),e(128|t>>6&63),e(128|t&63);return}else if(t<=1114111){e(240|t>>18),e(128|t>>12&63),e(128|t>>6&63),e(128|t&63);return}throw new Error(`Unrecognized Unicode codepoint: ${t.toString(16)}`)}function Pm(t,e){for(let r=0;r<t.length;r+=1){let n=t.charCodeAt(r);if(n>55295&&n<=56319){let i=(n-55296)*1024&65535;n=(t.charCodeAt(r+1)-56320&65535|i)+65536,r+=1;}xm(n,e);}}function Tm(t,e,r){if(e.utf8seq===0){if(t<=127){r(t);return}for(let n=1;n<6;n+=1)if((t>>7-n&1)===0){e.utf8seq=n;break}if(e.utf8seq===2)e.codepoint=t&31;else if(e.utf8seq===3)e.codepoint=t&15;else if(e.utf8seq===4)e.codepoint=t&7;else throw new Error("Invalid UTF-8 sequence");e.utf8seq-=1;}else if(e.utf8seq>0){if(t<=127)throw new Error("Invalid UTF-8 sequence");e.codepoint=e.codepoint<<6|t&63,e.utf8seq-=1,e.utf8seq===0&&r(e.codepoint);}}function Ke(t){let e=[],r={queue:0,queuedBits:0},n=i=>{e.push(i);};for(let i=0;i<t.length;i+=1)Rc(t.charCodeAt(i),r,n);return new Uint8Array(e)}function xc(t){let e=[];return Pm(t,r=>e.push(r)),new Uint8Array(e)}function je(t){let e=[],r={queue:0,queuedBits:0},n=i=>{e.push(i);};return t.forEach(i=>Ec(i,r,n)),Ec(null,r,n),e.join("")}var Xn,Cc,Rm,Zn=R(()=>{Xn="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_".split(""),Cc=`
31
- \r=`.split(""),Rm=(()=>{let t=new Array(128);for(let e=0;e<t.length;e+=1)t[e]=-1;for(let e=0;e<Cc.length;e+=1)t[Cc[e].charCodeAt(0)]=-2;for(let e=0;e<Xn.length;e+=1)t[Xn[e].charCodeAt(0)]=e;return t})();});function Pc(t){return Math.round(Date.now()/1e3)+t}function Tc(){return Symbol("auth-callback")}function Ac(t){let e={},r=new URL(t);if(r.hash&&r.hash[0]==="#")try{new URLSearchParams(r.hash.substring(1)).forEach((i,s)=>{e[s]=i;});}catch{}return r.searchParams.forEach((n,i)=>{e[i]=n;}),e}function Hr(t){let e=t.split(".");if(e.length!==3)throw new dt("Invalid JWT structure");for(let n=0;n<e.length;n++)if(!kc.test(e[n]))throw new dt("JWT not in base64url format");return {header:JSON.parse(Ms(e[0])),payload:JSON.parse(Ms(e[1])),signature:Ke(e[2]),raw:{header:e[0],payload:e[1]}}}async function Oc(t){return await new Promise(e=>{setTimeout(()=>e(null),t);})}function $c(t,e){return new Promise((n,i)=>{(async()=>{for(let s=0;s<1/0;s++)try{let o=await t(s);if(!e(s,null,o)){n(o);return}}catch(o){if(!e(s,o)){i(o);return}}})();})}function Am(t){return ("0"+t.toString(16)).substr(-2)}function Im(){let e=new Uint32Array(56);if(typeof crypto>"u"){let r="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~",n=r.length,i="";for(let s=0;s<56;s++)i+=r.charAt(Math.floor(Math.random()*n));return i}return crypto.getRandomValues(e),Array.from(e,Am).join("")}async function Om(t){let r=new TextEncoder().encode(t),n=await crypto.subtle.digest("SHA-256",r),i=new Uint8Array(n);return Array.from(i).map(s=>String.fromCharCode(s)).join("")}async function $m(t){if(!(typeof crypto<"u"&&typeof crypto.subtle<"u"&&typeof TextEncoder<"u"))return console.warn("WebCrypto API is not supported. Code challenge method will default to use plain instead of sha256."),t;let r=await Om(t);return btoa(r).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function gt(t,e,r=false){let n=Im(),i=n;r&&(i+="/PASSWORD_RECOVERY"),await ft(t,`${e}-code-verifier`,i);let s=await $m(n);return [s,n===s?"plain":"s256"]}function Nc(t){let e=t.headers.get(Lr);if(!e||!e.match(Nm))return null;try{return new Date(`${e}T00:00:00.0Z`)}catch{return null}}function jc(t){if(!t)throw new Error("Missing exp claim");let e=Math.floor(Date.now()/1e3);if(t<=e)throw new Error("JWT has expired")}function Dc(t){switch(t){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")}}function mt(t){if(!jm.test(t))throw new Error("@supabase/auth-js: Expected parameter to be UUID but is not")}function ti(){let t={};return new Proxy(t,{get:(e,r)=>{if(r==="__isUserNotAvailableProxy")return true;if(typeof r=="symbol"){let n=r.toString();if(n==="Symbol(Symbol.toPrimitive)"||n==="Symbol(Symbol.toStringTag)"||n==="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 "${r}" property of the session object is not supported. Please use getUser() instead.`)},set:(e,r)=>{throw new Error(`@supabase/auth-js: client was created with userStorage option and there was no user stored in the user storage. Setting the "${r}" property of the session object is not supported. Please use getUser() to fetch a user object you can manipulate.`)},deleteProperty:(e,r)=>{throw new Error(`@supabase/auth-js: client was created with userStorage option and there was no user stored in the user storage. Deleting the "${r}" property of the session object is not supported. Please use getUser() to fetch a user object you can manipulate.`)}})}function Mc(t,e){return new Proxy(t,{get:(r,n,i)=>{if(n==="__isInsecureUserWarningProxy")return true;if(typeof n=="symbol"){let s=n.toString();if(s==="Symbol(Symbol.toPrimitive)"||s==="Symbol(Symbol.toStringTag)"||s==="Symbol(util.inspect.custom)"||s==="Symbol(nodejs.util.inspect.custom)")return Reflect.get(r,n,i)}return !e.value&&typeof n=="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."),e.value=true),Reflect.get(r,n,i)}})}function Ls(t){return JSON.parse(JSON.stringify(t))}var q,ht,Qn,ei,Ic,ft,Ve,z,Fr,Nm,jm,Zt=R(()=>{Kn();pt();Zn();q=()=>typeof window<"u"&&typeof document<"u",ht={tested:false,writable:false},Qn=()=>{if(!q())return false;try{if(typeof globalThis.localStorage!="object")return !1}catch{return false}if(ht.tested)return ht.writable;let t=`lswt-${Math.random()}${Math.random()}`;try{globalThis.localStorage.setItem(t,t),globalThis.localStorage.removeItem(t),ht.tested=!0,ht.writable=!0;}catch{ht.tested=true,ht.writable=false;}return ht.writable};ei=t=>t?(...e)=>t(...e):(...e)=>fetch(...e),Ic=t=>typeof t=="object"&&t!==null&&"status"in t&&"ok"in t&&"json"in t&&typeof t.json=="function",ft=async(t,e,r)=>{await t.setItem(e,JSON.stringify(r));},Ve=async(t,e)=>{let r=await t.getItem(e);if(!r)return null;try{return JSON.parse(r)}catch{return r}},z=async(t,e)=>{await t.removeItem(e);},Fr=class t{constructor(){this.promise=new t.promiseConstructor((e,r)=>{this.resolve=e,this.reject=r;});}};Fr.promiseConstructor=Promise;Nm=/^2[0-9]{3}-(0[1-9]|1[0-2])-(0[1-9]|1[0-9]|2[0-9]|3[0-1])$/i;jm=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;});async function Lc(t){var e;if(!Ic(t))throw new Xt(_t(t),0);if(Dm.includes(t.status))throw new Xt(_t(t),t.status);let r;try{r=await t.json();}catch(s){throw new ue(_t(s),s)}let n,i=Nc(t);if(i&&i.getTime()>=Ds["2024-01-01"].timestamp&&typeof r=="object"&&r&&typeof r.code=="string"?n=r.code:typeof r=="object"&&r&&typeof r.error_code=="string"&&(n=r.error_code),n){if(n==="weak_password")throw new Wr(_t(r),t.status,((e=r.weak_password)===null||e===void 0?void 0:e.reasons)||[]);if(n==="session_not_found")throw new J}else if(typeof r=="object"&&r&&typeof r.weak_password=="object"&&r.weak_password&&Array.isArray(r.weak_password.reasons)&&r.weak_password.reasons.length&&r.weak_password.reasons.reduce((s,o)=>s&&typeof o=="string",true))throw new Wr(_t(r),t.status,r.weak_password.reasons);throw new Vn(_t(r),t.status||500,n)}async function S(t,e,r,n){var i;let s=Object.assign({},n?.headers);s[Lr]||(s[Lr]=Ds["2024-01-01"].name),n?.jwt&&(s.Authorization=`Bearer ${n.jwt}`);let o=(i=n?.query)!==null&&i!==void 0?i:{};n?.redirectTo&&(o.redirect_to=n.redirectTo);let a=Object.keys(o).length?"?"+new URLSearchParams(o).toString():"",l=await Lm(t,e,r+a,{headers:s,noResolveJson:n?.noResolveJson},{},n?.body);return n?.xform?n?.xform(l):{data:Object.assign({},l),error:null}}async function Lm(t,e,r,n,i,s){let o=Mm(e,n,i,s),a;try{a=await t(r,Object.assign({},o));}catch(l){throw console.error(l),new Xt(_t(l),0)}if(a.ok||await Lc(a),n?.noResolveJson)return a;try{return await a.json()}catch(l){await Lc(l);}}function de(t){var e;let r=null;Um(t)&&(r=Object.assign({},t),t.expires_at||(r.expires_at=Pc(t.expires_in)));let n=(e=t.user)!==null&&e!==void 0?e:t;return {data:{session:r,user:n},error:null}}function Us(t){let e=de(t);return !e.error&&t.weak_password&&typeof t.weak_password=="object"&&Array.isArray(t.weak_password.reasons)&&t.weak_password.reasons.length&&t.weak_password.message&&typeof t.weak_password.message=="string"&&t.weak_password.reasons.reduce((r,n)=>r&&typeof n=="string",true)&&(e.data.weak_password=t.weak_password),e}function Se(t){var e;return {data:{user:(e=t.user)!==null&&e!==void 0?e:t},error:null}}function Uc(t){return {data:t,error:null}}function Wc(t){let{action_link:e,email_otp:r,hashed_token:n,redirect_to:i,verification_type:s}=t,o=ot(t,["action_link","email_otp","hashed_token","redirect_to","verification_type"]),a={action_link:e,email_otp:r,hashed_token:n,redirect_to:i,verification_type:s},l=Object.assign({},o);return {data:{properties:a,user:l},error:null}}function Ws(t){return t}function Um(t){return t.access_token&&t.refresh_token&&t.expires_in}var _t,Dm,Mm,Bs=R(()=>{kr();Kn();Zt();pt();_t=t=>t.msg||t.message||t.error_description||t.error||JSON.stringify(t),Dm=[502,503,504,520,521,522,523,524,530];Mm=(t,e,r,n)=>{let i={method:t,headers:e?.headers||{}};return t==="GET"?i:(i.headers=Object.assign({"Content-Type":"application/json;charset=UTF-8"},e?.headers),i.body=JSON.stringify(n),Object.assign(Object.assign({},i),r))};});var ri,Fs=R(()=>{ri=["global","local","others"];});var wt,ni=R(()=>{kr();Bs();Zt();Fs();pt();wt=class{constructor({url:e="",headers:r={},fetch:n}){this.url=e,this.headers=r,this.fetch=ei(n),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)};}async signOut(e,r=ri[0]){if(ri.indexOf(r)<0)throw new Error(`@supabase/auth-js: Parameter scope must be one of ${ri.join(", ")}`);try{return await S(this.fetch,"POST",`${this.url}/logout?scope=${r}`,{headers:this.headers,jwt:e,noResolveJson:!0}),{data:null,error:null}}catch(n){if(v(n))return {data:null,error:n};throw n}}async inviteUserByEmail(e,r={}){try{return await S(this.fetch,"POST",`${this.url}/invite`,{body:{email:e,data:r.data},headers:this.headers,redirectTo:r.redirectTo,xform:Se})}catch(n){if(v(n))return {data:{user:null},error:n};throw n}}async generateLink(e){try{let{options:r}=e,n=ot(e,["options"]),i=Object.assign(Object.assign({},n),r);return "newEmail"in n&&(i.new_email=n?.newEmail,delete i.newEmail),await S(this.fetch,"POST",`${this.url}/admin/generate_link`,{body:i,headers:this.headers,xform:Wc,redirectTo:r?.redirectTo})}catch(r){if(v(r))return {data:{properties:null,user:null},error:r};throw r}}async createUser(e){try{return await S(this.fetch,"POST",`${this.url}/admin/users`,{body:e,headers:this.headers,xform:Se})}catch(r){if(v(r))return {data:{user:null},error:r};throw r}}async listUsers(e){var r,n,i,s,o,a,l;try{let c={nextPage:null,lastPage:0,total:0},u=await S(this.fetch,"GET",`${this.url}/admin/users`,{headers:this.headers,noResolveJson:!0,query:{page:(n=(r=e?.page)===null||r===void 0?void 0:r.toString())!==null&&n!==void 0?n:"",per_page:(s=(i=e?.perPage)===null||i===void 0?void 0:i.toString())!==null&&s!==void 0?s:""},xform:Ws});if(u.error)throw u.error;let d=await u.json(),p=(o=u.headers.get("x-total-count"))!==null&&o!==void 0?o:0,h=(l=(a=u.headers.get("link"))===null||a===void 0?void 0:a.split(","))!==null&&l!==void 0?l:[];return h.length>0&&(h.forEach(f=>{let m=parseInt(f.split(";")[0].split("=")[1].substring(0,1)),_=JSON.parse(f.split(";")[1].split("=")[1]);c[`${_}Page`]=m;}),c.total=parseInt(p)),{data:Object.assign(Object.assign({},d),c),error:null}}catch(c){if(v(c))return {data:{users:[]},error:c};throw c}}async getUserById(e){mt(e);try{return await S(this.fetch,"GET",`${this.url}/admin/users/${e}`,{headers:this.headers,xform:Se})}catch(r){if(v(r))return {data:{user:null},error:r};throw r}}async updateUserById(e,r){mt(e);try{return await S(this.fetch,"PUT",`${this.url}/admin/users/${e}`,{body:r,headers:this.headers,xform:Se})}catch(n){if(v(n))return {data:{user:null},error:n};throw n}}async deleteUser(e,r=false){mt(e);try{return await S(this.fetch,"DELETE",`${this.url}/admin/users/${e}`,{headers:this.headers,body:{should_soft_delete:r},xform:Se})}catch(n){if(v(n))return {data:{user:null},error:n};throw n}}async _listFactors(e){mt(e.userId);try{let{data:r,error:n}=await S(this.fetch,"GET",`${this.url}/admin/users/${e.userId}/factors`,{headers:this.headers,xform:i=>({data:{factors:i},error:null})});return {data:r,error:n}}catch(r){if(v(r))return {data:null,error:r};throw r}}async _deleteFactor(e){mt(e.userId),mt(e.id);try{return {data:await S(this.fetch,"DELETE",`${this.url}/admin/users/${e.userId}/factors/${e.id}`,{headers:this.headers}),error:null}}catch(r){if(v(r))return {data:null,error:r};throw r}}async _listOAuthClients(e){var r,n,i,s,o,a,l;try{let c={nextPage:null,lastPage:0,total:0},u=await S(this.fetch,"GET",`${this.url}/admin/oauth/clients`,{headers:this.headers,noResolveJson:!0,query:{page:(n=(r=e?.page)===null||r===void 0?void 0:r.toString())!==null&&n!==void 0?n:"",per_page:(s=(i=e?.perPage)===null||i===void 0?void 0:i.toString())!==null&&s!==void 0?s:""},xform:Ws});if(u.error)throw u.error;let d=await u.json(),p=(o=u.headers.get("x-total-count"))!==null&&o!==void 0?o:0,h=(l=(a=u.headers.get("link"))===null||a===void 0?void 0:a.split(","))!==null&&l!==void 0?l:[];return h.length>0&&(h.forEach(f=>{let m=parseInt(f.split(";")[0].split("=")[1].substring(0,1)),_=JSON.parse(f.split(";")[1].split("=")[1]);c[`${_}Page`]=m;}),c.total=parseInt(p)),{data:Object.assign(Object.assign({},d),c),error:null}}catch(c){if(v(c))return {data:{clients:[]},error:c};throw c}}async _createOAuthClient(e){try{return await S(this.fetch,"POST",`${this.url}/admin/oauth/clients`,{body:e,headers:this.headers,xform:r=>({data:r,error:null})})}catch(r){if(v(r))return {data:null,error:r};throw r}}async _getOAuthClient(e){try{return await S(this.fetch,"GET",`${this.url}/admin/oauth/clients/${e}`,{headers:this.headers,xform:r=>({data:r,error:null})})}catch(r){if(v(r))return {data:null,error:r};throw r}}async _updateOAuthClient(e,r){try{return await S(this.fetch,"PUT",`${this.url}/admin/oauth/clients/${e}`,{body:r,headers:this.headers,xform:n=>({data:n,error:null})})}catch(n){if(v(n))return {data:null,error:n};throw n}}async _deleteOAuthClient(e){try{return await S(this.fetch,"DELETE",`${this.url}/admin/oauth/clients/${e}`,{headers:this.headers,noResolveJson:!0}),{data:null,error:null}}catch(r){if(v(r))return {data:null,error:r};throw r}}async _regenerateOAuthClientSecret(e){try{return await S(this.fetch,"POST",`${this.url}/admin/oauth/clients/${e}/regenerate_secret`,{headers:this.headers,xform:r=>({data:r,error:null})})}catch(r){if(v(r))return {data:null,error:r};throw r}}async _listCustomProviders(e){try{let r={};return e?.type&&(r.type=e.type),await S(this.fetch,"GET",`${this.url}/admin/custom-providers`,{headers:this.headers,query:r,xform:n=>{var i;return {data:{providers:(i=n?.providers)!==null&&i!==void 0?i:[]},error:null}}})}catch(r){if(v(r))return {data:{providers:[]},error:r};throw r}}async _createCustomProvider(e){try{return await S(this.fetch,"POST",`${this.url}/admin/custom-providers`,{body:e,headers:this.headers,xform:r=>({data:r,error:null})})}catch(r){if(v(r))return {data:null,error:r};throw r}}async _getCustomProvider(e){try{return await S(this.fetch,"GET",`${this.url}/admin/custom-providers/${e}`,{headers:this.headers,xform:r=>({data:r,error:null})})}catch(r){if(v(r))return {data:null,error:r};throw r}}async _updateCustomProvider(e,r){try{return await S(this.fetch,"PUT",`${this.url}/admin/custom-providers/${e}`,{body:r,headers:this.headers,xform:n=>({data:n,error:null})})}catch(n){if(v(n))return {data:null,error:n};throw n}}async _deleteCustomProvider(e){try{return await S(this.fetch,"DELETE",`${this.url}/admin/custom-providers/${e}`,{headers:this.headers,noResolveJson:!0}),{data:null,error:null}}catch(r){if(v(r))return {data:null,error:r};throw r}}};});function Hs(t={}){return {getItem:e=>t[e]||null,setItem:(e,r)=>{t[e]=r;},removeItem:e=>{delete t[e];}}}var Bc=R(()=>{});async function qs(t,e,r){_e.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquire lock",t,e);let n=new globalThis.AbortController,i;e>0&&(i=setTimeout(()=>{n.abort(),_e.debug&&console.log("@supabase/gotrue-js: navigatorLock acquire timed out",t);},e)),await Promise.resolve();try{return await globalThis.navigator.locks.request(t,e===0?{mode:"exclusive",ifAvailable:!0}:{mode:"exclusive",signal:n.signal},async s=>{if(s){clearTimeout(i),_e.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquired",t,s.name);try{return await r()}finally{_e.debug&&console.log("@supabase/gotrue-js: navigatorLock: released",t,s.name);}}else {if(e===0)throw _e.debug&&console.log("@supabase/gotrue-js: navigatorLock: not immediately available",t),new zr(`Acquiring an exclusive Navigator LockManager lock "${t}" immediately failed`);if(_e.debug)try{let o=await globalThis.navigator.locks.query();console.log("@supabase/gotrue-js: Navigator LockManager state",JSON.stringify(o,null," "));}catch(o){console.warn("@supabase/gotrue-js: Error when querying Navigator LockManager state",o);}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(i),await r()}})}catch(s){if(e>0&&clearTimeout(i),s?.name==="AbortError"&&e>0){if(n.signal.aborted)return _e.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquire timeout, recovering by stealing lock",t),console.warn(`@supabase/gotrue-js: Lock "${t}" was not released within ${e}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(t,{mode:"exclusive",steal:true},async o=>{if(o){_e.debug&&console.log("@supabase/gotrue-js: navigatorLock: recovered (stolen)",t,o.name);try{return await r()}finally{_e.debug&&console.log("@supabase/gotrue-js: navigatorLock: released (stolen)",t,o.name);}}else return console.warn("@supabase/gotrue-js: Navigator LockManager returned null lock even with steal: true"),await r()}));throw _e.debug&&console.log("@supabase/gotrue-js: navigatorLock: lock was stolen by another request",t),new zr(`Lock "${t}" was released because another request stole it`)}throw s}}var _e,qr,zr,zs=R(()=>{Zt();_e={debug:!!(globalThis&&Qn()&&globalThis.localStorage&&globalThis.localStorage.getItem("supabase.gotrue-js.locks.debug")==="true")},qr=class extends Error{constructor(e){super(e),this.isAcquireTimeout=true;}},zr=class extends qr{};});function Fc(){if(typeof globalThis!="object")try{Object.defineProperty(Object.prototype,"__magic__",{get:function(){return this},configurable:!0}),__magic__.globalThis=__magic__,delete Object.prototype.__magic__;}catch{typeof self<"u"&&(self.globalThis=self);}}var Hc=R(()=>{});function Js(t){if(!/^0x[a-fA-F0-9]{40}$/.test(t))throw new Error(`@supabase/auth-js: Address "${t}" is invalid.`);return t.toLowerCase()}function qc(t){return parseInt(t,16)}function zc(t){let e=new TextEncoder().encode(t);return "0x"+Array.from(e,n=>n.toString(16).padStart(2,"0")).join("")}function Jc(t){var e;let{chainId:r,domain:n,expirationTime:i,issuedAt:s=new Date,nonce:o,notBefore:a,requestId:l,resources:c,scheme:u,uri:d,version:p}=t;{if(!Number.isInteger(r))throw new Error(`@supabase/auth-js: Invalid SIWE message field "chainId". Chain ID must be a EIP-155 chain ID. Provided value: ${r}`);if(!n)throw new Error('@supabase/auth-js: Invalid SIWE message field "domain". Domain must be provided.');if(o&&o.length<8)throw new Error(`@supabase/auth-js: Invalid SIWE message field "nonce". Nonce must be at least 8 characters. Provided value: ${o}`);if(!d)throw new Error('@supabase/auth-js: Invalid SIWE message field "uri". URI must be provided.');if(p!=="1")throw new Error(`@supabase/auth-js: Invalid SIWE message field "version". Version must be '1'. Provided value: ${p}`);if(!((e=t.statement)===null||e===void 0)&&e.includes(`
30
+ })`):new Error(`WebSocket not available: ${r}`)}this._handleNodeJsRaceCondition();}}endpointURL(){return this.socketAdapter.endPointURL()}async disconnect(e,r){return this.isDisconnecting()?"ok":await this.socketAdapter.disconnect(()=>{clearInterval(this._workerHeartbeatTimer),this._terminateWorker();},e,r)}getChannels(){return this.channels}async removeChannel(e){let r=await e.unsubscribe();return r==="ok"&&e.teardown(),this.channels.length===0&&this.disconnect(),r}async removeAllChannels(){let e=this.channels.map(async n=>{let i=await n.unsubscribe();return n.teardown(),i}),r=await Promise.all(e);return this.disconnect(),r}log(e,r,n){this.socketAdapter.log(e,r,n);}connectionState(){return this.socketAdapter.connectionState()||Er.closed}isConnected(){return this.socketAdapter.isConnected()}isConnecting(){return this.socketAdapter.isConnecting()}isDisconnecting(){return this.socketAdapter.isDisconnecting()}channel(e,r={config:{}}){let n=`realtime:${e}`,i=this.getChannels().find(s=>s.topic===n);if(i)return i;{let s=new Kt(`realtime:${e}`,r,this);return this.channels.push(s),s}}push(e){this.socketAdapter.push(e);}async setAuth(e=null){this._authPromise=this._performAuth(e);try{await this._authPromise;}finally{this._authPromise=null;}}_isManualToken(){return this._manuallySetToken}async sendHeartbeat(){this.socketAdapter.sendHeartbeat();}onHeartbeat(e){this.socketAdapter.heartbeatCallback=this._wrapHeartbeatCallback(e);}_makeRef(){return this.socketAdapter.makeRef()}_remove(e){this.channels=this.channels.filter(r=>r.topic!==e.topic);}async _performAuth(e=null){let r,n=false;if(e)r=e,n=true;else if(this.accessToken)try{r=await this.accessToken();}catch(i){this.log("error","Error fetching access token from callback",i),r=this.accessTokenValue;}else r=this.accessTokenValue;n?this._manuallySetToken=true:this.accessToken&&(this._manuallySetToken=false),this.accessTokenValue!=r&&(this.accessTokenValue=r,this.channels.forEach(i=>{let s={access_token:r,version:Jl};r&&i.updateJoinPayload(s),i.joinedOnce&&i.channelAdapter.isJoined()&&i.channelAdapter.push($n.access_token,{access_token:r});}));}async _waitForAuthIfNeeded(){this._authPromise&&await this._authPromise;}_setAuthSafely(e="general"){this._isManualToken()||this.setAuth().catch(r=>{this.log("error",`Error setting auth in ${e}`,r);});}_setupConnectionHandlers(){this.socketAdapter.onOpen(()=>{(this._authPromise||(this.accessToken&&!this.accessTokenValue?this.setAuth():Promise.resolve())).catch(r=>{this.log("error","error waiting for auth on connect",r);}),this.worker&&!this.workerRef&&this._startWorkerHeartbeat();}),this.socketAdapter.onClose(()=>{this.worker&&this.workerRef&&this._terminateWorker();}),this.socketAdapter.onMessage(e=>{e.ref&&e.ref===this._pendingWorkerHeartbeatRef&&(this._pendingWorkerHeartbeatRef=null);});}_handleNodeJsRaceCondition(){this.socketAdapter.isConnected()&&this.socketAdapter.getSocket().onConnOpen();}_wrapHeartbeatCallback(e){return (r,n)=>{r=="sent"&&this._setAuthSafely(),e&&e(r,n);}}_startWorkerHeartbeat(){this.workerUrl?this.log("worker",`starting worker for from ${this.workerUrl}`):this.log("worker","starting default worker");let e=this._workerObjectUrl(this.workerUrl);this.workerRef=new Worker(e),this.workerRef.onerror=r=>{this.log("worker","worker error",r.message),this._terminateWorker(),this.disconnect();},this.workerRef.onmessage=r=>{r.data.event==="keepAlive"&&this.sendHeartbeat();},this.workerRef.postMessage({event:"start",interval:this.heartbeatIntervalMs});}_terminateWorker(){this.workerRef&&(this.log("worker","terminating worker"),this.workerRef.terminate(),this.workerRef=void 0);}_workerObjectUrl(e){let r;if(e)r=e;else {let n=new Blob([Yg],{type:"application/javascript"});r=URL.createObjectURL(n);}return r}_initializeOptions(e){var r,n,i,s,o,a,l,c,u;this.worker=(r=e?.worker)!==null&&r!==void 0?r:false,this.accessToken=(n=e?.accessToken)!==null&&n!==void 0?n:null;let d={};d.timeout=(i=e?.timeout)!==null&&i!==void 0?i:Gl,d.heartbeatIntervalMs=(s=e?.heartbeatIntervalMs)!==null&&s!==void 0?s:Kg.HEARTBEAT_INTERVAL,d.transport=(o=e?.transport)!==null&&o!==void 0?o:ys.getWebSocketConstructor(),d.params=e?.params,d.logger=e?.logger,d.heartbeatCallback=this._wrapHeartbeatCallback(e?.heartbeatCallback),d.reconnectAfterMs=(a=e?.reconnectAfterMs)!==null&&a!==void 0?a:(m=>Vg[m-1]||Gg);let p,h,f=(l=e?.vsn)!==null&&l!==void 0?l:Vl;switch(f){case Kl:p=(m,_)=>_(JSON.stringify(m)),h=(m,_)=>_(JSON.parse(m));break;case bs:p=this.serializer.encode.bind(this.serializer),h=this.serializer.decode.bind(this.serializer);break;default:throw new Error(`Unsupported serializer version: ${d.vsn}`)}if(d.vsn=f,d.encode=(c=e?.encode)!==null&&c!==void 0?c:p,d.decode=(u=e?.decode)!==null&&u!==void 0?u:h,d.beforeReconnect=this._reconnectAuth.bind(this),(e?.logLevel||e?.log_level)&&(this.logLevel=e.logLevel||e.log_level,d.params=Object.assign(Object.assign({},d.params),{log_level:this.logLevel})),this.worker){if(typeof window<"u"&&!window.Worker)throw new Error("Web Worker is not supported");this.workerUrl=e?.workerUrl,d.autoSendHeartbeat=!this.worker;}return d}async _reconnectAuth(){await this._waitForAuthIfNeeded(),this.isConnected()||this.connect();}};});var Is=R(()=>{oc();As();Ps();ks();});function Xg(t,e,r){let n=new URL(e,t);if(r)for(let[i,s]of Object.entries(r))s!==void 0&&n.searchParams.set(i,s);return n.toString()}async function Zg(t){return !t||t.type==="none"?{}:t.type==="bearer"?{Authorization:`Bearer ${t.token}`}:t.type==="header"?{[t.name]:t.value}:t.type==="custom"?await t.getHeaders():{}}function Qg(t){let e=t.fetchImpl??globalThis.fetch;return {async request({method:r,path:n,query:i,body:s,headers:o}){let a=Xg(t.baseUrl,n,i),l=await Zg(t.auth),c=await e(a,{method:r,headers:{...s?{"Content-Type":"application/json"}:{},...l,...o},body:s?JSON.stringify(s):void 0}),u=await c.text(),d=(c.headers.get("content-type")||"").includes("application/json"),p=d&&u?JSON.parse(u):u;if(!c.ok){let h=d?p:void 0,f=h?.error;throw new $r(f?.message??`Request failed with status ${c.status}`,{status:c.status,icebergType:f?.type,icebergCode:f?.code,details:h})}return {status:c.status,headers:c.headers,data:p}}}}function Wn(t){return t.join("")}function Gt(t){return t.join("")}var $r,em,tm,ac,lc=R(()=>{$r=class extends Error{constructor(t,e){super(t),this.name="IcebergError",this.status=e.status,this.icebergType=e.icebergType,this.icebergCode=e.icebergCode,this.details=e.details,this.isCommitStateUnknown=e.icebergType==="CommitStateUnknownException"||[500,502,504].includes(e.status)&&e.icebergType?.includes("CommitState")===true;}isNotFound(){return this.status===404}isConflict(){return this.status===409}isAuthenticationTimeout(){return this.status===419}};em=class{constructor(t,e=""){this.client=t,this.prefix=e;}async listNamespaces(t){let e=t?{parent:Wn(t.namespace)}:void 0;return (await this.client.request({method:"GET",path:`${this.prefix}/namespaces`,query:e})).data.namespaces.map(n=>({namespace:n}))}async createNamespace(t,e){let r={namespace:t.namespace,properties:e?.properties};return (await this.client.request({method:"POST",path:`${this.prefix}/namespaces`,body:r})).data}async dropNamespace(t){await this.client.request({method:"DELETE",path:`${this.prefix}/namespaces/${Wn(t.namespace)}`});}async loadNamespaceMetadata(t){return {properties:(await this.client.request({method:"GET",path:`${this.prefix}/namespaces/${Wn(t.namespace)}`})).data.properties}}async namespaceExists(t){try{return await this.client.request({method:"HEAD",path:`${this.prefix}/namespaces/${Wn(t.namespace)}`}),!0}catch(e){if(e instanceof $r&&e.status===404)return false;throw e}}async createNamespaceIfNotExists(t,e){try{return await this.createNamespace(t,e)}catch(r){if(r instanceof $r&&r.status===409)return;throw r}}};tm=class{constructor(t,e="",r){this.client=t,this.prefix=e,this.accessDelegation=r;}async listTables(t){return (await this.client.request({method:"GET",path:`${this.prefix}/namespaces/${Gt(t.namespace)}/tables`})).data.identifiers}async createTable(t,e){let r={};return this.accessDelegation&&(r["X-Iceberg-Access-Delegation"]=this.accessDelegation),(await this.client.request({method:"POST",path:`${this.prefix}/namespaces/${Gt(t.namespace)}/tables`,body:e,headers:r})).data.metadata}async updateTable(t,e){let r=await this.client.request({method:"POST",path:`${this.prefix}/namespaces/${Gt(t.namespace)}/tables/${t.name}`,body:e});return {"metadata-location":r.data["metadata-location"],metadata:r.data.metadata}}async dropTable(t,e){await this.client.request({method:"DELETE",path:`${this.prefix}/namespaces/${Gt(t.namespace)}/tables/${t.name}`,query:{purgeRequested:String(e?.purge??false)}});}async loadTable(t){let e={};return this.accessDelegation&&(e["X-Iceberg-Access-Delegation"]=this.accessDelegation),(await this.client.request({method:"GET",path:`${this.prefix}/namespaces/${Gt(t.namespace)}/tables/${t.name}`,headers:e})).data.metadata}async tableExists(t){let e={};this.accessDelegation&&(e["X-Iceberg-Access-Delegation"]=this.accessDelegation);try{return await this.client.request({method:"HEAD",path:`${this.prefix}/namespaces/${Gt(t.namespace)}/tables/${t.name}`,headers:e}),!0}catch(r){if(r instanceof $r&&r.status===404)return false;throw r}}async createTableIfNotExists(t,e){try{return await this.createTable(t,e)}catch(r){if(r instanceof $r&&r.status===409)return await this.loadTable({namespace:t.namespace,name:e.name});throw r}}},ac=class{constructor(t){let e="v1";t.catalogName&&(e+=`/${t.catalogName}`);let r=t.baseUrl.endsWith("/")?t.baseUrl:`${t.baseUrl}/`;this.client=Qg({baseUrl:r,auth:t.auth,fetchImpl:t.fetch}),this.accessDelegation=t.accessDelegation?.join(","),this.namespaceOps=new em(this.client,e),this.tableOps=new tm(this.client,e,this.accessDelegation);}async listNamespaces(t){return this.namespaceOps.listNamespaces(t)}async createNamespace(t,e){return this.namespaceOps.createNamespace(t,e)}async dropNamespace(t){await this.namespaceOps.dropNamespace(t);}async loadNamespaceMetadata(t){return this.namespaceOps.loadNamespaceMetadata(t)}async listTables(t){return this.tableOps.listTables(t)}async createTable(t,e){return this.tableOps.createTable(t,e)}async updateTable(t,e){return this.tableOps.updateTable(t,e)}async dropTable(t,e){await this.tableOps.dropTable(t,e);}async loadTable(t){return this.tableOps.loadTable(t)}async namespaceExists(t){return this.namespaceOps.namespaceExists(t)}async tableExists(t){return this.tableOps.tableExists(t)}async createNamespaceIfNotExists(t,e){return this.namespaceOps.createNamespaceIfNotExists(t,e)}async createTableIfNotExists(t,e){return this.tableOps.createTableIfNotExists(t,e)}};});function Dr(t){"@babel/helpers - typeof";return Dr=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(e){return typeof e}:function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},Dr(t)}function rm(t,e){if(Dr(t)!="object"||!t)return t;var r=t[Symbol.toPrimitive];if(r!==void 0){var n=r.call(t,e);if(Dr(n)!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return (e==="string"?String:Number)(t)}function nm(t){var e=rm(t,"string");return Dr(e)=="symbol"?e:e+""}function im(t,e,r){return (e=nm(e))in t?Object.defineProperty(t,e,{value:r,enumerable:true,configurable:true,writable:true}):t[e]=r,t}function cc(t,e){var r=Object.keys(t);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(t);e&&(n=n.filter(function(i){return Object.getOwnPropertyDescriptor(t,i).enumerable})),r.push.apply(r,n);}return r}function E(t){for(var e=1;e<arguments.length;e++){var r=arguments[e]!=null?arguments[e]:{};e%2?cc(Object(r),true).forEach(function(n){im(t,n,r[n]);}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(r)):cc(Object(r)).forEach(function(n){Object.defineProperty(t,n,Object.getOwnPropertyDescriptor(r,n));});}return t}function Hn(t){return typeof t=="object"&&t!==null&&"__isStorageError"in t}function um(t,e,r){let n=E({},t);for(let i of Object.keys(n))i.toLowerCase()===e.toLowerCase()&&delete n[i];return n[e]=r,n}async function Nr(t,e,r,n,i,s,o){return new Promise((a,l)=>{t(r,cm(e,n,i,s)).then(c=>{if(!c.ok)throw c;if(n?.noResolveJson)return c;if(o==="vectors"){let u=c.headers.get("content-type");if(c.headers.get("content-length")==="0"||c.status===204)return {};if(!u||!u.includes("application/json"))return {}}return c.json()}).then(c=>a(c)).catch(c=>lm(c,l,n,o));})}function hc(t="storage"){return {get:async(e,r,n,i)=>Nr(e,"GET",r,n,i,void 0,t),post:async(e,r,n,i,s)=>Nr(e,"POST",r,i,s,n,t),put:async(e,r,n,i,s)=>Nr(e,"PUT",r,i,s,n,t),head:async(e,r,n,i)=>Nr(e,"HEAD",r,E(E({},n),{},{noResolveJson:true}),i,void 0,t),remove:async(e,r,n,i,s)=>Nr(e,"DELETE",r,i,s,n,t)}}var Fn,Bn,pc,sm,om,Os,am,uc,lm,cm,dm,jr,ge,$s,pm,Ns,re,Yt,hm,fc,fm,gm,dc,mm,_m,Mr,wm,ym,km,bm,vm,Sm,Cm,Em,gc,mc=R(()=>{lc();Fn=class extends Error{constructor(t,e="storage",r,n){super(t),this.__isStorageError=true,this.namespace=e,this.name=e==="vectors"?"StorageVectorsError":"StorageError",this.status=r,this.statusCode=n;}toJSON(){return {name:this.name,message:this.message,status:this.status,statusCode:this.statusCode}}};Bn=class extends Fn{constructor(t,e,r,n="storage"){super(t,n,e,r),this.name=n==="vectors"?"StorageVectorsApiError":"StorageApiError",this.status=e,this.statusCode=r;}toJSON(){return E({},super.toJSON())}},pc=class extends Fn{constructor(t,e,r="storage"){super(t,r),this.name=r==="vectors"?"StorageVectorsUnknownError":"StorageUnknownError",this.originalError=e;}},sm=t=>t?(...e)=>t(...e):(...e)=>fetch(...e),om=t=>{if(typeof t!="object"||t===null)return false;let e=Object.getPrototypeOf(t);return (e===null||e===Object.prototype||Object.getPrototypeOf(e)===null)&&!(Symbol.toStringTag in t)&&!(Symbol.iterator in t)},Os=t=>{if(Array.isArray(t))return t.map(r=>Os(r));if(typeof t=="function"||t!==Object(t))return t;let e={};return Object.entries(t).forEach(([r,n])=>{let i=r.replace(/([-_][a-z])/gi,s=>s.toUpperCase().replace(/[-_]/g,""));e[i]=Os(n);}),e},am=t=>!t||typeof t!="string"||t.length===0||t.length>100||t.trim()!==t||t.includes("/")||t.includes("\\")?false:/^[\w!.\*'() &$@=;:+,?-]+$/.test(t),uc=t=>{var e;return t.msg||t.message||t.error_description||(typeof t.error=="string"?t.error:(e=t.error)===null||e===void 0?void 0:e.message)||JSON.stringify(t)},lm=async(t,e,r,n)=>{if(t!==null&&typeof t=="object"&&typeof t.json=="function"){let i=t,s=parseInt(i.status,10);Number.isFinite(s)||(s=500),i.json().then(o=>{let a=o?.statusCode||o?.code||s+"";e(new Bn(uc(o),s,a,n));}).catch(()=>{let o=s+"";e(new Bn(i.statusText||`HTTP ${s} error`,s,o,n));});}else e(new pc(uc(t),t,n));},cm=(t,e,r,n)=>{let i={method:t,headers:e?.headers||{}};if(t==="GET"||t==="HEAD"||!n)return E(E({},i),r);if(om(n)){var s;let o=e?.headers||{},a;for(let[l,c]of Object.entries(o))l.toLowerCase()==="content-type"&&(a=c);i.headers=um(o,"Content-Type",(s=a)!==null&&s!==void 0?s:"application/json"),i.body=JSON.stringify(n);}else i.body=n;return e?.duplex&&(i.duplex=e.duplex),E(E({},i),r)};dm=hc("storage"),{get:jr,post:ge,put:$s,head:pm,remove:Ns}=dm,re=hc("vectors"),Yt=class{constructor(t,e={},r,n="storage"){this.shouldThrowOnError=false,this.url=t,this.headers=Object.fromEntries(Object.entries(e).map(([i,s])=>[i.toLowerCase(),s])),this.fetch=sm(r),this.namespace=n;}throwOnError(){return this.shouldThrowOnError=true,this}setHeader(t,e){return this.headers=E(E({},this.headers),{},{[t.toLowerCase()]:e}),this}async handleOperation(t){var e=this;try{return {data:await t(),error:null}}catch(r){if(e.shouldThrowOnError)throw r;if(Hn(r))return {data:null,error:r};throw r}}},hm=class{constructor(t,e){this.downloadFn=t,this.shouldThrowOnError=e;}then(t,e){return this.execute().then(t,e)}async execute(){var t=this;try{return {data:(await t.downloadFn()).body,error:null}}catch(e){if(t.shouldThrowOnError)throw e;if(Hn(e))return {data:null,error:e};throw e}}};fc=Symbol.toStringTag;fm=class{constructor(t,e){this.downloadFn=t,this.shouldThrowOnError=e,this[fc]="BlobDownloadBuilder",this.promise=null;}asStream(){return new hm(this.downloadFn,this.shouldThrowOnError)}then(t,e){return this.getPromise().then(t,e)}catch(t){return this.getPromise().catch(t)}finally(t){return this.getPromise().finally(t)}getPromise(){return this.promise||(this.promise=this.execute()),this.promise}async execute(){var t=this;try{return {data:await(await t.downloadFn()).blob(),error:null}}catch(e){if(t.shouldThrowOnError)throw e;if(Hn(e))return {data:null,error:e};throw e}}},gm={limit:100,offset:0,sortBy:{column:"name",order:"asc"}},dc={cacheControl:"3600",contentType:"text/plain;charset=UTF-8",upsert:false},mm=class extends Yt{constructor(t,e={},r,n){super(t,e,n,"storage"),this.bucketId=r;}async uploadOrUpdate(t,e,r,n){var i=this;return i.handleOperation(async()=>{let s,o=E(E({},dc),n),a=E(E({},i.headers),t==="POST"&&{"x-upsert":String(o.upsert)}),l=o.metadata;typeof Blob<"u"&&r instanceof Blob?(s=new FormData,s.append("cacheControl",o.cacheControl),l&&s.append("metadata",i.encodeMetadata(l)),s.append("",r)):typeof FormData<"u"&&r instanceof FormData?(s=r,s.has("cacheControl")||s.append("cacheControl",o.cacheControl),l&&!s.has("metadata")&&s.append("metadata",i.encodeMetadata(l))):(s=r,a["cache-control"]=`max-age=${o.cacheControl}`,a["content-type"]=o.contentType,l&&(a["x-metadata"]=i.toBase64(i.encodeMetadata(l))),(typeof ReadableStream<"u"&&s instanceof ReadableStream||s&&typeof s=="object"&&"pipe"in s&&typeof s.pipe=="function")&&!o.duplex&&(o.duplex="half")),n?.headers&&(a=E(E({},a),n.headers));let c=i._removeEmptyFolders(e),u=i._getFinalPath(c),d=await(t=="PUT"?$s:ge)(i.fetch,`${i.url}/object/${u}`,s,E({headers:a},o?.duplex?{duplex:o.duplex}:{}));return {path:c,id:d.Id,fullPath:d.Key}})}async upload(t,e,r){return this.uploadOrUpdate("POST",t,e,r)}async uploadToSignedUrl(t,e,r,n){var i=this;let s=i._removeEmptyFolders(t),o=i._getFinalPath(s),a=new URL(i.url+`/object/upload/sign/${o}`);return a.searchParams.set("token",e),i.handleOperation(async()=>{let l,c=E(E({},dc),n),u=E(E({},i.headers),{"x-upsert":String(c.upsert)});return typeof Blob<"u"&&r instanceof Blob?(l=new FormData,l.append("cacheControl",c.cacheControl),l.append("",r)):typeof FormData<"u"&&r instanceof FormData?(l=r,l.append("cacheControl",c.cacheControl)):(l=r,u["cache-control"]=`max-age=${c.cacheControl}`,u["content-type"]=c.contentType),{path:s,fullPath:(await $s(i.fetch,a.toString(),l,{headers:u})).Key}})}async createSignedUploadUrl(t,e){var r=this;return r.handleOperation(async()=>{let n=r._getFinalPath(t),i=E({},r.headers);e?.upsert&&(i["x-upsert"]="true");let s=await ge(r.fetch,`${r.url}/object/upload/sign/${n}`,{},{headers:i}),o=new URL(r.url+s.url),a=o.searchParams.get("token");if(!a)throw new Fn("No token returned by API");return {signedUrl:o.toString(),path:t,token:a}})}async update(t,e,r){return this.uploadOrUpdate("PUT",t,e,r)}async move(t,e,r){var n=this;return n.handleOperation(async()=>await ge(n.fetch,`${n.url}/object/move`,{bucketId:n.bucketId,sourceKey:t,destinationKey:e,destinationBucket:r?.destinationBucket},{headers:n.headers}))}async copy(t,e,r){var n=this;return n.handleOperation(async()=>({path:(await ge(n.fetch,`${n.url}/object/copy`,{bucketId:n.bucketId,sourceKey:t,destinationKey:e,destinationBucket:r?.destinationBucket},{headers:n.headers})).Key}))}async createSignedUrl(t,e,r){var n=this;return n.handleOperation(async()=>{let i=n._getFinalPath(t),s=typeof r?.transform=="object"&&r.transform!==null&&Object.keys(r.transform).length>0,o=await ge(n.fetch,`${n.url}/object/sign/${i}`,E({expiresIn:e},s?{transform:r.transform}:{}),{headers:n.headers}),a=new URLSearchParams;r?.download&&a.set("download",r.download===true?"":r.download),r?.cacheNonce!=null&&a.set("cacheNonce",String(r.cacheNonce));let l=a.toString();return {signedUrl:encodeURI(`${n.url}${o.signedURL}${l?`&${l}`:""}`)}})}async createSignedUrls(t,e,r){var n=this;return n.handleOperation(async()=>{let i=await ge(n.fetch,`${n.url}/object/sign/${n.bucketId}`,{expiresIn:e,paths:t},{headers:n.headers}),s=new URLSearchParams;r?.download&&s.set("download",r.download===true?"":r.download),r?.cacheNonce!=null&&s.set("cacheNonce",String(r.cacheNonce));let o=s.toString();return i.map(a=>E(E({},a),{},{signedUrl:a.signedURL?encodeURI(`${n.url}${a.signedURL}${o?`&${o}`:""}`):null}))})}download(t,e,r){let n=typeof e?.transform=="object"&&e.transform!==null&&Object.keys(e.transform).length>0?"render/image/authenticated":"object",i=new URLSearchParams;e?.transform&&this.applyTransformOptsToQuery(i,e.transform),e?.cacheNonce!=null&&i.set("cacheNonce",String(e.cacheNonce));let s=i.toString(),o=this._getFinalPath(t),a=()=>jr(this.fetch,`${this.url}/${n}/${o}${s?`?${s}`:""}`,{headers:this.headers,noResolveJson:true},r);return new fm(a,this.shouldThrowOnError)}async info(t){var e=this;let r=e._getFinalPath(t);return e.handleOperation(async()=>Os(await jr(e.fetch,`${e.url}/object/info/${r}`,{headers:e.headers})))}async exists(t){var e=this;let r=e._getFinalPath(t);try{return await pm(e.fetch,`${e.url}/object/${r}`,{headers:e.headers}),{data:!0,error:null}}catch(i){if(e.shouldThrowOnError)throw i;if(Hn(i)){var n;let s=i instanceof Bn?i.status:i instanceof pc?(n=i.originalError)===null||n===void 0?void 0:n.status:void 0;if(s!==void 0&&[400,404].includes(s))return {data:false,error:i}}throw i}}getPublicUrl(t,e){let r=this._getFinalPath(t),n=new URLSearchParams;e?.download&&n.set("download",e.download===true?"":e.download),e?.transform&&this.applyTransformOptsToQuery(n,e.transform),e?.cacheNonce!=null&&n.set("cacheNonce",String(e.cacheNonce));let i=n.toString(),s=typeof e?.transform=="object"&&e.transform!==null&&Object.keys(e.transform).length>0?"render/image":"object";return {data:{publicUrl:encodeURI(`${this.url}/${s}/public/${r}`)+(i?`?${i}`:"")}}}async remove(t){var e=this;return e.handleOperation(async()=>await Ns(e.fetch,`${e.url}/object/${e.bucketId}`,{prefixes:t},{headers:e.headers}))}async list(t,e,r){var n=this;return n.handleOperation(async()=>{let i=E(E(E({},gm),e),{},{prefix:t||""});return await ge(n.fetch,`${n.url}/object/list/${n.bucketId}`,i,{headers:n.headers},r)})}async listV2(t,e){var r=this;return r.handleOperation(async()=>{let n=E({},t);return await ge(r.fetch,`${r.url}/object/list-v2/${r.bucketId}`,n,{headers:r.headers},e)})}encodeMetadata(t){return JSON.stringify(t)}toBase64(t){return typeof Buffer<"u"?Buffer.from(t).toString("base64"):btoa(t)}_getFinalPath(t){return `${this.bucketId}/${t.replace(/^\/+/,"")}`}_removeEmptyFolders(t){return t.replace(/^\/|\/$/g,"").replace(/\/+/g,"/")}applyTransformOptsToQuery(t,e){return e.width&&t.set("width",e.width.toString()),e.height&&t.set("height",e.height.toString()),e.resize&&t.set("resize",e.resize),e.format&&t.set("format",e.format),e.quality&&t.set("quality",e.quality.toString()),t}},_m="2.103.2",Mr={"X-Client-Info":`storage-js/${_m}`},wm=class extends Yt{constructor(t,e={},r,n){let i=new URL(t);n?.useNewHostname&&/supabase\.(co|in|red)$/.test(i.hostname)&&!i.hostname.includes("storage.supabase.")&&(i.hostname=i.hostname.replace("supabase.","storage.supabase."));let s=i.href.replace(/\/$/,""),o=E(E({},Mr),e);super(s,o,r,"storage");}async listBuckets(t){var e=this;return e.handleOperation(async()=>{let r=e.listBucketOptionsToQueryString(t);return await jr(e.fetch,`${e.url}/bucket${r}`,{headers:e.headers})})}async getBucket(t){var e=this;return e.handleOperation(async()=>await jr(e.fetch,`${e.url}/bucket/${t}`,{headers:e.headers}))}async createBucket(t,e={public:false}){var r=this;return r.handleOperation(async()=>await ge(r.fetch,`${r.url}/bucket`,{id:t,name:t,type:e.type,public:e.public,file_size_limit:e.fileSizeLimit,allowed_mime_types:e.allowedMimeTypes},{headers:r.headers}))}async updateBucket(t,e){var r=this;return r.handleOperation(async()=>await $s(r.fetch,`${r.url}/bucket/${t}`,{id:t,name:t,public:e.public,file_size_limit:e.fileSizeLimit,allowed_mime_types:e.allowedMimeTypes},{headers:r.headers}))}async emptyBucket(t){var e=this;return e.handleOperation(async()=>await ge(e.fetch,`${e.url}/bucket/${t}/empty`,{},{headers:e.headers}))}async deleteBucket(t){var e=this;return e.handleOperation(async()=>await Ns(e.fetch,`${e.url}/bucket/${t}`,{},{headers:e.headers}))}listBucketOptionsToQueryString(t){let e={};return t&&("limit"in t&&(e.limit=String(t.limit)),"offset"in t&&(e.offset=String(t.offset)),t.search&&(e.search=t.search),t.sortColumn&&(e.sortColumn=t.sortColumn),t.sortOrder&&(e.sortOrder=t.sortOrder)),Object.keys(e).length>0?"?"+new URLSearchParams(e).toString():""}},ym=class extends Yt{constructor(t,e={},r){let n=t.replace(/\/$/,""),i=E(E({},Mr),e);super(n,i,r,"storage");}async createBucket(t){var e=this;return e.handleOperation(async()=>await ge(e.fetch,`${e.url}/bucket`,{name:t},{headers:e.headers}))}async listBuckets(t){var e=this;return e.handleOperation(async()=>{let r=new URLSearchParams;t?.limit!==void 0&&r.set("limit",t.limit.toString()),t?.offset!==void 0&&r.set("offset",t.offset.toString()),t?.sortColumn&&r.set("sortColumn",t.sortColumn),t?.sortOrder&&r.set("sortOrder",t.sortOrder),t?.search&&r.set("search",t.search);let n=r.toString(),i=n?`${e.url}/bucket?${n}`:`${e.url}/bucket`;return await jr(e.fetch,i,{headers:e.headers})})}async deleteBucket(t){var e=this;return e.handleOperation(async()=>await Ns(e.fetch,`${e.url}/bucket/${t}`,{},{headers:e.headers}))}from(t){var e=this;if(!am(t))throw new Fn("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 r=new ac({baseUrl:this.url,catalogName:t,auth:{type:"custom",getHeaders:async()=>e.headers},fetch:this.fetch}),n=this.shouldThrowOnError;return new Proxy(r,{get(i,s){let o=i[s];return typeof o!="function"?o:async(...a)=>{try{return {data:await o.apply(i,a),error:null}}catch(l){if(n)throw l;return {data:null,error:l}}}}})}},km=class extends Yt{constructor(t,e={},r){let n=t.replace(/\/$/,""),i=E(E({},Mr),{},{"Content-Type":"application/json"},e);super(n,i,r,"vectors");}async createIndex(t){var e=this;return e.handleOperation(async()=>await re.post(e.fetch,`${e.url}/CreateIndex`,t,{headers:e.headers})||{})}async getIndex(t,e){var r=this;return r.handleOperation(async()=>await re.post(r.fetch,`${r.url}/GetIndex`,{vectorBucketName:t,indexName:e},{headers:r.headers}))}async listIndexes(t){var e=this;return e.handleOperation(async()=>await re.post(e.fetch,`${e.url}/ListIndexes`,t,{headers:e.headers}))}async deleteIndex(t,e){var r=this;return r.handleOperation(async()=>await re.post(r.fetch,`${r.url}/DeleteIndex`,{vectorBucketName:t,indexName:e},{headers:r.headers})||{})}},bm=class extends Yt{constructor(t,e={},r){let n=t.replace(/\/$/,""),i=E(E({},Mr),{},{"Content-Type":"application/json"},e);super(n,i,r,"vectors");}async putVectors(t){var e=this;if(t.vectors.length<1||t.vectors.length>500)throw new Error("Vector batch size must be between 1 and 500 items");return e.handleOperation(async()=>await re.post(e.fetch,`${e.url}/PutVectors`,t,{headers:e.headers})||{})}async getVectors(t){var e=this;return e.handleOperation(async()=>await re.post(e.fetch,`${e.url}/GetVectors`,t,{headers:e.headers}))}async listVectors(t){var e=this;if(t.segmentCount!==void 0){if(t.segmentCount<1||t.segmentCount>16)throw new Error("segmentCount must be between 1 and 16");if(t.segmentIndex!==void 0&&(t.segmentIndex<0||t.segmentIndex>=t.segmentCount))throw new Error(`segmentIndex must be between 0 and ${t.segmentCount-1}`)}return e.handleOperation(async()=>await re.post(e.fetch,`${e.url}/ListVectors`,t,{headers:e.headers}))}async queryVectors(t){var e=this;return e.handleOperation(async()=>await re.post(e.fetch,`${e.url}/QueryVectors`,t,{headers:e.headers}))}async deleteVectors(t){var e=this;if(t.keys.length<1||t.keys.length>500)throw new Error("Keys batch size must be between 1 and 500 items");return e.handleOperation(async()=>await re.post(e.fetch,`${e.url}/DeleteVectors`,t,{headers:e.headers})||{})}},vm=class extends Yt{constructor(t,e={},r){let n=t.replace(/\/$/,""),i=E(E({},Mr),{},{"Content-Type":"application/json"},e);super(n,i,r,"vectors");}async createBucket(t){var e=this;return e.handleOperation(async()=>await re.post(e.fetch,`${e.url}/CreateVectorBucket`,{vectorBucketName:t},{headers:e.headers})||{})}async getBucket(t){var e=this;return e.handleOperation(async()=>await re.post(e.fetch,`${e.url}/GetVectorBucket`,{vectorBucketName:t},{headers:e.headers}))}async listBuckets(t={}){var e=this;return e.handleOperation(async()=>await re.post(e.fetch,`${e.url}/ListVectorBuckets`,t,{headers:e.headers}))}async deleteBucket(t){var e=this;return e.handleOperation(async()=>await re.post(e.fetch,`${e.url}/DeleteVectorBucket`,{vectorBucketName:t},{headers:e.headers})||{})}},Sm=class extends vm{constructor(t,e={}){super(t,e.headers||{},e.fetch);}from(t){return new Cm(this.url,this.headers,t,this.fetch)}async createBucket(t){var e=()=>super.createBucket,r=this;return e().call(r,t)}async getBucket(t){var e=()=>super.getBucket,r=this;return e().call(r,t)}async listBuckets(t={}){var e=()=>super.listBuckets,r=this;return e().call(r,t)}async deleteBucket(t){var e=()=>super.deleteBucket,r=this;return e().call(r,t)}},Cm=class extends km{constructor(t,e,r,n){super(t,e,n),this.vectorBucketName=r;}async createIndex(t){var e=()=>super.createIndex,r=this;return e().call(r,E(E({},t),{},{vectorBucketName:r.vectorBucketName}))}async listIndexes(t={}){var e=()=>super.listIndexes,r=this;return e().call(r,E(E({},t),{},{vectorBucketName:r.vectorBucketName}))}async getIndex(t){var e=()=>super.getIndex,r=this;return e().call(r,r.vectorBucketName,t)}async deleteIndex(t){var e=()=>super.deleteIndex,r=this;return e().call(r,r.vectorBucketName,t)}index(t){return new Em(this.url,this.headers,this.vectorBucketName,t,this.fetch)}},Em=class extends bm{constructor(t,e,r,n,i){super(t,e,i),this.vectorBucketName=r,this.indexName=n;}async putVectors(t){var e=()=>super.putVectors,r=this;return e().call(r,E(E({},t),{},{vectorBucketName:r.vectorBucketName,indexName:r.indexName}))}async getVectors(t){var e=()=>super.getVectors,r=this;return e().call(r,E(E({},t),{},{vectorBucketName:r.vectorBucketName,indexName:r.indexName}))}async listVectors(t={}){var e=()=>super.listVectors,r=this;return e().call(r,E(E({},t),{},{vectorBucketName:r.vectorBucketName,indexName:r.indexName}))}async queryVectors(t){var e=()=>super.queryVectors,r=this;return e().call(r,E(E({},t),{},{vectorBucketName:r.vectorBucketName,indexName:r.indexName}))}async deleteVectors(t){var e=()=>super.deleteVectors,r=this;return e().call(r,E(E({},t),{},{vectorBucketName:r.vectorBucketName,indexName:r.indexName}))}},gc=class extends wm{constructor(t,e={},r,n){super(t,e,r,n);}from(t){return new mm(this.url,this.headers,t,this.fetch)}get vectors(){return new Sm(this.url+"/vector",{headers:this.headers,fetch:this.fetch})}get analytics(){return new ym(this.url+"/iceberg",this.headers,this.fetch)}};});var qn,Ds=R(()=>{qn="2.103.2";});var lt,zn,Jn,_c,wc,yc,Lr,js,kc,bc,Kn=R(()=>{Ds();lt=30*1e3,zn=3,Jn=zn*lt,_c="http://localhost:9999",wc="supabase.auth.token",yc={"X-Client-Info":`gotrue-js/${qn}`},Lr="X-Supabase-Api-Version",js={"2024-01-01":{timestamp:Date.parse("2024-01-01T00:00:00.0Z"),name:"2024-01-01"}},kc=/^([a-z0-9_-]{4})*($|[a-z0-9_-]{3}$|[a-z0-9_-]{2}$)$/i,bc=600*1e3;});function v(t){return typeof t=="object"&&t!==null&&"__isAuthError"in t}function vc(t){return v(t)&&t.name==="AuthApiError"}function Br(t){return v(t)&&t.name==="AuthSessionMissingError"}function Sc(t){return v(t)&&t.name==="AuthImplicitGrantRedirectError"}function Yn(t){return v(t)&&t.name==="AuthRetryableFetchError"}var Je,Vn,ue,me,J,Ne,ct,ut,Ur,Gn,Xt,Wr,dt,pt=R(()=>{Je=class extends Error{constructor(e,r,n){super(e),this.__isAuthError=true,this.name="AuthError",this.status=r,this.code=n;}toJSON(){return {name:this.name,message:this.message,status:this.status,code:this.code}}};Vn=class extends Je{constructor(e,r,n){super(e,r,n),this.name="AuthApiError",this.status=r,this.code=n;}};ue=class extends Je{constructor(e,r){super(e),this.name="AuthUnknownError",this.originalError=r;}},me=class extends Je{constructor(e,r,n,i){super(e,n,i),this.name=r,this.status=n;}},J=class extends me{constructor(){super("Auth session missing!","AuthSessionMissingError",400,void 0);}};Ne=class extends me{constructor(){super("Auth session or user missing","AuthInvalidTokenResponseError",500,void 0);}},ct=class extends me{constructor(e){super(e,"AuthInvalidCredentialsError",400,void 0);}},ut=class extends me{constructor(e,r=null){super(e,"AuthImplicitGrantRedirectError",500,void 0),this.details=null,this.details=r;}toJSON(){return Object.assign(Object.assign({},super.toJSON()),{details:this.details})}};Ur=class extends me{constructor(e,r=null){super(e,"AuthPKCEGrantCodeExchangeError",500,void 0),this.details=null,this.details=r;}toJSON(){return Object.assign(Object.assign({},super.toJSON()),{details:this.details})}},Gn=class extends me{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");}},Xt=class extends me{constructor(e,r){super(e,"AuthRetryableFetchError",r,void 0);}};Wr=class extends me{constructor(e,r,n){super(e,"AuthWeakPasswordError",r,"weak_password"),this.reasons=n;}toJSON(){return Object.assign(Object.assign({},super.toJSON()),{reasons:this.reasons})}},dt=class extends me{constructor(e){super(e,"AuthInvalidJwtError",400,"invalid_jwt");}};});function Ec(t,e,r){if(t!==null)for(e.queue=e.queue<<8|t,e.queuedBits+=8;e.queuedBits>=6;){let n=e.queue>>e.queuedBits-6&63;r(Xn[n]),e.queuedBits-=6;}else if(e.queuedBits>0)for(e.queue=e.queue<<6-e.queuedBits,e.queuedBits=6;e.queuedBits>=6;){let n=e.queue>>e.queuedBits-6&63;r(Xn[n]),e.queuedBits-=6;}}function Rc(t,e,r){let n=Rm[t];if(n>-1)for(e.queue=e.queue<<6|n,e.queuedBits+=6;e.queuedBits>=8;)r(e.queue>>e.queuedBits-8&255),e.queuedBits-=8;else {if(n===-2)return;throw new Error(`Invalid Base64-URL character "${String.fromCharCode(t)}"`)}}function Ms(t){let e=[],r=o=>{e.push(String.fromCodePoint(o));},n={utf8seq:0,codepoint:0},i={queue:0,queuedBits:0},s=o=>{Tm(o,n,r);};for(let o=0;o<t.length;o+=1)Rc(t.charCodeAt(o),i,s);return e.join("")}function xm(t,e){if(t<=127){e(t);return}else if(t<=2047){e(192|t>>6),e(128|t&63);return}else if(t<=65535){e(224|t>>12),e(128|t>>6&63),e(128|t&63);return}else if(t<=1114111){e(240|t>>18),e(128|t>>12&63),e(128|t>>6&63),e(128|t&63);return}throw new Error(`Unrecognized Unicode codepoint: ${t.toString(16)}`)}function Pm(t,e){for(let r=0;r<t.length;r+=1){let n=t.charCodeAt(r);if(n>55295&&n<=56319){let i=(n-55296)*1024&65535;n=(t.charCodeAt(r+1)-56320&65535|i)+65536,r+=1;}xm(n,e);}}function Tm(t,e,r){if(e.utf8seq===0){if(t<=127){r(t);return}for(let n=1;n<6;n+=1)if((t>>7-n&1)===0){e.utf8seq=n;break}if(e.utf8seq===2)e.codepoint=t&31;else if(e.utf8seq===3)e.codepoint=t&15;else if(e.utf8seq===4)e.codepoint=t&7;else throw new Error("Invalid UTF-8 sequence");e.utf8seq-=1;}else if(e.utf8seq>0){if(t<=127)throw new Error("Invalid UTF-8 sequence");e.codepoint=e.codepoint<<6|t&63,e.utf8seq-=1,e.utf8seq===0&&r(e.codepoint);}}function Ke(t){let e=[],r={queue:0,queuedBits:0},n=i=>{e.push(i);};for(let i=0;i<t.length;i+=1)Rc(t.charCodeAt(i),r,n);return new Uint8Array(e)}function xc(t){let e=[];return Pm(t,r=>e.push(r)),new Uint8Array(e)}function De(t){let e=[],r={queue:0,queuedBits:0},n=i=>{e.push(i);};return t.forEach(i=>Ec(i,r,n)),Ec(null,r,n),e.join("")}var Xn,Cc,Rm,Zn=R(()=>{Xn="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_".split(""),Cc=`
31
+ \r=`.split(""),Rm=(()=>{let t=new Array(128);for(let e=0;e<t.length;e+=1)t[e]=-1;for(let e=0;e<Cc.length;e+=1)t[Cc[e].charCodeAt(0)]=-2;for(let e=0;e<Xn.length;e+=1)t[Xn[e].charCodeAt(0)]=e;return t})();});function Pc(t){return Math.round(Date.now()/1e3)+t}function Tc(){return Symbol("auth-callback")}function Ac(t){let e={},r=new URL(t);if(r.hash&&r.hash[0]==="#")try{new URLSearchParams(r.hash.substring(1)).forEach((i,s)=>{e[s]=i;});}catch{}return r.searchParams.forEach((n,i)=>{e[i]=n;}),e}function Hr(t){let e=t.split(".");if(e.length!==3)throw new dt("Invalid JWT structure");for(let n=0;n<e.length;n++)if(!kc.test(e[n]))throw new dt("JWT not in base64url format");return {header:JSON.parse(Ms(e[0])),payload:JSON.parse(Ms(e[1])),signature:Ke(e[2]),raw:{header:e[0],payload:e[1]}}}async function Oc(t){return await new Promise(e=>{setTimeout(()=>e(null),t);})}function $c(t,e){return new Promise((n,i)=>{(async()=>{for(let s=0;s<1/0;s++)try{let o=await t(s);if(!e(s,null,o)){n(o);return}}catch(o){if(!e(s,o)){i(o);return}}})();})}function Am(t){return ("0"+t.toString(16)).substr(-2)}function Im(){let e=new Uint32Array(56);if(typeof crypto>"u"){let r="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~",n=r.length,i="";for(let s=0;s<56;s++)i+=r.charAt(Math.floor(Math.random()*n));return i}return crypto.getRandomValues(e),Array.from(e,Am).join("")}async function Om(t){let r=new TextEncoder().encode(t),n=await crypto.subtle.digest("SHA-256",r),i=new Uint8Array(n);return Array.from(i).map(s=>String.fromCharCode(s)).join("")}async function $m(t){if(!(typeof crypto<"u"&&typeof crypto.subtle<"u"&&typeof TextEncoder<"u"))return console.warn("WebCrypto API is not supported. Code challenge method will default to use plain instead of sha256."),t;let r=await Om(t);return btoa(r).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function gt(t,e,r=false){let n=Im(),i=n;r&&(i+="/PASSWORD_RECOVERY"),await ft(t,`${e}-code-verifier`,i);let s=await $m(n);return [s,n===s?"plain":"s256"]}function Nc(t){let e=t.headers.get(Lr);if(!e||!e.match(Nm))return null;try{return new Date(`${e}T00:00:00.0Z`)}catch{return null}}function Dc(t){if(!t)throw new Error("Missing exp claim");let e=Math.floor(Date.now()/1e3);if(t<=e)throw new Error("JWT has expired")}function jc(t){switch(t){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")}}function mt(t){if(!Dm.test(t))throw new Error("@supabase/auth-js: Expected parameter to be UUID but is not")}function ti(){let t={};return new Proxy(t,{get:(e,r)=>{if(r==="__isUserNotAvailableProxy")return true;if(typeof r=="symbol"){let n=r.toString();if(n==="Symbol(Symbol.toPrimitive)"||n==="Symbol(Symbol.toStringTag)"||n==="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 "${r}" property of the session object is not supported. Please use getUser() instead.`)},set:(e,r)=>{throw new Error(`@supabase/auth-js: client was created with userStorage option and there was no user stored in the user storage. Setting the "${r}" property of the session object is not supported. Please use getUser() to fetch a user object you can manipulate.`)},deleteProperty:(e,r)=>{throw new Error(`@supabase/auth-js: client was created with userStorage option and there was no user stored in the user storage. Deleting the "${r}" property of the session object is not supported. Please use getUser() to fetch a user object you can manipulate.`)}})}function Mc(t,e){return new Proxy(t,{get:(r,n,i)=>{if(n==="__isInsecureUserWarningProxy")return true;if(typeof n=="symbol"){let s=n.toString();if(s==="Symbol(Symbol.toPrimitive)"||s==="Symbol(Symbol.toStringTag)"||s==="Symbol(util.inspect.custom)"||s==="Symbol(nodejs.util.inspect.custom)")return Reflect.get(r,n,i)}return !e.value&&typeof n=="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."),e.value=true),Reflect.get(r,n,i)}})}function Ls(t){return JSON.parse(JSON.stringify(t))}var q,ht,Qn,ei,Ic,ft,Ve,z,Fr,Nm,Dm,Zt=R(()=>{Kn();pt();Zn();q=()=>typeof window<"u"&&typeof document<"u",ht={tested:false,writable:false},Qn=()=>{if(!q())return false;try{if(typeof globalThis.localStorage!="object")return !1}catch{return false}if(ht.tested)return ht.writable;let t=`lswt-${Math.random()}${Math.random()}`;try{globalThis.localStorage.setItem(t,t),globalThis.localStorage.removeItem(t),ht.tested=!0,ht.writable=!0;}catch{ht.tested=true,ht.writable=false;}return ht.writable};ei=t=>t?(...e)=>t(...e):(...e)=>fetch(...e),Ic=t=>typeof t=="object"&&t!==null&&"status"in t&&"ok"in t&&"json"in t&&typeof t.json=="function",ft=async(t,e,r)=>{await t.setItem(e,JSON.stringify(r));},Ve=async(t,e)=>{let r=await t.getItem(e);if(!r)return null;try{return JSON.parse(r)}catch{return r}},z=async(t,e)=>{await t.removeItem(e);},Fr=class t{constructor(){this.promise=new t.promiseConstructor((e,r)=>{this.resolve=e,this.reject=r;});}};Fr.promiseConstructor=Promise;Nm=/^2[0-9]{3}-(0[1-9]|1[0-2])-(0[1-9]|1[0-9]|2[0-9]|3[0-1])$/i;Dm=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;});async function Lc(t){var e;if(!Ic(t))throw new Xt(_t(t),0);if(jm.includes(t.status))throw new Xt(_t(t),t.status);let r;try{r=await t.json();}catch(s){throw new ue(_t(s),s)}let n,i=Nc(t);if(i&&i.getTime()>=js["2024-01-01"].timestamp&&typeof r=="object"&&r&&typeof r.code=="string"?n=r.code:typeof r=="object"&&r&&typeof r.error_code=="string"&&(n=r.error_code),n){if(n==="weak_password")throw new Wr(_t(r),t.status,((e=r.weak_password)===null||e===void 0?void 0:e.reasons)||[]);if(n==="session_not_found")throw new J}else if(typeof r=="object"&&r&&typeof r.weak_password=="object"&&r.weak_password&&Array.isArray(r.weak_password.reasons)&&r.weak_password.reasons.length&&r.weak_password.reasons.reduce((s,o)=>s&&typeof o=="string",true))throw new Wr(_t(r),t.status,r.weak_password.reasons);throw new Vn(_t(r),t.status||500,n)}async function S(t,e,r,n){var i;let s=Object.assign({},n?.headers);s[Lr]||(s[Lr]=js["2024-01-01"].name),n?.jwt&&(s.Authorization=`Bearer ${n.jwt}`);let o=(i=n?.query)!==null&&i!==void 0?i:{};n?.redirectTo&&(o.redirect_to=n.redirectTo);let a=Object.keys(o).length?"?"+new URLSearchParams(o).toString():"",l=await Lm(t,e,r+a,{headers:s,noResolveJson:n?.noResolveJson},{},n?.body);return n?.xform?n?.xform(l):{data:Object.assign({},l),error:null}}async function Lm(t,e,r,n,i,s){let o=Mm(e,n,i,s),a;try{a=await t(r,Object.assign({},o));}catch(l){throw console.error(l),new Xt(_t(l),0)}if(a.ok||await Lc(a),n?.noResolveJson)return a;try{return await a.json()}catch(l){await Lc(l);}}function de(t){var e;let r=null;Um(t)&&(r=Object.assign({},t),t.expires_at||(r.expires_at=Pc(t.expires_in)));let n=(e=t.user)!==null&&e!==void 0?e:t;return {data:{session:r,user:n},error:null}}function Us(t){let e=de(t);return !e.error&&t.weak_password&&typeof t.weak_password=="object"&&Array.isArray(t.weak_password.reasons)&&t.weak_password.reasons.length&&t.weak_password.message&&typeof t.weak_password.message=="string"&&t.weak_password.reasons.reduce((r,n)=>r&&typeof n=="string",true)&&(e.data.weak_password=t.weak_password),e}function Se(t){var e;return {data:{user:(e=t.user)!==null&&e!==void 0?e:t},error:null}}function Uc(t){return {data:t,error:null}}function Wc(t){let{action_link:e,email_otp:r,hashed_token:n,redirect_to:i,verification_type:s}=t,o=ot(t,["action_link","email_otp","hashed_token","redirect_to","verification_type"]),a={action_link:e,email_otp:r,hashed_token:n,redirect_to:i,verification_type:s},l=Object.assign({},o);return {data:{properties:a,user:l},error:null}}function Ws(t){return t}function Um(t){return t.access_token&&t.refresh_token&&t.expires_in}var _t,jm,Mm,Bs=R(()=>{kr();Kn();Zt();pt();_t=t=>t.msg||t.message||t.error_description||t.error||JSON.stringify(t),jm=[502,503,504,520,521,522,523,524,530];Mm=(t,e,r,n)=>{let i={method:t,headers:e?.headers||{}};return t==="GET"?i:(i.headers=Object.assign({"Content-Type":"application/json;charset=UTF-8"},e?.headers),i.body=JSON.stringify(n),Object.assign(Object.assign({},i),r))};});var ri,Fs=R(()=>{ri=["global","local","others"];});var wt,ni=R(()=>{kr();Bs();Zt();Fs();pt();wt=class{constructor({url:e="",headers:r={},fetch:n}){this.url=e,this.headers=r,this.fetch=ei(n),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)};}async signOut(e,r=ri[0]){if(ri.indexOf(r)<0)throw new Error(`@supabase/auth-js: Parameter scope must be one of ${ri.join(", ")}`);try{return await S(this.fetch,"POST",`${this.url}/logout?scope=${r}`,{headers:this.headers,jwt:e,noResolveJson:!0}),{data:null,error:null}}catch(n){if(v(n))return {data:null,error:n};throw n}}async inviteUserByEmail(e,r={}){try{return await S(this.fetch,"POST",`${this.url}/invite`,{body:{email:e,data:r.data},headers:this.headers,redirectTo:r.redirectTo,xform:Se})}catch(n){if(v(n))return {data:{user:null},error:n};throw n}}async generateLink(e){try{let{options:r}=e,n=ot(e,["options"]),i=Object.assign(Object.assign({},n),r);return "newEmail"in n&&(i.new_email=n?.newEmail,delete i.newEmail),await S(this.fetch,"POST",`${this.url}/admin/generate_link`,{body:i,headers:this.headers,xform:Wc,redirectTo:r?.redirectTo})}catch(r){if(v(r))return {data:{properties:null,user:null},error:r};throw r}}async createUser(e){try{return await S(this.fetch,"POST",`${this.url}/admin/users`,{body:e,headers:this.headers,xform:Se})}catch(r){if(v(r))return {data:{user:null},error:r};throw r}}async listUsers(e){var r,n,i,s,o,a,l;try{let c={nextPage:null,lastPage:0,total:0},u=await S(this.fetch,"GET",`${this.url}/admin/users`,{headers:this.headers,noResolveJson:!0,query:{page:(n=(r=e?.page)===null||r===void 0?void 0:r.toString())!==null&&n!==void 0?n:"",per_page:(s=(i=e?.perPage)===null||i===void 0?void 0:i.toString())!==null&&s!==void 0?s:""},xform:Ws});if(u.error)throw u.error;let d=await u.json(),p=(o=u.headers.get("x-total-count"))!==null&&o!==void 0?o:0,h=(l=(a=u.headers.get("link"))===null||a===void 0?void 0:a.split(","))!==null&&l!==void 0?l:[];return h.length>0&&(h.forEach(f=>{let m=parseInt(f.split(";")[0].split("=")[1].substring(0,1)),_=JSON.parse(f.split(";")[1].split("=")[1]);c[`${_}Page`]=m;}),c.total=parseInt(p)),{data:Object.assign(Object.assign({},d),c),error:null}}catch(c){if(v(c))return {data:{users:[]},error:c};throw c}}async getUserById(e){mt(e);try{return await S(this.fetch,"GET",`${this.url}/admin/users/${e}`,{headers:this.headers,xform:Se})}catch(r){if(v(r))return {data:{user:null},error:r};throw r}}async updateUserById(e,r){mt(e);try{return await S(this.fetch,"PUT",`${this.url}/admin/users/${e}`,{body:r,headers:this.headers,xform:Se})}catch(n){if(v(n))return {data:{user:null},error:n};throw n}}async deleteUser(e,r=false){mt(e);try{return await S(this.fetch,"DELETE",`${this.url}/admin/users/${e}`,{headers:this.headers,body:{should_soft_delete:r},xform:Se})}catch(n){if(v(n))return {data:{user:null},error:n};throw n}}async _listFactors(e){mt(e.userId);try{let{data:r,error:n}=await S(this.fetch,"GET",`${this.url}/admin/users/${e.userId}/factors`,{headers:this.headers,xform:i=>({data:{factors:i},error:null})});return {data:r,error:n}}catch(r){if(v(r))return {data:null,error:r};throw r}}async _deleteFactor(e){mt(e.userId),mt(e.id);try{return {data:await S(this.fetch,"DELETE",`${this.url}/admin/users/${e.userId}/factors/${e.id}`,{headers:this.headers}),error:null}}catch(r){if(v(r))return {data:null,error:r};throw r}}async _listOAuthClients(e){var r,n,i,s,o,a,l;try{let c={nextPage:null,lastPage:0,total:0},u=await S(this.fetch,"GET",`${this.url}/admin/oauth/clients`,{headers:this.headers,noResolveJson:!0,query:{page:(n=(r=e?.page)===null||r===void 0?void 0:r.toString())!==null&&n!==void 0?n:"",per_page:(s=(i=e?.perPage)===null||i===void 0?void 0:i.toString())!==null&&s!==void 0?s:""},xform:Ws});if(u.error)throw u.error;let d=await u.json(),p=(o=u.headers.get("x-total-count"))!==null&&o!==void 0?o:0,h=(l=(a=u.headers.get("link"))===null||a===void 0?void 0:a.split(","))!==null&&l!==void 0?l:[];return h.length>0&&(h.forEach(f=>{let m=parseInt(f.split(";")[0].split("=")[1].substring(0,1)),_=JSON.parse(f.split(";")[1].split("=")[1]);c[`${_}Page`]=m;}),c.total=parseInt(p)),{data:Object.assign(Object.assign({},d),c),error:null}}catch(c){if(v(c))return {data:{clients:[]},error:c};throw c}}async _createOAuthClient(e){try{return await S(this.fetch,"POST",`${this.url}/admin/oauth/clients`,{body:e,headers:this.headers,xform:r=>({data:r,error:null})})}catch(r){if(v(r))return {data:null,error:r};throw r}}async _getOAuthClient(e){try{return await S(this.fetch,"GET",`${this.url}/admin/oauth/clients/${e}`,{headers:this.headers,xform:r=>({data:r,error:null})})}catch(r){if(v(r))return {data:null,error:r};throw r}}async _updateOAuthClient(e,r){try{return await S(this.fetch,"PUT",`${this.url}/admin/oauth/clients/${e}`,{body:r,headers:this.headers,xform:n=>({data:n,error:null})})}catch(n){if(v(n))return {data:null,error:n};throw n}}async _deleteOAuthClient(e){try{return await S(this.fetch,"DELETE",`${this.url}/admin/oauth/clients/${e}`,{headers:this.headers,noResolveJson:!0}),{data:null,error:null}}catch(r){if(v(r))return {data:null,error:r};throw r}}async _regenerateOAuthClientSecret(e){try{return await S(this.fetch,"POST",`${this.url}/admin/oauth/clients/${e}/regenerate_secret`,{headers:this.headers,xform:r=>({data:r,error:null})})}catch(r){if(v(r))return {data:null,error:r};throw r}}async _listCustomProviders(e){try{let r={};return e?.type&&(r.type=e.type),await S(this.fetch,"GET",`${this.url}/admin/custom-providers`,{headers:this.headers,query:r,xform:n=>{var i;return {data:{providers:(i=n?.providers)!==null&&i!==void 0?i:[]},error:null}}})}catch(r){if(v(r))return {data:{providers:[]},error:r};throw r}}async _createCustomProvider(e){try{return await S(this.fetch,"POST",`${this.url}/admin/custom-providers`,{body:e,headers:this.headers,xform:r=>({data:r,error:null})})}catch(r){if(v(r))return {data:null,error:r};throw r}}async _getCustomProvider(e){try{return await S(this.fetch,"GET",`${this.url}/admin/custom-providers/${e}`,{headers:this.headers,xform:r=>({data:r,error:null})})}catch(r){if(v(r))return {data:null,error:r};throw r}}async _updateCustomProvider(e,r){try{return await S(this.fetch,"PUT",`${this.url}/admin/custom-providers/${e}`,{body:r,headers:this.headers,xform:n=>({data:n,error:null})})}catch(n){if(v(n))return {data:null,error:n};throw n}}async _deleteCustomProvider(e){try{return await S(this.fetch,"DELETE",`${this.url}/admin/custom-providers/${e}`,{headers:this.headers,noResolveJson:!0}),{data:null,error:null}}catch(r){if(v(r))return {data:null,error:r};throw r}}};});function Hs(t={}){return {getItem:e=>t[e]||null,setItem:(e,r)=>{t[e]=r;},removeItem:e=>{delete t[e];}}}var Bc=R(()=>{});async function qs(t,e,r){_e.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquire lock",t,e);let n=new globalThis.AbortController,i;e>0&&(i=setTimeout(()=>{n.abort(),_e.debug&&console.log("@supabase/gotrue-js: navigatorLock acquire timed out",t);},e)),await Promise.resolve();try{return await globalThis.navigator.locks.request(t,e===0?{mode:"exclusive",ifAvailable:!0}:{mode:"exclusive",signal:n.signal},async s=>{if(s){clearTimeout(i),_e.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquired",t,s.name);try{return await r()}finally{_e.debug&&console.log("@supabase/gotrue-js: navigatorLock: released",t,s.name);}}else {if(e===0)throw _e.debug&&console.log("@supabase/gotrue-js: navigatorLock: not immediately available",t),new zr(`Acquiring an exclusive Navigator LockManager lock "${t}" immediately failed`);if(_e.debug)try{let o=await globalThis.navigator.locks.query();console.log("@supabase/gotrue-js: Navigator LockManager state",JSON.stringify(o,null," "));}catch(o){console.warn("@supabase/gotrue-js: Error when querying Navigator LockManager state",o);}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(i),await r()}})}catch(s){if(e>0&&clearTimeout(i),s?.name==="AbortError"&&e>0){if(n.signal.aborted)return _e.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquire timeout, recovering by stealing lock",t),console.warn(`@supabase/gotrue-js: Lock "${t}" was not released within ${e}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(t,{mode:"exclusive",steal:true},async o=>{if(o){_e.debug&&console.log("@supabase/gotrue-js: navigatorLock: recovered (stolen)",t,o.name);try{return await r()}finally{_e.debug&&console.log("@supabase/gotrue-js: navigatorLock: released (stolen)",t,o.name);}}else return console.warn("@supabase/gotrue-js: Navigator LockManager returned null lock even with steal: true"),await r()}));throw _e.debug&&console.log("@supabase/gotrue-js: navigatorLock: lock was stolen by another request",t),new zr(`Lock "${t}" was released because another request stole it`)}throw s}}var _e,qr,zr,zs=R(()=>{Zt();_e={debug:!!(globalThis&&Qn()&&globalThis.localStorage&&globalThis.localStorage.getItem("supabase.gotrue-js.locks.debug")==="true")},qr=class extends Error{constructor(e){super(e),this.isAcquireTimeout=true;}},zr=class extends qr{};});function Fc(){if(typeof globalThis!="object")try{Object.defineProperty(Object.prototype,"__magic__",{get:function(){return this},configurable:!0}),__magic__.globalThis=__magic__,delete Object.prototype.__magic__;}catch{typeof self<"u"&&(self.globalThis=self);}}var Hc=R(()=>{});function Js(t){if(!/^0x[a-fA-F0-9]{40}$/.test(t))throw new Error(`@supabase/auth-js: Address "${t}" is invalid.`);return t.toLowerCase()}function qc(t){return parseInt(t,16)}function zc(t){let e=new TextEncoder().encode(t);return "0x"+Array.from(e,n=>n.toString(16).padStart(2,"0")).join("")}function Jc(t){var e;let{chainId:r,domain:n,expirationTime:i,issuedAt:s=new Date,nonce:o,notBefore:a,requestId:l,resources:c,scheme:u,uri:d,version:p}=t;{if(!Number.isInteger(r))throw new Error(`@supabase/auth-js: Invalid SIWE message field "chainId". Chain ID must be a EIP-155 chain ID. Provided value: ${r}`);if(!n)throw new Error('@supabase/auth-js: Invalid SIWE message field "domain". Domain must be provided.');if(o&&o.length<8)throw new Error(`@supabase/auth-js: Invalid SIWE message field "nonce". Nonce must be at least 8 characters. Provided value: ${o}`);if(!d)throw new Error('@supabase/auth-js: Invalid SIWE message field "uri". URI must be provided.');if(p!=="1")throw new Error(`@supabase/auth-js: Invalid SIWE message field "version". Version must be '1'. Provided value: ${p}`);if(!((e=t.statement)===null||e===void 0)&&e.includes(`
32
32
  `))throw new Error(`@supabase/auth-js: Invalid SIWE message field "statement". Statement must not include '\\n'. Provided value: ${t.statement}`)}let h=Js(t.address),f=u?`${u}://${n}`:n,m=t.statement?`${t.statement}
33
33
  `:"",_=`${f} wants you to sign in with your Ethereum account:
34
34
  ${h}
@@ -43,9 +43,9 @@ Not Before: ${a.toISOString()}`),l&&(b+=`
43
43
  Request ID: ${l}`),c){let w=`
44
44
  Resources:`;for(let y of c){if(!y||typeof y!="string")throw new Error(`@supabase/auth-js: Invalid SIWE message field "resources". Every resource must be a valid string. Provided value: ${y}`);w+=`
45
45
  - ${y}`;}b+=w;}return `${_}
46
- ${b}`}var Kc=R(()=>{});function Vc({error:t,options:e}){var r,n,i;let{publicKey:s}=e;if(!s)throw Error("options was missing required publicKey property");if(t.name==="AbortError"){if(e.signal instanceof AbortSignal)return new L({message:"Registration ceremony was sent an abort signal",code:"ERROR_CEREMONY_ABORTED",cause:t})}else if(t.name==="ConstraintError"){if(((r=s.authenticatorSelection)===null||r===void 0?void 0:r.requireResidentKey)===true)return new L({message:"Discoverable credentials were required but no available authenticator supported it",code:"ERROR_AUTHENTICATOR_MISSING_DISCOVERABLE_CREDENTIAL_SUPPORT",cause:t});if(e.mediation==="conditional"&&((n=s.authenticatorSelection)===null||n===void 0?void 0:n.userVerification)==="required")return new L({message:"User verification was required during automatic registration but it could not be performed",code:"ERROR_AUTO_REGISTER_USER_VERIFICATION_FAILURE",cause:t});if(((i=s.authenticatorSelection)===null||i===void 0?void 0:i.userVerification)==="required")return new L({message:"User verification was required but no available authenticator supported it",code:"ERROR_AUTHENTICATOR_MISSING_USER_VERIFICATION_SUPPORT",cause:t})}else {if(t.name==="InvalidStateError")return new L({message:"The authenticator was previously registered",code:"ERROR_AUTHENTICATOR_PREVIOUSLY_REGISTERED",cause:t});if(t.name==="NotAllowedError")return new L({message:t.message,code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:t});if(t.name==="NotSupportedError")return s.pubKeyCredParams.filter(a=>a.type==="public-key").length===0?new L({message:'No entry in pubKeyCredParams was of type "public-key"',code:"ERROR_MALFORMED_PUBKEYCREDPARAMS",cause:t}):new L({message:"No available authenticator supported any of the specified pubKeyCredParams algorithms",code:"ERROR_AUTHENTICATOR_NO_SUPPORTED_PUBKEYCREDPARAMS_ALG",cause:t});if(t.name==="SecurityError"){let o=window.location.hostname;if(Ks(o)){if(s.rp.id!==o)return new L({message:`The RP ID "${s.rp.id}" is invalid for this domain`,code:"ERROR_INVALID_RP_ID",cause:t})}else return new L({message:`${window.location.hostname} is an invalid domain`,code:"ERROR_INVALID_DOMAIN",cause:t})}else if(t.name==="TypeError"){if(s.user.id.byteLength<1||s.user.id.byteLength>64)return new L({message:"User ID was not between 1 and 64 characters",code:"ERROR_INVALID_USER_ID_LENGTH",cause:t})}else if(t.name==="UnknownError")return new L({message:"The authenticator was unable to process the specified options, or could not create a new credential",code:"ERROR_AUTHENTICATOR_GENERAL_ERROR",cause:t})}return new L({message:"a Non-Webauthn related error has occurred",code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:t})}function Gc({error:t,options:e}){let{publicKey:r}=e;if(!r)throw Error("options was missing required publicKey property");if(t.name==="AbortError"){if(e.signal instanceof AbortSignal)return new L({message:"Authentication ceremony was sent an abort signal",code:"ERROR_CEREMONY_ABORTED",cause:t})}else {if(t.name==="NotAllowedError")return new L({message:t.message,code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:t});if(t.name==="SecurityError"){let n=window.location.hostname;if(Ks(n)){if(r.rpId!==n)return new L({message:`The RP ID "${r.rpId}" is invalid for this domain`,code:"ERROR_INVALID_RP_ID",cause:t})}else return new L({message:`${window.location.hostname} is an invalid domain`,code:"ERROR_INVALID_DOMAIN",cause:t})}else if(t.name==="UnknownError")return new L({message:"The authenticator was unable to process the specified options, or could not create a new assertion signature",code:"ERROR_AUTHENTICATOR_GENERAL_ERROR",cause:t})}return new L({message:"a Non-Webauthn related error has occurred",code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:t})}var L,yt,Yc=R(()=>{Vs();L=class extends Error{constructor({message:e,code:r,cause:n,name:i}){var s;super(e,{cause:n}),this.__isWebAuthnError=true,this.name=(s=i??(n instanceof Error?n.name:void 0))!==null&&s!==void 0?s:"Unknown Error",this.code=r;}},yt=class extends L{constructor(e,r){super({code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:r,message:e}),this.name="WebAuthnUnknownError",this.originalError=r;}};});function Zc(t){if(!t)throw new Error("Credential creation options are required");if(typeof PublicKeyCredential<"u"&&"parseCreationOptionsFromJSON"in PublicKeyCredential&&typeof PublicKeyCredential.parseCreationOptionsFromJSON=="function")return PublicKeyCredential.parseCreationOptionsFromJSON(t);let{challenge:e,user:r,excludeCredentials:n}=t,i=ot(t,["challenge","user","excludeCredentials"]),s=Ke(e).buffer,o=Object.assign(Object.assign({},r),{id:Ke(r.id).buffer}),a=Object.assign(Object.assign({},i),{challenge:s,user:o});if(n&&n.length>0){a.excludeCredentials=new Array(n.length);for(let l=0;l<n.length;l++){let c=n[l];a.excludeCredentials[l]=Object.assign(Object.assign({},c),{id:Ke(c.id).buffer,type:c.type||"public-key",transports:c.transports});}}return a}function Qc(t){if(!t)throw new Error("Credential request options are required");if(typeof PublicKeyCredential<"u"&&"parseRequestOptionsFromJSON"in PublicKeyCredential&&typeof PublicKeyCredential.parseRequestOptionsFromJSON=="function")return PublicKeyCredential.parseRequestOptionsFromJSON(t);let{challenge:e,allowCredentials:r}=t,n=ot(t,["challenge","allowCredentials"]),i=Ke(e).buffer,s=Object.assign(Object.assign({},n),{challenge:i});if(r&&r.length>0){s.allowCredentials=new Array(r.length);for(let o=0;o<r.length;o++){let a=r[o];s.allowCredentials[o]=Object.assign(Object.assign({},a),{id:Ke(a.id).buffer,type:a.type||"public-key",transports:a.transports});}}return s}function eu(t){var e;if("toJSON"in t&&typeof t.toJSON=="function")return t.toJSON();let r=t;return {id:t.id,rawId:t.id,response:{attestationObject:je(new Uint8Array(t.response.attestationObject)),clientDataJSON:je(new Uint8Array(t.response.clientDataJSON))},type:"public-key",clientExtensionResults:t.getClientExtensionResults(),authenticatorAttachment:(e=r.authenticatorAttachment)!==null&&e!==void 0?e:void 0}}function tu(t){var e;if("toJSON"in t&&typeof t.toJSON=="function")return t.toJSON();let r=t,n=t.getClientExtensionResults(),i=t.response;return {id:t.id,rawId:t.id,response:{authenticatorData:je(new Uint8Array(i.authenticatorData)),clientDataJSON:je(new Uint8Array(i.clientDataJSON)),signature:je(new Uint8Array(i.signature)),userHandle:i.userHandle?je(new Uint8Array(i.userHandle)):void 0},type:"public-key",clientExtensionResults:n,authenticatorAttachment:(e=r.authenticatorAttachment)!==null&&e!==void 0?e:void 0}}function Ks(t){return t==="localhost"||/^([a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,}$/i.test(t)}function Xc(){var t,e;return !!(q()&&"PublicKeyCredential"in window&&window.PublicKeyCredential&&"credentials"in navigator&&typeof((t=navigator?.credentials)===null||t===void 0?void 0:t.create)=="function"&&typeof((e=navigator?.credentials)===null||e===void 0?void 0:e.get)=="function")}async function Bm(t){try{let e=await navigator.credentials.create(t);return e?e instanceof PublicKeyCredential?{data:e,error:null}:{data:null,error:new yt("Browser returned unexpected credential type",e)}:{data:null,error:new yt("Empty credential response",e)}}catch(e){return {data:null,error:Vc({error:e,options:t})}}}async function Fm(t){try{let e=await navigator.credentials.get(t);return e?e instanceof PublicKeyCredential?{data:e,error:null}:{data:null,error:new yt("Browser returned unexpected credential type",e)}:{data:null,error:new yt("Empty credential response",e)}}catch(e){return {data:null,error:Gc({error:e,options:t})}}}function ii(...t){let e=i=>i!==null&&typeof i=="object"&&!Array.isArray(i),r=i=>i instanceof ArrayBuffer||ArrayBuffer.isView(i),n={};for(let i of t)if(i)for(let s in i){let o=i[s];if(o!==void 0)if(Array.isArray(o))n[s]=o;else if(r(o))n[s]=o;else if(e(o)){let a=n[s];e(a)?n[s]=ii(a,o):n[s]=ii(o);}else n[s]=o;}return n}function zm(t,e){return ii(Hm,t,e||{})}function Jm(t,e){return ii(qm,t,e||{})}var Gs,Wm,Hm,qm,si,Vs=R(()=>{kr();Zn();pt();Zt();Yc();Gs=class{createNewAbortSignal(){if(this.controller){let r=new Error("Cancelling existing WebAuthn API call for new one");r.name="AbortError",this.controller.abort(r);}let e=new AbortController;return this.controller=e,e.signal}cancelCeremony(){if(this.controller){let e=new Error("Manually cancelling existing WebAuthn API call");e.name="AbortError",this.controller.abort(e),this.controller=void 0;}}},Wm=new Gs;Hm={hints:["security-key"],authenticatorSelection:{authenticatorAttachment:"cross-platform",requireResidentKey:false,userVerification:"preferred",residentKey:"discouraged"},attestation:"direct"},qm={userVerification:"preferred",hints:["security-key"],attestation:"direct"};si=class{constructor(e){this.client=e,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(e){return this.client.mfa.enroll(Object.assign(Object.assign({},e),{factorType:"webauthn"}))}async _challenge({factorId:e,webauthn:r,friendlyName:n,signal:i},s){var o;try{let{data:a,error:l}=await this.client.mfa.challenge({factorId:e,webauthn:r});if(!a)return {data:null,error:l};let c=i??Wm.createNewAbortSignal();if(a.webauthn.type==="create"){let{user:u}=a.webauthn.credential_options.publicKey;if(!u.name){let d=n;if(d)u.name=`${u.id}:${d}`;else {let h=(await this.client.getUser()).data.user,f=((o=h?.user_metadata)===null||o===void 0?void 0:o.name)||h?.email||h?.id||"User";u.name=`${u.id}:${f}`;}}u.displayName||(u.displayName=u.name);}switch(a.webauthn.type){case "create":{let u=zm(a.webauthn.credential_options.publicKey,s?.create),{data:d,error:p}=await Bm({publicKey:u,signal:c});return d?{data:{factorId:e,challengeId:a.id,webauthn:{type:a.webauthn.type,credential_response:d}},error:null}:{data:null,error:p}}case "request":{let u=Jm(a.webauthn.credential_options.publicKey,s?.request),{data:d,error:p}=await Fm(Object.assign(Object.assign({},a.webauthn.credential_options),{publicKey:u,signal:c}));return d?{data:{factorId:e,challengeId:a.id,webauthn:{type:a.webauthn.type,credential_response:d}},error:null}:{data:null,error:p}}}}catch(a){return v(a)?{data:null,error:a}:{data:null,error:new ue("Unexpected error in challenge",a)}}}async _verify({challengeId:e,factorId:r,webauthn:n}){return this.client.mfa.verify({factorId:r,challengeId:e,webauthn:n})}async _authenticate({factorId:e,webauthn:{rpId:r=typeof window<"u"?window.location.hostname:void 0,rpOrigins:n=typeof window<"u"?[window.location.origin]:void 0,signal:i}={}},s){if(!r)return {data:null,error:new Je("rpId is required for WebAuthn authentication")};try{if(!Xc())return {data:null,error:new ue("Browser does not support WebAuthn",null)};let{data:o,error:a}=await this.challenge({factorId:e,webauthn:{rpId:r,rpOrigins:n},signal:i},{request:s});if(!o)return {data:null,error:a};let{webauthn:l}=o;return this._verify({factorId:e,challengeId:o.challengeId,webauthn:{type:l.type,rpId:r,rpOrigins:n,credential_response:l.credential_response}})}catch(o){return v(o)?{data:null,error:o}:{data:null,error:new ue("Unexpected error in authenticate",o)}}}async _register({friendlyName:e,webauthn:{rpId:r=typeof window<"u"?window.location.hostname:void 0,rpOrigins:n=typeof window<"u"?[window.location.origin]:void 0,signal:i}={}},s){if(!r)return {data:null,error:new Je("rpId is required for WebAuthn registration")};try{if(!Xc())return {data:null,error:new ue("Browser does not support WebAuthn",null)};let{data:o,error:a}=await this._enroll({friendlyName:e});if(!o)return await this.client.mfa.listFactors().then(u=>{var d;return (d=u.data)===null||d===void 0?void 0:d.all.find(p=>p.factor_type==="webauthn"&&p.friendly_name===e&&p.status!=="unverified")}).then(u=>u?this.client.mfa.unenroll({factorId:u?.id}):void 0),{data:null,error:a};let{data:l,error:c}=await this._challenge({factorId:o.id,friendlyName:o.friendly_name,webauthn:{rpId:r,rpOrigins:n},signal:i},{create:s});return l?this._verify({factorId:o.id,challengeId:l.challengeId,webauthn:{rpId:r,rpOrigins:n,type:l.webauthn.type,credential_response:l.webauthn.credential_response}}):{data:null,error:c}}catch(o){return v(o)?{data:null,error:o}:{data:null,error:new ue("Unexpected error in register",o)}}}};});async function ru(t,e,r){return await r()}var Km,Qt,oi,Ys,Xs=R(()=>{ni();Kn();pt();Bs();Zt();Bc();zs();Hc();js();Zn();Kc();Vs();Fc();Km={url:_c,storageKey:wc,autoRefreshToken:true,persistSession:true,detectSessionInUrl:true,headers:yc,flowType:"implicit",debug:false,hasCustomAuthorizationHeader:false,throwOnError:false,lockAcquireTimeout:5e3,skipAutoInitialize:false};Qt={},oi=class t{get jwks(){var e,r;return (r=(e=Qt[this.storageKey])===null||e===void 0?void 0:e.jwks)!==null&&r!==void 0?r:{keys:[]}}set jwks(e){Qt[this.storageKey]=Object.assign(Object.assign({},Qt[this.storageKey]),{jwks:e});}get jwks_cached_at(){var e,r;return (r=(e=Qt[this.storageKey])===null||e===void 0?void 0:e.cachedAt)!==null&&r!==void 0?r:Number.MIN_SAFE_INTEGER}set jwks_cached_at(e){Qt[this.storageKey]=Object.assign(Object.assign({},Qt[this.storageKey]),{cachedAt:e});}constructor(e){var r,n,i;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=true,this.hasCustomAuthorizationHeader=false,this.suppressGetSessionWarning=false,this.lockAcquired=false,this.pendingInLock=[],this.broadcastChannel=null,this.logger=console.log;let s=Object.assign(Object.assign({},Km),e);if(this.storageKey=s.storageKey,this.instanceID=(r=t.nextInstanceID[this.storageKey])!==null&&r!==void 0?r:0,t.nextInstanceID[this.storageKey]=this.instanceID+1,this.logDebugMessages=!!s.debug,typeof s.debug=="function"&&(this.logger=s.debug),this.instanceID>0&&q()){let o=`${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.`;console.warn(o),this.logDebugMessages&&console.trace(o);}if(this.persistSession=s.persistSession,this.autoRefreshToken=s.autoRefreshToken,this.admin=new wt({url:s.url,headers:s.headers,fetch:s.fetch}),this.url=s.url,this.headers=s.headers,this.fetch=ei(s.fetch),this.lock=s.lock||ru,this.detectSessionInUrl=s.detectSessionInUrl,this.flowType=s.flowType,this.hasCustomAuthorizationHeader=s.hasCustomAuthorizationHeader,this.throwOnError=s.throwOnError,this.lockAcquireTimeout=s.lockAcquireTimeout,s.lock?this.lock=s.lock:this.persistSession&&q()&&(!((n=globalThis?.navigator)===null||n===void 0)&&n.locks)?this.lock=qs:this.lock=ru,this.jwks||(this.jwks={keys:[]},this.jwks_cached_at=Number.MIN_SAFE_INTEGER),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 si(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.persistSession?(s.storage?this.storage=s.storage:Qn()?this.storage=globalThis.localStorage:(this.memoryStorage={},this.storage=Hs(this.memoryStorage)),s.userStorage&&(this.userStorage=s.userStorage)):(this.memoryStorage={},this.storage=Hs(this.memoryStorage)),q()&&globalThis.BroadcastChannel&&this.persistSession&&this.storageKey){try{this.broadcastChannel=new globalThis.BroadcastChannel(this.storageKey);}catch(o){console.error("Failed to create a new BroadcastChannel, multi-tab state changes will not be available",o);}(i=this.broadcastChannel)===null||i===void 0||i.addEventListener("message",async o=>{this._debug("received broadcast notification from other tab or client",o);try{await this._notifyAllSubscribers(o.data.event,o.data.session,!1);}catch(a){this._debug("#broadcastChannel","error",a);}});}s.skipAutoInitialize||this.initialize().catch(o=>{this._debug("#initialize()","error",o);});}isThrowOnErrorEnabled(){return this.throwOnError}_returnResult(e){if(this.throwOnError&&e&&e.error)throw e.error;return e}_logPrefix(){return `GoTrueClient@${this.storageKey}:${this.instanceID} (${qn}) ${new Date().toISOString()}`}_debug(...e){return this.logDebugMessages&&this.logger(this._logPrefix(),...e),this}async initialize(){return this.initializePromise?await this.initializePromise:(this.initializePromise=(async()=>await this._acquireLock(this.lockAcquireTimeout,async()=>await this._initialize()))(),await this.initializePromise)}async _initialize(){var e;try{let r={},n="none";if(q()&&(r=Ac(window.location.href),this._isImplicitGrantCallback(r)?n="implicit":await this._isPKCECallback(r)&&(n="pkce")),q()&&this.detectSessionInUrl&&n!=="none"){let{data:i,error:s}=await this._getSessionFromURL(r,n);if(s){if(this._debug("#_initialize()","error detecting session from URL",s),Sc(s)){let l=(e=s.details)===null||e===void 0?void 0:e.code;if(l==="identity_already_exists"||l==="identity_not_found"||l==="single_identity_not_deletable")return {error:s}}return {error:s}}let{session:o,redirectType:a}=i;return this._debug("#_initialize()","detected session in URL",o,"redirect type",a),await this._saveSession(o),setTimeout(async()=>{a==="recovery"?await this._notifyAllSubscribers("PASSWORD_RECOVERY",o):await this._notifyAllSubscribers("SIGNED_IN",o);},0),{error:null}}return await this._recoverAndRefresh(),{error:null}}catch(r){return v(r)?this._returnResult({error:r}):this._returnResult({error:new ue("Unexpected error during initialization",r)})}finally{await this._handleVisibilityChange(),this._debug("#_initialize()","end");}}async signInAnonymously(e){var r,n,i;try{let s=await S(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{data:(n=(r=e?.options)===null||r===void 0?void 0:r.data)!==null&&n!==void 0?n:{},gotrue_meta_security:{captcha_token:(i=e?.options)===null||i===void 0?void 0:i.captchaToken}},xform:de}),{data:o,error:a}=s;if(a||!o)return this._returnResult({data:{user:null,session:null},error:a});let l=o.session,c=o.user;return o.session&&(await this._saveSession(o.session),await this._notifyAllSubscribers("SIGNED_IN",l)),this._returnResult({data:{user:c,session:l},error:null})}catch(s){if(v(s))return this._returnResult({data:{user:null,session:null},error:s});throw s}}async signUp(e){var r,n,i;try{let s;if("email"in e){let{email:u,password:d,options:p}=e,h=null,f=null;this.flowType==="pkce"&&([h,f]=await gt(this.storage,this.storageKey)),s=await S(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,redirectTo:p?.emailRedirectTo,body:{email:u,password:d,data:(r=p?.data)!==null&&r!==void 0?r:{},gotrue_meta_security:{captcha_token:p?.captchaToken},code_challenge:h,code_challenge_method:f},xform:de});}else if("phone"in e){let{phone:u,password:d,options:p}=e;s=await S(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{phone:u,password:d,data:(n=p?.data)!==null&&n!==void 0?n:{},channel:(i=p?.channel)!==null&&i!==void 0?i:"sms",gotrue_meta_security:{captcha_token:p?.captchaToken}},xform:de});}else throw new ct("You must provide either an email or phone number and a password");let{data:o,error:a}=s;if(a||!o)return await z(this.storage,`${this.storageKey}-code-verifier`),this._returnResult({data:{user:null,session:null},error:a});let l=o.session,c=o.user;return o.session&&(await this._saveSession(o.session),await this._notifyAllSubscribers("SIGNED_IN",l)),this._returnResult({data:{user:c,session:l},error:null})}catch(s){if(await z(this.storage,`${this.storageKey}-code-verifier`),v(s))return this._returnResult({data:{user:null,session:null},error:s});throw s}}async signInWithPassword(e){try{let r;if("email"in e){let{email:s,password:o,options:a}=e;r=await S(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{email:s,password:o,gotrue_meta_security:{captcha_token:a?.captchaToken}},xform:Us});}else if("phone"in e){let{phone:s,password:o,options:a}=e;r=await S(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{phone:s,password:o,gotrue_meta_security:{captcha_token:a?.captchaToken}},xform:Us});}else throw new ct("You must provide either an email or phone number and a password");let{data:n,error:i}=r;if(i)return this._returnResult({data:{user:null,session:null},error:i});if(!n||!n.session||!n.user){let s=new Ne;return this._returnResult({data:{user:null,session:null},error:s})}return n.session&&(await this._saveSession(n.session),await this._notifyAllSubscribers("SIGNED_IN",n.session)),this._returnResult({data:Object.assign({user:n.user,session:n.session},n.weak_password?{weakPassword:n.weak_password}:null),error:i})}catch(r){if(v(r))return this._returnResult({data:{user:null,session:null},error:r});throw r}}async signInWithOAuth(e){var r,n,i,s;return await this._handleProviderSignIn(e.provider,{redirectTo:(r=e.options)===null||r===void 0?void 0:r.redirectTo,scopes:(n=e.options)===null||n===void 0?void 0:n.scopes,queryParams:(i=e.options)===null||i===void 0?void 0:i.queryParams,skipBrowserRedirect:(s=e.options)===null||s===void 0?void 0:s.skipBrowserRedirect})}async exchangeCodeForSession(e){return await this.initializePromise,this._acquireLock(this.lockAcquireTimeout,async()=>this._exchangeCodeForSession(e))}async signInWithWeb3(e){let{chain:r}=e;switch(r){case "ethereum":return await this.signInWithEthereum(e);case "solana":return await this.signInWithSolana(e);default:throw new Error(`@supabase/auth-js: Unsupported chain "${r}"`)}}async signInWithEthereum(e){var r,n,i,s,o,a,l,c,u,d,p;let h,f;if("message"in e)h=e.message,f=e.signature;else {let{chain:m,wallet:_,statement:b,options:w}=e,y;if(q())if(typeof _=="object")y=_;else {let le=window;if("ethereum"in le&&typeof le.ethereum=="object"&&"request"in le.ethereum&&typeof le.ethereum.request=="function")y=le.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.")}else {if(typeof _!="object"||!w?.url)throw new Error("@supabase/auth-js: Both wallet and url must be specified in non-browser environments.");y=_;}let I=new URL((r=w?.url)!==null&&r!==void 0?r:window.location.href),Z=await y.request({method:"eth_requestAccounts"}).then(le=>le).catch(()=>{throw new Error("@supabase/auth-js: Wallet method eth_requestAccounts is missing or invalid")});if(!Z||Z.length===0)throw new Error("@supabase/auth-js: No accounts available. Please ensure the wallet is connected.");let T=Js(Z[0]),$=(n=w?.signInWithEthereum)===null||n===void 0?void 0:n.chainId;if(!$){let le=await y.request({method:"eth_chainId"});$=qc(le);}let Ie={domain:I.host,address:T,statement:b,uri:I.href,version:"1",chainId:$,nonce:(i=w?.signInWithEthereum)===null||i===void 0?void 0:i.nonce,issuedAt:(o=(s=w?.signInWithEthereum)===null||s===void 0?void 0:s.issuedAt)!==null&&o!==void 0?o:new Date,expirationTime:(a=w?.signInWithEthereum)===null||a===void 0?void 0:a.expirationTime,notBefore:(l=w?.signInWithEthereum)===null||l===void 0?void 0:l.notBefore,requestId:(c=w?.signInWithEthereum)===null||c===void 0?void 0:c.requestId,resources:(u=w?.signInWithEthereum)===null||u===void 0?void 0:u.resources};h=Jc(Ie),f=await y.request({method:"personal_sign",params:[zc(h),T]});}try{let{data:m,error:_}=await S(this.fetch,"POST",`${this.url}/token?grant_type=web3`,{headers:this.headers,body:Object.assign({chain:"ethereum",message:h,signature:f},!((d=e.options)===null||d===void 0)&&d.captchaToken?{gotrue_meta_security:{captcha_token:(p=e.options)===null||p===void 0?void 0:p.captchaToken}}:null),xform:de});if(_)throw _;if(!m||!m.session||!m.user){let b=new Ne;return this._returnResult({data:{user:null,session:null},error:b})}return m.session&&(await this._saveSession(m.session),await this._notifyAllSubscribers("SIGNED_IN",m.session)),this._returnResult({data:Object.assign({},m),error:_})}catch(m){if(v(m))return this._returnResult({data:{user:null,session:null},error:m});throw m}}async signInWithSolana(e){var r,n,i,s,o,a,l,c,u,d,p,h;let f,m;if("message"in e)f=e.message,m=e.signature;else {let{chain:_,wallet:b,statement:w,options:y}=e,I;if(q())if(typeof b=="object")I=b;else {let T=window;if("solana"in T&&typeof T.solana=="object"&&("signIn"in T.solana&&typeof T.solana.signIn=="function"||"signMessage"in T.solana&&typeof T.solana.signMessage=="function"))I=T.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.")}else {if(typeof b!="object"||!y?.url)throw new Error("@supabase/auth-js: Both wallet and url must be specified in non-browser environments.");I=b;}let Z=new URL((r=y?.url)!==null&&r!==void 0?r:window.location.href);if("signIn"in I&&I.signIn){let T=await I.signIn(Object.assign(Object.assign(Object.assign({issuedAt:new Date().toISOString()},y?.signInWithSolana),{version:"1",domain:Z.host,uri:Z.href}),w?{statement:w}:null)),$;if(Array.isArray(T)&&T[0]&&typeof T[0]=="object")$=T[0];else if(T&&typeof T=="object"&&"signedMessage"in T&&"signature"in T)$=T;else throw new Error("@supabase/auth-js: Wallet method signIn() returned unrecognized value");if("signedMessage"in $&&"signature"in $&&(typeof $.signedMessage=="string"||$.signedMessage instanceof Uint8Array)&&$.signature instanceof Uint8Array)f=typeof $.signedMessage=="string"?$.signedMessage:new TextDecoder().decode($.signedMessage),m=$.signature;else throw new Error("@supabase/auth-js: Wallet method signIn() API returned object without signedMessage and signature fields")}else {if(!("signMessage"in I)||typeof I.signMessage!="function"||!("publicKey"in I)||typeof I!="object"||!I.publicKey||!("toBase58"in I.publicKey)||typeof I.publicKey.toBase58!="function")throw new Error("@supabase/auth-js: Wallet does not have a compatible signMessage() and publicKey.toBase58() API");f=[`${Z.host} wants you to sign in with your Solana account:`,I.publicKey.toBase58(),...w?["",w,""]:[""],"Version: 1",`URI: ${Z.href}`,`Issued At: ${(i=(n=y?.signInWithSolana)===null||n===void 0?void 0:n.issuedAt)!==null&&i!==void 0?i:new Date().toISOString()}`,...!((s=y?.signInWithSolana)===null||s===void 0)&&s.notBefore?[`Not Before: ${y.signInWithSolana.notBefore}`]:[],...!((o=y?.signInWithSolana)===null||o===void 0)&&o.expirationTime?[`Expiration Time: ${y.signInWithSolana.expirationTime}`]:[],...!((a=y?.signInWithSolana)===null||a===void 0)&&a.chainId?[`Chain ID: ${y.signInWithSolana.chainId}`]:[],...!((l=y?.signInWithSolana)===null||l===void 0)&&l.nonce?[`Nonce: ${y.signInWithSolana.nonce}`]:[],...!((c=y?.signInWithSolana)===null||c===void 0)&&c.requestId?[`Request ID: ${y.signInWithSolana.requestId}`]:[],...!((d=(u=y?.signInWithSolana)===null||u===void 0?void 0:u.resources)===null||d===void 0)&&d.length?["Resources",...y.signInWithSolana.resources.map($=>`- ${$}`)]:[]].join(`
47
- `);let T=await I.signMessage(new TextEncoder().encode(f),"utf8");if(!T||!(T instanceof Uint8Array))throw new Error("@supabase/auth-js: Wallet signMessage() API returned an recognized value");m=T;}}try{let{data:_,error:b}=await S(this.fetch,"POST",`${this.url}/token?grant_type=web3`,{headers:this.headers,body:Object.assign({chain:"solana",message:f,signature:je(m)},!((p=e.options)===null||p===void 0)&&p.captchaToken?{gotrue_meta_security:{captcha_token:(h=e.options)===null||h===void 0?void 0:h.captchaToken}}:null),xform:de});if(b)throw b;if(!_||!_.session||!_.user){let w=new Ne;return this._returnResult({data:{user:null,session:null},error:w})}return _.session&&(await this._saveSession(_.session),await this._notifyAllSubscribers("SIGNED_IN",_.session)),this._returnResult({data:Object.assign({},_),error:b})}catch(_){if(v(_))return this._returnResult({data:{user:null,session:null},error:_});throw _}}async _exchangeCodeForSession(e){let r=await Ve(this.storage,`${this.storageKey}-code-verifier`),[n,i]=(r??"").split("/");try{if(!n&&this.flowType==="pkce")throw new Gn;let{data:s,error:o}=await S(this.fetch,"POST",`${this.url}/token?grant_type=pkce`,{headers:this.headers,body:{auth_code:e,code_verifier:n},xform:de});if(await z(this.storage,`${this.storageKey}-code-verifier`),o)throw o;if(!s||!s.session||!s.user){let a=new Ne;return this._returnResult({data:{user:null,session:null,redirectType:null},error:a})}return s.session&&(await this._saveSession(s.session),await this._notifyAllSubscribers("SIGNED_IN",s.session)),this._returnResult({data:Object.assign(Object.assign({},s),{redirectType:i??null}),error:o})}catch(s){if(await z(this.storage,`${this.storageKey}-code-verifier`),v(s))return this._returnResult({data:{user:null,session:null,redirectType:null},error:s});throw s}}async signInWithIdToken(e){try{let{options:r,provider:n,token:i,access_token:s,nonce:o}=e,a=await S(this.fetch,"POST",`${this.url}/token?grant_type=id_token`,{headers:this.headers,body:{provider:n,id_token:i,access_token:s,nonce:o,gotrue_meta_security:{captcha_token:r?.captchaToken}},xform:de}),{data:l,error:c}=a;if(c)return this._returnResult({data:{user:null,session:null},error:c});if(!l||!l.session||!l.user){let u=new Ne;return this._returnResult({data:{user:null,session:null},error:u})}return l.session&&(await this._saveSession(l.session),await this._notifyAllSubscribers("SIGNED_IN",l.session)),this._returnResult({data:l,error:c})}catch(r){if(v(r))return this._returnResult({data:{user:null,session:null},error:r});throw r}}async signInWithOtp(e){var r,n,i,s,o;try{if("email"in e){let{email:a,options:l}=e,c=null,u=null;this.flowType==="pkce"&&([c,u]=await gt(this.storage,this.storageKey));let{error:d}=await S(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{email:a,data:(r=l?.data)!==null&&r!==void 0?r:{},create_user:(n=l?.shouldCreateUser)!==null&&n!==void 0?n:!0,gotrue_meta_security:{captcha_token:l?.captchaToken},code_challenge:c,code_challenge_method:u},redirectTo:l?.emailRedirectTo});return this._returnResult({data:{user:null,session:null},error:d})}if("phone"in e){let{phone:a,options:l}=e,{data:c,error:u}=await S(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{phone:a,data:(i=l?.data)!==null&&i!==void 0?i:{},create_user:(s=l?.shouldCreateUser)!==null&&s!==void 0?s:!0,gotrue_meta_security:{captcha_token:l?.captchaToken},channel:(o=l?.channel)!==null&&o!==void 0?o:"sms"}});return this._returnResult({data:{user:null,session:null,messageId:c?.message_id},error:u})}throw new ct("You must provide either an email or phone number.")}catch(a){if(await z(this.storage,`${this.storageKey}-code-verifier`),v(a))return this._returnResult({data:{user:null,session:null},error:a});throw a}}async verifyOtp(e){var r,n;try{let i,s;"options"in e&&(i=(r=e.options)===null||r===void 0?void 0:r.redirectTo,s=(n=e.options)===null||n===void 0?void 0:n.captchaToken);let{data:o,error:a}=await S(this.fetch,"POST",`${this.url}/verify`,{headers:this.headers,body:Object.assign(Object.assign({},e),{gotrue_meta_security:{captcha_token:s}}),redirectTo:i,xform:de});if(a)throw a;if(!o)throw new Error("An error occurred on token verification.");let l=o.session,c=o.user;return l?.access_token&&(await this._saveSession(l),await this._notifyAllSubscribers(e.type=="recovery"?"PASSWORD_RECOVERY":"SIGNED_IN",l)),this._returnResult({data:{user:c,session:l},error:null})}catch(i){if(v(i))return this._returnResult({data:{user:null,session:null},error:i});throw i}}async signInWithSSO(e){var r,n,i,s,o;try{let a=null,l=null;this.flowType==="pkce"&&([a,l]=await gt(this.storage,this.storageKey));let c=await S(this.fetch,"POST",`${this.url}/sso`,{body:Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},"providerId"in e?{provider_id:e.providerId}:null),"domain"in e?{domain:e.domain}:null),{redirect_to:(n=(r=e.options)===null||r===void 0?void 0:r.redirectTo)!==null&&n!==void 0?n:void 0}),!((i=e?.options)===null||i===void 0)&&i.captchaToken?{gotrue_meta_security:{captcha_token:e.options.captchaToken}}:null),{skip_http_redirect:!0,code_challenge:a,code_challenge_method:l}),headers:this.headers,xform:Uc});return !((s=c.data)===null||s===void 0)&&s.url&&q()&&!(!((o=e.options)===null||o===void 0)&&o.skipBrowserRedirect)&&window.location.assign(c.data.url),this._returnResult(c)}catch(a){if(await z(this.storage,`${this.storageKey}-code-verifier`),v(a))return this._returnResult({data:null,error:a});throw a}}async reauthenticate(){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>await this._reauthenticate())}async _reauthenticate(){try{return await this._useSession(async e=>{let{data:{session:r},error:n}=e;if(n)throw n;if(!r)throw new J;let{error:i}=await S(this.fetch,"GET",`${this.url}/reauthenticate`,{headers:this.headers,jwt:r.access_token});return this._returnResult({data:{user:null,session:null},error:i})})}catch(e){if(v(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async resend(e){try{let r=`${this.url}/resend`;if("email"in e){let{email:n,type:i,options:s}=e,{error:o}=await S(this.fetch,"POST",r,{headers:this.headers,body:{email:n,type:i,gotrue_meta_security:{captcha_token:s?.captchaToken}},redirectTo:s?.emailRedirectTo});return this._returnResult({data:{user:null,session:null},error:o})}else if("phone"in e){let{phone:n,type:i,options:s}=e,{data:o,error:a}=await S(this.fetch,"POST",r,{headers:this.headers,body:{phone:n,type:i,gotrue_meta_security:{captcha_token:s?.captchaToken}}});return this._returnResult({data:{user:null,session:null,messageId:o?.message_id},error:a})}throw new ct("You must provide either an email or phone number and a type")}catch(r){if(v(r))return this._returnResult({data:{user:null,session:null},error:r});throw r}}async getSession(){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>this._useSession(async r=>r))}async _acquireLock(e,r){this._debug("#_acquireLock","begin",e);try{if(this.lockAcquired){let n=this.pendingInLock.length?this.pendingInLock[this.pendingInLock.length-1]:Promise.resolve(),i=(async()=>(await n,await r()))();return this.pendingInLock.push((async()=>{try{await i;}catch{}})()),i}return await this.lock(`lock:${this.storageKey}`,e,async()=>{this._debug("#_acquireLock","lock acquired for storage key",this.storageKey);try{this.lockAcquired=!0;let n=r();for(this.pendingInLock.push((async()=>{try{await n;}catch{}})()),await n;this.pendingInLock.length;){let i=[...this.pendingInLock];await Promise.all(i),this.pendingInLock.splice(0,i.length);}return await n}finally{this._debug("#_acquireLock","lock released for storage key",this.storageKey),this.lockAcquired=!1;}})}finally{this._debug("#_acquireLock","end");}}async _useSession(e){this._debug("#_useSession","begin");try{let r=await this.__loadSession();return await e(r)}finally{this._debug("#_useSession","end");}}async __loadSession(){this._debug("#__loadSession()","begin"),this.lockAcquired||this._debug("#__loadSession()","used outside of an acquired lock!",new Error().stack);try{let e=null,r=await Ve(this.storage,this.storageKey);if(this._debug("#getSession()","session from storage",r),r!==null&&(this._isValidSession(r)?e=r:(this._debug("#getSession()","session from storage is not valid"),await this._removeSession())),!e)return {data:{session:null},error:null};let n=e.expires_at?e.expires_at*1e3-Date.now()<Jn:!1;if(this._debug("#__loadSession()",`session has${n?"":" not"} expired`,"expires_at",e.expires_at),!n){if(this.userStorage){let o=await Ve(this.userStorage,this.storageKey+"-user");o?.user?e.user=o.user:e.user=ti();}if(this.storage.isServer&&e.user&&!e.user.__isUserNotAvailableProxy){let o={value:this.suppressGetSessionWarning};e.user=Mc(e.user,o),o.value&&(this.suppressGetSessionWarning=!0);}return {data:{session:e},error:null}}let{data:i,error:s}=await this._callRefreshToken(e.refresh_token);return s?this._returnResult({data:{session:null},error:s}):this._returnResult({data:{session:i},error:null})}finally{this._debug("#__loadSession()","end");}}async getUser(e){if(e)return await this._getUser(e);await this.initializePromise;let r=await this._acquireLock(this.lockAcquireTimeout,async()=>await this._getUser());return r.data.user&&(this.suppressGetSessionWarning=true),r}async _getUser(e){try{return e?await S(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:e,xform:Se}):await this._useSession(async r=>{var n,i,s;let{data:o,error:a}=r;if(a)throw a;return !(!((n=o.session)===null||n===void 0)&&n.access_token)&&!this.hasCustomAuthorizationHeader?{data:{user:null},error:new J}:await S(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:(s=(i=o.session)===null||i===void 0?void 0:i.access_token)!==null&&s!==void 0?s:void 0,xform:Se})})}catch(r){if(v(r))return Br(r)&&(await this._removeSession(),await z(this.storage,`${this.storageKey}-code-verifier`)),this._returnResult({data:{user:null},error:r});throw r}}async updateUser(e,r={}){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>await this._updateUser(e,r))}async _updateUser(e,r={}){try{return await this._useSession(async n=>{let{data:i,error:s}=n;if(s)throw s;if(!i.session)throw new J;let o=i.session,a=null,l=null;this.flowType==="pkce"&&e.email!=null&&([a,l]=await gt(this.storage,this.storageKey));let{data:c,error:u}=await S(this.fetch,"PUT",`${this.url}/user`,{headers:this.headers,redirectTo:r?.emailRedirectTo,body:Object.assign(Object.assign({},e),{code_challenge:a,code_challenge_method:l}),jwt:o.access_token,xform:Se});if(u)throw u;return o.user=c.user,await this._saveSession(o),await this._notifyAllSubscribers("USER_UPDATED",o),this._returnResult({data:{user:o.user},error:null})})}catch(n){if(await z(this.storage,`${this.storageKey}-code-verifier`),v(n))return this._returnResult({data:{user:null},error:n});throw n}}async setSession(e){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>await this._setSession(e))}async _setSession(e){try{if(!e.access_token||!e.refresh_token)throw new J;let r=Date.now()/1e3,n=r,i=!0,s=null,{payload:o}=Hr(e.access_token);if(o.exp&&(n=o.exp,i=n<=r),i){let{data:a,error:l}=await this._callRefreshToken(e.refresh_token);if(l)return this._returnResult({data:{user:null,session:null},error:l});if(!a)return {data:{user:null,session:null},error:null};s=a;}else {let{data:a,error:l}=await this._getUser(e.access_token);if(l)return this._returnResult({data:{user:null,session:null},error:l});s={access_token:e.access_token,refresh_token:e.refresh_token,user:a.user,token_type:"bearer",expires_in:n-r,expires_at:n},await this._saveSession(s),await this._notifyAllSubscribers("SIGNED_IN",s);}return this._returnResult({data:{user:s.user,session:s},error:null})}catch(r){if(v(r))return this._returnResult({data:{session:null,user:null},error:r});throw r}}async refreshSession(e){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>await this._refreshSession(e))}async _refreshSession(e){try{return await this._useSession(async r=>{var n;if(!e){let{data:o,error:a}=r;if(a)throw a;e=(n=o.session)!==null&&n!==void 0?n:void 0;}if(!e?.refresh_token)throw new J;let{data:i,error:s}=await this._callRefreshToken(e.refresh_token);return s?this._returnResult({data:{user:null,session:null},error:s}):i?this._returnResult({data:{user:i.user,session:i},error:null}):this._returnResult({data:{user:null,session:null},error:null})})}catch(r){if(v(r))return this._returnResult({data:{user:null,session:null},error:r});throw r}}async _getSessionFromURL(e,r){try{if(!q())throw new ut("No browser detected.");if(e.error||e.error_description||e.error_code)throw new ut(e.error_description||"Error in URL with unspecified error_description",{error:e.error||"unspecified_error",code:e.error_code||"unspecified_code"});switch(r){case "implicit":if(this.flowType==="pkce")throw new Ur("Not a valid PKCE flow url.");break;case "pkce":if(this.flowType==="implicit")throw new ut("Not a valid implicit grant flow url.");break;default:}if(r==="pkce"){if(this._debug("#_initialize()","begin","is PKCE flow",!0),!e.code)throw new Ur("No code detected.");let{data:w,error:y}=await this._exchangeCodeForSession(e.code);if(y)throw y;let I=new URL(window.location.href);return I.searchParams.delete("code"),window.history.replaceState(window.history.state,"",I.toString()),{data:{session:w.session,redirectType:null},error:null}}let{provider_token:n,provider_refresh_token:i,access_token:s,refresh_token:o,expires_in:a,expires_at:l,token_type:c}=e;if(!s||!a||!o||!c)throw new ut("No session defined in URL");let u=Math.round(Date.now()/1e3),d=parseInt(a),p=u+d;l&&(p=parseInt(l));let h=p-u;h*1e3<=lt&&console.warn(`@supabase/gotrue-js: Session as retrieved from URL expires in ${h}s, should have been closer to ${d}s`);let f=p-d;u-f>=120?console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued over 120s ago, URL could be stale",f,p,u):u-f<0&&console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued in the future? Check the device clock for skew",f,p,u);let{data:m,error:_}=await this._getUser(s);if(_)throw _;let b={provider_token:n,provider_refresh_token:i,access_token:s,expires_in:d,expires_at:p,refresh_token:o,token_type:c,user:m.user};return window.location.hash="",this._debug("#_getSessionFromURL()","clearing window.location.hash"),this._returnResult({data:{session:b,redirectType:e.type},error:null})}catch(n){if(v(n))return this._returnResult({data:{session:null,redirectType:null},error:n});throw n}}_isImplicitGrantCallback(e){return typeof this.detectSessionInUrl=="function"?this.detectSessionInUrl(new URL(window.location.href),e):!!(e.access_token||e.error_description)}async _isPKCECallback(e){let r=await Ve(this.storage,`${this.storageKey}-code-verifier`);return !!(e.code&&r)}async signOut(e={scope:"global"}){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>await this._signOut(e))}async _signOut({scope:e}={scope:"global"}){return await this._useSession(async r=>{var n;let{data:i,error:s}=r;if(s&&!Br(s))return this._returnResult({error:s});let o=(n=i.session)===null||n===void 0?void 0:n.access_token;if(o){let{error:a}=await this.admin.signOut(o,e);if(a&&!(vc(a)&&(a.status===404||a.status===401||a.status===403)||Br(a)))return this._returnResult({error:a})}return e!=="others"&&(await this._removeSession(),await z(this.storage,`${this.storageKey}-code-verifier`)),this._returnResult({error:null})})}onAuthStateChange(e){let r=Tc(),n={id:r,callback:e,unsubscribe:()=>{this._debug("#unsubscribe()","state change callback with id removed",r),this.stateChangeEmitters.delete(r);}};return this._debug("#onAuthStateChange()","registered callback with id",r),this.stateChangeEmitters.set(r,n),(async()=>(await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>{this._emitInitialSession(r);})))(),{data:{subscription:n}}}async _emitInitialSession(e){return await this._useSession(async r=>{var n,i;try{let{data:{session:s},error:o}=r;if(o)throw o;await((n=this.stateChangeEmitters.get(e))===null||n===void 0?void 0:n.callback("INITIAL_SESSION",s)),this._debug("INITIAL_SESSION","callback id",e,"session",s);}catch(s){await((i=this.stateChangeEmitters.get(e))===null||i===void 0?void 0:i.callback("INITIAL_SESSION",null)),this._debug("INITIAL_SESSION","callback id",e,"error",s),Br(s)?console.warn(s):console.error(s);}})}async resetPasswordForEmail(e,r={}){let n=null,i=null;this.flowType==="pkce"&&([n,i]=await gt(this.storage,this.storageKey,true));try{return await S(this.fetch,"POST",`${this.url}/recover`,{body:{email:e,code_challenge:n,code_challenge_method:i,gotrue_meta_security:{captcha_token:r.captchaToken}},headers:this.headers,redirectTo:r.redirectTo})}catch(s){if(await z(this.storage,`${this.storageKey}-code-verifier`),v(s))return this._returnResult({data:null,error:s});throw s}}async getUserIdentities(){var e;try{let{data:r,error:n}=await this.getUser();if(n)throw n;return this._returnResult({data:{identities:(e=r.user.identities)!==null&&e!==void 0?e:[]},error:null})}catch(r){if(v(r))return this._returnResult({data:null,error:r});throw r}}async linkIdentity(e){return "token"in e?this.linkIdentityIdToken(e):this.linkIdentityOAuth(e)}async linkIdentityOAuth(e){var r;try{let{data:n,error:i}=await this._useSession(async s=>{var o,a,l,c,u;let{data:d,error:p}=s;if(p)throw p;let h=await this._getUrlForProvider(`${this.url}/user/identities/authorize`,e.provider,{redirectTo:(o=e.options)===null||o===void 0?void 0:o.redirectTo,scopes:(a=e.options)===null||a===void 0?void 0:a.scopes,queryParams:(l=e.options)===null||l===void 0?void 0:l.queryParams,skipBrowserRedirect:!0});return await S(this.fetch,"GET",h,{headers:this.headers,jwt:(u=(c=d.session)===null||c===void 0?void 0:c.access_token)!==null&&u!==void 0?u:void 0})});if(i)throw i;return q()&&!(!((r=e.options)===null||r===void 0)&&r.skipBrowserRedirect)&&window.location.assign(n?.url),this._returnResult({data:{provider:e.provider,url:n?.url},error:null})}catch(n){if(v(n))return this._returnResult({data:{provider:e.provider,url:null},error:n});throw n}}async linkIdentityIdToken(e){return await this._useSession(async r=>{var n;try{let{error:i,data:{session:s}}=r;if(i)throw i;let{options:o,provider:a,token:l,access_token:c,nonce:u}=e,d=await S(this.fetch,"POST",`${this.url}/token?grant_type=id_token`,{headers:this.headers,jwt:(n=s?.access_token)!==null&&n!==void 0?n:void 0,body:{provider:a,id_token:l,access_token:c,nonce:u,link_identity:!0,gotrue_meta_security:{captcha_token:o?.captchaToken}},xform:de}),{data:p,error:h}=d;return h?this._returnResult({data:{user:null,session:null},error:h}):!p||!p.session||!p.user?this._returnResult({data:{user:null,session:null},error:new Ne}):(p.session&&(await this._saveSession(p.session),await this._notifyAllSubscribers("USER_UPDATED",p.session)),this._returnResult({data:p,error:h}))}catch(i){if(await z(this.storage,`${this.storageKey}-code-verifier`),v(i))return this._returnResult({data:{user:null,session:null},error:i});throw i}})}async unlinkIdentity(e){try{return await this._useSession(async r=>{var n,i;let{data:s,error:o}=r;if(o)throw o;return await S(this.fetch,"DELETE",`${this.url}/user/identities/${e.identity_id}`,{headers:this.headers,jwt:(i=(n=s.session)===null||n===void 0?void 0:n.access_token)!==null&&i!==void 0?i:void 0})})}catch(r){if(v(r))return this._returnResult({data:null,error:r});throw r}}async _refreshAccessToken(e){let r=`#_refreshAccessToken(${e.substring(0,5)}...)`;this._debug(r,"begin");try{let n=Date.now();return await $c(async i=>(i>0&&await Oc(200*Math.pow(2,i-1)),this._debug(r,"refreshing attempt",i),await S(this.fetch,"POST",`${this.url}/token?grant_type=refresh_token`,{body:{refresh_token:e},headers:this.headers,xform:de})),(i,s)=>{let o=200*Math.pow(2,i);return s&&Yn(s)&&Date.now()+o-n<lt})}catch(n){if(this._debug(r,"error",n),v(n))return this._returnResult({data:{session:null,user:null},error:n});throw n}finally{this._debug(r,"end");}}_isValidSession(e){return typeof e=="object"&&e!==null&&"access_token"in e&&"refresh_token"in e&&"expires_at"in e}async _handleProviderSignIn(e,r){let n=await this._getUrlForProvider(`${this.url}/authorize`,e,{redirectTo:r.redirectTo,scopes:r.scopes,queryParams:r.queryParams});return this._debug("#_handleProviderSignIn()","provider",e,"options",r,"url",n),q()&&!r.skipBrowserRedirect&&window.location.assign(n),{data:{provider:e,url:n},error:null}}async _recoverAndRefresh(){var e,r;let n="#_recoverAndRefresh()";this._debug(n,"begin");try{let i=await Ve(this.storage,this.storageKey);if(i&&this.userStorage){let o=await Ve(this.userStorage,this.storageKey+"-user");!this.storage.isServer&&Object.is(this.storage,this.userStorage)&&!o&&(o={user:i.user},await ft(this.userStorage,this.storageKey+"-user",o)),i.user=(e=o?.user)!==null&&e!==void 0?e:ti();}else if(i&&!i.user&&!i.user){let o=await Ve(this.storage,this.storageKey+"-user");o&&o?.user?(i.user=o.user,await z(this.storage,this.storageKey+"-user"),await ft(this.storage,this.storageKey,i)):i.user=ti();}if(this._debug(n,"session from storage",i),!this._isValidSession(i)){this._debug(n,"session is not valid"),i!==null&&await this._removeSession();return}let s=((r=i.expires_at)!==null&&r!==void 0?r:1/0)*1e3-Date.now()<Jn;if(this._debug(n,`session has${s?"":" not"} expired with margin of ${Jn}s`),s){if(this.autoRefreshToken&&i.refresh_token){let{error:o}=await this._callRefreshToken(i.refresh_token);o&&(console.error(o),Yn(o)||(this._debug(n,"refresh failed with a non-retryable error, removing the session",o),await this._removeSession()));}}else if(i.user&&i.user.__isUserNotAvailableProxy===!0)try{let{data:o,error:a}=await this._getUser(i.access_token);!a&&o?.user?(i.user=o.user,await this._saveSession(i),await this._notifyAllSubscribers("SIGNED_IN",i)):this._debug(n,"could not get user data, skipping SIGNED_IN notification");}catch(o){console.error("Error getting user data:",o),this._debug(n,"error getting user data, skipping SIGNED_IN notification",o);}else await this._notifyAllSubscribers("SIGNED_IN",i);}catch(i){this._debug(n,"error",i),console.error(i);return}finally{this._debug(n,"end");}}async _callRefreshToken(e){var r,n;if(!e)throw new J;if(this.refreshingDeferred)return this.refreshingDeferred.promise;let i=`#_callRefreshToken(${e.substring(0,5)}...)`;this._debug(i,"begin");try{this.refreshingDeferred=new Fr;let{data:s,error:o}=await this._refreshAccessToken(e);if(o)throw o;if(!s.session)throw new J;await this._saveSession(s.session),await this._notifyAllSubscribers("TOKEN_REFRESHED",s.session);let a={data:s.session,error:null};return this.refreshingDeferred.resolve(a),a}catch(s){if(this._debug(i,"error",s),v(s)){let o={data:null,error:s};return Yn(s)||await this._removeSession(),(r=this.refreshingDeferred)===null||r===void 0||r.resolve(o),o}throw (n=this.refreshingDeferred)===null||n===void 0||n.reject(s),s}finally{this.refreshingDeferred=null,this._debug(i,"end");}}async _notifyAllSubscribers(e,r,n=true){let i=`#_notifyAllSubscribers(${e})`;this._debug(i,"begin",r,`broadcast = ${n}`);try{this.broadcastChannel&&n&&this.broadcastChannel.postMessage({event:e,session:r});let s=[],o=Array.from(this.stateChangeEmitters.values()).map(async a=>{try{await a.callback(e,r);}catch(l){s.push(l);}});if(await Promise.all(o),s.length>0){for(let a=0;a<s.length;a+=1)console.error(s[a]);throw s[0]}}finally{this._debug(i,"end");}}async _saveSession(e){this._debug("#_saveSession()",e),this.suppressGetSessionWarning=true,await z(this.storage,`${this.storageKey}-code-verifier`);let r=Object.assign({},e),n=r.user&&r.user.__isUserNotAvailableProxy===true;if(this.userStorage){!n&&r.user&&await ft(this.userStorage,this.storageKey+"-user",{user:r.user});let i=Object.assign({},r);delete i.user;let s=Ls(i);await ft(this.storage,this.storageKey,s);}else {let i=Ls(r);await ft(this.storage,this.storageKey,i);}}async _removeSession(){this._debug("#_removeSession()"),this.suppressGetSessionWarning=false,await z(this.storage,this.storageKey),await z(this.storage,this.storageKey+"-code-verifier"),await z(this.storage,this.storageKey+"-user"),this.userStorage&&await z(this.userStorage,this.storageKey+"-user"),await this._notifyAllSubscribers("SIGNED_OUT",null);}_removeVisibilityChangedCallback(){this._debug("#_removeVisibilityChangedCallback()");let e=this.visibilityChangedCallback;this.visibilityChangedCallback=null;try{e&&q()&&window?.removeEventListener&&window.removeEventListener("visibilitychange",e);}catch(r){console.error("removing visibilitychange callback failed",r);}}async _startAutoRefresh(){await this._stopAutoRefresh(),this._debug("#_startAutoRefresh()");let e=setInterval(()=>this._autoRefreshTokenTick(),lt);this.autoRefreshTicker=e,e&&typeof e=="object"&&typeof e.unref=="function"?e.unref():typeof Deno<"u"&&typeof Deno.unrefTimer=="function"&&Deno.unrefTimer(e);let r=setTimeout(async()=>{await this.initializePromise,await this._autoRefreshTokenTick();},0);this.autoRefreshTickTimeout=r,r&&typeof r=="object"&&typeof r.unref=="function"?r.unref():typeof Deno<"u"&&typeof Deno.unrefTimer=="function"&&Deno.unrefTimer(r);}async _stopAutoRefresh(){this._debug("#_stopAutoRefresh()");let e=this.autoRefreshTicker;this.autoRefreshTicker=null,e&&clearInterval(e);let r=this.autoRefreshTickTimeout;this.autoRefreshTickTimeout=null,r&&clearTimeout(r);}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 e=Date.now();try{return await this._useSession(async r=>{let{data:{session:n}}=r;if(!n||!n.refresh_token||!n.expires_at){this._debug("#_autoRefreshTokenTick()","no session");return}let i=Math.floor((n.expires_at*1e3-e)/lt);this._debug("#_autoRefreshTokenTick()",`access token expires in ${i} ticks, a tick lasts ${lt}ms, refresh threshold is ${zn} ticks`),i<=zn&&await this._callRefreshToken(n.refresh_token);})}catch(r){console.error("Auto refresh tick failed with error. This is likely a transient error.",r);}}finally{this._debug("#_autoRefreshTokenTick()","end");}});}catch(e){if(e.isAcquireTimeout||e instanceof qr)this._debug("auto refresh token tick lock not available");else throw e}}async _handleVisibilityChange(){if(this._debug("#_handleVisibilityChange()"),!q()||!window?.addEventListener)return this.autoRefreshToken&&this.startAutoRefresh(),false;try{this.visibilityChangedCallback=async()=>{try{await this._onVisibilityChanged(!1);}catch(e){this._debug("#visibilityChangedCallback","error",e);}},window?.addEventListener("visibilitychange",this.visibilityChangedCallback),await this._onVisibilityChanged(!0);}catch(e){console.error("_handleVisibilityChange",e);}}async _onVisibilityChanged(e){let r=`#_onVisibilityChanged(${e})`;this._debug(r,"visibilityState",document.visibilityState),document.visibilityState==="visible"?(this.autoRefreshToken&&this._startAutoRefresh(),e||(await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>{if(document.visibilityState!=="visible"){this._debug(r,"acquired the lock to recover the session, but the browser visibilityState is no longer visible, aborting");return}await this._recoverAndRefresh();}))):document.visibilityState==="hidden"&&this.autoRefreshToken&&this._stopAutoRefresh();}async _getUrlForProvider(e,r,n){let i=[`provider=${encodeURIComponent(r)}`];if(n?.redirectTo&&i.push(`redirect_to=${encodeURIComponent(n.redirectTo)}`),n?.scopes&&i.push(`scopes=${encodeURIComponent(n.scopes)}`),this.flowType==="pkce"){let[s,o]=await gt(this.storage,this.storageKey),a=new URLSearchParams({code_challenge:`${encodeURIComponent(s)}`,code_challenge_method:`${encodeURIComponent(o)}`});i.push(a.toString());}if(n?.queryParams){let s=new URLSearchParams(n.queryParams);i.push(s.toString());}return n?.skipBrowserRedirect&&i.push(`skip_http_redirect=${n.skipBrowserRedirect}`),`${e}?${i.join("&")}`}async _unenroll(e){try{return await this._useSession(async r=>{var n;let{data:i,error:s}=r;return s?this._returnResult({data:null,error:s}):await S(this.fetch,"DELETE",`${this.url}/factors/${e.factorId}`,{headers:this.headers,jwt:(n=i?.session)===null||n===void 0?void 0:n.access_token})})}catch(r){if(v(r))return this._returnResult({data:null,error:r});throw r}}async _enroll(e){try{return await this._useSession(async r=>{var n,i;let{data:s,error:o}=r;if(o)return this._returnResult({data:null,error:o});let a=Object.assign({friendly_name:e.friendlyName,factor_type:e.factorType},e.factorType==="phone"?{phone:e.phone}:e.factorType==="totp"?{issuer:e.issuer}:{}),{data:l,error:c}=await S(this.fetch,"POST",`${this.url}/factors`,{body:a,headers:this.headers,jwt:(n=s?.session)===null||n===void 0?void 0:n.access_token});return c?this._returnResult({data:null,error:c}):(e.factorType==="totp"&&l.type==="totp"&&(!((i=l?.totp)===null||i===void 0)&&i.qr_code)&&(l.totp.qr_code=`data:image/svg+xml;utf-8,${l.totp.qr_code}`),this._returnResult({data:l,error:null}))})}catch(r){if(v(r))return this._returnResult({data:null,error:r});throw r}}async _verify(e){return this._acquireLock(this.lockAcquireTimeout,async()=>{try{return await this._useSession(async r=>{var n;let{data:i,error:s}=r;if(s)return this._returnResult({data:null,error:s});let o=Object.assign({challenge_id:e.challengeId},"webauthn"in e?{webauthn:Object.assign(Object.assign({},e.webauthn),{credential_response:e.webauthn.type==="create"?eu(e.webauthn.credential_response):tu(e.webauthn.credential_response)})}:{code:e.code}),{data:a,error:l}=await S(this.fetch,"POST",`${this.url}/factors/${e.factorId}/verify`,{body:o,headers:this.headers,jwt:(n=i?.session)===null||n===void 0?void 0:n.access_token});return l?this._returnResult({data:null,error:l}):(await this._saveSession(Object.assign({expires_at:Math.round(Date.now()/1e3)+a.expires_in},a)),await this._notifyAllSubscribers("MFA_CHALLENGE_VERIFIED",a),this._returnResult({data:a,error:l}))})}catch(r){if(v(r))return this._returnResult({data:null,error:r});throw r}})}async _challenge(e){return this._acquireLock(this.lockAcquireTimeout,async()=>{try{return await this._useSession(async r=>{var n;let{data:i,error:s}=r;if(s)return this._returnResult({data:null,error:s});let o=await S(this.fetch,"POST",`${this.url}/factors/${e.factorId}/challenge`,{body:e,headers:this.headers,jwt:(n=i?.session)===null||n===void 0?void 0:n.access_token});if(o.error)return o;let{data:a}=o;if(a.type!=="webauthn")return {data:a,error:null};switch(a.webauthn.type){case "create":return {data:Object.assign(Object.assign({},a),{webauthn:Object.assign(Object.assign({},a.webauthn),{credential_options:Object.assign(Object.assign({},a.webauthn.credential_options),{publicKey:Zc(a.webauthn.credential_options.publicKey)})})}),error:null};case "request":return {data:Object.assign(Object.assign({},a),{webauthn:Object.assign(Object.assign({},a.webauthn),{credential_options:Object.assign(Object.assign({},a.webauthn.credential_options),{publicKey:Qc(a.webauthn.credential_options.publicKey)})})}),error:null}}})}catch(r){if(v(r))return this._returnResult({data:null,error:r});throw r}})}async _challengeAndVerify(e){let{data:r,error:n}=await this._challenge({factorId:e.factorId});return n?this._returnResult({data:null,error:n}):await this._verify({factorId:e.factorId,challengeId:r.id,code:e.code})}async _listFactors(){var e;let{data:{user:r},error:n}=await this.getUser();if(n)return {data:null,error:n};let i={all:[],phone:[],totp:[],webauthn:[]};for(let s of (e=r?.factors)!==null&&e!==void 0?e:[])i.all.push(s),s.status==="verified"&&i[s.factor_type].push(s);return {data:i,error:null}}async _getAuthenticatorAssuranceLevel(e){var r,n,i,s;if(e)try{let{payload:h}=Hr(e),f=null;h.aal&&(f=h.aal);let m=f,{data:{user:_},error:b}=await this.getUser(e);if(b)return this._returnResult({data:null,error:b});((n=(r=_?.factors)===null||r===void 0?void 0:r.filter(I=>I.status==="verified"))!==null&&n!==void 0?n:[]).length>0&&(m="aal2");let y=h.amr||[];return {data:{currentLevel:f,nextLevel:m,currentAuthenticationMethods:y},error:null}}catch(h){if(v(h))return this._returnResult({data:null,error:h});throw h}let{data:{session:o},error:a}=await this.getSession();if(a)return this._returnResult({data:null,error:a});if(!o)return {data:{currentLevel:null,nextLevel:null,currentAuthenticationMethods:[]},error:null};let{payload:l}=Hr(o.access_token),c=null;l.aal&&(c=l.aal);let u=c;((s=(i=o.user.factors)===null||i===void 0?void 0:i.filter(h=>h.status==="verified"))!==null&&s!==void 0?s:[]).length>0&&(u="aal2");let p=l.amr||[];return {data:{currentLevel:c,nextLevel:u,currentAuthenticationMethods:p},error:null}}async _getAuthorizationDetails(e){try{return await this._useSession(async r=>{let{data:{session:n},error:i}=r;return i?this._returnResult({data:null,error:i}):n?await S(this.fetch,"GET",`${this.url}/oauth/authorizations/${e}`,{headers:this.headers,jwt:n.access_token,xform:s=>({data:s,error:null})}):this._returnResult({data:null,error:new J})})}catch(r){if(v(r))return this._returnResult({data:null,error:r});throw r}}async _approveAuthorization(e,r){try{return await this._useSession(async n=>{let{data:{session:i},error:s}=n;if(s)return this._returnResult({data:null,error:s});if(!i)return this._returnResult({data:null,error:new J});let o=await S(this.fetch,"POST",`${this.url}/oauth/authorizations/${e}/consent`,{headers:this.headers,jwt:i.access_token,body:{action:"approve"},xform:a=>({data:a,error:null})});return o.data&&o.data.redirect_url&&q()&&!r?.skipBrowserRedirect&&window.location.assign(o.data.redirect_url),o})}catch(n){if(v(n))return this._returnResult({data:null,error:n});throw n}}async _denyAuthorization(e,r){try{return await this._useSession(async n=>{let{data:{session:i},error:s}=n;if(s)return this._returnResult({data:null,error:s});if(!i)return this._returnResult({data:null,error:new J});let o=await S(this.fetch,"POST",`${this.url}/oauth/authorizations/${e}/consent`,{headers:this.headers,jwt:i.access_token,body:{action:"deny"},xform:a=>({data:a,error:null})});return o.data&&o.data.redirect_url&&q()&&!r?.skipBrowserRedirect&&window.location.assign(o.data.redirect_url),o})}catch(n){if(v(n))return this._returnResult({data:null,error:n});throw n}}async _listOAuthGrants(){try{return await this._useSession(async e=>{let{data:{session:r},error:n}=e;return n?this._returnResult({data:null,error:n}):r?await S(this.fetch,"GET",`${this.url}/user/oauth/grants`,{headers:this.headers,jwt:r.access_token,xform:i=>({data:i,error:null})}):this._returnResult({data:null,error:new J})})}catch(e){if(v(e))return this._returnResult({data:null,error:e});throw e}}async _revokeOAuthGrant(e){try{return await this._useSession(async r=>{let{data:{session:n},error:i}=r;return i?this._returnResult({data:null,error:i}):n?(await S(this.fetch,"DELETE",`${this.url}/user/oauth/grants`,{headers:this.headers,jwt:n.access_token,query:{client_id:e.clientId},noResolveJson:!0}),{data:{},error:null}):this._returnResult({data:null,error:new J})})}catch(r){if(v(r))return this._returnResult({data:null,error:r});throw r}}async fetchJwk(e,r={keys:[]}){let n=r.keys.find(a=>a.kid===e);if(n)return n;let i=Date.now();if(n=this.jwks.keys.find(a=>a.kid===e),n&&this.jwks_cached_at+bc>i)return n;let{data:s,error:o}=await S(this.fetch,"GET",`${this.url}/.well-known/jwks.json`,{headers:this.headers});if(o)throw o;return !s.keys||s.keys.length===0||(this.jwks=s,this.jwks_cached_at=i,n=s.keys.find(a=>a.kid===e),!n)?null:n}async getClaims(e,r={}){try{let n=e;if(!n){let{data:h,error:f}=await this.getSession();if(f||!h.session)return this._returnResult({data:null,error:f});n=h.session.access_token;}let{header:i,payload:s,signature:o,raw:{header:a,payload:l}}=Hr(n);r?.allowExpired||jc(s.exp);let c=!i.alg||i.alg.startsWith("HS")||!i.kid||!("crypto"in globalThis&&"subtle"in globalThis.crypto)?null:await this.fetchJwk(i.kid,r?.keys?{keys:r.keys}:r?.jwks);if(!c){let{error:h}=await this.getUser(n);if(h)throw h;return {data:{claims:s,header:i,signature:o},error:null}}let u=Dc(i.alg),d=await crypto.subtle.importKey("jwk",c,u,!0,["verify"]);if(!await crypto.subtle.verify(u,d,o,xc(`${a}.${l}`)))throw new dt("Invalid JWT signature");return {data:{claims:s,header:i,signature:o},error:null}}catch(n){if(v(n))return this._returnResult({data:null,error:n});throw n}}};oi.nextInstanceID={};Ys=oi;});var nu=R(()=>{ni();});var Vm,Zs,iu=R(()=>{Xs();Vm=Ys,Zs=Vm;});var Qs=R(()=>{ni();Xs();nu();iu();Fs();pt();zs();});function Kr(t){"@babel/helpers - typeof";return Kr=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(e){return typeof e}:function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},Kr(t)}function t_(t,e){if(Kr(t)!="object"||!t)return t;var r=t[Symbol.toPrimitive];if(r!==void 0){var n=r.call(t,e);if(Kr(n)!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return (e==="string"?String:Number)(t)}function r_(t){var e=t_(t,"string");return Kr(e)=="symbol"?e:e+""}function n_(t,e,r){return (e=r_(e))in t?Object.defineProperty(t,e,{value:r,enumerable:true,configurable:true,writable:true}):t[e]=r,t}function su(t,e){var r=Object.keys(t);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(t);e&&(n=n.filter(function(i){return Object.getOwnPropertyDescriptor(t,i).enumerable})),r.push.apply(r,n);}return r}function W(t){for(var e=1;e<arguments.length;e++){var r=arguments[e]!=null?arguments[e]:{};e%2?su(Object(r),true).forEach(function(n){n_(t,n,r[n]);}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(r)):su(Object(r)).forEach(function(n){Object.defineProperty(t,n,Object.getOwnPropertyDescriptor(r,n));});}return t}function a_(t){return t.endsWith("/")?t:t+"/"}function l_(t,e){var r,n;let{db:i,auth:s,realtime:o,global:a}=t,{db:l,auth:c,realtime:u,global:d}=e,p={db:W(W({},l),i),auth:W(W({},c),s),realtime:W(W({},u),o),storage:{},global:W(W(W({},d),a),{},{headers:W(W({},(r=d?.headers)!==null&&r!==void 0?r:{}),(n=a?.headers)!==null&&n!==void 0?n:{})}),accessToken:async()=>""};return t.accessToken?p.accessToken=t.accessToken:delete p.accessToken,p}function c_(t){let e=t?.trim();if(!e)throw new Error("supabaseUrl is required.");if(!e.match(/^https?:\/\//i))throw new Error("Invalid supabaseUrl: Must be a valid HTTP or HTTPS URL.");try{return new URL(a_(e))}catch{throw Error("Invalid supabaseUrl: Provided URL is malformed.")}}function p_(){if(typeof window<"u")return false;let t=globalThis.process;if(!t)return false;let e=t.version;if(e==null)return false;let r=e.match(/^v(\d+)\./);return r?parseInt(r[1],10)<=18:false}var Gm,Jr,Ym,Xm,Zm,Qm,e_,i_,s_,o_,u_,d_,er,ai=R(()=>{Nl();Hl();Is();mc();Qs();Is();Qs();Gm="2.103.2",Jr="";typeof Deno<"u"?Jr="deno":typeof document<"u"?Jr="web":typeof navigator<"u"&&navigator.product==="ReactNative"?Jr="react-native":Jr="node";Ym={"X-Client-Info":`supabase-js-${Jr}/${Gm}`},Xm={headers:Ym},Zm={schema:"public"},Qm={autoRefreshToken:true,persistSession:true,detectSessionInUrl:true,flowType:"implicit"},e_={};i_=t=>t?(...e)=>t(...e):(...e)=>fetch(...e),s_=()=>Headers,o_=(t,e,r)=>{let n=i_(r),i=s_();return async(s,o)=>{var a;let l=(a=await e())!==null&&a!==void 0?a:t,c=new i(o?.headers);return c.has("apikey")||c.set("apikey",t),c.has("Authorization")||c.set("Authorization",`Bearer ${l}`),n(s,W(W({},o),{},{headers:c}))}};u_=class extends Zs{constructor(t){super(t);}},d_=class{constructor(t,e,r){var n,i;this.supabaseUrl=t,this.supabaseKey=e;let s=c_(t);if(!e)throw new Error("supabaseKey is required.");this.realtimeUrl=new URL("realtime/v1",s),this.realtimeUrl.protocol=this.realtimeUrl.protocol.replace("http","ws"),this.authUrl=new URL("auth/v1",s),this.storageUrl=new URL("storage/v1",s),this.functionsUrl=new URL("functions/v1",s);let o=`sb-${s.hostname.split(".")[0]}-auth-token`,a={db:Zm,realtime:e_,auth:W(W({},Qm),{},{storageKey:o}),global:Xm},l=l_(r??{},a);if(this.storageKey=(n=l.auth.storageKey)!==null&&n!==void 0?n:"",this.headers=(i=l.global.headers)!==null&&i!==void 0?i:{},l.accessToken)this.accessToken=l.accessToken,this.auth=new Proxy({},{get:(u,d)=>{throw new Error(`@supabase/supabase-js: Supabase Client is configured with the accessToken option, accessing supabase.auth.${String(d)} is not possible`)}});else {var c;this.auth=this._initSupabaseAuthClient((c=l.auth)!==null&&c!==void 0?c:{},this.headers,l.global.fetch);}this.fetch=o_(e,this._getAccessToken.bind(this),l.global.fetch),this.realtime=this._initRealtimeClient(W({headers:this.headers,accessToken:this._getAccessToken.bind(this)},l.realtime)),this.accessToken&&Promise.resolve(this.accessToken()).then(u=>this.realtime.setAuth(u)).catch(u=>console.warn("Failed to set initial Realtime auth token:",u)),this.rest=new Bl(new URL("rest/v1",s).href,{headers:this.headers,schema:l.db.schema,fetch:this.fetch,timeout:l.db.timeout,urlLengthLimit:l.db.urlLengthLimit}),this.storage=new gc(this.storageUrl.href,this.headers,this.fetch,r?.storage),l.accessToken||this._listenForAuthEvents();}get functions(){return new Sr(this.functionsUrl.href,{headers:this.headers,customFetch:this.fetch})}from(t){return this.rest.from(t)}schema(t){return this.rest.schema(t)}rpc(t,e={},r={head:false,get:false,count:void 0}){return this.rest.rpc(t,e,r)}channel(t,e={config:{}}){return this.realtime.channel(t,e)}getChannels(){return this.realtime.getChannels()}removeChannel(t){return this.realtime.removeChannel(t)}removeAllChannels(){return this.realtime.removeAllChannels()}async _getAccessToken(){var t=this,e,r;if(t.accessToken)return await t.accessToken();let{data:n}=await t.auth.getSession();return (e=(r=n.session)===null||r===void 0?void 0:r.access_token)!==null&&e!==void 0?e:t.supabaseKey}_initSupabaseAuthClient({autoRefreshToken:t,persistSession:e,detectSessionInUrl:r,storage:n,userStorage:i,storageKey:s,flowType:o,lock:a,debug:l,throwOnError:c},u,d){let p={Authorization:`Bearer ${this.supabaseKey}`,apikey:`${this.supabaseKey}`};return new u_({url:this.authUrl.href,headers:W(W({},p),u),storageKey:s,autoRefreshToken:t,persistSession:e,detectSessionInUrl:r,storage:n,userStorage:i,flowType:o,lock:a,debug:l,throwOnError:c,fetch:d,hasCustomAuthorizationHeader:Object.keys(this.headers).some(h=>h.toLowerCase()==="authorization")})}_initRealtimeClient(t){return new Vt(this.realtimeUrl.href,W(W({},t),{},{params:W(W({},{apikey:this.supabaseKey}),t?.params)}))}_listenForAuthEvents(){return this.auth.onAuthStateChange((t,e)=>{this._handleTokenChanged(t,"CLIENT",e?.access_token);})}_handleTokenChanged(t,e,r){(t==="TOKEN_REFRESHED"||t==="SIGNED_IN")&&this.changedAccessToken!==r?(this.changedAccessToken=r,this.realtime.setAuth(r)):t==="SIGNED_OUT"&&(this.realtime.setAuth(),e=="STORAGE"&&this.auth.signOut(),this.changedAccessToken=void 0);}},er=(t,e,r)=>new d_(t,e,r);p_()&&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 pe(t){let e=t.SUPABASE_URL??t.VITE_SUPABASE_URL??"https://xygyyikpgykarmqujajf.supabase.co",r=t.SUPABASE_ANON_KEY??t.VITE_SUPABASE_ANON_KEY??"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6Inh5Z3l5aWtwZ3lrYXJtcXVqYWpmIiwicm9sZSI6ImFub24iLCJpYXQiOjE3NzYyMjIyOTcsImV4cCI6MjA5MTc5ODI5N30.y_SPm1eJeofb4zYgPCogTJUPr4e7-z92BzcRzqQiK9g";if(!e||!r)throw new eo("missing_supabase_config","Missing Supabase client configuration for CLI login.");return {supabaseUrl:e,supabaseAnonKey:r}}var eo,Vr=R(()=>{eo=class extends Error{constructor(r,n=r){super(n);this.code=r;this.name="CliAuthConfigError";}code};});async function lu(t){let e=pe(t.env),r=m_(),n=er(e.supabaseUrl,e.supabaseAnonKey,{auth:{persistSession:true,detectSessionInUrl:false,flowType:"pkce",storage:r}}),i=await __({timeoutMs:t.timeoutMs??300*1e3}),s=i.redirectUri;try{let{data:o,error:a}=await n.auth.signInWithOAuth({provider:"github",options:{redirectTo:s,skipBrowserRedirect:!0}});if(a||!o.url)throw new G("oauth_start_failed",a?.message??"Supabase did not return an OAuth URL.");t.onOpen?.({url:o.url,redirectUri:s}),await t.openUrl(o.url);let l=await i.waitForCode(),{data:c,error:u}=await n.auth.exchangeCodeForSession(l);if(u||!c.session?.access_token||!c.session.refresh_token)throw new G("oauth_exchange_failed",u?.message??"Supabase did not return a complete session.");let d=await f_(n,c.session,t.promptMfaCode),p=cu(e.supabaseUrl);return await st(t.env).set(p,JSON.stringify(d)),{session:d,account:p}}finally{await i.close();}}async function f_(t,e,r){let{data:n,error:i}=await t.auth.mfa.getAuthenticatorAssuranceLevel();if(i)throw new G("mfa_check_failed",i.message);if(n.currentLevel===n.nextLevel||n.nextLevel!=="aal2")return g_(e);let{data:s,error:o}=await t.auth.mfa.listFactors();if(o)throw new G("mfa_factor_lookup_failed",o.message);let a=s.totp.find(d=>d.status==="verified");if(!a)throw new G("mfa_factor_missing","Two-factor authentication is enabled, but no verified TOTP factor was returned.");if(!r)throw new G("mfa_required","Two-factor authentication is required for this account.");let l=(await r("Authenticator code: ")).trim(),{data:c,error:u}=await t.auth.mfa.challengeAndVerify({factorId:a.id,code:l});if(u||!c)throw new G("mfa_verify_failed",u?.message??"Two-factor authentication failed.");return {access_token:c.access_token,refresh_token:c.refresh_token,expires_at:Math.floor(Date.now()/1e3)+c.expires_in,expires_in:c.expires_in,token_type:c.token_type,user:{id:c.user.id,email:c.user.email??void 0}}}function g_(t){return {access_token:t.access_token,refresh_token:t.refresh_token,expires_at:t.expires_at??Math.floor(Date.now()/1e3)+(t.expires_in??3600),expires_in:t.expires_in??void 0,token_type:t.token_type,user:{id:t.user.id,email:t.user.email??void 0}}}async function to(t){let e=pe(t.env),r=await ou(t.fetch,e,"auth-device-start",{});t.onPending?.({userCode:r.user_code,verificationUri:r.verification_uri,interval:r.interval});let n=Date.now()+r.expires_in*1e3,i=r.interval;for(;Date.now()<=n;){await t.sleep(i*1e3);let s=await ou(t.fetch,e,"auth-device-token",{device_code:r.device_code},{acceptError:true});if("access_token"in s){let o=cu(e.supabaseUrl);return await st(t.env).set(o,JSON.stringify(s)),{session:s,account:o}}switch(s.error){case "authorization_pending":i=s.interval??i;break;case "slow_down":i=s.interval??Math.min(i+5,30);break;case "expired_token":throw new De("expired_token","The device login code expired.");case "access_denied":throw new De("access_denied","The device login request was denied.");default:throw new De(s.error,`Device login failed: ${s.error}`)}}throw new De("expired_token","The device login code expired.")}function cu(t){let e=new URL(t).hostname;return `sb-${e.endsWith(".supabase.co")?e.slice(0,-12):e}-auth-token`}async function ou(t,e,r,n,i={}){let s=await t(`${e.supabaseUrl}/functions/v1/${r}`,{method:"POST",headers:{"content-type":"application/json",apikey:e.supabaseAnonKey},body:JSON.stringify(n)}),o=await s.json().catch(()=>({}));if(!s.ok&&!i.acceptError)throw new De(o.error??"request_failed");return o}function m_(){let t=new Map;return {getItem:e=>t.get(e)??null,setItem:(e,r)=>{t.set(e,r);},removeItem:e=>{t.delete(e);}}}async function __(t){let e=null,r=null,n=false,i=new Promise((l,c)=>{e=l,r=c;}),s=createServer((l,c)=>{w_(l,c,(u,d)=>{n||(n=true,u?r?.(u):e?.(d));});});await new Promise((l,c)=>{s.once("error",c),s.listen(0,"127.0.0.1",()=>{s.off("error",c),l();});});let o=s.address();if(!o||typeof o=="string")throw await au(s),new G("callback_server_failed");let a=setTimeout(()=>{n||(n=true,r?.(new G("oauth_timeout","Browser login timed out.")));},t.timeoutMs);return {redirectUri:`http://127.0.0.1:${o.port}/auth/callback`,waitForCode:()=>i,close:async()=>{clearTimeout(a),await au(s);}}}function w_(t,e,r){let n=t.headers.host??"127.0.0.1",i=new URL(t.url??"/",`http://${n}`);if(i.pathname!=="/auth/callback"){e.writeHead(404,{"content-type":"text/plain"}),e.end("Not found");return}let s=i.searchParams.get("error")??i.searchParams.get("error_description"),o=i.searchParams.get("code");if(s){e.writeHead(400,{"content-type":"text/plain"}),e.end("Pathrule login failed. You can close this window."),r(new G("oauth_denied",s),"");return}if(!o){e.writeHead(400,{"content-type":"text/plain"}),e.end("Pathrule login could not verify this browser response."),r(new G("oauth_invalid_callback"),"");return}e.writeHead(200,{"content-type":"text/html; charset=utf-8"}),e.end("<!doctype html><title>Pathrule CLI</title><p>Pathrule CLI is signed in. You can close this window.</p>"),r(null,o);}async function au(t){t.listening&&await new Promise(e=>t.close(()=>e()));}var De,G,li=R(()=>{_s();ai();Vr();Vr();De=class extends Error{constructor(r,n=r){super(n);this.code=r;this.name="DeviceLoginError";}code},G=class extends Error{constructor(r,n=r){super(n);this.code=r;this.name="BrowserLoginError";}code};});async function E_(t){await new Promise(e=>setTimeout(e,t));}async function R_(t){try{await mkdir(dirname(t),{recursive:!0,mode:448}),await chmod(dirname(t),448).catch(()=>{});let e=await open(t,"wx",384);await e.writeFile(`${process.pid}:${Date.now()}
48
- `,"utf8"),await e.close();let r=!1;return async()=>{r||(r=!0,await rm$1(t,{force:!0}).catch(()=>{}));}}catch(e){if(e.code==="EEXIST")return null;throw e}}async function x_(t,e){try{let{stat:r}=await import('fs/promises'),n=await r(t);Date.now()-n.mtimeMs>e&&await rm$1(t,{force:!0});}catch{}}async function pu(t,e={}){let r=e.timeoutMs??v_,n=e.staleMs??S_,i=e.lockFile??A(e.env).tokenLockFile,s=Date.now()+r;for(;Date.now()<=s;){let o=await R_(i);if(o)try{return await t()}finally{await o();}await x_(i,n),await E_(C_);}throw new ro}var v_,S_,C_,ro,hu=R(()=>{K();v_=15e3,S_=45e3,C_=100,ro=class extends Error{constructor(){super("token_refresh_lock_timeout"),this.name="TokenRefreshLockTimeoutError";}};});async function ne(t,e=process.env){let r=it(t,0,e);try{let n=await readFile(r.userConfigFile,"utf8"),i=JSON.parse(n);if(i&&typeof i=="object"&&i.schema_version===1)return i}catch(n){if(n.code!=="ENOENT")throw n}return {schema_version:1}}async function ci(t,e,r=process.env){let n=it(t,0,r);await _u(n.userConfigFile,{...e,schema_version:1});}async function ie(t,e,r=process.env){let i={...await ne(t,r),...e,schema_version:1};return await ci(t,i,r),i}async function gu(t,e=process.env){let r=A(e),n={user_id:t,updated_at:new Date().toISOString()};await _u(r.activeUserFile,n);}async function mu(t=process.env){await rm$1(A(t).activeUserFile,{force:true});}async function _u(t,e){let r=dirname(t);await mkdir(r,{recursive:true,mode:D}),await chmod(r,D).catch(()=>{});let n=`${t}.tmp`;await writeFile(n,JSON.stringify(e,null,2),{encoding:"utf8",mode:O}),await chmod(n,O).catch(()=>{}),await rename(n,t);}var Ge=R(()=>{K();});function wu(t){return t.startsWith(j_)&&t.endsWith(D_)}async function Ce(t=process.env){let e=await yu(t);return !e||!ku(e.session)?e:L_(e,t)}async function yu(t=process.env){let r=await st(t).findAll();for(let n of r)if(wu(n.account))try{let i=JSON.parse(n.value);if(!i.access_token||!i.refresh_token||!i.user?.id)continue;return {account:n.account,session:i}}catch{}return null}function ku(t){return t.expires_at<=Math.floor(Date.now()/1e3)+M_}async function L_(t,e){return pu(async()=>{let r=await yu(e);if(r&&!ku(r.session))return r;let n=pe(e),i=er(n.supabaseUrl,n.supabaseAnonKey,{auth:{persistSession:!1}}),{data:s,error:o}=await i.auth.refreshSession({refresh_token:t.session.refresh_token});if(o)throw new ui("refresh_failed",o.message);if(!s.session?.access_token||!s.session.refresh_token||!s.session.user?.id)throw new ui("refresh_failed","Supabase did not return a complete session.");let a={access_token:s.session.access_token,refresh_token:s.session.refresh_token,expires_at:s.session.expires_at??Math.floor(Date.now()/1e3)+(s.session.expires_in??3600),user:{id:s.session.user.id,email:s.session.user.email??void 0}};return await st(e).set(t.account,JSON.stringify(a)),{account:t.account,session:a}},{env:e})}async function no(t=process.env){let e=st(t),r=await e.findAll(),n=new Set,i=0;for(let o of r)if(wu(o.account)){try{let a=JSON.parse(o.value);a.user?.id&&n.add(a.user.id);}catch{}await e.delete(o.account)&&(i+=1);}let s=0;for(let o of n)await rm$1(it(o,0,t).userCacheDir,{recursive:true,force:true}),s+=1;return await mu(t),{removed_sessions:i,purged_user_caches:s}}var j_,D_,M_,ui,Gr=R(()=>{hu();Ge();_s();K();ai();Vr();j_="sb-",D_="-auth-token",M_=60,ui=class extends Error{constructor(r,n=r){super(n);this.code=r;this.name="CliSessionError";}code};});async function C(t=process.env){let e=await Ce(t);if(!e)throw new tr("not_authenticated","Pathrule CLI is not signed in.");let r=pe(t);return {session:e.session,supabase:er(r.supabaseUrl,r.supabaseAnonKey,{auth:{persistSession:false},global:{headers:{Authorization:`Bearer ${e.session.access_token}`}}})}}var tr,F=R(()=>{ai();li();Gr();tr=class extends Error{constructor(r,n=r){super(n);this.code=r;this.name="CliAuthError";}code};});var ju={};af(ju,{cliOrgWebUrl:()=>ee,currentCliOrg:()=>j,listCliOrgs:()=>we,useCliOrg:()=>hi});async function we(t){let{session:e,supabase:r}=await C(t),{data:n,error:i}=await r.from("organization_members").select("role, organization:organizations ( id, name, slug, plan, subscription_status, trial_status, trial_ends_at, seat_count, paid_extra_seats, trial_seat_cap, beta_referral_credit_cents, beta_referral_activated_count, beta_referral_founder )").eq("user_id",e.user.id);if(i)throw i;let s=await ne(e.user.id,t),o=[],a=new Set;for(let l of n??[]){let c=l.organization,u=Array.isArray(c)?c[0]:c;if(!u||a.has(u.id))continue;a.add(u.id);let d=u.subscription_status?String(u.subscription_status):null,p=u.trial_status?String(u.trial_status):null,h=u.trial_ends_at?String(u.trial_ends_at):null,f=tw(d,p,h);o.push({id:u.id,name:u.name,slug:u.slug,plan:u.plan,subscription_status:d,trial_status:p,trial_ends_at:h,seat_count:Ye(u.seat_count),paid_extra_seats:Ye(u.paid_extra_seats),trial_seat_cap:Ye(u.trial_seat_cap),beta_referral_credit_cents:Ye(u.beta_referral_credit_cents)??0,beta_referral_activated_count:Ye(u.beta_referral_activated_count)??0,beta_referral_founder:u.beta_referral_founder===true,role:l.role,current:s.current_org_id===u.id,billing:{status:d,freeze_kind:f.kind,freeze_reason:f.reason,seats:{active:Ye(u.seat_count),trial_cap:Ye(u.trial_seat_cap),paid_extra:Ye(u.paid_extra_seats)}}});}if(!s.current_org_id&&o.length===1){let l=o[0];l&&(o[0]={...l,current:true});}return o}async function j(t){let e=await we(t);return e.find(r=>r.current)??e[0]??null}async function hi(t,e){let{session:r}=await C(e),i=(await we(e)).find(s=>s.id===t||s.slug===t);if(!i)throw new Error("org_not_found");return await ie(r.user.id,{current_org_id:i.id},e),await gu(r.user.id,e),{...i,current:true}}function ee(t,e,r="home"){let i=`${(e.PATHRULE_WEB_URL??"https://app.pathrule.io").replace(/\/$/,"")}/org/${encodeURIComponent(t.slug)}`;return r==="home"?i:r==="billing"?`${i}/billing`:`${i}/settings${r==="members"?"/members":""}`}function Ye(t){return typeof t=="number"&&Number.isFinite(t)?t:null}function tw(t,e,r){return t==="unpaid"||t==="past_due"?{kind:"subscription",reason:"unpaid"}:t==="canceled"?e==="expired"||r&&new Date(r).getTime()<Date.now()?{kind:"subscription",reason:"trial_expired"}:{kind:"subscription",reason:"canceled"}:{kind:"none",reason:null}}var Ee=R(()=>{Ge();F();});cf(La());function Ua(t,e,r){return `${e}/.claude.json`}var wr="pathrule";function Zi(t){if(t==null)return {};if(typeof t!="object"||Array.isArray(t))throw new Error("Claude config root must be a JSON object");let e=t;if(e.mcpServers!==void 0&&(typeof e.mcpServers!="object"||e.mcpServers===null||Array.isArray(e.mcpServers)))throw new Error("Claude config `mcpServers` must be an object");return e}function Wa(t,e){let r=Zi(t),n={...r.mcpServers??{}},i=!(wr in n);return n[wr]=e,{config:{...r,mcpServers:n},wasNew:i}}function Ba(t){let e=Zi(t);if(!e.mcpServers||!(wr in e.mcpServers))return {config:e,wasPresent:false};let{[wr]:r,...n}=e.mcpServers;return {config:{...e,mcpServers:n},wasPresent:true}}function Fa(t){try{return Zi(t).mcpServers?.[wr]??null}catch{return null}}function B(t){return t.code==="PGRST116"?{code:"not_found",message:t.message}:t.code==="42501"?{code:"permission_denied",message:t.message}:{code:"upstream_error",message:t.message}}async function Dt(t,e){let{data:r,error:n}=await t.rpc("pathrule_check_content_dedup",{p_workspace_id:e.workspaceId,p_kind:e.kind,p_node_id:e.kind==="memory"?e.nodeId??null:null,p_candidate:e.candidate,p_threshold:e.threshold??.65,p_max_similar:e.maxSimilar??5,p_exclude_id:e.excludeId??null});if(n)return {ok:false,error:n.message};let i=r??{duplicate:null,similar:[]};return {ok:true,data:{duplicate:i.duplicate,similar:(i.similar??[]).map(s=>({id:s.id,title:s.title,similarity:typeof s.similarity=="string"?Number(s.similarity):s.similarity}))}}}function Ha(t){return t.code!=="23505"?false:!!t.message?.includes("skills_workspace_slug_unique")}async function Qi(t,e,r){let{data:n,error:i}=await t.from("nodes").select("id, workspace_id, parent_id, name, type, relative_path").eq("workspace_id",e).eq("relative_path","/").is("parent_id",null).maybeSingle();if(i)return {error:i.message};if(n)return n;let{data:s,error:o}=await t.from("nodes").insert({workspace_id:e,parent_id:null,name:r,type:"folder",relative_path:"/",order_index:0,status:"active"}).select("id, workspace_id, parent_id, name, type, relative_path").single();if(o||!s){if(o?.code==="23505"){let{data:a}=await t.from("nodes").select("id, workspace_id, parent_id, name, type, relative_path").eq("workspace_id",e).eq("relative_path","/").is("parent_id",null).maybeSingle();if(a)return a}return {error:o?.message??"Root node insert failed"}}return s}function qa(t){let e=t.trim();if(e===""||e==="/")return "/";let n=(e.startsWith("/")?e:"/"+e).replace(/\/+/g,"/");return n==="/"?"/":n.replace(/\/$/,"")}function df(t,e){return (t==="/"?"":t)+"/"+e.trim()}function pf(t){let e=t.split("/").filter(n=>n.length>0),r=e[e.length-1]??"";return /\.[A-Za-z0-9]{1,8}$/.test(r)?"file":"folder"}async function Mt(t,e,r){let{data:n,error:i}=await t.from("nodes").select("id, workspace_id, parent_id, name, type, relative_path").eq("workspace_id",e).eq("relative_path",r).maybeSingle();return i?{error:i.message}:n??null}async function hf(t,e,r,n){let i=qa(r);if(i==="/"){let d=await Mt(t,e,"/");return d&&!("error"in d)?d:{error:"Workspace root node missing \u2014 call ensureWorkspaceRootNode first."}}let s=await Mt(t,e,i);if(s&&!("error"in s)||s&&"error"in s)return s;let o=await Mt(t,e,"/");if(!o)return {error:"Workspace root node missing \u2014 call ensureWorkspaceRootNode first."};if("error"in o)return o;let a=i.split("/").filter(d=>d.length>0),l=pf(i),c=o,u="";for(let d=0;d<a.length;d+=1){let p=a[d];u+="/"+p;let f=d===a.length-1?l:"folder",m=await Mt(t,e,u);if(m&&"error"in m)return m;if(m){c=m;continue}let{count:_}=await t.from("nodes").select("*",{count:"exact",head:true}).eq("workspace_id",e).eq("parent_id",c.id),{data:b,error:w}=await t.from("nodes").insert({workspace_id:e,parent_id:c.id,name:p,type:f,relative_path:df(c.relative_path,p),order_index:_??0,status:"active"}).select("id, workspace_id, parent_id, name, type, relative_path").single();if(w||!b){if(w?.code==="23505"){let y=await Mt(t,e,u);if(y&&!("error"in y)){c=y;continue}}return {error:w?.message??`Insert failed at ${u}`}}c=b;}return c}async function Lt(t,e,r,n){let i=qa(r),s=await Mt(t,e,"/");if(s&&"error"in s)return s;if(!s){let{data:o,error:a}=await t.from("workspaces").select("name").eq("id",e).maybeSingle();if(a)return {error:a.message};let l=o?.name??"Workspace",c=await Qi(t,e,l);if("error"in c)return c}return hf(t,e,i)}function za(t){return {id:t.id,workspaceId:t.workspace_id,nodeId:t.node_id,title:t.title,content:t.content,source:t.source,semanticTags:t.semantic_tags??[],versionId:t.version_id,versionNumber:t.version_number,createdBy:t.created_by,lastEditedBy:t.last_edited_by,lastEditedAt:t.last_edited_at,createdAt:t.created_at,updatedAt:t.updated_at}}function ff(t){return t.length===0?null:{code:"similar_titles",message:`Found ${t.length} memory/rule(s) with a similar title.`,detail:{similar:t}}}async function Ja(t,e){if(!t.workspaceId)return {ok:false,error:{code:"invalid_args",message:"ctx.workspaceId is required for path-based writes"}};let r=await Lt(t.supabase,t.workspaceId,e.node_path);if("error"in r)return {ok:false,error:{code:"upstream_error",message:r.error}};let n=e.title.trim(),i=await Dt(t.supabase,{workspaceId:r.workspace_id,kind:"memory",nodeId:r.id,candidate:n});if(i.ok&&i.data.duplicate&&!e.allow_duplicate)return {ok:false,error:{code:"duplicate",message:`A memory titled "${i.data.duplicate.title}" already exists at ${e.node_path}. Use update_memory, pick a different title, or pass allow_duplicate: true to insert anyway.`,detail:{existing_id:i.data.duplicate.id,existing_title:i.data.duplicate.title,similar:i.ok?i.data.similar:[]}}};let{data:s,error:o}=await t.supabase.from("memories").insert({workspace_id:r.workspace_id,node_id:r.id,title:n,content:e.content,source:e.source??"claude",created_by:t.userId,last_edited_by:t.userId}).select("*").single();if(o||!s)return {ok:false,error:B(o??{message:"insert failed"})};let a=i.ok?ff(i.data.similar):null;return a?{ok:true,data:za(s),warnings:[a]}:{ok:true,data:za(s)}}function gf(t){return t.length===0?null:{code:"similar_titles",message:`Found ${t.length} rule(s) with a similar name.`,detail:{similar:t}}}function mf(t){return {id:t.id,workspaceId:t.workspace_id,name:t.name,content:t.content,scopeType:t.scope_type,priority:t.priority,semanticTags:t.semantic_tags??[],versionId:t.version_id,versionNumber:t.version_number,createdBy:t.created_by,lastEditedBy:t.last_edited_by,lastEditedAt:t.last_edited_at,createdAt:t.created_at,updatedAt:t.updated_at}}async function Ka(t,e){if(!t.workspaceId)return {ok:false,error:{code:"invalid_args",message:"ctx.workspaceId is required for path-based writes"}};let r=await Lt(t.supabase,t.workspaceId,e.node_path);if("error"in r)return {ok:false,error:{code:"upstream_error",message:r.error}};let n=e.name.trim(),i=await Dt(t.supabase,{workspaceId:r.workspace_id,kind:"rule",candidate:n});if(i.ok&&i.data.duplicate&&!e.allow_duplicate)return {ok:false,error:{code:"duplicate",message:`A rule named "${i.data.duplicate.title}" already exists in this workspace. Use update_rule, pick a different name, or pass allow_duplicate: true.`,detail:{existing_id:i.data.duplicate.id,existing_name:i.data.duplicate.title,similar:i.ok?i.data.similar:[]}}};let{data:s,error:o}=await t.supabase.from("rules").insert({workspace_id:r.workspace_id,name:n,content:e.content,scope_type:e.scope_type,priority:e.priority,created_by:t.userId,last_edited_by:t.userId}).select("*").single();if(o||!s)return {ok:false,error:B(o??{message:"insert failed"})};let a=mf(s),{error:l}=await t.supabase.from("node_rules").insert({node_id:r.id,rule_id:a.id});if(l)return await t.supabase.from("rules").delete().eq("id",a.id),{ok:false,error:{code:"upstream_error",message:`attach failed: ${l.message}`}};let c=i.ok?gf(i.data.similar):null;return c?{ok:true,data:a,warnings:[c]}:{ok:true,data:a}}function _f(t){return {id:t.id,workspaceId:t.workspace_id,name:t.name,description:t.description,content:t.content,source:t.source,githubUrl:t.github_url,version:t.version,tags:t.tags,semanticTags:t.semantic_tags??[],versionId:t.version_id,versionNumber:t.version_number,createdBy:t.created_by,lastEditedBy:t.last_edited_by,lastEditedAt:t.last_edited_at,createdAt:t.created_at,updatedAt:t.updated_at,contentFetchedAt:t.content_fetched_at}}async function Va(t,e){if(!t.workspaceId)return {ok:false,error:{code:"invalid_args",message:"ctx.workspaceId is required for path-based writes"}};let r=await Lt(t.supabase,t.workspaceId,e.node_path);if("error"in r)return {ok:false,error:{code:"upstream_error",message:r.error}};let n=e.name.trim(),i=await Dt(t.supabase,{workspaceId:r.workspace_id,kind:"skill",candidate:n,maxSimilar:0});if(i.ok&&i.data.duplicate)return {ok:false,error:{code:"duplicate",message:`A skill with this name already exists in this workspace: "${i.data.duplicate.title}". Use update_skill or pick a different name.`,detail:{existing_id:i.data.duplicate.id,existing_name:i.data.duplicate.title}}};let s=e.source??"manual",{data:o,error:a}=await t.supabase.from("skills").insert({workspace_id:r.workspace_id,name:n,description:e.description,content:e.content,source:s,github_url:e.github_url??null,tags:e.tags??[],created_by:t.userId,last_edited_by:t.userId,content_fetched_at:s==="github_ref"?new Date().toISOString():null}).select("*").single();if(a||!o)return Ha(a??{})?{ok:false,error:{code:"duplicate",message:"A skill with this name already exists in this workspace. Use update_skill or pick a different name."}}:{ok:false,error:B(a??{message:"insert failed"})};let l=_f(o),{error:c}=await t.supabase.from("node_skills").insert({node_id:r.id,skill_id:l.id,is_active:true});return c?(await t.supabase.from("skills").delete().eq("id",l.id),{ok:false,error:{code:"upstream_error",message:`attach failed: ${c.message}`}}):{ok:true,data:l}}var wf=/^[A-Za-z0-9_-]+/,yf=/[\s([{'"`]/;function ts(t){return t.trim().toLowerCase()}function Ga(t){let e=bf(t),r=[];for(let n=0;n<e.length-2;n+=1){if(e[n]!==":"||e[n+1]!==":")continue;let i=n===0?"":e[n-1]??"";if(i&&!yf.test(i))continue;let s=e.slice(n+2).match(wf);if(!s?.[0])continue;let o=s[0];r.push({raw:o,name:ts(o),start:n,end:n+2+o.length}),n+=1+o.length;}return kf(r)}function kf(t){let e=new Set,r=[];for(let n of t)e.has(n.name)||(e.add(n.name),r.push(n));return r}function bf(t){let e="",r=0,n=false,i=false;for(;r<t.length;){if(t.startsWith("```",r)){n=!n,e+=" ",r+=3;continue}let s=t[r]??"";if(!n&&s==="`"){i=!i,e+=" ",r+=1;continue}e+=n||i?s===`
46
+ ${b}`}var Kc=R(()=>{});function Vc({error:t,options:e}){var r,n,i;let{publicKey:s}=e;if(!s)throw Error("options was missing required publicKey property");if(t.name==="AbortError"){if(e.signal instanceof AbortSignal)return new L({message:"Registration ceremony was sent an abort signal",code:"ERROR_CEREMONY_ABORTED",cause:t})}else if(t.name==="ConstraintError"){if(((r=s.authenticatorSelection)===null||r===void 0?void 0:r.requireResidentKey)===true)return new L({message:"Discoverable credentials were required but no available authenticator supported it",code:"ERROR_AUTHENTICATOR_MISSING_DISCOVERABLE_CREDENTIAL_SUPPORT",cause:t});if(e.mediation==="conditional"&&((n=s.authenticatorSelection)===null||n===void 0?void 0:n.userVerification)==="required")return new L({message:"User verification was required during automatic registration but it could not be performed",code:"ERROR_AUTO_REGISTER_USER_VERIFICATION_FAILURE",cause:t});if(((i=s.authenticatorSelection)===null||i===void 0?void 0:i.userVerification)==="required")return new L({message:"User verification was required but no available authenticator supported it",code:"ERROR_AUTHENTICATOR_MISSING_USER_VERIFICATION_SUPPORT",cause:t})}else {if(t.name==="InvalidStateError")return new L({message:"The authenticator was previously registered",code:"ERROR_AUTHENTICATOR_PREVIOUSLY_REGISTERED",cause:t});if(t.name==="NotAllowedError")return new L({message:t.message,code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:t});if(t.name==="NotSupportedError")return s.pubKeyCredParams.filter(a=>a.type==="public-key").length===0?new L({message:'No entry in pubKeyCredParams was of type "public-key"',code:"ERROR_MALFORMED_PUBKEYCREDPARAMS",cause:t}):new L({message:"No available authenticator supported any of the specified pubKeyCredParams algorithms",code:"ERROR_AUTHENTICATOR_NO_SUPPORTED_PUBKEYCREDPARAMS_ALG",cause:t});if(t.name==="SecurityError"){let o=window.location.hostname;if(Ks(o)){if(s.rp.id!==o)return new L({message:`The RP ID "${s.rp.id}" is invalid for this domain`,code:"ERROR_INVALID_RP_ID",cause:t})}else return new L({message:`${window.location.hostname} is an invalid domain`,code:"ERROR_INVALID_DOMAIN",cause:t})}else if(t.name==="TypeError"){if(s.user.id.byteLength<1||s.user.id.byteLength>64)return new L({message:"User ID was not between 1 and 64 characters",code:"ERROR_INVALID_USER_ID_LENGTH",cause:t})}else if(t.name==="UnknownError")return new L({message:"The authenticator was unable to process the specified options, or could not create a new credential",code:"ERROR_AUTHENTICATOR_GENERAL_ERROR",cause:t})}return new L({message:"a Non-Webauthn related error has occurred",code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:t})}function Gc({error:t,options:e}){let{publicKey:r}=e;if(!r)throw Error("options was missing required publicKey property");if(t.name==="AbortError"){if(e.signal instanceof AbortSignal)return new L({message:"Authentication ceremony was sent an abort signal",code:"ERROR_CEREMONY_ABORTED",cause:t})}else {if(t.name==="NotAllowedError")return new L({message:t.message,code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:t});if(t.name==="SecurityError"){let n=window.location.hostname;if(Ks(n)){if(r.rpId!==n)return new L({message:`The RP ID "${r.rpId}" is invalid for this domain`,code:"ERROR_INVALID_RP_ID",cause:t})}else return new L({message:`${window.location.hostname} is an invalid domain`,code:"ERROR_INVALID_DOMAIN",cause:t})}else if(t.name==="UnknownError")return new L({message:"The authenticator was unable to process the specified options, or could not create a new assertion signature",code:"ERROR_AUTHENTICATOR_GENERAL_ERROR",cause:t})}return new L({message:"a Non-Webauthn related error has occurred",code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:t})}var L,yt,Yc=R(()=>{Vs();L=class extends Error{constructor({message:e,code:r,cause:n,name:i}){var s;super(e,{cause:n}),this.__isWebAuthnError=true,this.name=(s=i??(n instanceof Error?n.name:void 0))!==null&&s!==void 0?s:"Unknown Error",this.code=r;}},yt=class extends L{constructor(e,r){super({code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:r,message:e}),this.name="WebAuthnUnknownError",this.originalError=r;}};});function Zc(t){if(!t)throw new Error("Credential creation options are required");if(typeof PublicKeyCredential<"u"&&"parseCreationOptionsFromJSON"in PublicKeyCredential&&typeof PublicKeyCredential.parseCreationOptionsFromJSON=="function")return PublicKeyCredential.parseCreationOptionsFromJSON(t);let{challenge:e,user:r,excludeCredentials:n}=t,i=ot(t,["challenge","user","excludeCredentials"]),s=Ke(e).buffer,o=Object.assign(Object.assign({},r),{id:Ke(r.id).buffer}),a=Object.assign(Object.assign({},i),{challenge:s,user:o});if(n&&n.length>0){a.excludeCredentials=new Array(n.length);for(let l=0;l<n.length;l++){let c=n[l];a.excludeCredentials[l]=Object.assign(Object.assign({},c),{id:Ke(c.id).buffer,type:c.type||"public-key",transports:c.transports});}}return a}function Qc(t){if(!t)throw new Error("Credential request options are required");if(typeof PublicKeyCredential<"u"&&"parseRequestOptionsFromJSON"in PublicKeyCredential&&typeof PublicKeyCredential.parseRequestOptionsFromJSON=="function")return PublicKeyCredential.parseRequestOptionsFromJSON(t);let{challenge:e,allowCredentials:r}=t,n=ot(t,["challenge","allowCredentials"]),i=Ke(e).buffer,s=Object.assign(Object.assign({},n),{challenge:i});if(r&&r.length>0){s.allowCredentials=new Array(r.length);for(let o=0;o<r.length;o++){let a=r[o];s.allowCredentials[o]=Object.assign(Object.assign({},a),{id:Ke(a.id).buffer,type:a.type||"public-key",transports:a.transports});}}return s}function eu(t){var e;if("toJSON"in t&&typeof t.toJSON=="function")return t.toJSON();let r=t;return {id:t.id,rawId:t.id,response:{attestationObject:De(new Uint8Array(t.response.attestationObject)),clientDataJSON:De(new Uint8Array(t.response.clientDataJSON))},type:"public-key",clientExtensionResults:t.getClientExtensionResults(),authenticatorAttachment:(e=r.authenticatorAttachment)!==null&&e!==void 0?e:void 0}}function tu(t){var e;if("toJSON"in t&&typeof t.toJSON=="function")return t.toJSON();let r=t,n=t.getClientExtensionResults(),i=t.response;return {id:t.id,rawId:t.id,response:{authenticatorData:De(new Uint8Array(i.authenticatorData)),clientDataJSON:De(new Uint8Array(i.clientDataJSON)),signature:De(new Uint8Array(i.signature)),userHandle:i.userHandle?De(new Uint8Array(i.userHandle)):void 0},type:"public-key",clientExtensionResults:n,authenticatorAttachment:(e=r.authenticatorAttachment)!==null&&e!==void 0?e:void 0}}function Ks(t){return t==="localhost"||/^([a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,}$/i.test(t)}function Xc(){var t,e;return !!(q()&&"PublicKeyCredential"in window&&window.PublicKeyCredential&&"credentials"in navigator&&typeof((t=navigator?.credentials)===null||t===void 0?void 0:t.create)=="function"&&typeof((e=navigator?.credentials)===null||e===void 0?void 0:e.get)=="function")}async function Bm(t){try{let e=await navigator.credentials.create(t);return e?e instanceof PublicKeyCredential?{data:e,error:null}:{data:null,error:new yt("Browser returned unexpected credential type",e)}:{data:null,error:new yt("Empty credential response",e)}}catch(e){return {data:null,error:Vc({error:e,options:t})}}}async function Fm(t){try{let e=await navigator.credentials.get(t);return e?e instanceof PublicKeyCredential?{data:e,error:null}:{data:null,error:new yt("Browser returned unexpected credential type",e)}:{data:null,error:new yt("Empty credential response",e)}}catch(e){return {data:null,error:Gc({error:e,options:t})}}}function ii(...t){let e=i=>i!==null&&typeof i=="object"&&!Array.isArray(i),r=i=>i instanceof ArrayBuffer||ArrayBuffer.isView(i),n={};for(let i of t)if(i)for(let s in i){let o=i[s];if(o!==void 0)if(Array.isArray(o))n[s]=o;else if(r(o))n[s]=o;else if(e(o)){let a=n[s];e(a)?n[s]=ii(a,o):n[s]=ii(o);}else n[s]=o;}return n}function zm(t,e){return ii(Hm,t,e||{})}function Jm(t,e){return ii(qm,t,e||{})}var Gs,Wm,Hm,qm,si,Vs=R(()=>{kr();Zn();pt();Zt();Yc();Gs=class{createNewAbortSignal(){if(this.controller){let r=new Error("Cancelling existing WebAuthn API call for new one");r.name="AbortError",this.controller.abort(r);}let e=new AbortController;return this.controller=e,e.signal}cancelCeremony(){if(this.controller){let e=new Error("Manually cancelling existing WebAuthn API call");e.name="AbortError",this.controller.abort(e),this.controller=void 0;}}},Wm=new Gs;Hm={hints:["security-key"],authenticatorSelection:{authenticatorAttachment:"cross-platform",requireResidentKey:false,userVerification:"preferred",residentKey:"discouraged"},attestation:"direct"},qm={userVerification:"preferred",hints:["security-key"],attestation:"direct"};si=class{constructor(e){this.client=e,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(e){return this.client.mfa.enroll(Object.assign(Object.assign({},e),{factorType:"webauthn"}))}async _challenge({factorId:e,webauthn:r,friendlyName:n,signal:i},s){var o;try{let{data:a,error:l}=await this.client.mfa.challenge({factorId:e,webauthn:r});if(!a)return {data:null,error:l};let c=i??Wm.createNewAbortSignal();if(a.webauthn.type==="create"){let{user:u}=a.webauthn.credential_options.publicKey;if(!u.name){let d=n;if(d)u.name=`${u.id}:${d}`;else {let h=(await this.client.getUser()).data.user,f=((o=h?.user_metadata)===null||o===void 0?void 0:o.name)||h?.email||h?.id||"User";u.name=`${u.id}:${f}`;}}u.displayName||(u.displayName=u.name);}switch(a.webauthn.type){case "create":{let u=zm(a.webauthn.credential_options.publicKey,s?.create),{data:d,error:p}=await Bm({publicKey:u,signal:c});return d?{data:{factorId:e,challengeId:a.id,webauthn:{type:a.webauthn.type,credential_response:d}},error:null}:{data:null,error:p}}case "request":{let u=Jm(a.webauthn.credential_options.publicKey,s?.request),{data:d,error:p}=await Fm(Object.assign(Object.assign({},a.webauthn.credential_options),{publicKey:u,signal:c}));return d?{data:{factorId:e,challengeId:a.id,webauthn:{type:a.webauthn.type,credential_response:d}},error:null}:{data:null,error:p}}}}catch(a){return v(a)?{data:null,error:a}:{data:null,error:new ue("Unexpected error in challenge",a)}}}async _verify({challengeId:e,factorId:r,webauthn:n}){return this.client.mfa.verify({factorId:r,challengeId:e,webauthn:n})}async _authenticate({factorId:e,webauthn:{rpId:r=typeof window<"u"?window.location.hostname:void 0,rpOrigins:n=typeof window<"u"?[window.location.origin]:void 0,signal:i}={}},s){if(!r)return {data:null,error:new Je("rpId is required for WebAuthn authentication")};try{if(!Xc())return {data:null,error:new ue("Browser does not support WebAuthn",null)};let{data:o,error:a}=await this.challenge({factorId:e,webauthn:{rpId:r,rpOrigins:n},signal:i},{request:s});if(!o)return {data:null,error:a};let{webauthn:l}=o;return this._verify({factorId:e,challengeId:o.challengeId,webauthn:{type:l.type,rpId:r,rpOrigins:n,credential_response:l.credential_response}})}catch(o){return v(o)?{data:null,error:o}:{data:null,error:new ue("Unexpected error in authenticate",o)}}}async _register({friendlyName:e,webauthn:{rpId:r=typeof window<"u"?window.location.hostname:void 0,rpOrigins:n=typeof window<"u"?[window.location.origin]:void 0,signal:i}={}},s){if(!r)return {data:null,error:new Je("rpId is required for WebAuthn registration")};try{if(!Xc())return {data:null,error:new ue("Browser does not support WebAuthn",null)};let{data:o,error:a}=await this._enroll({friendlyName:e});if(!o)return await this.client.mfa.listFactors().then(u=>{var d;return (d=u.data)===null||d===void 0?void 0:d.all.find(p=>p.factor_type==="webauthn"&&p.friendly_name===e&&p.status!=="unverified")}).then(u=>u?this.client.mfa.unenroll({factorId:u?.id}):void 0),{data:null,error:a};let{data:l,error:c}=await this._challenge({factorId:o.id,friendlyName:o.friendly_name,webauthn:{rpId:r,rpOrigins:n},signal:i},{create:s});return l?this._verify({factorId:o.id,challengeId:l.challengeId,webauthn:{rpId:r,rpOrigins:n,type:l.webauthn.type,credential_response:l.webauthn.credential_response}}):{data:null,error:c}}catch(o){return v(o)?{data:null,error:o}:{data:null,error:new ue("Unexpected error in register",o)}}}};});async function ru(t,e,r){return await r()}var Km,Qt,oi,Ys,Xs=R(()=>{ni();Kn();pt();Bs();Zt();Bc();zs();Hc();Ds();Zn();Kc();Vs();Fc();Km={url:_c,storageKey:wc,autoRefreshToken:true,persistSession:true,detectSessionInUrl:true,headers:yc,flowType:"implicit",debug:false,hasCustomAuthorizationHeader:false,throwOnError:false,lockAcquireTimeout:5e3,skipAutoInitialize:false};Qt={},oi=class t{get jwks(){var e,r;return (r=(e=Qt[this.storageKey])===null||e===void 0?void 0:e.jwks)!==null&&r!==void 0?r:{keys:[]}}set jwks(e){Qt[this.storageKey]=Object.assign(Object.assign({},Qt[this.storageKey]),{jwks:e});}get jwks_cached_at(){var e,r;return (r=(e=Qt[this.storageKey])===null||e===void 0?void 0:e.cachedAt)!==null&&r!==void 0?r:Number.MIN_SAFE_INTEGER}set jwks_cached_at(e){Qt[this.storageKey]=Object.assign(Object.assign({},Qt[this.storageKey]),{cachedAt:e});}constructor(e){var r,n,i;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=true,this.hasCustomAuthorizationHeader=false,this.suppressGetSessionWarning=false,this.lockAcquired=false,this.pendingInLock=[],this.broadcastChannel=null,this.logger=console.log;let s=Object.assign(Object.assign({},Km),e);if(this.storageKey=s.storageKey,this.instanceID=(r=t.nextInstanceID[this.storageKey])!==null&&r!==void 0?r:0,t.nextInstanceID[this.storageKey]=this.instanceID+1,this.logDebugMessages=!!s.debug,typeof s.debug=="function"&&(this.logger=s.debug),this.instanceID>0&&q()){let o=`${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.`;console.warn(o),this.logDebugMessages&&console.trace(o);}if(this.persistSession=s.persistSession,this.autoRefreshToken=s.autoRefreshToken,this.admin=new wt({url:s.url,headers:s.headers,fetch:s.fetch}),this.url=s.url,this.headers=s.headers,this.fetch=ei(s.fetch),this.lock=s.lock||ru,this.detectSessionInUrl=s.detectSessionInUrl,this.flowType=s.flowType,this.hasCustomAuthorizationHeader=s.hasCustomAuthorizationHeader,this.throwOnError=s.throwOnError,this.lockAcquireTimeout=s.lockAcquireTimeout,s.lock?this.lock=s.lock:this.persistSession&&q()&&(!((n=globalThis?.navigator)===null||n===void 0)&&n.locks)?this.lock=qs:this.lock=ru,this.jwks||(this.jwks={keys:[]},this.jwks_cached_at=Number.MIN_SAFE_INTEGER),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 si(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.persistSession?(s.storage?this.storage=s.storage:Qn()?this.storage=globalThis.localStorage:(this.memoryStorage={},this.storage=Hs(this.memoryStorage)),s.userStorage&&(this.userStorage=s.userStorage)):(this.memoryStorage={},this.storage=Hs(this.memoryStorage)),q()&&globalThis.BroadcastChannel&&this.persistSession&&this.storageKey){try{this.broadcastChannel=new globalThis.BroadcastChannel(this.storageKey);}catch(o){console.error("Failed to create a new BroadcastChannel, multi-tab state changes will not be available",o);}(i=this.broadcastChannel)===null||i===void 0||i.addEventListener("message",async o=>{this._debug("received broadcast notification from other tab or client",o);try{await this._notifyAllSubscribers(o.data.event,o.data.session,!1);}catch(a){this._debug("#broadcastChannel","error",a);}});}s.skipAutoInitialize||this.initialize().catch(o=>{this._debug("#initialize()","error",o);});}isThrowOnErrorEnabled(){return this.throwOnError}_returnResult(e){if(this.throwOnError&&e&&e.error)throw e.error;return e}_logPrefix(){return `GoTrueClient@${this.storageKey}:${this.instanceID} (${qn}) ${new Date().toISOString()}`}_debug(...e){return this.logDebugMessages&&this.logger(this._logPrefix(),...e),this}async initialize(){return this.initializePromise?await this.initializePromise:(this.initializePromise=(async()=>await this._acquireLock(this.lockAcquireTimeout,async()=>await this._initialize()))(),await this.initializePromise)}async _initialize(){var e;try{let r={},n="none";if(q()&&(r=Ac(window.location.href),this._isImplicitGrantCallback(r)?n="implicit":await this._isPKCECallback(r)&&(n="pkce")),q()&&this.detectSessionInUrl&&n!=="none"){let{data:i,error:s}=await this._getSessionFromURL(r,n);if(s){if(this._debug("#_initialize()","error detecting session from URL",s),Sc(s)){let l=(e=s.details)===null||e===void 0?void 0:e.code;if(l==="identity_already_exists"||l==="identity_not_found"||l==="single_identity_not_deletable")return {error:s}}return {error:s}}let{session:o,redirectType:a}=i;return this._debug("#_initialize()","detected session in URL",o,"redirect type",a),await this._saveSession(o),setTimeout(async()=>{a==="recovery"?await this._notifyAllSubscribers("PASSWORD_RECOVERY",o):await this._notifyAllSubscribers("SIGNED_IN",o);},0),{error:null}}return await this._recoverAndRefresh(),{error:null}}catch(r){return v(r)?this._returnResult({error:r}):this._returnResult({error:new ue("Unexpected error during initialization",r)})}finally{await this._handleVisibilityChange(),this._debug("#_initialize()","end");}}async signInAnonymously(e){var r,n,i;try{let s=await S(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{data:(n=(r=e?.options)===null||r===void 0?void 0:r.data)!==null&&n!==void 0?n:{},gotrue_meta_security:{captcha_token:(i=e?.options)===null||i===void 0?void 0:i.captchaToken}},xform:de}),{data:o,error:a}=s;if(a||!o)return this._returnResult({data:{user:null,session:null},error:a});let l=o.session,c=o.user;return o.session&&(await this._saveSession(o.session),await this._notifyAllSubscribers("SIGNED_IN",l)),this._returnResult({data:{user:c,session:l},error:null})}catch(s){if(v(s))return this._returnResult({data:{user:null,session:null},error:s});throw s}}async signUp(e){var r,n,i;try{let s;if("email"in e){let{email:u,password:d,options:p}=e,h=null,f=null;this.flowType==="pkce"&&([h,f]=await gt(this.storage,this.storageKey)),s=await S(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,redirectTo:p?.emailRedirectTo,body:{email:u,password:d,data:(r=p?.data)!==null&&r!==void 0?r:{},gotrue_meta_security:{captcha_token:p?.captchaToken},code_challenge:h,code_challenge_method:f},xform:de});}else if("phone"in e){let{phone:u,password:d,options:p}=e;s=await S(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{phone:u,password:d,data:(n=p?.data)!==null&&n!==void 0?n:{},channel:(i=p?.channel)!==null&&i!==void 0?i:"sms",gotrue_meta_security:{captcha_token:p?.captchaToken}},xform:de});}else throw new ct("You must provide either an email or phone number and a password");let{data:o,error:a}=s;if(a||!o)return await z(this.storage,`${this.storageKey}-code-verifier`),this._returnResult({data:{user:null,session:null},error:a});let l=o.session,c=o.user;return o.session&&(await this._saveSession(o.session),await this._notifyAllSubscribers("SIGNED_IN",l)),this._returnResult({data:{user:c,session:l},error:null})}catch(s){if(await z(this.storage,`${this.storageKey}-code-verifier`),v(s))return this._returnResult({data:{user:null,session:null},error:s});throw s}}async signInWithPassword(e){try{let r;if("email"in e){let{email:s,password:o,options:a}=e;r=await S(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{email:s,password:o,gotrue_meta_security:{captcha_token:a?.captchaToken}},xform:Us});}else if("phone"in e){let{phone:s,password:o,options:a}=e;r=await S(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{phone:s,password:o,gotrue_meta_security:{captcha_token:a?.captchaToken}},xform:Us});}else throw new ct("You must provide either an email or phone number and a password");let{data:n,error:i}=r;if(i)return this._returnResult({data:{user:null,session:null},error:i});if(!n||!n.session||!n.user){let s=new Ne;return this._returnResult({data:{user:null,session:null},error:s})}return n.session&&(await this._saveSession(n.session),await this._notifyAllSubscribers("SIGNED_IN",n.session)),this._returnResult({data:Object.assign({user:n.user,session:n.session},n.weak_password?{weakPassword:n.weak_password}:null),error:i})}catch(r){if(v(r))return this._returnResult({data:{user:null,session:null},error:r});throw r}}async signInWithOAuth(e){var r,n,i,s;return await this._handleProviderSignIn(e.provider,{redirectTo:(r=e.options)===null||r===void 0?void 0:r.redirectTo,scopes:(n=e.options)===null||n===void 0?void 0:n.scopes,queryParams:(i=e.options)===null||i===void 0?void 0:i.queryParams,skipBrowserRedirect:(s=e.options)===null||s===void 0?void 0:s.skipBrowserRedirect})}async exchangeCodeForSession(e){return await this.initializePromise,this._acquireLock(this.lockAcquireTimeout,async()=>this._exchangeCodeForSession(e))}async signInWithWeb3(e){let{chain:r}=e;switch(r){case "ethereum":return await this.signInWithEthereum(e);case "solana":return await this.signInWithSolana(e);default:throw new Error(`@supabase/auth-js: Unsupported chain "${r}"`)}}async signInWithEthereum(e){var r,n,i,s,o,a,l,c,u,d,p;let h,f;if("message"in e)h=e.message,f=e.signature;else {let{chain:m,wallet:_,statement:b,options:w}=e,y;if(q())if(typeof _=="object")y=_;else {let le=window;if("ethereum"in le&&typeof le.ethereum=="object"&&"request"in le.ethereum&&typeof le.ethereum.request=="function")y=le.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.")}else {if(typeof _!="object"||!w?.url)throw new Error("@supabase/auth-js: Both wallet and url must be specified in non-browser environments.");y=_;}let I=new URL((r=w?.url)!==null&&r!==void 0?r:window.location.href),Z=await y.request({method:"eth_requestAccounts"}).then(le=>le).catch(()=>{throw new Error("@supabase/auth-js: Wallet method eth_requestAccounts is missing or invalid")});if(!Z||Z.length===0)throw new Error("@supabase/auth-js: No accounts available. Please ensure the wallet is connected.");let T=Js(Z[0]),$=(n=w?.signInWithEthereum)===null||n===void 0?void 0:n.chainId;if(!$){let le=await y.request({method:"eth_chainId"});$=qc(le);}let Ie={domain:I.host,address:T,statement:b,uri:I.href,version:"1",chainId:$,nonce:(i=w?.signInWithEthereum)===null||i===void 0?void 0:i.nonce,issuedAt:(o=(s=w?.signInWithEthereum)===null||s===void 0?void 0:s.issuedAt)!==null&&o!==void 0?o:new Date,expirationTime:(a=w?.signInWithEthereum)===null||a===void 0?void 0:a.expirationTime,notBefore:(l=w?.signInWithEthereum)===null||l===void 0?void 0:l.notBefore,requestId:(c=w?.signInWithEthereum)===null||c===void 0?void 0:c.requestId,resources:(u=w?.signInWithEthereum)===null||u===void 0?void 0:u.resources};h=Jc(Ie),f=await y.request({method:"personal_sign",params:[zc(h),T]});}try{let{data:m,error:_}=await S(this.fetch,"POST",`${this.url}/token?grant_type=web3`,{headers:this.headers,body:Object.assign({chain:"ethereum",message:h,signature:f},!((d=e.options)===null||d===void 0)&&d.captchaToken?{gotrue_meta_security:{captcha_token:(p=e.options)===null||p===void 0?void 0:p.captchaToken}}:null),xform:de});if(_)throw _;if(!m||!m.session||!m.user){let b=new Ne;return this._returnResult({data:{user:null,session:null},error:b})}return m.session&&(await this._saveSession(m.session),await this._notifyAllSubscribers("SIGNED_IN",m.session)),this._returnResult({data:Object.assign({},m),error:_})}catch(m){if(v(m))return this._returnResult({data:{user:null,session:null},error:m});throw m}}async signInWithSolana(e){var r,n,i,s,o,a,l,c,u,d,p,h;let f,m;if("message"in e)f=e.message,m=e.signature;else {let{chain:_,wallet:b,statement:w,options:y}=e,I;if(q())if(typeof b=="object")I=b;else {let T=window;if("solana"in T&&typeof T.solana=="object"&&("signIn"in T.solana&&typeof T.solana.signIn=="function"||"signMessage"in T.solana&&typeof T.solana.signMessage=="function"))I=T.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.")}else {if(typeof b!="object"||!y?.url)throw new Error("@supabase/auth-js: Both wallet and url must be specified in non-browser environments.");I=b;}let Z=new URL((r=y?.url)!==null&&r!==void 0?r:window.location.href);if("signIn"in I&&I.signIn){let T=await I.signIn(Object.assign(Object.assign(Object.assign({issuedAt:new Date().toISOString()},y?.signInWithSolana),{version:"1",domain:Z.host,uri:Z.href}),w?{statement:w}:null)),$;if(Array.isArray(T)&&T[0]&&typeof T[0]=="object")$=T[0];else if(T&&typeof T=="object"&&"signedMessage"in T&&"signature"in T)$=T;else throw new Error("@supabase/auth-js: Wallet method signIn() returned unrecognized value");if("signedMessage"in $&&"signature"in $&&(typeof $.signedMessage=="string"||$.signedMessage instanceof Uint8Array)&&$.signature instanceof Uint8Array)f=typeof $.signedMessage=="string"?$.signedMessage:new TextDecoder().decode($.signedMessage),m=$.signature;else throw new Error("@supabase/auth-js: Wallet method signIn() API returned object without signedMessage and signature fields")}else {if(!("signMessage"in I)||typeof I.signMessage!="function"||!("publicKey"in I)||typeof I!="object"||!I.publicKey||!("toBase58"in I.publicKey)||typeof I.publicKey.toBase58!="function")throw new Error("@supabase/auth-js: Wallet does not have a compatible signMessage() and publicKey.toBase58() API");f=[`${Z.host} wants you to sign in with your Solana account:`,I.publicKey.toBase58(),...w?["",w,""]:[""],"Version: 1",`URI: ${Z.href}`,`Issued At: ${(i=(n=y?.signInWithSolana)===null||n===void 0?void 0:n.issuedAt)!==null&&i!==void 0?i:new Date().toISOString()}`,...!((s=y?.signInWithSolana)===null||s===void 0)&&s.notBefore?[`Not Before: ${y.signInWithSolana.notBefore}`]:[],...!((o=y?.signInWithSolana)===null||o===void 0)&&o.expirationTime?[`Expiration Time: ${y.signInWithSolana.expirationTime}`]:[],...!((a=y?.signInWithSolana)===null||a===void 0)&&a.chainId?[`Chain ID: ${y.signInWithSolana.chainId}`]:[],...!((l=y?.signInWithSolana)===null||l===void 0)&&l.nonce?[`Nonce: ${y.signInWithSolana.nonce}`]:[],...!((c=y?.signInWithSolana)===null||c===void 0)&&c.requestId?[`Request ID: ${y.signInWithSolana.requestId}`]:[],...!((d=(u=y?.signInWithSolana)===null||u===void 0?void 0:u.resources)===null||d===void 0)&&d.length?["Resources",...y.signInWithSolana.resources.map($=>`- ${$}`)]:[]].join(`
47
+ `);let T=await I.signMessage(new TextEncoder().encode(f),"utf8");if(!T||!(T instanceof Uint8Array))throw new Error("@supabase/auth-js: Wallet signMessage() API returned an recognized value");m=T;}}try{let{data:_,error:b}=await S(this.fetch,"POST",`${this.url}/token?grant_type=web3`,{headers:this.headers,body:Object.assign({chain:"solana",message:f,signature:De(m)},!((p=e.options)===null||p===void 0)&&p.captchaToken?{gotrue_meta_security:{captcha_token:(h=e.options)===null||h===void 0?void 0:h.captchaToken}}:null),xform:de});if(b)throw b;if(!_||!_.session||!_.user){let w=new Ne;return this._returnResult({data:{user:null,session:null},error:w})}return _.session&&(await this._saveSession(_.session),await this._notifyAllSubscribers("SIGNED_IN",_.session)),this._returnResult({data:Object.assign({},_),error:b})}catch(_){if(v(_))return this._returnResult({data:{user:null,session:null},error:_});throw _}}async _exchangeCodeForSession(e){let r=await Ve(this.storage,`${this.storageKey}-code-verifier`),[n,i]=(r??"").split("/");try{if(!n&&this.flowType==="pkce")throw new Gn;let{data:s,error:o}=await S(this.fetch,"POST",`${this.url}/token?grant_type=pkce`,{headers:this.headers,body:{auth_code:e,code_verifier:n},xform:de});if(await z(this.storage,`${this.storageKey}-code-verifier`),o)throw o;if(!s||!s.session||!s.user){let a=new Ne;return this._returnResult({data:{user:null,session:null,redirectType:null},error:a})}return s.session&&(await this._saveSession(s.session),await this._notifyAllSubscribers("SIGNED_IN",s.session)),this._returnResult({data:Object.assign(Object.assign({},s),{redirectType:i??null}),error:o})}catch(s){if(await z(this.storage,`${this.storageKey}-code-verifier`),v(s))return this._returnResult({data:{user:null,session:null,redirectType:null},error:s});throw s}}async signInWithIdToken(e){try{let{options:r,provider:n,token:i,access_token:s,nonce:o}=e,a=await S(this.fetch,"POST",`${this.url}/token?grant_type=id_token`,{headers:this.headers,body:{provider:n,id_token:i,access_token:s,nonce:o,gotrue_meta_security:{captcha_token:r?.captchaToken}},xform:de}),{data:l,error:c}=a;if(c)return this._returnResult({data:{user:null,session:null},error:c});if(!l||!l.session||!l.user){let u=new Ne;return this._returnResult({data:{user:null,session:null},error:u})}return l.session&&(await this._saveSession(l.session),await this._notifyAllSubscribers("SIGNED_IN",l.session)),this._returnResult({data:l,error:c})}catch(r){if(v(r))return this._returnResult({data:{user:null,session:null},error:r});throw r}}async signInWithOtp(e){var r,n,i,s,o;try{if("email"in e){let{email:a,options:l}=e,c=null,u=null;this.flowType==="pkce"&&([c,u]=await gt(this.storage,this.storageKey));let{error:d}=await S(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{email:a,data:(r=l?.data)!==null&&r!==void 0?r:{},create_user:(n=l?.shouldCreateUser)!==null&&n!==void 0?n:!0,gotrue_meta_security:{captcha_token:l?.captchaToken},code_challenge:c,code_challenge_method:u},redirectTo:l?.emailRedirectTo});return this._returnResult({data:{user:null,session:null},error:d})}if("phone"in e){let{phone:a,options:l}=e,{data:c,error:u}=await S(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{phone:a,data:(i=l?.data)!==null&&i!==void 0?i:{},create_user:(s=l?.shouldCreateUser)!==null&&s!==void 0?s:!0,gotrue_meta_security:{captcha_token:l?.captchaToken},channel:(o=l?.channel)!==null&&o!==void 0?o:"sms"}});return this._returnResult({data:{user:null,session:null,messageId:c?.message_id},error:u})}throw new ct("You must provide either an email or phone number.")}catch(a){if(await z(this.storage,`${this.storageKey}-code-verifier`),v(a))return this._returnResult({data:{user:null,session:null},error:a});throw a}}async verifyOtp(e){var r,n;try{let i,s;"options"in e&&(i=(r=e.options)===null||r===void 0?void 0:r.redirectTo,s=(n=e.options)===null||n===void 0?void 0:n.captchaToken);let{data:o,error:a}=await S(this.fetch,"POST",`${this.url}/verify`,{headers:this.headers,body:Object.assign(Object.assign({},e),{gotrue_meta_security:{captcha_token:s}}),redirectTo:i,xform:de});if(a)throw a;if(!o)throw new Error("An error occurred on token verification.");let l=o.session,c=o.user;return l?.access_token&&(await this._saveSession(l),await this._notifyAllSubscribers(e.type=="recovery"?"PASSWORD_RECOVERY":"SIGNED_IN",l)),this._returnResult({data:{user:c,session:l},error:null})}catch(i){if(v(i))return this._returnResult({data:{user:null,session:null},error:i});throw i}}async signInWithSSO(e){var r,n,i,s,o;try{let a=null,l=null;this.flowType==="pkce"&&([a,l]=await gt(this.storage,this.storageKey));let c=await S(this.fetch,"POST",`${this.url}/sso`,{body:Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},"providerId"in e?{provider_id:e.providerId}:null),"domain"in e?{domain:e.domain}:null),{redirect_to:(n=(r=e.options)===null||r===void 0?void 0:r.redirectTo)!==null&&n!==void 0?n:void 0}),!((i=e?.options)===null||i===void 0)&&i.captchaToken?{gotrue_meta_security:{captcha_token:e.options.captchaToken}}:null),{skip_http_redirect:!0,code_challenge:a,code_challenge_method:l}),headers:this.headers,xform:Uc});return !((s=c.data)===null||s===void 0)&&s.url&&q()&&!(!((o=e.options)===null||o===void 0)&&o.skipBrowserRedirect)&&window.location.assign(c.data.url),this._returnResult(c)}catch(a){if(await z(this.storage,`${this.storageKey}-code-verifier`),v(a))return this._returnResult({data:null,error:a});throw a}}async reauthenticate(){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>await this._reauthenticate())}async _reauthenticate(){try{return await this._useSession(async e=>{let{data:{session:r},error:n}=e;if(n)throw n;if(!r)throw new J;let{error:i}=await S(this.fetch,"GET",`${this.url}/reauthenticate`,{headers:this.headers,jwt:r.access_token});return this._returnResult({data:{user:null,session:null},error:i})})}catch(e){if(v(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async resend(e){try{let r=`${this.url}/resend`;if("email"in e){let{email:n,type:i,options:s}=e,{error:o}=await S(this.fetch,"POST",r,{headers:this.headers,body:{email:n,type:i,gotrue_meta_security:{captcha_token:s?.captchaToken}},redirectTo:s?.emailRedirectTo});return this._returnResult({data:{user:null,session:null},error:o})}else if("phone"in e){let{phone:n,type:i,options:s}=e,{data:o,error:a}=await S(this.fetch,"POST",r,{headers:this.headers,body:{phone:n,type:i,gotrue_meta_security:{captcha_token:s?.captchaToken}}});return this._returnResult({data:{user:null,session:null,messageId:o?.message_id},error:a})}throw new ct("You must provide either an email or phone number and a type")}catch(r){if(v(r))return this._returnResult({data:{user:null,session:null},error:r});throw r}}async getSession(){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>this._useSession(async r=>r))}async _acquireLock(e,r){this._debug("#_acquireLock","begin",e);try{if(this.lockAcquired){let n=this.pendingInLock.length?this.pendingInLock[this.pendingInLock.length-1]:Promise.resolve(),i=(async()=>(await n,await r()))();return this.pendingInLock.push((async()=>{try{await i;}catch{}})()),i}return await this.lock(`lock:${this.storageKey}`,e,async()=>{this._debug("#_acquireLock","lock acquired for storage key",this.storageKey);try{this.lockAcquired=!0;let n=r();for(this.pendingInLock.push((async()=>{try{await n;}catch{}})()),await n;this.pendingInLock.length;){let i=[...this.pendingInLock];await Promise.all(i),this.pendingInLock.splice(0,i.length);}return await n}finally{this._debug("#_acquireLock","lock released for storage key",this.storageKey),this.lockAcquired=!1;}})}finally{this._debug("#_acquireLock","end");}}async _useSession(e){this._debug("#_useSession","begin");try{let r=await this.__loadSession();return await e(r)}finally{this._debug("#_useSession","end");}}async __loadSession(){this._debug("#__loadSession()","begin"),this.lockAcquired||this._debug("#__loadSession()","used outside of an acquired lock!",new Error().stack);try{let e=null,r=await Ve(this.storage,this.storageKey);if(this._debug("#getSession()","session from storage",r),r!==null&&(this._isValidSession(r)?e=r:(this._debug("#getSession()","session from storage is not valid"),await this._removeSession())),!e)return {data:{session:null},error:null};let n=e.expires_at?e.expires_at*1e3-Date.now()<Jn:!1;if(this._debug("#__loadSession()",`session has${n?"":" not"} expired`,"expires_at",e.expires_at),!n){if(this.userStorage){let o=await Ve(this.userStorage,this.storageKey+"-user");o?.user?e.user=o.user:e.user=ti();}if(this.storage.isServer&&e.user&&!e.user.__isUserNotAvailableProxy){let o={value:this.suppressGetSessionWarning};e.user=Mc(e.user,o),o.value&&(this.suppressGetSessionWarning=!0);}return {data:{session:e},error:null}}let{data:i,error:s}=await this._callRefreshToken(e.refresh_token);return s?this._returnResult({data:{session:null},error:s}):this._returnResult({data:{session:i},error:null})}finally{this._debug("#__loadSession()","end");}}async getUser(e){if(e)return await this._getUser(e);await this.initializePromise;let r=await this._acquireLock(this.lockAcquireTimeout,async()=>await this._getUser());return r.data.user&&(this.suppressGetSessionWarning=true),r}async _getUser(e){try{return e?await S(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:e,xform:Se}):await this._useSession(async r=>{var n,i,s;let{data:o,error:a}=r;if(a)throw a;return !(!((n=o.session)===null||n===void 0)&&n.access_token)&&!this.hasCustomAuthorizationHeader?{data:{user:null},error:new J}:await S(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:(s=(i=o.session)===null||i===void 0?void 0:i.access_token)!==null&&s!==void 0?s:void 0,xform:Se})})}catch(r){if(v(r))return Br(r)&&(await this._removeSession(),await z(this.storage,`${this.storageKey}-code-verifier`)),this._returnResult({data:{user:null},error:r});throw r}}async updateUser(e,r={}){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>await this._updateUser(e,r))}async _updateUser(e,r={}){try{return await this._useSession(async n=>{let{data:i,error:s}=n;if(s)throw s;if(!i.session)throw new J;let o=i.session,a=null,l=null;this.flowType==="pkce"&&e.email!=null&&([a,l]=await gt(this.storage,this.storageKey));let{data:c,error:u}=await S(this.fetch,"PUT",`${this.url}/user`,{headers:this.headers,redirectTo:r?.emailRedirectTo,body:Object.assign(Object.assign({},e),{code_challenge:a,code_challenge_method:l}),jwt:o.access_token,xform:Se});if(u)throw u;return o.user=c.user,await this._saveSession(o),await this._notifyAllSubscribers("USER_UPDATED",o),this._returnResult({data:{user:o.user},error:null})})}catch(n){if(await z(this.storage,`${this.storageKey}-code-verifier`),v(n))return this._returnResult({data:{user:null},error:n});throw n}}async setSession(e){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>await this._setSession(e))}async _setSession(e){try{if(!e.access_token||!e.refresh_token)throw new J;let r=Date.now()/1e3,n=r,i=!0,s=null,{payload:o}=Hr(e.access_token);if(o.exp&&(n=o.exp,i=n<=r),i){let{data:a,error:l}=await this._callRefreshToken(e.refresh_token);if(l)return this._returnResult({data:{user:null,session:null},error:l});if(!a)return {data:{user:null,session:null},error:null};s=a;}else {let{data:a,error:l}=await this._getUser(e.access_token);if(l)return this._returnResult({data:{user:null,session:null},error:l});s={access_token:e.access_token,refresh_token:e.refresh_token,user:a.user,token_type:"bearer",expires_in:n-r,expires_at:n},await this._saveSession(s),await this._notifyAllSubscribers("SIGNED_IN",s);}return this._returnResult({data:{user:s.user,session:s},error:null})}catch(r){if(v(r))return this._returnResult({data:{session:null,user:null},error:r});throw r}}async refreshSession(e){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>await this._refreshSession(e))}async _refreshSession(e){try{return await this._useSession(async r=>{var n;if(!e){let{data:o,error:a}=r;if(a)throw a;e=(n=o.session)!==null&&n!==void 0?n:void 0;}if(!e?.refresh_token)throw new J;let{data:i,error:s}=await this._callRefreshToken(e.refresh_token);return s?this._returnResult({data:{user:null,session:null},error:s}):i?this._returnResult({data:{user:i.user,session:i},error:null}):this._returnResult({data:{user:null,session:null},error:null})})}catch(r){if(v(r))return this._returnResult({data:{user:null,session:null},error:r});throw r}}async _getSessionFromURL(e,r){try{if(!q())throw new ut("No browser detected.");if(e.error||e.error_description||e.error_code)throw new ut(e.error_description||"Error in URL with unspecified error_description",{error:e.error||"unspecified_error",code:e.error_code||"unspecified_code"});switch(r){case "implicit":if(this.flowType==="pkce")throw new Ur("Not a valid PKCE flow url.");break;case "pkce":if(this.flowType==="implicit")throw new ut("Not a valid implicit grant flow url.");break;default:}if(r==="pkce"){if(this._debug("#_initialize()","begin","is PKCE flow",!0),!e.code)throw new Ur("No code detected.");let{data:w,error:y}=await this._exchangeCodeForSession(e.code);if(y)throw y;let I=new URL(window.location.href);return I.searchParams.delete("code"),window.history.replaceState(window.history.state,"",I.toString()),{data:{session:w.session,redirectType:null},error:null}}let{provider_token:n,provider_refresh_token:i,access_token:s,refresh_token:o,expires_in:a,expires_at:l,token_type:c}=e;if(!s||!a||!o||!c)throw new ut("No session defined in URL");let u=Math.round(Date.now()/1e3),d=parseInt(a),p=u+d;l&&(p=parseInt(l));let h=p-u;h*1e3<=lt&&console.warn(`@supabase/gotrue-js: Session as retrieved from URL expires in ${h}s, should have been closer to ${d}s`);let f=p-d;u-f>=120?console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued over 120s ago, URL could be stale",f,p,u):u-f<0&&console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued in the future? Check the device clock for skew",f,p,u);let{data:m,error:_}=await this._getUser(s);if(_)throw _;let b={provider_token:n,provider_refresh_token:i,access_token:s,expires_in:d,expires_at:p,refresh_token:o,token_type:c,user:m.user};return window.location.hash="",this._debug("#_getSessionFromURL()","clearing window.location.hash"),this._returnResult({data:{session:b,redirectType:e.type},error:null})}catch(n){if(v(n))return this._returnResult({data:{session:null,redirectType:null},error:n});throw n}}_isImplicitGrantCallback(e){return typeof this.detectSessionInUrl=="function"?this.detectSessionInUrl(new URL(window.location.href),e):!!(e.access_token||e.error_description)}async _isPKCECallback(e){let r=await Ve(this.storage,`${this.storageKey}-code-verifier`);return !!(e.code&&r)}async signOut(e={scope:"global"}){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>await this._signOut(e))}async _signOut({scope:e}={scope:"global"}){return await this._useSession(async r=>{var n;let{data:i,error:s}=r;if(s&&!Br(s))return this._returnResult({error:s});let o=(n=i.session)===null||n===void 0?void 0:n.access_token;if(o){let{error:a}=await this.admin.signOut(o,e);if(a&&!(vc(a)&&(a.status===404||a.status===401||a.status===403)||Br(a)))return this._returnResult({error:a})}return e!=="others"&&(await this._removeSession(),await z(this.storage,`${this.storageKey}-code-verifier`)),this._returnResult({error:null})})}onAuthStateChange(e){let r=Tc(),n={id:r,callback:e,unsubscribe:()=>{this._debug("#unsubscribe()","state change callback with id removed",r),this.stateChangeEmitters.delete(r);}};return this._debug("#onAuthStateChange()","registered callback with id",r),this.stateChangeEmitters.set(r,n),(async()=>(await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>{this._emitInitialSession(r);})))(),{data:{subscription:n}}}async _emitInitialSession(e){return await this._useSession(async r=>{var n,i;try{let{data:{session:s},error:o}=r;if(o)throw o;await((n=this.stateChangeEmitters.get(e))===null||n===void 0?void 0:n.callback("INITIAL_SESSION",s)),this._debug("INITIAL_SESSION","callback id",e,"session",s);}catch(s){await((i=this.stateChangeEmitters.get(e))===null||i===void 0?void 0:i.callback("INITIAL_SESSION",null)),this._debug("INITIAL_SESSION","callback id",e,"error",s),Br(s)?console.warn(s):console.error(s);}})}async resetPasswordForEmail(e,r={}){let n=null,i=null;this.flowType==="pkce"&&([n,i]=await gt(this.storage,this.storageKey,true));try{return await S(this.fetch,"POST",`${this.url}/recover`,{body:{email:e,code_challenge:n,code_challenge_method:i,gotrue_meta_security:{captcha_token:r.captchaToken}},headers:this.headers,redirectTo:r.redirectTo})}catch(s){if(await z(this.storage,`${this.storageKey}-code-verifier`),v(s))return this._returnResult({data:null,error:s});throw s}}async getUserIdentities(){var e;try{let{data:r,error:n}=await this.getUser();if(n)throw n;return this._returnResult({data:{identities:(e=r.user.identities)!==null&&e!==void 0?e:[]},error:null})}catch(r){if(v(r))return this._returnResult({data:null,error:r});throw r}}async linkIdentity(e){return "token"in e?this.linkIdentityIdToken(e):this.linkIdentityOAuth(e)}async linkIdentityOAuth(e){var r;try{let{data:n,error:i}=await this._useSession(async s=>{var o,a,l,c,u;let{data:d,error:p}=s;if(p)throw p;let h=await this._getUrlForProvider(`${this.url}/user/identities/authorize`,e.provider,{redirectTo:(o=e.options)===null||o===void 0?void 0:o.redirectTo,scopes:(a=e.options)===null||a===void 0?void 0:a.scopes,queryParams:(l=e.options)===null||l===void 0?void 0:l.queryParams,skipBrowserRedirect:!0});return await S(this.fetch,"GET",h,{headers:this.headers,jwt:(u=(c=d.session)===null||c===void 0?void 0:c.access_token)!==null&&u!==void 0?u:void 0})});if(i)throw i;return q()&&!(!((r=e.options)===null||r===void 0)&&r.skipBrowserRedirect)&&window.location.assign(n?.url),this._returnResult({data:{provider:e.provider,url:n?.url},error:null})}catch(n){if(v(n))return this._returnResult({data:{provider:e.provider,url:null},error:n});throw n}}async linkIdentityIdToken(e){return await this._useSession(async r=>{var n;try{let{error:i,data:{session:s}}=r;if(i)throw i;let{options:o,provider:a,token:l,access_token:c,nonce:u}=e,d=await S(this.fetch,"POST",`${this.url}/token?grant_type=id_token`,{headers:this.headers,jwt:(n=s?.access_token)!==null&&n!==void 0?n:void 0,body:{provider:a,id_token:l,access_token:c,nonce:u,link_identity:!0,gotrue_meta_security:{captcha_token:o?.captchaToken}},xform:de}),{data:p,error:h}=d;return h?this._returnResult({data:{user:null,session:null},error:h}):!p||!p.session||!p.user?this._returnResult({data:{user:null,session:null},error:new Ne}):(p.session&&(await this._saveSession(p.session),await this._notifyAllSubscribers("USER_UPDATED",p.session)),this._returnResult({data:p,error:h}))}catch(i){if(await z(this.storage,`${this.storageKey}-code-verifier`),v(i))return this._returnResult({data:{user:null,session:null},error:i});throw i}})}async unlinkIdentity(e){try{return await this._useSession(async r=>{var n,i;let{data:s,error:o}=r;if(o)throw o;return await S(this.fetch,"DELETE",`${this.url}/user/identities/${e.identity_id}`,{headers:this.headers,jwt:(i=(n=s.session)===null||n===void 0?void 0:n.access_token)!==null&&i!==void 0?i:void 0})})}catch(r){if(v(r))return this._returnResult({data:null,error:r});throw r}}async _refreshAccessToken(e){let r=`#_refreshAccessToken(${e.substring(0,5)}...)`;this._debug(r,"begin");try{let n=Date.now();return await $c(async i=>(i>0&&await Oc(200*Math.pow(2,i-1)),this._debug(r,"refreshing attempt",i),await S(this.fetch,"POST",`${this.url}/token?grant_type=refresh_token`,{body:{refresh_token:e},headers:this.headers,xform:de})),(i,s)=>{let o=200*Math.pow(2,i);return s&&Yn(s)&&Date.now()+o-n<lt})}catch(n){if(this._debug(r,"error",n),v(n))return this._returnResult({data:{session:null,user:null},error:n});throw n}finally{this._debug(r,"end");}}_isValidSession(e){return typeof e=="object"&&e!==null&&"access_token"in e&&"refresh_token"in e&&"expires_at"in e}async _handleProviderSignIn(e,r){let n=await this._getUrlForProvider(`${this.url}/authorize`,e,{redirectTo:r.redirectTo,scopes:r.scopes,queryParams:r.queryParams});return this._debug("#_handleProviderSignIn()","provider",e,"options",r,"url",n),q()&&!r.skipBrowserRedirect&&window.location.assign(n),{data:{provider:e,url:n},error:null}}async _recoverAndRefresh(){var e,r;let n="#_recoverAndRefresh()";this._debug(n,"begin");try{let i=await Ve(this.storage,this.storageKey);if(i&&this.userStorage){let o=await Ve(this.userStorage,this.storageKey+"-user");!this.storage.isServer&&Object.is(this.storage,this.userStorage)&&!o&&(o={user:i.user},await ft(this.userStorage,this.storageKey+"-user",o)),i.user=(e=o?.user)!==null&&e!==void 0?e:ti();}else if(i&&!i.user&&!i.user){let o=await Ve(this.storage,this.storageKey+"-user");o&&o?.user?(i.user=o.user,await z(this.storage,this.storageKey+"-user"),await ft(this.storage,this.storageKey,i)):i.user=ti();}if(this._debug(n,"session from storage",i),!this._isValidSession(i)){this._debug(n,"session is not valid"),i!==null&&await this._removeSession();return}let s=((r=i.expires_at)!==null&&r!==void 0?r:1/0)*1e3-Date.now()<Jn;if(this._debug(n,`session has${s?"":" not"} expired with margin of ${Jn}s`),s){if(this.autoRefreshToken&&i.refresh_token){let{error:o}=await this._callRefreshToken(i.refresh_token);o&&(console.error(o),Yn(o)||(this._debug(n,"refresh failed with a non-retryable error, removing the session",o),await this._removeSession()));}}else if(i.user&&i.user.__isUserNotAvailableProxy===!0)try{let{data:o,error:a}=await this._getUser(i.access_token);!a&&o?.user?(i.user=o.user,await this._saveSession(i),await this._notifyAllSubscribers("SIGNED_IN",i)):this._debug(n,"could not get user data, skipping SIGNED_IN notification");}catch(o){console.error("Error getting user data:",o),this._debug(n,"error getting user data, skipping SIGNED_IN notification",o);}else await this._notifyAllSubscribers("SIGNED_IN",i);}catch(i){this._debug(n,"error",i),console.error(i);return}finally{this._debug(n,"end");}}async _callRefreshToken(e){var r,n;if(!e)throw new J;if(this.refreshingDeferred)return this.refreshingDeferred.promise;let i=`#_callRefreshToken(${e.substring(0,5)}...)`;this._debug(i,"begin");try{this.refreshingDeferred=new Fr;let{data:s,error:o}=await this._refreshAccessToken(e);if(o)throw o;if(!s.session)throw new J;await this._saveSession(s.session),await this._notifyAllSubscribers("TOKEN_REFRESHED",s.session);let a={data:s.session,error:null};return this.refreshingDeferred.resolve(a),a}catch(s){if(this._debug(i,"error",s),v(s)){let o={data:null,error:s};return Yn(s)||await this._removeSession(),(r=this.refreshingDeferred)===null||r===void 0||r.resolve(o),o}throw (n=this.refreshingDeferred)===null||n===void 0||n.reject(s),s}finally{this.refreshingDeferred=null,this._debug(i,"end");}}async _notifyAllSubscribers(e,r,n=true){let i=`#_notifyAllSubscribers(${e})`;this._debug(i,"begin",r,`broadcast = ${n}`);try{this.broadcastChannel&&n&&this.broadcastChannel.postMessage({event:e,session:r});let s=[],o=Array.from(this.stateChangeEmitters.values()).map(async a=>{try{await a.callback(e,r);}catch(l){s.push(l);}});if(await Promise.all(o),s.length>0){for(let a=0;a<s.length;a+=1)console.error(s[a]);throw s[0]}}finally{this._debug(i,"end");}}async _saveSession(e){this._debug("#_saveSession()",e),this.suppressGetSessionWarning=true,await z(this.storage,`${this.storageKey}-code-verifier`);let r=Object.assign({},e),n=r.user&&r.user.__isUserNotAvailableProxy===true;if(this.userStorage){!n&&r.user&&await ft(this.userStorage,this.storageKey+"-user",{user:r.user});let i=Object.assign({},r);delete i.user;let s=Ls(i);await ft(this.storage,this.storageKey,s);}else {let i=Ls(r);await ft(this.storage,this.storageKey,i);}}async _removeSession(){this._debug("#_removeSession()"),this.suppressGetSessionWarning=false,await z(this.storage,this.storageKey),await z(this.storage,this.storageKey+"-code-verifier"),await z(this.storage,this.storageKey+"-user"),this.userStorage&&await z(this.userStorage,this.storageKey+"-user"),await this._notifyAllSubscribers("SIGNED_OUT",null);}_removeVisibilityChangedCallback(){this._debug("#_removeVisibilityChangedCallback()");let e=this.visibilityChangedCallback;this.visibilityChangedCallback=null;try{e&&q()&&window?.removeEventListener&&window.removeEventListener("visibilitychange",e);}catch(r){console.error("removing visibilitychange callback failed",r);}}async _startAutoRefresh(){await this._stopAutoRefresh(),this._debug("#_startAutoRefresh()");let e=setInterval(()=>this._autoRefreshTokenTick(),lt);this.autoRefreshTicker=e,e&&typeof e=="object"&&typeof e.unref=="function"?e.unref():typeof Deno<"u"&&typeof Deno.unrefTimer=="function"&&Deno.unrefTimer(e);let r=setTimeout(async()=>{await this.initializePromise,await this._autoRefreshTokenTick();},0);this.autoRefreshTickTimeout=r,r&&typeof r=="object"&&typeof r.unref=="function"?r.unref():typeof Deno<"u"&&typeof Deno.unrefTimer=="function"&&Deno.unrefTimer(r);}async _stopAutoRefresh(){this._debug("#_stopAutoRefresh()");let e=this.autoRefreshTicker;this.autoRefreshTicker=null,e&&clearInterval(e);let r=this.autoRefreshTickTimeout;this.autoRefreshTickTimeout=null,r&&clearTimeout(r);}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 e=Date.now();try{return await this._useSession(async r=>{let{data:{session:n}}=r;if(!n||!n.refresh_token||!n.expires_at){this._debug("#_autoRefreshTokenTick()","no session");return}let i=Math.floor((n.expires_at*1e3-e)/lt);this._debug("#_autoRefreshTokenTick()",`access token expires in ${i} ticks, a tick lasts ${lt}ms, refresh threshold is ${zn} ticks`),i<=zn&&await this._callRefreshToken(n.refresh_token);})}catch(r){console.error("Auto refresh tick failed with error. This is likely a transient error.",r);}}finally{this._debug("#_autoRefreshTokenTick()","end");}});}catch(e){if(e.isAcquireTimeout||e instanceof qr)this._debug("auto refresh token tick lock not available");else throw e}}async _handleVisibilityChange(){if(this._debug("#_handleVisibilityChange()"),!q()||!window?.addEventListener)return this.autoRefreshToken&&this.startAutoRefresh(),false;try{this.visibilityChangedCallback=async()=>{try{await this._onVisibilityChanged(!1);}catch(e){this._debug("#visibilityChangedCallback","error",e);}},window?.addEventListener("visibilitychange",this.visibilityChangedCallback),await this._onVisibilityChanged(!0);}catch(e){console.error("_handleVisibilityChange",e);}}async _onVisibilityChanged(e){let r=`#_onVisibilityChanged(${e})`;this._debug(r,"visibilityState",document.visibilityState),document.visibilityState==="visible"?(this.autoRefreshToken&&this._startAutoRefresh(),e||(await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>{if(document.visibilityState!=="visible"){this._debug(r,"acquired the lock to recover the session, but the browser visibilityState is no longer visible, aborting");return}await this._recoverAndRefresh();}))):document.visibilityState==="hidden"&&this.autoRefreshToken&&this._stopAutoRefresh();}async _getUrlForProvider(e,r,n){let i=[`provider=${encodeURIComponent(r)}`];if(n?.redirectTo&&i.push(`redirect_to=${encodeURIComponent(n.redirectTo)}`),n?.scopes&&i.push(`scopes=${encodeURIComponent(n.scopes)}`),this.flowType==="pkce"){let[s,o]=await gt(this.storage,this.storageKey),a=new URLSearchParams({code_challenge:`${encodeURIComponent(s)}`,code_challenge_method:`${encodeURIComponent(o)}`});i.push(a.toString());}if(n?.queryParams){let s=new URLSearchParams(n.queryParams);i.push(s.toString());}return n?.skipBrowserRedirect&&i.push(`skip_http_redirect=${n.skipBrowserRedirect}`),`${e}?${i.join("&")}`}async _unenroll(e){try{return await this._useSession(async r=>{var n;let{data:i,error:s}=r;return s?this._returnResult({data:null,error:s}):await S(this.fetch,"DELETE",`${this.url}/factors/${e.factorId}`,{headers:this.headers,jwt:(n=i?.session)===null||n===void 0?void 0:n.access_token})})}catch(r){if(v(r))return this._returnResult({data:null,error:r});throw r}}async _enroll(e){try{return await this._useSession(async r=>{var n,i;let{data:s,error:o}=r;if(o)return this._returnResult({data:null,error:o});let a=Object.assign({friendly_name:e.friendlyName,factor_type:e.factorType},e.factorType==="phone"?{phone:e.phone}:e.factorType==="totp"?{issuer:e.issuer}:{}),{data:l,error:c}=await S(this.fetch,"POST",`${this.url}/factors`,{body:a,headers:this.headers,jwt:(n=s?.session)===null||n===void 0?void 0:n.access_token});return c?this._returnResult({data:null,error:c}):(e.factorType==="totp"&&l.type==="totp"&&(!((i=l?.totp)===null||i===void 0)&&i.qr_code)&&(l.totp.qr_code=`data:image/svg+xml;utf-8,${l.totp.qr_code}`),this._returnResult({data:l,error:null}))})}catch(r){if(v(r))return this._returnResult({data:null,error:r});throw r}}async _verify(e){return this._acquireLock(this.lockAcquireTimeout,async()=>{try{return await this._useSession(async r=>{var n;let{data:i,error:s}=r;if(s)return this._returnResult({data:null,error:s});let o=Object.assign({challenge_id:e.challengeId},"webauthn"in e?{webauthn:Object.assign(Object.assign({},e.webauthn),{credential_response:e.webauthn.type==="create"?eu(e.webauthn.credential_response):tu(e.webauthn.credential_response)})}:{code:e.code}),{data:a,error:l}=await S(this.fetch,"POST",`${this.url}/factors/${e.factorId}/verify`,{body:o,headers:this.headers,jwt:(n=i?.session)===null||n===void 0?void 0:n.access_token});return l?this._returnResult({data:null,error:l}):(await this._saveSession(Object.assign({expires_at:Math.round(Date.now()/1e3)+a.expires_in},a)),await this._notifyAllSubscribers("MFA_CHALLENGE_VERIFIED",a),this._returnResult({data:a,error:l}))})}catch(r){if(v(r))return this._returnResult({data:null,error:r});throw r}})}async _challenge(e){return this._acquireLock(this.lockAcquireTimeout,async()=>{try{return await this._useSession(async r=>{var n;let{data:i,error:s}=r;if(s)return this._returnResult({data:null,error:s});let o=await S(this.fetch,"POST",`${this.url}/factors/${e.factorId}/challenge`,{body:e,headers:this.headers,jwt:(n=i?.session)===null||n===void 0?void 0:n.access_token});if(o.error)return o;let{data:a}=o;if(a.type!=="webauthn")return {data:a,error:null};switch(a.webauthn.type){case "create":return {data:Object.assign(Object.assign({},a),{webauthn:Object.assign(Object.assign({},a.webauthn),{credential_options:Object.assign(Object.assign({},a.webauthn.credential_options),{publicKey:Zc(a.webauthn.credential_options.publicKey)})})}),error:null};case "request":return {data:Object.assign(Object.assign({},a),{webauthn:Object.assign(Object.assign({},a.webauthn),{credential_options:Object.assign(Object.assign({},a.webauthn.credential_options),{publicKey:Qc(a.webauthn.credential_options.publicKey)})})}),error:null}}})}catch(r){if(v(r))return this._returnResult({data:null,error:r});throw r}})}async _challengeAndVerify(e){let{data:r,error:n}=await this._challenge({factorId:e.factorId});return n?this._returnResult({data:null,error:n}):await this._verify({factorId:e.factorId,challengeId:r.id,code:e.code})}async _listFactors(){var e;let{data:{user:r},error:n}=await this.getUser();if(n)return {data:null,error:n};let i={all:[],phone:[],totp:[],webauthn:[]};for(let s of (e=r?.factors)!==null&&e!==void 0?e:[])i.all.push(s),s.status==="verified"&&i[s.factor_type].push(s);return {data:i,error:null}}async _getAuthenticatorAssuranceLevel(e){var r,n,i,s;if(e)try{let{payload:h}=Hr(e),f=null;h.aal&&(f=h.aal);let m=f,{data:{user:_},error:b}=await this.getUser(e);if(b)return this._returnResult({data:null,error:b});((n=(r=_?.factors)===null||r===void 0?void 0:r.filter(I=>I.status==="verified"))!==null&&n!==void 0?n:[]).length>0&&(m="aal2");let y=h.amr||[];return {data:{currentLevel:f,nextLevel:m,currentAuthenticationMethods:y},error:null}}catch(h){if(v(h))return this._returnResult({data:null,error:h});throw h}let{data:{session:o},error:a}=await this.getSession();if(a)return this._returnResult({data:null,error:a});if(!o)return {data:{currentLevel:null,nextLevel:null,currentAuthenticationMethods:[]},error:null};let{payload:l}=Hr(o.access_token),c=null;l.aal&&(c=l.aal);let u=c;((s=(i=o.user.factors)===null||i===void 0?void 0:i.filter(h=>h.status==="verified"))!==null&&s!==void 0?s:[]).length>0&&(u="aal2");let p=l.amr||[];return {data:{currentLevel:c,nextLevel:u,currentAuthenticationMethods:p},error:null}}async _getAuthorizationDetails(e){try{return await this._useSession(async r=>{let{data:{session:n},error:i}=r;return i?this._returnResult({data:null,error:i}):n?await S(this.fetch,"GET",`${this.url}/oauth/authorizations/${e}`,{headers:this.headers,jwt:n.access_token,xform:s=>({data:s,error:null})}):this._returnResult({data:null,error:new J})})}catch(r){if(v(r))return this._returnResult({data:null,error:r});throw r}}async _approveAuthorization(e,r){try{return await this._useSession(async n=>{let{data:{session:i},error:s}=n;if(s)return this._returnResult({data:null,error:s});if(!i)return this._returnResult({data:null,error:new J});let o=await S(this.fetch,"POST",`${this.url}/oauth/authorizations/${e}/consent`,{headers:this.headers,jwt:i.access_token,body:{action:"approve"},xform:a=>({data:a,error:null})});return o.data&&o.data.redirect_url&&q()&&!r?.skipBrowserRedirect&&window.location.assign(o.data.redirect_url),o})}catch(n){if(v(n))return this._returnResult({data:null,error:n});throw n}}async _denyAuthorization(e,r){try{return await this._useSession(async n=>{let{data:{session:i},error:s}=n;if(s)return this._returnResult({data:null,error:s});if(!i)return this._returnResult({data:null,error:new J});let o=await S(this.fetch,"POST",`${this.url}/oauth/authorizations/${e}/consent`,{headers:this.headers,jwt:i.access_token,body:{action:"deny"},xform:a=>({data:a,error:null})});return o.data&&o.data.redirect_url&&q()&&!r?.skipBrowserRedirect&&window.location.assign(o.data.redirect_url),o})}catch(n){if(v(n))return this._returnResult({data:null,error:n});throw n}}async _listOAuthGrants(){try{return await this._useSession(async e=>{let{data:{session:r},error:n}=e;return n?this._returnResult({data:null,error:n}):r?await S(this.fetch,"GET",`${this.url}/user/oauth/grants`,{headers:this.headers,jwt:r.access_token,xform:i=>({data:i,error:null})}):this._returnResult({data:null,error:new J})})}catch(e){if(v(e))return this._returnResult({data:null,error:e});throw e}}async _revokeOAuthGrant(e){try{return await this._useSession(async r=>{let{data:{session:n},error:i}=r;return i?this._returnResult({data:null,error:i}):n?(await S(this.fetch,"DELETE",`${this.url}/user/oauth/grants`,{headers:this.headers,jwt:n.access_token,query:{client_id:e.clientId},noResolveJson:!0}),{data:{},error:null}):this._returnResult({data:null,error:new J})})}catch(r){if(v(r))return this._returnResult({data:null,error:r});throw r}}async fetchJwk(e,r={keys:[]}){let n=r.keys.find(a=>a.kid===e);if(n)return n;let i=Date.now();if(n=this.jwks.keys.find(a=>a.kid===e),n&&this.jwks_cached_at+bc>i)return n;let{data:s,error:o}=await S(this.fetch,"GET",`${this.url}/.well-known/jwks.json`,{headers:this.headers});if(o)throw o;return !s.keys||s.keys.length===0||(this.jwks=s,this.jwks_cached_at=i,n=s.keys.find(a=>a.kid===e),!n)?null:n}async getClaims(e,r={}){try{let n=e;if(!n){let{data:h,error:f}=await this.getSession();if(f||!h.session)return this._returnResult({data:null,error:f});n=h.session.access_token;}let{header:i,payload:s,signature:o,raw:{header:a,payload:l}}=Hr(n);r?.allowExpired||Dc(s.exp);let c=!i.alg||i.alg.startsWith("HS")||!i.kid||!("crypto"in globalThis&&"subtle"in globalThis.crypto)?null:await this.fetchJwk(i.kid,r?.keys?{keys:r.keys}:r?.jwks);if(!c){let{error:h}=await this.getUser(n);if(h)throw h;return {data:{claims:s,header:i,signature:o},error:null}}let u=jc(i.alg),d=await crypto.subtle.importKey("jwk",c,u,!0,["verify"]);if(!await crypto.subtle.verify(u,d,o,xc(`${a}.${l}`)))throw new dt("Invalid JWT signature");return {data:{claims:s,header:i,signature:o},error:null}}catch(n){if(v(n))return this._returnResult({data:null,error:n});throw n}}};oi.nextInstanceID={};Ys=oi;});var nu=R(()=>{ni();});var Vm,Zs,iu=R(()=>{Xs();Vm=Ys,Zs=Vm;});var Qs=R(()=>{ni();Xs();nu();iu();Fs();pt();zs();});function Kr(t){"@babel/helpers - typeof";return Kr=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(e){return typeof e}:function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},Kr(t)}function t_(t,e){if(Kr(t)!="object"||!t)return t;var r=t[Symbol.toPrimitive];if(r!==void 0){var n=r.call(t,e);if(Kr(n)!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return (e==="string"?String:Number)(t)}function r_(t){var e=t_(t,"string");return Kr(e)=="symbol"?e:e+""}function n_(t,e,r){return (e=r_(e))in t?Object.defineProperty(t,e,{value:r,enumerable:true,configurable:true,writable:true}):t[e]=r,t}function su(t,e){var r=Object.keys(t);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(t);e&&(n=n.filter(function(i){return Object.getOwnPropertyDescriptor(t,i).enumerable})),r.push.apply(r,n);}return r}function W(t){for(var e=1;e<arguments.length;e++){var r=arguments[e]!=null?arguments[e]:{};e%2?su(Object(r),true).forEach(function(n){n_(t,n,r[n]);}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(r)):su(Object(r)).forEach(function(n){Object.defineProperty(t,n,Object.getOwnPropertyDescriptor(r,n));});}return t}function a_(t){return t.endsWith("/")?t:t+"/"}function l_(t,e){var r,n;let{db:i,auth:s,realtime:o,global:a}=t,{db:l,auth:c,realtime:u,global:d}=e,p={db:W(W({},l),i),auth:W(W({},c),s),realtime:W(W({},u),o),storage:{},global:W(W(W({},d),a),{},{headers:W(W({},(r=d?.headers)!==null&&r!==void 0?r:{}),(n=a?.headers)!==null&&n!==void 0?n:{})}),accessToken:async()=>""};return t.accessToken?p.accessToken=t.accessToken:delete p.accessToken,p}function c_(t){let e=t?.trim();if(!e)throw new Error("supabaseUrl is required.");if(!e.match(/^https?:\/\//i))throw new Error("Invalid supabaseUrl: Must be a valid HTTP or HTTPS URL.");try{return new URL(a_(e))}catch{throw Error("Invalid supabaseUrl: Provided URL is malformed.")}}function p_(){if(typeof window<"u")return false;let t=globalThis.process;if(!t)return false;let e=t.version;if(e==null)return false;let r=e.match(/^v(\d+)\./);return r?parseInt(r[1],10)<=18:false}var Gm,Jr,Ym,Xm,Zm,Qm,e_,i_,s_,o_,u_,d_,er,ai=R(()=>{Nl();Hl();Is();mc();Qs();Is();Qs();Gm="2.103.2",Jr="";typeof Deno<"u"?Jr="deno":typeof document<"u"?Jr="web":typeof navigator<"u"&&navigator.product==="ReactNative"?Jr="react-native":Jr="node";Ym={"X-Client-Info":`supabase-js-${Jr}/${Gm}`},Xm={headers:Ym},Zm={schema:"public"},Qm={autoRefreshToken:true,persistSession:true,detectSessionInUrl:true,flowType:"implicit"},e_={};i_=t=>t?(...e)=>t(...e):(...e)=>fetch(...e),s_=()=>Headers,o_=(t,e,r)=>{let n=i_(r),i=s_();return async(s,o)=>{var a;let l=(a=await e())!==null&&a!==void 0?a:t,c=new i(o?.headers);return c.has("apikey")||c.set("apikey",t),c.has("Authorization")||c.set("Authorization",`Bearer ${l}`),n(s,W(W({},o),{},{headers:c}))}};u_=class extends Zs{constructor(t){super(t);}},d_=class{constructor(t,e,r){var n,i;this.supabaseUrl=t,this.supabaseKey=e;let s=c_(t);if(!e)throw new Error("supabaseKey is required.");this.realtimeUrl=new URL("realtime/v1",s),this.realtimeUrl.protocol=this.realtimeUrl.protocol.replace("http","ws"),this.authUrl=new URL("auth/v1",s),this.storageUrl=new URL("storage/v1",s),this.functionsUrl=new URL("functions/v1",s);let o=`sb-${s.hostname.split(".")[0]}-auth-token`,a={db:Zm,realtime:e_,auth:W(W({},Qm),{},{storageKey:o}),global:Xm},l=l_(r??{},a);if(this.storageKey=(n=l.auth.storageKey)!==null&&n!==void 0?n:"",this.headers=(i=l.global.headers)!==null&&i!==void 0?i:{},l.accessToken)this.accessToken=l.accessToken,this.auth=new Proxy({},{get:(u,d)=>{throw new Error(`@supabase/supabase-js: Supabase Client is configured with the accessToken option, accessing supabase.auth.${String(d)} is not possible`)}});else {var c;this.auth=this._initSupabaseAuthClient((c=l.auth)!==null&&c!==void 0?c:{},this.headers,l.global.fetch);}this.fetch=o_(e,this._getAccessToken.bind(this),l.global.fetch),this.realtime=this._initRealtimeClient(W({headers:this.headers,accessToken:this._getAccessToken.bind(this)},l.realtime)),this.accessToken&&Promise.resolve(this.accessToken()).then(u=>this.realtime.setAuth(u)).catch(u=>console.warn("Failed to set initial Realtime auth token:",u)),this.rest=new Bl(new URL("rest/v1",s).href,{headers:this.headers,schema:l.db.schema,fetch:this.fetch,timeout:l.db.timeout,urlLengthLimit:l.db.urlLengthLimit}),this.storage=new gc(this.storageUrl.href,this.headers,this.fetch,r?.storage),l.accessToken||this._listenForAuthEvents();}get functions(){return new Sr(this.functionsUrl.href,{headers:this.headers,customFetch:this.fetch})}from(t){return this.rest.from(t)}schema(t){return this.rest.schema(t)}rpc(t,e={},r={head:false,get:false,count:void 0}){return this.rest.rpc(t,e,r)}channel(t,e={config:{}}){return this.realtime.channel(t,e)}getChannels(){return this.realtime.getChannels()}removeChannel(t){return this.realtime.removeChannel(t)}removeAllChannels(){return this.realtime.removeAllChannels()}async _getAccessToken(){var t=this,e,r;if(t.accessToken)return await t.accessToken();let{data:n}=await t.auth.getSession();return (e=(r=n.session)===null||r===void 0?void 0:r.access_token)!==null&&e!==void 0?e:t.supabaseKey}_initSupabaseAuthClient({autoRefreshToken:t,persistSession:e,detectSessionInUrl:r,storage:n,userStorage:i,storageKey:s,flowType:o,lock:a,debug:l,throwOnError:c},u,d){let p={Authorization:`Bearer ${this.supabaseKey}`,apikey:`${this.supabaseKey}`};return new u_({url:this.authUrl.href,headers:W(W({},p),u),storageKey:s,autoRefreshToken:t,persistSession:e,detectSessionInUrl:r,storage:n,userStorage:i,flowType:o,lock:a,debug:l,throwOnError:c,fetch:d,hasCustomAuthorizationHeader:Object.keys(this.headers).some(h=>h.toLowerCase()==="authorization")})}_initRealtimeClient(t){return new Vt(this.realtimeUrl.href,W(W({},t),{},{params:W(W({},{apikey:this.supabaseKey}),t?.params)}))}_listenForAuthEvents(){return this.auth.onAuthStateChange((t,e)=>{this._handleTokenChanged(t,"CLIENT",e?.access_token);})}_handleTokenChanged(t,e,r){(t==="TOKEN_REFRESHED"||t==="SIGNED_IN")&&this.changedAccessToken!==r?(this.changedAccessToken=r,this.realtime.setAuth(r)):t==="SIGNED_OUT"&&(this.realtime.setAuth(),e=="STORAGE"&&this.auth.signOut(),this.changedAccessToken=void 0);}},er=(t,e,r)=>new d_(t,e,r);p_()&&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 pe(t){let e=t.SUPABASE_URL??t.VITE_SUPABASE_URL??"https://xygyyikpgykarmqujajf.supabase.co",r=t.SUPABASE_ANON_KEY??t.VITE_SUPABASE_ANON_KEY??"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6Inh5Z3l5aWtwZ3lrYXJtcXVqYWpmIiwicm9sZSI6ImFub24iLCJpYXQiOjE3NzYyMjIyOTcsImV4cCI6MjA5MTc5ODI5N30.y_SPm1eJeofb4zYgPCogTJUPr4e7-z92BzcRzqQiK9g";if(!e||!r)throw new eo("missing_supabase_config","Missing Supabase client configuration for CLI login.");return {supabaseUrl:e,supabaseAnonKey:r}}var eo,Vr=R(()=>{eo=class extends Error{constructor(r,n=r){super(n);this.code=r;this.name="CliAuthConfigError";}code};});async function lu(t){let e=pe(t.env),r=m_(),n=er(e.supabaseUrl,e.supabaseAnonKey,{auth:{persistSession:true,detectSessionInUrl:false,flowType:"pkce",storage:r}}),i=await __({timeoutMs:t.timeoutMs??300*1e3}),s=i.redirectUri;try{let{data:o,error:a}=await n.auth.signInWithOAuth({provider:"github",options:{redirectTo:s,skipBrowserRedirect:!0}});if(a||!o.url)throw new G("oauth_start_failed",a?.message??"Supabase did not return an OAuth URL.");t.onOpen?.({url:o.url,redirectUri:s}),await t.openUrl(o.url);let l=await i.waitForCode(),{data:c,error:u}=await n.auth.exchangeCodeForSession(l);if(u||!c.session?.access_token||!c.session.refresh_token)throw new G("oauth_exchange_failed",u?.message??"Supabase did not return a complete session.");let d=await f_(n,c.session,t.promptMfaCode),p=cu(e.supabaseUrl);return await st(t.env).set(p,JSON.stringify(d)),{session:d,account:p}}finally{await i.close();}}async function f_(t,e,r){let{data:n,error:i}=await t.auth.mfa.getAuthenticatorAssuranceLevel();if(i)throw new G("mfa_check_failed",i.message);if(n.currentLevel===n.nextLevel||n.nextLevel!=="aal2")return g_(e);let{data:s,error:o}=await t.auth.mfa.listFactors();if(o)throw new G("mfa_factor_lookup_failed",o.message);let a=s.totp.find(d=>d.status==="verified");if(!a)throw new G("mfa_factor_missing","Two-factor authentication is enabled, but no verified TOTP factor was returned.");if(!r)throw new G("mfa_required","Two-factor authentication is required for this account.");let l=(await r("Authenticator code: ")).trim(),{data:c,error:u}=await t.auth.mfa.challengeAndVerify({factorId:a.id,code:l});if(u||!c)throw new G("mfa_verify_failed",u?.message??"Two-factor authentication failed.");return {access_token:c.access_token,refresh_token:c.refresh_token,expires_at:Math.floor(Date.now()/1e3)+c.expires_in,expires_in:c.expires_in,token_type:c.token_type,user:{id:c.user.id,email:c.user.email??void 0}}}function g_(t){return {access_token:t.access_token,refresh_token:t.refresh_token,expires_at:t.expires_at??Math.floor(Date.now()/1e3)+(t.expires_in??3600),expires_in:t.expires_in??void 0,token_type:t.token_type,user:{id:t.user.id,email:t.user.email??void 0}}}async function to(t){let e=pe(t.env),r=await ou(t.fetch,e,"auth-device-start",{});t.onPending?.({userCode:r.user_code,verificationUri:r.verification_uri,interval:r.interval});let n=Date.now()+r.expires_in*1e3,i=r.interval;for(;Date.now()<=n;){await t.sleep(i*1e3);let s=await ou(t.fetch,e,"auth-device-token",{device_code:r.device_code},{acceptError:true});if("access_token"in s){let o=cu(e.supabaseUrl);return await st(t.env).set(o,JSON.stringify(s)),{session:s,account:o}}switch(s.error){case "authorization_pending":i=s.interval??i;break;case "slow_down":i=s.interval??Math.min(i+5,30);break;case "expired_token":throw new je("expired_token","The device login code expired.");case "access_denied":throw new je("access_denied","The device login request was denied.");default:throw new je(s.error,`Device login failed: ${s.error}`)}}throw new je("expired_token","The device login code expired.")}function cu(t){let e=new URL(t).hostname;return `sb-${e.endsWith(".supabase.co")?e.slice(0,-12):e}-auth-token`}async function ou(t,e,r,n,i={}){let s=await t(`${e.supabaseUrl}/functions/v1/${r}`,{method:"POST",headers:{"content-type":"application/json",apikey:e.supabaseAnonKey},body:JSON.stringify(n)}),o=await s.json().catch(()=>({}));if(!s.ok&&!i.acceptError)throw new je(o.error??"request_failed");return o}function m_(){let t=new Map;return {getItem:e=>t.get(e)??null,setItem:(e,r)=>{t.set(e,r);},removeItem:e=>{t.delete(e);}}}async function __(t){let e=null,r=null,n=false,i=new Promise((l,c)=>{e=l,r=c;}),s=createServer((l,c)=>{w_(l,c,(u,d)=>{n||(n=true,u?r?.(u):e?.(d));});});await new Promise((l,c)=>{s.once("error",c),s.listen(0,"127.0.0.1",()=>{s.off("error",c),l();});});let o=s.address();if(!o||typeof o=="string")throw await au(s),new G("callback_server_failed");let a=setTimeout(()=>{n||(n=true,r?.(new G("oauth_timeout","Browser login timed out.")));},t.timeoutMs);return {redirectUri:`http://127.0.0.1:${o.port}/auth/callback`,waitForCode:()=>i,close:async()=>{clearTimeout(a),await au(s);}}}function w_(t,e,r){let n=t.headers.host??"127.0.0.1",i=new URL(t.url??"/",`http://${n}`);if(i.pathname!=="/auth/callback"){e.writeHead(404,{"content-type":"text/plain"}),e.end("Not found");return}let s=i.searchParams.get("error")??i.searchParams.get("error_description"),o=i.searchParams.get("code");if(s){e.writeHead(400,{"content-type":"text/plain"}),e.end("Pathrule login failed. You can close this window."),r(new G("oauth_denied",s),"");return}if(!o){e.writeHead(400,{"content-type":"text/plain"}),e.end("Pathrule login could not verify this browser response."),r(new G("oauth_invalid_callback"),"");return}e.writeHead(200,{"content-type":"text/html; charset=utf-8"}),e.end("<!doctype html><title>Pathrule CLI</title><p>Pathrule CLI is signed in. You can close this window.</p>"),r(null,o);}async function au(t){t.listening&&await new Promise(e=>t.close(()=>e()));}var je,G,li=R(()=>{_s();ai();Vr();Vr();je=class extends Error{constructor(r,n=r){super(n);this.code=r;this.name="DeviceLoginError";}code},G=class extends Error{constructor(r,n=r){super(n);this.code=r;this.name="BrowserLoginError";}code};});async function E_(t){await new Promise(e=>setTimeout(e,t));}async function R_(t){try{await mkdir(dirname(t),{recursive:!0,mode:448}),await chmod(dirname(t),448).catch(()=>{});let e=await open(t,"wx",384);await e.writeFile(`${process.pid}:${Date.now()}
48
+ `,"utf8"),await e.close();let r=!1;return async()=>{r||(r=!0,await rm$1(t,{force:!0}).catch(()=>{}));}}catch(e){if(e.code==="EEXIST")return null;throw e}}async function x_(t,e){try{let{stat:r}=await import('fs/promises'),n=await r(t);Date.now()-n.mtimeMs>e&&await rm$1(t,{force:!0});}catch{}}async function pu(t,e={}){let r=e.timeoutMs??v_,n=e.staleMs??S_,i=e.lockFile??A(e.env).tokenLockFile,s=Date.now()+r;for(;Date.now()<=s;){let o=await R_(i);if(o)try{return await t()}finally{await o();}await x_(i,n),await E_(C_);}throw new ro}var v_,S_,C_,ro,hu=R(()=>{K();v_=15e3,S_=45e3,C_=100,ro=class extends Error{constructor(){super("token_refresh_lock_timeout"),this.name="TokenRefreshLockTimeoutError";}};});async function ne(t,e=process.env){let r=it(t,0,e);try{let n=await readFile(r.userConfigFile,"utf8"),i=JSON.parse(n);if(i&&typeof i=="object"&&i.schema_version===1)return i}catch(n){if(n.code!=="ENOENT")throw n}return {schema_version:1}}async function ci(t,e,r=process.env){let n=it(t,0,r);await _u(n.userConfigFile,{...e,schema_version:1});}async function ie(t,e,r=process.env){let i={...await ne(t,r),...e,schema_version:1};return await ci(t,i,r),i}async function gu(t,e=process.env){let r=A(e),n={user_id:t,updated_at:new Date().toISOString()};await _u(r.activeUserFile,n);}async function mu(t=process.env){await rm$1(A(t).activeUserFile,{force:true});}async function _u(t,e){let r=dirname(t);await mkdir(r,{recursive:true,mode:j}),await chmod(r,j).catch(()=>{});let n=`${t}.tmp`;await writeFile(n,JSON.stringify(e,null,2),{encoding:"utf8",mode:O}),await chmod(n,O).catch(()=>{}),await rename(n,t);}var Ge=R(()=>{K();});function wu(t){return t.startsWith(D_)&&t.endsWith(j_)}async function Ce(t=process.env){let e=await yu(t);return !e||!ku(e.session)?e:L_(e,t)}async function yu(t=process.env){let r=await st(t).findAll();for(let n of r)if(wu(n.account))try{let i=JSON.parse(n.value);if(!i.access_token||!i.refresh_token||!i.user?.id)continue;return {account:n.account,session:i}}catch{}return null}function ku(t){return t.expires_at<=Math.floor(Date.now()/1e3)+M_}async function L_(t,e){return pu(async()=>{let r=await yu(e);if(r&&!ku(r.session))return r;let n=pe(e),i=er(n.supabaseUrl,n.supabaseAnonKey,{auth:{persistSession:!1}}),{data:s,error:o}=await i.auth.refreshSession({refresh_token:t.session.refresh_token});if(o)throw new ui("refresh_failed",o.message);if(!s.session?.access_token||!s.session.refresh_token||!s.session.user?.id)throw new ui("refresh_failed","Supabase did not return a complete session.");let a={access_token:s.session.access_token,refresh_token:s.session.refresh_token,expires_at:s.session.expires_at??Math.floor(Date.now()/1e3)+(s.session.expires_in??3600),user:{id:s.session.user.id,email:s.session.user.email??void 0}};return await st(e).set(t.account,JSON.stringify(a)),{account:t.account,session:a}},{env:e})}async function no(t=process.env){let e=st(t),r=await e.findAll(),n=new Set,i=0;for(let o of r)if(wu(o.account)){try{let a=JSON.parse(o.value);a.user?.id&&n.add(a.user.id);}catch{}await e.delete(o.account)&&(i+=1);}let s=0;for(let o of n)await rm$1(it(o,0,t).userCacheDir,{recursive:true,force:true}),s+=1;return await mu(t),{removed_sessions:i,purged_user_caches:s}}var D_,j_,M_,ui,Gr=R(()=>{hu();Ge();_s();K();ai();Vr();D_="sb-",j_="-auth-token",M_=60,ui=class extends Error{constructor(r,n=r){super(n);this.code=r;this.name="CliSessionError";}code};});async function C(t=process.env){let e=await Ce(t);if(!e)throw new tr("not_authenticated","Pathrule CLI is not signed in.");let r=pe(t);return {session:e.session,supabase:er(r.supabaseUrl,r.supabaseAnonKey,{auth:{persistSession:false},global:{headers:{Authorization:`Bearer ${e.session.access_token}`}}})}}var tr,F=R(()=>{ai();li();Gr();tr=class extends Error{constructor(r,n=r){super(n);this.code=r;this.name="CliAuthError";}code};});var Du={};af(Du,{cliOrgWebUrl:()=>ee,currentCliOrg:()=>D,listCliOrgs:()=>we,useCliOrg:()=>hi});async function we(t){let{session:e,supabase:r}=await C(t),{data:n,error:i}=await r.from("organization_members").select("role, organization:organizations ( id, name, slug, plan, subscription_status, trial_status, trial_ends_at, seat_count, paid_extra_seats, trial_seat_cap, beta_referral_credit_cents, beta_referral_activated_count, beta_referral_founder )").eq("user_id",e.user.id);if(i)throw i;let s=await ne(e.user.id,t),o=[],a=new Set;for(let l of n??[]){let c=l.organization,u=Array.isArray(c)?c[0]:c;if(!u||a.has(u.id))continue;a.add(u.id);let d=u.subscription_status?String(u.subscription_status):null,p=u.trial_status?String(u.trial_status):null,h=u.trial_ends_at?String(u.trial_ends_at):null,f=tw(d,p,h);o.push({id:u.id,name:u.name,slug:u.slug,plan:u.plan,subscription_status:d,trial_status:p,trial_ends_at:h,seat_count:Ye(u.seat_count),paid_extra_seats:Ye(u.paid_extra_seats),trial_seat_cap:Ye(u.trial_seat_cap),beta_referral_credit_cents:Ye(u.beta_referral_credit_cents)??0,beta_referral_activated_count:Ye(u.beta_referral_activated_count)??0,beta_referral_founder:u.beta_referral_founder===true,role:l.role,current:s.current_org_id===u.id,billing:{status:d,freeze_kind:f.kind,freeze_reason:f.reason,seats:{active:Ye(u.seat_count),trial_cap:Ye(u.trial_seat_cap),paid_extra:Ye(u.paid_extra_seats)}}});}if(!s.current_org_id&&o.length===1){let l=o[0];l&&(o[0]={...l,current:true});}return o}async function D(t){let e=await we(t);return e.find(r=>r.current)??e[0]??null}async function hi(t,e){let{session:r}=await C(e),i=(await we(e)).find(s=>s.id===t||s.slug===t);if(!i)throw new Error("org_not_found");return await ie(r.user.id,{current_org_id:i.id},e),await gu(r.user.id,e),{...i,current:true}}function ee(t,e,r="home"){let i=`${(e.PATHRULE_WEB_URL??"https://app.pathrule.io").replace(/\/$/,"")}/org/${encodeURIComponent(t.slug)}`;return r==="home"?i:r==="billing"?`${i}/billing`:`${i}/settings${r==="members"?"/members":""}`}function Ye(t){return typeof t=="number"&&Number.isFinite(t)?t:null}function tw(t,e,r){return t==="unpaid"||t==="past_due"?{kind:"subscription",reason:"unpaid"}:t==="canceled"?e==="expired"||r&&new Date(r).getTime()<Date.now()?{kind:"subscription",reason:"trial_expired"}:{kind:"subscription",reason:"canceled"}:{kind:"none",reason:null}}var Ee=R(()=>{Ge();F();});cf(La());function Ua(t,e,r){return `${e}/.claude.json`}var wr="pathrule";function Zi(t){if(t==null)return {};if(typeof t!="object"||Array.isArray(t))throw new Error("Claude config root must be a JSON object");let e=t;if(e.mcpServers!==void 0&&(typeof e.mcpServers!="object"||e.mcpServers===null||Array.isArray(e.mcpServers)))throw new Error("Claude config `mcpServers` must be an object");return e}function Wa(t,e){let r=Zi(t),n={...r.mcpServers??{}},i=!(wr in n);return n[wr]=e,{config:{...r,mcpServers:n},wasNew:i}}function Ba(t){let e=Zi(t);if(!e.mcpServers||!(wr in e.mcpServers))return {config:e,wasPresent:false};let{[wr]:r,...n}=e.mcpServers;return {config:{...e,mcpServers:n},wasPresent:true}}function Fa(t){try{return Zi(t).mcpServers?.[wr]??null}catch{return null}}function B(t){return t.code==="PGRST116"?{code:"not_found",message:t.message}:t.code==="42501"?{code:"permission_denied",message:t.message}:{code:"upstream_error",message:t.message}}async function jt(t,e){let{data:r,error:n}=await t.rpc("pathrule_check_content_dedup",{p_workspace_id:e.workspaceId,p_kind:e.kind,p_node_id:e.kind==="memory"?e.nodeId??null:null,p_candidate:e.candidate,p_threshold:e.threshold??.65,p_max_similar:e.maxSimilar??5,p_exclude_id:e.excludeId??null});if(n)return {ok:false,error:n.message};let i=r??{duplicate:null,similar:[]};return {ok:true,data:{duplicate:i.duplicate,similar:(i.similar??[]).map(s=>({id:s.id,title:s.title,similarity:typeof s.similarity=="string"?Number(s.similarity):s.similarity}))}}}function Ha(t){return t.code!=="23505"?false:!!t.message?.includes("skills_workspace_slug_unique")}async function Qi(t,e,r){let{data:n,error:i}=await t.from("nodes").select("id, workspace_id, parent_id, name, type, relative_path").eq("workspace_id",e).eq("relative_path","/").is("parent_id",null).maybeSingle();if(i)return {error:i.message};if(n)return n;let{data:s,error:o}=await t.from("nodes").insert({workspace_id:e,parent_id:null,name:r,type:"folder",relative_path:"/",order_index:0,status:"active"}).select("id, workspace_id, parent_id, name, type, relative_path").single();if(o||!s){if(o?.code==="23505"){let{data:a}=await t.from("nodes").select("id, workspace_id, parent_id, name, type, relative_path").eq("workspace_id",e).eq("relative_path","/").is("parent_id",null).maybeSingle();if(a)return a}return {error:o?.message??"Root node insert failed"}}return s}function qa(t){let e=t.trim();if(e===""||e==="/")return "/";let n=(e.startsWith("/")?e:"/"+e).replace(/\/+/g,"/");return n==="/"?"/":n.replace(/\/$/,"")}function df(t,e){return (t==="/"?"":t)+"/"+e.trim()}function pf(t){let e=t.split("/").filter(n=>n.length>0),r=e[e.length-1]??"";return /\.[A-Za-z0-9]{1,8}$/.test(r)?"file":"folder"}async function Mt(t,e,r){let{data:n,error:i}=await t.from("nodes").select("id, workspace_id, parent_id, name, type, relative_path").eq("workspace_id",e).eq("relative_path",r).maybeSingle();return i?{error:i.message}:n??null}async function hf(t,e,r,n){let i=qa(r);if(i==="/"){let d=await Mt(t,e,"/");return d&&!("error"in d)?d:{error:"Workspace root node missing \u2014 call ensureWorkspaceRootNode first."}}let s=await Mt(t,e,i);if(s&&!("error"in s)||s&&"error"in s)return s;let o=await Mt(t,e,"/");if(!o)return {error:"Workspace root node missing \u2014 call ensureWorkspaceRootNode first."};if("error"in o)return o;let a=i.split("/").filter(d=>d.length>0),l=pf(i),c=o,u="";for(let d=0;d<a.length;d+=1){let p=a[d];u+="/"+p;let f=d===a.length-1?l:"folder",m=await Mt(t,e,u);if(m&&"error"in m)return m;if(m){c=m;continue}let{count:_}=await t.from("nodes").select("*",{count:"exact",head:true}).eq("workspace_id",e).eq("parent_id",c.id),{data:b,error:w}=await t.from("nodes").insert({workspace_id:e,parent_id:c.id,name:p,type:f,relative_path:df(c.relative_path,p),order_index:_??0,status:"active"}).select("id, workspace_id, parent_id, name, type, relative_path").single();if(w||!b){if(w?.code==="23505"){let y=await Mt(t,e,u);if(y&&!("error"in y)){c=y;continue}}return {error:w?.message??`Insert failed at ${u}`}}c=b;}return c}async function Lt(t,e,r,n){let i=qa(r),s=await Mt(t,e,"/");if(s&&"error"in s)return s;if(!s){let{data:o,error:a}=await t.from("workspaces").select("name").eq("id",e).maybeSingle();if(a)return {error:a.message};let l=o?.name??"Workspace",c=await Qi(t,e,l);if("error"in c)return c}return hf(t,e,i)}function za(t){return {id:t.id,workspaceId:t.workspace_id,nodeId:t.node_id,title:t.title,content:t.content,source:t.source,semanticTags:t.semantic_tags??[],versionId:t.version_id,versionNumber:t.version_number,createdBy:t.created_by,lastEditedBy:t.last_edited_by,lastEditedAt:t.last_edited_at,createdAt:t.created_at,updatedAt:t.updated_at}}function ff(t){return t.length===0?null:{code:"similar_titles",message:`Found ${t.length} memory/rule(s) with a similar title.`,detail:{similar:t}}}async function Ja(t,e){if(!t.workspaceId)return {ok:false,error:{code:"invalid_args",message:"ctx.workspaceId is required for path-based writes"}};let r=await Lt(t.supabase,t.workspaceId,e.node_path);if("error"in r)return {ok:false,error:{code:"upstream_error",message:r.error}};let n=e.title.trim(),i=await jt(t.supabase,{workspaceId:r.workspace_id,kind:"memory",nodeId:r.id,candidate:n});if(i.ok&&i.data.duplicate&&!e.allow_duplicate)return {ok:false,error:{code:"duplicate",message:`A memory titled "${i.data.duplicate.title}" already exists at ${e.node_path}. Use update_memory, pick a different title, or pass allow_duplicate: true to insert anyway.`,detail:{existing_id:i.data.duplicate.id,existing_title:i.data.duplicate.title,similar:i.ok?i.data.similar:[]}}};let{data:s,error:o}=await t.supabase.from("memories").insert({workspace_id:r.workspace_id,node_id:r.id,title:n,content:e.content,source:e.source??"claude",created_by:t.userId,last_edited_by:t.userId}).select("*").single();if(o||!s)return {ok:false,error:B(o??{message:"insert failed"})};let a=i.ok?ff(i.data.similar):null;return a?{ok:true,data:za(s),warnings:[a]}:{ok:true,data:za(s)}}function gf(t){return t.length===0?null:{code:"similar_titles",message:`Found ${t.length} rule(s) with a similar name.`,detail:{similar:t}}}function mf(t){return {id:t.id,workspaceId:t.workspace_id,name:t.name,content:t.content,scopeType:t.scope_type,priority:t.priority,semanticTags:t.semantic_tags??[],versionId:t.version_id,versionNumber:t.version_number,createdBy:t.created_by,lastEditedBy:t.last_edited_by,lastEditedAt:t.last_edited_at,createdAt:t.created_at,updatedAt:t.updated_at}}async function Ka(t,e){if(!t.workspaceId)return {ok:false,error:{code:"invalid_args",message:"ctx.workspaceId is required for path-based writes"}};let r=await Lt(t.supabase,t.workspaceId,e.node_path);if("error"in r)return {ok:false,error:{code:"upstream_error",message:r.error}};let n=e.name.trim(),i=await jt(t.supabase,{workspaceId:r.workspace_id,kind:"rule",candidate:n});if(i.ok&&i.data.duplicate&&!e.allow_duplicate)return {ok:false,error:{code:"duplicate",message:`A rule named "${i.data.duplicate.title}" already exists in this workspace. Use update_rule, pick a different name, or pass allow_duplicate: true.`,detail:{existing_id:i.data.duplicate.id,existing_name:i.data.duplicate.title,similar:i.ok?i.data.similar:[]}}};let{data:s,error:o}=await t.supabase.from("rules").insert({workspace_id:r.workspace_id,name:n,content:e.content,scope_type:e.scope_type,priority:e.priority,created_by:t.userId,last_edited_by:t.userId}).select("*").single();if(o||!s)return {ok:false,error:B(o??{message:"insert failed"})};let a=mf(s),{error:l}=await t.supabase.from("node_rules").insert({node_id:r.id,rule_id:a.id});if(l)return await t.supabase.from("rules").delete().eq("id",a.id),{ok:false,error:{code:"upstream_error",message:`attach failed: ${l.message}`}};let c=i.ok?gf(i.data.similar):null;return c?{ok:true,data:a,warnings:[c]}:{ok:true,data:a}}function _f(t){return {id:t.id,workspaceId:t.workspace_id,name:t.name,description:t.description,content:t.content,source:t.source,githubUrl:t.github_url,version:t.version,tags:t.tags,semanticTags:t.semantic_tags??[],versionId:t.version_id,versionNumber:t.version_number,createdBy:t.created_by,lastEditedBy:t.last_edited_by,lastEditedAt:t.last_edited_at,createdAt:t.created_at,updatedAt:t.updated_at,contentFetchedAt:t.content_fetched_at}}async function Va(t,e){if(!t.workspaceId)return {ok:false,error:{code:"invalid_args",message:"ctx.workspaceId is required for path-based writes"}};let r=await Lt(t.supabase,t.workspaceId,e.node_path);if("error"in r)return {ok:false,error:{code:"upstream_error",message:r.error}};let n=e.name.trim(),i=await jt(t.supabase,{workspaceId:r.workspace_id,kind:"skill",candidate:n,maxSimilar:0});if(i.ok&&i.data.duplicate)return {ok:false,error:{code:"duplicate",message:`A skill with this name already exists in this workspace: "${i.data.duplicate.title}". Use update_skill or pick a different name.`,detail:{existing_id:i.data.duplicate.id,existing_name:i.data.duplicate.title}}};let s=e.source??"manual",{data:o,error:a}=await t.supabase.from("skills").insert({workspace_id:r.workspace_id,name:n,description:e.description,content:e.content,source:s,github_url:e.github_url??null,tags:e.tags??[],created_by:t.userId,last_edited_by:t.userId,content_fetched_at:s==="github_ref"?new Date().toISOString():null}).select("*").single();if(a||!o)return Ha(a??{})?{ok:false,error:{code:"duplicate",message:"A skill with this name already exists in this workspace. Use update_skill or pick a different name."}}:{ok:false,error:B(a??{message:"insert failed"})};let l=_f(o),{error:c}=await t.supabase.from("node_skills").insert({node_id:r.id,skill_id:l.id,is_active:true});return c?(await t.supabase.from("skills").delete().eq("id",l.id),{ok:false,error:{code:"upstream_error",message:`attach failed: ${c.message}`}}):{ok:true,data:l}}var wf=/^[A-Za-z0-9_-]+/,yf=/[\s([{'"`]/;function ts(t){return t.trim().toLowerCase()}function Ga(t){let e=bf(t),r=[];for(let n=0;n<e.length-2;n+=1){if(e[n]!==":"||e[n+1]!==":")continue;let i=n===0?"":e[n-1]??"";if(i&&!yf.test(i))continue;let s=e.slice(n+2).match(wf);if(!s?.[0])continue;let o=s[0];r.push({raw:o,name:ts(o),start:n,end:n+2+o.length}),n+=1+o.length;}return kf(r)}function kf(t){let e=new Set,r=[];for(let n of t)e.has(n.name)||(e.add(n.name),r.push(n));return r}function bf(t){let e="",r=0,n=false,i=false;for(;r<t.length;){if(t.startsWith("```",r)){n=!n,e+=" ",r+=3;continue}let s=t[r]??"";if(!n&&s==="`"){i=!i,e+=" ",r+=1;continue}e+=n||i?s===`
49
49
  `?`
50
50
  `:" ":s,r+=1;}return e}var Xa=[{tag:"frontend",patterns:[/\/packages\/app\b/i,/\b(frontend|front-end|renderer|react|tsx|jsx|component|components|screen|page|view)\b/i]},{tag:"backend",patterns:[/\/packages\/mcp-server\b/i,/\b(backend|server|service|api|ipc|worker|queue)\b/i]},{tag:"database",patterns:[/\b(database|postgres|postgrest|db|sql|rpc|rls|schema)\b/i,/\/supabase\b/i]},{tag:"infra",patterns:[/\b(infra|deploy|deployment|cloudflare|r2|notarize|notarized|updater)\b/i]},{tag:"test",patterns:[/\b(test|tests|vitest|playwright|typecheck|lint|eslint|smoke)\b/i]},{tag:"docs",patterns:[/\b(docs|readme|claude\.md|agents\.md|llms\.txt|documentation)\b/i]},{tag:"config",patterns:[/\b(config|env|toml|yaml|yml|json|settings|preferences)\b/i]},{tag:"ui",patterns:[/\b(ui|ux|modal|popover|dialog|button|badge|tab|tree|layout|design|onboarding)\b/i,/\b(tasarim|tasarım|ekran|sayfa|gorunum|görünüm|yerlesim|yerleşim|rozet)\b/i]},{tag:"design-system",patterns:[/\b(design system|design-system|tokens?|theme|tailwind|shadcn|visual language)\b/i]},{tag:"i18n",patterns:[/\b(i18n|translation|translations|locale|localization|hardcoded)\b/i]},{tag:"electron",patterns:[/\b(electron|main process|renderer|tray|native menu)\b/i]},{tag:"mcp",patterns:[/\b(mcp|model context protocol|get_context|read_memory|tool surface)\b/i]},{tag:"hook",patterns:[/\b(hook|hooks|pretooluse|posttooluse|userpromptsubmit|sessionstart)\b/i]},{tag:"router",patterns:[/\b(router|routing|route|deterministic_route|ai-route)\b/i]},{tag:"performance",patterns:[/\b(performance|latency|timeout|telemetry|cache|optimize|hiz|hız)\b/i]},{tag:"supabase",patterns:[/\b(supabase|edge function|edge-function)\b/i,/\/supabase\b/i]},{tag:"edge-function",patterns:[/\b(edge function|edge-function|functions\/[a-z0-9_-]+)\b/i]},{tag:"rls",patterns:[/\b(rls|row level security|policy|policies)\b/i]},{tag:"auth",patterns:[/\b(auth|jwt|session|login|keychain|oauth)\b/i]},{tag:"billing",patterns:[/\b(billing|subscription|checkout|invoice|payment|usage limit)\b/i]},{tag:"stripe",patterns:[/\b(stripe|webhook|checkout session|paymentintent)\b/i]},{tag:"migration",patterns:[/\b(migration|migrations|schema change|alter table)\b/i]},{tag:"security",patterns:[/\b(security|secret|service role|rls|jwt|permission|access check)\b/i]},{tag:"release",patterns:[/\b(release|ship|publish|version bump|notarized|signed)\b/i]},{tag:"tree",patterns:[/\b(tree|collapse|expand|node tree|treetoolbar)\b/i]},{tag:"suggestions",patterns:[/\b(suggestion|suggestions|suggestionstab|refresh suggestion)\b/i]},{tag:"modal",patterns:[/\b(modal|dialog|popover|sheet)\b/i]},{tag:"skill-package",patterns:[/\b(skill package|skill-package|skillpackagetree|skillpackageviewer)\b/i]},{tag:"workspace",patterns:[/\b(workspace|project root|repo root|node path|root path)\b/i]},{tag:"activity",patterns:[/\b(activity|activities|recent activity|log_activity|activity log)\b/i]},{tag:"cache",patterns:[/\b(cache|cached|etag|warm|cold|ttl)\b/i]}],vf=new Set(Xa.map(t=>t.tag));function Sf(t){let e=t.trim().toLowerCase().replace(/[_\s]+/g,"-").replace(/[^a-z0-9-]/g,"");return vf.has(e)?e:null}function Ya(t){let e=`${t.path??""} ${t.text??""}`,r=new Set;for(let n of t.existingTags??[]){let i=Sf(n);i&&r.add(i);}for(let n of Xa)n.patterns.some(i=>i.test(e))&&r.add(n.tag);return Array.from(r).slice(0,t.limit??8)}function rt(t,e){let r=Ya({existingTags:t?Array.from(t):[],limit:e.limit});return r.length>0?r:Ya(e)}function Cf(t){let e=Array.isArray(t.skill_files)?t.skill_files:t.skill_files?[t.skill_files]:[];return (e.find(n=>n.path==="SKILL.md")??e.find(n=>n.role==="primary"))?.content??t.content??""}async function Ut(t,e){let[r,n,i,s]=await Promise.all([t.supabase.from("nodes").select("id, relative_path").eq("workspace_id",e.workspace_id).eq("status","active"),t.supabase.from("memories").select("id, title, node_id, semantic_tags").eq("workspace_id",e.workspace_id).eq("status","active").order("created_at",{ascending:true}),t.supabase.from("node_rules").select("node_id, rules(id, name, content, scope_type, priority, semantic_tags)"),t.supabase.from("node_skills").select("node_id, is_active, skills(id, name, description, source, tags, semantic_tags)").eq("is_active",true)]);if(r.error)return {ok:false,error:B(r.error)};if(n.error)return {ok:false,error:B(n.error)};if(i.error)return {ok:false,error:B(i.error)};if(s.error)return {ok:false,error:B(s.error)};let o=new Map;for(let u of r.data??[])o.set(u.id,u.relative_path);let a=new Map;function l(u){let d=a.get(u);return d||(d={memories:[],rules:[],skills:[]},a.set(u,d)),d}for(let u of n.data??[])l(u.node_id).memories.push({id:u.id,title:u.title,semantic_tags:rt(u.semantic_tags,{text:u.title,path:o.get(u.node_id)})});for(let u of i.data??[]){let d=u.rules,p=Array.isArray(d)?d[0]:d;if(!p)continue;let h=p,f=u.node_id;l(f).rules.push({id:h.id,name:h.name,scope_type:h.scope_type,priority:h.priority,semantic_tags:rt(h.semantic_tags,{text:`${h.name} ${h.content??""}`,path:o.get(f)})});}for(let u of s.data??[]){let d=u.skills,p=Array.isArray(d)?d[0]:d;if(!p)continue;let h=p,f=u.node_id;l(f).skills.push({id:h.id,name:h.name,source:h.source,semantic_tags:rt(h.semantic_tags,{text:`${h.name} ${h.description??""}`,path:o.get(f),existingTags:h.tags})});}let c=[];for(let[u,d]of a.entries()){if(e.exclude_node_id&&u===e.exclude_node_id)continue;let p=o.get(u);p&&(d.memories.length===0&&d.rules.length===0&&d.skills.length===0||c.push({node_id:u,relative_path:p,memories:d.memories,rules:d.rules,skills:d.skills}));}return c.sort((u,d)=>u.relative_path.localeCompare(d.relative_path)),{ok:true,data:c}}function Ef(t,e=160){let r=t.replace(/`[^`]*`/g,"").replace(/#+\s*/g,"").replace(/[*_~]+/g,"").trim(),n=r.indexOf("."),i=n>0&&n<e?r.slice(0,n+1):r.slice(0,e);return i.length<r.length?`${i}\u2026`:i}async function Rf(t,e,r){let n=Ga(r??"");if(n.length===0)return {invokedSkills:[],missingInvokedSkills:[]};let{data:i,error:s}=await t.from("skills").select("id, name, description, content, source, github_url, skill_files(path, content, role)").eq("workspace_id",e).is("deleted_at",null);if(s)throw new Error(`skill invocation lookup failed: ${s.message}`);let o=new Map;for(let c of i??[]){let u=c;if(!u.name)continue;let d=ts(u.name);o.set(d,[...o.get(d)??[],c]);}let a=[],l=[];for(let c of n){let u=o.get(c.name)??[];if(u.length===0){l.push({name:c.name,reason:"not_found"});continue}if(u.length>1){l.push({name:c.name,reason:"duplicate"});continue}let d=u[0];a.push({id:d.id,name:d.name,description:d.description,content:Cf(d),source:d.source,githubUrl:d.github_url,nodeRelativePath:null});}return {invokedSkills:a,missingInvokedSkills:l}}async function vn(t,e){let r=await Rf(t.supabase,e.workspace_id,e.user_intent),{data:n,error:i}=await t.supabase.from("nodes").select("id, name, relative_path").eq("workspace_id",e.workspace_id).eq("relative_path",e.relative_path).maybeSingle();if(i)return {ok:false,error:B(i)};if(!n){let h=await Ut(t,{workspace_id:e.workspace_id});return {ok:true,data:{resolved_workspace_path:e.relative_path||"/",node:null,memories:[],rules:[],skills:[],workspace_overview:h.ok?h.data:[],invoked_skills:r.invokedSkills.length>0?r.invokedSkills:void 0,missing_invoked_skills:r.missingInvokedSkills.length>0?r.missingInvokedSkills:void 0}}}let s=n.id,[o,a,l,c]=await Promise.all([t.supabase.from("memories").select("id, title, content, semantic_tags").eq("node_id",s).eq("status","active").order("created_at",{ascending:true}),t.supabase.from("node_rules").select("rules(id, name, content, scope_type, priority, semantic_tags)").eq("node_id",s),t.supabase.from("node_skills").select("skills(id, name, description, source, tags, semantic_tags)").eq("node_id",s).eq("is_active",true),Ut(t,{workspace_id:e.workspace_id,exclude_node_id:s})]);if(o.error)return {ok:false,error:B(o.error)};if(a.error)return {ok:false,error:B(a.error)};if(l.error)return {ok:false,error:B(l.error)};let u=(o.data??[]).map(h=>({id:h.id,title:h.title,preview:Ef(h.content??""),semantic_tags:rt(h.semantic_tags,{text:`${h.title} ${(h.content??"").slice(0,1e3)}`,path:n.relative_path})})),d=[];for(let h of a.data??[]){let f=h.rules,m=Array.isArray(f)?f[0]:f;if(!m)continue;let _=m;d.push({id:_.id,name:_.name,scope_type:_.scope_type,priority:_.priority,semantic_tags:rt(_.semantic_tags,{text:`${_.name} ${_.content??""}`,path:n.relative_path})});}let p=[];for(let h of l.data??[]){let f=h.skills,m=Array.isArray(f)?f[0]:f;if(!m)continue;let _=m;p.push({id:_.id,name:_.name,description:_.description,source:_.source,semantic_tags:rt(_.semantic_tags,{text:`${_.name} ${_.description??""}`,path:n.relative_path,existingTags:_.tags})});}return {ok:true,data:{resolved_workspace_path:e.relative_path||n.relative_path,node:{id:s,name:n.name,relative_path:n.relative_path},memories:u,rules:d,skills:p,workspace_overview:c.ok?c.data:[],invoked_skills:r.invokedSkills.length>0?r.invokedSkills:void 0,missing_invoked_skills:r.missingInvokedSkills.length>0?r.missingInvokedSkills:void 0}}}async function Za(t){if(t.recipientUserIds.length===0)return {ok:true,skipped:"empty_recipients"};let{error:e}=await t.supabase.rpc("emit_notification",{p_event_type:t.eventType,p_workspace_id:t.workspaceId,p_actor_user_id:t.actorUserId,p_payload:t.payload,p_recipient_user_ids:t.recipientUserIds});return e?(console.warn(`[notifications:emit] ${t.eventType} failed:`,e.message),{ok:false,error:e.message}):{ok:true}}async function Qa(t,e,r=null){let{data:n}=await t.from("workspaces").select("organization_id").eq("id",e).maybeSingle();if(!n)return [];let{data:i,error:s}=await t.from("organization_members").select("user_id, role").eq("organization_id",n.organization_id).in("role",["owner","admin"]);if(s||!i)return [];let o=new Set;for(let a of i)r!=null&&a.user_id===r||o.add(a.user_id);return Array.from(o)}async function xf(t,e,r){let n=e==="memory"?"memories":"rules",i=e==="memory"?"title":"name",{data:s}=await t.from(n).select(`created_by, ${i}`).eq("id",r).maybeSingle();return s?{creatorId:s.created_by??null,title:s[i]??""}:{creatorId:null,title:""}}function rs(t){return {id:t.id,workspaceId:t.workspace_id,suggestionId:t.suggestion_id,subjectType:t.subject_type,subjectId:t.subject_id,formulaId:t.formula_id,status:t.status,requestedByUserId:t.requested_by_user_id,claimedByAi:t.claimed_by_ai,claimedAt:t.claimed_at,resolvedAt:t.resolved_at,resolvedNote:t.resolved_note,createdAt:t.created_at,updatedAt:t.updated_at,brief:t.brief??{}}}async function el(t,e){let r=e.include_in_progress?["pending","in_progress"]:["pending"],{data:n,error:i}=await t.supabase.from("suggestion_refreshes").select("id, subject_type, subject_id, formula_id, status, created_at, brief").eq("workspace_id",e.workspace_id).in("status",r).order("created_at",{ascending:true});return i?{ok:false,error:B(i)}:{ok:true,data:(n??[]).map(a=>{let l=a.brief??{};return {id:a.id,subjectType:a.subject_type,subjectId:a.subject_id,subjectTitle:l.subject?.title??"(unknown)",nodePath:l.subject?.nodePath??"/",formulaId:a.formula_id,humanReason:l.signal?.humanReason??a.formula_id,status:a.status,createdAt:a.created_at,hasProposedPatch:!!l.proposedPatch?.newBody}})}}async function tl(t,e){let{data:r,error:n}=await t.supabase.from("suggestion_refreshes").select("*").eq("id",e.refresh_id).maybeSingle();if(n)return {ok:false,error:B(n)};if(!r)return {ok:false,error:{code:"not_found",message:`Refresh ${e.refresh_id} not found`}};let i=rs(r);if(i.status==="pending"){let s=new Date().toISOString(),{data:o,error:a}=await t.supabase.from("suggestion_refreshes").update({status:"in_progress",claimed_at:s,claimed_by_ai:e.claimed_by??null}).eq("id",e.refresh_id).eq("status","pending").select("*").maybeSingle();if(a)return {ok:false,error:B(a)};if(o)return {ok:true,data:rs(o)}}return {ok:true,data:i}}async function rl(t,e){let r=new Date().toISOString(),{data:n,error:i}=await t.supabase.from("suggestion_refreshes").update({status:e.status,resolved_at:r,resolved_note:e.note??null,...e.claimed_by?{claimed_by_ai:e.claimed_by}:{}}).eq("id",e.refresh_id).select("*").maybeSingle();if(i)return {ok:false,error:B(i)};if(!n)return {ok:false,error:{code:"not_found",message:`Refresh ${e.refresh_id} not found`}};let s=n;s.suggestion_id&&await t.supabase.from("suggestions").update({resolved_at:r}).eq("id",s.suggestion_id).is("resolved_at",null);let o=e.status==="applied"?30:365,{data:a}=await t.supabase.auth.getUser(),l=a?.user?.id;if(l&&await t.supabase.from("suggestion_dismissals").insert({workspace_id:s.workspace_id,subject_type:s.subject_type,subject_id:s.subject_id,formula_id:s.formula_id,action:"keep",dismiss_count:1,next_recheck_at:new Date(Date.now()+o*864e5).toISOString(),user_id:l}),e.status==="applied"||e.status==="rejected")try{let c=e.status==="applied"?"suggestion.applied":"suggestion.rejected",u=s.subject_type,d=s.subject_id,p=s.workspace_id,{creatorId:h,title:f}=await xf(t.supabase,u,d),m=await Qa(t.supabase,p,t.userId),_=new Set;h&&h!==t.userId&&_.add(h);for(let y of m)_.add(y);let b={subject_type:u,subject_title:f};e.status==="rejected"&&e.note&&(b.reason=e.note);let w=await Za({supabase:t.supabase,eventType:c,workspaceId:p,actorUserId:t.userId,payload:b,recipientUserIds:Array.from(_)});w.ok||console.warn(`[notifications:emit] suggestion resolution failed: ${w.error}`);}catch(c){console.warn("[notifications:emit] suggestion resolution threw:",c);}return {ok:true,data:rs(s)}}var Pf="<!-- managed by Pathrule \u2014 do not edit this file manually. Cloud state is authoritative. Local edits are overwritten. -->",Tf=["# Pathrule Workspace","","Pathrule is this workspace's shared memory, rule, and skill layer for AI agents.","Use it as a smart reminder system, not a full-context dump.","","## Context Policy","","- Pathrule is the first knowledge layer for this workspace. Use hook context first: metadata, relevant rule titles, path reminders, and filename/skill matches.","- `::skill-name` is a hard gate: use the exact injected skill; if missing, stop and resolve it through Pathrule/MCP before file edits.",'- Do not reflexively call `pathrule_get_context` before every small known-path code task. For discovery, inventory, architecture, recent activity, or "list/show/find/where/which" prompts (Turkish: listele, g\xF6ster, bul, nerede, hangi, neler), call it before any grep/read/fallback when hook context is missing, ambiguous, or stale.',"- Hook silence on a topic does not mean Pathrule has no relevant memory/rule. For discovery/inventory/architecture questions, call `pathrule_get_context` first; fall back to files, git, or general knowledge only after Pathrule returns nothing relevant.","- When calling `pathrule_get_context`, pass `cwd`, `user_intent`, and `omit_protocol: true`; this file already contains the protocol.","- Read full bodies with `pathrule_read_memory`, `pathrule_read_rule`, or `pathrule_read_skill` when a surfaced title/id is relevant.","- Treat existing local edits as protected user/team work: inspect overlaps, never revert unrelated changes, and keep edits scoped.","- Obey every surfaced rule. If a user request conflicts with a Pathrule rule, warn before taking action.","","## Writes","","- Pathrule cloud is the source of truth. Do not create local memory files such as `MEMORY.md` or `~/.claude/memory/`.","- Use path-first writes for lasting project knowledge: `pathrule_write_memory`, `pathrule_write_rule`, and `pathrule_write_skill` take the most specific workspace-relative `node_path`.","- Do not edit materialized local Pathrule files as the source of truth. This includes `.codex/skills/**/SKILL.md`, `.claude/skills/**`, rendered companion files, and synced skill/memory/rule files. Read only for orientation; create/update cloud records with the Pathrule MCP write/update tools.","- After any file-modifying response, call `pathrule_log_activity` once with domain, action, scope, subjects, files_touched, and a concise task_summary.",""].join(`
51
51
  `);function nl(t){let e=[Pf,"",Tf].join(`
@@ -54,7 +54,7 @@ ${b}`}var Kc=R(()=>{});function Vc({error:t,options:e}){var r,n,i;let{publicKey:
54
54
  `);return e.endsWith(`
55
55
  `)?e:`${e}
56
56
  `}async function Af(t,e){let{data:r,error:n}=await t.from("workspaces").select("name").eq("id",e).maybeSingle();if(n)throw new Error(`workspaces lookup failed: ${n.message}`);if(!r)throw new Error(`workspace ${e} not found (RLS or deleted)`);return r.name}async function il(t){await Af(t.supabase,t.workspaceId);let r={supabase:t.supabase},[n,i]=await Promise.all([vn(r,{workspace_id:t.workspaceId,relative_path:"/"}),Ut(r,{workspace_id:t.workspaceId})]);if(!n.ok)throw new Error(`getContext failed: ${n.error.message}`);if(!i.ok)throw new Error(`getWorkspaceOverview failed: ${i.error.message}`);let s=[];try{let l=new Date(Date.now()-12096e5).toISOString(),{data:c}=await t.supabase.from("activity_logs").select("domain, action, task_summary, created_at").eq("workspace_id",t.workspaceId).eq("status","active").gte("created_at",l).order("created_at",{ascending:!1}).limit(8);c&&(s=c);}catch{}let o=nl({rootContext:{memories:n.data.memories.map(l=>({id:l.id,title:l.title,preview:l.preview})),rules:n.data.rules,skills:n.data.skills.map(l=>({id:l.id,name:l.name,description:l.description,source:l.source}))},overview:i.data,recentActivities:s.length>0?s:void 0}),a=true;try{let{data:l,error:c}=await t.supabase.from("claude_md_snapshots").select("body").eq("workspace_id",t.workspaceId).maybeSingle();if(c)console.warn("[claude-md] snapshot read skipped:",c.message);else if(a=!l||l.body!==o,a){let{error:u}=await t.supabase.from("claude_md_snapshots").upsert({workspace_id:t.workspaceId,body:o,rendered_by:t.userId,rendered_at:new Date().toISOString()});u&&console.warn("[claude-md] snapshot upsert skipped:",u.message);}}catch{}return {body:o,snapshotChanged:a}}function sl(t){let e=ns(t),r=2166136261;for(let n=0;n<e.length;n++)r^=e.charCodeAt(n),r=Math.imul(r,16777619);return (r>>>0).toString(16).padStart(8,"0")}function ns(t){return t===null?"null":Array.isArray(t)?"["+t.map(ns).join(",")+"]":typeof t=="object"?"{"+Object.keys(t).sort().map(n=>JSON.stringify(n)+":"+ns(t[n])).join(",")+"}":JSON.stringify(t)}var ol={PreToolUse:"preToolUse",PostToolUse:"postToolUse",UserPromptSubmit:"beforeSubmitPrompt",SessionStart:"sessionStart",SessionEnd:"sessionEnd",Stop:"stop",SubagentStop:"subagentStop",Notification:null,PreCompact:null,PostCompact:null};var al={Edit:"Write",Bash:"Shell"},ll={PreToolUse:"PreToolUse",PostToolUse:"PostToolUse",UserPromptSubmit:"UserPromptSubmit",SessionStart:"SessionStart",SessionEnd:null,Stop:"Stop",SubagentStop:null,Notification:null,PreCompact:null,PostCompact:null},cl={Edit:"apply_patch",Write:"apply_patch"};var is=null;function If(t){return !!(t.startsWith("/")||/^[a-zA-Z]:[\\/]/.test(t)||t.startsWith("\\\\"))}function ss(t){if(typeof t!="string"||t.length===0)throw new Error("setHookCommand requires a non-empty string");if(t.startsWith("~"))throw new Error(`setHookCommand requires an absolute path; got ${t}. Tilde paths are not expanded by Codex's hook spawn (no shell), so they ENOENT silently. Resolve homedir() in the caller.`);if(!If(t))throw new Error(`setHookCommand requires an absolute path; got ${t}. Relative paths (e.g. bin/pathrule-hook.js) resolve against the AI client's working directory at hook spawn time, which is not stable.`);is=t;}function os(){if(is===null)throw new Error("Pathrule hook command not configured. Each Node entry point (electron main, mcp-server, build scripts) must call setHookCommand(absolutePath) at startup before invoking any merger (ensureClaudeSettingsHook, ensureCodexHooks, etc.).");return is}var Of=new Set(["Read","Write","Grep","Delete","Task","Shell"]),$f=new Set(["SessionStart","PreToolUse","PostToolUse","Stop","SubagentStop","SessionEnd"]);function as(t){return t.map(e=>({matcher:e.matcher,hooks:e.hooks.map(r=>({...r}))}))}function Nf(t){if(!t.matcher)return t;let e=new Set,r=[];for(let n of t.matcher.split("|")){let i=al[n]??n;Of.has(i)&&(e.has(i)||(e.add(i),r.push(i)));}return r.length===0?null:{...t,matcher:r.join("|")}}function He(t){let e=os();return {hooks:{SessionStart:[{hooks:[{type:"command",command:e}]}],PreToolUse:[{matcher:"Read|Edit|Write|Grep|Glob|Bash",hooks:[{type:"command",command:e}]}],PostToolUse:[{matcher:"Read|Edit|Write|Bash",hooks:[{type:"command",command:e}]}],UserPromptSubmit:[{hooks:[{type:"command",command:e}]}],Stop:[{hooks:[{type:"command",command:e}]}],SubagentStop:[{hooks:[{type:"command",command:e}]}],SessionEnd:[{hooks:[{type:"command",command:e}]}]}}}function ls(t){let e={};for(let[r,n]of Object.entries(t.hooks)){let i=r;if(!$f.has(i))continue;let s=ol[i];if(!s||!n||n.length===0)continue;let o=as(n).map(Nf).filter(a=>a!==null);o.length!==0&&(e[s]=o);}return e}function ul(t){return `${JSON.stringify({version:1,hooks:ls(t)},null,2)}
57
- `}var jf=new Set(["Bash","apply_patch"]),Df=new Set(["SessionStart","PreToolUse","PostToolUse","UserPromptSubmit","Stop"]);function Mf(t){if(!t.matcher)return t;let e=new Set,r=[];for(let n of t.matcher.split("|")){let i=cl[n]??n;jf.has(i)&&(e.has(i)||(e.add(i),r.push(i)));}return r.length===0?null:{...t,matcher:r.join("|")}}function cs(t){let e={};for(let[r,n]of Object.entries(t.hooks)){let i=r;if(!Df.has(i))continue;let s=ll[i];if(!s||!n||n.length===0)continue;let o=as(n).map(Mf).filter(a=>a!==null);if(o.length===0&&n.some(a=>!a.matcher)){e[s]=as(n).filter(a=>!a.matcher);continue}o.length!==0&&(e[s]=o);}return e}function dl(t){return `${JSON.stringify({hooks:cs(t)},null,2)}
57
+ `}var Df=new Set(["Bash","apply_patch"]),jf=new Set(["SessionStart","PreToolUse","PostToolUse","UserPromptSubmit","Stop"]);function Mf(t){if(!t.matcher)return t;let e=new Set,r=[];for(let n of t.matcher.split("|")){let i=cl[n]??n;Df.has(i)&&(e.has(i)||(e.add(i),r.push(i)));}return r.length===0?null:{...t,matcher:r.join("|")}}function cs(t){let e={};for(let[r,n]of Object.entries(t.hooks)){let i=r;if(!jf.has(i))continue;let s=ll[i];if(!s||!n||n.length===0)continue;let o=as(n).map(Mf).filter(a=>a!==null);if(o.length===0&&n.some(a=>!a.matcher)){e[s]=as(n).filter(a=>!a.matcher);continue}o.length!==0&&(e[s]=o);}return e}function dl(t){return `${JSON.stringify({hooks:cs(t)},null,2)}
58
58
  `}var Sn={before:["Pathrule is the first knowledge layer for this workspace. Hooks auto-inject path-scoped memory/rule titles + session digest on every tool call and user prompt (M12). Trust that context before falling back to files, git, or general knowledge.","`::skill-name` is a hard gate: use the exact injected skill; if missing, stop and resolve it through Pathrule/MCP before file edits.","Do NOT reflexively call pathrule_get_context before every small known-path code task. DO call pathrule_get_context(cwd, user_intent, omit_protocol: true) before any grep/read/fallback when hook context is missing, ambiguous, stale, or the user asks for discovery, inventory, architecture, recent activity, or list/show/find/where/which style questions (including Turkish: listele, g\xF6ster, bul, nerede, hangi, neler).","Hook silence on a topic does not mean Pathrule has no relevant memory/rule. For discovery/inventory/architecture questions, call pathrule_get_context first; fall back to files, git, or general knowledge only after Pathrule returns nothing relevant. It's a single unified tool (M13): the router classifies intent and returns a depth-appropriate response - minimal for ui_tweak/new_feature on a known path, focused for bug_fix/refactor, deep for debug/discovery.","For discovery/inventory questions, treat `subtree_memory_index`, `discovery_signal`, and `semantic_candidates` as Pathrule evidence before filesystem fallback. Semantic candidates are not answers or rules: call pathrule_read_memory(id) and inspect the body before citing or following one.","The response tells you `next_required_action.primary_files` when the router is confident \u2014 edit those directly. For full memory/rule bodies: pathrule_read_memory(id) / pathrule_read_rule(id).","Obey every rule the hooks surface (advisory + strict). Apply every memory whose title looks relevant \u2014 fetch the body only when you want to cite or follow it.","Treat existing local edits as protected user/team work: inspect before touching overlapping files, never revert unrelated changes, and keep edits scoped to the user's request."],during:["Path-first writes: write_memory / write_rule / write_skill take a node_path string (e.g. '/apps/mobile'). Target the most specific path; missing nodes auto-create.","Never use local file-based memory (~/.claude/memory/, MEMORY.md). Pathrule is the single source of truth for all persistent knowledge.","After every write, summarise what you did in natural language \u2014 don't paste raw tool JSON."],after:["Log EVERY file-modifying response with pathrule_log_activity. Trigger: did you modify files? \u2192 log it. Required fields: domain, action, scope, subjects (\u22645 keywords), files_touched, task_summary."]},hl=sl(Sn);function fl(){let t=["# Pathrule Protocol","","This workspace uses Pathrule MCP. Follow this protocol on EVERY task.","","## BEFORE \u2014 mandatory first steps",""],e=1;for(let r of Sn.before)t.push(`${e}. ${r}`),e++;t.push("","## DURING \u2014 constraints while coding","");for(let r of Sn.during)t.push(`${e}. ${r}`),e++;t.push("","## AFTER \u2014 mandatory after every file modification","");for(let r of Sn.after)t.push(`${e}. ${r}`),e++;return t.push(""),t.join(`
59
59
  `)}var Lf=["pathrule-hook.js","pathrule_log_activity"];function Uf(){return He().hooks}function Wf(){return ls(He())}function Bf(){return cs(He())}function Cn(t){return t?Lf.some(e=>t.includes(e)):false}function yr(t){let e=[];for(let r of t){let n=(r.hooks??[]).filter(i=>!Cn(i.command));n.length!==0&&e.push({...r,hooks:n});}return e}function En(t){let e={};if(t&&t.trim().length>0)try{e=JSON.parse(t);}catch{e={_backup:t};}e.hooks||(e.hooks={});let r=false;for(let[n,i]of Object.entries(Uf())){let s=e.hooks[n],o=Array.isArray(s)?s:[],a=o.filter(u=>(u.hooks??[]).some(d=>Cn(d.command))),l=yr(o);a.length===i.length&&a.every((u,d)=>{let p=i[d];if(!p)return false;let h=u.hooks,f=p.hooks;return (u.matcher??"")===(p.matcher??"")&&h.length===f.length&&h.every((m,_)=>m.command===f[_]?.command)})||(e.hooks[n]=[...l,...i],r=true);}return {body:JSON.stringify(e,null,2)+`
60
60
  `,changed:r}}function gl(t,e){let r={version:1};if(t&&t.trim().length>0)try{r=JSON.parse(t);}catch{r={version:1,_backup:t};}typeof r.version!="number"&&(r.version=1),(!r.hooks||typeof r.hooks!="object")&&(r.hooks={});let n=e?.uninstall===true,i=false;if(n){for(let a of Object.keys(r.hooks)){let l=r.hooks[a];if(!Array.isArray(l))continue;let c=yr(l);c.length!==l.length&&(c.length===0?delete r.hooks[a]:r.hooks[a]=c,i=true);}let s=Object.keys(r).filter(a=>a!=="version"&&a!=="hooks"),o=Object.keys(r.hooks);return s.length===0&&o.length===0?{body:"",changed:true}:{body:JSON.stringify(r,null,2)+`
@@ -70,13 +70,13 @@ ${a}`:"")).trimEnd();}else s=r.trimEnd();if(e?.uninstall===true){let a=s.length>
70
70
 
71
71
  ${pl}`:pl;return r===o?{body:r,changed:false}:{body:o,changed:true}}var Ff={profile:80,organization:100,workspace:120},Hf=new Set(["pathrule","pathrule admin","pathrule support","pathrule security"]),qf=new Set(["admin","administrator","security","support","system"]),wl=/[\u0000-\u001f\u007f-\u009f]/,zf=/[\u0000-\u001f\u007f-\u009f]/g,Jf=/<\/?[a-z][^>]*>/i,Kf=/(^|\s)(https?:\/\/|javascript:|data:|mailto:)/i,Vf=/^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)+$/i;function Gf(t){return t.replace(/\s+/g," ").trim()}function ds(t,e){if(wl.test(t))return {ok:false,reason:"control_chars"};let r=Gf(t);if(r.length===0)return {ok:false,reason:"empty"};if(Array.from(r).length>Ff[e])return {ok:false,reason:"too_long"};if(Jf.test(r))return {ok:false,reason:"html_like"};if(Kf.test(r))return {ok:false,reason:"url_like"};if(e==="profile"&&Vf.test(r))return {ok:false,reason:"url_like"};let n=r.toLocaleLowerCase("en-US");return e!=="workspace"&&Hf.has(n)?{ok:false,reason:"reserved"}:e==="profile"&&qf.has(n)?{ok:false,reason:"reserved"}:{ok:true,value:r}}function yl(t,e){if(typeof t!="string")return null;let r=ds(t,e);return r.ok?r.value??null:null}function kl(t,e=2048){if(typeof t!="string")return null;let r=t.trim();if(!r||r.length>e||wl.test(r))return null;try{let n=new URL(r);return n.protocol!=="http:"&&n.protocol!=="https:"?null:n.toString()}catch{return null}}function xn(t){return t.replace(zf,e=>e===`
72
72
  `?"\\n":e==="\r"?"\\r":e===" "?"\\t":`\\u${e.charCodeAt(0).toString(16).padStart(4,"0")}`)}var H={web:"Pathrule Web",desktop:"Pathrule Desktop",cli:"Pathrule CLI"},nt={web:"Pathrule in your browser. Manage cloud content from anywhere.",desktop:"The complete Pathrule app for macOS, Windows, and Linux.",cli:"Pathrule from your terminal. Headless, scriptable, fast."};var Yf=["event_name","schema_version","occurred_at","surface","host_kind","app_version","os_family","country_iso","pseudonymous_install_id","session_local_id","duration_ms","result","blocking_reason","feature_tag"];function bl(t){let e=new Set(Yf);for(let r of Object.keys(t))if(!e.has(r))throw new Error(`telemetry_field_not_allowed:${r}`)}var Xf=[{match:t=>t.some(e=>/^next\.config\.(js|mjs|ts)$/.test(ce(e))),title:"Next.js project",content:"This workspace uses Next.js as its React framework."},{match:t=>t.some(e=>/^nuxt\.config\.(js|ts)$/.test(ce(e))),title:"Nuxt project",content:"This workspace uses Nuxt as its Vue framework."},{match:t=>t.some(e=>/^tailwind\.config\.(js|mjs|ts|cjs)$/.test(ce(e))),title:"Uses Tailwind CSS",content:"This workspace uses Tailwind CSS for styling."},{match:t=>t.some(e=>/^vite\.config\.(js|ts|mjs)$/.test(ce(e))),title:"Vite build tool",content:"This workspace uses Vite as the build tool / dev server."},{match:t=>{let e=t.filter(n=>n.endsWith("/package.json")||n==="package.json"),r=t.some(n=>n.startsWith("packages/")||n.startsWith("apps/"));return e.length>2&&r},title:"Monorepo structure",content:"This workspace is a monorepo with multiple packages/apps, each with its own package.json."},{match:t=>t.some(e=>ce(e)==="Podfile"||e.endsWith(".xcodeproj")),title:"iOS/macOS native project",content:"This workspace contains iOS/macOS native code (Xcode project or CocoaPods)."},{match:t=>t.some(e=>ce(e)==="pubspec.yaml"),title:"Flutter project",content:"This workspace is a Flutter/Dart project."},{match:t=>t.some(e=>ce(e)==="Cargo.toml"),title:"Rust project",content:"This workspace contains Rust code (Cargo-managed)."},{match:t=>t.some(e=>ce(e)==="go.mod"),title:"Go project",content:"This workspace is a Go module."},{match:t=>t.some(e=>/^tsconfig(\.\w+)?\.json$/.test(ce(e))),title:"TypeScript project",content:"This workspace uses TypeScript."},{match:t=>t.some(e=>ce(e)==="docker-compose.yml"||ce(e)==="docker-compose.yaml"||ce(e)==="Dockerfile"),title:"Docker containerization",content:"This workspace uses Docker for containerization."},{match:t=>t.some(e=>e.startsWith(".github/workflows/")),title:"GitHub Actions CI/CD",content:"This workspace uses GitHub Actions for CI/CD."}];function ce(t){let e=t.split("/");return e[e.length-1]??t}function ps(t){return Xf.filter(e=>e.match(t)).map(e=>({title:e.title,content:e.content}))}function hs(t){let e=new Map,r=0,n=t.split("---").filter(i=>i.trim().length>0);for(let i of n){if(r>=1e4)break;r++;let s=i.split(`
73
- `).map(o=>o.trim()).filter(o=>o.length>0&&!o.startsWith("commit ")&&!o.startsWith("Author:"));if(!(s.length>20||s.length<2))for(let o=0;o<s.length;o++)for(let a=o+1;a<s.length;a++){let l=s[o],c=s[a],[u,d]=l<c?[l,c]:[c,l],p=`${u}\0${d}`;e.set(p,(e.get(p)??0)+1);}}return [...e.entries()].map(([i,s])=>{let[o,a]=i.split("\0");return {path_a:o,path_b:a,weight:s}}).sort((i,s)=>s.weight-i.weight).slice(0,1e4)}var U={"claude-code":{id:"claude-code",label:"Claude Code",skillsDir:".claude/skills",detectFile:".claude",supported:true},cursor:{id:"cursor",label:"Cursor",skillsDir:".cursor/skills",detectFile:".cursor",supported:true},windsurf:{id:"windsurf",label:"Windsurf",skillsDir:".windsurf/skills",detectFile:".windsurf",supported:true},codex:{id:"codex",label:"Codex",skillsDir:".codex/skills",detectFile:".codex",supported:true}},Pn=["claude-code"];function fs(t){return U[t]??null}function vl(t){let e=[];for(let r of t){let n=fs(r);n&&n.supported&&e.push(n);}return e}var Zf="skill";function Tn(t){let e=(t||"").toLowerCase().normalize("NFKD").replace(/[\u0300-\u036f]/g,"").replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"");return e?e.slice(0,80):Zf}function Sl(t,e){let r=Tn(t),n=e.replace(/-/g,"").slice(0,8);return `${r}-${n}`}var Cl="[redacted]",Qf="[redacted-email]",gs="[redacted-path]",eg=/(authorization|password|secret|token|api[_-]?key|access[_-]?token|refresh[_-]?token|pair[_-]?token|session|cookie|env|environment|cache|content|body|file[_-]?content)/i,tg=/(^|[_-])(path|paths|cwd|directory|root|repo|local_root|workspace_root)([_-]|$)/i,rg=/\b(?:Bearer\s+)?[A-Za-z0-9._~+/=-]{24,}\b/g,ng=/\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}\b/gi,ig=/(?:~|\/Users\/[^/\s]+|\/home\/[^/\s]+|\/var\/folders\/[^\s"']+|\/tmp\/[^\s"']+)/g,sg=/[A-Za-z]:\\(?:[^\\\s"']+\\?)+/g;function ms(t,e=""){return t&&(ag(e)?gs:og(e)?Cl:t.replace(ng,Qf).replace(ig,gs).replace(sg,gs).replace(rg,Cl))}function El(t){let e=JSON.stringify(t),r=[/Bearer\s+[A-Za-z0-9._~+/=-]+/i,/access[_-]?token["':\s]+[A-Za-z0-9._~+/=-]{8,}/i,/refresh[_-]?token["':\s]+[A-Za-z0-9._~+/=-]{8,}/i,/pair[_-]?token["':\s]+[A-Za-z0-9._~+/=-]{8,}/i,/\/Users\/[^/"']+/,/\/home\/[^/"']+/,/[A-Za-z]:\\[^"']+/];for(let n of r)if(n.test(e))throw new Error(`support bundle contains sensitive material matching ${n}`)}function og(t){return eg.test(t)}function ag(t){return tg.test(t)}var qe={free:{workspaces:1,memories:50,rules:50,seatsExtra:0,basePriceMonthly:0,basePriceYearly:0,perSeatMonthly:0},starter:{workspaces:3,memories:2500,rules:2500,seatsExtra:-1,basePriceMonthly:12,basePriceYearly:10,perSeatMonthly:6},pro:{workspaces:-1,memories:1e4,rules:1e4,seatsExtra:-1,basePriceMonthly:24,basePriceYearly:20,perSeatMonthly:6},business:{workspaces:-1,memories:5e4,rules:5e4,seatsExtra:-1,basePriceMonthly:48,basePriceYearly:40,perSeatMonthly:6},enterprise:{workspaces:-1,memories:-1,rules:-1,seatsExtra:-1,basePriceMonthly:0,basePriceYearly:0,perSeatMonthly:0}};function Rl(t,e){if(!t)return {failure:{error:"organization_not_found"},billingImpact:An(),billingRequirement:null};if(t.plan==="free")return {failure:{error:"free_plan_invites_disabled"},billingImpact:An(),billingRequirement:null};if(["past_due","unpaid","canceled"].includes(t.subscription_status??""))return {failure:{error:"subscription_not_invitable"},billingImpact:An(),billingRequirement:null};if(t.trial_status==="active"&&t.trial_seat_cap){let r=e+1,n=t.paid_extra_seats??0,i=t.trial_seat_cap+n,s=r>t.trial_seat_cap,o=Math.max(0,r-t.trial_seat_cap),a={seat_effect:s?r>i?"paid_extra_required":"paid_extra_available":"included",may_use_paid_extra_seat:s,active_seats_before:e,target_active_seats:r,included_seat_cap:t.trial_seat_cap,current_paid_extra_seats:n,required_paid_extra_seats:o};return r>i?{failure:null,billingImpact:a,billingRequirement:{targetSeats:r,requiredPaidExtraSeats:o,giftSeatCap:t.trial_seat_cap,currentPaidExtraSeats:n}}:{failure:null,billingImpact:a,billingRequirement:null}}return {failure:null,billingImpact:An(),billingRequirement:null}}function An(){return {seat_effect:"not_applicable",may_use_paid_extra_seat:false}}K();var fg={"claude-code":["CLAUDE.md",".claude/rules/pathrule-protocol.md",".claude/settings.json"],cursor:[".cursorrules",".cursor/rules/pathrule-protocol.mdc",".cursor/hooks.json"],codex:["codex.md","AGENTS.md",".codex/hooks.json",".codex/config.toml"],windsurf:[".windsurfrules",".windsurf/rules/pathrule-protocol.md"]};async function gg(t){try{return await access(t,constants.F_OK),!0}catch{return false}}async function ze(t){let e=Object.keys(U);return (await Promise.all(e.map(async n=>{for(let i of fg[n])if(await gg(join(t,i)))return n;return null}))).filter(n=>n!==null)}function In(t){let e=new Set(Object.keys(U)),r=(t.selected??[]).filter(n=>typeof n=="string"&&e.has(n));return r.length>0?r:t.detected.length>0?[...t.detected]:[...t.fallback]}li();Gr();F();var U_=new Map([["-h","--help"],["-v","--version"]]);function bu(t,e=process.env){let r=[],n={json:false,yes:false,noOpen:false,deviceCode:false,browserCallback:false,help:false,version:false,color:e.NO_COLOR!=="1"&&e.NO_COLOR!=="true",interactive:e.CI!=="true"};for(let o of t)switch(U_.get(o)??o){case "--json":n.json=true,n.color=false,n.interactive=false;break;case "--yes":n.yes=true;break;case "--no-open":n.noOpen=true;break;case "--device-code":n.deviceCode=true;break;case "--browser-callback":n.browserCallback=true;break;case "--help":n.help=true;break;case "--version":n.version=true;break;case "--no-color":n.color=false;break;default:r.push(o);break}let i=W_(r);return {command:i[0]??"help",positional:i,flags:n}}function W_(t){let e=t[0],r=t[1];return !e?.startsWith("/")||!r||!["memory","rule","skill","search"].includes(r)?t:[r,...t.slice(2),e]}Ge();F();K();var H_=randomUUID(),q_=20,z_=1500;function Ru(t){return t==="telemetry.enabled"||t==="telemetry.id"}async function xu(t,e){if(t==="telemetry.enabled")return oo(e,await ao(e));let r=await pi(e);return {key:t,value:r.pseudonymous_install_id,source:"config",configurable:true}}async function Pu(t,e){let r=X_(t);if(r===null)throw new Error("invalid_telemetry_enabled");let n=await pi(e);return await lo({...n,telemetry_enabled:r},e),oo(e,{...n,telemetry_enabled:r})}async function Tu(t){let r={...await pi(t),pseudonymous_install_id:randomUUID()};return await lo(r,t),{key:"telemetry.id",value:r.pseudonymous_install_id,source:"config",configurable:true}}async function Xr(t,e){let r=oo(t,await ao(t));if(!r.value)return {recorded:false,reason:r.source};let n=await pi(t),i={event_name:e.eventName,schema_version:1,occurred_at:new Date().toISOString(),surface:"cli",host_kind:"cli-bridge",app_version:e.appVersion,os_family:process.platform,pseudonymous_install_id:n.pseudonymous_install_id,session_local_id:H_,result:e.result,...typeof e.durationMs=="number"?{duration_ms:e.durationMs}:{},...e.blockingReason?{blocking_reason:e.blockingReason}:{},...e.featureTag?{feature_tag:e.featureTag}:{}};bl(i),Z_(i);let s=Iu(t);return await mkdir(dirname(s),{recursive:true,mode:D}),await chmod(dirname(s),D).catch(()=>{}),await appendFile(s,`${JSON.stringify(i)}
74
- `,{encoding:"utf8",mode:O}),await chmod(s,O).catch(()=>{}),await G_(t).catch(()=>{}),{recorded:true}}async function so(t,e){try{let r=J_(e.command,e.exitCode),n=e.exitCode===0?"ok":e.exitCode===64?"blocked":"failed";r&&await Xr(t,{eventName:r,result:n,appVersion:e.appVersion,durationMs:e.durationMs,featureTag:K_(e.command),blockingReason:e.exitCode===64?"usage_or_preflight_blocked":void 0});let i=V_(e.command,e.exitCode);i&&await Xr(t,{eventName:"dead_end_seen",result:"blocked",appVersion:e.appVersion,durationMs:e.durationMs,featureTag:i.featureTag,blockingReason:i.blockingReason});}catch{}}function J_(t,e){switch(t){case "help":case "version":case "status":return "surface_viewed";case "setup":return e===0?"cli_setup_completed":"cli_setup_started";case "doctor":return e===0?null:"cli_doctor_failed";case "bridge":return e===0?"cli_bridge_pair_succeeded":"cli_bridge_pair_started";case "sync":return e===0?"agent_sync_succeeded":null;case "billing":case "team":case "upgrade":case "reactivate":case "open":return "web_admin_route_opened_from_cli";case "preflight":return e===0?null:"cli_preflight_blocked";default:return null}}function K_(t){return t==="bridge"?"cli_bridge":t==="setup"?"cli_setup":t==="doctor"?"cli_doctor":t==="sync"?"agent_sync":["billing","team","upgrade","reactivate","open"].includes(t)?"web_route":t==="preflight"?"preflight":"surface"}function V_(t,e){return e===0?null:t==="doctor"?{featureTag:"cli_doctor",blockingReason:"doctor_cannot_repair"}:t==="preflight"?{featureTag:"preflight",blockingReason:"preflight_blocked"}:t==="setup"?{featureTag:"cli_setup",blockingReason:"cli_setup_incomplete"}:t==="bridge"?{featureTag:"cli_bridge",blockingReason:"bridge_pair_failed"}:["billing","team","upgrade","reactivate","open"].includes(t)?{featureTag:"web_route",blockingReason:"web_route_not_opened"}:null}function oo(t,e){return t.CI==="true"?{key:"telemetry.enabled",value:false,source:"ci",configurable:false}:t.NO_TELEMETRY==="1"?{key:"telemetry.enabled",value:false,source:"env",configurable:false}:typeof e?.telemetry_enabled=="boolean"?{key:"telemetry.enabled",value:e.telemetry_enabled,source:"config",configurable:true}:{key:"telemetry.enabled",value:true,source:"default",configurable:true}}async function pi(t){let e=await ao(t);if(e)return e;let r={schema_version:1,pseudonymous_install_id:randomUUID()};return await lo(r,t),r}async function ao(t){try{let e=JSON.parse(await readFile(Au(t),"utf8"));if(e&&typeof e=="object"&&e.schema_version===1&&typeof e.pseudonymous_install_id=="string")return e}catch(e){if(e.code!=="ENOENT")throw e}return null}async function lo(t,e){let r=Au(e);await mkdir(dirname(r),{recursive:true,mode:D}),await chmod(dirname(r),D).catch(()=>{});let n=`${r}.tmp`;await writeFile(n,JSON.stringify(t,null,2),{encoding:"utf8",mode:O}),await chmod(n,O).catch(()=>{}),await rename(n,r);}function Au(t){return join(A(t).home,"telemetry.json")}function Iu(t){return join(A(t).logsDir,"telemetry-events.jsonl")}async function G_(t){let e=Y_(t);if(!e)return;let r=Iu(t),n;try{n=(await readFile(r,"utf8")).split(`
73
+ `).map(o=>o.trim()).filter(o=>o.length>0&&!o.startsWith("commit ")&&!o.startsWith("Author:"));if(!(s.length>20||s.length<2))for(let o=0;o<s.length;o++)for(let a=o+1;a<s.length;a++){let l=s[o],c=s[a],[u,d]=l<c?[l,c]:[c,l],p=`${u}\0${d}`;e.set(p,(e.get(p)??0)+1);}}return [...e.entries()].map(([i,s])=>{let[o,a]=i.split("\0");return {path_a:o,path_b:a,weight:s}}).sort((i,s)=>s.weight-i.weight).slice(0,1e4)}var U={"claude-code":{id:"claude-code",label:"Claude Code",skillsDir:".claude/skills",detectFile:".claude",supported:true},cursor:{id:"cursor",label:"Cursor",skillsDir:".cursor/skills",detectFile:".cursor",supported:true},windsurf:{id:"windsurf",label:"Windsurf",skillsDir:".windsurf/skills",detectFile:".windsurf",supported:true},codex:{id:"codex",label:"Codex",skillsDir:".codex/skills",detectFile:".codex",supported:true}},Pn=["claude-code"];function fs(t){return U[t]??null}function vl(t){let e=[];for(let r of t){let n=fs(r);n&&n.supported&&e.push(n);}return e}var Zf="skill";function Tn(t){let e=(t||"").toLowerCase().normalize("NFKD").replace(/[\u0300-\u036f]/g,"").replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"");return e?e.slice(0,80):Zf}function Sl(t,e){let r=Tn(t),n=e.replace(/-/g,"").slice(0,8);return `${r}-${n}`}var Cl="[redacted]",Qf="[redacted-email]",gs="[redacted-path]",eg=/(authorization|password|secret|token|api[_-]?key|access[_-]?token|refresh[_-]?token|pair[_-]?token|session|cookie|env|environment|cache|content|body|file[_-]?content)/i,tg=/(^|[_-])(path|paths|cwd|directory|root|repo|local_root|workspace_root)([_-]|$)/i,rg=/\b(?:Bearer\s+)?[A-Za-z0-9._~+/=-]{24,}\b/g,ng=/\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}\b/gi,ig=/(?:~|\/Users\/[^/\s]+|\/home\/[^/\s]+|\/var\/folders\/[^\s"']+|\/tmp\/[^\s"']+)/g,sg=/[A-Za-z]:\\(?:[^\\\s"']+\\?)+/g;function ms(t,e=""){return t&&(ag(e)?gs:og(e)?Cl:t.replace(ng,Qf).replace(ig,gs).replace(sg,gs).replace(rg,Cl))}function El(t){let e=JSON.stringify(t),r=[/Bearer\s+[A-Za-z0-9._~+/=-]+/i,/access[_-]?token["':\s]+[A-Za-z0-9._~+/=-]{8,}/i,/refresh[_-]?token["':\s]+[A-Za-z0-9._~+/=-]{8,}/i,/pair[_-]?token["':\s]+[A-Za-z0-9._~+/=-]{8,}/i,/\/Users\/[^/"']+/,/\/home\/[^/"']+/,/[A-Za-z]:\\[^"']+/];for(let n of r)if(n.test(e))throw new Error(`support bundle contains sensitive material matching ${n}`)}function og(t){return eg.test(t)}function ag(t){return tg.test(t)}var qe={free:{workspaces:1,memories:50,rules:50,seatsExtra:0,basePriceMonthly:0,basePriceYearly:0,perSeatMonthly:0},starter:{workspaces:3,memories:2500,rules:2500,seatsExtra:-1,basePriceMonthly:12,basePriceYearly:10,perSeatMonthly:6},pro:{workspaces:-1,memories:1e4,rules:1e4,seatsExtra:-1,basePriceMonthly:24,basePriceYearly:20,perSeatMonthly:6},business:{workspaces:-1,memories:5e4,rules:5e4,seatsExtra:-1,basePriceMonthly:48,basePriceYearly:40,perSeatMonthly:6},enterprise:{workspaces:-1,memories:-1,rules:-1,seatsExtra:-1,basePriceMonthly:0,basePriceYearly:0,perSeatMonthly:0}};function Rl(t,e){if(!t)return {failure:{error:"organization_not_found"},billingImpact:An(),billingRequirement:null};if(t.plan==="free")return {failure:{error:"free_plan_invites_disabled"},billingImpact:An(),billingRequirement:null};if(["past_due","unpaid","canceled"].includes(t.subscription_status??""))return {failure:{error:"subscription_not_invitable"},billingImpact:An(),billingRequirement:null};if(t.trial_status==="active"&&t.trial_seat_cap){let r=e+1,n=t.paid_extra_seats??0,i=t.trial_seat_cap+n,s=r>t.trial_seat_cap,o=Math.max(0,r-t.trial_seat_cap),a={seat_effect:s?r>i?"paid_extra_required":"paid_extra_available":"included",may_use_paid_extra_seat:s,active_seats_before:e,target_active_seats:r,included_seat_cap:t.trial_seat_cap,current_paid_extra_seats:n,required_paid_extra_seats:o};return r>i?{failure:null,billingImpact:a,billingRequirement:{targetSeats:r,requiredPaidExtraSeats:o,giftSeatCap:t.trial_seat_cap,currentPaidExtraSeats:n}}:{failure:null,billingImpact:a,billingRequirement:null}}return {failure:null,billingImpact:An(),billingRequirement:null}}function An(){return {seat_effect:"not_applicable",may_use_paid_extra_seat:false}}K();var fg={"claude-code":["CLAUDE.md",".claude/rules/pathrule-protocol.md",".claude/settings.json"],cursor:[".cursorrules",".cursor/rules/pathrule-protocol.mdc",".cursor/hooks.json"],codex:["codex.md","AGENTS.md",".codex/hooks.json",".codex/config.toml"],windsurf:[".windsurfrules",".windsurf/rules/pathrule-protocol.md"]};async function gg(t){try{return await access(t,constants.F_OK),!0}catch{return false}}async function ze(t){let e=Object.keys(U);return (await Promise.all(e.map(async n=>{for(let i of fg[n])if(await gg(join(t,i)))return n;return null}))).filter(n=>n!==null)}function In(t){let e=new Set(Object.keys(U)),r=(t.selected??[]).filter(n=>typeof n=="string"&&e.has(n));return r.length>0?r:t.detected.length>0?[...t.detected]:[...t.fallback]}li();Gr();F();var U_=new Map([["-h","--help"],["-v","--version"]]);function bu(t,e=process.env){let r=[],n={json:false,yes:false,noOpen:false,deviceCode:false,browserCallback:false,help:false,version:false,color:e.NO_COLOR!=="1"&&e.NO_COLOR!=="true",interactive:e.CI!=="true"};for(let o of t)switch(U_.get(o)??o){case "--json":n.json=true,n.color=false,n.interactive=false;break;case "--yes":n.yes=true;break;case "--no-open":n.noOpen=true;break;case "--device-code":n.deviceCode=true;break;case "--browser-callback":n.browserCallback=true;break;case "--help":n.help=true;break;case "--version":n.version=true;break;case "--no-color":n.color=false;break;default:r.push(o);break}let i=W_(r);return {command:i[0]??"help",positional:i,flags:n}}function W_(t){let e=t[0],r=t[1];return !e?.startsWith("/")||!r||!["memory","rule","skill","search"].includes(r)?t:[r,...t.slice(2),e]}Ge();F();K();var H_=randomUUID(),q_=20,z_=1500;function Ru(t){return t==="telemetry.enabled"||t==="telemetry.id"}async function xu(t,e){if(t==="telemetry.enabled")return oo(e,await ao(e));let r=await pi(e);return {key:t,value:r.pseudonymous_install_id,source:"config",configurable:true}}async function Pu(t,e){let r=X_(t);if(r===null)throw new Error("invalid_telemetry_enabled");let n=await pi(e);return await lo({...n,telemetry_enabled:r},e),oo(e,{...n,telemetry_enabled:r})}async function Tu(t){let r={...await pi(t),pseudonymous_install_id:randomUUID()};return await lo(r,t),{key:"telemetry.id",value:r.pseudonymous_install_id,source:"config",configurable:true}}async function Xr(t,e){let r=oo(t,await ao(t));if(!r.value)return {recorded:false,reason:r.source};let n=await pi(t),i={event_name:e.eventName,schema_version:1,occurred_at:new Date().toISOString(),surface:"cli",host_kind:"cli-bridge",app_version:e.appVersion,os_family:process.platform,pseudonymous_install_id:n.pseudonymous_install_id,session_local_id:H_,result:e.result,...typeof e.durationMs=="number"?{duration_ms:e.durationMs}:{},...e.blockingReason?{blocking_reason:e.blockingReason}:{},...e.featureTag?{feature_tag:e.featureTag}:{}};bl(i),Z_(i);let s=Iu(t);return await mkdir(dirname(s),{recursive:true,mode:j}),await chmod(dirname(s),j).catch(()=>{}),await appendFile(s,`${JSON.stringify(i)}
74
+ `,{encoding:"utf8",mode:O}),await chmod(s,O).catch(()=>{}),await G_(t).catch(()=>{}),{recorded:true}}async function so(t,e){try{let r=J_(e.command,e.exitCode),n=e.exitCode===0?"ok":e.exitCode===64?"blocked":"failed";r&&await Xr(t,{eventName:r,result:n,appVersion:e.appVersion,durationMs:e.durationMs,featureTag:K_(e.command),blockingReason:e.exitCode===64?"usage_or_preflight_blocked":void 0});let i=V_(e.command,e.exitCode);i&&await Xr(t,{eventName:"dead_end_seen",result:"blocked",appVersion:e.appVersion,durationMs:e.durationMs,featureTag:i.featureTag,blockingReason:i.blockingReason});}catch{}}function J_(t,e){switch(t){case "help":case "version":case "status":return "surface_viewed";case "setup":return e===0?"cli_setup_completed":"cli_setup_started";case "doctor":return e===0?null:"cli_doctor_failed";case "bridge":return e===0?"cli_bridge_pair_succeeded":"cli_bridge_pair_started";case "sync":return e===0?"agent_sync_succeeded":null;case "billing":case "team":case "upgrade":case "reactivate":case "open":return "web_admin_route_opened_from_cli";case "preflight":return e===0?null:"cli_preflight_blocked";default:return null}}function K_(t){return t==="bridge"?"cli_bridge":t==="setup"?"cli_setup":t==="doctor"?"cli_doctor":t==="sync"?"agent_sync":["billing","team","upgrade","reactivate","open"].includes(t)?"web_route":t==="preflight"?"preflight":"surface"}function V_(t,e){return e===0?null:t==="doctor"?{featureTag:"cli_doctor",blockingReason:"doctor_cannot_repair"}:t==="preflight"?{featureTag:"preflight",blockingReason:"preflight_blocked"}:t==="setup"?{featureTag:"cli_setup",blockingReason:"cli_setup_incomplete"}:t==="bridge"?{featureTag:"cli_bridge",blockingReason:"bridge_pair_failed"}:["billing","team","upgrade","reactivate","open"].includes(t)?{featureTag:"web_route",blockingReason:"web_route_not_opened"}:null}function oo(t,e){return t.CI==="true"?{key:"telemetry.enabled",value:false,source:"ci",configurable:false}:t.NO_TELEMETRY==="1"?{key:"telemetry.enabled",value:false,source:"env",configurable:false}:typeof e?.telemetry_enabled=="boolean"?{key:"telemetry.enabled",value:e.telemetry_enabled,source:"config",configurable:true}:{key:"telemetry.enabled",value:true,source:"default",configurable:true}}async function pi(t){let e=await ao(t);if(e)return e;let r={schema_version:1,pseudonymous_install_id:randomUUID()};return await lo(r,t),r}async function ao(t){try{let e=JSON.parse(await readFile(Au(t),"utf8"));if(e&&typeof e=="object"&&e.schema_version===1&&typeof e.pseudonymous_install_id=="string")return e}catch(e){if(e.code!=="ENOENT")throw e}return null}async function lo(t,e){let r=Au(e);await mkdir(dirname(r),{recursive:true,mode:j}),await chmod(dirname(r),j).catch(()=>{});let n=`${r}.tmp`;await writeFile(n,JSON.stringify(t,null,2),{encoding:"utf8",mode:O}),await chmod(n,O).catch(()=>{}),await rename(n,r);}function Au(t){return join(A(t).home,"telemetry.json")}function Iu(t){return join(A(t).logsDir,"telemetry-events.jsonl")}async function G_(t){let e=Y_(t);if(!e)return;let r=Iu(t),n;try{n=(await readFile(r,"utf8")).split(`
75
75
  `).filter(Boolean);}catch(a){if(a.code==="ENOENT")return;throw a}if(n.length===0)return;let i=n.slice(0,q_).map(a=>JSON.parse(a)),s=new AbortController,o=setTimeout(()=>s.abort(),z_);try{let a=await fetch(e.url,{method:"POST",headers:{"Content-Type":"application/json",apikey:e.anonKey,Authorization:`Bearer ${e.anonKey}`},body:JSON.stringify({events:i}),signal:s.signal});if(!a.ok)return;let l=await a.json().catch(()=>null),c=typeof l?.accepted=="number"?l.accepted:i.length,u=Math.max(0,Math.min(c,i.length)),d=n.slice(u).join(`
76
76
  `);await writeFile(r,d?`${d}
77
- `:"",{encoding:"utf8",mode:O}),await chmod(r,O).catch(()=>{});}finally{clearTimeout(o);}}function Y_(t){let e=t.SUPABASE_URL??t.VITE_SUPABASE_URL,r=t.SUPABASE_ANON_KEY??t.VITE_SUPABASE_ANON_KEY;return !e||!r?null:{url:`${e.replace(/\/$/,"")}/functions/v1/telemetry-ingest`,anonKey:r}}function X_(t){if(!t)return null;let e=t.toLowerCase().trim();return e==="true"?true:e==="false"?false:null}function Z_(t){let e=JSON.stringify(t),r=[/[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}/i,/(?:^|["\s])\/Users\/[^"\s]+/,/(?:^|["\s])\/home\/[^"\s]+/,/[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}/,/ghp_[A-Za-z0-9_]{20,}/];for(let n of r)if(n.test(e))throw new Error(`telemetry_payload_contains_sensitive_material:${n}`)}var Q_=new Set(["manual","notify","auto"]);function $u(t,e){if(t.CI==="true"||t.NO_UPDATE_CHECK==="1")return {key:"update.policy",value:"manual",source:"ci",configurable:false};let r=co(t.PATHRULE_UPDATE_POLICY);if(r)return {key:"update.policy",value:r,source:"env",configurable:false};let n=co(e);return n?{key:"update.policy",value:n,source:"config",configurable:true}:{key:"update.policy",value:"notify",source:"default",configurable:true}}function Nu(t){return typeof t=="boolean"?{key:"suggestions.desktop",value:t,source:"config",configurable:true}:{key:"suggestions.desktop",value:true,source:"default",configurable:true}}async function kt(t,e){if(Ru(t))return xu(t,e);if(t!=="update.policy"&&t!=="suggestions.desktop")throw new Error("unsupported_config_key");try{let{session:r}=await C(e),n=await ne(r.user.id,e);return Ou(t,e,n)}catch{return Ou(t,e)}}async function uo(t,e,r){if(t==="telemetry.enabled")return Pu(e,r);if(t==="telemetry.id")throw new Error("use_config_reset_telemetry_id");if(t!=="update.policy"&&t!=="suggestions.desktop")throw new Error("unsupported_config_key");let{session:n}=await C(r);if(t==="update.policy"){let s=co(e);if(!s)throw new Error("invalid_update_policy");return await ie(n.user.id,{update_policy:s},r),$u(r,s)}let i=ew(e);if(i===null)throw new Error("invalid_desktop_suggestions");return await ie(n.user.id,{desktop_suggestions:i},r),Nu(i)}async function po(t,e){if(t==="telemetry-id"||t==="telemetry.id")return Tu(e);throw new Error("unsupported_config_reset_key")}function co(t){if(!t)return null;let e=t.toLowerCase().trim();return Q_.has(e)?e:null}function ew(t){if(!t)return null;let e=t.toLowerCase().trim();return e==="true"?true:e==="false"?false:null}function Ou(t,e,r){return t==="update.policy"?$u(e,r?.update_policy):Nu(r?.desktop_suggestions)}Ge();F();Ee();async function Re(t){let{session:e,supabase:r}=await C(t),n=await j(t);if(!n)return [];let{data:i,error:s}=await r.from("workspaces").select("id, organization_id, name, access_mode, git_remote_url, git_owner, git_repo, user_workspace_paths!left(local_root_path, user_id)").eq("organization_id",n.id).is("archived_at",null);if(s)throw s;let o=await ne(e.user.id,t),a=[];for(let l of i??[]){let u=(l.user_workspace_paths??[]).find(d=>d.user_id===e.user.id)??null;a.push({id:l.id,organization_id:l.organization_id,name:l.name,access_mode:l.access_mode,git_remote_url:l.git_remote_url,git_owner:l.git_owner,git_repo:l.git_repo,local_root_path:u?.local_root_path??null,current:o.current_workspace_id===l.id});}if(a.sort((l,c)=>l.name.localeCompare(c.name)),!o.current_workspace_id&&a.length===1){let l=a[0];l&&(a[0]={...l,current:true});}return a}async function M(t){let e=await Re(t),r=e.find(n=>n.current);return r||(e.length===1?e[0]??null:null)}async function Zr(t,e){let{session:r}=await C(e),i=(await Re(e)).find(s=>s.id===t||s.name===t);if(!i)throw new Error("workspace_not_found");return await ie(r.user.id,{current_workspace_id:i.id},e),{...i,current:true}}async function bt(t,e,r){let{session:n,supabase:i}=await C(r),s=await j(r);if(!s)throw new Error("org_required");let o=ds(t,"workspace");if(!o.ok||!o.value)throw new Error(`unsafe_workspace_name:${o.reason??"invalid"}`);let{data:a,error:l}=await i.from("workspaces").insert({organization_id:s.id,name:o.value,access_mode:"organization",git_remote_url:null,git_provider:null,git_owner:null,git_repo:null,detected_at:null}).select("id, organization_id, name, access_mode").single();if(l||!a)throw new Error(l?.message??"workspace_create_failed");let{error:c}=await i.from("user_workspace_paths").insert({user_id:n.user.id,workspace_id:a.id,local_root_path:e,watcher_enabled:true});if(c)throw new Error(c.message);let u=await Qi(i,a.id,o.value);return await ie(n.user.id,{current_org_id:s.id,current_workspace_id:a.id},r),{workspace:{id:a.id,organization_id:a.organization_id,name:a.name,access_mode:a.access_mode,local_root_path:e,current:true},local_root_path:e,root_node_created:!("error"in u)}}async function xe(t,e,r){let{session:n,supabase:i}=await C(r),s=t?await Du(t,r):await M(r);if(!s)throw new Error("workspace_required");let{error:o}=await i.from("user_workspace_paths").upsert({user_id:n.user.id,workspace_id:s.id,local_root_path:e,watcher_enabled:true},{onConflict:"user_id,workspace_id"});if(o)throw o;return await ie(n.user.id,{current_org_id:s.organization_id,current_workspace_id:s.id},r),{workspace:{...s,local_root_path:e,current:true},local_root_path:e,previous_local_root_path:s.local_root_path}}async function Qr(t,e){let{session:r,supabase:n}=await C(e),i=t?await Du(t,e):await M(e);if(!i)throw new Error("workspace_required");let{error:s}=await n.from("user_workspace_paths").delete().eq("user_id",r.user.id).eq("workspace_id",i.id);if(s)throw s;return {...i,local_root_path:null}}async function Du(t,e){let n=(await Re(e)).find(i=>i.id===t||i.name===t);if(!n)throw new Error("workspace_not_found");return n}F();function Mu(t,e=false){return e?true:t.length<=1200&&t.split(/\r?\n/).length<=24}function Lu(t,e={}){if(e.forceWeb)return {...t.open_targets.find(r=>r.kind==="web"),reason:"forced"};if(e.preferDesktopApp){let r=t.open_targets.find(n=>n.kind==="desktop-app");return r||{...t.open_targets.find(n=>n.kind==="web"),reason:"fallback"}}return t.open_targets[0]??{kind:"web",url:t.url,label:`Open ${t.kind} in Pathrule Web`,reason:"preferred"}}async function en(t,e,r={}){let n=await nw(e),{supabase:i}=await C(e),s=go(r.limit),o=lw(r.path);if(t==="memory"){let{data:c,error:u}=await i.from("memories").select("id, title, content, updated_at, nodes(id, relative_path)").eq("workspace_id",n.id).eq("status","active").order("updated_at",{ascending:false}).limit(s*3);if(u)throw u;return (c??[]).map(d=>ho("memory",n.id,d,e)).filter(d=>fo(d.path,o)).slice(0,s)}if(t==="rule"){let{data:c,error:u}=await i.from("rules").select("id, name, content, updated_at, node_rules(nodes(id, relative_path))").eq("workspace_id",n.id).order("updated_at",{ascending:false}).limit(s*3);if(u)throw u;return (c??[]).map(d=>ho("rule",n.id,d,e)).filter(d=>fo(d.path,o)).slice(0,s)}let{data:a,error:l}=await i.from("skills").select("id, name, description, content, updated_at, node_skills(nodes!node_skills_node_id_fkey(id, relative_path))").eq("workspace_id",n.id).order("updated_at",{ascending:false}).limit(s*3);if(l)throw l;return (a??[]).map(c=>ho("skill",n.id,c,e)).filter(c=>fo(c.path,o)).slice(0,s)}async function mo(t,e,r={}){let n=t.trim().toLowerCase();if(!n)throw new Error("search_query_required");let i=r.types?.length?r.types:["memory","rule","skill"];return (await Promise.all(i.map(o=>en(o,e,{path:r.path,limit:Math.max(go(r.limit),50)})))).flat().map(o=>({item:o,score:cw(o,n)})).filter(o=>o.score>0).sort((o,a)=>a.score-o.score||(a.item.updated_at??"").localeCompare(o.item.updated_at??"")).slice(0,go(r.limit)).map(o=>o.item)}async function _o(t,e,r){let n=await en(t,r,{limit:100}),i=e.toLowerCase(),s=n.find(d=>d.id===e||d.title.toLowerCase()===i);if(!s)throw new Error(`${t}_not_found`);let{supabase:o}=await C(r),a=t==="memory"?"memories":t==="rule"?"rules":"skills",{data:l,error:c}=await o.from(a).select("content").eq("id",s.id).maybeSingle();if(c)throw c;let u=typeof l?.content=="string"?l.content:"";return {...s,content:u}}function vt(t,e,r,n,i){let s=(n.PATHRULE_WEB_URL??"https://app.pathrule.io").replace(/\/$/,"");return i?`${s}/workspace/${encodeURIComponent(t)}/node/${encodeURIComponent(i)}/${e}/${encodeURIComponent(r)}`:`${s}/workspace/${encodeURIComponent(t)}/${e}/${encodeURIComponent(r)}`}function rw(t,e,r,n){let i=n?`/node/${encodeURIComponent(n)}`:"";return `pathrule://workspace/${encodeURIComponent(t)}${i}/${e}/${encodeURIComponent(r)}`}async function nw(t){let e=await M(t);if(!e)throw new Error("workspace_required");return e}function ho(t,e,r,n){let i=typeof r.title=="string"?r.title:typeof r.name=="string"?r.name:String(r.id),s=typeof r.content=="string"?r.content:typeof r.description=="string"?r.description:"",o=ow(t,r),a=aw(t,r),l=vt(e,t,String(r.id),n,a);return {id:String(r.id),kind:t,title:i,path:o,node_id:a,preview:uw(s),updated_at:typeof r.updated_at=="string"?r.updated_at:null,url:l,open_targets:[iw(e,t,String(r.id),n,a),sw(e,t,String(r.id),a)]}}function iw(t,e,r,n,i){return {kind:"web",url:vt(t,e,r,n,i),label:`Open ${e} in Pathrule Web`,reason:"preferred"}}function sw(t,e,r,n){return {kind:"desktop-app",url:rw(t,e,r,n),label:`Open ${e} in Pathrule Desktop`,reason:"fallback"}}function ow(t,e){if(t==="memory"){let s=e.nodes;return typeof s?.relative_path=="string"?s.relative_path:null}let i=e[t==="rule"?"node_rules":"node_skills"]?.[0]?.nodes?.relative_path;return typeof i=="string"?i:null}function aw(t,e){if(t==="memory"){let s=e.nodes;return typeof s?.id=="string"?s.id:null}let i=e[t==="rule"?"node_rules":"node_skills"]?.[0]?.nodes?.id;return typeof i=="string"?i:null}function lw(t){if(!t)return null;let e=t.trim();return e?e.startsWith("/")?e:`/${e}`:null}function fo(t,e){return e?t?t===e||t.startsWith(`${e}/`):false:true}function cw(t,e){let r=t.title.toLowerCase(),n=t.preview.toLowerCase(),i=t.path?.toLowerCase()??"",s=0;return r===e&&(s+=100),r.includes(e)&&(s+=30),i.includes(e)&&(s+=15),n.includes(e)&&(s+=10),s}function uw(t){return t.replace(/\s+/g," ").trim().slice(0,160)}function go(t){return !t||!Number.isFinite(t)?20:Math.min(Math.max(Math.trunc(t),1),100)}F();async function bo(t,e,r){let{session:n,supabase:i}=await C(r),s=await M(r);if(!s)throw new Error("workspace_required");let o={supabase:i,userId:n.user.id,workspaceId:s.id};if(t==="memory"){let c=e,u=await Ja(o,{node_path:rr(c.path),title:wo(c.title,"memory_title_required"),content:yo(c.body),source:"manual",allow_duplicate:c.allowDuplicate});if(!u.ok)throw new Error(u.error.message);return {item:{id:u.data.id,kind:t,title:u.data.title,path:rr(c.path),url:vt(s.id,t,u.data.id,r),open_targets:[ko(s.id,t,u.data.id,r)],content_length:u.data.content.length,source:u.data.source},warnings:u.warnings??[]}}if(t==="rule"){let c=e,u=await Ka(o,{node_path:rr(c.path),name:wo(c.name,"rule_name_required"),content:yo(c.body),priority:c.priority,scope_type:c.scopeType,allow_duplicate:c.allowDuplicate});if(!u.ok)throw new Error(u.error.message);return {item:{id:u.data.id,kind:t,title:u.data.name,path:rr(c.path),url:vt(s.id,t,u.data.id,r),open_targets:[ko(s.id,t,u.data.id,r)],content_length:u.data.content.length,priority:u.data.priority,scope_type:u.data.scopeType},warnings:u.warnings??[]}}let a=e,l=await Va(o,{node_path:rr(a.path),name:wo(a.name,"skill_name_required"),description:Wu(a.description),content:yo(a.body),source:"manual"});if(!l.ok)throw new Error(l.error.message);return {item:{id:l.data.id,kind:t,title:l.data.name,path:rr(a.path),url:vt(s.id,t,l.data.id,r),open_targets:[ko(s.id,t,l.data.id,r)],content_length:l.data.content.length,description:l.data.description,source:l.data.source},warnings:l.warnings??[]}}function Uu(t,e){if(t!=="skill")return "";let r=e,n=Wu(r.description)??"Describe when to use this skill.";return ["---",`name: ${r.name.trim()}`,`description: ${n}`,"---","","# Overview","","Explain when this skill should be used.","","## Instructions","","- Add the steps, constraints, and guardrails this skill should enforce.",""].join(`
77
+ `:"",{encoding:"utf8",mode:O}),await chmod(r,O).catch(()=>{});}finally{clearTimeout(o);}}function Y_(t){let e=t.SUPABASE_URL??t.VITE_SUPABASE_URL,r=t.SUPABASE_ANON_KEY??t.VITE_SUPABASE_ANON_KEY;return !e||!r?null:{url:`${e.replace(/\/$/,"")}/functions/v1/telemetry-ingest`,anonKey:r}}function X_(t){if(!t)return null;let e=t.toLowerCase().trim();return e==="true"?true:e==="false"?false:null}function Z_(t){let e=JSON.stringify(t),r=[/[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}/i,/(?:^|["\s])\/Users\/[^"\s]+/,/(?:^|["\s])\/home\/[^"\s]+/,/[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}/,/ghp_[A-Za-z0-9_]{20,}/];for(let n of r)if(n.test(e))throw new Error(`telemetry_payload_contains_sensitive_material:${n}`)}var Q_=new Set(["manual","notify","auto"]);function $u(t,e){if(t.CI==="true"||t.NO_UPDATE_CHECK==="1")return {key:"update.policy",value:"manual",source:"ci",configurable:false};let r=co(t.PATHRULE_UPDATE_POLICY);if(r)return {key:"update.policy",value:r,source:"env",configurable:false};let n=co(e);return n?{key:"update.policy",value:n,source:"config",configurable:true}:{key:"update.policy",value:"notify",source:"default",configurable:true}}function Nu(t){return typeof t=="boolean"?{key:"suggestions.desktop",value:t,source:"config",configurable:true}:{key:"suggestions.desktop",value:true,source:"default",configurable:true}}async function kt(t,e){if(Ru(t))return xu(t,e);if(t!=="update.policy"&&t!=="suggestions.desktop")throw new Error("unsupported_config_key");try{let{session:r}=await C(e),n=await ne(r.user.id,e);return Ou(t,e,n)}catch{return Ou(t,e)}}async function uo(t,e,r){if(t==="telemetry.enabled")return Pu(e,r);if(t==="telemetry.id")throw new Error("use_config_reset_telemetry_id");if(t!=="update.policy"&&t!=="suggestions.desktop")throw new Error("unsupported_config_key");let{session:n}=await C(r);if(t==="update.policy"){let s=co(e);if(!s)throw new Error("invalid_update_policy");return await ie(n.user.id,{update_policy:s},r),$u(r,s)}let i=ew(e);if(i===null)throw new Error("invalid_desktop_suggestions");return await ie(n.user.id,{desktop_suggestions:i},r),Nu(i)}async function po(t,e){if(t==="telemetry-id"||t==="telemetry.id")return Tu(e);throw new Error("unsupported_config_reset_key")}function co(t){if(!t)return null;let e=t.toLowerCase().trim();return Q_.has(e)?e:null}function ew(t){if(!t)return null;let e=t.toLowerCase().trim();return e==="true"?true:e==="false"?false:null}function Ou(t,e,r){return t==="update.policy"?$u(e,r?.update_policy):Nu(r?.desktop_suggestions)}Ge();F();Ee();async function Re(t){let{session:e,supabase:r}=await C(t),n=await D(t);if(!n)return [];let{data:i,error:s}=await r.from("workspaces").select("id, organization_id, name, access_mode, git_remote_url, git_owner, git_repo, user_workspace_paths!left(local_root_path, user_id)").eq("organization_id",n.id).is("archived_at",null);if(s)throw s;let o=await ne(e.user.id,t),a=[];for(let l of i??[]){let u=(l.user_workspace_paths??[]).find(d=>d.user_id===e.user.id)??null;a.push({id:l.id,organization_id:l.organization_id,name:l.name,access_mode:l.access_mode,git_remote_url:l.git_remote_url,git_owner:l.git_owner,git_repo:l.git_repo,local_root_path:u?.local_root_path??null,current:o.current_workspace_id===l.id});}if(a.sort((l,c)=>l.name.localeCompare(c.name)),!o.current_workspace_id&&a.length===1){let l=a[0];l&&(a[0]={...l,current:true});}return a}async function M(t){let e=await Re(t),r=e.find(n=>n.current);return r||(e.length===1?e[0]??null:null)}async function Zr(t,e){let{session:r}=await C(e),i=(await Re(e)).find(s=>s.id===t||s.name===t);if(!i)throw new Error("workspace_not_found");return await ie(r.user.id,{current_workspace_id:i.id},e),{...i,current:true}}async function bt(t,e,r){let{session:n,supabase:i}=await C(r),s=await D(r);if(!s)throw new Error("org_required");let o=ds(t,"workspace");if(!o.ok||!o.value)throw new Error(`unsafe_workspace_name:${o.reason??"invalid"}`);let{data:a,error:l}=await i.from("workspaces").insert({organization_id:s.id,name:o.value,access_mode:"organization",git_remote_url:null,git_provider:null,git_owner:null,git_repo:null,detected_at:null}).select("id, organization_id, name, access_mode").single();if(l||!a)throw new Error(l?.message??"workspace_create_failed");let{error:c}=await i.from("user_workspace_paths").insert({user_id:n.user.id,workspace_id:a.id,local_root_path:e,watcher_enabled:true});if(c)throw new Error(c.message);let u=await Qi(i,a.id,o.value);return await ie(n.user.id,{current_org_id:s.id,current_workspace_id:a.id},r),{workspace:{id:a.id,organization_id:a.organization_id,name:a.name,access_mode:a.access_mode,local_root_path:e,current:true},local_root_path:e,root_node_created:!("error"in u)}}async function xe(t,e,r){let{session:n,supabase:i}=await C(r),s=t?await ju(t,r):await M(r);if(!s)throw new Error("workspace_required");let{error:o}=await i.from("user_workspace_paths").upsert({user_id:n.user.id,workspace_id:s.id,local_root_path:e,watcher_enabled:true},{onConflict:"user_id,workspace_id"});if(o)throw o;return await ie(n.user.id,{current_org_id:s.organization_id,current_workspace_id:s.id},r),{workspace:{...s,local_root_path:e,current:true},local_root_path:e,previous_local_root_path:s.local_root_path}}async function Qr(t,e){let{session:r,supabase:n}=await C(e),i=t?await ju(t,e):await M(e);if(!i)throw new Error("workspace_required");let{error:s}=await n.from("user_workspace_paths").delete().eq("user_id",r.user.id).eq("workspace_id",i.id);if(s)throw s;return {...i,local_root_path:null}}async function ju(t,e){let n=(await Re(e)).find(i=>i.id===t||i.name===t);if(!n)throw new Error("workspace_not_found");return n}F();function Mu(t,e=false){return e?true:t.length<=1200&&t.split(/\r?\n/).length<=24}function Lu(t,e={}){if(e.forceWeb)return {...t.open_targets.find(r=>r.kind==="web"),reason:"forced"};if(e.preferDesktopApp){let r=t.open_targets.find(n=>n.kind==="desktop-app");return r||{...t.open_targets.find(n=>n.kind==="web"),reason:"fallback"}}return t.open_targets[0]??{kind:"web",url:t.url,label:`Open ${t.kind} in Pathrule Web`,reason:"preferred"}}async function en(t,e,r={}){let n=await nw(e),{supabase:i}=await C(e),s=go(r.limit),o=lw(r.path);if(t==="memory"){let{data:c,error:u}=await i.from("memories").select("id, title, content, updated_at, nodes(id, relative_path)").eq("workspace_id",n.id).eq("status","active").order("updated_at",{ascending:false}).limit(s*3);if(u)throw u;return (c??[]).map(d=>ho("memory",n.id,d,e)).filter(d=>fo(d.path,o)).slice(0,s)}if(t==="rule"){let{data:c,error:u}=await i.from("rules").select("id, name, content, updated_at, node_rules(nodes(id, relative_path))").eq("workspace_id",n.id).order("updated_at",{ascending:false}).limit(s*3);if(u)throw u;return (c??[]).map(d=>ho("rule",n.id,d,e)).filter(d=>fo(d.path,o)).slice(0,s)}let{data:a,error:l}=await i.from("skills").select("id, name, description, content, updated_at, node_skills(nodes!node_skills_node_id_fkey(id, relative_path))").eq("workspace_id",n.id).order("updated_at",{ascending:false}).limit(s*3);if(l)throw l;return (a??[]).map(c=>ho("skill",n.id,c,e)).filter(c=>fo(c.path,o)).slice(0,s)}async function mo(t,e,r={}){let n=t.trim().toLowerCase();if(!n)throw new Error("search_query_required");let i=r.types?.length?r.types:["memory","rule","skill"];return (await Promise.all(i.map(o=>en(o,e,{path:r.path,limit:Math.max(go(r.limit),50)})))).flat().map(o=>({item:o,score:cw(o,n)})).filter(o=>o.score>0).sort((o,a)=>a.score-o.score||(a.item.updated_at??"").localeCompare(o.item.updated_at??"")).slice(0,go(r.limit)).map(o=>o.item)}async function _o(t,e,r){let n=await en(t,r,{limit:100}),i=e.toLowerCase(),s=n.find(d=>d.id===e||d.title.toLowerCase()===i);if(!s)throw new Error(`${t}_not_found`);let{supabase:o}=await C(r),a=t==="memory"?"memories":t==="rule"?"rules":"skills",{data:l,error:c}=await o.from(a).select("content").eq("id",s.id).maybeSingle();if(c)throw c;let u=typeof l?.content=="string"?l.content:"";return {...s,content:u}}function vt(t,e,r,n,i){let s=(n.PATHRULE_WEB_URL??"https://app.pathrule.io").replace(/\/$/,"");return i?`${s}/workspace/${encodeURIComponent(t)}/node/${encodeURIComponent(i)}/${e}/${encodeURIComponent(r)}`:`${s}/workspace/${encodeURIComponent(t)}/${e}/${encodeURIComponent(r)}`}function rw(t,e,r,n){let i=n?`/node/${encodeURIComponent(n)}`:"";return `pathrule://workspace/${encodeURIComponent(t)}${i}/${e}/${encodeURIComponent(r)}`}async function nw(t){let e=await M(t);if(!e)throw new Error("workspace_required");return e}function ho(t,e,r,n){let i=typeof r.title=="string"?r.title:typeof r.name=="string"?r.name:String(r.id),s=typeof r.content=="string"?r.content:typeof r.description=="string"?r.description:"",o=ow(t,r),a=aw(t,r),l=vt(e,t,String(r.id),n,a);return {id:String(r.id),kind:t,title:i,path:o,node_id:a,preview:uw(s),updated_at:typeof r.updated_at=="string"?r.updated_at:null,url:l,open_targets:[iw(e,t,String(r.id),n,a),sw(e,t,String(r.id),a)]}}function iw(t,e,r,n,i){return {kind:"web",url:vt(t,e,r,n,i),label:`Open ${e} in Pathrule Web`,reason:"preferred"}}function sw(t,e,r,n){return {kind:"desktop-app",url:rw(t,e,r,n),label:`Open ${e} in Pathrule Desktop`,reason:"fallback"}}function ow(t,e){if(t==="memory"){let s=e.nodes;return typeof s?.relative_path=="string"?s.relative_path:null}let i=e[t==="rule"?"node_rules":"node_skills"]?.[0]?.nodes?.relative_path;return typeof i=="string"?i:null}function aw(t,e){if(t==="memory"){let s=e.nodes;return typeof s?.id=="string"?s.id:null}let i=e[t==="rule"?"node_rules":"node_skills"]?.[0]?.nodes?.id;return typeof i=="string"?i:null}function lw(t){if(!t)return null;let e=t.trim();return e?e.startsWith("/")?e:`/${e}`:null}function fo(t,e){return e?t?t===e||t.startsWith(`${e}/`):false:true}function cw(t,e){let r=t.title.toLowerCase(),n=t.preview.toLowerCase(),i=t.path?.toLowerCase()??"",s=0;return r===e&&(s+=100),r.includes(e)&&(s+=30),i.includes(e)&&(s+=15),n.includes(e)&&(s+=10),s}function uw(t){return t.replace(/\s+/g," ").trim().slice(0,160)}function go(t){return !t||!Number.isFinite(t)?20:Math.min(Math.max(Math.trunc(t),1),100)}F();async function bo(t,e,r){let{session:n,supabase:i}=await C(r),s=await M(r);if(!s)throw new Error("workspace_required");let o={supabase:i,userId:n.user.id,workspaceId:s.id};if(t==="memory"){let c=e,u=await Ja(o,{node_path:rr(c.path),title:wo(c.title,"memory_title_required"),content:yo(c.body),source:"manual",allow_duplicate:c.allowDuplicate});if(!u.ok)throw new Error(u.error.message);return {item:{id:u.data.id,kind:t,title:u.data.title,path:rr(c.path),url:vt(s.id,t,u.data.id,r),open_targets:[ko(s.id,t,u.data.id,r)],content_length:u.data.content.length,source:u.data.source},warnings:u.warnings??[]}}if(t==="rule"){let c=e,u=await Ka(o,{node_path:rr(c.path),name:wo(c.name,"rule_name_required"),content:yo(c.body),priority:c.priority,scope_type:c.scopeType,allow_duplicate:c.allowDuplicate});if(!u.ok)throw new Error(u.error.message);return {item:{id:u.data.id,kind:t,title:u.data.name,path:rr(c.path),url:vt(s.id,t,u.data.id,r),open_targets:[ko(s.id,t,u.data.id,r)],content_length:u.data.content.length,priority:u.data.priority,scope_type:u.data.scopeType},warnings:u.warnings??[]}}let a=e,l=await Va(o,{node_path:rr(a.path),name:wo(a.name,"skill_name_required"),description:Wu(a.description),content:yo(a.body),source:"manual"});if(!l.ok)throw new Error(l.error.message);return {item:{id:l.data.id,kind:t,title:l.data.name,path:rr(a.path),url:vt(s.id,t,l.data.id,r),open_targets:[ko(s.id,t,l.data.id,r)],content_length:l.data.content.length,description:l.data.description,source:l.data.source},warnings:l.warnings??[]}}function Uu(t,e){if(t!=="skill")return "";let r=e,n=Wu(r.description)??"Describe when to use this skill.";return ["---",`name: ${r.name.trim()}`,`description: ${n}`,"---","","# Overview","","Explain when this skill should be used.","","## Instructions","","- Add the steps, constraints, and guardrails this skill should enforce.",""].join(`
78
78
  `)}function rr(t){let e=t.trim();if(!e)throw new Error("content_path_required");return e.startsWith("/")?e:`/${e}`}function wo(t,e){let r=t.trim();if(!r)throw new Error(e);return r}function yo(t){let e=t.replace(/\r\n/g,`
79
- `);if(!e.trim())throw new Error("content_body_required");return e}function Wu(t){let e=t?.trim();return e||null}function ko(t,e,r,n){return {kind:"web",url:vt(t,e,r,n),label:`Open ${e} in Pathrule Web`,reason:"preferred"}}var Bu="ABCDEFGHJKLMNPQRSTUVWXYZ23456789",hw=16;function Fu(t=hw){if(t<12)throw new Error("bridge_pair_code_too_short");let e=randomBytes(t),r="";for(let n of e)r+=Bu[n%Bu.length];return r.match(/.{1,4}/g)?.join("-")??r}function Hu(t){let e=fw(t);return createHash("sha256").update("pathrule-bridge-pair-v1","utf8").update("\0","utf8").update(vo(t.pairCode),"utf8").update("\0","utf8").update(t.pairVerifier,"utf8").update("\0","utf8").update(e,"utf8").digest("base64url")}function fw(t){return JSON.stringify({daemon_session_id:tn(t.daemonSessionId,"daemon_session_id"),browser_profile_id:tn(t.browserProfileId,"browser_profile_id"),origin:gw(t.origin),user_id:tn(t.userId,"user_id")})}function vo(t){return tn(t,"pair_secret").replace(/[\s-]+/g,"").toUpperCase()}function gw(t){let e=tn(t,"origin"),r=new URL(e);if(r.protocol!=="https:"&&r.hostname!=="localhost")throw new Error("bridge_pair_origin_not_allowed");return r.pathname="",r.search="",r.hash="",r.toString().replace(/\/$/,"")}function tn(t,e){if(typeof t!="string"||t.trim()==="")throw new Error(`bridge_pair_${e}_required`);return t.trim()}K();F();var Sw=300*1e3,Y=class extends Error{constructor(r,n=r){super(n);this.code=r;this.name="BridgePairError";}code};async function Co(t){let e=t.user??await fi(t.env,t.verifyReauth!==false),r=Fu(),n=new Date(Date.now()+Sw).toISOString(),i={schema_version:1,pair_code_hash:zu(r),user_id:e.user_id,user_email:e.user_email,daemon_session_id:t.daemonSessionId,created_at:new Date().toISOString(),expires_at:n};return await Cw(t.env,i),{pair_code:r,expires_at:n,url:`${Rw(t.env)}/connect`,daemon_session_id:t.daemonSessionId}}async function qu(t){let e=await Ew(t.env);if(!e)throw new Y("pair_code_missing");if(e.daemon_session_id!==t.daemonSessionId)throw await So(t.env),new Y("pair_code_stale");if(Date.parse(e.expires_at)<=Date.now())throw await So(t.env),new Y("pair_code_expired");if(e.pair_code_hash!==zu(t.pairCode))throw new Y("pair_code_invalid");let r=Hu({daemonSessionId:t.daemonSessionId,browserProfileId:t.browserProfileId,origin:t.origin,userId:e.user_id,pairCode:t.pairCode,pairVerifier:t.pairVerifier});return await So(t.env),{pair_token:r,daemon_session_id:t.daemonSessionId,user_id:e.user_id}}async function fi(t,e=true){let{session:r,supabase:n}=await C(t);if(e){let{data:i,error:s}=await n.rpc("verify_sensitive_action_grant",{p_action:"bridge_pair"});if(s)throw new Y("bridge_pair_reauth_check_failed",s.message);if(i!==true)throw new Y("bridge_pair_reauth_required","Run sensitive-action reauth for bridge_pair before pairing this browser.")}return {user_id:r.user.id,user_email:r.user.email}}async function Cw(t,e){let r=A(t).bridgePairFile;await mkdir(dirname(r),{recursive:true,mode:D});let n=`${r}.tmp`;await writeFile(n,JSON.stringify(e,null,2),{encoding:"utf8",mode:O}),await rename(n,r);}async function Ew(t){try{return JSON.parse(await readFile(A(t).bridgePairFile,"utf8"))}catch{return null}}async function So(t){await unlink(A(t).bridgePairFile).catch(()=>{});}function zu(t){return createHash("sha256").update("pathrule-bridge-pair-code-v1","utf8").update("\0","utf8").update(vo(t),"utf8").digest("base64url")}function Rw(t){return (t.PATHRULE_WEB_URL||t.VITE_PATHRULE_WEB_URL||"https://app.pathrule.io").replace(/\/+$/,"")}var gi="x-pathrule-pair-token",Ju="x-pathrule-browser-profile-id";function St(t){let e=xw(t.headers,t.allowedOrigins);if(e)return e;let r=Eo(t.headers,"content-type");return !r||!/^application\/json(?:\s*;|$)/i.test(r)?{statusCode:415,reason:"json_content_type_required"}:t.requirePairToken!==false&&!Eo(t.headers,gi)?{statusCode:401,reason:"pair_token_required"}:null}function Ro(t,e){return !t||!mi(t,e)?null:{"Access-Control-Allow-Origin":t,"Access-Control-Allow-Headers":"Authorization, X-Pathrule-Pair-Token, X-Pathrule-Browser-Profile-Id, Content-Type","Access-Control-Allow-Methods":"GET, POST, OPTIONS","Access-Control-Allow-Credentials":"false"}}function xw(t,e){let r=Eo(t,"origin");return r?mi(r,e)?null:{statusCode:400,reason:"origin_not_allowed"}:{statusCode:400,reason:"origin_required"}}function mi(t,e){return e.some(r=>r===t)}function Ku(t){return {daemon_present:true,protocol_version:t}}function Vu(t){let e=t.windowMs??6e4,r=Math.floor((t.nowMs??Date.now())/e);return `${t.origin}\0${t.ip}\0${r}`}function Eo(t,e){let r=t[e]??t[e.toLowerCase()],n=Array.isArray(r)?r[0]:r;return (typeof n=="string"?n.trim():"")||void 0}K();function Gu(t){return t==="modified"||t==="added"||t==="deleted"||t==="renamed"||t==="untracked"||t==="unknown"}function Yu(t){let e=t.nowMs??Date.now(),r=t.rows.filter(i=>t.currentUserId===null||i.user_id!==t.currentUserId).flatMap(i=>Tw(i,t.displayNamesByUserId??{},e)).sort(Ow),n=Math.max(0,e-(t.startedAtMs??e));return r.length===0?{decision:"allow",conflicts:[],source:t.source,latency_ms:n}:{decision:"ask",conflicts:r,message:Aw(r[0],e),source:t.source,latency_ms:n}}function Xu(t=Date.now()){return {decision:"ask",conflicts:[],message:"Pathrule could not verify teammate local state in time. Continue?",source:"degraded",latency_ms:Math.max(0,Date.now()-t)}}function Zu(t){return Array.isArray(t)?t.flatMap(e=>{if(!e||typeof e!="object")return [];let r=e,n=typeof r.relative_path=="string"?r.relative_path:"",i=typeof r.user_id=="string"?r.user_id:"",s=typeof r.workspace_id=="string"?r.workspace_id:"";if(!n||!i||!s)return [];let o=Gu(r.git_status)?r.git_status:"unknown";return [{workspace_id:s,user_id:i,runtime_id:typeof r.runtime_id=="string"?r.runtime_id:"unknown",relative_path:n,is_active:r.is_active===true,is_dirty:r.is_dirty===true,git_status:o,last_heartbeat_at:typeof r.last_heartbeat_at=="string"?r.last_heartbeat_at:null,last_local_write_at:typeof r.last_local_write_at=="string"?r.last_local_write_at:null,last_git_scan_at:typeof r.last_git_scan_at=="string"?r.last_git_scan_at:new Date(0).toISOString()}]}):[]}function Tw(t,e,r){let n=t.last_heartbeat_at?Date.parse(t.last_heartbeat_at):Number.NaN,i=t.is_active&&Number.isFinite(n)&&r-n<=3e4,s=t.is_dirty;return !i&&!s?[]:[{user_id:t.user_id,display_name:Qu(e[t.user_id]??"A teammate"),relative_path:t.relative_path,reason:i&&s?"active_dirty":i?"active":"dirty",git_status:t.git_status,last_heartbeat_at:t.last_heartbeat_at,last_local_write_at:t.last_local_write_at}]}function Aw(t,e){let r=Qu(t.display_name);if(t.reason==="active"||t.reason==="active_dirty")return `Pathrule caught a possible conflict. ${r} is actively working on this file. Continue?`;let n=Iw(t.last_local_write_at,e);return `Pathrule caught a possible conflict. ${r} changed this file ${n} and has not committed it yet. Continue?`}function Iw(t,e){let r=t?Date.parse(t):Number.NaN;if(!Number.isFinite(r))return "recently";let n=Math.max(0,e-r),s=60*6e4,o=24*s;if(n<s)return "recently";if(n<o){let l=Math.max(1,Math.floor(n/s));return `${l} ${l===1?"hour":"hours"} ago`}let a=Math.max(1,Math.floor(n/o));return `${a} ${a===1?"day":"days"} ago`}function Ow(t,e){let r=i=>i.reason==="active"||i.reason==="active_dirty"?0:1,n=r(t)-r(e);return n!==0?n:t.relative_path.localeCompare(e.relative_path)}function Qu(t){let e=t.replace(/[\x00-\x1F\x7F]/g,"").trim();return !e||e.includes("@")||/^https?:\/\//i.test(e)?"A teammate":e.slice(0,80)}F();K();var Ww=".pathrule/managed-files.json";function td(t){return join(t,Ww)}function Po(t){let e=normalize(t).replace(/\\/g,"/").replace(/^\/+/,"");if(e==="."||e.length===0||e.startsWith("../")||e.includes("/../"))throw new Error(`Invalid managed file path: ${t}`);return e}async function _i(t){try{let e=await readFile(td(t),"utf8"),r=JSON.parse(e);if(r.schema_version!==1||!Array.isArray(r.files))return xo();let n=r.files.flatMap(i=>{if(!i||typeof i!="object")return [];let s=i;if(typeof s.path!="string"||!Hw(s.owner)||typeof s.owner_version!="string"||typeof s.updated_at!="string")return [];try{return [{path:Po(s.path),owner:s.owner,owner_version:s.owner_version,updated_at:s.updated_at}]}catch{return []}});return {schema_version:1,files:sd(qw(n))}}catch(e){if(e.code==="ENOENT"||e instanceof SyntaxError)return xo();throw e}}async function wi(t){if(t.paths.length===0)return;let e=await _i(t.workspaceRoot),r=(t.now??new Date).toISOString(),n=new Map(e.files.map(i=>[i.path,i]));for(let i of t.paths){let s=Po(i);n.set(s,{path:s,owner:t.owner,owner_version:t.ownerVersion,updated_at:r});}await id(t.workspaceRoot,{schema_version:1,files:sd(Array.from(n.values()))});}async function rd(t){if(t.paths.length===0)return;let e=await _i(t.workspaceRoot),r=new Set(t.paths.map(Po));await id(t.workspaceRoot,{schema_version:1,files:e.files.filter(n=>!r.has(n.path))});}function nd(t,e,r){return t.files.map(n=>({...n,status:Fw(n,e,r)}))}function Bw(t,e){let r=ed(t),n=ed(e),i=Math.max(r.length,n.length);for(let s=0;s<i;s+=1){let o=(r[s]??0)-(n[s]??0);if(o!==0)return o>0?1:-1}return 0}function Fw(t,e,r){if(t.owner!==e)return "other_owner";let n=Bw(t.owner_version,r);return n>0?"newer_version":n<0?"older_version":"current"}async function id(t,e){let r=td(t);await mkdir(dirname(r),{recursive:true});let n=`${r}.tmp`;await writeFile(n,`${JSON.stringify(e,null,2)}
79
+ `);if(!e.trim())throw new Error("content_body_required");return e}function Wu(t){let e=t?.trim();return e||null}function ko(t,e,r,n){return {kind:"web",url:vt(t,e,r,n),label:`Open ${e} in Pathrule Web`,reason:"preferred"}}var Bu="ABCDEFGHJKLMNPQRSTUVWXYZ23456789",hw=16;function Fu(t=hw){if(t<12)throw new Error("bridge_pair_code_too_short");let e=randomBytes(t),r="";for(let n of e)r+=Bu[n%Bu.length];return r.match(/.{1,4}/g)?.join("-")??r}function Hu(t){let e=fw(t);return createHash("sha256").update("pathrule-bridge-pair-v1","utf8").update("\0","utf8").update(vo(t.pairCode),"utf8").update("\0","utf8").update(t.pairVerifier,"utf8").update("\0","utf8").update(e,"utf8").digest("base64url")}function fw(t){return JSON.stringify({daemon_session_id:tn(t.daemonSessionId,"daemon_session_id"),browser_profile_id:tn(t.browserProfileId,"browser_profile_id"),origin:gw(t.origin),user_id:tn(t.userId,"user_id")})}function vo(t){return tn(t,"pair_secret").replace(/[\s-]+/g,"").toUpperCase()}function gw(t){let e=tn(t,"origin"),r=new URL(e);if(r.protocol!=="https:"&&r.hostname!=="localhost")throw new Error("bridge_pair_origin_not_allowed");return r.pathname="",r.search="",r.hash="",r.toString().replace(/\/$/,"")}function tn(t,e){if(typeof t!="string"||t.trim()==="")throw new Error(`bridge_pair_${e}_required`);return t.trim()}K();F();var Sw=300*1e3,Y=class extends Error{constructor(r,n=r){super(n);this.code=r;this.name="BridgePairError";}code};async function Co(t){let e=t.user??await fi(t.env,t.verifyReauth!==false),r=Fu(),n=new Date(Date.now()+Sw).toISOString(),i={schema_version:1,pair_code_hash:zu(r),user_id:e.user_id,user_email:e.user_email,daemon_session_id:t.daemonSessionId,created_at:new Date().toISOString(),expires_at:n};return await Cw(t.env,i),{pair_code:r,expires_at:n,url:`${Rw(t.env)}/connect`,daemon_session_id:t.daemonSessionId}}async function qu(t){let e=await Ew(t.env);if(!e)throw new Y("pair_code_missing");if(e.daemon_session_id!==t.daemonSessionId)throw await So(t.env),new Y("pair_code_stale");if(Date.parse(e.expires_at)<=Date.now())throw await So(t.env),new Y("pair_code_expired");if(e.pair_code_hash!==zu(t.pairCode))throw new Y("pair_code_invalid");let r=Hu({daemonSessionId:t.daemonSessionId,browserProfileId:t.browserProfileId,origin:t.origin,userId:e.user_id,pairCode:t.pairCode,pairVerifier:t.pairVerifier});return await So(t.env),{pair_token:r,daemon_session_id:t.daemonSessionId,user_id:e.user_id}}async function fi(t,e=true){let{session:r,supabase:n}=await C(t);if(e){let{data:i,error:s}=await n.rpc("verify_sensitive_action_grant",{p_action:"bridge_pair"});if(s)throw new Y("bridge_pair_reauth_check_failed",s.message);if(i!==true)throw new Y("bridge_pair_reauth_required","Run sensitive-action reauth for bridge_pair before pairing this browser.")}return {user_id:r.user.id,user_email:r.user.email}}async function Cw(t,e){let r=A(t).bridgePairFile;await mkdir(dirname(r),{recursive:true,mode:j});let n=`${r}.tmp`;await writeFile(n,JSON.stringify(e,null,2),{encoding:"utf8",mode:O}),await rename(n,r);}async function Ew(t){try{return JSON.parse(await readFile(A(t).bridgePairFile,"utf8"))}catch{return null}}async function So(t){await unlink(A(t).bridgePairFile).catch(()=>{});}function zu(t){return createHash("sha256").update("pathrule-bridge-pair-code-v1","utf8").update("\0","utf8").update(vo(t),"utf8").digest("base64url")}function Rw(t){return (t.PATHRULE_WEB_URL||t.VITE_PATHRULE_WEB_URL||"https://app.pathrule.io").replace(/\/+$/,"")}var gi="x-pathrule-pair-token",Ju="x-pathrule-browser-profile-id";function St(t){let e=xw(t.headers,t.allowedOrigins);if(e)return e;let r=Eo(t.headers,"content-type");return !r||!/^application\/json(?:\s*;|$)/i.test(r)?{statusCode:415,reason:"json_content_type_required"}:t.requirePairToken!==false&&!Eo(t.headers,gi)?{statusCode:401,reason:"pair_token_required"}:null}function Ro(t,e){return !t||!mi(t,e)?null:{"Access-Control-Allow-Origin":t,"Access-Control-Allow-Headers":"Authorization, X-Pathrule-Pair-Token, X-Pathrule-Browser-Profile-Id, Content-Type","Access-Control-Allow-Methods":"GET, POST, OPTIONS","Access-Control-Allow-Credentials":"false"}}function xw(t,e){let r=Eo(t,"origin");return r?mi(r,e)?null:{statusCode:400,reason:"origin_not_allowed"}:{statusCode:400,reason:"origin_required"}}function mi(t,e){return e.some(r=>r===t)}function Ku(t,e={}){let r={daemon_present:true,protocol_version:t};return e.daemonSessionId&&(r.daemon_session_id=e.daemonSessionId),r}function Vu(t){let e=t.windowMs??6e4,r=Math.floor((t.nowMs??Date.now())/e);return `${t.origin}\0${t.ip}\0${r}`}function Eo(t,e){let r=t[e]??t[e.toLowerCase()],n=Array.isArray(r)?r[0]:r;return (typeof n=="string"?n.trim():"")||void 0}K();function Gu(t){return t==="modified"||t==="added"||t==="deleted"||t==="renamed"||t==="untracked"||t==="unknown"}function Yu(t){let e=t.nowMs??Date.now(),r=t.rows.filter(i=>t.currentUserId===null||i.user_id!==t.currentUserId).flatMap(i=>Tw(i,t.displayNamesByUserId??{},e)).sort(Ow),n=Math.max(0,e-(t.startedAtMs??e));return r.length===0?{decision:"allow",conflicts:[],source:t.source,latency_ms:n}:{decision:"ask",conflicts:r,message:Aw(r[0],e),source:t.source,latency_ms:n}}function Xu(t=Date.now()){return {decision:"ask",conflicts:[],message:"Pathrule could not verify teammate local state in time. Continue?",source:"degraded",latency_ms:Math.max(0,Date.now()-t)}}function Zu(t){return Array.isArray(t)?t.flatMap(e=>{if(!e||typeof e!="object")return [];let r=e,n=typeof r.relative_path=="string"?r.relative_path:"",i=typeof r.user_id=="string"?r.user_id:"",s=typeof r.workspace_id=="string"?r.workspace_id:"";if(!n||!i||!s)return [];let o=Gu(r.git_status)?r.git_status:"unknown";return [{workspace_id:s,user_id:i,runtime_id:typeof r.runtime_id=="string"?r.runtime_id:"unknown",relative_path:n,is_active:r.is_active===true,is_dirty:r.is_dirty===true,git_status:o,last_heartbeat_at:typeof r.last_heartbeat_at=="string"?r.last_heartbeat_at:null,last_local_write_at:typeof r.last_local_write_at=="string"?r.last_local_write_at:null,last_git_scan_at:typeof r.last_git_scan_at=="string"?r.last_git_scan_at:new Date(0).toISOString()}]}):[]}function Tw(t,e,r){let n=t.last_heartbeat_at?Date.parse(t.last_heartbeat_at):Number.NaN,i=t.is_active&&Number.isFinite(n)&&r-n<=3e4,s=t.is_dirty;return !i&&!s?[]:[{user_id:t.user_id,display_name:Qu(e[t.user_id]??"A teammate"),relative_path:t.relative_path,reason:i&&s?"active_dirty":i?"active":"dirty",git_status:t.git_status,last_heartbeat_at:t.last_heartbeat_at,last_local_write_at:t.last_local_write_at}]}function Aw(t,e){let r=Qu(t.display_name);if(t.reason==="active"||t.reason==="active_dirty")return `Pathrule caught a possible conflict. ${r} is actively working on this file. Continue?`;let n=Iw(t.last_local_write_at,e);return `Pathrule caught a possible conflict. ${r} changed this file ${n} and has not committed it yet. Continue?`}function Iw(t,e){let r=t?Date.parse(t):Number.NaN;if(!Number.isFinite(r))return "recently";let n=Math.max(0,e-r),s=60*6e4,o=24*s;if(n<s)return "recently";if(n<o){let l=Math.max(1,Math.floor(n/s));return `${l} ${l===1?"hour":"hours"} ago`}let a=Math.max(1,Math.floor(n/o));return `${a} ${a===1?"day":"days"} ago`}function Ow(t,e){let r=i=>i.reason==="active"||i.reason==="active_dirty"?0:1,n=r(t)-r(e);return n!==0?n:t.relative_path.localeCompare(e.relative_path)}function Qu(t){let e=t.replace(/[\x00-\x1F\x7F]/g,"").trim();return !e||e.includes("@")||/^https?:\/\//i.test(e)?"A teammate":e.slice(0,80)}F();K();var Ww=".pathrule/managed-files.json";function td(t){return join(t,Ww)}function Po(t){let e=normalize(t).replace(/\\/g,"/").replace(/^\/+/,"");if(e==="."||e.length===0||e.startsWith("../")||e.includes("/../"))throw new Error(`Invalid managed file path: ${t}`);return e}async function _i(t){try{let e=await readFile(td(t),"utf8"),r=JSON.parse(e);if(r.schema_version!==1||!Array.isArray(r.files))return xo();let n=r.files.flatMap(i=>{if(!i||typeof i!="object")return [];let s=i;if(typeof s.path!="string"||!Hw(s.owner)||typeof s.owner_version!="string"||typeof s.updated_at!="string")return [];try{return [{path:Po(s.path),owner:s.owner,owner_version:s.owner_version,updated_at:s.updated_at}]}catch{return []}});return {schema_version:1,files:sd(qw(n))}}catch(e){if(e.code==="ENOENT"||e instanceof SyntaxError)return xo();throw e}}async function wi(t){if(t.paths.length===0)return;let e=await _i(t.workspaceRoot),r=(t.now??new Date).toISOString(),n=new Map(e.files.map(i=>[i.path,i]));for(let i of t.paths){let s=Po(i);n.set(s,{path:s,owner:t.owner,owner_version:t.ownerVersion,updated_at:r});}await id(t.workspaceRoot,{schema_version:1,files:sd(Array.from(n.values()))});}async function rd(t){if(t.paths.length===0)return;let e=await _i(t.workspaceRoot),r=new Set(t.paths.map(Po));await id(t.workspaceRoot,{schema_version:1,files:e.files.filter(n=>!r.has(n.path))});}function nd(t,e,r){return t.files.map(n=>({...n,status:Fw(n,e,r)}))}function Bw(t,e){let r=ed(t),n=ed(e),i=Math.max(r.length,n.length);for(let s=0;s<i;s+=1){let o=(r[s]??0)-(n[s]??0);if(o!==0)return o>0?1:-1}return 0}function Fw(t,e,r){if(t.owner!==e)return "other_owner";let n=Bw(t.owner_version,r);return n>0?"newer_version":n<0?"older_version":"current"}async function id(t,e){let r=td(t);await mkdir(dirname(r),{recursive:true});let n=`${r}.tmp`;await writeFile(n,`${JSON.stringify(e,null,2)}
80
80
  `,"utf8"),await rename(n,r);}function xo(){return {schema_version:1,files:[]}}function Hw(t){return t==="desktop"||t==="cli"||t==="mcp"}function ed(t){let e=t.match(/\d+(?:\.\d+)*/);return e?e[0].split(".").map(r=>Number.parseInt(r,10)):[0]}function qw(t){return Array.from(new Map(t.map(e=>[e.path,e])).values())}function sd(t){return t.sort((e,r)=>e.path.localeCompare(r.path))}function To(t){if(!(!t||t.trim().length===0))try{return JSON.parse(t)}catch(e){throw new Error(`Claude config is not valid JSON: ${e.message}`)}}function od(t){return JSON.stringify(t,null,2)+`
81
81
  `}var ad={id:"claude-code",homeConfigPath(t,e){return Ua(e,t)},inject(t,e){let r=To(t),{config:n,wasNew:i}=Wa(r??{},e);return {body:od(n),wasNew:i}},remove(t){if(t===null)return {body:null,wasPresent:false};let e=To(t),{config:r,wasPresent:n}=Ba(e);return n?{body:od(r),wasPresent:true}:{body:t,wasPresent:false}},read(t){try{let e=To(t);return Fa(e)}catch{return null}}};function zw(t,e){let r=t.slice(0,e).split(/\r\n|\n|\r/g);return [r.length,r.pop().length+1]}function Jw(t,e,r){let n=t.split(/\r\n|\n|\r/g),i="",s=(Math.log10(e+1)|0)+1;for(let o=e-1;o<=e+1;o++){let a=n[o-1];a&&(i+=o.toString().padEnd(s," "),i+=": ",i+=a,i+=`
82
82
  `,o===e&&(i+=" ".repeat(s+r+2),i+=`^
@@ -110,8 +110,8 @@ ${o}`:s||o}function Si(t,{maxDepth:e=1e3,numbersAsFloat:r=false}={}){if(sn(t)!==
110
110
  `?n+`
111
111
  `:n}var oe="pathrule";function No(t){if(!t||t.trim().length===0)return {};let e;try{e=Ao(t);}catch(r){throw new Error(`config.toml is not valid TOML: ${r.message}`)}if(e===null||typeof e!="object"||Array.isArray(e))throw new Error("config.toml root must be a TOML table");return e}function sy(t){let e={command:t.command,args:t.args,enabled:true};return t.env&&Object.keys(t.env).length>0&&(e.env=t.env),e}function oy(t){return !t||typeof t.command!="string"?null:{type:"stdio",command:t.command,args:Array.isArray(t.args)?t.args.map(String):[],env:t.env&&typeof t.env=="object"&&!Array.isArray(t.env)?t.env:void 0}}var gd={id:"codex",homeConfigPath(t,e){return `${t}/.codex/config.toml`},inject(t,e){let r=No(t),n={...r.mcp_servers??{}},i=!(oe in n);n[oe]=sy(e);let s={...r,mcp_servers:n};return {body:Si(s)+`
112
112
  `,wasNew:i}},remove(t){let e=No(t),r=e.mcp_servers??{};if(!(oe in r))return {body:t,wasPresent:false};let{[oe]:n,...i}=r,s={...e};return Object.keys(i).length===0?delete s.mcp_servers:s.mcp_servers=i,Object.keys(s).length===0?{body:null,wasPresent:true}:{body:Si(s)+`
113
- `,wasPresent:true}},read(t){try{let e=No(t);return oy(e.mcp_servers?.[oe])}catch{return null}}};function ay(t){if(t==null)return {};if(typeof t!="object"||Array.isArray(t))throw new Error("Config root must be a JSON object");let e=t;if(e.mcpServers!==void 0&&(typeof e.mcpServers!="object"||e.mcpServers===null||Array.isArray(e.mcpServers)))throw new Error("`mcpServers` must be an object");return e}function jo(t){if(!t||t.trim().length===0)return {};let e;try{e=JSON.parse(t);}catch(r){throw new Error(`Config is not valid JSON: ${r.message}`)}return ay(e)}function md(t){return JSON.stringify(t,null,2)+`
114
- `}function Ci(t){function e(r){if(t.includeTypeField)return r;let{type:n,...i}=r;return i}return {inject(r,n){let i=jo(r),s={...i.mcpServers??{}},o=!(oe in s);s[oe]=e(n);let a={...i,mcpServers:s};return {body:md(a),wasNew:o}},remove(r){let n=jo(r),i=n.mcpServers??{};if(!(oe in i))return {body:r,wasPresent:false};let{[oe]:s,...o}=i,a={...n,mcpServers:o};return Object.keys(o).length===0&&Object.keys(a).length===1&&"mcpServers"in a?{body:null,wasPresent:true}:{body:md(a),wasPresent:true}},read(r){try{return jo(r).mcpServers?.[oe]??null}catch{return null}}}}var Do=Ci({includeTypeField:true}),_d={id:"cursor",homeConfigPath(t,e){return `${t}/.cursor/mcp.json`},inject:Do.inject,remove:Do.remove,read:Do.read};var Mo=Ci({includeTypeField:false}),wd={id:"windsurf",homeConfigPath(t,e){return `${t}/.codeium/windsurf/mcp_config.json`},inject:Mo.inject,remove:Mo.remove,read:Mo.read};var ly={"claude-code":ad,cursor:_d,codex:gd,windsurf:wd};function Ct(t){return ly[t]}Gr();F();Ee();var gy=createRequire(import.meta.url),my=gy("../package.json"),_y=my.version,wy=["claude-code","cursor","codex","windsurf"];async function Me(t,e){let r=[],n=await Ce(t);r.push({name:"auth",status:n?"pass":"fail",detail:n?n.session.user.email??n.session.user.id:"not_authenticated"});let i=null;if(n){try{let u=await j(t);r.push({name:"organization",status:u?"pass":"warn",detail:u?.slug??"no organization selected"});}catch(u){r.push({name:"organization",status:"fail",detail:u instanceof Error?u.message:String(u)});}try{let u=await M(t);i=u?.local_root_path??null,r.push({name:"workspace",status:u?"pass":"warn",detail:u?.name??"no workspace selected"});}catch(u){r.push({name:"workspace",status:"fail",detail:u instanceof Error?u.message:String(u)});}}r.push({name:"cwd_attach",status:i===e?"pass":"warn",detail:i===e?"current folder is attached":i??"workspace not attached"});let s=await Promise.all(wy.map(Cy)),o=nd(await _i(e),"cli",_y),a=o.filter(u=>u.status==="other_owner").length,l=o.filter(u=>u.status==="newer_version").length;return a>0||l>0?r.push({name:"managed_files",status:"warn",detail:ky(a,l)}):o.length>0?r.push({name:"managed_files",status:"pass",detail:`${o.length} Pathrule-managed file${o.length===1?"":"s"} tracked`}):r.push({name:"managed_files",status:"pass",detail:"no Pathrule-managed files tracked yet"}),{ok:!r.some(u=>u.status==="fail"),checks:r,mcp:s,managed_files:o}}async function Uo(t,e){await vy(t);let r=await Me(t,e),n=A(t);await mkdir(n.supportDir,{recursive:true,mode:D}),await chmod(n.supportDir,D).catch(()=>{});let i=join(n.supportDir,`${new Date().toISOString().replace(/[:.]/g,"-")}-doctor.json`),s={schema_version:1,produced_at:new Date().toISOString(),cwd_hash:Sy(e),platform:process.platform,node_version:process.version,env_keys:Object.keys(t).filter(o=>o.startsWith("PATHRULE_")||o==="CI"||o==="NO_COLOR").sort(),report:yy(r)};return El(s),await writeFile(i,JSON.stringify(s,null,2),{encoding:"utf8",mode:O}),await chmod(i,O).catch(()=>{}),{ok:r.ok,path:i,report:r}}function yy(t){return {ok:t.ok,checks:t.checks.map(e=>({...e,detail:Lo(e.detail)})),mcp:t.mcp.map(e=>({...e,config_path:by(e.config_path),error:Lo(e.error)})),managed_files:t.managed_files.map(e=>({...e,path:Lo(e.path)??e.path}))}}function ky(t,e){let r=[];return t>0&&r.push(`${t} file${t===1?"":"s"} last written by another surface`),e>0&&r.push(`${e} file${e===1?"":"s"} last written by a newer CLI`),r.join("; ")}function Lo(t){return t&&ms(t)}function by(t){return ms(t,"path")}async function vy(t){let{supabase:e}=await C(t),{data:r,error:n}=await e.rpc("consume_sensitive_action_grant",{p_action:"token_export"});if(n)throw new Error(`token_export_reauth_check_failed: ${n.message}`);if(r!==true)throw new Error("token_export_reauth_required")}function Sy(t){let e=2166136261;for(let r=0;r<t.length;r+=1)e^=t.charCodeAt(r),e=Math.imul(e,16777619);return (e>>>0).toString(16).padStart(8,"0")}async function Cy(t){let e=Ct(t),r=e.homeConfigPath(homedir(),process.platform);try{let n=await readFile(r,"utf8");return {client:t,config_path:r,readable:!0,installed:e.read(n)!==null}}catch(n){return n.code==="ENOENT"?{client:t,config_path:r,readable:false,installed:false}:{client:t,config_path:r,readable:false,installed:false,error:n instanceof Error?n.message:String(n)}}}var Et=class extends Error{constructor(e){super(e),this.name="WorkspacePathSafetyError";}};async function bd(t,e){let r=await realpath(t),n=Ry(e),i=Xe.resolve(r,n||"."),s=await realpath(i);if(!Sd(r,s))throw new Et(`Refused: ${e||"/"} escapes the workspace root`);return {rootRealPath:r,absolutePath:s,relativePath:n===""?"/":`/${xy(n)}`}}async function vd(t,e){try{let r=await realpath(e);return Sd(t,r)?(await stat(r)).isDirectory():!1}catch{return false}}function Ry(t){if(typeof t!="string")throw new Et("Refused: workspace path must be a string");if(t.includes("\0"))throw new Et("Refused: workspace path contains a null byte");let e=t.trim();if(e===""||e==="/"||e===".")return "";if(/^[a-zA-Z]:[\\/]/.test(e)||e.startsWith("\\\\"))throw new Et("Refused: absolute workspace path is not allowed");let r=e.replace(/^[/\\]+/,""),i=Xe.normalize(r).split(/[\\/]+/).filter(Boolean);if(i.includes(".."))throw new Et(`Refused: ${t} escapes the workspace root`);return i.join(Xe.sep)}function Sd(t,e){let r=kd(Xe.resolve(t)),n=kd(Xe.resolve(e)),i=r.endsWith(Xe.sep)?r:r+Xe.sep;return n===r||n.startsWith(i)}function kd(t){return process.platform==="win32"||process.platform==="darwin"?t.toLowerCase():t}function xy(t){return t.split(Xe.sep).join("/")}var Ay=new Set([".git","node_modules",".next","dist","build",".turbo",".cache","coverage","target","__pycache__",".venv","venv",".DS_Store",".idea",".vscode"]);async function Bo(t,e){let r=await bd(t,e),n=await promises.readdir(r.absolutePath,{withFileTypes:true,encoding:"utf8"}),i=[];for(let s of n){if(Ay.has(s.name))continue;let o=Xe.join(r.absolutePath,s.name),a=s.isDirectory()||s.isSymbolicLink()&&await vd(r.rootRealPath,o);i.push({absPath:o,relativePath:Iy(e,s.name),name:s.name,isDir:a});}return i.sort((s,o)=>s.isDir!==o.isDir?s.isDir?-1:1:s.name.localeCompare(o.name)),i}function Iy(t,e){return t==="/"||t===""?"/"+e:t+"/"+e}K();async function Ei(t){let e=Ed(t.env,t.workspaceId),r=false;if(t.refreshEpisodes!==false){let{error:o}=await t.supabase.rpc("pathrule_refresh_work_episodes",{p_workspace_id:t.workspaceId});r=!o;}let{data:n,error:i}=await t.supabase.rpc("pathrule_build_hook_index_payload",{p_workspace_id:t.workspaceId});if(i)return {ok:false,path:e,refreshed_episodes:r,schema_version:null,error:i.message};if(!n||typeof n!="object")return {ok:false,path:e,refreshed_episodes:r,schema_version:null,error:"empty_hook_index_payload"};let s={...n,workspace_root:t.workspaceRoot};return await Dy(t.env,s),{ok:true,path:e,refreshed_episodes:r,schema_version:s.schema_version}}function Ed(t,e){return join(A(t).home,"cache",e,"hook-index.json")}async function Dy(t,e){let r=Ed(t,e.workspace_id);await mkdir(join(A(t).home,"cache",e.workspace_id),{recursive:true});let n=`${r}.tmp`;await writeFile(n,JSON.stringify(e,null,2),"utf8"),await chmod(n,384),await rename(n,r);}K();F();Ge();function Rt(t,e){let r=[];r.push("<!-- Pathrule managed \u2014 do not edit; cloud state is authoritative. -->",""),r.push("# Pathrule integration",""),r.push("Pathrule is this workspace's shared memory, rule, and skill layer for AI agents.",`${e.toolLabel} should use it as a smart reminder system, not a full-context dump.`,""),r.push("## Context Policy",""),r.push("- Pathrule is the first knowledge layer for this workspace. Use hook context first: metadata, relevant rule titles, path reminders, and filename/skill matches.","- `::skill-name` is a hard gate: use the exact injected skill; if missing, stop and resolve it through Pathrule/MCP before file edits.",'- Do not reflexively call `pathrule_get_context` before every small known-path code task. For discovery, inventory, architecture, recent activity, or "list/show/find/where/which" prompts (Turkish: listele, g\xF6ster, bul, nerede, hangi, neler), call it before any grep/read/fallback when hook context is missing, ambiguous, or stale.',"- Hook silence on a topic does not mean Pathrule has no relevant memory/rule. For discovery/inventory/architecture questions, call `pathrule_get_context` first; fall back to files, git, or general knowledge only after Pathrule returns nothing relevant.","- When calling `pathrule_get_context`, pass `cwd`, `user_intent`, and `omit_protocol: true`; the companion file already contains the protocol.","- Read full bodies with `pathrule_read_memory`, `pathrule_read_rule`, or `pathrule_read_skill` when a surfaced title/id is relevant.","- Treat existing local edits as protected user/team work: inspect overlaps, never revert unrelated changes, and keep edits scoped.","- Obey every surfaced rule. If a user request conflicts with a Pathrule rule, warn before taking action.",""),r.push("## Writes",""),r.push("- Pathrule cloud is the source of truth. Do not create local memory files such as `MEMORY.md` or `~/.claude/memory/`.","- Use path-first writes for lasting project knowledge: `pathrule_write_memory`, `pathrule_write_rule`, and `pathrule_write_skill` take the most specific workspace-relative `node_path`.","- Do not edit materialized local Pathrule files as the source of truth. This includes `.codex/skills/**/SKILL.md`, `.claude/skills/**`, rendered companion files, and synced skill/memory/rule files. Read only for orientation; create/update cloud records with the Pathrule MCP write/update tools.","- After any file-modifying response, call `pathrule_log_activity` once with domain, action, scope, subjects, files_touched, and a concise task_summary.","");let n=r.join(`
113
+ `,wasPresent:true}},read(t){try{let e=No(t);return oy(e.mcp_servers?.[oe])}catch{return null}}};function ay(t){if(t==null)return {};if(typeof t!="object"||Array.isArray(t))throw new Error("Config root must be a JSON object");let e=t;if(e.mcpServers!==void 0&&(typeof e.mcpServers!="object"||e.mcpServers===null||Array.isArray(e.mcpServers)))throw new Error("`mcpServers` must be an object");return e}function Do(t){if(!t||t.trim().length===0)return {};let e;try{e=JSON.parse(t);}catch(r){throw new Error(`Config is not valid JSON: ${r.message}`)}return ay(e)}function md(t){return JSON.stringify(t,null,2)+`
114
+ `}function Ci(t){function e(r){if(t.includeTypeField)return r;let{type:n,...i}=r;return i}return {inject(r,n){let i=Do(r),s={...i.mcpServers??{}},o=!(oe in s);s[oe]=e(n);let a={...i,mcpServers:s};return {body:md(a),wasNew:o}},remove(r){let n=Do(r),i=n.mcpServers??{};if(!(oe in i))return {body:r,wasPresent:false};let{[oe]:s,...o}=i,a={...n,mcpServers:o};return Object.keys(o).length===0&&Object.keys(a).length===1&&"mcpServers"in a?{body:null,wasPresent:true}:{body:md(a),wasPresent:true}},read(r){try{return Do(r).mcpServers?.[oe]??null}catch{return null}}}}var jo=Ci({includeTypeField:true}),_d={id:"cursor",homeConfigPath(t,e){return `${t}/.cursor/mcp.json`},inject:jo.inject,remove:jo.remove,read:jo.read};var Mo=Ci({includeTypeField:false}),wd={id:"windsurf",homeConfigPath(t,e){return `${t}/.codeium/windsurf/mcp_config.json`},inject:Mo.inject,remove:Mo.remove,read:Mo.read};var ly={"claude-code":ad,cursor:_d,codex:gd,windsurf:wd};function Ct(t){return ly[t]}Gr();F();Ee();var gy=createRequire(import.meta.url),my=gy("../package.json"),_y=my.version,wy=["claude-code","cursor","codex","windsurf"];async function Me(t,e){let r=[],n=await Ce(t);r.push({name:"auth",status:n?"pass":"fail",detail:n?n.session.user.email??n.session.user.id:"not_authenticated"});let i=null;if(n){try{let u=await D(t);r.push({name:"organization",status:u?"pass":"warn",detail:u?.slug??"no organization selected"});}catch(u){r.push({name:"organization",status:"fail",detail:u instanceof Error?u.message:String(u)});}try{let u=await M(t);i=u?.local_root_path??null,r.push({name:"workspace",status:u?"pass":"warn",detail:u?.name??"no workspace selected"});}catch(u){r.push({name:"workspace",status:"fail",detail:u instanceof Error?u.message:String(u)});}}r.push({name:"cwd_attach",status:i===e?"pass":"warn",detail:i===e?"current folder is attached":i??"workspace not attached"});let s=await Promise.all(wy.map(Cy)),o=nd(await _i(e),"cli",_y),a=o.filter(u=>u.status==="other_owner").length,l=o.filter(u=>u.status==="newer_version").length;return a>0||l>0?r.push({name:"managed_files",status:"warn",detail:ky(a,l)}):o.length>0?r.push({name:"managed_files",status:"pass",detail:`${o.length} Pathrule-managed file${o.length===1?"":"s"} tracked`}):r.push({name:"managed_files",status:"pass",detail:"no Pathrule-managed files tracked yet"}),{ok:!r.some(u=>u.status==="fail"),checks:r,mcp:s,managed_files:o}}async function Uo(t,e){await vy(t);let r=await Me(t,e),n=A(t);await mkdir(n.supportDir,{recursive:true,mode:j}),await chmod(n.supportDir,j).catch(()=>{});let i=join(n.supportDir,`${new Date().toISOString().replace(/[:.]/g,"-")}-doctor.json`),s={schema_version:1,produced_at:new Date().toISOString(),cwd_hash:Sy(e),platform:process.platform,node_version:process.version,env_keys:Object.keys(t).filter(o=>o.startsWith("PATHRULE_")||o==="CI"||o==="NO_COLOR").sort(),report:yy(r)};return El(s),await writeFile(i,JSON.stringify(s,null,2),{encoding:"utf8",mode:O}),await chmod(i,O).catch(()=>{}),{ok:r.ok,path:i,report:r}}function yy(t){return {ok:t.ok,checks:t.checks.map(e=>({...e,detail:Lo(e.detail)})),mcp:t.mcp.map(e=>({...e,config_path:by(e.config_path),error:Lo(e.error)})),managed_files:t.managed_files.map(e=>({...e,path:Lo(e.path)??e.path}))}}function ky(t,e){let r=[];return t>0&&r.push(`${t} file${t===1?"":"s"} last written by another surface`),e>0&&r.push(`${e} file${e===1?"":"s"} last written by a newer CLI`),r.join("; ")}function Lo(t){return t&&ms(t)}function by(t){return ms(t,"path")}async function vy(t){let{supabase:e}=await C(t),{data:r,error:n}=await e.rpc("consume_sensitive_action_grant",{p_action:"token_export"});if(n)throw new Error(`token_export_reauth_check_failed: ${n.message}`);if(r!==true)throw new Error("token_export_reauth_required")}function Sy(t){let e=2166136261;for(let r=0;r<t.length;r+=1)e^=t.charCodeAt(r),e=Math.imul(e,16777619);return (e>>>0).toString(16).padStart(8,"0")}async function Cy(t){let e=Ct(t),r=e.homeConfigPath(homedir(),process.platform);try{let n=await readFile(r,"utf8");return {client:t,config_path:r,readable:!0,installed:e.read(n)!==null}}catch(n){return n.code==="ENOENT"?{client:t,config_path:r,readable:false,installed:false}:{client:t,config_path:r,readable:false,installed:false,error:n instanceof Error?n.message:String(n)}}}var Et=class extends Error{constructor(e){super(e),this.name="WorkspacePathSafetyError";}};async function bd(t,e){let r=await realpath(t),n=Ry(e),i=Xe.resolve(r,n||"."),s=await realpath(i);if(!Sd(r,s))throw new Et(`Refused: ${e||"/"} escapes the workspace root`);return {rootRealPath:r,absolutePath:s,relativePath:n===""?"/":`/${xy(n)}`}}async function vd(t,e){try{let r=await realpath(e);return Sd(t,r)?(await stat(r)).isDirectory():!1}catch{return false}}function Ry(t){if(typeof t!="string")throw new Et("Refused: workspace path must be a string");if(t.includes("\0"))throw new Et("Refused: workspace path contains a null byte");let e=t.trim();if(e===""||e==="/"||e===".")return "";if(/^[a-zA-Z]:[\\/]/.test(e)||e.startsWith("\\\\"))throw new Et("Refused: absolute workspace path is not allowed");let r=e.replace(/^[/\\]+/,""),i=Xe.normalize(r).split(/[\\/]+/).filter(Boolean);if(i.includes(".."))throw new Et(`Refused: ${t} escapes the workspace root`);return i.join(Xe.sep)}function Sd(t,e){let r=kd(Xe.resolve(t)),n=kd(Xe.resolve(e)),i=r.endsWith(Xe.sep)?r:r+Xe.sep;return n===r||n.startsWith(i)}function kd(t){return process.platform==="win32"||process.platform==="darwin"?t.toLowerCase():t}function xy(t){return t.split(Xe.sep).join("/")}var Ay=new Set([".git","node_modules",".next","dist","build",".turbo",".cache","coverage","target","__pycache__",".venv","venv",".DS_Store",".idea",".vscode"]);async function Bo(t,e){let r=await bd(t,e),n=await promises.readdir(r.absolutePath,{withFileTypes:true,encoding:"utf8"}),i=[];for(let s of n){if(Ay.has(s.name))continue;let o=Xe.join(r.absolutePath,s.name),a=s.isDirectory()||s.isSymbolicLink()&&await vd(r.rootRealPath,o);i.push({absPath:o,relativePath:Iy(e,s.name),name:s.name,isDir:a});}return i.sort((s,o)=>s.isDir!==o.isDir?s.isDir?-1:1:s.name.localeCompare(o.name)),i}function Iy(t,e){return t==="/"||t===""?"/"+e:t+"/"+e}K();async function Ei(t){let e=Ed(t.env,t.workspaceId),r=false;if(t.refreshEpisodes!==false){let{error:o}=await t.supabase.rpc("pathrule_refresh_work_episodes",{p_workspace_id:t.workspaceId});r=!o;}let{data:n,error:i}=await t.supabase.rpc("pathrule_build_hook_index_payload",{p_workspace_id:t.workspaceId});if(i)return {ok:false,path:e,refreshed_episodes:r,schema_version:null,error:i.message};if(!n||typeof n!="object")return {ok:false,path:e,refreshed_episodes:r,schema_version:null,error:"empty_hook_index_payload"};let s={...n,workspace_root:t.workspaceRoot};return await jy(t.env,s),{ok:true,path:e,refreshed_episodes:r,schema_version:s.schema_version}}function Ed(t,e){return join(A(t).home,"cache",e,"hook-index.json")}async function jy(t,e){let r=Ed(t,e.workspace_id);await mkdir(join(A(t).home,"cache",e.workspace_id),{recursive:true});let n=`${r}.tmp`;await writeFile(n,JSON.stringify(e,null,2),"utf8"),await chmod(n,384),await rename(n,r);}K();F();Ge();function Rt(t,e){let r=[];r.push("<!-- Pathrule managed \u2014 do not edit; cloud state is authoritative. -->",""),r.push("# Pathrule integration",""),r.push("Pathrule is this workspace's shared memory, rule, and skill layer for AI agents.",`${e.toolLabel} should use it as a smart reminder system, not a full-context dump.`,""),r.push("## Context Policy",""),r.push("- Pathrule is the first knowledge layer for this workspace. Use hook context first: metadata, relevant rule titles, path reminders, and filename/skill matches.","- `::skill-name` is a hard gate: use the exact injected skill; if missing, stop and resolve it through Pathrule/MCP before file edits.",'- Do not reflexively call `pathrule_get_context` before every small known-path code task. For discovery, inventory, architecture, recent activity, or "list/show/find/where/which" prompts (Turkish: listele, g\xF6ster, bul, nerede, hangi, neler), call it before any grep/read/fallback when hook context is missing, ambiguous, or stale.',"- Hook silence on a topic does not mean Pathrule has no relevant memory/rule. For discovery/inventory/architecture questions, call `pathrule_get_context` first; fall back to files, git, or general knowledge only after Pathrule returns nothing relevant.","- When calling `pathrule_get_context`, pass `cwd`, `user_intent`, and `omit_protocol: true`; the companion file already contains the protocol.","- Read full bodies with `pathrule_read_memory`, `pathrule_read_rule`, or `pathrule_read_skill` when a surfaced title/id is relevant.","- Treat existing local edits as protected user/team work: inspect overlaps, never revert unrelated changes, and keep edits scoped.","- Obey every surfaced rule. If a user request conflicts with a Pathrule rule, warn before taking action.",""),r.push("## Writes",""),r.push("- Pathrule cloud is the source of truth. Do not create local memory files such as `MEMORY.md` or `~/.claude/memory/`.","- Use path-first writes for lasting project knowledge: `pathrule_write_memory`, `pathrule_write_rule`, and `pathrule_write_skill` take the most specific workspace-relative `node_path`.","- Do not edit materialized local Pathrule files as the source of truth. This includes `.codex/skills/**/SKILL.md`, `.claude/skills/**`, rendered companion files, and synced skill/memory/rule files. Read only for orientation; create/update cloud records with the Pathrule MCP write/update tools.","- After any file-modifying response, call `pathrule_log_activity` once with domain, action, scope, subjects, files_touched, and a concise task_summary.","");let n=r.join(`
115
115
  `).replace(/\n{3,}/g,`
116
116
 
117
117
  `);return n.endsWith(`
@@ -119,7 +119,7 @@ ${o}`:s||o}function Si(t,{maxDepth:e=1e3,numbersAsFloat:r=false}={}){if(sn(t)!==
119
119
  `}var Rd="AGENTS.md",xd=".codex/hooks.json",Pd=".codex/config.toml";function My(t){let e=Rt(t,{toolLabel:"Codex"}),r=dl(He()),n=Rn(null).body;return [{path:Rd,body:e},{path:xd,body:r},{path:Pd,body:n}]}function Ly(t){return [Rd,"codex.md",xd,Pd]}var Td={id:"codex",render:My,ownedPaths:Ly};var Ad=".cursor/rules/pathrule-protocol.mdc",Id=".cursorrules",Od=".cursor/hooks.json";function Uy(){return ["## Cursor-specific guardrail","","- If you call `pathrule_get_context`, include BOTH `cwd` and `user_intent`.","- `cwd` MUST be the absolute path of the active workspace root.","- Never call `pathrule_get_context` with empty args. If `cwd` is unknown, resolve it first.","","Example:","","```json",`{ "cwd": "/absolute/path/to/workspace", "user_intent": "<user's last message>", "omit_protocol": true }`,"```",""].join(`
120
120
  `)}function Wy(){return ["---",'description: "Pathrule integration \u2014 workspace-shared memories, rules, and skills"',"alwaysApply: true","---",""].join(`
121
121
  `)}function By(t){let e=Rt(t,{toolLabel:"Cursor"})+`
122
- `+Uy(),r=ul(He());return [{path:Ad,body:Wy()+e},{path:Id,body:e},{path:Od,body:r}]}function Fy(t){return [Ad,Id,Od]}var $d={id:"cursor",render:By,ownedPaths:Fy};var Nd=".windsurf/rules/pathrule-protocol.md",jd=".windsurfrules";function Hy(t){let e=Rt(t,{toolLabel:"Windsurf"});return [{path:Nd,body:e},{path:jd,body:e}]}function qy(t){return [Nd,jd]}var Dd={id:"windsurf",render:Hy,ownedPaths:qy};var zy={cursor:$d,codex:Td,windsurf:Dd};function Md(t){return zy[t]??null}async function Jy(t,e){let{data:r,error:n}=await t.from("workspaces").select("name").eq("id",e).maybeSingle();if(n)throw new Error(`workspaces lookup failed: ${n.message}`);if(!r)throw new Error(`workspace ${e} not found (RLS or deleted)`);return r.name}async function Ky(t,e){try{let r=new Date(Date.now()-12096e5).toISOString(),{data:n}=await t.from("activity_logs").select("domain, action, task_summary, created_at").eq("workspace_id",e).eq("status","active").gte("created_at",r).order("created_at",{ascending:!1}).limit(8);return n??[]}catch{return []}}async function Ld(t){let e={supabase:t.supabase},[r,n,i,s]=await Promise.all([Jy(t.supabase,t.workspaceId),vn(e,{workspace_id:t.workspaceId,relative_path:"/"}),Ut(e,{workspace_id:t.workspaceId}),Ky(t.supabase,t.workspaceId)]);if(!n.ok)throw new Error(`getContext failed: ${n.error.message}`);if(!i.ok)throw new Error(`getWorkspaceOverview failed: ${i.error.message}`);return {workspaceName:r,rootContext:{memories:n.data.memories.map(o=>({id:o.id,title:o.title,preview:o.preview})),rules:n.data.rules,skills:n.data.skills.map(o=>({id:o.id,name:o.name,description:o.description,source:o.source}))},overview:i.data,recentActivities:s.length>0?s:void 0}}function Ud(t,e){let r=[];for(let n of e){let i=Md(n);i&&r.push({client:n,files:i.render(t),ownedPaths:i.ownedPaths(t)});}return r}var Fo="<!-- Pathrule managed",Qy="<!-- managed by Pathrule";var ek={".cursor/rules/pathrule-protocol.mdc":{kind:"overwrite"},".cursorrules":{kind:"backup-on-first-write",markerSubstring:Fo},".cursor/hooks.json":{kind:"merge",merger:gl},".claude/rules/pathrule-protocol.md":{kind:"overwrite"},".claude/settings.json":{kind:"merge",merger:En},"CLAUDE.md":{kind:"backup-on-first-write",markerSubstring:Qy},"AGENTS.md":{kind:"backup-on-first-write",markerSubstring:Fo},".codex/hooks.json":{kind:"merge",merger:ml},".codex/config.toml":{kind:"merge",merger:Rn},".windsurf/rules/pathrule-protocol.md":{kind:"overwrite"},".windsurfrules":{kind:"backup-on-first-write",markerSubstring:Fo}};async function Bd(t){try{return await access(t,constants.F_OK),!0}catch{return false}}async function tk(t){if(!await Bd(t))return t;for(let e=1;e<1e3;e+=1){let r=`${t}.${e}`;if(!await Bd(r))return r}throw new Error(`Could not find a free backup name near ${t}`)}async function Ri(t){let e=ek[t.relativePath]??{kind:"overwrite"},r=join(t.workspaceRoot,t.relativePath);switch(e.kind){case "overwrite":return t.existingBody===t.renderedBody?{finalBody:null,backupPath:null}:{finalBody:t.renderedBody,backupPath:null};case "backup-on-first-write":{let n=t.existingBody!==null&&!t.existingBody.includes(e.markerSubstring)&&t.existingBody!==t.renderedBody,i=null;if(n){let s=await tk(join(dirname(r),`backup.${basename(r)}`));await rename(r,s),i=s;}return t.existingBody===t.renderedBody?{finalBody:null,backupPath:null}:{finalBody:t.renderedBody,backupPath:i}}case "merge":{let{body:n,changed:i}=e.merger(t.existingBody);return !i&&t.existingBody===n?{finalBody:null,backupPath:null}:{finalBody:n,backupPath:null}}}}async function uk(t){try{return await access(t,constants.F_OK),!0}catch{return false}}async function dk(t,e){await mkdir(dirname(t),{recursive:true});let r=`${t}.tmp`;await writeFile(r,e,"utf8"),await rename(r,t);}async function pk(t){try{return await readFile(t,"utf8")}catch(e){if(e.code==="ENOENT")return null;throw e}}async function hk(t){try{return await unlink(t),!0}catch(e){return e.code==="ENOENT",false}}async function Hd(t){let e={written:0,skipped:0,removed:0,backedUp:[],errors:[]},r=new Set,n=new Set;for(let i of t.results){let s=new Set(i.files.map(o=>o.path));for(let o of i.files){let a=join(t.workspaceRoot,o.path);try{let l=await pk(a),c=await Ri({workspaceRoot:t.workspaceRoot,relativePath:o.path,renderedBody:o.body,existingBody:l});if(c.backupPath&&e.backedUp.push(c.backupPath),c.finalBody===null){e.skipped+=1,r.add(o.path);continue}await dk(a,c.finalBody),e.written+=1,r.add(o.path);}catch(l){e.errors.push({path:o.path,message:l instanceof Error?l.message:String(l)});}}for(let o of i.ownedPaths){if(s.has(o))continue;let a=join(t.workspaceRoot,o);if(!await uk(a))continue;await hk(a)&&(e.removed+=1,n.add(o));}}if(t.runtimeOwner&&t.runtimeVersion)try{await wi({workspaceRoot:t.workspaceRoot,paths:Array.from(r),owner:t.runtimeOwner,ownerVersion:t.runtimeVersion}),await rd({workspaceRoot:t.workspaceRoot,paths:Array.from(n)});}catch(i){e.errors.push({path:".pathrule/managed-files.json",message:i instanceof Error?i.message:String(i)});}return e}var fk=["cursor","codex","windsurf"];async function gk(t,e,r){let{data:n}=await t.from("user_workspace_paths").select("selected_ai_clients").eq("workspace_id",r).eq("user_id",e).maybeSingle();return n?.selected_ai_clients??null}async function qd(t){let e={written:0,skipped:0,removed:0,backedUp:[],errors:[]};try{let[r,n]=await Promise.all([gk(t.supabase,t.userId,t.workspaceId),ze(t.workspaceRoot)]),i=In({selected:r,detected:n,fallback:Pn}),s=i.filter(c=>fk.includes(c));if(s.length===0)return {ok:!0,enabled:i,results:[],disk:e};let o=await Ld({supabase:t.supabase,workspaceId:t.workspaceId,userId:t.userId}),a=Ud(o,s),l=await Hd({workspaceRoot:t.workspaceRoot,results:a,sweepFor:s,runtimeOwner:t.runtimeOwner,runtimeVersion:t.runtimeVersion});return {ok:!0,enabled:i,results:a,disk:l}}catch(r){return {ok:false,enabled:[],results:[],disk:e,error:r instanceof Error?r.message:String(r)}}}K();var Sk=".pathrule-skills-manifest.json",ir=2;function on(){return {version:ir,skills:{}}}function an(t){return createHash("sha256").update(t,"utf8").digest("hex")}function zd(t){return join(t,".claude",Sk)}function Ck(t){if(!t||typeof t!="object")return false;let e=t;return typeof e.slug=="string"&&typeof e.hash=="string"&&typeof e.source=="string"&&(e.fetchedAt===null||typeof e.fetchedAt=="string")&&Array.isArray(e.targets)&&e.targets.every(r=>typeof r=="string")}function Ek(t){if(!t||typeof t!="object")return false;let e=t;return typeof e.path=="string"&&typeof e.hash=="string"}function Rk(t,e){if(!t||typeof t!="object"||Array.isArray(t))return null;let r={};for(let[n,i]of Object.entries(t)){if(!Ck(i)||e===ir&&i.files!==void 0&&!Array.isArray(i.files)||e===ir&&i.files?.some(s=>!Ek(s)))return null;r[n]={slug:i.slug,hash:i.hash,source:i.source,fetchedAt:i.fetchedAt,targets:i.targets,...e===ir&&i.files?{files:i.files}:{}};}return r}async function Jd(t){try{let e=await readFile(zd(t),"utf8"),r=JSON.parse(e);if(!r||typeof r!="object"||r.version!==ir&&r.version!==1)return on();let n=Rk(r.skills??{},r.version);return n?{version:ir,skills:n}:on()}catch{return on()}}async function Kd(t,e){let r=zd(t);await mkdir(dirname(r),{recursive:true});let n=`${r}.tmp`;await writeFile(n,JSON.stringify(e,null,2),"utf8"),await rename(n,r);}async function sr(t){try{return await access(t,constants.F_OK),!0}catch{return false}}async function Lk(t,e){await mkdir(dirname(t),{recursive:true});let r=`${t}.tmp`;await writeFile(r,e,"utf8"),await rename(r,t);}function Uk(t){let e=t.content??"";if(e.trim().startsWith("---"))return e.endsWith(`
122
+ `+Uy(),r=ul(He());return [{path:Ad,body:Wy()+e},{path:Id,body:e},{path:Od,body:r}]}function Fy(t){return [Ad,Id,Od]}var $d={id:"cursor",render:By,ownedPaths:Fy};var Nd=".windsurf/rules/pathrule-protocol.md",Dd=".windsurfrules";function Hy(t){let e=Rt(t,{toolLabel:"Windsurf"});return [{path:Nd,body:e},{path:Dd,body:e}]}function qy(t){return [Nd,Dd]}var jd={id:"windsurf",render:Hy,ownedPaths:qy};var zy={cursor:$d,codex:Td,windsurf:jd};function Md(t){return zy[t]??null}async function Jy(t,e){let{data:r,error:n}=await t.from("workspaces").select("name").eq("id",e).maybeSingle();if(n)throw new Error(`workspaces lookup failed: ${n.message}`);if(!r)throw new Error(`workspace ${e} not found (RLS or deleted)`);return r.name}async function Ky(t,e){try{let r=new Date(Date.now()-12096e5).toISOString(),{data:n}=await t.from("activity_logs").select("domain, action, task_summary, created_at").eq("workspace_id",e).eq("status","active").gte("created_at",r).order("created_at",{ascending:!1}).limit(8);return n??[]}catch{return []}}async function Ld(t){let e={supabase:t.supabase},[r,n,i,s]=await Promise.all([Jy(t.supabase,t.workspaceId),vn(e,{workspace_id:t.workspaceId,relative_path:"/"}),Ut(e,{workspace_id:t.workspaceId}),Ky(t.supabase,t.workspaceId)]);if(!n.ok)throw new Error(`getContext failed: ${n.error.message}`);if(!i.ok)throw new Error(`getWorkspaceOverview failed: ${i.error.message}`);return {workspaceName:r,rootContext:{memories:n.data.memories.map(o=>({id:o.id,title:o.title,preview:o.preview})),rules:n.data.rules,skills:n.data.skills.map(o=>({id:o.id,name:o.name,description:o.description,source:o.source}))},overview:i.data,recentActivities:s.length>0?s:void 0}}function Ud(t,e){let r=[];for(let n of e){let i=Md(n);i&&r.push({client:n,files:i.render(t),ownedPaths:i.ownedPaths(t)});}return r}var Fo="<!-- Pathrule managed",Qy="<!-- managed by Pathrule";var ek={".cursor/rules/pathrule-protocol.mdc":{kind:"overwrite"},".cursorrules":{kind:"backup-on-first-write",markerSubstring:Fo},".cursor/hooks.json":{kind:"merge",merger:gl},".claude/rules/pathrule-protocol.md":{kind:"overwrite"},".claude/settings.json":{kind:"merge",merger:En},"CLAUDE.md":{kind:"backup-on-first-write",markerSubstring:Qy},"AGENTS.md":{kind:"backup-on-first-write",markerSubstring:Fo},".codex/hooks.json":{kind:"merge",merger:ml},".codex/config.toml":{kind:"merge",merger:Rn},".windsurf/rules/pathrule-protocol.md":{kind:"overwrite"},".windsurfrules":{kind:"backup-on-first-write",markerSubstring:Fo}};async function Bd(t){try{return await access(t,constants.F_OK),!0}catch{return false}}async function tk(t){if(!await Bd(t))return t;for(let e=1;e<1e3;e+=1){let r=`${t}.${e}`;if(!await Bd(r))return r}throw new Error(`Could not find a free backup name near ${t}`)}async function Ri(t){let e=ek[t.relativePath]??{kind:"overwrite"},r=join(t.workspaceRoot,t.relativePath);switch(e.kind){case "overwrite":return t.existingBody===t.renderedBody?{finalBody:null,backupPath:null}:{finalBody:t.renderedBody,backupPath:null};case "backup-on-first-write":{let n=t.existingBody!==null&&!t.existingBody.includes(e.markerSubstring)&&t.existingBody!==t.renderedBody,i=null;if(n){let s=await tk(join(dirname(r),`backup.${basename(r)}`));await rename(r,s),i=s;}return t.existingBody===t.renderedBody?{finalBody:null,backupPath:null}:{finalBody:t.renderedBody,backupPath:i}}case "merge":{let{body:n,changed:i}=e.merger(t.existingBody);return !i&&t.existingBody===n?{finalBody:null,backupPath:null}:{finalBody:n,backupPath:null}}}}async function uk(t){try{return await access(t,constants.F_OK),!0}catch{return false}}async function dk(t,e){await mkdir(dirname(t),{recursive:true});let r=`${t}.tmp`;await writeFile(r,e,"utf8"),await rename(r,t);}async function pk(t){try{return await readFile(t,"utf8")}catch(e){if(e.code==="ENOENT")return null;throw e}}async function hk(t){try{return await unlink(t),!0}catch(e){return e.code==="ENOENT",false}}async function Hd(t){let e={written:0,skipped:0,removed:0,backedUp:[],errors:[]},r=new Set,n=new Set;for(let i of t.results){let s=new Set(i.files.map(o=>o.path));for(let o of i.files){let a=join(t.workspaceRoot,o.path);try{let l=await pk(a),c=await Ri({workspaceRoot:t.workspaceRoot,relativePath:o.path,renderedBody:o.body,existingBody:l});if(c.backupPath&&e.backedUp.push(c.backupPath),c.finalBody===null){e.skipped+=1,r.add(o.path);continue}await dk(a,c.finalBody),e.written+=1,r.add(o.path);}catch(l){e.errors.push({path:o.path,message:l instanceof Error?l.message:String(l)});}}for(let o of i.ownedPaths){if(s.has(o))continue;let a=join(t.workspaceRoot,o);if(!await uk(a))continue;await hk(a)&&(e.removed+=1,n.add(o));}}if(t.runtimeOwner&&t.runtimeVersion)try{await wi({workspaceRoot:t.workspaceRoot,paths:Array.from(r),owner:t.runtimeOwner,ownerVersion:t.runtimeVersion}),await rd({workspaceRoot:t.workspaceRoot,paths:Array.from(n)});}catch(i){e.errors.push({path:".pathrule/managed-files.json",message:i instanceof Error?i.message:String(i)});}return e}var fk=["cursor","codex","windsurf"];async function gk(t,e,r){let{data:n}=await t.from("user_workspace_paths").select("selected_ai_clients").eq("workspace_id",r).eq("user_id",e).maybeSingle();return n?.selected_ai_clients??null}async function qd(t){let e={written:0,skipped:0,removed:0,backedUp:[],errors:[]};try{let[r,n]=await Promise.all([gk(t.supabase,t.userId,t.workspaceId),ze(t.workspaceRoot)]),i=In({selected:r,detected:n,fallback:Pn}),s=i.filter(c=>fk.includes(c));if(s.length===0)return {ok:!0,enabled:i,results:[],disk:e};let o=await Ld({supabase:t.supabase,workspaceId:t.workspaceId,userId:t.userId}),a=Ud(o,s),l=await Hd({workspaceRoot:t.workspaceRoot,results:a,sweepFor:s,runtimeOwner:t.runtimeOwner,runtimeVersion:t.runtimeVersion});return {ok:!0,enabled:i,results:a,disk:l}}catch(r){return {ok:false,enabled:[],results:[],disk:e,error:r instanceof Error?r.message:String(r)}}}K();var Sk=".pathrule-skills-manifest.json",ir=2;function on(){return {version:ir,skills:{}}}function an(t){return createHash("sha256").update(t,"utf8").digest("hex")}function zd(t){return join(t,".claude",Sk)}function Ck(t){if(!t||typeof t!="object")return false;let e=t;return typeof e.slug=="string"&&typeof e.hash=="string"&&typeof e.source=="string"&&(e.fetchedAt===null||typeof e.fetchedAt=="string")&&Array.isArray(e.targets)&&e.targets.every(r=>typeof r=="string")}function Ek(t){if(!t||typeof t!="object")return false;let e=t;return typeof e.path=="string"&&typeof e.hash=="string"}function Rk(t,e){if(!t||typeof t!="object"||Array.isArray(t))return null;let r={};for(let[n,i]of Object.entries(t)){if(!Ck(i)||e===ir&&i.files!==void 0&&!Array.isArray(i.files)||e===ir&&i.files?.some(s=>!Ek(s)))return null;r[n]={slug:i.slug,hash:i.hash,source:i.source,fetchedAt:i.fetchedAt,targets:i.targets,...e===ir&&i.files?{files:i.files}:{}};}return r}async function Jd(t){try{let e=await readFile(zd(t),"utf8"),r=JSON.parse(e);if(!r||typeof r!="object"||r.version!==ir&&r.version!==1)return on();let n=Rk(r.skills??{},r.version);return n?{version:ir,skills:n}:on()}catch{return on()}}async function Kd(t,e){let r=zd(t);await mkdir(dirname(r),{recursive:true});let n=`${r}.tmp`;await writeFile(n,JSON.stringify(e,null,2),"utf8"),await rename(n,r);}async function sr(t){try{return await access(t,constants.F_OK),!0}catch{return false}}async function Lk(t,e){await mkdir(dirname(t),{recursive:true});let r=`${t}.tmp`;await writeFile(r,e,"utf8"),await rename(r,t);}function Uk(t){let e=t.content??"";if(e.trim().startsWith("---"))return e.endsWith(`
123
123
  `)?e:`${e}
124
124
  `;let r=t.name.replace(/"/g,"'"),n=(t.description??"").replace(/"/g,"'").replace(/\r?\n/g," ").trim();return `${`---
125
125
  name: "${r}"
@@ -139,7 +139,7 @@ ${Yd} cloud is the source of truth.
139
139
  .claude/.pathrule-skills-manifest.json
140
140
  `;async function Gk(t){let e=join(t,".gitignore");if(!await sr(e))return;let r=await readFile(e,"utf8");if(r.includes(Yd))return;let n=r.length>0&&!r.endsWith(`
141
141
  `);await appendFile(e,(n?`
142
- `:"")+Vk,"utf8");}F();F();Ee();var Yk=new Set(["write_memory","write_rule","write_skill","sync_agents","materialize_skills"]);async function ae(t,e){let{supabase:r}=await C(e),n=await j(e),i=(e.PATHRULE_WEB_URL??"https://app.pathrule.io").replace(/\/$/,"");if(!n)return or(t,"org_required",{web_url:`${i}/settings`,suggested_command_after_resolution:"pathrule org use <slug-or-id>"});let{data:s,error:o}=await r.from("organizations").select("id, slug, plan, seat_count, subscription_status").eq("id",n.id).single();if(o)throw o;let a=String(s.plan??n.plan),l=n.role,c=`${i}/org/${n.slug}/billing`;if(t==="create_workspace"){if(!eb(l))return or(t,"permission_denied",{role:l,plan:a,organization_id:n.id,web_url:`${i}/org/${n.slug}/settings/members`});let p=await Jo(r,"workspaces","organization_id",n.id,{archived_at:null}),h=Ko(a,"workspaces");return Xd(p,h)?or(t,"capacity_full",{role:l,plan:a,organization_id:n.id,usage:{dimension:"workspaces",used:p,limit:h},web_url:c,suggested_command_after_resolution:"pathrule init"}):Zd(t,{role:l,plan:a,organization_id:n.id})}let u=await M(e);if(!u)return or(t,"workspace_required",{role:l,plan:a,organization_id:n.id,web_url:`${i}/org/${n.slug}`,suggested_command_after_resolution:"pathrule workspace use <name-or-id>"});if(Yk.has(t)&&!tb(l))return or(t,"permission_denied",{role:l,plan:a,organization_id:n.id,workspace_id:u.id,web_url:`${i}/org/${n.slug}/settings/members`});let d=await Qk(t,a,u.id,r);return d&&Xd(d.used,d.limit)?or(t,"capacity_full",{role:l,plan:a,organization_id:n.id,workspace_id:u.id,usage:d,web_url:c,suggested_command_after_resolution:"pathrule status"}):Zd(t,{role:l,plan:a,organization_id:n.id,workspace_id:u.id,usage:d})}function Vo(t){return ["create_workspace","write_memory","write_rule","write_skill","sync_agents","materialize_skills"].includes(t)}function ar(t){return t.allowed?{summary:`${t.action} is allowed.`,details:[],url:null,suggested_command_after_resolution:null}:t.blocking_reason==="capacity_full"&&t.usage?{summary:`${Xk(t.usage.dimension)} limit reached on the ${t.plan??"current"} plan (${t.usage.used} / ${Zk(t.usage.limit)}).`,details:["Open Pathrule Web to upgrade or clean up usage."],url:t.web_url,suggested_command_after_resolution:t.suggested_command_after_resolution}:t.blocking_reason==="permission_denied"?{summary:`Your current role (${t.role??"unknown"}) cannot run ${t.action}.`,details:["Ask an organization admin to update your role or run the action from an admin account."],url:t.web_url,suggested_command_after_resolution:t.suggested_command_after_resolution}:t.blocking_reason==="workspace_required"?{summary:"No current workspace is selected for this folder.",details:["Run setup or choose a workspace before retrying."],url:t.web_url,suggested_command_after_resolution:t.suggested_command_after_resolution??"pathrule setup --json"}:t.blocking_reason==="org_required"?{summary:"No organization is selected.",details:["Choose an organization before retrying."],url:t.web_url,suggested_command_after_resolution:t.suggested_command_after_resolution??"pathrule org use <slug-or-id>"}:{summary:`${t.action} blocked: ${t.blocking_reason??"preflight_blocked"}.`,details:[],url:t.web_url,suggested_command_after_resolution:t.suggested_command_after_resolution}}function Xk(t){return t.charAt(0).toLocaleUpperCase("en-US")+t.slice(1)}function Zk(t){return t===-1?"unlimited":String(t)}async function Qk(t,e,r,n){return t==="write_memory"?{dimension:"memories",used:await Jo(n,"memories","workspace_id",r),limit:Ko(e,"memories")}:t==="write_rule"?{dimension:"rules",used:await Jo(n,"rules","workspace_id",r),limit:Ko(e,"rules")}:null}async function Jo(t,e,r,n,i={}){let s=t.from(e).select("id",{count:"exact",head:true}).eq(r,n);for(let l of Object.keys(i))s=s.is(l,null);let{count:o,error:a}=await s;if(a)throw a;return o??0}function eb(t){return t==="owner"||t==="admin"||t==="member"}function tb(t){return t==="owner"||t==="admin"||t==="member"}function Ko(t,e){return qe[t]?.[e]??qe.free[e]}function Xd(t,e){return e!==-1&&t>=e}function Zd(t,e={}){return {action:t,allowed:true,blocking_reason:null,role:null,plan:null,organization_id:null,workspace_id:null,usage:null,web_url:null,suggested_command_after_resolution:null,...e}}function or(t,e,r={}){return {action:t,allowed:false,blocking_reason:e,role:null,plan:null,organization_id:null,workspace_id:null,usage:null,web_url:null,suggested_command_after_resolution:null,...r}}var lb=createRequire(import.meta.url),cb=lb("../package.json"),ep="cli",tp=cb.version;async function Le(t,e,r={}){let{session:n,supabase:i}=await C(t),s=await M(t);if(!s)throw new Error("workspace_required");if(!s.local_root_path)throw new Error("workspace_not_attached");if(s.local_root_path!==e)throw new Error("workspace_cwd_mismatch");ss(join(A(t).home,"bin","pathrule-hook.js"));let o=await ae(r.skillsOnly?"materialize_skills":"sync_agents",t);if(!o.allowed)return {ok:false,workspace_id:s.id,workspace_root:s.local_root_path,preflight:o,error:o.blocking_reason??"preflight_blocked"};if(r.skillsOnly){let u=await db({supabase:i,userId:n.user.id,workspaceId:s.id,workspaceRoot:s.local_root_path});return {ok:u.errors.length===0,workspace_id:s.id,workspace_root:s.local_root_path,preflight:o,skills:{ok:u.errors.length===0,enabled:u.enabled,written:u.written,skipped:u.skipped,removed:u.removed,errors:u.errors},error:u.errors.length===0?void 0:"skill_sync_failed"}}let a=await qd({supabase:i,userId:n.user.id,workspaceId:s.id,workspaceRoot:s.local_root_path,runtimeOwner:ep,runtimeVersion:tp}),l=await ub({supabase:i,userId:n.user.id,workspaceId:s.id,workspaceRoot:s.local_root_path}),c=await Ei({supabase:i,workspaceId:s.id,workspaceRoot:s.local_root_path,env:t});return {ok:a.ok&&l.errors.length===0&&c.ok,workspace_id:s.id,workspace_root:s.local_root_path,preflight:o,companion:{ok:a.ok,enabled:a.enabled,written:a.disk.written,skipped:a.disk.skipped,removed:a.disk.removed,errors:a.disk.errors,error:a.error},claude:{ok:l.errors.length===0,written:l.written,skipped:l.skipped,backed_up:l.backedUp,errors:l.errors,snapshot_changed:l.snapshotChanged},hook_index:c,error:a.error??(l.errors.length>0?"claude_sync_failed":c.ok?void 0:"hook_index_sync_failed")}}async function ln(t,e,r,n={}){let{session:i}=await C(t),s=await ne(i.user.id,t);await ci(i.user.id,{...s,current_workspace_id:e,schema_version:1},t);try{return await Le(t,r,n)}finally{await ci(i.user.id,s,t);}}async function ub(t){let e={written:0,skipped:0,backedUp:[],errors:[],snapshotChanged:false},r=new Set,{body:n,snapshotChanged:i}=await il({supabase:t.supabase,workspaceId:t.workspaceId,userId:t.userId});e.snapshotChanged=i,await Qd(e,t.workspaceRoot,"CLAUDE.md",n)&&r.add("CLAUDE.md"),await Qd(e,t.workspaceRoot,".claude/rules/pathrule-protocol.md",fl())&&r.add(".claude/rules/pathrule-protocol.md");let s=".claude/settings.json";try{let o=join(t.workspaceRoot,s),a=await np(o),{body:l,changed:c}=En(a);c?(await rp(o,l),e.written+=1):e.skipped+=1,r.add(s);}catch(o){e.errors.push({path:s,message:o instanceof Error?o.message:String(o)});}try{await wi({workspaceRoot:t.workspaceRoot,paths:Array.from(r),owner:ep,ownerVersion:tp});}catch(o){e.errors.push({path:".pathrule/managed-files.json",message:o instanceof Error?o.message:String(o)});}return e}async function Qd(t,e,r,n){let i=join(e,r);try{let s=await np(i),o=await Ri({workspaceRoot:e,relativePath:r,renderedBody:n,existingBody:s});return o.backupPath&&t.backedUp.push(o.backupPath),o.finalBody===null?(t.skipped+=1,!0):(await rp(i,o.finalBody),t.written+=1,!0)}catch(s){return t.errors.push({path:r,message:s instanceof Error?s.message:String(s)}),false}}async function rp(t,e){await mkdir(dirname(t),{recursive:true});let r=`${t}.tmp`;await writeFile(r,e,"utf8"),await rename(r,t);}async function np(t){try{return await readFile(t,"utf8")}catch(e){if(e.code==="ENOENT")return null;throw e}}async function db(t){let[e,r]=await Promise.all([pb(t.supabase,t.userId,t.workspaceId,t.workspaceRoot),hb(t.supabase,t.workspaceId)]),n=await Gd({workspaceRoot:t.workspaceRoot,activeTargets:e,skills:r});return {enabled:e,written:n.written,skipped:n.skipped,removed:n.removed,errors:n.errors}}async function pb(t,e,r,n){let[{data:i},s]=await Promise.all([t.from("user_workspace_paths").select("selected_ai_clients").eq("workspace_id",r).eq("user_id",e).maybeSingle(),ze(n)]),o=i?.selected_ai_clients??null;return In({selected:o,detected:s,fallback:Pn})}async function hb(t,e){let{data:r,error:n}=await t.from("skills").select("id, name, description, content, source, github_url, content_fetched_at, updated_at, skill_files(path, content, sha256)").eq("workspace_id",e);if(n)throw new Error(`skill_catalogue_read_failed: ${n.message}`);return (r??[]).map(i=>({id:i.id,name:i.name,description:i.description,content:i.content,source:i.source,githubUrl:i.github_url,contentFetchedAt:i.content_fetched_at,updatedAt:i.updated_at,files:(i.skill_files??[]).map(s=>({path:s.path,content:s.content,sha256:s.sha256}))}))}async function cn(t,e){let r=await Me(t,e);try{let n=await Le(t,e),i=await Me(t,e);return {ok:n.ok&&i.ok,doctor_before:r,sync:n,doctor_after:i,error:n.ok&&i.ok?void 0:n.error??"repair_incomplete"}}catch(n){return {ok:false,doctor_before:r,error:n instanceof Error?n.message:String(n)}}}function sp(t){let e=ip(t.doctor_before.checks),r=t.doctor_after??t.doctor_before,n=ip(r.checks),i=t.sync?.preflight,s=r.mcp.filter(p=>!p.installed),o=yb(e,n),a=kb(e,n),l=bb(r.mcp),c=vb(t),u=Sb(t),d=Cb(i);return {ok:t.ok,headline:t.ok?"Local runtime repaired":"Repair incomplete",next_command:Eb(t,n,s.length),sections:[o,a,l,c,u,d]}}async function Yo(t,e={}){let{session:r,supabase:n}=await C(t),{data:i,error:s}=await n.from("user_security_state").select("security_epoch").eq("user_id",r.user.id).maybeSingle();if(s)throw s;let o=typeof i?.security_epoch=="number"?i.security_epoch:0,a=it(r.user.id,o,t),l=[];for(let c=0;c<o;c+=1){let u=join(a.userCacheDir,`epoch-${c}`),d=await wb(u);if(d===0)continue;let p=e.dryRun!==false?false:await _b(u);l.push({path:u,epoch:c,removed:p,bytes:d});}return {ok:true,dry_run:e.dryRun!==false,current_epoch:o,candidates:l,reclaimed_bytes:l.filter(c=>c.removed).reduce((c,u)=>c+u.bytes,0)}}async function _b(t){return await rm$1(t,{recursive:true,force:true}),true}async function wb(t){try{let e=await stat(t);return e.isFile()?e.size:e.isDirectory()?1:0}catch{return 0}}function ip(t){return new Map(t.map(e=>[e.name,e]))}function yb(t,e){let r=t.get("auth"),n=e.get("auth"),i=t.get("organization"),s=e.get("organization"),o=[Ti(r,n,{pass:(a,l)=>l?`Signed in again as ${a??"the current account"}.`:`Signed in as ${a??"the current account"}.`,warn:a=>`Authentication still needs attention${a?`: ${a}`:""}.`,fail:a=>`Authentication is still blocked${a?`: ${a}`:""}.`}),Ti(i,s,{pass:(a,l)=>l?`Organization context restored: ${a??"selected"}.`:`Organization context: ${a??"selected"}.`,warn:a=>`Organization selection is still missing${a&&a!=="no organization selected"?`: ${a}`:""}.`,fail:a=>`Organization lookup failed${a?`: ${a}`:""}.`})];return {title:"Account",status:op(n?.status,s?.status),lines:o}}function kb(t,e){let r=t.get("workspace"),n=e.get("workspace"),i=t.get("cwd_attach"),s=e.get("cwd_attach"),o=[Ti(r,n,{pass:(a,l)=>l?`Workspace selection recovered: ${a??"current workspace"}.`:`Workspace selection: ${a??"current workspace"}.`,warn:a=>`Workspace selection is still incomplete${a&&a!=="no workspace selected"?`: ${a}`:""}.`,fail:a=>`Workspace lookup failed${a?`: ${a}`:""}.`}),Ti(i,s,{pass:(a,l)=>l?"Current folder is attached again.":"Current folder is attached.",warn:a=>a==="workspace not attached"?"Current folder is still not attached.":`Current folder still points to ${a??"another workspace root"}.`,fail:a=>`Current folder attachment check failed${a?`: ${a}`:""}.`})];return {title:"Workspace",status:op(n?.status,s?.status),lines:o}}function bb(t){let e=t.filter(s=>s.installed).length,r=t.filter(s=>!s.installed).map(s=>s.client),n=t.filter(s=>s.error).map(s=>`${s.client}: ${s.error}`),i=[`MCP configs ready for ${e}/${t.length} supported clients.`,r.length>0?`Still missing: ${r.join(", ")}.`:"All supported MCP client configs are present."];return n.length>0&&i.push(`Agent config read errors: ${n.join("; ")}.`),{title:"Agents",status:n.length>0?"fail":r.length>0?"warn":"pass",lines:i}}function vb(t){let e=t.sync?.hook_index;return t.sync?e?{title:"Hooks",status:e.ok?"pass":"fail",lines:[e.ok?`Hook index refreshed${e.schema_version?` (schema ${e.schema_version})`:""}.`:`Hook index refresh failed: ${e.error??"unknown error"}.`,e.refreshed_episodes?"Hook work episodes were refreshed before rebuilding the index.":"Hook work episodes were left unchanged."]}:{title:"Hooks",status:"warn",lines:["Repair did not produce a hook index update."]}:{title:"Hooks",status:"warn",lines:["Repair stopped before hook files could be refreshed."]}}function Sb(t){if(!t.sync)return {title:"Files",status:"warn",lines:["Repair stopped before local files could be rewritten."]};let e=[],r="pass";return t.sync.companion&&(e.push(`Companion files: ${t.sync.companion.written} written, ${t.sync.companion.skipped} unchanged, ${t.sync.companion.removed} removed.`),(t.sync.companion.errors.length>0||!t.sync.companion.ok)&&(r="fail",e.push(`Companion errors: ${t.sync.companion.errors.map(n=>n.message).join("; ")||t.sync.companion.error||"unknown error"}.`))),t.sync.claude&&(e.push(`Claude files: ${t.sync.claude.written} written, ${t.sync.claude.skipped} unchanged, ${t.sync.claude.backed_up.length} backed up.`),t.sync.claude.errors.length>0&&(r="fail",e.push(`Claude sync errors: ${t.sync.claude.errors.map(n=>n.message).join("; ")}.`))),t.sync.skills&&(e.push(`Skills: ${t.sync.skills.written} written, ${t.sync.skills.skipped} unchanged, ${t.sync.skills.removed} removed.`),t.sync.skills.errors.length>0&&(r="fail",e.push(`Skill materialization errors: ${t.sync.skills.errors.map(n=>n.message).join("; ")}.`))),e.length===0&&e.push("No local file rewrites were needed."),{title:"Files",status:r,lines:e}}function Cb(t){return t?t.allowed?{title:"Capacity",status:"pass",lines:["No plan limit blocked this repair."]}:t.blocking_reason==="capacity_full"&&t.usage?{title:"Capacity",status:"fail",lines:[`${Rb(t.usage.dimension)} limit reached (${t.usage.used} / ${xb(t.usage.limit)}).`,"Open billing or clean up usage before retrying the repair."]}:{title:"Capacity",status:"warn",lines:["Capacity is not the blocking issue for this repair."]}:{title:"Capacity",status:"warn",lines:["Capacity checks did not run because repair stopped early."]}}function Ti(t,e,r){let n=e??t;if(!n)return "No status available.";let i=t!=null&&t.status!=="pass"&&n.status==="pass";return n.status==="pass"?r.pass(n.detail,i):n.status==="warn"?r.warn(n.detail,i):r.fail(n.detail,i)}function op(...t){return t.includes("fail")?"fail":t.includes("warn")?"warn":"pass"}function Eb(t,e,r){if(e.get("auth")?.status!=="pass")return "pathrule login";if(e.get("organization")?.status!=="pass")return "pathrule org use <slug-or-id>";if(e.get("workspace")?.status!=="pass")return "pathrule workspace use <name-or-id>";if(e.get("cwd_attach")?.status!=="pass")return "pathrule attach <workspace>";let a=t.sync?.preflight;if(a&&!a.allowed&&a.suggested_command_after_resolution)return a.suggested_command_after_resolution;if(r>0)return "pathrule install";let l=!t.sync?.companion?.ok||!!t.sync?.companion?.errors.length||!!t.sync?.claude?.errors.length||!!t.sync?.skills?.errors.length||t.sync?.hook_index?.ok===false;return !t.ok||l?"pathrule sync":"pathrule doctor"}function Rb(t){return t.charAt(0).toLocaleUpperCase("en-US")+t.slice(1)}function xb(t){return t===-1?"unlimited":String(t)}F();Vr();var Db={all:"all",claude:"claude-code","claude-code":"claude-code",cursor:"cursor",codex:"codex",windsurf:"windsurf"},Mb=["claude-code","cursor","codex","windsurf"];function lp(t){let e=Db[(t??"all").toLowerCase()];if(!e)throw new Error("invalid_install_target");return e==="all"?Mb:[e]}async function Ze(t,e){let r=lp(t),n=Lb(e);return Promise.all(r.map(async i=>{let s=Ct(i),o=s.homeConfigPath(homedir(),process.platform);try{let a=await cp(o),l=s.inject(a,n);return await up(o,l.body),{client:i,ok:!0,status:"installed",config_path:o,was_new:l.wasNew}}catch(a){return {client:i,ok:false,status:"error",config_path:o,error:a instanceof Error?a.message:String(a)}}}))}async function Xo(t){return Promise.all(lp(t).map(async e=>{let r=Ct(e),n=r.homeConfigPath(homedir(),process.platform);try{let i=await cp(n),s=r.remove(i);return s.wasPresent?(s.body===null?await rm$1(n,{force:!0}):await up(n,s.body),{client:e,ok:!0,status:"removed",config_path:n}):{client:e,ok:!0,status:"not_present",config_path:n}}catch(i){return {client:e,ok:false,status:"error",config_path:n,error:i instanceof Error?i.message:String(i)}}}))}function Lb(t){let{supabaseUrl:e,supabaseAnonKey:r}=pe(t);return {type:"stdio",command:Ub(),args:[fileURLToPath(new URL("../../mcp-server/dist/index.js",import.meta.url))],env:{SUPABASE_URL:e,SUPABASE_ANON_KEY:r}}}function Ub(){try{return execFileSync("which",["node"],{encoding:"utf8"}).trim()||process.execPath}catch{return process.execPath}}async function cp(t){try{return await readFile(t,"utf8")}catch(e){if(e.code==="ENOENT")return null;throw e}}async function up(t,e){await mkdir(dirname(t),{recursive:true});let r=`${t}.tmp`;await writeFile(r,e,"utf8"),await rename(r,t);}async function Pt(t,e,r,n){let{session:i,supabase:s}=await C(t);if(i.user.id!==e)throw new Error("session_user_mismatch");let[{data:o},a]=await Promise.all([s.from("user_workspace_paths").select("selected_ai_clients").eq("user_id",e).eq("workspace_id",r).maybeSingle(),n?ze(n):Promise.resolve([])]),l=new Set(o?.selected_ai_clients??[]),c=new Set(a),u=Object.keys(U);return Promise.all(u.map(async d=>{let p=await Jb(d);return {client:d,active:l.has(d)||c.has(d),selected:l.has(d),markers:c.has(d)?["workspace_marker_detected"]:[],machineInstalled:p.installed,machineConfigPath:p.configPath,machineConfigExists:p.configExists}}))}async function fp(t,e,r,n,i,s,o="restore-backup"){let a=Kb(i),{session:l,supabase:c}=await C(t);if(l.user.id!==e)throw new Error("session_user_mismatch");let{data:u,error:d}=await c.from("user_workspace_paths").select("selected_ai_clients").eq("user_id",e).eq("workspace_id",r).eq("local_root_path",n).maybeSingle();if(d)throw new Error(`workspace_client_selection_read_failed: ${d.message}`);if(!u)throw new Error("workspace_root_not_attached");let p=[],h=new Set((u.selected_ai_clients??[]).filter(gp)),f=Array.from(h);s?h.add(a):h.delete(a);let m=Array.from(h);if(!Vb(f,m)){let{error:w}=await c.from("user_workspace_paths").update({selected_ai_clients:m}).eq("user_id",e).eq("workspace_id",r).eq("local_root_path",n);if(w)throw new Error(`workspace_client_selection_update_failed: ${w.message}`)}if(s){let w=await Ze(a,t);for(let y of w)y.ok||p.push(`${y.client}: ${y.error??y.status}`);}else await pp(n,a);let _=await ln(t,r,n);return _.ok||p.push(_.error??"workspace_sync_failed"),s||await pp(n,a),{ok:true,statuses:await Pt(t,e,r,n),warnings:p}}async function Jb(t){let e=Ct(t),r=e.homeConfigPath(homedir(),process.platform);try{let n=await readFile(r,"utf8");return {configPath:r,configExists:!0,installed:e.read(n)!==null}}catch(n){return n.code!=="ENOENT"?{configPath:r,configExists:false,installed:false}:{configPath:r,configExists:false,installed:false}}}function Kb(t){if(gp(t))return t;throw new Error("invalid_agent_target")}function gp(t){return fs(t)!==null}function Vb(t,e){if(t.length!==e.length)return false;let r=new Set(t);return e.every(n=>r.has(n))}async function pp(t,e,r){let n=U[e]?.skillsDir;if(!n)return;let i=join(t,n);await rm$1(i,{recursive:true,force:true}),await Gb(dirname(i),t);}async function Gb(t,e){let r=resolve(e),n=resolve(t);for(;n!==r&&n.startsWith(`${r}${sep}`);){try{await rmdir(n);}catch{return}n=dirname(n);}}Ge();var Zb=promisify(execFile),Qb=2e3;function Zo(t){if(t.startsWith("/")||/^[A-Za-z]:[\\/]/.test(t))return null;let e=t.replace(/\\/g,"/").replace(/\/+/g,"/");return e.length===0||e==="."||e.startsWith("../")||e.includes("/../")||e.startsWith(".git/")||/[\x00-\x1F]/.test(e)?null:e}function ev(t){let r=(Buffer.isBuffer(t)?t.toString("utf8"):t).split("\0").filter(i=>i.length>0),n=[];for(let i=0;i<r.length;i+=1){let s=r[i];if(!s||s.length<4)continue;let o=s.slice(0,2),a=s.slice(3),l=tv(o);if(o.includes("R")||o.includes("C")){let u=Zo(a);u&&n.push({relativePath:u,gitStatus:"renamed"});let d=Zo(r[i+1]??"");d&&n.push({relativePath:d,gitStatus:"renamed"}),i+=1;continue}let c=Zo(a);c&&n.push({relativePath:c,gitStatus:l});}return rv(n)}async function mp(t,e={}){try{let{stdout:r}=await Zb("git",["status","--porcelain=v1","-z"],{cwd:t,encoding:"buffer",maxBuffer:5242880,timeout:e.timeoutMs??Qb});return {entries:ev(r),degraded:!1}}catch{return {entries:[],degraded:true}}}function tv(t){return t==="??"?"untracked":t.includes("A")?"added":t.includes("D")?"deleted":t.includes("R")||t.includes("C")?"renamed":t.includes("M")||t.includes("T")||t.includes("U")?"modified":"unknown"}function rv(t){let e=new Map;for(let r of t)e.set(r.relativePath,r);return Array.from(e.values()).sort((r,n)=>r.relativePath.localeCompare(n.relativePath))}var iv=800,sv=6e4,Ai=500,un=class{constructor(e){this.options=e;}options;dirty=new Map;pendingTimer=null;intervalTimer=null;stopped=false;degraded=false;lastScanAt=null;start(){this.intervalTimer||(this.reconcile(),this.intervalTimer=setInterval(()=>{this.reconcile();},this.options.scanIntervalMs??sv),this.intervalTimer.unref?.());}stop(){this.stopped=true,this.pendingTimer&&clearTimeout(this.pendingTimer),this.intervalTimer&&clearInterval(this.intervalTimer),this.pendingTimer=null,this.intervalTimer=null;}markActivePath(e){if(this.stopped||!ov(e))return;let r=this.isoNow();this.publishRows([{relative_path:e,is_active:true,is_dirty:this.dirty.has(e),git_status:this.dirty.get(e)?.gitStatus??"unknown",last_heartbeat_at:r,last_git_scan_at:r}],[]),this.scheduleReconcile();}scheduleReconcile(){this.stopped||(this.pendingTimer&&clearTimeout(this.pendingTimer),this.pendingTimer=setTimeout(()=>{this.pendingTimer=null,this.reconcile();},this.options.debounceMs??iv),this.pendingTimer.unref?.());}async reconcile(){if(this.stopped)return this.status();let e=this.isoNow(),r=await mp(this.options.workspaceRoot);if(this.degraded=r.degraded,r.degraded)return this.status();let n=new Map;for(let o of r.entries){let a=this.dirty.get(o.relativePath);n.set(o.relativePath,{gitStatus:o.gitStatus,firstSeenAt:a?.firstSeenAt??e});}let i=Array.from(this.dirty.keys()).filter(o=>!n.has(o));this.dirty.clear();for(let[o,a]of n)this.dirty.set(o,a);this.lastScanAt=e;let s=Array.from(n.entries()).map(([o,a])=>({relative_path:o,is_active:false,is_dirty:true,git_status:a.gitStatus,last_local_write_at:a.firstSeenAt,last_git_scan_at:e}));return await this.publishChunked(s,i),this.status()}status(){return {healthy:!this.degraded,degraded:this.degraded,lastScanAt:this.lastScanAt,dirtyPathCount:this.dirty.size}}async publishChunked(e,r){for(let n=0;n<e.length;n+=Ai)await this.publishRows(e.slice(n,n+Ai),[]);for(let n=0;n<r.length;n+=Ai)await this.publishRows([],r.slice(n,n+Ai));}async publishRows(e,r){if(e.length===0&&r.length===0)return;let{error:n}=await this.options.supabase.rpc("pathrule_upsert_file_work_state",{p_workspace_id:this.options.workspaceId,p_runtime_id:this.options.runtimeId,p_rows:e,p_clear_paths:r});n&&(this.degraded=true);}isoNow(){return (this.options.now?.()??new Date).toISOString()}};async function Qo(t,e=process.env){let r=await ne(t,e);if(r.work_state_runtime_id)return r.work_state_runtime_id;let n=`runtime:${randomUUID()}`;return await ie(t,{work_state_runtime_id:n},e),n}function ov(t){return t.length>0&&!t.startsWith("/")&&!t.startsWith("../")&&!t.includes("/../")&&!t.startsWith(".git/")&&!/[\x00-\x1F]/.test(t)}F();var Tt=new Map;async function _p(t=process.env){let{session:e,supabase:r}=await C(t),{data:n,error:i}=await r.from("user_workspace_paths").select("workspace_id, local_root_path, watcher_enabled").eq("user_id",e.user.id).eq("watcher_enabled",true);if(i)throw i;let s=await Qo(e.user.id,t);for(let o of n??[]){if(!o.workspace_id||!o.local_root_path||Tt.has(o.workspace_id))continue;let a=new un({workspaceId:o.workspace_id,workspaceRoot:o.local_root_path,userId:e.user.id,runtimeId:s,supabase:r});Tt.set(o.workspace_id,{tracker:a,workspaceRoot:o.local_root_path}),a.start();}}async function ea(t,e,r=process.env){if(Tt.has(t))return;let{session:n,supabase:i}=await C(r),s=await Qo(n.user.id,r),o=new un({workspaceId:t,workspaceRoot:e,userId:n.user.id,runtimeId:s,supabase:i});Tt.set(t,{tracker:o,workspaceRoot:e}),o.start();}async function ta(t){return Tt.get(t)?.tracker.reconcile()??null}function wp(){for(let t of Tt.values())t.tracker.stop();Tt.clear();}var ra="1.0",dr=37913,ur="127.0.0.1",wv=60,yv=createRequire(import.meta.url),kv=yv("../package.json"),fe=promisify(execFile),hn="io.pathrule.cli-daemon",Oi="pathrule-daemon.service",bv=60;async function pr(t){let e=await We(t);if(e.running)return e;let r=process.argv[1];if(!r)throw new Error("daemon_entrypoint_missing");spawn(process.execPath,[r,"daemon","run"],{detached:true,stdio:"ignore",env:{...process.env,...t}}).unref();let i=Date.now()+3e3;for(;Date.now()<i;){let s=await We(t);if(s.running)return s;await Hv(100);}throw new Error("daemon_start_timeout")}async function fn(t){let e=await We(t);if(e.state?.pid&&e.state.pid!==process.pid)try{process.kill(e.state.pid,"SIGTERM");}catch{}return await unlink(A(t).daemonFile).catch(()=>{}),We(t)}async function Pe(t=process.env){let e=Tp(t);if(!e.supported)return e;if(e.method==="task-scheduler"){let r=await Pv();return {...e,enabled:r}}return {...e,enabled:e.path?await aa(e.path):false}}async function Qe(t,e){let r=Tp(t);if(!r.supported)return r;if(e){let n=Sv(t);if(r.method==="launchd"){if(!r.path)throw new Error("daemon_autostart_path_missing");return await Cv(r.path,n,t),t.PATHRULE_SKIP_AUTOSTART_ACTIVATE!=="1"&&await Rv(r.path),Pe(t)}if(r.method==="systemd"){if(!r.path)throw new Error("daemon_autostart_path_missing");return await Ev(r.path,n,t),t.PATHRULE_SKIP_AUTOSTART_ACTIVATE!=="1"&&(await fe("systemctl",["--user","daemon-reload"]),await fe("systemctl",["--user","enable","--now",Oi])),Pe(t)}return await Tv(n,t),Pe(t)}return r.method==="launchd"?(t.PATHRULE_SKIP_AUTOSTART_ACTIVATE!=="1"&&r.path&&await xv(r.path),r.path&&await unlink(r.path).catch(()=>{}),Pe(t)):r.method==="systemd"?(t.PATHRULE_SKIP_AUTOSTART_ACTIVATE!=="1"&&(await fe("systemctl",["--user","disable","--now",Oi]).catch(()=>{}),await fe("systemctl",["--user","daemon-reload"]).catch(()=>{})),r.path&&await unlink(r.path).catch(()=>{}),Pe(t)):(await Av(),Pe(t))}async function We(t){let e=A(t).daemonFile,r;try{r=JSON.parse(await readFile(e,"utf8"));}catch(i){let s=i.code==="ENOENT"?"missing":"unreadable";return await kp(t)?{running:true,state:null,state_path:e,reason:"probed"}:{running:false,state:null,state_path:e,reason:s}}let n=Fv(r.pid);return !n&&await kp(t)?{running:true,state:null,state_path:e,reason:"probed"}:{running:n,state:r,state_path:e,reason:n?void 0:"stale"}}async function kp(t){let e=vv(t);if(e===0)return false;let r=new AbortController,n=setTimeout(()=>r.abort(),250);try{let i=await fetch(`http://${ur}:${e}/v1/status`,{signal:r.signal});if(!i.ok)return !1;let s=await i.json();return s.daemon_present===!0&&typeof s.protocol_version=="string"}catch{return false}finally{clearTimeout(n);}}function vv(t){let e=t.PATHRULE_DAEMON_PORT?.trim()||String(dr),r=Number(e);return Number.isInteger(r)&&r>=0&&r<=65535?r:dr}function Tp(t){let e=t.PATHRULE_TEST_PLATFORM??process.platform,r=t.PATHRULE_AUTOSTART_DIR;return e==="darwin"?{supported:true,enabled:false,method:"launchd",path:r?join(r,`${hn}.plist`):join(homedir(),"Library","LaunchAgents",`${hn}.plist`)}:e==="linux"?{supported:true,enabled:false,method:"systemd",path:r?join(r,Oi):join(homedir(),".config","systemd","user",Oi)}:e==="win32"?{supported:false,enabled:false,method:"task-scheduler",path:null,reason:"Windows daemon autostart requires installer support."}:{supported:false,enabled:false,method:"unsupported",path:null,reason:`Unsupported platform: ${e}`}}function Sv(t){let e=t.PATHRULE_CLI_ENTRYPOINT?.trim()||process.argv[1];if(!e)throw new Error("daemon_entrypoint_missing");return {command:process.execPath,args:[e,"daemon","run"]}}function oa(t){let e={PATHRULE_DAEMON_PORT:t.PATHRULE_DAEMON_PORT?.trim()||String(dr)};for(let r of ["PATH","PATHRULE_HOME","PATHRULE_WEB_URL"]){let n=t[r];n&&n.trim()!==""&&(e[r]=n);}return e}async function Cv(t,e,r){let n=`<?xml version="1.0" encoding="UTF-8"?>
142
+ `:"")+Vk,"utf8");}F();F();Ee();var Yk=new Set(["write_memory","write_rule","write_skill","sync_agents","materialize_skills"]);async function ae(t,e){let{supabase:r}=await C(e),n=await D(e),i=(e.PATHRULE_WEB_URL??"https://app.pathrule.io").replace(/\/$/,"");if(!n)return or(t,"org_required",{web_url:`${i}/settings`,suggested_command_after_resolution:"pathrule org use <slug-or-id>"});let{data:s,error:o}=await r.from("organizations").select("id, slug, plan, seat_count, subscription_status").eq("id",n.id).single();if(o)throw o;let a=String(s.plan??n.plan),l=n.role,c=`${i}/org/${n.slug}/billing`;if(t==="create_workspace"){if(!eb(l))return or(t,"permission_denied",{role:l,plan:a,organization_id:n.id,web_url:`${i}/org/${n.slug}/settings/members`});let p=await Jo(r,"workspaces","organization_id",n.id,{archived_at:null}),h=Ko(a,"workspaces");return Xd(p,h)?or(t,"capacity_full",{role:l,plan:a,organization_id:n.id,usage:{dimension:"workspaces",used:p,limit:h},web_url:c,suggested_command_after_resolution:"pathrule init"}):Zd(t,{role:l,plan:a,organization_id:n.id})}let u=await M(e);if(!u)return or(t,"workspace_required",{role:l,plan:a,organization_id:n.id,web_url:`${i}/org/${n.slug}`,suggested_command_after_resolution:"pathrule workspace use <name-or-id>"});if(Yk.has(t)&&!tb(l))return or(t,"permission_denied",{role:l,plan:a,organization_id:n.id,workspace_id:u.id,web_url:`${i}/org/${n.slug}/settings/members`});let d=await Qk(t,a,u.id,r);return d&&Xd(d.used,d.limit)?or(t,"capacity_full",{role:l,plan:a,organization_id:n.id,workspace_id:u.id,usage:d,web_url:c,suggested_command_after_resolution:"pathrule status"}):Zd(t,{role:l,plan:a,organization_id:n.id,workspace_id:u.id,usage:d})}function Vo(t){return ["create_workspace","write_memory","write_rule","write_skill","sync_agents","materialize_skills"].includes(t)}function ar(t){return t.allowed?{summary:`${t.action} is allowed.`,details:[],url:null,suggested_command_after_resolution:null}:t.blocking_reason==="capacity_full"&&t.usage?{summary:`${Xk(t.usage.dimension)} limit reached on the ${t.plan??"current"} plan (${t.usage.used} / ${Zk(t.usage.limit)}).`,details:["Open Pathrule Web to upgrade or clean up usage."],url:t.web_url,suggested_command_after_resolution:t.suggested_command_after_resolution}:t.blocking_reason==="permission_denied"?{summary:`Your current role (${t.role??"unknown"}) cannot run ${t.action}.`,details:["Ask an organization admin to update your role or run the action from an admin account."],url:t.web_url,suggested_command_after_resolution:t.suggested_command_after_resolution}:t.blocking_reason==="workspace_required"?{summary:"No current workspace is selected for this folder.",details:["Run setup or choose a workspace before retrying."],url:t.web_url,suggested_command_after_resolution:t.suggested_command_after_resolution??"pathrule setup --json"}:t.blocking_reason==="org_required"?{summary:"No organization is selected.",details:["Choose an organization before retrying."],url:t.web_url,suggested_command_after_resolution:t.suggested_command_after_resolution??"pathrule org use <slug-or-id>"}:{summary:`${t.action} blocked: ${t.blocking_reason??"preflight_blocked"}.`,details:[],url:t.web_url,suggested_command_after_resolution:t.suggested_command_after_resolution}}function Xk(t){return t.charAt(0).toLocaleUpperCase("en-US")+t.slice(1)}function Zk(t){return t===-1?"unlimited":String(t)}async function Qk(t,e,r,n){return t==="write_memory"?{dimension:"memories",used:await Jo(n,"memories","workspace_id",r),limit:Ko(e,"memories")}:t==="write_rule"?{dimension:"rules",used:await Jo(n,"rules","workspace_id",r),limit:Ko(e,"rules")}:null}async function Jo(t,e,r,n,i={}){let s=t.from(e).select("id",{count:"exact",head:true}).eq(r,n);for(let l of Object.keys(i))s=s.is(l,null);let{count:o,error:a}=await s;if(a)throw a;return o??0}function eb(t){return t==="owner"||t==="admin"||t==="member"}function tb(t){return t==="owner"||t==="admin"||t==="member"}function Ko(t,e){return qe[t]?.[e]??qe.free[e]}function Xd(t,e){return e!==-1&&t>=e}function Zd(t,e={}){return {action:t,allowed:true,blocking_reason:null,role:null,plan:null,organization_id:null,workspace_id:null,usage:null,web_url:null,suggested_command_after_resolution:null,...e}}function or(t,e,r={}){return {action:t,allowed:false,blocking_reason:e,role:null,plan:null,organization_id:null,workspace_id:null,usage:null,web_url:null,suggested_command_after_resolution:null,...r}}var lb=createRequire(import.meta.url),cb=lb("../package.json"),ep="cli",tp=cb.version;async function Le(t,e,r={}){let{session:n,supabase:i}=await C(t),s=await M(t);if(!s)throw new Error("workspace_required");if(!s.local_root_path)throw new Error("workspace_not_attached");if(s.local_root_path!==e)throw new Error("workspace_cwd_mismatch");ss(join(A(t).home,"bin","pathrule-hook.js"));let o=await ae(r.skillsOnly?"materialize_skills":"sync_agents",t);if(!o.allowed)return {ok:false,workspace_id:s.id,workspace_root:s.local_root_path,preflight:o,error:o.blocking_reason??"preflight_blocked"};if(r.skillsOnly){let u=await db({supabase:i,userId:n.user.id,workspaceId:s.id,workspaceRoot:s.local_root_path});return {ok:u.errors.length===0,workspace_id:s.id,workspace_root:s.local_root_path,preflight:o,skills:{ok:u.errors.length===0,enabled:u.enabled,written:u.written,skipped:u.skipped,removed:u.removed,errors:u.errors},error:u.errors.length===0?void 0:"skill_sync_failed"}}let a=await qd({supabase:i,userId:n.user.id,workspaceId:s.id,workspaceRoot:s.local_root_path,runtimeOwner:ep,runtimeVersion:tp}),l=await ub({supabase:i,userId:n.user.id,workspaceId:s.id,workspaceRoot:s.local_root_path}),c=await Ei({supabase:i,workspaceId:s.id,workspaceRoot:s.local_root_path,env:t});return {ok:a.ok&&l.errors.length===0&&c.ok,workspace_id:s.id,workspace_root:s.local_root_path,preflight:o,companion:{ok:a.ok,enabled:a.enabled,written:a.disk.written,skipped:a.disk.skipped,removed:a.disk.removed,errors:a.disk.errors,error:a.error},claude:{ok:l.errors.length===0,written:l.written,skipped:l.skipped,backed_up:l.backedUp,errors:l.errors,snapshot_changed:l.snapshotChanged},hook_index:c,error:a.error??(l.errors.length>0?"claude_sync_failed":c.ok?void 0:"hook_index_sync_failed")}}async function ln(t,e,r,n={}){let{session:i}=await C(t),s=await ne(i.user.id,t);await ci(i.user.id,{...s,current_workspace_id:e,schema_version:1},t);try{return await Le(t,r,n)}finally{await ci(i.user.id,s,t);}}async function ub(t){let e={written:0,skipped:0,backedUp:[],errors:[],snapshotChanged:false},r=new Set,{body:n,snapshotChanged:i}=await il({supabase:t.supabase,workspaceId:t.workspaceId,userId:t.userId});e.snapshotChanged=i,await Qd(e,t.workspaceRoot,"CLAUDE.md",n)&&r.add("CLAUDE.md"),await Qd(e,t.workspaceRoot,".claude/rules/pathrule-protocol.md",fl())&&r.add(".claude/rules/pathrule-protocol.md");let s=".claude/settings.json";try{let o=join(t.workspaceRoot,s),a=await np(o),{body:l,changed:c}=En(a);c?(await rp(o,l),e.written+=1):e.skipped+=1,r.add(s);}catch(o){e.errors.push({path:s,message:o instanceof Error?o.message:String(o)});}try{await wi({workspaceRoot:t.workspaceRoot,paths:Array.from(r),owner:ep,ownerVersion:tp});}catch(o){e.errors.push({path:".pathrule/managed-files.json",message:o instanceof Error?o.message:String(o)});}return e}async function Qd(t,e,r,n){let i=join(e,r);try{let s=await np(i),o=await Ri({workspaceRoot:e,relativePath:r,renderedBody:n,existingBody:s});return o.backupPath&&t.backedUp.push(o.backupPath),o.finalBody===null?(t.skipped+=1,!0):(await rp(i,o.finalBody),t.written+=1,!0)}catch(s){return t.errors.push({path:r,message:s instanceof Error?s.message:String(s)}),false}}async function rp(t,e){await mkdir(dirname(t),{recursive:true});let r=`${t}.tmp`;await writeFile(r,e,"utf8"),await rename(r,t);}async function np(t){try{return await readFile(t,"utf8")}catch(e){if(e.code==="ENOENT")return null;throw e}}async function db(t){let[e,r]=await Promise.all([pb(t.supabase,t.userId,t.workspaceId,t.workspaceRoot),hb(t.supabase,t.workspaceId)]),n=await Gd({workspaceRoot:t.workspaceRoot,activeTargets:e,skills:r});return {enabled:e,written:n.written,skipped:n.skipped,removed:n.removed,errors:n.errors}}async function pb(t,e,r,n){let[{data:i},s]=await Promise.all([t.from("user_workspace_paths").select("selected_ai_clients").eq("workspace_id",r).eq("user_id",e).maybeSingle(),ze(n)]),o=i?.selected_ai_clients??null;return In({selected:o,detected:s,fallback:Pn})}async function hb(t,e){let{data:r,error:n}=await t.from("skills").select("id, name, description, content, source, github_url, content_fetched_at, updated_at, skill_files(path, content, sha256)").eq("workspace_id",e);if(n)throw new Error(`skill_catalogue_read_failed: ${n.message}`);return (r??[]).map(i=>({id:i.id,name:i.name,description:i.description,content:i.content,source:i.source,githubUrl:i.github_url,contentFetchedAt:i.content_fetched_at,updatedAt:i.updated_at,files:(i.skill_files??[]).map(s=>({path:s.path,content:s.content,sha256:s.sha256}))}))}async function cn(t,e){let r=await Me(t,e);try{let n=await Le(t,e),i=await Me(t,e);return {ok:n.ok&&i.ok,doctor_before:r,sync:n,doctor_after:i,error:n.ok&&i.ok?void 0:n.error??"repair_incomplete"}}catch(n){return {ok:false,doctor_before:r,error:n instanceof Error?n.message:String(n)}}}function sp(t){let e=ip(t.doctor_before.checks),r=t.doctor_after??t.doctor_before,n=ip(r.checks),i=t.sync?.preflight,s=r.mcp.filter(p=>!p.installed),o=yb(e,n),a=kb(e,n),l=bb(r.mcp),c=vb(t),u=Sb(t),d=Cb(i);return {ok:t.ok,headline:t.ok?"Local runtime repaired":"Repair incomplete",next_command:Eb(t,n,s.length),sections:[o,a,l,c,u,d]}}async function Yo(t,e={}){let{session:r,supabase:n}=await C(t),{data:i,error:s}=await n.from("user_security_state").select("security_epoch").eq("user_id",r.user.id).maybeSingle();if(s)throw s;let o=typeof i?.security_epoch=="number"?i.security_epoch:0,a=it(r.user.id,o,t),l=[];for(let c=0;c<o;c+=1){let u=join(a.userCacheDir,`epoch-${c}`),d=await wb(u);if(d===0)continue;let p=e.dryRun!==false?false:await _b(u);l.push({path:u,epoch:c,removed:p,bytes:d});}return {ok:true,dry_run:e.dryRun!==false,current_epoch:o,candidates:l,reclaimed_bytes:l.filter(c=>c.removed).reduce((c,u)=>c+u.bytes,0)}}async function _b(t){return await rm$1(t,{recursive:true,force:true}),true}async function wb(t){try{let e=await stat(t);return e.isFile()?e.size:e.isDirectory()?1:0}catch{return 0}}function ip(t){return new Map(t.map(e=>[e.name,e]))}function yb(t,e){let r=t.get("auth"),n=e.get("auth"),i=t.get("organization"),s=e.get("organization"),o=[Ti(r,n,{pass:(a,l)=>l?`Signed in again as ${a??"the current account"}.`:`Signed in as ${a??"the current account"}.`,warn:a=>`Authentication still needs attention${a?`: ${a}`:""}.`,fail:a=>`Authentication is still blocked${a?`: ${a}`:""}.`}),Ti(i,s,{pass:(a,l)=>l?`Organization context restored: ${a??"selected"}.`:`Organization context: ${a??"selected"}.`,warn:a=>`Organization selection is still missing${a&&a!=="no organization selected"?`: ${a}`:""}.`,fail:a=>`Organization lookup failed${a?`: ${a}`:""}.`})];return {title:"Account",status:op(n?.status,s?.status),lines:o}}function kb(t,e){let r=t.get("workspace"),n=e.get("workspace"),i=t.get("cwd_attach"),s=e.get("cwd_attach"),o=[Ti(r,n,{pass:(a,l)=>l?`Workspace selection recovered: ${a??"current workspace"}.`:`Workspace selection: ${a??"current workspace"}.`,warn:a=>`Workspace selection is still incomplete${a&&a!=="no workspace selected"?`: ${a}`:""}.`,fail:a=>`Workspace lookup failed${a?`: ${a}`:""}.`}),Ti(i,s,{pass:(a,l)=>l?"Current folder is attached again.":"Current folder is attached.",warn:a=>a==="workspace not attached"?"Current folder is still not attached.":`Current folder still points to ${a??"another workspace root"}.`,fail:a=>`Current folder attachment check failed${a?`: ${a}`:""}.`})];return {title:"Workspace",status:op(n?.status,s?.status),lines:o}}function bb(t){let e=t.filter(s=>s.installed).length,r=t.filter(s=>!s.installed).map(s=>s.client),n=t.filter(s=>s.error).map(s=>`${s.client}: ${s.error}`),i=[`MCP configs ready for ${e}/${t.length} supported clients.`,r.length>0?`Still missing: ${r.join(", ")}.`:"All supported MCP client configs are present."];return n.length>0&&i.push(`Agent config read errors: ${n.join("; ")}.`),{title:"Agents",status:n.length>0?"fail":r.length>0?"warn":"pass",lines:i}}function vb(t){let e=t.sync?.hook_index;return t.sync?e?{title:"Hooks",status:e.ok?"pass":"fail",lines:[e.ok?`Hook index refreshed${e.schema_version?` (schema ${e.schema_version})`:""}.`:`Hook index refresh failed: ${e.error??"unknown error"}.`,e.refreshed_episodes?"Hook work episodes were refreshed before rebuilding the index.":"Hook work episodes were left unchanged."]}:{title:"Hooks",status:"warn",lines:["Repair did not produce a hook index update."]}:{title:"Hooks",status:"warn",lines:["Repair stopped before hook files could be refreshed."]}}function Sb(t){if(!t.sync)return {title:"Files",status:"warn",lines:["Repair stopped before local files could be rewritten."]};let e=[],r="pass";return t.sync.companion&&(e.push(`Companion files: ${t.sync.companion.written} written, ${t.sync.companion.skipped} unchanged, ${t.sync.companion.removed} removed.`),(t.sync.companion.errors.length>0||!t.sync.companion.ok)&&(r="fail",e.push(`Companion errors: ${t.sync.companion.errors.map(n=>n.message).join("; ")||t.sync.companion.error||"unknown error"}.`))),t.sync.claude&&(e.push(`Claude files: ${t.sync.claude.written} written, ${t.sync.claude.skipped} unchanged, ${t.sync.claude.backed_up.length} backed up.`),t.sync.claude.errors.length>0&&(r="fail",e.push(`Claude sync errors: ${t.sync.claude.errors.map(n=>n.message).join("; ")}.`))),t.sync.skills&&(e.push(`Skills: ${t.sync.skills.written} written, ${t.sync.skills.skipped} unchanged, ${t.sync.skills.removed} removed.`),t.sync.skills.errors.length>0&&(r="fail",e.push(`Skill materialization errors: ${t.sync.skills.errors.map(n=>n.message).join("; ")}.`))),e.length===0&&e.push("No local file rewrites were needed."),{title:"Files",status:r,lines:e}}function Cb(t){return t?t.allowed?{title:"Capacity",status:"pass",lines:["No plan limit blocked this repair."]}:t.blocking_reason==="capacity_full"&&t.usage?{title:"Capacity",status:"fail",lines:[`${Rb(t.usage.dimension)} limit reached (${t.usage.used} / ${xb(t.usage.limit)}).`,"Open billing or clean up usage before retrying the repair."]}:{title:"Capacity",status:"warn",lines:["Capacity is not the blocking issue for this repair."]}:{title:"Capacity",status:"warn",lines:["Capacity checks did not run because repair stopped early."]}}function Ti(t,e,r){let n=e??t;if(!n)return "No status available.";let i=t!=null&&t.status!=="pass"&&n.status==="pass";return n.status==="pass"?r.pass(n.detail,i):n.status==="warn"?r.warn(n.detail,i):r.fail(n.detail,i)}function op(...t){return t.includes("fail")?"fail":t.includes("warn")?"warn":"pass"}function Eb(t,e,r){if(e.get("auth")?.status!=="pass")return "pathrule login";if(e.get("organization")?.status!=="pass")return "pathrule org use <slug-or-id>";if(e.get("workspace")?.status!=="pass")return "pathrule workspace use <name-or-id>";if(e.get("cwd_attach")?.status!=="pass")return "pathrule attach <workspace>";let a=t.sync?.preflight;if(a&&!a.allowed&&a.suggested_command_after_resolution)return a.suggested_command_after_resolution;if(r>0)return "pathrule install";let l=!t.sync?.companion?.ok||!!t.sync?.companion?.errors.length||!!t.sync?.claude?.errors.length||!!t.sync?.skills?.errors.length||t.sync?.hook_index?.ok===false;return !t.ok||l?"pathrule sync":"pathrule doctor"}function Rb(t){return t.charAt(0).toLocaleUpperCase("en-US")+t.slice(1)}function xb(t){return t===-1?"unlimited":String(t)}F();Vr();var jb={all:"all",claude:"claude-code","claude-code":"claude-code",cursor:"cursor",codex:"codex",windsurf:"windsurf"},Mb=["claude-code","cursor","codex","windsurf"];function lp(t){let e=jb[(t??"all").toLowerCase()];if(!e)throw new Error("invalid_install_target");return e==="all"?Mb:[e]}async function Ze(t,e){let r=lp(t),n=Lb(e);return Promise.all(r.map(async i=>{let s=Ct(i),o=s.homeConfigPath(homedir(),process.platform);try{let a=await cp(o),l=s.inject(a,n);return await up(o,l.body),{client:i,ok:!0,status:"installed",config_path:o,was_new:l.wasNew}}catch(a){return {client:i,ok:false,status:"error",config_path:o,error:a instanceof Error?a.message:String(a)}}}))}async function Xo(t){return Promise.all(lp(t).map(async e=>{let r=Ct(e),n=r.homeConfigPath(homedir(),process.platform);try{let i=await cp(n),s=r.remove(i);return s.wasPresent?(s.body===null?await rm$1(n,{force:!0}):await up(n,s.body),{client:e,ok:!0,status:"removed",config_path:n}):{client:e,ok:!0,status:"not_present",config_path:n}}catch(i){return {client:e,ok:false,status:"error",config_path:n,error:i instanceof Error?i.message:String(i)}}}))}function Lb(t){let{supabaseUrl:e,supabaseAnonKey:r}=pe(t);return {type:"stdio",command:Ub(),args:[fileURLToPath(new URL("../../mcp-server/dist/index.js",import.meta.url))],env:{SUPABASE_URL:e,SUPABASE_ANON_KEY:r}}}function Ub(){try{return execFileSync("which",["node"],{encoding:"utf8"}).trim()||process.execPath}catch{return process.execPath}}async function cp(t){try{return await readFile(t,"utf8")}catch(e){if(e.code==="ENOENT")return null;throw e}}async function up(t,e){await mkdir(dirname(t),{recursive:true});let r=`${t}.tmp`;await writeFile(r,e,"utf8"),await rename(r,t);}async function Pt(t,e,r,n){let{session:i,supabase:s}=await C(t);if(i.user.id!==e)throw new Error("session_user_mismatch");let[{data:o},a]=await Promise.all([s.from("user_workspace_paths").select("selected_ai_clients").eq("user_id",e).eq("workspace_id",r).maybeSingle(),n?ze(n):Promise.resolve([])]),l=new Set(o?.selected_ai_clients??[]),c=new Set(a),u=Object.keys(U);return Promise.all(u.map(async d=>{let p=await Jb(d);return {client:d,active:l.has(d)||c.has(d),selected:l.has(d),markers:c.has(d)?["workspace_marker_detected"]:[],machineInstalled:p.installed,machineConfigPath:p.configPath,machineConfigExists:p.configExists}}))}async function fp(t,e,r,n,i,s,o="restore-backup"){let a=Kb(i),{session:l,supabase:c}=await C(t);if(l.user.id!==e)throw new Error("session_user_mismatch");let{data:u,error:d}=await c.from("user_workspace_paths").select("selected_ai_clients").eq("user_id",e).eq("workspace_id",r).eq("local_root_path",n).maybeSingle();if(d)throw new Error(`workspace_client_selection_read_failed: ${d.message}`);if(!u)throw new Error("workspace_root_not_attached");let p=[],h=new Set((u.selected_ai_clients??[]).filter(gp)),f=Array.from(h);s?h.add(a):h.delete(a);let m=Array.from(h);if(!Vb(f,m)){let{error:w}=await c.from("user_workspace_paths").update({selected_ai_clients:m}).eq("user_id",e).eq("workspace_id",r).eq("local_root_path",n);if(w)throw new Error(`workspace_client_selection_update_failed: ${w.message}`)}if(s){let w=await Ze(a,t);for(let y of w)y.ok||p.push(`${y.client}: ${y.error??y.status}`);}else await pp(n,a);let _=await ln(t,r,n);return _.ok||p.push(_.error??"workspace_sync_failed"),s||await pp(n,a),{ok:true,statuses:await Pt(t,e,r,n),warnings:p}}async function Jb(t){let e=Ct(t),r=e.homeConfigPath(homedir(),process.platform);try{let n=await readFile(r,"utf8");return {configPath:r,configExists:!0,installed:e.read(n)!==null}}catch(n){return n.code!=="ENOENT"?{configPath:r,configExists:false,installed:false}:{configPath:r,configExists:false,installed:false}}}function Kb(t){if(gp(t))return t;throw new Error("invalid_agent_target")}function gp(t){return fs(t)!==null}function Vb(t,e){if(t.length!==e.length)return false;let r=new Set(t);return e.every(n=>r.has(n))}async function pp(t,e,r){let n=U[e]?.skillsDir;if(!n)return;let i=join(t,n);await rm$1(i,{recursive:true,force:true}),await Gb(dirname(i),t);}async function Gb(t,e){let r=resolve(e),n=resolve(t);for(;n!==r&&n.startsWith(`${r}${sep}`);){try{await rmdir(n);}catch{return}n=dirname(n);}}Ge();var Zb=promisify(execFile),Qb=2e3;function Zo(t){if(t.startsWith("/")||/^[A-Za-z]:[\\/]/.test(t))return null;let e=t.replace(/\\/g,"/").replace(/\/+/g,"/");return e.length===0||e==="."||e.startsWith("../")||e.includes("/../")||e.startsWith(".git/")||/[\x00-\x1F]/.test(e)?null:e}function ev(t){let r=(Buffer.isBuffer(t)?t.toString("utf8"):t).split("\0").filter(i=>i.length>0),n=[];for(let i=0;i<r.length;i+=1){let s=r[i];if(!s||s.length<4)continue;let o=s.slice(0,2),a=s.slice(3),l=tv(o);if(o.includes("R")||o.includes("C")){let u=Zo(a);u&&n.push({relativePath:u,gitStatus:"renamed"});let d=Zo(r[i+1]??"");d&&n.push({relativePath:d,gitStatus:"renamed"}),i+=1;continue}let c=Zo(a);c&&n.push({relativePath:c,gitStatus:l});}return rv(n)}async function mp(t,e={}){try{let{stdout:r}=await Zb("git",["status","--porcelain=v1","-z"],{cwd:t,encoding:"buffer",maxBuffer:5242880,timeout:e.timeoutMs??Qb});return {entries:ev(r),degraded:!1}}catch{return {entries:[],degraded:true}}}function tv(t){return t==="??"?"untracked":t.includes("A")?"added":t.includes("D")?"deleted":t.includes("R")||t.includes("C")?"renamed":t.includes("M")||t.includes("T")||t.includes("U")?"modified":"unknown"}function rv(t){let e=new Map;for(let r of t)e.set(r.relativePath,r);return Array.from(e.values()).sort((r,n)=>r.relativePath.localeCompare(n.relativePath))}var iv=800,sv=6e4,Ai=500,un=class{constructor(e){this.options=e;}options;dirty=new Map;pendingTimer=null;intervalTimer=null;stopped=false;degraded=false;lastScanAt=null;start(){this.intervalTimer||(this.reconcile(),this.intervalTimer=setInterval(()=>{this.reconcile();},this.options.scanIntervalMs??sv),this.intervalTimer.unref?.());}stop(){this.stopped=true,this.pendingTimer&&clearTimeout(this.pendingTimer),this.intervalTimer&&clearInterval(this.intervalTimer),this.pendingTimer=null,this.intervalTimer=null;}markActivePath(e){if(this.stopped||!ov(e))return;let r=this.isoNow();this.publishRows([{relative_path:e,is_active:true,is_dirty:this.dirty.has(e),git_status:this.dirty.get(e)?.gitStatus??"unknown",last_heartbeat_at:r,last_git_scan_at:r}],[]),this.scheduleReconcile();}scheduleReconcile(){this.stopped||(this.pendingTimer&&clearTimeout(this.pendingTimer),this.pendingTimer=setTimeout(()=>{this.pendingTimer=null,this.reconcile();},this.options.debounceMs??iv),this.pendingTimer.unref?.());}async reconcile(){if(this.stopped)return this.status();let e=this.isoNow(),r=await mp(this.options.workspaceRoot);if(this.degraded=r.degraded,r.degraded)return this.status();let n=new Map;for(let o of r.entries){let a=this.dirty.get(o.relativePath);n.set(o.relativePath,{gitStatus:o.gitStatus,firstSeenAt:a?.firstSeenAt??e});}let i=Array.from(this.dirty.keys()).filter(o=>!n.has(o));this.dirty.clear();for(let[o,a]of n)this.dirty.set(o,a);this.lastScanAt=e;let s=Array.from(n.entries()).map(([o,a])=>({relative_path:o,is_active:false,is_dirty:true,git_status:a.gitStatus,last_local_write_at:a.firstSeenAt,last_git_scan_at:e}));return await this.publishChunked(s,i),this.status()}status(){return {healthy:!this.degraded,degraded:this.degraded,lastScanAt:this.lastScanAt,dirtyPathCount:this.dirty.size}}async publishChunked(e,r){for(let n=0;n<e.length;n+=Ai)await this.publishRows(e.slice(n,n+Ai),[]);for(let n=0;n<r.length;n+=Ai)await this.publishRows([],r.slice(n,n+Ai));}async publishRows(e,r){if(e.length===0&&r.length===0)return;let{error:n}=await this.options.supabase.rpc("pathrule_upsert_file_work_state",{p_workspace_id:this.options.workspaceId,p_runtime_id:this.options.runtimeId,p_rows:e,p_clear_paths:r});n&&(this.degraded=true);}isoNow(){return (this.options.now?.()??new Date).toISOString()}};async function Qo(t,e=process.env){let r=await ne(t,e);if(r.work_state_runtime_id)return r.work_state_runtime_id;let n=`runtime:${randomUUID()}`;return await ie(t,{work_state_runtime_id:n},e),n}function ov(t){return t.length>0&&!t.startsWith("/")&&!t.startsWith("../")&&!t.includes("/../")&&!t.startsWith(".git/")&&!/[\x00-\x1F]/.test(t)}F();var Tt=new Map;async function _p(t=process.env){let{session:e,supabase:r}=await C(t),{data:n,error:i}=await r.from("user_workspace_paths").select("workspace_id, local_root_path, watcher_enabled").eq("user_id",e.user.id).eq("watcher_enabled",true);if(i)throw i;let s=await Qo(e.user.id,t);for(let o of n??[]){if(!o.workspace_id||!o.local_root_path||Tt.has(o.workspace_id))continue;let a=new un({workspaceId:o.workspace_id,workspaceRoot:o.local_root_path,userId:e.user.id,runtimeId:s,supabase:r});Tt.set(o.workspace_id,{tracker:a,workspaceRoot:o.local_root_path}),a.start();}}async function ea(t,e,r=process.env){if(Tt.has(t))return;let{session:n,supabase:i}=await C(r),s=await Qo(n.user.id,r),o=new un({workspaceId:t,workspaceRoot:e,userId:n.user.id,runtimeId:s,supabase:i});Tt.set(t,{tracker:o,workspaceRoot:e}),o.start();}async function ta(t){return Tt.get(t)?.tracker.reconcile()??null}function wp(){for(let t of Tt.values())t.tracker.stop();Tt.clear();}var ra="1.0",dr=37913,ur="127.0.0.1",wv=60,yv=createRequire(import.meta.url),kv=yv("../package.json"),fe=promisify(execFile),hn="io.pathrule.cli-daemon",Oi="pathrule-daemon.service",bv=60;async function pr(t){let e=await We(t);if(e.running)return e;let r=process.argv[1];if(!r)throw new Error("daemon_entrypoint_missing");spawn(process.execPath,[r,"daemon","run"],{detached:true,stdio:"ignore",env:{...process.env,...t}}).unref();let i=Date.now()+3e3;for(;Date.now()<i;){let s=await We(t);if(s.running)return s;await Hv(100);}throw new Error("daemon_start_timeout")}async function fn(t){let e=await We(t);if(e.state?.pid&&e.state.pid!==process.pid)try{process.kill(e.state.pid,"SIGTERM");}catch{}return await unlink(A(t).daemonFile).catch(()=>{}),We(t)}async function Pe(t=process.env){let e=Tp(t);if(!e.supported)return e;if(e.method==="task-scheduler"){let r=await Pv();return {...e,enabled:r}}return {...e,enabled:e.path?await aa(e.path):false}}async function Qe(t,e){let r=Tp(t);if(!r.supported)return r;if(e){let n=Sv(t);if(r.method==="launchd"){if(!r.path)throw new Error("daemon_autostart_path_missing");return await Cv(r.path,n,t),t.PATHRULE_SKIP_AUTOSTART_ACTIVATE!=="1"&&await Rv(r.path),Pe(t)}if(r.method==="systemd"){if(!r.path)throw new Error("daemon_autostart_path_missing");return await Ev(r.path,n,t),t.PATHRULE_SKIP_AUTOSTART_ACTIVATE!=="1"&&(await fe("systemctl",["--user","daemon-reload"]),await fe("systemctl",["--user","enable","--now",Oi])),Pe(t)}return await Tv(n,t),Pe(t)}return r.method==="launchd"?(t.PATHRULE_SKIP_AUTOSTART_ACTIVATE!=="1"&&r.path&&await xv(r.path),r.path&&await unlink(r.path).catch(()=>{}),Pe(t)):r.method==="systemd"?(t.PATHRULE_SKIP_AUTOSTART_ACTIVATE!=="1"&&(await fe("systemctl",["--user","disable","--now",Oi]).catch(()=>{}),await fe("systemctl",["--user","daemon-reload"]).catch(()=>{})),r.path&&await unlink(r.path).catch(()=>{}),Pe(t)):(await Av(),Pe(t))}async function We(t){let e=A(t).daemonFile,r;try{r=JSON.parse(await readFile(e,"utf8"));}catch(i){let s=i.code==="ENOENT"?"missing":"unreadable";return await kp(vv(t))?{running:true,state:null,state_path:e,reason:"probed"}:{running:false,state:null,state_path:e,reason:s}}let n=Fv(r.pid);if(!n){let i=await kp(r.port);if(i)return {running:true,state:i.daemonSessionId?{...r,pid:0,daemon_session_id:i.daemonSessionId,protocol_version:i.protocolVersion}:null,state_path:e,reason:"probed"}}return {running:n,state:r,state_path:e,reason:n?void 0:"stale"}}async function kp(t){if(!Number.isInteger(t)||t<=0||t>65535)return null;let e=new AbortController,r=setTimeout(()=>e.abort(),250);try{let n=await fetch(`http://${ur}:${t}/v1/status`,{signal:e.signal});if(!n.ok)return null;let i=await n.json();return i.daemon_present!==!0||typeof i.protocol_version!="string"?null:{protocolVersion:i.protocol_version,daemonSessionId:typeof i.daemon_session_id=="string"&&i.daemon_session_id.length>0?i.daemon_session_id:null}}catch{return null}finally{clearTimeout(r);}}function vv(t){let e=t.PATHRULE_DAEMON_PORT?.trim()||String(dr),r=Number(e);return Number.isInteger(r)&&r>=0&&r<=65535?r:dr}function Tp(t){let e=t.PATHRULE_TEST_PLATFORM??process.platform,r=t.PATHRULE_AUTOSTART_DIR;return e==="darwin"?{supported:true,enabled:false,method:"launchd",path:r?join(r,`${hn}.plist`):join(homedir(),"Library","LaunchAgents",`${hn}.plist`)}:e==="linux"?{supported:true,enabled:false,method:"systemd",path:r?join(r,Oi):join(homedir(),".config","systemd","user",Oi)}:e==="win32"?{supported:false,enabled:false,method:"task-scheduler",path:null,reason:"Windows daemon autostart requires installer support."}:{supported:false,enabled:false,method:"unsupported",path:null,reason:`Unsupported platform: ${e}`}}function Sv(t){let e=t.PATHRULE_CLI_ENTRYPOINT?.trim()||process.argv[1];if(!e)throw new Error("daemon_entrypoint_missing");return {command:process.execPath,args:[e,"daemon","run"]}}function oa(t){let e={PATHRULE_DAEMON_PORT:t.PATHRULE_DAEMON_PORT?.trim()||String(dr)};for(let r of ["PATH","PATHRULE_HOME","PATHRULE_WEB_URL"]){let n=t[r];n&&n.trim()!==""&&(e[r]=n);}return e}async function Cv(t,e,r){let n=`<?xml version="1.0" encoding="UTF-8"?>
143
143
  <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
144
144
  <plist version="1.0">
145
145
  <dict>
@@ -166,7 +166,7 @@ ${Object.entries(oa(r)).map(([i,s])=>` <key>${lr(i)}</key>
166
166
  <string>${lr(join(A(r).logsDir,"daemon-launchd.err.log"))}</string>
167
167
  </dict>
168
168
  </plist>
169
- `;await mkdir(dirname(t),{recursive:true,mode:D}),await mkdir(A(r).logsDir,{recursive:true,mode:D}),await writeFile(t,n,{encoding:"utf8",mode:O}),await chmod(t,O).catch(()=>{});}async function Ev(t,e,r){let n=oa(r),i=`[Unit]
169
+ `;await mkdir(dirname(t),{recursive:true,mode:j}),await mkdir(A(r).logsDir,{recursive:true,mode:j}),await writeFile(t,n,{encoding:"utf8",mode:O}),await chmod(t,O).catch(()=>{});}async function Ev(t,e,r){let n=oa(r),i=`[Unit]
170
170
  Description=Pathrule CLI daemon
171
171
 
172
172
  [Service]
@@ -179,12 +179,12 @@ RestartSec=5
179
179
 
180
180
  [Install]
181
181
  WantedBy=default.target
182
- `;await mkdir(dirname(t),{recursive:true,mode:D}),await writeFile(t,i,{encoding:"utf8",mode:O}),await chmod(t,O).catch(()=>{});}async function Rv(t){let e=Ap();await fe("launchctl",["bootout",e,t]).catch(()=>{}),await fe("launchctl",["bootstrap",e,t]),await fe("launchctl",["enable",`${e}/${hn}`]).catch(()=>{}),await fe("launchctl",["kickstart","-k",`${e}/${hn}`]).catch(()=>{});}async function xv(t){await fe("launchctl",["bootout",Ap(),t]).catch(()=>{});}function Ap(){return `gui/${typeof process.getuid=="function"?process.getuid():0}`}async function Pv(){try{return await fe("schtasks.exe",["/Query","/TN","Pathrule CLI Daemon"]),!0}catch{return false}}async function Tv(t,e){let r=oa(e),n=Object.entries(r).map(([o,a])=>`set ${na(o)}=${na(a)}`).join("&&"),i=[t.command,...t.args].map(Iv).join(" "),s=n?`cmd.exe /d /c "${n}&&${i}"`:i;await fe("schtasks.exe",["/Create","/TN","Pathrule CLI Daemon","/TR",s,"/SC","ONLOGON","/F"]);}async function Av(){await fe("schtasks.exe",["/Delete","/TN","Pathrule CLI Daemon","/F"]).catch(()=>{});}function lr(t){return t.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&apos;")}function bp(t){return `"${t.replace(/(["\\$`])/g,"\\$1")}"`}function Iv(t){return `"${na(t)}"`}function na(t){return t.replace(/(["^&|<>%])/g,"^$1")}async function Ip(t,e={}){let r=null,n=new Map,i=new Map,s=createServer((l,c)=>{Nv(l,c,t,r,n,i);}),o=Ov(t);await new Promise((l,c)=>{s.once("error",c),s.listen(o.port,o.host,()=>{s.off("error",c),l();});});let a=s.address();if(!a||typeof a=="string")throw new Error("daemon_bind_failed");r={schema_version:1,pid:process.pid,host:ur,port:a.port,protocol_version:ra,daemon_session_id:randomUUID(),started_at:new Date().toISOString()},await Dv(t,r),await dn(t,`listening ${ur}:${a.port}`),_p(t).catch(l=>{dn(t,`work_state_trackers_start_failed error=${l instanceof Error?l.message:"unknown"}`);}),await new Promise(l=>{let c=false,u=()=>{c||(c=true,process.off("SIGTERM",u),process.off("SIGINT",u),e.shutdownSignal?.removeEventListener("abort",u),wp(),s.close(()=>l()));};process.once("SIGTERM",u),process.once("SIGINT",u),e.shutdownSignal?.addEventListener("abort",u,{once:true});}),await unlink(A(t).daemonFile).catch(()=>{}),await dn(t,"stopped");}function Ov(t){let e=t.PATHRULE_DAEMON_HOST?.trim();if(e&&e!==ur&&e!=="localhost")throw new Error("daemon_host_must_be_loopback");let r=t.PATHRULE_DAEMON_PORT?.trim();if(!r)return {host:ur,port:0};let n=Number(r);if(!Number.isInteger(n)||n<0||n>65535)throw new Error("daemon_port_invalid");return {host:ur,port:n}}function $v(t,e,r,n=Date.now()){let i=Vu({origin:e,ip:r,nowMs:n}),s=(t.get(i)??0)+1;return t.set(i,s),s<=wv}async function Nv(t,e,r,n,i,s){let o=new URL(t.url??"/","http://127.0.0.1"),a=$i(t.headers,"origin"),l=Lv();if(t.method==="OPTIONS"){let d=Ro(a,l);if(!d){x(e,400,{ok:false,error:a?"origin_not_allowed":"origin_required"});return}e.writeHead(204,d),e.end();return}if(a&&!mi(a,l)){x(e,400,{ok:false,error:"origin_not_allowed"});return}if(a&&!$v(s,a,Uv(t))){x(e,429,{ok:false,error:"rate_limited"});return}let c=a?Ro(a,l)??void 0:void 0;if(t.method==="POST"&&o.pathname==="/hook/work-conflicts"&&!a)try{let d=await cr(t,8192),p=await vp(r,{workspaceId:Ue(d,"workspace_id"),relativePaths:Rp(d,"relative_paths")});x(e,200,p);return}catch(d){x(e,400,{ok:false,error:d instanceof Error?d.message:String(d)});return}if(t.method==="GET"&&o.pathname==="/v1/status"){let d=At(t,a,i);if(d&&n){let p=await $p(r);x(e,200,{daemon_present:true,paired:true,daemon_version:kv.version,protocol_version:ra,daemon_session_id:d.daemonSessionId,user_id:d.userId,paired_at:d.pairedAt,desktop_runtime_detected:p},c);return}x(e,200,Ku(ra),c);return}if(t.method==="POST"&&o.pathname==="/v1/pair"){let d=St({headers:t.headers,allowedOrigins:l,requirePairToken:false});if(d){x(e,d.statusCode,{ok:false,error:d.reason},c);return}if(!n){x(e,503,{ok:false,error:"daemon_not_ready"},c);return}try{let p=await cr(t),h=Ue(p,"browser_profile_id"),f=await qu({env:r,daemonSessionId:n.daemon_session_id,origin:a??"",pairCode:Ue(p,"pair_code"),pairVerifier:Ue(p,"pair_verifier"),browserProfileId:h});i.set(f.pair_token,{daemonSessionId:f.daemon_session_id,browserProfileId:h,origin:a??"",userId:f.user_id,pairedAt:new Date().toISOString()}),await dn(r,Cp("bridge_paired",{origin:a??"",userId:f.user_id,browserProfileId:h})),x(e,200,f,c);return}catch(p){let h=p instanceof Y?p.code:"pair_failed",f=h==="pair_code_missing"||h==="pair_code_invalid"?401:h==="pair_code_expired"||h==="pair_code_stale"?410:h.endsWith("_required")?400:500;x(e,f,{ok:false,error:h},c);return}}if(t.method==="POST"&&o.pathname==="/v1/fs/read-dir"){let d=At(t,a,i),p=St({headers:t.headers,allowedOrigins:l});if(p){x(e,p.statusCode,{ok:false,error:p.reason},c);return}if(!d){x(e,401,{ok:false,error:"pair_token_invalid"},c);return}try{let h=await cr(t),f=Ue(h,"workspace_root"),m=Ue(h,"relative_dir");await he(r,d.userId,f);let _=await Bo(f,m);x(e,200,{entries:_},c);return}catch(h){x(e,400,{error:h instanceof Error?h.message:String(h)},c);return}}if(t.method==="POST"&&o.pathname==="/v1/fs/path-exists"){let d=At(t,a,i),p=St({headers:t.headers,allowedOrigins:l});if(p){x(e,p.statusCode,{ok:false,error:p.reason},c);return}if(!d){x(e,401,{ok:false,error:"pair_token_invalid"},c);return}try{let h=await cr(t),f=Ue(h,"path");await he(r,d.userId,f);let m=await aa(f),_=m?await Op(f):!1;x(e,200,{exists:m,isDirectory:_},c);return}catch(h){x(e,400,{error:h instanceof Error?h.message:String(h)},c);return}}if(t.method==="POST"&&o.pathname==="/v1/doctor"){let d=At(t,a,i),p=St({headers:t.headers,allowedOrigins:l});if(p){x(e,p.statusCode,{ok:false,error:p.reason},c);return}if(!d){x(e,401,{ok:false,error:"pair_token_invalid"},c);return}try{await ia(r,d.userId);let h=await cr(t),f=Ep(h,"workspace_root")??process.cwd(),m=await Me(r,f);x(e,200,{ok:m.ok,report:m},c);return}catch(h){x(e,400,{ok:false,error:h instanceof Error?h.message:String(h)},c);return}}let u=jv(o.pathname);if(t.method==="GET"&&u){let d=At(t,a,i);if(!d){x(e,401,{ok:false,error:"pair_token_invalid"},c);return}try{let p=o.searchParams.get("workspace_root")?.trim()??"";if(!p)throw new Error("workspace_root_required");if(u.action==="local-status"){await Sp(e,r,d.userId,u.workspaceId,p,c);return}if(u.action==="agents-status"){await he(r,d.userId,p,u.workspaceId);let h=await Pt(r,d.userId,u.workspaceId,p);x(e,200,{ok:!0,statuses:h,ai_clients:h},c);return}if(u.action==="fs-read"){await he(r,d.userId,p,u.workspaceId);let h=await Bo(p,o.searchParams.get("dir")??"/");x(e,200,{ok:!0,entries:h},c);return}}catch(p){x(e,400,{ok:false,error:p instanceof Error?p.message:String(p)},c);return}}if(t.method==="POST"&&u){let d=At(t,a,i),p=St({headers:t.headers,allowedOrigins:l});if(p){x(e,p.statusCode,{ok:false,error:p.reason},c);return}if(!d){x(e,401,{ok:false,error:"pair_token_invalid"},c);return}try{let h=await cr(t),f=Ue(h,"workspace_root");if(u.action==="local-status"){await Sp(e,r,d.userId,u.workspaceId,f,c);return}if(u.action==="attach"){await ia(r,d.userId);let m=await xe(u.workspaceId,f,r);x(e,200,{ok:!0,...m},c);return}if(u.action==="sync"){await he(r,d.userId,f,u.workspaceId);let m=await ln(r,u.workspaceId,f);await ea(u.workspaceId,f,r),await ta(u.workspaceId),x(e,m.ok?200:409,m,c);return}if(u.action==="repair"){await he(r,d.userId,f,u.workspaceId);let m=await cn(r,f);x(e,m.ok?200:409,m,c);return}if(u.action==="agents-status"){await he(r,d.userId,f,u.workspaceId);let m=await Pt(r,d.userId,u.workspaceId,f);x(e,200,{ok:!0,statuses:m,ai_clients:m},c);return}if(u.action==="agents-install"||u.action==="agents-uninstall"||u.action==="agents-set-enabled"){await he(r,d.userId,f,u.workspaceId);let m=u.action==="agents-set-enabled"?Wv(h,"enabled"):u.action==="agents-install",_=await fp(r,d.userId,u.workspaceId,f,Ue(h,"client"),m,Bv(Ep(h,"disable_mode")));x(e,_.ok?200:409,_,c);return}if(u.action==="hooks-sync"||u.action==="hook-index-rebuild"){await he(r,d.userId,f,u.workspaceId);let{supabase:m}=await C(r),_=await Ei({supabase:m,workspaceId:u.workspaceId,workspaceRoot:f,env:r});await ea(u.workspaceId,f,r),await ta(u.workspaceId),x(e,_.ok?200:409,_,c);return}if(u.action==="work-conflicts"){await he(r,d.userId,f,u.workspaceId);let m=await vp(r,{workspaceId:u.workspaceId,relativePaths:Rp(h,"relative_paths")});x(e,200,{ok:!0,decision:m},c);return}if(u.action==="skills-materialize"){await he(r,d.userId,f,u.workspaceId);let m=await ln(r,u.workspaceId,f,{skillsOnly:!0});x(e,m.ok?200:409,m,c);return}}catch(h){x(e,400,{ok:false,error:h instanceof Error?h.message:String(h)},c);return}}if(t.method==="POST"&&o.pathname==="/v1/unpair"){let d=St({headers:t.headers,allowedOrigins:l});if(d){x(e,d.statusCode,{ok:false,error:d.reason},c);return}let p=$i(t.headers,gi),h=At(t,a,i);if(!p||!h){x(e,401,{ok:false,error:"pair_token_invalid"},c);return}i.delete(p),await dn(r,Cp("bridge_unpaired",{origin:a??"",userId:h.userId,browserProfileId:h.browserProfileId})),x(e,200,{ok:true},c);return}x(e,404,{ok:false,error:"not_found"},c);}function At(t,e,r){let n=$i(t.headers,gi);if(!n||!e)return null;let i=r.get(n);return !i||i.origin!==e||i.browserProfileId!==$i(t.headers,Ju)?null:i}async function he(t,e,r,n){await ia(t,e);let{session:i,supabase:s}=await C(t),o=s.from("user_workspace_paths").select("workspace_id").eq("user_id",e).eq("local_root_path",r).limit(1);n&&(o=o.eq("workspace_id",n));let{data:a,error:l}=await o;if(l)throw l;if(!a||a.length===0)throw new Error("workspace_root_not_attached")}async function ia(t,e){let{session:r}=await C(t);if(r.user.id!==e)throw new Error("session_user_mismatch")}function jv(t){let e=/^\/v1\/workspaces\/([^/]+)\/(.+)$/.exec(t);if(!e)return null;let r=decodeURIComponent(e[1]??""),n=e[2]??"";return r?n==="local-status"?{workspaceId:r,action:"local-status"}:n==="fs"?{workspaceId:r,action:"fs-read"}:n==="attach"?{workspaceId:r,action:"attach"}:n==="sync"?{workspaceId:r,action:"sync"}:n==="repair"?{workspaceId:r,action:"repair"}:n==="agents/status"?{workspaceId:r,action:"agents-status"}:n==="agents/install"?{workspaceId:r,action:"agents-install"}:n==="agents/uninstall"?{workspaceId:r,action:"agents-uninstall"}:n==="agents/set-enabled"?{workspaceId:r,action:"agents-set-enabled"}:n==="hooks/sync"?{workspaceId:r,action:"hooks-sync"}:n==="hook-index/rebuild"?{workspaceId:r,action:"hook-index-rebuild"}:n==="skills/materialize"?{workspaceId:r,action:"skills-materialize"}:n==="work-conflicts"?{workspaceId:r,action:"work-conflicts"}:null:null}async function vp(t,e){let r=Date.now(),{session:n,supabase:i}=await C(t),s=i.rpc("pathrule_check_file_work_conflicts",{p_workspace_id:e.workspaceId,p_relative_paths:e.relativePaths}),o=await qv(s,bv);if(!o||o.error)return Xu(r);let a=Array.isArray(o.data)?o.data:[],l={};for(let c of a){if(!c||typeof c!="object")continue;let u=c;typeof u.user_id=="string"&&typeof u.display_name=="string"&&(l[u.user_id]=u.display_name);}return Yu({workspaceId:e.workspaceId,relativePaths:e.relativePaths,currentUserId:n.user.id,rows:Zu(a),displayNamesByUserId:l,source:"cloud_rpc",startedAtMs:r})}async function Sp(t,e,r,n,i,s){await he(e,r,i,n);let o=await aa(i),a=o?await Op(i):false,l=await $p(e),c=await Pt(e,r,n,i);x(t,200,{ok:true,workspace_id:n,local_root_path:i,root_exists:o,root_is_directory:a,desktop_runtime_detected:l,local_runtime_state:o?a?l?"cli_attached_desktop_also_detected":"cli_attached":"root_not_directory":"root_missing",ai_clients:c},s);}async function aa(t){try{return await access(t,constants.F_OK),!0}catch{return false}}async function Op(t){try{return (await stat(t)).isDirectory()}catch{return false}}async function Dv(t,e){let r=A(t).daemonFile;await mkdir(dirname(r),{recursive:true,mode:D});let n=`${r}.tmp`;await writeFile(n,JSON.stringify(e,null,2),{encoding:"utf8",mode:O}),await rename(n,r);}async function dn(t,e){let r=A(t).logsDir;await mkdir(r,{recursive:true,mode:D});let n=new Date().toISOString().slice(0,10),i=`${new Date().toISOString()} ${Mv(e)}
182
+ `;await mkdir(dirname(t),{recursive:true,mode:j}),await writeFile(t,i,{encoding:"utf8",mode:O}),await chmod(t,O).catch(()=>{});}async function Rv(t){let e=Ap();await fe("launchctl",["bootout",e,t]).catch(()=>{}),await fe("launchctl",["bootstrap",e,t]),await fe("launchctl",["enable",`${e}/${hn}`]).catch(()=>{}),await fe("launchctl",["kickstart","-k",`${e}/${hn}`]).catch(()=>{});}async function xv(t){await fe("launchctl",["bootout",Ap(),t]).catch(()=>{});}function Ap(){return `gui/${typeof process.getuid=="function"?process.getuid():0}`}async function Pv(){try{return await fe("schtasks.exe",["/Query","/TN","Pathrule CLI Daemon"]),!0}catch{return false}}async function Tv(t,e){let r=oa(e),n=Object.entries(r).map(([o,a])=>`set ${na(o)}=${na(a)}`).join("&&"),i=[t.command,...t.args].map(Iv).join(" "),s=n?`cmd.exe /d /c "${n}&&${i}"`:i;await fe("schtasks.exe",["/Create","/TN","Pathrule CLI Daemon","/TR",s,"/SC","ONLOGON","/F"]);}async function Av(){await fe("schtasks.exe",["/Delete","/TN","Pathrule CLI Daemon","/F"]).catch(()=>{});}function lr(t){return t.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&apos;")}function bp(t){return `"${t.replace(/(["\\$`])/g,"\\$1")}"`}function Iv(t){return `"${na(t)}"`}function na(t){return t.replace(/(["^&|<>%])/g,"^$1")}async function Ip(t,e={}){let r=null,n=new Map,i=new Map,s=createServer((l,c)=>{Nv(l,c,t,r,n,i);}),o=Ov(t);await new Promise((l,c)=>{s.once("error",c),s.listen(o.port,o.host,()=>{s.off("error",c),l();});});let a=s.address();if(!a||typeof a=="string")throw new Error("daemon_bind_failed");r={schema_version:1,pid:process.pid,host:ur,port:a.port,protocol_version:ra,daemon_session_id:randomUUID(),started_at:new Date().toISOString()},await jv(t,r),await dn(t,`listening ${ur}:${a.port}`),_p(t).catch(l=>{dn(t,`work_state_trackers_start_failed error=${l instanceof Error?l.message:"unknown"}`);}),await new Promise(l=>{let c=false,u=()=>{c||(c=true,process.off("SIGTERM",u),process.off("SIGINT",u),e.shutdownSignal?.removeEventListener("abort",u),wp(),s.close(()=>l()));};process.once("SIGTERM",u),process.once("SIGINT",u),e.shutdownSignal?.addEventListener("abort",u,{once:true});}),await unlink(A(t).daemonFile).catch(()=>{}),await dn(t,"stopped");}function Ov(t){let e=t.PATHRULE_DAEMON_HOST?.trim();if(e&&e!==ur&&e!=="localhost")throw new Error("daemon_host_must_be_loopback");let r=t.PATHRULE_DAEMON_PORT?.trim();if(!r)return {host:ur,port:0};let n=Number(r);if(!Number.isInteger(n)||n<0||n>65535)throw new Error("daemon_port_invalid");return {host:ur,port:n}}function $v(t,e,r,n=Date.now()){let i=Vu({origin:e,ip:r,nowMs:n}),s=(t.get(i)??0)+1;return t.set(i,s),s<=wv}async function Nv(t,e,r,n,i,s){let o=new URL(t.url??"/","http://127.0.0.1"),a=$i(t.headers,"origin"),l=Lv();if(t.method==="OPTIONS"){let d=Ro(a,l);if(!d){x(e,400,{ok:false,error:a?"origin_not_allowed":"origin_required"});return}e.writeHead(204,d),e.end();return}if(a&&!mi(a,l)){x(e,400,{ok:false,error:"origin_not_allowed"});return}if(a&&!$v(s,a,Uv(t))){x(e,429,{ok:false,error:"rate_limited"});return}let c=a?Ro(a,l)??void 0:void 0;if(t.method==="POST"&&o.pathname==="/hook/work-conflicts"&&!a)try{let d=await cr(t,8192),p=await vp(r,{workspaceId:Ue(d,"workspace_id"),relativePaths:Rp(d,"relative_paths")});x(e,200,p);return}catch(d){x(e,400,{ok:false,error:d instanceof Error?d.message:String(d)});return}if(t.method==="GET"&&o.pathname==="/v1/status"){let d=At(t,a,i);if(d&&n){let h=await $p(r);x(e,200,{daemon_present:true,paired:true,daemon_version:kv.version,protocol_version:ra,daemon_session_id:d.daemonSessionId,user_id:d.userId,paired_at:d.pairedAt,desktop_runtime_detected:h},c);return}let p=!a&&n?.daemon_session_id?n.daemon_session_id:null;x(e,200,Ku(ra,{daemonSessionId:p}),c);return}if(t.method==="POST"&&o.pathname==="/v1/pair"){let d=St({headers:t.headers,allowedOrigins:l,requirePairToken:false});if(d){x(e,d.statusCode,{ok:false,error:d.reason},c);return}if(!n){x(e,503,{ok:false,error:"daemon_not_ready"},c);return}try{let p=await cr(t),h=Ue(p,"browser_profile_id"),f=await qu({env:r,daemonSessionId:n.daemon_session_id,origin:a??"",pairCode:Ue(p,"pair_code"),pairVerifier:Ue(p,"pair_verifier"),browserProfileId:h});i.set(f.pair_token,{daemonSessionId:f.daemon_session_id,browserProfileId:h,origin:a??"",userId:f.user_id,pairedAt:new Date().toISOString()}),await dn(r,Cp("bridge_paired",{origin:a??"",userId:f.user_id,browserProfileId:h})),x(e,200,f,c);return}catch(p){let h=p instanceof Y?p.code:"pair_failed",f=h==="pair_code_missing"||h==="pair_code_invalid"?401:h==="pair_code_expired"||h==="pair_code_stale"?410:h.endsWith("_required")?400:500;x(e,f,{ok:false,error:h},c);return}}if(t.method==="POST"&&o.pathname==="/v1/fs/read-dir"){let d=At(t,a,i),p=St({headers:t.headers,allowedOrigins:l});if(p){x(e,p.statusCode,{ok:false,error:p.reason},c);return}if(!d){x(e,401,{ok:false,error:"pair_token_invalid"},c);return}try{let h=await cr(t),f=Ue(h,"workspace_root"),m=Ue(h,"relative_dir");await he(r,d.userId,f);let _=await Bo(f,m);x(e,200,{entries:_},c);return}catch(h){x(e,400,{error:h instanceof Error?h.message:String(h)},c);return}}if(t.method==="POST"&&o.pathname==="/v1/fs/path-exists"){let d=At(t,a,i),p=St({headers:t.headers,allowedOrigins:l});if(p){x(e,p.statusCode,{ok:false,error:p.reason},c);return}if(!d){x(e,401,{ok:false,error:"pair_token_invalid"},c);return}try{let h=await cr(t),f=Ue(h,"path");await he(r,d.userId,f);let m=await aa(f),_=m?await Op(f):!1;x(e,200,{exists:m,isDirectory:_},c);return}catch(h){x(e,400,{error:h instanceof Error?h.message:String(h)},c);return}}if(t.method==="POST"&&o.pathname==="/v1/doctor"){let d=At(t,a,i),p=St({headers:t.headers,allowedOrigins:l});if(p){x(e,p.statusCode,{ok:false,error:p.reason},c);return}if(!d){x(e,401,{ok:false,error:"pair_token_invalid"},c);return}try{await ia(r,d.userId);let h=await cr(t),f=Ep(h,"workspace_root")??process.cwd(),m=await Me(r,f);x(e,200,{ok:m.ok,report:m},c);return}catch(h){x(e,400,{ok:false,error:h instanceof Error?h.message:String(h)},c);return}}let u=Dv(o.pathname);if(t.method==="GET"&&u){let d=At(t,a,i);if(!d){x(e,401,{ok:false,error:"pair_token_invalid"},c);return}try{let p=o.searchParams.get("workspace_root")?.trim()??"";if(!p)throw new Error("workspace_root_required");if(u.action==="local-status"){await Sp(e,r,d.userId,u.workspaceId,p,c);return}if(u.action==="agents-status"){await he(r,d.userId,p,u.workspaceId);let h=await Pt(r,d.userId,u.workspaceId,p);x(e,200,{ok:!0,statuses:h,ai_clients:h},c);return}if(u.action==="fs-read"){await he(r,d.userId,p,u.workspaceId);let h=await Bo(p,o.searchParams.get("dir")??"/");x(e,200,{ok:!0,entries:h},c);return}}catch(p){x(e,400,{ok:false,error:p instanceof Error?p.message:String(p)},c);return}}if(t.method==="POST"&&u){let d=At(t,a,i),p=St({headers:t.headers,allowedOrigins:l});if(p){x(e,p.statusCode,{ok:false,error:p.reason},c);return}if(!d){x(e,401,{ok:false,error:"pair_token_invalid"},c);return}try{let h=await cr(t),f=Ue(h,"workspace_root");if(u.action==="local-status"){await Sp(e,r,d.userId,u.workspaceId,f,c);return}if(u.action==="attach"){await ia(r,d.userId);let m=await xe(u.workspaceId,f,r);x(e,200,{ok:!0,...m},c);return}if(u.action==="sync"){await he(r,d.userId,f,u.workspaceId);let m=await ln(r,u.workspaceId,f);await ea(u.workspaceId,f,r),await ta(u.workspaceId),x(e,m.ok?200:409,m,c);return}if(u.action==="repair"){await he(r,d.userId,f,u.workspaceId);let m=await cn(r,f);x(e,m.ok?200:409,m,c);return}if(u.action==="agents-status"){await he(r,d.userId,f,u.workspaceId);let m=await Pt(r,d.userId,u.workspaceId,f);x(e,200,{ok:!0,statuses:m,ai_clients:m},c);return}if(u.action==="agents-install"||u.action==="agents-uninstall"||u.action==="agents-set-enabled"){await he(r,d.userId,f,u.workspaceId);let m=u.action==="agents-set-enabled"?Wv(h,"enabled"):u.action==="agents-install",_=await fp(r,d.userId,u.workspaceId,f,Ue(h,"client"),m,Bv(Ep(h,"disable_mode")));x(e,_.ok?200:409,_,c);return}if(u.action==="hooks-sync"||u.action==="hook-index-rebuild"){await he(r,d.userId,f,u.workspaceId);let{supabase:m}=await C(r),_=await Ei({supabase:m,workspaceId:u.workspaceId,workspaceRoot:f,env:r});await ea(u.workspaceId,f,r),await ta(u.workspaceId),x(e,_.ok?200:409,_,c);return}if(u.action==="work-conflicts"){await he(r,d.userId,f,u.workspaceId);let m=await vp(r,{workspaceId:u.workspaceId,relativePaths:Rp(h,"relative_paths")});x(e,200,{ok:!0,decision:m},c);return}if(u.action==="skills-materialize"){await he(r,d.userId,f,u.workspaceId);let m=await ln(r,u.workspaceId,f,{skillsOnly:!0});x(e,m.ok?200:409,m,c);return}}catch(h){x(e,400,{ok:false,error:h instanceof Error?h.message:String(h)},c);return}}if(t.method==="POST"&&o.pathname==="/v1/unpair"){let d=St({headers:t.headers,allowedOrigins:l});if(d){x(e,d.statusCode,{ok:false,error:d.reason},c);return}let p=$i(t.headers,gi),h=At(t,a,i);if(!p||!h){x(e,401,{ok:false,error:"pair_token_invalid"},c);return}i.delete(p),await dn(r,Cp("bridge_unpaired",{origin:a??"",userId:h.userId,browserProfileId:h.browserProfileId})),x(e,200,{ok:true},c);return}x(e,404,{ok:false,error:"not_found"},c);}function At(t,e,r){let n=$i(t.headers,gi);if(!n||!e)return null;let i=r.get(n);return !i||i.origin!==e||i.browserProfileId!==$i(t.headers,Ju)?null:i}async function he(t,e,r,n){await ia(t,e);let{session:i,supabase:s}=await C(t),o=s.from("user_workspace_paths").select("workspace_id").eq("user_id",e).eq("local_root_path",r).limit(1);n&&(o=o.eq("workspace_id",n));let{data:a,error:l}=await o;if(l)throw l;if(!a||a.length===0)throw new Error("workspace_root_not_attached")}async function ia(t,e){let{session:r}=await C(t);if(r.user.id!==e)throw new Error("session_user_mismatch")}function Dv(t){let e=/^\/v1\/workspaces\/([^/]+)\/(.+)$/.exec(t);if(!e)return null;let r=decodeURIComponent(e[1]??""),n=e[2]??"";return r?n==="local-status"?{workspaceId:r,action:"local-status"}:n==="fs"?{workspaceId:r,action:"fs-read"}:n==="attach"?{workspaceId:r,action:"attach"}:n==="sync"?{workspaceId:r,action:"sync"}:n==="repair"?{workspaceId:r,action:"repair"}:n==="agents/status"?{workspaceId:r,action:"agents-status"}:n==="agents/install"?{workspaceId:r,action:"agents-install"}:n==="agents/uninstall"?{workspaceId:r,action:"agents-uninstall"}:n==="agents/set-enabled"?{workspaceId:r,action:"agents-set-enabled"}:n==="hooks/sync"?{workspaceId:r,action:"hooks-sync"}:n==="hook-index/rebuild"?{workspaceId:r,action:"hook-index-rebuild"}:n==="skills/materialize"?{workspaceId:r,action:"skills-materialize"}:n==="work-conflicts"?{workspaceId:r,action:"work-conflicts"}:null:null}async function vp(t,e){let r=Date.now(),{session:n,supabase:i}=await C(t),s=i.rpc("pathrule_check_file_work_conflicts",{p_workspace_id:e.workspaceId,p_relative_paths:e.relativePaths}),o=await qv(s,bv);if(!o||o.error)return Xu(r);let a=Array.isArray(o.data)?o.data:[],l={};for(let c of a){if(!c||typeof c!="object")continue;let u=c;typeof u.user_id=="string"&&typeof u.display_name=="string"&&(l[u.user_id]=u.display_name);}return Yu({workspaceId:e.workspaceId,relativePaths:e.relativePaths,currentUserId:n.user.id,rows:Zu(a),displayNamesByUserId:l,source:"cloud_rpc",startedAtMs:r})}async function Sp(t,e,r,n,i,s){await he(e,r,i,n);let o=await aa(i),a=o?await Op(i):false,l=await $p(e),c=await Pt(e,r,n,i);x(t,200,{ok:true,workspace_id:n,local_root_path:i,root_exists:o,root_is_directory:a,desktop_runtime_detected:l,local_runtime_state:o?a?l?"cli_attached_desktop_also_detected":"cli_attached":"root_not_directory":"root_missing",ai_clients:c},s);}async function aa(t){try{return await access(t,constants.F_OK),!0}catch{return false}}async function Op(t){try{return (await stat(t)).isDirectory()}catch{return false}}async function jv(t,e){let r=A(t).daemonFile;await mkdir(dirname(r),{recursive:true,mode:j});let n=`${r}.tmp`;await writeFile(n,JSON.stringify(e,null,2),{encoding:"utf8",mode:O}),await rename(n,r);}async function dn(t,e){let r=A(t).logsDir;await mkdir(r,{recursive:true,mode:j});let n=new Date().toISOString().slice(0,10),i=`${new Date().toISOString()} ${Mv(e)}
183
183
  `;await writeFile(join(r,`daemon-${n}.log`),i,{flag:"a",encoding:"utf8",mode:O});}function Mv(t){return t.replace(/(authorization|token|secret|password)=\S+/gi,"$1=[redacted]")}function Cp(t,e){let r=createHash("sha256").update("pathrule-bridge-profile-v1","utf8").update("\0","utf8").update(e.browserProfileId,"utf8").digest("base64url").slice(0,16);return `${t} origin=${e.origin||"unknown"} user_id=${e.userId} browser_profile_hash=${r}`}async function $p(t,e=Date.now()){let r=t.PATHRULE_DESKTOP_HEALTH?.trim().toLowerCase();if(r==="healthy"||r==="1"||r==="true")return true;if(r==="unhealthy"||r==="0"||r==="false")return false;let n;try{n=JSON.parse(await readFile(A(t).desktopFile,"utf8"));}catch{return false}if(n.healthy!==true||!n.updated_at)return false;let i=Date.parse(n.updated_at);return Number.isFinite(i)&&e-i<=600*1e3}function Lv(){let t=process.env.PATHRULE_BRIDGE_ORIGINS;return t?t.split(",").map(e=>e.trim()).filter(Boolean):["https://app.pathrule.io","http://localhost:5173"]}function $i(t,e){let r=t[e]??t[e.toLowerCase()],n=Array.isArray(r)?r[0]:r;return (typeof n=="string"?n.trim():"")||void 0}function Uv(t){return t.socket.remoteAddress??"unknown"}async function cr(t,e=4096){let r="";for await(let i of t)if(r+=i,Buffer.byteLength(r,"utf8")>e)throw new Error("request_body_too_large");let n=JSON.parse(r||"{}");if(!n||typeof n!="object"||Array.isArray(n))throw new Error("invalid_json_body");return n}function Ue(t,e){let r=t[e];if(typeof r!="string"||r.trim()==="")throw new Y(`${e}_required`);return r.trim()}function Ep(t,e){let r=t[e];return typeof r!="string"||r.trim()===""?null:r.trim()}function Wv(t,e){let r=t[e];if(typeof r!="boolean")throw new Y(`${e}_required`);return r}function Rp(t,e){let r=t[e];if(!Array.isArray(r))throw new Y(`${e}_required`);return Array.from(new Set(r.filter(n=>typeof n=="string"))).filter(n=>n.trim()!=="").slice(0,100)}function Bv(t){return t==="full-remove"?"full-remove":"restore-backup"}function x(t,e,r,n){t.writeHead(e,{"content-type":"application/json",...n}),t.end(JSON.stringify(r));}function Fv(t){if(!Number.isInteger(t)||t<=0)return false;try{return process.kill(t,0),!0}catch{return false}}function Hv(t){return new Promise(e=>setTimeout(e,t))}async function qv(t,e){let r=null;try{return await Promise.race([t,new Promise(n=>{r=setTimeout(()=>n(null),e),r.unref?.();})])}finally{r&&clearTimeout(r);}}F();function k(t){return {schema_version:1,ok:t.ok,command:t.command,cwd:t.cwd,...t.data===void 0?{}:{data:t.data},...t.error===void 0?{}:{error:t.error},...t.next_steps===void 0?{}:{next_steps:t.next_steps}}}function Np(t){return `${JSON.stringify(t,null,2)}
184
- `}function g(t,e){let r={ok:"[ok]",warn:"[warn]",error:"[error]",info:"[info]"};return e.color?`${{ok:"\x1B[32m",warn:"\x1B[33m",error:"\x1B[31m",info:"\x1B[36m"}[t]}${r[t]}\x1B[0m`:r[t]}Ee();var Jv=/^[^\s@]+@[^\s@]+\.[^\s@]+$/i,Te=class extends Error{constructor(r,n){super(n);this.code=r;this.name="CliInviteUsageError";}code};function la(t){let e=[],r="editor",n,i;for(let o=0;o<t.length;o+=1){let a=t[o];if(a){if(a==="--role"){r=tS(t[++o]);continue}if(a==="--org"){n=jp(t[++o],"--org requires a value","invite_org_required");continue}if(a==="--workspace"){i=jp(t[++o],"--workspace requires a value","invite_workspace_required");continue}if(a.startsWith("--"))throw new Te("unknown_invite_option",`Unknown invite option "${a}".`);e.push(a);}}let s=e[0];if(!s)throw new Te("invite_email_required","Usage: pathrule invite <email> [--role admin|editor|viewer] [--org <slug-or-id>] [--workspace <name-or-id>]");if(e.length>1)throw new Te("unexpected_invite_argument",`Unexpected extra argument "${e[1]}".`);return {email:s,role:r,orgSelector:n,workspaceSelector:i}}async function ca(t,e){let r=t.email.trim().toLowerCase();if(!Jv.test(r))return Ot("invalid_email",null,null,e,r);let{session:n,supabase:i}=await C(e),s=await Kv(t.orgSelector,e);if(!s)return Ot("org_required",null,null,e,r);if(s.role!=="admin"&&s.role!=="owner")return Ot("forbidden",s,null,e,r);let o=await Vv(i,n.user.id,s.id,t.workspaceSelector,e);if(!o&&t.workspaceSelector)return Ot("workspace_not_found",s,null,e,r);let a=await rS(i,s.id);if(a.failure)return Ot(a.failure.error,s,o,e,r,a.failure.details);let l=await Qv(i,s.id,a,e);if(!l.ok)return Ot(l.error,s,o,e,r,l.details);let{data:c,error:u}=await i.rpc("create_org_invite",{p_org_id:s.id,p_email:r,p_role:t.role}),d=c,p=d&&d.ok===false?d.error:void 0;if(u||!d||d.ok!==true)return Ot(u?.message??p??"invite_failed",s,o,e,r);let h=true;try{let{error:m}=await i.functions.invoke("send-org-invite-email",{body:{invite_id:d.invite_id}});m&&(h=!1);}catch{h=false;}let f={kind:"web",url:ee(s,e,"members"),label:"Open team in Pathrule Web",reason:"preferred"};return {ok:true,invite_id:d.invite_id,email:d.email,role:d.role,email_sent:h,billing_impact:a.billingImpact,billing_adjustment:l.adjustment,organization:Dp(s),workspace:Mp(o),open_target:f,next_steps:[{label:"Open team in Pathrule Web",url:f.url},...h?[]:[{label:"Retry invite email from Pathrule Web",url:f.url}]]}}function Dp(t){return t?{id:t.id,name:t.name,slug:t.slug,role:t.role}:null}function Mp(t){return t?{id:t.id,name:t.name}:null}async function Kv(t,e){return t?(await we(e)).find(n=>n.id===t||n.slug===t)??null:j(e)}async function Vv(t,e,r,n,i){if(!n){let a=await M(i);return a?.organization_id===r?a:null}let{data:s,error:o}=await t.from("workspaces").select("id, organization_id, name, access_mode, git_remote_url, git_owner, git_repo, user_workspace_paths!left(local_root_path, user_id)").eq("organization_id",r).is("archived_at",null);if(o)throw o;for(let a of s??[]){let c=(a.user_workspace_paths??[]).find(d=>d.user_id===e)??null,u={id:a.id,organization_id:a.organization_id,name:a.name,access_mode:a.access_mode,git_remote_url:a.git_remote_url,git_owner:a.git_owner,git_repo:a.git_repo,local_root_path:c?.local_root_path??null,current:false};if(u.id===n||u.name===n)return u}return null}function Ot(t,e,r,n,i,s){let o=Gv(t,e,n),a=Yv(t,i);return {ok:false,error:t,message:Zv(t),...a?{email_hash:a}:{},organization:Dp(e),workspace:Mp(r),open_target:o,next_steps:Xv(t,o),...s}}function Gv(t,e,r){if(e){if(t==="free_plan_invites_disabled"||t==="invite_blocked_billing"||t==="billing_update_failed")return {kind:"web",url:ee(e,r,"billing"),label:"Open billing in Pathrule Web",reason:"fallback"};if(t==="subscription_not_invitable"||t==="subscription_frozen")return {kind:"web",url:`${ee(e,r,"billing")}/reactivate`,label:"Open billing reactivation in Pathrule Web",reason:"fallback"};if(t==="paid_seats_required"||t==="seat_limit_reached")return {kind:"web",url:ee(e,r,"billing"),label:"Open billing in Pathrule Web",reason:"fallback"};if(t==="forbidden"||t==="permission_denied"||t==="already_member"||t==="email_already_member"||t==="invite_pending")return {kind:"web",url:ee(e,r,"members"),label:"Open team in Pathrule Web",reason:"fallback"}}}function Yv(t,e){if(e&&!(t!=="rate_limited"&&t!=="invite_resent_cooldown_hit"&&t!=="invite_declined_cooldown"))return createHash("sha256").update(e.trim().toLowerCase()).digest("hex")}function Xv(t,e){if(t==="not_authenticated"||t==="session_expired_security_epoch")return [{label:"Sign in again",command:"pathrule login"}];if(t==="org_required")return [{label:"Choose an organization",command:"pathrule org use <slug-or-id>"}];if(t==="workspace_not_found")return [{label:"List workspaces",command:"pathrule workspace list"}];if(t==="rate_limited"||t==="invite_resent_cooldown_hit"||t==="invite_declined_cooldown")return [{label:"Retry later"}];if(e)return [{label:e.label,url:e.url}]}function Zv(t){switch(t){case "invalid_email":return "Enter a valid email address.";case "invalid_role":return "Role must be admin, editor, or viewer.";case "not_authenticated":return "Pathrule CLI is not signed in.";case "session_expired_security_epoch":return "Your session is stale after a security change. Sign in again.";case "org_required":return "No organization is selected.";case "workspace_not_found":return "Workspace context not found for that organization.";case "forbidden":case "permission_denied":return "Your current role cannot invite teammates to this organization.";case "free_plan_invites_disabled":return "Invites require a paid Pathrule organization plan.";case "subscription_not_invitable":case "subscription_frozen":return "Invites are blocked until billing is reactivated.";case "paid_seats_required":case "seat_limit_reached":return "Pathrule could not automatically add paid seat coverage for this invite.";case "billing_update_failed":return "Billing could not be updated for this invite. Review billing before sending it.";case "rate_limited":return "Rate limit reached, try again later.";case "invite_resent_cooldown_hit":case "invite_declined_cooldown":return "Please wait before inviting this email again.";case "already_member":case "email_already_member":return "That email is already a member of this organization.";case "invite_pending":return "There is already a pending invite for this email.";case "organization_not_found":return "Organization not found.";default:return t.replace(/_/g," ")}}async function Qv(t,e,r,n){if(!r.billingRequirement)return {ok:true,adjustment:{status:r.billingImpact.seat_effect==="paid_extra_available"?"already_covered":"not_needed",target_seats:r.billingImpact.target_active_seats,required_paid_extra_seats:r.billingImpact.required_paid_extra_seats,paid_extra_seats_after:r.billingImpact.current_paid_extra_seats}};let i=r.billingRequirement,s={target_seats:i.targetSeats,required_paid_extra_seats:i.requiredPaidExtraSeats,gift_seat_cap:i.giftSeatCap,current_paid_extra_seats:i.currentPaidExtraSeats},o=null;try{let{data:a,error:l}=await t.functions.invoke("start-paid-seat-checkout",{body:{org_id:e,target_seats:i.targetSeats,return_url_origin:eS(n)}});if(l)return {ok:!1,error:"billing_update_failed",details:s};o=a;}catch{return {ok:false,error:"billing_update_failed",details:s}}return o?.ok?o.url?{ok:false,error:"paid_seats_required",details:s}:{ok:true,adjustment:{status:o.updated?"updated":"already_covered",target_seats:i.targetSeats,required_paid_extra_seats:i.requiredPaidExtraSeats,paid_extra_seats_after:o.paid_extra_seats}}:{ok:false,error:o?.error??"billing_update_failed",details:s}}function eS(t){return (t.PATHRULE_WEB_URL??"https://app.pathrule.io").replace(/\/$/,"")}function tS(t){let e=t?.trim().toLowerCase();if(!e||e==="member")return "editor";if(e==="admin"||e==="editor"||e==="viewer")return e;throw new Te("invalid_invite_role",`Invalid invite role "${t}".`)}function jp(t,e,r){if(!t)throw new Te(r,e);return t}async function rS(t,e){let[r,n]=await Promise.all([t.from("organizations").select("plan, subscription_status, trial_status, trial_seat_cap, paid_extra_seats").eq("id",e).maybeSingle(),t.from("organization_members").select("id",{count:"exact",head:true}).eq("organization_id",e)]);if(r.error)throw r.error;if(n.error)throw n.error;let i=Rl(r.data,n.count??0);return {failure:i.failure?{error:i.failure.error}:null,billingImpact:i.billingImpact,billingRequirement:i.billingRequirement}}Ee();F();var $t=class extends Error{constructor(r,n=r){super(n);this.code=r;this.name="CliRefreshError";}code};async function gn(t,e={}){let r=await Di(t),n=await fa(t,r.id),i=await el(n,{workspace_id:r.id,include_in_progress:e.includeInProgress});if(!i.ok)throw ga(i.error);return i.data.slice(0,sS(e.limit)).map(s=>Lp(s,r.id,t))}async function ua(t,e,r={}){let n=await Di(t),i=e??await iS(t),s=await fa(t,n.id),o=await tl(s,{refresh_id:i,claimed_by:r.claimedBy??"codex"});if(!o.ok)throw ga(o.error);return Up(o.data,t)}async function da(t,e,r,n={}){await Di(t);let i=await fa(t),s=await rl(i,{refresh_id:e,status:r,note:n.note,claimed_by:n.claimedBy??"codex"});if(!s.ok)throw ga(s.error);return Up(s.data,t)}async function pa(t,e){let r=await Di(t);if(!e){let l=(await gn(t,{includeInProgress:true,limit:1}))[0];if(!l)throw new $t("refresh_not_found","No pending refresh tasks found.");return l}let{supabase:n}=await C(t),{data:i,error:s}=await n.from("suggestion_refreshes").select("id, workspace_id, subject_type, subject_id, formula_id, status, created_at, brief").eq("id",e).eq("workspace_id",r.id).maybeSingle();if(s)throw s;if(!i)throw new $t("refresh_not_found",`Refresh ${e} not found.`);let o=i,a=o.brief??{};return Lp({id:o.id,subjectType:o.subject_type,subjectId:o.subject_id,subjectTitle:a.subject?.title??"(unknown)",nodePath:a.subject?.nodePath??"/",formulaId:o.formula_id,humanReason:a.signal?.humanReason??o.formula_id,status:o.status,createdAt:o.created_at,hasProposedPatch:!!a.proposedPatch?.newBody},r.id,t)}function ji(t,e={}){let r=t.open_targets.find(n=>n.kind==="web")??{kind:"web",url:t.url,label:"Open refresh task in Pathrule Web",reason:"preferred"};if(e.forceWeb)return {...r,reason:"forced"};if(e.preferDesktopApp){let n=t.open_targets.find(i=>i.kind==="desktop-app");return n||{...r,reason:"fallback"}}return t.open_targets[0]??r}function ha(t,e,r){return `${(r.PATHRULE_WEB_URL??"https://app.pathrule.io").replace(/\/$/,"")}/workspace/${encodeURIComponent(t)}?tab=suggestions&refresh=${encodeURIComponent(e)}`}function nS(t,e){return `pathrule://workspace/${encodeURIComponent(t)}/refresh/${encodeURIComponent(e)}`}async function iS(t){let e=(await gn(t,{limit:1}))[0];if(!e)throw new $t("refresh_not_found","No pending refresh tasks found.");return e.id}async function Di(t){let e=await M(t);if(!e)throw new $t("workspace_required","No current workspace. Run pathrule workspace use <name-or-id>.");return e}async function fa(t,e=null){let{session:r,supabase:n}=await C(t);return {supabase:n,userId:r.user.id,workspaceId:e,clientId:"codex"}}function Lp(t,e,r){let n=ha(e,t.id,r);return {...t,workspace_id:e,url:n,open_targets:[Wp(e,t.id,r),Bp(e,t.id)]}}function Up(t,e){return {...t,url:ha(t.workspaceId,t.id,e),open_targets:[Wp(t.workspaceId,t.id,e),Bp(t.workspaceId,t.id)]}}function Wp(t,e,r){return {kind:"web",url:ha(t,e,r),label:"Open refresh task in Pathrule Web",reason:"preferred"}}function Bp(t,e){return {kind:"desktop-app",url:nS(t,e),label:"Open refresh task in Pathrule Desktop",reason:"fallback"}}function sS(t){return !t||!Number.isFinite(t)?20:Math.min(Math.max(Math.trunc(t),1),100)}function ga(t){return new $t(t.code,t.message)}K();K();var gS=promisify(execFile),mS=1440*60*1e3;function Fp(t,e=process.env){return join(A(e).home,"cache",t,"bootstrap-v2-brief.json")}async function Hp(t){let e=Fp(t.workspaceId,t.env),r=t.now??new Date;try{let[n,i,s]=await Promise.all([readFile(e,"utf8"),stat(e),qp(t.localRootPath)]);if(r.getTime()-i.mtimeMs>mS)return {ok:!1,brief:null,cachePath:e,reason:"expired"};let o=JSON.parse(n);return o.schemaVersion!==1||o.workspaceId!==t.workspaceId||o.localRootPath!==t.localRootPath||o.brief.version!==2?{ok:!1,brief:null,cachePath:e,reason:"mismatch"}:o.gitHead!==s?{ok:!1,brief:null,cachePath:e,reason:"git_head_changed"}:{ok:!0,brief:o.brief,cachePath:e}}catch{return {ok:false,brief:null,cachePath:e,reason:"missing"}}}async function ma(t){let e=Fp(t.workspaceId,t.env),r={schemaVersion:1,workspaceId:t.workspaceId,localRootPath:t.localRootPath,gitHead:await qp(t.localRootPath),cachedAt:new Date().toISOString(),brief:t.brief};await mkdir(dirname(e),{recursive:true});let n=`${e}.tmp`;return await writeFile(n,`${JSON.stringify(r,null,2)}
184
+ `}function g(t,e){let r={ok:"[ok]",warn:"[warn]",error:"[error]",info:"[info]"};return e.color?`${{ok:"\x1B[32m",warn:"\x1B[33m",error:"\x1B[31m",info:"\x1B[36m"}[t]}${r[t]}\x1B[0m`:r[t]}Ee();var Jv=/^[^\s@]+@[^\s@]+\.[^\s@]+$/i,Te=class extends Error{constructor(r,n){super(n);this.code=r;this.name="CliInviteUsageError";}code};function la(t){let e=[],r="editor",n,i;for(let o=0;o<t.length;o+=1){let a=t[o];if(a){if(a==="--role"){r=tS(t[++o]);continue}if(a==="--org"){n=Dp(t[++o],"--org requires a value","invite_org_required");continue}if(a==="--workspace"){i=Dp(t[++o],"--workspace requires a value","invite_workspace_required");continue}if(a.startsWith("--"))throw new Te("unknown_invite_option",`Unknown invite option "${a}".`);e.push(a);}}let s=e[0];if(!s)throw new Te("invite_email_required","Usage: pathrule invite <email> [--role admin|editor|viewer] [--org <slug-or-id>] [--workspace <name-or-id>]");if(e.length>1)throw new Te("unexpected_invite_argument",`Unexpected extra argument "${e[1]}".`);return {email:s,role:r,orgSelector:n,workspaceSelector:i}}async function ca(t,e){let r=t.email.trim().toLowerCase();if(!Jv.test(r))return Ot("invalid_email",null,null,e,r);let{session:n,supabase:i}=await C(e),s=await Kv(t.orgSelector,e);if(!s)return Ot("org_required",null,null,e,r);if(s.role!=="admin"&&s.role!=="owner")return Ot("forbidden",s,null,e,r);let o=await Vv(i,n.user.id,s.id,t.workspaceSelector,e);if(!o&&t.workspaceSelector)return Ot("workspace_not_found",s,null,e,r);let a=await rS(i,s.id);if(a.failure)return Ot(a.failure.error,s,o,e,r,a.failure.details);let l=await Qv(i,s.id,a,e);if(!l.ok)return Ot(l.error,s,o,e,r,l.details);let{data:c,error:u}=await i.rpc("create_org_invite",{p_org_id:s.id,p_email:r,p_role:t.role}),d=c,p=d&&d.ok===false?d.error:void 0;if(u||!d||d.ok!==true)return Ot(u?.message??p??"invite_failed",s,o,e,r);let h=true;try{let{error:m}=await i.functions.invoke("send-org-invite-email",{body:{invite_id:d.invite_id}});m&&(h=!1);}catch{h=false;}let f={kind:"web",url:ee(s,e,"members"),label:"Open team in Pathrule Web",reason:"preferred"};return {ok:true,invite_id:d.invite_id,email:d.email,role:d.role,email_sent:h,billing_impact:a.billingImpact,billing_adjustment:l.adjustment,organization:jp(s),workspace:Mp(o),open_target:f,next_steps:[{label:"Open team in Pathrule Web",url:f.url},...h?[]:[{label:"Retry invite email from Pathrule Web",url:f.url}]]}}function jp(t){return t?{id:t.id,name:t.name,slug:t.slug,role:t.role}:null}function Mp(t){return t?{id:t.id,name:t.name}:null}async function Kv(t,e){return t?(await we(e)).find(n=>n.id===t||n.slug===t)??null:D(e)}async function Vv(t,e,r,n,i){if(!n){let a=await M(i);return a?.organization_id===r?a:null}let{data:s,error:o}=await t.from("workspaces").select("id, organization_id, name, access_mode, git_remote_url, git_owner, git_repo, user_workspace_paths!left(local_root_path, user_id)").eq("organization_id",r).is("archived_at",null);if(o)throw o;for(let a of s??[]){let c=(a.user_workspace_paths??[]).find(d=>d.user_id===e)??null,u={id:a.id,organization_id:a.organization_id,name:a.name,access_mode:a.access_mode,git_remote_url:a.git_remote_url,git_owner:a.git_owner,git_repo:a.git_repo,local_root_path:c?.local_root_path??null,current:false};if(u.id===n||u.name===n)return u}return null}function Ot(t,e,r,n,i,s){let o=Gv(t,e,n),a=Yv(t,i);return {ok:false,error:t,message:Zv(t),...a?{email_hash:a}:{},organization:jp(e),workspace:Mp(r),open_target:o,next_steps:Xv(t,o),...s}}function Gv(t,e,r){if(e){if(t==="free_plan_invites_disabled"||t==="invite_blocked_billing"||t==="billing_update_failed")return {kind:"web",url:ee(e,r,"billing"),label:"Open billing in Pathrule Web",reason:"fallback"};if(t==="subscription_not_invitable"||t==="subscription_frozen")return {kind:"web",url:`${ee(e,r,"billing")}/reactivate`,label:"Open billing reactivation in Pathrule Web",reason:"fallback"};if(t==="paid_seats_required"||t==="seat_limit_reached")return {kind:"web",url:ee(e,r,"billing"),label:"Open billing in Pathrule Web",reason:"fallback"};if(t==="forbidden"||t==="permission_denied"||t==="already_member"||t==="email_already_member"||t==="invite_pending")return {kind:"web",url:ee(e,r,"members"),label:"Open team in Pathrule Web",reason:"fallback"}}}function Yv(t,e){if(e&&!(t!=="rate_limited"&&t!=="invite_resent_cooldown_hit"&&t!=="invite_declined_cooldown"))return createHash("sha256").update(e.trim().toLowerCase()).digest("hex")}function Xv(t,e){if(t==="not_authenticated"||t==="session_expired_security_epoch")return [{label:"Sign in again",command:"pathrule login"}];if(t==="org_required")return [{label:"Choose an organization",command:"pathrule org use <slug-or-id>"}];if(t==="workspace_not_found")return [{label:"List workspaces",command:"pathrule workspace list"}];if(t==="rate_limited"||t==="invite_resent_cooldown_hit"||t==="invite_declined_cooldown")return [{label:"Retry later"}];if(e)return [{label:e.label,url:e.url}]}function Zv(t){switch(t){case "invalid_email":return "Enter a valid email address.";case "invalid_role":return "Role must be admin, editor, or viewer.";case "not_authenticated":return "Pathrule CLI is not signed in.";case "session_expired_security_epoch":return "Your session is stale after a security change. Sign in again.";case "org_required":return "No organization is selected.";case "workspace_not_found":return "Workspace context not found for that organization.";case "forbidden":case "permission_denied":return "Your current role cannot invite teammates to this organization.";case "free_plan_invites_disabled":return "Invites require a paid Pathrule organization plan.";case "subscription_not_invitable":case "subscription_frozen":return "Invites are blocked until billing is reactivated.";case "paid_seats_required":case "seat_limit_reached":return "Pathrule could not automatically add paid seat coverage for this invite.";case "billing_update_failed":return "Billing could not be updated for this invite. Review billing before sending it.";case "rate_limited":return "Rate limit reached, try again later.";case "invite_resent_cooldown_hit":case "invite_declined_cooldown":return "Please wait before inviting this email again.";case "already_member":case "email_already_member":return "That email is already a member of this organization.";case "invite_pending":return "There is already a pending invite for this email.";case "organization_not_found":return "Organization not found.";default:return t.replace(/_/g," ")}}async function Qv(t,e,r,n){if(!r.billingRequirement)return {ok:true,adjustment:{status:r.billingImpact.seat_effect==="paid_extra_available"?"already_covered":"not_needed",target_seats:r.billingImpact.target_active_seats,required_paid_extra_seats:r.billingImpact.required_paid_extra_seats,paid_extra_seats_after:r.billingImpact.current_paid_extra_seats}};let i=r.billingRequirement,s={target_seats:i.targetSeats,required_paid_extra_seats:i.requiredPaidExtraSeats,gift_seat_cap:i.giftSeatCap,current_paid_extra_seats:i.currentPaidExtraSeats},o=null;try{let{data:a,error:l}=await t.functions.invoke("start-paid-seat-checkout",{body:{org_id:e,target_seats:i.targetSeats,return_url_origin:eS(n)}});if(l)return {ok:!1,error:"billing_update_failed",details:s};o=a;}catch{return {ok:false,error:"billing_update_failed",details:s}}return o?.ok?o.url?{ok:false,error:"paid_seats_required",details:s}:{ok:true,adjustment:{status:o.updated?"updated":"already_covered",target_seats:i.targetSeats,required_paid_extra_seats:i.requiredPaidExtraSeats,paid_extra_seats_after:o.paid_extra_seats}}:{ok:false,error:o?.error??"billing_update_failed",details:s}}function eS(t){return (t.PATHRULE_WEB_URL??"https://app.pathrule.io").replace(/\/$/,"")}function tS(t){let e=t?.trim().toLowerCase();if(!e||e==="member")return "editor";if(e==="admin"||e==="editor"||e==="viewer")return e;throw new Te("invalid_invite_role",`Invalid invite role "${t}".`)}function Dp(t,e,r){if(!t)throw new Te(r,e);return t}async function rS(t,e){let[r,n]=await Promise.all([t.from("organizations").select("plan, subscription_status, trial_status, trial_seat_cap, paid_extra_seats").eq("id",e).maybeSingle(),t.from("organization_members").select("id",{count:"exact",head:true}).eq("organization_id",e)]);if(r.error)throw r.error;if(n.error)throw n.error;let i=Rl(r.data,n.count??0);return {failure:i.failure?{error:i.failure.error}:null,billingImpact:i.billingImpact,billingRequirement:i.billingRequirement}}Ee();F();var $t=class extends Error{constructor(r,n=r){super(n);this.code=r;this.name="CliRefreshError";}code};async function gn(t,e={}){let r=await ji(t),n=await fa(t,r.id),i=await el(n,{workspace_id:r.id,include_in_progress:e.includeInProgress});if(!i.ok)throw ga(i.error);return i.data.slice(0,sS(e.limit)).map(s=>Lp(s,r.id,t))}async function ua(t,e,r={}){let n=await ji(t),i=e??await iS(t),s=await fa(t,n.id),o=await tl(s,{refresh_id:i,claimed_by:r.claimedBy??"codex"});if(!o.ok)throw ga(o.error);return Up(o.data,t)}async function da(t,e,r,n={}){await ji(t);let i=await fa(t),s=await rl(i,{refresh_id:e,status:r,note:n.note,claimed_by:n.claimedBy??"codex"});if(!s.ok)throw ga(s.error);return Up(s.data,t)}async function pa(t,e){let r=await ji(t);if(!e){let l=(await gn(t,{includeInProgress:true,limit:1}))[0];if(!l)throw new $t("refresh_not_found","No pending refresh tasks found.");return l}let{supabase:n}=await C(t),{data:i,error:s}=await n.from("suggestion_refreshes").select("id, workspace_id, subject_type, subject_id, formula_id, status, created_at, brief").eq("id",e).eq("workspace_id",r.id).maybeSingle();if(s)throw s;if(!i)throw new $t("refresh_not_found",`Refresh ${e} not found.`);let o=i,a=o.brief??{};return Lp({id:o.id,subjectType:o.subject_type,subjectId:o.subject_id,subjectTitle:a.subject?.title??"(unknown)",nodePath:a.subject?.nodePath??"/",formulaId:o.formula_id,humanReason:a.signal?.humanReason??o.formula_id,status:o.status,createdAt:o.created_at,hasProposedPatch:!!a.proposedPatch?.newBody},r.id,t)}function Di(t,e={}){let r=t.open_targets.find(n=>n.kind==="web")??{kind:"web",url:t.url,label:"Open refresh task in Pathrule Web",reason:"preferred"};if(e.forceWeb)return {...r,reason:"forced"};if(e.preferDesktopApp){let n=t.open_targets.find(i=>i.kind==="desktop-app");return n||{...r,reason:"fallback"}}return t.open_targets[0]??r}function ha(t,e,r){return `${(r.PATHRULE_WEB_URL??"https://app.pathrule.io").replace(/\/$/,"")}/workspace/${encodeURIComponent(t)}?tab=suggestions&refresh=${encodeURIComponent(e)}`}function nS(t,e){return `pathrule://workspace/${encodeURIComponent(t)}/refresh/${encodeURIComponent(e)}`}async function iS(t){let e=(await gn(t,{limit:1}))[0];if(!e)throw new $t("refresh_not_found","No pending refresh tasks found.");return e.id}async function ji(t){let e=await M(t);if(!e)throw new $t("workspace_required","No current workspace. Run pathrule workspace use <name-or-id>.");return e}async function fa(t,e=null){let{session:r,supabase:n}=await C(t);return {supabase:n,userId:r.user.id,workspaceId:e,clientId:"codex"}}function Lp(t,e,r){let n=ha(e,t.id,r);return {...t,workspace_id:e,url:n,open_targets:[Wp(e,t.id,r),Bp(e,t.id)]}}function Up(t,e){return {...t,url:ha(t.workspaceId,t.id,e),open_targets:[Wp(t.workspaceId,t.id,e),Bp(t.workspaceId,t.id)]}}function Wp(t,e,r){return {kind:"web",url:ha(t,e,r),label:"Open refresh task in Pathrule Web",reason:"preferred"}}function Bp(t,e){return {kind:"desktop-app",url:nS(t,e),label:"Open refresh task in Pathrule Desktop",reason:"fallback"}}function sS(t){return !t||!Number.isFinite(t)?20:Math.min(Math.max(Math.trunc(t),1),100)}function ga(t){return new $t(t.code,t.message)}K();K();var gS=promisify(execFile),mS=1440*60*1e3;function Fp(t,e=process.env){return join(A(e).home,"cache",t,"bootstrap-v2-brief.json")}async function Hp(t){let e=Fp(t.workspaceId,t.env),r=t.now??new Date;try{let[n,i,s]=await Promise.all([readFile(e,"utf8"),stat(e),qp(t.localRootPath)]);if(r.getTime()-i.mtimeMs>mS)return {ok:!1,brief:null,cachePath:e,reason:"expired"};let o=JSON.parse(n);return o.schemaVersion!==1||o.workspaceId!==t.workspaceId||o.localRootPath!==t.localRootPath||o.brief.version!==2?{ok:!1,brief:null,cachePath:e,reason:"mismatch"}:o.gitHead!==s?{ok:!1,brief:null,cachePath:e,reason:"git_head_changed"}:{ok:!0,brief:o.brief,cachePath:e}}catch{return {ok:false,brief:null,cachePath:e,reason:"missing"}}}async function ma(t){let e=Fp(t.workspaceId,t.env),r={schemaVersion:1,workspaceId:t.workspaceId,localRootPath:t.localRootPath,gitHead:await qp(t.localRootPath),cachedAt:new Date().toISOString(),brief:t.brief};await mkdir(dirname(e),{recursive:true});let n=`${e}.tmp`;return await writeFile(n,`${JSON.stringify(r,null,2)}
185
185
  `,{encoding:"utf8",mode:O}),await rename(n,e),{cachePath:e}}async function qp(t){try{let{stdout:e}=await gS("git",["rev-parse","HEAD"],{cwd:t,timeout:1e3});return e.trim()||null}catch{return null}}var _S=/\b(?:packages|apps|src|docs|supabase|types|scripts|config|public|tests?)\/[A-Za-z0-9._/-]+/g;function Nt(t,e="/"){if(!t)return e;let r=t.trim().replace(/\\/g,"/").replace(/^\/+/,"").replace(/\/+$/,"");return !r||r==="."?e:`/${r}`}function hr(t){let e=Nt(t),r=e.replace(/^\/+/,"");return r.includes("/")?Nt(r.slice(0,r.lastIndexOf("/"))):e}function zp(t){let e=new Set;for(let r of t.matchAll(_S)){let n=r[0].replace(/[),.;:]+$/,"");n.length>2&&e.add(n);}return [...e].slice(0,20)}function _a(t,e){let r=t.find(Boolean);return r?hr(r):e}function Jp(t,e){let r=new Set,n=[];for(let i of t){let s=Nt(i);if(!r.has(s)&&(r.add(s),n.push(s),n.length>=e))break}return n}var wa=200,bS=1024*1024,vS=8*1024*1024,SS=new Set([".git","node_modules","dist","build","coverage","vendor","archive","archived",".next",".turbo"]),Yp=/\b(setup|development|architecture|testing|security|release|deploy|contributing|conventions?|workflow|migration)\b/i,CS=/\b(must|never|always|required|before merging|run|do not|don't|avoid|ensure)\b/gi,ES=/\b(pnpm|npm|bun|yarn|supabase|vercel|gh|electron-builder|vitest|tsx|tsc)\b/g;async function Xp(t){let e=[],r=await RS(t,e),n=[],i=0;for(let a of r){if(i>=vS){e.push("Documentation scan reached the 8 MB budget.");break}let l=await stat(join(t,a)).catch(()=>null);if(!l||l.size>bS)continue;i+=l.size;let c=await readFile(join(t,a),"utf8").catch(()=>"");if(c.trim())for(let u of PS(c)){let d=TS(a,u);d&&n.push(d);}}let s=n.sort((a,l)=>Vp(l)-Vp(a)).slice(0,40),o=new Set(s.flatMap(a=>a.pathMentions)).size;return {findings:s,candidateMemories:OS(s),candidateRules:$S(s),docsFilesScanned:r.length,filesMentionedByDocs:o,warnings:e}}async function RS(t,e){let r=[];return await n(t,""),r.sort((i,s)=>Kp(i)-Kp(s)).slice(0,wa);async function n(i,s){if(r.length>=wa)return;let o=await readdir(i,{withFileTypes:true}).catch(()=>[]);for(let a of o){if(r.length>=wa){e.push("Documentation scan reached the 200 file budget.");return}let l=s?`${s}/${a.name}`:a.name;if(a.isDirectory()){if(SS.has(a.name))continue;await n(join(i,a.name),l);continue}a.isFile()&&xS(l)&&r.push(l);}}}function xS(t){let e=basename(t).toLowerCase();return e==="readme.md"||/^readme\..+\.md$/.test(e)||e==="contributing.md"?true:t.startsWith("docs/")&&/\.(md|mdx)$/i.test(t)}function Kp(t){let e=basename(t).toLowerCase();return e==="readme.md"?0:e==="contributing.md"?1:t.startsWith("docs/")?2:3}function PS(t){let e=t.split(/\r?\n/),r=[],n={body:""};for(let i of e){let s=i.match(/^(#{1,4})\s+(.+?)\s*#*\s*$/);s?(n.body.trim()&&r.push(n),n={heading:s[2],body:""}):n.body+=`${i}
186
186
  `;}return n.body.trim()&&r.push(n),r}function TS(t,e){let r=`${e.heading??""}
187
- ${e.body}`.trim();if(AS(e.heading,r))return null;let n=[...r.matchAll(CS)].length,i=zp(r),s=[...new Set([...r.matchAll(ES)].map(a=>a[0]))].slice(0,8);return !(e.heading?Yp.test(e.heading):false)&&n===0&&i.length===0&&s.length===0?null:{path:t,heading:e.heading,kind:IS(e.heading??r),summary:NS(r),pathMentions:i,commandMentions:s,imperativeScore:n,excerpt:jS(r)}}function AS(t,e){let r=`${t??""} ${e.slice(0,200)}`.toLowerCase();return /\b(changelog|release notes|history)\b/.test(r)&&/\b\d{4}-\d{2}-\d{2}\b/.test(r)}function IS(t){let e=t.toLowerCase();return e.includes("security")?"security":e.includes("test")?"testing":e.includes("release")||e.includes("deploy")?"release":e.includes("architecture")?"architecture":e.includes("setup")||e.includes("development")||e.includes("contributing")?"workflow":"convention"}function OS(t){return t.filter(e=>e.kind==="architecture"||e.kind==="workflow"||e.pathMentions.length>0).slice(0,18).map(e=>{let r=_a(e.pathMentions,hr(e.path));return {title:Zp("Project note",e),bodyGuidance:`Write a concise memory summarizing ${e.summary}. Include the relevant paths and commands, but do not paste the source document verbatim.`,nodePath:r,confidence:eh(.55+e.pathMentions.length*.03+e.commandMentions.length*.02),evidence:[Qp(e)]}})}function $S(t){return t.filter(e=>e.imperativeScore>0||e.kind==="security"||e.kind==="testing").slice(0,12).map(e=>({title:Zp("Rule",e),bodyGuidance:`Write a rule from the documented requirement: ${e.summary}. Keep it imperative and scoped to the most specific path.`,nodePath:_a(e.pathMentions,Nt(e.kind==="security"?"/":hr(e.path))),confidence:eh(.62+e.imperativeScore*.04),evidence:[Qp(e)]}))}function Zp(t,e){let r=e.heading||e.summary;return `${t}: ${r.replace(/[`*_#]/g,"").slice(0,80)}`}function Qp(t){return {kind:"doc",path:t.path,heading:t.heading,excerpt:t.excerpt}}function Vp(t){return t.imperativeScore*3+t.pathMentions.length*2+t.commandMentions.length+(t.heading&&Yp.test(t.heading)?8:0)}function NS(t){return t.replace(/\s+/g," ").replace(/[`*_#>-]/g,"").trim().slice(0,220)}function jS(t){return t.replace(/\s+/g," ").trim().slice(0,280)}function eh(t){return Math.max(0,Math.min(1,Number(t.toFixed(2))))}var DS=/\b(fix|bug|regression|hotfix|breaking|break|migration|schema|refactor|rewrite|cleanup)\b/i,rh=/\b(breaking|break|migration|schema)\b/i,MS=/\b(fix|bug|regression|hotfix)\b/i,LS=/\b(refactor|rewrite|cleanup)\b/i;function nh(t){let e=US(t),r=new Map;for(let i of e){let s=rh.test(i.subject)?"breaking":MS.test(i.subject)?"fix":LS.test(i.subject)?"refactor":null;if(!s)continue;let o=new Set;for(let a of i.files){o.add(Nt(a)),o.add(hr(a));let l=WS(a);l&&o.add(l);}for(let a of o){let l=r.get(a)??{path:a,fix:0,breaking:0,refactor:0,commits:new Map};l.commits.set(i.hash,i),s==="fix"&&(l.fix+=1),s==="breaking"&&(l.breaking+=1),s==="refactor"&&(l.refactor+=1),r.set(a,l);}}return {findings:[...r.values()].filter(i=>i.commits.size>=3||i.breaking>=1).sort((i,s)=>th(s)-th(i)).slice(0,15).map(BS),commitsScanned:e.length}}function US(t){let e=[];for(let r of t.split("")){let n=r.split(/\r?\n/).map(c=>c.trim()).filter(Boolean),i=n[0];if(!i)continue;let[s,o,a]=i.split("");if(!s||!o||!a||!DS.test(a)||/^merge\b/i.test(a))continue;let l=n.slice(1).filter(c=>!c.includes(" => "));l.length<1||l.length>30&&!rh.test(a)||e.push({hash:s,date:o,subject:a,files:l});}return e}function WS(t){let e=t.split("/");return (e[0]==="packages"||e[0]==="apps")&&e[1]?`/${e[0]}/${e[1]}`:e[0]==="supabase"&&e[1]?`/supabase/${e[1]}`:null}function th(t){return t.fix*3+t.breaking*5+t.refactor*2+t.commits.size}function BS(t){let e=[...t.commits.values()].sort((i,s)=>s.date.localeCompare(i.date)),r=e[0],n=e.slice(0,4).map(i=>({kind:"commit",commit:i.hash.slice(0,12),path:t.path,excerpt:`${i.date} ${i.subject}`}));return {path:t.path,summary:`${t.path} has ${t.fix} fix, ${t.breaking} breaking/schema, and ${t.refactor} refactor commits in recent history.`,fixCount:t.fix,breakingCount:t.breaking,refactorCount:t.refactor,uniqueCommits:t.commits.size,latestDate:r?.date,evidence:n}}var oh=promisify(execFile);async function ah(t){let e=t.now??new Date;if(!t.force){let r=await Hp({workspaceId:t.workspaceId,localRootPath:t.localRootPath,env:t.env,now:e});if(r.ok&&r.brief)return {ok:true,brief:r.brief,cachePath:r.cachePath,reusedCache:true}}try{let r=await QS(KS(t,e),t.timeoutMs??3e4),n=await ma({workspaceId:t.workspaceId,localRootPath:t.localRootPath,brief:r,env:t.env});return {ok:!0,brief:r,cachePath:n.cachePath,reusedCache:!1}}catch(r){let n=ZS(t,e,r instanceof Error?r.message:String(r)),i=await ma({workspaceId:t.workspaceId,localRootPath:t.localRootPath,brief:n,env:t.env}).catch(()=>({cachePath:null}));return {ok:false,brief:n,cachePath:i.cachePath,reusedCache:false,error:n.warnings[0]}}}async function KS(t,e){let r=[],[n,i,s,o,a]=await Promise.all([VS(t.supabase,t.workspaceId),Xp(t.localRootPath),GS(t.localRootPath,r),XS(t.localRootPath,r),YS(t.localRootPath,r)]);r.push(...i.warnings);let l=nh(s),c=a?hs(a):[],u=ps(o).map(w=>({title:w.title,summary:w.content})),d=u.map(w=>({title:w.title,bodyGuidance:`Write a short memory noting that ${w.summary.toLowerCase()}`,nodePath:"/",confidence:.72,evidence:[{kind:"stack",excerpt:w.summary}]})),p=l.findings.map(w=>({title:`Risk hotspot: ${w.path}`,bodyGuidance:`Write a memory explaining the risk pattern for ${w.path}: ${w.summary} Include the kinds of changes that should be reviewed together.`,nodePath:w.path,confidence:Math.min(.95,.6+w.uniqueCommits*.04+w.breakingCount*.08),evidence:w.evidence})),h=ih([...i.candidateMemories,...p,...d]),f=ih(i.candidateRules);h=sh(h,n.titles).slice(0,15),f=sh(f,n.titles).slice(0,8);let m=n.memoryCount+n.ruleCount>=8;m&&(h=[],f=[],r.push("Workspace already has meaningful setup content; Bootstrap v2 will avoid duplicate starter guidance."));let _=Jp([...f.map(w=>w.nodePath),...h.map(w=>w.nodePath),...i.findings.flatMap(w=>[w.path,...w.pathMentions]),...l.findings.map(w=>w.path)],20),b=m?"Bootstrap v2 found existing Pathrule setup content. Use pathrule_get_context for task-specific context instead of writing duplicate starter memories or rules.":`Bootstrap v2 prepared ${h.length} memory candidates and ${f.length} rule candidates from ${i.docsFilesScanned} docs files and ${l.commitsScanned} risky commits.`;return {version:2,workspaceId:t.workspaceId,localRootPath:t.localRootPath,generatedAt:e.toISOString(),summary:b,stackSignals:u,documentationFindings:i.findings,commitWisdom:l.findings,candidateMemories:h,candidateRules:f,candidateSkills:[],suggestedOrder:_,coverage:{docsFilesScanned:i.docsFilesScanned,commitsScanned:l.commitsScanned,filesMentionedByDocs:i.filesMentionedByDocs,coChangePairsAvailable:c.length},warnings:r,alreadyBootstrapped:m}}async function VS(t,e){if(!t)return {memoryCount:0,ruleCount:0,skillCount:0,titles:new Set};let[r,n,i]=await Promise.all([t.from("memories").select("title",{count:"exact"}).eq("workspace_id",e).limit(200),t.from("rules").select("name",{count:"exact"}).eq("workspace_id",e).limit(200),t.from("skills").select("name",{count:"exact"}).eq("workspace_id",e).limit(50)]),s=new Set;for(let o of r.data??[])o.title&&s.add(mn(o.title));for(let o of n.data??[])o.name&&s.add(mn(o.name));for(let o of i.data??[])o.name&&s.add(mn(o.name));return {memoryCount:r.count??s.size,ruleCount:n.count??0,skillCount:i.count??0,titles:s}}async function GS(t,e){try{let{stdout:r}=await oh("git",["log","--date=short","--format=%x1e%H%x1f%ad%x1f%s","--name-only","-n","5000"],{cwd:t,maxBuffer:52428800,timeout:2e4});return r}catch{return e.push("Git commit wisdom skipped; repository history was unavailable."),""}}async function YS(t,e){try{let{stdout:r}=await oh("git",["log","--name-only","--pretty=format:---","-n","10000"],{cwd:t,maxBuffer:52428800,timeout:2e4});return r}catch{return e.push("Git co-change scan skipped; repository history was unavailable."),""}}async function XS(t,e){let r=[];async function n(i,s){if(s>4||r.length>5e3)return;let o=await readdir(i,{withFileTypes:true}).catch(()=>[]);for(let a of o){if(a.name===".git"||a.name==="node_modules"||a.name==="dist")continue;let l=join(i,a.name);a.isDirectory()?await n(l,s+1):a.isFile()&&r.push(relative(t,l).replace(/\\/g,"/"));}}return await n(t,0).catch(()=>e.push("Stack detection skipped; file tree was unavailable.")),r}function ih(t){let e=new Map;for(let r of t){let n=`${r.nodePath}:${mn(r.title)}`,i=e.get(n);(!i||r.confidence>i.confidence)&&e.set(n,r);}return [...e.values()].sort((r,n)=>n.confidence-r.confidence)}function sh(t,e){return t.filter(r=>!e.has(mn(r.title)))}function mn(t){return t.toLocaleLowerCase("en-US").replace(/[^a-z0-9]+/g," ").trim()}function ZS(t,e,r){return {version:2,workspaceId:t.workspaceId,localRootPath:t.localRootPath,generatedAt:e.toISOString(),summary:"Bootstrap v2 could not complete the local scan. Use the fallback setup prompt.",stackSignals:[],documentationFindings:[],commitWisdom:[],candidateMemories:[],candidateRules:[],candidateSkills:[],suggestedOrder:[],coverage:{docsFilesScanned:0,commitsScanned:0,filesMentionedByDocs:0,coChangePairsAvailable:0},warnings:[r]}}function QS(t,e){return new Promise((r,n)=>{let i=setTimeout(()=>n(new Error("Bootstrap v2 scan timed out.")),e);t.then(s=>{clearTimeout(i),r(s);},s=>{clearTimeout(i),n(s);});})}F();K();li();F();async function uh(t,e,r=fetch){if(!e.gitRemoteUrl)return {status:"skipped",error:"missing_git_remote"};try{let{session:n,supabase:i}=await C(t),{data:s,error:o}=await i.from("beta_platform_invites").select("id").eq("claimed_user_id",n.user.id).eq("status","claimed").order("claimed_at",{ascending:!1}).limit(1);if(o)return {status:"skipped",error:"invite_lookup_unavailable"};let a=(s??[])[0]??null;if(!a)return {status:"skipped",error:"no_claimed_beta_invite"};let l=pe(t),c=await aC(t),u=await r(`${l.supabaseUrl}/functions/v1/process-beta-activation`,{method:"POST",headers:{"content-type":"application/json",apikey:l.supabaseAnonKey,Authorization:`Bearer ${n.access_token}`},body:JSON.stringify({invite_id:a.id,workspace_id:e.workspaceId,git_remote_url:e.gitRemoteUrl,machine_id:c,runtime_source:e.runtimeSource})}),d=await u.json().catch(()=>null);return !u.ok||!d?.status?{status:"skipped",error:"activation_unavailable"}:{status:d.status,credit_cents:ch(d.credit_cents),founder_bonus_cents:ch(d.founder_bonus_cents)}}catch{return {status:"skipped",error:"activation_unavailable"}}}async function aC(t){let e=join(A(t).home,"machine-install.json");try{let n=JSON.parse(await readFile(e,"utf8"));if(typeof n.machine_id=="string"&&n.machine_id.length>=16)return n.machine_id}catch{}let r=`cli_${randomUUID()}`;return await lC(e,{schema_version:1,machine_id:r}),r}async function lC(t,e){let r=dirname(t);await mkdir(r,{recursive:true,mode:D}),await chmod(r,D).catch(()=>{});let n=`${t}.tmp`;await writeFile(n,JSON.stringify(e,null,2),{encoding:"utf8",mode:O}),await chmod(n,O).catch(()=>{}),await rename(n,t);}function ch(t){return typeof t=="number"&&Number.isFinite(t)?t:void 0}Ee();var hC=promisify(execFile);async function Mi(t,e){let r=await j(e);if(!r)return {cwd:t,organization:null,candidates:[],recommended_action:"select_org"};let[n,i,s]=await Promise.all([Re(e),wh(t),wC(t,e)]),o=mC(t,r,n,i,s);return {cwd:t,organization:r,candidates:o,recommended_action:o.length===0?"create_workspace":o[0]?.confidence==="exact"||o[0]?.confidence==="high"?"attach_existing":"choose_workspace"}}async function fr(t,e,r,n={yes:false}){let i=gC(t);if(!i.shouldApply)return {plan:await Mi(e,r),applied:false,org_selected:null,workspace_action:"none",workspace:null,install:null,sync:null,beta_activation:null,bootstrap_v2:null};if(i.bootstrapRerun){let f=await M(r);if(!f?.id)throw new Error("workspace_required");let m=await hh(f.id,e,r,true);return {plan:await Mi(e,r),applied:true,org_selected:null,workspace_action:"none",workspace:f,install:null,sync:null,beta_activation:null,bootstrap_v2:m}}if(!n.yes)throw new Error("setup_requires_yes");let s=null;if(i.org){let{useCliOrg:f}=await Promise.resolve().then(()=>(Ee(),ju));s=(await f(i.org,r)).id;}let o=await Mi(e,r),a="none",l=null;if(i.createWorkspace){let f=await ae("create_workspace",r);if(!f.allowed)throw new Error(f.blocking_reason??"preflight_blocked");l=await bt(i.workspaceName??basename(e),e,r),a="created";}else i.workspaceSelector?(l=await xe(i.workspaceSelector,e,r),a="attached"):o.recommended_action==="attach_existing"&&o.candidates[0]?(l=await xe(o.candidates[0].workspace_id,e,r),a="attached"):i.selectCurrentWorkspace&&(l=await Zr(i.selectCurrentWorkspace,r),a="selected");o=await Mi(e,r);let c=i.target?await Ze(i.target,r):null,u=a==="attached"||a==="created"?await Le(r,e):null,d=fC(l),p=u?.ok&&d&&(a==="attached"||a==="created")?await hh(d,e,r,false):null,h=u?.ok&&(a==="attached"||a==="created")?await uh(r,{workspaceId:d,gitRemoteUrl:await wh(e),runtimeSource:"cli"}):null;return {plan:o,applied:true,org_selected:s,workspace_action:a,workspace:l,install:c,sync:u,beta_activation:h,bootstrap_v2:p}}async function hh(t,e,r,n){let{supabase:i}=await C(r),s=await ah({workspaceId:t,localRootPath:e,supabase:i,env:r,force:n});return {ok:s.ok,reused_cache:s.reusedCache,cache_path:s.cachePath,candidate_counts:{memories:s.brief.candidateMemories.length,rules:s.brief.candidateRules.length,skills:s.brief.candidateSkills.length},coverage:s.brief.coverage,summary:s.brief.summary,warnings:s.brief.warnings}}function fC(t){if(!t||typeof t!="object")return null;let e=t.id;if(typeof e=="string")return e;let r=t.workspace?.id;return typeof r=="string"?r:null}function gC(t){let e={org:null,workspaceSelector:null,workspaceName:null,createWorkspace:false,selectCurrentWorkspace:null,target:null,bootstrapRerun:false},r=false,n=false;for(let i=0;i<t.length;i+=1){let s=t[i],o=()=>{let a=t[i+1];if(!a||a.startsWith("--"))throw new Error(`missing_value:${s}`);return i+=1,a};if(s==="bootstrap"){if(r)throw new Error("unknown_setup_option:bootstrap");r=true;}else if(s==="--rerun"&&r)n=true;else if(s==="--org")e.org=o();else if(s==="--workspace"||s==="--workspace-id")e.workspaceSelector=o();else if(s==="--workspace-name")e.workspaceName=o();else if(s==="--create-workspace")e.createWorkspace=true;else if(s==="--select-workspace")e.selectCurrentWorkspace=o();else if(s==="--target")e.target=o();else throw new Error(`unknown_setup_option:${s}`)}if(r&&!n)throw new Error("missing_value:--rerun");return e.bootstrapRerun=r&&n,{...e,shouldApply:e.org!==null||e.workspaceSelector!==null||e.workspaceName!==null||e.createWorkspace||e.selectCurrentWorkspace!==null||e.target!==null||e.bootstrapRerun}}function mC(t,e,r,n,i){let s=mh(basename(t)),o=[],a=new Set,l=c=>{a.has(c.workspace_id)||(a.add(c.workspace_id),o.push(c));};for(let c of r){if(c.local_root_path===t){l(_n("cwd_mapping",c,e,"exact",false,"Exact local path mapping."));continue}if(n&&_C(c,n)){l(_n("git_remote",c,e,"high",true,"Git remote matches workspace metadata."));continue}if(i.has(c.id)){l(_n("hook_cache",c,e,"high",true,"Existing hook cache points at this folder."));continue}let u=mh(c.name);if(u===s){l(_n("name_match",c,e,"medium",true,"Folder name matches workspace name."));continue}yC(u,s)&&l(_n("name_match",c,e,"low",true,"Folder name is similar to workspace name."));}return o.sort((c,u)=>{let d=fh(u.confidence)-fh(c.confidence);return d!==0?d:gh(u.source)-gh(c.source)}),o.map((c,u)=>({...c,recommended:u===0}))}function _n(t,e,r,n,i,s){return {source:t,workspace_id:e.id,workspace_name:e.name,org_id:r.id,org_name:r.name,org_slug:r.slug,confidence:n,recommended:false,requires_confirmation:i,reason:s}}function fh(t){return {exact:4,high:3,medium:2,low:1}[t]}function gh(t){return {cwd_mapping:6,git_remote:5,hook_cache:4,companion_file:3,name_match:2,manual:1}[t]}function _C(t,e){let r=t;return r.git_remote_url&&ka(r.git_remote_url)===ka(e)?true:!r.git_owner||!r.git_repo?false:ka(e).endsWith(`/${r.git_owner}/${r.git_repo}`.toLocaleLowerCase("en-US"))}async function wh(t){try{let{stdout:e}=await hC("git",["config","--get","remote.origin.url"],{cwd:t,timeout:1e3});return e.trim()||null}catch{return null}}function ka(t){return t.trim().replace(/^git@([^:]+):/,"https://$1/").replace(/^https?:\/\//,"").replace(/\.git$/,"").toLocaleLowerCase("en-US")}async function wC(t,e){let r=new Set,n=join(A(e).home,"cache"),i;try{i=await readdir(n);}catch{return r}let s=resolve(t);return await Promise.all(i.map(async o=>{try{let a=await readFile(join(n,o,"hook-index.json"),"utf8"),l=JSON.parse(a);if(!l.workspace_id||!l.workspace_root)return;let c=resolve(l.workspace_root);(s===c||s.startsWith(`${c}/`))&&r.add(l.workspace_id);}catch{}})),r}function mh(t){return t.toLocaleLowerCase("en-US").replace(/[^a-z0-9]+/g," ").trim()}function yC(t,e){return !t||!e?false:t.includes(e)||e.includes(t)?true:kC(t,e)<=Math.max(2,Math.floor(Math.max(t.length,e.length)*.25))}function kC(t,e){let r=Array.from({length:e.length+1},(n,i)=>i);for(let n=1;n<=t.length;n+=1){let i=n,s=n-1;for(let o=1;o<=e.length;o+=1){let a=r[o]??0,l=t[n-1]===e[o-1]?0:1;r[o]=Math.min(a+1,i+1,s+l),i=r[o]??0,s=a;}r[0]=n;}return r[e.length]??0}F();Ee();async function ba(t,e){let r=await bC(t,e);if(!r)throw new Error("org_required");let{supabase:n}=await C(t),[i,s,o]=await Promise.all([n.from("organization_members").select("id, user_id, role, joined_at").eq("organization_id",r.id).order("joined_at",{ascending:true}),n.rpc("get_org_member_profiles",{p_org_id:r.id}),n.from("organization_invites").select("id, email, role, status, created_at, expires_at").eq("organization_id",r.id).eq("status","pending").order("created_at",{ascending:false})]);if(i.error)throw i.error;if(s.error)throw s.error;if(o.error)throw o.error;let a=new Map,l=s.data??[];for(let d of l)a.set(d.user_id,d);let c=(i.data??[]).map(d=>{let p=a.get(d.user_id);return {id:d.id,user_id:d.user_id,role:d.role,joined_at:d.joined_at,email:p?.email??null,full_name:yl(p?.full_name,"profile"),avatar_url:kl(p?.avatar_url),last_sign_in_at:p?.last_sign_in_at??null}}),u=(o.data??[]).map(d=>({id:d.id,email:d.email,role:d.role,status:d.status,created_at:d.created_at,expires_at:d.expires_at}));return {organization:{id:r.id,name:r.name,slug:r.slug,role:r.role},members:c,invites:u,open_target:{kind:"web",url:ee(r,t,"members"),label:"Open team in Pathrule Web",reason:"preferred"}}}async function bC(t,e){return e?(await we(t)).find(n=>n.id===e||n.slug===e)??null:j(t)}Ge();Gr();async function Li(t,e,r){let n=await kt("update.policy",e);if(n.key!=="update.policy")throw new Error("invalid_update_policy_state");let i=`${(e.PATHRULE_WEB_URL??"https://app.pathrule.io").replace(/\/$/,"")}/cli/versions.json`,s=e.PATHRULE_PROTOCOL_VERSION??hl;if(n.value==="manual")return {checked:false,policy:n.value,current_version:t,current_protocol_version:s,latest_version:null,min_supported_protocol_version:null,protocol_compatible:true,update_available:false,upgrade_command:null,reason:"manual_policy",url:i};try{let o=await r(i,{headers:{"user-agent":`pathrule-cli/${t}`}});if(!o.ok)throw new Error(`http_${o.status}`);let a=await o.json(),l=a.latest_version??a.latest??null,c=a.min_supported_protocol_version??null;return {checked:!0,policy:n.value,current_version:t,current_protocol_version:s,latest_version:l,min_supported_protocol_version:c,protocol_compatible:SC(s,c),update_available:l?l!==t:!1,upgrade_command:a.upgrade_command??vC(a.channels),url:i}}catch{return {checked:false,policy:n.value,current_version:t,current_protocol_version:s,latest_version:null,min_supported_protocol_version:null,protocol_compatible:true,update_available:false,upgrade_command:null,reason:"request_failed",url:i}}}async function kh(t,e,r){let n=await kt("update.policy",e);if(n.key!=="update.policy")throw new Error("invalid_update_policy_state");if(n.value==="manual")return null;let i=await Ce(e).catch(()=>null);if(!i)return null;let s=await ne(i.session.user.id,e);if(s.last_update_check_at){let l=new Date(s.last_update_check_at).getTime();if(Number.isFinite(l)&&Date.now()-l<1440*60*1e3)return null}await ie(i.session.user.id,{last_update_check_at:new Date().toISOString()},e);let o=await Li(t,e,r);if(!o.checked||!o.update_available)return null;let a=o.upgrade_command?` Run: ${o.upgrade_command}`:"";return `Pathrule CLI ${o.latest_version} is available.${a}`}function vC(t){return t?t.brew??t.npm??t.standalone??null:null}function SC(t,e){if(!e)return true;let r=yh(t),n=yh(e);return r&&n?CC(r,n)>=0:t===e}function yh(t){let e=t.match(/^v?(\d+)\.(\d+)\.(\d+)$/);return e?[Number(e[1]),Number(e[2]),Number(e[3])]:null}function CC(t,e){for(let r=0;r<3;r+=1){let n=(t[r]??0)-(e[r]??0);if(n!==0)return n}return 0}F();Ee();async function va(t){let{session:e,supabase:r}=await C(t.env),[n,i]=await Promise.all([j(t.env),M(t.env)]);if(!n)throw new Error("org_required");if(!i)throw new Error("workspace_required");let s=EC(n.plan),[o,a,l,c,u,d,p,h]=await Promise.all([RC(r,i.id),wn(r.from("nodes").select("id",{count:"exact",head:true}).eq("workspace_id",i.id)),wn(r.from("memories").select("id",{count:"exact",head:true}).eq("workspace_id",i.id)),wn(r.from("rules").select("id",{count:"exact",head:true}).eq("workspace_id",i.id)),wn(r.from("skills").select("id",{count:"exact",head:true}).eq("workspace_id",i.id)),wn(r.from("workspaces").select("id",{count:"exact",head:true}).eq("organization_id",n.id).is("archived_at",null)),xC(r,i.id),Pt(t.env,e.user.id,i.id,i.local_root_path)]);return {organization:{id:n.id,name:n.name,slug:n.slug,plan:s,role:n.role,subscription_status:n.subscription_status,trial_status:n.trial_status},workspace:i,local_status:{current_folder:t.cwd,attached_root:i.local_root_path,current_folder_attached:i.local_root_path===t.cwd,attached_elsewhere:i.local_root_path!==null&&i.local_root_path!==t.cwd},cloud_tree:{root_node_present:o,nodes:a,memories:l,rules:c,skills:u},capacity:{plan:s,workspaces:{used:d,limit:qe[s].workspaces},memories:{used:l,limit:qe[s].memories},rules:{used:c,limit:qe[s].rules}},active_clients:h.map(f=>TC(f)),recent_activity:p}}function EC(t){return Object.hasOwn(qe,t)?t:"free"}async function RC(t,e){let{data:r,error:n}=await t.from("nodes").select("id").eq("workspace_id",e).eq("relative_path","/").is("parent_id",null).maybeSingle();if(n)throw n;return !!r?.id}async function wn(t){let{count:e,error:r}=await t;if(r)throw new Error(r.message);return e??0}async function xC(t,e){let{data:r,error:n}=await t.from("activity_logs").select("created_at, domain, action, scope, node_path, task_summary, files_touched").eq("workspace_id",e).eq("status","active").order("created_at",{ascending:false}).limit(5);if(n)throw n;return (r??[]).map(i=>({created_at:String(i.created_at),domain:String(i.domain??"unknown"),action:String(i.action??"unknown"),scope:String(i.scope??"project"),node_path:String(i.node_path??"/"),task_summary:String(i.task_summary??""),files_touched_total:PC(i.files_touched)}))}function PC(t){if(!t||typeof t!="object")return 0;let e=t.total;return typeof e=="number"&&Number.isFinite(e)?e:0}function TC(t){let e=t.client;return {client:e,label:U[e]?.label??e,active:t.active,selected:t.selected,detected:t.markers.includes("workspace_marker_detected"),machine_installed:t.machineInstalled,machine_config_exists:t.machineConfigExists,machine_config_path:t.machineConfigPath}}var BC=createRequire(import.meta.url),Be=BC("../package.json"),Bi=promisify(execFile),X=class extends Error{constructor(r,n){super(n);this.code=r;this.name="CliContentUsageError";}code},FC=`${H.cli}
187
+ ${e.body}`.trim();if(AS(e.heading,r))return null;let n=[...r.matchAll(CS)].length,i=zp(r),s=[...new Set([...r.matchAll(ES)].map(a=>a[0]))].slice(0,8);return !(e.heading?Yp.test(e.heading):false)&&n===0&&i.length===0&&s.length===0?null:{path:t,heading:e.heading,kind:IS(e.heading??r),summary:NS(r),pathMentions:i,commandMentions:s,imperativeScore:n,excerpt:DS(r)}}function AS(t,e){let r=`${t??""} ${e.slice(0,200)}`.toLowerCase();return /\b(changelog|release notes|history)\b/.test(r)&&/\b\d{4}-\d{2}-\d{2}\b/.test(r)}function IS(t){let e=t.toLowerCase();return e.includes("security")?"security":e.includes("test")?"testing":e.includes("release")||e.includes("deploy")?"release":e.includes("architecture")?"architecture":e.includes("setup")||e.includes("development")||e.includes("contributing")?"workflow":"convention"}function OS(t){return t.filter(e=>e.kind==="architecture"||e.kind==="workflow"||e.pathMentions.length>0).slice(0,18).map(e=>{let r=_a(e.pathMentions,hr(e.path));return {title:Zp("Project note",e),bodyGuidance:`Write a concise memory summarizing ${e.summary}. Include the relevant paths and commands, but do not paste the source document verbatim.`,nodePath:r,confidence:eh(.55+e.pathMentions.length*.03+e.commandMentions.length*.02),evidence:[Qp(e)]}})}function $S(t){return t.filter(e=>e.imperativeScore>0||e.kind==="security"||e.kind==="testing").slice(0,12).map(e=>({title:Zp("Rule",e),bodyGuidance:`Write a rule from the documented requirement: ${e.summary}. Keep it imperative and scoped to the most specific path.`,nodePath:_a(e.pathMentions,Nt(e.kind==="security"?"/":hr(e.path))),confidence:eh(.62+e.imperativeScore*.04),evidence:[Qp(e)]}))}function Zp(t,e){let r=e.heading||e.summary;return `${t}: ${r.replace(/[`*_#]/g,"").slice(0,80)}`}function Qp(t){return {kind:"doc",path:t.path,heading:t.heading,excerpt:t.excerpt}}function Vp(t){return t.imperativeScore*3+t.pathMentions.length*2+t.commandMentions.length+(t.heading&&Yp.test(t.heading)?8:0)}function NS(t){return t.replace(/\s+/g," ").replace(/[`*_#>-]/g,"").trim().slice(0,220)}function DS(t){return t.replace(/\s+/g," ").trim().slice(0,280)}function eh(t){return Math.max(0,Math.min(1,Number(t.toFixed(2))))}var jS=/\b(fix|bug|regression|hotfix|breaking|break|migration|schema|refactor|rewrite|cleanup)\b/i,rh=/\b(breaking|break|migration|schema)\b/i,MS=/\b(fix|bug|regression|hotfix)\b/i,LS=/\b(refactor|rewrite|cleanup)\b/i;function nh(t){let e=US(t),r=new Map;for(let i of e){let s=rh.test(i.subject)?"breaking":MS.test(i.subject)?"fix":LS.test(i.subject)?"refactor":null;if(!s)continue;let o=new Set;for(let a of i.files){o.add(Nt(a)),o.add(hr(a));let l=WS(a);l&&o.add(l);}for(let a of o){let l=r.get(a)??{path:a,fix:0,breaking:0,refactor:0,commits:new Map};l.commits.set(i.hash,i),s==="fix"&&(l.fix+=1),s==="breaking"&&(l.breaking+=1),s==="refactor"&&(l.refactor+=1),r.set(a,l);}}return {findings:[...r.values()].filter(i=>i.commits.size>=3||i.breaking>=1).sort((i,s)=>th(s)-th(i)).slice(0,15).map(BS),commitsScanned:e.length}}function US(t){let e=[];for(let r of t.split("")){let n=r.split(/\r?\n/).map(c=>c.trim()).filter(Boolean),i=n[0];if(!i)continue;let[s,o,a]=i.split("");if(!s||!o||!a||!jS.test(a)||/^merge\b/i.test(a))continue;let l=n.slice(1).filter(c=>!c.includes(" => "));l.length<1||l.length>30&&!rh.test(a)||e.push({hash:s,date:o,subject:a,files:l});}return e}function WS(t){let e=t.split("/");return (e[0]==="packages"||e[0]==="apps")&&e[1]?`/${e[0]}/${e[1]}`:e[0]==="supabase"&&e[1]?`/supabase/${e[1]}`:null}function th(t){return t.fix*3+t.breaking*5+t.refactor*2+t.commits.size}function BS(t){let e=[...t.commits.values()].sort((i,s)=>s.date.localeCompare(i.date)),r=e[0],n=e.slice(0,4).map(i=>({kind:"commit",commit:i.hash.slice(0,12),path:t.path,excerpt:`${i.date} ${i.subject}`}));return {path:t.path,summary:`${t.path} has ${t.fix} fix, ${t.breaking} breaking/schema, and ${t.refactor} refactor commits in recent history.`,fixCount:t.fix,breakingCount:t.breaking,refactorCount:t.refactor,uniqueCommits:t.commits.size,latestDate:r?.date,evidence:n}}var oh=promisify(execFile);async function ah(t){let e=t.now??new Date;if(!t.force){let r=await Hp({workspaceId:t.workspaceId,localRootPath:t.localRootPath,env:t.env,now:e});if(r.ok&&r.brief)return {ok:true,brief:r.brief,cachePath:r.cachePath,reusedCache:true}}try{let r=await QS(KS(t,e),t.timeoutMs??3e4),n=await ma({workspaceId:t.workspaceId,localRootPath:t.localRootPath,brief:r,env:t.env});return {ok:!0,brief:r,cachePath:n.cachePath,reusedCache:!1}}catch(r){let n=ZS(t,e,r instanceof Error?r.message:String(r)),i=await ma({workspaceId:t.workspaceId,localRootPath:t.localRootPath,brief:n,env:t.env}).catch(()=>({cachePath:null}));return {ok:false,brief:n,cachePath:i.cachePath,reusedCache:false,error:n.warnings[0]}}}async function KS(t,e){let r=[],[n,i,s,o,a]=await Promise.all([VS(t.supabase,t.workspaceId),Xp(t.localRootPath),GS(t.localRootPath,r),XS(t.localRootPath,r),YS(t.localRootPath,r)]);r.push(...i.warnings);let l=nh(s),c=a?hs(a):[],u=ps(o).map(w=>({title:w.title,summary:w.content})),d=u.map(w=>({title:w.title,bodyGuidance:`Write a short memory noting that ${w.summary.toLowerCase()}`,nodePath:"/",confidence:.72,evidence:[{kind:"stack",excerpt:w.summary}]})),p=l.findings.map(w=>({title:`Risk hotspot: ${w.path}`,bodyGuidance:`Write a memory explaining the risk pattern for ${w.path}: ${w.summary} Include the kinds of changes that should be reviewed together.`,nodePath:w.path,confidence:Math.min(.95,.6+w.uniqueCommits*.04+w.breakingCount*.08),evidence:w.evidence})),h=ih([...i.candidateMemories,...p,...d]),f=ih(i.candidateRules);h=sh(h,n.titles).slice(0,15),f=sh(f,n.titles).slice(0,8);let m=n.memoryCount+n.ruleCount>=8;m&&(h=[],f=[],r.push("Workspace already has meaningful setup content; Bootstrap v2 will avoid duplicate starter guidance."));let _=Jp([...f.map(w=>w.nodePath),...h.map(w=>w.nodePath),...i.findings.flatMap(w=>[w.path,...w.pathMentions]),...l.findings.map(w=>w.path)],20),b=m?"Bootstrap v2 found existing Pathrule setup content. Use pathrule_get_context for task-specific context instead of writing duplicate starter memories or rules.":`Bootstrap v2 prepared ${h.length} memory candidates and ${f.length} rule candidates from ${i.docsFilesScanned} docs files and ${l.commitsScanned} risky commits.`;return {version:2,workspaceId:t.workspaceId,localRootPath:t.localRootPath,generatedAt:e.toISOString(),summary:b,stackSignals:u,documentationFindings:i.findings,commitWisdom:l.findings,candidateMemories:h,candidateRules:f,candidateSkills:[],suggestedOrder:_,coverage:{docsFilesScanned:i.docsFilesScanned,commitsScanned:l.commitsScanned,filesMentionedByDocs:i.filesMentionedByDocs,coChangePairsAvailable:c.length},warnings:r,alreadyBootstrapped:m}}async function VS(t,e){if(!t)return {memoryCount:0,ruleCount:0,skillCount:0,titles:new Set};let[r,n,i]=await Promise.all([t.from("memories").select("title",{count:"exact"}).eq("workspace_id",e).limit(200),t.from("rules").select("name",{count:"exact"}).eq("workspace_id",e).limit(200),t.from("skills").select("name",{count:"exact"}).eq("workspace_id",e).limit(50)]),s=new Set;for(let o of r.data??[])o.title&&s.add(mn(o.title));for(let o of n.data??[])o.name&&s.add(mn(o.name));for(let o of i.data??[])o.name&&s.add(mn(o.name));return {memoryCount:r.count??s.size,ruleCount:n.count??0,skillCount:i.count??0,titles:s}}async function GS(t,e){try{let{stdout:r}=await oh("git",["log","--date=short","--format=%x1e%H%x1f%ad%x1f%s","--name-only","-n","5000"],{cwd:t,maxBuffer:52428800,timeout:2e4});return r}catch{return e.push("Git commit wisdom skipped; repository history was unavailable."),""}}async function YS(t,e){try{let{stdout:r}=await oh("git",["log","--name-only","--pretty=format:---","-n","10000"],{cwd:t,maxBuffer:52428800,timeout:2e4});return r}catch{return e.push("Git co-change scan skipped; repository history was unavailable."),""}}async function XS(t,e){let r=[];async function n(i,s){if(s>4||r.length>5e3)return;let o=await readdir(i,{withFileTypes:true}).catch(()=>[]);for(let a of o){if(a.name===".git"||a.name==="node_modules"||a.name==="dist")continue;let l=join(i,a.name);a.isDirectory()?await n(l,s+1):a.isFile()&&r.push(relative(t,l).replace(/\\/g,"/"));}}return await n(t,0).catch(()=>e.push("Stack detection skipped; file tree was unavailable.")),r}function ih(t){let e=new Map;for(let r of t){let n=`${r.nodePath}:${mn(r.title)}`,i=e.get(n);(!i||r.confidence>i.confidence)&&e.set(n,r);}return [...e.values()].sort((r,n)=>n.confidence-r.confidence)}function sh(t,e){return t.filter(r=>!e.has(mn(r.title)))}function mn(t){return t.toLocaleLowerCase("en-US").replace(/[^a-z0-9]+/g," ").trim()}function ZS(t,e,r){return {version:2,workspaceId:t.workspaceId,localRootPath:t.localRootPath,generatedAt:e.toISOString(),summary:"Bootstrap v2 could not complete the local scan. Use the fallback setup prompt.",stackSignals:[],documentationFindings:[],commitWisdom:[],candidateMemories:[],candidateRules:[],candidateSkills:[],suggestedOrder:[],coverage:{docsFilesScanned:0,commitsScanned:0,filesMentionedByDocs:0,coChangePairsAvailable:0},warnings:[r]}}function QS(t,e){return new Promise((r,n)=>{let i=setTimeout(()=>n(new Error("Bootstrap v2 scan timed out.")),e);t.then(s=>{clearTimeout(i),r(s);},s=>{clearTimeout(i),n(s);});})}F();K();li();F();async function uh(t,e,r=fetch){if(!e.gitRemoteUrl)return {status:"skipped",error:"missing_git_remote"};try{let{session:n,supabase:i}=await C(t),{data:s,error:o}=await i.from("beta_platform_invites").select("id").eq("claimed_user_id",n.user.id).eq("status","claimed").order("claimed_at",{ascending:!1}).limit(1);if(o)return {status:"skipped",error:"invite_lookup_unavailable"};let a=(s??[])[0]??null;if(!a)return {status:"skipped",error:"no_claimed_beta_invite"};let l=pe(t),c=await aC(t),u=await r(`${l.supabaseUrl}/functions/v1/process-beta-activation`,{method:"POST",headers:{"content-type":"application/json",apikey:l.supabaseAnonKey,Authorization:`Bearer ${n.access_token}`},body:JSON.stringify({invite_id:a.id,workspace_id:e.workspaceId,git_remote_url:e.gitRemoteUrl,machine_id:c,runtime_source:e.runtimeSource})}),d=await u.json().catch(()=>null);return !u.ok||!d?.status?{status:"skipped",error:"activation_unavailable"}:{status:d.status,credit_cents:ch(d.credit_cents),founder_bonus_cents:ch(d.founder_bonus_cents)}}catch{return {status:"skipped",error:"activation_unavailable"}}}async function aC(t){let e=join(A(t).home,"machine-install.json");try{let n=JSON.parse(await readFile(e,"utf8"));if(typeof n.machine_id=="string"&&n.machine_id.length>=16)return n.machine_id}catch{}let r=`cli_${randomUUID()}`;return await lC(e,{schema_version:1,machine_id:r}),r}async function lC(t,e){let r=dirname(t);await mkdir(r,{recursive:true,mode:j}),await chmod(r,j).catch(()=>{});let n=`${t}.tmp`;await writeFile(n,JSON.stringify(e,null,2),{encoding:"utf8",mode:O}),await chmod(n,O).catch(()=>{}),await rename(n,t);}function ch(t){return typeof t=="number"&&Number.isFinite(t)?t:void 0}Ee();var hC=promisify(execFile);async function Mi(t,e){let r=await D(e);if(!r)return {cwd:t,organization:null,candidates:[],recommended_action:"select_org"};let[n,i,s]=await Promise.all([Re(e),wh(t),wC(t,e)]),o=mC(t,r,n,i,s);return {cwd:t,organization:r,candidates:o,recommended_action:o.length===0?"create_workspace":o[0]?.confidence==="exact"||o[0]?.confidence==="high"?"attach_existing":"choose_workspace"}}async function fr(t,e,r,n={yes:false}){let i=gC(t);if(!i.shouldApply)return {plan:await Mi(e,r),applied:false,org_selected:null,workspace_action:"none",workspace:null,install:null,sync:null,beta_activation:null,bootstrap_v2:null};if(i.bootstrapRerun){let f=await M(r);if(!f?.id)throw new Error("workspace_required");let m=await hh(f.id,e,r,true);return {plan:await Mi(e,r),applied:true,org_selected:null,workspace_action:"none",workspace:f,install:null,sync:null,beta_activation:null,bootstrap_v2:m}}if(!n.yes)throw new Error("setup_requires_yes");let s=null;if(i.org){let{useCliOrg:f}=await Promise.resolve().then(()=>(Ee(),Du));s=(await f(i.org,r)).id;}let o=await Mi(e,r),a="none",l=null;if(i.createWorkspace){let f=await ae("create_workspace",r);if(!f.allowed)throw new Error(f.blocking_reason??"preflight_blocked");l=await bt(i.workspaceName??basename(e),e,r),a="created";}else i.workspaceSelector?(l=await xe(i.workspaceSelector,e,r),a="attached"):o.recommended_action==="attach_existing"&&o.candidates[0]?(l=await xe(o.candidates[0].workspace_id,e,r),a="attached"):i.selectCurrentWorkspace&&(l=await Zr(i.selectCurrentWorkspace,r),a="selected");o=await Mi(e,r);let c=i.target?await Ze(i.target,r):null,u=a==="attached"||a==="created"?await Le(r,e):null,d=fC(l),p=u?.ok&&d&&(a==="attached"||a==="created")?await hh(d,e,r,false):null,h=u?.ok&&(a==="attached"||a==="created")?await uh(r,{workspaceId:d,gitRemoteUrl:await wh(e),runtimeSource:"cli"}):null;return {plan:o,applied:true,org_selected:s,workspace_action:a,workspace:l,install:c,sync:u,beta_activation:h,bootstrap_v2:p}}async function hh(t,e,r,n){let{supabase:i}=await C(r),s=await ah({workspaceId:t,localRootPath:e,supabase:i,env:r,force:n});return {ok:s.ok,reused_cache:s.reusedCache,cache_path:s.cachePath,candidate_counts:{memories:s.brief.candidateMemories.length,rules:s.brief.candidateRules.length,skills:s.brief.candidateSkills.length},coverage:s.brief.coverage,summary:s.brief.summary,warnings:s.brief.warnings}}function fC(t){if(!t||typeof t!="object")return null;let e=t.id;if(typeof e=="string")return e;let r=t.workspace?.id;return typeof r=="string"?r:null}function gC(t){let e={org:null,workspaceSelector:null,workspaceName:null,createWorkspace:false,selectCurrentWorkspace:null,target:null,bootstrapRerun:false},r=false,n=false;for(let i=0;i<t.length;i+=1){let s=t[i],o=()=>{let a=t[i+1];if(!a||a.startsWith("--"))throw new Error(`missing_value:${s}`);return i+=1,a};if(s==="bootstrap"){if(r)throw new Error("unknown_setup_option:bootstrap");r=true;}else if(s==="--rerun"&&r)n=true;else if(s==="--org")e.org=o();else if(s==="--workspace"||s==="--workspace-id")e.workspaceSelector=o();else if(s==="--workspace-name")e.workspaceName=o();else if(s==="--create-workspace")e.createWorkspace=true;else if(s==="--select-workspace")e.selectCurrentWorkspace=o();else if(s==="--target")e.target=o();else throw new Error(`unknown_setup_option:${s}`)}if(r&&!n)throw new Error("missing_value:--rerun");return e.bootstrapRerun=r&&n,{...e,shouldApply:e.org!==null||e.workspaceSelector!==null||e.workspaceName!==null||e.createWorkspace||e.selectCurrentWorkspace!==null||e.target!==null||e.bootstrapRerun}}function mC(t,e,r,n,i){let s=mh(basename(t)),o=[],a=new Set,l=c=>{a.has(c.workspace_id)||(a.add(c.workspace_id),o.push(c));};for(let c of r){if(c.local_root_path===t){l(_n("cwd_mapping",c,e,"exact",false,"Exact local path mapping."));continue}if(n&&_C(c,n)){l(_n("git_remote",c,e,"high",true,"Git remote matches workspace metadata."));continue}if(i.has(c.id)){l(_n("hook_cache",c,e,"high",true,"Existing hook cache points at this folder."));continue}let u=mh(c.name);if(u===s){l(_n("name_match",c,e,"medium",true,"Folder name matches workspace name."));continue}yC(u,s)&&l(_n("name_match",c,e,"low",true,"Folder name is similar to workspace name."));}return o.sort((c,u)=>{let d=fh(u.confidence)-fh(c.confidence);return d!==0?d:gh(u.source)-gh(c.source)}),o.map((c,u)=>({...c,recommended:u===0}))}function _n(t,e,r,n,i,s){return {source:t,workspace_id:e.id,workspace_name:e.name,org_id:r.id,org_name:r.name,org_slug:r.slug,confidence:n,recommended:false,requires_confirmation:i,reason:s}}function fh(t){return {exact:4,high:3,medium:2,low:1}[t]}function gh(t){return {cwd_mapping:6,git_remote:5,hook_cache:4,companion_file:3,name_match:2,manual:1}[t]}function _C(t,e){let r=t;return r.git_remote_url&&ka(r.git_remote_url)===ka(e)?true:!r.git_owner||!r.git_repo?false:ka(e).endsWith(`/${r.git_owner}/${r.git_repo}`.toLocaleLowerCase("en-US"))}async function wh(t){try{let{stdout:e}=await hC("git",["config","--get","remote.origin.url"],{cwd:t,timeout:1e3});return e.trim()||null}catch{return null}}function ka(t){return t.trim().replace(/^git@([^:]+):/,"https://$1/").replace(/^https?:\/\//,"").replace(/\.git$/,"").toLocaleLowerCase("en-US")}async function wC(t,e){let r=new Set,n=join(A(e).home,"cache"),i;try{i=await readdir(n);}catch{return r}let s=resolve(t);return await Promise.all(i.map(async o=>{try{let a=await readFile(join(n,o,"hook-index.json"),"utf8"),l=JSON.parse(a);if(!l.workspace_id||!l.workspace_root)return;let c=resolve(l.workspace_root);(s===c||s.startsWith(`${c}/`))&&r.add(l.workspace_id);}catch{}})),r}function mh(t){return t.toLocaleLowerCase("en-US").replace(/[^a-z0-9]+/g," ").trim()}function yC(t,e){return !t||!e?false:t.includes(e)||e.includes(t)?true:kC(t,e)<=Math.max(2,Math.floor(Math.max(t.length,e.length)*.25))}function kC(t,e){let r=Array.from({length:e.length+1},(n,i)=>i);for(let n=1;n<=t.length;n+=1){let i=n,s=n-1;for(let o=1;o<=e.length;o+=1){let a=r[o]??0,l=t[n-1]===e[o-1]?0:1;r[o]=Math.min(a+1,i+1,s+l),i=r[o]??0,s=a;}r[0]=n;}return r[e.length]??0}F();Ee();async function ba(t,e){let r=await bC(t,e);if(!r)throw new Error("org_required");let{supabase:n}=await C(t),[i,s,o]=await Promise.all([n.from("organization_members").select("id, user_id, role, joined_at").eq("organization_id",r.id).order("joined_at",{ascending:true}),n.rpc("get_org_member_profiles",{p_org_id:r.id}),n.from("organization_invites").select("id, email, role, status, created_at, expires_at").eq("organization_id",r.id).eq("status","pending").order("created_at",{ascending:false})]);if(i.error)throw i.error;if(s.error)throw s.error;if(o.error)throw o.error;let a=new Map,l=s.data??[];for(let d of l)a.set(d.user_id,d);let c=(i.data??[]).map(d=>{let p=a.get(d.user_id);return {id:d.id,user_id:d.user_id,role:d.role,joined_at:d.joined_at,email:p?.email??null,full_name:yl(p?.full_name,"profile"),avatar_url:kl(p?.avatar_url),last_sign_in_at:p?.last_sign_in_at??null}}),u=(o.data??[]).map(d=>({id:d.id,email:d.email,role:d.role,status:d.status,created_at:d.created_at,expires_at:d.expires_at}));return {organization:{id:r.id,name:r.name,slug:r.slug,role:r.role},members:c,invites:u,open_target:{kind:"web",url:ee(r,t,"members"),label:"Open team in Pathrule Web",reason:"preferred"}}}async function bC(t,e){return e?(await we(t)).find(n=>n.id===e||n.slug===e)??null:D(t)}Ge();Gr();async function Li(t,e,r){let n=await kt("update.policy",e);if(n.key!=="update.policy")throw new Error("invalid_update_policy_state");let i=`${(e.PATHRULE_WEB_URL??"https://app.pathrule.io").replace(/\/$/,"")}/cli/versions.json`,s=e.PATHRULE_PROTOCOL_VERSION??hl;if(n.value==="manual")return {checked:false,policy:n.value,current_version:t,current_protocol_version:s,latest_version:null,min_supported_protocol_version:null,protocol_compatible:true,update_available:false,upgrade_command:null,reason:"manual_policy",url:i};try{let o=await r(i,{headers:{"user-agent":`pathrule-cli/${t}`}});if(!o.ok)throw new Error(`http_${o.status}`);let a=await o.json(),l=a.latest_version??a.latest??null,c=a.min_supported_protocol_version??null;return {checked:!0,policy:n.value,current_version:t,current_protocol_version:s,latest_version:l,min_supported_protocol_version:c,protocol_compatible:SC(s,c),update_available:l?l!==t:!1,upgrade_command:a.upgrade_command??vC(a.channels),url:i}}catch{return {checked:false,policy:n.value,current_version:t,current_protocol_version:s,latest_version:null,min_supported_protocol_version:null,protocol_compatible:true,update_available:false,upgrade_command:null,reason:"request_failed",url:i}}}async function kh(t,e,r){let n=await kt("update.policy",e);if(n.key!=="update.policy")throw new Error("invalid_update_policy_state");if(n.value==="manual")return null;let i=await Ce(e).catch(()=>null);if(!i)return null;let s=await ne(i.session.user.id,e);if(s.last_update_check_at){let l=new Date(s.last_update_check_at).getTime();if(Number.isFinite(l)&&Date.now()-l<1440*60*1e3)return null}await ie(i.session.user.id,{last_update_check_at:new Date().toISOString()},e);let o=await Li(t,e,r);if(!o.checked||!o.update_available)return null;let a=o.upgrade_command?` Run: ${o.upgrade_command}`:"";return `Pathrule CLI ${o.latest_version} is available.${a}`}function vC(t){return t?t.brew??t.npm??t.standalone??null:null}function SC(t,e){if(!e)return true;let r=yh(t),n=yh(e);return r&&n?CC(r,n)>=0:t===e}function yh(t){let e=t.match(/^v?(\d+)\.(\d+)\.(\d+)$/);return e?[Number(e[1]),Number(e[2]),Number(e[3])]:null}function CC(t,e){for(let r=0;r<3;r+=1){let n=(t[r]??0)-(e[r]??0);if(n!==0)return n}return 0}F();Ee();async function va(t){let{session:e,supabase:r}=await C(t.env),[n,i]=await Promise.all([D(t.env),M(t.env)]);if(!n)throw new Error("org_required");if(!i)throw new Error("workspace_required");let s=EC(n.plan),[o,a,l,c,u,d,p,h]=await Promise.all([RC(r,i.id),wn(r.from("nodes").select("id",{count:"exact",head:true}).eq("workspace_id",i.id)),wn(r.from("memories").select("id",{count:"exact",head:true}).eq("workspace_id",i.id)),wn(r.from("rules").select("id",{count:"exact",head:true}).eq("workspace_id",i.id)),wn(r.from("skills").select("id",{count:"exact",head:true}).eq("workspace_id",i.id)),wn(r.from("workspaces").select("id",{count:"exact",head:true}).eq("organization_id",n.id).is("archived_at",null)),xC(r,i.id),Pt(t.env,e.user.id,i.id,i.local_root_path)]);return {organization:{id:n.id,name:n.name,slug:n.slug,plan:s,role:n.role,subscription_status:n.subscription_status,trial_status:n.trial_status},workspace:i,local_status:{current_folder:t.cwd,attached_root:i.local_root_path,current_folder_attached:i.local_root_path===t.cwd,attached_elsewhere:i.local_root_path!==null&&i.local_root_path!==t.cwd},cloud_tree:{root_node_present:o,nodes:a,memories:l,rules:c,skills:u},capacity:{plan:s,workspaces:{used:d,limit:qe[s].workspaces},memories:{used:l,limit:qe[s].memories},rules:{used:c,limit:qe[s].rules}},active_clients:h.map(f=>TC(f)),recent_activity:p}}function EC(t){return Object.hasOwn(qe,t)?t:"free"}async function RC(t,e){let{data:r,error:n}=await t.from("nodes").select("id").eq("workspace_id",e).eq("relative_path","/").is("parent_id",null).maybeSingle();if(n)throw n;return !!r?.id}async function wn(t){let{count:e,error:r}=await t;if(r)throw new Error(r.message);return e??0}async function xC(t,e){let{data:r,error:n}=await t.from("activity_logs").select("created_at, domain, action, scope, node_path, task_summary, files_touched").eq("workspace_id",e).eq("status","active").order("created_at",{ascending:false}).limit(5);if(n)throw n;return (r??[]).map(i=>({created_at:String(i.created_at),domain:String(i.domain??"unknown"),action:String(i.action??"unknown"),scope:String(i.scope??"project"),node_path:String(i.node_path??"/"),task_summary:String(i.task_summary??""),files_touched_total:PC(i.files_touched)}))}function PC(t){if(!t||typeof t!="object")return 0;let e=t.total;return typeof e=="number"&&Number.isFinite(e)?e:0}function TC(t){let e=t.client;return {client:e,label:U[e]?.label??e,active:t.active,selected:t.selected,detected:t.markers.includes("workspace_marker_detected"),machine_installed:t.machineInstalled,machine_config_exists:t.machineConfigExists,machine_config_path:t.machineConfigPath}}var BC=createRequire(import.meta.url),Be=BC("../package.json"),Bi=promisify(execFile),X=class extends Error{constructor(r,n){super(n);this.code=r;this.name="CliContentUsageError";}code},FC=`${H.cli}
188
188
 
189
189
  Usage:
190
190
  pathrule <command> [options]
@@ -309,8 +309,8 @@ Useful commands:
309
309
  pathrule bridge pair
310
310
  `}function Ih(t){return t?HC(t)?{ok:true,text:qC(t),topic:t}:{ok:false,message:`Unknown help topic "${t}". Try: ${Ta.join(", ")}.`}:{ok:true,text:FC,topic:null}}async function Oh(t,e){let r=Date.now(),n=bu(t,e.env),i={json:n.flags.json,color:n.flags.color,interactive:n.flags.interactive,noOpen:n.flags.noOpen},s=n.flags.version?"version":n.flags.help?"help":n.command;if(i.json){let a=await zC(s,e,n.positional.slice(1),n.flags);return e.stdout.write(Np(a.envelope)),await so(e.env,{command:s,exitCode:a.exitCode,appVersion:Be.version,durationMs:Date.now()-r}),a.exitCode}let o;switch(s){case "help":{let a=Ih(n.positional[1]);if(!a.ok){e.stderr.write(`${g("error",i)} ${a.message}
311
311
  `),o=64;break}e.stdout.write(a.text),o=0;break}case "version":e.stdout.write(`${Be.version}
312
- `),o=0;break;case "start":o=await H0(e,i);break;case "login":o=await Gh(e,i,n.flags.browserCallback);break;case "org":o=await bE(n.positional[1]??"list",n.positional.slice(2),e,i);break;case "workspace":o=await f0(n.positional[1]??"list",n.positional.slice(2),e,i);break;case "init":o=await g0(n.positional[1],e,i);break;case "setup":o=await m0(e,i,n.positional.slice(1),n.flags.yes);break;case "attach":o=await N0(n.positional[1],e,i);break;case "detach":o=await j0(n.positional[1],e,i);break;case "preflight":o=await D0(n.positional[1],e,i);break;case "install":o=await M0(n.positional[1],e,i);break;case "uninstall":o=await L0(n.positional[1],e,i);break;case "sync":o=await U0(n.positional.slice(1),e,i);break;case "config":o=await W0(n.positional[1],n.positional[2],n.positional[3],e,i);break;case "update":o=await B0(e,i);break;case "daemon":o=await q0(n.positional.slice(1),e,i);break;case "bridge":o=await J0(n.positional[1]??"pair",e,i);break;case "open":o=await Dh(n.positional.slice(1),e,i);break;case "search":o=await cE(n.positional.slice(1),e,i);break;case "memory":case "rule":case "skill":o=await lE(s,n.positional.slice(1),e,i);break;case "refresh":o=await uE(n.positional.slice(1),e,i);break;case "repair":o=await dE(e,i);break;case "cache":o=await pE(n.positional.slice(1),e,i,n.flags.yes);break;case "billing":case "team":case "invite":case "upgrade":case "reactivate":o=s==="invite"?await Q0(n.positional.slice(1),e,i):s==="team"?await eE(n.positional.slice(1),e,i):await Z0(s,n.positional.slice(1),e,i);break;case "status":o=await G0(e,i);break;case "doctor":o=await V0(n.positional.slice(1),e,i);break;case "whoami":o=await X0(e,i);break;case "logout":o=await IE(e,i);break;default:e.stderr.write(`${g("error",i)} Unknown command "${s}". Run pathrule help.
313
- `),o=64;}return s!=="update"&&s!=="login"&&s!=="logout"&&await F0(e,i),await so(e.env,{command:s,exitCode:o,appVersion:Be.version,durationMs:Date.now()-r}),o}async function zC(t,e,r,n={yes:false}){if(t==="version")return {exitCode:0,envelope:k({command:t,cwd:e.cwd,ok:true,data:{version:Be.version}})};if(t==="help"){let i=Ih(r[0]);return i.ok?{exitCode:0,envelope:k({command:t,cwd:e.cwd,ok:true,data:{topic:i.topic,topics:[...Ta],text:i.text,commands:["help","version","start","login","status","doctor","whoami","logout","org","workspace","init","setup","attach","detach","preflight","install","uninstall","sync","config","update","daemon","bridge","open","search","memory","rule","skill","refresh","repair","cache","billing","team","invite","upgrade","reactivate"]}})}:{exitCode:64,envelope:k({command:t,cwd:e.cwd,ok:false,error:{code:"invalid_help_topic",message:i.message}})}}if(t==="login")try{let i=await to({env:e.env,fetch:e.fetch??fetch,sleep:e.sleep??Yh});return {exitCode:0,envelope:k({command:t,cwd:e.cwd,ok:!0,data:{user_id:i.session.user.id,email:i.session.user.email??null,expires_at:i.session.expires_at}})}}catch(i){let s=i instanceof De?i.code:"login_failed";return {exitCode:1,envelope:k({command:t,cwd:e.cwd,ok:false,error:{code:s,message:i instanceof Error?i.message:String(i)}})}}if(t==="start")return u0(e);if(t==="daemon")return c0(e,r);if(t==="bridge")return d0(e,r[0]??"pair");if(t==="open")return Mh(e,r);if(t==="search")return fE(e,r);if(t==="memory"||t==="rule"||t==="skill")return hE(t,e,r);if(t==="refresh")return gE(e,r);if(t==="repair")return mE(e);if(t==="cache")return _E(e,r,n.yes);if(t==="invite")return rE(e,r);if(t==="team")return nE(e,r);if(t==="billing"||t==="upgrade"||t==="reactivate")return tE(t,e,r);if(t==="whoami"){let i=await Ce(e.env);return i?{exitCode:0,envelope:k({command:t,cwd:e.cwd,ok:true,data:{user_id:i.session.user.id,email:i.session.user.email??null,expires_at:i.session.expires_at,...await GC(e.env)}})}:{exitCode:1,envelope:k({command:t,cwd:e.cwd,ok:false,error:{code:"not_authenticated",message:"Pathrule CLI is not signed in.",remediation:[{label:"Sign in",command:"pathrule login"}]}})}}if(t==="logout"){let i=await no(e.env);return {exitCode:0,envelope:k({command:t,cwd:e.cwd,ok:true,data:i})}}return t==="org"?p0(e,r[0]??"list",r.slice(1)):t==="workspace"?ZC(e,r[0]??"list",r.slice(1)):t==="init"?QC(e,r[0]):t==="setup"?e0(e,r,n.yes):t==="attach"?t0(e,r[0]):t==="detach"?r0(e,r[0]):t==="preflight"?n0(e,r[0]):t==="install"?i0(e,r[0]):t==="uninstall"?s0(e,r[0]):t==="sync"?o0(e,r):t==="config"?a0(e,r[0],r[1],r[2]):t==="update"?l0(e):t==="status"?XC(e):t==="doctor"?JC(e,r):t==="__scaffold"?{exitCode:0,envelope:k({command:t,cwd:e.cwd,ok:true,data:{status:"not_implemented",phase:"m31a_cli_foundation"},next_steps:VC(t)})}:{exitCode:64,envelope:k({command:t,cwd:e.cwd,ok:false,error:{code:"unknown_command",message:`Unknown command "${t}".`,remediation:[{label:"Show help",command:"pathrule help"}]}})}}async function JC(t,e){try{if(e.includes("--bundle")){let n=await Uo(t.env,t.cwd);return {exitCode:n.ok?0:1,envelope:k({command:"doctor --bundle",cwd:t.cwd,ok:n.ok,data:{path:n.path,report:n.report}})}}let r=await Me(t.env,t.cwd);return await KC(t.env,r.managed_files),{exitCode:r.ok?0:1,envelope:k({command:"doctor",cwd:t.cwd,ok:r.ok,data:r})}}catch(r){return {exitCode:1,envelope:k({command:"doctor",cwd:t.cwd,ok:false,error:{code:V(r,"doctor_failed"),message:r instanceof Error?r.message:String(r)}})}}}async function KC(t,e){e.some(r=>r.status==="other_owner"||r.status==="newer_version")&&(await Xr(t,{eventName:"managed_file_owner_conflict",result:"blocked",appVersion:Be.version,featureTag:"managed_files",blockingReason:"managed_file_owner_conflict"}).catch(()=>{}),await Xr(t,{eventName:"dead_end_seen",result:"blocked",appVersion:Be.version,featureTag:"managed_files",blockingReason:"managed_file_owner_conflict"}).catch(()=>{}));}function VC(t){if(t==="status"||t==="doctor"||t==="whoami")return [{label:"Continue M31a implementation",command:"pathrule login"}]}async function GC(t){try{let[e,r,n]=await Promise.all([we(t),j(t),M(t)]);return {organizations:e,current_org:r,current_workspace:n}}catch(e){return {context_error:e instanceof Error?e.message:String(e)}}}async function YC(t){let e=await M(t);if(!e)throw new Error("workspace_required");return e}async function XC(t){try{let e=await $h(t);return {exitCode:e.authenticated?0:1,envelope:k({command:"status",cwd:t.cwd,ok:e.authenticated,data:e,error:e.authenticated?void 0:{code:"not_authenticated",message:"Pathrule CLI is not signed in.",remediation:[{label:"Sign in",command:"pathrule login"}]}})}}catch(e){return {exitCode:1,envelope:k({command:"status",cwd:t.cwd,ok:false,error:{code:V(e,"status_failed"),message:e instanceof Error?e.message:String(e)}})}}}async function ZC(t,e,r){try{if(e==="inspect"){let i=await va(t);return {exitCode:0,envelope:k({command:"workspace inspect",cwd:t.cwd,ok:!0,data:i})}}if(e==="open"){let i=await gr(t);if(!i)throw new Error("workspace_required");let s=await qi(i.id,t.env,{preferDesktopApp:r.includes("--desktop-app"),forceWeb:r.includes("--web")});return {exitCode:0,envelope:k({command:"workspace open",cwd:t.cwd,ok:!0,data:s})}}if(e==="create"){let i=await ae("create_workspace",t.env);if(!i.allowed){let s=ar(i);return {exitCode:1,envelope:k({command:"workspace create",cwd:t.cwd,ok:!1,data:{preflight:i},error:{code:i.blocking_reason??"preflight_blocked",message:s.summary},next_steps:Ki(s)})}}}let n=e==="current"?await YC(t.env):e==="use"?await Zr(r[0]??"",t.env):e==="create"?await bt(r[0]??"",t.cwd,t.env):e==="attach"?await xe(r[0],t.cwd,t.env):e==="detach"?await Qr(r[0],t.env):await Re(t.env);return {exitCode:0,envelope:k({command:`workspace ${e}`,cwd:t.cwd,ok:!0,data:n})}}catch(n){return {exitCode:1,envelope:k({command:`workspace ${e}`,cwd:t.cwd,ok:false,error:{code:V(n,"workspace_command_failed"),message:n instanceof Error?n.message:String(n)}})}}}async function QC(t,e){try{let r=await ae("create_workspace",t.env);if(!r.allowed){let i=ar(r);return {exitCode:1,envelope:k({command:"init",cwd:t.cwd,ok:!1,data:{preflight:r},error:{code:r.blocking_reason??"preflight_blocked",message:i.summary},next_steps:Ki(i)})}}let n=await bt(e??Xh(t.cwd),t.cwd,t.env);return {exitCode:0,envelope:k({command:"init",cwd:t.cwd,ok:!0,data:n})}}catch(r){return {exitCode:1,envelope:k({command:"init",cwd:t.cwd,ok:false,error:{code:V(r,"init_failed"),message:r instanceof Error?r.message:String(r)}})}}}async function e0(t,e,r){try{let n=await fr(e,t.cwd,t.env,{yes:r});return {exitCode:0,envelope:k({command:"setup",cwd:t.cwd,ok:!0,data:n})}}catch(n){let i=V(n,"setup_failed");return {exitCode:i.startsWith("unknown_setup_option")||i.startsWith("missing_value")||i==="setup_requires_yes"?64:1,envelope:k({command:"setup",cwd:t.cwd,ok:false,error:{code:i,message:n instanceof Error?n.message:String(n)}})}}}async function t0(t,e){try{let r=await xe(e,t.cwd,t.env);return {exitCode:0,envelope:k({command:"attach",cwd:t.cwd,ok:!0,data:r})}}catch(r){return {exitCode:1,envelope:k({command:"attach",cwd:t.cwd,ok:false,error:{code:V(r,"attach_failed"),message:r instanceof Error?r.message:String(r)}})}}}async function r0(t,e){try{let r=await Qr(e,t.env);return {exitCode:0,envelope:k({command:"detach",cwd:t.cwd,ok:!0,data:r})}}catch(r){return {exitCode:1,envelope:k({command:"detach",cwd:t.cwd,ok:false,error:{code:V(r,"detach_failed"),message:r instanceof Error?r.message:String(r)}})}}}async function n0(t,e){if(!e||!Vo(e))return {exitCode:64,envelope:k({command:"preflight",cwd:t.cwd,ok:false,error:{code:"invalid_preflight_action",message:"Usage: pathrule preflight <create_workspace|write_memory|write_rule|write_skill|sync_agents|materialize_skills>"}})};try{let r=await ae(e,t.env),n=r.allowed?null:ar(r);return {exitCode:r.allowed?0:1,envelope:k({command:`preflight ${e}`,cwd:t.cwd,ok:r.allowed,data:r,error:r.allowed?void 0:{code:r.blocking_reason??"preflight_blocked",message:n?.summary??"Preflight blocked."},next_steps:n?Ki(n):void 0})}}catch(r){return {exitCode:1,envelope:k({command:`preflight ${e}`,cwd:t.cwd,ok:false,error:{code:V(r,"preflight_failed"),message:r instanceof Error?r.message:String(r)}})}}}async function i0(t,e){try{let r=await Ze(e,t.env);return {exitCode:r.every(n=>n.ok)?0:1,envelope:k({command:"install",cwd:t.cwd,ok:r.every(n=>n.ok),data:r})}}catch(r){return {exitCode:r instanceof Error&&r.message==="invalid_install_target"?64:1,envelope:k({command:"install",cwd:t.cwd,ok:false,error:{code:r instanceof Error?r.message:"install_failed",message:r instanceof Error?r.message:String(r)}})}}}async function s0(t,e){try{let r=await Xo(e);return {exitCode:r.every(n=>n.ok)?0:1,envelope:k({command:"uninstall",cwd:t.cwd,ok:r.every(n=>n.ok),data:r})}}catch(r){return {exitCode:r instanceof Error&&r.message==="invalid_install_target"?64:1,envelope:k({command:"uninstall",cwd:t.cwd,ok:false,error:{code:r instanceof Error?r.message:"uninstall_failed",message:r instanceof Error?r.message:String(r)}})}}}async function o0(t,e){try{let r=await Le(t.env,t.cwd,{skillsOnly:e.includes("--skills")});return {exitCode:r.ok?0:1,envelope:k({command:"sync",cwd:t.cwd,ok:r.ok,data:r,error:r.ok?void 0:{code:r.error??"sync_failed",message:r.error??"Pathrule sync failed."}})}}catch(r){return {exitCode:1,envelope:k({command:"sync",cwd:t.cwd,ok:false,error:{code:V(r,"sync_failed"),message:r instanceof Error?r.message:String(r)}})}}}async function a0(t,e,r,n){try{if(e==="get"&&r){let i=await kt(r,t.env);return {exitCode:0,envelope:k({command:`config get ${r}`,cwd:t.cwd,ok:!0,data:i})}}if(e==="set"&&r&&n){let i=await uo(r,n,t.env);return {exitCode:0,envelope:k({command:`config set ${r}`,cwd:t.cwd,ok:!0,data:i})}}if(e==="reset"&&r){let i=await po(r,t.env);return {exitCode:0,envelope:k({command:`config reset ${r}`,cwd:t.cwd,ok:!0,data:i})}}return {exitCode:64,envelope:k({command:"config",cwd:t.cwd,ok:!1,error:{code:"invalid_config_command",message:"Usage: pathrule config get <update.policy|suggestions.desktop|telemetry.enabled|telemetry.id> OR pathrule config set update.policy manual|notify|auto OR pathrule config set suggestions.desktop true|false OR pathrule config set telemetry.enabled true|false OR pathrule config reset telemetry-id"}})}}catch(i){return {exitCode:i instanceof Error&&i.message.startsWith("invalid_")?64:1,envelope:k({command:"config",cwd:t.cwd,ok:false,error:{code:i instanceof Error?i.message:"config_failed",message:i instanceof Error?i.message:String(i)}})}}}async function l0(t){let e=await Li(Be.version,t.env,t.fetch??fetch);return {exitCode:0,envelope:k({command:"update",cwd:t.cwd,ok:true,data:e})}}async function c0(t,e){let r=e[0]??"status";try{if(r==="run")throw new Error("daemon_run_not_available_in_json_mode");if(r==="autostart"||r==="toggle"){let i=r==="toggle"?"toggle":e[1]??"status",s=await Pe(t.env),o=i==="status"?s:i==="on"||i==="enable"?await Qe(t.env,!0):i==="off"||i==="disable"?await Qe(t.env,!1):i==="toggle"?await Qe(t.env,!s.enabled):null;if(!o)throw new Error("invalid_daemon_command");return {exitCode:o.supported?0:1,envelope:k({command:r==="toggle"?"daemon toggle":`daemon autostart ${i}`,cwd:t.cwd,ok:o.supported,data:o,error:o.supported?void 0:{code:"daemon_autostart_unsupported",message:o.reason??"Daemon autostart is not supported on this platform."}})}}let n=r==="start"?await pr(Ae(t.env)):r==="stop"?await fn(t.env):r==="status"?await We(t.env):null;if(!n)throw new Error("invalid_daemon_command");return {exitCode:0,envelope:k({command:`daemon ${r}`,cwd:t.cwd,ok:!0,data:n})}}catch(n){let i=n instanceof Error?n.message:"daemon_failed";return {exitCode:i==="invalid_daemon_command"?64:1,envelope:k({command:`daemon ${r}`,cwd:t.cwd,ok:false,error:{code:i,message:n instanceof Error?n.message:String(n)}})}}}async function u0(t){try{let e=await pr(Ae(t.env));return {exitCode:0,envelope:k({command:"start",cwd:t.cwd,ok:!0,data:e})}}catch(e){let r=e instanceof Error?e.message:"start_failed";return {exitCode:1,envelope:k({command:"start",cwd:t.cwd,ok:false,error:{code:r,message:e instanceof Error?e.message:String(e)}})}}}async function d0(t,e){try{if(e!=="pair")throw new Error("invalid_bridge_command");let r=Ae(t.env),n=await fi(r),i=(await zi(r)).status;if(!i.state?.daemon_session_id)throw new Error("daemon_session_missing");let s=await Co({env:r,daemonSessionId:i.state.daemon_session_id,user:n,verifyReauth:!1});return {exitCode:0,envelope:k({command:"bridge pair",cwd:t.cwd,ok:!0,data:s})}}catch(r){let n=r instanceof Y||r instanceof tr?r.code:r instanceof Error?r.message:"bridge_pair_failed";return {exitCode:n==="invalid_bridge_command"?64:1,envelope:k({command:`bridge ${e}`,cwd:t.cwd,ok:false,error:{code:n,message:r instanceof Error?r.message:String(r)}})}}}async function p0(t,e,r){try{let n=e==="current"?await j(t.env):e==="use"?await hi(r[0]??"",t.env):e==="open"?await h0(t,r[0]):await we(t.env);return {exitCode:0,envelope:k({command:`org ${e}`,cwd:t.cwd,ok:!0,data:n})}}catch(n){return {exitCode:1,envelope:k({command:`org ${e}`,cwd:t.cwd,ok:false,error:{code:V(n,"org_command_failed"),message:n instanceof Error?n.message:String(n)}})}}}async function h0(t,e){let r=await j(t.env);if(!r)throw new Error("org_required");let n=zh(e);return {org_id:r.id,slug:r.slug,name:r.name,role:r.role,billing:r.billing,url:ee(r,t.env,n),opened:false}}async function $h(t){let e=await Ce(t.env);if(!e)return {authenticated:false,user:null,organization:null,workspace:null,cwd_workspace_match:null};let r=await j(t.env),n=await M(t.env),i=await Re(t.env),s=Uh(i,t.cwd),o=s??n;return {authenticated:true,user:{id:e.session.user.id,email:e.session.user.email??null,expires_at:e.session.expires_at},organization:r,workspace:o,selected_workspace:n,cwd_workspace_match:s}}async function f0(t,e,r,n){try{if(t==="current"){let s=await M(r.env);return s?(r.stdout.write(`${g("ok",n)} ${s.name}
312
+ `),o=0;break;case "start":o=await H0(e,i);break;case "login":o=await Gh(e,i,n.flags.browserCallback);break;case "org":o=await bE(n.positional[1]??"list",n.positional.slice(2),e,i);break;case "workspace":o=await f0(n.positional[1]??"list",n.positional.slice(2),e,i);break;case "init":o=await g0(n.positional[1],e,i);break;case "setup":o=await m0(e,i,n.positional.slice(1),n.flags.yes);break;case "attach":o=await N0(n.positional[1],e,i);break;case "detach":o=await D0(n.positional[1],e,i);break;case "preflight":o=await j0(n.positional[1],e,i);break;case "install":o=await M0(n.positional[1],e,i);break;case "uninstall":o=await L0(n.positional[1],e,i);break;case "sync":o=await U0(n.positional.slice(1),e,i);break;case "config":o=await W0(n.positional[1],n.positional[2],n.positional[3],e,i);break;case "update":o=await B0(e,i);break;case "daemon":o=await q0(n.positional.slice(1),e,i);break;case "bridge":o=await J0(n.positional[1]??"pair",e,i);break;case "open":o=await jh(n.positional.slice(1),e,i);break;case "search":o=await cE(n.positional.slice(1),e,i);break;case "memory":case "rule":case "skill":o=await lE(s,n.positional.slice(1),e,i);break;case "refresh":o=await uE(n.positional.slice(1),e,i);break;case "repair":o=await dE(e,i);break;case "cache":o=await pE(n.positional.slice(1),e,i,n.flags.yes);break;case "billing":case "team":case "invite":case "upgrade":case "reactivate":o=s==="invite"?await Q0(n.positional.slice(1),e,i):s==="team"?await eE(n.positional.slice(1),e,i):await Z0(s,n.positional.slice(1),e,i);break;case "status":o=await G0(e,i);break;case "doctor":o=await V0(n.positional.slice(1),e,i);break;case "whoami":o=await X0(e,i);break;case "logout":o=await IE(e,i);break;default:e.stderr.write(`${g("error",i)} Unknown command "${s}". Run pathrule help.
313
+ `),o=64;}return s!=="update"&&s!=="login"&&s!=="logout"&&await F0(e,i),await so(e.env,{command:s,exitCode:o,appVersion:Be.version,durationMs:Date.now()-r}),o}async function zC(t,e,r,n={yes:false}){if(t==="version")return {exitCode:0,envelope:k({command:t,cwd:e.cwd,ok:true,data:{version:Be.version}})};if(t==="help"){let i=Ih(r[0]);return i.ok?{exitCode:0,envelope:k({command:t,cwd:e.cwd,ok:true,data:{topic:i.topic,topics:[...Ta],text:i.text,commands:["help","version","start","login","status","doctor","whoami","logout","org","workspace","init","setup","attach","detach","preflight","install","uninstall","sync","config","update","daemon","bridge","open","search","memory","rule","skill","refresh","repair","cache","billing","team","invite","upgrade","reactivate"]}})}:{exitCode:64,envelope:k({command:t,cwd:e.cwd,ok:false,error:{code:"invalid_help_topic",message:i.message}})}}if(t==="login")try{let i=await to({env:e.env,fetch:e.fetch??fetch,sleep:e.sleep??Yh});return {exitCode:0,envelope:k({command:t,cwd:e.cwd,ok:!0,data:{user_id:i.session.user.id,email:i.session.user.email??null,expires_at:i.session.expires_at}})}}catch(i){let s=i instanceof je?i.code:"login_failed";return {exitCode:1,envelope:k({command:t,cwd:e.cwd,ok:false,error:{code:s,message:i instanceof Error?i.message:String(i)}})}}if(t==="start")return u0(e);if(t==="daemon")return c0(e,r);if(t==="bridge")return d0(e,r[0]??"pair");if(t==="open")return Mh(e,r);if(t==="search")return fE(e,r);if(t==="memory"||t==="rule"||t==="skill")return hE(t,e,r);if(t==="refresh")return gE(e,r);if(t==="repair")return mE(e);if(t==="cache")return _E(e,r,n.yes);if(t==="invite")return rE(e,r);if(t==="team")return nE(e,r);if(t==="billing"||t==="upgrade"||t==="reactivate")return tE(t,e,r);if(t==="whoami"){let i=await Ce(e.env);return i?{exitCode:0,envelope:k({command:t,cwd:e.cwd,ok:true,data:{user_id:i.session.user.id,email:i.session.user.email??null,expires_at:i.session.expires_at,...await GC(e.env)}})}:{exitCode:1,envelope:k({command:t,cwd:e.cwd,ok:false,error:{code:"not_authenticated",message:"Pathrule CLI is not signed in.",remediation:[{label:"Sign in",command:"pathrule login"}]}})}}if(t==="logout"){let i=await no(e.env);return {exitCode:0,envelope:k({command:t,cwd:e.cwd,ok:true,data:i})}}return t==="org"?p0(e,r[0]??"list",r.slice(1)):t==="workspace"?ZC(e,r[0]??"list",r.slice(1)):t==="init"?QC(e,r[0]):t==="setup"?e0(e,r,n.yes):t==="attach"?t0(e,r[0]):t==="detach"?r0(e,r[0]):t==="preflight"?n0(e,r[0]):t==="install"?i0(e,r[0]):t==="uninstall"?s0(e,r[0]):t==="sync"?o0(e,r):t==="config"?a0(e,r[0],r[1],r[2]):t==="update"?l0(e):t==="status"?XC(e):t==="doctor"?JC(e,r):t==="__scaffold"?{exitCode:0,envelope:k({command:t,cwd:e.cwd,ok:true,data:{status:"not_implemented",phase:"m31a_cli_foundation"},next_steps:VC(t)})}:{exitCode:64,envelope:k({command:t,cwd:e.cwd,ok:false,error:{code:"unknown_command",message:`Unknown command "${t}".`,remediation:[{label:"Show help",command:"pathrule help"}]}})}}async function JC(t,e){try{if(e.includes("--bundle")){let n=await Uo(t.env,t.cwd);return {exitCode:n.ok?0:1,envelope:k({command:"doctor --bundle",cwd:t.cwd,ok:n.ok,data:{path:n.path,report:n.report}})}}let r=await Me(t.env,t.cwd);return await KC(t.env,r.managed_files),{exitCode:r.ok?0:1,envelope:k({command:"doctor",cwd:t.cwd,ok:r.ok,data:r})}}catch(r){return {exitCode:1,envelope:k({command:"doctor",cwd:t.cwd,ok:false,error:{code:V(r,"doctor_failed"),message:r instanceof Error?r.message:String(r)}})}}}async function KC(t,e){e.some(r=>r.status==="other_owner"||r.status==="newer_version")&&(await Xr(t,{eventName:"managed_file_owner_conflict",result:"blocked",appVersion:Be.version,featureTag:"managed_files",blockingReason:"managed_file_owner_conflict"}).catch(()=>{}),await Xr(t,{eventName:"dead_end_seen",result:"blocked",appVersion:Be.version,featureTag:"managed_files",blockingReason:"managed_file_owner_conflict"}).catch(()=>{}));}function VC(t){if(t==="status"||t==="doctor"||t==="whoami")return [{label:"Continue M31a implementation",command:"pathrule login"}]}async function GC(t){try{let[e,r,n]=await Promise.all([we(t),D(t),M(t)]);return {organizations:e,current_org:r,current_workspace:n}}catch(e){return {context_error:e instanceof Error?e.message:String(e)}}}async function YC(t){let e=await M(t);if(!e)throw new Error("workspace_required");return e}async function XC(t){try{let e=await $h(t);return {exitCode:e.authenticated?0:1,envelope:k({command:"status",cwd:t.cwd,ok:e.authenticated,data:e,error:e.authenticated?void 0:{code:"not_authenticated",message:"Pathrule CLI is not signed in.",remediation:[{label:"Sign in",command:"pathrule login"}]}})}}catch(e){return {exitCode:1,envelope:k({command:"status",cwd:t.cwd,ok:false,error:{code:V(e,"status_failed"),message:e instanceof Error?e.message:String(e)}})}}}async function ZC(t,e,r){try{if(e==="inspect"){let i=await va(t);return {exitCode:0,envelope:k({command:"workspace inspect",cwd:t.cwd,ok:!0,data:i})}}if(e==="open"){let i=await gr(t);if(!i)throw new Error("workspace_required");let s=await qi(i.id,t.env,{preferDesktopApp:r.includes("--desktop-app"),forceWeb:r.includes("--web")});return {exitCode:0,envelope:k({command:"workspace open",cwd:t.cwd,ok:!0,data:s})}}if(e==="create"){let i=await ae("create_workspace",t.env);if(!i.allowed){let s=ar(i);return {exitCode:1,envelope:k({command:"workspace create",cwd:t.cwd,ok:!1,data:{preflight:i},error:{code:i.blocking_reason??"preflight_blocked",message:s.summary},next_steps:Ki(s)})}}}let n=e==="current"?await YC(t.env):e==="use"?await Zr(r[0]??"",t.env):e==="create"?await bt(r[0]??"",t.cwd,t.env):e==="attach"?await xe(r[0],t.cwd,t.env):e==="detach"?await Qr(r[0],t.env):await Re(t.env);return {exitCode:0,envelope:k({command:`workspace ${e}`,cwd:t.cwd,ok:!0,data:n})}}catch(n){return {exitCode:1,envelope:k({command:`workspace ${e}`,cwd:t.cwd,ok:false,error:{code:V(n,"workspace_command_failed"),message:n instanceof Error?n.message:String(n)}})}}}async function QC(t,e){try{let r=await ae("create_workspace",t.env);if(!r.allowed){let i=ar(r);return {exitCode:1,envelope:k({command:"init",cwd:t.cwd,ok:!1,data:{preflight:r},error:{code:r.blocking_reason??"preflight_blocked",message:i.summary},next_steps:Ki(i)})}}let n=await bt(e??Xh(t.cwd),t.cwd,t.env);return {exitCode:0,envelope:k({command:"init",cwd:t.cwd,ok:!0,data:n})}}catch(r){return {exitCode:1,envelope:k({command:"init",cwd:t.cwd,ok:false,error:{code:V(r,"init_failed"),message:r instanceof Error?r.message:String(r)}})}}}async function e0(t,e,r){try{let n=await fr(e,t.cwd,t.env,{yes:r});return {exitCode:0,envelope:k({command:"setup",cwd:t.cwd,ok:!0,data:n})}}catch(n){let i=V(n,"setup_failed");return {exitCode:i.startsWith("unknown_setup_option")||i.startsWith("missing_value")||i==="setup_requires_yes"?64:1,envelope:k({command:"setup",cwd:t.cwd,ok:false,error:{code:i,message:n instanceof Error?n.message:String(n)}})}}}async function t0(t,e){try{let r=await xe(e,t.cwd,t.env);return {exitCode:0,envelope:k({command:"attach",cwd:t.cwd,ok:!0,data:r})}}catch(r){return {exitCode:1,envelope:k({command:"attach",cwd:t.cwd,ok:false,error:{code:V(r,"attach_failed"),message:r instanceof Error?r.message:String(r)}})}}}async function r0(t,e){try{let r=await Qr(e,t.env);return {exitCode:0,envelope:k({command:"detach",cwd:t.cwd,ok:!0,data:r})}}catch(r){return {exitCode:1,envelope:k({command:"detach",cwd:t.cwd,ok:false,error:{code:V(r,"detach_failed"),message:r instanceof Error?r.message:String(r)}})}}}async function n0(t,e){if(!e||!Vo(e))return {exitCode:64,envelope:k({command:"preflight",cwd:t.cwd,ok:false,error:{code:"invalid_preflight_action",message:"Usage: pathrule preflight <create_workspace|write_memory|write_rule|write_skill|sync_agents|materialize_skills>"}})};try{let r=await ae(e,t.env),n=r.allowed?null:ar(r);return {exitCode:r.allowed?0:1,envelope:k({command:`preflight ${e}`,cwd:t.cwd,ok:r.allowed,data:r,error:r.allowed?void 0:{code:r.blocking_reason??"preflight_blocked",message:n?.summary??"Preflight blocked."},next_steps:n?Ki(n):void 0})}}catch(r){return {exitCode:1,envelope:k({command:`preflight ${e}`,cwd:t.cwd,ok:false,error:{code:V(r,"preflight_failed"),message:r instanceof Error?r.message:String(r)}})}}}async function i0(t,e){try{let r=await Ze(e,t.env);return {exitCode:r.every(n=>n.ok)?0:1,envelope:k({command:"install",cwd:t.cwd,ok:r.every(n=>n.ok),data:r})}}catch(r){return {exitCode:r instanceof Error&&r.message==="invalid_install_target"?64:1,envelope:k({command:"install",cwd:t.cwd,ok:false,error:{code:r instanceof Error?r.message:"install_failed",message:r instanceof Error?r.message:String(r)}})}}}async function s0(t,e){try{let r=await Xo(e);return {exitCode:r.every(n=>n.ok)?0:1,envelope:k({command:"uninstall",cwd:t.cwd,ok:r.every(n=>n.ok),data:r})}}catch(r){return {exitCode:r instanceof Error&&r.message==="invalid_install_target"?64:1,envelope:k({command:"uninstall",cwd:t.cwd,ok:false,error:{code:r instanceof Error?r.message:"uninstall_failed",message:r instanceof Error?r.message:String(r)}})}}}async function o0(t,e){try{let r=await Le(t.env,t.cwd,{skillsOnly:e.includes("--skills")});return {exitCode:r.ok?0:1,envelope:k({command:"sync",cwd:t.cwd,ok:r.ok,data:r,error:r.ok?void 0:{code:r.error??"sync_failed",message:r.error??"Pathrule sync failed."}})}}catch(r){return {exitCode:1,envelope:k({command:"sync",cwd:t.cwd,ok:false,error:{code:V(r,"sync_failed"),message:r instanceof Error?r.message:String(r)}})}}}async function a0(t,e,r,n){try{if(e==="get"&&r){let i=await kt(r,t.env);return {exitCode:0,envelope:k({command:`config get ${r}`,cwd:t.cwd,ok:!0,data:i})}}if(e==="set"&&r&&n){let i=await uo(r,n,t.env);return {exitCode:0,envelope:k({command:`config set ${r}`,cwd:t.cwd,ok:!0,data:i})}}if(e==="reset"&&r){let i=await po(r,t.env);return {exitCode:0,envelope:k({command:`config reset ${r}`,cwd:t.cwd,ok:!0,data:i})}}return {exitCode:64,envelope:k({command:"config",cwd:t.cwd,ok:!1,error:{code:"invalid_config_command",message:"Usage: pathrule config get <update.policy|suggestions.desktop|telemetry.enabled|telemetry.id> OR pathrule config set update.policy manual|notify|auto OR pathrule config set suggestions.desktop true|false OR pathrule config set telemetry.enabled true|false OR pathrule config reset telemetry-id"}})}}catch(i){return {exitCode:i instanceof Error&&i.message.startsWith("invalid_")?64:1,envelope:k({command:"config",cwd:t.cwd,ok:false,error:{code:i instanceof Error?i.message:"config_failed",message:i instanceof Error?i.message:String(i)}})}}}async function l0(t){let e=await Li(Be.version,t.env,t.fetch??fetch);return {exitCode:0,envelope:k({command:"update",cwd:t.cwd,ok:true,data:e})}}async function c0(t,e){let r=e[0]??"status";try{if(r==="run")throw new Error("daemon_run_not_available_in_json_mode");if(r==="autostart"||r==="toggle"){let i=r==="toggle"?"toggle":e[1]??"status",s=await Pe(t.env),o=i==="status"?s:i==="on"||i==="enable"?await Qe(t.env,!0):i==="off"||i==="disable"?await Qe(t.env,!1):i==="toggle"?await Qe(t.env,!s.enabled):null;if(!o)throw new Error("invalid_daemon_command");return {exitCode:o.supported?0:1,envelope:k({command:r==="toggle"?"daemon toggle":`daemon autostart ${i}`,cwd:t.cwd,ok:o.supported,data:o,error:o.supported?void 0:{code:"daemon_autostart_unsupported",message:o.reason??"Daemon autostart is not supported on this platform."}})}}let n=r==="start"?await pr(Ae(t.env)):r==="stop"?await fn(t.env):r==="status"?await We(t.env):null;if(!n)throw new Error("invalid_daemon_command");return {exitCode:0,envelope:k({command:`daemon ${r}`,cwd:t.cwd,ok:!0,data:n})}}catch(n){let i=n instanceof Error?n.message:"daemon_failed";return {exitCode:i==="invalid_daemon_command"?64:1,envelope:k({command:`daemon ${r}`,cwd:t.cwd,ok:false,error:{code:i,message:n instanceof Error?n.message:String(n)}})}}}async function u0(t){try{let e=await pr(Ae(t.env));return {exitCode:0,envelope:k({command:"start",cwd:t.cwd,ok:!0,data:e})}}catch(e){let r=e instanceof Error?e.message:"start_failed";return {exitCode:1,envelope:k({command:"start",cwd:t.cwd,ok:false,error:{code:r,message:e instanceof Error?e.message:String(e)}})}}}async function d0(t,e){try{if(e!=="pair")throw new Error("invalid_bridge_command");let r=Ae(t.env),n=await fi(r),i=(await zi(r)).status;if(!i.state?.daemon_session_id)throw new Error("daemon_session_missing");let s=await Co({env:r,daemonSessionId:i.state.daemon_session_id,user:n,verifyReauth:!1});return {exitCode:0,envelope:k({command:"bridge pair",cwd:t.cwd,ok:!0,data:s})}}catch(r){let n=r instanceof Y||r instanceof tr?r.code:r instanceof Error?r.message:"bridge_pair_failed";return {exitCode:n==="invalid_bridge_command"?64:1,envelope:k({command:`bridge ${e}`,cwd:t.cwd,ok:false,error:{code:n,message:r instanceof Error?r.message:String(r)}})}}}async function p0(t,e,r){try{let n=e==="current"?await D(t.env):e==="use"?await hi(r[0]??"",t.env):e==="open"?await h0(t,r[0]):await we(t.env);return {exitCode:0,envelope:k({command:`org ${e}`,cwd:t.cwd,ok:!0,data:n})}}catch(n){return {exitCode:1,envelope:k({command:`org ${e}`,cwd:t.cwd,ok:false,error:{code:V(n,"org_command_failed"),message:n instanceof Error?n.message:String(n)}})}}}async function h0(t,e){let r=await D(t.env);if(!r)throw new Error("org_required");let n=zh(e);return {org_id:r.id,slug:r.slug,name:r.name,role:r.role,billing:r.billing,url:ee(r,t.env,n),opened:false}}async function $h(t){let e=await Ce(t.env);if(!e)return {authenticated:false,user:null,organization:null,workspace:null,cwd_workspace_match:null};let r=await D(t.env),n=await M(t.env),i=await Re(t.env),s=Uh(i,t.cwd),o=s??n;return {authenticated:true,user:{id:e.session.user.id,email:e.session.user.email??null,expires_at:e.session.expires_at},organization:r,workspace:o,selected_workspace:n,cwd_workspace_match:s}}async function f0(t,e,r,n){try{if(t==="current"){let s=await M(r.env);return s?(r.stdout.write(`${g("ok",n)} ${s.name}
314
314
  `),0):(r.stdout.write(`${g("warn",n)} No current workspace selected. Run pathrule workspace use <name-or-id>.
315
315
  `),1)}if(t==="use"){let s=e[0];if(!s)return r.stderr.write(`${g("error",n)} Usage: pathrule workspace use <name-or-id>
316
316
  `),64;let o=await Zr(s,r.env);return r.stdout.write(`${g("ok",n)} Current workspace: ${o.name}
@@ -348,7 +348,7 @@ Useful commands:
348
348
  `):i.workspace_action==="selected"&&t.stdout.write(`${g("ok",e)} Workspace selected.
349
349
  `),i.install&&t.stdout.write(`${g("ok",e)} Local AI tool setup completed.
350
350
  `),i.sync&&t.stdout.write(`${g("ok",e)} Workspace files synced.
351
- `),Nh(i.bootstrap_v2,t.stdout,e),jh(i.beta_activation,t.stdout,e),i.bootstrap_v2&&t.stdout.write(`Next: run this in your AI tool: ${Hi}
351
+ `),Nh(i.bootstrap_v2,t.stdout,e),Dh(i.beta_activation,t.stdout,e),i.bootstrap_v2&&t.stdout.write(`Next: run this in your AI tool: ${Hi}
352
352
  `),t.stdout.write(`Next: pathrule doctor
353
353
  `),await tt(t,e),await mr(t,e),0;if(!s.organization)return t.stdout.write(`${g("warn",e)} No organization selected.
354
354
  `),t.stdout.write(`Next: pathrule org list
@@ -368,7 +368,7 @@ Useful commands:
368
368
  `);let i=await k0(n,t,e);if(!i)return t.stdout.write(`${g("info",e)} Setup canceled.
369
369
  `),0;let s=await fr(i,t.cwd,t.env,{yes:!0}),o=$0(s.workspace);if(!o)throw new Error("workspace_setup_failed");s.workspace_action==="created"?t.stdout.write(`${g("ok",e)} Workspace created and attached.
370
370
  `):s.workspace_action==="attached"&&t.stdout.write(`${g("ok",e)} Workspace attached to this folder.
371
- `),Nh(s.bootstrap_v2,t.stdout,e),jh(s.beta_activation,t.stdout,e);let a=await b0(t,e);if(a.length>0){await O0(t.env,o.workspaceId,a);for(let c of a){let u=await Ze(c,t.env);for(let d of u)d.ok?t.stdout.write(`${g("ok",e)} ${U[d.client].label} MCP installed.
371
+ `),Nh(s.bootstrap_v2,t.stdout,e),Dh(s.beta_activation,t.stdout,e);let a=await b0(t,e);if(a.length>0){await O0(t.env,o.workspaceId,a);for(let c of a){let u=await Ze(c,t.env);for(let d of u)d.ok?t.stdout.write(`${g("ok",e)} ${U[d.client].label} MCP installed.
372
372
  `):t.stdout.write(`${g("warn",e)} ${U[d.client].label}: ${d.error??d.status}
373
373
  `);}let l=await Le(t.env,t.cwd);l.ok?t.stdout.write(`${g("ok",e)} Workspace files synced.
374
374
  `):t.stdout.write(`${g("warn",e)} ${l.error??"Workspace sync failed."}
@@ -415,9 +415,9 @@ tell application "Terminal" to activate`;spawn("osascript",["-e",s],{detached:tr
415
415
 
416
416
  ${t}`}function Sh(t){return `'${t.replace(/'/g,"'\\''")}'`}function I0(t){return t.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}async function O0(t,e,r){let{session:n,supabase:i}=await C(t),{error:s}=await i.from("user_workspace_paths").update({selected_ai_clients:r}).eq("user_id",n.user.id).eq("workspace_id",e);if(s)throw new Error(`workspace_client_selection_update_failed: ${s.message}`)}function $0(t){if(!t||typeof t!="object")return null;let e=t;return typeof e.workspace?.id!="string"||typeof e.local_root_path!="string"?null:{workspaceId:e.workspace.id,localRootPath:e.local_root_path}}async function N0(t,e,r){try{let n=await xe(t,e.cwd,e.env);return e.stdout.write(`${g("ok",r)} Attached ${n.workspace.name} to ${n.local_root_path}
417
417
  `),await tt(e,r),await mr(e,r),0}catch(n){return e.stderr.write(`${g("error",r)} ${n instanceof Error?n.message:String(n)}
418
- `),1}}async function j0(t,e,r){try{let n=await Qr(t,e.env);return e.stdout.write(`${g("ok",r)} Detached ${n.name} from this machine.
418
+ `),1}}async function D0(t,e,r){try{let n=await Qr(t,e.env);return e.stdout.write(`${g("ok",r)} Detached ${n.name} from this machine.
419
419
  `),0}catch(n){return e.stderr.write(`${g("error",r)} ${n instanceof Error?n.message:String(n)}
420
- `),1}}async function D0(t,e,r){if(!t||!Vo(t))return e.stderr.write(`${g("error",r)} Usage: pathrule preflight <create_workspace|write_memory|write_rule|write_skill|sync_agents|materialize_skills>
420
+ `),1}}async function j0(t,e,r){if(!t||!Vo(t))return e.stderr.write(`${g("error",r)} Usage: pathrule preflight <create_workspace|write_memory|write_rule|write_skill|sync_agents|materialize_skills>
421
421
  `),64;try{let n=await ae(t,e.env);return n.allowed?(e.stdout.write(`${g("ok",r)} ${t} is allowed.
422
422
  `),0):(Vi(n,e.stderr,r),1)}catch(n){return e.stderr.write(`${g("error",r)} ${n instanceof Error?n.message:String(n)}
423
423
  `),1}}async function M0(t,e,r){try{let n=await Ze(t,e.env);for(let s of n)e.stdout.write(`${g(s.ok?"ok":"error",r)} ${s.client}: ${s.status} (${s.config_path})
@@ -483,7 +483,7 @@ ${t}
483
483
  `);}}async function G0(t,e){try{let r=await $h(t);return r.authenticated?(t.stdout.write(["Pathrule status",`${g("ok",e)} Signed in as ${r.user?.email??r.user?.id}`,`Organization: ${r.organization?.slug??"none"}`,`Trial ends: ${r.organization?.trial_ends_at??"none"}`,`Beta credit: ${Y0(r.organization?.beta_referral_credit_cents??0)}`,`Beta Founder: ${r.organization?.beta_referral_founder?"yes":"no"}`,`Workspace: ${r.workspace?.name??"none"}`,`Current folder: ${r.cwd_workspace_match?`attached to ${r.cwd_workspace_match.name}`:"not attached"}`,""].join(`
484
484
  `)),0):(t.stderr.write(`${g("error",e)} Not signed in. Run pathrule login.
485
485
  `),1)}catch(r){return t.stderr.write(`${g("error",e)} ${r instanceof Error?r.message:String(r)}
486
- `),1}}function jh(t,e,r){if(t){if(t.status==="credited"){e.write(`${g("ok",r)} Beta activation credited: $20 earned for your inviter.
486
+ `),1}}function Dh(t,e,r){if(t){if(t.status==="credited"){e.write(`${g("ok",r)} Beta activation credited: $20 earned for your inviter.
487
487
  `),e.write(`${g("info",r)} Invite your own beta users to earn credits too.
488
488
  `),t.founder_bonus_cents&&t.founder_bonus_cents>0&&e.write(`${g("ok",r)} Beta Founder bonus unlocked.
489
489
  `);return}t.status==="duplicate_repo"?e.write(`${g("info",r)} Beta activation already used this repo.
@@ -491,10 +491,10 @@ ${t}
491
491
  `):t.status==="reward_cap_reached"&&e.write(`${g("info",r)} Beta invite accepted; inviter reward cap is already full.
492
492
  `);}}function Y0(t){return `$${(t/100).toFixed(2)}`}async function X0(t,e){let r=await Ce(t.env);return r?(t.stdout.write(["Pathrule account",`${g("ok",e)} Signed in`,`User: ${r.session.user.email??r.session.user.id}`,`Expires: ${new Date(r.session.expires_at*1e3).toISOString()}`,""].join(`
493
493
  `)),0):(t.stderr.write(`${g("error",e)} Not signed in. Run pathrule login.
494
- `),1)}async function Dh(t,e,r){try{let n=await Lh(t,e);return r.interactive&&!r.noOpen?(await Fe(e,n.url),e.stdout.write(`${g("ok",r)} Opened ${n.url}
494
+ `),1)}async function jh(t,e,r){try{let n=await Lh(t,e);return r.interactive&&!r.noOpen?(await Fe(e,n.url),e.stdout.write(`${g("ok",r)} Opened ${n.url}
495
495
  `)):e.stdout.write(`${n.url}
496
496
  `),0}catch(n){return e.stderr.write(`${g("error",r)} ${n instanceof Error?n.message:String(n)}
497
- `),1}}async function Z0(t,e,r,n){return Dh([Wh(t),...e],r,n)}async function Q0(t,e,r){try{let n=await ca(la(t),e.env);return n.ok?(e.stdout.write(`${g("ok",r)} Invited ${n.email} to ${n.organization.name} as ${n.role}
497
+ `),1}}async function Z0(t,e,r,n){return jh([Wh(t),...e],r,n)}async function Q0(t,e,r){try{let n=await ca(la(t),e.env);return n.ok?(e.stdout.write(`${g("ok",r)} Invited ${n.email} to ${n.organization.name} as ${n.role}
498
498
  `),n.workspace&&e.stdout.write(`Workspace context: ${n.workspace.name}
499
499
  `),n.email_sent?e.stdout.write(`Invite email sent.
500
500
  `):e.stdout.write(`${g("warn",r)} Invite created, but the email could not be sent automatically.
@@ -514,7 +514,7 @@ ${t}
514
514
  `)):e.stdout.write(`${s.url}
515
515
  `),0):(e.stdout.write([`${xn(i.organization.name)} (${i.organization.slug})`,`${g("info",r)} Your role: ${i.organization.role}`,"","Members",...i.members.map(o=>`- ${xn(o.email??o.user_id)} \xB7 ${o.role}${o.full_name?` \xB7 ${xn(o.full_name)}`:""}`),"","Pending invites",...i.invites.length?i.invites.map(o=>`- ${o.email} \xB7 ${o.role} \xB7 expires ${o.expires_at}`):["- none"],"",`${s.label}: ${s.url}`,""].join(`
516
516
  `)),0)}catch(n){return e.stderr.write(`${g("error",r)} ${n instanceof Error?n.message:String(n)}
517
- `),1}}async function Mh(t,e){try{let r=await Lh(e,t);return {exitCode:0,envelope:k({command:"open",cwd:t.cwd,ok:!0,data:r})}}catch(r){return {exitCode:1,envelope:k({command:"open",cwd:t.cwd,ok:false,error:{code:"open_target_failed",message:r instanceof Error?r.message:String(r)}})}}}async function tE(t,e,r){let n=await Mh(e,[Wh(t),...r]);return {...n,envelope:{...n.envelope,command:t}}}async function rE(t,e){try{let r=await ca(la(e),t.env);return {exitCode:r.ok?0:1,envelope:k({command:"invite",cwd:t.cwd,ok:r.ok,data:r,error:r.ok?void 0:{code:r.error,message:r.message},next_steps:r.next_steps})}}catch(r){let n=V(r,"invite_failed");return {exitCode:r instanceof Te?64:1,envelope:k({command:"invite",cwd:t.cwd,ok:false,error:{code:n,message:r instanceof Error?r.message:String(r)}})}}}async function nE(t,e){try{let r=Jh(e),n=await ba(t.env,r.orgSelector),i=await yn(n.organization.slug,t.env,"members",{preferDesktopApp:r.preferDesktopApp,forceWeb:r.forceWeb});return {exitCode:0,envelope:k({command:"team",cwd:t.cwd,ok:!0,data:r.open?i:{...n,open_target:i}})}}catch(r){let n=V(r,"team_failed");return {exitCode:n.startsWith("unknown_team_option")?64:1,envelope:k({command:"team",cwd:t.cwd,ok:false,error:{code:n,message:r instanceof Error?r.message:String(r)}})}}}async function Lh(t,e){let r=t.find(s=>s&&!["--web","--desktop-app","--no-open"].includes(s)),n=t.includes("--web"),i=t.includes("--desktop-app")&&!n;if(!r){let s=await gr(e);return s?qi(s.id,e.env,{preferDesktopApp:i,forceWeb:n}):oE(e.env)}if(r==="workspace"||r==="--workspace"){let s=await gr(e);if(!s)throw new Error("workspace_required");return qi(s.id,e.env,{preferDesktopApp:i,forceWeb:n})}if(r==="workspace-settings"||r==="--workspace-settings"){let s=await gr(e);if(!s)throw new Error("workspace_required");return Ch(s.id,e.env,"settings",n)}if(r==="agent-setup"||r==="agents"||r==="ai-tools"||r==="--agent-setup"){let s=await gr(e);if(!s)throw new Error("workspace_required");return Ch(s.id,e.env,"ai-tools",n)}if(r==="org"||r==="--org"){let s=await j(e.env);if(!s)throw new Error("org_required");return yn(s.slug,e.env,"home",{preferDesktopApp:i,forceWeb:n})}if(r==="team"||r==="--team")return Ca(e.env,"members",n,i);if(r==="billing"||r==="--billing"||r==="upgrade"||r==="--upgrade")return Ca(e.env,"billing",n,i);if(r==="settings"||r==="--settings")return Ca(e.env,"settings",n,i);if(r==="reactivate"||r==="--reactivate"){let s=await j(e.env);if(!s)throw new Error("org_required");return yn(s.slug,e.env,"reactivate",{preferDesktopApp:i,forceWeb:n})}throw new Error("invalid_open_target")}async function gr(t){let e=await Re(t.env);return Uh(e,t.cwd)??iE(e)}function iE(t){let e=t.find(r=>r.current);return e||(t.length===1?t[0]??null:null)}function Uh(t,e){let r=t.filter(n=>n.local_root_path?sE(n.local_root_path,e):false);return r.sort((n,i)=>(i.local_root_path?.length??0)-(n.local_root_path?.length??0)),r[0]??null}function sE(t,e){let r=resolve(t),n=resolve(e),i=relative(r,n);return i===""||!i.startsWith("..")&&!isAbsolute(i)}function oE(t){return {kind:"web",url:(t.PATHRULE_WEB_URL??"https://app.pathrule.io").replace(/\/$/,""),label:"Open Pathrule Web",reason:"preferred"}}async function Ca(t,e,r,n){let i=await j(t);if(!i)throw new Error("org_required");return yn(i.slug,t,e,{preferDesktopApp:n,forceWeb:r})}function Wh(t){return t==="team"?"team":t==="upgrade"?"upgrade":t==="reactivate"?"reactivate":"billing"}function Ia(t,e){return `${(e.PATHRULE_WEB_URL??"https://app.pathrule.io").replace(/\/$/,"")}/workspace/${encodeURIComponent(t)}`}function aE(t,e,r){let n=`${Ia(t,e)}/settings`;return r==="ai-tools"?`${n}/ai-tools`:n}function Ch(t,e,r,n=false){return {kind:"web",url:aE(t,e,r),label:r==="ai-tools"?"Open AI tools in Pathrule Web":"Open workspace settings in Pathrule Web",reason:n?"forced":"preferred"}}async function qi(t,e,r={}){return r.preferDesktopApp&&!r.forceWeb?{kind:"desktop-app",url:`pathrule://workspace/${encodeURIComponent(t)}`,label:"Open workspace in Pathrule Desktop",reason:"forced"}:!r.forceWeb&&await Oa(e,"workspace")?{kind:"desktop-app",url:`pathrule://workspace/${encodeURIComponent(t)}`,label:"Open workspace in Pathrule Desktop",reason:"preferred"}:{kind:"web",url:Ia(t,e),label:"Open workspace in Pathrule Web",reason:r.forceWeb?"forced":"preferred"}}async function yn(t,e,r,n={}){let i=r==="reactivate"?"billing":r,s={slug:t},o=r==="reactivate"?`${ee(s,e,"billing")}/reactivate`:ee(s,e,i),a=r==="billing"?"Open billing in Pathrule Web":r==="members"?"Open team in Pathrule Web":r==="settings"?"Open settings in Pathrule Web":r==="reactivate"?"Open billing reactivation in Pathrule Web":"Open organization in Pathrule Web";if(n.preferDesktopApp&&!n.forceWeb){let c=r==="members"?"team":r;return {kind:"desktop-app",url:`pathrule://org/${encodeURIComponent(t)}/${c}`,label:a.replace("Pathrule Web","Pathrule Desktop"),reason:"forced"}}let l=r==="members"?"team":r;return !n.forceWeb&&await Oa(e,`org:${l}`)?{kind:"desktop-app",url:`pathrule://org/${encodeURIComponent(t)}/${l}`,label:a.replace("Pathrule Web","Pathrule Desktop"),reason:"preferred"}:{kind:"web",url:o,label:a,reason:n.forceWeb?"forced":"preferred"}}async function Oa(t,e,r=Date.now()){let n=t.PATHRULE_DESKTOP_HEALTH?.trim().toLowerCase();if(n==="healthy"||n==="1"||n==="true")return true;if(n==="unhealthy"||n==="0"||n==="false")return false;let i;try{i=JSON.parse(await readFile(A(t).desktopFile,"utf8"));}catch{return false}if(i.healthy!==true||!i.updated_at)return false;let s=Date.parse(i.updated_at);return !(!Number.isFinite(s)||r-s>600*1e3||i.routes&&!i.routes.includes(e)&&!i.routes.includes("*"))}function Ea(t,e){return `${t} / ${e===-1?"unlimited":e}`}async function lE(t,e,r,n){try{let i=e[0]??"list";if(i==="add"){let a=Fh(t,e.slice(1)),l=await ae(qh(t),r.env);if(!l.allowed)return Vi(l,r.stderr,n),1;let c=await Hh(t,a,r),u=await bo(t,c,r.env);r.stdout.write(`${g("ok",n)} Created ${t}: ${u.item.title}
517
+ `),1}}async function Mh(t,e){try{let r=await Lh(e,t);return {exitCode:0,envelope:k({command:"open",cwd:t.cwd,ok:!0,data:r})}}catch(r){return {exitCode:1,envelope:k({command:"open",cwd:t.cwd,ok:false,error:{code:"open_target_failed",message:r instanceof Error?r.message:String(r)}})}}}async function tE(t,e,r){let n=await Mh(e,[Wh(t),...r]);return {...n,envelope:{...n.envelope,command:t}}}async function rE(t,e){try{let r=await ca(la(e),t.env);return {exitCode:r.ok?0:1,envelope:k({command:"invite",cwd:t.cwd,ok:r.ok,data:r,error:r.ok?void 0:{code:r.error,message:r.message},next_steps:r.next_steps})}}catch(r){let n=V(r,"invite_failed");return {exitCode:r instanceof Te?64:1,envelope:k({command:"invite",cwd:t.cwd,ok:false,error:{code:n,message:r instanceof Error?r.message:String(r)}})}}}async function nE(t,e){try{let r=Jh(e),n=await ba(t.env,r.orgSelector),i=await yn(n.organization.slug,t.env,"members",{preferDesktopApp:r.preferDesktopApp,forceWeb:r.forceWeb});return {exitCode:0,envelope:k({command:"team",cwd:t.cwd,ok:!0,data:r.open?i:{...n,open_target:i}})}}catch(r){let n=V(r,"team_failed");return {exitCode:n.startsWith("unknown_team_option")?64:1,envelope:k({command:"team",cwd:t.cwd,ok:false,error:{code:n,message:r instanceof Error?r.message:String(r)}})}}}async function Lh(t,e){let r=t.find(s=>s&&!["--web","--desktop-app","--no-open"].includes(s)),n=t.includes("--web"),i=t.includes("--desktop-app")&&!n;if(!r){let s=await gr(e);return s?qi(s.id,e.env,{preferDesktopApp:i,forceWeb:n}):oE(e.env)}if(r==="workspace"||r==="--workspace"){let s=await gr(e);if(!s)throw new Error("workspace_required");return qi(s.id,e.env,{preferDesktopApp:i,forceWeb:n})}if(r==="workspace-settings"||r==="--workspace-settings"){let s=await gr(e);if(!s)throw new Error("workspace_required");return Ch(s.id,e.env,"settings",n)}if(r==="agent-setup"||r==="agents"||r==="ai-tools"||r==="--agent-setup"){let s=await gr(e);if(!s)throw new Error("workspace_required");return Ch(s.id,e.env,"ai-tools",n)}if(r==="org"||r==="--org"){let s=await D(e.env);if(!s)throw new Error("org_required");return yn(s.slug,e.env,"home",{preferDesktopApp:i,forceWeb:n})}if(r==="team"||r==="--team")return Ca(e.env,"members",n,i);if(r==="billing"||r==="--billing"||r==="upgrade"||r==="--upgrade")return Ca(e.env,"billing",n,i);if(r==="settings"||r==="--settings")return Ca(e.env,"settings",n,i);if(r==="reactivate"||r==="--reactivate"){let s=await D(e.env);if(!s)throw new Error("org_required");return yn(s.slug,e.env,"reactivate",{preferDesktopApp:i,forceWeb:n})}throw new Error("invalid_open_target")}async function gr(t){let e=await Re(t.env);return Uh(e,t.cwd)??iE(e)}function iE(t){let e=t.find(r=>r.current);return e||(t.length===1?t[0]??null:null)}function Uh(t,e){let r=t.filter(n=>n.local_root_path?sE(n.local_root_path,e):false);return r.sort((n,i)=>(i.local_root_path?.length??0)-(n.local_root_path?.length??0)),r[0]??null}function sE(t,e){let r=resolve(t),n=resolve(e),i=relative(r,n);return i===""||!i.startsWith("..")&&!isAbsolute(i)}function oE(t){return {kind:"web",url:(t.PATHRULE_WEB_URL??"https://app.pathrule.io").replace(/\/$/,""),label:"Open Pathrule Web",reason:"preferred"}}async function Ca(t,e,r,n){let i=await D(t);if(!i)throw new Error("org_required");return yn(i.slug,t,e,{preferDesktopApp:n,forceWeb:r})}function Wh(t){return t==="team"?"team":t==="upgrade"?"upgrade":t==="reactivate"?"reactivate":"billing"}function Ia(t,e){return `${(e.PATHRULE_WEB_URL??"https://app.pathrule.io").replace(/\/$/,"")}/workspace/${encodeURIComponent(t)}`}function aE(t,e,r){let n=`${Ia(t,e)}/settings`;return r==="ai-tools"?`${n}/ai-tools`:n}function Ch(t,e,r,n=false){return {kind:"web",url:aE(t,e,r),label:r==="ai-tools"?"Open AI tools in Pathrule Web":"Open workspace settings in Pathrule Web",reason:n?"forced":"preferred"}}async function qi(t,e,r={}){return r.preferDesktopApp&&!r.forceWeb?{kind:"desktop-app",url:`pathrule://workspace/${encodeURIComponent(t)}`,label:"Open workspace in Pathrule Desktop",reason:"forced"}:!r.forceWeb&&await Oa(e,"workspace")?{kind:"desktop-app",url:`pathrule://workspace/${encodeURIComponent(t)}`,label:"Open workspace in Pathrule Desktop",reason:"preferred"}:{kind:"web",url:Ia(t,e),label:"Open workspace in Pathrule Web",reason:r.forceWeb?"forced":"preferred"}}async function yn(t,e,r,n={}){let i=r==="reactivate"?"billing":r,s={slug:t},o=r==="reactivate"?`${ee(s,e,"billing")}/reactivate`:ee(s,e,i),a=r==="billing"?"Open billing in Pathrule Web":r==="members"?"Open team in Pathrule Web":r==="settings"?"Open settings in Pathrule Web":r==="reactivate"?"Open billing reactivation in Pathrule Web":"Open organization in Pathrule Web";if(n.preferDesktopApp&&!n.forceWeb){let c=r==="members"?"team":r;return {kind:"desktop-app",url:`pathrule://org/${encodeURIComponent(t)}/${c}`,label:a.replace("Pathrule Web","Pathrule Desktop"),reason:"forced"}}let l=r==="members"?"team":r;return !n.forceWeb&&await Oa(e,`org:${l}`)?{kind:"desktop-app",url:`pathrule://org/${encodeURIComponent(t)}/${l}`,label:a.replace("Pathrule Web","Pathrule Desktop"),reason:"preferred"}:{kind:"web",url:o,label:a,reason:n.forceWeb?"forced":"preferred"}}async function Oa(t,e,r=Date.now()){let n=t.PATHRULE_DESKTOP_HEALTH?.trim().toLowerCase();if(n==="healthy"||n==="1"||n==="true")return true;if(n==="unhealthy"||n==="0"||n==="false")return false;let i;try{i=JSON.parse(await readFile(A(t).desktopFile,"utf8"));}catch{return false}if(i.healthy!==true||!i.updated_at)return false;let s=Date.parse(i.updated_at);return !(!Number.isFinite(s)||r-s>600*1e3||i.routes&&!i.routes.includes(e)&&!i.routes.includes("*"))}function Ea(t,e){return `${t} / ${e===-1?"unlimited":e}`}async function lE(t,e,r,n){try{let i=e[0]??"list";if(i==="add"){let a=Fh(t,e.slice(1)),l=await ae(qh(t),r.env);if(!l.allowed)return Vi(l,r.stderr,n),1;let c=await Hh(t,a,r),u=await bo(t,c,r.env);r.stdout.write(`${g("ok",n)} Created ${t}: ${u.item.title}
518
518
  `),r.stdout.write(`${g("info",n)} Path: ${u.item.path}
519
519
  `),a.open?await Fi({kind:t,title:u.item.title,totalResults:1,target:u.item.open_targets[0],runtime:r,mode:n}):r.stdout.write(`${g("info",n)} URL: ${u.item.url}
520
520
  `);for(let d of u.warnings)r.stdout.write(`${g("warn",n)} ${d.message??d.code}
@@ -525,11 +525,11 @@ ${t}
525
525
  `),64):(r.stderr.write(`${g("error",n)} ${i instanceof Error?i.message:String(i)}
526
526
  `),1)}}async function cE(t,e,r){try{let n=Ji(t),i=n.positionals.join(" ").trim();if(!i)return e.stderr.write(`${g("error",r)} Usage: pathrule search <query>
527
527
  `),64;let s=await mo(i,e.env,{...n,types:n.types});if(Bh(e.stdout,r,s),n.open&&s.length>0){let o=await Kh("result",s,e,r);if(!o)return 0;await Fi({kind:o.item.kind,title:o.item.title,totalResults:s.length,selectionIndex:o.index,target:await Pa(o.item,n,e.env),runtime:e,mode:r});}return 0}catch(n){return e.stderr.write(`${g("error",r)} ${n instanceof Error?n.message:String(n)}
528
- `),1}}async function uE(t,e,r){let n=t[0]??"list";try{if(n==="list"){let i=et(t.slice(1)),s=await gn(e.env,{includeInProgress:i.includeInProgress,limit:i.limit});if(wE(e.stdout,r,s),i.open&&s.length>0){let o=s[0];if(!o)return 0;await xh({target:ji(o,{forceWeb:i.forceWeb,preferDesktopApp:i.preferDesktopApp}),title:o.subjectTitle,totalResults:s.length,runtime:e,mode:r});}return 0}if(n==="claim"){let i=et(t.slice(1)),s=await ua(e.env,i.positionals[0]);return yE(e.stdout,r,s),0}if(n==="resolve"){let i=et(t.slice(1)),s=i.positionals[0];if(!s)return e.stderr.write(`${g("error",r)} Usage: pathrule refresh resolve <refresh-id> --status applied|rejected [--note "..."]
528
+ `),1}}async function uE(t,e,r){let n=t[0]??"list";try{if(n==="list"){let i=et(t.slice(1)),s=await gn(e.env,{includeInProgress:i.includeInProgress,limit:i.limit});if(wE(e.stdout,r,s),i.open&&s.length>0){let o=s[0];if(!o)return 0;await xh({target:Di(o,{forceWeb:i.forceWeb,preferDesktopApp:i.preferDesktopApp}),title:o.subjectTitle,totalResults:s.length,runtime:e,mode:r});}return 0}if(n==="claim"){let i=et(t.slice(1)),s=await ua(e.env,i.positionals[0]);return yE(e.stdout,r,s),0}if(n==="resolve"){let i=et(t.slice(1)),s=i.positionals[0];if(!s)return e.stderr.write(`${g("error",r)} Usage: pathrule refresh resolve <refresh-id> --status applied|rejected [--note "..."]
529
529
  `),64;if(i.status!=="applied"&&i.status!=="rejected")return e.stderr.write(`${g("error",r)} Usage: pathrule refresh resolve <refresh-id> --status applied|rejected [--note "..."]
530
530
  `),64;let o=await da(e.env,s,i.status,{note:i.note});return e.stdout.write(`${g("ok",r)} Refresh task marked ${o.status}.
531
531
  `),o.resolvedNote&&e.stdout.write(`${g("info",r)} Note: ${o.resolvedNote}
532
- `),0}if(n==="open"){let i=et(t.slice(1)),s=await pa(e.env,i.positionals[0]);return await xh({target:ji(s,{forceWeb:i.forceWeb,preferDesktopApp:i.preferDesktopApp}),title:s.subjectTitle,totalResults:1,runtime:e,mode:r}),0}return e.stderr.write(`${g("error",r)} Usage: pathrule refresh list|claim|resolve|open
532
+ `),0}if(n==="open"){let i=et(t.slice(1)),s=await pa(e.env,i.positionals[0]);return await xh({target:Di(s,{forceWeb:i.forceWeb,preferDesktopApp:i.preferDesktopApp}),title:s.subjectTitle,totalResults:1,runtime:e,mode:r}),0}return e.stderr.write(`${g("error",r)} Usage: pathrule refresh list|claim|resolve|open
533
533
  `),64}catch(i){return e.stderr.write(`${g("error",r)} ${i instanceof Error?i.message:String(i)}
534
534
  `),V(i,"refresh_failed")==="workspace_required",1}}async function dE(t,e){let r=await cn(t.env,t.cwd),n=sp(r);t.stdout.write(`Pathrule repair
535
535
  `),t.stdout.write(`${g(n.ok?"ok":"error",e)} ${n.headline}${r.error?`: ${r.error}`:""}
@@ -542,7 +542,7 @@ Next: ${n.next_command}
542
542
  `),64;let s=await Yo(e.env,{dryRun:!n});return s.dry_run?(e.stdout.write(`${g("warn",r)} Dry run: ${s.candidates.length} stale epoch cache dirs found
543
543
  `),e.stdout.write(`Run pathrule cache prune --yes to remove them.
544
544
  `)):e.stdout.write(`${g("ok",r)} Removed ${s.candidates.filter(o=>o.removed).length} stale epoch cache dirs
545
- `),0}async function hE(t,e,r){try{let n=r[0]??"list";if(n==="add"){let o=Fh(t,r.slice(1)),a=await ae(qh(t),e.env);if(!a.allowed){let u=ar(a);return {exitCode:1,envelope:k({command:`${t} add`,cwd:e.cwd,ok:!1,error:{code:a.blocking_reason??"preflight_blocked",message:u.summary,remediation:Ki(u)}})}}let l=await Hh(t,o,e),c=await bo(t,l,e.env);return {exitCode:0,envelope:k({command:`${t} add`,cwd:e.cwd,ok:!0,data:{...c,open_target:c.item.open_targets[0]??null}})}}let i=Ji(r.slice(1)),s=n==="read"?await _o(t,$a(i.positionals[0],`${t}_selector_required`),e.env):await en(t,e.env,i);return {exitCode:0,envelope:k({command:t,cwd:e.cwd,ok:!0,data:s})}}catch(n){return {exitCode:n instanceof X?64:1,envelope:k({command:r[0]==="add"?`${t} add`:t,cwd:e.cwd,ok:false,error:{code:V(n,"content_command_failed"),message:n instanceof Error?n.message:String(n)}})}}}async function fE(t,e){try{let r=Ji(e),n=$a(r.positionals.join(" ").trim(),"search_query_required"),i=await mo(n,t.env,r);return {exitCode:0,envelope:k({command:"search",cwd:t.cwd,ok:!0,data:i})}}catch(r){return {exitCode:1,envelope:k({command:"search",cwd:t.cwd,ok:false,error:{code:"search_failed",message:r instanceof Error?r.message:String(r)}})}}}async function gE(t,e){let r=e[0]??"list";try{if(r==="list"){let n=et(e.slice(1)),i=await gn(t.env,{includeInProgress:n.includeInProgress,limit:n.limit});return {exitCode:0,envelope:k({command:"refresh list",cwd:t.cwd,ok:!0,data:i})}}if(r==="claim"){let n=et(e.slice(1)),i=await ua(t.env,n.positionals[0]);return {exitCode:0,envelope:k({command:"refresh claim",cwd:t.cwd,ok:!0,data:i})}}if(r==="resolve"){let n=et(e.slice(1)),i=$a(n.positionals[0],"refresh_id_required");if(n.status!=="applied"&&n.status!=="rejected")throw new Error("refresh_status_required");let s=await da(t.env,i,n.status,{note:n.note});return {exitCode:0,envelope:k({command:"refresh resolve",cwd:t.cwd,ok:!0,data:s})}}if(r==="open"){let n=et(e.slice(1)),i=await pa(t.env,n.positionals[0]),s={refresh:i,open_target:ji(i,{forceWeb:n.forceWeb,preferDesktopApp:n.preferDesktopApp})};return {exitCode:0,envelope:k({command:"refresh open",cwd:t.cwd,ok:!0,data:s})}}return {exitCode:64,envelope:k({command:"refresh",cwd:t.cwd,ok:!1,error:{code:"usage",message:"Usage: pathrule refresh list|claim|resolve|open"}})}}catch(n){let i=V(n,"refresh_failed");return {exitCode:i==="refresh_id_required"||i==="refresh_status_required"?64:1,envelope:k({command:r==="list"?"refresh list":`refresh ${r}`,cwd:t.cwd,ok:false,error:{code:i,message:n instanceof Error?n.message:String(n),remediation:i==="workspace_required"?[{label:"Select a workspace",command:"pathrule workspace use <name-or-id>"}]:void 0}})}}}async function mE(t){let e=await cn(t.env,t.cwd);return {exitCode:e.ok?0:1,envelope:k({command:"repair",cwd:t.cwd,ok:e.ok,data:e.ok?e:void 0,error:e.ok?void 0:{code:"repair_failed",message:e.error??"Repair incomplete"}})}}async function _E(t,e,r){if((e[0]??"prune")!=="prune")return {exitCode:64,envelope:k({command:"cache",cwd:t.cwd,ok:false,error:{code:"usage",message:"Usage: pathrule cache prune [--yes]"}})};let i=await Yo(t.env,{dryRun:!r});return {exitCode:0,envelope:k({command:"cache",cwd:t.cwd,ok:true,data:i})}}function Bh(t,e,r){if(r.length===0){t.write(`${g("warn",e)} No content found.
545
+ `),0}async function hE(t,e,r){try{let n=r[0]??"list";if(n==="add"){let o=Fh(t,r.slice(1)),a=await ae(qh(t),e.env);if(!a.allowed){let u=ar(a);return {exitCode:1,envelope:k({command:`${t} add`,cwd:e.cwd,ok:!1,error:{code:a.blocking_reason??"preflight_blocked",message:u.summary,remediation:Ki(u)}})}}let l=await Hh(t,o,e),c=await bo(t,l,e.env);return {exitCode:0,envelope:k({command:`${t} add`,cwd:e.cwd,ok:!0,data:{...c,open_target:c.item.open_targets[0]??null}})}}let i=Ji(r.slice(1)),s=n==="read"?await _o(t,$a(i.positionals[0],`${t}_selector_required`),e.env):await en(t,e.env,i);return {exitCode:0,envelope:k({command:t,cwd:e.cwd,ok:!0,data:s})}}catch(n){return {exitCode:n instanceof X?64:1,envelope:k({command:r[0]==="add"?`${t} add`:t,cwd:e.cwd,ok:false,error:{code:V(n,"content_command_failed"),message:n instanceof Error?n.message:String(n)}})}}}async function fE(t,e){try{let r=Ji(e),n=$a(r.positionals.join(" ").trim(),"search_query_required"),i=await mo(n,t.env,r);return {exitCode:0,envelope:k({command:"search",cwd:t.cwd,ok:!0,data:i})}}catch(r){return {exitCode:1,envelope:k({command:"search",cwd:t.cwd,ok:false,error:{code:"search_failed",message:r instanceof Error?r.message:String(r)}})}}}async function gE(t,e){let r=e[0]??"list";try{if(r==="list"){let n=et(e.slice(1)),i=await gn(t.env,{includeInProgress:n.includeInProgress,limit:n.limit});return {exitCode:0,envelope:k({command:"refresh list",cwd:t.cwd,ok:!0,data:i})}}if(r==="claim"){let n=et(e.slice(1)),i=await ua(t.env,n.positionals[0]);return {exitCode:0,envelope:k({command:"refresh claim",cwd:t.cwd,ok:!0,data:i})}}if(r==="resolve"){let n=et(e.slice(1)),i=$a(n.positionals[0],"refresh_id_required");if(n.status!=="applied"&&n.status!=="rejected")throw new Error("refresh_status_required");let s=await da(t.env,i,n.status,{note:n.note});return {exitCode:0,envelope:k({command:"refresh resolve",cwd:t.cwd,ok:!0,data:s})}}if(r==="open"){let n=et(e.slice(1)),i=await pa(t.env,n.positionals[0]),s={refresh:i,open_target:Di(i,{forceWeb:n.forceWeb,preferDesktopApp:n.preferDesktopApp})};return {exitCode:0,envelope:k({command:"refresh open",cwd:t.cwd,ok:!0,data:s})}}return {exitCode:64,envelope:k({command:"refresh",cwd:t.cwd,ok:!1,error:{code:"usage",message:"Usage: pathrule refresh list|claim|resolve|open"}})}}catch(n){let i=V(n,"refresh_failed");return {exitCode:i==="refresh_id_required"||i==="refresh_status_required"?64:1,envelope:k({command:r==="list"?"refresh list":`refresh ${r}`,cwd:t.cwd,ok:false,error:{code:i,message:n instanceof Error?n.message:String(n),remediation:i==="workspace_required"?[{label:"Select a workspace",command:"pathrule workspace use <name-or-id>"}]:void 0}})}}}async function mE(t){let e=await cn(t.env,t.cwd);return {exitCode:e.ok?0:1,envelope:k({command:"repair",cwd:t.cwd,ok:e.ok,data:e.ok?e:void 0,error:e.ok?void 0:{code:"repair_failed",message:e.error??"Repair incomplete"}})}}async function _E(t,e,r){if((e[0]??"prune")!=="prune")return {exitCode:64,envelope:k({command:"cache",cwd:t.cwd,ok:false,error:{code:"usage",message:"Usage: pathrule cache prune [--yes]"}})};let i=await Yo(t.env,{dryRun:!r});return {exitCode:0,envelope:k({command:"cache",cwd:t.cwd,ok:true,data:i})}}function Bh(t,e,r){if(r.length===0){t.write(`${g("warn",e)} No content found.
546
546
  `);return}for(let n of r)t.write([`${n.kind.padEnd(6)} ${n.title}`,` ${n.path??"/"} ${n.updated_at??""}`,n.preview?` ${n.preview}`:"",` ${n.url}`].filter(Boolean).join(`
547
547
  `)+`
548
548
  `);}function wE(t,e,r){if(r.length===0){t.write(`${g("warn",e)} No pending refresh tasks.
@@ -552,12 +552,12 @@ Next: ${n.next_command}
552
552
  ${r.brief.aiInstructions}`:"",r.brief.proposedPatch?.newBody?`
553
553
  Proposed patch: ${r.brief.proposedPatch.reasoning} (confidence ${r.brief.proposedPatch.confidence})`:"","",`Next: update the ${r.subjectType}, then run pathrule refresh resolve ${r.id} --status applied`,`URL: ${r.url}`].filter(s=>s!=="").join(`
554
554
  `)+`
555
- `);}function Ji(t){let e={open:false,print:false,forceWeb:false,preferDesktopApp:false,positionals:[]};for(let r=0;r<t.length;r+=1){let n=t[r];n==="--path"?e.path=t[++r]:n==="--limit"?e.limit=Number(t[++r]):n==="--type"?e.types=kE(t[++r]):n==="--open"?e.open=true:n==="--print"?e.print=true:n==="--web"?e.forceWeb=true:n==="--desktop-app"?e.preferDesktopApp=true:n?.startsWith("/")&&e.positionals.length===0&&!e.path?e.path=n:n&&e.positionals.push(n);}return e}function et(t){let e={includeInProgress:false,open:false,forceWeb:false,preferDesktopApp:false,positionals:[]};for(let r=0;r<t.length;r+=1){let n=t[r];if(n){if(n==="--all"||n==="--include-in-progress"){e.includeInProgress=true;continue}if(n==="--limit"){e.limit=Number(t[++r]);continue}if(n==="--open"){e.open=true;continue}if(n==="--web"){e.forceWeb=true;continue}if(n==="--desktop-app"){e.preferDesktopApp=true;continue}if(n==="--status"){let i=t[++r];(i==="applied"||i==="rejected")&&(e.status=i);continue}if(n==="--note"){e.note=t[++r]??"";continue}e.positionals.push(n);}}return e}function Fh(t,e){let r={allowDuplicate:false,open:false,positionals:[]};for(let n=0;n<e.length;n+=1){let i=e[n];if(i){if(i==="--path"){r.path=jt(e[++n],"--path","content_path_required");continue}if(i==="--title"){r.title=jt(e[++n],"--title",`${t}_title_required`);continue}if(i==="--name"){r.name=jt(e[++n],"--name",`${t}_name_required`);continue}if(i==="--description"){r.description=jt(e[++n],"--description","skill_description_required");continue}if(i==="--body"){r.body=jt(e[++n],"--body","content_body_required");continue}if(i==="--priority"){r.priority=jt(e[++n],"--priority","rule_priority_required");continue}if(i==="--scope"){r.scope=jt(e[++n],"--scope","rule_scope_required");continue}if(i==="--allow-duplicate"){r.allowDuplicate=true;continue}if(i==="--open"){r.open=true;continue}if(i?.startsWith("/")&&r.positionals.length===0&&!r.path){r.path=i;continue}if(i.startsWith("--"))throw new X("unknown_content_option",`Unknown ${t} option "${i}".`);r.positionals.push(i);}}if(t==="memory"?r.positionals.length>0&&!r.title&&(r.title=r.positionals.shift()):r.positionals.length>0&&!r.name&&(r.name=r.positionals.shift()),r.positionals.length>0)throw new X("unexpected_content_argument",`Unexpected extra argument "${r.positionals[0]}".`);return r}async function Hh(t,e,r){let n=e.path?.trim();if(!n)throw new X("content_path_required",Ui(t));if(t==="memory"){let s=e.title?.trim();if(!s)throw new X("memory_title_required",Ui(t));return {path:n,title:s,body:await Ra(r,t,{path:n,title:s,body:e.body??""}),allowDuplicate:e.allowDuplicate}}if(t==="rule"){let s=e.name?.trim();if(!s)throw new X("rule_name_required",Ui(t));return {path:n,name:s,body:await Ra(r,t,{path:n,name:s,body:e.body??"",priority:Eh(e.priority),scopeType:Rh(e.scope)}),priority:Eh(e.priority),scopeType:Rh(e.scope),allowDuplicate:e.allowDuplicate}}let i=e.name?.trim();if(!i)throw new X("skill_name_required",Ui(t));return {path:n,name:i,description:e.description?.trim()||null,body:await Ra(r,t,{path:n,name:i,description:e.description?.trim()||null,body:e.body??""})}}async function Ra(t,e,r){if("body"in r&&typeof r.body=="string"&&r.body.trim())return xa(r.body);if(!(t.stdinIsTTY??process.stdin.isTTY??true)){let a=t.readStdin?await t.readStdin():await SE();return xa(a)}let i=Uu(e,r),s=e==="skill"?"SKILL.md":`${e}.md`,o=t.editText?await t.editText(i,s):await CE(t,i,s);return xa(o)}function Eh(t){let e=t?.trim().toLowerCase()||"medium";if(e==="high"||e==="medium"||e==="low")return e;throw new X("invalid_rule_priority","Rule priority must be high, medium, or low.")}function Rh(t){let e=t?.trim().toLowerCase()||"project";if(e==="folder"||e==="file_type"||e==="project")return e;throw new X("invalid_rule_scope","Rule scope must be folder, file_type, or project.")}function jt(t,e,r){if(!t)throw new X(r,`${e} requires a value.`);return t}function xa(t){let e=t.replace(/\r\n/g,`
556
- `);if(!e.trim())throw new X("content_body_required","Content body is required. Pass --body, pipe stdin, or save content in your editor.");return e}function Ui(t){return t==="memory"?"Usage: pathrule memory add --path </node/path> --title <title> [--body <text>] [--allow-duplicate] [--open]":t==="rule"?"Usage: pathrule rule add --path </node/path> --name <name> [--body <text>] [--priority high|medium|low] [--scope project|folder|file_type] [--allow-duplicate] [--open]":"Usage: pathrule skill add --path </node/path> --name <name> [--description <text>] [--body <text>] [--open]"}function qh(t){return t==="memory"?"write_memory":t==="rule"?"write_rule":"write_skill"}function kE(t){if(!t)return [];let e=new Set(["memory","rule","skill"]);return t.split(",").map(r=>r.trim()).filter(r=>e.has(r))}function $a(t,e){if(!t)throw new Error(e);return t}async function bE(t,e,r,n){try{if(t==="current"){let s=await j(r.env);return s?(r.stdout.write(`${g("ok",n)} ${s.name} (${s.slug}) \u2014 ${s.role}
555
+ `);}function Ji(t){let e={open:false,print:false,forceWeb:false,preferDesktopApp:false,positionals:[]};for(let r=0;r<t.length;r+=1){let n=t[r];n==="--path"?e.path=t[++r]:n==="--limit"?e.limit=Number(t[++r]):n==="--type"?e.types=kE(t[++r]):n==="--open"?e.open=true:n==="--print"?e.print=true:n==="--web"?e.forceWeb=true:n==="--desktop-app"?e.preferDesktopApp=true:n?.startsWith("/")&&e.positionals.length===0&&!e.path?e.path=n:n&&e.positionals.push(n);}return e}function et(t){let e={includeInProgress:false,open:false,forceWeb:false,preferDesktopApp:false,positionals:[]};for(let r=0;r<t.length;r+=1){let n=t[r];if(n){if(n==="--all"||n==="--include-in-progress"){e.includeInProgress=true;continue}if(n==="--limit"){e.limit=Number(t[++r]);continue}if(n==="--open"){e.open=true;continue}if(n==="--web"){e.forceWeb=true;continue}if(n==="--desktop-app"){e.preferDesktopApp=true;continue}if(n==="--status"){let i=t[++r];(i==="applied"||i==="rejected")&&(e.status=i);continue}if(n==="--note"){e.note=t[++r]??"";continue}e.positionals.push(n);}}return e}function Fh(t,e){let r={allowDuplicate:false,open:false,positionals:[]};for(let n=0;n<e.length;n+=1){let i=e[n];if(i){if(i==="--path"){r.path=Dt(e[++n],"--path","content_path_required");continue}if(i==="--title"){r.title=Dt(e[++n],"--title",`${t}_title_required`);continue}if(i==="--name"){r.name=Dt(e[++n],"--name",`${t}_name_required`);continue}if(i==="--description"){r.description=Dt(e[++n],"--description","skill_description_required");continue}if(i==="--body"){r.body=Dt(e[++n],"--body","content_body_required");continue}if(i==="--priority"){r.priority=Dt(e[++n],"--priority","rule_priority_required");continue}if(i==="--scope"){r.scope=Dt(e[++n],"--scope","rule_scope_required");continue}if(i==="--allow-duplicate"){r.allowDuplicate=true;continue}if(i==="--open"){r.open=true;continue}if(i?.startsWith("/")&&r.positionals.length===0&&!r.path){r.path=i;continue}if(i.startsWith("--"))throw new X("unknown_content_option",`Unknown ${t} option "${i}".`);r.positionals.push(i);}}if(t==="memory"?r.positionals.length>0&&!r.title&&(r.title=r.positionals.shift()):r.positionals.length>0&&!r.name&&(r.name=r.positionals.shift()),r.positionals.length>0)throw new X("unexpected_content_argument",`Unexpected extra argument "${r.positionals[0]}".`);return r}async function Hh(t,e,r){let n=e.path?.trim();if(!n)throw new X("content_path_required",Ui(t));if(t==="memory"){let s=e.title?.trim();if(!s)throw new X("memory_title_required",Ui(t));return {path:n,title:s,body:await Ra(r,t,{path:n,title:s,body:e.body??""}),allowDuplicate:e.allowDuplicate}}if(t==="rule"){let s=e.name?.trim();if(!s)throw new X("rule_name_required",Ui(t));return {path:n,name:s,body:await Ra(r,t,{path:n,name:s,body:e.body??"",priority:Eh(e.priority),scopeType:Rh(e.scope)}),priority:Eh(e.priority),scopeType:Rh(e.scope),allowDuplicate:e.allowDuplicate}}let i=e.name?.trim();if(!i)throw new X("skill_name_required",Ui(t));return {path:n,name:i,description:e.description?.trim()||null,body:await Ra(r,t,{path:n,name:i,description:e.description?.trim()||null,body:e.body??""})}}async function Ra(t,e,r){if("body"in r&&typeof r.body=="string"&&r.body.trim())return xa(r.body);if(!(t.stdinIsTTY??process.stdin.isTTY??true)){let a=t.readStdin?await t.readStdin():await SE();return xa(a)}let i=Uu(e,r),s=e==="skill"?"SKILL.md":`${e}.md`,o=t.editText?await t.editText(i,s):await CE(t,i,s);return xa(o)}function Eh(t){let e=t?.trim().toLowerCase()||"medium";if(e==="high"||e==="medium"||e==="low")return e;throw new X("invalid_rule_priority","Rule priority must be high, medium, or low.")}function Rh(t){let e=t?.trim().toLowerCase()||"project";if(e==="folder"||e==="file_type"||e==="project")return e;throw new X("invalid_rule_scope","Rule scope must be folder, file_type, or project.")}function Dt(t,e,r){if(!t)throw new X(r,`${e} requires a value.`);return t}function xa(t){let e=t.replace(/\r\n/g,`
556
+ `);if(!e.trim())throw new X("content_body_required","Content body is required. Pass --body, pipe stdin, or save content in your editor.");return e}function Ui(t){return t==="memory"?"Usage: pathrule memory add --path </node/path> --title <title> [--body <text>] [--allow-duplicate] [--open]":t==="rule"?"Usage: pathrule rule add --path </node/path> --name <name> [--body <text>] [--priority high|medium|low] [--scope project|folder|file_type] [--allow-duplicate] [--open]":"Usage: pathrule skill add --path </node/path> --name <name> [--description <text>] [--body <text>] [--open]"}function qh(t){return t==="memory"?"write_memory":t==="rule"?"write_rule":"write_skill"}function kE(t){if(!t)return [];let e=new Set(["memory","rule","skill"]);return t.split(",").map(r=>r.trim()).filter(r=>e.has(r))}function $a(t,e){if(!t)throw new Error(e);return t}async function bE(t,e,r,n){try{if(t==="current"){let s=await D(r.env);return s?(r.stdout.write(`${g("ok",n)} ${s.name} (${s.slug}) \u2014 ${s.role}
557
557
  `),0):(r.stdout.write(`${g("warn",n)} No organizations found.
558
558
  `),1)}if(t==="use"){let s=e[0];if(!s)return r.stderr.write(`${g("error",n)} Usage: pathrule org use <slug-or-id>
559
559
  `),64;let o=await hi(s,r.env);return r.stdout.write(`${g("ok",n)} Current organization: ${o.name}
560
- `),0}if(t==="open"){let s=await j(r.env);if(!s)return r.stderr.write(`${g("error",n)} No current organization. Run pathrule org use <slug-or-id>.
560
+ `),0}if(t==="open"){let s=await D(r.env);if(!s)return r.stderr.write(`${g("error",n)} No current organization. Run pathrule org use <slug-or-id>.
561
561
  `),1;let o=zh(e[0]),a=ee(s,r.env,o);return n.interactive&&!n.noOpen?(await Fe(r,a),r.stdout.write(`${g("ok",n)} Opened ${a}
562
562
  `)):r.stdout.write(`${a}
563
563
  `),0}if(t!=="list")return r.stderr.write(`${g("error",n)} Unknown org command "${t}".