commerce-kit 0.67.0 → 0.67.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/uploads.js +79 -21
- package/dist/uploads.js.map +1 -1
- package/package.json +4 -2
- package/dist/uploads.d.ts +0 -54
package/dist/uploads.js
CHANGED
|
@@ -1,23 +1,81 @@
|
|
|
1
|
-
var li=Object.create;var qe=Object.defineProperty;var pi=Object.getOwnPropertyDescriptor;var ui=Object.getOwnPropertyNames;var fi=Object.getPrototypeOf,hi=Object.prototype.hasOwnProperty;var mi=(e,t,r)=>t in e?qe(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r;var p=(e,t)=>()=>(e&&(t=e(e=0)),t);var Q=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),ir=(e,t)=>{for(var r in t)qe(e,r,{get:t[r],enumerable:!0})},yn=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of ui(t))!hi.call(e,o)&&o!==r&&qe(e,o,{get:()=>t[o],enumerable:!(n=pi(t,o))||n.enumerable});return e};var Xe=(e,t,r)=>(r=e!=null?li(fi(e)):{},yn(t||!e||!e.__esModule?qe(r,"default",{value:e,enumerable:!0}):r,e)),yi=e=>yn(qe({},"__esModule",{value:!0}),e);var wn=(e,t,r)=>mi(e,typeof t!="symbol"?t+"":t,r);var En=Q((Vc,bn)=>{"use strict";bn.exports=function(t){return t!=null&&t.constructor!=null&&typeof t.constructor.isBuffer=="function"&&t.constructor.isBuffer(t)}});var xn=Q((Gc,An)=>{"use strict";var sr=Object.defineProperty,wi=Object.getOwnPropertyDescriptor,gi=Object.getOwnPropertyNames,bi=Object.prototype.hasOwnProperty,Ei=(e,t)=>{for(var r in t)sr(e,r,{get:t[r],enumerable:!0})},_i=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of gi(t))!bi.call(e,o)&&o!==r&&sr(e,o,{get:()=>t[o],enumerable:!(n=wi(t,o))||n.enumerable});return e},vi=e=>_i(sr({},"__esModule",{value:!0}),e),vn={};Ei(vn,{SYMBOL_FOR_REQ_CONTEXT:()=>Sn,getContext:()=>Si});An.exports=vi(vn);var Sn=Symbol.for("@vercel/request-context");function Si(){return globalThis[Sn]?.get?.()??{}}});var h,O,M=p(()=>{"use strict";h=crypto,O=e=>e instanceof CryptoKey});var Ai,wt,cr=p(()=>{"use strict";M();Ai=async(e,t)=>{let r=`SHA-${e.slice(-3)}`;return new Uint8Array(await h.subtle.digest(r,t))},wt=Ai});function N(...e){let t=e.reduce((o,{length:a})=>o+a,0),r=new Uint8Array(t),n=0;for(let o of e)r.set(o,n),n+=o.length;return r}function Cn(e,t){return N(A.encode(e),new Uint8Array([0]),t)}function dr(e,t,r){if(t<0||t>=gt)throw new RangeError(`value must be >= 0 and <= ${gt-1}. Received ${t}`);e.set([t>>>24,t>>>16,t>>>8,t&255],r)}function bt(e){let t=Math.floor(e/gt),r=e%gt,n=new Uint8Array(8);return dr(n,t,0),dr(n,r,4),n}function Et(e){let t=new Uint8Array(4);return dr(t,e),t}function _t(e){return N(Et(e.length),e)}async function Pn(e,t,r){let n=Math.ceil((t>>3)/32),o=new Uint8Array(n*32);for(let a=0;a<n;a++){let i=new Uint8Array(4+e.length+r.length);i.set(Et(a+1)),i.set(e,4),i.set(r,4+e.length),o.set(await wt("sha256",i),a*32)}return o.slice(0,t>>3)}var A,R,gt,k=p(()=>{"use strict";cr();A=new TextEncoder,R=new TextDecoder,gt=2**32});var vt,x,lr,C,D=p(()=>{"use strict";k();vt=e=>{let t=e;typeof t=="string"&&(t=A.encode(t));let r=32768,n=[];for(let o=0;o<t.length;o+=r)n.push(String.fromCharCode.apply(null,t.subarray(o,o+r)));return btoa(n.join(""))},x=e=>vt(e).replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_"),lr=e=>{let t=atob(e),r=new Uint8Array(t.length);for(let n=0;n<t.length;n++)r[n]=t.charCodeAt(n);return r},C=e=>{let t=e;t instanceof Uint8Array&&(t=R.decode(t)),t=t.replace(/-/g,"+").replace(/_/g,"/").replace(/\s/g,"");try{return lr(t)}catch{throw new TypeError("The input to be decoded is not correctly encoded.")}}});var pr={};ir(pr,{JOSEAlgNotAllowed:()=>ae,JOSEError:()=>H,JOSENotSupported:()=>m,JWEDecryptionFailed:()=>Z,JWEInvalid:()=>u,JWKInvalid:()=>Te,JWKSInvalid:()=>_e,JWKSMultipleMatchingKeys:()=>Ue,JWKSNoMatchingKey:()=>pe,JWKSTimeout:()=>Oe,JWSInvalid:()=>_,JWSSignatureVerificationFailed:()=>ue,JWTClaimValidationFailed:()=>W,JWTExpired:()=>Ee,JWTInvalid:()=>K});var H,W,Ee,ae,m,Z,u,_,K,Te,_e,pe,Ue,Oe,ue,E=p(()=>{"use strict";H=class extends Error{constructor(t,r){super(t,r),this.code="ERR_JOSE_GENERIC",this.name=this.constructor.name,Error.captureStackTrace?.(this,this.constructor)}};H.code="ERR_JOSE_GENERIC";W=class extends H{constructor(t,r,n="unspecified",o="unspecified"){super(t,{cause:{claim:n,reason:o,payload:r}}),this.code="ERR_JWT_CLAIM_VALIDATION_FAILED",this.claim=n,this.reason=o,this.payload=r}};W.code="ERR_JWT_CLAIM_VALIDATION_FAILED";Ee=class extends H{constructor(t,r,n="unspecified",o="unspecified"){super(t,{cause:{claim:n,reason:o,payload:r}}),this.code="ERR_JWT_EXPIRED",this.claim=n,this.reason=o,this.payload=r}};Ee.code="ERR_JWT_EXPIRED";ae=class extends H{constructor(){super(...arguments),this.code="ERR_JOSE_ALG_NOT_ALLOWED"}};ae.code="ERR_JOSE_ALG_NOT_ALLOWED";m=class extends H{constructor(){super(...arguments),this.code="ERR_JOSE_NOT_SUPPORTED"}};m.code="ERR_JOSE_NOT_SUPPORTED";Z=class extends H{constructor(t="decryption operation failed",r){super(t,r),this.code="ERR_JWE_DECRYPTION_FAILED"}};Z.code="ERR_JWE_DECRYPTION_FAILED";u=class extends H{constructor(){super(...arguments),this.code="ERR_JWE_INVALID"}};u.code="ERR_JWE_INVALID";_=class extends H{constructor(){super(...arguments),this.code="ERR_JWS_INVALID"}};_.code="ERR_JWS_INVALID";K=class extends H{constructor(){super(...arguments),this.code="ERR_JWT_INVALID"}};K.code="ERR_JWT_INVALID";Te=class extends H{constructor(){super(...arguments),this.code="ERR_JWK_INVALID"}};Te.code="ERR_JWK_INVALID";_e=class extends H{constructor(){super(...arguments),this.code="ERR_JWKS_INVALID"}};_e.code="ERR_JWKS_INVALID";pe=class extends H{constructor(t="no applicable key found in the JSON Web Key Set",r){super(t,r),this.code="ERR_JWKS_NO_MATCHING_KEY"}};pe.code="ERR_JWKS_NO_MATCHING_KEY";Ue=class extends H{constructor(t="multiple matching keys found in the JSON Web Key Set",r){super(t,r),this.code="ERR_JWKS_MULTIPLE_MATCHING_KEYS"}};Ue.code="ERR_JWKS_MULTIPLE_MATCHING_KEYS";Oe=class extends H{constructor(t="request timed out",r){super(t,r),this.code="ERR_JWKS_TIMEOUT"}};Oe.code="ERR_JWKS_TIMEOUT";ue=class extends H{constructor(t="signature verification failed",r){super(t,r),this.code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED"}};ue.code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED"});var fe,Ye=p(()=>{"use strict";M();fe=h.getRandomValues.bind(h)});function ur(e){switch(e){case"A128GCM":case"A128GCMKW":case"A192GCM":case"A192GCMKW":case"A256GCM":case"A256GCMKW":return 96;case"A128CBC-HS256":case"A192CBC-HS384":case"A256CBC-HS512":return 128;default:throw new m(`Unsupported JWE Algorithm: ${e}`)}}var Un,fr=p(()=>{"use strict";E();Ye();Un=e=>fe(new Uint8Array(ur(e)>>3))});var xi,St,hr=p(()=>{"use strict";E();fr();xi=(e,t)=>{if(t.length<<3!==ur(e))throw new u("Invalid Initialization Vector length")},St=xi});var Ci,Re,mr=p(()=>{"use strict";E();Ci=(e,t)=>{let r=e.byteLength<<3;if(r!==t)throw new u(`Invalid Content Encryption Key length. Expected ${t} bits, got ${r} bits`)},Re=Ci});var Pi,On,Rn=p(()=>{"use strict";Pi=(e,t)=>{if(!(e instanceof Uint8Array))throw new TypeError("First argument must be a buffer");if(!(t instanceof Uint8Array))throw new TypeError("Second argument must be a buffer");if(e.length!==t.length)throw new TypeError("Input buffers must have the same length");let r=e.length,n=0,o=-1;for(;++o<r;)n|=e[o]^t[o];return n===0},On=Pi});function L(e,t="algorithm.name"){return new TypeError(`CryptoKey does not support this operation, its ${t} must be ${e}`)}function ie(e,t){return e.name===t}function At(e){return parseInt(e.name.slice(4),10)}function Ti(e){switch(e){case"ES256":return"P-256";case"ES384":return"P-384";case"ES512":return"P-521";default:throw new Error("unreachable")}}function In(e,t){if(t.length&&!t.some(r=>e.usages.includes(r))){let r="CryptoKey does not support this operation, its usages must include ";if(t.length>2){let n=t.pop();r+=`one of ${t.join(", ")}, or ${n}.`}else t.length===2?r+=`one of ${t[0]} or ${t[1]}.`:r+=`${t[0]}.`;throw new TypeError(r)}}function Kn(e,t,...r){switch(t){case"HS256":case"HS384":case"HS512":{if(!ie(e.algorithm,"HMAC"))throw L("HMAC");let n=parseInt(t.slice(2),10);if(At(e.algorithm.hash)!==n)throw L(`SHA-${n}`,"algorithm.hash");break}case"RS256":case"RS384":case"RS512":{if(!ie(e.algorithm,"RSASSA-PKCS1-v1_5"))throw L("RSASSA-PKCS1-v1_5");let n=parseInt(t.slice(2),10);if(At(e.algorithm.hash)!==n)throw L(`SHA-${n}`,"algorithm.hash");break}case"PS256":case"PS384":case"PS512":{if(!ie(e.algorithm,"RSA-PSS"))throw L("RSA-PSS");let n=parseInt(t.slice(2),10);if(At(e.algorithm.hash)!==n)throw L(`SHA-${n}`,"algorithm.hash");break}case"EdDSA":{if(e.algorithm.name!=="Ed25519"&&e.algorithm.name!=="Ed448")throw L("Ed25519 or Ed448");break}case"Ed25519":{if(!ie(e.algorithm,"Ed25519"))throw L("Ed25519");break}case"ES256":case"ES384":case"ES512":{if(!ie(e.algorithm,"ECDSA"))throw L("ECDSA");let n=Ti(t);if(e.algorithm.namedCurve!==n)throw L(n,"algorithm.namedCurve");break}default:throw new TypeError("CryptoKey does not support this operation")}In(e,r)}function F(e,t,...r){switch(t){case"A128GCM":case"A192GCM":case"A256GCM":{if(!ie(e.algorithm,"AES-GCM"))throw L("AES-GCM");let n=parseInt(t.slice(1,4),10);if(e.algorithm.length!==n)throw L(n,"algorithm.length");break}case"A128KW":case"A192KW":case"A256KW":{if(!ie(e.algorithm,"AES-KW"))throw L("AES-KW");let n=parseInt(t.slice(1,4),10);if(e.algorithm.length!==n)throw L(n,"algorithm.length");break}case"ECDH":{switch(e.algorithm.name){case"ECDH":case"X25519":case"X448":break;default:throw L("ECDH, X25519, or X448")}break}case"PBES2-HS256+A128KW":case"PBES2-HS384+A192KW":case"PBES2-HS512+A256KW":if(!ie(e.algorithm,"PBKDF2"))throw L("PBKDF2");break;case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":{if(!ie(e.algorithm,"RSA-OAEP"))throw L("RSA-OAEP");let n=parseInt(t.slice(9),10)||1;if(At(e.algorithm.hash)!==n)throw L(`SHA-${n}`,"algorithm.hash");break}default:throw new TypeError("CryptoKey does not support this operation")}In(e,r)}var he=p(()=>{"use strict"});function Hn(e,t,...r){if(r=r.filter(Boolean),r.length>2){let n=r.pop();e+=`one of type ${r.join(", ")}, or ${n}.`}else r.length===2?e+=`one of type ${r[0]} or ${r[1]}.`:e+=`of type ${r[0]}.`;return t==null?e+=` Received ${t}`:typeof t=="function"&&t.name?e+=` Received function ${t.name}`:typeof t=="object"&&t!=null&&t.constructor?.name&&(e+=` Received an instance of ${t.constructor.name}`),e}function yr(e,t,...r){return Hn(`Key for the ${e} algorithm must be `,t,...r)}var U,X=p(()=>{"use strict";U=(e,...t)=>Hn("Key must be ",e,...t)});var wr,T,Y=p(()=>{"use strict";M();wr=e=>O(e)?!0:e?.[Symbol.toStringTag]==="KeyObject",T=["CryptoKey"]});async function Ui(e,t,r,n,o,a){if(!(t instanceof Uint8Array))throw new TypeError(U(t,"Uint8Array"));let i=parseInt(e.slice(1,4),10),s=await h.subtle.importKey("raw",t.subarray(i>>3),"AES-CBC",!1,["decrypt"]),c=await h.subtle.importKey("raw",t.subarray(0,i>>3),{hash:`SHA-${i<<1}`,name:"HMAC"},!1,["sign"]),d=N(a,n,r,bt(a.length<<3)),l=new Uint8Array((await h.subtle.sign("HMAC",c,d)).slice(0,i>>3)),f;try{f=On(o,l)}catch{}if(!f)throw new Z;let g;try{g=new Uint8Array(await h.subtle.decrypt({iv:n,name:"AES-CBC"},s,r))}catch{}if(!g)throw new Z;return g}async function Oi(e,t,r,n,o,a){let i;t instanceof Uint8Array?i=await h.subtle.importKey("raw",t,"AES-GCM",!1,["decrypt"]):(F(t,e,"decrypt"),i=t);try{return new Uint8Array(await h.subtle.decrypt({additionalData:a,iv:n,name:"AES-GCM",tagLength:128},i,N(r,o)))}catch{throw new Z}}var Ri,xt,gr=p(()=>{"use strict";k();hr();mr();Rn();E();M();he();X();Y();Ri=async(e,t,r,n,o,a)=>{if(!O(t)&&!(t instanceof Uint8Array))throw new TypeError(U(t,...T,"Uint8Array"));if(!n)throw new u("JWE Initialization Vector missing");if(!o)throw new u("JWE Authentication Tag missing");switch(St(e,n),e){case"A128CBC-HS256":case"A192CBC-HS384":case"A256CBC-HS512":return t instanceof Uint8Array&&Re(t,parseInt(e.slice(-3),10)),Ui(e,t,r,n,o,a);case"A128GCM":case"A192GCM":case"A256GCM":return t instanceof Uint8Array&&Re(t,parseInt(e.slice(1,4),10)),Oi(e,t,r,n,o,a);default:throw new m("Unsupported JWE Content Encryption Algorithm")}},xt=Ri});var Ii,ee,Ie=p(()=>{"use strict";Ii=(...e)=>{let t=e.filter(Boolean);if(t.length===0||t.length===1)return!0;let r;for(let n of t){let o=Object.keys(n);if(!r||r.size===0){r=new Set(o);continue}for(let a of o){if(r.has(a))return!1;r.add(a)}}return!0},ee=Ii});function Ki(e){return typeof e=="object"&&e!==null}function v(e){if(!Ki(e)||Object.prototype.toString.call(e)!=="[object Object]")return!1;if(Object.getPrototypeOf(e)===null)return!0;let t=e;for(;Object.getPrototypeOf(t)!==null;)t=Object.getPrototypeOf(t);return Object.getPrototypeOf(e)===t}var $=p(()=>{"use strict"});var Hi,Ke,br=p(()=>{"use strict";Hi=[{hash:"SHA-256",name:"HMAC"},!0,["sign"]],Ke=Hi});function kn(e,t){if(e.algorithm.length!==parseInt(t.slice(1,4),10))throw new TypeError(`Invalid key size for alg: ${t}`)}function Wn(e,t,r){if(O(e))return F(e,t,r),e;if(e instanceof Uint8Array)return h.subtle.importKey("raw",e,"AES-KW",!0,[r]);throw new TypeError(U(e,...T,"Uint8Array"))}var je,Qe,Ct=p(()=>{"use strict";br();M();he();X();Y();je=async(e,t,r)=>{let n=await Wn(t,e,"wrapKey");kn(n,e);let o=await h.subtle.importKey("raw",r,...Ke);return new Uint8Array(await h.subtle.wrapKey("raw",o,n,"AES-KW"))},Qe=async(e,t,r)=>{let n=await Wn(t,e,"unwrapKey");kn(n,e);let o=await h.subtle.unwrapKey("raw",r,n,"AES-KW",...Ke);return new Uint8Array(await h.subtle.exportKey("raw",o))}});async function Pt(e,t,r,n,o=new Uint8Array(0),a=new Uint8Array(0)){if(!O(e))throw new TypeError(U(e,...T));if(F(e,"ECDH"),!O(t))throw new TypeError(U(t,...T));F(t,"ECDH","deriveBits");let i=N(_t(A.encode(r)),_t(o),_t(a),Et(n)),s;e.algorithm.name==="X25519"?s=256:e.algorithm.name==="X448"?s=448:s=Math.ceil(parseInt(e.algorithm.namedCurve.substr(-3),10)/8)<<3;let c=new Uint8Array(await h.subtle.deriveBits({name:e.algorithm.name,public:e},t,s));return Pn(c,n,i)}async function Jn(e){if(!O(e))throw new TypeError(U(e,...T));return h.subtle.generateKey(e.algorithm,!0,["deriveBits"])}function Tt(e){if(!O(e))throw new TypeError(U(e,...T));return["P-256","P-384","P-521"].includes(e.algorithm.namedCurve)||e.algorithm.name==="X25519"||e.algorithm.name==="X448"}var Er=p(()=>{"use strict";k();M();he();X();Y()});function _r(e){if(!(e instanceof Uint8Array)||e.length<8)throw new u("PBES2 Salt Input must be 8 or more octets")}var Bn=p(()=>{"use strict";E()});function ki(e,t){if(e instanceof Uint8Array)return h.subtle.importKey("raw",e,"PBKDF2",!1,["deriveBits"]);if(O(e))return F(e,t,"deriveBits","deriveKey"),e;throw new TypeError(U(e,...T,"Uint8Array"))}async function Mn(e,t,r,n){_r(e);let o=Cn(t,e),a=parseInt(t.slice(13,16),10),i={hash:`SHA-${t.slice(8,11)}`,iterations:r,name:"PBKDF2",salt:o},s={length:a,name:"AES-KW"},c=await ki(n,t);if(c.usages.includes("deriveBits"))return new Uint8Array(await h.subtle.deriveBits(i,c,a));if(c.usages.includes("deriveKey"))return h.subtle.deriveKey(i,c,s,!1,["wrapKey","unwrapKey"]);throw new TypeError('PBKDF2 key "usages" must include "deriveBits" or "deriveKey"')}var Nn,Dn,vr=p(()=>{"use strict";Ye();k();D();Ct();Bn();M();he();X();Y();Nn=async(e,t,r,n=2048,o=fe(new Uint8Array(16)))=>{let a=await Mn(o,e,n,t);return{encryptedKey:await je(e.slice(-6),a,r),p2c:n,p2s:x(o)}},Dn=async(e,t,r,n,o)=>{let a=await Mn(o,e,n,t);return Qe(e.slice(-6),a,r)}});function He(e){switch(e){case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":return"RSA-OAEP";default:throw new m(`alg ${e} is not supported either by JOSE or your javascript runtime`)}}var $n=p(()=>{"use strict";E()});var ve,Ut=p(()=>{"use strict";ve=(e,t)=>{if(e.startsWith("RS")||e.startsWith("PS")){let{modulusLength:r}=t.algorithm;if(typeof r!="number"||r<2048)throw new TypeError(`${e} requires key modulusLength to be 2048 bits or larger`)}}});var Vn,Fn,Sr=p(()=>{"use strict";$n();br();M();he();Ut();X();Y();Vn=async(e,t,r)=>{if(!O(t))throw new TypeError(U(t,...T));if(F(t,e,"encrypt","wrapKey"),ve(e,t),t.usages.includes("encrypt"))return new Uint8Array(await h.subtle.encrypt(He(e),t,r));if(t.usages.includes("wrapKey")){let n=await h.subtle.importKey("raw",r,...Ke);return new Uint8Array(await h.subtle.wrapKey("raw",n,t,He(e)))}throw new TypeError('RSA-OAEP key "usages" must include "encrypt" or "wrapKey" for this operation')},Fn=async(e,t,r)=>{if(!O(t))throw new TypeError(U(t,...T));if(F(t,e,"decrypt","unwrapKey"),ve(e,t),t.usages.includes("decrypt"))return new Uint8Array(await h.subtle.decrypt(He(e),t,r));if(t.usages.includes("unwrapKey")){let n=await h.subtle.unwrapKey("raw",r,t,He(e),...Ke);return new Uint8Array(await h.subtle.exportKey("raw",n))}throw new TypeError('RSA-OAEP key "usages" must include "decrypt" or "unwrapKey" for this operation')}});function se(e){return v(e)&&typeof e.kty=="string"}function Gn(e){return e.kty!=="oct"&&typeof e.d=="string"}function zn(e){return e.kty!=="oct"&&typeof e.d>"u"}function qn(e){return se(e)&&e.kty==="oct"&&typeof e.k=="string"}var Ot=p(()=>{"use strict";$()});function Ji(e){let t,r;switch(e.kty){case"RSA":{switch(e.alg){case"PS256":case"PS384":case"PS512":t={name:"RSA-PSS",hash:`SHA-${e.alg.slice(-3)}`},r=e.d?["sign"]:["verify"];break;case"RS256":case"RS384":case"RS512":t={name:"RSASSA-PKCS1-v1_5",hash:`SHA-${e.alg.slice(-3)}`},r=e.d?["sign"]:["verify"];break;case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":t={name:"RSA-OAEP",hash:`SHA-${parseInt(e.alg.slice(-3),10)||1}`},r=e.d?["decrypt","unwrapKey"]:["encrypt","wrapKey"];break;default:throw new m('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break}case"EC":{switch(e.alg){case"ES256":t={name:"ECDSA",namedCurve:"P-256"},r=e.d?["sign"]:["verify"];break;case"ES384":t={name:"ECDSA",namedCurve:"P-384"},r=e.d?["sign"]:["verify"];break;case"ES512":t={name:"ECDSA",namedCurve:"P-521"},r=e.d?["sign"]:["verify"];break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":t={name:"ECDH",namedCurve:e.crv},r=e.d?["deriveBits"]:[];break;default:throw new m('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break}case"OKP":{switch(e.alg){case"Ed25519":t={name:"Ed25519"},r=e.d?["sign"]:["verify"];break;case"EdDSA":t={name:e.crv},r=e.d?["sign"]:["verify"];break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":t={name:e.crv},r=e.d?["deriveBits"]:[];break;default:throw new m('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break}default:throw new m('Invalid or unsupported JWK "kty" (Key Type) Parameter value')}return{algorithm:t,keyUsages:r}}var Li,Rt,Ar=p(()=>{"use strict";M();E();Li=async e=>{if(!e.alg)throw new TypeError('"alg" argument is required when "jwk.alg" is not present');let{algorithm:t,keyUsages:r}=Ji(e),n=[t,e.ext??!1,e.key_ops??r],o={...e};return delete o.alg,delete o.use,h.subtle.importKey("jwk",o,...n)},Rt=Li});var Xn,ke,We,Yn,It,Bi,Mi,Se,Kt=p(()=>{"use strict";Ot();D();Ar();Xn=e=>C(e),Yn=e=>e?.[Symbol.toStringTag]==="KeyObject",It=async(e,t,r,n,o=!1)=>{let a=e.get(t);if(a?.[n])return a[n];let i=await Rt({...r,alg:n});return o&&Object.freeze(t),a?a[n]=i:e.set(t,{[n]:i}),i},Bi=(e,t)=>{if(Yn(e)){let r=e.export({format:"jwk"});return delete r.d,delete r.dp,delete r.dq,delete r.p,delete r.q,delete r.qi,r.k?Xn(r.k):(We||(We=new WeakMap),It(We,e,r,t))}return se(e)?e.k?C(e.k):(We||(We=new WeakMap),It(We,e,e,t,!0)):e},Mi=(e,t)=>{if(Yn(e)){let r=e.export({format:"jwk"});return r.k?Xn(r.k):(ke||(ke=new WeakMap),It(ke,e,r,t))}return se(e)?e.k?C(e.k):(ke||(ke=new WeakMap),It(ke,e,e,t,!0)):e},Se={normalizePublicKey:Bi,normalizePrivateKey:Mi}});function Ze(e){switch(e){case"A128GCM":return 128;case"A192GCM":return 192;case"A256GCM":case"A128CBC-HS256":return 256;case"A192CBC-HS384":return 384;case"A256CBC-HS512":return 512;default:throw new m(`Unsupported JWE Algorithm: ${e}`)}}var te,et=p(()=>{"use strict";E();Ye();te=e=>fe(new Uint8Array(Ze(e)>>3))});var xr,jn=p(()=>{"use strict";xr=(e,t)=>{let r=(e.match(/.{1,64}/g)||[]).join(`
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
-----END ${t}-----`}});function Zn(e){let t=[],r=0;for(;r<e.length;){let n=ao(e.subarray(r));t.push(n),r+=n.byteLength}return t}function ao(e){let t=0,r=e[0]&31;if(t++,r===31){for(r=0;e[t]>=128;)r=r*128+e[t]-128,t++;r=r*128+e[t]-128,t++}let n=0;if(e[t]<128)n=e[t],t++;else if(n===128){for(n=0;e[t+n]!==0||e[t+n+1]!==0;){if(n>e.byteLength)throw new TypeError("invalid indefinite form length");n++}let a=t+n+2;return{byteLength:a,contents:e.subarray(t,t+n),raw:e.subarray(0,a)}}else{let a=e[t]&127;t++,n=0;for(let i=0;i<a;i++)n=n*256+e[t],t++}let o=t+n;return{byteLength:o,contents:e.subarray(t,o),raw:e.subarray(0,o)}}function Ni(e){let t=Zn(Zn(ao(e).contents)[0].contents);return vt(t[t[0].raw[0]===160?6:5].raw)}function Di(e){let t=e.replace(/(?:-----(?:BEGIN|END) CERTIFICATE-----|\s)/g,""),r=lr(t);return xr(Ni(r),"PUBLIC KEY")}var eo,to,ro,me,Qn,no,oo,Cr,io,Ht=p(()=>{"use strict";M();X();D();jn();E();Y();eo=async(e,t,r)=>{if(!O(r))throw new TypeError(U(r,...T));if(!r.extractable)throw new TypeError("CryptoKey is not extractable");if(r.type!==e)throw new TypeError(`key is not a ${e} key`);return xr(vt(new Uint8Array(await h.subtle.exportKey(t,r))),`${e.toUpperCase()} KEY`)},to=e=>eo("public","spki",e),ro=e=>eo("private","pkcs8",e),me=(e,t,r=0)=>{r===0&&(t.unshift(t.length),t.unshift(6));let n=e.indexOf(t[0],r);if(n===-1)return!1;let o=e.subarray(n,n+t.length);return o.length!==t.length?!1:o.every((a,i)=>a===t[i])||me(e,t,n+1)},Qn=e=>{switch(!0){case me(e,[42,134,72,206,61,3,1,7]):return"P-256";case me(e,[43,129,4,0,34]):return"P-384";case me(e,[43,129,4,0,35]):return"P-521";case me(e,[43,101,110]):return"X25519";case me(e,[43,101,111]):return"X448";case me(e,[43,101,112]):return"Ed25519";case me(e,[43,101,113]):return"Ed448";default:throw new m("Invalid or unsupported EC Key Curve or OKP Key Sub Type")}},no=async(e,t,r,n,o)=>{let a,i,s=new Uint8Array(atob(r.replace(e,"")).split("").map(d=>d.charCodeAt(0))),c=t==="spki";switch(n){case"PS256":case"PS384":case"PS512":a={name:"RSA-PSS",hash:`SHA-${n.slice(-3)}`},i=c?["verify"]:["sign"];break;case"RS256":case"RS384":case"RS512":a={name:"RSASSA-PKCS1-v1_5",hash:`SHA-${n.slice(-3)}`},i=c?["verify"]:["sign"];break;case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":a={name:"RSA-OAEP",hash:`SHA-${parseInt(n.slice(-3),10)||1}`},i=c?["encrypt","wrapKey"]:["decrypt","unwrapKey"];break;case"ES256":a={name:"ECDSA",namedCurve:"P-256"},i=c?["verify"]:["sign"];break;case"ES384":a={name:"ECDSA",namedCurve:"P-384"},i=c?["verify"]:["sign"];break;case"ES512":a={name:"ECDSA",namedCurve:"P-521"},i=c?["verify"]:["sign"];break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":{let d=Qn(s);a=d.startsWith("P-")?{name:"ECDH",namedCurve:d}:{name:d},i=c?[]:["deriveBits"];break}case"Ed25519":a={name:"Ed25519"},i=c?["verify"]:["sign"];break;case"EdDSA":a={name:Qn(s)},i=c?["verify"]:["sign"];break;default:throw new m('Invalid or unsupported "alg" (Algorithm) value')}return h.subtle.importKey(t,s,a,o?.extractable??!1,i)},oo=(e,t,r)=>no(/(?:-----(?:BEGIN|END) PRIVATE KEY-----|\s)/g,"pkcs8",e,t,r),Cr=(e,t,r)=>no(/(?:-----(?:BEGIN|END) PUBLIC KEY-----|\s)/g,"spki",e,t,r);io=(e,t,r)=>{let n;try{n=Di(e)}catch(o){throw new TypeError("Failed to parse the X.509 certificate",{cause:o})}return Cr(n,t,r)}});async function so(e,t,r){if(typeof e!="string"||e.indexOf("-----BEGIN PUBLIC KEY-----")!==0)throw new TypeError('"spki" must be SPKI formatted string');return Cr(e,t,r)}async function co(e,t,r){if(typeof e!="string"||e.indexOf("-----BEGIN CERTIFICATE-----")!==0)throw new TypeError('"x509" must be X.509 formatted string');return io(e,t,r)}async function lo(e,t,r){if(typeof e!="string"||e.indexOf("-----BEGIN PRIVATE KEY-----")!==0)throw new TypeError('"pkcs8" must be PKCS#8 formatted string');return oo(e,t,r)}async function re(e,t){if(!v(e))throw new TypeError("JWK must be an object");switch(t||(t=e.alg),e.kty){case"oct":if(typeof e.k!="string"||!e.k)throw new TypeError('missing "k" (Key Value) Parameter value');return C(e.k);case"RSA":if("oth"in e&&e.oth!==void 0)throw new m('RSA JWK "oth" (Other Primes Info) Parameter value is not supported');case"EC":case"OKP":return Rt({...e,alg:t});default:throw new m('Unsupported "kty" (Key Type) Parameter value')}}var Je=p(()=>{"use strict";D();Ht();Ar();E();$()});function po(e,t,r,n){t.startsWith("HS")||t==="dir"||t.startsWith("PBES2")||/^A\d{3}(?:GCM)?KW$/.test(t)?$i(t,r,n,e):Vi(t,r,n,e)}var Le,Pr,$i,Vi,kt,tt,rt=p(()=>{"use strict";X();Y();Ot();Le=e=>e?.[Symbol.toStringTag],Pr=(e,t,r)=>{if(t.use!==void 0&&t.use!=="sig")throw new TypeError("Invalid key for this operation, when present its use must be sig");if(t.key_ops!==void 0&&t.key_ops.includes?.(r)!==!0)throw new TypeError(`Invalid key for this operation, when present its key_ops must include ${r}`);if(t.alg!==void 0&&t.alg!==e)throw new TypeError(`Invalid key for this operation, when present its alg must be ${e}`);return!0},$i=(e,t,r,n)=>{if(!(t instanceof Uint8Array)){if(n&&se(t)){if(qn(t)&&Pr(e,t,r))return;throw new TypeError('JSON Web Key for symmetric algorithms must have JWK "kty" (Key Type) equal to "oct" and the JWK "k" (Key Value) present')}if(!wr(t))throw new TypeError(yr(e,t,...T,"Uint8Array",n?"JSON Web Key":null));if(t.type!=="secret")throw new TypeError(`${Le(t)} instances for symmetric algorithms must be of type "secret"`)}},Vi=(e,t,r,n)=>{if(n&&se(t))switch(r){case"sign":if(Gn(t)&&Pr(e,t,r))return;throw new TypeError("JSON Web Key for this operation be a private JWK");case"verify":if(zn(t)&&Pr(e,t,r))return;throw new TypeError("JSON Web Key for this operation be a public JWK")}if(!wr(t))throw new TypeError(yr(e,t,...T,n?"JSON Web Key":null));if(t.type==="secret")throw new TypeError(`${Le(t)} instances for asymmetric algorithms must not be of type "secret"`);if(r==="sign"&&t.type==="public")throw new TypeError(`${Le(t)} instances for asymmetric algorithm signing must be of type "private"`);if(r==="decrypt"&&t.type==="public")throw new TypeError(`${Le(t)} instances for asymmetric algorithm decryption must be of type "private"`);if(t.algorithm&&r==="verify"&&t.type==="private")throw new TypeError(`${Le(t)} instances for asymmetric algorithm verifying must be of type "public"`);if(t.algorithm&&r==="encrypt"&&t.type==="private")throw new TypeError(`${Le(t)} instances for asymmetric algorithm encryption must be of type "public"`)};kt=po.bind(void 0,!1),tt=po.bind(void 0,!0)});async function Fi(e,t,r,n,o){if(!(r instanceof Uint8Array))throw new TypeError(U(r,"Uint8Array"));let a=parseInt(e.slice(1,4),10),i=await h.subtle.importKey("raw",r.subarray(a>>3),"AES-CBC",!1,["encrypt"]),s=await h.subtle.importKey("raw",r.subarray(0,a>>3),{hash:`SHA-${a<<1}`,name:"HMAC"},!1,["sign"]),c=new Uint8Array(await h.subtle.encrypt({iv:n,name:"AES-CBC"},i,t)),d=N(o,n,c,bt(o.length<<3)),l=new Uint8Array((await h.subtle.sign("HMAC",s,d)).slice(0,a>>3));return{ciphertext:c,tag:l,iv:n}}async function Gi(e,t,r,n,o){let a;r instanceof Uint8Array?a=await h.subtle.importKey("raw",r,"AES-GCM",!1,["encrypt"]):(F(r,e,"encrypt"),a=r);let i=new Uint8Array(await h.subtle.encrypt({additionalData:o,iv:n,name:"AES-GCM",tagLength:128},a,t)),s=i.slice(-16);return{ciphertext:i.slice(0,-16),tag:s,iv:n}}var zi,Wt,Tr=p(()=>{"use strict";k();hr();mr();M();he();X();fr();E();Y();zi=async(e,t,r,n,o)=>{if(!O(r)&&!(r instanceof Uint8Array))throw new TypeError(U(r,...T,"Uint8Array"));switch(n?St(e,n):n=Un(e),e){case"A128CBC-HS256":case"A192CBC-HS384":case"A256CBC-HS512":return r instanceof Uint8Array&&Re(r,parseInt(e.slice(-3),10)),Fi(e,t,r,n,o);case"A128GCM":case"A192GCM":case"A256GCM":return r instanceof Uint8Array&&Re(r,parseInt(e.slice(1,4),10)),Gi(e,t,r,n,o);default:throw new m("Unsupported JWE Content Encryption Algorithm")}},Wt=zi});async function uo(e,t,r,n){let o=e.slice(0,7),a=await Wt(o,r,t,n,new Uint8Array(0));return{encryptedKey:a.ciphertext,iv:x(a.iv),tag:x(a.tag)}}async function fo(e,t,r,n,o){let a=e.slice(0,7);return xt(a,t,r,n,o,new Uint8Array(0))}var Ur=p(()=>{"use strict";Tr();gr();D()});async function qi(e,t,r,n,o){switch(kt(e,t,"decrypt"),t=await Se.normalizePrivateKey?.(t,e)||t,e){case"dir":{if(r!==void 0)throw new u("Encountered unexpected JWE Encrypted Key");return t}case"ECDH-ES":if(r!==void 0)throw new u("Encountered unexpected JWE Encrypted Key");case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":{if(!v(n.epk))throw new u('JOSE Header "epk" (Ephemeral Public Key) missing or invalid');if(!Tt(t))throw new m("ECDH with the provided key is not allowed or not supported by your javascript runtime");let a=await re(n.epk,e),i,s;if(n.apu!==void 0){if(typeof n.apu!="string")throw new u('JOSE Header "apu" (Agreement PartyUInfo) invalid');try{i=C(n.apu)}catch{throw new u("Failed to base64url decode the apu")}}if(n.apv!==void 0){if(typeof n.apv!="string")throw new u('JOSE Header "apv" (Agreement PartyVInfo) invalid');try{s=C(n.apv)}catch{throw new u("Failed to base64url decode the apv")}}let c=await Pt(a,t,e==="ECDH-ES"?n.enc:e,e==="ECDH-ES"?Ze(n.enc):parseInt(e.slice(-5,-2),10),i,s);if(e==="ECDH-ES")return c;if(r===void 0)throw new u("JWE Encrypted Key missing");return Qe(e.slice(-6),c,r)}case"RSA1_5":case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":{if(r===void 0)throw new u("JWE Encrypted Key missing");return Fn(e,t,r)}case"PBES2-HS256+A128KW":case"PBES2-HS384+A192KW":case"PBES2-HS512+A256KW":{if(r===void 0)throw new u("JWE Encrypted Key missing");if(typeof n.p2c!="number")throw new u('JOSE Header "p2c" (PBES2 Count) missing or invalid');let a=o?.maxPBES2Count||1e4;if(n.p2c>a)throw new u('JOSE Header "p2c" (PBES2 Count) out is of acceptable bounds');if(typeof n.p2s!="string")throw new u('JOSE Header "p2s" (PBES2 Salt) missing or invalid');let i;try{i=C(n.p2s)}catch{throw new u("Failed to base64url decode the p2s")}return Dn(e,t,r,n.p2c,i)}case"A128KW":case"A192KW":case"A256KW":{if(r===void 0)throw new u("JWE Encrypted Key missing");return Qe(e,t,r)}case"A128GCMKW":case"A192GCMKW":case"A256GCMKW":{if(r===void 0)throw new u("JWE Encrypted Key missing");if(typeof n.iv!="string")throw new u('JOSE Header "iv" (Initialization Vector) missing or invalid');if(typeof n.tag!="string")throw new u('JOSE Header "tag" (Authentication Tag) missing or invalid');let a;try{a=C(n.iv)}catch{throw new u("Failed to base64url decode the iv")}let i;try{i=C(n.tag)}catch{throw new u("Failed to base64url decode the tag")}return fo(e,t,r,a,i)}default:throw new m('Invalid or unsupported "alg" (JWE Algorithm) header value')}}var ho,mo=p(()=>{"use strict";Ct();Er();vr();Sr();D();Kt();E();et();Je();rt();$();Ur();ho=qi});function Xi(e,t,r,n,o){if(o.crit!==void 0&&n?.crit===void 0)throw new e('"crit" (Critical) Header Parameter MUST be integrity protected');if(!n||n.crit===void 0)return new Set;if(!Array.isArray(n.crit)||n.crit.length===0||n.crit.some(i=>typeof i!="string"||i.length===0))throw new e('"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present');let a;r!==void 0?a=new Map([...Object.entries(r),...t.entries()]):a=t;for(let i of n.crit){if(!a.has(i))throw new m(`Extension Header Parameter "${i}" is not recognized`);if(o[i]===void 0)throw new e(`Extension Header Parameter "${i}" is missing`);if(a.get(i)&&n[i]===void 0)throw new e(`Extension Header Parameter "${i}" MUST be integrity protected`)}return new Set(n.crit)}var ne,Be=p(()=>{"use strict";E();ne=Xi});var Yi,nt,Or=p(()=>{"use strict";Yi=(e,t)=>{if(t!==void 0&&(!Array.isArray(t)||t.some(r=>typeof r!="string")))throw new TypeError(`"${e}" option must be an array of strings`);if(t)return new Set(t)},nt=Yi});async function Me(e,t,r){if(!v(e))throw new u("Flattened JWE must be an object");if(e.protected===void 0&&e.header===void 0&&e.unprotected===void 0)throw new u("JOSE Header missing");if(e.iv!==void 0&&typeof e.iv!="string")throw new u("JWE Initialization Vector incorrect type");if(typeof e.ciphertext!="string")throw new u("JWE Ciphertext missing or incorrect type");if(e.tag!==void 0&&typeof e.tag!="string")throw new u("JWE Authentication Tag incorrect type");if(e.protected!==void 0&&typeof e.protected!="string")throw new u("JWE Protected Header incorrect type");if(e.encrypted_key!==void 0&&typeof e.encrypted_key!="string")throw new u("JWE Encrypted Key incorrect type");if(e.aad!==void 0&&typeof e.aad!="string")throw new u("JWE AAD incorrect type");if(e.header!==void 0&&!v(e.header))throw new u("JWE Shared Unprotected Header incorrect type");if(e.unprotected!==void 0&&!v(e.unprotected))throw new u("JWE Per-Recipient Unprotected Header incorrect type");let n;if(e.protected)try{let V=C(e.protected);n=JSON.parse(R.decode(V))}catch{throw new u("JWE Protected Header is invalid")}if(!ee(n,e.header,e.unprotected))throw new u("JWE Protected, JWE Unprotected Header, and JWE Per-Recipient Unprotected Header Parameter names must be disjoint");let o={...n,...e.header,...e.unprotected};if(ne(u,new Map,r?.crit,n,o),o.zip!==void 0)throw new m('JWE "zip" (Compression Algorithm) Header Parameter is not supported.');let{alg:a,enc:i}=o;if(typeof a!="string"||!a)throw new u("missing JWE Algorithm (alg) in JWE Header");if(typeof i!="string"||!i)throw new u("missing JWE Encryption Algorithm (enc) in JWE Header");let s=r&&nt("keyManagementAlgorithms",r.keyManagementAlgorithms),c=r&&nt("contentEncryptionAlgorithms",r.contentEncryptionAlgorithms);if(s&&!s.has(a)||!s&&a.startsWith("PBES2"))throw new ae('"alg" (Algorithm) Header Parameter value not allowed');if(c&&!c.has(i))throw new ae('"enc" (Encryption Algorithm) Header Parameter value not allowed');let d;if(e.encrypted_key!==void 0)try{d=C(e.encrypted_key)}catch{throw new u("Failed to base64url decode the encrypted_key")}let l=!1;typeof t=="function"&&(t=await t(n,e),l=!0);let f;try{f=await ho(a,t,d,o,r)}catch(V){if(V instanceof TypeError||V instanceof u||V instanceof m)throw V;f=te(i)}let g,b;if(e.iv!==void 0)try{g=C(e.iv)}catch{throw new u("Failed to base64url decode the iv")}if(e.tag!==void 0)try{b=C(e.tag)}catch{throw new u("Failed to base64url decode the tag")}let w=A.encode(e.protected??""),S;e.aad!==void 0?S=N(w,A.encode("."),A.encode(e.aad)):S=w;let B;try{B=C(e.ciphertext)}catch{throw new u("Failed to base64url decode the ciphertext")}let I={plaintext:await xt(i,f,B,g,b,S)};if(e.protected!==void 0&&(I.protectedHeader=n),e.aad!==void 0)try{I.additionalAuthenticatedData=C(e.aad)}catch{throw new u("Failed to base64url decode the aad")}return e.unprotected!==void 0&&(I.sharedUnprotectedHeader=e.unprotected),e.header!==void 0&&(I.unprotectedHeader=e.header),l?{...I,key:t}:I}var Jt=p(()=>{"use strict";D();gr();E();Ie();$();mo();k();et();Be();Or()});async function Lt(e,t,r){if(e instanceof Uint8Array&&(e=R.decode(e)),typeof e!="string")throw new u("Compact JWE must be a string or Uint8Array");let{0:n,1:o,2:a,3:i,4:s,length:c}=e.split(".");if(c!==5)throw new u("Invalid Compact JWE");let d=await Me({ciphertext:i,iv:a||void 0,protected:n,tag:s||void 0,encrypted_key:o||void 0},t,r),l={plaintext:d.plaintext,protectedHeader:d.protectedHeader};return typeof t=="function"?{...l,key:d.key}:l}var Rr=p(()=>{"use strict";Jt();E();k()});async function yo(e,t,r){if(!v(e))throw new u("General JWE must be an object");if(!Array.isArray(e.recipients)||!e.recipients.every(v))throw new u("JWE Recipients missing or incorrect type");if(!e.recipients.length)throw new u("JWE Recipients has no members");for(let n of e.recipients)try{return await Me({aad:e.aad,ciphertext:e.ciphertext,encrypted_key:n.encrypted_key,header:n.header,iv:e.iv,protected:e.protected,tag:e.tag,unprotected:e.unprotected},t,r)}catch{}throw new Z}var wo=p(()=>{"use strict";Jt();E();$()});var Bt,Ir=p(()=>{"use strict";Bt=Symbol()});var ji,go,bo=p(()=>{"use strict";M();X();D();Y();ji=async e=>{if(e instanceof Uint8Array)return{kty:"oct",k:x(e)};if(!O(e))throw new TypeError(U(e,...T,"Uint8Array"));if(!e.extractable)throw new TypeError("non-extractable CryptoKey cannot be exported as a JWK");let{ext:t,key_ops:r,alg:n,use:o,...a}=await h.subtle.exportKey("jwk",e);return a},go=ji});async function Eo(e){return to(e)}async function _o(e){return ro(e)}async function Mt(e){return go(e)}var Kr=p(()=>{"use strict";Ht();Ht();bo()});async function Qi(e,t,r,n,o={}){let a,i,s;switch(kt(e,r,"encrypt"),r=await Se.normalizePublicKey?.(r,e)||r,e){case"dir":{s=r;break}case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":{if(!Tt(r))throw new m("ECDH with the provided key is not allowed or not supported by your javascript runtime");let{apu:c,apv:d}=o,{epk:l}=o;l||(l=(await Jn(r)).privateKey);let{x:f,y:g,crv:b,kty:w}=await Mt(l),S=await Pt(r,l,e==="ECDH-ES"?t:e,e==="ECDH-ES"?Ze(t):parseInt(e.slice(-5,-2),10),c,d);if(i={epk:{x:f,crv:b,kty:w}},w==="EC"&&(i.epk.y=g),c&&(i.apu=x(c)),d&&(i.apv=x(d)),e==="ECDH-ES"){s=S;break}s=n||te(t);let B=e.slice(-6);a=await je(B,S,s);break}case"RSA1_5":case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":{s=n||te(t),a=await Vn(e,r,s);break}case"PBES2-HS256+A128KW":case"PBES2-HS384+A192KW":case"PBES2-HS512+A256KW":{s=n||te(t);let{p2c:c,p2s:d}=o;({encryptedKey:a,...i}=await Nn(e,r,s,c,d));break}case"A128KW":case"A192KW":case"A256KW":{s=n||te(t),a=await je(e,r,s);break}case"A128GCMKW":case"A192GCMKW":case"A256GCMKW":{s=n||te(t);let{iv:c}=o;({encryptedKey:a,...i}=await uo(e,r,s,c));break}default:throw new m('Invalid or unsupported "alg" (JWE Algorithm) header value')}return{cek:s,encryptedKey:a,parameters:i}}var Nt,Hr=p(()=>{"use strict";Ct();Er();vr();Sr();D();Kt();et();E();Kr();rt();Ur();Nt=Qi});var ce,Dt=p(()=>{"use strict";D();Ir();Tr();Hr();E();Ie();k();Be();ce=class{constructor(t){if(!(t instanceof Uint8Array))throw new TypeError("plaintext must be an instance of Uint8Array");this._plaintext=t}setKeyManagementParameters(t){if(this._keyManagementParameters)throw new TypeError("setKeyManagementParameters can only be called once");return this._keyManagementParameters=t,this}setProtectedHeader(t){if(this._protectedHeader)throw new TypeError("setProtectedHeader can only be called once");return this._protectedHeader=t,this}setSharedUnprotectedHeader(t){if(this._sharedUnprotectedHeader)throw new TypeError("setSharedUnprotectedHeader can only be called once");return this._sharedUnprotectedHeader=t,this}setUnprotectedHeader(t){if(this._unprotectedHeader)throw new TypeError("setUnprotectedHeader can only be called once");return this._unprotectedHeader=t,this}setAdditionalAuthenticatedData(t){return this._aad=t,this}setContentEncryptionKey(t){if(this._cek)throw new TypeError("setContentEncryptionKey can only be called once");return this._cek=t,this}setInitializationVector(t){if(this._iv)throw new TypeError("setInitializationVector can only be called once");return this._iv=t,this}async encrypt(t,r){if(!this._protectedHeader&&!this._unprotectedHeader&&!this._sharedUnprotectedHeader)throw new u("either setProtectedHeader, setUnprotectedHeader, or sharedUnprotectedHeader must be called before #encrypt()");if(!ee(this._protectedHeader,this._unprotectedHeader,this._sharedUnprotectedHeader))throw new u("JWE Protected, JWE Shared Unprotected and JWE Per-Recipient Header Parameter names must be disjoint");let n={...this._protectedHeader,...this._unprotectedHeader,...this._sharedUnprotectedHeader};if(ne(u,new Map,r?.crit,this._protectedHeader,n),n.zip!==void 0)throw new m('JWE "zip" (Compression Algorithm) Header Parameter is not supported.');let{alg:o,enc:a}=n;if(typeof o!="string"||!o)throw new u('JWE "alg" (Algorithm) Header Parameter missing or invalid');if(typeof a!="string"||!a)throw new u('JWE "enc" (Encryption Algorithm) Header Parameter missing or invalid');let i;if(this._cek&&(o==="dir"||o==="ECDH-ES"))throw new TypeError(`setContentEncryptionKey cannot be called with JWE "alg" (Algorithm) Header ${o}`);let s;{let S;({cek:s,encryptedKey:i,parameters:S}=await Nt(o,a,t,this._cek,this._keyManagementParameters)),S&&(r&&Bt in r?this._unprotectedHeader?this._unprotectedHeader={...this._unprotectedHeader,...S}:this.setUnprotectedHeader(S):this._protectedHeader?this._protectedHeader={...this._protectedHeader,...S}:this.setProtectedHeader(S))}let c,d,l;this._protectedHeader?d=A.encode(x(JSON.stringify(this._protectedHeader))):d=A.encode(""),this._aad?(l=x(this._aad),c=N(d,A.encode("."),A.encode(l))):c=d;let{ciphertext:f,tag:g,iv:b}=await Wt(a,this._plaintext,s,this._iv,c),w={ciphertext:x(f)};return b&&(w.iv=x(b)),g&&(w.tag=x(g)),i&&(w.encrypted_key=x(i)),l&&(w.aad=l),this._protectedHeader&&(w.protected=R.decode(d)),this._sharedUnprotectedHeader&&(w.unprotected=this._sharedUnprotectedHeader),this._unprotectedHeader&&(w.header=this._unprotectedHeader),w}}});var kr,$t,vo=p(()=>{"use strict";Dt();Ir();E();et();Ie();Hr();D();Be();kr=class{constructor(t,r,n){this.parent=t,this.key=r,this.options=n}setUnprotectedHeader(t){if(this.unprotectedHeader)throw new TypeError("setUnprotectedHeader can only be called once");return this.unprotectedHeader=t,this}addRecipient(...t){return this.parent.addRecipient(...t)}encrypt(...t){return this.parent.encrypt(...t)}done(){return this.parent}},$t=class{constructor(t){this._recipients=[],this._plaintext=t}addRecipient(t,r){let n=new kr(this,t,{crit:r?.crit});return this._recipients.push(n),n}setProtectedHeader(t){if(this._protectedHeader)throw new TypeError("setProtectedHeader can only be called once");return this._protectedHeader=t,this}setSharedUnprotectedHeader(t){if(this._unprotectedHeader)throw new TypeError("setSharedUnprotectedHeader can only be called once");return this._unprotectedHeader=t,this}setAdditionalAuthenticatedData(t){return this._aad=t,this}async encrypt(){if(!this._recipients.length)throw new u("at least one recipient must be added");if(this._recipients.length===1){let[o]=this._recipients,a=await new ce(this._plaintext).setAdditionalAuthenticatedData(this._aad).setProtectedHeader(this._protectedHeader).setSharedUnprotectedHeader(this._unprotectedHeader).setUnprotectedHeader(o.unprotectedHeader).encrypt(o.key,{...o.options}),i={ciphertext:a.ciphertext,iv:a.iv,recipients:[{}],tag:a.tag};return a.aad&&(i.aad=a.aad),a.protected&&(i.protected=a.protected),a.unprotected&&(i.unprotected=a.unprotected),a.encrypted_key&&(i.recipients[0].encrypted_key=a.encrypted_key),a.header&&(i.recipients[0].header=a.header),i}let t;for(let o=0;o<this._recipients.length;o++){let a=this._recipients[o];if(!ee(this._protectedHeader,this._unprotectedHeader,a.unprotectedHeader))throw new u("JWE Protected, JWE Shared Unprotected and JWE Per-Recipient Header Parameter names must be disjoint");let i={...this._protectedHeader,...this._unprotectedHeader,...a.unprotectedHeader},{alg:s}=i;if(typeof s!="string"||!s)throw new u('JWE "alg" (Algorithm) Header Parameter missing or invalid');if(s==="dir"||s==="ECDH-ES")throw new u('"dir" and "ECDH-ES" alg may only be used with a single recipient');if(typeof i.enc!="string"||!i.enc)throw new u('JWE "enc" (Encryption Algorithm) Header Parameter missing or invalid');if(!t)t=i.enc;else if(t!==i.enc)throw new u('JWE "enc" (Encryption Algorithm) Header Parameter must be the same for all recipients');if(ne(u,new Map,a.options.crit,this._protectedHeader,i),i.zip!==void 0)throw new m('JWE "zip" (Compression Algorithm) Header Parameter is not supported.')}let r=te(t),n={ciphertext:"",iv:"",recipients:[],tag:""};for(let o=0;o<this._recipients.length;o++){let a=this._recipients[o],i={};n.recipients.push(i);let c={...this._protectedHeader,...this._unprotectedHeader,...a.unprotectedHeader}.alg.startsWith("PBES2")?2048+o:void 0;if(o===0){let f=await new ce(this._plaintext).setAdditionalAuthenticatedData(this._aad).setContentEncryptionKey(r).setProtectedHeader(this._protectedHeader).setSharedUnprotectedHeader(this._unprotectedHeader).setUnprotectedHeader(a.unprotectedHeader).setKeyManagementParameters({p2c:c}).encrypt(a.key,{...a.options,[Bt]:!0});n.ciphertext=f.ciphertext,n.iv=f.iv,n.tag=f.tag,f.aad&&(n.aad=f.aad),f.protected&&(n.protected=f.protected),f.unprotected&&(n.unprotected=f.unprotected),i.encrypted_key=f.encrypted_key,f.header&&(i.header=f.header);continue}let{encryptedKey:d,parameters:l}=await Nt(a.unprotectedHeader?.alg||this._protectedHeader?.alg||this._unprotectedHeader?.alg,t,a.key,r,{p2c:c});i.encrypted_key=x(d),(a.unprotectedHeader||l)&&(i.header={...a.unprotectedHeader,...l})}return n}}});function ot(e,t){let r=`SHA-${e.slice(-3)}`;switch(e){case"HS256":case"HS384":case"HS512":return{hash:r,name:"HMAC"};case"PS256":case"PS384":case"PS512":return{hash:r,name:"RSA-PSS",saltLength:e.slice(-3)>>3};case"RS256":case"RS384":case"RS512":return{hash:r,name:"RSASSA-PKCS1-v1_5"};case"ES256":case"ES384":case"ES512":return{hash:r,name:"ECDSA",namedCurve:t.namedCurve};case"Ed25519":return{name:"Ed25519"};case"EdDSA":return{name:t.name};default:throw new m(`alg ${e} is not supported either by JOSE or your javascript runtime`)}}var Wr=p(()=>{"use strict";E()});async function at(e,t,r){if(r==="sign"&&(t=await Se.normalizePrivateKey(t,e)),r==="verify"&&(t=await Se.normalizePublicKey(t,e)),O(t))return Kn(t,e,r),t;if(t instanceof Uint8Array){if(!e.startsWith("HS"))throw new TypeError(U(t,...T));return h.subtle.importKey("raw",t,{hash:`SHA-${e.slice(-3)}`,name:"HMAC"},!1,[r])}throw new TypeError(U(t,...T,"Uint8Array","JSON Web Key"))}var Jr=p(()=>{"use strict";M();he();X();Y();Kt()});var Zi,So,Ao=p(()=>{"use strict";Wr();M();Ut();Jr();Zi=async(e,t,r,n)=>{let o=await at(e,t,"verify");ve(e,o);let a=ot(e,o.algorithm);try{return await h.subtle.verify(a,o,r,n)}catch{return!1}},So=Zi});async function Ne(e,t,r){if(!v(e))throw new _("Flattened JWS must be an object");if(e.protected===void 0&&e.header===void 0)throw new _('Flattened JWS must have either of the "protected" or "header" members');if(e.protected!==void 0&&typeof e.protected!="string")throw new _("JWS Protected Header incorrect type");if(e.payload===void 0)throw new _("JWS Payload missing");if(typeof e.signature!="string")throw new _("JWS Signature missing or incorrect type");if(e.header!==void 0&&!v(e.header))throw new _("JWS Unprotected Header incorrect type");let n={};if(e.protected)try{let S=C(e.protected);n=JSON.parse(R.decode(S))}catch{throw new _("JWS Protected Header is invalid")}if(!ee(n,e.header))throw new _("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");let o={...n,...e.header},a=ne(_,new Map([["b64",!0]]),r?.crit,n,o),i=!0;if(a.has("b64")&&(i=n.b64,typeof i!="boolean"))throw new _('The "b64" (base64url-encode payload) Header Parameter must be a boolean');let{alg:s}=o;if(typeof s!="string"||!s)throw new _('JWS "alg" (Algorithm) Header Parameter missing or invalid');let c=r&&nt("algorithms",r.algorithms);if(c&&!c.has(s))throw new ae('"alg" (Algorithm) Header Parameter value not allowed');if(i){if(typeof e.payload!="string")throw new _("JWS Payload must be a string")}else if(typeof e.payload!="string"&&!(e.payload instanceof Uint8Array))throw new _("JWS Payload must be a string or an Uint8Array instance");let d=!1;typeof t=="function"?(t=await t(n,e),d=!0,tt(s,t,"verify"),se(t)&&(t=await re(t,s))):tt(s,t,"verify");let l=N(A.encode(e.protected??""),A.encode("."),typeof e.payload=="string"?A.encode(e.payload):e.payload),f;try{f=C(e.signature)}catch{throw new _("Failed to base64url decode the signature")}if(!await So(s,t,f,l))throw new ue;let b;if(i)try{b=C(e.payload)}catch{throw new _("Failed to base64url decode the payload")}else typeof e.payload=="string"?b=A.encode(e.payload):b=e.payload;let w={payload:b};return e.protected!==void 0&&(w.protectedHeader=n),e.header!==void 0&&(w.unprotectedHeader=e.header),d?{...w,key:t}:w}var Vt=p(()=>{"use strict";D();Ao();E();k();Ie();$();rt();Be();Or();Ot();Je()});async function Ft(e,t,r){if(e instanceof Uint8Array&&(e=R.decode(e)),typeof e!="string")throw new _("Compact JWS must be a string or Uint8Array");let{0:n,1:o,2:a,length:i}=e.split(".");if(i!==3)throw new _("Invalid Compact JWS");let s=await Ne({payload:o,protected:n,signature:a},t,r),c={payload:s.payload,protectedHeader:s.protectedHeader};return typeof t=="function"?{...c,key:s.key}:c}var Lr=p(()=>{"use strict";Vt();E();k()});async function xo(e,t,r){if(!v(e))throw new _("General JWS must be an object");if(!Array.isArray(e.signatures)||!e.signatures.every(v))throw new _("JWS Signatures missing or incorrect type");for(let n of e.signatures)try{return await Ne({header:n.header,payload:e.payload,protected:n.protected,signature:n.signature},t,r)}catch{}throw new ue}var Co=p(()=>{"use strict";Vt();E();$()});var oe,Br=p(()=>{"use strict";oe=e=>Math.floor(e.getTime()/1e3)});var es,Ae,Mr=p(()=>{"use strict";es=/^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i,Ae=e=>{let t=es.exec(e);if(!t||t[4]&&t[1])throw new TypeError("Invalid time period format");let r=parseFloat(t[2]),n=t[3].toLowerCase(),o;switch(n){case"sec":case"secs":case"second":case"seconds":case"s":o=Math.round(r);break;case"minute":case"minutes":case"min":case"mins":case"m":o=Math.round(r*60);break;case"hour":case"hours":case"hr":case"hrs":case"h":o=Math.round(r*3600);break;case"day":case"days":case"d":o=Math.round(r*86400);break;case"week":case"weeks":case"w":o=Math.round(r*604800);break;default:o=Math.round(r*31557600);break}return t[1]==="-"||t[4]==="ago"?-o:o}});var Po,ts,De,Gt=p(()=>{"use strict";E();k();Br();Mr();$();Po=e=>e.toLowerCase().replace(/^application\//,""),ts=(e,t)=>typeof e=="string"?t.includes(e):Array.isArray(e)?t.some(Set.prototype.has.bind(new Set(e))):!1,De=(e,t,r={})=>{let n;try{n=JSON.parse(R.decode(t))}catch{}if(!v(n))throw new K("JWT Claims Set must be a top-level JSON object");let{typ:o}=r;if(o&&(typeof e.typ!="string"||Po(e.typ)!==Po(o)))throw new W('unexpected "typ" JWT header value',n,"typ","check_failed");let{requiredClaims:a=[],issuer:i,subject:s,audience:c,maxTokenAge:d}=r,l=[...a];d!==void 0&&l.push("iat"),c!==void 0&&l.push("aud"),s!==void 0&&l.push("sub"),i!==void 0&&l.push("iss");for(let w of new Set(l.reverse()))if(!(w in n))throw new W(`missing required "${w}" claim`,n,w,"missing");if(i&&!(Array.isArray(i)?i:[i]).includes(n.iss))throw new W('unexpected "iss" claim value',n,"iss","check_failed");if(s&&n.sub!==s)throw new W('unexpected "sub" claim value',n,"sub","check_failed");if(c&&!ts(n.aud,typeof c=="string"?[c]:c))throw new W('unexpected "aud" claim value',n,"aud","check_failed");let f;switch(typeof r.clockTolerance){case"string":f=Ae(r.clockTolerance);break;case"number":f=r.clockTolerance;break;case"undefined":f=0;break;default:throw new TypeError("Invalid clockTolerance option type")}let{currentDate:g}=r,b=oe(g||new Date);if((n.iat!==void 0||d)&&typeof n.iat!="number")throw new W('"iat" claim must be a number',n,"iat","invalid");if(n.nbf!==void 0){if(typeof n.nbf!="number")throw new W('"nbf" claim must be a number',n,"nbf","invalid");if(n.nbf>b+f)throw new W('"nbf" claim timestamp check failed',n,"nbf","check_failed")}if(n.exp!==void 0){if(typeof n.exp!="number")throw new W('"exp" claim must be a number',n,"exp","invalid");if(n.exp<=b-f)throw new Ee('"exp" claim timestamp check failed',n,"exp","check_failed")}if(d){let w=b-n.iat,S=typeof d=="number"?d:Ae(d);if(w-f>S)throw new Ee('"iat" claim timestamp check failed (too far in the past)',n,"iat","check_failed");if(w<0-f)throw new W('"iat" claim timestamp check failed (it should be in the past)',n,"iat","check_failed")}return n}});async function To(e,t,r){let n=await Ft(e,t,r);if(n.protectedHeader.crit?.includes("b64")&&n.protectedHeader.b64===!1)throw new K("JWTs MUST NOT use unencoded payload");let a={payload:De(n.protectedHeader,n.payload,r),protectedHeader:n.protectedHeader};return typeof t=="function"?{...a,key:n.key}:a}var Uo=p(()=>{"use strict";Lr();Gt();E()});async function Oo(e,t,r){let n=await Lt(e,t,r),o=De(n.protectedHeader,n.plaintext,r),{protectedHeader:a}=n;if(a.iss!==void 0&&a.iss!==o.iss)throw new W('replicated "iss" claim header parameter mismatch',o,"iss","mismatch");if(a.sub!==void 0&&a.sub!==o.sub)throw new W('replicated "sub" claim header parameter mismatch',o,"sub","mismatch");if(a.aud!==void 0&&JSON.stringify(a.aud)!==JSON.stringify(o.aud))throw new W('replicated "aud" claim header parameter mismatch',o,"aud","mismatch");let i={payload:o,protectedHeader:a};return typeof t=="function"?{...i,key:n.key}:i}var Ro=p(()=>{"use strict";Rr();Gt();E()});var $e,Nr=p(()=>{"use strict";Dt();$e=class{constructor(t){this._flattened=new ce(t)}setContentEncryptionKey(t){return this._flattened.setContentEncryptionKey(t),this}setInitializationVector(t){return this._flattened.setInitializationVector(t),this}setProtectedHeader(t){return this._flattened.setProtectedHeader(t),this}setKeyManagementParameters(t){return this._flattened.setKeyManagementParameters(t),this}async encrypt(t,r){let n=await this._flattened.encrypt(t,r);return[n.protected,n.encrypted_key,n.iv,n.ciphertext,n.tag].join(".")}}});var rs,Io,Ko=p(()=>{"use strict";Wr();M();Ut();Jr();rs=async(e,t,r)=>{let n=await at(e,t,"sign");ve(e,n);let o=await h.subtle.sign(ot(e,n.algorithm),n,r);return new Uint8Array(o)},Io=rs});var ye,zt=p(()=>{"use strict";D();Ko();Ie();E();k();rt();Be();ye=class{constructor(t){if(!(t instanceof Uint8Array))throw new TypeError("payload must be an instance of Uint8Array");this._payload=t}setProtectedHeader(t){if(this._protectedHeader)throw new TypeError("setProtectedHeader can only be called once");return this._protectedHeader=t,this}setUnprotectedHeader(t){if(this._unprotectedHeader)throw new TypeError("setUnprotectedHeader can only be called once");return this._unprotectedHeader=t,this}async sign(t,r){if(!this._protectedHeader&&!this._unprotectedHeader)throw new _("either setProtectedHeader or setUnprotectedHeader must be called before #sign()");if(!ee(this._protectedHeader,this._unprotectedHeader))throw new _("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");let n={...this._protectedHeader,...this._unprotectedHeader},o=ne(_,new Map([["b64",!0]]),r?.crit,this._protectedHeader,n),a=!0;if(o.has("b64")&&(a=this._protectedHeader.b64,typeof a!="boolean"))throw new _('The "b64" (base64url-encode payload) Header Parameter must be a boolean');let{alg:i}=n;if(typeof i!="string"||!i)throw new _('JWS "alg" (Algorithm) Header Parameter missing or invalid');tt(i,t,"sign");let s=this._payload;a&&(s=A.encode(x(s)));let c;this._protectedHeader?c=A.encode(x(JSON.stringify(this._protectedHeader))):c=A.encode("");let d=N(c,A.encode("."),s),l=await Io(i,t,d),f={signature:x(l),payload:""};return a&&(f.payload=R.decode(s)),this._unprotectedHeader&&(f.header=this._unprotectedHeader),this._protectedHeader&&(f.protected=R.decode(c)),f}}});var Ve,Dr=p(()=>{"use strict";zt();Ve=class{constructor(t){this._flattened=new ye(t)}setProtectedHeader(t){return this._flattened.setProtectedHeader(t),this}async sign(t,r){let n=await this._flattened.sign(t,r);if(n.payload===void 0)throw new TypeError("use the flattened module for creating JWS with b64: false");return`${n.protected}.${n.payload}.${n.signature}`}}});var $r,qt,Ho=p(()=>{"use strict";zt();E();$r=class{constructor(t,r,n){this.parent=t,this.key=r,this.options=n}setProtectedHeader(t){if(this.protectedHeader)throw new TypeError("setProtectedHeader can only be called once");return this.protectedHeader=t,this}setUnprotectedHeader(t){if(this.unprotectedHeader)throw new TypeError("setUnprotectedHeader can only be called once");return this.unprotectedHeader=t,this}addSignature(...t){return this.parent.addSignature(...t)}sign(...t){return this.parent.sign(...t)}done(){return this.parent}},qt=class{constructor(t){this._signatures=[],this._payload=t}addSignature(t,r){let n=new $r(this,t,r);return this._signatures.push(n),n}async sign(){if(!this._signatures.length)throw new _("at least one signature must be added");let t={signatures:[],payload:""};for(let r=0;r<this._signatures.length;r++){let n=this._signatures[r],o=new ye(this._payload);o.setProtectedHeader(n.protectedHeader),o.setUnprotectedHeader(n.unprotectedHeader);let{payload:a,...i}=await o.sign(n.key,n.options);if(r===0)t.payload=a;else if(t.payload!==a)throw new _("inconsistent use of JWS Unencoded Payload (RFC7797)");t.signatures.push(i)}return t}}});function xe(e,t){if(!Number.isFinite(t))throw new TypeError(`Invalid ${e} input`);return t}var we,Xt=p(()=>{"use strict";Br();$();Mr();we=class{constructor(t={}){if(!v(t))throw new TypeError("JWT Claims Set MUST be an object");this._payload=t}setIssuer(t){return this._payload={...this._payload,iss:t},this}setSubject(t){return this._payload={...this._payload,sub:t},this}setAudience(t){return this._payload={...this._payload,aud:t},this}setJti(t){return this._payload={...this._payload,jti:t},this}setNotBefore(t){return typeof t=="number"?this._payload={...this._payload,nbf:xe("setNotBefore",t)}:t instanceof Date?this._payload={...this._payload,nbf:xe("setNotBefore",oe(t))}:this._payload={...this._payload,nbf:oe(new Date)+Ae(t)},this}setExpirationTime(t){return typeof t=="number"?this._payload={...this._payload,exp:xe("setExpirationTime",t)}:t instanceof Date?this._payload={...this._payload,exp:xe("setExpirationTime",oe(t))}:this._payload={...this._payload,exp:oe(new Date)+Ae(t)},this}setIssuedAt(t){return typeof t>"u"?this._payload={...this._payload,iat:oe(new Date)}:t instanceof Date?this._payload={...this._payload,iat:xe("setIssuedAt",oe(t))}:typeof t=="string"?this._payload={...this._payload,iat:xe("setIssuedAt",oe(new Date)+Ae(t))}:this._payload={...this._payload,iat:xe("setIssuedAt",t)},this}}});var Yt,ko=p(()=>{"use strict";Dr();E();k();Xt();Yt=class extends we{setProtectedHeader(t){return this._protectedHeader=t,this}async sign(t,r){let n=new Ve(A.encode(JSON.stringify(this._payload)));if(n.setProtectedHeader(this._protectedHeader),Array.isArray(this._protectedHeader?.crit)&&this._protectedHeader.crit.includes("b64")&&this._protectedHeader.b64===!1)throw new K("JWTs MUST NOT use unencoded payload");return n.sign(t,r)}}});var jt,Wo=p(()=>{"use strict";Nr();k();Xt();jt=class extends we{setProtectedHeader(t){if(this._protectedHeader)throw new TypeError("setProtectedHeader can only be called once");return this._protectedHeader=t,this}setKeyManagementParameters(t){if(this._keyManagementParameters)throw new TypeError("setKeyManagementParameters can only be called once");return this._keyManagementParameters=t,this}setContentEncryptionKey(t){if(this._cek)throw new TypeError("setContentEncryptionKey can only be called once");return this._cek=t,this}setInitializationVector(t){if(this._iv)throw new TypeError("setInitializationVector can only be called once");return this._iv=t,this}replicateIssuerAsHeader(){return this._replicateIssuerAsHeader=!0,this}replicateSubjectAsHeader(){return this._replicateSubjectAsHeader=!0,this}replicateAudienceAsHeader(){return this._replicateAudienceAsHeader=!0,this}async encrypt(t,r){let n=new $e(A.encode(JSON.stringify(this._payload)));return this._replicateIssuerAsHeader&&(this._protectedHeader={...this._protectedHeader,iss:this._payload.iss}),this._replicateSubjectAsHeader&&(this._protectedHeader={...this._protectedHeader,sub:this._payload.sub}),this._replicateAudienceAsHeader&&(this._protectedHeader={...this._protectedHeader,aud:this._payload.aud}),n.setProtectedHeader(this._protectedHeader),this._iv&&n.setInitializationVector(this._iv),this._cek&&n.setContentEncryptionKey(this._cek),this._keyManagementParameters&&n.setKeyManagementParameters(this._keyManagementParameters),n.encrypt(t,r)}}});async function Vr(e,t){if(!v(e))throw new TypeError("JWK must be an object");if(t??(t="sha256"),t!=="sha256"&&t!=="sha384"&&t!=="sha512")throw new TypeError('digestAlgorithm must one of "sha256", "sha384", or "sha512"');let r;switch(e.kty){case"EC":ge(e.crv,'"crv" (Curve) Parameter'),ge(e.x,'"x" (X Coordinate) Parameter'),ge(e.y,'"y" (Y Coordinate) Parameter'),r={crv:e.crv,kty:e.kty,x:e.x,y:e.y};break;case"OKP":ge(e.crv,'"crv" (Subtype of Key Pair) Parameter'),ge(e.x,'"x" (Public Key) Parameter'),r={crv:e.crv,kty:e.kty,x:e.x};break;case"RSA":ge(e.e,'"e" (Exponent) Parameter'),ge(e.n,'"n" (Modulus) Parameter'),r={e:e.e,kty:e.kty,n:e.n};break;case"oct":ge(e.k,'"k" (Key Value) Parameter'),r={k:e.k,kty:e.kty};break;default:throw new m('"kty" (Key Type) Parameter missing or unsupported')}let n=A.encode(JSON.stringify(r));return x(await wt(t,n))}async function Jo(e,t){t??(t="sha256");let r=await Vr(e,t);return`urn:ietf:params:oauth:jwk-thumbprint:sha-${t.slice(-3)}:${r}`}var ge,Lo=p(()=>{"use strict";cr();D();E();k();$();ge=(e,t)=>{if(typeof e!="string"||!e)throw new Te(`${t} missing or invalid`)}});async function Bo(e,t){let r={...e,...t?.header};if(!v(r.jwk))throw new _('"jwk" (JSON Web Key) Header Parameter must be a JSON object');let n=await re({...r.jwk,ext:!0},r.alg);if(n instanceof Uint8Array||n.type!=="public")throw new _('"jwk" (JSON Web Key) Header Parameter must be a public key');return n}var Mo=p(()=>{"use strict";Je();$();E()});function ns(e){switch(typeof e=="string"&&e.slice(0,2)){case"RS":case"PS":return"RSA";case"ES":return"EC";case"Ed":return"OKP";default:throw new m('Unsupported "alg" value for a JSON Web Key Set')}}function os(e){return e&&typeof e=="object"&&Array.isArray(e.keys)&&e.keys.every(as)}function as(e){return v(e)}function Do(e){return typeof structuredClone=="function"?structuredClone(e):JSON.parse(JSON.stringify(e))}async function No(e,t,r){let n=e.get(t)||e.set(t,{}).get(t);if(n[r]===void 0){let o=await re({...t,ext:!0},r);if(o instanceof Uint8Array||o.type!=="public")throw new _e("JSON Web Key Set members must be public keys");n[r]=o}return n[r]}function it(e){let t=new Fr(e),r=async(n,o)=>t.getKey(n,o);return Object.defineProperties(r,{jwks:{value:()=>Do(t._jwks),enumerable:!0,configurable:!1,writable:!1}}),r}var Fr,Gr=p(()=>{"use strict";Je();E();$();Fr=class{constructor(t){if(this._cached=new WeakMap,!os(t))throw new _e("JSON Web Key Set malformed");this._jwks=Do(t)}async getKey(t,r){let{alg:n,kid:o}={...t,...r?.header},a=ns(n),i=this._jwks.keys.filter(d=>{let l=a===d.kty;if(l&&typeof o=="string"&&(l=o===d.kid),l&&typeof d.alg=="string"&&(l=n===d.alg),l&&typeof d.use=="string"&&(l=d.use==="sig"),l&&Array.isArray(d.key_ops)&&(l=d.key_ops.includes("verify")),l)switch(n){case"ES256":l=d.crv==="P-256";break;case"ES256K":l=d.crv==="secp256k1";break;case"ES384":l=d.crv==="P-384";break;case"ES512":l=d.crv==="P-521";break;case"Ed25519":l=d.crv==="Ed25519";break;case"EdDSA":l=d.crv==="Ed25519"||d.crv==="Ed448";break}return l}),{0:s,length:c}=i;if(c===0)throw new pe;if(c!==1){let d=new Ue,{_cached:l}=this;throw d[Symbol.asyncIterator]=async function*(){for(let f of i)try{yield await No(l,f,n)}catch{}},d}return No(this._cached,s,n)}}});var is,$o,Vo=p(()=>{"use strict";E();is=async(e,t,r)=>{let n,o,a=!1;typeof AbortController=="function"&&(n=new AbortController,o=setTimeout(()=>{a=!0,n.abort()},t));let i=await fetch(e.href,{signal:n?n.signal:void 0,redirect:"manual",headers:r.headers}).catch(s=>{throw a?new Oe:s});if(o!==void 0&&clearTimeout(o),i.status!==200)throw new H("Expected 200 OK from the JSON Web Key Set HTTP response");try{return await i.json()}catch{throw new H("Failed to parse the JSON Web Key Set HTTP response as JSON")}},$o=is});function ss(){return typeof WebSocketPair<"u"||typeof navigator<"u"&&navigator.userAgent==="Cloudflare-Workers"||typeof EdgeRuntime<"u"&&EdgeRuntime==="vercel"}function cs(e,t){return!(typeof e!="object"||e===null||!("uat"in e)||typeof e.uat!="number"||Date.now()-e.uat>=t||!("jwks"in e)||!v(e.jwks)||!Array.isArray(e.jwks.keys)||!Array.prototype.every.call(e.jwks.keys,v))}function Fo(e,t){let r=new qr(e,t),n=async(o,a)=>r.getKey(o,a);return Object.defineProperties(n,{coolingDown:{get:()=>r.coolingDown(),enumerable:!0,configurable:!1},fresh:{get:()=>r.fresh(),enumerable:!0,configurable:!1},reload:{value:()=>r.reload(),enumerable:!0,configurable:!1,writable:!1},reloading:{get:()=>!!r._pendingFetch,enumerable:!0,configurable:!1},jwks:{value:()=>r._local?.jwks(),enumerable:!0,configurable:!1,writable:!1}}),n}var zr,Fe,qr,Go,zo=p(()=>{"use strict";Vo();E();Gr();$();(typeof navigator>"u"||!navigator.userAgent?.startsWith?.("Mozilla/5.0 "))&&(zr="jose/v5.10.0");Fe=Symbol();qr=class{constructor(t,r){if(!(t instanceof URL))throw new TypeError("url must be an instance of URL");this._url=new URL(t.href),this._options={agent:r?.agent,headers:r?.headers},this._timeoutDuration=typeof r?.timeoutDuration=="number"?r?.timeoutDuration:5e3,this._cooldownDuration=typeof r?.cooldownDuration=="number"?r?.cooldownDuration:3e4,this._cacheMaxAge=typeof r?.cacheMaxAge=="number"?r?.cacheMaxAge:6e5,r?.[Fe]!==void 0&&(this._cache=r?.[Fe],cs(r?.[Fe],this._cacheMaxAge)&&(this._jwksTimestamp=this._cache.uat,this._local=it(this._cache.jwks)))}coolingDown(){return typeof this._jwksTimestamp=="number"?Date.now()<this._jwksTimestamp+this._cooldownDuration:!1}fresh(){return typeof this._jwksTimestamp=="number"?Date.now()<this._jwksTimestamp+this._cacheMaxAge:!1}async getKey(t,r){(!this._local||!this.fresh())&&await this.reload();try{return await this._local(t,r)}catch(n){if(n instanceof pe&&this.coolingDown()===!1)return await this.reload(),this._local(t,r);throw n}}async reload(){this._pendingFetch&&ss()&&(this._pendingFetch=void 0);let t=new Headers(this._options.headers);zr&&!t.has("User-Agent")&&(t.set("User-Agent",zr),this._options.headers=Object.fromEntries(t.entries())),this._pendingFetch||(this._pendingFetch=$o(this._url,this._timeoutDuration,this._options).then(r=>{this._local=it(r),this._cache&&(this._cache.uat=Date.now(),this._cache.jwks=r),this._jwksTimestamp=Date.now(),this._pendingFetch=void 0}).catch(r=>{throw this._pendingFetch=void 0,r})),await this._pendingFetch}};Go=Fe});var Qt,qo=p(()=>{"use strict";D();k();E();Gt();Xt();Qt=class extends we{encode(){let t=x(JSON.stringify({alg:"none"})),r=x(JSON.stringify(this._payload));return`${t}.${r}.`}static decode(t,r){if(typeof t!="string")throw new K("Unsecured JWT must be a string");let{0:n,1:o,2:a,length:i}=t.split(".");if(i!==3||a!=="")throw new K("Invalid Unsecured JWT");let s;try{if(s=JSON.parse(R.decode(C(n))),s.alg!=="none")throw new Error}catch{throw new K("Invalid Unsecured JWT")}return{payload:De(s,C(o),r),header:s}}}});var Xr={};ir(Xr,{decode:()=>st,encode:()=>ds});var ds,st,Zt=p(()=>{"use strict";D();ds=x,st=C});function Xo(e){let t;if(typeof e=="string"){let r=e.split(".");(r.length===3||r.length===5)&&([t]=r)}else if(typeof e=="object"&&e)if("protected"in e)t=e.protected;else throw new TypeError("Token does not contain a Protected Header");try{if(typeof t!="string"||!t)throw new Error;let r=JSON.parse(R.decode(st(t)));if(!v(r))throw new Error;return r}catch{throw new TypeError("Invalid Token or Protected Header formatting")}}var Yo=p(()=>{"use strict";Zt();k();$()});function jo(e){if(typeof e!="string")throw new K("JWTs must use Compact JWS serialization, JWT must be a string");let{1:t,length:r}=e.split(".");if(r===5)throw new K("Only JWTs using Compact JWS serialization can be decoded");if(r!==3)throw new K("Invalid JWT");if(!t)throw new K("JWTs must contain a payload");let n;try{n=st(t)}catch{throw new K("Failed to base64url decode the payload")}let o;try{o=JSON.parse(R.decode(n))}catch{throw new K("Failed to parse the decoded payload as JSON")}if(!v(o))throw new K("Invalid JWT Claims Set");return o}var Qo=p(()=>{"use strict";Zt();k();$();E()});async function Zo(e,t){let r,n,o;switch(e){case"HS256":case"HS384":case"HS512":r=parseInt(e.slice(-3),10),n={name:"HMAC",hash:`SHA-${r}`,length:r},o=["sign","verify"];break;case"A128CBC-HS256":case"A192CBC-HS384":case"A256CBC-HS512":return r=parseInt(e.slice(-3),10),fe(new Uint8Array(r>>3));case"A128KW":case"A192KW":case"A256KW":r=parseInt(e.slice(1,4),10),n={name:"AES-KW",length:r},o=["wrapKey","unwrapKey"];break;case"A128GCMKW":case"A192GCMKW":case"A256GCMKW":case"A128GCM":case"A192GCM":case"A256GCM":r=parseInt(e.slice(1,4),10),n={name:"AES-GCM",length:r},o=["encrypt","decrypt"];break;default:throw new m('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}return h.subtle.generateKey(n,t?.extractable??!1,o)}function Yr(e){let t=e?.modulusLength??2048;if(typeof t!="number"||t<2048)throw new m("Invalid or unsupported modulusLength option provided, 2048 bits or larger keys must be used");return t}async function ea(e,t){let r,n;switch(e){case"PS256":case"PS384":case"PS512":r={name:"RSA-PSS",hash:`SHA-${e.slice(-3)}`,publicExponent:new Uint8Array([1,0,1]),modulusLength:Yr(t)},n=["sign","verify"];break;case"RS256":case"RS384":case"RS512":r={name:"RSASSA-PKCS1-v1_5",hash:`SHA-${e.slice(-3)}`,publicExponent:new Uint8Array([1,0,1]),modulusLength:Yr(t)},n=["sign","verify"];break;case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":r={name:"RSA-OAEP",hash:`SHA-${parseInt(e.slice(-3),10)||1}`,publicExponent:new Uint8Array([1,0,1]),modulusLength:Yr(t)},n=["decrypt","unwrapKey","encrypt","wrapKey"];break;case"ES256":r={name:"ECDSA",namedCurve:"P-256"},n=["sign","verify"];break;case"ES384":r={name:"ECDSA",namedCurve:"P-384"},n=["sign","verify"];break;case"ES512":r={name:"ECDSA",namedCurve:"P-521"},n=["sign","verify"];break;case"Ed25519":r={name:"Ed25519"},n=["sign","verify"];break;case"EdDSA":{n=["sign","verify"];let o=t?.crv??"Ed25519";switch(o){case"Ed25519":case"Ed448":r={name:o};break;default:throw new m("Invalid or unsupported crv option provided")}break}case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":{n=["deriveKey","deriveBits"];let o=t?.crv??"P-256";switch(o){case"P-256":case"P-384":case"P-521":{r={name:"ECDH",namedCurve:o};break}case"X25519":case"X448":r={name:o};break;default:throw new m("Invalid or unsupported crv option provided, supported values are P-256, P-384, P-521, X25519, and X448")}break}default:throw new m('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}return h.subtle.generateKey(r,t?.extractable??!1,n)}var jr=p(()=>{"use strict";M();E();Ye()});async function ta(e,t){return ea(e,t)}var ra=p(()=>{"use strict";jr()});async function na(e,t){return Zo(e,t)}var oa=p(()=>{"use strict";jr()});var aa,ia=p(()=>{"use strict";aa="WebCryptoAPI"});var sa,ca=p(()=>{"use strict";ia();sa=aa});var da={};ir(da,{CompactEncrypt:()=>$e,CompactSign:()=>Ve,EmbeddedJWK:()=>Bo,EncryptJWT:()=>jt,FlattenedEncrypt:()=>ce,FlattenedSign:()=>ye,GeneralEncrypt:()=>$t,GeneralSign:()=>qt,SignJWT:()=>Yt,UnsecuredJWT:()=>Qt,base64url:()=>Xr,calculateJwkThumbprint:()=>Vr,calculateJwkThumbprintUri:()=>Jo,compactDecrypt:()=>Lt,compactVerify:()=>Ft,createLocalJWKSet:()=>it,createRemoteJWKSet:()=>Fo,cryptoRuntime:()=>sa,decodeJwt:()=>jo,decodeProtectedHeader:()=>Xo,errors:()=>pr,experimental_jwksCache:()=>Go,exportJWK:()=>Mt,exportPKCS8:()=>_o,exportSPKI:()=>Eo,flattenedDecrypt:()=>Me,flattenedVerify:()=>Ne,generalDecrypt:()=>yo,generalVerify:()=>xo,generateKeyPair:()=>ta,generateSecret:()=>na,importJWK:()=>re,importPKCS8:()=>lo,importSPKI:()=>so,importX509:()=>co,jwksCache:()=>Fe,jwtDecrypt:()=>Oo,jwtVerify:()=>To});var la=p(()=>{"use strict";Rr();Jt();wo();vo();Lr();Vt();Co();Uo();Ro();Nr();Dt();Dr();zt();Ho();ko();Wo();Lo();Mo();Gr();zo();qo();Kr();Je();Yo();Qo();E();ra();oa();Zt();ca()});var ma=Q((dm,ha)=>{"use strict";var Qr=Object.defineProperty,ls=Object.getOwnPropertyDescriptor,ps=Object.getOwnPropertyNames,us=Object.prototype.hasOwnProperty,fs=(e,t)=>{for(var r in t)Qr(e,r,{get:t[r],enumerable:!0})},hs=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of ps(t))!us.call(e,o)&&o!==r&&Qr(e,o,{get:()=>t[o],enumerable:!(n=ls(t,o))||n.enumerable});return e},ms=e=>hs(Qr({},"__esModule",{value:!0}),e),ua={};fs(ua,{verifyVercelOidcToken:()=>bs});ha.exports=ms(ua);var fa=(la(),yi(da)),er="https://oidc.vercel.com",ys=new URL("https://oidc.vercel.com/.well-known/jwks"),ws=["RS256"],gs=(0,fa.createRemoteJWKSet)(ys);async function bs(e,t){let{algorithms:r,projectId:n=process.env.VERCEL_PROJECT_ID,environment:o=process.env.VERCEL_TARGET_ENV||process.env.VERCEL_ENV,ownerId:a,...i}=t??{};if(n==="*"&&a===void 0&&!Es(i.audience))throw new TypeError("Expected ownerId or audience to be provided when projectId is '*'.");let s=await(0,fa.jwtVerify)(e,gs,{...i,algorithms:r??ws});return _s(s.payload.iss),pa({actual:s.payload.project_id,claim:"project_id",env:"VERCEL_PROJECT_ID",expected:n,option:"projectId"}),pa({actual:s.payload.environment,claim:"environment",env:"VERCEL_TARGET_ENV or VERCEL_ENV",expected:o,option:"environment"}),vs({actual:s.payload.owner_id,claim:"owner_id",expected:a}),s}function Es(e){return Array.isArray(e)?e.length>0:e!==void 0}function _s(e){if(e!==er&&(typeof e!="string"||!e.startsWith(`${er}/`)))throw new TypeError(`Expected Vercel OIDC token iss claim to be "${er}" or to start with "${er}/".`)}function pa({actual:e,claim:t,env:r,expected:n,option:o}){if(n!=="*"){if(n===void 0||n.length===0)throw new TypeError(`Expected ${r} to be set or ${o} to be provided. Pass ${o}: '*' to allow any ${t} claim.`);if(!(Array.isArray(n)&&typeof e=="string"&&n.includes(e))&&e!==n)throw new TypeError(Array.isArray(n)?`Expected Vercel OIDC token ${t} claim to be one of: ${n.map(a=>`"${a}"`).join(", ")}.`:`Expected Vercel OIDC token ${t} claim to be "${n}".`)}}function vs({actual:e,claim:t,expected:r}){if(r!==void 0&&e!==r)throw new TypeError(`Expected Vercel OIDC token ${t} claim to be "${r}".`)}});var ga=Q((lm,wa)=>{"use strict";var tn=Object.defineProperty,Ss=Object.getOwnPropertyDescriptor,As=Object.getOwnPropertyNames,xs=Object.prototype.hasOwnProperty,Cs=(e,t)=>{for(var r in t)tn(e,r,{get:t[r],enumerable:!0})},Ps=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of As(t))!xs.call(e,o)&&o!==r&&tn(e,o,{get:()=>t[o],enumerable:!(n=Ss(t,o))||n.enumerable});return e},Ts=e=>Ps(tn({},"__esModule",{value:!0}),e),ya={};Cs(ya,{AccessTokenMissingError:()=>Zr,RefreshAccessTokenFailedError:()=>en});wa.exports=Ts(ya);var Zr=class extends Error{constructor(){super("No authentication found. Please log in with the Vercel CLI (vercel login)."),this.name="AccessTokenMissingError"}},en=class extends Error{constructor(t){super("Failed to refresh authentication token."),this.name="RefreshAccessTokenFailedError",t!==void 0&&(this.cause=t)}}});var va=Q((pm,_a)=>{"use strict";var rn=Object.defineProperty,Us=Object.getOwnPropertyDescriptor,Os=Object.getOwnPropertyNames,Rs=Object.prototype.hasOwnProperty,Is=(e,t)=>{for(var r in t)rn(e,r,{get:t[r],enumerable:!0})},Ks=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of Os(t))!Rs.call(e,o)&&o!==r&&rn(e,o,{get:()=>t[o],enumerable:!(n=Us(t,o))||n.enumerable});return e},Hs=e=>Ks(rn({},"__esModule",{value:!0}),e),Ea={};Is(Ea,{AccessTokenMissingError:()=>ba.AccessTokenMissingError,RefreshAccessTokenFailedError:()=>ba.RefreshAccessTokenFailedError,getContext:()=>ks.getContext,getVercelOidcToken:()=>Js,getVercelOidcTokenSync:()=>Ls,getVercelToken:()=>Bs,verifyVercelOidcToken:()=>Ws.verifyVercelOidcToken});_a.exports=Hs(Ea);var ks=xn(),Ws=ma(),ba=ga();async function Js(){return""}function Ls(){return""}async function Bs(){throw new Error("getVercelToken is not supported in browser environments")}});var Aa=Q((um,Sa)=>{"use strict";function z(e,t){typeof t=="boolean"&&(t={forever:t}),this._originalTimeouts=JSON.parse(JSON.stringify(e)),this._timeouts=e,this._options=t||{},this._maxRetryTime=t&&t.maxRetryTime||1/0,this._fn=null,this._errors=[],this._attempts=1,this._operationTimeout=null,this._operationTimeoutCb=null,this._timeout=null,this._operationStart=null,this._timer=null,this._options.forever&&(this._cachedTimeouts=this._timeouts.slice(0))}Sa.exports=z;z.prototype.reset=function(){this._attempts=1,this._timeouts=this._originalTimeouts.slice(0)};z.prototype.stop=function(){this._timeout&&clearTimeout(this._timeout),this._timer&&clearTimeout(this._timer),this._timeouts=[],this._cachedTimeouts=null};z.prototype.retry=function(e){if(this._timeout&&clearTimeout(this._timeout),!e)return!1;var t=new Date().getTime();if(e&&t-this._operationStart>=this._maxRetryTime)return this._errors.push(e),this._errors.unshift(new Error("RetryOperation timeout occurred")),!1;this._errors.push(e);var r=this._timeouts.shift();if(r===void 0)if(this._cachedTimeouts)this._errors.splice(0,this._errors.length-1),r=this._cachedTimeouts.slice(-1);else return!1;var n=this;return this._timer=setTimeout(function(){n._attempts++,n._operationTimeoutCb&&(n._timeout=setTimeout(function(){n._operationTimeoutCb(n._attempts)},n._operationTimeout),n._options.unref&&n._timeout.unref()),n._fn(n._attempts)},r),this._options.unref&&this._timer.unref(),!0};z.prototype.attempt=function(e,t){this._fn=e,t&&(t.timeout&&(this._operationTimeout=t.timeout),t.cb&&(this._operationTimeoutCb=t.cb));var r=this;this._operationTimeoutCb&&(this._timeout=setTimeout(function(){r._operationTimeoutCb()},r._operationTimeout)),this._operationStart=new Date().getTime(),this._fn(this._attempts)};z.prototype.try=function(e){console.log("Using RetryOperation.try() is deprecated"),this.attempt(e)};z.prototype.start=function(e){console.log("Using RetryOperation.start() is deprecated"),this.attempt(e)};z.prototype.start=z.prototype.try;z.prototype.errors=function(){return this._errors};z.prototype.attempts=function(){return this._attempts};z.prototype.mainError=function(){if(this._errors.length===0)return null;for(var e={},t=null,r=0,n=0;n<this._errors.length;n++){var o=this._errors[n],a=o.message,i=(e[a]||0)+1;e[a]=i,i>=r&&(t=o,r=i)}return t}});var xa=Q(Ce=>{"use strict";var Ms=Aa();Ce.operation=function(e){var t=Ce.timeouts(e);return new Ms(t,{forever:e&&(e.forever||e.retries===1/0),unref:e&&e.unref,maxRetryTime:e&&e.maxRetryTime})};Ce.timeouts=function(e){if(e instanceof Array)return[].concat(e);var t={retries:10,factor:2,minTimeout:1*1e3,maxTimeout:1/0,randomize:!1};for(var r in e)t[r]=e[r];if(t.minTimeout>t.maxTimeout)throw new Error("minTimeout is greater than maxTimeout");for(var n=[],o=0;o<t.retries;o++)n.push(this.createTimeout(o,t));return e&&e.forever&&!n.length&&n.push(this.createTimeout(o,t)),n.sort(function(a,i){return a-i}),n};Ce.createTimeout=function(e,t){var r=t.randomize?Math.random()+1:1,n=Math.round(r*Math.max(t.minTimeout,1)*Math.pow(t.factor,e));return n=Math.min(n,t.maxTimeout),n};Ce.wrap=function(e,t,r){if(t instanceof Array&&(r=t,t=null),!r){r=[];for(var n in e)typeof e[n]=="function"&&r.push(n)}for(var o=0;o<r.length;o++){var a=r[o],i=e[a];e[a]=function(c){var d=Ce.operation(t),l=Array.prototype.slice.call(arguments,1),f=l.pop();l.push(function(g){d.retry(g)||(g&&(arguments[0]=d.mainError()),f.apply(this,arguments))}),d.attempt(function(){c.apply(e,l)})}.bind(e,i),e[a].options=t}}});var Pa=Q((hm,Ca)=>{"use strict";Ca.exports=xa()});var Ua=Q((mm,Ta)=>{"use strict";var Ns=Pa();function Ds(e,t){function r(n,o){var a=t||{},i;"randomize"in a||(a.randomize=!0),i=Ns.operation(a);function s(l){o(l||new Error("Aborted"))}function c(l,f){if(l.bail){s(l);return}i.retry(l)?a.onRetry&&a.onRetry(l,f):o(i.mainError())}function d(l){var f;try{f=e(s,l)}catch(g){c(g,l);return}Promise.resolve(f).then(n).catch(function(b){c(b,l)})}i.attempt(d)}return new Promise(r)}Ta.exports=Ds});var nn=Q((wm,Oa)=>{"use strict";function $s(e,t){if(typeof e!="function")throw new TypeError(`Expected the first argument to be a \`function\`, got \`${typeof e}\`.`);let r,n=0;return function(...a){clearTimeout(r);let i=Date.now(),s=i-n,c=t-s;c<=0?(n=i,e.apply(this,a)):r=setTimeout(()=>{n=Date.now(),e.apply(this,a)},c)}}Oa.exports=$s});function gn(){if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof process<"u"){let e=process.type;return e==="renderer"||e==="worker"?!1:!!(process.versions&&process.versions.node)}return!1}var Ma=Xe(En(),1);var _n={toWeb(){throw new Error("Vercel Blob: Sorry, we cannot get a Readable stream in this environment. If you see this message please open an issue here: https://github.com/vercel/storage/ with details on your environment.")}};var $a=Xe(va(),1),za=Xe(Ua(),1);var Ge=globalThis.fetch.bind(globalThis);var Za=Xe(nn(),1),ni=Xe(nn(),1),Vs=new Promise(e=>{try{let t=new Uint8Array([104,101,108,108,111]);new Blob([t]).text().then(n=>{e(n==="hello")}).catch(()=>{e(!1)})}catch{e(!1)}});async function Na(e){if(e instanceof ReadableStream)return e;if(e instanceof Blob)return e.stream();if(Da(e))return _n.toWeb(e);let t;return e instanceof ArrayBuffer?t=new Uint8Array(e):Gs(e)?t=e:t=Fs(e),await Vs?new Blob([t]).stream():new ReadableStream({start(r){r.enqueue(t),r.close()}})}function Da(e){return typeof e=="object"&&typeof e.pipe=="function"&&e.readable&&typeof e._read=="function"&&typeof e._readableState=="object"}function Fs(e){return new TextEncoder().encode(e)}function Gs(e){return(0,Ma.default)(e)}async function zs(){try{let e=(await(0,$a.getVercelOidcToken)()).trim();return e===""?void 0:e}catch{return}}var qs=/^((-|\+)?(\d+(?:\.\d+)?)) *(kb|mb|gb|tb|pb)$/i,Xs={b:1,kb:1024,mb:1<<20,gb:1<<30,tb:1024**4,pb:1024**5};function q(e){if(typeof e=="number"&&!Number.isNaN(e))return e;if(typeof e!="string")return null;let t=qs.exec(e),r,n="b";if(!t)r=parseInt(e,10);else{let[,o,,,a]=t;if(!o)return null;r=parseFloat(o),a&&(n=a.toLowerCase())}return Number.isNaN(r)?null:Math.floor(Xs[n]*r)}var Ys="https://vercel.com/api/blob";function Ra(e){try{let t=process.env[e];return typeof t=="string"&&t.trim()!==""?t.trim():void 0}catch{return}}function on(e){let[,,,t=""]=e.split("_");return t}function js(e){let t=e.replace(/-/g,"+").replace(/_/g,"/"),r=4-t.length%4;if(r!==4&&(t+="=".repeat(r)),typeof atob=="function")return atob(t);if(typeof Buffer<"u")return Buffer.from(t,"base64").toString("utf8");throw new y("Cannot decode base64: no atob or Buffer available.")}function Qs(e){let t=e.indexOf(".");if(t<0)throw new y("Invalid delegation token format.");let r=e.slice(0,t),n;try{n=JSON.parse(js(r))}catch{throw new y("Invalid delegation token payload.")}if(!n.storeId||typeof n.storeId!="string")throw new y("Delegation token payload is missing `storeId`.");return an(n.storeId)}function an(e){return e.startsWith("store_")?e.slice(6):e}async function Zs(e){var t,r;if(e?.presignedUrlPayload)return{kind:"presigned",storeId:Qs(e.presignedUrlPayload.delegationToken)};if(e?.token){let i=on(e.token);return{kind:"readWrite",token:e.token,storeId:i}}let n=(t=e?.oidcToken)==null?void 0:t.trim(),o=n||await zs();if(o){let i=(r=e?.storeId)==null?void 0:r.trim();if(i)return{kind:"oidc",token:o,storeId:an(i)};let s=Ra("BLOB_STORE_ID");if(s)return{kind:"oidc",token:o,storeId:an(s)};if(n)throw new y("oidcToken was passed, but no storeId was found. Pass a `storeId` option or set `BLOB_STORE_ID` to use OIDC auth")}let a=Ra("BLOB_READ_WRITE_TOKEN");if(a){let i=on(a);return{kind:"readWrite",token:a,storeId:i}}throw new y("No blob credentials found. Pass a `token` option, set `BLOB_READ_WRITE_TOKEN`, or use `oidcToken` (or `VERCEL_OIDC_TOKEN`) with `storeId` or `BLOB_STORE_ID`.")}var y=class extends Error{constructor(e){super(`Vercel Blob: ${e}`)}};function ln(e){if(typeof e!="object"||e===null)return!1;let t=Object.getPrototypeOf(e);return(t===null||t===Object.prototype||Object.getPrototypeOf(t)===null)&&!(Symbol.toStringTag in e)&&!(Symbol.iterator in e)}var ec=["//"],Va=(()=>{if(gn())return!0;if(sn().startsWith("http://localhost"))return!1;let t=!1,r=new Request(sn(),{body:new ReadableStream,method:"POST",get duplex(){return t=!0,"half"}}).headers.has("Content-Type");return t&&!r})();function sn(e=""){let t=null;try{t=process.env.VERCEL_BLOB_API_URL||process.env.NEXT_PUBLIC_VERCEL_BLOB_API_URL}catch{}return`${t||Ys}${e}`}var Ia=typeof TextEncoder=="function"?new TextEncoder:null;function tr(e){return e?typeof e=="string"?Ia?Ia.encode(e).byteLength:new Blob([e]).size:"byteLength"in e&&typeof e.byteLength=="number"?e.byteLength:"size"in e&&typeof e.size=="number"?e.size:0:0}var tc=(e,t)=>{let r=new Uint8Array(0);return new TransformStream({transform(n,o){let a=new Uint8Array(r.length+n.byteLength);for(a.set(r),a.set(new Uint8Array(n),r.length),r=a;r.length>=e;){let i=r.slice(0,e);o.enqueue(i),t?.(i.byteLength),r=r.slice(e)}},flush(n){r.length>0&&(n.enqueue(r),t?.(r.byteLength))}})};function Fa(e){return globalThis.ReadableStream&&e instanceof ReadableStream}function Ga(e){return!!(Fa(e)||Da(e))}var rc=(e,t)=>{let r=new URL(e);for(let[n,o]of Object.entries(t.params))r.searchParams.set(n,o);return r.searchParams.set("vercel-blob-delegation",t.delegationToken),r.searchParams.set("vercel-blob-signature",t.signature),r.toString()};var qa=!1,Ka,Ha;try{((Ka=process.env.DEBUG)!=null&&Ka.includes("blob")||(Ha=process.env.NEXT_PUBLIC_DEBUG)!=null&&Ha.includes("blob"))&&(qa=!0)}catch{}function G(e,...t){qa&&console.debug(`vercel-blob: ${e}`,...t)}var ka,nc=(ka=globalThis.DOMException)!=null?ka:(()=>{try{atob("~")}catch(e){return Object.getPrototypeOf(e).constructor}})(),oc=Object.prototype.toString,ac=e=>oc.call(e)==="[object Error]",ic=new Set(["network error","Failed to fetch","NetworkError when attempting to fetch resource.","The Internet connection appears to be offline.","Load failed","Network request failed","fetch failed","terminated"]);function sc(e){return e&&ac(e)&&e.name==="TypeError"&&typeof e.message=="string"?e.message==="Load failed"?e.stack===void 0:ic.has(e.message):!1}var Xa=typeof Ge=="function",cc=Xa&&Va,dc=64*1024,Wa=async({input:e,init:t,onUploadProgress:r})=>{G("using fetch");let n;if(t.body)if(r){let a=await Na(t.body),i=0,s=tc(dc,c=>{i+=c,r(i)});n=a.pipeThrough(s)}else n=t.body;let o=Va&&n&&Ga(n)?"half":void 0;return Ge(e,{...t,...t.body?{body:n}:{},duplex:o})},Ja=typeof XMLHttpRequest<"u",La=async({input:e,init:t,onUploadProgress:r})=>{G("using xhr");let n=null;return t.body&&(Fa(t.body)?n=await new Response(t.body).blob():n=t.body),new Promise((o,a)=>{let i=new XMLHttpRequest;if(i.open(t.method||"GET",e.toString(),!0),r&&i.upload.addEventListener("progress",s=>{s.lengthComputable&&r(s.loaded)}),i.onload=()=>{var s;if((s=t.signal)!=null&&s.aborted){a(new DOMException("The user aborted the request.","AbortError"));return}let c=new Headers;i.getAllResponseHeaders().trim().split(/[\r\n]+/).forEach(f=>{let g=f.split(": "),b=g.shift(),w=g.join(": ");b&&c.set(b.toLowerCase(),w)});let l=new Response(i.response,{status:i.status,statusText:i.statusText,headers:c});o(l)},i.onerror=()=>{a(new TypeError("Network request failed"))},i.ontimeout=()=>{a(new TypeError("Network request timed out"))},i.onabort=()=>{a(new DOMException("The user aborted a request.","AbortError"))},t.headers&&new Headers(t.headers).forEach((c,d)=>{i.setRequestHeader(d,c)}),t.signal&&(t.signal.addEventListener("abort",()=>{i.abort()}),t.signal.aborted)){i.abort();return}i.send(n)})},lc=async({input:e,init:t,onUploadProgress:r})=>{if(r){if(cc)return Wa({input:e,init:t,onUploadProgress:r});if(Ja)return La({input:e,init:t,onUploadProgress:r})}if(Xa)return Wa({input:e,init:t});if(Ja)return La({input:e,init:t});throw new Error("No request implementation available")},Ba=950,pc=class extends y{constructor(){super("Access denied, please provide a valid token for this resource.")}},uc=class extends y{constructor(e){super(e??"OIDC is enabled for this project, but not for this token's environment.")}},fc=class extends y{constructor(e){super(`Content type mismatch, ${e}.`)}},hc=class extends y{constructor(e){super(`Pathname mismatch, ${e}. Check the pathname used in upload() or put() matches the one from the client token.`)}},mc=class extends y{constructor(){super("Client token has expired.")}},yc=class extends y{constructor(e){super(`File is too large, ${e}.`)}},wc=class extends y{constructor(){super("This store does not exist.")}},gc=class extends y{constructor(){super("This store has been suspended.")}},Ya=class extends y{constructor(){super("Unknown error, please visit https://vercel.com/help.")}},bc=class extends y{constructor(){super("The requested blob does not exist")}},rr=class extends y{constructor(){super("The blob service is currently not available. Please try again.")}},Ec=class extends y{constructor(e){super(`Too many requests please lower the number of concurrent requests ${e?` - try again in ${e} seconds`:""}.`),this.retryAfter=e??0}},_c=class extends y{constructor(){super("The request was aborted.")}},vc=class extends y{constructor(){super("Precondition failed: ETag mismatch.")}},Sc=12;function Ac(){let e=null;try{e=process.env.VERCEL_BLOB_API_VERSION_OVERRIDE||process.env.NEXT_PUBLIC_VERCEL_BLOB_API_VERSION_OVERRIDE}catch{}return`${e??Sc}`}function xc(){try{let e=process.env.VERCEL_BLOB_RETRIES||"10";return parseInt(e,10)}catch{return 10}}function Cc(e){let t=e.headers.get("retry-after");return new Ec(t?parseInt(t,10):void 0)}async function Pc(e){var t,r,n;let o,a;try{let s=await e.json();o=(r=(t=s.error)==null?void 0:t.code)!=null?r:"unknown_error",a=(n=s.error)==null?void 0:n.message}catch{o="unknown_error"}a?.includes("contentType")&&a.includes("is not allowed")&&(o="content_type_not_allowed"),a?.includes('"pathname"')&&a.includes("does not match the token payload")&&(o="client_token_pathname_mismatch"),a==="Token expired"&&(o="client_token_expired"),a?.includes("the file length cannot be greater than")&&(o="file_too_large"),a?.startsWith("OIDC is enabled for this project, but not for the")&&a.includes("environment.")&&(o="oidc_environment_not_allowed");let i;switch(o){case"store_suspended":i=new gc;break;case"forbidden":i=new pc;break;case"oidc_environment_not_allowed":i=new uc(a);break;case"content_type_not_allowed":i=new fc(a);break;case"client_token_pathname_mismatch":i=new hc(a);break;case"client_token_expired":i=new mc;break;case"file_too_large":i=new yc(a);break;case"not_found":i=new bc;break;case"client_token_not_allowed":i=new y(a??"This operation is not available when using a client token. Use a read\u2013write or OIDC token on the server.");break;case"store_not_found":i=new wc;break;case"bad_request":i=new y(a??"Bad request");break;case"service_unavailable":i=new rr;break;case"rate_limited":i=Cc(e);break;case"precondition_failed":i=new vc;break;default:i=new Ya;break}return{code:o,error:i}}async function dt(e,t,r){let n=Ac(),o=await Zs(r),a=o.kind==="presigned"?void 0:o.token,i=Tc(),s=sn(e);r?.presignedUrlPayload&&(s=rc(s,r.presignedUrlPayload));let c=`${o.storeId}:${Date.now()}:${Math.random().toString(16).slice(2)}`,d=0,l=0,f=0,g=r?.onUploadProgress||Uc();t.body&&g&&(l=tr(t.body)),r?.onUploadProgress&&r.onUploadProgress({loaded:0,total:l,percentage:0});let b=await(0,za.default)(async w=>{let S;try{S=await lc({input:s,init:{...t,headers:{"x-api-blob-request-id":c,"x-vercel-blob-store-id":o.storeId,"x-api-blob-request-attempt":String(d),"x-api-version":n,...g?{"x-content-length":String(l)}:{},...a!==void 0?{authorization:`Bearer ${a}`}:{},...i,...t.headers}},onUploadProgress:r?.onUploadProgress?I=>{var V;let de=l!==0?l:I;f=I;let be=l>0?Number((I/de*100).toFixed(2)):0;be===100&&l>0||(V=r.onUploadProgress)==null||V.call(r,{loaded:I,total:de,percentage:be})}:void 0})}catch(I){if(I instanceof nc&&I.name==="AbortError"){w(new _c);return}if(sc(I))throw I;if(I instanceof TypeError){w(I);return}throw I}if(S.ok)return S;let{code:B,error:J}=await Pc(S);if(B==="unknown_error"||B==="service_unavailable"||B==="internal_server_error")throw J;w(J)},{retries:xc(),onRetry:w=>{w instanceof Error&&G(`retrying API request to ${e}`,w.message),d=d+1}});if(!b)throw new Ya;return r?.onUploadProgress&&r.onUploadProgress({loaded:f,total:f,percentage:100}),await b.json()}function Tc(){let e={};try{"VERCEL_BLOB_PROXY_THROUGH_ALTERNATIVE_API"in process.env&&process.env.VERCEL_BLOB_PROXY_THROUGH_ALTERNATIVE_API!==void 0?e["x-proxy-through-alternative-api"]=process.env.VERCEL_BLOB_PROXY_THROUGH_ALTERNATIVE_API:"NEXT_PUBLIC_VERCEL_BLOB_PROXY_THROUGH_ALTERNATIVE_API"in process.env&&process.env.NEXT_PUBLIC_VERCEL_BLOB_PROXY_THROUGH_ALTERNATIVE_API!==void 0&&(e["x-proxy-through-alternative-api"]=process.env.NEXT_PUBLIC_VERCEL_BLOB_PROXY_THROUGH_ALTERNATIVE_API)}catch{}return e}function Uc(){try{return process.env.VERCEL_BLOB_USE_X_CONTENT_LENGTH==="1"}catch{return!1}}var cn={jpeg:"image/jpeg",png:"image/png",webp:"image/webp",avif:"image/avif"};function Oc(e){if(typeof e!="object"||e===null)throw new y("optimizeImage must be an object, see usage");let{width:t,quality:r,format:n}=e;if(!Number.isInteger(t)||t<1||t>8192)throw new y("optimizeImage.width must be an integer between 1 and 8192");if(r!==void 0&&(!Number.isInteger(r)||r<1||r>100))throw new y("optimizeImage.quality must be an integer between 1 and 100");if(n!==void 0&&!(n in cn))throw new y(`optimizeImage.format must be one of: ${Object.keys(cn).join(", ")}`)}function Rc(e){if(e&&e!=="application/octet-stream"&&!e.startsWith("image/"))throw new y(`optimizeImage requires an image body, but the content type is "${e}"`)}function Ic(e,t){var r;Oc(t),e.set("width",String(t.width)),e.set("quality",String((r=t.quality)!=null?r:75)),t.format&&e.set("format",cn[t.format])}var Pe={cacheControlMaxAge:"x-cache-control-max-age",addRandomSuffix:"x-add-random-suffix",allowOverwrite:"x-allow-overwrite",contentType:"x-content-type",access:"x-vercel-blob-access",ifMatch:"x-if-match"};function lt(e,t){let r={};if(r[Pe.access]=t.access,e.includes("contentType")&&t.contentType&&(r[Pe.contentType]=t.contentType),e.includes("addRandomSuffix")&&t.addRandomSuffix!==void 0&&(r[Pe.addRandomSuffix]=t.addRandomSuffix?"1":"0"),e.includes("ifMatch")&&t.ifMatch){if(t.allowOverwrite===!1)throw new y("ifMatch and allowOverwrite: false are contradictory. ifMatch is used for conditional overwrites, which requires allowOverwrite to be true.");r[Pe.ifMatch]=t.ifMatch,e.includes("allowOverwrite")&&t.allowOverwrite===void 0&&(r[Pe.allowOverwrite]="1")}return e.includes("allowOverwrite")&&t.allowOverwrite!==void 0&&(r[Pe.allowOverwrite]=t.allowOverwrite?"1":"0"),e.includes("cacheControlMaxAge")&&t.cacheControlMaxAge!==void 0&&(r[Pe.cacheControlMaxAge]=t.cacheControlMaxAge.toString()),r}async function pt({pathname:e,options:t,extraChecks:r,getToken:n}){if(!e)throw new y("pathname is required");if(e.length>Ba)throw new y(`pathname is too long, maximum length is ${Ba}`);for(let o of ec)if(e.includes(o))throw new y(`pathname cannot contain "${o}", please encode it if needed`);if(!t)throw new y("missing options, see usage");if(t.access!=="public"&&t.access!=="private")throw new y('access must be "private" or "public", see https://vercel.com/docs/vercel-blob');return r&&r(t),n&&(t.token=await n(e,t)),t}function ja({allowedOptions:e,getToken:t,extraChecks:r}){return async(n,o,a)=>{let i=await pt({pathname:n,options:a,extraChecks:r,getToken:t}),s=lt(e,i);return pn({uploadId:i.uploadId,key:i.key,pathname:n,headers:s,options:i,parts:o})}}async function pn({uploadId:e,key:t,pathname:r,parts:n,headers:o,options:a}){let i=new URLSearchParams({pathname:r});try{let s=await dt(`/mpu?${i.toString()}`,{method:"POST",headers:{...o,"content-type":"application/json","x-mpu-action":"complete","x-mpu-upload-id":e,"x-mpu-key":encodeURIComponent(t)},body:JSON.stringify(n),signal:a.abortSignal},a);return G("mpu: complete",s),s}catch(s){throw s instanceof TypeError&&(s.message==="Failed to fetch"||s.message==="fetch failed")?new rr:s}}function Qa({allowedOptions:e,getToken:t,extraChecks:r}){return async(n,o)=>{let a=await pt({pathname:n,options:o,extraChecks:r,getToken:t}),i=lt(e,a),s=await un(n,i,a);return{key:s.key,uploadId:s.uploadId}}}async function un(e,t,r){G("mpu: create","pathname:",e);let n=new URLSearchParams({pathname:e});try{let o=await dt(`/mpu?${n.toString()}`,{method:"POST",headers:{...t,"x-mpu-action":"create"},signal:r.abortSignal},r);return G("mpu: create",o),o}catch(o){throw o instanceof TypeError&&(o.message==="Failed to fetch"||o.message==="fetch failed")?new rr:o}}function ei({allowedOptions:e,getToken:t,extraChecks:r}){return async(n,o,a)=>{let i=await pt({pathname:n,options:a,extraChecks:r,getToken:t}),s=lt(e,i);if(ln(o))throw new y("Body must be a string, buffer or stream. You sent a plain JavaScript object, double check what you're trying to upload.");return{etag:(await fn({uploadId:i.uploadId,key:i.key,pathname:n,part:{blob:o,partNumber:i.partNumber},headers:s,options:i})).etag,partNumber:i.partNumber}}}async function fn({uploadId:e,key:t,pathname:r,headers:n,options:o,internalAbortController:a=new AbortController,part:i}){var s,c,d;let l=new URLSearchParams({pathname:r}),f=dt(`/mpu?${l.toString()}`,{signal:a.signal,method:"POST",headers:{...n,"x-mpu-action":"upload","x-mpu-key":encodeURIComponent(t),"x-mpu-upload-id":e,"x-mpu-part-number":i.partNumber.toString()},body:i.blob},o);function g(){a.abort()}(s=o.abortSignal)!=null&&s.aborted?g():(c=o.abortSignal)==null||c.addEventListener("abort",g);let b=await f;return(d=o.abortSignal)==null||d.removeEventListener("abort",g),b}var ti=typeof window<"u"?6:8,dn=8*1024*1024,ct=ti*dn*2;function Kc({uploadId:e,key:t,pathname:r,stream:n,headers:o,options:a,totalToLoad:i}){G("mpu: upload init","key:",t);let s=new AbortController;return new Promise((c,d)=>{let l=[],f=[],g=n.getReader(),b=0,w=!1,S=1,B=!1,J=0,I=!1,V=0,de=[],be=0,or,hn={};a.onUploadProgress&&(or=(0,Za.default)(()=>{var P;let j=Object.values(hn).reduce((mt,yt)=>mt+yt,0),le=i||j,ze=i>0?Number(((j/i||j)*100).toFixed(2)):0;(P=a.onUploadProgress)==null||P.call(a,{loaded:j,total:le,percentage:ze})},150)),mn().catch(ht);async function mn(){for(G("mpu: upload read start","activeUploads:",b,"currentBytesInMemory:",`${q(J)}/${q(ct)}`,"bytesSent:",q(V)),w=!0;J<ct&&!B;)try{let{value:P,done:j}=await g.read();if(j){I=!0,G("mpu: upload read consumed the whole stream"),de.length>0?(l.push({partNumber:S++,blob:new Blob(de,{type:"application/octet-stream"})}),ar()):b===0&&(g.releaseLock(),c(f)),w=!1;return}J+=P.byteLength;let le=0;for(;le<P.byteLength;){let ze=dn-be,mt=Math.min(le+ze,P.byteLength),yt=P.slice(le,mt);de.push(yt),be+=yt.byteLength,le=mt,be===dn&&(l.push({partNumber:S++,blob:new Blob(de,{type:"application/octet-stream"})}),de=[],be=0,ar())}}catch(P){ht(P)}G("mpu: upload read end","activeUploads:",b,"currentBytesInMemory:",`${q(J)}/${q(ct)}`,"bytesSent:",q(V)),w=!1}async function di(P){b++,G("mpu: upload send part start","partNumber:",P.partNumber,"size:",P.blob.size,"activeUploads:",b,"currentBytesInMemory:",`${q(J)}/${q(ct)}`,"bytesSent:",q(V));try{let j=a.onUploadProgress?ze=>{hn[P.partNumber]=ze.loaded,or&&or()}:void 0,le=await fn({uploadId:e,key:t,pathname:r,headers:o,options:{...a,onUploadProgress:j},internalAbortController:s,part:P});if(G("mpu: upload send part end","partNumber:",P.partNumber,"activeUploads",b,"currentBytesInMemory:",`${q(J)}/${q(ct)}`,"bytesSent:",q(V)),B)return;if(f.push({partNumber:P.partNumber,etag:le.etag}),J-=P.blob.size,b--,V+=P.blob.size,l.length>0&&ar(),I){b===0&&(g.releaseLock(),c(f));return}w||mn().catch(ht)}catch(j){ht(j)}}function ar(){if(!B)for(G("send parts","activeUploads",b,"partsToUpload",l.length);b<ti&&l.length>0;){let P=l.shift();P&&di(P)}}function ht(P){B||(B=!0,s.abort(),g.releaseLock(),P instanceof TypeError&&(P.message==="Failed to fetch"||P.message==="fetch failed")?d(new rr):d(P))}})}function ri({allowedOptions:e,getToken:t,extraChecks:r}){return async(n,o)=>{let a=await pt({pathname:n,options:o,extraChecks:r,getToken:t}),i=lt(e,a),s=await un(n,i,a);return{key:s.key,uploadId:s.uploadId,async uploadPart(c,d){if(ln(d))throw new y("Body must be a string, buffer or stream. You sent a plain JavaScript object, double check what you're trying to upload.");return{etag:(await fn({uploadId:s.uploadId,key:s.key,pathname:n,part:{partNumber:c,blob:d},headers:i,options:a})).etag,partNumber:c}},async complete(c){return pn({uploadId:s.uploadId,key:s.key,pathname:n,parts:c,headers:i,options:a})}}}}async function Hc(e,t,r,n){G("mpu: init","pathname:",e,"headers:",r);let o={...n,onUploadProgress:void 0};if(n.maximumSizeInBytes!==void 0&&!Ga(t)&&tr(t)>n.maximumSizeInBytes)throw new y(`Body size of ${tr(t)} bytes exceeds the maximum allowed size of ${n.maximumSizeInBytes} bytes`);let a=await un(e,r,o),i=tr(t),s=await Na(t),c=await Kc({uploadId:a.uploadId,key:a.key,pathname:e,stream:s,headers:r,options:n,totalToLoad:i});return await pn({uploadId:a.uploadId,key:a.key,pathname:e,parts:c,headers:r,options:o})}function nr({allowedOptions:e,getToken:t,getPresignedUrlPayload:r,extraChecks:n}){return async function(a,i,s){var c;if(!i)throw new y("body is required");if(ln(i))throw new y("Body must be a string, buffer or stream. You sent a plain JavaScript object, double check what you're trying to upload.");let d=await pt({pathname:a,options:s,extraChecks:n,getToken:t}),l=await r?.(a,d),f={...d,presignedUrlPayload:l},g=lt(e,d);if(d.optimizeImage){if(d.multipart===!0)throw new y("optimizeImage cannot be combined with multipart uploads");Rc((c=d.contentType)!=null?c:typeof Blob<"u"&&i instanceof Blob?i.type:void 0);let B=new URLSearchParams({pathname:a});Ic(B,d.optimizeImage);let J=await dt(`/put-optimized?${B.toString()}`,{method:"POST",body:i,headers:g,signal:d.abortSignal},f);return{url:J.url,downloadUrl:J.downloadUrl,pathname:J.pathname,contentType:J.contentType,contentDisposition:J.contentDisposition,etag:J.etag}}if(d.multipart===!0)return Hc(a,i,g,f);let b=d.onUploadProgress?(0,ni.default)(d.onUploadProgress,100):void 0,w=new URLSearchParams({pathname:a}),S=await dt(`/?${w.toString()}`,{method:"PUT",body:i,headers:g,signal:d.abortSignal},{...f,onUploadProgress:b});return{url:S.url,downloadUrl:S.downloadUrl,pathname:S.pathname,contentType:S.contentType,contentDisposition:S.contentDisposition,etag:S.etag}}}var _m=365*24*60*60;var vm=new TextEncoder;function ut(e){return function(r){if(!r.token.startsWith("vercel_blob_client_"))throw new y(`${e} must be called with a client token`);if(r.addRandomSuffix!==void 0||r.allowOverwrite!==void 0||r.cacheControlMaxAge!==void 0)throw new y(`${e} doesn't allow \`addRandomSuffix\`, \`cacheControlMaxAge\` or \`allowOverwrite\`. Configure these options at the server side when generating client tokens.`)}}var oi=nr({allowedOptions:["contentType"],extraChecks:ut("client/`put`")}),Vm=Qa({allowedOptions:["contentType"],extraChecks:ut("client/`createMultipartUpload`")}),Fm=ri({allowedOptions:["contentType"],extraChecks:ut("client/`createMultipartUpload`")}),Gm=ei({allowedOptions:["contentType"],extraChecks:ut("client/`multipartUpload`")}),zm=ja({allowedOptions:["contentType"],extraChecks:ut("client/`completeMultipartUpload`")}),qm=nr({allowedOptions:["contentType"],extraChecks(e){if(e.handleUploadUrl===void 0)throw new y("client/`upload` requires the 'handleUploadUrl' parameter");if(e.addRandomSuffix!==void 0||e.allowOverwrite!==void 0||e.cacheControlMaxAge!==void 0||e.ifMatch!==void 0)throw new y("client/`upload` doesn't allow `addRandomSuffix`, `cacheControlMaxAge`, `allowOverwrite` or `ifMatch`. Configure these options at the server side when generating client tokens.")},async getToken(e,t){var r,n;return kc({handleUploadUrl:t.handleUploadUrl,pathname:e,clientPayload:(r=t.clientPayload)!=null?r:null,multipart:(n=t.multipart)!=null?n:!1,headers:t.headers})}}),Xm=nr({allowedOptions:["contentType"],extraChecks(e){if(e.handleUploadUrl===void 0)throw new y("client/`upload` requires the 'handleUploadUrl' parameter");if(e.addRandomSuffix!==void 0||e.allowOverwrite!==void 0||e.cacheControlMaxAge!==void 0||e.ifMatch!==void 0)throw new y("client/`uploadPresigned` doesn't allow `addRandomSuffix`, `cacheControlMaxAge`, `allowOverwrite` or `ifMatch`. Configure these options at the server side when generating presigned URLs.")},async getPresignedUrlPayload(e,t){var r,n;return Wc({pathname:e,handleUploadUrl:t.handleUploadUrl,clientPayload:(r=t.clientPayload)!=null?r:null,multipart:(n=t.multipart)!=null?n:!1,headers:t.headers})}});var ai={generateClientToken:"blob.generate-client-token",generatePresignedUrl:"blob.generate-presigned-url",uploadCompleted:"blob.upload-completed"};async function kc(e){let{handleUploadUrl:t,pathname:r}=e,n=si(t)?t:ii(t),o={type:ai.generateClientToken,payload:{pathname:r,clientPayload:e.clientPayload,multipart:e.multipart}},a=await Ge(n,{method:"POST",body:JSON.stringify(o),headers:{"content-type":"application/json",...e.headers},signal:e.abortSignal});if(!a.ok)throw new y("Failed to retrieve the client token");try{let{clientToken:i}=await a.json();return i}catch{throw new y("Failed to retrieve the client token")}}async function Wc(e){let{handleUploadUrl:t,pathname:r}=e,n=si(t)?t:ii(t),o={type:ai.generatePresignedUrl,payload:{pathname:r,clientPayload:e.clientPayload,multipart:e.multipart}},a=await Ge(n,{method:"POST",body:JSON.stringify(o),headers:{"content-type":"application/json",...e.headers},signal:e.abortSignal});if(!a.ok)throw new y("Failed to retrieve the presigned URL");try{let{presignedUrlPayload:i}=await a.json();if(i)return i;throw new y("Missing presignedUrlPayload")}catch(i){throw i instanceof y?i:new y("Failed to retrieve the presigned URL")}}function ii(e){return new URL(e,location.href).href}function si(e){try{return!!new URL(e)}catch{return!1}}var Jc="/checkout/api/line-item-uploads",Lc=20*1024*1024,ci={jpg:"image/jpeg",jpeg:"image/jpeg",png:"image/png",webp:"image/webp",gif:"image/gif",heic:"image/heic",heif:"image/heif",avif:"image/avif",tif:"image/tiff",tiff:"image/tiff",pdf:"application/pdf"},Qm=[...new Set(Object.values(ci))].join(","),ft=class extends Error{constructor(r,n){super(r);wn(this,"status");this.name="LineItemUploadError",this.status=n}},Bc=e=>e.type||ci[e.name.split(".").pop()?.toLowerCase()??""]||"",Mc=e=>typeof e=="object"&&e!==null&&"uploadId"in e&&typeof e.uploadId=="string"&&"pathname"in e&&typeof e.pathname=="string"&&"clientToken"in e&&typeof e.clientToken=="string",Nc=e=>typeof e=="object"&&e!==null&&"error"in e&&typeof e.error=="string"?e.error:null;async function Zm(e,t){let r=Bc(e);if(!r)throw new ft("This file type can't be uploaded.",400);if(e.size>Lc)throw new ft("The file is larger than 20 MB.",400);let n=await fetch(t.endpoint??Jc,{method:"POST",headers:{"Content-Type":"application/json"},credentials:"same-origin",body:JSON.stringify({variantId:t.variantId,filename:e.name,contentType:r,size:e.size}),...t.abortSignal?{signal:t.abortSignal}:{}}),o=await n.json().catch(()=>null);if(!n.ok||!Mc(o))throw new ft(Nc(o)??"The upload could not start.",n.status);return await oi(o.pathname,e,{access:"private",token:o.clientToken,contentType:r,multipart:e.size>8*1024*1024,...t.onUploadProgress?{onUploadProgress:t.onUploadProgress}:{},...t.abortSignal?{abortSignal:t.abortSignal}:{}}),{uploadId:o.uploadId}}var ey=({key:e,label:t,uploadId:r})=>({key:e,...t!==void 0?{label:t}:{},type:"file",value:r});export{Qm as ACCEPTED_LINE_ITEM_UPLOAD_TYPES,Jc as LINE_ITEM_UPLOAD_ENDPOINT,ft as LineItemUploadError,Lc as MAX_LINE_ITEM_UPLOAD_BYTES,ey as lineItemFileProperty,Zm as uploadLineItemFile};
|
|
5
|
-
/*! Bundled license information:
|
|
1
|
+
var __defProp = Object.defineProperty;
|
|
2
|
+
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
|
|
3
|
+
var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
|
|
6
4
|
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
5
|
+
// src/uploads.ts
|
|
6
|
+
import { put } from "@vercel/blob/client";
|
|
7
|
+
var LINE_ITEM_UPLOAD_ENDPOINT = "/checkout/api/line-item-uploads";
|
|
8
|
+
var MAX_LINE_ITEM_UPLOAD_BYTES = 20 * 1024 * 1024;
|
|
9
|
+
var TYPE_BY_EXTENSION = {
|
|
10
|
+
jpg: "image/jpeg",
|
|
11
|
+
jpeg: "image/jpeg",
|
|
12
|
+
png: "image/png",
|
|
13
|
+
webp: "image/webp",
|
|
14
|
+
gif: "image/gif",
|
|
15
|
+
heic: "image/heic",
|
|
16
|
+
heif: "image/heif",
|
|
17
|
+
avif: "image/avif",
|
|
18
|
+
tif: "image/tiff",
|
|
19
|
+
tiff: "image/tiff",
|
|
20
|
+
pdf: "application/pdf"
|
|
21
|
+
};
|
|
22
|
+
var ACCEPTED_LINE_ITEM_UPLOAD_TYPES = [...new Set(Object.values(TYPE_BY_EXTENSION))].join(",");
|
|
23
|
+
var LineItemUploadError = class extends Error {
|
|
24
|
+
constructor(message, status) {
|
|
25
|
+
super(message);
|
|
26
|
+
__publicField(this, "status");
|
|
27
|
+
this.name = "LineItemUploadError";
|
|
28
|
+
this.status = status;
|
|
29
|
+
}
|
|
30
|
+
};
|
|
31
|
+
var contentTypeOf = (file) => file.type || TYPE_BY_EXTENSION[file.name.split(".").pop()?.toLowerCase() ?? ""] || "";
|
|
32
|
+
var isTokenResponse = (value) => typeof value === "object" && value !== null && "uploadId" in value && typeof value.uploadId === "string" && "pathname" in value && typeof value.pathname === "string" && "clientToken" in value && typeof value.clientToken === "string";
|
|
33
|
+
var errorMessageOf = (value) => typeof value === "object" && value !== null && "error" in value && typeof value.error === "string" ? value.error : null;
|
|
34
|
+
async function uploadLineItemFile(file, options) {
|
|
35
|
+
const contentType = contentTypeOf(file);
|
|
36
|
+
if (!contentType) {
|
|
37
|
+
throw new LineItemUploadError("This file type can't be uploaded.", 400);
|
|
38
|
+
}
|
|
39
|
+
if (file.size > MAX_LINE_ITEM_UPLOAD_BYTES) {
|
|
40
|
+
throw new LineItemUploadError("The file is larger than 20 MB.", 400);
|
|
41
|
+
}
|
|
42
|
+
const response = await fetch(options.endpoint ?? LINE_ITEM_UPLOAD_ENDPOINT, {
|
|
43
|
+
method: "POST",
|
|
44
|
+
headers: { "Content-Type": "application/json" },
|
|
45
|
+
credentials: "same-origin",
|
|
46
|
+
body: JSON.stringify({ variantId: options.variantId, filename: file.name, contentType, size: file.size }),
|
|
47
|
+
...options.abortSignal ? { signal: options.abortSignal } : {}
|
|
48
|
+
});
|
|
49
|
+
const body = await response.json().catch(() => null);
|
|
50
|
+
if (!response.ok || !isTokenResponse(body)) {
|
|
51
|
+
throw new LineItemUploadError(errorMessageOf(body) ?? "The upload could not start.", response.status);
|
|
52
|
+
}
|
|
53
|
+
await put(body.pathname, file, {
|
|
54
|
+
access: "private",
|
|
55
|
+
token: body.clientToken,
|
|
56
|
+
contentType,
|
|
57
|
+
multipart: file.size > 8 * 1024 * 1024,
|
|
58
|
+
...options.onUploadProgress ? { onUploadProgress: options.onUploadProgress } : {},
|
|
59
|
+
...options.abortSignal ? { abortSignal: options.abortSignal } : {}
|
|
60
|
+
});
|
|
61
|
+
return { uploadId: body.uploadId };
|
|
62
|
+
}
|
|
63
|
+
var lineItemFileProperty = ({
|
|
64
|
+
key,
|
|
65
|
+
label,
|
|
66
|
+
uploadId
|
|
67
|
+
}) => ({
|
|
68
|
+
key,
|
|
69
|
+
...label !== void 0 ? { label } : {},
|
|
70
|
+
type: "file",
|
|
71
|
+
value: uploadId
|
|
72
|
+
});
|
|
73
|
+
export {
|
|
74
|
+
ACCEPTED_LINE_ITEM_UPLOAD_TYPES,
|
|
75
|
+
LINE_ITEM_UPLOAD_ENDPOINT,
|
|
76
|
+
LineItemUploadError,
|
|
77
|
+
MAX_LINE_ITEM_UPLOAD_BYTES,
|
|
78
|
+
lineItemFileProperty,
|
|
79
|
+
uploadLineItemFile
|
|
80
|
+
};
|
|
23
81
|
//# sourceMappingURL=uploads.js.map
|