import{Cookie,Type}from"./Cookie.js";export class CookieParser{constructor(i){i&&(this._domain=i.toLowerCase().replace(/^\./,"")),this._cookies=[],this._input,this._originalInputLength=0}static parseCookie(i){return(new CookieParser).parseCookie(i)}static parseSetCookie(i,t){return new CookieParser(t).parseSetCookie(i)}cookies(){return this._cookies}parseCookie(i){if(!this._initialize(i))return null;for(let t=this._extractKeyValue();t;t=this._extractKeyValue())"$"===t.key.charAt(0)&&this._lastCookie?this._lastCookie.addAttribute(t.key.slice(1),t.value):"$version"!==t.key.toLowerCase()&&"string"===typeof t.value&&this._addCookie(t,Type.Request),this._advanceAndCheckCookieDelimiter();return this._flushCookie(),this._cookies}parseSetCookie(i){if(!this._initialize(i))return null;for(let t=this._extractKeyValue();t;t=this._extractKeyValue())this._lastCookie?this._lastCookie.addAttribute(t.key,t.value):this._addCookie(t,Type.Response),this._advanceAndCheckCookieDelimiter()&&this._flushCookie();return this._flushCookie(),this._cookies}_initialize(i){return this._input=i,"string"===typeof i&&(this._cookies=[],this._lastCookie=null,this._lastCookieLine="",this._originalInputLength=this._input.length,!0)}_flushCookie(){this._lastCookie&&(this._lastCookie.setSize(this._originalInputLength-this._input.length-this._lastCookiePosition),this._lastCookie.setCookieLine(this._lastCookieLine.replace("\n",""))),this._lastCookie=null,this._lastCookieLine=""}_extractKeyValue(){if(!this._input||!this._input.length)return null;const i=/^[ \t]*([^\s=;]+)[ \t]*(?:=[ \t]*([^;\n]*))?/.exec(this._input);if(!i)return console.error("Failed parsing cookie header before: "+this._input),null;const t=new KeyValue(i[1],i[2]&&i[2].trim(),this._originalInputLength-this._input.length);return this._lastCookieLine+=i[0],this._input=this._input.slice(i[0].length),t}_advanceAndCheckCookieDelimiter(){if(!this._input)return!1;const i=/^\s*[\n;]\s*/.exec(this._input);return!!i&&(this._lastCookieLine+=i[0],this._input=this._input.slice(i[0].length),null!==i[0].match("\n"))}_addCookie(i,t){this._lastCookie&&this._lastCookie.setSize(i.position-this._lastCookiePosition),this._lastCookie="string"===typeof i.value?new Cookie(i.key,i.value,t):new Cookie("",i.key,t),this._domain&&this._lastCookie.addAttribute("domain",this._domain),this._lastCookiePosition=i.position,this._cookies.push(this._lastCookie)}}class KeyValue{constructor(i,t,e){this.key=i,this.value=t,this.position=e}}