@shumai-one/shumai-agent 0.6.0 → 0.6.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (99) hide show
  1. package/bin/chunk-023w4q1f.js +2 -0
  2. package/bin/chunk-29r6a67p.js +2 -0
  3. package/bin/chunk-2exf93nx.js +3 -0
  4. package/bin/chunk-3ev1fh2w.js +3 -0
  5. package/bin/chunk-3kt4k4jg.js +11 -0
  6. package/bin/chunk-62n25c3m.js +2 -0
  7. package/bin/chunk-6pf9rgk6.js +2 -0
  8. package/bin/{chunk-yk14703k.js → chunk-7bn1mjf2.js} +2 -2
  9. package/bin/chunk-7pwsjw9r.js +8 -0
  10. package/bin/{chunk-vnn8sej7.js → chunk-847yv5m2.js} +10 -10
  11. package/bin/chunk-9fqyh49m.js +2 -0
  12. package/bin/chunk-a5rn622e.js +7 -0
  13. package/bin/chunk-akj1v1zj.js +5 -0
  14. package/bin/{chunk-w5h5ctmd.js → chunk-am25vkck.js} +2 -2
  15. package/bin/chunk-at5qzp08.js +7 -0
  16. package/bin/chunk-b2n9g75s.js +2 -0
  17. package/bin/chunk-b767451d.js +3 -0
  18. package/bin/chunk-bsxxt20c.js +2 -0
  19. package/bin/{chunk-yd3kbedy.js → chunk-crc78aby.js} +2 -2
  20. package/bin/chunk-ee8rt9we.js +2 -0
  21. package/bin/chunk-eh6xcwvv.js +16 -0
  22. package/bin/chunk-fgabndrh.js +4 -0
  23. package/bin/chunk-fq1tf20c.js +45 -0
  24. package/bin/chunk-g7ad4dw4.js +2 -0
  25. package/bin/chunk-g7v8pfhe.js +2 -0
  26. package/bin/chunk-gx33h4rt.js +3 -0
  27. package/bin/chunk-hnpr396w.js +12 -0
  28. package/bin/chunk-hssdv3mc.js +2 -0
  29. package/bin/chunk-m3saxrzj.js +13 -0
  30. package/bin/chunk-mnd4dn3q.js +2 -0
  31. package/bin/chunk-nmygzasv.js +2 -0
  32. package/bin/chunk-nwz9f1dy.js +2 -0
  33. package/bin/chunk-p5nhcxwg.js +3 -0
  34. package/bin/chunk-pbdctjg4.js +2 -0
  35. package/bin/chunk-pphsqcqt.js +2 -0
  36. package/bin/chunk-pqa01d4g.js +2 -0
  37. package/bin/{chunk-7w6jsrka.js → chunk-q0x8yqms.js} +2 -2
  38. package/bin/chunk-q5w77y3e.js +2 -0
  39. package/bin/chunk-rf428t28.js +2 -0
  40. package/bin/chunk-rkcsrrvy.js +497 -0
  41. package/bin/chunk-rtqengn3.js +2 -0
  42. package/bin/chunk-rx0fmt6n.js +4 -0
  43. package/bin/chunk-ss91akc0.js +2 -0
  44. package/bin/{chunk-dsa7hrkt.js → chunk-stex0y7j.js} +2 -2
  45. package/bin/chunk-vngxwvwv.js +2 -0
  46. package/bin/chunk-w0e5ek1r.js +2 -0
  47. package/bin/chunk-x71z4a2a.js +3 -0
  48. package/bin/chunk-z19gfsnw.js +3 -0
  49. package/bin/chunk-z3gbypjs.js +2 -0
  50. package/bin/chunk-zphx997k.js +8 -0
  51. package/bin/shumai-agent-app.js +862 -1062
  52. package/package.json +7 -7
  53. package/prisma/migrations/20261026024507_hash_api_tokens/migration.sql +28 -0
  54. package/prisma/migrations/20261026031904_add_audit_log_via/migration.sql +2 -0
  55. package/prisma/migrations/20261029024626_add_oauth_and_jwks/migration.sql +205 -0
  56. package/prisma/migrations/20261029030321_default_empty_arrays_oauth/migration.sql +25 -0
  57. package/prisma/schema.prisma +186 -1
  58. package/bin/chunk-28e1j4am.js +0 -2
  59. package/bin/chunk-2gyngq15.js +0 -11
  60. package/bin/chunk-2n1dj1cv.js +0 -2
  61. package/bin/chunk-46jd4vhk.js +0 -45
  62. package/bin/chunk-56c9m0pd.js +0 -2
  63. package/bin/chunk-5yd2h4j1.js +0 -2
  64. package/bin/chunk-6ddtb9e6.js +0 -2
  65. package/bin/chunk-7qprxs9y.js +0 -2
  66. package/bin/chunk-8kyt2vpr.js +0 -7
  67. package/bin/chunk-8z4drz4c.js +0 -8
  68. package/bin/chunk-av6bexjx.js +0 -3
  69. package/bin/chunk-bhgneh6h.js +0 -2
  70. package/bin/chunk-c26v3b7f.js +0 -3
  71. package/bin/chunk-cam5rwb7.js +0 -2
  72. package/bin/chunk-e5amq469.js +0 -16
  73. package/bin/chunk-e5s9dk8d.js +0 -2
  74. package/bin/chunk-g80kdkky.js +0 -2
  75. package/bin/chunk-gmfm23kd.js +0 -2
  76. package/bin/chunk-h3dvj1c7.js +0 -12
  77. package/bin/chunk-hg8pmr2h.js +0 -2
  78. package/bin/chunk-jheky96k.js +0 -3
  79. package/bin/chunk-jtsbe34h.js +0 -4
  80. package/bin/chunk-k71cxhsn.js +0 -2
  81. package/bin/chunk-m4801ex4.js +0 -2
  82. package/bin/chunk-mfyektx6.js +0 -2
  83. package/bin/chunk-mryt63fx.js +0 -2
  84. package/bin/chunk-n75x7as6.js +0 -3
  85. package/bin/chunk-p0sycvda.js +0 -3
  86. package/bin/chunk-ph0978mm.js +0 -3
  87. package/bin/chunk-q032segv.js +0 -2
  88. package/bin/chunk-qnh6wt00.js +0 -2
  89. package/bin/chunk-qve2p771.js +0 -2
  90. package/bin/chunk-sgv9dhyw.js +0 -2
  91. package/bin/chunk-sk26g8gq.js +0 -5
  92. package/bin/chunk-tsfemjnp.js +0 -4
  93. package/bin/chunk-w2xc1r8f.js +0 -3
  94. package/bin/chunk-w5jhww1y.js +0 -8
  95. package/bin/chunk-w82m268v.js +0 -2
  96. package/bin/chunk-xpx7v1cz.js +0 -2
  97. package/bin/chunk-ynv1dwvb.js +0 -7
  98. package/bin/chunk-ywmjzwj6.js +0 -13
  99. package/bin/chunk-z65d9fhw.js +0 -2
@@ -0,0 +1,497 @@
1
+ // @bun
2
+ import{E,A,Ie,C,X,tt,H,yt,Lt,Et,B,yr,V,Er,ke,Cr,Ct,It,Se,Fr,te,ue,W,zr}from"./chunk-mnd4dn3q.js";var Nu=A(function(XH){var G_;(function(e){e.HEADER="header",e.QUERY="query"})(G_||(G_={}));var K_;(function(e){e.HEADER="header",e.QUERY="query"})(K_||(K_={}));var J_;(function(e){e.HTTP="http",e.HTTPS="https"})(J_||(J_={}));var Af;(function(e){e.MD5="md5",e.CRC32="crc32",e.CRC32C="crc32c",e.SHA1="sha1",e.SHA256="sha256"})(Af||(Af={}));var GH=(e)=>{let t=[];if(e.sha256!==void 0)t.push({algorithmId:()=>Af.SHA256,checksumConstructor:()=>e.sha256});if(e.md5!=null)t.push({algorithmId:()=>Af.MD5,checksumConstructor:()=>e.md5});return{addChecksumAlgorithm(r){t.push(r)},checksumAlgorithms(){return t}}},KH=(e)=>{let t={};return e.checksumAlgorithms().forEach((r)=>{t[r.algorithmId()]=r.checksumConstructor()}),t},JH=(e)=>GH(e),QH=(e)=>KH(e),Q_;(function(e){e[e.HEADER=0]="HEADER",e[e.TRAILER=1]="TRAILER"})(Q_||(Q_={}));var YH="__smithy_context",Y_;(function(e){e.PROFILE="profile",e.SSO_SESSION="sso-session",e.SERVICES="services"})(Y_||(Y_={}));var X_;(function(e){e.HTTP_0_9="http/0.9",e.HTTP_1_0="http/1.0",e.TDS_8_0="tds/8.0"})(X_||(X_={}));XH.AlgorithmId=Af;XH.EndpointURLScheme=J_;XH.FieldPosition=Q_;XH.HttpApiKeyAuthLocation=K_;XH.HttpAuthLocation=G_;XH.IniSectionType=Y_;XH.RequestHandlerProtocol=X_;XH.SMITHY_CONTEXT_KEY=YH;XH.getDefaultClientConfiguration=JH;XH.resolveDefaultRuntimeConfig=QH});var Po=A(function(mV){var{SMITHY_CONTEXT_KEY:Tk}=Nu(),uV=(e)=>e[Tk]||(e[Tk]={});function vk(e,t){return Object.prototype.hasOwnProperty.call(e,t)}class rm{method;protocol;hostname;port;path;query;headers;username;password;fragment;body;constructor(e){this.method=e.method||"GET",this.hostname=e.hostname||"localhost",this.port=e.port,this.query=e.query||{},this.headers=e.headers||{},this.body=e.body,this.protocol=e.protocol?e.protocol.slice(-1)!==":"?`${e.protocol}:`:e.protocol:"https:",this.path=e.path?e.path.charAt(0)!=="/"?`/${e.path}`:e.path:"/",this.username=e.username,this.password=e.password,this.fragment=e.fragment}static clone(e){let t=new rm({...e,headers:{...e.headers}});if(t.query)t.query=dV(t.query);return t}static isInstance(e){if(!e)return!1;let t=e;return"method"in t&&"protocol"in t&&"hostname"in t&&"path"in t&&typeof t.query==="object"&&typeof t.headers==="object"}clone(){return rm.clone(this)}}function dV(e){return Object.keys(e).reduce((t,r)=>{let n=e[r];return{...t,[r]:Array.isArray(n)?[...n]:n}},{})}class kk{statusCode;reason;headers;body;constructor(e){this.statusCode=e.statusCode,this.reason=e.reason,this.headers=e.headers||{},this.body=e.body}static isInstance(e){if(!e)return!1;let t=e;return typeof t.statusCode==="number"&&typeof t.headers==="object"}}var lV=new RegExp("^(?!.*-$)(?!-)[a-zA-Z0-9-]{1,63}$"),Rk=(e,t=!1)=>{if(!t)return lV.test(e);let r=e.split(".");for(let n of r)if(!Rk(n))return!1;return!0};function fV(e){return/^[a-z0-9][a-z0-9.-]*[a-z0-9]$/.test(e)}var hV=(e)=>{if(typeof e==="function")return e;let t=Promise.resolve(e);return()=>t};function Nk(e){let t={};if(e=e.replace(/^\?/,""),e)for(let r of e.split("&")){let[n,i=null]=r.split("=");if(n=decodeURIComponent(n),i)i=decodeURIComponent(i);if(!(n in t))t[n]=i;else if(Array.isArray(t[n]))t[n].push(i);else t[n]=[t[n],i]}return t}var nm=(e)=>{if(typeof e==="string")return nm(new URL(e));let{hostname:t,pathname:r,port:n,protocol:i,search:o}=e,s;if(o)s=Nk(o);return{hostname:t,port:n?parseInt(n):void 0,protocol:i,path:r,query:s}},pV=(e)=>{if(typeof e==="object"){if("url"in e){let t=nm(e.url);if(e.headers){t.headers={};for(let r in e.headers){if(!vk(e.headers,r))continue;t.headers[r.toLowerCase()]=e.headers[r].join(", ")}}return t}return e}return nm(e)};mV.HttpRequest=rm;mV.HttpResponse=kk;mV.getSmithyContext=uV;mV.hasOwn=vk;mV.isValidHostLabel=Rk;mV.isValidHostname=fV;mV.normalizeProvider=hV;mV.parseQueryString=Nk;mV.parseUrl=nm;mV.toEndpointV1=pV});var le=A(function(BV){var{getSmithyContext:xk,HttpResponse:kV,toEndpointV1:RV}=Po(),im=(e)=>{if(typeof e==="function")return e();return e},tb=(e,t,r,n,i)=>({name:t,namespace:e,traits:r,input:n,output:i}),NV=(e)=>(t,r)=>async(n)=>{let{response:i}=await t(n),{operationSchema:o}=xk(r),[,s,a,c,u,d]=o??[];try{let f=await e.protocol.deserializeResponse(tb(s,a,c,u,d),{...e,...r},i);return{response:i,output:f}}catch(f){if(Object.defineProperty(f,"$response",{value:i,enumerable:!1,writable:!1,configurable:!1}),!("$metadata"in f)){try{f.message+=`
3
+ Deserialization error: to see the raw response, inspect the hidden field {error}.$response on this object.`}catch(p){if(!r.logger||r.logger?.constructor?.name==="NoOpLogger")console.warn("Deserialization error: to see the raw response, inspect the hidden field {error}.$response on this object.");else r.logger?.warn?.("Deserialization error: to see the raw response, inspect the hidden field {error}.$response on this object.")}if(typeof f.$responseBodyText<"u"){if(f.$response)f.$response.body=f.$responseBodyText}try{if(kV.isInstance(i)){let{headers:p={},statusCode:g}=i,_=Object.entries(p);f.$metadata={httpStatusCode:g,requestId:Z_(/^x-[\w-]+-request-?id$/,_),extendedRequestId:Z_(/^x-[\w-]+-id-2$/,_),cfId:Z_(/^x-[\w-]+-cf-id$/,_)}}}catch(p){}}throw f}},Z_=(e,t)=>(t.find(([r])=>r.match(e))||[void 0,void 0])[1],xV=(e)=>(t,r)=>async(n)=>{let{operationSchema:i}=xk(r),[,o,s,a,c,u]=i??[],d=r.endpointV2?async()=>RV(r.endpointV2):e.endpoint,f=await e.protocol.serializeRequest(tb(o,s,a,c,u),n.input,{...e,...r,endpoint:d});return t({...n,request:f})},Ck={name:"deserializerMiddleware",step:"deserialize",tags:["DESERIALIZER"],override:!0},Ok={name:"serializerMiddleware",step:"serialize",tags:["SERIALIZER"],override:!0};function CV(e){return{applyToStack:(t)=>{t.add(xV(e),Ok),t.add(NV(e),Ck),e.protocol.setSerdeContext(e)}}}class Ao{name;namespace;traits;static assign(e,t){return Object.assign(e,t)}static[Symbol.hasInstance](e){let t=this.prototype.isPrototypeOf(e);if(!t&&typeof e==="object"&&e!==null)return e.symbol===this.symbol;return t}getName(){return this.namespace+"#"+this.name}}class cm extends Ao{static symbol=Symbol.for("@smithy/lis");valueSchema;symbol=cm.symbol}var OV=(e,t,r,n)=>Ao.assign(new cm,{name:t,namespace:e,traits:r,valueSchema:n});class um extends Ao{static symbol=Symbol.for("@smithy/map");keySchema;valueSchema;symbol=um.symbol}var IV=(e,t,r,n,i)=>Ao.assign(new um,{name:t,namespace:e,traits:r,keySchema:n,valueSchema:i});class dm extends Ao{static symbol=Symbol.for("@smithy/ope");input;output;symbol=dm.symbol}var DV=(e,t,r,n,i)=>Ao.assign(new dm,{name:t,namespace:e,traits:r,input:n,output:i});class Rf extends Ao{static symbol=Symbol.for("@smithy/str");memberNames;memberList;symbol=Rf.symbol}var UV=(e,t,r,n,i)=>Ao.assign(new Rf,{name:t,namespace:e,traits:r,memberNames:n,memberList:i});class lm extends Rf{static symbol=Symbol.for("@smithy/err");ctor;symbol=lm.symbol}var PV=(e,t,r,n,i,o)=>Ao.assign(new lm,{name:t,namespace:e,traits:r,memberNames:n,memberList:i,ctor:null}),om=[];function kf(e){if(typeof e==="object")return e;if(e=e|0,om[e])return om[e];let t={},r=0;for(let n of["httpLabel","idempotent","idempotencyToken","sensitive","httpPayload","httpResponseCode","httpQueryParams"])if((e>>r++&1)===1)t[n]=1;return om[e]=t}var Tf={it:Symbol.for("@smithy/nor-struct-it"),ns:Symbol.for("@smithy/ns")},sm=[],am={};class Ba{ref;memberName;static symbol=Symbol.for("@smithy/nor");symbol=Ba.symbol;name;schema;_isMemberSchema;traits;memberTraits;normalizedTraits;constructor(e,t){this.ref=e,this.memberName=t;let r=[],n=e,i=e;this._isMemberSchema=!1;while(eb(n))r.push(n[1]),n=n[0],i=im(n),this._isMemberSchema=!0;if(r.length>0){this.memberTraits={};for(let o=r.length-1;o>=0;--o){let s=r[o];Object.assign(this.memberTraits,kf(s))}}else this.memberTraits=0;if(i instanceof Ba){let o=this.memberTraits;Object.assign(this,i),this.memberTraits=Object.assign({},o,i.getMemberTraits(),this.getMemberTraits()),this.normalizedTraits=void 0,this.memberName=t??i.memberName;return}if(this.schema=im(i),Ik(this.schema))this.name=`${this.schema[1]}#${this.schema[2]}`,this.traits=this.schema[3];else this.name=this.memberName??String(i),this.traits=0;if(this._isMemberSchema&&!t)throw Error(`@smithy/core/schema - NormalizedSchema member init ${this.getName(!0)} missing member name.`)}static[Symbol.hasInstance](e){let t=this.prototype.isPrototypeOf(e);if(!t&&typeof e==="object"&&e!==null)return e.symbol===this.symbol;return t}static of(e){let t=typeof e==="function"||typeof e==="object"&&e!==null;if(typeof e==="number"){if(sm[e])return sm[e]}else if(typeof e==="string"){if(am[e])return am[e]}else if(t){if(e[Tf.ns])return e[Tf.ns]}let r=im(e);if(r instanceof Ba)return r;if(eb(r)){let[i,o]=r;if(i instanceof Ba)return Object.assign(i.getMergedTraits(),kf(o)),i;throw Error(`@smithy/core/schema - may not init unwrapped member schema=${JSON.stringify(e,null,2)}.`)}let n=new Ba(r);if(t)return e[Tf.ns]=n;if(typeof r==="string")return am[r]=n;if(typeof r==="number")return sm[r]=n;return n}getSchema(){let e=this.schema;if(Array.isArray(e)&&e[0]===0)return e[4];return e}getName(e=!1){let{name:t}=this;return!e&&t&&t.includes("#")?t.split("#")[1]:t||void 0}getMemberName(){return this.memberName}isMemberSchema(){return this._isMemberSchema}isListSchema(){let e=this.getSchema();return typeof e==="number"?e>=64&&e<128:e[0]===1}isMapSchema(){let e=this.getSchema();return typeof e==="number"?e>=128&&e<=255:e[0]===2}isStructSchema(){let e=this.getSchema();if(typeof e!=="object")return!1;let t=e[0];return t===3||t===-3||t===4}isUnionSchema(){let e=this.getSchema();if(typeof e!=="object")return!1;return e[0]===4}isBlobSchema(){let e=this.getSchema();return e===21||e===42}isTimestampSchema(){let e=this.getSchema();return typeof e==="number"&&e>=4&&e<=7}isUnitSchema(){return this.getSchema()==="unit"}isDocumentSchema(){return this.getSchema()===15}isStringSchema(){return this.getSchema()===0}isBooleanSchema(){return this.getSchema()===2}isNumericSchema(){return this.getSchema()===1}isBigIntegerSchema(){return this.getSchema()===17}isBigDecimalSchema(){return this.getSchema()===19}isStreaming(){let{streaming:e}=this.getMergedTraits();return!!e||this.getSchema()===42}isIdempotencyToken(){return!!this.getMergedTraits().idempotencyToken}getMergedTraits(){return this.normalizedTraits??(this.normalizedTraits={...this.getOwnTraits(),...this.getMemberTraits()})}getMemberTraits(){return kf(this.memberTraits)}getOwnTraits(){return kf(this.traits)}getKeySchema(){let[e,t]=[this.isDocumentSchema(),this.isMapSchema()];if(!e&&!t)throw Error(`@smithy/core/schema - cannot get key for non-map: ${this.getName(!0)}`);let r=this.getSchema(),n=e?15:r[4]??0;return vf([n,0],"key")}getValueSchema(){let e=this.getSchema(),[t,r,n]=[this.isDocumentSchema(),this.isMapSchema(),this.isListSchema()],i=typeof e==="number"?63&e:e&&typeof e==="object"&&(r||n)?e[3+e[0]]:t?15:void 0;if(i!=null)return vf([i,0],r?"value":"member");throw Error(`@smithy/core/schema - ${this.getName(!0)} has no value member.`)}getMemberSchema(e){let t=this.getSchema();if(this.isStructSchema()&&t[4].includes(e)){let r=t[4].indexOf(e),n=t[5][r];return vf(eb(n)?n:[n,0],e)}if(this.isDocumentSchema())return vf([15,0],e);throw Error(`@smithy/core/schema - ${this.getName(!0)} has no member=${e}.`)}getMemberSchemas(){let e={};try{for(let[t,r]of this.structIterator())e[t]=r}catch(t){}return e}getEventStreamMember(){if(this.isStructSchema()){for(let[e,t]of this.structIterator())if(t.isStreaming()&&t.isStructSchema())return e}return""}*structIterator(){if(this.isUnitSchema())return;if(!this.isStructSchema())throw Error("@smithy/core/schema - cannot iterate non-struct schema.");let e=this.getSchema(),t=e[4].length,r=e[Tf.it];if(r&&t===r.length){yield*r;return}r=Array(t);for(let n=0;n<t;++n){let i=e[4][n],o=vf([e[5][n],0],i);yield r[n]=[i,o]}e[Tf.it]=r}}function vf(e,t){if(e instanceof Ba)return Object.assign(e,{memberName:t,_isMemberSchema:!0});return new Ba(e,t)}var eb=(e)=>Array.isArray(e)&&e.length===2,Ik=(e)=>Array.isArray(e)&&e.length>=5;class Nf extends Ao{static symbol=Symbol.for("@smithy/sim");schemaRef;symbol=Nf.symbol}var LV=(e,t,r,n)=>Ao.assign(new Nf,{name:t,namespace:e,traits:n,schemaRef:r}),MV=(e,t,r,n)=>Ao.assign(new Nf,{name:t,namespace:e,traits:r,schemaRef:n}),qV={BLOB:21,STREAMING_BLOB:42,BOOLEAN:2,STRING:0,NUMERIC:1,BIG_INTEGER:17,BIG_DECIMAL:19,DOCUMENT:15,TIMESTAMP_DEFAULT:4,TIMESTAMP_DATE_TIME:5,TIMESTAMP_HTTP_DATE:6,TIMESTAMP_EPOCH_SECONDS:7,LIST_MODIFIER:64,MAP_MODIFIER:128};class qa{namespace;schemas;exceptions;static registries=new Map;constructor(e,t=new Map,r=new Map){this.namespace=e,this.schemas=t,this.exceptions=r}static for(e){if(!qa.registries.has(e))qa.registries.set(e,new qa(e));return qa.registries.get(e)}copyFrom(e){let{schemas:t,exceptions:r}=this;for(let[n,i]of e.schemas)if(!t.has(n))t.set(n,i);for(let[n,i]of e.exceptions)if(!r.has(n))r.set(n,i)}register(e,t){let r=this.normalizeShapeId(e);for(let n of[this,qa.for(r.split("#")[0])])n.schemas.set(r,t)}getSchema(e){let t=this.normalizeShapeId(e);if(!this.schemas.has(t)){if(!e.includes("#")){let r="#"+e,n=[];for(let[i,o]of this.schemas.entries())if(i.endsWith(r))n.push(o);if(n.length===1)return n[0]}throw Error(`@smithy/core/schema - schema not found for ${t}`)}return this.schemas.get(t)}registerError(e,t){let r=e,n=r[1];for(let i of[this,qa.for(n)])i.schemas.set(n+"#"+r[2],r),i.exceptions.set(r,t)}getErrorCtor(e){let t=e;if(this.exceptions.has(t))return this.exceptions.get(t);return qa.for(t[1]).exceptions.get(t)}getBaseException(){for(let e of this.exceptions.keys())if(Array.isArray(e)){let[,t,r]=e,n=t+"#"+r;if(n.startsWith("smithy.ts.sdk.synthetic.")&&n.endsWith("ServiceException"))return e}return}find(e){for(let t of this.schemas.values())if(e(t))return t;return}clear(){this.schemas.clear(),this.exceptions.clear()}normalizeShapeId(e){if(e.includes("#"))return e;return this.namespace+"#"+e}}BV.ErrorSchema=lm;BV.ListSchema=cm;BV.MapSchema=um;BV.NormalizedSchema=Ba;BV.OperationSchema=dm;BV.SCHEMA=qV;BV.Schema=Ao;BV.SimpleSchema=Nf;BV.StructureSchema=Rf;BV.TypeRegistry=qa;BV.deref=im;BV.deserializerMiddlewareOption=Ck;BV.error=PV;BV.getSchemaSerdePlugin=CV;BV.isStaticSchema=Ik;BV.list=OV;BV.map=IV;BV.op=DV;BV.operation=tb;BV.serializerMiddlewareOption=Ok;BV.sim=LV;BV.simAdapter=MV;BV.simpleSchemaCacheN=sm;BV.simpleSchemaCacheS=am;BV.struct=UV;BV.traitsCache=om;BV.translateTraits=kf});var q=A(function(V4){var{hasOwn:Of}=Po(),{getSmithyContext:h4,normalizeProvider:p4}=Po();V4.getSmithyContext=h4;V4.normalizeProvider=p4;var{SMITHY_CONTEXT_KEY:m4,AlgorithmId:xf}=Nu();V4.AlgorithmId=xf;var{NormalizedSchema:g4}=le(),xu=(e,t)=>{let r=[];if(e)r.push(e);if(t)for(let n of t)r.push(n);return r},_c=(e,t)=>`${e||"anonymous"}${t&&t.length>0?` (a.k.a. ${t.join(",")})`:""}`,Cf=()=>{let e=[],t=[],r=!1,n=new Set,i=(f)=>f.sort((h,p)=>Dk[p.step]-Dk[h.step]||Uk[p.priority||"normal"]-Uk[h.priority||"normal"]),o=(f)=>{let h=!1,p=(g)=>{let _=xu(g.name,g.aliases);if(_.includes(f)){h=!0;for(let R of _)n.delete(R);return!1}return!0};return e=e.filter(p),t=t.filter(p),h},s=(f)=>{let h=!1,p=(g)=>{if(g.middleware===f){h=!0;for(let _ of xu(g.name,g.aliases))n.delete(_);return!1}return!0};return e=e.filter(p),t=t.filter(p),h},a=(f)=>(e.forEach((h)=>{f.add(h.middleware,{...h})}),t.forEach((h)=>{f.addRelativeTo(h.middleware,{...h})}),f.identifyOnResolve?.(d.identifyOnResolve()),f),c=(f)=>{let h=[];return f.before.forEach((p)=>{if(p.before.length===0&&p.after.length===0)h.push(p);else h.push(...c(p))}),h.push(f),f.after.reverse().forEach((p)=>{if(p.before.length===0&&p.after.length===0)h.push(p);else h.push(...c(p))}),h},u=(f=!1)=>{let h=[],p=[],g={};return e.forEach((R)=>{let O={...R,before:[],after:[]};for(let I of xu(O.name,O.aliases))g[I]=O;h.push(O)}),t.forEach((R)=>{let O={...R,before:[],after:[]};for(let I of xu(O.name,O.aliases))g[I]=O;p.push(O)}),p.forEach((R)=>{if(R.toMiddleware){let O=g[R.toMiddleware];if(O===void 0){if(f)return;throw Error(`${R.toMiddleware} is not found when adding ${_c(R.name,R.aliases)} middleware ${R.relation} ${R.toMiddleware}`)}if(R.relation==="after")O.after.push(R);if(R.relation==="before")O.before.push(R)}}),i(h).map(c).reduce((R,O)=>(R.push(...O),R),[])},d={add:(f,h={})=>{let{name:p,override:g,aliases:_}=h,R={step:"initialize",priority:"normal",middleware:f,...h},O=xu(p,_);if(O.length>0){if(O.some((I)=>n.has(I))){if(!g)throw Error(`Duplicate middleware name '${_c(p,_)}'`);for(let I of O){let Ne=e.findIndex((j)=>j.name===I||j.aliases?.some((re)=>re===I));if(Ne===-1)continue;let k=e[Ne];if(k.step!==R.step||R.priority!==k.priority)throw Error(`"${_c(k.name,k.aliases)}" middleware with ${k.priority} priority in ${k.step} step cannot be overridden by "${_c(p,_)}" middleware with ${R.priority} priority in ${R.step} step.`);e.splice(Ne,1)}}for(let I of O)n.add(I)}e.push(R)},addRelativeTo:(f,h)=>{let{name:p,override:g,aliases:_}=h,R={middleware:f,...h},O=xu(p,_);if(O.length>0){if(O.some((I)=>n.has(I))){if(!g)throw Error(`Duplicate middleware name '${_c(p,_)}'`);for(let I of O){let Ne=t.findIndex((j)=>j.name===I||j.aliases?.some((re)=>re===I));if(Ne===-1)continue;let k=t[Ne];if(k.toMiddleware!==R.toMiddleware||k.relation!==R.relation)throw Error(`"${_c(k.name,k.aliases)}" middleware ${k.relation} "${k.toMiddleware}" middleware cannot be overridden by "${_c(p,_)}" middleware ${R.relation} "${R.toMiddleware}" middleware.`);t.splice(Ne,1)}}for(let I of O)n.add(I)}t.push(R)},clone:()=>a(Cf()),use:(f)=>{f.applyToStack(d)},remove:(f)=>{if(typeof f==="string")return o(f);else return s(f)},removeByTag:(f)=>{let h=!1,p=(g)=>{let{tags:_,name:R,aliases:O}=g;if(_&&_.includes(f)){let I=xu(R,O);for(let Ne of I)n.delete(Ne);return h=!0,!1}return!0};return e=e.filter(p),t=t.filter(p),h},concat:(f)=>{let h=a(Cf());return h.use(f),h.identifyOnResolve(r||h.identifyOnResolve()||(f.identifyOnResolve?.()??!1)),h},applyToStack:a,identify:()=>u(!0).map((f)=>{let h=f.step??f.relation+" "+f.toMiddleware;return _c(f.name,f.aliases)+" - "+h}),identifyOnResolve(f){if(typeof f==="boolean")r=f;return r},resolve:(f,h)=>{for(let p of u().map((g)=>g.middleware).reverse())f=p(f,h);if(r)console.log(d.identify());return f}};return d},Dk={initialize:5,serialize:4,build:3,finalizeRequest:2,deserialize:1},Uk={high:3,normal:2,low:1},y4=(e)=>()=>{throw Error(e)},w4=(e)=>()=>Promise.reject(e),fm=()=>{let e=new WeakSet;return(t,r)=>{if(typeof r==="object"&&r!==null){if(e.has(r))return"[Circular]";e.add(r)}return r}},_4=(e)=>new Promise((t)=>setTimeout(t,e*1000)),Mk={minDelay:2,maxDelay:120},ta;(function(e){e.ABORTED="ABORTED",e.FAILURE="FAILURE",e.SUCCESS="SUCCESS",e.RETRY="RETRY",e.TIMEOUT="TIMEOUT"})(ta||(ta={}));var b4=(e)=>{if(e.state===ta.ABORTED){let t=Error(`${JSON.stringify({...e,reason:"Request was aborted"},fm())}`);throw t.name="AbortError",t}else if(e.state===ta.TIMEOUT){let t=Error(`${JSON.stringify({...e,reason:"Waiter has timed out"},fm())}`);throw t.name="TimeoutError",t}else if(e.state!==ta.SUCCESS)throw Error(`${JSON.stringify(e,fm())}`);return e},E4=async({minDelay:e,maxDelay:t,maxWaitTime:r,abortController:n,client:i,abortSignal:o},s,a)=>{let c={},[u,d]=[e*1000,t*1000],f=0,h=Date.now()+r*1000,p=Date.now()+60000,g=!1;while(!0){if(f>0){let O=T4(u,d,f,h);if(n?.signal?.aborted||o?.aborted)return c["AbortController signal aborted."]|=0,c["AbortController signal aborted."]+=1,{state:ta.ABORTED,observedResponses:c};if(Date.now()+O>h)return{state:ta.TIMEOUT,observedResponses:c};await _4(O/1000)}let{state:_,reason:R}=await a(i,s);if(R){let O=A4(R);c[O]|=0,c[O]+=1}if(_!==ta.RETRY)return{state:_,reason:R,final:R,observedResponses:c};if(f+=1,!g&&Date.now()>=p)S4(c,i),g=!0}},S4=(e={},t)=>{let r=Object.keys(e),n=0;for(let s of r){let a=e[s]|0;if(s.startsWith("403:"))n+=a}let i=t?.config?.logger,o=typeof i?.warn==="function"&&!i.constructor?.name?.includes?.("NoOpLogger")?i:console;if(n>=3||r[r.length-1]?.startsWith("403:"))o.warn("@smithy/util-waiter WARN - 403 status code encountered during waiter polling.")},A4=(e)=>{let t=e?.$response?.statusCode??e?.$metadata?.httpStatusCode;if(e?.$responseBodyText)return`${t?t+": ":""}Deserialization error for body: ${e.$responseBodyText}`;if(t){if(e?.$response||e?.message)return`${t??"Unknown"}: ${e?.message}`;return`${t}: OK`}return String(e?.message??JSON.stringify(e,fm())??"Unknown")},T4=(e,t,r,n)=>{let i=Math.log(t/e)/Math.log(2)+1;if(r>i)return t;let o=e*2**(r-1),s=Math.min(o,t),a=v4(e,s);if(Date.now()+a>n){let c=n-Date.now();return Math.max(0,c-500)}return a},v4=(e,t)=>e+Math.random()*(t-e),k4=(e)=>{if(e.maxWaitTime<=0)throw Error("WaiterConfiguration.maxWaitTime must be greater than 0");else if(e.minDelay<=0)throw Error("WaiterConfiguration.minDelay must be greater than 0");else if(e.maxDelay<=0)throw Error("WaiterConfiguration.maxDelay must be greater than 0");else if(e.maxWaitTime<=e.minDelay)throw Error(`WaiterConfiguration.maxWaitTime [${e.maxWaitTime}] must be greater than WaiterConfiguration.minDelay [${e.minDelay}] for this waiter`);else if(e.maxDelay<e.minDelay)throw Error(`WaiterConfiguration.maxDelay [${e.maxDelay}] must be greater than WaiterConfiguration.minDelay [${e.minDelay}] for this waiter`)},Pk=(e)=>{let t,r=new Promise((n)=>{if(t=()=>n({state:ta.ABORTED}),typeof e.addEventListener==="function")e.addEventListener("abort",t);else e.onabort=t});return{clearListener(){if(typeof e.removeEventListener==="function")e.removeEventListener("abort",t)},aborted:r}},R4=async(e,t,r)=>{let n={...Mk,...e};k4(n);let i=[E4(n,t,r)],o=[];if(e.abortSignal){let{aborted:s,clearListener:a}=Pk(e.abortSignal);o.push(a),i.push(s)}if(e.abortController?.signal){let{aborted:s,clearListener:a}=Pk(e.abortController.signal);o.push(a),i.push(s)}return Promise.race(i).then((s)=>{for(let a of o)a();return s})};class qk{config;middlewareStack=Cf();initConfig;handlers;constructor(e){this.config=e;let{protocol:t,protocolSettings:r}=e;if(r){if(typeof t==="function")e.protocol=new t(r)}}send(e,t,r){let n=typeof t!=="function"?t:void 0,i=typeof t==="function"?t:r,o=n===void 0&&this.config.cacheMiddleware===!0,s;if(o){if(!this.handlers)this.handlers=new WeakMap;let a=this.handlers;if(a.has(e.constructor))s=a.get(e.constructor);else s=e.resolveMiddleware(this.middlewareStack,this.config,n),a.set(e.constructor,s)}else delete this.handlers,s=e.resolveMiddleware(this.middlewareStack,this.config,n);if(i)s(e).then((a)=>i(null,a.output),(a)=>i(a)).catch(()=>{});else return s(e).then((a)=>a.output)}destroy(){this.config?.requestHandler?.destroy?.(),delete this.handlers}}var rb="***SensitiveInformation***";function hm(e,t){if(t==null)return t;let r=g4.of(e);if(r.getMergedTraits().sensitive)return rb;if(r.isListSchema()){if(!!r.getValueSchema().getMergedTraits().sensitive)return rb}else if(r.isMapSchema()){if(!!r.getKeySchema().getMergedTraits().sensitive||!!r.getValueSchema().getMergedTraits().sensitive)return rb}else if(r.isStructSchema()&&typeof t==="object"){let n=t,i={};for(let[o,s]of r.structIterator())if(n[o]!=null)i[o]=hm(s,n[o]);return i}return t}class pm{middlewareStack=Cf();schema;static classBuilder(){return new Bk}resolveMiddlewareWithContext(e,t,r,{middlewareFn:n,clientName:i,commandName:o,inputFilterSensitiveLog:s,outputFilterSensitiveLog:a,smithyContext:c,additionalContext:u,CommandCtor:d}){for(let R of n.bind(this)(d,e,t,r))this.middlewareStack.use(R);let f=e.concat(this.middlewareStack),{logger:h}=t,p={logger:h,clientName:i,commandName:o,inputFilterSensitiveLog:s,outputFilterSensitiveLog:a,[m4]:{commandInstance:this,...c},...u},{requestHandler:g}=t,_=r??{};if(c.eventStream)_={isEventStream:!0,..._};return f.resolve((R)=>g.handle(R.request,_),p)}}class Bk{_init=()=>{};_ep={};_middlewareFn=()=>[];_commandName="";_clientName="";_additionalContext={};_smithyContext={};_inputFilterSensitiveLog=void 0;_outputFilterSensitiveLog=void 0;_serializer=null;_deserializer=null;_operationSchema;init(e){this._init=e}ep(e){return this._ep=e,this}m(e){return this._middlewareFn=e,this}s(e,t,r={}){return this._smithyContext={service:e,operation:t,...r},this}c(e={}){return this._additionalContext=e,this}n(e,t){return this._clientName=e,this._commandName=t,this}f(e=(r)=>r,t=(r)=>r){return this._inputFilterSensitiveLog=e,this._outputFilterSensitiveLog=t,this}ser(e){return this._serializer=e,this}de(e){return this._deserializer=e,this}sc(e){return this._operationSchema=e,this._smithyContext.operationSchema=e,this}build(){let e=this,t;return t=class extends pm{input;static getEndpointParameterInstructions(){return e._ep}constructor(...[r]){super();this.input=r??{},e._init(this),this.schema=e._operationSchema}resolveMiddleware(r,n,i){let o=e._operationSchema,s=o?.[4]??o?.input,a=o?.[5]??o?.output;return this.resolveMiddlewareWithContext(r,n,i,{CommandCtor:t,middlewareFn:e._middlewareFn,clientName:e._clientName,commandName:e._commandName,inputFilterSensitiveLog:e._inputFilterSensitiveLog??(o?hm.bind(null,s):(c)=>c),outputFilterSensitiveLog:e._outputFilterSensitiveLog??(o?hm.bind(null,a):(c)=>c),smithyContext:e._smithyContext,additionalContext:e._additionalContext})}serialize=e._serializer;deserialize=e._deserializer}}}var N4="***SensitiveInformation***",x4=(e,t,r)=>{for(let[o,s]of Object.entries(e)){let a=async function(u,d,f){let h=new s(u);if(typeof d==="function")this.send(h,d);else if(typeof f==="function"){if(typeof d!=="object")throw Error(`Expected http options but got ${typeof d}`);this.send(h,d||{},f)}else return this.send(h,d)},c=(o[0].toLowerCase()+o.slice(1)).replace(/Command$/,"");t.prototype[c]=a}let{paginators:n={},waiters:i={}}=r??{};for(let[o,s]of Object.entries(n))if(t.prototype[o]===void 0)t.prototype[o]=function(a={},c,...u){return s({...c,client:this},a,...u)};for(let[o,s]of Object.entries(i))if(t.prototype[o]===void 0)t.prototype[o]=async function(a={},c,...u){let d=c;if(typeof c==="number")d={maxWaitTime:c};return s({...d,client:this},a,...u)}};class Ad extends Error{$fault;$response;$retryable;$metadata;constructor(e){super(e.message);Object.setPrototypeOf(this,Object.getPrototypeOf(this).constructor.prototype),this.name=e.name,this.$fault=e.$fault,this.$metadata=e.$metadata}static isInstance(e){if(!e)return!1;let t=e;return Ad.prototype.isPrototypeOf(t)||Boolean(t.$fault)&&Boolean(t.$metadata)&&(t.$fault==="client"||t.$fault==="server")}static[Symbol.hasInstance](e){if(!e)return!1;let t=e;if(this===Ad)return Ad.isInstance(e);if(Ad.isInstance(e)){if(t.name&&this.name)return this.prototype.isPrototypeOf(e)||t.name===this.name;return this.prototype.isPrototypeOf(e)}return!1}}var jk=(e,t={})=>{Object.entries(t).filter(([,n])=>n!==void 0).forEach(([n,i])=>{if(e[n]==null||e[n]==="")e[n]=i});let r=e.message||e.Message||"UnknownError";return e.message=r,delete e.Message,e},$k=({output:e,parsedBody:t,exceptionCtor:r,errorCode:n})=>{let i=O4(e),o=i.httpStatusCode?i.httpStatusCode+"":void 0,s=new r({name:t?.code||t?.Code||n||o||"UnknownError",$fault:"client",$metadata:i});throw jk(s,t)},C4=(e)=>({output:t,parsedBody:r,errorCode:n})=>{$k({output:t,parsedBody:r,exceptionCtor:e,errorCode:n})},O4=(e)=>({httpStatusCode:e.statusCode,requestId:e.headers["x-amzn-requestid"]??e.headers["x-amzn-request-id"]??e.headers["x-amz-request-id"],extendedRequestId:e.headers["x-amz-id-2"],cfId:e.headers["x-amz-cf-id"]}),I4=(e)=>{switch(e){case"standard":return{retryMode:"standard",connectionTimeout:3100};case"in-region":return{retryMode:"standard",connectionTimeout:1100};case"cross-region":return{retryMode:"standard",connectionTimeout:3100};case"mobile":return{retryMode:"standard",connectionTimeout:30000};default:return{}}},Lk=!1,D4=(e)=>{if(e&&!Lk&&parseInt(e.substring(1,e.indexOf(".")))<16)Lk=!0},Fk=Object.values(xf),zk=(e)=>{let t=[];for(let r in xf){if(!Of(xf,r))continue;let n=xf[r];if(e[n]===void 0)continue;t.push({algorithmId:()=>n,checksumConstructor:()=>e[n]})}for(let[r,n]of Object.entries(e.checksumAlgorithms??{}))t.push({algorithmId:()=>r,checksumConstructor:()=>n});return{addChecksumAlgorithm(r){e.checksumAlgorithms=e.checksumAlgorithms??{};let n=r.algorithmId(),i=r.checksumConstructor();if(Fk.includes(n))e.checksumAlgorithms[n.toUpperCase()]=i;else e.checksumAlgorithms[n]=i;t.push(r)},checksumAlgorithms(){return t}}},Wk=(e)=>{let t={};return e.checksumAlgorithms().forEach((r)=>{let n=r.algorithmId();if(Fk.includes(n))t[n]=r.checksumConstructor()}),t},Hk=(e)=>({setRetryStrategy(t){e.retryStrategy=t},retryStrategy(){return e.retryStrategy}}),Vk=(e)=>{let t={};return t.retryStrategy=e.retryStrategy(),t},Gk=(e)=>Object.assign(zk(e),Hk(e)),U4=Gk,P4=(e)=>Object.assign(Wk(e),Vk(e)),L4=(e)=>Array.isArray(e)?e:[e],Kk=(e)=>{for(let r in e){if(!Of(e,r))continue;if(e[r]["#text"]!==void 0)e[r]=e[r]["#text"];else if(typeof e[r]==="object"&&e[r]!==null)e[r]=Kk(e[r])}return e},M4=(e)=>e!=null;class Jk{trace(){}debug(){}info(){}warn(){}error(){}}function Qk(e,t,r){let n,i,o;if(typeof t>"u"&&typeof r>"u")n={},o=e;else if(n=e,typeof t==="function")return i=t,o=r,j4(n,i,o);else o=t;for(let s in o){if(!Of(o,s))continue;if(!Array.isArray(o[s])){n[s]=o[s];continue}Yk(n,null,o,s)}return n}var q4=(e)=>{let t={};for(let[r,n]of Object.entries(e||{}))t[r]=[,n];return t},B4=(e,t)=>{let r={};for(let n in t){if(!Of(t,n))continue;Yk(r,e,t,n)}return r},j4=(e,t,r)=>Qk(e,Object.entries(r).reduce((n,[i,o])=>{if(Array.isArray(o))n[i]=o;else if(typeof o==="function")n[i]=[t,o()];else n[i]=[t,o];return n},{})),Yk=(e,t,r,n)=>{if(t!==null){let s=r[n];if(typeof s==="function")s=[,s];let[a=$4,c=F4,u=n]=s;if(typeof a==="function"&&a(t[u])||typeof a!=="function"&&!!a)e[n]=c(t[u]);return}let[i,o]=r[n];if(typeof o==="function"){let s,a=i===void 0&&(s=o())!=null,c=typeof i==="function"&&!!i(void 0)||typeof i!=="function"&&!!i;if(a)e[n]=s;else if(c)e[n]=o()}else{let s=i===void 0&&o!=null,a=typeof i==="function"&&!!i(o)||typeof i!=="function"&&!!i;if(s||a)e[n]=o}},$4=(e)=>e!=null,F4=(e)=>e,z4=(e)=>{if(e!==e)return"NaN";switch(e){case 1/0:return"Infinity";case-1/0:return"-Infinity";default:return e}},W4=(e)=>e.toISOString().replace(".000Z","Z"),nb=(e)=>{if(e==null)return{};if(Array.isArray(e))return e.filter((t)=>t!=null).map(nb);if(typeof e==="object"){let t={};for(let r in e){if(!Of(e,r))continue;if(e[r]==null)continue;t[r]=nb(e[r])}return t}return e};function H4(e,t,r,n){return function(o,s,a,c,u={}){let d=Object.assign({},e,o);return pm.classBuilder().ep(d).m(function(f,h,p,g){let _=s.call(this,f,h,p,g);return _.unshift(n(p,f.getEndpointParameterInstructions())),_}).s(t,a,u).n(r,a.charAt(0).toUpperCase()+a.slice(1)+"Command").sc(c).build()}}V4.Client=qk;V4.Command=pm;V4.NoOpLogger=Jk;V4.SENSITIVE_STRING=N4;V4.ServiceException=Ad;V4.WaiterState=ta;V4._json=nb;V4.checkExceptions=b4;V4.constructStack=Cf;V4.convertMap=q4;V4.createAggregatedClient=x4;V4.createWaiter=R4;V4.decorateServiceException=jk;V4.emitWarningIfUnsupportedVersion=D4;V4.getArrayIfSingleItem=L4;V4.getChecksumConfiguration=zk;V4.getDefaultClientConfiguration=U4;V4.getDefaultExtensionConfiguration=Gk;V4.getRetryConfiguration=Hk;V4.getValueFromTextNode=Kk;V4.invalidFunction=y4;V4.invalidProvider=w4;V4.isSerializableHeaderValue=M4;V4.loadConfigsForDefaultMode=I4;V4.makeBuilder=H4;V4.map=Qk;V4.resolveChecksumRuntimeConfig=Wk;V4.resolveDefaultRuntimeConfig=P4;V4.resolveRetryRuntimeConfig=Vk;V4.schemaLogFilter=hm;V4.serializeDateTime=W4;V4.serializeFloat=z4;V4.take=B4;V4.throwDefaultError=$k;V4.waiterServiceDefaults=Mk;V4.withBaseException=C4});var P=A(function(I3){var{homedir:I6}=C("os"),{sep:D6,join:If}=C("path"),{createHash:U6}=C("crypto"),{readFile:sR}=C("fs/promises"),{IniSectionType:mm}=Nu(),{normalizeProvider:gm}=q(),{isValidHostLabel:P6}=Po();class Td extends Error{name="ProviderError";tryNextLink;constructor(e,t=!0){let r,n=!0;if(typeof t==="boolean")r=void 0,n=t;else if(t!=null&&typeof t==="object")r=t.logger,n=t.tryNextLink??!0;super(e);this.tryNextLink=n,Object.setPrototypeOf(this,Td.prototype),r?.debug?.(`@smithy/property-provider ${n?"->":"(!)"} ${e}`)}static from(e,t=!0){return Object.assign(new this(e.message,t),e)}}class Df extends Td{name="CredentialsProviderError";constructor(e,t=!0){super(e,t);Object.setPrototypeOf(this,Df.prototype)}}class cb extends Td{name="TokenProviderError";constructor(e,t=!0){super(e,t);Object.setPrototypeOf(this,cb.prototype)}}var aR=(...e)=>async()=>{if(e.length===0)throw new Td("No providers in chain");let t;for(let r of e)try{return await r()}catch(n){if(t=n,n?.tryNextLink)continue;throw n}throw t},cR=(e)=>()=>Promise.resolve(e),ub=(e,t,r)=>{let n,i,o,s=!1,a=async()=>{if(!i)i=e();try{n=await i,o=!0,s=!1}finally{i=void 0}return n};if(t===void 0)return async(c)=>{if(!o||c?.forceRefresh)n=await a();return n};return async(c)=>{if(!o||c?.forceRefresh)n=await a();if(s)return n;if(r&&!r(n))return s=!0,n;if(t(n))return await a(),n;return n}},ja=(e,t,r)=>{if(!(t in e))return;if(e[t]==="true")return!0;if(e[t]==="false")return!1;throw Error(`Cannot load ${r} "${t}". Expected "true" or "false", got ${e[t]}.`)},L6=(e,t,r)=>{if(!(t in e))return;let n=parseInt(e[t],10);if(Number.isNaN(n))throw TypeError(`Cannot load ${r} '${t}'. Expected number, got '${e[t]}'.`);return n},Ts;(function(e){e.ENV="env",e.CONFIG="shared config entry"})(Ts||(Ts={}));var ib={},M6=()=>{if(process&&process.geteuid)return`${process.geteuid()}`;return"DEFAULT"},Uf=()=>{let{HOME:e,USERPROFILE:t,HOMEPATH:r,HOMEDRIVE:n=`C:${D6}`}=process.env;if(e)return e;if(t)return t;if(r)return`${n}${r}`;let i=M6();if(!ib[i])ib[i]=I6();return ib[i]},uR="AWS_PROFILE",dR="default",lR=(e)=>e.profile||process.env[uR]||dR,fR=(e)=>{let r=U6("sha1").update(e).digest("hex");return If(Uf(),".aws","sso","cache",`${r}.json`)},ym={},q6=async(e)=>{if(ym[e])return ym[e];let t=fR(e),r=await sR(t,"utf8");return JSON.parse(r)},Cu=".",B6=(e)=>Object.entries(e).filter(([t])=>{let r=t.indexOf(Cu);if(r===-1)return!1;return Object.values(mm).includes(t.substring(0,r))}).reduce((t,[r,n])=>{let i=r.indexOf(Cu),o=r.substring(0,i)===mm.PROFILE?r.substring(i+1):r;return t[o]=n,t},{...e.default&&{default:e.default}}),j6="AWS_CONFIG_FILE",hR=()=>process.env[j6]||If(Uf(),".aws","config"),$6="AWS_SHARED_CREDENTIALS_FILE",F6=()=>process.env[$6]||If(Uf(),".aws","credentials"),z6=/^([\w-]+)\s(["'])?([\w-@+.%:/]+)\2$/,W6=["__proto__","profile __proto__"],sb=(e)=>{let t={},r,n;for(let i of e.split(/\r?\n/)){let o=i.split(/(^|\s)[;#]/)[0].trim();if(o[0]==="["&&o[o.length-1]==="]"){r=void 0,n=void 0;let a=o.substring(1,o.length-1),c=z6.exec(a);if(c){let[,u,,d]=c;if(Object.values(mm).includes(u))r=[u,d].join(Cu)}else r=a;if(W6.includes(a))throw Error(`Found invalid profile name "${a}"`)}else if(r){let a=o.indexOf("=");if(![0,-1].includes(a)){let[c,u]=[o.substring(0,a).trim(),o.substring(a+1).trim()];if(u==="")n=c;else{if(n&&i.trimStart()===i)n=void 0;t[r]=t[r]||{};let d=n?[n,c].join(Cu):c;t[r][d]=u}}}}return t},ob={},wm={},_m=(e,t)=>{if(wm[e]!==void 0)return wm[e];if(!ob[e]||t?.ignoreCache)ob[e]=sR(e,"utf8");return ob[e]},Xk=()=>({}),db=async(e={})=>{let{filepath:t=F6(),configFilepath:r=hR()}=e,n=Uf(),i="~/",o=t;if(t.startsWith("~/"))o=If(n,t.slice(2));let s=r;if(r.startsWith("~/"))s=If(n,r.slice(2));let a=await Promise.all([_m(s,{ignoreCache:e.ignoreCache}).then(sb).then(B6).catch(Xk),_m(o,{ignoreCache:e.ignoreCache}).then(sb).catch(Xk)]);return{configFile:a[0],credentialsFile:a[1]}},H6=(e)=>Object.entries(e).filter(([t])=>t.startsWith(mm.SSO_SESSION+Cu)).reduce((t,[r,n])=>({...t,[r.substring(r.indexOf(Cu)+1)]:n}),{}),V6=()=>({}),G6=async(e={})=>_m(e.configFilepath??hR()).then(sb).then(H6).catch(V6),K6=(...e)=>{let t={};for(let r of e)for(let[n,i]of Object.entries(r))if(t[n]!==void 0)Object.assign(t[n],i);else t[n]=i;return t},J6=async(e)=>{let t=await db(e);return K6(t.configFile,t.credentialsFile)},Q6={getFileRecord(){return wm},interceptFile(e,t){wm[e]=Promise.resolve(t)},getTokenRecord(){return ym},interceptToken(e,t){ym[e]=t}};function pR(e){try{let t=new Set(Array.from(e.match(/([A-Z_]){3,}/g)??[]));return t.delete("CONFIG"),t.delete("CONFIG_PREFIX_SEPARATOR"),t.delete("ENV"),[...t].join(", ")}catch(t){return e}}var Y6=(e,t)=>async()=>{try{let r=e(process.env,t);if(r===void 0)throw Error();return r}catch(r){throw new Df(r.message||`Not found in ENV: ${pR(e.toString())}`,{logger:t?.logger})}},X6=(e,{preferredFile:t="config",...r}={})=>async()=>{let n=lR(r),{configFile:i,credentialsFile:o}=await db(r),s=o[n]||{},a=i[n]||{},c=t==="config"?{...s,...a}:{...a,...s};try{let d=e(c,t==="config"?i:o);if(d===void 0)throw Error();return d}catch(u){throw new Df(u.message||`Not found in config files w/ profile [${n}]: ${pR(e.toString())}`,{logger:r.logger})}},Z6=(e)=>typeof e==="function",mR=(e)=>Z6(e)?async()=>await e():cR(e),ab=({environmentVariableSelector:e,configFileSelector:t,default:r},n={})=>{let{signingName:i,logger:o}=n;return ub(aR(Y6(e,{signingName:i,logger:o}),X6(t,n),mR(r)))},lb="AWS_USE_DUALSTACK_ENDPOINT",fb="use_dualstack_endpoint",e3=!1,t3={environmentVariableSelector:(e)=>ja(e,lb,Ts.ENV),configFileSelector:(e)=>ja(e,fb,Ts.CONFIG),default:!1},r3={environmentVariableSelector:(e)=>ja(e,lb,Ts.ENV),configFileSelector:(e)=>ja(e,fb,Ts.CONFIG),default:void 0},hb="AWS_USE_FIPS_ENDPOINT",pb="use_fips_endpoint",n3=!1,i3={environmentVariableSelector:(e)=>ja(e,hb,Ts.ENV),configFileSelector:(e)=>ja(e,pb,Ts.CONFIG),default:!1},o3={environmentVariableSelector:(e)=>ja(e,hb,Ts.ENV),configFileSelector:(e)=>ja(e,pb,Ts.CONFIG),default:void 0},s3=(e)=>{let{tls:t,endpoint:r,urlParser:n,useDualstackEndpoint:i}=e;return Object.assign(e,{tls:t??!0,endpoint:gm(typeof r==="string"?n(r):r),isCustomEndpoint:!0,useDualstackEndpoint:gm(i??!1)})},a3=async(e)=>{let{tls:t=!0}=e,r=await e.region();if(!new RegExp(/^([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9-]{0,61}[a-zA-Z0-9])$/).test(r))throw Error("Invalid region in client config");let i=await e.useDualstackEndpoint(),o=await e.useFipsEndpoint(),{hostname:s}=await e.regionInfoProvider(r,{useDualstackEndpoint:i,useFipsEndpoint:o})??{};if(!s)throw Error("Cannot resolve hostname from client config");return e.urlParser(`${t?"https:":"http:"}//${s}`)},c3=(e)=>{let t=gm(e.useDualstackEndpoint??!1),{endpoint:r,useFipsEndpoint:n,urlParser:i,tls:o}=e;return Object.assign(e,{tls:o??!0,endpoint:r?gm(typeof r==="string"?i(r):r):()=>a3({...e,useDualstackEndpoint:t,useFipsEndpoint:n}),isCustomEndpoint:!!r,useDualstackEndpoint:t})},u3="AWS_EXECUTION_ENV",Zk="AWS_REGION",eR="AWS_DEFAULT_REGION",d3="AWS_EC2_METADATA_DISABLED",l3=["in-region","cross-region","mobile","standard","legacy"],f3="/latest/meta-data/placement/region",h3="/latest/api/token",p3="x-aws-ec2-metadata-token",m3="x-aws-ec2-metadata-token-ttl-seconds",tR=1000,g3=60000,gR=0,yR=async()=>{if(process.env[d3])return;if(Date.now()<gR)return;try{let e=y3(),t=(await nR({...e,path:h3,method:"PUT",headers:{[m3]:"21600"}})).toString();return(await nR({...e,path:f3,method:"GET",headers:{[p3]:t}})).toString().trim()||rR()}catch{return rR()}},rR=()=>{gR=Date.now()+g3;return},y3=()=>{let e=process.env.AWS_EC2_METADATA_SERVICE_ENDPOINT;if(e){let t=new URL(e);return{hostname:t.hostname.replace(/^\[(.+)]$/,"$1"),port:t.port?Number(t.port):void 0}}if(process.env.AWS_EC2_METADATA_SERVICE_ENDPOINT_MODE==="IPv6")return{hostname:"fd00:ec2::254"};return{hostname:"169.254.169.254"}},nR=async(e)=>{let{request:t}=C("http");return new Promise((r,n)=>{let i=t({hostname:e.hostname,port:e.port,path:e.path,method:e.method,headers:e.headers,timeout:tR,signal:AbortSignal.timeout(tR)});i.on("error",(o)=>{n(o),i.destroy()}),i.on("timeout",()=>{n(Error("TimeoutError from instance metadata service")),i.destroy()}),i.on("response",(o)=>{let{statusCode:s=400}=o;if(s<200||s>=300){n(Object.assign(Error("Error response received from instance metadata service"),{statusCode:s})),i.destroy();return}let a=[];o.on("data",(c)=>a.push(c)),o.on("end",()=>{r(Buffer.concat(a)),i.destroy()})}),i.end()})},wR="AWS_REGION",_R="region",bR={environmentVariableSelector:(e)=>e[wR],configFileSelector:(e)=>e[_R],default:async()=>{let e=await yR();if(e)return e;throw Error("Region is missing")}},w3={preferredFile:"credentials"},iR=new Set,_3=(e,t=P6)=>{if(!iR.has(e)&&!t(e))if(e==="*")console.warn('@smithy/config-resolver WARN - Please use the caller region instead of "*". See "sigv4a" in https://github.com/aws/aws-sdk-js-v3/blob/main/supplemental-docs/CLIENTS.md.');else throw Error(`Region not accepted: region="${e}" is not a valid hostname component.`);else iR.add(e)},ER=(e)=>typeof e==="string"&&(e.startsWith("fips-")||e.endsWith("-fips")),b3=(e)=>ER(e)?["fips-aws-global","aws-fips"].includes(e)?"us-east-1":e.replace(/fips-(dkr-|prod-)?|-fips/,""):e,E3=(e)=>{let{region:t,useFipsEndpoint:r}=e;if(!t)throw Error("Region is missing");return Object.assign(e,{region:async()=>{let n=typeof t==="function"?await t():t,i=b3(n);return _3(i),i},useFipsEndpoint:async()=>{let n=typeof t==="string"?t:await t();if(ER(n))return!0;return typeof r!=="function"?Promise.resolve(!!r):r()}})},oR=(e=[],{useFipsEndpoint:t,useDualstackEndpoint:r})=>e.find(({tags:n})=>t===n.includes("fips")&&r===n.includes("dualstack"))?.hostname,S3=(e,{regionHostname:t,partitionHostname:r})=>t?t:r?r.replace("{region}",e):void 0,A3=(e,{partitionHash:t})=>Object.keys(t||{}).find((r)=>t[r].regions.includes(e))??"aws",T3=(e,{signingRegion:t,regionRegex:r,useFipsEndpoint:n})=>{if(t)return t;else if(n){let i=r.replace("\\\\","\\").replace(/^\^/g,"\\.").replace(/\$$/g,"\\."),o=e.match(i);if(o)return o[0].slice(1,-1)}},v3=(e,{useFipsEndpoint:t=!1,useDualstackEndpoint:r=!1,signingService:n,regionHash:i,partitionHash:o})=>{let s=A3(e,{partitionHash:o}),a=e in i?e:o[s]?.endpoint??e,c={useFipsEndpoint:t,useDualstackEndpoint:r},u=oR(i[a]?.variants,c),d=oR(o[s]?.variants,c),f=S3(a,{regionHostname:u,partitionHostname:d});if(f===void 0)throw Error(`Endpoint resolution failed for: ${{resolvedRegion:a,useFipsEndpoint:t,useDualstackEndpoint:r}}`);let h=T3(f,{signingRegion:i[a]?.signingRegion,regionRegex:o[s].regionRegex,useFipsEndpoint:t});return{partition:s,signingService:n,hostname:f,...h&&{signingRegion:h},...i[a]?.signingService&&{signingService:i[a].signingService}}},k3="AWS_DEFAULTS_MODE",R3="defaults_mode",N3={environmentVariableSelector:(e)=>e[k3],configFileSelector:(e)=>e[R3],default:"legacy"},x3=({region:e=ab(bR),defaultsMode:t=ab(N3)}={})=>ub(async()=>{let r=typeof t==="function"?await t():t;switch(r?.toLowerCase()){case"auto":return C3(e);case"in-region":case"cross-region":case"mobile":case"standard":case"legacy":return Promise.resolve(r?.toLocaleLowerCase());case void 0:return Promise.resolve("legacy");default:throw Error(`Invalid parameter for "defaultsMode", expect ${l3.join(", ")}, got ${r}`)}}),C3=async(e)=>{if(e){let t=typeof e==="function"?await e():e,r=await O3();if(!r)return"standard";if(t===r)return"in-region";else return"cross-region"}return"standard"},O3=async()=>{if(process.env[u3]&&(process.env[Zk]||process.env[eR]))return process.env[Zk]??process.env[eR];return yR()};I3.CONFIG_PREFIX_SEPARATOR=Cu;I3.CONFIG_USE_DUALSTACK_ENDPOINT=fb;I3.CONFIG_USE_FIPS_ENDPOINT=pb;I3.CredentialsProviderError=Df;I3.DEFAULT_PROFILE=dR;I3.DEFAULT_USE_DUALSTACK_ENDPOINT=e3;I3.DEFAULT_USE_FIPS_ENDPOINT=n3;I3.ENV_PROFILE=uR;I3.ENV_USE_DUALSTACK_ENDPOINT=lb;I3.ENV_USE_FIPS_ENDPOINT=hb;I3.NODE_REGION_CONFIG_FILE_OPTIONS=w3;I3.NODE_REGION_CONFIG_OPTIONS=bR;I3.NODE_USE_DUALSTACK_ENDPOINT_CONFIG_OPTIONS=t3;I3.NODE_USE_FIPS_ENDPOINT_CONFIG_OPTIONS=i3;I3.ProviderError=Td;I3.REGION_ENV_NAME=wR;I3.REGION_INI_NAME=_R;I3.SelectorType=Ts;I3.TokenProviderError=cb;I3.booleanSelector=ja;I3.chain=aR;I3.externalDataInterceptor=Q6;I3.fromStatic=mR;I3.fromValue=cR;I3.getHomeDir=Uf;I3.getProfileName=lR;I3.getRegionInfo=v3;I3.getSSOTokenFilepath=fR;I3.getSSOTokenFromFile=q6;I3.loadConfig=ab;I3.loadSharedConfigFiles=db;I3.loadSsoSessionData=G6;I3.memoize=ub;I3.nodeDualstackConfigSelectors=r3;I3.nodeFipsConfigSelectors=o3;I3.numberSelector=L6;I3.parseKnownFiles=J6;I3.readFile=_m;I3.resolveCustomEndpointsConfig=s3;I3.resolveDefaultsModeConfig=x3;I3.resolveEndpointsConfig=c3;I3.resolveRegionConfig=E3});var oe=A(function(c5){var{CONFIG_PREFIX_SEPARATOR:SR,booleanSelector:AR,SelectorType:TR,loadConfig:vR}=P(),{toEndpointV1:bm,getSmithyContext:EG,normalizeProvider:mb,isValidHostLabel:NR,hasOwn:SG}=Po();c5.isValidHostLabel=NR;c5.middlewareEndpointToEndpointV1=bm;c5.toEndpointV1=bm;var{EndpointURLScheme:wb}=Nu(),kR="AWS_ENDPOINT_URL",RR="endpoint_url",AG=(e)=>({environmentVariableSelector:(t)=>{let r=e.split(" ").map((o)=>o.toUpperCase()),n=t[[kR,...r].join("_")];if(n)return n;let i=t[kR];if(i)return i;return},configFileSelector:(t,r)=>{if(t.services){let i=["services",t.services].join(SR);if(!r||!r[i])throw Error(`The services section "${t.services}" specified in the profile is not present in the shared configuration file.`);let o=r[i],s=e.split(" ").map((c)=>c.toLowerCase()),a=o[[s.join("_"),RR].join(SR)];if(a)return a}let n=t[RR];if(n)return n;return},default:void 0}),TG="AWS_IGNORE_CONFIGURED_ENDPOINT_URLS",vG="ignore_configured_endpoint_urls",kG={environmentVariableSelector:(e)=>AR(e,TG,TR.ENV),configFileSelector:(e)=>AR(e,vG,TR.CONFIG),default:!1},Em=async(e)=>{if(await vR(kG)())return;return vR(AG(e??""))()},RG=async(e)=>{let t=e?.Bucket||"";if(typeof e.Bucket==="string")e.Bucket=t.replace(/#/g,encodeURIComponent("#")).replace(/\?/g,encodeURIComponent("?"));if(IG(t)){if(e.ForcePathStyle===!0)throw Error("Path-style addressing cannot be used with ARN buckets")}else if(!OG(t)||t.indexOf(".")!==-1&&!String(e.Endpoint).startsWith("http:")||t.toLowerCase()!==t||t.length<3)e.ForcePathStyle=!0;if(e.DisableMultiRegionAccessPoints)e.disableMultiRegionAccessPoints=!0,e.DisableMRAP=!0;return e},NG=/^[a-z0-9][a-z0-9.-]{1,61}[a-z0-9]$/,xG=/(\d+\.){3}\d+/,CG=/\.\./,OG=(e)=>NG.test(e)&&!xG.test(e)&&!CG.test(e),IG=(e)=>{let[t,r,n,,,i]=e.split(":"),o=t==="arn"&&e.split(":").length>=6,s=Boolean(o&&r&&n&&i);if(o&&!s)throw Error(`Invalid ARN: ${e} was an invalid ARN.`);return s},DG=(e,t,r,n=!1)=>{let i=async()=>{let o;if(n)o=r.clientContextParams?.[e]??r[e]??r[t];else o=r[e]??r[t];if(typeof o==="function")return o();return o};if(e==="credentialScope"||t==="CredentialScope")return async()=>{let o=typeof r.credentials==="function"?await r.credentials():r.credentials;return o?.credentialScope??o?.CredentialScope};if(e==="accountId"||t==="AccountId")return async()=>{let o=typeof r.credentials==="function"?await r.credentials():r.credentials;return o?.accountId??o?.AccountId};if(e==="endpoint"||t==="endpoint")return async()=>{if(r.isCustomEndpoint===!1)return;let o=await i();if(o&&typeof o==="object"){if("url"in o)return o.url.href;if("hostname"in o){let{protocol:s,hostname:a,port:c,path:u}=o;return`${s}//${a}${c?":"+c:""}${u}`}}return o};return i};function xR(e){return async(t,r,n,i)=>{if(!n.isCustomEndpoint&&!n.ignoreConfiguredEndpointUrls){let a;if(n.serviceConfiguredEndpoint)a=await n.serviceConfiguredEndpoint();else a=await e(n.serviceId);if(a)n.endpoint=()=>Promise.resolve(bm(a)),n.isCustomEndpoint=!0,i?.logger?.debug?.(`@smithy/core/endpoints - resolved endpoint from config: ${a}`)}let o=await CR(t,r,n);if(typeof n.endpointProvider!=="function")throw Error("config.endpointProvider is not set.");let s=n.endpointProvider(o,i);if(n.isCustomEndpoint&&n.endpoint){let a=await n.endpoint();if(a?.headers){s.headers??={};for(let[c,u]of Object.entries(a.headers))s.headers[c]=Array.isArray(u)?u:[u]}}return s}}var CR=async(e,t,r)=>{let n={},i=t?.getEndpointParameterInstructions?.()||{};for(let[o,s]of Object.entries(i))switch(s.type){case"staticContextParams":n[o]=s.value;break;case"contextParams":n[o]=e[s.name];break;case"clientContextParams":case"builtInParams":n[o]=await DG(s.name,o,r,s.type!=="builtInParams")();break;case"operationContextParams":n[o]=s.get(e);break;default:throw Error("Unrecognized endpoint parameter instruction: "+JSON.stringify(s))}if(Object.keys(i).length===0)Object.assign(n,r);if(String(r.serviceId).toLowerCase()==="s3")await RG(n);return n};function UG(e,t,r){if(!e.__smithy_context)e.__smithy_context={features:{}};else if(!e.__smithy_context.features)e.__smithy_context.features={};e.__smithy_context.features[t]=r}function OR(e){let t=xR(e);return({config:r,instructions:n})=>(i,o)=>async(s)=>{if(r.isCustomEndpoint)UG(o,"ENDPOINT_OVERRIDE","N");let a=await t(s.input,{getEndpointParameterInstructions(){return n}},{...r},o);o.endpointV2=a,o.authSchemes=a.properties?.authSchemes;let c=o.authSchemes?.[0];if(c){o.signing_region=c.signingRegion,o.signing_service=c.signingName;let d=EG(o)?.selectedHttpAuthScheme?.httpAuthOption;if(d)d.signingProperties=Object.assign(d.signingProperties||{},{signing_region:c.signingRegion,signingRegion:c.signingRegion,signing_service:c.signingName,signingName:c.signingName,signingRegionSet:c.signingRegionSet},c.properties)}return i({...s})}}var PG={name:"serializerMiddleware"},IR={step:"serialize",tags:["ENDPOINT_PARAMETERS","ENDPOINT_V2","ENDPOINT"],name:"endpointV2Middleware",override:!0,relation:"before",toMiddleware:PG.name};function LG(e){let t=OR(e);return(r,n)=>({applyToStack:(i)=>{i.addRelativeTo(t({config:r,instructions:n}),IR)}})}function MG(e){return(t)=>{let r=t.tls??!0,{endpoint:n,useDualstackEndpoint:i,useFipsEndpoint:o}=t,s=n!=null?async()=>bm(await mb(n)()):void 0,c=Object.assign(t,{endpoint:s,tls:r,isCustomEndpoint:!!n,useDualstackEndpoint:mb(i??!1),useFipsEndpoint:mb(o??!1),ignoreConfiguredEndpointUrls:!!t.ignoreConfiguredEndpointUrls}),u=void 0;return c.serviceConfiguredEndpoint=async()=>{if(t.serviceId&&!u)u=e(t.serviceId);return u},c}}class _b{nodes;root;conditions;results;constructor(e,t,r,n){this.nodes=e,this.root=t,this.conditions=r,this.results=n}static from(e,t,r,n){return new _b(e,t,r,n)}}class DR{capacity;data=new Map;parameters=[];constructor({size:e,params:t}){if(this.capacity=e??50,t)this.parameters=t}get(e,t){let r=this.hash(e);if(r===!1)return t();if(!this.data.has(r)){if(this.data.size>this.capacity+10){let n=this.data.keys(),i=0;while(!0){let{value:o,done:s}=n.next();if(this.data.delete(o),s||++i>10)break}}this.data.set(r,t())}return this.data.get(r)}size(){return this.data.size}hash(e){let t="",{parameters:r}=this;if(r.length===0)return!1;for(let n of r){let i=String(e[n]??"");if(i.includes("|;"))return!1;t+=i+"|;"}return t}}class Vi extends Error{constructor(e){super(e);this.name="EndpointError"}}var Pf="endpoints";function bc(e){if(typeof e!=="object"||e==null)return e;if("ref"in e)return`$${bc(e.ref)}`;if("fn"in e)return`${e.fn}(${(e.argv||[]).map(bc).join(", ")})`;return JSON.stringify(e,null,2)}var UR={},qG=(e,t)=>e===t;function BG(...e){for(let t of e)if(t!=null)return t;return}var jG=(e)=>{let t=e.split("."),r=[];for(let n of t){let i=n.indexOf("[");if(i!==-1){if(n.indexOf("]")!==n.length-1)throw new Vi(`Path: '${e}' does not end with ']'`);let o=n.slice(i+1,-1);if(Number.isNaN(parseInt(o)))throw new Vi(`Invalid array index: '${o}' in path: '${e}'`);if(i!==0)r.push(n.slice(0,i));r.push(o)}else r.push(n)}return r},PR=(e,t)=>jG(t).reduce((r,n)=>{if(typeof r!=="object")throw new Vi(`Index '${n}' in '${t}' not found in '${JSON.stringify(e)}'`);else if(Array.isArray(r)){let i=parseInt(n);return r[i<0?r.length+i:i]}return r[n]},e),$G=(e)=>e!=null;function FG(e,t,r){return e?t:r}var zG=(e)=>!e,WG=new RegExp("^(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)(?:\\.(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)){3}$"),LR=(e)=>WG.test(e)||e.startsWith("[")&&e.endsWith("]"),gb={[wb.HTTP]:80,[wb.HTTPS]:443},HG=(e)=>{let t=(()=>{try{if(e instanceof URL)return e;if(typeof e==="object"&&"hostname"in e){let{hostname:h,port:p,protocol:g="",path:_="",query:R={}}=e,O=new URL(`${g}//${h}${p?`:${p}`:""}${_}`);return O.search=Object.entries(R).map(([I,Ne])=>`${I}=${Ne}`).join("&"),O}return new URL(e)}catch(h){return null}})();if(!t)return console.error(`Unable to parse ${JSON.stringify(e)} as a whatwg URL.`),null;let r=t.href,{host:n,hostname:i,pathname:o,protocol:s,search:a}=t;if(a)return null;let c=s.slice(0,-1);if(!Object.values(wb).includes(c))return null;let u=LR(i),d=r.includes(`${n}:${gb[c]}`)||typeof e==="string"&&e.includes(`${n}:${gb[c]}`),f=`${n}${d?`:${gb[c]}`:""}`;return{scheme:c,authority:f,path:o,normalizedPath:o.endsWith("/")?o:`${o}/`,isIp:u}};function VG(e,t,r){if(r===1)return[e];if(e==="")return[""];let n=e.split(t);if(r===0)return n;return n.slice(0,r-1).concat(n.slice(1).join(t))}var GG=(e,t)=>e===t,KG=(e,t,r,n)=>{if(e==null||t>=r||e.length<r||/[^\u0000-\u007f]/.test(e))return null;if(!n)return e.substring(t,r);return e.substring(e.length-r,e.length-t)},JG=(e)=>encodeURIComponent(e).replace(/[!*'()]/g,(t)=>`%${t.charCodeAt(0).toString(16).toUpperCase()}`),QG={booleanEquals:qG,coalesce:BG,getAttr:PR,isSet:$G,isValidHostLabel:NR,ite:FG,not:zG,parseURL:HG,split:VG,stringEquals:GG,substring:KG,uriEncode:JG},MR=(e,t)=>{let r=[],{referenceRecord:n,endpointParams:i}=t,o=0;while(o<e.length){let s=e.indexOf("{",o);if(s===-1){r.push(e.slice(o));break}r.push(e.slice(o,s));let a=e.indexOf("}",s);if(a===-1){r.push(e.slice(s));break}if(e[s+1]==="{"&&e[a+1]==="}")r.push(e.slice(s+1,a)),o=a+2;let c=e.substring(s+1,a);if(c.includes("#")){let[u,d]=c.split("#");r.push(PR(n[u]??i[u],d))}else r.push(n[c]??i[c]);o=a+1}return r.join("")},YG=({ref:e},t)=>t.referenceRecord[e]??t.endpointParams[e],Lf=(e,t,r)=>{if(typeof e==="string")return MR(e,r);else if(e.fn)return BR.callFunction(e,r);else if(e.ref)return YG(e,r);throw new Vi(`'${t}': ${String(e)} is not a string, function or reference.`)},qR=({fn:e,argv:t},r)=>{let n=Array(t.length);for(let s=0;s<n.length;++s){let a=t[s];if(typeof a==="boolean"||typeof a==="number")n[s]=a;else n[s]=BR.evaluateExpression(a,"arg",r)}let i=e.indexOf(".");if(i!==-1){let a=UR[e.slice(0,i)]?.[e.slice(i+1)];if(typeof a==="function")return a(...n)}let o=QG[e];if(typeof o==="function")return o(...n);throw Error(`function ${e} not loaded in endpointFunctions.`)},BR={evaluateExpression:Lf,callFunction:qR},jR=(e,t)=>{let{assign:r}=e;if(r&&r in t.referenceRecord)throw new Vi(`'${r}' is already defined in Reference Record.`);let n=qR(e,t);t.logger?.debug?.(`${Pf} evaluateCondition: ${bc(e)} = ${bc(n)}`);let i=n===""?!0:!!n;if(r!=null)return{result:i,toAssign:{name:r,value:n}};return{result:i}},$R=(e,t)=>Object.entries(e??{}).reduce((r,[n,i])=>(r[n]=i.map((o)=>{let s=Lf(o,"Header value entry",t);if(typeof s!=="string")throw new Vi(`Header '${n}' value '${s}' is not a string`);return s}),r),{}),bb=(e,t)=>Object.entries(e).reduce((r,[n,i])=>(r[n]=zR.getEndpointProperty(i,t),r),{}),FR=(e,t)=>{if(Array.isArray(e))return e.map((r)=>FR(r,t));switch(typeof e){case"string":return MR(e,t);case"object":if(e===null)throw new Vi(`Unexpected endpoint property: ${e}`);return zR.getEndpointProperties(e,t);case"boolean":return e;default:throw new Vi(`Unexpected endpoint property type: ${typeof e}`)}},zR={getEndpointProperty:FR,getEndpointProperties:bb},WR=(e,t)=>{let r=Lf(e,"Endpoint URL",t);if(typeof r==="string")try{return new URL(r)}catch(n){throw console.error(`Failed to construct URL with ${r}`,n),n}throw new Vi(`Endpoint URL must be a string, got ${typeof r}`)},yb=1e8,XG=(e,t)=>{let{nodes:r,root:n,results:i,conditions:o}=e,s=n,a={},c={referenceRecord:a,endpointParams:t.endpointParams,logger:t.logger};while(s!==1&&s!==-1&&s<yb){let u=3*(Math.abs(s)-1),[d,f,h]=[r[u],r[u+1],r[u+2]],[p,g,_]=o[d],R=jR({fn:p,assign:_,argv:g},c);if(R.toAssign){let{name:O,value:I}=R.toAssign;a[O]=I}s=s>=0===R.result?f:h}if(s>=yb){let u=i[s-yb];if(u[0]===-1){let[,p]=u;throw new Vi(Lf(p,"Error",c))}let[d,f,h]=u;return{url:WR(d,c),properties:bb(f,c),headers:$R(h??{},c)}}throw new Vi("No matching endpoint.")},Eb=(e=[],t)=>{let r={},n={...t,referenceRecord:{...t.referenceRecord}},i=!1;for(let o of e){let{result:s,toAssign:a}=jR(o,n);if(!s)return{result:s};if(a)i=!0,r[a.name]=a.value,n.referenceRecord[a.name]=a.value,t.logger?.debug?.(`${Pf} assign: ${a.name} := ${bc(a.value)}`)}if(i)return{result:!0,referenceRecord:r};return{result:!0}},ZG=(e,t)=>{let{conditions:r,endpoint:n}=e,{result:i,referenceRecord:o}=Eb(r,t);if(!i)return;let s=o?{...t,referenceRecord:{...t.referenceRecord,...o}}:t,{url:a,properties:c,headers:u}=n;t.logger?.debug?.(`${Pf} Resolving endpoint from template: ${bc(n)}`);let d={url:WR(a,s)};if(u!=null)d.headers=$R(u,s);if(c!=null)d.properties=bb(c,s);return d},e5=(e,t)=>{let{conditions:r,error:n}=e,{result:i,referenceRecord:o}=Eb(r,t);if(!i)return;let s=o?{...t,referenceRecord:{...t.referenceRecord,...o}}:t;throw new Vi(Lf(n,"Error",s))},HR=(e,t)=>{for(let r of e)if(r.type==="endpoint"){let n=ZG(r,t);if(n)return n}else if(r.type==="error")e5(r,t);else if(r.type==="tree"){let n=VR.evaluateTreeRule(r,t);if(n)return n}else throw new Vi(`Unknown endpoint rule: ${r}`);throw new Vi("Rules evaluation failed")},t5=(e,t)=>{let{conditions:r,rules:n}=e,{result:i,referenceRecord:o}=Eb(r,t);if(!i)return;let s=o?{...t,referenceRecord:{...t.referenceRecord,...o}}:t;return VR.evaluateRules(n,s)},VR={evaluateRules:HR,evaluateTreeRule:t5},r5=(e,t)=>{let{endpointParams:r,logger:n}=t,{parameters:i,rules:o}=e;t.logger?.debug?.(`${Pf} Initial EndpointParams: ${bc(r)}`);for(let a in i){if(!SG(i,a))continue;let c=i[a],u=r[a];if(u==null&&c.default!=null){r[a]=c.default;continue}if(c.required&&u==null)throw new Vi(`Missing required parameter: '${a}'`)}let s=HR(o,{endpointParams:r,logger:n,referenceRecord:{}});return t.logger?.debug?.(`${Pf} Resolved endpoint: ${bc(s)}`),s},n5=(e)=>{let{endpoint:t}=e;if(t===void 0)e.endpoint=async()=>{throw Error("@smithy/middleware-endpoint: (default endpointRuleSet) endpoint is not set - you must configure an endpoint.")};return e},i5=xR(Em),o5=MG(Em),s5=OR(Em),a5=LG(Em);c5.BinaryDecisionDiagram=_b;c5.EndpointCache=DR;c5.EndpointError=Vi;c5.customEndpointFunctions=UR;c5.decideEndpoint=XG;c5.endpointMiddleware=s5;c5.endpointMiddlewareOptions=IR;c5.getEndpointFromInstructions=i5;c5.getEndpointPlugin=a5;c5.isIpAddress=LR;c5.resolveEndpoint=r5;c5.resolveEndpointConfig=o5;c5.resolveEndpointRequiredConfig=n5;c5.resolveParams=CR});var z=A(function(e8){var{createHmac:k5,createHash:R5,getRandomValues:N5}=C("crypto"),{hasOwn:eN,HttpResponse:x5}=Po();e8.hasOwn=eN;var{ReadStream:C5,lstatSync:O5,fstatSync:I5}=C("fs"),{toEndpointV1:D5}=oe(),{Readable:vd,Writable:tN,PassThrough:GR}=C("stream"),rN=(e)=>typeof ArrayBuffer==="function"&&e instanceof ArrayBuffer||Object.prototype.toString.call(e)==="[object ArrayBuffer]",Rd=(e,t=0,r=e.byteLength-t)=>{if(!rN(e))throw TypeError(`The "input" argument must be ArrayBuffer. Received type ${typeof e} (${e})`);return Buffer.from(e,t,r)},vm=(e,t)=>{if(typeof e!=="string")throw TypeError(`The "input" argument must be of type string. Received type ${typeof e} (${e})`);return t?Buffer.from(e,t):Buffer.from(e)},U5=/^[A-Za-z0-9+/]*={0,2}$/,nN=(e)=>{if(e.length*3%4!==0)throw TypeError("Incorrect padding on base64 string.");if(!U5.exec(e))throw TypeError("Invalid base64 string.");let t=vm(e,"base64");return new Uint8Array(t.buffer,t.byteOffset,t.byteLength)},km=(e)=>{let t=vm(e,"utf8");return new Uint8Array(t.buffer,t.byteOffset,t.byteLength/Uint8Array.BYTES_PER_ELEMENT)},xb=(e)=>{let t;if(typeof e==="string")t=km(e);else t=e;if(typeof t!=="object"||typeof t.byteOffset!=="number"||typeof t.byteLength!=="number")throw Error("@smithy/util-base64: toBase64 encoder function only accepts string | Uint8Array.");return Rd(t.buffer,t.byteOffset,t.byteLength).toString("base64")};function P5(e,t,r,n){return class i extends Uint8Array{static fromString(o,s="utf-8"){if(typeof o==="string"){if(s==="base64")return i.mutate(n(o));return i.mutate(t(o))}throw Error(`Unsupported conversion from ${typeof o} to Uint8ArrayBlobAdapter.`)}static mutate(o){return Object.setPrototypeOf(o,i.prototype),o}transformToString(o="utf-8"){if(o==="base64")return r(this);return e(this)}}}var iN=(e)=>{if(typeof e==="string")return e;if(typeof e!=="object"||typeof e.byteOffset!=="number"||typeof e.byteLength!=="number")throw Error("@smithy/util-utf8: toUtf8 encoder function only accepts string | Uint8Array.");return Rd(e.buffer,e.byteOffset,e.byteLength).toString("utf8")},io=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));function L5(e){if(typeof crypto<"u"&&typeof crypto.randomUUID==="function")return()=>crypto.randomUUID();return()=>{let t=new Uint8Array(16);return e(t),t[6]=t[6]&15|64,t[8]=t[8]&63|128,io[t[0]]+io[t[1]]+io[t[2]]+io[t[3]]+"-"+io[t[4]]+io[t[5]]+"-"+io[t[6]]+io[t[7]]+"-"+io[t[8]]+io[t[9]]+"-"+io[t[10]]+io[t[11]]+io[t[12]]+io[t[13]]+io[t[14]]+io[t[15]]}}var M5=(e,t,r=(n)=>n)=>e,q5=(e)=>{switch(e){case"true":return!0;case"false":return!1;default:throw Error(`Unable to parse boolean value "${e}"`)}},B5=(e)=>{if(e===null||e===void 0)return;if(typeof e==="number"){if(e===0||e===1)jf.warn(Am(`Expected boolean, got ${typeof e}: ${e}`));if(e===0)return!1;if(e===1)return!0}if(typeof e==="string"){let t=e.toLowerCase();if(t==="false"||t==="true")jf.warn(Am(`Expected boolean, got ${typeof e}: ${e}`));if(t==="false")return!1;if(t==="true")return!0}if(typeof e==="boolean")return e;throw TypeError(`Expected boolean, got ${typeof e}: ${e}`)},qf=(e)=>{if(e===null||e===void 0)return;if(typeof e==="string"){let t=parseFloat(e);if(!Number.isNaN(t)){if(String(t)!==String(e))jf.warn(Am(`Expected number but observed string: ${e}`));return t}}if(typeof e==="number")return e;throw TypeError(`Expected number, got ${typeof e}: ${e}`)},j5=Math.ceil(340282346638528860000000000000000000000),Sm=(e)=>{let t=qf(e);if(t!==void 0&&!Number.isNaN(t)&&t!==1/0&&t!==-1/0){if(Math.abs(t)>j5)throw TypeError(`Expected 32-bit float, got ${e}`)}return t},Bf=(e)=>{if(e===null||e===void 0)return;if(Number.isInteger(e)&&!Number.isNaN(e))return e;throw TypeError(`Expected integer, got ${typeof e}: ${e}`)},$5=Bf,vb=(e)=>Cb(e,32),kb=(e)=>Cb(e,16),Rb=(e)=>Cb(e,8),Cb=(e,t)=>{let r=Bf(e);if(r!==void 0&&F5(r,t)!==r)throw TypeError(`Expected ${t}-bit integer, got ${e}`);return r},F5=(e,t)=>{switch(t){case 32:return Int32Array.of(e)[0];case 16:return Int16Array.of(e)[0];case 8:return Int8Array.of(e)[0]}},z5=(e,t)=>{if(e===null||e===void 0){if(t)throw TypeError(`Expected a non-null value for ${t}`);throw TypeError("Expected a non-null value")}return e},oN=(e)=>{if(e===null||e===void 0)return;if(typeof e==="object"&&!Array.isArray(e))return e;let t=Array.isArray(e)?"array":typeof e;throw TypeError(`Expected object, got ${t}: ${e}`)},W5=(e)=>{if(e===null||e===void 0)return;if(typeof e==="string")return e;if(["boolean","number","bigint"].includes(typeof e))return jf.warn(Am(`Expected string, got ${typeof e}: ${e}`)),String(e);throw TypeError(`Expected string, got ${typeof e}: ${e}`)},H5=(e)=>{if(e===null||e===void 0)return;let t=oN(e),r=[];for(let n in t){if(!eN(t,n))continue;if(t[n]!=null)r.push(n)}if(r.length===0)throw TypeError("Unions must have exactly one non-null member. None were found.");if(r.length>1)throw TypeError(`Unions must have exactly one non-null member. Keys ${r} were not null.`);return t},Ob=(e)=>{if(typeof e=="string")return qf(Cd(e));return qf(e)},V5=Ob,sN=(e)=>{if(typeof e=="string")return Sm(Cd(e));return Sm(e)},G5=/(-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?)|(-?Infinity)|(NaN)/g,Cd=(e)=>{let t=e.match(G5);if(t===null||t[0].length!==e.length)throw TypeError("Expected real number, got implicit NaN");return parseFloat(e)},Ib=(e)=>{if(typeof e=="string")return aN(e);return qf(e)},K5=Ib,J5=Ib,Q5=(e)=>{if(typeof e=="string")return aN(e);return Sm(e)},aN=(e)=>{switch(e){case"NaN":return NaN;case"Infinity":return 1/0;case"-Infinity":return-1/0;default:throw Error(`Unable to parse float value: ${e}`)}},cN=(e)=>{if(typeof e==="string")return Bf(Cd(e));return Bf(e)},Y5=cN,X5=(e)=>{if(typeof e==="string")return vb(Cd(e));return vb(e)},Nd=(e)=>{if(typeof e==="string")return kb(Cd(e));return kb(e)},uN=(e)=>{if(typeof e==="string")return Rb(Cd(e));return Rb(e)},Am=(e)=>String(TypeError(e).stack||e).split(`
4
+ `).slice(0,5).filter((t)=>!t.includes("stackTraceWarning")).join(`
5
+ `),jf={warn:console.warn},Z5=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],Db=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function eK(e){let t=e.getUTCFullYear(),r=e.getUTCMonth(),n=e.getUTCDay(),i=e.getUTCDate(),o=e.getUTCHours(),s=e.getUTCMinutes(),a=e.getUTCSeconds(),c=i<10?`0${i}`:`${i}`,u=o<10?`0${o}`:`${o}`,d=s<10?`0${s}`:`${s}`,f=a<10?`0${a}`:`${a}`;return`${Z5[n]}, ${c} ${Db[r]} ${t} ${u}:${d}:${f} GMT`}var tK=new RegExp(/^(\d{4})-(\d{2})-(\d{2})[tT](\d{2}):(\d{2}):(\d{2})(?:\.(\d+))?[zZ]$/),rK=(e)=>{if(e===null||e===void 0)return;if(typeof e!=="string")throw TypeError("RFC-3339 date-times must be expressed as strings");let t=tK.exec(e);if(!t)throw TypeError("Invalid RFC-3339 date-time value");let[r,n,i,o,s,a,c,u]=t,d=Nd(xd(n)),f=ra(i,"month",1,12),h=ra(o,"day",1,31);return Mf(d,f,h,{hours:s,minutes:a,seconds:c,fractionalMilliseconds:u})},nK=new RegExp(/^(\d{4})-(\d{2})-(\d{2})[tT](\d{2}):(\d{2}):(\d{2})(?:\.(\d+))?(([-+]\d{2}:\d{2})|[zZ])$/),iK=(e)=>{if(e===null||e===void 0)return;if(typeof e!=="string")throw TypeError("RFC-3339 date-times must be expressed as strings");let t=nK.exec(e);if(!t)throw TypeError("Invalid RFC-3339 date-time value");let[r,n,i,o,s,a,c,u,d]=t,f=Nd(xd(n)),h=ra(i,"month",1,12),p=ra(o,"day",1,31),g=Mf(f,h,p,{hours:s,minutes:a,seconds:c,fractionalMilliseconds:u});if(d.toUpperCase()!="Z")g.setTime(g.getTime()-yK(d));return g},oK=new RegExp(/^(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun), (\d{2}) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) (\d{4}) (\d{1,2}):(\d{2}):(\d{2})(?:\.(\d+))? GMT$/),sK=new RegExp(/^(?:Monday|Tuesday|Wednesday|Thursday|Friday|Saturday|Sunday), (\d{2})-(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)-(\d{2}) (\d{1,2}):(\d{2}):(\d{2})(?:\.(\d+))? GMT$/),aK=new RegExp(/^(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) ( [1-9]|\d{2}) (\d{1,2}):(\d{2}):(\d{2})(?:\.(\d+))? (\d{4})$/),cK=(e)=>{if(e===null||e===void 0)return;if(typeof e!=="string")throw TypeError("RFC-7231 date-times must be expressed as strings");let t=oK.exec(e);if(t){let[r,n,i,o,s,a,c,u]=t;return Mf(Nd(xd(o)),Sb(i),ra(n,"day",1,31),{hours:s,minutes:a,seconds:c,fractionalMilliseconds:u})}if(t=sK.exec(e),t){let[r,n,i,o,s,a,c,u]=t;return fK(Mf(dK(o),Sb(i),ra(n,"day",1,31),{hours:s,minutes:a,seconds:c,fractionalMilliseconds:u}))}if(t=aK.exec(e),t){let[r,n,i,o,s,a,c,u]=t;return Mf(Nd(xd(u)),Sb(n),ra(i.trimLeft(),"day",1,31),{hours:o,minutes:s,seconds:a,fractionalMilliseconds:c})}throw TypeError("Invalid RFC-7231 date-time value")},uK=(e)=>{if(e===null||e===void 0)return;let t;if(typeof e==="number")t=e;else if(typeof e==="string")t=Ob(e);else if(typeof e==="object"&&e.tag===1)t=e.value;else throw TypeError("Epoch timestamps must be expressed as floating point numbers or their string representation");if(Number.isNaN(t)||t===1/0||t===-1/0)throw TypeError("Epoch timestamps must be valid, non-Infinite, non-NaN numerics");return new Date(Math.round(t*1000))},Mf=(e,t,r,n)=>{let i=t-1;return pK(e,i,r),new Date(Date.UTC(e,i,r,ra(n.hours,"hour",0,23),ra(n.minutes,"minute",0,59),ra(n.seconds,"seconds",0,60),gK(n.fractionalMilliseconds)))},dK=(e)=>{let t=new Date().getUTCFullYear(),r=Math.floor(t/100)*100+Nd(xd(e));if(r<t)return r+100;return r},lK=1576800000000,fK=(e)=>{if(e.getTime()-new Date().getTime()>lK)return new Date(Date.UTC(e.getUTCFullYear()-100,e.getUTCMonth(),e.getUTCDate(),e.getUTCHours(),e.getUTCMinutes(),e.getUTCSeconds(),e.getUTCMilliseconds()));return e},Sb=(e)=>{let t=Db.indexOf(e);if(t<0)throw TypeError(`Invalid month: ${e}`);return t+1},hK=[31,28,31,30,31,30,31,31,30,31,30,31],pK=(e,t,r)=>{let n=hK[t];if(t===1&&mK(e))n=29;if(r>n)throw TypeError(`Invalid day for ${Db[t]} in ${e}: ${r}`)},mK=(e)=>e%4===0&&(e%100!==0||e%400===0),ra=(e,t,r,n)=>{let i=uN(xd(e));if(i<r||i>n)throw TypeError(`${t} must be between ${r} and ${n}, inclusive`);return i},gK=(e)=>{if(e===null||e===void 0)return 0;return sN("0."+e)*1000},yK=(e)=>{let t=e[0],r=1;if(t=="+")r=1;else if(t=="-")r=-1;else throw TypeError(`Offset direction, ${t}, must be "+" or "-"`);let n=Number(e.substring(1,3)),i=Number(e.substring(4,6));return r*(n*60+i)*60*1000},xd=(e)=>{let t=0;while(t<e.length-1&&e.charAt(t)==="0")t++;if(t===0)return e;return e.slice(t)},Ou=function(t){return Object.assign(new String(t),{deserializeJSON(){return JSON.parse(String(t))},toString(){return String(t)},toJSON(){return String(t)}})};Ou.from=(e)=>{if(e&&typeof e==="object"&&(e instanceof Ou||("deserializeJSON"in e)))return e;else if(typeof e==="string"||Object.getPrototypeOf(e)===String.prototype)return Ou(String(e));return Ou(JSON.stringify(e))};Ou.fromObject=Ou.from;function wK(e){if(e.includes(",")||e.includes('"'))e=`"${e.replace(/"/g,"\\\"")}"`;return e}var Ub="(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun)(?:[ne|u?r]?s?day)?",Pb="(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)",Lb="(\\d?\\d):(\\d{2}):(\\d{2})(?:\\.(\\d+))?",dN="(\\d?\\d)",lN="(\\d{4})",_K=new RegExp(/^(\d{4})-(\d\d)-(\d\d)[tT](\d\d):(\d\d):(\d\d)(\.(\d+))?(([-+]\d\d:\d\d)|[zZ])$/),bK=new RegExp(`^${Ub}, ${dN} ${Pb} ${lN} ${Lb} GMT$`),EK=new RegExp(`^${Ub}, ${dN}-${Pb}-(\\d\\d) ${Lb} GMT$`),SK=new RegExp(`^${Ub} ${Pb} ( [1-9]|\\d\\d) ${Lb} ${lN}$`),AK=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],TK=(e)=>{if(e==null)return;let t=NaN;if(typeof e==="number")t=e;else if(typeof e==="string"){if(!/^-?\d*\.?\d+$/.test(e))throw TypeError("parseEpochTimestamp - numeric string invalid.");t=Number.parseFloat(e)}else if(typeof e==="object"&&e.tag===1)t=e.value;if(isNaN(t)||Math.abs(t)===1/0)throw TypeError("Epoch timestamps must be valid finite numbers.");return new Date(Math.round(t*1000))},vK=(e)=>{if(e==null)return;if(typeof e!=="string")throw TypeError("RFC3339 timestamps must be strings");let t=_K.exec(e);if(!t)throw TypeError(`Invalid RFC3339 timestamp format ${e}`);let[,r,n,i,o,s,a,,c,u]=t;$a(n,1,12),$a(i,1,31),$a(o,0,23),$a(s,0,59),$a(a,0,60);let d=new Date(Date.UTC(Number(r),Number(n)-1,Number(i),Number(o),Number(s),Number(a),Number(c)?Math.round(parseFloat(`0.${c}`)*1000):0));if(d.setUTCFullYear(Number(r)),u.toUpperCase()!="Z"){let[,f,h,p]=/([+-])(\d\d):(\d\d)/.exec(u)||[void 0,"+",0,0],g=f==="-"?1:-1;d.setTime(d.getTime()+g*(Number(h)*60*60*1000+Number(p)*60*1000))}return d},kK=(e)=>{if(e==null)return;if(typeof e!=="string")throw TypeError("RFC7231 timestamps must be strings.");let t,r,n,i,o,s,a,c;if(c=bK.exec(e))[,t,r,n,i,o,s,a]=c;else if(c=EK.exec(e))[,t,r,n,i,o,s,a]=c,n=(Number(n)+1900).toString();else if(c=SK.exec(e))[,r,t,i,o,s,a,n]=c;if(n&&s){let u=Date.UTC(Number(n),AK.indexOf(r),Number(t),Number(i),Number(o),Number(s),a?Math.round(parseFloat(`0.${a}`)*1000):0);$a(t,1,31),$a(i,0,23),$a(o,0,59),$a(s,0,60);let d=new Date(u);return d.setUTCFullYear(Number(n)),d}throw TypeError(`Invalid RFC7231 date-time value ${e}.`)};function $a(e,t,r){let n=Number(e);if(n<t||n>r)throw Error(`Value ${n} out of range [${t}, ${r}]`)}function RK(e,t,r){if(r<=0||!Number.isInteger(r))throw Error("Invalid number of delimiters ("+r+") for splitEvery.");let n=e.split(t);if(r===1)return n;let i=[],o="";for(let s=0;s<n.length;s++){if(o==="")o=n[s];else o+=t+n[s];if((s+1)%r===0)i.push(o),o=""}if(o!=="")i.push(o);return i}var NK=(e)=>{let t=e.length,r=[],n=!1,i=void 0,o=0;for(let s=0;s<t;++s){let a=e[s];switch(a){case'"':if(i!=="\\")n=!n;break;case",":if(!n)r.push(e.slice(o,s)),o=s+1;break}i=a}return r.push(e.slice(o)),r.map((s)=>{s=s.trim();let a=s.length;if(a<2)return s;if(s[0]==='"'&&s[a-1]==='"')s=s.slice(1,a-1);return s.replace(/\\"/g,'"')})},KR=/^-?((0|[1-9]\d*)(\.\d+)?|\.\d+)([eE][+-]?\d+)?$/;class Rm{string;type;constructor(e,t){if(this.string=e,this.type=t,!KR.test(e))throw Error(`@smithy/core/serde - NumericValue string must conform to the Smithy bigDecimal format. Received: "${e}"`)}toString(){return this.string}static[Symbol.hasInstance](e){if(!e||typeof e!=="object")return!1;let t=e;return Rm.prototype.isPrototypeOf(e)||t.type==="bigDecimal"&&KR.test(t.string)}}function xK(e){return new Rm(String(e),"bigDecimal")}var fN={},Nb={};for(let e=0;e<256;e++){let t=e.toString(16).toLowerCase();if(t.length===1)t=`0${t}`;fN[e]=t,Nb[t]=e}function CK(e){if(e.length%2!==0)throw Error("Hex encoded strings must have an even number length");let t=new Uint8Array(e.length/2);for(let r=0;r<e.length;r+=2){let n=e.slice(r,r+2).toLowerCase();if(n in Nb)t[r/2]=Nb[n];else throw Error(`Cannot decode unrecognized sequence ${n} as hexadecimal`)}return t}function hN(e){let t="";for(let r=0;r<e.byteLength;r++)t+=fN[e[r]];return t}var OK=(e)=>{if(!e)return 0;if(typeof e==="string")return Buffer.byteLength(e);else if(typeof e.byteLength==="number")return e.byteLength;else if(typeof e.size==="number")return e.size;else if(typeof e.start==="number"&&typeof e.end==="number")return e.end+1-e.start;else if(e instanceof C5){if(e.path!=null)return O5(e.path).size;else if(typeof e.fd==="number")return I5(e.fd).size}throw Error(`Body Length computation failed for ${e}`)},pN=(e)=>{if(e instanceof Uint8Array)return e;if(typeof e==="string")return km(e);if(ArrayBuffer.isView(e))return new Uint8Array(e.buffer,e.byteOffset,e.byteLength/Uint8Array.BYTES_PER_ELEMENT);return new Uint8Array(e)};function Nm(e,t){if(t===void 0){t=0;for(let i of e)t+=i.byteLength}let r=new Uint8Array(t),n=0;for(let i of e)r.set(i,n),n+=i.byteLength;return r}var mN=(e,t)=>(r,n)=>async(i)=>{let{response:o}=await r(i);try{let s=await t(o,e);return{response:o,output:s}}catch(s){if(Object.defineProperty(s,"$response",{value:o,enumerable:!1,writable:!1,configurable:!1}),!("$metadata"in s)){try{s.message+=`
6
+ Deserialization error: to see the raw response, inspect the hidden field {error}.$response on this object.`}catch(c){if(!n.logger||n.logger?.constructor?.name==="NoOpLogger")console.warn("Deserialization error: to see the raw response, inspect the hidden field {error}.$response on this object.");else n.logger?.warn?.("Deserialization error: to see the raw response, inspect the hidden field {error}.$response on this object.")}if(typeof s.$responseBodyText<"u"){if(s.$response)s.$response.body=s.$responseBodyText}try{if(x5.isInstance(o)){let{headers:c={}}=o,u=Object.entries(c);s.$metadata={httpStatusCode:o.statusCode,requestId:Ab(/^x-[\w-]+-request-?id$/,u),extendedRequestId:Ab(/^x-[\w-]+-id-2$/,u),cfId:Ab(/^x-[\w-]+-cf-id$/,u)}}}catch(c){}}throw s}},Ab=(e,t)=>(t.find(([r])=>r.match(e))||[void 0,void 0])[1],gN=(e,t)=>(r,n)=>async(i)=>{let o=e,s=n.endpointV2?async()=>D5(n.endpointV2):o.endpoint;if(!s)throw Error("No valid endpoint provider available.");let a=await t(i.input,{...e,endpoint:s});return r({...i,request:a})},yN={name:"deserializerMiddleware",step:"deserialize",tags:["DESERIALIZER"],override:!0},wN={name:"serializerMiddleware",step:"serialize",tags:["SERIALIZER"],override:!0};function IK(e,t,r){return{applyToStack:(n)=>{n.add(mN(e,r),yN),n.add(gN(e,t),wN)}}}class _N{algorithmIdentifier;secret;hash;constructor(e,t){this.algorithmIdentifier=e,this.secret=t,this.reset()}update(e,t){this.hash.update(pN(JR(e,t)))}digest(){return Promise.resolve(this.hash.digest())}reset(){this.hash=this.secret?k5(this.algorithmIdentifier,JR(this.secret)):R5(this.algorithmIdentifier)}}function JR(e,t){if(Buffer.isBuffer(e))return e;if(typeof e==="string")return vm(e,t);if(ArrayBuffer.isView(e))return Rd(e.buffer,e.byteOffset,e.byteLength);return Rd(e)}var bN=class extends vd{expectedChecksum;checksumSourceLocation;checksum;source;base64Encoder;constructor({expectedChecksum:t,checksum:r,source:n,checksumSourceLocation:i,base64Encoder:o}){super();if(typeof n.pipe!=="function")throw Error(`@smithy/util-stream: unsupported source type ${n?.constructor?.name??n} in ChecksumStream.`);this.source=n,this.base64Encoder=o??xb,this.expectedChecksum=t,this.checksum=r,this.checksumSourceLocation=i,this.source.on("data",this.onSourceData),this.source.on("end",this.onSourceEnd),this.source.on("error",this.onSourceError),this.source.on("close",this.onSourceClose),this.source.pause()}onSourceData=(t)=>{if(this.destroyed)return;try{this.checksum.update(t)}catch(r){this.destroy(r);return}if(!this.push(t))this.source.pause()};onSourceEnd=async()=>{if(this.destroyed)return;try{let t=await this.checksum.digest(),r=this.base64Encoder(t);if(this.expectedChecksum!==r){this.destroy(Error(`Checksum mismatch: expected "${this.expectedChecksum}" but received "${r}" in response header "${this.checksumSourceLocation}".`));return}}catch(t){this.destroy(t);return}this.push(null)};onSourceError=(t)=>{this.destroy(t)};onSourceClose=()=>{if(!this.destroyed&&!this.source.readableEnded)this.destroy(Error("Connection lost or stream closed before all data was received."))};_read(t){this.source.resume()}_destroy(t,r){this.source?.removeListener("data",this.onSourceData),this.source?.removeListener("end",this.onSourceEnd),this.source?.removeListener("error",this.onSourceError),this.source?.removeListener("close",this.onSourceClose),this.source?.destroy(),r(t)}},na=(e)=>typeof ReadableStream==="function"&&(e?.constructor?.name===ReadableStream.name||e instanceof ReadableStream),xm=(e)=>typeof Blob==="function"&&(e?.constructor?.name===Blob.name||e instanceof Blob),DK=(e)=>new TextEncoder().encode(e),EN="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";Object.entries(EN).reduce((e,[t,r])=>(e[r]=Number(t),e),{});var UK=EN.split(""),Tb=6,QR=8,PK=63;function SN(e){let t;if(typeof e==="string")t=DK(e);else t=e;let r=typeof t==="object"&&typeof t.length==="number",n=typeof t==="object"&&typeof t.byteOffset==="number"&&typeof t.byteLength==="number";if(!r&&!n)throw Error("@smithy/util-base64: toBase64 encoder function only accepts string | Uint8Array.");let i="";for(let o=0;o<t.length;o+=3){let s=0,a=0;for(let u=o,d=Math.min(o+3,t.length);u<d;u++)s|=t[u]<<(d-u-1)*QR,a+=QR;let c=Math.ceil(a/Tb);s<<=c*Tb-a;for(let u=1;u<=c;u++){let d=(c-u)*Tb;i+=UK[(s&PK<<d)>>d]}i+="==".slice(0,4-c)}return i}var LK=typeof ReadableStream==="function"?ReadableStream:function(){};class AN extends LK{}var MK=({expectedChecksum:e,checksum:t,source:r,checksumSourceLocation:n,base64Encoder:i})=>{if(!na(r))throw Error(`@smithy/util-stream: unsupported source type ${r?.constructor?.name??r} in ChecksumStream.`);let o=i??SN;if(typeof TransformStream!=="function")throw Error("@smithy/util-stream: unable to instantiate ChecksumStream because API unavailable: ReadableStream/TransformStream.");let s=new TransformStream({start(){},async transform(c,u){t.update(c),u.enqueue(c)},async flush(c){let u=await t.digest(),d=o(u);if(e!==d){let f=Error(`Checksum mismatch: expected "${e}" but received "${d}" in response header "${n}".`);c.error(f)}else c.terminate()}});r.pipeThrough(s);let a=s.readable;return Object.setPrototypeOf(a,AN.prototype),a};function qK(e){if(typeof ReadableStream==="function"&&na(e.source))return MK(e);return new bN(e)}class Tm{allocByteArray;byteLength=0;byteArrays=[];constructor(e){this.allocByteArray=e}push(e){this.byteArrays.push(e),this.byteLength+=e.byteLength}flush(){if(this.byteArrays.length===1){let r=this.byteArrays[0];return this.reset(),r}let e=this.allocByteArray(this.byteLength),t=0;for(let r=0;r<this.byteArrays.length;++r){let n=this.byteArrays[r];e.set(n,t),t+=n.byteLength}return this.reset(),e}reset(){this.byteArrays=[],this.byteLength=0}}function BK(e,t,r){let n=e.getReader(),i=!1,o=0,s=["",new Tm((u)=>new Uint8Array(u))],a=-1,c=async(u)=>{let{value:d,done:f}=await n.read(),h=d;if(f){if(a!==-1){let p=kd(s,a);if(Ec(p)>0)u.enqueue(p)}u.close()}else{let p=vN(h,!1);if(a!==p){if(a>=0)u.enqueue(kd(s,a));a=p}if(a===-1){u.enqueue(h);return}let g=Ec(h);o+=g;let _=Ec(s[a]);if(g>=t&&_===0)u.enqueue(h);else{let R=TN(s,a,h);if(!i&&o>t*2)i=!0,r?.warn(`@smithy/util-stream - stream chunk size ${g} is below threshold of ${t}, automatically buffering.`);if(R>=t)u.enqueue(kd(s,a));else await c(u)}}};return new ReadableStream({pull:c})}function TN(e,t,r){switch(t){case 0:return e[0]+=r,Ec(e[0]);case 1:case 2:return e[t].push(r),Ec(e[t])}}function kd(e,t){switch(t){case 0:let r=e[0];return e[0]="",r;case 1:case 2:return e[t].flush()}throw Error(`@smithy/util-stream - invalid index ${t} given to flush()`)}function Ec(e){return e?.byteLength??e?.length??0}function vN(e,t=!0){if(t&&typeof Buffer<"u"&&e instanceof Buffer)return 2;if(e instanceof Uint8Array)return 1;if(typeof e==="string")return 0;return-1}function jK(e,t,r){if(na(e))return BK(e,t,r);let n=new vd({read(){}}),i=!1,o=0,s=["",new Tm((c)=>new Uint8Array(c)),new Tm((c)=>Buffer.from(new Uint8Array(c)))],a=-1;return e.on("data",(c)=>{let u=vN(c,!0);if(a!==u){if(a>=0)n.push(kd(s,a));a=u}if(a===-1){n.push(c);return}let d=Ec(c);o+=d;let f=Ec(s[a]);if(d>=t&&f===0)n.push(c);else{let h=TN(s,a,c);if(!i&&o>t*2)i=!0,r?.warn(`@smithy/util-stream - stream chunk size ${d} is below threshold of ${t}, automatically buffering.`);if(h>=t)n.push(kd(s,a))}}),e.on("end",()=>{if(a!==-1){let c=kd(s,a);if(Ec(c)>0)n.push(c)}n.push(null)}),n}var $K=(e,t)=>{let{base64Encoder:r,bodyLengthChecker:n,checksumAlgorithmFn:i,checksumLocationName:o,streamHasher:s}=t,a=r!==void 0&&n!==void 0&&i!==void 0&&o!==void 0&&s!==void 0,c=a?s(i,e):void 0,u=e.getReader();return new ReadableStream({async pull(d){let{value:f,done:h}=await u.read();if(h){if(d.enqueue(`0\r
7
+ `),a){let p=r(await c);d.enqueue(`${o}:${p}\r
8
+ `),d.enqueue(`\r
9
+ `)}d.close()}else d.enqueue(`${(n(f)||0).toString(16)}\r
10
+ ${f}\r
11
+ `)}})};function FK(e,t){let r=e,n=e;if(na(n))return $K(n,t);let{base64Encoder:i,bodyLengthChecker:o,checksumAlgorithmFn:s,checksumLocationName:a,streamHasher:c}=t,u=i!==void 0&&s!==void 0&&a!==void 0&&c!==void 0,d=u?c(s,r):void 0,f=new vd({read:()=>{}});return r.on("data",(h)=>{let p=o(h)||0;if(p===0)return;f.push(`${p.toString(16)}\r
12
+ `),f.push(h),f.push(`\r
13
+ `)}),r.on("end",async()=>{if(f.push(`0\r
14
+ `),u){let h=i(await d);f.push(`${a}:${h}\r
15
+ `),f.push(`\r
16
+ `)}f.push(null)}),f}async function zK(e,t){let r=0,n=[],i=e.getReader(),o=!1;while(!o){let{done:c,value:u}=await i.read();if(u)n.push(u),r+=u?.byteLength??0;if(r>=t)break;o=c}i.releaseLock();let s=new Uint8Array(Math.min(t,r)),a=0;for(let c of n){if(c.byteLength>s.byteLength-a){s.set(c.subarray(0,s.byteLength-a),a);break}else s.set(c,a);a+=c.length}return s}var WK=(e,t)=>{if(na(e))return zK(e,t);return new Promise((r,n)=>{let i=new HK;i.limit=t,e.pipe(i),e.on("error",(o)=>{i.end(),n(o)}),i.on("error",n),i.on("finish",function(){let o=Nm(this.buffers);r(o)})})},HK=class extends tN{buffers=[];limit=1/0;bytesBuffered=0;_write(t,r,n){if(this.buffers.push(t),this.bytesBuffered+=t.byteLength??0,this.bytesBuffered>=this.limit){let i=this.bytesBuffered-this.limit,o=this.buffers[this.buffers.length-1];this.buffers[this.buffers.length-1]=o.subarray(0,o.byteLength-i),this.emit("finish")}n()}},VK=(e)=>{if(typeof e==="string")return e;if(typeof e!=="object"||typeof e.byteOffset!=="number"||typeof e.byteLength!=="number")throw Error("@smithy/util-utf8: toUtf8 encoder function only accepts string | Uint8Array.");return new TextDecoder("utf-8").decode(e)},GK=async(e)=>{if(xm(e))return kN(e);return RN(e)};async function kN(e){return e.arrayBuffer().then((t)=>new Uint8Array(t))}async function RN(e){let t=[],r=e.getReader(),n=0;while(!0){let{done:i,value:o}=await r.read();if(o)t.push(o),n+=o.length;if(i)break}return Nm(t,n)}var YR="The stream has already been transformed.",KK=(e)=>{if(!XR(e)&&!na(e)){let i=e?.__proto__?.constructor?.name||e;throw Error(`Unexpected stream implementation, expect Blob or ReadableStream, got ${i}`)}let t=!1,r=async()=>{if(t)throw Error(YR);return t=!0,await GK(e)},n=(i)=>{if(typeof i.stream!=="function")throw Error(`Cannot transform payload Blob to web stream. Please make sure the Blob.stream() is polyfilled.
17
+ If you are using React Native, this API is not yet supported, see: https://react-native.canny.io/feature-requests/p/fetch-streaming-body`);return i.stream()};return Object.assign(e,{transformToByteArray:r,transformToString:async(i)=>{let o=await r();if(i==="base64")return SN(o);else if(i==="hex")return hN(o);else if(i===void 0||i==="utf8"||i==="utf-8")return VK(o);else if(typeof TextDecoder==="function")return new TextDecoder(i).decode(o);else throw Error("TextDecoder is not available, please make sure polyfill is provided.")},transformToWebStream:()=>{if(t)throw Error(YR);if(t=!0,XR(e))return n(e);else if(na(e))return e;else throw Error(`Cannot transform payload to web stream, got ${e}`)}})},XR=(e)=>typeof Blob==="function"&&e instanceof Blob,NN=(e)=>{if(xm(e))return kN(e);if(na(e))return RN(e);return new Promise((t,r)=>{let n=new xN,i=e;i.pipe(n),i.on("error",(o)=>{n.end(),r(o)}),n.on("error",r),n.on("finish",function(){let o=Nm(this.bufferedBytes);t(o)})})};class xN extends tN{bufferedBytes=[];_write(e,t,r){this.bufferedBytes.push(e),r()}}var ZR="The stream has already been transformed.",JK=(e)=>{if(!(e instanceof vd))try{return KK(e)}catch(n){let i=e?.__proto__?.constructor?.name||e;throw Error(`Unexpected stream implementation, expect Stream.Readable instance, got ${i}`)}let t=!1,r=async()=>{if(t)throw Error(ZR);return t=!0,await NN(e)};return Object.assign(e,{transformToByteArray:r,transformToString:async(n)=>{let i=await r();if(n===void 0||Buffer.isEncoding(n))return Rd(i.buffer,i.byteOffset,i.byteLength).toString(n);else return new TextDecoder(n).decode(i)},transformToWebStream:()=>{if(t)throw Error(ZR);if(e.readableFlowing!==null)throw Error("The stream has been consumed by other callbacks.");if(typeof vd.toWeb!=="function")throw Error("Readable.toWeb() is not supported. Please ensure a polyfill is available.");return t=!0,vd.toWeb(e)}})};async function QK(e){if(typeof e.stream==="function")e=e.stream();return e.tee()}async function YK(e){if(na(e)||xm(e))return QK(e);let t=new GR,r=new GR;return e.pipe(t),e.pipe(r),[t,r]}class CN extends P5(iN,km,xb,nN){}var XK=N5,ON=L5(XK),ZK=ON;e8.ChecksumStream=bN;e8.Hash=_N;e8.LazyJsonString=Ou;e8.NumericValue=Rm;e8.Uint8ArrayBlobAdapter=CN;e8._parseEpochTimestamp=TK;e8._parseRfc3339DateTimeWithOffset=vK;e8._parseRfc7231DateTime=kK;e8.calculateBodyLength=OK;e8.concatBytes=Nm;e8.copyDocumentWithTransform=M5;e8.createBufferedReadable=jK;e8.createChecksumStream=qK;e8.dateToUtcString=eK;e8.deserializerMiddleware=mN;e8.deserializerMiddlewareOption=yN;e8.expectBoolean=B5;e8.expectByte=Rb;e8.expectFloat32=Sm;e8.expectInt=$5;e8.expectInt32=vb;e8.expectLong=Bf;e8.expectNonNull=z5;e8.expectNumber=qf;e8.expectObject=oN;e8.expectShort=kb;e8.expectString=W5;e8.expectUnion=H5;e8.fromArrayBuffer=Rd;e8.fromBase64=nN;e8.fromHex=CK;e8.fromString=vm;e8.fromUtf8=km;e8.generateIdempotencyToken=ZK;e8.getAwsChunkedEncodingStream=FK;e8.getSerdePlugin=IK;e8.handleFloat=K5;e8.headStream=WK;e8.isArrayBuffer=rN;e8.isBlob=xm;e8.isReadableStream=na;e8.limitedParseDouble=Ib;e8.limitedParseFloat=J5;e8.limitedParseFloat32=Q5;e8.logger=jf;e8.nv=xK;e8.parseBoolean=q5;e8.parseEpochTimestamp=uK;e8.parseRfc3339DateTime=rK;e8.parseRfc3339DateTimeWithOffset=iK;e8.parseRfc7231DateTime=cK;e8.quoteHeader=wK;e8.sdkStreamMixin=JK;e8.serializerMiddleware=gN;e8.serializerMiddlewareOption=wN;e8.splitEvery=RK;e8.splitHeader=NK;e8.splitStream=YK;e8.streamCollector=NN;e8.strictParseByte=uN;e8.strictParseDouble=Ob;e8.strictParseFloat=V5;e8.strictParseFloat32=sN;e8.strictParseInt=Y5;e8.strictParseInt32=X5;e8.strictParseLong=cN;e8.strictParseShort=Nd;e8.toBase64=xb;e8.toHex=hN;e8.toUint8Array=pN;e8.toUtf8=iN;e8.v4=ON});var me=A(function(FJ){var{createReadStream:bJ}=C("fs"),{Writable:EJ}=C("stream"),{toUint8Array:Od,concatBytes:SJ}=z(),{createHash:$f,createHmac:AJ}=C("crypto"),Om=C("zlib");async function LN(e,t,r=1048576){let n=e.size,i=0;while(i<n){let o=e.slice(i,Math.min(n,i+r));t(new Uint8Array(await o.arrayBuffer())),i+=o.size}}var TJ=async function(t,r){let n=new t;return await LN(r,(i)=>{n.update(i)}),n.digest()};class Bb extends EJ{hash;constructor(e,t){super(t);this.hash=e}_write(e,t,r){try{this.hash.update(Od(e))}catch(n){return r(n)}r()}}var vJ=(e,t)=>new Promise((r,n)=>{if(!kJ(t)){n(Error("Unable to calculate hash for non-file streams."));return}let i=bJ(t.path,{start:t.start,end:t.end}),o=new e,s=new Bb(o);i.pipe(s),i.on("error",(a)=>{s.end(),n(a)}),s.on("error",n),s.on("finish",function(){o.digest().then(r).catch(n)})}),kJ=(e)=>typeof e.path==="string",RJ=(e,t)=>{if(t.readableFlowing!==null)throw Error("Unable to calculate hash for flowing readable stream");let r=new e,n=new Bb(r);return t.pipe(n),new Promise((i,o)=>{t.on("error",(s)=>{n.end(),o(s)}),n.on("error",o),n.on("finish",()=>{r.digest().then(i).catch(o)})})};class jb{digestLength=16;state=Uint32Array.from(IN);writeBuffer=new DataView(new ArrayBuffer(64));bufferLength=0;bytesHashed=0;update(e){let t=Od(e),r=0,n=t.byteLength;this.bytesHashed+=n;while(n>0)if(this.writeBuffer.setUint8(this.bufferLength++,t[r++]),--n,this.bufferLength===64)Mb(this.state,this.writeBuffer),this.bufferLength=0}async digest(){let e=Uint32Array.from(this.state),t=new DataView(this.writeBuffer.buffer.slice(0)),r=this.bufferLength,n=this.bytesHashed*8;if(t.setUint8(r++,128),this.bufferLength%64>=56){for(let s=r;s<64;++s)t.setUint8(s,0);Mb(e,t),r=0}for(let s=r;s<56;++s)t.setUint8(s,0);t.setUint32(56,n>>>0,!0),t.setUint32(60,Math.floor(n/4294967296),!0),Mb(e,t);let i=new Uint8Array(16),o=new DataView(i.buffer);for(let s=0;s<4;++s)o.setUint32(s*4,e[s],!0);return i}reset(){this.state.set(IN),this.writeBuffer=new DataView(new ArrayBuffer(64)),this.bufferLength=0,this.bytesHashed=0}}var IN=[1732584193,4023233417,2562383102,271733878],Sc=4294967295,NJ=Uint8Array.of(7,12,17,22,5,9,14,20,4,11,16,23,6,10,15,21),xJ=Array.from({length:64},(e,t)=>Math.abs(Math.sin(t+1))*4294967296>>>0);function Mb(e,t){let r=e[0],n=e[1],i=e[2],o=e[3];for(let s=0;s<64;++s){let a,c;if(s<16)a=n&i|~n&o,c=s;else if(s<32)a=o&n|i&~o,c=(5*s+1)%16;else if(s<48)a=n^i^o,c=(3*s+5)%16;else a=i^(n|~o),c=7*s%16;let u=t.getUint32(c*4,!0),d=o;o=i,i=n;let f=NJ[(s>>4)*4+(s&3)],h=(r+a&Sc)+(u+xJ[s]&Sc)&Sc;n=n+((h<<f|h>>>32-f)>>>0)&Sc,r=d}e[0]=e[0]+r&Sc,e[1]=e[1]+n&Sc,e[2]=e[2]+i&Sc,e[3]=e[3]+o&Sc}var CJ=(()=>{try{return $f("md5"),!0}catch{return!1}})(),MN=CJ?OJ():jb;function OJ(){return class{digestLength=16;hash=$f("md5");update(t){this.hash.update(Od(t))}async digest(){let t=this.hash.copy().digest();return new Uint8Array(t.buffer,t.byteOffset,t.byteLength)}reset(){this.hash=$f("md5")}}}var qN=new Uint32Array(256);for(let e=0;e<256;++e){let t=e;for(let r=0;r<8;++r)t=t&1?3988292384^t>>>1:t>>>1;qN[e]=t>>>0}var qb=4294967295;class $b{digestLength=4;checksum=qb;update(e){for(let t=0;t<e.length;++t)this.checksum=this.checksum>>>8^qN[(this.checksum^e[t])&255]}digestSync(){return(this.checksum^qb)>>>0}async digest(){let e=this.digestSync(),t=new Uint8Array(4);return new DataView(t.buffer).setUint32(0,e,!1),t}reset(){this.checksum=qb}}var DN=typeof Om.crc32==="function"?Om.crc32:void 0,BN=DN?IJ(DN):$b;function IJ(e){return class{digestLength=4;value=0;update(r){this.value=e(r,this.value)}digestSync(){return this.value>>>0}async digest(){let r=new Uint8Array(4);return new DataView(r.buffer).setUint32(0,this.digestSync(),!1),r}reset(){this.value=0}}}var Gi=64,UN=32,DJ=9007199254740991;class Fa{digestLength=UN;state=Int32Array.from(PN);w;buffer=new Uint8Array(64);bufferLength=0;bytesHashed=0;finished=!1;inner;outer;constructor(e){if(e){let t=Fa.normalizeKey(e);this.inner=new Fa,this.outer=new Fa;let{inner:r,outer:n}=this,i=new Uint8Array(Gi*2);for(let o=0;o<Gi;++o)i[o]=54^t[o],i[o+Gi]=92^t[o];r.update(i.subarray(0,Gi)),n.update(i.subarray(Gi))}}update(e){if(this.finished)throw Error("Attempted to update an already finished HMAC.");if(this.inner){this.inner.update(e);return}let t=Od(e),r=0,{byteLength:n}=t;if(this.bytesHashed+=n,this.bytesHashed*8>DJ)throw Error("Cannot hash more than 2^53 - 1 bits");while(n>0)if(this.buffer[this.bufferLength++]=t[r++],n--,this.bufferLength===Gi)this.hashBuffer(),this.bufferLength=0}async digest(){let{inner:e,outer:t}=this;if(e&&t){if(this.finished)throw Error("Attempted to digest an already finished HMAC.");this.finished=!0;let r=e.digestSync();return t.update(r),t.digestSync()}return this.digestSync()}reset(){this.state=Int32Array.from(PN),this.buffer=new Uint8Array(64),this.bufferLength=0,this.bytesHashed=0}digestSync(){let e=this.state.slice(),t=this.buffer.slice(),r=this.bufferLength,n=this.bytesHashed*8,i=new DataView(t.buffer,t.byteOffset,t.byteLength);if(i.setUint8(r++,128),(r-1)%Gi>=Gi-8){for(let s=r;s<Gi;++s)i.setUint8(s,0);this.hashBufferWith(e,t),r=0}for(let s=r;s<Gi-8;++s)i.setUint8(s,0);i.setUint32(Gi-8,Math.floor(n/4294967296),!1),i.setUint32(Gi-4,n,!1),this.hashBufferWith(e,t);let o=new Uint8Array(UN);for(let s=0;s<8;++s)o[s*4]=e[s]>>>24&255,o[s*4+1]=e[s]>>>16&255,o[s*4+2]=e[s]>>>8&255,o[s*4+3]=e[s]>>>0&255;return o}static normalizeKey(e){let t=Od(e);if(t.byteLength>Gi){let r=new Fa;r.update(t);let n=r.digestSync(),i=new Uint8Array(Gi);return i.set(n),i}if(t.byteLength<Gi){let r=new Uint8Array(Gi);return r.set(t),r}return t}hashBuffer(){this.hashBufferWith(this.state,this.buffer)}hashBufferWith(e,t){let r=this.w??=new Int32Array(64),n=e[0],i=e[1],o=e[2],s=e[3],a=e[4],c=e[5],u=e[6],d=e[7];for(let f=0;f<Gi;++f){if(f<16)r[f]=(t[f*4]&255)<<24|(t[f*4+1]&255)<<16|(t[f*4+2]&255)<<8|t[f*4+3]&255;else{let g=r[f-2],_=(g>>>17|g<<15)^(g>>>19|g<<13)^g>>>10;g=r[f-15];let R=(g>>>7|g<<25)^(g>>>18|g<<14)^g>>>3;r[f]=(_+r[f-7]|0)+(R+r[f-16]|0)}let h=(((a>>>6|a<<26)^(a>>>11|a<<21)^(a>>>25|a<<7))+(a&c^~a&u)|0)+(d+(UJ[f]+r[f]|0)|0)|0,p=((n>>>2|n<<30)^(n>>>13|n<<19)^(n>>>22|n<<10))+(n&i^n&o^i&o)|0;d=u,u=c,c=a,a=s+h|0,s=o,o=i,i=n,n=h+p|0}e[0]+=n,e[1]+=i,e[2]+=o,e[3]+=s,e[4]+=a,e[5]+=c,e[6]+=u,e[7]+=d}}var PN=new Int32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),UJ=new Int32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),PJ=(()=>{try{return $f("sha256"),!0}catch{return!1}})(),jN=PJ?LJ():Fa;function LJ(){return class{digestLength=32;secret;hash;isHmac;finished=!1;constructor(t){this.secret=t,this.isHmac=!!t,this.hash=this.createHash()}update(t){if(this.finished)throw Error("Attempted to update an already finished hash.");this.hash.update(t)}async digest(){let t;if(this.isHmac)this.finished=!0,t=this.hash.digest();else t=this.hash.copy().digest();return new Uint8Array(t.buffer,t.byteOffset,t.byteLength)}reset(){this.hash=this.createHash(),this.finished=!1}createHash(){return this.secret?AJ("sha256",MJ(this.secret)):$f("sha256")}}}function MJ(e){if(typeof e==="string")return e;if(ArrayBuffer.isView(e))return Buffer.from(e.buffer,e.byteOffset,e.byteLength);return Buffer.from(e)}var{digest:qJ,sign:BJ,importKey:jJ}=globalThis?.crypto?.subtle??{},Cm=typeof qJ==="function"&&typeof BJ==="function"&&typeof jJ==="function"?globalThis.crypto.subtle:void 0,$J=8388608;class $N{digestLength=32;secret;pending=[];pendingBytes=0;fallback;finished=!1;constructor(e){if(e)this.secret=Od(e)}update(e){if(this.finished)throw Error("Attempted to update an already finished HMAC.");if(this.fallback){this.fallback.update(e);return}if(this.pending.push(e.slice()),this.pendingBytes+=e.byteLength,this.pendingBytes>=$J)this.switchToFallback()}async digest(){if(this.fallback)return this.fallback.digest();if(this.secret&&this.finished)throw Error("Attempted to digest an already finished HMAC.");let e=SJ(this.pending);if(Cm){if(this.secret){this.finished=!0;let n=await Cm.importKey("raw",this.secret,{name:"HMAC",hash:"SHA-256"},!1,["sign"]),i=await Cm.sign("HMAC",n,e);return new Uint8Array(i)}let r=await Cm.digest("SHA-256",e);return new Uint8Array(r)}let t=new Fa(this.secret);return t.update(e),t.digest()}reset(){this.pending=[],this.pendingBytes=0,this.fallback=void 0,this.finished=!1}switchToFallback(){let e=new Fa(this.secret);for(let t of this.pending)e.update(t);this.fallback=e,this.pending=[],this.pendingBytes=0}}FJ.Crc32=BN;FJ.Crc32Js=$b;FJ.Crc32Node=BN;FJ.Md5=MN;FJ.Md5Js=jb;FJ.Md5Node=MN;FJ.Sha256=jN;FJ.Sha256Js=Fa;FJ.Sha256Node=jN;FJ.Sha256WebCrypto=$N;FJ.blobHasher=TJ;FJ.blobReader=LN;FJ.fileStreamHasher=vJ;FJ.readableStreamHasher=RJ});var Jt=A(function(kQ){var{Crc32:HN}=me(),{hasOwn:Im}=Po(),{toHex:Id,fromHex:nQ,toUtf8:iQ,fromUtf8:oQ}=z(),{Readable:sQ}=C("stream"),{TypeRegistry:aQ}=le();class Dd{bytes;constructor(e){if(this.bytes=e,e.byteLength!==8)throw Error("Int64 buffers must be exactly 8 bytes")}static fromNumber(e){if(e>9223372036854776000||e<-9223372036854776000)throw Error(`${e} is too large (or, if negative, too small) to represent as an Int64`);let t=new Uint8Array(8);for(let r=7,n=Math.abs(Math.round(e));r>-1&&n>0;r--,n/=256)t[r]=n;if(e<0)FN(t);return new Dd(t)}valueOf(){let e=this.bytes.slice(0),t=e[0]&128;if(t)FN(e);return parseInt(Id(e),16)*(t?-1:1)}toString(){return String(this.valueOf())}}function FN(e){for(let t=0;t<8;t++)e[t]^=255;for(let t=7;t>-1;t--)if(e[t]++,e[t]!==0)break}class Fb{toUtf8;fromUtf8;constructor(e,t){this.toUtf8=e,this.fromUtf8=t}format(e){let t=[];for(let i in e){if(!Im(e,i))continue;let o=this.fromUtf8(i);t.push(Uint8Array.from([o.byteLength]),o,this.formatHeaderValue(e[i]))}let r=new Uint8Array(t.reduce((i,o)=>i+o.byteLength,0)),n=0;for(let i of t)r.set(i,n),n+=i.byteLength;return r}formatHeaderValue(e){switch(e.type){case"boolean":return Uint8Array.from([e.value?0:1]);case"byte":return Uint8Array.from([2,e.value]);case"short":let t=new DataView(new ArrayBuffer(3));return t.setUint8(0,3),t.setInt16(1,e.value,!1),new Uint8Array(t.buffer);case"integer":let r=new DataView(new ArrayBuffer(5));return r.setUint8(0,4),r.setInt32(1,e.value,!1),new Uint8Array(r.buffer);case"long":let n=new Uint8Array(9);return n[0]=5,n.set(e.value.bytes,1),n;case"binary":let i=new DataView(new ArrayBuffer(3+e.value.byteLength));i.setUint8(0,6),i.setUint16(1,e.value.byteLength,!1);let o=new Uint8Array(i.buffer);return o.set(e.value,3),o;case"string":let s=this.fromUtf8(e.value),a=new DataView(new ArrayBuffer(3+s.byteLength));a.setUint8(0,7),a.setUint16(1,s.byteLength,!1);let c=new Uint8Array(a.buffer);return c.set(s,3),c;case"timestamp":let u=new Uint8Array(9);return u[0]=8,u.set(Dd.fromNumber(e.value.valueOf()).bytes,1),u;case"uuid":if(!gQ.test(e.value))throw Error(`Invalid UUID received: ${e.value}`);let d=new Uint8Array(17);return d[0]=9,d.set(nQ(e.value.replace(/-/g,"")),1),d}}parse(e){let t={},r=0;while(r<e.byteLength){let n=e.getUint8(r++),i=this.toUtf8(new Uint8Array(e.buffer,e.byteOffset+r,n));switch(r+=n,e.getUint8(r++)){case 0:t[i]={type:WN,value:!0};break;case 1:t[i]={type:WN,value:!1};break;case 2:t[i]={type:cQ,value:e.getInt8(r++)};break;case 3:t[i]={type:uQ,value:e.getInt16(r,!1)},r+=2;break;case 4:t[i]={type:dQ,value:e.getInt32(r,!1)},r+=4;break;case 5:t[i]={type:lQ,value:new Dd(new Uint8Array(e.buffer,e.byteOffset+r,8))},r+=8;break;case 6:let o=e.getUint16(r,!1);r+=2,t[i]={type:fQ,value:new Uint8Array(e.buffer,e.byteOffset+r,o)},r+=o;break;case 7:let s=e.getUint16(r,!1);r+=2,t[i]={type:hQ,value:this.toUtf8(new Uint8Array(e.buffer,e.byteOffset+r,s))},r+=s;break;case 8:t[i]={type:pQ,value:new Date(new Dd(new Uint8Array(e.buffer,e.byteOffset+r,8)).valueOf())},r+=8;break;case 9:let a=new Uint8Array(e.buffer,e.byteOffset+r,16);r+=16,t[i]={type:mQ,value:`${Id(a.subarray(0,4))}-${Id(a.subarray(4,6))}-${Id(a.subarray(6,8))}-${Id(a.subarray(8,10))}-${Id(a.subarray(10))}`};break;default:throw Error("Unrecognized header type tag")}}return t}}var zN;(function(e){e[e.boolTrue=0]="boolTrue",e[e.boolFalse=1]="boolFalse",e[e.byte=2]="byte",e[e.short=3]="short",e[e.integer=4]="integer",e[e.long=5]="long",e[e.byteArray=6]="byteArray",e[e.string=7]="string",e[e.timestamp=8]="timestamp",e[e.uuid=9]="uuid"})(zN||(zN={}));var WN="boolean",cQ="byte",uQ="short",dQ="integer",lQ="long",fQ="binary",hQ="string",pQ="timestamp",mQ="uuid",gQ=/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/,VN=4,Ac=VN*2,Iu=4,yQ=Ac+Iu*2;function wQ({byteLength:e,byteOffset:t,buffer:r}){if(e<yQ)throw Error("Provided message too short to accommodate event stream message overhead");let n=new DataView(r,t,e),i=n.getUint32(0,!1);if(e!==i)throw Error("Reported message length does not match received message length");let o=n.getUint32(VN,!1),s=n.getUint32(Ac,!1),a=n.getUint32(e-Iu,!1),c=new HN;if(c.update(new Uint8Array(r,t,Ac)),s!==c.digestSync())throw Error(`The prelude checksum specified in the message (${s}) does not match the calculated CRC32 checksum (${c.digestSync()})`);if(c.update(new Uint8Array(r,t+Ac,e-(Ac+Iu))),a!==c.digestSync())throw Error(`The message checksum (${c.digestSync()}) did not match the expected value of ${a}`);return{headers:new DataView(r,t+Ac+Iu,o),body:new Uint8Array(r,t+Ac+Iu+o,i-o-(Ac+Iu+Iu))}}class zb{headerMarshaller;messageBuffer;isEndOfStream;constructor(e,t){this.headerMarshaller=new Fb(e,t),this.messageBuffer=[],this.isEndOfStream=!1}feed(e){this.messageBuffer.push(this.decode(e))}endOfStream(){this.isEndOfStream=!0}getMessage(){let e=this.messageBuffer.pop(),t=this.isEndOfStream;return{getMessage(){return e},isEndOfStream(){return t}}}getAvailableMessages(){let e=this.messageBuffer;this.messageBuffer=[];let t=this.isEndOfStream;return{getMessages(){return e},isEndOfStream(){return t}}}encode({headers:e,body:t}){let r=this.headerMarshaller.format(e),n=r.byteLength+t.byteLength+16,i=new Uint8Array(n),o=new DataView(i.buffer,i.byteOffset,i.byteLength),s=new HN;return o.setUint32(0,n,!1),o.setUint32(4,r.byteLength,!1),s.update(i.subarray(0,8)),o.setUint32(8,s.digestSync(),!1),i.set(r,12),i.set(t,r.byteLength+12),s.update(i.subarray(8,n-4)),o.setUint32(n-4,s.digestSync(),!1),i}decode(e){let{headers:t,body:r}=wQ(e);return{headers:this.headerMarshaller.parse(t),body:r}}formatHeaders(e){return this.headerMarshaller.format(e)}}class Wb{options;constructor(e){this.options=e}[Symbol.asyncIterator](){return this.asyncIterator()}async*asyncIterator(){for await(let e of this.options.inputStream)yield this.options.decoder.decode(e)}}class Hb{options;constructor(e){this.options=e}[Symbol.asyncIterator](){return this.asyncIterator()}async*asyncIterator(){for await(let e of this.options.messageStream)yield this.options.encoder.encode(e);if(this.options.includeEndFrame)yield new Uint8Array(0)}}class Vb{options;constructor(e){this.options=e}[Symbol.asyncIterator](){return this.asyncIterator()}async*asyncIterator(){for await(let e of this.options.messageStream){let t=await this.options.deserializer(e);if(t===void 0)continue;yield t}}}class Gb{options;constructor(e){this.options=e}[Symbol.asyncIterator](){return this.asyncIterator()}async*asyncIterator(){for await(let e of this.options.inputStream)yield this.options.serializer(e)}}function GN(e){let t=0,r=0,n=null,i=null,o=(a)=>{if(typeof a!=="number")throw Error("Attempted to allocate an event message where size was not a number: "+a);t=a,r=4,n=new Uint8Array(a),new DataView(n.buffer).setUint32(0,a,!1)},s=async function*(){let a=e[Symbol.asyncIterator]();while(!0){let{value:c,done:u}=await a.next();if(u){if(!t)return;else if(t===r)yield n;else throw Error("Truncated event message received.");return}let d=c.length,f=0;while(f<d){if(!n){let p=d-f;if(!i)i=new Uint8Array(4);let g=Math.min(4-r,p);if(i.set(c.slice(f,f+g),r),r+=g,f+=g,r<4)break;o(new DataView(i.buffer).getUint32(0,!1)),i=null}let h=Math.min(t-r,d-f);if(n.set(c.slice(f,f+h),r),r+=h,f+=h,t&&t===r)yield n,n=null,t=0,r=0}}};return{[Symbol.asyncIterator]:s}}function _Q(e,t){let r=Kb(t.deserializer,t.toUtf8);return{[Symbol.asyncIterator]:async function*(){for await(let n of e){let i=t.eventStreamCodec.decode(n),o=await r(i);if(o===void 0)continue;yield o}}}}function Kb(e,t){return async function(r){let{value:n}=r.headers[":message-type"];if(n==="error"){let i=Error(r.headers[":error-message"].value||"UnknownError");throw i.name=r.headers[":error-code"].value,i}else if(n==="exception"){let i=r.headers[":exception-type"].value,o={[i]:r},s=await e(o);if(s.$unknown){let a=Error(t(r.body));throw a.name=i,a}throw s[i]}else if(n==="event"){let i={[r.headers[":event-type"].value]:r},o=await e(i);if(o.$unknown)return;return o}else throw Error(`Unrecognizable event type: ${r.headers[":event-type"].value}`)}}var Jb=class{eventStreamCodec;utfEncoder;constructor({utf8Encoder:t,utf8Decoder:r}){this.eventStreamCodec=new zb(t,r),this.utfEncoder=t}deserialize(t,r){let n=GN(t);return new Vb({messageStream:new Wb({inputStream:n,decoder:this.eventStreamCodec}),deserializer:Kb(r,this.utfEncoder)})}serialize(t,r){return new Hb({messageStream:new Gb({inputStream:t,serializer:r}),encoder:this.eventStreamCodec,includeEndFrame:!0})}},bQ=(e)=>new Jb(e);class Qb{universalMarshaller;constructor({utf8Encoder:e,utf8Decoder:t}){this.universalMarshaller=new Jb({utf8Decoder:t,utf8Encoder:e})}deserialize(e,t){let r=typeof e[Symbol.asyncIterator]==="function"?e:SQ(e);return this.universalMarshaller.deserialize(r,t)}serialize(e,t){return sQ.from(this.universalMarshaller.serialize(e,t))}}var EQ=(e)=>new Qb(e);async function*SQ(e){let t=!1,r=!1,n=[];e.on("error",(i)=>{if(!t)t=!0;if(i)throw i}),e.on("data",(i)=>{n.push(i)}),e.on("end",()=>{t=!0});while(!r){let i=await new Promise((o)=>setTimeout(()=>o(n.shift()),0));if(i)yield i;r=t&&n.length===0}}var AQ=(e)=>({[Symbol.asyncIterator]:async function*(){let t=e.getReader();try{while(!0){let{done:r,value:n}=await t.read();if(r)return;yield n}}finally{t.releaseLock()}}}),TQ=(e)=>{let t=e[Symbol.asyncIterator]();return new ReadableStream({async pull(r){let{done:n,value:i}=await t.next();if(n)return r.close();r.enqueue(i)}})},vQ=(e)=>Object.assign(e,{eventStreamMarshaller:e.eventStreamSerdeProvider(e)});class KN{marshaller;serializer;deserializer;serdeContext;defaultContentType;compositeErrorRegistry;constructor({marshaller:e,serializer:t,deserializer:r,serdeContext:n,defaultContentType:i,compositeErrorRegistry:o}){this.marshaller=e,this.serializer=t,this.deserializer=r,this.serdeContext=n,this.defaultContentType=i,this.compositeErrorRegistry=o}async serializeEventStream({eventStream:e,requestSchema:t,initialRequest:r,initialMessageType:n}){let i=this.marshaller,o=t.getEventStreamMember(),s=t.getMemberSchema(o),a=this.serializer,c=this.defaultContentType,u=Symbol("initialRequestMarker"),d={async*[Symbol.asyncIterator](){if(r){let f={":event-type":{type:"string",value:n??"initial-request"},":message-type":{type:"string",value:"event"},":content-type":{type:"string",value:c}};a.write(t,r);let h=a.flush();yield{[u]:!0,headers:f,body:h}}for await(let f of e)yield f}};return i.serialize(d,(f)=>{if(f[u])return{headers:f.headers,body:f.body};let h="";for(let I in f){if(!Im(f,I))continue;if(I!=="__type"){h=I;break}}let{additionalHeaders:p,body:g,eventType:_,explicitPayloadContentType:R}=this.writeEventBody(h,s,f);return{headers:{":event-type":{type:"string",value:_},":message-type":{type:"string",value:"event"},":content-type":{type:"string",value:R??c},...p},body:g}})}async deserializeEventStream({response:e,responseSchema:t,initialResponseContainer:r,initialMessageType:n}){let i=this.marshaller,o=t.getEventStreamMember(),a=t.getMemberSchema(o).getMemberSchemas(),c=Symbol("initialResponseMarker"),u=i.deserialize(e.body,async(h)=>{let p="";for(let _ in h){if(!Im(h,_))continue;if(_!=="__type"){p=_;break}}let g=h[p].body;if(p===(n??"initial-response")){let _=await this.deserializer.read(t,g);return delete _[o],{[c]:!0,..._}}else if(p in a){let _=a[p];if(_.isStructSchema()){let R={},O=!1;for(let[I,Ne]of _.structIterator()){let{eventHeader:k,eventPayload:j}=Ne.getMergedTraits();if(O=O||Boolean(k||j),j){if(Ne.isBlobSchema())R[I]=g;else if(Ne.isStringSchema())R[I]=(this.serdeContext?.utf8Encoder??iQ)(g);else if(Ne.isStructSchema())R[I]=await this.deserializer.read(Ne,g)}else if(k){let re=h[p].headers[I]?.value;if(re!=null)if(Ne.isNumericSchema())if(re&&typeof re==="object"&&"bytes"in re)R[I]=BigInt(re.toString());else R[I]=Number(re);else R[I]=re}}return{[p]:await this.readEventMember(_,g,O,R)}}return{[p]:await this.deserializer.read(_,g)}}else return{$unknown:h}}),d=u[Symbol.asyncIterator](),f=await d.next();if(f.done)return u;if(f.value?.[c]){if(!t)throw Error("@smithy::core/protocols - initial-response event encountered in event stream but no response schema given.");for(let h in f.value){if(!Im(f.value,h))continue;r[h]=f.value[h]}}return{async*[Symbol.asyncIterator](){if(!f?.value?.[c])yield f.value;while(!0){let{done:h,value:p}=await d.next();if(h)break;yield p}}}}async readEventMember(e,t,r,n){let i,o=e.getSchema();if(Array.isArray(o)&&o[0]===-3){let a=o[1],c=aQ.for(a);this.compositeErrorRegistry?.copyFrom(c),i=(this.compositeErrorRegistry??c)?.getErrorCtor(o)}let s=r?n:t.byteLength===0?{}:await this.deserializer.read(e,t);if(i){let a=s.message??s.Message??"Unknown",c={},u=e.getMergedTraits().error;if(u)c.$fault=u;return Object.assign(new i({}),c,{message:a},s)}return s}writeEventBody(e,t,r){let n=this.serializer,i=e,o=null,s,a=(()=>t.getSchema()[4].includes(e))(),c={};if(!a){let[f,h]=r[e];i=f,n.write(15,h)}else{let f=t.getMemberSchema(e);if(f.isStructSchema()){for(let[h,p]of f.structIterator()){let{eventHeader:g,eventPayload:_}=p.getMergedTraits();if(_)o=h;else if(g){let R=r[e][h],O="binary";if(p.isNumericSchema())if(-2147483648<=R&&R<=2147483647)O="integer";else O="long";else if(p.isTimestampSchema())O="timestamp";else if(p.isStringSchema())O="string";else if(p.isBooleanSchema())O="boolean";if(R!=null)c[h]={type:O,value:R},delete r[e][h]}}if(o!==null){let h=f.getMemberSchema(o);if(h.isBlobSchema())s="application/octet-stream";else if(h.isStringSchema())s="text/plain";n.write(h,r[e][o])}else n.write(f,r[e])}else if(f.isUnitSchema())n.write(f,{});else throw Error("@smithy/core/event-streams - non-struct member not supported in event stream union.")}let u=n.flush()??new Uint8Array;return{body:typeof u==="string"?(this.serdeContext?.utf8Decoder??oQ)(u):u,eventType:i,explicitPayloadContentType:s,additionalHeaders:c}}}kQ.EventStreamCodec=zb;kQ.EventStreamMarshaller=Qb;kQ.EventStreamSerde=KN;kQ.HeaderMarshaller=Fb;kQ.Int64=Dd;kQ.MessageDecoderStream=Wb;kQ.MessageEncoderStream=Hb;kQ.SmithyMessageDecoderStream=Vb;kQ.SmithyMessageEncoderStream=Gb;kQ.UniversalEventStreamMarshaller=Jb;kQ.eventStreamSerdeProvider=EQ;kQ.getChunkedStream=GN;kQ.getMessageUnmarshaller=Kb;kQ.getUnmarshalledStream=_Q;kQ.iterableToReadableStream=TQ;kQ.readableStreamToIterable=AQ;kQ.resolveEventStreamSerdeConfig=vQ;kQ.universalEventStreamSerdeProvider=bQ});var L=A(function(f9){var{Uint8ArrayBlobAdapter:Yb,sdkStreamMixin:HQ,splitEvery:VQ,splitHeader:XN,fromBase64:JN,_parseEpochTimestamp:GQ,_parseRfc7231DateTime:KQ,_parseRfc3339DateTimeWithOffset:JQ,LazyJsonString:ZN,NumericValue:QQ,toUtf8:ex,fromUtf8:YQ,generateIdempotencyToken:XQ,toBase64:QN,dateToUtcString:ZQ,quoteHeader:e9}=z(),{HttpRequest:Ud,HttpResponse:tx,hasOwn:Du,isValidHostname:rx}=Po(),{parseQueryString:t9,parseUrl:r9}=Po();f9.HttpRequest=Ud;f9.HttpResponse=tx;f9.isValidHostname=rx;f9.parseQueryString=t9;f9.parseUrl=r9;var{TypeRegistry:n9,NormalizedSchema:ia,translateTraits:nx}=le(),{FieldPosition:i9}=Nu(),Uu=async(e=new Uint8Array,t)=>{if(e instanceof Uint8Array)return Yb.mutate(e);if(!e)return Yb.mutate(new Uint8Array);let r=t.streamCollector(e);return Yb.mutate(await r)};function zf(e){return encodeURIComponent(e).replace(/[!'()*]/g,function(t){return"%"+t.charCodeAt(0).toString(16).toUpperCase()})}class Pd{serdeContext;setSerdeContext(e){this.serdeContext=e}}class Dm extends Pd{options;compositeErrorRegistry;constructor(e){super();this.options=e,this.compositeErrorRegistry=n9.for(e.defaultNamespace);for(let t of e.errorTypeRegistries??[])this.compositeErrorRegistry.copyFrom(t)}getRequestType(){return Ud}getResponseType(){return tx}setSerdeContext(e){if(this.serdeContext=e,this.serializer.setSerdeContext(e),this.deserializer.setSerdeContext(e),this.getPayloadCodec())this.getPayloadCodec().setSerdeContext(e)}updateServiceEndpoint(e,t){if("url"in t){if(e.protocol=t.url.protocol,e.hostname=t.url.hostname,e.port=t.url.port?Number(t.url.port):void 0,e.path=t.url.pathname,e.fragment=t.url.hash||void 0,e.username=t.url.username||void 0,e.password=t.url.password||void 0,!e.query)e.query={};for(let[r,n]of t.url.searchParams.entries())e.query[r]=n;if(t.headers)for(let r in t.headers){if(!Du(t.headers,r))continue;e.headers[r]=t.headers[r].join(", ")}return e}else{if(e.protocol=t.protocol,e.hostname=t.hostname,e.port=t.port?Number(t.port):void 0,e.path=t.path,e.query={...t.query},t.headers)for(let r in t.headers){if(!Du(t.headers,r))continue;e.headers[r]=t.headers[r]}return e}}setHostPrefix(e,t,r){if(this.serdeContext?.disableHostPrefix)return;let n=ia.of(t.input),i=nx(t.traits??{});if(i.endpoint){let o=i.endpoint?.[0];if(typeof o==="string"){for(let[s,a]of n.structIterator()){if(!a.getMergedTraits().hostLabel)continue;let c=r[s];if(typeof c!=="string")throw Error(`@smithy/core/schema - ${s} in input must be a string as hostLabel.`);o=o.replace(`{${s}}`,c)}if(e.hostname=o+e.hostname,!rx(e.hostname))throw Error(`[${e.hostname}] is not a valid hostname.`)}}}deserializeMetadata(e){return{httpStatusCode:e.statusCode,requestId:e.headers["x-amzn-requestid"]??e.headers["x-amzn-request-id"]??e.headers["x-amz-request-id"],extendedRequestId:e.headers["x-amz-id-2"],cfId:e.headers["x-amz-cf-id"]}}async serializeEventStream({eventStream:e,requestSchema:t,initialRequest:r}){return(await this.loadEventStreamCapability()).serializeEventStream({eventStream:e,requestSchema:t,initialRequest:r})}async deserializeEventStream({response:e,responseSchema:t,initialResponseContainer:r}){return(await this.loadEventStreamCapability()).deserializeEventStream({response:e,responseSchema:t,initialResponseContainer:r})}async loadEventStreamCapability(){let{EventStreamSerde:e,eventStreamSerdeProvider:t}=Jt(),r=this.resolveEventStreamMarshaller(t);return new e({marshaller:r,serializer:this.serializer,deserializer:this.deserializer,serdeContext:this.serdeContext,defaultContentType:this.getDefaultContentType(),compositeErrorRegistry:this.compositeErrorRegistry})}resolveEventStreamMarshaller(e){let t=this.serdeContext;if(t.eventStreamMarshaller)return t.eventStreamMarshaller;return e(this.serdeContext)}getDefaultContentType(){throw Error(`@smithy/core/protocols - ${this.constructor.name} getDefaultContentType() implementation missing.`)}async deserializeHttpMessage(e,t,r,n,i){return[]}getEventStreamMarshaller(){let e=this.serdeContext;if(!e.eventStreamMarshaller)throw Error("@smithy/core - HttpProtocol: eventStreamMarshaller missing in serdeContext.");return e.eventStreamMarshaller}}class ix extends Dm{async serializeRequest(e,t,r){let n=t&&typeof t==="object"?t:{},i=this.serializer,o={},s={},a=await r.endpoint(),c=ia.of(e?.input),u=[],d=[],f=!1,h,p=new Ud({protocol:"",hostname:"",port:void 0,path:"",fragment:void 0,query:o,headers:s,body:void 0});if(a){this.updateServiceEndpoint(p,a),this.setHostPrefix(p,e,n);let g=nx(e.traits);if(g.http){p.method=g.http[0];let[_,R]=g.http[1].split("?");if(p.path=="/")p.path=_;else p.path+=_;let O=new URLSearchParams(R??"");for(let[I,Ne]of O)o[I]=Ne}}for(let[g,_]of c.structIterator()){let R=_.getMergedTraits()??{},O=n[g];if(O==null&&!_.isIdempotencyToken()){if(R.httpLabel){if(p.path.includes(`{${g}+}`)||p.path.includes(`{${g}}`))throw Error(`No value provided for input HTTP label: ${g}.`)}continue}if(R.httpPayload)if(_.isStreaming())if(_.isStructSchema()){if(n[g])h=await this.serializeEventStream({eventStream:n[g],requestSchema:c})}else h=O;else i.write(_,O),h=i.flush();else if(R.httpLabel){i.write(_,O);let I=i.flush();if(p.path.includes(`{${g}+}`))p.path=p.path.replace(`{${g}+}`,I.split("/").map(zf).join("/"));else if(p.path.includes(`{${g}}`))p.path=p.path.replace(`{${g}}`,zf(I))}else if(R.httpHeader)i.write(_,O),s[R.httpHeader.toLowerCase()]=String(i.flush());else if(typeof R.httpPrefixHeaders==="string")for(let I in O){if(!Du(O,I))continue;let Ne=O[I],k=R.httpPrefixHeaders+I;i.write([_.getValueSchema(),{httpHeader:k}],Ne),s[k.toLowerCase()]=i.flush()}else if(R.httpQuery||R.httpQueryParams)this.serializeQuery(_,O,o);else f=!0,u.push(g),d.push(_)}if(f&&n){let[g,_]=(c.getName(!0)??"#Unknown").split("#"),R=c.getSchema()[6],O=[3,g,_,c.getMergedTraits(),u,d,void 0];if(R)O[6]=R;else O.pop();i.write(O,n),h=i.flush()}return p.headers=s,p.query=o,p.body=h,p}serializeQuery(e,t,r){let n=this.serializer,i=e.getMergedTraits();if(i.httpQueryParams){for(let o in t){if(!Du(t,o))continue;if(!(o in r)){let s=t[o],a=e.getValueSchema();Object.assign(a.getMergedTraits(),{...i,httpQuery:o,httpQueryParams:void 0}),this.serializeQuery(a,s,r)}}return}if(e.isListSchema()){let o=!!e.getMergedTraits().sparse,s=[];for(let a of t){n.write([e.getValueSchema(),i],a);let c=n.flush();if(o||c!==void 0)s.push(c)}r[i.httpQuery]=s}else n.write([e,i],t),r[i.httpQuery]=n.flush()}async deserializeResponse(e,t,r){let n=this.deserializer,i=ia.of(e.output),o={};if(r.statusCode>=300){let a=await Uu(r.body,t);if(a.byteLength>0)Object.assign(o,await n.read(15,a));throw await this.handleError(e,t,r,o,this.deserializeMetadata(r)),Error("@smithy/core/protocols - HTTP Protocol error handler failed to throw.")}for(let a in r.headers){if(!Du(r.headers,a))continue;let c=r.headers[a];delete r.headers[a],r.headers[a.toLowerCase()]=c}let s=await this.deserializeHttpMessage(i,t,r,o);if(s.length){let a=await Uu(r.body,t);if(a.byteLength>0){let c=await n.read(i,a);for(let u of s)if(c[u]!=null)o[u]=c[u]}}else if(s.discardResponseBody)await Uu(r.body,t);return o.$metadata=this.deserializeMetadata(r),o}async deserializeHttpMessage(e,t,r,n,i){let o;if(n instanceof Set)o=i;else o=n;let s=!0,a=this.deserializer,c=ia.of(e),u=[];for(let[d,f]of c.structIterator()){let h=f.getMemberTraits();if(h.httpPayload){if(s=!1,f.isStreaming())if(f.isStructSchema())o[d]=await this.deserializeEventStream({response:r,responseSchema:c});else o[d]=HQ(r.body);else if(r.body){let g=await Uu(r.body,t);if(g.byteLength>0)o[d]=await a.read(f,g)}}else if(h.httpHeader){let p=String(h.httpHeader).toLowerCase(),g=r.headers[p];if(g!=null)if(f.isListSchema()){let _=f.getValueSchema();_.getMergedTraits().httpHeader=p;let R;if(_.isTimestampSchema()&&_.getSchema()===4)R=VQ(g,",",2);else R=XN(g);let O=[];for(let I of R)O.push(await a.read(_,I.trim()));o[d]=O}else o[d]=await a.read(f,g)}else if(h.httpPrefixHeaders!==void 0){o[d]={};for(let p in r.headers){if(!Du(r.headers,p))continue;if(p.startsWith(h.httpPrefixHeaders)){let g=r.headers[p],_=f.getValueSchema();_.getMergedTraits().httpHeader=p,o[d][p.slice(h.httpPrefixHeaders.length)]=await a.read(_,g)}}}else if(h.httpResponseCode)o[d]=r.statusCode;else u.push(d)}return u.discardResponseBody=s,u}}class ox extends Dm{async serializeRequest(e,t,r){let n=this.serializer,i={},o={},s=await r.endpoint(),a=ia.of(e?.input),c=a.getSchema(),u,d=t&&typeof t==="object"?t:{},f=new Ud({protocol:"",hostname:"",port:void 0,path:"/",fragment:void 0,query:i,headers:o,body:void 0});if(s)this.updateServiceEndpoint(f,s),this.setHostPrefix(f,e,d);if(d){let h=a.getEventStreamMember();if(h){if(d[h]){let p={};for(let[g]of a.structIterator())if(g!==h&&d[g]!=null)p[g]=d[g];u=await this.serializeEventStream({eventStream:d[h],requestSchema:a,initialRequest:p})}}else n.write(c,d),u=n.flush()}return f.headers=Object.assign(f.headers,o),f.query=i,f.body=u,f.method="POST",f}async deserializeResponse(e,t,r){let n=this.deserializer,i=ia.of(e.output),o={};if(r.statusCode>=300){let a=await Uu(r.body,t);if(a.byteLength>0)Object.assign(o,await n.read(15,a));throw await this.handleError(e,t,r,o,this.deserializeMetadata(r)),Error("@smithy/core/protocols - RPC Protocol error handler failed to throw.")}for(let a in r.headers){if(!Du(r.headers,a))continue;let c=r.headers[a];delete r.headers[a],r.headers[a.toLowerCase()]=c}let s=i.getEventStreamMember();if(s)o[s]=await this.deserializeEventStream({response:r,responseSchema:i,initialResponseContainer:o});else{let a=await Uu(r.body,t);if(a.byteLength>0)Object.assign(o,await n.read(i,a))}return o.$metadata=this.deserializeMetadata(r),o}}var sx=(e,t,r,n,i,o)=>{if(t!=null&&t[r]!==void 0){let s=n();if(s==null||s.length<=0)throw Error("Empty value provided for input HTTP label: "+r+".");e=e.replace(i,o?s.split("/").map((a)=>zf(a)).join("/"):zf(s))}else throw Error("No value provided for input HTTP label: "+r+".");return e};function o9(e,t){return new Xb(e,t)}class Xb{input;context;query={};method="";headers={};path="";body=null;hostname="";resolvePathStack=[];constructor(e,t){this.input=e,this.context=t}async build(){let{hostname:e,protocol:t="https",port:r,path:n}=await this.context.endpoint();this.path=n;for(let i of this.resolvePathStack)i(this.path);return new Ud({protocol:t,hostname:this.hostname||e,port:r,method:this.method,path:this.path,query:this.query,body:this.body,headers:this.headers})}hn(e){return this.hostname=e,this}bp(e){return this.resolvePathStack.push((t)=>{this.path=`${t?.endsWith("/")?t.slice(0,-1):t||""}`+e}),this}p(e,t,r,n){return this.resolvePathStack.push((i)=>{this.path=sx(i,this.input,e,t,r,n)}),this}h(e){return this.headers=e,this}q(e){return this.query=e,this}b(e){return this.body=e,this}m(e){return this.method=e,this}}function Zb(e,t){if(t.timestampFormat.useTrait){if(e.isTimestampSchema()&&(e.getSchema()===5||e.getSchema()===6||e.getSchema()===7))return e.getSchema()}let{httpLabel:r,httpPrefixHeaders:n,httpHeader:i,httpQuery:o}=e.getMergedTraits();return(t.httpBindings?typeof n==="string"||Boolean(i)?6:Boolean(o)||Boolean(r)?5:void 0:void 0)??t.timestampFormat.default}class eE extends Pd{settings;constructor(e){super();this.settings=e}read(e,t){let r=ia.of(e);if(r.isListSchema())return XN(t).map((n)=>this.read(r.getValueSchema(),n));if(r.isBlobSchema())return(this.serdeContext?.base64Decoder??JN)(t);if(r.isTimestampSchema())switch(Zb(r,this.settings)){case 5:return JQ(t);case 6:return KQ(t);case 7:return GQ(t);default:return console.warn("Missing timestamp format, parsing value with Date constructor:",t),new Date(t)}if(r.isStringSchema()){let n=r.getMergedTraits().mediaType,i=t;if(n){if(r.getMergedTraits().httpHeader)i=this.base64ToUtf8(i);if(n==="application/json"||n.endsWith("+json"))i=ZN.from(i);return i}}if(r.isNumericSchema())return Number(t);if(r.isBigIntegerSchema())return BigInt(t);if(r.isBigDecimalSchema())return new QQ(t,"bigDecimal");if(r.isBooleanSchema())return String(t).toLowerCase()==="true";return t}base64ToUtf8(e){return(this.serdeContext?.utf8Encoder??ex)((this.serdeContext?.base64Decoder??JN)(e))}}class ax extends Pd{codecDeserializer;stringDeserializer;constructor(e,t){super();this.codecDeserializer=e,this.stringDeserializer=new eE(t)}setSerdeContext(e){this.stringDeserializer.setSerdeContext(e),this.codecDeserializer.setSerdeContext(e),this.serdeContext=e}read(e,t){let r=ia.of(e),n=r.getMergedTraits(),i=this.serdeContext?.utf8Encoder??ex;if(n.httpHeader||n.httpResponseCode)return this.stringDeserializer.read(r,i(t));if(n.httpPayload){if(r.isBlobSchema()){let o=this.serdeContext?.utf8Decoder??YQ;if(typeof t==="string")return o(t);return t}else if(r.isStringSchema()){if("byteLength"in t)return i(t);return t}}return this.codecDeserializer.read(r,t)}}class tE extends Pd{settings;stringBuffer="";constructor(e){super();this.settings=e}write(e,t){let r=ia.of(e);switch(typeof t){case"object":if(t===null){this.stringBuffer="null";return}if(r.isTimestampSchema()){if(!(t instanceof Date))throw Error(`@smithy/core/protocols - received non-Date value ${t} when schema expected Date in ${r.getName(!0)}`);switch(Zb(r,this.settings)){case 5:this.stringBuffer=t.toISOString().replace(".000Z","Z");break;case 6:this.stringBuffer=ZQ(t);break;case 7:this.stringBuffer=String(t.getTime()/1000);break;default:console.warn("Missing timestamp format, using epoch seconds",t),this.stringBuffer=String(t.getTime()/1000)}return}if(r.isBlobSchema()&&"byteLength"in t){this.stringBuffer=(this.serdeContext?.base64Encoder??QN)(t);return}if(r.isListSchema()&&Array.isArray(t)){let o="";for(let s of t){this.write([r.getValueSchema(),r.getMergedTraits()],s);let a=this.flush(),c=r.getValueSchema().isTimestampSchema()?a:e9(a);if(o!=="")o+=", ";o+=c}this.stringBuffer=o;return}this.stringBuffer=JSON.stringify(t,null,2);break;case"string":let n=r.getMergedTraits().mediaType,i=t;if(n){if(n==="application/json"||n.endsWith("+json"))i=ZN.from(i);if(r.getMergedTraits().httpHeader){this.stringBuffer=(this.serdeContext?.base64Encoder??QN)(i.toString());return}}this.stringBuffer=t;break;default:if(r.isIdempotencyToken())this.stringBuffer=XQ();else this.stringBuffer=String(t)}}flush(){let e=this.stringBuffer;return this.stringBuffer="",e}}class cx{codecSerializer;stringSerializer;buffer;constructor(e,t,r=new tE(t)){this.codecSerializer=e,this.stringSerializer=r}setSerdeContext(e){this.codecSerializer.setSerdeContext(e),this.stringSerializer.setSerdeContext(e)}write(e,t){let r=ia.of(e),n=r.getMergedTraits();if(n.httpHeader||n.httpLabel||n.httpQuery){this.stringSerializer.write(r,t),this.buffer=this.stringSerializer.flush();return}return this.codecSerializer.write(r,t)}flush(){if(this.buffer!==void 0){let e=this.buffer;return this.buffer=void 0,e}return this.codecSerializer.flush()}}class ux{name;kind;values;constructor({name:e,kind:t=i9.HEADER,values:r=[]}){this.name=e,this.kind=t,this.values=r}add(e){this.values.push(e)}set(e){this.values=e}remove(e){this.values=this.values.filter((t)=>t!==e)}toString(){return this.values.map((e)=>e.includes(",")||e.includes(" ")?`"${e}"`:e).join(", ")}get(){return this.values}}class dx{entries={};encoding;constructor({fields:e=[],encoding:t="utf-8"}){e.forEach(this.setField.bind(this)),this.encoding=t}setField(e){this.entries[e.name.toLowerCase()]=e}getField(e){return this.entries[e.toLowerCase()]}removeField(e){delete this.entries[e.toLowerCase()]}getByType(e){return Object.values(this.entries).filter((t)=>t.kind===e)}}var s9=(e)=>{if(e.logger&&e.logger.constructor?.name!=="NoOpLogger")e.requestHandler?.updateHttpClientConfig?.(Symbol.for("logger"),e.logger);return{setHttpHandler(t){e.requestHandler=t},httpHandler(){return e.requestHandler},updateHttpClientConfig(t,r){e.requestHandler?.updateHttpClientConfig(t,r)},httpHandlerConfigs(){return e.requestHandler.httpHandlerConfigs()}}},a9=(e)=>({requestHandler:e.httpHandler()}),YN="content-length";function lx(e){return(t)=>async(r)=>{let n=r.request;if(Ud.isInstance(n)){let{body:i,headers:o}=n;if(i&&Object.keys(o).map((s)=>s.toLowerCase()).indexOf(YN)===-1)try{let s=e(i);if(s!=null)n.headers={...n.headers,[YN]:String(s)}}catch(s){}}return t({...r,request:n})}}var fx={step:"build",tags:["SET_CONTENT_LENGTH","CONTENT_LENGTH"],name:"contentLengthMiddleware",override:!0},c9=(e)=>({applyToStack:(t)=>{t.add(lx(e.bodyLengthChecker),fx)}}),Ff=(e)=>encodeURIComponent(e).replace(/[!'()*]/g,u9),u9=(e)=>`%${e.charCodeAt(0).toString(16).toUpperCase()}`,d9=(e)=>e.split("/").map(Ff).join("/");function l9(e){let t=[];for(let r of Object.keys(e).sort()){let n=e[r];if(r=Ff(r),Array.isArray(n))for(let i=0,o=n.length;i<o;i++)t.push(`${r}=${Ff(n[i])}`);else{let i=r;if(n||typeof n==="string")i+=`=${Ff(n)}`;t.push(i)}}return t.join("&")}f9.Field=ux;f9.Fields=dx;f9.FromStringShapeDeserializer=eE;f9.HttpBindingProtocol=ix;f9.HttpInterceptingShapeDeserializer=ax;f9.HttpInterceptingShapeSerializer=cx;f9.HttpProtocol=Dm;f9.RequestBuilder=Xb;f9.RpcProtocol=ox;f9.SerdeContext=Pd;f9.ToStringShapeSerializer=tE;f9.buildQueryString=l9;f9.collectBody=Uu;f9.contentLengthMiddleware=lx;f9.contentLengthMiddlewareOptions=fx;f9.determineTimestampFormat=Zb;f9.escapeUri=Ff;f9.escapeUriPath=d9;f9.extendedEncodeURIComponent=zf;f9.getContentLengthPlugin=c9;f9.getHttpHandlerExtensionConfiguration=s9;f9.requestBuilder=o9;f9.resolveHttpHandlerRuntimeConfig=a9;f9.resolvedPath=sx});var we=A(function(f7){var{Readable:F9}=C("stream"),{NoOpLogger:z9,normalizeProvider:hx}=q(),{HttpResponse:px,HttpRequest:Pm}=L(),{parseRfc7231DateTime:W9,v4:mx}=z(),{hasOwn:H9}=Po(),gx=(e)=>e?.body instanceof F9||typeof ReadableStream<"u"&&e?.body instanceof ReadableStream,V9=["AccessDeniedException","AuthFailure","InvalidSignatureException","RequestExpired","RequestInTheFuture","RequestTimeTooSkewed","SignatureDoesNotMatch"],G9=["BandwidthLimitExceeded","EC2ThrottledException","LimitExceededException","PriorRequestNotComplete","ProvisionedThroughputExceededException","RequestLimitExceeded","RequestThrottled","RequestThrottledException","SlowDown","ThrottledException","Throttling","ThrottlingException","TooManyRequestsException","TransactionInProgressException"],K9=["TimeoutError","RequestTimeout","RequestTimeoutException"],J9=[500,502,503,504],Q9=["ECONNRESET","ECONNREFUSED","EPIPE","ETIMEDOUT"],Y9=["EHOSTUNREACH","ENETUNREACH","ENOTFOUND","EAI_AGAIN"],oE=(e)=>e?.$retryable!==void 0,yx=(e)=>V9.includes(e.name),wx=(e)=>e.$metadata?.clockSkewCorrected,_x=(e)=>{let t=new Set(["Failed to fetch","NetworkError when attempting to fetch resource","The Internet connection appears to be offline","Load failed","Network request failed"]);if(!(e&&e instanceof TypeError))return!1;return t.has(e.message)},Hf=(e)=>e.$metadata?.httpStatusCode===429||G9.includes(e.name)||e.$retryable?.throttling==!0,Vf=(e,t=0)=>oE(e)||wx(e)||e.name==="InvalidSignatureException"&&e.message?.includes("Signature expired")||K9.includes(e.name)||Q9.includes(e?.code||"")||Y9.includes(e?.code||"")||J9.includes(e.$metadata?.httpStatusCode||0)||_x(e)||Ex(e)||e.cause!==void 0&&t<=10&&Vf(e.cause,t+1),bx=(e)=>{if(e.$metadata?.httpStatusCode!==void 0){let t=e.$metadata.httpStatusCode;if(500<=t&&t<=599&&!Vf(e))return!0;return!1}return!1};function Ex(e){return e.code==="ERR_HTTP2_STREAM_ERROR"&&e.message.includes("NGHTTP2_REFUSED_STREAM")}var Sx=100,Mm=20000,Ax=500,Lm=500,Tx=5,vx=10,sE=1,qm="amz-sdk-invocation-id",Bm="amz-sdk-request";function kx(e,t){if(!px.isInstance(e))return;for(let r in e.headers){if(!H9(e.headers,r))continue;let n=r.toLowerCase();if(n==="retry-after"){let i=e.headers[r],o=NaN;if(i.endsWith("GMT"))try{o=(W9(i).getTime()-Date.now())/1000}catch(s){t?.trace?.("Failed to parse retry-after header"),t?.trace?.(s)}else if(i.match(/ GMT, ((\d+)|(\d+\.\d+))$/))o=Number(i.match(/ GMT, ([\d.]+)$/)?.[1]);else if(i.match(/^((\d+)|(\d+\.\d+))$/))o=Number(i);else if(Date.parse(i)>=Date.now())o=(Date.parse(i)-Date.now())/1000;if(isNaN(o))return;return new Date(Date.now()+o*1000)}else if(n==="x-amz-retry-after"){let i=e.headers[r],o=Number(i);if(isNaN(o)){t?.trace?.(`Failed to parse x-amz-retry-after=${i}`);return}return new Date(Date.now()+o)}}}function X9(e,t){return kx(e,t)}var Rx=(e)=>{if(e instanceof Error)return e;if(e instanceof Object)return Object.assign(Error(),e);if(typeof e==="string")return Error(e);return Error(`AWS SDK error wrapper for ${e}`)};function Nx(e){return(t)=>(r,n)=>async(i)=>{let o=await t.retryStrategy(),s=await t.maxAttempts();if(e7(o)){o=o;let a=await o.acquireInitialRetryToken((n.partition_id??"")+(n.__retryLongPoll?":longpoll":"")),c=Error(),u=0,d=0,{request:f}=i,h=Pm.isInstance(f);if(h)f.headers[qm]=mx();while(!0)try{if(h)f.headers[Bm]=`attempt=${u+1}; max=${s}`;let{response:p,output:g}=await r(i);return o.recordSuccess(a),g.$metadata.attempts=u+1,g.$metadata.totalRetryDelay=d,{response:p,output:g}}catch(p){let g=t7(p,t.logger);if(c=Rx(p),h&&e(f))throw(n.logger instanceof z9?console:n.logger)?.warn("An error was encountered in a non-retryable streaming request."),c;try{a=await o.refreshRetryTokenForRetry(a,g)}catch(R){if(!c.$metadata)c.$metadata={};throw c.$metadata.attempts=u+1,c.$metadata.totalRetryDelay=d,c}u=a.getRetryCount();let _=a.getRetryDelay();if(d+=(a?.$retryLog?.acquisitionDelay??0)+_,_>0)await Z9(_)}}else{if(o=o,o?.mode)n.userAgent=[...n.userAgent||[],["cfg/retry-mode",o.mode]];return o.retry(r,i)}}}var Z9=(e)=>new Promise((t)=>setTimeout(t,e)),e7=(e)=>typeof e.acquireInitialRetryToken<"u"&&typeof e.refreshRetryTokenForRetry<"u"&&typeof e.recordSuccess<"u",t7=(e,t)=>{let r={error:e,errorType:r7(e)},n=kx(e.$response,t);if(n)r.retryAfterHint=n;return r},r7=(e)=>{if(Hf(e))return"THROTTLING";if(Vf(e))return"TRANSIENT";if(bx(e))return"SERVER_ERROR";return"CLIENT_ERROR"},xx={name:"retryMiddleware",tags:["RETRY"],step:"finalizeRequest",priority:"high",override:!0};function n7(e){let t=Nx(e);return(r)=>({applyToStack:(n)=>{n.add(t(r),xx)}})}class Gf{static setTimeoutFn=(e,t)=>setTimeout(e,t);beta;minCapacity;minFillRate;scaleConstant;smooth;enabled=!1;availableTokens=0;lastMaxRate=0;measuredTxRate=0;requestCount=0;fillRate;lastThrottleTime;lastTimestamp=0;lastTxRateBucket;maxCapacity;timeWindow=0;constructor(e){this.beta=e?.beta??0.7,this.minCapacity=e?.minCapacity??1,this.minFillRate=e?.minFillRate??0.5,this.scaleConstant=e?.scaleConstant??0.4,this.smooth=e?.smooth??0.8,this.lastThrottleTime=this.getCurrentTimeInSeconds(),this.lastTxRateBucket=Math.floor(this.getCurrentTimeInSeconds()),this.fillRate=this.minFillRate,this.maxCapacity=this.minCapacity}async getSendToken(){return this.acquireTokenBucket(1)}updateClientSendingRate(e){let t;this.updateMeasuredRate();let r=e;if(r?.errorType==="THROTTLING"||Hf(r?.error??e)){let o=!this.enabled?this.measuredTxRate:Math.min(this.measuredTxRate,this.fillRate);this.lastMaxRate=o,this.calculateTimeWindow(),this.lastThrottleTime=this.getCurrentTimeInSeconds(),t=this.cubicThrottle(o),this.enableTokenBucket()}else this.calculateTimeWindow(),t=this.cubicSuccess(this.getCurrentTimeInSeconds());let i=Math.min(t,2*this.measuredTxRate);this.updateTokenBucketRate(i)}getCurrentTimeInSeconds(){return Date.now()/1000}async acquireTokenBucket(e){if(!this.enabled)return;this.refillTokenBucket();while(e>this.availableTokens){let t=(e-this.availableTokens)/this.fillRate*1000;await new Promise((r)=>Gf.setTimeoutFn(r,t)),this.refillTokenBucket()}this.availableTokens=this.availableTokens-e}refillTokenBucket(){let e=this.getCurrentTimeInSeconds();if(!this.lastTimestamp){this.lastTimestamp=e;return}let t=(e-this.lastTimestamp)*this.fillRate;this.availableTokens=Math.min(this.maxCapacity,this.availableTokens+t),this.lastTimestamp=e}calculateTimeWindow(){this.timeWindow=this.getPrecise(Math.pow(this.lastMaxRate*(1-this.beta)/this.scaleConstant,0.3333333333333333))}cubicThrottle(e){return this.getPrecise(e*this.beta)}cubicSuccess(e){return this.getPrecise(this.scaleConstant*Math.pow(e-this.lastThrottleTime-this.timeWindow,3)+this.lastMaxRate)}enableTokenBucket(){this.enabled=!0}updateTokenBucketRate(e){this.refillTokenBucket(),this.fillRate=Math.max(e,this.minFillRate),this.maxCapacity=Math.max(e,this.minCapacity),this.availableTokens=Math.min(this.availableTokens,this.maxCapacity)}updateMeasuredRate(){let e=this.getCurrentTimeInSeconds(),t=Math.floor(e*2)/2;if(this.requestCount++,t>this.lastTxRateBucket){let r=this.requestCount/(t-this.lastTxRateBucket);this.measuredTxRate=this.getPrecise(r*this.smooth+this.measuredTxRate*(1-this.smooth)),this.requestCount=0,this.lastTxRateBucket=t}}getPrecise(e){return parseFloat(e.toFixed(8))}}class Pi{static v2026=typeof process<"u"&&process.env?.SMITHY_NEW_RETRIES_2026==="true";static delay(){return Pi.v2026?50:100}static throttlingDelay(){return Pi.v2026?1000:500}static cost(){return Pi.v2026?14:5}static throttlingCost(){return Pi.v2026?5:10}static modifiedCostType(){return Pi.v2026?"THROTTLING":"TRANSIENT"}}class Cx{x=Pi.delay();computeNextBackoffDelay(e){let t=Math.random(),r=2,n=t*Math.min(this.x*2**e,Mm);return Math.floor(n)}setDelayBase(e){this.x=e}}class rE{delay;count;cost;longPoll;$retryLog={acquisitionDelay:0};constructor(e,t,r,n){this.delay=e,this.count=t,this.cost=r,this.longPoll=n}getRetryCount(){return this.count}getRetryDelay(){return Math.min(Mm,this.delay)}getRetryCost(){return this.cost}isLongPoll(){return this.longPoll}}var za;(function(e){e.STANDARD="standard",e.ADAPTIVE="adaptive"})(za||(za={}));var Pu=3,Ox=za.STANDARD,Um={incompatible:1,attempts:2,capacity:3},Wf=class{mode=za.STANDARD;retryBackoffStrategy;capacity=Lm;maxAttemptsProvider;baseDelay;constructor(t){if(typeof t==="number")this.maxAttemptsProvider=async()=>t;else if(typeof t==="function")this.maxAttemptsProvider=t;else if(t&&typeof t==="object")this.maxAttemptsProvider=async()=>t.maxAttempts,this.baseDelay=t.baseDelay,this.retryBackoffStrategy=t.backoff;this.maxAttemptsProvider??=async()=>Pu,this.baseDelay??=Pi.delay(),this.retryBackoffStrategy??=new Cx}async acquireInitialRetryToken(t){return new rE(Pi.delay(),0,void 0,Pi.v2026&&t.includes(":longpoll"))}async refreshRetryTokenForRetry(t,r){let n=await this.getMaxAttempts(),i=this.retryCode(t,r,n),o=i===0,s=t.isLongPoll?.();if(o||s){let a=r.errorType;this.retryBackoffStrategy.setDelayBase(a==="THROTTLING"?Pi.throttlingDelay():this.baseDelay);let c=this.retryBackoffStrategy.computeNextBackoffDelay(t.getRetryCount()),u=c;if(r.retryAfterHint instanceof Date)u=Math.max(c,Math.min(r.retryAfterHint.getTime()-Date.now(),c+5000));if(!o){let d=Pi.v2026&&i===Um.capacity&&s?u:0;if(d>0)await new Promise((f)=>setTimeout(f,d))}else{let d=this.getCapacityCost(a);this.capacity-=d;let f=new rE(0,t.getRetryCount()+1,d,t.isLongPoll?.()??!1);return await new Promise((h)=>setTimeout(h,u)),f.$retryLog.acquisitionDelay=u,f}}throw Error("No retry token available")}recordSuccess(t){this.capacity=Math.min(Lm,this.capacity+(t.getRetryCost()??sE))}getCapacity(){return this.capacity}async maxAttempts(){return this.maxAttemptsProvider()}async getMaxAttempts(){try{return await this.maxAttemptsProvider()}catch(t){return console.warn(`Max attempts provider could not resolve. Using default of ${Pu}`),Pu}}retryCode(t,r,n){let i=t.getRetryCount()+1,o=this.isRetryableError(r.errorType)?0:Um.incompatible,s=i<n?0:Um.attempts,a=this.capacity>=this.getCapacityCost(r.errorType)?0:Um.capacity;return o||s||a}getCapacityCost(t){return t===Pi.modifiedCostType()?Pi.throttlingCost():Pi.cost()}isRetryableError(t){return t==="THROTTLING"||t==="TRANSIENT"}},Ix=class{mode=za.ADAPTIVE;rateLimiter;standardRetryStrategy;constructor(t,r){let{rateLimiter:n}=r??{};this.rateLimiter=n??new Gf,this.standardRetryStrategy=r?new Wf({maxAttempts:typeof t==="number"?t:3,...r}):new Wf(t)}async acquireInitialRetryToken(t){let r=await this.standardRetryStrategy.acquireInitialRetryToken(t);return await this.rateLimiter.getSendToken(),r}async refreshRetryTokenForRetry(t,r){this.rateLimiter.updateClientSendingRate(r);let n=await this.standardRetryStrategy.refreshRetryTokenForRetry(t,r);return await this.rateLimiter.getSendToken(),n}recordSuccess(t){this.rateLimiter.updateClientSendingRate({}),this.standardRetryStrategy.recordSuccess(t)}async maxAttemptsProvider(){return this.standardRetryStrategy.maxAttempts()}};class Dx extends Wf{computeNextBackoffDelay;constructor(e,t=Pi.delay()){super(typeof e==="function"?e:async()=>e);if(typeof t==="number")this.computeNextBackoffDelay=()=>t;else this.computeNextBackoffDelay=t;this.retryBackoffStrategy.computeNextBackoffDelay=(r)=>{let n=r+1;return this.computeNextBackoffDelay(n)}}}var i7=(e,t)=>{let r=e,n=sE,i=Tx,o=vx,s=e,a=(f)=>f.name==="TimeoutError"?o:i,c=(f)=>a(f)<=s;return Object.freeze({hasRetryTokens:c,retrieveRetryTokens:(f)=>{if(!c(f))throw Error("No retry token available");let h=a(f);return s-=h,h},releaseRetryTokens:(f)=>{s+=f??n,s=Math.min(s,r)}})},Ux=(e,t)=>Math.floor(Math.min(Mm,Math.random()*2**t*e)),Px=(e)=>{if(!e)return!1;return oE(e)||yx(e)||Hf(e)||Vf(e)};class aE{maxAttemptsProvider;retryDecider;delayDecider;retryQuota;mode=za.STANDARD;constructor(e,t){this.maxAttemptsProvider=e,this.retryDecider=t?.retryDecider??Px,this.delayDecider=t?.delayDecider??Ux,this.retryQuota=t?.retryQuota??i7(Lm)}shouldRetry(e,t,r){return t<r&&this.retryDecider(e)&&this.retryQuota.hasRetryTokens(e)}async getMaxAttempts(){let e;try{e=await this.maxAttemptsProvider()}catch(t){e=Pu}return e}async retry(e,t,r){let n,i=0,o=0,s=await this.getMaxAttempts(),{request:a}=t;if(Pm.isInstance(a))a.headers[qm]=mx();while(!0)try{if(Pm.isInstance(a))a.headers[Bm]=`attempt=${i+1}; max=${s}`;if(r?.beforeRequest)await r.beforeRequest();let{response:c,output:u}=await e(t);if(r?.afterRequest)r.afterRequest(c);return this.retryQuota.releaseRetryTokens(n),u.$metadata.attempts=i+1,u.$metadata.totalRetryDelay=o,{response:c,output:u}}catch(c){let u=Rx(c);if(i++,this.shouldRetry(u,i,s)){n=this.retryQuota.retrieveRetryTokens(u);let d=this.delayDecider(Hf(u)?Ax:Sx,i),f=o7(u.$response),h=Math.max(f||0,d);o+=h,await new Promise((p)=>setTimeout(p,h));continue}if(!u.$metadata)u.$metadata={};throw u.$metadata.attempts=i,u.$metadata.totalRetryDelay=o,u}}}var o7=(e)=>{if(!px.isInstance(e))return;let t=Object.keys(e.headers).find((o)=>o.toLowerCase()==="retry-after");if(!t)return;let r=e.headers[t],n=Number(r);if(!Number.isNaN(n))return Math.min(n*1000,20000);let i=new Date(r);return Math.min(i.getTime()-Date.now(),20000)};class Lx extends aE{rateLimiter;constructor(e,t){let{rateLimiter:r,...n}=t??{};super(e,n);this.rateLimiter=r??new Gf,this.mode=za.ADAPTIVE}async retry(e,t){return super.retry(e,t,{beforeRequest:async()=>this.rateLimiter.getSendToken(),afterRequest:(r)=>{this.rateLimiter.updateClientSendingRate(r)}})}}var nE="AWS_MAX_ATTEMPTS",iE="max_attempts",s7={environmentVariableSelector:(e)=>{let t=e[nE];if(!t)return;let r=parseInt(t);if(Number.isNaN(r))throw Error(`Environment variable ${nE} mast be a number, got "${t}"`);return r},configFileSelector:(e)=>{let t=e[iE];if(!t)return;let r=parseInt(t);if(Number.isNaN(r))throw Error(`Shared config file entry ${iE} mast be a number, got "${t}"`);return r},default:Pu},a7=(e,t)=>{let{retryStrategy:r,retryMode:n}=e,{defaultMaxAttempts:i=Pu,defaultBaseDelay:o=Pi.delay()}=t??{},s=hx(e.maxAttempts??i),a=r?Promise.resolve(r):void 0,c=async()=>{let u=await s();if(await hx(n)()===za.ADAPTIVE)return new Ix(s,{maxAttempts:u,baseDelay:o});return new Wf({maxAttempts:u,baseDelay:o})};return Object.assign(e,{maxAttempts:s,retryStrategy:()=>a??=c()})},Mx="AWS_RETRY_MODE",qx="retry_mode",c7={environmentVariableSelector:(e)=>e[Mx],configFileSelector:(e)=>e[qx],default:Ox},Bx=()=>(e)=>async(t)=>{let{request:r}=t;if(Pm.isInstance(r))delete r.headers[qm],delete r.headers[Bm];return e(t)},jx={name:"omitRetryHeadersMiddleware",tags:["RETRY","HEADERS","OMIT_RETRY_HEADERS"],relation:"before",toMiddleware:"awsAuthMiddleware",override:!0},u7=(e)=>({applyToStack:(t)=>{t.addRelativeTo(Bx(),jx)}}),d7=Nx(gx),l7=n7(gx);f7.AdaptiveRetryStrategy=Ix;f7.CONFIG_MAX_ATTEMPTS=iE;f7.CONFIG_RETRY_MODE=qx;f7.ConfiguredRetryStrategy=Dx;f7.DEFAULT_MAX_ATTEMPTS=Pu;f7.DEFAULT_RETRY_DELAY_BASE=Sx;f7.DEFAULT_RETRY_MODE=Ox;f7.DefaultRateLimiter=Gf;f7.DeprecatedAdaptiveRetryStrategy=Lx;f7.DeprecatedStandardRetryStrategy=aE;f7.ENV_MAX_ATTEMPTS=nE;f7.ENV_RETRY_MODE=Mx;f7.INITIAL_RETRY_TOKENS=Lm;f7.INVOCATION_ID_HEADER=qm;f7.MAXIMUM_RETRY_DELAY=Mm;f7.NODE_MAX_ATTEMPT_CONFIG_OPTIONS=s7;f7.NODE_RETRY_MODE_CONFIG_OPTIONS=c7;f7.NO_RETRY_INCREMENT=sE;f7.REQUEST_HEADER=Bm;f7.RETRY_COST=Tx;f7.RETRY_MODES=za;f7.Retry=Pi;f7.StandardRetryStrategy=Wf;f7.THROTTLING_RETRY_DELAY_BASE=Ax;f7.TIMEOUT_RETRY_COST=vx;f7.defaultDelayDecider=Ux;f7.defaultRetryDecider=Px;f7.getOmitRetryHeadersPlugin=u7;f7.getRetryAfterHint=X9;f7.getRetryPlugin=l7;f7.isBrowserNetworkError=_x;f7.isClockSkewCorrectedError=wx;f7.isClockSkewError=yx;f7.isNodeJsHttp2TransientError=Ex;f7.isRetryableByTrait=oE;f7.isServerError=bx;f7.isThrottlingError=Hf;f7.isTransientError=Vf;f7.omitRetryHeadersMiddleware=Bx;f7.omitRetryHeadersMiddlewareOptions=jx;f7.resolveRetryConfig=a7;f7.retryMiddleware=d7;f7.retryMiddlewareOptions=xx});var Fx=A(function(rY){var Tc={REQUEST_ID:Symbol.for("_AWS_LAMBDA_REQUEST_ID"),X_RAY_TRACE_ID:Symbol.for("_AWS_LAMBDA_X_RAY_TRACE_ID"),TENANT_ID:Symbol.for("_AWS_LAMBDA_TENANT_ID"),TRACEPARENT:Symbol.for("_AWS_LAMBDA_TRACEPARENT"),TRACESTATE:Symbol.for("_AWS_LAMBDA_TRACESTATE"),BAGGAGE:Symbol.for("_AWS_LAMBDA_BAGGAGE")},cE=["true","1"].includes(process.env?.AWS_LAMBDA_NODEJS_NO_GLOBAL_AWSLAMBDA??"");if(!cE)globalThis.awslambda=globalThis.awslambda||{};class jm{static PROTECTED_KEYS=Tc;isProtectedKey(e){return Object.values(Tc).includes(e)}getRequestId(){return this.get(Tc.REQUEST_ID)??"-"}getXRayTraceId(){return this.get(Tc.X_RAY_TRACE_ID)}getTenantId(){return this.get(Tc.TENANT_ID)}getTraceparent(){return this.get(Tc.TRACEPARENT)}getTracestate(){return this.get(Tc.TRACESTATE)}getBaggage(){return this.get(Tc.BAGGAGE)}}class $x extends jm{currentContext;getContext(){return this.currentContext}hasContext(){return this.currentContext!==void 0}get(e){return this.currentContext?.[e]}set(e,t){if(this.isProtectedKey(e))throw Error(`Cannot modify protected Lambda context field: ${String(e)}`);this.currentContext=this.currentContext||{},this.currentContext[e]=t}run(e,t){return this.currentContext=e,t()}}class dE extends jm{als;static async create(){let e=new dE,t=await import("async_hooks");return e.als=new t.AsyncLocalStorage,e}getContext(){return this.als.getStore()}hasContext(){return this.als.getStore()!==void 0}get(e){return this.als.getStore()?.[e]}set(e,t){if(this.isProtectedKey(e))throw Error(`Cannot modify protected Lambda context field: ${String(e)}`);let r=this.als.getStore();if(!r)throw Error("No context available");r[e]=t}run(e,t){return this.als.run(e,t)}}rY.InvokeStore=void 0;(function(e){let t=null;async function r(n){if(!t)t=(async()=>{let o=n===!0||"AWS_LAMBDA_MAX_CONCURRENCY"in process.env?await dE.create():new $x;if(!cE&&globalThis.awslambda?.InvokeStore)return globalThis.awslambda.InvokeStore;else if(!cE&&globalThis.awslambda)return globalThis.awslambda.InvokeStore=o,o;else return o})();return t}e.getInstanceAsync=r,e._testing=process.env.AWS_LAMBDA_BENCHMARK_MODE==="1"?{reset:()=>{if(t=null,globalThis.awslambda?.InvokeStore)delete globalThis.awslambda.InvokeStore;globalThis.awslambda={InvokeStore:void 0}}}:void 0})(rY.InvokeStore||(rY.InvokeStore={}));rY.InvokeStoreBase=jm});var ge=A(function(bY){var{getSmithyContext:lE,hasOwn:iY}=Po();bY.getSmithyContext=lE;var{HttpRequest:fE}=L(),{requestBuilder:oY}=L();bY.requestBuilder=oY;var{HttpApiKeyAuthLocation:zx}=Nu(),sY=(e,t)=>{if(!t||t.length===0)return e;let r=[];for(let n of t)for(let i of e)if(i.schemeId.split("#")[1]===n)r.push(i);for(let n of e)if(!r.find(({schemeId:i})=>i===n.schemeId))r.push(n);return r};function aY(e){let t=new Map;for(let r of e)t.set(r.schemeId,r);return t}var hE=(e,t)=>(r,n)=>async(i)=>{let o=e.httpAuthSchemeProvider(await t.httpAuthSchemeParametersProvider(e,n,i.input)),s=e.authSchemePreference?await e.authSchemePreference():[],a=sY(o,s),c=aY(e.httpAuthSchemes),u=lE(n),d=[];for(let f of a){let h=c.get(f.schemeId);if(!h){d.push(`HttpAuthScheme \`${f.schemeId}\` was not enabled for this service.`);continue}let p=h.identityProvider(await t.identityProviderConfigProvider(e));if(!p){d.push(`HttpAuthScheme \`${f.schemeId}\` did not have an IdentityProvider configured.`);continue}let{identityProperties:g={},signingProperties:_={}}=f.propertiesExtractor?.(e,n)||{};f.identityProperties=Object.assign(f.identityProperties||{},g),f.signingProperties=Object.assign(f.signingProperties||{},_),u.selectedHttpAuthScheme={httpAuthOption:f,identity:await p(f.identityProperties),signer:h.signer};break}if(!u.selectedHttpAuthScheme)throw Error(d.join(`
18
+ `));return r(i)},Wx={step:"serialize",tags:["HTTP_AUTH_SCHEME"],name:"httpAuthSchemeMiddleware",override:!0,relation:"before",toMiddleware:"endpointV2Middleware"},cY=(e,{httpAuthSchemeParametersProvider:t,identityProviderConfigProvider:r})=>({applyToStack:(n)=>{n.addRelativeTo(hE(e,{httpAuthSchemeParametersProvider:t,identityProviderConfigProvider:r}),Wx)}}),Hx={step:"serialize",tags:["HTTP_AUTH_SCHEME"],name:"httpAuthSchemeMiddleware",override:!0,relation:"before",toMiddleware:"serializerMiddleware"},uY=(e,{httpAuthSchemeParametersProvider:t,identityProviderConfigProvider:r})=>({applyToStack:(n)=>{n.addRelativeTo(hE(e,{httpAuthSchemeParametersProvider:t,identityProviderConfigProvider:r}),Hx)}}),dY=(e)=>(t)=>{throw t},lY=(e,t)=>{},Vx=(e)=>(t,r)=>async(n)=>{if(!fE.isInstance(n.request))return t(n);let o=lE(r).selectedHttpAuthScheme;if(!o)throw Error("No HttpAuthScheme was selected: unable to sign request");let{httpAuthOption:{signingProperties:s={}},identity:a,signer:c}=o,u=await t({...n,request:await c.sign(n.request,a,s)}).catch((c.errorHandler||dY)(s));return(c.successHandler||lY)(u.response,s),u},Gx={step:"finalizeRequest",tags:["HTTP_SIGNING"],name:"httpSigningMiddleware",aliases:["apiKeyMiddleware","tokenMiddleware","awsAuthMiddleware"],override:!0,relation:"after",toMiddleware:"retryMiddleware"},fY=(e)=>({applyToStack:(t)=>{t.addRelativeTo(Vx(),Gx)}}),hY=(e)=>{if(typeof e==="function")return e;let t=Promise.resolve(e);return()=>t},pY=async(e,t,r,n=(o)=>o,...i)=>{let o=new e(r);return o=n(o)??o,await t.send(o,...i)};function mY(e,t,r,n,i){return async function*(s,a,...c){let u=a,d=s.startingToken??u[r],f=!0,h;while(f){if(u[r]=d,i)u[i]=u[i]??s.pageSize;if(s.client instanceof e)h=await pY(t,s.client,a,s.withCommand,...c);else throw Error(`Invalid client, expected instance of ${e.name}`);yield h;let p=d;d=gY(h,n),f=!!(d&&(!s.stopOnSameToken||d!==p))}return}}var gY=(e,t)=>{let r=e,n=t.split(".");for(let i of n){if(!r||typeof r!=="object")return;r=r[i]}return r};function yY(e,t,r){if(!e.__smithy_context)e.__smithy_context={features:{}};else if(!e.__smithy_context.features)e.__smithy_context.features={};e.__smithy_context.features[t]=r}class Kx{authSchemes=new Map;constructor(e){for(let t in e){if(!iY(e,t))continue;let r=e[t];if(r!==void 0)this.authSchemes.set(t,r)}}getIdentityProvider(e){return this.authSchemes.get(e)}}class Jx{async sign(e,t,r){if(!r)throw Error("request could not be signed with `apiKey` since the `name` and `in` signer properties are missing");if(!r.name)throw Error("request could not be signed with `apiKey` since the `name` signer property is missing");if(!r.in)throw Error("request could not be signed with `apiKey` since the `in` signer property is missing");if(!t.apiKey)throw Error("request could not be signed with `apiKey` since the `apiKey` is not defined");let n=fE.clone(e);if(r.in===zx.QUERY)n.query[r.name]=t.apiKey;else if(r.in===zx.HEADER)n.headers[r.name]=r.scheme?`${r.scheme} ${t.apiKey}`:t.apiKey;else throw Error("request can only be signed with `apiKey` locations `query` or `header`, but found: `"+r.in+"`");return n}}class Qx{async sign(e,t,r){let n=fE.clone(e);if(!t.token)throw Error("request could not be signed with `token` since the `token` is not defined");return n.headers.Authorization=`Bearer ${t.token}`,n}}class Yx{async sign(e,t,r){return e}}var Xx=(e)=>function(r){return eC(r)&&r.expiration.getTime()-Date.now()<e},Zx=300000,wY=Xx(Zx),eC=(e)=>e.expiration!==void 0,_Y=(e,t,r)=>{if(e===void 0)return;let n=typeof e!=="function"?async()=>Promise.resolve(e):e,i,o,s,a=!1,c=async(u)=>{if(!o)o=n(u);try{i=await o,s=!0,a=!1}finally{o=void 0}return i};if(t===void 0)return async(u)=>{if(!s||u?.forceRefresh)i=await c(u);return i};return async(u)=>{if(!s||u?.forceRefresh)i=await c(u);if(a)return i;if(!r(i))return a=!0,i;if(t(i))return await c(u),i;return i}};bY.DefaultIdentityProviderConfig=Kx;bY.EXPIRATION_MS=Zx;bY.HttpApiKeyAuthSigner=Jx;bY.HttpBearerAuthSigner=Qx;bY.NoAuthSigner=Yx;bY.createIsIdentityExpiredFunction=Xx;bY.createPaginator=mY;bY.doesIdentityRequireRefresh=eC;bY.getHttpAuthSchemeEndpointRuleSetPlugin=cY;bY.getHttpAuthSchemePlugin=uY;bY.getHttpSigningPlugin=fY;bY.httpAuthSchemeEndpointRuleSetMiddlewareOptions=Wx;bY.httpAuthSchemeMiddleware=hE;bY.httpAuthSchemeMiddlewareOptions=Hx;bY.httpSigningMiddleware=Vx;bY.httpSigningMiddlewareOptions=Gx;bY.isIdentityExpired=wY;bY.memoizeIdentityProvider=_Y;bY.normalizeProvider=hY;bY.setFeature=yY});var tC=A(function(Kf,pE){(function(e,t){typeof Kf=="object"&&typeof pE=="object"?pE.exports=t():typeof define=="function"&&define.amd?define([],t):typeof Kf=="object"?Kf.bowser=t():e.bowser=t()})(Kf,function(){return function(e){var t={};function r(n){if(t[n])return t[n].exports;var i=t[n]={i:n,l:!1,exports:{}};return e[n].call(i.exports,i,i.exports,r),i.l=!0,i.exports}return r.m=e,r.c=t,r.d=function(n,i,o){r.o(n,i)||Object.defineProperty(n,i,{enumerable:!0,get:o})},r.r=function(n){typeof Symbol<"u"&&Symbol.toStringTag&&Object.defineProperty(n,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(n,"__esModule",{value:!0})},r.t=function(n,i){if(1&i&&(n=r(n)),8&i)return n;if(4&i&&typeof n=="object"&&n&&n.__esModule)return n;var o=Object.create(null);if(r.r(o),Object.defineProperty(o,"default",{enumerable:!0,value:n}),2&i&&typeof n!="string")for(var s in n)r.d(o,s,function(a){return n[a]}.bind(null,s));return o},r.n=function(n){var i=n&&n.__esModule?function(){return n.default}:function(){return n};return r.d(i,"a",i),i},r.o=function(n,i){return Object.prototype.hasOwnProperty.call(n,i)},r.p="",r(r.s=90)}({17:function(e,t,r){t.__esModule=!0,t.default=void 0;var n=r(18),i=function(){function o(){}return o.getFirstMatch=function(s,a){var c=a.match(s);return c&&c.length>0&&c[1]||""},o.getSecondMatch=function(s,a){var c=a.match(s);return c&&c.length>1&&c[2]||""},o.matchAndReturnConst=function(s,a,c){if(s.test(a))return c},o.getWindowsVersionName=function(s){switch(s){case"NT":return"NT";case"XP":return"XP";case"NT 5.0":return"2000";case"NT 5.1":return"XP";case"NT 5.2":return"2003";case"NT 6.0":return"Vista";case"NT 6.1":return"7";case"NT 6.2":return"8";case"NT 6.3":return"8.1";case"NT 10.0":return"10";default:return}},o.getMacOSVersionName=function(s){var a=s.split(".").splice(0,2).map(function(d){return parseInt(d,10)||0});a.push(0);var c=a[0],u=a[1];if(c===10)switch(u){case 5:return"Leopard";case 6:return"Snow Leopard";case 7:return"Lion";case 8:return"Mountain Lion";case 9:return"Mavericks";case 10:return"Yosemite";case 11:return"El Capitan";case 12:return"Sierra";case 13:return"High Sierra";case 14:return"Mojave";case 15:return"Catalina";default:return}switch(c){case 11:return"Big Sur";case 12:return"Monterey";case 13:return"Ventura";case 14:return"Sonoma";case 15:return"Sequoia";default:return}},o.getAndroidVersionName=function(s){var a=s.split(".").splice(0,2).map(function(c){return parseInt(c,10)||0});if(a.push(0),!(a[0]===1&&a[1]<5))return a[0]===1&&a[1]<6?"Cupcake":a[0]===1&&a[1]>=6?"Donut":a[0]===2&&a[1]<2?"Eclair":a[0]===2&&a[1]===2?"Froyo":a[0]===2&&a[1]>2?"Gingerbread":a[0]===3?"Honeycomb":a[0]===4&&a[1]<1?"Ice Cream Sandwich":a[0]===4&&a[1]<4?"Jelly Bean":a[0]===4&&a[1]>=4?"KitKat":a[0]===5?"Lollipop":a[0]===6?"Marshmallow":a[0]===7?"Nougat":a[0]===8?"Oreo":a[0]===9?"Pie":void 0},o.getVersionPrecision=function(s){return s.split(".").length},o.compareVersions=function(s,a,c){c===void 0&&(c=!1);var u=o.getVersionPrecision(s),d=o.getVersionPrecision(a),f=Math.max(u,d),h=0,p=o.map([s,a],function(g){var _=f-o.getVersionPrecision(g),R=g+Array(_+1).join(".0");return o.map(R.split("."),function(O){return Array(20-O.length).join("0")+O}).reverse()});for(c&&(h=f-Math.min(u,d)),f-=1;f>=h;){if(p[0][f]>p[1][f])return 1;if(p[0][f]===p[1][f]){if(f===h)return 0;f-=1}else if(p[0][f]<p[1][f])return-1}},o.map=function(s,a){var c,u=[];if(Array.prototype.map)return Array.prototype.map.call(s,a);for(c=0;c<s.length;c+=1)u.push(a(s[c]));return u},o.find=function(s,a){var c,u;if(Array.prototype.find)return Array.prototype.find.call(s,a);for(c=0,u=s.length;c<u;c+=1){var d=s[c];if(a(d,c))return d}},o.assign=function(s){for(var a,c,u=s,d=arguments.length,f=Array(d>1?d-1:0),h=1;h<d;h++)f[h-1]=arguments[h];if(Object.assign)return Object.assign.apply(Object,[s].concat(f));var p=function(){var g=f[a];typeof g=="object"&&g!==null&&Object.keys(g).forEach(function(_){u[_]=g[_]})};for(a=0,c=f.length;a<c;a+=1)p();return s},o.getBrowserAlias=function(s){return n.BROWSER_ALIASES_MAP[s]},o.getBrowserTypeByAlias=function(s){return n.BROWSER_MAP[s]||""},o}();t.default=i,e.exports=t.default},18:function(e,t,r){t.__esModule=!0,t.ENGINE_MAP=t.OS_MAP=t.PLATFORMS_MAP=t.BROWSER_MAP=t.BROWSER_ALIASES_MAP=void 0,t.BROWSER_ALIASES_MAP={AmazonBot:"amazonbot","Amazon Silk":"amazon_silk","Android Browser":"android",BaiduSpider:"baiduspider",Bada:"bada",BingCrawler:"bingcrawler",Brave:"brave",BlackBerry:"blackberry","ChatGPT-User":"chatgpt_user",Chrome:"chrome",ClaudeBot:"claudebot",Chromium:"chromium",Diffbot:"diffbot",DuckDuckBot:"duckduckbot",DuckDuckGo:"duckduckgo",Electron:"electron",Epiphany:"epiphany",FacebookExternalHit:"facebookexternalhit",Firefox:"firefox",Focus:"focus",Generic:"generic","Google Search":"google_search",Googlebot:"googlebot",GPTBot:"gptbot","Internet Explorer":"ie",InternetArchiveCrawler:"internetarchivecrawler","K-Meleon":"k_meleon",LibreWolf:"librewolf",Linespider:"linespider",Maxthon:"maxthon","Meta-ExternalAds":"meta_externalads","Meta-ExternalAgent":"meta_externalagent","Meta-ExternalFetcher":"meta_externalfetcher","Meta-WebIndexer":"meta_webindexer","Microsoft Edge":"edge","MZ Browser":"mz","NAVER Whale Browser":"naver","OAI-SearchBot":"oai_searchbot",Omgilibot:"omgilibot",Opera:"opera","Opera Coast":"opera_coast","Pale Moon":"pale_moon",PerplexityBot:"perplexitybot","Perplexity-User":"perplexity_user",PhantomJS:"phantomjs",PingdomBot:"pingdombot",Puffin:"puffin",QQ:"qq",QQLite:"qqlite",QupZilla:"qupzilla",Roku:"roku",Safari:"safari",Sailfish:"sailfish","Samsung Internet for Android":"samsung_internet",SlackBot:"slackbot",SeaMonkey:"seamonkey",Sleipnir:"sleipnir","Sogou Browser":"sogou",Swing:"swing",Tizen:"tizen","UC Browser":"uc",Vivaldi:"vivaldi","WebOS Browser":"webos",WeChat:"wechat",YahooSlurp:"yahooslurp","Yandex Browser":"yandex",YandexBot:"yandexbot",YouBot:"youbot"},t.BROWSER_MAP={amazonbot:"AmazonBot",amazon_silk:"Amazon Silk",android:"Android Browser",baiduspider:"BaiduSpider",bada:"Bada",bingcrawler:"BingCrawler",blackberry:"BlackBerry",brave:"Brave",chatgpt_user:"ChatGPT-User",chrome:"Chrome",claudebot:"ClaudeBot",chromium:"Chromium",diffbot:"Diffbot",duckduckbot:"DuckDuckBot",duckduckgo:"DuckDuckGo",edge:"Microsoft Edge",electron:"Electron",epiphany:"Epiphany",facebookexternalhit:"FacebookExternalHit",firefox:"Firefox",focus:"Focus",generic:"Generic",google_search:"Google Search",googlebot:"Googlebot",gptbot:"GPTBot",ie:"Internet Explorer",internetarchivecrawler:"InternetArchiveCrawler",k_meleon:"K-Meleon",librewolf:"LibreWolf",linespider:"Linespider",maxthon:"Maxthon",meta_externalads:"Meta-ExternalAds",meta_externalagent:"Meta-ExternalAgent",meta_externalfetcher:"Meta-ExternalFetcher",meta_webindexer:"Meta-WebIndexer",mz:"MZ Browser",naver:"NAVER Whale Browser",oai_searchbot:"OAI-SearchBot",omgilibot:"Omgilibot",opera:"Opera",opera_coast:"Opera Coast",pale_moon:"Pale Moon",perplexitybot:"PerplexityBot",perplexity_user:"Perplexity-User",phantomjs:"PhantomJS",pingdombot:"PingdomBot",puffin:"Puffin",qq:"QQ Browser",qqlite:"QQ Browser Lite",qupzilla:"QupZilla",roku:"Roku",safari:"Safari",sailfish:"Sailfish",samsung_internet:"Samsung Internet for Android",seamonkey:"SeaMonkey",slackbot:"SlackBot",sleipnir:"Sleipnir",sogou:"Sogou Browser",swing:"Swing",tizen:"Tizen",uc:"UC Browser",vivaldi:"Vivaldi",webos:"WebOS Browser",wechat:"WeChat",yahooslurp:"YahooSlurp",yandex:"Yandex Browser",yandexbot:"YandexBot",youbot:"YouBot"},t.PLATFORMS_MAP={bot:"bot",desktop:"desktop",mobile:"mobile",tablet:"tablet",tv:"tv"},t.OS_MAP={Android:"Android",Bada:"Bada",BlackBerry:"BlackBerry",ChromeOS:"Chrome OS",HarmonyOS:"HarmonyOS",iOS:"iOS",Linux:"Linux",MacOS:"macOS",PlayStation4:"PlayStation 4",Roku:"Roku",Tizen:"Tizen",WebOS:"WebOS",Windows:"Windows",WindowsPhone:"Windows Phone"},t.ENGINE_MAP={Blink:"Blink",EdgeHTML:"EdgeHTML",Gecko:"Gecko",Presto:"Presto",Trident:"Trident",WebKit:"WebKit"}},90:function(e,t,r){t.__esModule=!0,t.default=void 0;var n,i=(n=r(91))&&n.__esModule?n:{default:n},o=r(18);function s(c,u){for(var d=0;d<u.length;d++){var f=u[d];f.enumerable=f.enumerable||!1,f.configurable=!0,"value"in f&&(f.writable=!0),Object.defineProperty(c,f.key,f)}}var a=function(){function c(){}var u,d,f;return c.getParser=function(h,p,g){if(p===void 0&&(p=!1),g===void 0&&(g=null),typeof h!="string")throw Error("UserAgent should be a string");return new i.default(h,p,g)},c.parse=function(h,p){return p===void 0&&(p=null),new i.default(h,p).getResult()},u=c,f=[{key:"BROWSER_MAP",get:function(){return o.BROWSER_MAP}},{key:"ENGINE_MAP",get:function(){return o.ENGINE_MAP}},{key:"OS_MAP",get:function(){return o.OS_MAP}},{key:"PLATFORMS_MAP",get:function(){return o.PLATFORMS_MAP}}],(d=null)&&s(u.prototype,d),f&&s(u,f),c}();t.default=a,e.exports=t.default},91:function(e,t,r){t.__esModule=!0,t.default=void 0;var n=c(r(92)),i=c(r(93)),o=c(r(94)),s=c(r(95)),a=c(r(17));function c(d){return d&&d.__esModule?d:{default:d}}var u=function(){function d(h,p,g){if(p===void 0&&(p=!1),g===void 0&&(g=null),h==null||h==="")throw Error("UserAgent parameter can't be empty");this._ua=h;var _=!1;typeof p=="boolean"?(_=p,this._hints=g):this._hints=p!=null&&typeof p=="object"?p:null,this.parsedResult={},_!==!0&&this.parse()}var f=d.prototype;return f.getHints=function(){return this._hints},f.hasBrand=function(h){if(!this._hints||!Array.isArray(this._hints.brands))return!1;var p=h.toLowerCase();return this._hints.brands.some(function(g){return g.brand&&g.brand.toLowerCase()===p})},f.getBrandVersion=function(h){if(this._hints&&Array.isArray(this._hints.brands)){var p=h.toLowerCase(),g=this._hints.brands.find(function(_){return _.brand&&_.brand.toLowerCase()===p});return g?g.version:void 0}},f.getUA=function(){return this._ua},f.test=function(h){return h.test(this._ua)},f.parseBrowser=function(){var h=this;this.parsedResult.browser={};var p=a.default.find(n.default,function(g){if(typeof g.test=="function")return g.test(h);if(Array.isArray(g.test))return g.test.some(function(_){return h.test(_)});throw Error("Browser's test function is not valid")});return p&&(this.parsedResult.browser=p.describe(this.getUA(),this)),this.parsedResult.browser},f.getBrowser=function(){return this.parsedResult.browser?this.parsedResult.browser:this.parseBrowser()},f.getBrowserName=function(h){return h?String(this.getBrowser().name).toLowerCase()||"":this.getBrowser().name||""},f.getBrowserVersion=function(){return this.getBrowser().version},f.getOS=function(){return this.parsedResult.os?this.parsedResult.os:this.parseOS()},f.parseOS=function(){var h=this;this.parsedResult.os={};var p=a.default.find(i.default,function(g){if(typeof g.test=="function")return g.test(h);if(Array.isArray(g.test))return g.test.some(function(_){return h.test(_)});throw Error("Browser's test function is not valid")});return p&&(this.parsedResult.os=p.describe(this.getUA())),this.parsedResult.os},f.getOSName=function(h){var p=this.getOS().name;return h?String(p).toLowerCase()||"":p||""},f.getOSVersion=function(){return this.getOS().version},f.getPlatform=function(){return this.parsedResult.platform?this.parsedResult.platform:this.parsePlatform()},f.getPlatformType=function(h){h===void 0&&(h=!1);var p=this.getPlatform().type;return h?String(p).toLowerCase()||"":p||""},f.parsePlatform=function(){var h=this;this.parsedResult.platform={};var p=a.default.find(o.default,function(g){if(typeof g.test=="function")return g.test(h);if(Array.isArray(g.test))return g.test.some(function(_){return h.test(_)});throw Error("Browser's test function is not valid")});return p&&(this.parsedResult.platform=p.describe(this.getUA())),this.parsedResult.platform},f.getEngine=function(){return this.parsedResult.engine?this.parsedResult.engine:this.parseEngine()},f.getEngineName=function(h){return h?String(this.getEngine().name).toLowerCase()||"":this.getEngine().name||""},f.parseEngine=function(){var h=this;this.parsedResult.engine={};var p=a.default.find(s.default,function(g){if(typeof g.test=="function")return g.test(h);if(Array.isArray(g.test))return g.test.some(function(_){return h.test(_)});throw Error("Browser's test function is not valid")});return p&&(this.parsedResult.engine=p.describe(this.getUA())),this.parsedResult.engine},f.parse=function(){return this.parseBrowser(),this.parseOS(),this.parsePlatform(),this.parseEngine(),this},f.getResult=function(){return a.default.assign({},this.parsedResult)},f.satisfies=function(h){var p=this,g={},_=0,R={},O=0;if(Object.keys(h).forEach(function(M){var F=h[M];typeof F=="string"?(R[M]=F,O+=1):typeof F=="object"&&(g[M]=F,_+=1)}),_>0){var I=Object.keys(g),Ne=a.default.find(I,function(M){return p.isOS(M)});if(Ne){var k=this.satisfies(g[Ne]);if(k!==void 0)return k}var j=a.default.find(I,function(M){return p.isPlatform(M)});if(j){var re=this.satisfies(g[j]);if(re!==void 0)return re}}if(O>0){var Oe=Object.keys(R),ne=a.default.find(Oe,function(M){return p.isBrowser(M,!0)});if(ne!==void 0)return this.compareVersion(R[ne])}},f.isBrowser=function(h,p){p===void 0&&(p=!1);var g=this.getBrowserName().toLowerCase(),_=h.toLowerCase(),R=a.default.getBrowserTypeByAlias(_);return p&&R&&(_=R.toLowerCase()),_===g},f.compareVersion=function(h){var p=[0],g=h,_=!1,R=this.getBrowserVersion();if(typeof R=="string")return h[0]===">"||h[0]==="<"?(g=h.substr(1),h[1]==="="?(_=!0,g=h.substr(2)):p=[],h[0]===">"?p.push(1):p.push(-1)):h[0]==="="?g=h.substr(1):h[0]==="~"&&(_=!0,g=h.substr(1)),p.indexOf(a.default.compareVersions(R,g,_))>-1},f.isOS=function(h){return this.getOSName(!0)===String(h).toLowerCase()},f.isPlatform=function(h){return this.getPlatformType(!0)===String(h).toLowerCase()},f.isEngine=function(h){return this.getEngineName(!0)===String(h).toLowerCase()},f.is=function(h,p){return p===void 0&&(p=!1),this.isBrowser(h,p)||this.isOS(h)||this.isPlatform(h)},f.some=function(h){var p=this;return h===void 0&&(h=[]),h.some(function(g){return p.is(g)})},d}();t.default=u,e.exports=t.default},92:function(e,t,r){t.__esModule=!0,t.default=void 0;var n,i=(n=r(17))&&n.__esModule?n:{default:n},o=/version\/(\d+(\.?_?\d+)+)/i,s=[{test:[/gptbot/i],describe:function(a){var c={name:"GPTBot"},u=i.default.getFirstMatch(/gptbot\/(\d+(\.\d+)+)/i,a)||i.default.getFirstMatch(o,a);return u&&(c.version=u),c}},{test:[/chatgpt-user/i],describe:function(a){var c={name:"ChatGPT-User"},u=i.default.getFirstMatch(/chatgpt-user\/(\d+(\.\d+)+)/i,a)||i.default.getFirstMatch(o,a);return u&&(c.version=u),c}},{test:[/oai-searchbot/i],describe:function(a){var c={name:"OAI-SearchBot"},u=i.default.getFirstMatch(/oai-searchbot\/(\d+(\.\d+)+)/i,a)||i.default.getFirstMatch(o,a);return u&&(c.version=u),c}},{test:[/claudebot/i,/claude-web/i,/claude-user/i,/claude-searchbot/i],describe:function(a){var c={name:"ClaudeBot"},u=i.default.getFirstMatch(/(?:claudebot|claude-web|claude-user|claude-searchbot)\/(\d+(\.\d+)+)/i,a)||i.default.getFirstMatch(o,a);return u&&(c.version=u),c}},{test:[/omgilibot/i,/webzio-extended/i],describe:function(a){var c={name:"Omgilibot"},u=i.default.getFirstMatch(/(?:omgilibot|webzio-extended)\/(\d+(\.\d+)+)/i,a)||i.default.getFirstMatch(o,a);return u&&(c.version=u),c}},{test:[/diffbot/i],describe:function(a){var c={name:"Diffbot"},u=i.default.getFirstMatch(/diffbot\/(\d+(\.\d+)+)/i,a)||i.default.getFirstMatch(o,a);return u&&(c.version=u),c}},{test:[/perplexitybot/i],describe:function(a){var c={name:"PerplexityBot"},u=i.default.getFirstMatch(/perplexitybot\/(\d+(\.\d+)+)/i,a)||i.default.getFirstMatch(o,a);return u&&(c.version=u),c}},{test:[/perplexity-user/i],describe:function(a){var c={name:"Perplexity-User"},u=i.default.getFirstMatch(/perplexity-user\/(\d+(\.\d+)+)/i,a)||i.default.getFirstMatch(o,a);return u&&(c.version=u),c}},{test:[/youbot/i],describe:function(a){var c={name:"YouBot"},u=i.default.getFirstMatch(/youbot\/(\d+(\.\d+)+)/i,a)||i.default.getFirstMatch(o,a);return u&&(c.version=u),c}},{test:[/meta-webindexer/i],describe:function(a){var c={name:"Meta-WebIndexer"},u=i.default.getFirstMatch(/meta-webindexer\/(\d+(\.\d+)+)/i,a)||i.default.getFirstMatch(o,a);return u&&(c.version=u),c}},{test:[/meta-externalads/i],describe:function(a){var c={name:"Meta-ExternalAds"},u=i.default.getFirstMatch(/meta-externalads\/(\d+(\.\d+)+)/i,a)||i.default.getFirstMatch(o,a);return u&&(c.version=u),c}},{test:[/meta-externalagent/i],describe:function(a){var c={name:"Meta-ExternalAgent"},u=i.default.getFirstMatch(/meta-externalagent\/(\d+(\.\d+)+)/i,a)||i.default.getFirstMatch(o,a);return u&&(c.version=u),c}},{test:[/meta-externalfetcher/i],describe:function(a){var c={name:"Meta-ExternalFetcher"},u=i.default.getFirstMatch(/meta-externalfetcher\/(\d+(\.\d+)+)/i,a)||i.default.getFirstMatch(o,a);return u&&(c.version=u),c}},{test:[/googlebot/i],describe:function(a){var c={name:"Googlebot"},u=i.default.getFirstMatch(/googlebot\/(\d+(\.\d+))/i,a)||i.default.getFirstMatch(o,a);return u&&(c.version=u),c}},{test:[/linespider/i],describe:function(a){var c={name:"Linespider"},u=i.default.getFirstMatch(/(?:linespider)(?:-[-\w]+)?[\s/](\d+(\.\d+)+)/i,a)||i.default.getFirstMatch(o,a);return u&&(c.version=u),c}},{test:[/amazonbot/i],describe:function(a){var c={name:"AmazonBot"},u=i.default.getFirstMatch(/amazonbot\/(\d+(\.\d+)+)/i,a)||i.default.getFirstMatch(o,a);return u&&(c.version=u),c}},{test:[/bingbot/i],describe:function(a){var c={name:"BingCrawler"},u=i.default.getFirstMatch(/bingbot\/(\d+(\.\d+)+)/i,a)||i.default.getFirstMatch(o,a);return u&&(c.version=u),c}},{test:[/baiduspider/i],describe:function(a){var c={name:"BaiduSpider"},u=i.default.getFirstMatch(/baiduspider\/(\d+(\.\d+)+)/i,a)||i.default.getFirstMatch(o,a);return u&&(c.version=u),c}},{test:[/duckduckbot/i],describe:function(a){var c={name:"DuckDuckBot"},u=i.default.getFirstMatch(/duckduckbot\/(\d+(\.\d+)+)/i,a)||i.default.getFirstMatch(o,a);return u&&(c.version=u),c}},{test:[/ia_archiver/i],describe:function(a){var c={name:"InternetArchiveCrawler"},u=i.default.getFirstMatch(/ia_archiver\/(\d+(\.\d+)+)/i,a)||i.default.getFirstMatch(o,a);return u&&(c.version=u),c}},{test:[/facebookexternalhit/i,/facebookcatalog/i],describe:function(){return{name:"FacebookExternalHit"}}},{test:[/slackbot/i,/slack-imgProxy/i],describe:function(a){var c={name:"SlackBot"},u=i.default.getFirstMatch(/(?:slackbot|slack-imgproxy)(?:-[-\w]+)?[\s/](\d+(\.\d+)+)/i,a)||i.default.getFirstMatch(o,a);return u&&(c.version=u),c}},{test:[/yahoo!?[\s/]*slurp/i],describe:function(){return{name:"YahooSlurp"}}},{test:[/yandexbot/i,/yandexmobilebot/i],describe:function(){return{name:"YandexBot"}}},{test:[/pingdom/i],describe:function(){return{name:"PingdomBot"}}},{test:[/opera/i],describe:function(a){var c={name:"Opera"},u=i.default.getFirstMatch(o,a)||i.default.getFirstMatch(/(?:opera)[\s/](\d+(\.?_?\d+)+)/i,a);return u&&(c.version=u),c}},{test:[/opr\/|opios/i],describe:function(a){var c={name:"Opera"},u=i.default.getFirstMatch(/(?:opr|opios)[\s/](\S+)/i,a)||i.default.getFirstMatch(o,a);return u&&(c.version=u),c}},{test:[/SamsungBrowser/i],describe:function(a){var c={name:"Samsung Internet for Android"},u=i.default.getFirstMatch(o,a)||i.default.getFirstMatch(/(?:SamsungBrowser)[\s/](\d+(\.?_?\d+)+)/i,a);return u&&(c.version=u),c}},{test:[/Whale/i],describe:function(a){var c={name:"NAVER Whale Browser"},u=i.default.getFirstMatch(o,a)||i.default.getFirstMatch(/(?:whale)[\s/](\d+(?:\.\d+)+)/i,a);return u&&(c.version=u),c}},{test:[/PaleMoon/i],describe:function(a){var c={name:"Pale Moon"},u=i.default.getFirstMatch(o,a)||i.default.getFirstMatch(/(?:PaleMoon)[\s/](\d+(?:\.\d+)+)/i,a);return u&&(c.version=u),c}},{test:[/MZBrowser/i],describe:function(a){var c={name:"MZ Browser"},u=i.default.getFirstMatch(/(?:MZBrowser)[\s/](\d+(?:\.\d+)+)/i,a)||i.default.getFirstMatch(o,a);return u&&(c.version=u),c}},{test:[/focus/i],describe:function(a){var c={name:"Focus"},u=i.default.getFirstMatch(/(?:focus)[\s/](\d+(?:\.\d+)+)/i,a)||i.default.getFirstMatch(o,a);return u&&(c.version=u),c}},{test:[/swing/i],describe:function(a){var c={name:"Swing"},u=i.default.getFirstMatch(/(?:swing)[\s/](\d+(?:\.\d+)+)/i,a)||i.default.getFirstMatch(o,a);return u&&(c.version=u),c}},{test:[/coast/i],describe:function(a){var c={name:"Opera Coast"},u=i.default.getFirstMatch(o,a)||i.default.getFirstMatch(/(?:coast)[\s/](\d+(\.?_?\d+)+)/i,a);return u&&(c.version=u),c}},{test:[/opt\/\d+(?:.?_?\d+)+/i],describe:function(a){var c={name:"Opera Touch"},u=i.default.getFirstMatch(/(?:opt)[\s/](\d+(\.?_?\d+)+)/i,a)||i.default.getFirstMatch(o,a);return u&&(c.version=u),c}},{test:[/yabrowser/i],describe:function(a){var c={name:"Yandex Browser"},u=i.default.getFirstMatch(/(?:yabrowser)[\s/](\d+(\.?_?\d+)+)/i,a)||i.default.getFirstMatch(o,a);return u&&(c.version=u),c}},{test:[/ucbrowser/i],describe:function(a){var c={name:"UC Browser"},u=i.default.getFirstMatch(o,a)||i.default.getFirstMatch(/(?:ucbrowser)[\s/](\d+(\.?_?\d+)+)/i,a);return u&&(c.version=u),c}},{test:[/Maxthon|mxios/i],describe:function(a){var c={name:"Maxthon"},u=i.default.getFirstMatch(o,a)||i.default.getFirstMatch(/(?:Maxthon|mxios)[\s/](\d+(\.?_?\d+)+)/i,a);return u&&(c.version=u),c}},{test:[/epiphany/i],describe:function(a){var c={name:"Epiphany"},u=i.default.getFirstMatch(o,a)||i.default.getFirstMatch(/(?:epiphany)[\s/](\d+(\.?_?\d+)+)/i,a);return u&&(c.version=u),c}},{test:[/puffin/i],describe:function(a){var c={name:"Puffin"},u=i.default.getFirstMatch(o,a)||i.default.getFirstMatch(/(?:puffin)[\s/](\d+(\.?_?\d+)+)/i,a);return u&&(c.version=u),c}},{test:[/sleipnir/i],describe:function(a){var c={name:"Sleipnir"},u=i.default.getFirstMatch(o,a)||i.default.getFirstMatch(/(?:sleipnir)[\s/](\d+(\.?_?\d+)+)/i,a);return u&&(c.version=u),c}},{test:[/k-meleon/i],describe:function(a){var c={name:"K-Meleon"},u=i.default.getFirstMatch(o,a)||i.default.getFirstMatch(/(?:k-meleon)[\s/](\d+(\.?_?\d+)+)/i,a);return u&&(c.version=u),c}},{test:[/micromessenger/i],describe:function(a){var c={name:"WeChat"},u=i.default.getFirstMatch(/(?:micromessenger)[\s/](\d+(\.?_?\d+)+)/i,a)||i.default.getFirstMatch(o,a);return u&&(c.version=u),c}},{test:[/qqbrowser/i],describe:function(a){var c={name:/qqbrowserlite/i.test(a)?"QQ Browser Lite":"QQ Browser"},u=i.default.getFirstMatch(/(?:qqbrowserlite|qqbrowser)[/](\d+(\.?_?\d+)+)/i,a)||i.default.getFirstMatch(o,a);return u&&(c.version=u),c}},{test:[/msie|trident/i],describe:function(a){var c={name:"Internet Explorer"},u=i.default.getFirstMatch(/(?:msie |rv:)(\d+(\.?_?\d+)+)/i,a);return u&&(c.version=u),c}},{test:[/\sedg\//i],describe:function(a){var c={name:"Microsoft Edge"},u=i.default.getFirstMatch(/\sedg\/(\d+(\.?_?\d+)+)/i,a);return u&&(c.version=u),c}},{test:[/edg([ea]|ios)/i],describe:function(a){var c={name:"Microsoft Edge"},u=i.default.getSecondMatch(/edg([ea]|ios)\/(\d+(\.?_?\d+)+)/i,a);return u&&(c.version=u),c}},{test:[/vivaldi/i],describe:function(a){var c={name:"Vivaldi"},u=i.default.getFirstMatch(/vivaldi\/(\d+(\.?_?\d+)+)/i,a);return u&&(c.version=u),c}},{test:[/seamonkey/i],describe:function(a){var c={name:"SeaMonkey"},u=i.default.getFirstMatch(/seamonkey\/(\d+(\.?_?\d+)+)/i,a);return u&&(c.version=u),c}},{test:[/sailfish/i],describe:function(a){var c={name:"Sailfish"},u=i.default.getFirstMatch(/sailfish\s?browser\/(\d+(\.\d+)?)/i,a);return u&&(c.version=u),c}},{test:[/silk/i],describe:function(a){var c={name:"Amazon Silk"},u=i.default.getFirstMatch(/silk\/(\d+(\.?_?\d+)+)/i,a);return u&&(c.version=u),c}},{test:[/phantom/i],describe:function(a){var c={name:"PhantomJS"},u=i.default.getFirstMatch(/phantomjs\/(\d+(\.?_?\d+)+)/i,a);return u&&(c.version=u),c}},{test:[/slimerjs/i],describe:function(a){var c={name:"SlimerJS"},u=i.default.getFirstMatch(/slimerjs\/(\d+(\.?_?\d+)+)/i,a);return u&&(c.version=u),c}},{test:[/blackberry|\bbb\d+/i,/rim\stablet/i],describe:function(a){var c={name:"BlackBerry"},u=i.default.getFirstMatch(o,a)||i.default.getFirstMatch(/blackberry[\d]+\/(\d+(\.?_?\d+)+)/i,a);return u&&(c.version=u),c}},{test:[/(web|hpw)[o0]s/i],describe:function(a){var c={name:"WebOS Browser"},u=i.default.getFirstMatch(o,a)||i.default.getFirstMatch(/w(?:eb)?[o0]sbrowser\/(\d+(\.?_?\d+)+)/i,a);return u&&(c.version=u),c}},{test:[/bada/i],describe:function(a){var c={name:"Bada"},u=i.default.getFirstMatch(/dolfin\/(\d+(\.?_?\d+)+)/i,a);return u&&(c.version=u),c}},{test:[/tizen/i],describe:function(a){var c={name:"Tizen"},u=i.default.getFirstMatch(/(?:tizen\s?)?browser\/(\d+(\.?_?\d+)+)/i,a)||i.default.getFirstMatch(o,a);return u&&(c.version=u),c}},{test:[/qupzilla/i],describe:function(a){var c={name:"QupZilla"},u=i.default.getFirstMatch(/(?:qupzilla)[\s/](\d+(\.?_?\d+)+)/i,a)||i.default.getFirstMatch(o,a);return u&&(c.version=u),c}},{test:[/librewolf/i],describe:function(a){var c={name:"LibreWolf"},u=i.default.getFirstMatch(/(?:librewolf)[\s/](\d+(\.?_?\d+)+)/i,a);return u&&(c.version=u),c}},{test:[/firefox|iceweasel|fxios/i],describe:function(a){var c={name:"Firefox"},u=i.default.getFirstMatch(/(?:firefox|iceweasel|fxios)[\s/](\d+(\.?_?\d+)+)/i,a);return u&&(c.version=u),c}},{test:[/electron/i],describe:function(a){var c={name:"Electron"},u=i.default.getFirstMatch(/(?:electron)\/(\d+(\.?_?\d+)+)/i,a);return u&&(c.version=u),c}},{test:[/sogoumobilebrowser/i,/metasr/i,/se 2\.[x]/i],describe:function(a){var c={name:"Sogou Browser"},u=i.default.getFirstMatch(/(?:sogoumobilebrowser)[\s/](\d+(\.?_?\d+)+)/i,a),d=i.default.getFirstMatch(/(?:chrome|crios|crmo)\/(\d+(\.?_?\d+)+)/i,a),f=i.default.getFirstMatch(/se ([\d.]+)x/i,a),h=u||d||f;return h&&(c.version=h),c}},{test:[/MiuiBrowser/i],describe:function(a){var c={name:"Miui"},u=i.default.getFirstMatch(/(?:MiuiBrowser)[\s/](\d+(\.?_?\d+)+)/i,a);return u&&(c.version=u),c}},{test:function(a){return!!a.hasBrand("DuckDuckGo")||a.test(/\sDdg\/[\d.]+$/i)},describe:function(a,c){var u={name:"DuckDuckGo"};if(c){var d=c.getBrandVersion("DuckDuckGo");if(d)return u.version=d,u}var f=i.default.getFirstMatch(/\sDdg\/([\d.]+)$/i,a);return f&&(u.version=f),u}},{test:function(a){return a.hasBrand("Brave")},describe:function(a,c){var u={name:"Brave"};if(c){var d=c.getBrandVersion("Brave");if(d)return u.version=d,u}return u}},{test:[/chromium/i],describe:function(a){var c={name:"Chromium"},u=i.default.getFirstMatch(/(?:chromium)[\s/](\d+(\.?_?\d+)+)/i,a)||i.default.getFirstMatch(o,a);return u&&(c.version=u),c}},{test:[/chrome|crios|crmo/i],describe:function(a){var c={name:"Chrome"},u=i.default.getFirstMatch(/(?:chrome|crios|crmo)\/(\d+(\.?_?\d+)+)/i,a);return u&&(c.version=u),c}},{test:[/GSA/i],describe:function(a){var c={name:"Google Search"},u=i.default.getFirstMatch(/(?:GSA)\/(\d+(\.?_?\d+)+)/i,a);return u&&(c.version=u),c}},{test:function(a){var c=!a.test(/like android/i),u=a.test(/android/i);return c&&u},describe:function(a){var c={name:"Android Browser"},u=i.default.getFirstMatch(o,a);return u&&(c.version=u),c}},{test:[/playstation 4/i],describe:function(a){var c={name:"PlayStation 4"},u=i.default.getFirstMatch(o,a);return u&&(c.version=u),c}},{test:[/safari|applewebkit/i],describe:function(a){var c={name:"Safari"},u=i.default.getFirstMatch(o,a);return u&&(c.version=u),c}},{test:[/.*/i],describe:function(a){var c=a.search("\\(")!==-1?/^(.*)\/(.*)[ \t]\((.*)/:/^(.*)\/(.*) /;return{name:i.default.getFirstMatch(c,a),version:i.default.getSecondMatch(c,a)}}}];t.default=s,e.exports=t.default},93:function(e,t,r){t.__esModule=!0,t.default=void 0;var n,i=(n=r(17))&&n.__esModule?n:{default:n},o=r(18),s=[{test:[/Roku\/DVP/],describe:function(a){var c=i.default.getFirstMatch(/Roku\/DVP-(\d+\.\d+)/i,a);return{name:o.OS_MAP.Roku,version:c}}},{test:[/windows phone/i],describe:function(a){var c=i.default.getFirstMatch(/windows phone (?:os)?\s?(\d+(\.\d+)*)/i,a);return{name:o.OS_MAP.WindowsPhone,version:c}}},{test:[/windows /i],describe:function(a){var c=i.default.getFirstMatch(/Windows ((NT|XP)( \d\d?.\d)?)/i,a),u=i.default.getWindowsVersionName(c);return{name:o.OS_MAP.Windows,version:c,versionName:u}}},{test:[/Macintosh(.*?) FxiOS(.*?)\//],describe:function(a){var c={name:o.OS_MAP.iOS},u=i.default.getSecondMatch(/(Version\/)(\d[\d.]+)/,a);return u&&(c.version=u),c}},{test:[/macintosh/i],describe:function(a){var c=i.default.getFirstMatch(/mac os x (\d+(\.?_?\d+)+)/i,a).replace(/[_\s]/g,"."),u=i.default.getMacOSVersionName(c),d={name:o.OS_MAP.MacOS,version:c};return u&&(d.versionName=u),d}},{test:[/(ipod|iphone|ipad)/i],describe:function(a){var c=i.default.getFirstMatch(/os (\d+([_\s]\d+)*) like mac os x/i,a).replace(/[_\s]/g,".");return{name:o.OS_MAP.iOS,version:c}}},{test:[/OpenHarmony/i],describe:function(a){var c=i.default.getFirstMatch(/OpenHarmony\s+(\d+(\.\d+)*)/i,a);return{name:o.OS_MAP.HarmonyOS,version:c}}},{test:function(a){var c=!a.test(/like android/i),u=a.test(/android/i);return c&&u},describe:function(a){var c=i.default.getFirstMatch(/android[\s/-](\d+(\.\d+)*)/i,a),u=i.default.getAndroidVersionName(c),d={name:o.OS_MAP.Android,version:c};return u&&(d.versionName=u),d}},{test:[/(web|hpw)[o0]s/i],describe:function(a){var c=i.default.getFirstMatch(/(?:web|hpw)[o0]s\/(\d+(\.\d+)*)/i,a),u={name:o.OS_MAP.WebOS};return c&&c.length&&(u.version=c),u}},{test:[/blackberry|\bbb\d+/i,/rim\stablet/i],describe:function(a){var c=i.default.getFirstMatch(/rim\stablet\sos\s(\d+(\.\d+)*)/i,a)||i.default.getFirstMatch(/blackberry\d+\/(\d+([_\s]\d+)*)/i,a)||i.default.getFirstMatch(/\bbb(\d+)/i,a);return{name:o.OS_MAP.BlackBerry,version:c}}},{test:[/bada/i],describe:function(a){var c=i.default.getFirstMatch(/bada\/(\d+(\.\d+)*)/i,a);return{name:o.OS_MAP.Bada,version:c}}},{test:[/tizen/i],describe:function(a){var c=i.default.getFirstMatch(/tizen[/\s](\d+(\.\d+)*)/i,a);return{name:o.OS_MAP.Tizen,version:c}}},{test:[/linux/i],describe:function(){return{name:o.OS_MAP.Linux}}},{test:[/CrOS/],describe:function(){return{name:o.OS_MAP.ChromeOS}}},{test:[/PlayStation 4/],describe:function(a){var c=i.default.getFirstMatch(/PlayStation 4[/\s](\d+(\.\d+)*)/i,a);return{name:o.OS_MAP.PlayStation4,version:c}}}];t.default=s,e.exports=t.default},94:function(e,t,r){t.__esModule=!0,t.default=void 0;var n,i=(n=r(17))&&n.__esModule?n:{default:n},o=r(18),s=[{test:[/googlebot/i],describe:function(){return{type:o.PLATFORMS_MAP.bot,vendor:"Google"}}},{test:[/linespider/i],describe:function(){return{type:o.PLATFORMS_MAP.bot,vendor:"Line"}}},{test:[/amazonbot/i],describe:function(){return{type:o.PLATFORMS_MAP.bot,vendor:"Amazon"}}},{test:[/gptbot/i],describe:function(){return{type:o.PLATFORMS_MAP.bot,vendor:"OpenAI"}}},{test:[/chatgpt-user/i],describe:function(){return{type:o.PLATFORMS_MAP.bot,vendor:"OpenAI"}}},{test:[/oai-searchbot/i],describe:function(){return{type:o.PLATFORMS_MAP.bot,vendor:"OpenAI"}}},{test:[/baiduspider/i],describe:function(){return{type:o.PLATFORMS_MAP.bot,vendor:"Baidu"}}},{test:[/bingbot/i],describe:function(){return{type:o.PLATFORMS_MAP.bot,vendor:"Bing"}}},{test:[/duckduckbot/i],describe:function(){return{type:o.PLATFORMS_MAP.bot,vendor:"DuckDuckGo"}}},{test:[/claudebot/i,/claude-web/i,/claude-user/i,/claude-searchbot/i],describe:function(){return{type:o.PLATFORMS_MAP.bot,vendor:"Anthropic"}}},{test:[/omgilibot/i,/webzio-extended/i],describe:function(){return{type:o.PLATFORMS_MAP.bot,vendor:"Webz.io"}}},{test:[/diffbot/i],describe:function(){return{type:o.PLATFORMS_MAP.bot,vendor:"Diffbot"}}},{test:[/perplexitybot/i],describe:function(){return{type:o.PLATFORMS_MAP.bot,vendor:"Perplexity AI"}}},{test:[/perplexity-user/i],describe:function(){return{type:o.PLATFORMS_MAP.bot,vendor:"Perplexity AI"}}},{test:[/youbot/i],describe:function(){return{type:o.PLATFORMS_MAP.bot,vendor:"You.com"}}},{test:[/ia_archiver/i],describe:function(){return{type:o.PLATFORMS_MAP.bot,vendor:"Internet Archive"}}},{test:[/meta-webindexer/i],describe:function(){return{type:o.PLATFORMS_MAP.bot,vendor:"Meta"}}},{test:[/meta-externalads/i],describe:function(){return{type:o.PLATFORMS_MAP.bot,vendor:"Meta"}}},{test:[/meta-externalagent/i],describe:function(){return{type:o.PLATFORMS_MAP.bot,vendor:"Meta"}}},{test:[/meta-externalfetcher/i],describe:function(){return{type:o.PLATFORMS_MAP.bot,vendor:"Meta"}}},{test:[/facebookexternalhit/i,/facebookcatalog/i],describe:function(){return{type:o.PLATFORMS_MAP.bot,vendor:"Meta"}}},{test:[/slackbot/i,/slack-imgProxy/i],describe:function(){return{type:o.PLATFORMS_MAP.bot,vendor:"Slack"}}},{test:[/yahoo/i],describe:function(){return{type:o.PLATFORMS_MAP.bot,vendor:"Yahoo"}}},{test:[/yandexbot/i,/yandexmobilebot/i],describe:function(){return{type:o.PLATFORMS_MAP.bot,vendor:"Yandex"}}},{test:[/pingdom/i],describe:function(){return{type:o.PLATFORMS_MAP.bot,vendor:"Pingdom"}}},{test:[/huawei/i],describe:function(a){var c=i.default.getFirstMatch(/(can-l01)/i,a)&&"Nova",u={type:o.PLATFORMS_MAP.mobile,vendor:"Huawei"};return c&&(u.model=c),u}},{test:[/nexus\s*(?:7|8|9|10).*/i],describe:function(){return{type:o.PLATFORMS_MAP.tablet,vendor:"Nexus"}}},{test:[/ipad/i],describe:function(){return{type:o.PLATFORMS_MAP.tablet,vendor:"Apple",model:"iPad"}}},{test:[/Macintosh(.*?) FxiOS(.*?)\//],describe:function(){return{type:o.PLATFORMS_MAP.tablet,vendor:"Apple",model:"iPad"}}},{test:[/kftt build/i],describe:function(){return{type:o.PLATFORMS_MAP.tablet,vendor:"Amazon",model:"Kindle Fire HD 7"}}},{test:[/silk/i],describe:function(){return{type:o.PLATFORMS_MAP.tablet,vendor:"Amazon"}}},{test:[/tablet(?! pc)/i],describe:function(){return{type:o.PLATFORMS_MAP.tablet}}},{test:function(a){var c=a.test(/ipod|iphone/i),u=a.test(/like (ipod|iphone)/i);return c&&!u},describe:function(a){var c=i.default.getFirstMatch(/(ipod|iphone)/i,a);return{type:o.PLATFORMS_MAP.mobile,vendor:"Apple",model:c}}},{test:[/nexus\s*[0-6].*/i,/galaxy nexus/i],describe:function(){return{type:o.PLATFORMS_MAP.mobile,vendor:"Nexus"}}},{test:[/Nokia/i],describe:function(a){var c=i.default.getFirstMatch(/Nokia\s+([0-9]+(\.[0-9]+)?)/i,a),u={type:o.PLATFORMS_MAP.mobile,vendor:"Nokia"};return c&&(u.model=c),u}},{test:[/[^-]mobi/i],describe:function(){return{type:o.PLATFORMS_MAP.mobile}}},{test:function(a){return a.getBrowserName(!0)==="blackberry"},describe:function(){return{type:o.PLATFORMS_MAP.mobile,vendor:"BlackBerry"}}},{test:function(a){return a.getBrowserName(!0)==="bada"},describe:function(){return{type:o.PLATFORMS_MAP.mobile}}},{test:function(a){return a.getBrowserName()==="windows phone"},describe:function(){return{type:o.PLATFORMS_MAP.mobile,vendor:"Microsoft"}}},{test:function(a){var c=Number(String(a.getOSVersion()).split(".")[0]);return a.getOSName(!0)==="android"&&c>=3},describe:function(){return{type:o.PLATFORMS_MAP.tablet}}},{test:function(a){return a.getOSName(!0)==="android"},describe:function(){return{type:o.PLATFORMS_MAP.mobile}}},{test:[/smart-?tv|smarttv/i],describe:function(){return{type:o.PLATFORMS_MAP.tv}}},{test:[/netcast/i],describe:function(){return{type:o.PLATFORMS_MAP.tv}}},{test:function(a){return a.getOSName(!0)==="macos"},describe:function(){return{type:o.PLATFORMS_MAP.desktop,vendor:"Apple"}}},{test:function(a){return a.getOSName(!0)==="windows"},describe:function(){return{type:o.PLATFORMS_MAP.desktop}}},{test:function(a){return a.getOSName(!0)==="linux"},describe:function(){return{type:o.PLATFORMS_MAP.desktop}}},{test:function(a){return a.getOSName(!0)==="playstation 4"},describe:function(){return{type:o.PLATFORMS_MAP.tv}}},{test:function(a){return a.getOSName(!0)==="roku"},describe:function(){return{type:o.PLATFORMS_MAP.tv}}}];t.default=s,e.exports=t.default},95:function(e,t,r){t.__esModule=!0,t.default=void 0;var n,i=(n=r(17))&&n.__esModule?n:{default:n},o=r(18),s=[{test:function(a){return a.getBrowserName(!0)==="microsoft edge"},describe:function(a){if(/\sedg\//i.test(a))return{name:o.ENGINE_MAP.Blink};var c=i.default.getFirstMatch(/edge\/(\d+(\.?_?\d+)+)/i,a);return{name:o.ENGINE_MAP.EdgeHTML,version:c}}},{test:[/trident/i],describe:function(a){var c={name:o.ENGINE_MAP.Trident},u=i.default.getFirstMatch(/trident\/(\d+(\.?_?\d+)+)/i,a);return u&&(c.version=u),c}},{test:function(a){return a.test(/presto/i)},describe:function(a){var c={name:o.ENGINE_MAP.Presto},u=i.default.getFirstMatch(/presto\/(\d+(\.?_?\d+)+)/i,a);return u&&(c.version=u),c}},{test:function(a){var c=a.test(/gecko/i),u=a.test(/like gecko/i);return c&&!u},describe:function(a){var c={name:o.ENGINE_MAP.Gecko},u=i.default.getFirstMatch(/gecko\/(\d+(\.?_?\d+)+)/i,a);return u&&(c.version=u),c}},{test:[/(apple)?webkit\/537\.36/i],describe:function(){return{name:o.ENGINE_MAP.Blink}}},{test:[/(apple)?webkit/i],describe:function(a){var c={name:o.ENGINE_MAP.WebKit},u=i.default.getFirstMatch(/webkit\/(\d+(\.?_?\d+)+)/i,a);return u&&(c.version=u),c}}];t.default=s,e.exports=t.default}})})});var N=A(function(MX){var{Retry:zY,RETRY_MODES:rC}=we(),{HttpRequest:bE,parseUrl:WY}=L(),{InvokeStore:nC}=Fx(),{normalizeProvider:HY}=ge(),{platform:VY,release:GY}=C("os"),{versions:mE,env:iC}=C("process"),{isValidHostLabel:KY,isIpAddress:uC,customEndpointFunctions:JY}=oe(),{EndpointError:QY,resolveEndpoint:YY}=oe();MX.EndpointError=QY;MX.isIpAddress=uC;MX.resolveEndpoint=YY;var{loadConfig:XY,NODE_REGION_CONFIG_OPTIONS:dC,NODE_REGION_CONFIG_FILE_OPTIONS:lC}=P(),{REGION_ENV_NAME:ZY,REGION_INI_NAME:eX,resolveRegionConfig:tX}=P();MX.NODE_REGION_CONFIG_FILE_OPTIONS=lC;MX.NODE_REGION_CONFIG_OPTIONS=dC;MX.REGION_ENV_NAME=ZY;MX.REGION_INI_NAME=eX;MX.resolveRegionConfig=tX;var Fm={warningEmitted:!1},rX=(e)=>{if(e&&!Fm.warningEmitted){if(process.env.AWS_SDK_JS_NODE_VERSION_SUPPORT_WARNING_DISABLED==="true"){Fm.warningEmitted=!0;return}let t=parseInt(e.substring(1,e.indexOf("."))),r=22;if(t<r)Fm.warningEmitted=!0,process.emitWarning(`NodeVersionSupportWarning: The AWS SDK for JavaScript (v3)
19
+ versions published after the first week of January 2027
20
+ will require node >=${r}. You are running node ${e}.
21
+
22
+ To continue receiving updates to AWS services, bug fixes,
23
+ and security updates please upgrade to node >=${r}.
24
+
25
+ More information can be found at: https://a.co/c895JFp`)}},nX=()=>(e,t)=>async(r)=>(t.__retryLongPoll=!0,e(r)),iX={name:"longPollMiddleware",tags:["RETRY"],step:"initialize",override:!0},oX=(e)=>({applyToStack:(t)=>{t.add(nX(),iX)}});function sX(e,t,r){if(!e.$source)e.$source={};return e.$source[t]=r,e}zY.v2026||=typeof process==="object"&&process.env?.AWS_NEW_RETRIES_2026==="true";function oa(e,t,r){if(!e.__aws_sdk_context)e.__aws_sdk_context={features:{}};else if(!e.__aws_sdk_context.features)e.__aws_sdk_context.features={};e.__aws_sdk_context.features[t]=r}function aX(e,t,r){if(!e.$source)e.$source={};return e.$source[t]=r,e}function cX(e){return e}var fC=(e)=>(t)=>async(r)=>{if(!bE.isInstance(r.request))return t(r);let{request:n}=r,{handlerProtocol:i=""}=e.requestHandler.metadata||{};if(i.indexOf("h2")>=0&&!n.headers[":authority"])delete n.headers.host,n.headers[":authority"]=n.hostname+(n.port?":"+n.port:"");else if(!n.headers.host){let o=n.hostname;if(n.port!=null)o+=`:${n.port}`;n.headers.host=o}return t(r)},hC={name:"hostHeaderMiddleware",step:"build",priority:"low",tags:["HOST"],override:!0},uX=(e)=>({applyToStack:(t)=>{t.add(fC(e),hC)}}),pC=()=>(e,t)=>async(r)=>{try{let n=await e(r),{clientName:i,commandName:o,logger:s,dynamoDbDocumentClientOptions:a={}}=t,{overrideInputFilterSensitiveLog:c,overrideOutputFilterSensitiveLog:u}=a,d=c??t.inputFilterSensitiveLog,f=u??t.outputFilterSensitiveLog,{$metadata:h,...p}=n.output;return s?.info?.({clientName:i,commandName:o,input:d(r.input),output:f(p),metadata:h}),n}catch(n){let{clientName:i,commandName:o,logger:s,dynamoDbDocumentClientOptions:a={}}=t,{overrideInputFilterSensitiveLog:c}=a,u=c??t.inputFilterSensitiveLog;throw s?.error?.({clientName:i,commandName:o,input:u(r.input),error:n,metadata:n.$metadata}),n}},mC={name:"loggerMiddleware",tags:["LOGGER"],step:"initialize",override:!0},dX=(e)=>({applyToStack:(t)=>{t.add(pC(),mC)}}),gC={step:"build",tags:["RECURSION_DETECTION","TRACE_CONTEXT_PROPAGATION"],name:"recursionDetectionMiddleware",override:!0,priority:"low"},lX="AWS_LAMBDA_FUNCTION_NAME",fX="_X_AMZN_TRACE_ID",gE="X-Amzn-Trace-Id",_E="traceparent",yC="tracestate",wC="baggage",_C=()=>(e)=>async(t)=>{let{request:r}=t;if(!bE.isInstance(r))return e(t);let n;{let i=Object.keys(r.headers??{}).find((o)=>o.toLowerCase()===gE.toLowerCase())??gE;if(!r.headers.hasOwnProperty(i)){let o=process.env[lX],s=process.env[fX];n??=await nC.getInstanceAsync();let c=n?.getXRayTraceId()??s,u=(d)=>typeof d==="string"&&d.length>0;if(u(o)&&u(c))r.headers[gE]=c}}if(hX(r.headers),!r.headers[_E]){let o=(n??=await nC.getInstanceAsync())?.getTraceparent?.();if(o){r.headers[_E]=o;let s=n?.getTracestate?.();if(s)r.headers[yC]=s;let a=n?.getBaggage?.();if(a)r.headers[wC]=a}}return e(t)};function hX(e){for(let t of Object.keys(e)){let r=t.toLowerCase();if(t!==r&&(r===_E||r===yC||r===wC))e[r]=e[t],delete e[t]}}var pX=(e)=>({applyToStack:(t)=>{t.add(_C(),gC)}}),EE=void 0;function mX(e){if(e===void 0)return!0;return typeof e==="string"&&e.length<=50}function gX(e){let t=HY(e.userAgentAppId??EE),{customUserAgent:r}=e;return Object.assign(e,{customUserAgent:typeof r==="string"?[[r]]:r,userAgentAppId:async()=>{let n=await t();if(!mX(n)){let i=e.logger?.constructor?.name==="NoOpLogger"||!e.logger?console:e.logger;if(typeof n!=="string")i?.warn("userAgentAppId must be a string or undefined.");else if(n.length>50)i?.warn("The provided userAgentAppId exceeds the maximum length of 50 characters.")}return n}})}var bC={partitions:[{id:"aws",outputs:{dnsSuffix:"amazonaws.com",dualStackDnsSuffix:"api.aws",implicitGlobalRegion:"us-east-1",name:"aws",supportsDualStack:!0,supportsFIPS:!0},regionRegex:"^(us|eu|ap|sa|ca|me|af|il|mx)\\-\\w+\\-\\d+$",regions:{"af-south-1":{description:"Africa (Cape Town)"},"ap-east-1":{description:"Asia Pacific (Hong Kong)"},"ap-east-2":{description:"Asia Pacific (Taipei)"},"ap-northeast-1":{description:"Asia Pacific (Tokyo)"},"ap-northeast-2":{description:"Asia Pacific (Seoul)"},"ap-northeast-3":{description:"Asia Pacific (Osaka)"},"ap-south-1":{description:"Asia Pacific (Mumbai)"},"ap-south-2":{description:"Asia Pacific (Hyderabad)"},"ap-southeast-1":{description:"Asia Pacific (Singapore)"},"ap-southeast-2":{description:"Asia Pacific (Sydney)"},"ap-southeast-3":{description:"Asia Pacific (Jakarta)"},"ap-southeast-4":{description:"Asia Pacific (Melbourne)"},"ap-southeast-5":{description:"Asia Pacific (Malaysia)"},"ap-southeast-6":{description:"Asia Pacific (New Zealand)"},"ap-southeast-7":{description:"Asia Pacific (Thailand)"},"aws-global":{description:"aws global region"},"ca-central-1":{description:"Canada (Central)"},"ca-west-1":{description:"Canada West (Calgary)"},"eu-central-1":{description:"Europe (Frankfurt)"},"eu-central-2":{description:"Europe (Zurich)"},"eu-north-1":{description:"Europe (Stockholm)"},"eu-south-1":{description:"Europe (Milan)"},"eu-south-2":{description:"Europe (Spain)"},"eu-west-1":{description:"Europe (Ireland)"},"eu-west-2":{description:"Europe (London)"},"eu-west-3":{description:"Europe (Paris)"},"il-central-1":{description:"Israel (Tel Aviv)"},"me-central-1":{description:"Middle East (UAE)"},"me-south-1":{description:"Middle East (Bahrain)"},"mx-central-1":{description:"Mexico (Central)"},"sa-east-1":{description:"South America (Sao Paulo)"},"us-east-1":{description:"US East (N. Virginia)"},"us-east-2":{description:"US East (Ohio)"},"us-west-1":{description:"US West (N. California)"},"us-west-2":{description:"US West (Oregon)"}}},{id:"aws-cn",outputs:{dnsSuffix:"amazonaws.com.cn",dualStackDnsSuffix:"api.amazonwebservices.com.cn",implicitGlobalRegion:"cn-northwest-1",name:"aws-cn",supportsDualStack:!0,supportsFIPS:!0},regionRegex:"^cn\\-\\w+\\-\\d+$",regions:{"aws-cn-global":{description:"aws-cn global region"},"cn-north-1":{description:"China (Beijing)"},"cn-northwest-1":{description:"China (Ningxia)"}}},{id:"aws-eusc",outputs:{dnsSuffix:"amazonaws.eu",dualStackDnsSuffix:"api.amazonwebservices.eu",implicitGlobalRegion:"eusc-de-east-1",name:"aws-eusc",supportsDualStack:!0,supportsFIPS:!0},regionRegex:"^eusc\\-(de)\\-\\w+\\-\\d+$",regions:{"eusc-de-east-1":{description:"AWS European Sovereign Cloud (Germany)"}}},{id:"aws-iso",outputs:{dnsSuffix:"c2s.ic.gov",dualStackDnsSuffix:"api.aws.ic.gov",implicitGlobalRegion:"us-iso-east-1",name:"aws-iso",supportsDualStack:!0,supportsFIPS:!0},regionRegex:"^us\\-iso\\-\\w+\\-\\d+$",regions:{"aws-iso-global":{description:"aws-iso global region"},"us-iso-east-1":{description:"US ISO East"},"us-iso-west-1":{description:"US ISO WEST"}}},{id:"aws-iso-b",outputs:{dnsSuffix:"sc2s.sgov.gov",dualStackDnsSuffix:"api.aws.scloud",implicitGlobalRegion:"us-isob-east-1",name:"aws-iso-b",supportsDualStack:!0,supportsFIPS:!0},regionRegex:"^us\\-isob\\-\\w+\\-\\d+$",regions:{"aws-iso-b-global":{description:"aws-iso-b global region"},"us-isob-east-1":{description:"US ISOB East (Ohio)"},"us-isob-west-1":{description:"US ISOB West"}}},{id:"aws-iso-e",outputs:{dnsSuffix:"cloud.adc-e.uk",dualStackDnsSuffix:"api.cloud-aws.adc-e.uk",implicitGlobalRegion:"eu-isoe-west-1",name:"aws-iso-e",supportsDualStack:!0,supportsFIPS:!0},regionRegex:"^eu\\-isoe\\-\\w+\\-\\d+$",regions:{"aws-iso-e-global":{description:"aws-iso-e global region"},"eu-isoe-west-1":{description:"EU ISOE West"}}},{id:"aws-iso-f",outputs:{dnsSuffix:"csp.hci.ic.gov",dualStackDnsSuffix:"api.aws.hci.ic.gov",implicitGlobalRegion:"us-isof-south-1",name:"aws-iso-f",supportsDualStack:!0,supportsFIPS:!0},regionRegex:"^us\\-isof\\-\\w+\\-\\d+$",regions:{"aws-iso-f-global":{description:"aws-iso-f global region"},"us-isof-east-1":{description:"US ISOF EAST"},"us-isof-south-1":{description:"US ISOF SOUTH"}}},{id:"aws-us-gov",outputs:{dnsSuffix:"amazonaws.com",dualStackDnsSuffix:"api.aws",implicitGlobalRegion:"us-gov-west-1",name:"aws-us-gov",supportsDualStack:!0,supportsFIPS:!0},regionRegex:"^us\\-gov\\-\\w+\\-\\d+$",regions:{"aws-us-gov-global":{description:"aws-us-gov global region"},"us-gov-east-1":{description:"AWS GovCloud (US-East)"},"us-gov-west-1":{description:"AWS GovCloud (US-West)"}}}],version:"1.1"},EC=bC,SC="",AC=(e)=>{let{partitions:t}=EC;for(let n of t){let{regions:i,outputs:o}=n;for(let[s,a]of Object.entries(i))if(s===e)return{...o,...a}}for(let n of t){let{regionRegex:i,outputs:o}=n;if(new RegExp(i).test(e))return{...o}}let r=t.find((n)=>n.id==="aws");if(!r)throw Error("Provided region was not found in the partition array or regex, and default partition with id 'aws' doesn't exist.");return{...r.outputs}},TC=(e,t="")=>{EC=e,SC=t},yX=()=>{TC(bC,"")},vC=()=>SC,wX=/\d{12}\.ddb/;async function _X(e,t,r){if(r.request?.headers?.["smithy-protocol"]==="rpc-v2-cbor")oa(e,"PROTOCOL_RPC_V2_CBOR","M");if(typeof t.retryStrategy==="function"){let o=await t.retryStrategy();if(typeof o.mode==="string")switch(o.mode){case rC.ADAPTIVE:oa(e,"RETRY_MODE_ADAPTIVE","F");break;case rC.STANDARD:oa(e,"RETRY_MODE_STANDARD","E");break}}if(typeof t.accountIdEndpointMode==="function"){let o=e.endpointV2;if(String(o?.url?.hostname).match(wX))oa(e,"ACCOUNT_ID_ENDPOINT","O");switch(await t.accountIdEndpointMode?.()){case"disabled":oa(e,"ACCOUNT_ID_MODE_DISABLED","Q");break;case"preferred":oa(e,"ACCOUNT_ID_MODE_PREFERRED","P");break;case"required":oa(e,"ACCOUNT_ID_MODE_REQUIRED","R");break}}let i=e.__smithy_context?.selectedHttpAuthScheme?.identity;if(i?.$source){let o=i;if(o.accountId)oa(e,"RESOLVED_ACCOUNT_ID","T");for(let[s,a]of Object.entries(o.$source??{}))oa(e,s,a)}}var oC="user-agent",yE="x-amz-user-agent",sC=" ",wE="/",bX=/[^!$%&'*+\-.^_`|~\w]/g,EX=/[^!$%&'*+\-.^_`|~\w#]/g,aC="-",SX=1024;function AX(e){let t="";for(let r in e){let n=e[r];if(t.length+n.length+1<=SX){if(t.length)t+=","+n;else t+=n;continue}break}return t}var kC=(e)=>(t,r)=>async(n)=>{let{request:i}=n;if(!bE.isInstance(i))return t(n);let{headers:o}=i,s=r?.userAgent?.map($m)||[],a=(await e.defaultUserAgentProvider()).map($m);await _X(r,e,n);let c=r;a.push(`m/${AX(Object.assign({},r.__smithy_context?.features,c.__aws_sdk_context?.features))}`);let u=e?.customUserAgent?.map($m)||[],d=await e.userAgentAppId();if(d)a.push($m(["app",`${d}`]));let f=vC(),h=(f?[f]:[]).concat([...a,...s,...u]).join(sC),p=[...a.filter((g)=>g.startsWith("aws-sdk-")),...u].join(sC);if(e.runtime!=="browser"){if(p)o[yE]=o[yE]?`${o[oC]} ${p}`:p;o[oC]=h}else o[yE]=h;return t({...n,request:i})},$m=(e)=>{let t=e[0].split(wE).map((s)=>s.replace(bX,aC)).join(wE),r=e[1]?.replace(EX,aC),n=t.indexOf(wE),i=t.substring(0,n),o=t.substring(n+1);if(i==="api")o=o.toLowerCase();return[i,o,r].filter((s)=>s&&s.length>0).reduce((s,a,c)=>{switch(c){case 0:return a;case 1:return`${s}/${a}`;default:return`${s}#${a}`}},"")},RC={name:"getUserAgentMiddleware",step:"build",priority:"low",tags:["SET_USER_AGENT","USER_AGENT"],override:!0},TX=(e)=>({applyToStack:(t)=>{t.add(kC(e),RC)}}),vX=()=>{let e=["deno","bun","llrt"];for(let t of e)if(mE[t])return[`md/${t}`,mE[t]];return["md/nodejs",mE.node]},NC={isCrtAvailable:!1},kX=()=>{if(NC.isCrtAvailable)return["md/crt-avail"];return null},xC=({serviceId:e,clientVersion:t})=>{let r=vX();return async(n)=>{let i=[["aws-sdk-js",t],["ua","2.1"],[`os/${VY()}`,GY()],["lang/js"],r],o=kX();if(o)i.push(o);if(e)i.push([`api/${e}`,t]);if(iC.AWS_EXECUTION_ENV)i.push([`exec-env/${iC.AWS_EXECUTION_ENV}`]);let s=await n?.userAgentAppId?.();return s?[...i,[`app/${s}`]]:[...i]}},RX=xC,CC="AWS_SDK_UA_APP_ID",OC="sdk_ua_app_id",NX="sdk-ua-app-id",xX={environmentVariableSelector:(e)=>e[CC],configFileSelector:(e)=>e[OC]??e[NX],default:EE},CX=({serviceId:e,clientVersion:t})=>async(r)=>{let n=tC(),i=n.parse??n.default.parse??(()=>""),o=typeof window<"u"&&window?.navigator?.userAgent?i(window.navigator.userAgent):void 0,s=[["aws-sdk-js",t],["ua","2.1"],[`os/${o?.os?.name||"other"}`,o?.os?.version],["lang/js"],["md/browser",`${o?.browser?.name??"unknown"}_${o?.browser?.version??"unknown"}`]];if(e)s.push([`api/${e}`,t]);let a=await r?.userAgentAppId?.();if(a)s.push([`app/${a}`]);return s},OX={os(e){if(/iPhone|iPad|iPod/.test(e))return"iOS";if(/Macintosh|Mac OS X/.test(e))return"macOS";if(/Windows NT/.test(e))return"Windows";if(/Android/.test(e))return"Android";if(/Linux/.test(e))return"Linux";return},browser(e){if(/EdgiOS|EdgA|Edg\//.test(e))return"Microsoft Edge";if(/Firefox\//.test(e))return"Firefox";if(/Chrome\//.test(e))return"Chrome";if(/Safari\//.test(e))return"Safari";return}},SE=(e,t=!1)=>{if(t){for(let r of e.split("."))if(!SE(r))return!1;return!0}if(!KY(e))return!1;if(e.length<3||e.length>63)return!1;if(e!==e.toLowerCase())return!1;if(uC(e))return!1;return!0},cC=":",IX="/",IC=(e)=>{let t=e.split(cC);if(t.length<6)return null;let[r,n,i,o,s,...a]=t;if(r!=="arn"||n===""||i===""||a.join(cC)==="")return null;let c=a.map((u)=>u.split(IX)).flat();return{partition:n,service:i,region:o,accountId:s,resourceId:c}},DC={isVirtualHostableS3Bucket:SE,parseArn:IC,partition:AC};JY.aws=DC;var DX=(e)=>{if(typeof e.endpointProvider!=="function")throw Error("@aws-sdk/util-endpoint - endpointProvider and endpoint missing in config for this client.");let{endpoint:t}=e;if(t===void 0)e.endpoint=async()=>UC(e.endpointProvider({Region:typeof e.region==="function"?await e.region():e.region,UseDualStack:typeof e.useDualstackEndpoint==="function"?await e.useDualstackEndpoint():e.useDualstackEndpoint,UseFIPS:typeof e.useFipsEndpoint==="function"?await e.useFipsEndpoint():e.useFipsEndpoint,Endpoint:void 0},{logger:e.logger}));return e},UC=(e)=>WY(e.url);function UX(e={}){return XY({...dC,async default(){if(!PC.silence)console.warn("@aws-sdk - WARN - default STS region of us-east-1 used. See @aws-sdk/credential-providers README and set a region explicitly.");return"us-east-1"}},{...lC,...e})}var PC={silence:!1},PX=(e)=>({setRegion(t){e.region=t},region(){return e.region}}),LX=(e)=>({region:e.region()});MX.DEFAULT_UA_APP_ID=EE;MX.NODE_APP_ID_CONFIG_OPTIONS=xX;MX.UA_APP_ID_ENV_NAME=CC;MX.UA_APP_ID_INI_NAME=OC;MX.awsEndpointFunctions=DC;MX.createDefaultUserAgentProvider=xC;MX.createUserAgentStringParsingProvider=CX;MX.crtAvailability=NC;MX.defaultUserAgent=RX;MX.emitWarningIfUnsupportedVersion=rX;MX.fallback=OX;MX.getAwsRegionExtensionConfiguration=PX;MX.getHostHeaderPlugin=uX;MX.getLoggerPlugin=dX;MX.getLongPollPlugin=oX;MX.getRecursionDetectionPlugin=pX;MX.getUserAgentMiddlewareOptions=RC;MX.getUserAgentPlugin=TX;MX.getUserAgentPrefix=vC;MX.hostHeaderMiddleware=fC;MX.hostHeaderMiddlewareOptions=hC;MX.isVirtualHostableS3Bucket=SE;MX.loggerMiddleware=pC;MX.loggerMiddlewareOptions=mC;MX.parseArn=IC;MX.partition=AC;MX.recursionDetectionMiddleware=_C;MX.recursionDetectionMiddlewareOptions=gC;MX.resolveAwsRegionExtensionConfiguration=LX;MX.resolveDefaultAwsRegionalEndpointsConfig=DX;MX.resolveHostHeaderConfig=cX;MX.resolveUserAgentConfig=gX;MX.setCredentialFeature=sX;MX.setFeature=oa;MX.setPartitionInfo=TC;MX.setTokenFeature=aX;MX.state=Fm;MX.stsRegionDefaultResolver=UX;MX.stsRegionWarning=PC;MX.toEndpointV1=UC;MX.useDefaultPartitionInfo=yX;MX.userAgentMiddleware=kC});var DE=A(function(HZ){var{hasOwn:Md,fromUtf8:LC,fromHex:UZ,toHex:Lu,toUint8Array:Jf,isArrayBuffer:PZ}=z(),{normalizeProvider:MC}=q(),{escapeUri:zm,HttpRequest:$C}=L();class FC{format(e){let t=[];for(let i in e){if(!Md(e,i))continue;let o=LC(i);t.push(Uint8Array.from([o.byteLength]),o,this.formatHeaderValue(e[i]))}let r=new Uint8Array(t.reduce((i,o)=>i+o.byteLength,0)),n=0;for(let i of t)r.set(i,n),n+=i.byteLength;return r}formatHeaderValue(e){switch(e.type){case"boolean":return Uint8Array.from([e.value?0:1]);case"byte":return Uint8Array.from([2,e.value]);case"short":let t=new DataView(new ArrayBuffer(3));return t.setUint8(0,3),t.setInt16(1,e.value,!1),new Uint8Array(t.buffer);case"integer":let r=new DataView(new ArrayBuffer(5));return r.setUint8(0,4),r.setInt32(1,e.value,!1),new Uint8Array(r.buffer);case"long":let n=new Uint8Array(9);return n[0]=5,n.set(e.value.bytes,1),n;case"binary":let i=new DataView(new ArrayBuffer(3+e.value.byteLength));i.setUint8(0,6),i.setUint16(1,e.value.byteLength,!1);let o=new Uint8Array(i.buffer);return o.set(e.value,3),o;case"string":let s=LC(e.value),a=new DataView(new ArrayBuffer(3+s.byteLength));a.setUint8(0,7),a.setUint16(1,s.byteLength,!1);let c=new Uint8Array(a.buffer);return c.set(s,3),c;case"timestamp":let u=new Uint8Array(9);return u[0]=8,u.set(vE.fromNumber(e.value.valueOf()).bytes,1),u;case"uuid":if(!LZ.test(e.value))throw Error(`Invalid UUID received: ${e.value}`);let d=new Uint8Array(17);return d[0]=9,d.set(UZ(e.value.replace(/-/g,"")),1),d}}}var qC;(function(e){e[e.boolTrue=0]="boolTrue",e[e.boolFalse=1]="boolFalse",e[e.byte=2]="byte",e[e.short=3]="short",e[e.integer=4]="integer",e[e.long=5]="long",e[e.byteArray=6]="byteArray",e[e.string=7]="string",e[e.timestamp=8]="timestamp",e[e.uuid=9]="uuid"})(qC||(qC={}));var LZ=/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/;class vE{bytes;constructor(e){if(this.bytes=e,e.byteLength!==8)throw Error("Int64 buffers must be exactly 8 bytes")}static fromNumber(e){if(e>9223372036854776000||e<-9223372036854776000)throw Error(`${e} is too large (or, if negative, too small) to represent as an Int64`);let t=new Uint8Array(8);for(let r=7,n=Math.abs(Math.round(e));r>-1&&n>0;r--,n/=256)t[r]=n;if(e<0)BC(t);return new vE(t)}valueOf(){let e=this.bytes.slice(0),t=e[0]&128;if(t)BC(e);return parseInt(Lu(e),16)*(t?-1:1)}toString(){return String(this.valueOf())}}function BC(e){for(let t=0;t<8;t++)e[t]^=255;for(let t=7;t>-1;t--)if(e[t]++,e[t]!==0)break}var zC="X-Amz-Algorithm",WC="X-Amz-Credential",kE="X-Amz-Date",HC="X-Amz-SignedHeaders",VC="X-Amz-Expires",RE="X-Amz-Signature",NE="X-Amz-Security-Token",MZ="X-Amz-Region-Set",xE="authorization",CE=kE.toLowerCase(),GC="date",KC=[xE,CE,GC],JC=RE.toLowerCase(),Km="x-amz-content-sha256",QC=NE.toLowerCase(),qZ="host",YC={authorization:!0,"cache-control":!0,connection:!0,expect:!0,from:!0,"keep-alive":!0,"max-forwards":!0,pragma:!0,referer:!0,te:!0,trailer:!0,"transfer-encoding":!0,upgrade:!0,"user-agent":!0,"x-amzn-trace-id":!0},XC=/^proxy-/,ZC=/^sec-/,BZ=[/^proxy-/i,/^sec-/i],Wm="AWS4-HMAC-SHA256",jZ="AWS4-ECDSA-P256-SHA256",eO="AWS4-HMAC-SHA256-PAYLOAD",tO="UNSIGNED-PAYLOAD",rO=50,OE="aws4_request",nO=604800,iO=({query:e={}})=>{let t=[],r={};for(let n in e){if(!Md(e,n))continue;if(n.toLowerCase()===JC)continue;let i=zm(n);t.push(i);let o=e[n];if(typeof o==="string")r[i]=`${i}=${zm(o)}`;else if(Array.isArray(o))r[i]=o.slice(0).reduce((s,a)=>s.concat([`${i}=${zm(a)}`]),[]).sort().join("&")}return t.sort().map((n)=>r[n]).filter((n)=>n).join("&")},$Z=(e)=>FZ(e).toISOString().replace(/\.\d{3}Z$/,"Z"),FZ=(e)=>{if(typeof e==="number")return new Date(e*1000);if(typeof e==="string"){if(Number(e))return new Date(Number(e)*1000);return new Date(e)}return e};class IE{service;regionProvider;credentialProvider;sha256;uriEscapePath;applyChecksum;constructor({applyChecksum:e,credentials:t,region:r,service:n,sha256:i,uriEscapePath:o=!0}){this.service=n,this.sha256=i,this.uriEscapePath=o,this.applyChecksum=typeof e==="boolean"?e:!0,this.regionProvider=MC(r),this.credentialProvider=MC(t)}createCanonicalRequest(e,t,r){let n=Object.keys(t).sort();return`${e.method}
26
+ ${this.getCanonicalPath(e)}
27
+ ${iO(e)}
28
+ ${n.map((i)=>`${i}:${t[i]}`).join(`
29
+ `)}
30
+
31
+ ${n.join(";")}
32
+ ${r}`}async createStringToSign(e,t,r,n){let i=new this.sha256;i.update(Jf(r));let o=await i.digest();return`${n}
33
+ ${e}
34
+ ${t}
35
+ ${Lu(o)}`}getCanonicalPath({path:e}){if(this.uriEscapePath){let t=[];for(let i of e.split("/")){if(i?.length===0)continue;if(i===".")continue;if(i==="..")t.pop();else t.push(i)}let r=`${e?.startsWith("/")?"/":""}${t.join("/")}${t.length>0&&e?.endsWith("/")?"/":""}`;return zm(r).replace(/%2F/g,"/")}return e}validateResolvedCredentials(e){if(typeof e!=="object"||typeof e.accessKeyId!=="string"||typeof e.secretAccessKey!=="string")throw Error("Resolved credential object is not valid")}formatDate(e){let t=$Z(e).replace(/[-:]/g,"");return{longDate:t,shortDate:t.slice(0,8)}}getCanonicalHeaderList(e){return Object.keys(e).sort().join(";")}}var Ld={},Hm=[],Vm=(e,t,r)=>`${e}/${t}/${r}/${OE}`,oO=async(e,t,r,n,i)=>{let o=await jC(e,t.secretAccessKey,t.accessKeyId),s=`${r}:${n}:${i}:${Lu(o)}:${t.sessionToken}`;if(s in Ld)return Ld[s];Hm.push(s);while(Hm.length>rO)delete Ld[Hm.shift()];let a=`AWS4${t.secretAccessKey}`;for(let c of[r,n,i,OE])a=await jC(e,a,c);return Ld[s]=a},zZ=()=>{Hm.length=0,Object.keys(Ld).forEach((e)=>{delete Ld[e]})},jC=(e,t,r)=>{let n=new e(t);return n.update(Jf(r)),n.digest()},AE=({headers:e},t,r)=>{let n={};for(let i of Object.keys(e).sort()){if(e[i]==null)continue;let o=i.toLowerCase();if(o in YC||t?.has(o)||XC.test(o)||ZC.test(o)){if(!r||r&&!r.has(o))continue}n[o]=e[i].trim().replace(/\s+/g," ")}return n},Gm=async({headers:e,body:t},r)=>{for(let n in e){if(!Md(e,n))continue;if(n.toLowerCase()===Km)return e[n]}if(t==null)return"e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855";else if(typeof t==="string"||ArrayBuffer.isView(t)||PZ(t)){let n=new r;return n.update(Jf(t)),Lu(await n.digest())}return tO},sO=(e,t)=>{e=e.toLowerCase();for(let r in t){if(!Md(t,r))continue;if(e===r.toLowerCase())return!0}return!1},aO=(e,t={})=>{let{headers:r,query:n={}}=$C.clone(e);for(let i in r){if(!Md(r,i))continue;let o=i.toLowerCase();if(o.slice(0,6)==="x-amz-"&&!t.unhoistableHeaders?.has(o)||t.hoistableHeaders?.has(o))n[i]=r[i],delete r[i]}return{...e,headers:r,query:n}},TE=(e)=>{e=$C.clone(e);for(let t in e.headers){if(!Md(e.headers,t))continue;if(KC.indexOf(t.toLowerCase())>-1)delete e.headers[t]}return e};class cO extends IE{headerFormatter=new FC;constructor({applyChecksum:e,credentials:t,region:r,service:n,sha256:i,uriEscapePath:o=!0}){super({applyChecksum:e,credentials:t,region:r,service:n,sha256:i,uriEscapePath:o})}async presign(e,t={}){let{signingDate:r=new Date,expiresIn:n=3600,unsignableHeaders:i,unhoistableHeaders:o,signableHeaders:s,hoistableHeaders:a,signingRegion:c,signingService:u}=t,d=await this.credentialProvider();this.validateResolvedCredentials(d);let f=c??await this.regionProvider(),{longDate:h,shortDate:p}=this.formatDate(r);if(n>nO)return Promise.reject("Signature version 4 presigned URLs must have an expiration date less than one week in the future");let g=Vm(p,f,u??this.service),_=aO(TE(e),{unhoistableHeaders:o,hoistableHeaders:a});if(d.sessionToken)_.query[NE]=d.sessionToken;_.query[zC]=Wm,_.query[WC]=`${d.accessKeyId}/${g}`,_.query[kE]=h,_.query[VC]=n.toString(10);let R=AE(_,i,s);return _.query[HC]=this.getCanonicalHeaderList(R),_.query[RE]=await this.getSignature(h,g,this.getSigningKey(d,f,p,u),this.createCanonicalRequest(_,R,await Gm(e,this.sha256))),_}async sign(e,t){if(typeof e==="string")return this.signString(e,t);else if(e.headers&&e.payload)return this.signEvent(e,t);else if(e.message)return this.signMessage(e,t);else return this.signRequest(e,t)}async signEvent({headers:e,payload:t},{signingDate:r=new Date,priorSignature:n,signingRegion:i,signingService:o,eventStreamCredentials:s}){let a=i??await this.regionProvider(),{shortDate:c,longDate:u}=this.formatDate(r),d=Vm(c,a,o??this.service),f=await Gm({headers:{},body:t},this.sha256),h=new this.sha256;h.update(e);let p=Lu(await h.digest()),g=[eO,u,d,n,p,f].join(`
36
+ `);return this.signString(g,{signingDate:r,signingRegion:a,signingService:o,eventStreamCredentials:s})}async signMessage(e,{signingDate:t=new Date,signingRegion:r,signingService:n,eventStreamCredentials:i}){return this.signEvent({headers:this.headerFormatter.format(e.message.headers),payload:e.message.body},{signingDate:t,signingRegion:r,signingService:n,priorSignature:e.priorSignature,eventStreamCredentials:i}).then((s)=>({message:e.message,signature:s}))}async signString(e,{signingDate:t=new Date,signingRegion:r,signingService:n,eventStreamCredentials:i}={}){let o=i??await this.credentialProvider();this.validateResolvedCredentials(o);let s=r??await this.regionProvider(),{shortDate:a}=this.formatDate(t),c=new this.sha256(await this.getSigningKey(o,s,a,n));return c.update(Jf(e)),Lu(await c.digest())}async signRequest(e,{signingDate:t=new Date,signableHeaders:r,unsignableHeaders:n,signingRegion:i,signingService:o}={}){let s=await this.credentialProvider();this.validateResolvedCredentials(s);let a=i??await this.regionProvider(),c=TE(e),{longDate:u,shortDate:d}=this.formatDate(t),f=Vm(d,a,o??this.service);if(c.headers[CE]=u,s.sessionToken)c.headers[QC]=s.sessionToken;let h=await Gm(c,this.sha256);if(!sO(Km,c.headers)&&this.applyChecksum)c.headers[Km]=h;let p=AE(c,n,r),g=await this.getSignature(u,f,this.getSigningKey(s,a,d,o),this.createCanonicalRequest(c,p,h));return c.headers[xE]=`${Wm} Credential=${s.accessKeyId}/${f}, SignedHeaders=${this.getCanonicalHeaderList(p)}, Signature=${g}`,c}async getSignature(e,t,r,n){let i=await this.createStringToSign(e,t,n,Wm),o=new this.sha256(await r);return o.update(Jf(i)),Lu(await o.digest())}getSigningKey(e,t,r,n){return oO(this.sha256,e,r,t,n||this.service)}}var WZ={SignatureV4a:null};HZ.ALGORITHM_IDENTIFIER=Wm;HZ.ALGORITHM_IDENTIFIER_V4A=jZ;HZ.ALGORITHM_QUERY_PARAM=zC;HZ.ALWAYS_UNSIGNABLE_HEADERS=YC;HZ.AMZ_DATE_HEADER=CE;HZ.AMZ_DATE_QUERY_PARAM=kE;HZ.AUTH_HEADER=xE;HZ.CREDENTIAL_QUERY_PARAM=WC;HZ.DATE_HEADER=GC;HZ.EVENT_ALGORITHM_IDENTIFIER=eO;HZ.EXPIRES_QUERY_PARAM=VC;HZ.GENERATED_HEADERS=KC;HZ.HOST_HEADER=qZ;HZ.KEY_TYPE_IDENTIFIER=OE;HZ.MAX_CACHE_SIZE=rO;HZ.MAX_PRESIGNED_TTL=nO;HZ.PROXY_HEADER_PATTERN=XC;HZ.REGION_SET_PARAM=MZ;HZ.SEC_HEADER_PATTERN=ZC;HZ.SHA256_HEADER=Km;HZ.SIGNATURE_HEADER=JC;HZ.SIGNATURE_QUERY_PARAM=RE;HZ.SIGNED_HEADERS_QUERY_PARAM=HC;HZ.SignatureV4=cO;HZ.SignatureV4Base=IE;HZ.TOKEN_HEADER=QC;HZ.TOKEN_QUERY_PARAM=NE;HZ.UNSIGNABLE_PATTERNS=BZ;HZ.UNSIGNED_PAYLOAD=tO;HZ.clearCredentialCache=zZ;HZ.createScope=Vm;HZ.getCanonicalHeaders=AE;HZ.getCanonicalQuery=iO;HZ.getPayloadHash=Gm;HZ.getSigningKey=oO;HZ.hasHeader=sO;HZ.moveHeadersToQuery=aO;HZ.prepareRequest=TE;HZ.signatureV4aContainer=WZ});var ht=A(function(Iee){var{SignatureV4:Oee,signatureV4aContainer:uO}=DE(),Qf={CrtSignerV4:null},dO="X-Amz-S3session-Token".toLowerCase();class UE extends Oee{async signWithCredentials(e,t,r){let n=lO(t);e.headers[dO]=t.sessionToken;let i=this;return fO(i,n),i.signRequest(e,r??{})}async presignWithCredentials(e,t,r){let n=lO(t);return delete e.headers[dO],e.headers["X-Amz-S3session-Token"]=t.sessionToken,e.query=e.query??{},e.query["X-Amz-S3session-Token"]=t.sessionToken,fO(this,n),this.presign(e,r)}}function lO(e){return{accessKeyId:e.accessKeyId,secretAccessKey:e.secretAccessKey,expiration:e.expiration}}function fO(e,t){let r=e.credentialProvider;e.credentialProvider=()=>(e.credentialProvider=r,Promise.resolve(t))}class hO{sigv4aSigner;sigv4Signer;signerOptions;static sigv4aDependency(){if(typeof Qf.CrtSignerV4==="function")return"crt";else if(typeof uO.SignatureV4a==="function")return"js";return"none"}constructor(e){this.sigv4Signer=new UE(e),this.signerOptions=e}async sign(e,t={}){if(t.signingRegion==="*")return this.getSigv4aSigner().sign(e,t);return this.sigv4Signer.sign(e,t)}async signWithCredentials(e,t,r={}){if(r.signingRegion==="*"){let n=this.getSigv4aSigner(),i=Qf.CrtSignerV4;if(i&&n instanceof i)return n.signWithCredentials(e,t,r);else throw Error(`signWithCredentials with signingRegion '*' is only supported when using the CRT dependency @aws-sdk/signature-v4-crt. Please check whether you have installed the "@aws-sdk/signature-v4-crt" package explicitly. You must also register the package by calling [require("@aws-sdk/signature-v4-crt");] or an ESM equivalent such as [import "@aws-sdk/signature-v4-crt";]. For more information please go to https://github.com/aws/aws-sdk-js-v3#functionality-requiring-aws-common-runtime-crt`)}return this.sigv4Signer.signWithCredentials(e,t,r)}async presign(e,t={}){if(t.signingRegion==="*"){let r=this.getSigv4aSigner(),n=Qf.CrtSignerV4;if(n&&r instanceof n)return r.presign(e,t);else throw Error(`presign with signingRegion '*' is only supported when using the CRT dependency @aws-sdk/signature-v4-crt. Please check whether you have installed the "@aws-sdk/signature-v4-crt" package explicitly. You must also register the package by calling [require("@aws-sdk/signature-v4-crt");] or an ESM equivalent such as [import "@aws-sdk/signature-v4-crt";]. For more information please go to https://github.com/aws/aws-sdk-js-v3#functionality-requiring-aws-common-runtime-crt`)}return this.sigv4Signer.presign(e,t)}async presignWithCredentials(e,t,r={}){if(r.signingRegion==="*")throw Error("Method presignWithCredentials is not supported for [signingRegion=*].");return this.sigv4Signer.presignWithCredentials(e,t,r)}getSigv4aSigner(){if(!this.sigv4aSigner){let e=Qf.CrtSignerV4,t=uO.SignatureV4a;if(this.signerOptions.runtime==="node"){if(!e&&!t)throw Error("Neither CRT nor JS SigV4a implementation is available. Please load either @aws-sdk/signature-v4-crt or @aws-sdk/signature-v4a. For more information please go to https://github.com/aws/aws-sdk-js-v3#functionality-requiring-aws-common-runtime-crt");if(e&&typeof e==="function")this.sigv4aSigner=new e({...this.signerOptions,signingAlgorithm:1});else if(t&&typeof t==="function")this.sigv4aSigner=new t({...this.signerOptions});else throw Error("Available SigV4a implementation is not a valid constructor. Please ensure you've properly imported @aws-sdk/signature-v4-crt or @aws-sdk/signature-v4a.For more information please go to https://github.com/aws/aws-sdk-js-v3#functionality-requiring-aws-common-runtime-crt")}else{if(!t||typeof t!=="function")throw Error("JS SigV4a implementation is not available or not a valid constructor. Please check whether you have installed the @aws-sdk/signature-v4a package explicitly. The CRT implementation is not available for browsers. You must also register the package by calling [require('@aws-sdk/signature-v4a');] or an ESM equivalent such as [import '@aws-sdk/signature-v4a';]. For more information please go to https://github.com/aws/aws-sdk-js-v3#using-javascript-non-crt-implementation-of-sigv4a");this.sigv4aSigner=new t({...this.signerOptions})}}return this.sigv4aSigner}}Iee.SignatureV4MultiRegion=hO;Iee.SignatureV4SignWithCredentials=UE;Iee.signatureV4CrtContainer=Qf});var jO=A(function(xte){var{nv:TO,NumericValue:rh,calculateBodyLength:Lee,generateIdempotencyToken:vO,fromBase64:HE,_parseEpochTimestamp:eh}=z(),{hasOwn:Ki,getSmithyContext:Mee}=Po(),{HttpRequest:qee,collectBody:Bee,SerdeContext:nh,RpcProtocol:jee}=L(),{NormalizedSchema:ts,deref:$ee,TypeRegistry:pO}=le();function Wd(e){return typeof Buffer<"u"?Buffer.alloc(e):new Uint8Array(e)}var ih=Symbol("@smithy/core/cbor::tagSymbol");function VE(e){return e[ih]=!0,e}var kO=typeof Buffer<"u",GE=new TextDecoder,Kr=Wd(0),KE=!1,vs=new DataView(Kr.buffer,Kr.byteOffset,Kr.byteLength),Gt=0;function Fee(e){Kr=e,KE=kO&&Kr instanceof Buffer,vs=new DataView(Kr.buffer,Kr.byteOffset,Kr.byteLength)}function kc(e,t){if(e>=t)throw Error("unexpected end of (decode) payload.");let r=(Kr[e]&224)>>5,n=Kr[e]&31;if(n===31&&2<=r&&r<=5)return zee(e,t);switch(r){case 0:case 1:case 6:{let i,o;if(n<24)i=n,o=1;else switch(n){case 24:if(t-e<2)sa(1);i=Kr[e+1],o=2;break;case 25:if(t-e<3)sa(2);i=vs.getUint16(e+1),o=3;break;case 26:if(t-e<5)sa(4);i=vs.getUint32(e+1),o=5;break;case 27:if(t-e<9)sa(8);{let s=vs.getUint32(e+1);if(s<2097152)i=s*4294967296+vs.getUint32(e+5);else i=vs.getBigUint64(e+1)}o=9;break;default:QE(n)}if(r===0)return Gt=o,jE(i);else if(r===1){let s;if(typeof i==="bigint")s=BigInt(-1)-i;else s=-1-i;return Gt=o,jE(s)}else return Yee(e,t,n,i,o)}case 3:return th(e,t);case 5:return Hee(e,t);case 4:return Kee(e,t);case 2:return JE(e,t);default:return Xee(e,t)}}function zee(e,t){let r=(Kr[e]&224)>>5;if((Kr[e]&31)===31)switch(r){case 3:return tte(e,t);case 5:return Zee(e,t);case 4:return ete(e,t);case 2:return rte(e,t)}}function Wee(e,t){let r=e>>7,n=(e&124)>>2,i=(e&3)<<8|t,o=r===0?1:-1;if(n===0){if(i===0)return 0;return o*(Math.pow(2,-14)*(i/1024))}else if(n===31){if(i===0)return o*(1/0);return NaN}return o*(Math.pow(2,n-15)*(1+i/1024))}function Hee(e,t){let r=oh(e,t);if(r<25)return Gee(e,t,r);return Vee(e,t,r)}function Vee(e,t,r){let n=Gt;e+=n;let i=e,o=Object.create(null);for(let s=0;s<r;++s){let a=th(e,t);if(e+=Gt,(Kr[e]&224)>>5===3)o[a]=th(e,t);else o[a]=kc(e,t);e+=Gt}return Gt=n+(e-i),Object.setPrototypeOf(o,Object.prototype),o}function Gee(e,t,r){let n=Gt;e+=n;let i=e,o={};for(let s=0;s<r;++s){let a=th(e,t);e+=Gt,o[a]=kc(e,t),e+=Gt}return Gt=n+(e-i),o}function Kee(e,t){let r=oh(e,t),n=Gt;e+=n;let i=e,o=Array(r);for(let s=0;s<r;++s)o[s]=kc(e,t),e+=Gt;return Gt=n+(e-i),o}function th(e,t){let r=oh(e,t),n=Gt;if(e+=n,t-e<r)sa(r);if(Gt=n+r,r<24)return Qee(e,r);if(KE)return Kr.toString("utf-8",e,e+r);return GE.decode(Kr.subarray(e,e+r))}var mO=Array(2048),PE=new Uint16Array(2048),Yf=0;function Jee(){Yf=Yf+1&65535}function Qee(e,t){let r=t;for(let s=0;s<t;++s)r=r*31+Kr[e+s]|0;let n=r>>>0&2047,i=mO[n];if(i!==void 0){if(i.length===t){let s=!0;for(let a=0;a<t;++a)if(i.charCodeAt(a)!==Kr[e+a]){s=!1;break}if(s)return PE[n]=Yf,i}}let o=KE?Kr.toString("utf-8",e,e+t):GE.decode(Kr.subarray(e,e+t));if(PE[n]!==Yf)mO[n]=o,PE[n]=Yf;return o}function JE(e,t){let r=oh(e,t),n=Gt;if(e+=n,t-e<r)sa(r);let i=Kr.subarray(e,e+r);return Gt=n+r,i}function Yee(e,t,r,n,i){if(r===2||r===3){let o=oh(e+i,t),s=BigInt(0),a=e+i+Gt;for(let c=a;c<a+o;++c)s=s<<BigInt(8)|BigInt(Kr[c]);return Gt=i+Gt+o,r===3?-s-BigInt(1):s}else if(r===4){let o=kc(e+i,t),[s,a]=o,c=a<0?-1:1,u=BigInt(c)*BigInt(a),d=String(u),f=a<0?"-":"",h;if(typeof s==="number"&&Math.abs(s)<=268435456){let g=s,_="0".repeat(Math.abs(g)+1)+d;if(h=g===0?_:_.slice(0,_.length+g)+"."+_.slice(g),h=h.replace(/^0+/g,""),h==="")h="0";if(h[0]===".")h="0"+h;h=f+h}else{let g=BigInt(s);if(d.length===1)h=f+d+"e"+String(g);else{let _=g+BigInt(d.length-1);h=f+d[0]+"."+d.slice(1)+"e"+String(_)}}return Gt=i+Gt,TO(h)}else{let o=kc(e+i,t);return Gt=i+Gt,VE({tag:jE(n),value:o})}}function Xee(e,t){let r=Kr[e]&31;switch(r){case 21:case 20:return Gt=1,r===21;case 22:return Gt=1,null;case 23:return Gt=1,null;case 25:if(t-e<3)throw Error("incomplete float16 at end of buf.");return Gt=3,Wee(Kr[e+1],Kr[e+2]);case 26:if(t-e<5)throw Error("incomplete float32 at end of buf.");return Gt=5,vs.getFloat32(e+1);case 27:if(t-e<9)throw Error("incomplete float64 at end of buf.");return Gt=9,vs.getFloat64(e+1);default:QE(r)}}function oh(e,t){let r=Kr[e]&31;if(r<24)return Gt=1,r;switch(r){case 24:if(t-e<2)sa(1);return Gt=2,Kr[e+1];case 25:if(t-e<3)sa(2);return Gt=3,vs.getUint16(e+1);case 26:if(t-e<5)sa(4);return Gt=5,vs.getUint32(e+1);case 27:if(t-e<9)sa(8);return Gt=9,nte(vs.getBigUint64(e+1));default:QE(r)}}function Zee(e,t){e+=1;let r=e,n={};for(;e<t;){if(Kr[e]===255)return Gt=e-r+2,n;let i=th(e,t);e+=Gt,n[i]=kc(e,t),e+=Gt}throw Error("expected break marker.")}function ete(e,t){e+=1;let r=[];for(let n=e;e<t;){if(Kr[e]===255)return Gt=e-n+2,r;r.push(kc(e,t)),e+=Gt}throw Error("expected break marker.")}function tte(e,t){e+=1;let r=[];for(let n=e;e<t;){if(Kr[e]===255){let c=Wd(r.length);if(c.set(r,0),Gt=e-n+2,kO)return c.toString("utf-8",0,c.length);return GE.decode(c)}let i=(Kr[e]&224)>>5,o=Kr[e]&31;if(i!==3)RO(i);if(o===31)throw Error("nested indefinite string.");let s=JE(e,t);e+=Gt;for(let c=0;c<s.length;++c)r.push(s[c])}throw Error("expected break marker.")}function rte(e,t){e+=1;let r=[];for(let n=e;e<t;){if(Kr[e]===255){let c=Wd(r.length);return c.set(r,0),Gt=e-n+2,c}let i=(Kr[e]&224)>>5,o=Kr[e]&31;if(i!==2)RO(i);if(o===31)throw Error("nested indefinite string.");let s=JE(e,t);e+=Gt;for(let c=0;c<s.length;++c)r.push(s[c])}throw Error("expected break marker.")}function jE(e){if(typeof e==="number")return e;let t=Number(e);if(Number.MIN_SAFE_INTEGER<=t&&t<=Number.MAX_SAFE_INTEGER)return t;return e}function nte(e){let t=Number(e);if(t<Number.MIN_SAFE_INTEGER||Number.MAX_SAFE_INTEGER<t)console.warn(Error(`@smithy/core/cbor - truncating BigInt(${e}) to ${t} with loss of precision.`));return t}function sa(e){throw Error(`length ${e} greater than remaining buf len.`)}function QE(e){throw Error(`unexpected minor value ${e}.`)}function RO(e){throw Error(`unexpected major type ${e} in indefinite string.`)}var ite=typeof Buffer<"u",qd=new Map,Xf=0,$E=!1,ote=2048,zt=Wd(ote),es=new DataView(zt.buffer,zt.byteOffset,zt.byteLength),mt=0;function ste(e){let t=[e];while(t.length){let r=t.pop();if(typeof r==="string"){let n=r.length;if(ite)if(Bd(n*3+9),n>23)LE(3,Buffer.byteLength(r)),mt+=zt.write(r,mt);else cte(r);else{let i=n*3;Bd(i+9);let o=mt,a=new TextEncoder().encodeInto(r,zt.subarray(mt+9)).written,c;if(a<24)c=1;else if(a<256)c=2;else if(a<65536)c=3;else if(a<4294967296)c=5;else c=9;if(c<9)zt.copyWithin(o+c,o+9,o+9+a);mt=o,Mu(3,a),mt+=a}continue}if(zt.byteLength-mt<9)Bd(64);if(typeof r==="number"){if(Number.isInteger(r)&&r>=-9007199254740992&&r<=9007199254740991){let n=r>=0,i=n?0:1,o=n?r:-r-1;if(o<24)zt[mt++]=i<<5|o;else if(o<256)zt[mt++]=i<<5|24,zt[mt++]=o;else if(o<65536)zt[mt++]=i<<5|25,zt[mt++]=o>>8,zt[mt++]=o&255;else if(o<4294967296)zt[mt++]=i<<5|26,es.setUint32(mt,o),mt+=4;else{zt[mt++]=i<<5|27;let s=o/4294967296|0,a=o-s*4294967296|0;es.setUint32(mt,s),es.setUint32(mt+4,a),mt+=8}continue}zt[mt++]=251,es.setFloat64(mt,r),mt+=8;continue}else if(typeof r==="bigint"){let n=r>=0,i=n?0:1,o=n?r:-r-BigInt(1);if(o<BigInt("18446744073709551616")){let s=Number(o);if(s<4294967296)Mu(i,s);else zt[mt++]=i<<5|27,es.setBigUint64(mt,o),mt+=8}else{let s=o.toString(2),a=new Uint8Array(Math.ceil(s.length/8)),c=o,u=0;while(a.byteLength-++u>=0)a[a.byteLength-u]=Number(c&BigInt(255)),c>>=BigInt(8);Bd(a.byteLength*2+16),zt[mt++]=n?194:195,LE(2,a.byteLength),zt.set(a,mt),mt+=a.byteLength}continue}else if(r===null){zt[mt++]=246;continue}else if(typeof r==="boolean"){zt[mt++]=224|(r?21:20);continue}else if(typeof r>"u")throw Error("@smithy/core/cbor: client may not serialize undefined value.");else if(Array.isArray(r)){Mu(4,r.length),Bd(r.length*9+64);for(let n=r.length-1;n>=0;--n)t.push(r[n]);continue}else if(typeof r.byteLength==="number"){Bd(r.length*2+9),Mu(2,r.length),zt.set(r,mt),mt+=r.byteLength;continue}else if(typeof r==="object"){if(r instanceof rh){let o=r.string,s=BigInt(0),a=o.search(/[eE]/);if(a!==-1)s=BigInt(o.slice(a+1)),o=o.slice(0,a);let c=o.indexOf("."),u=c===-1?0:o.length-c-1,d=s-BigInt(u),f=BigInt(o.replace(".",""));zt[mt++]=196,Mu(4,2),t.push(f),t.push(d>=-0x20000000000000n&&d<=0x1fffffffffffffn?Number(d):d);continue}if(r[ih])if("tag"in r&&"value"in r){t.push(r.value),LE(6,r.tag);continue}else throw Error("tag encountered with missing fields, need 'tag' and 'value', found: "+JSON.stringify(r));let n=Object.keys(r),i=n.length;Mu(5,i);for(let o=i-1;o>=0;--o)t.push(r[n[o]]),t.push(n[o]);continue}throw Error(`data type ${r?.constructor?.name??typeof r} not compatible for encoding.`)}}function ate(){Xf=Xf+1&65535,$E=!1}function gO(){let e=Wd(mt);return e.set(zt.subarray(0,mt),0),mt=0,e}function FE(e){let t=zt;if(zt=Wd(e),t)if(t.copy)t.copy(zt,0,0,t.byteLength);else zt.set(t,0);es=new DataView(zt.buffer,zt.byteOffset,zt.byteLength)}function cte(e){let t=qd.get(e);if(t!==void 0){zt.set(t.bytes,mt),mt+=t.bytes.length,t.epoch=Xf;return}let r=mt,n=Buffer.byteLength(e);Mu(3,n),mt+=zt.write(e,mt);let i=Uint8Array.prototype.slice.call(zt,r,mt);if(qd.size>=2048){if($E)return;let o=0;for(let[s,a]of qd){if(o>=1024)break;if(a.epoch!==Xf)qd.delete(s),o++}if(o===0){$E=!0;return}}if(qd.size<2048)qd.set(e,{epoch:Xf,bytes:i})}function Bd(e){if(zt.byteLength-mt<e)if(mt<16000000)FE(Math.max(zt.byteLength*4,zt.byteLength+e));else FE(zt.byteLength+e+16000000)}function LE(e,t){if(t<24)zt[mt++]=e<<5|t;else if(t<256)zt[mt++]=e<<5|24,zt[mt++]=t;else if(t<65536)zt[mt++]=e<<5|25,es.setUint16(mt,t),mt+=2;else if(t<4294967296)zt[mt++]=e<<5|26,es.setUint32(mt,t),mt+=4;else zt[mt++]=e<<5|27,es.setBigUint64(mt,typeof t==="bigint"?t:BigInt(t)),mt+=8}function Mu(e,t){if(t<24)zt[mt++]=e<<5|t;else if(t<256)zt[mt++]=e<<5|24,zt[mt++]=t;else if(t<65536)zt[mt++]=e<<5|25,zt[mt++]=t>>8,zt[mt++]=t&255;else if(t<4294967296)zt[mt++]=e<<5|26,es.setUint32(mt,t),mt+=4;else{zt[mt++]=e<<5|27;let r=t/4294967296|0,n=t-r*4294967296|0;es.setUint32(mt,r),es.setUint32(mt+4,n),mt+=8}}var Zm={deserialize(e){return Jee(),Fee(e),kc(0,e.length)},serialize(e){ate();try{return ste(e),gO()}catch(t){throw gO(),t}},resizeEncodingBuffer(e){FE(e)}},NO=(e,t)=>Bee(e,t).then(async(r)=>{if(r.length)try{return Zm.deserialize(r)}catch(n){throw Object.defineProperty(n,"$responseBodyText",{value:t.utf8Encoder(r)}),n}return{}}),Jm=(e)=>VE({tag:1,value:e.getTime()/1000}),ute=async(e,t)=>{let r=await NO(e,t);return r.message=r.message??r.Message,r},xO=(e,t)=>{let r=(i)=>{let o=i;if(typeof o==="number")o=o.toString();if(o.indexOf(",")>=0)o=o.split(",")[0];if(o.indexOf(":")>=0)o=o.split(":")[0];if(o.indexOf("#")>=0)o=o.split("#")[1];return o};if(t.__type!==void 0)return r(t.__type);let n;for(let i in t){if(!Ki(t,i))continue;if(i.toLowerCase()==="code"){n=i;break}}if(n&&t[n]!==void 0)return r(t[n])},dte=(e)=>{if(String(e.headers["smithy-protocol"]).toLowerCase()!=="rpc-v2-cbor")throw Error("Malformed RPCv2 CBOR response, status: "+e.statusCode)},lte=async(e,t,r,n,i)=>{let o=await e.endpoint(),{hostname:s,protocol:a="https",port:c,path:u}=o,d={protocol:a,hostname:s,port:c,method:"POST",path:u.endsWith("/")?u.slice(0,-1)+r:u+r,headers:{...t}};if(n!==void 0)d.hostname=n;if(o.headers)for(let f in o.headers){if(!Ki(o.headers,f))continue;d.headers[f]=o.headers[f]}if(i!==void 0){d.body=i;try{d.headers["content-length"]=String(Lee(i))}catch(f){}}return new qee(d)};class YE extends nh{write(e,t){Ht=0;let r=ts.of(e);$d(r,t,void 0,this.serdeContext)}flush(){let e=Qt.subarray(0,Ht);return Ht=0,Qt=CO(zE),qu=new DataView(Qt.buffer,Qt.byteOffset,Qt.byteLength),e}}var yO=Symbol.for("@smithy/cbor-struct-cache");function XE(e){let t=e.getSchema(),r=t[yO];if(r)return r;let n=[],i=[];for(let[a,c]of e.structIterator())n.push(a),i.push(c);let o=Array(n.length);for(let a=0;a<n.length;++a)o[a]=fte(n[a]);let s={memberNames:n,memberSchemas:i,encodedKeys:o};return t[yO]=s,s}function fte(e){let t;if(eg)t=Buffer.from(e,"utf-8");else t=new TextEncoder().encode(e);let r=t.length,n;if(r<24)n=1;else if(r<256)n=2;else n=3;let i=new Uint8Array(n+r);if(n===1)i[0]=96|r;else if(n===2)i[0]=120,i[1]=r;else i[0]=121,i[1]=r>>8,i[2]=r&255;return i.set(t,n),i}var eg=typeof Buffer<"u",hte=new TextEncoder,zE=2048,Qt=eg?Buffer.allocUnsafe(zE):new Uint8Array(zE),qu=new DataView(Qt.buffer,Qt.byteOffset,Qt.byteLength),Ht=0,wO=2048,jd=new Map,ME=0,_O=!1;function CO(e){return eg?Buffer.allocUnsafe(e):new Uint8Array(e)}function $d(e,t,r,n){if(t==null){if(t===void 0&&e.isIdempotencyToken()){aa(vO());return}Fn(1),Qt[Ht++]=246;return}if(e.isUnitSchema()){Fn(1),Mi(5,0);return}if(typeof t==="object"){if(e.isBlobSchema()){if(t instanceof Uint8Array){Qm(t);return}}if(e.isTimestampSchema()){if(t instanceof Date){WE(t);return}}if(e.isStructSchema()){pte(e,t,n);return}if(Array.isArray(t)&&(e.isListSchema()||e.isDocumentSchema())){bO(e,t,e.isDocumentSchema(),n);return}if(e.isMapSchema()){qE(e,t,!1,n);return}if(t instanceof Date){WE(t);return}if(t instanceof Uint8Array){Qm(t);return}if(t instanceof rh){DO(t);return}if(t[ih]){let o=t;IO(o.tag,o.value);return}if(e.isDocumentSchema()){if(Array.isArray(t))bO(e,t,!0,n);else qE(e,t,!0,n);return}if(e.isBigDecimalSchema()){Fd(t);return}qE(e,t,!0,n);return}if(typeof t==="string"){if(e.isBlobSchema()){let o=(n?.base64Decoder??HE)(t);Qm(o);return}aa(t);return}if(typeof t==="number"){if(Fn(9),Number.isInteger(t)&&t>=-9007199254740992&&t<=9007199254740991)tg(t);else ZE(t);return}if(typeof t==="boolean"){Fn(1),Qt[Ht++]=224|(t?21:20);return}if(typeof t==="bigint"){Xm(t);return}aa(String(t))}function pte(e,t,r){if(e.isUnionSchema()){let f=!1;for(let[h,p]of e.structIterator()){let g=t[h];if(g!=null){Fn(9),Mi(5,1),aa(h),$d(p,g,e,r),f=!0;break}}if(!f){let{$unknown:h}=t;if(Array.isArray(h))Fn(9),Mi(5,1),aa(h[0]),Fd(h[1]);else Fn(9),Mi(5,0)}return}let n=XE(e),{memberNames:i,memberSchemas:o,encodedKeys:s}=n,a=i.length,c;if(a<24)c=1;else if(a<256)c=2;else c=3;Fn(c);let u=Ht;Ht+=c;let d=0;for(let f=0;f<a;++f){let h=t[i[f]];if(h==null&&!o[f].isIdempotencyToken())continue;let p=s[f];Fn(p.length),Qt.set(p,Ht),Ht+=p.length,$d(o[f],h,e,r),++d}if(typeof t.__type==="string")for(let f in t){if(!Ki(t,f))continue;if(!i.includes(f))aa(f),Fd(t[f]),++d}if(c===1)Qt[u]=160|d;else if(c===2)Qt[u]=184,Qt[u+1]=d;else Qt[u]=185,Qt[u+1]=d>>8,Qt[u+2]=d&255}function bO(e,t,r,n){let i=!!e.getMergedTraits().sparse,o=e.getValueSchema();if(r||i){let s=[];for(let a=0;a<t.length;++a){let c=t[a];if(r){if(c!==void 0)s.push(c)}else if(c!=null||i)s.push(c)}Fn(9),Mi(4,s.length);for(let a=0;a<s.length;++a)$d(o,s[a],void 0,n)}else{let s=0;for(let a=0;a<t.length;++a)if(t[a]!=null)++s;Fn(9),Mi(4,s);for(let a=0;a<t.length;++a)if(t[a]!=null)$d(o,t[a],void 0,n)}}function qE(e,t,r,n){let i=!!e.getMergedTraits().sparse,o=e.getValueSchema(),s=[];for(let a in t){if(!Ki(t,a))continue;let c=t[a];if(r?c!==void 0:c!=null||i)s.push(a)}Fn(9),Mi(5,s.length);for(let a=0;a<s.length;++a){let c=s[a];aa(c),$d(o,t[c],void 0,n)}}function Fd(e){if(e==null){Fn(1),Qt[Ht++]=246;return}if(typeof e==="string"){aa(e);return}if(typeof e==="number"){if(Fn(9),Number.isInteger(e)&&e>=-9007199254740992&&e<=9007199254740991)tg(e);else ZE(e);return}if(typeof e==="boolean"){Fn(1),Qt[Ht++]=224|(e?21:20);return}if(typeof e==="bigint"){Xm(e);return}if(e instanceof Uint8Array){Qm(e);return}if(e instanceof Date){WE(e);return}if(e instanceof rh){DO(e);return}if(e[ih]){let t=e;IO(t.tag,t.value);return}if(Array.isArray(e)){Fn(9),Mi(4,e.length);for(let t=0;t<e.length;++t)Fd(e[t]);return}if(typeof e==="object"){let t=Object.keys(e);Fn(9),Mi(5,t.length);for(let r=0;r<t.length;++r)aa(t[r]),Fd(e[t[r]]);return}aa(String(e))}function Fn(e){if(Ht+e>Qt.length){let t=Qt.length*2;while(t<Ht+e)t*=2;let r=CO(t);r.set(Qt.subarray(0,Ht)),Qt=r,qu=new DataView(r.buffer,r.byteOffset,r.byteLength)}}function Mi(e,t){if(t<24)Qt[Ht++]=e<<5|t;else if(t<256)Qt[Ht++]=e<<5|24,Qt[Ht++]=t;else if(t<65536)Qt[Ht++]=e<<5|25,Qt[Ht++]=t>>8,Qt[Ht++]=t&255;else if(t<4294967296)Qt[Ht++]=e<<5|26,qu.setUint32(Ht,t),Ht+=4;else{Qt[Ht++]=e<<5|27;let r=t/4294967296|0,n=t-r*4294967296|0;qu.setUint32(Ht,r),qu.setUint32(Ht+4,n),Ht+=8}}function OO(e,t){let r=Number(t);if(r<4294967296){Mi(e,r);return}Qt[Ht++]=e<<5|27,qu.setBigUint64(Ht,t),Ht+=8}function aa(e){let t=e.length;if(t<=23){let r=jd.get(e);if(r){Fn(r.bytes.length),Qt.set(r.bytes,Ht),Ht+=r.bytes.length,r.epoch=ME;return}let n=Ht;EO(e,t);let i=Ht,o=Uint8Array.prototype.slice.call(Qt,n,i);if(jd.size>=wO){if(_O)return;let s=0;for(let[a,c]of jd){if(s>=1024)break;if(c.epoch!==ME)jd.delete(a),++s}if(s===0){_O=!0;return}}if(jd.size<wO)jd.set(e,{epoch:ME,bytes:o});return}EO(e,t)}function EO(e,t){if(eg){let r=t*3;Fn(r+9);let n=Buffer.byteLength(e);Mi(3,n),Ht+=Qt.write(e,Ht)}else{let r=t*3;Fn(r+9);let n=Ht,o=hte.encodeInto(e,Qt.subarray(n+9)).written,s;if(o<24)s=1;else if(o<256)s=2;else if(o<65536)s=3;else if(o<4294967296)s=5;else s=9;if(s<9)Qt.copyWithin(n+s,n+9,n+9+o);Ht=n,Mi(3,o),Ht+=o}}function ZE(e){Fn(9),Qt[Ht++]=251,qu.setFloat64(Ht,e),Ht+=8}function tg(e){Fn(9);let t=e>=0,r=t?0:1,n=t?e:-e-1;Mi(r,n)}function Xm(e){let t=e>=0,r=t?0:1,n=t?e:-e-BigInt(1);if(n<BigInt("18446744073709551616"))Fn(9),OO(r,n);else{let i=n.toString(2),o=Math.ceil(i.length/8),s=new Uint8Array(o),a=n;for(let c=o-1;c>=0;--c)s[c]=Number(a&BigInt(255)),a>>=BigInt(8);Fn(o+16),Qt[Ht++]=t?194:195,Mi(2,o),Qt.set(s,Ht),Ht+=o}}function Qm(e){Fn(e.length+9),Mi(2,e.length),Qt.set(e,Ht),Ht+=e.length}function IO(e,t){if(Fn(9),typeof e==="bigint")OO(6,e);else Mi(6,e);Fd(t)}function DO(e){let t=e.string,r=BigInt(0),n=t.search(/[eE]/);if(n!==-1)r=BigInt(t.slice(n+1)),t=t.slice(0,n);let i=t.indexOf("."),o=i===-1?0:t.length-i-1,s=r-BigInt(o),a=BigInt(t.replace(".",""));if(Fn(9),Qt[Ht++]=196,Mi(4,2),Fn(9),s>=-0x20000000000000n&&s<=0x1fffffffffffffn)tg(Number(s));else Xm(s);Xm(a)}function WE(e){Fn(18),Mi(6,1);let t=e.getTime()/1000;if(Number.isInteger(t))tg(t);else ZE(t)}class eS extends nh{read(e,t){return yi=t,rS=UO&&t instanceof Buffer,vc=new DataView(t.buffer,t.byteOffset,t.byteLength),Bt=0,Li=t.length,Zf=Zf+1&65535,Lo(ts.of(e))}readValue(e,t){return Ym(ts.of(e),t)}}var UO=typeof Buffer<"u",tS=new TextDecoder,yi=new Uint8Array(0),rS=!1,vc=new DataView(new ArrayBuffer(0)),Bt=0,Li=0,nS=2048,SO=Array(nS),BE=new Uint16Array(nS),Zf=0;function Lo(e){if(Bt>=Li)throw Error("unexpected end of CBOR payload.");let t=(yi[Bt]&224)>>5;if((yi[Bt]&31)===31&&t>=2&&t<=5)return _te(e,t);switch(t){case 0:return Tte();case 1:return vte();case 2:return ig();case 3:return zd();case 4:return mte(e);case 5:return gte(e);case 6:return wte();case 7:return Rte();default:throw Error(`unexpected CBOR major type ${t}.`)}}function mte(e){let t=ng(),r=e.isListSchema()?e.getValueSchema():e,n=Array(t);for(let i=0;i<t;++i)n[i]=Lo(r);return n}function gte(e){let t=ng();if(e.isStructSchema())return yte(e,t,Bt);let r=e.isMapSchema()?e.getValueSchema():e,n={};for(let i=0;i<t;++i){let o=zd();n[o]=Lo(r)}return n}function yte(e,t,r){let n=e.isUnionSchema(),i=XE(e),{memberSchemas:o,encodedKeys:s,memberNames:a}=i,c=s.length,u={},d,f,h=0,p=!1,g=0;for(let _=0;_<t;++_){let R=PO(s,c,g);if(R>=0){if(g=R+1,g>=c)g=0;let O=Lo(o[R]);if(O!=null)u[a[R]]=O}else{let O=zd(),I=Lo(ts.of(15));if(O==="__type"&&typeof I==="string")p=!0;else d=O,f=I,++h}}if(n){let _=!0;for(let R in u){if(!Ki(u,R))continue;_=!1;break}if(_&&h===1)u.$unknown=[d,f]}else if(p){Bt=r;let _=ts.of(15);for(let R=0;R<t;++R){let O=zd(),I=Lo(_);if(!(O in u))u[O]=I}}return u}function wte(e){let t=rg(),r=typeof t==="bigint"?Number(t):t;if(r===1){let o=ts.of(15),s=Lo(o);return eh(s)}if(r===2||r===3){let o=ig(),s=BigInt(0);for(let a=0;a<o.length;++a)s=s<<BigInt(8)|BigInt(o[a]);return r===3?-s-BigInt(1):s}if(r===4){let o=ts.of(15),s=Lo(o),[a,c]=s,u=c<0?-1:1,d=BigInt(u)*BigInt(c),f=String(d),h=c<0?"-":"",p;if(typeof a==="number"&&Math.abs(a)<=268435456){let _=a,R="0".repeat(Math.abs(_)+1)+f;if(p=_===0?R:R.slice(0,R.length+_)+"."+R.slice(_),p=p.replace(/^0+/g,""),p==="")p="0";if(p[0]===".")p="0"+p;p=h+p}else{let _=BigInt(a);if(f.length===1)p=h+f+"e"+String(_);else{let R=_+BigInt(f.length-1);p=h+f[0]+"."+f.slice(1)+"e"+String(R)}}return TO(p)}let n=ts.of(15),i=Lo(n);return{tag:LO(t),value:i}}function _te(e,t){switch(t){case 3:return bte();case 2:return Ete();case 4:return Ste(e);case 5:return Ate(e);default:throw Error(`unexpected indefinite length for major ${t}.`)}}function bte(){Bt+=1;let e=[],t=0;while(Bt<Li){if(yi[Bt]===255){Bt+=1;let n=new Uint8Array(t),i=0;for(let o=0;o<e.length;++o)n.set(e[o],i),i+=e[o].length;if(UO)return Buffer.from(n.buffer,n.byteOffset,n.byteLength).toString("utf-8");return tS.decode(n)}let r=ig();e.push(r),t+=r.length}throw Error("expected break marker.")}function Ete(){Bt+=1;let e=[],t=0;while(Bt<Li){if(yi[Bt]===255){Bt+=1;let n=new Uint8Array(t),i=0;for(let o=0;o<e.length;++o)n.set(e[o],i),i+=e[o].length;return n}let r=ig();e.push(r),t+=r.length}throw Error("expected break marker.")}function Ste(e){Bt+=1;let t=e.isListSchema()?e.getValueSchema():e,r=[];while(Bt<Li){if(yi[Bt]===255)return Bt+=1,r;r.push(Lo(t))}throw Error("expected break marker.")}function Ate(e){if(Bt+=1,e.isStructSchema()){let n=XE(e),{memberSchemas:i,encodedKeys:o,memberNames:s}=n,a=o.length,c=e.isUnionSchema(),u={},d,f,h=0,p=0;while(Bt<Li){if(yi[Bt]===255){if(Bt+=1,c){let _=!0;for(let R in u){if(!Ki(u,R))continue;_=!1;break}if(_&&h===1)u.$unknown=[d,f]}return u}let g=PO(o,a,p);if(g>=0){if(p=g+1,p>=a)p=0;let _=Lo(i[g]);if(_!=null)u[s[g]]=_}else{let _=zd(),R=Lo(ts.of(15));if(_!=="__type")d=_,f=R,++h}}throw Error("expected break marker.")}let t=e.isMapSchema()?e.getValueSchema():e,r={};while(Bt<Li){if(yi[Bt]===255)return Bt+=1,r;let n=zd();r[n]=Lo(t)}throw Error("expected break marker.")}function PO(e,t,r){let n=e[r];if(Bt+n.length<=Li&&AO(Bt,n))return Bt+=n.length,r;for(let i=0;i<t;++i){if(i===r)continue;let o=e[i];if(Bt+o.length<=Li&&AO(Bt,o))return Bt+=o.length,i}return-1}function AO(e,t){let r=t.length;if(yi[e]!==t[0])return!1;for(let n=1;n<r;++n)if(yi[e+n]!==t[n])return!1;return!0}function rg(){let e=yi[Bt]&31;if(e<24)return Bt+=1,e;switch(e){case 24:if(Li-Bt<2)Wa(1);return Bt+=2,yi[Bt-1];case 25:if(Li-Bt<3)Wa(2);return Bt+=3,vc.getUint16(Bt-2);case 26:if(Li-Bt<5)Wa(4);return Bt+=5,vc.getUint32(Bt-4);case 27:{if(Li-Bt<9)Wa(8);Bt+=9;let t=vc.getUint32(Bt-8);if(t<2097152)return t*4294967296+vc.getUint32(Bt-4);return vc.getBigUint64(Bt-8)}default:throw Error(`unexpected minor value ${e}.`)}}function ng(){let e=rg();return typeof e==="bigint"?Number(e):e}function Tte(){let e=rg();return LO(e)}function vte(){let e=rg();if(typeof e==="bigint")return BigInt(-1)-e;return-1-e}function ig(){let e=ng();if(Li-Bt<e)Wa(e);let t=Bt;return Bt+=e,yi.subarray(t,t+e)}function zd(){let e=ng();if(Li-Bt<e)Wa(e);let t=Bt;if(Bt+=e,e<24)return kte(t,e);if(rS)return yi.toString("utf-8",t,t+e);return tS.decode(yi.subarray(t,t+e))}function kte(e,t){let r=t;for(let s=0;s<t;++s)r=r*31+yi[e+s]|0;let n=r>>>0&nS-1,i=SO[n];if(i!==void 0&&i.length===t){let s=!0;for(let a=0;a<t;++a)if(i.charCodeAt(a)!==yi[e+a]){s=!1;break}if(s)return BE[n]=Zf,i}let o=rS?yi.toString("utf-8",e,e+t):tS.decode(yi.subarray(e,e+t));if(BE[n]!==Zf)SO[n]=o,BE[n]=Zf;return o}function Rte(){let e=Bt,t=yi[e]&31;switch(t){case 21:return Bt=e+1,!0;case 20:return Bt=e+1,!1;case 22:return Bt=e+1,null;case 23:return Bt=e+1,null;case 25:{if(Li-e<3)Wa(2);return Bt=e+3,Nte(yi[e+1],yi[e+2])}case 26:{if(Li-e<5)Wa(4);return Bt=e+5,vc.getFloat32(e+1)}case 27:{if(Li-e<9)Wa(8);return Bt=e+9,vc.getFloat64(e+1)}default:throw Error(`unexpected minor value ${t} for major 7.`)}}function Nte(e,t){let r=e>>7,n=(e&124)>>2,i=(e&3)<<8|t,o=r===0?1:-1;if(n===0){if(i===0)return 0;return o*(Math.pow(2,-14)*(i/1024))}else if(n===31){if(i===0)return o*(1/0);return NaN}return o*(Math.pow(2,n-15)*(1+i/1024))}function LO(e){if(typeof e==="number")return e;let t=Number(e);if(Number.MIN_SAFE_INTEGER<=t&&t<=Number.MAX_SAFE_INTEGER)return t;return e}function Wa(e){throw Error(`CBOR: length ${e} greater than remaining buffer length.`)}function Ym(e,t){if(e.isTimestampSchema()){if(typeof t==="number")return eh(t);if(typeof t==="object"&&t!==null){if(t.tag===1&&"value"in t)return eh(t.value)}}if(e.isBlobSchema())return t;if(typeof t>"u"||typeof t==="boolean"||typeof t==="number"||typeof t==="string"||typeof t==="bigint"||typeof t==="symbol")return t;if(typeof t!=="object"||t===null)return t;if("byteLength"in t)return t;if(t instanceof Date)return t;if(t instanceof rh)return t;if(e.isDocumentSchema())return t;if(e.isListSchema()){let n=e.getValueSchema(),i=[];for(let o of t)i.push(Ym(n,o));return i}let r={};if(e.isMapSchema()){let n=e.getValueSchema();for(let i in t){if(!Ki(t,i))continue;r[i]=Ym(n,t[i])}}else if(e.isStructSchema()){let n=e.isUnionSchema(),i;if(n){i=new Set;for(let o in t){if(!Ki(t,o))continue;if(o!=="__type")i.add(o)}}for(let[o,s]of e.structIterator()){if(n)i.delete(o);if(t[o]!=null)r[o]=Ym(s,t[o])}if(n&&i?.size===1){let o=!0;for(let s in r){if(!Ki(r,s))continue;o=!1;break}if(o){let s=i.values().next().value;r.$unknown=[s,t[s]]}}else if(typeof t.__type==="string")for(let o in t){if(!Ki(t,o))continue;if(!(o in r))r[o]=t[o]}}return r}class iS extends nh{createSerializer(){let e=new YE;return e.setSerdeContext(this.serdeContext),e}createDeserializer(){let e=new eS;return e.setSerdeContext(this.serdeContext),e}}class MO extends jee{codec=new iS;serializer=this.codec.createSerializer();deserializer=this.codec.createDeserializer();constructor({defaultNamespace:e,errorTypeRegistries:t}){super({defaultNamespace:e,errorTypeRegistries:t})}getShapeId(){return"smithy.protocols#rpcv2Cbor"}getPayloadCodec(){return this.codec}async serializeRequest(e,t,r){let n=await super.serializeRequest(e,t,r);if(Object.assign(n.headers,{"content-type":this.getDefaultContentType(),"smithy-protocol":"rpc-v2-cbor",accept:this.getDefaultContentType()}),$ee(e.input)==="unit")delete n.body,delete n.headers["content-type"];else{if(!n.body)this.serializer.write(15,{}),n.body=this.serializer.flush();if(n.body instanceof Uint8Array)n.headers["content-length"]=String(n.body.byteLength)}let{service:i,operation:o}=Mee(r),s=`/service/${i}/operation/${o}`;if(n.path.endsWith("/"))n.path+=s.slice(1);else n.path+=s;return n}async deserializeResponse(e,t,r){return super.deserializeResponse(e,t,r)}async handleError(e,t,r,n,i){let o=xO(r,n)??"Unknown",s={$metadata:i,$fault:r.statusCode<=500?"client":"server"},a=this.options.defaultNamespace;if(o.includes("#"))[a]=o.split("#");let c=this.compositeErrorRegistry,u=pO.for(a);c.copyFrom(u);let d;try{d=c.getSchema(o)}catch(R){if(n.Message)n.message=n.Message;let O=pO.for("smithy.ts.sdk.synthetic."+a);c.copyFrom(O);let I=c.getBaseException();if(I){let Ne=c.getErrorCtor(I);throw Object.assign(new Ne({name:o}),s,n)}throw Object.assign(Error(o),s,n)}let f=ts.of(d),h=c.getErrorCtor(d),p=n.message??n.Message??"Unknown",g=new h({}),_={};for(let[R,O]of f.structIterator())_[R]=this.deserializer.readValue(O,n[R]);throw Object.assign(g,s,{$fault:f.getMergedTraits().error,message:p},_)}getDefaultContentType(){return"application/cbor"}}class qO extends nh{value;write(e,t){this.value=this.serialize(e,t)}serialize(e,t){let r=ts.of(e);if(t==null){if(r.isIdempotencyToken())return vO();return t}if(r.isBlobSchema()){if(typeof t==="string")return(this.serdeContext?.base64Decoder??HE)(t);return t}if(r.isTimestampSchema()){if(typeof t==="number"||typeof t==="bigint")return Jm(new Date(Number(t)/1000|0));return Jm(t)}if(typeof t==="function"||typeof t==="object"){let n=t;if(r.isListSchema()&&Array.isArray(n)){let o=!!r.getMergedTraits().sparse,s=[],a=0;for(let c of n){let u=this.serialize(r.getValueSchema(),c);if(u!=null||o)s[a++]=u}return s}if(n instanceof Date)return Jm(n);let i={};if(r.isMapSchema()){let o=!!r.getMergedTraits().sparse;for(let s in n){if(!Ki(n,s))continue;let a=this.serialize(r.getValueSchema(),n[s]);if(a!=null||o)i[s]=a}}else if(r.isStructSchema()){for(let[s,a]of r.structIterator()){let c=this.serialize(a,n[s]);if(c!=null)i[s]=c}if(r.isUnionSchema()&&Array.isArray(n.$unknown)){let[s,a]=n.$unknown;i[s]=a}else if(typeof n.__type==="string")for(let s in n){if(!Ki(n,s))continue;if(!(s in i))i[s]=this.serialize(15,n[s])}}else if(r.isDocumentSchema()){if(Array.isArray(n)){let o=[],s=0;for(let a of n)o[s++]=this.serialize(r.getValueSchema(),a);return o}for(let o in n){if(!Ki(n,o))continue;i[o]=this.serialize(r.getValueSchema(),n[o])}}else if(r.isBigDecimalSchema())return n;return i}return t}flush(){let e=Zm.serialize(this.value);return this.value=void 0,e}}class BO extends nh{read(e,t){let r=Zm.deserialize(t);return this.readValue(e,r)}readValue(e,t){let r=ts.of(e);if(r.isTimestampSchema()){if(typeof t==="number")return eh(t);if(typeof t==="object"){if(t.tag===1&&"value"in t)return eh(t.value)}}if(r.isBlobSchema()){if(typeof t==="string")return(this.serdeContext?.base64Decoder??HE)(t);return t}if(typeof t>"u"||typeof t==="boolean"||typeof t==="number"||typeof t==="string"||typeof t==="bigint"||typeof t==="symbol")return t;else if(typeof t==="object"){if(t===null)return null;if("byteLength"in t)return t;if(t instanceof Date)return t;if(r.isDocumentSchema())return t;if(r.isListSchema()){let i=[],o=r.getValueSchema();for(let s of t){let a=this.readValue(o,s);i.push(a)}return i}let n={};if(r.isMapSchema()){let i=r.getValueSchema();for(let o in t){if(!Ki(t,o))continue;let s=this.readValue(i,t[o]);n[o]=s}}else if(r.isStructSchema()){let i=r.isUnionSchema(),o;if(i){o=new Set;for(let s in t){if(!Ki(t,s))continue;if(s!=="__type")o.add(s)}}for(let[s,a]of r.structIterator()){if(i)o.delete(s);if(t[s]!=null)n[s]=this.readValue(a,t[s])}if(i&&o?.size===1){let s=!0;for(let a in n){if(!Ki(n,a))continue;s=!1;break}if(s){let a=o.values().next().value;n.$unknown=[a,t[a]]}}else if(typeof t.__type==="string")for(let s in t){if(!Ki(t,s))continue;if(!(s in n))n[s]=t[s]}}else if(t instanceof rh)return t;return n}else return t}}xte.CborCodec=iS;xte.CborShapeDeserializer=BO;xte.CborShapeDeserializer2=eS;xte.CborShapeSerializer=qO;xte.CborShapeSerializer2=YE;xte.SmithyRpcV2CborProtocol=MO;xte.buildHttpRpcRequest=lte;xte.cbor=Zm;xte.checkCborResponse=dte;xte.dateToTag=Jm;xte.loadSmithyRpcV2CborErrorCode=xO;xte.parseCborBody=NO;xte.parseCborErrorBody=ute;xte.tag=VE;xte.tagSymbol=ih});var $O=A(function(Xte){var Hte=/[&<>"]/g,Vte={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;"};function Gte(e){return e.replace(Hte,(t)=>Vte[t])}var Kte=/[&"'<>\r\n\u0085\u2028]/g,Jte={"&":"&amp;",'"':"&quot;","'":"&apos;","<":"&lt;",">":"&gt;","\r":"&#x0D;","\n":"&#x0A;","\x85":"&#x85;","\u2028":"&#x2028;"};function Qte(e){return e.replace(Kte,(t)=>Jte[t])}class sS{value;constructor(e){this.value=e}toString(){return Qte(""+this.value)}}class sh{name;children;attributes={};static of(e,t,r){let n=new sh(e);if(t!==void 0)n.addChildNode(new sS(t));if(r!==void 0)n.withName(r);return n}constructor(e,t=[]){this.name=e,this.children=t}withName(e){return this.name=e,this}addAttribute(e,t){return this.attributes[e]=t,this}addChildNode(e){return this.children.push(e),this}removeAttribute(e){return delete this.attributes[e],this}n(e){return this.name=e,this}c(e){return this.children.push(e),this}a(e,t){if(t!=null)this.attributes[e]=t;return this}cc(e,t,r=t){if(e[t]!=null){let n=sh.of(t,e[t]).withName(r);this.c(n)}}l(e,t,r,n){if(e[t]!=null)n().map((o)=>{o.withName(r),this.c(o)})}lc(e,t,r,n){if(e[t]!=null){let i=n(),o=new sh(r);i.map((s)=>{o.c(s)}),this.c(o)}}toString(){let e=Boolean(this.children.length),t=`<${this.name}`,r=this.attributes;for(let n of Object.keys(r)){let i=r[n];if(i!=null)t+=` ${n}="${Gte(""+i)}"`}return t+=!e?"/>":`>${this.children.map((n)=>n.toString()).join("")}</${this.name}>`}}function oS(e){Object.defineProperty(e,"__proto__",{value:void 0,writable:!0,enumerable:!0,configurable:!0})}function Yte(e){return new aS(e).parse()}class aS{x;i=0;z;constructor(e){this.x=e,this.x=e.replace(/\r\n?/g,`
37
+ `),this.z=this.x.length}parse(){let e=this,{z:t}=e;while(e.i<t){if(e.trim(),e.i>=t)break;if(e.isNext("<?"))e.readTo("?>"),e.trim();else if(e.isNext("<!--"))e.readTo("-->"),e.trim();else if(e.isNext("<!DOCTYPE",!1))e.skipDoctype(),e.trim();else if(e.x[e.i]==="<"){let r=e.parseTag();return{[r.tag]:r.value}}else throw Error("@aws-sdk XML parse error: unexpected content.")}throw Error("@aws-sdk XML parse error: no root element.")}isNext(e,t=!0){let r=this;if(t)return r.x.startsWith(e,r.i);return r.x.toLowerCase().startsWith(e.toLowerCase(),r.i)}readTo(e){let t=this,r=t.x.indexOf(e,t.i);if(r===-1)throw Error(`@aws-sdk XML parse error: expected "${e}" not found.`);let n=t.x.slice(t.i,r);return t.i=r+e.length,n}trim(){let e=this;while(e.i<e.z&&` \r
38
+ `.includes(e.x[e.i]))++e.i}readAttrValue(){let e=this,t=e.x[e.i];++e.i;let r="";while(e.i<e.z&&e.x[e.i]!==t)r+=e.x[e.i++];return++e.i,e.decodeEntities(r)}parseTag(){let e=this;++e.i;let t="";while(e.i<e.z&&!` \r
39
+ >/`.includes(e.x[e.i]))t+=e.x[e.i++];let r=!1,n={};while(e.i<e.z){if(e.trim(),">/".includes(e.x[e.i]))break;let u="";while(e.i<e.z&&!`= \r
40
+ >/?`.includes(e.x[e.i]))u+=e.x[e.i++];if(e.trim(),e.x[e.i]!=="=")break;if(++e.i,e.trim(),u==="__proto__")oS(n);n[u]=e.readAttrValue(),r=!0}if(e.i>=e.z)throw Error("@aws-sdk XML parse error: unexpected end of input.");if(e.x[e.i]==="/"){if(++e.i,e.i>=e.z||e.x[e.i]!==">")throw Error("@aws-sdk XML parse error: expected > at the end of self-closing tag.");return++e.i,{tag:t,value:r?n:""}}if(e.x[e.i]!==">")throw Error("@aws-sdk XML parse error: expected > at the end of opening tag.");++e.i;let i=[],o=[],s=!1;while(e.i<e.z){if(e.isNext("</"))break;if(e.x[e.i]==="<")if(e.isNext("<!--"))e.readTo("-->");else if(e.isNext("<![CDATA["))e.i+=9,i.push(e.readTo("]]>"));else if(e.isNext("<?"))e.readTo("?>");else s=!0,o.push(e.parseTag());else{let u="";while(e.i<e.z&&e.x[e.i]!=="<")u+=e.x[e.i++];i.push(e.decodeEntities(u))}}if(!e.isNext("</"))throw Error(`@aws-sdk XML parse error: missing closing tag </${t}>.`);e.i+=2;let a=e.readTo(">").trim();if(a!==t)throw Error(`@aws-sdk XML parse error: mismatched tags <${t}> and </${a}>.`);if(!r&&i.length===0&&!s)return{tag:t,value:""};if(!r&&!s){let u=i.length===1?i[0]:i.join("");if(u.trim()===""&&u.includes(`
41
+ `))return{tag:t,value:""};return{tag:t,value:u}}let c={};for(let u of i){if(u.trim()===""&&u.includes(`
42
+ `))continue;c["#text"]="#text"in c?c["#text"]+u:u}for(let u of o){if(u.tag==="__proto__")oS(c);if(u.tag in c)if(Array.isArray(c[u.tag]))c[u.tag].push(u.value);else c[u.tag]=[c[u.tag],u.value];else c[u.tag]=u.value}for(let[u,d]of Object.entries(n)){if(u==="__proto__")oS(c);c[u]=d}return{tag:t,value:c}}static ENTITIES={amp:"&",lt:"<",gt:">",quot:'"',apos:"'"};skipDoctype(){let e=this;e.i+=9;let t=0;while(e.i<e.z){let r=e.x[e.i];if(r==="[")++t;else if(r==="]")--t;else if(r===">"&&t===0){++e.i;return}++e.i}throw Error("@aws-sdk XML parse error: unclosed DOCTYPE.")}decodeEntities(e){return e.replace(/&(?:#x([0-9a-fA-F]{1,6})|#(\d{1,7})|([a-zA-Z][a-zA-Z0-9]{0,30}));/g,(t,r,n,i)=>{if(r)return String.fromCharCode(parseInt(r,16));if(n)return String.fromCharCode(parseInt(n,10));return aS.ENTITIES[i]??""})}}Xte.XmlNode=sh;Xte.XmlText=sS;Xte.parseXML=Yte});var Fe=A(function(bre){var{SmithyRpcV2CborProtocol:rre,loadSmithyRpcV2CborErrorCode:nre}=jO(),{TypeRegistry:FO,NormalizedSchema:ei,deref:ZO}=le(),{decorateServiceException:zO,getValueFromTextNode:eI}=q(),{collectBody:cg,determineTimestampFormat:Gd,RpcProtocol:tI,HttpBindingProtocol:rI,HttpInterceptingShapeSerializer:nI,HttpInterceptingShapeDeserializer:iI,FromStringShapeDeserializer:ire,extendedEncodeURIComponent:WO}=L(),{NumericValue:Ji,toUtf8:fS,fromBase64:hS,LazyJsonString:lg,parseEpochTimestamp:oI,parseRfc7231DateTime:sI,parseRfc3339DateTimeWithOffset:aI,generateIdempotencyToken:fg,toBase64:Vd,dateToUtcString:ch,expectUnion:ore}=z(),{parseXML:cI,XmlNode:ks,XmlText:HO}=$O();class Kd{queryCompat;errorRegistry;constructor(e=!1){this.queryCompat=e}resolveRestContentType(e,t){let r=t.getMemberSchemas(),n=Object.values(r).find((i)=>!!i.getMergedTraits().httpPayload);if(n){let i=n.getMergedTraits().mediaType;if(i)return i;else if(n.isStringSchema())return"text/plain";else if(n.isBlobSchema())return"application/octet-stream";else return e}else if(!t.isUnitSchema()){if(Object.values(r).find((o)=>{let{httpQuery:s,httpQueryParams:a,httpHeader:c,httpLabel:u,httpPrefixHeaders:d}=o.getMergedTraits();return!s&&!a&&!c&&!u&&d===void 0}))return e}}async getErrorSchemaOrThrowBaseException(e,t,r,n,i,o){let s=e;if(e.includes("#"))[,s]=e.split("#");let a={$metadata:i,$fault:r.statusCode<500?"client":"server"};if(!this.errorRegistry)throw Error("@aws-sdk/core/protocols - error handler not initialized.");try{return{errorSchema:o?.(this.errorRegistry,s)??this.errorRegistry.getSchema(e),errorMetadata:a}}catch(c){n.message=n.message??n.Message??"UnknownError";let u=this.errorRegistry,d=u.getBaseException();if(d){let p=u.getErrorCtor(d)??Error;throw this.decorateServiceException(Object.assign(new p({name:s}),a),n)}let f=n,h=f?.message??f?.Message??f?.Error?.Message??f?.Error?.message;throw this.decorateServiceException(Object.assign(Error(h),{name:s},a),n)}}compose(e,t,r){let n=r;if(t.includes("#"))[n]=t.split("#");let i=FO.for(n),o=FO.for("smithy.ts.sdk.synthetic."+r);e.copyFrom(i),e.copyFrom(o),this.errorRegistry=e}decorateServiceException(e,t={}){if(this.queryCompat){let r=e.Message??t.Message,n=zO(e,t);if(r)n.message=r;let i=n.Error??{};i.Type=n.Error?.Type,i.Code=n.Error?.Code,i.Message=n.Error?.message??n.Error?.Message??r,n.Error=i;let o=n.$metadata.requestId;if(o)n.RequestId=o;return n}return zO(e,t)}setQueryCompatError(e,t){let r=t.headers?.["x-amzn-query-error"];if(e!==void 0&&r!=null){let[n,i]=r.split(";"),o=Object.keys(e),s={Code:n,Type:i};e.Code=n,e.Type=i;for(let a=0;a<o.length;a++){let c=o[a];s[c==="message"?"Message":c]=e[c]}delete s.__type,e.Error=s}}queryCompatOutput(e,t){if(e.Error)t.Error=e.Error;if(e.Type)t.Type=e.Type;if(e.Code)t.Code=e.Code}findQueryCompatibleError(e,t){try{return e.getSchema(t)}catch(r){return e.find((n)=>ei.of(n).getMergedTraits().awsQueryError?.[0]===t)}}}class uI extends rre{awsQueryCompatible;mixin;constructor({defaultNamespace:e,errorTypeRegistries:t,awsQueryCompatible:r}){super({defaultNamespace:e,errorTypeRegistries:t});this.awsQueryCompatible=!!r,this.mixin=new Kd(this.awsQueryCompatible)}async serializeRequest(e,t,r){let n=await super.serializeRequest(e,t,r);if(this.awsQueryCompatible)n.headers["x-amzn-query-mode"]="true";return n}async handleError(e,t,r,n,i){if(this.awsQueryCompatible)this.mixin.setQueryCompatError(n,r);let o=(()=>{let p=r.headers["x-amzn-query-error"];if(p&&this.awsQueryCompatible)return p.split(";")[0];return nre(r,n)??"Unknown"})();this.mixin.compose(this.compositeErrorRegistry,o,this.options.defaultNamespace);let{errorSchema:s,errorMetadata:a}=await this.mixin.getErrorSchemaOrThrowBaseException(o,this.options.defaultNamespace,r,n,i,this.awsQueryCompatible?this.mixin.findQueryCompatibleError:void 0),c=ei.of(s),u=n.message??n.Message??"UnknownError",f=new(this.compositeErrorRegistry.getErrorCtor(s)??Error)({}),h={};for(let[p,g]of c.structIterator())if(n[p]!=null)h[p]=this.deserializer.readValue(g,n[p]);if(this.awsQueryCompatible)this.mixin.queryCompatOutput(n,h);throw this.mixin.decorateServiceException(Object.assign(f,a,{$fault:c.getMergedTraits().error,message:u},h),n)}}class Rs{serdeContext;setSerdeContext(e){this.serdeContext=e}}class hg{from;to;keys;constructor(e,t){this.from=e,this.to=t;let r=Object.keys(this.from),n=new Set(r);n.delete("__type"),this.keys=n}mark(e){this.keys.delete(e)}hasUnknown(){return this.keys.size===1&&Object.keys(this.to).length===0}writeUnknown(){if(this.hasUnknown()){let e=this.keys.values().next().value,t=this.from[e];this.to.$unknown=[e,t]}}}var ah;function dI(){if(ah===void 0)try{if(typeof Buffer!=="function")ah=!1;else{let e=JSON.parse(Buffer.from([123,125]));ah=e!==null&&typeof e==="object"}}catch{ah=!1}return ah}function pS(e,t,r){if(r?.source){let n=r.source;if(typeof t==="number")if(t<=Number.MAX_SAFE_INTEGER&&t>=Number.MIN_SAFE_INTEGER){if(are(n,t))return t;return new Ji(n,"bigDecimal")}else{if(sre(n))return new Ji(n,"bigDecimal");if(/[eE]/.test(n))return cre(n);return BigInt(n)}}return t}function sre(e){let t=e.indexOf(".");if(t===-1)return!1;let r=e.search(/[eE]/);if(r===-1)return!0;let n=r-t-1;return parseInt(e.slice(r+1),10)<n}function are(e,t){if(e===String(t))return!0;if(Object.is(t,-0))return!0;if(/[eE]/.test(e))return cS(e)===cS(String(t));let r=e.replace(/(\.\d*?)0+$/,"$1").replace(/\.$/,""),n=String(t);if(r===n)return!0;if(/[eE]/.test(n))return r===cS(n);return!1}function cS(e){let t=e.startsWith("-"),r=t?e.slice(1):e,n=r.search(/[eE]/),i;if(n===-1)i=r;else{let o=parseInt(r.slice(n+1),10),s=r.slice(0,n),a=s.indexOf("."),c,u;if(a===-1)c=s,u=s.length;else c=s.slice(0,a)+s.slice(a+1),u=a;c=c.replace(/0+$/,"")||"0";let d=u+o;if(c==="0")i="0";else if(d<=0)i="0."+"0".repeat(-d)+c;else if(d>=c.length)i=c+"0".repeat(d-c.length);else i=c.slice(0,d)+"."+c.slice(d)}if(i.includes("."))i=i.replace(/(\.\d*?)0+$/,"$1").replace(/\.$/,"");return(t?"-":"")+i}function cre(e){let t=e.search(/[eE]/),r=parseInt(e.slice(t+1),10),n=e.startsWith("-"),i=e.slice(n?1:0,t),o=i.indexOf("."),s,a;if(o===-1)s=i,a=r;else{s=i.slice(0,o)+i.slice(o+1);let u=i.length-o-1;a=r-u}s=s.replace(/0+$/,"")||"0";let c=BigInt(s)*10n**BigInt(a+(i.replace(".","").length-s.length));return n?-c:c}var uS=Symbol.for("@aws-sdk/reviver");function mS(e){let t=ei.of(e),r=t.getSchema();if(Array.isArray(r)&&t.isStructSchema()){if(uS in r)return r[uS];let n=ug(t,new Set);return r[uS]=n,n}return ug(t,new Set)}function ug(e,t){let r=e.getSchema();if(t.has(r))return!1;if(t.add(r),e.isBigIntegerSchema()||e.isBigDecimalSchema())return!0;if(e.isStructSchema()){for(let[,n]of e.structIterator())if(ug(n,t))return!0}else if(e.isListSchema()||e.isMapSchema()){if(ug(e.getValueSchema(),t))return!0}else if(e.isDocumentSchema())return!0;return!1}var lI=(e,t)=>cg(e,t).then((r)=>(t?.utf8Encoder??fS)(r));async function pg(e,t,r){let n;if(dI()&&typeof e?.[Symbol.asyncIterator]==="function"){let o=await cg(e,t);if(typeof Buffer==="function")if(Buffer.isBuffer(o))n=o;else n=Buffer.from(o.buffer,o.byteOffset,o.byteLength)}if(!n)n=await lI(e,t);if(n.length===0)return{};let i=r&&mS(r)?pS:void 0;try{return JSON.parse(n,i)}catch(o){if(o?.name==="SyntaxError")Object.defineProperty(o,"$responseBodyText",{value:typeof n==="string"?n:n.toString("utf8")});throw o}}var ure=async(e,t)=>{let r=await pg(e,t);return r.message=r.message??r.Message,r},VO=(e,t)=>Object.keys(e).find((r)=>r.toLowerCase()===t.toLowerCase()),dS=(e)=>{let t=e;if(typeof t==="number")t=t.toString();if(t.indexOf(",")>=0)t=t.split(",")[0];if(t.indexOf(":")>=0)t=t.split(":")[0];if(t.indexOf("#")>=0)t=t.split("#")[1];return t},fI=(e,t)=>pI(e,t,["header","code","type"]),hI=(e,t,r=!1)=>pI(e,t,r?["code","header","type"]:["type","code","header"]),pI=({headers:e},t,r)=>{while(r.length>0)switch(r.shift()){case"header":let i=VO(e??{},"x-amzn-errortype");if(i!==void 0)return dS(e[i]);break;case"code":let o=VO(t??{},"code");if(o&&t[o]!==void 0)return dS(t[o]);break;case"type":if(t?.__type!==void 0)return dS(t.__type);break}};function Rc(e){Object.defineProperty(e,"__proto__",{value:void 0,writable:!0,enumerable:!0,configurable:!0})}class gS extends Rs{settings;constructor(e){super();this.settings=e}async read(e,t){let r=mS(e)?pS:void 0,n;if(typeof t==="string"){if(t.length===0)return{};n=JSON.parse(t,r)}else if(t instanceof Uint8Array&&dI()){if(t.byteLength===0)return{};let i=Buffer.isBuffer(t)?t:Buffer.from(t.buffer,t.byteOffset,t.byteLength);n=JSON.parse(i,r)}else n=await pg(t,this.serdeContext,e);return this._read(e,n)}readObject(e,t){return this._read(e,t)}_read(e,t){let r=t!==null&&typeof t==="object",n=ei.of(e);if(r){if(n.isStructSchema())return this._readStruct(n,t);if(Array.isArray(t)&&n.isListSchema()){let o=n.getValueSchema();if(this.needsTransform(o))for(let s=0;s<t.length;++s)t[s]=this._read(o,t[s]);return t}if(n.isMapSchema()){let o=n.getValueSchema(),s=t;if(this.needsTransform(o))for(let a in s){if(a==="__proto__")Rc(s);s[a]=this._read(o,s[a])}return s}}if(n.isBlobSchema()&&typeof t==="string")return hS(t);let i=n.getMergedTraits().mediaType;if(n.isStringSchema()&&typeof t==="string"&&i){if(i==="application/json"||i.endsWith("+json"))return lg.from(t);return t}if(n.isTimestampSchema()&&t!=null)switch(Gd(n,this.settings)){case 5:return aI(t);case 6:return sI(t);case 7:return oI(t);default:return console.warn("Missing timestamp format, parsing value with Date constructor:",t),new Date(t)}if(n.isBigIntegerSchema()&&(typeof t==="number"||typeof t==="string"))return BigInt(t);if(n.isBigDecimalSchema()&&t!=null){if(t instanceof Ji)return t;let o=t;if(o.type==="bigDecimal"&&"string"in o)return new Ji(o.string,o.type);return new Ji(String(t),"bigDecimal")}if(n.isNumericSchema()&&typeof t==="string"){switch(t){case"Infinity":return 1/0;case"-Infinity":return-1/0;case"NaN":return NaN}return t}if(n.isDocumentSchema()){if(r)if(Array.isArray(t))for(let o=0;o<t.length;++o){let s=t[o];if(!(s instanceof Ji))t[o]=this._read(n,s)}else{let o=t;for(let s in o){if(s==="__proto__")Rc(o);let a=o[s];if(!(a instanceof Ji))o[s]=this._read(n,a)}}}return t}_readStruct(e,t){let r=e.isUnionSchema(),n={},i,o=typeof t.__type==="string",{jsonName:s}=this.settings;if(s&&o)i={};let a;if(r)a=new hg(t,n);for(let[c,u]of e.structIterator()){let d=c;if(s){if(d=u.getMergedTraits().jsonName??d,o)i[d]=c}if(r)a.mark(d);if(t[d]!=null)n[c]=this._read(u,t[d])}if(r)a.writeUnknown();else if(o)for(let c in t){let u=t[c],d=s?i[c]??c:c;if(!(d in n))n[d]=u}return n}needsTransform(e){if(e.isBlobSchema()||e.isTimestampSchema()||e.isBigIntegerSchema()||e.isBigDecimalSchema())return!0;if(e.isDocumentSchema()||e.isStructSchema()||e.isListSchema()||e.isMapSchema())return!0;if(e.isStringSchema()&&e.getMergedTraits().mediaType)return!0;return!1}}class dg extends Uint8Array{string=null;static allocUnsafe(e){if(typeof Buffer==="function"){let t=Buffer.allocUnsafe(e);return new dg(t.buffer,t.byteOffset,t.byteLength)}return new dg(e)}toString(){return this.s()}valueOf(){return this.s()}includes(e,t){if(typeof e==="string")return this.s().includes(e,t);return Uint8Array.prototype.includes.call(this,e,t)}indexOf(e,t){if(typeof e==="string")return this.s().indexOf(e,t);return Uint8Array.prototype.indexOf.call(this,e,t)}lastIndexOf(e,t){if(typeof e==="string")return this.s().lastIndexOf(e,t);let r=Uint8Array.prototype.lastIndexOf;if(t!==void 0)return r.call(this,e,t);return r.call(this,e)}startsWith(e,t){return this.s().startsWith(e,t)}endsWith(e,t){return this.s().endsWith(e,t)}match(e){return this.s().match(e)}replace(e,t){return this.s().replace(e,t)}search(e){return this.s().search(e)}split(e,t){return this.s().split(e,t)}substring(e,t){return this.s().substring(e,t)}trim(){return this.s().trim()}trimStart(){return this.s().trimStart()}trimEnd(){return this.s().trimEnd()}charAt(e){return this.s().charAt(e)}charCodeAt(e){return this.s().charCodeAt(e)}padStart(e,t){return this.s().padStart(e,t)}padEnd(e,t){return this.s().padEnd(e,t)}repeat(e){return this.s().repeat(e)}toUpperCase(){return this.s().toUpperCase()}toLowerCase(){return this.s().toLowerCase()}s(){if(this.string==null){let e=Date.now();if(e>GO+60000)console.warn("@aws-sdk/core/protocols - WARN - JsonCodec2: you have called a string method on a Uint8Array request body. It has been automatically converted to string. In a future version this will throw an error."),GO=e;this.string=fS(this)}return this.string}}var GO=0,og=new TextEncoder,KO=123,JO=125,dre=91,lre=93,Hd=34,sg=58,ag=44,QO=92,fre=new Uint8Array([116,114,117,101]),hre=new Uint8Array([102,97,108,115,101]),pre=new Uint8Array([110,117,108,108]),ca=Array(128).fill(null);ca[8]="b";ca[9]="t";ca[10]="n";ca[12]="f";ca[13]="r";ca[34]='"';ca[92]="\\";for(let e=0;e<32;e++)if(ca[e]===null)ca[e]="u00"+e.toString(16).padStart(2,"0");var YO=2048;function lS(e){return dg.allocUnsafe(e)}class mg extends Rs{settings;json;i=0;rootSchema;rawValue;passthrough=!1;constructor(e){super();this.settings=e,this.json=lS(YO)}write(e,t){if(this.i=0,this.rawValue=t,this.rootSchema=ei.of(e),this.passthrough=this.rootSchema.isBlobSchema()||this.rootSchema.isStringSchema(),!this.passthrough)this.writeValue(this.rootSchema,t,void 0)}writeDiscriminatedDocument(e,t){this.i=0,this.rootSchema=ei.of(e);let r=this.rootSchema;if(r.isStructSchema()&&t!=null&&typeof t==="object"){this.writeValue(r,t,void 0);let n=`"__type":"${r.getName(!0)??"Unknown"}",`,i=n.length;this.ensure(i),this.json.copyWithin(1+i,1,this.i),og.encodeInto(n,this.json.subarray(1)),this.i+=i}else this.writeValue(r,t,void 0)}flush(){this.rootSchema=void 0;let e=this.i;this.i=0;let t=this.rawValue;if(this.rawValue=void 0,e===0)return t;let r=this.json.subarray(0,e);return this.json=lS(YO),r}ensure(e){let{i:t,json:r}=this;if(t+e>r.length){let n=r.length*2;while(n<t+e)n*=2;let i=lS(n);i.set(this.json),this.json=i}}writeAscii(e){let t=e.length;this.ensure(t);let{i:r,json:n}=this;for(let i=0;i<t;++i)n[r]=e.charCodeAt(i),r+=1;this.i=r}writeAsciiQuoted(e){let t=e.length;this.ensure(t+4);let{json:r,i:n}=this;r[n++]=Hd;for(let i=0;i<t;++i)r[n++]=e.charCodeAt(i);r[n++]=Hd,this.i=n}writeJsonString(e){this.ensure(e.length*3+2),this.json[this.i++]=Hd;let t=e.length;for(let r=0;r<t;++r){let n=e.charCodeAt(r);if(n>34&&n<92)this.json[this.i++]=n;else if(n<128){let i=ca[n];if(i!==null){this.ensure(i.length+1),this.json[this.i++]=QO;for(let o=0;o<i.length;o++)this.json[this.i++]=i.charCodeAt(o)}else this.json[this.i++]=n}else if(n>=55296&&n<=56319){let i=r+1<t?e.charCodeAt(r+1):0;if(i>=56320&&i<=57343){this.ensure(4);let{written:o}=og.encodeInto(e.substring(r,r+2),this.json.subarray(this.i));this.i+=o,++r}else this.ensure(6),this.writeUnicodeEscape(n)}else if(n>=56320&&n<=57343)this.ensure(6),this.writeUnicodeEscape(n);else{let{i,json:o}=this;if(n<2048)o[i++]=192|n>>6,o[i++]=128|n&63;else o[i++]=224|n>>12,o[i++]=128|n>>6&63,o[i++]=128|n&63;this.i=i}}this.json[this.i++]=Hd}writeUnicodeEscape(e){let{json:t,i:r}=this;t[r++]=QO,t[r++]=117;let n=e.toString(16).padStart(4,"0");for(let i=0;i<4;++i)t[r++]=n.charCodeAt(i);this.i=r}static B64=(()=>{let t=new Uint8Array(64);for(let r=0;r<64;++r)t[r]="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".charCodeAt(r);return t})();writeBase64(e){let t=Math.ceil(e.length/3)*4;this.ensure(t+2);let r=this.json,n=mg.B64,i=this.i;r[i++]=Hd;let o=e.length,s=o%3,a=o-s;for(let c=0;c<a;c+=3){let u=e[c],d=e[c+1],f=e[c+2];r[i++]=n[u>>2],r[i++]=n[(u&3)<<4|d>>4],r[i++]=n[(d&15)<<2|f>>6],r[i++]=n[f&63]}if(s===2){let c=e[a],u=e[a+1];r[i++]=n[c>>2],r[i++]=n[(c&3)<<4|u>>4],r[i++]=n[(u&15)<<2],r[i++]=61}else if(s===1){let c=e[a];r[i++]=n[c>>2],r[i++]=n[(c&3)<<4],r[i++]=61,r[i++]=61}r[i++]=Hd,this.i=i}writeValue(e,t,r){if(t==null){if(r?.isStructSchema()){if(t===void 0){if(ei.of(e).isIdempotencyToken()){this.writeAsciiQuoted(fg());return}}return}this.ensure(4),this.json.set(pre,this.i),this.i+=4;return}let n=ei.of(e),i=typeof t==="object";if(n.isStringSchema()){let o=n.getMergedTraits().mediaType;if(o){if(o==="application/json"||o.endsWith("+json")){this.writeJsonString(lg.from(t).toString());return}}}if(i){if(n.isStructSchema()){this.writeStruct(n,t);return}if(Array.isArray(t)&&(n.isListSchema()||n.isDocumentSchema())){this.writeList(n,t,n.isDocumentSchema());return}if(n.isMapSchema()){this.writeMap(n,t,!1);return}if(t instanceof Uint8Array&&(n.isBlobSchema()||n.isDocumentSchema())){this.writeBase64(t);return}if(t instanceof Date&&(n.isTimestampSchema()||n.isDocumentSchema())){this.writeTimestamp(n,t);return}if(t instanceof Ji){this.writeAscii(t.string);return}if(n.isDocumentSchema()){if(Array.isArray(t))this.writeList(n,t,!0);else this.writeMap(n,t,!0);return}let o=JSON.stringify(t);this.writeAscii(o);return}if(typeof t==="string"){if(n.isBlobSchema()){let o=(this.serdeContext?.base64Encoder??Vd)(t);this.writeAsciiQuoted(o);return}this.writeJsonString(t);return}if(typeof t==="number"){if(Math.abs(t)===1/0||Number.isNaN(t)){this.writeAsciiQuoted(String(t));return}let o=String(t);this.writeAscii(o);return}if(typeof t==="boolean"){this.ensure(5);let{i:o,json:s}=this;if(t)s.set(fre,o),o+=4;else s.set(hre,o),o+=5;this.i=o;return}if(typeof t==="bigint"){this.writeAscii(t.toString());return}this.writeAscii(String(t))}writeStruct(e,t){this.ensure(2),this.json[this.i++]=KO;let r=!1,n=typeof t.__type==="string",i;if(n)i=new Set;for(let[o,s]of e.structIterator()){let a=t[o];if(a==null&&!s.isIdempotencyToken())continue;if(r)this.ensure(1),this.json[this.i++]=ag;r=!0;let c=this.settings.jsonName?s.getMergedTraits().jsonName??o:o;if(i)i.add(o),i.add(c);this.writeAsciiQuoted(c),this.json[this.i++]=sg,this.writeValue(s,a,e)}if(!r&&e.isUnionSchema()){let{$unknown:o}=t;if(Array.isArray(o)){let[s,a]=o;this.writeAsciiQuoted(s),this.ensure(1),this.json[this.i++]=sg,this.writeValue(15,a,e)}}else if(n)for(let o in t){if(i.has(o))continue;i.add(o);let s=t[o];if(r)this.ensure(1),this.json[this.i++]=ag;r=!0,this.writeAsciiQuoted(o),this.ensure(1),this.json[this.i++]=sg,this.writeValue(15,s,void 0)}this.ensure(1),this.json[this.i++]=JO}writeList(e,t,r){let n=!!e.getMergedTraits().sparse,i=e.getValueSchema();if(!r){if(i.isStringSchema()||i.isNumericSchema()||i.isBooleanSchema()){let s=!1;for(let c=0;c<t.length;++c){let u=t[c];if(Number.isNaN(u)||u===1/0||u===-1/0||u==null&&!n){s=!0;break}}let a;if(!s)a=JSON.stringify(t);else{let c=[];for(let u=0;u<t.length;++u){let d=t[u];if(d==null&&!n)continue;if(Number.isNaN(d)||d===1/0||d===-1/0)c.push(String(d));else c.push(d)}a=JSON.stringify(c)}this.ensure(a.length*3),this.i+=og.encodeInto(a,this.json.subarray(this.i)).written;return}}this.ensure(2),this.json[this.i++]=dre;let o=!1;for(let s=0;s<t.length;++s){let a=t[s];if(r?a===void 0:a==null&&!n)continue;if(o)this.ensure(1),this.json[this.i++]=ag;this.writeValue(i,a,void 0),o=!0}this.ensure(1),this.json[this.i++]=lre}writeMap(e,t,r){let n=!!e.getMergedTraits().sparse,i=e.getValueSchema();if(!r){if(i.isStringSchema()||i.isNumericSchema()||i.isBooleanSchema()){let s;for(let c in t){let u=t[c];if(Number.isNaN(u)||u===1/0||u===-1/0)(s??={})[c]=u,t[c]=String(u);else if(u===null&&!n)(s??={})[c]=null,t[c]=void 0}let a=JSON.stringify(t);if(s)Object.assign(t,s);this.ensure(a.length*3),this.i+=og.encodeInto(a,this.json.subarray(this.i)).written;return}}this.ensure(2),this.json[this.i++]=KO;let o=!0;for(let s in t){let a=t[s];if(r?a===void 0:a==null&&!n)continue;if(!o)this.ensure(1),this.json[this.i++]=ag;o=!1,this.writeJsonString(s),this.ensure(1),this.json[this.i++]=sg,this.writeValue(i,a,void 0)}this.ensure(1),this.json[this.i++]=JO}writeTimestamp(e,t){switch(Gd(e,this.settings)){case 5:{let n=t.toISOString().replace(".000Z","Z");this.writeAsciiQuoted(n);return}case 6:{this.writeAsciiQuoted(ch(t));return}case 7:{let n=String(t.getTime()/1000);this.writeAscii(n);return}default:{let n=String(t.getTime()/1000);this.writeAscii(n);return}}}}class gg extends Rs{settings;constructor(e){super();this.settings=e}createSerializer(){let e=new mg(this.settings);return e.setSerdeContext(this.serdeContext),e}createDeserializer(){let e=new gS(this.settings);return e.setSerdeContext(this.serdeContext),e}}class yg extends tI{serializer;deserializer;serviceTarget;codec;mixin;awsQueryCompatible;constructor({defaultNamespace:e,errorTypeRegistries:t,serviceTarget:r,awsQueryCompatible:n,jsonCodec:i}){super({defaultNamespace:e,errorTypeRegistries:t});this.serviceTarget=r,this.codec=i??new gg({timestampFormat:{useTrait:!0,default:7},jsonName:!1}),this.serializer=this.codec.createSerializer(),this.deserializer=this.codec.createDeserializer(),this.awsQueryCompatible=!!n,this.mixin=new Kd(this.awsQueryCompatible)}async serializeRequest(e,t,r){let n=await super.serializeRequest(e,t,r);if(!n.path.endsWith("/"))n.path+="/";if(n.headers["content-type"]=`application/x-amz-json-${this.getJsonRpcVersion()}`,n.headers["x-amz-target"]=`${this.serviceTarget}.${e.name}`,this.awsQueryCompatible)n.headers["x-amzn-query-mode"]="true";if(ZO(e.input)==="unit"||!n.body)n.body="{}";return n}getPayloadCodec(){return this.codec}async handleError(e,t,r,n,i){let{awsQueryCompatible:o}=this;if(o)this.mixin.setQueryCompatError(n,r);let s=hI(r,n,o)??"Unknown";this.mixin.compose(this.compositeErrorRegistry,s,this.options.defaultNamespace);let{errorSchema:a,errorMetadata:c}=await this.mixin.getErrorSchemaOrThrowBaseException(s,this.options.defaultNamespace,r,n,i,o?this.mixin.findQueryCompatibleError:void 0),u=ei.of(a),d=n.message??n.Message??"UnknownError",h=new(this.compositeErrorRegistry.getErrorCtor(a)??Error)({}),p={},g=this.codec.createDeserializer();for(let[_,R]of u.structIterator())if(n[_]!=null)p[_]=g.readObject(R,n[_]);if(o)this.mixin.queryCompatOutput(n,p);throw this.mixin.decorateServiceException(Object.assign(h,c,{$fault:u.getMergedTraits().error,message:d},p),n)}}class mI extends yg{constructor({defaultNamespace:e,errorTypeRegistries:t,serviceTarget:r,awsQueryCompatible:n,jsonCodec:i}){super({defaultNamespace:e,errorTypeRegistries:t,serviceTarget:r,awsQueryCompatible:n,jsonCodec:i})}getShapeId(){return"aws.protocols#awsJson1_0"}getJsonRpcVersion(){return"1.0"}getDefaultContentType(){return"application/x-amz-json-1.0"}}class gI extends yg{constructor({defaultNamespace:e,errorTypeRegistries:t,serviceTarget:r,awsQueryCompatible:n,jsonCodec:i}){super({defaultNamespace:e,errorTypeRegistries:t,serviceTarget:r,awsQueryCompatible:n,jsonCodec:i})}getShapeId(){return"aws.protocols#awsJson1_1"}getJsonRpcVersion(){return"1.1"}getDefaultContentType(){return"application/x-amz-json-1.1"}}class yI extends rI{serializer;deserializer;codec;mixin=new Kd;constructor({defaultNamespace:e,errorTypeRegistries:t,jsonCodec:r}){super({defaultNamespace:e,errorTypeRegistries:t});let n={timestampFormat:{useTrait:!0,default:7},httpBindings:!0,jsonName:!0};this.codec=r??new gg(n),this.serializer=new nI(this.codec.createSerializer(),n),this.deserializer=new iI(this.codec.createDeserializer(),n)}getShapeId(){return"aws.protocols#restJson1"}getPayloadCodec(){return this.codec}setSerdeContext(e){this.codec.setSerdeContext(e),super.setSerdeContext(e)}async serializeRequest(e,t,r){let n=await super.serializeRequest(e,t,r),i=ei.of(e.input);if(!n.headers["content-type"]){let o=this.mixin.resolveRestContentType(this.getDefaultContentType(),i);if(o)n.headers["content-type"]=o}if(n.body==null&&n.headers["content-type"]===this.getDefaultContentType())n.body="{}";return n}async deserializeResponse(e,t,r){let n=await super.deserializeResponse(e,t,r),i=ei.of(e.output);for(let[o,s]of i.structIterator())if(s.getMemberTraits().httpPayload&&!(o in n))n[o]=null;return n}async handleError(e,t,r,n,i){let o=fI(r,n)??"Unknown";this.mixin.compose(this.compositeErrorRegistry,o,this.options.defaultNamespace);let{errorSchema:s,errorMetadata:a}=await this.mixin.getErrorSchemaOrThrowBaseException(o,this.options.defaultNamespace,r,n,i),c=ei.of(s),u=n.message??n.Message??"UnknownError",f=new(this.compositeErrorRegistry.getErrorCtor(s)??Error)({});await this.deserializeHttpMessage(s,t,r,n);let h={},p=this.codec.createDeserializer();for(let[g,_]of c.structIterator()){let R=_.getMergedTraits().jsonName??g;h[g]=p.readObject(_,n[R])}throw this.mixin.decorateServiceException(Object.assign(f,a,{$fault:c.getMergedTraits().error,message:u},h),n)}getDefaultContentType(){return"application/json"}}class yS extends Rs{settings;constructor(e){super();this.settings=e}async read(e,t){let r=mS(e)?pS:void 0;return this._read(e,typeof t==="string"?JSON.parse(t,r):await pg(t,this.serdeContext,e))}readObject(e,t){return this._read(e,t)}_read(e,t){let r=t!==null&&typeof t==="object",n=ei.of(e);if(r){if(n.isStructSchema()){let o=t,s=n.isUnionSchema(),a={},c=void 0,{jsonName:u}=this.settings;if(u)c={};let d;if(s)d=new hg(o,a);for(let[f,h]of n.structIterator()){let p=f;if(u)p=h.getMergedTraits().jsonName??p,c[p]=f;if(s)d.mark(p);if(o[p]!=null)a[f]=this._read(h,o[p])}if(s)d.writeUnknown();else if(typeof o.__type==="string")for(let f in o){let h=o[f],p=u?c[f]??f:f;if(!(p in a))a[p]=h}return a}if(Array.isArray(t)&&n.isListSchema()){let o=n.getValueSchema(),s=[];for(let a of t)s.push(this._read(o,a));return s}if(n.isMapSchema()){let o=n.getValueSchema(),s={};for(let a in t){if(a==="__proto__")Rc(s);s[a]=this._read(o,t[a])}return s}}if(n.isBlobSchema()&&typeof t==="string")return hS(t);let i=n.getMergedTraits().mediaType;if(n.isStringSchema()&&typeof t==="string"&&i){if(i==="application/json"||i.endsWith("+json"))return lg.from(t);return t}if(n.isTimestampSchema()&&t!=null)switch(Gd(n,this.settings)){case 5:return aI(t);case 6:return sI(t);case 7:return oI(t);default:return console.warn("Missing timestamp format, parsing value with Date constructor:",t),new Date(t)}if(n.isBigIntegerSchema()&&(typeof t==="number"||typeof t==="string"))return BigInt(t);if(n.isBigDecimalSchema()&&t!=null){if(t instanceof Ji)return t;let o=t;if(o.type==="bigDecimal"&&"string"in o)return new Ji(o.string,o.type);return new Ji(String(t),"bigDecimal")}if(n.isNumericSchema()&&typeof t==="string"){switch(t){case"Infinity":return 1/0;case"-Infinity":return-1/0;case"NaN":return NaN}return t}if(n.isDocumentSchema())if(r){let o=Array.isArray(t)?[]:{};for(let s in t){if(s==="__proto__")Rc(o);let a=t[s];if(a instanceof Ji)o[s]=a;else o[s]=this._read(n,a)}return o}else return structuredClone(t);return t}}var XO=String.fromCharCode(925);class wI{values=new Map;counter=0;stage=0;createReplacer(){if(this.stage===1)throw Error("@aws-sdk/core/protocols - JsonReplacer already created.");if(this.stage===2)throw Error("@aws-sdk/core/protocols - JsonReplacer exhausted.");return this.stage=1,(e,t)=>{if(t instanceof Ji){let r=`${XO+"nv"+this.counter++}_`+t.string;return this.values.set(`"${r}"`,t.string),r}if(typeof t==="bigint"){let r=t.toString(),n=`${XO+"b"+this.counter++}_`+r;return this.values.set(`"${n}"`,r),n}return t}}replaceInJson(e){if(this.stage===0)throw Error("@aws-sdk/core/protocols - JsonReplacer not created yet.");if(this.stage===2)throw Error("@aws-sdk/core/protocols - JsonReplacer exhausted.");if(this.stage=2,this.counter===0)return e;for(let[t,r]of this.values)e=e.replace(t,r);return e}}class wS extends Rs{settings;buffer;useReplacer=!1;rootSchema;constructor(e){super();this.settings=e}write(e,t){this.rootSchema=ei.of(e),this.buffer=this._write(this.rootSchema,t)}flush(){let{rootSchema:e,useReplacer:t}=this;if(this.rootSchema=void 0,this.useReplacer=!1,e?.isStructSchema()||e?.isDocumentSchema()){if(!t)return JSON.stringify(this.buffer);let r=new wI;return r.replaceInJson(JSON.stringify(this.buffer,r.createReplacer(),0))}return this.buffer}writeDiscriminatedDocument(e,t){if(this.write(e,t),typeof this.buffer==="object")this.buffer.__type=ei.of(e).getName(!0)}_write(e,t,r){let n=t!==null&&typeof t==="object",i=ei.of(e);if(n){if(i.isStructSchema()){let o=t,s={},{jsonName:a}=this.settings,c=void 0;if(a)c={};let u=0;for(let[d,f]of i.structIterator()){let h=this._write(f,o[d],i);if(h!==void 0){let p=d;if(a)p=f.getMergedTraits().jsonName??d,c[d]=p;s[p]=h,u++}}if(i.isUnionSchema()&&u===0){let{$unknown:d}=o;if(Array.isArray(d)){let[f,h]=d;if(f==="__proto__")Rc(s);s[f]=this._write(15,h)}}else if(typeof o.__type==="string")for(let d in o){let f=o[d],h=a?c[d]??d:d;if(!(h in s))s[h]=this._write(15,f)}return s}if(Array.isArray(t)&&i.isListSchema()){let o=i.getValueSchema(),s=[],a=!!i.getMergedTraits().sparse;for(let c of t)if(a||c!=null)s.push(this._write(o,c));return s}if(i.isMapSchema()){let o=i.getValueSchema(),s={},a=!!i.getMergedTraits().sparse;for(let c in t){let u=t[c];if(a||u!=null){if(c==="__proto__")Rc(s);s[c]=this._write(o,u)}}return s}if(t instanceof Uint8Array&&i.isBlobSchema()){if(i===this.rootSchema)return t;return(this.serdeContext?.base64Encoder??Vd)(t)}if(t instanceof Date&&(i.isTimestampSchema()||i.isDocumentSchema()))switch(Gd(i,this.settings)){case 5:return t.toISOString().replace(".000Z","Z");case 6:return ch(t);case 7:return t.getTime()/1000;default:return console.warn("Missing timestamp format, using epoch seconds",t),t.getTime()/1000}if(t instanceof Ji)this.useReplacer=!0}if(t===null&&r?.isStructSchema())return;if(i.isStringSchema()){if(typeof t>"u"&&i.isIdempotencyToken())return fg();let o=i.getMergedTraits().mediaType;if(t!=null&&o){if(o==="application/json"||o.endsWith("+json"))return lg.from(t)}return t}if(typeof t==="number"){if(Math.abs(t)===1/0||isNaN(t))return String(t);return t}if(typeof t==="string"&&i.isBlobSchema()){if(i===this.rootSchema)return t;return(this.serdeContext?.base64Encoder??Vd)(t)}if(typeof t==="bigint")this.useReplacer=!0;if(i.isDocumentSchema())if(n){if(t instanceof Uint8Array)return(this.serdeContext?.base64Encoder??Vd)(t);let o=Array.isArray(t)?[]:{};for(let s in t){let a=t[s];if(s==="__proto__")Rc(o);if(a instanceof Ji)this.useReplacer=!0,o[s]=a;else o[s]=this._write(i,a)}return o}else return structuredClone(t);return t}}class _I extends Rs{settings;constructor(e){super();this.settings=e}createSerializer(){let e=new wS(this.settings);return e.setSerdeContext(this.serdeContext),e}createDeserializer(){let e=new yS(this.settings);return e.setSerdeContext(this.serdeContext),e}}class wg extends Rs{settings;stringDeserializer;constructor(e){super();this.settings=e,this.stringDeserializer=new ire(e)}setSerdeContext(e){this.serdeContext=e,this.stringDeserializer.setSerdeContext(e)}read(e,t,r){let n=ei.of(e),i=n.getMemberSchemas();if(n.isStructSchema()&&n.isMemberSchema()&&!!Object.values(i).find((c)=>!!c.getMemberTraits().eventPayload)){let c={},u=Object.keys(i)[0];if(i[u].isBlobSchema())c[u]=t;else c[u]=this.read(i[u],t);return c}let s=(this.serdeContext?.utf8Encoder??fS)(t),a=this.parseXml(s);return this.readSchema(e,r?a[r]:a)}readSchema(e,t){let r=ei.of(e);if(r.isUnitSchema())return;let n=r.getMergedTraits();if(r.isListSchema()&&!Array.isArray(t))return this.readSchema(r,[t]);if(t==null)return t;if(typeof t==="object"){let i=!!n.xmlFlattened;if(r.isListSchema()){let s=r.getValueSchema(),a=[],c=s.getMergedTraits().xmlName??"member",u=i?t:(t[0]??t)[c];if(u==null)return a;let d=Array.isArray(u)?u:[u];for(let f of d)a.push(this.readSchema(s,f));return a}let o={};if(r.isMapSchema()){let s=r.getKeySchema(),a=r.getValueSchema(),c;if(i)c=Array.isArray(t)?t:[t];else c=Array.isArray(t.entry)?t.entry:[t.entry];let u=s.getMergedTraits().xmlName??"key",d=a.getMergedTraits().xmlName??"value";for(let f of c){let h=f[u],p=f[d];if(h==="__proto__")Rc(o);o[h]=this.readSchema(a,p)}return o}if(r.isStructSchema()){let s=r.isUnionSchema(),a;if(s)a=new hg(t,o);for(let[c,u]of r.structIterator()){let d=u.getMergedTraits(),f=!d.httpPayload?u.getMemberTraits().xmlName??c:d.xmlName??u.getName();if(s)a.mark(f);if(t[f]!=null)o[c]=this.readSchema(u,t[f])}if(s)a.writeUnknown();return o}if(r.isDocumentSchema())return t;throw Error(`@aws-sdk/core/protocols - xml deserializer unhandled schema type for ${r.getName(!0)}`)}if(r.isListSchema())return[];if(r.isMapSchema()||r.isStructSchema())return{};return this.stringDeserializer.read(r,t)}parseXml(e){if(e.length){let t;try{t=cI(e)}catch(o){if(o&&typeof o==="object")Object.defineProperty(o,"$responseBodyText",{value:e});throw o}let r="#text",n=Object.keys(t)[0],i=t[n];if(i[r])i[n]=i[r],delete i[r];return eI(i)}return{}}}class _S extends Rs{settings;buffer;constructor(e){super();this.settings=e}write(e,t,r=""){if(this.buffer===void 0)this.buffer="";let n=ei.of(e);if(r&&!r.endsWith("."))r+=".";if(n.isBlobSchema()){if(typeof t==="string"||t instanceof Uint8Array)this.writeKey(r),this.writeValue((this.serdeContext?.base64Encoder??Vd)(t))}else if(n.isBooleanSchema()||n.isNumericSchema()||n.isStringSchema()){if(t!=null)this.writeKey(r),this.writeValue(String(t));else if(n.isIdempotencyToken())this.writeKey(r),this.writeValue(fg())}else if(n.isBigIntegerSchema()){if(t!=null)this.writeKey(r),this.writeValue(String(t))}else if(n.isBigDecimalSchema()){if(t!=null)this.writeKey(r),this.writeValue(t instanceof Ji?t.string:String(t))}else if(n.isTimestampSchema()){if(t instanceof Date)switch(this.writeKey(r),Gd(n,this.settings)){case 5:this.writeValue(t.toISOString().replace(".000Z","Z"));break;case 6:this.writeValue(ch(t));break;case 7:this.writeValue(String(t.getTime()/1000));break}}else if(n.isDocumentSchema())if(Array.isArray(t))this.write(79,t,r);else if(t instanceof Date)this.write(4,t,r);else if(t instanceof Uint8Array)this.write(21,t,r);else if(t&&typeof t==="object")this.write(143,t,r);else this.writeKey(r),this.writeValue(String(t));else if(n.isListSchema()){if(Array.isArray(t))if(t.length===0){if(this.settings.serializeEmptyLists)this.writeKey(r),this.writeValue("")}else{let i=n.getValueSchema(),o=this.settings.flattenLists||n.getMergedTraits().xmlFlattened,s=1;for(let a of t){if(a==null)continue;let c=i.getMergedTraits(),u=this.getKey("member",c.xmlName,c.ec2QueryName),d=o?`${r}${s}`:`${r}${u}.${s}`;this.write(i,a,d),++s}}}else if(n.isMapSchema()){if(t&&typeof t==="object"){let i=n.getKeySchema(),o=n.getValueSchema(),s=n.getMergedTraits().xmlFlattened,a=1;for(let c in t){let u=t[c];if(u==null)continue;let d=i.getMergedTraits(),f=this.getKey("key",d.xmlName,d.ec2QueryName),h=s?`${r}${a}.${f}`:`${r}entry.${a}.${f}`,p=o.getMergedTraits(),g=this.getKey("value",p.xmlName,p.ec2QueryName),_=s?`${r}${a}.${g}`:`${r}entry.${a}.${g}`;this.write(i,c,h),this.write(o,u,_),++a}}}else if(n.isStructSchema()){if(t&&typeof t==="object"){let i=!1;for(let[o,s]of n.structIterator()){if(t[o]==null&&!s.isIdempotencyToken())continue;let a=s.getMergedTraits(),c=this.getKey(o,a.xmlName,a.ec2QueryName,"struct"),u=`${r}${c}`;this.write(s,t[o],u),i=!0}if(!i&&n.isUnionSchema()){let{$unknown:o}=t;if(Array.isArray(o)){let[s,a]=o,c=`${r}${s}`;this.write(15,a,c)}}}}else if(n.isUnitSchema());else throw Error(`@aws-sdk/core/protocols - QuerySerializer unrecognized schema type ${n.getName(!0)}`)}flush(){if(this.buffer===void 0)throw Error("@aws-sdk/core/protocols - QuerySerializer cannot flush with nothing written to buffer.");let e=this.buffer;return delete this.buffer,e}getKey(e,t,r,n){let{ec2:i,capitalizeKeys:o}=this.settings;if(i&&r)return r;let s=t??e;if(o&&n==="struct")return s[0].toUpperCase()+s.slice(1);return s}writeKey(e){if(e.endsWith("."))e=e.slice(0,e.length-1);this.buffer+=`&${WO(e)}=`}writeValue(e){this.buffer+=WO(e)}}class bS extends tI{options;serializer;deserializer;mixin=new Kd;constructor(e){super({defaultNamespace:e.defaultNamespace,errorTypeRegistries:e.errorTypeRegistries});this.options=e;let t={timestampFormat:{useTrait:!0,default:5},httpBindings:!1,xmlNamespace:e.xmlNamespace,serviceNamespace:e.defaultNamespace,serializeEmptyLists:!0};this.serializer=new _S(t),this.deserializer=new wg(t)}getShapeId(){return"aws.protocols#awsQuery"}setSerdeContext(e){this.serializer.setSerdeContext(e),this.deserializer.setSerdeContext(e)}getPayloadCodec(){throw Error("AWSQuery protocol has no payload codec.")}async serializeRequest(e,t,r){let n=await super.serializeRequest(e,t,r);if(!n.path.endsWith("/"))n.path+="/";if(n.headers["content-type"]="application/x-www-form-urlencoded",ZO(e.input)==="unit"||!n.body)n.body="";let i=e.name.split("#")[1]??e.name;if(n.body=`Action=${i}&Version=${this.options.version}`+n.body,n.body.endsWith("&"))n.body=n.body.slice(-1);return n}async deserializeResponse(e,t,r){let n=this.deserializer,i=ei.of(e.output),o={};if(r.statusCode>=300){let u=await cg(r.body,t);if(u.byteLength>0)Object.assign(o,await n.read(15,u));await this.handleError(e,t,r,o,this.deserializeMetadata(r))}for(let u in r.headers){let d=r.headers[u];delete r.headers[u],r.headers[u.toLowerCase()]=d}let s=e.name.split("#")[1]??e.name,a=i.isStructSchema()&&this.useNestedResult()?s+"Result":void 0,c=await cg(r.body,t);if(c.byteLength>0)Object.assign(o,await n.read(i,c,a));return o.$metadata=this.deserializeMetadata(r),o}useNestedResult(){return!0}async handleError(e,t,r,n,i){let o=this.loadQueryErrorCode(r,n)??"Unknown";this.mixin.compose(this.compositeErrorRegistry,o,this.options.defaultNamespace);let s=this.loadQueryError(n)??{},a=this.loadQueryErrorMessage(n);s.message=a,s.Error={Type:s.Type,Code:s.Code,Message:a};let{errorSchema:c,errorMetadata:u}=await this.mixin.getErrorSchemaOrThrowBaseException(o,this.options.defaultNamespace,r,s,i,this.mixin.findQueryCompatibleError),d=ei.of(c),h=new(this.compositeErrorRegistry.getErrorCtor(c)??Error)({}),p={Type:s.Error.Type,Code:s.Error.Code,Error:s.Error};for(let[g,_]of d.structIterator()){let R=_.getMergedTraits().xmlName??g,O=s[R]??n[R];p[g]=this.deserializer.readSchema(_,O)}throw this.mixin.decorateServiceException(Object.assign(h,u,{$fault:d.getMergedTraits().error,message:a},p),n)}loadQueryErrorCode(e,t){let r=(t.Errors?.[0]?.Error??t.Errors?.Error??t.Error)?.Code;if(r!==void 0)return r;if(e.statusCode==404)return"NotFound"}loadQueryError(e){return e.Errors?.[0]?.Error??e.Errors?.Error??e.Error}loadQueryErrorMessage(e){let t=this.loadQueryError(e);return t?.message??t?.Message??e.message??e.Message??"Unknown"}getDefaultContentType(){return"application/x-www-form-urlencoded"}}class bI extends bS{options;constructor(e){super(e);this.options=e;let t={capitalizeKeys:!0,flattenLists:!0,serializeEmptyLists:!1,ec2:!0};Object.assign(this.serializer.settings,t)}getShapeId(){return"aws.protocols#ec2Query"}useNestedResult(){return!1}}var EI=(e,t)=>lI(e,t).then((r)=>{if(r.length){let n;try{n=cI(r)}catch(a){if(a&&typeof a==="object")Object.defineProperty(a,"$responseBodyText",{value:r});throw a}let i="#text",o=Object.keys(n)[0],s=n[o];if(s[i])s[o]=s[i],delete s[i];return eI(s)}return{}}),mre=async(e,t)=>{let r=await EI(e,t);if(r.Error)r.Error.message=r.Error.message??r.Error.Message;return r},SI=(e,t)=>{if(t?.Error?.Code!==void 0)return t.Error.Code;if(t?.Code!==void 0)return t.Code;if(e.statusCode==404)return"NotFound"};class ES extends Rs{settings;stringBuffer;byteBuffer;buffer;constructor(e){super();this.settings=e}write(e,t){let r=ei.of(e);if(r.isStringSchema()&&typeof t==="string")this.stringBuffer=t;else if(r.isBlobSchema())this.byteBuffer="byteLength"in t?t:(this.serdeContext?.base64Decoder??hS)(t);else{this.buffer=this.writeStruct(r,t,void 0);let n=r.getMergedTraits();if(n.httpPayload&&!n.xmlName)this.buffer.withName(r.getName())}}flush(){if(this.byteBuffer!==void 0){let t=this.byteBuffer;return delete this.byteBuffer,t}if(this.stringBuffer!==void 0){let t=this.stringBuffer;return delete this.stringBuffer,t}let e=this.buffer;if(this.settings.xmlNamespace){if(!e?.attributes?.xmlns)e.addAttribute("xmlns",this.settings.xmlNamespace)}return delete this.buffer,e.toString()}writeStruct(e,t,r){let n=e.getMergedTraits(),i=e.isMemberSchema()&&!n.httpPayload?e.getMemberTraits().xmlName??e.getMemberName():n.xmlName??e.getName();if(!i||!e.isStructSchema())throw Error(`@aws-sdk/core/protocols - xml serializer, cannot write struct with empty name or non-struct, schema=${e.getName(!0)}.`);let o=ks.of(i),[s,a]=this.getXmlnsAttribute(e,r);for(let[u,d]of e.structIterator()){let f=t[u];if(f!=null||d.isIdempotencyToken()){if(d.getMergedTraits().xmlAttribute){o.addAttribute(d.getMergedTraits().xmlName??u,this.writeSimple(d,f));continue}if(d.isListSchema())this.writeList(d,f,o,a);else if(d.isMapSchema())this.writeMap(d,f,o,a);else if(d.isStructSchema())o.addChildNode(this.writeStruct(d,f,a));else{let h=ks.of(d.getMergedTraits().xmlName??d.getMemberName());this.writeSimpleInto(d,f,h,a),o.addChildNode(h)}}}let{$unknown:c}=t;if(c&&e.isUnionSchema()&&Array.isArray(c)&&Object.keys(t).length===1){let[u,d]=c,f=ks.of(u);if(typeof d!=="string")if(t instanceof ks||t instanceof HO)o.addChildNode(t);else throw Error("@aws-sdk - $unknown union member in XML requires value of type string, @aws-sdk/xml-builder::XmlNode or XmlText.");this.writeSimpleInto(0,d,f,a),o.addChildNode(f)}if(a)o.addAttribute(s,a);return o}writeList(e,t,r,n){if(!e.isMemberSchema())throw Error(`@aws-sdk/core/protocols - xml serializer, cannot write non-member list: ${e.getName(!0)}`);let i=e.getMergedTraits(),o=e.getValueSchema(),s=o.getMergedTraits(),a=!!s.sparse,c=!!i.xmlFlattened,[u,d]=this.getXmlnsAttribute(e,n),f=(h,p)=>{if(o.isListSchema())this.writeList(o,Array.isArray(p)?p:[p],h,d);else if(o.isMapSchema())this.writeMap(o,p,h,d);else if(o.isStructSchema()){let g=this.writeStruct(o,p,d);h.addChildNode(g.withName(c?i.xmlName??e.getMemberName():s.xmlName??"member"))}else{let g=ks.of(c?i.xmlName??e.getMemberName():s.xmlName??"member");this.writeSimpleInto(o,p,g,d),h.addChildNode(g)}};if(c){for(let h of t)if(a||h!=null)f(r,h)}else{let h=ks.of(i.xmlName??e.getMemberName());if(d)h.addAttribute(u,d);for(let p of t)if(a||p!=null)f(h,p);r.addChildNode(h)}}writeMap(e,t,r,n,i=!1){if(!e.isMemberSchema())throw Error(`@aws-sdk/core/protocols - xml serializer, cannot write non-member map: ${e.getName(!0)}`);let o=e.getMergedTraits(),s=e.getKeySchema(),c=s.getMergedTraits().xmlName??"key",u=e.getValueSchema(),d=u.getMergedTraits(),f=d.xmlName??"value",h=!!d.sparse,p=!!o.xmlFlattened,[g,_]=this.getXmlnsAttribute(e,n),R=(O,I,Ne)=>{let k=ks.of(c,I),[j,re]=this.getXmlnsAttribute(s,_);if(re)k.addAttribute(j,re);O.addChildNode(k);let Oe=ks.of(f);if(u.isListSchema())this.writeList(u,Ne,Oe,_);else if(u.isMapSchema())this.writeMap(u,Ne,Oe,_,!0);else if(u.isStructSchema())Oe=this.writeStruct(u,Ne,_);else this.writeSimpleInto(u,Ne,Oe,_);O.addChildNode(Oe)};if(p)for(let O in t){let I=t[O];if(h||I!=null){let Ne=ks.of(o.xmlName??e.getMemberName());R(Ne,O,I),r.addChildNode(Ne)}}else{let O;if(!i){if(O=ks.of(o.xmlName??e.getMemberName()),_)O.addAttribute(g,_);r.addChildNode(O)}for(let I in t){let Ne=t[I];if(h||Ne!=null){let k=ks.of("entry");R(k,I,Ne),(i?r:O).addChildNode(k)}}}}writeSimple(e,t){if(t===null)throw Error("@aws-sdk/core/protocols - (XML serializer) cannot write null value.");let r=ei.of(e),n=null;if(t&&typeof t==="object")if(r.isBlobSchema())n=(this.serdeContext?.base64Encoder??Vd)(t);else if(r.isTimestampSchema()&&t instanceof Date)switch(Gd(r,this.settings)){case 5:n=t.toISOString().replace(".000Z","Z");break;case 6:n=ch(t);break;case 7:n=String(t.getTime()/1000);break;default:console.warn("Missing timestamp format, using http date",t),n=ch(t);break}else if(r.isBigDecimalSchema()&&t){if(t instanceof Ji)return t.string;return String(t)}else if(r.isMapSchema()||r.isListSchema())throw Error("@aws-sdk/core/protocols - xml serializer, cannot call _write() on List/Map schema, call writeList or writeMap() instead.");else throw Error(`@aws-sdk/core/protocols - xml serializer, unhandled schema type for object value and schema: ${r.getName(!0)}`);if(r.isBooleanSchema()||r.isNumericSchema()||r.isBigIntegerSchema()||r.isBigDecimalSchema())n=String(t);if(r.isStringSchema())if(t===void 0&&r.isIdempotencyToken())n=fg();else n=String(t);if(n===null)throw Error(`Unhandled schema-value pair ${r.getName(!0)}=${t}`);return n}writeSimpleInto(e,t,r,n){let i=this.writeSimple(e,t),o=ei.of(e),s=new HO(i),[a,c]=this.getXmlnsAttribute(o,n);if(c)r.addAttribute(a,c);r.addChildNode(s)}getXmlnsAttribute(e,t){let r=e.getMergedTraits(),[n,i]=r.xmlNamespace??[];if(i&&i!==t)return[n?`xmlns:${n}`:"xmlns",i];return[void 0,void 0]}}class SS extends Rs{settings;constructor(e){super();this.settings=e}createSerializer(){let e=new ES(this.settings);return e.setSerdeContext(this.serdeContext),e}createDeserializer(){let e=new wg(this.settings);return e.setSerdeContext(this.serdeContext),e}}class AI extends rI{codec;serializer;deserializer;mixin=new Kd;constructor(e){super(e);let t={timestampFormat:{useTrait:!0,default:5},httpBindings:!0,xmlNamespace:e.xmlNamespace,serviceNamespace:e.defaultNamespace};this.codec=new SS(t),this.serializer=new nI(this.codec.createSerializer(),t),this.deserializer=new iI(this.codec.createDeserializer(),t)}getPayloadCodec(){return this.codec}getShapeId(){return"aws.protocols#restXml"}async serializeRequest(e,t,r){let n=await super.serializeRequest(e,t,r),i=ei.of(e.input);if(!n.headers["content-type"]){let o=this.mixin.resolveRestContentType(this.getDefaultContentType(),i);if(o)n.headers["content-type"]=o}if(typeof n.body==="string"&&n.headers["content-type"]===this.getDefaultContentType()&&!n.body.startsWith("<?xml ")&&!this.hasUnstructuredPayloadBinding(i))n.body='<?xml version="1.0" encoding="UTF-8"?>'+n.body;return n}async deserializeResponse(e,t,r){return super.deserializeResponse(e,t,r)}async handleError(e,t,r,n,i){let o=SI(r,n)??"Unknown";if(this.mixin.compose(this.compositeErrorRegistry,o,this.options.defaultNamespace),n.Error&&typeof n.Error==="object"){for(let g of Object.keys(n.Error))if(n[g]=n.Error[g],g.toLowerCase()==="message")n.message=n.Error[g]}if(n.RequestId&&!i.requestId)i.requestId=n.RequestId;let{errorSchema:s,errorMetadata:a}=await this.mixin.getErrorSchemaOrThrowBaseException(o,this.options.defaultNamespace,r,n,i),c=ei.of(s),u=n.Error?.message??n.Error?.Message??n.message??n.Message??"UnknownError",f=new(this.compositeErrorRegistry.getErrorCtor(s)??Error)({});await this.deserializeHttpMessage(s,t,r,n);let h={},p=this.codec.createDeserializer();for(let[g,_]of c.structIterator()){let R=_.getMergedTraits().xmlName??g,O=n.Error?.[R]??n[R];h[g]=p.readSchema(_,O)}throw this.mixin.decorateServiceException(Object.assign(f,a,{$fault:c.getMergedTraits().error,message:u},h),n)}getDefaultContentType(){return"application/xml"}hasUnstructuredPayloadBinding(e){for(let[,t]of e.structIterator())if(t.getMergedTraits().httpPayload)return!(t.isStructSchema()||t.isMapSchema()||t.isListSchema());return!1}}var gre=(e)=>{if(e==null)return;if(typeof e==="object"&&"__type"in e)delete e.__type;return ore(e)},yre=(e)=>{if(e==null)return e;if(typeof e==="number"||typeof e==="bigint"){let t=Error(`Received number ${e} where a string was expected.`);return t.name="Warning",console.warn(t),String(e)}if(typeof e==="boolean"){let t=Error(`Received boolean ${e} where a string was expected.`);return t.name="Warning",console.warn(t),String(e)}return e},wre=(e)=>{if(e==null)return e;if(typeof e==="string"){let t=e.toLowerCase();if(e!==""&&t!=="false"&&t!=="true"){let r=Error(`Received string "${e}" where a boolean was expected.`);r.name="Warning",console.warn(r)}return e!==""&&t!=="false"}return e},_re=(e)=>{if(e==null)return e;if(typeof e==="string"){let t=Number(e);if(t.toString()!==e){let r=Error(`Received string "${e}" where a number was expected.`);return r.name="Warning",console.warn(r),e}return t}return e};bre.AwsEc2QueryProtocol=bI;bre.AwsJson1_0Protocol=mI;bre.AwsJson1_1Protocol=gI;bre.AwsJsonRpcProtocol=yg;bre.AwsQueryProtocol=bS;bre.AwsRestJsonProtocol=yI;bre.AwsRestXmlProtocol=AI;bre.AwsSmithyRpcV2CborProtocol=uI;bre.JsonCodec=_I;bre.JsonCodec2=gg;bre.JsonShapeDeserializer=yS;bre.JsonShapeDeserializer2=gS;bre.JsonShapeSerializer=wS;bre.JsonShapeSerializer2=mg;bre.QueryShapeSerializer=_S;bre.XmlCodec=SS;bre.XmlShapeDeserializer=wg;bre.XmlShapeSerializer=ES;bre._toBool=wre;bre._toNum=_re;bre._toStr=yre;bre.awsExpectUnion=gre;bre.loadJsonRpcErrorCode=hI;bre.loadRestJsonErrorCode=fI;bre.loadRestXmlErrorCode=SI;bre.parseJsonBody=pg;bre.parseJsonErrorBody=ure;bre.parseXmlBody=EI;bre.parseXmlErrorBody=mre});var ve=A(function(hne){var{ProviderError:TI,booleanSelector:vI,SelectorType:kI,loadConfig:Qre}=P(),{setCredentialFeature:Yre}=N(),{normalizeProvider:Jd,memoizeIdentityProvider:Xre,isIdentityExpired:Zre,doesIdentityRequireRefresh:ene}=ge(),{SignatureV4:RI}=DE(),{HttpResponse:UI,HttpRequest:PI}=L(),NI=(e)=>UI.isInstance(e)?e.headers?.date??e.headers?.Date:void 0,xI=(e)=>UI.isInstance(e)?e.headers?.age??e.headers?.Age:void 0,LI=(e)=>new Date(Date.now()+e),CI=(e,t,r,n)=>{if(n!==void 0)return t;let i=Date.parse(e),o=Date.now();if(r!==void 0&&o-r>900000)return t;return r!==void 0?i-(r+o)/2:i-o},uh=(e,t)=>{if(!t)throw Error(`Property \`${e}\` is not resolved for AWS SDK SigV4Auth`);return t},AS=async(e)=>{let t=uh("context",e.context),r=uh("config",e.config),n=t.endpointV2?.properties?.authSchemes?.[0],o=await uh("signer",r.signer)(n),s=e?.signingRegion,a=e?.signingRegionSet,c=e?.signingName;return{config:r,signer:o,signingRegion:s,signingRegionSet:a,signingName:c}};class _g{async sign(e,t,r){if(!PI.isInstance(e))throw Error("The request is not an instance of `HttpRequest` and cannot be signed");let n=await AS(r),{config:i,signer:o}=n,{signingRegion:s,signingName:a}=n,c=r.context;if(c?.authSchemes?.length??!1){let[f,h]=c.authSchemes;if(f?.name==="sigv4a"&&h?.name==="sigv4")s=h?.signingRegion??s,a=h?.signingName??a}let u=await i.disableClockSkewCorrection?.()===!0;if(r._disableClockSkewCorrection=u,!u)r._preRequestSystemClockOffset=i.systemClockOffset,r._requestSentAt=Date.now();return await o.sign(e,{signingDate:u?new Date:LI(i.systemClockOffset),signingRegion:s,signingService:a})}errorHandler(e){return(t)=>{let r=t;if(!e._disableClockSkewCorrection){let n=r.ServerTime??NI(r.$response);if(n){let i=uh("config",e.config),{_preRequestSystemClockOffset:o,_requestSentAt:s}=e,a=xI(r.$response),c=CI(n,i.systemClockOffset,s,a);if(i.systemClockOffset=c,Math.abs(c)>=240000&&(c!==o||o!==void 0&&o!==c)&&r.$metadata)r.$metadata.clockSkewCorrected=!0}}throw t}}successHandler(e,t){if(t._disableClockSkewCorrection)return;let r=NI(e);if(r){let n=uh("config",t.config),i=t._requestSentAt,o=xI(e);n.systemClockOffset=CI(r,n.systemClockOffset,i,o)}}}var tne=_g;class MI extends _g{async sign(e,t,r){if(!PI.isInstance(e))throw Error("The request is not an instance of `HttpRequest` and cannot be signed");let{config:n,signer:i,signingRegion:o,signingRegionSet:s,signingName:a}=await AS(r),u=(await n.sigv4aSigningRegionSet?.()??s??[o]).join(","),d=await n.disableClockSkewCorrection?.()===!0;if(r._disableClockSkewCorrection=d,!d)r._preRequestSystemClockOffset=n.systemClockOffset,r._requestSentAt=Date.now();return await i.sign(e,{signingDate:d?new Date:LI(n.systemClockOffset),signingRegion:u,signingService:a})}}var OI=(e)=>typeof e==="string"&&e.length>0?e.split(",").map((t)=>t.trim()):[],qI=(e)=>`AWS_BEARER_TOKEN_${e.replace(/[\s-]/g,"_").toUpperCase()}`,II="AWS_AUTH_SCHEME_PREFERENCE",DI="auth_scheme_preference",rne={environmentVariableSelector:(e,t)=>{if(t?.signingName){if(qI(t.signingName)in e)return["httpBearerAuth"]}if(!(II in e))return;return OI(e[II])},configFileSelector:(e)=>{if(!(DI in e))return;return OI(e[DI])},default:[]},nne=(e)=>(e.sigv4aSigningRegionSet=Jd(e.sigv4aSigningRegionSet),e),ine={environmentVariableSelector(e){if(e.AWS_SIGV4A_SIGNING_REGION_SET)return e.AWS_SIGV4A_SIGNING_REGION_SET.split(",").map((t)=>t.trim());throw new TI("AWS_SIGV4A_SIGNING_REGION_SET not set in env.",{tryNextLink:!0})},configFileSelector(e){if(e.sigv4a_signing_region_set)return(e.sigv4a_signing_region_set??"").split(",").map((t)=>t.trim());throw new TI("sigv4a_signing_region_set not set in profile.",{tryNextLink:!0})},default:void 0},one=(e)=>(t)=>{let r=t.credentials,n=!!t.credentials,i=void 0;Object.defineProperty(t,"credentials",{set(d){if(d&&d!==r&&d!==i)n=!0;r=d;let f=sne(t,{credentials:r,credentialDefaultProvider:t.credentialDefaultProvider}),h=ane(t,f);if(n&&!h.attributed){let p=typeof r==="object"&&r!==null;i=async(g)=>{let R=await h(g);if(p&&(!R.$source||Object.keys(R.$source).length===0))return Yre(R,"CREDENTIALS_CODE","e");return R},i.memoized=h.memoized,i.configBound=h.configBound,i.attributed=!0}else i=h},get(){return i},enumerable:!0,configurable:!0}),t.credentials=r;let{signingEscapePath:o=!0,systemClockOffset:s=t.systemClockOffset||0,sha256:a}=t,c;if(t.signer)c=Jd(t.signer);else if(t.regionInfoProvider)c=()=>Jd(t.region)().then(async(d)=>[await t.regionInfoProvider(d,{useFipsEndpoint:await t.useFipsEndpoint(),useDualstackEndpoint:await t.useDualstackEndpoint()})||{},d]).then(([d,f])=>{let{signingRegion:h,signingService:p}=d;t.signingRegion=t.signingRegion||h||f,t.signingName=t.signingName||p||t.serviceId;let g={...t,credentials:t.credentials,region:t.signingRegion,service:t.signingName,sha256:a,uriEscapePath:o};return new(t.signerConstructor||RI)(g)});else c=async(d)=>{d=Object.assign({},{name:"sigv4",signingName:t.signingName||t.defaultSigningName,signingRegion:await Jd(t.region)(),properties:{}},d);let f=d.signingRegion,h=d.signingName;t.signingRegion=t.signingRegion||f,t.signingName=t.signingName||h||t.serviceId;let p={...t,credentials:t.credentials,region:t.signingRegion,service:t.signingName,sha256:a,uriEscapePath:o};return new(t.signerConstructor||RI)(p)};return Object.assign(t,{systemClockOffset:s,signingEscapePath:o,signer:c,disableClockSkewCorrection:Jd(t.disableClockSkewCorrection??e)})};function sne(e,{credentials:t,credentialDefaultProvider:r}){let n;if(t)if(!t?.memoized)n=Xre(t,Zre,ene);else n=t;else if(r)n=Jd(r(Object.assign({},e,{parentClientConfig:e})));else n=async()=>{throw Error("@aws-sdk/core::resolveAwsSdkSigV4Config - `credentials` not provided and no credentialDefaultProvider was configured.")};return n.memoized=!0,n}function ane(e,t){if(t.configBound)return t;let r=async(n)=>t({...n,callerClientConfig:e});return r.memoized=t.memoized,r.configBound=!0,r}var cne="AWS_DISABLE_CLOCK_SKEW_CORRECTION",une="disable_clock_skew_correction",dne={environmentVariableSelector:(e)=>vI(e,cne,kI.ENV),configFileSelector:(e)=>vI(e,une,kI.CONFIG),default:!1},lne=Qre(dne),BI=one(lne),fne=BI;hne.AWSSDKSigV4Signer=tne;hne.AwsSdkSigV4ASigner=MI;hne.AwsSdkSigV4Signer=_g;hne.NODE_AUTH_SCHEME_PREFERENCE_OPTIONS=rne;hne.NODE_SIGV4A_CONFIG_OPTIONS=ine;hne.getBearerTokenEnvKey=qI;hne.resolveAWSSDKSigV4Config=fne;hne.resolveAwsSdkSigV4AConfig=nne;hne.resolveAwsSdkSigV4Config=BI;hne.validateSigningProperties=AS});var be=A(function(Pne){var{hasOwn:YI}=z(),{streamCollector:Tne}=z();Pne.streamCollector=Tne;var{buildQueryString:XI,HttpResponse:ZI}=L(),Nc=C("https"),{Readable:vne}=C("stream"),dh=C("http2");function Eg(e){let t=e&&typeof e==="object"&&"reason"in e?e.reason:void 0;if(t){if(t instanceof Error){let i=Error("Request aborted");return i.name="AbortError",i.cause=t,i}let n=Error(String(t));return n.name="AbortError",n}let r=Error("Request aborted");return r.name="AbortError",r}var kne=["ECONNRESET","EPIPE","ETIMEDOUT"],eD=(e)=>{let t={};for(let r in e){if(!YI(e,r))continue;let n=e[r];t[r]=Array.isArray(n)?n.join(","):n}return t},Qi={setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:(e)=>clearTimeout(e)},VI=1000,Rne=(e,t,r=0)=>{if(!r)return-1;let n=(i)=>{let o=Qi.setTimeout(()=>{e.destroy(),t(Object.assign(Error(`@smithy/node-http-handler - the request socket did not establish a connection with the server within the configured timeout of ${r} ms.`),{name:"TimeoutError"}))},r-i),s=(a)=>{if(a?.connecting)a.on("connect",()=>{Qi.clearTimeout(o)});else Qi.clearTimeout(o)};if(e.socket)s(e.socket);else e.on("socket",s)};if(r<2000)return n(0),0;return Qi.setTimeout(n.bind(null,VI),VI)},Nne=(e,t,r=0,n,i)=>{if(r)return Qi.setTimeout(()=>{let o=`@smithy/node-http-handler - [${n?"ERROR":"WARN"}] a request has exceeded the configured ${r} ms requestTimeout.`;if(n){let s=Object.assign(Error(o),{name:"TimeoutError",code:"ETIMEDOUT"});e.destroy(s),t(s)}else o+=" Init client requestHandler with throwOnRequestTimeout=true to turn this into an error.",i?.warn?.(o)},r);return-1},xne=3000,Cne=(e,{keepAlive:t,keepAliveMsecs:r},n=xne)=>{if(t!==!0)return-1;let i=()=>{if(e.socket)e.socket.setKeepAlive(t,r||0);else e.on("socket",(o)=>{o.setKeepAlive(t,r||0)})};if(n===0)return i(),0;return Qi.setTimeout(i,n)},GI=3000,One=(e,t,r=0)=>{let n=(i)=>{let o=r-i,s=()=>{e.destroy(),t(Object.assign(Error(`@smithy/node-http-handler - the request socket timed out after ${r} ms of inactivity (configured by client requestHandler).`),{name:"TimeoutError"}))};if(e.socket)e.socket.setTimeout(o,s),e.on("close",()=>e.socket?.removeListener("timeout",s));else e.setTimeout(o,s)};if(0<r&&r<6000)return n(0),0;return Qi.setTimeout(n.bind(null,r===0?0:GI),GI)},KI=6000;async function tD(e,t,r=KI,n=!1){let i=t.headers,o=i?i.Expect||i.expect:void 0,s=-1,a=!0;if(!n&&o==="100-continue")a=await Promise.race([new Promise((c)=>{s=Number(Qi.setTimeout(()=>c(!0),Math.max(KI,r)))}),new Promise((c)=>{e.on("continue",()=>{Qi.clearTimeout(s),c(!0)}),e.on("response",()=>{Qi.clearTimeout(s),c(!1)}),e.on("error",()=>{Qi.clearTimeout(s),c(!1)})})]);if(a)Ine(e,t.body)}function Ine(e,t){if(t instanceof vne){t.pipe(e);return}if(t){let r=Buffer.isBuffer(t);if(r||typeof t==="string"){if(r&&t.byteLength===0)e.end();else e.end(t);return}let i=t;if(typeof i==="object"&&i.buffer&&typeof i.byteOffset==="number"&&typeof i.byteLength==="number"){e.end(Buffer.from(i.buffer,i.byteOffset,i.byteLength));return}e.end(Buffer.from(t));return}e.end()}var Dne=0,bg=void 0,JI=void 0;class Sg{config;configProvider;socketWarningTimestamp=0;externalAgent=!1;metadata={handlerProtocol:"http/1.1"};static create(e){if(typeof e?.handle==="function")return e;return new Sg(e)}static checkSocketUsage(e,t,r=console){let{sockets:n,requests:i,maxSockets:o}=e;if(typeof o!=="number"||o===1/0)return t;let s=15000;if(Date.now()-s<t)return t;if(n&&i)for(let a in n){if(!YI(n,a))continue;let c=n[a]?.length??0,u=i[a]?.length??0;if(c>=o&&u>=2*o)return r?.warn?.(`@smithy/node-http-handler:WARN - socket usage at capacity=${c} and ${u} additional requests are enqueued.
43
+ See https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/node-configuring-maxsockets.html
44
+ or increase socketAcquisitionWarningTimeout=(millis) in the NodeHttpHandler config.`),Date.now()}return t}constructor(e){this.configProvider=new Promise((t,r)=>{if(typeof e==="function")e().then((n)=>{t(this.resolveDefaultConfig(n))}).catch(r);else t(this.resolveDefaultConfig(e))})}destroy(){this.config?.httpAgent?.destroy(),this.config?.httpsAgent?.destroy()}async handle(e,{abortSignal:t,requestTimeout:r}={}){if(!this.config)this.config=await this.configProvider;let n=this.config,i=n.logger,o=e.protocol==="https:";if(!o&&!this.config.httpAgent)this.config.httpAgent=await this.config.httpAgentProvider();return new Promise((s,a)=>{let c=void 0,u=-1,d=-1,f=-1,h=-1,p=-1,g=()=>{Qi.clearTimeout(u),Qi.clearTimeout(d),Qi.clearTimeout(f),Qi.clearTimeout(h),Qi.clearTimeout(p)},_=async(pe)=>{await c,g(),s(pe)},R=async(pe)=>{await c,g(),a(pe)};if(t?.aborted){let pe=Eg(t);R(pe);return}let O=e.headers,I=O?(O.Expect??O.expect)==="100-continue":!1,Ne=o?n.httpsAgent:n.httpAgent;if(I&&!this.externalAgent)Ne=new(o?Nc.Agent:bg)({keepAlive:!1,maxSockets:1/0});u=Qi.setTimeout(()=>{this.socketWarningTimestamp=Sg.checkSocketUsage(Ne,this.socketWarningTimestamp,i)},n.socketAcquisitionWarningTimeout??(n.requestTimeout??2000)+(n.connectionTimeout??1000));let k=e.query?XI(e.query):"",j=void 0;if(e.username!=null||e.password!=null){let pe=e.username??"",ae=e.password??"";j=`${pe}:${ae}`}let re=e.path;if(k)re+=`?${k}`;if(e.fragment)re+=`#${e.fragment}`;let Oe=e.hostname??"";if(Oe[0]==="["&&Oe.endsWith("]"))Oe=e.hostname.slice(1,-1);else Oe=e.hostname;let ne={headers:e.headers,host:Oe,method:e.method,path:re,port:e.port,agent:Ne,auth:j},F=(o?Nc.request:JI)(ne,(pe)=>{let ae=new ZI({statusCode:pe.statusCode||-1,reason:pe.statusMessage,headers:eD(pe.headers),body:pe});_({response:ae})});if(F.on("error",(pe)=>{if(kne.includes(pe.code))R(Object.assign(pe,{name:"TimeoutError"}));else R(pe)}),t){let pe=()=>{F.destroy();let ae=Eg(t);R(ae)};if(typeof t.addEventListener==="function"){let ae=t;ae.addEventListener("abort",pe,{once:!0}),F.once("close",()=>ae.removeEventListener("abort",pe))}else t.onabort=pe}let ce=r??n.requestTimeout;d=Rne(F,R,n.connectionTimeout),f=Nne(F,R,ce,n.throwOnRequestTimeout,i??console),h=One(F,R,n.socketTimeout);let de=ne.agent;if(typeof de==="object"&&"keepAlive"in de)p=Cne(F,{keepAlive:de.keepAlive,keepAliveMsecs:de.keepAliveMsecs});c=tD(F,e,ce,this.externalAgent).catch((pe)=>(g(),a(pe)))})}updateHttpClientConfig(e,t){this.config=void 0,this.configProvider=this.configProvider.then((r)=>{if(e===Symbol.for("logger"))return{...r,logger:r.logger??t};return{...r,[e]:t}})}httpHandlerConfigs(){return this.config??{}}resolveDefaultConfig(e){let{requestTimeout:t,connectionTimeout:r,socketTimeout:n,socketAcquisitionWarningTimeout:i,httpAgent:o,httpsAgent:s,throwOnRequestTimeout:a,logger:c}=e||{},u=!0,d=50;return{connectionTimeout:r,requestTimeout:t,socketTimeout:n,socketAcquisitionWarningTimeout:i,throwOnRequestTimeout:a,httpAgentProvider:async()=>{let f=C("http"),{Agent:h,request:p}=f.default??f;if(JI=p,bg=h,o instanceof bg||typeof o?.destroy==="function")return this.externalAgent=!0,o;return new bg({keepAlive:!0,maxSockets:50,...o})},httpsAgent:(()=>{if(s instanceof Nc.Agent||typeof s?.destroy==="function")return this.externalAgent=!0,s;return new Nc.Agent({keepAlive:!0,maxSockets:50,...s})})(),logger:c}}}var Une=new Uint16Array(1);class Ag{id=Une[0]++;total=0;max=0;session;refs=0;constructor(e){e.unref(),this.session=e}retain(){if(this.session.destroyed)throw Error("@smithy/node-http-handler - cannot acquire reference to destroyed session.");this.refs+=1,this.total+=1,this.max=Math.max(this.refs,this.max),this.session.ref()}free(){if(this.session.destroyed)return;if(this.refs-=1,this.refs===0)this.session.unref();if(this.refs<0)throw Error("@smithy/node-http-handler - ClientHttp2Session refcount at zero, cannot decrement.")}deref(){return this.session}close(){if(!this.session.closed)this.session.close()}destroy(){if(this.refs=0,!this.session.destroyed)this.session.destroy()}useCount(){return this.refs}}class rD{sessions=[];maxConcurrency=0;constructor(e){this.sessions=(e??[]).map((t)=>new Ag(t))}poll(){let e=!1;for(let t of this.sessions){if(t.deref().destroyed){e=!0;continue}if(!this.maxConcurrency||t.useCount()<this.maxConcurrency)return t}if(e){for(let t of this.sessions)if(t.deref().destroyed)this.remove(t)}}offerLast(e){this.sessions.push(e)}remove(e){let t=this.sessions.indexOf(e);if(t>-1)this.sessions.splice(t,1)}[Symbol.iterator](){return this.sessions[Symbol.iterator]()}setMaxConcurrency(e){this.maxConcurrency=e}destroy(e){this.remove(e),e.destroy()}}class nD{config;connectOptions;connectionPools=new Map;constructor(e){if(this.config=e,this.config.maxConcurrency&&this.config.maxConcurrency<=0)throw RangeError("maxConcurrency must be greater than zero.")}lease(e,t){let r=this.getUrlString(e),n=this.getPool(r);if(!this.config.disableConcurrency&&!t.isEventStream){let c=n.poll();if(c)return c.retain(),c}let i=new Ag(this.connect(r)),o=i.deref();if(this.config.maxConcurrency)o.settings({maxConcurrentStreams:this.config.maxConcurrency},(c)=>{if(c)throw Error("Fail to set maxConcurrentStreams to "+this.config.maxConcurrency+"when creating new session for "+e.destination.toString())});let s=()=>{this.removeFromPoolAndClose(r,i)},a=()=>{this.removeFromPoolAndCheckedDestroy(r,i)};if(o.on("goaway",s),o.on("error",a),o.on("frameError",a),o.on("close",a),t.requestTimeout)o.setTimeout(t.requestTimeout,a);return n.offerLast(i),i.retain(),i}release(e,t){t.free()}createIsolatedSession(e,t){let r=this.getUrlString(e),n=new Ag(this.connect(r)),i=n.deref();i.settings({maxConcurrentStreams:1});let o=()=>{n.destroy()};if(i.on("error",o),i.on("frameError",o),i.on("close",o),t.requestTimeout)i.setTimeout(t.requestTimeout,o);return n.retain(),n}destroy(){for(let[e,t]of this.connectionPools){for(let r of[...t])r.destroy();this.connectionPools.delete(e)}}setMaxConcurrentStreams(e){if(e&&e<=0)throw RangeError("maxConcurrentStreams must be greater than zero.");this.config.maxConcurrency=e;for(let t of this.connectionPools.values())t.setMaxConcurrency(e)}setDisableConcurrentStreams(e){this.config.disableConcurrency=e}setNodeHttp2ConnectOptions(e){this.connectOptions=e}debug(){let e={};for(let[t,r]of this.connectionPools){let n=[];for(let i of r)n.push({id:i.id,active:i.useCount(),maxConcurrent:i.max,totalRequests:i.total});e[t]={sessions:n}}return e}removeFromPoolAndClose(e,t){this.connectionPools.get(e)?.remove(t),t.close()}removeFromPoolAndCheckedDestroy(e,t){this.connectionPools.get(e)?.remove(t),t.destroy()}getPool(e){if(!this.connectionPools.has(e)){let t=new rD;if(this.config.maxConcurrency)t.setMaxConcurrency(this.config.maxConcurrency);this.connectionPools.set(e,t)}return this.connectionPools.get(e)}getUrlString(e){return e.destination.toString()}connect(e){return this.connectOptions===void 0?dh.connect(e):dh.connect(e,this.connectOptions)}}var{constants:QI}=dh;class TS{config;configProvider;metadata={handlerProtocol:"h2"};connectionManager=new nD({});static create(e){if(typeof e?.handle==="function")return e;return new TS(e)}constructor(e){this.configProvider=new Promise((t,r)=>{if(typeof e==="function")e().then((n)=>{t(n||{})}).catch(r);else t(e||{})})}destroy(){this.connectionManager.destroy()}async handle(e,{abortSignal:t,requestTimeout:r,isEventStream:n}={}){if(!this.config){this.config=await this.configProvider;let{disableConcurrentStreams:c,maxConcurrentStreams:u,nodeHttp2ConnectOptions:d}=this.config;if(this.connectionManager.setDisableConcurrentStreams(c??!1),u)this.connectionManager.setMaxConcurrentStreams(u);if(d)this.connectionManager.setNodeHttp2ConnectOptions(d)}let{requestTimeout:i,disableConcurrentStreams:o}=this.config,s=o||n,a=r??i;return new Promise((c,u)=>{let d=!1,f=void 0,h=async(pe)=>{await f,c(pe)},p=async(pe)=>{await f,u(pe)};if(t?.aborted){d=!0;let pe=Eg(t);p(pe);return}let{hostname:g,method:_,port:R,protocol:O,query:I}=e,Ne="";if(e.username!=null||e.password!=null){let pe=e.username??"",ae=e.password??"";Ne=`${pe}:${ae}@`}let k=`${O}//${Ne}${g}${R?`:${R}`:""}`,j={destination:new URL(k)},re={requestTimeout:this.config?.sessionTimeout,isEventStream:n},Oe=s?this.connectionManager.createIsolatedSession(j,re):this.connectionManager.lease(j,re),ne=Oe.deref(),M=(pe)=>{if(s)Oe.destroy();d=!0,p(pe)},F=I?XI(I):"",ce=e.path;if(F)ce+=`?${F}`;if(e.fragment)ce+=`#${e.fragment}`;let de=ne.request({...e.headers,[QI.HTTP2_HEADER_PATH]:ce,[QI.HTTP2_HEADER_METHOD]:_});if(a)de.setTimeout(a,()=>{de.close();let pe=Error(`Stream timed out because of no activity for ${a} ms`);pe.name="TimeoutError",M(pe)});if(t){let pe=()=>{de.close();let ae=Eg(t);M(ae)};if(typeof t.addEventListener==="function"){let ae=t;ae.addEventListener("abort",pe,{once:!0}),de.once("close",()=>ae.removeEventListener("abort",pe))}else t.onabort=pe}de.on("frameError",(pe,ae,He)=>{M(Error(`Frame type id ${pe} in stream id ${He} has failed with code ${ae}.`))}),de.on("error",M),de.on("aborted",()=>{M(Error(`HTTP/2 stream is abnormally aborted in mid-communication with result code ${de.rstCode}.`))}),de.on("response",(pe)=>{let ae=new ZI({statusCode:pe[":status"]??-1,headers:eD(pe),body:de});if(d=!0,h({response:ae}),s)ne.close()}),de.on("close",()=>{if(s)Oe.destroy();else this.connectionManager.release(j,Oe);if(!d)M(Error("Unexpected error: http2 request did not get a response"))}),f=tD(de,e,a)})}updateHttpClientConfig(e,t){this.config=void 0,this.configProvider=this.configProvider.then((r)=>({...r,[e]:t}))}httpHandlerConfigs(){return this.config??{}}}Pne.DEFAULT_REQUEST_TIMEOUT=Dne;Pne.NodeHttp2Handler=TS;Pne.NodeHttpHandler=Sg});var fj=A(function(P8e,lj){function hs(e,t){if(typeof t==="boolean")t={forever:t};if(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)}lj.exports=hs;hs.prototype.reset=function(){this._attempts=1,this._timeouts=this._originalTimeouts.slice(0)};hs.prototype.stop=function(){if(this._timeout)clearTimeout(this._timeout);if(this._timer)clearTimeout(this._timer);this._timeouts=[],this._cachedTimeouts=null};hs.prototype.retry=function(e){if(this._timeout)clearTimeout(this._timeout);if(!e)return!1;var t=new Date().getTime();if(e&&t-this._operationStart>=this._maxRetryTime)return this._errors.push(e),this._errors.unshift(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;if(this._timer=setTimeout(function(){if(n._attempts++,n._operationTimeoutCb){if(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();return!0};hs.prototype.attempt=function(e,t){if(this._fn=e,t){if(t.timeout)this._operationTimeout=t.timeout;if(t.cb)this._operationTimeoutCb=t.cb}var r=this;if(this._operationTimeoutCb)this._timeout=setTimeout(function(){r._operationTimeoutCb()},r._operationTimeout);this._operationStart=new Date().getTime(),this._fn(this._attempts)};hs.prototype.try=function(e){console.log("Using RetryOperation.try() is deprecated"),this.attempt(e)};hs.prototype.start=function(e){console.log("Using RetryOperation.start() is deprecated"),this.attempt(e)};hs.prototype.start=hs.prototype.try;hs.prototype.errors=function(){return this._errors};hs.prototype.attempts=function(){return this._attempts};hs.prototype.mainError=function(){if(this._errors.length===0)return null;var e={},t=null,r=0;for(var n=0;n<this._errors.length;n++){var i=this._errors[n],o=i.message,s=(e[o]||0)+1;if(e[o]=s,s>=r)t=i,r=s}return t}});var pj=A(function(Jv){var Xfe=fj();Jv.operation=function(e){var t=Jv.timeouts(e);return new Xfe(t,{forever:e&&(e.forever||e.retries===1/0),unref:e&&e.unref,maxRetryTime:e&&e.maxRetryTime})};Jv.timeouts=function(e){if(e instanceof Array)return[].concat(e);var t={retries:10,factor:2,minTimeout:1000,maxTimeout:1/0,randomize:!1};for(var r in e)t[r]=e[r];if(t.minTimeout>t.maxTimeout)throw Error("minTimeout is greater than maxTimeout");var n=[];for(var i=0;i<t.retries;i++)n.push(this.createTimeout(i,t));if(e&&e.forever&&!n.length)n.push(this.createTimeout(i,t));return n.sort(function(o,s){return o-s}),n};Jv.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};Jv.wrap=function(e,t,r){if(t instanceof Array)r=t,t=null;if(!r){r=[];for(var n in e)if(typeof e[n]==="function")r.push(n)}for(var i=0;i<r.length;i++){var o=r[i],s=e[o];e[o]=function(c){var u=Jv.operation(t),d=Array.prototype.slice.call(arguments,1),f=d.pop();d.push(function(h){if(u.retry(h))return;if(h)arguments[0]=u.mainError();f.apply(this,arguments)}),u.attempt(function(){c.apply(e,d)})}.bind(e,s),e[o].options=t}}});var Qr=A(function(M8e,Fw){var mj=pj(),rhe=["Failed to fetch","NetworkError when attempting to fetch resource.","The Internet connection appears to be offline.","Network request failed"];class Qv extends Error{constructor(e){super();if(e instanceof Error)this.originalError=e,{message:e}=e;else this.originalError=Error(e),this.originalError.stack=this.stack;this.name="AbortError",this.message=e}}var nhe=(e,t,r)=>{let n=r.retries-(t-1);return e.attemptNumber=t,e.retriesLeft=n,e},ihe=(e)=>rhe.includes(e),gj=(e,t)=>new Promise((r,n)=>{t={onFailedAttempt:()=>{},retries:10,...t};let i=mj.operation(t);i.attempt(async(o)=>{try{r(await e(o))}catch(s){if(!(s instanceof Error)){n(TypeError(`Non-error was thrown: "${s}". You should only throw errors.`));return}if(s instanceof Qv)i.stop(),n(s.originalError);else if(s instanceof TypeError&&!ihe(s.message))i.stop(),n(s);else{nhe(s,o,t);try{await t.onFailedAttempt(s)}catch(a){n(a);return}if(!i.retry(s))n(i.mainError())}}})});Fw.exports=gj;Fw.exports.default=gj;Fw.exports.AbortError=Qv});var Yv=A(function(q8e,Tj){var zw=Object.prototype.hasOwnProperty,Aj=Object.prototype.toString,{defineProperty:yj,getOwnPropertyDescriptor:wj}=Object,_j=function(t){if(typeof Array.isArray==="function")return Array.isArray(t);return Aj.call(t)==="[object Array]"},bj=function(t){if(!t||Aj.call(t)!=="[object Object]")return!1;var r=zw.call(t,"constructor"),n=t.constructor&&t.constructor.prototype&&zw.call(t.constructor.prototype,"isPrototypeOf");if(t.constructor&&!r&&!n)return!1;var i;for(i in t);return typeof i>"u"||zw.call(t,i)},Ej=function(t,r){if(yj&&r.name==="__proto__")yj(t,r.name,{enumerable:!0,configurable:!0,value:r.newValue,writable:!0});else t[r.name]=r.newValue},Sj=function(t,r){if(r==="__proto__"){if(!zw.call(t,r))return;else if(wj)return wj(t,r).value}return t[r]};Tj.exports=function e(){var t,r,n,i,o,s,a=arguments[0],c=1,u=arguments.length,d=!1;if(typeof a==="boolean")d=a,a=arguments[1]||{},c=2;if(a==null||typeof a!=="object"&&typeof a!=="function")a={};for(;c<u;++c)if(t=arguments[c],t!=null){for(r in t)if(n=Sj(a,r),i=Sj(t,r),a!==i){if(d&&i&&(bj(i)||(o=_j(i)))){if(o)o=!1,s=n&&_j(n)?n:[];else s=n&&bj(n)?n:{};Ej(a,{name:r,newValue:e(d,s,i)})}else if(typeof i<"u")Ej(a,{name:r,newValue:i})}}return a}});var vj=A(function(B8e,ohe){ohe.exports={name:"gaxios",version:"7.3.1",description:"A simple common HTTP client specifically for Google APIs and services.",main:"build/cjs/src/index.js",types:"build/cjs/src/index.d.ts",files:["build/"],exports:{".":{import:{types:"./build/esm/src/index.d.ts",default:"./build/esm/src/index.js"},require:{types:"./build/cjs/src/index.d.ts",default:"./build/cjs/src/index.js"}}},scripts:{lint:"gts check --no-inline-config",test:"c8 mocha build/esm/test","presystem-test":"npm run compile","system-test":"mocha build/esm/system-test --timeout 80000",compile:"tsc -b ./tsconfig.json ./tsconfig.cjs.json && node utils/enable-esm.mjs",fix:"gts fix",prepare:"npm run compile",pretest:"npm run compile",webpack:"webpack","prebrowser-test":"npm run compile","browser-test":"node build/browser-test/browser-test-runner.js",docs:"jsdoc -c .jsdoc.js","samples-test":"cd samples/ && npm link ../ && npm test && cd ../",prelint:"cd samples; npm link ../; npm install",clean:"gts clean"},repository:{type:"git",directory:"core/packages/gaxios",url:"https://github.com/googleapis/google-cloud-node.git"},keywords:["google"],engines:{node:">=18"},author:"Google, LLC",license:"Apache-2.0",devDependencies:{"@babel/plugin-proposal-private-methods":"^7.18.6","@types/cors":"^2.8.6","@types/express":"^5.0.0","@types/extend":"^3.0.1","@types/mocha":"^10.0.10","@types/multiparty":"4.2.1","@types/mv":"^2.1.0","@types/ncp":"^2.0.8","@types/node":"^24.0.0","@types/sinon":"^21.0.0","@types/tmp":"^0.2.6",assert:"^2.0.0",browserify:"^17.0.0",c8:"^10.1.3",cors:"^2.8.5",express:"^5.0.0",gts:"^6.0.2","is-docker":"^3.0.0",jsdoc:"^4.0.4","jsdoc-fresh":"^5.0.0","jsdoc-region-tag":"^4.0.0",karma:"^6.0.0","karma-chrome-launcher":"^3.0.0","karma-coverage":"^2.0.0","karma-firefox-launcher":"^2.0.0","karma-mocha":"^2.0.0","karma-remap-coverage":"^0.1.5","karma-sourcemap-loader":"^0.4.0","karma-webpack":"^5.0.0",mocha:"^11.1.0",multiparty:"^4.2.1",mv:"^2.1.1",ncp:"^2.0.0",nock:"14.0.5","null-loader":"^4.0.1","pack-n-play":"^4.0.0",puppeteer:"^24.0.0",sinon:"21.0.3","stream-browserify":"^3.0.0",tmp:"0.2.7","ts-loader":"^9.5.2",typescript:"5.8.3","undici-types":"^7.24.1",webpack:"^5.97.1","webpack-cli":"^6.0.1"},dependencies:{extend:"^3.0.2","https-proxy-agent":"^7.0.1","node-fetch":"^3.3.2"},homepage:"https://github.com/googleapis/google-cloud-node/tree/main/core/packages/gaxios"}});var Rj=A(function(j8e,kj){var she=vj();kj.exports={pkg:she}});var e0=A(function(ps){var xj=ps&&ps.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(ps,"__esModule",{value:!0});ps.GaxiosError=ps.GAXIOS_ERROR_SYMBOL=void 0;ps.defaultErrorRedactor=Cj;var Nj=xj(Yv()),ahe=xj(Rj()),Xv=ahe.default.pkg;ps.GAXIOS_ERROR_SYMBOL=Symbol.for(`${Xv.name}-gaxios-error`);class Zv extends Error{config;response;code;status;error;[ps.GAXIOS_ERROR_SYMBOL]=Xv.version;static[Symbol.hasInstance](e){if(e&&typeof e==="object"&&ps.GAXIOS_ERROR_SYMBOL in e&&e[ps.GAXIOS_ERROR_SYMBOL]===Xv.version)return!0;return Function.prototype[Symbol.hasInstance].call(Zv,e)}constructor(e,t,r,n){super(e,{cause:n});if(this.config=t,this.response=r,this.error=n instanceof Error?n:void 0,this.config=(0,Nj.default)(!0,{},t),this.response)this.response.config=(0,Nj.default)(!0,{},this.response.config);if(this.response){try{this.response.data=che(this.config.responseType,this.response?.bodyUsed?this.response?.data:void 0)}catch{}this.status=this.response.status}if(n instanceof DOMException)this.code=n.name;else if(n&&typeof n==="object"&&"code"in n&&(typeof n.code==="string"||typeof n.code==="number"))this.code=n.code}static extractAPIErrorFromResponse(e,t="The request failed"){let r=t;if(typeof e.data==="string")r=e.data;if(e.data&&typeof e.data==="object"&&"error"in e.data&&e.data.error&&!e.ok){if(typeof e.data.error==="string")return{message:e.data.error,code:e.status,status:e.statusText};if(typeof e.data.error==="object"){r="message"in e.data.error&&typeof e.data.error.message==="string"?e.data.error.message:r;let n="status"in e.data.error&&typeof e.data.error.status==="string"?e.data.error.status:e.statusText,i="code"in e.data.error&&typeof e.data.error.code==="number"?e.data.error.code:e.status;if("errors"in e.data.error&&Array.isArray(e.data.error.errors)){let o=[];for(let s of e.data.error.errors)if(typeof s==="object"&&"message"in s&&typeof s.message==="string")o.push(s.message);return Object.assign({message:o.join(`
45
+ `)||r,code:i,status:n},e.data.error)}return Object.assign({message:r,code:i,status:n},e.data.error)}}return{message:r,code:e.status,status:e.statusText}}}ps.GaxiosError=Zv;function che(e,t){switch(e){case"stream":return t;case"json":return JSON.parse(JSON.stringify(t));case"arraybuffer":return JSON.parse(Buffer.from(t).toString("utf8"));case"blob":return JSON.parse(t.text());default:return t}}function Cj(e){function r(o){if(!o)return;o.forEach((s,a)=>{if(/^authentication$/i.test(a)||/^authorization$/i.test(a)||/secret/i.test(a))o.set(a,"<<REDACTED> - See `errorRedactor` option in `gaxios` for configuration>.")})}function n(o,s){if(typeof o==="object"&&o!==null&&typeof o[s]==="string"){let a=o[s];if(/grant_type=/i.test(a)||/assertion=/i.test(a)||/secret/i.test(a))o[s]="<<REDACTED> - See `errorRedactor` option in `gaxios` for configuration>."}}function i(o){if(!o||typeof o!=="object")return;else if(o instanceof FormData||o instanceof URLSearchParams||"forEach"in o&&"set"in o)o.forEach((s,a)=>{if(["grant_type","assertion"].includes(a)||/secret/.test(a))o.set(a,"<<REDACTED> - See `errorRedactor` option in `gaxios` for configuration>.")});else{if("grant_type"in o)o.grant_type="<<REDACTED> - See `errorRedactor` option in `gaxios` for configuration>.";if("assertion"in o)o.assertion="<<REDACTED> - See `errorRedactor` option in `gaxios` for configuration>.";if("client_secret"in o)o.client_secret="<<REDACTED> - See `errorRedactor` option in `gaxios` for configuration>."}}if(e.config){if(r(e.config.headers),n(e.config,"data"),i(e.config.data),n(e.config,"body"),i(e.config.body),e.config.url.searchParams.has("token"))e.config.url.searchParams.set("token","<<REDACTED> - See `errorRedactor` option in `gaxios` for configuration>.");if(e.config.url.searchParams.has("client_secret"))e.config.url.searchParams.set("client_secret","<<REDACTED> - See `errorRedactor` option in `gaxios` for configuration>.")}if(e.response){if(Cj({config:e.response.config}),r(e.response.headers),e.response.bodyUsed)n(e.response,"data"),i(e.response.data)}return e}});var Dj=A(function(Ij){Object.defineProperty(Ij,"__esModule",{value:!0});Ij.getRetryConfig=uhe;async function uhe(e){let t=Oj(e);if(!e||!e.config||!t&&!e.config.retry)return{shouldRetry:!1};t=t||{},t.currentRetryAttempt=t.currentRetryAttempt||0,t.retry=t.retry===void 0||t.retry===null?3:t.retry,t.httpMethodsToRetry=t.httpMethodsToRetry||["GET","HEAD","PUT","OPTIONS","DELETE"],t.noResponseRetries=t.noResponseRetries===void 0||t.noResponseRetries===null?2:t.noResponseRetries,t.retryDelayMultiplier=t.retryDelayMultiplier?t.retryDelayMultiplier:2,t.timeOfFirstRequest=t.timeOfFirstRequest?t.timeOfFirstRequest:Date.now(),t.totalTimeout=t.totalTimeout?t.totalTimeout:Number.MAX_SAFE_INTEGER,t.maxRetryDelay=t.maxRetryDelay?t.maxRetryDelay:Number.MAX_SAFE_INTEGER;let r=[[100,199],[408,408],[429,429],[500,599]];if(t.statusCodesToRetry=t.statusCodesToRetry||r,e.config.retryConfig=t,!await(t.shouldRetry||dhe)(e))return{shouldRetry:!1,config:e.config};let i=lhe(t);e.config.retryConfig.currentRetryAttempt+=1;let o=t.retryBackoff?t.retryBackoff(e,i):new Promise((s)=>{setTimeout(s,i)});if(t.onRetryAttempt)await t.onRetryAttempt(e);return await o,{shouldRetry:!0,config:e.config}}function dhe(e){let t=Oj(e);if(e.config.signal?.aborted&&e.code!=="TimeoutError"||e.code==="AbortError")return!1;if(!t||t.retry===0)return!1;if(!e.response&&(t.currentRetryAttempt||0)>=t.noResponseRetries)return!1;if(!t.httpMethodsToRetry||!t.httpMethodsToRetry.includes(e.config.method?.toUpperCase()||"GET"))return!1;if(e.response&&e.response.status){let r=!1;for(let[n,i]of t.statusCodesToRetry){let o=e.response.status;if(o>=n&&o<=i){r=!0;break}}if(!r)return!1}if(t.currentRetryAttempt=t.currentRetryAttempt||0,t.currentRetryAttempt>=t.retry)return!1;return!0}function Oj(e){if(e&&e.config&&e.config.retryConfig)return e.config.retryConfig;return}function lhe(e){let r=(e.currentRetryAttempt?0:e.retryDelay??100)+(Math.pow(e.retryDelayMultiplier,e.currentRetryAttempt)-1)/2*1000,n=e.totalTimeout-(Date.now()-e.timeOfFirstRequest);return Math.min(r,n,e.maxRetryDelay)}});var t0=A(function(Pj){Object.defineProperty(Pj,"__esModule",{value:!0});Pj.GaxiosInterceptorManager=void 0;class Uj extends Set{}Pj.GaxiosInterceptorManager=Uj});var Bj=A(function(Zl){var hhe=Zl&&Zl.__importDefault||function(e){return e&&e.__esModule?e:{default:e}},Xl;Object.defineProperty(Zl,"__esModule",{value:!0});Zl.Gaxios=void 0;var phe=hhe(Yv()),Mj=C("https"),Do=e0(),qj=Dj(),Ww=C("stream"),Hw=t0(),mhe=async()=>globalThis.crypto?.randomUUID()||(await import("crypto")).randomUUID(),ghe=204;class r0{agentCache=new Map;defaults;interceptors;constructor(e){this.defaults=e||{},this.interceptors={request:new Hw.GaxiosInterceptorManager,response:new Hw.GaxiosInterceptorManager}}fetch(...e){let t=e[0],r=e[1],n=void 0,i=new Headers;if(typeof t==="string")n=new URL(t);else if(t instanceof URL)n=t;else if(t&&t.url)n=new URL(t.url);if(t&&typeof t==="object"&&"headers"in t)Xl.mergeHeaders(i,t.headers);if(r)Xl.mergeHeaders(i,new Headers(r.headers));if(typeof t==="object"&&!(t instanceof URL))return this.request({...r,...t,headers:i,url:n});else return this.request({...r,headers:i,url:n})}async request(e={}){let t=await this.#n(e);return t=await this.#t(t),this.#r(this._request(t))}async _defaultAdapter(e){let t=e.fetchImplementation||this.defaults.fetchImplementation||await Xl.#a(),r={...e};delete r.data;let n=await t(e.url,r),i=await this.getResponseData(e,n);if(!Object.getOwnPropertyDescriptor(n,"data")?.configurable)Object.defineProperties(n,{data:{configurable:!0,writable:!0,enumerable:!0,value:i}});return Object.assign(n,{config:e,data:i})}async _request(e){try{let t;if(e.adapter)t=await e.adapter(e,this._defaultAdapter.bind(this));else t=await this._defaultAdapter(e);if(!e.validateStatus(t.status)){if(e.responseType==="stream"){let n=[];for await(let i of t.data)n.push(i);t.data=Buffer.concat(n.map((i)=>typeof i==="string"?Buffer.from(i):i)).toString("utf8")}let r=Do.GaxiosError.extractAPIErrorFromResponse(t,`Request failed with status code ${t.status}`);throw new Do.GaxiosError(r?.message,e,t,r)}return t}catch(t){let r;if(t instanceof Do.GaxiosError)r=t;else if(t instanceof Error)r=new Do.GaxiosError(t.message,e,void 0,t);else r=new Do.GaxiosError("Unexpected Gaxios Error",e,void 0,t);let{shouldRetry:n,config:i}=await qj.getRetryConfig(r);if(n&&i)return r.config.retryConfig.currentRetryAttempt=i.retryConfig.currentRetryAttempt,e.retryConfig=r.config?.retryConfig,this.#i(e),this._request(e);if(e.errorRedactor)e.errorRedactor(r);throw r}}async getResponseData(e,t){if(t.status===ghe)return"";if(e.maxContentLength&&t.headers.has("content-length")&&e.maxContentLength<Number.parseInt(t.headers?.get("content-length")||""))throw new Do.GaxiosError("Response's `Content-Length` is over the limit.",e,Object.assign(t,{config:e}));switch(e.responseType){case"stream":return t.body;case"json":{let r=await t.text();try{return JSON.parse(r)}catch{return r}}case"arraybuffer":return t.arrayBuffer();case"blob":return t.blob();case"text":return t.text();default:return this.getResponseDataFromContentType(t)}}#e(e,t=[]){let r=new URL(e),n=[...t],i=(process.env.NO_PROXY??process.env.no_proxy)?.split(",")||[];for(let o of i)n.push(o.trim());for(let o of n)if(o instanceof RegExp){if(o.test(r.toString()))return!1}else if(o instanceof URL){if(o.origin===r.origin)return!1}else if(o.startsWith("*.")||o.startsWith(".")){let s=o.replace(/^\*\./,".");if(r.hostname.endsWith(s))return!1}else if(o===r.origin||o===r.hostname||o===r.href)return!1;return!0}async#t(e){let t=Promise.resolve(e);for(let r of this.interceptors.request.values())if(r)t=t.then(r.resolved,r.rejected);return t}async#r(e){let t=Promise.resolve(e);for(let r of this.interceptors.response.values())if(r)t=t.then(r.resolved,r.rejected);return t}async#n(e){let t=new Headers(this.defaults.headers);Xl.mergeHeaders(t,e.headers);let r=(0,phe.default)(!0,{},this.defaults,e);if(!r.url)throw Error("URL is required.");if(r.baseURL)r.url=new URL(r.url,r.baseURL);if(r.url=new URL(r.url),r.params)if(r.paramsSerializer){let o=r.paramsSerializer(r.params);if(o.startsWith("?"))o=o.slice(1);let s=r.url.toString().includes("?")?"&":"?";r.url=r.url+s+o}else{let o=r.url instanceof URL?r.url:new URL(r.url);for(let[s,a]of new URLSearchParams(r.params))o.searchParams.append(s,a);r.url=o}if(typeof e.maxContentLength==="number")r.size=e.maxContentLength;if(typeof e.maxRedirects==="number")r.follow=e.maxRedirects;let n=typeof r.data==="string"||r.data instanceof ArrayBuffer||r.data instanceof Blob||globalThis.File&&r.data instanceof File||r.data instanceof FormData||r.data instanceof Ww.Readable||r.data instanceof ReadableStream||r.data instanceof String||r.data instanceof URLSearchParams||ArrayBuffer.isView(r.data)||["Blob","File","FormData"].includes(r.data?.constructor?.name||"");if(r.multipart?.length){let o=await mhe();t.set("content-type",`multipart/related; boundary=${o}`),r.body=Ww.Readable.from(this.getMultipartRequest(r.multipart,o))}else if(n)r.body=r.data;else if(typeof r.data==="object")if(t.get("Content-Type")==="application/x-www-form-urlencoded")r.body=r.paramsSerializer?r.paramsSerializer(r.data):new URLSearchParams(r.data);else{if(!t.has("content-type"))t.set("content-type","application/json");r.body=JSON.stringify(r.data)}else if(r.data)r.body=r.data;if(r.validateStatus=r.validateStatus||this.validateStatus,r.responseType=r.responseType||"unknown",!t.has("accept")&&r.responseType==="json")t.set("accept","application/json");let i=r.proxy||process?.env?.HTTPS_PROXY||process?.env?.https_proxy||process?.env?.HTTP_PROXY||process?.env?.http_proxy;if(r.agent);else if(i&&this.#e(r.url,r.noProxy)){let o=await Xl.#o();if(this.agentCache.has(i))r.agent=this.agentCache.get(i);else r.agent=new o(i,{cert:r.cert,key:r.key}),this.agentCache.set(i,r.agent)}else if(r.cert&&r.key)if(this.agentCache.has(r.key))r.agent=this.agentCache.get(r.key);else r.agent=new Mj.Agent({cert:r.cert,key:r.key}),this.agentCache.set(r.key,r.agent);if(typeof r.errorRedactor!=="function"&&r.errorRedactor!==!1)r.errorRedactor=Do.defaultErrorRedactor;if(r.body&&!("duplex"in r))r.duplex="half";return this.#i(r),Object.assign(r,{headers:t,url:r.url instanceof URL?r.url:new URL(r.url)})}#i(e){if(e.timeout){let t=AbortSignal.timeout(e.timeout);if(e.signal&&!e.signal.aborted)e.signal=AbortSignal.any([e.signal,t]);else e.signal=t}}validateStatus(e){return e>=200&&e<300}async getResponseDataFromContentType(e){let t=e.headers.get("Content-Type");if(t===null)return e.text();if(t=t.toLowerCase(),t.includes("application/json")){let r=await e.text();try{r=JSON.parse(r)}catch{}return r}else if(t.match(/^text\//))return e.text();else return e.blob()}async*getMultipartRequest(e,t){let r=`--${t}--`;for(let n of e){let i=n.headers.get("Content-Type")||"application/octet-stream";if(yield`--${t}\r
46
+ Content-Type: ${i}\r
47
+ \r
48
+ `,typeof n.content==="string")yield n.content;else yield*n.content;yield`\r
49
+ `}yield r}static#s;static#c;static async#o(){return this.#s||=(await import("./chunk-m3saxrzj.js").then((m)=>E(m.default))).HttpsProxyAgent,this.#s}static async#a(){let e=typeof window<"u"&&!!window;return this.#c||=e?window.fetch:(await import("node-fetch")).default,this.#c}static mergeHeaders(e,...t){e=e instanceof Headers?e:new Headers(e);for(let r of t)(r instanceof Headers?r:new Headers(r)).forEach((i,o)=>{o==="set-cookie"?e.append(o,i):e.set(o,i)});return e}}Zl.Gaxios=r0;Xl=r0});var to=A(function(So){var yhe=So&&So.__createBinding||(Object.create?function(e,t,r,n){if(n===void 0)n=r;var i=Object.getOwnPropertyDescriptor(t,r);if(!i||("get"in i?!t.__esModule:i.writable||i.configurable))i={enumerable:!0,get:function(){return t[r]}};Object.defineProperty(e,n,i)}:function(e,t,r,n){if(n===void 0)n=r;e[n]=t[r]}),whe=So&&So.__exportStar||function(e,t){for(var r in e)if(r!=="default"&&!Object.prototype.hasOwnProperty.call(t,r))yhe(t,e,r)};Object.defineProperty(So,"__esModule",{value:!0});So.instance=So.Gaxios=So.GaxiosError=void 0;So.request=bhe;var Vw=Bj();Object.defineProperty(So,"Gaxios",{enumerable:!0,get:function(){return Vw.Gaxios}});var _he=e0();Object.defineProperty(So,"GaxiosError",{enumerable:!0,get:function(){return _he.GaxiosError}});whe(t0(),So);So.instance=new Vw.Gaxios;async function bhe(e){return So.instance.request(e)}});var n0=A(function(jj,Gw){(function(e){var t,r=/^-?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?$/i,{ceil:n,floor:i}=Math,o="[BigNumber Error] ",s=o+"Number primitive has more than 15 significant digits: ",a=100000000000000,c=14,u=9007199254740991,d=[1,10,100,1000,1e4,1e5,1e6,1e7,1e8,1e9,10000000000,100000000000,1000000000000,10000000000000],f=1e7,h=1e9;function p(j){var re,Oe,ne,M=ot.prototype={constructor:ot,toString:null,valueOf:null},F=new ot(1),ce=20,de=4,pe=-7,ae=21,He=-1e7,Be=1e7,Ke=!1,Te=1,Ve=0,Je={prefix:"",groupSize:3,secondaryGroupSize:0,groupSeparator:",",decimalSeparator:".",fractionGroupSize:0,fractionGroupSeparator:"\xA0",suffix:""},ft="0123456789abcdefghijklmnopqrstuvwxyz",qt=!0;function ot(Z,Ae){var De,rt,je,We,it,Me,$e,nt,Qe=this;if(!(Qe instanceof ot))return new ot(Z,Ae);if(Ae==null){if(Z&&Z._isBigNumber===!0){if(Qe.s=Z.s,!Z.c||Z.e>Be)Qe.c=Qe.e=null;else if(Z.e<He)Qe.c=[Qe.e=0];else Qe.e=Z.e,Qe.c=Z.c.slice();return}if((Me=typeof Z=="number")&&Z*0==0){if(Qe.s=1/Z<0?(Z=-Z,-1):1,Z===~~Z){for(We=0,it=Z;it>=10;it/=10,We++);if(We>Be)Qe.c=Qe.e=null;else Qe.e=We,Qe.c=[Z];return}nt=String(Z)}else{if(!r.test(nt=String(Z)))return ne(Qe,nt,Me);Qe.s=nt.charCodeAt(0)==45?(nt=nt.slice(1),-1):1}if((We=nt.indexOf("."))>-1)nt=nt.replace(".","");if((it=nt.search(/e/i))>0){if(We<0)We=it;We+=+nt.slice(it+1),nt=nt.substring(0,it)}else if(We<0)We=nt.length}else{if(O(Ae,2,ft.length,"Base"),Ae==10&&qt)return Qe=new ot(Z),Kt(Qe,ce+Qe.e+1,de);if(nt=String(Z),Me=typeof Z=="number"){if(Z*0!=0)return ne(Qe,nt,Me,Ae);if(Qe.s=1/Z<0?(nt=nt.slice(1),-1):1,ot.DEBUG&&nt.replace(/^0\.0*|\./,"").length>15)throw Error(s+Z)}else Qe.s=nt.charCodeAt(0)===45?(nt=nt.slice(1),-1):1;De=ft.slice(0,Ae),We=it=0;for($e=nt.length;it<$e;it++)if(De.indexOf(rt=nt.charAt(it))<0){if(rt=="."){if(it>We){We=$e;continue}}else if(!je){if(nt==nt.toUpperCase()&&(nt=nt.toLowerCase())||nt==nt.toLowerCase()&&(nt=nt.toUpperCase())){je=!0,it=-1,We=0;continue}}return ne(Qe,String(Z),Me,Ae)}if(Me=!1,nt=Oe(nt,Ae,10,Qe.s),(We=nt.indexOf("."))>-1)nt=nt.replace(".","");else We=nt.length}for(it=0;nt.charCodeAt(it)===48;it++);for($e=nt.length;nt.charCodeAt(--$e)===48;);if(nt=nt.slice(it,++$e)){if($e-=it,Me&&ot.DEBUG&&$e>15&&(Z>u||Z!==i(Z)))throw Error(s+Qe.s*Z);if((We=We-it-1)>Be)Qe.c=Qe.e=null;else if(We<He)Qe.c=[Qe.e=0];else{if(Qe.e=We,Qe.c=[],it=(We+1)%c,We<0)it+=c;if(it<$e){if(it)Qe.c.push(+nt.slice(0,it));for($e-=c;it<$e;)Qe.c.push(+nt.slice(it,it+=c));it=c-(nt=nt.slice(it)).length}else it-=$e;for(;it--;nt+="0");Qe.c.push(+nt)}}else Qe.c=[Qe.e=0]}ot.clone=p,ot.ROUND_UP=0,ot.ROUND_DOWN=1,ot.ROUND_CEIL=2,ot.ROUND_FLOOR=3,ot.ROUND_HALF_UP=4,ot.ROUND_HALF_DOWN=5,ot.ROUND_HALF_EVEN=6,ot.ROUND_HALF_CEIL=7,ot.ROUND_HALF_FLOOR=8,ot.EUCLID=9,ot.config=ot.set=function(Z){var Ae,De;if(Z!=null)if(typeof Z=="object"){if(Z.hasOwnProperty(Ae="DECIMAL_PLACES"))De=Z[Ae],O(De,0,h,Ae),ce=De;if(Z.hasOwnProperty(Ae="ROUNDING_MODE"))De=Z[Ae],O(De,0,8,Ae),de=De;if(Z.hasOwnProperty(Ae="EXPONENTIAL_AT"))if(De=Z[Ae],De&&De.pop)O(De[0],-h,0,Ae),O(De[1],0,h,Ae),pe=De[0],ae=De[1];else O(De,-h,h,Ae),pe=-(ae=De<0?-De:De);if(Z.hasOwnProperty(Ae="RANGE"))if(De=Z[Ae],De&&De.pop)O(De[0],-h,-1,Ae),O(De[1],1,h,Ae),He=De[0],Be=De[1];else if(O(De,-h,h,Ae),De)He=-(Be=De<0?-De:De);else throw Error(o+Ae+" cannot be zero: "+De);if(Z.hasOwnProperty(Ae="CRYPTO"))if(De=Z[Ae],De===!!De)if(De)if(typeof crypto<"u"&&crypto&&(crypto.getRandomValues||crypto.randomBytes))Ke=De;else throw Ke=!De,Error(o+"crypto unavailable");else Ke=De;else throw Error(o+Ae+" not true or false: "+De);if(Z.hasOwnProperty(Ae="MODULO_MODE"))De=Z[Ae],O(De,0,9,Ae),Te=De;if(Z.hasOwnProperty(Ae="POW_PRECISION"))De=Z[Ae],O(De,0,h,Ae),Ve=De;if(Z.hasOwnProperty(Ae="FORMAT"))if(De=Z[Ae],typeof De=="object")Je=De;else throw Error(o+Ae+" not an object: "+De);if(Z.hasOwnProperty(Ae="ALPHABET"))if(De=Z[Ae],typeof De=="string"&&!/^.?$|[+\-.\s]|(.).*\1/.test(De))qt=De.slice(0,10)=="0123456789",ft=De;else throw Error(o+Ae+" invalid: "+De)}else throw Error(o+"Object expected: "+Z);return{DECIMAL_PLACES:ce,ROUNDING_MODE:de,EXPONENTIAL_AT:[pe,ae],RANGE:[He,Be],CRYPTO:Ke,MODULO_MODE:Te,POW_PRECISION:Ve,FORMAT:Je,ALPHABET:ft}},ot.isBigNumber=function(Z){if(!Z||Z._isBigNumber!==!0)return!1;if(!ot.DEBUG)return!0;var Ae,De,{c:rt,e:je,s:We}=Z;e:if({}.toString.call(rt)=="[object Array]"){if((We===1||We===-1)&&je>=-h&&je<=h&&je===i(je)){if(rt[0]===0){if(je===0&&rt.length===1)return!0;break e}if(Ae=(je+1)%c,Ae<1)Ae+=c;if(String(rt[0]).length==Ae){for(Ae=0;Ae<rt.length;Ae++)if(De=rt[Ae],De<0||De>=a||De!==i(De))break e;if(De!==0)return!0}}}else if(rt===null&&je===null&&(We===null||We===1||We===-1))return!0;throw Error(o+"Invalid BigNumber: "+Z)},ot.maximum=ot.max=function(){return un(arguments,-1)},ot.minimum=ot.min=function(){return un(arguments,1)},ot.random=function(){var Z=9007199254740992,Ae=Math.random()*Z&2097151?function(){return i(Math.random()*Z)}:function(){return(Math.random()*1073741824|0)*8388608+(Math.random()*8388608|0)};return function(De){var rt,je,We,it,Me,$e=0,nt=[],Qe=new ot(F);if(De==null)De=ce;else O(De,0,h);if(it=n(De/c),Ke)if(crypto.getRandomValues){rt=crypto.getRandomValues(new Uint32Array(it*=2));for(;$e<it;)if(Me=rt[$e]*131072+(rt[$e+1]>>>11),Me>=9000000000000000)je=crypto.getRandomValues(new Uint32Array(2)),rt[$e]=je[0],rt[$e+1]=je[1];else nt.push(Me%100000000000000),$e+=2;$e=it/2}else if(crypto.randomBytes){rt=crypto.randomBytes(it*=7);for(;$e<it;)if(Me=(rt[$e]&31)*281474976710656+rt[$e+1]*1099511627776+rt[$e+2]*4294967296+rt[$e+3]*16777216+(rt[$e+4]<<16)+(rt[$e+5]<<8)+rt[$e+6],Me>=9000000000000000)crypto.randomBytes(7).copy(rt,$e);else nt.push(Me%100000000000000),$e+=7;$e=it/7}else throw Ke=!1,Error(o+"crypto unavailable");if(!Ke){for(;$e<it;)if(Me=Ae(),Me<9000000000000000)nt[$e++]=Me%100000000000000}if(it=nt[--$e],De%=c,it&&De)Me=d[c-De],nt[$e]=i(it/Me)*Me;for(;nt[$e]===0;nt.pop(),$e--);if($e<0)nt=[We=0];else{for(We=-1;nt[0]===0;nt.splice(0,1),We-=c);for($e=1,Me=nt[0];Me>=10;Me/=10,$e++);if($e<c)We-=c-$e}return Qe.e=We,Qe.c=nt,Qe}}(),ot.sum=function(){var Z=1,Ae=arguments,De=new ot(Ae[0]);for(;Z<Ae.length;)De=De.plus(Ae[Z++]);return De},Oe=function(){var Z="0123456789";function Ae(De,rt,je,We){var it,Me=[0],$e,nt=0,Qe=De.length;for(;nt<Qe;){for($e=Me.length;$e--;Me[$e]*=rt);Me[0]+=We.indexOf(De.charAt(nt++));for(it=0;it<Me.length;it++)if(Me[it]>je-1){if(Me[it+1]==null)Me[it+1]=0;Me[it+1]+=Me[it]/je|0,Me[it]%=je}}return Me.reverse()}return function(De,rt,je,We,it){var Me,$e,nt,Qe,at,jt,Ft,Nn,mi=De.indexOf("."),Oi=ce,vn=de;if(mi>=0)Qe=Ve,Ve=0,De=De.replace(".",""),Nn=new ot(rt),jt=Nn.pow(De.length-mi),Ve=Qe,Nn.c=Ae(k(_(jt.c),jt.e,"0"),10,je,Z),Nn.e=Nn.c.length;Ft=Ae(De,rt,je,it?(Me=ft,Z):(Me=Z,ft)),nt=Qe=Ft.length;for(;Ft[--Qe]==0;Ft.pop());if(!Ft[0])return Me.charAt(0);if(mi<0)--nt;else jt.c=Ft,jt.e=nt,jt.s=We,jt=re(jt,Nn,Oi,vn,je),Ft=jt.c,at=jt.r,nt=jt.e;if($e=nt+Oi+1,mi=Ft[$e],Qe=je/2,at=at||$e<0||Ft[$e+1]!=null,at=vn<4?(mi!=null||at)&&(vn==0||vn==(jt.s<0?3:2)):mi>Qe||mi==Qe&&(vn==4||at||vn==6&&Ft[$e-1]&1||vn==(jt.s<0?8:7)),$e<1||!Ft[0])De=at?k(Me.charAt(1),-Oi,Me.charAt(0)):Me.charAt(0);else{if(Ft.length=$e,at){for(--je;++Ft[--$e]>je;)if(Ft[$e]=0,!$e)++nt,Ft=[1].concat(Ft)}for(Qe=Ft.length;!Ft[--Qe];);for(mi=0,De="";mi<=Qe;De+=Me.charAt(Ft[mi++]));De=k(De,nt,Me.charAt(0))}return De}}(),re=function(){function Z(rt,je,We){var it,Me,$e,nt,Qe=0,at=rt.length,jt=je%f,Ft=je/f|0;for(rt=rt.slice();at--;)$e=rt[at]%f,nt=rt[at]/f|0,it=Ft*$e+nt*jt,Me=jt*$e+it%f*f+Qe,Qe=(Me/We|0)+(it/f|0)+Ft*nt,rt[at]=Me%We;if(Qe)rt=[Qe].concat(rt);return rt}function Ae(rt,je,We,it){var Me,$e;if(We!=it)$e=We>it?1:-1;else for(Me=$e=0;Me<We;Me++)if(rt[Me]!=je[Me]){$e=rt[Me]>je[Me]?1:-1;break}return $e}function De(rt,je,We,it){var Me=0;for(;We--;)rt[We]-=Me,Me=rt[We]<je[We]?1:0,rt[We]=Me*it+rt[We]-je[We];for(;!rt[0]&&rt.length>1;rt.splice(0,1));}return function(rt,je,We,it,Me){var $e,nt,Qe,at,jt,Ft,Nn,mi,Oi,vn,Hn,no,tm,H_,V_,ea,Sf,Zo=rt.s==je.s?1:-1,ho=rt.c,gi=je.c;if(!ho||!ho[0]||!gi||!gi[0])return new ot(!rt.s||!je.s||(ho?gi&&ho[0]==gi[0]:!gi)?NaN:ho&&ho[0]==0||!gi?Zo*0:Zo/0);if(mi=new ot(Zo),Oi=mi.c=[],nt=rt.e-je.e,Zo=We+nt+1,!Me)Me=a,nt=g(rt.e/c)-g(je.e/c),Zo=Zo/c|0;for(Qe=0;gi[Qe]==(ho[Qe]||0);Qe++);if(gi[Qe]>(ho[Qe]||0))nt--;if(Zo<0)Oi.push(1),at=!0;else{if(H_=ho.length,ea=gi.length,Qe=0,Zo+=2,jt=i(Me/(gi[0]+1)),jt>1)gi=Z(gi,jt,Me),ho=Z(ho,jt,Me),ea=gi.length,H_=ho.length;tm=ea,vn=ho.slice(0,ea),Hn=vn.length;for(;Hn<ea;vn[Hn++]=0);if(Sf=gi.slice(),Sf=[0].concat(Sf),V_=gi[0],gi[1]>=Me/2)V_++;do{if(jt=0,$e=Ae(gi,vn,ea,Hn),$e<0){if(no=vn[0],ea!=Hn)no=no*Me+(vn[1]||0);if(jt=i(no/V_),jt>1){if(jt>=Me)jt=Me-1;Ft=Z(gi,jt,Me),Nn=Ft.length,Hn=vn.length;while(Ae(Ft,vn,Nn,Hn)==1)jt--,De(Ft,ea<Nn?Sf:gi,Nn,Me),Nn=Ft.length,$e=1}else{if(jt==0)$e=jt=1;Ft=gi.slice(),Nn=Ft.length}if(Nn<Hn)Ft=[0].concat(Ft);if(De(vn,Ft,Hn,Me),Hn=vn.length,$e==-1)while(Ae(gi,vn,ea,Hn)<1)jt++,De(vn,ea<Hn?Sf:gi,Hn,Me),Hn=vn.length}else if($e===0)jt++,vn=[0];if(Oi[Qe++]=jt,vn[0])vn[Hn++]=ho[tm]||0;else vn=[ho[tm]],Hn=1}while((tm++<H_||vn[0]!=null)&&Zo--);if(at=vn[0]!=null,!Oi[0])Oi.splice(0,1)}if(Me==a){for(Qe=1,Zo=Oi[0];Zo>=10;Zo/=10,Qe++);Kt(mi,We+(mi.e=Qe+nt*c-1)+1,it,at)}else mi.e=nt,mi.r=+at;return mi}}();function Tr(Z,Ae,De,rt){var je,We,it,Me,$e;if(De==null)De=de;else O(De,0,8);if(!Z.c)return Z.toString();if(je=Z.c[0],it=Z.e,Ae==null)$e=_(Z.c),$e=rt==1||rt==2&&(it<=pe||it>=ae)?Ne($e,it):k($e,it,"0");else if(Z=Kt(new ot(Z),Ae,De),We=Z.e,$e=_(Z.c),Me=$e.length,rt==1||rt==2&&(Ae<=We||We<=pe)){for(;Me<Ae;$e+="0",Me++);$e=Ne($e,We)}else if(Ae-=it+(rt===2&&We>it),$e=k($e,We,"0"),We+1>Me){if(--Ae>0)for($e+=".";Ae--;$e+="0");}else if(Ae+=We-Me,Ae>0){if(We+1==Me)$e+=".";for(;Ae--;$e+="0");}return Z.s<0&&je?"-"+$e:$e}function un(Z,Ae){var De,rt,je=1,We=new ot(Z[0]);for(;je<Z.length;je++)if(rt=new ot(Z[je]),!rt.s||(De=R(We,rt))===Ae||De===0&&We.s===Ae)We=rt;return We}function oi(Z,Ae,De){var rt=1,je=Ae.length;for(;!Ae[--je];Ae.pop());for(je=Ae[0];je>=10;je/=10,rt++);if((De=rt+De*c-1)>Be)Z.c=Z.e=null;else if(De<He)Z.c=[Z.e=0];else Z.e=De,Z.c=Ae;return Z}ne=function(){var Z=/^(-?)0([xbo])(?=\w[\w.]*$)/i,Ae=/^([^.]+)\.$/,De=/^\.([^.]+)$/,rt=/^-?(Infinity|NaN)$/,je=/^\s*\+(?=[\w.])|^\s+|\s+$/g;return function(We,it,Me,$e){var nt,Qe=Me?it:it.replace(je,"");if(rt.test(Qe))We.s=isNaN(Qe)?null:Qe<0?-1:1;else{if(!Me){if(Qe=Qe.replace(Z,function(at,jt,Ft){return nt=(Ft=Ft.toLowerCase())=="x"?16:Ft=="b"?2:8,!$e||$e==nt?jt:at}),$e)nt=$e,Qe=Qe.replace(Ae,"$1").replace(De,"0.$1");if(it!=Qe)return new ot(Qe,nt)}if(ot.DEBUG)throw Error(o+"Not a"+($e?" base "+$e:"")+" number: "+it);We.s=null}We.c=We.e=null}}();function Kt(Z,Ae,De,rt){var je,We,it,Me,$e,nt,Qe,at=Z.c,jt=d;if(at){e:{for(je=1,Me=at[0];Me>=10;Me/=10,je++);if(We=Ae-je,We<0)We+=c,it=Ae,$e=at[nt=0],Qe=i($e/jt[je-it-1]%10);else if(nt=n((We+1)/c),nt>=at.length)if(rt){for(;at.length<=nt;at.push(0));$e=Qe=0,je=1,We%=c,it=We-c+1}else break e;else{$e=Me=at[nt];for(je=1;Me>=10;Me/=10,je++);We%=c,it=We-c+je,Qe=it<0?0:i($e/jt[je-it-1]%10)}if(rt=rt||Ae<0||at[nt+1]!=null||(it<0?$e:$e%jt[je-it-1]),rt=De<4?(Qe||rt)&&(De==0||De==(Z.s<0?3:2)):Qe>5||Qe==5&&(De==4||rt||De==6&&(We>0?it>0?$e/jt[je-it]:0:at[nt-1])%10&1||De==(Z.s<0?8:7)),Ae<1||!at[0]){if(at.length=0,rt)Ae-=Z.e+1,at[0]=jt[(c-Ae%c)%c],Z.e=-Ae||0;else at[0]=Z.e=0;return Z}if(We==0)at.length=nt,Me=1,nt--;else at.length=nt+1,Me=jt[c-We],at[nt]=it>0?i($e/jt[je-it]%jt[it])*Me:0;if(rt)for(;;)if(nt==0){for(We=1,it=at[0];it>=10;it/=10,We++);it=at[0]+=Me;for(Me=1;it>=10;it/=10,Me++);if(We!=Me){if(Z.e++,at[0]==a)at[0]=1}break}else{if(at[nt]+=Me,at[nt]!=a)break;at[nt--]=0,Me=1}for(We=at.length;at[--We]===0;at.pop());}if(Z.e>Be)Z.c=Z.e=null;else if(Z.e<He)Z.c=[Z.e=0]}return Z}function Ci(Z){var Ae,De=Z.e;if(De===null)return Z.toString();return Ae=_(Z.c),Ae=De<=pe||De>=ae?Ne(Ae,De):k(Ae,De,"0"),Z.s<0?"-"+Ae:Ae}if(M.absoluteValue=M.abs=function(){var Z=new ot(this);if(Z.s<0)Z.s=1;return Z},M.comparedTo=function(Z,Ae){return R(this,new ot(Z,Ae))},M.decimalPlaces=M.dp=function(Z,Ae){var De,rt,je,We=this;if(Z!=null){if(O(Z,0,h),Ae==null)Ae=de;else O(Ae,0,8);return Kt(new ot(We),Z+We.e+1,Ae)}if(!(De=We.c))return null;if(rt=((je=De.length-1)-g(this.e/c))*c,je=De[je])for(;je%10==0;je/=10,rt--);if(rt<0)rt=0;return rt},M.dividedBy=M.div=function(Z,Ae){return re(this,new ot(Z,Ae),ce,de)},M.dividedToIntegerBy=M.idiv=function(Z,Ae){return re(this,new ot(Z,Ae),0,1)},M.exponentiatedBy=M.pow=function(Z,Ae){var De,rt,je,We,it,Me,$e,nt,Qe,at=this;if(Z=new ot(Z),Z.c&&!Z.isInteger())throw Error(o+"Exponent not an integer: "+Ci(Z));if(Ae!=null)Ae=new ot(Ae);if(Me=Z.e>14,!at.c||!at.c[0]||at.c[0]==1&&!at.e&&at.c.length==1||!Z.c||!Z.c[0])return Qe=new ot(Math.pow(+Ci(at),Me?Z.s*(2-I(Z)):+Ci(Z))),Ae?Qe.mod(Ae):Qe;if($e=Z.s<0,Ae){if(Ae.c?!Ae.c[0]:!Ae.s)return new ot(NaN);if(rt=!$e&&at.isInteger()&&Ae.isInteger(),rt)at=at.mod(Ae)}else if(Z.e>9&&(at.e>0||at.e<-1||(at.e==0?at.c[0]>1||Me&&at.c[1]>=240000000:at.c[0]<80000000000000||Me&&at.c[0]<=99999750000000))){if(We=at.s<0&&I(Z)?-0:0,at.e>-1)We=1/We;return new ot($e?1/We:We)}else if(Ve)We=n(Ve/c+2);if(Me){if(De=new ot(0.5),$e)Z.s=1;nt=I(Z)}else je=Math.abs(+Ci(Z)),nt=je%2;Qe=new ot(F);for(;;){if(nt){if(Qe=Qe.times(at),!Qe.c)break;if(We){if(Qe.c.length>We)Qe.c.length=We}else if(rt)Qe=Qe.mod(Ae)}if(je){if(je=i(je/2),je===0)break;nt=je%2}else if(Z=Z.times(De),Kt(Z,Z.e+1,1),Z.e>14)nt=I(Z);else{if(je=+Ci(Z),je===0)break;nt=je%2}if(at=at.times(at),We){if(at.c&&at.c.length>We)at.c.length=We}else if(rt)at=at.mod(Ae)}if(rt)return Qe;if($e)Qe=F.div(Qe);return Ae?Qe.mod(Ae):We?Kt(Qe,Ve,de,it):Qe},M.integerValue=function(Z){var Ae=new ot(this);if(Z==null)Z=de;else O(Z,0,8);return Kt(Ae,Ae.e+1,Z)},M.isEqualTo=M.eq=function(Z,Ae){return R(this,new ot(Z,Ae))===0},M.isFinite=function(){return!!this.c},M.isGreaterThan=M.gt=function(Z,Ae){return R(this,new ot(Z,Ae))>0},M.isGreaterThanOrEqualTo=M.gte=function(Z,Ae){return(Ae=R(this,new ot(Z,Ae)))===1||Ae===0},M.isInteger=function(){return!!this.c&&g(this.e/c)>this.c.length-2},M.isLessThan=M.lt=function(Z,Ae){return R(this,new ot(Z,Ae))<0},M.isLessThanOrEqualTo=M.lte=function(Z,Ae){return(Ae=R(this,new ot(Z,Ae)))===-1||Ae===0},M.isNaN=function(){return!this.s},M.isNegative=function(){return this.s<0},M.isPositive=function(){return this.s>0},M.isZero=function(){return!!this.c&&this.c[0]==0},M.minus=function(Z,Ae){var De,rt,je,We,it=this,Me=it.s;if(Z=new ot(Z,Ae),Ae=Z.s,!Me||!Ae)return new ot(NaN);if(Me!=Ae)return Z.s=-Ae,it.plus(Z);var $e=it.e/c,nt=Z.e/c,Qe=it.c,at=Z.c;if(!$e||!nt){if(!Qe||!at)return Qe?(Z.s=-Ae,Z):new ot(at?it:NaN);if(!Qe[0]||!at[0])return at[0]?(Z.s=-Ae,Z):new ot(Qe[0]?it:de==3?-0:0)}if($e=g($e),nt=g(nt),Qe=Qe.slice(),Me=$e-nt){if(We=Me<0)Me=-Me,je=Qe;else nt=$e,je=at;je.reverse();for(Ae=Me;Ae--;je.push(0));je.reverse()}else{rt=(We=(Me=Qe.length)<(Ae=at.length))?Me:Ae;for(Me=Ae=0;Ae<rt;Ae++)if(Qe[Ae]!=at[Ae]){We=Qe[Ae]<at[Ae];break}}if(We)je=Qe,Qe=at,at=je,Z.s=-Z.s;if(Ae=(rt=at.length)-(De=Qe.length),Ae>0)for(;Ae--;Qe[De++]=0);Ae=a-1;for(;rt>Me;){if(Qe[--rt]<at[rt]){for(De=rt;De&&!Qe[--De];Qe[De]=Ae);--Qe[De],Qe[rt]+=a}Qe[rt]-=at[rt]}for(;Qe[0]==0;Qe.splice(0,1),--nt);if(!Qe[0])return Z.s=de==3?-1:1,Z.c=[Z.e=0],Z;return oi(Z,Qe,nt)},M.modulo=M.mod=function(Z,Ae){var De,rt,je=this;if(Z=new ot(Z,Ae),!je.c||!Z.s||Z.c&&!Z.c[0])return new ot(NaN);else if(!Z.c||je.c&&!je.c[0])return new ot(je);if(Te==9)rt=Z.s,Z.s=1,De=re(je,Z,0,3),Z.s=rt,De.s*=rt;else De=re(je,Z,0,Te);if(Z=je.minus(De.times(Z)),!Z.c[0]&&Te==1)Z.s=je.s;return Z},M.multipliedBy=M.times=function(Z,Ae){var De,rt,je,We,it,Me,$e,nt,Qe,at,jt,Ft,Nn,mi,Oi,vn=this,Hn=vn.c,no=(Z=new ot(Z,Ae)).c;if(!Hn||!no||!Hn[0]||!no[0]){if(!vn.s||!Z.s||Hn&&!Hn[0]&&!no||no&&!no[0]&&!Hn)Z.c=Z.e=Z.s=null;else if(Z.s*=vn.s,!Hn||!no)Z.c=Z.e=null;else Z.c=[0],Z.e=0;return Z}if(rt=g(vn.e/c)+g(Z.e/c),Z.s*=vn.s,$e=Hn.length,at=no.length,$e<at)Nn=Hn,Hn=no,no=Nn,je=$e,$e=at,at=je;for(je=$e+at,Nn=[];je--;Nn.push(0));mi=a,Oi=f;for(je=at;--je>=0;){De=0,jt=no[je]%Oi,Ft=no[je]/Oi|0;for(it=$e,We=je+it;We>je;)nt=Hn[--it]%Oi,Qe=Hn[it]/Oi|0,Me=Ft*nt+Qe*jt,nt=jt*nt+Me%Oi*Oi+Nn[We]+De,De=(nt/mi|0)+(Me/Oi|0)+Ft*Qe,Nn[We--]=nt%mi;Nn[We]=De}if(De)++rt;else Nn.splice(0,1);return oi(Z,Nn,rt)},M.negated=function(){var Z=new ot(this);return Z.s=-Z.s||null,Z},M.plus=function(Z,Ae){var De,rt=this,je=rt.s;if(Z=new ot(Z,Ae),Ae=Z.s,!je||!Ae)return new ot(NaN);if(je!=Ae)return Z.s=-Ae,rt.minus(Z);var We=rt.e/c,it=Z.e/c,Me=rt.c,$e=Z.c;if(!We||!it){if(!Me||!$e)return new ot(je/0);if(!Me[0]||!$e[0])return $e[0]?Z:new ot(Me[0]?rt:je*0)}if(We=g(We),it=g(it),Me=Me.slice(),je=We-it){if(je>0)it=We,De=$e;else je=-je,De=Me;De.reverse();for(;je--;De.push(0));De.reverse()}if(je=Me.length,Ae=$e.length,je-Ae<0)De=$e,$e=Me,Me=De,Ae=je;for(je=0;Ae;)je=(Me[--Ae]=Me[Ae]+$e[Ae]+je)/a|0,Me[Ae]=a===Me[Ae]?0:Me[Ae]%a;if(je)Me=[je].concat(Me),++it;return oi(Z,Me,it)},M.precision=M.sd=function(Z,Ae){var De,rt,je,We=this;if(Z!=null&&Z!==!!Z){if(O(Z,1,h),Ae==null)Ae=de;else O(Ae,0,8);return Kt(new ot(We),Z,Ae)}if(!(De=We.c))return null;if(je=De.length-1,rt=je*c+1,je=De[je]){for(;je%10==0;je/=10,rt--);for(je=De[0];je>=10;je/=10,rt++);}if(Z&&We.e+1>rt)rt=We.e+1;return rt},M.shiftedBy=function(Z){return O(Z,-u,u),this.times("1e"+Z)},M.squareRoot=M.sqrt=function(){var Z,Ae,De,rt,je,We=this,{c:it,s:Me,e:$e}=We,nt=ce+4,Qe=new ot("0.5");if(Me!==1||!it||!it[0])return new ot(!Me||Me<0&&(!it||it[0])?NaN:it?We:1/0);if(Me=Math.sqrt(+Ci(We)),Me==0||Me==1/0){if(Ae=_(it),(Ae.length+$e)%2==0)Ae+="0";if(Me=Math.sqrt(+Ae),$e=g(($e+1)/2)-($e<0||$e%2),Me==1/0)Ae="5e"+$e;else Ae=Me.toExponential(),Ae=Ae.slice(0,Ae.indexOf("e")+1)+$e;De=new ot(Ae)}else De=new ot(Me+"");if(De.c[0]){if($e=De.e,Me=$e+nt,Me<3)Me=0;for(;;)if(je=De,De=Qe.times(je.plus(re(We,je,nt,1))),_(je.c).slice(0,Me)===(Ae=_(De.c)).slice(0,Me)){if(De.e<$e)--Me;if(Ae=Ae.slice(Me-3,Me+1),Ae=="9999"||!rt&&Ae=="4999"){if(!rt){if(Kt(je,je.e+ce+2,0),je.times(je).eq(We)){De=je;break}}nt+=4,Me+=4,rt=1}else{if(!+Ae||!+Ae.slice(1)&&Ae.charAt(0)=="5")Kt(De,De.e+ce+2,1),Z=!De.times(De).eq(We);break}}}return Kt(De,De.e+ce+1,de,Z)},M.toExponential=function(Z,Ae){if(Z!=null)O(Z,0,h),Z++;return Tr(this,Z,Ae,1)},M.toFixed=function(Z,Ae){if(Z!=null)O(Z,0,h),Z=Z+this.e+1;return Tr(this,Z,Ae)},M.toFormat=function(Z,Ae,De){var rt,je=this;if(De==null)if(Z!=null&&Ae&&typeof Ae=="object")De=Ae,Ae=null;else if(Z&&typeof Z=="object")De=Z,Z=Ae=null;else De=Je;else if(typeof De!="object")throw Error(o+"Argument not an object: "+De);if(rt=je.toFixed(Z,Ae),je.c){var We,it=rt.split("."),Me=+De.groupSize,$e=+De.secondaryGroupSize,nt=De.groupSeparator||"",Qe=it[0],at=it[1],jt=je.s<0,Ft=jt?Qe.slice(1):Qe,Nn=Ft.length;if($e)We=Me,Me=$e,$e=We,Nn-=We;if(Me>0&&Nn>0){We=Nn%Me||Me,Qe=Ft.substr(0,We);for(;We<Nn;We+=Me)Qe+=nt+Ft.substr(We,Me);if($e>0)Qe+=nt+Ft.slice(We);if(jt)Qe="-"+Qe}rt=at?Qe+(De.decimalSeparator||"")+(($e=+De.fractionGroupSize)?at.replace(new RegExp("\\d{"+$e+"}\\B","g"),"$&"+(De.fractionGroupSeparator||"")):at):Qe}return(De.prefix||"")+rt+(De.suffix||"")},M.toFraction=function(Z){var Ae,De,rt,je,We,it,Me,$e,nt,Qe,at,jt,Ft=this,Nn=Ft.c;if(Z!=null){if(Me=new ot(Z),!Me.isInteger()&&(Me.c||Me.s!==1)||Me.lt(F))throw Error(o+"Argument "+(Me.isInteger()?"out of range: ":"not an integer: ")+Ci(Me))}if(!Nn)return new ot(Ft);Ae=new ot(F),nt=De=new ot(F),rt=$e=new ot(F),jt=_(Nn),We=Ae.e=jt.length-Ft.e-1,Ae.c[0]=d[(it=We%c)<0?c+it:it],Z=!Z||Me.comparedTo(Ae)>0?We>0?Ae:nt:Me,it=Be,Be=1/0,Me=new ot(jt),$e.c[0]=0;for(;;){if(Qe=re(Me,Ae,0,1),je=De.plus(Qe.times(rt)),je.comparedTo(Z)==1)break;De=rt,rt=je,nt=$e.plus(Qe.times(je=nt)),$e=je,Ae=Me.minus(Qe.times(je=Ae)),Me=je}return je=re(Z.minus(De),rt,0,1),$e=$e.plus(je.times(nt)),De=De.plus(je.times(rt)),$e.s=nt.s=Ft.s,We=We*2,at=re(nt,rt,We,de).minus(Ft).abs().comparedTo(re($e,De,We,de).minus(Ft).abs())<1?[nt,rt]:[$e,De],Be=it,at},M.toNumber=function(){return+Ci(this)},M.toPrecision=function(Z,Ae){if(Z!=null)O(Z,1,h);return Tr(this,Z,Ae,2)},M.toString=function(Z){var Ae,De=this,rt=De.s,je=De.e;if(je===null)if(rt){if(Ae="Infinity",rt<0)Ae="-"+Ae}else Ae="NaN";else{if(Z==null)Ae=je<=pe||je>=ae?Ne(_(De.c),je):k(_(De.c),je,"0");else if(Z===10&&qt)De=Kt(new ot(De),ce+je+1,de),Ae=k(_(De.c),De.e,"0");else O(Z,2,ft.length,"Base"),Ae=Oe(k(_(De.c),je,"0"),10,Z,rt,!0);if(rt<0&&De.c[0])Ae="-"+Ae}return Ae},M.valueOf=M.toJSON=function(){return Ci(this)},M._isBigNumber=!0,j!=null)ot.set(j);return ot}function g(j){var re=j|0;return j>0||j===re?re:re-1}function _(j){var re,Oe,ne=1,M=j.length,F=j[0]+"";for(;ne<M;){re=j[ne++]+"",Oe=c-re.length;for(;Oe--;re="0"+re);F+=re}for(M=F.length;F.charCodeAt(--M)===48;);return F.slice(0,M+1||1)}function R(j,re){var Oe,ne,M=j.c,F=re.c,ce=j.s,de=re.s,pe=j.e,ae=re.e;if(!ce||!de)return null;if(Oe=M&&!M[0],ne=F&&!F[0],Oe||ne)return Oe?ne?0:-de:ce;if(ce!=de)return ce;if(Oe=ce<0,ne=pe==ae,!M||!F)return ne?0:!M^Oe?1:-1;if(!ne)return pe>ae^Oe?1:-1;de=(pe=M.length)<(ae=F.length)?pe:ae;for(ce=0;ce<de;ce++)if(M[ce]!=F[ce])return M[ce]>F[ce]^Oe?1:-1;return pe==ae?0:pe>ae^Oe?1:-1}function O(j,re,Oe,ne){if(j<re||j>Oe||j!==i(j))throw Error(o+(ne||"Argument")+(typeof j=="number"?j<re||j>Oe?" out of range: ":" not an integer: ":" not a primitive number: ")+String(j))}function I(j){var re=j.c.length-1;return g(j.e/c)==re&&j.c[re]%2!=0}function Ne(j,re){return(j.length>1?j.charAt(0)+"."+j.slice(1):j)+(re<0?"e":"e+")+re}function k(j,re,Oe){var ne,M;if(re<0){for(M=Oe+".";++re;M+=Oe);j=M+j}else if(ne=j.length,++re>ne){for(M=Oe,re-=ne;--re;M+=Oe);j+=M}else if(re<ne)j=j.slice(0,re)+"."+j.slice(re);return j}if(t=p(),t.default=t.BigNumber=t,typeof define=="function"&&define.amd)define(function(){return t});else if(typeof Gw<"u"&&Gw.exports)Gw.exports=t;else{if(!e)e=typeof self<"u"&&self?self:window;e.BigNumber=t}})(jj)});var Wj=A(function(V8e,zj){var $j=n0(),Fj=V8e;(function(){function e(u){return u<10?"0"+u:u}var t=/[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,r=/[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,n,i,o={"\b":"\\b","\t":"\\t","\n":"\\n","\f":"\\f","\r":"\\r",'"':"\\\"","\\":"\\\\"},s;function a(u){return r.lastIndex=0,r.test(u)?'"'+u.replace(r,function(d){var f=o[d];return typeof f==="string"?f:"\\u"+("0000"+d.charCodeAt(0).toString(16)).slice(-4)})+'"':'"'+u+'"'}function c(u,d){var f,h,p,g,_=n,R,O=d[u],I=O!=null&&(O instanceof $j||$j.isBigNumber(O));if(O&&typeof O==="object"&&typeof O.toJSON==="function")O=O.toJSON(u);if(typeof s==="function")O=s.call(d,u,O);switch(typeof O){case"string":if(I)return O;else return a(O);case"number":return isFinite(O)?String(O):"null";case"boolean":case"null":case"bigint":return String(O);case"object":if(!O)return"null";if(n+=i,R=[],Object.prototype.toString.apply(O)==="[object Array]"){g=O.length;for(f=0;f<g;f+=1)R[f]=c(f,O)||"null";return p=R.length===0?"[]":n?`[
50
+ `+n+R.join(`,
51
+ `+n)+`
52
+ `+_+"]":"["+R.join(",")+"]",n=_,p}if(s&&typeof s==="object"){g=s.length;for(f=0;f<g;f+=1)if(typeof s[f]==="string"){if(h=s[f],p=c(h,O),p)R.push(a(h)+(n?": ":":")+p)}}else Object.keys(O).forEach(function(Ne){var k=c(Ne,O);if(k)R.push(a(Ne)+(n?": ":":")+k)});return p=R.length===0?"{}":n?`{
53
+ `+n+R.join(`,
54
+ `+n)+`
55
+ `+_+"}":"{"+R.join(",")+"}",n=_,p}}if(typeof Fj.stringify!=="function")Fj.stringify=function(u,d,f){var h;if(n="",i="",typeof f==="number")for(h=0;h<f;h+=1)i+=" ";else if(typeof f==="string")i=f;if(s=d,d&&typeof d!=="function"&&(typeof d!=="object"||typeof d.length!=="number"))throw Error("JSON.stringify");return c("",{"":u})}})()});var Vj=A(function(G8e,Hj){var Kw=null,Ehe=/(?:_|\\u005[Ff])(?:_|\\u005[Ff])(?:p|\\u0070)(?:r|\\u0072)(?:o|\\u006[Ff])(?:t|\\u0074)(?:o|\\u006[Ff])(?:_|\\u005[Ff])(?:_|\\u005[Ff])/,She=/(?:c|\\u0063)(?:o|\\u006[Ff])(?:n|\\u006[Ee])(?:s|\\u0073)(?:t|\\u0074)(?:r|\\u0072)(?:u|\\u0075)(?:c|\\u0063)(?:t|\\u0074)(?:o|\\u006[Ff])(?:r|\\u0072)/,Ahe=function(e){var t={strict:!1,storeAsString:!1,alwaysParseAsBig:!1,useNativeBigInt:!1,protoAction:"error",constructorAction:"error"};if(e!==void 0&&e!==null){if(e.strict===!0)t.strict=!0;if(e.storeAsString===!0)t.storeAsString=!0;if(t.alwaysParseAsBig=e.alwaysParseAsBig===!0?e.alwaysParseAsBig:!1,t.useNativeBigInt=e.useNativeBigInt===!0?e.useNativeBigInt:!1,typeof e.constructorAction<"u")if(e.constructorAction==="error"||e.constructorAction==="ignore"||e.constructorAction==="preserve")t.constructorAction=e.constructorAction;else throw Error(`Incorrect value for constructorAction option, must be "error", "ignore" or undefined but passed ${e.constructorAction}`);if(typeof e.protoAction<"u")if(e.protoAction==="error"||e.protoAction==="ignore"||e.protoAction==="preserve")t.protoAction=e.protoAction;else throw Error(`Incorrect value for protoAction option, must be "error", "ignore" or undefined but passed ${e.protoAction}`)}var r,n,i={'"':'"',"\\":"\\","/":"/",b:"\b",f:"\f",n:`
56
+ `,r:"\r",t:"\t"},o,s=function(_){throw{name:"SyntaxError",message:_,at:r,text:o}},a=function(_){if(_&&_!==n)s("Expected '"+_+"' instead of '"+n+"'");return n=o.charAt(r),r+=1,n},c=function(){var _,R="";if(n==="-")R="-",a("-");while(n>="0"&&n<="9")R+=n,a();if(n==="."){R+=".";while(a()&&n>="0"&&n<="9")R+=n}if(n==="e"||n==="E"){if(R+=n,a(),n==="-"||n==="+")R+=n,a();while(n>="0"&&n<="9")R+=n,a()}if(_=+R,!isFinite(_))s("Bad number");else{if(Kw==null)Kw=n0();if(R.length>15)return t.storeAsString?R:t.useNativeBigInt?BigInt(R):new Kw(R);else return!t.alwaysParseAsBig?_:t.useNativeBigInt?BigInt(_):new Kw(_)}},u=function(){var _,R,O="",I;if(n==='"'){var Ne=r;while(a()){if(n==='"'){if(r-1>Ne)O+=o.substring(Ne,r-1);return a(),O}if(n==="\\"){if(r-1>Ne)O+=o.substring(Ne,r-1);if(a(),n==="u"){I=0;for(R=0;R<4;R+=1){if(_=parseInt(a(),16),!isFinite(_))break;I=I*16+_}O+=String.fromCharCode(I)}else if(typeof i[n]==="string")O+=i[n];else break;Ne=r}}}s("Bad string")},d=function(){while(n&&n<=" ")a()},f=function(){switch(n){case"t":return a("t"),a("r"),a("u"),a("e"),!0;case"f":return a("f"),a("a"),a("l"),a("s"),a("e"),!1;case"n":return a("n"),a("u"),a("l"),a("l"),null}s("Unexpected '"+n+"'")},h,p=function(){var _=[];if(n==="["){if(a("["),d(),n==="]")return a("]"),_;while(n){if(_.push(h()),d(),n==="]")return a("]"),_;a(","),d()}}s("Bad array")},g=function(){var _,R=Object.create(null);if(n==="{"){if(a("{"),d(),n==="}")return a("}"),R;while(n){if(_=u(),d(),a(":"),t.strict===!0&&Object.hasOwnProperty.call(R,_))s('Duplicate key "'+_+'"');if(Ehe.test(_)===!0)if(t.protoAction==="error")s("Object contains forbidden prototype property");else if(t.protoAction==="ignore")h();else R[_]=h();else if(She.test(_)===!0)if(t.constructorAction==="error")s("Object contains forbidden constructor property");else if(t.constructorAction==="ignore")h();else R[_]=h();else R[_]=h();if(d(),n==="}")return a("}"),R;a(","),d()}}s("Bad object")};return h=function(){switch(d(),n){case"{":return g();case"[":return p();case'"':return u();case"-":return c();default:return n>="0"&&n<="9"?c():f()}},function(_,R){var O;if(o=_+"",r=0,n=" ",O=h(),d(),n)s("Syntax error");return typeof R==="function"?function I(Ne,k){var j,re,Oe=Ne[k];if(Oe&&typeof Oe==="object")Object.keys(Oe).forEach(function(ne){if(re=I(Oe,ne),re!==void 0)Oe[ne]=re;else delete Oe[ne]});return R.call(Ne,k,Oe)}({"":O},""):O}};Hj.exports=Ahe});var Jj=A(function(K8e,Jw){var Gj=Wj().stringify,Kj=Vj();Jw.exports=function(e){return{parse:Kj(e),stringify:Gj}};Jw.exports.parse=Kj();Jw.exports.stringify=Gj});var i0=A(function(e$){Object.defineProperty(e$,"__esModule",{value:!0});e$.GCE_LINUX_BIOS_PATHS=void 0;e$.isGoogleCloudServerless=Qj;e$.isGoogleComputeEngineLinux=Yj;e$.isGoogleComputeEngineMACAddress=Xj;e$.isGoogleComputeEngine=Zj;e$.detectGCPResidency=vhe;var Qw=C("fs"),Xw=C("os");e$.GCE_LINUX_BIOS_PATHS={BIOS_DATE:"/sys/class/dmi/id/bios_date",BIOS_VENDOR:"/sys/class/dmi/id/bios_vendor"};var The=/^42:01/;function Qj(){return!!(process.env.CLOUD_RUN_JOB||process.env.FUNCTION_NAME||process.env.K_SERVICE)}function Yj(){if(Xw.platform()!=="linux")return!1;try{Qw.statSync(e$.GCE_LINUX_BIOS_PATHS.BIOS_DATE);let e=Qw.readFileSync(e$.GCE_LINUX_BIOS_PATHS.BIOS_VENDOR,"utf8");return/Google/.test(e)}catch{return!1}}function Xj(){let e=Xw.networkInterfaces();for(let t of Object.values(e)){if(!t)continue;for(let{mac:r}of t)if(The.test(r))return!0}return!1}function Zj(){return Yj()||Xj()}function vhe(){return Qj()||Zj()}});var n$=A(function(t$){Object.defineProperty(t$,"__esModule",{value:!0});t$.Colours=void 0;class Zn{static enabled=!1;static reset="";static bright="";static dim="";static red="";static green="";static yellow="";static blue="";static magenta="";static cyan="";static white="";static grey="";static isEnabled(e){return e&&e.isTTY&&(typeof e.getColorDepth==="function"?e.getColorDepth()>2:!0)}static refresh(){if(Zn.enabled=Zn.isEnabled(process?.stderr),!this.enabled)Zn.reset="",Zn.bright="",Zn.dim="",Zn.red="",Zn.green="",Zn.yellow="",Zn.blue="",Zn.magenta="",Zn.cyan="",Zn.white="",Zn.grey="";else Zn.reset="\x1B[0m",Zn.bright="\x1B[1m",Zn.dim="\x1B[2m",Zn.red="\x1B[31m",Zn.green="\x1B[32m",Zn.yellow="\x1B[33m",Zn.blue="\x1B[34m",Zn.magenta="\x1B[35m",Zn.cyan="\x1B[36m",Zn.white="\x1B[37m",Zn.grey="\x1B[90m"}}t$.Colours=Zn;Zn.refresh()});var a$=A(function(o$){Object.defineProperty(o$,"__esModule",{value:!0});o$.LogSeverity=void 0;var i$;(function(e){e.DEFAULT="DEFAULT",e.DEBUG="DEBUG",e.INFO="INFO",e.WARNING="WARNING",e.ERROR="ERROR"})(i$||(o$.LogSeverity=i$={}))});var m$=A(function(ni){var Ohe=ni&&ni.__createBinding||(Object.create?function(e,t,r,n){if(n===void 0)n=r;var i=Object.getOwnPropertyDescriptor(t,r);if(!i||("get"in i?!t.__esModule:i.writable||i.configurable))i={enumerable:!0,get:function(){return t[r]}};Object.defineProperty(e,n,i)}:function(e,t,r,n){if(n===void 0)n=r;e[n]=t[r]}),Ihe=ni&&ni.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),c$=ni&&ni.__importStar||function(){var e=function(t){return e=Object.getOwnPropertyNames||function(r){var n=[];for(var i in r)if(Object.prototype.hasOwnProperty.call(r,i))n[n.length]=i;return n},e(t)};return function(t){if(t&&t.__esModule)return t;var r={};if(t!=null){for(var n=e(t),i=0;i<n.length;i++)if(n[i]!=="default")Ohe(r,t,n[i])}return Ihe(r,t),r}}();Object.defineProperty(ni,"__esModule",{value:!0});ni.env=ni.DebugLogBackendBase=ni.placeholder=ni.AdhocDebugLogger=void 0;ni.getNodeBackend=o0;ni.getDebugBackend=Dhe;ni.getStructuredBackend=Uhe;ni.setBackend=Phe;ni.log=p$;var u$=C("events"),qp=c$(C("process")),d$=c$(C("util")),ri=n$(),Hi=a$();class Zw extends u$.EventEmitter{namespace;upstream;func;constructor(e,t){super();this.namespace=e,this.upstream=t,this.func=Object.assign(this.invoke.bind(this),{instance:this,on:(r,n)=>this.on(r,n)}),this.func.debug=(...r)=>this.invokeSeverity(Hi.LogSeverity.DEBUG,...r),this.func.info=(...r)=>this.invokeSeverity(Hi.LogSeverity.INFO,...r),this.func.warn=(...r)=>this.invokeSeverity(Hi.LogSeverity.WARNING,...r),this.func.error=(...r)=>this.invokeSeverity(Hi.LogSeverity.ERROR,...r),this.func.sublog=(r)=>p$(r,this.func)}invoke(e,...t){if(this.upstream)try{this.upstream(e,...t)}catch(r){}try{this.emit("log",e,t)}catch(r){}}invokeSeverity(e,...t){this.invoke({severity:e},...t)}}ni.AdhocDebugLogger=Zw;ni.placeholder=new Zw("",()=>{}).func;class Bp{cached=new Map;filters=[];filtersSet=!1;constructor(){let e=qp.env[ni.env.nodeEnables]??"*";if(e==="all")e="*";this.filters=e.split(",")}log(e,t,...r){try{if(!this.filtersSet)this.setFilters(),this.filtersSet=!0;let n=this.cached.get(e);if(!n)n=this.makeLogger(e),this.cached.set(e,n);n(t,...r)}catch(n){console.error(n)}}}ni.DebugLogBackendBase=Bp;class l$ extends Bp{enabledRegexp=/.*/g;isEnabled(e){return this.enabledRegexp.test(e)}makeLogger(e){if(!this.enabledRegexp.test(e))return()=>{};return(t,...r)=>{let n=`${ri.Colours.green}${e}${ri.Colours.reset}`,i=`${ri.Colours.yellow}${qp.pid}${ri.Colours.reset}`,o;switch(t.severity){case Hi.LogSeverity.ERROR:o=`${ri.Colours.red}${t.severity}${ri.Colours.reset}`;break;case Hi.LogSeverity.INFO:o=`${ri.Colours.magenta}${t.severity}${ri.Colours.reset}`;break;case Hi.LogSeverity.WARNING:o=`${ri.Colours.yellow}${t.severity}${ri.Colours.reset}`;break;default:o=t.severity??Hi.LogSeverity.DEFAULT;break}let s=d$.formatWithOptions({colors:ri.Colours.enabled},...r),a=Object.assign({},t);delete a.severity;let c=Object.getOwnPropertyNames(a).length?JSON.stringify(a):"",u=c?`${ri.Colours.grey}${c}${ri.Colours.reset}`:"";console.error("%s [%s|%s] %s%s",i,n,o,s,c?` ${u}`:"")}}setFilters(){let t=this.filters.join(",").replace(/[|\\{}()[\]^$+?.]/g,"\\$&").replace(/\*/g,".*").replace(/,/g,"$|^");this.enabledRegexp=new RegExp(`^${t}$`,"i")}}function o0(){return new l$}class f$ extends Bp{debugPkg;constructor(e){super();this.debugPkg=e}makeLogger(e){let t=this.debugPkg(e);return(r,...n)=>{t(n[0],...n.slice(1))}}setFilters(){let e=qp.env.NODE_DEBUG??"";qp.env.NODE_DEBUG=`${e}${e?",":""}${this.filters.join(",")}`}}function Dhe(e){return new f$(e)}class h$ extends Bp{upstream;constructor(e){super();this.upstream=e??void 0}makeLogger(e){let t=this.upstream?.makeLogger(e);return(r,...n)=>{let i=r.severity??Hi.LogSeverity.INFO,o=Object.assign({severity:i,message:d$.format(...n)},r),s=JSON.stringify(o);if(t)t(r,s);else console.log("%s",s)}}setFilters(){this.upstream?.setFilters()}}function Uhe(e){return new h$(e)}ni.env={nodeEnables:"GOOGLE_SDK_NODE_LOGGING"};var s0=new Map,Js=void 0;function Phe(e){Js=e,s0.clear()}function p$(e,t){if(!Js){if(!qp.env[ni.env.nodeEnables])return ni.placeholder}if(!e)return ni.placeholder;if(t)e=`${t.instance.namespace}:${e}`;let r=s0.get(e);if(r)return r.func;if(Js===null)return ni.placeholder;else if(Js===void 0)Js=o0();let n=(()=>{let i=void 0;return new Zw(e,(s,...a)=>{if(i!==Js){if(Js===null)return;else if(Js===void 0)Js=o0();i=Js}Js?.log(e,s,...a)})})();return s0.set(e,n),n.func}});var g$=A(function(_d){var Lhe=_d&&_d.__createBinding||(Object.create?function(e,t,r,n){if(n===void 0)n=r;var i=Object.getOwnPropertyDescriptor(t,r);if(!i||("get"in i?!t.__esModule:i.writable||i.configurable))i={enumerable:!0,get:function(){return t[r]}};Object.defineProperty(e,n,i)}:function(e,t,r,n){if(n===void 0)n=r;e[n]=t[r]}),Mhe=_d&&_d.__exportStar||function(e,t){for(var r in e)if(r!=="default"&&!Object.prototype.hasOwnProperty.call(t,r))Lhe(t,e,r)};Object.defineProperty(_d,"__esModule",{value:!0});Mhe(m$(),_d)});var $p=A(function(Wt){var w$=Wt&&Wt.__createBinding||(Object.create?function(e,t,r,n){if(n===void 0)n=r;var i=Object.getOwnPropertyDescriptor(t,r);if(!i||("get"in i?!t.__esModule:i.writable||i.configurable))i={enumerable:!0,get:function(){return t[r]}};Object.defineProperty(e,n,i)}:function(e,t,r,n){if(n===void 0)n=r;e[n]=t[r]}),qhe=Wt&&Wt.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),Bhe=Wt&&Wt.__importStar||function(){var e=function(t){return e=Object.getOwnPropertyNames||function(r){var n=[];for(var i in r)if(Object.prototype.hasOwnProperty.call(r,i))n[n.length]=i;return n},e(t)};return function(t){if(t&&t.__esModule)return t;var r={};if(t!=null){for(var n=e(t),i=0;i<n.length;i++)if(n[i]!=="default")w$(r,t,n[i])}return qhe(r,t),r}}(),jhe=Wt&&Wt.__exportStar||function(e,t){for(var r in e)if(r!=="default"&&!Object.prototype.hasOwnProperty.call(t,r))w$(t,e,r)};Object.defineProperty(Wt,"__esModule",{value:!0});Wt.gcpResidencyCache=Wt.METADATA_SERVER_DETECTION=Wt.HEADERS=Wt.HEADER_VALUE=Wt.HEADER_NAME=Wt.SECONDARY_HOST_ADDRESS=Wt.HOST_ADDRESS=Wt.BASE_PATH=void 0;Wt.instance=Whe;Wt.project=Hhe;Wt.universe=Vhe;Wt.bulk=Ghe;Wt.isAvailable=Jhe;Wt.resetIsAvailableCache=Qhe;Wt.getGCPResidency=c0;Wt.setGCPResidency=E$;Wt.requestTimeout=S$;var ef=to(),_$=Jj(),b$=i0(),$he=Bhe(g$());Wt.BASE_PATH="/computeMetadata/v1";Wt.HOST_ADDRESS="http://169.254.169.254";Wt.SECONDARY_HOST_ADDRESS="http://metadata.google.internal.";Wt.HEADER_NAME="Metadata-Flavor";Wt.HEADER_VALUE="Google";Wt.HEADERS=Object.freeze({[Wt.HEADER_NAME]:Wt.HEADER_VALUE});var y$=$he.log("gcp-metadata");Wt.METADATA_SERVER_DETECTION=Object.freeze({"assume-present":"don't try to ping the metadata server, but assume it's present",none:"don't try to ping the metadata server, but don't try to use it either","bios-only":"treat the result of a BIOS probe as canonical (don't fall back to pinging)","ping-only":"skip the BIOS probe, and go straight to pinging"});function a0(e){if(!e)e=process.env.GCE_METADATA_IP||process.env.GCE_METADATA_HOST||Wt.HOST_ADDRESS;if(!/^https?:\/\//.test(e))e=`http://${e}`;return new URL(Wt.BASE_PATH,e).href}function Fhe(e){Object.keys(e).forEach((t)=>{switch(t){case"params":case"property":case"headers":break;case"qs":throw Error("'qs' is not a valid configuration option. Please use 'params' instead.");default:throw Error(`'${t}' is not a valid configuration option.`)}})}async function jp(e,t={},r=3,n=!1){let i=new Headers(Wt.HEADERS),o="",s={};if(typeof e==="object"){let f=e;new Headers(f.headers).forEach((h,p)=>i.set(p,h)),o=f.metadataKey,s=f.params||s,r=f.noResponseRetries||r,n=f.fastFail||n}else o=e;if(typeof t==="string")o+=`/${t}`;else{if(Fhe(t),t.property)o+=`/${t.property}`;new Headers(t.headers).forEach((f,h)=>i.set(h,f)),s=t.params||s}let a=n?zhe:ef.request,c={url:`${a0()}/${o}`,headers:i,retryConfig:{noResponseRetries:r},params:s,responseType:"text",timeout:S$()};y$.info("instance request %j",c);let u=await a(c);y$.info("instance metadata is %s",u.data);let d=u.headers.get(Wt.HEADER_NAME);if(d!==Wt.HEADER_VALUE)throw RangeError(`Invalid response from metadata service: incorrect ${Wt.HEADER_NAME} header. Expected '${Wt.HEADER_VALUE}', got ${d?`'${d}'`:"no header"}`);if(typeof u.data==="string")try{return _$.parse(u.data)}catch{}return u.data}async function zhe(e){let t={...e,url:e.url?.toString().replace(a0(),a0(Wt.SECONDARY_HOST_ADDRESS))},r=ef.request(e),n=ef.request(t);return Promise.any([r,n])}function Whe(e){return jp("instance",e)}function Hhe(e){return jp("project",e)}function Vhe(e){return jp("universe",e)}async function Ghe(e){let t={};return await Promise.all(e.map((r)=>(async()=>{let n=await jp(r),i=r.metadataKey;t[i]=n})())),t}function Khe(){return process.env.DETECT_GCP_RETRIES?Number(process.env.DETECT_GCP_RETRIES):0}var e_;async function Jhe(){if(process.env.METADATA_SERVER_DETECTION){let e=process.env.METADATA_SERVER_DETECTION.trim().toLocaleLowerCase();if(!(e in Wt.METADATA_SERVER_DETECTION))throw RangeError(`Unknown \`METADATA_SERVER_DETECTION\` env variable. Got \`${e}\`, but it should be \`${Object.keys(Wt.METADATA_SERVER_DETECTION).join("`, `")}\`, or unset`);switch(e){case"assume-present":return!0;case"none":return!1;case"bios-only":return c0();case"ping-only":}}try{if(e_===void 0)e_=jp("instance",void 0,Khe(),!(process.env.GCE_METADATA_IP||process.env.GCE_METADATA_HOST));return await e_,!0}catch(e){let t=e;if(process.env.DEBUG_AUTH)console.info(t);if(t.type==="request-timeout")return!1;if(t.response&&t.response.status===404)return!1;else{if(!(t.response&&t.response.status===404)&&(!t.code||!["EHOSTDOWN","EHOSTUNREACH","ENETUNREACH","ENOENT","ENOTFOUND","ECONNREFUSED"].includes(t.code.toString()))){let r="UNKNOWN";if(t.code)r=t.code.toString();process.emitWarning(`received unexpected error = ${t.message} code = ${r}`,"MetadataLookupWarning")}return!1}}}function Qhe(){e_=void 0}Wt.gcpResidencyCache=null;function c0(){if(Wt.gcpResidencyCache===null)E$();return Wt.gcpResidencyCache}function E$(e=null){Wt.gcpResidencyCache=e!==null?e:b$.detectGCPResidency()}function S$(){return c0()?0:3000}jhe(i0(),Wt)});var T$=A(function(ipe){ipe.byteLength=Xhe;ipe.toByteArray=epe;ipe.fromByteArray=npe;var Ia=[],ms=[],Yhe=typeof Uint8Array<"u"?Uint8Array:Array,u0="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";for(gu=0,d0=u0.length;gu<d0;++gu)Ia[gu]=u0[gu],ms[u0.charCodeAt(gu)]=gu;var gu,d0;ms[45]=62;ms[95]=63;function A$(e){var t=e.length;if(t%4>0)throw Error("Invalid string. Length must be a multiple of 4");var r=e.indexOf("=");if(r===-1)r=t;var n=r===t?0:4-r%4;return[r,n]}function Xhe(e){var t=A$(e),r=t[0],n=t[1];return(r+n)*3/4-n}function Zhe(e,t,r){return(t+r)*3/4-r}function epe(e){var t,r=A$(e),n=r[0],i=r[1],o=new Yhe(Zhe(e,n,i)),s=0,a=i>0?n-4:n,c;for(c=0;c<a;c+=4)t=ms[e.charCodeAt(c)]<<18|ms[e.charCodeAt(c+1)]<<12|ms[e.charCodeAt(c+2)]<<6|ms[e.charCodeAt(c+3)],o[s++]=t>>16&255,o[s++]=t>>8&255,o[s++]=t&255;if(i===2)t=ms[e.charCodeAt(c)]<<2|ms[e.charCodeAt(c+1)]>>4,o[s++]=t&255;if(i===1)t=ms[e.charCodeAt(c)]<<10|ms[e.charCodeAt(c+1)]<<4|ms[e.charCodeAt(c+2)]>>2,o[s++]=t>>8&255,o[s++]=t&255;return o}function tpe(e){return Ia[e>>18&63]+Ia[e>>12&63]+Ia[e>>6&63]+Ia[e&63]}function rpe(e,t,r){var n,i=[];for(var o=t;o<r;o+=3)n=(e[o]<<16&16711680)+(e[o+1]<<8&65280)+(e[o+2]&255),i.push(tpe(n));return i.join("")}function npe(e){var t,r=e.length,n=r%3,i=[],o=16383;for(var s=0,a=r-n;s<a;s+=o)i.push(rpe(e,s,s+o>a?a:s+o));if(n===1)t=e[r-1],i.push(Ia[t>>2]+Ia[t<<4&63]+"==");else if(n===2)t=(e[r-2]<<8)+e[r-1],i.push(Ia[t>>10]+Ia[t>>4&63]+Ia[t<<2&63]+"=");return i.join("")}});var l0=A(function(v$){Object.defineProperty(v$,"__esModule",{value:!0});v$.fromArrayBufferToHex=cpe;function cpe(e){return Array.from(new Uint8Array(e)).map((r)=>r.toString(16).padStart(2,"0")).join("")}});var x$=A(function(R$){Object.defineProperty(R$,"__esModule",{value:!0});R$.BrowserCrypto=void 0;var gs=T$(),k$=l0();class t_{constructor(){if(typeof window>"u"||window.crypto===void 0||window.crypto.subtle===void 0)throw Error("SubtleCrypto not found. Make sure it's an https:// website.")}async sha256DigestBase64(e){let t=new TextEncoder().encode(e),r=await window.crypto.subtle.digest("SHA-256",t);return gs.fromByteArray(new Uint8Array(r))}randomBytesBase64(e){let t=new Uint8Array(e);return window.crypto.getRandomValues(t),gs.fromByteArray(t)}static padBase64(e){while(e.length%4!==0)e+="=";return e}async verify(e,t,r){let n={name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},i=new TextEncoder().encode(t),o=gs.toByteArray(t_.padBase64(r)),s=await window.crypto.subtle.importKey("jwk",e,n,!0,["verify"]);return await window.crypto.subtle.verify(n,s,Buffer.from(o),i)}async sign(e,t){let r={name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},n=new TextEncoder().encode(t),i=await window.crypto.subtle.importKey("jwk",e,r,!0,["sign"]),o=await window.crypto.subtle.sign(r,i,n);return gs.fromByteArray(new Uint8Array(o))}decodeBase64StringUtf8(e){let t=gs.toByteArray(t_.padBase64(e));return new TextDecoder().decode(t)}encodeBase64StringUtf8(e){let t=new TextEncoder().encode(e);return gs.fromByteArray(t)}async sha256DigestHex(e){let t=new TextEncoder().encode(e),r=await window.crypto.subtle.digest("SHA-256",t);return k$.fromArrayBufferToHex(r)}async signWithHmacSha256(e,t){let r=typeof e==="string"?e:String.fromCharCode(...new Uint16Array(e)),n=new TextEncoder,i=await window.crypto.subtle.importKey("raw",n.encode(r),{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]);return window.crypto.subtle.sign("HMAC",i,n.encode(t))}}R$.BrowserCrypto=t_});var D$=A(function(O$){Object.defineProperty(O$,"__esModule",{value:!0});O$.NodeCrypto=void 0;var ys=C("crypto");class C${async sha256DigestBase64(e){return ys.createHash("sha256").update(e).digest("base64")}randomBytesBase64(e){return ys.randomBytes(e).toString("base64")}async verify(e,t,r){let n=ys.createVerify("RSA-SHA256");return n.update(t),n.end(),n.verify(e,r,"base64")}async sign(e,t){let r=ys.createSign("RSA-SHA256");return r.update(t),r.end(),r.sign(e,"base64")}decodeBase64StringUtf8(e){return Buffer.from(e,"base64").toString("utf-8")}encodeBase64StringUtf8(e){return Buffer.from(e,"utf-8").toString("base64")}async sha256DigestHex(e){return ys.createHash("sha256").update(e).digest("hex")}async signWithHmacSha256(e,t){let r=typeof e==="string"?e:lpe(e);return dpe(ys.createHmac("sha256",r).update(t).digest())}}O$.NodeCrypto=C$;function dpe(e){let t=new ArrayBuffer(e.length),r=new Uint8Array(t);for(let n=0;n<e.length;++n)r[n]=e[n];return t}function lpe(e){return Buffer.from(e)}});var Fp=A(function(hc){var fpe=hc&&hc.__createBinding||(Object.create?function(e,t,r,n){if(n===void 0)n=r;var i=Object.getOwnPropertyDescriptor(t,r);if(!i||("get"in i?!t.__esModule:i.writable||i.configurable))i={enumerable:!0,get:function(){return t[r]}};Object.defineProperty(e,n,i)}:function(e,t,r,n){if(n===void 0)n=r;e[n]=t[r]}),hpe=hc&&hc.__exportStar||function(e,t){for(var r in e)if(r!=="default"&&!Object.prototype.hasOwnProperty.call(t,r))fpe(t,e,r)};Object.defineProperty(hc,"__esModule",{value:!0});hc.createCrypto=ppe;hc.hasBrowserCrypto=L$;var U$=x$(),P$=D$();hpe(l0(),hc);function ppe(){if(L$())return new U$.BrowserCrypto;return new P$.NodeCrypto}function L$(){return typeof window<"u"&&typeof window.crypto<"u"&&typeof window.crypto.subtle<"u"}});var tf=A(function(f0,q$){/*! safe-buffer. MIT License. Feross Aboukhadijeh <https://feross.org/opensource> */var r_=C("buffer"),Da=r_.Buffer;function M$(e,t){for(var r in e)t[r]=e[r]}if(Da.from&&Da.alloc&&Da.allocUnsafe&&Da.allocUnsafeSlow)q$.exports=r_;else M$(r_,f0),f0.Buffer=bd;function bd(e,t,r){return Da(e,t,r)}bd.prototype=Object.create(Da.prototype);M$(Da,bd);bd.from=function(e,t,r){if(typeof e==="number")throw TypeError("Argument must not be a number");return Da(e,t,r)};bd.alloc=function(e,t,r){if(typeof e!=="number")throw TypeError("Argument must be a number");var n=Da(e);if(t!==void 0)if(typeof r==="string")n.fill(t,r);else n.fill(t);else n.fill(0);return n};bd.allocUnsafe=function(e){if(typeof e!=="number")throw TypeError("Argument must be a number");return Da(e)};bd.allocUnsafeSlow=function(e){if(typeof e!=="number")throw TypeError("Argument must be a number");return r_.SlowBuffer(e)}});var j$=A(function(sJe,B$){function h0(e){var t=(e/8|0)+(e%8===0?0:1);return t}var mpe={ES256:h0(256),ES384:h0(384),ES512:h0(521)};function gpe(e){var t=mpe[e];if(t)return t;throw Error('Unknown algorithm "'+e+'"')}B$.exports=gpe});var p0=A(function(aJe,V$){var n_=tf().Buffer,F$=j$(),i_=128,z$=0,ype=32,wpe=16,_pe=2,W$=wpe|ype|z$<<6,o_=_pe|z$<<6;function bpe(e){return e.replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}function H$(e){if(n_.isBuffer(e))return e;else if(typeof e==="string")return n_.from(e,"base64");throw TypeError("ECDSA signature must be a Base64 string or a Buffer")}function Epe(e,t){e=H$(e);var r=F$(t),n=r+1,i=e.length,o=0;if(e[o++]!==W$)throw Error('Could not find expected "seq"');var s=e[o++];if(s===(i_|1))s=e[o++];if(i-o<s)throw Error('"seq" specified length of "'+s+'", only "'+(i-o)+'" remaining');if(e[o++]!==o_)throw Error('Could not find expected "int" for "r"');var a=e[o++];if(i-o-2<a)throw Error('"r" specified length of "'+a+'", only "'+(i-o-2)+'" available');if(n<a)throw Error('"r" specified length of "'+a+'", max of "'+n+'" is acceptable');var c=o;if(o+=a,e[o++]!==o_)throw Error('Could not find expected "int" for "s"');var u=e[o++];if(i-o!==u)throw Error('"s" specified length of "'+u+'", expected "'+(i-o)+'"');if(n<u)throw Error('"s" specified length of "'+u+'", max of "'+n+'" is acceptable');var d=o;if(o+=u,o!==i)throw Error('Expected to consume entire buffer, but "'+(i-o)+'" bytes remain');var f=r-a,h=r-u,p=n_.allocUnsafe(f+a+h+u);for(o=0;o<f;++o)p[o]=0;e.copy(p,o,c+Math.max(-f,0),c+a),o=r;for(var g=o;o<g+h;++o)p[o]=0;return e.copy(p,o,d+Math.max(-h,0),d+u),p=p.toString("base64"),p=bpe(p),p}function $$(e,t,r){var n=0;while(t+n<r&&e[t+n]===0)++n;var i=e[t+n]>=i_;if(i)--n;return n}function Spe(e,t){e=H$(e);var r=F$(t),n=e.length;if(n!==r*2)throw TypeError('"'+t+'" signatures must be "'+r*2+'" bytes, saw "'+n+'"');var i=$$(e,0,r),o=$$(e,r,e.length),s=r-i,a=r-o,c=2+s+1+1+a,u=c<i_,d=n_.allocUnsafe((u?2:3)+c),f=0;if(d[f++]=W$,u)d[f++]=c;else d[f++]=i_|1,d[f++]=c&255;if(d[f++]=o_,d[f++]=s,i<0)d[f++]=0,f+=e.copy(d,f,0,r);else f+=e.copy(d,f,i,r);if(d[f++]=o_,d[f++]=a,o<0)d[f++]=0,e.copy(d,f,r);else e.copy(d,f,r+o);return d}V$.exports={derToJose:Epe,joseToDer:Spe}});var Qs=A(function(X$){Object.defineProperty(X$,"__esModule",{value:!0});X$.LRUCache=void 0;X$.snakeToCamel=Q$;X$.originalOrCamelOptions=Tpe;X$.removeUndefinedValuesInObject=vpe;X$.isValidFile=kpe;X$.getWellKnownCertificateConfigFileLocation=Rpe;var K$=C("fs"),J$=C("os"),rf=C("path"),Ape="certificate_config.json",G$="gcloud";function Q$(e){return e.replace(/([_][^_])/g,(t)=>t.slice(1).toUpperCase())}function Tpe(e){function t(r){let n=e||{};return n[r]??n[Q$(r)]}return{get:t}}class Y${capacity;#e=new Map;maxAge;constructor(e){this.capacity=e.capacity,this.maxAge=e.maxAge}#t(e,t){this.#e.delete(e),this.#e.set(e,{value:t,lastAccessed:Date.now()})}set(e,t){this.#t(e,t),this.#r()}get(e){let t=this.#e.get(e);if(!t)return;return this.#t(e,t.value),this.#r(),t.value}#r(){let e=this.maxAge?Date.now()-this.maxAge:0,t=this.#e.entries().next();while(!t.done&&(this.#e.size>this.capacity||t.value[1].lastAccessed<e))this.#e.delete(t.value[0]),t=this.#e.entries().next()}}X$.LRUCache=Y$;function vpe(e){return Object.entries(e).forEach(([t,r])=>{if(r===void 0||r==="undefined")delete e[t]}),e}async function kpe(e){try{return(await K$.promises.lstat(e)).isFile()}catch(t){return!1}}function Rpe(){let e=process.env.CLOUDSDK_CONFIG||(Npe()?rf.join(process.env.APPDATA||"",G$):rf.join(process.env.HOME||"",".config",G$));return rf.join(e,Ape)}function Npe(){return J$.platform().startsWith("win")}});var rF=A(function(eF){Object.defineProperty(eF,"__esModule",{value:!0});eF.Colours=void 0;class qr{static isEnabled(e){return e&&e.isTTY&&(typeof e.getColorDepth==="function"?e.getColorDepth()>2:!0)}static refresh(){if(qr.enabled=qr.isEnabled(process===null||process===void 0?void 0:process.stderr),!this.enabled)qr.reset="",qr.bright="",qr.dim="",qr.red="",qr.green="",qr.yellow="",qr.blue="",qr.magenta="",qr.cyan="",qr.white="",qr.grey="";else qr.reset="\x1B[0m",qr.bright="\x1B[1m",qr.dim="\x1B[2m",qr.red="\x1B[31m",qr.green="\x1B[32m",qr.yellow="\x1B[33m",qr.blue="\x1B[34m",qr.magenta="\x1B[35m",qr.cyan="\x1B[36m",qr.white="\x1B[37m",qr.grey="\x1B[90m"}}eF.Colours=qr;qr.enabled=!1;qr.reset="";qr.bright="";qr.dim="";qr.red="";qr.green="";qr.yellow="";qr.blue="";qr.magenta="";qr.cyan="";qr.white="";qr.grey="";qr.refresh()});var dF=A(function(Gn){var Upe=Gn&&Gn.__createBinding||(Object.create?function(e,t,r,n){if(n===void 0)n=r;var i=Object.getOwnPropertyDescriptor(t,r);if(!i||("get"in i?!t.__esModule:i.writable||i.configurable))i={enumerable:!0,get:function(){return t[r]}};Object.defineProperty(e,n,i)}:function(e,t,r,n){if(n===void 0)n=r;e[n]=t[r]}),Ppe=Gn&&Gn.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),nF=Gn&&Gn.__importStar||function(){var e=function(t){return e=Object.getOwnPropertyNames||function(r){var n=[];for(var i in r)if(Object.prototype.hasOwnProperty.call(r,i))n[n.length]=i;return n},e(t)};return function(t){if(t&&t.__esModule)return t;var r={};if(t!=null){for(var n=e(t),i=0;i<n.length;i++)if(n[i]!=="default")Upe(r,t,n[i])}return Ppe(r,t),r}}();Object.defineProperty(Gn,"__esModule",{value:!0});Gn.env=Gn.DebugLogBackendBase=Gn.placeholder=Gn.AdhocDebugLogger=Gn.LogSeverity=void 0;Gn.getNodeBackend=m0;Gn.getDebugBackend=Lpe;Gn.getStructuredBackend=Mpe;Gn.setBackend=qpe;Gn.log=uF;var iF=C("events"),zp=nF(C("process")),oF=nF(C("util")),ii=rF(),Ys;(function(e){e.DEFAULT="DEFAULT",e.DEBUG="DEBUG",e.INFO="INFO",e.WARNING="WARNING",e.ERROR="ERROR"})(Ys||(Gn.LogSeverity=Ys={}));class s_ extends iF.EventEmitter{constructor(e,t){super();this.namespace=e,this.upstream=t,this.func=Object.assign(this.invoke.bind(this),{instance:this,on:(r,n)=>this.on(r,n)}),this.func.debug=(...r)=>this.invokeSeverity(Ys.DEBUG,...r),this.func.info=(...r)=>this.invokeSeverity(Ys.INFO,...r),this.func.warn=(...r)=>this.invokeSeverity(Ys.WARNING,...r),this.func.error=(...r)=>this.invokeSeverity(Ys.ERROR,...r),this.func.sublog=(r)=>uF(r,this.func)}invoke(e,...t){if(this.upstream)try{this.upstream(e,...t)}catch(r){}try{this.emit("log",e,t)}catch(r){}}invokeSeverity(e,...t){this.invoke({severity:e},...t)}}Gn.AdhocDebugLogger=s_;Gn.placeholder=new s_("",()=>{}).func;class Wp{constructor(){var e;this.cached=new Map,this.filters=[],this.filtersSet=!1;let t=(e=zp.env[Gn.env.nodeEnables])!==null&&e!==void 0?e:"*";if(t==="all")t="*";this.filters=t.split(",")}log(e,t,...r){try{if(!this.filtersSet)this.setFilters(),this.filtersSet=!0;let n=this.cached.get(e);if(!n)n=this.makeLogger(e),this.cached.set(e,n);n(t,...r)}catch(n){console.error(n)}}}Gn.DebugLogBackendBase=Wp;class sF extends Wp{constructor(){super(...arguments);this.enabledRegexp=/.*/g}isEnabled(e){return this.enabledRegexp.test(e)}makeLogger(e){if(!this.enabledRegexp.test(e))return()=>{};return(t,...r)=>{var n;let i=`${ii.Colours.green}${e}${ii.Colours.reset}`,o=`${ii.Colours.yellow}${zp.pid}${ii.Colours.reset}`,s;switch(t.severity){case Ys.ERROR:s=`${ii.Colours.red}${t.severity}${ii.Colours.reset}`;break;case Ys.INFO:s=`${ii.Colours.magenta}${t.severity}${ii.Colours.reset}`;break;case Ys.WARNING:s=`${ii.Colours.yellow}${t.severity}${ii.Colours.reset}`;break;default:s=(n=t.severity)!==null&&n!==void 0?n:Ys.DEFAULT;break}let a=oF.formatWithOptions({colors:ii.Colours.enabled},...r),c=Object.assign({},t);delete c.severity;let u=Object.getOwnPropertyNames(c).length?JSON.stringify(c):"",d=u?`${ii.Colours.grey}${u}${ii.Colours.reset}`:"";console.error("%s [%s|%s] %s%s",o,i,s,a,u?` ${d}`:"")}}setFilters(){let t=this.filters.join(",").replace(/[|\\{}()[\]^$+?.]/g,"\\$&").replace(/\*/g,".*").replace(/,/g,"$|^");this.enabledRegexp=new RegExp(`^${t}$`,"i")}}function m0(){return new sF}class aF extends Wp{constructor(e){super();this.debugPkg=e}makeLogger(e){let t=this.debugPkg(e);return(r,...n)=>{t(n[0],...n.slice(1))}}setFilters(){var e;let t=(e=zp.env.NODE_DEBUG)!==null&&e!==void 0?e:"";zp.env.NODE_DEBUG=`${t}${t?",":""}${this.filters.join(",")}`}}function Lpe(e){return new aF(e)}class cF extends Wp{constructor(e){var t;super();this.upstream=(t=e)!==null&&t!==void 0?t:void 0}makeLogger(e){var t;let r=(t=this.upstream)===null||t===void 0?void 0:t.makeLogger(e);return(n,...i)=>{var o;let s=(o=n.severity)!==null&&o!==void 0?o:Ys.INFO,a=Object.assign({severity:s,message:oF.format(...i)},n),c=JSON.stringify(a);if(r)r(n,c);else console.log("%s",c)}}setFilters(){var e;(e=this.upstream)===null||e===void 0||e.setFilters()}}function Mpe(e){return new cF(e)}Gn.env={nodeEnables:"GOOGLE_SDK_NODE_LOGGING"};var g0=new Map,Yo=void 0;function qpe(e){Yo=e,g0.clear()}function uF(e,t){if(!Yo){if(!zp.env[Gn.env.nodeEnables])return Gn.placeholder}if(!e)return Gn.placeholder;if(t)e=`${t.instance.namespace}:${e}`;let r=g0.get(e);if(r)return r.func;if(Yo===null)return Gn.placeholder;else if(Yo===void 0)Yo=m0();let n=(()=>{let i=void 0;return new s_(e,(s,...a)=>{if(i!==Yo){if(Yo===null)return;else if(Yo===void 0)Yo=m0();i=Yo}Yo===null||Yo===void 0||Yo.log(e,s,...a)})})();return g0.set(e,n),n.func}});var lF=A(function(Ed){var Bpe=Ed&&Ed.__createBinding||(Object.create?function(e,t,r,n){if(n===void 0)n=r;var i=Object.getOwnPropertyDescriptor(t,r);if(!i||("get"in i?!t.__esModule:i.writable||i.configurable))i={enumerable:!0,get:function(){return t[r]}};Object.defineProperty(e,n,i)}:function(e,t,r,n){if(n===void 0)n=r;e[n]=t[r]}),jpe=Ed&&Ed.__exportStar||function(e,t){for(var r in e)if(r!=="default"&&!Object.prototype.hasOwnProperty.call(t,r))Bpe(t,e,r)};Object.defineProperty(Ed,"__esModule",{value:!0});jpe(dF(),Ed)});var fF=A(function(fJe,$pe){$pe.exports={name:"google-auth-library",version:"10.9.1",author:"Google Inc.",description:"Google APIs Authentication Client Library for Node.js",engines:{node:">=18"},main:"./build/src/index.js",types:"./build/src/index.d.ts",repository:{type:"git",directory:"core/packages/google-auth-library-nodejs",url:"https://github.com/googleapis/google-cloud-node.git"},keywords:["google","api","google apis","client","client library"],dependencies:{"base64-js":"^1.3.0","ecdsa-sig-formatter":"^1.0.11",gaxios:"^7.1.4","gcp-metadata":"8.1.2","google-logging-utils":"1.1.3",jws:"^4.0.0"},devDependencies:{"@types/base64-js":"^1.2.5","@types/jws":"^3.1.0","@types/mocha":"^10.0.10","@types/mv":"^2.1.0","@types/ncp":"^2.0.8","@types/node":"^24.0.0","@types/sinon":"^21.0.0","assert-rejects":"^1.0.0",c8:"^10.1.3",codecov:"^3.8.3",gts:"^6.0.2","is-docker":"^3.0.0",jsdoc:"^4.0.4","jsdoc-fresh":"^5.0.0","jsdoc-region-tag":"^4.0.0",karma:"^6.0.0","karma-chrome-launcher":"^3.0.0","karma-coverage":"^2.0.0","karma-firefox-launcher":"^2.0.0","karma-mocha":"^2.0.0","karma-sourcemap-loader":"^0.4.0","karma-webpack":"^5.0.1",keypair:"^1.0.4",mocha:"^11.1.0",mv:"^2.1.1",ncp:"^2.0.0",nock:"^14.0.5","null-loader":"^4.0.1",puppeteer:"^24.0.0",sinon:"21.0.3","ts-loader":"^9.5.2",typescript:"5.8.3",webpack:"^5.97.1","webpack-cli":"^6.0.1"},files:["build/src","!build/src/**/*.map"],scripts:{test:"c8 mocha build/test",clean:"gts clean",prepare:"npm run compile",lint:"gts check --no-inline-config",compile:"tsc -p .",fix:"gts fix",pretest:"npm run compile -- --sourceMap",docs:"jsdoc -c .jsdoc.js","samples-setup":"cd samples/ && npm link ../ && npm run setup && cd ../","samples-test":"cd samples/ && npm link ../ && npm test && cd ../","system-test":"mocha build/system-test --timeout 60000","presystem-test":"npm run compile -- --sourceMap",webpack:"webpack","browser-test":"karma start",prelint:"cd samples; npm link ../; npm install"},license:"Apache-2.0",homepage:"https://github.com/googleapis/google-cloud-node/tree/main/core/packages/google-auth-library-nodejs"}});var w0=A(function(pF){Object.defineProperty(pF,"__esModule",{value:!0});pF.USER_AGENT=pF.PRODUCT_NAME=pF.pkg=void 0;var y0=fF();pF.pkg=y0;var hF="google-api-nodejs-client";pF.PRODUCT_NAME=hF;var Fpe=`${hF}/${y0.version}`;pF.USER_AGENT=Fpe});var Xo=A(function(_F){Object.defineProperty(_F,"__esModule",{value:!0});_F.AuthClient=_F.DEFAULT_EAGER_REFRESH_THRESHOLD_MILLIS=_F.DEFAULT_UNIVERSE=void 0;var gF=C("events"),nf=to(),yF=Qs(),wF=lF(),of=w0();_F.DEFAULT_UNIVERSE="googleapis.com";_F.DEFAULT_EAGER_REFRESH_THRESHOLD_MILLIS=300000;class ro extends gF.EventEmitter{apiKey;projectId;quotaProjectId;transporter;credentials={};eagerRefreshThresholdMillis=_F.DEFAULT_EAGER_REFRESH_THRESHOLD_MILLIS;forceRefreshOnFailure=!1;universeDomain=_F.DEFAULT_UNIVERSE;static RequestMethodNameSymbol=Symbol("request method name");static RequestLogIdSymbol=Symbol("request log id");constructor(e={}){super();let t=yF.originalOrCamelOptions(e);if(this.apiKey=e.apiKey,this.projectId=t.get("project_id")??null,this.quotaProjectId=t.get("quota_project_id"),this.credentials=t.get("credentials")??{},this.universeDomain=t.get("universe_domain")??_F.DEFAULT_UNIVERSE,this.transporter=e.transporter??new nf.Gaxios(e.transporterOptions),t.get("useAuthRequestParameters")!==!1)this.transporter.interceptors.request.add(ro.DEFAULT_REQUEST_INTERCEPTOR),this.transporter.interceptors.response.add(ro.DEFAULT_RESPONSE_INTERCEPTOR);if(e.eagerRefreshThresholdMillis)this.eagerRefreshThresholdMillis=e.eagerRefreshThresholdMillis;this.forceRefreshOnFailure=e.forceRefreshOnFailure??!1}fetch(...e){let t=e[0],r=e[1],n=void 0,i=new Headers;if(typeof t==="string")n=new URL(t);else if(t instanceof URL)n=t;else if(t&&t.url)n=new URL(t.url);if(t&&typeof t==="object"&&"headers"in t)nf.Gaxios.mergeHeaders(i,t.headers);if(r)nf.Gaxios.mergeHeaders(i,new Headers(r.headers));if(typeof t==="object"&&!(t instanceof URL))return this.request({...r,...t,headers:i,url:n});else return this.request({...r,headers:i,url:n})}setCredentials(e){this.credentials=e}addSharedMetadataHeaders(e){if(!e.has("x-goog-user-project")&&this.quotaProjectId)e.set("x-goog-user-project",this.quotaProjectId);return e}addUserProjectAndAuthHeaders(e,t){let r=t.get("x-goog-user-project"),n=t.get("authorization");if(r)e.set("x-goog-user-project",r);if(n)e.set("authorization",n);return e}static log=wF.log("auth");static DEFAULT_REQUEST_INTERCEPTOR={resolved:async(e)=>{if(!e.headers.has("x-goog-api-client")){let r=process.version.replace(/^v/,"");e.headers.set("x-goog-api-client",`gl-node/${r}`)}let t=e.headers.get("User-Agent");if(!t)e.headers.set("User-Agent",of.USER_AGENT);else if(!t.includes(`${of.PRODUCT_NAME}/`))e.headers.set("User-Agent",`${t} ${of.USER_AGENT}`);try{let r=e,n=r[ro.RequestMethodNameSymbol],i=`${Math.floor(Math.random()*1000)}`;r[ro.RequestLogIdSymbol]=i;let o={url:e.url,headers:e.headers};if(n)ro.log.info("%s [%s] request %j",n,i,o);else ro.log.info("[%s] request %j",i,o)}catch(r){}return e}};static DEFAULT_RESPONSE_INTERCEPTOR={resolved:async(e)=>{try{let t=e.config,r=t[ro.RequestMethodNameSymbol],n=t[ro.RequestLogIdSymbol];if(r)ro.log.info("%s [%s] response %j",r,n,e.data);else ro.log.info("[%s] response %j",n,e.data)}catch(t){}return e},rejected:async(e)=>{try{let t=e.config,r=t[ro.RequestMethodNameSymbol],n=t[ro.RequestLogIdSymbol];if(r)ro.log.info("%s [%s] error %j",r,n,e.response?.data);else ro.log.error("[%s] error %j",n,e.response?.data)}catch(t){}throw e}};static setMethodName(e,t){try{let r=e;r[ro.RequestMethodNameSymbol]=t}catch(r){}}static get RETRY_CONFIG(){return{retry:!0,retryConfig:{httpMethodsToRetry:["GET","PUT","POST","HEAD","OPTIONS","DELETE"]}}}}_F.AuthClient=ro});var b0=A(function(AF){Object.defineProperty(AF,"__esModule",{value:!0});AF.LoginTicket=void 0;class SF{envelope;payload;constructor(e,t){this.envelope=e,this.payload=t}getEnvelope(){return this.envelope}getPayload(){return this.payload}getUserId(){let e=this.getPayload();if(e&&e.sub)return e.sub;return null}getAttributes(){return{envelope:this.getEnvelope(),payload:this.getPayload()}}}AF.LoginTicket=SF});var yu=A(function(CF){Object.defineProperty(CF,"__esModule",{value:!0});CF.OAuth2Client=CF.ClientAuthentication=CF.CertificateFormat=CF.CodeChallengeMethod=void 0;var a_=to(),kF=C("querystring"),RF=C("stream"),NF=p0(),c_=Qs(),sf=Fp(),_s=Xo(),xF=b0(),vF;(function(e){e.Plain="plain",e.S256="S256"})(vF||(CF.CodeChallengeMethod=vF={}));var pc;(function(e){e.PEM="PEM",e.JWK="JWK"})(pc||(CF.CertificateFormat=pc={}));var Hp;(function(e){e.ClientSecretPost="ClientSecretPost",e.ClientSecretBasic="ClientSecretBasic",e.None="None"})(Hp||(CF.ClientAuthentication=Hp={}));class ws extends _s.AuthClient{redirectUri;certificateCache={};certificateExpiry=null;certificateCacheFormat=pc.PEM;refreshTokenPromises=new Map;endpoints;issuers;clientAuthentication;_clientId;_clientSecret;refreshHandler;constructor(e={},t,r){super(typeof e==="object"?e:{});if(typeof e!=="object")e={clientId:e,clientSecret:t,redirectUri:r};this._clientId=e.clientId||e.client_id,this._clientSecret=e.clientSecret||e.client_secret,this.redirectUri=e.redirectUri||e.redirect_uris?.[0],this.endpoints={tokenInfoUrl:"https://oauth2.googleapis.com/tokeninfo",oauth2AuthBaseUrl:"https://accounts.google.com/o/oauth2/v2/auth",oauth2TokenUrl:"https://oauth2.googleapis.com/token",oauth2RevokeUrl:"https://oauth2.googleapis.com/revoke",oauth2FederatedSignonPemCertsUrl:"https://www.googleapis.com/oauth2/v1/certs",oauth2FederatedSignonJwkCertsUrl:"https://www.googleapis.com/oauth2/v3/certs",oauth2IapPublicKeyUrl:"https://www.gstatic.com/iap/verify/public_key",...e.endpoints},this.clientAuthentication=e.clientAuthentication||Hp.ClientSecretPost,this.issuers=e.issuers||["accounts.google.com","https://accounts.google.com",this.universeDomain]}static GOOGLE_TOKEN_INFO_URL="https://oauth2.googleapis.com/tokeninfo";static CLOCK_SKEW_SECS_=300;static DEFAULT_MAX_TOKEN_LIFETIME_SECS_=86400;generateAuthUrl(e={}){if(e.code_challenge_method&&!e.code_challenge)throw Error("If a code_challenge_method is provided, code_challenge must be included.");if(e.response_type=e.response_type||"code",e.client_id=e.client_id||this._clientId,e.redirect_uri=e.redirect_uri||this.redirectUri,Array.isArray(e.scope))e.scope=e.scope.join(" ");return this.endpoints.oauth2AuthBaseUrl.toString()+"?"+kF.stringify(e)}generateCodeVerifier(){throw Error("generateCodeVerifier is removed, please use generateCodeVerifierAsync instead.")}async generateCodeVerifierAsync(){let e=sf.createCrypto(),r=e.randomBytesBase64(96).replace(/\+/g,"~").replace(/=/g,"_").replace(/\//g,"-"),i=(await e.sha256DigestBase64(r)).split("=")[0].replace(/\+/g,"-").replace(/\//g,"_");return{codeVerifier:r,codeChallenge:i}}getToken(e,t){let r=typeof e==="string"?{code:e}:e;if(t)this.getTokenAsync(r).then((n)=>t(null,n.tokens,n.res),(n)=>t(n,null,n.response));else return this.getTokenAsync(r)}async getTokenAsync(e){let t=this.endpoints.oauth2TokenUrl.toString(),r=new Headers,n={client_id:e.client_id||this._clientId,code_verifier:e.codeVerifier,code:e.code,grant_type:"authorization_code",redirect_uri:e.redirect_uri||this.redirectUri};if(this.clientAuthentication===Hp.ClientSecretBasic){let a=Buffer.from(`${this._clientId}:${this._clientSecret}`);r.set("authorization",`Basic ${a.toString("base64")}`)}if(this.clientAuthentication===Hp.ClientSecretPost)n.client_secret=this._clientSecret;let i={...ws.RETRY_CONFIG,method:"POST",url:t,data:new URLSearchParams(c_.removeUndefinedValuesInObject(n)),headers:r};_s.AuthClient.setMethodName(i,"getTokenAsync");let o=await this.transporter.request(i),s=o.data;if(o.data&&o.data.expires_in)s.expiry_date=new Date().getTime()+o.data.expires_in*1000,delete s.expires_in;return this.emit("tokens",s),{tokens:s,res:o}}async refreshToken(e){if(!e)return this.refreshTokenNoCache(e);if(this.refreshTokenPromises.has(e))return this.refreshTokenPromises.get(e);let t=this.refreshTokenNoCache(e).then((r)=>(this.refreshTokenPromises.delete(e),r),(r)=>{throw this.refreshTokenPromises.delete(e),r});return this.refreshTokenPromises.set(e,t),t}async refreshTokenNoCache(e){if(!e)throw Error("No refresh token is set.");let t=this.endpoints.oauth2TokenUrl.toString(),r={refresh_token:e,client_id:this._clientId,client_secret:this._clientSecret,grant_type:"refresh_token"},n;try{let o={...ws.RETRY_CONFIG,method:"POST",url:t,data:new URLSearchParams(c_.removeUndefinedValuesInObject(r))};_s.AuthClient.setMethodName(o,"refreshTokenNoCache"),n=await this.transporter.request(o)}catch(o){if(o instanceof a_.GaxiosError&&o.message==="invalid_grant"&&o.response?.data&&/ReAuth/i.test(o.response.data.error_description))o.message=JSON.stringify(o.response.data);throw o}let i=n.data;if(n.data&&n.data.expires_in)i.expiry_date=new Date().getTime()+n.data.expires_in*1000,delete i.expires_in;return this.emit("tokens",i),{tokens:i,res:n}}refreshAccessToken(e){if(e)this.refreshAccessTokenAsync().then((t)=>e(null,t.credentials,t.res),e);else return this.refreshAccessTokenAsync()}async refreshAccessTokenAsync(){let e=await this.refreshToken(this.credentials.refresh_token),t=e.tokens;return t.refresh_token=this.credentials.refresh_token,this.credentials=t,{credentials:this.credentials,res:e.res}}getAccessToken(e){if(e)this.getAccessTokenAsync().then((t)=>e(null,t.token,t.res),e);else return this.getAccessTokenAsync()}async getAccessTokenAsync(){if(!this.credentials.access_token||this.isTokenExpiring()){if(!this.credentials.refresh_token)if(this.refreshHandler){let r=await this.processAndValidateRefreshHandler();if(r?.access_token)return this.setCredentials(r),{token:this.credentials.access_token}}else throw Error("No refresh token or refresh handler callback is set.");let t=await this.refreshAccessTokenAsync();if(!t.credentials||t.credentials&&!t.credentials.access_token)throw Error("Could not refresh access token.");return{token:t.credentials.access_token,res:t.res}}else return{token:this.credentials.access_token}}async getRequestHeaders(e){return(await this.getRequestMetadataAsync(e)).headers}async getRequestMetadataAsync(e){let t=this.credentials;if(!t.access_token&&!t.refresh_token&&!this.apiKey&&!this.refreshHandler)throw Error("No access, refresh token, API key or refresh handler callback is set.");if(t.access_token&&!this.isTokenExpiring()){t.token_type=t.token_type||"Bearer";let s=new Headers({authorization:t.token_type+" "+t.access_token});return{headers:this.addSharedMetadataHeaders(s)}}if(this.refreshHandler){let s=await this.processAndValidateRefreshHandler();if(s?.access_token){this.setCredentials(s);let a=new Headers({authorization:"Bearer "+this.credentials.access_token});return{headers:this.addSharedMetadataHeaders(a)}}}if(this.apiKey)return{headers:new Headers({"X-Goog-Api-Key":this.apiKey})};let r=null,n=null;try{r=await this.refreshToken(t.refresh_token),n=r.tokens}catch(s){let a=s;if(a.response&&(a.response.status===403||a.response.status===404))a.message=`Could not refresh access token: ${a.message}`;throw a}let i=this.credentials;i.token_type=i.token_type||"Bearer",n.refresh_token=i.refresh_token,this.credentials=n;let o=new Headers({authorization:i.token_type+" "+n.access_token});return{headers:this.addSharedMetadataHeaders(o),res:r.res}}static getRevokeTokenUrl(e){return new ws().getRevokeTokenURL(e).toString()}getRevokeTokenURL(e){let t=new URL(this.endpoints.oauth2RevokeUrl);return t.searchParams.append("token",e),t}revokeToken(e,t){let r={...ws.RETRY_CONFIG,url:this.getRevokeTokenURL(e).toString(),method:"POST"};if(_s.AuthClient.setMethodName(r,"revokeToken"),t)this.transporter.request(r).then((n)=>t(null,n),t);else return this.transporter.request(r)}revokeCredentials(e){if(e)this.revokeCredentialsAsync().then((t)=>e(null,t),e);else return this.revokeCredentialsAsync()}async revokeCredentialsAsync(){let e=this.credentials.access_token;if(this.credentials={},e)return this.revokeToken(e);else throw Error("No access token to revoke.")}request(e,t){if(t)this.requestAsync(e).then((r)=>t(null,r),(r)=>t(r,r.response));else return this.requestAsync(e)}async requestAsync(e,t=!1){try{let r=await this.getRequestMetadataAsync();if(e.headers=a_.Gaxios.mergeHeaders(e.headers),this.addUserProjectAndAuthHeaders(e.headers,r.headers),this.apiKey)e.headers.set("X-Goog-Api-Key",this.apiKey);return await this.transporter.request(e)}catch(r){let n=r.response;if(n){let i=n.status,o=this.credentials&&this.credentials.access_token&&this.credentials.refresh_token&&(!this.credentials.expiry_date||this.forceRefreshOnFailure),s=this.credentials&&this.credentials.access_token&&!this.credentials.refresh_token&&(!this.credentials.expiry_date||this.forceRefreshOnFailure)&&this.refreshHandler,a=n.config.data instanceof RF.Readable,c=i===401||i===403;if(!t&&c&&!a&&o)return await this.refreshAccessTokenAsync(),this.requestAsync(e,!0);else if(!t&&c&&!a&&s){let u=await this.processAndValidateRefreshHandler();if(u?.access_token)this.setCredentials(u);return this.requestAsync(e,!0)}}throw r}}verifyIdToken(e,t){if(t&&typeof t!=="function")throw Error("This method accepts an options object as the first parameter, which includes the idToken, audience, and maxExpiry.");if(t)this.verifyIdTokenAsync(e).then((r)=>t(null,r),t);else return this.verifyIdTokenAsync(e)}async verifyIdTokenAsync(e){if(!e.idToken)throw Error("The verifyIdToken method requires an ID Token");let t=await this.getFederatedSignonCertsAsync();return await this.verifySignedJwtWithCertsAsync(e.idToken,t.certs,e.audience,this.issuers,e.maxExpiry)}async getTokenInfo(e){let{data:t}=await this.transporter.request({...ws.RETRY_CONFIG,method:"POST",headers:{"content-type":"application/x-www-form-urlencoded;charset=UTF-8",authorization:`Bearer ${e}`},url:this.endpoints.tokenInfoUrl.toString()}),r=Object.assign({expiry_date:new Date().getTime()+t.expires_in*1000,scopes:t.scope.split(" ")},t);return delete r.expires_in,delete r.scope,r}getFederatedSignonCerts(e){if(e)this.getFederatedSignonCertsAsync().then((t)=>e(null,t.certs,t.res),e);else return this.getFederatedSignonCertsAsync()}async getFederatedSignonCertsAsync(){let e=new Date().getTime(),t=sf.hasBrowserCrypto()?pc.JWK:pc.PEM;if(this.certificateExpiry&&e<this.certificateExpiry.getTime()&&this.certificateCacheFormat===t)return{certs:this.certificateCache,format:t};let r,n;switch(t){case pc.PEM:n=this.endpoints.oauth2FederatedSignonPemCertsUrl.toString();break;case pc.JWK:n=this.endpoints.oauth2FederatedSignonJwkCertsUrl.toString();break;default:throw Error(`Unsupported certificate format ${t}`)}try{let c={...ws.RETRY_CONFIG,url:n};_s.AuthClient.setMethodName(c,"getFederatedSignonCertsAsync"),r=await this.transporter.request(c)}catch(c){if(c instanceof Error)c.message=`Failed to retrieve verification certificates: ${c.message}`;throw c}let i=r?.headers.get("cache-control"),o=-1;if(i){let c=/max-age=(?<maxAge>[0-9]+)/.exec(i)?.groups?.maxAge;if(c)o=Number(c)*1000}let s={};switch(t){case pc.PEM:s=r.data;break;case pc.JWK:for(let c of r.data.keys)s[c.kid]=c;break;default:throw Error(`Unsupported certificate format ${t}`)}let a=new Date;return this.certificateExpiry=o===-1?null:new Date(a.getTime()+o),this.certificateCache=s,this.certificateCacheFormat=t,{certs:s,format:t,res:r}}getIapPublicKeys(e){if(e)this.getIapPublicKeysAsync().then((t)=>e(null,t.pubkeys,t.res),e);else return this.getIapPublicKeysAsync()}async getIapPublicKeysAsync(){let e,t=this.endpoints.oauth2IapPublicKeyUrl.toString();try{let r={...ws.RETRY_CONFIG,url:t};_s.AuthClient.setMethodName(r,"getIapPublicKeysAsync"),e=await this.transporter.request(r)}catch(r){if(r instanceof Error)r.message=`Failed to retrieve verification certificates: ${r.message}`;throw r}return{pubkeys:e.data,res:e}}verifySignedJwtWithCerts(){throw Error("verifySignedJwtWithCerts is removed, please use verifySignedJwtWithCertsAsync instead.")}async verifySignedJwtWithCertsAsync(e,t,r,n,i){let o=sf.createCrypto();if(!i)i=ws.DEFAULT_MAX_TOKEN_LIFETIME_SECS_;let s=e.split(".");if(s.length!==3)throw Error("Wrong number of segments in token: "+e);let a=s[0]+"."+s[1],c=s[2],u,d;try{u=JSON.parse(o.decodeBase64StringUtf8(s[0]))}catch(I){if(I instanceof Error)I.message=`Can't parse token envelope: ${s[0]}': ${I.message}`;throw I}if(!u)throw Error("Can't parse token envelope: "+s[0]);try{d=JSON.parse(o.decodeBase64StringUtf8(s[1]))}catch(I){if(I instanceof Error)I.message=`Can't parse token payload '${s[0]}`;throw I}if(!d)throw Error("Can't parse token payload: "+s[1]);if(!Object.prototype.hasOwnProperty.call(t,u.kid))throw Error("No pem found for envelope: "+JSON.stringify(u));let f=t[u.kid];if(u.alg==="ES256")c=NF.joseToDer(c,"ES256").toString("base64");if(!await o.verify(f,a,c))throw Error("Invalid token signature: "+e);if(!d.iat)throw Error("No issue time in token: "+JSON.stringify(d));if(!d.exp)throw Error("No expiration time in token: "+JSON.stringify(d));let p=Number(d.iat);if(isNaN(p))throw Error("iat field using invalid format");let g=Number(d.exp);if(isNaN(g))throw Error("exp field using invalid format");let _=new Date().getTime()/1000;if(g>=_+i)throw Error("Expiration time too far in future: "+JSON.stringify(d));let R=p-ws.CLOCK_SKEW_SECS_,O=g+ws.CLOCK_SKEW_SECS_;if(_<R)throw Error("Token used too early, "+_+" < "+R+": "+JSON.stringify(d));if(_>O)throw Error("Token used too late, "+_+" > "+O+": "+JSON.stringify(d));if(n&&n.indexOf(d.iss)<0)throw Error("Invalid issuer, expected one of ["+n+"], but got "+d.iss);if(typeof r<"u"&&r!==null){let I=d.aud,Ne=!1;if(r.constructor===Array)Ne=r.indexOf(I)>-1;else Ne=I===r;if(!Ne)throw Error("Wrong recipient, payload audience != requiredAudience")}return new xF.LoginTicket(u,d)}async processAndValidateRefreshHandler(){if(this.refreshHandler){let e=await this.refreshHandler();if(!e.access_token)throw Error("No access token is returned by the refreshHandler callback.");return e}return}isTokenExpiring(){let e=this.credentials.expiry_date;return e?e<=new Date().getTime()+this.eagerRefreshThresholdMillis:!1}}CF.OAuth2Client=ws});var E0=A(function(PF){Object.defineProperty(PF,"__esModule",{value:!0});PF.Compute=void 0;var IF=to(),u_=$p(),DF=yu();class UF extends DF.OAuth2Client{serviceAccountEmail;scopes;constructor(e={}){super(e);this.credentials={expiry_date:1,refresh_token:"compute-placeholder"},this.serviceAccountEmail=e.serviceAccountEmail||"default",this.scopes=Array.isArray(e.scopes)?e.scopes:e.scopes?[e.scopes]:[]}async refreshTokenNoCache(){let e=`service-accounts/${this.serviceAccountEmail}/token`,t;try{let n={property:e};if(this.scopes.length>0)n.params={scopes:this.scopes.join(",")};t=await u_.instance(n)}catch(n){if(n instanceof IF.GaxiosError)n.message=`Could not refresh access token: ${n.message}`,this.wrapError(n);throw n}let r=t;if(t&&t.expires_in)r.expiry_date=new Date().getTime()+t.expires_in*1000,delete r.expires_in;return this.emit("tokens",r),{tokens:r,res:null}}async fetchIdToken(e){let t=`service-accounts/${this.serviceAccountEmail}/identity?format=full&audience=${e}`,r;try{r=await u_.instance({property:t})}catch(n){if(n instanceof Error)n.message=`Could not fetch ID token: ${n.message}`;throw n}return r}wrapError(e){let t=e.response;if(t&&t.status){if(e.status=t.status,t.status===403)e.message="A Forbidden error was returned while attempting to retrieve an access token for the Compute Engine built-in service account. This may be because the Compute Engine instance does not have the correct permission scopes specified: "+e.message;else if(t.status===404)e.message="A Not Found error was returned while attempting to retrieve an accesstoken for the Compute Engine built-in service account. This may be because the Compute Engine instance does not have any permission scopes specified: "+e.message}}}PF.Compute=UF});var S0=A(function(BF){Object.defineProperty(BF,"__esModule",{value:!0});BF.IdTokenClient=void 0;var MF=yu();class qF extends MF.OAuth2Client{targetAudience;idTokenProvider;constructor(e){super(e);this.targetAudience=e.targetAudience,this.idTokenProvider=e.idTokenProvider}async getRequestMetadataAsync(){if(!this.credentials.id_token||!this.credentials.expiry_date||this.isTokenExpiring()){let t=await this.idTokenProvider.fetchIdToken(this.targetAudience);this.credentials={id_token:t,expiry_date:this.getIdTokenExpiryDate(t)}}return{headers:new Headers({authorization:"Bearer "+this.credentials.id_token})}}getIdTokenExpiryDate(e){let t=e.split(".")[1];if(t)return JSON.parse(Buffer.from(t,"base64").toString("ascii")).exp*1000}}BF.IdTokenClient=qF});var A0=A(function($F){Object.defineProperty($F,"__esModule",{value:!0});$F.GCPEnv=void 0;$F.clear=Kpe;$F.getEnv=Jpe;var d_=$p(),Ua;(function(e){e.APP_ENGINE="APP_ENGINE",e.KUBERNETES_ENGINE="KUBERNETES_ENGINE",e.CLOUD_FUNCTIONS="CLOUD_FUNCTIONS",e.COMPUTE_ENGINE="COMPUTE_ENGINE",e.CLOUD_RUN="CLOUD_RUN",e.CLOUD_RUN_JOBS="CLOUD_RUN_JOBS",e.NONE="NONE"})(Ua||($F.GCPEnv=Ua={}));var Vp;function Kpe(){Vp=void 0}async function Jpe(){if(Vp)return Vp;return Vp=Qpe(),Vp}async function Qpe(){let e=Ua.NONE;if(Ype())e=Ua.APP_ENGINE;else if(Xpe())e=Ua.CLOUD_FUNCTIONS;else if(await rme())if(await tme())e=Ua.KUBERNETES_ENGINE;else if(Zpe())e=Ua.CLOUD_RUN;else if(eme())e=Ua.CLOUD_RUN_JOBS;else e=Ua.COMPUTE_ENGINE;else e=Ua.NONE;return e}function Ype(){return!!(process.env.GAE_SERVICE||process.env.GAE_MODULE_NAME)}function Xpe(){return!!(process.env.FUNCTION_NAME||process.env.FUNCTION_TARGET)}function Zpe(){return!!process.env.K_CONFIGURATION}function eme(){return!!process.env.CLOUD_RUN_JOB}async function tme(){try{return await d_.instance("attributes/cluster-name"),!0}catch(e){return!1}}async function rme(){return d_.isAvailable()}});var T0=A(function(bJe,zF){var l_=tf().Buffer,ome=C("stream"),sme=C("util");function f_(e){if(this.buffer=null,this.writable=!0,this.readable=!0,!e)return this.buffer=l_.alloc(0),this;if(typeof e.pipe==="function")return this.buffer=l_.alloc(0),e.pipe(this),this;if(e.length||typeof e==="object")return this.buffer=e,this.writable=!1,process.nextTick(function(){this.emit("end",e),this.readable=!1,this.emit("close")}.bind(this)),this;throw TypeError("Unexpected data type ("+typeof e+")")}sme.inherits(f_,ome);f_.prototype.write=function(t){this.buffer=l_.concat([this.buffer,l_.from(t)]),this.emit("data",t)};f_.prototype.end=function(t){if(t)this.write(t);this.emit("end",t),this.emit("close"),this.writable=!1,this.readable=!1};zF.exports=f_});var HF=A(function(EJe,WF){var Gp=C("buffer").Buffer,v0=C("buffer").SlowBuffer;WF.exports=h_;function h_(e,t){if(!Gp.isBuffer(e)||!Gp.isBuffer(t))return!1;if(e.length!==t.length)return!1;var r=0;for(var n=0;n<e.length;n++)r|=e[n]^t[n];return r===0}h_.install=function(){Gp.prototype.equal=v0.prototype.equal=function(t){return h_(this,t)}};var ame=Gp.prototype.equal,cme=v0.prototype.equal;h_.restore=function(){Gp.prototype.equal=ame,v0.prototype.equal=cme}});var x0=A(function(SJe,e2){var cf=tf().Buffer,bs=C("crypto"),GF=p0(),VF=C("util"),ume=`"%s" is not a valid algorithm.
57
+ Supported algorithms are:
58
+ "HS256", "HS384", "HS512", "RS256", "RS384", "RS512", "PS256", "PS384", "PS512", "ES256", "ES384", "ES512" and "none".`,Kp="secret must be a string or buffer",af="key must be a string or a buffer",dme="key must be a string, a buffer or an object",R0=typeof bs.createPublicKey==="function";if(R0)af+=" or a KeyObject",Kp+="or a KeyObject";function KF(e){if(cf.isBuffer(e))return;if(typeof e==="string")return;if(!R0)throw Xs(af);if(typeof e!=="object")throw Xs(af);if(typeof e.type!=="string")throw Xs(af);if(typeof e.asymmetricKeyType!=="string")throw Xs(af);if(typeof e.export!=="function")throw Xs(af)}function JF(e){if(cf.isBuffer(e))return;if(typeof e==="string")return;if(typeof e==="object")return;throw Xs(dme)}function lme(e){if(cf.isBuffer(e))return;if(typeof e==="string")return e;if(!R0)throw Xs(Kp);if(typeof e!=="object")throw Xs(Kp);if(e.type!=="secret")throw Xs(Kp);if(typeof e.export!=="function")throw Xs(Kp)}function N0(e){return e.replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}function QF(e){e=e.toString();var t=4-e.length%4;if(t!==4)for(var r=0;r<t;++r)e+="=";return e.replace(/\-/g,"+").replace(/_/g,"/")}function Xs(e){var t=[].slice.call(arguments,1),r=VF.format.bind(VF,e).apply(null,t);return TypeError(r)}function fme(e){return cf.isBuffer(e)||typeof e==="string"}function Jp(e){if(!fme(e))e=JSON.stringify(e);return e}function YF(e){return function(r,n){lme(n),r=Jp(r);var i=bs.createHmac("sha"+e,n),o=(i.update(r),i.digest("base64"));return N0(o)}}var k0,hme="timingSafeEqual"in bs?function(t,r){if(t.byteLength!==r.byteLength)return!1;return bs.timingSafeEqual(t,r)}:function(t,r){if(!k0)k0=HF();return k0(t,r)};function pme(e){return function(r,n,i){var o=YF(e)(r,i);return hme(cf.from(n),cf.from(o))}}function XF(e){return function(r,n){JF(n),r=Jp(r);var i=bs.createSign("RSA-SHA"+e),o=(i.update(r),i.sign(n,"base64"));return N0(o)}}function ZF(e){return function(r,n,i){KF(i),r=Jp(r),n=QF(n);var o=bs.createVerify("RSA-SHA"+e);return o.update(r),o.verify(i,n,"base64")}}function mme(e){return function(r,n){JF(n),r=Jp(r);var i=bs.createSign("RSA-SHA"+e),o=(i.update(r),i.sign({key:n,padding:bs.constants.RSA_PKCS1_PSS_PADDING,saltLength:bs.constants.RSA_PSS_SALTLEN_DIGEST},"base64"));return N0(o)}}function gme(e){return function(r,n,i){KF(i),r=Jp(r),n=QF(n);var o=bs.createVerify("RSA-SHA"+e);return o.update(r),o.verify({key:i,padding:bs.constants.RSA_PKCS1_PSS_PADDING,saltLength:bs.constants.RSA_PSS_SALTLEN_DIGEST},n,"base64")}}function yme(e){var t=XF(e);return function(){var n=t.apply(null,arguments);return n=GF.derToJose(n,"ES"+e),n}}function wme(e){var t=ZF(e);return function(n,i,o){i=GF.joseToDer(i,"ES"+e).toString("base64");var s=t(n,i,o);return s}}function _me(){return function(){return""}}function bme(){return function(t,r){return r===""}}e2.exports=function(t){var r={hs:YF,rs:XF,ps:mme,es:yme,none:_me},n={hs:pme,rs:ZF,ps:gme,es:wme,none:bme},i=t.match(/^(RS|PS|ES|HS)(256|384|512)$|^(none)$/);if(!i)throw Xs(ume,t);var o=(i[1]||i[3]).toLowerCase(),s=i[2];return{sign:r[o](s),verify:n[o](s)}}});var C0=A(function(AJe,t2){var Eme=C("buffer").Buffer;t2.exports=function(t){if(typeof t==="string")return t;if(typeof t==="number"||Eme.isBuffer(t))return t.toString();return JSON.stringify(t)}});var a2=A(function(TJe,s2){var Sme=tf().Buffer,r2=T0(),Ame=x0(),Tme=C("stream"),n2=C0(),O0=C("util");function i2(e,t){return Sme.from(e,t).toString("base64").replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}function vme(e,t,r){r=r||"utf8";var n=i2(n2(e),"binary"),i=i2(n2(t),r);return O0.format("%s.%s",n,i)}function o2(e){var{header:t,payload:r}=e,n=e.secret||e.privateKey,i=e.encoding,o=Ame(t.alg),s=vme(t,r,i),a=o.sign(s,n);return O0.format("%s.%s",s,a)}function p_(e){var t=e.secret;if(t=t==null?e.privateKey:t,t=t==null?e.key:t,/^hs/i.test(e.header.alg)===!0&&t==null)throw TypeError("secret must be a string or buffer or a KeyObject");var r=new r2(t);this.readable=!0,this.header=e.header,this.encoding=e.encoding,this.secret=this.privateKey=this.key=r,this.payload=new r2(e.payload),this.secret.once("close",function(){if(!this.payload.writable&&this.readable)this.sign()}.bind(this)),this.payload.once("close",function(){if(!this.secret.writable&&this.readable)this.sign()}.bind(this))}O0.inherits(p_,Tme);p_.prototype.sign=function(){try{var t=o2({header:this.header,payload:this.payload.buffer,secret:this.secret.buffer,encoding:this.encoding});return this.emit("done",t),this.emit("data",t),this.emit("end"),this.readable=!1,t}catch(r){this.readable=!1,this.emit("error",r),this.emit("close")}};p_.sign=o2;s2.exports=p_});var y2=A(function(vJe,g2){var u2=tf().Buffer,c2=T0(),kme=x0(),Rme=C("stream"),d2=C0(),Nme=C("util"),xme=/^[a-zA-Z0-9\-_]+?\.[a-zA-Z0-9\-_]+?\.([a-zA-Z0-9\-_]+)?$/;function Cme(e){return Object.prototype.toString.call(e)==="[object Object]"}function Ome(e){if(Cme(e))return e;try{return JSON.parse(e)}catch(t){return}}function l2(e){var t=e.split(".",1)[0];return Ome(u2.from(t,"base64").toString("binary"))}function Ime(e){return e.split(".",2).join(".")}function f2(e){return e.split(".")[2]}function Dme(e,t){t=t||"utf8";var r=e.split(".")[1];return u2.from(r,"base64").toString(t)}function h2(e){return xme.test(e)&&!!l2(e)}function p2(e,t,r){if(!t){var n=Error("Missing algorithm parameter for jws.verify");throw n.code="MISSING_ALGORITHM",n}e=d2(e);var i=f2(e),o=Ime(e),s=kme(t);return s.verify(o,i,r)}function m2(e,t){if(t=t||{},e=d2(e),!h2(e))return null;var r=l2(e);if(!r)return null;var n=Dme(e);if(r.typ==="JWT"||t.json)n=JSON.parse(n,t.encoding);return{header:r,payload:n,signature:f2(e)}}function uf(e){e=e||{};var t=e.secret;if(t=t==null?e.publicKey:t,t=t==null?e.key:t,/^hs/i.test(e.algorithm)===!0&&t==null)throw TypeError("secret must be a string or buffer or a KeyObject");var r=new c2(t);this.readable=!0,this.algorithm=e.algorithm,this.encoding=e.encoding,this.secret=this.publicKey=this.key=r,this.signature=new c2(e.signature),this.secret.once("close",function(){if(!this.signature.writable&&this.readable)this.verify()}.bind(this)),this.signature.once("close",function(){if(!this.secret.writable&&this.readable)this.verify()}.bind(this))}Nme.inherits(uf,Rme);uf.prototype.verify=function(){try{var t=p2(this.signature.buffer,this.algorithm,this.key.buffer),r=m2(this.signature.buffer,this.encoding);return this.emit("done",t,r),this.emit("data",t),this.emit("end"),this.readable=!1,t}catch(n){this.readable=!1,this.emit("error",n),this.emit("close")}};uf.decode=m2;uf.isValid=h2;uf.verify=p2;g2.exports=uf});var I0=A(function(Pme){var w2=a2(),m_=y2(),Ume=["HS256","HS384","HS512","RS256","RS384","RS512","PS256","PS384","PS512","ES256","ES384","ES512"];Pme.ALGORITHMS=Ume;Pme.sign=w2.sign;Pme.verify=m_.verify;Pme.decode=m_.decode;Pme.isValid=m_.isValid;Pme.createSign=function(t){return new w2(t)};Pme.createVerify=function(t){return new m_(t)}});var S2=A(function(E2){Object.defineProperty(E2,"__esModule",{value:!0});E2.buildPayloadForJwsSign=b2;E2.getJwsSign=Hme;var _2=I0(),zme="RS256",Wme="https://oauth2.googleapis.com/token";function b2(e){let t=Math.floor(new Date().getTime()/1000);return{iss:e.iss,scope:e.scope,aud:Wme,exp:t+3600,iat:t,sub:e.sub,...e.additionalClaims}}function Hme(e){let t=b2(e);return _2.sign({header:{alg:zme},payload:t,secret:e.key})}});var v2=A(function(T2){Object.defineProperty(T2,"__esModule",{value:!0});T2.getToken=Yme;var A2=S2(),Kme="https://oauth2.googleapis.com/token",Jme="urn:ietf:params:oauth:grant-type:jwt-bearer",Qme=(e)=>({method:"POST",url:Kme,data:new URLSearchParams({grant_type:Jme,assertion:A2.getJwsSign(e)}),responseType:"json",retryConfig:{httpMethodsToRetry:["POST"]}});async function Yme(e){if(!e.transporter)throw Error("No transporter set.");try{let t=Qme(e);return(await e.transporter.request(t)).data}catch(t){let r=t,n=r.response?.data;if(n?.error)r.message=`${n.error}: ${n.error_description}`;throw r}}});var x2=A(function(R2){Object.defineProperty(R2,"__esModule",{value:!0});R2.ErrorWithCode=void 0;class k2 extends Error{code;constructor(e,t){super(e);this.code=t}}R2.ErrorWithCode=k2});var D0=A(function(M2){Object.defineProperty(M2,"__esModule",{value:!0});M2.getCredentials=Zme;var C2=C("path"),g_=C("fs"),O2=C("util"),_u=x2(),I2=g_.readFile?O2.promisify(g_.readFile):async()=>{throw new _u.ErrorWithCode("use key rather than keyFile.","MISSING_CREDENTIALS")},wu;(function(e){e.JSON=".json",e.DER=".der",e.CRT=".crt",e.PEM=".pem",e.P12=".p12",e.PFX=".pfx"})(wu||(wu={}));class D2{keyFilePath;constructor(e){this.keyFilePath=e}async getCredentials(){let e=await I2(this.keyFilePath,"utf8"),t;try{t=JSON.parse(e)}catch(i){throw Error(`Invalid JSON key file: ${i.message}`)}let r=t.private_key,n=t.client_email;if(!r||!n)throw new _u.ErrorWithCode("private_key and client_email are required.","MISSING_CREDENTIALS");return{privateKey:r,clientEmail:n}}}class U2{keyFilePath;constructor(e){this.keyFilePath=e}async getCredentials(){return{privateKey:await I2(this.keyFilePath,"utf8")}}}class P2{async getCredentials(){throw new _u.ErrorWithCode("*.p12 certificates are not supported after v6.1.2. Consider utilizing *.json format or converting *.p12 to *.pem using the OpenSSL CLI.","UNKNOWN_CERTIFICATE_TYPE")}}class L2{static create(e){switch(C2.extname(e)){case wu.JSON:return new D2(e);case wu.DER:case wu.CRT:case wu.PEM:return new U2(e);case wu.P12:case wu.PFX:return new P2;default:throw new _u.ErrorWithCode("Unknown certificate type. Type is determined based on file extension. Current supported extensions are *.json, and *.pem.","UNKNOWN_CERTIFICATE_TYPE")}}}async function Zme(e){return L2.create(e).getCredentials()}});var z2=A(function($2){Object.defineProperty($2,"__esModule",{value:!0});$2.TokenHandler=void 0;var q2=v2(),B2=D0();class j2{token;tokenExpiresAt;inFlightRequest;tokenOptions;constructor(e){this.tokenOptions=e}async processCredentials(){if(!this.tokenOptions.key&&!this.tokenOptions.keyFile)throw Error("No key or keyFile set.");if(!this.tokenOptions.key&&this.tokenOptions.keyFile){let e=await B2.getCredentials(this.tokenOptions.keyFile);this.tokenOptions.key=e.privateKey,this.tokenOptions.email=e.clientEmail}}isTokenExpiring(){if(!this.token||!this.tokenExpiresAt)return!0;let e=new Date().getTime(),t=this.tokenOptions.eagerRefreshThresholdMillis??0;return this.tokenExpiresAt<=e+t}hasExpired(){let e=new Date().getTime();if(this.token&&this.tokenExpiresAt)return new Date().getTime()>=this.tokenExpiresAt;return!0}async getToken(e){if(await this.processCredentials(),this.inFlightRequest&&!e)return this.inFlightRequest;if(this.token&&!this.isTokenExpiring()&&!e)return this.token;try{this.inFlightRequest=q2.getToken(this.tokenOptions);let t=await this.inFlightRequest;return this.token=t,this.tokenExpiresAt=new Date().getTime()+(t.expires_in??0)*1000,t}finally{this.inFlightRequest=void 0}}}$2.TokenHandler=j2});var H2=A(function(W2){Object.defineProperty(W2,"__esModule",{value:!0});W2.revokeToken=nge;var tge="https://oauth2.googleapis.com/revoke?token=",rge=!0;async function nge(e,t){let r=tge+e;return await t.request({url:r,retry:rge})}});var U0=A(function(J2){Object.defineProperty(J2,"__esModule",{value:!0});J2.GoogleToken=void 0;var V2=to(),y_=z2(),G2=H2();class K2{tokenOptions;tokenHandler;constructor(e){if(this.tokenOptions=e||{},this.tokenOptions.transporter=this.tokenOptions.transporter||{request:(t)=>V2.request(t)},!this.tokenOptions.iss)this.tokenOptions.iss=this.tokenOptions.email;if(typeof this.tokenOptions.scope==="object")this.tokenOptions.scope=this.tokenOptions.scope.join(" ");this.tokenHandler=new y_.TokenHandler(this.tokenOptions)}get expiresAt(){return this.tokenHandler.tokenExpiresAt}get accessToken(){return this.tokenHandler.token?.access_token}get idToken(){return this.tokenHandler.token?.id_token}get tokenType(){return this.tokenHandler.token?.token_type}get refreshToken(){return this.tokenHandler.token?.refresh_token}hasExpired(){return this.tokenHandler.hasExpired()}isTokenExpiring(){return this.tokenHandler.isTokenExpiring()}getToken(e,t={forceRefresh:!1}){let r;if(typeof e==="function")r=e;else if(typeof e==="object")t=e;let n=this.tokenHandler.getToken(t.forceRefresh??!1);if(r)n.then((i)=>r(null,i),r);return n}revokeToken(e){if(!this.accessToken)return Promise.reject(Error("No token to revoke."));let t=G2.revokeToken(this.accessToken,this.tokenOptions.transporter);if(e)t.then(()=>e(),e);this.tokenHandler=new y_.TokenHandler(this.tokenOptions)}get googleTokenOptions(){return this.tokenOptions}}J2.GoogleToken=K2});var L0=A(function(ez){Object.defineProperty(ez,"__esModule",{value:!0});ez.JWTAccess=void 0;var X2=I0(),Z2=Qs(),Y2={alg:"RS256",typ:"JWT"};class P0{email;key;keyId;projectId;eagerRefreshThresholdMillis;cache=new Z2.LRUCache({capacity:500,maxAge:3600000});constructor(e,t,r,n){this.email=e,this.key=t,this.keyId=r,this.eagerRefreshThresholdMillis=n??300000}getCachedKey(e,t){let r=e;if(t&&Array.isArray(t)&&t.length)r=e?`${e}_${t.join("_")}`:`${t.join("_")}`;else if(typeof t==="string")r=e?`${e}_${t}`:t;if(!r)throw Error("Scopes or url must be provided");return r}getRequestHeaders(e,t,r){let n=this.getCachedKey(e,r),i=this.cache.get(n),o=Date.now();if(i&&i.expiration-o>this.eagerRefreshThresholdMillis)return new Headers(i.headers);let s=Math.floor(Date.now()/1000),a=P0.getExpirationTime(s),c;if(Array.isArray(r))r=r.join(" ");if(r)c={iss:this.email,sub:this.email,scope:r,exp:a,iat:s};else c={iss:this.email,sub:this.email,aud:e,exp:a,iat:s};if(t){for(let p in c)if(t[p])throw Error(`The '${p}' property is not allowed when passing additionalClaims. This claim is included in the JWT by default.`)}let u=this.keyId?{...Y2,kid:this.keyId}:Y2,d=Object.assign(c,t),f=X2.sign({header:u,payload:d,secret:this.key}),h=new Headers({authorization:`Bearer ${f}`});return this.cache.set(n,{expiration:a*1000,headers:h}),h}static getExpirationTime(e){return e+3600}fromJSON(e){if(!e)throw Error("Must pass in a JSON object containing the service account auth settings.");if(!e.client_email)throw Error("The incoming JSON object does not contain a client_email field");if(!e.private_key)throw Error("The incoming JSON object does not contain a private_key field");this.email=e.client_email,this.key=e.private_key,this.keyId=e.private_key_id,this.projectId=e.project_id}fromStream(e,t){if(t)this.fromStreamAsync(e).then(()=>t(),t);else return this.fromStreamAsync(e)}fromStreamAsync(e){return new Promise((t,r)=>{if(!e)r(Error("Must pass in a stream containing the service account auth settings."));let n="";e.setEncoding("utf8").on("data",(i)=>n+=i).on("error",r).on("end",()=>{try{let i=JSON.parse(n);this.fromJSON(i),t()}catch(i){r(i)}})})}}ez.JWTAccess=P0});var q0=A(function(oz){Object.defineProperty(oz,"__esModule",{value:!0});oz.JWT=void 0;var w_=U0(),rz=D0(),nz=L0(),iz=yu(),bu=Xo();class M0 extends iz.OAuth2Client{email;keyFile;key;keyId;defaultScopes;scopes;scope;subject;gtoken;additionalClaims;useJWTAccessWithScope;defaultServicePath;access;constructor(e={}){super(e);this.email=e.email,this.keyFile=e.keyFile,this.key=e.key,this.keyId=e.keyId,this.scopes=e.scopes,this.subject=e.subject,this.additionalClaims=e.additionalClaims,this.credentials={refresh_token:"jwt-placeholder",expiry_date:1}}createScoped(e){let t=new M0(this);return t.scopes=e,t}async getRequestMetadataAsync(e){e=this.defaultServicePath?`https://${this.defaultServicePath}/`:e;let t=!this.hasUserScopes()&&e||this.useJWTAccessWithScope&&this.hasAnyScopes()||this.universeDomain!==bu.DEFAULT_UNIVERSE;if(this.subject&&this.universeDomain!==bu.DEFAULT_UNIVERSE)throw RangeError(`Service Account user is configured for the credential. Domain-wide delegation is not supported in universes other than ${bu.DEFAULT_UNIVERSE}`);if(!this.apiKey&&t)if(this.additionalClaims&&this.additionalClaims.target_audience){let{tokens:r}=await this.refreshToken();return{headers:this.addSharedMetadataHeaders(new Headers({authorization:`Bearer ${r.id_token}`}))}}else{if(!this.access)this.access=new nz.JWTAccess(this.email,this.key,this.keyId,this.eagerRefreshThresholdMillis);let r;if(this.hasUserScopes())r=this.scopes;else if(!e)r=this.defaultScopes;let n=this.useJWTAccessWithScope||this.universeDomain!==bu.DEFAULT_UNIVERSE,i=await this.access.getRequestHeaders(e??void 0,this.additionalClaims,n?r:void 0);return{headers:this.addSharedMetadataHeaders(i)}}else if(this.hasAnyScopes()||this.apiKey)return super.getRequestMetadataAsync(e);else return{headers:new Headers}}async fetchIdToken(e){let t=new w_.GoogleToken({iss:this.email,sub:this.subject,scope:this.scopes||this.defaultScopes,keyFile:this.keyFile,key:this.key,additionalClaims:{target_audience:e},transporter:this.transporter});if(await t.getToken({forceRefresh:!0}),!t.idToken)throw Error("Unknown error: Failed to fetch ID token");return t.idToken}hasUserScopes(){if(!this.scopes)return!1;return this.scopes.length>0}hasAnyScopes(){if(this.scopes&&this.scopes.length>0)return!0;if(this.defaultScopes&&this.defaultScopes.length>0)return!0;return!1}authorize(e){if(e)this.authorizeAsync().then((t)=>e(null,t),e);else return this.authorizeAsync()}async authorizeAsync(){let e=await this.refreshToken();if(!e)throw Error("No result returned");return this.credentials=e.tokens,this.credentials.refresh_token="jwt-placeholder",this.key=this.gtoken.googleTokenOptions?.key,this.email=this.gtoken.googleTokenOptions?.iss,e.tokens}async refreshTokenNoCache(){let e=this.createGToken(),r={access_token:(await e.getToken({forceRefresh:this.isTokenExpiring()})).access_token,token_type:"Bearer",expiry_date:e.expiresAt,id_token:e.idToken};return this.emit("tokens",r),{res:null,tokens:r}}createGToken(){if(!this.gtoken)this.gtoken=new w_.GoogleToken({iss:this.email,sub:this.subject,scope:this.scopes||this.defaultScopes,keyFile:this.keyFile,key:this.key,additionalClaims:this.additionalClaims,transporter:this.transporter});return this.gtoken}fromJSON(e){if(!e)throw Error("Must pass in a JSON object containing the service account auth settings.");if(!e.client_email)throw Error("The incoming JSON object does not contain a client_email field");if(!e.private_key)throw Error("The incoming JSON object does not contain a private_key field");this.email=e.client_email,this.key=e.private_key,this.keyId=e.private_key_id,this.projectId=e.project_id,this.quotaProjectId=e.quota_project_id,this.universeDomain=e.universe_domain||this.universeDomain}fromStream(e,t){if(t)this.fromStreamAsync(e).then(()=>t(),t);else return this.fromStreamAsync(e)}fromStreamAsync(e){return new Promise((t,r)=>{if(!e)throw Error("Must pass in a stream containing the service account auth settings.");let n="";e.setEncoding("utf8").on("error",r).on("data",(i)=>n+=i).on("end",()=>{try{let i=JSON.parse(n);this.fromJSON(i),t()}catch(i){r(i)}})})}fromAPIKey(e){if(typeof e!=="string")throw Error("Must provide an API Key string.");this.apiKey=e}async getCredentials(){if(this.key)return{private_key:this.key,client_email:this.email};else if(this.keyFile){let e=this.createGToken(),t=await rz.getCredentials(this.keyFile);return{private_key:t.privateKey,client_email:t.clientEmail}}throw Error("A key or a keyFile must be provided to getCredentials.")}}oz.JWT=M0});var B0=A(function(uz){Object.defineProperty(uz,"__esModule",{value:!0});uz.UserRefreshClient=uz.USER_REFRESH_ACCOUNT_TYPE=void 0;var az=yu(),cz=Xo();uz.USER_REFRESH_ACCOUNT_TYPE="authorized_user";class __ extends az.OAuth2Client{_refreshToken;constructor(e,t,r,n,i){let o=e&&typeof e==="object"?e:{clientId:e,clientSecret:t,refreshToken:r,eagerRefreshThresholdMillis:n,forceRefreshOnFailure:i};super(o);this._refreshToken=o.refreshToken,this.credentials.refresh_token=o.refreshToken}async refreshTokenNoCache(){return super.refreshTokenNoCache(this._refreshToken)}async fetchIdToken(e){let t={...__.RETRY_CONFIG,url:this.endpoints.oauth2TokenUrl,method:"POST",data:new URLSearchParams({client_id:this._clientId,client_secret:this._clientSecret,grant_type:"refresh_token",refresh_token:this._refreshToken,target_audience:e}),responseType:"json"};return cz.AuthClient.setMethodName(t,"fetchIdToken"),(await this.transporter.request(t)).data.id_token}fromJSON(e){if(!e)throw Error("Must pass in a JSON object containing the user refresh token");if(e.type!=="authorized_user")throw Error('The incoming JSON object does not have the "authorized_user" type');if(!e.client_id)throw Error("The incoming JSON object does not contain a client_id field");if(!e.client_secret)throw Error("The incoming JSON object does not contain a client_secret field");if(!e.refresh_token)throw Error("The incoming JSON object does not contain a refresh_token field");this._clientId=e.client_id,this._clientSecret=e.client_secret,this._refreshToken=e.refresh_token,this.credentials.refresh_token=e.refresh_token,this.quotaProjectId=e.quota_project_id,this.universeDomain=e.universe_domain||this.universeDomain}fromStream(e,t){if(t)this.fromStreamAsync(e).then(()=>t(),t);else return this.fromStreamAsync(e)}async fromStreamAsync(e){return new Promise((t,r)=>{if(!e)return r(Error("Must pass in a stream containing the user refresh token."));let n="";e.setEncoding("utf8").on("error",r).on("data",(i)=>n+=i).on("end",()=>{try{let i=JSON.parse(n);return this.fromJSON(i),t()}catch(i){return r(i)}})})}static fromJSON(e){let t=new __;return t.fromJSON(e),t}}uz.UserRefreshClient=__});var j0=A(function(hz){Object.defineProperty(hz,"__esModule",{value:!0});hz.Impersonated=hz.IMPERSONATED_ACCOUNT_TYPE=void 0;var b_=yu(),lz=to(),fz=Qs();hz.IMPERSONATED_ACCOUNT_TYPE="impersonated_service_account";class Qp extends b_.OAuth2Client{sourceClient;targetPrincipal;targetScopes;delegates;lifetime;endpoint;constructor(e={}){super(e);if(this.credentials={expiry_date:1,refresh_token:"impersonated-placeholder"},this.sourceClient=e.sourceClient??new b_.OAuth2Client,this.targetPrincipal=e.targetPrincipal??"",this.delegates=e.delegates??[],this.targetScopes=e.targetScopes??[],this.lifetime=e.lifetime??3600,!fz.originalOrCamelOptions(e).get("universe_domain"))this.universeDomain=this.sourceClient.universeDomain;else if(this.sourceClient.universeDomain!==this.universeDomain)throw RangeError(`Universe domain ${this.sourceClient.universeDomain} in source credentials does not match ${this.universeDomain} universe domain set for impersonated credentials.`);this.endpoint=e.endpoint??`https://iamcredentials.${this.universeDomain}`}async sign(e){await this.sourceClient.getAccessToken();let t=`projects/-/serviceAccounts/${this.targetPrincipal}`,r=`${this.endpoint}/v1/${t}:signBlob`,n={delegates:this.delegates,payload:Buffer.from(e).toString("base64")};return(await this.sourceClient.request({...Qp.RETRY_CONFIG,url:r,data:n,method:"POST"})).data}getTargetPrincipal(){return this.targetPrincipal}async refreshToken(){try{await this.sourceClient.getAccessToken();let e="projects/-/serviceAccounts/"+this.targetPrincipal,t=`${this.endpoint}/v1/${e}:generateAccessToken`,r={delegates:this.delegates,scope:this.targetScopes,lifetime:this.lifetime+"s"},n=await this.sourceClient.request({...Qp.RETRY_CONFIG,url:t,data:r,method:"POST"}),i=n.data;return this.credentials.access_token=i.accessToken,this.credentials.expiry_date=Date.parse(i.expireTime),{tokens:this.credentials,res:n}}catch(e){if(!(e instanceof Error))throw e;let t=0,r="";if(e instanceof lz.GaxiosError)t=e?.response?.data?.error?.status,r=e?.response?.data?.error?.message;if(t&&r)throw e.message=`${t}: unable to impersonate: ${r}`,e;else throw e.message=`unable to impersonate: ${e}`,e}}async fetchIdToken(e,t){await this.sourceClient.getAccessToken();let r=`projects/-/serviceAccounts/${this.targetPrincipal}`,n=`${this.endpoint}/v1/${r}:generateIdToken`,i={delegates:this.delegates,audience:e,includeEmail:t?.includeEmail??!0,useEmailAzp:t?.includeEmail??!0};return(await this.sourceClient.request({...Qp.RETRY_CONFIG,url:n,data:i,method:"POST"})).data.token}}hz.Impersonated=Qp});var $0=A(function(yz){Object.defineProperty(yz,"__esModule",{value:!0});yz.OAuthClientAuthHandler=void 0;yz.getErrorFromOAuthErrorResponse=cge;var Es=to(),mz=Fp(),age=["PUT","POST","PATCH"];class gz{#e=mz.createCrypto();#t;transporter;constructor(e){if(e&&"clientId"in e)this.#t=e,this.transporter=new Es.Gaxios;else this.#t=e?.clientAuthentication,this.transporter=e?.transporter||new Es.Gaxios}applyClientAuthenticationOptions(e,t){if(e.headers=Es.Gaxios.mergeHeaders(e.headers),this.injectAuthenticatedHeaders(e,t),!t)this.injectAuthenticatedRequestBody(e)}injectAuthenticatedHeaders(e,t){if(t)e.headers=Es.Gaxios.mergeHeaders(e.headers,{authorization:`Bearer ${t}`});else if(this.#t?.confidentialClientType==="basic"){e.headers=Es.Gaxios.mergeHeaders(e.headers);let r=this.#t.clientId,n=this.#t.clientSecret||"",i=this.#e.encodeBase64StringUtf8(`${r}:${n}`);Es.Gaxios.mergeHeaders(e.headers,{authorization:`Basic ${i}`})}}injectAuthenticatedRequestBody(e){if(this.#t?.confidentialClientType==="request-body"){let t=(e.method||"GET").toUpperCase();if(!age.includes(t))throw Error(`${t} HTTP method does not support ${this.#t.confidentialClientType} client authentication`);let n=new Headers(e.headers).get("content-type");if(n?.startsWith("application/x-www-form-urlencoded")||e.data instanceof URLSearchParams){let i=new URLSearchParams(e.data??"");i.append("client_id",this.#t.clientId),i.append("client_secret",this.#t.clientSecret||""),e.data=i}else if(n?.startsWith("application/json"))e.data=e.data||{},Object.assign(e.data,{client_id:this.#t.clientId,client_secret:this.#t.clientSecret||""});else throw Error(`${n} content-types are not supported with ${this.#t.confidentialClientType} client authentication`)}}static get RETRY_CONFIG(){return{retry:!0,retryConfig:{httpMethodsToRetry:["GET","PUT","POST","HEAD","OPTIONS","DELETE"]}}}}yz.OAuthClientAuthHandler=gz;function cge(e,t){let{error:r,error_description:n,error_uri:i}=e,o=`Error code ${r}`;if(typeof n<"u")o+=`: ${n}`;if(typeof i<"u")o+=` - ${i}`;let s=Error(o);if(t){let a=Object.keys(t);if(t.stack)a.push("stack");a.forEach((c)=>{if(c!=="message")Object.defineProperty(s,c,{value:t[c],writable:!1,enumerable:!0})})}return s}});var S_=A(function(Sz){Object.defineProperty(Sz,"__esModule",{value:!0});Sz.StsCredentials=void 0;var _z=to(),bz=Xo(),E_=$0(),Ez=Qs();class F0 extends E_.OAuthClientAuthHandler{#e;constructor(e={tokenExchangeEndpoint:""},t){if(typeof e!=="object"||e instanceof URL)e={tokenExchangeEndpoint:e,clientAuthentication:t};super(e);this.#e=e.tokenExchangeEndpoint}async exchangeToken(e,t,r){let n={grant_type:e.grantType,resource:e.resource,audience:e.audience,scope:e.scope?.join(" "),requested_token_type:e.requestedTokenType,subject_token:e.subjectToken,subject_token_type:e.subjectTokenType,actor_token:e.actingParty?.actorToken,actor_token_type:e.actingParty?.actorTokenType,options:r&&JSON.stringify(r)},i={...F0.RETRY_CONFIG,url:this.#e.toString(),method:"POST",headers:t,data:new URLSearchParams(Ez.removeUndefinedValuesInObject(n)),responseType:"json"};bz.AuthClient.setMethodName(i,"exchangeToken"),this.applyClientAuthenticationOptions(i);try{let o=await this.transporter.request(i),s=o.data;return s.res=o,s}catch(o){if(o instanceof _z.GaxiosError&&o.response)throw E_.getErrorFromOAuthErrorResponse(o.response.data,o);throw o}}}Sz.StsCredentials=F0});var Eu=A(function(Nz){Object.defineProperty(Nz,"__esModule",{value:!0});Nz.BaseExternalAccountClient=Nz.CLOUD_RESOURCE_MANAGER=Nz.EXTERNAL_ACCOUNT_TYPE=Nz.EXPIRATION_TIME_OFFSET=void 0;var Tz=to(),vz=C("stream"),df=Xo(),kz=S_(),A_=Qs(),Rz=w0(),dge="urn:ietf:params:oauth:grant-type:token-exchange",lge="urn:ietf:params:oauth:token-type:access_token",z0="https://www.googleapis.com/auth/cloud-platform",fge=3600;Nz.EXPIRATION_TIME_OFFSET=300000;Nz.EXTERNAL_ACCOUNT_TYPE="external_account";Nz.CLOUD_RESOURCE_MANAGER="https://cloudresourcemanager.googleapis.com/v1/projects/";var hge="//iam\\.googleapis\\.com/locations/[^/]+/workforcePools/[^/]+/providers/.+",pge="https://sts.{universeDomain}/v1/token";class T_ extends df.AuthClient{scopes;projectNumber;audience;subjectTokenType;stsCredential;clientAuth;credentialSourceType;cachedAccessToken;serviceAccountImpersonationUrl;serviceAccountImpersonationLifetime;workforcePoolUserProject;configLifetimeRequested;tokenUrl;cloudResourceManagerURL;supplierContext;#e=null;constructor(e){super(e);let t=A_.originalOrCamelOptions(e),r=t.get("type");if(r&&r!==Nz.EXTERNAL_ACCOUNT_TYPE)throw Error(`Expected "${Nz.EXTERNAL_ACCOUNT_TYPE}" type but received "${e.type}"`);let n=t.get("client_id"),i=t.get("client_secret");this.tokenUrl=t.get("token_url")??pge.replace("{universeDomain}",this.universeDomain);let o=t.get("subject_token_type"),s=t.get("workforce_pool_user_project"),a=t.get("service_account_impersonation_url"),c=t.get("service_account_impersonation"),u=A_.originalOrCamelOptions(c).get("token_lifetime_seconds");if(this.cloudResourceManagerURL=new URL(t.get("cloud_resource_manager_url")||`https://cloudresourcemanager.${this.universeDomain}/v1/projects/`),n)this.clientAuth={confidentialClientType:"basic",clientId:n,clientSecret:i};this.stsCredential=new kz.StsCredentials({tokenExchangeEndpoint:this.tokenUrl,clientAuthentication:this.clientAuth}),this.scopes=t.get("scopes")||[z0],this.cachedAccessToken=null,this.audience=t.get("audience"),this.subjectTokenType=o,this.workforcePoolUserProject=s;let d=new RegExp(hge);if(this.workforcePoolUserProject&&!this.audience.match(d))throw Error("workforcePoolUserProject should not be set for non-workforce pool credentials.");if(this.serviceAccountImpersonationUrl=a,this.serviceAccountImpersonationLifetime=u,this.serviceAccountImpersonationLifetime)this.configLifetimeRequested=!0;else this.configLifetimeRequested=!1,this.serviceAccountImpersonationLifetime=fge;this.projectNumber=this.getProjectNumber(this.audience),this.supplierContext={audience:this.audience,subjectTokenType:this.subjectTokenType,transporter:this.transporter}}getServiceAccountEmail(){if(this.serviceAccountImpersonationUrl){if(this.serviceAccountImpersonationUrl.length>256)throw RangeError(`URL is too long: ${this.serviceAccountImpersonationUrl}`);return/serviceAccounts\/(?<email>[^:]+):generateAccessToken$/.exec(this.serviceAccountImpersonationUrl)?.groups?.email||null}return null}setCredentials(e){super.setCredentials(e),this.cachedAccessToken=e}async getAccessToken(){if(!this.cachedAccessToken||this.isExpired(this.cachedAccessToken))await this.refreshAccessTokenAsync();return{token:this.cachedAccessToken.access_token,res:this.cachedAccessToken.res}}async getRequestHeaders(){let e=await this.getAccessToken(),t=new Headers({authorization:`Bearer ${e.token}`});return this.addSharedMetadataHeaders(t)}request(e,t){if(t)this.requestAsync(e).then((r)=>t(null,r),(r)=>t(r,r.response));else return this.requestAsync(e)}async getProjectId(){let e=this.projectNumber||this.workforcePoolUserProject;if(this.projectId)return this.projectId;else if(e){let t=await this.getRequestHeaders(),r={...T_.RETRY_CONFIG,headers:t,url:`${this.cloudResourceManagerURL.toString()}${e}`,responseType:"json"};df.AuthClient.setMethodName(r,"getProjectId");let n=await this.transporter.request(r);return this.projectId=n.data.projectId,this.projectId}return null}async requestAsync(e,t=!1){let r;try{let n=await this.getRequestHeaders();e.headers=Tz.Gaxios.mergeHeaders(e.headers),this.addUserProjectAndAuthHeaders(e.headers,n),r=await this.transporter.request(e)}catch(n){let i=n.response;if(i){let o=i.status,s=i.config.data instanceof vz.Readable;if(!t&&(o===401||o===403)&&!s&&this.forceRefreshOnFailure)return await this.refreshAccessTokenAsync(),await this.requestAsync(e,!0)}throw n}return r}async refreshAccessTokenAsync(){this.#e=this.#e||this.#t();try{return await this.#e}finally{this.#e=null}}async#t(){let e=await this.retrieveSubjectToken(),t={grantType:dge,audience:this.audience,requestedTokenType:lge,subjectToken:e,subjectTokenType:this.subjectTokenType,scope:this.serviceAccountImpersonationUrl?[z0]:this.getScopesArray()},r=!this.clientAuth&&this.workforcePoolUserProject?{userProject:this.workforcePoolUserProject}:void 0,n=new Headers({"x-goog-api-client":this.getMetricsHeaderValue()}),i=await this.stsCredential.exchangeToken(t,n,r);if(this.serviceAccountImpersonationUrl)this.cachedAccessToken=await this.getImpersonatedAccessToken(i.access_token);else if(i.expires_in)this.cachedAccessToken={access_token:i.access_token,expiry_date:new Date().getTime()+i.expires_in*1000,res:i.res};else this.cachedAccessToken={access_token:i.access_token,res:i.res};return this.credentials={},Object.assign(this.credentials,this.cachedAccessToken),delete this.credentials.res,this.emit("tokens",{refresh_token:null,expiry_date:this.cachedAccessToken.expiry_date,access_token:this.cachedAccessToken.access_token,token_type:"Bearer",id_token:null}),this.cachedAccessToken}getProjectNumber(e){let t=e.match(/\/projects\/([^/]+)/);if(!t)return null;return t[1]}async getImpersonatedAccessToken(e){let t={...T_.RETRY_CONFIG,url:this.serviceAccountImpersonationUrl,method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${e}`},data:{scope:this.getScopesArray(),lifetime:this.serviceAccountImpersonationLifetime+"s"},responseType:"json"};df.AuthClient.setMethodName(t,"getImpersonatedAccessToken");let r=await this.transporter.request(t),n=r.data;return{access_token:n.accessToken,expiry_date:new Date(n.expireTime).getTime(),res:r}}isExpired(e){let t=new Date().getTime();return e.expiry_date?t>=e.expiry_date-this.eagerRefreshThresholdMillis:!1}getScopesArray(){if(typeof this.scopes==="string")return[this.scopes];return this.scopes||[z0]}getMetricsHeaderValue(){let e=process.version.replace(/^v/,""),t=this.serviceAccountImpersonationUrl!==void 0,r=this.credentialSourceType?this.credentialSourceType:"unknown";return`gl-node/${e} auth/${Rz.pkg.version} google-byoid-sdk source/${r} sa-impersonation/${t} config-lifetime/${this.configLifetimeRequested}`}getTokenUrl(){return this.tokenUrl}}Nz.BaseExternalAccountClient=T_});var Dz=A(function(Oz){Object.defineProperty(Oz,"__esModule",{value:!0});Oz.FileSubjectTokenSupplier=void 0;var lf=C("util"),ff=C("fs"),yge=lf.promisify(ff.readFile??(()=>{})),wge=lf.promisify(ff.realpath??(()=>{})),_ge=lf.promisify(ff.lstat??(()=>{}));class Cz{filePath;formatType;subjectTokenFieldName;constructor(e){this.filePath=e.filePath,this.formatType=e.formatType,this.subjectTokenFieldName=e.subjectTokenFieldName}async getSubjectToken(){let e=this.filePath;try{if(e=await wge(e),!(await _ge(e)).isFile())throw Error()}catch(n){if(n instanceof Error)n.message=`The file at ${e} does not exist, or it is not a file. ${n.message}`;throw n}let t,r=await yge(e,{encoding:"utf8"});if(this.formatType==="text")t=r;else if(this.formatType==="json"&&this.subjectTokenFieldName)t=JSON.parse(r)[this.subjectTokenFieldName];if(!t)throw Error("Unable to parse the subject_token from the credential_source file");return t}}Oz.FileSubjectTokenSupplier=Cz});var qz=A(function(Lz){Object.defineProperty(Lz,"__esModule",{value:!0});Lz.UrlSubjectTokenSupplier=void 0;var Uz=Xo();class Pz{url;headers;formatType;subjectTokenFieldName;additionalGaxiosOptions;constructor(e){this.url=e.url,this.formatType=e.formatType,this.subjectTokenFieldName=e.subjectTokenFieldName,this.headers=e.headers,this.additionalGaxiosOptions=e.additionalGaxiosOptions}async getSubjectToken(e){let t={...this.additionalGaxiosOptions,url:this.url,method:"GET",headers:this.headers,responseType:this.formatType};Uz.AuthClient.setMethodName(t,"getSubjectToken");let r;if(this.formatType==="text")r=(await e.transporter.request(t)).data;else if(this.formatType==="json"&&this.subjectTokenFieldName)r=(await e.transporter.request(t)).data[this.subjectTokenFieldName];if(!r)throw Error("Unable to parse the subject_token from the credential_source URL");return r}}Lz.UrlSubjectTokenSupplier=Pz});var zz=A(function($z){Object.defineProperty($z,"__esModule",{value:!0});$z.CertificateSubjectTokenSupplier=$z.InvalidConfigurationError=$z.CertificateSourceUnavailableError=$z.CERTIFICATE_CONFIGURATION_ENV_VARIABLE=void 0;var Su=Qs(),Au=C("fs"),Tu=C("crypto"),Bz=C("https");$z.CERTIFICATE_CONFIGURATION_ENV_VARIABLE="GOOGLE_API_CERTIFICATE_CONFIG";class mc extends Error{constructor(e){super(e);this.name="CertificateSourceUnavailableError"}}$z.CertificateSourceUnavailableError=mc;class Zs extends Error{constructor(e){super(e);this.name="InvalidConfigurationError"}}$z.InvalidConfigurationError=Zs;class jz{certificateConfigPath;trustChainPath;cert;key;constructor(e){if(!e.useDefaultCertificateConfig&&!e.certificateConfigLocation)throw new Zs("Either `useDefaultCertificateConfig` must be true or a `certificateConfigLocation` must be provided.");if(e.useDefaultCertificateConfig&&e.certificateConfigLocation)throw new Zs("Both `useDefaultCertificateConfig` and `certificateConfigLocation` cannot be provided.");this.trustChainPath=e.trustChainPath,this.certificateConfigPath=e.certificateConfigLocation??""}async createMtlsHttpsAgent(){if(!this.key||!this.cert)throw new Zs("Cannot create mTLS Agent with missing certificate or key");return new Bz.Agent({key:this.key,cert:this.cert})}async getSubjectToken(){this.certificateConfigPath=await this.#e();let{certPath:e,keyPath:t}=await this.#t();return{cert:this.cert,key:this.key}=await this.#r(e,t),await this.#n(this.cert)}async#e(){let e=this.certificateConfigPath;if(e){if(await Su.isValidFile(e))return e;throw new mc(`Provided certificate config path is invalid: ${e}`)}let t=process.env[$z.CERTIFICATE_CONFIGURATION_ENV_VARIABLE];if(t){if(await Su.isValidFile(t))return t;throw new mc(`Path from environment variable "${$z.CERTIFICATE_CONFIGURATION_ENV_VARIABLE}" is invalid: ${t}`)}let r=Su.getWellKnownCertificateConfigFileLocation();if(await Su.isValidFile(r))return r;throw new mc(`Could not find certificate configuration file. Searched override path, the "${$z.CERTIFICATE_CONFIGURATION_ENV_VARIABLE}" env var, and the gcloud path (${r}).`)}async#t(){let e=this.certificateConfigPath,t;try{t=await Au.promises.readFile(e,"utf8")}catch(r){throw new mc(`Failed to read certificate config file at: ${e}`)}try{let r=JSON.parse(t),n=r?.cert_configs?.workload?.cert_path,i=r?.cert_configs?.workload?.key_path;if(!n||!i)throw new Zs(`Certificate config file (${e}) is missing required "cert_path" or "key_path" in the workload config.`);return{certPath:n,keyPath:i}}catch(r){if(r instanceof Zs)throw r;throw new Zs(`Failed to parse certificate config from ${e}: ${r.message}`)}}async#r(e,t){let r,n;try{r=await Au.promises.readFile(e),new Tu.X509Certificate(r)}catch(i){let o=i instanceof Error?i.message:String(i);throw new mc(`Failed to read certificate file at ${e}: ${o}`)}try{n=await Au.promises.readFile(t),Tu.createPrivateKey(n)}catch(i){let o=i instanceof Error?i.message:String(i);throw new mc(`Failed to read private key file at ${t}: ${o}`)}return{cert:r,key:n}}async#n(e){let t=new Tu.X509Certificate(e);if(!this.trustChainPath)return JSON.stringify([t.raw.toString("base64")]);try{let i=((await Au.promises.readFile(this.trustChainPath,"utf8")).match(/-----BEGIN CERTIFICATE-----[^-]+-----END CERTIFICATE-----/g)??[]).map((a,c)=>{try{return new Tu.X509Certificate(a)}catch(u){let d=u instanceof Error?u.message:String(u);throw new Zs(`Failed to parse certificate at index ${c} in trust chain file ${this.trustChainPath}: ${d}`)}}),o=i.findIndex((a)=>t.raw.equals(a.raw)),s;if(o===-1)s=[t,...i];else if(o===0)s=i;else throw new Zs(`Leaf certificate exists in the trust chain but is not the first entry (found at index ${o}).`);return JSON.stringify(s.map((a)=>a.raw.toString("base64")))}catch(r){if(r instanceof Zs)throw r;let n=r instanceof Error?r.message:String(r);throw new mc(`Failed to process certificate chain from ${this.trustChainPath}: ${n}`)}}}$z.CertificateSubjectTokenSupplier=jz});var V0=A(function(Kz){Object.defineProperty(Kz,"__esModule",{value:!0});Kz.IdentityPoolClient=void 0;var Wz=Eu(),hf=Qs(),Hz=Dz(),Vz=qz(),k_=zz(),Gz=S_(),R_=to();class H0 extends Wz.BaseExternalAccountClient{subjectTokenSupplier;constructor(e){super(e);let t=hf.originalOrCamelOptions(e),r=t.get("credential_source"),n=t.get("subject_token_supplier");if(!r&&!n)throw Error("A credential source or subject token supplier must be specified.");if(r&&n)throw Error("Only one of credential source or subject token supplier can be specified.");if(n)this.subjectTokenSupplier=n,this.credentialSourceType="programmatic";else{let i=hf.originalOrCamelOptions(r),o=hf.originalOrCamelOptions(i.get("format")),s=o.get("type")||"text",a=o.get("subject_token_field_name");if(s!=="json"&&s!=="text")throw Error(`Invalid credential_source format "${s}"`);if(s==="json"&&!a)throw Error("Missing subject_token_field_name for JSON credential_source format");let c=i.get("file"),u=i.get("url"),d=i.get("certificate"),f=i.get("headers");if(c&&u||u&&d||c&&d)throw Error('No valid Identity Pool "credential_source" provided, must be either file, url, or certificate.');else if(c)this.credentialSourceType="file",this.subjectTokenSupplier=new Hz.FileSubjectTokenSupplier({filePath:c,formatType:s,subjectTokenFieldName:a});else if(u)this.credentialSourceType="url",this.subjectTokenSupplier=new Vz.UrlSubjectTokenSupplier({url:u,formatType:s,subjectTokenFieldName:a,headers:f,additionalGaxiosOptions:H0.RETRY_CONFIG});else if(d){this.credentialSourceType="certificate";let h=new k_.CertificateSubjectTokenSupplier({useDefaultCertificateConfig:d.use_default_certificate_config,certificateConfigLocation:d.certificate_config_location,trustChainPath:d.trust_chain_path});this.subjectTokenSupplier=h}else throw Error('No valid Identity Pool "credential_source" provided, must be either file, url, or certificate.')}}async retrieveSubjectToken(){let e=await this.subjectTokenSupplier.getSubjectToken(this.supplierContext);if(this.subjectTokenSupplier instanceof k_.CertificateSubjectTokenSupplier){let t=await this.subjectTokenSupplier.createMtlsHttpsAgent();this.stsCredential=new Gz.StsCredentials({tokenExchangeEndpoint:this.getTokenUrl(),clientAuthentication:this.clientAuth,transporter:new R_.Gaxios({agent:t})}),this.transporter=new R_.Gaxios({...this.transporter.defaults||{},agent:t})}return e}}Kz.IdentityPoolClient=H0});var G0=A(function(Xz){Object.defineProperty(Xz,"__esModule",{value:!0});Xz.AwsRequestSigner=void 0;var vu=to(),N_=Fp(),Qz="AWS4-HMAC-SHA256",Sge="aws4_request";class Yz{getCredentials;region;crypto;constructor(e,t){this.getCredentials=e,this.region=t,this.crypto=N_.createCrypto()}async getRequestOptions(e){if(!e.url)throw RangeError('"url" is required in "amzOptions"');let t=typeof e.data==="object"?JSON.stringify(e.data):e.data,r=e.url,n=e.method||"GET",i=e.body||t,o=e.headers,s=await this.getCredentials(),a=new URL(r);if(typeof i!=="string"&&i!==void 0)throw TypeError(`'requestPayload' is expected to be a string if provided. Got: ${i}`);let c=await Tge({crypto:this.crypto,host:a.host,canonicalUri:a.pathname,canonicalQuerystring:a.search.slice(1),method:n,region:this.region,securityCredentials:s,requestPayload:i,additionalAmzHeaders:o}),u=vu.Gaxios.mergeHeaders(c.amzDate?{"x-amz-date":c.amzDate}:{},{authorization:c.authorizationHeader,host:a.host},o||{});if(s.token)vu.Gaxios.mergeHeaders(u,{"x-amz-security-token":s.token});let d={url:r,method:n,headers:u};if(i!==void 0)d.body=i;return d}}Xz.AwsRequestSigner=Yz;async function Yp(e,t,r){return await e.signWithHmacSha256(t,r)}async function Age(e,t,r,n,i){let o=await Yp(e,`AWS4${t}`,r),s=await Yp(e,o,n),a=await Yp(e,s,i);return await Yp(e,a,"aws4_request")}async function Tge(e){let t=vu.Gaxios.mergeHeaders(e.additionalAmzHeaders),r=e.requestPayload||"",n=e.host.split(".")[0],i=new Date,o=i.toISOString().replace(/[-:]/g,"").replace(/\.[0-9]+/,""),s=i.toISOString().replace(/[-]/g,"").replace(/T.*/,"");if(e.securityCredentials.token)t.set("x-amz-security-token",e.securityCredentials.token);let a=vu.Gaxios.mergeHeaders({host:e.host},t.has("date")?{}:{"x-amz-date":o},t),c="",u=[...a.keys()].sort();u.forEach((I)=>{c+=`${I}:${a.get(I)}
59
+ `});let d=u.join(";"),f=await e.crypto.sha256DigestHex(r),h=`${e.method.toUpperCase()}
60
+ ${e.canonicalUri}
61
+ ${e.canonicalQuerystring}
62
+ ${c}
63
+ ${d}
64
+ ${f}`,p=`${s}/${e.region}/${n}/${Sge}`,g=`${Qz}
65
+ ${o}
66
+ ${p}
67
+ `+await e.crypto.sha256DigestHex(h),_=await Age(e.crypto,e.securityCredentials.secretAccessKey,s,e.region,n),R=await Yp(e.crypto,_,g),O=`${Qz} Credential=${e.securityCredentials.accessKeyId}/${p}, SignedHeaders=${d}, Signature=${N_.fromArrayBufferToHex(R)}`;return{amzDate:t.has("date")?void 0:o,authorizationHeader:O,canonicalQuerystring:e.canonicalQuerystring}}});var nW=A(function(tW){Object.defineProperty(tW,"__esModule",{value:!0});tW.DefaultAwsSecurityCredentialsSupplier=void 0;var ku=Xo();class eW{regionUrl;securityCredentialsUrl;imdsV2SessionTokenUrl;additionalGaxiosOptions;constructor(e){this.regionUrl=e.regionUrl,this.securityCredentialsUrl=e.securityCredentialsUrl,this.imdsV2SessionTokenUrl=e.imdsV2SessionTokenUrl,this.additionalGaxiosOptions=e.additionalGaxiosOptions}async getAwsRegion(e){if(this.#n)return this.#n;let t=new Headers;if(!this.#n&&this.imdsV2SessionTokenUrl)t.set("x-aws-ec2-metadata-token",await this.#e(e.transporter));if(!this.regionUrl)throw RangeError('Unable to determine AWS region due to missing "options.credential_source.region_url"');let r={...this.additionalGaxiosOptions,url:this.regionUrl,method:"GET",responseType:"text",headers:t};ku.AuthClient.setMethodName(r,"getAwsRegion");let n=await e.transporter.request(r);return n.data.substr(0,n.data.length-1)}async getAwsSecurityCredentials(e){if(this.#i)return this.#i;let t=new Headers;if(this.imdsV2SessionTokenUrl)t.set("x-aws-ec2-metadata-token",await this.#e(e.transporter));let r=await this.#t(t,e.transporter),n=await this.#r(r,t,e.transporter);return{accessKeyId:n.AccessKeyId,secretAccessKey:n.SecretAccessKey,token:n.Token}}async#e(e){let t={...this.additionalGaxiosOptions,url:this.imdsV2SessionTokenUrl,method:"PUT",responseType:"text",headers:{"x-aws-ec2-metadata-token-ttl-seconds":"300"}};return ku.AuthClient.setMethodName(t,"#getImdsV2SessionToken"),(await e.request(t)).data}async#t(e,t){if(!this.securityCredentialsUrl)throw Error('Unable to determine AWS role name due to missing "options.credential_source.url"');let r={...this.additionalGaxiosOptions,url:this.securityCredentialsUrl,method:"GET",responseType:"text",headers:e};return ku.AuthClient.setMethodName(r,"#getAwsRoleName"),(await t.request(r)).data}async#r(e,t,r){let n={...this.additionalGaxiosOptions,url:`${this.securityCredentialsUrl}/${e}`,headers:t,responseType:"json"};return ku.AuthClient.setMethodName(n,"#retrieveAwsSecurityCredentials"),(await r.request(n)).data}get#n(){return process.env.AWS_REGION||process.env.AWS_DEFAULT_REGION||null}get#i(){if(process.env.AWS_ACCESS_KEY_ID&&process.env.AWS_SECRET_ACCESS_KEY)return{accessKeyId:process.env.AWS_ACCESS_KEY_ID,secretAccessKey:process.env.AWS_SECRET_ACCESS_KEY,token:process.env.AWS_SESSION_TOKEN};return null}}tW.DefaultAwsSecurityCredentialsSupplier=eW});var K0=A(function(cW){Object.defineProperty(cW,"__esModule",{value:!0});cW.AwsClient=void 0;var iW=G0(),oW=Eu(),sW=nW(),x_=Qs(),aW=to();class C_ extends oW.BaseExternalAccountClient{environmentId;awsSecurityCredentialsSupplier;regionalCredVerificationUrl;awsRequestSigner;region;static#e="https://sts.{region}.amazonaws.com?Action=GetCallerIdentity&Version=2011-06-15";static AWS_EC2_METADATA_IPV4_ADDRESS="169.254.169.254";static AWS_EC2_METADATA_IPV6_ADDRESS="fd00:ec2::254";constructor(e){super(e);let t=x_.originalOrCamelOptions(e),r=t.get("credential_source"),n=t.get("aws_security_credentials_supplier");if(!r&&!n)throw Error("A credential source or AWS security credentials supplier must be specified.");if(r&&n)throw Error("Only one of credential source or AWS security credentials supplier can be specified.");if(n)this.awsSecurityCredentialsSupplier=n,this.regionalCredVerificationUrl=C_.#e,this.credentialSourceType="programmatic";else{let i=x_.originalOrCamelOptions(r);this.environmentId=i.get("environment_id");let o=i.get("region_url"),s=i.get("url"),a=i.get("imdsv2_session_token_url");this.awsSecurityCredentialsSupplier=new sW.DefaultAwsSecurityCredentialsSupplier({regionUrl:o,securityCredentialsUrl:s,imdsV2SessionTokenUrl:a}),this.regionalCredVerificationUrl=i.get("regional_cred_verification_url"),this.credentialSourceType="aws",this.validateEnvironmentId()}this.awsRequestSigner=null,this.region=""}validateEnvironmentId(){let e=this.environmentId?.match(/^(aws)(\d+)$/);if(!e||!this.regionalCredVerificationUrl)throw Error('No valid AWS "credential_source" provided');else if(parseInt(e[2],10)!==1)throw Error(`aws version "${e[2]}" is not supported in the current build.`)}async retrieveSubjectToken(){if(!this.awsRequestSigner)this.region=await this.awsSecurityCredentialsSupplier.getAwsRegion(this.supplierContext),this.awsRequestSigner=new iW.AwsRequestSigner(async()=>this.awsSecurityCredentialsSupplier.getAwsSecurityCredentials(this.supplierContext),this.region);let e=await this.awsRequestSigner.getRequestOptions({...C_.RETRY_CONFIG,url:this.regionalCredVerificationUrl.replace("{region}",this.region),method:"POST"}),t=[];return aW.Gaxios.mergeHeaders({"x-goog-cloud-target-resource":this.audience},e.headers).forEach((n,i)=>t.push({key:i,value:n})),encodeURIComponent(JSON.stringify({url:e.url,method:e.method,headers:t}))}}cW.AwsClient=C_});var rk=A(function(fW){Object.defineProperty(fW,"__esModule",{value:!0});fW.InvalidSubjectTokenError=fW.InvalidMessageFieldError=fW.InvalidCodeFieldError=fW.InvalidTokenTypeFieldError=fW.InvalidExpirationTimeFieldError=fW.InvalidSuccessFieldError=fW.InvalidVersionFieldError=fW.ExecutableResponseError=fW.ExecutableResponse=void 0;var O_="urn:ietf:params:oauth:token-type:saml2",J0="urn:ietf:params:oauth:token-type:id_token",Q0="urn:ietf:params:oauth:token-type:jwt";class dW{version;success;expirationTime;tokenType;errorCode;errorMessage;subjectToken;constructor(e){if(!e.version)throw new Y0("Executable response must contain a 'version' field.");if(e.success===void 0)throw new X0("Executable response must contain a 'success' field.");if(this.version=e.version,this.success=e.success,this.success){if(this.expirationTime=e.expiration_time,this.tokenType=e.token_type,this.tokenType!==O_&&this.tokenType!==J0&&this.tokenType!==Q0)throw new Z0(`Executable response must contain a 'token_type' field when successful and it must be one of ${J0}, ${Q0}, or ${O_}.`);if(this.tokenType===O_){if(!e.saml_response)throw new I_(`Executable response must contain a 'saml_response' field when token_type=${O_}.`);this.subjectToken=e.saml_response}else{if(!e.id_token)throw new I_(`Executable response must contain a 'id_token' field when token_type=${J0} or ${Q0}.`);this.subjectToken=e.id_token}}else{if(!e.code)throw new ek("Executable response must contain a 'code' field when unsuccessful.");if(!e.message)throw new tk("Executable response must contain a 'message' field when unsuccessful.");this.errorCode=e.code,this.errorMessage=e.message}}isValid(){return!this.isExpired()&&this.success}isExpired(){return this.expirationTime!==void 0&&this.expirationTime<Math.round(Date.now()/1000)}}fW.ExecutableResponse=dW;class gc extends Error{constructor(e){super(e);Object.setPrototypeOf(this,new.target.prototype)}}fW.ExecutableResponseError=gc;class Y0 extends gc{}fW.InvalidVersionFieldError=Y0;class X0 extends gc{}fW.InvalidSuccessFieldError=X0;class lW extends gc{}fW.InvalidExpirationTimeFieldError=lW;class Z0 extends gc{}fW.InvalidTokenTypeFieldError=Z0;class ek extends gc{}fW.InvalidCodeFieldError=ek;class tk extends gc{}fW.InvalidMessageFieldError=tk;class I_ extends gc{}fW.InvalidSubjectTokenError=I_});var ok=A(function(mW){Object.defineProperty(mW,"__esModule",{value:!0});mW.PluggableAuthHandler=mW.ExecutableError=void 0;var Uo=rk(),pW=C("child_process"),pf=C("fs");class nk extends Error{code;constructor(e,t){super(`The executable failed with exit code: ${t} and error message: ${e}.`);this.code=t,Object.setPrototypeOf(this,new.target.prototype)}}mW.ExecutableError=nk;class ik{commandComponents;timeoutMillis;outputFile;constructor(e){if(!e.command)throw Error("No command provided.");if(this.commandComponents=ik.parseCommand(e.command),this.timeoutMillis=e.timeoutMillis,!this.timeoutMillis)throw Error("No timeoutMillis provided.");this.outputFile=e.outputFile}retrieveResponseFromExecutable(e){return new Promise((t,r)=>{let n=pW.spawn(this.commandComponents[0],this.commandComponents.slice(1),{env:{...process.env,...Object.fromEntries(e)}}),i="";n.stdout.on("data",(s)=>{i+=s}),n.stderr.on("data",(s)=>{i+=s});let o=setTimeout(()=>(n.removeAllListeners(),n.kill(),r(Error("The executable failed to finish within the timeout specified."))),this.timeoutMillis);n.on("close",(s)=>{if(clearTimeout(o),s===0)try{let a=JSON.parse(i),c=new Uo.ExecutableResponse(a);return t(c)}catch(a){if(a instanceof Uo.ExecutableResponseError)return r(a);return r(new Uo.ExecutableResponseError(`The executable returned an invalid response: ${i}`))}else return r(new nk(i,s.toString()))})})}async retrieveCachedResponse(){if(!this.outputFile||this.outputFile.length===0)return;let e;try{e=await pf.promises.realpath(this.outputFile)}catch{return}if(!(await pf.promises.lstat(e)).isFile())return;let t=await pf.promises.readFile(e,{encoding:"utf8"});if(t==="")return;try{let r=JSON.parse(t);if(new Uo.ExecutableResponse(r).isValid())return new Uo.ExecutableResponse(r);return}catch(r){if(r instanceof Uo.ExecutableResponseError)throw r;throw new Uo.ExecutableResponseError(`The output file contained an invalid response: ${t}`)}}static parseCommand(e){let t=e.match(/(?:[^\s"]+|"[^"]*")+/g);if(!t)throw Error(`Provided command: "${e}" could not be parsed.`);for(let r=0;r<t.length;r++)if(t[r][0]==='"'&&t[r].slice(-1)==='"')t[r]=t[r].slice(1,-1);return t}}mW.PluggableAuthHandler=ik});var ak=A(function(sk){Object.defineProperty(sk,"__esModule",{value:!0});sk.PluggableAuthClient=sk.ExecutableError=void 0;var bW=Eu(),EW=rk(),D_=ok(),Uge=ok();Object.defineProperty(sk,"ExecutableError",{enumerable:!0,get:function(){return Uge.ExecutableError}});var Pge=30000,yW=5000,wW=120000,Lge="GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES",_W=1;class SW extends bW.BaseExternalAccountClient{command;timeoutMillis;outputFile;handler;constructor(e){super(e);if(!e.credential_source.executable)throw Error('No valid Pluggable Auth "credential_source" provided.');if(this.command=e.credential_source.executable.command,!this.command)throw Error('No valid Pluggable Auth "credential_source" provided.');if(e.credential_source.executable.timeout_millis===void 0)this.timeoutMillis=Pge;else if(this.timeoutMillis=e.credential_source.executable.timeout_millis,this.timeoutMillis<yW||this.timeoutMillis>wW)throw Error(`Timeout must be between ${yW} and ${wW} milliseconds.`);this.outputFile=e.credential_source.executable.output_file,this.handler=new D_.PluggableAuthHandler({command:this.command,timeoutMillis:this.timeoutMillis,outputFile:this.outputFile}),this.credentialSourceType="executable"}async retrieveSubjectToken(){if(process.env[Lge]!=="1")throw Error("Pluggable Auth executables need to be explicitly allowed to run by setting the GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES environment Variable to 1.");let e=void 0;if(this.outputFile)e=await this.handler.retrieveCachedResponse();if(!e){let t=new Map;if(t.set("GOOGLE_EXTERNAL_ACCOUNT_AUDIENCE",this.audience),t.set("GOOGLE_EXTERNAL_ACCOUNT_TOKEN_TYPE",this.subjectTokenType),t.set("GOOGLE_EXTERNAL_ACCOUNT_INTERACTIVE","0"),this.outputFile)t.set("GOOGLE_EXTERNAL_ACCOUNT_OUTPUT_FILE",this.outputFile);let r=this.getServiceAccountEmail();if(r)t.set("GOOGLE_EXTERNAL_ACCOUNT_IMPERSONATED_EMAIL",r);e=await this.handler.retrieveResponseFromExecutable(t)}if(e.version>_W)throw Error(`Version of executable is not currently supported, maximum supported version is ${_W}.`);if(!e.success)throw new D_.ExecutableError(e.errorMessage,e.errorCode);if(this.outputFile){if(!e.expirationTime)throw new EW.InvalidExpirationTimeFieldError("The executable response must contain the `expiration_time` field for successful responses when an output_file has been specified in the configuration.")}if(e.isExpired())throw Error("Executable response is expired.");return e.subjectToken}}sk.PluggableAuthClient=SW});var ck=A(function(xW){Object.defineProperty(xW,"__esModule",{value:!0});xW.ExternalAccountClient=void 0;var TW=Eu(),vW=V0(),kW=K0(),RW=ak();class NW{constructor(){throw Error("ExternalAccountClients should be initialized via: ExternalAccountClient.fromJSON(), directly via explicit constructors, eg. new AwsClient(options), new IdentityPoolClient(options), newPluggableAuthClientOptions, or via new GoogleAuth(options).getClient()")}static fromJSON(e){if(e&&e.type===TW.EXTERNAL_ACCOUNT_TYPE)if(e.credential_source?.environment_id)return new kW.AwsClient(e);else if(e.credential_source?.executable)return new RW.PluggableAuthClient(e);else return new vW.IdentityPoolClient(e);else return null}}xW.ExternalAccountClient=NW});var dk=A(function(UW){Object.defineProperty(UW,"__esModule",{value:!0});UW.ExternalAccountAuthorizedUserClient=UW.EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE=void 0;var P_=Xo(),U_=$0(),L_=to(),OW=C("stream"),IW=Eu();UW.EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE="external_account_authorized_user";var Mge="https://sts.{universeDomain}/v1/oauthtoken";class uk extends U_.OAuthClientAuthHandler{#e;constructor(e){super(e);this.#e=e.tokenRefreshEndpoint}async refreshToken(e,t){let r={...uk.RETRY_CONFIG,url:this.#e,method:"POST",headers:t,data:new URLSearchParams({grant_type:"refresh_token",refresh_token:e}),responseType:"json"};P_.AuthClient.setMethodName(r,"refreshToken"),this.applyClientAuthenticationOptions(r);try{let n=await this.transporter.request(r),i=n.data;return i.res=n,i}catch(n){if(n instanceof L_.GaxiosError&&n.response)throw U_.getErrorFromOAuthErrorResponse(n.response.data,n);throw n}}}class DW extends P_.AuthClient{cachedAccessToken;externalAccountAuthorizedUserHandler;refreshToken;constructor(e){super(e);if(e.universe_domain)this.universeDomain=e.universe_domain;this.refreshToken=e.refresh_token;let t={confidentialClientType:"basic",clientId:e.client_id,clientSecret:e.client_secret};if(this.externalAccountAuthorizedUserHandler=new uk({tokenRefreshEndpoint:e.token_url??Mge.replace("{universeDomain}",this.universeDomain),transporter:this.transporter,clientAuthentication:t}),this.cachedAccessToken=null,this.quotaProjectId=e.quota_project_id,typeof e?.eagerRefreshThresholdMillis!=="number")this.eagerRefreshThresholdMillis=IW.EXPIRATION_TIME_OFFSET;else this.eagerRefreshThresholdMillis=e.eagerRefreshThresholdMillis;this.forceRefreshOnFailure=!!e?.forceRefreshOnFailure}async getAccessToken(){if(!this.cachedAccessToken||this.isExpired(this.cachedAccessToken))await this.refreshAccessTokenAsync();return{token:this.cachedAccessToken.access_token,res:this.cachedAccessToken.res}}async getRequestHeaders(){let e=await this.getAccessToken(),t=new Headers({authorization:`Bearer ${e.token}`});return this.addSharedMetadataHeaders(t)}request(e,t){if(t)this.requestAsync(e).then((r)=>t(null,r),(r)=>t(r,r.response));else return this.requestAsync(e)}async requestAsync(e,t=!1){let r;try{let n=await this.getRequestHeaders();e.headers=L_.Gaxios.mergeHeaders(e.headers),this.addUserProjectAndAuthHeaders(e.headers,n),r=await this.transporter.request(e)}catch(n){let i=n.response;if(i){let o=i.status,s=i.config.data instanceof OW.Readable;if(!t&&(o===401||o===403)&&!s&&this.forceRefreshOnFailure)return await this.refreshAccessTokenAsync(),await this.requestAsync(e,!0)}throw n}return r}async refreshAccessTokenAsync(){let e=await this.externalAccountAuthorizedUserHandler.refreshToken(this.refreshToken);if(this.cachedAccessToken={access_token:e.access_token,expiry_date:new Date().getTime()+e.expires_in*1000,res:e.res},e.refresh_token!==void 0)this.refreshToken=e.refresh_token;return this.cachedAccessToken}isExpired(e){let t=new Date().getTime();return e.expiry_date?t>=e.expiry_date-this.eagerRefreshThresholdMillis:!1}}UW.ExternalAccountAuthorizedUserClient=DW});var hk=A(function(jW){Object.defineProperty(jW,"__esModule",{value:!0});jW.GdchClient=jW.GDCH_SERVICE_ACCOUNT_TYPE=void 0;var LW=C("crypto"),MW=C("fs"),qW=C("https"),BW=yu(),Bge=3600;jW.GDCH_SERVICE_ACCOUNT_TYPE="gdch_service_account";class fk extends BW.OAuth2Client{projectId;privateKeyId;privateKey;serviceIdentityName;tokenServerUri;caCertPath;apiAudience;lifetime;gdchOptions;caAgentPromise;cachedCaCertPath;lastCaCertReadTime=0;CA_CERT_TTL_MS=300000;constructor(e={}){super(e);this.gdchOptions=e,this.projectId=e.projectId||void 0,this.privateKeyId=e.privateKeyId,this.privateKey=e.privateKey,this.serviceIdentityName=e.serviceIdentityName,this.tokenServerUri=e.tokenServerUri,this.caCertPath=e.caCertPath,this.apiAudience=e.apiAudience,this.lifetime=e.lifetime||Bge,this.credentials={refresh_token:"gdch-placeholder",expiry_date:1}}createWithGdchAudience(e){if(!e)throw Error("Audience cannot be null or empty for GDCH service account credentials.");return new fk({...this.gdchOptions,projectId:this.projectId,privateKeyId:this.privateKeyId,privateKey:this.privateKey,serviceIdentityName:this.serviceIdentityName,tokenServerUri:this.tokenServerUri,caCertPath:this.caCertPath,lifetime:this.lifetime,apiAudience:e})}fromJSON(e){if(!e)throw Error("Must pass in a JSON object containing the GDCH credentials settings.");if(e.type!==jW.GDCH_SERVICE_ACCOUNT_TYPE)throw Error(`The incoming JSON object does not have the "${jW.GDCH_SERVICE_ACCOUNT_TYPE}" type`);if(e.format_version!=="1")throw Error("Only format version 1 is supported.");if(!e.project)throw Error("The incoming JSON object does not contain a project field");if(!e.private_key_id)throw Error("The incoming JSON object does not contain a private_key_id field");if(!e.private_key)throw Error("The incoming JSON object does not contain a private_key field");if(!e.name)throw Error("The incoming JSON object does not contain a name field");if(!e.token_uri)throw Error("The incoming JSON object does not contain a token_uri field");this.projectId=e.project,this.privateKeyId=e.private_key_id,this.privateKey=e.private_key,this.serviceIdentityName=e.name,this.tokenServerUri=e.token_uri,this.caCertPath=e.ca_cert_path,this.gdchOptions={...this.gdchOptions,projectId:e.project,privateKeyId:e.private_key_id,privateKey:e.private_key,serviceIdentityName:e.name,tokenServerUri:e.token_uri,caCertPath:e.ca_cert_path}}async refreshTokenNoCache(){if(!this.apiAudience)throw Error("Audience cannot be null or empty for GDCH service account credentials. Specify the audience by calling createWithGdchAudience.");if(!this.privateKey)throw Error("Private key is not configured for GDCH credentials.");if(!this.privateKeyId)throw Error("Private key ID is not configured for GDCH credentials.");if(!this.projectId)throw Error("Project is not configured for GDCH credentials.");if(!this.serviceIdentityName)throw Error("Service identity name is not configured for GDCH credentials.");if(!this.tokenServerUri)throw Error("Token server URI is not configured for GDCH credentials.");let e=this.createAssertion(),t={audience:this.apiAudience,grant_type:"urn:ietf:params:oauth:token-type:token-exchange",requested_token_type:"urn:ietf:params:oauth:token-type:access_token",subject_token:e,subject_token_type:"urn:k8s:params:oauth:token-type:serviceaccount"},r={url:this.tokenServerUri,method:"POST",headers:{"Content-Type":"application/json"},data:t,responseType:"json",timeout:1e4,retry:!0,retryConfig:{httpMethodsToRetry:["POST"],statusCodesToRetry:[[500,599]],noResponseRetries:3}};if(this.caCertPath)r.agent=await this.getCaAgent();try{let n=await this.transporter.request(r),i=n.data;if(!i.access_token)throw Error("Token response did not contain an access_token.");if(!i.expires_in)throw Error("Token response did not contain an expires_in field.");let o={access_token:i.access_token,token_type:"STS-Bearer",expiry_date:Date.now()+i.expires_in*1000};return this.emit("tokens",o),{res:n,tokens:o}}catch(n){if(n&&n.config&&n.config.data)try{if(typeof n.config.data==="string"){let i=JSON.parse(n.config.data);if(i.subject_token)i.subject_token="***REDACTED***",n.config.data=JSON.stringify(i)}else if(typeof n.config.data==="object"&&n.config.data.subject_token)n.config.data.subject_token="***REDACTED***"}catch{}if(n instanceof Error)n.message=`Error getting access token for GDCH service account: ${n.message}, iss: ${this.serviceIdentityName}`;throw n}}createAssertion(){let e={alg:"ES256",typ:"JWT",kid:this.privateKeyId},t=`system:serviceaccount:${this.projectId}:${this.serviceIdentityName}`,r=Math.floor(Date.now()/1000),n={iss:t,sub:t,iat:r,exp:r+this.lifetime,aud:this.tokenServerUri},i=this.base64UrlEncode(JSON.stringify(e)),o=this.base64UrlEncode(JSON.stringify(n)),s=`${i}.${o}`,a=LW.sign("sha256",Buffer.from(s),{key:this.privateKey,dsaEncoding:"ieee-p1363"}),c=this.base64UrlEncode(a);return`${s}.${c}`}async requestAsync(e,t=!1){if(this.caCertPath&&!e.agent){let r=(e.url||"").toString();if(!r.includes("googleapis.com")&&!r.includes("google.com"))e.agent=await this.getCaAgent()}return super.requestAsync(e,t)}getCaAgent(){if(!this.caCertPath){this.caAgentPromise=void 0,this.cachedCaCertPath=void 0,this.lastCaCertReadTime=0;return}let e=Date.now(),t=e-this.lastCaCertReadTime>this.CA_CERT_TTL_MS;if(this.caAgentPromise&&this.caCertPath===this.cachedCaCertPath&&!t)return this.caAgentPromise;this.cachedCaCertPath=this.caCertPath,this.lastCaCertReadTime=e;let r=this.caCertPath;return this.caAgentPromise=(async()=>{try{let n=await MW.promises.readFile(r);return new qW.Agent({ca:n})}catch(n){if(this.cachedCaCertPath===r)this.caAgentPromise=void 0,this.cachedCaCertPath=void 0,this.lastCaCertReadTime=0;if(n instanceof Error)n.message=`Error reading certificate file from CA cert path, value '${r}': ${n.message}`;throw n}})(),this.caAgentPromise}toJSON(){return{...this,privateKey:this.privateKey?"***REDACTED***":void 0,_clientSecret:this._clientSecret?"***REDACTED***":void 0,apiKey:this.apiKey?"***REDACTED***":void 0,gdchOptions:this.gdchOptions?{...this.gdchOptions,privateKey:this.gdchOptions.privateKey?"***REDACTED***":void 0,clientSecret:this.gdchOptions.clientSecret?"***REDACTED***":void 0,client_secret:this.gdchOptions.client_secret?"***REDACTED***":void 0,apiKey:this.gdchOptions.apiKey?"***REDACTED***":void 0,credentials:this.gdchOptions.credentials?{...this.gdchOptions.credentials,access_token:this.gdchOptions.credentials.access_token?"***REDACTED***":void 0,refresh_token:this.gdchOptions.credentials.refresh_token?"***REDACTED***":void 0}:void 0}:void 0,credentials:{...this.credentials,access_token:this.credentials?.access_token?"***REDACTED***":void 0,refresh_token:this.credentials?.refresh_token?"***REDACTED***":void 0}}}[Symbol.for("nodejs.util.inspect.custom")](){return this.toJSON()}base64UrlEncode(e){return(typeof e==="string"?Buffer.from(e):e).toString("base64url")}}jW.GdchClient=fk});var ZW=A(function(YW){Object.defineProperty(YW,"__esModule",{value:!0});YW.GoogleAuth=YW.GoogleAuthExceptionMessages=void 0;var FW=C("child_process"),Pa=C("fs"),zW=to(),La=$p(),WW=C("os"),Ru=C("path"),HW=Fp(),VW=E0(),GW=S0(),KW=A0(),Ss=q0(),M_=B0(),As=j0(),JW=ck(),Ma=Eu(),gf=Xo(),q_=dk(),yf=hk(),B_=Qs();YW.GoogleAuthExceptionMessages={API_KEY_WITH_CREDENTIALS:"API Keys and Credentials are mutually exclusive authentication methods and cannot be used together.",NO_PROJECT_ID_FOUND:`Unable to detect a Project Id in the current environment.
68
+ To learn more about authentication and Google APIs, visit:
69
+ https://cloud.google.com/docs/authentication/getting-started`,NO_CREDENTIALS_FOUND:`Unable to find credentials in current environment.
70
+ To learn more about authentication and Google APIs, visit:
71
+ https://cloud.google.com/docs/authentication/getting-started`,NO_ADC_FOUND:"Could not load the default credentials. Browse to https://cloud.google.com/docs/authentication/getting-started for more information.",NO_UNIVERSE_DOMAIN_FOUND:`Unable to detect a Universe Domain in the current environment.
72
+ To learn more about Universe Domain retrieval, visit:
73
+ https://cloud.google.com/compute/docs/metadata/predefined-metadata-keys`};class QW{checkIsGCE=void 0;useJWTAccessWithScope;defaultServicePath;get isGCE(){return this.checkIsGCE}_findProjectIdPromise;_cachedProjectId;jsonContent=null;apiKey;cachedCredential=null;#e=null;defaultScopes;keyFilename;scopes;clientOptions={};constructor(e={}){if(this._cachedProjectId=e.projectId||null,this.cachedCredential=e.authClient||null,this.keyFilename=e.keyFilename||e.keyFile,this.scopes=e.scopes,this.clientOptions=e.clientOptions||{},this.jsonContent=e.credentials||null,this.apiKey=e.apiKey||this.clientOptions.apiKey||null,this.apiKey&&(this.jsonContent||this.clientOptions.credentials))throw RangeError(YW.GoogleAuthExceptionMessages.API_KEY_WITH_CREDENTIALS);if(e.universeDomain)this.clientOptions.universeDomain=e.universeDomain}setGapicJWTValues(e){e.defaultServicePath=this.defaultServicePath,e.useJWTAccessWithScope=this.useJWTAccessWithScope,e.defaultScopes=this.defaultScopes}getProjectId(e){if(e)this.getProjectIdAsync().then((t)=>e(null,t),e);else return this.getProjectIdAsync()}async getProjectIdOptional(){try{return await this.getProjectId()}catch(e){if(e instanceof Error&&e.message===YW.GoogleAuthExceptionMessages.NO_PROJECT_ID_FOUND)return null;else throw e}}async findAndCacheProjectId(){let e=null;if(e||=await this.getProductionProjectId(),e||=await this.getFileProjectId(),e||=await this.getDefaultServiceProjectId(),e||=await this.getGCEProjectId(),e||=await this.getExternalAccountClientProjectId(),e)return this._cachedProjectId=e,e;else throw Error(YW.GoogleAuthExceptionMessages.NO_PROJECT_ID_FOUND)}async getProjectIdAsync(){if(this._cachedProjectId)return this._cachedProjectId;if(!this._findProjectIdPromise)this._findProjectIdPromise=this.findAndCacheProjectId();return this._findProjectIdPromise}async getUniverseDomainFromMetadataServer(){let e;try{e=await La.universe("universe-domain"),e||=gf.DEFAULT_UNIVERSE}catch(t){if(t&&t?.response?.status===404)e=gf.DEFAULT_UNIVERSE;else throw t}return e}async getUniverseDomain(){let e=B_.originalOrCamelOptions(this.clientOptions).get("universe_domain");try{e??=(await this.getClient()).universeDomain}catch{e??=gf.DEFAULT_UNIVERSE}return e}getAnyScopes(){return this.scopes||this.defaultScopes}getApplicationDefault(e={},t){let r;if(typeof e==="function")t=e;else r=e;if(t)this.getApplicationDefaultAsync(r).then((n)=>t(null,n.credential,n.projectId),t);else return this.getApplicationDefaultAsync(r)}async getApplicationDefaultAsync(e={}){if(this.cachedCredential)return await this.#t(this.cachedCredential,null);let t;if(t=await this._tryGetApplicationCredentialsFromEnvironmentVariable(e),t){if(t instanceof Ss.JWT)t.scopes=this.scopes;else if(t instanceof Ma.BaseExternalAccountClient)t.scopes=this.getAnyScopes();return await this.#t(t)}if(t=await this._tryGetApplicationCredentialsFromWellKnownFile(e),t){if(t instanceof Ss.JWT)t.scopes=this.scopes;else if(t instanceof Ma.BaseExternalAccountClient)t.scopes=this.getAnyScopes();return await this.#t(t)}if(await this._checkIsGCE())return e.scopes=this.getAnyScopes(),await this.#t(new VW.Compute(e));throw Error(YW.GoogleAuthExceptionMessages.NO_ADC_FOUND)}async#t(e,t=process.env.GOOGLE_CLOUD_QUOTA_PROJECT||null){let r=await this.getProjectIdOptional();if(t)e.quotaProjectId=t;return this.cachedCredential=e,{credential:e,projectId:r}}async _checkIsGCE(){if(this.checkIsGCE===void 0)this.checkIsGCE=La.getGCPResidency()||await La.isAvailable();return this.checkIsGCE}async _tryGetApplicationCredentialsFromEnvironmentVariable(e){let t=process.env.GOOGLE_APPLICATION_CREDENTIALS||process.env.google_application_credentials;if(!t||t.length===0)return null;try{return await this._getApplicationCredentialsFromFilePath(t,e)}catch(r){if(r instanceof Error)r.message=`Unable to read the credential file specified by the GOOGLE_APPLICATION_CREDENTIALS environment variable: ${r.message}`;throw r}}async _tryGetApplicationCredentialsFromWellKnownFile(e){let t=process.env.CLOUDSDK_CONFIG;if(!t)if(this._isWindows()){if(process.env.APPDATA)t=Ru.join(process.env.APPDATA,"gcloud")}else{let i=process.env.HOME;if(i)t=Ru.join(i,".config","gcloud")}if(!t)return null;let r=Ru.join(t,"application_default_credentials.json");if(!Pa.existsSync(r))return null;return await this._getApplicationCredentialsFromFilePath(r,e)}async _getApplicationCredentialsFromFilePath(e,t={}){if(!e||e.length===0)throw Error("The file path is invalid.");try{if(e=Pa.realpathSync(e),!Pa.lstatSync(e).isFile())throw Error()}catch(n){if(n instanceof Error)n.message=`The file at ${e} does not exist, or it is not a file. ${n.message}`;throw n}let r=Pa.createReadStream(e);return this.fromStream(r,t)}fromImpersonatedJSON(e){if(!e)throw Error("Must pass in a JSON object containing an impersonated refresh token");if(e.type!==As.IMPERSONATED_ACCOUNT_TYPE)throw Error(`The incoming JSON object does not have the "${As.IMPERSONATED_ACCOUNT_TYPE}" type`);if(!e.source_credentials)throw Error("The incoming JSON object does not contain a source_credentials field");if(!e.service_account_impersonation_url)throw Error("The incoming JSON object does not contain a service_account_impersonation_url field");let t=this.fromJSON(e.source_credentials);if(e.service_account_impersonation_url?.length>256)throw RangeError(`Target principal is too long: ${e.service_account_impersonation_url}`);let r=/(?<target>[^/]+):(generateAccessToken|generateIdToken)$/.exec(e.service_account_impersonation_url)?.groups?.target;if(!r)throw RangeError(`Cannot extract target principal from ${e.service_account_impersonation_url}`);let n=(this.scopes||e.scopes||this.defaultScopes)??[];return new As.Impersonated({...e,sourceClient:t,targetPrincipal:r,targetScopes:Array.isArray(n)?n:[n]})}fromJSON(e,t={}){let r,n=B_.originalOrCamelOptions(t).get("universe_domain");if(e.type===M_.USER_REFRESH_ACCOUNT_TYPE)r=new M_.UserRefreshClient(t),r.fromJSON(e);else if(e.type===As.IMPERSONATED_ACCOUNT_TYPE)r=this.fromImpersonatedJSON(e);else if(e.type===Ma.EXTERNAL_ACCOUNT_TYPE)r=JW.ExternalAccountClient.fromJSON({...e,...t}),r.scopes=this.getAnyScopes();else if(e.type===q_.EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE)r=new q_.ExternalAccountAuthorizedUserClient({...e,...t});else if(e.type===yf.GDCH_SERVICE_ACCOUNT_TYPE)r=new yf.GdchClient(t),r.fromJSON(e);else t.scopes=this.scopes,r=new Ss.JWT(t),this.setGapicJWTValues(r),r.fromJSON(e);if(n)r.universeDomain=n;return r}_cacheClientFromJSON(e,t){let r=this.fromJSON(e,t);return this.jsonContent=e,this.cachedCredential=r,r}fromStream(e,t={},r){let n={};if(typeof t==="function")r=t;else n=t;if(r)this.fromStreamAsync(e,n).then((i)=>r(null,i),r);else return this.fromStreamAsync(e,n)}fromStreamAsync(e,t){return new Promise((r,n)=>{if(!e)throw Error("Must pass in a stream containing the Google auth settings.");let i=[];e.setEncoding("utf8").on("error",n).on("data",(o)=>i.push(o)).on("end",()=>{try{try{let o=JSON.parse(i.join("")),s=this._cacheClientFromJSON(o,t);return r(s)}catch(o){if(!this.keyFilename)throw o;let s=new Ss.JWT({...this.clientOptions,keyFile:this.keyFilename});return this.cachedCredential=s,this.setGapicJWTValues(s),r(s)}}catch(o){return n(o)}})})}fromAPIKey(e,t={}){return new Ss.JWT({...t,apiKey:e})}_isWindows(){let e=WW.platform();if(e&&e.length>=3){if(e.substring(0,3).toLowerCase()==="win")return!0}return!1}async getDefaultServiceProjectId(){return new Promise((e)=>{FW.exec("gcloud config config-helper --format json",(t,r)=>{if(!t&&r)try{let n=JSON.parse(r).configuration.properties.core.project;e(n);return}catch(n){}e(null)})})}getProductionProjectId(){return process.env.GCLOUD_PROJECT||process.env.GOOGLE_CLOUD_PROJECT||process.env.gcloud_project||process.env.google_cloud_project}async getFileProjectId(){if(this.cachedCredential)return this.cachedCredential.projectId;if(this.keyFilename){let t=await this.getClient();if(t&&t.projectId)return t.projectId}let e=await this._tryGetApplicationCredentialsFromEnvironmentVariable();if(e)return e.projectId;else return null}async getExternalAccountClientProjectId(){if(!this.jsonContent||this.jsonContent.type!==Ma.EXTERNAL_ACCOUNT_TYPE)return null;return await(await this.getClient()).getProjectId()}async getGCEProjectId(){try{return await La.project("project-id")}catch(e){return null}}getCredentials(e){if(e)this.getCredentialsAsync().then((t)=>e(null,t),e);else return this.getCredentialsAsync()}async getCredentialsAsync(){let e=await this.getClient();if(e instanceof As.Impersonated)return{client_email:e.getTargetPrincipal()};if(e instanceof Ma.BaseExternalAccountClient){let t=e.getServiceAccountEmail();if(t)return{client_email:t,universe_domain:e.universeDomain}}if(this.jsonContent)return{client_email:this.jsonContent.client_email,private_key:this.jsonContent.private_key,universe_domain:this.jsonContent.universe_domain};if(await this._checkIsGCE()){let[t,r]=await Promise.all([La.instance("service-accounts/default/email"),this.getUniverseDomain()]);return{client_email:t,universe_domain:r}}throw Error(YW.GoogleAuthExceptionMessages.NO_CREDENTIALS_FOUND)}async getClient(){if(this.cachedCredential)return this.cachedCredential;this.#e=this.#e||this.#r();try{let e=await this.#e;if(e instanceof yf.GdchClient&&!e.apiAudience){let t=this.clientOptions,r=t.apiEndpoint||t.servicePath;if(r){let i=`${r.startsWith("http")?"":"https://"}${r}`.replace(/\/+$/,""),o=e.createWithGdchAudience(i);return this.cachedCredential=o,o}}return e}finally{this.#e=null}}async#r(){if(this.jsonContent)return this._cacheClientFromJSON(this.jsonContent,this.clientOptions);else if(this.keyFilename){let e=Ru.resolve(this.keyFilename),t=Pa.createReadStream(e);return await this.fromStreamAsync(t,this.clientOptions)}else if(this.apiKey){let e=await this.fromAPIKey(this.apiKey,this.clientOptions);e.scopes=this.scopes;let{credential:t}=await this.#t(e);return t}else{let{credential:e}=await this.getApplicationDefaultAsync(this.clientOptions);return e}}async getIdTokenClient(e){let t=await this.getClient();if(!("fetchIdToken"in t))throw Error("Cannot fetch ID token in this environment, use GCE or set the GOOGLE_APPLICATION_CREDENTIALS environment variable to a service account credentials JSON file.");return new GW.IdTokenClient({targetAudience:e,idTokenProvider:t})}async getAccessToken(){return(await(await this.getClient()).getAccessToken()).token}async getRequestHeaders(e){return(await this.getClient()).getRequestHeaders(e)}async authorizeRequest(e={}){let t=e.url,n=await(await this.getClient()).getRequestHeaders(t);return e.headers=zW.Gaxios.mergeHeaders(e.headers,n),e}async fetch(...e){return(await this.getClient()).fetch(...e)}async request(e){return(await this.getClient()).request(e)}getEnv(){return KW.getEnv()}async sign(e,t){let r=await this.getClient(),n=await this.getUniverseDomain();if(t=t||`https://iamcredentials.${n}/v1/projects/-/serviceAccounts/`,r instanceof As.Impersonated)return(await r.sign(e)).signedBlob;let i=HW.createCrypto();if(r instanceof Ss.JWT&&r.key)return await i.sign(r.key,e);let o=await this.getCredentials();if(!o.client_email)throw Error("Cannot sign data without `client_email`.");return this.signBlob(i,o.client_email,e,t)}async signBlob(e,t,r,n){let i=new URL(n+`${t}:signBlob`);return(await this.request({method:"POST",url:i.href,data:{payload:e.encodeBase64StringUtf8(r)},retry:!0,retryConfig:{httpMethodsToRetry:["POST"]}})).data.signedBlob}}YW.GoogleAuth=QW});var nH=A(function(tH){Object.defineProperty(tH,"__esModule",{value:!0});tH.IAMAuth=void 0;class eH{selector;token;constructor(e,t){this.selector=e,this.token=t,this.selector=e,this.token=t}getRequestHeaders(){return{"x-goog-iam-authority-selector":this.selector,"x-goog-iam-authorization-token":this.token}}}tH.IAMAuth=eH});var dH=A(function(cH){Object.defineProperty(cH,"__esModule",{value:!0});cH.DownscopedClient=cH.EXPIRATION_TIME_OFFSET=cH.MAX_ACCESS_BOUNDARY_RULES_COUNT=void 0;var iH=to(),oH=C("stream"),wf=Xo(),sH=S_(),jge="urn:ietf:params:oauth:grant-type:token-exchange",$ge="urn:ietf:params:oauth:token-type:access_token",Fge="urn:ietf:params:oauth:token-type:access_token";cH.MAX_ACCESS_BOUNDARY_RULES_COUNT=10;cH.EXPIRATION_TIME_OFFSET=300000;class aH extends wf.AuthClient{authClient;credentialAccessBoundary;cachedDownscopedAccessToken;stsCredential;constructor(e,t={accessBoundary:{accessBoundaryRules:[]}}){super(e instanceof wf.AuthClient?{}:e);if(e instanceof wf.AuthClient)this.authClient=e,this.credentialAccessBoundary=t;else this.authClient=e.authClient,this.credentialAccessBoundary=e.credentialAccessBoundary;if(this.credentialAccessBoundary.accessBoundary.accessBoundaryRules.length===0)throw Error("At least one access boundary rule needs to be defined.");else if(this.credentialAccessBoundary.accessBoundary.accessBoundaryRules.length>cH.MAX_ACCESS_BOUNDARY_RULES_COUNT)throw Error(`The provided access boundary has more than ${cH.MAX_ACCESS_BOUNDARY_RULES_COUNT} access boundary rules.`);for(let r of this.credentialAccessBoundary.accessBoundary.accessBoundaryRules)if(r.availablePermissions.length===0)throw Error("At least one permission should be defined in access boundary rules.");this.stsCredential=new sH.StsCredentials({tokenExchangeEndpoint:`https://sts.${this.universeDomain}/v1/token`}),this.cachedDownscopedAccessToken=null}setCredentials(e){if(!e.expiry_date)throw Error("The access token expiry_date field is missing in the provided credentials.");super.setCredentials(e),this.cachedDownscopedAccessToken=e}async getAccessToken(){if(!this.cachedDownscopedAccessToken||this.isExpired(this.cachedDownscopedAccessToken))await this.refreshAccessTokenAsync();return{token:this.cachedDownscopedAccessToken.access_token,expirationTime:this.cachedDownscopedAccessToken.expiry_date,res:this.cachedDownscopedAccessToken.res}}async getRequestHeaders(){let e=await this.getAccessToken(),t=new Headers({authorization:`Bearer ${e.token}`});return this.addSharedMetadataHeaders(t)}request(e,t){if(t)this.requestAsync(e).then((r)=>t(null,r),(r)=>t(r,r.response));else return this.requestAsync(e)}async requestAsync(e,t=!1){let r;try{let n=await this.getRequestHeaders();e.headers=iH.Gaxios.mergeHeaders(e.headers),this.addUserProjectAndAuthHeaders(e.headers,n),r=await this.transporter.request(e)}catch(n){let i=n.response;if(i){let o=i.status,s=i.config.data instanceof oH.Readable;if(!t&&(o===401||o===403)&&!s&&this.forceRefreshOnFailure)return await this.refreshAccessTokenAsync(),await this.requestAsync(e,!0)}throw n}return r}async refreshAccessTokenAsync(){let e=(await this.authClient.getAccessToken()).token,t={grantType:jge,requestedTokenType:$ge,subjectToken:e,subjectTokenType:Fge},r=await this.stsCredential.exchangeToken(t,void 0,this.credentialAccessBoundary),n=this.authClient.credentials?.expiry_date||null,i=r.expires_in?new Date().getTime()+r.expires_in*1000:n;return this.cachedDownscopedAccessToken={access_token:r.access_token,expiry_date:i,res:r.res},this.credentials={},Object.assign(this.credentials,this.cachedDownscopedAccessToken),delete this.credentials.res,this.emit("tokens",{refresh_token:null,expiry_date:this.cachedDownscopedAccessToken.expiry_date,access_token:this.cachedDownscopedAccessToken.access_token,token_type:"Bearer",id_token:null}),this.cachedDownscopedAccessToken}isExpired(e){let t=new Date().getTime();return e.expiry_date?t>=e.expiry_date-this.eagerRefreshThresholdMillis:!1}}cH.DownscopedClient=aH});var mH=A(function(hH){Object.defineProperty(hH,"__esModule",{value:!0});hH.PassThroughClient=void 0;var lH=Xo();class fH extends lH.AuthClient{async request(e){return this.transporter.request(e)}async getAccessToken(){return{}}async getRequestHeaders(){return new Headers}}hH.PassThroughClient=fH});var _r=A(function(wt){var Wge=wt&&wt.__createBinding||(Object.create?function(e,t,r,n){if(n===void 0)n=r;var i=Object.getOwnPropertyDescriptor(t,r);if(!i||("get"in i?!t.__esModule:i.writable||i.configurable))i={enumerable:!0,get:function(){return t[r]}};Object.defineProperty(e,n,i)}:function(e,t,r,n){if(n===void 0)n=r;e[n]=t[r]}),Hge=wt&&wt.__exportStar||function(e,t){for(var r in e)if(r!=="default"&&!Object.prototype.hasOwnProperty.call(t,r))Wge(t,e,r)};Object.defineProperty(wt,"__esModule",{value:!0});wt.GoogleAuth=wt.auth=wt.GDCH_SERVICE_ACCOUNT_TYPE=wt.GdchClient=wt.PassThroughClient=wt.ExternalAccountAuthorizedUserClient=wt.EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE=wt.ExecutableError=wt.PluggableAuthClient=wt.DownscopedClient=wt.BaseExternalAccountClient=wt.ExternalAccountClient=wt.IdentityPoolClient=wt.AwsRequestSigner=wt.AwsClient=wt.UserRefreshClient=wt.LoginTicket=wt.ClientAuthentication=wt.OAuth2Client=wt.CodeChallengeMethod=wt.Impersonated=wt.JWT=wt.JWTAccess=wt.IdTokenClient=wt.IAMAuth=wt.GCPEnv=wt.Compute=wt.DEFAULT_UNIVERSE=wt.AuthClient=wt.gaxios=wt.gcpMetadata=void 0;var j_=ZW();Object.defineProperty(wt,"GoogleAuth",{enumerable:!0,get:function(){return j_.GoogleAuth}});wt.gcpMetadata=$p();wt.gaxios=to();var gH=Xo();Object.defineProperty(wt,"AuthClient",{enumerable:!0,get:function(){return gH.AuthClient}});Object.defineProperty(wt,"DEFAULT_UNIVERSE",{enumerable:!0,get:function(){return gH.DEFAULT_UNIVERSE}});var Vge=E0();Object.defineProperty(wt,"Compute",{enumerable:!0,get:function(){return Vge.Compute}});var Gge=A0();Object.defineProperty(wt,"GCPEnv",{enumerable:!0,get:function(){return Gge.GCPEnv}});var Kge=nH();Object.defineProperty(wt,"IAMAuth",{enumerable:!0,get:function(){return Kge.IAMAuth}});var Jge=S0();Object.defineProperty(wt,"IdTokenClient",{enumerable:!0,get:function(){return Jge.IdTokenClient}});var Qge=L0();Object.defineProperty(wt,"JWTAccess",{enumerable:!0,get:function(){return Qge.JWTAccess}});var Yge=q0();Object.defineProperty(wt,"JWT",{enumerable:!0,get:function(){return Yge.JWT}});var Xge=j0();Object.defineProperty(wt,"Impersonated",{enumerable:!0,get:function(){return Xge.Impersonated}});var mk=yu();Object.defineProperty(wt,"CodeChallengeMethod",{enumerable:!0,get:function(){return mk.CodeChallengeMethod}});Object.defineProperty(wt,"OAuth2Client",{enumerable:!0,get:function(){return mk.OAuth2Client}});Object.defineProperty(wt,"ClientAuthentication",{enumerable:!0,get:function(){return mk.ClientAuthentication}});var Zge=b0();Object.defineProperty(wt,"LoginTicket",{enumerable:!0,get:function(){return Zge.LoginTicket}});var eye=B0();Object.defineProperty(wt,"UserRefreshClient",{enumerable:!0,get:function(){return eye.UserRefreshClient}});var tye=K0();Object.defineProperty(wt,"AwsClient",{enumerable:!0,get:function(){return tye.AwsClient}});var rye=G0();Object.defineProperty(wt,"AwsRequestSigner",{enumerable:!0,get:function(){return rye.AwsRequestSigner}});var nye=V0();Object.defineProperty(wt,"IdentityPoolClient",{enumerable:!0,get:function(){return nye.IdentityPoolClient}});var iye=ck();Object.defineProperty(wt,"ExternalAccountClient",{enumerable:!0,get:function(){return iye.ExternalAccountClient}});var oye=Eu();Object.defineProperty(wt,"BaseExternalAccountClient",{enumerable:!0,get:function(){return oye.BaseExternalAccountClient}});var sye=dH();Object.defineProperty(wt,"DownscopedClient",{enumerable:!0,get:function(){return sye.DownscopedClient}});var yH=ak();Object.defineProperty(wt,"PluggableAuthClient",{enumerable:!0,get:function(){return yH.PluggableAuthClient}});Object.defineProperty(wt,"ExecutableError",{enumerable:!0,get:function(){return yH.ExecutableError}});var wH=dk();Object.defineProperty(wt,"EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE",{enumerable:!0,get:function(){return wH.EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE}});Object.defineProperty(wt,"ExternalAccountAuthorizedUserClient",{enumerable:!0,get:function(){return wH.ExternalAccountAuthorizedUserClient}});var aye=mH();Object.defineProperty(wt,"PassThroughClient",{enumerable:!0,get:function(){return aye.PassThroughClient}});var _H=hk();Object.defineProperty(wt,"GdchClient",{enumerable:!0,get:function(){return _H.GdchClient}});Object.defineProperty(wt,"GDCH_SERVICE_ACCOUNT_TYPE",{enumerable:!0,get:function(){return _H.GDCH_SERVICE_ACCOUNT_TYPE}});Hge(U0(),wt);var cye=new j_.GoogleAuth;wt.auth=cye});var Nt=A(function(sQe,SH){var{defineProperty:gk,getOwnPropertyDescriptor:uye,getOwnPropertyNames:dye}=Object,lye=Object.prototype.hasOwnProperty,fye=(e,t)=>{for(var r in t)gk(e,r,{get:t[r],enumerable:!0})},hye=(e,t,r,n)=>{if(t&&typeof t==="object"||typeof t==="function"){for(let i of dye(t))if(!lye.call(e,i)&&i!==r)gk(e,i,{get:()=>t[i],enumerable:!(n=uye(t,i))||n.enumerable})}return e},pye=(e)=>hye(gk({},"__esModule",{value:!0}),e),bH={};fye(bH,{VercelOidcTokenError:()=>EH});SH.exports=pye(bH);class EH extends Error{constructor(e,t){super(e);this.name="VercelOidcTokenError",this.cause=t}toString(){if(this.cause)return`${this.name}: ${this.message}: ${this.cause}`;return`${this.name}: ${this.message}`}}});var ln=A(function(aQe,kH){var{defineProperty:yk,getOwnPropertyDescriptor:mye,getOwnPropertyNames:gye}=Object,yye=Object.prototype.hasOwnProperty,wye=(e,t)=>{for(var r in t)yk(e,r,{get:t[r],enumerable:!0})},_ye=(e,t,r,n)=>{if(t&&typeof t==="object"||typeof t==="function"){for(let i of gye(t))if(!yye.call(e,i)&&i!==r)yk(e,i,{get:()=>t[i],enumerable:!(n=mye(t,i))||n.enumerable})}return e},bye=(e)=>_ye(yk({},"__esModule",{value:!0}),e),AH={};wye(AH,{AccessTokenMissingError:()=>TH,RefreshAccessTokenFailedError:()=>vH});kH.exports=bye(AH);class TH extends Error{constructor(){super("No authentication found. Please log in with the Vercel CLI (vercel login).");this.name="AccessTokenMissingError"}}class vH extends Error{constructor(e){super("Failed to refresh authentication token.",{cause:e});this.name="RefreshAccessTokenFailedError"}}});var CH=A(function(cQe,xH){var{create:Eye,defineProperty:$_,getOwnPropertyDescriptor:Sye,getOwnPropertyNames:Aye,getPrototypeOf:Tye}=Object,vye=Object.prototype.hasOwnProperty,kye=(e,t)=>{for(var r in t)$_(e,r,{get:t[r],enumerable:!0})},RH=(e,t,r,n)=>{if(t&&typeof t==="object"||typeof t==="function"){for(let i of Aye(t))if(!vye.call(e,i)&&i!==r)$_(e,i,{get:()=>t[i],enumerable:!(n=Sye(t,i))||n.enumerable})}return e},_k=(e,t,r)=>(r=e!=null?Eye(Tye(e)):{},RH(t||!e||!e.__esModule?$_(r,"default",{value:e,enumerable:!0}):r,e)),Rye=(e)=>RH($_({},"__esModule",{value:!0}),e),NH={};kye(NH,{findRootDir:()=>Cye,getUserDataDir:()=>Oye});xH.exports=Rye(NH);var Xp=_k(C("path")),Nye=_k(C("fs")),wk=_k(C("os")),xye=Nt();function Cye(){try{let e=process.cwd();while(e!==Xp.default.dirname(e)){let t=Xp.default.join(e,".vercel");if(Nye.default.existsSync(t))return e;e=Xp.default.dirname(e)}}catch(e){throw new xye.VercelOidcTokenError("Token refresh only supported in node server environments")}return null}function Oye(){if(process.env.XDG_DATA_HOME)return process.env.XDG_DATA_HOME;switch(wk.default.platform()){case"darwin":return Xp.default.join(wk.default.homedir(),"Library/Application Support");case"linux":return Xp.default.join(wk.default.homedir(),".local/share");case"win32":if(process.env.LOCALAPPDATA)return process.env.LOCALAPPDATA;return null;default:return null}}});var MH=A(function(uQe,LH){var{create:Iye,defineProperty:F_,getOwnPropertyDescriptor:Dye,getOwnPropertyNames:Uye,getPrototypeOf:Pye}=Object,Lye=Object.prototype.hasOwnProperty,Mye=(e,t)=>{for(var r in t)F_(e,r,{get:t[r],enumerable:!0})},OH=(e,t,r,n)=>{if(t&&typeof t==="object"||typeof t==="function"){for(let i of Uye(t))if(!Lye.call(e,i)&&i!==r)F_(e,i,{get:()=>t[i],enumerable:!(n=Dye(t,i))||n.enumerable})}return e},IH=(e,t,r)=>(r=e!=null?Iye(Pye(e)):{},OH(t||!e||!e.__esModule?F_(r,"default",{value:e,enumerable:!0}):r,e)),qye=(e)=>OH(F_({},"__esModule",{value:!0}),e),DH={};Mye(DH,{isValidAccessToken:()=>Fye,readAuthConfig:()=>jye,writeAuthConfig:()=>$ye});LH.exports=qye(DH);var Zp=IH(C("fs")),UH=IH(C("path")),Bye=Ut();function PH(){let e=(0,Bye.getVercelDataDir)();if(!e)throw Error(`Unable to find Vercel CLI data directory. Your platform: ${process.platform}. Supported: darwin, linux, win32.`);return UH.join(e,"auth.json")}function jye(){try{let e=PH();if(!Zp.existsSync(e))return null;let t=Zp.readFileSync(e,"utf8");if(!t)return null;return JSON.parse(t)}catch(e){return null}}function $ye(e){let t=PH(),r=UH.dirname(t);if(!Zp.existsSync(r))Zp.mkdirSync(r,{mode:504,recursive:!0});Zp.writeFileSync(t,JSON.stringify(e,null,2),{mode:384})}function Fye(e,t=0){if(!e.token)return!1;if(typeof e.expiresAt!=="number")return!0;let r=Math.floor(Date.now()/1000),n=t/1000;return e.expiresAt>=r+n}});var $H=A(function(dQe,jH){var{defineProperty:Sk,getOwnPropertyDescriptor:zye,getOwnPropertyNames:Wye}=Object,Hye=Object.prototype.hasOwnProperty,Vye=(e,t)=>{for(var r in t)Sk(e,r,{get:t[r],enumerable:!0})},Gye=(e,t,r,n)=>{if(t&&typeof t==="object"||typeof t==="function"){for(let i of Wye(t))if(!Hye.call(e,i)&&i!==r)Sk(e,i,{get:()=>t[i],enumerable:!(n=zye(t,i))||n.enumerable})}return e},Kye=(e)=>Gye(Sk({},"__esModule",{value:!0}),e),qH={};Vye(qH,{processTokenResponse:()=>Zye,refreshTokenRequest:()=>Xye});jH.exports=Kye(qH);var bk=C("os"),Jye="https://vercel.com",Qye="cl_HYyOPBNtFMfHhaUn9L4QPfTZz6TP47bp",BH=`@vercel/oidc node-${process.version} ${(0,bk.platform)()} (${(0,bk.arch)()}) ${(0,bk.hostname)()}`,Ek=null;async function Yye(){if(Ek)return Ek;let e=`${Jye}/.well-known/openid-configuration`,t=await fetch(e,{headers:{"user-agent":BH}});if(!t.ok)throw Error("Failed to discover OAuth endpoints");let r=await t.json();if(!r||typeof r.token_endpoint!=="string")throw Error("Invalid OAuth discovery response");let n=r.token_endpoint;return Ek=n,n}async function Xye(e){let t=await Yye();return await fetch(t,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded","user-agent":BH},body:new URLSearchParams({client_id:Qye,grant_type:"refresh_token",...e})})}async function Zye(e){let t=await e.json();if(!e.ok){let r=typeof t==="object"&&t&&"error"in t?String(t.error):"Token refresh failed";return[Error(r)]}if(typeof t!=="object"||t===null)return[Error("Invalid token response")];if(typeof t.access_token!=="string")return[Error("Missing access_token in response")];if(t.token_type!=="Bearer")return[Error("Invalid token_type in response")];if(typeof t.expires_in!=="number")return[Error("Missing expires_in in response")];return[null,t]}});var Ut=A(function(lQe,VH){var{create:ewe,defineProperty:z_,getOwnPropertyDescriptor:twe,getOwnPropertyNames:rwe,getPrototypeOf:nwe}=Object,iwe=Object.prototype.hasOwnProperty,owe=(e,t)=>{for(var r in t)z_(e,r,{get:t[r],enumerable:!0})},zH=(e,t,r,n)=>{if(t&&typeof t==="object"||typeof t==="function"){for(let i of rwe(t))if(!iwe.call(e,i)&&i!==r)z_(e,i,{get:()=>t[i],enumerable:!(n=twe(t,i))||n.enumerable})}return e},WH=(e,t,r)=>(r=e!=null?ewe(nwe(e)):{},zH(t||!e||!e.__esModule?z_(r,"default",{value:e,enumerable:!0}):r,e)),swe=(e)=>zH(z_({},"__esModule",{value:!0}),e),HH={};owe(HH,{assertVercelOidcTokenResponse:()=>Ak,findProjectInfo:()=>dwe,getTokenPayload:()=>hwe,getVercelDataDir:()=>awe,getVercelOidcToken:()=>uwe,getVercelToken:()=>cwe,isExpired:()=>pwe,loadToken:()=>fwe,saveToken:()=>lwe});VH.exports=swe(HH);var em=WH(C("path")),Sd=WH(C("fs")),Ef=Nt(),W_=CH(),_f=MH(),FH=$H(),bf=ln();function awe(){let t=(0,W_.getUserDataDir)();if(!t)return null;return em.join(t,"com.vercel.cli")}async function cwe(e){let t=(0,_f.readAuthConfig)();if(!t?.token)throw new bf.AccessTokenMissingError;if((0,_f.isValidAccessToken)(t,e?.expirationBufferMs))return t.token;if(!t.refreshToken)throw(0,_f.writeAuthConfig)({}),new bf.RefreshAccessTokenFailedError("No refresh token available");try{let r=await(0,FH.refreshTokenRequest)({refresh_token:t.refreshToken}),[n,i]=await(0,FH.processTokenResponse)(r);if(n||!i)throw(0,_f.writeAuthConfig)({}),new bf.RefreshAccessTokenFailedError(n);let o={token:i.access_token,expiresAt:Math.floor(Date.now()/1000)+i.expires_in};if(i.refresh_token)o.refreshToken=i.refresh_token;return(0,_f.writeAuthConfig)(o),o.token}catch(r){if((0,_f.writeAuthConfig)({}),r instanceof bf.AccessTokenMissingError||r instanceof bf.RefreshAccessTokenFailedError)throw r;throw new bf.RefreshAccessTokenFailedError(r)}}async function uwe(e,t,r){let n=`https://api.vercel.com/v1/projects/${t}/token?source=vercel-oidc-refresh${r?`&teamId=${r}`:""}`,i=await fetch(n,{method:"POST",headers:{Authorization:`Bearer ${e}`}});if(!i.ok)throw new Ef.VercelOidcTokenError(`Failed to refresh OIDC token: ${i.statusText}`);let o=await i.json();return Ak(o),o}function Ak(e){if(!e||typeof e!=="object")throw TypeError("Vercel OIDC token is malformed. Expected an object. Please run `vc env pull` and try again");if(!("token"in e)||typeof e.token!=="string")throw TypeError("Vercel OIDC token is malformed. Expected a string-valued token property. Please run `vc env pull` and try again")}function dwe(){let e=(0,W_.findRootDir)();if(!e)throw new Ef.VercelOidcTokenError("Unable to find project root directory. Have you linked your project with `vc link?`");let t=em.join(e,".vercel","project.json");if(!Sd.existsSync(t))throw new Ef.VercelOidcTokenError("project.json not found, have you linked your project with `vc link?`");let r=JSON.parse(Sd.readFileSync(t,"utf8"));if(typeof r.projectId!=="string"&&typeof r.orgId!=="string")throw TypeError("Expected a string-valued projectId property. Try running `vc link` to re-link your project.");return{projectId:r.projectId,teamId:r.orgId}}function lwe(e,t){let r=(0,W_.getUserDataDir)();if(!r)throw new Ef.VercelOidcTokenError("Unable to find user data directory. Please reach out to Vercel support.");let n=em.join(r,"com.vercel.token",`${t}.json`),i=JSON.stringify(e);Sd.mkdirSync(em.dirname(n),{mode:504,recursive:!0}),Sd.writeFileSync(n,i),Sd.chmodSync(n,432);return}function fwe(e){let t=(0,W_.getUserDataDir)();if(!t)throw new Ef.VercelOidcTokenError("Unable to find user data directory. Please reach out to Vercel support.");let r=em.join(t,"com.vercel.token",`${e}.json`);if(!Sd.existsSync(r))return null;let n=JSON.parse(Sd.readFileSync(r,"utf8"));return Ak(n),n}function hwe(e){let t=e.split(".");if(t.length!==3)throw new Ef.VercelOidcTokenError("Invalid token. Please run `vc env pull` and try again");let r=t[1].replace(/-/g,"+").replace(/_/g,"/"),n=r.padEnd(r.length+(4-r.length%4)%4,"=");return JSON.parse(Buffer.from(n,"base64").toString("utf8"))}function pwe(e,t=0){return e.exp*1000<Date.now()+t}});var RS={};Ie(RS,{accountSchema:()=>lD,coreSchema:()=>ua,getAuthTables:()=>ye,rateLimitSchema:()=>fD,sessionSchema:()=>Ng,userSchema:()=>xg,verificationSchema:()=>hD});var jI=E(N()),$I=E(P()),Yt="AWS_ACCESS_KEY_ID",Xt="AWS_SECRET_ACCESS_KEY",FI="AWS_SESSION_TOKEN",zI="AWS_CREDENTIAL_EXPIRATION",WI="AWS_CREDENTIAL_SCOPE",HI="AWS_ACCOUNT_ID",wr=(e)=>async()=>{e?.logger?.debug("@aws-sdk/credential-provider-env - fromEnv");let t=process.env[Yt],r=process.env[Xt],n=process.env[FI],i=process.env[zI],o=process.env[WI],s=process.env[HI];if(t&&r){let a={accessKeyId:t,secretAccessKey:r,...n&&{sessionToken:n},...i&&{expiration:new Date(i)},...o&&{credentialScope:o},...s&&{accountId:s}};return jI.setCredentialFeature(a,"CREDENTIALS_ENV_VARS","g"),a}throw new $I.CredentialsProviderError("Unable to find environment variable credentials.",{logger:e?.logger})};function iD(e){return Object.fromEntries(Object.entries(e).map(([t,r])=>[t,{code:t,message:r,toString:()=>t}]))}var S=iD({USER_NOT_FOUND:"User not found",FAILED_TO_CREATE_USER:"Failed to create user",FAILED_TO_CREATE_SESSION:"Failed to create session",FAILED_TO_UPDATE_USER:"Failed to update user",FAILED_TO_GET_SESSION:"Failed to get session",INVALID_PASSWORD:"Invalid password",INVALID_EMAIL:"Invalid email",INVALID_EMAIL_OR_PASSWORD:"Invalid email or password",INVALID_USER:"Invalid user",SOCIAL_ACCOUNT_ALREADY_LINKED:"Social account already linked",PROVIDER_NOT_FOUND:"Provider not found",INVALID_TOKEN:"Invalid token",TOKEN_EXPIRED:"Token expired",ID_TOKEN_NOT_SUPPORTED:"id_token not supported",FAILED_TO_GET_USER_INFO:"Failed to get user info",USER_EMAIL_NOT_FOUND:"User email not found",EMAIL_NOT_VERIFIED:"Email not verified",PASSWORD_TOO_SHORT:"Password too short",PASSWORD_TOO_LONG:"Password too long",USER_ALREADY_EXISTS:"User already exists.",USER_ALREADY_EXISTS_USE_ANOTHER_EMAIL:"User already exists. Use another email.",EMAIL_CAN_NOT_BE_UPDATED:"Email can not be updated",CHANGE_EMAIL_DISABLED:"Change email is disabled",CREDENTIAL_ACCOUNT_NOT_FOUND:"Credential account not found",SESSION_EXPIRED:"Session expired. Re-authenticate to perform this action.",FAILED_TO_UNLINK_LAST_ACCOUNT:"You can't unlink your last account",ACCOUNT_NOT_FOUND:"Account not found",USER_ALREADY_HAS_PASSWORD:"User already has a password. Provide that to delete the account.",CROSS_SITE_NAVIGATION_LOGIN_BLOCKED:"Cross-site navigation login blocked. This request appears to be a CSRF attack.",VERIFICATION_EMAIL_NOT_ENABLED:"Verification email isn't enabled",EMAIL_ALREADY_VERIFIED:"Email is already verified",EMAIL_MISMATCH:"Email mismatch",SESSION_NOT_FRESH:"Session is not fresh",LINKED_ACCOUNT_ALREADY_EXISTS:"Linked account already exists",INVALID_ORIGIN:"Invalid origin",INVALID_CALLBACK_URL:"Invalid callbackURL",INVALID_REDIRECT_URL:"Invalid redirectURL",INVALID_ERROR_CALLBACK_URL:"Invalid errorCallbackURL",INVALID_NEW_USER_CALLBACK_URL:"Invalid newUserCallbackURL",MISSING_OR_NULL_ORIGIN:"Missing or null Origin",CALLBACK_URL_REQUIRED:"callbackURL is required",FAILED_TO_CREATE_VERIFICATION:"Unable to create verification",FIELD_NOT_ALLOWED:"Field not allowed to be set",ASYNC_VALIDATION_NOT_SUPPORTED:"Async validation is not supported",VALIDATION_ERROR:"Validation Error",MISSING_FIELD:"Field is required",METHOD_NOT_ALLOWED_DEFER_SESSION_REQUIRED:"POST method requires deferSessionRefresh to be enabled in session config",BODY_MUST_BE_AN_OBJECT:"Body must be an object",PASSWORD_ALREADY_SET:"User already has a password set"});function jne(){let e=Object.getOwnPropertyDescriptor(Error,"stackTraceLimit");if(e===void 0)return Object.isExtensible(Error);return Object.prototype.hasOwnProperty.call(e,"writable")?e.writable:e.set!==void 0}function oD(e){let t=e.split(`
74
+ at `);if(t.length<=1)return e;return t.splice(1,1),t.join(`
75
+ at `)}function sD(e,t){class r extends e{#e;constructor(...n){if(jne()){let o=Error.stackTraceLimit;Error.stackTraceLimit=0;super(...n);Error.stackTraceLimit=o}else super(...n);let i=Error().stack;if(i)this.#e=oD(i.replace(/^Error/,this.name))}get errorStack(){return this.#e}}return Object.defineProperty(r.prototype,"constructor",{get(){return t},enumerable:!1,configurable:!0}),r}var aD={OK:200,CREATED:201,ACCEPTED:202,NO_CONTENT:204,MULTIPLE_CHOICES:300,MOVED_PERMANENTLY:301,FOUND:302,SEE_OTHER:303,NOT_MODIFIED:304,TEMPORARY_REDIRECT:307,BAD_REQUEST:400,UNAUTHORIZED:401,PAYMENT_REQUIRED:402,FORBIDDEN:403,NOT_FOUND:404,METHOD_NOT_ALLOWED:405,NOT_ACCEPTABLE:406,PROXY_AUTHENTICATION_REQUIRED:407,REQUEST_TIMEOUT:408,CONFLICT:409,GONE:410,LENGTH_REQUIRED:411,PRECONDITION_FAILED:412,PAYLOAD_TOO_LARGE:413,URI_TOO_LONG:414,UNSUPPORTED_MEDIA_TYPE:415,RANGE_NOT_SATISFIABLE:416,EXPECTATION_FAILED:417,"I'M_A_TEAPOT":418,MISDIRECTED_REQUEST:421,UNPROCESSABLE_ENTITY:422,LOCKED:423,FAILED_DEPENDENCY:424,TOO_EARLY:425,UPGRADE_REQUIRED:426,PRECONDITION_REQUIRED:428,TOO_MANY_REQUESTS:429,REQUEST_HEADER_FIELDS_TOO_LARGE:431,UNAVAILABLE_FOR_LEGAL_REASONS:451,INTERNAL_SERVER_ERROR:500,NOT_IMPLEMENTED:501,BAD_GATEWAY:502,SERVICE_UNAVAILABLE:503,GATEWAY_TIMEOUT:504,HTTP_VERSION_NOT_SUPPORTED:505,VARIANT_ALSO_NEGOTIATES:506,INSUFFICIENT_STORAGE:507,LOOP_DETECTED:508,NOT_EXTENDED:510,NETWORK_AUTHENTICATION_REQUIRED:511},cD=class extends Error{status;body;headers;statusCode;constructor(e="INTERNAL_SERVER_ERROR",t=void 0,r={},n=typeof e==="number"?e:aD[e]){super(t?.message,t&&"cause"in t?{cause:t.cause}:void 0);if(this.status=e,this.body=t,this.headers=r,this.statusCode=n,this.name="APIError",this.status=e,this.headers=r,this.statusCode=n,t&&"cause"in t){let{cause:i,...o}=t;this.body=Object.defineProperty(o,"cause",{value:i,writable:!0,configurable:!0});return}this.body=t}},lh=class extends cD{message;issues;constructor(e,t){super(400,{message:e,code:"VALIDATION_ERROR"});this.message=e,this.issues=t,this.issues=t}},Tg=class extends Error{constructor(e){super(e);this.name="BetterCallError"}},xc=Symbol.for("better-call:api-error-headers"),st=sD(cD,Error);var y=class extends Error{constructor(e,t){super(e,t);this.name="BetterAuthError",this.message=e,this.stack=""}},l=class e extends st{constructor(...t){super(...t)}static fromStatus(t,r){return new e(t,r)}static from(t,r,n){let{code:i,message:o}=r;if(n?.cause===void 0)return new e(t,{message:o,code:i});return new e(t,{message:o,code:i,cause:n.cause})}};var vg=63,uD=16;function _e(e){return e.toLowerCase()}function kg(e){return new TextEncoder().encode(e).length}function $ne(e,t){let r="",n=0;for(let i of e){let o=kg(i);if(n+o>t)break;r+=i,n+=o}return r}function Fne(e){let t=2166136261;for(let r=0;r<e.length;r++)t^=e.charCodeAt(r),t=Math.imul(t,16777619);return(t>>>0).toString(16).padStart(8,"0")}function vS(e,t){if(t.name!==void 0){if(t.name.trim().length===0)throw new y("Database index names must contain at least one visible character.");if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(t.name))throw new y("Database index names must start with a letter or underscore and contain only letters, numbers, and underscores.");if(kg(t.name)>vg)throw new y(`Database index names must be at most ${vg} UTF-8 bytes.`);return t.name}let r=t.unique?"uidx":"idx",n=`${e}_${t.fields.join("_")}_${r}`;if(kg(n)<=vg)return n;let i=`_${Fne(n)}_${r}`;return`${$ne(n.slice(0,-r.length-1),vg-kg(i))}${i}`}function Zt(e,t,r){return vS(e,{fields:[t],unique:r})}function dD({fields:e,indexes:t,tableName:r}){let n=(t??[]).map((s)=>{if(s.fields.length===0)throw new y(`Index on table "${r}" must include at least one field.`);if(s.fields.length>uD)throw new y(`Index on table "${r}" can include at most ${uD} fields so it works across supported databases.`);if(new Set(s.fields).size!==s.fields.length)throw new y(`Index on table "${r}" contains the same field more than once.`);if(s.unique&&s.fields.some((h)=>e[h]?.required===!1))throw new y(`Unique index on table "${r}" can only include required fields so its behavior is consistent across databases.`);let a=s.fields.find((h)=>{let p=e[h]?.type;return p==="json"||p==="string[]"||p==="number[]"});if(a)throw new y(`Index on table "${r}" references field "${a}", whose type is not portably indexable.`);let c=(h)=>{let p=e[h];if(!p)throw new y(`Index on table "${r}" references unknown field "${h}".`);return p.fieldName||h},[u,...d]=s.fields,f=[c(u),...d.map(c)];if(new Set(f.map(_e)).size!==f.length)throw new y(`Index on table "${r}" resolves more than one field to the same database column.`);return{columns:f,name:vS(r,{...s,fields:f}),unique:s.unique}}),i=new Map,o=[];for(let s of n){let a=JSON.stringify([s.columns,s.unique??!1]),c=_e(s.name),u=i.get(c);if(u&&u!==a)throw new y(`Database index name "${s.name}" identifies more than one index on table "${r}".`);if(u)continue;i.set(c,a),o.push(s)}return o}function vr({columnName:e,dialect:t,fields:r,indexes:n}){let i=new Map(Object.entries(r).map(([u,d])=>[d.fieldName||u,d])),o=n.filter((u)=>u.columns.includes(e));if(o.length===0)return;let s=t==="mysql"?3072:1700,a=t==="mysql"?4:1,c=t==="mysql"?191:255;return o.reduce((u,d)=>{let f=d.columns.filter((g)=>{let _=i.get(g)?.type;return _==="string"||Array.isArray(_)}).length;if(f===0)return u;let h=(d.columns.length-f)*16,p=Math.floor(Math.max(1,s-h)/a/f);return Math.min(u,p)},c)}function kS(e){let t=new Map;for(let s of e){let a=t.get(s.tableName);if(a){if(a.indexes.length>0||(s.indexes?.length??0)>0)throw new y(`Database schema resolves more than one indexed logical table to "${s.tableName}". Define table-level indexes through one logical schema key instead of aliasing multiple keys to the same database table.`);Object.assign(a.fields,s.fields);continue}let c={fields:{},indexes:[],tableName:s.tableName};Object.assign(c.fields,s.fields),c.indexes.push(...s.indexes??[]),t.set(s.tableName,c)}let r=new Map,n=new Map,i=new Map([...t.keys()].map((s)=>[_e(s),s])),o=new Map;for(let s of t.values())for(let[a,c]of Object.entries(s.fields)){if(!c.index&&!c.unique)continue;let u=Zt(s.tableName,c.fieldName||a,c.unique??!1),d=_e(u);if(i.has(d))throw new y(`Database index name "${u}" conflicts with a table name. Index and table names must be unique across the schema.`);let f=o.get(d);if(f)throw new y(`Database field-level index name "${u}" is used by both table "${f}" and table "${s.tableName}".`);o.set(d,s.tableName)}for(let s of t.values()){let a=dD(s);r.set(s.tableName,[...a]);for(let c of a){let u=_e(c.name);if(i.has(u))throw new y(`Database index name "${c.name}" conflicts with a table name. Index and table names must be unique across the schema.`);let d=o.get(u);if(d)throw new y(`Database index name "${c.name}" is already reserved by field-level index metadata on table "${d}". Remove the duplicate table-level index or give it a distinct name.`);let f=n.get(u);if(f&&f!==s.tableName)throw new y(`Database index name "${c.name}" is used by both table "${f}" and table "${s.tableName}". Index names must be unique across the schema.`);n.set(u,s.tableName)}}return r}function zne(...e){let t=[],r=new Set;for(let n of e.flatMap((i)=>i??[])){let i=JSON.stringify([n.name??null,n.fields,n.unique??!1]);if(r.has(i))continue;r.add(i),t.push(n)}return t}var Wne=(e)=>{let t=(e.plugins??[]).reduce((f,h)=>{let p=h.schema;if(!p)return f;for(let[g,_]of Object.entries(p))f[g]={fields:{...f[g]?.fields,..._.fields},indexes:zne(f[g]?.indexes,_.indexes),modelName:_.modelName||g,disableMigrations:_.disableMigration??f[g]?.disableMigrations};return f},{}),r=e.rateLimit?.storage==="database",n={rateLimit:{modelName:e.rateLimit?.modelName||"rateLimit",fields:{key:{type:"string",unique:!0,required:!0,fieldName:e.rateLimit?.fields?.key||"key"},count:{type:"number",required:!0,fieldName:e.rateLimit?.fields?.count||"count"},lastRequest:{type:"number",bigint:!0,required:!0,fieldName:e.rateLimit?.fields?.lastRequest||"lastRequest",defaultValue:()=>Date.now()}}}},{user:i,session:o,account:s,verification:a,...c}=t,u={verification:{modelName:e.verification?.modelName||"verification",indexes:a?.indexes,fields:{identifier:{type:"string",required:!0,fieldName:e.verification?.fields?.identifier||"identifier",index:!0},value:{type:"string",required:!0,fieldName:e.verification?.fields?.value||"value"},expiresAt:{type:"date",required:!0,fieldName:e.verification?.fields?.expiresAt||"expiresAt"},createdAt:{type:"date",required:!0,defaultValue:()=>new Date,fieldName:e.verification?.fields?.createdAt||"createdAt"},updatedAt:{type:"date",required:!0,defaultValue:()=>new Date,onUpdate:()=>new Date,fieldName:e.verification?.fields?.updatedAt||"updatedAt"},...a?.fields,...e.verification?.additionalFields},order:4}},d={session:{modelName:e.session?.modelName||"session",indexes:o?.indexes,fields:{expiresAt:{type:"date",required:!0,fieldName:e.session?.fields?.expiresAt||"expiresAt"},token:{type:"string",required:!0,fieldName:e.session?.fields?.token||"token",unique:!0},createdAt:{type:"date",required:!0,fieldName:e.session?.fields?.createdAt||"createdAt",defaultValue:()=>new Date},updatedAt:{type:"date",required:!0,fieldName:e.session?.fields?.updatedAt||"updatedAt",onUpdate:()=>new Date},ipAddress:{type:"string",required:!1,fieldName:e.session?.fields?.ipAddress||"ipAddress"},userAgent:{type:"string",required:!1,fieldName:e.session?.fields?.userAgent||"userAgent"},userId:{type:"string",fieldName:e.session?.fields?.userId||"userId",references:{model:"user",field:"id",onDelete:"cascade"},required:!0,index:!0},...o?.fields,...e.session?.additionalFields},order:2}};return{user:{modelName:e.user?.modelName||"user",indexes:i?.indexes,fields:{name:{type:"string",required:!0,fieldName:e.user?.fields?.name||"name",sortable:!0},email:{type:"string",unique:!0,required:!0,fieldName:e.user?.fields?.email||"email",sortable:!0},emailVerified:{type:"boolean",defaultValue:!1,required:!0,fieldName:e.user?.fields?.emailVerified||"emailVerified",input:!1},image:{type:"string",required:!1,fieldName:e.user?.fields?.image||"image"},createdAt:{type:"date",defaultValue:()=>new Date,required:!0,fieldName:e.user?.fields?.createdAt||"createdAt"},updatedAt:{type:"date",defaultValue:()=>new Date,onUpdate:()=>new Date,required:!0,fieldName:e.user?.fields?.updatedAt||"updatedAt"},...i?.fields,...e.user?.additionalFields},order:1},...!e.secondaryStorage||e.session?.storeSessionInDatabase?d:{},account:{modelName:e.account?.modelName||"account",indexes:s?.indexes,fields:{accountId:{type:"string",required:!0,fieldName:e.account?.fields?.accountId||"accountId"},providerId:{type:"string",required:!0,fieldName:e.account?.fields?.providerId||"providerId"},userId:{type:"string",references:{model:"user",field:"id",onDelete:"cascade"},required:!0,fieldName:e.account?.fields?.userId||"userId",index:!0},accessToken:{type:"string",required:!1,returned:!1,fieldName:e.account?.fields?.accessToken||"accessToken"},refreshToken:{type:"string",required:!1,returned:!1,fieldName:e.account?.fields?.refreshToken||"refreshToken"},idToken:{type:"string",required:!1,returned:!1,fieldName:e.account?.fields?.idToken||"idToken"},accessTokenExpiresAt:{type:"date",required:!1,returned:!1,fieldName:e.account?.fields?.accessTokenExpiresAt||"accessTokenExpiresAt"},refreshTokenExpiresAt:{type:"date",required:!1,returned:!1,fieldName:e.account?.fields?.refreshTokenExpiresAt||"refreshTokenExpiresAt"},scope:{type:"string",required:!1,fieldName:e.account?.fields?.scope||"scope"},password:{type:"string",required:!1,returned:!1,fieldName:e.account?.fields?.password||"password"},createdAt:{type:"date",required:!0,fieldName:e.account?.fields?.createdAt||"createdAt",defaultValue:()=>new Date},updatedAt:{type:"date",required:!0,fieldName:e.account?.fields?.updatedAt||"updatedAt",onUpdate:()=>new Date},...s?.fields,...e.account?.additionalFields},order:3},...!e.secondaryStorage||e.verification?.storeInDatabase?u:{},...c,...r?n:{}}};function Rg(e){let t=Wne(e);return{indexesByTable:kS(Object.values(t).filter((r)=>!("disableMigrations"in r)||!r.disableMigrations).map((r)=>({fields:r.fields,indexes:"indexes"in r?r.indexes:void 0,tableName:r.modelName}))),tables:t}}var ye=(e)=>Rg(e).tables;import*as Bu from"zod";var ua=Bu.object({id:Bu.string(),createdAt:Bu.date().default(()=>new Date),updatedAt:Bu.date().default(()=>new Date)});import*as Mo from"zod";var lD=ua.extend({providerId:Mo.string(),accountId:Mo.string(),userId:Mo.coerce.string(),accessToken:Mo.string().nullish(),refreshToken:Mo.string().nullish(),idToken:Mo.string().nullish(),accessTokenExpiresAt:Mo.date().nullish(),refreshTokenExpiresAt:Mo.date().nullish(),scope:Mo.string().nullish(),password:Mo.string().nullish()});import*as ju from"zod";var fD=ju.object({key:ju.string(),count:ju.number(),lastRequest:ju.number()});import*as Cc from"zod";var Ng=ua.extend({userId:Cc.coerce.string(),expiresAt:Cc.date(),token:Cc.string(),ipAddress:Cc.string().nullish(),userAgent:Cc.string().nullish()});import*as Qd from"zod";var xg=ua.extend({email:Qd.string().transform((e)=>e.toLowerCase()),emailVerified:Qd.boolean().default(!1),name:Qd.string(),image:Qd.string().nullish()});import*as fh from"zod";var hD=ua.extend({value:fh.string(),expiresAt:fh.date(),identifier:fh.string()});var Cg=Object.create(null),hh=(e)=>globalThis.process?.env||globalThis.Deno?.env.toObject()||globalThis.__env__||(e?Cg:globalThis),D=new Proxy(Cg,{get(e,t){return hh()[t]??Cg[t]},has(e,t){return t in hh()||t in Cg},set(e,t,r){let n=hh(!0);return n[t]=r,!0},deleteProperty(e,t){if(!t)return!1;let r=hh(!0);return delete r[t],!0},ownKeys(){let e=hh(!0);return Object.keys(e)}});function Hne(e){return e?e!=="false":!1}var ph=D.NODE_ENV??"",ut=ph==="production",$u=()=>ph==="dev"||ph==="development",Ye=()=>ph==="test"||Hne(D.TEST);function U(e,t){if(typeof process<"u"&&process.env)return process.env[e]??t;if(typeof Deno<"u")return Deno.env.get(e)??t;if(typeof Bun<"u")return Bun.env[e]??t;return t}function br(e,t=!0){let r=U(e);if(!r)return t;return r!=="0"&&r.toLowerCase()!=="false"&&r!==""}var jr=Object.freeze({get BETTER_AUTH_SECRET(){return U("BETTER_AUTH_SECRET")},get AUTH_SECRET(){return U("AUTH_SECRET")},get BETTER_AUTH_TELEMETRY(){return U("BETTER_AUTH_TELEMETRY")},get BETTER_AUTH_TELEMETRY_ID(){return U("BETTER_AUTH_TELEMETRY_ID")},get NODE_ENV(){return U("NODE_ENV","development")},get PACKAGE_VERSION(){return U("PACKAGE_VERSION","0.0.0")},get BETTER_AUTH_TELEMETRY_ENDPOINT(){return U("BETTER_AUTH_TELEMETRY_ENDPOINT","")}});var mh=1,qi=4,da=8,qo=24,pD={eterm:qi,cons25:qi,console:qi,cygwin:qi,dtterm:qi,gnome:qi,hurd:qi,jfbterm:qi,konsole:qi,kterm:qi,mlterm:qi,mosh:qo,putty:qi,st:qi,"rxvt-unicode-24bit":qo,terminator:qo,"xterm-kitty":qo},Vne=new Map(Object.entries({APPVEYOR:da,BUILDKITE:da,CIRCLECI:qo,DRONE:da,GITEA_ACTIONS:qo,GITHUB_ACTIONS:qo,GITLAB_CI:da,TRAVIS:da})),Gne=[/ansi/,/color/,/linux/,/direct/,/^con[0-9]*x[0-9]/,/^rxvt/,/^screen/,/^xterm/,/^vt100/,/^vt220/];function Og(){if(U("FORCE_COLOR")!==void 0)switch(U("FORCE_COLOR")){case"":case"1":case"true":return qi;case"2":return da;case"3":return qo;default:return mh}if(U("NODE_DISABLE_COLORS")!==void 0&&U("NODE_DISABLE_COLORS")!==""||U("NO_COLOR")!==void 0&&U("NO_COLOR")!==""||U("TERM")==="dumb")return mh;if(U("TMUX"))return qo;if("TF_BUILD"in D&&"AGENT_NAME"in D)return qi;if("CI"in D){for(let{0:e,1:t}of Vne)if(e in D)return t;if(U("CI_NAME")==="codeship")return da;return mh}if("TEAMCITY_VERSION"in D)return/^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.exec(U("TEAMCITY_VERSION"))!==null?qi:mh;switch(U("TERM_PROGRAM")){case"iTerm.app":if(!U("TERM_PROGRAM_VERSION")||/^[0-2]\./.exec(U("TERM_PROGRAM_VERSION"))!==null)return da;return qo;case"HyperTerm":case"MacTerm":return qo;case"Apple_Terminal":return da}if(U("COLORTERM")==="truecolor"||U("COLORTERM")==="24bit")return qo;if(U("TERM")){if(/truecolor/.exec(U("TERM"))!==null)return qo;if(/^xterm-256/.exec(U("TERM"))!==null)return da;let e=U("TERM").toLowerCase();if(pD[e])return pD[e];if(Gne.some((t)=>t.exec(e)!==null))return qi}if(U("COLORTERM"))return qi;return mh}var gh=Symbol.for("better-auth:global"),yh=null,Kne={},NS="1.7.12";function Ha(){if(!globalThis[gh])globalThis[gh]={version:NS,epoch:1,context:Kne},yh=globalThis[gh];if(yh=globalThis[gh],yh.version!==NS)yh.version=NS,yh.epoch++;return globalThis[gh]}function Ig(){return Ha().context.endpointContextAsyncStorage?.getStore()}function Vr(){return Ha().version}var Ei={reset:"\x1B[0m",bright:"\x1B[1m",dim:"\x1B[2m",undim:"\x1B[22m",underscore:"\x1B[4m",blink:"\x1B[5m",reverse:"\x1B[7m",hidden:"\x1B[8m",fg:{black:"\x1B[30m",red:"\x1B[31m",green:"\x1B[32m",yellow:"\x1B[33m",blue:"\x1B[34m",magenta:"\x1B[35m",cyan:"\x1B[36m",white:"\x1B[37m"},bg:{black:"\x1B[40m",red:"\x1B[41m",green:"\x1B[42m",yellow:"\x1B[43m",blue:"\x1B[44m",magenta:"\x1B[45m",cyan:"\x1B[46m",white:"\x1B[47m"}},Dg=["debug","info","success","warn","error"];function Xd(e,t){return Dg.indexOf(t)>=Dg.indexOf(e)}var Jne={info:Ei.fg.blue,success:Ei.fg.green,warn:Ei.fg.yellow,error:Ei.fg.red,debug:Ei.fg.magenta},Qne=(e,t,r)=>{let n=new Date().toISOString();if(r)return`${Ei.dim}${n}${Ei.reset} ${Jne[e]}${e.toUpperCase()}${Ei.reset} ${Ei.bright}[Better Auth]:${Ei.reset} ${t}`;return`${n} ${e.toUpperCase()} [Better Auth]: ${t}`},Xe=(e)=>{let t=e?.disabled!==!0,r=e?.level??"warn",n=e?.disableColors!==void 0?!e.disableColors:Og()!==1,i=(o,s,a=[])=>{if(!t||!Xd(r,o))return;let c=Qne(o,s,n);if(!e||typeof e.log!=="function"){if(o==="error")console.error(c,...a);else if(o==="warn")console.warn(c,...a);else console.log(c,...a);return}e.log(o==="success"?"info":o,s,...a)};return{...Object.fromEntries(Dg.map((o)=>[o,(...[s,...a])=>i(o,s,a)])),get level(){return r}}},Yne=Xe(),Yd=()=>{let e=Ig()?.context.logger;return e&&e!==T?e:Yne},T={debug:(...e)=>Yd().debug(...e),info:(...e)=>Yd().info(...e),success:(...e)=>Yd().success(...e),warn:(...e)=>Yd().warn(...e),error:(...e)=>Yd().error(...e),get level(){return Yd().level}};function sr(e,{usePlural:t=!1}={}){let r={};for(let n of Object.values(ye(e))){let i=t?`${n.modelName}s`:n.modelName,o=r[i]??={fields:{},disableMigrations:!0};for(let[s,a]of Object.entries(n.fields))o.fields[a.fieldName||s]=a;o.disableMigrations=o.disableMigrations&&!!n.disableMigrations}return r}function dt(e,t){let r=[];for(let[n,i]of Object.entries(e)){if(i.disableMigrations)continue;let o=t.find((a)=>a.name===n&&(i.schema===void 0||a.schema===i.schema));if(!o){r.push({kind:"missing-table",table:n});continue}let s=new Set([i.idColumn??"id",...Object.keys(i.fields)]);for(let a of s)if(!o.columns.some((c)=>c.name===a))r.push({kind:"missing-column",table:n,column:a});for(let a of o.columns){if(s.has(a.name)||a.nullable||a.hasDefault)continue;r.push({kind:"unexpected-required-column",table:n,column:a.name})}}return r}var xS={database:"Run `npx auth migrate` to add it.",drizzle:"Run `npx auth generate` to refresh the Drizzle schema, then apply it with your migration tool.",prisma:"Run `npx auth generate` to refresh the Prisma schema, then run `prisma migrate`."},Xne={database:"Drop the column, make it nullable, or give it a database default.",drizzle:"Remove it from the Drizzle schema, make it nullable, or give it a default, then apply the change with your migration tool.",prisma:"Remove it from the Prisma schema, make it optional, or give it a default, then run `prisma migrate`."},Zne={database:"Database",drizzle:"Drizzle",prisma:"Prisma"};function Xr(e,t){switch(e.kind){case"missing-table":return`Table "${e.table}" is missing. ${xS[t]}`;case"missing-column":return`Column "${e.column}" is missing from table "${e.table}". ${xS[t]}`;case"unexpected-required-column":{let r=e.column==="issuer"?" If this column came from Better Auth 1.7.0 through 1.7.2, follow the upgrade guide before removing it: https://www.better-auth.com/docs/guides/1-7-upgrade-guide":"";return`Column "${e.column}" on table "${e.table}" is required but Better Auth never writes it, so every insert into "${e.table}" fails. ${Xne[t]}${r}`}}}var eie={database:"Make the listed columns nullable, give them defaults, or remove them.",drizzle:"Make the listed columns nullable in your Drizzle schema, give them defaults, or remove them.",prisma:"Make the listed fields optional in your Prisma schema, give them defaults, or remove them."},tie={...xS,database:"Run `npx auth migrate` to add the missing tables and columns."};function rie(e,t){let r=[],n=[],i=[],o=new Set,s=!1;for(let u of e)switch(u.kind){case"missing-table":r.push(u.table);break;case"missing-column":n.push(`${u.table}.${u.column}`);break;case"unexpected-required-column":i.push(`${u.table}.${u.column}`),o.add(u.table),s||=u.column==="issuer";break}let a=[`${Zne[t]} schema mismatch`];if(r.length)a.push(` Missing tables
76
+ ${r.join(", ")}`);if(n.length)a.push(` Missing columns
77
+ ${n.join(`
78
+ `)}`);if(i.length)a.push(` Required columns Better Auth never writes
79
+ ${i.join(`
80
+ `)}`),a.push(` Inserts into ${[...o].join(", ")} will fail.`);let c=[];if(i.length)c.push(eie[t]);if(r.length||n.length||i.length&&t!=="database")c.push(tie[t]);if(c.length)a.push(` help: ${c.join(`
81
+ `)}`);if(s)a.push(` note: If this column came from Better Auth 1.7.0 through 1.7.2,
82
+ follow the upgrade guide before removing it:
83
+ https://www.better-auth.com/docs/guides/1-7-upgrade-guide`);return a.join(`
84
+
85
+ `)}var ir=class extends y{code="SCHEMA_MISMATCH";constructor(e,t){super(rie(e,t));this.findings=e,this.source=t}};function ar(e){return e.advanced?.database?.validateSchema!==!1}var OS=new WeakMap,CS=new WeakMap;function Zr(e){let t=CS.get(e);if(t)t.value++}function cr(e,t,r={}){let n=r.runtimeEnabled??!0;OS.set(e,{check:t,runtimeEnabled:n})}function en(e){return OS.get(e)?.check}function lr(e){let t=OS.get(e);return t?.runtimeEnabled?t.check:void 0}function ur(e,t,r){let n=r?CS.get(r):void 0;if(r&&!n)n={value:0},CS.set(r,n);let i=n?.value,o=!1,s,a=function c(){let u=n?.value;if(i!==u)i=u,o=!1,s=void 0;if(o)return;return s??=Promise.resolve().then(e).then((d)=>{if(n?.value!==u)return c();if(d.length)throw new ir(d,t);if(i===u)o=!0},(d)=>{if(n?.value!==u)return c();if(i===u)s=void 0;throw d})};return a.source=t,a}function mD(e){switch(e){case"a-z":return"abcdefghijklmnopqrstuvwxyz";case"A-Z":return"ABCDEFGHIJKLMNOPQRSTUVWXYZ";case"0-9":return"0123456789";case"-_":return"-_";default:throw Error(`Unsupported alphabet: ${e}`)}}function vt(...e){let t=e.map(mD).join("");if(t.length===0)throw Error("No valid characters provided for random string generation.");let r=t.length;return(n,...i)=>{if(n<=0)throw Error("Length must be a positive integer.");let o=t,s=r;if(i.length>0)o=i.map(mD).join(""),s=o.length;let a=Math.floor(256/s)*s,c=new Uint8Array(n*2),u=c.length,d="",f=u,h;while(d.length<n){if(f>=u)crypto.getRandomValues(c),f=0;if(h=c[f++],h<a)d+=o[h%s]}return d}}var xe=(e)=>vt("a-z","A-Z","0-9")(e||32);var rs=({usePlural:e,schema:t})=>(n)=>{let i=(s)=>{if(t[s])return s;return Object.entries(t).find(([a,c])=>c.modelName===s)?.[0]};if(e&&n.charAt(n.length-1)==="s"){let s=i(n.slice(0,-1));if(s)return s}let o=i(n);if(!o)throw new y(`Model "${n}" not found in schema`);return o};function Fu(e){if(typeof e==="string")return new TextEncoder().encode(e);if(!ArrayBuffer.isView(e))return e;if(e.buffer instanceof ArrayBuffer)return e;return new Uint8Array(e.buffer,e.byteOffset,e.byteLength).slice()}function wh(e){if(typeof e==="string")return new TextEncoder().encode(e);return new Uint8Array(e)}function Ug(e){return e?"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_":"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"}function gD(e,t,r){let n="",i=0,o=0;for(let s of e){i=i<<8|s,o+=8;while(o>=6)o-=6,n+=t[i>>o&63]}if(o>0)n+=t[i<<6-o&63];if(r){let s=(4-n.length%4)%4;n+="=".repeat(s)}return n}function yD(e,t){let r=new Map;for(let s=0;s<t.length;s++)r.set(t[s],s);let n=[],i=0,o=0;for(let s of e){if(s==="=")break;let a=r.get(s);if(a===void 0)throw Error(`Invalid Base64 character: ${s}`);if(i=i<<6|a,o+=6,o>=8)o-=8,n.push(i>>o&255)}return Uint8Array.from(n)}var fe={encode(e,t={}){let r=Ug(!1);return gD(wh(e),r,t.padding??!0)},decode(e){if(typeof e!=="string")e=new TextDecoder().decode(e);let t=Ug(e.includes("-")||e.includes("_"));return yD(e,t)}},po={encode(e,t={}){let r=Ug(!0);return gD(wh(e),r,t.padding??!0)},decode(e){return yD(e,Ug(e.includes("-")||e.includes("_")))}};function wD(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in e&&e.BYTES_PER_ELEMENT===1}var IS=(e)=>e?`"${e}" `:"";function _h(e,t=""){if(typeof e!=="number")throw TypeError(IS(t)+"expected number, got "+typeof e);if(!Number.isSafeInteger(e)||e<0)throw RangeError(IS(t)+"expected integer >= 0, got "+e);return e}function Va(e,t,r=""){if(wD(e)&&(t===void 0||e.length===t))return e;if(t!==void 0)_h(t,"length");let n=wD(e),i=t!==void 0?` of length ${t}`:"",o=n?`length=${e.length}`:`type=${typeof e}`,s=IS(r)+"expected Uint8Array"+i+", got "+o;if(!n)throw TypeError(s);throw RangeError(s)}function bh(e){if(typeof e!=="function"||typeof e.create!=="function")throw TypeError("expected hash wrapped by utils.createHasher");if(_h(e.outputLen),_h(e.blockLen),e.outputLen<1||e.blockLen<1)throw Error("hash blockLen / outputLen must be >= 1")}var nie=(e,t)=>{if(e===null||typeof e!=="object"||Array.isArray(e))throw TypeError((t==="object"?"":`"${t}" `)+"expected object, got type="+typeof e)},_D=(e,t)=>{nie(e,t);let r=Object.getPrototypeOf(e);if(r!==Object.prototype&&r!==null)throw TypeError(`"${t}" expected plain object`);if(Object.hasOwn(e,"__proto__"))throw TypeError(`"${t}.__proto__" is not allowed`)};function Zd(e,t=!0){if(e.destroyed)throw Error("hash was destroyed");if(t&&e.finished)throw Error("digest() was already called")}function Pg(e,t){Va(e,void 0,"output");let r=t.outputLen;if(!(e.length>=r))throw RangeError('"output" expected length >= '+r)}function Ns(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function Lg(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function xs(e,t){return e<<32-t|e>>>t}var ED=(()=>typeof Uint8Array.from([]).toHex==="function"&&typeof Uint8Array.fromHex==="function")(),iie=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));function SD(e){if(Va(e),ED)return e.toHex();let t="";for(let r=0;r<e.length;r++)t+=iie[e[r]];return t}function bD(e){return e>=48&&e<=57?e-48:e>=65&&e<=70?e-55:e>=97&&e<=102?e-87:void 0}function AD(e){if(typeof e!=="string")throw TypeError("hex string expected, got "+typeof e);if(ED)try{return Uint8Array.fromHex(e)}catch(i){if(i instanceof SyntaxError)throw RangeError(i.message);throw i}let t=e.length,r=t/2;if(t%2)throw RangeError("hex string expected, got unpadded hex of length "+t);let n=new Uint8Array(r);for(let i=0,o=0;i<r;i++,o+=2){let s=bD(e.charCodeAt(o)),a=bD(e.charCodeAt(o+1));if(s===void 0||a===void 0){let c=e[o]+e[o+1];throw RangeError('hex string expected, got non-hex character "'+c+'" at index '+o)}n[i]=s*16+a}return n}function Mg(e){if(typeof e!=="string")throw TypeError("string expected");let t=new TextEncoder().encode(e);try{return new Uint8Array(t)}finally{Ns(t)}}function oie(e,t,r="opts"){if(_D(e,"defaults"),t!==void 0)_D(t,r);return Object.assign(Object.create(null),e,t)}function TD(e,t={}){if(typeof e!=="function")throw TypeError('"hashCons" expected function, got type='+typeof e);t=oie({},t,"info");let r=(i,o)=>e(o).update(i).digest(),n=e(void 0);return r.outputLen=n.outputLen,r.blockLen=n.blockLen,r.canXOF=n.canXOF,r.create=(i)=>e(i),Object.assign(r,t),Object.freeze(r)}var vD=(e)=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,e])});var kD=(e)=>AD(e),Eh={encode:(e)=>{let t=wh(e);if(t.byteLength===0)return"";let r="";for(let n of t)r+=n.toString(16).padStart(2,"0");return r},decode:(e)=>{if(!e)return"";if(typeof e==="string")return new TextDecoder().decode(kD(e));return new TextDecoder().decode(e)},toBytes:kD};var RD=!1;function Sh(e,t){let r=t.advanced?.database?.generateId;if(r==="serial"&&!RD)RD=!0,T.warn('Single-use checks (such as SAML assertion IDs, DPoP proofs, and private_key_jwt assertions) need string ids and are not enforced with `advanced.database.generateId: "serial"`.');if(r!=="uuid")return po.encode(e,{padding:!1});let n=e.slice(0,16);n[6]=n[6]&15|80,n[8]=n[8]&63|128;let i=Eh.encode(n);return`${i.slice(0,8)}-${i.slice(8,12)}-${i.slice(12,16)}-${i.slice(16,20)}-${i.slice(20)}`}var qg=({usePlural:e,schema:t,disableIdGeneration:r,options:n,customIdGenerator:i,supportsUUIDs:o})=>{let s=rs({usePlural:e,schema:t});return({customModelName:c,forceAllowId:u})=>{let d=n.advanced?.database?.generateId==="serial",f=n.advanced?.database?.generateId==="uuid",h=(()=>{if(r)return!1;else if(d&&!u)return!1;else if(f)return!o;else return!0})(),p=s(c??"id");return{type:d?"number":"string",required:h?!0:!1,...h?{defaultValue(){if(r)return;let g=n.advanced?.database?.generateId;if(g===!1||g==="serial")return;if(typeof g==="function")return g({model:p});if(g==="uuid")return crypto.randomUUID();if(i)return i({model:p});return xe()}}:{},transform:{input:(g)=>{if(!g)return;if(d){let _=Number(g);if(isNaN(_))return;return _}if(f){if(h&&!u)return g;if(r)return;if(u&&typeof g==="string")if(/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(g))return g;else{let _=Error().stack?.split(`
86
+ `).filter((R,O)=>O!==1).join(`
87
+ `).replace("Error:","");T.warn("[Adapter Factory] - Invalid UUID value for field `id` provided when `forceAllowId` is true. Generating a new UUID.",_)}if(o)return;if(typeof g!=="string"&&!o)return crypto.randomUUID();return}return g},output:(g)=>{if(!g)return;return String(g)}}}}};function ND(e){return on(e).schema}function on(e){let{indexesByTable:t,tables:r}=Rg(e),n=new Map,i={};for(let o in r){let s=r[o],a=s.fields,c={};if(Object.entries(a).forEach(([u,d])=>{let f=d.references,h=f?r[f.model]:void 0,p=f&&h?{...d,references:{...f,model:h.modelName}}:d;if(c[d.fieldName||u]=p,f)n.set(p,{modelKey:f.model,fieldKey:f.field})}),i[s.modelName]){if(i[s.modelName].fields={...i[s.modelName].fields,...c},s.disableMigrations)i[s.modelName].disableMigrations=!0;continue}i[s.modelName]={fields:c,order:s.order||1/0,disableMigrations:s.disableMigrations}}for(let[o,s]of t)if(i[o])i[o].indexes=s;return{schema:i,tables:r,referenceKeys:n}}function mo(e){return typeof e>"u"||e===void 0}function Ln(e){return typeof e==="string"}function Cs(e){return typeof e==="number"}function Ga(e){return typeof e==="boolean"}function Oc(e){return e===null}function Bg(e){return e instanceof Date}function Ic(e){return typeof e==="bigint"}function xD(e){return typeof Buffer<"u"&&Buffer.isBuffer(e)}function qn(e){return typeof e==="function"}function wi(e){return typeof e==="object"&&e!==null}function m(e){return Object.freeze(e)}function Ah(e){if(oo(e))return e;else return[e]}function oo(e){return Array.isArray(e)}function go(e){return e}var dn=m({is(e){return e.kind==="AlterTableNode"},create(e){return m({kind:"AlterTableNode",table:e})},cloneWithTableProps(e,t){return m({...e,...t})},cloneWithColumnAlteration(e,t){return m({...e,columnAlterations:e.columnAlterations?[...e.columnAlterations,t]:[t]})}});var $t=m({is(e){return e.kind==="IdentifierNode"},create(e){return m({kind:"IdentifierNode",name:e})}});var Os=m({is(e){return e.kind==="CreateIndexNode"},create(e){return m({kind:"CreateIndexNode",name:$t.create(e)})},cloneWith(e,t){return m({...e,...t})},cloneWithColumns(e,t){return m({...e,columns:[...e.columns||[],...t]})}});var jg=m({is(e){return e.kind==="CreateSchemaNode"},create(e,t){return m({kind:"CreateSchemaNode",schema:$t.create(e),...t})},cloneWith(e,t){return m({...e,...t})}});var CD=["preserve rows","delete rows","drop"],so=m({is(e){return e.kind==="CreateTableNode"},create(e){return m({kind:"CreateTableNode",table:e,columns:m([])})},cloneWithColumn(e,t){return m({...e,columns:m([...e.columns,t])})},cloneWithConstraint(e,t){return m({...e,constraints:e.constraints?m([...e.constraints,t]):m([t])})},cloneWithFrontModifier(e,t){return m({...e,frontModifiers:e.frontModifiers?m([...e.frontModifiers,t]):m([t])})},cloneWithEndModifier(e,t){return m({...e,endModifiers:e.endModifiers?m([...e.endModifiers,t]):m([t])})},cloneWith(e,t){return m({...e,...t})}});var ao=m({is(e){return e.kind==="SchemableIdentifierNode"},create(e){return m({kind:"SchemableIdentifierNode",identifier:$t.create(e)})},createWithSchema(e,t){return m({kind:"SchemableIdentifierNode",schema:$t.create(e),identifier:$t.create(t)})}});var Dc=m({is(e){return e.kind==="DropIndexNode"},create(e,t){return m({kind:"DropIndexNode",name:ao.create(e),...t})},cloneWith(e,t){return m({...e,...t})}});var Th=m({is(e){return e.kind==="DropSchemaNode"},create(e,t){return m({kind:"DropSchemaNode",schema:$t.create(e),...t})},cloneWith(e,t){return m({...e,...t})}});var vh=m({is(e){return e.kind==="DropTableNode"},create(e,t){return m({kind:"DropTableNode",table:e,...t})},cloneWith(e,t){return m({...e,...t})}});var Bi=m({is(e){return e.kind==="AliasNode"},create(e,t){return m({kind:"AliasNode",node:e,alias:t})}});var co=m({is(e){return e.kind==="TableNode"},create(e){return m({kind:"TableNode",table:ao.create(e)})},createWithSchema(e,t){return m({kind:"TableNode",table:ao.createWithSchema(e,t)})}});function Kn(e){return wi(e)&&qn(e.toOperationNode)}function $g(e){return wi(e)&&"expressionType"in e&&Kn(e)}function OD(e){return wi(e)&&"expression"in e&&Ln(e.alias)&&Kn(e)}var la=m({is(e){return e.kind==="SelectModifierNode"},create(e,t){return m({kind:"SelectModifierNode",modifier:e,of:t})},createWithExpression(e){return m({kind:"SelectModifierNode",rawModifier:e})}});var To=m({is(e){return e.kind==="AndNode"},create(e,t){return m({kind:"AndNode",left:e,right:t})}});var Is=m({is(e){return e.kind==="OrNode"},create(e,t){return m({kind:"OrNode",left:e,right:t})}});var Fg=m({is(e){return e.kind==="OnNode"},create(e){return m({kind:"OnNode",on:e})},cloneWithOperation(e,t,r){return m({...e,on:t==="And"?To.create(e.on,r):Is.create(e.on,r)})}});var Ds=m({is(e){return e.kind==="JoinNode"},create(e,t){return m({kind:"JoinNode",joinType:e,table:t,on:void 0})},createWithOn(e,t,r){return m({kind:"JoinNode",joinType:e,table:t,on:Fg.create(r)})},cloneWithOn(e,t){return m({...e,on:e.on?Fg.cloneWithOperation(e.on,"And",t):Fg.create(t)})}});var Uc=m({is(e){return e.kind==="BinaryOperationNode"},create(e,t,r){return m({kind:"BinaryOperationNode",leftOperand:e,operator:t,rightOperand:r})}});var sie=["=","==","!=","<>",">",">=","<","<=","in","not in","is","is not","like","not like","match","ilike","not ilike","@>","<@","^@","&&","?","?&","?|","!<","!>","<=>","!~","~","~*","!~*","@@","@@@","!!","<->","regexp","is distinct from","is not distinct from"],aie=["+","-","*","/","%","^","&","|","#","<<",">>"],ID=["->","->>"],cie=[...sie,...aie,"&&","||"],uie=["exists","not exists"],die=["not","-",...uie],DD=[...cie,...ID,...die,"between","between symmetric"],Bo=m({is(e){return e.kind==="OperatorNode"},create(e){return m({kind:"OperatorNode",operator:e})}});function DS(e){return Ln(e)&&ID.includes(e)}var Hr=m({is(e){return e.kind==="ColumnNode"},create(e){return m({kind:"ColumnNode",column:$t.create(e)})}});var el=m({is(e){return e.kind==="SelectAllNode"},create(){return m({kind:"SelectAllNode"})}});var Pc=m({is(e){return e.kind==="ReferenceNode"},create(e,t){return m({kind:"ReferenceNode",table:t,column:e})},createSelectAll(e){return m({kind:"ReferenceNode",table:e,column:el.create()})}});class US{#e;get dynamicReference(){return this.#e}get refType(){return}constructor(e){this.#e=e}toOperationNode(){return PS(this.#e)}}function zg(e){return wi(e)&&Kn(e)&&Ln(e.dynamicReference)}var Us=m({is(e){return e.kind==="OrderByItemNode"},create(e,t){return m({kind:"OrderByItemNode",orderBy:e,direction:t})},cloneWith(e,t){return m({...e,...t})}});var pn=m({is(e){return e.kind==="RawNode"},create(e,t){return m({kind:"RawNode",sqlFragments:m(e),parameters:m(t)})},createWithSql(e){return pn.create([e],[])},createWithChild(e){return pn.create(["",""],[e])},createWithChildren(e){return pn.create(Array(e.length+1).fill(""),e)}});var UD=m({is(e){return e.kind==="CollateNode"},create(e){return m({kind:"CollateNode",collation:$t.create(e)})}});class Lc{#e;constructor(e){this.#e=m(e)}desc(){return new Lc({node:Us.cloneWith(this.#e.node,{direction:pn.createWithSql("desc")})})}asc(){return new Lc({node:Us.cloneWith(this.#e.node,{direction:pn.createWithSql("asc")})})}nullsLast(){return new Lc({node:Us.cloneWith(this.#e.node,{nulls:"last"})})}nullsFirst(){return new Lc({node:Us.cloneWith(this.#e.node,{nulls:"first"})})}collate(e){return new Lc({node:Us.cloneWith(this.#e.node,{collation:UD.create(e)})})}toOperationNode(){return this.#e.node}}var PD=new Set;function fa(e){if(PD.has(e))return;PD.add(e),console.log(e)}function MS(e){return e==="asc"||e==="desc"}function $o(e){if(e.length===2)return[LS(e[0],e[1])];if(e.length===1){let[t]=e;if(Array.isArray(t))return fa("orderBy(array) is deprecated, use multiple orderBy calls instead."),t.map((r)=>LS(r));return[LS(t)]}throw Error(`Invalid number of arguments at order by! expected 1-2, received ${e.length}`)}function LS(e,t){let r=lie(e);if(Us.is(r)){if(t)throw Error("Cannot specify direction twice!");return r}return LD(r,t)}function lie(e){if(Ka(e))return vo(e);if(zg(e))return e.toOperationNode();let[t,r]=e.split(" ");if(r)return fa("`orderBy('column asc')` is deprecated. Use `orderBy('column', 'asc')` instead."),LD(jo(t),r);return jo(e)}function LD(e,t){if(typeof t==="string"){if(!MS(t))throw Error(`Invalid order by direction: ${t}`);return Us.create(e,pn.createWithSql(t))}if($g(t))return fa("`orderBy(..., expr)` is deprecated. Use `orderBy(..., 'asc')` or `orderBy(..., (ob) => ...)` instead."),Us.create(e,t.toOperationNode());let r=Us.create(e);if(!t)return r;return t(new Lc({node:r})).toOperationNode()}var tl=m({is(e){return e.kind==="JSONReferenceNode"},create(e,t){return m({kind:"JSONReferenceNode",reference:e,traversal:t})},cloneWithTraversal(e,t){return m({...e,traversal:t})}});var Wg=m({is(e){return e.kind==="JSONOperatorChainNode"},create(e){return m({kind:"JSONOperatorChainNode",operator:e,values:m([])})},cloneWithValue(e,t){return m({...e,values:m([...e.values,t])})}});var Mc=m({is(e){return e.kind==="JSONPathNode"},create(e){return m({kind:"JSONPathNode",inOperator:e,pathLegs:m([])})},cloneWithLeg(e,t){return m({...e,pathLegs:m([...e.pathLegs,t])})}});function PS(e){if(Ln(e))return jo(e);return e.toOperationNode()}function Ja(e){if(oo(e))return e.map((t)=>Yi(t));else return[Yi(e)]}function Yi(e){if(Ka(e))return vo(e);return PS(e)}function MD(e,t){let r=jo(e);if(DS(t))return tl.create(r,Wg.create(Bo.create(t)));let n=t.slice(0,-1);if(DS(n))return tl.create(r,Mc.create(Bo.create(n)));throw Error(`Invalid JSON operator: ${t}`)}function jo(e){if(!e.includes("."))return Pc.create(Hr.create(e));let r=e.split(".").map(BS);if(r.length===3)return fie(r);if(r.length===2)return hie(r);throw Error(`invalid column reference ${e}`)}function qD(e){if(e.includes(" as ")){let[r,n]=e.split(" as ").map(BS);return Bi.create(jo(r),$t.create(n))}else return jo(e)}function qS(e){return Hr.create(e)}function rl(e){if(e.includes(" ")){let[r,n]=e.split(" ").map(BS);if(!MS(n))throw Error(`invalid order direction "${n}" next to "${r}"`);return $o([r,n])[0]}else return qS(e)}function fie(e){let[t,r,n]=e;return Pc.create(Hr.create(n),co.createWithSchema(t,r))}function hie(e){let[t,r]=e;return Pc.create(Hr.create(r),co.create(t))}function BS(e){return e.trim()}var Hg=m({is(e){return e.kind==="PrimitiveValueListNode"},create(e){return m({kind:"PrimitiveValueListNode",values:m([...e])})}});var qc=m({is(e){return e.kind==="ValueListNode"},create(e){return m({kind:"ValueListNode",values:m(e)})}});var Ti=m({is(e){return e.kind==="ValueNode"},create(e){return m({kind:"ValueNode",value:e})},createImmediate(e){return m({kind:"ValueNode",value:e,immediate:!0})}});function BD(e){if(oo(e))return pie(e);return zn(e)}function zn(e){if(Ka(e))return vo(e);return Ti.create(e)}function Vg(e){return Cs(e)||Ga(e)||Oc(e)}function kh(e){if(!Vg(e))throw Error(`unsafe immediate value ${JSON.stringify(e)}`);return Ti.createImmediate(e)}function pie(e){if(e.some(Ka))return qc.create(e.map((t)=>zn(t)));return Hg.create(e)}var Fo=m({is(e){return e.kind==="ParensNode"},create(e){return m({kind:"ParensNode",node:e})}});function Vn(e){if(e.length===3)return Gg(e[0],e[1],e[2]);else if(e.length===1)return zn(e[0]);throw Error(`invalid arguments: ${JSON.stringify(e)}`)}function Gg(e,t,r){if(mie(t)&&$D(r))return Uc.create(Yi(e),jS(t),Ti.createImmediate(r));return Uc.create(Yi(e),jS(t),BD(r))}function ji(e,t,r){return Uc.create(Yi(e),jS(t),Yi(r))}function $S(e,t){return nl(Object.entries(e).filter(([,r])=>!mo(r)).map(([r,n])=>Gg(r,$D(n)?"is":"=",n)),t)}function nl(e,t,r=!0){let n=t==="and"?To.create:Is.create;if(e.length===0)return Uc.create(Ti.createImmediate(1),Bo.create("="),Ti.createImmediate(t==="and"?1:0));let i=jD(e[0]);for(let o=1;o<e.length;++o)i=n(i,jD(e[o]));if(e.length>1&&r)return Fo.create(i);return i}function mie(e){return e==="is"||e==="is not"}function $D(e){return Oc(e)||Ga(e)}function jS(e){if(Ln(e)&&DD.includes(e))return Bo.create(e);if(Kn(e))return e.toOperationNode();throw Error(`invalid operator ${JSON.stringify(e)}`)}function jD(e){return Kn(e)?e.toOperationNode():e}var Qa=m({is(e){return e.kind==="OrderByNode"},create(e){return m({kind:"OrderByNode",items:m([...e])})},cloneWithItems(e,t){return m({...e,items:m([...e.items,...t])})}});var FS=m({is(e){return e.kind==="PartitionByNode"},create(e){return m({kind:"PartitionByNode",items:m(e)})},cloneWithItems(e,t){return m({...e,items:m([...e.items,...t])})}});var Rh=m({is(e){return e.kind==="OverNode"},create(){return m({kind:"OverNode"})},cloneWithOrderByItems(e,t){return m({...e,orderBy:e.orderBy?Qa.cloneWithItems(e.orderBy,t):Qa.create(t)})},cloneWithPartitionByItems(e,t){return m({...e,partitionBy:e.partitionBy?FS.cloneWithItems(e.partitionBy,t):FS.create(t)})}});var zu=m({is(e){return e.kind==="FromNode"},create(e){return m({kind:"FromNode",froms:m(e)})},cloneWithFroms(e,t){return m({...e,froms:m([...e.froms,...t])})}});var zS=m({is(e){return e.kind==="GroupByNode"},create(e){return m({kind:"GroupByNode",items:m(e)})},cloneWithItems(e,t){return m({...e,items:m([...e.items,...t])})}});var WS=m({is(e){return e.kind==="HavingNode"},create(e){return m({kind:"HavingNode",having:e})},cloneWithOperation(e,t,r){return m({...e,having:t==="And"?To.create(e.having,r):Is.create(e.having,r)})}});var di=m({is(e){return e.kind==="InsertQueryNode"},create(e,t,r){return m({kind:"InsertQueryNode",into:e,...t&&{with:t},replace:r})},createWithoutInto(){return m({kind:"InsertQueryNode"})},cloneWith(e,t){return m({...e,...t})}});var Kg=m({is(e){return e.kind==="ListNode"},create(e){return m({kind:"ListNode",items:m(e)})}});var ha=m({is(e){return e.kind==="UpdateQueryNode"},create(e,t){return m({kind:"UpdateQueryNode",table:e.length===1?e[0]:Kg.create(e),...t&&{with:t}})},createWithoutTable(){return m({kind:"UpdateQueryNode"})},cloneWithFromItems(e,t){return m({...e,from:e.from?zu.cloneWithFroms(e.from,t):zu.create(t)})},cloneWithUpdates(e,t){return m({...e,updates:e.updates?m([...e.updates,...t]):t})},cloneWithLimit(e,t){return m({...e,limit:t})}});var Nh=m({is(e){return e.kind==="UsingNode"},create(e){return m({kind:"UsingNode",tables:m(e)})},cloneWithTables(e,t){return m({...e,tables:m([...e.tables,...t])})}});var Bc=m({is(e){return e.kind==="DeleteQueryNode"},create(e,t){return m({kind:"DeleteQueryNode",from:zu.create(e),...t&&{with:t}})},cloneWithOrderByItems:(e,t)=>pt.cloneWithOrderByItems(e,t),cloneWithoutOrderBy:(e)=>pt.cloneWithoutOrderBy(e),cloneWithLimit(e,t){return m({...e,limit:t})},cloneWithoutLimit(e){return m({...e,limit:void 0})},cloneWithUsing(e,t){return m({...e,using:e.using!==void 0?Nh.cloneWithTables(e.using,t):Nh.create(t)})}});var Xi=m({is(e){return e.kind==="WhereNode"},create(e){return m({kind:"WhereNode",where:e})},cloneWithOperation(e,t,r){return m({...e,where:t==="And"?To.create(e.where,r):Is.create(e.where,r)})}});var HS=m({is(e){return e.kind==="ReturningNode"},create(e){return m({kind:"ReturningNode",selections:m(e)})},cloneWithSelections(e,t){return m({...e,selections:e.selections?m([...e.selections,...t]):m(t)})}});var FD=m({is(e){return e.kind==="ExplainNode"},create(e,t){return m({kind:"ExplainNode",format:e,options:t})}});var ns=m({is(e){return e.kind==="WhenNode"},create(e){return m({kind:"WhenNode",condition:e})},cloneWithResult(e,t){return m({...e,result:t})}});var zo=m({is(e){return e.kind==="MergeQueryNode"},create(e,t){return m({kind:"MergeQueryNode",into:e,...t&&{with:t}})},cloneWithUsing(e,t){return m({...e,using:t})},cloneWithWhen(e,t){return m({...e,whens:e.whens?m([...e.whens,t]):m([t])})},cloneWithThen(e,t){return m({...e,whens:e.whens?m([...e.whens.slice(0,-1),ns.cloneWithResult(e.whens[e.whens.length-1],t)]):void 0})}});var VS=m({is(e){return e.kind==="OutputNode"},create(e){return m({kind:"OutputNode",selections:m(e)})},cloneWithSelections(e,t){return m({...e,selections:e.selections?m([...e.selections,...t]):m(t)})}});var pt=m({is(e){return mn.is(e)||di.is(e)||ha.is(e)||Bc.is(e)||zo.is(e)},cloneWithEndModifier(e,t){return m({...e,endModifiers:e.endModifiers?m([...e.endModifiers,t]):m([t])})},cloneWithWhere(e,t){return m({...e,where:e.where?Xi.cloneWithOperation(e.where,"And",t):Xi.create(t)})},cloneWithJoin(e,t){return m({...e,joins:e.joins?m([...e.joins,t]):m([t])})},cloneWithReturning(e,t){return m({...e,returning:e.returning?HS.cloneWithSelections(e.returning,t):HS.create(t)})},cloneWithoutReturning(e){return m({...e,returning:void 0})},cloneWithoutWhere(e){return m({...e,where:void 0})},cloneWithExplain(e,t,r){return m({...e,explain:FD.create(t,r?.toOperationNode())})},cloneWithTop(e,t){return m({...e,top:t})},cloneWithOutput(e,t){return m({...e,output:e.output?VS.cloneWithSelections(e.output,t):VS.create(t)})},cloneWithOrderByItems(e,t){return m({...e,orderBy:e.orderBy?Qa.cloneWithItems(e.orderBy,t):Qa.create(t)})},cloneWithoutOrderBy(e){return m({...e,orderBy:void 0})}});var mn=m({is(e){return e.kind==="SelectQueryNode"},create(e){return m({kind:"SelectQueryNode",...e&&{with:e}})},createFrom(e,t){return m({kind:"SelectQueryNode",from:zu.create(e),...t&&{with:t}})},cloneWithSelections(e,t){return m({...e,selections:e.selections?m([...e.selections,...t]):m(t)})},cloneWithDistinctOn(e,t){return m({...e,distinctOn:e.distinctOn?m([...e.distinctOn,...t]):m(t)})},cloneWithFrontModifier(e,t){return m({...e,frontModifiers:e.frontModifiers?m([...e.frontModifiers,t]):m([t])})},cloneWithOrderByItems:(e,t)=>pt.cloneWithOrderByItems(e,t),cloneWithGroupByItems(e,t){return m({...e,groupBy:e.groupBy?zS.cloneWithItems(e.groupBy,t):zS.create(t)})},cloneWithLimit(e,t){return m({...e,limit:t})},cloneWithOffset(e,t){return m({...e,offset:t})},cloneWithFetch(e,t){return m({...e,fetch:t})},cloneWithHaving(e,t){return m({...e,having:e.having?WS.cloneWithOperation(e.having,"And",t):WS.create(t)})},cloneWithSetOperations(e,t){return m({...e,setOperations:e.setOperations?m([...e.setOperations,...t]):m([...t])})},cloneWithoutSelections(e){return m({...e,selections:[]})},cloneWithoutLimit(e){return m({...e,limit:void 0})},cloneWithoutOffset(e){return m({...e,offset:void 0})},cloneWithoutOrderBy:(e)=>pt.cloneWithoutOrderBy(e),cloneWithoutGroupBy(e){return m({...e,groupBy:void 0})}});class il{#e;constructor(e){this.#e=m(e)}on(...e){return new il({...this.#e,joinNode:Ds.cloneWithOn(this.#e.joinNode,Vn(e))})}onRef(e,t,r){return new il({...this.#e,joinNode:Ds.cloneWithOn(this.#e.joinNode,ji(e,t,r))})}onTrue(){return new il({...this.#e,joinNode:Ds.cloneWithOn(this.#e.joinNode,pn.createWithSql("true"))})}$call(e){return e(this)}toOperationNode(){return this.#e.joinNode}}var zD=m({is(e){return e.kind==="PartitionByItemNode"},create(e){return m({kind:"PartitionByItemNode",partitionBy:e})}});function WD(e){return Ja(e).map(zD.create)}class ol{#e;constructor(e){this.#e=m(e)}orderBy(...e){return new ol({overNode:Rh.cloneWithOrderByItems(this.#e.overNode,$o(e))})}clearOrderBy(){return new ol({overNode:pt.cloneWithoutOrderBy(this.#e.overNode)})}partitionBy(e){return new ol({overNode:Rh.cloneWithPartitionByItems(this.#e.overNode,WD(e))})}$call(e){return e(this)}toOperationNode(){return this.#e.overNode}}var sl=m({is(e){return e.kind==="SelectionNode"},create(e){return m({kind:"SelectionNode",selection:e})},createSelectAll(){return m({kind:"SelectionNode",selection:el.create()})},createSelectAllFromTable(e){return m({kind:"SelectionNode",selection:Pc.createSelectAll(e)})}});function Ii(e){if(qn(e))return Ii(e(Ps()));else if(oo(e))return e.map((t)=>HD(t));else return[HD(e)]}function HD(e){if(Ln(e))return sl.create(qD(e));else if(zg(e))return sl.create(e.toOperationNode());else return sl.create(Jg(e))}function $i(e){if(!e)return[sl.createSelectAll()];else if(Array.isArray(e))return e.map(VD);else return[VD(e)]}function VD(e){if(Ln(e))return sl.createSelectAllFromTable(wn(e));throw Error(`invalid value selectAll expression: ${JSON.stringify(e)}`)}var GD=m({is(e){return e.kind==="ValuesNode"},create(e){return m({kind:"ValuesNode",values:m(e)})}});var KD=m({is(e){return e.kind==="DefaultInsertValueNode"},create(){return m({kind:"DefaultInsertValueNode"})}});function Qg(e){let t=qn(e)?e(Ps()):e,r=oo(t)?t:m([t]);return gie(r)}function gie(e){let t=yie(e);return[m([...t.keys()].map(Hr.create)),GD.create(e.map((r)=>wie(r,t)))]}function yie(e){let t=new Map;for(let r of e){let n=Object.keys(r);for(let i of n)if(!t.has(i)&&r[i]!==void 0)t.set(i,t.size)}return t}function wie(e,t){let r=Object.keys(e),n=Array.from({length:t.size}),i=!1,o=r.length;for(let a of r){let c=t.get(a);if(mo(c)){o--;continue}let u=e[a];if(mo(u)||Ka(u))i=!0;n[c]=u}if(o<t.size||i){let a=KD.create();return qc.create(n.map((c)=>mo(c)?a:zn(c)))}return Hg.create(n)}var GS=m({is(e){return e.kind==="ColumnUpdateNode"},create(e,t){return m({kind:"ColumnUpdateNode",column:e,value:t})}});function JD(...e){if(e.length===2)return[GS.create(Yi(e[0]),zn(e[1]))];return xh(e[0])}function xh(e){let t=qn(e)?e(Ps()):e;return Object.entries(t).filter(([r,n])=>n!==void 0).map(([r,n])=>GS.create(Hr.create(r),zn(n)))}var QD=m({is(e){return e.kind==="OnDuplicateKeyNode"},create(e){return m({kind:"OnDuplicateKeyNode",updates:e})}});class KS{insertId;numInsertedOrUpdatedRows;constructor(e,t){this.insertId=e,this.numInsertedOrUpdatedRows=t}}class Ls extends Error{node;constructor(e){super("no result");this.node=e}}function pa(e){return Object.prototype.hasOwnProperty.call(e,"prototype")}var yo=m({is(e){return e.kind==="OnConflictNode"},create(){return m({kind:"OnConflictNode"})},cloneWith(e,t){return m({...e,...t})},cloneWithIndexWhere(e,t){return m({...e,indexWhere:e.indexWhere?Xi.cloneWithOperation(e.indexWhere,"And",t):Xi.create(t)})},cloneWithIndexOrWhere(e,t){return m({...e,indexWhere:e.indexWhere?Xi.cloneWithOperation(e.indexWhere,"Or",t):Xi.create(t)})},cloneWithUpdateWhere(e,t){return m({...e,updateWhere:e.updateWhere?Xi.cloneWithOperation(e.updateWhere,"And",t):Xi.create(t)})},cloneWithUpdateOrWhere(e,t){return m({...e,updateWhere:e.updateWhere?Xi.cloneWithOperation(e.updateWhere,"Or",t):Xi.create(t)})},cloneWithoutIndexWhere(e){return m({...e,indexWhere:void 0})},cloneWithoutUpdateWhere(e){return m({...e,updateWhere:void 0})}});class ma{#e;constructor(e){this.#e=m(e)}column(e){let t=Hr.create(e);return new ma({...this.#e,onConflictNode:yo.cloneWith(this.#e.onConflictNode,{columns:this.#e.onConflictNode.columns?m([...this.#e.onConflictNode.columns,t]):m([t])})})}columns(e){let t=e.map(Hr.create);return new ma({...this.#e,onConflictNode:yo.cloneWith(this.#e.onConflictNode,{columns:this.#e.onConflictNode.columns?m([...this.#e.onConflictNode.columns,...t]):m(t)})})}constraint(e){return new ma({...this.#e,onConflictNode:yo.cloneWith(this.#e.onConflictNode,{constraint:$t.create(e)})})}expression(e){return new ma({...this.#e,onConflictNode:yo.cloneWith(this.#e.onConflictNode,{indexExpression:e.toOperationNode()})})}where(...e){return new ma({...this.#e,onConflictNode:yo.cloneWithIndexWhere(this.#e.onConflictNode,Vn(e))})}whereRef(e,t,r){return new ma({...this.#e,onConflictNode:yo.cloneWithIndexWhere(this.#e.onConflictNode,ji(e,t,r))})}clearWhere(){return new ma({...this.#e,onConflictNode:yo.cloneWithoutIndexWhere(this.#e.onConflictNode)})}doNothing(){return new YD({...this.#e,onConflictNode:yo.cloneWith(this.#e.onConflictNode,{doNothing:!0})})}doUpdateSet(e){return new Ch({...this.#e,onConflictNode:yo.cloneWith(this.#e.onConflictNode,{updates:xh(e)})})}$call(e){return e(this)}}class YD{#e;constructor(e){this.#e=m(e)}toOperationNode(){return this.#e.onConflictNode}}class Ch{#e;constructor(e){this.#e=m(e)}where(...e){return new Ch({...this.#e,onConflictNode:yo.cloneWithUpdateWhere(this.#e.onConflictNode,Vn(e))})}whereRef(e,t,r){return new Ch({...this.#e,onConflictNode:yo.cloneWithUpdateWhere(this.#e.onConflictNode,ji(e,t,r))})}clearWhere(){return new Ch({...this.#e,onConflictNode:yo.cloneWithoutUpdateWhere(this.#e.onConflictNode)})}$call(e){return e(this)}toOperationNode(){return this.#e.onConflictNode}}var XD=m({is(e){return e.kind==="TopNode"},create(e,t){return m({kind:"TopNode",expression:e,modifiers:t})}});function Ms(e,t){if(!Cs(e)&&!Ic(e))throw Error(`Invalid top expression: ${e}`);if(!mo(t)&&!_ie(t))throw Error(`Invalid top modifiers: ${t}`);return XD.create(e,t)}function _ie(e){return e==="percent"||e==="with ties"||e==="percent with ties"}var Wu=m({is(e){return e.kind==="OrActionNode"},create(e){return m({kind:"OrActionNode",action:e})}});class Wn{#e;constructor(e){this.#e=m(e)}values(e){let[t,r]=Qg(e);return new Wn({...this.#e,queryNode:di.cloneWith(this.#e.queryNode,{columns:t,values:r})})}columns(e){return new Wn({...this.#e,queryNode:di.cloneWith(this.#e.queryNode,{columns:m(e.map(Hr.create))})})}expression(e){return new Wn({...this.#e,queryNode:di.cloneWith(this.#e.queryNode,{values:vo(e)})})}defaultValues(){return new Wn({...this.#e,queryNode:di.cloneWith(this.#e.queryNode,{defaultValues:!0})})}modifyEnd(e){return new Wn({...this.#e,queryNode:pt.cloneWithEndModifier(this.#e.queryNode,e.toOperationNode())})}ignore(){return new Wn({...this.#e,queryNode:di.cloneWith(this.#e.queryNode,{orAction:Wu.create("ignore")})})}orIgnore(){return new Wn({...this.#e,queryNode:di.cloneWith(this.#e.queryNode,{orAction:Wu.create("ignore")})})}orAbort(){return new Wn({...this.#e,queryNode:di.cloneWith(this.#e.queryNode,{orAction:Wu.create("abort")})})}orFail(){return new Wn({...this.#e,queryNode:di.cloneWith(this.#e.queryNode,{orAction:Wu.create("fail")})})}orReplace(){return new Wn({...this.#e,queryNode:di.cloneWith(this.#e.queryNode,{orAction:Wu.create("replace")})})}orRollback(){return new Wn({...this.#e,queryNode:di.cloneWith(this.#e.queryNode,{orAction:Wu.create("rollback")})})}top(e,t){return new Wn({...this.#e,queryNode:pt.cloneWithTop(this.#e.queryNode,Ms(e,t))})}onConflict(e){return new Wn({...this.#e,queryNode:di.cloneWith(this.#e.queryNode,{onConflict:e(new ma({onConflictNode:yo.create()})).toOperationNode()})})}onDuplicateKeyUpdate(e){return new Wn({...this.#e,queryNode:di.cloneWith(this.#e.queryNode,{onDuplicateKey:QD.create(xh(e))})})}returning(e){return new Wn({...this.#e,queryNode:pt.cloneWithReturning(this.#e.queryNode,Ii(e))})}returningAll(){return new Wn({...this.#e,queryNode:pt.cloneWithReturning(this.#e.queryNode,$i())})}output(e){return new Wn({...this.#e,queryNode:pt.cloneWithOutput(this.#e.queryNode,Ii(e))})}outputAll(e){return new Wn({...this.#e,queryNode:pt.cloneWithOutput(this.#e.queryNode,$i(e))})}clearReturning(){return new Wn({...this.#e,queryNode:pt.cloneWithoutReturning(this.#e.queryNode)})}$call(e){return e(this)}$if(e,t){if(e)return t(this);return new Wn({...this.#e})}$castTo(){return new Wn(this.#e)}$narrowType(){return new Wn(this.#e)}$assertType(){return new Wn(this.#e)}withPlugin(e){return new Wn({...this.#e,executor:this.#e.executor.withPlugin(e)})}toOperationNode(){return this.#e.executor.transformQuery(this.#e.queryNode,this.#e.queryId)}compile(){return this.#e.executor.compileQuery(this.toOperationNode(),this.#e.queryId)}async execute(){let e=this.compile(),t=await this.#e.executor.executeQuery(e),{adapter:r}=this.#e.executor,n=e.query;if(n.returning&&r.supportsReturning||n.output&&r.supportsOutput)return t.rows;return[new KS(t.insertId,t.numAffectedRows??BigInt(0))]}async executeTakeFirst(){let[e]=await this.execute();return e}async executeTakeFirstOrThrow(e=Ls){let t=await this.executeTakeFirst();if(t===void 0)throw pa(e)?new e(this.toOperationNode()):e(this.toOperationNode());return t}async*stream(e=100){let t=this.compile(),r=this.#e.executor.stream(t,e);for await(let n of r)yield*n.rows}async explain(e,t){return await new Wn({...this.#e,queryNode:pt.cloneWithExplain(this.#e.queryNode,e,t)}).execute()}}class JS{numDeletedRows;constructor(e){this.numDeletedRows=e}}var al=m({is(e){return e.kind==="LimitNode"},create(e){return m({kind:"LimitNode",limit:e})}});var li;class Yg{#e;constructor(e){this.#e=m(e)}where(...e){return new li({...this.#e,queryNode:pt.cloneWithWhere(this.#e.queryNode,Vn(e))})}whereRef(e,t,r){return new li({...this.#e,queryNode:pt.cloneWithWhere(this.#e.queryNode,ji(e,t,r))})}clearWhere(){return new li({...this.#e,queryNode:pt.cloneWithoutWhere(this.#e.queryNode)})}top(e,t){return new li({...this.#e,queryNode:pt.cloneWithTop(this.#e.queryNode,Ms(e,t))})}using(e){return new li({...this.#e,queryNode:Bc.cloneWithUsing(this.#e.queryNode,qs(e))})}innerJoin(...e){return this.#t("InnerJoin",e)}leftJoin(...e){return this.#t("LeftJoin",e)}rightJoin(...e){return this.#t("RightJoin",e)}fullJoin(...e){return this.#t("FullJoin",e)}#t(e,t){return new li({...this.#e,queryNode:pt.cloneWithJoin(this.#e.queryNode,jc(e,t))})}returning(e){return new li({...this.#e,queryNode:pt.cloneWithReturning(this.#e.queryNode,Ii(e))})}returningAll(e){return new li({...this.#e,queryNode:pt.cloneWithReturning(this.#e.queryNode,$i(e))})}output(e){return new li({...this.#e,queryNode:pt.cloneWithOutput(this.#e.queryNode,Ii(e))})}outputAll(e){return new li({...this.#e,queryNode:pt.cloneWithOutput(this.#e.queryNode,$i(e))})}clearReturning(){return new li({...this.#e,queryNode:pt.cloneWithoutReturning(this.#e.queryNode)})}clearLimit(){return new li({...this.#e,queryNode:Bc.cloneWithoutLimit(this.#e.queryNode)})}orderBy(...e){return new li({...this.#e,queryNode:pt.cloneWithOrderByItems(this.#e.queryNode,$o(e))})}clearOrderBy(){return new li({...this.#e,queryNode:pt.cloneWithoutOrderBy(this.#e.queryNode)})}limit(e){return new li({...this.#e,queryNode:Bc.cloneWithLimit(this.#e.queryNode,al.create(zn(e)))})}modifyEnd(e){return new li({...this.#e,queryNode:pt.cloneWithEndModifier(this.#e.queryNode,e.toOperationNode())})}$call(e){return e(this)}$if(e,t){if(e)return t(this);return new li({...this.#e})}$castTo(){return new li(this.#e)}$narrowType(){return new li(this.#e)}$assertType(){return new li(this.#e)}withPlugin(e){return new li({...this.#e,executor:this.#e.executor.withPlugin(e)})}toOperationNode(){return this.#e.executor.transformQuery(this.#e.queryNode,this.#e.queryId)}compile(){return this.#e.executor.compileQuery(this.toOperationNode(),this.#e.queryId)}async execute(){let e=this.compile(),t=await this.#e.executor.executeQuery(e),{adapter:r}=this.#e.executor,n=e.query;if(n.returning&&r.supportsReturning||n.output&&r.supportsOutput)return t.rows;return[new JS(t.numAffectedRows??BigInt(0))]}async executeTakeFirst(){let[e]=await this.execute();return e}async executeTakeFirstOrThrow(e=Ls){let t=await this.executeTakeFirst();if(t===void 0)throw pa(e)?new e(this.toOperationNode()):e(this.toOperationNode());return t}async*stream(e=100){let t=this.compile(),r=this.#e.executor.stream(t,e);for await(let n of r)yield*n.rows}async explain(e,t){return await new li({...this.#e,queryNode:pt.cloneWithExplain(this.#e.queryNode,e,t)}).execute()}}li=Yg;class QS{numUpdatedRows;numChangedRows;constructor(e,t){this.numUpdatedRows=e,this.numChangedRows=t}}var fi;class cl{#e;constructor(e){this.#e=m(e)}where(...e){return new fi({...this.#e,queryNode:pt.cloneWithWhere(this.#e.queryNode,Vn(e))})}whereRef(e,t,r){return new fi({...this.#e,queryNode:pt.cloneWithWhere(this.#e.queryNode,ji(e,t,r))})}clearWhere(){return new fi({...this.#e,queryNode:pt.cloneWithoutWhere(this.#e.queryNode)})}top(e,t){return new fi({...this.#e,queryNode:pt.cloneWithTop(this.#e.queryNode,Ms(e,t))})}from(e){return new fi({...this.#e,queryNode:ha.cloneWithFromItems(this.#e.queryNode,qs(e))})}innerJoin(...e){return this.#t("InnerJoin",e)}leftJoin(...e){return this.#t("LeftJoin",e)}rightJoin(...e){return this.#t("RightJoin",e)}fullJoin(...e){return this.#t("FullJoin",e)}#t(e,t){return new fi({...this.#e,queryNode:pt.cloneWithJoin(this.#e.queryNode,jc(e,t))})}orderBy(...e){return new fi({...this.#e,queryNode:pt.cloneWithOrderByItems(this.#e.queryNode,$o(e))})}clearOrderBy(){return new fi({...this.#e,queryNode:pt.cloneWithoutOrderBy(this.#e.queryNode)})}limit(e){return new fi({...this.#e,queryNode:ha.cloneWithLimit(this.#e.queryNode,al.create(zn(e)))})}set(...e){return new fi({...this.#e,queryNode:ha.cloneWithUpdates(this.#e.queryNode,JD(...e))})}returning(e){return new fi({...this.#e,queryNode:pt.cloneWithReturning(this.#e.queryNode,Ii(e))})}returningAll(e){return new fi({...this.#e,queryNode:pt.cloneWithReturning(this.#e.queryNode,$i(e))})}output(e){return new fi({...this.#e,queryNode:pt.cloneWithOutput(this.#e.queryNode,Ii(e))})}outputAll(e){return new fi({...this.#e,queryNode:pt.cloneWithOutput(this.#e.queryNode,$i(e))})}modifyEnd(e){return new fi({...this.#e,queryNode:pt.cloneWithEndModifier(this.#e.queryNode,e.toOperationNode())})}clearReturning(){return new fi({...this.#e,queryNode:pt.cloneWithoutReturning(this.#e.queryNode)})}$call(e){return e(this)}$if(e,t){if(e)return t(this);return new fi({...this.#e})}$castTo(){return new fi(this.#e)}$narrowType(){return new fi(this.#e)}$assertType(){return new fi(this.#e)}withPlugin(e){return new fi({...this.#e,executor:this.#e.executor.withPlugin(e)})}toOperationNode(){return this.#e.executor.transformQuery(this.#e.queryNode,this.#e.queryId)}compile(){return this.#e.executor.compileQuery(this.toOperationNode(),this.#e.queryId)}async execute(){let e=this.compile(),t=await this.#e.executor.executeQuery(e),{adapter:r}=this.#e.executor,n=e.query;if(n.returning&&r.supportsReturning||n.output&&r.supportsOutput)return t.rows;return[new QS(t.numAffectedRows??BigInt(0),t.numChangedRows)]}async executeTakeFirst(){let[e]=await this.execute();return e}async executeTakeFirstOrThrow(e=Ls){let t=await this.executeTakeFirst();if(t===void 0)throw pa(e)?new e(this.toOperationNode()):e(this.toOperationNode());return t}async*stream(e=100){let t=this.compile(),r=this.#e.executor.stream(t,e);for await(let n of r)yield*n.rows}async explain(e,t){return await new fi({...this.#e,queryNode:pt.cloneWithExplain(this.#e.queryNode,e,t)}).execute()}}fi=cl;var YS=m({is(e){return e.kind==="CommonTableExpressionNameNode"},create(e,t){return m({kind:"CommonTableExpressionNameNode",table:co.create(e),columns:t?m(t.map(Hr.create)):void 0})}});var ul=m({is(e){return e.kind==="CommonTableExpressionNode"},create(e,t){return m({kind:"CommonTableExpressionNode",name:e,expression:t})},cloneWith(e,t){return m({...e,...t})}});class Oh{#e;constructor(e){this.#e=m(e)}materialized(){return new Oh({...this.#e,node:ul.cloneWith(this.#e.node,{materialized:!0})})}notMaterialized(){return new Oh({...this.#e,node:ul.cloneWith(this.#e.node,{materialized:!1})})}toOperationNode(){return this.#e.node}}function XS(e,t){let r=t(eU()).toOperationNode();if(qn(e))return e(bie(r)).toOperationNode();return ul.create(ZD(e),r)}function bie(e){return(t)=>new Oh({node:ul.create(ZD(t),e)})}function ZD(e){if(e.includes("(")){let t=e.split(/[\(\)]/),r=t[0],n=t[1].split(",").map((i)=>i.trim());return YS.create(r,n)}else return YS.create(e)}var Ih=m({is(e){return e.kind==="WithNode"},create(e,t){return m({kind:"WithNode",expressions:m([e]),...t})},cloneWithExpression(e,t){return m({...e,expressions:m([...e.expressions,t])})}});var tU=["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z","a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z","0","1","2","3","4","5","6","7","8","9"];function Xg(e){let t="";for(let r=0;r<e;++r)t+=Eie();return t}function Eie(){return tU[~~(Math.random()*tU.length)]}function Vt(){return new rU}class rU{#e;get queryId(){if(this.#e===void 0)this.#e=Xg(8);return this.#e}}function lt(e){return e}class Dh{nodeStack=[];#e=m({AliasNode:this.transformAlias.bind(this),ColumnNode:this.transformColumn.bind(this),IdentifierNode:this.transformIdentifier.bind(this),SchemableIdentifierNode:this.transformSchemableIdentifier.bind(this),RawNode:this.transformRaw.bind(this),ReferenceNode:this.transformReference.bind(this),SelectQueryNode:this.transformSelectQuery.bind(this),SelectionNode:this.transformSelection.bind(this),TableNode:this.transformTable.bind(this),FromNode:this.transformFrom.bind(this),SelectAllNode:this.transformSelectAll.bind(this),AndNode:this.transformAnd.bind(this),OrNode:this.transformOr.bind(this),ValueNode:this.transformValue.bind(this),ValueListNode:this.transformValueList.bind(this),PrimitiveValueListNode:this.transformPrimitiveValueList.bind(this),ParensNode:this.transformParens.bind(this),JoinNode:this.transformJoin.bind(this),OperatorNode:this.transformOperator.bind(this),WhereNode:this.transformWhere.bind(this),InsertQueryNode:this.transformInsertQuery.bind(this),DeleteQueryNode:this.transformDeleteQuery.bind(this),ReturningNode:this.transformReturning.bind(this),CreateTableNode:this.transformCreateTable.bind(this),AddColumnNode:this.transformAddColumn.bind(this),ColumnDefinitionNode:this.transformColumnDefinition.bind(this),DropTableNode:this.transformDropTable.bind(this),DataTypeNode:this.transformDataType.bind(this),OrderByNode:this.transformOrderBy.bind(this),OrderByItemNode:this.transformOrderByItem.bind(this),GroupByNode:this.transformGroupBy.bind(this),GroupByItemNode:this.transformGroupByItem.bind(this),UpdateQueryNode:this.transformUpdateQuery.bind(this),ColumnUpdateNode:this.transformColumnUpdate.bind(this),LimitNode:this.transformLimit.bind(this),OffsetNode:this.transformOffset.bind(this),OnConflictNode:this.transformOnConflict.bind(this),OnDuplicateKeyNode:this.transformOnDuplicateKey.bind(this),CreateIndexNode:this.transformCreateIndex.bind(this),DropIndexNode:this.transformDropIndex.bind(this),ListNode:this.transformList.bind(this),PrimaryKeyConstraintNode:this.transformPrimaryKeyConstraint.bind(this),UniqueConstraintNode:this.transformUniqueConstraint.bind(this),ReferencesNode:this.transformReferences.bind(this),CheckConstraintNode:this.transformCheckConstraint.bind(this),WithNode:this.transformWith.bind(this),CommonTableExpressionNode:this.transformCommonTableExpression.bind(this),CommonTableExpressionNameNode:this.transformCommonTableExpressionName.bind(this),HavingNode:this.transformHaving.bind(this),CreateSchemaNode:this.transformCreateSchema.bind(this),DropSchemaNode:this.transformDropSchema.bind(this),AlterTableNode:this.transformAlterTable.bind(this),DropColumnNode:this.transformDropColumn.bind(this),RenameColumnNode:this.transformRenameColumn.bind(this),AlterColumnNode:this.transformAlterColumn.bind(this),ModifyColumnNode:this.transformModifyColumn.bind(this),AddConstraintNode:this.transformAddConstraint.bind(this),DropConstraintNode:this.transformDropConstraint.bind(this),RenameConstraintNode:this.transformRenameConstraint.bind(this),ForeignKeyConstraintNode:this.transformForeignKeyConstraint.bind(this),CreateViewNode:this.transformCreateView.bind(this),RefreshMaterializedViewNode:this.transformRefreshMaterializedView.bind(this),DropViewNode:this.transformDropView.bind(this),GeneratedNode:this.transformGenerated.bind(this),DefaultValueNode:this.transformDefaultValue.bind(this),OnNode:this.transformOn.bind(this),ValuesNode:this.transformValues.bind(this),SelectModifierNode:this.transformSelectModifier.bind(this),CreateTypeNode:this.transformCreateType.bind(this),DropTypeNode:this.transformDropType.bind(this),ExplainNode:this.transformExplain.bind(this),DefaultInsertValueNode:this.transformDefaultInsertValue.bind(this),AggregateFunctionNode:this.transformAggregateFunction.bind(this),OverNode:this.transformOver.bind(this),PartitionByNode:this.transformPartitionBy.bind(this),PartitionByItemNode:this.transformPartitionByItem.bind(this),SetOperationNode:this.transformSetOperation.bind(this),BinaryOperationNode:this.transformBinaryOperation.bind(this),UnaryOperationNode:this.transformUnaryOperation.bind(this),UsingNode:this.transformUsing.bind(this),FunctionNode:this.transformFunction.bind(this),CaseNode:this.transformCase.bind(this),WhenNode:this.transformWhen.bind(this),JSONReferenceNode:this.transformJSONReference.bind(this),JSONPathNode:this.transformJSONPath.bind(this),JSONPathLegNode:this.transformJSONPathLeg.bind(this),JSONOperatorChainNode:this.transformJSONOperatorChain.bind(this),TupleNode:this.transformTuple.bind(this),MergeQueryNode:this.transformMergeQuery.bind(this),MatchedNode:this.transformMatched.bind(this),AddIndexNode:this.transformAddIndex.bind(this),CastNode:this.transformCast.bind(this),FetchNode:this.transformFetch.bind(this),TopNode:this.transformTop.bind(this),OutputNode:this.transformOutput.bind(this),OrActionNode:this.transformOrAction.bind(this),CollateNode:this.transformCollate.bind(this)});transformNode(e,t){if(!e)return e;this.nodeStack.push(e);let r=this.transformNodeImpl(e,t);return this.nodeStack.pop(),m(r)}transformNodeImpl(e,t){return this.#e[e.kind](e,t)}transformNodeList(e,t){if(!e)return e;return m(e.map((r)=>this.transformNode(r,t)))}transformSelectQuery(e,t){return lt({kind:"SelectQueryNode",from:this.transformNode(e.from,t),selections:this.transformNodeList(e.selections,t),distinctOn:this.transformNodeList(e.distinctOn,t),joins:this.transformNodeList(e.joins,t),groupBy:this.transformNode(e.groupBy,t),orderBy:this.transformNode(e.orderBy,t),where:this.transformNode(e.where,t),frontModifiers:this.transformNodeList(e.frontModifiers,t),endModifiers:this.transformNodeList(e.endModifiers,t),limit:this.transformNode(e.limit,t),offset:this.transformNode(e.offset,t),with:this.transformNode(e.with,t),having:this.transformNode(e.having,t),explain:this.transformNode(e.explain,t),setOperations:this.transformNodeList(e.setOperations,t),fetch:this.transformNode(e.fetch,t),top:this.transformNode(e.top,t)})}transformSelection(e,t){return lt({kind:"SelectionNode",selection:this.transformNode(e.selection,t)})}transformColumn(e,t){return lt({kind:"ColumnNode",column:this.transformNode(e.column,t)})}transformAlias(e,t){return lt({kind:"AliasNode",node:this.transformNode(e.node,t),alias:this.transformNode(e.alias,t)})}transformTable(e,t){return lt({kind:"TableNode",table:this.transformNode(e.table,t)})}transformFrom(e,t){return lt({kind:"FromNode",froms:this.transformNodeList(e.froms,t)})}transformReference(e,t){return lt({kind:"ReferenceNode",column:this.transformNode(e.column,t),table:this.transformNode(e.table,t)})}transformAnd(e,t){return lt({kind:"AndNode",left:this.transformNode(e.left,t),right:this.transformNode(e.right,t)})}transformOr(e,t){return lt({kind:"OrNode",left:this.transformNode(e.left,t),right:this.transformNode(e.right,t)})}transformValueList(e,t){return lt({kind:"ValueListNode",values:this.transformNodeList(e.values,t)})}transformParens(e,t){return lt({kind:"ParensNode",node:this.transformNode(e.node,t)})}transformJoin(e,t){return lt({kind:"JoinNode",joinType:e.joinType,table:this.transformNode(e.table,t),on:this.transformNode(e.on,t)})}transformRaw(e,t){return lt({kind:"RawNode",sqlFragments:m([...e.sqlFragments]),parameters:this.transformNodeList(e.parameters,t)})}transformWhere(e,t){return lt({kind:"WhereNode",where:this.transformNode(e.where,t)})}transformInsertQuery(e,t){return lt({kind:"InsertQueryNode",into:this.transformNode(e.into,t),columns:this.transformNodeList(e.columns,t),values:this.transformNode(e.values,t),returning:this.transformNode(e.returning,t),onConflict:this.transformNode(e.onConflict,t),onDuplicateKey:this.transformNode(e.onDuplicateKey,t),endModifiers:this.transformNodeList(e.endModifiers,t),with:this.transformNode(e.with,t),ignore:e.ignore,orAction:this.transformNode(e.orAction,t),replace:e.replace,explain:this.transformNode(e.explain,t),defaultValues:e.defaultValues,top:this.transformNode(e.top,t),output:this.transformNode(e.output,t)})}transformValues(e,t){return lt({kind:"ValuesNode",values:this.transformNodeList(e.values,t)})}transformDeleteQuery(e,t){return lt({kind:"DeleteQueryNode",from:this.transformNode(e.from,t),using:this.transformNode(e.using,t),joins:this.transformNodeList(e.joins,t),where:this.transformNode(e.where,t),returning:this.transformNode(e.returning,t),endModifiers:this.transformNodeList(e.endModifiers,t),with:this.transformNode(e.with,t),orderBy:this.transformNode(e.orderBy,t),limit:this.transformNode(e.limit,t),explain:this.transformNode(e.explain,t),top:this.transformNode(e.top,t),output:this.transformNode(e.output,t)})}transformReturning(e,t){return lt({kind:"ReturningNode",selections:this.transformNodeList(e.selections,t)})}transformCreateTable(e,t){return lt({kind:"CreateTableNode",table:this.transformNode(e.table,t),columns:this.transformNodeList(e.columns,t),constraints:this.transformNodeList(e.constraints,t),temporary:e.temporary,ifNotExists:e.ifNotExists,onCommit:e.onCommit,frontModifiers:this.transformNodeList(e.frontModifiers,t),endModifiers:this.transformNodeList(e.endModifiers,t),selectQuery:this.transformNode(e.selectQuery,t)})}transformColumnDefinition(e,t){return lt({kind:"ColumnDefinitionNode",column:this.transformNode(e.column,t),dataType:this.transformNode(e.dataType,t),references:this.transformNode(e.references,t),primaryKey:e.primaryKey,autoIncrement:e.autoIncrement,unique:e.unique,notNull:e.notNull,unsigned:e.unsigned,defaultTo:this.transformNode(e.defaultTo,t),check:this.transformNode(e.check,t),generated:this.transformNode(e.generated,t),frontModifiers:this.transformNodeList(e.frontModifiers,t),endModifiers:this.transformNodeList(e.endModifiers,t),nullsNotDistinct:e.nullsNotDistinct,identity:e.identity,ifNotExists:e.ifNotExists})}transformAddColumn(e,t){return lt({kind:"AddColumnNode",column:this.transformNode(e.column,t)})}transformDropTable(e,t){return lt({kind:"DropTableNode",table:this.transformNode(e.table,t),ifExists:e.ifExists,cascade:e.cascade})}transformOrderBy(e,t){return lt({kind:"OrderByNode",items:this.transformNodeList(e.items,t)})}transformOrderByItem(e,t){return lt({kind:"OrderByItemNode",orderBy:this.transformNode(e.orderBy,t),direction:this.transformNode(e.direction,t),collation:this.transformNode(e.collation,t),nulls:e.nulls})}transformGroupBy(e,t){return lt({kind:"GroupByNode",items:this.transformNodeList(e.items,t)})}transformGroupByItem(e,t){return lt({kind:"GroupByItemNode",groupBy:this.transformNode(e.groupBy,t)})}transformUpdateQuery(e,t){return lt({kind:"UpdateQueryNode",table:this.transformNode(e.table,t),from:this.transformNode(e.from,t),joins:this.transformNodeList(e.joins,t),where:this.transformNode(e.where,t),updates:this.transformNodeList(e.updates,t),returning:this.transformNode(e.returning,t),endModifiers:this.transformNodeList(e.endModifiers,t),with:this.transformNode(e.with,t),explain:this.transformNode(e.explain,t),limit:this.transformNode(e.limit,t),top:this.transformNode(e.top,t),output:this.transformNode(e.output,t),orderBy:this.transformNode(e.orderBy,t)})}transformColumnUpdate(e,t){return lt({kind:"ColumnUpdateNode",column:this.transformNode(e.column,t),value:this.transformNode(e.value,t)})}transformLimit(e,t){return lt({kind:"LimitNode",limit:this.transformNode(e.limit,t)})}transformOffset(e,t){return lt({kind:"OffsetNode",offset:this.transformNode(e.offset,t)})}transformOnConflict(e,t){return lt({kind:"OnConflictNode",columns:this.transformNodeList(e.columns,t),constraint:this.transformNode(e.constraint,t),indexExpression:this.transformNode(e.indexExpression,t),indexWhere:this.transformNode(e.indexWhere,t),updates:this.transformNodeList(e.updates,t),updateWhere:this.transformNode(e.updateWhere,t),doNothing:e.doNothing})}transformOnDuplicateKey(e,t){return lt({kind:"OnDuplicateKeyNode",updates:this.transformNodeList(e.updates,t)})}transformCreateIndex(e,t){return lt({kind:"CreateIndexNode",name:this.transformNode(e.name,t),table:this.transformNode(e.table,t),columns:this.transformNodeList(e.columns,t),unique:e.unique,using:this.transformNode(e.using,t),ifNotExists:e.ifNotExists,where:this.transformNode(e.where,t),nullsNotDistinct:e.nullsNotDistinct})}transformList(e,t){return lt({kind:"ListNode",items:this.transformNodeList(e.items,t)})}transformDropIndex(e,t){return lt({kind:"DropIndexNode",name:this.transformNode(e.name,t),table:this.transformNode(e.table,t),ifExists:e.ifExists,cascade:e.cascade})}transformPrimaryKeyConstraint(e,t){return lt({kind:"PrimaryKeyConstraintNode",columns:this.transformNodeList(e.columns,t),name:this.transformNode(e.name,t),deferrable:e.deferrable,initiallyDeferred:e.initiallyDeferred})}transformUniqueConstraint(e,t){return lt({kind:"UniqueConstraintNode",columns:this.transformNodeList(e.columns,t),name:this.transformNode(e.name,t),nullsNotDistinct:e.nullsNotDistinct,deferrable:e.deferrable,initiallyDeferred:e.initiallyDeferred})}transformForeignKeyConstraint(e,t){return lt({kind:"ForeignKeyConstraintNode",columns:this.transformNodeList(e.columns,t),references:this.transformNode(e.references,t),name:this.transformNode(e.name,t),onDelete:e.onDelete,onUpdate:e.onUpdate,deferrable:e.deferrable,initiallyDeferred:e.initiallyDeferred})}transformSetOperation(e,t){return lt({kind:"SetOperationNode",operator:e.operator,expression:this.transformNode(e.expression,t),all:e.all})}transformReferences(e,t){return lt({kind:"ReferencesNode",table:this.transformNode(e.table,t),columns:this.transformNodeList(e.columns,t),onDelete:e.onDelete,onUpdate:e.onUpdate})}transformCheckConstraint(e,t){return lt({kind:"CheckConstraintNode",expression:this.transformNode(e.expression,t),name:this.transformNode(e.name,t)})}transformWith(e,t){return lt({kind:"WithNode",expressions:this.transformNodeList(e.expressions,t),recursive:e.recursive})}transformCommonTableExpression(e,t){return lt({kind:"CommonTableExpressionNode",name:this.transformNode(e.name,t),materialized:e.materialized,expression:this.transformNode(e.expression,t)})}transformCommonTableExpressionName(e,t){return lt({kind:"CommonTableExpressionNameNode",table:this.transformNode(e.table,t),columns:this.transformNodeList(e.columns,t)})}transformHaving(e,t){return lt({kind:"HavingNode",having:this.transformNode(e.having,t)})}transformCreateSchema(e,t){return lt({kind:"CreateSchemaNode",schema:this.transformNode(e.schema,t),ifNotExists:e.ifNotExists})}transformDropSchema(e,t){return lt({kind:"DropSchemaNode",schema:this.transformNode(e.schema,t),ifExists:e.ifExists,cascade:e.cascade})}transformAlterTable(e,t){return lt({kind:"AlterTableNode",table:this.transformNode(e.table,t),renameTo:this.transformNode(e.renameTo,t),setSchema:this.transformNode(e.setSchema,t),columnAlterations:this.transformNodeList(e.columnAlterations,t),addConstraint:this.transformNode(e.addConstraint,t),dropConstraint:this.transformNode(e.dropConstraint,t),renameConstraint:this.transformNode(e.renameConstraint,t),addIndex:this.transformNode(e.addIndex,t),dropIndex:this.transformNode(e.dropIndex,t)})}transformDropColumn(e,t){return lt({kind:"DropColumnNode",column:this.transformNode(e.column,t)})}transformRenameColumn(e,t){return lt({kind:"RenameColumnNode",column:this.transformNode(e.column,t),renameTo:this.transformNode(e.renameTo,t)})}transformAlterColumn(e,t){return lt({kind:"AlterColumnNode",column:this.transformNode(e.column,t),dataType:this.transformNode(e.dataType,t),dataTypeExpression:this.transformNode(e.dataTypeExpression,t),setDefault:this.transformNode(e.setDefault,t),dropDefault:e.dropDefault,setNotNull:e.setNotNull,dropNotNull:e.dropNotNull})}transformModifyColumn(e,t){return lt({kind:"ModifyColumnNode",column:this.transformNode(e.column,t)})}transformAddConstraint(e,t){return lt({kind:"AddConstraintNode",constraint:this.transformNode(e.constraint,t)})}transformDropConstraint(e,t){return lt({kind:"DropConstraintNode",constraintName:this.transformNode(e.constraintName,t),ifExists:e.ifExists,modifier:e.modifier})}transformRenameConstraint(e,t){return lt({kind:"RenameConstraintNode",oldName:this.transformNode(e.oldName,t),newName:this.transformNode(e.newName,t)})}transformCreateView(e,t){return lt({kind:"CreateViewNode",name:this.transformNode(e.name,t),temporary:e.temporary,orReplace:e.orReplace,ifNotExists:e.ifNotExists,materialized:e.materialized,columns:this.transformNodeList(e.columns,t),as:this.transformNode(e.as,t)})}transformRefreshMaterializedView(e,t){return lt({kind:"RefreshMaterializedViewNode",name:this.transformNode(e.name,t),concurrently:e.concurrently,withNoData:e.withNoData})}transformDropView(e,t){return lt({kind:"DropViewNode",name:this.transformNode(e.name,t),ifExists:e.ifExists,materialized:e.materialized,cascade:e.cascade})}transformGenerated(e,t){return lt({kind:"GeneratedNode",byDefault:e.byDefault,always:e.always,identity:e.identity,stored:e.stored,expression:this.transformNode(e.expression,t)})}transformDefaultValue(e,t){return lt({kind:"DefaultValueNode",defaultValue:this.transformNode(e.defaultValue,t)})}transformOn(e,t){return lt({kind:"OnNode",on:this.transformNode(e.on,t)})}transformSelectModifier(e,t){return lt({kind:"SelectModifierNode",modifier:e.modifier,rawModifier:this.transformNode(e.rawModifier,t),of:this.transformNodeList(e.of,t)})}transformCreateType(e,t){return lt({kind:"CreateTypeNode",name:this.transformNode(e.name,t),enum:this.transformNode(e.enum,t)})}transformDropType(e,t){return lt({kind:"DropTypeNode",name:this.transformNode(e.name,t),ifExists:e.ifExists})}transformExplain(e,t){return lt({kind:"ExplainNode",format:e.format,options:this.transformNode(e.options,t)})}transformSchemableIdentifier(e,t){return lt({kind:"SchemableIdentifierNode",schema:this.transformNode(e.schema,t),identifier:this.transformNode(e.identifier,t)})}transformAggregateFunction(e,t){return lt({kind:"AggregateFunctionNode",func:e.func,aggregated:this.transformNodeList(e.aggregated,t),distinct:e.distinct,orderBy:this.transformNode(e.orderBy,t),withinGroup:this.transformNode(e.withinGroup,t),filter:this.transformNode(e.filter,t),over:this.transformNode(e.over,t)})}transformOver(e,t){return lt({kind:"OverNode",orderBy:this.transformNode(e.orderBy,t),partitionBy:this.transformNode(e.partitionBy,t)})}transformPartitionBy(e,t){return lt({kind:"PartitionByNode",items:this.transformNodeList(e.items,t)})}transformPartitionByItem(e,t){return lt({kind:"PartitionByItemNode",partitionBy:this.transformNode(e.partitionBy,t)})}transformBinaryOperation(e,t){return lt({kind:"BinaryOperationNode",leftOperand:this.transformNode(e.leftOperand,t),operator:this.transformNode(e.operator,t),rightOperand:this.transformNode(e.rightOperand,t)})}transformUnaryOperation(e,t){return lt({kind:"UnaryOperationNode",operator:this.transformNode(e.operator,t),operand:this.transformNode(e.operand,t)})}transformUsing(e,t){return lt({kind:"UsingNode",tables:this.transformNodeList(e.tables,t)})}transformFunction(e,t){return lt({kind:"FunctionNode",func:e.func,arguments:this.transformNodeList(e.arguments,t)})}transformCase(e,t){return lt({kind:"CaseNode",value:this.transformNode(e.value,t),when:this.transformNodeList(e.when,t),else:this.transformNode(e.else,t),isStatement:e.isStatement})}transformWhen(e,t){return lt({kind:"WhenNode",condition:this.transformNode(e.condition,t),result:this.transformNode(e.result,t)})}transformJSONReference(e,t){return lt({kind:"JSONReferenceNode",reference:this.transformNode(e.reference,t),traversal:this.transformNode(e.traversal,t)})}transformJSONPath(e,t){return lt({kind:"JSONPathNode",inOperator:this.transformNode(e.inOperator,t),pathLegs:this.transformNodeList(e.pathLegs,t)})}transformJSONPathLeg(e,t){return lt({kind:"JSONPathLegNode",type:e.type,value:e.value})}transformJSONOperatorChain(e,t){return lt({kind:"JSONOperatorChainNode",operator:this.transformNode(e.operator,t),values:this.transformNodeList(e.values,t)})}transformTuple(e,t){return lt({kind:"TupleNode",values:this.transformNodeList(e.values,t)})}transformMergeQuery(e,t){return lt({kind:"MergeQueryNode",into:this.transformNode(e.into,t),using:this.transformNode(e.using,t),whens:this.transformNodeList(e.whens,t),with:this.transformNode(e.with,t),top:this.transformNode(e.top,t),endModifiers:this.transformNodeList(e.endModifiers,t),output:this.transformNode(e.output,t),returning:this.transformNode(e.returning,t)})}transformMatched(e,t){return lt({kind:"MatchedNode",not:e.not,bySource:e.bySource})}transformAddIndex(e,t){return lt({kind:"AddIndexNode",name:this.transformNode(e.name,t),columns:this.transformNodeList(e.columns,t),unique:e.unique,using:this.transformNode(e.using,t),ifNotExists:e.ifNotExists})}transformCast(e,t){return lt({kind:"CastNode",expression:this.transformNode(e.expression,t),dataType:this.transformNode(e.dataType,t)})}transformFetch(e,t){return lt({kind:"FetchNode",rowCount:this.transformNode(e.rowCount,t),modifier:e.modifier})}transformTop(e,t){return lt({kind:"TopNode",expression:e.expression,modifiers:e.modifiers})}transformOutput(e,t){return lt({kind:"OutputNode",selections:this.transformNodeList(e.selections,t)})}transformDataType(e,t){return e}transformSelectAll(e,t){return e}transformIdentifier(e,t){return e}transformValue(e,t){return e}transformPrimitiveValueList(e,t){return e}transformOperator(e,t){return e}transformDefaultInsertValue(e,t){return e}transformOrAction(e,t){return e}transformCollate(e,t){return e}}var Sie=m({AlterTableNode:!0,CreateIndexNode:!0,CreateSchemaNode:!0,CreateTableNode:!0,CreateTypeNode:!0,CreateViewNode:!0,RefreshMaterializedViewNode:!0,DeleteQueryNode:!0,DropIndexNode:!0,DropSchemaNode:!0,DropTableNode:!0,DropTypeNode:!0,DropViewNode:!0,InsertQueryNode:!0,RawNode:!0,SelectQueryNode:!0,UpdateQueryNode:!0,MergeQueryNode:!0}),Aie={json_agg:!0,to_json:!0};class ZS extends Dh{#e;#t=new Set;#r=new Set;constructor(e){super();this.#e=e}transformNodeImpl(e,t){if(!this.#i(e))return super.transformNodeImpl(e,t);let r=this.#c(e);for(let o of r)this.#r.add(o);let n=this.#s(e);for(let o of n)this.#t.add(o);let i=super.transformNodeImpl(e,t);for(let o of n)this.#t.delete(o);for(let o of r)this.#r.delete(o);return i}transformSchemableIdentifier(e,t){let r=super.transformSchemableIdentifier(e,t);if(r.schema||!this.#t.has(e.identifier.name))return r;return{...r,schema:$t.create(this.#e)}}transformReferences(e,t){let r=super.transformReferences(e,t);if(r.table.table.schema)return r;return{...r,table:co.createWithSchema(this.#e,r.table.table.identifier.name)}}transformAggregateFunction(e,t){return{...super.transformAggregateFunction({...e,aggregated:[]},t),aggregated:this.#n(e,t,"aggregated")}}transformFunction(e,t){return{...super.transformFunction({...e,arguments:[]},t),arguments:this.#n(e,t,"arguments")}}transformSelectModifier(e,t){return{...super.transformSelectModifier({...e,of:void 0},t),of:e.of?.map((r)=>co.is(r)&&!r.table.schema?{...r,table:this.transformIdentifier(r.table.identifier,t)}:this.transformNode(r,t))}}#n(e,t,r){return Aie[e.func]?e[r].map((n)=>!co.is(n)||n.table.schema?this.transformNode(n,t):{...n,table:this.transformIdentifier(n.table.identifier,t)}):this.transformNodeList(e[r],t)}#i(e){return e.kind in Sie}#s(e){let t=new Set;if("name"in e&&e.name&&ao.is(e.name))this.#a(e.name,t);if("from"in e&&e.from)for(let r of e.from.froms)this.#o(r,t);if("into"in e&&e.into)this.#o(e.into,t);if("table"in e&&e.table)this.#o(e.table,t);if("joins"in e&&e.joins)for(let r of e.joins)this.#o(r.table,t);if("using"in e&&e.using)if(Ds.is(e.using))this.#o(e.using.table,t);else this.#o(e.using,t);return t}#c(e){let t=new Set;if("with"in e&&e.with)this.#u(e.with,t);return t}#o(e,t){if(co.is(e))return this.#a(e.table,t);if(Bi.is(e)&&co.is(e.node))return this.#a(e.node.table,t);if(Kg.is(e)){for(let r of e.items)this.#o(r,t);return}if(Nh.is(e)){for(let r of e.tables)this.#o(r,t);return}}#a(e,t){let r=e.identifier.name;if(!this.#t.has(r)&&!this.#r.has(r))t.add(r)}#u(e,t){for(let r of e.expressions){let n=r.name.table.table.identifier.name;if(!this.#r.has(n))t.add(n)}}}class Bs{#e;constructor(e){this.#e=new ZS(e)}transformQuery(e){return this.#e.transformNode(e.node,e.queryId)}async transformResult(e){return e.result}}var nU=m({is(e){return e.kind==="MatchedNode"},create(e,t=!1){return m({kind:"MatchedNode",not:e,bySource:t})}});function eA(e,t,r){return ns.create(nl([nU.create(!e.isMatched,e.bySource),...t&&t.length>0?[t.length===3&&r?ji(t[0],t[1],t[2]):Vn(t)]:[]],"and",!1))}function dl(e){if(Ln(e))return pn.create([e],[]);if(Kn(e))return e.toOperationNode();return e}class $c{#e;#t;#r;constructor(){this.#e=new Promise((e,t)=>{this.#r=t,this.#t=e})}get promise(){return this.#e}resolve=(e)=>{if(this.#t)this.#t(e)};reject=(e)=>{if(this.#r)this.#r(e)}}async function Zg(e){let t=new $c,r=new $c;return e.provideConnection(async(n)=>(t.resolve(n),await r.promise)).catch((n)=>t.reject(n)),m({connection:await t.promise,release:r.resolve})}var Tie=m([]);class Uh{#e;constructor(e=Tie){this.#e=e}get plugins(){return this.#e}transformQuery(e,t){for(let r of this.#e){let n=r.transformQuery({node:e,queryId:t});if(n.kind===e.kind)e=n;else throw Error(["KyselyPlugin.transformQuery must return a node","of the same kind that was given to it.",`The plugin was given a ${e.kind}`,`but it returned a ${n.kind}`].join(" "))}return e}async executeQuery(e){return await this.provideConnection(async(t)=>{let r=await t.executeQuery(e);if("numUpdatedOrDeletedRows"in r)fa("kysely:warning: outdated driver/plugin detected! `QueryResult.numUpdatedOrDeletedRows` has been replaced with `QueryResult.numAffectedRows`.");return await this.#t(r,e.queryId)})}async*stream(e,t){let{connection:r,release:n}=await Zg(this);try{for await(let i of r.streamQuery(e,t))yield await this.#t(i,e.queryId)}finally{n()}}async#t(e,t){for(let r of this.#e)e=await r.transformResult({result:e,queryId:t});return e}}class ll extends Uh{get adapter(){throw Error("this query cannot be compiled to SQL")}compileQuery(){throw Error("this query cannot be compiled to SQL")}provideConnection(){throw Error("this query cannot be executed")}withConnectionProvider(){throw Error("this query cannot have a connection provider")}withPlugin(e){return new ll([...this.plugins,e])}withPlugins(e){return new ll([...this.plugins,...e])}withPluginAtFront(e){return new ll([e,...this.plugins])}withoutPlugins(){return new ll([])}}var Fc=new ll;class tA{numChangedRows;constructor(e){this.numChangedRows=e}}class Ya{#e;constructor(e){this.#e=m(e)}modifyEnd(e){return new Ya({...this.#e,queryNode:pt.cloneWithEndModifier(this.#e.queryNode,e.toOperationNode())})}top(e,t){return new Ya({...this.#e,queryNode:pt.cloneWithTop(this.#e.queryNode,Ms(e,t))})}using(...e){return new ko({...this.#e,queryNode:zo.cloneWithUsing(this.#e.queryNode,jc("Using",e))})}returning(e){return new Ya({...this.#e,queryNode:pt.cloneWithReturning(this.#e.queryNode,Ii(e))})}returningAll(e){return new Ya({...this.#e,queryNode:pt.cloneWithReturning(this.#e.queryNode,$i(e))})}output(e){return new Ya({...this.#e,queryNode:pt.cloneWithOutput(this.#e.queryNode,Ii(e))})}outputAll(e){return new Ya({...this.#e,queryNode:pt.cloneWithOutput(this.#e.queryNode,$i(e))})}}class ko{#e;constructor(e){this.#e=m(e)}modifyEnd(e){return new ko({...this.#e,queryNode:pt.cloneWithEndModifier(this.#e.queryNode,e.toOperationNode())})}top(e,t){return new ko({...this.#e,queryNode:pt.cloneWithTop(this.#e.queryNode,Ms(e,t))})}whenMatched(){return this.#t([])}whenMatchedAnd(...e){return this.#t(e)}whenMatchedAndRef(e,t,r){return this.#t([e,t,r],!0)}#t(e,t){return new rA({...this.#e,queryNode:zo.cloneWithWhen(this.#e.queryNode,eA({isMatched:!0},e,t))})}whenNotMatched(){return this.#r([])}whenNotMatchedAnd(...e){return this.#r(e)}whenNotMatchedAndRef(e,t,r){return this.#r([e,t,r],!0)}whenNotMatchedBySource(){return this.#r([],!1,!0)}whenNotMatchedBySourceAnd(...e){return this.#r(e,!1,!0)}whenNotMatchedBySourceAndRef(e,t,r){return this.#r([e,t,r],!0,!0)}returning(e){return new ko({...this.#e,queryNode:pt.cloneWithReturning(this.#e.queryNode,Ii(e))})}returningAll(e){return new ko({...this.#e,queryNode:pt.cloneWithReturning(this.#e.queryNode,$i(e))})}output(e){return new ko({...this.#e,queryNode:pt.cloneWithOutput(this.#e.queryNode,Ii(e))})}outputAll(e){return new ko({...this.#e,queryNode:pt.cloneWithOutput(this.#e.queryNode,$i(e))})}#r(e,t=!1,r=!1){let n={...this.#e,queryNode:zo.cloneWithWhen(this.#e.queryNode,eA({isMatched:!1,bySource:r},e,t))};return new(r?rA:iU)(n)}$call(e){return e(this)}$if(e,t){if(e)return t(this);return new ko({...this.#e})}toOperationNode(){return this.#e.executor.transformQuery(this.#e.queryNode,this.#e.queryId)}compile(){return this.#e.executor.compileQuery(this.toOperationNode(),this.#e.queryId)}async execute(){let e=this.compile(),t=await this.#e.executor.executeQuery(e),{adapter:r}=this.#e.executor,n=e.query;if(n.returning&&r.supportsReturning||n.output&&r.supportsOutput)return t.rows;return[new tA(t.numAffectedRows)]}async executeTakeFirst(){let[e]=await this.execute();return e}async executeTakeFirstOrThrow(e=Ls){let t=await this.executeTakeFirst();if(t===void 0)throw pa(e)?new e(this.toOperationNode()):e(this.toOperationNode());return t}}class rA{#e;constructor(e){this.#e=m(e)}thenDelete(){return new ko({...this.#e,queryNode:zo.cloneWithThen(this.#e.queryNode,dl("delete"))})}thenDoNothing(){return new ko({...this.#e,queryNode:zo.cloneWithThen(this.#e.queryNode,dl("do nothing"))})}thenUpdate(e){return new ko({...this.#e,queryNode:zo.cloneWithThen(this.#e.queryNode,dl(e(new cl({queryId:this.#e.queryId,executor:Fc,queryNode:ha.createWithoutTable()}))))})}thenUpdateSet(...e){return this.thenUpdate((t)=>t.set(...e))}}class iU{#e;constructor(e){this.#e=m(e)}thenDoNothing(){return new ko({...this.#e,queryNode:zo.cloneWithThen(this.#e.queryNode,dl("do nothing"))})}thenInsertValues(e){let[t,r]=Qg(e);return new ko({...this.#e,queryNode:zo.cloneWithThen(this.#e.queryNode,dl(di.cloneWith(di.createWithoutInto(),{columns:t,values:r})))})}}class ga{#e;constructor(e){this.#e=m(e)}selectFrom(e){return Ph({queryId:Vt(),executor:this.#e.executor,queryNode:mn.createFrom(qs(e),this.#e.withNode)})}selectNoFrom(e){return Ph({queryId:Vt(),executor:this.#e.executor,queryNode:mn.cloneWithSelections(mn.create(this.#e.withNode),Ii(e))})}insertInto(e){return new Wn({queryId:Vt(),executor:this.#e.executor,queryNode:di.create(wn(e),this.#e.withNode)})}replaceInto(e){return new Wn({queryId:Vt(),executor:this.#e.executor,queryNode:di.create(wn(e),this.#e.withNode,!0)})}deleteFrom(e){return new Yg({queryId:Vt(),executor:this.#e.executor,queryNode:Bc.create(qs(e),this.#e.withNode)})}updateTable(e){return new cl({queryId:Vt(),executor:this.#e.executor,queryNode:ha.create(qs(e),this.#e.withNode)})}mergeInto(e){return new Ya({queryId:Vt(),executor:this.#e.executor,queryNode:zo.create(nA(e),this.#e.withNode)})}with(e,t){let r=XS(e,t);return new ga({...this.#e,withNode:this.#e.withNode?Ih.cloneWithExpression(this.#e.withNode,r):Ih.create(r)})}withRecursive(e,t){let r=XS(e,t);return new ga({...this.#e,withNode:this.#e.withNode?Ih.cloneWithExpression(this.#e.withNode,r):Ih.create(r,{recursive:!0})})}withPlugin(e){return new ga({...this.#e,executor:this.#e.executor.withPlugin(e)})}withoutPlugins(){return new ga({...this.#e,executor:this.#e.executor.withoutPlugins()})}withSchema(e){return new ga({...this.#e,executor:this.#e.executor.withPluginAtFront(new Bs(e))})}}function eU(){return new ga({executor:Fc})}function oU(e,t){return new il({joinNode:Ds.create(e,Hu(t))})}function sU(){return new ol({overNode:Rh.create()})}function jc(e,t){if(t.length===3)return kie(e,t[0],t[1],t[2]);else if(t.length===2)return vie(e,t[0],t[1]);else if(t.length===1)return Rie(e,t[0]);else throw Error("not implemented")}function vie(e,t,r){return r(oU(e,t)).toOperationNode()}function kie(e,t,r,n){return Ds.createWithOn(e,Hu(t),ji(r,"=",n))}function Rie(e,t){return Ds.create(e,Hu(t))}var aU=m({is(e){return e.kind==="OffsetNode"},create(e){return m({kind:"OffsetNode",offset:e})}});var cU=m({is(e){return e.kind==="GroupByItemNode"},create(e){return m({kind:"GroupByItemNode",groupBy:e})}});function uU(e){return e=qn(e)?e(Ps()):e,Ja(e).map(cU.create)}var ey=m({is(e){return e.kind==="SetOperationNode"},create(e,t,r){return m({kind:"SetOperationNode",operator:e,expression:t,all:r})}});function Vu(e,t,r){if(qn(t))t=t(ty());if(!oo(t))t=[t];return t.map((n)=>ey.create(e,vo(n),r))}class Un{#e;constructor(e){this.#e=e}get expressionType(){return}as(e){return new iy(this,e)}or(...e){return new ry(Is.create(this.#e,Vn(e)))}and(...e){return new ny(To.create(this.#e,Vn(e)))}$castTo(){return new Un(this.#e)}$notNull(){return new Un(this.#e)}toOperationNode(){return this.#e}}class iy{#e;#t;constructor(e,t){this.#e=e,this.#t=t}get expression(){return this.#e}get alias(){return this.#t}toOperationNode(){return Bi.create(this.#e.toOperationNode(),Kn(this.#t)?this.#t.toOperationNode():$t.create(this.#t))}}class ry{#e;constructor(e){this.#e=e}get expressionType(){return}as(e){return new iy(this,e)}or(...e){return new ry(Is.create(this.#e,Vn(e)))}$castTo(){return new ry(this.#e)}toOperationNode(){return Fo.create(this.#e)}}class ny{#e;constructor(e){this.#e=e}get expressionType(){return}as(e){return new iy(this,e)}and(...e){return new ny(To.create(this.#e,Vn(e)))}$castTo(){return new ny(this.#e)}toOperationNode(){return Fo.create(this.#e)}}var dU=m({is(e){return e.kind==="FetchNode"},create(e,t){return{kind:"FetchNode",rowCount:Ti.create(e),modifier:t}}});function lU(e,t){if(!Cs(e)&&!Ic(e))throw Error(`Invalid fetch row count: ${e}`);if(!Nie(t))throw Error(`Invalid fetch modifier: ${t}`);return dU.create(e,t)}function Nie(e){return e==="only"||e==="with ties"}var Sr;class iA{#e;constructor(e){this.#e=m(e)}get expressionType(){return}get isSelectQueryBuilder(){return!0}where(...e){return new Sr({...this.#e,queryNode:pt.cloneWithWhere(this.#e.queryNode,Vn(e))})}whereRef(e,t,r){return new Sr({...this.#e,queryNode:pt.cloneWithWhere(this.#e.queryNode,ji(e,t,r))})}having(...e){return new Sr({...this.#e,queryNode:mn.cloneWithHaving(this.#e.queryNode,Vn(e))})}havingRef(e,t,r){return new Sr({...this.#e,queryNode:mn.cloneWithHaving(this.#e.queryNode,ji(e,t,r))})}select(e){return new Sr({...this.#e,queryNode:mn.cloneWithSelections(this.#e.queryNode,Ii(e))})}distinctOn(e){return new Sr({...this.#e,queryNode:mn.cloneWithDistinctOn(this.#e.queryNode,Ja(e))})}modifyFront(e){return new Sr({...this.#e,queryNode:mn.cloneWithFrontModifier(this.#e.queryNode,la.createWithExpression(e.toOperationNode()))})}modifyEnd(e){return new Sr({...this.#e,queryNode:pt.cloneWithEndModifier(this.#e.queryNode,la.createWithExpression(e.toOperationNode()))})}distinct(){return new Sr({...this.#e,queryNode:mn.cloneWithFrontModifier(this.#e.queryNode,la.create("Distinct"))})}forUpdate(e){return new Sr({...this.#e,queryNode:pt.cloneWithEndModifier(this.#e.queryNode,la.create("ForUpdate",e?Ah(e).map(wn):void 0))})}forShare(e){return new Sr({...this.#e,queryNode:pt.cloneWithEndModifier(this.#e.queryNode,la.create("ForShare",e?Ah(e).map(wn):void 0))})}forKeyShare(e){return new Sr({...this.#e,queryNode:pt.cloneWithEndModifier(this.#e.queryNode,la.create("ForKeyShare",e?Ah(e).map(wn):void 0))})}forNoKeyUpdate(e){return new Sr({...this.#e,queryNode:pt.cloneWithEndModifier(this.#e.queryNode,la.create("ForNoKeyUpdate",e?Ah(e).map(wn):void 0))})}skipLocked(){return new Sr({...this.#e,queryNode:pt.cloneWithEndModifier(this.#e.queryNode,la.create("SkipLocked"))})}noWait(){return new Sr({...this.#e,queryNode:pt.cloneWithEndModifier(this.#e.queryNode,la.create("NoWait"))})}selectAll(e){return new Sr({...this.#e,queryNode:mn.cloneWithSelections(this.#e.queryNode,$i(e))})}innerJoin(...e){return this.#t("InnerJoin",e)}leftJoin(...e){return this.#t("LeftJoin",e)}rightJoin(...e){return this.#t("RightJoin",e)}fullJoin(...e){return this.#t("FullJoin",e)}crossJoin(...e){return this.#t("CrossJoin",e)}innerJoinLateral(...e){return this.#t("LateralInnerJoin",e)}leftJoinLateral(...e){return this.#t("LateralLeftJoin",e)}crossJoinLateral(...e){return this.#t("LateralCrossJoin",e)}crossApply(...e){return this.#t("CrossApply",e)}outerApply(...e){return this.#t("OuterApply",e)}#t(e,t){return new Sr({...this.#e,queryNode:pt.cloneWithJoin(this.#e.queryNode,jc(e,t))})}orderBy(...e){return new Sr({...this.#e,queryNode:pt.cloneWithOrderByItems(this.#e.queryNode,$o(e))})}groupBy(e){return new Sr({...this.#e,queryNode:mn.cloneWithGroupByItems(this.#e.queryNode,uU(e))})}limit(e){return new Sr({...this.#e,queryNode:mn.cloneWithLimit(this.#e.queryNode,al.create(zn(e)))})}offset(e){return new Sr({...this.#e,queryNode:mn.cloneWithOffset(this.#e.queryNode,aU.create(zn(e)))})}fetch(e,t="only"){return new Sr({...this.#e,queryNode:mn.cloneWithFetch(this.#e.queryNode,lU(e,t))})}top(e,t){return new Sr({...this.#e,queryNode:pt.cloneWithTop(this.#e.queryNode,Ms(e,t))})}union(e){return new Sr({...this.#e,queryNode:mn.cloneWithSetOperations(this.#e.queryNode,Vu("union",e,!1))})}unionAll(e){return new Sr({...this.#e,queryNode:mn.cloneWithSetOperations(this.#e.queryNode,Vu("union",e,!0))})}intersect(e){return new Sr({...this.#e,queryNode:mn.cloneWithSetOperations(this.#e.queryNode,Vu("intersect",e,!1))})}intersectAll(e){return new Sr({...this.#e,queryNode:mn.cloneWithSetOperations(this.#e.queryNode,Vu("intersect",e,!0))})}except(e){return new Sr({...this.#e,queryNode:mn.cloneWithSetOperations(this.#e.queryNode,Vu("except",e,!1))})}exceptAll(e){return new Sr({...this.#e,queryNode:mn.cloneWithSetOperations(this.#e.queryNode,Vu("except",e,!0))})}as(e){return new fU(this,e)}clearSelect(){return new Sr({...this.#e,queryNode:mn.cloneWithoutSelections(this.#e.queryNode)})}clearWhere(){return new Sr({...this.#e,queryNode:pt.cloneWithoutWhere(this.#e.queryNode)})}clearLimit(){return new Sr({...this.#e,queryNode:mn.cloneWithoutLimit(this.#e.queryNode)})}clearOffset(){return new Sr({...this.#e,queryNode:mn.cloneWithoutOffset(this.#e.queryNode)})}clearOrderBy(){return new Sr({...this.#e,queryNode:pt.cloneWithoutOrderBy(this.#e.queryNode)})}clearGroupBy(){return new Sr({...this.#e,queryNode:mn.cloneWithoutGroupBy(this.#e.queryNode)})}$call(e){return e(this)}$if(e,t){if(e)return t(this);return new Sr({...this.#e})}$castTo(){return new Sr(this.#e)}$narrowType(){return new Sr(this.#e)}$assertType(){return new Sr(this.#e)}$asTuple(){return new Un(this.toOperationNode())}$asScalar(){return new Un(this.toOperationNode())}withPlugin(e){return new Sr({...this.#e,executor:this.#e.executor.withPlugin(e)})}toOperationNode(){return this.#e.executor.transformQuery(this.#e.queryNode,this.#e.queryId)}compile(){return this.#e.executor.compileQuery(this.toOperationNode(),this.#e.queryId)}async execute(){let e=this.compile();return(await this.#e.executor.executeQuery(e)).rows}async executeTakeFirst(){let[e]=await this.execute();return e}async executeTakeFirstOrThrow(e=Ls){let t=await this.executeTakeFirst();if(t===void 0)throw pa(e)?new e(this.toOperationNode()):e(this.toOperationNode());return t}async*stream(e=100){let t=this.compile(),r=this.#e.executor.stream(t,e);for await(let n of r)yield*n.rows}async explain(e,t){return await new Sr({...this.#e,queryNode:pt.cloneWithExplain(this.#e.queryNode,e,t)}).execute()}}Sr=iA;function Ph(e){return new iA(e)}class fU{#e;#t;constructor(e,t){this.#e=e,this.#t=t}get expression(){return this.#e}get alias(){return this.#t}get isAliasedSelectQueryBuilder(){return!0}toOperationNode(){return Bi.create(this.#e.toOperationNode(),$t.create(this.#t))}}var ya=m({is(e){return e.kind==="AggregateFunctionNode"},create(e,t=[]){return m({kind:"AggregateFunctionNode",func:e,aggregated:t})},cloneWithDistinct(e){return m({...e,distinct:!0})},cloneWithOrderBy(e,t,r=!1){let n=r?"withinGroup":"orderBy";return m({...e,[n]:e[n]?Qa.cloneWithItems(e[n],t):Qa.create(t)})},cloneWithFilter(e,t){return m({...e,filter:e.filter?Xi.cloneWithOperation(e.filter,"And",t):Xi.create(t)})},cloneWithOrFilter(e,t){return m({...e,filter:e.filter?Xi.cloneWithOperation(e.filter,"Or",t):Xi.create(t)})},cloneWithOver(e,t){return m({...e,over:t})}});var oA=m({is(e){return e.kind==="FunctionNode"},create(e,t){return m({kind:"FunctionNode",func:e,arguments:t})}});class Ro{#e;constructor(e){this.#e=m(e)}get expressionType(){return}as(e){return new hU(this,e)}distinct(){return new Ro({...this.#e,aggregateFunctionNode:ya.cloneWithDistinct(this.#e.aggregateFunctionNode)})}orderBy(...e){return new Ro({...this.#e,aggregateFunctionNode:pt.cloneWithOrderByItems(this.#e.aggregateFunctionNode,$o(e))})}clearOrderBy(){return new Ro({...this.#e,aggregateFunctionNode:pt.cloneWithoutOrderBy(this.#e.aggregateFunctionNode)})}withinGroupOrderBy(...e){return new Ro({...this.#e,aggregateFunctionNode:ya.cloneWithOrderBy(this.#e.aggregateFunctionNode,$o(e),!0)})}filterWhere(...e){return new Ro({...this.#e,aggregateFunctionNode:ya.cloneWithFilter(this.#e.aggregateFunctionNode,Vn(e))})}filterWhereRef(e,t,r){return new Ro({...this.#e,aggregateFunctionNode:ya.cloneWithFilter(this.#e.aggregateFunctionNode,ji(e,t,r))})}over(e){let t=sU();return new Ro({...this.#e,aggregateFunctionNode:ya.cloneWithOver(this.#e.aggregateFunctionNode,(e?e(t):t).toOperationNode())})}$call(e){return e(this)}$castTo(){return new Ro(this.#e)}$notNull(){return new Ro(this.#e)}toOperationNode(){return this.#e.aggregateFunctionNode}}class hU{#e;#t;constructor(e,t){this.#e=e,this.#t=t}get expression(){return this.#e}get alias(){return this.#t}toOperationNode(){return Bi.create(this.#e.toOperationNode(),$t.create(this.#t))}}function oy(){let e=(r,n)=>new Un(oA.create(r,Ja(n??[]))),t=(r,n)=>new Ro({aggregateFunctionNode:ya.create(r,n?Ja(n):void 0)});return Object.assign(e,{agg:t,avg(r){return t("avg",[r])},coalesce(...r){return e("coalesce",r)},count(r){return t("count",[r])},countAll(r){return new Ro({aggregateFunctionNode:ya.create("count",$i(r))})},max(r){return t("max",[r])},min(r){return t("min",[r])},sum(r){return t("sum",[r])},any(r){return e("any",[r])},jsonAgg(r){return new Ro({aggregateFunctionNode:ya.create("json_agg",[Ln(r)?wn(r):r.toOperationNode()])})},toJson(r){return new Un(oA.create("to_json",[Ln(r)?wn(r):r.toOperationNode()]))}})}var pU=m({is(e){return e.kind==="UnaryOperationNode"},create(e,t){return m({kind:"UnaryOperationNode",operator:e,operand:t})}});function mU(e,t){return pU.create(Bo.create(e),Yi(t))}var Wo=m({is(e){return e.kind==="CaseNode"},create(e){return m({kind:"CaseNode",value:e})},cloneWithWhen(e,t){return m({...e,when:m(e.when?[...e.when,t]:[t])})},cloneWithThen(e,t){return m({...e,when:e.when?m([...e.when.slice(0,-1),ns.cloneWithResult(e.when[e.when.length-1],t)]):void 0})},cloneWith(e,t){return m({...e,...t})}});class Lh{#e;constructor(e){this.#e=m(e)}when(...e){return new sA({...this.#e,node:Wo.cloneWithWhen(this.#e.node,ns.create(Vn(e)))})}}class sA{#e;constructor(e){this.#e=m(e)}then(e){return new gU({...this.#e,node:Wo.cloneWithThen(this.#e.node,Vg(e)?kh(e):zn(e))})}}class gU{#e;constructor(e){this.#e=m(e)}when(...e){return new sA({...this.#e,node:Wo.cloneWithWhen(this.#e.node,ns.create(Vn(e)))})}else(e){return new yU({...this.#e,node:Wo.cloneWith(this.#e.node,{else:Vg(e)?kh(e):zn(e)})})}end(){return new Un(Wo.cloneWith(this.#e.node,{isStatement:!1}))}endCase(){return new Un(Wo.cloneWith(this.#e.node,{isStatement:!0}))}}class yU{#e;constructor(e){this.#e=m(e)}end(){return new Un(Wo.cloneWith(this.#e.node,{isStatement:!1}))}endCase(){return new Un(Wo.cloneWith(this.#e.node,{isStatement:!0}))}}var aA=m({is(e){return e.kind==="JSONPathLegNode"},create(e,t){return m({kind:"JSONPathLegNode",type:e,value:t})}});var xie=/^#-\d+$/;class qh{#e;constructor(e){this.#e=e}at(e){if(typeof e!=="number"&&typeof e!=="string"||typeof e==="number"&&!Number.isInteger(e)||typeof e==="string"&&e!=="last"&&!xie.test(e))throw Error(`Unexpected index value in .at(...): ${e}`);return this.#t("ArrayLocation",e)}key(e){return this.#t("Member",e)}#t(e,t){if(tl.is(this.#e))return new Mh(tl.cloneWithTraversal(this.#e,Mc.is(this.#e.traversal)?Mc.cloneWithLeg(this.#e.traversal,aA.create(e,t)):Wg.cloneWithValue(this.#e.traversal,Ti.createImmediate(t))));return new Mh(Mc.cloneWithLeg(this.#e,aA.create(e,t)))}}class Mh extends qh{#e;constructor(e){super(e);this.#e=e}get expressionType(){return}as(e){return new wU(this,e)}$castTo(){return new Mh(this.#e)}$notNull(){return new Mh(this.#e)}toOperationNode(){return this.#e}}class wU{#e;#t;constructor(e,t){this.#e=e,this.#t=t}get expression(){return this.#e}get alias(){return this.#t}toOperationNode(){return Bi.create(this.#e.toOperationNode(),Kn(this.#t)?this.#t.toOperationNode():$t.create(this.#t))}}var cA=m({is(e){return e.kind==="TupleNode"},create(e){return m({kind:"TupleNode",values:m(e)})}});var Cie=["varchar","char","text","integer","int2","int4","int8","smallint","bigint","boolean","real","double precision","float4","float8","decimal","numeric","binary","bytea","date","datetime","time","timetz","timestamp","timestamptz","serial","bigserial","uuid","json","jsonb","blob","varbinary","int4range","int4multirange","int8range","int8multirange","numrange","nummultirange","tsrange","tsmultirange","tstzrange","tstzmultirange","daterange","datemultirange"],Oie=[/^varchar\(\d+\)$/,/^char\(\d+\)$/,/^decimal\(\d+, \d+\)$/,/^numeric\(\d+, \d+\)$/,/^binary\(\d+\)$/,/^datetime\(\d+\)$/,/^time\(\d+\)$/,/^timetz\(\d+\)$/,/^timestamp\(\d+\)$/,/^timestamptz\(\d+\)$/,/^varbinary\(\d+\)$/],_U=m({is(e){return e.kind==="DataTypeNode"},create(e){return m({kind:"DataTypeNode",dataType:e})}});function bU(e){if(Cie.includes(e))return!0;if(Oie.some((t)=>t.test(e)))return!0;return!1}function js(e){if(Kn(e))return e.toOperationNode();if(bU(e))return _U.create(e);throw Error(`invalid column data type ${JSON.stringify(e)}`)}var EU=m({is(e){return e.kind==="CastNode"},create(e,t){return m({kind:"CastNode",expression:e,dataType:t})}});function ty(e=Fc){function t(i,o,s){return new Un(Gg(i,o,s))}function r(i,o){return new Un(mU(i,o))}let n=Object.assign(t,{fn:void 0,eb:void 0,selectFrom(i){return Ph({queryId:Vt(),executor:e,queryNode:mn.createFrom(qs(i))})},case(i){return new Lh({node:Wo.create(mo(i)?void 0:Yi(i))})},ref(i,o){if(mo(o))return new Un(jo(i));return new qh(MD(i,o))},jsonPath(){return new qh(Mc.create())},table(i){return new Un(wn(i))},val(i){return new Un(zn(i))},refTuple(...i){return new Un(cA.create(i.map(Yi)))},tuple(...i){return new Un(cA.create(i.map(zn)))},lit(i){return new Un(kh(i))},unary:r,not(i){return r("not",i)},exists(i){return r("exists",i)},neg(i){return r("-",i)},between(i,o,s){return new Un(Uc.create(Yi(i),Bo.create("between"),To.create(zn(o),zn(s))))},betweenSymmetric(i,o,s){return new Un(Uc.create(Yi(i),Bo.create("between symmetric"),To.create(zn(o),zn(s))))},and(i){if(oo(i))return new Un(nl(i,"and"));return new Un($S(i,"and"))},or(i){if(oo(i))return new Un(nl(i,"or"));return new Un($S(i,"or"))},parens(...i){let o=Vn(i);if(Fo.is(o))return new Un(o);else return new Un(Fo.create(o))},cast(i,o){return new Un(EU.create(Yi(i),js(o)))},withSchema(i){return ty(e.withPluginAtFront(new Bs(i)))}});return n.fn=oy(),n.eb=n,n}function Ps(e){return ty()}function vo(e){if(Kn(e))return e.toOperationNode();else if(qn(e))return e(Ps()).toOperationNode();throw Error(`invalid expression: ${JSON.stringify(e)}`)}function Jg(e){if(Kn(e))return e.toOperationNode();else if(qn(e))return e(Ps()).toOperationNode();throw Error(`invalid aliased expression: ${JSON.stringify(e)}`)}function Ka(e){return $g(e)||OD(e)||qn(e)}class uA{#e;get table(){return this.#e}constructor(e){this.#e=e}as(e){return new SU(this.#e,e)}}class SU{#e;#t;get table(){return this.#e}get alias(){return this.#t}constructor(e,t){this.#e=e,this.#t=t}toOperationNode(){return Bi.create(wn(this.#e),$t.create(this.#t))}}function AU(e){return wi(e)&&Kn(e)&&Ln(e.table)&&Ln(e.alias)}function qs(e){if(oo(e))return e.map((t)=>Hu(t));else return[Hu(e)]}function Hu(e){if(Ln(e))return nA(e);else if(AU(e))return e.toOperationNode();else return Jg(e)}function nA(e){if(e.includes(" as ")){let[r,n]=e.split(" as ").map(TU);return Bi.create(wn(r),$t.create(n))}else return wn(e)}function wn(e){if(e.includes(".")){let[r,n]=e.split(".").map(TU);return co.createWithSchema(r,n)}else return co.create(e)}function TU(e){return e.trim()}var dA=m({is(e){return e.kind==="AddColumnNode"},create(e){return m({kind:"AddColumnNode",column:e})}});var Jn=m({is(e){return e.kind==="ColumnDefinitionNode"},create(e,t){return m({kind:"ColumnDefinitionNode",column:Hr.create(e),dataType:t})},cloneWithFrontModifier(e,t){return m({...e,frontModifiers:e.frontModifiers?m([...e.frontModifiers,t]):[t]})},cloneWithEndModifier(e,t){return m({...e,endModifiers:e.endModifiers?m([...e.endModifiers,t]):[t]})},cloneWith(e,t){return m({...e,...t})}});var lA=m({is(e){return e.kind==="DropColumnNode"},create(e){return m({kind:"DropColumnNode",column:Hr.create(e)})}});var fA=m({is(e){return e.kind==="RenameColumnNode"},create(e,t){return m({kind:"RenameColumnNode",column:Hr.create(e),renameTo:Hr.create(t)})}});var fl=m({is(e){return e.kind==="CheckConstraintNode"},create(e,t){return m({kind:"CheckConstraintNode",expression:e,name:t?$t.create(t):void 0})}});var vU=["no action","restrict","cascade","set null","set default"],hl=m({is(e){return e.kind==="ReferencesNode"},create(e,t){return m({kind:"ReferencesNode",table:e,columns:m([...t])})},cloneWithOnDelete(e,t){return m({...e,onDelete:t})},cloneWithOnUpdate(e,t){return m({...e,onUpdate:t})}});function sy(e){return Kn(e)?e.toOperationNode():Ti.createImmediate(e)}var Bh=m({is(e){return e.kind==="GeneratedNode"},create(e){return m({kind:"GeneratedNode",...e})},createWithExpression(e){return m({kind:"GeneratedNode",always:!0,expression:e})},cloneWith(e,t){return m({...e,...t})}});var kU=m({is(e){return e.kind==="DefaultValueNode"},create(e){return m({kind:"DefaultValueNode",defaultValue:e})}});function pl(e){if(vU.includes(e))return e;throw Error(`invalid OnModifyForeignAction ${e}`)}class Qn{#e;constructor(e){this.#e=e}autoIncrement(){return new Qn(Jn.cloneWith(this.#e,{autoIncrement:!0}))}identity(){return new Qn(Jn.cloneWith(this.#e,{identity:!0}))}primaryKey(){return new Qn(Jn.cloneWith(this.#e,{primaryKey:!0}))}references(e){let t=jo(e);if(!t.table||el.is(t.column))throw Error(`invalid call references('${e}'). The reference must have format table.column or schema.table.column`);return new Qn(Jn.cloneWith(this.#e,{references:hl.create(t.table,[t.column])}))}onDelete(e){if(!this.#e.references)throw Error("on delete constraint can only be added for foreign keys");return new Qn(Jn.cloneWith(this.#e,{references:hl.cloneWithOnDelete(this.#e.references,pl(e))}))}onUpdate(e){if(!this.#e.references)throw Error("on update constraint can only be added for foreign keys");return new Qn(Jn.cloneWith(this.#e,{references:hl.cloneWithOnUpdate(this.#e.references,pl(e))}))}unique(){return new Qn(Jn.cloneWith(this.#e,{unique:!0}))}notNull(){return new Qn(Jn.cloneWith(this.#e,{notNull:!0}))}unsigned(){return new Qn(Jn.cloneWith(this.#e,{unsigned:!0}))}defaultTo(e){return new Qn(Jn.cloneWith(this.#e,{defaultTo:kU.create(sy(e))}))}check(e){return new Qn(Jn.cloneWith(this.#e,{check:fl.create(e.toOperationNode())}))}generatedAlwaysAs(e){return new Qn(Jn.cloneWith(this.#e,{generated:Bh.createWithExpression(e.toOperationNode())}))}generatedAlwaysAsIdentity(){return new Qn(Jn.cloneWith(this.#e,{generated:Bh.create({identity:!0,always:!0})}))}generatedByDefaultAsIdentity(){return new Qn(Jn.cloneWith(this.#e,{generated:Bh.create({identity:!0,byDefault:!0})}))}stored(){if(!this.#e.generated)throw Error("stored() can only be called after generatedAlwaysAs");return new Qn(Jn.cloneWith(this.#e,{generated:Bh.cloneWith(this.#e.generated,{stored:!0})}))}modifyFront(e){return new Qn(Jn.cloneWithFrontModifier(this.#e,e.toOperationNode()))}nullsNotDistinct(){return new Qn(Jn.cloneWith(this.#e,{nullsNotDistinct:!0}))}ifNotExists(){return new Qn(Jn.cloneWith(this.#e,{ifNotExists:!0}))}modifyEnd(e){return new Qn(Jn.cloneWithEndModifier(this.#e,e.toOperationNode()))}$call(e){return e(this)}toOperationNode(){return this.#e}}var hA=m({is(e){return e.kind==="ModifyColumnNode"},create(e){return m({kind:"ModifyColumnNode",column:e})}});var $s=m({is(e){return e.kind==="ForeignKeyConstraintNode"},create(e,t,r,n){return m({kind:"ForeignKeyConstraintNode",columns:e,references:hl.create(t,r),name:n?$t.create(n):void 0})},cloneWith(e,t){return m({...e,...t})}});class Fs{#e;constructor(e){this.#e=e}onDelete(e){return new Fs($s.cloneWith(this.#e,{onDelete:pl(e)}))}onUpdate(e){return new Fs($s.cloneWith(this.#e,{onUpdate:pl(e)}))}deferrable(){return new Fs($s.cloneWith(this.#e,{deferrable:!0}))}notDeferrable(){return new Fs($s.cloneWith(this.#e,{deferrable:!1}))}initiallyDeferred(){return new Fs($s.cloneWith(this.#e,{initiallyDeferred:!0}))}initiallyImmediate(){return new Fs($s.cloneWith(this.#e,{initiallyDeferred:!1}))}$call(e){return e(this)}toOperationNode(){return this.#e}}var ml=m({is(e){return e.kind==="AddConstraintNode"},create(e){return m({kind:"AddConstraintNode",constraint:e})}});var wa=m({is(e){return e.kind==="UniqueConstraintNode"},create(e,t,r){return m({kind:"UniqueConstraintNode",columns:m(e.map(Hr.create)),name:t?$t.create(t):void 0,nullsNotDistinct:r})},cloneWith(e,t){return m({...e,...t})}});var gl=m({is(e){return e.kind==="DropConstraintNode"},create(e){return m({kind:"DropConstraintNode",constraintName:$t.create(e)})},cloneWith(e,t){return m({...e,...t})}});var yl=m({is(e){return e.kind==="AlterColumnNode"},create(e,t,r){return m({kind:"AlterColumnNode",column:Hr.create(e),[t]:r})}});class ay{#e;constructor(e){this.#e=e}setDataType(e){return new wl(yl.create(this.#e,"dataType",js(e)))}setDefault(e){return new wl(yl.create(this.#e,"setDefault",sy(e)))}dropDefault(){return new wl(yl.create(this.#e,"dropDefault",!0))}setNotNull(){return new wl(yl.create(this.#e,"setNotNull",!0))}dropNotNull(){return new wl(yl.create(this.#e,"dropNotNull",!0))}$call(e){return e(this)}}class wl{#e;constructor(e){this.#e=e}toOperationNode(){return this.#e}}class zc{#e;constructor(e){this.#e=m(e)}toOperationNode(){return this.#e.executor.transformQuery(this.#e.node,this.#e.queryId)}compile(){return this.#e.executor.compileQuery(this.toOperationNode(),this.#e.queryId)}async execute(){await this.#e.executor.executeQuery(this.compile())}}class Xa{#e;constructor(e){this.#e=m(e)}onDelete(e){return new Xa({...this.#e,constraintBuilder:this.#e.constraintBuilder.onDelete(e)})}onUpdate(e){return new Xa({...this.#e,constraintBuilder:this.#e.constraintBuilder.onUpdate(e)})}deferrable(){return new Xa({...this.#e,constraintBuilder:this.#e.constraintBuilder.deferrable()})}notDeferrable(){return new Xa({...this.#e,constraintBuilder:this.#e.constraintBuilder.notDeferrable()})}initiallyDeferred(){return new Xa({...this.#e,constraintBuilder:this.#e.constraintBuilder.initiallyDeferred()})}initiallyImmediate(){return new Xa({...this.#e,constraintBuilder:this.#e.constraintBuilder.initiallyImmediate()})}$call(e){return e(this)}toOperationNode(){return this.#e.executor.transformQuery(dn.cloneWithTableProps(this.#e.node,{addConstraint:ml.create(this.#e.constraintBuilder.toOperationNode())}),this.#e.queryId)}compile(){return this.#e.executor.compileQuery(this.toOperationNode(),this.#e.queryId)}async execute(){await this.#e.executor.executeQuery(this.compile())}}class Gu{#e;constructor(e){this.#e=m(e)}ifExists(){return new Gu({...this.#e,node:dn.cloneWithTableProps(this.#e.node,{dropConstraint:gl.cloneWith(this.#e.node.dropConstraint,{ifExists:!0})})})}cascade(){return new Gu({...this.#e,node:dn.cloneWithTableProps(this.#e.node,{dropConstraint:gl.cloneWith(this.#e.node.dropConstraint,{modifier:"cascade"})})})}restrict(){return new Gu({...this.#e,node:dn.cloneWithTableProps(this.#e.node,{dropConstraint:gl.cloneWith(this.#e.node.dropConstraint,{modifier:"restrict"})})})}$call(e){return e(this)}toOperationNode(){return this.#e.executor.transformQuery(this.#e.node,this.#e.queryId)}compile(){return this.#e.executor.compileQuery(this.toOperationNode(),this.#e.queryId)}async execute(){await this.#e.executor.executeQuery(this.compile())}}var Za=m({is(e){return e.kind==="PrimaryKeyConstraintNode"},create(e,t){return m({kind:"PrimaryKeyConstraintNode",columns:m(e.map(Hr.create)),name:t?$t.create(t):void 0})},cloneWith(e,t){return m({...e,...t})}});var Wc=m({is(e){return e.kind==="AddIndexNode"},create(e){return m({kind:"AddIndexNode",name:$t.create(e)})},cloneWith(e,t){return m({...e,...t})},cloneWithColumns(e,t){return m({...e,columns:[...e.columns||[],...t]})}});class Hc{#e;constructor(e){this.#e=m(e)}unique(){return new Hc({...this.#e,node:dn.cloneWithTableProps(this.#e.node,{addIndex:Wc.cloneWith(this.#e.node.addIndex,{unique:!0})})})}column(e){return new Hc({...this.#e,node:dn.cloneWithTableProps(this.#e.node,{addIndex:Wc.cloneWithColumns(this.#e.node.addIndex,[rl(e)])})})}columns(e){return new Hc({...this.#e,node:dn.cloneWithTableProps(this.#e.node,{addIndex:Wc.cloneWithColumns(this.#e.node.addIndex,e.map(rl))})})}expression(e){return new Hc({...this.#e,node:dn.cloneWithTableProps(this.#e.node,{addIndex:Wc.cloneWithColumns(this.#e.node.addIndex,[e.toOperationNode()])})})}using(e){return new Hc({...this.#e,node:dn.cloneWithTableProps(this.#e.node,{addIndex:Wc.cloneWith(this.#e.node.addIndex,{using:pn.createWithSql(e)})})})}$call(e){return e(this)}toOperationNode(){return this.#e.executor.transformQuery(this.#e.node,this.#e.queryId)}compile(){return this.#e.executor.compileQuery(this.toOperationNode(),this.#e.queryId)}async execute(){await this.#e.executor.executeQuery(this.compile())}}class _a{#e;constructor(e){this.#e=e}nullsNotDistinct(){return new _a(wa.cloneWith(this.#e,{nullsNotDistinct:!0}))}deferrable(){return new _a(wa.cloneWith(this.#e,{deferrable:!0}))}notDeferrable(){return new _a(wa.cloneWith(this.#e,{deferrable:!1}))}initiallyDeferred(){return new _a(wa.cloneWith(this.#e,{initiallyDeferred:!0}))}initiallyImmediate(){return new _a(wa.cloneWith(this.#e,{initiallyDeferred:!1}))}$call(e){return e(this)}toOperationNode(){return this.#e}}class ec{#e;constructor(e){this.#e=e}deferrable(){return new ec(Za.cloneWith(this.#e,{deferrable:!0}))}notDeferrable(){return new ec(Za.cloneWith(this.#e,{deferrable:!1}))}initiallyDeferred(){return new ec(Za.cloneWith(this.#e,{initiallyDeferred:!0}))}initiallyImmediate(){return new ec(Za.cloneWith(this.#e,{initiallyDeferred:!1}))}$call(e){return e(this)}toOperationNode(){return this.#e}}class jh{#e;constructor(e){this.#e=e}$call(e){return e(this)}toOperationNode(){return this.#e}}var RU=m({is(e){return e.kind==="RenameConstraintNode"},create(e,t){return m({kind:"RenameConstraintNode",oldName:$t.create(e),newName:$t.create(t)})}});class pA{#e;constructor(e){this.#e=m(e)}renameTo(e){return new zc({...this.#e,node:dn.cloneWithTableProps(this.#e.node,{renameTo:wn(e)})})}setSchema(e){return new zc({...this.#e,node:dn.cloneWithTableProps(this.#e.node,{setSchema:$t.create(e)})})}alterColumn(e,t){let r=t(new ay(e));return new zs({...this.#e,node:dn.cloneWithColumnAlteration(this.#e.node,r.toOperationNode())})}dropColumn(e){return new zs({...this.#e,node:dn.cloneWithColumnAlteration(this.#e.node,lA.create(e))})}renameColumn(e,t){return new zs({...this.#e,node:dn.cloneWithColumnAlteration(this.#e.node,fA.create(e,t))})}addColumn(e,t,r=go){let n=r(new Qn(Jn.create(e,js(t))));return new zs({...this.#e,node:dn.cloneWithColumnAlteration(this.#e.node,dA.create(n.toOperationNode()))})}modifyColumn(e,t,r=go){let n=r(new Qn(Jn.create(e,js(t))));return new zs({...this.#e,node:dn.cloneWithColumnAlteration(this.#e.node,hA.create(n.toOperationNode()))})}addUniqueConstraint(e,t,r=go){let n=r(new _a(wa.create(t,e)));return new zc({...this.#e,node:dn.cloneWithTableProps(this.#e.node,{addConstraint:ml.create(n.toOperationNode())})})}addCheckConstraint(e,t,r=go){let n=r(new jh(fl.create(t.toOperationNode(),e)));return new zc({...this.#e,node:dn.cloneWithTableProps(this.#e.node,{addConstraint:ml.create(n.toOperationNode())})})}addForeignKeyConstraint(e,t,r,n,i=go){let o=i(new Fs($s.create(t.map(Hr.create),wn(r),n.map(Hr.create),e)));return new Xa({...this.#e,constraintBuilder:o})}addPrimaryKeyConstraint(e,t,r=go){let n=r(new ec(Za.create(t,e)));return new zc({...this.#e,node:dn.cloneWithTableProps(this.#e.node,{addConstraint:ml.create(n.toOperationNode())})})}dropConstraint(e){return new Gu({...this.#e,node:dn.cloneWithTableProps(this.#e.node,{dropConstraint:gl.create(e)})})}renameConstraint(e,t){return new Gu({...this.#e,node:dn.cloneWithTableProps(this.#e.node,{renameConstraint:RU.create(e,t)})})}addIndex(e){return new Hc({...this.#e,node:dn.cloneWithTableProps(this.#e.node,{addIndex:Wc.create(e)})})}dropIndex(e){return new zc({...this.#e,node:dn.cloneWithTableProps(this.#e.node,{dropIndex:Dc.create(e)})})}$call(e){return e(this)}}class zs{#e;constructor(e){this.#e=m(e)}alterColumn(e,t){let r=t(new ay(e));return new zs({...this.#e,node:dn.cloneWithColumnAlteration(this.#e.node,r.toOperationNode())})}dropColumn(e){return new zs({...this.#e,node:dn.cloneWithColumnAlteration(this.#e.node,lA.create(e))})}renameColumn(e,t){return new zs({...this.#e,node:dn.cloneWithColumnAlteration(this.#e.node,fA.create(e,t))})}addColumn(e,t,r=go){let n=r(new Qn(Jn.create(e,js(t))));return new zs({...this.#e,node:dn.cloneWithColumnAlteration(this.#e.node,dA.create(n.toOperationNode()))})}modifyColumn(e,t,r=go){let n=r(new Qn(Jn.create(e,js(t))));return new zs({...this.#e,node:dn.cloneWithColumnAlteration(this.#e.node,hA.create(n.toOperationNode()))})}toOperationNode(){return this.#e.executor.transformQuery(this.#e.node,this.#e.queryId)}compile(){return this.#e.executor.compileQuery(this.toOperationNode(),this.#e.queryId)}async execute(){await this.#e.executor.executeQuery(this.compile())}}class $h extends Dh{transformPrimitiveValueList(e){return qc.create(e.values.map(Ti.createImmediate))}transformValue(e){return Ti.createImmediate(e.value)}}class is{#e;constructor(e){this.#e=m(e)}ifNotExists(){return new is({...this.#e,node:Os.cloneWith(this.#e.node,{ifNotExists:!0})})}unique(){return new is({...this.#e,node:Os.cloneWith(this.#e.node,{unique:!0})})}nullsNotDistinct(){return new is({...this.#e,node:Os.cloneWith(this.#e.node,{nullsNotDistinct:!0})})}on(e){return new is({...this.#e,node:Os.cloneWith(this.#e.node,{table:wn(e)})})}column(e){return new is({...this.#e,node:Os.cloneWithColumns(this.#e.node,[rl(e)])})}columns(e){return new is({...this.#e,node:Os.cloneWithColumns(this.#e.node,e.map(rl))})}expression(e){return new is({...this.#e,node:Os.cloneWithColumns(this.#e.node,[e.toOperationNode()])})}using(e){return new is({...this.#e,node:Os.cloneWith(this.#e.node,{using:pn.createWithSql(e)})})}where(...e){let t=new $h;return new is({...this.#e,node:pt.cloneWithWhere(this.#e.node,t.transformNode(Vn(e),this.#e.queryId))})}$call(e){return e(this)}toOperationNode(){return this.#e.executor.transformQuery(this.#e.node,this.#e.queryId)}compile(){return this.#e.executor.compileQuery(this.toOperationNode(),this.#e.queryId)}async execute(){await this.#e.executor.executeQuery(this.compile())}}class cy{#e;constructor(e){this.#e=m(e)}ifNotExists(){return new cy({...this.#e,node:jg.cloneWith(this.#e.node,{ifNotExists:!0})})}$call(e){return e(this)}toOperationNode(){return this.#e.executor.transformQuery(this.#e.node,this.#e.queryId)}compile(){return this.#e.executor.compileQuery(this.toOperationNode(),this.#e.queryId)}async execute(){await this.#e.executor.executeQuery(this.compile())}}function NU(e){if(CD.includes(e))return e;throw Error(`invalid OnCommitAction ${e}`)}class No{#e;constructor(e){this.#e=m(e)}temporary(){return new No({...this.#e,node:so.cloneWith(this.#e.node,{temporary:!0})})}onCommit(e){return new No({...this.#e,node:so.cloneWith(this.#e.node,{onCommit:NU(e)})})}ifNotExists(){return new No({...this.#e,node:so.cloneWith(this.#e.node,{ifNotExists:!0})})}addColumn(e,t,r=go){let n=r(new Qn(Jn.create(e,js(t))));return new No({...this.#e,node:so.cloneWithColumn(this.#e.node,n.toOperationNode())})}addPrimaryKeyConstraint(e,t,r=go){let n=r(new ec(Za.create(t,e)));return new No({...this.#e,node:so.cloneWithConstraint(this.#e.node,n.toOperationNode())})}addUniqueConstraint(e,t,r=go){let n=r(new _a(wa.create(t,e)));return new No({...this.#e,node:so.cloneWithConstraint(this.#e.node,n.toOperationNode())})}addCheckConstraint(e,t,r=go){let n=r(new jh(fl.create(t.toOperationNode(),e)));return new No({...this.#e,node:so.cloneWithConstraint(this.#e.node,n.toOperationNode())})}addForeignKeyConstraint(e,t,r,n,i=go){let o=i(new Fs($s.create(t.map(Hr.create),wn(r),n.map(Hr.create),e)));return new No({...this.#e,node:so.cloneWithConstraint(this.#e.node,o.toOperationNode())})}modifyFront(e){return new No({...this.#e,node:so.cloneWithFrontModifier(this.#e.node,e.toOperationNode())})}modifyEnd(e){return new No({...this.#e,node:so.cloneWithEndModifier(this.#e.node,e.toOperationNode())})}as(e){return new No({...this.#e,node:so.cloneWith(this.#e.node,{selectQuery:vo(e)})})}$call(e){return e(this)}toOperationNode(){return this.#e.executor.transformQuery(this.#e.node,this.#e.queryId)}compile(){return this.#e.executor.compileQuery(this.toOperationNode(),this.#e.queryId)}async execute(){await this.#e.executor.executeQuery(this.compile())}}class _l{#e;constructor(e){this.#e=m(e)}on(e){return new _l({...this.#e,node:Dc.cloneWith(this.#e.node,{table:wn(e)})})}ifExists(){return new _l({...this.#e,node:Dc.cloneWith(this.#e.node,{ifExists:!0})})}cascade(){return new _l({...this.#e,node:Dc.cloneWith(this.#e.node,{cascade:!0})})}$call(e){return e(this)}toOperationNode(){return this.#e.executor.transformQuery(this.#e.node,this.#e.queryId)}compile(){return this.#e.executor.compileQuery(this.toOperationNode(),this.#e.queryId)}async execute(){await this.#e.executor.executeQuery(this.compile())}}class Fh{#e;constructor(e){this.#e=m(e)}ifExists(){return new Fh({...this.#e,node:Th.cloneWith(this.#e.node,{ifExists:!0})})}cascade(){return new Fh({...this.#e,node:Th.cloneWith(this.#e.node,{cascade:!0})})}$call(e){return e(this)}toOperationNode(){return this.#e.executor.transformQuery(this.#e.node,this.#e.queryId)}compile(){return this.#e.executor.compileQuery(this.toOperationNode(),this.#e.queryId)}async execute(){await this.#e.executor.executeQuery(this.compile())}}class zh{#e;constructor(e){this.#e=m(e)}ifExists(){return new zh({...this.#e,node:vh.cloneWith(this.#e.node,{ifExists:!0})})}cascade(){return new zh({...this.#e,node:vh.cloneWith(this.#e.node,{cascade:!0})})}$call(e){return e(this)}toOperationNode(){return this.#e.executor.transformQuery(this.#e.node,this.#e.queryId)}compile(){return this.#e.executor.compileQuery(this.toOperationNode(),this.#e.queryId)}async execute(){await this.#e.executor.executeQuery(this.compile())}}var Ws=m({is(e){return e.kind==="CreateViewNode"},create(e){return m({kind:"CreateViewNode",name:ao.create(e)})},cloneWith(e,t){return m({...e,...t})}});class mA{#e=new $h;transformQuery(e){return this.#e.transformNode(e.node,e.queryId)}transformResult(e){return Promise.resolve(e.result)}}class tc{#e;constructor(e){this.#e=m(e)}temporary(){return new tc({...this.#e,node:Ws.cloneWith(this.#e.node,{temporary:!0})})}materialized(){return new tc({...this.#e,node:Ws.cloneWith(this.#e.node,{materialized:!0})})}ifNotExists(){return new tc({...this.#e,node:Ws.cloneWith(this.#e.node,{ifNotExists:!0})})}orReplace(){return new tc({...this.#e,node:Ws.cloneWith(this.#e.node,{orReplace:!0})})}columns(e){return new tc({...this.#e,node:Ws.cloneWith(this.#e.node,{columns:e.map(qS)})})}as(e){let t=e.withPlugin(new mA).toOperationNode();return new tc({...this.#e,node:Ws.cloneWith(this.#e.node,{as:t})})}$call(e){return e(this)}toOperationNode(){return this.#e.executor.transformQuery(this.#e.node,this.#e.queryId)}compile(){return this.#e.executor.compileQuery(this.toOperationNode(),this.#e.queryId)}async execute(){await this.#e.executor.executeQuery(this.compile())}}var bl=m({is(e){return e.kind==="DropViewNode"},create(e){return m({kind:"DropViewNode",name:ao.create(e)})},cloneWith(e,t){return m({...e,...t})}});class El{#e;constructor(e){this.#e=m(e)}materialized(){return new El({...this.#e,node:bl.cloneWith(this.#e.node,{materialized:!0})})}ifExists(){return new El({...this.#e,node:bl.cloneWith(this.#e.node,{ifExists:!0})})}cascade(){return new El({...this.#e,node:bl.cloneWith(this.#e.node,{cascade:!0})})}$call(e){return e(this)}toOperationNode(){return this.#e.executor.transformQuery(this.#e.node,this.#e.queryId)}compile(){return this.#e.executor.compileQuery(this.toOperationNode(),this.#e.queryId)}async execute(){await this.#e.executor.executeQuery(this.compile())}}var uy=m({is(e){return e.kind==="CreateTypeNode"},create(e){return m({kind:"CreateTypeNode",name:e})},cloneWithEnum(e,t){return m({...e,enum:qc.create(t.map(Ti.createImmediate))})}});class dy{#e;constructor(e){this.#e=m(e)}toOperationNode(){return this.#e.executor.transformQuery(this.#e.node,this.#e.queryId)}asEnum(e){return new dy({...this.#e,node:uy.cloneWithEnum(this.#e.node,e)})}$call(e){return e(this)}compile(){return this.#e.executor.compileQuery(this.toOperationNode(),this.#e.queryId)}async execute(){await this.#e.executor.executeQuery(this.compile())}}var ly=m({is(e){return e.kind==="DropTypeNode"},create(e){return m({kind:"DropTypeNode",name:e})},cloneWith(e,t){return m({...e,...t})}});class fy{#e;constructor(e){this.#e=m(e)}ifExists(){return new fy({...this.#e,node:ly.cloneWith(this.#e.node,{ifExists:!0})})}$call(e){return e(this)}toOperationNode(){return this.#e.executor.transformQuery(this.#e.node,this.#e.queryId)}compile(){return this.#e.executor.compileQuery(this.toOperationNode(),this.#e.queryId)}async execute(){await this.#e.executor.executeQuery(this.compile())}}function gA(e){if(e.includes(".")){let r=e.split(".").map(Iie);if(r.length===2)return ao.createWithSchema(r[0],r[1]);else throw Error(`invalid schemable identifier ${e}`)}else return ao.create(e)}function Iie(e){return e.trim()}var Sl=m({is(e){return e.kind==="RefreshMaterializedViewNode"},create(e){return m({kind:"RefreshMaterializedViewNode",name:ao.create(e)})},cloneWith(e,t){return m({...e,...t})}});class Al{#e;constructor(e){this.#e=m(e)}concurrently(){return new Al({...this.#e,node:Sl.cloneWith(this.#e.node,{concurrently:!0,withNoData:!1})})}withData(){return new Al({...this.#e,node:Sl.cloneWith(this.#e.node,{withNoData:!1})})}withNoData(){return new Al({...this.#e,node:Sl.cloneWith(this.#e.node,{withNoData:!0,concurrently:!1})})}$call(e){return e(this)}toOperationNode(){return this.#e.executor.transformQuery(this.#e.node,this.#e.queryId)}compile(){return this.#e.executor.compileQuery(this.toOperationNode(),this.#e.queryId)}async execute(){await this.#e.executor.executeQuery(this.compile())}}class Tl{#e;constructor(e){this.#e=e}createTable(e){return new No({queryId:Vt(),executor:this.#e,node:so.create(wn(e))})}dropTable(e){return new zh({queryId:Vt(),executor:this.#e,node:vh.create(wn(e))})}createIndex(e){return new is({queryId:Vt(),executor:this.#e,node:Os.create(e)})}dropIndex(e){return new _l({queryId:Vt(),executor:this.#e,node:Dc.create(e)})}createSchema(e){return new cy({queryId:Vt(),executor:this.#e,node:jg.create(e)})}dropSchema(e){return new Fh({queryId:Vt(),executor:this.#e,node:Th.create(e)})}alterTable(e){return new pA({queryId:Vt(),executor:this.#e,node:dn.create(wn(e))})}createView(e){return new tc({queryId:Vt(),executor:this.#e,node:Ws.create(e)})}refreshMaterializedView(e){return new Al({queryId:Vt(),executor:this.#e,node:Sl.create(e)})}dropView(e){return new El({queryId:Vt(),executor:this.#e,node:bl.create(e)})}createType(e){return new dy({queryId:Vt(),executor:this.#e,node:uy.create(gA(e))})}dropType(e){return new fy({queryId:Vt(),executor:this.#e,node:ly.create(gA(e))})}withPlugin(e){return new Tl(this.#e.withPlugin(e))}withoutPlugins(){return new Tl(this.#e.withoutPlugins())}withSchema(e){return new Tl(this.#e.withPluginAtFront(new Bs(e)))}}class yA{ref(e){return new US(e)}table(e){return new uA(e)}}class wA{#e;constructor(e){this.#e=e}async provideConnection(e){let t=await this.#e.acquireConnection();try{return await e(t)}finally{await this.#e.releaseConnection(t)}}}class Vc extends Uh{#e;#t;#r;constructor(e,t,r,n=[]){super(n);this.#e=e,this.#t=t,this.#r=r}get adapter(){return this.#t}compileQuery(e,t){return this.#e.compileQuery(e,t)}provideConnection(e){return this.#r.provideConnection(e)}withPlugins(e){return new Vc(this.#e,this.#t,this.#r,[...this.plugins,...e])}withPlugin(e){return new Vc(this.#e,this.#t,this.#r,[...this.plugins,e])}withPluginAtFront(e){return new Vc(this.#e,this.#t,this.#r,[e,...this.plugins])}withConnectionProvider(e){return new Vc(this.#e,this.#t,e,[...this.plugins])}withoutPlugins(){return new Vc(this.#e,this.#t,this.#r,[])}}function hy(){if(typeof performance<"u"&&qn(performance.now))return performance.now();else return Date.now()}class _A{#e;#t;#r;#n;#i;#s=new WeakSet;constructor(e,t){this.#n=!1,this.#e=e,this.#t=t}async init(){if(this.#i)throw Error("driver has already been destroyed");if(!this.#r)this.#r=this.#e.init().then(()=>{this.#n=!0}).catch((e)=>(this.#r=void 0,Promise.reject(e)));await this.#r}async acquireConnection(){if(this.#i)throw Error("driver has already been destroyed");if(!this.#n)await this.init();let e=await this.#e.acquireConnection();if(!this.#s.has(e)){if(this.#c())this.#o(e);this.#s.add(e)}return e}async releaseConnection(e){await this.#e.releaseConnection(e)}beginTransaction(e,t){return this.#e.beginTransaction(e,t)}commitTransaction(e){return this.#e.commitTransaction(e)}rollbackTransaction(e){return this.#e.rollbackTransaction(e)}savepoint(e,t,r){if(this.#e.savepoint)return this.#e.savepoint(e,t,r);throw Error("The `savepoint` method is not supported by this driver")}rollbackToSavepoint(e,t,r){if(this.#e.rollbackToSavepoint)return this.#e.rollbackToSavepoint(e,t,r);throw Error("The `rollbackToSavepoint` method is not supported by this driver")}releaseSavepoint(e,t,r){if(this.#e.releaseSavepoint)return this.#e.releaseSavepoint(e,t,r);throw Error("The `releaseSavepoint` method is not supported by this driver")}async destroy(){if(!this.#r)return;if(await this.#r,!this.#i)this.#i=this.#e.destroy().catch((e)=>(this.#i=void 0,Promise.reject(e)));await this.#i}#c(){return this.#t.isLevelEnabled("query")||this.#t.isLevelEnabled("error")}#o(e){let{executeQuery:t,streamQuery:r}=e,n=this;e.executeQuery=async(i)=>{let o,s=hy();try{return await t.call(e,i)}catch(a){throw o=a,await n.#a(a,i,s),a}finally{if(!o)await n.#u(i,s)}},e.streamQuery=async function*(i,o){let s,a=hy();try{for await(let c of r.call(e,i,o))yield c}catch(c){throw s=c,await n.#a(c,i,a),c}finally{if(!s)await n.#u(i,a,!0)}}}async#a(e,t,r){await this.#t.error(()=>({level:"error",error:e,query:t,queryDurationMillis:this.#d(r)}))}async#u(e,t,r=!1){await this.#t.query(()=>({level:"query",isStream:r,query:e,queryDurationMillis:this.#d(t)}))}#d(e){return hy()-e}}var Die=()=>{};class Wh{#e;#t;constructor(e){this.#e=e}async provideConnection(e){while(this.#t)await this.#t.catch(Die);return this.#t=this.#r(e).finally(()=>{this.#t=void 0}),this.#t}async#r(e){return await e(this.#e)}}var Uie=["read only","read write"],Pie=["read uncommitted","read committed","repeatable read","serializable","snapshot"];function bA(e){if(e.accessMode&&!Uie.includes(e.accessMode))throw Error(`invalid transaction access mode ${e.accessMode}`);if(e.isolationLevel&&!Pie.includes(e.isolationLevel))throw Error(`invalid transaction isolation level ${e.isolationLevel}`)}var Lie=["query","error"],pUe=m(Lie);class EA{#e;#t;constructor(e){if(qn(e))this.#t=e,this.#e=m({query:!0,error:!0});else this.#t=Mie,this.#e=m({query:e.includes("query"),error:e.includes("error")})}isLevelEnabled(e){return this.#e[e]}async query(e){if(this.#e.query)await this.#t(e())}async error(e){if(this.#e.error)await this.#t(e())}}function Mie(e){if(e.level==="query"){let t=`kysely:query:${e.isStream?"stream:":""}`;console.log(`${t} ${e.query.sql}`),console.log(`${t} duration: ${e.queryDurationMillis.toFixed(1)}ms`)}else if(e.level==="error")if(e.error instanceof Error)console.error(`kysely:error: ${e.error.stack??e.error.message}`);else console.error(`kysely:error: ${JSON.stringify({error:e.error,query:e.query.sql,queryDurationMillis:e.queryDurationMillis})}`)}function xU(e){return wi(e)&&qn(e.compile)}Symbol.asyncDispose??=Symbol("Symbol.asyncDispose");class ba extends ga{#e;constructor(e){let t,r;if(qie(e))t={executor:e.executor},r={...e};else{let n=e.dialect,i=n.createDriver(),o=n.createQueryCompiler(),s=n.createAdapter(),a=new EA(e.log??[]),c=new _A(i,a),u=new wA(c),d=new Vc(o,s,u,e.plugins??[]);t={executor:d},r={config:e,executor:d,dialect:n,driver:c}}super(t);this.#e=m(r)}get schema(){return new Tl(this.#e.executor)}get dynamic(){return new yA}get introspection(){return this.#e.dialect.createIntrospector(this.withoutPlugins())}case(e){return new Lh({node:Wo.create(mo(e)?void 0:vo(e))})}get fn(){return oy()}transaction(){return new py({...this.#e})}startTransaction(){return new my({...this.#e})}connection(){return new CU({...this.#e})}withPlugin(e){return new ba({...this.#e,executor:this.#e.executor.withPlugin(e)})}withoutPlugins(){return new ba({...this.#e,executor:this.#e.executor.withoutPlugins()})}withSchema(e){return new ba({...this.#e,executor:this.#e.executor.withPluginAtFront(new Bs(e))})}withTables(){return new ba({...this.#e})}async destroy(){await this.#e.driver.destroy()}get isTransaction(){return!1}getExecutor(){return this.#e.executor}executeQuery(e,t){if(t!==void 0)fa("Passing `queryId` in `db.executeQuery` is deprecated and will result in a compile-time error in the future.");let r=xU(e)?e.compile():e;return this.getExecutor().executeQuery(r)}async[Symbol.asyncDispose](){await this.destroy()}}class Ju extends ba{#e;constructor(e){super(e);this.#e=e}get isTransaction(){return!0}transaction(){throw Error("calling the transaction method for a Transaction is not supported")}connection(){throw Error("calling the connection method for a Transaction is not supported")}async destroy(){throw Error("calling the destroy method for a Transaction is not supported")}withPlugin(e){return new Ju({...this.#e,executor:this.#e.executor.withPlugin(e)})}withoutPlugins(){return new Ju({...this.#e,executor:this.#e.executor.withoutPlugins()})}withSchema(e){return new Ju({...this.#e,executor:this.#e.executor.withPluginAtFront(new Bs(e))})}withTables(){return new Ju({...this.#e})}}function qie(e){return wi(e)&&wi(e.config)&&wi(e.driver)&&wi(e.executor)&&wi(e.dialect)}class CU{#e;constructor(e){this.#e=m(e)}async execute(e){return this.#e.executor.provideConnection(async(t)=>{let r=this.#e.executor.withConnectionProvider(new Wh(t)),n=new ba({...this.#e,executor:r});return await e(n)})}}class py{#e;constructor(e){this.#e=m(e)}setAccessMode(e){return new py({...this.#e,accessMode:e})}setIsolationLevel(e){return new py({...this.#e,isolationLevel:e})}async execute(e){let{isolationLevel:t,accessMode:r,...n}=this.#e,i={isolationLevel:t,accessMode:r};return bA(i),this.#e.executor.provideConnection(async(o)=>{let s={isCommitted:!1,isRolledBack:!1},a=new nc(this.#e.executor.withConnectionProvider(new Wh(o)),s),c=new Ju({...n,executor:a}),u=!1;try{await this.#e.driver.beginTransaction(o,i),u=!0;let d=await e(c);return await this.#e.driver.commitTransaction(o),s.isCommitted=!0,d}catch(d){if(u)await this.#e.driver.rollbackTransaction(o),s.isRolledBack=!0;throw d}})}}class my{#e;constructor(e){this.#e=m(e)}setAccessMode(e){return new my({...this.#e,accessMode:e})}setIsolationLevel(e){return new my({...this.#e,isolationLevel:e})}async execute(){let{isolationLevel:e,accessMode:t,...r}=this.#e,n={isolationLevel:e,accessMode:t};bA(n);let i=await Zg(this.#e.executor);return await this.#e.driver.beginTransaction(i.connection,n),new rc({...r,connection:i,executor:this.#e.executor.withConnectionProvider(new Wh(i.connection))})}}class rc extends Ju{#e;#t;#r;constructor(e){let t={isCommitted:!1,isRolledBack:!1};e={...e,executor:new nc(e.executor,t)};let{connection:r,...n}=e;super(n);this.#e=m(e),this.#r=t;let i=Vt();this.#t=(o)=>e.executor.compileQuery(o,i)}get isCommitted(){return this.#r.isCommitted}get isRolledBack(){return this.#r.isRolledBack}commit(){return Ku(this.#r),new vl(async()=>{await this.#e.driver.commitTransaction(this.#e.connection.connection),this.#r.isCommitted=!0,this.#e.connection.release()})}rollback(){return Ku(this.#r),new vl(async()=>{await this.#e.driver.rollbackTransaction(this.#e.connection.connection),this.#r.isRolledBack=!0,this.#e.connection.release()})}savepoint(e){return Ku(this.#r),new vl(async()=>(await this.#e.driver.savepoint?.(this.#e.connection.connection,e,this.#t),new rc({...this.#e})))}rollbackToSavepoint(e){return Ku(this.#r),new vl(async()=>(await this.#e.driver.rollbackToSavepoint?.(this.#e.connection.connection,e,this.#t),new rc({...this.#e})))}releaseSavepoint(e){return Ku(this.#r),new vl(async()=>(await this.#e.driver.releaseSavepoint?.(this.#e.connection.connection,e,this.#t),new rc({...this.#e})))}withPlugin(e){return new rc({...this.#e,executor:this.#e.executor.withPlugin(e)})}withoutPlugins(){return new rc({...this.#e,executor:this.#e.executor.withoutPlugins()})}withSchema(e){return new rc({...this.#e,executor:this.#e.executor.withPluginAtFront(new Bs(e))})}withTables(){return new rc({...this.#e})}}class vl{#e;constructor(e){this.#e=e}async execute(){return await this.#e()}}function Ku(e){if(e.isCommitted)throw Error("Transaction is already committed");if(e.isRolledBack)throw Error("Transaction is already rolled back")}class nc{#e;#t;constructor(e,t){if(e instanceof nc)this.#e=e.#e;else this.#e=e;this.#t=t}get adapter(){return this.#e.adapter}get plugins(){return this.#e.plugins}transformQuery(e,t){return this.#e.transformQuery(e,t)}compileQuery(e,t){return this.#e.compileQuery(e,t)}provideConnection(e){return this.#e.provideConnection(e)}executeQuery(e){return Ku(this.#t),this.#e.executeQuery(e)}stream(e,t){return Ku(this.#t),this.#e.stream(e,t)}withConnectionProvider(e){return new nc(this.#e.withConnectionProvider(e),this.#t)}withPlugin(e){return new nc(this.#e.withPlugin(e),this.#t)}withPlugins(e){return new nc(this.#e.withPlugins(e),this.#t)}withPluginAtFront(e){return new nc(this.#e.withPluginAtFront(e),this.#t)}withoutPlugins(){return new nc(this.#e.withoutPlugins(),this.#t)}}class Hh{#e;constructor(e){this.#e=m(e)}get expressionType(){return}get isRawBuilder(){return!0}as(e){return new OU(this,e)}$castTo(){return new Hh({...this.#e})}$notNull(){return new Hh(this.#e)}withPlugin(e){return new Hh({...this.#e,plugins:this.#e.plugins!==void 0?m([...this.#e.plugins,e]):m([e])})}toOperationNode(){return this.#r(this.#t())}compile(e){return this.#n(this.#t(e))}async execute(e){let t=this.#t(e);return t.executeQuery(this.#n(t))}#t(e){let t=e!==void 0?e.getExecutor():Fc;return this.#e.plugins!==void 0?t.withPlugins(this.#e.plugins):t}#r(e){return e.transformQuery(this.#e.rawNode,this.#e.queryId)}#n(e){return e.compileQuery(this.#r(e),this.#e.queryId)}}function ic(e){return new Hh(e)}class OU{#e;#t;constructor(e,t){this.#e=e,this.#t=t}get expression(){return this.#e}get alias(){return this.#t}get rawBuilder(){return this.#e}toOperationNode(){return Bi.create(this.#e.toOperationNode(),Kn(this.#t)?this.#t.toOperationNode():$t.create(this.#t))}}var x=Object.assign((e,...t)=>ic({queryId:Vt(),rawNode:pn.create(e,t?.map(IU)??[])}),{ref(e){return ic({queryId:Vt(),rawNode:pn.createWithChild(jo(e))})},val(e){return ic({queryId:Vt(),rawNode:pn.createWithChild(zn(e))})},value(e){return this.val(e)},table(e){return ic({queryId:Vt(),rawNode:pn.createWithChild(wn(e))})},id(...e){let t=Array(e.length+1).fill(".");return t[0]="",t[t.length-1]="",ic({queryId:Vt(),rawNode:pn.create(t,e.map($t.create))})},lit(e){return ic({queryId:Vt(),rawNode:pn.createWithChild(Ti.createImmediate(e))})},literal(e){return this.lit(e)},raw(e){return ic({queryId:Vt(),rawNode:pn.createWithSql(e)})},join(e,t=x`, `){let r=Array(Math.max(2*e.length-1,0)),n=t.toOperationNode();for(let i=0;i<e.length;++i)if(r[2*i]=IU(e[i]),i!==e.length-1)r[2*i+1]=n;return ic({queryId:Vt(),rawNode:pn.createWithChildren(r)})}});function IU(e){if(Kn(e))return e.toOperationNode();return zn(e)}class SA{nodeStack=[];get parentNode(){return this.nodeStack[this.nodeStack.length-2]}#e=m({AliasNode:this.visitAlias.bind(this),ColumnNode:this.visitColumn.bind(this),IdentifierNode:this.visitIdentifier.bind(this),SchemableIdentifierNode:this.visitSchemableIdentifier.bind(this),RawNode:this.visitRaw.bind(this),ReferenceNode:this.visitReference.bind(this),SelectQueryNode:this.visitSelectQuery.bind(this),SelectionNode:this.visitSelection.bind(this),TableNode:this.visitTable.bind(this),FromNode:this.visitFrom.bind(this),SelectAllNode:this.visitSelectAll.bind(this),AndNode:this.visitAnd.bind(this),OrNode:this.visitOr.bind(this),ValueNode:this.visitValue.bind(this),ValueListNode:this.visitValueList.bind(this),PrimitiveValueListNode:this.visitPrimitiveValueList.bind(this),ParensNode:this.visitParens.bind(this),JoinNode:this.visitJoin.bind(this),OperatorNode:this.visitOperator.bind(this),WhereNode:this.visitWhere.bind(this),InsertQueryNode:this.visitInsertQuery.bind(this),DeleteQueryNode:this.visitDeleteQuery.bind(this),ReturningNode:this.visitReturning.bind(this),CreateTableNode:this.visitCreateTable.bind(this),AddColumnNode:this.visitAddColumn.bind(this),ColumnDefinitionNode:this.visitColumnDefinition.bind(this),DropTableNode:this.visitDropTable.bind(this),DataTypeNode:this.visitDataType.bind(this),OrderByNode:this.visitOrderBy.bind(this),OrderByItemNode:this.visitOrderByItem.bind(this),GroupByNode:this.visitGroupBy.bind(this),GroupByItemNode:this.visitGroupByItem.bind(this),UpdateQueryNode:this.visitUpdateQuery.bind(this),ColumnUpdateNode:this.visitColumnUpdate.bind(this),LimitNode:this.visitLimit.bind(this),OffsetNode:this.visitOffset.bind(this),OnConflictNode:this.visitOnConflict.bind(this),OnDuplicateKeyNode:this.visitOnDuplicateKey.bind(this),CreateIndexNode:this.visitCreateIndex.bind(this),DropIndexNode:this.visitDropIndex.bind(this),ListNode:this.visitList.bind(this),PrimaryKeyConstraintNode:this.visitPrimaryKeyConstraint.bind(this),UniqueConstraintNode:this.visitUniqueConstraint.bind(this),ReferencesNode:this.visitReferences.bind(this),CheckConstraintNode:this.visitCheckConstraint.bind(this),WithNode:this.visitWith.bind(this),CommonTableExpressionNode:this.visitCommonTableExpression.bind(this),CommonTableExpressionNameNode:this.visitCommonTableExpressionName.bind(this),HavingNode:this.visitHaving.bind(this),CreateSchemaNode:this.visitCreateSchema.bind(this),DropSchemaNode:this.visitDropSchema.bind(this),AlterTableNode:this.visitAlterTable.bind(this),DropColumnNode:this.visitDropColumn.bind(this),RenameColumnNode:this.visitRenameColumn.bind(this),AlterColumnNode:this.visitAlterColumn.bind(this),ModifyColumnNode:this.visitModifyColumn.bind(this),AddConstraintNode:this.visitAddConstraint.bind(this),DropConstraintNode:this.visitDropConstraint.bind(this),RenameConstraintNode:this.visitRenameConstraint.bind(this),ForeignKeyConstraintNode:this.visitForeignKeyConstraint.bind(this),CreateViewNode:this.visitCreateView.bind(this),RefreshMaterializedViewNode:this.visitRefreshMaterializedView.bind(this),DropViewNode:this.visitDropView.bind(this),GeneratedNode:this.visitGenerated.bind(this),DefaultValueNode:this.visitDefaultValue.bind(this),OnNode:this.visitOn.bind(this),ValuesNode:this.visitValues.bind(this),SelectModifierNode:this.visitSelectModifier.bind(this),CreateTypeNode:this.visitCreateType.bind(this),DropTypeNode:this.visitDropType.bind(this),ExplainNode:this.visitExplain.bind(this),DefaultInsertValueNode:this.visitDefaultInsertValue.bind(this),AggregateFunctionNode:this.visitAggregateFunction.bind(this),OverNode:this.visitOver.bind(this),PartitionByNode:this.visitPartitionBy.bind(this),PartitionByItemNode:this.visitPartitionByItem.bind(this),SetOperationNode:this.visitSetOperation.bind(this),BinaryOperationNode:this.visitBinaryOperation.bind(this),UnaryOperationNode:this.visitUnaryOperation.bind(this),UsingNode:this.visitUsing.bind(this),FunctionNode:this.visitFunction.bind(this),CaseNode:this.visitCase.bind(this),WhenNode:this.visitWhen.bind(this),JSONReferenceNode:this.visitJSONReference.bind(this),JSONPathNode:this.visitJSONPath.bind(this),JSONPathLegNode:this.visitJSONPathLeg.bind(this),JSONOperatorChainNode:this.visitJSONOperatorChain.bind(this),TupleNode:this.visitTuple.bind(this),MergeQueryNode:this.visitMergeQuery.bind(this),MatchedNode:this.visitMatched.bind(this),AddIndexNode:this.visitAddIndex.bind(this),CastNode:this.visitCast.bind(this),FetchNode:this.visitFetch.bind(this),TopNode:this.visitTop.bind(this),OutputNode:this.visitOutput.bind(this),OrActionNode:this.visitOrAction.bind(this),CollateNode:this.visitCollate.bind(this)});visitNode=(e)=>{this.nodeStack.push(e),this.#e[e.kind](e),this.nodeStack.pop()}}var Bie=/'/g,jie=/['"]/g;class he extends SA{#e="";#t=[];get numParameters(){return this.#t.length}compileQuery(e,t){return this.#e="",this.#t=[],this.nodeStack.splice(0,this.nodeStack.length),this.visitNode(e),m({query:e,queryId:t,sql:this.getSql(),parameters:[...this.#t]})}getSql(){return this.#e}visitSelectQuery(e){let t=this.parentNode!==void 0&&!Fo.is(this.parentNode)&&!di.is(this.parentNode)&&!so.is(this.parentNode)&&!Ws.is(this.parentNode)&&!ey.is(this.parentNode);if(this.parentNode===void 0&&e.explain)this.visitNode(e.explain),this.append(" ");if(t)this.append("(");if(e.with)this.visitNode(e.with),this.append(" ");if(this.append("select"),e.distinctOn)this.append(" "),this.compileDistinctOn(e.distinctOn);if(e.frontModifiers?.length)this.append(" "),this.compileList(e.frontModifiers," ");if(e.top)this.append(" "),this.visitNode(e.top);if(e.selections)this.append(" "),this.compileList(e.selections);if(e.from)this.append(" "),this.visitNode(e.from);if(e.joins)this.append(" "),this.compileList(e.joins," ");if(e.where)this.append(" "),this.visitNode(e.where);if(e.groupBy)this.append(" "),this.visitNode(e.groupBy);if(e.having)this.append(" "),this.visitNode(e.having);if(e.setOperations)this.append(" "),this.compileList(e.setOperations," ");if(e.orderBy)this.append(" "),this.visitNode(e.orderBy);if(e.limit)this.append(" "),this.visitNode(e.limit);if(e.offset)this.append(" "),this.visitNode(e.offset);if(e.fetch)this.append(" "),this.visitNode(e.fetch);if(e.endModifiers?.length)this.append(" "),this.compileList(this.sortSelectModifiers([...e.endModifiers])," ");if(t)this.append(")")}visitFrom(e){this.append("from "),this.compileList(e.froms)}visitSelection(e){this.visitNode(e.selection)}visitColumn(e){this.visitNode(e.column)}compileDistinctOn(e){this.append("distinct on ("),this.compileList(e),this.append(")")}compileList(e,t=", "){let r=e.length-1;for(let n=0;n<=r;n++)if(this.visitNode(e[n]),n<r)this.append(t)}visitWhere(e){this.append("where "),this.visitNode(e.where)}visitHaving(e){this.append("having "),this.visitNode(e.having)}visitInsertQuery(e){let t=this.parentNode!==void 0&&!Fo.is(this.parentNode)&&!pn.is(this.parentNode)&&!ns.is(this.parentNode);if(this.parentNode===void 0&&e.explain)this.visitNode(e.explain),this.append(" ");if(t)this.append("(");if(e.with)this.visitNode(e.with),this.append(" ");if(this.append(e.replace?"replace":"insert"),e.ignore)fa("`InsertQueryNode.ignore` is deprecated. Use `InsertQueryNode.orAction` instead."),this.append(" ignore");if(e.orAction)this.append(" "),this.visitNode(e.orAction);if(e.top)this.append(" "),this.visitNode(e.top);if(e.into)this.append(" into "),this.visitNode(e.into);if(e.columns)this.append(" ("),this.compileList(e.columns),this.append(")");if(e.output)this.append(" "),this.visitNode(e.output);if(e.values)this.append(" "),this.visitNode(e.values);if(e.defaultValues)this.append(" "),this.append("default values");if(e.onConflict)this.append(" "),this.visitNode(e.onConflict);if(e.onDuplicateKey)this.append(" "),this.visitNode(e.onDuplicateKey);if(e.returning)this.append(" "),this.visitNode(e.returning);if(t)this.append(")");if(e.endModifiers?.length)this.append(" "),this.compileList(e.endModifiers," ")}visitValues(e){this.append("values "),this.compileList(e.values)}visitDeleteQuery(e){let t=this.parentNode!==void 0&&!Fo.is(this.parentNode)&&!pn.is(this.parentNode);if(this.parentNode===void 0&&e.explain)this.visitNode(e.explain),this.append(" ");if(t)this.append("(");if(e.with)this.visitNode(e.with),this.append(" ");if(this.append("delete "),e.top)this.visitNode(e.top),this.append(" ");if(this.visitNode(e.from),e.output)this.append(" "),this.visitNode(e.output);if(e.using)this.append(" "),this.visitNode(e.using);if(e.joins)this.append(" "),this.compileList(e.joins," ");if(e.where)this.append(" "),this.visitNode(e.where);if(e.orderBy)this.append(" "),this.visitNode(e.orderBy);if(e.limit)this.append(" "),this.visitNode(e.limit);if(e.returning)this.append(" "),this.visitNode(e.returning);if(t)this.append(")");if(e.endModifiers?.length)this.append(" "),this.compileList(e.endModifiers," ")}visitReturning(e){this.append("returning "),this.compileList(e.selections)}visitAlias(e){this.visitNode(e.node),this.append(" as "),this.visitNode(e.alias)}visitReference(e){if(e.table)this.visitNode(e.table),this.append(".");this.visitNode(e.column)}visitSelectAll(e){this.append("*")}visitIdentifier(e){this.append(this.getLeftIdentifierWrapper()),this.compileUnwrappedIdentifier(e),this.append(this.getRightIdentifierWrapper())}compileUnwrappedIdentifier(e){if(!Ln(e.name))throw Error("a non-string identifier was passed to compileUnwrappedIdentifier.");this.append(this.sanitizeIdentifier(e.name))}visitAnd(e){this.visitNode(e.left),this.append(" and "),this.visitNode(e.right)}visitOr(e){this.visitNode(e.left),this.append(" or "),this.visitNode(e.right)}visitValue(e){if(e.immediate)this.appendImmediateValue(e.value);else this.appendValue(e.value)}visitValueList(e){this.append("("),this.compileList(e.values),this.append(")")}visitTuple(e){this.append("("),this.compileList(e.values),this.append(")")}visitPrimitiveValueList(e){this.append("(");let{values:t}=e;for(let r=0;r<t.length;++r)if(this.appendValue(t[r]),r!==t.length-1)this.append(", ");this.append(")")}visitParens(e){this.append("("),this.visitNode(e.node),this.append(")")}visitJoin(e){if(this.append(Fie[e.joinType]),this.append(" "),this.visitNode(e.table),e.on)this.append(" "),this.visitNode(e.on)}visitOn(e){this.append("on "),this.visitNode(e.on)}visitRaw(e){let{sqlFragments:t,parameters:r}=e;for(let n=0;n<t.length;++n)if(this.append(t[n]),r.length>n)this.visitNode(r[n])}visitOperator(e){this.append(e.operator)}visitTable(e){this.visitNode(e.table)}visitSchemableIdentifier(e){if(e.schema)this.visitNode(e.schema),this.append(".");this.visitNode(e.identifier)}visitCreateTable(e){if(this.append("create "),e.frontModifiers?.length)this.compileList(e.frontModifiers," "),this.append(" ");if(e.temporary)this.append("temporary ");if(this.append("table "),e.ifNotExists)this.append("if not exists ");if(this.visitNode(e.table),!e.selectQuery)this.append(" ("),this.compileList([...e.columns,...e.constraints??[]]),this.append(")");if(e.onCommit)this.append(" on commit "),this.append(e.onCommit);if(e.endModifiers?.length)this.append(" "),this.compileList(e.endModifiers," ");if(e.selectQuery)this.append(" as "),this.visitNode(e.selectQuery)}visitColumnDefinition(e){if(e.ifNotExists)this.append("if not exists ");if(this.visitNode(e.column),this.append(" "),this.visitNode(e.dataType),e.unsigned)this.append(" unsigned");if(e.frontModifiers&&e.frontModifiers.length>0)this.append(" "),this.compileList(e.frontModifiers," ");if(e.generated)this.append(" "),this.visitNode(e.generated);if(e.identity)this.append(" identity");if(e.defaultTo)this.append(" "),this.visitNode(e.defaultTo);if(e.notNull)this.append(" not null");if(e.unique)this.append(" unique");if(e.nullsNotDistinct)this.append(" nulls not distinct");if(e.primaryKey)this.append(" primary key");if(e.autoIncrement)this.append(" "),this.append(this.getAutoIncrement());if(e.references)this.append(" "),this.visitNode(e.references);if(e.check)this.append(" "),this.visitNode(e.check);if(e.endModifiers&&e.endModifiers.length>0)this.append(" "),this.compileList(e.endModifiers," ")}getAutoIncrement(){return"auto_increment"}visitReferences(e){if(this.append("references "),this.visitNode(e.table),this.append(" ("),this.compileList(e.columns),this.append(")"),e.onDelete)this.append(" on delete "),this.append(e.onDelete);if(e.onUpdate)this.append(" on update "),this.append(e.onUpdate)}visitDropTable(e){if(this.append("drop table "),e.ifExists)this.append("if exists ");if(this.visitNode(e.table),e.cascade)this.append(" cascade")}visitDataType(e){this.append(e.dataType)}visitOrderBy(e){this.append("order by "),this.compileList(e.items)}visitOrderByItem(e){if(this.visitNode(e.orderBy),e.collation)this.append(" "),this.visitNode(e.collation);if(e.direction)this.append(" "),this.visitNode(e.direction);if(e.nulls)this.append(" nulls "),this.append(e.nulls)}visitGroupBy(e){this.append("group by "),this.compileList(e.items)}visitGroupByItem(e){this.visitNode(e.groupBy)}visitUpdateQuery(e){let t=this.parentNode!==void 0&&!Fo.is(this.parentNode)&&!pn.is(this.parentNode)&&!ns.is(this.parentNode);if(this.parentNode===void 0&&e.explain)this.visitNode(e.explain),this.append(" ");if(t)this.append("(");if(e.with)this.visitNode(e.with),this.append(" ");if(this.append("update "),e.top)this.visitNode(e.top),this.append(" ");if(e.table)this.visitNode(e.table),this.append(" ");if(this.append("set "),e.updates)this.compileList(e.updates);if(e.output)this.append(" "),this.visitNode(e.output);if(e.from)this.append(" "),this.visitNode(e.from);if(e.joins){if(!e.from)throw Error("Joins in an update query are only supported as a part of a PostgreSQL 'update set from join' query. If you want to create a MySQL 'update join set' query, see https://kysely.dev/docs/examples/update/my-sql-joins");this.append(" "),this.compileList(e.joins," ")}if(e.where)this.append(" "),this.visitNode(e.where);if(e.returning)this.append(" "),this.visitNode(e.returning);if(e.orderBy)this.append(" "),this.visitNode(e.orderBy);if(e.limit)this.append(" "),this.visitNode(e.limit);if(t)this.append(")");if(e.endModifiers?.length)this.append(" "),this.compileList(e.endModifiers," ")}visitColumnUpdate(e){this.visitNode(e.column),this.append(" = "),this.visitNode(e.value)}visitLimit(e){this.append("limit "),this.visitNode(e.limit)}visitOffset(e){this.append("offset "),this.visitNode(e.offset)}visitOnConflict(e){if(this.append("on conflict"),e.columns)this.append(" ("),this.compileList(e.columns),this.append(")");else if(e.constraint)this.append(" on constraint "),this.visitNode(e.constraint);else if(e.indexExpression)this.append(" ("),this.visitNode(e.indexExpression),this.append(")");if(e.indexWhere)this.append(" "),this.visitNode(e.indexWhere);if(e.doNothing===!0)this.append(" do nothing");else if(e.updates){if(this.append(" do update set "),this.compileList(e.updates),e.updateWhere)this.append(" "),this.visitNode(e.updateWhere)}}visitOnDuplicateKey(e){this.append("on duplicate key update "),this.compileList(e.updates)}visitCreateIndex(e){if(this.append("create "),e.unique)this.append("unique ");if(this.append("index "),e.ifNotExists)this.append("if not exists ");if(this.visitNode(e.name),e.table)this.append(" on "),this.visitNode(e.table);if(e.using)this.append(" using "),this.visitNode(e.using);if(e.columns)this.append(" ("),this.compileList(e.columns),this.append(")");if(e.nullsNotDistinct)this.append(" nulls not distinct");if(e.where)this.append(" "),this.visitNode(e.where)}visitDropIndex(e){if(this.append("drop index "),e.ifExists)this.append("if exists ");if(this.visitNode(e.name),e.table)this.append(" on "),this.visitNode(e.table);if(e.cascade)this.append(" cascade")}visitCreateSchema(e){if(this.append("create schema "),e.ifNotExists)this.append("if not exists ");this.visitNode(e.schema)}visitDropSchema(e){if(this.append("drop schema "),e.ifExists)this.append("if exists ");if(this.visitNode(e.schema),e.cascade)this.append(" cascade")}visitPrimaryKeyConstraint(e){if(e.name)this.append("constraint "),this.visitNode(e.name),this.append(" ");this.append("primary key ("),this.compileList(e.columns),this.append(")"),this.buildDeferrable(e)}buildDeferrable(e){if(e.deferrable!==void 0)if(e.deferrable)this.append(" deferrable");else this.append(" not deferrable");if(e.initiallyDeferred!==void 0)if(e.initiallyDeferred)this.append(" initially deferred");else this.append(" initially immediate")}visitUniqueConstraint(e){if(e.name)this.append("constraint "),this.visitNode(e.name),this.append(" ");if(this.append("unique"),e.nullsNotDistinct)this.append(" nulls not distinct");this.append(" ("),this.compileList(e.columns),this.append(")"),this.buildDeferrable(e)}visitCheckConstraint(e){if(e.name)this.append("constraint "),this.visitNode(e.name),this.append(" ");this.append("check ("),this.visitNode(e.expression),this.append(")")}visitForeignKeyConstraint(e){if(e.name)this.append("constraint "),this.visitNode(e.name),this.append(" ");if(this.append("foreign key ("),this.compileList(e.columns),this.append(") "),this.visitNode(e.references),e.onDelete)this.append(" on delete "),this.append(e.onDelete);if(e.onUpdate)this.append(" on update "),this.append(e.onUpdate);this.buildDeferrable(e)}visitList(e){this.compileList(e.items)}visitWith(e){if(this.append("with "),e.recursive)this.append("recursive ");this.compileList(e.expressions)}visitCommonTableExpression(e){if(this.visitNode(e.name),this.append(" as "),Ga(e.materialized)){if(!e.materialized)this.append("not ");this.append("materialized ")}this.visitNode(e.expression)}visitCommonTableExpressionName(e){if(this.visitNode(e.table),e.columns)this.append("("),this.compileList(e.columns),this.append(")")}visitAlterTable(e){if(this.append("alter table "),this.visitNode(e.table),this.append(" "),e.renameTo)this.append("rename to "),this.visitNode(e.renameTo);if(e.setSchema)this.append("set schema "),this.visitNode(e.setSchema);if(e.addConstraint)this.visitNode(e.addConstraint);if(e.dropConstraint)this.visitNode(e.dropConstraint);if(e.renameConstraint)this.visitNode(e.renameConstraint);if(e.columnAlterations)this.compileColumnAlterations(e.columnAlterations);if(e.addIndex)this.visitNode(e.addIndex);if(e.dropIndex)this.visitNode(e.dropIndex)}visitAddColumn(e){this.append("add column "),this.visitNode(e.column)}visitRenameColumn(e){this.append("rename column "),this.visitNode(e.column),this.append(" to "),this.visitNode(e.renameTo)}visitDropColumn(e){this.append("drop column "),this.visitNode(e.column)}visitAlterColumn(e){if(this.append("alter column "),this.visitNode(e.column),this.append(" "),e.dataType){if(this.announcesNewColumnDataType())this.append("type ");if(this.visitNode(e.dataType),e.dataTypeExpression)this.append("using "),this.visitNode(e.dataTypeExpression)}if(e.setDefault)this.append("set default "),this.visitNode(e.setDefault);if(e.dropDefault)this.append("drop default");if(e.setNotNull)this.append("set not null");if(e.dropNotNull)this.append("drop not null")}visitModifyColumn(e){this.append("modify column "),this.visitNode(e.column)}visitAddConstraint(e){this.append("add "),this.visitNode(e.constraint)}visitDropConstraint(e){if(this.append("drop constraint "),e.ifExists)this.append("if exists ");if(this.visitNode(e.constraintName),e.modifier==="cascade")this.append(" cascade");else if(e.modifier==="restrict")this.append(" restrict")}visitRenameConstraint(e){this.append("rename constraint "),this.visitNode(e.oldName),this.append(" to "),this.visitNode(e.newName)}visitSetOperation(e){if(this.append(e.operator),this.append(" "),e.all)this.append("all ");this.visitNode(e.expression)}visitCreateView(e){if(this.append("create "),e.orReplace)this.append("or replace ");if(e.materialized)this.append("materialized ");if(e.temporary)this.append("temporary ");if(this.append("view "),e.ifNotExists)this.append("if not exists ");if(this.visitNode(e.name),this.append(" "),e.columns)this.append("("),this.compileList(e.columns),this.append(") ");if(e.as)this.append("as "),this.visitNode(e.as)}visitRefreshMaterializedView(e){if(this.append("refresh materialized view "),e.concurrently)this.append("concurrently ");if(this.visitNode(e.name),e.withNoData)this.append(" with no data");else this.append(" with data")}visitDropView(e){if(this.append("drop "),e.materialized)this.append("materialized ");if(this.append("view "),e.ifExists)this.append("if exists ");if(this.visitNode(e.name),e.cascade)this.append(" cascade")}visitGenerated(e){if(this.append("generated "),e.always)this.append("always ");if(e.byDefault)this.append("by default ");if(this.append("as "),e.identity)this.append("identity");if(e.expression)this.append("("),this.visitNode(e.expression),this.append(")");if(e.stored)this.append(" stored")}visitDefaultValue(e){this.append("default "),this.visitNode(e.defaultValue)}visitSelectModifier(e){if(e.rawModifier)this.visitNode(e.rawModifier);else this.append($ie[e.modifier]);if(e.of)this.append(" of "),this.compileList(e.of,", ")}visitCreateType(e){if(this.append("create type "),this.visitNode(e.name),e.enum)this.append(" as enum "),this.visitNode(e.enum)}visitDropType(e){if(this.append("drop type "),e.ifExists)this.append("if exists ");this.visitNode(e.name)}visitExplain(e){if(this.append("explain"),e.options||e.format){if(this.append(" "),this.append(this.getLeftExplainOptionsWrapper()),e.options){if(this.visitNode(e.options),e.format)this.append(this.getExplainOptionsDelimiter())}if(e.format)this.append("format"),this.append(this.getExplainOptionAssignment()),this.append(e.format);this.append(this.getRightExplainOptionsWrapper())}}visitDefaultInsertValue(e){this.append("default")}visitAggregateFunction(e){if(this.append(e.func),this.append("("),e.distinct)this.append("distinct ");if(this.compileList(e.aggregated),e.orderBy)this.append(" "),this.visitNode(e.orderBy);if(this.append(")"),e.withinGroup)this.append(" within group ("),this.visitNode(e.withinGroup),this.append(")");if(e.filter)this.append(" filter("),this.visitNode(e.filter),this.append(")");if(e.over)this.append(" "),this.visitNode(e.over)}visitOver(e){if(this.append("over("),e.partitionBy){if(this.visitNode(e.partitionBy),e.orderBy)this.append(" ")}if(e.orderBy)this.visitNode(e.orderBy);this.append(")")}visitPartitionBy(e){this.append("partition by "),this.compileList(e.items)}visitPartitionByItem(e){this.visitNode(e.partitionBy)}visitBinaryOperation(e){this.visitNode(e.leftOperand),this.append(" "),this.visitNode(e.operator),this.append(" "),this.visitNode(e.rightOperand)}visitUnaryOperation(e){if(this.visitNode(e.operator),!this.isMinusOperator(e.operator))this.append(" ");this.visitNode(e.operand)}isMinusOperator(e){return Bo.is(e)&&e.operator==="-"}visitUsing(e){this.append("using "),this.compileList(e.tables)}visitFunction(e){this.append(e.func),this.append("("),this.compileList(e.arguments),this.append(")")}visitCase(e){if(this.append("case"),e.value)this.append(" "),this.visitNode(e.value);if(e.when)this.append(" "),this.compileList(e.when," ");if(e.else)this.append(" else "),this.visitNode(e.else);if(this.append(" end"),e.isStatement)this.append(" case")}visitWhen(e){if(this.append("when "),this.visitNode(e.condition),e.result)this.append(" then "),this.visitNode(e.result)}visitJSONReference(e){this.visitNode(e.reference),this.visitNode(e.traversal)}visitJSONPath(e){if(e.inOperator)this.visitNode(e.inOperator);this.append("'$");for(let t of e.pathLegs)this.visitNode(t);this.append("'")}visitJSONPathLeg(e){let t=e.type==="ArrayLocation",r=String(e.value);if(t)this.append("["),this.append(this.sanitizeStringLiteral(r)),this.append("]");else this.append('."'),this.append(this.sanitizeJSONPathMemberValue(r)),this.append('"')}visitJSONOperatorChain(e){for(let t=0,r=e.values.length;t<r;t++){if(t===r-1)this.visitNode(e.operator);else this.append("->");this.visitNode(e.values[t])}}visitMergeQuery(e){if(e.with)this.visitNode(e.with),this.append(" ");if(this.append("merge "),e.top)this.visitNode(e.top),this.append(" ");if(this.append("into "),this.visitNode(e.into),e.using)this.append(" "),this.visitNode(e.using);if(e.whens)this.append(" "),this.compileList(e.whens," ");if(e.returning)this.append(" "),this.visitNode(e.returning);if(e.output)this.append(" "),this.visitNode(e.output);if(e.endModifiers?.length)this.append(" "),this.compileList(e.endModifiers," ")}visitMatched(e){if(e.not)this.append("not ");if(this.append("matched"),e.bySource)this.append(" by source")}visitAddIndex(e){if(this.append("add "),e.unique)this.append("unique ");if(this.append("index "),this.visitNode(e.name),e.columns)this.append(" ("),this.compileList(e.columns),this.append(")");if(e.using)this.append(" using "),this.visitNode(e.using)}visitCast(e){this.append("cast("),this.visitNode(e.expression),this.append(" as "),this.visitNode(e.dataType),this.append(")")}visitFetch(e){this.append("fetch next "),this.visitNode(e.rowCount),this.append(` rows ${e.modifier}`)}visitOutput(e){this.append("output "),this.compileList(e.selections)}visitTop(e){if(this.append(`top(${e.expression})`),e.modifiers)this.append(` ${e.modifiers}`)}visitOrAction(e){this.append(e.action)}visitCollate(e){this.append("collate "),this.visitNode(e.collation)}append(e){this.#e+=e}appendValue(e){this.addParameter(e),this.append(this.getCurrentParameterPlaceholder())}getLeftIdentifierWrapper(){return'"'}getRightIdentifierWrapper(){return'"'}getCurrentParameterPlaceholder(){return"$"+this.numParameters}getLeftExplainOptionsWrapper(){return"("}getExplainOptionAssignment(){return" "}getExplainOptionsDelimiter(){return", "}getRightExplainOptionsWrapper(){return")"}sanitizeIdentifier(e){let t=this.getLeftIdentifierWrapper(),r=this.getRightIdentifierWrapper(),n="";for(let i of e)if(n+=i,i===t)n+=t;else if(i===r)n+=r;return n}sanitizeStringLiteral(e){return e.replace(Bie,"''")}sanitizeJSONPathMemberValue(e){return e.replace(jie,(t)=>t==="'"?"''":"\\\"")}addParameter(e){this.#t.push(e)}appendImmediateValue(e){if(Ln(e))this.appendStringLiteral(e);else if(Cs(e)||Ga(e)||Ic(e))this.append(e.toString());else if(Oc(e))this.append("null");else if(Bg(e))this.appendImmediateValue(e.toISOString());else throw Error(`invalid immediate value ${e}`)}appendStringLiteral(e){this.append("'"),this.append(this.sanitizeStringLiteral(e)),this.append("'")}sortSelectModifiers(e){return e.sort((t,r)=>t.modifier&&r.modifier?DU[t.modifier]-DU[r.modifier]:1),m(e)}compileColumnAlterations(e){this.compileList(e)}announcesNewColumnDataType(){return!0}}var $ie=m({ForKeyShare:"for key share",ForNoKeyUpdate:"for no key update",ForUpdate:"for update",ForShare:"for share",NoWait:"nowait",SkipLocked:"skip locked",Distinct:"distinct"}),DU=m({ForKeyShare:1,ForNoKeyUpdate:1,ForUpdate:1,ForShare:1,NoWait:2,SkipLocked:2,Distinct:0}),Fie=m({InnerJoin:"inner join",LeftJoin:"left join",RightJoin:"right join",FullJoin:"full join",CrossJoin:"cross join",LateralInnerJoin:"inner join lateral",LateralLeftJoin:"left join lateral",LateralCrossJoin:"cross join lateral",OuterApply:"outer apply",CrossApply:"cross apply",Using:"using"});var G=m({raw(e,t=[]){return m({sql:e,query:pn.createWithSql(e),parameters:m(t),queryId:Vt()})}});class oc{get supportsCreateIfNotExists(){return!0}get supportsTransactionalDdl(){return!1}get supportsReturning(){return!1}get supportsOutput(){return!1}}function os(e,t){return pn.createWithChildren([pn.createWithSql(`${e} `),$t.create(t)])}class AA{#e;#t=new PU;#r;#n;constructor(e){this.#e=m({...e})}async init(){if(this.#r=qn(this.#e.database)?await this.#e.database():this.#e.database,this.#n=new UU(this.#r),this.#e.onCreateConnection)await this.#e.onCreateConnection(this.#n)}async acquireConnection(){return await this.#t.lock(),this.#n}async beginTransaction(e){await e.executeQuery(G.raw("begin"))}async commitTransaction(e){await e.executeQuery(G.raw("commit"))}async rollbackTransaction(e){await e.executeQuery(G.raw("rollback"))}async savepoint(e,t,r){await e.executeQuery(r(os("savepoint",t),Vt()))}async rollbackToSavepoint(e,t,r){await e.executeQuery(r(os("rollback to",t),Vt()))}async releaseSavepoint(e,t,r){await e.executeQuery(r(os("release",t),Vt()))}async releaseConnection(){this.#t.unlock()}async destroy(){this.#r?.close()}}class UU{#e;constructor(e){this.#e=e}executeQuery(e){let{sql:t,parameters:r}=e,n=this.#e.prepare(t);if(n.reader)return Promise.resolve({rows:n.all(r)});let{changes:i,lastInsertRowid:o}=n.run(r);return Promise.resolve({numAffectedRows:i!==void 0&&i!==null?BigInt(i):void 0,insertId:o!==void 0&&o!==null?BigInt(o):void 0,rows:[]})}async*streamQuery(e,t){let{sql:r,parameters:n,query:i}=e,o=this.#e.prepare(r);if(mn.is(i)){let s=o.iterate(n);for(let a of s)yield{rows:[a]}}else throw Error("Sqlite driver only supports streaming of select queries")}}class PU{#e;#t;async lock(){while(this.#e)await this.#e;this.#e=new Promise((e)=>{this.#t=e})}unlock(){let e=this.#t;this.#e=void 0,this.#t=void 0,e?.()}}var zie=/"/g,Wie=/[\\'"]/g;class rr extends he{visitOrAction(e){this.append("or "),this.append(e.action)}getCurrentParameterPlaceholder(){return"?"}getLeftExplainOptionsWrapper(){return""}getRightExplainOptionsWrapper(){return""}getLeftIdentifierWrapper(){return'"'}getRightIdentifierWrapper(){return'"'}getAutoIncrement(){return"autoincrement"}sanitizeIdentifier(e){return e.replace(zie,'""')}sanitizeJSONPathMemberValue(e){return e.replace(Wie,(t)=>t==="\\"?"\\\\":t==="'"?"''":"\\\"")}visitDefaultInsertValue(e){this.append("null")}}var Ea="kysely_migration",Gc="kysely_migration_lock";var IPe=m({__noMigrations__:!0});class TA{#e;constructor(e){this.#e=e}async getSchemas(){return[]}async getTables(e={withInternalKyselyTables:!1}){return await this.#r(e)}async getMetadata(e){return{tables:await this.getTables(e)}}#t(e,t){let r=e.selectFrom("sqlite_master").where("type","in",["table","view"]).where("name","not like","sqlite_%").select(["name","sql","type"]).orderBy("name");if(!t.withInternalKyselyTables)r=r.where("name","!=",Ea).where("name","!=",Gc);return r}async#r(e){let t=await this.#t(this.#e,e).execute(),r=await this.#e.with("table_list",(i)=>this.#t(i,e)).selectFrom(["table_list as tl",x`pragma_table_info(tl.name)`.as("p")]).select(["tl.name as table","p.cid","p.name","p.type","p.notnull","p.dflt_value","p.pk"]).orderBy("tl.name").orderBy("p.cid").execute(),n={};for(let i of r)n[i.table]??=[],n[i.table].push(i);return t.map(({name:i,sql:o,type:s})=>{let a=o?.split(/[\(\),]/)?.find((u)=>u.toLowerCase().includes("autoincrement"))?.trimStart()?.split(/\s+/)?.[0]?.replace(/["`]/g,""),c=n[i]??[];if(!a){let u=c.filter((d)=>d.pk>0);if(u.length===1&&u[0].type.toLowerCase()==="integer")a=u[0].name}return{name:i,isView:s==="view",columns:c.map((u)=>({name:u.name,dataType:u.type,isNullable:!u.notnull,isAutoIncrementing:u.name===a,hasDefaultValue:u.dflt_value!=null,comment:void 0}))}})}}class nr extends oc{get supportsTransactionalDdl(){return!1}get supportsReturning(){return!0}async acquireMigrationLock(e,t){}async releaseMigrationLock(e,t){}}class gy{#e;constructor(e){this.#e=m({...e})}createDriver(){return new AA(this.#e)}createQueryCompiler(){return new rr}createAdapter(){return new nr}createIntrospector(e){return new TA(e)}}var Hie=/"/g;class vA extends he{sanitizeIdentifier(e){return e.replace(Hie,'""')}}class kA{#e;constructor(e){this.#e=e}async getSchemas(){return(await this.#e.selectFrom("pg_catalog.pg_namespace").select("nspname").$castTo().execute()).map((t)=>({name:t.nspname}))}async getTables(e={withInternalKyselyTables:!1}){let t=this.#e.selectFrom("pg_catalog.pg_attribute as a").innerJoin("pg_catalog.pg_class as c","a.attrelid","c.oid").innerJoin("pg_catalog.pg_namespace as ns","c.relnamespace","ns.oid").innerJoin("pg_catalog.pg_type as typ","a.atttypid","typ.oid").innerJoin("pg_catalog.pg_namespace as dtns","typ.typnamespace","dtns.oid").select(["a.attname as column","a.attnotnull as not_null","a.atthasdef as has_default","c.relname as table","c.relkind as table_type","ns.nspname as schema","typ.typname as type","dtns.nspname as type_schema",x`col_description(a.attrelid, a.attnum)`.as("column_description"),x`pg_get_serial_sequence(quote_ident(ns.nspname) || '.' || quote_ident(c.relname), a.attname)`.as("auto_incrementing")]).where("c.relkind","in",["r","v","p"]).where("ns.nspname","!~","^pg_").where("ns.nspname","!=","information_schema").where("ns.nspname","!=","crdb_internal").where(x`has_schema_privilege(ns.nspname, 'USAGE')`).where("a.attnum",">=",0).where("a.attisdropped","!=",!0).orderBy("ns.nspname").orderBy("c.relname").orderBy("a.attnum").$castTo();if(!e.withInternalKyselyTables)t=t.where("c.relname","!=",Ea).where("c.relname","!=",Gc);let r=await t.execute();return this.#t(r)}async getMetadata(e){return{tables:await this.getTables(e)}}#t(e){let t=new Map;for(let r=0,n=e.length;r<n;r++){let i=e[r],{schema:o,table:s}=i,a=`schema:${o};table:${s}`;if(!t.has(a))t.set(a,m({columns:[],isView:i.table_type==="v",name:s,schema:o}));t.get(a).columns.push(m({comment:i.column_description??void 0,dataType:i.type,dataTypeSchema:i.type_schema,hasDefaultValue:i.has_default,isAutoIncrementing:i.auto_incrementing!==null,isNullable:!i.not_null,name:i.column}))}return Array.from(t.values())}}var Vie=BigInt("3853314791062309107");class RA extends oc{get supportsTransactionalDdl(){return!0}get supportsReturning(){return!0}async acquireMigrationLock(e,t){await x`select pg_advisory_xact_lock(${x.lit(Vie)})`.execute(e)}async releaseMigrationLock(e,t){}}function kl(e,t){if(Gie(e)&&t.stack){let r=t.stack.split(`
88
+ `).slice(1).join(`
89
+ `);return e.stack+=`
90
+ ${r}`,e}return e}function Gie(e){return wi(e)&&Ln(e.stack)}var LU=Symbol();class NA{#e;#t=new WeakMap;#r;constructor(e){this.#e=m({...e})}async init(){this.#r=qn(this.#e.pool)?await this.#e.pool():this.#e.pool}async acquireConnection(){let e=await this.#n(),t=this.#t.get(e);if(!t){if(t=new MU(e),this.#t.set(e,t),this.#e?.onCreateConnection)await this.#e.onCreateConnection(t)}if(this.#e?.onReserveConnection)await this.#e.onReserveConnection(t);return t}async#n(){return new Promise((e,t)=>{this.#r.getConnection(async(r,n)=>{if(r)t(r);else e(n)})})}async beginTransaction(e,t){if(t.isolationLevel||t.accessMode){let r=[];if(t.isolationLevel)r.push(`isolation level ${t.isolationLevel}`);if(t.accessMode)r.push(t.accessMode);let n=`set transaction ${r.join(", ")}`;await e.executeQuery(G.raw(n))}await e.executeQuery(G.raw("begin"))}async commitTransaction(e){await e.executeQuery(G.raw("commit"))}async rollbackTransaction(e){await e.executeQuery(G.raw("rollback"))}async savepoint(e,t,r){await e.executeQuery(r(os("savepoint",t),Vt()))}async rollbackToSavepoint(e,t,r){await e.executeQuery(r(os("rollback to",t),Vt()))}async releaseSavepoint(e,t,r){await e.executeQuery(r(os("release savepoint",t),Vt()))}async releaseConnection(e){e[LU]()}async destroy(){return new Promise((e,t)=>{this.#r.end((r)=>{if(r)t(r);else e()})})}}function Kie(e){return wi(e)&&"insertId"in e&&"affectedRows"in e}class MU{#e;constructor(e){this.#e=e}async executeQuery(e){try{let t=await this.#t(e);if(Kie(t)){let{insertId:r,affectedRows:n,changedRows:i}=t;return{insertId:r!==void 0&&r!==null&&r.toString()!=="0"?BigInt(r):void 0,numAffectedRows:n!==void 0&&n!==null?BigInt(n):void 0,numChangedRows:i!==void 0&&i!==null?BigInt(i):void 0,rows:[]}}else if(Array.isArray(t))return{rows:t};return{rows:[]}}catch(t){throw kl(t,Error())}}#t(e){return new Promise((t,r)=>{this.#e.query(e.sql,e.parameters,(n,i)=>{if(n)r(n);else t(i)})})}async*streamQuery(e,t){let r=this.#e.query(e.sql,e.parameters).stream({objectMode:!0});try{for await(let n of r)yield{rows:[n]}}catch(n){if(n&&typeof n==="object"&&"code"in n&&n.code==="ERR_STREAM_PREMATURE_CLOSE")return;throw n}}[LU](){this.#e.release()}}var Jie=/[\\']/g,xA=/`/g,Qie=/[\\'"]/g;class CA extends he{getCurrentParameterPlaceholder(){return"?"}getLeftExplainOptionsWrapper(){return""}getExplainOptionAssignment(){return"="}getExplainOptionsDelimiter(){return" "}getRightExplainOptionsWrapper(){return""}getLeftIdentifierWrapper(){return xA.source}getRightIdentifierWrapper(){return xA.source}sanitizeIdentifier(e){return e.replace(xA,"``")}sanitizeStringLiteral(e){return e.replace(Jie,(t)=>t==="\\"?"\\\\":"''")}sanitizeJSONPathMemberValue(e){return e.replace(Qie,(t)=>t==="\\"?"\\\\\\\\":t==="'"?"''":'\\\\"')}visitCreateIndex(e){if(this.append("create "),e.unique)this.append("unique ");if(this.append("index "),e.ifNotExists)this.append("if not exists ");if(this.visitNode(e.name),e.using)this.append(" using "),this.visitNode(e.using);if(e.table)this.append(" on "),this.visitNode(e.table);if(e.columns)this.append(" ("),this.compileList(e.columns),this.append(")");if(e.where)this.append(" "),this.visitNode(e.where)}}class OA{#e;constructor(e){this.#e=e}async getSchemas(){return(await this.#e.selectFrom("information_schema.schemata").select("schema_name").$castTo().execute()).map((t)=>({name:t.SCHEMA_NAME}))}async getTables(e={withInternalKyselyTables:!1}){let t=this.#e.selectFrom("information_schema.columns as columns").innerJoin("information_schema.tables as tables",(n)=>n.onRef("columns.TABLE_CATALOG","=","tables.TABLE_CATALOG").onRef("columns.TABLE_SCHEMA","=","tables.TABLE_SCHEMA").onRef("columns.TABLE_NAME","=","tables.TABLE_NAME")).select(["columns.COLUMN_NAME","columns.COLUMN_DEFAULT","columns.TABLE_NAME","columns.TABLE_SCHEMA","tables.TABLE_TYPE","columns.IS_NULLABLE","columns.DATA_TYPE","columns.EXTRA","columns.COLUMN_COMMENT"]).where("columns.TABLE_SCHEMA","=",x`database()`).orderBy("columns.TABLE_NAME").orderBy("columns.ORDINAL_POSITION").$castTo();if(!e.withInternalKyselyTables)t=t.where("columns.TABLE_NAME","!=",Ea).where("columns.TABLE_NAME","!=",Gc);let r=await t.execute();return this.#t(r)}async getMetadata(e){return{tables:await this.getTables(e)}}#t(e){return e.reduce((t,r)=>{let n=t.find((i)=>i.name===r.TABLE_NAME);if(!n)n=m({name:r.TABLE_NAME,isView:r.TABLE_TYPE==="VIEW",schema:r.TABLE_SCHEMA,columns:[]}),t.push(n);return n.columns.push(m({name:r.COLUMN_NAME,dataType:r.DATA_TYPE,isNullable:r.IS_NULLABLE==="YES",isAutoIncrementing:r.EXTRA.toLowerCase().includes("auto_increment"),hasDefaultValue:r.COLUMN_DEFAULT!==null,comment:r.COLUMN_COMMENT===""?void 0:r.COLUMN_COMMENT})),t},[])}}var qU="ea586330-2c93-47c8-908d-981d9d270f9d",Yie=3600;class IA extends oc{get supportsTransactionalDdl(){return!1}get supportsReturning(){return!1}async acquireMigrationLock(e,t){await x`select get_lock(${x.lit(qU)}, ${x.lit(Yie)})`.execute(e)}async releaseMigrationLock(e,t){await x`select release_lock(${x.lit(qU)})`.execute(e)}}class yy{#e;constructor(e){this.#e=e}createDriver(){return new NA(this.#e)}createQueryCompiler(){return new CA}createAdapter(){return new IA}createIntrospector(e){return new OA(e)}}var BU=Symbol();class DA{#e;#t=new WeakMap;#r;constructor(e){this.#e=m({...e})}async init(){this.#r=qn(this.#e.pool)?await this.#e.pool():this.#e.pool}async acquireConnection(){let e=await this.#r.connect(),t=this.#t.get(e);if(!t){if(t=new jU(e,{cursor:this.#e.cursor??null}),this.#t.set(e,t),this.#e.onCreateConnection)await this.#e.onCreateConnection(t)}if(this.#e.onReserveConnection)await this.#e.onReserveConnection(t);return t}async beginTransaction(e,t){if(t.isolationLevel||t.accessMode){let r="start transaction";if(t.isolationLevel)r+=` isolation level ${t.isolationLevel}`;if(t.accessMode)r+=` ${t.accessMode}`;await e.executeQuery(G.raw(r))}else await e.executeQuery(G.raw("begin"))}async commitTransaction(e){await e.executeQuery(G.raw("commit"))}async rollbackTransaction(e){await e.executeQuery(G.raw("rollback"))}async savepoint(e,t,r){await e.executeQuery(r(os("savepoint",t),Vt()))}async rollbackToSavepoint(e,t,r){await e.executeQuery(r(os("rollback to",t),Vt()))}async releaseSavepoint(e,t,r){await e.executeQuery(r(os("release",t),Vt()))}async releaseConnection(e){e[BU]()}async destroy(){if(this.#r){let e=this.#r;this.#r=void 0,await e.end()}}}class jU{#e;#t;constructor(e,t){this.#e=e,this.#t=t}async executeQuery(e){try{let{command:t,rowCount:r,rows:n}=await this.#e.query(e.sql,[...e.parameters]);return{numAffectedRows:t==="INSERT"||t==="UPDATE"||t==="DELETE"||t==="MERGE"?BigInt(r):void 0,rows:n??[]}}catch(t){throw kl(t,Error())}}async*streamQuery(e,t){if(!this.#t.cursor)throw Error("'cursor' is not present in your postgres dialect config. It's required to make streaming work in postgres.");if(!Number.isInteger(t)||t<=0)throw Error("chunkSize must be a positive integer");let r=this.#e.query(new this.#t.cursor(e.sql,e.parameters.slice()));try{while(!0){let n=await r.read(t);if(n.length===0)break;yield{rows:n}}}finally{await r.close()}}[BU](){this.#e.release()}}class wy{#e;constructor(e){this.#e=e}createDriver(){return new DA(this.#e)}createQueryCompiler(){return new vA}createAdapter(){return new RA}createIntrospector(e){return new kA(e)}}class UA extends oc{get supportsCreateIfNotExists(){return!1}get supportsTransactionalDdl(){return!0}get supportsOutput(){return!0}async acquireMigrationLock(e){await x`exec sp_getapplock @DbPrincipal = ${x.lit("dbo")}, @Resource = ${x.lit(Ea)}, @LockMode = ${x.lit("Exclusive")}`.execute(e)}async releaseMigrationLock(){}}var $U=Symbol(),FU=Symbol(),zU=Symbol();class PA{#e;#t;constructor(e){this.#e=m({...e});let{tarn:t,tedious:r,validateConnections:n}=this.#e,{validateConnections:i,...o}=t.options;this.#t=new t.Pool({...o,create:async()=>{let s=await r.connectionFactory();return await new WU(s,r).connect()},destroy:async(s)=>{await s[FU]()},validate:n===!1||i===!1?void 0:(s)=>s[zU]()})}async init(){}async acquireConnection(){return await this.#t.acquire().promise}async beginTransaction(e,t){await e.beginTransaction(t)}async commitTransaction(e){await e.commitTransaction()}async rollbackTransaction(e){await e.rollbackTransaction()}async savepoint(e,t){await e.savepoint(t)}async rollbackToSavepoint(e,t){await e.rollbackTransaction(t)}async releaseConnection(e){if(this.#e.resetConnectionsOnRelease||this.#e.tedious.resetConnectionOnRelease)await e[$U]();this.#t.release(e)}async destroy(){await this.#t.destroy()}}class WU{#e;#t;#r;constructor(e,t){this.#e=e,this.#t=!1,this.#r=t}async beginTransaction(e){let{isolationLevel:t}=e;await new Promise((r,n)=>this.#e.beginTransaction((i)=>{if(i)n(i);else r(void 0)},t?Xg(8):void 0,t?this.#n(t):void 0))}async commitTransaction(){await new Promise((e,t)=>this.#e.commitTransaction((r)=>{if(r)t(r);else e(void 0)}))}async connect(){let{promise:e,reject:t,resolve:r}=new $c;this.#e.connect((i)=>{if(i)return t(i);r()}),this.#e.on("error",(i)=>{if(i instanceof Error&&"code"in i&&i.code==="ESOCKET")this.#t=!0;console.error(i),t(i)});function n(){t(Error("The connection ended without ever completing the connection"))}return this.#e.once("end",n),await e,this.#e.off("end",n),this}async executeQuery(e){try{let t=new $c,r=new _y({compiledQuery:e,tedious:this.#r,onDone:t});this.#e.execSql(r.request);let{rowCount:n,rows:i}=await t.promise;return{numAffectedRows:n!==void 0?BigInt(n):void 0,rows:i}}catch(t){throw kl(t,Error())}}async rollbackTransaction(e){await new Promise((t,r)=>this.#e.rollbackTransaction((n)=>{if(n)r(n);else t(void 0)},e))}async savepoint(e){await new Promise((t,r)=>this.#e.saveTransaction((n)=>{if(n)r(n);else t(void 0)},e))}async*streamQuery(e,t){if(!Number.isInteger(t)||t<=0)throw Error("chunkSize must be a positive integer");let r=new _y({compiledQuery:e,streamChunkSize:t,tedious:this.#r});this.#e.execSql(r.request);try{while(!0){let n=await r.readChunk();if(n.length===0)break;if(yield{rows:n},n.length<t)break}}finally{await this.#i(r)}}#n(e){let{ISOLATION_LEVEL:t}=this.#r,n={"read committed":t.READ_COMMITTED,"read uncommitted":t.READ_UNCOMMITTED,"repeatable read":t.REPEATABLE_READ,serializable:t.SERIALIZABLE,snapshot:t.SNAPSHOT}[e];if(n===void 0)throw Error(`Unknown isolation level: ${e}`);return n}#i(e){return new Promise((t)=>{if(e.request.once("requestCompleted",t),!this.#e.cancel())e.request.off("requestCompleted",t),t()})}[FU](){if("closed"in this.#e&&this.#e.closed)return Promise.resolve();return new Promise((e)=>{this.#e.once("end",e),this.#e.close()})}async[$U](){await new Promise((e,t)=>{this.#e.reset((r)=>{if(r)return t(r);e()})})}async[zU](){if(this.#t||this.#s())return!1;try{let e=new $c,t=new _y({compiledQuery:G.raw("select 1"),onDone:e,tedious:this.#r});return this.#e.execSql(t.request),await e.promise,!0}catch{return!1}}#s(){return"closed"in this.#e&&Boolean(this.#e.closed)}}class _y{#e;#t;#r;#n;#i;#s;constructor(e){let{compiledQuery:t,onDone:r,streamChunkSize:n,tedious:i}=e;if(this.#t=[],this.#r=n,this.#n={},this.#i=i,r)this.#n.onDone=(s,a)=>{if(s==="chunkReady")return;if(delete this.#n.onDone,s==="error")return r.reject(a);r.resolve({rowCount:this.#s,rows:this.#t})};this.#e=new this.#i.Request(t.sql,(o,s)=>{if(o)return Object.values(this.#n).forEach((a)=>a("error",o instanceof AggregateError?o.errors:o));this.#s=s}),this.#c(t.parameters),this.#o()}get request(){return this.#e}readChunk(){let e=this.readChunk.name;return new Promise((t,r)=>{this.#n[e]=(n,i)=>{if(delete this.#n[e],n==="error")return r(i);t(this.#t.splice(0,this.#r))},this.#e.resume()})}#c(e){for(let t=0;t<e.length;t++){let r=e[t];this.#e.addParameter(String(t+1),this.#a(r),r)}}#o(){let e=this.#r?()=>{if(this.#r<=this.#t.length)this.#e.pause(),Object.values(this.#n).forEach((r)=>r("chunkReady"))}:()=>{},t=(r)=>{let n={};for(let i of r)n[i.metadata.colName]=i.value;this.#t.push(n),e()};this.#e.on("row",t),this.#e.once("requestCompleted",()=>{Object.values(this.#n).forEach((r)=>r("completed")),this.#e.off("row",t)})}#a(e){if(Oc(e)||mo(e)||Ln(e))return this.#i.TYPES.NVarChar;if(Ic(e)||Cs(e)&&e%1===0)if(e<-2147483648||e>2147483647)return this.#i.TYPES.BigInt;else return this.#i.TYPES.Int;if(Cs(e))return this.#i.TYPES.Float;if(Ga(e))return this.#i.TYPES.Bit;if(Bg(e))return this.#i.TYPES.DateTime;if(xD(e))return this.#i.TYPES.VarBinary;return this.#i.TYPES.NVarChar}}class LA{#e;constructor(e){this.#e=e}async getSchemas(){return await this.#e.selectFrom("sys.schemas").select("name").execute()}async getTables(e={withInternalKyselyTables:!1}){let t=await this.#e.selectFrom("sys.tables as tables").leftJoin("sys.schemas as table_schemas","table_schemas.schema_id","tables.schema_id").innerJoin("sys.columns as columns","columns.object_id","tables.object_id").innerJoin("sys.types as types","types.user_type_id","columns.user_type_id").leftJoin("sys.schemas as type_schemas","type_schemas.schema_id","types.schema_id").leftJoin("sys.extended_properties as comments",(n)=>n.onRef("comments.major_id","=","tables.object_id").onRef("comments.minor_id","=","columns.column_id").on("comments.name","=","MS_Description")).$if(!e.withInternalKyselyTables,(n)=>n.where("tables.name","!=",Ea).where("tables.name","!=",Gc)).select(["tables.name as table_name",(n)=>n.ref("tables.type").$castTo().as("table_type"),"table_schemas.name as table_schema_name","columns.default_object_id as column_default_object_id","columns.generated_always_type_desc as column_generated_always_type","columns.is_computed as column_is_computed","columns.is_identity as column_is_identity","columns.is_nullable as column_is_nullable","columns.is_rowguidcol as column_is_rowguidcol","columns.name as column_name","types.is_nullable as type_is_nullable","types.name as type_name","type_schemas.name as type_schema_name","comments.value as column_comment"]).unionAll(this.#e.selectFrom("sys.views as views").leftJoin("sys.schemas as view_schemas","view_schemas.schema_id","views.schema_id").innerJoin("sys.columns as columns","columns.object_id","views.object_id").innerJoin("sys.types as types","types.user_type_id","columns.user_type_id").leftJoin("sys.schemas as type_schemas","type_schemas.schema_id","types.schema_id").leftJoin("sys.extended_properties as comments",(n)=>n.onRef("comments.major_id","=","views.object_id").onRef("comments.minor_id","=","columns.column_id").on("comments.name","=","MS_Description")).select(["views.name as table_name","views.type as table_type","view_schemas.name as table_schema_name","columns.default_object_id as column_default_object_id","columns.generated_always_type_desc as column_generated_always_type","columns.is_computed as column_is_computed","columns.is_identity as column_is_identity","columns.is_nullable as column_is_nullable","columns.is_rowguidcol as column_is_rowguidcol","columns.name as column_name","types.is_nullable as type_is_nullable","types.name as type_name","type_schemas.name as type_schema_name","comments.value as column_comment"])).orderBy("table_schema_name").orderBy("table_name").orderBy("column_name").execute(),r={};for(let n of t){let i=`${n.table_schema_name}.${n.table_name}`;(r[i]=r[i]||m({columns:[],isView:n.table_type==="V ",name:n.table_name,schema:n.table_schema_name??void 0})).columns.push(m({dataType:n.type_name,dataTypeSchema:n.type_schema_name??void 0,hasDefaultValue:n.column_default_object_id>0||n.column_generated_always_type!=="NOT_APPLICABLE"||n.column_is_identity||n.column_is_computed||n.column_is_rowguidcol,isAutoIncrementing:n.column_is_identity,isNullable:n.column_is_nullable&&n.type_is_nullable,name:n.column_name,comment:n.column_comment??void 0}))}return Object.values(r)}async getMetadata(e){return{tables:await this.getTables(e)}}}var Xie=/^[a-z0-9_]$/i;class MA extends he{getCurrentParameterPlaceholder(){return`@${this.numParameters}`}visitOffset(e){super.visitOffset(e),this.append(" rows")}compileColumnAlterations(e){let t={};for(let n of e){if(!t[n.kind])t[n.kind]=[];t[n.kind].push(n)}let r=!0;if(t.AddColumnNode)this.append("add "),this.compileList(t.AddColumnNode),r=!1;if(t.AlterColumnNode){if(!r)this.append(", ");this.compileList(t.AlterColumnNode)}if(t.DropColumnNode){if(!r)this.append(", ");this.append("drop column "),this.compileList(t.DropColumnNode)}if(t.ModifyColumnNode){if(!r)this.append(", ");this.compileList(t.ModifyColumnNode)}if(t.RenameColumnNode){if(!r)this.append(", ");this.compileList(t.RenameColumnNode)}}visitAddColumn(e){this.visitNode(e.column)}visitDropColumn(e){this.visitNode(e.column)}visitMergeQuery(e){super.visitMergeQuery(e),this.append(";")}visitCollate(e){this.append("collate ");let{name:t}=e.collation;for(let r of t)if(!Xie.test(r))throw Error(`Invalid collation: ${t}`);this.append(t)}announcesNewColumnDataType(){return!1}}class qA{#e;constructor(e){this.#e=e}createDriver(){return new PA(this.#e)}createQueryCompiler(){return new MA}createAdapter(){return new UA}createIntrospector(e){return new LA(e)}}var Wr="kysely_migration",Jr="kysely_migration_lock";function Yr(e){let t=e.filter((n)=>n.pk>0),r=t.length===1?t[0]:void 0;return r?.type.toLowerCase()==="integer"?r.name:void 0}async function HU(e,t,r){let n=Yr(r);if(!n)return;let{rows:i}=await x`
91
+ PRAGMA index_list(${x.id(t)})
92
+ `.execute(e.withoutPlugins());return i.some((o)=>o.origin==="pk")?void 0:n}function xr(e,t,r){return{name:e.name,isView:e.type==="view",columns:t.map((n)=>({name:n.name,dataType:n.type,isNullable:n.notnull===0,isAutoIncrementing:n.name===r,hasDefaultValue:n.dflt_value!=null}))}}async function Zie(e,t){let{rows:r}=await x`
93
+ PRAGMA table_info(${x.id(t)})
94
+ `.execute(e.withoutPlugins());if(r.length===0)return;let n=await HU(e,t,r);return xr({name:t},r,n)}async function VU(e,t){if(t.length===0)return[];try{return await e.introspection.getTables()}catch{return(await Promise.all(t.map((r)=>Zie(e,r)))).filter((r)=>r!==void 0)}}function or(e){let t=e;async function r(){return[]}async function n(i={withInternalKyselyTables:!1}){let o=t.selectFrom("sqlite_schema").where("type","=","table").where("name","not like","sqlite_%").select("name");if(!i.withInternalKyselyTables)o=o.where("name","!=",Wr).where("name","!=",Jr);let s=await o.execute();return Promise.all(s.map(async({name:a})=>{let c=await e.selectFrom(x`pragma_table_info(${a})`.as("table_info")).select(["cid","name","type","notnull","dflt_value","pk"]).execute(),u=await HU(e,a,c);return xr({name:a},c,u)}))}return{getSchemas:r,getTables:n,getMetadata:async(i)=>({tables:await n(i)})}}var Rl=({schema:e,usePlural:t})=>{let r=rs({schema:e,usePlural:t});return({field:i,model:o})=>{if(i==="id"||i==="_id")return"id";let s=r(o),a=e[s]?.fields[i];if(!a){let c=Object.entries(e[s].fields).find(([u,d])=>d.fieldName===i);if(c)a=c[1],i=c[0]}if(!a)throw new y(`Field ${i} not found in model ${s}`);return i}};var GU=({usePlural:e,schema:t,options:r,customIdGenerator:n,disableIdGeneration:i})=>{let o=rs({usePlural:e,schema:t}),s=Rl({usePlural:e,schema:t}),a=qg({usePlural:e,schema:t,options:r,customIdGenerator:n,disableIdGeneration:i});return({model:u,field:d})=>{let f=o(u),h=s({field:d,model:f}),p=t[f].fields;p.id=a({customModelName:f});let g=p[h];if(!g)throw new y(`Field ${d} not found in model ${u}`);return g}};var er=({schema:e,usePlural:t})=>{let r=rs({schema:e,usePlural:t}),n=Rl({schema:e,usePlural:t});function i({model:o,field:s}){let a=r(o),c=n({model:a,field:s});return e[a]?.fields[c]?.fieldName||c}return i};var tr=({usePlural:e,schema:t})=>{let r=rs({schema:t,usePlural:e});return(i)=>{let o=r(i);if(t&&t[o]&&t[o].modelName!==i)return e?`${t[o].modelName}s`:t[o].modelName;return e?`${i}s`:i}};function KU(e,t,r){if(r==="update"){if(e===void 0&&t.onUpdate!==void 0){if(typeof t.onUpdate==="function")return t.onUpdate();return t.onUpdate}return e}if(r==="create"){if(e===void 0||t.required===!0&&e===null){if(t.defaultValue!==void 0){if(typeof t.defaultValue==="function")return t.defaultValue();return t.defaultValue}}}return e}var eoe=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?Z$/;function JU(e){if(typeof e==="string"&&eoe.test(e)){let t=new Date(e);if(!isNaN(t.getTime()))return t}return e}function BA(e){if(e===null||e===void 0)return e;if(typeof e==="string")return JU(e);if(e instanceof Date)return e;if(Array.isArray(e))return e.map(BA);if(typeof e==="object"){let t={};for(let r of Object.keys(e))t[r]=BA(e[r]);return t}return e}function ti(e){try{if(typeof e!=="string"){if(e===null||e===void 0)return null;return BA(e)}return JSON.parse(e,(t,r)=>JU(r))}catch(t){return T.error("Error parsing JSON",{error:t}),null}}import*as ui from"zod";var toe=5,roe=ui.union([ui.string(),ui.number(),ui.boolean(),ui.date()]).nullable(),noe=ui.record(ui.string(),ui.unknown()).nullish(),ioe=ui.record(ui.string(),ui.unknown()).transform((e)=>{let t={};for(let[r,n]of Object.entries(e))if(n!==void 0)t[r]=n;return t}),ooe=ui.object({increment:ui.record(ui.string(),ui.number()),set:ioe.optional()}),soe=ui.number().nullish();function QU(e){let{adapter:t,adapterId:r}=e,n=Object.entries(e.mapKeysTransformOutput??{}).find(([,d])=>d==="id")?.[0]??"id";async function i(d,f,h){let p=e.mapKeysTransformInput?.id||e.getFieldName({model:f,field:"id"});if(d[p]===void 0||d[p]===null)throw new y(`Adapter "${e.adapterId}" must return the row id for atomic fallbacks.`);let g=(await e.transformOutput(d,f,[n],void 0))?.id;if(typeof g!=="string"&&typeof g!=="number")throw new y(`Adapter "${e.adapterId}" must expose a logical string or number id through its output transform.`);let[_]=e.transformWhereClause({model:f,where:[{field:"id",value:g}],action:h});if(!_)throw new y("The atomic fallback id condition was transformed away.");return _}async function o({model:d,modelKey:f,where:h}){let p=noe.safeParse(await t.findOne({model:d,modelKey:f,where:h}));if(!p.success)throw new y(`Adapter "${r}" must return a row snapshot or null.`);return p.data??null}async function s(d,f,h,p){let g=await i(d,h.modelKey,p),_=h.where.some((I)=>I.connector==="OR"),R=_?[g]:[...h.where,g],O=new Set(f);for(let I of O){if(I===g.field)continue;let Ne=roe.safeParse(d[I]??null);if(!Ne.success){if(_&&h.where.some((k)=>k.field===I))throw new y(`Adapter "${r}" must implement native atomic methods for OR predicates on structured values.`);continue}R.push({field:I,value:Ne.data,operator:"eq",connector:"AND",mode:"sensitive"})}return R}function a(d){if(d!==0&&d!==1)throw new y(`Adapter "${r}" must return an affected row count of 0 or 1 from an atomic fallback.`);return d===1}async function c(d){let{model:f,where:h}=d,p=await o(d);if(p===null)return null;let g=await s(p,[...Object.keys(p),...h.map(({field:_})=>_)],d,"consumeOne");return a(await t.deleteMany({model:f,modelKey:d.modelKey,where:g}))?p:null}async function u(d){let{model:f,where:h}=d,p=ooe.safeParse(d);if(!p.success)throw new y("incrementOne requires finite increments and a set object for the atomic fallback.");let{increment:g,set:_}=p.data,R=Object.entries(g),O=[...h.map(({field:I})=>I),...Object.keys(g),...Object.keys(_??{})];for(let I=0;I<toe;I++){let Ne=await o(d);if(Ne===null)return null;let k={..._};for(let[re,Oe]of R){let ne=soe.safeParse(Ne[re]);if(!ne.success)throw new y(`Adapter "${r}" must return finite numeric counter values or null for atomic increments.`);let M=ne.data??0,F=M+Oe;if(!Number.isFinite(F)||Oe!==0&&F===M)throw new y(`Adapter "${r}" cannot represent the requested counter increment safely.`);k[re]=F}let j=await s(Ne,O,d,"incrementOne");if(Object.entries(k).every(([re,Oe])=>{let ne=Ne[re];if(ne instanceof Date&&Oe instanceof Date)return ne.getTime()===Oe.getTime();return Object.is(ne,Oe)}))return Ne;if(a(await t.updateMany({model:f,modelKey:d.modelKey,where:j,update:k})))return{...Ne,...k}}throw new y(`Adapter "${r}" could not complete an atomic increment due to contention. Retry the operation or implement incrementOne natively.`)}return{consumeOne:c,incrementOne:u}}var Yn="db.collection.name",xo="db.operation.name",Vh="http.response.status_code",Kc="http.route",Nl="better_auth.operation_id",Si="better_auth.hook.type",Ai="better_auth.context";function aoe(){let e={end(){},setAttribute(t,r){},setStatus(t){},recordException(t){},updateName(t){return e}};return e}function coe(e){function t(r,...n){let i=n[n.length-1];return i(e)}return{startActiveSpan:t}}function uoe(){let e=coe(aoe());return{getTracer(t,r){return e},getActiveSpan(){}}}function doe(){return{SpanStatusCode:{UNSET:0,OK:1,ERROR:2},trace:uoe()}}var YU=doe();function XU(e,t,r){return r()}var ZU,eP;async function loe(){try{eP=await import("./chunk-g7ad4dw4.js").then((m)=>E(m.default,1))}catch{}}function jA(){if(!ZU)ZU=loe();return eP??YU}var foe="better-auth",hoe="1.7.12";function poe(e){if(e!=null&&typeof e==="object"&&"name"in e&&e.name==="APIError"&&"statusCode"in e){let t=e.statusCode;return t>=300&&t<400}return!1}function tP(e,t){let{SpanStatusCode:r}=jA();if(poe(t))e.setAttribute(Vh,t.statusCode),e.setStatus({code:r.OK});else e.recordException(t),e.setStatus({code:r.ERROR,message:String(t?.message??t)});e.end()}function rP(e,t,r){let{trace:n}=jA();return n.getTracer(foe,hoe).startActiveSpan(e,{attributes:t},(i)=>{try{let o=r();if(o instanceof Promise)return o.then((s)=>(i.end(),s)).catch((s)=>{throw tP(i,s),s});return i.end(),o}catch(o){throw tP(i,o),o}})}function ss(e){return e.experimental?.instrumentation?.enabled===!1?XU:rP}var by=[],vi=-1,moe=(e)=>(t)=>t(e),ze=({adapter:e,config:t})=>(r)=>{let n=ss(r),i=Math.random().toString(36).substring(2,15),o={...t,supportsBooleans:t.supportsBooleans??!0,supportsDates:t.supportsDates??!0,supportsJSON:t.supportsJSON??!1,adapterName:t.adapterName??t.adapterId,supportsNumericIds:t.supportsNumericIds??!0,supportsUUIDs:t.supportsUUIDs??!1,supportsArrays:t.supportsArrays??!1,transaction:t.transaction??!1,disableTransformInput:t.disableTransformInput??!1,disableTransformOutput:t.disableTransformOutput??!1,disableTransformJoin:t.disableTransformJoin??!1};if(r.advanced?.database?.generateId==="serial"&&o.supportsNumericIds===!1)throw new y(`[${o.adapterName}] Your database or database adapter does not support numeric ids. Please disable "useNumberId" in your config.`);let s=ye(r),a=(...ne)=>{if(o.debugLogs===!0||typeof o.debugLogs==="object"){let M=Xe({level:"info"});if(typeof o.debugLogs==="object"&&"isRunningAdapterTests"in o.debugLogs){if(o.debugLogs.isRunningAdapterTests)ne.shift(),by.push({instance:i,args:ne});return}if(typeof o.debugLogs==="object"&&o.debugLogs.logCondition&&!o.debugLogs.logCondition?.())return;if(typeof ne[0]==="object"&&"method"in ne[0]){let F=ne.shift().method;if(typeof o.debugLogs==="object"){if(F==="create"&&!o.debugLogs.create)return;else if(F==="update"&&!o.debugLogs.update)return;else if(F==="updateMany"&&!o.debugLogs.updateMany)return;else if(F==="findOne"&&!o.debugLogs.findOne)return;else if(F==="findMany"&&!o.debugLogs.findMany)return;else if(F==="delete"&&!o.debugLogs.delete)return;else if(F==="deleteMany"&&!o.debugLogs.deleteMany)return;else if(F==="consumeOne"&&!o.debugLogs.consumeOne)return;else if(F==="incrementOne"&&!o.debugLogs.incrementOne)return;else if(F==="count"&&!o.debugLogs.count)return}M.info(`[${o.adapterName}]`,...ne)}else M.info(`[${o.adapterName}]`,...ne)}},c=Xe(r.logger),u=rs({usePlural:o.usePlural,schema:s}),d=Rl({usePlural:o.usePlural,schema:s}),f=tr({usePlural:o.usePlural,schema:s}),h=er({schema:s,usePlural:o.usePlural}),p=qg({schema:s,options:r,usePlural:o.usePlural,disableIdGeneration:o.disableIdGeneration,customIdGenerator:o.customIdGenerator,supportsUUIDs:o.supportsUUIDs}),g=GU({schema:s,options:r,usePlural:o.usePlural,disableIdGeneration:o.disableIdGeneration,customIdGenerator:o.customIdGenerator}),_=async(ne,M,F,ce)=>{let de={},pe=s[M].fields,ae=o.mapKeysTransformInput??{},He=r.advanced?.database?.generateId==="serial";pe.id=p({customModelName:M,forceAllowId:ce&&"id"in ne});for(let Be in pe){let Ke=ne[Be],Te=pe[Be],Ve=ae[Be]||pe[Be].fieldName||Be;if(Ke===void 0&&(Te.defaultValue===void 0&&!Te.transform?.input&&!(F==="update"&&Te.onUpdate)||F==="update"&&!Te.onUpdate))continue;if(Te&&Te.type==="date"&&!(Ke instanceof Date)&&typeof Ke==="string")try{Ke=new Date(Ke)}catch{c.error("[Adapter Factory] Failed to convert string to date",{value:Ke,field:Be})}let Je=KU(Ke,Te,F);if(Te.transform?.input)Je=await Te.transform.input(Je);if(Te.references?.field==="id"&&He)if(Array.isArray(Je))Je=Je.map((ft)=>ft!==null?Number(ft):null);else Je=Je!==null?Number(Je):null;else if(o.supportsJSON===!1&&typeof Je==="object"&&Te.type==="json")Je=JSON.stringify(Je);else if(o.supportsArrays===!1&&Array.isArray(Je)&&(Te.type==="string[]"||Te.type==="number[]"))Je=JSON.stringify(Je);else if(o.supportsDates===!1&&Je instanceof Date&&Te.type==="date")Je=Je.toISOString();else if(o.supportsBooleans===!1&&typeof Je==="boolean")Je=Je?1:0;if(o.customTransformInput)Je=o.customTransformInput({data:Je,action:F,field:Ve,fieldAttributes:Te,model:f(M),schema:s,options:r});if(Je!==void 0)de[Ve]=Je}return de},R=async(ne,M,F=[],ce)=>{let de=async(Be,Ke,Te=[])=>{if(!Be)return null;let Ve=u(Ke),Je=o.mapKeysTransformOutput??{},ft={},qt=s[Ve].fields,ot=Object.entries(Je).find(([Tr,un])=>un==="id")?.[0];qt[ot??"id"]={type:r.advanced?.database?.generateId==="serial"?"number":"string"};for(let Tr in qt){if(Te.length&&!Te.includes(Tr))continue;let un=qt[Tr];if(un){let oi=un.fieldName||Tr,Kt=Be[Object.entries(Je).find(([Z,Ae])=>Ae===oi)?.[0]||oi];if(un.transform?.output)Kt=await un.transform.output(Kt);let Ci=Je[Tr]||Tr;if(oi==="id"||un.references?.field==="id"){if(typeof Kt<"u"&&Kt!==null)Kt=String(Kt)}else if(o.supportsJSON===!1&&typeof Kt==="string"&&un.type==="json")Kt=ti(Kt);else if(o.supportsArrays===!1&&typeof Kt==="string"&&(un.type==="string[]"||un.type==="number[]"))Kt=ti(Kt);else if(o.supportsDates===!1&&typeof Kt==="string"&&un.type==="date")Kt=new Date(Kt);else if(o.supportsBooleans===!1&&typeof Kt==="number"&&un.type==="boolean")Kt=Kt===1;if(o.customTransformOutput)Kt=o.customTransformOutput({data:Kt,field:Ci,fieldAttributes:un,select:Te,model:f(Ve),schema:s,options:r});ft[Ci]=Kt}}return ft};if(!ce||Object.keys(ce).length===0)return await de(ne,M,F);let pe=u(M),ae=await de(ne,pe,F),He=Object.entries(ce).map(([Be,Ke])=>({modelName:Be,defaultModelName:Ke.modelKey??u(Be),joinConfig:Ke}));if(!ne)return null;for(let{modelName:Be,defaultModelName:Ke,joinConfig:Te}of He){let Ve=await(async()=>{if(r.advanced?.database?.joins){if(Be in ne)return ne[Be]}return await Ne({baseModel:pe,baseData:ae,joinModel:Be,specificJoinConfig:Te})})();if(Ve===void 0||Ve===null)Ve=Te.relation==="one-to-one"?null:[];if(Te.relation==="one-to-many"&&!Array.isArray(Ve))Ve=[Ve];let Je=[];if(Array.isArray(Ve))for(let ft of Ve){let qt=await de(ft,Ke,[]);Je.push(qt)}else{let ft=await de(Ve,Ke,[]);Je.push(ft)}ae[Ke]=(Te.relation==="one-to-one"?Je[0]:Je)??null}return ae},O=({model:ne,where:M,action:F})=>{if(!M)return;let ce=o.mapKeysTransformInput??{};return M.map((de)=>{let{field:pe,value:ae,operator:He="eq",connector:Be="AND",mode:Ke="sensitive"}=de;if(He==="in"){if(!Array.isArray(ae))throw new y("Value must be an array")}let Te=ae,Ve=u(ne),Je=d({field:pe,model:ne}),ft=ce[Je]||h({field:Je,model:Ve}),qt=g({field:Je,model:Ve}),ot=r.advanced?.database?.generateId==="serial";if(Je==="id"||qt.references?.field==="id"){if(ot)if(Array.isArray(ae))Te=ae.map(Number);else Te=Number(ae)}if(qt.type==="date"&&ae instanceof Date&&!o.supportsDates)Te=ae.toISOString();if(qt.type==="boolean"&&typeof Te==="string")Te=Te==="true";if(qt.type==="number"){if(typeof Te==="string"&&Te.trim()!==""){let Tr=Number(Te);if(!Number.isNaN(Tr))Te=Tr}else if(Array.isArray(Te)){let Tr=Te.map((un)=>typeof un==="string"&&un.trim()!==""?Number(un):NaN);if(Tr.every((un)=>!Number.isNaN(un)))Te=Tr}}if(qt.type==="boolean"&&typeof Te==="boolean"&&!o.supportsBooleans)Te=Te?1:0;if(qt.type==="json"&&typeof ae==="object"&&!o.supportsJSON)try{Te=JSON.stringify(ae)}catch(Tr){throw Error(`Failed to stringify JSON value for field ${ft}`,{cause:Tr})}if(o.customTransformInput)Te=o.customTransformInput({data:Te,fieldAttributes:qt,field:ft,model:f(ne),schema:s,options:r,action:F});return{operator:He,connector:Be,field:ft,value:Te,mode:Ke}})},I=(ne,M,F)=>{if(!M)return;if(Object.keys(M).length===0)return;let ce={};for(let[de,pe]of Object.entries(M)){if(!pe)continue;let ae=u(de),He=u(ne),Be=Object.entries(s[ae].fields).filter(([un,oi])=>oi.references&&u(oi.references.model)===He),Ke=!0;if(!Be.length)Be=Object.entries(s[He].fields).filter(([un,oi])=>oi.references&&u(oi.references.model)===ae),Ke=!1;if(!Be.length)throw new y(`No foreign key found for model ${de} and base model ${ne} while performing join operation.`);else if(Be.length>1)throw new y(`Multiple foreign keys found for model ${de} and base model ${ne} while performing join operation. Only one foreign key is supported.`);let[Te,Ve]=Be[0];if(!Ve.references)throw new y(`No references found for foreign key ${Te} on model ${de} while performing join operation.`);let Je,ft,qt;if(Ke)qt=Ve.references.field,Je=h({model:ne,field:qt}),ft=h({model:de,field:Te});else qt=Te,Je=h({model:ne,field:qt}),ft=h({model:de,field:Ve.references.field});if(F&&!F.includes(qt))F.push(qt);let ot=ft==="id"?!0:Ve.unique??!1,Tr=r.advanced?.database?.defaultFindManyLimit??100;if(ot)Tr=1;else if(typeof pe==="object"&&typeof pe.limit==="number")Tr=pe.limit;ce[f(de)]={modelKey:de,on:{from:Je,to:ft},limit:Tr,relation:ot?"one-to-one":"one-to-many"}}return{join:ce,select:F}},Ne=async({baseModel:ne,baseData:M,joinModel:F,specificJoinConfig:ce})=>{if(!M)return M;let de=ce.modelKey??u(F),pe=f(de),ae=ce.on.to,He=M[d({field:ce.on.from,model:ne})];if(He===null||He===void 0)return ce.relation==="one-to-one"?null:[];let Be,Ke=O({model:de,where:[{field:ae,value:He,operator:"eq",connector:"AND"}],action:"findOne"});try{if(ce.relation==="one-to-one")Be=await n(`db findOne ${pe}`,{[xo]:"findOne",[Yn]:pe},()=>k.findOne({model:pe,modelKey:de,where:Ke}));else{let Te=ce.limit??r.advanced?.database?.defaultFindManyLimit??100;Be=await n(`db findMany ${pe}`,{[xo]:"findMany",[Yn]:pe},()=>k.findMany({model:pe,modelKey:de,where:Ke,limit:Te}))}}catch(Te){throw c.error(`Failed to query fallback join for model ${pe}:`,{where:Ke,limit:ce.limit}),console.error(Te),Te}return Be},k=e({options:r,schema:s,debugLog:a,getFieldName:h,getModelName:f,getDefaultModelName:u,getDefaultFieldName:d,getFieldAttributes:g,transformInput:_,transformOutput:R,transformWhereClause:O}),j=null,re=QU({adapter:k,adapterId:o.adapterId,mapKeysTransformInput:o.mapKeysTransformInput,mapKeysTransformOutput:o.mapKeysTransformOutput,getFieldName:h,transformOutput:R,transformWhereClause:O}),Oe={transaction:async(ne)=>{if(!j)if(!o.transaction)j=moe(Oe);else c.debug(`[${o.adapterName}] - Using provided transaction implementation.`),j=o.transaction;return j(ne)},create:async({data:ne,model:M,select:F,forceAllowId:ce=!1})=>{vi++;let de=vi,pe=u(M),ae=f(pe);if("id"in ne&&typeof ne.id<"u"&&!ce){c.warn(`[${o.adapterName}] - You are trying to create a record with an id. This is not allowed as we handle id generation for you, unless you pass in the \`forceAllowId\` parameter. The id will be ignored.`);let Te=Error().stack?.split(`
95
+ `).filter((Ve,Je)=>Je!==1).join(`
96
+ `).replace("Error:","Create method with `id` being called at:");console.log(Te),ne.id=void 0}a({method:"create"},`${Bn(de)} ${jn(1,4)}`,`${$n("create")} ${si("Unsafe Input")}:`,{model:ae,data:ne});let He=ne;if(!o.disableTransformInput)He=await _(ne,pe,"create",ce);a({method:"create"},`${Bn(de)} ${jn(2,4)}`,`${$n("create")} ${si("Parsed Input")}:`,{model:ae,data:He});let Be=await n(`db create ${ae}`,{[xo]:"create",[Yn]:ae},()=>k.create({data:He,model:ae,modelKey:pe}));a({method:"create"},`${Bn(de)} ${jn(3,4)}`,`${$n("create")} ${si("DB Result")}:`,{model:ae,res:Be});let Ke=Be;if(!o.disableTransformOutput)Ke=await R(Be,pe,F,void 0);return a({method:"create"},`${Bn(de)} ${jn(4,4)}`,`${$n("create")} ${si("Parsed Result")}:`,{model:ae,data:Ke}),Ke},update:async({model:ne,where:M,update:F})=>{vi++;let ce=vi,de=u(ne),pe=f(de),ae=O({model:de,where:M,action:"update"});if(ae.length===0)return null;a({method:"update"},`${Bn(ce)} ${jn(1,4)}`,`${$n("update")} ${si("Unsafe Input")}:`,{model:pe,data:F});let He=F;if(!o.disableTransformInput)He=await _(F,de,"update");a({method:"update"},`${Bn(ce)} ${jn(2,4)}`,`${$n("update")} ${si("Parsed Input")}:`,{model:pe,data:He});let Be=await n(`db update ${pe}`,{[xo]:"update",[Yn]:pe},()=>k.update({model:pe,modelKey:de,where:ae,update:He}));a({method:"update"},`${Bn(ce)} ${jn(3,4)}`,`${$n("update")} ${si("DB Result")}:`,{model:pe,data:Be});let Ke=Be;if(!o.disableTransformOutput)Ke=await R(Be,de,void 0,void 0);return a({method:"update"},`${Bn(ce)} ${jn(4,4)}`,`${$n("update")} ${si("Parsed Result")}:`,{model:pe,data:Ke}),Ke},updateMany:async({model:ne,where:M,update:F})=>{vi++;let ce=vi,de=u(ne),pe=f(de),ae=O({model:de,where:M,action:"updateMany"});a({method:"updateMany"},`${Bn(ce)} ${jn(1,4)}`,`${$n("updateMany")} ${si("Unsafe Input")}:`,{model:pe,data:F});let He=F;if(!o.disableTransformInput)He=await _(F,de,"update");a({method:"updateMany"},`${Bn(ce)} ${jn(2,4)}`,`${$n("updateMany")} ${si("Parsed Input")}:`,{model:pe,data:He});let Be=await n(`db updateMany ${pe}`,{[xo]:"updateMany",[Yn]:pe},()=>k.updateMany({model:pe,modelKey:de,where:ae,update:He}));if(typeof Be!=="number"||!Number.isFinite(Be))throw new y(`Adapter "${o.adapterId}" updateMany must return a finite number affected row count.`);return a({method:"updateMany"},`${Bn(ce)} ${jn(3,4)}`,`${$n("updateMany")} ${si("DB Result")}:`,{model:pe,data:Be}),a({method:"updateMany"},`${Bn(ce)} ${jn(4,4)}`,`${$n("updateMany")} ${si("Parsed Result")}:`,{model:pe,data:Be}),Be},findOne:async({model:ne,where:M,select:F,join:ce})=>{vi++;let de=vi,pe=u(ne),ae=f(pe),He=O({model:pe,where:M,action:"findOne"}),Be,Ke=!0;if(!o.disableTransformJoin){let Je=I(pe,ce,F);if(Je)Be=Je.join,F=Je.select;if(!r.advanced?.database?.joins&&Be&&Object.keys(Be).length>0)Ke=!1}else Be=ce;a({method:"findOne"},`${Bn(de)} ${jn(1,3)}`,`${$n("findOne")}:`,{model:ae,where:He,select:F,join:Be});let Te=await n(`db findOne ${ae}`,{[xo]:"findOne",[Yn]:ae},()=>k.findOne({model:ae,modelKey:pe,where:He,select:F,join:Ke?Be:void 0}));a({method:"findOne"},`${Bn(de)} ${jn(2,3)}`,`${$n("findOne")} ${si("DB Result")}:`,{model:ae,data:Te});let Ve=Te;if(!o.disableTransformOutput)Ve=await R(Te,pe,F,Be);return a({method:"findOne"},`${Bn(de)} ${jn(3,3)}`,`${$n("findOne")} ${si("Parsed Result")}:`,{model:ae,data:Ve}),Ve},findMany:async({model:ne,where:M,limit:F,select:ce,sortBy:de,offset:pe,join:ae})=>{vi++;let He=vi,Be=F??r.advanced?.database?.defaultFindManyLimit??100,Ke=u(ne),Te=f(Ke),Ve=O({model:Ke,where:M,action:"findMany"}),Je,ft=!0;if(!o.disableTransformJoin){let Tr=I(Ke,ae,ce);if(Tr)Je=Tr.join,ce=Tr.select;if(!r.advanced?.database?.joins&&Je&&Object.keys(Je).length>0)ft=!1}else Je=ae;a({method:"findMany"},`${Bn(He)} ${jn(1,3)}`,`${$n("findMany")}:`,{model:Te,where:Ve,limit:Be,sortBy:de,offset:pe,join:Je});let qt=await n(`db findMany ${Te}`,{[xo]:"findMany",[Yn]:Te},()=>k.findMany({model:Te,modelKey:Ke,where:Ve,limit:Be,select:ce,sortBy:de,offset:pe,join:ft?Je:void 0}));a({method:"findMany"},`${Bn(He)} ${jn(2,3)}`,`${$n("findMany")} ${si("DB Result")}:`,{model:Te,data:qt});let ot=qt;if(!o.disableTransformOutput)ot=await Promise.all(qt.map(async(Tr)=>await R(Tr,Ke,void 0,Je)));return a({method:"findMany"},`${Bn(He)} ${jn(3,3)}`,`${$n("findMany")} ${si("Parsed Result")}:`,{model:Te,data:ot}),ot},delete:async({model:ne,where:M})=>{vi++;let F=vi,ce=u(ne),de=f(ce),pe=O({model:ce,where:M,action:"delete"});a({method:"delete"},`${Bn(F)} ${jn(1,2)}`,`${$n("delete")}:`,{model:de,where:pe}),await n(`db delete ${de}`,{[xo]:"delete",[Yn]:de},()=>k.delete({model:de,modelKey:ce,where:pe})),a({method:"delete"},`${Bn(F)} ${jn(2,2)}`,`${$n("delete")} ${si("DB Result")}:`,{model:de})},deleteMany:async({model:ne,where:M})=>{vi++;let F=vi,ce=u(ne),de=f(ce),pe=O({model:ce,where:M,action:"deleteMany"});a({method:"deleteMany"},`${Bn(F)} ${jn(1,2)}`,`${$n("deleteMany")} ${si("DeleteMany")}:`,{model:de,where:pe});let ae=await n(`db deleteMany ${de}`,{[xo]:"deleteMany",[Yn]:de},()=>k.deleteMany({model:de,modelKey:ce,where:pe}));return a({method:"deleteMany"},`${Bn(F)} ${jn(2,2)}`,`${$n("deleteMany")} ${si("DB Result")}:`,{model:de,data:ae}),ae},consumeOne:async({model:ne,where:M})=>{vi++;let F=vi,ce=u(ne),de=f(ce),pe=O({model:ce,where:M,action:"consumeOne"});a({method:"consumeOne"},`${Bn(F)} ${jn(1,3)}`,`${$n("consumeOne")} ${si("ConsumeOne")}:`,{model:de,where:pe});let ae=await n(`db consumeOne ${de}`,{[xo]:"consumeOne",[Yn]:de},()=>k.consumeOne?k.consumeOne({model:de,modelKey:ce,where:pe}):re.consumeOne({model:de,modelKey:ce,where:pe}));a({method:"consumeOne"},`${Bn(F)} ${jn(2,3)}`,`${$n("consumeOne")} ${si("DB Result")}:`,{model:de,data:ae});let He=ae;if(!o.disableTransformOutput&&ae)He=await R(ae,ce,void 0,void 0);return a({method:"consumeOne"},`${Bn(F)} ${jn(3,3)}`,`${$n("consumeOne")} ${si("Parsed Result")}:`,{model:de,data:He}),He},incrementOne:async({model:ne,where:M,increment:F,set:ce})=>{let de=Object.keys(F).length>0,pe=!!ce&&Object.keys(ce).length>0;if(!de&&!pe)throw new y("incrementOne requires a non-empty `increment` or `set`; both were empty.");vi++;let ae=vi,He=u(ne),Be=f(He),Ke=O({model:He,where:M,action:"incrementOne"});a({method:"incrementOne"},`${Bn(ae)} ${jn(1,3)}`,`${$n("incrementOne")} ${si("IncrementOne")}:`,{model:Be,where:Ke,increment:F,set:ce});let Te=o.mapKeysTransformInput??{},Ve={};for(let[ot,Tr]of Object.entries(F))Ve[Te[ot]||h({model:He,field:ot})]=Tr;let Je;if(ce&&!o.disableTransformInput)Je=await _(ce,He,"update");else Je=ce;if(Object.keys(Ve).length===0&&(!Je||Object.keys(Je).length===0))throw new y("incrementOne resolved to an empty update: every increment/set field was unknown to the schema or transformed away.");let ft=await n(`db incrementOne ${Be}`,{[xo]:"incrementOne",[Yn]:Be},()=>k.incrementOne?k.incrementOne({model:Be,modelKey:He,where:Ke,increment:Ve,set:Je}):re.incrementOne({model:Be,modelKey:He,where:Ke,increment:Ve,set:Je}));a({method:"incrementOne"},`${Bn(ae)} ${jn(2,3)}`,`${$n("incrementOne")} ${si("DB Result")}:`,{model:Be,data:ft});let qt=ft;if(!o.disableTransformOutput&&ft)qt=await R(ft,He,void 0,void 0);return a({method:"incrementOne"},`${Bn(ae)} ${jn(3,3)}`,`${$n("incrementOne")} ${si("Parsed Result")}:`,{model:Be,data:qt}),qt},count:async({model:ne,where:M})=>{vi++;let F=vi,ce=u(ne),de=f(ce),pe=O({model:ce,where:M,action:"count"});a({method:"count"},`${Bn(F)} ${jn(1,2)}`,`${$n("count")}:`,{model:de,where:pe});let ae=await n(`db count ${de}`,{[xo]:"count",[Yn]:de},()=>k.count({model:de,modelKey:ce,where:pe}));return a({method:"count"},`${Bn(F)} ${jn(2,2)}`,`${$n("count")}:`,{model:de,data:ae}),ae},createSchema:k.createSchema?async(ne,M)=>{let F=ye(r);if(r.secondaryStorage&&!r.session?.storeSessionInDatabase)delete F.session;return k.createSchema({file:M,tables:F})}:void 0,options:{adapterConfig:o,...k.options??{}},id:o.adapterId,...o.debugLogs?.isRunningAdapterTests?{adapterTestDebugLogs:{resetDebugLogs(){by=by.filter((ne)=>ne.instance!==i)},printDebugLogs(){let ne="\u2500".repeat(80),M=by.filter((ce)=>ce.instance===i);if(M.length===0)return;let F=M.reverse().map((ce)=>(ce.args[0]=`
97
+ ${ce.args[0]}`,[...ce.args,`
98
+ `])).reduce((ce,de)=>[...de,...ce],[`
99
+ ${ne}`]);console.log(...F)}}}:{}};return Oe};function Bn(e){if(Og()<8)return`#${e}`;return`${Ei.fg.magenta}#${e}${Ei.reset}`}function jn(e,t){return`${Ei.bg.black}${Ei.fg.yellow}[${e}/${t}]${Ei.reset}`}function $n(e){return`${Ei.bright}${e}${Ei.reset}`}function si(e){return`${Ei.dim}(${e})${Ei.reset}`}function $A(e){return e.charAt(0).toUpperCase()+e.slice(1)}function Rr(e){if(!e)return null;if("dialect"in e)return Rr(e.dialect);if("createDriver"in e){if(e instanceof gy)return"sqlite";if(e instanceof yy)return"mysql";if(e instanceof wy)return"postgres";if(e instanceof qA)return"mssql"}if("aggregate"in e)return"sqlite";if("getConnection"in e)return"mysql";if("connect"in e)return"postgres";if("fileControl"in e)return"sqlite";if("open"in e&&"close"in e&&"prepare"in e)return"sqlite";if("batch"in e&&"exec"in e&&"prepare"in e)return"sqlite";return null}function nP(e,t){if(e===void 0)return;if(typeof e!=="string"||e.length===0)throw new y("`database.schemaName` must be a non-empty schema name.");if(t!=="postgres")throw new y(`\`database.schemaName\` is only supported on PostgreSQL, but the configured database type is "${t??"unknown"}".`)}var tn=async(e)=>{let t=e.database;if(!t)return{kysely:null,databaseType:null,introspectIndexes:void 0,schemaName:void 0,transaction:void 0};if("db"in t){let s=t.schemaName;return nP(s,t.type),{kysely:s?t.db.withSchema(s):t.db,databaseType:t.type,introspectIndexes:void 0,schemaName:s,transaction:t.transaction}}if("dialect"in t){let s=t.schemaName;nP(s,t.type);let a=new ba({dialect:t.dialect});return{kysely:s?a.withSchema(s):a,databaseType:t.type,introspectIndexes:void 0,schemaName:s,transaction:t.transaction}}let r=void 0,n=void 0,i=void 0,o=Rr(t);if("createDriver"in t)r=t;if("aggregate"in t&&!("createSession"in t))r=new gy({database:t}),i=!0;if("getConnection"in t)r=new yy(t),i=!0;if("connect"in t)r=new wy({pool:t}),i=!0;if("fileControl"in t){let{BunSqliteDialect:s}=await import("./chunk-pphsqcqt.js");r=new s({database:t}),i=!0}if("createSession"in t){let s=void 0;try{({DatabaseSync:s}=await import("node:sqlite"))}catch(a){if(a!==null&&typeof a==="object"&&"code"in a&&a.code!=="ERR_UNKNOWN_BUILTIN_MODULE")throw a}if(s&&t instanceof s){let{NodeSqliteDialect:a}=await import("./chunk-w0e5ek1r.js");r=new a({database:t}),i=!0}}if("batch"in t&&"exec"in t&&"prepare"in t){let{createD1IndexIntrospector:s,D1SqliteDialect:a}=await import("./chunk-6pf9rgk6.js");r=new a({database:t}),n=s(t),i=!1}return{kysely:r?new ba({dialect:r}):null,databaseType:o,introspectIndexes:n,schemaName:void 0,transaction:i}};function FA(e,t,r){return r==="postgres"?x`${x.ref(e)} ILIKE ${t}`:x`LOWER(${x.ref(e)}) LIKE LOWER(${t})`}function goe(e,t){return{lhs:x`LOWER(${x.ref(e)})`,values:t.map((r)=>r.toLowerCase())}}function yoe(e,t){return{lhs:x`LOWER(${x.ref(e)})`,values:t.map((r)=>r.toLowerCase())}}function woe(e,t){return{lhs:x`LOWER(${x.ref(e)})`,value:t.toLowerCase()}}function _oe(e,t){return{lhs:x`LOWER(${x.ref(e)})`,value:t.toLowerCase()}}function kr(e){return e.map((t)=>({name:t.name,schema:t.schema,columns:t.columns.map((r)=>({name:r.name,nullable:r.isNullable,hasDefault:r.hasDefaultValue||r.isAutoIncrementing}))}))}function rn(e,t){let r={};for(let[n,i]of Object.entries(t)){let o=Object.entries(i.fields),s=boe(e,n,[i.idColumn??"id",...o.map(([c])=>c)]),a={};o.forEach(([c,u],d)=>{a[s.columns[d+1]??c]=u}),r[s.table]={...i,fields:a,schema:s.schema??i.schema,...s.columns[0]!=="id"&&{idColumn:s.columns[0]}}}return r}function boe(e,t,r){let{query:n}=e.selectFrom(t).select(r).compile();if(!mn.is(n))return{table:t,columns:[]};let i=n.from?.froms[0],o=i&&co.is(i)?i.table:void 0;return{schema:o?.schema?.name,table:o?.identifier.name??t,columns:(n.selections??[]).map(({selection:s})=>Pc.is(s)&&Hr.is(s.column)?s.column.column.name:void 0)}}async function fn(e){return(await x`
100
+ SELECT pg_catalog.current_schema() AS schema
101
+ `.execute(e.withoutPlugins())).rows[0]?.schema??"public"}async function nn(e){return(await x`
102
+ SELECT SCHEMA_NAME() AS "schemaName"
103
+ `.execute(e.withoutPlugins())).rows[0]?.schemaName||"dbo"}async function Eoe(e,t){if(t==="postgres")return(await x`
104
+ SELECT pg_catalog.current_schemas(true)::text[] AS schemas
105
+ `.execute(e.withoutPlugins())).rows[0]?.schemas??[];if(t==="mssql")return[await nn(e),"dbo"]}async function Soe(e,t,r){let n=rn(e,r);if(t==="sqlite")return dt(n,kr(await VU(e,Object.entries(n).flatMap(([i,o])=>o.disableMigrations?[]:[i]))));return e.connection().execute(async(i)=>{let o=await Eoe(i,t),s=kr(await i.introspection.getTables());for(let[a,c]of Object.entries(n)){if(c.schema!==void 0||!o)continue;c.schema=o.find((u)=>s.some((d)=>d.name===a&&d.schema===u))??""}return dt(n,s)})}var kn=(e,t)=>{let r=null,n=!1,i=(a,c=!1)=>({getFieldName:u,schema:d,getDefaultFieldName:f,getDefaultModelName:h,getFieldAttributes:p,getModelName:g,options:_})=>{if(t?.type==="mysql"&&_.advanced?.database?.generateId===!1&&!n)n=!0,T.warn(`[Kysely Adapter] MySQL does not support INSERT...RETURNING. With generateId set to false, the adapter uses best-effort fallback strategies (unique columns, full-field match) to retrieve inserted rows. For reliable behavior, use Better Auth's default ID generation, a custom generateId function, or generateId: "serial" for auto-increment.`);let R=(k)=>{let j=[],re=[];if(k)for(let[Oe,ne]of Object.entries(k)){let M=d[ne.modelKey??h(Oe)]?.fields,[F,ce]=Oe.includes(".")?Oe.split("."):[void 0,Oe];if(!M)continue;M.id={type:"string"};for(let[de,pe]of Object.entries(M))j.push(x`${x.ref(`join_${ce}`)}.${x.ref(pe.fieldName||de)} as ${x.ref(`_joined_${ce}_${pe.fieldName||de}`)}`),re.push({joinModel:Oe,joinModelRef:ce,fieldName:pe.fieldName||de})}return{allSelectsStr:re,allSelects:j}},O=async(k,j,re,Oe,ne)=>{if(t?.type==="mysql"){if(ne.length>0){let F=await j.executeTakeFirst();if(!F||Number(F.numUpdatedRows??0)===0)return null;let ce=ne.find((ae)=>ae.field==="id"&&(ae.operator===void 0||ae.operator==="eq")&&ae.connector!=="OR"&&ae.value!==void 0&&ae.value!==null),de,pe;if(k.id!==void 0&&k.id!==null)de="id",pe=k.id;else if(ce)de="id",pe=ce.value;else if(ne[0]?.field)de=ne[0].field,pe=k[de]!==void 0?k[de]:ne[0].value;else return null;return await a.selectFrom(re).selectAll().where(u({model:Oe,field:de}),pe===null?"is":"=",pe).limit(1).executeTakeFirst()}await j.execute();let M=async(F)=>{if(k.id)return await F.selectFrom(re).selectAll().where(u({model:Oe,field:"id"}),"=",k.id).limit(1).executeTakeFirst();if(_.advanced?.database?.generateId==="serial"){let ae=(await x`SELECT LAST_INSERT_ID() as id`.execute(F)).rows[0]?.id;if(ae)return await F.selectFrom(re).selectAll().where(u({model:Oe,field:"id"}),"=",ae).limit(1).executeTakeFirst()}let ce=d[Oe]?.fields;if(ce)for(let[ae,He]of Object.entries(ce)){if(!He.unique)continue;let Be=u({model:Oe,field:ae}),Ke=k[Be];if(Ke===void 0||Ke===null)continue;let Te=await F.selectFrom(re).selectAll().where(Be,"=",Ke).limit(1).executeTakeFirst();if(Te)return Te}let de=F.selectFrom(re).selectAll(),pe=!1;for(let[ae,He]of Object.entries(k)){if(He===void 0)continue;de=de.where(ae,He===null?"is":"=",He),pe=!0}if(pe){let ae=await de.limit(2).execute();if(ae.length===1)return ae[0]}return T.warn(`[Kysely Adapter] Unable to safely identify the inserted "${re}" row on MySQL. Enable Better Auth ID generation or use generateId: "serial" for reliable behavior.`),null};return c?M(a):a.transaction().execute(M)}if(t?.type==="mssql")return await j.outputAll("inserted").executeTakeFirst();return await j.returningAll().executeTakeFirst()};function I(k,j,re){if(!re)return{and:null,or:null};let Oe={and:[],or:[]};return re.forEach((ne)=>{let{field:M,value:F,operator:ce="eq",connector:de="AND",mode:pe="sensitive"}=ne,ae=F,He=u({model:j,field:M}),Be=pe==="insensitive"&&(typeof ae==="string"||Array.isArray(ae)&&ae.every((Te)=>typeof Te==="string")),Ke=(Te)=>{let Ve=`${k}.${He}`;if(ce.toLowerCase()==="in"){if(Be){let{lhs:Je,values:ft}=goe(Ve,Array.isArray(ae)?ae:[ae]);return Te(Je,"in",ft)}return Te(Ve,"in",Array.isArray(ae)?ae:[ae])}if(ce.toLowerCase()==="not_in"){if(Be){let{lhs:Je,values:ft}=yoe(Ve,Array.isArray(ae)?ae:[ae]);return Te(Je,"not in",ft)}return Te(Ve,"not in",Array.isArray(ae)?ae:[ae])}if(ce==="contains"){if(Be&&typeof ae==="string")return FA(Ve,`%${ae}%`,t?.type);return Te(Ve,"like",`%${ae}%`)}if(ce==="starts_with"){if(Be&&typeof ae==="string")return FA(Ve,`${ae}%`,t?.type);return Te(Ve,"like",`${ae}%`)}if(ce==="ends_with"){if(Be&&typeof ae==="string")return FA(Ve,`%${ae}`,t?.type);return Te(Ve,"like",`%${ae}`)}if(ce==="eq"){if(ae===null)return Te(Ve,"is",null);if(Be&&typeof ae==="string"){let{lhs:Je,value:ft}=woe(Ve,ae);return Te(Je,"=",ft)}return Te(Ve,"=",ae)}if(ce==="ne"){if(ae===null)return Te(Ve,"is not",null);if(Be&&typeof ae==="string"){let{lhs:Je,value:ft}=_oe(Ve,ae);return Te(Je,"<>",ft)}return Te(Ve,"<>",ae)}if(ce==="gt")return Te(Ve,">",ae);if(ce==="gte")return Te(Ve,">=",ae);if(ce==="lt")return Te(Ve,"<",ae);if(ce==="lte")return Te(Ve,"<=",ae);return Te(Ve,ce,ae)};if(de==="OR")Oe.or.push(Ke);else Oe.and.push(Ke)}),{and:Oe.and.length?Oe.and:null,or:Oe.or.length?Oe.or:null}}function Ne(k,j,re){if(!j||!k.length)return k;let Oe=new Map;for(let M of k){let F={},ce={};for(let[ae]of Object.entries(j))ce[ae]={};for(let[ae,He]of Object.entries(M)){let Be=String(ae),Ke=!1;for(let{joinModel:Te,fieldName:Ve,joinModelRef:Je}of re)if(Be===`_joined_${Je}_${Ve}`||Be===`_Joined${$A(Je)}${$A(Ve)}`){ce[Te][u({model:j[Te]?.modelKey??Te,field:Ve})]=He,Ke=!0;break}if(!Ke)F[ae]=He}let de=F.id;if(!de)continue;if(!Oe.has(de)){let ae={...F};for(let[He,Be]of Object.entries(j))ae[He]=Be.relation==="one-to-one"?null:[];Oe.set(de,ae)}let pe=Oe.get(de);for(let[ae,He]of Object.entries(j)){let Be=He.relation==="one-to-one",Ke=He.limit??100,Te=ce[ae],Ve=Te&&Object.keys(Te).length>0&&Object.values(Te).some((Je)=>Je!==null&&Je!==void 0);if(Be)pe[ae]=Ve?Te:null;else{let Je=ae;if(Array.isArray(pe[Je])&&Ve){if(pe[Je].length>=Ke)continue;let ft=u({model:He.modelKey??ae,field:"id"}),qt=Te[ft];if(qt){if(!pe[Je].some((ot)=>ot[ft]===qt)&&pe[Je].length<Ke)pe[Je].push(Te)}else if(pe[Je].length<Ke)pe[Je].push(Te)}}}}let ne=Array.from(Oe.values());for(let M of ne)for(let[F,ce]of Object.entries(j))if(ce.relation!=="one-to-one"){let de=F;if(Array.isArray(M[de])){let pe=ce.limit??100;if(M[de].length>pe)M[de]=M[de].slice(0,pe)}}return ne}return{async create({data:k,model:j,modelKey:re=j}){return await O(k,a.insertInto(j).values(k),j,re,[])},async findOne({model:k,modelKey:j=k,where:re,select:Oe,join:ne}){let{and:M,or:F}=I(k,j,re),ce=a.selectFrom((Be)=>{let Ke=Be.selectFrom(k);if(M)Ke=Ke.where((Te)=>Te.and(M.map((Ve)=>Ve(Te))));if(F)Ke=Ke.where((Te)=>Te.or(F.map((Ve)=>Ve(Te))));if(Oe?.length&&Oe.length>0)Ke=Ke.select(Oe.map((Te)=>u({model:j,field:Te})));else Ke=Ke.selectAll();return Ke.as("primary")}).selectAll("primary");if(ne)for(let[Be,Ke]of Object.entries(ne)){let[Te,Ve]=Be.includes(".")?Be.split("."):[void 0,Be];ce=ce.leftJoin(`${Be} as join_${Ve}`,(Je)=>Je.onRef(`join_${Ve}.${Ke.on.to}`,"=",`primary.${Ke.on.from}`))}let{allSelectsStr:de,allSelects:pe}=R(ne);ce=ce.select(pe);let ae=await ce.execute();if(!ae||!Array.isArray(ae)||ae.length===0)return null;let He=ae[0];if(ne)return Ne(ae,ne,de)[0];return He},async findMany({model:k,modelKey:j=k,where:re,limit:Oe,select:ne,offset:M,sortBy:F,join:ce}){let{and:de,or:pe}=I(k,j,re),ae=a.selectFrom((Te)=>{let Ve=Te.selectFrom(k);if(t?.type==="mssql"){if(M!==void 0){if(!F)Ve=Ve.orderBy(u({model:j,field:"id"}));Ve=Ve.offset(M).fetch(Oe||100)}else if(Oe!==void 0)Ve=Ve.top(Oe)}else{if(Oe!==void 0)Ve=Ve.limit(Oe);if(M!==void 0)Ve=Ve.offset(M)}if(F?.field)Ve=Ve.orderBy(`${u({model:j,field:F.field})}`,F.direction);if(de)Ve=Ve.where((Je)=>Je.and(de.map((ft)=>ft(Je))));if(pe)Ve=Ve.where((Je)=>Je.or(pe.map((ft)=>ft(Je))));if(ne?.length&&ne.length>0)Ve=Ve.select(ne.map((Je)=>u({model:j,field:Je})));else Ve=Ve.selectAll();return Ve.as("primary")}).selectAll("primary");if(ce)for(let[Te,Ve]of Object.entries(ce)){let[Je,ft]=Te.includes(".")?Te.split("."):[void 0,Te];ae=ae.leftJoin(`${Te} as join_${ft}`,(qt)=>qt.onRef(`join_${ft}.${Ve.on.to}`,"=",`primary.${Ve.on.from}`))}let{allSelectsStr:He,allSelects:Be}=R(ce);if(ae=ae.select(Be),F?.field)ae=ae.orderBy(`${u({model:j,field:F.field})}`,F.direction);let Ke=await ae.execute();if(!Ke)return[];if(ce)return Ne(Ke,ce,He);return Ke},async update({model:k,modelKey:j=k,where:re,update:Oe}){if(re.length===0)return null;let{and:ne,or:M}=I(k,j,re),F=a.updateTable(k).set(Oe);if(ne)F=F.where((ce)=>ce.and(ne.map((de)=>de(ce))));if(M)F=F.where((ce)=>ce.or(M.map((de)=>de(ce))));return await O(Oe,F,k,j,re)},async updateMany({model:k,modelKey:j=k,where:re,update:Oe}){let{and:ne,or:M}=I(k,j,re),F=a.updateTable(k).set(Oe);if(ne)F=F.where((de)=>de.and(ne.map((pe)=>pe(de))));if(M)F=F.where((de)=>de.or(M.map((pe)=>pe(de))));let ce=(await F.executeTakeFirst()).numUpdatedRows;return ce>Number.MAX_SAFE_INTEGER?Number.MAX_SAFE_INTEGER:Number(ce)},async count({model:k,modelKey:j=k,where:re}){let{and:Oe,or:ne}=I(k,j,re),M=a.selectFrom(k).select(a.fn.count("id").as("count"));if(Oe)M=M.where((ce)=>ce.and(Oe.map((de)=>de(ce))));if(ne)M=M.where((ce)=>ce.or(ne.map((de)=>de(ce))));let F=await M.execute();if(typeof F[0].count==="number")return F[0].count;if(typeof F[0].count==="bigint")return Number(F[0].count);return parseInt(F[0].count)},async delete({model:k,modelKey:j=k,where:re}){let{and:Oe,or:ne}=I(k,j,re),M=a.deleteFrom(k);if(Oe)M=M.where((F)=>F.and(Oe.map((ce)=>ce(F))));if(ne)M=M.where((F)=>F.or(ne.map((ce)=>ce(F))));await M.execute()},async deleteMany({model:k,modelKey:j=k,where:re}){let{and:Oe,or:ne}=I(k,j,re),M=a.deleteFrom(k);if(Oe)M=M.where((ce)=>ce.and(Oe.map((de)=>de(ce))));if(ne)M=M.where((ce)=>ce.or(ne.map((de)=>de(ce))));let F=(await M.executeTakeFirst()).numDeletedRows;return F>Number.MAX_SAFE_INTEGER?Number.MAX_SAFE_INTEGER:Number(F)},async consumeOne({model:k,modelKey:j=k,where:re}){let{and:Oe,or:ne}=I(k,j,re),M=(He)=>{if(Oe)He=He.where((Be)=>Be.and(Oe.map((Ke)=>Ke(Be))));if(ne)He=He.where((Be)=>Be.or(ne.map((Ke)=>Ke(Be))));return He},F=u({model:j,field:"id"}),ce=async(He,Be)=>{let Ke=Be[F]??Be.id;if(Ke===void 0||Ke===null)return null;let Te=He.deleteFrom(k).where(`${k}.${F}`,"=",Ke);if(t?.type==="mysql"){let Ve=await Te.executeTakeFirst();return Number(Ve.numDeletedRows)>0?Be:null}if(t?.type==="mssql")return await Te.outputAll("deleted").executeTakeFirst()??null;return await Te.returningAll().executeTakeFirst()??null},de=async(He)=>{if(t?.type==="mssql")return await He.outputAll("deleted").executeTakeFirst()??null;return await He.returningAll().executeTakeFirst()??null};if(t?.type==="mysql"){let He=async(Be)=>{let Ke=await M(Be.selectFrom(k).selectAll().forUpdate()).limit(1).executeTakeFirst();if(!Ke)return null;return ce(Be,Ke)};return c?He(a):a.transaction().execute(He)}let pe=M(a.selectFrom(k).select(`${k}.${F}`)),ae=t?.type==="mssql"?pe.top(1):pe.limit(1);return de(M(a.deleteFrom(k).where(`${k}.${F}`,"in",ae)))},async incrementOne({model:k,modelKey:j=k,where:re,increment:Oe,set:ne}){let{and:M,or:F}=I(k,j,re),ce=(Ke)=>{if(M)Ke=Ke.where((Te)=>Te.and(M.map((Ve)=>Ve(Te))));if(F)Ke=Ke.where((Te)=>Te.or(F.map((Ve)=>Ve(Te))));return Ke},de={...ne??{}};for(let[Ke,Te]of Object.entries(Oe))de[Ke]=x`${x.ref(Ke)} + ${Te}`;let pe=u({model:j,field:"id"});if(t?.type==="mysql"){let Ke=async(Te)=>{let Ve=await ce(Te.selectFrom(k).select(`${k}.${pe}`).forUpdate()).limit(1).executeTakeFirst();if(!Ve)return null;let Je=Ve[pe]??Ve.id;if(Je===void 0||Je===null)return null;let ft=await ce(Te.updateTable(k).set(de)).where(`${k}.${pe}`,"=",Je).executeTakeFirst();if(Number(ft.numUpdatedRows)===0)return null;return await Te.selectFrom(k).selectAll().where(`${k}.${pe}`,"=",Je).limit(1).executeTakeFirst()??null};return c?Ke(a):a.transaction().execute(Ke)}let ae=ce(a.selectFrom(k).select(`${k}.${pe}`)),He=t?.type==="mssql"?ae.top(1):ae.limit(1),Be=ce(a.updateTable(k).set(de)).where(`${k}.${pe}`,"in",He);if(t?.type==="mssql")return await Be.outputAll("inserted").executeTakeFirst()??null;return await Be.returningAll().executeTakeFirst()??null},options:t}},o=null;o={config:{adapterId:"kysely",adapterName:"Kysely Adapter",usePlural:t?.usePlural,debugLogs:t?.debugLogs,supportsBooleans:t?.type==="sqlite"||t?.type==="mssql"||t?.type==="mysql"||!t?.type?!1:!0,supportsDates:t?.type==="sqlite"||t?.type==="mssql"||!t?.type?!1:!0,supportsJSON:t?.type==="postgres"?!0:!1,supportsArrays:!1,supportsUUIDs:t?.type==="postgres"?!0:!1,transaction:t?.transaction?(a)=>e.transaction().execute((c)=>a(ze({config:{...o.config,transaction:!1},adapter:i(c,!0)})(r))):!1},adapter:i(e)};let s=ze(o);return(a)=>{r=a;let c=s(a);return cr(c,ur(()=>Soe(e,t?.type,sr(a,{usePlural:t?.usePlural})),"database",a.database),{runtimeEnabled:ar(a)}),c}};function zA(e){if(e==="-"||e==="^"||e==="$"||e==="+"||e==="."||e==="("||e===")"||e==="|"||e==="["||e==="]"||e==="{"||e==="}"||e==="*"||e==="?"||e==="\\")return`\\${e}`;else return e}function Aoe(e){let t="";for(let r=0;r<e.length;r++)t+=zA(e[r]);return t}function iP(e,t=!0){if(Array.isArray(e))return`(?:${e.map((u)=>`^${iP(u,t)}$`).join("|")})`;let r="",n="",i=".";if(t===!0)r="/",n="[/\\\\]",i="[^/\\\\]";else if(t)if(r=t,n=Aoe(r),n.length>1)n=`(?:${n})`,i=`((?!${n}).)`;else i=`[^${n}]`;let o=t?`${n}+?`:"",s=t?`${n}*?`:"",a=t?e.split(r):[e],c="";for(let u=0;u<a.length;u++){let d=a[u],f=a[u+1],h="";if(!d&&u>0)continue;if(t)if(u===a.length-1)h=s;else if(f!=="**")h=o;else h="";if(t&&d==="**"){if(h)c+=u===0?"":h,c+=`(?:${i}*?${h})*?`;continue}for(let p=0;p<d.length;p++){let g=d[p];if(g==="\\"){if(p<d.length-1)c+=zA(d[p+1]),p++}else if(g==="?")c+=i;else if(g==="*")c+=`${i}*?`;else c+=zA(g)}c+=h}return c}function Toe(e,t){if(typeof t!=="string")throw TypeError(`Sample must be a string, but ${typeof t} given`);return e.test(t)}function Qu(e,t){if(typeof e!=="string"&&!Array.isArray(e))throw TypeError(`The first argument must be a single pattern string or an array of patterns, but ${typeof e} given`);if(typeof t==="string"||typeof t==="boolean")t={separator:t};if(arguments.length===2&&!(typeof t>"u"||typeof t==="object"&&t!==null&&!Array.isArray(t)))throw TypeError(`The second argument must be an options object or a string/boolean separator, but ${typeof t} given`);if(t=t||{},t.separator==="\\")throw Error("\\ is not a valid separator because it is used for escaping. Try setting the separator to `true` instead");let r=iP(e,t.separator),n=new RegExp(`^${r}$`,t.flags),i=Toe.bind(null,n);return i.options=t,i.pattern=e,i.regexp=n,i}var voe=47;function koe(e){let t=e.replace(/:\d+$/,"").replace(/^\[|\]$/g,"").toLowerCase();return t==="localhost"||t.endsWith(".localhost")||t==="::1"||t.startsWith("127.")}function oP(e){let t=e.length;while(t>0&&e.charCodeAt(t-1)===voe)t--;return t===e.length?e:e.slice(0,t)}function Roe(e){try{return(oP(new URL(e).pathname)||"/")!=="/"}catch{throw new y(`Invalid base URL: ${e}. Please provide a valid base URL.`)}}function Noe(e){try{let t=new URL(e);if(t.protocol!=="http:"&&t.protocol!=="https:")throw new y(`Invalid base URL: ${e}. URL must include 'http://' or 'https://'`)}catch(t){if(t instanceof y)throw t;throw new y(`Invalid base URL: ${e}. Please provide a valid base URL.`,{cause:t})}}function sc(e,t="/api/auth"){if(Noe(e),Roe(e))return e;let r=oP(e);if(!t||t==="/")return r;return t=t.startsWith("/")?t:`/${t}`,`${r}${t}`}function Gh(e,t){if(!e||e.trim()==="")return!1;if(t==="proto")return e==="http"||e==="https";if(t==="host"){if([/\.\./,/\0/,/[\s]/,/^[.]/,/[<>'"]/,/javascript:/i,/file:/i,/data:/i].some((r)=>r.test(e)))return!1;return/^[a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(\.[a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*(:[0-9]{1,5})?$/.test(e)||/^(\d{1,3}\.){3}\d{1,3}(:[0-9]{1,5})?$/.test(e)||/^\[[0-9a-fA-F:]+\](:[0-9]{1,5})?$/.test(e)||/^localhost(:[0-9]{1,5})?$/i.test(e)}return!1}function Ue(e,t,r,n,i){if(e)return sc(e,t);if(n!==!1){let a=D.BETTER_AUTH_URL||D.NEXT_PUBLIC_BETTER_AUTH_URL||D.PUBLIC_BETTER_AUTH_URL||D.NUXT_PUBLIC_BETTER_AUTH_URL||D.NUXT_PUBLIC_AUTH_URL||(D.BASE_URL!=="/"?D.BASE_URL:void 0);if(a)return sc(a,t)}let o=r?.headers.get("x-forwarded-host"),s=r?.headers.get("x-forwarded-proto");if(o&&s&&i){if(Gh(s,"proto")&&Gh(o,"host"))try{return sc(`${s}://${o}`,t)}catch(a){}}if(r){let a=qe(r.url);if(!a)throw new y("Could not get origin from request. Please provide a valid base URL.");return sc(a,t)}if(typeof window<"u"&&window.location)return sc(window.location.origin,t)}function qe(e){try{let t=new URL(e);return t.origin==="null"?null:t.origin}catch{return null}}function sP(e){try{return new URL(e).protocol}catch{return null}}function aP(e){try{return new URL(e).host}catch{return null}}function Ee(e){return typeof e==="object"&&e!==null&&"allowedHosts"in e&&Array.isArray(e.allowedHosts)}function as(e){if(e instanceof Request)return!0;if(typeof e!=="object"||e===null||Object.prototype.toString.call(e)!=="[object Request]")return!1;let t=e;return typeof t.url==="string"&&typeof t.headers==="object"&&t.headers!==null&&typeof t.headers.get==="function"}function cP(e,t){let r=as(e)?e.headers:e;if(t){let i=r.get("x-forwarded-host");if(i&&Gh(i,"host"))return i}let n=r.get("host");if(n&&Gh(n,"host"))return n;if(as(e))try{return new URL(e.url).host}catch{return null}return null}function xoe(e,t,r){if(t==="http"||t==="https")return t;let n=as(e)?e.headers:e;if(r){let o=n.get("x-forwarded-proto");if(o&&Gh(o,"proto"))return o}if(as(e))try{let o=new URL(e.url);if(o.protocol==="http:"||o.protocol==="https:")return o.protocol.slice(0,-1)}catch{}let i=cP(e,r);if(i&&koe(i))return"http";return"https"}var Coe=(e,t)=>{if(!e||!t)return!1;let r=e.replace(/^https?:\/\//,"").split("/")[0].toLowerCase(),n=t.replace(/^https?:\/\//,"").split("/")[0].toLowerCase();if(n.includes("*")||n.includes("?"))return Qu(n)(r);return r.toLowerCase()===n.toLowerCase()};function Ooe(e,t,r,n){let i=cP(t,n);if(!i){if(e.fallback)return sc(e.fallback,r);throw new y("Could not determine host from request headers. Please provide a fallback URL in your baseURL config.")}if(e.allowedHosts.some((o)=>Coe(i,o)))return sc(`${xoe(t,e.protocol,n)}://${i}`,r);if(e.fallback)return sc(e.fallback,r);throw new y(`Host "${i}" is not in the allowed hosts list. Allowed hosts: ${e.allowedHosts.join(", ")}. Add this host to your allowedHosts config or provide a fallback URL.`)}function uP(e,t,r,n,i){if(Ee(e)){if(r)return Ooe(e,r,t,i);if(e.fallback)return sc(e.fallback,t);return Ue(void 0,t,void 0,n,i)}let o=as(r)?r:void 0;if(typeof e==="string")return Ue(e,t,o,n,i);return Ue(void 0,t,o,n,i)}var fP=/[\u0000-\u001f\u007f-\u009f]/,dP="https://better-auth.invalid",Ioe=/%2[fF]|%5[cC]/,Doe=(e)=>{let t=e;try{t=decodeURIComponent(e)}catch{}let r=[];for(let n of t.split("/"))if(n==="..")r.pop();else if(n!=="."&&n!=="")r.push(n);return r.length>0?`/${r.join("/")}`:""},lP=(e)=>{if(fP.test(e))return null;let t=e.indexOf(":");if(t<=0)return null;let r=e.slice(0,t).toLowerCase(),n=e.slice(t+1),i="";if(n.startsWith("//")){n=n.slice(2);let a=n.search(/[/?#]/);if(a===-1)i=n,n="";else i=n.slice(0,a),n=n.slice(a)}let o=n.search(/[?#]/),s=Doe(o===-1?n:n.slice(0,o));return{scheme:r,authority:i.toLowerCase(),path:s}},Uoe=(e)=>{if(!e.startsWith("/")||e.startsWith("//")||e.includes("\\")||fP.test(e))return!1;let t=e.search(/[?#]/),r=t===-1?e:e.slice(0,t);if(Ioe.test(r))return!1;try{return new URL(e,dP).origin===dP}catch{return!1}},Or=(e,t,r)=>{if(e.startsWith("/"))return r?.allowRelativePaths===!0&&Uoe(e);if(t.includes("*")||t.includes("?")){if(t.includes("://"))return Qu(t)(qe(e)||e);let s=aP(e);if(!s)return!1;return Qu(t)(s)}let n=sP(e);if(n==="http:"||n==="https:"||!n)return t===qe(e);let i=lP(e),o=lP(t);if(!i||!o||i.scheme!==o.scheme)return!1;if(o.authority&&i.authority!==o.authority)return!1;if(!o.path)return!0;return i.path===o.path||i.path.startsWith(`${o.path}/`)};function Pr(e){return!!e.database||!!e.secondaryStorage}function Poe(e){return!!e.database}function Ey(e){return Poe(e)}function bt(e){return!!e&&(typeof e==="object"||typeof e==="function")&&typeof e.then==="function"}class WA{oHash;iHash;blockLen;outputLen;canXOF=!1;finished=!1;destroyed=!1;constructor(e,t){if(bh(e),Va(t,void 0,"key"),this.iHash=e.create(),typeof this.iHash.update!=="function")throw Error("expected Hash instance");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;let r=this.blockLen,n=new Uint8Array(r);n.set(t.length>r?e.create().update(t).digest():t);for(let i=0;i<n.length;i++)n[i]^=54;this.iHash.update(n),this.oHash=e.create();for(let i=0;i<n.length;i++)n[i]^=106;this.oHash.update(n),Ns(n)}update(e){return Zd(this),this.iHash.update(e),this}digestInto(e){Zd(this),Pg(e,this),this.finished=!0;let t=e.subarray(0,this.outputLen);this.iHash.digestInto(t),this.oHash.update(t),this.oHash.digestInto(t),this.destroy()}digest(){let e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||=Object.create(Object.getPrototypeOf(this),{});let{oHash:t,iHash:r,finished:n,destroyed:i,blockLen:o,outputLen:s,canXOF:a}=this;return e=e,e.finished=n,e.destroyed=i,e.blockLen=o,e.outputLen=s,e.canXOF=a,e.oHash=t._cloneInto(e.oHash),e.iHash=r._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}}var HA=(()=>{let e=(t,r,n)=>new WA(t,r).update(n).digest();return e.create=(t,r)=>new WA(t,r),e})();var Kh=Uint8Array.of(0),Loe=Uint8Array.of();function Moe(e,t,r,n=32,i){bh(e),_h(n,"length"),Va(t,void 0,"prk");let o=e.outputLen;if(t.length<o)throw Error('"prk" must be at least HashLen octets');if(n>255*o)throw Error("Length must be <= 255*HashLen");let s=Math.ceil(n/o);if(r===void 0)r=Loe;else Va(r,void 0,"info");if(!s){if(i)Ns(t);return new Uint8Array}let a=i&&s===1?t:new Uint8Array(s*o),{iHash:c,oHash:u}=HA.create(e,t),d=i?t:new Uint8Array(o),f=s>1?i?.iHash||e.create():void 0;for(let p=0;p<s-1;p++){Kh[0]=p+1;let g=c._cloneInto(f);if(p)g.update(d);g.update(r).update(Kh).digestInto(d),u._cloneInto(f).update(d).digestInto(d),a.set(d,o*p)}if(Kh[0]=s,s>1)c.update(d);if(c.update(r).update(Kh).digestInto(d),u.update(d).digestInto(d),a.set(d,o*(s-1)),c.destroy(),u.destroy(),f?.destroy(),d!==a)Ns(d);if(Ns(Kh),n===a.length)return a;let h=a.slice(0,n);return Ns(a),h}var Sy=(e,t,r,n,i)=>{if(bh(e),r===void 0)r=new Uint8Array(e.outputLen);let o=HA.create(e,r).update(t);return Moe(e,o.digest(),n,i,o)};var qoe=(e)=>e/4294967296|0,Boe=(e)=>e>>>0;function hP(e,t,r,n){let i=qoe(r),o=Boe(r);e.setUint32(t,n?o:i,n),e.setUint32(t+4,n?i:o,n)}function pP(e,t,r){return e&t^~e&r}function mP(e,t,r){return e&t^e&r^t&r}class VA{blockLen;outputLen;canXOF=!1;padOffset;isLE;buffer;view;finished=!1;length=0;pos=0;destroyed=!1;constructor(e,t,r,n){this.blockLen=e,this.outputLen=t,this.padOffset=r,this.isLE=n,this.buffer=new Uint8Array(e),this.view=Lg(this.buffer)}update(e){Zd(this),Va(e);let{view:t,buffer:r,blockLen:n}=this,i=e.length,o=!1;for(let s=0;s<i;){let a=Math.min(n-this.pos,i-s);if(a===n){let c=Lg(e);for(;n<=i-s;s+=n)this.process(c,s);o=!0;continue}if(r.set(s===0&&a===i?e:e.subarray(s,s+a),this.pos),this.pos+=a,s+=a,this.pos===n)this.process(t,0),this.pos=0,o=!0}if(this.length+=e.length,o)this.roundClean();return this}digestInto(e){Zd(this),Pg(e,this),this.finished=!0;let{buffer:t,view:r,blockLen:n,isLE:i}=this,{pos:o}=this;if(t[o++]=128,t.fill(0,o),this.padOffset>n-o)this.process(r,0),t.fill(0);hP(r,n-8,this.length*8,i),this.process(r,0),this.roundClean();let s=e===t?r:Lg(e),a=this.outputLen,c=a/4,u=this.get();if(a%4||c>u.length)throw Error("invalid outputLen");for(let d=0;d<c;d++)s.setUint32(4*d,u[d],i)}digest(){let{buffer:e,outputLen:t}=this;this.digestInto(e);let r=e.slice(0,t);return this.destroy(),r}_cloneIntoMeta(e){let{buffer:t,length:r,finished:n,destroyed:i,pos:o}=this;if(e.destroyed=i,e.finished=n,e.length=r,e.pos=o,o)e.buffer.set(t);return e}clone(){return this._cloneInto()}}var gP=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);var joe=Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),Jc=new Uint32Array(64);class yP extends VA{A=0;B=0;C=0;D=0;E=0;F=0;G=0;H=0;constructor(e,t){super(64,e,8,!1);this.A=t[0]|0,this.B=t[1]|0,this.C=t[2]|0,this.D=t[3]|0,this.E=t[4]|0,this.F=t[5]|0,this.G=t[6]|0,this.H=t[7]|0}get(){let{A:e,B:t,C:r,D:n,E:i,F:o,G:s,H:a}=this;return[e,t,r,n,i,o,s,a]}set(e,t,r,n,i,o,s,a){this.A=e|0,this.B=t|0,this.C=r|0,this.D=n|0,this.E=i|0,this.F=o|0,this.G=s|0,this.H=a|0}_cloneInto(e){return(e||=new this.constructor).set(...this.get()),this._cloneIntoMeta(e)}process(e,t){for(let d=0;d<16;d++,t+=4)Jc[d]=e.getUint32(t,!1);for(let d=16;d<64;d++){let f=Jc[d-15],h=Jc[d-2],p=xs(f,7)^xs(f,18)^f>>>3,g=xs(h,17)^xs(h,19)^h>>>10;Jc[d]=g+Jc[d-7]+p+Jc[d-16]|0}let{A:r,B:n,C:i,D:o,E:s,F:a,G:c,H:u}=this;for(let d=0;d<64;d++){let f=xs(s,6)^xs(s,11)^xs(s,25),h=u+f+pP(s,a,c)+joe[d]+Jc[d]|0,g=(xs(r,2)^xs(r,13)^xs(r,22))+mP(r,n,i)|0;u=c,c=a,a=s,s=o+h|0,o=i,i=n,n=r,r=h+g|0}r=r+this.A|0,n=n+this.B|0,i=i+this.C|0,o=o+this.D|0,s=s+this.E|0,a=a+this.F|0,c=c+this.G|0,u=u+this.H|0,this.set(r,n,i,o,s,a,c,u)}roundClean(){Ns(Jc)}destroy(){this.destroyed=!0,this.set(0,0,0,0,0,0,0,0),Ns(this.buffer)}}class wP extends yP{constructor(){super(32,gP)}}var Ay=TD(()=>new wP,vD(1));async function Ty(e,t,r=3600){return await new ke(e).setProtectedHeader({alg:"HS256"}).setIssuedAt().setExpirationTime(Math.floor(Date.now()/1000)+r).sign(new TextEncoder().encode(t))}async function SP(e,t){try{return(await V(e,new TextEncoder().encode(t))).payload}catch{return null}}var $oe=new Uint8Array([66,101,116,116,101,114,65,117,116,104,46,106,115,32,71,101,110,101,114,97,116,101,100,32,69,110,99,114,121,112,116,105,111,110,32,75,101,121]),Foe=()=>Date.now()/1000|0,AP="dir",TP="A256CBC-HS512";function Jh(e,t){return Sy(Ay,new TextEncoder().encode(e),new TextEncoder().encode(t),$oe,64)}function zoe(e){if(typeof e==="string")return e;let t=e.keys.get(e.currentVersion);if(!t)throw Error(`Secret version ${e.currentVersion} not found in keys`);return t}function _P(e){if(typeof e==="string")return[{version:0,value:e}];let t=[];for(let[r,n]of e.keys)t.push({version:r,value:n});if(e.legacySecret&&!t.some((r)=>r.value===e.legacySecret))t.push({version:-1,value:e.legacySecret});return t}async function vy(e,t,r,n=3600){let i=Jh(zoe(t),r),o=await It({kty:"oct",k:B(i)},"sha256");return await new Cr(e).setProtectedHeader({alg:AP,enc:TP,kid:o}).setIssuedAt().setExpirationTime(Foe()+n).setJti(crypto.randomUUID()).encrypt(i)}var bP={clockTolerance:15,keyManagementAlgorithms:[AP],contentEncryptionAlgorithms:[TP,"A256GCM"]};async function ky(e,t,r){if(!e)return null;let n=!1;try{n=ue(e).kid!==void 0}catch{return null}try{let i=_P(t),{payload:o}=await Er(e,async(s)=>{let a=s.kid;if(a!==void 0){for(let c of i){let u=Jh(c.value,r);if(a===await It({kty:"oct",k:B(u)},"sha256"))return u}throw Error("no matching decryption secret")}if(i.length===1)return Jh(i[0].value,r);return Jh(i[0].value,r)},bP);return o}catch{if(n)return null;let i=_P(t);if(i.length<=1)return null;for(let o=1;o<i.length;o++)try{let s=i[o],{payload:a}=await Er(e,Jh(s.value,r),bP);return a}catch{continue}return null}}function xl(e,t){if(!e||!t)return e;let r=Object.entries(t).filter(([,{returned:n}])=>n===!1).map(([n])=>n);return Object.entries(structuredClone(e)).filter(([n])=>!r.includes(n)).reduce((n,[i,o])=>({...n,[i]:o}),{})}var GA=new WeakMap;function Sa(e,t,r){let n=`${t}:${r}`;if(!GA.has(e))GA.set(e,new Map);let i=GA.get(e);if(i.has(n))return i.get(n);let o=r==="output"?ye(e)[t]?.fields??{}:{},s=t==="user"||t==="session"||t==="account"?e[t]?.additionalFields:void 0,a={...o,...s??{}};for(let c of e.plugins||[])if(c.schema&&c.schema[t])a={...a,...c.schema[t].fields};return i.set(n,a),a}function Xn(e,t){return xl(t,Sa(e,"user","output"))}function Qh(e,t){let r=Sa(e,"user","output"),n={};for(let i in r){let o=r[i];if(o.returned===!1)continue;if(i in t&&t[i]!==void 0)n[i]=t[i];else if(o.defaultValue!==void 0)n[i]=typeof o.defaultValue==="function"?o.defaultValue():o.defaultValue;else if(!o.required)n[i]=null}if("id"in t)n.id=t.id;return n}function Di(e,t){return xl(t,Sa(e,"session","output"))}function Ry(e,t){let{accessToken:r,refreshToken:n,idToken:i,accessTokenExpiresAt:o,refreshTokenExpiresAt:s,password:a,...c}=xl(t,Sa(e,"account","output"));return c}function Yu(e,t){let r=t.action||"create",n=t.fields,i=Object.create(null);for(let o in n){if(o in e){if(n[o].input===!1){if(n[o].defaultValue!==void 0){if(r!=="update"){i[o]=n[o].defaultValue;continue}}if(e[o])throw l.from("BAD_REQUEST",{...S.FIELD_NOT_ALLOWED,message:`${o} is not allowed to be set`});continue}if(n[o].validator?.input&&e[o]!==void 0){let s=n[o].validator.input["~standard"].validate(e[o]);if(s instanceof Promise)throw l.from("INTERNAL_SERVER_ERROR",S.ASYNC_VALIDATION_NOT_SUPPORTED);if("issues"in s&&s.issues)throw l.from("BAD_REQUEST",{...S.VALIDATION_ERROR,message:s.issues[0]?.message||"Validation Error"});i[o]=s.value;continue}if(n[o].transform?.input&&e[o]!==void 0){i[o]=n[o].transform?.input(e[o]);continue}i[o]=e[o];continue}if(n[o].defaultValue!==void 0&&r==="create"){if(typeof n[o].defaultValue==="function"){i[o]=n[o].defaultValue();continue}i[o]=n[o].defaultValue;continue}if(n[o].required&&r==="create")throw l.from("BAD_REQUEST",{...S.MISSING_FIELD,message:`${o} is required`})}return i}function Cl(e,t={},r){return Yu(t,{fields:Sa(e,"user","input"),action:r})}function Ol(e,t={},r){let n=Sa(e,"user","input"),i=Object.create(null);for(let o of Object.keys(t)){if(n[o]?.input===!1)continue;i[o]=t[o]}return Yu(i,{fields:n,action:r})}function vP(e,t){let r=Sa(e,"user","input");return Yu(t||{},{fields:r})}function kP(e,t){return Yu(t,{fields:Sa(e,"account","input")})}function Ny(e,t,r){return Yu(t,{fields:Sa(e,"session","input"),action:r})}function xy(e){let t=Sa(e,"session","input"),r={};for(let n in t)if(t[n].defaultValue!==void 0)r[n]=typeof t[n].defaultValue==="function"?t[n].defaultValue():t[n].defaultValue;return r}function xt(e,t){if(!t)return e;for(let r in t){let n=t[r]?.modelName;if(n)e[r].modelName=n;for(let i in e[r].fields){let o=t[r]?.fields?.[i];if(!o)continue;e[r].fields[i].fieldName=o}}return e}var ac=(e,t="ms")=>new Date(Date.now()+(t==="sec"?e*1000:e));var Woe=/^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|months?|mo|years?|yrs?|y)(?: (ago|from now))?$/i;function Hoe(e){let t=Woe.exec(e);if(!t||t[4]&&t[1])throw TypeError(`Invalid time string format: "${e}". Use formats like "7d", "30m", "1 hour", etc.`);let r=parseFloat(t[2]),n=t[3].toLowerCase(),i;switch(n){case"years":case"year":case"yrs":case"yr":case"y":i=r*31557600000;break;case"months":case"month":case"mo":i=r*2592000000;break;case"weeks":case"week":case"w":i=r*604800000;break;case"days":case"day":case"d":i=r*86400000;break;case"hours":case"hour":case"hrs":case"hr":case"h":i=r*3600000;break;case"minutes":case"minute":case"mins":case"min":case"m":i=r*60000;break;case"seconds":case"second":case"secs":case"sec":case"s":i=r*1000;break;default:throw TypeError(`Unknown time unit: "${n}"`)}if(t[1]==="-"||t[4]==="ago")return-i;return i}function Cy(e){return Math.round(Hoe(e)/1000)}import*as wo from"zod";var Voe=wo.looseObject({session:Ng.loose(),user:xg.loose(),updatedAt:wo.number(),version:wo.string().optional()}),Goe=wo.object({session:wo.record(wo.string(),wo.unknown()),expiresAt:wo.number(),signature:wo.string()});function Rt(e){let t=ti(e);if(t===null)return null;let r=Voe.safeParse(t);if(r.success)return r.data;return T.warn("Cookie cache payload failed schema validation",{issues:r.error.issues.map(({code:n,path:i})=>({code:n,path:i}))}),null}function RP(e){let t=Goe.safeParse(e);return t.success?t.data:null}function xP(e){if(e.indexOf("%")===-1)return e;try{return decodeURIComponent(e)}catch{return e}}var CP="__Secure-";function Oy(e){if(!e)return[];let t=[],r=0,n=0;while(n<e.length){if(e[n]===","){let o=n+1;while(o<e.length&&e[o]===" ")o++;while(o<e.length&&e[o]!=="="&&e[o]!==";"&&e[o]!==",")o++;if(o<e.length&&e[o]==="="){let s=e.slice(r,n).trim();if(s)t.push(s);r=n+1;while(r<e.length&&e[r]===" ")r++;n=r;continue}}n++}let i=e.slice(r).trim();if(i)t.push(i);return t}function Iy(e){let t=new Map;return Oy(e).forEach((r)=>{let[n,...i]=r.split(";").map((u)=>u.trim()),[o,...s]=(n||"").split("="),a=IP(s.join("="));if(!o)return;let c={value:xP(a)};i.forEach((u)=>{let[d,...f]=u.split("="),h=f.join("="),p=d.trim().toLowerCase();switch(p){case"max-age":c["max-age"]=h?parseInt(h.trim(),10):void 0;break;case"expires":c.expires=h?new Date(h.trim()):void 0;break;case"domain":c.domain=h?h.trim():void 0;break;case"path":c.path=h?h.trim():void 0;break;case"secure":c.secure=!0;break;case"httponly":c.httponly=!0;break;case"samesite":c.samesite=h?h.trim().toLowerCase():void 0;break;case"partitioned":c.partitioned=!0;break;default:c[p]=h?h.trim():!0;break}}),t.set(o,c)}),t}var OP=/^[\x21\x23-\x27\x2A\x2B\x2D\x2E\x30-\x39\x41-\x5A\x5E\x5F\x60\x61-\x7A\x7C\x7E]+$/,Koe=/^[\x20\x21\x23-\x3A\x3C-\x5B\x5D-\x7E]*$/;function IP(e){if(e.length<2||!e.startsWith('"')||!e.endsWith('"'))return e;return e.slice(1,-1)}function NP(e){let t=0,r=e.length;while(t<r){let n=e.charCodeAt(t);if(n!==32&&n!==9)break;t++}while(r>t){let n=e.charCodeAt(r-1);if(n!==32&&n!==9)break;r--}return t===0&&r===e.length?e:e.slice(t,r)}function Dy(e){let t=new Map;if(e.length<2)return t;for(let r of e.split(";")){let n=r.indexOf("=");if(n===-1)continue;let i=NP(r.slice(0,n)),o=IP(NP(r.slice(n+1)));if(OP.test(i)&&Koe.test(o))t.set(i,xP(o))}return t}function Ho(){let e=typeof globalThis<"u"&&globalThis.crypto;if(e&&typeof e.subtle==="object"&&e.subtle!=null)return e.subtle;throw Error("crypto.subtle must be defined")}var KA={name:"HMAC",hash:"SHA-256"},JA=async(e)=>{let t=typeof e==="string"?new TextEncoder().encode(e):e;return await Ho().importKey("raw",t,KA,!1,["sign","verify"])},DP=async(e,t,r)=>{try{let n=atob(e),i=new Uint8Array(n.length);for(let o=0,s=n.length;o<s;o++)i[o]=n.charCodeAt(o);return await Ho().verify(KA,r,i,new TextEncoder().encode(t))}catch{return!1}},Joe=async(e,t)=>{let r=await JA(t),n=await Ho().sign(KA.name,r,new TextEncoder().encode(e));return btoa(String.fromCharCode(...new Uint8Array(n)))},UP=async(e,t)=>{let r=await Joe(e,t);return e=`${e}.${r}`,e=encodeURIComponent(e),e};var Qoe=/^application\/([a-z0-9.+-]*\+)?json/i;async function PP(e,t){let r=e.headers.get("content-type")||"",n=r.toLowerCase();if(!e.body)return;if(t&&t.length>0){if(!t.some((i)=>{let o=n.split(";")[0].trim(),s=i.toLowerCase().trim();return o===s||o.includes(s)})){if(!n)throw new st(415,{message:`Content-Type is required. Allowed types: ${t.join(", ")}`,code:"UNSUPPORTED_MEDIA_TYPE"});throw new st(415,{message:`Content-Type "${r}" is not allowed. Allowed types: ${t.join(", ")}`,code:"UNSUPPORTED_MEDIA_TYPE"})}}if(Qoe.test(n))try{return await e.json()}catch(i){if(i instanceof SyntaxError)throw new st(400,{message:"Invalid JSON in request body",code:"BAD_REQUEST"});throw i}if(n.includes("application/x-www-form-urlencoded")){let i=await e.formData(),o={};return i.forEach((s,a)=>{o[a]=s.toString()}),o}if(n.includes("multipart/form-data")){let i=await e.formData(),o={};return i.forEach((s,a)=>{o[a]=s}),o}if(n.includes("text/plain"))return await e.text();if(n.includes("application/octet-stream"))return await e.arrayBuffer();if(n.includes("application/pdf")||n.includes("image/")||n.includes("video/"))return await e.blob();if(n.includes("application/stream")||e.body instanceof ReadableStream)return e.body;return await e.text()}function cc(e){return e instanceof st||e?.name==="APIError"}function LP(e){try{return e.includes("%")?decodeURIComponent(e):e}catch{return e}}async function MP(e){try{return{data:await e,error:null}}catch(t){return{data:null,error:t}}}function Uy(e){return e instanceof Request||Object.prototype.toString.call(e)==="[object Request]"}var Yoe={secure:"__Secure-",host:"__Host-"},Yh=(e,t)=>{if(!t)return e;if(t!=="secure"&&t!=="host")return;return Yoe[t]+e};function QA(e){if(typeof e!=="string")throw TypeError("argument str must be a string");let t=new Map,r=0;while(r<e.length){let n=e.indexOf("=",r);if(n===-1)break;let i=e.indexOf(";",r);if(i===-1)i=e.length;else if(i<n){r=e.lastIndexOf(";",n-1)+1;continue}let o=e.slice(r,n).trim();if(!t.has(o)){let s=e.slice(n+1,i).trim();if(s.codePointAt(0)===34)s=s.slice(1,-1);t.set(o,LP(s))}r=i+1}return t}function qP(e,t,r={}){let n=Yh(e,r.prefix)??e,i={...r},o=n.toLowerCase();if(o.startsWith("__host-"))i.secure=!0,i.path="/",i.domain=void 0;else if(o.startsWith("__secure-"))i.secure=!0;if(i.partitioned===!0||i.sameSite?.toLowerCase()==="none")i.secure=!0;return{name:n,value:t,options:i}}function BP({name:e,value:t,options:r}){let n=`${e}=${t}`;if(typeof r.maxAge==="number"&&r.maxAge>=0){if(r.maxAge>34560000)throw Error("Cookies Max-Age SHOULD NOT be greater than 400 days (34560000 seconds) in duration.");n+=`; Max-Age=${Math.floor(r.maxAge)}`}if(r.domain)n+=`; Domain=${r.domain}`;if(r.path)n+=`; Path=${r.path}`;if(r.expires){if(r.expires.getTime()-Date.now()>34560000000)throw Error("Cookies Expires SHOULD NOT be greater than 400 days (34560000 seconds) in the future.");n+=`; Expires=${r.expires.toUTCString()}`}if(r.httpOnly)n+="; HttpOnly";if(r.secure)n+="; Secure";if(r.sameSite)n+=`; SameSite=${r.sameSite.charAt(0).toUpperCase()+r.sameSite.slice(1)}`;if(r.partitioned)n+="; Partitioned";return n}var Xh=(e,t,r)=>(t=encodeURIComponent(t),BP(qP(e,t,r))),YA=async(e,t,r,n)=>(t=await UP(t,r),BP(qP(e,t,n)));async function $P(e,t={}){let r={body:t.body,query:t.query};if(e.body){let n=await e.body["~standard"].validate(t.body);if(n.issues)return{data:null,error:jP(n.issues,"body")};r.body=n.value}if(e.query){let n=await e.query["~standard"].validate(t.query);if(n.issues)return{data:null,error:jP(n.issues,"query")};r.query=n.value}if(e.requireHeaders&&!t.headers)return{data:null,error:{message:"Headers is required",issues:[]}};if(e.requireRequest&&!t.request)return{data:null,error:{message:"Request is required",issues:[]}};return{data:r,error:null}}function jP(e,t){return{message:e.map((r)=>`[${r.path?.length?`${t}.`+r.path.map((n)=>typeof n==="object"?n.key:n).join("."):t}] ${r.message}`).join("; "),issues:e}}var Zh=async(e,{options:t,path:r})=>{let n=new Headers,i=void 0,{data:o,error:s}=await $P(t,e);if(s)throw new lh(s.message,s.issues);let a=e.headers!==void 0?e.headers instanceof Headers?e.headers:new Headers(e.headers):("request"in e)&&Uy(e.request)?e.request.headers:null,c=a?.get("cookie"),u=c?QA(c):void 0,d={...e,body:o.body,query:o.query,path:e.path||r||"virtual:",context:"context"in e&&e.context?e.context:{},returned:void 0,headers:e?.headers,request:e?.request,params:"params"in e?e.params:void 0,method:e.method??(Array.isArray(t.method)?t.method[0]:t.method==="*"?"GET":t.method),setHeader:(f,h)=>{n.set(f,h)},getHeader:(f)=>{if(!a)return null;return a.get(f)},getCookie:(f,h)=>{let p=Yh(f,h);if(!p)return null;return u?.get(p)||null},getSignedCookie:async(f,h,p)=>{let g=Yh(f,p);if(!g)return null;let _=u?.get(g);if(!_)return null;let R=_.lastIndexOf(".");if(R<1)return null;let O=_.substring(0,R),I=_.substring(R+1);if(I.length!==44||!I.endsWith("="))return null;return await DP(I,O,await JA(h))?O:!1},setCookie:(f,h,p)=>{let g=Xh(f,h,p);return n.append("set-cookie",g),g},setSignedCookie:async(f,h,p,g)=>{let _=await YA(f,h,p,g);return n.append("set-cookie",_),_},redirect:(f)=>(n.set("location",f),new st("FOUND",void 0,n)),error:(f,h,p)=>new st(f,h,p),setStatus:(f)=>{i=f},json:(f,h)=>{if(!e.asResponse)return f;return{body:h?.body||f,routerResponse:h,_flag:"json"}},responseHeaders:n,get responseStatus(){return i}};for(let f of t.use||[]){let h=await f({...d,returnHeaders:!0,asResponse:!1});if(h.response)Object.assign(d.context,h.response);if(h.headers)h.headers.forEach((p,g)=>{d.responseHeaders.set(g,p)})}return d};function Xoe(e){if(e===void 0)return!1;let t=typeof e;if(t==="string"||t==="number"||t==="boolean"||t===null)return!0;if(t!=="object")return!1;if(Array.isArray(e))return!0;if(e.buffer)return!1;return e.constructor&&e.constructor.name==="Object"||typeof e.toJSON==="function"}function Zoe(e){let t=new WeakMap,r=new WeakMap,n=0,i=(o,s)=>{let a=s;while(a){if(a===o)return!0;a=t.get(a)}return!1};return JSON.stringify(e,function(o,s){if(typeof s==="bigint")return s.toString();if(typeof s==="object"&&s!==null){if(i(s,this))return`[Circular ref-${r.get(s)}]`;if(t.set(s,this),!r.has(s))r.set(s,n++)}return s})}function ese(e){if(!e||typeof e!=="object")return!1;return"_flag"in e&&e._flag==="json"}var tse=new Set(["host","user-agent","referer","from","expect","authorization","proxy-authorization","cookie","origin","accept-charset","accept-encoding","accept-language","if-match","if-none-match","if-modified-since","if-unmodified-since","if-range","range","max-forwards","connection","keep-alive","transfer-encoding","te","upgrade","trailer","proxy-connection","content-length"]);function XA(e){for(let t of tse)e.delete(t)}function Py(e,t){if(!t)return;for(let[r,n]of new Headers(t).entries())if(r.toLowerCase()==="set-cookie")e.append(r,n);else e.set(r,n)}function Hs(e,t){if(e instanceof Response){if(t?.headers){let i=new Headers(t.headers);XA(i),Py(e.headers,i)}return e}if(ese(e)){let{body:i,routerResponse:o}=e;if(o instanceof Response)return o;let s=new Headers;if(Py(s,o?.headers),Py(s,e.headers),t?.headers){let u=new Headers(t.headers);XA(u),Py(s,u)}s.set("Content-Type","application/json");let a=e.status??t?.status??o?.status,c=t?.statusText??o?.statusText;return new Response(JSON.stringify(i),{...o,headers:s,...a===void 0?{}:{status:a},...c===void 0?{}:{statusText:c}})}if(cc(e))return Hs(e.body,{status:t?.status??e.statusCode,statusText:e.status.toString(),headers:t?.headers||e.headers});let r=e,n=new Headers(t?.headers);if(XA(n),!e){if(e===null)r=JSON.stringify(null);n.set("content-type","application/json")}else if(typeof e==="string")r=e,n.set("Content-Type","text/plain");else if(e instanceof ArrayBuffer||ArrayBuffer.isView(e))r=e,n.set("Content-Type","application/octet-stream");else if(e instanceof Blob)r=e,n.set("Content-Type",e.type||"application/octet-stream");else if(e instanceof FormData)r=e;else if(e instanceof URLSearchParams)r=e,n.set("Content-Type","application/x-www-form-urlencoded");else if(e instanceof ReadableStream)r=e,n.set("Content-Type","application/octet-stream");else if(Xoe(e))r=Zoe(e),n.set("Content-Type","application/json");return new Response(r,{...t,headers:n})}function Qc(e,t,r){let n=typeof e==="string"?e:void 0,i=typeof t==="object"?t:e,o=typeof t==="function"?t:r;if((i.method==="GET"||i.method==="HEAD")&&i.body)throw new Tg("Body is not allowed with GET or HEAD methods");if(n&&/\/{2,}/.test(n))throw new Tg("Path cannot contain consecutive slashes");let s=async(...a)=>{let c=a[0]||{},{data:u,error:d}=await MP(Zh(c,{options:i,path:n}));if(d){if(!(d instanceof lh))throw d;if(i.onValidationError)await i.onValidationError({message:d.message,issues:d.issues});throw new st(400,{message:d.message,code:"VALIDATION_ERROR"})}let f=await o(u).catch(async(g)=>{if(cc(g)){let _=i.onAPIError;if(_)await _(g);if(c.asResponse)return g}throw g}),{responseHeaders:h,responseStatus:p}=u;return c.asResponse?Hs(f,p===void 0?{headers:h}:{headers:h,status:p}):c.returnHeaders?c.returnStatus?{headers:h,response:f,status:p}:{headers:h,response:f}:c.returnStatus?{response:f,status:p}:f};return s.options=i,s.path=n,s}function FP(e,t){return[...e??[],...t??[]]}Qc.create=(e)=>{function t(...r){if(r.length===3){let[o,s,a]=r;return Qc(o,{...s,use:FP(s.use,e?.use)},a)}let[n,i]=r;return Qc({...n,use:FP(n.use,e?.use)},i)}return t};function Yc(e,t){let r=async(n)=>{let i=n,o=typeof e==="function"?e:t,s=await Zh(i,{options:typeof e==="function"?{}:e,path:"/"});if(!o)throw Error("handler must be defined");try{let a=await o(s),c=s.responseHeaders;return i.returnHeaders?{headers:c,response:a}:a}catch(a){if(cc(a))Object.defineProperty(a,xc,{enumerable:!1,configurable:!0,get(){return s.responseHeaders}});throw a}};return r.options=typeof e==="function"?{}:e,r}Yc.create=(e)=>{function t(r,n){if(typeof r==="function")return Yc({use:e?.use},r);if(!n)throw Error("Middleware handler is required");return Yc({...r,method:"*",use:[...e?.use||[],...r.use||[]]},n)}return t};import{ZodObject as Ly,ZodOptional as ZA}from"zod";var eT={};function HP(e){switch(e.constructor.name){case"ZodString":return"string";case"ZodNumber":return"number";case"ZodBoolean":return"boolean";case"ZodObject":return"object";case"ZodArray":return"array";default:return"string"}}function zP(e){let t=[];if(e.metadata?.openapi?.parameters)return t.push(...e.metadata.openapi.parameters),t;if(e.query instanceof Ly)Object.entries(e.query.shape).forEach(([r,n])=>{if(n instanceof Ly)t.push({name:r,in:"query",schema:{type:HP(n),..."minLength"in n&&n.minLength?{minLength:n.minLength}:{},description:n.description}})});return t}function rse(e){if(e.metadata?.openapi?.requestBody)return e.metadata.openapi.requestBody;if(!e.body)return;if(e.body instanceof Ly||e.body instanceof ZA){let t=e.body.shape;if(!t)return;let r={},n=[];return Object.entries(t).forEach(([i,o])=>{if(o instanceof Ly){if(r[i]={type:HP(o),description:o.description},!(o instanceof ZA))n.push(i)}}),{required:e.body instanceof ZA?!1:e.body?!0:!1,content:{"application/json":{schema:{type:"object",properties:r,required:n}}}}}}function WP(e){return{"400":{content:{"application/json":{schema:{type:"object",properties:{message:{type:"string"}},required:["message"]}}},description:"Bad Request. Usually due to missing parameters, or invalid parameters."},"401":{content:{"application/json":{schema:{type:"object",properties:{message:{type:"string"}},required:["message"]}}},description:"Unauthorized. Due to missing or invalid authentication."},"403":{content:{"application/json":{schema:{type:"object",properties:{message:{type:"string"}}}}},description:"Forbidden. You do not have permission to access this resource or to perform this action."},"404":{content:{"application/json":{schema:{type:"object",properties:{message:{type:"string"}}}}},description:"Not Found. The requested resource was not found."},"429":{content:{"application/json":{schema:{type:"object",properties:{message:{type:"string"}}}}},description:"Too Many Requests. You have exceeded the rate limit. Try again later."},"500":{content:{"application/json":{schema:{type:"object",properties:{message:{type:"string"}}}}},description:"Internal Server Error. This is a problem with the server that you cannot fix."},...e}}async function tT(e,t){let r={schemas:{}};return Object.entries(e).forEach(([n,i])=>{let o=i.options;if(!i.path||o.metadata?.SERVER_ONLY)return;if(o.method==="GET")eT[i.path]={get:{tags:["Default",...o.metadata?.openapi?.tags||[]],description:o.metadata?.openapi?.description,operationId:o.metadata?.openapi?.operationId,security:[{bearerAuth:[]}],parameters:zP(o),responses:WP(o.metadata?.openapi?.responses)}};if(o.method==="POST"){let s=rse(o);eT[i.path]={post:{tags:["Default",...o.metadata?.openapi?.tags||[]],description:o.metadata?.openapi?.description,operationId:o.metadata?.openapi?.operationId,security:[{bearerAuth:[]}],parameters:zP(o),...s?{requestBody:s}:{requestBody:{content:{"application/json":{schema:{type:"object",properties:{}}}}}},responses:WP(o.metadata?.openapi?.responses)}}}}),{openapi:"3.1.1",info:{title:"Better Auth",description:"API Reference for your Better Auth Instance",version:"1.1.0"},components:r,security:[{apiKeyCookie:[]}],servers:[{url:t?.url}],tags:[{name:"Default",description:"Default endpoints that are included with Better Auth by default. These endpoints are not part of any plugin."}],paths:eT}}var rT=(e,t)=>`<!doctype html>
106
+ <html>
107
+ <head>
108
+ <title>Scalar API Reference</title>
109
+ <meta charset="utf-8" />
110
+ <meta
111
+ name="viewport"
112
+ content="width=device-width, initial-scale=1" />
113
+ </head>
114
+ <body>
115
+ <script
116
+ id="api-reference"
117
+ type="application/json">
118
+ ${JSON.stringify(e)}
119
+ </script>
120
+ <script>
121
+ var configuration = {
122
+ favicon: ${t?.logo?`data:image/svg+xml;utf8,${encodeURIComponent(t.logo)}`:void 0} ,
123
+ theme: ${t?.theme||"saturn"},
124
+ metaData: {
125
+ title: ${t?.title||"Open API Reference"},
126
+ description: ${t?.description||"Better Call Open API"},
127
+ }
128
+ }
129
+ document.getElementById('api-reference').dataset.configuration =
130
+ JSON.stringify(configuration)
131
+ </script>
132
+ <script src="https://cdn.jsdelivr.net/npm/@scalar/api-reference"></script>
133
+ </body>
134
+ </html>`;var By=(()=>{let e=function(){};return e.prototype=Object.create(null),Object.freeze(e.prototype),e})();function oT(){return{root:{key:""},static:new By}}function nse(e){let t=0,r=0;for(;t<e.length;t++){let s=e.charCodeAt(t);if(s===92)t++;else if(s===40)r++;else if(s===41&&r>0)r--;else if(s===123&&r===0)break}if(t>=e.length)return;let n=t+1;r=0;for(;n<e.length;n++){let s=e.charCodeAt(n);if(s===92)n++;else if(s===40)r++;else if(s===41&&r>0)r--;else if(s===125&&r===0)break}if(n>=e.length)return;let i=e[n+1],o=i==="?"||i==="+"||i==="*";return[e.slice(0,t),e.slice(t+1,n),e.slice(n+(o?2:1)),o?i:void 0]}function ise(e){if(!e.includes("{"))return;let t=nse(e);if(!t)return;let[r,n,i,o]=t;if(!o)return[r+n+i];if(o==="?")return[r+n+i,r+i];if(n.includes("/"))throw Error("unsupported group repetition across segments");return[`${r}(?:${n})${o}${i}`]}var ose="__rou3_unnamed_",sse="__rou3_esc_";function VP(e){return`${ose}${e}`}function ase(e){return/^(?!__rou3_|_\d)[A-Za-z_]\w*$/.test(e)?e:sse+e.replace(/[_-]/g,(t)=>t==="_"?"__":"_h")}function cse(e){if(e.charCodeAt(0)!==95)return e;if(e.startsWith("__rou3_esc_"))return e.slice(11).replace(/__|_h/g,(t)=>t==="__"?"_":"-");return e.startsWith("__rou3_unnamed_")?e.slice(15):e}function use(e){let t=0;for(let r=0;r<e.length;r++){let n=e.charCodeAt(r);if(n===92){r++;continue}if(n===40){t++;continue}if(n===41&&t>0){t--;continue}if(n===42&&t===0)return!0}return!1}function dse(e,t,r=VP){let n=0,i=t,o="";for(let s=0;s<e.length;s++){let a=e.charCodeAt(s);if(a===92){if(o+=e[s],s+1<e.length)o+=e[++s];continue}if(a===40){n++,o+=e[s];continue}if(a===41&&n>0){n--,o+=e[s];continue}if(a===42&&n===0){o+=`(?<${r(i++)}>[^/]*)`;continue}o+=e[s]}return[o,i]}function lse(e){if(!e.includes("\\"))return e;return e.replace(/\\([:(){}])/g,(t,r)=>"\uFFFD"+"ABCDE"[":(){}".indexOf(r)])}function fse(e){if(e.startsWith("**"))return 2;if(e==="*"||e.includes(":")||e.includes("(")||use(e))return 1;if(e==="\\*")return"*";if(e==="\\*\\*")return"**";if(!e.includes("\uFFFD"))return e;return e.replace(/\uFFFD([A-E])/g,(t,r)=>r==="A"?":":r==="B"?"(":r==="C"?")":r==="D"?"{":"}")}function hse(e){for(let t=0;t<e.length;t++){let r=e[t].charCodeAt(e[t].length-1);if(r!==63&&r!==43&&r!==42)continue;let n=e[t].match(/^(.*:[\w-]+(?:\([^)]*\))?)([?+*])$/);if(!n)continue;let i=e.slice(0,t),o=e.slice(t+1);if(n[2]==="?")return["/"+i.concat(n[1]).concat(o).join("/"),"/"+i.concat(o).join("/")];let s=n[1].match(/:([\w-]+)/)?.[1]||"_",a="/"+[...i,`**:${s}`,...o].join("/"),c="/"+[...i,...o].join("/");return n[2]==="+"?[a]:[a,c]}}function GP(e){if(!e.includes("/."))return e;let t=[];for(let r of e.split("/"))if(r===".")continue;else if(r===".."&&t.length>1)t.pop();else t.push(r);return t.join("/")||"/"}function sT(e){let t=e.split("/");if(t.shift(),t[t.length-1]==="")t.pop();return t}function pse(e){let t=sT(e);while(t[t.length-1]==="")t.pop();return t}function KP(e,t){let r=new By;for(let[n,i]of t){let o=n<0?e.slice(-(n+1)).join("/"):e[n];if(typeof i==="string")r[i]=o;else{let s=o.match(i);if(s)for(let a in s.groups)r[cse(a)]=s.groups[a]}}return r}function ep(e,t="",r,n){if(t=t.toUpperCase(),r.charCodeAt(0)!==47)r=`/${r}`;let i=ise(r);if(i){for(let p of i)ep(e,t,p,n);return}r=lse(r);let o=pse(r),s=hse(o);if(s){for(let p of s)ep(e,t,p,n);return}let a=e.root,c=0,u=[],d=[];for(let p=0;p<o.length;p++){let g=o[p],_=fse(g);if(_===2){if(!a.wildcard)a.wildcard={key:"**"};a=a.wildcard,u.push([-(p+1),g.split(":")[1]||"_",g.length===2]);break}if(_===1){if(!a.param)a.param={key:"*"};if(a=a.param,g==="*")u.push([p,String(c++),!0]);else if(g.includes("(")||g.includes(":",1)||!/^:[\w-]+$/.test(g)){let[O,I]=mse(g,c);c=I,d[p]=O,a.hasRegexParam=!0,u.push([p,O,!1])}else u.push([p,g.slice(1),!1]);continue}g=o[p]=_;let R=a.static?.[g];if(R)a=R;else{let O={key:g};if(!a.static)a.static=new By;a.static[g]=O,a=O}}let f=u.length>0,h=a.methods??=new By;if((h[t]??=[]).push({data:n||null,paramsRegexp:d,paramsMap:f?u:void 0}),!f)e.static["/"+o.join("/")]=a}function mse(e,t=0){let r=t,n="",i=0;for(let s=0;s<e.length;s++){let a=e.charCodeAt(s);if(a===40)i++;else if(a===41&&i>0)i--;else if(a===92&&i===0&&s+1<e.length){let c=e[s+1];if(c!==":"&&c!=="("&&c!=="*"&&c!=="\\"){n+="\uFFFE"+c,s++;continue}}else if(a===46&&i===0){n+="\\.";continue}n+=e[s]}[n,r]=dse(n,r);let o=n.replace(/:([\w-]+)(?:\(([^)]*)\))?/g,(s,a,c)=>`(?<${ase(a)}>${c||"[^/]+"})`).replace(/\((?![?<])/g,()=>`(?<${VP(r++)}>`).replace(/\uFFFE(.)/g,(s,a)=>/[.*+?^${}()|[\]\\]/.test(a)?`\\${a}`:a);return[new RegExp(`^${o}$`),r]}function JP(e,t="",r,n){if(n?.normalize)r=GP(r);if(r.charCodeAt(r.length-1)===47)r=r.slice(0,-1);let i=e.static[r];if(i&&i.methods){let a=i.methods[t]||i.methods[""];if(a!==void 0)return a[0]}let o=sT(r),s=nT(e.root,t,o,0);if(s===void 0)return;if(n?.params===!1)return s;return{data:s.data,params:s.paramsMap?KP(o,s.paramsMap):void 0}}function nT(e,t,r,n){if(n===r.length){if(e.methods){let o=My(e.methods,t,r,e.key==="*",!1);if(o)return o}return e.param?.methods&&My(e.param.methods,t,r,!0,!0)||e.wildcard?.methods&&My(e.wildcard.methods,t,r,!0,!0)||void 0}let i=r[n];if(e.static){let o=e.static[i];if(o){let s=nT(o,t,r,n+1);if(s)return s}}if(e.param){let o=nT(e.param,t,r,n+1);if(o)return o}if(e.wildcard&&e.wildcard.methods)return My(e.wildcard.methods,t,r,!0,!1)}function My(e,t,r,n,i){let o=e[t]||e[""];if(!o)return;let s=o[0];if(o.length===1&&s.paramsRegexp.length===0){if(!i)return s;let u=s.paramsMap;return u?.[u.length-1]?.[2]?s:void 0}let a,c=-1;for(let u of o){let d=u.paramsMap,f=d?.[d.length-1]?.[2];if(i&&!f)continue;let h=n&&d&&!f?1:0,p=u.paramsRegexp;for(let g=0;g<p.length;g++)if(p[g]){if(!p[g].test(r[g])){h=-1;break}h++}if(h>c)a=u,c=h}return a}function QP(e,t="",r,n){if(n?.normalize)r=GP(r);if(r.charCodeAt(r.length-1)===47)r=r.slice(0,-1);let i=sT(r),o=iT(e.root,t,i,0);if(n?.params===!1)return o;return o.map((s)=>({data:s.data,params:s.paramsMap?KP(i,s.paramsMap):void 0}))}function iT(e,t,r,n,i=[]){let o=r[n];if(e.wildcard&&e.wildcard.methods){let s=e.wildcard.methods[t]||e.wildcard.methods[""];if(s)if(n<r.length)qy(i,s,!0);else{let a=[];for(let c of s){let u=c.paramsMap;if(u?.[u.length-1]?.[2])a.push(c)}qy(i,a,!0)}}if(e.param){if(n<r.length){let s=i.length;if(iT(e.param,t,r,n+1,i),e.param.hasRegexParam){for(let a=i.length-1;a>=s;a--)if(i[a].paramsRegexp[n]?.test(o)===!1)i.splice(a,1)}}else if(e.param.methods){let s=e.param.methods[t]||e.param.methods[""];if(s){let a=[];for(let c of s){let u=c.paramsMap;if(u?.[u.length-1]?.[2])a.push(c)}qy(i,a,!0)}}}if(n<r.length){let s=e.static?.[o];if(s)iT(s,t,r,n+1,i)}if(n===r.length&&e.methods){let s=e.methods[t]||e.methods[""];if(s)qy(i,s,e.key==="*")}return i}function qy(e,t,r){if(t.length>1)t=t.map((n)=>{let i=0,{paramsRegexp:o,paramsMap:s}=n;for(let a=0;a<o.length;a++)if(o[a])i++;if(r&&s&&!s[s.length-1][2])i++;return[n,i]}).sort((n,i)=>n[1]-i[1]).map((n)=>n[0]);for(let n of t)e.push(n)}var aT=(e,t)=>{if(!t?.openapi?.disabled){let s={path:"/api/reference",...t?.openapi};e.openapi=Qc(s.path,{method:"GET"},async(a)=>{let c=await tT(e);return new Response(rT(c,s.scalar),{headers:{"Content-Type":"text/html"}})})}let r=oT(),n=oT();for(let s of Object.values(e)){if(!s.options||!s.path)continue;if(s.options?.metadata?.SERVER_ONLY)continue;let a=Array.isArray(s.options?.method)?s.options.method:[s.options?.method];for(let c of a)ep(r,c,s.path,s)}if(t?.routerMiddleware?.length)for(let{path:s,middleware:a}of t.routerMiddleware)ep(n,"*",s,a);let i=t?.basePath&&t.basePath!=="/"?t.basePath.replace(/\/+$/,""):"",o=async(s)=>{let a=new URL(s.url),c=a.pathname,u;if(i){if(!c.startsWith(`${i}/`))return new Response(null,{status:404,statusText:"Not Found"});u=c.slice(i.length)}else u=c;if(u.length===0||/\/{2,}/.test(u))return new Response(null,{status:404,statusText:"Not Found"});let d=JP(r,s.method,u);if(u.endsWith("/")!==d?.data?.path?.endsWith("/")&&!t?.skipTrailingSlashes)return new Response(null,{status:404,statusText:"Not Found"});if(!d?.data)return new Response(null,{status:404,statusText:"Not Found"});let f={};a.searchParams.forEach((p,g)=>{if(g in f)if(Array.isArray(f[g]))f[g].push(p);else f[g]=[f[g],p];else f[g]=p});let h=d.data;try{let p=h.options.metadata?.allowedMediaTypes||t?.allowedMediaTypes,g={path:u,method:s.method,headers:s.headers,params:d.params?{...d.params}:{},request:s,body:h.options.disableBody?void 0:await PP(h.options.cloneRequest?s.clone():s,p),query:f,_flag:"router",asResponse:!0,context:t?.routerContext},_=QP(n,"*",u);if(_?.length)for(let{data:R,params:O}of _){let I=await R({...g,params:O?{...O}:{},asResponse:!1});if(I instanceof Response)return I}return await h(g)}catch(p){if(t?.onError)try{let g=await t.onError(p,s);if(g instanceof Response)return Hs(g)}catch(g){if(cc(g))return Hs(g);throw g}if(t?.throwError)throw p;if(cc(p))return Hs(p);return console.error("# SERVER_ERROR: ",p),new Response(null,{status:500,statusText:"Internal Server Error"})}};return{handler:async(s)=>{let a=await t?.onRequest?.(s);if(a instanceof Response)return a;let c=Uy(a)?a:s,u=await o(c),d=await t?.onResponse?.(u,c);if(d instanceof Response)return d;return u},endpoints:e}};import*as Xu from"zod";var XP=4050,YP=100;function gse(e,t){return XP-Xh(e,"",{...t}).length}function ZP(e,t){let r=`${e}.`;if(!t.startsWith(r))return null;let n=t.slice(r.length),i=Number(n);if(!Number.isSafeInteger(i)||i<0||String(i)!==n)return null;return i}function yse(e,t){let r={},n=Dy(t.headers?.get("cookie")||"");for(let[i,o]of n){if(i!==e&&ZP(e,i)===null)continue;r[i]=o}return r}function wse(e,t,r,n){let i=gse(`${t.name}.${YP-1}`,t.attributes),o=i>0?Math.ceil(t.value.length/i):1/0;if(o<=1)return r[t.name]=t.value,[t];if(o>YP)return n.warn(`${e} cookie is too large to store even after chunking, so the cookie cache was skipped. Reduce the cached data size or avoid storing this data in cookies.`),[];let s=[];for(let a=0;a<o;a++){let c=`${t.name}.${a}`,u=a*i,d=t.value.substring(u,u+i);s.push({...t,name:c,value:d}),r[c]=d}return n.debug(`CHUNKING_${e.toUpperCase()}_COOKIE`,{message:`${e} cookie exceeds the ${XP} byte limit and was split into ${o} chunks.`,valueSize:t.value.length,chunkCount:o,chunkSizes:s.map((a)=>a.value.length)}),s}function _se(e,t){let r={};for(let n in e)r[n]={name:n,value:"",attributes:{...t,maxAge:0}};return r}var e1=(e)=>(t,r,n)=>{let i=yse(t,n),o=n.context.logger,s=()=>{let a=_se(i,r);for(let c in i)delete i[c];return a};return{chunk(a,c){let u=s(),d=wse(e,{name:t,value:a,attributes:{...r,...c}},i,o);for(let f of d)u[f.name]=f;return Object.values(u)},clean(){return Object.values(s())},setCookies(a){for(let c of a)n.setCookie(c.name,c.value,c.attributes)}}},tp=e1("Session"),jy=e1("Account");function $y(e,t){let r=e.getCookie(t);if(r)return r;let n=[],i=e.headers?.get("cookie");if(!i)return null;for(let[o,s]of Dy(i)){let a=ZP(t,o);if(a===null)continue;n.push({index:a,value:s})}if(n.length>0)return n.sort((o,s)=>o.index-s.index),n.map((o)=>o.value).join("");return null}async function uc(e,t){let r=e.context.authCookies.accountData,n={maxAge:300,...r.attributes},i=await vy(t,e.context.secretConfig,"better-auth-account",n.maxAge),o=jy(r.name,n,e);o.setCookies(o.chunk(i,n))}async function Fy(e){let t=$y(e,e.context.authCookies.accountData.name);if(t){let r=ti(await ky(t,e.context.secretConfig,"better-auth-account"));if(r)return r}return null}var t1=Xu.optional(Xu.object({disableCookieCache:Xu.coerce.boolean().meta({description:"Disable cookie cache and fetch session from database"}).optional(),disableRefresh:Xu.coerce.boolean().meta({description:"Disable session refresh. Useful for checking session status, without updating the session"}).optional()}));var cT=new Map,bse=new TextEncoder,r1={decode:(e,t="utf-8")=>{if(!cT.has(t))cT.set(t,new TextDecoder(t));return cT.get(t).decode(e)},encode:(e)=>bse.encode(e)};var uT=(e="SHA-256",t="none")=>{let r={importKey:async(n,i)=>Ho().importKey("raw",Fu(n),{name:"HMAC",hash:{name:e}},!1,[i]),sign:async(n,i)=>{if(typeof n==="string")n=await r.importKey(n,"sign");let o=await Ho().sign("HMAC",n,Fu(i));if(t==="hex")return Eh.encode(o);if(t==="base64")return fe.encode(o);if(t==="base64url"||t==="base64urlnopad")return po.encode(o,{padding:t!=="base64urlnopad"});return o},verify:async(n,i,o)=>{if(typeof n==="string")n=await r.importKey(n,"verify");if(t==="hex")o=typeof o==="string"?Eh.toBytes(o):o;if(t==="base64"||t==="base64url"||t==="base64urlnopad")o=await fe.decode(o);return Ho().verify("HMAC",n,Fu(o),Fu(i))}};return r};function dr(e){let t=typeof e.baseURL==="string"?e.baseURL:void 0,r=typeof e.baseURL==="object"&&e.baseURL!==null?e.baseURL.protocol:void 0,n=(e.advanced?.useSecureCookies!==void 0?e.advanced?.useSecureCookies:r==="https"?!0:r==="http"?!1:t?t.startsWith("https://"):ut)?CP:"",i=!!e.advanced?.crossSubDomainCookies?.enabled,o=i?e.advanced?.crossSubDomainCookies?.domain||(t?new URL(t).hostname:void 0):void 0;if(i&&!o&&!Ee(e.baseURL))throw new y("baseURL is required when crossSubdomainCookies are enabled.");function s(a,c={}){let u=e.advanced?.cookiePrefix||"better-auth",d=e.advanced?.cookies?.[a]?.name||`${u}.${a}`,f=e.advanced?.cookies?.[a]?.attributes??{};return{name:`${n}${d}`,attributes:{secure:!!n,sameSite:"lax",path:"/",httpOnly:!0,...i?{domain:o}:{},...e.advanced?.defaultCookieAttributes,...c,...f}}}return s}function Mr(e){let t=dr(e),r=t("session_token",{maxAge:e.session?.expiresIn||Cy("7d")}),n=t("session_data",{maxAge:e.session?.cookieCache?.maxAge||300}),i=t("account_data",{maxAge:e.session?.cookieCache?.maxAge||300}),o=t("dont_remember");return{sessionToken:{name:r.name,attributes:r.attributes},sessionData:{name:n.name,attributes:n.attributes},dontRememberToken:{name:o.name,attributes:o.attributes},accountData:{name:i.name,attributes:i.attributes}}}async function rp(e,t,r){if(!e.context.options.session?.cookieCache?.enabled)return;let n=xl(t.session,e.context.options.session?.additionalFields),i=Xn(e.context.options,t.user),o=e.context.options.session?.cookieCache?.version,s="1";if(o){if(typeof o==="string")s=o;else if(typeof o==="function"){let p=o(t.session,t.user);s=bt(p)?await p:p}}let a={session:n,user:i,updatedAt:Date.now(),version:s},c={...e.context.authCookies.sessionData.attributes,maxAge:r?void 0:e.context.authCookies.sessionData.attributes.maxAge},u=ac(c.maxAge||60,"sec").getTime(),d=e.context.options.session?.cookieCache?.strategy||"compact",f;if(d==="jwe")f=await vy(a,e.context.secretConfig,"better-auth-session",c.maxAge||300);else if(d==="jwt"){let p=e.context.sessionConfig.cookieCacheSigner;f=p?await p.sign(e,a,c.maxAge||300):await Ty(a,e.context.secret,c.maxAge||300)}else f=po.encode(JSON.stringify({session:a,expiresAt:u,signature:await uT("SHA-256","base64urlnopad").sign(e.context.secret,JSON.stringify({...a,expiresAt:u}))}),{padding:!1});let h=tp(e.context.authCookies.sessionData.name,c,e);if(h.setCookies(h.chunk(f,c)),e.context.options.account?.storeAccountCookie&&!Sse(e,e.context.authCookies.accountData.name)){let p=await Fy(e);if(p)if(!Ey(e.context.options)||p.userId===t.user.id)await uc(e,p);else{cs(e,e.context.authCookies.accountData);let g=jy(e.context.authCookies.accountData.name,e.context.authCookies.accountData.attributes,e);g.setCookies(g.clean())}}}async function n1(e,t){let r=e.context.options.session?.cookieCache?.strategy||"compact";if(r==="jwe"){let o=await ky(t,e.context.secretConfig,"better-auth-session"),s=Rt(o);if(!s)return null;return{session:s,expiresAt:o?.exp?o.exp*1000:Date.now()}}if(r==="jwt"){let o=e.context.sessionConfig.cookieCacheSigner;if(o){let c=await o.verify(e,t);if(!c)return null;return{session:c.payload,expiresAt:c.expiresAt}}let s=await SP(t,e.context.secret),a=Rt(s);if(!a)return null;return{session:a,expiresAt:s?.exp?s.exp*1000:Date.now()}}let n=RP(ti(r1.decode(po.decode(t))));if(!n)return null;if(!await uT("SHA-256","base64urlnopad").verify(e.context.secret,JSON.stringify({...n.session,expiresAt:n.expiresAt}),n.signature))return null;let i=Rt(n.session);return i?{session:i,expiresAt:n.expiresAt}:null}async function ki(e,t,r,n){let i=await e.getSignedCookie(e.context.authCookies.dontRememberToken.name,e.context.secret);r=r!==void 0?r:!!i;let o=e.context.authCookies.sessionToken.attributes,s=r?void 0:e.context.sessionConfig.expiresIn;if(await e.setSignedCookie(e.context.authCookies.sessionToken.name,t.session.token,e.context.secret,{...o,maxAge:s,...n}),r)await e.setSignedCookie(e.context.authCookies.dontRememberToken.name,"true",e.context.secret,e.context.authCookies.dontRememberToken.attributes);await rp(e,t,r),e.context.setNewSession(t)}function Ese(e,t){let r=e,n=new Set;if(r.responseHeaders)n.add(r.responseHeaders);if(r.context?.responseHeaders)n.add(r.context.responseHeaders);let i=`${t}=`,o=`${t}.`;for(let s of n){let a=typeof s.getSetCookie==="function"?s.getSetCookie():Oy(s.get("set-cookie")||"");if(!a.length)continue;let c=a.filter((u)=>!u.startsWith(i)&&!u.startsWith(o));if(c.length===a.length)continue;s.delete("set-cookie");for(let u of c)s.append("set-cookie",u)}}function Sse(e,t){let r=e,n=new Set;if(r.responseHeaders)n.add(r.responseHeaders);if(r.context?.responseHeaders)n.add(r.context.responseHeaders);let i=`${t}=`,o=`${t}.`;for(let s of n)if((typeof s.getSetCookie==="function"?s.getSetCookie():Oy(s.get("set-cookie")||"")).some((a)=>a.startsWith(i)||a.startsWith(o)))return!0;return!1}function cs(e,t){Ese(e,t.name),e.setCookie(t.name,"",{...t.attributes,maxAge:0})}function Vo(e,t){if(cs(e,e.context.authCookies.sessionToken),cs(e,e.context.authCookies.sessionData),e.context.options.account?.storeAccountCookie){cs(e,e.context.authCookies.accountData);let i=jy(e.context.authCookies.accountData.name,e.context.authCookies.accountData.attributes,e),o=i.clean();i.setCookies(o)}if(e.context.oauthConfig.storeStateStrategy==="cookie")cs(e,e.context.createAuthCookie("oauth_state"));let r=tp(e.context.authCookies.sessionData.name,e.context.authCookies.sessionData.attributes,e),n=r.clean();if(r.setCookies(n),!t)cs(e,e.context.authCookies.dontRememberToken)}function dT(e){if(!e?.method)throw new l("FORBIDDEN",{code:"validation_source_missing",message:"User validation source is required"});if(e.method==="oauth"&&!e.oauth?.providerId)throw new l("FORBIDDEN",{code:"validation_source_missing",message:"OAuth user validation source requires oauth.providerId"});if((e.method==="sso-oidc"||e.method==="sso-saml")&&!e.sso?.providerId)throw new l("FORBIDDEN",{code:"validation_source_missing",message:"SSO user validation source requires sso.providerId"})}async function Il(e,t){let r=e.context.options.user?.validateUserInfo;if(!r)return;dT(t.source);let n;try{n=await r(t,e)}catch(i){throw e.context.logger.error("validateUserInfo callback threw",i),new l("FORBIDDEN",{code:"validation_failed",message:"User validation failed"})}if(n?.error)throw new l("FORBIDDEN",{code:n.error,message:n.errorDescription||n.error})}function Ce(e,t){return{digest:async(r)=>{let n=Fu(r),i=await Ho().digest(e,n);if(t==="hex")return Array.from(new Uint8Array(i)).map((o)=>o.toString(16).padStart(2,"0")).join("");if(t==="base64"||t==="base64url"||t==="base64urlnopad"){if(t.includes("url"))return po.encode(i,{padding:t!=="base64urlnopad"});return fe.encode(i)}return i}}}var Ase=async(e)=>{let t=await Ce("SHA-256").digest(new TextEncoder().encode(e));return po.encode(new Uint8Array(t),{padding:!1})};async function Zu(e,t){if(!t||t==="plain")return e;if(t==="hashed")return Ase(e);if(typeof t==="object"&&"hash"in t)return t.hash(e);return e}function ed(e,t){if(!t)return;if(typeof t==="object"&&"default"in t){if(t.overrides){for(let[r,n]of Object.entries(t.overrides))if(e.startsWith(r))return n}return t.default}return t}var Xc,i1=!1;function Tse(){try{return globalThis.process?.getBuiltinModule?.("node:async_hooks")?.AsyncLocalStorage}catch{return}}async function Dl(){if(Xc)return Xc;let e=Tse();if(e)return Xc??=e,Xc;try{let{AsyncLocalStorage:t}=await import("async_hooks");return Xc??=t,Xc}catch(t){let r=globalThis.AsyncLocalStorage;if(typeof r==="function")return Xc??=r,Xc;if(typeof window<"u")throw Error("getAsyncLocalStorage is only available in server code");if(!i1)i1=!0,console.warn("[better-auth] Warning: AsyncLocalStorage is not available in this environment. Some features may not work as expected."),console.warn("[better-auth] Please read more about this warning at https://better-auth.com/docs/installation#mount-handler"),console.warn("[better-auth] If you are using Cloudflare Workers, please see: https://developers.cloudflare.com/workers/configuration/compatibility-flags/#nodejs-compatibility-flag");throw t}}var vse=()=>Ha().context.endpointContextAsyncStorage,kse=async()=>{let e=vse();if(e)return e;let t=await Dl(),r=Ha().context;return r.endpointContextAsyncStorage??=new t};function Vs(){return Ig()}function pr(){let e=Vs();if(!e)throw Error("No auth context found. Please make sure you are calling this function within a `runWithEndpointContext` callback.");return e}async function Ul(e,t){return(await kse()).run(e,t)}var fT=async()=>{let e=Ha(),t=e.context.requestStateAsyncStorage;if(t)return t;let r=await Dl();return e.context.requestStateAsyncStorage??=new r,e.context.requestStateAsyncStorage};async function hT(){return(await fT()).getStore()!==void 0}async function lT(){let e=(await fT()).getStore();if(!e)throw Error("No request state found. Please make sure you are calling this function within a `runWithRequestState` callback.");return e}async function pT(e,t){return(await fT()).run(e,t)}function Zc(e){let t=Object.freeze({});return{get ref(){return t},async get(){let r=await lT();if(!r.has(t)){let n=await e();return r.set(t,n),n}return r.get(t)},async set(r){(await lT()).set(t,r)}}}var zy=async()=>{let e=Ha(),t=e.context.adapterAsyncStorage;if(t)return t;let r=await Dl();return e.context.adapterAsyncStorage??=new r,e.context.adapterAsyncStorage};var $r=async(e)=>zy().then((t)=>t.getStore()?.adapter||e).catch(()=>e),sn=async(e,t)=>{let r=!1;return zy().then(async(n)=>{r=!0;let i=[],o,s,a=!1;try{o=await n.run({adapter:e,pendingHooks:i,isTransactionActive:!1},t)}catch(c){s=c,a=!0}for(let c of i)await c();if(a)throw s;return o}).catch((n)=>{if(!r)return t();throw n})},Co=async(e,t,r)=>{let n=!1;return zy().then(async(i)=>{if(n=!0,i.getStore()?.isTransactionActive)return t();let o=lr(e)?.();if(o)await o;let s=[],a,c,u=!1;try{a=await e.transaction(async(f)=>(s=[],i.run({adapter:f,pendingHooks:s,isTransactionActive:!0},t)))}catch(f){u=!0,c=f}let d=async(f)=>{for(let h of s)try{await h()}catch(p){if(!r?.onAfterCommitHookError){if(f==="throw")throw p;try{T.error("Failed to run an after-commit hook for work that could not roll back",p)}catch{}continue}try{await r.onAfterCommitHookError(p)}catch{}}};if(u){if(e.options?.adapterConfig.transaction===!1)await d("log");throw c}return await d("throw"),a}).catch((i)=>{if(!n)return t();throw i})},_o=async(e,t)=>{let r=async()=>{try{await e()}catch(o){if(!t?.onError)throw o;await t.onError(o)}},n;try{n=await zy()}catch{return r()}let i=n.getStore();if(!i?.isTransactionActive)return r();i.pendingHooks.push(r)};function Wy(e,t){let r=ss(t.options),n=t.hooks;async function i(d,f,h){let p=Vs(),g=d;for(let{source:R,hooks:O}of n){let I=O[f]?.create?.before;if(I){let Ne=await r(`db create.before ${f}`,{[Si]:"create.before",[Yn]:f,[Ai]:R},()=>I(g,p));if(Ne===!1)return null;if(typeof Ne==="object"&&"data"in Ne)g={...g,...Ne.data}}}let _=null;if(!h||h.executeMainFn)_=await(await $r(e)).create({model:f,data:g,forceAllowId:!0});if(h?.fn)_=await h.fn(_??g);for(let{source:R,hooks:O}of n){let I=O[f]?.create?.after;if(I)await _o(async()=>{await r(`db create.after ${f}`,{[Si]:"create.after",[Yn]:f,[Ai]:R},()=>I(_,p))})}return _}async function o(d,f,h,p){let g=Vs(),_=d;for(let{source:I,hooks:Ne}of n){let k=Ne[h]?.update?.before;if(k){let j=await r(`db update.before ${h}`,{[Si]:"update.before",[Yn]:h,[Ai]:I},()=>k(d,g));if(j===!1)return null;if(typeof j==="object"&&"data"in j)_={..._,...j.data}}}let R=p?await p.fn(_):null,O=!p||p.executeMainFn?await(await $r(e)).update({model:h,update:_,where:f}):R;for(let{source:I,hooks:Ne}of n){let k=Ne[h]?.update?.after;if(k)await _o(async()=>{await r(`db update.after ${h}`,{[Si]:"update.after",[Yn]:h,[Ai]:I},()=>k(O,g))})}return O}async function s(d,f,h,p){let g=Vs(),_=d;for(let{source:I,hooks:Ne}of n){let k=Ne[h]?.update?.before;if(k){let j=await r(`db updateMany.before ${h}`,{[Si]:"updateMany.before",[Yn]:h,[Ai]:I},()=>k(d,g));if(j===!1)return null;if(typeof j==="object"&&"data"in j)_={..._,...j.data}}}let R=p?await p.fn(_):null,O=!p||p.executeMainFn?await(await $r(e)).updateMany({model:h,update:_,where:f}):R;for(let{source:I,hooks:Ne}of n){let k=Ne[h]?.update?.after;if(k)await _o(async()=>{await r(`db updateMany.after ${h}`,{[Si]:"updateMany.after",[Yn]:h,[Ai]:I},()=>k(O,g))})}return O}async function a(d,f,h){let p=Vs(),g=null;try{g=(await(await $r(e)).findMany({model:f,where:d,limit:1}))[0]||null}catch{}if(g)for(let{source:O,hooks:I}of n){let Ne=I[f]?.delete?.before;if(Ne){if(await r(`db delete.before ${f}`,{[Si]:"delete.before",[Yn]:f,[Ai]:O},()=>Ne(g,p))===!1)return null}}let _=h?await h.fn(d):null,R=(!h||h.executeMainFn)&&g?await(await $r(e)).delete({model:f,where:d}):_;if(g)for(let{source:O,hooks:I}of n){let Ne=I[f]?.delete?.after;if(Ne)await _o(async()=>{await r(`db delete.after ${f}`,{[Si]:"delete.after",[Yn]:f,[Ai]:O},()=>Ne(g,p))})}return R}async function c(d,f,h){let p=Vs(),g=[];try{g=await(await $r(e)).findMany({model:f,where:d})}catch{}for(let O of g)for(let{source:I,hooks:Ne}of n){let k=Ne[f]?.delete?.before;if(k){if(await r(`db delete.before ${f}`,{[Si]:"delete.before",[Yn]:f,[Ai]:I},()=>k(O,p))===!1)return null}}let _=h?await h.fn(d):null,R=!h||h.executeMainFn?await(await $r(e)).deleteMany({model:f,where:d}):_;for(let O of g)for(let{source:I,hooks:Ne}of n){let k=Ne[f]?.delete?.after;if(k)await _o(async()=>{await r(`db delete.after ${f}`,{[Si]:"delete.after",[Yn]:f,[Ai]:I},()=>k(O,p))})}return R}async function u(d,f,h,p){let g=Vs(),_=n.flatMap(({source:I,hooks:Ne})=>{let k=Ne[d]?.delete?.before;return k?[{source:I,fn:k}]:[]}),R=p??null;if(_.length){if(!R)try{R=(await(await $r(e)).findMany({model:d,where:f,limit:1}))[0]||null}catch{}if(R){for(let{source:I,fn:Ne}of _)if(await r(`db delete.before ${d}`,{[Si]:"delete.before",[Yn]:d,[Ai]:I},()=>Ne(R,g))===!1)return null}}let O=await h();if(!O)return null;for(let{source:I,hooks:Ne}of n){let k=Ne[d]?.delete?.after;if(k)await _o(async()=>{await r(`db delete.after ${d}`,{[Si]:"delete.after",[Yn]:d,[Ai]:I},()=>k(O,g))})}return O}return{createWithHooks:i,updateWithHooks:o,updateManyWithHooks:s,deleteWithHooks:a,deleteManyWithHooks:c,consumeOneWithHooks:u}}import*as td from"zod";var Rse=td.ipv4(),Nse=td.ipv6();function mT(e){return np(e)||gT(e)}function np(e){return td.validate(Rse,e)}function gT(e){return td.validate(Nse,e)}function o1(e){let t=e.toLowerCase();if(t.startsWith("::ffff:")){let n=t.substring(7);if(np(n))return n}let r=e.split(":");if(r.length===7&&r[5]?.toLowerCase()==="ffff"){let n=r[6];if(n&&np(n))return n}if(t.includes("::ffff:")||t.includes(":ffff:")){let n=yT(e);if(n.length===8&&n[0]==="0000"&&n[1]==="0000"&&n[2]==="0000"&&n[3]==="0000"&&n[4]==="0000"&&n[5]==="ffff"&&n[6]&&n[7])return`${Number.parseInt(n[6].substring(0,2),16)}.${Number.parseInt(n[6].substring(2,4),16)}.${Number.parseInt(n[7].substring(0,2),16)}.${Number.parseInt(n[7].substring(2,4),16)}`}return null}function yT(e){if(e.includes("::")){let t=e.split("::"),r=t[0]?t[0].split(":"):[],n=t[1]?t[1].split(":"):[],i=8-r.length-n.length,o=Array(i).fill("0000"),s=r.map((c)=>c.padStart(4,"0")),a=n.map((c)=>c.padStart(4,"0"));return[...s,...o,...a]}return e.split(":").map((t)=>t.padStart(4,"0"))}function xse(e,t){let r=yT(e);if(t!==void 0&&t<128){let n=Math.max(0,Math.floor(t));return r.map((i)=>{if(n<=0)return"0000";if(n>=16)return n-=16,i;let o=Number.parseInt(i,16)&(65535<<16-n&65535);return n=0,o.toString(16).padStart(4,"0")}).join(":").toLowerCase()}return r.join(":").toLowerCase()}function Hy(e,t={}){if(np(e))return e.toLowerCase();if(!gT(e))return e.toLowerCase();let r=o1(e);if(r)return r.toLowerCase();return xse(e,t.ipv6Subnet??64)}function s1(e){if(np(e))return Uint8Array.from(e.split(".").map((i)=>Number(i)));if(!gT(e))return null;let t=o1(e);if(t)return Uint8Array.from(t.split(".").map((i)=>Number(i)));let r=yT(e),n=new Uint8Array(16);for(let i=0;i<8;i++){let o=Number.parseInt(r[i]??"0",16);n[i*2]=o>>8&255,n[i*2+1]=o&255}return n}var Cse=/^\d+$/;function a1(e){let t=e.lastIndexOf("/"),r=s1(t===-1?e:e.slice(0,t));if(!r)return null;let n=r.length*8;if(t===-1)return{bytes:r,prefix:n};let i=e.slice(t+1);if(!Cse.test(i))return null;let o=Number(i);return o<=n?{bytes:r,prefix:o}:null}function Ose(e,t){if(e.length!==t.bytes.length)return!1;let r=t.prefix;for(let n=0;n<e.length&&r>0;n++){let i=r>=8?8:r,o=i===8?255:255<<8-i&255;if(((e[n]??0)&o)!==((t.bytes[n]??0)&o))return!1;r-=8}return!0}function hn(e){return e.filter((t)=>a1(t)===null)}function Ise(e,t={}){let r=e.split(",").map((o)=>o.trim()).filter(Boolean);if(r.length===0)return null;let n=(t.trustedProxies??[]).map(a1).filter((o)=>o!==null);if(n.length>0){for(let o=r.length-1;o>=0;o--){let s=r[o],a=s?s1(s):null;if(!s||!a)return null;if(n.some((c)=>Ose(a,c)))continue;return Hy(s,{ipv6Subnet:t.ipv6Subnet})}return null}if(r.length!==1)return null;let i=r[0];if(!i||!mT(i))return null;return Hy(i,{ipv6Subnet:t.ipv6Subnet})}var Dse="127.0.0.1",Use=["x-forwarded-for"];function Vy(e,t){if(t.advanced?.ipAddress?.disableIpTracking)return null;let r="headers"in e?e.headers:e,n=t.advanced?.ipAddress?.ipAddressHeaders||Use;for(let i of n){let o="get"in r?r.get(i):r[i];if(typeof o==="string"){let s=Ise(o,{ipv6Subnet:t.advanced?.ipAddress?.ipv6Subnet,trustedProxies:t.advanced?.ipAddress?.trustedProxies});if(s)return s}}if(Ye()||$u())return Dse;return null}function c1(e,t){return`${e}|${t}`}function Aa(e,t=Date.now()){let r=typeof e==="number"?e:e.getTime();return Math.max(Math.floor((r-t)/1000),0)}var kt=(e,t)=>{let{logger:r,options:n}=t,i=n.secondaryStorage,o=new Map,s=n.session?.expiresIn||604800,a=!!i&&n.session?.storeSessionInDatabase===!0&&n.session?.preserveSessionInDatabase!==!0,{createWithHooks:c,updateWithHooks:u,updateManyWithHooks:d,deleteWithHooks:f,deleteManyWithHooks:h,consumeOneWithHooks:p}=Wy(e,t),g=(k)=>{let j=[...k,{field:"expiresAt",value:new Date,operator:"gt"}];return h(j,"session",{fn:async()=>{await(await $r(e)).updateMany({model:"session",where:j,update:{expiresAt:new Date}})},executeMainFn:!1})};async function _(k){if(!i)return;let j=await i.get(`active-sessions-${k.id}`);if(!j)return;let re=Date.now(),Oe=(ti(j)||[]).filter((ne)=>ne.expiresAt>re);await Promise.all(Oe.map(async({token:ne})=>{let M=await i.get(ne);if(!M)return;let F=ti(M);if(!F)return;let ce=Aa(F.session.expiresAt,re);await i.set(ne,JSON.stringify({session:F.session,user:k}),Math.floor(ce))}))}async function R(k){if(!i)return[];let j=await i.get(`active-sessions-${k}`);return j?ti(j)||[]:[]}async function O(k,j){if(!i)return;let re=new Set(j.map((de)=>de.token));for(let{token:de}of j)await i.delete(de);let Oe=`active-sessions-${k}`,ne=await R(k),M=Date.now(),F=ne.filter((de)=>de.expiresAt>M&&!re.has(de.token));F.sort((de,pe)=>de.expiresAt-pe.expiresAt);let ce=F.at(-1)?.expiresAt;if(ce){await i.set(Oe,JSON.stringify(F),Aa(ce,M));return}await i.delete(Oe)}async function I(k,j){if(!i)return;let re=j??await R(k);await _o(()=>O(k,re),{onError(Oe){r.error("Failed to delete committed user sessions from secondary storage",Oe)}})}async function Ne(k,j){let re=o.get(k)??Promise.resolve(),Oe,ne=new Promise((F)=>{Oe=F}),M=re.catch(()=>{}).then(()=>ne);o.set(k,M),await re.catch(()=>{});try{return await j()}finally{if(Oe(),o.get(k)===M)o.delete(k)}}return{createOAuthUser:async(k,j)=>Co(e,async()=>{let re=await c({createdAt:new Date,updatedAt:new Date,...k,email:k.email?.toLowerCase()},"user",void 0);if(!re)throw new l("BAD_REQUEST",{message:"Failed to create user"});return{user:re,account:await c({...j,userId:re.id,createdAt:new Date,updatedAt:new Date},"account",void 0)}}),createUser:async(k,j)=>{let re={createdAt:new Date,updatedAt:new Date,...k,email:k.email?.toLowerCase()};if(n.user?.validateUserInfo){let Oe={...j,action:"create-user"};dT(Oe);let ne;try{ne=pr()}catch(M){throw r.error("Unable to run validateUserInfo: missing endpoint context",M),new l("FORBIDDEN",{code:"validation_context_missing",message:"User validation requires an endpoint context"})}await Il(ne,{user:re,source:Oe})}return await c(re,"user",void 0)},createAccount:async(k)=>await c({createdAt:new Date,updatedAt:new Date,...k},"account",void 0),listSessions:async(k,j)=>{if(a)return(await(await $r(e)).findMany({model:"session",where:[{field:"userId",value:k},{field:"expiresAt",value:new Date,operator:"gt"}]})).map((re)=>Di(t.options,re));if(i){let re=await i.get(`active-sessions-${k}`);if(!re)return[];let Oe=ti(re)||[],ne=Date.now(),M=new Set,F=[];for(let{token:ce,expiresAt:de}of Oe){if(de<=ne||M.has(ce))continue;M.add(ce);let pe=await i.get(ce);if(!pe)continue;try{let ae=typeof pe==="string"?JSON.parse(pe):pe;if(!ae?.session)continue;F.push(Di(t.options,{...ae.session,expiresAt:new Date(ae.session.expiresAt)}))}catch{continue}}return F}return await(await $r(e)).findMany({model:"session",where:[{field:"userId",value:k},...j?.onlyActiveSessions?[{field:"expiresAt",value:new Date,operator:"gt"}]:[]]})},listUsers:async(k,j,re,Oe)=>await(await $r(e)).findMany({model:"user",limit:k,offset:j,sortBy:re,where:Oe}),countTotalUsers:async(k)=>{let j=await(await $r(e)).count({model:"user",where:k});if(typeof j==="string")return parseInt(j);return j},deleteUser:async(k)=>{let j=await R(k);if(!i||n.session?.storeSessionInDatabase)await h([{field:"userId",value:k}],"session",void 0);if(await h([{field:"userId",value:k}],"account",void 0),await f([{field:"id",value:k}],"user",void 0)!==null)await I(k,j)},createSession:async(k,j,re,Oe,ne)=>{let M=await(async()=>{let Te=Vs();return Te?.headers||Te?.request?.headers})(),F=n.session?.storeSessionInDatabase,ce=ne?.deferSecondaryStorageWrites===!0&&a,{id:de,...pe}=re||{},ae;if(i&&!F){let Te=t.generateId({model:"session"});ae=Te!==!1?Te:xe()}let He=xy(n),Be={...ae?{id:ae}:{},ipAddress:M?Vy(M,n)||"":"",userAgent:M?.get("user-agent")||"",...pe,expiresAt:j?ac(86400,"sec"):ac(s,"sec"),userId:k,token:xe(32),createdAt:new Date,updatedAt:new Date,...He,...Oe?pe:{}},Ke=async(Te)=>{if(!i)return Te;let Ve=await i.get(`active-sessions-${k}`),Je=[],ft=Date.now();if(Ve)Je=ti(Ve)||[],Je=Je.filter((oi)=>oi.expiresAt>ft&&oi.token!==Be.token);let qt=[...Je,{token:Be.token,expiresAt:Be.expiresAt.getTime()}].sort((oi,Kt)=>oi.expiresAt-Kt.expiresAt),ot=Aa(qt.at(-1)?.expiresAt??Be.expiresAt.getTime(),ft);if(ot>0)await i.set(`active-sessions-${k}`,JSON.stringify(qt),ot);let Tr=await(await $r(e)).findOne({model:"user",where:[{field:"id",value:k}]}),un=Aa(Be.expiresAt,ft);if(un>0)await i.set(Be.token,JSON.stringify({session:Te,user:Tr}),un);return Te};return await c(Be,"session",i?{fn:async(Te)=>{if(!ce)return Ke(Te);return await _o(async()=>{await Ke(Te)},{onError(Ve){r.error("Failed to mirror committed session to secondary storage",Ve)}}),Te},executeMainFn:F}:void 0)},findSession:async(k)=>{if(i){let ne=await i.get(k);if(!ne&&(!n.session?.storeSessionInDatabase||t.options.session?.preserveSessionInDatabase))return null;if(ne){let M=ti(ne);if(!M)return null;return{session:Di(t.options,{...M.session,expiresAt:new Date(M.session.expiresAt),createdAt:new Date(M.session.createdAt),updatedAt:new Date(M.session.updatedAt)}),user:Xn(t.options,{...M.user,createdAt:new Date(M.user.createdAt),updatedAt:new Date(M.user.updatedAt)})}}}let j=await(await $r(e)).findOne({model:"session",where:[{value:k,field:"token"}],join:{user:!0}});if(!j)return null;let{user:re,...Oe}=j;if(!re)return null;return{session:Di(t.options,Oe),user:Xn(t.options,re)}},findSessions:async(k,j)=>{let re=[...new Set(k)],Oe=new Map,ne=[];if(i)for(let F of re){let ce=await i.get(F);if(ce)try{let de=typeof ce==="string"?JSON.parse(ce):ce;if(!de)continue;let pe=new Date(de.session.expiresAt);if(j?.onlyActiveSessions&&pe<=new Date)continue;let ae={session:{...de.session,expiresAt:new Date(de.session.expiresAt)},user:{...de.user,createdAt:new Date(de.user.createdAt),updatedAt:new Date(de.user.updatedAt)}};Oe.set(F,ae)}catch{continue}else ne.push(F)}let M=i?ne:re;if(M.length>0&&(!i||a)){let F=await(await $r(e)).findMany({model:"session",limit:M.length,where:[{field:"token",value:M,operator:"in"},...j?.onlyActiveSessions?[{field:"expiresAt",value:new Date,operator:"gt"}]:[]],join:{user:!0}});for(let{user:ce,...de}of F)if(ce)Oe.set(de.token,{session:de,user:ce})}return re.flatMap((F)=>{let ce=Oe.get(F);return ce?[ce]:[]})},updateSession:async(k,j)=>await u(j,[{field:"token",value:k}],"session",i?{async fn(re){let Oe=await i.get(k);if(!Oe)return null;let ne=ti(Oe);if(!ne)return null;let M={...ne.session,...re,expiresAt:new Date(re.expiresAt??ne.session.expiresAt),createdAt:new Date(ne.session.createdAt),updatedAt:new Date(re.updatedAt??ne.session.updatedAt)},F=Di(t.options,M),ce=Date.now(),de=new Date(F.expiresAt).getTime(),pe=Aa(de,ce);if(pe>0){await i.set(k,JSON.stringify({session:F,user:ne.user}),pe);let ae=`active-sessions-${F.userId}`,He=await i.get(ae),Be=(He?ti(He)||[]:[]).filter((Te)=>Te.token!==k&&Te.expiresAt>ce).concat([{token:k,expiresAt:de}]).sort((Te,Ve)=>Te.expiresAt-Ve.expiresAt),Ke=Be.at(-1)?.expiresAt;if(Ke&&Ke>ce)await i.set(ae,JSON.stringify(Be),Aa(Ke,ce));else await i.delete(ae)}return F},executeMainFn:n.session?.storeSessionInDatabase}:void 0),deleteSession:async(k)=>{if(i){let j=await i.get(k);if(j){let{session:re}=ti(j)??{};if(!re){r.error("Session not found in secondary storage");return}let Oe=re.userId,ne=await i.get(`active-sessions-${Oe}`);if(ne){let M=ti(ne)||[],F=Date.now(),ce=M.filter((pe)=>pe.expiresAt>F&&pe.token!==k),de=ce.sort((pe,ae)=>pe.expiresAt-ae.expiresAt).at(-1)?.expiresAt;if(ce.length>0&&de&&de>Date.now())await i.set(`active-sessions-${Oe}`,JSON.stringify(ce),Aa(de,F));else await i.delete(`active-sessions-${Oe}`)}else r.error("Active sessions list not found in secondary storage")}if(await i.delete(k),!n.session?.storeSessionInDatabase)return;if(t.options.session?.preserveSessionInDatabase){await g([{field:"token",value:k}]);return}}await f([{field:"token",value:k}],"session",void 0)},deleteAccounts:async(k)=>{await h([{field:"userId",value:k}],"account",void 0)},deleteAccount:async(k)=>{await f([{field:"id",value:k}],"account",void 0)},deleteUserSessions:async(k)=>{let j=await R(k);if(i){if(!n.session?.storeSessionInDatabase){await I(k,j);return}if(t.options.session?.preserveSessionInDatabase){if(await g([{field:"userId",value:k}])!==null)await I(k,j);return}}if(await h([{field:"userId",value:k}],"session",void 0)!==null)await I(k,j)},deleteSessions:async(k)=>{if(i){if(await Promise.all(k.map((j)=>i.delete(j))),!n.session?.storeSessionInDatabase)return;if(t.options.session?.preserveSessionInDatabase){await g([{field:"token",value:k,operator:"in"}]);return}}await h([{field:"token",value:k,operator:"in"}],"session",void 0)},findAccountOwnerByKey:async({providerId:k,accountId:j})=>{let re=await(await $r(e)).findMany({model:"account",where:[{field:"providerId",value:k},{field:"accountId",value:j}],limit:2,join:{user:!0}});if(re.length>1)throw new y(`Multiple accounts match the same accountId for provider ${JSON.stringify(k)}. Resolve duplicate account identities before continuing.`);let Oe=re[0];if(!Oe)return null;let{user:ne,...M}=Oe;return ne?{kind:"owned",user:ne,account:M}:{kind:"orphaned",account:M}},findUserByEmail:async(k,j)=>{let re=await(await $r(e)).findOne({model:"user",where:[{value:k.toLowerCase(),field:"email"}],join:{...j?.includeAccounts?{account:!0}:{}}});if(!re)return null;let{account:Oe,...ne}=re;return{user:ne,accounts:Oe??[]}},findUserById:async(k)=>{if(!k)return null;return await(await $r(e)).findOne({model:"user",where:[{field:"id",value:k}]})},linkAccount:async(k)=>await c({createdAt:new Date,updatedAt:new Date,...k},"account",void 0),updateUser:async(k,j)=>{let re=await u({...j,...j.email?{email:j.email.toLowerCase()}:{}},[{field:"id",value:k}],"user",void 0);return await _o(()=>_(re),{onError(Oe){r.error("Failed to refresh committed user sessions in secondary storage",Oe)}}),re},updateUserByEmail:async(k,j)=>{let re=await u({...j,...j.email?{email:j.email.toLowerCase()}:{}},[{field:"email",value:k.toLowerCase()}],"user",void 0);return await _o(()=>_(re),{onError(Oe){r.error("Failed to refresh committed user sessions in secondary storage",Oe)}}),re},updatePassword:async(k,j)=>{await d({password:j},[{field:"userId",value:k},{field:"providerId",value:"credential"},{field:"accountId",value:k}],"account",void 0)},findAccounts:async(k)=>await(await $r(e)).findMany({model:"account",where:[{field:"userId",value:k}]}),findCredentialAccount:async(k)=>(await $r(e)).findOne({model:"account",where:[{field:"userId",value:k},{field:"providerId",value:"credential"},{field:"accountId",value:k}]}),findAccountByKey:async({providerId:k,accountId:j})=>{let re=await(await $r(e)).findMany({model:"account",limit:2,where:[{field:"providerId",value:k},{field:"accountId",value:j}]});if(re.length>1)throw new y(`Multiple accounts match the same accountId for provider ${JSON.stringify(k)}. Resolve duplicate account identities before continuing.`);return re[0]??null},findAccountByUserId:async(k)=>await(await $r(e)).findMany({model:"account",where:[{field:"userId",value:k}]}),updateAccount:async(k,j)=>await u(j,[{field:"id",value:k}],"account",void 0),createVerificationValue:async(k)=>{let j=ed(k.identifier,n.verification?.storeIdentifier),re=await Zu(k.identifier,j);return await c({createdAt:new Date,updatedAt:new Date,...k,identifier:re},"verification",i?{async fn(Oe){let ne=Aa(Oe.expiresAt);if(ne>0)await i.set(`verification:${re}`,JSON.stringify(Oe),ne);return Oe},executeMainFn:n.verification?.storeInDatabase}:void 0)},findVerificationValue:async(k)=>{let j=ed(k,n.verification?.storeIdentifier),re=await Zu(k,j);if(i){let F=await i.get(`verification:${re}`);if(F){let ce=ti(F);if(ce)return ce}if(j&&j!=="plain"){let ce=await i.get(`verification:${k}`);if(ce){let de=ti(ce);if(de)return de}}if(!n.verification?.storeInDatabase)return null}let Oe=await $r(e);async function ne(F){return Oe.findMany({model:"verification",where:[{field:"identifier",value:F}],sortBy:{field:"createdAt",direction:"desc"},limit:1})}let M=await ne(re);if(!M.length&&j&&j!=="plain")M=await ne(k);if(!n.verification?.disableCleanup)await h([{field:"expiresAt",value:new Date,operator:"lt"}],"verification",void 0);return M[0]||null},deleteVerificationByIdentifier:async(k)=>{let j=await Zu(k,ed(k,n.verification?.storeIdentifier));if(i)await i.delete(`verification:${j}`);if(!i||n.verification?.storeInDatabase)await f([{field:"identifier",value:j}],"verification",void 0)},consumeVerificationValue:async(k)=>{let j=ed(k,n.verification?.storeIdentifier),re=await Zu(k,j),Oe=j&&j!=="plain"?[re,k]:[re],ne=(F)=>{if(!F)return null;let ce=typeof F==="string"?ti(F):typeof F==="object"?F:null;if(!ce)return null;let de=new Date(ce.expiresAt);if(!Number.isFinite(de.getTime()))return null;return{...ce,expiresAt:de}},M=null;if(i&&!n.verification?.storeInDatabase){let F=async(ce)=>ne(await i.getAndDelete(ce));for(let ce of Oe){let de=await F(`verification:${ce}`);if(!de)continue;await Promise.all(Oe.filter((pe)=>pe!==ce).map((pe)=>i.delete(`verification:${pe}`))),M=de;break}}else{let F=async(ce)=>Ne(`verification:${ce}`,()=>Co(e,async()=>{let de=await $r(e),pe=[{field:"identifier",value:ce}],ae=(await de.findMany({model:"verification",where:pe,sortBy:{field:"createdAt",direction:"desc"},limit:1}))[0]??null;if(!ae)return null;return p("verification",[{field:"id",value:ae.id}],async()=>{let He=await de.consumeOne({model:"verification",where:[{field:"id",value:ae.id}]});if(!He)return null;return await de.deleteMany({model:"verification",where:pe}),He},ae)}));for(let ce of Oe)if(M=await F(ce),M)break;if(M&&i)await Promise.all(Oe.map((ce)=>i.delete(`verification:${ce}`)))}if(!M||M.expiresAt<new Date)return null;return M},reserveVerificationValue:async(k)=>{let j=Sh(new Uint8Array(await Ce("SHA-256").digest(new TextEncoder().encode("reserve:"+k.identifier))),n),re=ed(k.identifier,n.verification?.storeIdentifier),Oe=await Zu(k.identifier,re);if(i&&!n.verification?.storeInDatabase)throw new y("reserveVerificationValue requires database-backed verification storage. Set verification.storeInDatabase to true for flows that reserve verification values.");try{await e.create({model:"verification",data:{id:j,identifier:Oe,value:k.value,expiresAt:k.expiresAt,createdAt:new Date,updatedAt:new Date},forceAllowId:!0})}catch(ne){if(await e.findOne({model:"verification",where:[{field:"id",value:j}]}))return!1;throw ne}if(i){let ne=Aa(k.expiresAt);if(ne>0)await i.set(`verification:${Oe}`,JSON.stringify({id:j,identifier:Oe,value:k.value,expiresAt:k.expiresAt}),ne)}return!0},updateVerificationByIdentifier:async(k,j)=>{let re=await Zu(k,ed(k,n.verification?.storeIdentifier));if(i){let Oe=await i.get(`verification:${re}`);if(Oe){let ne=ti(Oe);if(ne){let M={...ne,...j},F=M.expiresAt??ne.expiresAt,ce=Aa(F instanceof Date?F:new Date(F));if(ce>0)await i.set(`verification:${re}`,JSON.stringify(M),ce);if(!n.verification?.storeInDatabase)return M}}}if(!i||n.verification?.storeInDatabase)return await u(j,[{field:"identifier",value:re}],"verification",void 0);return j},refreshUserSessions:_}};function wT(e){if(e===null||typeof e!=="object")return!1;let t=Object.getPrototypeOf(e);if(t!==null&&t!==Object.prototype&&Object.getPrototypeOf(t)!==null)return!1;if(Symbol.iterator in e)return!1;if(Symbol.toStringTag in e)return Object.prototype.toString.call(e)==="[object Module]";return!0}function _T(e,t,r=".",n){if(!wT(t))return _T(e,{},r,n);let i={...t};for(let o of Object.keys(e)){if(o==="__proto__"||o==="constructor")continue;let s=e[o];if(s===null||s===void 0)continue;if(n&&n(i,o,s,r))continue;if(Array.isArray(s)&&Array.isArray(i[o]))i[o]=[...s,...i[o]];else if(wT(s)&&wT(i[o]))i[o]=_T(s,i[o],(r?`${r}.`:"")+o.toString(),n);else i[o]=s}return i}function ip(e){return(...t)=>t.reduce((r,n)=>_T(r,n,"",e),{})}var Ar=ip(),dje=ip((e,t,r)=>{if(e[t]!==void 0&&typeof r==="function")return e[t]=r(e[t]),!0}),lje=ip((e,t,r)=>{if(Array.isArray(e[t])&&typeof r==="function")return e[t]=r(e[t]),!0});var Pse=new Set(["metadata.google.internal","metadata.goog","metadata","instance-data","instance-data.ec2.internal"]);function Lse(e){if(e.length>=2&&e.startsWith("[")&&e.endsWith("]"))return e.slice(1,-1);return e}function Mse(e){if(e.startsWith("[")){let r=e.indexOf("]");if(r===-1)return e;return e.slice(0,r+1)}let t=e.indexOf(":");if(t===-1)return e;if(e.indexOf(":",t+1)!==-1)return e;return e.slice(0,t)}function qse(e){let t=e.indexOf("%");if(t===-1)return e;return e.slice(0,t)}function Bse(e){return e.replace(/\.+$/,"")}function u1(e){return/^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.test(e)}function uo(e){let t=e.split(".");return(Number(t[0])<<24|Number(t[1])<<16|Number(t[2])<<8|Number(t[3]))>>>0}function bo(e,t,r){if(r===0)return!0;let n=r===32?4294967295:-1<<32-r>>>0;return(e&n)===(t&n)}function op(e){if(e==="0.0.0.0")return"unspecified";if(e==="255.255.255.255")return"broadcast";let t=uo(e);if(bo(t,uo("127.0.0.0"),8))return"loopback";if(bo(t,uo("10.0.0.0"),8))return"private";if(bo(t,uo("172.16.0.0"),12))return"private";if(bo(t,uo("192.168.0.0"),16))return"private";if(bo(t,uo("169.254.0.0"),16))return"linkLocal";if(bo(t,uo("100.64.0.0"),10))return"sharedAddressSpace";if(bo(t,uo("192.0.2.0"),24))return"documentation";if(bo(t,uo("198.51.100.0"),24))return"documentation";if(bo(t,uo("203.0.113.0"),24))return"documentation";if(bo(t,uo("198.18.0.0"),15))return"benchmarking";if(bo(t,uo("224.0.0.0"),4))return"multicast";if(bo(t,uo("0.0.0.0"),8))return"reserved";if(bo(t,uo("192.0.0.0"),24))return"reserved";if(bo(t,uo("192.88.99.0"),24))return"reserved";if(bo(t,uo("240.0.0.0"),4))return"reserved";return"public"}function bT(e,t,r={}){let n=t*5,i=Number.parseInt(e.slice(n,n+4),16),o=Number.parseInt(e.slice(n+5,n+9),16);if(!Number.isFinite(i)||!Number.isFinite(o))return null;let s=(i<<16|o)>>>0;if(r.xor)s=(s^4294967295)>>>0;return`${s>>>24&255}.${s>>>16&255}.${s>>>8&255}.${s&255}`}function jse(e){if(e==="0000:0000:0000:0000:0000:0000:0000:0000")return"unspecified";if(e==="0000:0000:0000:0000:0000:0000:0000:0001")return"loopback";let t=Number.parseInt(e.slice(0,2),16),r=Number.parseInt(e.slice(2,4),16);if(t===255)return"multicast";if(t===254&&(r&192)===128)return"linkLocal";if(t===254&&(r&192)===192)return"reserved";if((t&254)===252)return"private";if(e.startsWith("2001:0db8:"))return"documentation";if(e.startsWith("2001:0002:0000:"))return"benchmarking";if(e.startsWith("2002:")){let n=bT(e,1);if(n&&op(n)!=="public")return"reserved";return"public"}if(e.startsWith("0064:ff9b:0000:0000:0000:0000:")){let n=bT(e,6);if(n&&op(n)!=="public")return"reserved";return"reserved"}if(e.startsWith("0064:ff9b:0001:"))return"reserved";if(e.startsWith("2001:0000:")){let n=bT(e,6,{xor:!0});if(n&&op(n)!=="public")return"reserved";return"reserved"}if(e.startsWith("0100:0000:0000:0000:"))return"reserved";if(e.startsWith("3fff:0"))return"documentation";if(e.startsWith("5f00:"))return"reserved";if(e.startsWith("0000:0000:0000:0000:0000:0000:"))return"reserved";return"public"}function ET(e){let t=Bse(qse(Lse(Mse(e.trim())))).toLowerCase();if(t==="")return{kind:"reserved",literal:"fqdn",canonical:""};if(!mT(t)){if(t==="localhost"||t.endsWith(".localhost"))return{kind:"localhost",literal:"fqdn",canonical:t};if(Pse.has(t))return{kind:"cloudMetadata",literal:"fqdn",canonical:t};return{kind:"public",literal:"fqdn",canonical:t}}if(u1(t))return{kind:op(t),literal:"ipv4",canonical:t};let r=Hy(t,{ipv6Subnet:128});if(u1(r))return{kind:op(r),literal:"ipv4",canonical:r};return{kind:jse(r),literal:"ipv6",canonical:r}}function ST(e){return ET(e).kind==="loopback"}function Pl(e){let t=ET(e).kind;return t==="loopback"||t==="localhost"}function d1(e){return ET(e).kind==="public"}async function gn(e){let t=e.options,r=t.plugins||[],n=[],i=[];for(let o of r)if(o.init){let s=o.init(e),a;if(bt(s))a=await s;else a=s;if(typeof a==="object"){if(a.options){let{databaseHooks:c,trustedOrigins:u,...d}=a.options;if(c)i.push({source:`plugin:${o.id}`,hooks:c});if(u)n.push(u);t=Ar(t,d)}if(a.context)Object.assign(e,a.context)}}if(n.length>0){let o=[...t.trustedOrigins?[t.trustedOrigins]:[],...n],s=o.filter(Array.isArray).flat(),a=o.filter((c)=>typeof c==="function");if(a.length>0)t.trustedOrigins=async(c)=>{let u=await Promise.all(a.map((d)=>d(c)));return[...s,...u.flat()].filter((d)=>typeof d==="string"&&d!=="")};else t.trustedOrigins=s}if(t.databaseHooks)i.push({source:"user",hooks:t.databaseHooks});e.internalAdapter=kt(e.adapter,{options:t,logger:e.logger,hooks:i,generateId:e.generateId}),e.options=t}function _n(e){let t=[];if(e.advanced?.crossSubDomainCookies?.enabled);return t}async function mr(e,t){let r=[];if(Ee(e.baseURL)){let i=e.baseURL.allowedHosts,o=e.baseURL.protocol;for(let s of i)if(!s.includes("://")){if(!o||o==="https"||o==="auto")r.push(`https://${s}`);if(o==="http"||o==="auto"||Pl(s))r.push(`http://${s}`)}else r.push(s);if(e.baseURL.fallback)try{r.push(new URL(e.baseURL.fallback).origin)}catch{}}else{let i=Ue(typeof e.baseURL==="string"?e.baseURL:void 0,e.basePath,t);if(i)r.push(new URL(i).origin)}if(e.trustedOrigins){if(Array.isArray(e.trustedOrigins))r.push(...e.trustedOrigins);if(typeof e.trustedOrigins==="function"){let i=await e.trustedOrigins(t);r.push(...i)}}let n=D.BETTER_AUTH_TRUSTED_ORIGINS;if(n)r.push(...n.split(","));return r.filter((i)=>Boolean(i))}function l1(e){if(as(e?.request))return e.request;if(!e?.headers)return;let t=e.headers instanceof Headers?e.headers:new Headers(e.headers);if(!t.has("host")&&!t.has("x-forwarded-host"))return;return t}function Dr(e){return e.advanced?.trustedProxyHeaders??!1}async function Nr(e,t,r){let n=e.options.baseURL,i=uP(n,e.options.basePath||"/api/auth",t,void 0,r);if(!i)throw new y("Could not resolve base URL from request. Check your allowedHosts config.");let o=Object.create(Object.getPrototypeOf(e),Object.getOwnPropertyDescriptors(e));o.baseURL=i,o.options={...e.options,baseURL:qe(i)||void 0};let s={...o.options,baseURL:n},a=typeof e.options.trustedOrigins==="function"||typeof e.options.account?.accountLinking?.trustedProviders==="function",c;if(a)if(as(t))c=t;else if(t)c=new Request(i,{headers:t});else c=void 0;else c=void 0;if(o.trustedOrigins=await mr(s,c),o.trustedProviders=await fr(o.options,c),e.options.advanced?.crossSubDomainCookies?.enabled)o.authCookies=Mr(o.options),o.createAuthCookie=dr(o.options);return o}async function Ta(e,t){if(!e)return;for(let r of e){let n=typeof r==="function"?await r():r;if(n[t.field??"id"]===t.value)return n}}async function fr(e,t){let r=e.account?.accountLinking?.trustedProviders;if(!r)return[];if(Array.isArray(r))return r.filter((n)=>Boolean(n));return(await r(t)??[]).filter((n)=>Boolean(n))}function rd(e,t){if(t.length<e.context.password.config.minPasswordLength)throw e.context.logger.warn("Password is too short"),l.from("BAD_REQUEST",S.PASSWORD_TOO_SHORT)}function Go(e,t){if(t.length>e.context.password.config.maxPasswordLength)throw e.context.logger.warn("Password is too long"),l.from("BAD_REQUEST",S.PASSWORD_TOO_LONG)}async function f1(e,t,r,n){await Co(e.context.adapter,async()=>{if(await n?.(),e.context.options.emailAndPassword?.revokeSessionsOnPasswordReset)await e.context.internalAdapter.deleteUserSessions(t);if(!await e.context.internalAdapter.findCredentialAccount(t)){await e.context.internalAdapter.createAccount({userId:t,providerId:"credential",accountId:t,password:r});return}await e.context.internalAdapter.updatePassword(t,r)})}async function h1(e,t){Go(e,t.password);let r=await e.context.internalAdapter.findCredentialAccount(t.userId),n=r?.password;if(!r||!n)return!1;return await e.context.password.verify({hash:n,password:t.password})}async function yn(e,t){let r=t.body.password;if(typeof r==="string")Go(t,r);let n=await t.context.internalAdapter.findCredentialAccount(e),i=n?.password;if(!n||!i||!r){if(r)await t.context.password.hash(r);throw l.from("BAD_REQUEST",S.INVALID_PASSWORD)}if(!await t.context.password.verify({hash:i,password:r}))throw l.from("BAD_REQUEST",S.INVALID_PASSWORD);return!0}function hi(e){return e instanceof st||e instanceof l||e?.name==="APIError"}var sp={"Cache-Control":"no-store",Pragma:"no-cache"};function $se(e,t){if(!hi(t)||!e)return;Object.defineProperty(t,xc,{enumerable:!1,configurable:!0,value:e,writable:!1})}var AT=Yc(async()=>({})),ee=Yc.create({use:[AT,Yc(async()=>({}))]}),p1=Qc.create({use:[AT]});function m1(e,t){let r=t.metadata?.noStore===!0;return async(n)=>{if(r)for(let[i,o]of Object.entries(sp))n.setHeader(i,o);try{return await Ul(n,()=>e(n))}catch(i){throw $se(n.responseHeaders,i),i}}}function v(...e){if(e.length===3){let[n,i,o]=e;return p1(n,i,m1(o,i))}let[t,r]=e;return p1(t,m1(r,t))}function Fse(e){return{...e,metadata:{...e.metadata,SERVER_ONLY:!0}}}v.serverOnly=(e,t)=>v(Fse(e),t);function Ll(e,t){let r;try{r=new URL(e).pathname.replace(/\/+$/,"")||"/"}catch{return"/"}let n=t.replace(/\/+$/,"");if(n==="")return r;if(r===n)return"/";if(r.startsWith(n+"/"))return r.slice(n.length).replace(/\/+$/,"")||"/";return r}var g1="https://better-auth.invalid";function us(e,t){let r=e.startsWith("/");if(e.startsWith("//")||e.startsWith("/\\"))throw TypeError("Expected an absolute or root-relative URL");let n=r?new URL(e,g1):new URL(e);if(r&&n.origin!==g1)throw TypeError("Expected an absolute or root-relative URL");let i=t.toString();if(!i)return e;let o=n.search.endsWith("&")?"":"&";return n.search=n.search?`${n.search}${o}${i}`:i,r?n.href.slice(n.origin.length):n.href}var y1=["javascript:","data:","vbscript:"];function w1(e,t,r){let n=!1;return function(...i){if(!n)(r?.warn??console.warn)(`[Deprecation] ${t}`),n=!0;return e.apply(this,i)}}function _1(e){return e.context.skipOriginCheck===!0&&e.context.options.advanced?.disableCSRFCheck===void 0}function TT(e){let t=e.context.skipOriginCheck;if(t===!0)return!0;if(Array.isArray(t)&&e.request)try{let r=new URL(e.context.baseURL).pathname,n=Ll(e.request.url,r);return t.some((i)=>{let o=i.replace(/\/+$/,"");return n===o||n.startsWith(`${o}/`)})}catch{}return!1}var zse=w1(function(){},"disableOriginCheck: true currently also disables CSRF checks. In a future version, disableOriginCheck will ONLY disable URL validation. To keep CSRF disabled, add disableCSRFCheck: true to your config."),b1=ee(async(e)=>{if(e.request?.method==="GET"||e.request?.method==="OPTIONS"||e.request?.method==="HEAD"||!e.request)return;if(await Gy(e),TT(e))return;let{body:t,query:r}=e,n=t?.callbackURL||r?.callbackURL,i=t?.redirectTo,o=t?.errorCallbackURL,s=t?.newUserCallbackURL,a=(c,u)=>{if(!c)return;if(typeof c!=="string")throw l.fromStatus("BAD_REQUEST",{message:`Invalid ${u}: expected a string`});if(!e.context.isTrustedOrigin(c,{allowRelativePaths:u!=="origin"})){if(e.context.logger.error(`Invalid ${u}: ${c}`),e.context.logger.info(`If it's a valid URL, please add ${c} to trustedOrigins in your auth config
135
+ `,`Current list of trustedOrigins: ${e.context.trustedOrigins}`),u==="origin")throw l.from("FORBIDDEN",S.INVALID_ORIGIN);if(u==="callbackURL")throw l.from("FORBIDDEN",S.INVALID_CALLBACK_URL);if(u==="redirectURL")throw l.from("FORBIDDEN",S.INVALID_REDIRECT_URL);if(u==="errorCallbackURL")throw l.from("FORBIDDEN",S.INVALID_ERROR_CALLBACK_URL);if(u==="newUserCallbackURL")throw l.from("FORBIDDEN",S.INVALID_NEW_USER_CALLBACK_URL);throw l.fromStatus("FORBIDDEN",{message:`Invalid ${u}`})}};n&&a(n,"callbackURL"),i&&a(i,"redirectURL"),o&&a(o,"errorCallbackURL"),s&&a(s,"newUserCallbackURL")}),eu=(e)=>ee(async(t)=>{if(!t.request)return;if(TT(t))return;let r=e(t),n=(o,s)=>{if(!o)return;if(!t.context.isTrustedOrigin(o,{allowRelativePaths:s!=="origin"})){if(t.context.logger.error(`Invalid ${s}: ${o}`),t.context.logger.info(`If it's a valid URL, please add ${o} to trustedOrigins in your auth config
136
+ `,`Current list of trustedOrigins: ${t.context.trustedOrigins}`),s==="origin")throw l.from("FORBIDDEN",S.INVALID_ORIGIN);if(s==="callbackURL")throw l.from("FORBIDDEN",S.INVALID_CALLBACK_URL);if(s==="redirectURL")throw l.from("FORBIDDEN",S.INVALID_REDIRECT_URL);if(s==="errorCallbackURL")throw l.from("FORBIDDEN",S.INVALID_ERROR_CALLBACK_URL);if(s==="newUserCallbackURL")throw l.from("FORBIDDEN",S.INVALID_NEW_USER_CALLBACK_URL);throw l.fromStatus("FORBIDDEN",{message:`Invalid ${s}`})}},i=Array.isArray(r)?r:[r];for(let o of i)n(o,"callbackURL")});async function Gy(e,t=!1){let r=e.request?.headers;if(!r||!e.request)return;let n=r.get("origin"),i=n||r.get("referer")||"",o=r.has("cookie");if(e.context.skipCSRFCheck)return;if(_1(e)){e.context.options.advanced?.disableOriginCheck===!0&&zse();return}if(TT(e))return;if(!(t||o))return;let s=n==="null"&&r.get("sec-fetch-site")==="same-origin"?Ue(void 0,e.context.options.basePath,e.request,!1,e.context.options.advanced?.trustedProxyHeaders):void 0,a=(s?qe(s):void 0)??i;if(!a||a==="null")throw l.from("FORBIDDEN",S.MISSING_OR_NULL_ORIGIN);let c=Array.isArray(e.context.options.trustedOrigins)?e.context.trustedOrigins:[...e.context.trustedOrigins,...(await e.context.options.trustedOrigins?.(e.request))?.filter((u)=>Boolean(u))||[]];if(!c.some((u)=>Or(a,u)))throw e.context.logger.error(`Invalid origin: ${a}`),e.context.logger.info(`If it's a valid URL, please add ${a} to trustedOrigins in your auth config
137
+ `,`Current list of trustedOrigins: ${c}`),l.from("FORBIDDEN",S.INVALID_ORIGIN)}var ap=ee(async(e)=>{if(!e.request)return;await Wse(e)});async function Wse(e){let t=e.request;if(!t)return;if(e.context.skipCSRFCheck)return;if(_1(e))return;let r=t.headers;if(r.has("cookie"))return await Gy(e);let n=r.get("Sec-Fetch-Site"),i=r.get("Sec-Fetch-Mode"),o=r.get("Sec-Fetch-Dest");if(Boolean(n&&n.trim()||i&&i.trim()||o&&o.trim())){if(n==="cross-site"&&i==="navigate")throw e.context.logger.error("Blocked cross-site navigation login attempt (CSRF protection)",{secFetchSite:n,secFetchMode:i,secFetchDest:o}),l.from("FORBIDDEN",S.CROSS_SITE_NAVIGATION_LOGIN_BLOCKED);return await Gy(e,!0)}if(r.get("origin")||r.get("referer"))return await Gy(e,!0)}var tu=new Map,E1=1e5;function Hse(){let e=Date.now();for(let[n,i]of tu)if(e>=i.expiresAt)tu.delete(n);if(tu.size<=E1)return;let t=tu.size-E1,r=0;for(let n of tu.keys())if(tu.delete(n),++r>=t)break}function Vse(e,t,r){let n=t.window*1000;if(!e)return{next:{key:"",count:1,lastRequest:r},update:!1,allowed:!0,retryAfter:null};if(r-e.lastRequest>=n)return{next:{...e,count:1,lastRequest:r},update:!0,allowed:!0,retryAfter:null};if(e.count>=t.max)return{next:e,update:!0,allowed:!1,retryAfter:A1(e.lastRequest,t.window)};return{next:{...e,count:e.count+1,lastRequest:r},update:!0,allowed:!0,retryAfter:null}}function Gse(e){return new Response(JSON.stringify({message:"Too many requests. Please try again later."}),{status:429,statusText:"Too Many Requests",headers:{"Content-Type":"application/json","X-Retry-After":e.toString()}})}function A1(e,t){let r=Date.now(),n=t*1000;return Math.ceil((e+n-r)/1000)}function Kse(e){let r=e.adapter,n=Math.max(...Jse(e)),i=async(a)=>{let c=(await r.findMany({model:"rateLimit",where:[{field:"key",value:a}]}))[0];if(c)c.lastRequest=Number(c.lastRequest);return c},o=async(a,c)=>{if(c.window>n)n=c.window;let u=c.window*1000,d=await i(a),f=Date.now();if(!d)try{return await r.create({model:"rateLimit",data:{key:a,count:1,lastRequest:f}}),{allowed:!0,retryAfter:null}}catch(g){if(!await i(a))throw g;return o(a,c)}if(f-d.lastRequest>=u){if(await r.incrementOne({model:"rateLimit",where:[{field:"key",value:a},{field:"lastRequest",operator:"lte",value:d.lastRequest}],increment:{},set:{count:1,lastRequest:f}}))return await s(f),{allowed:!0,retryAfter:null};return o(a,c)}let h=f-u;if(await r.incrementOne({model:"rateLimit",where:[{field:"key",value:a},{field:"lastRequest",operator:"gt",value:h},{field:"count",operator:"lt",value:c.max}],increment:{count:1},set:{lastRequest:f}}))return{allowed:!0,retryAfter:null};let p=await i(a);if(!p)return o(a,c);if(f-p.lastRequest>=u)return o(a,c);return{allowed:!1,retryAfter:A1(p.lastRequest,c.window)}},s=async(a)=>{let c=a-n*1000;await e.runInBackgroundOrAwait(r.deleteMany({model:"rateLimit",where:[{field:"lastRequest",operator:"lt",value:c}]}).then(()=>{return}).catch((u)=>e.logger.error("Error pruning rate limit rows",u)))};return{consume:o}}function Jse(e){let t=[e.rateLimit.window,...v1().map((n)=>n.window)];for(let n of e.options.plugins||[])if(n.rateLimit)t.push(...n.rateLimit.map((i)=>i.window));if(e.rateLimit.customRules){for(let n of Object.values(e.rateLimit.customRules))if(n&&typeof n!=="function")t.push(n.window)}let r=t.filter((n)=>Number.isFinite(n)&&n>0);return r.length>0?r:[e.rateLimit.window]}function Qse(e,t){if(e.options.rateLimit?.customStorage)return e.options.rateLimit.customStorage;let r=e.rateLimit.storage;if(r==="secondary-storage"){let n=(o)=>o??e.options.rateLimit?.window??10,i=e.options.secondaryStorage?.increment;if(!i)throw new y("Secondary-storage rate limiting requires SecondaryStorage.increment.");return{consume:async(o,s)=>{if(await i(o,n(s.window))<=s.max)return{allowed:!0,retryAfter:null};return{allowed:!1,retryAfter:s.window}}}}else if(r==="memory"){let n=(i)=>i??e.options.rateLimit?.window??10;return{async consume(i,o){Hse();let s=Date.now(),a=tu.get(i),c=Vse(a&&s<a.expiresAt?a.data:void 0,o,s);if(c.allowed)tu.set(i,{data:{...c.next,key:i},expiresAt:s+n(o.window)*1000});return{allowed:c.allowed,retryAfter:c.retryAfter}}}}return Kse(e)}var S1=!1,Yse="no-trusted-ip";async function Xse(e,t){let r=new URL(t.baseURL).pathname,n=Ll(e.url,r),i=t.rateLimit.window,o=t.rateLimit.max,s=Vy(e,t.options);if(!s&&t.options.advanced?.ipAddress?.disableIpTracking)return null;if(!s&&!S1)t.logger.warn("Rate limiting could not determine a client IP and is falling back to a single shared per-path bucket. Ensure your runtime forwards a trusted client IP header, then set `advanced.ipAddress.ipAddressHeaders` or `advanced.ipAddress.trustedProxies` so the address can be resolved."),S1=!0;let a=c1(s??Yse,n),c=v1().find((u)=>u.pathMatcher(n));if(c)i=c.window,o=c.max;for(let u of t.options.plugins||[])if(u.rateLimit){let d=u.rateLimit.find((f)=>f.pathMatcher(n));if(d){i=d.window,o=d.max;break}}if(t.rateLimit.customRules){let u=Object.keys(t.rateLimit.customRules).find((d)=>{if(d.includes("*"))return Qu(d)(n);return d===n});if(u){let d=t.rateLimit.customRules[u],f=typeof d==="function"?await d(e,{window:i,max:o}):d;if(f)i=f.window,o=f.max;if(f===!1)return null}}return{key:a,currentWindow:i,currentMax:o}}async function T1(e,t){if(!t.rateLimit.enabled)return;let r=await Xse(e,t);if(!r)return;let{key:n,currentWindow:i,currentMax:o}=r,s=Qse(t,{window:i}),a={window:i,max:o},{allowed:c,retryAfter:u}=await s.consume(n,a);if(!c)return Gse(u??i)}function v1(){return[{pathMatcher(e){return e.startsWith("/sign-in")||e.startsWith("/sign-up")||e.startsWith("/change-password")||e.startsWith("/change-email")},window:10,max:3},{pathMatcher(e){return e==="/request-password-reset"||e==="/send-verification-email"||e.startsWith("/forget-password")||e==="/email-otp/send-verification-otp"||e==="/email-otp/request-password-reset"},window:60,max:3}]}var{get:Zse,set:vT}=Zc(()=>null),kT=async()=>await Zse(),{get:RT,set:eae}=Zc(()=>null),NT=async(e)=>{await eae({...await RT()??{},...e})};var{get:xT,set:Zje}=Zc(()=>!1);import*as Ky from"zod";var CT=()=>v("/get-session",{method:["GET","POST"],operationId:"getSession",query:t1,requireHeaders:!0,metadata:{openapi:{operationId:"getSession",description:"Get the current session",responses:{"200":{description:"Success",content:{"application/json":{schema:{type:["object","null"],properties:{session:{$ref:"#/components/schemas/Session"},user:{$ref:"#/components/schemas/User"}},required:["session","user"]}}}}}}}},async(e)=>{e.setHeader("cache-control","no-store"),e.setHeader("pragma","no-cache");let t=e.context.options.session?.deferSessionRefresh,r=e.method==="POST";if(r&&!t)throw l.from("METHOD_NOT_ALLOWED",S.METHOD_NOT_ALLOWED_DEFER_SESSION_REQUIRED);try{let n=e.context.options.session?.cookieCache?.enabled===!0,i=await e.getSignedCookie(e.context.authCookies.sessionToken.name,e.context.secret);if(!i&&n)return null;let o=$y(e,e.context.authCookies.sessionData.name);if(o&&!n){let I=tp(e.context.authCookies.sessionData.name,e.context.authCookies.sessionData.attributes,e);I.setCookies(I.clean())}if(!i)return null;let s=n&&!e.query?.disableCookieCache,a=s&&o?await n1(e,o):null;if(s&&o&&!a)cs(e,e.context.authCookies.sessionData);let c=await e.getSignedCookie(e.context.authCookies.dontRememberToken.name,e.context.secret);if(a?.session){let I=a.session,Ne=I.session.token!==i;if(!Ne){let k=e.context.options.session?.cookieCache?.version,j="1";if(k){if(typeof k==="string")j=k;else if(typeof k==="function"){let re=k(I.session,I.user);j=re instanceof Promise?await re:re}}Ne=(I.version||"1")!==j}if(!Ne){let k=Date.now(),j=new Date(I.session.expiresAt).getTime();Ne=a.expiresAt<k||!Number.isFinite(j)||j<k}if(Ne)cs(e,e.context.authCookies.sessionData);else{let k=e.context.sessionConfig.cookieRefreshCache;if(k===!1){e.context.session=I;let F=Di(e.context.options,{...I.session,expiresAt:new Date(I.session.expiresAt),createdAt:new Date(I.session.createdAt),updatedAt:new Date(I.session.updatedAt)}),ce=Xn(e.context.options,{...I.user,createdAt:new Date(I.user.createdAt),updatedAt:new Date(I.user.updatedAt)});return e.json({session:F,user:ce})}let j=a.expiresAt-Date.now(),re=k.updateAge*1000,Oe=await xT();if(j<re&&!Oe){let F={session:{...I.session},user:I.user,updatedAt:Date.now()};await rp(e,F,!1);let ce=e.context.authCookies.sessionToken.attributes,de=c?void 0:e.context.sessionConfig.expiresIn;await e.setSignedCookie(e.context.authCookies.sessionToken.name,I.session.token,e.context.secret,{...ce,maxAge:de});let pe=Di(e.context.options,{...F.session,expiresAt:new Date(F.session.expiresAt),createdAt:new Date(F.session.createdAt),updatedAt:new Date(F.session.updatedAt)}),ae=Xn(e.context.options,{...F.user,createdAt:new Date(F.user.createdAt),updatedAt:new Date(F.user.updatedAt)});return e.context.session={session:pe,user:ae},e.json({session:pe,user:ae})}let ne=Di(e.context.options,{...I.session,expiresAt:new Date(I.session.expiresAt),createdAt:new Date(I.session.createdAt),updatedAt:new Date(I.session.updatedAt)}),M=Xn(e.context.options,{...I.user,createdAt:new Date(I.user.createdAt),updatedAt:new Date(I.user.updatedAt)});return e.context.session={session:ne,user:M},e.json({session:ne,user:M})}}let u=await e.context.internalAdapter.findSession(i);if(e.context.session=u,!u||u.session.expiresAt<new Date){if(Vo(e),u){if(!t||r)await e.context.internalAdapter.deleteSession(u.session.token)}return e.json(null)}if(c||e.query?.disableRefresh){let I=Di(e.context.options,u.session),Ne=Xn(e.context.options,u.user);return e.json({session:I,user:Ne})}let d=e.context.sessionConfig.expiresIn,f=e.context.sessionConfig.updateAge,h=u.session.expiresAt.valueOf()-d*1000+f*1000<=Date.now(),p=e.query?.disableRefresh||e.context.options.session?.disableSessionRefresh,g=await xT(),_=h&&!p&&!g;if(t&&!r){await rp(e,u,!!c);let I=Di(e.context.options,u.session),Ne=Xn(e.context.options,u.user);return e.json({session:I,user:Ne,needsRefresh:_})}if(_){let I=await e.context.internalAdapter.updateSession(u.session.token,{expiresAt:ac(e.context.sessionConfig.expiresIn,"sec"),updatedAt:new Date});if(!I)throw Vo(e),l.from("UNAUTHORIZED",S.FAILED_TO_GET_SESSION);let Ne=e.context.sessionConfig.expiresIn;await ki(e,{session:I,user:u.user},!1,{maxAge:Ne});let k=Di(e.context.options,I),j=Xn(e.context.options,u.user);return e.json({session:k,user:j})}await rp(e,u,!!c);let R=Di(e.context.options,u.session),O=Xn(e.context.options,u.user);return e.json({session:R,user:O})}catch(n){if(hi(n))throw n;throw e.context.logger.error("INTERNAL_SERVER_ERROR",n),l.from("INTERNAL_SERVER_ERROR",S.FAILED_TO_GET_SESSION,{cause:n})}}),ru=(e)=>Pr(e.context.options),Gr=async(e,t)=>{if(e.context.session)return e.context.session;let r=await CT()({...e,method:"GET",asResponse:!1,headers:e.headers,returnHeaders:!0,returnStatus:!1,query:{...t,...e.query,disableCookieCache:t?.disableCookieCache||e.query?.disableCookieCache,disableRefresh:t?.disableRefresh||e.query?.disableRefresh}}).catch(()=>null);if(!r)return e.context.session=null,null;if(r.headers)r.headers.forEach((n,i)=>{let o=i.toLowerCase();if(o==="cache-control"||o==="pragma")return;if(o==="set-cookie")e.responseHeaders.append(i,n);else e.responseHeaders.set(i,n)});return e.context.session=r.response,r.response},k1=async(e)=>{if(!ru(e))return Gr(e);return e.context.session=null,Gr(e,{disableCookieCache:!0})},K=ee(async(e)=>{let t=await Gr(e);if(!t?.session)throw l.from("UNAUTHORIZED",{message:"Unauthorized",code:"UNAUTHORIZED"});return{session:t}}),Gs=ee(async(e)=>{let t=await k1(e);if(!t?.session)throw l.from("UNAUTHORIZED",{message:"Unauthorized",code:"UNAUTHORIZED"});return{session:t}}),tae=ee(async(e)=>{let t=await Gr(e);if(!t?.session&&(e.request||e.headers))throw l.from("UNAUTHORIZED",{message:"Unauthorized",code:"UNAUTHORIZED"});return{session:t}}),Jy=ee(async(e)=>{let t=await Gr(e);if(!t?.session)throw l.from("UNAUTHORIZED",{message:"Unauthorized",code:"UNAUTHORIZED"});if(e.context.sessionConfig.freshAge!==0){let r=new Date(t.session.createdAt).getTime(),n=e.context.sessionConfig.freshAge*1000;if(Date.now()-r>=n)throw l.from("FORBIDDEN",S.SESSION_NOT_FRESH)}return{session:t}}),R1=()=>v("/list-sessions",{method:"GET",operationId:"listUserSessions",use:[Jy],requireHeaders:!0,metadata:{openapi:{operationId:"listUserSessions",description:"List all active sessions for the user",responses:{"200":{description:"Success",content:{"application/json":{schema:{type:"array",items:{$ref:"#/components/schemas/Session"}}}}}}}}},async(e)=>{try{let t=(await e.context.internalAdapter.listSessions(e.context.session.user.id,{onlyActiveSessions:!0})).filter((r)=>r.expiresAt>new Date);return e.json(t.map((r)=>Di(e.context.options,r)))}catch(t){throw e.context.logger.error(t),e.error("INTERNAL_SERVER_ERROR")}}),N1=v("/revoke-session",{method:"POST",body:Ky.object({token:Ky.string().meta({description:"The token to revoke"})}),use:[Gs],requireHeaders:!0,metadata:{openapi:{description:"Revoke a single session",requestBody:{content:{"application/json":{schema:{type:"object",properties:{token:{type:"string",description:"The token to revoke"}},required:["token"]}}}},responses:{"200":{description:"Success",content:{"application/json":{schema:{type:"object",properties:{status:{type:"boolean",description:"Indicates if the session was revoked successfully"}},required:["status"]}}}}}}}},async(e)=>{let t=e.body.token;if((await e.context.internalAdapter.findSession(t))?.session.userId===e.context.session.user.id)try{await e.context.internalAdapter.deleteSession(t)}catch(r){throw e.context.logger.error(r&&typeof r==="object"&&"name"in r?r.name:"",r),l.from("INTERNAL_SERVER_ERROR",{message:"Internal Server Error",code:"INTERNAL_SERVER_ERROR"})}return e.json({status:!0})}),x1=v("/revoke-sessions",{method:"POST",use:[Gs],requireHeaders:!0,metadata:{openapi:{description:"Revoke all sessions for the user",responses:{"200":{description:"Success",content:{"application/json":{schema:{type:"object",properties:{status:{type:"boolean",description:"Indicates if all sessions were revoked successfully"}},required:["status"]}}}}}}}},async(e)=>{try{await e.context.internalAdapter.deleteUserSessions(e.context.session.user.id)}catch(t){throw e.context.logger.error(t&&typeof t==="object"&&"name"in t?t.name:"",t),l.from("INTERNAL_SERVER_ERROR",{message:"Internal Server Error",code:"INTERNAL_SERVER_ERROR"})}return e.json({status:!0})}),C1=v("/revoke-other-sessions",{method:"POST",requireHeaders:!0,use:[Gs],metadata:{openapi:{description:"Revoke all other sessions for the user except the current one",responses:{"200":{description:"Success",content:{"application/json":{schema:{type:"object",properties:{status:{type:"boolean",description:"Indicates if all other sessions were revoked successfully"}},required:["status"]}}}}}}}},async(e)=>{let t=e.context.session;if(!t.user)throw l.from("UNAUTHORIZED",{message:"Unauthorized",code:"UNAUTHORIZED"});let r=(await e.context.internalAdapter.listSessions(t.user.id)).filter((n)=>n.expiresAt>new Date).filter((n)=>n.token!==e.context.session.session.token);return await Promise.all(r.map((n)=>e.context.internalAdapter.deleteSession(n.token))),e.json({status:!0})});function Qy(e){return e}async function OT(e,t,r){let n={tokens:t,profile:r},i=e.accountSubject,o=await i(n),s=String(o);if(typeof o==="number"&&!Number.isFinite(o)||s.trim().length===0||s==="undefined"||s==="null")throw new y("OAUTH_ACCOUNT_SUBJECT_INVALID");return{providerId:e.id,accountId:s}}async function Yy(e,t,r){try{return await OT(e,t,r)}catch{throw l.from("UNAUTHORIZED",S.FAILED_TO_GET_USER_INFO)}}var Ri={NO_CODE:"no_code",PROVIDER_NOT_FOUND:"oauth_provider_not_found",ISSUER_MISSING:"issuer_missing",ISSUER_MISMATCH:"issuer_mismatch",INVALID_CODE:"invalid_code",NONCE_BINDING_MISSING:"nonce_binding_missing",UNABLE_TO_GET_USER_INFO:"unable_to_get_user_info",NO_CALLBACK_URL:"no_callback_url",UNABLE_TO_LINK_ACCOUNT:"unable_to_link_account",EMAIL_DOES_NOT_MATCH:"email_does_not_match",ACCOUNT_ALREADY_LINKED_TO_DIFFERENT_USER:"account_already_linked_to_different_user",EMAIL_NOT_FOUND:"email_not_found",EMAIL_NOT_VERIFIED:"email_not_verified"},rae="https://www.better-auth.com/docs/concepts/oauth#handling-providers-without-email";function cp(e,t,r,n){let i=new URLSearchParams({error:r});if(n)i.set("error_description",n);let o=us(t,i);throw e.redirect(o)}function Ml(e,t){return`${t?.source==="generic"?`Generic OAuth provider "${e}"`:`Provider "${e}"`} did not return an email${t?.source==="id_token"?" in the id token":""}. Either request the provider's email scope, or create a placeholder via \`mapProfileToUser\`. See ${rae}`}function nd(e,t){if(typeof e==="string")e=new TextEncoder().encode(e);if(typeof t==="string")t=new TextEncoder().encode(t);let r=new Uint8Array(e),n=new Uint8Array(t),i=r.length^n.length,o=Math.max(r.length,n.length);for(let s=0;s<o;s++)i|=(s<r.length?r[s]:0)^(s<n.length?n[s]:0);return i===0}var Ui=vt("a-z","0-9","A-Z","-_");/*! noble-ciphers - MIT License (c) 2023 Paul Miller (paulmillr.com) */function IT(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in e&&e.BYTES_PER_ELEMENT===1}var Xy=(e)=>e?`"${e}" `:"";function Zy(e,t=""){if(typeof e!=="boolean")throw TypeError(Xy(t)+"expected boolean, got type="+typeof e);return e}function dc(e,t=""){if(typeof e!=="number")throw TypeError(Xy(t)+"expected number, got "+typeof e);if(!Number.isSafeInteger(e)||e<0)throw RangeError(Xy(t)+"expected integer >= 0, got "+e);return e}function ai(e,t,r=""){if(IT(e)&&(t===void 0||e.length===t))return e;if(t!==void 0)dc(t,"length");let n=IT(e),i=t!==void 0?` of length ${t}`:"",o=n?`length=${e.length}`:`type=${typeof e}`,s=Xy(r)+"expected Uint8Array"+i+", got "+o;if(!n)throw TypeError(s);throw RangeError(s)}var O1=(e,t)=>{if(e===null||typeof e!=="object"||Array.isArray(e))throw TypeError(t==="object"?"expected valid options object":`"${t}" expected object, got type=${typeof e}`)};function DT(e,t=!0){if(e.destroyed)throw Error("hash was destroyed");if(t&&e.finished)throw Error("digest() was already called")}function D1(e,t){ai(e,void 0,"output");let r=t.outputLen;if(!(e.length>=r))throw RangeError('"output" expected length >= '+r)}function va(e){return new Uint32Array(e.buffer,e.byteOffset,Math.floor(e.byteLength/4))}function Ko(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function nae(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}var ds=(()=>new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68)();function iae(e){return e<<24&4278190080|e<<8&16711680|e>>>8&65280|e>>>24&255}function oae(e){for(let t=0;t<e.length;t++)e[t]=iae(e[t]);return e}var Jo=ds?(e)=>e:oae,U1=(()=>typeof Uint8Array.from([]).toHex==="function"&&typeof Uint8Array.fromHex==="function")(),sae=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));function P1(e){if(ai(e),U1)return e.toHex();let t="";for(let r=0;r<e.length;r++)t+=sae[e[r]];return t}function I1(e){return e>=48&&e<=57?e-48:e>=65&&e<=70?e-55:e>=97&&e<=102?e-87:void 0}function L1(e){if(typeof e!=="string")throw TypeError("hex string expected, got "+typeof e);if(U1)try{return Uint8Array.fromHex(e)}catch(i){if(i instanceof SyntaxError)throw RangeError(i.message);throw i}let t=e.length,r=t/2;if(t%2)throw RangeError("hex string expected, got unpadded hex of length "+t);let n=new Uint8Array(r);for(let i=0,o=0;i<r;i++,o+=2){let s=I1(e.charCodeAt(o)),a=I1(e.charCodeAt(o+1));if(s===void 0||a===void 0){let c=e[o]+e[o+1];throw RangeError('hex string expected, got non-hex character "'+c+'" at index '+o)}n[i]=s*16+a}return n}function M1(e){if(typeof e!=="string")throw TypeError("string expected");return new Uint8Array(new TextEncoder().encode(e))}function q1(e,t){if(!e.byteLength||!t.byteLength)return!1;return e.buffer===t.buffer&&e.byteOffset<t.byteOffset+t.byteLength&&t.byteOffset<e.byteOffset+e.byteLength}function B1(e,t){if(q1(e,t)&&e.byteOffset<t.byteOffset)throw Error("complex overlap of input and output is not supported")}function aae(...e){let t=0;for(let n=0;n<e.length;n++){let i=e[n];ai(i),t+=i.length}let r=new Uint8Array(t);for(let n=0,i=0;n<e.length;n++){let o=e[n];r.set(o,i),i+=o.length}return r}function j1(e,t){return O1(e,"defaults"),O1(t,"opts"),Object.assign(e,t)}function $1(e,t){if(e=ai(e),t=ai(t),e.length!==t.length)return!1;let r=0;for(let n=0;n<e.length;n++)r|=e[n]^t[n];return r===0}function F1(e,t,r){let n=t,i=r||(()=>[]),o=(a,c)=>n(c,...i(a)).update(a).digest(),s=n(new Uint8Array(e),...i(new Uint8Array(0)));return o.outputLen=s.outputLen,o.blockLen=s.blockLen,o.create=(a,...c)=>n(a,...c),o}var z1=(e,t)=>{function r(n,...i){if(ai(n,void 0,"key"),e.nonceLength!==void 0){let f=i[0];ai(f,e.varSizeNonce?void 0:e.nonceLength,"nonce")}let o=e.tagLength,s=e.nonceLength!==void 0?1:0;if(!e.withAAD){for(let f=s;f<i.length;f++)if(IT(i[f]))throw Error("AAD not supported")}if(e.withAAD&&i[s]!==void 0)ai(i[s],void 0,"AAD");let a=t(n,...i),c=(f,h)=>{if(h!==void 0){if(f!==2)throw Error("cipher output not supported");ai(h,void 0,"output")}},u=!1;return{encrypt(f,h){if(u)throw Error("cannot encrypt() twice with same key + nonce");return u=!0,ai(f,void 0,"data"),c(a.encrypt.length,h),a.encrypt(f,h)},decrypt(f,h){if(ai(f,void 0,"data"),o&&f.length<o)throw Error('"ciphertext" expected length >= tagLength='+o);return c(a.decrypt.length,h),a.decrypt(f,h)}}}return Object.assign(r,e),r};function up(e,t,r=!0){if(t===void 0)return new Uint8Array(e);if(ai(t,e,"output"),r&&!dp(t))throw Error("invalid output, must be aligned");return t}function W1(e,t,r){dc(e),dc(t),Zy(r);let n=new Uint8Array(16),i=nae(n);return i.setBigUint64(0,BigInt(t),r),i.setBigUint64(8,BigInt(e),r),n}function dp(e){return e.byteOffset%4===0}function ql(e){return Uint8Array.from(ai(e))}function H1(e=32){dc(e,"bytesLength");let t=typeof globalThis==="object"?globalThis.crypto:null;if(typeof t?.getRandomValues!=="function")throw Error("crypto.getRandomValues must be defined");if(e>65536)throw RangeError(`"bytesLength" expected <= 65536, got ${e}`);return t.getRandomValues(new Uint8Array(e))}function UT(e,t=H1){if(typeof e!=="function")throw TypeError('"fn" expected cipher constructor, got type='+typeof e);if(typeof t!=="function")throw TypeError('"randomBytes_" expected function, got type='+typeof t);let{nonceLength:r}=e;dc(r,"fn.nonceLength");let n=(o,s,a)=>{let c=aae(o,s);if(!q1(a,s))s.fill(0);return c},i=(o,...s)=>({encrypt(a){ai(a,void 0,"data");let c=t(r),u=e(o,c,...s).encrypt(a);if(u instanceof Promise)return u.then((d)=>n(c,d,a));return n(c,u,a)},decrypt(a){ai(a,void 0,"data");let c=a.subarray(0,r),u=a.subarray(r);return e(o,c,...s).decrypt(u)}});if("blockSize"in e)i.blockSize=e.blockSize;if("tagLength"in e)i.tagLength=e.tagLength;if("withAAD"in e)i.withAAD=e.withAAD;return i}var G1=(e)=>Uint8Array.from(e.split(""),(t)=>t.charCodeAt(0)),cae=(()=>Jo(va(G1("expand 16-byte k"))))(),uae=(()=>Jo(va(G1("expand 32-byte k"))))();function Rn(e,t){return e<<t|e>>>32-t}var lp=64,dae=16,PT=(()=>4294967295)(),V1=Uint32Array.of();function lae(e,t,r,n,i,o,s,a){let c=i.length,u=new Uint8Array(lp),d=va(u),f=ds&&dp(i)&&dp(o),h=f?va(i):V1,p=f?va(o):V1;if(!ds){for(let g=0;g<c;s++){if(e(t,r,n,d,s,a),Jo(d),s>=PT)throw Error("arx: counter overflow");let _=Math.min(lp,c-g);for(let R=0,O;R<_;R++)O=g+R,o[O]=i[O]^u[R];g+=_}return}for(let g=0;g<c;s++){if(e(t,r,n,d,s,a),s>=PT)throw Error("arx: counter overflow");let _=Math.min(lp,c-g);if(f&&_===lp){let R=g/4;if(g%4!==0)throw Error("arx: invalid block position");for(let O=0,I;O<dae;O++)I=R+O,p[I]=h[I]^d[O];g+=lp;continue}for(let R=0,O;R<_;R++)O=g+R,o[O]=i[O]^u[R];g+=_}}function K1(e,t){let{allowShortKeys:r,extendNonceFn:n,counterLength:i,counterRight:o,rounds:s}=j1({allowShortKeys:!1,counterLength:8,counterRight:!1,rounds:20},t);if(typeof e!=="function")throw Error("core must be a function");return dc(i),dc(s),Zy(o),Zy(r),(a,c,u,d,f=0)=>{ai(a,void 0,"key"),ai(c,void 0,"nonce"),ai(u,void 0,"data");let h=u.length,p=d!==void 0;if(d=up(h,d,!1),p)B1(u,d);if(dc(f),f<0||f>=PT)throw Error("arx: counter overflow");let g=[],_=a.length,R,O;if(_===32)g.push(R=ql(a)),O=uae;else if(_===16&&r)R=new Uint8Array(32),R.set(a),R.set(a,16),O=cae,g.push(R);else throw ai(a,32,"arx key"),Error("invalid key size");if(!ds||!dp(c))g.push(c=ql(c));let I=va(R);if(n){if(c.length!==24)throw Error("arx: extended nonce must be 24 bytes");let j=c.subarray(0,16);if(ds)n(O,I,va(j),I);else{let re=Jo(Uint32Array.from(O));n(re,I,va(j),I),Ko(re),Jo(I)}c=c.subarray(16)}else if(!ds)Jo(I);let Ne=16-i;if(Ne!==c.length)throw Error(`arx: nonce must be ${Ne} or 16 bytes`);if(Ne!==12){let j=new Uint8Array(12);j.set(c,o?0:12-c.length),c=j,g.push(c)}let k=Jo(va(c));try{return lae(e,O,I,k,u,d,f,s),d}finally{Ko(...g)}}}function Zi(e,t){return e[t++]&255|(e[t++]&255)<<8}class J1{blockLen=16;outputLen=16;buffer=new Uint8Array(16);r=new Uint16Array(10);h=new Uint16Array(10);pad=new Uint16Array(8);pos=0;finished=!1;destroyed=!1;constructor(e){e=ql(ai(e,32,"key"));let t=Zi(e,0),r=Zi(e,2),n=Zi(e,4),i=Zi(e,6),o=Zi(e,8),s=Zi(e,10),a=Zi(e,12),c=Zi(e,14);this.r[0]=t&8191,this.r[1]=(t>>>13|r<<3)&8191,this.r[2]=(r>>>10|n<<6)&7939,this.r[3]=(n>>>7|i<<9)&8191,this.r[4]=(i>>>4|o<<12)&255,this.r[5]=o>>>1&8190,this.r[6]=(o>>>14|s<<2)&8191,this.r[7]=(s>>>11|a<<5)&8065,this.r[8]=(a>>>8|c<<8)&8191,this.r[9]=c>>>5&127;for(let u=0;u<8;u++)this.pad[u]=Zi(e,16+2*u)}process(e,t,r=!1){let n=r?0:2048,{h:i,r:o}=this,s=o[0],a=o[1],c=o[2],u=o[3],d=o[4],f=o[5],h=o[6],p=o[7],g=o[8],_=o[9],R=Zi(e,t+0),O=Zi(e,t+2),I=Zi(e,t+4),Ne=Zi(e,t+6),k=Zi(e,t+8),j=Zi(e,t+10),re=Zi(e,t+12),Oe=Zi(e,t+14),ne=i[0]+(R&8191),M=i[1]+((R>>>13|O<<3)&8191),F=i[2]+((O>>>10|I<<6)&8191),ce=i[3]+((I>>>7|Ne<<9)&8191),de=i[4]+((Ne>>>4|k<<12)&8191),pe=i[5]+(k>>>1&8191),ae=i[6]+((k>>>14|j<<2)&8191),He=i[7]+((j>>>11|re<<5)&8191),Be=i[8]+((re>>>8|Oe<<8)&8191),Ke=i[9]+(Oe>>>5|n),Te=0,Ve=Te+ne*s+M*(5*_)+F*(5*g)+ce*(5*p)+de*(5*h);Te=Ve>>>13,Ve&=8191,Ve+=pe*(5*f)+ae*(5*d)+He*(5*u)+Be*(5*c)+Ke*(5*a),Te+=Ve>>>13,Ve&=8191;let Je=Te+ne*a+M*s+F*(5*_)+ce*(5*g)+de*(5*p);Te=Je>>>13,Je&=8191,Je+=pe*(5*h)+ae*(5*f)+He*(5*d)+Be*(5*u)+Ke*(5*c),Te+=Je>>>13,Je&=8191;let ft=Te+ne*c+M*a+F*s+ce*(5*_)+de*(5*g);Te=ft>>>13,ft&=8191,ft+=pe*(5*p)+ae*(5*h)+He*(5*f)+Be*(5*d)+Ke*(5*u),Te+=ft>>>13,ft&=8191;let qt=Te+ne*u+M*c+F*a+ce*s+de*(5*_);Te=qt>>>13,qt&=8191,qt+=pe*(5*g)+ae*(5*p)+He*(5*h)+Be*(5*f)+Ke*(5*d),Te+=qt>>>13,qt&=8191;let ot=Te+ne*d+M*u+F*c+ce*a+de*s;Te=ot>>>13,ot&=8191,ot+=pe*(5*_)+ae*(5*g)+He*(5*p)+Be*(5*h)+Ke*(5*f),Te+=ot>>>13,ot&=8191;let Tr=Te+ne*f+M*d+F*u+ce*c+de*a;Te=Tr>>>13,Tr&=8191,Tr+=pe*s+ae*(5*_)+He*(5*g)+Be*(5*p)+Ke*(5*h),Te+=Tr>>>13,Tr&=8191;let un=Te+ne*h+M*f+F*d+ce*u+de*c;Te=un>>>13,un&=8191,un+=pe*a+ae*s+He*(5*_)+Be*(5*g)+Ke*(5*p),Te+=un>>>13,un&=8191;let oi=Te+ne*p+M*h+F*f+ce*d+de*u;Te=oi>>>13,oi&=8191,oi+=pe*c+ae*a+He*s+Be*(5*_)+Ke*(5*g),Te+=oi>>>13,oi&=8191;let Kt=Te+ne*g+M*p+F*h+ce*f+de*d;Te=Kt>>>13,Kt&=8191,Kt+=pe*u+ae*c+He*a+Be*s+Ke*(5*_),Te+=Kt>>>13,Kt&=8191;let Ci=Te+ne*_+M*g+F*p+ce*h+de*f;Te=Ci>>>13,Ci&=8191,Ci+=pe*d+ae*u+He*c+Be*a+Ke*s,Te+=Ci>>>13,Ci&=8191,Te=(Te<<2)+Te|0,Te=Te+Ve|0,Ve=Te&8191,Te=Te>>>13,Je+=Te,i[0]=Ve,i[1]=Je,i[2]=ft,i[3]=qt,i[4]=ot,i[5]=Tr,i[6]=un,i[7]=oi,i[8]=Kt,i[9]=Ci}finalize(){let{h:e,pad:t}=this,r=new Uint16Array(10),n=e[1]>>>13;e[1]&=8191;for(let s=2;s<10;s++)e[s]+=n,n=e[s]>>>13,e[s]&=8191;e[0]+=n*5,n=e[0]>>>13,e[0]&=8191,e[1]+=n,n=e[1]>>>13,e[1]&=8191,e[2]+=n,r[0]=e[0]+5,n=r[0]>>>13,r[0]&=8191;for(let s=1;s<10;s++)r[s]=e[s]+n,n=r[s]>>>13,r[s]&=8191;r[9]-=8192;let i=(n^1)-1;for(let s=0;s<10;s++)r[s]&=i;i=~i;for(let s=0;s<10;s++)e[s]=e[s]&i|r[s];e[0]=(e[0]|e[1]<<13)&65535,e[1]=(e[1]>>>3|e[2]<<10)&65535,e[2]=(e[2]>>>6|e[3]<<7)&65535,e[3]=(e[3]>>>9|e[4]<<4)&65535,e[4]=(e[4]>>>12|e[5]<<1|e[6]<<14)&65535,e[5]=(e[6]>>>2|e[7]<<11)&65535,e[6]=(e[7]>>>5|e[8]<<8)&65535,e[7]=(e[8]>>>8|e[9]<<5)&65535;let o=e[0]+t[0];e[0]=o&65535;for(let s=1;s<8;s++)o=(e[s]+t[s]|0)+(o>>>16)|0,e[s]=o&65535;Ko(r)}update(e){DT(this),ai(e),e=ql(e);let{buffer:t,blockLen:r}=this,n=e.length;for(let i=0;i<n;){let o=Math.min(r-this.pos,n-i);if(o===r){for(;r<=n-i;i+=r)this.process(e,i);continue}if(t.set(e.subarray(i,i+o),this.pos),this.pos+=o,i+=o,this.pos===r)this.process(t,0,!1),this.pos=0}return this}destroy(){this.destroyed=!0,Ko(this.h,this.r,this.buffer,this.pad)}digestInto(e){DT(this),D1(e,this),this.finished=!0;let{buffer:t,h:r}=this,{pos:n}=this;if(n){t[n++]=1;for(;n<16;n++)t[n]=0;this.process(t,0,!0)}this.finalize();let i=0;for(let o=0;o<8;o++)e[i++]=r[o]>>>0,e[i++]=r[o]>>>8}digest(){let{buffer:e,outputLen:t}=this;this.digestInto(e);let r=e.slice(0,t);return this.destroy(),r}}var Q1=F1(32,(e)=>new J1(e));function Z1(e,t,r,n,i,o=20){let s=e[0],a=e[1],c=e[2],u=e[3],d=t[0],f=t[1],h=t[2],p=t[3],g=t[4],_=t[5],R=t[6],O=t[7],I=i,Ne=r[0],k=r[1],j=r[2],re=s,Oe=a,ne=c,M=u,F=d,ce=f,de=h,pe=p,ae=g,He=_,Be=R,Ke=O,Te=I,Ve=Ne,Je=k,ft=j;for(let ot=0;ot<o;ot+=2)re=re+F|0,Te=Rn(Te^re,16),ae=ae+Te|0,F=Rn(F^ae,12),re=re+F|0,Te=Rn(Te^re,8),ae=ae+Te|0,F=Rn(F^ae,7),Oe=Oe+ce|0,Ve=Rn(Ve^Oe,16),He=He+Ve|0,ce=Rn(ce^He,12),Oe=Oe+ce|0,Ve=Rn(Ve^Oe,8),He=He+Ve|0,ce=Rn(ce^He,7),ne=ne+de|0,Je=Rn(Je^ne,16),Be=Be+Je|0,de=Rn(de^Be,12),ne=ne+de|0,Je=Rn(Je^ne,8),Be=Be+Je|0,de=Rn(de^Be,7),M=M+pe|0,ft=Rn(ft^M,16),Ke=Ke+ft|0,pe=Rn(pe^Ke,12),M=M+pe|0,ft=Rn(ft^M,8),Ke=Ke+ft|0,pe=Rn(pe^Ke,7),re=re+ce|0,ft=Rn(ft^re,16),Be=Be+ft|0,ce=Rn(ce^Be,12),re=re+ce|0,ft=Rn(ft^re,8),Be=Be+ft|0,ce=Rn(ce^Be,7),Oe=Oe+de|0,Te=Rn(Te^Oe,16),Ke=Ke+Te|0,de=Rn(de^Ke,12),Oe=Oe+de|0,Te=Rn(Te^Oe,8),Ke=Ke+Te|0,de=Rn(de^Ke,7),ne=ne+pe|0,Ve=Rn(Ve^ne,16),ae=ae+Ve|0,pe=Rn(pe^ae,12),ne=ne+pe|0,Ve=Rn(Ve^ne,8),ae=ae+Ve|0,pe=Rn(pe^ae,7),M=M+F|0,Je=Rn(Je^M,16),He=He+Je|0,F=Rn(F^He,12),M=M+F|0,Je=Rn(Je^M,8),He=He+Je|0,F=Rn(F^He,7);let qt=0;n[qt++]=s+re|0,n[qt++]=a+Oe|0,n[qt++]=c+ne|0,n[qt++]=u+M|0,n[qt++]=d+F|0,n[qt++]=f+ce|0,n[qt++]=h+de|0,n[qt++]=p+pe|0,n[qt++]=g+ae|0,n[qt++]=_+He|0,n[qt++]=R+Be|0,n[qt++]=O+Ke|0,n[qt++]=I+Te|0,n[qt++]=Ne+Ve|0,n[qt++]=k+Je|0,n[qt++]=j+ft|0}function fae(e,t,r,n){let i=ds?e:Jo(e.slice(0,4)),o=ds?t:Jo(t.slice(0,8)),s=ds?r:Jo(r.slice(0,4)),a=new Uint32Array(16);Z1(i,o,s.subarray(1),a,s[0]);let c=0;if(n[c++]=a[0]-i[0]|0,n[c++]=a[1]-i[1]|0,n[c++]=a[2]-i[2]|0,n[c++]=a[3]-i[3]|0,n[c++]=a[12]-s[0]|0,n[c++]=a[13]-s[1]|0,n[c++]=a[14]-s[2]|0,n[c++]=a[15]-s[3]|0,Jo(n),!ds)Ko(i,o,s);Ko(a)}var hae=K1(Z1,{counterRight:!1,counterLength:8,extendNonceFn:fae,allowShortKeys:!1});var pae=new Uint8Array(16),Y1=(e,t)=>{e.update(t);let r=t.length%16;if(r)e.update(pae.subarray(r))},mae=new Uint8Array(32);function X1(e,t,r,n,i){if(i!==void 0)ai(i,void 0,"AAD");let o=e(t,r,mae),s=W1(n.length,i?i.length:0,!0),a=Q1.create(o);if(i)Y1(a,i);Y1(a,n),a.update(s);let c=a.digest();return Ko(o,s),c}var gae=(e)=>(t,r,n)=>({encrypt(o,s){let a=o.length;s=up(a+16,s,!1),s.set(o);let c=s.subarray(0,-16);e(t,r,c,c,1);let u=X1(e,t,r,c,n);return s.set(u,a),Ko(u),s},decrypt(o,s){s=up(o.length-16,s,!1);let a=o.subarray(0,-16),c=o.subarray(-16),u=X1(e,t,r,a,n);if(!$1(c,u))throw Ko(u),Error("invalid tag");return s.set(o.subarray(0,-16)),e(t,r,s,s,1),Ko(u),s}});var LT=z1({blockSize:64,nonceLength:24,tagLength:16,withAAD:!0},gae(hae));var tL={name:"HMAC",hash:"SHA-256"},rL="$ba$";function yae(e){if(!e.startsWith(rL))return null;let t=4,r=e.indexOf("$",t);if(r===-1)return null;let n=parseInt(e.slice(t,r),10);if(!Number.isInteger(n)||n<0)return null;return{version:n,ciphertext:e.slice(r+1)}}function wae(e,t){return`${rL}${e}$${t}`}async function eL(e,t){let r=await Ce("SHA-256").digest(e),n=M1(t);return P1(UT(LT)(new Uint8Array(r)).encrypt(n))}async function MT(e,t){let r=await Ce("SHA-256").digest(e),n=L1(t),i=UT(LT)(new Uint8Array(r));return new TextDecoder().decode(i.decrypt(n))}var ka=async({key:e,data:t})=>{if(typeof e==="string")return eL(e,t);let r=e.keys.get(e.currentVersion);if(!r)throw Error(`Secret version ${e.currentVersion} not found in keys`);let n=await eL(r,t);return wae(e.currentVersion,n)},Ra=async({key:e,data:t})=>{if(typeof e==="string")return MT(e,t);let r=yae(t);if(r){let n=e.keys.get(r.version);if(!n)throw Error(`Secret version ${r.version} not found in keys (key may have been retired)`);return MT(n,r.ciphertext)}if(e.legacySecret)return MT(e.legacySecret,t);throw Error("Cannot decrypt legacy bare-hex payload: no legacy secret available. Set BETTER_AUTH_SECRET for backwards compatibility.")},_ae=async(e)=>{let t=typeof e==="string"?new TextEncoder().encode(e):e;return await Ho().importKey("raw",t,tL,!1,["sign","verify"])},fp=async(e,t)=>{let r=await _ae(t),n=await Ho().sign(tL.name,r,new TextEncoder().encode(e));return btoa(String.fromCharCode(...new Uint8Array(n)))};function bae(e){if(e.startsWith("$ba$"))return!0;return e.length%2===0&&/^[0-9a-f]+$/i.test(e)}function ew(e,t){if(!e)return e;if(t.options.account?.encryptOAuthTokens){if(!bae(e))return e;return Ra({key:t.secretConfig,data:e})}return e}function Ni(e,t){if(t.options.account?.encryptOAuthTokens&&e)return ka({key:t.secretConfig,data:e});return e}function nu(e){if(!e.callbackPath)return`/callback/${e.id}`;return e.callbackPath.startsWith("/")?e.callbackPath:`/${e.callbackPath}`}function iu(e){if(!e)return;try{return e.clone()}catch{return new Request(e.url,{cache:e.cache,credentials:e.credentials,headers:e.headers,integrity:e.integrity,keepalive:e.keepalive,method:e.method,mode:e.mode,redirect:e.redirect,referrer:e.referrer,referrerPolicy:e.referrerPolicy,signal:e.signal})}}import*as Qo from"zod";async function lo(e,t,r,n=3600,i){return await Ty({email:t.toLowerCase(),updateTo:r?.toLowerCase(),...i},e,n)}async function qT(e,t){if(!e.context.options.emailVerification?.sendVerificationEmail)throw e.context.logger.error("Verification email isn't enabled."),l.from("BAD_REQUEST",S.VERIFICATION_EMAIL_NOT_ENABLED);let r=await lo(e.context.secret,t.email,void 0,e.context.options.emailVerification?.expiresIn),n=e.body.callbackURL?encodeURIComponent(e.body.callbackURL):encodeURIComponent("/"),i=`${e.context.baseURL}/verify-email?token=${r}&callbackURL=${n}`;await e.context.options.emailVerification.sendVerificationEmail({user:t,url:i,token:r},e.request)}var nL=v("/send-verification-email",{method:"POST",operationId:"sendVerificationEmail",cloneRequest:!0,body:Qo.object({email:Qo.email().meta({description:"The email to send the verification email to"}),callbackURL:Qo.string().meta({description:"The URL to use for email verification callback"}).optional()}),metadata:{openapi:{operationId:"sendVerificationEmail",description:"Send a verification email to the user",requestBody:{content:{"application/json":{schema:{type:"object",properties:{email:{type:"string",description:"The email to send the verification email to",example:"user@example.com"},callbackURL:{type:"string",description:"The URL to use for email verification callback",example:"https://example.com/callback",nullable:!0}},required:["email"]}}}},responses:{"200":{description:"Success",content:{"application/json":{schema:{type:"object",properties:{status:{type:"boolean",description:"Indicates if the email was sent successfully",example:!0}}}}}},"400":{description:"Bad Request",content:{"application/json":{schema:{type:"object",properties:{message:{type:"string",description:"Error message",example:"Verification email isn't enabled"}}}}}}}}}},async(e)=>{if(!e.context.options.emailVerification?.sendVerificationEmail)throw e.context.logger.error("Verification email isn't enabled."),l.from("BAD_REQUEST",S.VERIFICATION_EMAIL_NOT_ENABLED);let{email:t}=e.body,r=await Gr(e);if(!r){let i=Date.now(),o=await e.context.internalAdapter.findUserByEmail(t),s;if(!o||o.user.emailVerified)await lo(e.context.secret,t,void 0,e.context.options.emailVerification?.expiresIn);else try{await qT(e,o.user)}catch(c){s=c}let a=500-(Date.now()-i);if(a>0)await new Promise((c)=>setTimeout(c,a));if(s)throw s;return e.json({status:!0})}if(r?.user.email.toLowerCase()!==t.toLowerCase())throw l.from("BAD_REQUEST",S.EMAIL_MISMATCH);if(r?.user.emailVerified)throw l.from("BAD_REQUEST",S.EMAIL_ALREADY_VERIFIED);return await qT(e,r.user),e.json({status:!0})}),iL=v("/verify-email",{method:"GET",operationId:"verifyEmail",query:Qo.object({token:Qo.string().meta({description:"The token to verify the email"}),callbackURL:Qo.string().meta({description:"The URL to redirect to after email verification"}).optional()}),use:[eu((e)=>e.query.callbackURL)],metadata:{openapi:{description:"Verify the email of the user",parameters:[{name:"token",in:"query",description:"The token to verify the email",required:!0,schema:{type:"string"}},{name:"callbackURL",in:"query",description:"The URL to redirect to after email verification",required:!1,schema:{type:"string"}}],responses:{"200":{description:"Success",content:{"application/json":{schema:{type:"object",properties:{user:{type:"object",$ref:"#/components/schemas/User"},status:{type:"boolean",description:"Indicates if the email was verified successfully"}},required:["user","status"]}}}}}}}},async(e)=>{function t(a){if(e.query.callbackURL){let c=new URLSearchParams({error:a.code}),u=us(e.query.callbackURL,c);throw e.redirect(u)}throw l.from("UNAUTHORIZED",a)}let{token:r}=e.query,n;try{n=await V(r,new TextEncoder().encode(e.context.secret),{algorithms:["HS256"]})}catch(a){if(a instanceof tt)return t(S.TOKEN_EXPIRED);return t(S.INVALID_TOKEN)}let i=Qo.object({email:Qo.email(),updateTo:Qo.string().optional(),requestType:Qo.string().optional()}).parse(n.payload),o=await e.context.internalAdapter.findUserByEmail(i.email);if(!o)return t(S.USER_NOT_FOUND);if(i.updateTo){let a=await Gr(e);if(a&&a.user.email!==i.email)return t(S.INVALID_USER);switch(i.requestType){case"change-email-confirmation":{let c=await lo(e.context.secret,i.email,i.updateTo,e.context.options.emailVerification?.expiresIn,{requestType:"change-email-verification"}),u=e.query.callbackURL?encodeURIComponent(e.query.callbackURL):encodeURIComponent("/"),d=`${e.context.baseURL}/verify-email?token=${c}&callbackURL=${u}`;if(e.context.options.emailVerification?.sendVerificationEmail)await e.context.runInBackgroundOrAwait(e.context.options.emailVerification.sendVerificationEmail({user:{...o.user,email:i.updateTo},url:d,token:c},iu(e.request)));if(e.query.callbackURL)throw e.redirect(e.query.callbackURL);return e.json({status:!0})}case"change-email-verification":{let c=a;if(!c){let d=await e.context.internalAdapter.createSession(o.user.id);if(!d)throw l.from("INTERNAL_SERVER_ERROR",S.FAILED_TO_CREATE_SESSION);c={session:d,user:o.user}}let u=await e.context.internalAdapter.updateUserByEmail(i.email,{email:i.updateTo,emailVerified:!0});if(e.context.options.emailVerification?.afterEmailVerification)await e.context.options.emailVerification.afterEmailVerification(u,e.request);if(await ki(e,{session:c.session,user:{...c.user,email:i.updateTo,emailVerified:!0}}),e.query.callbackURL)throw e.redirect(e.query.callbackURL);return e.json({status:!0,user:Xn(e.context.options,u)})}default:{let c=a;if(!c){let h=await e.context.internalAdapter.createSession(o.user.id);if(!h)throw l.from("INTERNAL_SERVER_ERROR",S.FAILED_TO_CREATE_SESSION);c={session:h,user:o.user}}let u=await e.context.internalAdapter.updateUserByEmail(i.email,{email:i.updateTo,emailVerified:!1}),d=await lo(e.context.secret,i.updateTo),f=e.query.callbackURL?encodeURIComponent(e.query.callbackURL):encodeURIComponent("/");if(e.context.options.emailVerification?.sendVerificationEmail)await e.context.runInBackgroundOrAwait(e.context.options.emailVerification.sendVerificationEmail({user:u,url:`${e.context.baseURL}/verify-email?token=${d}&callbackURL=${f}`,token:d},iu(e.request)));if(await ki(e,{session:c.session,user:{...c.user,email:i.updateTo,emailVerified:!1}}),e.query.callbackURL)throw e.redirect(e.query.callbackURL);return e.json({status:!0,user:Xn(e.context.options,u)})}}}if(o.user.emailVerified){if(e.query.callbackURL)throw e.redirect(e.query.callbackURL);return e.json({status:!0,user:null})}if(e.context.options.emailVerification?.beforeEmailVerification)await e.context.options.emailVerification.beforeEmailVerification(o.user,e.request);let s=await e.context.internalAdapter.updateUserByEmail(i.email,{emailVerified:!0});if(e.context.options.emailVerification?.afterEmailVerification)await e.context.options.emailVerification.afterEmailVerification(s,e.request);if(e.context.options.emailVerification?.autoSignInAfterVerification){let a=await Gr(e);if(!a||a.user.email!==i.email){let c=await e.context.internalAdapter.createSession(o.user.id);if(!c)throw l.from("INTERNAL_SERVER_ERROR",S.FAILED_TO_CREATE_SESSION);await ki(e,{session:c,user:{...o.user,emailVerified:!0}})}else await ki(e,{session:a.session,user:{...a.user,emailVerified:!0}})}if(e.query.callbackURL)throw e.redirect(e.query.callbackURL);return e.json({status:!0,user:null})});function BT(e){if(Array.isArray(e))return e.map((t)=>typeof t==="string"?t.trim():"").filter(Boolean);if(typeof e==="string")return e.trim().split(/\s+/).filter(Boolean);return[]}function hp(e){let t=(r)=>new Date(new Date().getTime()+r*1000);return{tokenType:e.token_type,accessToken:e.access_token,refreshToken:e.refresh_token,accessTokenExpiresAt:e.expires_in?t(e.expires_in):void 0,refreshTokenExpiresAt:e.refresh_token_expires_in?t(e.refresh_token_expires_in):void 0,scopes:BT(e.scope),idToken:e.id_token,raw:e}}function jT(e,t){let r=e?e.split(",").map((i)=>i.trim()).filter(Boolean):[],n=(t??[]).map((i)=>i.trim()).filter(Boolean);return[...new Set([...r,...n])].join(",")}function fo(e){let t=Array.isArray(e)?e[0]:e;return typeof t==="string"&&t.length>0?t:void 0}async function pp(e){let t=new TextEncoder().encode(e),r=await crypto.subtle.digest("SHA-256",t);return po.encode(new Uint8Array(r),{padding:!1})}var $T=["state","client_id","redirect_uri","response_type","code_challenge","code_challenge_method","nonce","scope"],id=new Set($T);async function St({id:e,options:t,authorizationEndpoint:r,state:n,codeVerifier:i,scopes:o,claims:s,redirectURI:a,duration:c,prompt:u,accessType:d,responseType:f,display:h,loginHint:p,nonce:g,hd:_,responseMode:R,additionalParams:O,scopeJoiner:I}){t=typeof t==="function"?await t():t;let Ne=new URL(t.authorizationEndpoint||r);Ne.searchParams.set("response_type",f||"code");let k=fo(t.clientId);if(!k)throw Error("OAuth provider requires clientId");if(Ne.searchParams.set("client_id",k),Ne.searchParams.set("state",n),o?.length)Ne.searchParams.set("scope",o.join(I||" "));if(Ne.searchParams.set("redirect_uri",t.redirectURI||a),c&&Ne.searchParams.set("duration",c),h&&Ne.searchParams.set("display",h),p&&Ne.searchParams.set("login_hint",p),g&&Ne.searchParams.set("nonce",g),u&&Ne.searchParams.set("prompt",u),_&&Ne.searchParams.set("hd",_),d&&Ne.searchParams.set("access_type",d),R&&Ne.searchParams.set("response_mode",R),i){let j=await pp(i);Ne.searchParams.set("code_challenge_method","S256"),Ne.searchParams.set("code_challenge",j)}if(s){let j=s.reduce((re,Oe)=>(re[Oe]=null,re),{});Ne.searchParams.set("claims",JSON.stringify({id_token:{email:null,email_verified:null,...j}}))}if(O)for(let[j,re]of Object.entries(O)){if(id.has(j))continue;Ne.searchParams.set(j,re)}return Ne}import*as mp from"zod";var gp=mp.record(mp.string(),mp.string()).refine((e)=>!Object.keys(e).some((t)=>id.has(t)),{message:`additionalParams cannot include reserved OAuth parameters: ${$T.join(", ")}`}).meta({description:"Extra query parameters to append to the provider authorization URL (e.g. Cognito identity_provider, Google hd)."}).optional();var Eae=/^Basic +(.*)$/i;function oL(e){return new URLSearchParams({v:e}).toString().slice(2)}function sL(e){let t=new URLSearchParams(`v=${e}`).get("v");if(t===null)throw Error("form-url-encoded value could not be decoded");return t}function FT(e,t){let r=`${oL(e)}:${oL(t)}`;return`Basic ${fe.encode(r)}`}function zT(e){let t=e.match(Eae);if(!t)throw Error("Authorization header is not a Basic credential");let r=t[1]??"",n=new TextDecoder().decode(fe.decode(r)),i=n.indexOf(":");if(i===-1)throw Error("Basic credential is missing the client id/secret separator");let o=n.slice(0,i),s=n.slice(i+1);if(!o||!s)throw Error("Basic credential client id and secret must both be non-empty");return{clientId:sL(o),clientSecret:sL(s)}}var od=["RS256","RS384","RS512","PS256","PS384","PS512","ES256","ES384","ES512","EdDSA"];var sd="urn:ietf:params:oauth:client-assertion-type:jwt-bearer";async function WT({getClientAssertion:e,context:t}){return{client_assertion:await e(t),client_assertion_type:sd}}var Sae=class extends Error{constructor(e,t,r){super(t||e.toString(),{cause:r});this.status=e,this.statusText=t,this.error=r,Error.captureStackTrace(this,this.constructor)}},Aae=async(e,t)=>{let r=t||{},n={onRequest:[t===null||t===void 0?void 0:t.onRequest],onResponse:[t===null||t===void 0?void 0:t.onResponse],onSuccess:[t===null||t===void 0?void 0:t.onSuccess],onError:[t===null||t===void 0?void 0:t.onError],onRetry:[t===null||t===void 0?void 0:t.onRetry]};if(!t||!(t===null||t===void 0?void 0:t.plugins))return{url:e,options:r,hooks:n};for(let d of(t===null||t===void 0?void 0:t.plugins)||[]){var i,o,s,a,c;if(d.init){var u;let f=await((u=d.init)===null||u===void 0?void 0:u.call(d,e.toString(),r));r=f.options||r,e=f.url}n.onRequest.push((i=d.hooks)===null||i===void 0?void 0:i.onRequest),n.onResponse.push((o=d.hooks)===null||o===void 0?void 0:o.onResponse),n.onSuccess.push((s=d.hooks)===null||s===void 0?void 0:s.onSuccess),n.onError.push((a=d.hooks)===null||a===void 0?void 0:a.onError),n.onRetry.push((c=d.hooks)===null||c===void 0?void 0:c.onRetry)}return{url:e,options:r,hooks:n}},aL=class{constructor(e){this.options=e}shouldAttemptRetry(e,t){if(this.options.shouldRetry)return Promise.resolve(e<this.options.attempts&&this.options.shouldRetry(t));return Promise.resolve(e<this.options.attempts)}getDelay(){return this.options.delay}},Tae=class{constructor(e){this.options=e}shouldAttemptRetry(e,t){if(this.options.shouldRetry)return Promise.resolve(e<this.options.attempts&&this.options.shouldRetry(t));return Promise.resolve(e<this.options.attempts)}getDelay(e){return Math.min(this.options.maxDelay,this.options.baseDelay*2**e)}};function vae(e){if(typeof e==="number")return new aL({type:"linear",attempts:e,delay:1000});switch(e.type){case"linear":return new aL(e);case"exponential":return new Tae(e);default:throw Error("Invalid retry strategy")}}var kae=["get","post","put","patch","delete"];function lL(e){if(!e.startsWith("@"))return{method:void 0,path:e};let t=e.indexOf("/"),r=e.slice(1,t===-1?void 0:t);if(!kae.includes(r))return{method:void 0,path:e};return{method:r,path:t===-1?e:e.slice(t+1)}}var Rae=(e)=>e==="."||e==="..",Nae=(e)=>e.split(":").map((t)=>encodeURIComponent(t)).join(":");function xae(e,t){let r=t.get(e);if(r===void 0)return Nae(e);if(Rae(r))throw TypeError("Path parameters cannot be reserved path segments");return encodeURIComponent(r)}function Cae(e,t){let{baseURL:r,params:n,query:i}=t||{query:{},params:{},baseURL:""},o=e.startsWith("http")?e.split("/").slice(0,3).join("/"):r||"",{path:s}=lL(e);if(s!==e)e=`/${s}`;if(!o.endsWith("/"))o+="/";let[a,c]=e.replace(o,"").split("?"),u=new URLSearchParams(c);for(let[h,p]of Object.entries(i||{})){if(p==null)continue;let g;if(typeof p==="string")g=p;else if(Array.isArray(p)){for(let _ of p)u.append(h,_);continue}else g=JSON.stringify(p);u.set(h,g)}let d=new Map;if(n)if(Array.isArray(n)){let h=a.split("/").filter((p)=>p.startsWith(":"));for(let[p,g]of h.entries()){let _=n[p];d.set(g,String(_))}}else for(let[h,p]of Object.entries(n))d.set(`:${h}`,String(p));a=a.split("/").map((h)=>xae(h,d)).join("/"),a=a.replace(/^\/+/,"");let f=u.toString();if(f=f.length>0?`?${f}`.replace(/\+/g,"%20"):"",!o.startsWith("http"))return`${o}${a}${f}`;return new URL(`${a}${f}`,o)}var Oae=async(e)=>{let t={},r=async(n)=>typeof n==="function"?await n():n;if(e===null||e===void 0?void 0:e.auth){if(e.auth.type==="Bearer"){let n=await r(e.auth.token);if(!n)return t;t.authorization=`Bearer ${n}`}else if(e.auth.type==="Basic"){let[n,i]=await Promise.all([r(e.auth.username),r(e.auth.password)]);if(!n||!i)return t;t.authorization=`Basic ${btoa(`${n}:${i}`)}`}else if(e.auth.type==="Custom"){let[n,i]=await Promise.all([r(e.auth.prefix),r(e.auth.value)]);if(!i)return t;t.authorization=`${n!==null&&n!==void 0?n:""} ${i}`}}return t},Iae=/^application\/(?:[\w!#$%&*.^`~-]*\+)?json(;.+)?$/i;function Dae(e){let t=e.headers.get("content-type"),r=new Set(["image/svg","application/xml","application/xhtml","application/html"]);if(!t)return"json";let n=t.split(";").shift()||"";if(Iae.test(n))return"json";if(r.has(n)||n.startsWith("text/"))return"text";return"blob"}function Uae(e){try{return JSON.parse(e),!0}catch(t){return!1}}function fL(e){if(e===void 0)return!1;let t=typeof e;if(t==="string"||t==="number"||t==="boolean"||t===null)return!0;if(t!=="object")return!1;if(Array.isArray(e))return!0;if(e.buffer)return!1;return e.constructor&&e.constructor.name==="Object"||typeof e.toJSON==="function"}function cL(e){try{return JSON.parse(e)}catch(t){return e}}function uL(e){return typeof e==="function"}function Pae(e){if(e===null||e===void 0?void 0:e.customFetchImpl)return e.customFetchImpl;if(typeof globalThis<"u"&&uL(globalThis.fetch))return globalThis.fetch;if(typeof window<"u"&&uL(window.fetch))return window.fetch;throw Error("No fetch implementation found")}function Lae(...e){let t={};for(let r of e){if(!r)continue;if(r instanceof Headers)r.forEach((n,i)=>{t[i]=n});else{let n=Array.isArray(r)?r:Object.entries(r);for(let[i,o]of n)if(o!==null&&o!==void 0)t[i]=o}}return t}async function Mae(e){let t=new Headers(Lae(e===null||e===void 0?void 0:e.headers,await Oae(e)));if(!t.has("content-type")){let r=qae(e===null||e===void 0?void 0:e.body);if(r)t.set("content-type",r)}return t}function qae(e){if(fL(e))return"application/json";return null}function Bae(e){let t=e.get("content-type");return t?t.split(";")[0].trim().toLowerCase():null}function jae(e,t){let{body:r}=e;if(!r)return null;if(!fL(r))return r;if(typeof r==="string")return r;if(Bae(t)==="application/x-www-form-urlencoded")return new URLSearchParams(r).toString();return JSON.stringify(r)}function $ae(e,t){if(t===null||t===void 0?void 0:t.method)return t.method.toUpperCase();let{method:r}=lL(e);if(r)return r.toUpperCase();return(t===null||t===void 0?void 0:t.body)?"POST":"GET"}function Fae(e,t){let r;if(!(e===null||e===void 0?void 0:e.signal)&&(e===null||e===void 0?void 0:e.timeout))r=setTimeout(()=>t===null||t===void 0?void 0:t.abort(),e===null||e===void 0?void 0:e.timeout);return{abortTimeout:r,clearTimeout:()=>{if(r)clearTimeout(r)}}}var zae=class e extends Error{constructor(t,r){super(r||JSON.stringify(t,null,2));this.issues=t,Object.setPrototypeOf(this,e.prototype)}};async function Wae(e,t){let r=await e["~standard"].validate(t);if(r.issues)throw new zae(r.issues);return r.value}function yp(e){return yp=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},yp(e)}function Hae(e,t){if(yp(e)!="object"||!e)return e;var r=e[Symbol.toPrimitive];if(r!==void 0){var n=r.call(e,t||"default");if(yp(n)!="object")return n;throw TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}function Vae(e){var t=Hae(e,"string");return yp(t)=="symbol"?t:t+""}function Gae(e,t,r){return(t=Vae(t))in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function dL(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(i){return Object.getOwnPropertyDescriptor(e,i).enumerable})),r.push.apply(r,n)}return r}function Oo(e){for(var t=1;t<arguments.length;t++){var r=arguments[t]!=null?arguments[t]:{};t%2?dL(Object(r),!0).forEach(function(n){Gae(e,n,r[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):dL(Object(r)).forEach(function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(r,n))})}return e}var w=async(e,t)=>{var r,n,i;let{hooks:o,url:s,options:a}=await Aae(e,t),c=Pae(a),u=new AbortController,d=(r=a.signal)!==null&&r!==void 0?r:u.signal,f=Cae(s,a),h=await Mae(a),p=jae(a,h),g=$ae(s,a),_=Oo(Oo({},a),{},{url:f,headers:h,body:p,method:g,signal:d});for(let pe of o.onRequest)if(pe){let ae=await pe(_);if(typeof ae==="object"&&ae!==null)Object.assign(_,ae)}if("pipeTo"in _&&typeof _.pipeTo==="function"||typeof(t===null||t===void 0||(n=t.body)===null||n===void 0?void 0:n.pipe)==="function"){if(!("duplex"in _))_.duplex="half"}let{clearTimeout:R}=Fae(a,u),O=await c(_.url,_);R();let I={response:O,request:_};for(let pe of o.onResponse)if(pe){var Ne;let ae=await pe(Oo(Oo({},I),{},{response:(t===null||t===void 0||(Ne=t.hookOptions)===null||Ne===void 0?void 0:Ne.cloneResponse)?O.clone():O}));if(ae instanceof Response)O=ae;else if(typeof ae==="object"&&ae!==null)O=ae.response}if(O.ok){if(_.method==="HEAD")return{data:"",error:null};let pe=Dae(O),ae={data:null,response:O,request:_};if(pe==="json"||pe==="text"){var k;let He=await O.text();ae.data=await((k=_.jsonParser)!==null&&k!==void 0?k:cL)(He)}else ae.data=await O[pe]();if(_===null||_===void 0?void 0:_.output){if(_.output&&!_.disableValidation)ae.data=await Wae(_.output,ae.data)}for(let He of o.onSuccess)if(He){var j;await He(Oo(Oo({},ae),{},{response:(t===null||t===void 0||(j=t.hookOptions)===null||j===void 0?void 0:j.cloneResponse)?O.clone():O}))}if(t===null||t===void 0?void 0:t.throw)return ae.data;return{data:ae.data,error:null}}let re=(i=t===null||t===void 0?void 0:t.jsonParser)!==null&&i!==void 0?i:cL,Oe=await O.text(),ne=Uae(Oe),M=ne?await re(Oe):null,F={response:O,responseText:Oe,request:_,error:Oo(Oo({},M),{},{status:O.status,statusText:O.statusText})};for(let pe of o.onError)if(pe){var ce;await pe(Oo(Oo({},F),{},{response:(t===null||t===void 0||(ce=t.hookOptions)===null||ce===void 0?void 0:ce.cloneResponse)?O.clone():O}))}if(t===null||t===void 0?void 0:t.retry){var de;let pe=vae(t.retry),ae=(de=t.retryAttempt)!==null&&de!==void 0?de:0;if(await pe.shouldAttemptRetry(ae,O)){for(let Be of o.onRetry)if(Be)await Be(I);let He=pe.getDelay(ae);return await new Promise((Be)=>setTimeout(Be,He)),await w(e,Oo(Oo({},t),{},{retryAttempt:ae+1}))}}if(t===null||t===void 0?void 0:t.throw)throw new Sae(O.status,O.statusText,ne?M:Oe);return{data:null,error:Oo(Oo({},M),{},{status:O.status,statusText:O.statusText})}};var Kae=new Set([301,302,303,307,308]);function Jae(e){return e.type==="opaqueredirect"||Kae.has(e.status)}function hL(e){return new y(`The OAuth endpoint "${e}" returned an HTTP redirect. Server-side OAuth fetches refuse redirects to prevent SSRF; configure the final endpoint URL.`)}async function Bl(e,t){let r=!1,n=t?.onError,i=await w(e,{...t,redirect:"manual",async onError(o){if(Jae(o.response))r=!0;await n?.(o)}}).catch((o)=>{if(r)throw hL(e);throw o});if(r)throw hL(e);return i}function Qae(e,t){if(t==="basic")return{method:"client_secret_basic"};if(e.clientSecret)return{method:"client_secret_post"};return{method:"none"}}function HT(e,t,r){if(t.clientSecret||r.has("client_secret"))throw Error(`${e} token endpoint authentication cannot be combined with clientSecret`)}function tw(e,t){if(t)e.set("client_id",t)}function mL(e,t){if(!t.clientSecret)throw Error(`${e} token endpoint authentication requires clientSecret`)}function rw(e,t){if(!t)throw Error(`${e} token endpoint authentication requires clientId`)}function Yae({body:e,options:t,clientId:r,requireClientSecret:n}){if(n)mL("client_secret_post",t);if(t.clientSecret)rw("client_secret_post",r),tw(e,r),e.set("client_secret",t.clientSecret)}function Xae({headers:e,options:t,clientId:r,body:n}){if(n.has("client_secret"))throw Error("client_secret_basic token endpoint authentication cannot be combined with client_secret body parameters");mL("client_secret_basic",t),rw("client_secret_basic",r),e.authorization=FT(r,t.clientSecret)}function pL(e){if(e.has("client_assertion")!==e.has("client_assertion_type"))throw Error("client_assertion and client_assertion_type must both be provided")}async function nw({body:e,headers:t,options:r,tokenEndpoint:n,grantType:i,tokenEndpointAuth:o,authentication:s}){pL(e);let a=fo(r.clientId);if(e.has("client_assertion")){if(o)throw Error("client_assertion body parameters cannot be combined with tokenEndpointAuth");HT("private_key_jwt",r,e),tw(e,a);return}let c=o??Qae(r,s);if(c.method==="custom"){await c.customizeRequest({body:e,headers:t,options:r,tokenEndpoint:n,grantType:i}),pL(e);return}if(c.method==="private_key_jwt"){if(HT(c.method,r,e),rw(c.method,a),!n)throw Error("private_key_jwt token endpoint authentication requires tokenEndpoint");let u=await WT({getClientAssertion:c.getClientAssertion,context:{clientId:a,tokenEndpoint:n,grantType:i}});tw(e,a);for(let[d,f]of Object.entries(u))e.set(d,f);return}if(c.method==="none"){if(HT(c.method,r,e),i==="client_credentials")throw Error("none token endpoint authentication cannot be used with client_credentials grant");rw(c.method,a),tw(e,a);return}if(c.method==="client_secret_basic"){Xae({headers:t,options:r,clientId:a,body:e});return}Yae({body:e,options:r,clientId:a,requireClientSecret:o?.method==="client_secret_post"})}var gL="dpop+jwt",Ot=["EdDSA","ES256","ES512","PS256","RS256"],Zae=300,ece=512,tce=new Set(["d","p","q","dp","dq","qi","oth","k"]);function GT(){let e=new Map;return{reserve({key:t,expiresAt:r,now:n}){let i=n.getTime();for(let[o,s]of e)if(s<=i)e.delete(o);if(e.has(t))return!1;return e.set(t,r.getTime()),!0}}}function ow(e){return{reserve:({key:t,expiresAt:r})=>e.reserveVerificationValue({identifier:`dpop-proof:${t}`,value:t,expiresAt:r})}}function xi(e,t){return Object.assign(Error(t),{code:e})}function sw(e){return e instanceof Error&&"code"in e&&e.code==="invalid_dpop_proof"}function _p(e){if(!e)return;let t=e.trim();if(!t)return;let r=/^([A-Za-z][A-Za-z0-9!#$%&'*+.^_`|~-]*)\s+(.+)$/.exec(t);if(!r)return{scheme:"Unknown",token:t};let n=r[1]??"",i=r[2]?.trim()??"";if(n.toLowerCase()==="bearer")return{scheme:"Bearer",token:i};if(n.toLowerCase()==="dpop")return{scheme:"DPoP",token:i};return{scheme:"Unknown",token:t}}function bp(e){return _p(e)?.token??e}function VT(e){let t=new URL(e);if(t.hash)throw Error("DPoP proof htu must not contain a fragment");return`${t.origin}${t.pathname}`}async function yL(e){let t=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(e));return B(new Uint8Array(t))}async function wL(e){return It(e,"sha256")}function Ep(e){if(!e||typeof e!=="object"||Array.isArray(e))return;let t=e.jkt;return typeof t==="string"&&t.length>0?t:void 0}function Sp(e){return Ep(e.cnf)}function iw(e,t){let r=e[t];return typeof r==="string"&&r.length>0?r:void 0}function rce(e,t){let r=e[t];return typeof r==="number"&&Number.isFinite(r)?r:void 0}function nce(e,t){if(!e||e==="none"||e.startsWith("HS"))throw xi("invalid_dpop_proof","DPoP proof must use an asymmetric JWS algorithm");if(!t.includes(e))throw xi("invalid_dpop_proof","DPoP proof uses an unsupported JWS algorithm")}function ice(e){if(!e||typeof e!=="object"||Array.isArray(e))throw xi("invalid_dpop_proof","DPoP proof header must include a public jwk");if(e.kty==="oct")throw xi("invalid_dpop_proof","DPoP proof jwk must be asymmetric");for(let t of tce)if(t in e)throw xi("invalid_dpop_proof","DPoP proof jwk must not contain private key material")}async function oce(e){let t=`${e.jkt}
138
+ ${e.htm}
139
+ ${e.htu}
140
+ ${e.jti}`,r=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(t));return B(new Uint8Array(r))}async function sce(e,t){if(!e)return;if(!await e.reserve(t))throw xi("invalid_dpop_proof","DPoP proof jti has already been used")}async function aw({proofJwt:e,method:t,url:r,accessToken:n,expectedJkt:i,requireAth:o=!1,nowSeconds:s=Math.floor(Date.now()/1000),proofMaxAgeSeconds:a=Zae,signingAlgorithms:c=Ot,replayStore:u}){if(!e||e.split(".").length!==3)throw xi("invalid_dpop_proof","DPoP proof must be a compact JWT");let d;try{d=ue(e)}catch(re){throw xi("invalid_dpop_proof",re instanceof Error?re.message:"DPoP proof header is invalid")}if(d.typ!=="dpop+jwt")throw xi("invalid_dpop_proof",'DPoP proof typ must be "dpop+jwt"');nce(d.alg,c),ice(d.jwk);let f;try{f=(await V(e,await te(d.jwk,d.alg),{typ:gL})).payload}catch(re){throw xi("invalid_dpop_proof",re instanceof Error?re.message:"DPoP proof signature is invalid")}let h=iw(f,"htm"),p=iw(f,"htu"),g=iw(f,"jti"),_=rce(f,"iat");if(!h||!p||!g||_===void 0)throw xi("invalid_dpop_proof","DPoP proof must include htm, htu, jti, and iat claims");if(g.length>ece)throw xi("invalid_dpop_proof","DPoP proof jti is too large");if(h.toUpperCase()!==t.toUpperCase())throw xi("invalid_dpop_proof","DPoP proof htm does not match the request method");let R,O;try{R=VT(r),O=VT(p)}catch(re){throw xi("invalid_dpop_proof",re instanceof Error?re.message:"DPoP proof htu is invalid")}if(O!==R)throw xi("invalid_dpop_proof","DPoP proof htu does not match the request URL");if(_>s+5||s-_>a)throw xi("invalid_dpop_proof","DPoP proof iat is outside the accepted window");let I=iw(f,"ath");if(o&&!I)throw xi("invalid_dpop_proof","DPoP proof must include an ath claim");if(n!==void 0){if(I!==await yL(n))throw xi("invalid_dpop_proof","DPoP proof ath does not match the access token")}let Ne=await wL(d.jwk);if(i!==void 0&&Ne!==i)throw xi("invalid_dpop_proof","DPoP proof key does not match the bound token");let k=await oce({jkt:Ne,htm:h.toUpperCase(),htu:R,jti:g}),j=new Date((_+a)*1000);return await sce(u,{key:k,expiresAt:j,now:new Date(s*1000)}),{jwk:d.jwk,jkt:Ne,jti:g,htm:h,htu:R,iat:_,ath:I,replayKey:k,expiresAt:j}}function wp(e,t){return Object.assign(Error(t),{code:e})}function cw(e){return e instanceof Error&&"code"in e&&(e.code==="invalid_token"||e.code==="invalid_dpop_proof")}async function uw({payload:e,authorization:t,proofJwt:r,method:n,url:i,replayStore:o,proofMaxAgeSeconds:s,signingAlgorithms:a}){let c=Sp(e);if(!c){if(t.scheme==="DPoP")throw wp("invalid_token","DPoP authorization requires a DPoP-bound access token");return}if(t.scheme!=="DPoP")throw wp("invalid_token","DPoP-bound access token requires the DPoP authorization scheme");if(!r)throw wp("invalid_dpop_proof","DPoP proof header is required");try{await aw({proofJwt:r,method:n,url:i,accessToken:t.token,expectedJkt:c,requireAth:!0,proofMaxAgeSeconds:s,signingAlgorithms:a,replayStore:o})}catch(u){if(sw(u))throw wp("invalid_dpop_proof",u.message);throw u}}var ace=new Set(["grant_type","refresh_token","__proto__","constructor","prototype"]);async function cce({refreshToken:e,options:t,authentication:r,tokenEndpointAuth:n,tokenEndpoint:i,extraParams:o,resource:s}){t=typeof t==="function"?await t():t;let a=dce({refreshToken:e,options:t,extraParams:o,resource:s});return await nw({body:a.body,headers:a.headers,options:t,tokenEndpoint:i??"",grantType:"refresh_token",tokenEndpointAuth:n,authentication:r}),a}function uce(e,t){if(!t)return;for(let[r,n]of Object.entries(t)){if(ace.has(r))continue;e.set(r,n)}}function dce({refreshToken:e,options:t,extraParams:r,resource:n}){let i=new URLSearchParams,o={"content-type":"application/x-www-form-urlencoded",accept:"application/json"};if(i.set("grant_type","refresh_token"),i.set("refresh_token",e),n)if(typeof n==="string")i.append("resource",n);else for(let s of n)i.append("resource",s);if(r)uce(i,r);return{body:i,headers:o}}async function At({refreshToken:e,options:t,tokenEndpoint:r,authentication:n,tokenEndpointAuth:i,extraParams:o,resource:s}){let{body:a,headers:c}=await cce({refreshToken:e,options:t,authentication:n,tokenEndpointAuth:i,tokenEndpoint:r,extraParams:o,resource:s}),{data:u,error:d}=await Bl(r,{method:"POST",body:a,headers:c});if(d)throw d;let f={accessToken:u.access_token,refreshToken:u.refresh_token,tokenType:u.token_type,scopes:BT(u.scope),idToken:u.id_token};if(u.expires_in)f.accessTokenExpiresAt=new Date(new Date().getTime()+u.expires_in*1000);if(u.refresh_token_expires_in)f.refreshTokenExpiresAt=new Date(new Date().getTime()+u.refresh_token_expires_in*1000);return f}var NFe=new Set([Et.code,yt.code,Lt.code]);var lce=new Map,fce=new WeakMap,hce=300000,pce=30000,bL=5000;function _L(e,t){let r=e.get(t);if(!r)r={fetchedAt:0,refetchedAt:0},e.set(t,r);return r}function EL(e,t){return e.pending!==void 0&&t-e.pending.startedAt<bL}async function SL(e,t){let r=Date.now();if(!e.pending||!EL(e,r)){let s={startedAt:r,promise:gce(t).then((a)=>{if(r>=e.fetchedAt)e.jwks=a,e.fetchedAt=r;return a}).finally(()=>{if(e.pending===s)e.pending=void 0})};e.pending=s}let{promise:n,startedAt:i}=e.pending,o;try{return await Promise.race([n,new Promise((s,a)=>{o=setTimeout(()=>a(new Et),i+bL-r)})])}finally{clearTimeout(o)}}async function mce(e,t,r){if(e.jwks!==t)return e.jwks;let n=Date.now();if(!EL(e,n)){if(n-e.refetchedAt<pce)return;e.refetchedAt=n}return SL(e,r)}async function gce(e){try{let t=typeof e==="string"?await Bl(e,{headers:{Accept:"application/json"}}).then(async(r)=>{if(r.error)throw Error(`Jwks failed: ${r.error.message??r.error.statusText}`);return r.data}):await e();if(!t)throw Error("No jwks found");return t}catch(t){if(t instanceof TypeError){try{T.error("JWKS fetch failed:",t)}catch{}throw Error("JWKS fetch failed")}throw t}}var xFe=GT();async function jl(e,t){return(await yce(e,t)).jwks}async function yce(e,t){let r;try{r=ue(e)}catch(a){if(a instanceof Error)throw a;throw Error(a)}let n=r.kid,i=typeof t.jwksFetch==="string"?_L(lce,t.jwksFetch):t.jwksCacheKey?_L(fce,t.jwksCacheKey):{fetchedAt:0,refetchedAt:0},o=Date.now()-i.fetchedAt<hce?i.jwks:void 0;if(!o)return{jwks:await SL(i,t.jwksFetch),kid:n};let s=(a)=>mce(i,a,t.jwksFetch);if(!n||o.keys.some((a)=>a.kid===n))return{jwks:o,kid:n,refresh:s};return{jwks:await s(o)??o,kid:n}}async function JT({code:e,codeVerifier:t,redirectURI:r,options:n,authentication:i,tokenEndpointAuth:o,tokenEndpoint:s,deviceId:a,headers:c,additionalParams:u={},resource:d}){n=typeof n==="function"?await n():n;let f=wce({code:e,codeVerifier:t,redirectURI:r,options:n,deviceId:a,headers:c,additionalParams:u,resource:d});return await nw({body:f.body,headers:f.headers,options:n,tokenEndpoint:s??"",grantType:"authorization_code",tokenEndpointAuth:o,authentication:i}),f}function wce({code:e,codeVerifier:t,redirectURI:r,options:n,deviceId:i,headers:o,additionalParams:s={},resource:a}){let c=new URLSearchParams,u={"content-type":"application/x-www-form-urlencoded",accept:"application/json",...o};if(c.set("grant_type","authorization_code"),c.set("code",e),t&&c.set("code_verifier",t),n.clientKey&&c.set("client_key",n.clientKey),i&&c.set("device_id",i),c.set("redirect_uri",n.redirectURI||r),a)if(typeof a==="string")c.append("resource",a);else for(let d of a)c.append("resource",d);for(let[d,f]of Object.entries(s))if(!c.has(d))c.append(d,f);return{body:c,headers:u}}async function Tt({code:e,codeVerifier:t,redirectURI:r,options:n,tokenEndpoint:i,authentication:o,tokenEndpointAuth:s,deviceId:a,headers:c,additionalParams:u={},resource:d}){let{body:f,headers:h}=await JT({code:e,codeVerifier:t,redirectURI:r,options:n,authentication:o,tokenEndpointAuth:s,tokenEndpoint:i,deviceId:a,headers:c,additionalParams:u,resource:d}),{data:p,error:g}=await Bl(i,{method:"POST",body:f,headers:h});if(g)throw g;return hp(p)}var _ce=30,bce=["iss","sub","aud","exp","iat"];function Ece(e){return{issuer:e.issuer,audience:e.audience,algorithms:e.algorithms,maxTokenAge:e.maxTokenAge,requiredClaims:bce,clockTolerance:_ce}}async function Sce(e){let t=new TextEncoder().encode(e),r=await crypto.subtle.digest("SHA-256",t);return Array.from(new Uint8Array(r)).map((n)=>n.toString(16).padStart(2,"0")).join("")}async function Ace(e,t,r="exact"){if(typeof e!=="string")return!1;if(e===t)return!0;if(r==="exact-or-sha256")return e===await Sce(t);return!1}async function Tce(e,t,r){if(![t.audience].flat().some(Boolean))throw Error("ID token audience is not configured");let n=await V(e,t.jwks,Ece(t));if(r&&!await Ace(n.payload.nonce,r,t.nonceComparison))throw Error("ID token nonce does not match");if(t.verifyClaims&&!t.verifyClaims(n.payload))throw Error("ID token claims were rejected");return n}function Ap(e){let t=e.options??{};if(t.disableIdTokenSignIn)return!1;return Boolean(e.idToken||t.verifyIdToken)}async function Tp(e,t,r,n){let i=e.options??{};if(i.disableIdTokenSignIn)return!1;try{if(i.verifyIdToken)return await i.verifyIdToken(t,r,n);let o=e.idToken;if(!o)return!1;if("verify"in o)return await o.verify(t,r,n);if(t.split(".").length!==3)return o.allowOpaqueToken===!0;return await Tce(t,o,r),!0}catch{return!1}}function vp(e,t){return{linked:!1,error:{code:e,message:t}}}async function TL(e,{link:t,userInfo:r,account:n,profile:i,scopes:o}){try{await Il(e,{user:{...r,id:t.userId,email:r.email??void 0},source:{action:"link-account",method:"oauth",oauth:{providerId:n.providerId,profile:i}}})}catch(a){if(!hi(a)||!a.body?.code)throw a;return vp(a.body.code,a.body.message)}if(!e.context.trustedProviders.includes(n.providerId)&&!r.emailVerified||e.context.options.account?.accountLinking?.enabled===!1)return e.context.logger.error("Unable to link account - untrusted provider"),vp(Ri.UNABLE_TO_LINK_ACCOUNT);if(r.email?.toLowerCase()!==t.email.toLowerCase()&&e.context.options.account?.accountLinking?.allowDifferentEmails!==!0)return vp(Ri.EMAIL_DOES_NOT_MATCH);let s=await e.context.internalAdapter.findAccountByKey(n);if(s){if(s.userId.toString()!==t.userId.toString())return vp(Ri.ACCOUNT_ALREADY_LINKED_TO_DIFFERENT_USER);let a=jT(s.scope,o),c=Object.fromEntries(Object.entries({providerId:n.providerId,accessToken:await Ni(n.accessToken,e.context),refreshToken:await Ni(n.refreshToken,e.context),idToken:n.idToken,accessTokenExpiresAt:n.accessTokenExpiresAt,refreshTokenExpiresAt:n.refreshTokenExpiresAt,scope:a||void 0}).filter(([u,d])=>d!==void 0));await e.context.internalAdapter.updateAccount(s.id,c)}else if(!await e.context.internalAdapter.createAccount({userId:t.userId,...n,accessToken:await Ni(n.accessToken,e.context),refreshToken:await Ni(n.refreshToken,e.context),scope:o?.join(",")??n.scope}))return vp(Ri.UNABLE_TO_LINK_ACCOUNT);return await kp(e,t.userId,r),{linked:!0}}async function dw(e,t){let{userInfo:r,account:n,callbackURL:i,disableSignUp:o,overrideUserInfo:s}=t,a=t.source??{method:"oauth",oauth:{providerId:n.providerId}},c=!!t.selectedUser||t.requireExactAccountBinding===!0,u=null,d=await e.context.internalAdapter.findAccountOwnerByKey({providerId:n.providerId,accountId:n.accountId}).catch((R)=>{e.context.logger.error(`Better auth was unable to query your database.
141
+ Error: `,R),cp(e,e.context.options.onAPIError?.errorURL||`${e.context.baseURL}/error`,"internal_server_error")});if(d?.kind==="orphaned")return e.context.logger.error("OAuth account references a missing user. Repair the account before retrying authentication."),{error:"unable to link account",data:null,isRegister:!1};let f=await(async()=>{if(d?.kind==="owned"){if(t.selectedUser&&d.user.id!==t.selectedUser.userId)throw new l("CONFLICT",{code:"account_ownership_conflict",message:"Account is already linked to another user"});return{user:d.user,linkedAccount:d.account,accounts:[d.account]}}if(t.selectedUser){let O=await e.context.internalAdapter.findUserById(t.selectedUser.userId);if(!O)throw new l("NOT_FOUND",{code:"user_not_found",message:"User not found"});return{user:O,linkedAccount:null,accounts:[]}}let R=await e.context.internalAdapter.findUserByEmail(r.email.toLowerCase(),{includeAccounts:!0});if(!R)return null;return{user:R.user,linkedAccount:null,accounts:R.accounts}})().catch((R)=>{if(hi(R))throw R;e.context.logger.error(`Better auth was unable to query your database.
142
+ Error: `,R),cp(e,e.context.options.onAPIError?.errorURL||`${e.context.baseURL}/error`,"internal_server_error")}),h=f?.user,p=!h;if(f){let R=f.linkedAccount??f.accounts.find((O)=>O.providerId===n.providerId&&O.accountId===n.accountId);if(!R){let O=e.context.options.account?.accountLinking,I=t.isTrustedProvider||t.trustProviderByName!==!1&&e.context.trustedProviders.includes(n.providerId),Ne=O?.requireLocalEmailVerified??!0;if(!t.selectedUser&&(!I&&!r.emailVerified||Ne&&!f.user.emailVerified||O?.enabled===!1||O?.disableImplicitLinking===!0)){if($u())e.context.logger.warn(`User already exist but account isn't linked to ${n.providerId}. To read more about how account linking works in Better Auth see https://www.better-auth.com/docs/concepts/users-accounts#account-linking.`);return{error:"account not linked",data:null}}try{let{id:k,...j}=r;await Il(e,{user:{...j,id:f.user.id,email:r.email.toLowerCase()},source:{...a,action:"link-account"}});let re=await e.context.internalAdapter.linkAccount({providerId:n.providerId,accountId:n.accountId,userId:f.user.id,accessToken:await Ni(n.accessToken,e.context),refreshToken:await Ni(n.refreshToken,e.context),idToken:n.idToken,accessTokenExpiresAt:n.accessTokenExpiresAt,refreshTokenExpiresAt:n.refreshTokenExpiresAt,scope:n.scope});if(!re)return{error:"unable to link account",data:null};if(c&&(re.accountId!==n.accountId||re.providerId!==n.providerId||re.userId!==f.user.id))throw new l("CONFLICT",{code:"account_hook_binding_conflict",message:"Account hook changed the selected authentication binding"});if(e.context.options.account?.storeAccountCookie)if(t.deferNonDatabaseWrites)u=re;else await uc(e,re)}catch(k){if(hi(k))throw k;return e.context.logger.error("Unable to link account",k),{error:"unable to link account",data:null}}if(!t.selectedUser&&r.emailVerified&&!f.user.emailVerified&&r.email.toLowerCase()===f.user.email)await e.context.internalAdapter.updateUser(f.user.id,{emailVerified:!0});if(!t.selectedUser)h=await kp(e,f.user.id,r)??h}else{let{id:O,...I}=r;await Il(e,{user:{...I,id:f.user.id,email:r.email.toLowerCase()},source:{...a,action:"sign-in"}});let Ne=e.context.options.account?.updateAccountOnSignIn!==!1?Object.fromEntries(Object.entries({providerId:n.providerId,idToken:n.idToken,accessToken:await Ni(n.accessToken,e.context),refreshToken:await Ni(n.refreshToken,e.context),accessTokenExpiresAt:n.accessTokenExpiresAt,refreshTokenExpiresAt:n.refreshTokenExpiresAt}).filter(([k,j])=>j!==void 0)):{};if(e.context.options.account?.storeAccountCookie){let k={...R,...Ne};if(t.deferNonDatabaseWrites)u=k;else await uc(e,k)}if(Object.keys(Ne).length>0){let k=await e.context.internalAdapter.updateAccount(R.id,Ne);if(!k)return{error:"unable to update account",data:null};if(c&&(k.accountId!==n.accountId||k.providerId!==n.providerId||k.userId!==f.user.id))throw new l("CONFLICT",{code:"account_hook_binding_conflict",message:"Account hook changed the selected authentication binding"});if(t.deferNonDatabaseWrites&&u)u=k}if(!t.selectedUser&&r.emailVerified&&!f.user.emailVerified&&r.email.toLowerCase()===f.user.email)await e.context.internalAdapter.updateUser(f.user.id,{emailVerified:!0})}if(t.selectedUser?t.selectedUser.profile==="update":s){let{id:O,email:I,emailVerified:Ne,name:k,image:j,...re}=r,Oe=Ol(e.context.options,re,"update"),ne=await e.context.internalAdapter.updateUser(f.user.id,{name:k,image:j,...Oe,email:r.email.toLowerCase(),emailVerified:r.email.toLowerCase()===f.user.email?f.user.emailVerified||r.emailVerified:r.emailVerified});if(ne==null)e.context.logger.warn("Could not update user info during OAuth sign in; preserving existing user for session.");if(t.selectedUser&&ne&&ne.id!==t.selectedUser.userId)throw new l("CONFLICT",{code:"user_hook_selection_conflict",message:"User hook changed the selected user"});h=ne??h}}else{if(o)return{error:"signup disabled",data:null,isRegister:!1};try{let{id:R,email:O,emailVerified:I,name:Ne,image:k,...j}=r,re=Ol(e.context.options,j,"create"),Oe={accessToken:await Ni(n.accessToken,e.context),refreshToken:await Ni(n.refreshToken,e.context),idToken:n.idToken,accessTokenExpiresAt:n.accessTokenExpiresAt,refreshTokenExpiresAt:n.refreshTokenExpiresAt,scope:n.scope,providerId:n.providerId,accountId:n.accountId},{createdUser:ne,createdAccount:M}=await Co(e.context.adapter,async()=>{let F=await e.context.internalAdapter.createUser({name:Ne,image:k,...re,email:r.email.toLowerCase(),emailVerified:r.emailVerified},a);return{createdUser:F,createdAccount:await e.context.internalAdapter.createAccount({...Oe,userId:F.id})}});if(c&&(M.accountId!==n.accountId||M.providerId!==n.providerId||M.userId!==ne.id))throw new l("CONFLICT",{code:"account_hook_binding_conflict",message:"Account hook changed the selected authentication binding"});if(h=ne,e.context.options.account?.storeAccountCookie)if(t.deferNonDatabaseWrites)u=M;else await uc(e,M)}catch(R){if(hi(R))throw R;return e.context.logger.error("Unable to create OAuth user",R),{error:"unable to create user",data:null,isRegister:!1}}}if(!h)return{error:"unable to create user",data:null,isRegister:!1};let g=e.context.socialProviders.find((R)=>R.id===n.providerId)?.options?.requireEmailVerification;if(p&&!h.emailVerified&&(e.context.options.emailVerification?.sendOnSignUp??g))await AL(e,h,i,t.deferNonDatabaseWrites);if(g&&!h.emailVerified){if(!p&&e.context.options.emailVerification?.sendOnSignIn)await AL(e,h,i,t.deferNonDatabaseWrites);return{error:Ri.EMAIL_NOT_VERIFIED,data:null,isRegister:p}}let _=await e.context.internalAdapter.createSession(h.id,void 0,void 0,void 0,{deferSecondaryStorageWrites:t.deferNonDatabaseWrites===!0});if(!_)return{error:"unable to create session",data:null,isRegister:!1};if(c&&_.userId!==(t.selectedUser?.userId??h.id))throw new l("CONFLICT",{code:"session_hook_user_conflict",message:"Session hook changed the selected user"});return{data:{session:_,user:h},error:null,isRegister:p,accountCookie:u}}async function AL(e,t,r,n){let i=e.context.options.emailVerification?.sendVerificationEmail;if(!i)return;let o=async()=>{try{let s=await lo(e.context.secret,t.email,void 0,e.context.options.emailVerification?.expiresIn),a=`${e.context.baseURL}/verify-email?token=${s}&callbackURL=${encodeURIComponent(r||"/")}`;await e.context.runInBackgroundOrAwait(i({user:t,url:a,token:s},e.request))}catch(s){e.context.logger.error("Failed to send OAuth verification email",s)}};if(n)await _o(o);else await o()}async function kp(e,t,r){if(e.context.options.account?.accountLinking?.updateUserInfoOnLink!==!0)return;try{let{email:n,emailVerified:i,name:o,image:s,...a}=r,c=Ol(e.context.options,a,"update");return await e.context.internalAdapter.updateUser(t,{name:o,image:s,...c})}catch(n){e.context.logger.warn("Could not update user info on account link",n);return}}var vce=Mg("better-auth:oauth-encryption:v1");function QT(e,t){return SD(Sy(Ay,Mg(e),vce,Mg(`better-auth:${t}:v1`),32))}function YT(e,t){if(typeof e==="string")return QT(e,t);return{keys:new Map(Array.from(e.keys,([r,n])=>[r,QT(n,t)])),currentVersion:e.currentVersion,...e.legacySecret&&{legacySecret:QT(e.legacySecret,t)}}}import*as pi from"zod";var XT=pi.looseObject({callbackURL:pi.string(),codeVerifier:pi.string(),errorURL:pi.string().optional(),newUserURL:pi.string().optional(),expiresAt:pi.number(),oauthState:pi.string().optional(),link:pi.object({email:pi.string(),userId:pi.coerce.string()}).optional(),requestSignUp:pi.boolean().optional(),idTokenNonce:pi.string().optional(),serverContext:pi.record(pi.string(),pi.unknown()).optional()}),ZT=(e)=>`auth-state:${e}`,A2e=new Set(Object.keys(XT.shape)),Ks=class extends y{code;details;errorURL;constructor(e,t){super(e,t);this.code=t.code,this.details=t.details,this.errorURL=t.errorURL}};async function vL(e,t,r){let n=Ui(32);if(e.context.oauthConfig.storeStateStrategy==="cookie"){let s={...t,oauthState:n},a=await ka({key:YT(e.context.secretConfig,"oauth-state-cookie"),data:JSON.stringify(s)}),c=e.context.createAuthCookie(r?.cookieName??"oauth_state",{maxAge:600});return e.setCookie(c.name,a,c.attributes),{state:n,codeVerifier:t.codeVerifier}}let i=e.context.createAuthCookie(r?.cookieName??"state",{maxAge:300});await e.setSignedCookie(i.name,n,e.context.secret,i.attributes);let o=new Date;if(o.setMinutes(o.getMinutes()+10),!await e.context.internalAdapter.createVerificationValue({value:JSON.stringify({...t,oauthState:n}),identifier:ZT(n),expiresAt:o}))throw new Ks("Unable to create verification. Make sure the database adapter is properly working and there is a verification table in the database",{code:"state_generation_error"});return{state:n,codeVerifier:t.codeVerifier}}async function kL(e,t,r){if(!t)throw new Ks("State not found in OAuth callback",{code:"state_not_found"});let n=e.context.oauthConfig.storeStateStrategy,i;if(n==="cookie"){let o=e.context.createAuthCookie(r?.cookieName??"oauth_state"),s=e.getCookie(o.name);if(!s)throw new Ks("State mismatch: auth state cookie not found",{code:"state_mismatch",details:{state:t}});try{let a=await Ra({key:YT(e.context.secretConfig,"oauth-state-cookie"),data:s});i=XT.parse(JSON.parse(a))}catch(a){throw new Ks("State invalid: Failed to decrypt or parse auth state",{code:"state_invalid",details:{state:t},cause:a})}if(!i.oauthState||i.oauthState!==t)throw new Ks("State mismatch: OAuth state parameter does not match stored state",{code:"state_security_mismatch",details:{state:t},errorURL:i.errorURL});cs(e,o)}else{let o=await e.context.internalAdapter.findVerificationValue(ZT(t));if(!o)throw new Ks("State mismatch: verification not found",{code:"state_mismatch",details:{state:t}});if(i=XT.parse(JSON.parse(o.value)),i.oauthState!==void 0&&i.oauthState!==t)throw new Ks("State mismatch: OAuth state parameter does not match stored state",{code:"state_security_mismatch",details:{state:t},errorURL:i.errorURL});let s=e.context.createAuthCookie(r?.cookieName??"state"),a=await e.getSignedCookie(s.name,e.context.secret);if(!(r?.skipStateCookieCheck??e.context.oauthConfig.skipStateCookieCheck)&&(!a||a!==t))throw new Ks("State mismatch: State not persisted correctly",{code:"state_security_mismatch",details:{state:t},errorURL:i.errorURL});cs(e,s),await e.context.internalAdapter.deleteVerificationByIdentifier(ZT(t))}if(i.expiresAt<Date.now())throw new Ks("Invalid state: request expired",{code:"state_mismatch",details:{expiresAt:i.expiresAt},errorURL:i.errorURL});return i}function $l(e){return e.requiresIdTokenNonce?Ui(32):void 0}async function Fl(e,t){let r=e.body?.callbackURL||e.context.options.baseURL;if(!r)throw l.from("BAD_REQUEST",S.CALLBACK_URL_REQUIRED);let n=t?.codeVerifier??Ui(128),i=await RT(),o=i&&Object.keys(i).length?i:void 0,s={...t?.additionalData?t.additionalData:{},callbackURL:r,codeVerifier:n,errorURL:e.body?.errorCallbackURL,newUserURL:e.body?.newUserCallbackURL,link:t?.link,serverContext:o,expiresAt:Date.now()+600000,requestSignUp:e.body?.requestSignUp,idTokenNonce:t?.idTokenNonce};await vT(s);try{return vL(e,s)}catch(a){throw e.context.logger.error("Failed to create verification",a),new l("INTERNAL_SERVER_ERROR",{message:"Unable to create verification",cause:a})}}async function RL(e){let t=e.query.state||e.body?.state,r=e.context.options.onAPIError?.errorURL||`${e.context.baseURL}/error`,n;try{n=await kL(e,t)}catch(i){e.context.logger.error("Failed to parse state",i);let o="internal_server_error",s=r;if(i instanceof Ks)o=i.code==="state_security_mismatch"?"state_mismatch":i.code,s=i.errorURL||r;cp(e,s,o)}if(!n.errorURL)n.errorURL=r;if(n)await vT(n);return n}var NL=(e)=>({id:"apple",name:"Apple",accountSubject:({profile:r})=>r.sub,async createAuthorizationURL({state:r,scopes:n,redirectURI:i,additionalParams:o,codeVerifier:s}){if(!fo(e.clientId)||!e.clientSecret)throw T.error("Client ID and client secret are required for Apple. Make sure to provide them in the options."),new y("CLIENT_ID_AND_SECRET_REQUIRED");let a=e.disableDefaultScope?[]:["email","name"];if(e.scope)a.push(...e.scope);if(n)a.push(...n);return await St({id:"apple",options:e,authorizationEndpoint:"https://appleid.apple.com/auth/authorize",scopes:a,state:r,redirectURI:i,codeVerifier:s,responseMode:"form_post",responseType:"code id_token",additionalParams:o})},validateAuthorizationCode:async({code:r,codeVerifier:n,redirectURI:i})=>Tt({code:r,codeVerifier:n,redirectURI:i,options:e,tokenEndpoint:"https://appleid.apple.com/auth/token"}),idToken:{jwks:(r)=>xL(r.kid),issuer:"https://appleid.apple.com",algorithms:["RS256"],audience:e.audience&&e.audience.length?e.audience:e.appBundleIdentifier?e.appBundleIdentifier:e.clientId,maxTokenAge:"1h",nonceComparison:"exact-or-sha256"},refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async(r)=>At({refreshToken:r,options:e,tokenEndpoint:"https://appleid.apple.com/auth/token"}),async getUserInfo(r){if(e.getUserInfo)return e.getUserInfo(r);if(!r.idToken)return null;let n=W(r.idToken);if(!n)return null;let i;if(r.user?.name)i=`${r.user.name.firstName||""} ${r.user.name.lastName||""}`.trim();else i=n.name||"";let o=typeof n.email_verified==="boolean"?n.email_verified:n.email_verified==="true",s={...n,name:i},a=await e.mapProfileToUser?.(s);return{user:{name:s.name,emailVerified:o,email:n.email,...a},data:s}},options:e}),xL=async(e)=>{let{data:t}=await w("https://appleid.apple.com/auth/keys");if(!t?.keys)throw new l("BAD_REQUEST",{message:"Keys not found"});let r=t.keys.find((n)=>n.kid===e);if(!r)throw Error(`JWK with kid ${e} not found`);return await te(r,r.alg)};var CL=(e)=>({id:"atlassian",name:"Atlassian",accountSubject:({profile:r})=>r.account_id,async createAuthorizationURL({state:r,scopes:n,codeVerifier:i,redirectURI:o,additionalParams:s}){if(!e.clientId||!e.clientSecret)throw T.error("Client Id and Secret are required for Atlassian"),new y("CLIENT_ID_AND_SECRET_REQUIRED");if(!i)throw new y("codeVerifier is required for Atlassian");let a=e.disableDefaultScope?[]:["read:jira-user","offline_access"];if(e.scope)a.push(...e.scope);if(n)a.push(...n);return St({id:"atlassian",options:e,authorizationEndpoint:"https://auth.atlassian.com/authorize",scopes:a,state:r,codeVerifier:i,redirectURI:o,additionalParams:{...s??{},audience:"api.atlassian.com"},prompt:e.prompt})},validateAuthorizationCode:async({code:r,codeVerifier:n,redirectURI:i})=>Tt({code:r,codeVerifier:n,redirectURI:i,options:e,tokenEndpoint:"https://auth.atlassian.com/oauth/token"}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async(r)=>At({refreshToken:r,options:{clientId:e.clientId,clientSecret:e.clientSecret},tokenEndpoint:"https://auth.atlassian.com/oauth/token"}),async getUserInfo(r){if(e.getUserInfo)return e.getUserInfo(r);if(!r.accessToken)return null;try{let{data:n}=await w("https://api.atlassian.com/me",{headers:{Authorization:`Bearer ${r.accessToken}`}});if(!n)return null;let i=await e.mapProfileToUser?.(n);return{user:{name:n.name,email:n.email,image:n.picture,emailVerified:!1,...i},data:n}}catch(n){return T.error("Failed to fetch user info from Atlassian:",n),null}},options:e});var kce="https://dash.cloudflare.com/oauth2/auth",OL="https://dash.cloudflare.com/oauth2/token",Rce="https://api.cloudflare.com/client/v4/user",IL=(e)=>{let t=e.clientSecret?"client_secret_basic":"none";return{method:e.tokenEndpointAuthMethod??t}},DL=(e)=>({id:"cloudflare",name:"Cloudflare",accountSubject:({profile:t})=>t.id,createAuthorizationURL({state:t,scopes:r,codeVerifier:n,redirectURI:i}){let o=e.disableDefaultScope?[]:["user-details.read"];if(e.scope?.length)o.push(...e.scope);if(r?.length)o.push(...r);return St({id:"cloudflare",options:e,authorizationEndpoint:kce,scopes:o.length?[...new Set(o)]:void 0,state:t,codeVerifier:n,redirectURI:i})},validateAuthorizationCode:async({code:t,codeVerifier:r,redirectURI:n})=>Tt({code:t,codeVerifier:r,redirectURI:n,options:e,tokenEndpoint:OL,tokenEndpointAuth:IL(e)}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async(t)=>At({refreshToken:t,options:{clientId:e.clientId,clientKey:e.clientKey,clientSecret:e.clientSecret},tokenEndpoint:OL,tokenEndpointAuth:IL(e)}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:r,error:n}=await w(Rce,{headers:{authorization:`Bearer ${t.accessToken}`}});if(n||!r?.success||!r.result)return T.error("Failed to fetch user info from Cloudflare:",n??r?.errors),null;let i=r.result,o=[i.first_name,i.last_name].filter(Boolean).join(" ")||i.email,s=await e.mapProfileToUser?.(i);return{user:{name:o,email:i.email,emailVerified:!1,...s},data:i}},options:e});var UL=(e)=>{if(!e.domain||!e.region||!e.userPoolId)throw T.error("Domain, region and userPoolId are required for Amazon Cognito. Make sure to provide them in the options."),new y("DOMAIN_AND_REGION_REQUIRED");let t=e.domain.replace(/^https?:\/\//,""),r=`https://${t}/oauth2/authorize`,n=`https://${t}/oauth2/token`,i=`https://${t}/oauth2/userinfo`;return{id:"cognito",name:"Cognito",accountSubject:({profile:o})=>o.sub,async createAuthorizationURL({state:o,scopes:s,codeVerifier:a,redirectURI:c,additionalParams:u}){if(!fo(e.clientId))throw T.error("ClientId is required for Amazon Cognito. Make sure to provide them in the options."),new y("CLIENT_ID_AND_SECRET_REQUIRED");if(e.requireClientSecret&&!e.clientSecret)throw T.error("Client Secret is required when requireClientSecret is true. Make sure to provide it in the options."),new y("CLIENT_SECRET_REQUIRED");let d=e.disableDefaultScope?[]:["openid","profile","email"];if(e.scope)d.push(...e.scope);if(s)d.push(...s);let f=await St({id:"cognito",options:{...e},authorizationEndpoint:r,scopes:d,state:o,codeVerifier:a,redirectURI:c,prompt:e.prompt,additionalParams:{...e.identityProvider?{identity_provider:e.identityProvider}:{},...u??{}}}),h=f.searchParams.get("scope");if(h){f.searchParams.delete("scope");let p=encodeURIComponent(h),g=f.toString(),_=g.includes("?")?"&":"?";return new URL(`${g}${_}scope=${p}`)}return f},validateAuthorizationCode:async({code:o,codeVerifier:s,redirectURI:a})=>Tt({code:o,codeVerifier:s,redirectURI:a,options:e,tokenEndpoint:n}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async(o)=>At({refreshToken:o,options:{clientId:e.clientId,clientKey:e.clientKey,clientSecret:e.clientSecret},tokenEndpoint:n}),idToken:{jwks:(o)=>PL(o.kid,e.region,e.userPoolId),issuer:`https://cognito-idp.${e.region}.amazonaws.com/${e.userPoolId}`,audience:e.clientId,algorithms:["RS256"],maxTokenAge:"1h"},async getUserInfo(o){if(e.getUserInfo)return e.getUserInfo(o);if(o.idToken)try{let s=W(o.idToken);if(!s)return null;let a=s.name||s.given_name||s.username||"",c={...s,name:a},u=await e.mapProfileToUser?.(c);return{user:{name:c.name,email:s.email,image:s.picture,emailVerified:s.email_verified,...u},data:c}}catch(s){T.error("Failed to decode ID token:",s)}if(o.accessToken)try{let{data:s}=await w(i,{headers:{Authorization:`Bearer ${o.accessToken}`}});if(s){let a=await e.mapProfileToUser?.(s);return{user:{name:s.name||s.given_name||s.username||"",email:s.email,image:s.picture,emailVerified:s.email_verified,...a},data:s}}}catch(s){T.error("Failed to fetch user info from Cognito:",s)}return null},options:e}},PL=async(e,t,r)=>{let n=`https://cognito-idp.${t}.amazonaws.com/${r}/.well-known/jwks.json`;try{let{data:i}=await w(n);if(!i?.keys)throw new l("BAD_REQUEST",{message:"Keys not found"});let o=i.keys.find((s)=>s.kid===e);if(!o)throw Error(`JWK with kid ${e} not found`);return await te(o,o.alg)}catch(i){throw T.error("Failed to fetch Cognito public key:",i),i}};var LL=(e)=>({id:"discord",name:"Discord",accountSubject:({profile:r})=>r.id,createAuthorizationURL({state:r,scopes:n,redirectURI:i,additionalParams:o}){let s=e.disableDefaultScope?[]:["identify","email"];if(n)s.push(...n);if(e.scope)s.push(...e.scope);let a=s.includes("bot");return St({id:"discord",options:e,authorizationEndpoint:"https://discord.com/api/oauth2/authorize",scopes:s,state:r,redirectURI:i,prompt:e.prompt||"none",additionalParams:{...a&&e.permissions!==void 0?{permissions:String(e.permissions)}:{},...o??{}}})},validateAuthorizationCode:async({code:r,redirectURI:n})=>Tt({code:r,redirectURI:n,options:e,tokenEndpoint:"https://discord.com/api/oauth2/token"}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async(r)=>At({refreshToken:r,options:{clientId:e.clientId,clientKey:e.clientKey,clientSecret:e.clientSecret},tokenEndpoint:"https://discord.com/api/oauth2/token"}),async getUserInfo(r){if(e.getUserInfo)return e.getUserInfo(r);let{data:n,error:i}=await w("https://discord.com/api/users/@me",{headers:{authorization:`Bearer ${r.accessToken}`}});if(i)return null;if(n.avatar===null)n.image_url=`https://cdn.discordapp.com/embed/avatars/${n.discriminator==="0"?Number(BigInt(n.id)>>BigInt(22))%6:parseInt(n.discriminator)%5}.png`;else{let s=n.avatar.startsWith("a_")?"gif":"png";n.image_url=`https://cdn.discordapp.com/avatars/${n.id}/${n.avatar}.${s}`}let o=await e.mapProfileToUser?.(n);return{user:{name:n.global_name||n.username||"",email:n.email,emailVerified:n.verified,image:n.image_url,...o},data:n}},options:e});var ML=(e)=>({id:"dropbox",name:"Dropbox",accountSubject:({profile:r})=>r.account_id,createAuthorizationURL:async({state:r,scopes:n,codeVerifier:i,redirectURI:o,additionalParams:s})=>{let a=e.disableDefaultScope?[]:["account_info.read"];if(e.scope)a.push(...e.scope);if(n)a.push(...n);return await St({id:"dropbox",options:e,authorizationEndpoint:"https://www.dropbox.com/oauth2/authorize",scopes:a,state:r,redirectURI:o,codeVerifier:i,additionalParams:{...e.accessType?{token_access_type:e.accessType}:{},...s??{}}})},validateAuthorizationCode:async({code:r,codeVerifier:n,redirectURI:i})=>await Tt({code:r,codeVerifier:n,redirectURI:i,options:e,tokenEndpoint:"https://api.dropboxapi.com/oauth2/token"}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async(r)=>At({refreshToken:r,options:{clientId:e.clientId,clientKey:e.clientKey,clientSecret:e.clientSecret},tokenEndpoint:"https://api.dropboxapi.com/oauth2/token"}),async getUserInfo(r){if(e.getUserInfo)return e.getUserInfo(r);let{data:n,error:i}=await w("https://api.dropboxapi.com/2/users/get_current_account",{method:"POST",headers:{Authorization:`Bearer ${r.accessToken}`}});if(i)return null;let o=await e.mapProfileToUser?.(n);return{user:{name:n.name?.display_name,email:n.email,emailVerified:n.email_verified||!1,image:n.profile_photo_url,...o},data:n}},options:e});async function qL(e,t){let r=fo(t.clientId);if(!r||!t.clientSecret)return null;let n=Array.isArray(t.clientId)?t.clientId:[t.clientId],{data:i,error:o}=await w("https://graph.facebook.com/debug_token",{query:{input_token:e,access_token:`${r}|${t.clientSecret}`}});if(o||!i?.data)return null;let{is_valid:s,app_id:a,user_id:c}=i.data;if(s!==!0||!a||!n.includes(a)||!c)return null;return c}var BL=(e)=>({id:"facebook",name:"Facebook",accountSubject:({profile:t})=>("sub"in t)?t.sub:t.id,async createAuthorizationURL({state:t,scopes:r,redirectURI:n,loginHint:i,additionalParams:o}){if(!fo(e.clientId)||!e.clientSecret)throw T.error("Client ID and client secret are required for Facebook. Make sure to provide them in the options."),new y("CLIENT_ID_AND_SECRET_REQUIRED");let s=e.disableDefaultScope?[]:["email","public_profile"];if(e.scope)s.push(...e.scope);if(r)s.push(...r);return await St({id:"facebook",options:e,authorizationEndpoint:"https://www.facebook.com/v24.0/dialog/oauth",scopes:s,state:t,redirectURI:n,loginHint:i,additionalParams:{...e.configId?{config_id:e.configId}:{},...o??{}}})},validateAuthorizationCode:async({code:t,redirectURI:r})=>Tt({code:t,redirectURI:r,options:e,tokenEndpoint:"https://graph.facebook.com/v24.0/oauth/access_token"}),idToken:{jwks:Fr(new URL("https://limited.facebook.com/.well-known/oauth/openid/jwks/")),issuer:"https://www.facebook.com",audience:e.clientId,algorithms:["RS256"],allowOpaqueToken:!0},refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async(t)=>At({refreshToken:t,options:{clientId:e.clientId,clientKey:e.clientKey,clientSecret:e.clientSecret},tokenEndpoint:"https://graph.facebook.com/v24.0/oauth/access_token"}),async getUserInfo(t){if(e.getUserInfo){let a=!!t.idToken&&t.idToken.split(".").length!==3,c=t.accessToken||(a?t.idToken:void 0);if(c&&!await qL(c,e))return null;return e.getUserInfo(t)}if(t.idToken&&t.idToken.split(".").length===3){let a=W(t.idToken),c=await e.mapProfileToUser?.(a);return{user:{name:a.name,email:a.email,image:a.picture,emailVerified:!1,...c},data:a}}let r=t.accessToken;if(!r)return null;let n=await qL(r,e);if(!n)return null;let{data:i,error:o}=await w("https://graph.facebook.com/me?fields="+["id","name","email","picture",...e?.fields||[]].join(","),{auth:{type:"Bearer",token:r}});if(o)return null;if(i.id!==n)return null;let s=await e.mapProfileToUser?.(i);return{user:{name:i.name,email:i.email,image:i.picture.data.url,emailVerified:i.email_verified??!1,...s},data:i}},options:e});var jL=(e)=>({id:"figma",name:"Figma",accountSubject:({profile:r})=>r.id,async createAuthorizationURL({state:r,scopes:n,codeVerifier:i,redirectURI:o,additionalParams:s}){if(!e.clientId||!e.clientSecret)throw T.error("Client Id and Client Secret are required for Figma. Make sure to provide them in the options."),new y("CLIENT_ID_AND_SECRET_REQUIRED");if(!i)throw new y("codeVerifier is required for Figma");let a=e.disableDefaultScope?[]:["current_user:read"];if(e.scope)a.push(...e.scope);if(n)a.push(...n);return await St({id:"figma",options:e,authorizationEndpoint:"https://www.figma.com/oauth",scopes:a,state:r,codeVerifier:i,redirectURI:o,additionalParams:s})},validateAuthorizationCode:async({code:r,codeVerifier:n,redirectURI:i})=>Tt({code:r,codeVerifier:n,redirectURI:i,options:e,tokenEndpoint:"https://api.figma.com/v1/oauth/token",authentication:"basic"}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async(r)=>At({refreshToken:r,options:{clientId:e.clientId,clientKey:e.clientKey,clientSecret:e.clientSecret},tokenEndpoint:"https://api.figma.com/v1/oauth/token",authentication:"basic"}),async getUserInfo(r){if(e.getUserInfo)return e.getUserInfo(r);try{let{data:n}=await w("https://api.figma.com/v1/me",{headers:{Authorization:`Bearer ${r.accessToken}`}});if(!n)return T.error("Failed to fetch user from Figma"),null;let i=await e.mapProfileToUser?.(n);return{user:{name:n.handle,email:n.email,image:n.img_url,emailVerified:!1,...i},data:n}}catch(n){return T.error("Failed to fetch user info from Figma:",n),null}},options:e});var $L=(e)=>({id:"github",name:"GitHub",accountSubject:({profile:r})=>r.id,createAuthorizationURL({state:r,scopes:n,loginHint:i,codeVerifier:o,redirectURI:s,additionalParams:a}){let c=e.disableDefaultScope?[]:["read:user","user:email"];if(e.scope)c.push(...e.scope);if(n)c.push(...n);return St({id:"github",options:e,authorizationEndpoint:"https://github.com/login/oauth/authorize",scopes:c,state:r,codeVerifier:o,redirectURI:s,loginHint:i,prompt:e.prompt,additionalParams:a})},validateAuthorizationCode:async({code:r,codeVerifier:n,redirectURI:i})=>{let{body:o,headers:s}=await JT({code:r,codeVerifier:n,redirectURI:i,options:e}),{data:a,error:c}=await w("https://github.com/login/oauth/access_token",{method:"POST",body:o,headers:s});if(c)return T.error("GitHub OAuth token exchange failed:",c),null;if("error"in a)return T.error("GitHub OAuth token exchange failed:",a),null;return hp(a)},refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async(r)=>At({refreshToken:r,options:{clientId:e.clientId,clientKey:e.clientKey,clientSecret:e.clientSecret},tokenEndpoint:"https://github.com/login/oauth/access_token"}),async getUserInfo(r){if(e.getUserInfo)return e.getUserInfo(r);let{data:n,error:i}=await w("https://api.github.com/user",{headers:{"User-Agent":"better-auth",authorization:`Bearer ${r.accessToken}`}});if(i)return null;let{data:o}=await w("https://api.github.com/user/emails",{headers:{Authorization:`Bearer ${r.accessToken}`,"User-Agent":"better-auth"}});if(!n.email&&o)n.email=(o.find((c)=>c.primary)??o[0])?.email;let s=o?.find((c)=>c.email===n.email)?.verified??!1,a=await e.mapProfileToUser?.(n);return{user:{name:n.name||n.login||"",email:n.email,image:n.avatar_url,emailVerified:s,...a},data:n}},options:e});var ev=(e="")=>e.split("://").map((t)=>t.replace(/\/{2,}/g,"/")).join("://"),Nce=(e)=>{let t=e||"https://gitlab.com";return{authorizationEndpoint:ev(`${t}/oauth/authorize`),tokenEndpoint:ev(`${t}/oauth/token`),userinfoEndpoint:ev(`${t}/api/v4/user`)}},FL=(e)=>{let{authorizationEndpoint:t,tokenEndpoint:r,userinfoEndpoint:n}=Nce(e.issuer),i="gitlab";return{id:"gitlab",name:"Gitlab",accountSubject:({profile:o})=>o.id,createAuthorizationURL:async({state:o,scopes:s,codeVerifier:a,loginHint:c,redirectURI:u,additionalParams:d})=>{let f=e.disableDefaultScope?[]:["read_user"];if(e.scope)f.push(...e.scope);if(s)f.push(...s);return await St({id:"gitlab",options:e,authorizationEndpoint:t,scopes:f,state:o,redirectURI:u,codeVerifier:a,loginHint:c,additionalParams:d})},validateAuthorizationCode:async({code:o,redirectURI:s,codeVerifier:a})=>Tt({code:o,redirectURI:s,options:e,codeVerifier:a,tokenEndpoint:r}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async(o)=>At({refreshToken:o,options:{clientId:e.clientId,clientKey:e.clientKey,clientSecret:e.clientSecret},tokenEndpoint:r}),async getUserInfo(o){if(e.getUserInfo)return e.getUserInfo(o);let{data:s,error:a}=await w(n,{headers:{authorization:`Bearer ${o.accessToken}`}});if(a||s.state!=="active"||s.locked)return null;let c=await e.mapProfileToUser?.(s);return{user:{name:s.name??s.username??"",email:s.email,image:s.avatar_url,emailVerified:s.email_verified??!1,...c},data:s}},options:e}};var xce="1h",zL="RS256",Cce=[zL];var tv=(e,t)=>{if(!e)return!0;if(typeof t!=="string"||!t)return!1;if(e==="*")return!0;return t===e},WL=(e)=>({id:"google",name:"Google",accountSubject:({profile:t})=>t.sub,async createAuthorizationURL({state:t,scopes:r,codeVerifier:n,redirectURI:i,loginHint:o,display:s,additionalParams:a}){if(!fo(e.clientId)||!e.clientSecret)throw T.error("Client Id and Client Secret is required for Google. Make sure to provide them in the options."),new y("CLIENT_ID_AND_SECRET_REQUIRED");if(!n)throw new y("codeVerifier is required for Google");let c=e.disableDefaultScope?[]:["email","profile","openid"];if(e.scope)c.push(...e.scope);if(r)c.push(...r);return await St({id:"google",options:e,authorizationEndpoint:"https://accounts.google.com/o/oauth2/v2/auth",scopes:c,state:t,codeVerifier:n,redirectURI:i,prompt:e.prompt,accessType:e.accessType,display:s||e.display,loginHint:o,hd:e.hd,additionalParams:{...e.includeGrantedScopes===!1?{}:{include_granted_scopes:"true"},...a??{}}})},validateAuthorizationCode:async({code:t,codeVerifier:r,redirectURI:n})=>Tt({code:t,codeVerifier:r,redirectURI:n,options:e,tokenEndpoint:"https://oauth2.googleapis.com/token"}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async(t)=>At({refreshToken:t,options:{clientId:e.clientId,clientKey:e.clientKey,clientSecret:e.clientSecret},tokenEndpoint:"https://oauth2.googleapis.com/token"}),idToken:{jwks:(t)=>HL(t.kid),issuer:["https://accounts.google.com","accounts.google.com"],audience:e.clientId,algorithms:Cce,maxTokenAge:xce,verifyClaims:e.hd?(t)=>tv(e.hd,t.hd):void 0},async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);if(!t.idToken)return null;let r=W(t.idToken);if(!tv(e.hd,r.hd))return T.error(`Google sign-in rejected: id token hosted domain (hd) "${r.hd??"<missing>"}" does not satisfy the configured "hd" option "${e.hd}".`),null;let n=await e.mapProfileToUser?.(r);return{user:{name:r.name,email:r.email,image:r.picture,emailVerified:r.email_verified,...n},data:r}},options:e}),HL=async(e)=>{let[t]=await Oce(e);if(!t)throw Error(`JWK with kid ${e} not found`);return t},Oce=async(e)=>{let{data:t}=await w("https://www.googleapis.com/oauth2/v3/certs");if(!t?.keys)throw new l("BAD_REQUEST",{message:"Keys not found"});let r=e?t.keys.filter((n)=>n.kid===e):t.keys;if(!r.length)throw Error(`JWK with kid ${e} not found`);return Promise.all(r.map((n)=>te(n,zL)))};var VL=(e)=>({id:"huggingface",name:"Hugging Face",accountSubject:({profile:r})=>r.sub,createAuthorizationURL({state:r,scopes:n,codeVerifier:i,redirectURI:o,additionalParams:s}){let a=e.disableDefaultScope?[]:["openid","profile","email"];if(e.scope)a.push(...e.scope);if(n)a.push(...n);return St({id:"huggingface",options:e,authorizationEndpoint:"https://huggingface.co/oauth/authorize",scopes:a,state:r,codeVerifier:i,redirectURI:o,additionalParams:s})},validateAuthorizationCode:async({code:r,codeVerifier:n,redirectURI:i})=>Tt({code:r,codeVerifier:n,redirectURI:i,options:e,tokenEndpoint:"https://huggingface.co/oauth/token"}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async(r)=>At({refreshToken:r,options:{clientId:e.clientId,clientKey:e.clientKey,clientSecret:e.clientSecret},tokenEndpoint:"https://huggingface.co/oauth/token"}),async getUserInfo(r){if(e.getUserInfo)return e.getUserInfo(r);let{data:n,error:i}=await w("https://huggingface.co/oauth/userinfo",{method:"GET",headers:{Authorization:`Bearer ${r.accessToken}`}});if(i)return null;let o=await e.mapProfileToUser?.(n);return{user:{name:n.name||n.preferred_username||"",email:n.email,image:n.picture,emailVerified:n.email_verified??!1,...o},data:n}},options:e});var GL=(e)=>({id:"kakao",name:"Kakao",accountSubject:({profile:r})=>r.id,createAuthorizationURL({state:r,scopes:n,redirectURI:i,additionalParams:o}){let s=e.disableDefaultScope?[]:["account_email","profile_image","profile_nickname"];if(e.scope)s.push(...e.scope);if(n)s.push(...n);return St({id:"kakao",options:e,authorizationEndpoint:"https://kauth.kakao.com/oauth/authorize",scopes:s,state:r,redirectURI:i,additionalParams:o})},validateAuthorizationCode:async({code:r,redirectURI:n})=>Tt({code:r,redirectURI:n,options:e,tokenEndpoint:"https://kauth.kakao.com/oauth/token"}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async(r)=>At({refreshToken:r,options:{clientId:e.clientId,clientKey:e.clientKey,clientSecret:e.clientSecret},tokenEndpoint:"https://kauth.kakao.com/oauth/token"}),async getUserInfo(r){if(e.getUserInfo)return e.getUserInfo(r);let{data:n,error:i}=await w("https://kapi.kakao.com/v2/user/me",{headers:{Authorization:`Bearer ${r.accessToken}`}});if(i||!n)return null;let o=await e.mapProfileToUser?.(n),s=n.kakao_account||{},a=s.profile||{};return{user:{name:a.nickname||s.name||"",email:s.email,image:a.profile_image_url||a.thumbnail_image_url,emailVerified:!!s.is_email_valid&&!!s.is_email_verified,...o},data:n}},options:e});var KL=(e)=>({id:"kick",name:"Kick",accountSubject:({profile:t})=>t.user_id,createAuthorizationURL({state:t,scopes:r,redirectURI:n,codeVerifier:i,additionalParams:o}){let s=e.disableDefaultScope?[]:["user:read"];if(e.scope)s.push(...e.scope);if(r)s.push(...r);return St({id:"kick",redirectURI:n,options:e,authorizationEndpoint:"https://id.kick.com/oauth/authorize",scopes:s,codeVerifier:i,state:t,additionalParams:o})},async validateAuthorizationCode({code:t,redirectURI:r,codeVerifier:n}){return Tt({code:t,redirectURI:r,options:e,tokenEndpoint:"https://id.kick.com/oauth/token",codeVerifier:n})},refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async(t)=>At({refreshToken:t,options:{clientId:e.clientId,clientSecret:e.clientSecret},tokenEndpoint:"https://id.kick.com/oauth/token"}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:r,error:n}=await w("https://api.kick.com/public/v1/users",{method:"GET",headers:{Authorization:`Bearer ${t.accessToken}`}});if(n)return null;let i=r.data[0],o=await e.mapProfileToUser?.(i);return{user:{name:i.name,email:i.email,image:i.profile_picture,emailVerified:!1,...o},data:i}},options:e});var JL=(e)=>({id:"line",name:"LINE",accountSubject:({profile:o})=>o.sub,async createAuthorizationURL({state:o,scopes:s,codeVerifier:a,redirectURI:c,loginHint:u,additionalParams:d}){let f=e.disableDefaultScope?[]:["openid","profile","email"];if(e.scope)f.push(...e.scope);if(s)f.push(...s);return await St({id:"line",options:e,authorizationEndpoint:"https://access.line.me/oauth2/v2.1/authorize",scopes:f,state:o,codeVerifier:a,redirectURI:c,loginHint:u,additionalParams:d})},validateAuthorizationCode:async({code:o,codeVerifier:s,redirectURI:a})=>Tt({code:o,codeVerifier:s,redirectURI:a,options:e,tokenEndpoint:"https://api.line.me/oauth2/v2.1/token"}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async(o)=>At({refreshToken:o,options:{clientId:e.clientId,clientSecret:e.clientSecret},tokenEndpoint:"https://api.line.me/oauth2/v2.1/token"}),idToken:{verify:async(o,s)=>{let a=new URLSearchParams;if(a.set("id_token",o),a.set("client_id",e.clientId),s)a.set("nonce",s);let{data:c,error:u}=await w("https://api.line.me/oauth2/v2.1/verify",{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:a});if(u||!c)return!1;if(c.aud!==e.clientId)return!1;if(c.nonce&&c.nonce!==s)return!1;return!0}},async getUserInfo(o){if(e.getUserInfo)return e.getUserInfo(o);let s=null;if(o.idToken)try{s=W(o.idToken)}catch{}if(!s){let{data:c}=await w("https://api.line.me/oauth2/v2.1/userinfo",{headers:{authorization:`Bearer ${o.accessToken}`}});s=c||null}if(!s)return null;let a=await e.mapProfileToUser?.(s);return{user:{name:s.name||"",email:s.email,image:s.picture,emailVerified:!1,...a},data:s}},options:e});var QL=(e)=>({id:"linear",name:"Linear",accountSubject:({profile:r})=>r.id,createAuthorizationURL({state:r,scopes:n,loginHint:i,redirectURI:o,additionalParams:s}){let a=e.disableDefaultScope?[]:["read"];if(e.scope)a.push(...e.scope);if(n)a.push(...n);return St({id:"linear",options:e,authorizationEndpoint:"https://linear.app/oauth/authorize",scopes:a,state:r,redirectURI:o,loginHint:i,additionalParams:s})},validateAuthorizationCode:async({code:r,redirectURI:n})=>Tt({code:r,redirectURI:n,options:e,tokenEndpoint:"https://api.linear.app/oauth/token"}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async(r)=>At({refreshToken:r,options:{clientId:e.clientId,clientKey:e.clientKey,clientSecret:e.clientSecret},tokenEndpoint:"https://api.linear.app/oauth/token"}),async getUserInfo(r){if(e.getUserInfo)return e.getUserInfo(r);let{data:n,error:i}=await w("https://api.linear.app/graphql",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${r.accessToken}`},body:JSON.stringify({query:`
143
+ query {
144
+ viewer {
145
+ id
146
+ name
147
+ email
148
+ avatarUrl
149
+ active
150
+ createdAt
151
+ updatedAt
152
+ }
153
+ }
154
+ `})});if(i||!n?.data?.viewer)return null;let o=n.data.viewer,s=await e.mapProfileToUser?.(o);return{user:{name:n.data.viewer.name,email:n.data.viewer.email,image:n.data.viewer.avatarUrl,emailVerified:!1,...s},data:o}},options:e});var YL=(e)=>({id:"linkedin",name:"Linkedin",accountSubject:({profile:n})=>n.sub,createAuthorizationURL:async({state:n,scopes:i,redirectURI:o,loginHint:s,additionalParams:a})=>{let c=e.disableDefaultScope?[]:["profile","email","openid"];if(e.scope)c.push(...e.scope);if(i)c.push(...i);return await St({id:"linkedin",options:e,authorizationEndpoint:"https://www.linkedin.com/oauth/v2/authorization",scopes:c,state:n,loginHint:s,redirectURI:o,additionalParams:a})},validateAuthorizationCode:async({code:n,redirectURI:i})=>await Tt({code:n,redirectURI:i,options:e,tokenEndpoint:"https://www.linkedin.com/oauth/v2/accessToken"}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async(n)=>At({refreshToken:n,options:{clientId:e.clientId,clientKey:e.clientKey,clientSecret:e.clientSecret},tokenEndpoint:"https://www.linkedin.com/oauth/v2/accessToken"}),async getUserInfo(n){if(e.getUserInfo)return e.getUserInfo(n);let{data:i,error:o}=await w("https://api.linkedin.com/v2/userinfo",{method:"GET",headers:{Authorization:`Bearer ${n.accessToken}`}});if(o)return null;let s=await e.mapProfileToUser?.(i);return{user:{name:i.name,email:i.email,emailVerified:i.email_verified??!1,image:i.picture,...s},data:i}},options:e});var XL="9188040d-6c67-4c5b-b112-36a304b66dad",ZL=(e)=>{let t=e.tenantId||"common",r=e.authority||"https://login.microsoftonline.com";while(r.endsWith("/"))r=r.slice(0,-1);let n=`${r}/${t}/oauth2/v2.0/authorize`,i=`${r}/${t}/oauth2/v2.0/token`;if(e.clientSecret&&e.clientAssertion)throw new y("Microsoft Entra ID clientAssertion cannot be combined with clientSecret");let o=e.clientAssertion?{method:"private_key_jwt",getClientAssertion:e.clientAssertion}:void 0;return{id:"microsoft",name:"Microsoft EntraID",accountSubject:({profile:s})=>s.oid,createAuthorizationURL(s){if(!fo(e.clientId))throw T.error("Client Id is required for Microsoft Entra ID. Make sure to provide it in the options."),new y("CLIENT_ID_AND_SECRET_REQUIRED");let a=e.disableDefaultScope?[]:["openid","profile","email","User.Read","offline_access"];if(e.scope)a.push(...e.scope);if(s.scopes)a.push(...s.scopes);return St({id:"microsoft",options:e,authorizationEndpoint:n,state:s.state,codeVerifier:s.codeVerifier,scopes:a,redirectURI:s.redirectURI,prompt:e.prompt,loginHint:s.loginHint,additionalParams:s.additionalParams})},validateAuthorizationCode({code:s,codeVerifier:a,redirectURI:c}){return Tt({code:s,codeVerifier:a,redirectURI:c,options:e,tokenEndpoint:i,tokenEndpointAuth:o})},idToken:{jwks:(s)=>eM(s.kid,t,r),algorithms:["RS256"],audience:e.clientId,maxTokenAge:"1h",issuer:t!=="common"&&t!=="organizations"&&t!=="consumers"?`${r}/${t}/v2.0`:void 0,verifyClaims:(s)=>{let a=s.tid;if(typeof a!=="string"||s.iss!==`${r}/${a}/v2.0`)return!1;if(t==="organizations"&&a===XL)return!1;if(t==="consumers"&&a!==XL)return!1;return!0}},async getUserInfo(s){if(e.getUserInfo)return e.getUserInfo(s);if(!s.idToken)return null;let a=W(s.idToken);if(typeof a.oid!=="string"||a.oid.trim().length===0)return T.error("Microsoft Entra ID token did not include a valid oid claim; unable to resolve a stable account identifier."),null;let c=e.profilePhotoSize||48;if(!e.disableProfilePhoto&&s.accessToken)await w(`https://graph.microsoft.com/v1.0/me/photos/${c}x${c}/$value`,{headers:{Authorization:`Bearer ${s.accessToken}`},async onResponse(f){if(!f.response.ok)return;try{let h=await f.response.clone().arrayBuffer();a.picture=`data:image/jpeg;base64, ${fe.encode(h)}`}catch(h){T.error(h&&typeof h==="object"&&"name"in h?h.name:"",h)}}});let u=await e.mapProfileToUser?.(a),d=a.email_verified!==void 0?a.email_verified:a.email&&(a.verified_primary_email?.includes(a.email)||a.verified_secondary_email?.includes(a.email))?!0:!1;return{user:{name:a.name,email:a.email,image:a.picture,emailVerified:d,...u},data:a}},refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async(s)=>{let a=e.disableDefaultScope?[]:["openid","profile","email","User.Read","offline_access"];if(e.scope)a.push(...e.scope);return At({refreshToken:s,options:{clientId:e.clientId,clientSecret:e.clientSecret},extraParams:{scope:a.join(" ")},tokenEndpoint:i,tokenEndpointAuth:o})},options:e}},eM=async(e,t,r)=>{let{data:n}=await w(`${r}/${t}/discovery/v2.0/keys`);if(!n?.keys)throw new l("BAD_REQUEST",{message:"Keys not found"});let i=n.keys.find((o)=>o.kid===e);if(!i)throw Error(`JWK with kid ${e} not found`);return await te(i,i.alg??"RS256")};var tM=(e)=>({id:"naver",name:"Naver",accountSubject:({profile:r})=>r.response.id,createAuthorizationURL({state:r,scopes:n,redirectURI:i,additionalParams:o}){let s=e.disableDefaultScope?[]:["profile","email"];if(e.scope)s.push(...e.scope);if(n)s.push(...n);return St({id:"naver",options:e,authorizationEndpoint:"https://nid.naver.com/oauth2.0/authorize",scopes:s,state:r,redirectURI:i,additionalParams:o})},validateAuthorizationCode:async({code:r,redirectURI:n})=>Tt({code:r,redirectURI:n,options:e,tokenEndpoint:"https://nid.naver.com/oauth2.0/token"}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async(r)=>At({refreshToken:r,options:{clientId:e.clientId,clientKey:e.clientKey,clientSecret:e.clientSecret},tokenEndpoint:"https://nid.naver.com/oauth2.0/token"}),async getUserInfo(r){if(e.getUserInfo)return e.getUserInfo(r);let{data:n,error:i}=await w("https://openapi.naver.com/v1/nid/me",{headers:{Authorization:`Bearer ${r.accessToken}`}});if(i||!n||n.resultcode!=="00")return null;let o=await e.mapProfileToUser?.(n),s=n.response||{};return{user:{name:s.name||s.nickname||"",email:s.email,image:s.profile_image,emailVerified:!1,...o},data:n}},options:e});var rM=(e)=>({id:"notion",name:"Notion",accountSubject:({profile:r})=>r.id,createAuthorizationURL({state:r,scopes:n,loginHint:i,redirectURI:o,additionalParams:s}){let a=e.disableDefaultScope?[]:[];if(e.scope)a.push(...e.scope);if(n)a.push(...n);return St({id:"notion",options:e,authorizationEndpoint:"https://api.notion.com/v1/oauth/authorize",scopes:a,state:r,redirectURI:o,loginHint:i,additionalParams:{...s??{},owner:"user"}})},validateAuthorizationCode:async({code:r,redirectURI:n})=>Tt({code:r,redirectURI:n,options:e,tokenEndpoint:"https://api.notion.com/v1/oauth/token",authentication:"basic"}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async(r)=>At({refreshToken:r,options:{clientId:e.clientId,clientKey:e.clientKey,clientSecret:e.clientSecret},tokenEndpoint:"https://api.notion.com/v1/oauth/token"}),async getUserInfo(r){if(e.getUserInfo)return e.getUserInfo(r);let{data:n,error:i}=await w("https://api.notion.com/v1/users/me",{headers:{Authorization:`Bearer ${r.accessToken}`,"Notion-Version":"2022-06-28"}});if(i||!n)return null;let o=n.bot?.owner?.user;if(!o)return null;let s=await e.mapProfileToUser?.(o);return{user:{name:o.name||"",email:o.person?.email||null,image:o.avatar_url,emailVerified:!1,...s},data:o}},options:e});var nM=(e)=>{let t=e.issuer||"https://idp.paybin.io",r=`${t}/oauth2/authorize`,n=`${t}/oauth2/token`;return{id:"paybin",name:"Paybin",accountSubject:({profile:i})=>i.sub,async createAuthorizationURL({state:i,scopes:o,codeVerifier:s,redirectURI:a,loginHint:c,additionalParams:u}){if(!e.clientId||!e.clientSecret)throw T.error("Client Id and Client Secret is required for Paybin. Make sure to provide them in the options."),new y("CLIENT_ID_AND_SECRET_REQUIRED");if(!s)throw new y("codeVerifier is required for Paybin");let d=e.disableDefaultScope?[]:["openid","email","profile"];if(e.scope)d.push(...e.scope);if(o)d.push(...o);return await St({id:"paybin",options:e,authorizationEndpoint:r,scopes:d,state:i,codeVerifier:s,redirectURI:a,prompt:e.prompt,loginHint:c,additionalParams:u})},validateAuthorizationCode:async({code:i,codeVerifier:o,redirectURI:s})=>Tt({code:i,codeVerifier:o,redirectURI:s,options:e,tokenEndpoint:n}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async(i)=>At({refreshToken:i,options:{clientId:e.clientId,clientKey:e.clientKey,clientSecret:e.clientSecret},tokenEndpoint:n}),async getUserInfo(i){if(e.getUserInfo)return e.getUserInfo(i);if(!i.idToken)return null;let o=W(i.idToken),s=await e.mapProfileToUser?.(o);return{user:{name:o.name||o.preferred_username||"",email:o.email,image:o.picture,emailVerified:o.email_verified||!1,...s},data:o}},options:e}};var iM=(e)=>{let t=(e.environment||"sandbox")==="sandbox",r=t?"https://www.sandbox.paypal.com/signin/authorize":"https://www.paypal.com/signin/authorize",n=t?"https://api-m.sandbox.paypal.com/v1/oauth2/token":"https://api-m.paypal.com/v1/oauth2/token",i=t?"https://api-m.sandbox.paypal.com/v1/identity/oauth2/userinfo":"https://api-m.paypal.com/v1/identity/oauth2/userinfo",o={clientId:e.clientId,clientSecret:e.clientSecret},s={method:"client_secret_basic"};return{id:"paypal",name:"PayPal",accountSubject:({profile:a})=>a.user_id,async createAuthorizationURL({state:a,codeVerifier:c,redirectURI:u,additionalParams:d}){if(!e.clientId||!e.clientSecret)throw T.error("Client Id and Client Secret is required for PayPal. Make sure to provide them in the options."),new y("CLIENT_ID_AND_SECRET_REQUIRED");return await St({id:"paypal",options:e,authorizationEndpoint:r,scopes:[],state:a,codeVerifier:c,redirectURI:u,prompt:e.prompt,additionalParams:d})},validateAuthorizationCode:async({code:a,codeVerifier:c,redirectURI:u})=>{try{return await Tt({code:a,codeVerifier:c,redirectURI:e.redirectURI||u,options:o,tokenEndpoint:n,tokenEndpointAuth:s})}catch(d){throw T.error("PayPal token exchange failed:",d),new y("FAILED_TO_GET_ACCESS_TOKEN")}},refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async(a)=>{try{return await At({refreshToken:a,options:o,tokenEndpoint:n,tokenEndpointAuth:s})}catch(c){throw T.error("PayPal token refresh failed:",c),new y("FAILED_TO_REFRESH_ACCESS_TOKEN")}},async getUserInfo(a){if(e.getUserInfo)return e.getUserInfo(a);if(!a.accessToken)return T.error("Access token is required to fetch PayPal user info"),null;try{let c=await w(`${i}?schema=paypalv1.1`,{headers:{Authorization:`Bearer ${a.accessToken}`,Accept:"application/json"}});if(!c.data)return T.error("Failed to fetch user info from PayPal"),null;let u=c.data;if(a.idToken){let f;try{f=W(a.idToken).sub}catch(p){return T.error("Failed to decode PayPal ID token:",p),null}let h=u.sub??u.user_id;if(!f||h!==f)return T.error("PayPal user info subject does not match ID token subject"),null}let d=await e.mapProfileToUser?.(u);return{user:{name:u.name,email:u.email,image:u.picture,emailVerified:u.email_verified,...d},data:u}}catch(c){return T.error("Failed to fetch user info from PayPal:",c),null}},options:e}};var oM=(e)=>({id:"polar",name:"Polar",accountSubject:({profile:r})=>r.id,createAuthorizationURL({state:r,scopes:n,codeVerifier:i,redirectURI:o,additionalParams:s}){let a=e.disableDefaultScope?[]:["openid","profile","email"];if(e.scope)a.push(...e.scope);if(n)a.push(...n);return St({id:"polar",options:e,authorizationEndpoint:"https://polar.sh/oauth2/authorize",scopes:a,state:r,codeVerifier:i,redirectURI:o,prompt:e.prompt,additionalParams:s})},validateAuthorizationCode:async({code:r,codeVerifier:n,redirectURI:i})=>Tt({code:r,codeVerifier:n,redirectURI:i,options:e,tokenEndpoint:"https://api.polar.sh/v1/oauth2/token"}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async(r)=>At({refreshToken:r,options:{clientId:e.clientId,clientKey:e.clientKey,clientSecret:e.clientSecret},tokenEndpoint:"https://api.polar.sh/v1/oauth2/token"}),async getUserInfo(r){if(e.getUserInfo)return e.getUserInfo(r);let{data:n,error:i}=await w("https://api.polar.sh/v1/oauth2/userinfo",{headers:{Authorization:`Bearer ${r.accessToken}`}});if(i)return null;let o=await e.mapProfileToUser?.(n);return{user:{name:n.public_name||n.username||"",email:n.email,image:n.avatar_url,emailVerified:n.email_verified??!1,...o},data:n}},options:e});var Ice="https://backboard.railway.com/oauth/auth",sM="https://backboard.railway.com/oauth/token",Dce="https://backboard.railway.com/oauth/me",aM=(e)=>({id:"railway",name:"Railway",accountSubject:({profile:t})=>t.sub,createAuthorizationURL({state:t,scopes:r,codeVerifier:n,redirectURI:i,additionalParams:o}){let s=e.disableDefaultScope?[]:["openid","email","profile"];if(e.scope)s.push(...e.scope);if(r)s.push(...r);return St({id:"railway",options:e,authorizationEndpoint:Ice,scopes:s,state:t,codeVerifier:n,redirectURI:i,additionalParams:o})},validateAuthorizationCode:async({code:t,codeVerifier:r,redirectURI:n})=>Tt({code:t,codeVerifier:r,redirectURI:n,options:e,tokenEndpoint:sM,authentication:"basic"}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async(t)=>At({refreshToken:t,options:{clientId:e.clientId,clientKey:e.clientKey,clientSecret:e.clientSecret},tokenEndpoint:sM,authentication:"basic"}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:r,error:n}=await w(Dce,{headers:{authorization:`Bearer ${t.accessToken}`}});if(n||!r)return null;let i=await e.mapProfileToUser?.(r);return{user:{name:r.name,email:r.email,image:r.picture,emailVerified:!1,...i},data:r}},options:e});import*as cM from"zod";var Uce="placeholder.invalid";function Na({identifier:e,namespace:t}){let r=cM.email().safeParse(`${e}@${t}.${Uce}`);if(!r.success)throw TypeError("Invalid placeholder email");return r.data}var uM=(e)=>{let r={clientId:e.clientId,clientSecret:e.clientSecret},n={method:"client_secret_basic"};return{id:"reddit",name:"Reddit",accountSubject:({profile:i})=>i.id,createAuthorizationURL({state:i,scopes:o,redirectURI:s,additionalParams:a}){let c=e.disableDefaultScope?[]:["identity"];if(e.scope)c.push(...e.scope);if(o)c.push(...o);return St({id:"reddit",options:e,authorizationEndpoint:"https://www.reddit.com/api/v1/authorize",scopes:c,state:i,redirectURI:s,duration:e.duration,additionalParams:a})},validateAuthorizationCode:async({code:i,redirectURI:o})=>Tt({code:i,redirectURI:e.redirectURI||o,options:r,tokenEndpoint:"https://www.reddit.com/api/v1/access_token",tokenEndpointAuth:n,headers:{accept:"text/plain","user-agent":"better-auth"}}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async(i)=>At({refreshToken:i,options:r,tokenEndpoint:"https://www.reddit.com/api/v1/access_token",tokenEndpointAuth:n}),async getUserInfo(i){if(e.getUserInfo)return e.getUserInfo(i);let{data:o,error:s}=await w("https://oauth.reddit.com/api/v1/me",{headers:{Authorization:`Bearer ${i.accessToken}`,"User-Agent":"better-auth"}});if(s)return null;let a=await e.mapProfileToUser?.(o),c=a?.email||Na({identifier:o.id,namespace:"reddit"});return{user:{name:o.name,image:o.icon_img?.split("?")[0],...a,email:c,emailVerified:a?.emailVerified??!1},data:o}},options:e}};var dM=(e)=>({id:"roblox",name:"Roblox",accountSubject:({profile:r})=>r.sub,createAuthorizationURL({state:r,scopes:n,redirectURI:i,additionalParams:o}){let s=e.disableDefaultScope?[]:["openid","profile"];if(e.scope)s.push(...e.scope);if(n)s.push(...n);return St({id:"roblox",options:e,authorizationEndpoint:"https://apis.roblox.com/oauth/v1/authorize",scopes:s,state:r,redirectURI:i,prompt:e.prompt||"select_account consent",additionalParams:o})},validateAuthorizationCode:async({code:r,redirectURI:n})=>Tt({code:r,redirectURI:e.redirectURI||n,options:e,tokenEndpoint:"https://apis.roblox.com/oauth/v1/token",authentication:"post"}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async(r)=>At({refreshToken:r,options:{clientId:e.clientId,clientKey:e.clientKey,clientSecret:e.clientSecret},tokenEndpoint:"https://apis.roblox.com/oauth/v1/token"}),async getUserInfo(r){if(e.getUserInfo)return e.getUserInfo(r);let{data:n,error:i}=await w("https://apis.roblox.com/oauth/v1/userinfo",{headers:{authorization:`Bearer ${r.accessToken}`}});if(i)return null;let o=await e.mapProfileToUser?.(n);return{user:{name:n.nickname||n.preferred_username||"",image:n.picture,email:Na({identifier:n.sub,namespace:"roblox"}),emailVerified:!1,...o},data:{...n}}},options:e});var lM=(e)=>{let t=(e.environment??"production")==="sandbox",r=e.loginUrl?`https://${e.loginUrl}/services/oauth2/authorize`:t?"https://test.salesforce.com/services/oauth2/authorize":"https://login.salesforce.com/services/oauth2/authorize",n=e.loginUrl?`https://${e.loginUrl}/services/oauth2/token`:t?"https://test.salesforce.com/services/oauth2/token":"https://login.salesforce.com/services/oauth2/token",i=e.loginUrl?`https://${e.loginUrl}/services/oauth2/userinfo`:t?"https://test.salesforce.com/services/oauth2/userinfo":"https://login.salesforce.com/services/oauth2/userinfo";return{id:"salesforce",name:"Salesforce",accountSubject:({profile:o})=>o.user_id,async createAuthorizationURL({state:o,scopes:s,codeVerifier:a,redirectURI:c,additionalParams:u}){if(!e.clientId||!e.clientSecret)throw T.error("Client Id and Client Secret are required for Salesforce. Make sure to provide them in the options."),new y("CLIENT_ID_AND_SECRET_REQUIRED");if(!a)throw new y("codeVerifier is required for Salesforce");let d=e.disableDefaultScope?[]:["openid","email","profile"];if(e.scope)d.push(...e.scope);if(s)d.push(...s);return St({id:"salesforce",options:e,authorizationEndpoint:r,scopes:d,state:o,codeVerifier:a,redirectURI:e.redirectURI||c,additionalParams:u})},validateAuthorizationCode:async({code:o,codeVerifier:s,redirectURI:a})=>Tt({code:o,codeVerifier:s,redirectURI:e.redirectURI||a,options:e,tokenEndpoint:n}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async(o)=>At({refreshToken:o,options:{clientId:e.clientId,clientSecret:e.clientSecret},tokenEndpoint:n}),async getUserInfo(o){if(e.getUserInfo)return e.getUserInfo(o);try{let{data:s}=await w(i,{headers:{Authorization:`Bearer ${o.accessToken}`}});if(!s)return T.error("Failed to fetch user info from Salesforce"),null;let a=await e.mapProfileToUser?.(s);return{user:{name:s.name,email:s.email,image:s.photos?.picture||s.photos?.thumbnail,emailVerified:s.email_verified??!1,...a},data:s}}catch(s){return T.error("Failed to fetch user info from Salesforce:",s),null}},options:e}};var fM=(e)=>({id:"slack",name:"Slack",accountSubject:({profile:r})=>r["https://slack.com/user_id"],createAuthorizationURL({state:r,scopes:n,redirectURI:i,additionalParams:o}){let s=e.disableDefaultScope?[]:["openid","profile","email"];if(n)s.push(...n);if(e.scope)s.push(...e.scope);return St({id:"slack",options:e,authorizationEndpoint:"https://slack.com/openid/connect/authorize",scopes:s,state:r,redirectURI:i,additionalParams:o})},validateAuthorizationCode:async({code:r,redirectURI:n})=>Tt({code:r,redirectURI:n,options:e,tokenEndpoint:"https://slack.com/api/openid.connect.token"}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async(r)=>At({refreshToken:r,options:{clientId:e.clientId,clientKey:e.clientKey,clientSecret:e.clientSecret},tokenEndpoint:"https://slack.com/api/openid.connect.token"}),async getUserInfo(r){if(e.getUserInfo)return e.getUserInfo(r);let{data:n,error:i}=await w("https://slack.com/api/openid.connect.userInfo",{headers:{authorization:`Bearer ${r.accessToken}`}});if(i)return null;let o=await e.mapProfileToUser?.(n);return{user:{name:n.name||"",email:n.email,emailVerified:n.email_verified,image:n.picture||n["https://slack.com/user_image_512"],...o},data:n}},options:e});var hM=(e)=>({id:"spotify",name:"Spotify",accountSubject:({profile:r})=>r.id,createAuthorizationURL({state:r,scopes:n,codeVerifier:i,redirectURI:o,additionalParams:s}){let a=e.disableDefaultScope?[]:["user-read-email"];if(e.scope)a.push(...e.scope);if(n)a.push(...n);return St({id:"spotify",options:e,authorizationEndpoint:"https://accounts.spotify.com/authorize",scopes:a,state:r,codeVerifier:i,redirectURI:o,additionalParams:s})},validateAuthorizationCode:async({code:r,codeVerifier:n,redirectURI:i})=>Tt({code:r,codeVerifier:n,redirectURI:i,options:e,tokenEndpoint:"https://accounts.spotify.com/api/token"}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async(r)=>At({refreshToken:r,options:{clientId:e.clientId,clientKey:e.clientKey,clientSecret:e.clientSecret},tokenEndpoint:"https://accounts.spotify.com/api/token"}),async getUserInfo(r){if(e.getUserInfo)return e.getUserInfo(r);let{data:n,error:i}=await w("https://api.spotify.com/v1/me",{method:"GET",headers:{Authorization:`Bearer ${r.accessToken}`}});if(i)return null;let o=await e.mapProfileToUser?.(n);return{user:{name:n.display_name,email:n.email,image:n.images[0]?.url,emailVerified:!1,...o},data:n}},options:e});var pM=(e)=>{let r={method:"custom",customizeRequest({body:n}){n.set("client_key",e.clientKey),n.set("client_secret",e.clientSecret)}};return{id:"tiktok",name:"TikTok",accountSubject:({profile:n})=>n.data.user.open_id,createAuthorizationURL({state:n,scopes:i,redirectURI:o,additionalParams:s}){let a=e.disableDefaultScope?[]:["user.info.profile"];if(e.scope)a.push(...e.scope);if(i)a.push(...i);let c=new URL("https://www.tiktok.com/v2/auth/authorize");if(c.searchParams.set("scope",a.join(",")),c.searchParams.set("response_type","code"),c.searchParams.set("client_key",e.clientKey),c.searchParams.set("redirect_uri",e.redirectURI||o),c.searchParams.set("state",n),s)for(let[u,d]of Object.entries(s)){if(id.has(u))continue;if(u==="client_key")continue;c.searchParams.set(u,d)}return c},validateAuthorizationCode:async({code:n,codeVerifier:i,redirectURI:o})=>Tt({code:n,codeVerifier:i,redirectURI:e.redirectURI||o,options:{},tokenEndpoint:"https://open.tiktokapis.com/v2/oauth/token/",tokenEndpointAuth:r}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async(n)=>At({refreshToken:n,options:{},tokenEndpoint:"https://open.tiktokapis.com/v2/oauth/token/",tokenEndpointAuth:r}),async getUserInfo(n){if(e.getUserInfo)return e.getUserInfo(n);let{data:i,error:o}=await w(`https://open.tiktokapis.com/v2/user/info/?fields=${["open_id","avatar_large_url","display_name","username"].join(",")}`,{headers:{authorization:`Bearer ${n.accessToken}`}});if(o)return null;return{user:{email:i.data.user.email||Na({identifier:i.data.user.open_id,namespace:"tiktok"}),name:i.data.user.display_name||i.data.user.username||"",image:i.data.user.avatar_large_url,emailVerified:!1},data:i}},options:e}};var mM=(e)=>({id:"twitch",name:"Twitch",accountSubject:({profile:r})=>r.sub,createAuthorizationURL({state:r,scopes:n,redirectURI:i,additionalParams:o}){let s=e.disableDefaultScope?[]:["user:read:email","openid"];if(e.scope)s.push(...e.scope);if(n)s.push(...n);return St({id:"twitch",redirectURI:i,options:e,authorizationEndpoint:"https://id.twitch.tv/oauth2/authorize",scopes:s,state:r,claims:e.claims||["email","email_verified","preferred_username","picture"],additionalParams:o})},validateAuthorizationCode:async({code:r,redirectURI:n})=>Tt({code:r,redirectURI:n,options:e,tokenEndpoint:"https://id.twitch.tv/oauth2/token"}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async(r)=>At({refreshToken:r,options:{clientId:e.clientId,clientKey:e.clientKey,clientSecret:e.clientSecret},tokenEndpoint:"https://id.twitch.tv/oauth2/token"}),async getUserInfo(r){if(e.getUserInfo)return e.getUserInfo(r);let n=r.idToken;if(!n)return T.error("No idToken found in token"),null;let i=W(n),o=await e.mapProfileToUser?.(i);return{user:{name:i.preferred_username,email:i.email,image:i.picture,emailVerified:i.email_verified,...o},data:i}},options:e});var gM=(e)=>({id:"twitter",name:"Twitter",accountSubject:({profile:r})=>r.data.id,createAuthorizationURL(r){let n=e.disableDefaultScope?[]:["users.read","tweet.read","offline.access","users.email"];if(e.scope)n.push(...e.scope);if(r.scopes)n.push(...r.scopes);return St({id:"twitter",options:e,authorizationEndpoint:"https://x.com/i/oauth2/authorize",scopes:n,state:r.state,codeVerifier:r.codeVerifier,redirectURI:r.redirectURI,additionalParams:r.additionalParams})},validateAuthorizationCode:async({code:r,codeVerifier:n,redirectURI:i})=>Tt({code:r,codeVerifier:n,authentication:"basic",redirectURI:i,options:e,tokenEndpoint:"https://api.x.com/2/oauth2/token"}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async(r)=>At({refreshToken:r,options:{clientId:e.clientId,clientKey:e.clientKey,clientSecret:e.clientSecret},authentication:"basic",tokenEndpoint:"https://api.x.com/2/oauth2/token"}),async getUserInfo(r){if(e.getUserInfo)return e.getUserInfo(r);let{data:n,error:i}=await w("https://api.x.com/2/users/me?user.fields=profile_image_url",{method:"GET",headers:{Authorization:`Bearer ${r.accessToken}`}});if(i)return null;let{data:o,error:s}=await w("https://api.x.com/2/users/me?user.fields=confirmed_email",{method:"GET",headers:{Authorization:`Bearer ${r.accessToken}`}}),a=!1;if(!s&&o?.data?.confirmed_email)n.data.email=o.data.confirmed_email,a=!0;let c=await e.mapProfileToUser?.(n);return{user:{name:n.data.name,email:n.data.email||Na({identifier:n.data.id,namespace:"twitter"}),image:n.data.profile_image_url,emailVerified:a,...c},data:n}},options:e});var yM=(e)=>({id:"vercel",name:"Vercel",accountSubject:({profile:t})=>t.sub,createAuthorizationURL({state:t,scopes:r,codeVerifier:n,redirectURI:i,additionalParams:o}){if(!n)throw new y("codeVerifier is required for Vercel");let s=void 0;if(e.scope!==void 0||r!==void 0){if(s=[],e.scope)s.push(...e.scope);if(r)s.push(...r)}return St({id:"vercel",options:e,authorizationEndpoint:"https://vercel.com/oauth/authorize",scopes:s,state:t,codeVerifier:n,redirectURI:i,additionalParams:o})},validateAuthorizationCode:async({code:t,codeVerifier:r,redirectURI:n})=>Tt({code:t,codeVerifier:r,redirectURI:n,options:e,tokenEndpoint:"https://api.vercel.com/login/oauth/token"}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:r,error:n}=await w("https://api.vercel.com/login/oauth/userinfo",{headers:{Authorization:`Bearer ${t.accessToken}`}});if(n||!r)return null;let i=await e.mapProfileToUser?.(r);return{user:{name:r.name??r.preferred_username??"",email:r.email,image:r.picture,emailVerified:r.email_verified??!1,...i},data:r}},options:e});var wM=(e)=>({id:"vk",name:"VK",accountSubject:({profile:r})=>r.user.user_id,async createAuthorizationURL({state:r,scopes:n,codeVerifier:i,redirectURI:o,additionalParams:s}){let a=e.disableDefaultScope?[]:["email","phone"];if(e.scope)a.push(...e.scope);if(n)a.push(...n);return St({id:"vk",options:e,authorizationEndpoint:"https://id.vk.com/authorize",scopes:a,state:r,redirectURI:o,codeVerifier:i,additionalParams:s})},validateAuthorizationCode:async({code:r,codeVerifier:n,redirectURI:i,deviceId:o})=>Tt({code:r,codeVerifier:n,redirectURI:e.redirectURI||i,options:e,deviceId:o,tokenEndpoint:"https://id.vk.com/oauth2/auth"}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async(r)=>At({refreshToken:r,options:{clientId:e.clientId,clientKey:e.clientKey,clientSecret:e.clientSecret},tokenEndpoint:"https://id.vk.com/oauth2/auth"}),async getUserInfo(r){if(e.getUserInfo)return e.getUserInfo(r);if(!r.accessToken)return null;let{data:n,error:i}=await w("https://id.vk.com/oauth2/user_info",{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({access_token:r.accessToken,client_id:e.clientId}).toString()});if(i)return null;let o=await e.mapProfileToUser?.(n);if(!n.user.email&&!o?.email)return null;return{user:{first_name:n.user.first_name,last_name:n.user.last_name,email:n.user.email,image:n.user.avatar,emailVerified:!1,birthday:n.user.birthday,sex:n.user.sex,name:`${n.user.first_name} ${n.user.last_name}`,...o},data:n}},options:e});var _M=(e)=>({id:"wechat",name:"WeChat",accountSubject:({profile:t})=>t.unionid||t.openid,createAuthorizationURL({state:t,scopes:r,redirectURI:n,additionalParams:i}){let o=e.disableDefaultScope?[]:["snsapi_login"];e.scope&&o.push(...e.scope),r&&o.push(...r);let s=new URL("https://open.weixin.qq.com/connect/qrconnect");if(s.searchParams.set("scope",o.join(",")),s.searchParams.set("response_type","code"),s.searchParams.set("appid",e.clientId),s.searchParams.set("redirect_uri",e.redirectURI||n),s.searchParams.set("state",t),s.searchParams.set("lang",e.lang||"cn"),i)for(let[a,c]of Object.entries(i)){if(id.has(a))continue;if(a==="appid")continue;s.searchParams.set(a,c)}return s.hash="wechat_redirect",s},validateAuthorizationCode:async({code:t})=>{let{data:r,error:n}=await w("https://api.weixin.qq.com/sns/oauth2/access_token?"+new URLSearchParams({appid:e.clientId,secret:e.clientSecret,code:t,grant_type:"authorization_code"}).toString(),{method:"GET"});if(n||!r||r.errcode)throw Error(`Failed to validate authorization code: ${r?.errmsg||n?.message||"Unknown error"}`);return{tokenType:"Bearer",accessToken:r.access_token,refreshToken:r.refresh_token,accessTokenExpiresAt:new Date(Date.now()+r.expires_in*1000),scopes:r.scope.split(","),openid:r.openid,unionid:r.unionid}},refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async(t)=>{let{data:r,error:n}=await w("https://api.weixin.qq.com/sns/oauth2/refresh_token?"+new URLSearchParams({appid:e.clientId,grant_type:"refresh_token",refresh_token:t}).toString(),{method:"GET"});if(n||!r||r.errcode)throw Error(`Failed to refresh access token: ${r?.errmsg||n?.message||"Unknown error"}`);return{tokenType:"Bearer",accessToken:r.access_token,refreshToken:r.refresh_token,accessTokenExpiresAt:new Date(Date.now()+r.expires_in*1000),scopes:r.scope.split(",")}},async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let r=t.openid;if(!r)return null;let{data:n,error:i}=await w("https://api.weixin.qq.com/sns/userinfo?"+new URLSearchParams({access_token:t.accessToken||"",openid:r,lang:"zh_CN"}).toString(),{method:"GET"});if(i||!n||n.errcode)return null;let o=await e.mapProfileToUser?.(n),s=n.unionid||n.openid||r;return{user:{name:n.nickname,email:n.email||Na({identifier:s,namespace:"wechat"}),image:n.headimgurl,emailVerified:!1,...o},data:n}},options:e});var bM=(e)=>{let t={pkce:!0,...e};return{id:"zoom",name:"Zoom",accountSubject:({profile:r})=>r.id,createAuthorizationURL:async({state:r,redirectURI:n,codeVerifier:i,additionalParams:o})=>St({id:"zoom",options:t,authorizationEndpoint:"https://zoom.us/oauth/authorize",state:r,redirectURI:n,codeVerifier:t.pkce?i:void 0,additionalParams:o}),validateAuthorizationCode:async({code:r,redirectURI:n,codeVerifier:i})=>Tt({code:r,redirectURI:t.redirectURI||n,codeVerifier:i,options:t,tokenEndpoint:"https://zoom.us/oauth/token",authentication:"post"}),refreshAccessToken:t.refreshAccessToken?t.refreshAccessToken:async(r)=>At({refreshToken:r,options:{clientId:t.clientId,clientKey:t.clientKey,clientSecret:t.clientSecret},tokenEndpoint:"https://zoom.us/oauth/token"}),async getUserInfo(r){if(t.getUserInfo)return t.getUserInfo(r);let{data:n,error:i}=await w("https://api.zoom.us/v2/users/me",{headers:{authorization:`Bearer ${r.accessToken}`}});if(i)return null;let o=await t.mapProfileToUser?.(n);return{user:{name:n.display_name,image:n.pic_url,email:n.email,emailVerified:Boolean(n.verified),...o},data:{...n}}}}};import*as lw from"zod";var an={apple:NL,atlassian:CL,cloudflare:DL,cognito:UL,discord:LL,facebook:BL,figma:jL,github:$L,microsoft:ZL,google:WL,huggingface:VL,slack:fM,spotify:hM,twitch:mM,twitter:gM,dropbox:ML,kick:KL,linear:QL,linkedin:YL,gitlab:FL,tiktok:pM,reddit:uM,roblox:dM,salesforce:lM,vk:wM,zoom:bM,notion:rM,kakao:GL,naver:tM,line:JL,paybin:nM,paypal:iM,polar:oM,railway:aM,vercel:yM,wechat:_M},Pce=Object.keys(an),fw=lw.enum(Pce).or(lw.string());import*as An from"zod";function EM(e){if(!e)return[];return e.split(",").map((t)=>t.trim()).filter(Boolean)}var SM=v("/list-accounts",{method:"GET",use:[K],metadata:{openapi:{operationId:"listUserAccounts",description:"List all accounts linked to the user",responses:{"200":{description:"Success",content:{"application/json":{schema:{type:"array",items:{type:"object",properties:{id:{type:"string"},providerId:{type:"string"},createdAt:{type:"string",format:"date-time"},updatedAt:{type:"string",format:"date-time"},accountId:{type:"string"},userId:{type:"string"},scopes:{type:"array",items:{type:"string"}}},required:["id","providerId","createdAt","updatedAt","accountId","userId","scopes"]}}}}}}}}},async(e)=>{let t=e.context.session,r=await e.context.internalAdapter.findAccounts(t.user.id);return e.json(r.map((n)=>{let{scope:i,...o}=Ry(e.context.options,n);return{...o,scopes:EM(i)}}))}),AM=v("/link-social",{method:"POST",requireHeaders:!0,body:An.object({callbackURL:An.string().meta({description:"The URL to redirect to after the user has signed in"}).optional(),provider:fw,idToken:An.object({token:An.string(),nonce:An.string().optional(),accessToken:An.string().optional(),refreshToken:An.string().optional()}).optional(),requestSignUp:An.boolean().optional(),scopes:An.array(An.string()).meta({description:"Additional scopes to request from the provider"}).optional(),errorCallbackURL:An.string().meta({description:"The URL to redirect to if there is an error during the link process"}).optional(),disableRedirect:An.boolean().meta({description:"Disable automatic redirection to the provider. Useful for handling the redirection yourself"}).optional(),loginHint:An.string().meta({description:"The login hint to use for the authorization code request"}).optional(),additionalParams:gp,additionalData:An.record(An.string(),An.any()).optional()}),use:[K],metadata:{openapi:{description:"Link a social account to the user",operationId:"linkSocialAccount",responses:{"200":{description:"Success",content:{"application/json":{schema:{type:"object",properties:{url:{type:"string",description:"The authorization URL to redirect the user to"},redirect:{type:"boolean",description:"Indicates if the user should be redirected to the authorization URL"},status:{type:"boolean"}},required:["redirect"]}}}}}}}},async(e)=>{let t=e.context.session,r=await Ta(e.context.socialProviders,{value:e.body.provider});if(!r)throw e.context.logger.error("Provider not found. Make sure to add the provider in your auth config",{provider:e.body.provider}),l.from("NOT_FOUND",S.PROVIDER_NOT_FOUND);if(e.body.idToken){if(!Ap(r))throw e.context.logger.error("Provider does not support id token verification",{provider:e.body.provider}),l.from("NOT_FOUND",S.ID_TOKEN_NOT_SUPPORTED);let{token:s,nonce:a}=e.body.idToken;if(!await Tp(r,s,a,e))throw e.context.logger.warn("Invalid id token",{provider:e.body.provider}),l.from("UNAUTHORIZED",S.INVALID_TOKEN);let c=await r.getUserInfo({idToken:s,accessToken:e.body.idToken.accessToken,refreshToken:e.body.idToken.refreshToken});if(!c||!c?.user)throw e.context.logger.error("Failed to get user info",{provider:e.body.provider}),l.from("UNAUTHORIZED",S.FAILED_TO_GET_USER_INFO);if(!c.user.email)throw e.context.logger.error(Ml(e.body.provider,{source:"id_token"}),{provider:e.body.provider}),l.from("UNAUTHORIZED",S.USER_EMAIL_NOT_FOUND);let u=await Yy(r,{idToken:s,accessToken:e.body.idToken.accessToken,refreshToken:e.body.idToken.refreshToken},c.data),d=await e.context.internalAdapter.findAccountByKey(u);if(d?.userId===t.user.id){let f=Object.fromEntries(Object.entries({providerId:r.id,accessToken:await Ni(e.body.idToken.accessToken,e.context),idToken:s,refreshToken:await Ni(e.body.idToken.refreshToken,e.context)}).filter(([h,p])=>p!==void 0));return await e.context.internalAdapter.updateAccount(d.id,f),await kp(e,t.user.id,c.user),e.json({url:"",status:!0,redirect:!1})}if(d)throw l.from("CONFLICT",S.SOCIAL_ACCOUNT_ALREADY_LINKED);if(!e.context.trustedProviders.includes(r.id)&&!c.user.emailVerified||e.context.options.account?.accountLinking?.enabled===!1)throw l.from("UNAUTHORIZED",{message:"Account not linked - linking not allowed",code:"LINKING_NOT_ALLOWED"});if(c.user.email?.toLowerCase()!==t.user.email.toLowerCase()&&e.context.options.account?.accountLinking?.allowDifferentEmails!==!0)throw l.from("UNAUTHORIZED",{message:"Account not linked - different emails not allowed",code:"LINKING_DIFFERENT_EMAILS_NOT_ALLOWED"});try{await e.context.internalAdapter.createAccount({userId:t.user.id,...u,accessToken:await Ni(e.body.idToken.accessToken,e.context),idToken:s,refreshToken:await Ni(e.body.idToken.refreshToken,e.context)})}catch{throw l.from("EXPECTATION_FAILED",{message:"Account not linked - unable to create account",code:"LINKING_FAILED"})}return await kp(e,t.user.id,c.user),e.json({url:"",status:!0,redirect:!1})}let n=$l(r),i=await Fl(e,{link:{userId:t.user.id,email:t.user.email},additionalData:e.body.additionalData,idTokenNonce:n}),o=await r.createAuthorizationURL({state:i.state,codeVerifier:i.codeVerifier,idTokenNonce:n,redirectURI:`${e.context.baseURL}${nu(r)}`,scopes:e.body.scopes,loginHint:e.body.loginHint,additionalParams:e.body.additionalParams});if(!e.body.disableRedirect)e.setHeader("Location",o.toString());return e.json({url:o.toString(),redirect:!e.body.disableRedirect})}),TM=v("/unlink-account",{method:"POST",body:An.object({accountId:An.string().meta({description:"The Better Auth account ID to unlink"})}),use:[Jy],metadata:{openapi:{description:"Unlink an account",responses:{"200":{description:"Success",content:{"application/json":{schema:{type:"object",properties:{status:{type:"boolean"}}}}}}}}}},async(e)=>{let{accountId:t}=e.body,r=await e.context.internalAdapter.findAccounts(e.context.session.user.id);if(r.length===1&&!e.context.options.account?.accountLinking?.allowUnlinkingAll)throw l.from("BAD_REQUEST",S.FAILED_TO_UNLINK_LAST_ACCOUNT);let n=r.find((i)=>i.id===t);if(!n)throw l.from("BAD_REQUEST",S.ACCOUNT_NOT_FOUND);return await e.context.internalAdapter.deleteAccount(n.id),e.json({status:!0})});async function rv(e,t){let r=await Gr(e,{disableCookieCache:ru(e)});if(!r&&(e.request||e.headers))throw e.error("UNAUTHORIZED");let n=r?.user?.id||t;if(!n)throw l.from("BAD_REQUEST",{message:"Either userId or session is required",code:"USER_ID_OR_SESSION_REQUIRED"});return n}var nv=An.union([An.strictObject({accountId:An.string().meta({description:"The Better Auth account ID"}),userId:An.string().meta({description:"The user ID associated with the account"}).optional()}),An.strictObject({useAccountCookie:An.literal(!0).meta({description:"Select the current OAuth account from its signed cookie"}),userId:An.string().meta({description:"The user ID associated with the account"}).optional()})]);function vM(e,t,{resolvedUserId:r,selection:n}){return(!Ey(e.context.options)||t.userId===r)&&("accountId"in n?t.id===n.accountId:!0)}async function iv(e,{resolvedUserId:t,selection:r}){if("accountId"in r){let n=(await e.context.internalAdapter.findAccounts(t)).find((i)=>i.id===r.accountId);if(n)return{account:n,accountCookie:null}}else if(e.context.options.account?.storeAccountCookie){let n=await Fy(e);if(n&&vM(e,n,{resolvedUserId:t,selection:r}))return{account:n,accountCookie:n}}throw l.from("BAD_REQUEST",S.ACCOUNT_NOT_FOUND)}async function kM(e,{resolvedUserId:t,selection:r,account:n}){let i=n??(await iv(e,{resolvedUserId:t,selection:r})).account;if(!vM(e,i,{resolvedUserId:t,selection:r}))throw l.from("BAD_REQUEST",S.ACCOUNT_NOT_FOUND);let o=await Ta(e.context.socialProviders,{value:i.providerId});if(!o)throw l.from("BAD_REQUEST",{message:`Provider ${i.providerId} is not supported.`,code:"PROVIDER_NOT_SUPPORTED"});try{let s=null,a=i.accessTokenExpiresAt&&new Date(i.accessTokenExpiresAt).getTime()-Date.now()<5000;if(i.refreshToken&&a&&o.refreshAccessToken){let u=await ew(i.refreshToken,e.context);s=await o.refreshAccessToken(u,e);let d={accessToken:await Ni(s?.accessToken,e.context),accessTokenExpiresAt:s?.accessTokenExpiresAt,refreshToken:s?.refreshToken?await Ni(s.refreshToken,e.context):i.refreshToken,refreshTokenExpiresAt:s?.refreshTokenExpiresAt??i.refreshTokenExpiresAt,idToken:s?.idToken||i.idToken},f=null;if(i.id)f=await e.context.internalAdapter.updateAccount(i.id,d);if(e.context.options.account?.storeAccountCookie)await uc(e,{...i,...f??d})}let c=(()=>{if(s?.accessTokenExpiresAt){if(typeof s.accessTokenExpiresAt==="string")return new Date(s.accessTokenExpiresAt);return s.accessTokenExpiresAt}if(i.accessTokenExpiresAt){if(typeof i.accessTokenExpiresAt==="string")return new Date(i.accessTokenExpiresAt);return i.accessTokenExpiresAt}})();return{accessToken:s?.accessToken??await ew(i.accessToken??"",e.context),accessTokenExpiresAt:c,scopes:EM(i.scope),idToken:s?.idToken??i.idToken??void 0}}catch(s){throw l.from("BAD_REQUEST",{message:"Failed to get a valid access token",code:"FAILED_TO_GET_ACCESS_TOKEN"})}}var RM=v("/get-access-token",{method:"POST",body:nv,metadata:{openapi:{description:"Get a valid access token, doing a refresh if needed",responses:{200:{description:"A Valid access token",content:{"application/json":{schema:{type:"object",properties:{tokenType:{type:"string"},idToken:{type:"string"},accessToken:{type:"string"},accessTokenExpiresAt:{type:"string",format:"date-time"}}}}}},400:{description:"Invalid refresh token or provider configuration"}}}}},async(e)=>{let{userId:t}=e.body,r=await kM(e,{resolvedUserId:await rv(e,t),selection:e.body});return e.json(r)}),NM=v("/refresh-token",{method:"POST",body:nv,metadata:{openapi:{description:"Refresh the access token using a refresh token",responses:{200:{description:"Access token refreshed successfully",content:{"application/json":{schema:{type:"object",properties:{tokenType:{type:"string"},idToken:{type:"string"},accessToken:{type:"string"},refreshToken:{type:"string"},accessTokenExpiresAt:{type:"string",format:"date-time"},refreshTokenExpiresAt:{type:"string",format:"date-time"}}}}}},400:{description:"Invalid refresh token or provider configuration"}}}}},async(e)=>{let{userId:t}=e.body,{account:r,accountCookie:n}=await iv(e,{resolvedUserId:await rv(e,t),selection:e.body}),i=await Ta(e.context.socialProviders,{value:r.providerId});if(!i)throw l.from("BAD_REQUEST",{message:`Provider ${r.providerId} is not supported.`,code:"PROVIDER_NOT_SUPPORTED"});if(!i.refreshAccessToken)throw l.from("BAD_REQUEST",{message:`Provider ${r.providerId} does not support token refreshing.`,code:"TOKEN_REFRESH_NOT_SUPPORTED"});let o=r.refreshToken??void 0;if(!o)throw l.from("BAD_REQUEST",{message:"Refresh token not found",code:"REFRESH_TOKEN_NOT_FOUND"});try{let s=await ew(o,e.context),a=await i.refreshAccessToken(s,e),c=a.refreshToken?await Ni(a.refreshToken,e.context):o,u=a.refreshTokenExpiresAt??r.refreshTokenExpiresAt,d={accessToken:await Ni(a.accessToken,e.context),refreshToken:c,accessTokenExpiresAt:a.accessTokenExpiresAt,refreshTokenExpiresAt:u,idToken:a.idToken||r.idToken},f=null;if(r.id)f=await e.context.internalAdapter.updateAccount(r.id,d);if(n?.id===r.id&&e.context.options.account?.storeAccountCookie)await uc(e,{...n,...f??d});let h=f?.scope??r.scope;return e.json({accessToken:a.accessToken,refreshToken:a.refreshToken??s,accessTokenExpiresAt:a.accessTokenExpiresAt,refreshTokenExpiresAt:u,scope:h,idToken:a.idToken||r.idToken,providerId:r.providerId,accountId:r.id})}catch(s){throw l.from("BAD_REQUEST",{message:"Failed to refresh access token",code:"FAILED_TO_REFRESH_ACCESS_TOKEN"})}}),xM=v("/account-info",{method:"GET",metadata:{openapi:{description:"Get the account info provided by the provider",responses:{"200":{description:"Success",content:{"application/json":{schema:{type:"object",properties:{user:{type:"object",properties:{name:{type:"string"},email:{type:"string",nullable:!0},image:{type:"string"},emailVerified:{type:"boolean"}},required:["emailVerified"]},account:{type:"object",properties:{id:{type:"string"},providerId:{type:"string"},accountId:{type:"string"}},required:["id","providerId","accountId"],additionalProperties:!1},data:{type:"object",properties:{},additionalProperties:!0}},required:["user","data","account"],additionalProperties:!1}}}}}}},query:nv},async(e)=>{let{userId:t}=e.query,r=await rv(e,t),{account:n}=await iv(e,{resolvedUserId:r,selection:e.query}),i=await Ta(e.context.socialProviders,{value:n.providerId});if(!i)throw l.from("BAD_REQUEST",{message:"Account is not associated with a configured social provider.",code:"PROVIDER_NOT_CONFIGURED"});let o=await kM(e,{resolvedUserId:r,selection:e.query,account:n});if(!o.accessToken)throw l.from("BAD_REQUEST",{message:"Access token not found",code:"ACCESS_TOKEN_NOT_FOUND"});let s=await i.getUserInfo({...o,accessToken:o.accessToken});if(!s)throw l.from("UNAUTHORIZED",S.FAILED_TO_GET_USER_INFO);return e.json({...s,account:{id:n.id,providerId:n.providerId,accountId:n.accountId}})});async function CM(e,t,r){if(r.iss&&t.issuer&&r.iss!==t.issuer)return e.context.logger.error("OAuth issuer mismatch",{expected:t.issuer,received:r.iss}),{error:Ri.ISSUER_MISMATCH};if(t.requiresIdTokenNonce&&!r.idTokenNonce)return e.context.logger.error("OAuth id_token nonce binding required but no expected nonce was found in state",{providerId:t.id}),{error:Ri.NONCE_BINDING_MISSING};let n;try{n=await t.validateAuthorizationCode({code:r.code,codeVerifier:r.codeVerifier,deviceId:r.deviceId,redirectURI:`${e.context.baseURL}${nu(t)}`})}catch(s){return e.context.logger.error("Failed to validate authorization code",s),{error:Ri.INVALID_CODE}}if(!n)return{error:Ri.INVALID_CODE};let i=await t.getUserInfo({...n,expectedIdTokenNonce:r.idTokenNonce,user:ti(r.user)??void 0});if(!i?.user)return e.context.logger.error("Unable to get user info"),{error:Ri.UNABLE_TO_GET_USER_INFO};let o=await OT(t,n,i.data).catch((s)=>(e.context.logger.error("Unable to derive provider account identity",{providerId:t.id,error:s}),null));if(!o)return{error:Ri.UNABLE_TO_GET_USER_INFO};return{tokens:n,userInfo:i.user,providerProfile:Qy(i.data),accountKey:o}}var zl={scope:"server"};import*as xa from"zod";var ad=xa.object({code:xa.string().optional(),error:xa.string().optional(),device_id:xa.string().optional(),error_description:xa.string().optional(),state:xa.string().optional(),user:xa.string().optional(),iss:xa.string().optional()}),OM=v("/callback/:id",{method:["GET","POST"],operationId:"handleOAuthCallback",body:ad.optional(),query:ad.optional(),metadata:{...zl,allowedMediaTypes:["application/x-www-form-urlencoded","application/json"]}},async(e)=>{let t,r=e.context.options.onAPIError?.errorURL||`${e.context.baseURL}/error`;if(e.method==="POST"){let ae=e.body?ad.parse(e.body):{},He=e.query?ad.parse(e.query):{},Be=ad.parse({...ae,...He}),Ke=new URLSearchParams;for(let[Ve,Je]of Object.entries(Be))if(Je!==void 0&&Je!==null)Ke.set(Ve,String(Je));let Te=`${e.context.baseURL}/callback/${e.params.id}?${Ke.toString()}`;throw e.redirect(Te)}try{if(e.method==="GET")t=ad.parse(e.query);else if(e.method==="POST")t=ad.parse(e.body);else throw Error("Unsupported method")}catch(ae){e.context.logger.error("INVALID_CALLBACK_REQUEST",ae);let He=us(r,new URLSearchParams({error:"invalid_callback_request"}));throw e.redirect(He)}let{code:n,error:i,state:o,error_description:s,device_id:a,user:c,iss:u}=t;if(o===void 0&&n){let ae=await Ta(e.context.socialProviders,{value:e.params.id});if(ae?.allowIdpInitiated){let He=$l(ae),{state:Be,codeVerifier:Ke}=await Fl(e,{idTokenNonce:He}),Te=await ae.createAuthorizationURL({state:Be,codeVerifier:Ke,idTokenNonce:He,redirectURI:`${e.context.baseURL}${nu(ae)}`});throw e.redirect(Te.toString())}}if(!o){e.context.logger.error("State not found",i);let ae=us(r,new URLSearchParams({error:"state_not_found"}));throw e.redirect(ae)}let{codeVerifier:d,callbackURL:f,link:h,errorURL:p,newUserURL:g,requestSignUp:_,idTokenNonce:R}=await RL(e);function O(ae,He){let Be=p??r,Ke=new URLSearchParams({error:ae});if(He)Ke.set("error_description",He);let Te=us(Be,Ke);throw e.redirect(Te)}if(i)O(i,s);if(!n)throw e.context.logger.warn("Code not found"),O(Ri.NO_CODE);let I=await Ta(e.context.socialProviders,{value:e.params.id});if(!I)throw e.context.logger.warn("OAuth provider not found",{providerId:e.params.id}),O(Ri.PROVIDER_NOT_FOUND);let Ne=await CM(e,I,{code:n,codeVerifier:d,iss:u,deviceId:a,user:c,idTokenNonce:R});if(Ne.error)throw O(Ne.error);let{tokens:k,userInfo:j,providerProfile:re,accountKey:Oe}=Ne,{accountId:ne}=Oe;if(!f)throw e.context.logger.error("No callback URL found"),O(Ri.NO_CALLBACK_URL);let M={...Oe,...k,scope:k.scopes?.join(",")};if(h){let ae=await TL(e,{link:h,userInfo:j,account:M,profile:re,scopes:k.scopes});if(!ae.linked)return O(ae.error.code,ae.error.message);throw e.redirect(f)}if(!j.email)return e.context.logger.error(Ml(I.id)),O(Ri.EMAIL_NOT_FOUND);let F;try{F=await dw(e,{userInfo:{...j,id:ne,email:j.email,name:j.name||""},account:M,callbackURL:f,disableSignUp:I.disableImplicitSignUp&&!_||I.options?.disableSignUp,overrideUserInfo:I.options?.overrideUserInfoOnSignIn,source:{method:"oauth",oauth:{providerId:I.id,profile:re}}})}catch(ae){if(hi(ae)&&ae.body?.code)O(ae.body.code,ae.body.message);throw ae}if(F.error)return e.context.logger.error(F.error.split(" ").join("_")),O(F.error.split(" ").join("_"));let{session:ce,user:de}=F.data;await ki(e,{session:ce,user:de});let pe;try{pe=(F.isRegister?g||f:f).toString()}catch{pe=F.isRegister?g||f:f}throw e.redirect(pe)});function IM(e){return e.replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;").replace(/&(?!amp;|lt;|gt;|quot;|#39;|#x[0-9a-fA-F]+;|#[0-9]+;)/g,"&amp;")}var Lce=(e,t="Unknown",r=null)=>{let n=e.onAPIError?.customizeDefaultErrorPage;return`<!DOCTYPE html>
155
+ <html lang="en">
156
+ <head>
157
+ <meta charset="UTF-8" />
158
+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />
159
+ <title>Error</title>
160
+ <style>
161
+ * {
162
+ box-sizing: border-box;
163
+ }
164
+ body {
165
+ font-family: ${n?.font?.defaultFamily||"-apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif"};
166
+ background: ${n?.colors?.background||"var(--background)"};
167
+ color: var(--foreground);
168
+ margin: 0;
169
+ }
170
+ :root,
171
+ :host {
172
+ --spacing: 0.25rem;
173
+ --container-md: 28rem;
174
+ --text-sm: ${n?.size?.textSm||"0.875rem"};
175
+ --text-sm--line-height: calc(1.25 / 0.875);
176
+ --text-2xl: ${n?.size?.text2xl||"1.5rem"};
177
+ --text-2xl--line-height: calc(2 / 1.5);
178
+ --text-4xl: ${n?.size?.text4xl||"2.25rem"};
179
+ --text-4xl--line-height: calc(2.5 / 2.25);
180
+ --text-6xl: ${n?.size?.text6xl||"3rem"};
181
+ --text-6xl--line-height: 1;
182
+ --font-weight-medium: 500;
183
+ --font-weight-semibold: 600;
184
+ --font-weight-bold: 700;
185
+ --default-transition-duration: 150ms;
186
+ --default-transition-timing-function: cubic-bezier(0.4, 0, 0.2, 1);
187
+ --radius: ${n?.size?.radiusSm||"0.625rem"};
188
+ --default-mono-font-family: ${n?.font?.monoFamily||"var(--font-geist-mono)"};
189
+ --primary: ${n?.colors?.primary||"black"};
190
+ --primary-foreground: ${n?.colors?.primaryForeground||"white"};
191
+ --background: ${n?.colors?.background||"white"};
192
+ --foreground: ${n?.colors?.foreground||"oklch(0.271 0 0)"};
193
+ --border: ${n?.colors?.border||"oklch(0.89 0 0)"};
194
+ --destructive: ${n?.colors?.destructive||"oklch(0.55 0.15 25.723)"};
195
+ --muted-foreground: ${n?.colors?.mutedForeground||"oklch(0.545 0 0)"};
196
+ --corner-border: ${n?.colors?.cornerBorder||"#404040"};
197
+ }
198
+
199
+ button, .btn {
200
+ cursor: pointer;
201
+ background: none;
202
+ border: none;
203
+ color: inherit;
204
+ font: inherit;
205
+ transition: all var(--default-transition-duration)
206
+ var(--default-transition-timing-function);
207
+ }
208
+ button:hover, .btn:hover {
209
+ opacity: 0.8;
210
+ }
211
+
212
+ @media (prefers-color-scheme: dark) {
213
+ :root,
214
+ :host {
215
+ --primary: ${n?.colors?.primary||"white"};
216
+ --primary-foreground: ${n?.colors?.primaryForeground||"black"};
217
+ --background: ${n?.colors?.background||"oklch(0.15 0 0)"};
218
+ --foreground: ${n?.colors?.foreground||"oklch(0.98 0 0)"};
219
+ --border: ${n?.colors?.border||"oklch(0.27 0 0)"};
220
+ --destructive: ${n?.colors?.destructive||"oklch(0.65 0.15 25.723)"};
221
+ --muted-foreground: ${n?.colors?.mutedForeground||"oklch(0.65 0 0)"};
222
+ --corner-border: ${n?.colors?.cornerBorder||"#a0a0a0"};
223
+ }
224
+ }
225
+ @media (max-width: 640px) {
226
+ :root, :host {
227
+ --text-6xl: 2.5rem;
228
+ --text-2xl: 1.25rem;
229
+ --text-sm: 0.8125rem;
230
+ }
231
+ }
232
+ @media (max-width: 480px) {
233
+ :root, :host {
234
+ --text-6xl: 2rem;
235
+ --text-2xl: 1.125rem;
236
+ }
237
+ }
238
+ </style>
239
+ </head>
240
+ <body style="width: 100vw; min-height: 100vh; overflow-x: hidden; overflow-y: auto;">
241
+ <div
242
+ style="
243
+ display: flex;
244
+ flex-direction: column;
245
+ align-items: center;
246
+ justify-content: center;
247
+ gap: 1.5rem;
248
+ position: relative;
249
+ width: 100%;
250
+ min-height: 100vh;
251
+ padding: 1rem;
252
+ "
253
+ >
254
+ ${n?.disableBackgroundGrid?"":`
255
+ <div
256
+ style="
257
+ position: absolute;
258
+ inset: 0;
259
+ background-image: linear-gradient(to right, ${n?.colors?.gridColor||"var(--border)"} 1px, transparent 1px),
260
+ linear-gradient(to bottom, ${n?.colors?.gridColor||"var(--border)"} 1px, transparent 1px);
261
+ background-size: 40px 40px;
262
+ opacity: 0.6;
263
+ pointer-events: none;
264
+ width: 100vw;
265
+ height: 100vh;
266
+ "
267
+ ></div>
268
+ <div
269
+ style="
270
+ position: absolute;
271
+ inset: 0;
272
+ display: flex;
273
+ align-items: center;
274
+ justify-content: center;
275
+ background: ${n?.colors?.background||"var(--background)"};
276
+ mask-image: radial-gradient(ellipse at center, transparent 20%, black);
277
+ -webkit-mask-image: radial-gradient(ellipse at center, transparent 20%, black);
278
+ pointer-events: none;
279
+ "
280
+ ></div>
281
+ `}
282
+
283
+ <div
284
+ style="
285
+ position: relative;
286
+ z-index: 10;
287
+ border: 2px solid var(--border);
288
+ background: ${n?.colors?.cardBackground||"var(--background)"};
289
+ padding: 1.5rem;
290
+ max-width: 42rem;
291
+ width: 100%;
292
+ "
293
+ >
294
+ ${n?.disableCornerDecorations?"":`
295
+ <!-- Corner decorations -->
296
+ <div
297
+ style="
298
+ position: absolute;
299
+ top: -2px;
300
+ left: -2px;
301
+ width: 2rem;
302
+ height: 2rem;
303
+ border-top: 4px solid var(--corner-border);
304
+ border-left: 4px solid var(--corner-border);
305
+ "
306
+ ></div>
307
+ <div
308
+ style="
309
+ position: absolute;
310
+ top: -2px;
311
+ right: -2px;
312
+ width: 2rem;
313
+ height: 2rem;
314
+ border-top: 4px solid var(--corner-border);
315
+ border-right: 4px solid var(--corner-border);
316
+ "
317
+ ></div>
318
+
319
+ <div
320
+ style="
321
+ position: absolute;
322
+ bottom: -2px;
323
+ left: -2px;
324
+ width: 2rem;
325
+ height: 2rem;
326
+ border-bottom: 4px solid var(--corner-border);
327
+ border-left: 4px solid var(--corner-border);
328
+ "
329
+ ></div>
330
+ <div
331
+ style="
332
+ position: absolute;
333
+ bottom: -2px;
334
+ right: -2px;
335
+ width: 2rem;
336
+ height: 2rem;
337
+ border-bottom: 4px solid var(--corner-border);
338
+ border-right: 4px solid var(--corner-border);
339
+ "
340
+ ></div>`}
341
+
342
+ <div style="text-align: center; margin-bottom: 1.5rem;">
343
+ <div style="margin-bottom: 1.5rem;">
344
+ <div
345
+ style="
346
+ display: inline-block;
347
+ border: 2px solid ${n?.disableTitleBorder?"transparent":n?.colors?.titleBorder||"var(--destructive)"};
348
+ padding: 0.375rem 1rem;
349
+ "
350
+ >
351
+ <h1
352
+ style="
353
+ font-size: var(--text-6xl);
354
+ font-weight: var(--font-weight-semibold);
355
+ color: ${n?.colors?.titleColor||"var(--foreground)"};
356
+ letter-spacing: -0.02em;
357
+ margin: 0;
358
+ "
359
+ >
360
+ ERROR
361
+ </h1>
362
+ </div>
363
+ <div
364
+ style="
365
+ height: 2px;
366
+ background-color: var(--border);
367
+ width: calc(100% + 3rem);
368
+ margin-left: -1.5rem;
369
+ margin-top: 1.5rem;
370
+ "
371
+ ></div>
372
+ </div>
373
+
374
+ <h2
375
+ style="
376
+ font-size: var(--text-2xl);
377
+ font-weight: var(--font-weight-semibold);
378
+ color: var(--foreground);
379
+ margin: 0 0 1rem;
380
+ "
381
+ >
382
+ Something went wrong
383
+ </h2>
384
+
385
+ <div
386
+ style="
387
+ display: inline-flex;
388
+ align-items: center;
389
+ gap: 0.5rem;
390
+ border: 2px solid var(--border);
391
+ background-color: var(--muted);
392
+ padding: 0.375rem 0.75rem;
393
+ margin: 0 0 1rem;
394
+ flex-wrap: wrap;
395
+ justify-content: center;
396
+ "
397
+ >
398
+ <span
399
+ style="
400
+ font-size: 0.75rem;
401
+ color: var(--muted-foreground);
402
+ font-weight: var(--font-weight-semibold);
403
+ "
404
+ >
405
+ CODE:
406
+ </span>
407
+ <span
408
+ style="
409
+ font-size: var(--text-sm);
410
+ font-family: var(--default-mono-font-family, monospace);
411
+ color: var(--foreground);
412
+ word-break: break-all;
413
+ "
414
+ >
415
+ ${IM(t)}
416
+ </span>
417
+ </div>
418
+
419
+ <p
420
+ style="
421
+ color: var(--muted-foreground);
422
+ max-width: 28rem;
423
+ margin: 0 auto;
424
+ font-size: var(--text-sm);
425
+ line-height: 1.5;
426
+ text-wrap: pretty;
427
+ "
428
+ >
429
+ ${!r?`We encountered an unexpected error. Please try again or return to the home page. If you're a developer, you can find <a href='https://better-auth.com/docs/reference/errors/${encodeURIComponent(t)}' target='_blank' rel="noopener noreferrer" style='color: var(--foreground); text-decoration: underline;'>more information about the error</a>.`:r}
430
+ </p>
431
+ </div>
432
+
433
+ <div
434
+ style="
435
+ display: flex;
436
+ gap: 0.75rem;
437
+ margin-top: 1.5rem;
438
+ justify-content: center;
439
+ flex-wrap: wrap;
440
+ "
441
+ >
442
+ <a
443
+ href="/"
444
+ style="
445
+ text-decoration: none;
446
+ "
447
+ >
448
+ <div
449
+ style="
450
+ border: 2px solid var(--border);
451
+ background: var(--primary);
452
+ color: var(--primary-foreground);
453
+ padding: 0.5rem 1rem;
454
+ border-radius: 0;
455
+ white-space: nowrap;
456
+ "
457
+ class="btn"
458
+ >
459
+ Go Home
460
+ </div>
461
+ </a>
462
+ <a
463
+ href="https://better-auth.com/docs/reference/errors/${encodeURIComponent(t)}?askai=${encodeURIComponent(`What does the error code ${t} mean?`)}"
464
+ target="_blank"
465
+ rel="noopener noreferrer"
466
+ style="
467
+ text-decoration: none;
468
+ "
469
+ >
470
+ <div
471
+ style="
472
+ border: 2px solid var(--border);
473
+ background: transparent;
474
+ color: var(--foreground);
475
+ padding: 0.5rem 1rem;
476
+ border-radius: 0;
477
+ white-space: nowrap;
478
+ "
479
+ class="btn"
480
+ >
481
+ Ask AI
482
+ </div>
483
+ </a>
484
+ </div>
485
+ </div>
486
+ </div>
487
+ </body>
488
+ </html>`},DM=v("/error",{method:"GET",metadata:{...zl,openapi:{description:"Displays an error page",responses:{"200":{description:"Success",content:{"text/html":{schema:{type:"string",description:"The HTML content of the error page"}}}}}}}},async(e)=>{let t=new URL(e.request?.url||""),r=t.searchParams.get("error")||"UNKNOWN",n=t.searchParams.get("error_description")||null,i=/^[\'A-Za-z0-9_-]+$/.test(r||"")?r:"UNKNOWN",o=n?IM(n):null,s=new URLSearchParams;if(s.set("error",i),n)s.set("error_description",n);let a=e.context.options,c=a.onAPIError?.errorURL;if(c){let u=us(c,s);return new Response(null,{status:302,headers:{Location:u}})}if(ut&&!a.onAPIError?.customizeDefaultErrorPage)return new Response(null,{status:302,headers:{Location:`/?${s.toString()}`}});return new Response(Lce(e.context.options,i,o),{headers:{"Content-Type":"text/html"}})});var UM=v("/ok",{method:"GET",metadata:{...zl,openapi:{description:"Check if the API is working",responses:{"200":{description:"API is working",content:{"application/json":{schema:{type:"object",properties:{ok:{type:"boolean",description:"Indicates if the API is working"}},required:["ok"]}}}}}}}},async(e)=>e.json({ok:!0}));import*as Eo from"zod";function PM(e,t,r){let n=t?new URL(t,e.baseURL):new URL(`${e.baseURL}/error`);if(r)Object.entries(r).forEach(([i,o])=>n.searchParams.set(i,o));return n.href}function Mce(e,t,r){let n=new URL(t,e.baseURL);if(r)Object.entries(r).forEach(([i,o])=>n.searchParams.set(i,o));return n.href}var LM=v("/request-password-reset",{method:"POST",body:Eo.object({email:Eo.email().meta({description:"The email address of the user to send a password reset email to"}),redirectTo:Eo.string().meta({description:"The URL to redirect the user to reset their password. If the token isn't valid or expired, it'll be redirected with a query parameter `?error=INVALID_TOKEN`. If the token is valid, it'll be redirected with a query parameter `?token=VALID_TOKEN"}).optional()}),metadata:{openapi:{operationId:"requestPasswordReset",description:"Send a password reset email to the user",responses:{"200":{description:"Success",content:{"application/json":{schema:{type:"object",properties:{status:{type:"boolean"},message:{type:"string"}}}}}}}}},use:[eu((e)=>e.body.redirectTo)]},async(e)=>{if(!e.context.options.emailAndPassword?.sendResetPassword)throw e.context.logger.error("Reset password isn't enabled.Please pass an emailAndPassword.sendResetPassword function in your auth config!"),l.from("BAD_REQUEST",{message:"Reset password isn't enabled",code:"RESET_PASSWORD_DISABLED"});let{email:t,redirectTo:r}=e.body,n=await e.context.internalAdapter.findUserByEmail(t,{includeAccounts:!0});if(!n)return xe(24),await e.context.internalAdapter.findVerificationValue("dummy-verification-token"),e.context.logger.warn("Reset Password: User not found"),e.json({status:!0,message:"If this email exists in our system, check your email for the reset link"});let i=ac(e.context.options.emailAndPassword.resetPasswordTokenExpiresIn||3600,"sec"),o=xe(24);await e.context.internalAdapter.createVerificationValue({value:n.user.id,identifier:`reset-password:${o}`,expiresAt:i});let s=r?encodeURIComponent(r):"",a=`${e.context.baseURL}/reset-password/${o}?callbackURL=${s}`;return await e.context.runInBackgroundOrAwait(e.context.options.emailAndPassword.sendResetPassword({user:n.user,url:a,token:o},e.request)),e.json({status:!0,message:"If this email exists in our system, check your email for the reset link"})}),MM=v("/reset-password/:token",{method:"GET",operationId:"resetPasswordCallback",query:Eo.object({callbackURL:Eo.string().meta({description:"The URL to redirect the user to reset their password"})}),use:[eu((e)=>e.query.callbackURL)],metadata:{openapi:{operationId:"resetPasswordCallback",description:"Redirects the user to the callback URL with the token",parameters:[{name:"token",in:"path",required:!0,description:"The token to reset the password",schema:{type:"string"}},{name:"callbackURL",in:"query",required:!0,description:"The URL to redirect the user to reset their password",schema:{type:"string"}}],responses:{"200":{description:"Success",content:{"application/json":{schema:{type:"object",properties:{token:{type:"string"}}}}}}}}}},async(e)=>{let{token:t}=e.params,{callbackURL:r}=e.query;if(!t||!r)throw e.redirect(PM(e.context,r,{error:"INVALID_TOKEN"}));let n=await e.context.internalAdapter.findVerificationValue(`reset-password:${t}`);if(!n||n.expiresAt<new Date)throw e.redirect(PM(e.context,r,{error:"INVALID_TOKEN"}));throw e.redirect(Mce(e.context,r,{token:t}))}),qM=v("/reset-password",{method:"POST",operationId:"resetPassword",query:Eo.object({token:Eo.string().optional()}).optional(),body:Eo.object({newPassword:Eo.string().meta({description:"The new password to set"}),token:Eo.string().meta({description:"The token to reset the password"}).optional()}),metadata:{openapi:{operationId:"resetPassword",description:"Reset the password for a user",responses:{"200":{description:"Success",content:{"application/json":{schema:{type:"object",properties:{status:{type:"boolean"}}}}}}}}}},async(e)=>{let t=e.body.token||e.query?.token;if(!t)throw l.from("BAD_REQUEST",S.INVALID_TOKEN);let{newPassword:r}=e.body;rd(e,r),Go(e,r);let n=`reset-password:${t}`,i=await e.context.internalAdapter.findVerificationValue(n);if(!i||i.expiresAt<new Date)throw l.from("BAD_REQUEST",S.INVALID_TOKEN);let o=i.value,s=await e.context.internalAdapter.findUserById(o);if(!s)throw l.from("BAD_REQUEST",S.USER_NOT_FOUND);if(await f1(e,o,await e.context.password.hash(r),async()=>{if(!await e.context.internalAdapter.consumeVerificationValue(n))throw l.from("BAD_REQUEST",S.INVALID_TOKEN)}),e.context.options.emailAndPassword?.onPasswordReset)await e.context.options.emailAndPassword.onPasswordReset({user:s},e.request);return e.json({status:!0})}),BM=v("/verify-password",{method:"POST",body:Eo.object({password:Eo.string().meta({description:"The password to verify"})}),metadata:{scope:"server",openapi:{operationId:"verifyPassword",description:"Verify the current user's password",responses:{"200":{description:"Success",content:{"application/json":{schema:{type:"object",properties:{status:{type:"boolean"}}}}}}}}},use:[Gs]},async(e)=>{let{password:t}=e.body,r=e.context.session;if(!await h1(e,{password:t,userId:r.user.id}))throw l.from("BAD_REQUEST",S.INVALID_PASSWORD);return e.json({status:!0})});import*as Ir from"zod";var qce=Ir.object({callbackURL:Ir.string().meta({description:"Callback URL to redirect to after the user has signed in"}).optional(),newUserCallbackURL:Ir.string().optional(),errorCallbackURL:Ir.string().meta({description:"Callback URL to redirect to if an error happens"}).optional(),provider:fw,disableRedirect:Ir.boolean().meta({description:"Disable automatic redirection to the provider. Useful for handling the redirection yourself"}).optional(),idToken:Ir.optional(Ir.object({token:Ir.string().meta({description:"ID token from the provider"}),nonce:Ir.string().meta({description:"Nonce used to generate the token"}).optional(),accessToken:Ir.string().meta({description:"Access token from the provider"}).optional(),refreshToken:Ir.string().meta({description:"Refresh token from the provider"}).optional(),expiresAt:Ir.number().meta({description:"Expiry date of the token"}).optional(),user:Ir.object({name:Ir.object({firstName:Ir.string().optional(),lastName:Ir.string().optional()}).optional(),email:Ir.string().optional()}).meta({description:"The user object from the provider. Only available for some providers like Apple."}).optional()})),scopes:Ir.array(Ir.string()).meta({description:"Array of scopes to request from the provider. This will override the default scopes passed."}).optional(),requestSignUp:Ir.boolean().meta({description:"Explicitly request sign-up. Useful when disableImplicitSignUp is true for this provider"}).optional(),loginHint:Ir.string().meta({description:"The login hint to use for the authorization code request"}).optional(),additionalParams:gp,additionalData:Ir.record(Ir.string(),Ir.any()).optional().meta({description:"Additional data to be passed through the OAuth flow"})}),jM=()=>v("/sign-in/social",{method:"POST",operationId:"socialSignIn",body:qce,metadata:{$Infer:{body:{},returned:{}},openapi:{description:"Sign in with a social provider",operationId:"socialSignIn",responses:{"200":{description:"Success - Returns session details (idToken branch) or an authorize URL (redirect branch)",content:{"application/json":{schema:{type:"object",description:"Returns session details when idToken is provided, or an authorize URL otherwise",properties:{token:{type:"string"},user:{type:"object",$ref:"#/components/schemas/User"},url:{type:"string"},redirect:{type:"boolean"}},required:["redirect"]}}}}}}}},async(e)=>{let t=await Ta(e.context.socialProviders,{value:e.body.provider});if(!t)throw e.context.logger.error("Provider not found. Make sure to add the provider in your auth config",{provider:e.body.provider}),l.from("NOT_FOUND",S.PROVIDER_NOT_FOUND);if(e.body.idToken){if(!Ap(t))throw e.context.logger.error("Provider does not support id token verification",{provider:e.body.provider}),l.from("NOT_FOUND",S.ID_TOKEN_NOT_SUPPORTED);let{token:s,nonce:a}=e.body.idToken;if(!await Tp(t,s,a,e))throw e.context.logger.warn("Invalid id token",{provider:e.body.provider}),l.from("UNAUTHORIZED",S.INVALID_TOKEN);let c={idToken:s,accessToken:e.body.idToken.accessToken,refreshToken:e.body.idToken.refreshToken,user:e.body.idToken.user},u=await t.getUserInfo(c);if(!u||!u?.user)throw e.context.logger.error("Failed to get user info",{provider:e.body.provider}),l.from("UNAUTHORIZED",S.FAILED_TO_GET_USER_INFO);if(!u.user.email)throw e.context.logger.error(Ml(e.body.provider,{source:"id_token"}),{provider:e.body.provider}),l.from("UNAUTHORIZED",S.USER_EMAIL_NOT_FOUND);let d=await Yy(t,c,u.data),f=Qy(u.data),h=await dw(e,{userInfo:{...u.user,email:u.user.email,id:d.accountId,name:u.user.name||"",image:u.user.image,emailVerified:u.user.emailVerified||!1},account:{...d,accessToken:e.body.idToken.accessToken,idToken:s},callbackURL:e.body.callbackURL,disableSignUp:t.disableImplicitSignUp&&!e.body.requestSignUp||t.options?.disableSignUp||t.disableSignUp,source:{method:"oauth",oauth:{providerId:t.id,profile:f}}});if(h.error){if(h.error===Ri.EMAIL_NOT_VERIFIED)throw l.from("FORBIDDEN",S.EMAIL_NOT_VERIFIED);throw l.from("UNAUTHORIZED",{message:h.error,code:"OAUTH_LINK_ERROR"})}return await ki(e,h.data),e.json({redirect:!1,token:h.data.session.token,url:void 0,user:Xn(e.context.options,h.data.user)})}let r=$l(t),{codeVerifier:n,state:i}=await Fl(e,{additionalData:e.body.additionalData,idTokenNonce:r}),o=await t.createAuthorizationURL({state:i,codeVerifier:n,idTokenNonce:r,redirectURI:`${e.context.baseURL}${nu(t)}`,scopes:e.body.scopes,loginHint:e.body.loginHint,additionalParams:e.body.additionalParams});if(!e.body.disableRedirect)e.setHeader("Location",o.toString());return e.json({url:o.toString(),redirect:!e.body.disableRedirect})}),$M=()=>v("/sign-in/email",{method:"POST",operationId:"signInEmail",use:[ap],cloneRequest:!0,body:Ir.object({email:Ir.string().meta({description:"Email of the user"}),password:Ir.string().meta({description:"Password of the user"}),callbackURL:Ir.string().meta({description:"Callback URL to use as a redirect for email verification"}).optional(),rememberMe:Ir.boolean().meta({description:"If this is false, the session will not be remembered. Default is `true`."}).default(!0).optional()}),metadata:{allowedMediaTypes:["application/x-www-form-urlencoded","application/json"],$Infer:{body:{},returned:{}},openapi:{operationId:"signInEmail",description:"Sign in with email and password",responses:{"200":{description:"Success - Returns either session details or redirect URL",content:{"application/json":{schema:{type:"object",description:"Session response when idToken is provided",properties:{redirect:{type:"boolean",enum:[!1]},token:{type:"string",description:"Session token"},url:{type:"string",nullable:!0},user:{type:"object",$ref:"#/components/schemas/User"}},required:["redirect","token","user"]}}}}}}}},async(e)=>{if(!e.context.options?.emailAndPassword?.enabled)throw e.context.logger.error("Email and password is not enabled. Make sure to enable it in the options on you `auth.ts` file. Check `https://better-auth.com/docs/authentication/email-password` for more!"),l.from("BAD_REQUEST",{code:"EMAIL_PASSWORD_DISABLED",message:"Email and password is not enabled"});let{email:t,password:r}=e.body;if(!Ir.email().safeParse(t).success)throw l.from("BAD_REQUEST",S.INVALID_EMAIL);Go(e,r);let n=await e.context.internalAdapter.findUserByEmail(t.toLowerCase(),{includeAccounts:!0}),i=n?.accounts.find((c)=>c.providerId==="credential"&&c.accountId===n.user.id);if(!n||!i)throw await e.context.password.hash(r),e.context.logger.warn("User not found"),l.from("UNAUTHORIZED",S.INVALID_EMAIL_OR_PASSWORD);let o=n.user,s=i.password;if(!s)throw await e.context.password.hash(r),e.context.logger.warn("Password not found"),l.from("UNAUTHORIZED",S.INVALID_EMAIL_OR_PASSWORD);if(!await e.context.password.verify({hash:s,password:r}))throw e.context.logger.warn("Invalid password"),l.from("UNAUTHORIZED",S.INVALID_EMAIL_OR_PASSWORD);if(e.context.options?.emailAndPassword?.requireEmailVerification&&!o.emailVerified){if(!e.context.options?.emailVerification?.sendVerificationEmail)throw l.from("FORBIDDEN",S.EMAIL_NOT_VERIFIED);if(e.context.options?.emailVerification?.sendOnSignIn){let c=await lo(e.context.secret,o.email,void 0,e.context.options.emailVerification?.expiresIn),u=e.body.callbackURL?encodeURIComponent(e.body.callbackURL):encodeURIComponent("/"),d=`${e.context.baseURL}/verify-email?token=${c}&callbackURL=${u}`;await e.context.runInBackgroundOrAwait(e.context.options.emailVerification.sendVerificationEmail({user:o,url:d,token:c},iu(e.request)))}throw l.from("FORBIDDEN",S.EMAIL_NOT_VERIFIED)}let a=await e.context.internalAdapter.createSession(o.id,e.body.rememberMe===!1);if(!a)throw e.context.logger.error("Failed to create session"),l.from("UNAUTHORIZED",S.FAILED_TO_CREATE_SESSION);if(await ki(e,{session:a,user:o},e.body.rememberMe===!1),e.body.callbackURL)e.setHeader("Location",e.body.callbackURL);return e.json({redirect:!!e.body.callbackURL,token:a.token,url:e.body.callbackURL,user:Xn(e.context.options,o)})});import*as cd from"zod";var Bce=cd.object({callbackURL:cd.string().meta({description:"The URL to redirect to after provider logout"}).optional(),disableRedirect:cd.boolean().meta({description:"Return the provider logout URL without redirecting"}).optional(),state:cd.string().meta({description:"State to pass to the provider logout endpoint"}).optional()}).optional(),FM=(e)=>({success:!0,url:e?.url,redirect:e?.redirect}),zM=v("/sign-out",{method:"POST",body:Bce,operationId:"signOut",requireHeaders:!0,metadata:{openapi:{operationId:"signOut",description:"Sign out the current user",responses:{"200":{description:"Success",content:{"application/json":{schema:{type:"object",properties:{success:{type:"boolean"},url:{type:"string",description:"Provider logout URL when RP-initiated logout is available"},redirect:{type:"boolean",description:"Whether the client should redirect to the provider logout URL"}}}}}}}}}},async(e)=>{let t=await e.getSignedCookie(e.context.authCookies.sessionToken.name,e.context.secret),r=null;if(t)try{r=await e.context.internalAdapter.findSession(t)}catch(i){e.context.logger.error("Failed to read session from database",i)}if(t)try{await e.context.internalAdapter.deleteSession(t)}catch(i){e.context.logger.error("Failed to delete session from database",i)}Vo(e);let n=await(async()=>{try{if(!r)return null;let i=await e.context.internalAdapter.findAccounts(r.user.id),o=new Map(e.context.socialProviders.map((u)=>[u.id,u])),s=i.filter((u)=>Boolean(o.get(u.providerId)?.createEndSessionURL)).sort((u,d)=>d.updatedAt.getTime()-u.updatedAt.getTime());if(s.length===0)return null;let a=new Set,c=e.body?.callbackURL?new URL(e.body.callbackURL,e.context.baseURL).toString():void 0;for(let u of s){if(a.has(u.providerId))continue;a.add(u.providerId);let d=o.get(u.providerId);try{let f=await d?.createEndSessionURL?.({idToken:u.idToken,postLogoutRedirectURI:c,state:e.body?.state});if(f)return f.toString()}catch(f){e.context.logger.error(`Failed to create logout URL for provider "${u.providerId}"`,f)}}return null}catch(i){return e.context.logger.error("Failed to create provider logout URL",i),null}})();if(n){let i=!e.body?.disableRedirect;if(i)e.setHeader("Location",n);return e.json(FM({url:n,redirect:i}))}return e.json(FM())});import*as eo from"zod";var jce=eo.object({name:eo.string(),email:eo.email(),password:eo.string().nonempty(),image:eo.string().optional(),callbackURL:eo.string().optional(),rememberMe:eo.boolean().optional()}).and(eo.record(eo.string(),eo.any())),WM=()=>v("/sign-up/email",{method:"POST",operationId:"signUpWithEmailAndPassword",use:[ap],body:jce,cloneRequest:!0,metadata:{allowedMediaTypes:["application/x-www-form-urlencoded","application/json"],$Infer:{body:{},returned:{}},openapi:{operationId:"signUpWithEmailAndPassword",description:"Sign up a user using email and password",requestBody:{content:{"application/json":{schema:{type:"object",properties:{name:{type:"string",description:"The name of the user"},email:{type:"string",description:"The email of the user"},password:{type:"string",description:"The password of the user"},image:{type:"string",description:"The profile image URL of the user"},callbackURL:{type:"string",description:"The URL to use for email verification callback"},rememberMe:{type:"boolean",description:"If this is false, the session will not be remembered. Default is `true`."}},required:["name","email","password"]}}}},responses:{"200":{description:"Successfully created user",content:{"application/json":{schema:{type:"object",properties:{token:{type:"string",nullable:!0,description:"Authentication token for the session"},user:{type:"object",properties:{id:{type:"string",description:"The unique identifier of the user"},email:{type:"string",format:"email",description:"The email address of the user"},name:{type:"string",description:"The name of the user"},image:{type:"string",format:"uri",nullable:!0,description:"The profile image URL of the user"},emailVerified:{type:"boolean",description:"Whether the email has been verified"},createdAt:{type:"string",format:"date-time",description:"When the user was created"},updatedAt:{type:"string",format:"date-time",description:"When the user was last updated"}},required:["id","email","name","emailVerified","createdAt","updatedAt"]}},required:["user"]}}}},"422":{description:"Unprocessable Entity. User already exists or failed to create user.",content:{"application/json":{schema:{type:"object",properties:{message:{type:"string"}}}}}}}}}},async(e)=>Co(e.context.adapter,async()=>{if(!e.context.options.emailAndPassword?.enabled||e.context.options.emailAndPassword?.disableSignUp)throw l.from("BAD_REQUEST",{message:"Email and password sign up is not enabled",code:"EMAIL_PASSWORD_SIGN_UP_DISABLED"});let t=e.body,{name:r,email:n,password:i,image:o,callbackURL:s,rememberMe:a,...c}=t;if(!eo.email().safeParse(n).success)throw l.from("BAD_REQUEST",S.INVALID_EMAIL);if(!i||typeof i!=="string")throw l.from("BAD_REQUEST",S.INVALID_PASSWORD);rd(e,i),Go(e,i);let u=e.context.options.emailAndPassword.requireEmailVerification||e.context.options.emailAndPassword.autoSignIn===!1,d=e.context.options.emailAndPassword.autoSignIn===!1||u,f=Cl(e.context.options,c,"create"),h=n.toLowerCase(),p=()=>{let I=new Date,Ne=e.context.generateId({model:"user"})||xe(),k={name:r,email:h,emailVerified:!1,image:o??null,createdAt:I,updatedAt:I},j=e.context.options.emailAndPassword?.customSyntheticUser,re;if(j){let Oe=Object.keys(e.context.options.user?.additionalFields??{}),ne={};for(let F of Oe)if(F in f)ne[F]=f[F];let M=j({coreFields:k,additionalFields:ne,id:Ne});re=Qh(e.context.options,M)}else re=Qh(e.context.options,{...k,...f,id:Ne});return e.json({token:null,user:Xn(e.context.options,re)})},g=await e.context.internalAdapter.findUserByEmail(h);if(g?.user){if(e.context.logger.info(`Sign-up attempt for existing email: ${n}`),u){if(await e.context.password.hash(i),e.context.options.emailAndPassword?.onExistingUserSignUp)await e.context.runInBackgroundOrAwait(e.context.options.emailAndPassword.onExistingUserSignUp({user:g.user},iu(e.request)));return p()}throw l.from("UNPROCESSABLE_ENTITY",S.USER_ALREADY_EXISTS_USE_ANOTHER_EMAIL)}let _=await e.context.password.hash(i),R;try{if(R=await e.context.internalAdapter.createUser({email:h,name:r,image:o,...f,emailVerified:!1},{method:"email-password"}),!R)throw l.from("BAD_REQUEST",S.FAILED_TO_CREATE_USER)}catch(I){if(hi(I)){if(I.statusCode===403&&u)return p();throw I}if($u())e.context.logger.error("Failed to create user",I);throw e.context.logger?.error("Failed to create user",I),l.from("UNPROCESSABLE_ENTITY",S.FAILED_TO_CREATE_USER)}if(!R)throw l.from("UNPROCESSABLE_ENTITY",S.FAILED_TO_CREATE_USER);if(await e.context.internalAdapter.linkAccount({userId:R.id,providerId:"credential",accountId:R.id,password:_}),e.context.options.emailVerification?.sendOnSignUp??e.context.options.emailAndPassword.requireEmailVerification){let I=await lo(e.context.secret,R.email,void 0,e.context.options.emailVerification?.expiresIn),Ne=t.callbackURL?encodeURIComponent(t.callbackURL):encodeURIComponent("/"),k=`${e.context.baseURL}/verify-email?token=${I}&callbackURL=${Ne}`;if(e.context.options.emailVerification?.sendVerificationEmail)await e.context.runInBackgroundOrAwait(e.context.options.emailVerification.sendVerificationEmail({user:R,url:k,token:I},iu(e.request)))}if(d)return e.json({token:null,user:Xn(e.context.options,R)});let O=await e.context.internalAdapter.createSession(R.id,a===!1,void 0,void 0,{deferSecondaryStorageWrites:!0});if(!O)throw l.from("BAD_REQUEST",S.FAILED_TO_CREATE_SESSION);return await ki(e,{session:O,user:R},a===!1),e.json({token:O.token,user:Xn(e.context.options,R)})}));import*as Wl from"zod";var $ce=Wl.record(Wl.string().meta({description:"Field name must be a string"}),Wl.any()),HM=()=>v("/update-session",{method:"POST",operationId:"updateSession",body:$ce,use:[K],metadata:{$Infer:{body:{}},openapi:{operationId:"updateSession",description:"Update the current session",responses:{"200":{description:"Success",content:{"application/json":{schema:{type:"object",properties:{session:{type:"object",$ref:"#/components/schemas/Session"}}}}}}}}}},async(e)=>{let t=e.body;if(typeof t!=="object"||Array.isArray(t))throw l.from("BAD_REQUEST",S.BODY_MUST_BE_AN_OBJECT);let r=e.context.session,n=Ny(e.context.options,t,"update");if(Object.keys(n).length===0)throw l.fromStatus("BAD_REQUEST",{message:"No fields to update"});let i=await e.context.internalAdapter.updateSession(r.session.token,{...n,updatedAt:new Date});if(!i&&ru(e))throw Vo(e),l.from("UNAUTHORIZED",S.FAILED_TO_GET_SESSION);let o=i??{...r.session,...n,updatedAt:new Date};return await ki(e,{session:o,user:r.user}),e.json({session:Di(e.context.options,o)})});import*as ci from"zod";var Fce=ci.record(ci.string().meta({description:"Field name must be a string"}),ci.any()),VM=()=>v("/update-user",{method:"POST",operationId:"updateUser",body:Fce,use:[K],metadata:{$Infer:{body:{}},openapi:{operationId:"updateUser",description:"Update the current user",requestBody:{content:{"application/json":{schema:{type:"object",properties:{name:{type:"string",description:"The name of the user"},image:{type:"string",description:"The image of the user",nullable:!0}}}}}},responses:{"200":{description:"Success",content:{"application/json":{schema:{type:"object",properties:{user:{type:"object",$ref:"#/components/schemas/User"}}}}}}}}}},async(e)=>{let t=e.body;if(typeof t!=="object"||Array.isArray(t))throw l.from("BAD_REQUEST",S.BODY_MUST_BE_AN_OBJECT);if(t.email)throw l.from("BAD_REQUEST",S.EMAIL_CAN_NOT_BE_UPDATED);let{name:r,image:n,...i}=t,o=e.context.session,s=Cl(e.context.options,i,"update");if(n===void 0&&r===void 0&&Object.keys(s).length===0)throw l.fromStatus("BAD_REQUEST",{message:"No fields to update"});let a=await e.context.internalAdapter.updateUser(o.user.id,{name:r,image:n,...s})??{...o.user,...r!==void 0&&{name:r},...n!==void 0&&{image:n},...s};return await ki(e,{session:o.session,user:a}),e.json({status:!0})}),GM=v("/change-password",{method:"POST",operationId:"changePassword",body:ci.object({newPassword:ci.string().meta({description:"The new password to set"}),currentPassword:ci.string().meta({description:"The current password is required"}),revokeOtherSessions:ci.boolean().meta({description:"Must be a boolean value"}).optional()}),use:[Gs],metadata:{openapi:{operationId:"changePassword",description:"Change the password of the user",responses:{"200":{description:"Password successfully changed",content:{"application/json":{schema:{type:"object",properties:{token:{type:"string",nullable:!0,description:"New session token if other sessions were revoked"},user:{type:"object",properties:{id:{type:"string",description:"The unique identifier of the user"},email:{type:"string",format:"email",description:"The email address of the user"},name:{type:"string",description:"The name of the user"},image:{type:"string",format:"uri",nullable:!0,description:"The profile image URL of the user"},emailVerified:{type:"boolean",description:"Whether the email has been verified"},createdAt:{type:"string",format:"date-time",description:"When the user was created"},updatedAt:{type:"string",format:"date-time",description:"When the user was last updated"}},required:["id","email","name","emailVerified","createdAt","updatedAt"]}},required:["user"]}}}}}}}},async(e)=>{let{newPassword:t,currentPassword:r,revokeOtherSessions:n}=e.body,i=e.context.session;rd(e,t),Go(e,t),Go(e,r);let o=await e.context.internalAdapter.findCredentialAccount(i.user.id);if(!o||!o.password)throw l.from("BAD_REQUEST",S.CREDENTIAL_ACCOUNT_NOT_FOUND);let s=await e.context.password.hash(t);if(!await e.context.password.verify({hash:o.password,password:r}))throw l.from("BAD_REQUEST",S.INVALID_PASSWORD);let a=await Co(e.context.adapter,async()=>{if(n)await e.context.internalAdapter.deleteUserSessions(i.user.id);if(await e.context.internalAdapter.updateAccount(o.id,{password:s}),!n)return null;let u=await e.context.internalAdapter.createSession(i.user.id,void 0,void 0,void 0,{deferSecondaryStorageWrites:!0});if(!u)throw l.from("INTERNAL_SERVER_ERROR",S.FAILED_TO_GET_SESSION);return u}),c=null;if(a)await ki(e,{session:a,user:i.user}),c=a.token;return e.json({token:c,user:Xn(e.context.options,i.user)})}),KM=v.serverOnly({method:"POST",body:ci.object({newPassword:ci.string().meta({description:"The new password to set is required"})}),use:[Gs]},async(e)=>{let{newPassword:t}=e.body,r=e.context.session;rd(e,t),Go(e,t);let n=await e.context.internalAdapter.findCredentialAccount(r.user.id),i=await e.context.password.hash(t);if(!n)return await e.context.internalAdapter.linkAccount({userId:r.user.id,providerId:"credential",accountId:r.user.id,password:i}),e.json({status:!0});if(!n.password)return await e.context.internalAdapter.updateAccount(n.id,{password:i}),e.json({status:!0});throw l.from("BAD_REQUEST",S.PASSWORD_ALREADY_SET)}),JM=v("/delete-user",{method:"POST",use:[Gs],body:ci.object({callbackURL:ci.string().meta({description:"The callback URL to redirect to after the user is deleted"}).optional(),password:ci.string().meta({description:"The password of the user is required to delete the user"}).optional(),token:ci.string().meta({description:"The token to delete the user is required"}).optional()}),metadata:{openapi:{operationId:"deleteUser",description:"Delete the user",requestBody:{content:{"application/json":{schema:{type:"object",properties:{callbackURL:{type:"string",description:"The callback URL to redirect to after the user is deleted"},password:{type:"string",description:"The user's password. Required if session is not fresh"},token:{type:"string",description:"The deletion verification token"}}}}}},responses:{"200":{description:"User deletion processed successfully",content:{"application/json":{schema:{type:"object",properties:{success:{type:"boolean",description:"Indicates if the operation was successful"},message:{type:"string",enum:["User deleted","Verification email sent"],description:"Status message of the deletion process"}},required:["success","message"]}}}}}}}},async(e)=>{if(!e.context.options.user?.deleteUser?.enabled)throw e.context.logger.error("Delete user is disabled. Enable it in the options"),l.fromStatus("NOT_FOUND");let t=e.context.session;if(e.body.password){Go(e,e.body.password);let i=await e.context.internalAdapter.findCredentialAccount(t.user.id);if(!i||!i.password)throw l.from("BAD_REQUEST",S.CREDENTIAL_ACCOUNT_NOT_FOUND);if(!await e.context.password.verify({hash:i.password,password:e.body.password}))throw l.from("BAD_REQUEST",S.INVALID_PASSWORD)}if(e.body.token)return await ov({...e,query:{token:e.body.token}}),e.json({success:!0,message:"User deleted"});if(e.context.options.user.deleteUser?.sendDeleteAccountVerification){let i=Ui(32,"0-9","a-z");await e.context.internalAdapter.createVerificationValue({value:t.user.id,identifier:`delete-account-${i}`,expiresAt:new Date(Date.now()+(e.context.options.user.deleteUser?.deleteTokenExpiresIn||86400)*1000)});let o=`${e.context.baseURL}/delete-user/callback?token=${i}&callbackURL=${encodeURIComponent(e.body.callbackURL||"/")}`;return await e.context.runInBackgroundOrAwait(e.context.options.user.deleteUser.sendDeleteAccountVerification({user:t.user,url:o,token:i},e.request)),e.json({success:!0,message:"Verification email sent"})}if(!e.body.password&&e.context.sessionConfig.freshAge!==0){let i=new Date(t.session.createdAt).getTime(),o=e.context.sessionConfig.freshAge*1000;if(Date.now()-i>=o)throw l.from("BAD_REQUEST",S.SESSION_EXPIRED)}let r=e.context.options.user.deleteUser?.beforeDelete;if(r)await r(t.user,e.request);await e.context.internalAdapter.deleteUser(t.user.id),await e.context.internalAdapter.deleteUserSessions(t.user.id),Vo(e);let n=e.context.options.user.deleteUser?.afterDelete;if(n)await n(t.user,e.request);return e.json({success:!0,message:"User deleted"})}),ov=v("/delete-user/callback",{method:"GET",query:ci.object({token:ci.string().meta({description:"The token to verify the deletion request"}),callbackURL:ci.string().meta({description:"The URL to redirect to after deletion"}).optional()}),use:[eu((e)=>e.query.callbackURL)],metadata:{openapi:{description:"Callback to complete user deletion with verification token",responses:{"200":{description:"User successfully deleted",content:{"application/json":{schema:{type:"object",properties:{success:{type:"boolean",description:"Indicates if the deletion was successful"},message:{type:"string",enum:["User deleted"],description:"Confirmation message"}},required:["success","message"]}}}}}}}},async(e)=>{if(!e.context.options.user?.deleteUser?.enabled)throw e.context.logger.error("Delete user is disabled. Enable it in the options"),l.from("NOT_FOUND",{message:"Not found",code:"NOT_FOUND"});let t=await Gr(e,{disableCookieCache:ru(e)});if(!t)throw l.from("NOT_FOUND",S.FAILED_TO_GET_USER_INFO);let r=await e.context.internalAdapter.consumeVerificationValue(`delete-account-${e.query.token}`);if(!r||r.value!==t.user.id)throw l.from("NOT_FOUND",S.INVALID_TOKEN);let n=e.context.options.user.deleteUser?.beforeDelete;if(n)await n(t.user,e.request);await e.context.internalAdapter.deleteUser(t.user.id),await e.context.internalAdapter.deleteUserSessions(t.user.id),await e.context.internalAdapter.deleteAccounts(t.user.id),Vo(e);let i=e.context.options.user.deleteUser?.afterDelete;if(i)await i(t.user,e.request);if(e.query.callbackURL)throw e.redirect(e.query.callbackURL||"/");return e.json({success:!0,message:"User deleted"})}),QM=v("/change-email",{method:"POST",body:ci.object({newEmail:ci.email().meta({description:"The new email address to set must be a valid email address"}),callbackURL:ci.string().meta({description:"The URL to redirect to after email verification"}).optional()}),use:[Gs],metadata:{openapi:{operationId:"changeEmail",responses:{"200":{description:"Email change request processed successfully",content:{"application/json":{schema:{type:"object",properties:{user:{type:"object",$ref:"#/components/schemas/User"},status:{type:"boolean",description:"Indicates if the request was successful"},message:{type:"string",enum:["Email updated","Verification email sent"],description:"Status message of the email change process",nullable:!0}},required:["status"]}}}}}}}},async(e)=>{if(!e.context.options.user?.changeEmail?.enabled)throw e.context.logger.error("Change email is disabled."),l.from("BAD_REQUEST",S.CHANGE_EMAIL_DISABLED);let t=e.body.newEmail.toLowerCase();if(t===e.context.session.user.email)throw e.context.logger.warn("Email is the same"),l.fromStatus("BAD_REQUEST",{message:"Email is the same"});let r=e.context.session.user.emailVerified!==!0&&e.context.options.user.changeEmail.updateEmailWithoutVerification,n=e.context.options.emailVerification?.sendVerificationEmail,i=n&&e.context.session.user.emailVerified&&e.context.options.user.changeEmail.sendChangeEmailConfirmation;if(!r&&!i&&!n)throw e.context.logger.error("Verification email isn't enabled."),l.fromStatus("BAD_REQUEST",{message:"Verification email isn't enabled"});if(await e.context.internalAdapter.findUserByEmail(t))return await lo(e.context.secret,e.context.session.user.email,t,e.context.options.emailVerification?.expiresIn),e.context.logger.info("Change email attempt for existing email"),e.json({status:!0});if(r){if(await e.context.internalAdapter.updateUser(e.context.session.user.id,{email:t}),await ki(e,{session:e.context.session.session,user:{...e.context.session.user,email:t}}),n){let a=await lo(e.context.secret,t,void 0,e.context.options.emailVerification?.expiresIn),c=`${e.context.baseURL}/verify-email?token=${a}&callbackURL=${encodeURIComponent(e.body.callbackURL||"/")}`;await e.context.runInBackgroundOrAwait(n({user:{...e.context.session.user,email:t},url:c,token:a},e.request))}return e.json({status:!0})}if(i){let a=await lo(e.context.secret,e.context.session.user.email,t,e.context.options.emailVerification?.expiresIn,{requestType:"change-email-confirmation"}),c=`${e.context.baseURL}/verify-email?token=${a}&callbackURL=${encodeURIComponent(e.body.callbackURL||"/")}`;return await e.context.runInBackgroundOrAwait(i({user:e.context.session.user,newEmail:t,url:c,token:a},e.request)),e.json({status:!0})}if(!n)throw e.context.logger.error("Verification email isn't enabled."),l.fromStatus("BAD_REQUEST",{message:"Verification email isn't enabled"});let o=await lo(e.context.secret,e.context.session.user.email,t,e.context.options.emailVerification?.expiresIn,{requestType:"change-email-verification"}),s=`${e.context.baseURL}/verify-email?token=${o}&callbackURL=${encodeURIComponent(e.body.callbackURL||"/")}`;return await e.context.runInBackgroundOrAwait(n({user:{...e.context.session.user,email:t},url:s,token:o},e.request)),e.json({status:!0})});var YM=ip((e,t,r)=>{if(Array.isArray(e[t])&&Array.isArray(r))return e[t]=r,!0}),ud=new WeakMap;function sv(e,t){let r=e.options;return r?.operationId??r?.metadata?.openapi?.operationId??t??e.path??"/:virtual"}function XM(e,t){if(!t)return;t.forEach((r,n)=>{if(!e.responseHeaders)e.responseHeaders=new Headers({[n]:r});else if(n.toLowerCase()==="set-cookie")e.responseHeaders.append(n,r);else e.responseHeaders.set(n,r)})}function ZM(e){let t=e[xc],r=e.headers&&e.headers!==t?new Headers(e.headers):null;if(!t&&!r)return null;let n=new Headers;return t?.forEach((i,o)=>{n.append(o,i)}),r?.forEach((i,o)=>{if(o.toLowerCase()==="set-cookie")n.append(o,i);else n.set(o,i)}),n}async function zce(e,t,r,n){let i=ss(e.context.options),o={};for(let s of t){let a=!1;try{a=s.matcher(e)}catch(h){let p=ud.get(s.handler)??"unknown";throw e.context.logger.error(`An error occurred during ${p} hook matcher execution:`,h),new l("INTERNAL_SERVER_ERROR",{message:"An error occurred during hook matcher execution. Check the logs for more details."})}if(!a)continue;let c=ud.get(s.handler)??"unknown",u=r.path??"/:virtual",d=await i(`hook before ${u} ${c}`,{[Si]:"before",[Kc]:u,[Ai]:c,[Nl]:n},()=>s.handler({...e,returnHeaders:!0})).catch((h)=>{if(hi(h)&&Xd(e.context.logger.level,"debug"))h.stack=h.errorStack;throw h});XM(e.context,d?.headers);let f=d?.response;if(f&&typeof f==="object"){if("context"in f&&typeof f.context==="object"){let{headers:h,...p}=f.context;if(h instanceof Headers)if(o.headers)h.forEach((g,_)=>{o.headers?.set(_,g)});else o.headers=h;o=YM(p,o);continue}return f}}return{context:o}}async function Wce(e,t,r,n){let i=ss(e.context.options);for(let o of t){if(!o.matcher(e))continue;let s=ud.get(o.handler)??"unknown",a=r.path??"/:virtual",c=await i(`hook after ${a} ${s}`,{[Si]:"after",[Kc]:a,[Ai]:s,[Nl]:n},()=>o.handler(e)).catch((u)=>{if(hi(u)){if(Xd(e.context.logger.level,"debug"))u.stack=u.errorStack;return{response:u,headers:ZM(u)}}throw u});if(XM(e.context,c.headers),c.response!==void 0)e.context.returned=c.response}return{response:e.context.returned,headers:e.context.responseHeaders}}function Hce(e){let t=e.options.plugins||[],r=[],n=[],i=e.options.hooks?.before;if(i)ud.set(i,"user"),r.push({matcher:()=>!0,handler:i});let o=e.options.hooks?.after;if(o)ud.set(o,"user"),n.push({matcher:()=>!0,handler:o});let s=t.flatMap((c)=>(c.hooks?.before??[]).map((u)=>(ud.set(u.handler,`plugin:${c.id}`),u))),a=t.flatMap((c)=>(c.hooks?.after??[]).map((u)=>(ud.set(u.handler,`plugin:${c.id}`),u)));if(s.length)r.push(...s);if(a.length)n.push(...a);return{beforeHooks:r,afterHooks:n}}async function Rp(e,t){let r=ss(t.context.options),n=t.operationId??sv(e),i=e.path??"/:virtual",o=e.options?.method,s=Array.isArray(o)?o[0]:o,a=t.method??t.request?.method??s??"?",c=t.asResponse??as(t.request),u={...t,context:{...t.context,returned:void 0,responseHeaders:void 0,session:t.context.session??null},path:e.path,headers:t.headers?new Headers(t.headers):void 0};return r(`${a} ${i}`,{[Kc]:i,[Nl]:n},async()=>Ul(u,async()=>{let{beforeHooks:d,afterHooks:f}=Hce(u.context),h=await zce(u,d,e,n);if("context"in h&&h.context&&typeof h.context==="object"){let{headers:_,...R}=h.context;if(_){if(!u.headers)u.headers=new Headers;let O=u.headers;_.forEach((I,Ne)=>{O.set(Ne,I)})}u=YM(R,u)}else if(h){let _=u.context.responseHeaders;return c?Hs(h,{headers:_}):t.returnHeaders?{headers:_,response:h}:h}u.asResponse=!1,u.returnHeaders=!0,u.returnStatus=!0;let p=await Ul(u,()=>r(`handler ${i}`,{[Kc]:i,[Nl]:n},()=>e(u))).catch((_)=>{if(hi(_))return{response:_,status:_.statusCode,headers:ZM(_)};throw _});if(p instanceof Response)return p;u.context.returned=p.response,u.context.responseHeaders=p.headers??void 0;let g=await Wce(u,f,e,n);if(g.response!==void 0)p.response=g.response;if(p.headers=g.headers??p.headers,hi(p.response)&&Xd(u.context.logger.level,"debug"))p.response.stack=p.response.errorStack;if(hi(p.response)&&!c){if(p.headers)Object.defineProperty(p.response,xc,{enumerable:!1,configurable:!0,writable:!1,value:p.headers});throw p.response}return c?Hs(p.response,{headers:p.headers??void 0,status:p.status}):t.returnHeaders?t.returnStatus?{headers:p.headers,response:p.response,status:p.status}:{headers:p.headers,response:p.response}:t.returnStatus?{response:p.response,status:p.status}:p.response}))}async function Vce(e,t){if(e.baseURL)return e;let r=l1(t),n=e.options.baseURL,i=Ee(n)&&Boolean(n.fallback);if(r===void 0&&!i)throw new l("INTERNAL_SERVER_ERROR",{message:"Dynamic baseURL could not be resolved for this direct auth.api call. Pass `headers: request.headers` (or `request`) to the call, or add `fallback` to your baseURL config."});try{return await Nr(e,r,Dr(e.options))}catch(o){if(o instanceof y)throw new l("INTERNAL_SERVER_ERROR",{message:o.message});throw o}}function eq(e,t){let r={};for(let[n,i]of Object.entries(e))r[n]=async(o)=>{let s=sv(i,n),a=async()=>{let c=await t,u=c.checkSchema?.();if(u)await u;let d=Ee(c.options.baseURL)?await Vce(c,o):c;return Rp(i,{...o,context:d,operationId:s,asResponse:o?.asResponse??as(o?.request)})};if(await hT())return a();return pT(new WeakMap,a)},r[n].path=i.path,r[n].options=i.options;return r}function En(e,t){let r=new Map;e.plugins?.forEach((i)=>{if(i.endpoints){for(let[o,s]of Object.entries(i.endpoints))if(s&&"path"in s&&typeof s.path==="string"){let a=s.path,c=[];if(s.options&&"method"in s.options){if(Array.isArray(s.options.method))c=s.options.method;else if(typeof s.options.method==="string")c=[s.options.method]}if(c.length===0)c=["*"];if(!r.has(a))r.set(a,[]);r.get(a).push({pluginId:i.id,endpointKey:o,methods:c})}}});let n=[];for(let[i,o]of r.entries())if(o.length>1){let s=new Map,a=!1;for(let c of o)for(let u of c.methods){if(!s.has(u))s.set(u,[]);if(s.get(u).push(c.pluginId),s.get(u).length>1)a=!0;if(u==="*"&&o.length>1)a=!0;else if(u!=="*"&&s.has("*"))a=!0}if(a){let c=[...new Set(o.map((d)=>d.pluginId))],u=[];for(let[d,f]of s.entries())if(f.length>1||d==="*"&&o.length>1||d!=="*"&&s.has("*"))u.push(d);n.push({path:i,plugins:c,conflictingMethods:u})}}if(n.length>0){let i=n.map((o)=>` - "${o.path}" [${o.conflictingMethods.join(", ")}] used by plugins: ${o.plugins.join(", ")}`).join(`
489
+ `);t.error(`Endpoint path conflicts detected! Multiple plugins are trying to use the same endpoint paths with conflicting HTTP methods:
490
+ ${i}
491
+
492
+ To resolve this, you can:
493
+ 1. Use only one of the conflicting plugins
494
+ 2. Configure the plugins to use different paths (if supported)
495
+ 3. Ensure plugins use different HTTP methods for the same path
496
+ `)}}function cn(e,t){let r=ss(t),n=t.plugins?.reduce((o,s)=>({...o,...s.endpoints}),{})??{},i=t.plugins?.map((o)=>o.middlewares?.map((s)=>{let a=async(c)=>{let u=await e;return r(`middleware ${s.path} ${o.id}`,{[Si]:"middleware",[Kc]:s.path,[Ai]:`plugin:${o.id}`},()=>s.middleware({...c,context:{...u,...c.context}}))};return a.options=s.middleware.options,{path:s.path,middleware:a}})).filter((o)=>o!==void 0).flat()||[];return{api:eq({signInSocial:jM(),callbackOAuth:OM,getSession:CT(),signOut:zM,signUpEmail:WM(),signInEmail:$M(),resetPassword:qM,verifyPassword:BM,verifyEmail:iL,sendVerificationEmail:nL,changeEmail:QM,changePassword:GM,setPassword:KM,updateSession:HM(),updateUser:VM(),deleteUser:JM,requestPasswordReset:LM,requestPasswordResetCallback:MM,listSessions:R1(),revokeSession:N1,revokeSessions:x1,revokeOtherSessions:C1,linkSocialAccount:AM,listUserAccounts:SM,deleteUserCallback:ov,unlinkAccount:TM,refreshToken:NM,getAccessToken:RM,accountInfo:xM,...n,ok:UM,error:DM},e),middlewares:i}}var Cn=(e,t)=>{let r=ss(t),{api:n,middlewares:i}=cn(e,t),o=new URL(e.baseURL).pathname;return aT(n,{routerContext:e,openapi:{disabled:!0},basePath:o,routerMiddleware:[{path:"/**",middleware:b1},...i],allowedMediaTypes:["application/json"],skipTrailingSlashes:t.advanced?.skipTrailingSlashes??!1,async onRequest(s){let a=e.options.disabledPaths||[],c=Ll(s.url,o);if(a.includes(c))return new Response("Not Found",{status:404});let u=e.checkSchema?.();if(u)await u;let d=s,f=await T1(d,e);if(f)return f;for(let h of e.options.plugins||[])if(h.onRequest){let p=await r(`onRequest ${h.id}`,{[Si]:"onRequest",[Ai]:`plugin:${h.id}`},()=>h.onRequest(d,e));if(p&&"response"in p)return p.response;if(p&&"request"in p)d=p.request}return d},async onResponse(s,a){for(let c of e.options.plugins||[])if(c.onResponse){let u=await r(`onResponse ${c.id}`,{[Si]:"onResponse",[Ai]:`plugin:${c.id}`,[Vh]:s.status},()=>c.onResponse(s,e));if(u)return u.response}return s},async onError(s){if(hi(s)&&s.status==="FOUND")return;if(t.onAPIError?.throw)throw s;if(t.onAPIError?.onError){try{await t.onAPIError.onError(s,e)}catch(u){e.logger.error("onAPIError.onError threw",u)}return}let a=t.logger?.level,c=a==="error"||a==="warn"||a==="debug"?T:void 0;if(t.logger?.disabled!==!0){if(s&&typeof s==="object"&&"message"in s&&typeof s.message==="string"){if(s.message.includes("no column")||s.message.includes("column")||s.message.includes("relation")||s.message.includes("table")||s.message.includes("does not exist")){e.logger?.error(s.message);return}}if(hi(s)){if(s.status==="INTERNAL_SERVER_ERROR")e.logger.error(s.status,s);c?.error(s.message)}else e.logger?.error(s&&typeof s==="object"&&"name"in s?s.name:"",s)}}})};function Re(e){return e?.jwks?.keyPairConfig?.alg??"EdDSA"}var Ge=(e,t)=>({getAllKeys:async(r)=>{if(t?.adapter?.getJwks)return await t.adapter.getJwks(r);return await(await $r(e)).findMany({model:"jwks"})},getLatestKey:async(r)=>{let n=new Date,i=(o)=>!o.expiresAt||o.expiresAt>n;if(t?.adapter?.getJwks)return(await t.adapter.getJwks(r))?.filter(i).sort((o,s)=>s.createdAt.getTime()-o.createdAt.getTime())[0];return(await(await $r(e)).findMany({model:"jwks"}))?.filter(i).sort((o,s)=>s.createdAt.getTime()-o.createdAt.getTime())[0]},getKeyById:async(r,n)=>{if(t?.adapter?.getJwks)return(await t.adapter.getJwks(r))?.find((i)=>i.id===n);return await(await $r(e)).findOne({model:"jwks",where:[{field:"id",value:n}]})??void 0},getLatestKeyByAlg:async(r,n)=>{let i=t?.adapter?.getJwks?await t.adapter.getJwks(r):await(await $r(e)).findMany({model:"jwks"});if(!i)return;let o=Re(t),s=new Date;return i.filter((a)=>a.alg===n||a.alg==null&&o===n).filter((a)=>!a.expiresAt||a.expiresAt>s).sort((a,c)=>c.createdAt.getTime()-a.createdAt.getTime())[0]},createJwk:async(r,n)=>{if(t?.adapter?.createJwk)return await t.adapter.createJwk(n,r);return await(await $r(e)).create({model:"jwks",data:{...n,createdAt:new Date}})}});function dd(e,t){if(typeof e==="number")return e;else if(e instanceof Date)return Math.floor(e.getTime()/1000);else return t+Cy(e)}async function tq(e){let{alg:t,...r}=e?.jwks?.keyPairConfig??{alg:"EdDSA",crv:"Ed25519"},{publicKey:n,privateKey:i}=await zr(t,{...r,extractable:!0});return{publicWebKey:await Ct(n),privateWebKey:await Ct(i),alg:t,cfg:r}}async function Pt(e,t){let{publicWebKey:r,privateWebKey:n,alg:i,cfg:o}=await tq(t),s=o&&"crv"in o?o.crv:void 0,a=typeof r.crv==="string"?r.crv:void 0,c=s??a,u=JSON.stringify(n),d=!t?.jwks?.disablePrivateKeyEncryption,f={alg:i,...c?{crv:c}:{},publicKey:JSON.stringify(r),privateKey:d?JSON.stringify(await ka({key:e.context.secretConfig,data:u})):u,createdAt:new Date,...t?.jwks?.rotationInterval?{expiresAt:new Date(Date.now()+t.jwks.rotationInterval*1000)}:{}};return await Ge(e.context.adapter,t).createJwk(e,f)}async function Ze(e,t,r){if(t?.jwt?.sign)return null;let n=Ge(e.context.adapter,t),i;if(r?.signingKeyId!==void 0){if(i=await n.getKeyById(e,r.signingKeyId),!i)throw new y(`signJWT: signingKeyId "${r.signingKeyId}" not found in JWKS. The key must be provisioned before it can be referenced.`);if(r.signingAlgorithm!==void 0){let c=Re(t);if((i.alg??c)!==r.signingAlgorithm)throw new y(`signJWT: signingKeyId "${r.signingKeyId}" has alg "${i.alg??`unset (inherits keyPairConfig.alg "${c}")`}" but signingAlgorithm was set to "${r.signingAlgorithm}".`)}}else if(r?.signingAlgorithm!==void 0){if(i=await n.getLatestKeyByAlg(e,r.signingAlgorithm),!i){let c=Re(t),u=t?.jwks?.keyPairConfigs?.find((f)=>f.alg===r.signingAlgorithm),d=c===r.signingAlgorithm;if(u||d)i=await Pt(e,{...t,jwks:{...t?.jwks,keyPairConfig:u??t?.jwks?.keyPairConfig}});else{let f=t?.jwks?.keyPairConfigs?.map((h)=>h.alg).join(", ")||"none";throw new y(`signJWT: no key with alg "${r.signingAlgorithm}" found in JWKS. The plugin auto-mints only one key matching keyPairConfig.alg="${c}"; additional algs configured via keyPairConfigs: ${f}. Add "${r.signingAlgorithm}" to jwks.keyPairConfigs so the plugin provisions it on first use, or mint the key explicitly via createJwk().`)}}}else{let c=Re(t);i=await n.getLatestKeyByAlg(e,c)??await n.getLatestKey(e)}if(!i||i.expiresAt&&i.expiresAt<new Date){if(r?.signingKeyId!==void 0||r?.signingAlgorithm!==void 0)throw new y("signJWT: requested signing key is expired and an explicit kid/alg was provided; not auto-minting a replacement. Rotate the key explicitly.");i=await Pt(e,t)}let o=!t?.jwks?.disablePrivateKeyEncryption?await Ra({key:e.context.secretConfig,data:JSON.parse(i.privateKey)}).catch(()=>{throw new y("Failed to decrypt private key. Make sure the secret currently in use is the same as the one used to encrypt the private key. If you are using a different secret, either clean up your JWKS or disable private key encryption.")}):i.privateKey,s=i.alg??Re(t),a=await te(JSON.parse(o),s);return{alg:s,kid:i.id,privateKey:a}}async function et(e,t){let{options:r}=t,n=t.payload,i=Math.floor(Date.now()/1000),{iat:o,exp:s}=n,a=dd(r?.jwt?.expirationTime??"15m",o??i);s=s??a;let c=n.nbf,u=typeof e.context.options.baseURL==="string"?e.context.options.baseURL:"",d=n.iss,f=r?.jwt?.issuer??u,h=n.aud,p=r?.jwt?.audience??u;if(!(d??f)||!(h??p))e.context.logger.warn("[better-auth] The JWT plugin signed a JWT without an issuer or audience because no base URL was resolved for this call. Set `baseURL`, or `jwt.issuer` and `jwt.audience` in the JWT plugin options.");if(r?.jwt?.sign){let I={...n,iat:o,exp:s,nbf:c,iss:d??f,aud:h??p};return r.jwt.sign(I,t.header,{signingKeyId:t.signingKeyId,signingAlgorithm:t.signingAlgorithm})}let{alg:g,kid:_,privateKey:R}=t.resolvedKey??await Ze(e,r,{signingKeyId:t.signingKeyId,signingAlgorithm:t.signingAlgorithm}),O=new ke(n).setProtectedHeader({...t.header,alg:g,kid:_}).setExpirationTime(s).setIssuer(d??f).setAudience(h??p);if(o)O.setIssuedAt(o);if(n.sub)O.setSubject(n.sub);if(n.nbf)O.setNotBefore(n.nbf);if(n.jti)O.setJti(n.jti);return await O.sign(R)}async function Ur(e,t){let r=!t?.jwt?.definePayload?e.context.session.user:await t.jwt.definePayload(e.context.session);return await et(e,{options:t,payload:{iat:Math.floor(Date.now()/1000),...r,sub:await t?.jwt?.getSubject?.(e.context.session)??e.context.session.user.id}})}var rq=Object.defineProperty,hw=(e,t)=>{let r={};for(var n in e)rq(r,n,{get:e[n],enumerable:!0});if(!t)rq(r,Symbol.toStringTag,{value:"Module"});return r};var av="ba_iat",pw="ba_pl";function mw(e){let t=new URLSearchParams,r=[...e.entries()].sort(([n,i],[o,s])=>{if(n<o)return-1;if(n>o)return 1;if(i<s)return-1;if(i>s)return 1;return 0});for(let[n,i]of r)t.append(n,i);return t}function nq(e){e.delete("ba_param");let t=[...new Set([...e.keys(),"ba_param"])].sort();for(let r of t)e.append("ba_param",r)}function iq(e){let t=new URLSearchParams(e).get("ba_iat");if(!t)return null;let r=Number(t);if(!Number.isFinite(r)||r<=0)return null;return new Date(r)}var Gce=["authorization_code","client_credentials","refresh_token"],sq=["client_secret_basic","client_secret_post","private_key_jwt"],Kce=["none",...sq],Jce=new Set(Kce);function dv(e,t){if(t.trim().length>0)return;throw new y(`OAuth Provider extension ${e} cannot be empty`)}function aq(e,t){dv(e,t);let r;try{r=new URL(t)}catch{r=void 0}if(r?.protocol)return;throw new y(`OAuth Provider extension ${e} must be an absolute URI: ${t}`)}function Qce(e){aq("grant type",e)}function Yce(e){if(dv("token_endpoint_auth_method",e),!Jce.has(e))return;throw new y(`OAuth Provider extension token_endpoint_auth_method is reserved: ${e}`)}function Xce(e){if(aq("client_assertion_type",e),e!==sd)return;throw new y(`OAuth Provider extension client_assertion_type is reserved: ${e}`)}function Zce(e){let t=Object.keys(e.grants??{});for(let o of t)Qce(o);let r=[],n=[];for(let[o,s]of Object.entries(e.clientAuthentication??{})){Yce(o),r.push(o);let a=s.assertionTypes??[o];if(a.length===0)throw new y(`OAuth Provider extension client_assertion_type list cannot be empty for ${o}`);for(let c of a)Xce(c),n.push(c)}let i=(e.clientDiscovery?Array.isArray(e.clientDiscovery)?e.clientDiscovery:[e.clientDiscovery]:[]).map((o)=>o.id);for(let o of i)dv("client discovery id",o);return{grantTypes:t,authMethods:r,assertionTypes:n,clientDiscoveryIds:i}}function gw(e,t){let r=new Set;for(let n of t){if(r.has(n))throw new y(`OAuth Provider extensions register ${e} "${n}" more than once. Extension contributions must be disjoint.`);r.add(n)}}function cq(e){let t=(e??[]).map(Zce);gw("grant type",t.flatMap((r)=>r.grantTypes)),gw("token_endpoint_auth_method",t.flatMap((r)=>r.authMethods)),gw("client_assertion_type",t.flatMap((r)=>r.assertionTypes)),gw("client discovery id",t.flatMap((r)=>r.clientDiscoveryIds))}function ou(e){return e.extensions??[]}function xp(e){return ou(e).flatMap((t)=>{let r=t.clientDiscovery;if(!r)return[];return Array.isArray(r)?r:[r]})}function eue(e){return ou(e).flatMap((t)=>Object.keys(t.grants??{}))}function Vl(e){return Array.from(new Set([...e.grantTypes??Gce,...eue(e)]))}function uq(e,t){for(let r of ou(e)){let n=r.grants?.[t];if(n)return n}}function dq(e){return ou(e).flatMap((t)=>Object.keys(t.clientAuthentication??{}))}function yw(e,t){return Array.from(new Set([...t?.includeNone?["none"]:[],...sq,...dq(e)]))}function lv(e,t){return t?dq(e).includes(t):!1}function tue(e,t){if(t===sd)return;for(let r of ou(e)){let n=r.clientAuthentication??{};for(let[i,o]of Object.entries(n))if((o.assertionTypes??[i]).includes(t))return{method:i,strategy:o}}}function fv(e,t,r,n){let i={...n};for(let o of ou(t)){let s=o.metadata?.({ctx:e,opts:t,type:r,document:n});for(let[a,c]of Object.entries(s??{}))if(!(a in i))i[a]=c}return i}async function hv(e,t){let r={};for(let n of ou(e)){let i=await t(n)??{};for(let[o,s]of Object.entries(i)){if(o in r){T.warn(`oauth-provider: two extensions contributed the claim "${o}"; keeping the first-registered value.`);continue}r[o]=s}}return r}function lq(e,t){return hv(e,(r)=>r.claims?.accessToken?.(t))}function fq(e,t){return hv(e,(r)=>r.claims?.idToken?.(t))}function hq(e,t){return hv(e,(r)=>r.claims?.userInfo?.(t))}function pq(e){return ou(e).some((t)=>t.claims?.userInfo)}function mq(e){if(!e)return;let[t,r,...n]=e.trim().split(/\s+/);if(t?.toLowerCase()!=="bearer")return;if(!r||n.length>0)throw new st("BAD_REQUEST",{error:"invalid_request",error_description:"Malformed Bearer Authorization header"});return r}function rue(){let e=new Map;return{get(t){let r=e.get(t);if(!r)return;if(r.expiresAt&&r.expiresAt<new Date){e.delete(t);return}return r},set(t,r){e.set(t,r)}}}var Io=(e)=>{let t=e.getPlugin("jwt");if(!t)throw new y("jwt_config");return t},nue=new Set([Et.code,yt.code,Lt.code]);function ww(e){return e instanceof X&&!nue.has(e.code)}function Ca(e){if(e==null)return;if(e instanceof Date)return Number.isFinite(e.getTime())?e:void 0;if(typeof e==="number"){if(!Number.isFinite(e))return;let t=new Date(e);return Number.isFinite(t.getTime())?t:void 0}if(typeof e==="string"){let t=e.trim();if(!t.length)return;let r=Number(t);if(Number.isFinite(r)){let i=new Date(r);return Number.isFinite(i.getTime())?i:void 0}let n=new Date(t);return Number.isFinite(n.getTime())?n:void 0}}function gq(e){if(e instanceof Date)return Ca(e);if(!e||typeof e!=="object")return Ca(e);let t=Ca(e.createdAt)??Ca(e.created_at);if(t)return t;let r=e.session;if(!r||typeof r!=="object")return;return Ca(r.createdAt)??Ca(r.created_at)}function su(e){if(typeof e==="string")return[e];if(!e?.length)return;return e}function pv(e){if(typeof e==="string")return e;if(!e?.length)return;return e.length===1?e.at(0):e}var oq=new WeakMap;function iue(e){let t=oq.get(e);if(t)return t;let r=rue();return oq.set(e,r),r}async function mv(e,t){let r=new URLSearchParams(e),n=r.get("sig"),i=r.getAll("sig"),o=Number(r.get("exp"));r.delete("sig");let s=await fp(mw(r).toString(),t);return i.length===1&&!!n&&nd(n,s)&&new Date(o*1000)>=new Date}function Cp(e,t){if(e.cachedTrustedClients?.has(t))throw new st("BAD_REQUEST",{error:"invalid_client",error_description:"trusted clients must be updated manually"})}async function Fi(e,t,r){let n=iue(t),i=n.get(r);if(i&&!i.clientDiscoveryId)return Object.assign({},i);let o=await e.context.adapter.findOne({model:t.schema?.oauthClient?.modelName??"oauthClient",where:[{field:"clientId",value:r}]}),s=xp(t);if(o?.clientDiscoveryId){let a=o.clientDiscoveryId,c=s.find((u)=>u.id===a);if(!c?.matches(r))return null;if(o=await c.resolve(e,r,o),!o)return null}else if(o){if(t.cachedTrustedClients?.has(r))n.set(r,Object.assign({},o));return o}else for(let a of s){if(!a.matches(r))continue;let c=await a.resolve(e,r,null);if(c){o=c;break}}return o}function gv(e){return e.reduce((t,r)=>({...t,...r.discoveryMetadata??{}}),{})}var _w=async(e)=>{let t=await Ce("SHA-256").digest(new TextEncoder().encode(e));return po.encode(new Uint8Array(t),{padding:!1})};async function Hl(e,t,r){if(t==="encrypted")return await Ra({key:e.context.secretConfig,data:r});else if(typeof t==="object"&&"decrypt"in t)return await t.decrypt(r);throw new y(`Unsupported decryption storageMethod type '${t}'`)}async function oue(e,t,r,n){let i=t.storeClientSecret??(t.disableJwtPlugin?"encrypted":"hashed");if(n&&t.prefix?.clientSecret)if(n.startsWith(t.prefix?.clientSecret))n=n.replace(t.prefix.clientSecret,"");else throw new st("UNAUTHORIZED",{error_description:"invalid client_secret",error:"invalid_client"});if(i==="hashed"){let o=n?await _w(n):void 0;return!!o&&nd(o,r)}else if(typeof i==="object"&&"hash"in i)if(i.verify)return!!n&&await i.verify(n,r);else{let o=n?await i.hash(n):void 0;return!!o&&nd(o,r)}else if(i==="encrypted")try{let o=await Hl(e,i,r);return!!n&&nd(o,n)}catch{return!1}else if(typeof i==="object"&&"decrypt"in i){let o=await Hl(e,i,r);return!!n&&nd(o,n)}throw new y(`Unsupported verify storageMethod type '${i}'`)}async function bw(e,t,r){let n=t.storeClientSecret??(t.disableJwtPlugin?"encrypted":"hashed");if(n==="encrypted")return await ka({key:e.context.secretConfig,data:r});else if(n==="hashed")return await _w(r);else if(typeof n==="object"&&"hash"in n)return await n.hash(r);else if(typeof n==="object"&&"encrypt"in n)return await n.encrypt(r);throw new y(`Unsupported storeClientSecret type '${n}'`)}async function fd(e="hashed",t,r){if(e==="hashed")return await _w(t);else if(typeof e==="object"&&"hash"in e)return await e.hash(t,r);throw new y(`storeToken: unsupported storageMethod type '${e}'`)}async function hd(e="hashed",t,r){if(e==="hashed")return await _w(t);else if(typeof e==="object"&&"hash"in e)return await e.hash(t,r);throw new y(`getStoredToken: unsupported storageMethod type '${e}'`)}var uv=/^Basic +/i,sue=/^([!#$%&'*+\-.^_`|~0-9A-Za-z]+)(?=\s|$)/;function aue(e){return e.match(sue)?.[1]}var cv=["client_secret","client_assertion","client_assertion_type"];function Np(e){throw new st("BAD_REQUEST",{error:"invalid_request",error_description:e})}async function cue(e,t={}){let r;if(t.client_id!==void 0&&t.client_id!==""){if(typeof t.client_id!=="string")Np("client_id must be a string");r=t.client_id}let n={},i=(u,d)=>{if(d===void 0||d==="")return;if(typeof d!=="string")Np(`${u} must be a string`);n[u]=d};for(let u of cv)if(Object.hasOwn(t,u))i(u,t[u]);let o=e?.headers.get("authorization"),s=Boolean(o);if(e){if((e.headers.get("content-type")?.toLowerCase()??"").includes("application/x-www-form-urlencoded")){let u=new URLSearchParams(await e.clone().text()),d=u.getAll("client_id").filter((f)=>f.length>0);if(d.length>1)Np("client_id must not be repeated");r=d[0];for(let f of cv){let h=u.getAll(f).filter((p)=>p.length>0);if(h.length>1)Np(`${f} must not be repeated`);if(h.length===1)i(f,h[0])}}}let a=n.client_secret!==void 0,c=n.client_assertion!==void 0||n.client_assertion_type!==void 0;if(s&&(a||c)||a&&c)Np("A request must use only one client authentication method");t.client_id=r;for(let u of cv)t[u]=n[u];return{detected:s||Object.keys(n).length>0}}function uue(e){if(!uv.test(e))return;try{let{clientId:t,clientSecret:r}=zT(e);return{client_id:t,client_secret:r}}catch{throw new st("UNAUTHORIZED",{error_description:"invalid authorization header format",error:"invalid_client"},{"WWW-Authenticate":"Basic"})}}function Op(e,t){let r=e.grantTypes&&e.grantTypes.length>0?e.grantTypes:["authorization_code"];if(t==="refresh_token"&&r.includes("authorization_code"))return!0;return r.includes(t)}function Ew(e,t){if(!t||!e.scopes)return;let r=new Set(e.scopes);for(let n of t)if(!r.has(n))throw new st("BAD_REQUEST",{error_description:`client does not allow scope ${n}`,error:"invalid_scope"})}function ld(e,t){let r=t?.method==="client_secret_basic",n=t?.scheme??(r?"Basic":void 0);throw new st(n?"UNAUTHORIZED":"BAD_REQUEST",{error_description:e,error:"invalid_client"},n?{"WWW-Authenticate":n}:void 0)}async function au(e,t,r,n,i,o,s,a){let c=await Fi(e,t,r);if(!c)ld("client not found",{method:a});if(c.disabled)ld("client is disabled",{method:a});let u=c.tokenEndpointAuthMethod??"client_secret_basic";if(a&&u!==a)ld(`client registered for ${u} cannot use ${a}`,{method:a});if((c.tokenEndpointAuthMethod==="private_key_jwt"||lv(t,c.tokenEndpointAuthMethod))&&!o)throw new st("BAD_REQUEST",{error_description:`client registered for ${c.tokenEndpointAuthMethod} must use client_assertion`,error:"invalid_client"});if(!o){if(c.tokenEndpointAuthMethod!=="none"&&!n)ld("client secret must be provided",{method:a});if(n&&!c.clientSecret)ld("public client, client secret should not be received",{method:a});if(n&&!await oue(e,t,c.clientSecret,n))ld("invalid client_secret",{method:a})}if(Ew(c,i),s&&!Op(c,s))throw new st("BAD_REQUEST",{error_description:`client is not authorized to use grant type ${s}`,error:"unauthorized_client"});return c}function pd(e){if(!e)return;return typeof e==="string"?JSON.parse(e):e}function cu(e){return{clientId:e?.clientId,clientSecret:e?.kind==="client_secret"?e.clientSecret:void 0,preVerified:e?.kind==="pre_verified",authMethod:e?.method,confirmation:e?.kind==="pre_verified"?e.confirmation:void 0}}async function uu(e,t,r){let n={...e.body??{}};await cue(e.request,n);let i=e.request?.headers.get("authorization")??void 0;if(n.client_assertion_type||n.client_assertion){if(!n.client_assertion||!n.client_assertion_type)throw new st("BAD_REQUEST",{error_description:"client_assertion and client_assertion_type must both be provided",error:"invalid_client"});let{client_assertion:o,client_assertion_type:s}=n,a=tue(t,s);if(a){let u=await a.strategy.authenticate({ctx:e,opts:t,assertion:o,assertionType:s,clientId:n.client_id,expectedAudience:r});return{kind:"pre_verified",method:a.method,clientId:u.clientId,confirmation:u.confirmation}}let{verifyClientAssertion:c}=await import("./chunk-b2n9g75s.js").then((u)=>u.o);return{kind:"pre_verified",method:"private_key_jwt",clientId:(await c(e,t,o,s,n.client_id,r)).clientId}}if(i&&!uv.test(i)){let o=aue(i);if(!o)throw new st("BAD_REQUEST",{error:"invalid_request",error_description:"Invalid authorization header format"});ld("unsupported authorization scheme",{scheme:o})}if(i&&uv.test(i)){let o=uue(i);if(o)return{kind:"client_secret",method:"client_secret_basic",clientId:o.client_id,clientSecret:o.client_secret}}if(n.client_id&&n.client_secret)return{kind:"client_secret",method:"client_secret_post",clientId:n.client_id,clientSecret:n.client_secret};if(n.client_id)return{kind:"public",method:"none",clientId:n.client_id};return null}function yv(e){let t=e.split(" ").map((n)=>n.trim()),r=new Set;for(let n of t)if(n==="login"||n==="consent"||n==="create"||n==="select_account"||n==="none")r.add(n);return new Set(r)}function due(e){let t=e.redirectUris?.[0];if(!t)throw new y("Client has no redirect URIs for sector identifier");return new URL(t).host}async function lue(e,t,r){return fp(`${due(t)}.${e}`,r)}async function Gl(e,t,r){if(t.subjectType==="pairwise"&&r.pairwiseSecret)return lue(e,t,r.pairwiseSecret);return e}async function wv(e,t){return await e.postLogin?.consentReferenceId?.(t)||void 0}async function _v(e,t,r,n){let i=[{field:"clientId",value:t},{field:"userId",value:r}];if(n)return e.context.adapter.findOne({model:"oauthConsent",where:[...i,{field:"referenceId",value:n}]});let o=100;for(let s=0;;s+=o){let a=await e.context.adapter.findMany({model:"oauthConsent",where:i,limit:o,offset:s,sortBy:{field:"id",direction:"asc"}}),c=a.find((u)=>!u.referenceId);if(c||a.length<o)return c??null}}function md(e){let t=Object.create(null);for(let r of new Set(e.keys())){let n=e.getAll(r);t[r]=n.length===1?n[0]:n}return t}function bv(e,t){if(!t)return!1;let r=Ca(e);if(!r)return!1;return r.getTime()>=t.getTime()}function Kl(e,t){let r=new URLSearchParams(e),n=r.get("prompt")?.split(" "),i=n?.findIndex((o)=>o===t)??-1;if(i>=0)n?.splice(i,1),n?.length?r.set("prompt",n.join(" ")):r.delete("prompt");return r}function Ev(e){let t=new URLSearchParams(e);return t.delete("max_age"),t}function Sw(e,t){if(e.tokenEndpointAuthMethod==="none")return"pkce is required for public clients";let r=t?.scopes??[],n=r.includes("openid"),i=typeof t?.nonce==="string"&&t.nonce.length>0,o=n&&i;if(r.includes("offline_access")&&!o)return"pkce or OIDC nonce is required when requesting offline_access scope";if(e.requirePKCE??!0)return"pkce is required for this client";return!1}import*as ct from"zod";import*as Aw from"zod";var fue=/^[a-z](?:[a-z0-9-]*[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]*[a-z0-9])?)+$/i,hue=new Set(["http:","https:","ws:","wss:","file:","ftp:","mailto:","javascript:","data:","vbscript:","blob:","about:","view-source:"]);function pue(e){let t=e.protocol.slice(0,-1),r=e.href.slice(e.protocol.length);return e.protocol!=="http:"&&e.protocol!=="https:"&&e.host.length===0&&r.startsWith("/")&&!r.startsWith("//")&&fue.test(t)}function mue(e){if(hue.has(e.protocol))return!1;if(e.host.length===0)return!1;return e.pathname.startsWith("/")}function yq(e){return pue(e)||mue(e)}var _i=Aw.url().superRefine((e,t)=>{let r;try{r=new URL(e)}catch{return t.addIssue({code:"custom",message:"URL must be parseable",fatal:!0}),Aw.NEVER}if(y1.includes(r.protocol)){t.addIssue({code:"custom",message:"URL cannot use javascript:, data:, or vbscript: scheme"});return}if(e.includes("#"))t.addIssue({code:"custom",message:"Redirect URI must not contain a fragment component"});if(r.protocol==="http:"&&!Pl(r.host))t.addIssue({code:"custom",message:"Redirect URI must use HTTPS (HTTP allowed only for loopback hosts)"})});var gue=new Set(["iss","sub","aud","exp","nbf","iat","jti","auth_time","nonce","acr","amr","azp","sid","at_hash","c_hash","s_hash"]);function wq(e){if(!e)return{};let t=[],r=Object.create(null);for(let[n,i]of Object.entries(e)){if(gue.has(n)){t.push(n);continue}r[n]=i}if(t.length>0)T.warn(`oauth-provider: stripped reserved id-token claim name(s): ${t.join(", ")}. The AS owns these claim values.`);return r}var Nq=ct.record(ct.string(),ct.unknown()).nullable(),yue=ct.looseObject({essential:ct.boolean().optional(),value:ct.string().optional(),values:ct.array(ct.string()).optional()}).nullable(),wue=ct.object({acr:yue.optional()}).catchall(Nq),_ue=ct.looseObject({userinfo:ct.record(ct.string(),Nq).optional(),id_token:wue.optional()});function bue(e){if(typeof e==="string")try{return JSON.parse(e)}catch{return}return e}function Ip(e){let t=bue(e),r=_ue.safeParse(t);return r.success?r.data:void 0}var xq=ct.union([ct.string(),ct.record(ct.string(),ct.unknown())]),Eue=xq,Av=xq.refine((e)=>Ip(e)!==void 0,{error:"claims must be a valid Claims request object"});function Cq(e){return e===void 0||Ip(e)!==void 0}function Dp(e,t){let r=Ip(e)?.userinfo;if(!r)return[];let n=Object.keys(r);if(!t)return n;let i=new Set(t);return n.filter((o)=>i.has(o))}function Oq(e,t){let r=Ip(e);if(!r)return e===void 0;let n=r.id_token?.acr;if(!n||n.essential!==!0)return!0;let i=n.value===void 0||n.value===t,o=n.values===void 0||n.values.includes(t);return i&&o}function Iq(e,t){let r=Ip(e);if(!r)return;let n=new Set(t),i=Object.fromEntries(Object.entries(r.userinfo??{}).filter(([s])=>n.has(s))),o=Object.keys(i).length?{...r,userinfo:i}:Object.fromEntries(Object.entries(r).filter(([s])=>s!=="userinfo"));return Object.keys(o).length?o:void 0}function _q(e){let t=e.split(" ").filter((r)=>r!=="");if(t.length<=1)return{};return{given:t.slice(0,-1).join(" "),family:t.at(-1)}}var kw={name:{scope:"profile",resolve:(e)=>e.name??void 0},picture:{scope:"profile",resolve:(e)=>e.image??void 0},given_name:{scope:"profile",resolve:(e)=>_q(e.name).given},family_name:{scope:"profile",resolve:(e)=>_q(e.name).family},email:{scope:"email",resolve:(e)=>e.email??void 0},email_verified:{scope:"email",resolve:(e)=>e.emailVerified??!1}},Tv=Object.keys(kw);function Up(e){return e.advertisedMetadata?.claims_supported??e.claims??[]}var Sue=new Set(["iss","sub","aud","exp","iat","jti","client_id","scope","auth_time","acr","amr","cnf"]);function Aue(e){if(!e)return{};let t=[],r={};for(let[n,i]of Object.entries(e)){if(Sue.has(n)){t.push(n);continue}r[n]=i}if(t.length>0)T.warn(`oauth-provider: stripped reserved access-token claim name(s): ${t.join(", ")}. The AS owns these claim values.`);return r}async function Dq(e){let{ctx:t,opts:r,user:n,client:i,scopes:o,resources:s,referenceId:a,metadata:c,grantType:u,sessionId:d,perRequestClaims:f,resourcePolicyClaims:h}=e,p=await lq(r,{ctx:t,opts:r,user:n,client:i,scopes:o,grantType:u,referenceId:a,sessionId:d,resources:s,metadata:c}),g=r.customAccessTokenClaims?await r.customAccessTokenClaims({user:n,scopes:o,resources:s,referenceId:a,metadata:c}):{};return Aue({...p,...f??{},...g,...h})}var Tue=["javascript:","data:","vbscript:"],Le=ct.string().superRefine((e,t)=>{if(!URL.canParse(e))return t.addIssue({code:"custom",message:"resource must be an absolute URI",fatal:!0}),ct.NEVER;if(e.includes("#")){t.addIssue({code:"custom",message:"resource must not contain a fragment"});return}if(Tue.includes(new URL(e).protocol))t.addIssue({code:"custom",message:"resource cannot use javascript:, data:, or vbscript: scheme"})}),vue=ct.enum(["none","consent","login","create","select_account"]),kue=ct.string().superRefine((e,t)=>{let r=e.split(" ").map((i)=>i.trim()).filter(Boolean),n=new Set;if(!r.length){t.addIssue({code:"custom",message:"prompt must include at least one value"});return}for(let i of r){let o=vue.safeParse(i);if(!o.success){t.addIssue({code:"custom",message:`unsupported prompt value: ${i}`});continue}n.add(o.data)}if(n.has("none")&&n.size>1)t.addIssue({code:"custom",message:"prompt=none cannot be combined with other prompt values"})}),Pp=ct.object({keys:ct.array(ct.record(ct.string(),ct.unknown())).min(1)}),Rue=ct.union([ct.number(),ct.string().trim().min(1)]).transform((e,t)=>{let r=typeof e==="number"?e:Number(e);if(!Number.isInteger(r)||r<0)return t.addIssue({code:"custom",message:"max_age must be a non-negative integer"}),ct.NEVER;return r}),Nue=ct.string().regex(/^[A-Za-z0-9_-]{43}$/,"dpop_jkt must be a base64url-encoded SHA-256 JWK thumbprint"),vv=ct.object({response_type:ct.string().pipe(ct.enum(["code"])).optional(),request:ct.string().optional(),request_uri:ct.string().optional(),redirect_uri:_i.optional(),scope:ct.string().optional(),state:ct.string().optional(),client_id:ct.string().min(1,"client_id is required"),prompt:kue.optional(),display:ct.string().optional(),ui_locales:ct.string().optional(),max_age:Rue.optional(),acr_values:ct.string().optional(),login_hint:ct.string().optional(),id_token_hint:ct.string().optional(),code_challenge:ct.string().optional(),code_challenge_method:ct.string().pipe(ct.enum(["S256"])).optional(),nonce:ct.string().optional(),claims:Eue.optional(),dpop_jkt:Nue.optional(),resource:ct.union([Le,ct.array(Le).min(1)]).optional()}).passthrough(),xue=vv.extend({redirect_uri:_i.optional(),claims:Av.optional()}),Cue=ct.object({type:ct.literal("authorization_code"),query:xue,sessionId:ct.string(),userId:ct.string(),referenceId:ct.string().optional(),authTime:ct.number().optional(),resource:ct.array(ct.string()).optional()}).passthrough(),kv=ct.object({redirect_uris:ct.array(_i).min(1).optional(),scope:ct.string().optional(),client_name:ct.string().refine((e)=>e.trim().length>0,"client_name cannot be empty").optional(),client_uri:ct.string().optional(),logo_uri:ct.string().optional(),contacts:ct.array(ct.string().min(1)).min(1).optional(),tos_uri:ct.string().optional(),policy_uri:ct.string().optional(),software_id:ct.string().optional(),software_version:ct.string().optional(),software_statement:ct.string().optional(),post_logout_redirect_uris:ct.array(_i).min(1).optional(),backchannel_logout_uri:_i.optional(),backchannel_logout_session_required:ct.boolean().optional(),token_endpoint_auth_method:ct.string().trim().min(1).optional(),jwks:Pp.optional(),jwks_uri:ct.string().optional(),grant_types:ct.array(ct.string().trim().min(1)).min(1).optional(),response_types:ct.array(ct.enum(["code"])).optional(),application_type:ct.enum(["web","native"]).optional(),subject_type:ct.enum(["public","pairwise"]).optional(),dpop_bound_access_tokens:ct.boolean().optional(),resources:ct.array(Le).optional(),skip_consent:ct.never({error:"skip_consent cannot be set during dynamic client registration"}).optional()}),OKe=kv.omit({skip_consent:!0}).extend({client_id:ct.string().refine((e)=>e.trim().length>0,"client_id cannot be empty"),client_secret:ct.string().optional(),client_secret_expires_at:ct.number().int().nonnegative().optional(),client_id_issued_at:ct.number().int().nonnegative().optional()}).loose(),Rw=["EdDSA","ES256","ES512","PS256","RS256"],Oue=new Set(Rw),Iue=64;async function Uq(e,t){let r=e.identifierValidator;if(r){if(!await r(t))return{ok:!1,reason:`resource identifier ${t} failed validation`};return{ok:!0}}let n=Le.safeParse(t);if(!n.success)return{ok:!1,reason:`resource identifier ${t} is invalid: ${n.error.issues[0]?.message??"not an absolute URI"}`};return{ok:!0}}async function Pq(e,t){let r=await Uq(e,t);if(!r.ok)throw new l("BAD_REQUEST",{error:"invalid_target",error_description:r.reason})}var Due=(e)=>`${e}/oauth2/userinfo`;async function Lq(e){if(!(e.headers.get("content-type")?.toLowerCase()??"").includes("application/x-www-form-urlencoded"))return;let t;try{t=await e.clone().text()}catch{return}if(!t)return;let r=new URLSearchParams(t).getAll("resource").filter((n)=>n.length>0);return r.length>0?r:void 0}function Uue(e){if(e===void 0||e===null)return;if(typeof e==="string")return[e];if(Array.isArray(e)){let t=e.filter((r)=>typeof r==="string"&&r.length>0);return t.length>0?t:void 0}}async function Nw(e,t,r,n=[]){if(r===void 0)return!0;let i=Array.isArray(r)?r:[r];if(i.length>Iue)return!1;let o=new Set(n),s=new Set;for(let a of i){if(o.has(a))continue;s.add(a)}if(s.size===0)return!0;return(await Promise.all(Array.from(s,(a)=>Cw(e,t,a)))).every(Boolean)}async function Rv(e,t,r){let n=Uue(r.resource),i=r.requestedScopes.includes("openid"),o=Due(e.context.baseURL??"");if(!n)return{audienceClaim:void 0,accessTokenTtl:null,refreshTokenTtl:null,signingAlgorithm:null,signingKeyId:null,rawCustomClaims:{},dpopBoundAccessTokensRequired:!1,effectiveScopes:[...r.requestedScopes]};let s=[...new Set(n)],a=[];for(let k of s){if(k===o)continue;let j=await Cw(e,t,k);if(j){if(j.disabled)throw new l("BAD_REQUEST",{error:"invalid_target",error_description:`requested resource ${k} is disabled`});a.push(j);continue}throw new l("BAD_REQUEST",{error:"invalid_target",error_description:`requested resource ${k} is not configured`})}let{value:c}=Mq(t);if(c&&a.length>0)await Pue(e,t,r.clientId,a);let u=[...r.requestedScopes];for(let k of a){if(k.allowedScopes===null||k.allowedScopes===void 0)continue;let j=new Set(k.allowedScopes),re=u.filter((Oe)=>j.has(Oe));if(re.length===0)throw new l("BAD_REQUEST",{error:"invalid_scope",error_description:`none of the requested scopes are allowed for resource ${k.identifier}`});u=re}let d=null,f=null;for(let k of a){if(k.accessTokenTtl!=null)d=d===null?k.accessTokenTtl:Math.min(d,k.accessTokenTtl);if(k.refreshTokenTtl!=null)f=f===null?k.refreshTokenTtl:Math.min(f,k.refreshTokenTtl)}let h=new Set,p=new Set;for(let k of a){if(k.signingAlgorithm)h.add(k.signingAlgorithm);if(k.signingKeyId)p.add(k.signingKeyId)}if(h.size>1)throw new l("BAD_REQUEST",{error:"invalid_request",error_description:"multi-resource request has conflicting signingAlgorithm pins; a single JWS signature cannot satisfy multiple algorithms"});if(p.size>1)throw new l("BAD_REQUEST",{error:"invalid_request",error_description:"multi-resource request has conflicting signingKeyId pins; a single JWS signature cannot satisfy multiple key ids"});let g=h.values().next().value??null,_=p.values().next().value??null,R={};for(let k of a)if(k.customClaims&&typeof k.customClaims==="object")Object.assign(R,k.customClaims);let O=a.some((k)=>k.dpopBoundAccessTokensRequired===!0),I=i?[...s,o]:s,Ne=[...new Set(I)];return{audienceClaim:Ne.length===1?Ne[0]:Ne,accessTokenTtl:d,refreshTokenTtl:f,signingAlgorithm:g,signingKeyId:_,rawCustomClaims:R,dpopBoundAccessTokensRequired:O,effectiveScopes:u}}async function Pue(e,t,r,n){if(n.length===0)return;let i=t.schema?.oauthClientResource?.modelName??"oauthClientResource",o=await e.context.adapter.findMany({model:i,where:[{field:"clientId",value:r}]}),s=new Set(o?.map((c)=>c.resourceId)??[]),a=n.filter((c)=>!s.has(c.identifier));if(a.length>0)throw new l("BAD_REQUEST",{error:"invalid_target",error_description:`client ${r} is not linked to resource(s) ${a.map((c)=>c.identifier).join(", ")}`})}async function Lue(e,t,r,n){if(n.length===0)return!1;let i=t.schema?.oauthClientResource?.modelName??"oauthClientResource";return((await e.context.adapter.findMany({model:i,where:[{field:"clientId",value:r},{field:"resourceId",operator:"in",value:n}],limit:1}))?.length??0)>0}async function Mue(e,t,r){if(r.length===0)return{};let n=await e.context.adapter.findMany({model:t.schema?.oauthResource?.modelName??"oauthResource",where:[{field:"identifier",operator:"in",value:r}]}),i=new Map(n.map((s)=>[s.identifier,s])),o={};for(let s of r){let a=i.get(s);if(a?.customClaims&&typeof a.customClaims==="object")Object.assign(o,a.customClaims)}return o}function Mq(e){if(e.enforcePerClientResources!==void 0)return{value:e.enforcePerClientResources,source:"explicit"};return{value:!0,source:"default"}}var Tw=new Map;function xw(e){if(e===void 0){Tw.clear();return}Tw.delete(e)}async function Cw(e,t,r){if(await Nv(e.context,t),t.cachedResources?.has(r)){let i=Tw.get(r);if(i)return Object.assign({},i)}let n=await e.context.adapter.findOne({model:t.schema?.oauthResource?.modelName??"oauthResource",where:[{field:"identifier",value:r}]});if(n&&t.cachedResources?.has(r))Tw.set(r,Object.assign({},n));return n}function que(e){return e.name??e.identifier}function Bue(e){let t=[];if(e.resources?.length)for(let r of e.resources)t.push(typeof r==="string"?{identifier:r}:r);return t}function qq(e,t){return{identifier:e.identifier,name:que(e),accessTokenTtl:e.accessTokenTtl??null,refreshTokenTtl:e.refreshTokenTtl??null,signingAlgorithm:e.signingAlgorithm??null,signingKeyId:e.signingKeyId??null,allowedScopes:e.allowedScopes??null,customClaims:e.customClaims??null,dpopBoundAccessTokensRequired:e.dpopBoundAccessTokensRequired??!1,disabled:e.disabled??!1,policyVersion:1,metadata:e.metadata??null,createdAt:t,updatedAt:t}}function jue(e,t,r){if(t==="overwrite"){let{identifier:i,createdAt:o,...s}=qq(e,r);return s}let n={updatedAt:r};if(e.name!==void 0)n.name=e.name;if(e.accessTokenTtl!==void 0)n.accessTokenTtl=e.accessTokenTtl;if(e.refreshTokenTtl!==void 0)n.refreshTokenTtl=e.refreshTokenTtl;if(e.signingAlgorithm!==void 0)n.signingAlgorithm=e.signingAlgorithm;if(e.signingKeyId!==void 0)n.signingKeyId=e.signingKeyId;if(e.allowedScopes!==void 0)n.allowedScopes=e.allowedScopes;if(e.customClaims!==void 0)n.customClaims=e.customClaims;if(e.dpopBoundAccessTokensRequired!==void 0)n.dpopBoundAccessTokensRequired=e.dpopBoundAccessTokensRequired;if(e.disabled!==void 0)n.disabled=e.disabled;if(e.metadata!==void 0)n.metadata=e.metadata;return n}var $ue=/no such table|relation.*does not exist|table.*does(?: not|n'?t) exist|model.*(?:does not exist|was not found in the schema)/i;function Bq(e,t){let r=!1,n=t;for(let i=0;n&&!r&&i<5;i++)r=$ue.test(n instanceof Error?n.message:String(n)),n=n instanceof Error?n.cause:void 0;if(r){e.logger.debug("oauth-provider: oauthResource table not yet created; deferring resource seed to first access.");return}e.logger.error("oauth-provider: could not seed `resources` at startup; retrying on first resource access.",t)}var bq=new WeakMap;function Fue(e,t){let r=e.adapter,n=bq.get(r);if(!n)n=new WeakMap,bq.set(r,n);let i=n.get(t);if(i)return i;let o={completed:!1,promise:null};return n.set(t,o),o}async function zue(e,t){let r=Bue(t);if(r.length===0)return;let n=t.resourceSeedMode??"insertOnly",i=t.schema?.oauthResource?.modelName??"oauthResource";for(let o of r){let s=await Uq(t,o.identifier);if(!s.ok){T.warn(`oauth-provider: skipping resource seed for ${o.identifier} \u2014 ${s.reason}`);continue}let a=o;if(a.signingAlgorithm!=null&&!Oue.has(a.signingAlgorithm)){T.warn(`oauth-provider: dropping unsupported signingAlgorithm "${a.signingAlgorithm}" for resource ${a.identifier} \u2014 must be one of ${Rw.join(", ")}. Continuing without an algorithm override.`);let{signingAlgorithm:f,...h}=a;a=h}let c=[{field:"identifier",value:a.identifier}],u=await e.adapter.findOne({model:i,where:c}),d=new Date;if(!u)try{await e.adapter.create({model:i,data:qq(a,d)});continue}catch(f){if(!await e.adapter.findOne({model:i,where:c}).catch(()=>null))throw f}if(n==="insertOnly")continue;await e.adapter.update({model:i,where:c,update:jue(a,n,d)})}}async function Nv(e,t){let r=Fue(e,t);if(r.completed===!0)return;if(r.promise!==null)return r.promise;return r.promise=zue(e,t).then(()=>{r.completed=!0}).catch((n)=>{throw r.promise=null,n}),r.promise}function jq(e){let t=Mq(e);T.info(`oauth-provider: enforcePerClientResources resolved to ${t.value} (${t.source})`)}function $q(e){return e.headers?.get("dpop")??void 0}function Ow(e,t){let{baseURL:r}=e.context,n=r.length;while(n>0&&r[n-1]==="/")n--;let i=r.slice(0,n);if(!e.request||!i)return`${i}${t}`;let o=new URL(i).pathname.replace(/\/$/,""),s=new URL(e.request.url).pathname;return`${i}${s.startsWith(`${o}/`)?s.slice(o.length):t}`}var Wue=new Set(["openid","profile","email","offline_access"]);function Fq(e){return Wue.has(e)}function xv(e){return[...new Set(e.map((t)=>t.trim()).filter(Boolean))]}function Cv(e,t,r,n){if(e.length===0)return;if(!t.includes("client_credentials"))throw new l("BAD_REQUEST",{error:"invalid_client_metadata",error_description:"client_credentials_scopes requires the client_credentials grant"});if(r==="none")throw new l("BAD_REQUEST",{error:"invalid_client_metadata",error_description:"public clients cannot be assigned client_credentials scopes"});let i=new Set(n.scopes??[]),o=e.filter((s)=>!i.has(s)||Fq(s));if(o.length>0)throw new l("BAD_REQUEST",{error:"invalid_scope",error_description:`The following client_credentials scopes are invalid: ${o.join(", ")}`})}function Hue(e,t,r=[]){let n=new Set(r),i={sub:e.id??void 0};for(let[o,s]of Object.entries(kw))if(t.includes(s.scope)||n.has(o))i[o]=s.resolve(e);return i}function Sv(e,t){let r={};for(let[n,i]of Object.entries(e??{})){if(i===void 0)continue;if(t&&n in t)continue;r[n]=i}return r}function Vue(e){let t=e.headers?.get("authorization"),r=_p(t),n=e.request?.method==="POST"?e.body?.access_token??void 0:void 0;if(r&&n)throw new l("BAD_REQUEST",{error_description:"Multiple access token transport methods are not allowed",error:"invalid_request"});let i=r??(n?{scheme:"Bearer",token:n}:void 0);return{authorization:i,token:i?.token}}async function zq(e,t){let{authorization:r}=Vue(e);if(!r?.token)throw new l("UNAUTHORIZED",{error_description:"access token not found",error:"invalid_request"});let{payload:n,requestedUserInfoClaims:i}=await Xq(e,t,r.token);if(Sp(n)&&!e.request)throw new l("UNAUTHORIZED",{error_description:"DPoP-bound access token requires an HTTP request context",error:"invalid_token"});try{await uw({payload:n,authorization:r,proofJwt:$q(e),method:e.request?.method??"GET",url:Ow(e,"/oauth2/userinfo"),proofMaxAgeSeconds:t.dpop?.proofMaxAgeSeconds,signingAlgorithms:t.dpop?.signingAlgorithms,replayStore:ow(e.context.internalAdapter)})}catch(h){if(cw(h))throw new l("UNAUTHORIZED",{error_description:h.message,error:h.code});throw h}let o=n.scope?.split(" ");if(!o?.includes("openid"))throw new l("BAD_REQUEST",{error_description:"Missing required scope",error:"invalid_scope"});if(!n.sub)throw new l("BAD_REQUEST",{error_description:"user not found",error:"invalid_request"});let s=await e.context.internalAdapter.findUserById(n.sub);if(!s)throw new l("BAD_REQUEST",{error_description:"user not found",error:"invalid_request"});let a=Hue(s,o??[],i),c=n.client_id??n.azp,u=c&&(t.pairwiseSecret||pq(t))?await Fi(e,t,c):void 0;if(t.pairwiseSecret&&u)a.sub=await Gl(s.id,u,t);let d=o?.length?await hq(t,{ctx:e,opts:t,user:s,scopes:o,jwt:n,client:u??void 0,requestedClaims:i}):{},f=t.customUserInfoClaims&&o?.length?await t.customUserInfoClaims({user:s,scopes:o,jwt:n,requestedClaims:i}):{};return{...a,...Sv(d,a),...Sv(f),sub:a.sub}}var Gue=Object.fromEntries(Tv.map((e)=>[e,void 0]));function Iw(e){return Ep(e)?"DPoP":"Bearer"}var Kue="at+jwt";async function Wq(e,t){let r=e.body.grant_type;if(!Vl(t).includes(r))throw new l("BAD_REQUEST",{error_description:`unsupported grant_type ${r}`,error:"unsupported_grant_type"});switch(r){case"authorization_code":return mde(e,t);case"client_credentials":return gde(e,t);case"refresh_token":return yde(e,t);default:{let n=uq(t,r);if(n)return n({ctx:e,opts:t,grantType:r,provider:Jue(e,t,r)});throw new l("BAD_REQUEST",{error_description:`unsupported grant_type ${r}`,error:"unsupported_grant_type"})}}}function Jue(e,t,r){return{getClient:(n)=>Fi(e,t,n),authenticateClient:async(n)=>{let{clientId:i,clientSecret:o,preVerified:s,authMethod:a,confirmation:c}=cu(await uu(e,t,`${e.context.baseURL}${e.path??"/oauth2/token"}`));if(!i)throw new l("BAD_REQUEST",{error_description:"Missing required client_id",error:"invalid_request"});if(n?.requireCredentials!==!1&&!o&&!s)throw new l("BAD_REQUEST",{error_description:"Missing required client credentials",error:"invalid_client"});return{clientId:i,client:await au(e,t,i,o,n?.scopes,s,r,a),method:a,confirmation:c}},issueTokens:(n)=>{if(!r)throw new l("INTERNAL_SERVER_ERROR",{error_description:"issueTokens requires a grant type; pass it to getOAuthProviderApi(ctx, opts, grantType).",error:"server_error"});return Pw(e,t,{...n,grantType:r})},hashToken:(n,i)=>fd(t.storeTokens,n,i),validateAccessToken:async(n,i)=>{let{validateAccessToken:o}=await Promise.resolve().then(()=>kq);return o(e,t,n,i)},requireActiveAccessToken:async(n,i)=>{let{requireActiveAccessToken:o}=await Promise.resolve().then(()=>kq);return o(e,t,n,i)}}}async function Que(e,t,r,n,i,o,s){let a=s?.iat??Math.floor(Date.now()/1000),c=s?.exp??a+(t.accessTokenExpiresIn??3600),u=Io(e.context).options,d=r?.id??n.clientId;return et(e,{options:u,header:{typ:Kue},signingKeyId:s?.signingKeyId??void 0,signingAlgorithm:s?.signingAlgorithm??void 0,payload:{...s?.accessTokenClaims??{},sub:d,aud:pv(i),client_id:n.clientId,azp:n.clientId,scope:o.join(" "),sid:s?.sid,iss:u?.jwt?.issuer??e.context.baseURL,iat:a,exp:c,jti:Ui(32),...s?.confirmation?{cnf:s.confirmation}:{}}})}async function Yue(e,t){let r;if(t==="EdDSA")r="SHA-512";else if(t.endsWith("384"))r="SHA-384";else if(t.endsWith("512"))r="SHA-512";else r="SHA-256";let n=new Uint8Array(await crypto.subtle.digest(r,new TextEncoder().encode(e)));return B(n.slice(0,n.length/2))}async function Xue(e,t,r,n,i,o,s,a,c,u){let d=Math.floor(Date.now()/1000),f=d+(t.idTokenExpiresIn??36000),h=await Gl(r.id,n,t),p=a!=null?Math.floor(a.getTime()/1000):void 0,g=wq(t.customIdTokenClaims?await t.customIdTokenClaims({user:r,scopes:i,metadata:pd(n.metadata)}):void 0),_=t.disableJwtPlugin?void 0:Io(e.context).options,R=!t.disableJwtPlugin&&!_?.jwt?.sign?await Ze(e,_):void 0,O=t.disableJwtPlugin?"HS256":R?.alg??_?.jwks?.keyPairConfig?.alg,I=c?await Yue(c,O):void 0,Ne=Boolean(n.enableEndSession||n.backchannelLogoutUri),k={...Gue,auth_time:p,acr:"0",...g,at_hash:I,iss:_?.jwt?.issuer??e.context.baseURL,sub:h,aud:n.clientId,nonce:o,iat:d,exp:f,sid:Ne?s:void 0},j=wq(u);if(Object.assign(k,Sv(j,k)),t.disableJwtPlugin&&!n.clientSecret)return;let re=t.disableJwtPlugin?await new ke(k).setProtectedHeader({alg:"HS256"}).sign(new TextEncoder().encode(await Hl(e,t.storeClientSecret,n.clientSecret))):await et(e,{options:_,payload:k,resolvedKey:R??void 0});if(re&&I&&_?.jwt?.sign){let Oe=ue(re);if(Oe.alg!==O)throw new l("INTERNAL_SERVER_ERROR",{error_description:`ID token signed with "${Oe.alg}" but at_hash was computed for "${O}". Ensure jwt.sign uses the algorithm declared in keyPairConfig.alg.`,error:"server_error"})}return re}async function Eq(e,t,r){return(e.prefix?.refreshToken??"")+(e.formatRefreshToken?.encrypt?e.formatRefreshToken.encrypt(t,r):t)}async function Dw(e,t){if(e.prefix?.refreshToken)if(t.startsWith(e.prefix.refreshToken))t=t.replace(e.prefix.refreshToken,"");else throw new l("BAD_REQUEST",{error_description:"refresh token not found",error:"invalid_token"});return e.formatRefreshToken?.decrypt?e.formatRefreshToken?.decrypt(t):{token:t}}async function Zue(e,t,r,n,i,o,s,a,c,u,d,f){let h=o.iat??Math.floor(Date.now()/1000),p=o?.exp??h+(t.accessTokenExpiresIn??3600),g=t.generateOpaqueAccessToken?await t.generateOpaqueAccessToken():Ui(32,"A-Z","a-z");return await e.context.adapter.create({model:"oauthAccessToken",data:{token:await fd(t.storeTokens,g,"access_token"),clientId:n.clientId,sessionId:o?.sid,userId:r?.id,referenceId:a,authorizationCodeId:c,resources:s,refreshId:u,confirmation:d,requestedUserInfoClaims:f?.length?f:void 0,scopes:i,createdAt:new Date(h*1000),expiresAt:new Date(p*1000)}}),(t.prefix?.opaqueAccessToken??"")+g}async function Uw(e,t,r){let n=await e.context.adapter.findMany({model:"oauthRefreshToken",where:[{field:"clientId",value:t},{field:"userId",value:r}]});if(n.length)await e.context.adapter.deleteMany({model:"oauthAccessToken",where:[{field:"refreshId",operator:"in",value:n.map((i)=>i.id)}]});await e.context.adapter.deleteMany({model:"oauthRefreshToken",where:[{field:"clientId",value:t},{field:"userId",value:r}]})}async function ede(e,t){let r=async(n)=>{try{await e.context.adapter.deleteMany({model:n,where:[{field:"authorizationCodeId",value:t}]})}catch(i){e.context.logger.error("authorization code replay cleanup failed",i)}};await r("oauthAccessToken"),await r("oauthRefreshToken")}async function Sq(e,t,r,n,i,o,s,a,c,u,d,f,h){let p=a.iat??Math.floor(Date.now()/1000),g=a?.exp??p+(t.refreshTokenExpiresIn??2592000),_=t.generateRefreshToken?await t.generateRefreshToken():Ui(32,"A-Z","a-z"),R=a?.sid,O={token:await fd(t.storeTokens,_,"refresh_token"),clientId:o.clientId,sessionId:R,userId:r.id,referenceId:n,authorizationCodeId:i,authTime:u,confirmation:f,requestedUserInfoClaims:h?.length?h:void 0,scopes:s,resources:d,createdAt:new Date(p*1000),expiresAt:new Date(g*1000)};if(!c?.id)return{id:(await e.context.adapter.create({model:"oauthRefreshToken",data:O})).id,token:await Eq(t,_,R)};let I=new Date(p*1000),Ne={revoked:I,rotatedAt:I},k=t.refreshTokenReuseInterval??0;if(k>0)Ne.rotationReplayExpiresAt=new Date((p+k)*1000);if(!await e.context.adapter.incrementOne({model:"oauthRefreshToken",where:[{field:"id",value:c.id},{field:"revoked",operator:"eq",value:null}],increment:{},set:Ne}))throw new l("BAD_REQUEST",{error_description:"invalid refresh token",error:"invalid_grant"});return{id:(await e.context.adapter.create({model:"oauthRefreshToken",data:O})).id,token:await Eq(t,_,R)}}async function Hq(e,t,r){let n=await Rv(e,t,{resource:r.resources,clientId:r.clientId,requestedScopes:r.requestedScopes}),i=n.accessTokenTtl!==null?r.iat+n.accessTokenTtl:r.scopeExpiresAtSeconds,o=t.refreshTokenExpiresIn??2592000,s=n.refreshTokenTtl!==null?Math.min(n.refreshTokenTtl,o):o;return{audienceClaim:n.audienceClaim,effectiveScopes:n.effectiveScopes,accessTokenExpiresAtSeconds:Math.min(r.scopeExpiresAtSeconds,i),refreshTokenExpiresAtSeconds:r.iat+s,refreshResources:r.refreshToken?.resources??r.originalResources??r.resources,signingAlgorithm:n.signingAlgorithm,signingKeyId:n.signingKeyId,resourceCustomClaims:n.rawCustomClaims,dpopBoundAccessTokensRequired:n.dpopBoundAccessTokensRequired}}function Aq(e){throw new l("BAD_REQUEST",{error:"invalid_dpop_proof",error_description:e})}function tde(e){let t=pd(e.metadata)??{};return e.dpopBoundAccessTokens===!0||t.dpop_bound_access_tokens===!0}async function Vq(e,t,r){let n=r.verificationValue?.query.dpop_jkt,i=Ep(r.refreshToken?.confirmation),o=i??n,s=$q(e),a=tde(r.client)||r.grantIssuance.dpopBoundAccessTokensRequired||!!n||!!i;if(!s){if(a)Aq("DPoP proof header is required");return}try{return{jkt:(await aw({proofJwt:s,method:"POST",url:Ow(e,e.path??"/oauth2/token"),expectedJkt:o,proofMaxAgeSeconds:t.dpop?.proofMaxAgeSeconds,signingAlgorithms:t.dpop?.signingAlgorithms,replayStore:ow(e.context.internalAdapter)})).jkt}}catch(c){if(sw(c))Aq(c.message);throw c}}function vw(e){return e?[...new Set(e)].sort():void 0}function Tq(e,t){let r=vw(e),n=vw(t);if(r===void 0||n===void 0)return r===n;if(r.length!==n.length)return!1;return r.every((i,o)=>i===n[o])}function vq(e){if(!e)return;if("jkt"in e)return`jkt:${e.jkt}`;return`x5t#S256:${e["x5t#S256"]}`}function rde(e,t){return vq(e)===vq(t)}function nde(e){if(!e||typeof e!=="object")return!1;let t=e;return typeof t.jkt==="string"&&t["x5t#S256"]===void 0||typeof t["x5t#S256"]==="string"&&t.jkt===void 0}function ide(e){return e==="Bearer"||e==="DPoP"}function ode(e){if(!e||typeof e!=="object")return!1;let t=e;return typeof t.access_token==="string"&&typeof t.expires_in==="number"&&typeof t.expires_at==="number"&&ide(t.token_type)&&typeof t.scope==="string"&&(t.refresh_token===void 0||typeof t.refresh_token==="string")&&(t.id_token===void 0||typeof t.id_token==="string")}function sde(e){if(!e||typeof e!=="object")return!1;let t=e,r=t.request;return!!r&&Array.isArray(r.effectiveScopes)&&r.effectiveScopes.every((n)=>typeof n==="string")&&(r.requestedResources===void 0||Array.isArray(r.requestedResources)&&r.requestedResources.every((n)=>typeof n==="string"))&&(r.confirmation===void 0||nde(r.confirmation))&&ode(t.response)}function Gq(e){let t=vw(e.requestedResources);return{effectiveScopes:vw(e.effectiveScopes)??[],...t?{requestedResources:t}:{},...e.confirmation?{confirmation:e.confirmation}:{}}}function ade(e,t){return Tq(e.effectiveScopes,t.effectiveScopes)&&Tq(e.requestedResources,t.requestedResources)&&rde(e.confirmation,t.confirmation)}async function cde(e,t){return ka({key:e.context.secretConfig,data:JSON.stringify(t)})}async function ude(e,t){let r=await Ra({key:e.context.secretConfig,data:t}),n=JSON.parse(r);if(!sde(n))return;return n}function Kq(e){return!!e.rotatedAt&&!!e.rotationReplayExpiresAt&&e.rotationReplayExpiresAt>=new Date}async function dde(e,t,r,n,i){if((t.refreshTokenReuseInterval??0)<=0)return;await e.context.adapter.update({model:"oauthRefreshToken",where:[{field:"id",value:r.id}],update:{rotationReplayResponse:await cde(e,{request:n,response:i})}})}async function lde(e,t,r){if(!Kq(t))return;if(!t.rotationReplayResponse)return;try{let n=await ude(e,t.rotationReplayResponse);if(!n||!ade(n.request,r))return;return n.response}catch(n){e.context.logger.error("refresh token rotation replay failed",n);return}}async function fde(e,t,r){let n=Math.floor(Date.now()/1000),i=await Hq(e,t,{clientId:r.client.clientId,requestedScopes:r.scopes,resources:r.resources,refreshToken:r.refreshToken,iat:n,scopeExpiresAtSeconds:n+(t.accessTokenExpiresIn??3600)}),o=await Vq(e,t,{client:r.client,grantIssuance:i,refreshToken:r.refreshToken});return Gq({effectiveScopes:i.effectiveScopes,requestedResources:r.resources,confirmation:o})}function hde(e,t){let r=Math.floor(Date.now()/1000);return e.json({...t,expires_in:Math.max(0,t.expires_at-r)})}async function Pw(e,t,r){let{client:n,scopes:i,user:o,grantType:s,referenceId:a,sessionId:c,nonce:u,refreshToken:d,authTime:f,verificationValue:h}=r,p=Math.floor(Date.now()/1000),g=p+(o?t.accessTokenExpiresIn??3600:t.m2mAccessTokenExpiresIn??3600),_=t.scopeExpirations?i.map((Je)=>t.scopeExpirations?.[Je]?dd(t.scopeExpirations[Je],p):g).reduce((Je,ft)=>Je<ft?Je:ft,g):g,R=await Hq(e,t,{clientId:n.clientId,requestedScopes:i,resources:r.resources,originalResources:r.originalResources,refreshToken:r.refreshToken,iat:p,scopeExpiresAtSeconds:_}),{audienceClaim:O,effectiveScopes:I,accessTokenExpiresAtSeconds:Ne,refreshTokenExpiresAtSeconds:k}=R,j=o&&Op(n,"refresh_token")&&(d?.scopes?.includes("offline_access")||i.includes("offline_access")),re=O&&!t.disableJwtPlugin,Oe=o&&I.includes("openid"),ne=pd(n.metadata),M=Oe&&o?{...await fq(t,{ctx:e,opts:t,user:o,client:n,scopes:I,grantType:s,referenceId:a,sessionId:c,resources:r.resources,metadata:ne}),...r.idTokenClaims??{}}:void 0,F=t.customTokenResponseFields?await t.customTokenResponseFields({grantType:s,user:o,scopes:I,metadata:ne,verificationValue:h}):void 0,ce=R.refreshResources,de=r.confirmation??await Vq(e,t,{client:n,grantIssuance:R,verificationValue:h,refreshToken:d}),pe=r.requestedUserInfoClaims??d?.requestedUserInfoClaims??[],ae=j&&o&&!re?await Sq(e,t,o,a,r.authorizationCodeId,n,I,{iat:p,exp:k,sid:c},d,f,ce,de,pe):void 0,He=re?await Dq({ctx:e,opts:t,user:o,client:n,scopes:I,grantType:s,sessionId:c,resources:r.resources,referenceId:a,metadata:ne,perRequestClaims:r.accessTokenClaims,resourcePolicyClaims:R.resourceCustomClaims}):void 0,[Be,Ke]=await Promise.all([re?Que(e,t,o,n,O,I,{iat:p,exp:Ne,sid:c,signingAlgorithm:R.signingAlgorithm,signingKeyId:R.signingKeyId,accessTokenClaims:He,confirmation:de}):Zue(e,t,o,n,I,{iat:p,exp:Ne,sid:c},r?.resources,a,r.authorizationCodeId,ae?.id,de,pe),ae?ae:j&&o?Sq(e,t,o,a,r.authorizationCodeId,n,I,{iat:p,exp:k,sid:c},d,f,ce,de,pe):void 0]),Te=Oe?await Xue(e,t,o,n,I,u,c,f,Be,M):void 0,Ve={...F,...r.tokenResponse??{},access_token:Be,expires_in:Ne-p,expires_at:Ne,token_type:Iw(de),refresh_token:Ke?.token,scope:I.join(" "),id_token:Te};if(d?.id&&Ke?.id)try{await dde(e,t,d,Gq({effectiveScopes:I,requestedResources:r.resources,confirmation:de}),Ve)}catch(Je){e.context.logger.error("failed to store refresh token rotation replay",Je)}return e.json(Ve)}async function pde(e,t,r,n,i,o){let s=await fd(t.storeTokens,r,"authorization_code"),a=await e.context.internalAdapter.consumeVerificationValue(s);if(!a)throw await ede(e,s),new l("BAD_REQUEST",{error_description:"invalid code",error:"invalid_grant"});let c;try{c=JSON.parse(a.value)}catch{throw new l("BAD_REQUEST",{error_description:"malformed verification value",error:"invalid_grant"})}let u=Cue.safeParse(c);if(!u.success)throw new l("BAD_REQUEST",{error_description:"malformed verification value",error:"invalid_grant"});let d=u.data;if(d.query.client_id!==n)throw new l("BAD_REQUEST",{error_description:"invalid client_id",error:"invalid_grant"});let f=d.query.redirect_uri;if(f){if(!i)throw new l("BAD_REQUEST",{error_description:"redirect_uri is required",error:"invalid_request"});if(f!==i)throw new l("BAD_REQUEST",{error_description:"redirect_uri mismatch",error:"invalid_grant"})}else if(i)throw new l("BAD_REQUEST",{error_description:"redirect_uri mismatch",error:"invalid_grant"});let h=su(d.resource)??su(d.query.resource),p=o??h;if(o&&h){let g=new Set(o),_=new Set(h);for(let R of g)if(!_.has(R))throw new l("BAD_REQUEST",{error_description:"requested resource not authorized",error:"invalid_target"})}return{verificationValue:d,effectiveResources:p,authorizedResources:h,authorizationCodeId:s}}async function mde(e,t){let{clientId:r,clientSecret:n,preVerified:i,authMethod:o}=cu(await uu(e,t,`${e.context.baseURL}/oauth2/token`)),{code:s,code_verifier:a,redirect_uri:c,resource:u}=e.body,d=su(u);if(!r)throw new l("BAD_REQUEST",{error_description:"client_id is required",error:"invalid_request"});if(!s)throw new l("BAD_REQUEST",{error_description:"code is required",error:"invalid_request"});let f=r&&n,h=r&&s&&a;if(!f&&!h&&!i)throw new l("BAD_REQUEST",{error_description:"Either code_verifier or client_secret is required",error:"invalid_request"});let p=await au(e,t,r,n,void 0,i,"authorization_code",o),{verificationValue:g,effectiveResources:_,authorizedResources:R,authorizationCodeId:O}=await pde(e,t,s,r,c,d),I=g.query.scope?.split(" ");if(!I)throw new l("INTERNAL_SERVER_ERROR",{error_description:"verification scope unset",error:"invalid_scope"});if(Ew(p,I),Sw(p,{scopes:g.query?.scope?.split(" ")||[],nonce:g.query?.nonce})){if(!h)throw new l("BAD_REQUEST",{error_description:"PKCE is required for this client",error:"invalid_request"})}else if(!(h||f||i))throw new l("BAD_REQUEST",{error_description:"Either PKCE (code_verifier) or client authentication (client_secret or client_assertion) is required",error:"invalid_request"});let Ne=!!g.query?.code_challenge,k=!!a;if(Ne||k){if(Ne&&!k)throw new l("BAD_REQUEST",{error_description:"code_verifier required because PKCE was used in authorization",error:"invalid_request"});if(!Ne&&k)throw new l("BAD_REQUEST",{error_description:"code_verifier provided but PKCE was not used in authorization",error:"invalid_request"});if((g.query?.code_challenge_method==="S256"?await pp(a):void 0)!==g.query?.code_challenge)throw new l("BAD_REQUEST",{error_description:"code verification failed",error:"invalid_grant"})}if(!g.userId)throw new l("BAD_REQUEST",{error_description:"missing user, user may have been deleted",error:"invalid_user"});let j=await e.context.internalAdapter.findUserById(g.userId);if(!j)throw new l("BAD_REQUEST",{error_description:"missing user, user may have been deleted",error:"invalid_user"});let re=await e.context.adapter.findOne({model:"session",where:[{field:"id",value:g.sessionId}]});if(!re||re.expiresAt<new Date)throw new l("BAD_REQUEST",{error_description:"session no longer exists",error:"invalid_request"});let Oe=g.authTime!=null?Ca(g.authTime):gq(re),ne=Dp(g.query.claims,Up(t));return Pw(e,t,{client:p,scopes:g.query.scope?.split(" ")??[],user:j,grantType:"authorization_code",referenceId:g.referenceId,sessionId:re.id,nonce:g.query?.nonce,authTime:Oe,verificationValue:g,authorizationCodeId:O,requestedUserInfoClaims:ne,resources:_,originalResources:R})}async function gde(e,t){let{clientId:r,clientSecret:n,preVerified:i,authMethod:o}=cu(await uu(e,t,`${e.context.baseURL}/oauth2/token`)),{scope:s,resource:a}=e.body,c=su(a);if(!r)throw new l("BAD_REQUEST",{error_description:"Missing required client_id",error:"invalid_request"});let u=await au(e,t,r,n,void 0,i,"client_credentials",o);if(u.tokenEndpointAuthMethod==="none")throw new l("BAD_REQUEST",{error_description:"public clients cannot use the client_credentials grant",error:"unauthorized_client"});let d=u.clientCredentialsScopes;if(!d?.length)throw new l("BAD_REQUEST",{error_description:"client has no authorized client_credentials scopes",error:"unauthorized_client"});let f=s?.split(" ");if(f){let h=new Set(d),p=f.filter((g)=>!h.has(g)||Fq(g));if(p.length)throw new l("BAD_REQUEST",{error_description:`The following scopes are invalid: ${p.join(", ")}`,error:"invalid_scope"})}if(!f)f=[...d];return Pw(e,t,{client:u,scopes:f,grantType:"client_credentials",resources:c})}async function yde(e,t){let{clientId:r,clientSecret:n,preVerified:i,authMethod:o}=cu(await uu(e,t,`${e.context.baseURL}/oauth2/token`)),{refresh_token:s,scope:a,resource:c}=e.body,u=su(c);if(!r)throw new l("BAD_REQUEST",{error_description:"Missing required client_id",error:"invalid_request"});if(!s)throw new l("BAD_REQUEST",{error_description:"Missing a required refresh_token for refresh_token grant",error:"invalid_request"});let d=await au(e,t,r,n,void 0,i,"refresh_token",o),f=await Dw(t,s),h=await e.context.adapter.findOne({model:"oauthRefreshToken",where:[{field:"token",value:await hd(t.storeTokens,f.token,"refresh_token")}]});if(!h)throw new l("BAD_REQUEST",{error_description:"session not found",error:"invalid_grant"});if(h.clientId!==r)throw new l("BAD_REQUEST",{error_description:"invalid refresh token",error:"invalid_grant"});if(h.expiresAt<new Date)throw new l("BAD_REQUEST",{error_description:"invalid refresh token",error:"invalid_grant"});if(u&&h.resources&&!u.every((O)=>h.resources?.includes(O)))throw new l("BAD_REQUEST",{error_description:"requested resource invalid",error:"invalid_target"});let p=h?.scopes,g=a?.split(" ");if(g){let O=new Set(p);for(let I of g)if(!O.has(I))throw new l("BAD_REQUEST",{error_description:`unable to issue scope ${I}`,error:"invalid_scope"})}if(Ew(d,g??p),h.revoked){if(Kq(h)){let O=await lde(e,h,await fde(e,t,{client:d,refreshToken:h,scopes:g??p,resources:u??h.resources}));if(O)return hde(e,O);throw new l("BAD_REQUEST",{error_description:"invalid refresh token",error:"invalid_grant"})}throw await Uw(e,r,h.userId),new l("BAD_REQUEST",{error_description:"invalid refresh token",error:"invalid_grant"})}let _=await e.context.internalAdapter.findUserById(h.userId);if(!_)throw new l("BAD_REQUEST",{error_description:"user not found",error:"invalid_request"});let R=h.authTime!=null?Ca(h.authTime):void 0;return Pw(e,t,{client:d,scopes:g??p,user:_,grantType:"refresh_token",referenceId:h.referenceId,authorizationCodeId:h.authorizationCodeId,sessionId:h.sessionId,refreshToken:h,resources:u??h.resources,authTime:R,requestedUserInfoClaims:h.requestedUserInfoClaims})}var kq=hw({introspectEndpoint:()=>Dv,requireActiveAccessToken:()=>Tde,requireActiveAccessTokenWithClaims:()=>Xq,validateAccessToken:()=>Iv}),Jq="Invalid access token",wde=`Bearer error="invalid_token", error_description="${Jq}"`;function Jl(){return{payload:{active:!1},requestedUserInfoClaims:[]}}function _de(e,t){if(e==null)return[];return(Array.isArray(e)?e:[e]).filter((r)=>typeof r==="string"&&r!==t)}async function Qq(e,t,r){let{introspectingClientId:n,issuerClientId:i,audienceResources:o}=r;if(!n)return!0;if(n===i)return!0;if(o.length===0)return!1;return Lue(e,t,n,o)}async function bde(e,t,r,n){if(t.disableJwtPlugin)throw new st("BAD_REQUEST",{error_description:"JWT access tokens are disabled",error:"invalid_request"});let i=Io(e.context),o=i.options,s=`${e.context.baseURL??""}/oauth2/userinfo`,a=o?.jwt?.issuer??e.context.baseURL,c;try{c=(await V(r,Se(await jl(r,{jwksFetch:o?.jwks?.remoteUrl?o.jwks.remoteUrl:async()=>(await i.endpoints.getJwks(e))?.response,jwksCacheKey:i})),{issuer:a})).payload}catch(h){if(h instanceof tt||h instanceof H)return{active:!1};if(h instanceof TypeError||ww(h))throw new st("BAD_REQUEST",{error_description:"invalid JWT signature",error:"invalid_request"});throw h}let u=c.aud;if(!await Nw(e,t,u,[s]))return{active:!1};if(!c.azp)return{active:!1};let d=await Fi(e,t,c.azp);if(!d||d?.disabled)return{active:!1};if(!await Qq(e,t,{introspectingClientId:n,issuerClientId:c.azp,audienceResources:_de(u,s)}))return{active:!1};let f=c.sid;if(f){let h=await e.context.adapter.findOne({model:"session",where:[{field:"id",value:f}]});if(!h||h.expiresAt<new Date)return{active:!1}}return c.client_id=c.azp,c.active=!0,c.token_type=Iw(c.cnf),c}async function Ede(e,t,r,n){let i=r;if(t.prefix?.opaqueAccessToken)if(i.startsWith(t.prefix.opaqueAccessToken))i=i.replace(t.prefix.opaqueAccessToken,"");else throw new st("BAD_REQUEST",{error_description:"opaque access token not found",error:"invalid_request"});let o=await e.context.adapter.findOne({model:"oauthAccessToken",where:[{field:"token",value:await hd(t.storeTokens,i,"access_token")}]});if(!o)throw new st("BAD_REQUEST",{error_description:"opaque access token not found",error:"invalid_token"});if(!o.expiresAt||o.expiresAt<new Date)return Jl();if(o.revoked)return Jl();let s=Array.isArray(o.resources)?o.resources:void 0,a;if(o.clientId){if(a=await Fi(e,t,o.clientId),!a||a?.disabled)return Jl();if(!await Qq(e,t,{introspectingClientId:n,issuerClientId:o.clientId,audienceResources:s??[]}))return Jl()}let c=o.sessionId??void 0;if(c){let _=await e.context.adapter.findOne({model:"session",where:[{field:"id",value:c}]});if(!_||_.expiresAt<new Date)return Jl()}let u;if(o.userId)u=await e.context.internalAdapter.findUserById(o?.userId);let d=`${e.context.baseURL}/oauth2/userinfo`;if(s?.length&&!await Nw(e,t,s,[d]))return Jl();let f=s?[...s]:void 0;if(f?.length&&o.scopes?.includes("openid")){if(!f.includes(d))f.push(d)}let h=s?.length?await Mue(e,t,s):{},p=a?await Dq({ctx:e,opts:t,user:u,client:a,scopes:o.scopes??[],grantType:void 0,sessionId:void 0,resources:s,referenceId:o.referenceId,metadata:pd(a.metadata),perRequestClaims:void 0,resourcePolicyClaims:h}):{},g=(t.disableJwtPlugin?void 0:Io(e.context))?.options;return{payload:{...p,active:!0,iss:g?.jwt?.issuer??e.context.baseURL,aud:pv(f),client_id:o.clientId,azp:o.clientId,sub:u?.id,sid:c,exp:Math.floor(new Date(o.expiresAt).getTime()/1000),iat:Math.floor(new Date(o.createdAt).getTime()/1000),scope:o.scopes?.join(" "),token_type:Iw(o.confirmation),...o.confirmation?{cnf:o.confirmation}:{}},requestedUserInfoClaims:o.requestedUserInfoClaims??[]}}async function Sde(e,t,r,n){let i=await e.context.adapter.findOne({model:"oauthRefreshToken",where:[{field:"token",value:await hd(t.storeTokens,r,"refresh_token")}]});if(!i)throw new st("BAD_REQUEST",{error_description:"token not found",error:"invalid_token"});if(!i.clientId||i.clientId!==n)return{active:!1};if(!i.expiresAt||i.expiresAt<new Date)return{active:!1};if(i.revoked)return{active:!1};let o=i.sessionId??void 0;if(o){let a=await e.context.adapter.findOne({model:"session",where:[{field:"id",value:o}]});if(!a||a.expiresAt<new Date)o=void 0}let s=void 0;if(i.userId)s=await e.context.internalAdapter.findUserById(i?.userId)??void 0;return{active:!0,client_id:n,iss:(t.disableJwtPlugin?void 0:Io(e.context))?.options?.jwt?.issuer??e.context.baseURL,sub:s?.id,sid:o,exp:Math.floor(new Date(i.expiresAt).getTime()/1000),iat:Math.floor(new Date(i.createdAt).getTime()/1000),scope:i.scopes?.join(" "),token_type:Iw(i.confirmation),...i.confirmation?{cnf:i.confirmation}:{}}}function Ov(){return new st("UNAUTHORIZED",{error_description:Jq,error:"invalid_token"},{"WWW-Authenticate":wde})}function Ade(e){return e.status==="BAD_REQUEST"||e.body?.error==="invalid_token"}async function Yq(e,t,r,n){try{return{payload:await bde(e,t,r,n),requestedUserInfoClaims:[]}}catch(i){if(i instanceof st);else if(i instanceof Error)throw i;else throw Error(i)}try{return await Ede(e,t,r,n)}catch(i){if(i instanceof st);else if(i instanceof Error)throw i;else throw Error("Unknown error validating access token")}throw Ov()}async function Iv(e,t,r,n){return(await Yq(e,t,r,n)).payload}async function Tde(e,t,r,n){let i=await Iv(e,t,r,n);if(i.active)return i;throw Ov()}async function Xq(e,t,r,n){let{payload:i,requestedUserInfoClaims:o}=await Yq(e,t,r,n);if(i.active)return{payload:i,requestedUserInfoClaims:o};throw Ov()}async function Rq(e,t,r,n){if(!r.active||!r.sub)return r;let i=r.client_id??r.azp;if(!i)return r;let o=i===n.clientId?n:await Fi(e,t,i);if(!o)return r;let s=await Gl(r.sub,o,t);return{...r,sub:s}}async function Dv(e,t){let{token:r,token_type_hint:n}=e.body;if(n!=="access_token"&&n!=="refresh_token")n=void 0;let{clientId:i,clientSecret:o,preVerified:s,authMethod:a}=cu(await uu(e,t,`${e.context.baseURL}/oauth2/introspect`));if(!i||!o&&!s)throw new st("UNAUTHORIZED",{error_description:"missing required credentials",error:"invalid_client"});if(r&&typeof r==="string")r=bp(r);if(!r?.length)throw new st("BAD_REQUEST",{error_description:"missing a required token for introspection",error:"invalid_request"});let c=await au(e,t,i,o,void 0,s,void 0,a);try{if(n===void 0||n==="access_token")try{return Rq(e,t,await Iv(e,t,r,c.clientId),c)}catch(u){if(u instanceof st){if(n==="access_token")throw u}else if(u instanceof Error)throw u;else throw Error(u)}if(n===void 0||n==="refresh_token")try{return Rq(e,t,await Sde(e,t,(await Dw(t,r)).token,c.clientId),c)}catch(u){if(u instanceof st){if(n==="refresh_token")throw u}else if(u instanceof Error)throw u;else throw Error(u)}throw new st("BAD_REQUEST",{error_description:"token not found",error:"invalid_request"})}catch(u){if(u instanceof st){if(Ade(u))return{active:!1};throw u}else if(u instanceof Error)throw T.error("Introspection error:",u.message,u.stack),new st("INTERNAL_SERVER_ERROR");else throw T.error("Introspection error:",u),new st("INTERNAL_SERVER_ERROR")}}var Zq="1.7.12";function Uv(e){return e?.get("sec-fetch-mode")==="cors"}import*as Pe from"zod";var{defineProperty:Pv,getOwnPropertyDescriptor:vde,getOwnPropertyNames:kde}=Object,Rde=Object.prototype.hasOwnProperty,tB=(e,t)=>{let r={};for(var n in e)Pv(r,n,{get:e[n],enumerable:!0});if(!t)Pv(r,Symbol.toStringTag,{value:"Module"});return r},eB=(e,t,r,n)=>{if(t&&typeof t==="object"||typeof t==="function"){for(var i=kde(t),o=0,s=i.length,a;o<s;o++)if(a=i[o],!Rde.call(e,a)&&a!==r)Pv(e,a,{get:((c)=>t[c]).bind(null,a),enumerable:!(n=vde(t,a))||n.enumerable})}return e},rB=(e,t,r)=>(eB(e,t,"default"),r&&eB(r,t,"default"));function nB(e,t){let r=t.id?{id:t.id}:{};for(let n in e){let i=e[n],o=t[n];if(o===void 0)continue;r[i.fieldName||n]=o}return r}function iB(e,t){if(!t)return null;let r={id:t.id};for(let[n,i]of Object.entries(e))r[n]=t[i.fieldName||n];return r}var Nde=5000,xde=2000,Cde=250,Ode=(e)=>`revoke-unproven-account-access:${e}`;async function Ide(e,t){let r=Date.now()+xde;while(Date.now()<r){let n=await e.context.internalAdapter.findVerificationValue(t);if(!n)return;if(n.expiresAt<=new Date){await e.context.internalAdapter.deleteVerificationByIdentifier(t);return}await new Promise((i)=>setTimeout(i,Cde))}}async function oB(e,t){let r=Ode(t);if(!await e.context.internalAdapter.reserveVerificationValue({identifier:r,value:t,expiresAt:new Date(Date.now()+Nde)}).catch((n)=>{if(n instanceof y&&n.message.includes("requires database-backed verification storage"))return!0;throw n}))return await Ide(e,r),e.context.internalAdapter.findUserById(t);try{let n=await e.context.internalAdapter.findUserById(t);if(!n||n.emailVerified)return n;let i=await e.context.internalAdapter.findAccounts(t);for(let o of i)await e.context.internalAdapter.deleteAccount(o.id);return await e.context.internalAdapter.deleteUserSessions(t),await e.context.internalAdapter.updateUser(t,{emailVerified:!0})}finally{await e.context.internalAdapter.deleteVerificationByIdentifier(r).catch(()=>{})}}import*as zi from"zod";var Dde={string:zi.string,number:zi.number,boolean:zi.boolean,date:zi.date};function sB({fields:e,isClientSide:t}){let r=Object.keys(e).reduce((n,i)=>{let o=e[i];if(!o)return n;if(t&&o.input===!1)return n;let s;if(o.type==="json")s=zi.json();else if(o.type==="string[]"||o.type==="number[]")s=zi.array(o.type==="string[]"?zi.string():zi.number());else if(Array.isArray(o.type))s=zi.any();else s=Dde[o.type]();if(o?.required===!1)s=s.nullish();if(!t&&o?.returned===!1)return n;return{...n,[i]:s}},{});return zi.object(r)}var Ude=tB({buildSyntheticUserOutput:()=>Qh,convertFromDB:()=>iB,convertToDB:()=>nB,createInternalAdapter:()=>kt,getSchema:()=>ND,getSessionDefaultFields:()=>xy,getWithHooks:()=>Wy,mergeSchema:()=>xt,parseAccountInput:()=>kP,parseAccountOutput:()=>Ry,parseAdditionalUserInput:()=>vP,parseAdditionalUserInputFromProviderProfile:()=>Ol,parseInputData:()=>Yu,parseSessionInput:()=>Ny,parseSessionOutput:()=>Di,parseUserInput:()=>Cl,parseUserOutput:()=>Xn,revokeUnprovenAccountAccess:()=>oB,toZodSchema:()=>sB});rB(Ude,RS);async function Pde(e,t,r){let n=await pu.get(),i=n?.query;if(!i)throw new l("BAD_REQUEST",{error_description:"missing oauth query",error:"invalid_request"});let o=new URLSearchParams(i),s=o.get("scope")?.split(" ")??[],a=Up(t),c=Dp(o.get("claims"),a),u=o.get("client_id");if(!u)throw new l("BAD_REQUEST",{error_description:"client_id is required",error:"invalid_client"});let d=e.body.scope?.split(" ");if(d){if(!d.every((re)=>s?.includes(re)))throw new l("BAD_REQUEST",{error_description:"Scope not originally requested",error:"invalid_request"})}let f=e.body.claims,h=f!==void 0?Dp(f,a):c;if(f!==void 0&&!h.every((re)=>c.includes(re)))throw new l("BAD_REQUEST",{error_description:"Claim not originally requested",error:"invalid_request"});if(e.body.accept!==!0)return{redirect:!0,url:ls(o.get("redirect_uri")??"","access_denied","User denied access",o.get("state")??void 0,se(e,t))};let p=await Gr(e),g=yv(o.get("prompt")??"").has("login"),_=g&&bv(p?.session.createdAt,n?.signedQueryIssuedAt);if(g&&!_)return e?.headers?.set("accept","application/json"),e.query=md(o),await r(e);let R=await wv(t,{user:p?.user,session:p?.session,scopes:d??s}),O=await _v(e,u,p?.user.id,R),I=Math.floor(Date.now()/1000),Ne=o.getAll("resource"),k={clientId:u,userId:p?.user.id,scopes:d??s,requestedUserInfoClaims:h,createdAt:new Date(I*1000),updatedAt:new Date(I*1000),resources:Ne.length?Ne:void 0,referenceId:R};if(O?.id?await e.context.adapter.update({model:"oauthConsent",where:[{field:"id",value:O.id}],update:{resources:k.resources,scopes:k.scopes,requestedUserInfoClaims:k.requestedUserInfoClaims,updatedAt:new Date(I*1000)}}):await e.context.adapter.create({model:"oauthConsent",data:{...k,scopes:k.scopes}}),d)o.set("scope",k.scopes.join(" "));if(f!==void 0){let re=Iq(o.get("claims"),h);if(re)o.set("claims",JSON.stringify(re));else o.delete("claims")}e?.headers?.set("accept","application/json");let j=Kl(o,"consent");if(_)j=Kl(j,"login"),j=Ev(j);return e.query=md(j),await r(e,{postLogin:n?.postLoginClearedForSession!==void 0&&n.postLoginClearedForSession===p?.session.id})}async function Lde(e,t){if(e.body.selected===!0)return await Mde(e,t);else if(e.body.created===!0)return await qde(e,t);else if(e.body.postLogin===!0)return await Bde(e,t);else throw new l("BAD_REQUEST",{error_description:"Missing parameters",error:"invalid_request"})}async function Mde(e,t){let r=(await pu.get())?.query;if(!r)throw new l("BAD_REQUEST",{error_description:"missing oauth query",error:"invalid_request"});return e.headers?.set("accept","application/json"),e.query=md(Kl(new URLSearchParams(r),"select_account")),await t(e)}async function qde(e,t){let r=(await pu.get())?.query;if(!r)throw new l("BAD_REQUEST",{error_description:"missing oauth query",error:"invalid_request"});let n=new URLSearchParams(r);return e.headers?.set("accept","application/json"),e.query=md(Kl(n,"create")),await t(e)}async function Bde(e,t){let r=await pu.get(),n=r?.query;if(!n)throw new l("BAD_REQUEST",{error_description:"missing oauth query",error:"invalid_request"});let i=new URLSearchParams(n);e.headers?.set("accept","application/json"),e.query=md(i);let o=await Gr(e);return await t(e,{postLogin:r?.postLoginClearedForSession!==void 0&&r.postLoginClearedForSession===o?.session.id,isPostLoginContinuation:!0})}var jde="http://schemas.openid.net/event/backchannel-logout",$de="logout+jwt",Fde=120,zde=5000;async function Wde(e,t,r,n){return et(e,{options:t,payload:{...n,events:{[jde]:{}}},header:{typ:$de},resolvedKey:r??void 0})}async function Hde(e,t,r){let{sessionId:n,userId:i}=r;if(!i)return null;let o=e.context.logger;try{let s=await $r(e.context.adapter),a=[{field:"sessionId",value:n}],[c,u]=await Promise.all([s.findMany({model:"oauthAccessToken",where:a}),s.findMany({model:"oauthRefreshToken",where:a})]),d=new Set;for(let _ of c)d.add(_.clientId);for(let _ of u)d.add(_.clientId);if(d.size===0)return null;let f=await s.findMany({model:"oauthClient",where:[{field:"clientId",operator:"in",value:Array.from(d)}]}),h=c.filter((_)=>!_.revoked).map((_)=>_.id),p=u.filter((_)=>!_.revoked&&!_.scopes?.includes("offline_access")).map((_)=>_.id),g=t.disableJwtPlugin?[]:f.filter((_)=>Boolean(_.backchannelLogoutUri)&&!_.disabled);return{accessTokenIds:h,refreshTokenIds:p,sessionId:n,targets:(await Promise.all(g.map(async(_)=>{try{return{client:_,sub:await Gl(i,_,t)}}catch(R){return o.warn(`back-channel logout: unable to resolve subject for client ${_.clientId}`,R),null}}))).filter((_)=>_!==null)}}catch(s){return o.error("back-channel logout planning failed",s),null}}async function Vde(e,t){let r=new Date,n=await $r(e.context.adapter),i=await Promise.allSettled([t.accessTokenIds.length>0?n.updateMany({model:"oauthAccessToken",where:[{field:"id",operator:"in",value:t.accessTokenIds}],update:{revoked:r}}):Promise.resolve(),t.refreshTokenIds.length>0?n.updateMany({model:"oauthRefreshToken",where:[{field:"id",operator:"in",value:t.refreshTokenIds}],update:{revoked:r}}):Promise.resolve()]);for(let o of i)if(o.status==="rejected")e.context.logger.error("back-channel logout: token revocation update failed",o.reason);if(t.targets.length>0)await Gde(e,t)}async function Gde(e,t){let r=e.context.logger,n=Io(e.context)?.options,i=n?.jwt?.issuer??e.context.baseURL,o=Math.floor(Date.now()/1000),s=o+Fde,a=n?.jwt?.sign?null:await Ze(e,n);await Promise.allSettled(t.targets.map(async({client:c,sub:u})=>{try{let d=Ui(32,"a-z","A-Z","0-9"),f=await Wde(e,n,a,{iss:i,aud:c.clientId,sub:u,sid:t.sessionId,iat:o,exp:s,jti:d}),h=await fetch(c.backchannelLogoutUri,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"},body:new URLSearchParams({logout_token:f}),signal:AbortSignal.timeout(zde),redirect:"error"});if(h.status!==200&&h.status!==204)r.warn(`back-channel logout to client ${c.clientId} returned ${h.status}`)}catch(d){r.warn(`back-channel logout to client ${c.clientId} failed`,d)}}))}var aB=300,Kde=".oauth_logout_confirmation";function jw(e){return e.replace(/[&<>"']/g,(t)=>{switch(t){case"&":return"&amp;";case"<":return"&lt;";case">":return"&gt;";case'"':return"&quot;";case"'":return"&#39;";default:return t}})}function hu(e){let t=e.request?.headers??e.headers;if(!t||Uv(t))return!1;let r=t.get("accept")??"";return t.get("sec-fetch-mode")==="navigate"||r.includes("text/html")||r.includes("application/xhtml+xml")}function Fv(e,t,r=200){return new Response(`<!doctype html><html><head><meta charset="utf-8"><title>${jw(e)}</title></head><body>${t}</body></html>`,{status:r,headers:{"cache-control":"no-store","content-security-policy":"default-src 'none'; form-action 'self'; base-uri 'none'; frame-ancestors 'none'","content-type":"text/html; charset=utf-8",pragma:"no-cache","x-content-type-options":"nosniff"}})}function SB(e){return`${e.context.baseURL.replace(/\/$/,"")}/oauth2/end-session/confirm`}function Jde(e){try{return new URL(SB(e)).pathname}catch{return"/oauth2/end-session/confirm"}}function cB(e){return Fv("Confirm logout",`<main><h1>Confirm logout</h1><p>Do you want to log out of this account?</p><form method="post" data-oidc-logout-confirmation action="${jw(SB(e))}"><button type="submit" name="action" value="confirm">Confirm logout</button></form></main>`)}function Bv(e){return Fv("Logged out",`<main><p data-oidc-logout-state="logged-out">${e?`Logged out. ${jw(e)}`:"Logged out."}</p></main>`)}function Qde(e,t){return Fv("Logout error",`<main><h1>Logout error</h1><p data-oidc-logout-state="error">${jw(e)}</p></main>`,t)}function fs(e,t,r,n){if(hu(e))return Qde(n,t==="BAD_REQUEST"?400:t==="UNAUTHORIZED"?401:500);throw new st(t,{error:r,error_description:n})}function zv(e){return`${e.context.authCookies.sessionToken.name}${Kde}`}function AB(e,t){return{...e.context.authCookies.sessionToken.attributes,httpOnly:!0,maxAge:t,path:Jde(e),sameSite:"lax"}}async function uB(e,t,r={}){let n={...t?{sessionId:t}:{},...r,expiresAt:Date.now()+aB*1000};await e.setSignedCookie(zv(e),JSON.stringify(n),e.context.secret,AB(e,aB))}async function Yde(e){let t=await e.getSignedCookie(zv(e),e.context.secret);if(typeof t!=="string")return null;try{let r=JSON.parse(t);if(typeof r!=="object"||r===null)return null;let n=r;if(n.sessionId!==void 0&&(typeof n.sessionId!=="string"||n.sessionId.length===0)||n.clientId!==void 0&&(typeof n.clientId!=="string"||n.clientId.length===0)||n.postLogoutRedirectUri!==void 0&&(typeof n.postLogoutRedirectUri!=="string"||n.postLogoutRedirectUri.length===0)||n.state!==void 0&&typeof n.state!=="string"||n.redirectInvalid!==void 0&&typeof n.redirectInvalid!=="boolean"||n.postLogoutRedirectUri!==void 0&&n.clientId===void 0||typeof n.expiresAt!=="number"||!Number.isFinite(n.expiresAt))return null;return{...typeof n.sessionId==="string"?{sessionId:n.sessionId}:{},...typeof n.clientId==="string"?{clientId:n.clientId}:{},...typeof n.postLogoutRedirectUri==="string"?{postLogoutRedirectUri:n.postLogoutRedirectUri}:{},...typeof n.state==="string"?{state:n.state}:{},...typeof n.redirectInvalid==="boolean"?{redirectInvalid:n.redirectInvalid}:{},expiresAt:n.expiresAt}}catch{return null}}function jv(e){e.setCookie(zv(e),"",AB(e,0))}async function TB(e){let t=await e.getSignedCookie(e.context.authCookies.sessionToken.name,e.context.secret);if(typeof t!=="string"||t.length===0)return null;try{let r=await e.context.internalAdapter.findSession(t);return r?{session:r.session}:null}catch(r){throw e.context.logger.error("Failed to read the current logout session",r),new st("INTERNAL_SERVER_ERROR",{error:"server_error",error_description:"Unable to read the current session"})}}async function Xde(e,t){try{return await e.context.adapter.findOne({model:"session",where:[{field:"id",value:t}]})}catch(r){throw e.context.logger.error("Failed to read the hinted logout session",r),new st("INTERNAL_SERVER_ERROR",{error:"server_error",error_description:"Unable to read the hinted session"})}}async function vB(e,t){if(typeof t.token!=="string"||t.token.length===0)throw new st("INTERNAL_SERVER_ERROR",{error:"server_error",error_description:"Unable to complete logout"});try{await e.context.internalAdapter.deleteSession(t.token)}catch(r){throw e.context.logger.error("Failed to delete the logout session",r),new st("INTERNAL_SERVER_ERROR",{error:"server_error",error_description:"Unable to complete logout"})}}async function qw(e,t,r){try{return await Fi(e,t,r)}catch(n){throw e.context.logger.error("Failed to resolve the logout client",n),new st("INTERNAL_SERVER_ERROR",{error:"server_error",error_description:"Unable to resolve the logout client"})}}function kB(e){return(Array.isArray(e)?e:[e]).filter((t)=>typeof t==="string")}function Zde(e){if(typeof e.aud==="string"&&e.aud.length>0)return e.aud;if(typeof e.azp==="string"&&e.azp.length>0)return e.azp;let t=kB(e.aud);return t.length===1?t[0]:null}async function ele(e,t,r,n){if(n)return qw(e,t,n);let i;try{i=W(r)}catch{return null}let o=Zde(i);return o?qw(e,t,o):null}async function tle(e,t,r,n){try{let i;if(t.disableJwtPlugin){if(!n.clientSecret)return null;let o=await Hl(e,t.storeClientSecret,n.clientSecret),{payload:s}=await yr(r,new TextEncoder().encode(o));i=JSON.parse(new TextDecoder().decode(s))}else{let o=Io(e.context).options,{payload:s}=await yr(r,Se(await jl(r,{jwksFetch:o?.jwks?.remoteUrl??`${e.context.baseURL}${o?.jwks?.jwksPath??"/jwks"}`})));i=JSON.parse(new TextDecoder().decode(s))}if(i.iss!==se(e,t))return null;if(!kB(i.aud).includes(n.clientId))return null;if(typeof i.sid!=="string"||i.sid.length===0||typeof i.sub!=="string"||i.sub.length===0)return null;return i}catch{return null}}function Wv(e,t,r){if(!t)return{invalid:!1};if(!e.postLogoutRedirectUris?.includes(t))return{invalid:!0};if(!r)return{uri:t,invalid:!1};try{let n=new URL(t);return n.searchParams.set("state",r),{uri:n.toString(),invalid:!1}}catch{return{invalid:!0}}}function Lv(e,t){if(!t.post_logout_redirect_uri)return{};if(Wv(e,t.post_logout_redirect_uri,t.state).invalid)return{redirectInvalid:!0};return{clientId:e.clientId,postLogoutRedirectUri:t.post_logout_redirect_uri,...t.state!==void 0?{state:t.state}:{}}}async function rle(e,t,r){if(r.redirectInvalid)return{invalid:!0};if(!r.clientId||!r.postLogoutRedirectUri)return{invalid:!1};let n=await qw(e,t,r.clientId);if(!n||n.disabled||!n.enableEndSession)return{invalid:!0};return Wv(n,r.postLogoutRedirectUri,r.state)}async function Lw(e,t,r={}){if(!t){if(hu(e))return await uB(e,void 0,r),cB(e);return fs(e,"BAD_REQUEST","invalid_request","No active session is available for logout")}if(!hu(e))return fs(e,"BAD_REQUEST","invalid_request","User confirmation is required to complete logout");return await uB(e,t.session.id,r),cB(e)}async function nle(e,t){let r=await Yde(e),n=await TB(e);if(!r||r.expiresAt<=Date.now())return fs(e,"BAD_REQUEST","invalid_request","The logout confirmation is invalid or expired");let i=await rle(e,t,r);if(!n){if(jv(e),i.uri)return bi(e,i.uri);return hu(e)?Bv(i.invalid?"The requested post-logout redirect was not registered.":void 0):fs(e,"BAD_REQUEST","invalid_request","No active session is available for logout")}if(r.sessionId&&r.sessionId!==n.session.id)return fs(e,"BAD_REQUEST","invalid_request","The logout confirmation is invalid or expired");if(await vB(e,n.session),Vo(e),jv(e),i.uri)return bi(e,i.uri);return hu(e)?Bv(i.invalid?"The requested post-logout redirect was not registered.":void 0):null}async function ile(e,t){let r=e.query??{},n=e.body??{},i={...r,...n},o=await TB(e);if(i.id_token_hint===void 0){let p={};if(i.client_id){let g=await qw(e,t,i.client_id);if(!g)return fs(e,"BAD_REQUEST","invalid_client","The logout client does not exist");if(g.disabled)return fs(e,"BAD_REQUEST","invalid_client","The logout client is disabled");if(!g.enableEndSession)return fs(e,"UNAUTHORIZED","invalid_client","The client is not allowed to initiate logout");p=Lv(g,i)}return Lw(e,o,p)}let s=await ele(e,t,i.id_token_hint,i.client_id);if(!s){if(o&&hu(e))return Lw(e,o);return fs(e,"BAD_REQUEST","invalid_client","The logout client does not exist")}if(s.disabled)return fs(e,"BAD_REQUEST","invalid_client","The logout client is disabled");if(!s.enableEndSession)return fs(e,"UNAUTHORIZED","invalid_client","The client is not allowed to initiate logout");let a=await tle(e,t,i.id_token_hint,s);if(!a){if(o&&hu(e))return Lw(e,o,i.client_id?Lv(s,i):{});return fs(e,"UNAUTHORIZED","invalid_token","The id_token_hint is invalid")}let c=a.sid,u=await Xde(e,c),d=o?.session.id===c;if(o&&!d)return Lw(e,o,Lv(s,i));let f=Wv(s,i.post_logout_redirect_uri,i.state),h=u??(d?o?.session:null);if(h)await vB(e,h);if(d)Vo(e);if(jv(e),f.uri)return bi(e,f.uri);return hu(e)?Bv(f.invalid?"The requested post-logout redirect was not registered.":void 0):null}async function ole(e,t){return nle(e,t)}function bn(e,t,r){let n=e.context.baseURL,i=!r?.jwt_disabled;return{scopes_supported:r?.scopes_supported,issuer:rj(t?.jwt?.issuer??n),authorization_endpoint:`${n}/oauth2/authorize`,token_endpoint:`${n}/oauth2/token`,jwks_uri:r?.jwt_disabled?void 0:t?.jwks?.remoteUrl??`${n}${t?.jwks?.jwksPath??"/jwks"}`,registration_endpoint:r?.dynamic_client_registration_supported?`${n}/oauth2/register`:void 0,introspection_endpoint:`${n}/oauth2/introspect`,revocation_endpoint:`${n}/oauth2/revoke`,response_types_supported:r?.grant_types_supported&&!r.grant_types_supported.includes("authorization_code")?[]:["code"],response_modes_supported:["query"],grant_types_supported:r?.grant_types_supported??["authorization_code","client_credentials","refresh_token"],token_endpoint_auth_methods_supported:r?.token_endpoint_auth_methods_supported??[...r?.public_client_supported?["none"]:[],"client_secret_basic","client_secret_post","private_key_jwt"],token_endpoint_auth_signing_alg_values_supported:[...od],introspection_endpoint_auth_methods_supported:r?.endpoint_auth_methods_supported??["client_secret_basic","client_secret_post","private_key_jwt"],introspection_endpoint_auth_signing_alg_values_supported:[...od],revocation_endpoint_auth_methods_supported:r?.endpoint_auth_methods_supported??["client_secret_basic","client_secret_post","private_key_jwt"],revocation_endpoint_auth_signing_alg_values_supported:[...od],code_challenge_methods_supported:["S256"],authorization_response_iss_parameter_supported:!0,dpop_signing_alg_values_supported:r?.dpop_signing_alg_values_supported??[...Ot],backchannel_logout_supported:i,backchannel_logout_session_supported:i}}function RB(e,t){let r=t.disableJwtPlugin?void 0:Io(e.context).options,n=xp(t),i=t.allowUnauthenticatedClientRegistration||n.length>0;return{jwtPluginOptions:r,clientDiscoveries:n,authMetadata:bn(e,r,{scopes_supported:t.advertisedMetadata?.scopes_supported??t.scopes,dynamic_client_registration_supported:t.allowDynamicClientRegistration,public_client_supported:i,grant_types_supported:Vl(t),token_endpoint_auth_methods_supported:yw(t,{includeNone:i}),endpoint_auth_methods_supported:yw(t),jwt_disabled:t.disableJwtPlugin,dpop_signing_alg_values_supported:t.dpop?.signingAlgorithms})}}function In(e,t){let{clientDiscoveries:r,authMetadata:n}=RB(e,t);return fv(e,t,"oauth-authorization-server",{...gv(r),...n})}function Lr(e,t){let r=e.context.baseURL,{jwtPluginOptions:n,clientDiscoveries:i,authMetadata:o}=RB(e,t),s={...o,claims_supported:Up(t),claims_parameter_supported:!0,userinfo_endpoint:`${r}/oauth2/userinfo`,subject_types_supported:t.pairwiseSecret?["public","pairwise"]:["public"],acr_values_supported:["0"],id_token_signing_alg_values_supported:(()=>{if(t.disableJwtPlugin)return["HS256"];let a=n?.jwks?.keyPairConfig?.alg??"EdDSA",c=n?.jwks?.keyPairConfigs?.map((u)=>u.alg)??[];return Array.from(new Set([a,...c]))})(),end_session_endpoint:`${r}/oauth2/end-session`,request_parameter_supported:!1,request_uri_parameter_supported:!1,prompt_values_supported:["login","consent","create","select_account","none"]};return fv(e,t,"openid-configuration",{...gv(i),...s})}var sle="public, max-age=15, stale-while-revalidate=15, stale-if-error=86400";function gt(e,t){let r=new Headers(t);if(!r.has("Cache-Control"))r.set("Cache-Control",sle);return r.set("Content-Type","application/json"),new Response(JSON.stringify(e),{status:200,headers:r})}var On=(e,t)=>async(r)=>gt(await e.api.getOAuthServerConfig({request:r,asResponse:!1}),t?.headers),Pn=(e,t)=>async(r)=>gt(await e.api.getOpenIdConfig({request:r,asResponse:!1}),t?.headers);function lu(e,t,r){let{redirectOnError:n,onValidationError:i,errorCodesByField:o,defaultError:s="invalid_request",...a}=t;if(!n)return v(e,{...a,onValidationError:async(p)=>{if(i)await i(p);throw new st("BAD_REQUEST",{...$v(p.issues,o,s)})}},r);let c=n,{body:u,query:d,...f}=a;async function h(p,g,_){if(!_)return{ok:!0};let R=await _.safeParseAsync(p[g]??{});if(R.success)return p[g]=R.data,{ok:!0};if(i)await i({message:R.error.message,issues:R.error.issues});return{ok:!1,response:c({...$v(R.error.issues,o,s),ctx:p})}}return v(e,f,async(p)=>{let g=await h(p,"body",u);if(!g.ok)return g.response;let _=await h(p,"query",d);if(!_.ok)return _.response;return r(p)})}function $v(e,t,r="invalid_request"){let n=e[0];if(!n)return{error:r,error_description:"Invalid request."};let i=n.path?.[0],o=typeof i==="string"?i:void 0,s=o?t?.[o]:void 0,a=n.path?.length?Pe.core.toDotPath(n.path):"";return{error:ale(n,s,r),error_description:ule(n,a)}}function ale(e,t,r){if(typeof t==="string")return t;if(cle(e))return t?.missing??r;if(e.code==="invalid_value")return t?.invalid??r;return r}function cle(e){return e.code==="invalid_type"&&e.message.endsWith("received undefined")}function ule(e,t){if(!t)return e.message;if(e.code==="invalid_type"){if(e.message.endsWith("received undefined"))return`${t} is required`;if(e.message.endsWith("received array"))return`${t} must not appear more than once`;return`${t} must be a ${e.expected??"valid value"}`}if(e.code==="invalid_value"){let r=e.values;if(Array.isArray(r)&&r.length>0)return`${t} must be one of: ${r.join(", ")}`}return`${t}: ${e.message}`}var dle=(e)=>ee(async(t)=>{if(!e.allowPublicClientPrelogin)throw new l("BAD_REQUEST");let r=t.body.oauth_query;if(!await mv(r,t.context.secret))throw new l("UNAUTHORIZED",{error:"invalid_signature"})}),NB={"P-256":"ES256","P-384":"ES384","P-521":"ES512"},lle=["Ed25519"],fle=["d","p","q","dp","dq","qi","oth"];function dB(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}function Lp(e,t){return typeof e[t]==="string"&&e[t].length>0}function xB(e){return typeof e==="string"&&Object.prototype.hasOwnProperty.call(NB,e)}function CB(e){return lle.some((t)=>t===e)}function hle(e){switch(e.kty){case"RSA":return Lp(e,"n")&&Lp(e,"e");case"EC":return xB(e.crv)&&Lp(e,"x")&&Lp(e,"y");case"OKP":return CB(e.crv)&&Lp(e,"x");default:return!1}}function ple(e){if(e.alg===void 0)return!0;if(typeof e.alg!=="string"||!od.some((t)=>t===e.alg))return!1;switch(e.kty){case"RSA":return e.alg.startsWith("RS")||e.alg.startsWith("PS");case"EC":return xB(e.crv)&&NB[e.crv]===e.alg;case"OKP":return CB(e.crv)&&e.alg==="EdDSA";default:return!1}}function OB(e){let t=dB(e)&&Array.isArray(e.keys)?e.keys:void 0;if(!t?.length)return{valid:!1,error:"jwks must be an RFC 7517 JWK Set object with a non-empty keys array"};for(let r of t){if(!dB(r))return{valid:!1,error:"jwks keys must be supported public JWKs with required key parameters"};if(r.kty==="oct"||"k"in r||fle.some((n)=>(n in r)))return{valid:!1,error:"jwks must contain only public asymmetric keys"};if(!hle(r))return{valid:!1,error:"jwks keys must be supported public JWKs with required key parameters"};if(!ple(r))return{valid:!1,error:"jwks key alg must be supported for private_key_jwt and compatible with its key type and signing curve"}}return{valid:!0,jwks:{keys:t}}}function IB(e){let t=OB(e);if(!t.valid)throw new l("BAD_REQUEST",{error:"invalid_client_metadata",error_description:t.error})}var mle=Object.freeze(Object.keys({clientId:!0,clientSecret:!0,clientDiscoveryId:!0,disabled:!0,scopes:!0,clientCredentialsScopes:!0,userId:!0,createdAt:!0,updatedAt:!0,expiresAt:!0,name:!0,uri:!0,icon:!0,contacts:!0,tos:!0,policy:!0,softwareId:!0,softwareVersion:!0,softwareStatement:!0,redirectUris:!0,postLogoutRedirectUris:!0,backchannelLogoutUri:!0,backchannelLogoutSessionRequired:!0,tokenEndpointAuthMethod:!0,grantTypes:!0,responseTypes:!0,applicationType:!0,jwks:!0,jwksUri:!0,requirePKCE:!0,dpopBoundAccessTokens:!0,skipConsent:!0,enableEndSession:!0,subjectType:!0,referenceId:!0,metadata:!0})),gle=["client_id","client_secret","client_secret_expires_at","scope","user_id","client_id_issued_at","client_name","client_uri","logo_uri","contacts","tos_uri","policy_uri","jwks","jwks_uri","software_id","software_version","software_statement","redirect_uris","post_logout_redirect_uris","backchannel_logout_uri","backchannel_logout_session_required","token_endpoint_auth_method","grant_types","response_types","application_type","disabled","skip_consent","enable_end_session","require_pkce","dpop_bound_access_tokens","subject_type","reference_id"],yle=new Set([...mle,...gle,"public","type","resources","client_credentials_scopes"]);function DB(e){if(!e)return;return Object.fromEntries(Object.entries(e).filter(([t])=>!yle.has(t)))}async function Oa(e,t,r,n,i){if(!t)throw new l("UNAUTHORIZED");if(!e.headers)throw new l("BAD_REQUEST");if(n==="configure-client-credentials-scopes"&&!r.clientPrivileges)throw new l("UNAUTHORIZED");if(r.clientPrivileges&&!await r.clientPrivileges({headers:e.headers,action:n,session:t.session,user:t.user,clientId:i}))throw new l("UNAUTHORIZED")}async function mu(e,t,r,n,i){if(!t)throw new l("UNAUTHORIZED");if(!e.headers)throw new l("BAD_REQUEST");if(!r.resourcePrivileges)return;if(!await r.resourcePrivileges({headers:e.headers,action:n,session:t.session,user:t.user,resourceId:i}))throw new l("UNAUTHORIZED")}var Mn=hw({consumeClientAssertion:()=>Sn,isPrivateHostname:()=>Bw,verifyClientAssertion:()=>qB}),lB=new WeakMap,fB=300000,wle=500,_le=5000,hB=65536,ble=/^application\/(?:[-\w.]+\+)?json\s*(?:;|$)/i;function UB(e,t,r,n){if(e.set(t,{jwks:r,fetchedAt:n}),e.size>wle){let i=e.keys().next().value;if(i!==void 0)e.delete(i)}}function PB(e){let t=lB.get(e);if(t)return t;let r=new Map;return lB.set(e,r),r}function LB(e){return`${e.clientDiscoveryId??"managed"}:${e.jwksUri??""}`}var pB=[...od];function Bw(e){return!d1(e)}function Ele(e,t,r){let n=new URL(t);if(n.protocol!=="https:")throw new st("BAD_REQUEST",{error_description:"jwks_uri must use HTTPS",error:"invalid_client"});if(n.username||n.password)throw new st("BAD_REQUEST",{error_description:"jwks_uri must not contain credentials",error:"invalid_client"});if(t.includes("#"))throw new st("BAD_REQUEST",{error_description:"jwks_uri must not include a fragment component",error:"invalid_client"});if(Bw(n.hostname))throw new st("BAD_REQUEST",{error_description:"jwks_uri must not point to a private or reserved address",error:"invalid_client"});if(r&&n.origin===r)return;if(!e.context.isTrustedOrigin(n.href))throw new st("BAD_REQUEST",{error_description:"client jwks_uri is not trusted",error:"invalid_client"})}function Sle(e){try{let t=new URL(e);if(t.protocol!=="https:"&&t.protocol!=="http:")return;return t.origin}catch{return}}async function Ale(e){let t=e.headers.get("content-length");if(t!==null&&Number.isFinite(Number(t))&&Number(t)>hB)throw await e.body?.cancel(),Error("JWKS response exceeds 64 KiB");if(!e.body)return"";let r=e.body.getReader(),n=[],i=0;while(!0){let{done:a,value:c}=await r.read();if(a)break;if(i+=c.byteLength,i>hB)throw await r.cancel(),Error("JWKS response exceeds 64 KiB");n.push(c)}let o=new Uint8Array(i),s=0;for(let a of n)o.set(a,s),s+=a.byteLength;return new TextDecoder().decode(o)}async function MB(e,t=globalThis.fetch){let r=new AbortController,n=setTimeout(()=>r.abort(),_le);try{let i=await t(e,{signal:r.signal,headers:{accept:"application/json"},redirect:"error"});if(i.redirected)throw Error("JWKS fetch redirected");if(i.status!==200)throw Error(`JWKS fetch returned ${i.status}`);let o=i.headers.get("content-type");if(!o||!ble.test(o))throw Error("JWKS response must use a JSON media type");let s=await Ale(i),a;try{a=JSON.parse(s)}catch{return{valid:!1}}let c=OB(a);if(!c.valid)return{valid:!1};return{valid:!0,jwks:c.jwks}}finally{clearTimeout(n)}}function mB(){return new st("BAD_REQUEST",{error_description:"failed to fetch client JWKS",error:"invalid_client"})}async function Tle(e,t,r){if(r.jwks)return JSON.parse(r.jwks);if(!r.jwksUri)throw new st("BAD_REQUEST",{error_description:"client has no JWKS configured",error:"invalid_client"});let n=r.clientDiscoveryId?xp(t).find((u)=>u.id===r.clientDiscoveryId):void 0;if(r.clientDiscoveryId&&!n?.fetchClientMetadataResource)throw new st("BAD_REQUEST",{error_description:"client discovery does not provide a metadata resource transport",error:"invalid_client"});Ele(e,r.jwksUri,r.clientDiscoveryId?Sle(r.clientId):void 0);let i=Date.now(),o=LB(r),s=PB(t),a=s.get(o);if(a&&i-a.fetchedAt<fB)return a.jwks;let c;try{c=await MB(r.jwksUri,n?.fetchClientMetadataResource)}catch{let u=fB*2;if(a&&i-a.fetchedAt<u)return a.jwks;throw mB()}if(!c.valid)throw mB();return UB(s,o,c.jwks,i),c.jwks}async function vle(e,t){if(!t.jwksUri)return null;let r=t.clientDiscoveryId?xp(e).find((n)=>n.id===t.clientDiscoveryId):void 0;if(t.clientDiscoveryId&&!r?.fetchClientMetadataResource)return null;try{let n=await MB(t.jwksUri,r?.fetchClientMetadataResource);if(!n.valid)return null;return UB(PB(e),LB(t),n.jwks,Date.now()),n.jwks}catch{return null}}async function Sn(e,t,r){let{namespace:n,payload:i,expectedAudience:o}=r;if(!(Array.isArray(i.aud)?i.aud:i.aud!=null?[i.aud]:[]).includes(o))throw new st("BAD_REQUEST",{error_description:"client assertion aud does not match the endpoint",error:"invalid_client"});let s=t.assertionMaxLifetime??300,a=Math.floor(Date.now()/1000);if(typeof i.exp!=="number")throw new st("BAD_REQUEST",{error_description:"client assertion must include exp claim",error:"invalid_client"});if(i.exp<=a)throw new st("BAD_REQUEST",{error_description:"client assertion has expired",error:"invalid_client"});if(i.exp-a>s)throw new st("BAD_REQUEST",{error_description:`client assertion exp is too far in the future (max ${s}s)`,error:"invalid_client"});if(typeof i.iat==="number"&&a-i.iat>s)throw new st("BAD_REQUEST",{error_description:`client assertion iat is too far in the past (max ${s}s)`,error:"invalid_client"});if(typeof i.jti!=="string"||i.jti.length===0)throw new st("BAD_REQUEST",{error_description:"client assertion must include jti claim",error:"invalid_client"});let c=await Ce("SHA-256").digest(new TextEncoder().encode(`${n}:${i.jti}`)),u=Sh(new Uint8Array(c).slice(0,24),e.context.options);try{await e.context.adapter.create({model:"oauthClientAssertion",data:{id:u,expiresAt:new Date(i.exp*1000)},forceAllowId:!0})}catch(d){let f=!1;try{f=Boolean(await e.context.adapter.findOne({model:"oauthClientAssertion",where:[{field:"id",value:u}]}))}catch{}if(f)throw new st("BAD_REQUEST",{error_description:"client assertion jti has already been used",error:"invalid_client"});throw d}}async function qB(e,t,r,n,i,o,s){if(n!==sd)throw new st("BAD_REQUEST",{error_description:"unsupported client_assertion_type",error:"invalid_client"});let a;try{a=ue(r)}catch{throw new st("BAD_REQUEST",{error_description:"malformed client assertion: invalid JWT header",error:"invalid_client"})}if(!a.alg||!pB.includes(a.alg))throw new st("BAD_REQUEST",{error_description:`unsupported assertion signing algorithm: ${a.alg}`,error:"invalid_client"});let c;try{c=W(r)}catch{throw new st("BAD_REQUEST",{error_description:"malformed client assertion: invalid JWT payload",error:"invalid_client"})}let u=c.sub??c.iss;if(!u)throw new st("BAD_REQUEST",{error_description:"client assertion must contain sub or iss claim identifying the client",error:"invalid_client"});if(i&&i!==u)throw new st("BAD_REQUEST",{error_description:"client_id in body does not match assertion sub/iss",error:"invalid_client"});let d=await Fi(e,t,u);if(!d)throw new st("BAD_REQUEST",{error_description:"client not found",error:"invalid_client"});if(d.disabled)throw new st("BAD_REQUEST",{error_description:"client is disabled",error:"invalid_client"});if(d.tokenEndpointAuthMethod!=="private_key_jwt")throw new st("BAD_REQUEST",{error_description:"client is not registered for private_key_jwt authentication",error:"invalid_client"});s?.assertClient?.(d);let f=await Tle(e,t,d),h=o??`${e.context.baseURL}/oauth2/token`,p=se(e,t),g=s?.endpointAudienceOnly?[h]:[...new Set([h,p])],_={issuer:u,subject:u,audience:g,algorithms:pB},R;try{({payload:R}=await V(r,Se(f),_))}catch(I){if(I instanceof Error&&/no matching key|no applicable key/i.test(I.message)){let Ne=await vle(t,d);if(Ne)try{({payload:R}=await V(r,Se(Ne),_))}catch{throw new st("UNAUTHORIZED",{error_description:"client assertion signature verification failed",error:"invalid_client"})}else throw new st("UNAUTHORIZED",{error_description:"client assertion signature verification failed",error:"invalid_client"})}else throw new st("UNAUTHORIZED",{error_description:"client assertion signature verification failed",error:"invalid_client"})}let O=(Array.isArray(R.aud)?R.aud:[R.aud]).find((I)=>typeof I==="string"&&g.includes(I));return await Sn(e,t,{namespace:`private_key_jwt:${u}`,payload:R,expectedAudience:O}),{clientId:u,client:d}}function Mv(e,t,r){return new st(e,{error:t,error_description:r},{"WWW-Authenticate":`Bearer error="${t}"`,...sp})}async function kle(e,t,r){let n=e.headers,i;try{i=mq(n?.get("authorization"))}catch{throw Mv("BAD_REQUEST","invalid_request","Malformed initial access token Authorization header")}if(!i||!n)return;if(!t.validateInitialAccessToken)throw Mv("UNAUTHORIZED","invalid_token","Invalid initial access token");let o;try{o=await t.validateInitialAccessToken({initialAccessToken:i,headers:n,clientMetadata:r})}catch(s){if(s instanceof st)throw s;throw new st("INTERNAL_SERVER_ERROR",{error:"server_error",error_description:"Initial access token validation failed"})}if(!o)throw Mv("UNAUTHORIZED","invalid_token","Invalid initial access token");return o}var Rle=["authorization_code"];function BB(e){return[...new Set([...e.clientRegistrationDefaultScopes??e.scopes??[],...e.clientRegistrationAllowedScopes??[]])]}function jB(e){let t=e.grant_types??[...Rle];if(t.length>0)return t;throw new l("BAD_REQUEST",{error:"invalid_client_metadata",error_description:"grant_types must contain at least one grant type"})}function Nle(e,t){if(e.response_types)return e.response_types;return t.includes("authorization_code")?["code"]:void 0}function $B(e,t){let r=new Set(Vl(e)),n=t.filter((i)=>r.has(i));if(n.length===0)throw new l("BAD_REQUEST",{error:"invalid_client_metadata",error_description:`no mutually supported grant_type among ${t.join(", ")}`});return n}function FB(e,t="web"){let r=jB(e);return{...e,token_endpoint_auth_method:e.token_endpoint_auth_method??"client_secret_basic",application_type:e.application_type??(t===null?void 0:t),grant_types:r,response_types:Nle(e,r)}}function xle(e){let t=new URL(e);return t.protocol!=="http:"&&t.protocol!=="https:"&&t.host!==""}function Cle(e){try{let t=new URL(e).protocol;return t!=="http:"&&t!=="https:"}catch{return!1}}function zB(e,t){let r=e.clientRegistrationDefaultApplicationType??"web";if(r!=="infer")return r;return(t.redirect_uris??[]).some((n)=>Cle(n)||WB(n))?"native":"web"}function gd(e){throw new l("BAD_REQUEST",{error:"invalid_redirect_uri",error_description:e})}function Ole(e){let t=/^http:\/\/([^/?#]*)/i.exec(e)?.[1];if(!t)return null;let r=t.slice(t.lastIndexOf("@")+1);if(r.startsWith("[")){let n=r.indexOf("]");return n<0?null:r.slice(0,n+1).toLowerCase()}return(r.split(":")[0]??"").toLowerCase()}function WB(e){let t=Ole(e);return t==="localhost"||t==="127.0.0.1"||t==="[::1]"}function Ile(e,t){let r=new Set([...e.clientRegistrationDefaultResources??[],...e.clientRegistrationAllowedResources??[]]);for(let n of t)if(!r.has(n))throw new l("BAD_REQUEST",{error:"invalid_target",error_description:`requested resource ${n} is not allowed for client registration`})}async function Dle(e,t,r){let n=t.clientRegistrationDefaultResources??[],i=[...new Set([...n,...r])];for(let o of i){let s=await Cw(e,t,o);if(!s)throw new l("BAD_REQUEST",{error:"invalid_target",error_description:`requested resource ${o} does not exist`});if(s.disabled)throw new l("BAD_REQUEST",{error:"invalid_target",error_description:`requested resource ${o} is disabled`})}return i}function Ule(e,t){let r;try{r=new URL(e)}catch{gd(`redirect URI must be an absolute URI: ${e}`)}if(e.includes("#")||r.username.length>0||r.password.length>0)gd(`redirect URI must not include credentials or a fragment: ${e}`);let n=r.protocol==="http:",i=r.protocol==="https:";if(/^localhost\.+$/i.test(r.hostname))gd(`redirect URI localhost must not include trailing dots: ${e}`);let o=ST(r.hostname)||r.hostname==="localhost";if(t==="web"){if(!i||o)gd(`web clients require https redirect URIs on non-loopback hosts: ${e}`);return}if(i){if(o)gd(`native clients must not use https loopback redirect URIs: ${e}`);return}if(n){if(!WB(e))gd(`native clients may use http only on the exact loopback hosts localhost, 127.0.0.1, or [::1]: ${e}`);return}if(!yq(r))gd(`native private-use redirect URI schemes must not use a reserved scheme; they must be an authority-free reverse-domain URI or a custom-scheme URI with a host and a path: ${e}`)}async function Ple(e,t){let r=e.body;if(!t.allowDynamicClientRegistration)throw new l("FORBIDDEN",{error:"access_denied",error_description:"Client registration is disabled"});let n=await Gr(e),i=n?void 0:await kle(e,t,r),o=Boolean(i);if(!(n||o||t.allowUnauthenticatedClientRegistration))throw new l("UNAUTHORIZED",{error_description:"Authentication required for client registration"},{"WWW-Authenticate":"Bearer",...sp});let s=r.grant_types?.length?$B(t,r.grant_types):r.grant_types,a=r.grant_types?.includes("authorization_code")&&!s?.includes("authorization_code"),c={...r,grant_types:s,response_types:a?void 0:r.response_types};if(!n&&!o){if(c.grant_types?.includes("client_credentials"))throw new l("BAD_REQUEST",{error:"invalid_client_metadata",error_description:"client_credentials grant requires authenticated registration"})}let u=Array.isArray(r.resources)?r.resources.filter((h)=>typeof h==="string"&&h.length>0):[];if(n)await Oa(e,n,t,"create");let d=i?.referenceId??(n&&t.clientReference?await t.clientReference({user:n.user,session:n.session}):void 0),f=await KB(e,t,{metadata:c,registrationSource:"dynamic",userId:d?void 0:n?.session.userId,referenceId:d,requestedResources:u});return e.setStatus(201),e.json(f)}async function HB(e,t,r){let n=r?.registrationSource==="clientMetadataDocument",i=FB(e,n?null:r?.registrationSource==="dynamic"?zB(t,e):"web"),o=i.token_endpoint_auth_method??"client_secret_basic";if(!new Set(yw(t,{includeNone:!0})).has(o))throw new l("BAD_REQUEST",{error:"invalid_client_metadata",error_description:`unsupported token_endpoint_auth_method ${o}`});if(i.dpop_bound_access_tokens!==void 0&&typeof i.dpop_bound_access_tokens!=="boolean")throw new l("BAD_REQUEST",{error:"invalid_client_metadata",error_description:"dpop_bound_access_tokens must be a boolean"});let s=i.grant_types??[],{response_types:a,application_type:c}=i;if(c!==void 0&&c!=="web"&&c!=="native")throw new l("BAD_REQUEST",{error:"invalid_client_metadata",error_description:"application_type must be web or native"});if(s.includes("authorization_code")&&(!i.redirect_uris||i.redirect_uris.length===0))throw new l("BAD_REQUEST",{error:"invalid_redirect_uri",error_description:"Redirect URIs are required for authorization_code and implicit grant types"});for(let h of i.redirect_uris??[])Ule(h,c??(n?"native":"web"));if(n)$B(t,s);else{let h=new Set(Vl(t));for(let p of s)if(!h.has(p))throw new l("BAD_REQUEST",{error:"invalid_client_metadata",error_description:`unsupported grant_type ${p}`})}if(s.includes("authorization_code")&&!a?.includes("code"))throw new l("BAD_REQUEST",{error:"invalid_client_metadata",error_description:"When 'authorization_code' grant type is used, 'code' response type must be included"});if(!s.includes("authorization_code")&&a?.includes("code"))throw new l("BAD_REQUEST",{error:"invalid_client_metadata",error_description:"When 'code' response type is used, 'authorization_code' grant type must be included"});if(i.subject_type!==void 0){if(i.subject_type!=="public"&&i.subject_type!=="pairwise")throw new l("BAD_REQUEST",{error:"invalid_client_metadata",error_description:'subject_type must be "public" or "pairwise"'});if(i.subject_type==="pairwise"&&!t.pairwiseSecret)throw new l("BAD_REQUEST",{error:"invalid_client_metadata",error_description:"pairwise subject_type requires server pairwiseSecret configuration"});if(i.subject_type==="pairwise"&&i.redirect_uris?.some(xle))throw new l("BAD_REQUEST",{error:"invalid_client_metadata",error_description:"pairwise clients cannot use custom-scheme redirect URIs that include a host"});if(i.subject_type==="pairwise"&&i.redirect_uris&&i.redirect_uris.length>1){if(new Set(i.redirect_uris.map((h)=>new URL(h).host)).size>1)throw new l("BAD_REQUEST",{error:"invalid_client_metadata",error_description:"pairwise clients with redirect_uris on different hosts require a sector_identifier_uri, which is not yet supported. All redirect_uris must share the same host."})}}let u=i?.scope?.split(" ").filter((h)=>h.length),d=r?.registrationSource==="dynamic"||r?.registrationSource==="clientMetadataDocument",f=d?BB(t):t.scopes;if(f){let h=new Set(f);for(let p of u??[])if(!h?.has(p))throw new l("BAD_REQUEST",{error:"invalid_scope",error_description:`cannot request scope ${p}`})}if(d&&i.require_pkce===!1)throw new l("BAD_REQUEST",{error:"invalid_client_metadata",error_description:"pkce is required for registered clients."});if(i.jwks||i.jwks_uri){if(i.jwks&&i.jwks_uri)throw new l("BAD_REQUEST",{error:"invalid_client_metadata",error_description:"jwks and jwks_uri are mutually exclusive"});if(i.jwks_uri)try{let h=new URL(i.jwks_uri);if(h.protocol!=="https:")throw new l("BAD_REQUEST",{error:"invalid_client_metadata",error_description:"jwks_uri must use HTTPS"});if(h.username||h.password)throw new l("BAD_REQUEST",{error:"invalid_client_metadata",error_description:"jwks_uri must not contain credentials"});if(i.jwks_uri.includes("#"))throw new l("BAD_REQUEST",{error:"invalid_client_metadata",error_description:"jwks_uri must not include a fragment component"});if(Bw(h.hostname))throw new l("BAD_REQUEST",{error:"invalid_client_metadata",error_description:"jwks_uri must not point to a private or reserved address"});if(r?.ctx&&!r.ctx.context.isTrustedOrigin(h.href)){let p=typeof i.client_id==="string"?i.client_id:void 0;if(!(n&&p!==void 0&&URL.canParse(p)&&new URL(p).origin===h.origin))throw new l("BAD_REQUEST",{error:"invalid_client_metadata",error_description:"jwks_uri must belong to a trusted origin or the Client ID Metadata Document origin"})}}catch(h){if(h instanceof l)throw h;throw new l("BAD_REQUEST",{error:"invalid_client_metadata",error_description:"jwks_uri must be a valid URL"})}if(i.jwks)IB(i.jwks)}if(o==="private_key_jwt"&&!i.jwks&&!i.jwks_uri)throw new l("BAD_REQUEST",{error:"invalid_client_metadata",error_description:"private_key_jwt requires either jwks or jwks_uri"});if(i.backchannel_logout_uri!==void 0){if(t.disableJwtPlugin)throw new l("BAD_REQUEST",{error:"invalid_client_metadata",error_description:"backchannel_logout_uri requires the jwt plugin (disableJwtPlugin must be false)"});let h;try{h=new URL(i.backchannel_logout_uri)}catch{throw new l("BAD_REQUEST",{error:"invalid_client_metadata",error_description:"backchannel_logout_uri must be an absolute URL"})}if(i.backchannel_logout_uri.includes("#"))throw new l("BAD_REQUEST",{error:"invalid_client_metadata",error_description:"backchannel_logout_uri must not include a fragment component"});if(h.protocol!=="https:")throw new l("BAD_REQUEST",{error:"invalid_client_metadata",error_description:"backchannel_logout_uri must use https"});if(h.username||h.password)throw new l("BAD_REQUEST",{error:"invalid_client_metadata",error_description:"backchannel_logout_uri must not contain credentials"});if(Bw(h.hostname))throw new l("BAD_REQUEST",{error:"invalid_client_metadata",error_description:"backchannel_logout_uri must not point to a private or reserved address"})}}var gB=Symbol("client-registration-collision");async function VB(e,t,r){let n=r.registrationSource==="dynamic"&&!r.metadata.scope?{...r.metadata,scope:(t.clientRegistrationDefaultScopes??t.scopes)?.join(" ")}:r.metadata,i=FB(n,r.registrationSource==="clientMetadataDocument"?null:r.registrationSource==="dynamic"?zB(t,n):"web"),o=i.token_endpoint_auth_method==="none",s=i.token_endpoint_auth_method==="private_key_jwt",a=lv(t,i.token_endpoint_auth_method);await HB(i,t,{registrationSource:r.registrationSource,ctx:e});let c=r.clientId??t.generateClientId?.()??Ui(32,"a-z","A-Z"),u=o||s||a?void 0:t.generateClientSecret?.()||Ui(32,"a-z","A-Z"),d=u?await bw(e,t,u):void 0,f=r.registrationSource==="dynamic"&&!o&&t.clientRegistrationRequirePKCE===!1,h=i.require_pkce??(f?!1:void 0),p=Math.floor(Date.now()/1000),{resources:g,..._}=r.registrationSource==="dynamic"||r.registrationSource==="clientMetadataDocument"?{...i,scope:BB(t).join(" ")}:i,R=r.registrationSource==="clientMetadataDocument"?void 0:{userId:r.userId,referenceId:r.referenceId},O=QB({..._,redirect_uris:i.redirect_uris??[],disabled:void 0,client_secret_expires_at:d?r.registrationSource==="dynamic"&&t.clientRegistrationClientSecretExpiration?dd(t.clientRegistrationClientSecretExpiration,p):0:void 0,client_id:c,client_secret:d,client_id_issued_at:p,require_pkce:h,user_id:R?.referenceId?void 0:R?.userId,reference_id:R?.referenceId});if(O.clientCredentialsScopes=r.registrationSource==="managed"?r.clientCredentialsScopes??[]:[],O.clientDiscoveryId=r.registrationSource==="clientMetadataDocument"?r.clientDiscoveryId:null,r.registrationSource==="clientMetadataDocument"&&i.application_type===void 0)O.applicationType=null;let I=r.registrationSource==="clientMetadataDocument"?[]:r.requestedResources??[];if(r.registrationSource==="dynamic")Ile(t,I);let Ne=await Dle(e,t,I),k=t.schema?.oauthClient?.modelName??"oauthClient",j=t.schema?.oauthClientResource?.modelName??"oauthClientResource",re=r.registrationSource==="clientMetadataDocument"?r.existingClient:void 0,Oe=r.registrationSource==="clientMetadataDocument"?r.clientDiscoveryId:null,ne=await Co(e.context.adapter,async()=>{let M=await $r(e.context.adapter),F,ce=!1;if(re){let{clientCredentialsScopes:He,disabled:Be,skipConsent:Ke,enableEndSession:Te,...Ve}=O,Je=await M.update({model:k,where:[{field:"clientId",value:c},{field:"clientDiscoveryId",value:Oe}],update:{...Ve,createdAt:re.createdAt,updatedAt:new Date(p*1000)}});if(!Je)throw new l("BAD_REQUEST",{error:"invalid_client",error_description:"client no longer exists"});F=Je}else{try{F=await M.create({model:k,data:{...O,createdAt:new Date(p*1000),updatedAt:new Date(p*1000)}})}catch(He){if(r.registrationSource==="clientMetadataDocument"&&yB(He))throw{[gB]:!0,kind:"oauth-client-row-unique",clientId:c,cause:He};throw He}ce=!0}let de=Ne.length===0?[]:await M.findMany({model:j,where:[{field:"clientId",value:c}]}),pe=new Set(de.map((He)=>He.resourceId)),ae=new Date;for(let He of Ne){if(pe.has(He))continue;try{await M.create({model:j,data:{clientId:c,resourceId:He,createdAt:ae}})}catch(Be){if(r.registrationSource==="clientMetadataDocument"&&yB(Be))throw{[gB]:!0,kind:"oauth-client-resource-link-unique",clientId:c,resourceId:He,cause:Be};throw Be}}return{client:F,created:ce}});return{client:ne.client,clientSecret:u,resources:Ne,created:ne.created}}function GB(e,t){let r=lc({...e.client,clientSecret:e.clientSecret?(t.prefix?.clientSecret??"")+e.clientSecret:void 0});if(e.resources.length>0)r.resources=e.resources;return r}function Lle(e,t){return{...GB(e,t),client_credentials_scopes:[...e.client.clientCredentialsScopes??[]]}}async function KB(e,t,r){return GB(await VB(e,t,r),t)}async function Mle(e,t,r){return Lle(await VB(e,t,r),t)}function yB(e){if(!e||typeof e!=="object")return!1;let t=e,r=String(t.code??t.errno??"");if(["1062","11000","23505","ER_DUP_ENTRY","P2002","SQLITE_CONSTRAINT_UNIQUE"].includes(r))return!0;if(t.name==="MongoServerError"&&t.code===11000)return!0;return typeof t.message==="string"&&/(?:duplicate|unique constraint|unique key)/i.test(t.message)}async function JB(e,t,r){let n=await Gr(e);if(await Oa(e,n,t,"create"),!n)throw new l("UNAUTHORIZED");let i=t.clientReference?await t.clientReference({user:n.user,session:n.session}):void 0,{client_credentials_scopes:o,...s}=e.body,a=r?.admin?xv(o??[]):[];if(Cv(a,jB(s),s.token_endpoint_auth_method,t),a.length>0)await Oa(e,n,t,"configure-client-credentials-scopes");let c=r?.admin?s.resources:void 0;for(let f of new Set(c??[]))await mu(e,n,t,"link",f);let u={metadata:s,registrationSource:"managed",userId:i?void 0:n.session.userId,referenceId:i,clientCredentialsScopes:a,...c?{requestedResources:c}:{}},d=r?.admin?await Mle(e,t,u):await KB(e,t,u);return e.setStatus(201),e.json(d)}function QB(e){let{client_id:t,client_secret:r,client_secret_expires_at:n,scope:i,user_id:o,client_id_issued_at:s,client_name:a,client_uri:c,logo_uri:u,contacts:d,tos_uri:f,policy_uri:h,jwks:p,jwks_uri:g,software_id:_,software_version:R,software_statement:O,redirect_uris:I,post_logout_redirect_uris:Ne,backchannel_logout_uri:k,backchannel_logout_session_required:j,token_endpoint_auth_method:re,grant_types:Oe,response_types:ne,application_type:M,disabled:F,skip_consent:ce,enable_end_session:de,require_pkce:pe,dpop_bound_access_tokens:ae,subject_type:He,reference_id:Be,metadata:Ke}=e,Te=n?new Date(Number(n)*1000):void 0,Ve=s?new Date(s*1000):void 0,Je=i?.split(" "),ft=DB(Ke??{}),qt=ft&&Object.keys(ft).length?JSON.stringify(ft):void 0;return{clientId:t,clientSecret:r,disabled:F,scopes:Je,userId:o,createdAt:Ve,expiresAt:Te,name:a,uri:c,icon:u,contacts:d,tos:f,policy:h,softwareId:_,softwareVersion:R,softwareStatement:O,redirectUris:I,postLogoutRedirectUris:Ne,backchannelLogoutUri:k,backchannelLogoutSessionRequired:j,tokenEndpointAuthMethod:re,grantTypes:Oe,responseTypes:ne,jwks:p?JSON.stringify(p):void 0,jwksUri:g,applicationType:M,skipConsent:ce,enableEndSession:de,requirePKCE:pe,dpopBoundAccessTokens:ae,subjectType:He,referenceId:Be,metadata:qt}}function lc(e){let{clientId:t,clientSecret:r,disabled:n,scopes:i,userId:o,createdAt:s,updatedAt:a,expiresAt:c,name:u,uri:d,icon:f,contacts:h,tos:p,policy:g,softwareId:_,softwareVersion:R,softwareStatement:O,redirectUris:I,postLogoutRedirectUris:Ne,backchannelLogoutUri:k,backchannelLogoutSessionRequired:j,tokenEndpointAuthMethod:re,grantTypes:Oe,responseTypes:ne,applicationType:M,jwks:F,jwksUri:ce,skipConsent:de,enableEndSession:pe,requirePKCE:ae,dpopBoundAccessTokens:He,subjectType:Be,referenceId:Ke,metadata:Te}=e,Ve=c?Math.round(new Date(c).getTime()/1000):void 0,Je=s?Math.round(new Date(s).getTime()/1000):void 0,ft=i?.join(" ");return{...DB(pd(Te)),client_id:t,client_secret:r??void 0,client_secret_expires_at:r?Ve??0:void 0,scope:ft??void 0,user_id:o??void 0,client_id_issued_at:Je??void 0,client_name:u??void 0,client_uri:d??void 0,logo_uri:f??void 0,contacts:h??void 0,tos_uri:p??void 0,policy_uri:g??void 0,jwks:F?JSON.parse(F):void 0,jwks_uri:ce??void 0,software_id:_??void 0,software_version:R??void 0,software_statement:O??void 0,redirect_uris:I??[],post_logout_redirect_uris:Ne??void 0,backchannel_logout_uri:k??void 0,backchannel_logout_session_required:j??void 0,token_endpoint_auth_method:re??void 0,grant_types:Oe??void 0,response_types:ne??void 0,application_type:M??void 0,disabled:n??void 0,skip_consent:de??void 0,enable_end_session:pe??void 0,require_pkce:ae??void 0,dpop_bound_access_tokens:He??void 0,subject_type:Be??void 0,reference_id:Ke??void 0}}async function qle(e,t){let r=await Gr(e);if(await Oa(e,r,t,"read",e.query.client_id),!r)throw new l("UNAUTHORIZED");let n=await Fi(e,t,e.query.client_id);if(!n)throw new l("NOT_FOUND",{error_description:"client not found",error:"not_found"});if(n.userId){if(n.userId!==r.user.id)throw new l("UNAUTHORIZED")}else if(n.referenceId&&t.clientReference){if(n.referenceId!==await t.clientReference(r))throw new l("UNAUTHORIZED")}else throw new l("UNAUTHORIZED");let i=lc(n);return i.client_secret=void 0,i}async function YB(e,t,r){let n=await Fi(e,t,r);if(!n)throw new l("NOT_FOUND",{error_description:"client not found",error:"not_found"});if(n.disabled)throw new l("NOT_FOUND",{error_description:"client not found",error:"not_found"});return lc({clientId:n.clientId,name:n.name,uri:n.uri,contacts:n.contacts,icon:n.icon,tos:n.tos,policy:n.policy})}async function Ble(e,t){let r=await Gr(e);if(await Oa(e,r,t,"list"),!r)throw new l("UNAUTHORIZED");let n=await t.clientReference?.(r);if(n)return await e.context.adapter.findMany({model:"oauthClient",where:[{field:"referenceId",value:n}]}).then((i)=>{if(!i)return null;return i.map((o)=>{let s=lc(o);return s.client_secret=void 0,s})});else if(r.user.id)return await e.context.adapter.findMany({model:"oauthClient",where:[{field:"userId",value:r.user.id}]}).then((i)=>{if(!i)return null;return i.map((o)=>{let s=lc(o);return s.client_secret=void 0,s})});else throw new l("BAD_REQUEST",{message:"either user_id or reference_id must be provided"})}async function jle(e,t){let r=await Gr(e);if(await Oa(e,r,t,"delete",e.body.client_id),!r)throw new l("UNAUTHORIZED");let n=e.body.client_id;Cp(t,n);let i=await Fi(e,t,n);if(!i)throw new l("NOT_FOUND",{error_description:"client not found",error:"not_found"});if(i.userId){if(i.userId!==r.user.id)throw new l("UNAUTHORIZED")}else if(i.referenceId&&t.clientReference){if(i.referenceId!==await t.clientReference(r))throw new l("UNAUTHORIZED")}else throw new l("UNAUTHORIZED");await e.context.adapter.delete({model:"oauthClient",where:[{field:"clientId",value:n}]})}async function XB(e,t,r){let n=await Gr(e);if(await Oa(e,n,t,"update",e.body.client_id),!n)throw new l("UNAUTHORIZED");let i=e.body.client_id;Cp(t,i);let o=await Fi(e,t,i);if(!o)throw new l("NOT_FOUND",{error_description:"client not found",error:"not_found"});let{client_credentials_scopes:s,...a}=e.body.update,c=o.userId?o.userId===n.user.id:o.referenceId&&t.clientReference?o.referenceId===await t.clientReference(n):!1,u=!c&&r?.admin&&s!==void 0&&Object.keys(a).length===0;if(!c&&!u)throw new l("UNAUTHORIZED");if(u)await Oa(e,n,t,"configure-client-credentials-scopes",i);if(Object.keys(a).length===0&&s===void 0){let R=lc(o);if(R.client_secret=void 0,r?.admin)return{...R,client_credentials_scopes:[...o.clientCredentialsScopes??[]]};return R}let d=a.grant_types??o.grantTypes??[],f=a.token_endpoint_auth_method??o.tokenEndpointAuthMethod,h=s===void 0?void 0:xv(s);if(h!==void 0){if(Cv(h,d,f,t),h.length>0&&!u)await Oa(e,n,t,"configure-client-credentials-scopes",i)}await HB({...lc(o),...a},t,{ctx:e});let p={...QB(a)};if(!d.includes("client_credentials")||f==="none")p.clientCredentialsScopes=[];else if(h!==void 0)p.clientCredentialsScopes=h;if(a.token_endpoint_auth_method){if(a.token_endpoint_auth_method==="private_key_jwt")p.clientSecret=null;else if(p.jwks=null,p.jwksUri=null,!p.clientSecret)p.clientSecret=await bw(e,t,t.generateClientSecret?.()||Ui(32,"a-z","A-Z"))}let g=await e.context.adapter.update({model:"oauthClient",where:[{field:"clientId",value:i}],update:{...p,updatedAt:new Date(Math.floor(Date.now()/1000)*1000)}});if(!g)throw new l("INTERNAL_SERVER_ERROR",{error_description:"unable to update client",error:"invalid_client"});let _=lc(g);if(_.client_secret=void 0,r?.admin)return{..._,client_credentials_scopes:[...g.clientCredentialsScopes??[]]};return _}async function $le(e,t){let r=await Gr(e);if(await Oa(e,r,t,"rotate",e.body.client_id),!r)throw new l("UNAUTHORIZED");let n=e.body.client_id;Cp(t,n);let i=await Fi(e,t,n);if(!i)throw new l("NOT_FOUND",{error_description:"client not found",error:"not_found"});if(i.userId){if(i.userId!==r.user.id)throw new l("UNAUTHORIZED")}else if(i.referenceId&&t.clientReference){if(i.referenceId!==await t.clientReference(r))throw new l("UNAUTHORIZED")}else throw new l("UNAUTHORIZED");if(i.tokenEndpointAuthMethod==="none"||!i.clientSecret)throw new l("BAD_REQUEST",{error_description:"secret rotation is only available for clients using client_secret authentication",error:"invalid_client"});let o=t.generateClientSecret?.()||Ui(32,"a-z","A-Z"),s=o?await bw(e,t,o):void 0,a=await e.context.adapter.update({model:"oauthClient",where:[{field:"clientId",value:n}],update:{clientSecret:s,updatedAt:new Date(Math.floor(Date.now()/1000)*1000)}});if(!a)throw new l("INTERNAL_SERVER_ERROR",{error_description:"unable to update client",error:"invalid_client"});return lc({...a,clientSecret:(t.prefix?.clientSecret??"")+o})}async function Fle(e,t){if(!t.allowClientKeyRotation)throw new l("FORBIDDEN",{error:"access_denied",error_description:"Client key rotation is disabled"});let{body:r}=e;IB(r.jwks);let{client:n}=await qB(e,t,r.client_assertion,r.client_assertion_type,void 0,Ow({context:e.context,request:void 0},"/oauth2/client/rotate-keys"),{endpointAudienceOnly:!0,assertClient:(i)=>zle(t,i)});if(!await e.context.adapter.incrementOne({model:"oauthClient",where:[{field:"clientId",value:n.clientId},{field:"jwks",value:n.jwks}],increment:{},set:{jwks:JSON.stringify(r.jwks),updatedAt:new Date}}))throw new l("CONFLICT",{error:"invalid_request",error_description:"client keys changed while rotating; retry with a fresh client assertion"});return{client_id:n.clientId,jwks:r.jwks}}function zle(e,t){if(Cp(e,t.clientId),t.clientDiscoveryId||t.jwksUri||!t.jwks)throw new l("BAD_REQUEST",{error:"invalid_client",error_description:"client keys are not stored inline; rotate them where the client publishes them"})}var ZB=Pe.string().trim().min(1),$w=Pe.array(Pe.string().trim().min(1)).min(1),Wle=(e)=>v("/admin/oauth2/create-client",{method:"POST",body:Pe.object({redirect_uris:Pe.array(_i).min(1).optional(),scope:Pe.string().optional(),client_name:Pe.string().optional(),client_uri:Pe.string().optional(),logo_uri:Pe.string().optional(),contacts:Pe.array(Pe.string().min(1)).min(1).optional(),tos_uri:Pe.string().optional(),policy_uri:Pe.string().optional(),software_id:Pe.string().optional(),software_version:Pe.string().optional(),software_statement:Pe.string().optional(),post_logout_redirect_uris:Pe.array(_i).min(1).optional(),backchannel_logout_uri:_i.optional(),backchannel_logout_session_required:Pe.boolean().optional(),token_endpoint_auth_method:ZB.optional(),application_type:Pe.enum(["web","native"]).optional(),jwks:Pp.optional(),jwks_uri:Pe.string().optional(),grant_types:$w.optional(),client_credentials_scopes:Pe.array(Pe.string().trim().min(1)).optional(),resources:Pe.array(Le).optional(),response_types:Pe.array(Pe.enum(["code"])).optional(),client_secret_expires_at:Pe.union([Pe.string(),Pe.number()]).optional().default(0),skip_consent:Pe.boolean().optional(),enable_end_session:Pe.boolean().optional(),require_pkce:Pe.boolean().optional(),dpop_bound_access_tokens:Pe.boolean().optional(),subject_type:Pe.enum(["public","pairwise"]).optional(),metadata:Pe.record(Pe.string(),Pe.unknown()).optional()}),metadata:{noStore:!0,SERVER_ONLY:!0,openapi:{description:"Register an OAuth2 application",responses:{"201":{description:"OAuth2 application registered successfully",content:{"application/json":{schema:{type:"object",properties:{client_id:{type:"string",description:"Unique identifier for the client"},client_secret:{type:"string",description:"Secret key for the client"},client_secret_expires_at:{type:"number",description:"Time the client secret will expire. If 0, the client secret will never expire."},scope:{type:"string",description:"Space-separated scopes allowed by the client"},client_credentials_scopes:{type:"array",items:{type:"string"},description:"Server-authorized scope ceiling for client_credentials tokens"},user_id:{type:"string",description:"ID of the user who registered the client, null if registered anonymously"},client_id_issued_at:{type:"number",description:"Creation timestamp of this client"},client_name:{type:"string",description:"Name of the OAuth2 application"},client_uri:{type:"string",description:"URI of the OAuth2 application"},logo_uri:{type:"string",description:"Icon URI for the application"},contacts:{type:"array",items:{type:"string"},description:"List representing ways to contact people responsible for this client, typically email addresses"},tos_uri:{type:"string",description:"Client's terms of service uri"},policy_uri:{type:"string",description:"Client's policy uri"},software_id:{type:"string",description:"Unique identifier assigned by the developer to help in the dynamic registration process"},software_version:{type:"string",description:"Version identifier for the software_id"},software_statement:{type:"string",description:"JWT containing metadata values about the client software as claims"},redirect_uris:{type:"array",items:{type:"string",format:"uri"},description:"List of allowed redirect uris"},token_endpoint_auth_method:{type:"string",description:"Requested authentication method for the token endpoint"},grant_types:{type:"array",items:{type:"string"},description:"Grant types the client may use at the token endpoint"},response_types:{type:"array",items:{type:"string",enum:["code"]},description:"Response types the client may use at the authorization endpoint"},application_type:{type:"string",description:"OIDC application type used to classify redirect URI policy",enum:["web","native"]},resources:{type:"array",items:{type:"string",format:"uri"},description:"Final server-owned resources linked to the client"},disabled:{type:"boolean",description:"Whether the client is disabled"},require_pkce:{type:"boolean",description:"Whether the client requires PKCE",default:!0},metadata:{type:"object",additionalProperties:!0,nullable:!0,description:"Additional metadata for the application"}},required:["client_id"]}}}}}}}},async(t)=>JB(t,e,{admin:!0})),Hle=(e)=>v("/oauth2/create-client",{method:"POST",use:[K],body:Pe.object({redirect_uris:Pe.array(_i).min(1).optional(),scope:Pe.string().optional(),client_name:Pe.string().optional(),client_uri:Pe.string().optional(),logo_uri:Pe.string().optional(),contacts:Pe.array(Pe.string().min(1)).min(1).optional(),tos_uri:Pe.string().optional(),policy_uri:Pe.string().optional(),software_id:Pe.string().optional(),software_version:Pe.string().optional(),software_statement:Pe.string().optional(),post_logout_redirect_uris:Pe.array(_i).min(1).optional(),backchannel_logout_uri:_i.optional(),backchannel_logout_session_required:Pe.boolean().optional(),token_endpoint_auth_method:ZB.optional(),application_type:Pe.enum(["web","native"]).optional(),jwks:Pp.optional(),jwks_uri:Pe.string().optional(),grant_types:$w.optional(),response_types:Pe.array(Pe.enum(["code"])).optional(),dpop_bound_access_tokens:Pe.boolean().optional()}),metadata:{noStore:!0,openapi:{description:"Register an OAuth2 application",responses:{"201":{description:"OAuth2 application registered successfully",content:{"application/json":{schema:{type:"object",properties:{client_id:{type:"string",description:"Unique identifier for the client"},client_secret:{type:"string",description:"Secret key for the client"},client_secret_expires_at:{type:"number",description:"Time the client secret will expire. If 0, the client secret will never expire."},scope:{type:"string",description:"Space-separated scopes allowed by the client"},user_id:{type:"string",description:"ID of the user who registered the client, null if registered anonymously"},client_id_issued_at:{type:"number",description:"Creation timestamp of this client"},client_name:{type:"string",description:"Name of the OAuth2 application"},client_uri:{type:"string",description:"URI of the OAuth2 application"},logo_uri:{type:"string",description:"Icon URI for the application"},contacts:{type:"array",items:{type:"string"},description:"List representing ways to contact people responsible for this client, typically email addresses"},tos_uri:{type:"string",description:"Client's terms of service uri"},policy_uri:{type:"string",description:"Client's policy uri"},software_id:{type:"string",description:"Unique identifier assigned by the developer to help in the dynamic registration process"},software_version:{type:"string",description:"Version identifier for the software_id"},software_statement:{type:"string",description:"JWT containing metadata values about the client software as claims"},redirect_uris:{type:"array",items:{type:"string",format:"uri"},description:"List of allowed redirect uris"},token_endpoint_auth_method:{type:"string",description:"Requested authentication method for the token endpoint"},grant_types:{type:"array",items:{type:"string"},description:"Grant types the client may use at the token endpoint"},response_types:{type:"array",items:{type:"string",enum:["code"]},description:"Response types the client may use at the authorization endpoint"},application_type:{type:"string",description:"OIDC application type used to classify redirect URI policy",enum:["web","native"]},resources:{type:"array",items:{type:"string",format:"uri"},description:"Final server-owned resources linked to the client"},disabled:{type:"boolean",description:"Whether the client is disabled"},metadata:{type:"object",additionalProperties:!0,nullable:!0,description:"Additional metadata for the application"}},required:["client_id"]}}}}}}}},async(t)=>JB(t,e)),Vle=(e)=>v("/oauth2/get-client",{method:"GET",use:[K],query:Pe.object({client_id:Pe.string()}),metadata:{openapi:{description:"Get OAuth2 formatted client details"}}},async(t)=>qle(t,e)),Gle=(e)=>v("/oauth2/public-client",{method:"GET",use:[K],query:Pe.object({client_id:Pe.string()}),metadata:{openapi:{description:"Gets publicly available client fields"}}},async(t)=>{let r=t.query.client_id;return YB(t,e,r)}),Kle=(e)=>v("/oauth2/public-client-prelogin",{method:"POST",use:[dle(e)],body:Pe.object({client_id:Pe.string(),oauth_query:Pe.string().optional()}),metadata:{openapi:{description:"Gets publicly available client fields (prior to login)"}}},async(t)=>{let r=t.body.client_id;return YB(t,e,r)}),Jle=(e)=>v("/oauth2/get-clients",{method:"GET",use:[K],metadata:{openapi:{description:"Get OAuth2 formatted client details for a user or organization"}}},async(t)=>Ble(t,e)),Qle=(e)=>v("/admin/oauth2/update-client",{method:"PATCH",body:Pe.object({client_id:Pe.string(),update:Pe.object({redirect_uris:Pe.array(_i).min(1).optional(),scope:Pe.string().optional(),client_name:Pe.string().optional(),client_uri:Pe.string().optional(),logo_uri:Pe.string().optional(),contacts:Pe.array(Pe.string().min(1)).min(1).optional(),tos_uri:Pe.string().optional(),policy_uri:Pe.string().optional(),software_id:Pe.string().optional(),software_version:Pe.string().optional(),software_statement:Pe.string().optional(),post_logout_redirect_uris:Pe.array(_i).min(1).optional(),backchannel_logout_uri:_i.optional(),backchannel_logout_session_required:Pe.boolean().optional(),application_type:Pe.enum(["web","native"]).optional(),grant_types:$w.optional(),client_credentials_scopes:Pe.array(Pe.string().trim().min(1)).optional(),response_types:Pe.array(Pe.enum(["code"])).optional(),client_secret_expires_at:Pe.union([Pe.string(),Pe.number()]).optional(),skip_consent:Pe.boolean().optional(),enable_end_session:Pe.boolean().optional(),disabled:Pe.boolean().optional(),dpop_bound_access_tokens:Pe.boolean().optional(),metadata:Pe.record(Pe.string(),Pe.unknown()).optional()})}),metadata:{SERVER_ONLY:!0,openapi:{description:"Updates OAuth2 formatted client details."}}},async(t)=>XB(t,e,{admin:!0})),Yle=(e)=>v("/oauth2/update-client",{method:"POST",use:[K],body:Pe.object({client_id:Pe.string(),update:Pe.object({redirect_uris:Pe.array(_i).min(1).optional(),scope:Pe.string().optional(),client_name:Pe.string().optional(),client_uri:Pe.string().optional(),logo_uri:Pe.string().optional(),contacts:Pe.array(Pe.string().min(1)).min(1).optional(),tos_uri:Pe.string().optional(),policy_uri:Pe.string().optional(),software_id:Pe.string().optional(),software_version:Pe.string().optional(),software_statement:Pe.string().optional(),post_logout_redirect_uris:Pe.array(_i).min(1).optional(),backchannel_logout_uri:_i.optional(),backchannel_logout_session_required:Pe.boolean().optional(),application_type:Pe.enum(["web","native"]).optional(),grant_types:$w.optional(),response_types:Pe.array(Pe.enum(["code"])).optional()})}),metadata:{openapi:{description:"Updates OAuth2 formatted client details."}}},async(t)=>XB(t,e)),Xle=(e)=>v("/oauth2/client/rotate-secret",{method:"POST",use:[K],body:Pe.object({client_id:Pe.string()}),metadata:{noStore:!0,openapi:{description:"Rotates a confidential client's secret"}}},async(t)=>$le(t,e)),Zle=(e)=>lu("/oauth2/client/rotate-keys",{method:"POST",body:Pe.object({client_assertion:Pe.string(),client_assertion_type:Pe.string(),jwks:Pp}),errorCodesByField:{client_assertion:"invalid_client",client_assertion_type:"invalid_client",jwks:"invalid_client_metadata"},metadata:{noStore:!0,openapi:{description:"Replaces the signing keys of a private_key_jwt client. The request is authenticated by a client assertion signed with one of the client's current keys and addressed to this endpoint. Keys left out of the new set stop verifying at once."}}},async(t)=>Fle(t,e)),efe=(e)=>v("/oauth2/delete-client",{method:"POST",use:[K],body:Pe.object({client_id:Pe.string()}),metadata:{openapi:{description:"Deletes an oauth client"}}},async(t)=>jle(t,e));async function Hv(e,t,r){return await e.context.adapter.findOne({model:"oauthConsent",where:[{field:"id",value:r}]})}async function tfe(e,t){let r=await Gr(e);if(!r)throw new l("UNAUTHORIZED");let{id:n}=e.query;if(!n)throw new l("NOT_FOUND",{error_description:"missing id parameter",error:"not_found"});let i=await Hv(e,t,n);if(!i)throw new l("NOT_FOUND",{error_description:"no consent",error:"not_found"});if(i.userId!==r.user.id)throw new l("UNAUTHORIZED");return i}async function rfe(e,t){let r=await Gr(e);if(!r)throw new l("UNAUTHORIZED");return await e.context.adapter.findMany({model:"oauthConsent",where:[{field:"userId",value:r.user.id}]})}async function nfe(e,t){let r=await Gr(e);if(!r)throw new l("UNAUTHORIZED");let{id:n}=e.body;if(!n)throw new l("NOT_FOUND",{error_description:"missing id parameter",error:"not_found"});let i=await Hv(e,t,n);if(!i)throw new l("NOT_FOUND",{error_description:"no consent",error:"not_found"});if(i.userId!==r.user.id)throw new l("UNAUTHORIZED");await e.context.adapter.delete({model:"oauthConsent",where:[{field:"id",value:n}]})}async function ife(e,t){let r=await Gr(e);if(!r)throw new l("UNAUTHORIZED");let{id:n}=e.body;if(!n)throw new l("NOT_FOUND",{error_description:"missing id parameter",error:"not_found"});let i=await Hv(e,t,n);if(!i)throw new l("NOT_FOUND",{error_description:"no consent",error:"not_found"});if(i.userId!==r.user.id)throw new l("UNAUTHORIZED");let o=await Fi(e,t,i.clientId);if(!o)throw new l("NOT_FOUND",{error_description:"client not found",error:"not_found"});let s=o?.scopes??t.scopes??[],a=e.body.update,c=a.scopes;if(c&&!c.every((d)=>s?.includes(d)))throw new l("BAD_REQUEST",{error_description:`unable to provide scopes to ${o?.referenceId??o?.userId}`,error:"invalid_request"});let u=Math.floor(Date.now()/1000);return await e.context.adapter.update({model:"oauthConsent",where:[{field:"id",value:n}],update:{...a,updatedAt:new Date(u*1000)}})}var ofe=(e)=>v("/oauth2/get-consent",{method:"GET",query:Pe.object({id:Pe.string()}),use:[K],metadata:{openapi:{description:"Gets details of a specific OAuth2 consent for a user"}}},async(t)=>tfe(t,e)),sfe=(e)=>v("/oauth2/get-consents",{method:"GET",use:[K],metadata:{openapi:{description:"Gets all available OAuth2 consents for a user"}}},async(t)=>rfe(t,e)),afe=(e)=>v("/oauth2/update-consent",{method:"POST",use:[K],body:Pe.object({id:Pe.string(),update:Pe.object({scopes:Pe.array(Pe.string())})}),metadata:{openapi:{description:"Updates consent granted to a client."}}},async(t)=>ife(t,e)),cfe=(e)=>v("/oauth2/delete-consent",{method:"POST",use:[K],body:Pe.object({id:Pe.string()}),metadata:{openapi:{description:"Deletes consent granted to a client"}}},async(t)=>nfe(t,e)),fc=(e)=>e.schema?.oauthResource?.modelName??"oauthResource",ej=(e)=>e.schema?.oauthClientResource?.modelName??"oauthClientResource",ufe=(e)=>e.schema?.oauthClient?.modelName??"oauthClient";function wd(e){try{return decodeURIComponent(e)}catch{return e}}function dfe(e,t){return{identifier:e.identifier,name:e.name??e.identifier,accessTokenTtl:e.accessTokenTtl??null,refreshTokenTtl:e.refreshTokenTtl??null,signingAlgorithm:e.signingAlgorithm??null,signingKeyId:e.signingKeyId??null,allowedScopes:e.allowedScopes??null,customClaims:e.customClaims??null,dpopBoundAccessTokensRequired:e.dpopBoundAccessTokensRequired??!1,disabled:e.disabled??!1,policyVersion:1,metadata:e.metadata??null,createdAt:t,updatedAt:t}}async function lfe(e,t){await mu(e,await Gr(e),t,"create");let r=e.body;if(!r?.identifier)throw new l("BAD_REQUEST",{error:"invalid_request",error_description:"identifier is required"});await Pq(t,r.identifier);let n=new Date,i;try{i=await e.context.adapter.create({model:fc(t),data:dfe(r,n)})}catch(o){let s=o instanceof Error?o.message:String(o);if(/unique|duplicate|UNIQUE/i.test(s))throw new l("BAD_REQUEST",{error:"invalid_request",error_description:`resource ${r.identifier} already exists`});throw o}if(!i)throw new l("BAD_REQUEST",{error:"invalid_request",error_description:`resource ${r.identifier} could not be created`});return xw(i.identifier),e.json(i,{status:201})}async function ffe(e,t){await mu(e,await Gr(e),t,"list");let r=await e.context.adapter.findMany({model:fc(t)});return e.json(r??[])}async function hfe(e,t){let r=wd(e.params.identifier);await mu(e,await Gr(e),t,"read",r);let n=await e.context.adapter.findOne({model:fc(t),where:[{field:"identifier",value:r}]});if(!n)throw new l("NOT_FOUND",{error:"not_found",error_description:`resource ${r} not found`});return e.json(n)}async function pfe(e,t){let r=wd(e.params.identifier);if(await mu(e,await Gr(e),t,"update",r),!await e.context.adapter.findOne({model:fc(t),where:[{field:"identifier",value:r}]}))throw new l("NOT_FOUND",{error:"not_found",error_description:`resource ${r} not found`});let n={updatedAt:new Date};for(let o of["name","accessTokenTtl","refreshTokenTtl","signingAlgorithm","signingKeyId","allowedScopes","customClaims","dpopBoundAccessTokensRequired","disabled","metadata"])if(Object.prototype.hasOwnProperty.call(e.body,o))n[o]=e.body[o];await e.context.adapter.update({model:fc(t),where:[{field:"identifier",value:r}],update:n}),xw(r);let i=await e.context.adapter.findOne({model:fc(t),where:[{field:"identifier",value:r}]});if(!i)throw new l("NOT_FOUND",{error:"not_found",error_description:`resource ${r} not found`});return e.json(i)}async function mfe(e,t){let r=wd(e.params.identifier);if(await mu(e,await Gr(e),t,"delete",r),!await e.context.adapter.findOne({model:fc(t),where:[{field:"identifier",value:r}]}))throw new l("NOT_FOUND",{error:"not_found",error_description:`resource ${r} not found`});return await e.context.adapter.delete({model:fc(t),where:[{field:"identifier",value:r}]}),xw(r),e.json({deleted:!0})}async function gfe(e,t){let r=await Gr(e),n=wd(e.params.identifier),i=wd(e.params.client_id);if(await mu(e,r,t,"link",n),!await e.context.adapter.findOne({model:fc(t),where:[{field:"identifier",value:n}]}))throw new l("NOT_FOUND",{error:"not_found",error_description:`resource ${n} not found`});if(!await e.context.adapter.findOne({model:ufe(t),where:[{field:"clientId",value:i}]}))throw new l("NOT_FOUND",{error:"not_found",error_description:`client ${i} not found`});try{await e.context.adapter.create({model:ej(t),data:{clientId:i,resourceId:n,createdAt:new Date}})}catch(o){let s=o instanceof Error?o.message:String(o);if(/unique|duplicate|UNIQUE/i.test(s))return e.json({linked:!0,alreadyLinked:!0});throw o}return e.json({linked:!0})}async function yfe(e,t){let r=await Gr(e),n=wd(e.params.identifier),i=wd(e.params.client_id);return await mu(e,r,t,"unlink",n),await e.context.adapter.deleteMany({model:ej(t),where:[{field:"clientId",value:i},{field:"resourceId",value:n}]}),e.json({unlinked:!0})}var tj=Pe.object({identifier:Pe.string().min(1).optional(),name:Pe.string().optional(),accessTokenTtl:Pe.number().int().positive().nullable().optional(),refreshTokenTtl:Pe.number().int().positive().nullable().optional(),signingAlgorithm:Pe.enum(Rw).nullable().optional(),signingKeyId:Pe.string().nullable().optional(),allowedScopes:Pe.array(Pe.string()).nullable().optional(),customClaims:Pe.record(Pe.string(),Pe.unknown()).nullable().optional(),dpopBoundAccessTokensRequired:Pe.boolean().optional(),disabled:Pe.boolean().optional(),metadata:Pe.record(Pe.string(),Pe.unknown()).nullable().optional()}),wfe=(e)=>v("/admin/oauth2/resources",{method:"POST",body:tj.required({identifier:!0}),metadata:{SERVER_ONLY:!0}},async(t)=>lfe(t,e)),_fe=(e)=>v("/admin/oauth2/resources",{method:"GET",metadata:{SERVER_ONLY:!0}},async(t)=>ffe(t,e)),bfe=(e)=>v("/admin/oauth2/resources/:identifier",{method:"GET",metadata:{SERVER_ONLY:!0}},async(t)=>hfe(t,e)),Efe=(e)=>v("/admin/oauth2/resources/:identifier",{method:"PATCH",body:tj,metadata:{SERVER_ONLY:!0}},async(t)=>pfe(t,e)),Sfe=(e)=>v("/admin/oauth2/resources/:identifier",{method:"DELETE",metadata:{SERVER_ONLY:!0}},async(t)=>mfe(t,e)),Afe=(e)=>v("/admin/oauth2/resources/:identifier/clients/:client_id",{method:"POST",metadata:{SERVER_ONLY:!0}},async(t)=>gfe(t,e)),Tfe=(e)=>v("/admin/oauth2/resources/:identifier/clients/:client_id",{method:"DELETE",metadata:{SERVER_ONLY:!0}},async(t)=>yfe(t,e));async function vfe(e,t,r){if(t.disableJwtPlugin)throw new st("BAD_REQUEST",{error_description:"JWT access tokens are disabled",error:"invalid_request"});let n=Io(e.context),i=n.options,o;try{o=(await V(r,Se(await jl(r,{jwksFetch:i?.jwks?.remoteUrl?i.jwks.remoteUrl:async()=>(await n.endpoints.getJwks(e))?.response,jwksCacheKey:n})),{issuer:i?.jwt?.issuer??e.context.baseURL})).payload}catch(a){if(a instanceof tt||a instanceof H)return null;if(a instanceof TypeError||ww(a))throw new st("BAD_REQUEST",{error_description:"invalid JWT signature",error:"invalid_request"});throw a}let s=`${e.context.baseURL}/oauth2/userinfo`;if(!o.azp||!await Nw(e,t,o.aud,[s]))return null;throw new st("BAD_REQUEST",{error_description:"JWT access tokens are self-contained and cannot be revoked server-side",error:"unsupported_token_type"})}async function kfe(e,t,r,n){let i=r;if(t.prefix?.opaqueAccessToken)if(i.startsWith(t.prefix.opaqueAccessToken))i=i.replace(t.prefix.opaqueAccessToken,"");else throw new st("BAD_REQUEST",{error_description:"opaque access token not found",error:"invalid_request"});let o=await e.context.adapter.findOne({model:"oauthAccessToken",where:[{field:"token",value:await hd(t.storeTokens,i,"access_token")}]});if(!o)throw new st("BAD_REQUEST",{error_description:"opaque access token not found",error:"invalid_request"});if(!o.clientId||o.clientId!==n)return null;o.id?await e.context.adapter.delete({model:"oauthAccessToken",where:[{field:"id",value:o.id}]}):await e.context.adapter.delete({model:"oauthAccessToken",where:[{field:"token",value:o.token}]})}async function Rfe(e,t,r,n){let i=await e.context.adapter.findOne({model:"oauthRefreshToken",where:[{field:"token",value:await hd(t.storeTokens,r,"refresh_token")}]});if(!i)throw new st("BAD_REQUEST",{error_description:"token not found",error:"invalid_request"});if(i.revoked)throw await Uw(e,n,i.userId),new st("BAD_REQUEST",{error_description:"refresh token revoked",error:"invalid_request"});if(!i.clientId||i.clientId!==n)return null;let o=Math.floor(Date.now()/1000);if(!await e.context.adapter.incrementOne({model:"oauthRefreshToken",where:[{field:"id",value:i.id},{field:"revoked",operator:"eq",value:null}],increment:{},set:{revoked:new Date(o*1000)}}))throw await Uw(e,n,i.userId),new st("BAD_REQUEST",{error_description:"refresh token revoked",error:"invalid_request"});await e.context.adapter.deleteMany({model:"oauthAccessToken",where:[{field:"refreshId",value:i.id}]})}async function Nfe(e,t,r,n){try{return await vfe(e,t,n)}catch(i){if(i instanceof st){if(i.body?.error==="unsupported_token_type")throw i}else if(i instanceof Error)throw i;else throw Error(i)}try{return await kfe(e,t,n,r)}catch(i){if(i instanceof st);else if(i instanceof Error)throw i;else throw Error("Unknown error validating access token")}throw new st("BAD_REQUEST",{error_description:"Invalid access token",error:"invalid_request"})}async function xfe(e,t){let{token:r,token_type_hint:n}=e.body;if(n!=="access_token"&&n!=="refresh_token")n=void 0;let{clientId:i,clientSecret:o,preVerified:s,authMethod:a}=cu(await uu(e,t,`${e.context.baseURL}/oauth2/revoke`));if(!i)throw new st("UNAUTHORIZED",{error_description:"missing required credentials",error:"invalid_client"});if(typeof r==="string")r=bp(r);if(!r?.length)throw new st("BAD_REQUEST",{error_description:"missing a required token for introspection",error:"invalid_request"});let c=await au(e,t,i,o,void 0,s,void 0,a);try{if(n===void 0||n==="access_token")try{return await Nfe(e,t,c.clientId,r)}catch(u){if(u instanceof st){if(n==="access_token"||u.body?.error==="unsupported_token_type")throw u}else if(u instanceof Error)throw u;else throw Error(u)}if(n===void 0||n==="refresh_token")try{return await Rfe(e,t,(await Dw(t,r)).token,c.clientId)}catch(u){if(u instanceof st){if(n==="refresh_token")throw u}else if(u instanceof Error)throw u;else throw Error(u)}throw new st("BAD_REQUEST",{error_description:"token not found",error:"invalid_request"})}catch(u){if(u instanceof st){if(u.body?.error==="unsupported_token_type")throw u;if(u.name==="BAD_REQUEST")return null;throw u}else if(u instanceof Error)throw T.error("Introspection error:",u.message,u.stack),new st("INTERNAL_SERVER_ERROR");else throw T.error("Introspection error:",u),new st("INTERNAL_SERVER_ERROR")}}var Cfe={oauthClient:{modelName:"oauthClient",fields:{clientId:{type:"string",unique:!0,required:!0},clientSecret:{type:"string",required:!1},clientDiscoveryId:{type:"string",required:!1},disabled:{type:"boolean",defaultValue:!1,required:!1},skipConsent:{type:"boolean",required:!1},enableEndSession:{type:"boolean",required:!1},subjectType:{type:"string",required:!1},scopes:{type:"string[]",required:!1},clientCredentialsScopes:{type:"string[]",required:!1,defaultValue:[]},userId:{type:"string",required:!1,references:{model:"user",field:"id"},index:!0},createdAt:{type:"date",required:!1},updatedAt:{type:"date",required:!1},name:{type:"string",required:!1},uri:{type:"string",required:!1},icon:{type:"string",required:!1},contacts:{type:"string[]",required:!1},tos:{type:"string",required:!1},policy:{type:"string",required:!1},softwareId:{type:"string",required:!1},softwareVersion:{type:"string",required:!1},softwareStatement:{type:"string",required:!1},redirectUris:{type:"string[]",required:!0},postLogoutRedirectUris:{type:"string[]",required:!1},backchannelLogoutUri:{type:"string",required:!1},backchannelLogoutSessionRequired:{type:"boolean",required:!1},tokenEndpointAuthMethod:{type:"string",required:!1},applicationType:{type:"string",required:!1},jwks:{type:"string",required:!1},jwksUri:{type:"string",required:!1},grantTypes:{type:"string[]",required:!1},responseTypes:{type:"string[]",required:!1},requirePKCE:{type:"boolean",required:!1},dpopBoundAccessTokens:{type:"boolean",required:!1,defaultValue:!1},referenceId:{type:"string",required:!1},metadata:{type:"json",required:!1}}},oauthResource:{modelName:"oauthResource",fields:{identifier:{type:"string",required:!0,unique:!0},name:{type:"string",required:!0},accessTokenTtl:{type:"number",required:!1},refreshTokenTtl:{type:"number",required:!1},signingAlgorithm:{type:"string",required:!1},signingKeyId:{type:"string",required:!1},allowedScopes:{type:"string[]",required:!1},customClaims:{type:"json",required:!1},dpopBoundAccessTokensRequired:{type:"boolean",required:!1,defaultValue:!1},disabled:{type:"boolean",required:!1,defaultValue:!1},createdAt:{type:"date",required:!1},updatedAt:{type:"date",required:!1},policyVersion:{type:"number",required:!1,defaultValue:1},metadata:{type:"json",required:!1}}},oauthClientResource:{modelName:"oauthClientResource",fields:{clientId:{type:"string",required:!0,references:{model:"oauthClient",field:"clientId",onDelete:"cascade"},index:!0},resourceId:{type:"string",required:!0,references:{model:"oauthResource",field:"identifier",onDelete:"cascade"},index:!0},metadata:{type:"json",required:!1},createdAt:{type:"date",required:!1}},indexes:[{fields:["clientId","resourceId"],unique:!0}]},oauthRefreshToken:{fields:{token:{type:"string",required:!0,unique:!0},clientId:{type:"string",required:!0,references:{model:"oauthClient",field:"clientId"},index:!0},sessionId:{type:"string",required:!1,references:{model:"session",field:"id",onDelete:"set null"},index:!0},userId:{type:"string",required:!0,references:{model:"user",field:"id"},index:!0},referenceId:{type:"string",required:!1},authorizationCodeId:{type:"string",required:!1,index:!0},resources:{type:"string[]",required:!1},requestedUserInfoClaims:{type:"string[]",required:!1},expiresAt:{type:"date"},createdAt:{type:"date"},revoked:{type:"date",required:!1},rotatedAt:{type:"date",required:!1},rotationReplayResponse:{type:"string",required:!1},rotationReplayExpiresAt:{type:"date",required:!1},authTime:{type:"date",required:!1},confirmation:{type:"json",required:!1},scopes:{type:"string[]",required:!0}}},oauthAccessToken:{modelName:"oauthAccessToken",fields:{token:{type:"string",unique:!0},clientId:{type:"string",required:!0,references:{model:"oauthClient",field:"clientId"},index:!0},sessionId:{type:"string",required:!1,references:{model:"session",field:"id",onDelete:"set null"},index:!0},userId:{type:"string",required:!1,references:{model:"user",field:"id"},index:!0},referenceId:{type:"string",required:!1},authorizationCodeId:{type:"string",required:!1,index:!0},resources:{type:"string[]",required:!1},requestedUserInfoClaims:{type:"string[]",required:!1},refreshId:{type:"string",required:!1,references:{model:"oauthRefreshToken",field:"id"},index:!0},expiresAt:{type:"date"},createdAt:{type:"date"},revoked:{type:"date",required:!1},confirmation:{type:"json",required:!1},scopes:{type:"string[]",required:!0}}},oauthConsent:{modelName:"oauthConsent",fields:{clientId:{type:"string",required:!0,references:{model:"oauthClient",field:"clientId"},index:!0},userId:{type:"string",required:!1,references:{model:"user",field:"id"},index:!0},referenceId:{type:"string",required:!1},resources:{type:"string[]",required:!1},requestedUserInfoClaims:{type:"string[]",required:!1},scopes:{type:"string[]",required:!0},createdAt:{type:"date"},updatedAt:{type:"date"}}},oauthClientAssertion:{modelName:"oauthClientAssertion",fields:{expiresAt:{type:"date",required:!0}}}},xn=["openid","profile","email","offline_access"],wB=Pe.object({id_token_hint:Pe.string().optional(),client_id:Pe.string().optional(),post_logout_redirect_uri:_i.optional(),state:Pe.string().optional()}),pu=Zc(()=>null),Dn=pu.get,Mw=new WeakMap,_B="signedQueryIssuedAtMs";function Ofe(e){let t=typeof e==="number"?e:typeof e==="string"?Number(e):void 0;if(!t||!Number.isFinite(t)||t<=0)return;return new Date(t)}var Br=(e)=>{let t=e.clientRegistrationAllowedScopes;if(e.clientRegistrationDefaultScopes){let u=t?new Set([...t,...e.clientRegistrationDefaultScopes]):new Set([...e.clientRegistrationDefaultScopes]);t=Array.from(u)}let r=new Set((e.scopes??xn).filter((u)=>u.length));if(t){for(let u of t)if(!r.has(u))throw new y(`clientRegistrationAllowedScope ${u} not found in scopes`)}for(let u of e.advertisedMetadata?.scopes_supported??[])if(!r?.has(u))throw new y(`advertisedMetadata.scopes_supported ${u} not found in scopes`);let n=new Set((e.resources??[]).map((u)=>typeof u==="string"?u:u.identifier));for(let[u,d]of[["clientRegistrationDefaultResources",e.clientRegistrationDefaultResources],["clientRegistrationAllowedResources",e.clientRegistrationAllowedResources]])for(let f of d??[])if(!n.has(f))throw new y(`${u} resource ${f} not found in resources`);let i=new Set(["sub","iss","aud","exp","iat","sid","scope","azp",...Tv.filter((u)=>r.has(kw[u].scope))]),o={codeExpiresIn:600,accessTokenExpiresIn:3600,m2mAccessTokenExpiresIn:3600,refreshTokenExpiresIn:2592000,refreshTokenReuseInterval:0,allowUnauthenticatedClientRegistration:!1,allowDynamicClientRegistration:!1,disableJwtPlugin:!1,storeClientSecret:e.disableJwtPlugin?"encrypted":"hashed",storeTokens:"hashed",grantTypes:["authorization_code","client_credentials","refresh_token"],...e,scopes:Array.from(r),claims:Array.from(i),clientRegistrationAllowedScopes:t};if(cq(o.extensions),o.pairwiseSecret&&o.pairwiseSecret.length<32)throw new y("pairwiseSecret must be at least 32 characters long for adequate HMAC-SHA256 security");if(o.grantTypes&&o.grantTypes.includes("refresh_token")&&!o.grantTypes.includes("authorization_code"))throw new y("refresh_token grant requires authorization_code grant");if(o.disableJwtPlugin&&(o.storeClientSecret==="hashed"||typeof o.storeClientSecret==="object"&&("hash"in o.storeClientSecret)))throw new y("unable to store hashed secrets because id tokens will be signed with secret");if(!o.disableJwtPlugin&&(o.storeClientSecret==="encrypted"||typeof o.storeClientSecret==="object"&&(("encrypt"in o.storeClientSecret)||("decrypt"in o.storeClientSecret))))throw new y("encryption method not recommended, please use 'hashed' or the 'hash' function");let s=async(u,d)=>{let f=new URL(u.url).pathname,h=d.options.advanced?.skipTrailingSlashes?f.replace(/\/+$/,"")||"/":f,p=o.disableJwtPlugin?d.baseURL:Io(d)?.options?.jwt?.issuer??d.baseURL,g="/";try{g=new URL(p).pathname.replace(/\/$/,"")||""}catch{g=new URL(d.baseURL).pathname.replace(/\/$/,"")||""}let _={context:d},R=new Set([`/.well-known/oauth-authorization-server${g}`,`${g}/.well-known/oauth-authorization-server`]),O=`${g}/.well-known/openid-configuration`,I=R.has(h),Ne=o.scopes?.includes("openid")&&h===O,k=(j)=>{let re=gt(j);if(u.method==="HEAD")return new Response(null,{status:re.status,headers:re.headers});return re};if(I||Ne){if(u.method!=="GET"&&u.method!=="HEAD")return{response:new Response(null,{status:405,headers:{Allow:"GET, HEAD"}})}}if(I){if(o.scopes?.includes("openid"))return{response:k(Lr(_,o))};return{response:k(In(_,o))}}if(Ne)return{response:k(Lr(_,o))}},a=lu("/oauth2/authorize",{method:["GET","POST"],body:Pe.object({}).passthrough(),redirectOnError:fu(o),metadata:{allowedMediaTypes:["application/x-www-form-urlencoded"],openapi:{description:"Authorize an OAuth 2.1 request from query parameters or an application/x-www-form-urlencoded POST body",parameters:[{name:"response_type",in:"query",required:!1,schema:{type:"string"},description:"OAuth 2.1 response type (e.g., 'code')"},{name:"client_id",in:"query",required:!0,schema:{type:"string"},description:"OAuth 2.1 client ID"},{name:"redirect_uri",in:"query",required:!1,schema:{type:"string",format:"uri"},description:"OAuth 2.1 redirect URI"},{name:"scope",in:"query",required:!1,schema:{type:"string"},description:"OAuth 2.1 scopes (space-separated)"},{name:"state",in:"query",required:!1,schema:{type:"string"},description:"OAuth 2.1 state parameter"},{name:"request_uri",in:"query",required:!1,schema:{type:"string"},description:"Pushed Authorization Request URI referencing stored parameters"},{name:"code_challenge",in:"query",required:!1,schema:{type:"string"},description:"PKCE code challenge"},{name:"code_challenge_method",in:"query",required:!1,schema:{type:"string"},description:"PKCE code challenge method"},{name:"nonce",in:"query",required:!1,schema:{type:"string"},description:"OpenID Connect nonce"},{name:"max_age",in:"query",required:!1,schema:{type:"integer",minimum:0},description:"Maximum authentication age in seconds; forces re-authentication when exceeded"},{name:"resource",in:"query",required:!1,schema:{type:"array",items:{type:"string"}},description:"Requested protected resource(s) for the access token. May be supplied multiple times as repeated 'resource' query parameters (RFC 8707) or as an array of strings."},{name:"prompt",in:"query",required:!1,schema:{type:"string"},description:"OAuth2 prompt parameter"}],responses:{"302":{description:"Redirect to client with code or error",headers:{Location:{description:"Redirect URI with code or error",schema:{type:"string",format:"uri"}}}},"400":{description:"Invalid request",content:{"application/json":{schema:{type:"object",properties:{error:{type:"string"},error_description:{type:"string"},state:{type:"string"}},required:["error"]}}}}}}}},async(u)=>Bfe(u,o,u.authorizeSettings??{isAuthorize:!0})),c=(u,d)=>Rp(a,{...u,asResponse:!1,returnHeaders:!1,returnStatus:!1,authorizeSettings:d??{}});return{id:"oauth-provider",version:Zq,options:o,onRequest:s,init:async(u)=>{if(u.options.secondaryStorage&&u.options.session?.storeSessionInDatabase!==!0)throw new y("OAuth Provider requires `session.storeSessionInDatabase: true` when using secondaryStorage");if(o.allowClientKeyRotation){let d=u.adapter.id==="memory"?"the memory adapter":u.options.advanced?.database?.generateId==="serial"?'`advanced.database.generateId: "serial"`':void 0;if(d)throw new y(`\`allowClientKeyRotation\` requires single-use client assertions, which ${d} does not enforce`)}if(await Nv(u,o).catch((d)=>Bq(u,d)),jq(o),!o.disableJwtPlugin){let d=Io(u)?.options,f=d?.jwt?.issuer??u.baseURL,h=d?.jwt?.issuer==null&&typeof u.options.baseURL==="object"&&u.options.baseURL!==null&&"allowedHosts"in u.options.baseURL;try{new URL(f)}catch(p){if(!h||f!=="")throw p}}return{options:{databaseHooks:{session:{delete:{async before(d,f){if(!f)return;let h=await Hde(f,o,{sessionId:d.id,userId:d.userId});if(!h)return;let p=Mw.get(f)??new Map;p.set(d.id,h),Mw.set(f,p)},async after(d,f){if(!f)return;let h=Mw.get(f);if(!h)return;let p=h.get(d.id);if(h.delete(d.id),h.size===0)Mw.delete(f);if(!p)return;let g=Vde(f,p).catch((_)=>{f.context.logger.error("Back-channel logout failed after session deletion",_)});await f.context.runInBackgroundOrAwait(g)}}}}}}},hooks:{before:[{matcher(u){return u.body?.oauth_query},handler:ee(async(u)=>{let d=u.body.oauth_query;if(!await mv(d,u.context.secret))throw new l("BAD_REQUEST",{error:"invalid_signature"});let f=iq(d),h=new URLSearchParams(d),p=h.get("ba_pl")??void 0;if(h.delete("sig"),h.delete("exp"),h.delete(av),h.delete(pw),await pu.set({query:h.toString(),signedQueryIssuedAt:f??void 0,postLoginClearedForSession:p}),u.path==="/sign-in/social")await NT({query:h.toString(),...f?{[_B]:f.getTime()}:{}})})}],after:[{matcher(u){return Iy(u.context.responseHeaders?.get("set-cookie")||"").has(u.context.authCookies.sessionToken.name)},handler:ee(async(u)=>{let d=Iy(u.context.responseHeaders?.get("set-cookie")||"").get(u.context.authCookies.sessionToken.name)?.value.split(".")[0];if(!d)return;let f=await pu.get(),h=(await kT())?.serverContext,p=f?.query??h?.query;if(!p)return;let g=new URLSearchParams(p),_=await u.context.internalAdapter.findSession(d);if(!_)return;u.context.session=_;let R=u.request?.headers?.get("sec-fetch-mode")?.toLowerCase(),O=u.request?.headers?.get("accept")?.toLowerCase()??"";if(!(R==="navigate"||!R&&(O.includes("text/html")||O.includes("application/xhtml+xml"))))u.headers?.set("accept","application/json");let I=f?.signedQueryIssuedAt??Ofe(h?.[_B]),Ne=Kl(g,"login");if(bv(_.session.createdAt,I))Ne=Ev(Ne);return u.query=md(Ne),await c(u)})}]},endpoints:{getOAuthServerConfig:v("/.well-known/oauth-authorization-server",{method:"GET",metadata:{SERVER_ONLY:!0}},async(u)=>{if(o.scopes&&o.scopes.includes("openid"))return Lr(u,o);else return In(u,o)}),getOpenIdConfig:v("/.well-known/openid-configuration",{method:"GET",metadata:{SERVER_ONLY:!0}},async(u)=>{if(o.scopes&&!o.scopes.includes("openid"))throw new l("NOT_FOUND");return Lr(u,o)}),oauth2Authorize:a,oauth2Consent:v("/oauth2/consent",{method:"POST",body:Pe.object({accept:Pe.boolean().meta({description:"Accept or deny user consent for a set of scopes"}),scope:Pe.string().optional().meta({description:"List of accept of accepted space-separated scopes. If none is provided, then all originally requested scopes are accepted."}),claims:Av.optional().meta({description:"Accepted OIDC claims request object. If none is provided, then all originally requested claims are accepted."}),oauth_query:Pe.string().optional().meta({description:"The redirected page's query parameters"})}),use:[K],metadata:{openapi:{description:"Handle OAuth2 consent",responses:{"200":{description:"Consent processed successfully",content:{"application/json":{schema:{type:"object",properties:{redirect:{type:"boolean",description:"Always true. Indicates the caller should redirect to `url`.",enum:[!0]},url:{type:"string",format:"uri-reference",description:"The absolute or relative URI to redirect to next."}},required:["redirect","url"]}}}}}}}},async(u)=>Pde(u,o,c)),oauth2Continue:v("/oauth2/continue",{method:"POST",body:Pe.object({selected:Pe.boolean().optional().meta({description:"Confirms an account has been selected and authorization can proceed."}),created:Pe.boolean().optional().meta({description:"Confirms an account was registered"}),postLogin:Pe.boolean().optional().meta({description:"Resumes after the post login page. postLogin.shouldRedirect runs again with isContinuation: true."}),oauth_query:Pe.string().optional().meta({description:"The redirected page's query parameters"})}),use:[K],metadata:{openapi:{description:"Continues OAuth2 authorization flow",responses:{"200":{description:"Authorization flow continued successfully",content:{"application/json":{schema:{type:"object",properties:{redirect:{type:"boolean",description:"Always true. Indicates the caller should redirect to `url`.",enum:[!0]},url:{type:"string",format:"uri-reference",description:"The absolute or relative URI to redirect to next."}},required:["redirect","url"]}}}}}}}},async(u)=>Lde(u,c)),oauth2Token:lu("/oauth2/token",{method:"POST",cloneRequest:!0,body:Pe.object({grant_type:Pe.string().trim().min(1),client_id:Pe.string().optional(),client_secret:Pe.string().optional(),client_assertion:Pe.string().optional(),client_assertion_type:Pe.string().optional(),code:Pe.string().optional(),code_verifier:Pe.string().optional(),redirect_uri:_i.optional(),refresh_token:Pe.string().optional(),resource:Pe.union([Le,Pe.array(Le).min(1)]).optional(),scope:Pe.string().optional()}).passthrough(),errorCodesByField:{grant_type:{missing:"invalid_request",invalid:"unsupported_grant_type"},resource:{invalid:"invalid_target"}},metadata:{noStore:!0,allowedMediaTypes:["application/x-www-form-urlencoded"],openapi:{description:"Obtain an OAuth2.1 access token",parameters:[{name:"DPoP",in:"header",required:!1,schema:{type:"string"},description:"RFC 9449 DPoP proof JWT for issuing DPoP-bound tokens"}],requestBody:{required:!0,content:{"application/json":{schema:{type:"object",properties:{grant_type:{type:"string",description:"OAuth2 grant type"},client_id:{type:"string",description:"OAuth2 client ID"},client_secret:{type:"string",description:"OAuth2 client secret"},code:{type:"string",description:"Authorization code (for authorization_code grant)"},code_verifier:{type:"string",description:"PKCE code verifier (for authorization_code grant)"},redirect_uri:{type:"string",format:"uri",description:"Redirect URI (for authorization_code grant)"},refresh_token:{type:"string",description:"Refresh token (for refresh_token grant)"},resource:{oneOf:[{type:"string",description:"Single resource (URL)"},{type:"array",items:{type:"string"},description:"Multiple resources (URLs)"}],description:"Requested protected resource(s) for the access token"},scope:{type:"string",description:"Requested scopes (for client_credentials grant)"}},required:["grant_type"]}}}},responses:{"200":{description:"Access token response",content:{"application/json":{schema:{type:"object",properties:{access_token:{type:"string",description:"The access token issued by the authorization server"},token_type:{type:"string",description:"The type of the token issued",enum:["Bearer","DPoP"]},expires_in:{type:"number",description:"Lifetime in seconds of the access token"},refresh_token:{type:"string",description:"Refresh token, if issued"},scope:{type:"string",description:"Scopes granted by the access token"},id_token:{type:"string",description:"ID Token (if OpenID Connect)"}},required:["access_token","token_type","expires_in"]}}}},"400":{description:"Invalid request or error response",content:{"application/json":{schema:{type:"object",properties:{error:{type:"string"},error_description:{type:"string"},error_uri:{type:"string"}},required:["error"]}}}}}}}},async(u)=>{if(u.request){let d=await Lq(u.request);if(d&&d.length>1)u.body.resource=d}return Wq(u,o)}),oauth2Introspect:lu("/oauth2/introspect",{method:"POST",cloneRequest:!0,body:Pe.object({client_id:Pe.string().optional(),client_secret:Pe.string().optional(),client_assertion:Pe.string().optional(),client_assertion_type:Pe.string().optional(),token:Pe.string(),token_type_hint:Pe.string().optional()}),metadata:{noStore:!0,allowedMediaTypes:["application/x-www-form-urlencoded"],openapi:{description:"Introspect an OAuth2 access or refresh token",requestBody:{required:!0,content:{"application/json":{schema:{type:"object",properties:{client_id:{type:"string",description:"OAuth2 client ID"},client_secret:{type:"string",description:"OAuth2 client secret"},token:{type:"string",description:"The token to introspect (access or refresh token)"},token_type_hint:{type:"string",description:"Hint about the token type. Recognized values: `access_token`, `refresh_token`."}},required:["token"]}}}},responses:{"200":{description:"Token introspection response",content:{"application/json":{schema:{type:"object",properties:{active:{type:"boolean",description:"Whether the token is active"},scope:{type:"string",description:"Scopes associated with the token"},client_id:{type:"string",description:"Client ID associated with the token"},username:{type:"string",description:"Username associated with the token"},token_type:{type:"string",description:"Type of the token"},exp:{type:"number",description:"Expiration time of the token (seconds since epoch)"},iat:{type:"number",description:"Issued at time (seconds since epoch)"},nbf:{type:"number",description:"Not before time (seconds since epoch)"},sub:{type:"string",description:"Subject of the token"},aud:{type:"string",description:"Audience of the token"},iss:{type:"string",description:"Issuer of the token"},jti:{type:"string",description:"JWT ID"}},required:["active"]}}}},"400":{description:"Invalid request or error response",content:{"application/json":{schema:{type:"object",properties:{error:{type:"string"},error_description:{type:"string"},error_uri:{type:"string"}},required:["error"]}}}}}}}},async(u)=>Dv(u,o)),oauth2Revoke:lu("/oauth2/revoke",{method:"POST",cloneRequest:!0,body:Pe.object({client_id:Pe.string().optional(),client_secret:Pe.string().optional(),client_assertion:Pe.string().optional(),client_assertion_type:Pe.string().optional(),token:Pe.string(),token_type_hint:Pe.string().optional()}),metadata:{allowedMediaTypes:["application/x-www-form-urlencoded"],openapi:{description:"Revoke an OAuth2 access or refresh token",requestBody:{required:!0,content:{"application/json":{schema:{type:"object",properties:{client_id:{type:"string",description:"OAuth2 client ID"},client_secret:{type:"string",description:"OAuth2 client secret"},token:{type:"string",description:"The token to revoke (access or refresh token)"},token_type_hint:{type:"string",description:"Hint about the token type. Recognized values: `access_token`, `refresh_token`."}},required:["token"]}}}},responses:{"200":{description:"Token revoked successfully. The response body is empty.",content:{"application/json":{schema:{type:"object",description:"Empty object on success"}}}},"400":{description:"Invalid request or error response",content:{"application/json":{schema:{type:"object",properties:{error:{type:"string"},error_description:{type:"string"},error_uri:{type:"string"}},required:["error"]}}}}}}}},async(u)=>xfe(u,o)),oauth2UserInfo:v("/oauth2/userinfo",{method:["GET","POST"],body:Pe.object({access_token:Pe.string().optional()}).passthrough().optional(),metadata:{noStore:!0,allowedMediaTypes:["application/x-www-form-urlencoded"],openapi:{description:"Get OpenID Connect user information (UserInfo endpoint)",security:[{bearerAuth:[]},{OAuth2:["openid","profile","email"]}],parameters:[{name:"Authorization",in:"header",required:!1,schema:{type:"string"},description:"Bearer or DPoP access token"},{name:"DPoP",in:"header",required:!1,schema:{type:"string"},description:"RFC 9449 DPoP proof JWT when using a DPoP-bound access token"}],responses:{"200":{description:"User information retrieved successfully",content:{"application/json":{schema:{type:"object",properties:{sub:{type:"string",description:"Subject identifier (user ID)"},email:{type:"string",format:"email",nullable:!0,description:"User's email address, included if 'email' scope is granted"},name:{type:"string",nullable:!0,description:"User's full name, included if 'profile' scope is granted"},picture:{type:"string",format:"uri",nullable:!0,description:"User's profile picture URL, included if 'profile' scope is granted"},given_name:{type:"string",nullable:!0,description:"User's given name, included if 'profile' scope is granted"},family_name:{type:"string",nullable:!0,description:"User's family name, included if 'profile' scope is granted"},email_verified:{type:"boolean",nullable:!0,description:"Whether the email is verified, included if 'email' scope is granted"}},required:["sub"]}}}},"401":{description:"Unauthorized - invalid or missing access token",content:{"application/json":{schema:{type:"object",properties:{error:{type:"string"},error_description:{type:"string"}},required:["error"]}}}},"403":{description:"Forbidden - insufficient scope",content:{"application/json":{schema:{type:"object",properties:{error:{type:"string"},error_description:{type:"string"}},required:["error"]}}}}}}}},async(u)=>zq(u,o)),oauth2EndSession:lu("/oauth2/end-session",{method:["GET","POST"],body:wB.optional(),query:wB.optional(),metadata:{noStore:!0,allowedMediaTypes:["application/x-www-form-urlencoded","application/json"],$Infer:{body:{},query:{}},openapi:{description:"RP-Initiated Logout endpoint. Accepts standard logout parameters through GET or an application/x-www-form-urlencoded POST body, plus JSON for Better Auth generated-client calls. Requests without a usable id_token_hint may require explicit OP confirmation.",responses:{"200":{description:"Logout completed, or an HTML confirmation page was returned for browser navigation. A redirect is used only for an exact registered post_logout_redirect_uri.",content:{"application/json":{schema:{type:"object",properties:{redirect_uri:{type:"string",format:"uri",description:"URI to redirect to after logout (if post_logout_redirect_uri was provided)"},message:{type:"string",description:"Success message"}}}},"text/html":{schema:{type:"string"}}}}}}}},async(u)=>ile(u,o)),oauth2EndSessionConfirmation:lu("/oauth2/end-session/confirm",{method:"POST",body:Pe.object({action:Pe.literal("confirm")}),metadata:{noStore:!0,allowedMediaTypes:["application/x-www-form-urlencoded"],scope:"http"}},async(u)=>ole(u,o)),registerOAuthClient:lu("/oauth2/register",{method:"POST",body:kv,errorCodesByField:{redirect_uris:"invalid_redirect_uri",post_logout_redirect_uris:"invalid_redirect_uri",software_statement:"invalid_software_statement",resources:"invalid_target"},defaultError:"invalid_client_metadata",metadata:{noStore:!0,openapi:{description:"Register an OAuth2 application",responses:{"201":{description:"OAuth2 application registered successfully",content:{"application/json":{schema:{type:"object",properties:{client_id:{type:"string",description:"Unique identifier for the client"},client_secret:{type:"string",description:"Secret key for the client"},client_secret_expires_at:{type:"number",description:"Time the client secret will expire. If 0, the client secret will never expire."},scope:{type:"string",description:"Space-separated scopes allowed by the client"},user_id:{type:"string",description:"ID of the user who registered the client, null if registered anonymously"},client_id_issued_at:{type:"number",description:"Creation timestamp of this client"},client_name:{type:"string",description:"Name of the OAuth2 application"},client_uri:{type:"string",description:"Name of the OAuth2 application"},logo_uri:{type:"string",description:"Icon URL for the application"},contacts:{type:"array",items:{type:"string"},description:"List representing ways to contact people responsible for this client, typically email addresses"},tos_uri:{type:"string",description:"Client's terms of service uri"},policy_uri:{type:"string",description:"Client's policy uri"},software_id:{type:"string",description:"Unique identifier assigned by the developer to help in the dynamic registration process"},software_version:{type:"string",description:"Version identifier for the software_id"},software_statement:{type:"string",description:"JWT containing metadata values about the client software as claims"},redirect_uris:{type:"array",items:{type:"string",format:"uri"},description:"List of allowed redirect uris"},post_logout_redirect_uris:{type:"array",items:{type:"string",format:"uri"},description:"List of allowed logout redirect uris"},backchannel_logout_uri:{type:"string",format:"uri",description:"RP URL to receive signed Logout Tokens when the end-user's OP session terminates"},backchannel_logout_session_required:{type:"boolean",description:"Whether the RP requires a `sid` claim in every Logout Token"},token_endpoint_auth_method:{type:"string",description:"Requested authentication method for the token endpoint"},grant_types:{type:"array",items:{type:"string"},description:"Grant types the client may use at the token endpoint"},response_types:{type:"array",items:{type:"string",enum:["code"]},description:"Response types the client may use at the authorization endpoint"},application_type:{type:"string",description:"OIDC application type used to classify redirect URI policy",enum:["web","native"]},resources:{type:"array",items:{type:"string",format:"uri"},description:"Final resource identifiers linked to the registered client"},disabled:{type:"boolean",description:"Whether the client is disabled"}},required:["client_id"]}}}}}}}},async(u)=>Ple(u,o)),adminCreateOAuthClient:Wle(o),createOAuthClient:Hle(o),getOAuthClient:Vle(o),getOAuthClientPublic:Gle(o),getOAuthClientPublicPrelogin:Kle(o),getOAuthClients:Jle(o),adminUpdateOAuthClient:Qle(o),updateOAuthClient:Yle(o),rotateClientSecret:Xle(o),rotateClientKeys:Zle(o),deleteOAuthClient:efe(o),getOAuthConsent:ofe(o),getOAuthConsents:sfe(o),updateOAuthConsent:afe(o),deleteOAuthConsent:cfe(o),adminCreateOAuthResource:wfe(o),adminListOAuthResources:_fe(o),adminGetOAuthResource:bfe(o),adminUpdateOAuthResource:Efe(o),adminDeleteOAuthResource:Sfe(o),adminLinkClientResource:Afe(o),adminUnlinkClientResource:Tfe(o)},schema:xt(structuredClone(Cfe),o?.schema),rateLimit:[...o.rateLimit?.token!==!1?[{pathMatcher:(u)=>u==="/oauth2/token",window:o.rateLimit?.token?.window??60,max:o.rateLimit?.token?.max??20}]:[],...o.rateLimit?.authorize!==!1?[{pathMatcher:(u)=>u==="/oauth2/authorize",window:o.rateLimit?.authorize?.window??60,max:o.rateLimit?.authorize?.max??30}]:[],...o.rateLimit?.introspect!==!1?[{pathMatcher:(u)=>u==="/oauth2/introspect",window:o.rateLimit?.introspect?.window??60,max:o.rateLimit?.introspect?.max??100}]:[],...o.rateLimit?.revoke!==!1?[{pathMatcher:(u)=>u==="/oauth2/revoke",window:o.rateLimit?.revoke?.window??60,max:o.rateLimit?.revoke?.max??30}]:[],...o.rateLimit?.register!==!1?[{pathMatcher:(u)=>u==="/oauth2/register",window:o.rateLimit?.register?.window??60,max:o.rateLimit?.register?.max??5}]:[],...o.rateLimit?.rotateClientKeys!==!1?[{pathMatcher:(u)=>u==="/oauth2/client/rotate-keys",window:o.rateLimit?.rotateClientKeys?.window??60,max:o.rateLimit?.rotateClientKeys?.max??5}]:[],...o.rateLimit?.userinfo!==!1?[{pathMatcher:(u)=>u==="/oauth2/userinfo",window:o.rateLimit?.userinfo?.window??60,max:o.rateLimit?.userinfo?.max??60}]:[]]}};function Ife(e,t,r){if(t===0)return!1;return r.getTime()-e.getTime()<=t*1000}function Dfe(e){let{max_age:t,...r}=e;return r}function ls(e,t,r,n,i,o="query"){let s=new URLSearchParams({error:t,error_description:r});if(n&&s.append("state",n),i&&s.append("iss",i),o==="fragment")return`${e}#${s.toString()}`;return us(e,s)}function Ufe(e){let t=typeof e.response_mode==="string"?e.response_mode:void 0;if(t==="fragment")return"fragment";if(t==="query")return"query";let r=typeof e.response_type==="string"?e.response_type:void 0;if(r&&/\b(token|id_token)\b/.test(r))return"fragment";return"query"}var Pfe={response_type:{invalid:"unsupported_response_type"},resource:{invalid:"invalid_target"}};function Lfe(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}function qv(e){return typeof e==="string"?e:void 0}function Mfe(e,t){let r=e.method==="POST"&&t?.isAuthorize===!0?e.body:e.query;return{...Lfe(r)?r:{}}}var bi=(e,t)=>{let r=Uv(e.request?.headers),n=e.headers?.get("accept")?.includes("application/json");if(r||n)return{redirect:!0,url:t.toString()};else throw e.redirect(t)};function Ql(e,t,r,n,i){return bi(e,ls(r.redirect_uri,n,i,r.state,se(e,t)))}function rj(e){try{let t=new URL(e);if(t.protocol!=="https:"&&!Pl(t.host))t.protocol="https:";return t.search="",t.hash="",t.toString().replace(/\/$/,"")}catch{return e}}function se(e,t){let r;if(t.disableJwtPlugin)r=e.context.baseURL;else try{r=Io(e.context).options?.jwt?.issuer??e.context.baseURL}catch{r=e.context.baseURL}return rj(r)}function yd(e,t,r){return ls(e.context.options.onAPIError?.errorURL||`${e.context.baseURL}/error`,t,r)}function bB(e){let t;try{t=new URL(e)}catch{return}let r=ST(t.hostname)||t.hostname==="localhost";if(t.protocol!=="http:"||!r)return;let n=e.indexOf("://");if(n<0)return;let i=n+3,o=e.slice(i).search(/[/?#]/u),s=e.length;if(o>=0)s=i+o;let a=e.slice(i,s),c;if(a.startsWith("[")){let f=a.indexOf("]");if(f<0)return;if(a[f+1]!==":")return e;c=f+1}else if(c=a.lastIndexOf(":"),c<0)return e;let u=a.slice(c+1);if(!/^\d*$/u.test(u))return;let d=i+c;return`${e.slice(0,d)}${e.slice(s)}`}function nj(e,t){if(!e||!t)return;let r;try{r=new URL(t)}catch{return}let n=t.includes("#"),i=r.username.length>0||r.password.length>0;if(n||i)return;let o=bB(t);return e.find((s)=>{if(s===t)return!0;if(!o)return!1;return bB(s)===o})}function ij(e){if(!_i.safeParse(e).success)return!1;let t=new URL(e);return t.username.length===0&&t.password.length===0}async function qfe(e,t,r,n){if(!r||!n)return null;let i;try{i=await Fi(e,t,r)}catch{return null}if(!i||i.disabled)return null;let o=i.redirectUris??[],s=nj(o,n);if(t.validateRedirectUri){if(!ij(n))return null;try{return await t.validateRedirectUri(n,o,Boolean(s))?n:null}catch{return null}}return s?n:null}function fu(e){return async({error:t,error_description:r,ctx:n})=>{let i=n.query??{},o=await qfe(n,e,typeof i.client_id==="string"?i.client_id:void 0,typeof i.redirect_uri==="string"?i.redirect_uri:void 0);if(o)return bi(n,ls(o,t,r,typeof i.state==="string"?i.state:void 0,se(n,e),Ufe(i)));return bi(n,yd(n,t,r))}}async function Bfe(e,t,r){if(t.grantTypes&&!t.grantTypes.includes("authorization_code"))throw new st("NOT_FOUND");if(!e.request)throw new st("UNAUTHORIZED",{error_description:"request not found",error:"invalid_request"});let n=e.request,i=Mfe(e,r);e.query=i;let o=qv(i.request),s=qv(i.request_uri);if(o!==void 0&&s!==void 0)return fu(t)({error:"invalid_request",error_description:"request and request_uri cannot be used together",ctx:e});if(o!==void 0)return fu(t)({error:"request_not_supported",error_description:"request object not supported",ctx:e});if(s!==void 0){let ne=qv(i.client_id);if(!ne)return fu(t)({error:"invalid_request",error_description:"client_id is required",ctx:e});if(!t.requestUriResolver)return fu(t)({error:"request_uri_not_supported",error_description:"request_uri not supported",ctx:e});let M=await t.requestUriResolver({requestUri:s,clientId:ne,ctx:e});if(!M)return fu(t)({error:"invalid_request_uri",error_description:"request_uri is invalid or expired",ctx:e});let F=i.client_id;if(i=M,F)i.client_id=F}e.query=i;let a=vv.safeParse(i);if(!a.success){let ne=$v(a.error.issues,Pfe);return fu(t)({...ne,ctx:e})}if(i=a.data,e.query=i,await pu.set({query:oj(i).toString()}),!i.response_type)return fu(t)({error:"invalid_request",error_description:"response_type is required",ctx:e});let c=e.query?.prompt?yv(e.query?.prompt):void 0,u=c?.has("none")??!1;if(c?.has("select_account")&&!t.selectAccount?.page)return bi(e,yd(e,"unsupported_prompt_select_account","unsupported prompt type"));if(i.response_type!=="code")return bi(e,yd(e,"unsupported_response_type","unsupported response type"));let d=await Fi(e,t,i.client_id);if(!d)return bi(e,yd(e,"invalid_client","client not found"));if(d.disabled)return bi(e,yd(e,"client_disabled","client is disabled"));if(!Op(d,"authorization_code"))return bi(e,yd(e,"unauthorized_client","client is not authorized to use the authorization_code grant"));let f=d.redirectUris??[],h=!1;if(i.redirect_uri){let ne=Boolean(nj(f,i.redirect_uri));if(t.validateRedirectUri&&ij(i.redirect_uri))try{h=await t.validateRedirectUri(i.redirect_uri,f,ne)}catch{h=!1}else if(!t.validateRedirectUri)h=ne}if(!h)return bi(e,yd(e,"invalid_redirect","invalid redirect uri"));let p=i.scope?.split(" ").filter((ne)=>ne);if(p){let ne=new Set(d.scopes??t.scopes),M=p.filter((F)=>!ne?.has(F));if(M.length)return bi(e,ls(i.redirect_uri,"invalid_scope",`The following scopes are invalid: ${M.join(", ")}`,i.state,se(e,t)))}if(!p)p=d.scopes??t.scopes??[],i.scope=p.join(" ");let g=p.includes("openid");if(i.claims!==void 0&&!g)return bi(e,ls(i.redirect_uri,"invalid_request","openid scope must be requested when using the claims parameter",i.state,se(e,t)));if(g&&!Cq(i.claims))return bi(e,ls(i.redirect_uri,"invalid_request","claims must be a valid Claims request object",i.state,se(e,t)));if(g&&!Oq(i.claims,"0"))return bi(e,ls(i.redirect_uri,"access_denied","essential acr requirement cannot be met",i.state,se(e,t)));let _=Dp(i.claims,Up(t));if(i.resource!==void 0)try{await Rv(e,t,{resource:i.resource,clientId:d.clientId,requestedScopes:p})}catch(ne){if(ne instanceof st){let M=ne.body?.error??"invalid_target",F=ne.body?.error_description??"requested resource invalid";return bi(e,ls(i.redirect_uri,M,F,i.state,se(e,t)))}throw ne}let R=Sw(d,{scopes:p,nonce:i.nonce});if(R){if(!i.code_challenge||!i.code_challenge_method)return bi(e,ls(i.redirect_uri,"invalid_request",R.valueOf(),i.state,se(e,t)))}if(i.code_challenge||i.code_challenge_method){if(!i.code_challenge||!i.code_challenge_method)return bi(e,ls(i.redirect_uri,"invalid_request","code_challenge and code_challenge_method must both be provided",i.state,se(e,t)));if(!["S256"].includes(i.code_challenge_method))return bi(e,ls(i.redirect_uri,"invalid_request","invalid code_challenge method, only S256 is supported",i.state,se(e,t)))}let O=su(i.resource)??[],I=await Gr(e),Ne=i.max_age,k=I!=null&&Ne!==void 0&&Ife(new Date(I.session.createdAt),Ne,new Date);if(!I||I!=null&&Ne!==void 0&&!k||c?.has("login")||c?.has("create")){if(u)return Ql(e,t,i,"login_required","authentication required");return du(e,t,c?.has("create")?"create":"login")}if(k)i=Dfe(i),e.query=i;if(r?.isAuthorize&&c?.has("select_account"))return du(e,t,"select_account");if(r?.isAuthorize&&t.selectAccount){if(await t.selectAccount.shouldRedirect({headers:n.headers,user:I.user,session:I.session,scopes:p})){if(u)return Ql(e,t,i,"account_selection_required","End-User account selection is required");return du(e,t,"select_account")}}if(t.signup?.shouldRedirect){let ne=await t.signup.shouldRedirect({headers:n.headers,user:I.user,session:I.session,scopes:p});if(ne){if(u)return Ql(e,t,i,"interaction_required","End-User interaction is required");return du(e,t,"create",{page:typeof ne==="string"?ne:void 0})}}if(!r?.postLogin&&t.postLogin){if(await t.postLogin.shouldRedirect({headers:n.headers,user:I.user,session:I.session,scopes:p,isContinuation:r?.isPostLoginContinuation??!1})){if(u)return Ql(e,t,i,"interaction_required","End-User interaction is required");return du(e,t,"post_login")}}if(c?.has("consent"))return du(e,t,"consent",{sessionId:I.session.id});let j=await wv(t,{user:I.user,session:I.session,scopes:p});if(d.skipConsent)return EB(e,t,{query:i,clientId:d.clientId,userId:I.user.id,sessionId:I.session.id,authTime:new Date(I.session.createdAt).getTime(),referenceId:j,resource:O});let re=await _v(e,d.clientId,I.user.id,j);if(!re||!p.every((ne)=>re.scopes.includes(ne))||!_.every((ne)=>(re.requestedUserInfoClaims??[]).includes(ne))){if(u)return Ql(e,t,i,"consent_required","End-User consent is required");return du(e,t,"consent",{sessionId:I.session.id})}let Oe=re?.resources??[];if(O.some((ne)=>!Oe.includes(ne))){if(u)return Ql(e,t,i,"consent_required","End-User consent is required");return du(e,t,"consent",{sessionId:I.session.id})}return EB(e,t,{query:i,clientId:d.clientId,userId:I.user.id,sessionId:I.session.id,authTime:new Date(I.session.createdAt).getTime(),referenceId:j,resource:O})}function oj(e){let t=new URLSearchParams;for(let[r,n]of Object.entries(e)){if(n==null)continue;if(Array.isArray(n))for(let i of n)t.append(r,String(i));else if(r==="claims"&&typeof n==="object")t.set(r,JSON.stringify(n));else t.set(r,String(n))}return t}async function EB(e,t,r){let n=Ui(32,"a-z","A-Z","0-9"),i=Math.floor(Date.now()/1000),o=i+(t.codeExpiresIn??600),s={identifier:await fd(t.storeTokens,n,"authorization_code"),updatedAt:new Date(i*1000),expiresAt:new Date(o*1000),value:JSON.stringify({type:"authorization_code",query:r.query,userId:r.userId,sessionId:r?.sessionId,referenceId:r.referenceId,authTime:r.authTime,resource:r.resource})};await e.context.internalAdapter.createVerificationValue({...s,createdAt:new Date(i*1000)});let a=new URL(r.query.redirect_uri);if(a.searchParams.set("code",n),r.query.state)a.searchParams.set("state",r.query.state);return a.searchParams.set("iss",se(e,t)),bi(e,a.toString())}async function du(e,t,r,n){let i=await jfe(e,t,{postLoginClearedForSession:r==="consent"&&t.postLogin?n?.sessionId:void 0}),o=t.loginPage;if(r==="select_account")o=t.selectAccount?.page??t.loginPage;else if(r==="post_login"){if(!t.postLogin?.page)throw new st("INTERNAL_SERVER_ERROR",{error_description:"postLogin should have been defined"});o=t.postLogin?.page}else if(r==="consent")o=t.consentPage;else if(r==="create")o=t.signup?.page??t.loginPage;return bi(e,`${n?.page??o}?${i}`)}async function jfe(e,t,r){let n=Date.now(),i=Math.floor(n/1000)+(t.codeExpiresIn??600),o=oj(e.query);if(o.set("exp",String(i)),o.set(av,String(n)),o.delete("sig"),o.delete(pw),r?.postLoginClearedForSession)o.set(pw,r.postLoginClearedForSession);nq(o);let s=await fp(mw(o).toString(),e.context.secret);return o.set("sig",s),o.toString()}var $fe=function(e,t){if(typeof e==="string"&&/^\.\.?\//.test(e))return e.replace(/\.(tsx)$|((?:\.d)?)((?:\.[^./]+?)?)\.([cm]?)ts$/i,function(r,n,i,o,s){return n?t?".jsx":".js":i&&(!o||!s)?r:i+o+"."+s.toLowerCase()+"js"});return e},sj=(e)=>import($fe(e));function Ffe(){return globalThis.process?.env}function aj(){return{async env(e){let t=Ffe()?.[e];return typeof t==="string"&&t.trim().length>0?t:void 0},async fileExists(e){try{let t=await sj("node:fs/promises"),r=e;if(r.startsWith("~"))r=(await sj("node:os")).homedir()+r.slice(1);return await t.access(r),!0}catch{return!1}}}}class hr{credentials=new Map;chains=new Map;enqueue(e,t){let r=this.chains.get(e)??Promise.resolve(),n=(async()=>(await r.catch(()=>{}),t()))();return this.chains.set(e,n.catch(()=>{})),n}async read(e){return this.credentials.get(e)}async list(){return[...this.credentials].map(([e,t])=>({providerId:e,type:t.type}))}modify(e,t){return this.enqueue(e,async()=>{let r=this.credentials.get(e),n=await t(r);if(n!==void 0)this.credentials.set(e,n);return n??r})}delete(e){return this.enqueue(e,async()=>{this.credentials.delete(e)})}}function _t(e){if(e instanceof Error)return e.message||e.name;if(typeof e==="string")return e;return String(e)}function zfe(e){if(!(e instanceof Error))return{name:"ThrownValue",message:_t(e)};let t=e.code;return{name:e.name||void 0,message:e.message||e.name,stack:e.stack,code:typeof t==="string"||typeof t==="number"?t:void 0}}function gr(e,t,r){return{type:e,timestamp:Date.now(),error:zfe(t),details:r}}function Mt(e,t){e.diagnostics=[...e.diagnostics??[],t]}class Wi extends Error{code;constructor(e,t,r){super(Wfe(t,r?.cause),r);this.name="ModelsError",this.code=e}}function Wfe(e,t){if(t===void 0||t===null)return e;let r=_t(t).trim();if(!r||e.includes(r))return e;return`${e}: ${r}`}async function Gv(e,t,r,n){let i=n?.env?Hfe(r,n.env):r;if(n?.apiKey!==void 0&&e.auth.apiKey)return Vv(i,e.auth.apiKey,e.id,{type:"api_key",key:n.apiKey,env:n.env});let o=await Gfe(t,e.id);if(o){if(o.type==="oauth"&&e.auth.oauth)return Vfe(t,e.id,e.auth.oauth,o);if(o.type==="api_key"&&e.auth.apiKey){let s=n?.env?{...o,env:{...o.env,...n.env}}:o;return Vv(i,e.auth.apiKey,e.id,s)}return}return e.auth.apiKey?Vv(i,e.auth.apiKey,e.id,void 0):void 0}function Hfe(e,t){return{env:async(r)=>t[r]||await e.env(r),fileExists:(r)=>e.fileExists(r)}}async function Vfe(e,t,r,n){let i=n;if(Date.now()>=i.expires){let o;try{o=await e.modify(t,async(s)=>{if(s?.type!=="oauth")return;if(Date.now()<s.expires)return;try{return await r.refresh(s)}catch(a){throw new Wi("oauth",`OAuth refresh failed for ${t}`,{cause:a})}})}catch(s){if(s instanceof Wi)throw s;throw new Wi("auth",`Credential store modify failed for ${t}`,{cause:s})}if(o?.type!=="oauth")return;i=o}try{return{auth:await r.toAuth(i),source:"OAuth"}}catch(o){throw new Wi("oauth",`OAuth auth derivation failed for ${t}`,{cause:o})}}async function Vv(e,t,r,n){try{return await t.resolve({ctx:e,credential:n})}catch(i){throw new Wi("auth",`API key auth failed for provider ${r}`,{cause:i})}}async function Gfe(e,t){try{return await e.read(t)}catch(r){throw new Wi("auth",`Credential store read failed for ${t}`,{cause:r})}}class cj{queue=[];waiting=[];done=!1;finalResultPromise;resolveFinalResult;isComplete;extractResult;constructor(e,t){this.isComplete=e,this.extractResult=t,this.finalResultPromise=new Promise((r)=>{this.resolveFinalResult=r})}push(e){if(this.done)return;if(this.isComplete(e))this.done=!0,this.resolveFinalResult(this.extractResult(e));let t=this.waiting.shift();if(t)t({value:e,done:!1});else this.queue.push(e)}end(e){if(this.done=!0,e!==void 0)this.resolveFinalResult(e);while(this.waiting.length>0)this.waiting.shift()({value:void 0,done:!0})}async*[Symbol.asyncIterator](){while(!0)if(this.queue.length>0)yield this.queue.shift();else if(this.done)return;else{let e=await new Promise((t)=>this.waiting.push(t));if(e.done)return;yield e.value}}result(){return this.finalResultPromise}}class Q extends cj{constructor(){super((e)=>e.type==="done"||e.type==="error",(e)=>{if(e.type==="done")return e.message;else if(e.type==="error")return e.error;throw Error("Unexpected event type for final result")})}}function Kfe(e,t){return{role:"assistant",content:[],api:e.api,provider:e.provider,model:e.id,usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:"error",errorMessage:t instanceof Error?t.message:String(t),timestamp:Date.now()}}function Jfe(e){return typeof e.result==="function"}async function Qfe(e,t){for await(let r of t)e.push(r);e.end(Jfe(t)?await t.result():void 0)}function Yl(e,t){let r=new Q;return t().then((n)=>Qfe(r,n)).catch((n)=>{let i=Kfe(e,n);r.push({type:"error",reason:"error",error:i}),r.end(i)}),r}function J(e){return{stream:(t,r,n)=>Yl(t,async()=>(await e()).stream(t,r,n)),streamSimple:(t,r,n)=>Yl(t,async()=>(await e()).streamSimple(t,r,n))}}class Kv{entries=new Map;async read(e){let t=this.entries.get(e);return t?structuredClone(t):void 0}async write(e,t){this.entries.set(e,structuredClone(t))}async delete(e){this.entries.delete(e)}}function uj(e,t){if(!e&&!t)return;let r={...e};for(let[n,i]of Object.entries(t??{})){let o=n.toLowerCase();for(let s of Object.keys(r))if(s.toLowerCase()===o)delete r[s];r[n]=i}return r}class dj{providers=new Map;credentials;modelsStore;authContext;constructor(e){this.credentials=e?.credentials??new hr,this.modelsStore=e?.modelsStore??new Kv,this.authContext=e?.authContext??aj()}setProvider(e){this.providers.set(e.id,e)}deleteProvider(e){this.providers.delete(e)}clearProviders(){this.providers.clear()}getProviders(){return Array.from(this.providers.values())}getProvider(e){return this.providers.get(e)}getModels(e){if(e!==void 0){let r=this.providers.get(e);if(!r)return[];try{return r.getModels()}catch{return[]}}let t=[];for(let r of this.providers.values())try{t.push(...r.getModels())}catch{}return t}getModel(e,t){return this.getModels(e).find((r)=>r.id===t)}async refresh(e={}){let t=e.allowNetwork??!0,r=new Map,n=Array.from(this.providers.values()).filter((i)=>i.refreshModels!==void 0);return await Promise.all(n.map(async(i)=>{if(e.signal?.aborted)return;let o={read:()=>this.modelsStore.read(i.id),write:(a)=>this.modelsStore.write(i.id,a),delete:()=>this.modelsStore.delete(i.id)},s;try{s=await this.readCredential(i.id);let a=await this.resolveRefreshCredential(i,s,t,e.signal);if(!a)return;await i.refreshModels({credential:a,store:o,allowNetwork:t,force:e.force,signal:e.signal})}catch(a){if(!e.signal?.aborted)r.set(i.id,a instanceof Error?a:new Wi("model_source",`Model refresh failed for ${i.id}`,{cause:a}));try{await i.refreshModels({credential:s,store:o,allowNetwork:!1,signal:e.signal})}catch{}}})),{aborted:e.signal?.aborted??!1,errors:r}}async resolveRefreshCredential(e,t,r,n){if(t?.type==="oauth"){let a=e.auth.oauth;if(!a)return;if(!r||Date.now()<t.expires)return t;if(n?.aborted)return;let c=await this.credentials.modify(e.id,async(u)=>{if(u?.type!=="oauth"||Date.now()<u.expires)return;return a.refresh(u,n)});return c?.type==="oauth"?c:void 0}let i=e.auth.apiKey;if(!i)return;let o=t?.type==="api_key"?t:void 0,s=await i.resolve({ctx:this.authContext,credential:o});if(!s)return;return{type:"api_key",key:s.auth.apiKey,env:s.env}}async readCredential(e){try{return await this.credentials.read(e)}catch(t){throw new Wi("auth",`Credential store read failed for ${e}`,{cause:t})}}async checkProviderAuth(e,t){if(t?.type==="oauth")return e.auth.oauth?{source:"OAuth",type:"oauth"}:void 0;let r=e.auth.apiKey;if(!r)return;if(r.check)try{return await r.check({ctx:this.authContext,credential:t?.type==="api_key"?t:void 0})}catch(i){throw new Wi("auth",`API key auth check failed for provider ${e.id}`,{cause:i})}let n=await Gv(e,this.credentials,this.authContext);return n?{source:n.source,type:"api_key"}:void 0}async checkAuth(e){let t=this.providers.get(e);if(!t)return;return this.checkProviderAuth(t,await this.readCredential(e))}async getAvailable(e){let t=e?[this.providers.get(e)].filter((n)=>n!==void 0):this.getProviders();return(await Promise.all(t.map(async(n)=>{let i=await this.readCredential(n.id);return{provider:n,credential:i,auth:await this.checkProviderAuth(n,i)}}))).flatMap(({provider:n,credential:i,auth:o})=>{if(!o)return[];let s=n.getModels();return n.filterModels?.(s,i)??s})}async getAuth(e,t){let r=typeof e==="string"?e:e.provider,n=this.providers.get(r);if(!n)return;let i=await Gv(n,this.credentials,this.authContext,t);if(!i||typeof e==="string"||!e.headers)return i;return{...i,auth:{...i.auth,headers:uj(i.auth.headers,e.headers)}}}async login(e,t,r){let n=this.providers.get(e);if(!n)throw new Wi("provider",`Unknown provider: ${e}`);let i=t==="oauth"?n.auth.oauth:n.auth.apiKey;if(!i?.login)throw new Wi("auth",`${n.name} does not support ${t} login`);let o=await i.login(r);try{await this.credentials.modify(e,async()=>o)}catch(s){throw new Wi("auth",`Credential store modify failed for ${e}`,{cause:s})}return o}async logout(e){try{await this.credentials.delete(e)}catch(t){throw new Wi("auth",`Credential store delete failed for ${e}`,{cause:t})}}requireProvider(e){let t=this.providers.get(e.provider);if(!t)throw new Wi("provider",`Unknown provider: ${e.provider}`);return t}async applyAuth(e,t){this.requireProvider(e);let r=await this.getAuth(e,{apiKey:t?.apiKey,env:t?.env});if(!r)throw new Wi("auth",`Provider is not configured: ${e.provider}`);let n=r.auth,i=t?.apiKey??n.apiKey,o=uj(n.headers,t?.headers);if(t?.transformHeaders)o=await t.transformHeaders(o??{});let s=r.env||t?.env?{...r.env??{},...t?.env??{}}:void 0,a=n.baseUrl?{...e,baseUrl:n.baseUrl}:e,{transformHeaders:c,...u}=t??{},d={...u,apiKey:i,headers:o,env:s};return{requestModel:a,requestOptions:d}}stream(e,t,r){return Yl(e,async()=>{let n=this.requireProvider(e),{requestModel:i,requestOptions:o}=await this.applyAuth(e,r);return n.stream(i,t,o)})}async complete(e,t,r){return this.stream(e,t,r).result()}streamSimple(e,t,r){return Yl(e,async()=>{let n=this.requireProvider(e),{requestModel:i,requestOptions:o}=await this.applyAuth(e,r);return n.streamSimple(i,t,o)})}async completeSimple(e,t,r){return this.streamSimple(e,t,r).result()}}function Tn(e){return new dj(e)}function b(e){let t=e.models,r=[],n,i=e.fetchModels,o=()=>{let d=[...t];for(let f of r){let h=d.findIndex((p)=>p.id===f.id);if(h>=0)d[h]=f;else d.push(f)}return d},s=typeof e.api.stream==="function"?e.api:void 0,a=s?void 0:e.api,c=(d)=>s??a?.[d.api],u=(d,f)=>{let h=c(d);if(!h)return Yl(d,async()=>{throw new Wi("stream",`Provider ${e.id} has no API implementation for "${d.api}"`)});return f(h)};return{id:e.id,name:e.name??e.id,baseUrl:e.baseUrl,headers:e.headers,auth:e.auth,getModels:o,refreshModels:i?(d)=>(n??=(async()=>{try{let f=await d.store.read();if(f)r=f.models.filter((p)=>p.provider===e.id).map((p)=>p);if(!d.allowNetwork||d.signal?.aborted)return;let h=await i(d);if(d.signal?.aborted)return;r=h,await d.store.write({models:h,checkedAt:Date.now()})}finally{n=void 0}})(),n):void 0,filterModels:e.filterModels,stream:(d,f,h)=>u(d,(p)=>p.stream(d,f,h)),streamSimple:(d,f,h)=>u(d,(p)=>p.streamSimple(d,f,h))}}function ie(e,t){let r=t.input+t.cacheRead+t.cacheWrite,n=e.cost,i=-1;for(let a of e.cost.tiers??[])if(r>a.inputTokensAbove&&a.inputTokensAbove>i)n=a,i=a.inputTokensAbove;let o=t.cacheWrite1h??0,s=t.cacheWrite-o;return t.cost.input=n.input/1e6*t.input,t.cost.output=n.output/1e6*t.output,t.cost.cacheRead=n.cacheRead/1e6*t.cacheRead,t.cost.cacheWrite=(n.cacheWrite*s+n.input*2*o)/1e6,t.cost.total=t.cost.input+t.cost.output+t.cost.cacheRead+t.cost.cacheWrite,t.cost}var Mp=["off","minimal","low","medium","high","xhigh","max"];function Yfe(e){if(!e.reasoning)return["off"];return Mp.filter((t)=>{let r=e.thinkingLevelMap?.[t];if(r===null)return!1;if(t==="xhigh"||t==="max")return r!==void 0;return!0})}function Y(e,t){let r=Yfe(e);if(r.includes(t))return t;let n=Mp.indexOf(t);if(n===-1)return r[0]??"off";for(let i=n;i<Mp.length;i++){let o=Mp[i];if(r.includes(o))return o}for(let i=n-1;i>=0;i--){let o=Mp[i];if(r.includes(o))return o}return r[0]??"off"}var yc=-1/0,wc=0;function mwe(e){if(globalThis.crypto?.getRandomValues){globalThis.crypto.getRandomValues(e);return}for(let t=0;t<e.length;t++)e[t]=Math.floor(Math.random()*256)}function Dt(){let e=new Uint8Array(16);mwe(e);let t=Date.now();if(t>yc)wc=e[6]*16777216+e[7]*65536+e[8]*256+e[9],yc=t;else if(wc=wc+1>>>0,wc===0)yc++;let r=new Uint8Array(16);r[0]=yc/1099511627776&255,r[1]=yc/4294967296&255,r[2]=yc/16777216&255,r[3]=yc/65536&255,r[4]=yc/256&255,r[5]=yc&255,r[6]=112|wc>>>28&15,r[7]=wc>>>20&255,r[8]=128|wc>>>14&63,r[9]=wc>>>6&255,r[10]=(wc&63)<<2|e[10]&3,r[11]=e[11],r[12]=e[12],r[13]=e[13],r[14]=e[14],r[15]=e[15];let n=Array.from(r,(i)=>i.toString(16).padStart(2,"0"));return`${n.slice(0,4).join("")}-${n.slice(4,6).join("")}-${n.slice(6,8).join("")}-${n.slice(8,10).join("")}-${n.slice(10,16).join("")}`}
497
+ export{le,q,P,oe,z,me,Jt,L,we,ge,N,ht,Fe,ve,Yt,Xt,wr,be,S,y,l,_e,Zt,vr,ye,D,ut,Ye,U,br,jr,Vr,Xe,T,vt,xe,fe,er,tr,ze,x,he,G,rr,nr,Wr,Jr,Yr,xr,or,sr,dt,Xr,ir,ar,Zr,cr,en,lr,ur,Rr,tn,kr,rn,fn,nn,kn,on,Ue,qe,Ee,Or,Pr,bt,xt,Rt,dr,Mr,Ce,pr,sn,hn,kt,Ar,gn,_n,mr,Dr,Nr,fr,yn,ee,v,K,w,Ot,an,En,cn,Cn,Re,Ge,Pt,Ze,et,Ur,bn,In,Lr,gt,On,Pn,Mn,Sn,xn,Dn,Br,se,Le,hr,_t,gr,Mt,Q,J,Tn,b,ie,Y,Qr,_r,Dt,Nt,ln,Ut};