1"use strict";(self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[3582],{3184:(e,t,a)=>{a.d(t,{M:()=>u,y:()=>o});var r=a(40534),n=a(98217);function i(e){let t=null==e?void 0:e.trim();if(t)return t}function l(e,t){let a=[],r=new Set;for(let n of[...e,...null!=t?t:[]])!n.url||r.has(n.url)||(r.add(n.url),a.push(n));if(0!==a.length)return a}function o(e,t){if(!t)return{...e};let a=e.title,o=i(t.title);o&&(a=o);let u=(0,n.yG)(t),s=e.image,d=i(t.featuredImage);d?s=d:void 0!==t.featuredImage&&(s=void 0);let c=e.assets;return void 0!==t.attachments&&(c=l((0,r.D)(t.attachments),e.assets)),{...e,assets:c,image:s,methodTitle:u||void 0,title:a}}function u(e,t){var a;if(!e)return t;let r=e.title,n=i(t.title);n&&(r=n);let o=e.methodTitle,u=i(t.methodTitle);u&&(o=u);let s=e.image,d=i(t.image);d&&(s=d);let c=e.assets;return(null==(a=t.assets)?void 0:a.length)&&(c=l(t.assets,e.assets)),{...e,...t,assets:c,image:s,methodTitle:o,title:r}}},7101:(e,t,a)=>{a.d(t,{n:()=>p});var r=a(12115),n=a(75015),i=a(88478),l=a(54658),o=a(99863),u=a(11704),s=a(74454);let d="explorer-metadata",c=[d,"explorer-tags","explorer-categories"];function p(){let{engine:e,isReady:t}=(0,l.RI)(),{tags:a,availableCategories:p}=(0,o.QJ)((0,n.k)(e=>({tags:e.tags,availableCategories:e.availableCategories}))),m=a.length>0&&p.length>0,g=(0,r.useCallback)(async()=>{if(!e)return;let t=()=>{},a=!1;"retainExplorerBackgroundSyncKeysInFlight"in e&&"function"==typeof e.retainExplorerBackgroundSyncKeysInFlight&&(t=e.retainExplorerBackgroundSyncKeysInFlight(c));try{for(let t of(await Promise.all([e.pushAndWait({type:"query",entity:"explorerTags",data:{},kind:"query"}),e.pushAndWait({type:"query",entity:"explorer",data:{action:"getCategories"},kind:"query"})]),c))e.upsertEntityItem("explorerSyncState",t,{lastFetchedAt:Date.now()});a=!0}finally{t(a)}},[e]);(0,s.m)({tabKey:d,enabled:!0,hasSliceData:m,fetch:g}),(0,r.useEffect)(()=>{if(e&&t)try{let t=u.R.getState();t.isSuggestionsStale(i.zI)&&e.push({type:"query",entity:"explorer",data:{action:"suggestIntent"}}),t.isCategoriesStale(i.Pb)&&e.push({type:"query",entity:"explorer",data:{action:"suggestCategory"}})}catch(e){console.error("[ExplorerPageSync] Failed to fetch AI suggestions:",e)}},[e,t])}},17547:(e,t,a)=>{a.d(t,{s:()=>j});var r=a(61324),n=a(69351),i=a(69702),l=a(44457),o=a(87030),u=a(59953),s=a(76689),d=a(89005),c=a(3184),p=a(12986),m=a(60662),g=a(83696),f=a(8486),y=a(82901),h=a(7576),v=a(54617),I=a(97398),S=a(17377),k=a(58637);function T(e,t){let a=(0,v.Bj)(e);if(!a)throw Error("Created Method returned an invalid ".concat(t));return a}function b(e){var t;if(e)return{id:e.id,name:e.displayName,profilePicture:(0,k.sN)({authorId:e.id,avatar:null!=(t=e.avatar)?t:void 0}),isVerified:e.isVerified}}function w(e){return e?{lineageId:e.lineageId,versionId:e.versionId,title:e.title,listingId:e.listingId,author:b(e.author),sourceListingAvailable:e.sourceListingAvailable}:null}function A(e,t){return t||e||"Untitled Method"}function C(e){let t={id:e.id,updatedAt:e.updatedAt};return void 0!==e.versionNumber&&(t.versionNumber=e.versionNumber),t}function P(e){var t,a,r,n,i;let l=null!=(t=e.price)?t:0;return{id:e.defaultApprovedVersionId,lineageId:e.lineageId,defaultApprovedVersionId:e.defaultApprovedVersionId,title:A(e.title,e.methodTitle),methodTitle:null!=(a=e.methodTitle)?a:void 0,methodOutcomeLine:null!=(r=e.methodOutcomeLine)?r:void 0,description:null!=(n=e.description)?n:"",image:null!=(i=e.featuredImage)?i:void 0,duration:(0,S.o)(e.duration,e.durationDays),durationSeconds:e.duration,durationDays:e.durationDays,price:(0,I.b3)(l),priceInCents:l,priceStatus:(0,I.ZS)(l),relationship:e.relationship,acquisition:e.acquisition,availability:e.availability,canUse:e.canUse,category:(0,h.Ac)(e.intentCategories),author:b(e.author),rootSource:w(e.rootSource),currentVersion:C(e.currentVersion),updatedAt:e.currentVersion.updatedAt,hasCompletedPurchase:!0,isTemplate:!0}}function E(e){var t,a,r,n;let i={...a=e.sourceIntent,contentRevision:T(a.contentRevision,"source content revision")};return{id:i.id,lineageId:e.lineageId,title:A(e.title),description:"",image:null!=(t=e.featuredImage)?t:void 0,duration:(0,S.o)(e.duration),durationSeconds:e.duration,relationship:e.relationship,publicationStatus:e.publicationStatus,category:(0,h.Ac)(e.intentCategories),author:b(e.author),rootSource:w(e.rootSource),currentVersion:C(e.currentVersion),sourceIntent:i,liveVersion:(r=e.liveVersion)?{...r,sourceRevision:T(r.sourceRevision,"live source revision")}:null,latestSubmission:(n=e.latestSubmission)?{...n,sourceRevision:T(n.sourceRevision,"submission source revision")}:null,hasChangesSinceSubmission:e.hasChangesSinceSubmission,hasChangesSinceApproval:e.hasChangesSinceApproval,hasPendingSubmission:e.hasPendingSubmission,canPublishChanges:e.canPublishChanges,blockedReason:e.blockedReason,immediateSourceVersionId:e.immediateSourceVersionId,updatedAt:i.updatedAt,isTemplate:!1}}function R(e){let t=new Map;for(let r of e){var a;let e=null!=(a=r.lineageId)?a:r.id;t.has(e)||t.set(e,r)}return Array.from(t.values())}var D=a(60167);function B(e){var t;return!!e&&"object"==typeof e&&"templateIntents"in e&&Array.isArray(null==(t=e.templateIntents)?void 0:t.intents)}function L(){let{itemsPerPage:e}=r.QJ.getState();return e>0?e:12}function _(e,t){let a=r.QJ.getState(),n=new Set(a.bookmarkedTemplates);if(0===n.size)return;let i=new Map(a.bookmarkedTemplateData.map(e=>[e.id,e]));for(let a of t){var l;if(!(null==a?void 0:a.id)||!n.has(a.id))continue;let t=(0,c.M)(i.get(a.id),a);null==(l=e.upsertEntityItem)||l.call(e,"bookmarkedTemplateData",a.id,t),i.set(a.id,t)}}function M(e,t){var a,n,i,l,o,u,s,c;let p=r.QJ.getState(),g=null!=(n=t._bookmarkedMutationRevision)?n:0,f=t.templateIntents.intents.map(y.Z7),h=(0,y.qG)(f),v=f.length-h.length,I=Math.max(h.length,t.templateIntents.totalCount-v),S=null!=(i=t._bookmarkedPage)?i:1,k=null!=(l=t._bookmarkedPageSize)?l:L(),T=null!=(o=t._bookmarkedSortBy)?o:d.Bn,b=t._bookmarkedQuery,w=t._bookmarkedDuration,A=t._bookmarkedPrice,C=(0,d.Qq)({page:S,pageSize:k,sortBy:T,localQuery:b,duration:w,price:A}),P=p.bookmarkMutationsInFlight>0||g!==p.bookmarkMutationRevision;if(P&&!t._bookmarkedTemplateIds)return;let E=h,R=I,D=!1;if(P){let e=function(e){var t;let a=new Set(e.requestedBookmarkedIds),r=new Set(e.currentBookmarkedIds),n=new Set;for(let e of a)r.has(e)||n.add(e);let i=e.responseTemplates.filter(e=>!n.has(e.id)),l=new Set(i.map(e=>e.id)),o=[];if(null==(t=e.existingPage)?void 0:t.isOptimistic)for(let t of e.existingPage.templates)!n.has(t.id)&&(l.has(t.id)||o.push(t));let u=[...i,...o];1===e.page&&e.sortBy===d.Bn&&(u=[...o,...i]);let s=e.responseTotalCount;if("number"==typeof e.localTotalCount)s=e.localTotalCount;else{let t=new Set;for(let e of r)a.has(e)||t.add(e);
1s=Math.max(0,e.responseTotalCount-n.size+t.size)}return{isOptimistic:!0,templates:function(e){let t=new Set,a=[];for(let r of e)!r.id||t.has(r.id)||(t.add(r.id),a.push(r));return a}(u),totalCount:s}}({currentBookmarkedIds:p.bookmarkedTemplates,existingPage:p.bookmarkTemplatePagesByKey[C],localTotalCount:p.bookmarksTotalCount,requestedBookmarkedIds:null!=(u=t._bookmarkedTemplateIds)?u:[],responseTemplates:h,responseTotalCount:I,page:S,sortBy:T});E=e.templates,R=e.totalCount,D=e.isOptimistic}let B={id:C,page:S,pageSize:k,sortBy:T,metadataVersion:d._f,localQuery:b,duration:w,price:A,templates:E,totalCount:R,lastFetchedAt:Date.now()};D&&(B.isOptimistic=!0);let _=(0,m.K8)(B),M=new Map;for(let e of p.bookmarkedTemplateData)M.set(e.id,e);for(let e of E)M.set(e.id,e);for(let t of(p.setBookmarkedTemplateData(Array.from(M.values())),b||w||A||!_?b||w||A||(p.setBookmarksLoadedPage(null),p.setBookmarksLoadedSortBy(null),p.setBookmarksHydrated(!1)):(p.setBookmarksTotalCount(R),p.setBookmarksLoadedPage(S),p.setBookmarksLoadedSortBy(T),p.setBookmarksHydrated(!0)),p.setBookmarkTemplatePage(B),null==(a=e.upsertEntityItem)||a.call(e,"explorerBookmarkTemplatePage",B.id,B),E))(null==t?void 0:t.id)&&(null==(s=e.upsertEntityItem)||s.call(e,"bookmarkedTemplateData",t.id,t),null==(c=e.upsertEntityItem)||c.call(e,"bookmarkedTemplate",t.id,{}));if(_){let e=Math.ceil(R/k);p.setTotalPages(e||1)}p.setIsLoading(!1)}function U(e,t){if("author-profile-methods"!==e.scope||void 0===e.page||e.pageSize!==t.pageSize)return!1;let a=(0,d.Ey)({scope:"author-profile-methods",searchType:"methods",filters:{authorId:t.authorId,sortBy:t.sortBy},page:e.page,pageSize:t.pageSize});return"public"===t.audience&&(a=(0,d.Ey)({scope:"author-profile-methods",searchType:"methods",filters:{audience:t.audience,authorId:t.authorId,sortBy:t.sortBy},page:e.page,pageSize:t.pageSize})),e.id===a}function q(e,t,a){var n,i;if(!t._queryPageCacheKey||!t._queryPageScope)return;let l=(0,p.K)({page:t._queryPagePage,pageSize:t._queryPagePageSize,templates:t.templateIntents.intents,totalCount:t.templateIntents.totalCount||0},{page:t._queryPagePage,pageSize:t._queryPagePageSize}),o={id:t._queryPageCacheKey,scope:t._queryPageScope,page:t._queryPagePage,pageSize:t._queryPagePageSize,templates:a,totalCount:t.templateIntents.totalCount||0,sourceTotalCount:t.templateIntents.totalCount||0,sourceRowCount:t.templateIntents.intents.length,hasMore:l.hasMore,isTerminal:l.isTerminal,lastFetchedAt:Date.now()},u=r.QJ.getState(),s=[o],d=[];if("author-profile-methods"===o.scope&&t._authorId&&o.pageSize){let e=function(e,t,a){var r,n;let i=[],l=[],o=null!=(r=t.sourceTotalCount)?r:t.totalCount;for(let r of e)if(r.id!==t.id){if(!U(r,a)){"public"===a.audience&&U(r,{authorId:a.authorId,pageSize:a.pageSize,sortBy:a.sortBy})&&l.push(r.id);continue}if((null!=(n=r.sourceTotalCount)?n:r.totalCount)!==o){l.push(r.id);continue}i.push(r)}i.push(t);let u=t.totalCount;for(let e of i)!0===e.isTerminal&&(u=Math.min(u,(0,m.qM)(e)));return{pagesToPersist:i.map(e=>e.totalCount===u&&e.sourceTotalCount===o?e:{...e,sourceTotalCount:o,totalCount:u}),stalePageIds:l}}(Object.values(u.templateQueryPagesByKey),o,{audience:t._authorAudience,authorId:t._authorId,pageSize:o.pageSize,sortBy:t._authorSortBy});s=e.pagesToPersist,d=e.stalePageIds}if(d.length>0){let t=new Set(d);for(let a of t)null==(n=e.removeEntityItem)||n.call(e,"explorerTemplateQueryPage",a);let a=Object.values(u.templateQueryPagesByKey).filter(e=>!t.has(e.id));u.setTemplateQueryPages(a)}let c=o;for(let t of s)u.setTemplateQueryPage(t),null==(i=e.upsertEntityItem)||i.call(e,"explorerTemplateQueryPage",t.id,t),t.id===o.id&&(c=t);return c}function x(e,t){return e&&t?e.intentId===t.intentId&&e.reviewRequestId===t.reviewRequestId&&e.reviewStatus===t.reviewStatus&&e.sourceRevision===t.sourceRevision&&e.submittedAt===t.submittedAt:e===t}function F(e,t,a){let i=arguments.length>3&&void 0!==arguments[3]?arguments[3]:1,l=(0,n.R)({scope:t,authorId:e,page:i,pageSize:a});return r.QJ.getState().authorTemplatePagesByKey[l]}function O(e,t,a){return e.map(e=>{let r=F(e.id,t,a);return r?{...e,templates:r.templates}:e})}function Q(e,t,a){return e.filter(e=>!F(e,t,a))}function N(e,t){var a;t&&(null==(a=e.upsertEntityItem)||a.call(e,"explorerSyncState",t,{lastFetchedAt:Date.now()}))}function j(e){let t=0,a={"home-authors":null,"followed-authors":null};return e.registerStateUpdater("bookmarkedTemplates",t=>{if(!Array.isArray(t))return;let a=t.map(e=>e.id);r.QJ.getState().setBookmarkedTemplates(a);
1let n=new Set(a);if(0===n.size)return;let i=r.QJ.getState();for(let t of[...i.templates,...i.featuredTemplates,...i.myTemplates,...i.followingUserTemplates]){var l;(null==t?void 0:t.id)&&n.has(t.id)&&(null==(l=e.upsertEntityItem)||l.call(e,"bookmarkedTemplateData",t.id,t))}}),e.registerStateUpdater("ratedTemplates",e=>{if(!Array.isArray(e))return;let t=Object.fromEntries(e.map(e=>[e.id,e.rating]));r.QJ.getState().setUserTemplateRatings(t)}),e.registerStateUpdater("explorerCategoryCatalog",e=>{Array.isArray(e)&&r.QJ.getState().setAvailableCategories(e)}),e.registerStateUpdater("explorerTemplates",t=>{if(!B(t))return;if(t._isBookmarkedQuery)return void M(e,t);let a=(0,y.G6)(t.templateIntents.intents),n=r.QJ.getState();n.setTemplates(a),_(e,a);let i=Math.ceil(t.templateIntents.intents.length/12);n.setTotalPages(i||1)}),e.registerStateUpdater("myTemplates",t=>{if(!t||"object"!=typeof t||!("templateIntents"in t))return;let a=(0,y.N0)(t.templateIntents.intents);r.QJ.getState().setMyTemplates(a),_(e,a)}),e.registerStateUpdater("explorerTags",e=>{e&&"object"==typeof e&&"tags"in e&&r.QJ.getState().mergeTags(e.tags)}),e.registerStateUpdater("userFollowing",t=>{if(!(null==t?void 0:t.getFollowing)||0===t.getFollowing.length||t.id)return;let a=t.getFollowing.map(e=>e.id);for(let t of a){var n;null==(n=e.upsertEntityItem)||n.call(e,"followedAuthor",t,{})}r.QJ.getState().mergeFollowedAuthors(a)}),e.registerStateUpdater("explorer",c=>{var m,h,I,S,k,T,b,w,A,C,D,U,j,K,V;if(!c||"object"!=typeof c)return;let W=r.QJ.getState();if("bookmarksTotalCount"in c){let{bookmarksTotalCount:e}=c;"number"==typeof e&&W.setBookmarksTotalCount(e)}if("getTemplateDetails"in c&&c.getTemplateDetails){let e=(0,u.o)((0,o.e)(c.getTemplateDetails));W.setSelectedTemplateDetails(e)}if("userMerchantStatus"in c&&W.setMerchantStatus(null!=(h=null==(m=c.userMerchantStatus)?void 0:m.merchantStatus)?h:null),"currentUser"in c&&W.setCurrentUser({...c.currentUser,name:c.currentUser.firstName+" "+c.currentUser.lastName}),"listAuthors"in c){let n,o=c._listAuthorsScope,u="followed-authors"===o,s=!!c._includeTemplatePreviews,d=r.QJ.getState().followedAuthors,p=c.listAuthors.authors.map(e=>{let t=(0,l.X)(e),a=d.includes(e.id);return u&&(a=!0),{id:t.id,name:t.name||"",avatar:t.avatar,profilePicture:t.profilePicture,description:e.description||"",isVerified:t.isVerified,isFollowing:a}});for(let t of p)!function(e,t){var a;if(!t.id)return;let n={id:t.id,author:t,lastFetchedAt:Date.now()};r.QJ.getState().setAuthorProfilePage(n),null==(a=e.upsertEntityItem)||a.call(e,"explorerAuthorProfile",n.id,n)}(e,t);if("serp"===o){if(c._authorSearchCacheKey){let t={id:c._authorSearchCacheKey,authors:p,totalCount:c.listAuthors.totalCount||0,lastFetchedAt:Date.now()};W.setAuthorSearchPage(t),null==(I=e.upsertEntityItem)||I.call(e,"explorerAuthorSearchPage",t.id,t)}return}let m=(n,l,o)=>{if(!e.pushAndWait){r.QJ.getState().setIsLoading(!1),N(e,o);return}let u=++t;a[l]={id:u,authorIds:n,freshnessTabKey:o},(async()=>{var t,o;try{let a;await (t=e.pushAndWait({type:"query",entity:"explorer",kind:"query",data:{action:"getAuthorTemplatePreviews",authorIds:n,page:1,pageSize:i.F5,scope:l,_authorPreviewsRequestId:u}}),Promise.race([t,new Promise((e,t)=>{a=setTimeout(()=>{t(Error("Author template preview hydration timed out"))},i.JE)})]).finally(()=>{a&&clearTimeout(a)}))}catch(e){(null==(o=a[l])?void 0:o.id)===u&&r.QJ.getState().setIsLoading(!1)}})()};if(u){let t,r="followed-authors";p=O(p,r,i.F5),W.setFollowedAuthorsList(p);let n=c._authorListViewKey;if(!n&&c._isDefaultFollowedAuthorsQuery&&(n="followed-authors-default"),W.setFollowedAuthorsView(null!=n?n:null),W.setFollowedAuthorsTotalCount(c.listAuthors.totalCount),c._isDefaultFollowedAuthorsQuery){let e=c.listAuthors.authors.map(e=>e.id);W.mergeFollowedAuthors(e),0===c.listAuthors.authors.length&&(W.setFollowingUserTemplates([]),W.setFollowingUserTotalCount(0))}let l=Q(p.map(e=>e.id),r,i.F5);c._isDefaultFollowedAuthorsQuery&&(t="authors-you-follow-author-ids",s&&(t="authors-you-follow-authors")),s&&l.length>0?m(l,r,t):(a["followed-authors"]=null,W.setIsLoading(!1),N(e,t));return}let g="home-authors";p=O(p,g,i.F5),W.setAuthors(p);let f=c._authorListViewKey;!f&&c._isDefaultHomeAuthorsQuery&&(f="home-authors-default"),W.setAuthorsView(null!=f?f:null);let y=Q(p.map(e=>e.id),g,i.F5);c._isDefaultHomeAuthorsQuery&&(n="home-authors"),s&&y.length>0?m(y,g,n):(a["home-authors"]=null,W.setIsLoading(!1),N(e,n))}if("authorTemplatePreviews"in c){let t=c._authorPreviewsScope,l=c._authorPreviewsRequestId,o=c.authorTemplatePreviews||{},u=r.QJ.getState(),s=null!=(S=c._authorPreviewsPage)?S:1,d=null!=(k=c._authorPreviewsPageSize)?k:i.F5;if(c._cacheAuthorPreviews&&function(e,t,a,n){let l=r.QJ.getState();for(let[r,p]of Object.entries(t)){var o,u,s,d,c;let t=(0,i.KH)(p),m=null!=(u=l.authorTemplatesByAuthorId[r])?u:[],g=(0,i.KL)(m,t,a,n),f=Math.max(null!=(s=l.authorTemplateTotalCountsByAuthorId[r])?s:0,null!=(d=p.totalCount)?d:g.length),y=(0,i.Y6)(null!=(c=l.authorMethodPreviewLoadedPagesByAuthorId[r])?c:[],a),h=Date.now();l.setAuthorTemplates(r,g,f,{lastFetchedAt:h,loadedPages:y,replaceExisting:!0}),null==(o=e.upsertEntityItem)||o.call(e,"explorerAuthorMethodPreview",r,{id:r,authorId:r,templates:g,totalCount:f,loadedPages:y,lastFetchedAt:h,replaceFetchedPages:!0})}}(e,o,s,d),!t||"serp"===t)return;!function(e,t,a,l,o){var u,s,d;let c=r.QJ.getState(),p=[];for(let[e,r]of Object.entries(a)){let a=(0,i.KH)(r),d=F(e,t,o,l),c=new Map((null!=(u=null==d?void 0:d.templates)?u:[]).map(e=>[e.id,e])),m=a.map(e=>{let t=c.get(e.id);return t?(0,g.l)(t,e):e}),f={id:(0,n.R)({scope:t,authorId:e,page:l,pageSize:o}),scope:t,authorId:e,page:l,pageSize:o,templates:m,totalCount:null!=(s=r.totalCount)?s:0,lastFetchedAt:Date.now()};p.push(f)}if(0!==p.length)for(let t of(c.mergeAuthorTemplatePages(p),p))null==(d=e.upsertEntityItem)||d.call(e,"explorerAuthorTemplatePage",t.id,t)}(e,t,o,s,d);let p=a[t];if(!p||p.id!==l)return;let m=new Set(p.authorIds),f=e=>e.map(e=>m.has(e.id)&&Object.prototype.hasOwnProperty.call(o,e.id)?{...e,templates:(0,i.KH)(o[e.id])}:e);"followed-authors"===t?(u.setFollowedAuthorsList(f(u.followedAuthorsList)),u.setFollowedAuthorsView(u.followedAuthorsView),u.setIsLoading(!1),N(e,p.freshnessTabKey),a["followed-authors"]=null):"home-authors"===t&&(u.setAuthors(f(u.authors)),u.setAuthorsView(u.authorsView),u.setIsLoading(!1),N(e,p.freshnessTabKey),a["home-authors"]=null)}let z=function(e){let t;if(Array.isArray(e))t=e;else if(e&&"object"==typeof e)if("data"in e&&"object"==typeof e.data){let a=e.data;a&&Array.isArray(a.categories)&&(t=a.categories)}else"categories"in e&&Array.isArray(e.categories)&&(t=e.categories);return void 0===t?null:t.filter(e=>"object"==typeof e&&null!==e&&"name"in e&&"icon"in e&&"type"in e&&"id"in e)}(c);if(null!==z&&(r.QJ.getState().setAvailableCategories(z),null==(V=e.replaceEntityItems)||V.call(e,"explorerCategoryCatalog",z)),"suggestCategory"in c&&c.suggestCategory.length>0){let e=c.suggestCategory.map(e=>({id:e.id,name:e.name,type:e.type}));W.setSuggestedCategories(e),r.RD.getState().setSuggestedCategories(e)}if("suggestIntent"in c&&c.suggestIntent.length>0){let e=c.suggestIntent.map(e=>({text:e.title,type:"suggested",rationale:e.rationale||""}));r.RD.getState().setSuggestions(e),W.setSearchSuggestions(c.suggestIntent.map(e=>e.title))}if("titleSuggestions"in c){let t=null!=(T=c.titleSuggestions)?T:[];if(c._titleSuggestionsCacheKey){let a={id:c._titleSuggestionsCacheKey,searchQuery:null!=(w=c._titleSuggestionsSearch)?w:"",suggestions:t,lastFetchedAt:Date.now()};W.setTitleSuggestionsPage(a),null==(b=e.upsertEntityItem)||b.call(e,"explorerTitleSuggestions",a.id,a)}}if("userTemplateReviews"in c){for(let t of c.userTemplateReviews)t.bookmark?null==(A=e.upsertEntityItem)||A.call(e,"bookmarkedTemplate",t.templateId,{}):(null==(C=e.removeEntityItem)||C.call(e,"bookmarkedTemplate",t.templateId),null==(D=e.removeEntityItem)||D.call(e,"bookmarkedTemplateData",t.templateId));c.userTemplateReviews.filter(e=>e.rating>
10).forEach(t=>{var a;null==(a=e.upsertEntityItem)||a.call(e,"ratedTemplate",t.templateId,{rating:t.rating})})}if("searchIntent"in c&&c._isMyMethods){let e=c.searchIntent.intents.filter(e=>!e.isTemplate).map(y.Z7);W.setMyMethods(e),W.setIsLoading(!1)}if("templatePublicationState"in c){let t=(0,v.BO)(c.templatePublicationState);if(!t)return void W.setError("Unable to load the current publishing state.");let a={...t,id:t.sourceIntentId,lastFetchedAt:Date.now()},r=W.templatePublicationStatesBySourceId[a.sourceIntentId];return r&&!(r.blockedReason===a.blockedReason&&r.canPublish===a.canPublish&&r.canPublishChanges===a.canPublishChanges&&r.hasChangesSinceApproval===a.hasChangesSinceApproval&&r.hasChangesSinceSubmission===a.hasChangesSinceSubmission&&r.hasPendingSubmission===a.hasPendingSubmission&&r.hasUnpublishedChanges===a.hasUnpublishedChanges&&r.latestApprovedRevision===a.latestApprovedRevision&&r.latestReviewStatus===a.latestReviewStatus&&r.latestSubmissionId===a.latestSubmissionId&&r.latestSubmittedRevision===a.latestSubmittedRevision&&r.lineageId===a.lineageId&&r.liveTemplateId===a.liveTemplateId&&r.pendingTemplateId===a.pendingTemplateId&&r.sourceIntentId===a.sourceIntentId&&r.sourceRevision===a.sourceRevision&&x(r.latestSubmission,a.latestSubmission)&&x(r.liveVersion,a.liveVersion))&&function(e,t){let a=Object.values(t.templateQueryPagesByKey).filter(e=>"created-methods"===e.scope).map(e=>e.id),r=new Set(a);for(let t of a){var n;null==(n=e.removeEntityItem)||n.call(e,"explorerTemplateQueryPage",t)}let i=Object.values(t.templateQueryPagesByKey).filter(e=>!r.has(e.id));t.setTemplateQueryPages(i);let l={...t.tabSyncState};delete l["my-methods"],t.setTabSyncState(l)}(e,W),W.setTemplatePublicationState(a),W.setError(null),void(null==(U=e.upsertEntityItem)||U.call(e,"templatePublicationState",a.id,a))}if("createdMethods"in c)return void function(e,t){var a;if(!t._queryPageCacheKey||!t._queryPageScope)return;let n=R(t.createdMethods.methods.map(E)),i=(0,p.K)({page:t._queryPagePage,pageSize:t._queryPagePageSize,templates:n,totalCount:t.createdMethods.totalCount||0},{page:t._queryPagePage,pageSize:t._queryPagePageSize}),l={id:t._queryPageCacheKey,scope:t._queryPageScope,page:t._queryPagePage,pageSize:t._queryPagePageSize,templates:n,totalCount:t.createdMethods.totalCount||0,hasMore:i.hasMore,isTerminal:i.isTerminal,lastFetchedAt:Date.now()},o=r.QJ.getState();o.setTemplateQueryPage(l),o.setIsLoading(!1),o.setIsValidating(!1),null==(a=e.upsertEntityItem)||a.call(e,"explorerTemplateQueryPage",l.id,l),function(e,t){let a=Object.values(t.templateQueryPagesByKey).map((e,t)=>({insertionIndex:t,page:e})).filter(e=>"created-methods"===e.page.scope);if(a.length<=d._k)return;a.sort((e,t)=>{let a=t.page.lastFetchedAt-e.page.lastFetchedAt;return 0!==a?a:t.insertionIndex-e.insertionIndex});let r=new Set(a.slice(d._k).map(e=>e.page.id));for(let t of r){var n;null==(n=e.removeEntityItem)||n.call(e,"explorerTemplateQueryPage",t)}let i=Object.values(t.templateQueryPagesByKey).filter(e=>!r.has(e.id));t.setTemplateQueryPages(i)}(e,r.QJ.getState())}(e,c);if("myLibraryTemplates"in c)return void function(e,t){var a;if(!t._queryPageCacheKey||!t._queryPageScope)return;let n=R(t.myLibraryTemplates.templates.map(P)),i=(0,p.K)({page:t._queryPagePage,pageSize:t._queryPagePageSize,templates:n,totalCount:t.myLibraryTemplates.totalCount||0},{page:t._queryPagePage,pageSize:t._queryPagePageSize}),l={id:t._queryPageCacheKey,scope:t._queryPageScope,page:t._queryPagePage,pageSize:t._queryPagePageSize,templates:n,totalCount:t.myLibraryTemplates.totalCount||0,hasMore:i.hasMore,isTerminal:i.isTerminal,lastFetchedAt:Date.now()},o=r.QJ.getState();o.setTemplateQueryPage(l),o.setIsLoading(!1),o.setIsValidating(!1),null==(a=e.upsertEntityItem)||a.call(e,"explorerTemplateQueryPage",l.id,l),_(e,n)}(e,c);if(B(c)){let t=!0===c._isMyTemplates,a=!0===c._isFeaturedQuery,n=!0===c._isFollowingUserTemplatesQuery,i=!0===c._isAuthorTemplatesQuery,l=!0===c._isSerpAuthorPreviewQuery,o=!0===c._isBookmarkedQuery;if(l)return;if(o)return void M(e,c);let u=(0,y.G6)(c.templateIntents.intents);if("quick-action-preview"===c._queryPageSource&&(u=(0,y.bP)(c.templateIntents.intents)),t&&(u=(0,y.N0)(c.templateIntents.intents)),"owner-published-methods"===c._queryPageScope){let e=new Set(u.map(e=>e.id)),t=[];if(c._queryPageCacheKey){let e=W.templateQueryPagesByKey[c._queryPageCacheKey];e&&t.push(...e.templates)}
1for(let a of W.myTemplates)e.has(a.id)&&t.push(a);u=(0,f.W)(u,t)}if(a)q(e,c,u),W.setFeaturedTemplates(u),W.setFeaturedTotalCount(c.templateIntents.totalCount||0),null==(j=e.replaceEntityItems)||j.call(e,"featuredTemplateData",u),_(e,u);else if(t)q(e,c,u),!0!==c._isMyTemplatesCacheable&&W.setMyTemplates(u),W.setMyTemplatesTotalCount(c.templateIntents.totalCount||0),W.setIsLoading(!1),W.setIsValidating(!1),_(e,u);else if(n)q(e,c,u),W.setFollowingUserTemplates(u),W.setFollowingUserTotalCount(c.templateIntents.totalCount||0),W.setIsLoading(!1),W.setIsValidating(!1),_(e,u);else if(i){let t=q(e,c,u);if(c._authorId){let a=c.templateIntents.totalCount||0;t&&(a=t.totalCount),W.setAuthorTemplates(c._authorId,u,a),_(e,u)}W.setIsLoading(!1),W.setIsValidating(!1)}else if(function(e,t,a){var n,i,l,o,u,d;if(!t._categoryId)return!1;let c=null!=(i=t._categoryPage)?i:1,p=null!=(l=t._categoryPageSize)?l:L(),m=t._categoryQuery,g=t._categoryDuration,f=t._categoryPrice,y=t._categoryCacheKey;y||(y=(0,s.I)({categoryId:t._categoryId,page:c,pageSize:p,sortBy:t._categorySortBy,localQuery:m,duration:g,price:f}));let h={id:y,categoryId:t._categoryId,page:c,pageSize:p,sortBy:t._categorySortBy,localQuery:m,duration:g,price:f,templates:a,totalCount:t.templateIntents.totalCount||0,sourceRowCount:t.templateIntents.intents.length,isTerminal:t.templateIntents.intents.length<p||c*p>=t.templateIntents.totalCount,lastFetchedAt:Date.now()},v=r.QJ.getState();v.setCategoryTemplatePage(h);let I=v.currentTab||"home",S=v.tabSortBy[I],k="home"===I&&"methods"===v.searchType&&v.filters.categoryId===h.categoryId&&v.currentPage===h.page&&S===h.sortBy&&(null!=(o=v.moduleFilterQueriesByKey["category:".concat(h.categoryId)])?o:"")===(null!=(u=h.localQuery)?u:"")&&v.filters.duration===h.duration&&v.filters.price===h.price&&!v.filters.tagId&&!v.searchQuery&&!v.isFeaturedBrowseActive;if(k){v.setTemplates(a),v.setTemplatesView(null!=(d=t._view)?d:"category:".concat(t._categoryId)),v.setTotalCount(h.totalCount);let e=Math.ceil(h.totalCount/L());v.setTotalPages(e||1),v.setTemplatesLastFetchedAt(h.lastFetchedAt)}return k&&(v.setIsLoading(!1),v.setIsValidating(!1)),null==(n=e.upsertEntityItem)||n.call(e,"explorerCategoryTemplatePage",y,h),!0}(e,c,u))_(e,u);else if(function(e,t,a){var n,i,l,o,u,s,c;if(!t._tagId)return!1;let p=null!=(i=t._tagPage)?i:1,m=null!=(l=t._tagPageSize)?l:L(),g=null!=(o=t._tagIds)?o:[t._tagId],f=t._tagQuery,y=null!=(u=t._tagCacheKey)?u:(0,d.Cr)({tagId:t._tagId,fetchedTagIds:g,page:p,pageSize:m,sortBy:t._tagSortBy,localQuery:f}),h={id:y,tagId:t._tagId,fetchedTagIds:g,page:p,pageSize:m,sortBy:t._tagSortBy,localQuery:f,templates:a,totalCount:t.templateIntents.totalCount||0,lastFetchedAt:Date.now()},v=r.QJ.getState();v.setTagTemplatePage(h);let I=v.currentTab||"home",S=v.tabSortBy[I];return"home"!==I||"methods"!==v.searchType||v.filters.tagId!==h.tagId||v.currentPage!==h.page||S!==h.sortBy||(null!=(s=v.moduleFilterQueriesByKey["tag:".concat(h.tagId)])?s:"")!==(null!=(c=h.localQuery)?c:"")||v.filters.categoryId||v.filters.duration||v.filters.price||v.searchQuery||v.isFeaturedBrowseActive||(v.setIsLoading(!1),v.setIsValidating(!1)),null==(n=e.upsertEntityItem)||n.call(e,"explorerTagTemplatePage",y,h),!0}(e,c,u))q(e,c,u),_(e,u);else if(!1===c._projectToActiveTemplates)q(e,c,u),_(e,u);else{q(e,c,u),W.setTemplates(u),_(e,u),r.QJ.getState().setTemplatesView(null!=(K=c._view)?K:null),W.setTotalCount(c.templateIntents.totalCount||0);let t=Math.ceil((c.templateIntents.totalCount||c.templateIntents.intents.length)/L());W.setTotalPages(t||1),W.setTemplatesLastFetchedAt(Date.now()),W.setIsLoading(!1),W.setIsValidating(!1)}}}),e.registerStateUpdater("intent",e=>{if(!e||"object"!=typeof e)return;let t=Array.isArray(e)?e:[e],a=r.QJ.getState();for(let e of t){var n,i;if(!e||"object"!=typeof e)continue;let t=function(e){if("number"==typeof e){if(!Number.isFinite(e))return;return(0,D.X)(e)}if("string"==typeof e){let t=Number.parseFloat(e);if(!Number.isFinite(t))return;return(0,D.X)(t)}}(e.rating);if((null==(n=a.selectedTemplateDetails)?void 0:n.id)===e.id){let r={...a.selectedTemplateDetails};e.categories&&(r.intentCategories=e.categories),void 0!==e.title&&(r.title=e.title),void 0!==e.rationale&&(r.rationale=e.rationale),void 0!==e.outcome&&null!==e.outcome&&(r.outcome=e.outcome,r.methodOutcomeLine=e.outcome),void 0!==e.description&&null!==e.description&&(r.description=e.description),void 0!==e.overview&&null!==e.overview&&(r.overview=e.overview),void 0!==e.featuredImage&&(r.featuredImage=e.featuredImage),void 0!==t&&(r.rating=t),a.setSelectedTemplateDetails({...a.selectedTemplateDetails,...r})}if((null==(i=a.selectedTemplateDetails)?void 0:i.goalId)===e.id){let r={};void 0!==e.duration&&(r.duration=e.duration,r.durationDays=Math.ceil(e.duration/86400)),void 0!==e.title&&(r.goalName=e.title),void 0!==e.featuredImage&&(r.featuredImage=e.featuredImage),void 0!==e.price&&(r.price=e.price),void 0!==t&&(r.rating=t),e.categories&&(r.intentCategories=e.categories),Object.keys(r).length>0&&a.setSelectedTemplateDetails({...a.selectedTemplateDetails,...r})}}}),()=>{e.unregisterStateUpdater("bookmarkedTemplates"),e.unregisterStateUpdater("ratedTemplates"),e.unregisterStateUpdater("explorerCategoryCatalog"),e.unregisterStateUpdater("explorerTemplates"),e.unregisterStateUpdater("explorerAuthors"),e.unregisterStateUpdater("explorerTags"),e.unregisterStateUpdater("myTemplates"),e.unregisterStateUpdater("explorer"),e.unregisterStateUpdater("userFollowing"),e.unregisterStateUpdater("intent")}}},44794:(e,t,a)=>{a.d(t,{Ly:()=>n,TK:()=>i,jW:()=>l});var r=a(16902);let n=r.Ikc({key:r.YjP().refine(e=>e.trim().length>0),isEnabled:r.zMY(),audience:r.k5n(["FRONTEND","BACKEND","BOTH"]),isActive:r.zMY()}),i=r.Ikc({success:r.euz(!0),data:r.Ikc({featureFlags:r.YOg(n)})}),l=r.Ikc({success:r.euz(!0),data:r.Ikc({upsertFeatureFlag:r.euz(!0)})})},73582:(e,t,a)=>{a.d(t,{Yq:()=>tP,q2:()=>l,fU:()=>s,iZ:()=>u,hl:()=>g,a$:()=>eZ,mM:()=>e0.m,IY:()=>e4,Bg:()=>f,lN:()=>e7,Cb:()=>e6,dy:()=>ti,US:()=>tl,Qj:()=>e9,Mv:()=>
1td,Xu:()=>ty,Xt:()=>e8,qO:()=>tS,Wd:()=>tk,H0:()=>tT,ge:()=>tb,$5:()=>tA});var r=a(12115),n=a(54658),i=a(61324);let l=()=>{let{engine:e,isReady:t}=(0,n.RI)(),a=(0,i.Xs)(e=>e.resetsAt),l=(0,i.Xs)(e=>e.setRefreshError),o=(0,i.Xs)(e=>e.setRunLimit),u=(0,r.useRef)(null),s=(0,r.useCallback)(()=>{if(!e||!t||u.current)return;l(null);let a=e.pushAndWait({type:"query",entity:"aiRunLimit",kind:"query",data:{_requireFreshRead:!0,action:"getMyAiRunLimit"}}).catch(e=>{l((0,i.Vw)(e))}).finally(()=>{u.current===a&&(u.current=null)});u.current=a},[e,t,l]);(0,r.useEffect)(()=>{if(e&&t)return e.registerStateUpdater("aiRunLimit",e=>{e&&"object"==typeof e&&"myAiRunLimit"in e&&o(e.myAiRunLimit)}),()=>{e.unregisterStateUpdater("aiRunLimit")}},[e,t,o]),(0,r.useEffect)(()=>{if(!e||!t)return;let r=(0,i.mU)(a);if(null===r)return;let n=r.getTime();function l(){Date.now()<n||s()}window.addEventListener("focus",l);let o=n-Date.now(),u=null;return o<=0?s():u=window.setTimeout(s,o),()=>{window.removeEventListener("focus",l),null!==u&&window.clearTimeout(u)}},[e,t,s,a])};var o=a(2294);function u(){let e=(0,i.kH)(e=>e.currentUserId),t=(0,i.kH)(e=>e.usersById),a=(0,o.e)();return{user:e?t[e]:null,isLoading:a}}function s(){let{user:e,isLoading:t}=u();return(0,r.useMemo)(()=>{var a;let r=(a=null==e?void 0:e.connectedCalendarData,t||void 0===a?{status:"loading",email:null,sub:null}:null===a?{status:"disconnected"}:a.isReauthRequired?{status:"reauth_required",email:a.email,sub:a.sub}:a.isProvisioning?{status:"provisioning",email:a.email,sub:a.sub}:{status:"connected",email:a.email,sub:a.sub}),n=null;return("connected"===r.status||"reauth_required"===r.status||"provisioning"===r.status)&&(n=r.email),{state:r,isHealthy:"connected"===r.status,needsReauth:"reauth_required"===r.status,email:n,isLoading:"loading"===r.status}},[null==e?void 0:e.connectedCalendarData,t])}var d=a(19439),c=a(8948),p=a(43567);function m(e,t,a,r){i.Sj.getState().updateEvent(t,a),e.upsertEntityItem("event",t,a),r&&(0,p.Ow)(r,e)}let g=e=>{let t=(0,r.useRef)(!1),a=(0,r.useRef)(i.Sj.getState());(0,r.useEffect)(()=>i.Sj.subscribe(e=>{a.current=e}),[]);let l=(0,r.useCallback)(t=>{let{setEvents:r,setLoading:n,setError:l}=a.current;if(t&&"object"==typeof t&&"events"in t){let e=null;Array.isArray(t.events)?e=t.events:t.events&&"object"==typeof t.events&&"events"in t.events&&Array.isArray(t.events.events)&&(e=t.events.events),e&&(r(e.map(e=>(0,i._)(e))),n(!1));return}if(!t||"object"!=typeof t||!("scheduleEvent"in t)&&!("rescheduleEvent"in t)&&!("autoSchedule"in t)&&!("confirmSchedule"in t)){if(t&&"object"==typeof t&&"bulkRescheduleEvent"in t){var o,u;let r=(null==(o=t.bulkRescheduleEvent)?void 0:o.__correlationId)||t.__correlationId,n=(null==(u=t.bulkRescheduleEvent)?void 0:u.schedules)||[],i=null==e?void 0:e.getOptimisticState();r&&i&&i.resolve(r),n.forEach(e=>{e.eventId&&a.current.getEventById(e.eventId)&&a.current.updateEvent(e.eventId,{__isPending:!1})});return}if(t&&"object"==typeof t&&"error"in t){let e=t.error;console.error("[useEventsEngine] Error response:",e),l(e),n(!1);return}}},[e]);(0,r.useEffect)(()=>{if(e&&e.isRunning&&!t.current)return e.registerStateUpdater("event",l),e.registerRollbackHandler("event",t=>{let{correlationId:a,tempId:r,realId:l,operation:o,originalData:u}=t;if("create"===o&&r)i.Sj.getState().removeEvent(r);else if("update"===o&&l&&u){let t=(0,n.XN)(e).prepareRollback(a);if(t.isTracked){if(!t.shouldRollback||!t.originalEvent)return;m(e,l,t.originalEvent,t.scheduleTimingSnapshot);return}m(e,l,u)}}),t.current=!0,()=>{e.unregisterStateUpdater("event"),e.unregisterRollbackHandler("event"),t.current=!1}},[e,l])},f=e=>{let t=(0,r.useRef)(i.Sj.getState()),a=(0,r.useCallback)(e=>{if(!e)return;let t=(Array.isArray(e)?e:[e]).filter(e=>(0,c.Ewy)(e));return t.length>0?t:void 0},[]);(0,r.useEffect)(()=>i.Sj.subscribe(e=>{t.current=e}),[]);let l=(0,r.useCallback)((r,n,i,l)=>{if(!e)return;let o=a(i);t.current.setLoading(!0),e.push({type:"query",entity:"event",data:{startDate:r?(0,c.Hzr)(r):void 0,endDate:n?(0,c.Hzr)(n):void 0,intentIds:o,status:null==l?void 0:l.status,eventType:null==l?void 0:l.eventType}})},[e,a]),o=(0,r.useCallback)(r=>{if(!e)return;let n=a(r);if(!n)return void t.current.setLoading(!1);t.current.setLoading(!0),e.push({type:"query",entity:"event",data:{intentIds:n}})},[e,a]),u=(0,r.useCallback)(a=>{if(!e)return;let r=e.getOptimisticState(),l=(0,n.d$)("schedule-event"),o="temp-event-".concat(Date.now(),"-").concat(Math.random().toString(36).substr(2,9)),u=a.startDate instanceof Date?a.startDate.toISOString():a.startDate,
1s=a.endDate instanceof Date?a.endDate.toISOString():a.endDate,d=(0,i._)({id:o,title:a.title,description:a.description,startDate:u,endDate:s,eventType:a.eventType||"TODO",status:"scheduled",intentId:a.intentId,__isPending:!0});t.current.addEvent(d),e.upsertEntityItem("event",o,d),r.register({entity:"event",operation:"create",correlationId:l,tempId:o,mutationData:{title:a.title,description:a.description,fromTime:u,toTime:s,eventType:a.eventType||"TODO",intentId:a.intentId}}),e.push({type:"scheduleEvent",entity:"event",data:{input:{intentId:a.intentId,fromTime:u,toTime:s,eventType:a.eventType||"TODO"},__correlationId:l},kind:"mutation"})},[e]),s=(0,r.useCallback)((t,a)=>{if(e)return(0,n.oD)(e,t,a)},[e]);return{fetchEvents:l,fetchIntentEvents:o,scheduleEvent:u,rescheduleEvent:s,bulkRescheduleEvent:(0,r.useCallback)(a=>{if(!e||0===a.length)return;let r=e.getOptimisticState(),i=(0,n.d$)("bulk-reschedule");a.forEach(e=>{let a=e.startDate instanceof Date?e.startDate.toISOString():e.startDate,r=e.endDate instanceof Date?e.endDate.toISOString():e.endDate;t.current.updateEvent(e.eventId,{startDate:a,endDate:r,__isPending:!0})}),r.register({entity:"event",operation:"update",correlationId:i,mutationData:{changes:a}});let l=a.map(e=>({eventId:e.eventId,rescheduleMode:e.rescheduleMode||"SINGLE",fromTime:e.startDate instanceof Date?e.startDate.toISOString():e.startDate,toTime:e.endDate instanceof Date?e.endDate.toISOString():e.endDate}));e.push({type:"bulkRescheduleEvent",entity:"event",data:{input:{childIntentSchedules:l},__correlationId:i},kind:"mutation"})},[e]),unscheduleIntent:(0,r.useCallback)(t=>{e&&e.push({type:"unscheduleIntent",entity:"event",data:{__eventMutationLaneId:"task:".concat(t),intentId:t},kind:"mutation"})},[e])}};var y=a(49297),h=a(70053),v=a(75015),I=a(99104);function S(e){let t=i.ht.getState(),a=t.getRootIdForIntent(e);return a?{rootId:a,sequence:t.beginMutation(a)}:null}function k(e,t){return t?{...e,__templateVersionRootId:t.rootId,__templateVersionSequence:t.sequence}:e}function T(e,t){e&&void 0!==t&&i.ht.getState().confirmMutation(e.rootId,e.sequence)}function b(e){e&&i.ht.getState().failMutation(e.rootId,e.sequence)}var w=a(3811),A=a(39715),C=a(69702),P=a(44457),E=a(7576),R=a(89005),D=a(29915),B=a(8486),L=a(70769),_=a(59953),M=a(87030),U=a(86482),q=a(97398),x=a(84978),F=a(21468),O=a(94820);let Q="Method details are incomplete. Please wait and try again.";function N(e){for(let t of e){if(null==t)continue;let e=t.trim();if(e)return e}return""}function j(e){if(null==e)return;let t=e.trim();if(t)return t}function K(e){if("number"==typeof e&&Number.isFinite(e)&&!(e<0))return e}function V(e){let t=K(e);if(void 0!==t&&!(t<=0))return t}function W(e,t){return e.map((e,a)=>{var r;return{item:e,index:a,order:(r=t(e),"number"==typeof r&&Number.isFinite(r)?r:a+1)}}).sort((e,t)=>e.order!==t.order?e.order-t.order:e.index-t.index)}var z=a(93727),J=a(3184),H=a(54617),G=a(16862);function Y(e,t){return e instanceof Error?e:Error(t)}let X=[150,350],$=[1e4,2e4,2e4,2e4,2e4];async function Z(e){await new Promise(t=>{setTimeout(t,e)})}async function ee(e){await new Promise(t=>{setTimeout(t,e)})}function et(e,t){return e.isRunning&&e.getLifecycleSnapshot()===t}function ea(e){var t;let a=null==(t=i.Af.getState().data[e])?void 0:t.overview;return"string"==typeof a&&a.trim().length>0}function er(e){var t;let a=null==(t=i.Af.getState().data[e])?void 0:t.featuredImage;return"string"==typeof a&&a.trim().length>0}async function en(e,t,a){let r=e.getLifecycleSnapshot();for(let n of $){if(!et(e,r)||er(t)&&ea(a)||(await ee(n),!et(e,r)))return;let i=[];if(er(t)||i.push(e.pushAndWait({type:"query",entity:"intent",kind:"query",data:{action:"getById",id:t}})),ea(a)||i.push(e.pushAndWait({type:"query",entity:"intent",kind:"query",data:{action:"getById",id:a}})),await Promise.allSettled(i),er(t)&&ea(a))return}}async function ei(e,t,a,r,n,i){let l=await e.pushAndWait({type:"query",entity:"event",kind:"query",data:t});if(0!==a.length&&(0,z.C6)(l)&&!(0,z.NV)(l,a)){for(let o of X)if(await Z(o),!e.isRunning||r.current!==n||e.getLifecycleSnapshot()!==i||(l=await e.pushAndWait({type:"query",entity:"event",kind:"query",data:t}
1),(0,z.NV)(l,a)))return}}async function el(e,t){let a=(0,R.Ey)({scope:"my-library",page:1,pageSize:D.nB}),r=new Set([a]);for(let e of Object.values(t))"my-library"===e.scope&&r.add(e.id);for(let t of r)e.removeEntityItem("explorerSyncState",t);await e.pushAndWait({type:"query",entity:"explorer",kind:"query",data:{action:"getMyLibraryTemplates",page:1,pageSize:D.nB,_requireFreshRead:!0}}),e.upsertEntityItem("explorerSyncState",a,{lastFetchedAt:Date.now()})}function eo(e,t){for(let a of[e.templates,e.featuredTemplates,e.myTemplates,e.followingUserTemplates,e.bookmarkedTemplateData]){if(!a)continue;let e=a.find(e=>e.id===t);if(e)return e}for(let a of[e.categoryTemplatePagesByKey,e.authorTemplatePagesByKey,e.tagTemplatePagesByKey,e.bookmarkTemplatePagesByKey,e.templateQueryPagesByKey])if(a)for(let e of Object.values(a)){if(!e||!Array.isArray(e.templates))continue;let a=e.templates.find(e=>e.id===t);if(a)return a}for(let a of e.authorTemplatesByAuthorId?Object.values(e.authorTemplatesByAuthorId):[]){if(!a)continue;let e=a.find(e=>e.id===t);if(e)return e}}function eu(e){return{...e}}function es(e){return{id:e.id,page:e.page,pageSize:e.pageSize,sortBy:e.sortBy,metadataVersion:e.metadataVersion,isOptimistic:e.isOptimistic,localQuery:e.localQuery,duration:e.duration,price:e.price,templates:e.templates,totalCount:e.totalCount,lastFetchedAt:e.lastFetchedAt}}function ed(e){let t=new Set,a=[];for(let r of e)r.id&&(t.has(r.id)||(t.add(r.id),a.push(r)));return a}function ec(e,t){let a=i.QJ.getState();for(let r of t)a.setBookmarkTemplatePage(r),e.upsertEntityItem("explorerBookmarkTemplatePage",r.id,es(r))}function ep(e,t){var a,r,n,i,l,o,u;let s=new Map;for(let e of t){let t="".concat(e.sortBy,":").concat(null!=(a=e.localQuery)?a:"",":").concat(null!=(r=e.duration)?r:"",":").concat(null!=(n=e.price)?n:"");s.set(t,{sortBy:e.sortBy,localQuery:e.localQuery,duration:e.duration,price:e.price})}for(let t of s.values())i=t.sortBy,l=t.localQuery,o=t.duration,u=t.price,e.upsertEntityItem("explorerSyncState",(0,R.qO)(i,l,o,u),{lastFetchedAt:0})}function em(e,t){return"number"==typeof t?t:"number"==typeof e.bookmarksTotalCount?e.bookmarksTotalCount:e.bookmarkedTemplates.length}function eg(e,t){let a=i.QJ.getState(),r=em(a,t),n=Object.values(a.bookmarkTemplatePagesByKey).map(e=>{let t=e.totalCount;return e.localQuery||e.duration||e.price||(t=r),{...e,metadataVersion:R._f,totalCount:t,lastFetchedAt:0}});ec(e,n),ep(e,n),a.setBookmarksTotalCount(r)}function ef(e,t){var a;return!!e&&!!t&&!!(e.id===t||e.goalId===t||(null==(a=e.methods)?void 0:a.some(e=>e.id===t)))}function ey(e,t){var a,r;let n=e.selectedTemplateDetails;if(ef(n,t))return n;let i=null==(r=e.templateDetailsById)||null==(a=r[t])?void 0:a.details;return ef(i,t)?i:null}function eh(e,t){var a,r,n,i;return t?null!=(n=null==(r=e.copySerpMethod)?void 0:r.intents)?n:[]:null!=(i=null==(a=e.copyTemplate)?void 0:a.intents)?i:[]}let ev="home-default",eI="my-methods",eS="Unable to save method changes. Please try again.",ek="The saved preview count could not be confirmed. Please try again.",eT=new Map,eb=new Map,ew=new Map;function eA(e){var t,a,r,n;let i=(0,P.X)({...e.author,firstName:null!=(t=e.author.firstName)?t:void 0,lastName:null!=(a=e.author.lastName)?a:void 0,avatar:null!=(r=e.author.avatar)?r:void 0});return{reviewId:e.reviewId,templateId:e.templateId,title:e.title,requestedAt:e.requestedAt,adminReviewStatus:null!=(n=(0,x.Qz)(e.adminReviewStatus))?n:x.vi.UNDER_REVIEW,author:{id:i.id,name:i.name,firstName:e.author.firstName,lastName:e.author.lastName,avatar:i.profilePicture,isVerified:i.isVerified}}}function eC(e){var t,a;let r=(0,F.ck)(e.reviewStatus);if(!r)throw Error("Category review response contained an invalid status.");return{id:e.id,name:e.name,type:null!=(t=e.type)?t:null,icon:null!=(a=e.icon)?a:null,reviewStatus:r,createdAt:e.createdAt}}function eP(e,t){e.setTemplatesLastFetchedAt(null),e.setTemplatesView(null);let a={...e.tabSyncState};for(let e of t)delete a[e];e.setTabSyncState(a)}function eE(e,t){var a;let r=Object.values(null!=(a=t.templateQueryPagesByKey)?a:{}),n=(0,R.SH)(e,r);if(0===n.length)return;let i=new Set(n),l=r.filter(e=>!i.has(e.id));t.setTemplateQueryPages(l)}function eR(e,t,a){let r=!1,n=e.map(e=>e.id!==t?e:(r=!0,{...e,...a}));return r?n:null}function eD(e,t){return e.some(e=>e.id===t)}function eB(e){if("string"==typeof e)return e}function eL(e,t,a,r){var n,i,l;let o=e.selectedTemplateDetails,u=ef(o,t),s=null!=(l=null==(i=e.templateDetailsById)||null==(n=i[t])?void 0:n.details)?l:null;if(u&&o&&(s=o),!s)return;let d={...s,...a};u&&e.setSelectedTemplateDetails(d),r(t,d)}function e_(e,t,a,r,n){for(let i of(!function(e,t,a){e.updateTemplate(t,a);let r=eR(e.featuredTemplates,t,a);r&&e.setFeaturedTemplates(r);let n=eR(e.myTemplates,t,a);n&&e.setMyTemplates(n);let i=eR(e.followingUserTemplates,t,a);i&&e.setFollowingUserTemplates(i);let l=eR(e.bookmarkedTemplateData,t,a);for(let[r,n]of(l&&e.setBookmarkedTemplateData(l),Object.entries(e.authorTemplatesByAuthorId))){let i=eR(n,t,a);
1i&&e.setAuthorTemplates(r,i,e.authorTemplateTotalCountsByAuthorId[r])}}(t,a,r),eL(t,a,r,n),e.upsertEntityItem("intent",a,r),eD(t.templates,a)&&e.upsertEntityItem("explorerTemplate",a,r),eD(t.featuredTemplates,a)&&e.upsertEntityItem("featuredTemplateData",a,r),eD(t.myTemplates,a)&&e.upsertEntityItem("myExplorerTemplate",a,r),eD(t.bookmarkedTemplateData,a)&&e.upsertEntityItem("bookmarkedTemplateData",a,r),Object.keys(t.categoryTemplatePagesByKey)))e.removeEntityItem("explorerCategoryTemplatePage",i);for(let a of Object.keys(t.authorTemplatePagesByKey))e.removeEntityItem("explorerAuthorTemplatePage",a);for(let a of Object.keys(t.tagTemplatePagesByKey))e.removeEntityItem("explorerTagTemplatePage",a);for(let a of Object.keys(t.bookmarkTemplatePagesByKey))e.removeEntityItem("explorerBookmarkTemplatePage",a);for(let a of Object.keys(t.templateQueryPagesByKey))e.removeEntityItem("explorerTemplateQueryPage",a);t.setCategoryTemplatePages([]),t.setAuthorTemplatePages([]),t.setTagTemplatePages([]),t.setBookmarkTemplatePages([]),t.setTemplateQueryPages([]),t.setBookmarksHydrated(!1),t.setBookmarksLoadedPage(null),t.setBookmarksLoadedSortBy(null);let i=new Set(Object.keys(t.tabSyncState));i.add(ev),i.add(eI),eP(t,[...i])}function eM(e){return(!e||"object"!=typeof e||!("success"in e)||!1!==e.success)&&!0}function eU(e){if(!eM(e))return!0;let t=eV(e);return Array.isArray(null==t?void 0:t.errors)&&t.errors.length>0}function eq(e){return"string"!=typeof e||0===e.trim().length?null:e}async function ex(e,t){var a;let r=new Map,n=1,i=0,l=0;do{let a=function(e,t){if(!eM(e))return null;let a=eV(e),r=eV(null==a?void 0:a.data),n=eV(null==r?void 0:r.createdMethods);if(!n||!Array.isArray(n.methods)||"number"!=typeof n.totalCount||!Number.isInteger(n.totalCount)||n.totalCount<0)return null;let i=[];for(let e of n.methods){let a=eV(e),r=eV(null==a?void 0:a.currentVersion);if(!a||!r||"CHANGES_NOT_PUBLISHED"!==a.publicationStatus||a.immediateSourceVersionId!==t)continue;let n=eq(r.id),l=eq(a.lineageId);n&&l&&n!==t&&i.push({lineageId:l,sourceTemplateId:t,versionDraftId:n})}return{drafts:i,methodCount:n.methods.length,totalCount:n.totalCount}}(await e.pushAndWait({type:"query",entity:"explorer",kind:"query",data:{action:"getCreatedMethods",page:n,pageSize:100,section:"PRIVATE",sortBy:"recent"}}),t);if(!a)return null;for(let e of a.drafts)r.set(e.versionDraftId,e);if(i+=a.methodCount,l=a.totalCount,0===a.methodCount&&i<l)return null;n+=1}while(i<l);return 1!==r.size?null:null!=(a=Array.from(r.values())[0])?a:null}function eF(e){return eH("Could not create an editable template version.",e)}function eO(e){if(!eM(e))return null;let t=eV(e);if(!t)return null;let a=eV(t.data);return a?(0,H.BO)(a.templatePublicationState):null}function eQ(e){if("string"!=typeof e)return;let t=e.trim();if(t)return t}function eN(e){return"SOURCE_REVISION_CONFLICT"===e||"PENDING_SUBMISSION_EXISTS"===e}async function ej(e,t){return eO(await e.pushAndWait({type:"query",entity:"explorer",kind:"query",data:{action:"getTemplatePublicationState",sourceIntentId:t}}))}async function eK(e,t){let a=i.QJ.getState(),r=a.itemsPerPage>0?a.itemsPerPage:16;eE(e,a),eP(a,[ev,eI]),e.removeEntityItem("templatePublicationState",t),a.removeTemplatePublicationState(t),await Promise.allSettled([ej(e,t),e.pushAndWait({type:"query",entity:"explorer",kind:"query",data:{action:"getCreatedMethods",page:1,pageSize:r,query:"",section:"PRIVATE"}}),e.pushAndWait({type:"query",entity:"explorer",kind:"query",data:{action:"getCreatedMethods",page:1,pageSize:r,query:"",section:"PUBLISHED"}})])}function eV(e){return e&&"object"==typeof e?e:null}function eW(e){if("string"==typeof e&&e.trim())return e;let t=eV(e);if(!t)return;let a=t.message;if("string"==typeof a&&a.trim())return a}function ez(e){if(Array.isArray(e))for(let t of e){let e=eW(t);if(e)return e}}function eJ(e){let t=eV(e);if(!t)return;let a=eW(t.error);if(a)return a;let r=eW(t.message);if(r)return r;let n=ez(t.errors);if(n)return n;let i=eV(t.data);if(i)for(let e of Object.values(i)){let t=eV(e);if(!t)continue;let a=eW(t.error);if(a)return a;let r=eW(t.message);if(r)return r;let n=ez(t.errors);if(n)return n}}function eH(e,t){var a;return{errorMessage:null!=(a=eJ(t))?a:e,ok:!1}}function eG(e,t){var a;return{errorMessage:null!=(a=eJ(t))?a:e,ok:!1}}function eY(e,t,a,r){if(t)return void a(e);r(e)}function eX(e,t){let a=(0,w.TA)(t);if(a.message)return{errorMessage:a.message,ok:!1};let r=eJ(t);return r?{errorMessage:r,ok:!1}:{errorMessage:e,ok:!1}}function e$(e,t,a){var r,n,i,l;let o=function(e){let t,a,r=[e],n=new Set;for(;r.length>0;){let e=r.shift();if(!e||n.has(e))continue;n.add(e);let i=eV(e);if(!i)continue;let l=eQ(i.message);!t&&l&&(t=l);let o=eV(i.extensions);
1if(o){let e=eQ(o.code),r=function(e){let t={},a=(0,H.Bj)(e.currentRevision),r=eQ(e.lineageId),n=eQ(e.pendingTemplateId),i=eQ(e.reason),l=eQ(e.reviewRequestId);if(a&&(t.currentRevision=a),r&&(t.lineageId=r),n&&(t.pendingTemplateId=n),i&&(t.reason=i),l&&(t.reviewRequestId=l),0!==Object.keys(t).length)return t}(o);if(!a&&r&&(a=r),e)return{code:e,message:null!=l?l:t,metadata:r}}Array.isArray(i.graphQLErrors)&&r.push(...i.graphQLErrors),Array.isArray(i.errors)&&r.push(...i.errors),i.error&&r.push(i.error),i.originalError&&r.push(i.originalError)}return{message:t,metadata:a}}(t),u=null!=(r=o.code)?r:a,s=null;u&&(s=(0,G.H)({action:"publish-changes",errorCode:u,errorMetadata:o.metadata}));let d=null!=(n=o.message)?n:eJ(t),c={errorCode:u,errorMessage:null!=(l=null!=(i=null==s?void 0:s.description)?i:d)?l:e,ok:!1};return o.metadata&&(c.errorMetadata=o.metadata),s&&(c.publicationBlocker=s),c}function eZ(){let e=(0,n.Kj)(),t=(0,r.useRef)(0);(0,r.useLayoutEffect)(()=>(t.current+=1,()=>{t.current+=1}),[e]);let{startSchedulePreparation:a,finishSchedulePreparation:l}=(0,I.h)((0,v.k)(e=>({startSchedulePreparation:e.startSchedulePreparation,finishSchedulePreparation:e.finishSchedulePreparation}))),o=(0,r.useRef)(new Map),{toggleBookmark:u,completeBookmarkMutation:s,followAuthor:d,unfollowAuthor:c,itemsPerPage:p,reconcileFollowedAuthorCaches:m,setSelectedTemplateDetails:g,setTemplateDetailsCacheEntry:f,setIsLoadingTemplateDetails:T,clearSelectedTemplateDetails:b,updateTemplate:w,setUserRating:D,setPendingTemplateReviews:X,appendPendingTemplateReviews:$,removePendingTemplateReview:Z,templateQueryPagesByKey:ee,setCategoryReviews:et,appendCategoryReviews:ea,moveCategoryReview:er}=(0,i.QJ)((0,v.k)(e=>({toggleBookmark:e.toggleBookmark,completeBookmarkMutation:e.completeBookmarkMutation,followAuthor:e.followAuthor,unfollowAuthor:e.unfollowAuthor,itemsPerPage:e.itemsPerPage,reconcileFollowedAuthorCaches:e.reconcileFollowedAuthorCaches,setSelectedTemplateDetails:e.setSelectedTemplateDetails,setTemplateDetailsCacheEntry:e.setTemplateDetailsCacheEntry,setIsLoadingTemplateDetails:e.setIsLoadingTemplateDetails,clearSelectedTemplateDetails:e.clearSelectedTemplateDetails,updateTemplate:e.updateTemplate,setUserRating:e.setUserRating,setPendingTemplateReviews:e.setPendingTemplateReviews,appendPendingTemplateReviews:e.appendPendingTemplateReviews,removePendingTemplateReview:e.removePendingTemplateReview,templateQueryPagesByKey:e.templateQueryPagesByKey,setCategoryReviews:e.setCategoryReviews,appendCategoryReviews:e.appendCategoryReviews,moveCategoryReview:e.moveCategoryReview}))),ev=(0,r.useCallback)(async(t,a)=>{if(!e||!e.isRunning||!t)return;let r=eb.get(t);if(r)return void await r;let n=async function(){let r=i.QJ.getState(),n=function(e){let t={};for(let[a,r]of Object.entries(e.bookmarkTemplatePagesByKey))t[a]={...r,templates:r.templates.map(eu)};let a={};for(let[t,r]of Object.entries(e.tabSyncState))t.startsWith("bookmarks:")&&(a[t]=r);return{bookmarkedTemplates:[...e.bookmarkedTemplates],bookmarkedTemplateData:e.bookmarkedTemplateData.map(eu),bookmarkTemplatePagesByKey:t,bookmarkSyncStateByKey:a,bookmarksTotalCount:e.bookmarksTotalCount,isBookmarksHydrated:e.isBookmarksHydrated,bookmarksLoadedPage:e.bookmarksLoadedPage,bookmarksLoadedSortBy:e.bookmarksLoadedSortBy}}(r),l=eo(r,t),o=r.itemsPerPage||16;u(t,{beginMutation:!0}),a&&function(e,t){let a=i.QJ.getState(),r=em(a,void 0),n=a.bookmarkedTemplateData.filter(e=>e.id!==t);a.setBookmarkedTemplateData(n);let l=new Map;for(let e of Object.values(a.bookmarkTemplatePagesByKey)){var o,u,s;let t="".concat(e.sortBy,":").concat(e.pageSize,":").concat(null!=(o=e.localQuery)?o:"",":").concat(null!=(u=e.duration)?u:"",":").concat(null!=(s=e.price)?s:""),a=l.get(t);if(a){a.rows.push(e);continue}l.set(t,{key:t,pageSize:e.pageSize,rows:[e]})}let d=[];for(let e of l.values()){let a=[...e.rows].sort((e,t)=>e.page-t.page),n=a.some(e=>e.templates.some(e=>e.id===t)),i=a[0],l=r;((null==i?void 0:i.localQuery)||(null==i?void 0:i.duration)||(null==i?void 0:i.price))&&(l=i.totalCount,n&&(l=Math.max(0,i.totalCount-1))),d.push(...function(e,t,a){let r=[...e.rows].sort((e,t)=>
1e.page-t.page),n=new Set,i=r.map((e,r)=>{let i=e.templates.filter(e=>e.id!==t),l=e.isOptimistic;return i.length!==e.templates.length&&(n.add(r),l=!0),{...e,metadataVersion:R._f,isOptimistic:l,templates:i.map(eu),totalCount:a,lastFetchedAt:0}}),l=!1;for(let t=0;t<i.length;t+=1){if(n.has(t)&&(l=!0),!l)continue;let a=i.at(t),r=i.at(t+1);if(!a||!r||r.page!==a.page+1||a.templates.length>=e.pageSize){l=!1;continue}let o=r.templates.at(0);if(!o||a.templates.some(e=>e.id===o.id)){l=!1;continue}a.templates.push(eu(o)),r.templates=r.templates.slice(1).map(eu),a.isOptimistic=!0,r.isOptimistic=!0}return i}(e,t,l))}ec(e,d),ep(e,d),d.length>0&&a.setBookmarksHydrated(!0),e.removeEntityItem("bookmarkedTemplateData",t)}(e,t);try{var d,c,p,m,g,f,y,h;let r=await e.pushAndWait({type:"mutation",entity:"explorer",kind:"mutation",data:{action:a?"unbookmarkTemplate":"bookmarkTemplate",input:{intentId:t}}}),s=null!=(f=null==r||null==(m=r.data)||null==(p=m.bookmarkTemplate)||null==(c=p.intents)||null==(d=c[0])?void 0:d.id)?f:t,v=null==r||null==(g=r.data)?void 0:g.bookmarkTemplate;a&&(v=null==r||null==(y=r.data)?void 0:y.unbookmarkTemplate);let I=null==v?void 0:v.totalCount,S=function(e,t,a){let r=e.bookmarksTotalCount;if(null===r){let t=Object.values(e.bookmarkTemplatePagesByKey).filter(e=>1===e.page&&!e.localQuery&&!e.duration&&!e.price).sort((e,t)=>t.lastFetchedAt-e.lastFetchedAt).at(0);t&&(r=t.totalCount)}return"number"!=typeof r?a:t?Math.max(0,r-1):r+1}(n,a,I);if(a)e.removeEntityItem("bookmarkedTemplate",t),e.removeEntityItem("bookmarkedTemplateData",t),eg(e,S);else{s!==t&&(u(t),u(s)),e.upsertEntityItem("bookmarkedTemplate",s,{});let a=i.QJ.getState(),r=null!=(h=eo(a,t))?h:l;if(r){let n=ey(a,t),l={...(0,J.y)(r,n),id:s,isAiGenerated:!1,isBookmarked:!0,isTransientSerpResult:!1};e.upsertEntityItem("bookmarkedTemplateData",s,{...l}),function(e,t,a,r){let n=i.QJ.getState(),l=em(n,r);n.setBookmarksTotalCount(l);let o={...t,isAiGenerated:!1,isBookmarked:!0},u=ed([o,...n.bookmarkedTemplateData]);n.setBookmarkedTemplateData(u);let s=R.Bn,d=(0,R.Qq)({page:1,pageSize:a,sortBy:s}),c=n.bookmarkTemplatePagesByKey[d],p={id:d,page:1,pageSize:a,sortBy:s,templates:[],totalCount:l,lastFetchedAt:Date.now()},m=null!=c?c:p,g=Object.values(n.bookmarkTemplatePagesByKey).filter(e=>e.sortBy===s&&e.pageSize===a&&!e.localQuery&&!e.duration&&!e.price);g.some(e=>e.id===m.id)||g.push(m);let f={key:"".concat(s,":").concat(a),pageSize:a,rows:g},y=ed([o,...g.sort((e,t)=>e.page-t.page).flatMap(e=>e.templates)]),h=[...f.rows].sort((e,t)=>e.page-t.page).map((e,t)=>{let a=t*f.pageSize,r=y.slice(a,a+f.pageSize).map(eu);return{...e,metadataVersion:R._f,isOptimistic:!0,templates:r,totalCount:l,lastFetchedAt:Date.now()}}),v=new Set(h.map(e=>e.id));for(let e of Object.values(n.bookmarkTemplatePagesByKey)){if(v.has(e.id))continue;let t=e.totalCount;e.localQuery||e.duration||e.price||(t=l),h.push({...e,metadataVersion:R._f,totalCount:t,lastFetchedAt:0})}ec(e,h),ep(e,h),n.setBookmarksHydrated(!0),n.setBookmarksLoadedPage(1),n.setBookmarksLoadedSortBy(s)}(e,l,o,S)}else eg(e,S)}}catch(t){!function(e,t){let a=i.QJ.getState(),r=new Set(t.bookmarkedTemplates);for(let t of a.bookmarkedTemplates)r.has(t)||e.removeEntityItem("bookmarkedTemplate",t);for(let a of t.bookmarkedTemplates)e.upsertEntityItem("bookmarkedTemplate",a,{});let n=new Set(t.bookmarkedTemplateData.map(e=>e.id));for(let t of a.bookmarkedTemplateData)n.has(t.id)||e.removeEntityItem("bookmarkedTemplateData",t.id);let l=new Set(Object.keys(t.bookmarkSyncStateByKey));for(let e of Object.values(a.bookmarkTemplatePagesByKey))l.add((0,R.qO)(e.sortBy,e.localQuery,e.duration,e.price));let o=Object.keys(a.bookmarkTemplatePagesByKey),u=new Set(Object.keys(t.bookmarkTemplatePagesByKey));for(let t of o)u.has(t)||e.removeEntityItem("explorerBookmarkTemplatePage",t);for(let r of(a.setBookmarkedTemplates(t.bookmarkedTemplates),a.setBookmarkedTemplateData(t.bookmarkedTemplateData),a.setBookmarksTotalCount(t.bookmarksTotalCount),a.setBookmarksHydrated(t.isBookmarksHydrated),a.setBookmarksLoadedPage(t.bookmarksLoadedPage),a.setBookmarksLoadedSortBy(t.bookmarksLoadedSortBy),a.setBookmarkTemplatePages(Object.values(t.bookmarkTemplatePagesByKey)),Object.values(t.bookmarkTemplatePagesByKey)))e.upsertEntityItem("explorerBookmarkTemplatePage",r.id,es(r));for(let a of l){let r=t.bookmarkSyncStateByKey[a];if("number"==typeof r){e.upsertEntityItem("explorerSyncState",a,{lastFetchedAt:r});continue}e.removeEntityItem("explorerSyncState",a)}for(let a of t.bookmarkedTemplateData)e.upsertEntityItem("bookmarkedTemplateData",a.id,{...a})}(e,n),console.error("Failed to update bookmark:",t)}finally{s()}}();eb.set(t,n);try{await n}finally{eb.get(t)===n&&eb.delete(t)}},[s,e,u]),eI=async(t,a)=>{var r,n,l,o;if(!t||!e||!e.isRunning)return;let u=null!=(r=i.QJ.getState().userTemplateRatings[t])?r:0;D(t,a);try{let r=await e.pushAndWait({type:"mutation",entity:"explorer",kind:"mutation",data:{action:"rateTemplate",input:{templateId:t,rating:a}}}),i=null==r||null==(o=r.data)||null==(l=o.rateTemplate)||null==(n=l.intents)?void 0:n.find(e=>e.id===t);if((null==i?void 0:i.rating)!==void 0){let e="string"==typeof i.rating?parseFloat(i.rating):i.rating;if(!isNaN(e))return w(t,{rating:e}),e}console.warn("[handleRating] rateTemplate response missing intents[].rating for",t),D(t,u)}catch(e){D(t,u),console.error("Failed to rate template:",e)}},eP=(0,r.useCallback)(async(t,a)=>{let r,n;if(!e||!e.isRunning)return eG("Explorer is still loading. Please try again.");let i=!a;eY(t,i,d,c);let l="followUser";a&&(l="unfollowUser");try{r=await e.pushAndWait({type:"mutation",entity:"explorer",kind:"mutation",data:{action:l,targetUserId:t}})}catch(e){return eY(t,a,d,c),eG("Unable to update follow status. Please try again.",e)}if(eJ(r))return eY(t,a,d,c),eG("Unable to update follow status. Please try again.",r);a?e.removeEntityItem("followedAuthor",t):e.upsertEntityItem("followedAuthor",t,{});let o=m(t,i);for(let t of o.syncStateIds)e.removeEntityItem("explorerSyncState",t);for(let t of o.templateQueryPageIds)e.removeEntityItem("explorerTemplateQueryPage",t);let u=p;u<=0&&(u=16);try{n=await e.pushAndWait({type:"query",entity:"explorer",data:{action:"listAuthors",scope:"followed-authors",page:1,pageSize:u,isFollowing:!0,includeTemplatePreviews:!1}})}catch(e){return{ok:!0}}if(eJ(n))return{ok:!0};let s=Date.now();return e.upsertEntityItem("explorerSyncState","authors-you-follow-author-ids",{lastFetchedAt:s}),e.upsertEntityItem("explorerSyncState","authors-you-follow-authors",{lastFetchedAt:s}),{ok:!0}},[e,d,p,m,c]),eR=(0,r.useCallback)(async(r,n,o)=>
1{if(!e||!e.isRunning)throw Error("Method engine is not ready. Please try again.");let u=t.current,s=e.getLifecycleSnapshot();n(!0);try{var d,c,p,m,g,f,v,I;let n=i.QJ.getState(),S=eo(n,r),k=ey(n,r),T=(null==(g=(m={options:o,template:S,details:k}).options)?void 0:g.isTransientSerpResult)!==void 0?m.options.isTransientSerpResult:(null==(f=m.template)?void 0:f.isTransientSerpResult)!==void 0?m.template.isTransientSerpResult:(null==(v=m.details)?void 0:v.isTransientSerpResult)===!0,b={action:"copyTemplate",intentId:r};if(T){if(null==o?void 0:o.stagedDetailError)throw Error("Method details could not load. Please search again and retry.");if((null==o?void 0:o.isStagedDetailLoading)===!0||!0===n.isLoadingTemplateDetails||(null==o?void 0:o.isSerpAdoptionReady)===!1)throw Error("Method details are still loading. Please wait and try again.");let e=null!=(d=null==o?void 0:o.stagedDetails)?d:k,t=function(e){var t;let{templateId:a,details:r,template:n}=e;if(!r)return{input:null,error:Q};let i=N([r.goalName,null==n?void 0:n.title]),l=N([r.methodTitle,null==n?void 0:n.methodTitle,r.title]),o=(0,O.VU)(r),u=function(e){let{details:t,template:a}=e,r=(0,O.VU)(t),n=N([null==a?void 0:a.methodOutcomeLine,null==a?void 0:a.outcome]);return N([r.outcome,n])}({details:r,template:n});if(!i||!l||!u)return{input:null,error:Q};let s=null!=(t=r.tasks)?t:[];if(0===s.length)return{input:null,error:Q};let d=[];for(let e of W(s,e=>e.order)){let t=(0,O.vC)(e.item),a=N([t.title]);if(!a)return{input:null,error:Q};let r={title:a,order:e.order,steps:function(e){var t,a;return W(null!=(a=null!=(t=e.children)?t:e.steps)?a:[],e=>e.order).map(e=>{let t=(0,O.vC)(e.item),a={title:N([t.title]),order:e.order},r=j(t.description);void 0!==r&&(a.description=r);let n=function(e){let t=V(e.durationMinutes);if(void 0!==t)return Math.round(t);let a=V(e.duration);if(void 0!==a)return Math.round(a/60)}(e.item);return void 0!==n&&(a.durationMinutes=n),a})}(e.item)},n=j(t.description);void 0!==n&&(r.description=n);let i=function(e){if(!e)return;let t={},a=j(e.recurrence);void 0!==a&&(t.recurrence=a);let r=j(e.oneOffDates);void 0!==r&&(t.oneOffDates=r);let n=K(e.minimumGapsInDays);void 0!==n&&(t.minimumGapsInDays=Math.round(n));let i=K(e.minimumGapsInHours);void 0!==i&&(t.minimumGapsInHours=Math.round(i));let l=K(e.minimumGapsInMinutes);if(void 0!==l&&(t.minimumGapsInMinutes=Math.round(l)),0!==Object.keys(t).length)return t}(e.item.schedulePattern);void 0!==i&&(r.schedulePattern=i),d.push(r)}let c={templateId:a,goalTitle:i,methodTitle:l,methodOutcomeLine:u,tasks:d},p=j(o.description);return void 0!==p&&(c.methodDescription=p),{input:c,error:null}}({templateId:r,details:e,template:S});if(!t.input)throw Error(t.error||Q);b={action:"copySerpMethod",input:t.input}}let w=await e.pushAndWait({type:"mutation",entity:"explorer",kind:"mutation",data:b});if(null==w?void 0:w.data){let r=w.data,n=function(e,t){if(t){var a;let t=null==(a=e.copySerpMethod)?void 0:a.goalIntentId;if(t)return t}let r=eh(e,t),n=r.find(e=>{var t;return(null==(t=e.type)?void 0:t.toLowerCase())==="goal"});if(null==n?void 0:n.id)return n.id;let i=r[0];return(null==i?void 0:i.id)?i.id:null}(r,T),o=null==(c=r.copySerpMethod)?void 0:c.methodIntentId;if(n){let d=eh(r,T),c=d.filter(e=>{var t;return(null==(t=e.type)?void 0:t.toLowerCase())==="task"}).map(e=>e.id),m=(I=Object.values(i.Af.getState().data).filter(e=>"goal"===e.type),(0,U.LI)(I.filter(e=>"archived"!==e.status&&!0!==e.isFavorite))),g=d.find(e=>e.id===n),f={order:m};if(g&&(f={...g,order:m}),T&&(f=function(e){var t;let{copiedGoal:a,details:r,template:n}=e;if((null==n?void 0:n.isAiGenerated)!==!0&&(null==r?void 0:r.isAiGenerated)!==!0||"boolean"==typeof a.isAiGenerated)return a;let i={...a,isAiGenerated:!0},l=null!=(t=null==n?void 0:n.generationProvider)?t:null==r?void 0:r.generationProvider;return void 0!==l&&(i.generationProvider=l),i}({copiedGoal:f,details:k,template:S})),e.upsertEntityItem("intent",n,f),T&&o){let t=d.find(e=>e.id===o);t&&e.upsertEntityItem("intent",o,{...t,parent:f})}let v=await e.pushAndWait({type:"updateIntent",entity:"intent",kind:"mutation",data:{input:{id:n,order:m}}}),b=eV(v);if(!((null==b?void 0:b.success)===!0&&!eU(v))){let e=null!=(p=eJ(v))?p:"Failed to finalize Method adoption.";throw Error(e)}let w=i.QJ.getState();eE(e,w),a(n);let A=!1,C=async()=>{let a=[e.pushAndWait({type:"query",entity:"intent",kind:"query",data:{action:"search",input:{}}}),e.pushAndWait({type:"mutation",entity:"event",kind:"mutation",data:{action:"autoSchedule",goalId:n}})];
1a.push(el(e,w.templateQueryPagesByKey));let r=await Promise.allSettled(a),i=null;for(let e of r)if("rejected"===e.status){i=e.reason;break}let l=r[1];if(e.push({type:"query",entity:"intent",kind:"query",data:{action:"getById",id:n}}),(null==l?void 0:l.status)==="fulfilled"){let a=(0,z.dv)(l.value);A=a.length>0;let r={intentIds:c};if(0===c.length){let e=new Date,t=(0,y.f)(e,-7),a=(0,y.f)(e,45);r={startDate:(0,h.GP)(t,"yyyy-MM-dd"),endDate:(0,h.GP)(a,"yyyy-MM-dd")}}await ei(e,r,a,t,u,s)}if(i)throw Y(i,"Post-copy refresh failed.")},P=()=>{A||l(n)};return C().then(P,P),T&&o&&en(e,n,o).then(()=>void 0,()=>void 0),n}throw Error("Template copy completed but did not return a goal intent.")}throw Error("Failed to copy template data.")}catch(e){if((0,q.bZ)(e))throw new q.dy;throw Y(e,"Failed to use method.")}finally{n(!1)}},[e,l,a]),eD=(0,r.useCallback)(async t=>{if(!e||!e.isRunning||!t)return null;try{let r=await e.pushAndWait({type:"mutation",entity:"explorer",kind:"mutation",data:{action:"connectUser",input:{userId:t}}});if(null==r?void 0:r.data){var a;let e=r.data;if(null==(a=e.connectUser)?void 0:a.accountLinkUrl)return e.connectUser.accountLinkUrl}throw Error("Invalid response format from connectUser")}catch(e){throw e}},[e]),eQ=(0,r.useCallback)(async e=>eD(e),[eD]),eW=(0,r.useCallback)(async t=>{if(!e||!e.isRunning||!t)return null;try{let r=await e.pushAndWait({type:"mutation",entity:"explorer",kind:"mutation",data:{action:"manageUserPayouts",input:{userId:t}}});if(null==r?void 0:r.data){var a;let e=r.data;if(null==(a=e.manageUserPayouts)?void 0:a.accountDashboardUrl)return e.manageUserPayouts.accountDashboardUrl}throw Error("Invalid response format from manageUserPayouts")}catch(e){throw e}},[e]),ez=(0,r.useCallback)(async t=>{if(e&&t)try{let n=await e.pushAndWait({type:"query",entity:"explorer",kind:"query",data:{action:"userMerchantStatus",userId:t}});if(null==n?void 0:n.data){var a,r;return null!=(r=null==(a=n.data.userMerchantStatus)?void 0:a.merchantStatus)?r:null}return}catch(e){return}},[e]),eZ=(0,r.useCallback)(async(t,a)=>{if(!e||!e.isRunning||!t||!a)throw Error("Missing required parameters for purchase");let r=await e.pushAndWait({type:"mutation",entity:"explorer",kind:"mutation",data:{action:"purchaseTemplate",input:{userId:t,templateId:a}}});if(null==r?void 0:r.data){let e=r.data;if(e.purchaseTemplate){var n;return null!=(n=e.purchaseTemplate.checkoutSessionUrl)?n:null}}throw Error("Failed to acquire method")},[e]),e0=(0,r.useCallback)(()=>{if(e&&e.isRunning)for(let t of Object.values(ee).filter(e=>"my-library"===e.scope))e.removeEntityItem("explorerTemplateQueryPage",t.id)},[e,ee]),e1=(0,r.useCallback)(async t=>{var a,r,n,i;if(!e||!e.isRunning)return[];let l=await e.pushAndWait({type:"query",entity:"explorer",kind:"query",data:{action:"orderInvoices",page:null!=(a=null==t?void 0:t.page)?a:1,pageSize:null!=(r=null==t?void 0:t.pageSize)?r:20}});return(null==l?void 0:l.data)&&null!=(i=null==(n=l.data.orderInvoices)?void 0:n.items)?i:[]},[e]),e4=(0,r.useCallback)((t,a)=>{if(!t)return;let r=Date.now();f(t,{details:a,lastFetchedAt:r}),e&&e.isRunning&&e.upsertEntityItem("explorerTemplateDetails",t,{details:a,lastFetchedAt:r})},[e,f]),e5=(0,r.useCallback)(e=>{var t,a,r;if(!e)return;let n=i.QJ.getState(),l=n.selectedTemplateDetails,o=null!==l&&ef(l,e),u=null!=(r=null==(a=n.templateDetailsById)||null==(t=a[e])?void 0:t.details)?r:null;if(o&&(u=l),!u)return;let s={...u,hasCompletedPurchase:!0};o&&n.setSelectedTemplateDetails(s),e4(e,s)},[e4]),e3=(0,r.useCallback)(async(t,a)=>{if(!e||!e.isRunning||!t)return null;let r=(null==a?void 0:a.forceRefresh)!==!0,n=i.QJ.getState().templateDetailsById[t];if(n&&r&&(g(n.details),Date.now()-n.lastFetchedAt<3e5))return T(!1),n.details;let l=eT.get(t);if(l&&r)return n||T(!0),l;let o=!n;o&&T(!0);let u=(async()=>{try{let a=await e.pushAndWait({type:"query",entity:"explorer",kind:"query",data:{action:"getTemplateDetails",templateId:t}});if(null==a?void 0:a.data){let e=a.data;if(e.getTemplateDetails){let a=(0,_.o)((0,M.e)(e.getTemplateDetails));return g(a),e4(t,a),a}}return null}catch(e){return console.error("[fetchTemplateDetails] Failed to fetch template details:",{error:e,templateId:t}),null}finally{o&&T(!1),r&&eT.delete(t)}})();return r&&eT.set(t,u),u},[e,T,g,e4]),e7=(0,r.useCallback)(async t=>{if(!e||!e.isRunning||!t)return{};T(!0);try{return await (0,A.S)(e,t,{shouldHydrateTemplateChildren:!0,maxConcurrentRequests:8})}finally{T(!1)}},[e,T]),e6=(0,r.useCallback)(async t=>{if(!e||!e.isRunning||!t)return null;let a=i.QJ.getState().templateDetailsById[t];if(a&&Date.now()-a.lastFetchedAt<3e5)return a.details;let r=eT.get(t);if(r)return r;let n=(async()=>{try{let a=await e.pushAndWait({type:"query",entity:"explorer",kind:"query",data:{action:"getTemplateDetails",templateId:t}});if(null==a?void 0:a.data){let e=a.data;if(e.getTemplateDetails){let a=(0,_.o)((0,M.e)(e.getTemplateDetails));return e4(t,a),a}}throw Error("Template review details were unavailable for ".concat(t,"."))}finally{eT.delete(t)}})();return eT.set(t,n),n},[e,e4]),e8=(0,r.useCallback)(async(t,a)=>{if(!e||!e.isRunning||!t)return eX(eS);try{let r=i.QJ.getState().selectedTemplateDetails,n=ef(r,t);if(n&&(null==r?void 0:r.isTemplate)){let e=(0,x.Qz)(r.adminReviewStatus);if(e!==x.vi.UNDER_REVIEW&&e!==x.vi.DECLINED)return eX("Cannot modify a template intent. Unpublish to edit a draft copy.")}let{goalName:l,goalId:o,price:u,duration:s,featuredImage:d,categoryIds:c,categoryRecords:p,...m}=a,g=o;!g&&n&&(g=null==r?void 0:r.goalId),g||(g=t);let f={};if(void 0!==l&&(f.title=l),void 0!==u&&(f.price=u),void 0!==s&&(f.duration=s),void 0!==d&&(f.featuredImage=d),void 0!==c&&(f.categoryIds=c),Object.keys(m).length>0){let a=S(t);await e.pushAndWait({type:"updateIntent",entity:"intent",kind:"mutation",data:k({input:{id:t,...m}},a)}),e.upsertEntityItem("intent",t,m)}if(g&&Object.keys(f).length>0){let t=S(g);await e.pushAndWait({type:"updateIntent",entity:"intent",kind:"mutation",data:k({input:{id:g,...f}},t)}
1);let a={};void 0!==l&&(a.title=l),void 0!==u&&(a.price=u),void 0!==s&&(a.duration=s),void 0!==d&&(a.featuredImage=d),void 0!==p&&(a.categories=p),Object.keys(a).length>0&&e.upsertEntityItem("intent",g,a)}let y=i.QJ.getState(),h=y.selectedTemplateDetails;if(h&&ef(h,t)){let e={...h},a=!1;if(void 0!==m.title&&(e.methodTitle=m.title,e.methods&&0!==e.methods.length||(e.title=m.title),a=!0),void 0!==m.outcome&&(e.outcome=m.outcome,e.methodOutcomeLine=m.outcome,a=!0),void 0!==m.overview&&(e.overview=m.overview,a=!0),void 0!==m.description&&(e.description=m.description,a=!0),e.methods&&e.methods.length>0&&(e.methods=e.methods.map((e,t)=>{if(0!==t)return e;let a={...e},r=!1;return(void 0!==m.title&&(a.title=m.title,r=!0),void 0!==m.outcome&&(a.outcome=m.outcome,r=!0),void 0!==m.overview&&(a.overview=m.overview,r=!0),void 0!==m.description&&(a.description=m.description,r=!0),r)?a:e})),(h.goalId===g||h.id===g)&&(void 0!==l&&(e.goalName=l,a=!0),void 0!==s&&(e.duration=s,a=!0),void 0!==u&&(e.price=u,a=!0),void 0!==d&&(e.featuredImage=d,a=!0),void 0!==p&&(e.intentCategories=p,a=!0)),a)for(let a of(y.setSelectedTemplateDetails(e),function(e,t,a,r){let n=new Set([t,a,r.id]);for(let[t,a]of Object.entries(e.templateDetailsById)){var i;i=a.details,(i.id===r.id||i.goalId&&r.goalId&&i.goalId===r.goalId||i.id===r.goalId||i.goalId===r.id||0)&&n.add(t)}return[...n]}(y,t,g,h)))e4(a,e)}return Object.keys(f).length>0&&eE(e,y),{ok:!0}}catch(e){return eX(eS,e)}},[e,e4]),e2=(0,r.useCallback)(async(t,a)=>{let r=t.rootIntentId;if(!e||!e.isRunning||!r)return eX(eS);try{let n=S(r),i=await e.pushAndWait({type:"mutation",entity:"explorer",kind:"mutation",data:k({action:"updateTemplate",input:{intentId:r,previewTaskCount:a}},n)});if(!eM(i))return eX(eS,i);if("intent-tree"===t.kind){let t=(await (0,A.S)(e,r,{shouldHydrateTemplateChildren:!0}))[r];if(!t||t.id!==r||"goal"!==t.type||!0===t.isTemplate||"number"!=typeof t.previewTaskCount||t.previewTaskCount!==a)return eX(ek);return{ok:!0,previewTaskCount:t.previewTaskCount}}let l=await e3(r,{forceRefresh:!0});if(!ef(l,r)||(null==l?void 0:l.isTemplate)!==!0||"number"!=typeof l.previewTaskCount||l.previewTaskCount!==a)return eX(ek);return{ok:!0,previewTaskCount:l.previewTaskCount}}catch(e){return eX(eS,e)}},[e,e3]),e9=(0,r.useCallback)(async t=>{let a,r;if(!e||!e.isRunning||0===t.trim().length)return eF();let n=null;try{r=await e.pushAndWait({type:"mutation",entity:"explorer",kind:"mutation",data:{action:"createTemplateVersion",templateId:t}}),n=function(e,t){if(!eM(e))return null;let a=eV(e),r=eV(null==a?void 0:a.data),n=eV(null==r?void 0:r.createTemplateVersion);if(!n)return null;let i=eq(n.versionDraftId),l=eq(n.sourceTemplateId),o=eq(n.lineageId);return i&&l&&o&&l===t&&i!==l?{lineageId:o,sourceTemplateId:l,versionDraftId:i}:null}(r,t)}catch(e){a=e}let i=void 0!==a||eU(r);if(!n&&i)try{n=await ex(e,t)}catch(e){void 0===a&&(a=e)}if(!n)return eF(null!=a?a:r);try{let t=await (0,A.S)(e,n.versionDraftId,{shouldHydrateListedChildren:!0});if(!t[n.versionDraftId])return eF();return{draft:n,hydratedIntents:t,ok:!0}}catch(e){return eF(e)}},[e]),te=(0,r.useCallback)(async t=>{if(!e||!e.isRunning||0===t.trim().length)return null;try{return await ej(e,t)}catch(e){var a;return i.QJ.getState().setError(null!=(a=eJ(e))?a:"Unable to load the current publishing state."),null}},[e]),tt=(0,r.useCallback)(async t=>{let a="Could not publish this method. Please try again.";if(!e||!e.isRunning||0===t.trim().length)return e$(a);let r=ew.get(t);if(r)return r;let n=async function(){let r,n;try{r=await e.pushAndWait({type:"query",entity:"explorer",kind:"query",data:{action:"getTemplatePublicationState",sourceIntentId:t}})}catch(e){return e$(a,e)}let l=eO(r);if(!l||l.sourceIntentId!==t)return e$(a,r);let o=(0,G.t)(l),u=(0,G.H)({action:o,publicationState:l});if(u){var s;let e={errorCode:null!=(s=l.blockedReason)?s:void 0,errorMessage:u.description,ok:!1,publicationBlocker:u},t=function(e){if(e.pendingTemplateId)return{pendingTemplateId:e.pendingTemplateId}}(l);return t&&(e.errorMetadata=t),e}try{n=await e.pushAndWait({type:"mutation",entity:"explorer",kind:"mutation",data:{action:"publishTemplateFromSource",sourceIntentId:t,expectedSourceRevision:l.sourceRevision}})}catch(n){let r=e$(a,n);if(eN(r.errorCode))try{await ej(e,t)}catch(e){i.QJ.getState().setError("Unable to refresh the current publishing state.")}return r}let d=e$(a,n);if(d.errorCode){if(eN(d.errorCode))try{await ej(e,t)}catch(e){i.QJ.getState().setError("Unable to refresh the current publishing state.")}return d}let c=function(e){if(!eM(e))return null;let t=eV(e);if(!t)return null;let a=eV(t.data);return a?(0,H.$r)(a.publishTemplateFromSource):null}(n);return c&&c.sourceIntentId===t&&c.capturedSourceRevision===l.sourceRevision?(await eK(e,t),{ok:!0,publicationMode:"snapshot",publishedTemplateId:c.templateVersionId,...c}):e$(a,n)}();ew.set(t,n);try{return await n}finally{ew.get(t)===n&&ew.delete(t)}},[e]),ta=(0,r.useCallback)(async t=>{let a="Could not withdraw this template from review.";if(!e||!e.isRunning||!t)return eH(a);try{let r=await e.pushAndWait({type:"mutation",entity:"explorer",kind:"mutation",data:{action:"withdrawTemplateReview",templateId:t}});if(!eM(r))return eH(a,r);let n=function(e,t){if(!eM(e))return null;let a=eV(e),r=eV(null==a?void 0:a.data),n=eV(null==r?void 0:r.withdrawTemplateReview);if(!n||(0,x.Qz)(n.adminReviewStatus)!==x.vi.WITHDRAWN||n.templateId!==t)return null;let i=eq(n.editableRootId);if(!i||"string"!=typeof n.reviewId||"string"!=typeof n.lineageId||!1!==n.isTemplate||!0!==n.isEditable||"string"!=typeof n.withdrawnAt)return null;let l=null;if("string"==typeof n.liveTemplateId)l=n.liveTemplateId;else if(null!==n.liveTemplateId)return null;return{adminReviewStatus:x.vi.WITHDRAWN,editableRootId:i,isEditable:!0,isTemplate:!1,lineageId:n.lineageId,liveTemplateId:l,reviewId:n.reviewId,templateId:t,withdrawnAt:n.withdrawnAt}}(r,t);if(!n)return eH(a,r);return Z(t),await eK(e,n.editableRootId),{editableRootId:n.editableRootId,liveTemplateId:n.liveTemplateId,ok:!0,templateId:n.templateId}}catch(e){return eH(a,e)}},[e,Z]),tr=(0,r.useCallback)(async t=>{let a="Could not submit this template for review.";if(!e||!e.isRunning||!t)return eH(a);try{let r=await e.pushAndWait({type:"mutation",entity:"explorer",kind:"mutation",data:{action:"submitTemplateForReview",templateId:t}});if(!eM(r)||function(e){if(!eM(e))return null;let t=eV(e),a=eV(null==t?void 0:t.data),r=eV(null==a?void 0:a.submitTemplateForReview);return r&&"string"==typeof r.id?r.id:null}(r)!==t)return eH(a,r);let n={adminReviewStatus:x.vi.UNDER_REVIEW,declineReason:null,isTemplate:!0,withdrawnAt:null},l=i.QJ.getState(),o=function(e){var t,a,r,n,i,l,o,u,s,d,c,p,m,g,f;
1let{currentUser:y,existingTemplate:h,selectedDetails:v,templateId:I,updates:S}=e,k=null==h?void 0:h.author;!k&&(null==y?void 0:y.id)&&(k={id:y.id,name:null!=(t=y.name)?t:"You",profilePicture:y.avatar,isVerified:y.isVerified});let T=null==h?void 0:h.category;return T||(T=(0,E.Ac)(null==v?void 0:v.intentCategories)),{...h,id:I,title:null!=(n=null!=(r=null!=(a=null==h?void 0:h.title)?a:null==v?void 0:v.methodTitle)?r:null==v?void 0:v.title)?n:"New Method",methodTitle:null!=(i=null==h?void 0:h.methodTitle)?i:eB(null==v?void 0:v.methodTitle),methodOutcomeLine:null!=(l=null==h?void 0:h.methodOutcomeLine)?l:eB(null==v?void 0:v.methodOutcomeLine),outcome:null!=(o=null==h?void 0:h.outcome)?o:null==v?void 0:v.outcome,description:null!=(s=null!=(u=null==h?void 0:h.description)?u:null==v?void 0:v.description)?s:"",overview:null!=(d=null==h?void 0:h.overview)?d:null==v?void 0:v.overview,rationale:null!=(c=null==h?void 0:h.rationale)?c:null==v?void 0:v.rationale,author:k,category:T,duration:null==h?void 0:h.duration,price:null==h?void 0:h.price,popularity:null!=(p=null==h?void 0:h.popularity)?p:null==v?void 0:v.popularity,image:null!=(m=null==h?void 0:h.image)?m:null==v?void 0:v.featuredImage,createdAt:null==h?void 0:h.createdAt,updatedAt:null==h?void 0:h.updatedAt,tagId:null!=(g=null==h?void 0:h.tagId)?g:null==v?void 0:v.tagId,state:null!=(f=null==h?void 0:h.state)?f:null==v?void 0:v.state,archivedAt:null,...S}}({currentUser:l.currentUser,existingTemplate:eo(l,t),selectedDetails:l.selectedTemplateDetails,templateId:t,updates:n}),u=(0,B.i)({fallbackTemplate:o,myTemplates:l.myTemplates,pagesByKey:l.templateQueryPagesByKey,templateId:t,updates:n});return function(e,t,a){for(let e of(t.setMyTemplates(a.myTemplates),a.changedQueryPages))t.setTemplateQueryPage(e);if(a.ownerTemplate){let t={...a.ownerTemplate};e.upsertEntityItem("myExplorerTemplate",a.ownerTemplate.id,t)}for(let t of a.changedQueryPages)e.upsertEntityItem("explorerTemplateQueryPage",t.id,t)}(e,l,u),eL(l,t,n,e4),e.upsertEntityItem("intent",t,n),eE(e,l),{ok:!0}}catch(e){return eH(a,e)}},[e,e4]),tn=(0,r.useCallback)(async t=>{if(!e||!e.isRunning||!t)return null;try{let a=await e.pushAndWait({type:"mutation",entity:"explorer",kind:"mutation",data:{action:"unpublishTemplate",intentId:t}});if(!eM(a))return null;let r=eV(a),n=eV(null==r?void 0:r.data),l=eV(null==n?void 0:n.unpublishTemplate),o=eq(null==l?void 0:l.unpublishedTemplateId),u=eq(null==l?void 0:l.draftIntentId);if(!o||!u||o!==t)return null;let s=i.QJ.getState();e.removeEntityItem("explorerTemplate",t),e.removeEntityItem("featuredTemplateData",t),e.removeEntityItem("bookmarkedTemplateData",t),s.deleteTemplate(t),await eK(e,u);let d=i.QJ.getState().selectedTemplateDetails;return((null==d?void 0:d.id)===t||(null==d?void 0:d.goalId)===t)&&b(),{unpublishedTemplateId:o,draftIntentId:u}}catch(e){var a;return i.QJ.getState().setError(null!=(a=eJ(e))?a:"Could not unpublish this Method."),null}},[e,b]),ti=(0,r.useCallback)(async t=>{if(!e||!e.isRunning)return{items:[],totalCount:0};try{var a,r,n,i,l,o;let u=null!=(r=null==t?void 0:t.status)?r:x.vi.UNDER_REVIEW,s=await e.pushAndWait({type:"query",entity:"explorer",kind:"query",data:{action:"templatesUnderReview",page:null!=(n=null==t?void 0:t.page)?n:1,pageSize:null!=(i=null==t?void 0:t.pageSize)?i:20,status:u}});if(!eM(s))return{items:[],totalCount:0};let d=s.data,c=null==d?void 0:d.templatesUnderReview,p=null!=(l=null==c||null==(a=c.items)?void 0:a.map(eA))?l:[],m=null!=(o=null==c?void 0:c.totalCount)?o:p.length;if((null==t?void 0:t.append)===!0)return $(p,m),{items:p,totalCount:m};return X(p,m),{items:p,totalCount:m}}catch(e){return{items:[],totalCount:0}}},[$,e,X]),tl=(0,r.useCallback)(async(t,a)=>{let r="Could not approve this template.";if(!e||!e.isRunning||!t)return{errorMessage:r,ok:!1};try{let n=await e.pushAndWait({type:"mutation",entity:"explorer",kind:"mutation",data:{action:"approveTemplate",templateId:t,reason:a}});if(!eM(n))return eH(r,n);let l={isTemplate:!0,adminReviewStatus:x.vi.APPROVED,declineReason:null},o=i.QJ.getState();return e_(e,o,t,l,e4),Z(t),{ok:!0}}catch(e){return eH(r,e)}},[e,Z,e4]),to=(0,r.useCallback)(async(t,a)=>{let r="Could not reject this template.";if(!e||!e.isRunning||!t)return{errorMessage:r,ok:!1};let n=function(e){if(!e)return null;let t=e.trim();return t||null}(a);try{let a=await e.pushAndWait({type:"mutation",entity:"explorer",kind:"mutation",data:{action:"declineTemplate",templateId:t,reason:null!=n?n:void 0}});if(!eM(a))return eH(r,a);let l={isTemplate:!0,adminReviewStatus:x.vi.DECLINED,declineReason:n},o=i.QJ.getState();return e_(e,o,t,l,e4),Z(t),{ok:!0}}catch(e){return eH(r,e)}},[e,Z,e4]),tu=(0,r.useCallback)(async t=>{let a="Could not load category reviews.";if(!e||!e.isRunning)throw Error(a);try{var r,n;let i=await e.pushAndWait({type:"query",entity:"explorer",kind:"query",data:{action:"categoriesUnderReview",page:t.page,pageSize:t.pageSize,status:t.status}});if(!eM(i)){let e=null!=(n=eJ(i))?n:a;throw Error(e)}let l=null==(r=i.data)?void 0:r.categoriesUnderReview;if(!(null==l?void 0:l.items)||"number"!=typeof l.totalCount)throw Error(a);let o=l.items.map(eC);return!0===t.append?ea(t.status,o,l.totalCount):et(t.status,o,l.totalCount),{items:o,totalCount:l.totalCount}}catch(t){let e=eJ(t);if(e)throw Error(e);throw Y(t,a)}},[ea,e,et]),ts=(0,r.useCallback)(async()=>{let t="Could not refresh Explorer categories.";if(!e||!e.isRunning)return{errorMessage:t,ok:!1};try{let a=await e.pushAndWait({type:"query",entity:"explorer",kind:"query",data:{action:"getCategories"}});if(!eM(a))return eH(t,a);return{ok:!0}}catch(e){return eH(t,e)}},[e]),td=(0,r.useCallback)(async(t,a)=>{let r="Could not approve this category.",n="Category was approved, but Explorer categories could not refresh.";if("declineCategory"===a&&(r="Could not reject this category.",n="Category was rejected, but Explorer categories could not refresh."),!e||!e.isRunning||!t)return{errorMessage:r,ok:!1};try{var i,l;let o=await e.pushAndWait({type:"mutation",entity:"explorer",kind:"mutation",data:{action:a,categoryId:t}});if(!eM(o))return eH(r,o);let u=null==(i=o.data)?void 0:i.approveCategory;"declineCategory"===a&&(u=null==(l=o.data)?void 0:l.declineCategory);let s=(0,F.ck)(null==u?void 0:u.reviewStatus);if(!u||u.categoryId!==t||!s)return eH(r,o);er(t,F.Ln.PENDING,s);let d=await ts(),c={ok:!0,reviewStatus:s};return d.ok||(c.warningMessage=n),c}catch(e){return eH(r,e)}},[e,er,ts]),tc=(0,r.useCallback)(e=>td(e,"approveCategory"),[td]),tp=(0,r.useCallback)(e=>td(e,"declineCategory"),[td]),tm=(0,r.useCallback)(async function(t){var a,r,n;let i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:8,l=arguments.length>2?arguments[2]:void 0,o=arguments.length>3?arguments[3]:void 0,u=t.trim(),s=null!=(a=null==o?void 0:o.page)?a:1;if(!e||!e.isRunning)return[];try{return(null!=(n=null==(r=(await e.syncExplorerSerpMethodsPage({query:u,page:s,pageSize:i,filters:l,source:"explorer-results",fetchTitleSuggestions:null==o?void 0:o.fetchTitleSuggestions,preserveTitleSuggestions:null==o?void 0:o.preserveTitleSuggestions,projectToActiveTemplates:!0})).page)?void 0:r.templates)?n:[]).map(e=>{let t={id:e.id,title:e.title,methodTitle:e.methodTitle,methodOutcomeLine:e.methodOutcomeLine,rationale:e.rationale,description:e.description,generationProvider:e.generationProvider,isAiGenerated:e.isAiGenerated,isHumanReviewed:e.isHumanReviewed,rating:e.rating};return e.outcome&&(t.outcome=e.outcome),e.author&&(t.author={id:e.author.id,firstName:e.author.name,avatar:e.author.profilePicture}),"number"==typeof e.priceInCents&&(t.price=e.priceInCents),t})}catch(e){return[]}},[e]),tg=(0,r.useCallback)(function(t,a,r){var n,l,o;let u=arguments.length>3&&void 0!==arguments[3]?arguments[3]:C.KQ,s=(0,C.KH)(a),d=i.QJ.getState(),c=null!=(n=d.authorTemplatesByAuthorId[t])?n:[],p=(0,C.KL)(c,s,r,u),m=null!=(l=null==a?void 0:a.totalCount)?l:p.length,g=(0,C.Y6)(null!=(o=d.authorMethodPreviewLoadedPagesByAuthorId[t])?o:[],r),f=Date.now();return d.setAuthorTemplates(t,p,m,{lastFetchedAt:f,loadedPages:g,replaceExisting:!0}),(null==e?void 0:e.isRunning)&&e.upsertEntityItem("explorerAuthorMethodPreview",t,{id:t,authorId:t,templates:p,totalCount:m,loadedPages:g,lastFetchedAt:f,replaceFetchedPages:!0}),p},[e]),tf=(0,r.useCallback)(async function(t){let a=arguments.length>1&&void 0!==arguments[1]?arguments[1]:1,r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:C.KQ;if(!e||!e.isRunning||!t)return[];let n="".concat(t,":").concat(a,":").concat(r),i=o.current.get(n);if(i)return i;let l=(async()=>{var n,i;let l=null==(i=(await e.pushAndWait({type:"query",entity:"explorer",kind:"query",data:{action:"getAuthorTemplatePreviews",authorIds:[t],page:a,pageSize:r,_cacheAuthorPreviews:!0}})).data)||null==(n=i.authorTemplatePreviews)?void 0:n[t];return tg(t,l,a,r)})();o.current.set(n,l);try{return await l}finally{o.current.delete(n)}},[tg,e]);return{handleBookmark:ev,handleRating:eI,handleFollow:eP,handleUseMethod:eR,handleConnectUser:eQ,handleManagePayouts:eW,handleCheckMerchantStatus:ez,handlePurchaseTemplate:eZ,invalidateMyLibrary:e0,listOrderInvoices:e1,fetchTemplateDetails:e3,fetchCreatedMethodDetails:e7,fetchTemplateReviewDetails:e6,markTemplatePurchaseCompleted:e5,clearSelectedTemplateDetails:b,updateTemplateDetails:e8,updateTemplatePreviewTaskCount:e2,createTemplateVersion:e9,fetchTemplatePublicationState:te,handlePublishTemplate:tt,withdrawTemplateReview:ta,submitTemplateForReview:tr,handleUnpublishTemplate:tn,fetchPendingTemplateReviews:ti,approveTemplateReview:tl,declineTemplateReview:to,fetchCategoryReviews:tu,approveCategoryReview:tc,declineCategoryReview:tp,refreshExplorerCategoryMetadata:ts,searchTemplates:tm,searchAuthors:(0,r.useCallback)(async function(t){let a=arguments.length>1&&void 0!==arguments[1]?arguments[1]:8,r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:1,n=arguments.length>3?arguments[3]:void 0,l=arguments.length>4?arguments[4]:void 0;if(!e||!e.isRunning)return{authors:[],totalCount:0};try{var o,u,s;let d=await e.pushAndWait({type:"query",entity:"explorer",kind:"query",data:{action:"listAuthors",scope:"serp",search:t.trim()||void 0,page:r,pageSize:a,sortBy:n||void 0,categoryIds:(null==l?void 0:l.length)?l:void 0}}),c=null==d||null==(o=d.data)?void 0:o.listAuthors,p=null!=(u=null==c?void 0:c.authors)?u:[],m=null!=(s=null==c?void 0:c.totalCount)?s:0,g=i.QJ.getState().followedAuthors,f=p.map(e=>{let t=(0,P.X)(e);return{id:t.id,name:t.name||"",avatar:t.avatar,profilePicture:t.profilePicture,description:e.description||"",isVerified:t.isVerified,isFollowing:g.includes(e.id)}});if(0===f.length)return{authors:[],totalCount:m};let y=i.QJ.getState();return{authors:f.map(e=>({...e,templates:(0,L.p)(e,y)}
1)),totalCount:m}}catch(e){return{authors:[],totalCount:0}}},[e]),fetchAuthorMethodPreviewChunk:tf}}a(17547),a(7101);var e0=a(74454);let e1=new Map;function e4(e){let{onError:t,templateIds:a}=e,{engine:i,isReady:l}=(0,n.RI)(),o=(0,r.useMemo)(()=>[...new Set(a.filter(Boolean))].sort().join(","),[a]),u=(0,r.useRef)("");(0,r.useEffect)(()=>{if(!i||!l||!o||o===u.current)return;u.current=o;let e=o.split(",");(async()=>{let a=e1.get(o);if(a)return await a;let r=i.push({type:"query",entity:"explorer",data:{action:"userTemplateReviews",templateIds:e}}).then(()=>void 0);e1.set(o,r);try{await r}catch(e){u.current="",t&&t(e)}finally{e1.get(o)===r&&e1.delete(o)}})()},[i,l,t,o])}async function e5(e,t,a){let r;try{r=await fetch(t,{body:e,headers:{"Content-Type":a},method:"PUT"})}catch(e){throw Error("File upload failed")}if(!r.ok)throw Error("File upload failed")}function e3(e,t){if(!e||"object"!=typeof e)return null;let a=e.data;return a&&"object"==typeof a?a[t]:null}let e7=()=>{let[e,t]=(0,r.useState)(!1),[a,i]=(0,r.useState)(null),l=(0,n.Kj)();return{uploadFile:(0,r.useCallback)(async(e,a)=>{if(!l)return i("Upload service not available"),null;if(a&&!(0,c.Ewy)(a))return i("Cannot attach file: intent has not been saved yet. Please wait and try again."),null;let r=e.type.trim().toLowerCase()||"application/octet-stream",n=(0,c.a4J)(r);if(e.size>n.bytes)return i("File exceeds the ".concat(n.label," upload limit")),null;t(!0),i(null);let o=null;try{var u;let t=await l.pushAndWait({type:"createUpload",entity:"fileUpload",data:{input:{contentType:r,filename:e.name,size:e.size}},kind:"mutation",pendingQueuePolicy:"request-only"}),n=e3(t,"createUpload");if(!function(e){return!!e&&"object"==typeof e&&"string"==typeof e.expiresAt&&"string"==typeof e.key&&"string"==typeof e.presignedPutUrl&&"string"==typeof e.uploadId}(n))throw Error("Could not prepare file upload");await e5(e,n.presignedPutUrl,r);let i=null;for(let e=0;e<2&&null===i;e+=1){e>0&&await new Promise(e=>setTimeout(e,250));try{let e=await l.pushAndWait({type:"finalizeUpload",entity:"fileUpload",data:{uploadId:n.uploadId},kind:"mutation",pendingQueuePolicy:"request-only"}),t=e3(e,"finalizeUpload");(function(e){return!!e&&"object"==typeof e&&(null===e.fileName||"string"==typeof e.fileName)&&"string"==typeof e.id&&"string"==typeof e.url})(t)&&(i=t)}catch(e){}}if(null===i)throw Error("Could not finalize file upload");if(a){o=S(a);let e=await l.push({type:"addAttachment",entity:"intent",data:k({intentId:a,assetId:i.id,attachmentType:"EXTRA"},o),kind:"mutation"});T(o,e);try{await l.pushAndWait({type:"getById",entity:"intent",data:{id:a},kind:"query"})}catch(e){await l.push({type:"getById",entity:"intent",data:{id:a},kind:"query"})}}return{id:i.id,url:i.url,fileName:null!=(u=i.fileName)?u:e.name,size:e.size,type:e.type}}catch(e){return b(o),i(e instanceof Error?e.message:"Upload failed"),null}finally{t(!1)}},[l]),isUploading:e,uploadError:a}},e6=e=>{var t,a,l;let{engine:o,isReady:u}=(0,n.RI)(),{selectors:s}=(0,i.OP)(),d=(0,r.useRef)(null),p=(0,r.useRef)(void 0);p.current!==e&&(p.current=e,d.current=null);let m=null;if(e){let r=null!=(t=s.getIntentById(e))?t:null,n=null!=(a=s.getTemplateIntentById(e))?a:null;m=!function(e,t){if(!e||!t)return!!e;if(!e.isTemplate)return!1;if(e.type!==t.type)return!0;let a="draft"!==e.status&&"pending"!==e.status;return("draft"===t.status||"pending"===t.status)&&a}(n,r)&&r||n}let g=e,f=null,y=(null==m?void 0:m.isTemplate)===!0;m&&"method"===m.type&&m.parentId&&(g=m.parentId,f=m,y=!0===m.isTemplate);let h=s.getIntentById,v=s.getChildrenOf;y&&(h=s.getTemplateIntentById,v=s.getTemplateChildrenOf);let I=null;g&&(I=null!=(l=h(g))?l:null);let S=[];g&&(S=v(g).filter(e=>"method"===e.type));let k=null;return k=f||(0,c.zQd)(S,v),(0,r.useEffect)(()=>{g&&o&&u&&!I&&d.current!==g&&(0,c.Ewy)(g)&&(d.current=g,o.push({type:"query",entity:"intent",kind:"query",data:{action:"getById",id:g}}))},[g,I,o,u]),{goal:I,method:k,hasMethod:!!k,isLoading:!!(e&&!I&&(0,c.Ewy)(e))}},e8=()=>{let[e,t]=(0,r.useState)(!1),[a,i]=(0,r.useState)(null),l=(0,n.Kj)();return{removeAttachment:(0,r.useCallback)(async(e,a)=>{if(!l)return i("Remove service not available"),!1;if(!e||!(0,c.Ewy)(e))return console.warn("[useRemoveAttachment] Skipping â intentId is not a valid UUID:",e),i("Cannot remove attachment: invalid intent ID."),!1;t(!0),i(null);let r=null;try{r=S(e);let t=await l.push({type:"removeAttachments",entity:"intent",data:k({intentId:e,assetIds:[a]},r),kind:"mutation"});T(r,t);try{await l.pushAndWait({type:"getById",entity:"intent",data:{id:e},kind:"query"})}catch(t){await l.push({type:"getById",entity:"intent",data:{id:e},kind:"query"})}return!0}catch(e){return b(r),console.error("Attachment removal error:",e),i(e instanceof Error?e.message:"Removal failed"),!1}finally{t(!1)}},[l]),isRemoving:e,removeError:a}};function e2(e){return e&&"object"==typeof e?e:null}function e9(e){var t;let a=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},i=(0,n.Kj)(),l=null==(t=a.enabled)||t,o=(0,r.useRef)(0),[u,s]=(0,r.useState)({lifecycle:null,error:null,isFetching:!1,requestedIntentId:null}),d=(0,r.useCallback)(async()=>
1{if(!e)return s({lifecycle:null,error:Error("Missing intent id for calendar lifecycle."),isFetching:!1,requestedIntentId:null}),null;if(!(0,c.Ewy)(e))return s({lifecycle:null,error:Error("Invalid intent id for calendar lifecycle: ".concat(e)),isFetching:!1,requestedIntentId:e}),null;if(!i||!i.isRunning)return s({lifecycle:null,error:Error("Engine is not ready."),isFetching:!1,requestedIntentId:e}),null;let t=o.current+1;o.current=t,s({lifecycle:null,error:null,isFetching:!0,requestedIntentId:e});try{let a=await i.pushAndWait({type:"intentCalendarLifecycle",entity:"intent",kind:"query",data:{intentId:e}}),r=function(e){let t=e2(e);if(!t)return null;let a=e2(t.data);if(a){let e=a.intentCalendarLifecycle;if(e&&"object"==typeof e)return e}let r=t.intentCalendarLifecycle;return r&&"object"==typeof r?r:null}(a);if(!r)throw Error("Invalid intent calendar lifecycle response.");return o.current===t&&s({lifecycle:r,error:null,isFetching:!1,requestedIntentId:e}),r}catch(r){let a=r instanceof Error?r:Error(String(r));return o.current===t&&s({lifecycle:null,error:a,isFetching:!1,requestedIntentId:e}),null}},[i,e]);(0,r.useEffect)(()=>{l&&e&&d()},[l,e,d]);let p=(0,r.useMemo)(()=>!!u.isFetching||!!(l&&e&&(0,c.Ewy)(e))&&(u.requestedIntentId!==e||!u.lifecycle&&!u.error),[l,e,u.error,u.isFetching,u.lifecycle,u.requestedIntentId]);return{lifecycle:u.lifecycle,data:u.lifecycle,isLoading:p,error:u.error,refetch:d}}let te="draft-goal-id",tt="Could not check whether this Goal has a published Method. Please try again.",ta="Could not un-publish this Method. Please try again.";function tr(e){return"method"===e?"method":"goal"===e?"goal":null}function tn(e){return e.startsWith("intent-")}function ti(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},{deleteIntent:t,updateIntentStatus:a}=(0,i.cn)(),{fetchTemplatePublicationState:n,handleUnpublishTemplate:l}=eZ(),o=(0,i.Af)(e=>e.publishedSnapshotBySourceId);return function(e,t){let{deleteIntent:a,fetchTemplatePublicationState:n,getIntent:i,getPublishedSnapshot:l,unpublishTemplate:o,updateIntentStatus:u}=t,{onArchiveSuccess:s,onDeleteSuccess:d,onCompleteSuccess:c}=e,[p,m]=r.useState(!1),[g,f]=r.useState(null),[y,h]=r.useState(!1),[v,I]=r.useState(null),[S,k]=r.useState(!1),[T,b]=r.useState(null),[w,A]=r.useState(!1),[C,P]=r.useState(null),E=r.useRef(0),R=r.useRef(null),D=e9(null==g?void 0:g.id,{enabled:p&&null!==g}),B=e9(null==v?void 0:v.id,{enabled:y&&null!==v}),L=r.useCallback(e=>{let t=i(e);if(!t)return void console.error("Goal not found:",e);let a=tr(t.type);a&&(f({id:e,title:t.title,entityType:a}),m(!0))},[i]),_=r.useCallback(()=>{g&&(u(g.id,"archived"),null==s||s(g.id),f(null),m(!1))},[g,u,s]),M=r.useCallback(()=>{m(!1),f(null)},[]),U=r.useCallback(async(e,t)=>{let a=await n(e.id);if(E.current===t){if(!a||a.sourceIntentId!==e.id){I(e),b(null),P(tt),k(!0);return}if(a.liveTemplateId){I(e),b(a.liveTemplateId),P(null),k(!0);return}I(e),h(!0)}},[n]),q=r.useCallback(e=>{let t=E.current+1;if(E.current=t,tn(e)){if(tn(e))try{sessionStorage.getItem(te)===e&&sessionStorage.removeItem(te),sessionStorage.removeItem("".concat("draft-intent:").concat(e))}catch(e){}a(e),null==d||d(e);return}let r=i(e);if(!r)return void console.error("Goal not found:",e);let n=tr(r.type);if(!n)return;let o={id:e,title:r.title,entityType:n};if("method"===n){I(o),h(!0);return}let u=l(e);if(u){I(o),b(u.snapshotId),P(null),k(!0);return}P(null),U(o,t).catch(()=>{E.current===t&&(I(o),b(null),P(tt),k(!0))})},[a,i,l,d,U]),x=r.useCallback(()=>{v&&(a(v.id),null==d||d(v.id),I(null),h(!1))},[v,a,d]),F=r.useCallback(()=>{E.current+=1,h(!1),I(null)},[]),O=r.useCallback(()=>{R.current||(E.current+=1,k(!1),b(null),P(null),I(null))},[]),Q=r.useCallback(()=>{let e=R.current;if(e)return e;if(!v)return Promise.resolve();A(!0),P(null);let t=(async function(){let e=T;try{if(!e){let t=await n(v.id);if(!t||t.sourceIntentId!==v.id)return void P(tt);if(!t.liveTemplateId){k(!1),I(v),h(!0);return}e=t.liveTemplateId,b(e)}let t=await o(e);if(!t||t.draftIntentId!==v.id||t.unpublishedTemplateId!==e)return void P(ta);a(v.id),null==d||d(v.id),k(!1),b(null),I(null)}catch(e){P(ta)}})().finally(()=>{R.current===t&&(R.current=null),A(!1)});return R.current=t,t},[a,n,v,d,T,o]),N=r.useCallback(()=>{!R.current&&v&&(u(v.id,"archived"),null==s||s(v.id),k(!1),b(null),P(null),I(null))},[v,s,u]),j=r.useCallback(e=>{u(e,"completed"),null==c||c(e)},[u,c]);return{archiveModalOpen:p,goalToArchive:g,archiveLifecycle:D.lifecycle,archiveLifecycleLoading:D.isLoading,archiveLifecycleError:D.error,refetchArchiveLifecycle:D.refetch,handleArchiveGoal:L,confirmArchiveGoal:_,closeArchiveModal:M,deleteModalOpen:y,goalToDelete:v,deleteLifecycle:B.lifecycle,deleteLifecycleLoading:B.isLoading,deleteLifecycleError:B.error,refetchDeleteLifecycle:B.refetch,handleDeleteGoal:q,confirmDeleteGoal:x,closeDeleteModal:F,publishedDeleteModalOpen:S,publishedTemplateId:T,isPublishedDeleteProcessing:w,publishedDeleteError:C,confirmPublishedGoalDelete:Q,archivePublishedGoalInstead:N,closePublishedDeleteModal:O,handleCompleteGoal:j}}(e,{deleteIntent:t,fetchTemplatePublicationState:n,getIntent:r.useCallback(e=>i.Af.getState().data[e],[]),getPublishedSnapshot:r.useCallback(e=>o[e],[o]),unpublishTemplate:l,updateIntentStatus:a})}function tl(e){return{intent:(0,d.RD)(t=>e?t.data[e]:null),isLoading:(0,o.e)()}}var to=a(19008),tu=a(46633);function ts(e){return e instanceof Date?e:(0,tu.$j)(e)}let td=(e,t)=>{let{engine:a,isReady:l}=(0,n.RI)(),{fetchIntentEvents:o}=f(a),{selectors:u}=(0,i.OP)(),{goal:s,method:d,isLoading:c}=e6(e),p=(0,i.Sj)(e=>e.removeEventsByIntentId),m=(0,i.hv)(t=>!!e&&!0===t.preparingGoalIds[e]),g=(0,i.hv)(e=>e.finishSchedulePreparation),h=(0,r.useMemo)(()=>d?u.getChildrenOf(d.id).filter(e=>"task"===e.type):[],[d,u]),v=(0,r.useMemo)(()=>h.map(e=>e.id),[h]),I=(0,r.useMemo)(()=>v.join(","),[v]),[S,k]=(0,r.useState)(null);(0,r.useEffect)(()=>
1{if(0===v.length||!o||m||!l)return;let{events:e}=i.Sj.getState(),t=new Set(v),a=e.filter(e=>e.intentId&&t.has(e.intentId)),r=a.some(e=>(0,i.Y3)(e)&&!e.eventId),n=function(e,t){let a=new Set;for(let t of e)t.recurrence&&"none"!==t.recurrence.type&&a.add(t.id);if(0===a.size)return!1;let r=new Map;for(let e of t){var n;if(!e.intentId||!a.has(e.intentId)||!(0,i.Y3)(e)||!e.eventId)continue;let t=null!=(n=r.get(e.eventId))?n:0;r.set(e.eventId,t+1)}for(let e of t)if(e.intentId&&a.has(e.intentId)&&(0,i.Y3)(e)&&e.eventId&&e.id===e.eventId&&1===r.get(e.eventId))return!0;return!1}(h,a);(!(a.length>0)||r||n)&&(k(I),o(v))},[v,I,h,o,l,m]);let T=(0,i.Sj)(e=>e.events),b=(0,i.Sj)(e=>e.isLoading),w=(0,r.useMemo)(()=>new Set(v),[v]),A=(0,r.useMemo)(()=>(0,i.A)(T,{methodIntentIds:w}),[T,w]),C=(0,r.useCallback)(async()=>{if(a&&0!==v.length){for(let e of v)p(e);k(I),await a.pushAndWait({type:"query",entity:"event",kind:"query",data:{intentIds:v}})}},[a,p,v,I]),P=(0,r.useMemo)(()=>A.filter(e=>e.intentId&&w.has(e.intentId)),[A,w]),E=(0,r.useMemo)(()=>{let e=A.filter(e=>!e.intentId||!w.has(e.intentId));if(!(null==t?void 0:t.dateRange))return e;let{start:a,end:r}=t.dateRange,n=(0,to.e)(a,1),i=(0,y.f)(r,1);return e.filter(e=>{let t=e.startDate instanceof Date?e.startDate:(0,tu.$j)(e.startDate),a=e.endDate instanceof Date?e.endDate:(0,tu.$j)(e.endDate);return t<i&&a>n})},[A,w,null==t?void 0:t.dateRange]),R=(0,r.useCallback)((e,t)=>{let a=function(e,t){return e.source?e.source:t&&e.intentId?"truey":void 0}(e,t),r=ts(e.startDate),n=ts(e.endDate);return{id:e.id,title:e.title,start:r,end:n,color:e.color||"var(--color-surface-tertiary)",pattern:e.pattern||"solid",duration:e.duration,resource:{...e,source:a,eventType:e.eventType||"TODO",id:e.id,isDraft:!0===e.isDraft||"draft"===e.status,isMethodEvent:"truey"===a,isCurrentMethodEvent:t,intentTitle:e.title}}},[]),D=(0,r.useMemo)(()=>[...P.map(e=>R(e,!0)),...E.map(e=>R(e,!1))],[P,E,R]),B=(0,r.useMemo)(()=>Array.from(new Set(P.filter(e=>"draft"===e.status||e.isDraft).filter(e=>"string"==typeof e.eventId).map(e=>e.id).filter(e=>"string"==typeof e))),[P]);(0,r.useEffect)(()=>{let e=[],t=Object.keys(i.IF.getState().edits);if(0===t.length)return;let a=new Set(t);for(let t of P)a.has(t.id)&&"draft"!==t.status&&!0!==t.isDraft&&e.push(t.id);e.length>0&&i.IF.getState().clearEdits(e)},[P]);let L=B.length>0,_=!!(s&&!0!==s.isTemplate);return(0,r.useEffect)(()=>{e&&m&&L&&_&&g(e)},[g,L,_,m,e]),{method:d,tasks:h,events:D,rawEvents:P,hasDraftEvents:L,draftEventIds:B,hasLoadedMethodEvents:(0,r.useMemo)(()=>!c&&(0===v.length||S===I&&!b),[c,v.length,S,I,b]),reloadMethodEvents:C}},tc={DISCARD_UNAVAILABLE:"Copied replacement drafts are no longer used for publishing changes.",LISTING_UNAVAILABLE:"The approved Explorer listing could not be identified.",NOT_EDITABLE:"This Method is not editable in its current review state.",NOT_READY:"Publishing state is still loading. Try again in a moment.",PUBLICATION_FAILED:"Could not publish these changes. Your changes are still saved in Truey.",SOURCE_UNAVAILABLE:"The permanent source Method could not be identified. Refresh and try again.",SUBMISSION_UNAVAILABLE:"The pending Explorer submission could not be identified.",UNPUBLISH_FAILED:"Could not unpublish this Method. The approved listing is still live.",WITHDRAW_FAILED:"Could not withdraw this Method from review. Please try again."};function tp(e){return"string"==typeof e&&e.trim().length>0}function tm(e,t,a,r,n,i,l){let o={errorMessage:e,ok:!1};return t&&(o.draftId=t),a&&(o.listingId=a),r&&(o.errorCode=r),n&&(o.errorMetadata=n),i&&(o.submissionId=i),l&&(o.publicationBlocker=l),o}function tg(e,t){let a={ok:!0};return e&&(a.draftId=e),t&&(a.listingId=t),a}function tf(e){return!!e&&(!!e.liveTemplateId||!!e.latestSubmissionId||!!e.latestSubmittedRevision)}function ty(e){var t,a,l,o,u,s,d,c;let p,m=!1!==e.enabled,{engine:g,isReady:f}=(0,n.RI)();m&&(p=e.goalId);let{goal:y}=e6(p),h=eZ(),v=(0,i.Af)(e=>e.data),I=(0,i.QJ)(e=>e.templatePublicationStatesBySourceId),S=(0,i.QJ)(e=>e.templateQueryPagesByKey),[k,T]=(0,r.useState)(null),[b,w]=(0,r.useState)(!1),C=(0,r.useRef)(null),P=(0,r.useRef)(null),E=null;m&&(E=null!=(l=null!=(a=null==y?void 0:y.id)?a:e.goalId)?l:null);let R=(0,r.useMemo)(()=>
1{if(!E)return null;var e=E;for(let t of Object.values(S)){if("created-methods"!==t.scope)continue;let a=t.templates.find(t=>(function(e,t){var a,r,n;return e.id===t||(null==(a=e.sourceIntent)?void 0:a.id)===t||(null==(r=e.liveVersion)?void 0:r.id)===t||(null==(n=e.latestSubmission)?void 0:n.id)===t})(t,e));if(a)return a}return null},[E,S]),D=(0,r.useMemo)(()=>{var e;if(!E)return null;let t=function(e,t){let a=e[t];if(a)return a.sourceIntentId;for(let a of Object.values(e))if(a.liveTemplateId===t||a.pendingTemplateId===t||a.latestSubmissionId===t)return a.sourceIntentId;return null}(I,E);return t||((null==R||null==(e=R.sourceIntent)?void 0:e.id)?R.sourceIntent.id:(null==y?void 0:y.isTemplate)!==!0?E:null)},[E,R,null==y?void 0:y.isTemplate,I]),B=D&&null!=(o=I[D])?o:null,L=h.fetchTemplatePublicationState;(0,r.useEffect)(()=>{if(!m||!D||!f||!(null==g?void 0:g.isRunning))return;let e=!0,t=g.retainTemplatePublicationSource(D);return L(D).then(t=>{e&&!t&&T(tc.NOT_READY)}).catch(t=>{if(e){if(t instanceof Error&&tp(t.message))return void T(t.message);T(tc.NOT_READY)}}),()=>{e=!1,t()}},[g,L,m,f,D]);let _=(0,r.useMemo)(()=>(function(e){if(!e.activeRootId||!e.sourceId)return"ordinary";if(e.activeRootId===e.sourceId)return tf(e.publicationState)?"source":"ordinary";let t=e.publicationState;if(!t)return"locked";if(t.pendingTemplateId===e.activeRootId)return"under-review";if(t.liveTemplateId===e.activeRootId)return"approved-source";if(t.latestSubmissionId===e.activeRootId){if("DECLINED"===t.latestReviewStatus)return"declined";if("WITHDRAWN"===t.latestReviewStatus)return"withdrawn";if("PENDING"===t.latestReviewStatus)return"under-review"}return"locked"})({activeRootId:E,publicationState:B,sourceId:D}),[E,B,D]),M=null!=(u=null==B?void 0:B.liveTemplateId)?u:null,U=null!=(s=null==B?void 0:B.pendingTemplateId)?s:null;U||(null==B||null==(t=B.latestSubmission)?void 0:t.reviewStatus)!=="PENDING"||(U=B.latestSubmission.intentId);let q=function(e){if(e.isBusy)return"publishing";if(e.hasActionError)return"failed";let t=e.publicationState;return t&&"ordinary"!==e.context?t.hasPendingSubmission?"under-review":t.hasChangesSinceSubmission||t.hasChangesSinceApproval||t.hasUnpublishedChanges&&tf(t)?"dirty":t.liveTemplateId?"clean":null:null}({context:_,hasActionError:!!k,isBusy:b,publicationState:B}),x="under-review"===(d={context:_,createdMethodPublicationStatus:null==R?void 0:R.publicationStatus,listingId:M,publicationState:q}).context||"UNDER_REVIEW"===d.createdMethodPublicationStatus||"under-review"===d.publicationState?"Under review":"PUBLISHED"===d.createdMethodPublicationStatus||"CHANGES_NOT_PUBLISHED"===d.createdMethodPublicationStatus||d.listingId?"Published":"declined"===d.context||"withdrawn"===d.context||"PRIVATE"===d.createdMethodPublicationStatus||"UNPUBLISHED"===d.createdMethodPublicationStatus||"PUBLISHING_RESTRICTED"===d.createdMethodPublicationStatus||"dirty"===d.publicationState||"failed"===d.publicationState||"publishing"===d.publicationState?"Unpublished":null,F=(0,G.t)(B),O=(0,r.useMemo)(()=>"ordinary"!==_&&"source"!==_?null:(0,G.H)({action:F,publicationState:B}),[_,F,B]),Q=(null==y?void 0:y.status)==="archived",N=(0,r.useMemo)(()=>(function(e){let t="ordinary"===e.context||"source"===e.context,a=t&&!e.isArchived&&!e.isBusy,r=!1,n=!1;return"source"!==e.context||!e.publicationState||e.publicationState.hasPendingSubmission||e.isArchived||e.isBusy||("first-publish"===(0,G.t)(e.publicationState)?n=e.publicationState.canPublish:r=e.publicationState.canPublishChanges),{canDiscard:!1,canEditAttachments:a,canEditContent:a,canEditRecurrence:a,canEditStructure:a,canPublishChanges:r,canReorder:a,canStartEditing:!t&&!!e.sourceId&&!e.isArchived,canSubmitForReview:n,canUnpublish:!!e.listingId&&!e.isArchived&&!e.isBusy&&("source"===e.context||"approved-source"===e.context),canUseCalendar:t,canUseGoalActions:t,canUseMethodBrief:t,canViewListing:!!e.listingId,canViewSubmission:!!e.pendingTemplateId,canWithdrawReview:!!e.pendingTemplateId&&!e.isArchived&&!e.isBusy&&("source"===e.context||"under-review"===e.context)}})({context:_,isArchived:Q,isBusy:b,listingId:M,pendingTemplateId:U,publicationState:B,sourceId:D}),[_,Q,b,M,U,B,D]),j=N;m||(j={...N,canDiscard:!1,canEditAttachments:!1,canEditContent:!1,canEditRecurrence:!1,canEditStructure:!1,canPublishChanges:!1,canReorder:!1,canStartEditing:!1,canSubmitForReview:!1,canUnpublish:!1,canUseCalendar:!1,canUseGoalActions:!1,canUseMethodBrief:!1,canViewListing:!1,canViewSubmission:!1,canWithdrawReview:!1});let K=(c={context:_,isArchived:Q,isBusy:b}).isArchived?"archived":c.isBusy?"publishing":"under-review"===c.context?"under-review":"approved-source"===c.context||"declined"===c.context||"withdrawn"===c.context||"locked"===c.context?"locked":null,V=(0,r.useCallback)(async()=>{var e,t,a;
1if(!D){let t=tm(tc.SOURCE_UNAVAILABLE);return T(null!=(e=t.errorMessage)?e:tc.SOURCE_UNAVAILABLE),t}try{let e=await L(D);if(!e){let e=tm(tc.NOT_READY,D);return T(null!=(t=e.errorMessage)?t:tc.NOT_READY),e}return T(null),tg(D,null!=(a=e.liveTemplateId)?a:void 0)}catch(a){let e=tc.NOT_READY;a instanceof Error&&tp(a.message)&&(e=a.message);let t=tm(e,D);return T(e),t}},[L,D]),W=(0,r.useCallback)(async()=>{var e,t;if(!D||!g||!f){let t=tm(tc.SOURCE_UNAVAILABLE);return T(null!=(e=t.errorMessage)?e:tc.SOURCE_UNAVAILABLE),t}if("ordinary"===_||"source"===_)return T(null),tg(D,null!=M?M:void 0);let a=P.current;if(a)return a;let r=async function(){return v[D]||(await (0,A.S)(g,D,{shouldHydrateListedChildren:!0}))[D]?tg(D,null!=M?M:void 0):tm(tc.SOURCE_UNAVAILABLE)}();P.current=r,w(!0);try{let e=await r;return T(null!=(t=e.errorMessage)?t:null),e}finally{P.current=null,w(!1)}},[_,g,f,M,v,D]),z=(0,r.useCallback)(async()=>{var t,a,r;let n=C.current;if(n)return n;let i=j.canPublishChanges||j.canSubmitForReview;if(!D||!i){let e=tm(tc.NOT_EDITABLE,null!=D?D:void 0);return T(null!=(t=e.errorMessage)?t:tc.NOT_EDITABLE),e}if(!g&&!e.drainScopedMutations){let e=tm(tc.NOT_READY,D);return T(null!=(a=e.errorMessage)?a:tc.NOT_READY),e}let l=async function(){e.flushDeferredFields&&await e.flushDeferredFields(),e.drainScopedMutations?await e.drainScopedMutations(D):g&&await g.drainPublicationSourceMutations(D);let t=await h.handlePublishTemplate(D);if(!t.ok){var a;return tm(t.errorMessage,D,null!=M?M:void 0,t.errorCode,t.errorMetadata,null==(a=t.errorMetadata)?void 0:a.pendingTemplateId,t.publicationBlocker)}return tg(D,t.templateVersionId)}();C.current=l,w(!0);try{let e=await l;return T(null!=(r=e.errorMessage)?r:null),e}catch(a){let e=tc.PUBLICATION_FAILED;a instanceof Error&&tp(a.message)&&(e=a.message);let t=tm(e,D,null!=M?M:void 0);return T(e),t}finally{C.current=null,w(!1)}},[h,j.canPublishChanges,j.canSubmitForReview,g,M,e,D]),J=(0,r.useCallback)(async()=>{if(!M){var e;let t=tm(tc.LISTING_UNAVAILABLE,null!=D?D:void 0);return T(null!=(e=t.errorMessage)?e:tc.LISTING_UNAVAILABLE),t}return T(null),tg(null!=D?D:void 0,M)},[M,D]),H=(0,r.useCallback)(async()=>{if(!U){var e;let t=tm(tc.SUBMISSION_UNAVAILABLE,null!=D?D:void 0);return T(null!=(e=t.errorMessage)?e:tc.SUBMISSION_UNAVAILABLE),t}return T(null),tg(null!=D?D:void 0,U)},[U,D]),Y=(0,r.useCallback)(async()=>{var e;let t=tm(tc.DISCARD_UNAVAILABLE,null!=D?D:void 0,null!=M?M:void 0);return T(null!=(e=t.errorMessage)?e:tc.DISCARD_UNAVAILABLE),t},[M,D]),X=(0,r.useCallback)(async()=>{var e,t;let a=P.current;if(a)return a;if(!M||!j.canUnpublish){let t=tm(tc.NOT_EDITABLE,null!=D?D:void 0);return T(null!=(e=t.errorMessage)?e:tc.NOT_EDITABLE),t}let r=async function(){let e=await h.handleUnpublishTemplate(M);return(null==e?void 0:e.draftIntentId)?D&&e.draftIntentId!==D?tm(tc.SOURCE_UNAVAILABLE):tg(e.draftIntentId):tm(tc.UNPUBLISH_FAILED)}();P.current=r,w(!0);try{let e=await r;return T(null!=(t=e.errorMessage)?t:null),e}finally{P.current=null,w(!1)}},[h,j.canUnpublish,M,D]),$=(0,r.useCallback)(async()=>{var e,t;let a=P.current;if(a)return a;if(!U||!j.canWithdrawReview){let t=tm(tc.NOT_EDITABLE,null!=D?D:void 0);return T(null!=(e=t.errorMessage)?e:tc.NOT_EDITABLE),t}let r=U,n=async function(){var e,t;let a=await h.withdrawTemplateReview(r);return a.ok&&a.editableRootId?D&&a.editableRootId!==D?tm(tc.SOURCE_UNAVAILABLE):tg(a.editableRootId,null!=(t=a.liveTemplateId)?t:void 0):tm(null!=(e=a.errorMessage)?e:tc.WITHDRAW_FAILED)}();P.current=n,w(!0);try{let e=await n;return T(null!=(t=e.errorMessage)?t:null),e}finally{P.current=null,w(!1)}},[h,j.canWithdrawReview,U,D]);return{beginEditing:W,capabilities:j,context:_,discardReplacement:Y,draftId:D,editDisabledReason:K,errorMessage:k,isBusy:b,isTemplateEditContext:"ordinary"!==_,hasUnpublishedChangesDuringReview:!!((null==B?void 0:B.hasPendingSubmission)&&B.hasChangesSinceSubmission),listingId:M,publicationBlocker:O,publicationStatusLabel:x,publicationState:q,publishChanges:z,refreshPublicationState:V,resolveListing:J,resolveSubmission:H,unpublish:X,withdrawReview:$}}let th=new Map,tv=new Map;function tI(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:null;return{canOpenAdmin:!1,canReviewTemplates:!1,error:t,userId:e}}function tS(){let{user:e,isLoading:t}=u(),{engine:a,isReady:i}=(0,n.RI)(),l=null==e?void 0:e.id,[o,s]=(0,r.useState)(()=>tI(null)),[d,c]=(0,r.useState)(!1);(0,r.useEffect)(()=>
1{if(t)return;if(!l){s(tI(null)),c(!1);return}if(!a||!i)return void c(!0);let e=!1,r=function(e){var t;let a=null!=(t=tv.get(e))?t:{activeConsumerCount:0};return a.evictionTimeout&&(clearTimeout(a.evictionTimeout),delete a.evictionTimeout),a.activeConsumerCount+=1,tv.set(e,a),()=>{let t=tv.get(e);if(t&&(t.activeConsumerCount-=1,t.activeConsumerCount<=0)){if(t.activeConsumerCount=0,t.result||t.promise){t.evictionTimeout=setTimeout(()=>{let a=tv.get(e);a===t&&0===a.activeConsumerCount&&tv.delete(e)},3e4);return}tv.delete(e)}}}(l);return c(!0),(async()=>{try{let t=await function(e,t){let a=tv.get(t);if(null==a?void 0:a.result)return Promise.resolve(a.result);if(null==a?void 0:a.promise)return a.promise;let r=th.get(t);if(r)return a&&(a.promise=r,r.then(e=>{let a=tv.get(t);(null==a?void 0:a.promise)===r&&(a.result=e,delete a.promise)},()=>{let e=tv.get(t);(null==e?void 0:e.promise)===r&&delete e.promise})),r;let n=e.pushAndWait({type:"query",entity:"user",kind:"query",data:{action:"getPermissions",userId:t}}).then(e=>e);th.set(t,n),a&&(a.promise=n);let i=()=>{th.get(t)===n&&th.delete(t);let e=tv.get(t);(null==e?void 0:e.promise)===n&&delete e.promise};return n.then(e=>{let a=tv.get(t);(null==a?void 0:a.promise)===n&&(a.result=e,0===a.activeConsumerCount&&(a.evictionTimeout=setTimeout(()=>{let e=tv.get(t);e===a&&0===e.activeConsumerCount&&tv.delete(t)},3e4))),i()},()=>{i()}),n}(a,l);if(e)return;if(!1===t.success)return void s(tI(l,Error("Failed to load permissions.")));let r=function(e){if(!e||"object"!=typeof e||Array.isArray(e)||!Array.isArray(e.getPermissions))return null;for(let t of e.getPermissions)if(!t||"object"!=typeof t||"string"!=typeof t.object||"string"!=typeof t.permission||"string"!=typeof t.userId)return null;return e.getPermissions}(t.data);if(null===r)return void s(tI(l,Error("Failed to load permissions.")));let n=(0,x.WL)(r);s({canOpenAdmin:n,canReviewTemplates:n,error:null,userId:l})}catch(a){if(e)return;let t=Error("Failed to load permissions.");a instanceof Error&&(t=a),s(tI(l,t))}finally{e||c(!1)}})(),()=>{e=!0,r()}},[l,a,i,t]);let p=!!(l&&!t&&a&&i),m=!!(p&&o.userId===l),g=m&&o.canOpenAdmin,f=m&&o.canReviewTemplates,y=!!(l&&(!p||o.userId!==l)),h=null;return o.userId===l&&(h=o.error),{canOpenAdmin:g,canReviewTemplates:f,error:h,isLoading:t||d||y}}function tk(){let e=(0,n.Kj)(),t=(0,r.useCallback)(async function(t){let a=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(!e)return console.error("[useThreadActions] Engine not available"),{success:!1,correlationId:""};let{threadId:r,context:l="DASHBOARD",files:o}=a,u=(0,n.d$)("send-message"),s="temp_msg_".concat(Date.now(),"_").concat(Math.random().toString(36).substr(2,9));if(r){let e={id:s,type:"user",messageBody:t,files:o,correlationId:u,createdAt:new Date,updatedAt:new Date};i.eL.getState().addMessage(r,e)}e.getOptimisticState().register({entity:"message",operation:"create",correlationId:u,tempId:s,mutationData:{content:t,threadId:r,context:l,files:null==o?void 0:o.map(e=>e.id)}});try{if(await e.push({type:"mutation",entity:"message",data:{operation:"send",threadId:r,message:{text:t,context:l,files:o,correlationId:u}},kind:"mutation"}),r){let e={id:"typing-".concat(Date.now()),type:"action",action:"typing",timestamp:new Date().toISOString()};i.eL.getState().addMessage(r,e)}return{success:!0,correlationId:u}}catch(e){if(console.error("[useThreadActions] Failed to send message:",e),r){let e=i.eL.getState(),t=e.threads[r];if(t){let a=t.messages.filter(e=>e.id!==s&&!("action"===e.type&&"action"in e&&"typing"===e.action));e.updateThread(r,{messages:a}),e.addMessage(r,{id:"msg-error-".concat(Date.now()),type:"assistant",messageBody:"Sorry, I encountered an error processing your message. Please try again.",createdAt:new Date,updatedAt:new Date})}}return{success:!1,correlationId:u}}},[e]),a=(0,r.useCallback)(function(t){let a=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(!e)return void console.error("[useThreadActions] Engine not available");let{cursor:r,pageSize:n=20,direction:i="next"}=a;e.push({type:"query",entity:"message",data:{threadId:t,action:"getMessages",cursor:r,pageSize:n,direction:i},kind:"query"})},[e]),l=(0,r.useCallback)(function(e){let t=!(arguments.length>1)||void 0===arguments[1]||arguments[1];
1if(i.eL.getState().setActiveThread(e),e&&t){let t=i.eL.getState().threads[e];t&&0===t.messages.length&&a(e)}},[a]),o=(0,r.useCallback)(()=>{let e=Object.values(i.eL.getState().threads).find(e=>"DASHBOARD"===e.flowType);return e?(l(e.id),e.id):null},[l]);return{sendMessage:t,loadMessages:a,setActiveThread:l,getOrActivateDashboardThread:o,removeTypingIndicators:(0,r.useCallback)(e=>{let t=i.eL.getState(),a=t.threads[e];if(a){let r=a.messages.filter(e=>{var t;return!("action"===e.type&&"action"in e&&((null==(t=e.action)?void 0:t.includes("processing"))||"typing"===e.action))});t.updateThread(e,{messages:r})}},[]),isReady:!!e}}let tT=()=>{let{engine:e,isReady:t}=(0,n.RI)(),a=(0,i.eL)(e=>e.updateFromEngine),l=(0,i.eL)(e=>e.addMessage),o=(0,r.useRef)(!1);(0,r.useEffect)(()=>{if(e&&t&&!o.current)return e.registerStateUpdater("thread",e=>{let t={};if(Array.isArray(e)?t={threads:e}:e&&"object"==typeof e&&(t=e),t.threads&&Array.isArray(t.threads)){let e=t.threads.map(e=>!e.id&&e.threadId?{...e,id:e.threadId}:e);a({threads:e});let r=e.find(e=>"DASHBOARD"===e.flowType);if(r&&r.id){let e=i.eL.getState();e.activeThreadId||e.setActiveThread(r.id)}}else if("thread"in t&&t.thread){let e=t.thread;if(null==e?void 0:e.id){let t=i.eL.getState(),a=Object.values(t.threads).filter(e=>"syncing"===e.syncStatus).sort((e,t)=>t.createdAt.getTime()-e.createdAt.getTime())[0];a&&t.updateThread(a.id,{id:e.id,syncStatus:"synced",lastSyncedAt:new Date})}}}),e.registerStateUpdater("message",e=>{if(e&&"object"==typeof e&&"messages"in e&&Array.isArray(e.messages)){let t=e.threadId||i.eL.getState().activeThreadId,a=e=>{var t,a;if("type"in e&&"messageBody"in e)return e;let r=(null==(t=e.messageData)?void 0:t.text)||(null==(a=e.messageData)?void 0:a.message)||e.messageBody||"",n="ASSISTANT"===e.senderType||"assistant"===e.senderType?"assistant":"USER"===e.senderType||"user"===e.senderType?"user":e.type||"user";return{id:e.id,type:n,messageBody:r,createdAt:e.createdAt,updatedAt:e.updatedAt,..."assistant"===n&&{actions:["copy","regenerate"]}}};if(t){let r=i.eL.getState().threads[t],n=(null==r?void 0:r.messages)||[];if(e.isSubscriptionUpdate){if(!e.messages||0===e.messages.length)return;let r=e.messages.map(a),l=new Map;n.forEach(e=>{e.id&&"messageBody"in e&&e.messageBody&&""!==e.messageBody.trim()&&l.set(e.id,e)}),r.forEach(e=>{("action"!==e.type||!("action"in e)||"typing"!==e.action)&&"messageBody"in e&&e.messageBody&&""!==e.messageBody.trim()&&l.set(e.id,e)});let o=Array.from(l.values());o.sort((e,t)=>{let a="createdAt"in e?e.createdAt:void 0,r="createdAt"in t?t.createdAt:void 0;if(a&&r){let e=a instanceof Date?a:new Date(a),t=r instanceof Date?r:new Date(r);return e.getTime()-t.getTime()}return a&&!r?-1:!a&&r?1:0}),i.eL.getState().updateThread(t,{messages:o})}else{let r=e.messages.map(a);i.eL.getState().updateThread(t,{messages:r})}return}}if(e&&"object"==typeof e&&"completion"in e){let t=e.completion;if(t&&t.text){let e=i.eL.getState(),a=t.threadId||e.activeThreadId;if(t.threadId){if(!e.threads[t.threadId]){let e={id:t.threadId,title:"Chat Thread",subtitle:"Created automatically",messages:[],createdAt:new Date,updatedAt:new Date,syncStatus:"synced",flowType:"DASHBOARD"};i.eL.setState(a=>({...a,threads:{...a.threads,[t.threadId]:e}}))}a=t.threadId,e.setActiveThread(t.threadId)}if(a){let r=e.threads[a];if(r){let t=r.messages.filter(e=>{var t;return!("action"===e.type&&"action"in e&&((null==(t=e.action)?void 0:t.includes("processing"))||"typing"===e.action))});e.updateThread(a,{messages:t})}l(a,{id:t.id||"msg-".concat(Date.now()),type:"assistant",messageBody:t.text.message||"No response",actions:["copy","regenerate"],createdAt:t.createdAt?new Date(t.createdAt):new Date})}}}}),e.registerRollbackHandler("message",e=>{let{tempId:t,operation:a,mutationData:r}=e,n=null==r?void 0:r.threadId,l=i.eL.getState().activeThreadId,o=n||l;"create"===a&&t&&o&&i.eL.getState().removeMessageById(o,t)}),o.current=!0,()=>{e.unregisterStateUpdater("thread"),e.unregisterStateUpdater("message"),e.unregisterRollbackHandler("message"),o.current=!1}},[e,t,a,l])};function tb(){let e=(0,n.Kj)(),t=(0,r.useCallback)(async()=>
1{if(!e)throw Error("Engine is not ready");await e.pushAndWait({type:"query",entity:"user",kind:"query",data:{_requireFreshRead:!0,action:"getCurrentUser"}})},[e]);return{disconnectGoogleCalendar:(0,r.useCallback)(async()=>{var t;if(!e||!e.isRunning)throw Error("Engine is not ready");let{currentUserId:a}=i.kH.getState(),r=await e.pushAndWait({type:"mutation",entity:"user",kind:"mutation",data:{action:"detachUserCalendar"}}),n=null==r||null==(t=r.data)?void 0:t.detachUserCalendar;if(!n)throw Error("Invalid response from detachUserCalendar");return a&&e.upsertEntityItem("user",a,{connectedCalendarData:null}),n},[e]),refreshGoogleCalendarConnection:t}}var tw=a(12735);let tA=()=>{let{engine:e,isReady:t}=(0,n.RI)(),a=(0,i.kH)(e=>e.setUserData),l=(0,i.kH)(e=>e.setUser);(0,r.useEffect)(()=>{if(!e||!t)return;let r=null,n=!1,o=!1,u=()=>{var t;if(null!==r&&clearTimeout(r),r=null,o||n)return;let a=i.kH.getState(),l=a.currentUserId;if(!l)return;let s=null==(t=a.usersById[l])?void 0:t.connectedCalendarData;(null==s?void 0:s.isProvisioning)&&!s.isReauthRequired&&(r=setTimeout(()=>{if(r=null,o||i.kH.getState().currentUserId!==l)return;n=!0;let t=()=>{n=!1,u()};e.pushAndWait({type:"query",entity:"user",data:{_requireFreshRead:!0,action:"getCurrentUser"},kind:"query"}).then(t,t)},5e3))};e.registerStateUpdater("user",t=>{let r=t,n=!0;if(t&&"object"==typeof t&&(Array.isArray(t)&&t.length>0?r=t[0]:"currentUser"in t?r=t.currentUser:"updateUserProfile"in t?r=t.updateUserProfile:"finishOnboarding"in t?r=t.finishOnboarding:"detailUser"in t&&(r=t.detailUser,n=!1),r&&"object"==typeof r&&"id"in r)){var o,u,s,d,c,p;let t,m,g=r,f=g.id||"",y=f?i.kH.getState().usersById[f]:void 0,h=g.hasUserFinishedOnboarding;t=!0===h||!1!==h&&(null==y?void 0:y.hasUserFinishedOnboarding)===!0;let v=null==y?void 0:y.connectedCalendarData,I=!1;if(Object.prototype.hasOwnProperty.call(g,"connectedCalendarData")){let e=g.connectedCalendarData;null==e?v=e:"object"!=typeof e||Array.isArray(e)?v=null:(v={sub:null!=(o=e.sub)?o:"",email:null!=(u=e.email)?u:"",isReauthRequired:!0===e.isReauthRequired},"boolean"==typeof e.isProvisioning&&(v.isProvisioning=e.isProvisioning),I=!0)}let S=(0,tw.eA)();n&&S&&S.accountId!==f&&((0,tw.ro)(),S=null),n&&S&&null==v?(v={sub:"",email:S.email,isReauthRequired:!1,isProvisioning:!0},(0,tw.mR)(()=>{e.pushAndWait({type:"query",entity:"user",data:{_requireFreshRead:!0,action:"getCurrentUser"},kind:"query"}).catch(()=>{if(i.kH.getState().currentUserId!==f)return;let e=i.kH.getState().usersById[f];e&&a({...e,connectedCalendarData:null})})})):n&&S&&I&&(0,tw.ro)(),Array.isArray(g.categories)&&(m=g.categories.filter(e=>e&&"object"==typeof e).map(e=>({id:e.id||"",name:e.name||"",type:e.type,icon:e.icon})));let k="";"string"==typeof g.firstName&&(k=g.firstName.trim());let T="";"string"==typeof g.lastName&&(T=g.lastName.trim());let b="".concat(k," ").concat(T).trim();b||(b=null!=(d=null==y||null==(s=y.name)?void 0:s.trim())?d:"");let w={id:g.id||"",email:g.email||"",name:function(e,t){var a;let r="";"string"==typeof e.firstName&&(r=e.firstName.trim());let n="";"string"==typeof e.lastName&&(n=e.lastName.trim());let i=[r,n].filter(Boolean).join(" ");if(i)return i;if("string"==typeof e.name){let t=e.name.trim();if(t)return t}let l=null==t||null==(a=t.name)?void 0:a.trim();return l||""}(g,y),firstName:g.firstName||null,lastName:g.lastName||null,age:g.age||null,gender:g.gender||null,avatar:g.avatar||null,description:g.description||null,rating:parseFloat(String(null!=(c=g.rating)?c:"0"))||0,followCounter:g.followCounter||void 0,categories:m,bio:g.bio||null,coverImage:g.coverPhoto||null,coverPhoto:g.coverPhoto||null,stars:g.stars||void 0,followers:g.followers||void 0,createdAt:g.createdAt||new Date().toISOString(),updatedAt:g.updatedAt||new Date().toISOString(),connectedCalendarData:v,isVerified:g.isVerified||!1,hasUserFinishedOnboarding:t,role:g.role||"user",subscription:g.subscription||"free"};n?(a(w),I&&(null==y||null==(p=y.connectedCalendarData)?void 0:p.isProvisioning)===!0&&(null==v?void 0:v.isReauthRequired)===!1&&!1===v.isProvisioning&&e.invalidateCoveredEventRanges()):l(w)}});let s=i.kH.subscribe((e,t)=>{var a,r;let n=e.currentUserId?null==(a=e.usersById[e.currentUserId])?void 0:a.connectedCalendarData:void 0,i=t.currentUserId?null==(r=t.usersById[t.currentUserId])?void 0:r.connectedCalendarData:void 0;(e.currentUserId!==t.currentUserId||(null==n?void 0:n.isProvisioning)!==(null==i?void 0:i.isProvisioning)||(null==n?void 0:n.isReauthRequired)!==(null==i?void 0:i.isReauthRequired))&&u()});return u(),()=>{o=!0,s(),null!==r&&clearTimeout(r),e.unregisterStateUpdater("user")}},[e,t,l,a])};var tC=a(44794);function tP(e){let{isActive:t}=e,{engine:a,isReady:l}=(0,n.RI)(),o=(0,i.kH)(e=>e.currentUserId),u=(0,r.useMemo)(()=>({engine:a,isReady:l,userId:o,isActive:t}),[a,l,o,t]),s=(0,r.useRef)(null),d=(0,r.useRef)(0),c=(0,r.useRef)(null),[p,m]=(0,r.useState)({scope:null,flags:null,isLoading:!1,pendingKey:null,error:null}),g=(0,r.useCallback)(()=>s.current===u&&u.isActive&&i.kH.getState().currentUserId===u.userId,[u]),f=(0,r.useCallback)(async()=>
1{if(!a||!l||!o||!g()||c.current===u)return;let e=++d.current;m(e=>({scope:u,flags:e.scope===u?e.flags:null,isLoading:!0,pendingKey:null,error:null}));try{let t=await a.pushAndWait({type:"query",entity:"featureFlag",kind:"query",data:{action:"list",_requireFreshRead:!0,__skipStateProjection:!0}});if(!g()||e!==d.current)return;let r=tC.TK.safeParse(t);if(!r.success)throw Error("Could not read feature flags: invalid response.");m({scope:u,flags:r.data.data.featureFlags,isLoading:!1,pendingKey:null,error:null})}catch(t){if(!g()||e!==d.current)return;m(e=>({...e,isLoading:!1,error:t instanceof Error?t.message:"Could not load feature flags."}))}},[a,l,o,g,u]);(0,r.useEffect)(()=>(s.current=u,m({scope:u,flags:null,isLoading:!1,pendingKey:null,error:null}),f(),()=>{s.current=null,c.current===u&&(c.current=null)}),[u,f]);let y=(0,r.useCallback)(async e=>{if(!a||!l||!o||!g()||c.current===u||p.scope!==u||null===p.flags||p.isLoading)return!1;let t=tC.Ly.safeParse(e);if(!t.success)return m(e=>({...e,error:"Enter a valid feature flag definition."})),!1;let r=t.data;c.current=u,++d.current,m(e=>({...e,pendingKey:r.key,error:null}));try{let e=await a.pushAndWait({type:"mutation",entity:"featureFlag",kind:"mutation",pendingQueuePolicy:"request-only",data:{action:"upsert",input:r,__skipStateProjection:!0}});if(!g())return!1;if(!tC.jW.safeParse(e).success)throw Error("Feature flag was not confirmed saved. Refresh and try again.");return m(e=>{var t;let a=null!=(t=e.flags)?t:[],n=a.some(e=>e.key===r.key);return{...e,flags:n?a.map(e=>e.key===r.key?r:e):[...a,r],pendingKey:null,error:null}}),!0}catch(e){return g()&&m(t=>({...t,pendingKey:null,error:e instanceof Error?e.message:"Could not save feature flag."})),!1}finally{c.current===u&&(c.current=null)}},[a,l,o,g,u,p.scope,p.flags,p.isLoading]),h=t&&p.scope===u;return{flags:h?p.flags:null,isLoading:t&&!!o&&(!l||!h||p.isLoading),pendingKey:h?p.pendingKey:null,isSaving:h&&null!==p.pendingKey,error:h?p.error:null,load:f,save:y}}},74454:(e,t,a)=>{a.d(t,{m:()=>o});var r=a(12115),n=a(54658),i=a(99863);let l=new WeakMap;function o(e){let{tabKey:t,enabled:a,hasSliceData:o,fetch:u,staleMs:s=3e5,clearLoadingOnSuccess:d=!0,markFreshOnSuccess:c=!0,onFetchStart:p,onFetchSuccess:m,onFetchError:g}=e,{engine:f,isReady:y}=(0,n.RI)(),h=(0,r.useRef)(o);h.current=o;let v=(0,r.useRef)(u);v.current=u;let I=(0,r.useRef)(s);I.current=s;let S=(0,r.useRef)(d);S.current=d;let k=(0,r.useRef)(c);k.current=c;let T=(0,r.useRef)(p);T.current=p;let b=(0,r.useRef)(m);b.current=m;let w=(0,r.useRef)(g);w.current=g,(0,r.useEffect)(()=>{a&&f&&y&&o&&S.current&&i.QJ.getState().setIsLoading(!1)},[f,y,a,o]),(0,r.useEffect)(()=>{var e,r,n;let o;if(!a||!f||!y)return;let u=null!=(r=i.QJ.getState().tabSyncState[t])?r:null,s=h.current,d=null!=u&&Date.now()-u<I.current,{setIsLoading:c,setIsValidating:p}=i.QJ.getState(),m=null!=(n=null==(e=f.getLifecycleSnapshot)?void 0:e.call(f))?n:0,g=((o=l.get(f))||(o=new Map,l.set(f,o)),o),A="".concat(m,":").concat(t),C=!1,P=v.current,E=S.current,R=k.current,D=T.current,B=b.current,L=w.current,_=()=>{C||null==B||B()},M=e=>{C||null==L||L(e)},U=async e=>{let a,r=!1,n="function"!=typeof f.retainExplorerBackgroundSyncKeysInFlight?()=>void 0:f.retainExplorerBackgroundSyncKeysInFlight([t]);try{C||null==D||D(),await P(),r=!0,_(),R&&f.upsertEntityItem("explorerSyncState",t,{lastFetchedAt:Date.now()})}catch(e){a=e,M(e)}finally{if(n(r),!C){let t=i.QJ.getState();e?t.setIsValidating(!1):(E||!r)&&t.setIsLoading(!1)}g.delete(A)}return{didFetchSucceed:r,error:a}};if(s&&d)return c(!1),()=>{C=!0};let q=g.get(A);if(q)return q.then(e=>{if(C)return;let t=i.QJ.getState();if(e.didFetchSucceed?s||_():M(e.error),!C){if(s)return void t.setIsValidating(!1);(E||!e.didFetchSucceed)&&t.setIsLoading(!1)}}).catch(e=>{if(C||(M(e),C))return;let t=i.QJ.getState();s?t.setIsValidating(!1):t.setIsLoading(!1)}),()=>{C=!0};let x=!1;if("function"==typeof f.isExplorerBackgroundSyncInFlightForKey?x=f.isExplorerBackgroundSyncInFlightForKey(t):"function"==typeof f.isExplorerBackgroundSyncInFlight&&(x=f.isExplorerBackgroundSyncInFlight()),x)return s||c(!0),(async()=>{let e,a="home-default"===t;
1if("function"==typeof f.waitForExplorerBackgroundSyncKey)try{await f.waitForExplorerBackgroundSyncKey(t)}catch(t){e=t}else if(a&&"function"==typeof f.runExplorerHomeWarmup)try{await f.runExplorerHomeWarmup()}catch(t){e=t}else if("function"==typeof f.runExplorerBackgroundSync)try{await f.runExplorerBackgroundSync()}catch(t){e=t}if(C)return;if(!e&&h.current){_(),E&&i.QJ.getState().setIsLoading(!1);return}let r=g.get(A);if(r){let e=await r;if(C)return;if(e.didFetchSucceed){!h.current&&(_(),E&&i.QJ.getState().setIsLoading(!1));return}if(M(e.error),h.current)return}let n=U(!1);g.set(A,n)})().catch(()=>{C||i.QJ.getState().setIsLoading(!1)}),()=>{C=!0};s?p(!0):c(!0);let F=U(s);return g.set(A,F),()=>{C=!0}},[f,y,a,t])}},87030:(e,t,a)=>{a.d(t,{e:()=>n});var r=a(58637);function n(e){let t=function(e){var t,a,r;if(!(null==(t=e.tasks)?void 0:t.length)||!(null==(a=e.steps)?void 0:a.length))return e;let n=new Map;for(let t of e.steps){let e=null==(r=t.parent)?void 0:r.id;e&&(n.has(e)||n.set(e,[]),n.get(e).push(function(e){let t={id:e.id,title:e.title,description:e.description,rationale:e.rationale,order:e.order};return void 0!==e.duration&&(t.duration=e.duration),t}(t)))}return 0===n.size?e:{...e,tasks:e.tasks.map(e=>{if(e.children&&e.children.length>0)return e;let t=n.get(e.id);return t?{...e,children:t.sort((e,t)=>e.order-t.order)}:e})}}(e),a=function(e){if(!e)return;let t=(0,r.sN)({authorId:e.id,avatar:e.avatar});return t===e.avatar?e:{...e,avatar:t}}(t.author),n=t;a!==t.author&&(n={...t,author:a});let i=function(e){var t,a;let n=null==e?void 0:e.author;if(!e||!n)return e;let i=(0,r.sN)({authorId:null!=(t=n.id)?t:void 0,avatar:null!=(a=n.avatar)?a:void 0});return i===n.avatar?e:{...e,author:{...n,avatar:i}}}(n.originalTemplate);i!==n.originalTemplate&&(n={...n,originalTemplate:i});let l=function(e){var t,a;let r=[...null!=(t=e.attachments)?t:[],...(null!=(a=e.methods)?a:[]).flatMap(e=>{var t;return null!=(t=e.attachments)?t:[]})],n=new Set;return r.filter(e=>!n.has(e.id)&&(n.add(e.id),!0))}(n);return 0===l.length&&void 0===n.attachments?n:{...n,attachments:l}}}}]);
Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.