supascan 0.1.3 → 0.1.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/supascan.js +2 -1
- package/package.json +1 -1
package/dist/supascan.js
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
1
2
|
import{createRequire as $i}from"node:module";var qi=Object.create;var{getPrototypeOf:Ti,defineProperty:Sa,getOwnPropertyNames:Wi}=Object;var Oi=Object.prototype.hasOwnProperty;var Z1=(e,a,t)=>{t=e!=null?qi(Ti(e)):{};let d=a||!e||!e.__esModule?Sa(t,"default",{value:e,enumerable:!0}):t;for(let l of Wi(e))if(!Oi.call(d,l))Sa(d,l,{get:()=>e[l],enumerable:!0});return d};var f=(e,a)=>()=>(a||e((a={exports:{}}).exports,a),a.exports);var Na=(e,a)=>{for(var t in a)Sa(e,t,{get:a[t],enumerable:!0,configurable:!0,set:(d)=>a[t]=()=>d})};var Qa=(e,a)=>()=>(e&&(a=e(e=0)),a);var $=$i(import.meta.url);var v1=f((Ri)=>{class ka extends Error{constructor(e,a,t){super(t);Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name,this.code=a,this.exitCode=e,this.nestedError=void 0}}class Rt extends ka{constructor(e){super(1,"commander.invalidArgument",e);Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}}Ri.CommanderError=ka;Ri.InvalidArgumentError=Rt});var F1=f((Ci)=>{var{InvalidArgumentError:Ui}=v1();class Et{constructor(e,a){switch(this.description=a||"",this.variadic=!1,this.parseArg=void 0,this.defaultValue=void 0,this.defaultValueDescription=void 0,this.argChoices=void 0,e[0]){case"<":this.required=!0,this._name=e.slice(1,-1);break;case"[":this.required=!1,this._name=e.slice(1,-1);break;default:this.required=!0,this._name=e;break}if(this._name.endsWith("..."))this.variadic=!0,this._name=this._name.slice(0,-3)}name(){return this._name}_collectValue(e,a){if(a===this.defaultValue||!Array.isArray(a))return[e];return a.push(e),a}default(e,a){return this.defaultValue=e,this.defaultValueDescription=a,this}argParser(e){return this.parseArg=e,this}choices(e){return this.argChoices=e.slice(),this.parseArg=(a,t)=>{if(!this.argChoices.includes(a))throw new Ui(`Allowed choices are ${this.argChoices.join(", ")}.`);if(this.variadic)return this._collectValue(a,t);return a},this}argRequired(){return this.required=!0,this}argOptional(){return this.required=!1,this}}function Bi(e){let a=e.name()+(e.variadic===!0?"...":"");return e.required?"<"+a+">":"["+a+"]"}Ci.Argument=Et;Ci.humanReadableArgName=Bi});var Da=f((Li)=>{var{humanReadableArgName:ji}=F1();class _t{constructor(){this.helpWidth=void 0,this.minWidthToWrap=40,this.sortSubcommands=!1,this.sortOptions=!1,this.showGlobalOptions=!1}prepareContext(e){this.helpWidth=this.helpWidth??e.helpWidth??80}visibleCommands(e){let a=e.commands.filter((d)=>!d._hidden),t=e._getHelpCommand();if(t&&!t._hidden)a.push(t);if(this.sortSubcommands)a.sort((d,l)=>{return d.name().localeCompare(l.name())});return a}compareOptions(e,a){let t=(d)=>{return d.short?d.short.replace(/^-/,""):d.long.replace(/^--/,"")};return t(e).localeCompare(t(a))}visibleOptions(e){let a=e.options.filter((d)=>!d.hidden),t=e._getHelpOption();if(t&&!t.hidden){let d=t.short&&e._findOption(t.short),l=t.long&&e._findOption(t.long);if(!d&&!l)a.push(t);else if(t.long&&!l)a.push(e.createOption(t.long,t.description));else if(t.short&&!d)a.push(e.createOption(t.short,t.description))}if(this.sortOptions)a.sort(this.compareOptions);return a}visibleGlobalOptions(e){if(!this.showGlobalOptions)return[];let a=[];for(let t=e.parent;t;t=t.parent){let d=t.options.filter((l)=>!l.hidden);a.push(...d)}if(this.sortOptions)a.sort(this.compareOptions);return a}visibleArguments(e){if(e._argsDescription)e.registeredArguments.forEach((a)=>{a.description=a.description||e._argsDescription[a.name()]||""});if(e.registeredArguments.find((a)=>a.description))return e.registeredArguments;return[]}subcommandTerm(e){let a=e.registeredArguments.map((t)=>ji(t)).join(" ");return e._name+(e._aliases[0]?"|"+e._aliases[0]:"")+(e.options.length?" [options]":"")+(a?" "+a:"")}optionTerm(e){return e.flags}argumentTerm(e){return e.name()}longestSubcommandTermLength(e,a){return a.visibleCommands(e).reduce((t,d)=>{return Math.max(t,this.displayWidth(a.styleSubcommandTerm(a.subcommandTerm(d))))},0)}longestOptionTermLength(e,a){return a.visibleOptions(e).reduce((t,d)=>{return Math.max(t,this.displayWidth(a.styleOptionTerm(a.optionTerm(d))))},0)}longestGlobalOptionTermLength(e,a){return a.visibleGlobalOptions(e).reduce((t,d)=>{return Math.max(t,this.displayWidth(a.styleOptionTerm(a.optionTerm(d))))},0)}longestArgumentTermLength(e,a){return a.visibleArguments(e).reduce((t,d)=>{return Math.max(t,this.displayWidth(a.styleArgumentTerm(a.argumentTerm(d))))},0)}commandUsage(e){let a=e._name;if(e._aliases[0])a=a+"|"+e._aliases[0];let t="";for(let d=e.parent;d;d=d.parent)t=d.name()+" "+t;return t+a+" "+e.usage()}commandDescription(e){return e.description()}subcommandDescription(e){return e.summary()||e.description()}optionDescription(e){let a=[];if(e.argChoices)a.push(`choices: ${e.argChoices.map((t)=>JSON.stringify(t)).join(", ")}`);if(e.defaultValue!==void 0){if(e.required||e.optional||e.isBoolean()&&typeof e.defaultValue==="boolean")a.push(`default: ${e.defaultValueDescription||JSON.stringify(e.defaultValue)}`)}if(e.presetArg!==void 0&&e.optional)a.push(`preset: ${JSON.stringify(e.presetArg)}`);if(e.envVar!==void 0)a.push(`env: ${e.envVar}`);if(a.length>0){let t=`(${a.join(", ")})`;if(e.description)return`${e.description} ${t}`;return t}return e.description}argumentDescription(e){let a=[];if(e.argChoices)a.push(`choices: ${e.argChoices.map((t)=>JSON.stringify(t)).join(", ")}`);if(e.defaultValue!==void 0)a.push(`default: ${e.defaultValueDescription||JSON.stringify(e.defaultValue)}`);if(a.length>0){let t=`(${a.join(", ")})`;if(e.description)return`${e.description} ${t}`;return t}return e.description}formatItemList(e,a,t){if(a.length===0)return[];return[t.styleTitle(e),...a,""]}groupItems(e,a,t){let d=new Map;return e.forEach((l)=>{let i=t(l);if(!d.has(i))d.set(i,[])}),a.forEach((l)=>{let i=t(l);if(!d.has(i))d.set(i,[]);d.get(i).push(l)}),d}formatHelp(e,a){let t=a.padWidth(e,a),d=a.helpWidth??80;function l(u,m){return a.formatItem(u,t,m,a)}let i=[`${a.styleTitle("Usage:")} ${a.styleUsage(a.commandUsage(e))}`,""],n=a.commandDescription(e);if(n.length>0)i=i.concat([a.boxWrap(a.styleCommandDescription(n),d),""]);let p=a.visibleArguments(e).map((u)=>{return l(a.styleArgumentTerm(a.argumentTerm(u)),a.styleArgumentDescription(a.argumentDescription(u)))});if(i=i.concat(this.formatItemList("Arguments:",p,a)),this.groupItems(e.options,a.visibleOptions(e),(u)=>u.helpGroupHeading??"Options:").forEach((u,m)=>{let o=u.map((h)=>{return l(a.styleOptionTerm(a.optionTerm(h)),a.styleOptionDescription(a.optionDescription(h)))});i=i.concat(this.formatItemList(m,o,a))}),a.showGlobalOptions){let u=a.visibleGlobalOptions(e).map((m)=>{return l(a.styleOptionTerm(a.optionTerm(m)),a.styleOptionDescription(a.optionDescription(m)))});i=i.concat(this.formatItemList("Global Options:",u,a))}return this.groupItems(e.commands,a.visibleCommands(e),(u)=>u.helpGroup()||"Commands:").forEach((u,m)=>{let o=u.map((h)=>{return l(a.styleSubcommandTerm(a.subcommandTerm(h)),a.styleSubcommandDescription(a.subcommandDescription(h)))});i=i.concat(this.formatItemList(m,o,a))}),i.join(`
|
|
2
3
|
`)}displayWidth(e){return Ut(e).length}styleTitle(e){return e}styleUsage(e){return e.split(" ").map((a)=>{if(a==="[options]")return this.styleOptionText(a);if(a==="[command]")return this.styleSubcommandText(a);if(a[0]==="["||a[0]==="<")return this.styleArgumentText(a);return this.styleCommandText(a)}).join(" ")}styleCommandDescription(e){return this.styleDescriptionText(e)}styleOptionDescription(e){return this.styleDescriptionText(e)}styleSubcommandDescription(e){return this.styleDescriptionText(e)}styleArgumentDescription(e){return this.styleDescriptionText(e)}styleDescriptionText(e){return e}styleOptionTerm(e){return this.styleOptionText(e)}styleSubcommandTerm(e){return e.split(" ").map((a)=>{if(a==="[options]")return this.styleOptionText(a);if(a[0]==="["||a[0]==="<")return this.styleArgumentText(a);return this.styleSubcommandText(a)}).join(" ")}styleArgumentTerm(e){return this.styleArgumentText(e)}styleOptionText(e){return e}styleArgumentText(e){return e}styleSubcommandText(e){return e}styleCommandText(e){return e}padWidth(e,a){return Math.max(a.longestOptionTermLength(e,a),a.longestGlobalOptionTermLength(e,a),a.longestSubcommandTermLength(e,a),a.longestArgumentTermLength(e,a))}preformatted(e){return/\n[^\S\r\n]/.test(e)}formatItem(e,a,t,d){let i=" ".repeat(2);if(!t)return i+e;let n=e.padEnd(a+e.length-d.displayWidth(e)),p=2,s=(this.helpWidth??80)-a-p-2,u;if(s<this.minWidthToWrap||d.preformatted(t))u=t;else u=d.boxWrap(t,s).replace(/\n/g,`
|
|
3
4
|
`+" ".repeat(a+p));return i+n+" ".repeat(p)+u.replace(/\n/g,`
|
|
@@ -196,7 +197,7 @@ Request ID: ${r}`;if(s){let Z=`
|
|
|
196
197
|
Resources:`;for(let b of s){if(!b||typeof b!=="string")throw Error(`@supabase/auth-js: Invalid SIWE message field "resources". Every resource must be a valid string. Provided value: ${b}`);Z+=`
|
|
197
198
|
- ${b}`}v+=Z}return`${y}
|
|
198
199
|
${v}`}});var ni=f((li)=>{Object.defineProperty(li,"__esModule",{value:!0});li.WebAuthnUnknownError=li.WebAuthnError=void 0;li.isWebAuthnError=N8;li.identifyRegistrationError=Q8;li.identifyAuthenticationError=k8;var ti=qt();class B extends Error{constructor({message:e,code:a,cause:t,name:d}){var l;super(e,{cause:t});this.__isWebAuthnError=!0,this.name=(l=d!==null&&d!==void 0?d:t instanceof Error?t.name:void 0)!==null&&l!==void 0?l:"Unknown Error",this.code=a}}li.WebAuthnError=B;class di extends B{constructor(e,a){super({code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:a,message:e});this.name="WebAuthnUnknownError",this.originalError=a}}li.WebAuthnUnknownError=di;function N8(e){return typeof e==="object"&&e!==null&&"__isWebAuthnError"in e}function Q8({error:e,options:a}){var t,d,l;let{publicKey:i}=a;if(!i)throw Error("options was missing required publicKey property");if(e.name==="AbortError"){if(a.signal instanceof AbortSignal)return new B({message:"Registration ceremony was sent an abort signal",code:"ERROR_CEREMONY_ABORTED",cause:e})}else if(e.name==="ConstraintError"){if(((t=i.authenticatorSelection)===null||t===void 0?void 0:t.requireResidentKey)===!0)return new B({message:"Discoverable credentials were required but no available authenticator supported it",code:"ERROR_AUTHENTICATOR_MISSING_DISCOVERABLE_CREDENTIAL_SUPPORT",cause:e});else if(a.mediation==="conditional"&&((d=i.authenticatorSelection)===null||d===void 0?void 0:d.userVerification)==="required")return new B({message:"User verification was required during automatic registration but it could not be performed",code:"ERROR_AUTO_REGISTER_USER_VERIFICATION_FAILURE",cause:e});else if(((l=i.authenticatorSelection)===null||l===void 0?void 0:l.userVerification)==="required")return new B({message:"User verification was required but no available authenticator supported it",code:"ERROR_AUTHENTICATOR_MISSING_USER_VERIFICATION_SUPPORT",cause:e})}else if(e.name==="InvalidStateError")return new B({message:"The authenticator was previously registered",code:"ERROR_AUTHENTICATOR_PREVIOUSLY_REGISTERED",cause:e});else if(e.name==="NotAllowedError")return new B({message:e.message,code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:e});else if(e.name==="NotSupportedError"){if(i.pubKeyCredParams.filter((p)=>p.type==="public-key").length===0)return new B({message:'No entry in pubKeyCredParams was of type "public-key"',code:"ERROR_MALFORMED_PUBKEYCREDPARAMS",cause:e});return new B({message:"No available authenticator supported any of the specified pubKeyCredParams algorithms",code:"ERROR_AUTHENTICATOR_NO_SUPPORTED_PUBKEYCREDPARAMS_ALG",cause:e})}else if(e.name==="SecurityError"){let n=window.location.hostname;if(!(0,ti.isValidDomain)(n))return new B({message:`${window.location.hostname} is an invalid domain`,code:"ERROR_INVALID_DOMAIN",cause:e});else if(i.rp.id!==n)return new B({message:`The RP ID "${i.rp.id}" is invalid for this domain`,code:"ERROR_INVALID_RP_ID",cause:e})}else if(e.name==="TypeError"){if(i.user.id.byteLength<1||i.user.id.byteLength>64)return new B({message:"User ID was not between 1 and 64 characters",code:"ERROR_INVALID_USER_ID_LENGTH",cause:e})}else if(e.name==="UnknownError")return new B({message:"The authenticator was unable to process the specified options, or could not create a new credential",code:"ERROR_AUTHENTICATOR_GENERAL_ERROR",cause:e});return new B({message:"a Non-Webauthn related error has occurred",code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:e})}function k8({error:e,options:a}){let{publicKey:t}=a;if(!t)throw Error("options was missing required publicKey property");if(e.name==="AbortError"){if(a.signal instanceof AbortSignal)return new B({message:"Authentication ceremony was sent an abort signal",code:"ERROR_CEREMONY_ABORTED",cause:e})}else if(e.name==="NotAllowedError")return new B({message:e.message,code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:e});else if(e.name==="SecurityError"){let d=window.location.hostname;if(!(0,ti.isValidDomain)(d))return new B({message:`${window.location.hostname} is an invalid domain`,code:"ERROR_INVALID_DOMAIN",cause:e});else if(t.rpId!==d)return new B({message:`The RP ID "${t.rpId}" is invalid for this domain`,code:"ERROR_INVALID_RP_ID",cause:e})}else if(e.name==="UnknownError")return new B({message:"The authenticator was unable to process the specified options, or could not create a new assertion signature",code:"ERROR_AUTHENTICATOR_GENERAL_ERROR",cause:e});return new B({message:"a Non-Webauthn related error has occurred",code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:e})}});var qt=f((N)=>{var ri=N&&N.__rest||function(e,a){var t={};for(var d in e)if(Object.prototype.hasOwnProperty.call(e,d)&&a.indexOf(d)<0)t[d]=e[d];if(e!=null&&typeof Object.getOwnPropertySymbols==="function"){for(var l=0,d=Object.getOwnPropertySymbols(e);l<d.length;l++)if(a.indexOf(d[l])<0&&Object.prototype.propertyIsEnumerable.call(e,d[l]))t[d[l]]=e[d[l]]}return t};Object.defineProperty(N,"__esModule",{value:!0});N.WebAuthnApi=N.DEFAULT_REQUEST_OPTIONS=N.DEFAULT_CREATION_OPTIONS=N.webAuthnAbortService=N.WebAuthnAbortService=N.identifyAuthenticationError=N.identifyRegistrationError=N.isWebAuthnError=N.WebAuthnError=void 0;N.deserializeCredentialCreationOptions=W8;N.deserializeCredentialRequestOptions=O8;N.serializeCredentialCreationResponse=$8;N.serializeCredentialRequestResponse=R8;N.isValidDomain=E8;N.createCredential=si;N.getCredential=ui;N.mergeCredentialCreationOptions=mi;N.mergeCredentialRequestOptions=oi;var Xe=Za(),He=Pe(),T8=f1(),Se=ni();Object.defineProperty(N,"identifyAuthenticationError",{enumerable:!0,get:function(){return Se.identifyAuthenticationError}});Object.defineProperty(N,"identifyRegistrationError",{enumerable:!0,get:function(){return Se.identifyRegistrationError}});Object.defineProperty(N,"isWebAuthnError",{enumerable:!0,get:function(){return Se.isWebAuthnError}});Object.defineProperty(N,"WebAuthnError",{enumerable:!0,get:function(){return Se.WebAuthnError}});class Tt{createNewAbortSignal(){if(this.controller){let a=Error("Cancelling existing WebAuthn API call for new one");a.name="AbortError",this.controller.abort(a)}let e=new AbortController;return this.controller=e,e.signal}cancelCeremony(){if(this.controller){let e=Error("Manually cancelling existing WebAuthn API call");e.name="AbortError",this.controller.abort(e),this.controller=void 0}}}N.WebAuthnAbortService=Tt;N.webAuthnAbortService=new Tt;function W8(e){if(!e)throw Error("Credential creation options are required");if(typeof PublicKeyCredential<"u"&&"parseCreationOptionsFromJSON"in PublicKeyCredential&&typeof PublicKeyCredential.parseCreationOptionsFromJSON==="function")return PublicKeyCredential.parseCreationOptionsFromJSON(e);let{challenge:a,user:t,excludeCredentials:d}=e,l=ri(e,["challenge","user","excludeCredentials"]),i=(0,Xe.base64UrlToUint8Array)(a).buffer,n=Object.assign(Object.assign({},t),{id:(0,Xe.base64UrlToUint8Array)(t.id).buffer}),p=Object.assign(Object.assign({},l),{challenge:i,user:n});if(d&&d.length>0){p.excludeCredentials=Array(d.length);for(let r=0;r<d.length;r++){let s=d[r];p.excludeCredentials[r]=Object.assign(Object.assign({},s),{id:(0,Xe.base64UrlToUint8Array)(s.id).buffer,type:s.type||"public-key",transports:s.transports})}}return p}function O8(e){if(!e)throw Error("Credential request options are required");if(typeof PublicKeyCredential<"u"&&"parseRequestOptionsFromJSON"in PublicKeyCredential&&typeof PublicKeyCredential.parseRequestOptionsFromJSON==="function")return PublicKeyCredential.parseRequestOptionsFromJSON(e);let{challenge:a,allowCredentials:t}=e,d=ri(e,["challenge","allowCredentials"]),l=(0,Xe.base64UrlToUint8Array)(a).buffer,i=Object.assign(Object.assign({},d),{challenge:l});if(t&&t.length>0){i.allowCredentials=Array(t.length);for(let n=0;n<t.length;n++){let p=t[n];i.allowCredentials[n]=Object.assign(Object.assign({},p),{id:(0,Xe.base64UrlToUint8Array)(p.id).buffer,type:p.type||"public-key",transports:p.transports})}}return i}function $8(e){var a;if("toJSON"in e&&typeof e.toJSON==="function")return e.toJSON();let t=e;return{id:e.id,rawId:e.id,response:{attestationObject:(0,Xe.bytesToBase64URL)(new Uint8Array(e.response.attestationObject)),clientDataJSON:(0,Xe.bytesToBase64URL)(new Uint8Array(e.response.clientDataJSON))},type:"public-key",clientExtensionResults:e.getClientExtensionResults(),authenticatorAttachment:(a=t.authenticatorAttachment)!==null&&a!==void 0?a:void 0}}function R8(e){var a;if("toJSON"in e&&typeof e.toJSON==="function")return e.toJSON();let t=e,d=e.getClientExtensionResults(),l=e.response;return{id:e.id,rawId:e.id,response:{authenticatorData:(0,Xe.bytesToBase64URL)(new Uint8Array(l.authenticatorData)),clientDataJSON:(0,Xe.bytesToBase64URL)(new Uint8Array(l.clientDataJSON)),signature:(0,Xe.bytesToBase64URL)(new Uint8Array(l.signature)),userHandle:l.userHandle?(0,Xe.bytesToBase64URL)(new Uint8Array(l.userHandle)):void 0},type:"public-key",clientExtensionResults:d,authenticatorAttachment:(a=t.authenticatorAttachment)!==null&&a!==void 0?a:void 0}}function E8(e){return e==="localhost"||/^([a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,}$/i.test(e)}function pi(){var e,a;return!!((0,T8.isBrowser)()&&("PublicKeyCredential"in window)&&window.PublicKeyCredential&&("credentials"in navigator)&&typeof((e=navigator===null||navigator===void 0?void 0:navigator.credentials)===null||e===void 0?void 0:e.create)==="function"&&typeof((a=navigator===null||navigator===void 0?void 0:navigator.credentials)===null||a===void 0?void 0:a.get)==="function")}async function si(e){try{let a=await navigator.credentials.create(e);if(!a)return{data:null,error:new Se.WebAuthnUnknownError("Empty credential response",a)};if(!(a instanceof PublicKeyCredential))return{data:null,error:new Se.WebAuthnUnknownError("Browser returned unexpected credential type",a)};return{data:a,error:null}}catch(a){return{data:null,error:(0,Se.identifyRegistrationError)({error:a,options:e})}}}async function ui(e){try{let a=await navigator.credentials.get(e);if(!a)return{data:null,error:new Se.WebAuthnUnknownError("Empty credential response",a)};if(!(a instanceof PublicKeyCredential))return{data:null,error:new Se.WebAuthnUnknownError("Browser returned unexpected credential type",a)};return{data:a,error:null}}catch(a){return{data:null,error:(0,Se.identifyAuthenticationError)({error:a,options:e})}}}N.DEFAULT_CREATION_OPTIONS={hints:["security-key"],authenticatorSelection:{authenticatorAttachment:"cross-platform",requireResidentKey:!1,userVerification:"preferred",residentKey:"discouraged"},attestation:"none"};N.DEFAULT_REQUEST_OPTIONS={userVerification:"preferred",hints:["security-key"]};function ya(...e){let a=(l)=>l!==null&&typeof l==="object"&&!Array.isArray(l),t=(l)=>l instanceof ArrayBuffer||ArrayBuffer.isView(l),d={};for(let l of e){if(!l)continue;for(let i in l){let n=l[i];if(n===void 0)continue;if(Array.isArray(n))d[i]=n;else if(t(n))d[i]=n;else if(a(n)){let p=d[i];if(a(p))d[i]=ya(p,n);else d[i]=ya(n)}else d[i]=n}}return d}function mi(e,a){return ya(N.DEFAULT_CREATION_OPTIONS,e,a||{})}function oi(e,a){return ya(N.DEFAULT_REQUEST_OPTIONS,e,a||{})}class ci{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:a,friendlyName:t,signal:d},l){try{let{data:i,error:n}=await this.client.mfa.challenge({factorId:e,webauthn:a});if(!i)return{data:null,error:n};let p=d!==null&&d!==void 0?d:N.webAuthnAbortService.createNewAbortSignal();if(i.webauthn.type==="create"){let{user:r}=i.webauthn.credential_options.publicKey;if(!r.name)r.name=`${r.id}:${t}`;if(!r.displayName)r.displayName=r.name}switch(i.webauthn.type){case"create":{let r=mi(i.webauthn.credential_options.publicKey,l===null||l===void 0?void 0:l.create),{data:s,error:u}=await si({publicKey:r,signal:p});if(s)return{data:{factorId:e,challengeId:i.id,webauthn:{type:i.webauthn.type,credential_response:s}},error:null};return{data:null,error:u}}case"request":{let r=oi(i.webauthn.credential_options.publicKey,l===null||l===void 0?void 0:l.request),{data:s,error:u}=await ui(Object.assign(Object.assign({},i.webauthn.credential_options),{publicKey:r,signal:p}));if(s)return{data:{factorId:e,challengeId:i.id,webauthn:{type:i.webauthn.type,credential_response:s}},error:null};return{data:null,error:u}}}}catch(i){if((0,He.isAuthError)(i))return{data:null,error:i};return{data:null,error:new He.AuthUnknownError("Unexpected error in challenge",i)}}}async _verify({challengeId:e,factorId:a,webauthn:t}){return this.client.mfa.verify({factorId:a,challengeId:e,webauthn:t})}async _authenticate({factorId:e,webauthn:{rpId:a=typeof window<"u"?window.location.hostname:void 0,rpOrigins:t=typeof window<"u"?[window.location.origin]:void 0,signal:d}},l){if(!a)return{data:null,error:new He.AuthError("rpId is required for WebAuthn authentication")};try{if(!pi())return{data:null,error:new He.AuthUnknownError("Browser does not support WebAuthn",null)};let{data:i,error:n}=await this.challenge({factorId:e,webauthn:{rpId:a,rpOrigins:t},signal:d},{request:l});if(!i)return{data:null,error:n};let{webauthn:p}=i;return this._verify({factorId:e,challengeId:i.challengeId,webauthn:{type:p.type,rpId:a,rpOrigins:t,credential_response:p.credential_response}})}catch(i){if((0,He.isAuthError)(i))return{data:null,error:i};return{data:null,error:new He.AuthUnknownError("Unexpected error in authenticate",i)}}}async _register({friendlyName:e,rpId:a=typeof window<"u"?window.location.hostname:void 0,rpOrigins:t=typeof window<"u"?[window.location.origin]:void 0,signal:d},l){if(!a)return{data:null,error:new He.AuthError("rpId is required for WebAuthn registration")};try{if(!pi())return{data:null,error:new He.AuthUnknownError("Browser does not support WebAuthn",null)};let{data:i,error:n}=await this._enroll({friendlyName:e});if(!i)return await this.client.mfa.listFactors().then((s)=>{var u;return(u=s.data)===null||u===void 0?void 0:u.all.find((m)=>m.factor_type==="webauthn"&&m.friendly_name===e&&m.status!=="unverified")}).then((s)=>s?this.client.mfa.unenroll({factorId:s===null||s===void 0?void 0:s.id}):void 0),{data:null,error:n};let{data:p,error:r}=await this._challenge({factorId:i.id,friendlyName:i.friendly_name,webauthn:{rpId:a,rpOrigins:t},signal:d},{create:l});if(!p)return{data:null,error:r};return this._verify({factorId:i.id,challengeId:p.challengeId,webauthn:{rpId:a,rpOrigins:t,type:p.webauthn.type,credential_response:p.webauthn.credential_response}})}catch(i){if((0,He.isAuthError)(i))return{data:null,error:i};return{data:null,error:new He.AuthUnknownError("Unexpected error in register",i)}}}}N.WebAuthnApi=ci});var Wt=f((I1)=>{var _8=I1&&I1.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(I1,"__esModule",{value:!0});var U8=_8(Xa()),re=fa(),X=Pe(),g=Nt(),z=f1(),Yi=I2(),fi=xt(),B8=F2(),C8=gt(),hi=Za(),ga=ai(),C1=qt();(0,B8.polyfillGlobalThis)();var M8={url:re.GOTRUE_URL,storageKey:re.STORAGE_KEY,autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,headers:re.DEFAULT_HEADERS,flowType:"implicit",debug:!1,hasCustomAuthorizationHeader:!1};async function Zi(e,a,t){return await t()}var h1={};class M1{get jwks(){var e,a;return(a=(e=h1[this.storageKey])===null||e===void 0?void 0:e.jwks)!==null&&a!==void 0?a:{keys:[]}}set jwks(e){h1[this.storageKey]=Object.assign(Object.assign({},h1[this.storageKey]),{jwks:e})}get jwks_cached_at(){var e,a;return(a=(e=h1[this.storageKey])===null||e===void 0?void 0:e.cachedAt)!==null&&a!==void 0?a:Number.MIN_SAFE_INTEGER}set jwks_cached_at(e){h1[this.storageKey]=Object.assign(Object.assign({},h1[this.storageKey]),{cachedAt:e})}constructor(e){var a,t;if(this.userStorage=null,this.memoryStorage=null,this.stateChangeEmitters=new Map,this.autoRefreshTicker=null,this.visibilityChangedCallback=null,this.refreshingDeferred=null,this.initializePromise=null,this.detectSessionInUrl=!0,this.hasCustomAuthorizationHeader=!1,this.suppressGetSessionWarning=!1,this.lockAcquired=!1,this.pendingInLock=[],this.broadcastChannel=null,this.logger=console.log,this.instanceID=M1.nextInstanceID,M1.nextInstanceID+=1,this.instanceID>0&&(0,z.isBrowser)())console.warn("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.");let d=Object.assign(Object.assign({},M8),e);if(this.logDebugMessages=!!d.debug,typeof d.debug==="function")this.logger=d.debug;if(this.persistSession=d.persistSession,this.storageKey=d.storageKey,this.autoRefreshToken=d.autoRefreshToken,this.admin=new U8.default({url:d.url,headers:d.headers,fetch:d.fetch}),this.url=d.url,this.headers=d.headers,this.fetch=(0,z.resolveFetch)(d.fetch),this.lock=d.lock||Zi,this.detectSessionInUrl=d.detectSessionInUrl,this.flowType=d.flowType,this.hasCustomAuthorizationHeader=d.hasCustomAuthorizationHeader,d.lock)this.lock=d.lock;else if((0,z.isBrowser)()&&((a=globalThis===null||globalThis===void 0?void 0:globalThis.navigator)===null||a===void 0?void 0:a.locks))this.lock=fi.navigatorLock;else this.lock=Zi;if(!this.jwks)this.jwks={keys:[]},this.jwks_cached_at=Number.MIN_SAFE_INTEGER;if(this.mfa={verify:this._verify.bind(this),enroll:this._enroll.bind(this),unenroll:this._unenroll.bind(this),challenge:this._challenge.bind(this),listFactors:this._listFactors.bind(this),challengeAndVerify:this._challengeAndVerify.bind(this),getAuthenticatorAssuranceLevel:this._getAuthenticatorAssuranceLevel.bind(this),webauthn:new C1.WebAuthnApi(this)},this.persistSession){if(d.storage)this.storage=d.storage;else if((0,z.supportsLocalStorage)())this.storage=globalThis.localStorage;else this.memoryStorage={},this.storage=(0,Yi.memoryLocalStorageAdapter)(this.memoryStorage);if(d.userStorage)this.userStorage=d.userStorage}else this.memoryStorage={},this.storage=(0,Yi.memoryLocalStorageAdapter)(this.memoryStorage);if((0,z.isBrowser)()&&globalThis.BroadcastChannel&&this.persistSession&&this.storageKey){try{this.broadcastChannel=new globalThis.BroadcastChannel(this.storageKey)}catch(l){console.error("Failed to create a new BroadcastChannel, multi-tab state changes will not be available",l)}(t=this.broadcastChannel)===null||t===void 0||t.addEventListener("message",async(l)=>{this._debug("received broadcast notification from other tab or client",l),await this._notifyAllSubscribers(l.data.event,l.data.session,!1)})}this.initialize()}_debug(...e){if(this.logDebugMessages)this.logger(`GoTrueClient@${this.instanceID} (${C8.version}) ${new Date().toISOString()}`,...e);return this}async initialize(){if(this.initializePromise)return await this.initializePromise;return this.initializePromise=(async()=>{return await this._acquireLock(-1,async()=>{return await this._initialize()})})(),await this.initializePromise}async _initialize(){var e;try{let a=(0,z.parseParametersFromURL)(window.location.href),t="none";if(this._isImplicitGrantCallback(a))t="implicit";else if(await this._isPKCECallback(a))t="pkce";if((0,z.isBrowser)()&&this.detectSessionInUrl&&t!=="none"){let{data:d,error:l}=await this._getSessionFromURL(a,t);if(l){if(this._debug("#_initialize()","error detecting session from URL",l),(0,X.isAuthImplicitGrantRedirectError)(l)){let p=(e=l.details)===null||e===void 0?void 0:e.code;if(p==="identity_already_exists"||p==="identity_not_found"||p==="single_identity_not_deletable")return{error:l}}return await this._removeSession(),{error:l}}let{session:i,redirectType:n}=d;return this._debug("#_initialize()","detected session in URL",i,"redirect type",n),await this._saveSession(i),setTimeout(async()=>{if(n==="recovery")await this._notifyAllSubscribers("PASSWORD_RECOVERY",i);else await this._notifyAllSubscribers("SIGNED_IN",i)},0),{error:null}}return await this._recoverAndRefresh(),{error:null}}catch(a){if((0,X.isAuthError)(a))return{error:a};return{error:new X.AuthUnknownError("Unexpected error during initialization",a)}}finally{await this._handleVisibilityChange(),this._debug("#_initialize()","end")}}async signInAnonymously(e){var a,t,d;try{let l=await(0,g._request)(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{data:(t=(a=e===null||e===void 0?void 0:e.options)===null||a===void 0?void 0:a.data)!==null&&t!==void 0?t:{},gotrue_meta_security:{captcha_token:(d=e===null||e===void 0?void 0:e.options)===null||d===void 0?void 0:d.captchaToken}},xform:g._sessionResponse}),{data:i,error:n}=l;if(n||!i)return{data:{user:null,session:null},error:n};let{session:p,user:r}=i;if(i.session)await this._saveSession(i.session),await this._notifyAllSubscribers("SIGNED_IN",p);return{data:{user:r,session:p},error:null}}catch(l){if((0,X.isAuthError)(l))return{data:{user:null,session:null},error:l};throw l}}async signUp(e){var a,t,d;try{let l;if("email"in e){let{email:s,password:u,options:m}=e,o=null,h=null;if(this.flowType==="pkce")[o,h]=await(0,z.getCodeChallengeAndMethod)(this.storage,this.storageKey);l=await(0,g._request)(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,redirectTo:m===null||m===void 0?void 0:m.emailRedirectTo,body:{email:s,password:u,data:(a=m===null||m===void 0?void 0:m.data)!==null&&a!==void 0?a:{},gotrue_meta_security:{captcha_token:m===null||m===void 0?void 0:m.captchaToken},code_challenge:o,code_challenge_method:h},xform:g._sessionResponse})}else if("phone"in e){let{phone:s,password:u,options:m}=e;l=await(0,g._request)(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{phone:s,password:u,data:(t=m===null||m===void 0?void 0:m.data)!==null&&t!==void 0?t:{},channel:(d=m===null||m===void 0?void 0:m.channel)!==null&&d!==void 0?d:"sms",gotrue_meta_security:{captcha_token:m===null||m===void 0?void 0:m.captchaToken}},xform:g._sessionResponse})}else throw new X.AuthInvalidCredentialsError("You must provide either an email or phone number and a password");let{data:i,error:n}=l;if(n||!i)return{data:{user:null,session:null},error:n};let{session:p,user:r}=i;if(i.session)await this._saveSession(i.session),await this._notifyAllSubscribers("SIGNED_IN",p);return{data:{user:r,session:p},error:null}}catch(l){if((0,X.isAuthError)(l))return{data:{user:null,session:null},error:l};throw l}}async signInWithPassword(e){try{let a;if("email"in e){let{email:l,password:i,options:n}=e;a=await(0,g._request)(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{email:l,password:i,gotrue_meta_security:{captcha_token:n===null||n===void 0?void 0:n.captchaToken}},xform:g._sessionResponsePassword})}else if("phone"in e){let{phone:l,password:i,options:n}=e;a=await(0,g._request)(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{phone:l,password:i,gotrue_meta_security:{captcha_token:n===null||n===void 0?void 0:n.captchaToken}},xform:g._sessionResponsePassword})}else throw new X.AuthInvalidCredentialsError("You must provide either an email or phone number and a password");let{data:t,error:d}=a;if(d)return{data:{user:null,session:null},error:d};else if(!t||!t.session||!t.user)return{data:{user:null,session:null},error:new X.AuthInvalidTokenResponseError};if(t.session)await this._saveSession(t.session),await this._notifyAllSubscribers("SIGNED_IN",t.session);return{data:Object.assign({user:t.user,session:t.session},t.weak_password?{weakPassword:t.weak_password}:null),error:d}}catch(a){if((0,X.isAuthError)(a))return{data:{user:null,session:null},error:a};throw a}}async signInWithOAuth(e){var a,t,d,l;return await this._handleProviderSignIn(e.provider,{redirectTo:(a=e.options)===null||a===void 0?void 0:a.redirectTo,scopes:(t=e.options)===null||t===void 0?void 0:t.scopes,queryParams:(d=e.options)===null||d===void 0?void 0:d.queryParams,skipBrowserRedirect:(l=e.options)===null||l===void 0?void 0:l.skipBrowserRedirect})}async exchangeCodeForSession(e){return await this.initializePromise,this._acquireLock(-1,async()=>{return this._exchangeCodeForSession(e)})}async signInWithWeb3(e){let{chain:a}=e;switch(a){case"ethereum":return await this.signInWithEthereum(e);case"solana":return await this.signInWithSolana(e);default:throw Error(`@supabase/auth-js: Unsupported chain "${a}"`)}}async signInWithEthereum(e){var a,t,d,l,i,n,p,r,s,u,m;let o,h;if("message"in e)o=e.message,h=e.signature;else{let{chain:c,wallet:Y,statement:y,options:v}=e,Z;if(!(0,z.isBrowser)()){if(typeof Y!=="object"||!(v===null||v===void 0?void 0:v.url))throw Error("@supabase/auth-js: Both wallet and url must be specified in non-browser environments.");Z=Y}else if(typeof Y==="object")Z=Y;else{let Ne=window;if("ethereum"in Ne&&typeof Ne.ethereum==="object"&&"request"in Ne.ethereum&&typeof Ne.ethereum.request==="function")Z=Ne.ethereum;else throw Error("@supabase/auth-js: No compatible Ethereum wallet interface on the window object (window.ethereum) detected. Make sure the user already has a wallet installed and connected for this app. Prefer passing the wallet interface object directly to signInWithWeb3({ chain: 'ethereum', wallet: resolvedUserWallet }) instead.")}let b=new URL((a=v===null||v===void 0?void 0:v.url)!==null&&a!==void 0?a:window.location.href),S=await Z.request({method:"eth_requestAccounts"}).then((Ne)=>Ne).catch(()=>{throw Error("@supabase/auth-js: Wallet method eth_requestAccounts is missing or invalid")});if(!S||S.length===0)throw Error("@supabase/auth-js: No accounts available. Please ensure the wallet is connected.");let H=(0,ga.getAddress)(S[0]),V=(t=v===null||v===void 0?void 0:v.signInWithEthereum)===null||t===void 0?void 0:t.chainId;if(!V){let Ne=await Z.request({method:"eth_chainId"});V=(0,ga.fromHex)(Ne)}let me={domain:b.host,address:H,statement:y,uri:b.href,version:"1",chainId:V,nonce:(d=v===null||v===void 0?void 0:v.signInWithEthereum)===null||d===void 0?void 0:d.nonce,issuedAt:(i=(l=v===null||v===void 0?void 0:v.signInWithEthereum)===null||l===void 0?void 0:l.issuedAt)!==null&&i!==void 0?i:new Date,expirationTime:(n=v===null||v===void 0?void 0:v.signInWithEthereum)===null||n===void 0?void 0:n.expirationTime,notBefore:(p=v===null||v===void 0?void 0:v.signInWithEthereum)===null||p===void 0?void 0:p.notBefore,requestId:(r=v===null||v===void 0?void 0:v.signInWithEthereum)===null||r===void 0?void 0:r.requestId,resources:(s=v===null||v===void 0?void 0:v.signInWithEthereum)===null||s===void 0?void 0:s.resources};o=(0,ga.createSiweMessage)(me),h=await Z.request({method:"personal_sign",params:[(0,ga.toHex)(o),H]})}try{let{data:c,error:Y}=await(0,g._request)(this.fetch,"POST",`${this.url}/token?grant_type=web3`,{headers:this.headers,body:Object.assign({chain:"ethereum",message:o,signature:h},((u=e.options)===null||u===void 0?void 0:u.captchaToken)?{gotrue_meta_security:{captcha_token:(m=e.options)===null||m===void 0?void 0:m.captchaToken}}:null),xform:g._sessionResponse});if(Y)throw Y;if(!c||!c.session||!c.user)return{data:{user:null,session:null},error:new X.AuthInvalidTokenResponseError};if(c.session)await this._saveSession(c.session),await this._notifyAllSubscribers("SIGNED_IN",c.session);return{data:Object.assign({},c),error:Y}}catch(c){if((0,X.isAuthError)(c))return{data:{user:null,session:null},error:c};throw c}}async signInWithSolana(e){var a,t,d,l,i,n,p,r,s,u,m,o;let h,c;if("message"in e)h=e.message,c=e.signature;else{let{chain:Y,wallet:y,statement:v,options:Z}=e,b;if(!(0,z.isBrowser)()){if(typeof y!=="object"||!(Z===null||Z===void 0?void 0:Z.url))throw Error("@supabase/auth-js: Both wallet and url must be specified in non-browser environments.");b=y}else if(typeof y==="object")b=y;else{let H=window;if("solana"in H&&typeof H.solana==="object"&&(("signIn"in H.solana)&&typeof H.solana.signIn==="function"||("signMessage"in H.solana)&&typeof H.solana.signMessage==="function"))b=H.solana;else throw Error("@supabase/auth-js: No compatible Solana wallet interface on the window object (window.solana) detected. Make sure the user already has a wallet installed and connected for this app. Prefer passing the wallet interface object directly to signInWithWeb3({ chain: 'solana', wallet: resolvedUserWallet }) instead.")}let S=new URL((a=Z===null||Z===void 0?void 0:Z.url)!==null&&a!==void 0?a:window.location.href);if("signIn"in b&&b.signIn){let H=await b.signIn(Object.assign(Object.assign(Object.assign({issuedAt:new Date().toISOString()},Z===null||Z===void 0?void 0:Z.signInWithSolana),{version:"1",domain:S.host,uri:S.href}),v?{statement:v}:null)),V;if(Array.isArray(H)&&H[0]&&typeof H[0]==="object")V=H[0];else if(H&&typeof H==="object"&&"signedMessage"in H&&"signature"in H)V=H;else throw Error("@supabase/auth-js: Wallet method signIn() returned unrecognized value");if("signedMessage"in V&&"signature"in V&&(typeof V.signedMessage==="string"||V.signedMessage instanceof Uint8Array)&&V.signature instanceof Uint8Array)h=typeof V.signedMessage==="string"?V.signedMessage:new TextDecoder().decode(V.signedMessage),c=V.signature;else throw Error("@supabase/auth-js: Wallet method signIn() API returned object without signedMessage and signature fields")}else{if(!("signMessage"in b)||typeof b.signMessage!=="function"||!("publicKey"in b)||typeof b!=="object"||!b.publicKey||!("toBase58"in b.publicKey)||typeof b.publicKey.toBase58!=="function")throw Error("@supabase/auth-js: Wallet does not have a compatible signMessage() and publicKey.toBase58() API");h=[`${S.host} wants you to sign in with your Solana account:`,b.publicKey.toBase58(),...v?["",v,""]:[""],"Version: 1",`URI: ${S.href}`,`Issued At: ${(d=(t=Z===null||Z===void 0?void 0:Z.signInWithSolana)===null||t===void 0?void 0:t.issuedAt)!==null&&d!==void 0?d:new Date().toISOString()}`,...((l=Z===null||Z===void 0?void 0:Z.signInWithSolana)===null||l===void 0?void 0:l.notBefore)?[`Not Before: ${Z.signInWithSolana.notBefore}`]:[],...((i=Z===null||Z===void 0?void 0:Z.signInWithSolana)===null||i===void 0?void 0:i.expirationTime)?[`Expiration Time: ${Z.signInWithSolana.expirationTime}`]:[],...((n=Z===null||Z===void 0?void 0:Z.signInWithSolana)===null||n===void 0?void 0:n.chainId)?[`Chain ID: ${Z.signInWithSolana.chainId}`]:[],...((p=Z===null||Z===void 0?void 0:Z.signInWithSolana)===null||p===void 0?void 0:p.nonce)?[`Nonce: ${Z.signInWithSolana.nonce}`]:[],...((r=Z===null||Z===void 0?void 0:Z.signInWithSolana)===null||r===void 0?void 0:r.requestId)?[`Request ID: ${Z.signInWithSolana.requestId}`]:[],...((u=(s=Z===null||Z===void 0?void 0:Z.signInWithSolana)===null||s===void 0?void 0:s.resources)===null||u===void 0?void 0:u.length)?["Resources",...Z.signInWithSolana.resources.map((V)=>`- ${V}`)]:[]].join(`
|
|
199
|
-
`);let H=await b.signMessage(new TextEncoder().encode(h),"utf8");if(!H||!(H instanceof Uint8Array))throw Error("@supabase/auth-js: Wallet signMessage() API returned an recognized value");c=H}}try{let{data:Y,error:y}=await(0,g._request)(this.fetch,"POST",`${this.url}/token?grant_type=web3`,{headers:this.headers,body:Object.assign({chain:"solana",message:h,signature:(0,hi.bytesToBase64URL)(c)},((m=e.options)===null||m===void 0?void 0:m.captchaToken)?{gotrue_meta_security:{captcha_token:(o=e.options)===null||o===void 0?void 0:o.captchaToken}}:null),xform:g._sessionResponse});if(y)throw y;if(!Y||!Y.session||!Y.user)return{data:{user:null,session:null},error:new X.AuthInvalidTokenResponseError};if(Y.session)await this._saveSession(Y.session),await this._notifyAllSubscribers("SIGNED_IN",Y.session);return{data:Object.assign({},Y),error:y}}catch(Y){if((0,X.isAuthError)(Y))return{data:{user:null,session:null},error:Y};throw Y}}async _exchangeCodeForSession(e){let a=await(0,z.getItemAsync)(this.storage,`${this.storageKey}-code-verifier`),[t,d]=(a!==null&&a!==void 0?a:"").split("/");try{let{data:l,error:i}=await(0,g._request)(this.fetch,"POST",`${this.url}/token?grant_type=pkce`,{headers:this.headers,body:{auth_code:e,code_verifier:t},xform:g._sessionResponse});if(await(0,z.removeItemAsync)(this.storage,`${this.storageKey}-code-verifier`),i)throw i;if(!l||!l.session||!l.user)return{data:{user:null,session:null,redirectType:null},error:new X.AuthInvalidTokenResponseError};if(l.session)await this._saveSession(l.session),await this._notifyAllSubscribers("SIGNED_IN",l.session);return{data:Object.assign(Object.assign({},l),{redirectType:d!==null&&d!==void 0?d:null}),error:i}}catch(l){if((0,X.isAuthError)(l))return{data:{user:null,session:null,redirectType:null},error:l};throw l}}async signInWithIdToken(e){try{let{options:a,provider:t,token:d,access_token:l,nonce:i}=e,n=await(0,g._request)(this.fetch,"POST",`${this.url}/token?grant_type=id_token`,{headers:this.headers,body:{provider:t,id_token:d,access_token:l,nonce:i,gotrue_meta_security:{captcha_token:a===null||a===void 0?void 0:a.captchaToken}},xform:g._sessionResponse}),{data:p,error:r}=n;if(r)return{data:{user:null,session:null},error:r};else if(!p||!p.session||!p.user)return{data:{user:null,session:null},error:new X.AuthInvalidTokenResponseError};if(p.session)await this._saveSession(p.session),await this._notifyAllSubscribers("SIGNED_IN",p.session);return{data:p,error:r}}catch(a){if((0,X.isAuthError)(a))return{data:{user:null,session:null},error:a};throw a}}async signInWithOtp(e){var a,t,d,l,i;try{if("email"in e){let{email:n,options:p}=e,r=null,s=null;if(this.flowType==="pkce")[r,s]=await(0,z.getCodeChallengeAndMethod)(this.storage,this.storageKey);let{error:u}=await(0,g._request)(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{email:n,data:(a=p===null||p===void 0?void 0:p.data)!==null&&a!==void 0?a:{},create_user:(t=p===null||p===void 0?void 0:p.shouldCreateUser)!==null&&t!==void 0?t:!0,gotrue_meta_security:{captcha_token:p===null||p===void 0?void 0:p.captchaToken},code_challenge:r,code_challenge_method:s},redirectTo:p===null||p===void 0?void 0:p.emailRedirectTo});return{data:{user:null,session:null},error:u}}if("phone"in e){let{phone:n,options:p}=e,{data:r,error:s}=await(0,g._request)(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{phone:n,data:(d=p===null||p===void 0?void 0:p.data)!==null&&d!==void 0?d:{},create_user:(l=p===null||p===void 0?void 0:p.shouldCreateUser)!==null&&l!==void 0?l:!0,gotrue_meta_security:{captcha_token:p===null||p===void 0?void 0:p.captchaToken},channel:(i=p===null||p===void 0?void 0:p.channel)!==null&&i!==void 0?i:"sms"}});return{data:{user:null,session:null,messageId:r===null||r===void 0?void 0:r.message_id},error:s}}throw new X.AuthInvalidCredentialsError("You must provide either an email or phone number.")}catch(n){if((0,X.isAuthError)(n))return{data:{user:null,session:null},error:n};throw n}}async verifyOtp(e){var a,t;try{let d=void 0,l=void 0;if("options"in e)d=(a=e.options)===null||a===void 0?void 0:a.redirectTo,l=(t=e.options)===null||t===void 0?void 0:t.captchaToken;let{data:i,error:n}=await(0,g._request)(this.fetch,"POST",`${this.url}/verify`,{headers:this.headers,body:Object.assign(Object.assign({},e),{gotrue_meta_security:{captcha_token:l}}),redirectTo:d,xform:g._sessionResponse});if(n)throw n;if(!i)throw Error("An error occurred on token verification.");let{session:p,user:r}=i;if(p===null||p===void 0?void 0:p.access_token)await this._saveSession(p),await this._notifyAllSubscribers(e.type=="recovery"?"PASSWORD_RECOVERY":"SIGNED_IN",p);return{data:{user:r,session:p},error:null}}catch(d){if((0,X.isAuthError)(d))return{data:{user:null,session:null},error:d};throw d}}async signInWithSSO(e){var a,t,d;try{let l=null,i=null;if(this.flowType==="pkce")[l,i]=await(0,z.getCodeChallengeAndMethod)(this.storage,this.storageKey);return await(0,g._request)(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:(t=(a=e.options)===null||a===void 0?void 0:a.redirectTo)!==null&&t!==void 0?t:void 0}),((d=e===null||e===void 0?void 0:e.options)===null||d===void 0?void 0:d.captchaToken)?{gotrue_meta_security:{captcha_token:e.options.captchaToken}}:null),{skip_http_redirect:!0,code_challenge:l,code_challenge_method:i}),headers:this.headers,xform:g._ssoResponse})}catch(l){if((0,X.isAuthError)(l))return{data:null,error:l};throw l}}async reauthenticate(){return await this.initializePromise,await this._acquireLock(-1,async()=>{return await this._reauthenticate()})}async _reauthenticate(){try{return await this._useSession(async(e)=>{let{data:{session:a},error:t}=e;if(t)throw t;if(!a)throw new X.AuthSessionMissingError;let{error:d}=await(0,g._request)(this.fetch,"GET",`${this.url}/reauthenticate`,{headers:this.headers,jwt:a.access_token});return{data:{user:null,session:null},error:d}})}catch(e){if((0,X.isAuthError)(e))return{data:{user:null,session:null},error:e};throw e}}async resend(e){try{let a=`${this.url}/resend`;if("email"in e){let{email:t,type:d,options:l}=e,{error:i}=await(0,g._request)(this.fetch,"POST",a,{headers:this.headers,body:{email:t,type:d,gotrue_meta_security:{captcha_token:l===null||l===void 0?void 0:l.captchaToken}},redirectTo:l===null||l===void 0?void 0:l.emailRedirectTo});return{data:{user:null,session:null},error:i}}else if("phone"in e){let{phone:t,type:d,options:l}=e,{data:i,error:n}=await(0,g._request)(this.fetch,"POST",a,{headers:this.headers,body:{phone:t,type:d,gotrue_meta_security:{captcha_token:l===null||l===void 0?void 0:l.captchaToken}}});return{data:{user:null,session:null,messageId:i===null||i===void 0?void 0:i.message_id},error:n}}throw new X.AuthInvalidCredentialsError("You must provide either an email or phone number and a type")}catch(a){if((0,X.isAuthError)(a))return{data:{user:null,session:null},error:a};throw a}}async getSession(){return await this.initializePromise,await this._acquireLock(-1,async()=>{return this._useSession(async(a)=>{return a})})}async _acquireLock(e,a){this._debug("#_acquireLock","begin",e);try{if(this.lockAcquired){let t=this.pendingInLock.length?this.pendingInLock[this.pendingInLock.length-1]:Promise.resolve(),d=(async()=>{return await t,await a()})();return this.pendingInLock.push((async()=>{try{await d}catch(l){}})()),d}return await this.lock(`lock:${this.storageKey}`,e,async()=>{this._debug("#_acquireLock","lock acquired for storage key",this.storageKey);try{this.lockAcquired=!0;let t=a();this.pendingInLock.push((async()=>{try{await t}catch(d){}})()),await t;while(this.pendingInLock.length){let d=[...this.pendingInLock];await Promise.all(d),this.pendingInLock.splice(0,d.length)}return await t}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 a=await this.__loadSession();return await e(a)}finally{this._debug("#_useSession","end")}}async __loadSession(){if(this._debug("#__loadSession()","begin"),!this.lockAcquired)this._debug("#__loadSession()","used outside of an acquired lock!",Error().stack);try{let e=null,a=await(0,z.getItemAsync)(this.storage,this.storageKey);if(this._debug("#getSession()","session from storage",a),a!==null)if(this._isValidSession(a))e=a;else this._debug("#getSession()","session from storage is not valid"),await this._removeSession();if(!e)return{data:{session:null},error:null};let t=e.expires_at?e.expires_at*1000-Date.now()<re.EXPIRY_MARGIN_MS:!1;if(this._debug("#__loadSession()",`session has${t?"":" not"} expired`,"expires_at",e.expires_at),!t){if(this.userStorage){let i=await(0,z.getItemAsync)(this.userStorage,this.storageKey+"-user");if(i===null||i===void 0?void 0:i.user)e.user=i.user;else e.user=(0,z.userNotAvailableProxy)()}if(this.storage.isServer&&e.user){let i=this.suppressGetSessionWarning;e=new Proxy(e,{get:(p,r,s)=>{if(!i&&r==="user")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."),i=!0,this.suppressGetSessionWarning=!0;return Reflect.get(p,r,s)}})}return{data:{session:e},error:null}}let{data:d,error:l}=await this._callRefreshToken(e.refresh_token);if(l)return{data:{session:null},error:l};return{data:{session:d},error:null}}finally{this._debug("#__loadSession()","end")}}async getUser(e){if(e)return await this._getUser(e);return await this.initializePromise,await this._acquireLock(-1,async()=>{return await this._getUser()})}async _getUser(e){try{if(e)return await(0,g._request)(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:e,xform:g._userResponse});return await this._useSession(async(a)=>{var t,d,l;let{data:i,error:n}=a;if(n)throw n;if(!((t=i.session)===null||t===void 0?void 0:t.access_token)&&!this.hasCustomAuthorizationHeader)return{data:{user:null},error:new X.AuthSessionMissingError};return await(0,g._request)(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:(l=(d=i.session)===null||d===void 0?void 0:d.access_token)!==null&&l!==void 0?l:void 0,xform:g._userResponse})})}catch(a){if((0,X.isAuthError)(a)){if((0,X.isAuthSessionMissingError)(a))await this._removeSession(),await(0,z.removeItemAsync)(this.storage,`${this.storageKey}-code-verifier`);return{data:{user:null},error:a}}throw a}}async updateUser(e,a={}){return await this.initializePromise,await this._acquireLock(-1,async()=>{return await this._updateUser(e,a)})}async _updateUser(e,a={}){try{return await this._useSession(async(t)=>{let{data:d,error:l}=t;if(l)throw l;if(!d.session)throw new X.AuthSessionMissingError;let i=d.session,n=null,p=null;if(this.flowType==="pkce"&&e.email!=null)[n,p]=await(0,z.getCodeChallengeAndMethod)(this.storage,this.storageKey);let{data:r,error:s}=await(0,g._request)(this.fetch,"PUT",`${this.url}/user`,{headers:this.headers,redirectTo:a===null||a===void 0?void 0:a.emailRedirectTo,body:Object.assign(Object.assign({},e),{code_challenge:n,code_challenge_method:p}),jwt:i.access_token,xform:g._userResponse});if(s)throw s;return i.user=r.user,await this._saveSession(i),await this._notifyAllSubscribers("USER_UPDATED",i),{data:{user:i.user},error:null}})}catch(t){if((0,X.isAuthError)(t))return{data:{user:null},error:t};throw t}}async setSession(e){return await this.initializePromise,await this._acquireLock(-1,async()=>{return await this._setSession(e)})}async _setSession(e){try{if(!e.access_token||!e.refresh_token)throw new X.AuthSessionMissingError;let a=Date.now()/1000,t=a,d=!0,l=null,{payload:i}=(0,z.decodeJWT)(e.access_token);if(i.exp)t=i.exp,d=t<=a;if(d){let{data:n,error:p}=await this._callRefreshToken(e.refresh_token);if(p)return{data:{user:null,session:null},error:p};if(!n)return{data:{user:null,session:null},error:null};l=n}else{let{data:n,error:p}=await this._getUser(e.access_token);if(p)throw p;l={access_token:e.access_token,refresh_token:e.refresh_token,user:n.user,token_type:"bearer",expires_in:t-a,expires_at:t},await this._saveSession(l),await this._notifyAllSubscribers("SIGNED_IN",l)}return{data:{user:l.user,session:l},error:null}}catch(a){if((0,X.isAuthError)(a))return{data:{session:null,user:null},error:a};throw a}}async refreshSession(e){return await this.initializePromise,await this._acquireLock(-1,async()=>{return await this._refreshSession(e)})}async _refreshSession(e){try{return await this._useSession(async(a)=>{var t;if(!e){let{data:i,error:n}=a;if(n)throw n;e=(t=i.session)!==null&&t!==void 0?t:void 0}if(!(e===null||e===void 0?void 0:e.refresh_token))throw new X.AuthSessionMissingError;let{data:d,error:l}=await this._callRefreshToken(e.refresh_token);if(l)return{data:{user:null,session:null},error:l};if(!d)return{data:{user:null,session:null},error:null};return{data:{user:d.user,session:d},error:null}})}catch(a){if((0,X.isAuthError)(a))return{data:{user:null,session:null},error:a};throw a}}async _getSessionFromURL(e,a){try{if(!(0,z.isBrowser)())throw new X.AuthImplicitGrantRedirectError("No browser detected.");if(e.error||e.error_description||e.error_code)throw new X.AuthImplicitGrantRedirectError(e.error_description||"Error in URL with unspecified error_description",{error:e.error||"unspecified_error",code:e.error_code||"unspecified_code"});switch(a){case"implicit":if(this.flowType==="pkce")throw new X.AuthPKCEGrantCodeExchangeError("Not a valid PKCE flow url.");break;case"pkce":if(this.flowType==="implicit")throw new X.AuthImplicitGrantRedirectError("Not a valid implicit grant flow url.");break;default:}if(a==="pkce"){if(this._debug("#_initialize()","begin","is PKCE flow",!0),!e.code)throw new X.AuthPKCEGrantCodeExchangeError("No code detected.");let{data:v,error:Z}=await this._exchangeCodeForSession(e.code);if(Z)throw Z;let b=new URL(window.location.href);return b.searchParams.delete("code"),window.history.replaceState(window.history.state,"",b.toString()),{data:{session:v.session,redirectType:null},error:null}}let{provider_token:t,provider_refresh_token:d,access_token:l,refresh_token:i,expires_in:n,expires_at:p,token_type:r}=e;if(!l||!n||!i||!r)throw new X.AuthImplicitGrantRedirectError("No session defined in URL");let s=Math.round(Date.now()/1000),u=parseInt(n),m=s+u;if(p)m=parseInt(p);let o=m-s;if(o*1000<=re.AUTO_REFRESH_TICK_DURATION_MS)console.warn(`@supabase/gotrue-js: Session as retrieved from URL expires in ${o}s, should have been closer to ${u}s`);let h=m-u;if(s-h>=120)console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued over 120s ago, URL could be stale",h,m,s);else if(s-h<0)console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued in the future? Check the device clock for skew",h,m,s);let{data:c,error:Y}=await this._getUser(l);if(Y)throw Y;let y={provider_token:t,provider_refresh_token:d,access_token:l,expires_in:u,expires_at:m,refresh_token:i,token_type:r,user:c.user};return window.location.hash="",this._debug("#_getSessionFromURL()","clearing window.location.hash"),{data:{session:y,redirectType:e.type},error:null}}catch(t){if((0,X.isAuthError)(t))return{data:{session:null,redirectType:null},error:t};throw t}}_isImplicitGrantCallback(e){return Boolean(e.access_token||e.error_description)}async _isPKCECallback(e){let a=await(0,z.getItemAsync)(this.storage,`${this.storageKey}-code-verifier`);return!!(e.code&&a)}async signOut(e={scope:"global"}){return await this.initializePromise,await this._acquireLock(-1,async()=>{return await this._signOut(e)})}async _signOut({scope:e}={scope:"global"}){return await this._useSession(async(a)=>{var t;let{data:d,error:l}=a;if(l)return{error:l};let i=(t=d.session)===null||t===void 0?void 0:t.access_token;if(i){let{error:n}=await this.admin.signOut(i,e);if(n){if(!((0,X.isAuthApiError)(n)&&(n.status===404||n.status===401||n.status===403)))return{error:n}}}if(e!=="others")await this._removeSession(),await(0,z.removeItemAsync)(this.storage,`${this.storageKey}-code-verifier`);return{error:null}})}onAuthStateChange(e){let a=(0,z.uuid)(),t={id:a,callback:e,unsubscribe:()=>{this._debug("#unsubscribe()","state change callback with id removed",a),this.stateChangeEmitters.delete(a)}};return this._debug("#onAuthStateChange()","registered callback with id",a),this.stateChangeEmitters.set(a,t),(async()=>{await this.initializePromise,await this._acquireLock(-1,async()=>{this._emitInitialSession(a)})})(),{data:{subscription:t}}}async _emitInitialSession(e){return await this._useSession(async(a)=>{var t,d;try{let{data:{session:l},error:i}=a;if(i)throw i;await((t=this.stateChangeEmitters.get(e))===null||t===void 0?void 0:t.callback("INITIAL_SESSION",l)),this._debug("INITIAL_SESSION","callback id",e,"session",l)}catch(l){await((d=this.stateChangeEmitters.get(e))===null||d===void 0?void 0:d.callback("INITIAL_SESSION",null)),this._debug("INITIAL_SESSION","callback id",e,"error",l),console.error(l)}})}async resetPasswordForEmail(e,a={}){let t=null,d=null;if(this.flowType==="pkce")[t,d]=await(0,z.getCodeChallengeAndMethod)(this.storage,this.storageKey,!0);try{return await(0,g._request)(this.fetch,"POST",`${this.url}/recover`,{body:{email:e,code_challenge:t,code_challenge_method:d,gotrue_meta_security:{captcha_token:a.captchaToken}},headers:this.headers,redirectTo:a.redirectTo})}catch(l){if((0,X.isAuthError)(l))return{data:null,error:l};throw l}}async getUserIdentities(){var e;try{let{data:a,error:t}=await this.getUser();if(t)throw t;return{data:{identities:(e=a.user.identities)!==null&&e!==void 0?e:[]},error:null}}catch(a){if((0,X.isAuthError)(a))return{data:null,error:a};throw a}}async linkIdentity(e){if("token"in e)return this.linkIdentityIdToken(e);return this.linkIdentityOAuth(e)}async linkIdentityOAuth(e){var a;try{let{data:t,error:d}=await this._useSession(async(l)=>{var i,n,p,r,s;let{data:u,error:m}=l;if(m)throw m;let o=await this._getUrlForProvider(`${this.url}/user/identities/authorize`,e.provider,{redirectTo:(i=e.options)===null||i===void 0?void 0:i.redirectTo,scopes:(n=e.options)===null||n===void 0?void 0:n.scopes,queryParams:(p=e.options)===null||p===void 0?void 0:p.queryParams,skipBrowserRedirect:!0});return await(0,g._request)(this.fetch,"GET",o,{headers:this.headers,jwt:(s=(r=u.session)===null||r===void 0?void 0:r.access_token)!==null&&s!==void 0?s:void 0})});if(d)throw d;if((0,z.isBrowser)()&&!((a=e.options)===null||a===void 0?void 0:a.skipBrowserRedirect))window.location.assign(t===null||t===void 0?void 0:t.url);return{data:{provider:e.provider,url:t===null||t===void 0?void 0:t.url},error:null}}catch(t){if((0,X.isAuthError)(t))return{data:{provider:e.provider,url:null},error:t};throw t}}async linkIdentityIdToken(e){return await this._useSession(async(a)=>{var t;try{let{error:d,data:{session:l}}=a;if(d)throw d;let{options:i,provider:n,token:p,access_token:r,nonce:s}=e,u=await(0,g._request)(this.fetch,"POST",`${this.url}/token?grant_type=id_token`,{headers:this.headers,jwt:(t=l===null||l===void 0?void 0:l.access_token)!==null&&t!==void 0?t:void 0,body:{provider:n,id_token:p,access_token:r,nonce:s,link_identity:!0,gotrue_meta_security:{captcha_token:i===null||i===void 0?void 0:i.captchaToken}},xform:g._sessionResponse}),{data:m,error:o}=u;if(o)return{data:{user:null,session:null},error:o};else if(!m||!m.session||!m.user)return{data:{user:null,session:null},error:new X.AuthInvalidTokenResponseError};if(m.session)await this._saveSession(m.session),await this._notifyAllSubscribers("USER_UPDATED",m.session);return{data:m,error:o}}catch(d){if((0,X.isAuthError)(d))return{data:{user:null,session:null},error:d};throw d}})}async unlinkIdentity(e){try{return await this._useSession(async(a)=>{var t,d;let{data:l,error:i}=a;if(i)throw i;return await(0,g._request)(this.fetch,"DELETE",`${this.url}/user/identities/${e.identity_id}`,{headers:this.headers,jwt:(d=(t=l.session)===null||t===void 0?void 0:t.access_token)!==null&&d!==void 0?d:void 0})})}catch(a){if((0,X.isAuthError)(a))return{data:null,error:a};throw a}}async _refreshAccessToken(e){let a=`#_refreshAccessToken(${e.substring(0,5)}...)`;this._debug(a,"begin");try{let t=Date.now();return await(0,z.retryable)(async(d)=>{if(d>0)await(0,z.sleep)(200*Math.pow(2,d-1));return this._debug(a,"refreshing attempt",d),await(0,g._request)(this.fetch,"POST",`${this.url}/token?grant_type=refresh_token`,{body:{refresh_token:e},headers:this.headers,xform:g._sessionResponse})},(d,l)=>{let i=200*Math.pow(2,d);return l&&(0,X.isAuthRetryableFetchError)(l)&&Date.now()+i-t<re.AUTO_REFRESH_TICK_DURATION_MS})}catch(t){if(this._debug(a,"error",t),(0,X.isAuthError)(t))return{data:{session:null,user:null},error:t};throw t}finally{this._debug(a,"end")}}_isValidSession(e){return typeof e==="object"&&e!==null&&"access_token"in e&&"refresh_token"in e&&"expires_at"in e}async _handleProviderSignIn(e,a){let t=await this._getUrlForProvider(`${this.url}/authorize`,e,{redirectTo:a.redirectTo,scopes:a.scopes,queryParams:a.queryParams});if(this._debug("#_handleProviderSignIn()","provider",e,"options",a,"url",t),(0,z.isBrowser)()&&!a.skipBrowserRedirect)window.location.assign(t);return{data:{provider:e,url:t},error:null}}async _recoverAndRefresh(){var e,a;let t="#_recoverAndRefresh()";this._debug("#_recoverAndRefresh()","begin");try{let d=await(0,z.getItemAsync)(this.storage,this.storageKey);if(d&&this.userStorage){let i=await(0,z.getItemAsync)(this.userStorage,this.storageKey+"-user");if(!this.storage.isServer&&Object.is(this.storage,this.userStorage)&&!i)i={user:d.user},await(0,z.setItemAsync)(this.userStorage,this.storageKey+"-user",i);d.user=(e=i===null||i===void 0?void 0:i.user)!==null&&e!==void 0?e:(0,z.userNotAvailableProxy)()}else if(d&&!d.user){if(!d.user){let i=await(0,z.getItemAsync)(this.storage,this.storageKey+"-user");if(i&&(i===null||i===void 0?void 0:i.user))d.user=i.user,await(0,z.removeItemAsync)(this.storage,this.storageKey+"-user"),await(0,z.setItemAsync)(this.storage,this.storageKey,d);else d.user=(0,z.userNotAvailableProxy)()}}if(this._debug("#_recoverAndRefresh()","session from storage",d),!this._isValidSession(d)){if(this._debug("#_recoverAndRefresh()","session is not valid"),d!==null)await this._removeSession();return}let l=((a=d.expires_at)!==null&&a!==void 0?a:1/0)*1000-Date.now()<re.EXPIRY_MARGIN_MS;if(this._debug("#_recoverAndRefresh()",`session has${l?"":" not"} expired with margin of ${re.EXPIRY_MARGIN_MS}s`),l){if(this.autoRefreshToken&&d.refresh_token){let{error:i}=await this._callRefreshToken(d.refresh_token);if(i){if(console.error(i),!(0,X.isAuthRetryableFetchError)(i))this._debug("#_recoverAndRefresh()","refresh failed with a non-retryable error, removing the session",i),await this._removeSession()}}}else if(d.user&&d.user.__isUserNotAvailableProxy===!0)try{let{data:i,error:n}=await this._getUser(d.access_token);if(!n&&(i===null||i===void 0?void 0:i.user))d.user=i.user,await this._saveSession(d),await this._notifyAllSubscribers("SIGNED_IN",d);else this._debug("#_recoverAndRefresh()","could not get user data, skipping SIGNED_IN notification")}catch(i){console.error("Error getting user data:",i),this._debug("#_recoverAndRefresh()","error getting user data, skipping SIGNED_IN notification",i)}else await this._notifyAllSubscribers("SIGNED_IN",d)}catch(d){this._debug("#_recoverAndRefresh()","error",d),console.error(d);return}finally{this._debug("#_recoverAndRefresh()","end")}}async _callRefreshToken(e){var a,t;if(!e)throw new X.AuthSessionMissingError;if(this.refreshingDeferred)return this.refreshingDeferred.promise;let d=`#_callRefreshToken(${e.substring(0,5)}...)`;this._debug(d,"begin");try{this.refreshingDeferred=new z.Deferred;let{data:l,error:i}=await this._refreshAccessToken(e);if(i)throw i;if(!l.session)throw new X.AuthSessionMissingError;await this._saveSession(l.session),await this._notifyAllSubscribers("TOKEN_REFRESHED",l.session);let n={data:l.session,error:null};return this.refreshingDeferred.resolve(n),n}catch(l){if(this._debug(d,"error",l),(0,X.isAuthError)(l)){let i={data:null,error:l};if(!(0,X.isAuthRetryableFetchError)(l))await this._removeSession();return(a=this.refreshingDeferred)===null||a===void 0||a.resolve(i),i}throw(t=this.refreshingDeferred)===null||t===void 0||t.reject(l),l}finally{this.refreshingDeferred=null,this._debug(d,"end")}}async _notifyAllSubscribers(e,a,t=!0){let d=`#_notifyAllSubscribers(${e})`;this._debug(d,"begin",a,`broadcast = ${t}`);try{if(this.broadcastChannel&&t)this.broadcastChannel.postMessage({event:e,session:a});let l=[],i=Array.from(this.stateChangeEmitters.values()).map(async(n)=>{try{await n.callback(e,a)}catch(p){l.push(p)}});if(await Promise.all(i),l.length>0){for(let n=0;n<l.length;n+=1)console.error(l[n]);throw l[0]}}finally{this._debug(d,"end")}}async _saveSession(e){this._debug("#_saveSession()",e),this.suppressGetSessionWarning=!0;let a=Object.assign({},e),t=a.user&&a.user.__isUserNotAvailableProxy===!0;if(this.userStorage){if(!t&&a.user)await(0,z.setItemAsync)(this.userStorage,this.storageKey+"-user",{user:a.user});let d=Object.assign({},a);delete d.user;let l=(0,z.deepClone)(d);await(0,z.setItemAsync)(this.storage,this.storageKey,l)}else{let d=(0,z.deepClone)(a);await(0,z.setItemAsync)(this.storage,this.storageKey,d)}}async _removeSession(){if(this._debug("#_removeSession()"),await(0,z.removeItemAsync)(this.storage,this.storageKey),await(0,z.removeItemAsync)(this.storage,this.storageKey+"-code-verifier"),await(0,z.removeItemAsync)(this.storage,this.storageKey+"-user"),this.userStorage)await(0,z.removeItemAsync)(this.userStorage,this.storageKey+"-user");await this._notifyAllSubscribers("SIGNED_OUT",null)}_removeVisibilityChangedCallback(){this._debug("#_removeVisibilityChangedCallback()");let e=this.visibilityChangedCallback;this.visibilityChangedCallback=null;try{if(e&&(0,z.isBrowser)()&&(window===null||window===void 0?void 0:window.removeEventListener))window.removeEventListener("visibilitychange",e)}catch(a){console.error("removing visibilitychange callback failed",a)}}async _startAutoRefresh(){await this._stopAutoRefresh(),this._debug("#_startAutoRefresh()");let e=setInterval(()=>this._autoRefreshTokenTick(),re.AUTO_REFRESH_TICK_DURATION_MS);if(this.autoRefreshTicker=e,e&&typeof e==="object"&&typeof e.unref==="function")e.unref();else if(typeof Deno<"u"&&typeof Deno.unrefTimer==="function")Deno.unrefTimer(e);setTimeout(async()=>{await this.initializePromise,await this._autoRefreshTokenTick()},0)}async _stopAutoRefresh(){this._debug("#_stopAutoRefresh()");let e=this.autoRefreshTicker;if(this.autoRefreshTicker=null,e)clearInterval(e)}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(a)=>{let{data:{session:t}}=a;if(!t||!t.refresh_token||!t.expires_at){this._debug("#_autoRefreshTokenTick()","no session");return}let d=Math.floor((t.expires_at*1000-e)/re.AUTO_REFRESH_TICK_DURATION_MS);if(this._debug("#_autoRefreshTokenTick()",`access token expires in ${d} ticks, a tick lasts ${re.AUTO_REFRESH_TICK_DURATION_MS}ms, refresh threshold is ${re.AUTO_REFRESH_TICK_THRESHOLD} ticks`),d<=re.AUTO_REFRESH_TICK_THRESHOLD)await this._callRefreshToken(t.refresh_token)})}catch(a){console.error("Auto refresh tick failed with error. This is likely a transient error.",a)}}finally{this._debug("#_autoRefreshTokenTick()","end")}})}catch(e){if(e.isAcquireTimeout||e instanceof fi.LockAcquireTimeoutError)this._debug("auto refresh token tick lock not available");else throw e}}async _handleVisibilityChange(){if(this._debug("#_handleVisibilityChange()"),!(0,z.isBrowser)()||!(window===null||window===void 0?void 0:window.addEventListener)){if(this.autoRefreshToken)this.startAutoRefresh();return!1}try{this.visibilityChangedCallback=async()=>await this._onVisibilityChanged(!1),window===null||window===void 0||window.addEventListener("visibilitychange",this.visibilityChangedCallback),await this._onVisibilityChanged(!0)}catch(e){console.error("_handleVisibilityChange",e)}}async _onVisibilityChanged(e){let a=`#_onVisibilityChanged(${e})`;if(this._debug(a,"visibilityState",document.visibilityState),document.visibilityState==="visible"){if(this.autoRefreshToken)this._startAutoRefresh();if(!e)await this.initializePromise,await this._acquireLock(-1,async()=>{if(document.visibilityState!=="visible"){this._debug(a,"acquired the lock to recover the session, but the browser visibilityState is no longer visible, aborting");return}await this._recoverAndRefresh()})}else if(document.visibilityState==="hidden"){if(this.autoRefreshToken)this._stopAutoRefresh()}}async _getUrlForProvider(e,a,t){let d=[`provider=${encodeURIComponent(a)}`];if(t===null||t===void 0?void 0:t.redirectTo)d.push(`redirect_to=${encodeURIComponent(t.redirectTo)}`);if(t===null||t===void 0?void 0:t.scopes)d.push(`scopes=${encodeURIComponent(t.scopes)}`);if(this.flowType==="pkce"){let[l,i]=await(0,z.getCodeChallengeAndMethod)(this.storage,this.storageKey),n=new URLSearchParams({code_challenge:`${encodeURIComponent(l)}`,code_challenge_method:`${encodeURIComponent(i)}`});d.push(n.toString())}if(t===null||t===void 0?void 0:t.queryParams){let l=new URLSearchParams(t.queryParams);d.push(l.toString())}if(t===null||t===void 0?void 0:t.skipBrowserRedirect)d.push(`skip_http_redirect=${t.skipBrowserRedirect}`);return`${e}?${d.join("&")}`}async _unenroll(e){try{return await this._useSession(async(a)=>{var t;let{data:d,error:l}=a;if(l)return{data:null,error:l};return await(0,g._request)(this.fetch,"DELETE",`${this.url}/factors/${e.factorId}`,{headers:this.headers,jwt:(t=d===null||d===void 0?void 0:d.session)===null||t===void 0?void 0:t.access_token})})}catch(a){if((0,X.isAuthError)(a))return{data:null,error:a};throw a}}async _enroll(e){try{return await this._useSession(async(a)=>{var t,d;let{data:l,error:i}=a;if(i)return{data:null,error:i};let n=Object.assign({friendly_name:e.friendlyName,factor_type:e.factorType},e.factorType==="phone"?{phone:e.phone}:e.factorType==="totp"?{issuer:e.issuer}:{}),{data:p,error:r}=await(0,g._request)(this.fetch,"POST",`${this.url}/factors`,{body:n,headers:this.headers,jwt:(t=l===null||l===void 0?void 0:l.session)===null||t===void 0?void 0:t.access_token});if(r)return{data:null,error:r};if(e.factorType==="totp"&&p.type==="totp"&&((d=p===null||p===void 0?void 0:p.totp)===null||d===void 0?void 0:d.qr_code))p.totp.qr_code=`data:image/svg+xml;utf-8,${p.totp.qr_code}`;return{data:p,error:null}})}catch(a){if((0,X.isAuthError)(a))return{data:null,error:a};throw a}}async _verify(e){return this._acquireLock(-1,async()=>{try{return await this._useSession(async(a)=>{var t;let{data:d,error:l}=a;if(l)return{data:null,error:l};let i=Object.assign({challenge_id:e.challengeId},"webauthn"in e?{webauthn:Object.assign(Object.assign({},e.webauthn),{credential_response:e.webauthn.type==="create"?(0,C1.serializeCredentialCreationResponse)(e.webauthn.credential_response):(0,C1.serializeCredentialRequestResponse)(e.webauthn.credential_response)})}:{code:e.code}),{data:n,error:p}=await(0,g._request)(this.fetch,"POST",`${this.url}/factors/${e.factorId}/verify`,{body:i,headers:this.headers,jwt:(t=d===null||d===void 0?void 0:d.session)===null||t===void 0?void 0:t.access_token});if(p)return{data:null,error:p};return await this._saveSession(Object.assign({expires_at:Math.round(Date.now()/1000)+n.expires_in},n)),await this._notifyAllSubscribers("MFA_CHALLENGE_VERIFIED",n),{data:n,error:p}})}catch(a){if((0,X.isAuthError)(a))return{data:null,error:a};throw a}})}async _challenge(e){return this._acquireLock(-1,async()=>{try{return await this._useSession(async(a)=>{var t;let{data:d,error:l}=a;if(l)return{data:null,error:l};let i=await(0,g._request)(this.fetch,"POST",`${this.url}/factors/${e.factorId}/challenge`,{body:e,headers:this.headers,jwt:(t=d===null||d===void 0?void 0:d.session)===null||t===void 0?void 0:t.access_token});if(i.error)return i;let{data:n}=i;if(n.type!=="webauthn")return{data:n,error:null};switch(n.webauthn.type){case"create":return{data:Object.assign(Object.assign({},n),{webauthn:Object.assign(Object.assign({},n.webauthn),{credential_options:Object.assign(Object.assign({},n.webauthn.credential_options),{publicKey:(0,C1.deserializeCredentialCreationOptions)(n.webauthn.credential_options.publicKey)})})}),error:null};case"request":return{data:Object.assign(Object.assign({},n),{webauthn:Object.assign(Object.assign({},n.webauthn),{credential_options:Object.assign(Object.assign({},n.webauthn.credential_options),{publicKey:(0,C1.deserializeCredentialRequestOptions)(n.webauthn.credential_options.publicKey)})})}),error:null}}})}catch(a){if((0,X.isAuthError)(a))return{data:null,error:a};throw a}})}async _challengeAndVerify(e){let{data:a,error:t}=await this._challenge({factorId:e.factorId});if(t)return{data:null,error:t};return await this._verify({factorId:e.factorId,challengeId:a.id,code:e.code})}async _listFactors(){var e;let{data:{user:a},error:t}=await this.getUser();if(t)return{data:null,error:t};let d={all:[],phone:[],totp:[],webauthn:[]};for(let l of(e=a===null||a===void 0?void 0:a.factors)!==null&&e!==void 0?e:[])if(d.all.push(l),l.status==="verified")d[l.factor_type].push(l);return{data:d,error:null}}async _getAuthenticatorAssuranceLevel(){return this._acquireLock(-1,async()=>{return await this._useSession(async(e)=>{var a,t;let{data:{session:d},error:l}=e;if(l)return{data:null,error:l};if(!d)return{data:{currentLevel:null,nextLevel:null,currentAuthenticationMethods:[]},error:null};let{payload:i}=(0,z.decodeJWT)(d.access_token),n=null;if(i.aal)n=i.aal;let p=n;if(((t=(a=d.user.factors)===null||a===void 0?void 0:a.filter((u)=>u.status==="verified"))!==null&&t!==void 0?t:[]).length>0)p="aal2";let s=i.amr||[];return{data:{currentLevel:n,nextLevel:p,currentAuthenticationMethods:s},error:null}})})}async fetchJwk(e,a={keys:[]}){let t=a.keys.find((n)=>n.kid===e);if(t)return t;let d=Date.now();if(t=this.jwks.keys.find((n)=>n.kid===e),t&&this.jwks_cached_at+re.JWKS_TTL>d)return t;let{data:l,error:i}=await(0,g._request)(this.fetch,"GET",`${this.url}/.well-known/jwks.json`,{headers:this.headers});if(i)throw i;if(!l.keys||l.keys.length===0)return null;if(this.jwks=l,this.jwks_cached_at=d,t=l.keys.find((n)=>n.kid===e),!t)return null;return t}async getClaims(e,a={}){try{let t=e;if(!t){let{data:o,error:h}=await this.getSession();if(h||!o.session)return{data:null,error:h};t=o.session.access_token}let{header:d,payload:l,signature:i,raw:{header:n,payload:p}}=(0,z.decodeJWT)(t);if(!(a===null||a===void 0?void 0:a.allowExpired))(0,z.validateExp)(l.exp);let r=!d.alg||d.alg.startsWith("HS")||!d.kid||!(("crypto"in globalThis)&&("subtle"in globalThis.crypto))?null:await this.fetchJwk(d.kid,(a===null||a===void 0?void 0:a.keys)?{keys:a.keys}:a===null||a===void 0?void 0:a.jwks);if(!r){let{error:o}=await this.getUser(t);if(o)throw o;return{data:{claims:l,header:d,signature:i},error:null}}let s=(0,z.getAlgorithm)(d.alg),u=await crypto.subtle.importKey("jwk",r,s,!0,["verify"]);if(!await crypto.subtle.verify(s,u,i,(0,hi.stringToUint8Array)(`${n}.${p}`)))throw new X.AuthInvalidJwtError("Invalid JWT signature");return{data:{claims:l,header:d,signature:i},error:null}}catch(t){if((0,X.isAuthError)(t))return{data:null,error:t};throw t}}}M1.nextInstanceID=0;I1.default=M1});var vi=f((j1)=>{var I8=j1&&j1.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(j1,"__esModule",{value:!0});var j8=I8(Xa()),L8=j8.default;j1.default=L8});var wi=f((L1)=>{var P8=L1&&L1.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(L1,"__esModule",{value:!0});var A8=P8(Wt()),F8=A8.default;L1.default=F8});var Ot=f((W)=>{var K8=W&&W.__createBinding||(Object.create?function(e,a,t,d){if(d===void 0)d=t;var l=Object.getOwnPropertyDescriptor(a,t);if(!l||("get"in l?!a.__esModule:l.writable||l.configurable))l={enumerable:!0,get:function(){return a[t]}};Object.defineProperty(e,d,l)}:function(e,a,t,d){if(d===void 0)d=t;e[d]=a[t]}),Xi=W&&W.__exportStar||function(e,a){for(var t in e)if(t!=="default"&&!Object.prototype.hasOwnProperty.call(a,t))K8(a,e,t)},Ja=W&&W.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(W,"__esModule",{value:!0});W.processLock=W.lockInternals=W.NavigatorLockAcquireTimeoutError=W.navigatorLock=W.AuthClient=W.AuthAdminApi=W.GoTrueClient=W.GoTrueAdminApi=void 0;var e5=Ja(Xa());W.GoTrueAdminApi=e5.default;var a5=Ja(Wt());W.GoTrueClient=a5.default;var t5=Ja(vi());W.AuthAdminApi=t5.default;var d5=Ja(wi());W.AuthClient=d5.default;Xi(Qt(),W);Xi(Pe(),W);var ba=xt();Object.defineProperty(W,"navigatorLock",{enumerable:!0,get:function(){return ba.navigatorLock}});Object.defineProperty(W,"NavigatorLockAcquireTimeoutError",{enumerable:!0,get:function(){return ba.NavigatorLockAcquireTimeoutError}});Object.defineProperty(W,"lockInternals",{enumerable:!0,get:function(){return ba.internals}});Object.defineProperty(W,"processLock",{enumerable:!0,get:function(){return ba.processLock}})});var Ji=f((yi)=>{Object.defineProperty(yi,"__esModule",{value:!0});yi.SupabaseAuthClient=void 0;var l5=Ot();class zi extends l5.AuthClient{constructor(e){super(e)}}yi.SupabaseAuthClient=zi});var $t=f((P1)=>{var i5=P1&&P1.__awaiter||function(e,a,t,d){function l(i){return i instanceof t?i:new t(function(n){n(i)})}return new(t||(t=Promise))(function(i,n){function p(u){try{s(d.next(u))}catch(m){n(m)}}function r(u){try{s(d.throw(u))}catch(m){n(m)}}function s(u){u.done?i(u.value):l(u.value).then(p,r)}s((d=d.apply(e,a||[])).next())})};Object.defineProperty(P1,"__esModule",{value:!0});var n5=_a(),p5=pt(),r5=wt(),s5=l2(),Ga=m2(),u5=c2(),bi=f2(),m5=Ji();class Gi{constructor(e,a,t){var d,l,i;this.supabaseUrl=e,this.supabaseKey=a;let n=(0,bi.validateSupabaseUrl)(e);if(!a)throw Error("supabaseKey is required.");this.realtimeUrl=new URL("realtime/v1",n),this.realtimeUrl.protocol=this.realtimeUrl.protocol.replace("http","ws"),this.authUrl=new URL("auth/v1",n),this.storageUrl=new URL("storage/v1",n),this.functionsUrl=new URL("functions/v1",n);let p=`sb-${n.hostname.split(".")[0]}-auth-token`,r={db:Ga.DEFAULT_DB_OPTIONS,realtime:Ga.DEFAULT_REALTIME_OPTIONS,auth:Object.assign(Object.assign({},Ga.DEFAULT_AUTH_OPTIONS),{storageKey:p}),global:Ga.DEFAULT_GLOBAL_OPTIONS},s=(0,bi.applySettingDefaults)(t!==null&&t!==void 0?t:{},r);if(this.storageKey=(d=s.auth.storageKey)!==null&&d!==void 0?d:"",this.headers=(l=s.global.headers)!==null&&l!==void 0?l:{},!s.accessToken)this.auth=this._initSupabaseAuthClient((i=s.auth)!==null&&i!==void 0?i:{},this.headers,s.global.fetch);else this.accessToken=s.accessToken,this.auth=new Proxy({},{get:(u,m)=>{throw Error(`@supabase/supabase-js: Supabase Client is configured with the accessToken option, accessing supabase.auth.${String(m)} is not possible`)}});if(this.fetch=(0,u5.fetchWithAuth)(a,this._getAccessToken.bind(this),s.global.fetch),this.realtime=this._initRealtimeClient(Object.assign({headers:this.headers,accessToken:this._getAccessToken.bind(this)},s.realtime)),this.rest=new p5.PostgrestClient(new URL("rest/v1",n).href,{headers:this.headers,schema:s.db.schema,fetch:this.fetch}),this.storage=new s5.StorageClient(this.storageUrl.href,this.headers,this.fetch,t===null||t===void 0?void 0:t.storage),!s.accessToken)this._listenForAuthEvents()}get functions(){return new n5.FunctionsClient(this.functionsUrl.href,{headers:this.headers,customFetch:this.fetch})}from(e){return this.rest.from(e)}schema(e){return this.rest.schema(e)}rpc(e,a={},t={head:!1,get:!1,count:void 0}){return this.rest.rpc(e,a,t)}channel(e,a={config:{}}){return this.realtime.channel(e,a)}getChannels(){return this.realtime.getChannels()}removeChannel(e){return this.realtime.removeChannel(e)}removeAllChannels(){return this.realtime.removeAllChannels()}_getAccessToken(){return i5(this,void 0,void 0,function*(){var e,a;if(this.accessToken)return yield this.accessToken();let{data:t}=yield this.auth.getSession();return(a=(e=t.session)===null||e===void 0?void 0:e.access_token)!==null&&a!==void 0?a:this.supabaseKey})}_initSupabaseAuthClient({autoRefreshToken:e,persistSession:a,detectSessionInUrl:t,storage:d,userStorage:l,storageKey:i,flowType:n,lock:p,debug:r},s,u){let m={Authorization:`Bearer ${this.supabaseKey}`,apikey:`${this.supabaseKey}`};return new m5.SupabaseAuthClient({url:this.authUrl.href,headers:Object.assign(Object.assign({},m),s),storageKey:i,autoRefreshToken:e,persistSession:a,detectSessionInUrl:t,storage:d,userStorage:l,flowType:n,lock:p,debug:r,fetch:u,hasCustomAuthorizationHeader:Object.keys(this.headers).some((o)=>o.toLowerCase()==="authorization")})}_initRealtimeClient(e){return new r5.RealtimeClient(this.realtimeUrl.href,Object.assign(Object.assign({},e),{params:Object.assign({apikey:this.supabaseKey},e===null||e===void 0?void 0:e.params)}))}_listenForAuthEvents(){return this.auth.onAuthStateChange((a,t)=>{this._handleTokenChanged(a,"CLIENT",t===null||t===void 0?void 0:t.access_token)})}_handleTokenChanged(e,a,t){if((e==="TOKEN_REFRESHED"||e==="SIGNED_IN")&&this.changedAccessToken!==t)this.changedAccessToken=t,this.realtime.setAuth(t);else if(e==="SIGNED_OUT"){if(this.realtime.setAuth(),a=="STORAGE")this.auth.signOut();this.changedAccessToken=void 0}}}P1.default=Gi});var Ni=f((O)=>{var o5=O&&O.__createBinding||(Object.create?function(e,a,t,d){if(d===void 0)d=t;var l=Object.getOwnPropertyDescriptor(a,t);if(!l||("get"in l?!a.__esModule:l.writable||l.configurable))l={enumerable:!0,get:function(){return a[t]}};Object.defineProperty(e,d,l)}:function(e,a,t,d){if(d===void 0)d=t;e[d]=a[t]}),Hi=O&&O.__exportStar||function(e,a){for(var t in e)if(t!=="default"&&!Object.prototype.hasOwnProperty.call(a,t))o5(a,e,t)},Si=O&&O.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(O,"__esModule",{value:!0});O.createClient=O.SupabaseClient=O.FunctionRegion=O.FunctionsError=O.FunctionsRelayError=O.FunctionsFetchError=O.FunctionsHttpError=O.PostgrestError=void 0;var c5=Si($t());Hi(Ot(),O);var Y5=pt();Object.defineProperty(O,"PostgrestError",{enumerable:!0,get:function(){return Y5.PostgrestError}});var A1=_a();Object.defineProperty(O,"FunctionsHttpError",{enumerable:!0,get:function(){return A1.FunctionsHttpError}});Object.defineProperty(O,"FunctionsFetchError",{enumerable:!0,get:function(){return A1.FunctionsFetchError}});Object.defineProperty(O,"FunctionsRelayError",{enumerable:!0,get:function(){return A1.FunctionsRelayError}});Object.defineProperty(O,"FunctionsError",{enumerable:!0,get:function(){return A1.FunctionsError}});Object.defineProperty(O,"FunctionRegion",{enumerable:!0,get:function(){return A1.FunctionRegion}});Hi(wt(),O);var f5=$t();Object.defineProperty(O,"SupabaseClient",{enumerable:!0,get:function(){return Si(f5).default}});var h5=(e,a,t)=>{return new c5.default(e,a,t)};O.createClient=h5;function Z5(){if(typeof window<"u")return!1;if(typeof process>"u")return!1;let e=process.version;if(e===void 0||e===null)return!1;let a=e.match(/^v(\d+)\./);if(!a)return!1;return parseInt(a[1],10)<=18}if(Z5())console.warn("⚠️ 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")});var ld=Z1(dd(),1),{program:q5,createCommand:T5,createArgument:W5,createOption:O5,CommanderError:$5,InvalidArgumentError:R5,InvalidOptionArgumentError:E5,Command:id,Argument:_5,Option:U5,Help:B5}=ld.default;var nd="0.1.3";var pd=nd;var w=Z1(ta(),1);var F=(e)=>({value:e,success:!0}),ae=(e)=>({error:e,success:!1});async function*ud(e,a="NONEXISTANT_SCHEMA_THAT_SHOULDNT_EXIST"){yield{type:"schemas_fetch_started",data:{}};let{data:t,error:d}=await e.schema(a).from("").select();if(t)return ae(Error("Schema exists, this shouldn't happen"));let l=d?.message.split("following: ")[1]?.split(",").map((i)=>i.trim())??[];return yield{type:"schemas_discovered",data:{schemas:l}},F(l)}async function Ra(e,a){let{data:t,error:d}=await e.schema(a).from("").select();if(d)return ae(d);return F(t)}async function*md(e,a){yield{type:"swagger_fetch_started",data:{schema:a}};let t=await Ra(e,a);if(!t.success)return ae(t.error);yield{type:"swagger_fetched",data:{schema:a}};let d=Object.keys(t.value.paths).filter((l)=>!l.startsWith("/rpc/")).map((l)=>l.slice(1)).filter((l)=>!!l);return yield{type:"tables_discovered",data:{schema:a,tables:d}},F(d)}async function*od(e,a){yield{type:"swagger_fetch_started",data:{schema:a}};let t=await Ra(e,a);if(!t.success)return ae(t.error);yield{type:"swagger_fetched",data:{schema:a}};let d=Object.keys(t.value.paths).filter((l)=>l.startsWith("/rpc/")).map((l)=>l.slice(1));return yield{type:"rpcs_discovered",data:{schema:a,rpcs:d}},F(d)}async function cd(e,a){let t=await Ra(e,a);if(!t.success)return ae(t.error);let d=[];return Object.entries(t.value.paths).forEach(([l,i])=>{if(l.startsWith("/rpc/")){let n=l.slice(1),p=i.post;if(p&&p.parameters){let r=[];p.parameters.forEach((s)=>{if(s.in==="body"&&s.schema&&s.schema.properties){let u=s.schema.required||[];Object.entries(s.schema.properties).forEach(([m,o])=>{r.push({name:m,type:o.type||"unknown",format:o.format,required:u.includes(m),description:o.description})})}}),d.push({name:n,parameters:r})}}}),F(d)}async function Yd(e,a,t,d={},l={get:!1,explain:!1}){try{let i=e.schema(a).rpc(t,d);if(l.limit&&!l.explain)i=i.limit(l.limit);let{data:n,error:p}=l.explain?await i.explain({analyze:!0,format:"text",verbose:!0,settings:!0,wal:!0,buffers:!0}):await i;if(p)return ae(Error(`RPC call failed: ${p.message}`));return F(n)}catch(i){return ae(Error(`RPC call exception: ${i instanceof Error?i.message:String(i)}`))}}async function*qn(e,a,t){yield{type:"table_access_test_started",data:{schema:a,table:t}};let{data:d,error:l}=await e.schema(a).from(t).select("*").limit(1);if(l){let p={status:"denied",accessible:!1,hasData:!1};return yield{type:"table_access_test_completed",data:{schema:a,table:t,result:p}},F(p)}if(d&&d.length>0){let{count:p}=await e.schema(a).from(t).select("*",{count:"estimated",head:!0}),r={status:"readable",accessible:!0,hasData:!0,rowCount:p??void 0};return yield{type:"table_access_test_completed",data:{schema:a,table:t,result:r}},F(r)}let n={status:"empty",accessible:!0,hasData:!1,rowCount:0};return yield{type:"table_access_test_completed",data:{schema:a,table:t,result:n}},F(n)}async function*fd(e,a,t){let d={};for(let l of t){let i=qn(e,a,l),n={status:"denied",accessible:!1,hasData:!1};while(!0){let p=await i.next();if(p.done){if(p.value&&p.value.success)n=p.value.value;break}yield p.value}d[l]=n}return F(d)}async function hd(e,a,t,d=10){let{data:l,error:i,count:n}=await e.schema(a).from(t).select("*",{count:"exact"}).limit(d);if(i)return ae(i);let p=l&&l.length>0?Object.keys(l[0]??{}):[];return F({columns:p,rows:l??[],count:n??0})}async function*Zd(e,a,t,d={}){yield{type:"analysis_started",data:{}};let l=ud(e),i;while(!0){let u=await l.next();if(u.done){i=u.value;break}yield u.value}if(!i||!i.success)return ae(i?.error??Error("Failed to fetch schemas"));let n=d.schema?[d.schema]:i.value,p={};for(let u of n){yield{type:"schema_analysis_started",data:{schema:u}};let m=md(e,u),o;while(!0){let S=await m.next();if(S.done){o=S.value;break}yield S.value}let h=od(e,u),c;while(!0){let S=await h.next();if(S.done){c=S.value;break}yield S.value}let Y=await cd(e,u);if(!o?.success||!c?.success)continue;let y=o.value,v=fd(e,u,y),Z;while(!0){let S=await v.next();if(S.done){Z=S.value;break}yield S.value}if(!Z?.success)continue;let b={tables:y,rpcs:c.value,rpcFunctions:Y.success?Y.value:[],tableAccess:Z.value};p[u]=b,yield{type:"schema_analysis_completed",data:{schema:u,analysis:b}}}let r=await Tn(e,a,t),s={schemas:i.value,schemaDetails:p,summary:r};return yield{type:"analysis_completed",data:{result:s}},F(s)}async function Tn(e,a,t){let d=Wn(a),l=On(t),i=$n(a),n=await Rn(e),p={...i,...n};return{domain:d,jwtInfo:l,metadata:p}}function Wn(e){try{return new URL(e).hostname}catch{return e}}function On(e){try{let a=e.split(".");if(a.length!==3)return;let t=a[1];if(!t)return;let d=atob(t.replace(/-/g,"+").replace(/_/g,"/"));return JSON.parse(d)}catch{return}}function $n(e){let a={};try{let t=new URL(e);if(a.protocol=t.protocol,a.port=t.port||(t.protocol==="https:"?"443":"80"),t.hostname.includes(".supabase.co")){a.service="Supabase";let d=t.hostname.replace(".supabase.co","");a.region=d}}catch{}return a}async function Rn(e){try{let{data:a,error:t}=await e.schema("public").from("").select();if(t)return{};let d=a,l={};if(d.info&&typeof d.info==="object"){let i=d.info;l.title=i.title,l.description=i.description,l.version=i.version}return l}catch{return{}}}var a1=Z1(ta(),1),w1=(e,a,...t)=>{let d=[a,...t].map((l)=>typeof l==="object"?JSON.stringify(l):String(l)).join(" ");return`${e} ${d}`},x={debug:(e,...a)=>{console.error(w1(a1.default.gray("[DEBUG]"),e,...a))},info:(e,...a)=>console.error(w1(a1.default.blue("[INFO]"),e,...a)),success:(e,...a)=>console.error(w1(a1.default.green("[OK]"),e,...a)),warn:(e,...a)=>console.error(w1(a1.default.yellow("[WARN]"),e,...a)),error:(e,...a)=>console.error(w1(a1.default.red("[ERROR]"),e,...a))},wd=!1,Xd=(e)=>{wd=e},vd={value:!1},zd=()=>{if(!vd.value&&!wd)x.warn("This feature is experimental and may have bugs. You can suppress this with --suppress-experimental-warnings."),vd.value=!0};var te=Z1(ta(),1);function yd(e,a){if(!e.debug)return;switch(a.type){case"schemas_fetch_started":console.error(te.default.gray("[DEBUG] Fetching schemas..."));break;case"schemas_discovered":console.error(te.default.gray(`[DEBUG] Found ${a.data.schemas.length} schemas`));break;case"swagger_fetch_started":console.error(te.default.gray(`[DEBUG] Fetching swagger for schema: ${a.data.schema}`));break;case"tables_discovered":console.error(te.default.gray(`[DEBUG] Found ${a.data.tables.length} tables in ${a.data.schema}`));break;case"rpcs_discovered":console.error(te.default.gray(`[DEBUG] Found ${a.data.rpcs.length} RPCs in ${a.data.schema}`));break;case"table_access_test_started":console.error(te.default.gray(`[DEBUG] Testing read access for ${a.data.schema}.${a.data.table}`));break;case"table_access_test_completed":let t=a.data.result.status==="readable"?`readable with ~${a.data.result.rowCount??"?"} rows (EXPOSED)`:a.data.result.status==="empty"?"returned 0 rows (empty or RLS blocked)":"access denied";console.error(te.default.gray(`[DEBUG] Table ${a.data.table} is ${t}`));break;case"analysis_started":console.error(te.default.gray("[DEBUG] Analysis started"));break;case"schema_analysis_started":console.error(te.default.gray(`[DEBUG] Analyzing schema: ${a.data.schema}`));break;case"schema_analysis_completed":console.error(te.default.gray(`[DEBUG] Completed analysis of schema: ${a.data.schema}`));break;case"extraction_started":console.error(te.default.gray(`[DEBUG] Fetching content from: ${a.data.url}`));break;case"content_fetched":console.error(te.default.gray(`[DEBUG] Fetched ${a.data.size} bytes (${a.data.contentType})`));break;case"html_detected":console.error(te.default.gray(`[DEBUG] Detected HTML content, found ${a.data.scriptCount} scripts`));break;case"script_checking":console.error(te.default.gray(`[DEBUG] Checking script: ${a.data.scriptUrl}`));break;case"credentials_found":console.error(te.default.gray(`[DEBUG] Found credentials in ${a.data.source}`));break}}async function Qd(e,a){let t=Zd(e.client,e.url,e.key,a),d;while(!0){let l=await t.next();if(l.done){d=l.value;break}yd(e,l.value)}if(!d||!d.success)x.error("Analysis failed",d?.error.message??"Unknown error"),process.exit(1);if(e.json)console.log(JSON.stringify(d.value,null,2));else if(e.html){let{buildHtmlReport:l}=await Promise.resolve().then(() => (bd(),Jd)),i=await l(d.value,e.url,e.key),{generateTempFilePath:n,writeHtmlFile:p}=await Promise.resolve().then(() => (Hd(),Gd)),{openInBrowser:r}=await Promise.resolve().then(() => (Nd(),Sd)),s=n();p(s,i),r(s),x.success(`HTML report generated: ${s}`)}else Pn(d.value)}function Pn(e){if(console.log(),console.log(w.default.bold(w.default.cyan("=".repeat(60)))),console.log(w.default.bold(w.default.cyan(" SUPABASE DATABASE ANALYSIS"))),console.log(w.default.bold(w.default.cyan("=".repeat(60)))),console.log(),console.log(w.default.bold(w.default.yellow("TARGET SUMMARY"))),console.log(w.default.dim("-".repeat(20))),console.log(w.default.bold("Domain:"),w.default.white(e.summary.domain)),e.summary.metadata?.service)console.log(w.default.bold("Service:"),w.default.white(e.summary.metadata.service));if(e.summary.metadata?.region)console.log(w.default.bold("Project ID:"),w.default.white(e.summary.metadata.region));if(e.summary.metadata?.title)console.log(w.default.bold("Title:"),w.default.white(e.summary.metadata.title));if(e.summary.metadata?.version)console.log(w.default.bold("Version:"),w.default.white(e.summary.metadata.version));if(e.summary.jwtInfo){if(console.log(),console.log(w.default.bold(w.default.yellow("JWT TOKEN INFO"))),console.log(w.default.dim("-".repeat(20))),e.summary.jwtInfo.iss)console.log(w.default.bold("Issuer:"),w.default.white(e.summary.jwtInfo.iss));if(e.summary.jwtInfo.aud)console.log(w.default.bold("Audience:"),w.default.white(e.summary.jwtInfo.aud));if(e.summary.jwtInfo.role)console.log(w.default.bold("Role:"),w.default.white(e.summary.jwtInfo.role));if(e.summary.jwtInfo.exp){let a=new Date(e.summary.jwtInfo.exp*1000);console.log(w.default.bold("Expires:"),w.default.white(a.toISOString()))}if(e.summary.jwtInfo.iat){let a=new Date(e.summary.jwtInfo.iat*1000);console.log(w.default.bold("Issued:"),w.default.white(a.toISOString()))}}console.log(),console.log(w.default.bold(w.default.cyan("DATABASE ANALYSIS"))),console.log(w.default.dim("-".repeat(20))),console.log(w.default.bold("Schemas discovered:"),w.default.green(e.schemas.length.toString())),console.log(),Object.entries(e.schemaDetails).forEach(([a,t])=>{console.log(w.default.bold(w.default.cyan(`Schema: ${a}`))),console.log();let d=Object.values(t.tableAccess).filter((n)=>n.status==="readable").length,l=Object.values(t.tableAccess).filter((n)=>n.status==="denied").length,i=Object.values(t.tableAccess).filter((n)=>n.status==="empty").length;if(console.log(w.default.bold("Tables:"),w.default.green(t.tables.length.toString())),console.log(w.default.dim(` ${d} exposed | ${i} empty/protected | ${l} denied`)),console.log(),t.tables.length>0)t.tables.forEach((n)=>{let p=t.tableAccess[n],r="",s="";switch(p?.status){case"readable":r=w.default.green("[+]"),s=w.default.dim(`(~${p.rowCount??"?"} rows exposed)`);break;case"empty":r=w.default.yellow("[-]"),s=w.default.dim("(0 rows - empty or RLS)");break;case"denied":r=w.default.red("[X]"),s=w.default.dim("(access denied)");break}console.log(` ${r} ${w.default.white(n)} ${s}`)});else console.log(w.default.dim(" No tables found"));if(console.log(),console.log(w.default.bold("RPCs:"),w.default.green(t.rpcs.length.toString())),t.rpcFunctions.length>0)t.rpcFunctions.forEach((n)=>{if(console.log(` * ${w.default.white(n.name)}`),n.parameters.length>0)n.parameters.forEach((p)=>{let r=p.required?w.default.red("(required)"):w.default.dim("(optional)"),s=p.format?`${p.type} (${p.format})`:p.type;console.log(` - ${w.default.cyan(p.name)}: ${w.default.yellow(s)} ${r}`)});else console.log(w.default.dim(" No parameters"))});else console.log(w.default.dim(" No RPCs found"));console.log()}),console.log(w.default.bold(w.default.cyan("=".repeat(60)))),console.log()}async function kd(e,a){let t=a.dump.split(".");if(t.length===1){let d=t[0];if(!d)x.error("Invalid dump format. Use schema.table or schema"),process.exit(1);x.info(`Dumping swagger for schema: ${d}`);let{data:l,error:i}=await e.client.schema(d).from("").select();if(i)x.error("Failed to fetch swagger",i.message),process.exit(1);console.log(JSON.stringify(l,null,2));return}if(t.length===2){let d=t[0],l=t[1];if(!d||!l)x.error("Invalid dump format. Use schema.table"),process.exit(1);let i=parseInt(a.limit);if(isNaN(i)||i<=0)x.error("Invalid limit value"),process.exit(1);x.info(`Dumping table: ${d}.${l} (limit: ${i})`);let n=await hd(e.client,d,l,i);if(!n.success)x.error("Failed to dump table",n.error.message),process.exit(1);if(e.json)console.log(JSON.stringify(n.value,null,2));else console.log(`
|
|
200
|
+
`);let H=await b.signMessage(new TextEncoder().encode(h),"utf8");if(!H||!(H instanceof Uint8Array))throw Error("@supabase/auth-js: Wallet signMessage() API returned an recognized value");c=H}}try{let{data:Y,error:y}=await(0,g._request)(this.fetch,"POST",`${this.url}/token?grant_type=web3`,{headers:this.headers,body:Object.assign({chain:"solana",message:h,signature:(0,hi.bytesToBase64URL)(c)},((m=e.options)===null||m===void 0?void 0:m.captchaToken)?{gotrue_meta_security:{captcha_token:(o=e.options)===null||o===void 0?void 0:o.captchaToken}}:null),xform:g._sessionResponse});if(y)throw y;if(!Y||!Y.session||!Y.user)return{data:{user:null,session:null},error:new X.AuthInvalidTokenResponseError};if(Y.session)await this._saveSession(Y.session),await this._notifyAllSubscribers("SIGNED_IN",Y.session);return{data:Object.assign({},Y),error:y}}catch(Y){if((0,X.isAuthError)(Y))return{data:{user:null,session:null},error:Y};throw Y}}async _exchangeCodeForSession(e){let a=await(0,z.getItemAsync)(this.storage,`${this.storageKey}-code-verifier`),[t,d]=(a!==null&&a!==void 0?a:"").split("/");try{let{data:l,error:i}=await(0,g._request)(this.fetch,"POST",`${this.url}/token?grant_type=pkce`,{headers:this.headers,body:{auth_code:e,code_verifier:t},xform:g._sessionResponse});if(await(0,z.removeItemAsync)(this.storage,`${this.storageKey}-code-verifier`),i)throw i;if(!l||!l.session||!l.user)return{data:{user:null,session:null,redirectType:null},error:new X.AuthInvalidTokenResponseError};if(l.session)await this._saveSession(l.session),await this._notifyAllSubscribers("SIGNED_IN",l.session);return{data:Object.assign(Object.assign({},l),{redirectType:d!==null&&d!==void 0?d:null}),error:i}}catch(l){if((0,X.isAuthError)(l))return{data:{user:null,session:null,redirectType:null},error:l};throw l}}async signInWithIdToken(e){try{let{options:a,provider:t,token:d,access_token:l,nonce:i}=e,n=await(0,g._request)(this.fetch,"POST",`${this.url}/token?grant_type=id_token`,{headers:this.headers,body:{provider:t,id_token:d,access_token:l,nonce:i,gotrue_meta_security:{captcha_token:a===null||a===void 0?void 0:a.captchaToken}},xform:g._sessionResponse}),{data:p,error:r}=n;if(r)return{data:{user:null,session:null},error:r};else if(!p||!p.session||!p.user)return{data:{user:null,session:null},error:new X.AuthInvalidTokenResponseError};if(p.session)await this._saveSession(p.session),await this._notifyAllSubscribers("SIGNED_IN",p.session);return{data:p,error:r}}catch(a){if((0,X.isAuthError)(a))return{data:{user:null,session:null},error:a};throw a}}async signInWithOtp(e){var a,t,d,l,i;try{if("email"in e){let{email:n,options:p}=e,r=null,s=null;if(this.flowType==="pkce")[r,s]=await(0,z.getCodeChallengeAndMethod)(this.storage,this.storageKey);let{error:u}=await(0,g._request)(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{email:n,data:(a=p===null||p===void 0?void 0:p.data)!==null&&a!==void 0?a:{},create_user:(t=p===null||p===void 0?void 0:p.shouldCreateUser)!==null&&t!==void 0?t:!0,gotrue_meta_security:{captcha_token:p===null||p===void 0?void 0:p.captchaToken},code_challenge:r,code_challenge_method:s},redirectTo:p===null||p===void 0?void 0:p.emailRedirectTo});return{data:{user:null,session:null},error:u}}if("phone"in e){let{phone:n,options:p}=e,{data:r,error:s}=await(0,g._request)(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{phone:n,data:(d=p===null||p===void 0?void 0:p.data)!==null&&d!==void 0?d:{},create_user:(l=p===null||p===void 0?void 0:p.shouldCreateUser)!==null&&l!==void 0?l:!0,gotrue_meta_security:{captcha_token:p===null||p===void 0?void 0:p.captchaToken},channel:(i=p===null||p===void 0?void 0:p.channel)!==null&&i!==void 0?i:"sms"}});return{data:{user:null,session:null,messageId:r===null||r===void 0?void 0:r.message_id},error:s}}throw new X.AuthInvalidCredentialsError("You must provide either an email or phone number.")}catch(n){if((0,X.isAuthError)(n))return{data:{user:null,session:null},error:n};throw n}}async verifyOtp(e){var a,t;try{let d=void 0,l=void 0;if("options"in e)d=(a=e.options)===null||a===void 0?void 0:a.redirectTo,l=(t=e.options)===null||t===void 0?void 0:t.captchaToken;let{data:i,error:n}=await(0,g._request)(this.fetch,"POST",`${this.url}/verify`,{headers:this.headers,body:Object.assign(Object.assign({},e),{gotrue_meta_security:{captcha_token:l}}),redirectTo:d,xform:g._sessionResponse});if(n)throw n;if(!i)throw Error("An error occurred on token verification.");let{session:p,user:r}=i;if(p===null||p===void 0?void 0:p.access_token)await this._saveSession(p),await this._notifyAllSubscribers(e.type=="recovery"?"PASSWORD_RECOVERY":"SIGNED_IN",p);return{data:{user:r,session:p},error:null}}catch(d){if((0,X.isAuthError)(d))return{data:{user:null,session:null},error:d};throw d}}async signInWithSSO(e){var a,t,d;try{let l=null,i=null;if(this.flowType==="pkce")[l,i]=await(0,z.getCodeChallengeAndMethod)(this.storage,this.storageKey);return await(0,g._request)(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:(t=(a=e.options)===null||a===void 0?void 0:a.redirectTo)!==null&&t!==void 0?t:void 0}),((d=e===null||e===void 0?void 0:e.options)===null||d===void 0?void 0:d.captchaToken)?{gotrue_meta_security:{captcha_token:e.options.captchaToken}}:null),{skip_http_redirect:!0,code_challenge:l,code_challenge_method:i}),headers:this.headers,xform:g._ssoResponse})}catch(l){if((0,X.isAuthError)(l))return{data:null,error:l};throw l}}async reauthenticate(){return await this.initializePromise,await this._acquireLock(-1,async()=>{return await this._reauthenticate()})}async _reauthenticate(){try{return await this._useSession(async(e)=>{let{data:{session:a},error:t}=e;if(t)throw t;if(!a)throw new X.AuthSessionMissingError;let{error:d}=await(0,g._request)(this.fetch,"GET",`${this.url}/reauthenticate`,{headers:this.headers,jwt:a.access_token});return{data:{user:null,session:null},error:d}})}catch(e){if((0,X.isAuthError)(e))return{data:{user:null,session:null},error:e};throw e}}async resend(e){try{let a=`${this.url}/resend`;if("email"in e){let{email:t,type:d,options:l}=e,{error:i}=await(0,g._request)(this.fetch,"POST",a,{headers:this.headers,body:{email:t,type:d,gotrue_meta_security:{captcha_token:l===null||l===void 0?void 0:l.captchaToken}},redirectTo:l===null||l===void 0?void 0:l.emailRedirectTo});return{data:{user:null,session:null},error:i}}else if("phone"in e){let{phone:t,type:d,options:l}=e,{data:i,error:n}=await(0,g._request)(this.fetch,"POST",a,{headers:this.headers,body:{phone:t,type:d,gotrue_meta_security:{captcha_token:l===null||l===void 0?void 0:l.captchaToken}}});return{data:{user:null,session:null,messageId:i===null||i===void 0?void 0:i.message_id},error:n}}throw new X.AuthInvalidCredentialsError("You must provide either an email or phone number and a type")}catch(a){if((0,X.isAuthError)(a))return{data:{user:null,session:null},error:a};throw a}}async getSession(){return await this.initializePromise,await this._acquireLock(-1,async()=>{return this._useSession(async(a)=>{return a})})}async _acquireLock(e,a){this._debug("#_acquireLock","begin",e);try{if(this.lockAcquired){let t=this.pendingInLock.length?this.pendingInLock[this.pendingInLock.length-1]:Promise.resolve(),d=(async()=>{return await t,await a()})();return this.pendingInLock.push((async()=>{try{await d}catch(l){}})()),d}return await this.lock(`lock:${this.storageKey}`,e,async()=>{this._debug("#_acquireLock","lock acquired for storage key",this.storageKey);try{this.lockAcquired=!0;let t=a();this.pendingInLock.push((async()=>{try{await t}catch(d){}})()),await t;while(this.pendingInLock.length){let d=[...this.pendingInLock];await Promise.all(d),this.pendingInLock.splice(0,d.length)}return await t}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 a=await this.__loadSession();return await e(a)}finally{this._debug("#_useSession","end")}}async __loadSession(){if(this._debug("#__loadSession()","begin"),!this.lockAcquired)this._debug("#__loadSession()","used outside of an acquired lock!",Error().stack);try{let e=null,a=await(0,z.getItemAsync)(this.storage,this.storageKey);if(this._debug("#getSession()","session from storage",a),a!==null)if(this._isValidSession(a))e=a;else this._debug("#getSession()","session from storage is not valid"),await this._removeSession();if(!e)return{data:{session:null},error:null};let t=e.expires_at?e.expires_at*1000-Date.now()<re.EXPIRY_MARGIN_MS:!1;if(this._debug("#__loadSession()",`session has${t?"":" not"} expired`,"expires_at",e.expires_at),!t){if(this.userStorage){let i=await(0,z.getItemAsync)(this.userStorage,this.storageKey+"-user");if(i===null||i===void 0?void 0:i.user)e.user=i.user;else e.user=(0,z.userNotAvailableProxy)()}if(this.storage.isServer&&e.user){let i=this.suppressGetSessionWarning;e=new Proxy(e,{get:(p,r,s)=>{if(!i&&r==="user")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."),i=!0,this.suppressGetSessionWarning=!0;return Reflect.get(p,r,s)}})}return{data:{session:e},error:null}}let{data:d,error:l}=await this._callRefreshToken(e.refresh_token);if(l)return{data:{session:null},error:l};return{data:{session:d},error:null}}finally{this._debug("#__loadSession()","end")}}async getUser(e){if(e)return await this._getUser(e);return await this.initializePromise,await this._acquireLock(-1,async()=>{return await this._getUser()})}async _getUser(e){try{if(e)return await(0,g._request)(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:e,xform:g._userResponse});return await this._useSession(async(a)=>{var t,d,l;let{data:i,error:n}=a;if(n)throw n;if(!((t=i.session)===null||t===void 0?void 0:t.access_token)&&!this.hasCustomAuthorizationHeader)return{data:{user:null},error:new X.AuthSessionMissingError};return await(0,g._request)(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:(l=(d=i.session)===null||d===void 0?void 0:d.access_token)!==null&&l!==void 0?l:void 0,xform:g._userResponse})})}catch(a){if((0,X.isAuthError)(a)){if((0,X.isAuthSessionMissingError)(a))await this._removeSession(),await(0,z.removeItemAsync)(this.storage,`${this.storageKey}-code-verifier`);return{data:{user:null},error:a}}throw a}}async updateUser(e,a={}){return await this.initializePromise,await this._acquireLock(-1,async()=>{return await this._updateUser(e,a)})}async _updateUser(e,a={}){try{return await this._useSession(async(t)=>{let{data:d,error:l}=t;if(l)throw l;if(!d.session)throw new X.AuthSessionMissingError;let i=d.session,n=null,p=null;if(this.flowType==="pkce"&&e.email!=null)[n,p]=await(0,z.getCodeChallengeAndMethod)(this.storage,this.storageKey);let{data:r,error:s}=await(0,g._request)(this.fetch,"PUT",`${this.url}/user`,{headers:this.headers,redirectTo:a===null||a===void 0?void 0:a.emailRedirectTo,body:Object.assign(Object.assign({},e),{code_challenge:n,code_challenge_method:p}),jwt:i.access_token,xform:g._userResponse});if(s)throw s;return i.user=r.user,await this._saveSession(i),await this._notifyAllSubscribers("USER_UPDATED",i),{data:{user:i.user},error:null}})}catch(t){if((0,X.isAuthError)(t))return{data:{user:null},error:t};throw t}}async setSession(e){return await this.initializePromise,await this._acquireLock(-1,async()=>{return await this._setSession(e)})}async _setSession(e){try{if(!e.access_token||!e.refresh_token)throw new X.AuthSessionMissingError;let a=Date.now()/1000,t=a,d=!0,l=null,{payload:i}=(0,z.decodeJWT)(e.access_token);if(i.exp)t=i.exp,d=t<=a;if(d){let{data:n,error:p}=await this._callRefreshToken(e.refresh_token);if(p)return{data:{user:null,session:null},error:p};if(!n)return{data:{user:null,session:null},error:null};l=n}else{let{data:n,error:p}=await this._getUser(e.access_token);if(p)throw p;l={access_token:e.access_token,refresh_token:e.refresh_token,user:n.user,token_type:"bearer",expires_in:t-a,expires_at:t},await this._saveSession(l),await this._notifyAllSubscribers("SIGNED_IN",l)}return{data:{user:l.user,session:l},error:null}}catch(a){if((0,X.isAuthError)(a))return{data:{session:null,user:null},error:a};throw a}}async refreshSession(e){return await this.initializePromise,await this._acquireLock(-1,async()=>{return await this._refreshSession(e)})}async _refreshSession(e){try{return await this._useSession(async(a)=>{var t;if(!e){let{data:i,error:n}=a;if(n)throw n;e=(t=i.session)!==null&&t!==void 0?t:void 0}if(!(e===null||e===void 0?void 0:e.refresh_token))throw new X.AuthSessionMissingError;let{data:d,error:l}=await this._callRefreshToken(e.refresh_token);if(l)return{data:{user:null,session:null},error:l};if(!d)return{data:{user:null,session:null},error:null};return{data:{user:d.user,session:d},error:null}})}catch(a){if((0,X.isAuthError)(a))return{data:{user:null,session:null},error:a};throw a}}async _getSessionFromURL(e,a){try{if(!(0,z.isBrowser)())throw new X.AuthImplicitGrantRedirectError("No browser detected.");if(e.error||e.error_description||e.error_code)throw new X.AuthImplicitGrantRedirectError(e.error_description||"Error in URL with unspecified error_description",{error:e.error||"unspecified_error",code:e.error_code||"unspecified_code"});switch(a){case"implicit":if(this.flowType==="pkce")throw new X.AuthPKCEGrantCodeExchangeError("Not a valid PKCE flow url.");break;case"pkce":if(this.flowType==="implicit")throw new X.AuthImplicitGrantRedirectError("Not a valid implicit grant flow url.");break;default:}if(a==="pkce"){if(this._debug("#_initialize()","begin","is PKCE flow",!0),!e.code)throw new X.AuthPKCEGrantCodeExchangeError("No code detected.");let{data:v,error:Z}=await this._exchangeCodeForSession(e.code);if(Z)throw Z;let b=new URL(window.location.href);return b.searchParams.delete("code"),window.history.replaceState(window.history.state,"",b.toString()),{data:{session:v.session,redirectType:null},error:null}}let{provider_token:t,provider_refresh_token:d,access_token:l,refresh_token:i,expires_in:n,expires_at:p,token_type:r}=e;if(!l||!n||!i||!r)throw new X.AuthImplicitGrantRedirectError("No session defined in URL");let s=Math.round(Date.now()/1000),u=parseInt(n),m=s+u;if(p)m=parseInt(p);let o=m-s;if(o*1000<=re.AUTO_REFRESH_TICK_DURATION_MS)console.warn(`@supabase/gotrue-js: Session as retrieved from URL expires in ${o}s, should have been closer to ${u}s`);let h=m-u;if(s-h>=120)console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued over 120s ago, URL could be stale",h,m,s);else if(s-h<0)console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued in the future? Check the device clock for skew",h,m,s);let{data:c,error:Y}=await this._getUser(l);if(Y)throw Y;let y={provider_token:t,provider_refresh_token:d,access_token:l,expires_in:u,expires_at:m,refresh_token:i,token_type:r,user:c.user};return window.location.hash="",this._debug("#_getSessionFromURL()","clearing window.location.hash"),{data:{session:y,redirectType:e.type},error:null}}catch(t){if((0,X.isAuthError)(t))return{data:{session:null,redirectType:null},error:t};throw t}}_isImplicitGrantCallback(e){return Boolean(e.access_token||e.error_description)}async _isPKCECallback(e){let a=await(0,z.getItemAsync)(this.storage,`${this.storageKey}-code-verifier`);return!!(e.code&&a)}async signOut(e={scope:"global"}){return await this.initializePromise,await this._acquireLock(-1,async()=>{return await this._signOut(e)})}async _signOut({scope:e}={scope:"global"}){return await this._useSession(async(a)=>{var t;let{data:d,error:l}=a;if(l)return{error:l};let i=(t=d.session)===null||t===void 0?void 0:t.access_token;if(i){let{error:n}=await this.admin.signOut(i,e);if(n){if(!((0,X.isAuthApiError)(n)&&(n.status===404||n.status===401||n.status===403)))return{error:n}}}if(e!=="others")await this._removeSession(),await(0,z.removeItemAsync)(this.storage,`${this.storageKey}-code-verifier`);return{error:null}})}onAuthStateChange(e){let a=(0,z.uuid)(),t={id:a,callback:e,unsubscribe:()=>{this._debug("#unsubscribe()","state change callback with id removed",a),this.stateChangeEmitters.delete(a)}};return this._debug("#onAuthStateChange()","registered callback with id",a),this.stateChangeEmitters.set(a,t),(async()=>{await this.initializePromise,await this._acquireLock(-1,async()=>{this._emitInitialSession(a)})})(),{data:{subscription:t}}}async _emitInitialSession(e){return await this._useSession(async(a)=>{var t,d;try{let{data:{session:l},error:i}=a;if(i)throw i;await((t=this.stateChangeEmitters.get(e))===null||t===void 0?void 0:t.callback("INITIAL_SESSION",l)),this._debug("INITIAL_SESSION","callback id",e,"session",l)}catch(l){await((d=this.stateChangeEmitters.get(e))===null||d===void 0?void 0:d.callback("INITIAL_SESSION",null)),this._debug("INITIAL_SESSION","callback id",e,"error",l),console.error(l)}})}async resetPasswordForEmail(e,a={}){let t=null,d=null;if(this.flowType==="pkce")[t,d]=await(0,z.getCodeChallengeAndMethod)(this.storage,this.storageKey,!0);try{return await(0,g._request)(this.fetch,"POST",`${this.url}/recover`,{body:{email:e,code_challenge:t,code_challenge_method:d,gotrue_meta_security:{captcha_token:a.captchaToken}},headers:this.headers,redirectTo:a.redirectTo})}catch(l){if((0,X.isAuthError)(l))return{data:null,error:l};throw l}}async getUserIdentities(){var e;try{let{data:a,error:t}=await this.getUser();if(t)throw t;return{data:{identities:(e=a.user.identities)!==null&&e!==void 0?e:[]},error:null}}catch(a){if((0,X.isAuthError)(a))return{data:null,error:a};throw a}}async linkIdentity(e){if("token"in e)return this.linkIdentityIdToken(e);return this.linkIdentityOAuth(e)}async linkIdentityOAuth(e){var a;try{let{data:t,error:d}=await this._useSession(async(l)=>{var i,n,p,r,s;let{data:u,error:m}=l;if(m)throw m;let o=await this._getUrlForProvider(`${this.url}/user/identities/authorize`,e.provider,{redirectTo:(i=e.options)===null||i===void 0?void 0:i.redirectTo,scopes:(n=e.options)===null||n===void 0?void 0:n.scopes,queryParams:(p=e.options)===null||p===void 0?void 0:p.queryParams,skipBrowserRedirect:!0});return await(0,g._request)(this.fetch,"GET",o,{headers:this.headers,jwt:(s=(r=u.session)===null||r===void 0?void 0:r.access_token)!==null&&s!==void 0?s:void 0})});if(d)throw d;if((0,z.isBrowser)()&&!((a=e.options)===null||a===void 0?void 0:a.skipBrowserRedirect))window.location.assign(t===null||t===void 0?void 0:t.url);return{data:{provider:e.provider,url:t===null||t===void 0?void 0:t.url},error:null}}catch(t){if((0,X.isAuthError)(t))return{data:{provider:e.provider,url:null},error:t};throw t}}async linkIdentityIdToken(e){return await this._useSession(async(a)=>{var t;try{let{error:d,data:{session:l}}=a;if(d)throw d;let{options:i,provider:n,token:p,access_token:r,nonce:s}=e,u=await(0,g._request)(this.fetch,"POST",`${this.url}/token?grant_type=id_token`,{headers:this.headers,jwt:(t=l===null||l===void 0?void 0:l.access_token)!==null&&t!==void 0?t:void 0,body:{provider:n,id_token:p,access_token:r,nonce:s,link_identity:!0,gotrue_meta_security:{captcha_token:i===null||i===void 0?void 0:i.captchaToken}},xform:g._sessionResponse}),{data:m,error:o}=u;if(o)return{data:{user:null,session:null},error:o};else if(!m||!m.session||!m.user)return{data:{user:null,session:null},error:new X.AuthInvalidTokenResponseError};if(m.session)await this._saveSession(m.session),await this._notifyAllSubscribers("USER_UPDATED",m.session);return{data:m,error:o}}catch(d){if((0,X.isAuthError)(d))return{data:{user:null,session:null},error:d};throw d}})}async unlinkIdentity(e){try{return await this._useSession(async(a)=>{var t,d;let{data:l,error:i}=a;if(i)throw i;return await(0,g._request)(this.fetch,"DELETE",`${this.url}/user/identities/${e.identity_id}`,{headers:this.headers,jwt:(d=(t=l.session)===null||t===void 0?void 0:t.access_token)!==null&&d!==void 0?d:void 0})})}catch(a){if((0,X.isAuthError)(a))return{data:null,error:a};throw a}}async _refreshAccessToken(e){let a=`#_refreshAccessToken(${e.substring(0,5)}...)`;this._debug(a,"begin");try{let t=Date.now();return await(0,z.retryable)(async(d)=>{if(d>0)await(0,z.sleep)(200*Math.pow(2,d-1));return this._debug(a,"refreshing attempt",d),await(0,g._request)(this.fetch,"POST",`${this.url}/token?grant_type=refresh_token`,{body:{refresh_token:e},headers:this.headers,xform:g._sessionResponse})},(d,l)=>{let i=200*Math.pow(2,d);return l&&(0,X.isAuthRetryableFetchError)(l)&&Date.now()+i-t<re.AUTO_REFRESH_TICK_DURATION_MS})}catch(t){if(this._debug(a,"error",t),(0,X.isAuthError)(t))return{data:{session:null,user:null},error:t};throw t}finally{this._debug(a,"end")}}_isValidSession(e){return typeof e==="object"&&e!==null&&"access_token"in e&&"refresh_token"in e&&"expires_at"in e}async _handleProviderSignIn(e,a){let t=await this._getUrlForProvider(`${this.url}/authorize`,e,{redirectTo:a.redirectTo,scopes:a.scopes,queryParams:a.queryParams});if(this._debug("#_handleProviderSignIn()","provider",e,"options",a,"url",t),(0,z.isBrowser)()&&!a.skipBrowserRedirect)window.location.assign(t);return{data:{provider:e,url:t},error:null}}async _recoverAndRefresh(){var e,a;let t="#_recoverAndRefresh()";this._debug("#_recoverAndRefresh()","begin");try{let d=await(0,z.getItemAsync)(this.storage,this.storageKey);if(d&&this.userStorage){let i=await(0,z.getItemAsync)(this.userStorage,this.storageKey+"-user");if(!this.storage.isServer&&Object.is(this.storage,this.userStorage)&&!i)i={user:d.user},await(0,z.setItemAsync)(this.userStorage,this.storageKey+"-user",i);d.user=(e=i===null||i===void 0?void 0:i.user)!==null&&e!==void 0?e:(0,z.userNotAvailableProxy)()}else if(d&&!d.user){if(!d.user){let i=await(0,z.getItemAsync)(this.storage,this.storageKey+"-user");if(i&&(i===null||i===void 0?void 0:i.user))d.user=i.user,await(0,z.removeItemAsync)(this.storage,this.storageKey+"-user"),await(0,z.setItemAsync)(this.storage,this.storageKey,d);else d.user=(0,z.userNotAvailableProxy)()}}if(this._debug("#_recoverAndRefresh()","session from storage",d),!this._isValidSession(d)){if(this._debug("#_recoverAndRefresh()","session is not valid"),d!==null)await this._removeSession();return}let l=((a=d.expires_at)!==null&&a!==void 0?a:1/0)*1000-Date.now()<re.EXPIRY_MARGIN_MS;if(this._debug("#_recoverAndRefresh()",`session has${l?"":" not"} expired with margin of ${re.EXPIRY_MARGIN_MS}s`),l){if(this.autoRefreshToken&&d.refresh_token){let{error:i}=await this._callRefreshToken(d.refresh_token);if(i){if(console.error(i),!(0,X.isAuthRetryableFetchError)(i))this._debug("#_recoverAndRefresh()","refresh failed with a non-retryable error, removing the session",i),await this._removeSession()}}}else if(d.user&&d.user.__isUserNotAvailableProxy===!0)try{let{data:i,error:n}=await this._getUser(d.access_token);if(!n&&(i===null||i===void 0?void 0:i.user))d.user=i.user,await this._saveSession(d),await this._notifyAllSubscribers("SIGNED_IN",d);else this._debug("#_recoverAndRefresh()","could not get user data, skipping SIGNED_IN notification")}catch(i){console.error("Error getting user data:",i),this._debug("#_recoverAndRefresh()","error getting user data, skipping SIGNED_IN notification",i)}else await this._notifyAllSubscribers("SIGNED_IN",d)}catch(d){this._debug("#_recoverAndRefresh()","error",d),console.error(d);return}finally{this._debug("#_recoverAndRefresh()","end")}}async _callRefreshToken(e){var a,t;if(!e)throw new X.AuthSessionMissingError;if(this.refreshingDeferred)return this.refreshingDeferred.promise;let d=`#_callRefreshToken(${e.substring(0,5)}...)`;this._debug(d,"begin");try{this.refreshingDeferred=new z.Deferred;let{data:l,error:i}=await this._refreshAccessToken(e);if(i)throw i;if(!l.session)throw new X.AuthSessionMissingError;await this._saveSession(l.session),await this._notifyAllSubscribers("TOKEN_REFRESHED",l.session);let n={data:l.session,error:null};return this.refreshingDeferred.resolve(n),n}catch(l){if(this._debug(d,"error",l),(0,X.isAuthError)(l)){let i={data:null,error:l};if(!(0,X.isAuthRetryableFetchError)(l))await this._removeSession();return(a=this.refreshingDeferred)===null||a===void 0||a.resolve(i),i}throw(t=this.refreshingDeferred)===null||t===void 0||t.reject(l),l}finally{this.refreshingDeferred=null,this._debug(d,"end")}}async _notifyAllSubscribers(e,a,t=!0){let d=`#_notifyAllSubscribers(${e})`;this._debug(d,"begin",a,`broadcast = ${t}`);try{if(this.broadcastChannel&&t)this.broadcastChannel.postMessage({event:e,session:a});let l=[],i=Array.from(this.stateChangeEmitters.values()).map(async(n)=>{try{await n.callback(e,a)}catch(p){l.push(p)}});if(await Promise.all(i),l.length>0){for(let n=0;n<l.length;n+=1)console.error(l[n]);throw l[0]}}finally{this._debug(d,"end")}}async _saveSession(e){this._debug("#_saveSession()",e),this.suppressGetSessionWarning=!0;let a=Object.assign({},e),t=a.user&&a.user.__isUserNotAvailableProxy===!0;if(this.userStorage){if(!t&&a.user)await(0,z.setItemAsync)(this.userStorage,this.storageKey+"-user",{user:a.user});let d=Object.assign({},a);delete d.user;let l=(0,z.deepClone)(d);await(0,z.setItemAsync)(this.storage,this.storageKey,l)}else{let d=(0,z.deepClone)(a);await(0,z.setItemAsync)(this.storage,this.storageKey,d)}}async _removeSession(){if(this._debug("#_removeSession()"),await(0,z.removeItemAsync)(this.storage,this.storageKey),await(0,z.removeItemAsync)(this.storage,this.storageKey+"-code-verifier"),await(0,z.removeItemAsync)(this.storage,this.storageKey+"-user"),this.userStorage)await(0,z.removeItemAsync)(this.userStorage,this.storageKey+"-user");await this._notifyAllSubscribers("SIGNED_OUT",null)}_removeVisibilityChangedCallback(){this._debug("#_removeVisibilityChangedCallback()");let e=this.visibilityChangedCallback;this.visibilityChangedCallback=null;try{if(e&&(0,z.isBrowser)()&&(window===null||window===void 0?void 0:window.removeEventListener))window.removeEventListener("visibilitychange",e)}catch(a){console.error("removing visibilitychange callback failed",a)}}async _startAutoRefresh(){await this._stopAutoRefresh(),this._debug("#_startAutoRefresh()");let e=setInterval(()=>this._autoRefreshTokenTick(),re.AUTO_REFRESH_TICK_DURATION_MS);if(this.autoRefreshTicker=e,e&&typeof e==="object"&&typeof e.unref==="function")e.unref();else if(typeof Deno<"u"&&typeof Deno.unrefTimer==="function")Deno.unrefTimer(e);setTimeout(async()=>{await this.initializePromise,await this._autoRefreshTokenTick()},0)}async _stopAutoRefresh(){this._debug("#_stopAutoRefresh()");let e=this.autoRefreshTicker;if(this.autoRefreshTicker=null,e)clearInterval(e)}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(a)=>{let{data:{session:t}}=a;if(!t||!t.refresh_token||!t.expires_at){this._debug("#_autoRefreshTokenTick()","no session");return}let d=Math.floor((t.expires_at*1000-e)/re.AUTO_REFRESH_TICK_DURATION_MS);if(this._debug("#_autoRefreshTokenTick()",`access token expires in ${d} ticks, a tick lasts ${re.AUTO_REFRESH_TICK_DURATION_MS}ms, refresh threshold is ${re.AUTO_REFRESH_TICK_THRESHOLD} ticks`),d<=re.AUTO_REFRESH_TICK_THRESHOLD)await this._callRefreshToken(t.refresh_token)})}catch(a){console.error("Auto refresh tick failed with error. This is likely a transient error.",a)}}finally{this._debug("#_autoRefreshTokenTick()","end")}})}catch(e){if(e.isAcquireTimeout||e instanceof fi.LockAcquireTimeoutError)this._debug("auto refresh token tick lock not available");else throw e}}async _handleVisibilityChange(){if(this._debug("#_handleVisibilityChange()"),!(0,z.isBrowser)()||!(window===null||window===void 0?void 0:window.addEventListener)){if(this.autoRefreshToken)this.startAutoRefresh();return!1}try{this.visibilityChangedCallback=async()=>await this._onVisibilityChanged(!1),window===null||window===void 0||window.addEventListener("visibilitychange",this.visibilityChangedCallback),await this._onVisibilityChanged(!0)}catch(e){console.error("_handleVisibilityChange",e)}}async _onVisibilityChanged(e){let a=`#_onVisibilityChanged(${e})`;if(this._debug(a,"visibilityState",document.visibilityState),document.visibilityState==="visible"){if(this.autoRefreshToken)this._startAutoRefresh();if(!e)await this.initializePromise,await this._acquireLock(-1,async()=>{if(document.visibilityState!=="visible"){this._debug(a,"acquired the lock to recover the session, but the browser visibilityState is no longer visible, aborting");return}await this._recoverAndRefresh()})}else if(document.visibilityState==="hidden"){if(this.autoRefreshToken)this._stopAutoRefresh()}}async _getUrlForProvider(e,a,t){let d=[`provider=${encodeURIComponent(a)}`];if(t===null||t===void 0?void 0:t.redirectTo)d.push(`redirect_to=${encodeURIComponent(t.redirectTo)}`);if(t===null||t===void 0?void 0:t.scopes)d.push(`scopes=${encodeURIComponent(t.scopes)}`);if(this.flowType==="pkce"){let[l,i]=await(0,z.getCodeChallengeAndMethod)(this.storage,this.storageKey),n=new URLSearchParams({code_challenge:`${encodeURIComponent(l)}`,code_challenge_method:`${encodeURIComponent(i)}`});d.push(n.toString())}if(t===null||t===void 0?void 0:t.queryParams){let l=new URLSearchParams(t.queryParams);d.push(l.toString())}if(t===null||t===void 0?void 0:t.skipBrowserRedirect)d.push(`skip_http_redirect=${t.skipBrowserRedirect}`);return`${e}?${d.join("&")}`}async _unenroll(e){try{return await this._useSession(async(a)=>{var t;let{data:d,error:l}=a;if(l)return{data:null,error:l};return await(0,g._request)(this.fetch,"DELETE",`${this.url}/factors/${e.factorId}`,{headers:this.headers,jwt:(t=d===null||d===void 0?void 0:d.session)===null||t===void 0?void 0:t.access_token})})}catch(a){if((0,X.isAuthError)(a))return{data:null,error:a};throw a}}async _enroll(e){try{return await this._useSession(async(a)=>{var t,d;let{data:l,error:i}=a;if(i)return{data:null,error:i};let n=Object.assign({friendly_name:e.friendlyName,factor_type:e.factorType},e.factorType==="phone"?{phone:e.phone}:e.factorType==="totp"?{issuer:e.issuer}:{}),{data:p,error:r}=await(0,g._request)(this.fetch,"POST",`${this.url}/factors`,{body:n,headers:this.headers,jwt:(t=l===null||l===void 0?void 0:l.session)===null||t===void 0?void 0:t.access_token});if(r)return{data:null,error:r};if(e.factorType==="totp"&&p.type==="totp"&&((d=p===null||p===void 0?void 0:p.totp)===null||d===void 0?void 0:d.qr_code))p.totp.qr_code=`data:image/svg+xml;utf-8,${p.totp.qr_code}`;return{data:p,error:null}})}catch(a){if((0,X.isAuthError)(a))return{data:null,error:a};throw a}}async _verify(e){return this._acquireLock(-1,async()=>{try{return await this._useSession(async(a)=>{var t;let{data:d,error:l}=a;if(l)return{data:null,error:l};let i=Object.assign({challenge_id:e.challengeId},"webauthn"in e?{webauthn:Object.assign(Object.assign({},e.webauthn),{credential_response:e.webauthn.type==="create"?(0,C1.serializeCredentialCreationResponse)(e.webauthn.credential_response):(0,C1.serializeCredentialRequestResponse)(e.webauthn.credential_response)})}:{code:e.code}),{data:n,error:p}=await(0,g._request)(this.fetch,"POST",`${this.url}/factors/${e.factorId}/verify`,{body:i,headers:this.headers,jwt:(t=d===null||d===void 0?void 0:d.session)===null||t===void 0?void 0:t.access_token});if(p)return{data:null,error:p};return await this._saveSession(Object.assign({expires_at:Math.round(Date.now()/1000)+n.expires_in},n)),await this._notifyAllSubscribers("MFA_CHALLENGE_VERIFIED",n),{data:n,error:p}})}catch(a){if((0,X.isAuthError)(a))return{data:null,error:a};throw a}})}async _challenge(e){return this._acquireLock(-1,async()=>{try{return await this._useSession(async(a)=>{var t;let{data:d,error:l}=a;if(l)return{data:null,error:l};let i=await(0,g._request)(this.fetch,"POST",`${this.url}/factors/${e.factorId}/challenge`,{body:e,headers:this.headers,jwt:(t=d===null||d===void 0?void 0:d.session)===null||t===void 0?void 0:t.access_token});if(i.error)return i;let{data:n}=i;if(n.type!=="webauthn")return{data:n,error:null};switch(n.webauthn.type){case"create":return{data:Object.assign(Object.assign({},n),{webauthn:Object.assign(Object.assign({},n.webauthn),{credential_options:Object.assign(Object.assign({},n.webauthn.credential_options),{publicKey:(0,C1.deserializeCredentialCreationOptions)(n.webauthn.credential_options.publicKey)})})}),error:null};case"request":return{data:Object.assign(Object.assign({},n),{webauthn:Object.assign(Object.assign({},n.webauthn),{credential_options:Object.assign(Object.assign({},n.webauthn.credential_options),{publicKey:(0,C1.deserializeCredentialRequestOptions)(n.webauthn.credential_options.publicKey)})})}),error:null}}})}catch(a){if((0,X.isAuthError)(a))return{data:null,error:a};throw a}})}async _challengeAndVerify(e){let{data:a,error:t}=await this._challenge({factorId:e.factorId});if(t)return{data:null,error:t};return await this._verify({factorId:e.factorId,challengeId:a.id,code:e.code})}async _listFactors(){var e;let{data:{user:a},error:t}=await this.getUser();if(t)return{data:null,error:t};let d={all:[],phone:[],totp:[],webauthn:[]};for(let l of(e=a===null||a===void 0?void 0:a.factors)!==null&&e!==void 0?e:[])if(d.all.push(l),l.status==="verified")d[l.factor_type].push(l);return{data:d,error:null}}async _getAuthenticatorAssuranceLevel(){return this._acquireLock(-1,async()=>{return await this._useSession(async(e)=>{var a,t;let{data:{session:d},error:l}=e;if(l)return{data:null,error:l};if(!d)return{data:{currentLevel:null,nextLevel:null,currentAuthenticationMethods:[]},error:null};let{payload:i}=(0,z.decodeJWT)(d.access_token),n=null;if(i.aal)n=i.aal;let p=n;if(((t=(a=d.user.factors)===null||a===void 0?void 0:a.filter((u)=>u.status==="verified"))!==null&&t!==void 0?t:[]).length>0)p="aal2";let s=i.amr||[];return{data:{currentLevel:n,nextLevel:p,currentAuthenticationMethods:s},error:null}})})}async fetchJwk(e,a={keys:[]}){let t=a.keys.find((n)=>n.kid===e);if(t)return t;let d=Date.now();if(t=this.jwks.keys.find((n)=>n.kid===e),t&&this.jwks_cached_at+re.JWKS_TTL>d)return t;let{data:l,error:i}=await(0,g._request)(this.fetch,"GET",`${this.url}/.well-known/jwks.json`,{headers:this.headers});if(i)throw i;if(!l.keys||l.keys.length===0)return null;if(this.jwks=l,this.jwks_cached_at=d,t=l.keys.find((n)=>n.kid===e),!t)return null;return t}async getClaims(e,a={}){try{let t=e;if(!t){let{data:o,error:h}=await this.getSession();if(h||!o.session)return{data:null,error:h};t=o.session.access_token}let{header:d,payload:l,signature:i,raw:{header:n,payload:p}}=(0,z.decodeJWT)(t);if(!(a===null||a===void 0?void 0:a.allowExpired))(0,z.validateExp)(l.exp);let r=!d.alg||d.alg.startsWith("HS")||!d.kid||!(("crypto"in globalThis)&&("subtle"in globalThis.crypto))?null:await this.fetchJwk(d.kid,(a===null||a===void 0?void 0:a.keys)?{keys:a.keys}:a===null||a===void 0?void 0:a.jwks);if(!r){let{error:o}=await this.getUser(t);if(o)throw o;return{data:{claims:l,header:d,signature:i},error:null}}let s=(0,z.getAlgorithm)(d.alg),u=await crypto.subtle.importKey("jwk",r,s,!0,["verify"]);if(!await crypto.subtle.verify(s,u,i,(0,hi.stringToUint8Array)(`${n}.${p}`)))throw new X.AuthInvalidJwtError("Invalid JWT signature");return{data:{claims:l,header:d,signature:i},error:null}}catch(t){if((0,X.isAuthError)(t))return{data:null,error:t};throw t}}}M1.nextInstanceID=0;I1.default=M1});var vi=f((j1)=>{var I8=j1&&j1.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(j1,"__esModule",{value:!0});var j8=I8(Xa()),L8=j8.default;j1.default=L8});var wi=f((L1)=>{var P8=L1&&L1.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(L1,"__esModule",{value:!0});var A8=P8(Wt()),F8=A8.default;L1.default=F8});var Ot=f((W)=>{var K8=W&&W.__createBinding||(Object.create?function(e,a,t,d){if(d===void 0)d=t;var l=Object.getOwnPropertyDescriptor(a,t);if(!l||("get"in l?!a.__esModule:l.writable||l.configurable))l={enumerable:!0,get:function(){return a[t]}};Object.defineProperty(e,d,l)}:function(e,a,t,d){if(d===void 0)d=t;e[d]=a[t]}),Xi=W&&W.__exportStar||function(e,a){for(var t in e)if(t!=="default"&&!Object.prototype.hasOwnProperty.call(a,t))K8(a,e,t)},Ja=W&&W.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(W,"__esModule",{value:!0});W.processLock=W.lockInternals=W.NavigatorLockAcquireTimeoutError=W.navigatorLock=W.AuthClient=W.AuthAdminApi=W.GoTrueClient=W.GoTrueAdminApi=void 0;var e5=Ja(Xa());W.GoTrueAdminApi=e5.default;var a5=Ja(Wt());W.GoTrueClient=a5.default;var t5=Ja(vi());W.AuthAdminApi=t5.default;var d5=Ja(wi());W.AuthClient=d5.default;Xi(Qt(),W);Xi(Pe(),W);var ba=xt();Object.defineProperty(W,"navigatorLock",{enumerable:!0,get:function(){return ba.navigatorLock}});Object.defineProperty(W,"NavigatorLockAcquireTimeoutError",{enumerable:!0,get:function(){return ba.NavigatorLockAcquireTimeoutError}});Object.defineProperty(W,"lockInternals",{enumerable:!0,get:function(){return ba.internals}});Object.defineProperty(W,"processLock",{enumerable:!0,get:function(){return ba.processLock}})});var Ji=f((yi)=>{Object.defineProperty(yi,"__esModule",{value:!0});yi.SupabaseAuthClient=void 0;var l5=Ot();class zi extends l5.AuthClient{constructor(e){super(e)}}yi.SupabaseAuthClient=zi});var $t=f((P1)=>{var i5=P1&&P1.__awaiter||function(e,a,t,d){function l(i){return i instanceof t?i:new t(function(n){n(i)})}return new(t||(t=Promise))(function(i,n){function p(u){try{s(d.next(u))}catch(m){n(m)}}function r(u){try{s(d.throw(u))}catch(m){n(m)}}function s(u){u.done?i(u.value):l(u.value).then(p,r)}s((d=d.apply(e,a||[])).next())})};Object.defineProperty(P1,"__esModule",{value:!0});var n5=_a(),p5=pt(),r5=wt(),s5=l2(),Ga=m2(),u5=c2(),bi=f2(),m5=Ji();class Gi{constructor(e,a,t){var d,l,i;this.supabaseUrl=e,this.supabaseKey=a;let n=(0,bi.validateSupabaseUrl)(e);if(!a)throw Error("supabaseKey is required.");this.realtimeUrl=new URL("realtime/v1",n),this.realtimeUrl.protocol=this.realtimeUrl.protocol.replace("http","ws"),this.authUrl=new URL("auth/v1",n),this.storageUrl=new URL("storage/v1",n),this.functionsUrl=new URL("functions/v1",n);let p=`sb-${n.hostname.split(".")[0]}-auth-token`,r={db:Ga.DEFAULT_DB_OPTIONS,realtime:Ga.DEFAULT_REALTIME_OPTIONS,auth:Object.assign(Object.assign({},Ga.DEFAULT_AUTH_OPTIONS),{storageKey:p}),global:Ga.DEFAULT_GLOBAL_OPTIONS},s=(0,bi.applySettingDefaults)(t!==null&&t!==void 0?t:{},r);if(this.storageKey=(d=s.auth.storageKey)!==null&&d!==void 0?d:"",this.headers=(l=s.global.headers)!==null&&l!==void 0?l:{},!s.accessToken)this.auth=this._initSupabaseAuthClient((i=s.auth)!==null&&i!==void 0?i:{},this.headers,s.global.fetch);else this.accessToken=s.accessToken,this.auth=new Proxy({},{get:(u,m)=>{throw Error(`@supabase/supabase-js: Supabase Client is configured with the accessToken option, accessing supabase.auth.${String(m)} is not possible`)}});if(this.fetch=(0,u5.fetchWithAuth)(a,this._getAccessToken.bind(this),s.global.fetch),this.realtime=this._initRealtimeClient(Object.assign({headers:this.headers,accessToken:this._getAccessToken.bind(this)},s.realtime)),this.rest=new p5.PostgrestClient(new URL("rest/v1",n).href,{headers:this.headers,schema:s.db.schema,fetch:this.fetch}),this.storage=new s5.StorageClient(this.storageUrl.href,this.headers,this.fetch,t===null||t===void 0?void 0:t.storage),!s.accessToken)this._listenForAuthEvents()}get functions(){return new n5.FunctionsClient(this.functionsUrl.href,{headers:this.headers,customFetch:this.fetch})}from(e){return this.rest.from(e)}schema(e){return this.rest.schema(e)}rpc(e,a={},t={head:!1,get:!1,count:void 0}){return this.rest.rpc(e,a,t)}channel(e,a={config:{}}){return this.realtime.channel(e,a)}getChannels(){return this.realtime.getChannels()}removeChannel(e){return this.realtime.removeChannel(e)}removeAllChannels(){return this.realtime.removeAllChannels()}_getAccessToken(){return i5(this,void 0,void 0,function*(){var e,a;if(this.accessToken)return yield this.accessToken();let{data:t}=yield this.auth.getSession();return(a=(e=t.session)===null||e===void 0?void 0:e.access_token)!==null&&a!==void 0?a:this.supabaseKey})}_initSupabaseAuthClient({autoRefreshToken:e,persistSession:a,detectSessionInUrl:t,storage:d,userStorage:l,storageKey:i,flowType:n,lock:p,debug:r},s,u){let m={Authorization:`Bearer ${this.supabaseKey}`,apikey:`${this.supabaseKey}`};return new m5.SupabaseAuthClient({url:this.authUrl.href,headers:Object.assign(Object.assign({},m),s),storageKey:i,autoRefreshToken:e,persistSession:a,detectSessionInUrl:t,storage:d,userStorage:l,flowType:n,lock:p,debug:r,fetch:u,hasCustomAuthorizationHeader:Object.keys(this.headers).some((o)=>o.toLowerCase()==="authorization")})}_initRealtimeClient(e){return new r5.RealtimeClient(this.realtimeUrl.href,Object.assign(Object.assign({},e),{params:Object.assign({apikey:this.supabaseKey},e===null||e===void 0?void 0:e.params)}))}_listenForAuthEvents(){return this.auth.onAuthStateChange((a,t)=>{this._handleTokenChanged(a,"CLIENT",t===null||t===void 0?void 0:t.access_token)})}_handleTokenChanged(e,a,t){if((e==="TOKEN_REFRESHED"||e==="SIGNED_IN")&&this.changedAccessToken!==t)this.changedAccessToken=t,this.realtime.setAuth(t);else if(e==="SIGNED_OUT"){if(this.realtime.setAuth(),a=="STORAGE")this.auth.signOut();this.changedAccessToken=void 0}}}P1.default=Gi});var Ni=f((O)=>{var o5=O&&O.__createBinding||(Object.create?function(e,a,t,d){if(d===void 0)d=t;var l=Object.getOwnPropertyDescriptor(a,t);if(!l||("get"in l?!a.__esModule:l.writable||l.configurable))l={enumerable:!0,get:function(){return a[t]}};Object.defineProperty(e,d,l)}:function(e,a,t,d){if(d===void 0)d=t;e[d]=a[t]}),Hi=O&&O.__exportStar||function(e,a){for(var t in e)if(t!=="default"&&!Object.prototype.hasOwnProperty.call(a,t))o5(a,e,t)},Si=O&&O.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(O,"__esModule",{value:!0});O.createClient=O.SupabaseClient=O.FunctionRegion=O.FunctionsError=O.FunctionsRelayError=O.FunctionsFetchError=O.FunctionsHttpError=O.PostgrestError=void 0;var c5=Si($t());Hi(Ot(),O);var Y5=pt();Object.defineProperty(O,"PostgrestError",{enumerable:!0,get:function(){return Y5.PostgrestError}});var A1=_a();Object.defineProperty(O,"FunctionsHttpError",{enumerable:!0,get:function(){return A1.FunctionsHttpError}});Object.defineProperty(O,"FunctionsFetchError",{enumerable:!0,get:function(){return A1.FunctionsFetchError}});Object.defineProperty(O,"FunctionsRelayError",{enumerable:!0,get:function(){return A1.FunctionsRelayError}});Object.defineProperty(O,"FunctionsError",{enumerable:!0,get:function(){return A1.FunctionsError}});Object.defineProperty(O,"FunctionRegion",{enumerable:!0,get:function(){return A1.FunctionRegion}});Hi(wt(),O);var f5=$t();Object.defineProperty(O,"SupabaseClient",{enumerable:!0,get:function(){return Si(f5).default}});var h5=(e,a,t)=>{return new c5.default(e,a,t)};O.createClient=h5;function Z5(){if(typeof window<"u")return!1;if(typeof process>"u")return!1;let e=process.version;if(e===void 0||e===null)return!1;let a=e.match(/^v(\d+)\./);if(!a)return!1;return parseInt(a[1],10)<=18}if(Z5())console.warn("⚠️ 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")});var ld=Z1(dd(),1),{program:q5,createCommand:T5,createArgument:W5,createOption:O5,CommanderError:$5,InvalidArgumentError:R5,InvalidOptionArgumentError:E5,Command:id,Argument:_5,Option:U5,Help:B5}=ld.default;var nd="0.1.4";var pd=nd;var w=Z1(ta(),1);var F=(e)=>({value:e,success:!0}),ae=(e)=>({error:e,success:!1});async function*ud(e,a="NONEXISTANT_SCHEMA_THAT_SHOULDNT_EXIST"){yield{type:"schemas_fetch_started",data:{}};let{data:t,error:d}=await e.schema(a).from("").select();if(t)return ae(Error("Schema exists, this shouldn't happen"));let l=d?.message.split("following: ")[1]?.split(",").map((i)=>i.trim())??[];return yield{type:"schemas_discovered",data:{schemas:l}},F(l)}async function Ra(e,a){let{data:t,error:d}=await e.schema(a).from("").select();if(d)return ae(d);return F(t)}async function*md(e,a){yield{type:"swagger_fetch_started",data:{schema:a}};let t=await Ra(e,a);if(!t.success)return ae(t.error);yield{type:"swagger_fetched",data:{schema:a}};let d=Object.keys(t.value.paths).filter((l)=>!l.startsWith("/rpc/")).map((l)=>l.slice(1)).filter((l)=>!!l);return yield{type:"tables_discovered",data:{schema:a,tables:d}},F(d)}async function*od(e,a){yield{type:"swagger_fetch_started",data:{schema:a}};let t=await Ra(e,a);if(!t.success)return ae(t.error);yield{type:"swagger_fetched",data:{schema:a}};let d=Object.keys(t.value.paths).filter((l)=>l.startsWith("/rpc/")).map((l)=>l.slice(1));return yield{type:"rpcs_discovered",data:{schema:a,rpcs:d}},F(d)}async function cd(e,a){let t=await Ra(e,a);if(!t.success)return ae(t.error);let d=[];return Object.entries(t.value.paths).forEach(([l,i])=>{if(l.startsWith("/rpc/")){let n=l.slice(1),p=i.post;if(p&&p.parameters){let r=[];p.parameters.forEach((s)=>{if(s.in==="body"&&s.schema&&s.schema.properties){let u=s.schema.required||[];Object.entries(s.schema.properties).forEach(([m,o])=>{r.push({name:m,type:o.type||"unknown",format:o.format,required:u.includes(m),description:o.description})})}}),d.push({name:n,parameters:r})}}}),F(d)}async function Yd(e,a,t,d={},l={get:!1,explain:!1}){try{let i=e.schema(a).rpc(t,d);if(l.limit&&!l.explain)i=i.limit(l.limit);let{data:n,error:p}=l.explain?await i.explain({analyze:!0,format:"text",verbose:!0,settings:!0,wal:!0,buffers:!0}):await i;if(p)return ae(Error(`RPC call failed: ${p.message}`));return F(n)}catch(i){return ae(Error(`RPC call exception: ${i instanceof Error?i.message:String(i)}`))}}async function*qn(e,a,t){yield{type:"table_access_test_started",data:{schema:a,table:t}};let{data:d,error:l}=await e.schema(a).from(t).select("*").limit(1);if(l){let p={status:"denied",accessible:!1,hasData:!1};return yield{type:"table_access_test_completed",data:{schema:a,table:t,result:p}},F(p)}if(d&&d.length>0){let{count:p}=await e.schema(a).from(t).select("*",{count:"estimated",head:!0}),r={status:"readable",accessible:!0,hasData:!0,rowCount:p??void 0};return yield{type:"table_access_test_completed",data:{schema:a,table:t,result:r}},F(r)}let n={status:"empty",accessible:!0,hasData:!1,rowCount:0};return yield{type:"table_access_test_completed",data:{schema:a,table:t,result:n}},F(n)}async function*fd(e,a,t){let d={};for(let l of t){let i=qn(e,a,l),n={status:"denied",accessible:!1,hasData:!1};while(!0){let p=await i.next();if(p.done){if(p.value&&p.value.success)n=p.value.value;break}yield p.value}d[l]=n}return F(d)}async function hd(e,a,t,d=10){let{data:l,error:i,count:n}=await e.schema(a).from(t).select("*",{count:"exact"}).limit(d);if(i)return ae(i);let p=l&&l.length>0?Object.keys(l[0]??{}):[];return F({columns:p,rows:l??[],count:n??0})}async function*Zd(e,a,t,d={}){yield{type:"analysis_started",data:{}};let l=ud(e),i;while(!0){let u=await l.next();if(u.done){i=u.value;break}yield u.value}if(!i||!i.success)return ae(i?.error??Error("Failed to fetch schemas"));let n=d.schema?[d.schema]:i.value,p={};for(let u of n){yield{type:"schema_analysis_started",data:{schema:u}};let m=md(e,u),o;while(!0){let S=await m.next();if(S.done){o=S.value;break}yield S.value}let h=od(e,u),c;while(!0){let S=await h.next();if(S.done){c=S.value;break}yield S.value}let Y=await cd(e,u);if(!o?.success||!c?.success)continue;let y=o.value,v=fd(e,u,y),Z;while(!0){let S=await v.next();if(S.done){Z=S.value;break}yield S.value}if(!Z?.success)continue;let b={tables:y,rpcs:c.value,rpcFunctions:Y.success?Y.value:[],tableAccess:Z.value};p[u]=b,yield{type:"schema_analysis_completed",data:{schema:u,analysis:b}}}let r=await Tn(e,a,t),s={schemas:i.value,schemaDetails:p,summary:r};return yield{type:"analysis_completed",data:{result:s}},F(s)}async function Tn(e,a,t){let d=Wn(a),l=On(t),i=$n(a),n=await Rn(e),p={...i,...n};return{domain:d,jwtInfo:l,metadata:p}}function Wn(e){try{return new URL(e).hostname}catch{return e}}function On(e){try{let a=e.split(".");if(a.length!==3)return;let t=a[1];if(!t)return;let d=atob(t.replace(/-/g,"+").replace(/_/g,"/"));return JSON.parse(d)}catch{return}}function $n(e){let a={};try{let t=new URL(e);if(a.protocol=t.protocol,a.port=t.port||(t.protocol==="https:"?"443":"80"),t.hostname.includes(".supabase.co")){a.service="Supabase";let d=t.hostname.replace(".supabase.co","");a.region=d}}catch{}return a}async function Rn(e){try{let{data:a,error:t}=await e.schema("public").from("").select();if(t)return{};let d=a,l={};if(d.info&&typeof d.info==="object"){let i=d.info;l.title=i.title,l.description=i.description,l.version=i.version}return l}catch{return{}}}var a1=Z1(ta(),1),w1=(e,a,...t)=>{let d=[a,...t].map((l)=>typeof l==="object"?JSON.stringify(l):String(l)).join(" ");return`${e} ${d}`},x={debug:(e,...a)=>{console.error(w1(a1.default.gray("[DEBUG]"),e,...a))},info:(e,...a)=>console.error(w1(a1.default.blue("[INFO]"),e,...a)),success:(e,...a)=>console.error(w1(a1.default.green("[OK]"),e,...a)),warn:(e,...a)=>console.error(w1(a1.default.yellow("[WARN]"),e,...a)),error:(e,...a)=>console.error(w1(a1.default.red("[ERROR]"),e,...a))},wd=!1,Xd=(e)=>{wd=e},vd={value:!1},zd=()=>{if(!vd.value&&!wd)x.warn("This feature is experimental and may have bugs. You can suppress this with --suppress-experimental-warnings."),vd.value=!0};var te=Z1(ta(),1);function yd(e,a){if(!e.debug)return;switch(a.type){case"schemas_fetch_started":console.error(te.default.gray("[DEBUG] Fetching schemas..."));break;case"schemas_discovered":console.error(te.default.gray(`[DEBUG] Found ${a.data.schemas.length} schemas`));break;case"swagger_fetch_started":console.error(te.default.gray(`[DEBUG] Fetching swagger for schema: ${a.data.schema}`));break;case"tables_discovered":console.error(te.default.gray(`[DEBUG] Found ${a.data.tables.length} tables in ${a.data.schema}`));break;case"rpcs_discovered":console.error(te.default.gray(`[DEBUG] Found ${a.data.rpcs.length} RPCs in ${a.data.schema}`));break;case"table_access_test_started":console.error(te.default.gray(`[DEBUG] Testing read access for ${a.data.schema}.${a.data.table}`));break;case"table_access_test_completed":let t=a.data.result.status==="readable"?`readable with ~${a.data.result.rowCount??"?"} rows (EXPOSED)`:a.data.result.status==="empty"?"returned 0 rows (empty or RLS blocked)":"access denied";console.error(te.default.gray(`[DEBUG] Table ${a.data.table} is ${t}`));break;case"analysis_started":console.error(te.default.gray("[DEBUG] Analysis started"));break;case"schema_analysis_started":console.error(te.default.gray(`[DEBUG] Analyzing schema: ${a.data.schema}`));break;case"schema_analysis_completed":console.error(te.default.gray(`[DEBUG] Completed analysis of schema: ${a.data.schema}`));break;case"extraction_started":console.error(te.default.gray(`[DEBUG] Fetching content from: ${a.data.url}`));break;case"content_fetched":console.error(te.default.gray(`[DEBUG] Fetched ${a.data.size} bytes (${a.data.contentType})`));break;case"html_detected":console.error(te.default.gray(`[DEBUG] Detected HTML content, found ${a.data.scriptCount} scripts`));break;case"script_checking":console.error(te.default.gray(`[DEBUG] Checking script: ${a.data.scriptUrl}`));break;case"credentials_found":console.error(te.default.gray(`[DEBUG] Found credentials in ${a.data.source}`));break}}async function Qd(e,a){let t=Zd(e.client,e.url,e.key,a),d;while(!0){let l=await t.next();if(l.done){d=l.value;break}yd(e,l.value)}if(!d||!d.success)x.error("Analysis failed",d?.error.message??"Unknown error"),process.exit(1);if(e.json)console.log(JSON.stringify(d.value,null,2));else if(e.html){let{buildHtmlReport:l}=await Promise.resolve().then(() => (bd(),Jd)),i=await l(d.value,e.url,e.key),{generateTempFilePath:n,writeHtmlFile:p}=await Promise.resolve().then(() => (Hd(),Gd)),{openInBrowser:r}=await Promise.resolve().then(() => (Nd(),Sd)),s=n();p(s,i),r(s),x.success(`HTML report generated: ${s}`)}else Pn(d.value)}function Pn(e){if(console.log(),console.log(w.default.bold(w.default.cyan("=".repeat(60)))),console.log(w.default.bold(w.default.cyan(" SUPABASE DATABASE ANALYSIS"))),console.log(w.default.bold(w.default.cyan("=".repeat(60)))),console.log(),console.log(w.default.bold(w.default.yellow("TARGET SUMMARY"))),console.log(w.default.dim("-".repeat(20))),console.log(w.default.bold("Domain:"),w.default.white(e.summary.domain)),e.summary.metadata?.service)console.log(w.default.bold("Service:"),w.default.white(e.summary.metadata.service));if(e.summary.metadata?.region)console.log(w.default.bold("Project ID:"),w.default.white(e.summary.metadata.region));if(e.summary.metadata?.title)console.log(w.default.bold("Title:"),w.default.white(e.summary.metadata.title));if(e.summary.metadata?.version)console.log(w.default.bold("Version:"),w.default.white(e.summary.metadata.version));if(e.summary.jwtInfo){if(console.log(),console.log(w.default.bold(w.default.yellow("JWT TOKEN INFO"))),console.log(w.default.dim("-".repeat(20))),e.summary.jwtInfo.iss)console.log(w.default.bold("Issuer:"),w.default.white(e.summary.jwtInfo.iss));if(e.summary.jwtInfo.aud)console.log(w.default.bold("Audience:"),w.default.white(e.summary.jwtInfo.aud));if(e.summary.jwtInfo.role)console.log(w.default.bold("Role:"),w.default.white(e.summary.jwtInfo.role));if(e.summary.jwtInfo.exp){let a=new Date(e.summary.jwtInfo.exp*1000);console.log(w.default.bold("Expires:"),w.default.white(a.toISOString()))}if(e.summary.jwtInfo.iat){let a=new Date(e.summary.jwtInfo.iat*1000);console.log(w.default.bold("Issued:"),w.default.white(a.toISOString()))}}console.log(),console.log(w.default.bold(w.default.cyan("DATABASE ANALYSIS"))),console.log(w.default.dim("-".repeat(20))),console.log(w.default.bold("Schemas discovered:"),w.default.green(e.schemas.length.toString())),console.log(),Object.entries(e.schemaDetails).forEach(([a,t])=>{console.log(w.default.bold(w.default.cyan(`Schema: ${a}`))),console.log();let d=Object.values(t.tableAccess).filter((n)=>n.status==="readable").length,l=Object.values(t.tableAccess).filter((n)=>n.status==="denied").length,i=Object.values(t.tableAccess).filter((n)=>n.status==="empty").length;if(console.log(w.default.bold("Tables:"),w.default.green(t.tables.length.toString())),console.log(w.default.dim(` ${d} exposed | ${i} empty/protected | ${l} denied`)),console.log(),t.tables.length>0)t.tables.forEach((n)=>{let p=t.tableAccess[n],r="",s="";switch(p?.status){case"readable":r=w.default.green("[+]"),s=w.default.dim(`(~${p.rowCount??"?"} rows exposed)`);break;case"empty":r=w.default.yellow("[-]"),s=w.default.dim("(0 rows - empty or RLS)");break;case"denied":r=w.default.red("[X]"),s=w.default.dim("(access denied)");break}console.log(` ${r} ${w.default.white(n)} ${s}`)});else console.log(w.default.dim(" No tables found"));if(console.log(),console.log(w.default.bold("RPCs:"),w.default.green(t.rpcs.length.toString())),t.rpcFunctions.length>0)t.rpcFunctions.forEach((n)=>{if(console.log(` * ${w.default.white(n.name)}`),n.parameters.length>0)n.parameters.forEach((p)=>{let r=p.required?w.default.red("(required)"):w.default.dim("(optional)"),s=p.format?`${p.type} (${p.format})`:p.type;console.log(` - ${w.default.cyan(p.name)}: ${w.default.yellow(s)} ${r}`)});else console.log(w.default.dim(" No parameters"))});else console.log(w.default.dim(" No RPCs found"));console.log()}),console.log(w.default.bold(w.default.cyan("=".repeat(60)))),console.log()}async function kd(e,a){let t=a.dump.split(".");if(t.length===1){let d=t[0];if(!d)x.error("Invalid dump format. Use schema.table or schema"),process.exit(1);x.info(`Dumping swagger for schema: ${d}`);let{data:l,error:i}=await e.client.schema(d).from("").select();if(i)x.error("Failed to fetch swagger",i.message),process.exit(1);console.log(JSON.stringify(l,null,2));return}if(t.length===2){let d=t[0],l=t[1];if(!d||!l)x.error("Invalid dump format. Use schema.table"),process.exit(1);let i=parseInt(a.limit);if(isNaN(i)||i<=0)x.error("Invalid limit value"),process.exit(1);x.info(`Dumping table: ${d}.${l} (limit: ${i})`);let n=await hd(e.client,d,l,i);if(!n.success)x.error("Failed to dump table",n.error.message),process.exit(1);if(e.json)console.log(JSON.stringify(n.value,null,2));else console.log(`
|
|
200
201
|
Table: ${d}.${l} (${n.value.count} total rows, showing ${n.value.rows.length})
|
|
201
202
|
`),console.table(n.value.rows);return}x.error("Invalid dump format. Use schema.table or schema"),process.exit(1)}var Dd=(e)=>{try{let a=e.replace(/\$([A-Z_][A-Z0-9_]*)/g,(t,d)=>{let l=process.env[d];if(l===void 0)throw Error(`Environment variable ${d} not found`);return JSON.stringify(l)});return JSON.parse(a)}catch(a){throw Error(`Failed to parse RPC arguments: ${a instanceof Error?a.message:String(a)}`)}};async function Vd(e,a){let t=a.rpc.split(".");if(t.length!==2)x.error("Invalid RPC format. Use schema.rpc_name"),process.exit(1);let d=t[0],l=t[1];if(!d||!l)x.error("Invalid RPC format. Use schema.rpc_name"),process.exit(1);let i=a.args?Dd(a.args):{},n=parseInt(a.limit);if(isNaN(n)||n<=0)x.error("Invalid limit value"),process.exit(1);if(x.info(`Calling RPC: ${d}.${l}`),Object.keys(i).length>0)x.info("Arguments:",JSON.stringify(i));let p=await Yd(e.client,d,l,i,{limit:n,explain:a.explain});if(!p.success)x.error("RPC call failed",p.error.message),process.exit(1);if(e.json)console.log(JSON.stringify(p.value,null,2));else if(a.explain)console.log(`
|
|
202
203
|
Query Execution Plan:
|
package/package.json
CHANGED