import*as Common from"../common/common.js";import*as Root from"../root/root.js";import{Cookie}from"./Cookie.js";import{ResourceTreeModel}from"./ResourceTreeModel.js";import{Capability,SDKModel}from"./SDKModel.js";export class CookieModel extends SDKModel{constructor(e){super(e),this._blockedCookies=new Map,this._cookieToBlockedReasons=new Map}addBlockedCookie(e,o){const t=e.key(),s=this._blockedCookies.get(t);this._blockedCookies.set(t,e),this._cookieToBlockedReasons.set(e,o),s&&this._cookieToBlockedReasons.delete(t)}getCookieToBlockedReasonsMap(){return this._cookieToBlockedReasons}async getCookies(e){const o=await this.target().networkAgent().invoke_getCookies({urls:e});if(o.getError())return[];return o.cookies.map(Cookie.fromProtocolCookie).concat(Array.from(this._blockedCookies.values()))}async deleteCookie(e){await this.deleteCookies([e])}async clear(e,o){const t=await this.getCookiesForDomain(e||null);if(o){const e=t.filter((e=>e.matchesSecurityOrigin(o)));await this.deleteCookies(e)}else await this.deleteCookies(t)}async saveCookie(e){let o,t=e.domain();t.startsWith(".")||(t=""),e.expires()&&(o=Math.floor(Date.parse(`${e.expires()}`)/1e3));const s=Root.Runtime.experiments.isEnabled("experimentalCookieFeatures"),r={name:e.name(),value:e.value(),url:e.url()||void 0,domain:t,path:e.path(),secure:e.secure(),httpOnly:e.httpOnly(),sameSite:e.sameSite(),expires:o,priority:e.priority(),sameParty:e.sameParty(),sourceScheme:s?e.sourceScheme():(i=e.sourceScheme(),i===Protocol.Network.CookieSourceScheme.Unset?i:void 0),sourcePort:s?e.sourcePort():void 0};var i;const a=await this.target().networkAgent().invoke_setCookie(r);return!(a.getError()||!a.success)&&a.success}getCookiesForDomain(e){const o=[];const t=this.target().model(ResourceTreeModel);return t&&(t.mainFrame&&t.mainFrame.unreachableUrl()&&o.push(t.mainFrame.unreachableUrl()),t.forAllResources((function(t){const s=Common.ParsedURL.ParsedURL.fromString(t.documentURL);return!s||e&&s.securityOrigin()!==e||o.push(t.url),!1}))),this.getCookies(o)}async deleteCookies(e){const o=this.target().networkAgent();this._blockedCookies.clear(),this._cookieToBlockedReasons.clear(),await Promise.all(e.map((e=>o.invoke_deleteCookies({name:e.name(),url:void 0,domain:e.domain(),path:e.path()}))))}}SDKModel.register(CookieModel,Capability.Network,!1);export let BlockedReason;