PageSourceSearch

https://www.tracefiction.com/assets/index-Cp6Mk7n4.js

js tracefiction.com collected 2026-10-02 01:46:29 UTC 298,393 bytes, 5 lines download raw bytes

1const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/IPhoneSetupPage-efMDVY-5.js","assets/vendor-react-2mXWPygV.js","assets/vendor-app-Dz59apZY.js","assets/vendor-ui-BInLtbYF.js","assets/device-setup-BgaopxTg.css","assets/story-updates-surfaces.component-fW5MaEt7.js","assets/slide-over.component-CHomslcp.js","assets/use-overlay-focus-return-Ds4tDfMz.js","assets/story-update-context.component-BECkWl3i.js","assets/story-update-context-BbLd27cF.css","assets/story-updates-surfaces-BoSqp_lX.css","assets/MyStories-DPVKcTCZ.js","assets/format-compact-number-CxZfytn2.js","assets/useLibraryStickyChromeHeight-wJENPMje.js","assets/select.component-f6V8CInH.js","assets/useMinLg-BspfyuGX.js","assets/archive-masthead.component-4Yfx0GZ5.js","assets/mobile-primary-header.component-utDTvT7I.js","assets/archive-state-frame.component-B86kijZd.js","assets/setup-paths-CNuxu_dK.js","assets/first-story-activation-BLMmSc5Z.js","assets/rating.component-DPDKD9Os.js","assets/useCollectionActionDialog-Dp02eJzH.js","assets/index-FJnU_1X8.js","assets/SuggestionsPage-BGApgL5t.js","assets/StatsPage-lvfyK-zQ.js","assets/index-D09DlCsk.js","assets/SettingsPage-CbRersiT.js","assets/AppsPage-mcI6481d.js","assets/LandingPublicFooter-DZEzw8Fv.js","assets/landing.styles-_jTDm3Hb.js","assets/SetupPage-DbbILx0z.js","assets/LandingProductSections-9fbVU4yb.js","assets/ImportPage-uG0YfxhH.js","assets/AdminPage-Zv03GluY.js","assets/vendor-charts-BZSoBqRC.js","assets/UpdatesPage-B7YBtmEK.js","assets/Landing-kAmRRf46.js","assets/ReaderPage-D5bwifui.js","assets/MobileShellAuth-ad8bhLlM.js","assets/Privacy-C4v7STZ5.js","assets/legal-prose-classes-DMfk970t.js","assets/Terms-CwwXB30A.js","assets/About-De470AU-.js","assets/Support-DpOe24aj.js","assets/NotFound-wqOTQyCV.js","assets/MaintenancePage-D-ATM8Kj.js","assets/AuthCallbackPage-CleLWd3j.js"])))=>i.map(i=>d[i]);
2import{r as y,j as i,L as J,u as Te,c as na,R as Y,b as Fl,d as Bl,e as z,f as Hl,B as Vl}from"./vendor-react-2mXWPygV.js";import{u as ke,s as n,Z as se,p as q,a as it,_ as f,o as r,n as u,l as _,b as x,c as pe,d as H,e as V,f as p,g as ot,h as lt,i as C,t as Wl,j as Ce,k as he,m as Er,q as ns,v as wr,w as an,x as jt,y as Xt,z as $l,A as Yl,B as Mi,C as Gl,Q as zl,H as ql,D as Kl}from"./vendor-app-Dz59apZY.js";import{t as Ql,c as Jl,b as fe,B as Ar,H as Xl,M as Zl,d as ed,e as td,f as nd,g as ad,h as rd,i as id,j as od,k as as,l as sd,m as rs,n as is,o as cd,p as ld,u as dd,q as Fi,C as ud,r as md,D as pd,s as hd,v as fd,w as _d,x as gd,y as bd,z as os,A as rn,T as Bi,E as Hi,F as yd,G as vd,I as Sd,J as xd,K as Ed,L as Vi,N as wd,O as Ad,P as Rd,Q as Td,R as kd,S as Cd,U as Nd,V as Id,W as Od,X as Pd,Y as Ld}from"./vendor-ui-BInLtbYF.js";(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const m of document.querySelectorAll('link[rel="modulepreload"]'))c(m);new MutationObserver(m=>{for(const h of m)if(h.type==="childList")for(const d of h.addedNodes)d.tagName==="LINK"&&d.rel==="modulepreload"&&c(d)}).observe(document,{childList:!0,subtree:!0});function a(m){const h={};return m.integrity&&(h.integrity=m.integrity),m.referrerPolicy&&(h.referrerPolicy=m.referrerPolicy),m.crossOrigin==="use-credentials"?h.credentials="include":m.crossOrigin==="anonymous"?h.credentials="omit":h.credentials="same-origin",h}function c(m){if(m.ep)return;m.ep=!0;const h=a(m);fetch(m.href,h)}})();const Dd="modulepreload",jd=function(e){return"/"+e},Wi={},M=function(t,a,c){let m=Promise.resolve();if(a&&a.length>0){let o=function(s){return Promise.all(s.map(l=>Promise.resolve(l).then(b=>({status:"fulfilled",value:b}),b=>({status:"rejected",reason:b}))))};document.getElementsByTagName("link");const d=document.querySelector("meta[property=csp-nonce]"),v=d?.nonce||d?.getAttribute("nonce");m=o(a.map(s=>{if(s=jd(s),s in Wi)return;Wi[s]=!0;const l=s.endsWith(".css"),b=l?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${s}"]${b}`))return;const g=document.createElement("link");if(g.rel=l?"stylesheet":Dd,l||(g.as="script"),g.crossOrigin="",g.href=s,v&&g.setAttribute("nonce",v),document.head.appendChild(g),l)return new Promise((E,w)=>{g.addEventListener("load",E),g.addEventListener("error",()=>w(new Error(`Unable to preload CSS for ${s}`)))})}))}function h(d){const v=new Event("vite:preloadError",{cancelable:!0});if(v.payload=d,window.dispatchEvent(v),!v.defaultPrevented)throw d}return m.then(d=>{for(const v of d||[])v.status==="rejected"&&h(v.reason);return t().catch(h)})},Rr=2.99,aa=24.99;function ra(e){return`$${e.toFixed(2)}`}const Ud=ra(Rr),Md=ra(aa),Fd=ra(aa/12),Bd=Number((Rr*12-aa).toFixed(2)),Hd=ra(Bd),Hn="https://www.tracefiction.com",vw=`${Hn}/og-default.png`,Vd="trace — A reading memory for fanfiction",$i="Trace is a private fanfiction reading memory for AO3, FanFiction.net, and downloaded AO3 EPUBs: keep your place, remember what you tried, and gather it in one searchable library.",Sw="Trace Reader — Offline AO3 EPUB Reader for iPhone and iPad",Wd="A polished, accessible EPUB reader built around downloaded AO3 fanfiction, with powerful library tools and optional Trace sync.",$d="https://github.com/tracefiction/trace-browser-extension";function Tr(e){const t=e?.trim()||Hn;try{const a=new URL(t);return a.hostname==="tracefiction.com"&&(a.hostname="www.tracefiction.com"),a.pathname=a.pathname.replace(/\/+$/,""),a.search="",a.hash="",a.toString().replace(/\/$/,"")}catch{return Hn}}function xw(e,t){const a=Tr(e),c=`${a}/landing`,m=`${a}/og-default.png`;return{"@context":"https://schema.org","@graph":[{"@type":"Organization","@id":`${a}/#organization`,name:"Trace",url:a,logo:`${a}/180_logo.png`,sameAs:[$d]},{"@type":"WebSite","@id":`${a}/#website`,name:"Trace",url:a,description:"A private fanfiction reading memory for browser and EPUB reading.",publisher:{"@id":`${a}/#organization`}},{"@type":"WebPage","@id":`${c}#webpage`,url:c,name:Vd,description:$i,isPartOf:{"@id":`${a}/#website`},primaryImageOfPage:{"@type":"ImageObject",url:m},about:[{"@type":"Thing",name:"fanfiction reading memory"},{"@type":"Thing",name:"organizing fanfiction"},{"@type":"Thing",name:"AO3 reading progress tracking"},{"@type":"Thing",name:"FanFiction.net reading progress tracking"},{"@type":"Thing",name:"AO3 EPUB reader"},{"@type":"Thing",name:"AO3 saved filter views"},{"@type":"Thing",name:"fanfiction collections"}],mainEntity:{"@id":`${a}/#software`}},{"@type":"SoftwareApplication","@id":`${a}/#software`,name:"Trace",alternateName:"tracefiction",applicationCategory:"LifestyleApplication",applicationSubCategory:"Fanfiction reading library",operatingSystem:"Web, iOS, iPadOS, browser extension",url:c,image:m,description:$i,audience:{"@type":"Audience",audienceType:"Fanfiction readers"},isAccessibleForFree:!0,keywords:["fanfiction library","fanfiction organizer","fanfiction collections","AO3 reading tracker","AO3 saved filters","FanFiction.net reading tracker","AO3 EPUB reader","offline fanfiction reader","reading progress tracker","private reading memory"],featureList:["Organize browser and EPUB reading in one private searchable library.","Save works while browsing and see reading memory directly on archive pages.","Track reader states: Saved, Reading, Caught up, Paused, Finished, and Dropped.","Keep chapter progress current as you read.","Store personal notes, tags, ratings, and collections.","Read downloaded AO3 EPUBs offline without uploading EPUB files or story text.","Save AO3 filter views and return to the searches you use often.","Sync y
2our library across phone, laptop, and browser sessions."],offers:[{"@type":"Offer",name:`Free library up to ${t} works`,price:"0",priceCurrency:"USD",description:`Free for libraries up to ${t} works, with no time limit and no ads.`},{"@type":"Offer",name:"Unlimited monthly storage",price:Rr.toFixed(2),priceCurrency:"USD",description:"Unlimited library storage billed monthly."},{"@type":"Offer",name:"Unlimited yearly storage",price:aa.toFixed(2),priceCurrency:"USD",description:"Unlimited library storage billed yearly."}],softwareHelp:`${a}/support`,potentialAction:{"@type":"RegisterAction",target:c,name:"Start your library"}}]}}function Ew({siteOrigin:e,readerIosAppStoreUrl:t}){const a=Tr(e);return{"@context":"https://schema.org","@type":"MobileApplication",name:"Trace Reader",alternateName:"Trace — Offline EPUB Reader",applicationCategory:"BookApplication",operatingSystem:"iOS, iPadOS",url:`${a}/reader`,downloadUrl:t,image:`${a}/reader/app-icon.png`,description:Wd,isAccessibleForFree:!0,audience:{"@type":"Audience",audienceType:"Fanfiction readers"},featureList:["Read downloaded AO3 EPUBs with accessible themes, typography, and layouts.","Search and filter by AO3 fandoms, relationships, characters, tags, warnings, categories, completion status, and rating.","Organize reading status, ratings, personal tags, notes, and progress.","Automatically import new and updated AO3 EPUBs from approved folders.","Keep previous EPUB versions available to restore without cluttering the library.","Optionally connect Trace to bring browser and EPUB reading together.","Keep EPUB files and story text on the device."]}}function Oe(e){return e?.trim()||void 0}const ss="6791213935",Yd=`https://apps.apple.com/app/id${ss}`,cs="6761776345",Gd=`https://apps.apple.com/app/id${cs}`,ls={siteUrl:Tr(Oe(void 0)??Hn),iosAppStoreUrl:Oe("https://apps.apple.com/au/app/trace-fanfiction-library/id6761776345")??Gd,appleAppId:Oe(void 0)??cs,readerIosAppStoreUrl:Oe(void 0)??Yd,readerAppleAppId:Oe(void 0)??ss,chromeWebStoreUrl:Oe("https://chromewebstore.google.com/detail/ijajgeibblcknobjakpcjdkelfojappi?utm_source=item-share-cb"),safariExtensionGalleryUrl:Oe(void 0),edgeAddonsUrl:Oe(void 0),firefoxAddonsUrl:Oe("https://addons.mozilla.org/en-GB/firefox/addon/tracefiction/"),supportEmail:Oe(void 0)??"[email protected]"},kr="trace:auth-return-to-v1",Cr="trace:auth-logout-return-v1",ds="trace_logout",tr="trace:auth-login-prompt-after-logout-v1",Nr="trace:auth-return-outcome-v1",nr="/auth/callback",Yi="https://www.tracefiction.com/auth/callback",zd=/TraceFictionWebShell\/\d/i,qd="trace_app",Vn="trace:native_shell";function Kd(){if(typeof window>"u")return!1;try{return new URLSearchParams(window.location.search).get(qd)==="1"}catch{return!1}}function us(){return typeof window<"u"&&window.__TRACE_NATIVE_SHELL__===!0||typeof window<"u"&&window.webkit?.messageHandlers?.traceBilling||Kd()?!0:typeof navigator>"u"?!1:zd.test(navigator.userAgent)}function Qd(){if(!(typeof window>"u")){try{if(sessionStorage.getItem(Vn)==="1")return}catch{return}if(us())try{sessionStorage.setItem(Vn,"1")}catch{}}}function F(){if(typeof window<"u")try{if(sessionStorage.getItem(Vn)==="1")return!0}catch{}if(us()){try{sessionStorage.setItem(Vn,"1")}catch{}return!0}return!1}function Jd(){return F()?window.__TRACE_NATIVE_APP__?.httpsAuthCallbackURL===Yi?Yi:"traceauth://callback":`${window.location.origin}${nr}`}function Xd(){return F()?(Zd(),`traceauth://callback?${ds}=1`):window.location.origin}function ms(){return F()?(eu(),{openUrl:!1}):{logoutParams:{returnTo:Xd()}}}function Ir(){return`${window.location.pathname}${window.location.search}${window.location.hash}`}function Wn(e){try{sessionStorage.setItem(kr,e)}catch{}}function Zd(){try{sessionStorage.setItem(Cr,"1")}catch{}}function eu(){try{sessionStorage.setItem(tr,"1")}catch{}}function ww(){try{return sessionStorage.getItem(tr)!=="1"?!1:(sessionStorage.removeItem(tr),!0)}catch{return!1}}function tu(){try{const e=sessionStorage.getItem(kr);return typeof e=="string"&&e.length>0?e:null}catch{return null}}function nu(){try{sessionStorage.removeItem(kr)}catch{}}function au(e){try{sessionStorage.setItem(Nr,e)}catch{}}function ru(){try{return sessionStorage.getItem(Nr)==="oauth_callback_completed"?"oauth_callback_completed":"authenticated_session"}catch{return"authenticated_session"}}function iu(){try{sessionStorage.removeItem(Nr)}catch{}}function Gi(){try{sessionStorage.removeItem(Cr)}catch{}}function ou(e){try{const t=new URLSearchParams(e);return t.has("code")||t.has("state")||t.has("error")||t.has("error_description")}catch{return!1}}function su(e){try{return new URLSearchParams(e).get(ds)==="1"}catch{return!1}}function Aw(e){const t=typeof window>"u"?"":window.location.search,a=su(t),c=ou(t);let m=!1;try{m=sessionStorage.getItem(Cr)==="1"}catch{}return a||m&&!c?(Gi(),!0):(m&&c&&Gi(),!1)}
2function cu(e,t){const a=e?.returnTo,c=tu(),m=typeof a=="string"&&a.length>0?a:c??t;return nu(),m}function lu(e={}){const t=e.userAgent??"",a=e.userAgentData?.platform??e.platform??"";return/iPhone|iPad|iPod/i.test(t)||/^(iOS|iPadOS)$/i.test(a)||(/Macintosh/i.test(t)||/MacIntel|macOS/i.test(a))&&(e.maxTouchPoints??0)>1?{platform:"ios",path:"iphone_app"}:/Android/i.test(t)||/Android/i.test(a)?{platform:"android",path:/Firefox\//i.test(t)?"android_firefox":"android_switch_firefox"}:{platform:"desktop",path:"desktop"}}function du(){return!1}function Rw(){return!1}const Tw="https://addons.mozilla.org/firefox/addon/tracefiction/";function kw(){return lu(typeof navigator>"u"?{}:navigator)}function uu(){return du()}const mu=["/setup","/signup","/sign-up","/onboarding","/extension-setup","/open-trace"];function pu(e){const t=e.replace(/\/+$/,"")||"/";return mu.some(a=>t===a||["/setup","/onboarding","/extension-setup"].includes(a)&&t.startsWith(`${a}/`))}function I(...e){return Ql(Jl(e))}const ps=fe(["inline-flex items-center justify-center gap-1.5 whitespace-nowrap select-none","border border-border bg-transparent text-content-primary","font-medium leading-none","rounded-[var(--control-radius)]","transition-colors duration-150","hover:bg-hover hover:border-border-strong","active:bg-active active:border-border-strong","focus-visible:outline-none focus-visible:shadow-ring","disabled:opacity-50 disabled:shadow-none","cursor-pointer disabled:cursor-not-allowed"].join(" "),{variants:{variant:{solid:"border-transparent bg-[var(--action-primary-bg)] text-[var(--action-primary-fg)] font-semibold hover:bg-[var(--action-primary-hover-bg)] active:bg-[var(--action-primary-hover-bg)] disabled:hover:bg-[var(--action-primary-bg)]",outline:"aria-pressed:border-accent-600/35 aria-pressed:bg-accent-100 aria-pressed:text-content-primary",ghost:"border-transparent bg-transparent hover:bg-hover active:bg-active aria-pressed:bg-accent-100",link:"h-auto justify-start border-0 bg-transparent p-0 text-content-primary underline underline-offset-4 hover:border-0 hover:bg-transparent active:bg-transparent disabled:no-underline",danger:"border-transparent bg-danger-600 text-[var(--solid-button-fg)] hover:bg-danger-700 active:bg-danger-700 disabled:hover:bg-danger-600",menu:"h-auto w-full justify-start rounded-2xs border-0 bg-transparent px-2.5 py-2 text-sm text-content-primary hover:border-0 hover:bg-hover active:bg-active aria-current:bg-hover aria-expanded:bg-hover",cta:"h-12 rounded-sm border-transparent bg-[var(--action-primary-bg)] px-6 text-base font-semibold text-[var(--action-primary-fg)] hover:bg-[var(--action-primary-hover-bg)] active:bg-[var(--action-primary-hover-bg)] disabled:hover:bg-[var(--action-primary-bg)]"},size:{sm:"h-[var(--control-h)] px-4 text-sm",md:"h-field px-3 text-sm",lg:"h-11 px-4 text-base"},fullWidth:{true:"w-full"}},defaultVariants:{variant:"outline",size:"md"}}),L=y.forwardRef(({variant:e,size:t,fullWidth:a,loading:c=!1,disabled:m,leftIcon:h,rightIcon:d,className:v,children:o,...s},l)=>{const b=m||c,g=c||!!h;return i.jsxs(Ar,{ref:l,disabled:b,"aria-busy":c||void 0,focusableWhenDisabled:c?!0:s.focusableWhenDisabled,className:I(ps({variant:e,size:t,fullWidth:a}),v),...s,children:[g&&i.jsx("span",{className:"inline-flex h-4 w-4 items-center justify-center [&_svg]:h-4 [&_svg]:w-4","aria-hidden":"true",children:c?i.jsx("span",{className:"h-4 w-4 animate-spin rounded-full border-2 border-current border-t-transparent"}):h}),i.jsx("span",{className:I(c&&"opacity-90"),children:o}),!c&&d&&i.jsx("span",{className:"inline-flex h-4 w-4 items-center justify-center [&_svg]:h-4 [&_svg]:w-4","aria-hidden":"true",children:d})]})});L.displayName="Button";const hu="ml-[0.06em] align-super text-[0.58em] font-normal italic leading-none text-[var(--danger-600)]",fu={landing:"font-landing-serif",archive:"font-landing-serif",default:""};function $n({surface:e,className:t}){return i.jsx("span",{className:I(hu,fu[e],t),"aria-hidden":!0,children:"beta"})}const hs="trace.theme",Na="theme-transition-disabled";let Yt=null;function ar(e){const t=document.documentElement;if(t.classList.add(Na),t.dataset.theme=e,typeof window>"u"){t.classList.remove(Na);return}Yt!==null&&window.cancelAnimationFrame(Yt),Yt=window.requestAnimationFrame(()=>{Yt=window.requestAnimationFrame(()=>{t.classList.remove(Na),Yt=null})})}function _u(){return typeof window<"u"&&window.matchMedia("(prefers-color-scheme: dark)").matches?"dar
2k":"archive"}function Yn(e){switch(e){case"light":return"archive";case"dark":return"dark";case"system":return _u()}}function fs(){try{const e=localStorage.getItem(hs);return e==="light"||e==="dark"||e==="system"?e:e==="sticker"?"dark":"light"}catch{return"light"}}function gu(e){try{localStorage.setItem(hs,e)}catch{}}function bu(){const e=fs();ar(Yn(e))}const rr=new Set;let _s=fs();function yu(e){return rr.add(e),()=>rr.delete(e)}function vu(){for(const e of rr)e()}function zi(){return _s}function Or(){const e=y.useSyncExternalStore(yu,zi,zi),t=y.useCallback(a=>{_s=a,gu(a),ar(Yn(a)),vu()},[]);return y.useEffect(()=>{if(e!=="system")return;const a=window.matchMedia("(prefers-color-scheme: dark)"),c=()=>ar(Yn("system"));return a.addEventListener("change",c),()=>a.removeEventListener("change",c)},[e]),{preference:e,setPreference:t}}function Su({signedIn:e=!1,actionsDisabled:t=!0,onCopyCollection:a=()=>{},onReportCollection:c=()=>{},onSignIn:m=()=>{}}){const{preference:h,setPreference:d}=Or(),v=Yn(h)==="dark",o=v?rs:is;return i.jsxs("header",{className:I("public-collection-topbar",e&&"is-signed-in"),role:"banner",children:[i.jsxs(J,{to:"/",className:"public-collection-logo","aria-label":"Trace home",children:[i.jsx("img",{src:"/trace-mark.svg",alt:""}),i.jsxs("span",{children:["trace",i.jsx($n,{surface:"archive"})]})]}),i.jsxs("div",{className:"public-collection-topbar-actions",children:[i.jsxs("div",{className:"public-collection-header-actions",children:[i.jsx(L,{type:"button",variant:"outline",size:"sm",className:"public-collection-header-action",disabled:t,leftIcon:i.jsx(Xl,{}),onClick:a,children:"Copy link"}),i.jsxs(Zl,{children:[i.jsx(ed,{type:"button",className:"public-collection-header-menu-trigger","aria-label":"More public collection actions",disabled:t,children:i.jsx(td,{"aria-hidden":!0})}),i.jsx(nd,{children:i.jsx(ad,{side:"bottom",align:"end",sideOffset:8,children:i.jsx(rd,{className:"library-app archive-editorial-shell public-collection-header-menu",children:i.jsxs(id,{className:"public-collection-header-menu-item",onClick:c,children:[i.jsx(od,{"aria-hidden":!0}),i.jsx("span",{children:"Report collection"})]})})})})]})]}),e?i.jsxs(i.Fragment,{children:[i.jsxs(J,{to:"/",className:"public-collection-header-library","aria-label":"Your library",children:[i.jsx(as,{"aria-hidden":!0}),i.jsx("span",{children:"Your library"})]}),i.jsxs("span",{className:"public-collection-signed-in-chip",children:[i.jsx("span",{className:"public-collection-signed-in-avatar","aria-hidden":!0,children:i.jsx(sd,{})}),i.jsx("span",{children:"Signed in"})]})]}):null,i.jsx("button",{type:"button",className:"public-collection-theme-toggle","aria-label":v?"Switch to light theme":"Switch to dark theme",title:v?"Switch to light theme":"Switch to dark theme",onClick:()=>d(v?"light":"dark"),children:i.jsx(o,{"aria-hidden":!0})}),e?null:i.jsx("button",{type:"button",className:"public-collection-header-pill",onClick:m,children:"Log in"})]})]})}const xu=["sticky top-0 z-50 w-full max-w-full overflow-visible","bg-[color-mix(in_oklab,var(--landing-bg)_86%,transparent)]","border-b border-[var(--line)]","transition-[background,box-shadow] duration-300"].join(" "),Eu="pt-[max(env(safe-area-inset-top),44px)]",wu="mx-auto flex max-w-[1140px] items-center justify-between gap-3 overflow-visible px-4 py-[13px] sm:gap-4 sm:px-[22px]",Au=["inline-flex min-w-0 items-center gap-2 overflow-visible leading-none sm:gap-3","no-underline","hover:opacity-90","focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--landing-secondary)] focus-visible:ring-offset-2 focus-visible:ring-offset-[var(--landing-bg)]"].join(" "),Ru="block h-[38px] w-auto shrink-0 rounded-[11px]",Tu=["inline-block min-w-0 max-w-full whitespace-nowrap text-[24px] font-semibold italic tracking-normal font-landing-serif","text-[var(--landing-on-surface)]"].join(" "),ku=["inline-flex items-center leading-none","relative top-px","font-landing text-sm tracking-normal","text-[color-mix(in_oklab,var(--landing-on-surface)_72%,var(--landing-bg))] transition-colors duration-200","hover:text-[var(--landing-primary)]","focus-visible:outline-none focus-visible:text-[var(--landing-primary)]"].join(" "),Cu="hidden items-center gap-[26px] self-center md:flex",Nu="flex shrink-0 items-center gap-1.5 sm:gap-2";function qi(e){const t=document.getElementById(e);if(!t)return;const a=window.matchMedia("(prefers-reduced-motion: reduce)").matches;t.scrollIntoView({behavior:a?"instant":"smooth",block:"start"}),window.history.replaceState(null,"",`#${e}`)}const Ki=[{type:"hash",hash:"chaos",label:"The problem"}
2,{type:"hash",hash:"how",label:"How it works"},{type:"hash",hash:"trust",label:"Privacy"}],En="/landing";function Iu(){const{isAuthenticated:e,loginWithRedirect:t}=ke(),a=Te(),c=na(),m=y.useRef(null),[h,d]=y.useState(!1),v=F(),o=Ir(),s=()=>{const g=o;Wn(g),t({appState:{returnTo:g},authorizationParams:{screen_hint:"signup"}})},l=()=>{const g=o;Wn(g),t({appState:{returnTo:g}})},b=g=>{if(a.pathname!=="/")return;g.preventDefault();const E=window.matchMedia("(prefers-reduced-motion: reduce)").matches;window.scrollTo({top:0,behavior:E?"instant":"smooth"}),a.hash&&c("/",{replace:!0})};return y.useEffect(()=>{if(typeof document>"u")return;const g=document.documentElement,E=document.body,w=document.querySelector('meta[name="theme-color"]'),T=g.style.backgroundColor,D=E.style.backgroundColor,R=w?.getAttribute("content")??null,k=()=>{const X=m.current?.closest(".landing")??m.current,Z=(X?window.getComputedStyle(X).getPropertyValue("--landing-bg").trim():"")||"Canvas";g.style.backgroundColor=Z,E.style.backgroundColor=Z,w?.setAttribute("content",Z)};k();const W=new MutationObserver(k);return W.observe(g,{attributes:!0,attributeFilter:["data-theme"]}),()=>{W.disconnect(),g.style.backgroundColor=T,E.style.backgroundColor=D,R===null?w?.removeAttribute("content"):w?.setAttribute("content",R)}},[]),i.jsxs(i.Fragment,{children:[i.jsx("a",{href:"#main-content",className:I("sr-only focus:not-sr-only focus:fixed focus:left-4 focus:z-[100] focus:rounded-lg focus:bg-white focus:px-4 focus:py-2 focus:text-sm focus:font-medium focus:text-black focus:shadow-lg focus:ring-2 focus:ring-blue-500",v?"focus:top-[calc(0.75rem+env(safe-area-inset-top))]":"focus:top-4"),children:"Skip to main content"}),i.jsxs("header",{ref:m,className:I(xu,v&&Eu),children:[i.jsxs("div",{className:wu,children:[i.jsxs("div",{className:"flex min-w-0 items-center gap-8",children:[i.jsxs(J,{to:"/",className:Au,"aria-label":"Home",onClick:b,children:[i.jsx("img",{src:"/trace-mark.svg",alt:"",width:40,height:40,className:Ru,decoding:"async"}),i.jsxs("span",{className:Tu,children:["trace",i.jsx($n,{surface:"landing"})]})]}),i.jsx("nav",{className:Cu,"aria-label":"Page",children:Ki.map(g=>i.jsx(J,{to:`${En}#${g.hash}`,className:ku,onClick:E=>{a.pathname===En&&a.hash===`#${g.hash}`&&(E.preventDefault(),qi(g.hash))},children:g.label},g.hash))})]}),i.jsxs("div",{className:Nu,children:[e?i.jsx(L,{nativeButton:!1,render:i.jsx(J,{to:"/"}),variant:"solid",size:"sm",className:"landing-ink-button border-transparent px-4 text-[var(--landing-on-primary)] hover:brightness-[1.04] sm:px-5",children:"Open library"}):i.jsxs(i.Fragment,{children:[i.jsx(L,{type:"button",variant:"ghost",size:"sm",className:"border-transparent px-2 text-[var(--landing-muted)] hover:bg-[var(--landing-surface-high)] hover:text-[var(--landing-on-surface)] sm:px-3",onClick:l,children:"Sign in"}),i.jsx(L,{type:"button",variant:"solid",size:"sm",className:"landing-ink-button border-transparent px-4 text-[var(--landing-on-primary)] hover:brightness-[1.04] sm:px-5",onClick:s,children:"Start your library"})]}),i.jsxs("button",{type:"button",className:"hidden rounded-md p-2 text-[var(--landing-muted)] hover:bg-[var(--landing-surface-high)] md:hidden","aria-expanded":h,"aria-controls":"landing-mobile-nav",onClick:()=>d(g=>!g),children:[h?i.jsx(cd,{className:"h-6 w-6","aria-hidden":!0}):i.jsx(ld,{className:"h-6 w-6","aria-hidden":!0}),i.jsx("span",{className:"sr-only",children:"Menu"})]})]})]}),h?i.jsx("div",{id:"landing-mobile-nav",className:"absolute inset-x-0 top-full px-6 pb-4 md:hidden",children:i.jsxs("nav",{className:"landing-paper-panel flex flex-col gap-3 rounded-[24px] px-5 py-5","aria-label":"Page mobile",children:[Ki.map(g=>i.jsx(J,{to:`${En}#${g.hash}`,className:"text-left font-landing text-sm font-medium text-[var(--landing-on-surface)]",onClick:E=>{d(!1),a.pathname===En&&a.hash===`#${g.hash}`&&(E.preventDefault(),qi(g.hash))},children:g.label},g.hash)),e?i.jsx(L,{nativeButton:!1,render:i.jsx(J,{to:"/",onClick:()=>{d(!1)}}),variant:"solid",size:"sm",className:"landing-ink-button border-transparent text-[var(--landing-on-primary)]",children:"Open library"}):i.jsxs(i.Fragment,{children:[i.jsx(L,{type:"button",variant:"ghost",size:"sm",className:"justify-start border-transparent text-[var(--landing-muted)]",onClick:()=>{d(!1),l()},children:"Sign in"}),i.jsx(L,{type:"button",variant:"solid",size:"sm",className:"landing-ink-button border-transparent text-[var(--landing-on-primary)]",onClick:()=>{d(!1),s()},children:"Start your library"})]})]})}):null]})]})}function ne({className:e}){return i.jsx("span",{className:["archive-state-shimmer block rounded-pill","animate-[archive-shimmer_1.4s_ease-in-out_infinite]","bg-[linear-gradient(90deg,var(--paper-2),var(--paper-3),var(--paper-2))]","bg-[length:200%_100%]",e].join(" ")})}function Ou(){return i.jsxs("article",{className:"public-story-row","aria-hidden":!0,
2children:[i.jsx(ne,{className:"public-story-ordinal h-8 w-10 rounded-[var(--radius-v9-md)]"}),i.jsxs("div",{className:"public-story-body",children:[i.jsx(ne,{className:"h-6 w-3/5 rounded-[var(--radius-v9-md)]"}),i.jsx(ne,{className:"mt-4 h-3 w-2/5"}),i.jsx(ne,{className:"mt-3 h-3 w-4/5"}),i.jsx(ne,{className:"mt-2 h-3 w-1/2"}),i.jsxs("div",{className:"mt-4 flex flex-wrap gap-2",children:[i.jsx(ne,{className:"h-6 w-20"}),i.jsx(ne,{className:"h-6 w-24"}),i.jsx(ne,{className:"h-6 w-16"})]})]}),i.jsx("div",{className:"public-story-action",children:i.jsx(ne,{className:"h-9 w-32 rounded-[var(--radius-v9-md)]"})})]})}function Qi({loadingRows:e,statusLabel:t}){return i.jsx("main",{className:"public-collection-main",children:i.jsx("div",{className:"public-collection-body",children:i.jsxs("section",{className:"grid gap-8",role:"status","aria-live":"polite","aria-label":t,children:[i.jsx("div",{className:"public-collection-masthead","aria-hidden":!0,"data-testid":"public-route-skeleton",children:i.jsxs("div",{className:"public-collection-masthead-copy",children:[i.jsx(ne,{className:"h-3 w-36"}),i.jsx(ne,{className:"mt-5 h-11 w-full max-w-[34rem] rounded-[var(--radius-v9-md)]"}),i.jsx(ne,{className:"mt-4 h-4 w-full max-w-[42rem]"}),i.jsx(ne,{className:"mt-2 h-4 w-2/3 max-w-[31rem]"}),i.jsxs("div",{className:"mt-5 flex flex-wrap gap-3",children:[i.jsx(ne,{className:"h-3 w-24"}),i.jsx(ne,{className:"h-3 w-32"}),i.jsx(ne,{className:"h-3 w-20"})]})]})}),i.jsx("div",{"aria-hidden":!0,children:Array.from({length:e}).map((a,c)=>i.jsx(Ou,{},c))})]})})})}function ue({chrome:e="landing",loadingRows:t=2,statusLabel:a="Loading Trace page"}){const{isAuthenticated:c}=ke();return e==="landing"?i.jsxs("div",{className:"landing min-h-dvh font-landing text-[var(--landing-on-surface)]",children:[i.jsx(Iu,{}),i.jsx("div",{className:"library-app",children:i.jsx(Qi,{loadingRows:t,statusLabel:a})})]}):i.jsxs("div",{className:"library-app archive-editorial-shell public-collection-shell",children:[i.jsx(Su,{signedIn:c,actionsDisabled:!0}),i.jsx(Qi,{loadingRows:t,statusLabel:a})]})}function Pu(){return i.jsx(ue,{chrome:"collection",statusLabel:"Loading shared collection"})}const Lu="https://api.tracefiction.com".replace(/\/+$/,"");function Du(e,t){const a=t.startsWith("/")?t:`/${t}`,c=e.replace(/\/+$/,"");return c?`${c}${a}`:a}function ju(e){return Du(Lu,e)}function Cw(e,t=window.location.pathname){}function Uu(e=!0){const{pathname:t,key:a}=Te(),c=y.useRef(null);y.useEffect(()=>{e&&c.current!==a&&(c.current=a)},[a,t,e])}y.lazy(()=>M(()=>import("./IPhoneSetupPage-efMDVY-5.js"),__vite__mapDeps([0,1,2,3,4])));function Mu({children:e}){const{pathname:t}=Te(),{isAuthenticated:a}=ke(),c=uu();return Uu(pu(t)||c),i.jsxs(i.Fragment,{children:[c,e]})}function Fu(){const e=y.useRef(null);return y.useLayoutEffect(()=>{if(typeof document>"u")return;const t=document.documentElement,a=document.body,c=document.getElementById("root"),m=document.querySelector('meta[name="theme-color"]'),h=t.style.backgroundColor,d=a.style.backgroundColor,v=c?.style.backgroundColor??null,o=m?.getAttribute("content")??null,s=e.current?window.getComputedStyle(e.current):null,l=window.getComputedStyle(t),b=s?.getPropertyValue("--paper").trim()||l.getPropertyValue("--paper").trim()||l.getPropertyValue("--bg-app").trim()||"Canvas";return t.style.backgroundColor=b,a.style.backgroundColor=b,c&&(c.style.backgroundColor=b),m?.setAttribute("content",b),()=>{t.style.backgroundColor=h,a.style.backgroundColor=d,c&&v!==null&&(c.style.backgroundColor=v),o===null?m?.removeAttribute("content"):m?.setAttribute("content",o)}},[]),e}function gs(){const e=dd(),t=Fu();return i.jsx("div",{ref:t,className:"library-app archive-editorial-shell flex min-h-dvh flex-col items-center justify-center overflow-hidden bg-[var(--paper)] px-6 text-[var(--ink)]",children:i.jsxs("div",{className:"flex w-full max-w-[18rem] flex-col items-center gap-5 text-center",role:"status","aria-live":"polite","aria-label":"Loading Trace",children:[i.jsx("div",{className:"flex h-16 w-16 items-center justify-center rounded-[var(--radius-v9-xl)] border border-[var(--line-strong)] bg-[var(--paper-2)] shadow-[var(--shadow-sm)]",children:i.jsx("img",{src:"/trace-mark.svg",alt:"",width:44,height:44,className:"h-11 w-11 rounded-[var(--radius-v9-md)] opacity-[0.96]",decoding:"async"})}),i.jsxs("div",{className:"grid gap-2",children:[i.jsx("p",{className:"font-mono text-[length:var(--type-v9-eyebrow)] font-medium uppercase leading-none tracking-[0.22em] text-[var(--honey)]",children:"Trace"}),i.jsx("p",{className:"font-landing-serif text-[length:var(--type-v9-lede)] italic leading-snug text-[var(--ink-2)]",children:"Opening your archive."})]}
2),i.jsxs("div",{className:"grid w-full gap-2","aria-hidden":!0,children:[i.jsx("span",{className:"h-2 rounded-pill bg-[color-mix(in_oklab,var(--paper-2)_72%,var(--paper-3))]"}),i.jsx("span",{className:"relative h-2 overflow-hidden rounded-pill bg-[var(--paper-2)]",children:e?i.jsx("span",{className:"block h-full w-full rounded-pill bg-[color-mix(in_oklab,var(--honey)_38%,var(--paper-3))]"}):i.jsx(Fi.span,{className:"absolute inset-y-0 block w-2/5 rounded-pill bg-[linear-gradient(90deg,var(--forest-deep),var(--honey),var(--forest-deep))]",initial:{left:"-42%"},animate:{left:"100%"},transition:{duration:1.15,repeat:1/0,ease:"easeInOut",repeatDelay:.1}})}),e?i.jsx("span",{className:"h-2 w-2/3 rounded-pill bg-[color-mix(in_oklab,var(--paper-2)_72%,var(--paper-3))]"}):i.jsx(Fi.div,{className:"h-2 w-2/3 rounded-pill bg-[linear-gradient(90deg,var(--paper-2),var(--paper-3),var(--paper-2))] bg-[length:200%_100%]",initial:{backgroundPosition:"200% 0"},animate:{backgroundPosition:"-200% 0"},transition:{duration:1.4,repeat:1/0,ease:"easeInOut"}})]})]})})}const Ct=["library"],Ia=["library-views"],wn=["collections"],Ji=["public-collections"],B={me:["me"],accountPublicAttribution:["account","public-attribution"],accountReleaseNotice:e=>["account","release-notice",e],accountAdvocacyActivityMarker:e=>["account","advocacy-activity-marker",e],suggestions:["suggestions"],watches:{all:["watches"],setup:["watches","setup"],candidates:["watches","candidates"],operatorStatus:["watches","operator-status"],status:["watches","status"],inbox:(e=30)=>["watches","inbox",{limit:e}],preferences:["watches","preferences"],forwardingVerification:e=>["watches","forwarding-verification",e]},stats:{all:["stats"],summary:e=>["stats","summary",e]},library:{all:Ct,storyUpdatesCount:[...Ct,"story-updates-count"],list:e=>[...Ct,e],detail:e=>[...Ct,"detail",e],tagSuggestions:e=>[...Ct,"tag-suggestions",e],privateTagSuggestions:e=>[...Ct,"private-tag-suggestions",e]},libraryViews:{all:Ia,list:()=>[...Ia,"list"],detail:e=>[...Ia,"detail",e]},collections:{all:wn,list:()=>[...wn,"list"],detail:e=>[...wn,"detail",e],share:e=>[...wn,"share",e]},publicCollections:{detail:e=>[...Ji,"detail",e],libraryStates:(e,t,a)=>[...Ji,"library-states",e,t,a??null]},stories:{catalog:e=>["stories",e],detail:e=>["story",e],potentialMatches:e=>["story-matches",e]},admin:{overview:(e,t)=>["admin","overview",e,t],dashboard:["admin","dashboard"],feedback:e=>["admin","feedback",e],collectionReports:e=>["admin","collectionReports",e],collectionReport:e=>["admin","collectionReport",e],publicLinkDomains:e=>["admin","publicLinkDomains",e],moderationAuditEvents:e=>["admin","moderationAuditEvents",e],pendingAliases:["admin","pendingAliases"],canonicalSearch:e=>["admin","canonicalSearch",e]}};function Bu(){const e=F(),t=/iPhone|iPad|iPod|Android/i.test(navigator.userAgent)||navigator.platform==="MacIntel"&&navigator.maxTouchPoints>1,a={"X-Trace-Platform":e?"ios_shell":t?"web_mobile":"web_desktop"},c=window.__TRACE_NATIVE_APP__?.version;return e&&typeof c=="string"&&/^[0-9]{1,4}(\.[0-9]{1,4}){0,3}$/.test(c)&&(a["X-Trace-App-Version"]=c),a}const Hu=500,bs=n().trim().max(Hu).url().superRefine((e,t)=>{let a;try{a=new URL(e)}catch{return}a.protocol!=="http:"&&a.protocol!=="https:"&&t.addIssue({code:se.custom,message:"Public links must use HTTP or HTTPS"}),(a.username||a.password)&&t.addIssue({code:se.custom,message:"Public links must not include credentials"}),/\s/u.test(e)&&t.addIssue({code:se.custom,message:"Public links must not include whitespace"})});function Vu(e){const t=bs.safeParse(e);return t.success?t.data:null}const ys=q(e=>typeof e=="string"&&e.trim()===""?null:e,bs.nullable()),Pr=it().transform(Vu),Gn=e=>q(t=>typeof t=="string"&&t.trim()===""?null:t,n().trim().max(e).nullable()),vs=f(["anonymous","profile"]),Wu=r({default_mode:vs,display_name:Gn(80),handle:Gn(60),url:ys}).strict().superRefine((e,t)=>{e.default_mode==="profile"&&!e.display_name&&t.addIssue({code:se.custom,path:["display_name"],message:"A public display name is required for profile attribution"})}),$u=r({default_mode:vs,display_name:Gn(80),handle:Gn(60),url:Pr}).strict().superRefine((e,t)=>
2{e.default_mode==="profile"&&!e.display_name&&t.addIssue({code:se.custom,path:["display_name"],message:"A public display name is required for profile attribution"})}),Xi=r({public_attribution:$u}),Yu=f(["not_started","in_progress","completed","dismissed"]),Lr=r({version:_(1),status:Yu,step:u().int().min(1).max(3)}).strict(),Dr=f(["reader-1.0.0"]);r({noticeId:Dr}).strict();const Gu=r({library_discovery_dismissed:x().optional(),post_first_story_onboarding:Lr.optional()}).strict().refine(e=>e.library_discovery_dismissed!==void 0||e.post_first_story_onboarding!==void 0,{message:"At least one UI setting is required"}),zu=r({ok:_(!0),library_discovery_dismissed:x(),post_first_story_onboarding:Lr.default({version:1,status:"not_started",step:1})}).strict(),qu=r({notice_id:Dr,dismissed:x()}).strict(),Ku=r({ok:_(!0),notice_id:Dr,dismissed:_(!0)}).strict(),Ss=f(["feedback","review","share"]),xs=r({ok:_(!0)}).strict(),Qu=r({latest_activity_at:n().datetime().nullable()}).strict(),Ju=r({review_available:x()}).strict(),Xu=r({prompt:Ss.nullable()}).strict(),Zu=r({prompt:Ss}).strict(),em=xs,tm=f(["pending","completed"]),nm=r({state:tm}).strict(),am=f(["none","stripe","apple","both"]),rm=f(["active","trialing","past_due","unpaid","canceled","incomplete","incomplete_expired","paused"]),im=r({provider:am,stripe:r({present:x(),active:x(),status:rm.nullable().optional()}).strict(),apple:r({present:x(),active:x(),status:n().nullable(),product_id:n().nullable()}).strict()}).strict(),om=r({account_id:n().min(1).optional(),email:n().nullable().optional(),pro:x(),pro_expires_at:n().nullable(),push_suggestions_enabled:x(),library_discovery_dismissed:x(),first_story_completed_at:n().datetime().nullable().default(null),post_first_story_onboarding:Lr.default({version:1,status:"not_started",step:1}),created_at:n().nullable(),library_count:u().int().min(0),billing:im.optional(),cap:r({limit:u().int().min(0),remaining:u().int().min(0).nullable(),over:x()}).strict()}).strict(),sm=f(["state_viewed","action_clicked","step_selected"]),cm=f(["setup","library_empty"]),lm=f(["full","compact"]),dm=f(["checking","choose_supported_path","install_extension","connect_trace","open_archive","save_story","recover_auth","recover_permission","recover_unsupported","recover_parser","recover_network","confirm_library","empty_again","complete"]),um=f(["install","connect","save"]),mm=f(["install","refresh_page","check_again","connect_account","open_ao3","open_ffn","submit_story_url","first_story_url_success","first_story_url_failure","open_archive_self","manual_add","open_library","open_setup","manage_safari_settings"]),Zi=f(["chrome","firefox","desktop-other","ios-app","ios-safari","ios-other","android-firefox","android-other"]),pm=f(["checking","not_detected","detected"]),hm=f(["connected","signed_out","reconnect_required","error","unknown"]),fm=f(["chrome","firefox","safari","unknown"]),_m=f(["ao3","ffn","unknown"]),gm=f(["track","quick_add","import","metadata","unknown"]),bm=f(["permission","unsupported_page","auth","parser","network","unknown"]),ym=f(["unknown","empty","has_entries"]),vm=f(["extension_command","legacy_open_url","ios_safari_handoff"]),Sm=f(["submitted","opened","tracked","failed","invalid_url"]),xm=f(["oauth_callback_completed","authenticated_session"]),Es=f(["debug","app_store","unknown"]),Em=f(["ios_settings_checkpoint_v1","ios_settings_checkpoint_v2","ios_story_first_safari_v2"]),wm=f(["extension_enabled_verified","extension_enablement_acknowledged","permission_checkpoint_viewed","permission_instructions_confirmed","archive_verification_started","archive_heartbeat_verified","permission_recovery_viewed","first_extension_save_verified"]),Am=f(["checking","ready","unavailable"]),Rm=f(["native_unavailable","native_timeout","state_unavailable","other"]),Tm=r({route:n().startsWith("/").max(120),auth_return_outcome:xm,client_release:n().min(1).max(120),native_shell:x(),native_app_version:n().min(1).max(32).optional(),native_app_build:n().min(1).max(32).optional(),native_release_channel:Es.optional(),recorded_at:n().datetime().optional()}).strict(),km=r({action:sm,surface:cm,state_id:dm.optional(),variant:lm.optional(),target:mm.optional(),step_id:um.optional(),path_id:Zi.optional(),recommended_path_id:Zi.optional(),path_supp
2ort:f(["extension","fallback"]).optional(),extension_phase:pm.optional(),extension_connected:x().optional(),extension_auth_state:hm.optional(),extension_browser_kind:fm.optional(),archive_host_kind:_m.optional(),archive_action_kind:gm.optional(),archive_error_kind:bm.optional(),first_save_seen:x().optional(),extension_first_story_add_supported:x().optional(),first_story_entry_mode:vm.optional(),first_story_result:Sm.optional(),recent_archive_activity:x().optional(),library_count_state:ym.optional(),flow_version:Em.optional(),ios_activation_stage:wm.optional(),native_state_phase:Am.optional(),settings_supported:x().optional(),earned_permission_onboarding:x().optional(),native_state_error:Rm.optional(),client_release:n().min(1).max(120).optional(),native_shell:x().optional(),native_app_version:n().min(1).max(32).optional(),native_app_build:n().min(1).max(32).optional(),native_release_channel:Es.optional(),recorded_at:n().datetime().optional()}).strict(),Cm=pe(),Nm=pe(),jr=f(["bug","improvement","confusing","other"]),ws=f(["new","reviewed"]),As=r({route:n().trim().min(1).max(240).regex(/^\/(?!\/)/),client_timestamp:n().datetime(),viewport:r({width:u().int().min(0).max(1e4),height:u().int().min(0).max(1e4)}).strict(),user_agent:n().trim().min(1).max(500),theme:f(["light","dark","system"]),is_ios_shell:x()}).strict(),Im=r({type:jr,message:n().trim().min(5).max(4e3),follow_up_ok:x(),contact_email:n().trim().email().max(320).nullable().optional(),context:As}).strict().superRefine((e,t)=>{e.follow_up_ok&&!e.contact_email&&t.addIssue({code:"custom",path:["contact_email"],message:"Email is required when follow-up is requested."})}),Om=r({data:r({id:n().uuid(),created_at:n()})});r({type:jr.optional(),status:ws.optional(),limit:H().int().min(1).max(100).default(50),offset:H().int().min(0).default(0)}).strict();const S=u().int().min(0),ve=u().int().positive(),oe=u().min(0),An=1,Zt=2,Pm=q(e=>{if(typeof e!="string")return e;const t=e.trim();return t===String(An)?An:t===String(Zt)?Zt:e},V([_(An),_(Zt)]).default(An));r({contractVersion:Pm}).strict();const Pe=r({day:n(),count:S}).strict(),Lm=r({id:f(["authenticated_boot","activation_ui","setup_page","extension_detected","extension_connected","archive_activity","first_story"]),label:n(),users7d:S,users30d:S,rateFromView7d:oe,dropoffFromPrevious7d:oe.nullable()}).strict(),Dm=r({stateId:n(),label:n(),events7d:S,users7d:S,users30d:S,latestUsers30d:S}).strict(),jm=r({target:n(),label:n(),events7d:S,users7d:S}).strict(),Je=r({key:n(),label:n(),events7d:S,users7d:S,users30d:S}).strict(),Rs=r({pendingFandomAliases:S,pendingCharacterAliases:S,newFeedback:S,extensionPayloadSanitized24h:S,extensionPayloadSanitized7d:S,extensionPayloadRejected24h:S,extensionPayloadRejected7d:S,extensionPayloadSanitizedRate24h:oe,extensionPayloadSanitizedRate7d:oe,extensionPayloadRejectedRate24h:oe,extensionPayloadRejectedRate7d:oe,rateLimitBlocks24h:S,rateLimitBlocks7d:S,extensionTrackErrors24h:S,extensionTrackErrors7d:S,extensionTrackRateLimitBlocks24h:S,extensionTrackRateLimitBlocks7d:S}).strict(),Um=r({extensionFinalChapterTracks24h:S.default(0),extensionFinalChapterTracks7d:S.default(0),extensionFinishRequests24h:S.default(0),extensionFinishRequests7d:S.default(0),extensionFinishResolved24h:S.default(0),extensionFinishResolved7d:S.default(0),extensionFinishIgnored24h:S.default(0),extensionFinishIgnored7d:S.default(0),extensionFinishErrors24h:S.default(0),extensionFinishErrors7d:S.default(0)}).strict(),Mm=Rs.extend(Um.shape).strict();Rs.strip();const Fm=r({productPulse:r({totalUsers:S,activeUsers24h:S,activeUsers7d:S,activeUsers30d:S,newUsers7d:S,newUsers30d:S}).strict(),activation:r({activatedUsersTotal:S,activatedNewUsers7d:S,activatedNewUsers30d:S,activationRate7d:oe,activationRate30d:oe,medianHoursToFirstStory30d:oe.nullable()}).strict(),usage:r({totalStories:S,totalLibraryEntries:S,storiesAdded24h:S,storiesAdded7d:S,storiesAdded30d:S,usersAddingStories7d:S,usersAddingStories30d:S,extensionTracks24h:S,extensionTracks7d:S,chapterProgressUpdates24h:S,chapterProgressUpdates7d:S,usersTrackingChapters7d:S,usersTrackingChapters30d:S,manualStories7d:S,metadataBroadcasts7d:S,collectionsCreated7d:S,collectionsCreated30d:S,usersCreatingCollections7d:S,usersCreatingCollections30d:S,collectionsEdited7d:S,collectionsEdited30d:S,usersEditingCollections7d:S,usersEditingCollections30d:S,collectionItemsAdded7d:S,collectionItemsAdded30d:S,publicCollectionsTotal:S,publicCollectionsCreated7d:S,publicCollectionsCreated30d:S,usersCreatingPublicCollections7d:S,usersCreatingPublicCollections30d:S}
2).strict(),revenue:r({proUsers:S,estimatedPayingUsers:S,proUsersWithoutBillingInfo:S,proConversionRate:oe,grossMrrEstimate:oe,netMrrEstimate:oe,grossArrEstimate:oe,netArrEstimate:oe,stripeMonthlyUsers:S,stripeYearlyUsers:S,appleMonthlyUsers:S,appleYearlyUsers:S}).strict(),ops:Mm,ao3SavedFilters:r({activePresets:S,globalPresets:S,contextPresets:S,deletedTombstones:S,usersWithPresets:S,usersNearLimit:S,usersAtLimit:S,activeCreated24h:S,activeCreated7d:S,deleted24h:S,deleted7d:S,syncs24h:S,syncs7d:S,syncUsers7d:S,syncUpserts7d:S,syncDeletes7d:S,limitHits24h:S,limitHits7d:S}).strict(),onboarding:r({events24h:S,events7d:S,users7d:S,users30d:S,bootUsers7d:S,bootUsers30d:S,nativeBootUsers7d:S,signupNoBootUsers7d:S,signupNoBootUsers30d:S,setupUsers7d:S,libraryEmptyUsers7d:S,extensionDetectedUsers7d:S,extensionConnectedUsers7d:S,extensionFirstStoryAddSupportedUsers7d:S,connectedLegacyExtensionUsers7d:S,archiveActivityUsers7d:S,archiveErrorUsers7d:S,manualIntentUsers7d:S,firstStoryUrlSubmitUsers7d:S,firstStoryUrlOpenedUsers7d:S,firstStoryUrlTrackedUsers7d:S,firstStoryUrlFailureUsers7d:S,firstStoryUsers7d:S,funnel:p(Lm),states:p(Dm),actions:p(jm),surfaces:p(Je),setupPaths:p(Je),recommendedPaths:p(Je),browsers:p(Je),authStates:p(Je),archiveErrors:p(Je),firstStoryEntryModes:p(Je),firstStoryResults:p(Je)}).strict(),trends:r({signups30d:p(Pe),activeUsers30d:p(Pe),activatedUsers30d:p(Pe),libraryAdds30d:p(Pe),extensionTracks30d:p(Pe),chapterProgress30d:p(Pe),collectionActions30d:p(Pe),ao3SavedFilterSyncs30d:p(Pe),ao3SavedFilterUpserts30d:p(Pe),ao3SavedFilterDeletes30d:p(Pe)}).strict()}).strict(),Bm=r({contractVersion:_(Zt).optional(),data:Fm}).strict(),Ts=r({id:n().uuid(),user_id:n().nullable(),contact_email:n().nullable(),type:jr,message:n(),follow_up_ok:x(),context:As,status:ws,created_at:n(),reviewed_at:n().nullable(),reviewed_by:n().nullable()}).strict(),Hm=r({data:p(Ts),total:S}).strict(),Vm=r({data:Ts}).strict(),Ur=f(["open","reviewing","dismissed","actioned"]),Mr=f(["spam","harassment","sexual_or_violent","illegal_or_unsafe","privacy_or_impersonation","copyright","unsafe_link","other"]),Wm=f(["active","unpublished"]),ks=f(["approved","pending","blocked","ignored"]),Cs=f(["collection","report","user","domain"]),$m=r({status:Ur.optional(),reason:Mr.optional(),limit:H().int().min(1).max(100).default(50),offset:H().int().min(0).default(0)}).strict(),Fr=r({report_id:n().uuid(),collection_id:n().uuid().nullable(),share_slug:n(),owner_user_id:n().nullable(),reporter_user_id:n().nullable(),public_item_ref:n().nullable(),reason:Mr,message:n(),contact_email:n().nullable(),status:Ur,collection_title:n().nullable(),collection_public_status:Wm.nullable(),owner_public_collection_count:S,created_at:n(),updated_at:n(),reviewed_at:n().nullable(),reviewed_by:n().nullable(),resolution_note:n().nullable()}).strict(),Ym=r({data:p(Fr),total:S}).strict(),Gm=r({data:Fr.extend({snapshot:ot(n(),it())})}).strict(),zm=r({data:Fr}).strict(),qm=r({status:Ur,resolution_note:n().trim().min(1).max(5e3)}).strict(),eo=r({reason_code:Mr.optional(),reason:n().trim().min(1).max(5e3)}).strict(),to=r({reason:n().trim().min(1).max(5e3)}).strict(),Km=r({status:ks.optional(),limit:H().int().min(1).max(100).default(50),offset:H().int().min(0).default(0)}).strict(),Qm=r({domain_id:n().uuid(),normalized_host:n(),status:ks,allow_subdomains:x(),source:f(["seed","detected","operator"]),affected_collection_count:S,affected_user_count:S,sample_urls:p(n()).max(5),created_at:n(),updated_at:n(),reviewed_at:n().nullable(),reviewed_by:n().nullable(),review_note:n().nullable()}).strict(),Jm=r({data:p(Qm),total:S}).strict(),Oa=r({allow_subdomains:x().optional(),note:n().trim().max(5e3).optional().default("")}).strict(),Xm=r({event_id:n().uuid(),actor_user_id:n().nullable(),actor_kind:f(["operator","system"]),action:n(),target_type:Cs,target_id:n(),collection_id:n().uuid().nullable(),share_slug:n().nullable(),owner_user_id:n().nullable(),report_id:n().uuid().nullable(),domain_id:n().uuid().nullable(),metadata:ot(n(),it()),reason_category:n().nullable(),internal_note:n().nullable(),created_at:n()}).strict(),Zm=r({target_type:Cs.optional(),target_id:n().trim().min(1).max(200).optional(),limit:H().int().min(1).max(100).default(50),offset:H().int().min(0).default(0)}).strict(),ep=r({data:p(Xm),total:S}).strict(),ln=f(["fandom","character"]),Br=r({id:ve,name:n(),fandom_name:n().nullable().optional(),canonical_fandom_id:ve.nullable().optional(),score:oe,match_type:n(),match_reason:n(),matched_alias:n().nullable().optional()}).strict(),tp=f(["auto_resolve","auto_create","review"]),np=f(["exact_match","likely_new","possible_equivalent","blocked"]),Ns=r({action:tp,status:np,reason:n(),canonical_id:ve.nullable()}).strict(),Is=r({source:n(),story_count:S,library_count:S}).strict(),ap=r({id:ve,alias:n(),created_at:n(),source_name:n().nullable(),source_host:n().nullable(),story_count:S,library_count:S,sample_titles:p(n()),source_breakdown:p(Is),candidates:p(Br),automation:Ns}
2).strict(),rp=r({id:ve,alias:n(),created_at:n(),source_name:n().nullable(),fandom_name:n().nullable(),canonical_fandom_id:ve.nullable(),source_host:n().nullable(),scope_source:f(["stored","inferred","none"]),story_count:S,library_count:S,sample_titles:p(n()),source_breakdown:p(Is),candidates:p(Br),automation:Ns}).strict(),ip=r({fandoms:p(ap),characters:p(rp)}).strict(),op=r({data:ip}).strict(),sp=r({type:ln,pendingId:ve,alias:n(),message:n()}).strict(),cp=r({processed:S,autoResolved:S,autoCreated:S,leftForReview:S,stoppedReason:f(["limit","time_budget"]).nullable(),errors:p(sp)}).strict(),lp=r({data:cp}).strict(),dp=r({data:p(Br)}).strict(),He=r({ok:_(!0)}).strict(),up=r({data:r({canonicalId:ve}).strict()}).strict(),mp=r({limit:u().int().min(1).max(500).optional(),maxMs:u().int().min(1e3).max(25e3).optional()}).strict(),pp=r({type:ln,q:n().trim().min(1).max(200),limit:H().int().min(1).max(20).optional(),fandomName:n().trim().max(255).optional()}).strict(),hp=r({type:ln,pendingId:ve,canonicalId:ve}).strict(),fp=r({type:ln,pendingId:ve}).strict(),_p=r({type:ln,pendingId:ve,name:n().trim().min(1).max(255)}).strict(),ft=r({data:p(n())}).strict(),gp=r({value:n(),fandomId:u().int().positive(),canonicalFandomId:u().int().positive().nullable(),canonicalName:n().nullable(),matchedAlias:n().nullable().optional(),publicContextCount:u().int().min(0)}).strict(),bp=r({data:p(gp)}).strict(),yp=f(["seen_with","personal","legacy","global"]),vp=r({value:n(),characterId:u().int().positive(),canonicalCharacterId:u().int().positive().nullable(),context:r({fandomId:u().int().positive(),fandomName:n(),canonicalFandomId:u().int().positive().nullable(),sourceCount:u().int().min(0),publicSourceCount:u().int().min(0),authorityScore:u(),manualCount:u().int().min(0),importCount:u().int().min(0),evidenceLabel:yp}).strict()}).strict(),Sp=r({data:p(vp)}).strict(),xp=r({name:n(),canonical:x().optional()}).strict(),no=r({data:p(xp)}).strict(),Ep=r({data:r({canonical_fandom_id:u().int().positive().nullable()}).strict()}).strict(),Rn=r({name:n(),count:u().int().min(0)}).strict(),wp=r({source:n(),count:u().int().min(0)}).strict(),Pa=r({day:n(),count:u().int().min(0)}).strict(),ao=r({name:n(),avgRating:u().min(0).max(5),ratedCount:u().int().min(0)}).strict(),Ap=r({story_id:u().int().positive(),title:n(),re_read_count:u().int().min(0)}).strict(),Rp=r({SAVED:u().int().min(0),READING:u().int().min(0),CAUGHT_UP:u().int().min(0),PAUSED:u().int().min(0),FINISHED:u().int().min(0),DROPPED:u().int().min(0)}).strict(),Tp=r({schemaVersion:u().int().min(1),range:r({from:n(),to:n(),tz:n()}).strict(),kpis:r({completedReads:u().int().min(0),undatedCompletedReads:u().int().min(0),activeDays:u().int().min(0),longestStreakDays:u().int().min(0),currentStreakDays:u().int().min(0)}).strict(),funnel:Rp,wordProfile:r({short:u().int().min(0),medium:u().int().min(0),long:u().int().min(0)}).strict(),fandomProfile:p(Rn),shipProfile:p(Rn),characterProfile:p(Rn),tropeTrends:p(Rn),crossoverInsights:r({storiesTotal:u().int().min(0),crossoversTotal:u().int().min(0),multiFandomRate:u().min(0)}).strict(),sourceBreakdown:p(wp),averageRating:u().min(0).max(5).nullable(),topRatedRelationships:p(ao),topRatedTags:p(ao),mostRereadStories:p(Ap),wordsFinishedInRange:u().int().min(0),activityByDay:p(Pa),chaptersReadByDay:p(Pa),completionsByDay:p(Pa),completionRule:n()}).strict(),kp=r({data:Tp}).strict(),La=n().regex(/^\d{4}-\d{2}-\d{2}$/,"Expected an ISO calendar date"),Cp=r({requestedFrom:La.nullable(),from:La,to:La,tz:n().min(1),grain:f(["day","month","year"]),daysInclusive:u().int().positive(),monthsInclusive:u().int().positive(),allTime:x()}).strict(),Np=r({key:f(["under_10k","10k_50k","over_50k","unknown"]),label:n(),count:u().int().min(0)}).strict(),Ip=r({schemaVersion:_(1),range:Cp,completedReads:u().int().min(0),wordsRepresented:u().int().min(0),recordedChapterDays:u().int().min(0),lengthBuckets:p(Np).length(4),completionRule:n()}).strict();r({data:Ip}).strict();const ia=f(["unknown","extension_cap","library_cap","api_limit","header","mobile_menu","settings","stats","import"]),Op=f(["web","apple"]),Pp=f(["upgrade_modal_opened","upgrade_modal_dismissed","plan_selected","popup_blocked","checkout_cancelled","checkout_returned_success","entitlement_c
2onfirmed","entitlement_not_confirmed","apple_purchase_started","apple_restore_started","apple_purchase_cancelled","apple_purchase_failed"]),Lp=r({plan:f(["month","year"]).optional(),source:ia.optional()}).strict(),Dp=r({event:Pp,source:ia.optional(),plan:f(["month","year"]).optional(),platform:Op.optional()}).strict();r({event:f(["prompt_viewed","prompt_dismissed"]),surface:f(["story","listing"])}).strict();const jp=r({accepted:_(!0)}).strict(),ir=r({url:n().url()}).strict(),Up=ir,Mp=r({pro:x()}).strict(),Fp=r({pro:x(),pro_expires_at:n().nullable()}).strict(),oa=f(["general","teen","mature","explicit","not_rated"]);oa.options;const Bp={general:"General",teen:"Teen",mature:"Mature",explicit:"Explicit",not_rated:"Not rated"};function Hp(e){return e.trim().toLowerCase().replace(/[()[\]]/g," ").replace(/\s+/g," ").replace(/^(rated|rating):?\s*/,"").replace(/^fiction( rated)?:?\s*/,"").trim()}function Os(e){if(e==null)return null;const t=String(e).trim();if(!t)return null;const a=Hp(t),c=a.replace(/\s+/g,"");return a==="g"||a==="general"||a==="general audiences"||a==="k"||a==="k+"||a==="kids"?"general":a==="t"||a==="teen"||a==="teen and up"||a==="teen and up audiences"?"teen":a==="m"||a==="mature"?"mature":a==="e"||a==="explicit"?"explicit":a==="nr"||a==="none"||a==="no rating"||c==="notrated"||c==="unrated"?"not_rated":null}function Ps(e){const t=new Set;for(const a of e??[]){const c=Os(a);c&&t.add(c)}return[...t]}function Nw(e){const t=Os(e);return t?Bp[t]:e}const Ut=f(["BEST_MATCH","LAST_READ_DESC","UPDATED_DESC","WORK_UPDATED_DESC","TITLE_ASC","TITLE_DESC","RATING_ASC","RATING_DESC","STORY_UPDATE_DESC"]),zn=Ut,Vp=["SAVED","READING","CAUGHT_UP","PAUSED","FINISHED","DROPPED"],Wp=["PLANNING","READING","PAUSED","COMPLETED","DROPPED"],Se=f(Vp),Ls=f(Wp),$p={PLANNING:"SAVED",READING:"READING",PAUSED:"PAUSED",COMPLETED:"FINISHED",DROPPED:"DROPPED"};function Hr(e){if(typeof e!="string"&&typeof e!="number"&&typeof e!="boolean")return;const t=String(e).trim().toUpperCase();if(t){if(Se.safeParse(t).success)return t;if(Ls.safeParse(t).success)return $p[t]}}function Yp(e){return Array.from(new Set(e.map(t=>Hr(t)).filter(t=>!!t)))}const sa=q(e=>{if(!(e===void 0||e===""))return Hr(e)??e},Se.optional()),Ds=q(e=>{if(e===void 0||e==="")return;const a=(Array.isArray(e)?e:typeof e=="string"?e.split(","):[e]).map(c=>Hr(c)??c);return a.length?a:void 0},p(Se).max(10).optional()),Gp=q(e=>Array.isArray(e)?Ps(e):e,p(oa).max(5).optional()),Vr=r({ratings:Gp,platforms:p(n().trim().min(1).max(255)).max(10).optional(),minWords:u().int().min(0).max(5e7).optional(),maxWords:u().int().min(0).max(5e7).optional(),minKudos:u().int().min(0).max(1e7).optional(),maxKudos:u().int().min(0).max(1e7).optional(),hasNotes:x().optional(),notes:f(["ANY","WITH","WITHOUT"]).optional(),tag:n().trim().min(1).max(255).optional(),workTag:n().trim().min(1).max(255).optional(),statuses:Ds,pairMembers:p(n().trim().min(1).max(255)).max(10).optional(),pairExact:x().optional(),characters:p(n().trim().min(1).max(255)).max(60).optional(),relationships:p(n().trim().min(1).max(255)).max(80).optional(),fandoms:p(n().trim().min(1).max(255)).max(60).optional(),completionStatus:p(n().trim().min(1).max(50)).max(10).optional(),excludeWarnings:p(n().trim().min(1).max(255)).max(20).optional(),includeWarnings:p(n().trim().min(1).max(255)).max(20).optional(),categoryFilter:p(n().trim().min(1).max(50)).max(10).optional(),excludeTag:n().trim().min(1).max(255).optional(),excludeWorkTag:n().trim().min(1).max(255).optional(),excludePairMembers:p(n().trim().min(1).max(255)).max(10).optional(),excludePairExact:x().optional(),excludeCharacters:p(n().trim().min(1).max(255)).max(60).optional(),excludeFandoms:p(n().trim().min(1).max(255)).max(60).optional(),excludeCategoryFilter:p(n().trim().min(1).max(50)).max(10).optional(),lastReadAfter:n().trim().min(1).max(255).optional(),lastReadBefore:n().trim().min(1).max(255).optional(),minEntryRating:u().int().min(1).max(5).optional(),entryRating:f(["ANY","UNRATED"]).optional(),catchup:f(["ANY","UP","BEHIND"]).optional(),storyUpdates:f(["ANY","NEW"]).optional()}),zp=Vr.strict(),Ue=r({search:n().trim().max(200),sort:Ut,filters:zp}
2).strict(),re=(e,t,a)=>{(a??[]).forEach(c=>{c&&e.append(t,c)})},Xe=(e,t,a)=>{const c=a?.trim();c&&e.set(t,c)},qp=new Set(["true","1","yes","on"]),Kp=new Set(["false","0","no","off"]),Qp={ao3:"archiveofourown.org","archive of our own":"archiveofourown.org",archiveofourown:"archiveofourown.org",ffn:"fanfiction.net",fanfiction:"fanfiction.net","fanfiction net":"fanfiction.net",fictionpress:"fictionpress.com","fiction press":"fictionpress.com","adult fanfiction":"adult-fanfiction.org","adult-fanfiction":"adult-fanfiction.org",aff:"adult-fanfiction.org","sink into your eyes":"siye.co.uk",siye:"siye.co.uk",hpfanficarchive:"hpfanficarchive.com","hp fanfic archive":"hpfanficarchive.com"},ro=(e,t,a)=>Math.min(Math.max(e,t),a),Jp=e=>Array.isArray(e)?e[0]:e,ze=e=>{const t=Jp(e);if(!(typeof t!="string"&&typeof t!="number"&&typeof t!="boolean"))return String(t)},jn=e=>{const t=ze(e)?.trim().toLowerCase();if(t){if(qp.has(t))return!0;if(Kp.has(t))return!1}},qn=e=>{const t=ze(e)?.trim();if(!t)return;const a=parseInt(t,10);return Number.isFinite(a)?a:void 0},Xp=e=>{const t=Array.isArray(e)?e:typeof e=="string"?e.split(","):[];return Array.from(new Set(t.map(a=>String(a).trim()).filter(Boolean)))},ie=(...e)=>{for(const t of e){if(t===void 0||t==="")continue;const a=Xp(t);if(a.length)return a}return[]},Ze=(...e)=>{for(const t of e){const a=ze(t)?.trim();if(a)return a}},Zp=e=>{let t=String(e||"").trim().toLowerCase();if(!t)return t;try{t=new URL(t.includes("://")?t:`https://${t}`).hostname}catch{}return t.replace(/^(www\.|m\.)/,"")},js=e=>{const t=String(e||"").trim();if(!t)return"";const a=t.toLowerCase();return Qp[a]??Zp(t)};function eh(e){const t=new URLSearchParams,{search:a,sort:c,page:m,limit:h,cursor:d,pagination:v,filters:o}=e;Xe(t,"search",a),c&&t.set("sort",c),t.set("page",String(m)),t.set("limit",String(h)),(v==="cursor"||d)&&t.set("pagination","cursor"),Xe(t,"cursor",d),re(t,"status[]",o.statuses),re(t,"rating[]",o.ratings),re(t,"platforms[]",o.platforms),typeof o.minWords=="number"&&t.set("min_words",String(o.minWords)),typeof o.maxWords=="number"&&t.set("max_words",String(o.maxWords)),typeof o.minKudos=="number"&&t.set("min_kudos",String(o.minKudos)),typeof o.maxKudos=="number"&&t.set("max_kudos",String(o.maxKudos)),typeof o.minEntryRating=="number"&&o.minEntryRating>=1&&t.set("min_entry_rating",String(o.minEntryRating)),o.entryRating==="UNRATED"&&t.set("entry_rating","unrated");const s=o.notes??(o.hasNotes?"WITH":"ANY");s&&s!=="ANY"&&t.set("notes",s),Xe(t,"tag",o.tag),Xe(t,"work_tag",o.workTag),re(t,"pair_member[]",o.pairMembers),o.pairExact&&o.pairMembers?.length&&t.set("pair_exact","true"),re(t,"character[]",o.characters),re(t,"relationship[]",o.relationships),re(t,"fandom[]",o.fandoms),re(t,"completion_status[]",o.completionStatus),re(t,"exclude_warning[]",o.excludeWarnings),re(t,"include_warning[]",o.includeWarnings),re(t,"category[]",o.categoryFilter),Xe(t,"exclude_tag",o.excludeTag),Xe(t,"exclude_work_tag",o.excludeWorkTag),re(t,"exclude_pair_member[]",o.excludePairMembers),o.excludePairExact&&o.excludePairMembers?.length&&t.set("exclude_pair_exact","true"),re(t,"exclude_character[]",o.excludeCharacters),re(t,"exclude_fandom[]",o.excludeFandoms),re(t,"exclude_category[]",o.excludeCategoryFilter),Xe(t,"last_read_after",o.lastReadAfter),Xe(t,"last_read_before",o.lastReadBefore),o.catchup&&o.catchup!=="ANY"&&t.set("catchup",o.catchup),o.storyUpdates==="NEW"&&t.set("story_updates","NEW");const l=t.toString();return l?`?${l}`:""}const th=e=>Array.from(new Set(e.map(js).filter(Boolean))),nh=e=>{const t=ze(e);return zn.safeParse(t).success?t:void 0},ah=e=>{const t=ze(e)?.trim().toLowerCase();if(t==="cursor")return"cursor";if(t==="page")return"page"},rh=e=>{const t=ze(e)?.trim().toUpperCase();if(t==="UP"||t==="BEHIND"||t==="ANY")return t},ih=e=>{const t=ze(e)?.trim().toUpperCase();if(t==="NEW"||t==="ANY")return t},oh=(...e)=>{for(const t of e){const a=ze(t)?.trim().toUpperCase();if(a==="UNRATED"||a==="NO_RATING"||a==="NONE")return"UNRATED";if(a==="ANY")return"ANY"}},sh=e=>{const t=ze(e)?.trim().toUpperCase();if(t==="WITH"||t==="WITHOUT"||t==="ANY")return t},ch=(...e)=>{for(const t of e){const a=qn(t);if(a!==void 0)return a>=1&&a<=5?a:void 0}},Tn=(e,t,...a)=>{for(const c of a){const m=qn(c);if(m!==void 0)return m>=e&&m<=t?m:void 0}};function Wr(e){const t=Ps(ie(e.ratings,e.rating,e["rating[]"])),a=th(ie(e.platforms,e["platforms[]"])),c=Yp(ie(e.statuses,e.status,e["status[]"])),m=ie(e.pairMembers,e.pair_member,e["pair_member[]"]),h=ie(e.characters,e.character,e["character[]"]),d=ie(e.relationshipNames,e.relationship,e["relationship[]"]),v=ie(e.fandoms,e.fandom,e["fandom[]"]),o=ie(e.completion_status,e["completion_status[]"]),s=ie(e.exclude_warning,e["exclude_warning[]"]),l=ie(e.include_warning,e["include_warning[]"]),b=ie(e.category,e["category[]"]),g=ie(e.exclude_pair_member,e["exclude_pair_member[]"]),E=ie(e.exclude_character,e["exclude_character[]"]),w=ie(e.exclude_fandom,e["exclude_fandom[]"]),T=ie(e.exclude_category,e["exclude_category[]"]),D=ro(qn(e.page)??1,1,1e6),R=ro(qn(e.limit)??50,1,100),k=Ze(e.cursor),W=ah(e.pagination)??(k?"cursor":"page"),X=jn(e.pairExact??e.pair_exact),Z=jn(e.excludePairExact??e.exclude_pair_exact),K=sh(e.notes??e.notes_filter),ce=jn(e.hasNotes??e.has_notes),qe=ih(e.storyUpdates??e.story_updates);return{search:Ze(e.search)??"",sort:nh(e.sort)??"LAST_READ_DESC",page:D,limit:R,...W==="cursor"?{cursor:k,pagination:W}:{},filters:{ratings:t.length?t:void 0,platforms:a.length?a:void 0,statuses:c.length?c:void 0,minWords:Tn(0,5e7,e.minWords,e.min_words),maxWords:Tn(0,5e7,e.maxWords,e.max_words),minKudos:Tn(0,
21e7,e.minKudos,e.min_kudos),maxKudos:Tn(0,1e7,e.maxKudos,e.max_kudos),hasNotes:ce||void 0,notes:K!==void 0?K==="ANY"?void 0:K:ce?"WITH":void 0,tag:Ze(e.tag),workTag:Ze(e.workTag,e.work_tag),pairMembers:m.length?m:void 0,pairExact:m.length?X??!1:void 0,characters:h.length?h:void 0,relationships:d.length?d:void 0,fandoms:v.length?v:void 0,completionStatus:o.length?o:void 0,excludeWarnings:s.length?s:void 0,includeWarnings:l.length?l:void 0,categoryFilter:b.length?b:void 0,excludeTag:Ze(e.exclude_tag),excludeWorkTag:Ze(e.exclude_work_tag),excludePairMembers:g.length?g:void 0,excludePairExact:g.length?Z??!1:void 0,excludeCharacters:E.length?E:void 0,excludeFandoms:w.length?w:void 0,excludeCategoryFilter:T.length?T:void 0,lastReadAfter:Ze(e.lastReadAfter,e.last_read_after),lastReadBefore:Ze(e.lastReadBefore,e.last_read_before),minEntryRating:ch(e.min_entry_rating,e.minEntryRating),entryRating:oh(e.entry_rating,e.entryRating),catchup:rh(e.catchup),...qe?{storyUpdates:qe}:{}}}}function lh(e){return Wr(e)}r({search:n(),sort:Ut,page:u().int().min(1),limit:u().int().min(1).max(100),cursor:n().min(1).max(2048).optional(),pagination:f(["page","cursor"]).optional(),filters:Vr});const Us=r({search:n(),sort:zn,page:u().int().min(1),limit:u().int().min(1).max(100),cursor:n().min(1).max(2048).optional(),pagination:f(["page","cursor"]).optional(),filters:Vr}),Mt=f(["complete","wip","hiatus","abandoned","unknown"]),dh=f(["complete","wip","hiatus","unknown"]),uh=f(["wip","complete","hiatus","abandoned"]),Ft=f(["override","source","unknown"]),dn=f(["UP","BEHIND","UNKNOWN"]);r({work_status:Mt,work_status_provenance:Ft,catchup_state:dn,new_chapter_count:u().int().min(0)});function io(e,t){if(e==null)return{present:!1,status:null};if(typeof e!="string")return{present:!0,status:"unknown"};const a=e.trim().toLowerCase().replace(/[\s-]+/g,"_");return a?a==="complete"||a==="wip"||a==="hiatus"||a==="on_hiatus"||t.allowAbandoned&&a==="abandoned"?{present:!0,status:a==="on_hiatus"?"hiatus":a}:{present:!0,status:"unknown"}:{present:!1,status:null}}function mh(e){const t=io(e.workStatusOverride,{allowAbandoned:!0});if(t.present)return{work_status:t.status,work_status_provenance:t.status==="unknown"?"unknown":"override"};const a=io(e.completionStatus,{allowAbandoned:!1});if(a.present&&a.status==="complete")return{work_status:"complete",work_status_provenance:"source"};if(a.present&&a.status==="hiatus")return{work_status:"hiatus",work_status_provenance:"source"};if(a.present&&a.status==="wip")return{work_status:"wip",work_status_provenance:"source"};if(a.present&&a.status==="unknown")return{work_status:"unknown",work_status_provenance:"unknown"};const c=Kn(e.chaptersPublished),m=Kn(e.chaptersPlanned);return c!=null&&m!=null&&m>c?{work_status:"wip",work_status_provenance:"source"}:{work_status:"unknown",work_status_provenance:"unknown"}}function Kn(e){return typeof e!="number"||!Number.isFinite(e)||e<0?null:Math.trunc(e)}function ph(e){if(e.progressUnit!=="CHAPTER")return{catchup_state:"UNKNOWN",new_chapter_count:0};const t=Kn(e.progressValue),a=Kn(e.chaptersPublished);if(t==null||a==null)return{catchup_state:"UNKNOWN",new_chapter_count:0};const c=Math.max(0,a-t);return{catchup_state:c>0?"BEHIND":"UP",new_chapter_count:c}}function Iw(e){return{...mh(e),...ph(e)}}const dt="trace-watches.v1",ca="trace-story-updates.v1",$r=f(["new_chapter","new_work","backdated_work"]),hh=f(["work","creator","series","unknown"]),Ms=r({configured:x(),route_created_at:n().datetime().nullable(),last_delivery_at:n().datetime().nullable(),candidate_count:u().int().min(0),gmail:r({available:x(),connected:x(),connected_at:n().datetime().nullable(),last_synced_at:n().datetime().nullable(),sync_state:f(["idle","error"])}).strict()}).strict(),fh=r({contract_version:_(dt),setup:Ms}).strict(),oo=r({contract_version:_(dt),setup:Ms,address:n().email().nullable(),address_is_new:x()}).strict();r({sessionId:n().uuid()}).strict();r({address:n().min(1).max(512)}).strict();r({sessionId:n().uuid()}).strict();const _h=f(["recipient_validation","route_resolution","mime_validation","forwarding_verification","ingress"]),gh=f(["processing_unavailable","invali
2d_recipient","route_rejected","mime_rejected","forwarding_verification_handled","accepted","duplicate_delivery","ignored","review_required"]),bh=V([r({session_id:n().uuid(),status:_("pending"),expires_at:n().datetime()}).strict(),r({session_id:n().uuid(),status:_("observed"),expires_at:n().datetime(),comparison:f(["exact_match","case_only_difference","uncorrelated_or_malformed_activity"]),processing_stage:_h,processing_outcome:gh}).strict()]),so=r({contract_version:_(dt),recipient_diagnostic:bh}).strict();function yh(e){let t;try{t=new URL(e)}catch{return!1}const a=t.hostname.toLowerCase();return t.protocol==="https:"&&(a==="mail.google.com"||a==="mail-settings.google.com")&&t.port===""&&t.username===""&&t.password===""&&t.search===""&&t.hash===""&&/^\/mail\/vf-%5B[A-Za-z0-9_-]{16,512}%5D-[A-Za-z0-9_-]{16,512}$/i.test(t.pathname)}const vh=n().url().max(2048).refine(yh,"Invalid Gmail forwarding verification URL"),Sh=r({session_id:n().uuid(),status:_("pending"),expires_at:n().datetime()}).strict(),co={session_id:n().uuid(),status:_("received"),expires_at:n().datetime()},xh=r({redaction_version:_("gmail-forwarding-diagnostic.v1"),provider:_("gmail_forwarding"),subject_shape:n().max(1024),text_shape:n().max(12*1024).nullable(),html_shape:n().max(24*1024).nullable()}).strict(),Eh=V([Sh,r({...co,confirmation_code:n().regex(/^\d{6,12}$/)}).strict(),r({...co,confirmation_url:vh}).strict(),r({session_id:n().uuid(),status:_("diagnostic"),expires_at:n().datetime(),diagnostic:xh}).strict()]),Da=r({contract_version:_(dt),verification:Eh}).strict(),wh=r({candidate_id:n().uuid(),kind:$r,work_id:n().min(1),work_url:n().url(),work_title:n().min(1),chapter_id:n().nullable(),chapter_url:n().url().nullable(),chapter_number:u().int().positive().nullable(),chapter_title:n().nullable(),subscription_kind:hh,received_at:n().datetime(),expires_at:n().datetime(),source_state:_("unconfirmed"),eligible_for_mutation:_(!1)}).strict(),Ah=r({limit:H().int().min(1).max(100).default(30),cursor:n().trim().min(1).max(1024).optional()}).strict(),Rh=r({contract_version:_(dt),candidates:p(wh),next_cursor:n().nullable()}).strict();r({candidateId:n().uuid()}).strict();const Nt=r({contract_version:_(dt),ok:_(!0)}).strict(),la=n().regex(/^\d+$/),Yr=r({announcement_sequence:la,kind:$r,announced_at:n().datetime(),open_url:n().url(),chapter_number:u().int().positive().nullable(),chapter_title:n().nullable(),source_state:_("unconfirmed"),is_unseen:x()}).strict(),Th=Yr.extend({group_key:n().min(1).max(160),classification:f(["library","other"]),library_entry_id:n().uuid().nullable(),work_id:n().min(1).max(64),work_title:n().min(1).max(1e3),recent_announcement_count:u().int().min(0)}).strict(),kh=r({limit:H().int().min(1).max(100).default(30),cursor:n().trim().min(1).max(1024).optional()}).strict(),Ch=r({contract_version:_(ca),items:p(Th),counts:r({library_stories:u().int().min(0),other_subscriptions:u().int().min(0),unseen_stories:u().int().min(0)}).strict(),acknowledgement_boundary:la,next_cursor:n().nullable()}).strict(),Nh=r({group_key:n().min(1).max(160),announcement_sequence:la}).strict(),Ih=V([r({items:p(Nh).min(1).max(100)}).strict(),r({all_before:la}).strict()]),Oh=r({contract_version:_(ca),acknowledged:u().int().min(0)}).strict(),Gr=r({notifications_enabled:x(),title_previews_enabled:x()}).strict(),Ph=r({notifications_enabled:x().optional(),title_previews_enabled:x().optional()}).strict().refine(e=>Object.keys(e).length>0,{message:"At least one preference is required"}),lo=r({contract_version:_(ca),preferences:Gr}).strict(),Fs=r({verification_completed:_(!0),ao3_filter_created:_(!0),whole_mailbox_forwarding_disabled:_(!0)}).strict(),Lt=r({contract_version:_(ca),methods:r({forwarding:r({connected:x(),address_state:f(["not_created","available","rotation_required"]),setup_state:f(["not_configured","verification_required","waiting_for_first_ao3","active","needs_attention"]),address_created_at:n().datetime().nullable(),verification_received_at:n().datetime().nullable(),setup_completed_at:n().datetime().nullable(),last_successful_delivery_at:n().datetime().nullable(),attention_reason:f(["verification_authentication_failed","verification_message_unrecognized","ao3_message_requires_review"]).nullable()}).strict(),gmail:r({available:x(),connected:x(),connected_at:n().datetime().nullable(),last_successful_check_at:n().datetime().nullable(),state:f(["not_connected","healthy","error"])}).strict()}).strict(),last_successful_activity_at:n().datetime().nullable(),preferences:Gr}).strict(),Bs="trace-story-updates-onboarding.v1";r({address:n().min(1).max(512)}).strict();const uo=r({contract_version:_(Bs),address:n().email().nullable(),forwarding:Lt.shape.methods.shape.forwarding,setup_verification:r({state:f(["not_received","received"]),first_received_at:n().datetime().nullable()}).strict(),delivery_check:r({code:f(["not_configured","rotation_required","wrong_address","no_mail_yet","received"]),address_matches:x().nullable(),possible_causes:p(f(["wrong_address","provider_filtering"])),provider_filtering:_("not_observable")}
2).strict()}).strict();r({trace:r({path:_("/watches"),destination:r({contract_version:_(Bs),type:_("forwarding_setup_verified"),account_id:n().min(1).max(512),target:r({kind:_("forwarding_setup")}).strict(),first_received_at:n().datetime()}).strict()}).strict()}).strict();const Hs=n().regex(/^\d+$/),Lh=lt("kind",[r({kind:_("library_entry"),entry_id:n().uuid()}).strict(),r({kind:_("inbox"),acknowledgement_boundary:Hs}).strict()]),Dh=r({type:_("story_update"),account_id:n().min(1).max(512),target:Lh,announcement_sequence:Hs.optional(),kind:$r.optional(),chapter_number:u().int().positive().nullable().optional()}).strict().superRefine((e,t)=>{e.target.kind==="library_entry"&&!e.announcement_sequence&&t.addIssue({code:"custom",path:["announcement_sequence"],message:"A Library destination requires an announcement sequence"}),e.target.kind==="inbox"&&e.announcement_sequence!==void 0&&t.addIssue({code:"custom",path:["announcement_sequence"],message:"An inbox destination carries its acknowledgement boundary"})});r({trace:r({path:n().min(1).max(1024),destination:Dh}).strict()}).strict();const jh=r({contract_version:_(dt),authorization_url:n().url().refine(e=>new URL(e).origin==="https://accounts.google.com"),expires_at:n().datetime()}).strict(),Uh=r({contract_version:_(dt),checked:u().int().min(0),accepted:u().int().min(0),duplicates:u().int().min(0)}).strict(),Mh=200,Fh=5e3,Bh=2e4,Re=500,un=2e3,on=50,Hh=120,Vh=f(["empty","selected","tags","filter","public_share"]),da=f(["empty","copy_library_note"]);f(["empty","copy_library_note","custom"]);const Wh=f(["any","all"]),zr=f(["simple","ranked","grouped"]),ua=f(["ember","plum","ochre","graphite"]),Vs=ua.nullish().transform(e=>e??"graphite"),qr=n().min(1),Ne=n().uuid(),G=u().int().min(1),$h=n().trim().min(1).max(Hh);function Ow(e){return zr.safeParse(e).success}f(["COLLECTION_NOT_FOUND","COLLECTION_ITEM_LIMIT_EXCEEDED","COLLECTION_ENTRY_NOT_FOUND","COLLECTION_REORDER_DUPLICATE_ENTRY","COLLECTION_REORDER_MISSING_ENTRY","COLLECTION_REORDER_FOREIGN_ENTRY","COLLECTION_VALIDATION_FAILED","COLLECTION_REVISION_CONFLICT","COLLECTION_OPERATION_ID_REUSED","COLLECTION_OPERATION_CAPACITY_EXCEEDED","COLLECTION_UNDO_CONFLICT","COLLECTION_STRUCTURE_REQUIRES_CAPABLE_CLIENT","COLLECTION_STRUCTURE_WRITES_DISABLED","COLLECTION_COLOUR_WRITES_DISABLED","COLLECTION_GROUP_NOT_FOUND","COLLECTION_GROUP_REQUIRED","COLLECTION_GROUP_LIMIT_EXCEEDED","COLLECTION_GROUP_DELETE_DESTINATION_REQUIRED","COLLECTION_GROUP_SET_MISMATCH","PUBLIC_COLLECTION_ITEM_UNAVAILABLE","PUBLIC_COLLECTION_ITEM_NOT_FOUND","PUBLIC_COLLECTION_NO_ACTIONABLE_ITEMS"]);const ut=n().trim().min(1).max(Mh),mt=n().trim().max(Fh),Ws=n().max(Bh),$s=Ue,Ys=Ue.extend({sort:V([Ut,_("AUTHORED")])});r({request_id:n().uuid(),query:Ys}).strict();r({collectionId:n().uuid()}).strict();r({collectionId:n().uuid(),entryId:n().uuid()}).strict();r({collectionId:n().uuid(),operationId:Ne}).strict();const ma={colour:ua.optional(),structure:zr.optional(),operation_id:Ne.optional()},Yh=r({title:ut,description:mt.optional(),...ma}).strict(),Gh=r({title:ut.optional(),description:mt.optional(),expected_revision:G.optional()}).strict(),zh=r({title:ut.optional(),description:mt.optional(),expected_revision:G.optional(),operation_id:Ne.optional()}).strict().default({}),Gs=r({expected_revision:G.optional(),operation_id:Ne.optional()}).strict().default({}),qh=Gs,Kh=r({title:ut,description:mt.optional(),...ma,entry_ids:p(n().uuid()).min(1).max(un),note_mode:da.optional().default("empty")}).strict(),Qh=r({title:ut,description:mt.optional(),...ma,tags:p(n().trim().min(1).max(255)).min(1).max(200),match:Wh.optional().default("any"),query:$s.optional(),note_mode:da.optional().default("empty")}).strict(),Jh=r({title:ut,description:mt.optional(),...ma,query:$s,note_mode:da.optional().default("empty")}).strict(),Xh=r({entry_ids:p(n().uuid()).min(1).max(un),note_mode:da.optional().default("empty"),group_id:n().uuid().nullable().optional(),expected_revision:G.optional()}).strict(),Zh=r({entry_id:n().uuid(),note_mode:_("custom"),note:Ws,group_id:n().uuid().nullable().optional(),expected_revision:G.optional()}).strict(),ef=V([Xh,Zh]),tf=r({note:Ws,expected_revision:G.optional()}).strict(),nf=r({expected_revision:G.optional()}).strict().default({}),af=r({entry_ids:p(n().uuid()).max(Re)}
2).strict(),rf=r({group_id:n().uuid().nullable(),entry_ids:p(n().uuid()).max(Re)}).strict(),of=r({expected_revision:G,operation_id:Ne,layout:p(rf).min(1).max(on)}).strict(),sf=V([af,of]),cf=r({group_id:n().uuid(),name:$h,position:u().int().min(0).max(on-1)}).strict(),lf=r({group_id:n().uuid(),destination_group_id:n().uuid()}).strict();r({expected_revision:G,operation_id:Ne,entry_ids:p(n().uuid()).min(1).max(Re),destination_group_id:n().uuid(),destination_index:u().int().min(0).max(Re).optional()}).strict();const df=r({expected_revision:G,operation_id:Ne,entry_ids:p(n().uuid()).min(1).max(Re)}).strict(),uf=r({expected_revision:G,operation_id:Ne}).strict(),zs=r({group_id:n().uuid(),name:n(),position:u().int().min(0),created_at:n(),updated_at:n()});r({collection_id:n().uuid(),structure:qr,revision:G,groups:p(zs)});const mf=ot(n(),it()).nullable(),pf=r({entry_id:n().uuid(),position:u().int().min(0),title:n().nullable(),authors:p(n()),fandoms:p(n()),relationships:p(n()),source_host:n().nullable(),source:n().nullable()}),qs=r({kind:f(["available","review","collection_blocked","account_blocked","republish_blocked"])}).strict(),Ks=r({collection_id:n().uuid(),title:n(),description:n(),source_kind:Vh,source_query:mf,structure:qr.optional(),colour:Vs,revision:G.optional(),group_count:u().int().min(0).optional(),group_names:p(n()).max(50).optional(),item_count:u().int().min(0),note_count:u().int().min(0),share_enabled:x().default(!1),sharing_availability:qs.default({kind:"available"}),identity_summary:n(),preview_items:p(pf).max(3),last_curated_at:n(),created_at:n(),updated_at:n()}),hf=r({entry_id:n().uuid(),story_id:u().int().positive(),status:Se,progress:r({unit:f(["CHAPTER","WORD","PERCENT"]),value:u().int().min(0),total:u().int().min(0).nullable()}),rating:u().int().min(0).max(5),tags:p(n()),notes:n().optional(),has_notes:x().optional(),updated_at:n(),created_at:n(),re_read_count:u().int().min(0),last_read_at:n().nullable()}),ff=r({authors:x(),characters:x(),fandoms:x(),relationships:x(),warnings:x(),categories:x(),work_tags:x()}),_f=r({title:n().nullable().optional(),words:u().int().min(0).nullable().optional(),summary:n().nullable().optional(),rating:n().nullable().optional(),rating_bucket:oa.nullable().optional(),language:n().nullable().optional(),genre:n().nullable().optional(),kudos:u().int().min(0).nullable().optional(),favorites:u().int().min(0).nullable().optional(),published_date:n().nullable().optional(),updated_date:n().nullable().optional(),chapters_published:u().int().min(0).nullable().optional(),chapters_planned:u().int().min(0).nullable().optional(),completion_status:n().nullable().optional(),work_status_override:n().nullable().optional(),abandoned_at_chapters_published:u().int().min(0).nullable().optional(),canonical_url:n().nullable().optional(),source_host:n().nullable().optional(),source:n().nullable().optional(),authors:p(n()).optional(),characters:p(n()).optional(),canonical_characters:p(n()).optional(),fandoms:p(n()).optional(),canonical_fandoms:p(n()).optional(),relationships:p(n()).optional(),warnings:p(n()).optional(),categories:p(n()).optional(),work_tags:p(n()).optional(),series:p(ot(n(),it())).optional(),taxonomy_known:ff.optional()}).catchall(it()),pa=r({entry_id:n().uuid(),position:u().int().min(0),group_id:n().uuid().nullable().optional(),note:n(),added_at:n(),updated_at:n(),work_status:Mt,work_status_provenance:Ft,catchup_state:dn,new_chapter_count:u().int().min(0),story_update:Yr.nullable().optional(),entry:hf,story:_f}),De=Ks.extend({groups:p(zs).optional(),items:p(pa)}),Bt=r({operation_id:Ne,replayed:x(),previous_revision:u().int().min(0),revision:G,undo_available:x()}),gf=r({collections:p(Ks)}),$e=r({collection:De,operation:Bt.optional()});r({request_id:n().uuid(),query:Ys,collection:De,ordered_entry_ids:p(n().uuid()).max(Re),match_count:u().int().min(0).max(Re)});const bf=$e,yf=r({item:pa,revision:G.optional()}),vf=r({items:p(pa),revision:G.optional()}),Sf=r({ok:_(!0),operation:Bt.optional()}),mo=r({collection:De,operation:Bt});r({ok:_(!0),operation:Bt});r({code:_("COLLECTION_ITEM_LIMIT_EXCEEDED"),limit:_(Re),total:u().int().min(0).optional(),current_count:u().int().min(0).optional(),requested_count:u().int().min(0).optional()});const mn=n().trim().regex(/^[A-Za-z0-9_-]{16,80}$/),xf=n().trim().min(1).max(80),Ef=q(e=>typeof e=="string"&&e.trim()===""?null:e,n().trim().max(60).nullable().optional()),wf=ys.optional(),Af=f(["anonymous","profile","custom"]),Qs=lt("mode",[r({mode:_("anonymous")}).strict(),r({mode:_("profile")}
2).strict(),r({mode:_("custom"),display_name:xf,handle:Ef,url:wf}).strict()]),Rf=r({mode:Af,display_name:n().nullable(),handle:n().nullable(),url:Pr}).strict(),Tf=r({display_name:n(),handle:n().nullable(),url:Pr}).strict(),Fe=n().trim().regex(/^pci1_[A-Za-z0-9_-]{43}$/),Js=n().trim().regex(/^pcg1_[A-Za-z0-9_-]{43}$/);r({shareSlug:mn}).strict();const kf=f(["spam","harassment","sexual_or_violent","illegal_or_unsafe","privacy_or_impersonation","copyright","unsafe_link","other"]),Cf=r({reason:kf,message:n().trim().max(5e3).optional().default(""),contact_email:q(e=>typeof e=="string"&&e.trim()===""?null:e,n().trim().email().max(320).nullable().optional()).optional(),public_item_ref:Fe.optional()}).strict(),Nf=r({data:r({report_id:n().uuid(),created_at:n()}).strict()}).strict(),If=r({include_notes:x().optional(),attribution:Qs.optional(),expected_revision:G.optional()}).strict(),Xs=r({include_notes:x().optional(),enabled:x().optional(),attribution:Qs.optional(),expected_revision:G.optional()}).strict().refine(e=>e.include_notes!==void 0||e.enabled!==void 0||e.attribution!==void 0,{message:"At least one share setting is required"});r({expected_revision:G,operation_id:Ne,title:ut,description:mt,structure:zr,colour:ua.optional(),groups:p(cf).max(on),deleted_group_destinations:p(lf).max(on).optional().default([]),confirm_group_name_loss:x().optional().default(!1),share:Xs.optional()}).strict();const Of=r({revision:G.optional(),enabled:x(),share_slug:n().nullable(),share_url:n().nullable(),include_notes:x(),sharing_availability:qs.default({kind:"available"}),attribution:Rf,created_at:n().nullable(),updated_at:n().nullable()}),kn=r({share:Of,operation:Bt.optional()}),Pf=r({title:n().nullable(),authors:p(n()),fandoms:p(n()),relationships:p(n()),characters:p(n()),warnings:p(n()),categories:p(n()),work_tags:p(n()),source:n().nullable(),source_host:n().nullable(),canonical_url:n().nullable(),summary:n().nullable(),words:u().int().min(0).nullable(),rating:n().nullable(),language:n().nullable(),published_date:n().nullable(),updated_date:n().nullable(),chapters_published:u().int().min(0).nullable(),chapters_planned:u().int().min(0).nullable(),work_status:Mt,work_status_provenance:Ft,public_link:r({status:f(["approved","pending","blocked","ignored","unavailable"]),host:n().nullable(),url:n().nullable(),message:n().nullable()}).strict().optional()}),Lf=r({public_item_ref:Fe,public_group_ref:Js.nullable().optional(),position:u().int().min(0),note:n().optional(),story:Pf}),Df=r({public_group_ref:Js,name:n(),position:u().int().min(0)}),jf=r({share_slug:n(),title:n(),description:n(),structure:qr.optional(),colour:Vs.optional(),groups:p(Df).optional(),item_count:u().int().min(0),include_notes:x(),attribution:Tf.nullable(),created_at:n(),updated_at:n(),items:p(Lf)}),Pw=r({collection:jf}),Zs=f(["all","items"]),Uf=f(["empty","copy_public_note"]),Kr=r({public_item_ref:Fe.optional(),position:u().int().min(0)}),Mf=r({public_item_ref:Fe,position:u().int().min(0)}),ec=r({requested_count:u().int().min(0),created_library_entries:u().int().min(0),reused_library_entries:u().int().min(0),added_to_collection:u().int().min(0),skipped_unavailable:p(Kr),skipped_duplicates:p(Mf)}),Ff=r({share_slug:mn,public_item_ref:Fe}).strict(),tc=f(["created","already_in_library"]),nc=f(["created_from_public_snapshot","reused_existing_story","reused_existing_library_entry"]),Bf=r({data:r({entry_id:n().uuid(),status:tc,story_action:nc,skipped:p(Kr)})}),Hf=r({dry_run:x().optional(),chunk:x().optional(),share_slug:mn,public_item_refs:p(Fe).min(1).max(un).optional(),selection:Zs.optional().default("all")}).strict().superRefine(Qr),Vf=r({public_item_ref:Fe,position:u().int().min(0),entry_id:n().uuid(),status:tc,story_action:nc}),Wf=r({requested_count:u().int().min(0),created_library_entries:u().int().min(0),reused_library_entries:u().int().min(0),skipped_unavailable:p(Kr)}),$f=r({data:r({items:p(Vf),summary:Wf,capacity:r({requested_new:u().int().nonnegative(),remaining:u().int().nonnegative().nullable()}).optional()})}),Yf=r({share_slug:mn,public_item_refs:p(Fe).min(1).max(un)}).strict();r({code:_("FREE_LIMIT_REACHED"),limit:u().int().nonnegative(),used:u().int().nonnegative(),remaining:u().int().nonnegative(),requested_new:u().int().nonnegative(),would_exceed_by:u().int().positive()});const Gf=r({public_item_ref:Fe,status:_("already_in_library"),own_state:r({entry_id:n().uuid(),status:Se,progress_unit:f(["CHAPTER","PAGE","PERCENT"]),progress_value:u(),progress_total:u().nullable(),rating:u()}).optional()}),zf=r({items:p(Gf)}),ac={share_slug:mn,public_item_refs:p(Fe).min(1).max(un).optional(),selection:Zs.optional().default("items"),note_mode:Uf.optional().default("empty")};function Qr(e,t){e.selection==="items"&&!e.public_item_refs?.length&&t.addIssue({code:se.custom,path:["public_item_refs"],message:"public_item_refs are required when selection is items"})}const qf=r({colour:ua.optional(),title:ut,description:mt.optional(),operation_id:Ne.optional(),structure_mode:_("preserve").optional(),...ac}).strict().superRefine(Qr),Kf=r({collection:De,summary:ec,operation:Bt.optional()}),Qf=r({...ac,group_id:n().uuid().nullable().optional(),expected_revision:G.optional()}).strict().superRefine(Qr),Jf=r({items:p(pa),revision:G.optional(),summary:ec});r({error:n(),code:_("PUBLIC_COLLECTION_ITEM_UNAVAILABLE"),position:u().int().min(0).optional()});r({error:n(),code:_("PUBLIC_COLLECTION_ITEM_NOT_FOUND"),position:u().int().min(0).optional()});r({error:n(),code:_("PUBLIC_COLLECTION_NO_ACTIONABLE_ITEMS")});const Xf=n().regex(/^(?:[+-](?:0\d|1[0-3]):[0-5]\d|[+-]14:00)$/,"Expected a UTC offset from -14:00 through +14:00"),Zf=n().trim().min(1).max(100).refine(e=>{try{return new Intl.DateTimeFormat("en",{timeZone:e}).format(),!0}catch{return!1}},"Expected a valid IANA timezone"),e_=lt("kind",[r({kind:_("IANA"),value:Zf}).strict(),r({kind:_("OFFSET"),value:Xf}).strict()]),t_=r({occurredAt:n().datetime({offset:!0}).optional(),calendarDate:C().optional(),timeZone:e_.optional()}).strict(),rc=t_.extend({operationId:n().uuid().optional()}).strict(),O=(e,t=255)=>q(a=>a===void 0||a===""?void 0:Array.isArray(a)?a:[a],p(n().trim().max(t)).max(e).optional()),ja=()=>q(e=>e===void 0||e===""?void 0:Array.isArray(e)?e:[e],Ds),ee=(e=255)=>q(t=>{if(t===void 0||t==="")return;const a=Array.isArray(t)?t[0]:t;
2return typeof a=="string"||typeof a=="number"||typeof a=="boolean"?String(a).trim():void 0},n().max(e).optional()),or=(e,t,a)=>q(c=>{if(c===void 0||c==="")return e;const m=Array.isArray(c)?c[0]:c,h=parseInt(String(m??""),10),d=Number.isFinite(h)?h:e;return Math.min(Math.max(d,t),a)},u().int().min(t).max(a).default(e)),Le=(e,t)=>q(a=>{if(a===void 0||a==="")return;const c=Array.isArray(a)?a[0]:a,m=parseInt(String(c??""),10);return Number.isFinite(m)&&m>=e&&m<=t?m:void 0},u().int().min(e).max(t).optional()),It=()=>q(e=>jn(e),x().optional()),n_=()=>q(e=>{const t=Array.isArray(e)?e[0]:e,a=String(t??"").trim().toUpperCase();return a==="ANY"||a==="UP"||a==="BEHIND"?a:void 0},f(["ANY","UP","BEHIND"]).optional()),po=()=>q(e=>{const t=Array.isArray(e)?e[0]:e,a=String(t??"").trim().toUpperCase();return a==="ANY"||a==="WITH"||a==="WITHOUT"?a:void 0},f(["ANY","WITH","WITHOUT"]).optional()),a_=()=>q(e=>{const t=Array.isArray(e)?e[0]:e,a=typeof t=="string"?t:void 0;return zn.safeParse(a).success?a:"LAST_READ_DESC"},zn.default("LAST_READ_DESC")),r_=()=>q(e=>{const t=Array.isArray(e)?e[0]:e,a=typeof t=="string"?t.trim().toLowerCase():"";return a==="cursor"||a==="page"?a:"page"},f(["page","cursor"]).default("page")),ic=r({page:or(1,1,1e6),limit:or(50,1,100),cursor:ee(2048),pagination:r_(),search:ee(200),sort:a_(),status:ja(),"status[]":ja(),statuses:ja(),rating:O(20,20),"rating[]":O(20,20),ratings:O(20,20),"platforms[]":O(10,255),platforms:O(10,255),minWords:Le(0,5e7),min_words:Le(0,5e7),maxWords:Le(0,5e7),max_words:Le(0,5e7),minKudos:Le(0,1e7),min_kudos:Le(0,1e7),maxKudos:Le(0,1e7),max_kudos:Le(0,1e7),hasNotes:It(),has_notes:It(),notes:po(),notes_filter:po(),tag:ee(255),workTag:ee(255),work_tag:ee(255),character:O(60),"character[]":O(60),characters:O(60),relationship:O(80),"relationship[]":O(80),relationshipNames:O(80),fandom:O(60),"fandom[]":O(60),fandoms:O(60),pair_member:O(10),"pair_member[]":O(10),pairMembers:O(10),pairExact:It(),pair_exact:It(),"completion_status[]":O(10,50),completion_status:O(10,50),exclude_warning:O(20),"exclude_warning[]":O(20),include_warning:O(20),"include_warning[]":O(20),category:O(10,50),"category[]":O(10,50),exclude_tag:ee(255),exclude_work_tag:ee(255),exclude_pair_member:O(10),"exclude_pair_member[]":O(10),excludePairExact:It(),exclude_pair_exact:It(),exclude_character:O(60),"exclude_character[]":O(60),exclude_fandom:O(60),"exclude_fandom[]":O(60),exclude_category:O(10,50),"exclude_category[]":O(10,50),lastReadAfter:ee(),last_read_after:ee(),lastReadBefore:ee(),last_read_before:ee(),catchup:n_(),minEntryRating:Le(1,5),min_entry_rating:Le(1,5),entryRating:ee(20),entry_rating:ee(20),storyUpdates:ee(20),story_updates:ee(20)}).strip();ic.transform(e=>Us.parse(Wr(e)));ic.extend({q:ee(255),limit:or(200,1,500)}).transform(e=>{const{q:t,limit:a,...c}=e,m={...c};return delete m.cursor,delete m.pagination,{query:Us.parse(Wr(m)),q:t??"",limit:a}});const i_=r({tag:n(),count:u().int().min(0)}),o_=r({data:p(i_)}),s_=r({work_status_override:uh.nullable().optional(),abandoned_at_chapters_published:u().int().min(0).max(1e7).nullable().optional()}).strict(),ha=r({completedOn:n().regex(/^(?!0000)\d{4}-\d{2}-\d{2}$/,"Expected an ISO calendar date").nullable(),timeZone:n().trim().min(1).max(100)}).strict(),fa=r({status:sa,progress:r({unit:f(["CHAPTER","WORD","PERCENT"]),value:u().int().min(0).max(1e7),total:u().int().min(0).max(1e7).nullable().optional()}).optional(),rating:u().int().min(0).max(5).optional(),tags:p(n().trim().min(1).max(255)).max(200).optional(),notes:n().max(2e4).optional(),lastReadAt:n().datetime({offset:!0}).nullable().optional(),completion:ha.optional(),readingActivity:rc.optional(),story_snapshot:s_.optional()}),c_=r({updates:p(r({entryId:n().uuid(),patch:fa}).strict()).min(1).max(100)}).strict(),sr=(e="")=>q(t=>t??e,n()),me=()=>q(e=>e??[],p(n())),Qn=ot(n(),it()),l_=r({url:n().trim().url().max(2048)}).strict(),d_=r({url:n().trim().url().max(2048),claim:Qn.optional()}).strict(),u_=r({story_id:H().int().positive(),entry:fa.optional(),story_snapshot:Qn.optional(),insert_only:V([x(),n(),u()]).optional()}).strict(),m_=r({key:n().trim().min(1).max(512),url:n().trim().url().max(2048),
2claim:Qn.optional(),entry:fa.omit({lastReadAt:!0,story_snapshot:!0}).strict(),story_snapshot:Qn.optional()}).strict();r({items:p(m_).min(1).max(250)}).strict().superRefine(({items:e},t)=>{const a=new Set;for(const[c,m]of e.entries())a.has(m.key)&&t.addIssue({code:se.custom,path:["items",c,"key"],message:"Import item keys must be unique"}),a.add(m.key)});const p_=r({title:n().trim().min(1).max(300),author:n().trim().max(200).optional(),fandom:n().trim().max(255).optional(),url:n().trim().url().max(2048).optional(),characters:p(n().trim().max(255)).max(60).optional(),relationships:p(n().trim().max(255)).max(80).optional(),status:sa,notes:n().trim().max(1e4).optional(),tags:p(n().trim().max(100)).max(50).optional(),summary:n().trim().max(2e4).optional(),words:H().int().min(0).max(1e8).optional(),rating:n().trim().max(60).optional(),chaptersPublished:H().int().min(1).max(1e7).optional(),completionStatus:f(["complete","wip","hiatus","abandoned"]).optional(),completion:ha.optional(),progress:r({value:H().int().min(0).max(1e7).default(0),total:V([H().int().min(0).max(1e7),pe()]).optional()}).strict().optional()}).strict(),h_=r({name:n(),position:u().int().nullable(),url:n().nullable()}),f_=r({story_id:u().int().positive(),title:sr(),words:u().int().min(0).nullable(),rating:n().nullable(),language:n().nullable(),published_date:n().nullable(),updated_date:n().nullable(),chapters_published:u().int().min(0).nullable(),chapters_planned:u().int().min(0).nullable(),authors:me(),characters:me(),canonical_characters:me().optional(),fandoms:me(),canonical_fandoms:me().optional(),relationships:me(),summary:sr(),canonical_url:n().nullable(),source_host:n().nullable(),source:n().nullable(),kudos:u().int().min(0).nullable(),hits:u().int().min(0).nullable(),bookmarks:u().int().min(0).nullable(),comments_count:u().int().min(0).nullable(),reviews:u().int().min(0).nullable(),favorites:u().int().min(0).nullable(),follows:u().int().min(0).nullable(),completion_status:n().nullable(),work_status_override:n().nullable().optional(),abandoned_at_chapters_published:u().int().min(0).nullable().optional(),genre:n().nullable(),warnings:me(),categories:me(),work_tags:me().optional(),series:q(e=>e??[],p(h_))}),Jr=r({unit:f(["CHAPTER","WORD","PERCENT"]),value:u().int().min(0),total:u().int().min(0).nullable().optional()}),__=r({entry_id:n().uuid(),user_id:n(),story_id:u().int().positive(),status:Se,progress:Jr,rating:u().int().min(0).max(5),tags:me(),notes:n(),updated_at:n(),created_at:n(),re_read_count:u().int().min(0).optional(),last_read_at:n().nullable().optional(),continue_url:n().nullable().optional(),continue_url_chapter:u().int().min(0).nullable().optional(),continue_url_is_exact:x().nullable().optional()}),g_=r({collection_id:n().uuid(),title:n()}),en=r({work_status:Mt,source_work_status:dh.optional(),work_status_provenance:Ft,catchup_state:dn,new_chapter_count:u().int().min(0),story_update:Yr.nullable().optional(),collections:p(g_).optional(),story:f_,entry:__}),oc=r({read_number:u().int().positive(),completed:x(),completed_on:n().regex(/^(?!0000)\d{4}-\d{2}-\d{2}$/).nullable(),is_current:x()}),b_=r({data:p(en),total:u().int().min(0).optional(),hasMore:x().optional(),nextCursor:n().min(1).nullable().optional()}),y_=r({data:en.extend({source_work_key:n().regex(/^(ao3|ffn):[1-9][0-9]{0,19}$/).nullable().optional(),reading_history:p(oc)})}),v_=ha;r({lastReadOn:n().regex(/^(?!0000)\d{4}-\d{2}-\d{2}$/,"Expected an ISO calendar date").nullable(),timeZone:n().trim().min(1).max(100)}).strict();r({data:r({entry_id:n().uuid(),last_read_at:n().datetime({offset:!0}).nullable()}).strict()}).strict();const S_=r({data:oc}).strict(),x_=r({entry_id:n().uuid(),prestige_hint:x().optional()}),E_=r({data:x_.nullable()}),w_=r({data:r({updated:p(n().uuid()),missing:p(n().uuid())})}),A_=r({ok:_(!0)}),sc=r({data:r({entry_id:n().uuid(),re_read_count:u().int().min(0),status:Se,progress_value:u().int().min(0)})}),R_=sc;r({expected:r({progress:r({unit:_("CHAPTER"),value:u().int().min(0).max(1e7)}).strict(),sourceTarget:u().int().min(1).max(1e7)}).strict()}).strict();const T_=r({entry_id:n().uuid(),applied:x(),progress:r({unit:_("CHAPTER"),value:u().int().min(0),total:u().int().min(0).nullable()}).strict(),source_target:u().int().positive(),catchup_state:_("UP"),new_chapter_count:_(0)}).strict();r({data:T_}).strict();const Un=r({status:Se,progress:Jr,lastReadAt:n().datetime({offset:!0}).nullable(),readNumber:u().int().positive(),reReadCount:u().int().min(0),currentRead:r({completed:x(),completedOn:n().regex(/^(?!0000)\d{4}-\d{2}-\d{2}$/).nullable()}).strict()}).strict(),k_=f(["SAVED","READING","CAUGHT_UP","PAUSED","DROPPED"]);lt("action",[r({operationId:n().uuid(),action:_("FINISH"),expected:Un,completion:ha}).strict(),r({operationId:n().uuid(),action:_("CORRECT_FINISHED"),expected:Un,targetStatus:k_}).strict(),r({operationId:n().uuid(),action:_("START_REREAD"),expected:Un}
2).strict(),r({operationId:n().uuid(),action:_("UNDO_FINISH"),undoOfOperationId:n().uuid()}).strict()]);const C_=r({operation_id:n().uuid(),action:f(["FINISH","CORRECT_FINISHED","START_REREAD","UNDO_FINISH"]),replayed:x(),entry_id:n().uuid(),read_number:u().int().positive(),status:Se,progress:Jr.extend({total:u().int().min(0).nullable()}),re_read_count:u().int().min(0),undo_of_operation_id:n().uuid().optional()}).strict();r({data:C_}).strict();const N_=r({story_id:u().int().positive(),title:sr(),authors:me(),fandoms:me(),characters:me(),words:u().int().min(0).nullable(),chapters:u().int().min(0).nullable().optional(),canonical_url:n(),source:n().nullable().optional(),description:n().nullable().optional(),chaptersPublished:u().int().min(0).nullable(),chaptersPlanned:u().int().min(0).nullable()}),I_=r({story:N_}),O_=r({story_id:u().int().positive(),deltas:r({words:u().int(),chaptersPublished:u().int(),chaptersPlanned:u().int()})}),P_=r({story:O_}),L_=r({data:r({entry_id:n().uuid(),existed:x()})}),D_=lt("status",[r({key:n(),status:f(["ADDED","EXISTED"]),story_id:u().int().positive(),entry_id:n().uuid(),deltas:r({words:u().int(),chaptersPublished:u().int(),chaptersPlanned:u().int()}).optional()}).strict(),r({key:n(),status:_("ERROR"),code:n(),message:n(),retryable:x()}).strict()]);r({data:r({results:p(D_)}).strict()}).strict();const j_=r({data:r({story_id:u().int().positive(),entry_id:n().uuid()})});r({error:n().optional(),code:n().optional(),error_id:n().optional(),issues:p(r({path:n(),message:n()})).optional()}).loose();const cr=ot(n(),it()),U_=2e3,cc=500,M_=2e4,_a=200,Xr=25e5,Be=r({source:_("AO3"),work_id:n().trim().regex(/^\d{1,20}$/),canonical_url:n().trim().url().max(2048)}).strict().superRefine((e,t)=>{let a;try{a=new URL(e.canonical_url)}catch{return}const c=a.hostname.toLowerCase(),m=a.pathname.match(/\/works\/(\d+)/);(!c.endsWith("archiveofourown.org")||m?.[1]!==e.work_id)&&t.addIssue({code:se.custom,path:["canonical_url"],message:"canonical_url must be an AO3 work URL matching work_id"})}),F_=r({chapter:u().int().min(0).max(1e7),total_chapters:u().int().min(0).max(1e7).nullable().optional(),reading_event:x().default(!1)}).strict(),B_=r({entry_id:n().uuid().optional(),work:Be,claim:cr.optional(),story_snapshot:cr.optional(),progress:F_,readingActivity:rc.optional(),status:sa,rating:u().int().min(0).max(5).optional()}
2).strict(),H_=r({data:r({entry_id:n().uuid(),story_id:u().int().positive(),created:x(),status:Se,progress:r({unit:_("CHAPTER"),value:u().int().min(0),total:u().int().min(0).nullable()}),rating:u().int().min(0).max(5),personal_state:r({revision:u().int().min(1),field_revisions:r({status:u().int().min(1),rating:u().int().min(1),tags:u().int().min(1),note:u().int().min(1)}),tags:p(n()),note:n()}).optional()})}),St=f(["capacity","downgrade_lock","reader_removed"]),V_=r({data:r({sync_state:_("local_only"),reason:St,work:Be}).strict()}).strict();V([H_,V_]);const lc=r({client_id:n().uuid(),work:Be,last_read_at:n().datetime({offset:!0}).nullable().optional(),added_at:n().datetime({offset:!0}).nullable().optional()}).strict();function Zr(e,t,a="works",c=["work"]){const m=new Set,h=new Set;e.forEach((d,v)=>{m.has(d.client_id)&&t.addIssue({code:se.custom,path:[a,v,"client_id"],message:"client_id values must be unique"}),h.has(d.work.work_id)&&t.addIssue({code:se.custom,path:[a,v,...c,"work_id"],message:"AO3 work identities must be unique"}),m.add(d.client_id),h.add(d.work.work_id)})}r({works:p(lc).max(U_)}).strict().superRefine((e,t)=>Zr(e.works,t));const ei=r({plan:f(["free","unlimited"]),unlimited:x(),total_limit:u().int().min(0).nullable(),used:u().int().min(0),remaining:u().int().min(0).nullable(),downgrade_locked:x()}).strict(),ti=r({client_id:n().uuid(),work:Be,entry_id:n().uuid()}).strict();r({data:r({capacity:ei,matched:p(ti),recommended:p(n().uuid()),overflow:p(n().uuid()),selection_limits:r({max_items:_(_a),max_bytes:_(Xr)}).strict()}).strict()}).strict();const W_=r({client_id:n().uuid(),last_read_at:n().datetime({offset:!0}).nullable().optional(),added_at:n().datetime({offset:!0}).nullable().optional(),sync:B_}).strict();r({selection_id:n().uuid(),items:p(W_).min(1).max(_a)}).strict().superRefine((e,t)=>{Zr(e.items.map(a=>({client_id:a.client_id,work:a.sync.work,last_read_at:a.last_read_at,added_at:a.added_at})),t,"items",["sync","work"])});const $_=ti.extend({created:x(),progress_value:u().int().min(0)}).strict(),Y_=r({client_id:n().uuid(),work:Be,reason:St}).strict();r({data:r({selection_id:n().uuid(),capacity:ei,matched:p(ti),selected:p(n().uuid()),synced:p($_),overflow:p(Y_)}).strict()}).strict();r({request_id:n().uuid()}).strict();r({data:r({session_id:n().uuid(),expires_at:n().datetime({offset:!0}),selection_limits:r({max_items:_(_a),max_bytes:_(Xr)}).strict(),page_limits:r({max_works:_(cc),max_total_works:_(M_)}).strict()}).strict()}).strict();r({page_id:n().uuid(),works:p(lc).min(1).max(cc)}).strict().superRefine((e,t)=>Zr(e.works,t));r({data:r({session_id:n().uuid(),page_id:n().uuid(),accepted_count:u().int().min(0),total_count:u().int().min(0),replayed:x(),expires_at:n().datetime({offset:!0})}).strict()}).strict();r({data:r({session_id:n().uuid(),completed_at:n().datetime({offset:!0}),capacity:ei,total_count:u().int().min(0),matched_count:u().int().min(0),recommended_count:u().int().min(0),overflow_count:u().int().min(0),selection_limits:r({max_items:_(_a),max_bytes:_(Xr)}).strict()}).strict()}).strict();r({cursor:n().trim().min(1).max(128).optional(),limit:H().int().min(1).max(500).default(500)}).strict();const G_=r({client_id:n().uuid(),work:Be,entry_id:n().uuid().nullable(),recommended:x(),overflow_reason:St.nullable()}).strict();r({data:r({session_id:n().uuid(),items:p(G_),next_cursor:n().nullable()}).strict()}).strict();const dc=r({status:u().int().min(1),rating:u().int().min(1),tags:u().int().min(1),note:u().int().min(1)}).strict(),Dt=r({entry_id:n().uuid(),status:Se,rating:u().int().min(0).max(5),tags:p(n()),note:n(),revision:u().int().min(1),field_revisions:dc,updated_at:n()}).strict(),uc=r({algorithm:_("trace-chapter-map-sha256-v1"),value:n().regex(/^[0-9a-f]{64}$/)}).strict(),mc=r({chapter:u().int().min(1).max(1e7),progression:u().finite().min(0).max(1)}).strict(),pc=r({version:_(1),epub_fingerprint:uc,locator:mc,client_updated_at:n().datetime({offset:!0}),server_updated_at:n().datetime({offset:!0})}).strict();r({mutation_id:n().uuid(),work:Be,version:_(1),epub_fingerprint:uc,locator:mc,client_updated_at:n().datetime({offset:!0})}).strict();const ni=r({entry_id:n().uuid(),work:Be,resume_position:pc.nullable()}).strict();r({data:ni}
2).strict();const z_=r({data:ni.extend({applied:x(),replayed:x()}).strict()}).strict();r({code:_("READER_RESUME_POSITION_STALE"),data:ni.extend({applied:_(!1),replayed:x()}).strict()}).strict();const q_=r({data:r({entry_id:n().uuid(),work:Be,sync_state:_("local_only"),reason:St}).strict()}).strict();V([z_,q_]);r({cursor:n().trim().min(1).max(1024).optional(),limit:H().int().min(1).max(200).default(100)}).strict();const K_=r({sync_enabled:x(),paused_reason:_("downgrade_lock").nullable(),selected_at:n().datetime({offset:!0}),reader_added_at:n().datetime({offset:!0}).nullable(),reader_last_read_at:n().datetime({offset:!0}).nullable(),updated_at:n().datetime({offset:!0})}).strict().superRefine((e,t)=>{const a=e.sync_enabled&&e.paused_reason==null,c=!e.sync_enabled&&e.paused_reason==="downgrade_lock";!a&&!c&&t.addIssue({code:se.custom,message:"Reader restore association state is inconsistent"})}),Q_=r({entry_id:n().uuid(),work:Be,story_snapshot:cr,progress:r({unit:_("CHAPTER"),value:u().int().min(0),total:u().int().min(0).nullable()}).strict(),personal_state:Dt,resume_position:pc.nullable(),association:K_,entry_created_at:n().datetime({offset:!0}),entry_updated_at:n().datetime({offset:!0})}).strict();r({data:r({items:p(Q_).max(200),next_cursor:n().max(1024).nullable()}).strict()}).strict();r({data:r({entry_id:n().uuid(),detached:x(),removed_at:n().datetime({offset:!0}).nullable()}).strict()}).strict();r({entry_ids:p(n().uuid()).min(1).max(100)}).strict();r({data:p(Dt),local_only:p(r({entry_id:n().uuid(),sync_state:_("local_only"),reason:St}).strict()).optional()}).strict();const J_=r({status:sa.optional(),rating:u().int().min(0).max(5).optional(),tags:p(n().trim().min(1).max(40)).max(40).optional(),note:n().max(1e4).optional()}).strict(),X_=r({mutation_id:n().uuid(),base_revisions:dc,changes:J_}).strict().superRefine((e,t)=>{e.changes.status!==void 0||e.changes.rating!==void 0||e.changes.tags!==void 0||e.changes.note!==void 0||t.addIssue({code:se.custom,path:["changes"],message:"At least one personal-state field must change"})}),Z_=r({data:Dt}).strict(),hc=f(["development","testflight","app_store","unknown"]),eg=f(["contextual_prompt_viewed","contextual_prompt_dismissed","value_page_viewed","value_page_dismissed","auth_started","auth_succeeded","auth_cancelled","auth_failed","upgrade_started","upgrade_succeeded"]),tg=r({event:eg,consent:_("opted_in"),source:f(["story_detail","library","settings","account"]),app_channel:hc,plan:f(["free","unlimited","unknown"]).optional(),capacity_state:f(["under_limit","at_limit","overflow","unlimited","unknown"]).optional(),failure_category:f(["network","configuration","credentials","other"]).optional()}).strict().superRefine((e,t)=>{e.failure_category&&e.event!=="auth_failed"&&t.addIssue({code:se.custom,path:["failure_category"],message:"failure_category is only valid for auth_failed"})}),ng=new Set(["contextual_prompt_viewed","contextual_prompt_dismissed","value_page_viewed","value_page_dismissed","auth_started","auth_cancelled","auth_failed"]);tg.refine(e=>ng.has(e.event),{path:["event"],message:"This conversion event requires an authenticated Trace account"});r({event:f(["capacity_preflight","capacity_selection","restore","sync_flush","retry","auth_expired","conflict","resume_fallback","billing_purchase","billing_restore","entitlement_refresh"]),outcome:f(["succeeded","failed","deferred","cancelled"]),app_channel:hc,plan:f(["free","unlimited","unknown"]).optional(),capacity_state:f(["under_limit","at_limit","overflow","unlimited","unknown"]).optional(),failure_category:f(["offline","rate_limited","authentication","invalid_payload","invalid_response","server_unavailable","conflict","capacity","unknown"]).optional(),library_size_band:f(["0","1","2-10","11-50","51-100","101-300","301-1000","1001-2000","2001+"]).optional(),duration_band:f(["under_1s","1-5s","5-20s","20s_plus"]).optional(),retry_band:f(["none","1","2-3","4_plus"]).optional()}).strict();r({data:r({accepted:_(!0)}).strict()}).strict();r({code:_("READER_PERSONAL_STATE_CONFLICT"),conflicts:p(f(["status","rating","note"])).min(1),data:Dt}).strict();const ag=r({entry_id:n().uuid(),sync_state:_("local_only"),reason:St}).strict();r({mutations:p(r({entry_id:n().uuid(),mutation:X_}).strict()).min(1).max(50)}).strict().superRefine((e,t)=>
2{const a=new Set,c=new Set;e.mutations.forEach((m,h)=>{a.has(m.mutation.mutation_id)&&t.addIssue({code:se.custom,path:["mutations",h,"mutation","mutation_id"],message:"mutation_id values must be unique within a bulk request"}),a.add(m.mutation.mutation_id),c.has(m.entry_id)&&t.addIssue({code:se.custom,path:["mutations",h,"entry_id"],message:"entry_id values must be unique within a bulk request"}),c.add(m.entry_id)})});V([Z_,r({data:ag}).strict()]);const rg=lt("kind",[r({kind:_("updated"),entry_id:n().uuid(),mutation_id:n().uuid(),data:Dt}).strict(),r({kind:_("conflict"),entry_id:n().uuid(),mutation_id:n().uuid(),conflicts:p(f(["status","rating","note"])).min(1),data:Dt}).strict(),r({kind:_("local_only"),entry_id:n().uuid(),mutation_id:n().uuid(),sync_state:_("local_only"),reason:St}).strict(),r({kind:_("not_found"),entry_id:n().uuid(),mutation_id:n().uuid(),code:_("READER_LIBRARY_ENTRY_NOT_FOUND")}).strict()]);r({data:r({results:p(rg)}).strict()}).strict();const ig=200,og=500,fc=n().trim().min(1).max(ig);r({viewId:n().uuid()}).strict();const sg=r({name:fc,query:Ue,pinned:x().optional().default(!1)}).strict(),cg=r({name:fc.optional(),query:Ue.optional(),pinned:x().optional(),position:u().int().min(0).optional()}).strict().refine(e=>Object.keys(e).length>0,{message:"At least one field is required"}),lg=r({view_ids:p(n().uuid()).max(og)}).strict(),_c=r({view_id:n().uuid(),name:n(),query:Ue,pinned:x(),position:u().int().min(0),created_at:n(),updated_at:n(),live_count:u().int().min(0).optional()}).strict(),ho=r({view:_c}).strict(),fo=r({views:p(_c)}).strict(),dg=r({ok:_(!0)}).strict(),_o=100,gc=f(["context","global"]),pn=n().min(1).max(80).regex(/^[A-Za-z0-9._:-]+$/,{message:"Expected a stable extension-generated saved-filter id"}),ug=n().min(1).max(160).regex(/^(?:work_search|include_work_search|exclude_work_search)\[[a-z0-9_]+\](?:\[\])?$/,{message:"Expected an AO3 work filter query parameter"}),bc=Wl([ug,n().min(1).max(300)]).readonly(),yc=n().min(1).max(64),ye=n().datetime({offset:!0}),mg=r({id:n().uuid().optional(),clientId:pn,name:n().trim().min(1).max(96),scope:gc,contextKey:n().trim().min(1).max(240).optional().nullable(),contextLabel:n().trim().min(1).max(120).optional().nullable(),params:p(bc).min(1).max(80),summary:p(yc).max(5).default([]),createdAt:ye.optional(),clientUpdatedAt:ye}).strict(),pg=r({id:n().uuid().optional(),clientId:pn,clientUpdatedAt:ye}).strict();r({clientId:pn,since:ye.optional().nullable(),upserts:p(mg).max(_o).default([]),deletes:p(pg).max(_o).default([])}).strict();const hg=r({id:n().uuid(),clientId:pn,name:n().min(1).max(96),scope:gc,contextKey:n().max(240).nullable(),contextLabel:n().max(120).nullable(),params:p(bc).min(1).max(80),summary:p(yc).max(5),createdAt:ye,updatedAt:ye,clientUpdatedAt:ye}),fg=r({id:n().uuid(),clientId:pn,deletedAt:ye,updatedAt:ye,clientUpdatedAt:ye});r({serverTime:ye,syncVersion:ye,presets:p(hg),deleted:p(fg)});const go=Ls,_g=f(["abandoned","hiatus"]),gg=r({current:u().int().min(0),total:u().int().min(1).nullable()}),bg=r({kind:f(["source-updated","chapter-count-changed"]),chapterDelta:u().int().positive().optional()}),yg=r({kind:_g,challenge:bg.optional()}),vg=r({hasNotes:x(),tagCount:u().int().min(0),notePreview:n().max(180).optional(),tags:p(n().min(1).max(100)).max(5).optional()}),ai=r({hidden:x()}),Sg=r({browsePreference:ai}),xg=r({status:go,chapters:gg.optional(),readerStatus:go.optional(),canonicalReaderStatus:Se.optional(),entryId:n().uuid().optional(),browsePreference:ai.optional(),workMark:yg.optional(),workStatus:Mt.optional(),workStatusProvenance:Ft.optional(),catchupState:dn.optional(),newChapterCount:u().int().min(0).optional(),rating:u().int().min(0).max(5).optional(),privateContext:vg.optional()});r({entries:ot(n(),xg),workPreferences:ot(n(),Sg).optional(),syncVersion:n()});const Eg=r({key:n().regex(/^(ao3|ffn):[0-9]+$/,{message:"Expected a canonical AO3/FFN work key"}),hidden:x()}).strict();r({key:Eg.shape.key,browsePreference:ai});const wg=f(["finished_unknown_work_state","progress_looks_complete","stalled_reading","long_paused","planning_never_started","completed_unrated","completed_no_notes","abandoned_has_updates","unknown_work_state"]),Ag=r({fingerprint:n().trim().min(1).max(500)}),Rg=r({fingerprint:n().trim().min(1).max(500),days:H().int().min(1).max(90).default(7)}),ri=r({device_token:n().trim().min(32).max(200),environment:f(["sandbox","production"]),app_bundle_id:n().trim().min(1).max(200).optional()}),Tg=ri.extend({include_registration_id:x().optional(),registration_operation_id:n().uuid().optional()}).superRefine((e,t)=>
2{e.include_registration_id===!0&&!e.registration_operation_id&&t.addIssue({code:"custom",path:["registration_operation_id"],message:"Registration operation ID is required for a receipt"}),e.registration_operation_id&&e.include_registration_id!==!0&&t.addIssue({code:"custom",path:["include_registration_id"],message:"Registration operations require a receipt response"})});ri.extend({registration_id:n().uuid()});ri.extend({registration_operation_id:n().uuid()}).strict();const kg=r({push_suggestions_enabled:x()}),ii=r({ok:_(!0)}).strict(),Cg=ii,Ng=ii,Ig=ii,Og=r({ok:_(!0),registration_id:n().uuid(),registration_operation_id:n().uuid(),registration_state:f(["current","superseded"])}).strict();V([Og.extend({registration_state:_("current")}),r({ok:_(!0),registration_state:_("unavailable")}).strict()]);const Pg=r({ok:_(!0),push_suggestions_enabled:x()}).strict(),bo=r({kind:wg,fingerprint:n(),entry_id:n().uuid(),story_id:u().int().positive(),source:n().optional(),title:n().nullable(),author:n().nullable(),status:n(),progress_unit:n(),progress_value:u().int(),progress_total:u().int().nullable(),work_status:Mt,work_status_provenance:Ft,catchup_state:dn,chapters_published:u().int().min(0).nullable(),chapters_planned:u().int().min(0).nullable(),new_chapter_count:u().int().min(0),rating:u().int(),tags:p(n()).default([]),notes_empty:x(),last_read_at:n().nullable(),updated_at:n(),priority:u().int()}),Lg=r({week_key:n(),push_suggestions_enabled:x(),suggestions:p(bo),work_state_backlog:p(bo)}),Dg="v1",jg=f(["ao3_story","ao3_listing","ao3_bookmark","ffn_story_desktop","ffn_story_mobile","ffn_listing_desktop","ffn_listing_mobile"]),Ug=f(["src","ctx","u","chu","t","a","sm","w","chn","cht","chPub","l","upd","pub","r","s","cmp","gen","k","h","bk","cc","rev","fav","fol","fms","chars","rels","ra","tags","wrn","cat","ser"]),st=e=>n().trim().max(e),ae=e=>V([st(e),pe()]),be=e=>V([u().int().min(0).max(e),pe()]),Ee=(e,t)=>p(st(t)).max(e),Mg=r({name:st(500),pos:V([u().int().min(0),pe()]),url:V([st(2048),pe()])}).strict(),Mn=r({src:_("ao3"),ctx:f(["story","listing","bookmark"]),u:st(2048),chu:ae(2048).optional(),t:st(300),a:ae(120),sm:ae(2e4),w:be(5e7),chn:be(1e7),cht:V([u().int().min(0).max(1e7),pe()]),chPub:be(1e7),l:ae(50),upd:ae(50),pub:ae(50),r:ae(50),s:ae(20),k:be(2e6),h:be(1e8),bk:be(1e6),cc:be(1e6),wrn:Ee(40,255),cat:Ee(20,60),ser:V([Mg,pe()]),fms:Ee(40,255),chars:Ee(120,255),rels:Ee(120,255),ra:Ee(120,255),tags:Ee(300,500)}).strict(),Kt=r({src:_("ffn"),ctx:f(["story","listing"]),u:st(2048),t:st(300),a:ae(120),sm:ae(2e4),w:be(5e7),chn:be(1e7),cht:V([u().int().min(0).max(1e7),pe()]),l:ae(50),upd:ae(50),pub:ae(50),r:ae(50),rev:be(5e5),fav:be(5e5),fol:be(5e5),gen:ae(100),cmp:ae(20),fms:Ee(40,255),chars:Ee(120,255),rels:Ee(120,255),ra:Ee(120,255)}).strict();Mn.extend({ctx:_("story")}),Mn.extend({ctx:_("listing")}),Mn.extend({ctx:_("bookmark")}),Kt.extend({ctx:_("story")}),Kt.extend({ctx:_("story")}),Kt.extend({ctx:_("listing")}),Kt.extend({ctx:_("listing")});const Fg=V([Mn,Kt]),Bg=Ug.options;function Hg(e){return new Set(e)}function _t(e){const t=Hg(e);return Bg.filter(a=>!t.has(a))}const Ua=["src","ctx","u","chu","t","a","sm","w","chn","cht","chPub","l","upd","pub","r","s","k","h","bk","cc","fms","chars","rels","ra","tags","wrn","cat","ser"],Cn=["src","ctx","u","t","a","sm","w","chn","cht","l","upd","pub","r","rev","fav","fol","gen","cmp","fms","chars","rels","ra"];_t(Ua),_t(Ua),_t(Ua),_t(Cn),_t(Cn),_t(Cn),_t(Cn);r({version:_(Dg),page_type:jg,item:Fg}).strict();const Vg=1,Wg="tag-compass-rating-association.v0",vc=n().min(1).max(600).refine(e=>!/[\u0000-\u001f\u007f]/u.test(e),{message:"Tag Compass keys cannot contain control characters"}),oi=n().trim().min(1).max(500).refine(e=>!/[\u0000-\u001f\u007f]/u.test(e),{message:"Tag Compass labels cannot contain control characters"}),Sc=vc.refine(e=>e==="global"||e.startsWith("display:ao3:fandom:")&&e.length>19,{message:"Expected a Tag Compass scope key"}),$g=vc.refine(e=>e.startsWith("display:ao3:additional:")&&e.length>23,{message:"Expected an AO3 additional-tag display key"});r({scope:Sc.default("global")}
2).strict();const Yg=f(["ready","not_enough_ratings","no_usable_ao3_tags","no_clear_patterns"]),Gg=f(["global","fandom"]),xc=r({key:Sc,label:oi.max(255)}).strict(),Ec=xc.extend({kind:Gg,eligibleRatedStories:u().int().min(0)}).strict(),zg=Ec.extend({baselineRating:u().min(1).max(5).nullable()}).strict(),qg=f(["more","less"]),Kg=f(["emerging","supported","well_supported"]),yo=r({title:oi.max(300),rating:u().int().min(1).max(5)}).strict(),Qg=r({ratedStories:u().int().positive(),highRated:u().int().min(0),neutralRated:u().int().min(0),lowRated:u().int().min(0),tagAverage:u().min(1).max(5),scopeAverage:u().min(1).max(5),starDelta:u().min(-4).max(4),highRatedStories:p(yo).max(3),lowRatedStories:p(yo).max(3)}).strict(),vo=r({key:$g,label:oi,identityQuality:_("display_only"),direction:qg,score:u().int().min(-100).max(100),scope:xc,sampleStrength:Kg,evidence:Qg}).strict().superRefine((e,t)=>{e.direction==="more"&&e.score<=0&&t.addIssue({code:"custom",path:["score"],message:"More-like results require a positive score"}),e.direction==="less"&&e.score>=0&&t.addIssue({code:"custom",path:["score"],message:"Less-like results require a negative score"}),e.evidence.highRated+e.evidence.neutralRated+e.evidence.lowRated!==e.evidence.ratedStories&&t.addIssue({code:"custom",path:["evidence","ratedStories"],message:"Tag Compass evidence rating counts must add up"})});r({schemaVersion:_(Vg),modelVersion:_(Wg),availability:Yg,scope:zg,availableScopes:p(Ec),more:p(vo).max(12),less:p(vo).max(12)}).strict().superRefine((e,t)=>{e.availability==="ready"&&!e.more.length&&!e.less.length&&t.addIssue({code:"custom",path:["availability"],message:"Ready Tag Compass responses require at least one result"}),e.availability!=="ready"&&(e.more.length||e.less.length)&&t.addIssue({code:"custom",path:["availability"],message:"Unavailable Tag Compass responses cannot contain results"}),e.availableScopes.some(a=>a.key===e.scope.key)||t.addIssue({code:"custom",path:["availableScopes"],message:"The selected Tag Compass scope must remain available"})});r({error:n().optional(),code:n().optional(),error_id:n().optional()}).loose();const Jg="native-stats-internal-read.v1",sn=f(["FANDOM","RELATIONSHIP","ARCHIVE_TAG","LENGTH"]),Xg=f(["ALL","SAVED","FINISHED"]),hn=n().regex(/^[a-f0-9]{64}$/),Jn=n().trim().min(1).max(240),wc=n().min(1).max(2048),we=u().int().nonnegative(),si={cursor:wc.optional(),limit:H().int().min(1).max(50).default(20),revision:hn.optional()},Ac={filterDimension:sn.optional(),filterValue:Jn.optional()},Rc=e=>!!e.filterDimension==!!e.filterValue;r({}).strict();r({...si,...Ac,dimension:sn.default("FANDOM")}).strict().refine(Rc,"filterDimension and filterValue are required together");r({...si,rereadsOnly:f(["true","false"]).default("false").transform(e=>e==="true")}).strict();r({...si,...Ac,revision:hn,scope:f(["LIBRARY_NOW","COMPLETION_PERIOD"]),dimension:sn.optional(),value:Jn.optional(),cohort:Xg.default("ALL"),month:n().regex(/^\d{4}-(0[1-9]|1[0-2])$/).optional(),undated:f(["true","false"]).default("false").transform(e=>e==="true"),entryId:Ce().optional(),rereadsOnly:f(["true","false"]).default("false").transform(e=>e==="true")}).strict().superRefine((e,t)=>{(!Rc(e)||!!e.dimension!=!!e.value)&&t.addIssue({code:"custom",message:"Dimension and value must be supplied together"}),e.scope==="LIBRARY_NOW"&&(e.month||e.undated||e.entryId||e.rereadsOnly)&&t.addIssue({code:"custom",message:"Completion selectors cannot enter Library scope"}),e.scope==="COMPLETION_PERIOD"&&(e.dimension||e.filterDimension||e.cohort!=="ALL"||e.month&&e.undated)&&t.addIssue({code:"custom",message:"Invalid completion scope selectors"})});const ci=r({total:we,limit:we,hasMore:x(),nextCursor:wc.nullable()}).strict(),ga={contractId:_(Jg),generatedAt:he()},Ma=r({total:we,known:we,missing:we}).strict(),Qt=r({completedReads:we,distinctStories:we}).strict(),So=p(r({name:n(),avgRating:u().min(1).max(5),ratedCount:u().int().min(2)}).strict()).max(8);r({data:r({...ga,entitlement:f(["FREE","UNLIMITED"]),playback:r({availability:_("UNAVAILABLE"),reason:_("AUTHORITATIVE_READING_HISTORY_UNAVAILABLE")}).strict(),webStatsPath:_("/stats"),freeRecapPath:_("/stats")}).strict()}).strict();r({data:r({...ga,scope:_("LIBRARY_NOW"),revision:hn,dimension:sn,filterDimension:sn.nullable(),filterValue:Jn.nullable(),attribution:f(["OVERLAPPING","EXCLUSIVE"]),populations:r({all:Ma,saved:Ma,finished:Ma}).strict(),averageRating:u().min(1).max(5).nullable().optional(),topRatedRelationships:So.optional(),topRatedTags:So.optional(),ratingDistribution:p(r({rating:u().int().min(1).max(5),count:we}).strict()).length(5).optional(),rows:p(r({value:Jn,allCount:we,savedCount:we,finishedCount:we}).strict()).max(50),page:ci}
2).strict()}).strict();r({data:r({...ga,scope:_("COMPLETION_PERIOD"),revision:hn,dateBasis:_("SUPPORTED_COMPLETION_DATES_MAY_INCLUDE_LEGACY_ESTIMATES"),rereadsOnly:x(),totals:r({all:Qt,dated:Qt,undated:Qt}).strict(),months:p(r({month:n().regex(/^\d{4}-\d{2}$/),...Qt.shape}).strict()).max(50),page:ci}).strict()}).strict();const Zg=r({entryId:Ce(),title:n().max(500),authors:p(n().max(240)).max(20),source:n().max(240).nullable(),currentStatus:f(["SAVED","READING","CAUGHT_UP","PAUSED","FINISHED","DROPPED"]),currentWordCount:u().int().nonnegative().nullable(),readNumber:u().int().positive().nullable(),completedOn:C().nullable()}).strict();r({data:r({...ga,scope:f(["LIBRARY_NOW","COMPLETION_PERIOD"]),revision:hn,rows:p(Zg).max(50),counts:Qt.nullable(),page:ci}).strict()}).strict();r({error:n(),code:f(["AUTH_SUB_MISSING","ACCOUNT_REQUIRED","ACCOUNT_DELETED","PRO_REQUIRED","NATIVE_STATS_UNAVAILABLE","NATIVE_STATS_SCOPE_TOO_LARGE","NATIVE_STATS_CURSOR_INVALID","STATS_SNAPSHOT_CHANGED"])}).strict();const Tc=r({search:Ue.shape.search.default(""),sort:V([_("AUTHORED"),Ut]).default("AUTHORED"),filters:Ue.shape.filters.default({})}).strict();r({request_id:n().uuid(),query:Tc}).strict();r({request_id:n().uuid(),query:Tc,collection:De.extend({structure:De.shape.structure.unwrap(),revision:De.shape.revision.unwrap(),group_count:De.shape.group_count.unwrap(),items:De.shape.items.max(Re),groups:De.shape.groups.unwrap().max(on)}),ordered_entry_ids:p(n().uuid()).max(Re),match_count:u().int().min(0).max(Re)}).strict().superRefine((e,t)=>{const{collection:a,ordered_entry_ids:c}=e,m=new Set(a.items.map(b=>b.entry_id)),h=new Set(a.groups.map(b=>b.group_id)),d=new Map(a.groups.map(b=>[b.group_id,b.position])),v=a.items.map(b=>d.get(b.group_id??"")??-1),o=a.structure==="grouped"?h.size===0||v.some((b,g)=>b<0||g>0&&b<v[g-1]):(a.structure==="simple"||a.structure==="ranked")&&(h.size>0||a.items.some(b=>b.group_id!=null)),s=new Set(c),l=a.items.filter(b=>s.has(b.entry_id)).map(b=>b.entry_id);(m.size!==a.items.length||a.item_count!==m.size||c.length!==e.match_count||new Set(c).size!==c.length||c.some(b=>!m.has(b))||h.size!==a.groups.length||a.group_count!==h.size||a.items.some((b,g)=>b.position!==g||b.entry_id!==b.entry.entry_id||b.group_id!=null&&!h.has(b.group_id))||a.groups.some((b,g)=>b.position!==g)||o||e.query.sort==="AUTHORED"&&c.some((b,g)=>b!==l[g]))&&t.addIssue({code:"custom",message:"Collection query must contain one complete, consistent aggregate"})});const xo=n().trim().min(1).max(500),Eo=r({rating:u().int().min(0).max(5).optional(),notes:n().max(2e4).optional(),tags:p(n().trim().min(1).max(255)).max(200).optional()}).strict();lt("action",[r({operationId:n().uuid(),action:_("RESOLVE_WORK_STATUS"),fingerprint:xo,workStatus:f(["complete","abandoned","hiatus","wip"]),expected:Un,expectedChaptersPublished:u().int().min(0).max(1e7).nullable(),expectedSuggestionUpdatedAt:n().datetime({offset:!0})}).strict(),r({operationId:n().uuid(),action:_("SAVE_REFLECTION"),fingerprint:xo,changes:Eo,expected:Eo}).strict(),r({operationId:n().uuid(),action:_("UNDO"),undoOfOperationId:n().uuid()}).strict()]).superRefine((e,t)=>{if(e.action!=="SAVE_REFLECTION")return;const a=Object.keys(e.changes).sort();(!a.length||a.join()!==Object.keys(e.expected).sort().join())&&t.addIssue({code:"custom",path:["expected"],message:"Provide the exact baseline for each changed reflection field"})});r({data:r({operation_id:n().uuid(),entry_id:n().uuid(),action:f(["RESOLVE_WORK_STATUS","SAVE_REFLECTION","UNDO"]),replayed:x(),undo_available:x(),undo_expires_at:n().datetime({offset:!0}).nullable(),undo_of_operation_id:n().uuid().optional()}).strict()}).strict();const eb=r({deletion_operation_id:n().uuid(),recovery_secret:n().regex(/^[0-9a-f]{64}$/)}).strict();V([eb,r({}).strict()]).optional();r({deletion_operation_id:n().uuid(),status:f(["local_erased","unresolved"])}).strict();const tb="native-library-activity.v1",nb="native-reading-coverage.v1",kc="native-stats-reading-history.v1",xt=n().regex(/^[a-f0-9]{64}$/),ba=n().min(1).max(2048),P=u().int().nonnegative(),Pt=f(["SAVED","READING","CAUGHT_UP","PAUSED","FINISHED","DROPPED"]),Fa=r({unit:f(["CHAPTER","WORD","PERCENT"]),value:P,total:P.nullable()}).strict(),Cc=n().trim().min(1).max(100).refine(e=>{try{return new Intl.DateTimeFormat("en",{timeZone:e}).format(),!0}catch{return!1}},"Expected an IANA timezone"),je=r({view:f(["DATED","UNDATED_COMPLETIONS"]).default("DATED"),from:C().optional(),to:C().optional(),timeZone:Cc,limit:H().int().min(1).max(50).default(20),cursor:ba.optional(),revision:xt.optional()}).strict().superRefine((e,t)=>
2{if(e.view==="UNDATED_COMPLETIONS")(e.from||e.to)&&t.addIssue({code:"custom",message:"Undated completions have no date range"});else if(!e.from||!e.to)t.addIssue({code:"custom",message:"Dated activity requires from and to"});else{const a=(Date.parse(e.to)-Date.parse(e.from))/864e5+1;(a<1||a>366)&&t.addIssue({code:"custom",message:"Select an inclusive range of 1–366 days"})}}),ab=lt("kind",[r({kind:_("ADDED"),initialStatus:Pt,initialProgress:Fa}).strict(),r({kind:_("STATUS_CHANGED"),before:Pt,after:Pt}).strict(),r({kind:_("PROGRESS_CHANGED"),before:Fa,after:Fa}).strict(),r({kind:_("COMPLETED_READ"),readNumber:u().int().positive()}).strict()]),Nc=r({id:xt,entryId:Ce(),currentStory:r({title:n().max(500),authors:p(n().max(240)).max(20),source:n().max(240).nullable(),status:Pt}).strict(),day:C().nullable(),recordedAt:he().nullable(),dateBasis:f(["SERVER_RECORDED_CHANGE","SUPPORTED_COMPLETION_DATE_MAY_INCLUDE_LEGACY_ESTIMATE","UNDATED_COMPLETION"]),change:ab}).strict().superRefine((e,t)=>{(e.change.kind==="COMPLETED_READ"?e.recordedAt!==null||e.dateBasis!==(e.day?"SUPPORTED_COMPLETION_DATE_MAY_INCLUDE_LEGACY_ESTIMATE":"UNDATED_COMPLETION"):!e.day||!e.recordedAt||e.dateBasis!=="SERVER_RECORDED_CHANGE")&&t.addIssue({code:"custom",message:"Activity date basis does not match its evidence"})});r({data:r({contractId:_(tb),generatedAt:he(),revision:xt,scope:_("RECORDED_LIBRARY_ACTIVITY"),view:f(["DATED","UNDATED_COMPLETIONS"]),range:r({from:C().nullable(),to:C().nullable(),timeZone:Cc}).strict(),history:r({completeness:_("RETAINED_CHANGES_ONLY"),changeRetentionMonths:_(12),ordering:_("DAY_THEN_RECORDED_TIME_NOT_ENCOUNTER_ORDER")}).strict(),rows:p(Nc).max(50),page:r({total:P,limit:P,hasMore:x(),nextCursor:ba.nullable(),continuesPreviousDay:x(),continuesNextDay:x()}).strict()}).strict()}).strict();r({}).strict();r({data:r({contractId:_(nb),generatedAt:he(),revision:xt,scope:_("HISTORY_COVERAGE"),coverage:r({state:f(["UNAVAILABLE","PARTIAL","UNVERIFIED"]),reason:f(["NO_AUTHORITATIVE_HISTORY","RECORDING_NOT_REQUIRED","AUTHORITY_GAP","HISTORY_REMOVED","INCOMPLETE_CALENDAR","CONTINUITY_NOT_VERIFIED"]),authoritativeStartDay:C().nullable(),calendarCoverage:f(["NONE","PARTIAL","FULL"]),hasObservedEvidence:x()}).strict(),playback:r({availability:_("UNAVAILABLE"),eligibleOn:pe(),daysUntilEligible:pe()}).strict()}).strict()}).strict();const Xn=f(["FANDOM","RELATIONSHIP","ARCHIVE_TAG"]);r({}).strict();r({revision:xt,scope:f(["WINDOW","SUPPORTED_HISTORY"]).default("WINDOW"),sampleId:C(),dimension:Xn,value:n().trim().min(1).max(240).optional(),selector:n().min(20).max(128),limit:H().int().min(1).max(50).default(20),cursor:ba.optional()}).strict();const Ic=r({chapters:P,words:P,percentagePoints:P}).strict(),Oc=r({exact:P,estimated:P,estimatedEventCount:P,total:P,unavailableEventCount:P,estimationMethod:_("reading-word-estimate.v1")}).strict().refine(e=>e.total===e.exact+e.estimated,"Word contribution total must equal exact plus estimated"),ya=r({eventCount:P,storyCount:P,readingDayCount:P,nativeTotals:Ic,wordContribution:Oc}).strict().refine(e=>e.wordContribution.estimatedEventCount+e.wordContribution.unavailableEventCount<=e.eventCount,"Estimated and unavailable provenance counts cannot exceed the aggregate event count"),rb=r({value:n().trim().min(1).max(240),rank:u().int().positive(),volume:P,eventCount:P,storyCount:P,readingDayCount:P,nativeTotals:Ic,wordContribution:Oc,selector:n().min(20).max(128)}).strict(),ib=r({value:n().trim().min(1).max(240),volume:P}).strict(),ob=r({value:n().trim().min(1).max(240),totalVolume:P,points:p(P).max(50)}).strict(),sb=r({id:C(),fromDay:C(),toDay:C(),metric:f(["WORDS","READING_CHANGES"]),approximate:x(),aggregate:ya,knownEventCount:P,missingEventCount:P,selector:n().min(20).max(128),values:p(rb).max(5),transitionValues:p(ib).max(15)}).strict().refine(e=>e.knownEventCount+e.missingEventCount===e.aggregate.eventCount,"Taxonomy denominator must equal the selected event count"),cb=r({range:r({fromDay:C(),throughDay:C(),windowDays:_(30),sampleStepDays:_(7),truncatedBefore:x()}).strict(),metric:f(["WORDS","READING_CHANGES"]),total:ya,dimensions:p(r({dimension:Xn,attribution:_("OVERLAPPING"),series:p(ob).max(4),samples:p(sb).max(50)}).strict()).length(3),evidence:r({scope:_("SUPPORTED_HISTORY"),sampleId:C(),fromDay:C(),toDay:C(),dimension:Xn,value:pe(),selector:n().min(20).max(128)}).strict()}).strict().superRefine((e,t)=>
2{e.dimensions.some(a=>a.samples.some(c=>c.metric!==e.metric))&&t.addIssue({code:"custom",message:"Every sample must use the history metric"})}),lb=r({state:f(["UNAVAILABLE","PARTIAL","SO_FAR","ELIGIBLE"]),reason:f(["NO_AUTHORITATIVE_HISTORY","RECORDING_NOT_REQUIRED","AUTHORITY_GAP","HISTORY_REMOVED","INCOMPLETE_CALENDAR","CONTINUITY_NOT_ATTESTED","BUILDING_HISTORY","READY"]),authoritativeStartDay:C().nullable(),supportedFromDay:C().nullable(),supportedThroughDay:C().nullable(),coveredDays:P.nullable(),eligibleOn:C().nullable(),daysUntilEligible:P.nullable(),calendarCoverage:f(["NONE","PARTIAL","FULL"]),hasObservedEvidence:x()}).strict();r({data:r({contractId:_(kc),generatedAt:he(),scope:_("READING_PLAYBACK"),revision:xt,coverage:lb,history:cb.nullable()}).strict().superRefine((e,t)=>{const a=e.coverage.state==="SO_FAR"||e.coverage.state==="ELIGIBLE";a!==(e.history!==null)&&t.addIssue({code:"custom",message:"Only substantiated coverage may carry history"}),a&&(e.coverage.coveredDays===null||e.coverage.authoritativeStartDay===null||e.coverage.supportedFromDay===null||e.coverage.supportedThroughDay===null||e.coverage.eligibleOn===null||e.coverage.daysUntilEligible===null)&&t.addIssue({code:"custom",message:"Available history requires complete coverage facts"})})}).strict();const db=r({id:n().regex(/^[A-Za-z0-9_-]{43}$/),entryId:Ce(),currentStory:r({title:n().max(500),authors:p(n().max(240)).max(20),source:n().max(240).nullable(),status:Pt}).strict(),day:C(),unit:f(["CHAPTER","WORD","PERCENT"]),fromValue:P,toValue:u().int().positive(),observedTotal:P.nullable(),wordContribution:P.nullable(),wordTruth:f(["EXACT","ESTIMATED","UNAVAILABLE"]),estimationMethod:f(["EXACT_WORD_DELTA","CHAPTER_WORDS_PER_PUBLISHED_CHAPTER_V1","PERCENT_OF_EVENT_TIME_WORDS_V1","UNAVAILABLE"])}).strict().superRefine((e,t)=>{e.toValue<=e.fromValue&&t.addIssue({code:"custom",message:"Evidence movement must be positive"}),e.wordContribution===null!=(e.wordTruth==="UNAVAILABLE")&&t.addIssue({code:"custom",message:"Unavailable word truth must retain a null contribution"})}),ub=r({title:n().max(500),authors:p(n().max(240)).max(20),source:n().max(240).nullable(),status:Pt}).strict(),wo=r({day:C(),unit:f(["CHAPTER","WORD","PERCENT"]),fromValue:P,toValue:u().int().positive(),observedTotal:P.nullable()}).strict().refine(e=>e.toValue>e.fromValue,"Story position movement must be positive"),mb=r({rank:u().int().min(1).max(4),entryId:Ce(),currentStory:ub,aggregate:ya,first:wo,last:wo}).strict();r({data:r({contractId:_(kc),generatedAt:he(),scope:_("READING_PLAYBACK_EVIDENCE"),revision:xt,selection:r({scope:f(["WINDOW","SUPPORTED_HISTORY"]),sampleId:C(),fromDay:C(),toDay:C(),dimension:Xn,value:n().trim().min(1).max(240).nullable(),selector:n().min(20).max(128)}).strict(),aggregate:ya,topStories:p(mb).max(4),rows:p(db).max(50),page:r({total:P,limit:P,hasMore:x(),nextCursor:ba.nullable()}).strict()}).strict()}).strict();r({error:n(),code:f(["AUTH_SUB_MISSING","ACCOUNT_REQUIRED","ACCOUNT_DELETED","PRO_REQUIRED","NATIVE_READING_UNAVAILABLE","NATIVE_READING_SCOPE_TOO_LARGE","NATIVE_READING_CURSOR_INVALID","NATIVE_READING_SNAPSHOT_CHANGED"])}).strict();const li="native-library-overview.v1",pb="recorded-progress-runs.v1",de=n().regex(/^[a-f0-9]{64}$/),ct=n().min(1).max(2048),lr=u().int().nonnegative(),vt=u().int().positive(),va={view:je.shape.view,from:je.shape.from,to:je.shape.to,timeZone:je.shape.timeZone};function Pc(e,t){je.safeParse({view:e.view,from:e.from,to:e.to,timeZone:e.timeZone}).success||t.addIssue({code:"custom",message:"Select 1–366 dated days or a separate undated completion scope"})}r({...va,limit:H().int().min(1).max(50).default(20),cursor:ct.optional(),sequenceRevision:de.optional(),anchorOccurrenceId:de.optional(),fallbackDay:C().optional()}).strict().superRefine((e,t)=>{Pc(e,t),e.cursor&&(e.anchorOccurrenceId||e.fallbackDay)&&t.addIssue({code:"custom",message:"Anchors require a fresh read"}),e.fallbackDay&&(e.view!=="DATED"||e.fallbackDay<e.from||e.fallbackDay>e.to)&&t.addIssue({code:"custom",message:"Fallback day must belong to the selected dated range"})});r({...va,sequenceRevision:de,selectionToken:ct,limit:H().int().min(1).max(50).default(20),cursor:ct.optional()}).strict().superRefine(Pc);r({entryIds:p(Ce().transform(e=>e.toLowerCase())).min(1).max(50).refine(e=>new Set(e).size===e.length,"Entry IDs must be unique")}
2).strict();const Ye=Nc.shape,hb=r({id:Ye.id,entryId:Ye.entryId,day:Ye.day,groupId:de.optional(),recordedAt:Ye.recordedAt,dateBasis:Ye.dateBasis,change:Ye.change,order:r({kind:f(["TIMESTAMP","TIMESTAMP_TIE","DATE_ONLY","UNDATED"]),tieCount:vt}).strict()}).strict(),fb=Ye.currentStory.extend({fandoms:p(n().trim().min(1).max(255)).max(40).nullable(),workTags:p(n().trim().min(1).max(500)).max(300).nullable(),relationships:p(n().trim().min(1).max(255)).max(120).nullable(),characters:p(n().trim().min(1).max(255)).max(120).nullable(),words:u().int().min(0).max(1e8).nullable()}).strict(),Lc=r({entryId:Ce(),revision:de,readAt:he(),story:fb}).strict(),Ao=f(["SCOPE_EDGE","TIMESTAMP_TIE","DIFFERENT_ENTRY","DIFFERENT_KIND","DIFFERENT_DAY","UNIT_OR_TOTAL_CHANGED","NOT_FORWARD","DISCONTINUOUS","SINGLE_DATE","SEPARATE_OCCURRENCE"]),_b=r({id:de,kind:f(["OCCURRENCE","PROGRESS_RUN","ADDITIONS"]),occurrenceCount:vt,entryCount:vt,representedDates:p(C()).max(366),progress:r({olderOccurrenceId:de,newerOccurrenceId:de,before:Ye.change.options[2].shape.before,after:Ye.change.options[2].shape.after}).strict().nullable(),newerBoundary:Ao,olderBoundary:Ao,membershipToken:ct}).strict(),gb=r({id:de,day:C(),occurrenceCount:vt,entryCount:vt,membershipToken:ct}).strict(),bb=r({from:C().nullable(),to:C().nullable(),timeZone:n()}).strict(),yb=r({changeRetentionFrom:he(),changeRetentionFromDay:C(),oldestRecordedActivityDay:C().nullable()}).strict(),vb="native-recent-month-index.v1";r({timeZone:va.timeZone,beforeDay:C().optional()}).strict();r({data:r({contractId:_(vb),generatedAt:he(),timeZone:va.timeZone,months:p(n().regex(/^\d{4}-(0[1-9]|1[0-2])$/)).max(1200),beforeDay:C().nullable(),nearestOlderActivityDay:C().nullable(),hasUndatedCompletions:x()}).strict()}).strict();r({data:r({contractId:_(li),policyId:_(pb),identityPolicy:_("ACTIVITY_V1_HMAC_KEY_BOUND"),generatedAt:he(),sequenceRevision:de,contextRevision:de,view:f(["DATED","UNDATED_COMPLETIONS"]),range:bb,history:r({completeness:_("RETAINED_CHANGES_ONLY"),changeRetentionMonths:_(12),edges:yb.optional(),meaning:_("RECORDED_PROGRESS_NOT_VISITS_OR_SESSIONS"),ordering:_("DAY_THEN_RECORDED_TIME_NOT_ENCOUNTER_ORDER"),scopeEdges:_("OUTSIDE_SCOPE_NOT_EXAMINED")}).strict(),fragments:p(r({unit:_b,offset:lr,continuesPrevious:x(),continuesNext:x(),occurrences:p(hb).min(1).max(50)}).strict()).max(50),days:p(gb).max(50),contexts:p(Lc).max(50),anchor:r({outcome:f(["EXACT_OCCURRENCE","SAME_DAY","OLDER_DAY","START","EMPTY","PAGE"]),occurrenceId:de.nullable(),day:C().nullable()}).strict(),page:r({totalOccurrences:lr,limit:vt.max(50),hasMore:x(),nextCursor:ct.nullable(),previousCursor:ct.nullable()}).strict()}).strict()}).strict().superRefine((e,t)=>{e.data.fragments.reduce((a,c)=>a+c.occurrences.length,0)>e.data.page.limit&&t.addIssue({code:"custom",message:"Evidence page exceeds its limit"})});r({data:r({contractId:_(li),generatedAt:he(),sequenceRevision:de,selection:r({kind:f(["UNIT","DAY"]),id:de}).strict(),ordering:_("FIRST_REPRESENTED_OCCURRENCE_NOT_RANK"),entryIds:p(Ce()).max(50),page:r({totalEntries:lr,limit:vt.max(50),hasMore:x(),nextCursor:ct.nullable()}).strict()}).strict()}).strict();r({data:r({contractId:_(li),generatedAt:he(),contexts:p(Lc).max(50),absentEntryIds:p(Ce()).max(50)}).strict()}).strict();const Sb=r({authors:x(),characters:x(),fandoms:x(),relationships:x(),warnings:x(),categories:x(),work_tags:x()}),xb="native-library-overview-browse.v1",Fn=n().regex(/^[a-f0-9]{64}$/),dr=n().min(1).max(2048),Ba=u().int().min(0).max(2e4),Dc=r({view:je.shape.view,from:je.shape.from,to:je.shape.to,timeZone:je.shape.timeZone}).strict().superRefine((e,t)=>{je.safeParse(e).success||t.addIssue({code:"custom",message:"Select 1–366 dated days or a separate undated completion scope"})}),jc=r({search:Ue.shape.search.default(""),sort:Ue.shape.sort.default("LAST_READ_DESC"),filters:Ue.shape.filters.default({})}).strict();r({requestId:Ce(),scope:Dc,sequenceRevision:Fn,selectionToken:dr,query:jc,limit:u().int().min(1).max(50).default(20),cursor:dr.optional()}).strict();const Eb=en.extend({story:en.shape.story.extend({taxonomy_known:Sb,rating_bucket:oa.nullable()}),entry:en.shape.entry.extend({has_notes:x()})});r({data:r({contractId:_(xb),generatedAt:he(),requestId:Ce(),scope:Dc,sequenceRevision:Fn,selection:r({kind:f(["UNIT","DAY"]),id:Fn,totalEntries:Ba.min(1)}).strict(),query:jc,queryRevision:Fn,items:p(Eb).max(50),page:r({limit:u().int().min(1).max(50),offset:Ba,totalMatches:Ba,hasMore:x(),nextCursor:dr.nullable()}).strict()}).strict()}).strict().superRefine(({data:e},t)=>{const{items:a,page:c}=e,m=c.offset+a.length;(c.totalMatches>e.selection.totalEntries||m>c.totalMatches||a.length>c.limit||a.length!==Math.min(c.limit,c.totalMatches-c.offset)||new Set(a.map(h=>h.entry.entry_id)).size!==a.length||c.hasMore!==m<c.totalMatches||c.hasMore!==(c.nextCursor!==null))&&t.addIssue({code:"custom",message:"Browse page must contain one consistent selection query"})});const wb=f(["library","landing","setup","apps","signup","onboarding","extension_setup","import","open_trace","shared_collection","other"]);
2r({platform:f(["ios","android","desktop"]),path:f(["iphone_app","android_firefox","android_switch_firefox","desktop"]),route:wb,event:f(["path_shown","app_store_clicked","open_app_clicked","firefox_clicked","addon_clicked"])}).strict().refine(e=>e.platform==="ios"?e.path==="iphone_app"&&["path_shown","app_store_clicked","open_app_clicked"].includes(e.event):e.platform==="android"?e.path.startsWith("android_")&&["path_shown","firefox_clicked","addon_clicked"].includes(e.event):e.path==="desktop"&&e.event==="path_shown","Event must match the displayed platform path");const Ab=r({platform:n(),path:n(),route:n(),event:n(),count:u().nonnegative()}).strict(),Ro=r({requests:u().int().nonnegative(),errors:u().int().nonnegative(),aborted:u().int().nonnegative(),p95Ms:u().nonnegative().nullable(),errorRatePercent:u().min(0).max(100).nullable()}).strict(),Rb=r({generatedAt:n().datetime(),currentFrom:n().datetime(),previousFrom:n().datetime(),currentCoverageMinutes:u().int().min(0).max(1440),previousCoverageMinutes:u().int().min(0).max(1440),dropped:u().int().nonnegative(),routes:p(r({route:n(),current:Ro,previous:Ro,comparable:x(),latencyRegression:x(),errorRegression:x(),errorBreach:x()}).strict())}).strict(),Uc=f(["7d","30d","90d","12m","all"]),ur=f(["all","ios_native","ios_shell","web_desktop","web_mobile","unknown"]);r({range:Uc.default("30d"),platform:ur.default("all")}).strict();const N=u().nonnegative(),tn=u().nullable(),Gt=r({key:n(),label:n(),value:tn,previous:tn,unit:f(["count","percent","usd","decimal"]),note:n(),sparkline:p(r({date:n(),value:tn}).strict()).optional()}).strict(),Tb=r({date:n(),value:N,previous:N.nullable()}).strict(),kb=r({key:n(),label:n(),count:N,previous:N.nullable(),share:N,trend:p(Tb)}).strict(),Cb=r({key:n(),label:n(),count:N,eligible:N,conversion:tn,previous:N.nullable().optional(),previousConversion:tn.optional(),unknown:N,unsupported:N,failed:N,unattributed:N,immature:N}).strict(),Nb=r({generatedAt:n().datetime(),range:Uc,platform:ur,from:n().datetime(),to:n().datetime(),previousFrom:n().datetime().nullable(),bucket:f(["day","week","month"]),headlines:p(Gt),routeHealth:Rb.nullable().optional(),secondary:p(Gt).optional(),growth:p(r({date:n(),total:N,previousTotal:N.nullable(),signups:N,ios_native:N,ios_shell:N,web_desktop:N,web_mobile:N,unknown:N}).strict()).optional(),annotations:p(r({date:n(),label:n()}).strict()).optional(),attention:p(r({key:n(),label:n(),detail:n(),severity:f(["warning","info"])}).strict()).optional(),revenue:p(Gt),engagement:p(Gt),series:p(r({date:n(),previousDate:n().nullable(),signups:N,previousSignups:N.nullable(),active:N,previousActive:N.nullable(),saves:N,previousSaves:N.nullable()}).strict()),mix:p(r({key:n(),label:n(),note:n(),rows:p(kb)}).strict()),deviceSetupHandoffs:p(Ab).optional(),funnels:p(r({key:n(),label:n(),platform:ur,note:n(),steps:p(Cb)}).strict()),reliability:r({metrics:p(Gt),reasons:p(r({kind:n(),reason:n(),version:n(),count:N,last24h:N,previous:N.nullable()}).strict()),note:n()}).strict(),tools:r({aliases:N,feedback:N,moderation:N,domains:N,manualPro:N}).strict(),coverage:p(r({metric:n(),reason:n()}).strict())}).strict(),Ib=r({data:Nb.nullable(),status:f(["ready","stale","pending"])}).strict(),Et="trace-story-updates.v2",Mc=5e3;function Ae(e){return n().transform(t=>e.includes(t)?t:"unknown")}const Ob=Ae(["verification_authentication_failed","verification_message_unrecognized","ao3_message_requires_review","non_ao3_mail_received","mail_to_retired_address"]),Fc=Ae(["gmail","icloud","outlook"]),Bc=["address","computer_handoff","add_address","verification","filter","confirmation","waiting","complete"],Hc=["verification_completed","ao3_filter_created","whole_mailbox_forwarding_disabled"],Pb=r({provider:Fc,step:Ae(Bc),confirmed:p(Ae(Hc)),revision:u().int().nonnegative()});r({route_id:n().uuid(),revision:u().int().nonnegative(),provider:_("gmail"),step:f(Bc),confirmed:p(f(Hc)).max(3).refine(e=>new Set(e).size===e.length,"Duplicate confirmation")}).strict();const Vc=V([n().datetime(),_("indefinite")]).nullable(),di=Gr.extend({sound_enabled:x(),notifications_paused_until:Vc}).strip();r({notifications_enabled:x().optional(),title_previews_enabled:x().optional(),sound_enabled:x().optional(),notifications_paused_until:Vc.optional()}).strict().refine(e=>Object.keys(e).length>0,"At least one preference is required");r({contract_version:_(Et),preferences:di});const Wc=Lt.shape.methods.shape.forwarding.extend({route_id:n().uuid().nullable(),provider:Fc.nullable(),setup_progress:Pb.nullable(),address_state:Ae(["not_created","available","rotation_required"]),setup_state:Ae(["not_configured","verification_required","waiting_for_first_ao3","active","needs_attention"]),attention_reason:Ob.nullable(),attention_since:n().datetime().nullable(),first_delivery_at:n().datetime().nullable(),first_library_delivery_at:n().datetime().nullable()}).strip();Lt.extend({contract_version:_(Et),methods:r({forwarding:Wc,gmail:Lt.shape.methods.shape.gmail.extend({state:Ae(["not_connected","healthy","error"])}).strip()}),preferences:di,recent_update_count:u().int().nonnegative(),setup_poll_interval_ms:_(Mc)}).strip();r({contract_version:_(Et),address:n().email().nullable(),setup_status:Wc,setup_verification:uo.shape.setup_verification.extend({state:Ae(["not_received","received"])}).strip(),delivery_check:uo.shape.delivery_check.extend({code:Ae(["not_configured","rotation_required","wrong_address","no_mail_yet","received"]),possible_causes:p(Ae(["wrong_address","provider_filtering"])),provider_filtering:Ae(["not_observable"])}).strip(),preferences:di,setup_poll_interval_ms:_(Mc)});Fs.extend({route_id:n().uuid(),provider:_("gmail")}
2).strict();r({contract_version:f(["trace-story-updates.v1",Et]).optional()}).strict();r({purpose:f(["setup","disconnect"]).default("setup")}).strict();r({contract_version:_(Et),sent:_(!0)});r({trace:r({path:_("/watches/setup"),destination:r({contract_version:_(Et),type:_("setup_status"),account_id:n().min(1).max(512),route_id:n().uuid(),target:r({kind:_("setup_status")}).strict(),first_received_at:n().datetime()}).strict()}).strict()}).strict();r({trace:r({path:_("/watches/setup"),destination:r({contract_version:_(Et),type:_("attention"),account_id:n().min(1).max(512),route_id:n().uuid(),target:r({kind:_("attention")}).strict(),incident_id:n().uuid(),attention_reason:f(["non_ao3_mail_received","mail_to_retired_address"]),attention_since:n().datetime()}).strict()}).strict()}).strict();const Lb="READING_ACTIVITY_CLOCK_AHEAD",Db=3e5;function $c(e=globalThis.crypto){if(typeof e?.randomUUID=="function")return e.randomUUID();const t=new Uint8Array(16);if(typeof e?.getRandomValues=="function")e.getRandomValues(t);else for(let c=0;c<t.length;c+=1)t[c]=Math.floor(Math.random()*256);t[6]=t[6]&15|64,t[8]=t[8]&63|128;const a=Array.from(t,c=>c.toString(16).padStart(2,"0")).join("");return`${a.slice(0,8)}-${a.slice(8,12)}-${a.slice(12,16)}-${a.slice(16,20)}-${a.slice(20)}`}function Yc(e=new Date,t=$c()){const a=-e.getTimezoneOffset(),c=Math.abs(a),m=String(Math.floor(c/60)).padStart(2,"0"),h=String(c%60).padStart(2,"0");return{operationId:t,occurredAt:e.toISOString(),calendarDate:new Date(e.getTime()+a*6e4).toISOString().slice(0,10),timeZone:{kind:"OFFSET",value:`${a<0?"-":"+"}${m}:${h}`}}}function Ha(e){return e.readingActivity!==void 0||e.progress===void 0&&e.status===void 0&&e.completion===void 0?e:{...e,readingActivity:Yc()}}function jb(e){const t=e?.payload;if(!t||typeof t!="object")return null;const{code:a,server_time:c}=t;if(a!==Lb||typeof c!="string")return null;const m=new Date(c);return Number.isFinite(m.getTime())?m:null}function Va(e,t){const a=e.readingActivity,c=a?.occurredAt?Date.parse(a.occurredAt):Number.NaN;return!a||!(c>t.getTime()+Db)?e:{...e,readingActivity:Yc(new Date(t.getTime()),a.operationId??$c())}}const Lw=js;function mr(e){const{minRating:t,...a}=e.filters;return eh({...e,filters:{...a,minEntryRating:a.minEntryRating??t}})}function Ub(e){const t=new URLSearchParams(e.startsWith("?")?e.slice(1):e),a={};return t.forEach((c,m)=>{const h=a[m];if(h===void 0){a[m]=c;return}a[m]=Array.isArray(h)?[...h,c]:[h,c]}),a}function Dw(e){const t=mr({...e,page:1,limit:50}),a=lh(Ub(t));return{search:a.search,sort:a.sort,filters:a.filters}}const jw=e=>Ut.safeParse(e).success,Gc="localstorage",zc=!0,To=30,Mb=12;function qc(){const e=To;return Number.isFinite(e)&&e>0?e:To}function Kc(e){return!e}function Fb(e){return{auth_cache_location:Gc,auth_refresh_fallback:String(Kc(e)),auth_session_check_expiry_days:String(qc()),auth_use_refresh_tokens:String(zc)}}const pr="trace:authSessionRecoveryRequired",ui="trace:auth-session-recovery-pending-v1";let mi=!1;
2class Qc extends Error{constructor(){super("Auth session recovery is already in progress"),this.name="AuthSessionRecoveryPendingError"}}function Jc(){if(mi)return!0;try{return sessionStorage.getItem(ui)==="1"}catch{return!1}}function pi(){if(Jc())throw new Qc}function Bb(){if(Jc())return!1;mi=!0;try{sessionStorage.setItem(ui,"1")}catch{}return!0}function hr(){mi=!1;try{sessionStorage.removeItem(ui)}catch{}}const Hb=new Set(["consent_required","invalid_grant","invalid_refresh_token","invalid_token","login_required","missing_refresh_token"]),Vb=new Set(["AUTH_TOKEN_EXPIRED","AUTH_TOKEN_INVALID","AUTH_TOKEN_MISSING"]),Wb=new Set(["ACCOUNT_DELETED_STALE_TOKEN","AUTH_SUB_MISSING"]),$b=Date.now();function Xc(e){return typeof e=="object"&&e!==null}function Zn(e){if(!Xc(e))return null;for(const t of["error","errorCode","code"]){const a=e[t];if(typeof a=="string"&&a.length>0)return a}return null}function fr(e){if(!Xc(e))return null;const t=e.code;return typeof t=="string"&&t.length>0?t:null}function Yb(e){const t=Zn(e);return t&&Hb.has(t)?!0:e instanceof Error?/missing refresh token|invalid refresh token|login required/i.test(e.message):!1}function Gb(e){const t=fr(e);return!t||Vb.has(t)?!0:(Wb.has(t),!1)}function Wa(e){e.reason!=="account_deleted"&&!Bb()||window.dispatchEvent(new CustomEvent(pr,{detail:e}))}function zb(e){if(e)try{return new URL(e,typeof window>"u"?"https://tracefiction.local":window.location.origin).pathname}catch{return e.startsWith("/")?e.split(/[?#]/,1)[0]:void 0}}function Bn(e){return e&&e.replace(/[^A-Za-z0-9_.:-]/g,"_").slice(0,80)||"none"}function qb(e){return!Number.isFinite(e)||e<0?"unknown":e<6e4?"lt_1m":e<10*6e4?"1m_10m":e<60*6e4?"10m_1h":e<1440*6e4?"1h_24h":"gt_24h"}function Kb(){return typeof navigator>"u"?"unknown":typeof navigator.onLine=="boolean"?String(navigator.onLine):"unknown"}function Qb(){return typeof document>"u"?"unknown":Bn(document.visibilityState)}function Jb(){const e=F();return{...Fb(e),native_shell:String(e),online:Kb(),page_age:qb(Date.now()-$b),visibility:Qb()}}function Xb(e,t){return e==="callback_access_denied"||e==="account_deleted_logout_started"||e==="redirect_started"&&t.reason==="token_refresh_failed"?"info":"warning"}function Jt(e,t={reason:"token_refresh_failed"}){const a=zb(t.path),c=Bn(t.code),m=Bn(t.errorName),h=Bn(t.errorCode),d=t.status===void 0?"none":String(t.status);Er()&&ns("auth.session_recovery",{level:Xb(e,t),tags:{area:"auth",outcome:e,reason:t.reason,code:c,error_code:h,error_name:m,status:d,...Jb()},extra:{path:a}})}const Zb=12e3,ey=3e4;function Zc(e){const t=new Error(e);return t.name="TimeoutError",t}function rt(e){return typeof e=="object"&&e!==null}function ty(e){if(!rt(e)||e.status!==400||!rt(e.payload))return!1;const t=e.payload.issues;return Array.isArray(t)?t.some(a=>rt(a)&&typeof a.message=="string"&&a.message.includes("Unrecognized key")&&a.message.includes("source")):!1}function ny(e){return typeof e=="number"&&Number.isInteger(e)&&e>=0}const _r=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,ay=/^trd_v1_[A-Za-z0-9_-]{43}$/;function ry(e){if(!rt(e))throw new Error("Invalid extension device session response");const t=["createdAt","lastUsedAt","idleExpiresAt","absoluteExpiresAt"];if(typeof e.id!="string"||!_r.test(e.id)||typeof e.installationId!="string"||!_r.test(e.installationId)||t.some(a=>typeof e[a]!="string"||!Number.isFinite(Date.parse(e[a]))))throw new Error("Invalid extension device session response");return{id:e.id,installationId:e.installationId,createdAt:e.createdAt,lastUsedAt:e.lastUsedAt,idleExpiresAt:e.idleExpiresAt,absoluteExpiresAt:e.absoluteExpiresAt}}const iy={parse(e){if(!rt(e))throw new Error("Invalid extension device session response");const t=ry(e.session);if(e.status==="current")return{status:"current",session:t};if(e.status==="issued"&&typeof e.credential=="string"&&ay.test(e.credential))return{status:"issued",credential:e.credential,session:t};throw new Error("Invalid extension device session response")}},oy={parse(e){if(!rt(e)||e.ok!==!0)throw new Error("Invalid extension device session revoke response");return{ok:!0}}};function sy(e){if(!rt(e)||e.code!=="COLLECTION_ITEM_LIMIT_EXCEEDED"||e.limit!==500)return!1;for(const t of["total","current_count","requested_count"]){const a=e[t];if(a!==void 0&&!ny(a))return!1}return!0}function Uw(e){return rt(e)&&sy(e.payload)?e.payload:null}async function cy(e,t,a){let c;try{return await Promise.race([e,new Promise((m,h)=>{c=setTimeout(()=>h(Zc(a)),t)})])}finally{c&&clearTimeout(c)}}async function ly(e,t=!1){pi();const a=t?"Auth session refresh retry timed out":"Auth session refresh timed out";return cy(e(t?{cacheMode:"off"}:void 0),Zb,a)}async function ko(e){const t=await e.clone().text().catch(()=>"");
2if(!t)return null;try{return JSON.parse(t)}catch{return null}}function _e(){const{getAccessTokenSilently:e,isAuthenticated:t,isLoading:a}=ke(),c=y.useCallback(async(o,s={})=>{const l=o.startsWith("http")?o:ju(o),b=async(g=!1)=>{const E=new Headers(s.headers||{});if(t){const k=await ly(W=>e(W),g);E.set("Authorization",`Bearer ${k}`);for(const[W,X]of Object.entries(Bu()))E.set(W,X)}s.body&&!E.has("Content-Type")&&E.set("Content-Type","application/json");const w=new AbortController;let T=!1;const D=setTimeout(()=>{T=!0,w.abort()},ey),R=()=>w.abort(s.signal?.reason);try{return s.signal?.aborted?w.abort(s.signal.reason):s.signal?.addEventListener("abort",R,{once:!0}),await fetch(l,{...s,headers:E,cache:s.cache??"no-store",signal:w.signal})}catch(k){throw T?Zc(`Request timed out: ${l}`):k}finally{clearTimeout(D),s.signal?.removeEventListener("abort",R)}};try{const g=await b(!1);if(t&&g.status===410){const w=await ko(g),T=fr(w);return T==="ACCOUNT_DELETED"&&Wa({reason:"account_deleted",path:o,status:g.status,code:T}),g}if(!t||g.status!==401)return g;const E=await b(!0);if(E.status===401){const w=await ko(E),T=fr(w);Gb(w)?Wa({reason:"api_401_after_token_refresh",path:o,status:E.status,code:T}):Jt("api_401_nonrecoverable",{reason:"api_401_after_token_refresh",path:o,status:E.status,code:T})}return E}catch(g){throw Yb(g)&&Wa({reason:"token_refresh_failed",path:o,code:Zn(g)}),g}},[e,t]),m=!a&&t;async function h(o,s){const l=await c(o,s),b=await l.text().catch(()=>"");if(!l.ok){const g=new Error(`${l.status} ${l.statusText} :: ${b.slice(0,300)}`);g.status=l.status,g.url=l.url;try{g.payload=JSON.parse(b)}catch{}const E=l.headers.get("retry-after");if(E){const T=Number(E);Number.isNaN(T)||(g.retryAfterSec=T)}const w=l.headers.get("ratelimit-reset");if(w){const T=Number(w);Number.isNaN(T)||(g.rateLimitResetSec=T)}throw l.status===402&&window.dispatchEvent(new CustomEvent("trace:openUpgrade",{detail:{source:"useApi",path:o,payload:g.payload}})),g}if(!b)return null;try{return JSON.parse(b)}catch{throw new Error(`Bad JSON at ${l.url} :: ${b.slice(0,200)}`)}}async function d(o,s,l){return o.parse(await h(s,l))}async function v(o,s,l){try{return await l(o)}catch(b){const g=jb(b);if(!g)throw b;const E=s(o,g);if(E===o)throw b;return l(E)}}return{isReady:m,async getWatchesSetup(){return d(fh,"/api/watches/setup")},async getStoryUpdatesStatus(){return d(Lt,"/api/watches/status")},async listStoryUpdatesInbox(o={}){const s=kh.parse(o),l=new URLSearchParams({limit:String(s.limit)});return s.cursor&&l.set("cursor",s.cursor),d(Ch,`/api/watches/inbox?${l.toString()}`)},async acknowledgeStoryUpdates(o){const s=Ih.parse(o);return d(Oh,"/api/watches/acknowledge",{method:"POST",body:JSON.stringify(s)})},async getStoryUpdatesPreferences(){return d(lo,"/api/watches/preferences")},async patchStoryUpdatesPreferences(o){const s=Ph.parse(o);return d(lo,"/api/watches/preferences",{method:"PATCH",body:JSON.stringify(s)})},async completeStoryUpdatesForwardingSetup(o){const s=Fs.parse(o);return d(Lt,"/api/watches/forwarding-setup/complete",{method:"POST",body:JSON.stringify(s)})},async startWatchesGmailAuthorization(){return d(jh,"/api/watches/gmail/authorization",{method:"POST"})},async syncWatchesGmail(){return d(Uh,"/api/watches/gmail/sync",{method:"POST"})},async disconnectWatchesGmail(){return d(Nt,"/api/watches/gmail",{method:"DELETE"})},async provisionWatchesRoute(){return d(oo,"/api/watches/route",{method:"POST"})},async rotateWatchesRoute(){return d(oo,"/api/watches/route/rotate",{method:"POST"})},async disconnectWatches(){return d(Nt,"/api/watches/route",{method:"DELETE"})},async startWatchesForwardingVerification(){return d(Da,"/api/watches/forwarding-verification",{method:"POST"})},async startWatchesForwardingVerificationDiagnostic(){return d(Da,"/api/watches/forwarding-verification/diagnostic",{method:"POST"})},async getWatchesForwardingVerification(o){return d(Da,`/api/watches/forwarding-verification/${encodeURIComponent(o)}`)},async cancelWatchesForwardingVerification(o){return d(Nt,`/api/watches/forwarding-verification/${encodeURIComponent(o)}`,{method:"DELETE"})},async startWatchesRecipientDiagnostic(o){return d(so,"/api/watches/recipient-diagnostic",{method:"POST",body:JSON.stringify({address:o})})},async getWatchesRecipientDiagnostic(o){return d(so,`/api/watches/recipient-diagnostic/${encodeURIComponent(o)}`)},async cancelWatchesRecipientDiagnostic(o){return d(Nt,`/api/watches/recipient-diagnostic/${encodeURIComponent(o)}`,{method:"DELETE"})},async listWatchesCandidates(o={}){const s=Ah.parse(o),l=new URLSearchParams({limit:String(s.limit)});return s.cursor&&l.set("cursor",s.cursor),d(Rh,`/api/watches/candidates?${l.toString()}`)},async deleteWatchesCandidate(o){return d(Nt,`/api/watches/candidates/${encodeURIComponent(o)}`,{method:"DELETE"})},async clearWatchesCandidates(){return d(Nt,"/api/watches/candidates",{method:"DELETE"})},async listCollections(){return d(gf,"/api/collections")},async createCollection(o){const s=Yh.parse(o);return d($e,"/api/collections",{method:"POST",body:JSON.stringify(s)})},async createCollectionFromSelected(o){const s=Kh.parse(o);return d($e,"/api/collections/from-selected",{method:"POST",body:JSON.stringify(s)})},async createCollectionFromTags(o){const s=Qh.parse(o);return d($e,"/api/collections/from-tags",{method:"POST",body:JSON.stringify(s)})},async createCollectionFromQuery(o){const s=Jh.parse(o);return d($e,"/api/collections/from-query",{method:"POST",body:JSON.stringify(s)})},async getCollection(o){return d($e,`/api/collections/${o}`)},async updateCollection(o,s){const l=Gh.parse(s);return d($e,`/api/collections/${o}`,{method:"PATCH",body:JSON.stringify(l)})},async deleteCollection(o,s={}){const l=Gs.parse(s);return d(Sf,`/api/collections/${o}`,{method:"DELETE",body:JSON.stringify(l)})},async duplicateCollection(o,s={}){const l=zh.parse(s);return d(bf,`/api/collections/${o}/duplicate`,{method:"POST",body:JSON.stringify(l)})},async addCollectionItems(o,s){const l=ef.parse(s);return d(vf,`/api/collections/${o}/items`,{method:"POST",body:JSON.stringify(l)})},async addPublicCollectionItems(o,s){const l=Qf.parse(s);return d(Jf,`/api/collections/${o}/items/from-public-collection`,{method:"POST",body:JSON.stringify(l)})},async createCollectionFromPublicCollection(o){const s=qf.parse(o);return d(Kf,"/api/collections/from-public-collection",{method:"POST",body:JSON.stringify(s)})},async getPublicCollectionLibraryStates(o){const s=Yf.parse(o);return d(zf,"/api/collections/public-library-states",{method:"POST",body:JSON.stringify(s)})},async reportPublicCollection(o,s){const l=Cf.parse(s);return d(Nf,`/api/public/collections/${o}/report`,{method:"POST",body:JSON.stringify(l)})},async updateCollectionItemNote(o,s,l){const b=tf.parse(l);return d(yf,`/api/collections/${o}/items/${s}`,{method:"PATCH",body:JSON.stringify(b)})},async removeCollectionItem(o,s,l={}){const b=nf.parse(l);return d($e,`/api/collections/${o}/items/${s}`,{method:"DELETE",body:JSON.stringify(b)})},async removeCollectionItems(o,s){const l=df.parse(s);return d(mo,`/api/collections/${o}/items/remove`,{method:"POST",body:JSON.stringify(l)})},async undoCollectionOperation(o,s,l){const b=uf.parse(l);return d(mo,`/api/collections/${o}/operations/${s}/undo`,{method:"POST",body:JSON.stringify(b)})},async reorderCollectionItems(o,s){const l=sf.parse(s);return d($e,`/api/collections/${o}/reorder`,{method:"POST",body:JSON.stringify(l)})},async getCollectionShare(o){return d(kn,`/api/collections/${o}/share`)},async enableCollectionShare(o,s){const l=If.parse(s);return d(kn,`/api/collections/${o}/share`,{method:"POST",body:JSON.stringify(l)})},async updateCollectionShare(o,s){const l=Xs.parse(s);return d(kn,`/api/collections/${o}/share`,{method:"PATCH",body:JSON.stringify(l)})},async regenerateCollectionShare(o,s={}){const l=qh.parse(s);return d(kn,`/api/collections/${o}/share/regenerate`,{method:"POST",body:JSON.stringify(l)})},async listLibraryViews(){return d(fo,"/api/library/views")},async createLibraryView(o){const s=sg.parse(o);return d(ho,"/api/library/views",{method:"POST",body:JSON.stringify(s)})},async updateLibraryView(o,s){const l=cg.parse(s);return d(ho,`/api/library/views/${o}`,{method:"PATCH",body:JSON.stringify(l)})},async deleteLibraryView(o){return d(dg,`/api/library/views/${o}`,{method:"DELETE"})},async reorderLibraryViews(o){const s=lg.parse(o);return d(fo,"/api/library/views/reorder",{method:"POST",body:JSON.stringify(s)})},async listLibrary(o){const s=mr({...o}
2);return d(b_,`/api/library${s}`)},async getLibraryEntry(o){return d(y_,`/api/library/${o}`)},async patchEntry(o,s){const l=Ha(fa.parse(s));return v(l,Va,b=>d(E_,`/api/library/${o}`,{method:"PATCH",body:JSON.stringify(b)}))},async bulkPatchEntries(o){const s=c_.parse({updates:o});return s.updates=s.updates.map(l=>({...l,patch:Ha(l.patch)})),v(s,(l,b)=>{const g=l.updates.map(E=>{const w=Va(E.patch,b);return w===E.patch?E:{...E,patch:w}});return g.every((E,w)=>E===l.updates[w])?l:{...l,updates:g}},l=>d(w_,"/api/library/bulk",{method:"PATCH",body:JSON.stringify(l)}))},async prestigeEntry(o){return d(sc,`/api/library/${o}/prestige`,{method:"POST"})},async startReread(o){return d(R_,`/api/library/${o}/read-throughs`,{method:"POST"})},async updateReadingHistoryDate(o,s,l){const b=v_.parse(l);return d(S_,`/api/library/${o}/read-throughs/${s}`,{method:"PATCH",body:JSON.stringify(b)})},async resolveStory(o){const s=l_.parse({url:o});return d(I_,"/api/library/resolve-story",{method:"POST",body:JSON.stringify(s)})},async ensureStory(o,s){const l=d_.parse({url:o,claim:s});return d(P_,"/api/library/ensure-story",{method:"POST",body:JSON.stringify(l)})},async addToLibrary(o){const s=u_.parse(o),l=s.insert_only===!0||s.insert_only==="true"||s.insert_only===1;return s.entry&&!l&&(s.entry=Ha(s.entry)),v(s,(b,g)=>{const E=b.entry&&Va(b.entry,g);return E===b.entry?b:{...b,entry:E}},b=>d(L_,"/api/library",{method:"POST",body:JSON.stringify(b)}))},async addLibraryItemFromPublicCollection(o){const s=Ff.parse(o);return d(Bf,"/api/library/from-public-collection",{method:"POST",body:JSON.stringify(s)})},async addLibraryItemsFromPublicCollection(o,s){const l=Hf.parse(o);return d($f,"/api/library/from-public-collection/bulk",{method:"POST",signal:s,body:JSON.stringify(l)})},async deleteEntry(o){return d(A_,`/api/library/${o}`,{method:"DELETE"})},async suggestCharacters(o,s=20){const l=new URLSearchParams;return o.trim()&&l.set("q",o.trim()),l.set("limit",String(s)),(await d(ft,`/api/library/suggest/characters?${l.toString()}`)).data},async suggestFandoms(o,s=20){const l=new URLSearchParams;return o.trim()&&l.set("q",o.trim()),l.set("limit",String(s)),(await d(ft,`/api/library/suggest/fandoms?${l.toString()}`)).data},async suggestStructuredFandoms(o,s=20){const l=new URLSearchParams;return o.trim()&&l.set("q",o.trim()),l.set("limit",String(s)),(await d(bp,`/api/library/suggest/fandoms/structured?${l.toString()}`)).data},async suggestContextualCharacters(o,s=20,l={}){const b=new URLSearchParams;return o.trim()&&b.set("q",o.trim()),b.set("limit",String(s)),l.fandomId!=null&&b.set("fandomId",String(l.fandomId)),l.canonicalFandomId!=null&&b.set("canonicalFandomId",String(l.canonicalFandomId)),(await d(Sp,`/api/library/suggest/characters/context?${b.toString()}`)).data}
2,async suggestRelationships(o,s=20){const l=new URLSearchParams;return o.trim()&&l.set("q",o.trim()),l.set("limit",String(s)),(await d(ft,`/api/library/suggest/relationships?${l.toString()}`)).data},async suggestLibraryTags(o,s=20){const l=new URLSearchParams;return o.trim()&&l.set("q",o.trim()),l.set("limit",String(s)),(await d(ft,`/api/library/suggest/tags?${l.toString()}`)).data},async suggestLibraryPrivateTagsForQuery(o){const s=mr({search:o.query.search,sort:o.query.sort,filters:o.query.filters,page:1,limit:50}),l=new URLSearchParams(s.startsWith("?")?s.slice(1):s);return l.set("limit",String(o.limit??200)),o.q?.trim()&&l.set("q",o.q.trim()),d(o_,`/api/library/suggest/private-tags?${l.toString()}`)},async suggestWorkTags(o,s=20){const l=new URLSearchParams;return o.trim()&&l.set("q",o.trim()),l.set("limit",String(s)),(await d(ft,`/api/library/suggest/work-tags?${l.toString()}`)).data},async suggestPlatforms(o,s=20){const l=new URLSearchParams;return o.trim()&&l.set("q",o.trim()),l.set("limit",String(s)),(await d(ft,`/api/library/suggest/platforms?${l.toString()}`)).data},async metaSearchFandoms(o,s=40){const l=new URLSearchParams;return o.trim()&&l.set("q",o.trim()),l.set("limit",String(s)),(await d(no,`/api/meta/fandoms?${l.toString()}`)).data.map(g=>g.name)},async metaLookupCanonicalFandomId(o){const s=new URLSearchParams;return s.set("name",o.trim()),(await d(Ep,`/api/meta/fandoms/canonical-id?${s.toString()}`)).data.canonical_fandom_id},async metaSearchCharacters(o,s=40,l){const b=new URLSearchParams;return o.trim()&&b.set("q",o.trim()),b.set("limit",String(s)),l!=null&&b.set("fandomId",String(l)),(await d(no,`/api/meta/characters/search?${b.toString()}`)).data.map(E=>E.name)},async metaSearchRelationships(o,s=40,l){const b=new URLSearchParams;return o.trim()&&b.set("q",o.trim()),b.set("limit",String(s)),l!=null&&b.set("fandomId",String(l)),(await d(ft,`/api/meta/relationships?${b.toString()}`)).data},async deleteAccount(){return d(nm,"/api/account",{method:"DELETE"})},async resolveExtensionDeviceSession(o){return d(iy,"/api/extension/device-sessions",{method:"POST",body:JSON.stringify(o)})},async revokeExtensionDeviceSession(o){if(!_r.test(o))throw new Error("Invalid extension device session id");await d(oy,`/api/extension/device-sessions/${encodeURIComponent(o)}`,{method:"DELETE"})},async exportAccount(){const o=await c("/api/account/export",{method:"GET"});if(!o.ok){const s=await o.text().catch(()=>"");throw new Error(`Export failed: ${o.status} :: ${s.slice(0,200)}`)}return o.blob()},async createCheckout(o,s="unknown"){const l=Lp.parse({plan:o,source:s});try{return await d(ir,"/api/billing/checkout",{method:"POST",body:JSON.stringify(l)})}catch(b){if(!ty(b))throw b;return d(ir,"/api/billing/checkout",{method:"POST",body:JSON.stringify({plan:o})})}},async recordBillingEvent(o){const s=Dp.parse(o);return d(jp,"/api/billing/events",{method:"POST",body:JSON.stringify(s)})},async syncCheckoutSession(o){return d(Mp,"/api/billing/sync-checkout",{method:"POST",body:JSON.stringify({sessionId:o})})},async openPortal(){return d(Up,"/api/billing/portal",{method:"POST"})},async verifyApplePurchase(o){return d(Fp,"/api/billing/apple/verify",{method:"POST",body:JSON.stringify({signedTransaction:o})})},async me(){return d(om,"/api/account/me")},async patchAccountUiSettings(o){const s=Gu.parse(o);return d(zu,"/api/account/ui-settings",{method:"PATCH",body:JSON.stringify(s)})},async getAccountReleaseNotice(o){return d(qu,`/api/account/release-notices/${encodeURIComponent(o)}`)},async dismissAccountReleaseNotice(o){return d(Ku,`/api/account/release-notices/${encodeURIComponent(o)}/dismiss`,{method:"PATCH"})},async recordAdvocacyActivity(){return d(xs,"/api/account/advocacy/activity",{method:"POST"})},async getAdvocacyActivityMarker(){return d(Qu,"/api/account/advocacy/activity")},async claimAdvocacyPrompt(o){const s=Ju.parse({review_available:o});return d(Xu,"/api/account/advocacy/claim",{method:"POST",body:JSON.stringify(s)})},async completeAdvocacyPrompt(o){const s=Zu.parse({prompt:o});return d(em,"/api/account/advocacy/complete",{method:"POST",body:JSON.stringify(s)})},async getAccountPublicAttribution(){return d(Xi,"/api/account/public-attribution")},async patchAccountPublicAttribution(o){const s=Wu.parse(o);return d(Xi,"/api/account/public-attribution",{method:"PATCH",body:JSON.stringify(s)})},async getSuggestions(){return d(Lg,"/api/suggestions")},async dismissSuggestion(o){const s=Ag.parse({fingerprint:o});return d(Cg,"/api/suggestions/dismiss",{method:"POST",body:JSON.stringify(s)})},async snoozeSuggestion(o,s=7){const l=Rg.parse({fingerprint:o,days:s});return d(Ng,"/api/suggestions/snooze",{method:"POST",body:JSON.stringify(l)})},async patchNotificationPrefs(o){const s=kg.parse({push_suggestions_enabled:o});return d(Pg,"/api/account/notification-prefs",{method:"PATCH",body:JSON.stringify(s)})},async registerApnsToken(o){const s=Tg.parse(o);return d(Ig,"/api/push/apns/register",{method:"POST",body:JSON.stringify(s)})},async statsSummary(o){const s=new URLSearchParams;o.from&&s.set("from",o.from),o.to&&s.set("to",o.to),o.tz&&s.set("tz",o.tz);const l=s.toString()?`?${s.toString()}`:"";return d(kp,`/api/stats/summary${l}`)},async manualEntry(o){const s=p_.parse(o);return d(j_,"/api/library/manual-entry",{method:"POST",body:JSON.stringify(s)})},async submitFeedback(o){const s=Im.parse(o);return d(Om,"/api/feedback",{method:"POST",body:JSON.stringify(s)})},async recordOnboardingEvent(o){const s=km.parse(o);await d(Cm,"/api/account/onboarding-event",{method:"POST",body:JSON.stringify(s)})},async recordOnboardingBoot(o){const s=Tm.parse(o);await d(Nm,"/api/account/onboarding-boot",{method:"POST",body:JSON.stringify(s)})},async adminDashboard(){return d(Bm,`/api/admin/dashboard?contractVersion=${Zt}`)},async adminOverview(o){const s=new URLSearchParams(o);return d(Ib,`/api/admin/overview?${s}`)},async adminFeedback(o){const s=new URLSearchParams;o.type&&s.set("type",o.type),o.status&&s.set("status",o.status),o.limit!=null&&s.set("limit",String(o.limit)),o.offset!=null&&s.set("offset",String(o.offset));const l=s.toString()?`?${s.toString()}`:"";return d(Hm,`/api/admin/feedback${l}`)},async adminMarkFeedbackReviewed(o){return d(Vm,`/api/admin/feedback/${o}/reviewed`,{method:"PATCH"})},async adminCollectionReports(o={}){const s=$m.parse(o),l=new URLSearchParams;return s.status&&l.set("status",s.status),s.reason&&l.set("reason",s.reason),l.set("limit",String(s.limit)),l.set("offset",String(s.offset)),d(Ym,`/api/admin/collection-reports?${l.toString()}`)},async adminCollectionReport(o){return d(Gm,`/api/admin/collection-reports/${o}`)},async adminUpdateCollectionReport(o,s){const l=qm.parse(s);return d(zm,`/api/admin/collection-reports/${o}`,{method:"PATCH",body:JSON.stringify(l)})},async adminUnpublishPublicCollection(o,s){const l=eo.parse(s);return d(He,`/api/admin/public-collections/${o}/unpublish`,{method:"POST",body:JSON.stringify(l)})},async adminRestorePublicCollection(o,s){const l=eo.parse(s);return d(He,`/api/admin/public-collections/${o}/restore`,{method:"POST",body:JSON.stringify(l)})},async adminDisableUserPublicSharing(o,s){const l=to.parse(s);return d(He,`/api/admin/users/${encodeURIComponent(o)}/public-sharing/disable`,{method:"POST",body:JSON.stringify(l)})},async adminRestoreUserPublicSharing(o,s){const l=to.parse(s);return d(He,`/api/admin/users/${encodeURIComponent(o)}/public-sharing/restore`,{method:"POST",body:JSON.stringify(l)})},async adminPublicLinkDomains(o={}){const s=Km.parse(o),l=new URLSearchParams;return s.status&&l.set("status",s.status),l.set("limit",String(s.limit)),l.set("offset",String(s.offset)),d(Jm,`/api/admin/public-link-domains?${l.toString()}`)},async adminApprovePublicLinkDomain(o,s){const l=Oa.parse(s);return d(He,`/api/admin/public-link-domains/${o}/approve`,{method:"POST",body:JSON.stringify(l)})},async adminBlockPublicLinkDomain(o,s){const l=Oa.parse(s);return d(He,`/api/admin/public-link-domains/${o}/block`,{method:"POST",body:JSON.stringify(l)})},async adminIgnorePublicLinkDomain(o,s){const l=Oa.parse(s);return d(He,`/api/admin/public-link-domains/${o}/ignore`,{method:"POST",body:JSON.stringify(l)})},async adminModerationAuditEvents(o={}){const s=Zm.parse(o),l=new URLSearchParams;return s.target_type&&l.set("target_type",s.target_type),s.target_id&&l.set("target_id",s.target_id),l.set("limit",String(s.limit)),l.set("offset",String(s.offset)),d(ep,`/api/admin/moderation-audit-events?${l.toString()}`)},async adminPendingAliases(){return d(op,"/api/admin/pending-aliases")},async adminRunAliasAutomation(o={}){const s=mp.parse(o);return d(lp,"/api/admin/alias-automation",{method:"POST",body:JSON.stringify(s)})},async adminSearchCanonical(o){const s=pp.parse(o),l=new URLSearchParams;return l.set("type",s.type),l.set("q",s.q),s.limit!=null&&l.set("limit",String(s.limit)),s.fandomName&&l.set("fandomName",s.fandomName),d(dp,`/api/admin/canonical-search?${l.toString()}`)},async adminResolveAlias(o){const s=hp.parse(o);return d(He,"/api/admin/resolve-alias",{method:"POST",body:JSON.stringify(s)})},async adminIgnoreAlias(o){const s=fp.parse(o);return d(He,"/api/admin/ignore-alias",{method:"POST",body:JSON.stringify(s)})},async adminCreateCanonical(o){const s=_p.parse(o);return d(up,"/api/admin/create-canonical",{method:"POST",body:JSON.stringify(s)})}}}const gr="trace:first-story-activation",el="trace:onboarding-boot-v1";function Sa(){return"trace-web@0017ecb533ed".trim().slice(0,120)||"unknown"}function dy(){const e=window.location.pathname.split("/").find(t=>t.length>0);return e?`/${e.slice(0,119)}`:"/"}function uy(){const e=window.__TRACE_NATIVE_APP__;return{route:dy(),auth_return_outcome:ru(),client_release:Sa(),native_shell:F(),native_app_version:e?.version,native_app_build:e?.build,native_release_channel:e?.releaseChannel,recorded_at:new Date().toISOString()}}function my(){try{return sessionStorage.getItem(el)===Sa()}catch{return!1}}
2function py(){try{sessionStorage.setItem(el,Sa())}catch{}}function Co(e,t){typeof e=="object"&&e!==null&&"payload"in e&&typeof e.payload=="object"&&e.payload!==null&&"code"in e.payload&&e.payload.code==="ACCOUNT_DELETED"||wr(e,{tags:{telemetry_event_type:t,native_shell:String(F())}})}function Mw(e,t){const a={...e,...t,recordedAt:new Date().toISOString()};typeof window<"u"&&window.dispatchEvent(new CustomEvent(gr,{detail:a}))}function hy(e){const t=window.__TRACE_NATIVE_APP__;return{action:e.type,surface:e.surface,state_id:e.stateId,variant:e.variant,target:e.target,step_id:e.stepId,path_id:e.pathId,recommended_path_id:e.recommendedPathId,path_support:e.pathSupport,extension_phase:e.extensionPhase,extension_connected:e.extensionConnected,extension_auth_state:e.extensionAuthState,extension_browser_kind:e.extensionBrowserKind,archive_host_kind:e.archiveHostKind,archive_action_kind:e.archiveActionKind,archive_error_kind:e.archiveErrorKind,first_save_seen:e.firstSaveSeen,extension_first_story_add_supported:e.extensionFirstStoryAddSupported,first_story_entry_mode:e.firstStoryEntryMode,first_story_result:e.firstStoryResult,recent_archive_activity:e.recentArchiveActivity,library_count_state:e.libraryCountState,flow_version:e.onboardingFlowVersion,ios_activation_stage:e.iosActivationStage,native_state_phase:e.nativeStatePhase,settings_supported:e.settingsSupported,earned_permission_onboarding:e.earnedPermissionOnboarding,native_state_error:e.nativeStateError,client_release:Sa(),native_shell:F(),native_app_version:t?.version,native_app_build:t?.build,native_release_channel:t?.releaseChannel,recorded_at:e.recordedAt}}function fy(e){return typeof e=="object"&&e!==null}function _y(){const e=_e(),t=y.useRef(!1);y.useEffect(()=>{!e.isReady||typeof window>"u"||t.current||my()||(t.current=!0,e.recordOnboardingBoot(uy()).then(()=>{py(),iu()}).catch(a=>{Co(a,"onboarding.boot")}).finally(()=>{t.current=!1}))},[e]),y.useEffect(()=>{if(!e.isReady||typeof window>"u")return;const a=c=>{const m=c.detail;fy(m)&&e.recordOnboardingEvent(hy(m)).catch(h=>{Co(h,"onboarding.activation_event")})};return window.addEventListener(gr,a),()=>{window.removeEventListener(gr,a)}},[e])}const gy=fe(["inline-flex items-center justify-center select-none whitespace-nowrap","transition-colors duration-150","focus-visible:outline-none focus-visible:shadow-ring","disabled:opacity-50 disabled:shadow-none disabled:cursor-not-allowed","cursor-pointer disabled:cursor-not-allowed","aria-expanded:bg-hover aria-expanded:shadow-ring aria-pressed:shadow-ring"].join(" "),{variants:{variant:{ghost:"border border-transparent bg-transparent text-content-primary hover:bg-hover active:bg-active aria-pressed:bg-accent-100",outline:"border border-border bg-transparent text-content-primary hover:border-border-strong hover:bg-hover active:bg-active aria-pressed:border-accent-600/35 aria-pressed:bg-accent-100",surface:"border border-border bg-surface-2 text-content-primary hover:bg-hover active:bg-active aria-pressed:border-accent-600/35 aria-pressed:bg-accent-100",danger:"border border-transparent bg-danger-600 text-[var(--solid-button-fg)] hover:bg-danger-700 active:bg-danger-700"},size:{sm:"h-9 w-9 rounded-full p-0.5",md:"h-10 w-10 rounded-full p-0.5",lg:"h-11 w-11 rounded-full p-1"}},defaultVariants:{variant:"ghost",size:"sm"}}),yt=y.forwardRef(({variant:e,size:t,loading:a=!1,disabled:c,className:m,children:h,...d},v)=>{const o=c||a;return i.jsx(Ar,{ref:v,disabled:o,"aria-busy":a||void 0,focusableWhenDisabled:a?!0:d.focusableWhenDisabled,className:I(gy({variant:e,size:t}),m),...d,children:a?i.jsx("span",{className:"inline-block h-4 w-4 animate-spin rounded-full border-2 border-current border-t-transparent","aria-hidden":"true"}):h})});yt.displayName="IconButton";function by(e){const t=ls.siteUrl.replace(/\/$/,""),a=e.startsWith("/")?e:`/${e}`;return`${t}${a}`}const No=y.forwardRef(function({to:t="/setup",rel:a,target:c,...m},h){return F()?i.jsx("a",{...m,href:by(t),ref:h,rel:a??"noopener noreferrer",target:c??"_blank"}):i.jsx(J,{...m,ref:h,to:t})}),yy=72,vy=.65,Sy="transform 180ms cubic-bezier(.2,.8,.2,1)";function xy(e){e&&(e.style.transform="",e.style.transition="",e.style.willChange="")}function Ey(e){e.style.transition="none",e.style.willChange="transform"}
2function wy({className:e,indicatorClassName:t,targetRef:a,onDismiss:c,disabled:m=!1,showIndicator:h=!0,dismissThresholdPx:d=yy,velocityThresholdPxPerMs:v=vy}){const o=y.useRef(null),s=y.useRef(null);y.useEffect(()=>()=>{s.current!=null&&window.clearTimeout(s.current)},[]);const l=y.useCallback(g=>{g.style.transition=Sy,g.style.transform="translate3d(0, 0, 0)",g.style.willChange="transform",s.current!=null&&window.clearTimeout(s.current),s.current=window.setTimeout(()=>{xy(g),s.current=null},200)},[]),b=y.useCallback(g=>{const E=o.current;if(!E||E.pointerId!==g.pointerId)return;const w=Math.max(0,g.clientY-E.startY);o.current=null;try{g.currentTarget.releasePointerCapture(g.pointerId)}catch{}if(w>=d||E.velocity>=v){c();return}l(E.target)},[d,c,l,v]);return i.jsx("div",{"aria-hidden":"true",className:I("flex shrink-0 touch-none select-none justify-center",e),"data-mobile-sheet-drag-handle":"",onPointerDown:g=>{if(m||g.isPrimary===!1||g.button>0)return;const E=a.current??g.currentTarget.closest("[data-mobile-sheet-drag-target]");if(E){s.current!=null&&(window.clearTimeout(s.current),s.current=null),o.current={pointerId:g.pointerId,startY:g.clientY,lastY:g.clientY,lastTime:g.timeStamp,velocity:0,target:E},Ey(E);try{g.currentTarget.setPointerCapture(g.pointerId)}catch{}}},onPointerMove:g=>{const E=o.current;if(!E||E.pointerId!==g.pointerId)return;const w=Math.max(0,g.clientY-E.startY),T=Math.max(1,g.timeStamp-E.lastTime);E.velocity=Math.max(0,(g.clientY-E.lastY)/T),E.lastY=g.clientY,E.lastTime=g.timeStamp,E.target.style.transform=`translate3d(0, ${w}px, 0)`},onPointerUp:b,onPointerCancel:b,children:h?i.jsx("span",{className:I("block h-1 w-10 rounded-pill bg-[var(--ink-5)]",t)}):null})}const Io=30;function Nn(e){return e instanceof Error?e.message:"Check your connection and try again."}function Ay(e){if(e.kind==="new_chapter"){const t=e.chapter_number?`Chapter ${e.chapter_number}`:"New chapter";return e.chapter_title?`${t} · ${e.chapter_title}`:`${t} announced`}return e.kind==="backdated_work"?"Backdated work announced":"New work announced"}function Ry(e){return{id:e.group_key,groupKey:e.group_key,announcementSequence:e.announcement_sequence,workId:e.work_id,libraryEntryId:e.library_entry_id,kind:e.kind,title:e.work_title,byline:e.classification==="library"?"Saved in your Library":"AO3 subscription",latestAnnouncement:Ay(e),announcedAt:e.announced_at,announcedChapterHref:e.open_url,additionalAnnouncementCount:Math.max(e.recent_announcement_count-1,0),unseen:e.is_unseen,storyHref:e.library_entry_id?`/library/${e.library_entry_id}`:void 0}}async function $a(e){await Promise.all([e.invalidateQueries({queryKey:B.watches.all}),e.invalidateQueries({queryKey:B.library.all}),e.invalidateQueries({queryKey:B.collections.all})])}function Ty(e=!0){const t=_e(),a=jt(),[c,m]=y.useState(null),h=$l({queryKey:B.watches.inbox(Io),queryFn:({pageParam:l})=>t.listStoryUpdatesInbox({limit:Io,cursor:l??void 0}),initialPageParam:null,getNextPageParam:l=>l.next_cursor??void 0,enabled:e&&t.isReady}),d=Xt({mutationFn:l=>{if(!l.groupKey||!l.announcementSequence)throw new Error("This update cannot be acknowledged yet.");return t.acknowledgeStoryUpdates({items:[{group_key:l.groupKey,announcement_sequence:l.announcementSequence}]})},onMutate:()=>m(null),onSuccess:()=>$a(a),onError:l=>m(Nn(l))}),v=Xt({mutationFn:()=>{const l=h.data?.pages[0]?.acknowledgement_boundary;if(!l)throw new Error("No loaded updates can be acknowledged yet.");return t.acknowledgeStoryUpdates({all_before:l})},onMutate:()=>m(null),onSuccess:()=>$a(a),onError:l=>m(Nn(l))}),o=Xt({mutationFn:async l=>{const b=await t.ensureStory(l.announcedChapterHref);return t.addToLibrary({story_id:b.story.story_id,insert_only:!0})},onMutate:()=>m(null),onSuccess:()=>$a(a),onError:l=>m(Nn(l))});return{data:y.useMemo(()=>{const l=h.data?.pages??[],b=l[0],g=l.flatMap(E=>E.items).map(Ry);return{libraryItems:g.filter(E=>E.libraryEntryId!=null),otherItems:g.filter(E=>E.libraryEntryId==null),unseenCount:b?.counts.unseen_stories??0,loading:h.isLoading,error:h.error?Nn(h.error):null,hasMore:h.hasNextPage,loadingMore:h.isFetchingNextPage,actionError:c,pendingAction:v.isPending?{kind:"mark-all-seen"}:d.isPending?{kind:"mark-seen",itemId:d.variables?.id}:o.isPending?{kind:"add-to-library",itemId:o.variables?.id}:null}},[d.isPending,d.variables?.id,v.isPending,c,o.isPending,o.variables?.id,h.data,h.error,h.hasNextPage,h.isFetchingNextPage,h.isLoading]),actions:{onAddToLibrary:l=>{o.isPending||o.mutate(l)},onMarkAllSeen:()=>{v.isPending||v.mutate()},onMarkSeen:l=>{d.isPending||d.mutate(l)},onRetry:()=>{h.refetch()},onLoadMore:()=>{h.fetchNextPage()}}}}function Fw(e=!0){const t=_e();return an({queryKey:B.watches.status,queryFn:()=>t.getStoryUpdatesStatus(),enabled:e&&t.isReady})}function Bw(e=!0){const t=_e(),a=jt(),c=an({queryKey:B.watches.preferences,queryFn:()=>t.getStoryUpdatesPreferences(),enabled:e&&t.isReady}),m=Xt({mutationFn:h=>t.patchStoryUpdatesPreferences(h),onSuccess:h=>{a.setQueryData(B.watches.preferences,h),a.setQueryData(B.watches.status,d=>!d||typeof d!="object"?d:{...d,preferences:h.preferences})}});return{...c,update:m}}const ky="TRACE_BILLING_RESULT";function Cy(){return F()?window.webkit?.messageHandlers?.traceBilling??null:null}function hi(e){const t=Cy();if(!t)return!1;try{return t.postMessage({op:e}),!0}catch{return!1}}function Ny(){return hi("showPaywall")}function Iy(){return hi("restore")}function Hw(){return hi("manageSubscriptions")}function Oy(e){if(!e||typeof e!="object")return null;const t=e;if(t.type!==ky)return null;const a=t.op==="showPaywall"||t.op==="restore"||t.op==="manageSubscriptions"?t.op:void 0;
2return t.op!=null&&a==null||t.status!=="success"&&t.status!=="cancelled"&&t.status!=="error"?null:{status:t.status,op:a,message:typeof t.message=="string"?t.message:void 0,code:typeof t.code=="string"?t.code:void 0,pro:typeof t.pro=="boolean"?t.pro:void 0,pro_expires_at:typeof t.pro_expires_at=="string"||t.pro_expires_at===null?t.pro_expires_at:void 0}}function tl(e){const t=a=>{if(a.source!==window)return;const c=Oy(a.data);c&&e(c)};return window.addEventListener("message",t),()=>window.removeEventListener("message",t)}const Ya=NaN,Py=Number.isInteger(Ya)&&Ya>0?Ya:100;function Ly(e,t){Y.useEffect(()=>{if(!t)return;const a=c=>c.key==="Escape"&&e();return document.addEventListener("keydown",a),()=>document.removeEventListener("keydown",a)},[t,e])}function Oo(e){return(e||"").trim().toLowerCase().replace(/\s+/g,"_")}function Dy(e){const t=Oo(e.code),a=Oo(e.message),c=t||a;return c.includes("cancel")?"":c.includes("network")||c.includes("timed_out")||c.includes("timeout")||c.includes("offline")?"Could not reach Apple or Trace. Check your connection and try again.":c.includes("not_allowed")||c.includes("payment_not_allowed")||c.includes("payments_disabled")?"In-app purchases are disabled on this device/account.":c.includes("product_not_available")||c.includes("invalid_product")||c.includes("storekit_product_missing")?"This subscription product is not available for this App Store account yet.":c.includes("verification")||c.includes("invalid_transaction")||c.includes("apple_status_unavailable")?"Purchase completed, but verification failed. Tap Restore purchases, then try again.":c.includes("already_owned")||c.includes("already_subscribed")?"You already have an active subscription on this Apple account. Tap Restore purchases.":e.op==="restore"?e.message||"No eligible purchases were restored. Confirm you are signed into the same Apple account.":e.message||"Something went wrong with Apple billing."}function jy({open:e,onClose:t,source:a="unknown"}){const c=_e(),m=F(),[h,d]=Y.useState(null),[v,o]=Y.useState(""),s=Y.useRef(!1),l=Y.useCallback(()=>{d(null),o(""),t()},[t]),b=Y.useCallback(()=>{c.isReady&&c.recordBillingEvent({event:"upgrade_modal_dismissed",source:a,platform:m?"apple":"web"}).catch(()=>{}),l()},[c,l,m,a]),g=Y.useCallback(async()=>{try{return(await c.me()).pro?(l(),!0):!1}catch{return!1}},[c,l]);Ly(b,e),Y.useEffect(()=>{if(!e)return;const R=document.body.style.overflow;return document.body.style.overflow="hidden",()=>{document.body.style.overflow=R}},[e]),Y.useEffect(()=>{e||(d(null),o(""))},[e]),Y.useEffect(()=>{if(!e){s.current=!1;return}!c.isReady||s.current||(s.current=!0,c.recordBillingEvent({event:"upgrade_modal_opened",source:a,platform:m?"apple":"web"}).catch(()=>{}))},[c,m,e,a]),Y.useEffect(()=>{if(!(!e||!m))return tl(R=>{if(d(null),R.status==="success"){if(R.pro===!1){c.recordBillingEvent({event:"apple_purchase_failed",source:a,platform:"apple"}).catch(()=>{}),o("Purchase was not completed. Select a plan in Apple's sheet and confirm with Face ID/Touch ID.");return}if(R.pro===!0){l();return}(async()=>{try{if(await g())return;o("Apple did not return an active subscription yet. If you completed purchase, tap Restore purchases.")}catch{o("Could not confirm subscription status. Tap Restore purchases to sync.")}})();return}if(R.status==="cancelled"){c.recordBillingEvent({event:"apple_purchase_cancelled",source:a,platform:"apple"}).catch(()=>{}),o("");return}c.recordBillingEvent({event:"apple_purchase_failed",source:a,platform:"apple"}).catch(()=>{}),o(Dy(R))})},[c,g,l,m,e,a]),Y.useEffect(()=>{if(!e||!m||h!=="apple"&&h!=="restore")return;let R=!1;const k=()=>{(async()=>R||await g())()},W=()=>{document.visibilityState==="visible"&&k()};return window.addEventListener("focus",k),document.addEventListener("visibilitychange",W),()=>{R=!0,window.removeEventListener("focus",k),document.removeEventListener("visibilitychange",W)}},[h,g,m,e]),Y.useEffect(()=>{if(!e||!m||h!=="apple"&&h!=="restore")return;const R=window.setTimeout(()=>{(async()=>await g()||(d(k=>k==="apple"||k==="restore"?null:k),o("Apple purchase was not completed. If you dismissed the sheet, you can try again.")))()},2e4);return()=>window.clearTimeout(R)},[h,g,m,e]);async function E(R){c.recordBillingEvent({event:"plan_selected",source:a,plan:R,platform:"web"}).catch(()=>{});const k=window.open("about:blank","_blank");if(!k){c.recordBillingEvent({event:"popup_blocked",source:a,plan:R,platform:"web"}).catch(()=>{}),o("Could not open checkout. Allow popups for this site, or try again.");return}k.opener=null;try{o(""),d(R);const{url:W}=await c.createCheckout(R,a);k.location.href=W,d(null),t()}catch(W){k.close(),o(W instanceof Error?W.message:"Something went wrong starting checkout."),d(null)}}function w(){o(""),d("apple"),c.recordBillingEvent({event:"apple_purchase_started",source:a,platform:"apple"}).catch(()=>{}),!Ny()&&(c.recordBillingEvent({event:"apple_purchase_failed",source:a,platform:"apple"}).catch(()=>{}),d(null),o("Apple billing is not available in this app build."))}function T(){o(""),d("restore"),c.recordBillingEvent({event:"apple_restore_started",source:a,platform:"apple"}).catch(()=>{}),!Iy()&&(c.recordBillingEvent({event:"apple_purchase_failed",source:a,platform:"apple"}).catch(()=>{}),d(null),o("Apple purchase restore is not available in this app build."))}async function D(){const R=window.open("about:blank","_blank");if(!R){E("month");return}R.opener=null;try{o("");const{url:k}=await c.openPortal();R.location.href=k,t()}catch{R.close(),E("month")}}return e?Fl.createPortal(i.jsxs("div",{className:["fixed inset-0 z-[4000] flex items-end justify-center","px-3 pb-[calc(1rem_+_env(safe-area-inset-bottom))] pt-[calc(1rem_+_env(safe-area-inset-top))]","sm:items-center sm:p-4"].join(" "),children:[i.jsx("div",{className:"absolute inset-0 bg-black/55",onMouseDown:b,"aria-hidden":"true"}),i.jsxs("div",{role:"dialog","aria-modal":"true","aria-label":"Trace Unlimited options",className:["library-app archive-editorial-shell relative w-full max-w-[560px] text-[var(--ink)]","max-h-[calc(100dvh_-_2rem_-_env(safe-area-inset-top)_-_env(safe-area-inset-bottom))]","rounded-t-sm border border-[var(--line-strong)] bg-[var(--paper)] shadow-[var(--shadow-modal)] sm:rou
2nded-sm","flex flex-col overflow-hidden"].join(" "),onMouseDown:R=>R.stopPropagation(),children:[i.jsxs("div",{className:"flex items-start justify-between gap-4 border-b border-[var(--line)] px-5 py-4",children:[i.jsxs("div",{className:"min-w-0",children:[i.jsx("div",{className:"font-landing-serif text-xl font-medium leading-tight text-[var(--ink)]",children:"Trace Unlimited"}),i.jsxs("div",{className:"mt-2 max-w-prose font-landing-serif text-sm italic leading-6 text-[var(--ink-2)]",children:["Free includes up to"," ",i.jsx("strong",{children:Py})," stories. Trace Unlimited removes the limit and helps keep Trace running."]})]}),i.jsx(yt,{variant:"ghost","aria-label":"Close",onClick:b,className:"shrink-0 border-transparent text-[var(--ink-3)] hover:bg-[var(--paper-2)] hover:text-[var(--ink)]",children:"×"})]}),i.jsx("div",{className:"min-h-0 flex-1 overflow-y-auto overscroll-contain px-5 py-5 [-webkit-overflow-scrolling:touch]",children:i.jsxs("div",{className:"grid gap-4",children:[v&&i.jsx("div",{className:"rounded-sm border border-[var(--rust)] bg-[var(--rust-soft)] px-3 py-2 text-sm text-[var(--ink)]",children:v}),i.jsxs("ul",{className:"grid gap-2 text-sm leading-6 text-[var(--ink-2)]",children:[i.jsxs("li",{className:"flex gap-2",children:[i.jsx("span",{className:"text-[var(--honey)]","aria-hidden":!0,children:"✓"}),"No story cap"]}),i.jsxs("li",{className:"flex gap-2",children:[i.jsx("span",{className:"text-[var(--honey)]","aria-hidden":!0,children:"✓"}),"Support ongoing development"]}),i.jsxs("li",{className:"flex gap-2",children:[i.jsx("span",{className:"text-[var(--honey)]","aria-hidden":!0,children:"✓"}),"Reading stats included"]})]}),m?i.jsxs("div",{className:"grid gap-3 rounded-sm border border-[var(--line-strong)] bg-[var(--card)] p-4",children:[i.jsxs("div",{children:[i.jsx("div",{className:"font-landing-serif text-lg font-medium text-[var(--ink)]",children:"Subscribe with Apple"}),i.jsx("p",{className:"mt-1 text-sm leading-6 text-[var(--ink-2)]",children:"Choose monthly or yearly in Apple's purchase sheet. Apple handles billing and cancellation from iOS Settings."})]}),i.jsxs("div",{className:"grid gap-2 sm:grid-cols-2",children:[i.jsxs("div",{className:"rounded-sm border border-[var(--line)] bg-[var(--paper-2)] px-3 py-2",children:[i.jsx("p",{className:"font-mono text-2xs uppercase tracking-normal text-[var(--ink-3)]",children:"Monthly"}),i.jsx("p",{className:"mt-0.5 text-sm text-[var(--ink)]",children:"Flexible billing every month"})]}),i.jsxs("div",{className:"rounded-sm border border-[var(--line-strong)] bg-[var(--paper-2)] px-3 py-2",children:[i.jsx("p",{className:"font-mono text-2xs uppercase tracking-normal text-[var(--ink-3)]",children:"Yearly"}),i.jsx("p",{className:"mt-0.5 text-sm text-[var(--ink)]",children:"Best value for long-term use"})]})]}),i.jsx("p",{className:"font-mono text-2xs leading-5 text-[var(--ink-3)]",children:"Final localized pricing and any trial details are shown by Apple before you confirm."}),i.jsxs("div",{className:"grid gap-2 sm:grid-cols-2",children:[i.jsx(L,{variant:"solid",fullWidth:!0,loading:h==="apple",onClick:w,children:h==="apple"?"Opening...":"Subscribe with Apple"}),i.jsx(L,{variant:"outline",fullWidth:!0,loading:h==="restore",onClick:T,children:h==="restore"?"Restoring...":"Restore purchases"})]})]}):i.jsxs("div",{className:"grid gap-3 sm:grid-cols-2",children:[i.jsxs("div",{className:"rounded-sm border border-[var(--line-strong)] bg-[var(--card)] p-4",children:[i.jsx("div",{className:"font-mono text-2xs uppercase tracking-normal text-[var(--ink-3)]",children:"Monthly"}),i.jsxs("div",{className:"mt-2 font-landing-serif text-3xl font-medium leading-none text-[var(--ink)]",children:[Ud,i.jsx("span",{className:"ml-1 font-mono text-2xs uppercase tracking-normal text-[var(--ink-3)]",children:"/ month"})]}),i.jsx("div",{className:"mt-3",children:i.jsx(L,{variant:"solid",fullWidth:!0,loading:h==="month",onClick:()=>E("month"),children:h==="month"?"Redirecting…":"Choose monthly"})})]}),i.jsxs("div",{className:"rounded-sm border border-[var(--line-strong)] bg-[var(--card)] p-4",children:[i.jsxs("div",{className:"flex items-center justify-between gap-2",children:[i.jsx("div",{className:"font-mono text-2xs uppercase tracking-normal text-[var(--ink-3)]",children:"Yearly"}),i.jsx("span",{className:"shrink-0 rounded-sm border border-[var(--line)] bg-[var(--paper-2)] px-2 py-0.5 font-mono text-2xs text-[var(--ink-3)]",children:"Better value"})]}),i.jsxs("div",{className:"mt-2 font-landing-serif text-3xl font-medium leading-none text-[var(--ink)]",children:[Md,i.jsx("span",{className:"ml-1 font-mono text-2xs uppercase tracking-normal text-[var(--ink-3)]",children:"/ year"})]}),i.jsxs("div",{className:"mt-2 space-y-1 text-sm leading-6 text-[var(--ink-2)]",children:[i.jsxs("p",{children:["Equivalent to"," ",Fd,"/month, billed yearly."]}),i.jsxs("p",{children:["Save ",Hd," a year vs monthly."]})]}),i.jsx("div",{className:"mt-3",children:i.jsx(L,{variant:"solid",fullWidth:!0,loading:h==="year",onClick:()=>E("year"),children:h==="year"?"Redirecting…":"Choose yearly"})})]})]})]})}),i.jsx("div",{className:"border-t border-[var(--line)] bg-[var(--paper-2)] px-5 py-4",children:i.jsxs("div",{className:"flex flex-col gap-2 sm:flex-row sm:items-center sm:justify-between",children:[m?i.jsx("div",{className:"text-sm text-[var(--ink-3)]",children:"Manage Apple subscriptions in Settings > Apple ID > Subscriptions."}):i.jsxs("div",{className:"text-sm text-[var(--ink-3)]",children:["Already subscribed?"," ",i.jsx(L,{variant:"link",onClick:D,children:"Manage billing"})]}),i.jsx("div",{className:"flex items-center gap-2",children:i.jsx(L,{variant:"ghost",onClick:b,children:"Not now"})})]})})]})]}),document.body):null}const nl=y.createContext(null);function Po(e){const t=ia.safeParse(e);return t.success?t.data:"unknown"}function Uy({children:e}){const t=_e(),a=Te(),c=na(),[m,h]=y.useState(!1),[d,v]=y.useState("unknown"),o=Y.useCallback((b="unknown")=>{v(b),h(!0)},[]),s=()=>h(!1),l=Y.useRef(!1);return y.useEffect(()=>{const b=g=>{if(l.current)return;l.current=!0;const E=g.detail;o(E?.source==="useApi"?"api_limit":Po(E?.source))};return window.addEventListener("trace:openUpgrade",b),()=>window.removeEventListener("trace:openUpgrade",b)},[o]),y.useEffect(()=>{const b=new URLSearchParams(a.search);if(b.get("upgrade")!=="1"||!t.isReady)return;o(Po(b.get("source"))),b.delete("upgrade"),b.delete("source");const g=b.toString();c({pathname:a.pathname,search:g?`?${g}`:"",hash:a.hash},{replace:!0})},[t.isReady,a.hash,a.pathname,a.search,c,o]),y.useEffect(()=>{if(!m){const b=setTimeout(()=>{l.current=!1},800);return()=>clearTimeout(b)}},[m]),i.jsxs(nl.Provider,{value:{open:o,close:s,isOpen:m},children:[e,i.jsx(jy,{open:m,onClose:s,source:d})]})}function My(){const e=y.useContext(nl);if(!e)throw new Error("useUpgrade must be used within UpgradeProvider");return e}const Fy=/^https:\/\/(?:[^/]+\.)?(?:archiveofourown\.org|archiveofourown\.gay|archive\.transformativeworks\.org|ao3\.org)\/works\/\d+(?:\/chapters\/\d+)?(?:[?#].*)?$/i,By=/^\/s\/\d+(?:\/\d+)?(?:\/.*)?$/i;function Hy(e){const t=e.trim();if(!t)return null;let a;try{a=new URL(t)}catch{return null}if(a.protocol!=="https:")return null;const c=a.href;if(Fy.test(c))return c;const m=a.hostname.toLowerCase();return(m==="www.fanfiction.net"||m==="m.fanfiction.net")&&By.test(a.pathname)?c:null}const Vy="TRACE_IOS_EXTENSION_STATE_REQUEST",Wy="TRACE_IOS_OPEN_EXTENSION_SETTINGS",$y="TRACE_IOS_OPEN_STORY_URL",Yy="TRACE_IOS_OPEN_ARCHIVE_HOME",Gy="TRACE_IOS_OPEN_ARCHIVE_HOME_V2",Lo="TRACE_IOS_AUTH_TOKEN_UPDATE",zy="TRACE_IOS_AUTH_TOKEN_CLEAR",qy="TRACE_IOS_AUTH_PROVIDER_STATUS_REQUEST",Do="TRACE_IOS_EXTENSION_STATE",Ky="TRACE_IOS_OPEN_EXTENSION_SETTINGS_RESPONSE",Qy="TRACE_IOS_OPEN_STORY_URL_RESPONSE",Jy="TRACE_IOS_OPEN_ARCHIVE_HOME_RESPONSE",Xy="TRACE_IOS_OPEN_ARCHIVE_HOME_V2_RESPONSE",Zy="TRACE_IOS_AUTH_TOKEN_UPDATE_RESPONSE",ev="TRACE_IOS_AUTH_TOKEN_CLEAR_RESPONSE",jo="TRACE_IOS_AUTH_PROVIDER_STATUS_RESPONSE",Ge=12e3,Uo=2,br=3,fi=4e3,al=1500,tv=[0,100,400],Mo=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,nv=120;let zt=null,Fo=Promise.resolve(),bt=0,nn=null;function av(e){return nn=e,()=>{nn===e&&(nn=null)}}const Ga={phase:"unavailable",enabled:!1,settingsSupported:!1,archiveBrowseHosts:null,earnedPermissionOnboarding:!1,error:"native_unavailable",lastArchiveRunAt:null,lastArchiveSaveAt:null,lastRunByHost:null,grantedOrigins:null,permissionSnapshotAt:null,heartbeatUpdatedAt:null,lastRunHandoffId:null,lastRunHandoffAt:null},Bo={phase:"checking",enabled:!1,settingsSupported:!0,archiveBrowseHosts:null,earnedPermissionOnboarding:!1,error:null,lastArchiveRunAt:null,lastArchiveSaveAt:null,lastRunByHost:null,grantedOrigins:null,permissionSnapshotAt:null,heartbeatUpdatedAt:null,lastRunHandoffId:null,lastRunHandoffAt:null};function za(e){return{phase:"ready",enabled:e.enabled,settingsSupported:e.settingsSupported,archiveBrowseHosts:e.archiveBrowseHosts??null,earnedPermissionOnboarding:e.earnedPermissionOnboarding===!0,error:e.error??null,lastArchiveRunAt:e.lastArchiveRunAt??null,lastArchiveSaveAt:e.lastArchiveSaveAt??null,lastRunByHost:e.lastRunByHost??null,grantedOrigins:e.grantedOrigins??null,permissionSnapshotAt:e.permissionSnapshotAt??null,heartbeatUpdatedAt:e.heartbeatUpdatedAt??null,lastRunHandoffId:e.lastRunHandoffId??null,lastRunHandoffAt:e.lastRunHandoffAt??null}}function cn(e){return typeof e=="object"&&e!==null}function Me(){return typeof window.crypto?.randomUUID=="function"?window.crypto.randomUUID():["trace-ios-safari",Date.now().toString(36),Math.random().toString(36).slice(2)].join("-")}function _i(){return Me()}function rl(){if(!F())return null;const e=window.webkit?.messageHandlers?.traceSafariExtension;return typeof e?.postMessage=="function"?e:null}function ea(){return rl()!=null}function rv(e){return e.kind==="access_token"?`access_token:${e.token}`:e.kind==="device_session"?`device_session:${e.sessionId}:${e.credential}`:e.kind}function iv(e){return e==="provider_update_failed"||e==="provider_clear_failed"||e==="native_timeout"||e==="native_unavailable"||e==="native_error"}function gi(e,t){if(!ea())return Promise.resolve({ok:!1,error:"native_unavailable"});const a=rv(e);
2if(zt?.desiredStateKey===a)return zt.promise;const c=++bt,m=async()=>{const d=Date.now()+Math.max(0,t);let v="native_error";for(const o of tv){if(c!==bt)return{ok:!1,error:"superseded"};if(o>0){if(Date.now()+o>=d)return{ok:!1,error:v};await new Promise(E=>{window.setTimeout(E,o)})}if(c!==bt)return{ok:!1,error:"superseded"};const s=e.kind==="access_token"?{type:Lo,protocolVersion:Uo,nonce:Me(),token:e.token}:e.kind==="device_session"?{type:Lo,protocolVersion:br,nonce:Me(),provider:{version:2,kind:"device_session",sessionId:e.sessionId,credential:e.credential,expiresAt:e.expiresAt}}:{type:zy,protocolVersion:Uo,nonce:Me()},l=e.kind==="access_token"||e.kind==="device_session"?Zy:ev,b=d-Date.now();if(b<=0)return{ok:!1,error:v};const g=await _n(s,l,Math.min(al,b));if(c!==bt)return{ok:!1,error:"superseded"};if(g.ok)return{ok:!0};if(v=g.error??"native_error",!iv(v))break}return{ok:!1,error:v}},h=Fo.catch(()=>{}).then(m).finally(()=>{zt?.promise===h&&(zt=null)});return Fo=h.then(()=>{},()=>{}),zt={desiredStateKey:a,promise:h},h}function il(e,t=fi){const a=e.trim();return a?gi({kind:"access_token",token:a},t):Promise.resolve({ok:!1,error:"sign_in_required"})}async function Ho(e,t){try{await e.revoke(t)}catch{}}async function ol(e,t,a=fi){const c=e.trim();if(!c)return{ok:!1,error:"sign_in_required"};const m=++bt,h=await sl();if(m!==bt)return{ok:!1,error:"superseded"};
2if(h.kind==="unsupported")return il(c,a);if(h.kind==="unavailable")return{ok:!1,error:h.error};let d;try{d=await t.resolve({installationId:h.installationId,currentSessionId:h.provider?.sessionId,platform:"ios"})}catch{return{ok:!1,error:"device_session_unavailable"}}if(m!==bt)return d.status==="issued"&&await Ho(t,d.session.id),{ok:!1,error:"superseded"};if(d.status==="current"&&h.provider?.sessionId===d.session.id)return{ok:!0};if(d.status!=="issued")return{ok:!1,error:"device_session_invalid_response"};const v=await gi({kind:"device_session",sessionId:d.session.id,credential:d.credential,expiresAt:d.session.absoluteExpiresAt},a);if(!v.ok)return await Ho(t,d.session.id),v;const o=h.provider?.sessionId;if(o&&o!==d.session.id)try{await t.revoke(o)}catch{return{ok:!1,error:"device_session_revoke_failed"}}return{ok:!0}}function ov(e=fi){return gi({kind:"signed_out"},e)}function sv(e){return!cn(e)||e.type!==jo&&e.type!=="TRACE_IOS_AUTH_PROVIDER_STATUS_REQUEST_RESPONSE"||typeof e.nonce!="string"||!e.nonce.trim()||typeof e.ok!="boolean"?null:{type:jo,nonce:e.nonce,ok:e.ok,protocolVersion:typeof e.protocolVersion=="number"?e.protocolVersion:void 0,installationId:typeof e.installationId=="string"?e.installationId:void 0,provider:e.provider,error:typeof e.error=="string"?e.error:void 0}}function sl(e=al){const t=Me();return new Promise(a=>{let c=!1,m=null;const h=o=>{c||(c=!0,m!=null&&window.clearTimeout(m),window.removeEventListener("message",d),a(o))},d=o=>{if(!bi(o))return;const s=sv(o.data);if(!s||s.nonce!==t)return;if(!s.ok&&(s.error==="unknown_message_type"||s.error==="unsupported_protocol")){h({kind:"unsupported"});return}if(!s.ok||s.protocolVersion!==br||typeof s.installationId!="string"||!Mo.test(s.installationId)){h({kind:"unavailable",error:s.error??"native_error"});return}let l=null;if(s.provider!=null){if(!cn(s.provider)||s.provider.kind!=="device_session"||typeof s.provider.sessionId!="string"||!Mo.test(s.provider.sessionId)||typeof s.provider.expiresAt!="string"||!Number.isFinite(Date.parse(s.provider.expiresAt))){h({kind:"unavailable",error:"provider_unavailable"});return}l={kind:"device_session",sessionId:s.provider.sessionId,expiresAt:s.provider.expiresAt}}h({kind:"supported",installationId:s.installationId,provider:l})};if(window.addEventListener("message",d),!yi({type:qy,protocolVersion:br,nonce:t})){h({kind:"unavailable",error:"native_unavailable"});return}m=window.setTimeout(()=>h({kind:"unavailable",error:"native_timeout"}),e)})}function bi(e){return!e.origin||e.origin===window.location.origin}function Ot(e){return typeof e=="number"&&Number.isFinite(e)&&e>0?e:null}function fn(e){if(typeof e!="string")return null;const t=e.trim();return t&&t.length<=128?t:null}function cv(e){if(!cn(e)||e.type!==Do||typeof e.nonce!="string"||!e.nonce.trim()||typeof e.enabled!="boolean"||typeof e.settingsSupported!="boolean")return null;const t={type:Do,nonce:e.nonce,enabled:e.enabled,settingsSupported:e.settingsSupported};if(Array.isArray(e.archiveBrowseHosts)){const s=e.archiveBrowseHosts.filter((l,b,g)=>(l==="ao3"||l==="ffn")&&g.indexOf(l)===b);s.length>0&&(t.archiveBrowseHosts=s)}e.earnedPermissionOnboarding===!0&&(t.earnedPermissionOnboarding=!0),typeof e.error=="string"&&e.error.trim()&&(t.error=e.error.trim());const a=Ot(e.lastArchiveRunAt);a!=null&&(t.lastArchiveRunAt=a);const c=Ot(e.lastArchiveSaveAt);if(c!=null&&(t.lastArchiveSaveAt=c),cn(e.lastRunByHost)){const s={};for(const[l,b]of Object.entries(e.lastRunByHost)){const g=Ot(b);g!=null&&(s[l]=g)}Object.keys(s).length>0&&(t.lastRunByHost=s)}const m=Array.isArray(e.grantedOrigins)?e.grantedOrigins:Array.isArray(e.grantedHosts)?e.grantedHosts:null;if(m){const s=m.filter(l=>typeof l=="string"&&l.trim()!=="");s.length>0&&(t.grantedOrigins=s)}const h=Ot(e.permissionSnapshotAt);h!=null&&(t.permissionSnapshotAt=h);const d=Ot(e.heartbeatUpdatedAt);d!=null&&(t.heartbeatUpdatedAt=d);const v=fn(e.lastRunHandoffId);v!=null&&(t.lastRunHandoffId=v);const o=Ot(e.lastRunHandoffAt);return o!=null&&(t.lastRunHandoffAt=o),t}function lv(e,t){if(!cn(e)||e.type!==t||typeof e.nonce!="string"||!e.nonce.trim()||typeof e.ok!="boolean")return null;const a={type:t,nonce:e.nonce,ok:e.ok};typeof e.error=="string"&&e.error.trim()&&(a.error=e.error.trim());const c=fn(e.handoffId);return c!=null&&(a.handoffId=c),a}function yi(e){const t=rl();if(!t)return!1;try{return t.postMessage(e),!0}catch{return!1}}function dv(e=Ge){const t=Me();return new Promise(a=>{let c=!1,m=null;const h=o=>{c||(c=!0,m!=null&&window.clearTimeout(m),window.removeEventListener("message",d),a(o))},d=o=>{if(!bi(o))return;const s=cv(o.data);!s||s.nonce!==t||h({enabled:s.enabled,settingsSupported:s.settingsSupported,archiveBrowseHosts:s.archiveBrowseHosts,...s.earnedPermissionOnboarding===!0?{earnedPermissionOnboarding:!0}:{},error:s.error,lastArchiveRunAt:s.lastArchiveRunAt,lastArchiveSaveAt:s.lastArchiveSaveAt,lastRunByHost:s.lastRunByHost,grantedOrigins:s.grantedOrigins,permissionSnapshotAt:s.permissionSnapshotAt,heartbeatUpdatedAt:s.heartbeatUpdatedAt,lastRunHandoffId:s.lastRunHandoffId,lastRunHandoffAt:s.lastRunHandoffAt})};if(window.addEventListener("message",d),!yi({type:Vy,nonce:t})){h({enabled:!1,settingsSupported:!1,error:"native_unavailable"});return}m=window.setTimeout(()=>{h({enabled:!1,settingsSupported:!1,error:"native_timeout"})},e)})}function _n(e,t,a=Ge){return new Promise(c=>{let m=!1,h=null;const d=s=>{m||(m=!0,h!=null&&window.clearTimeout(h),window.removeEventListener("message",v),c(s))},v=s=>{if(!bi(s))return;const l=lv(s.data,t);
2!l||l.nonce!==e.nonce||d(l.ok?{ok:!0,handoffId:l.handoffId}:{ok:!1,error:l.error??"native_error"})};if(window.addEventListener("message",v),!yi(e)){d({ok:!1,error:"native_unavailable"});return}h=window.setTimeout(()=>{d({ok:!1,error:"native_timeout"})},a)})}async function uv(e){const t=window.__traceShellGetAccessToken;if(typeof t!="function")return{ok:!1,error:"sign_in_required"};let a;try{a=(await t())?.accessToken?.trim()??""}catch{return{ok:!1,error:"sign_in_required"}}return a?(nn?await ol(a,nn,e):await il(a,e)).ok?{ok:!0}:{ok:!1,error:"token_share_failed"}:{ok:!1,error:"sign_in_required"}}async function vi(e,t){const a=await uv(t);return a.ok?e():a}function mv(e=Ge){return _n({type:Wy,nonce:Me()},Ky,e)}function pv(e,t=Ge,a){const c=Hy(e);if(!c)return Promise.resolve({ok:!1,error:"invalid_url"});const m=fn(a)??_i();return vi(()=>_n({type:$y,nonce:Me(),url:c,handoffId:m},Qy,t),t).then(h=>h.ok&&h.handoffId===m?{ok:!0,handoffId:m}:h.ok?{ok:!0}:h)}function hv(e,t=Ge,a){const c=fn(a)??_i();return vi(()=>_n({type:Gy,nonce:Me(),hostKind:e,handoffId:c},Xy,t),t).then(m=>m.ok&&m.handoffId===c?{ok:!0,handoffId:c}:m.ok?{ok:!0}:m)}function fv(e=Ge,t){const a=fn(t)??_i();return vi(()=>_n({type:Yy,nonce:Me(),handoffId:a},Jy,e),e).then(c=>c.ok&&c.handoffId===a?{ok:!0,handoffId:a}:c.ok?{ok:!0}:c)}function Vw({enabled:e=!0,fixtureState:t=null}={}){const[a,c]=y.useState(()=>t?za(t):e?Bo:Ga),[m,h]=y.useState("idle"),d=y.useRef(0),v=y.useRef(0),o=y.useRef(null),s=y.useCallback(()=>{o.current!=null&&(window.clearTimeout(o.current),o.current=null)},[]),l=y.useCallback(async g=>{const E=++d.current;if(t){const D=za(t);return c(D),D}if(!e)return c(Ga),Ga;g?.preserveCurrent||c(D=>({...Bo,settingsSupported:D.settingsSupported}));const w=await dv();if(E!==d.current)return null;const T=za(w);return c(T),T},[e,t]);y.useEffect(()=>{l()},[l]),y.useEffect(()=>{if(!e)return;const g=()=>{document.visibilityState!=="hidden"&&(v.current+=1,h(E=>E==="opening"?"idle":E),s(),o.current=window.setTimeout(()=>{o.current=null,l({preserveCurrent:!0})},nv))};return window.addEventListener("pageshow",g),window.addEventListener("focus",g),document.addEventListener("visibilitychange",g),()=>{window.removeEventListener("pageshow",g),window.removeEventListener("focus",g),document.removeEventListener("visibilitychange",g),s()}},[s,e,l]);const b=y.useCallback(async()=>{const g=++v.current;if(h("opening"),t)return t.settingsSupported?(g===v.current&&h("idle"),{ok:!0}):(g===v.current&&h("error"),c(w=>({...w,settingsSupported:!1})),{ok:!1,error:"settings_unsupported"});const E=await mv();return g!==v.current?E:E.ok?(h("idle"),E):(h("error"),E.error==="settings_unsupported"&&c(w=>({...w,settingsSupported:!1})),E)},[t]);return{state:a,refresh:l,openSettings:b,settingsStatus:m}}function Ww(){const[e,t]=y.useState("idle"),[a,c]=y.useState(null),[m,h]=y.useState(null),d=y.useCallback(async b=>{t("submitting"),c(null),h(null);const g=await b();if(g.ok)return t("success"),h("opened"),{ok:!0,state:"opened",...g.handoffId?{handoffId:g.handoffId}:{}};const E=g.error??"native_error";return t("error"),c(E),{ok:!1,error:E}},[]),v=y.useCallback(async(b,g)=>{const E=b.trim();return E?d(()=>pv(E,Ge,g)):(t("error"),c("missing_url"),{ok:!1,error:"missing_url"})},[d]),o=y.useCallback((b,g)=>d(()=>hv(b,Ge,g)),[d]),s=y.useCallback(b=>d(()=>fv(Ge,b)),[d]),l=y.useCallback(()=>{t("idle"),c(null),h(null)},[]);return{status:e,error:a,resultState:m,addFirstStoryUrl:v,openArchiveHome:o,openLegacyAo3Home:s,reset:l}}class In extends Error{code;constructor(t){super("The Safari extension session could not be cleared."),this.name="NativeSafariProviderClearError",this.code=t}}async function cl(e,t,a={}){if(ea()){if(!a.deviceSessionsAlreadyRemoved){const m=await sl();if(m.kind==="unavailable")throw new In(m.error);if(m.kind==="supported"&&m.provider){if(!a.revokeDeviceSession)throw new In("device_session_revoke_unavailable");try{await a.revokeDeviceSession(m.provider.sessionId)}catch{throw new In("device_session_revoke_failed")}}}const c=await ov();if(!c.ok)throw new In(c.error??"provider_clear_failed")}await e(t)}const _v={default:["h-2 w-2","shadow-[0_0_0_2px_var(--bg-app),0_0_10px_2px_color-mix(in_oklab,var(--danger-600)_48%,transparent)]"].join(" "),subtle:["h-1.5 w-1.5","shadow-[0_0_0_1px_var(--bg-app),0_0_5px_1px_color-mix(in_oklab,var(--danger-600)_3
20%,transparent)]"].join(" ")};function gv({className:e,variant:t="default","aria-label":a}){return i.jsx("span",{className:I("pointer-events-none inline-block shrink-0 rounded-full bg-[var(--danger-600)]",_v[t],e),...a?{"aria-label":a}:{"aria-hidden":!0}})}const bv=["SAVED","READING","CAUGHT_UP","PAUSED","FINISHED","DROPPED"],yv="Unknown",vv={SAVED:"Saved",READING:"Reading",CAUGHT_UP:"Caught up",PAUSED:"Paused",FINISHED:"Finished",DROPPED:"Dropped"},$w={SAVED:"planning",READING:"reading",CAUGHT_UP:"catchup",PAUSED:"paused",FINISHED:"completed",DROPPED:"dropped"};function Sv(e){return typeof e=="string"&&bv.includes(e)}function Yw(e){return e?vv[e]:yv}const xv=["complete","wip","hiatus","abandoned"],Gw={complete:"Complete",wip:"Ongoing",hiatus:"Hiatus",abandoned:"Abandoned",unknown:"Unknown"},Ev={complete:"Complete",wip:"Ongoing",hiatus:"Hiatus",abandoned:"Abandoned"};function wv(e){if(typeof e!="string")return"unknown";const t=e.toLowerCase().trim().replace(/[\s-]+/g,"_");return t==="on_hiatus"?"hiatus":xv.includes(t)?t:"unknown"}function zw(e){const t=wv(e);return t==="unknown"?e:Ev[t]}const Vo={ANY:"Any",UP:"Caught up to last seen",BEHIND:"Unread chapters available",UNKNOWN:"Unknown"};function qw(e){return e?Vo[e]:Vo.UNKNOWN}const Av=8,Kw=6,Qw=[{value:"complete",label:"It's complete",tone:"finished"},{value:"abandoned",label:"Looks abandoned",tone:"abandoned"},{value:"hiatus",label:"On hiatus",tone:"hiatus"},{value:"wip",label:"Still ongoing",tone:"caughtup"}];function Jw(e){return e.slice(0,Av)}function Rv(e=[],t=[]){const a=e.flatMap(d=>Tv(d)),c=e.length-a.length,m=kv(t),h=m?[{id:"work-state-backlog",title:m.title,meta:"Mark works as complete, abandoned, on hiatus, or still ongoing",action:"work-state-backlog",icon:"layers",section:"optional"}]:[];return{gaps:a,railItems:h,quietMaybe:null,groupedEntry:null,workStateBacklog:m,intro:"Stories from your recent reading that Trace can't sort out on its own. One tap and it's saved.",footer:"That's everything from your recent reading.",hiddenLegacyCount:c}}function Tv(e){return e.kind==="finished_unknown_work_state"?[{type:"work-state",id:e.fingerprint,suggestion:e,title:e.title||"Untitled",author:e.author,kicker:"You finished the last posted chapter",chapterLine:`${Iv(e)}. Is it complete, or just up to date?`}]:e.kind==="completed_unrated"?[{type:"evaluation",id:e.fingerprint,suggestion:e,title:e.title||"Untitled",author:e.author,kicker:"Finished · you left it blank",subline:`${e.author||"Unknown author"} · a quick mark before it fades — optional, always`,rating:e.rating}]:[]}function kv(e){if(!e.length)return null;const t=e.length;return{id:"unknown-work-state-backlog",title:`Resolve ${t} unknown work ${t===1?"state":"states"}`,heading:"Resolve unknown work states",meta:"Legacy finishes and caught-up reads",doneTitle:`${t} work ${t===1?"state":"states"} resolved`,doneBody:"Trace can now separate finished stories from caught-up works more accurately.",items:e.map(a=>({id:a.fingerprint,title:a.title||"Untitled",author:a.author??"Archive reader",chapters:ll(a)??a.progress_value,kicker:Cv(a),suggestion:a}))}}function Cv(e){return e.status==="FINISHED"?"Finished in Library / work state unknown":e.status==="CAUGHT_UP"?"Caught up in Library / work state unknown":"At the last known chapter / work state unknown"}function Xw(e){return Sv(e)?e:null}function Nv(e){return e==="complete"||e==="abandoned"?"FINISHED":"CAUGHT_UP"}function Zw(e){return Nv(e)==="FINISHED"?"Finished":"Caught up"}function eA(e){switch(e){case"complete":return"Marked complete";case"abandoned":return"Marked abandoned";case"hiatus":return"Marked on hiatus";case"wip":return"Marked ongoing"}}function ll(e){return typeof e.chapters_published=="number"?e.chapters_published:typeof e.progress_total=="number"?e.progress_total:null}function Iv(e){const t=ll(e);return t==null?"You reached the latest posted chapter":`You read all ${t} posted ${t===1?"chapter":"chapters"}`}const Ov=fe(["inline-flex items-center justify-center shrink-0","border border-border bg-surface-2 text-content-primary","transition-colors","focus-visible:outline-none focus-visible:shadow-ring","data-[disabled]:opacity-50 data-[disabled]:cursor-not-allowed","cursor-pointer","data-[checked]:bg-accent-600 data-[checked]:border-transparent data-[checked]:text-[#0b0e14]","data-[unchecked]:hover:bg-hover data-[unchecked]:hover:border-border-strong"].join(" "),{variants:{size:{sm:"h-4 w-4 roun
2ded-[4px]",md:"h-[18px] w-[18px] rounded-[5px]"}},defaultVariants:{size:"md"}}),Pv="inline-flex items-center justify-center leading-none",Lv="inline-flex items-center gap-2 select-none cursor-pointer",Dv="text-sm text-content-primary";function jv(e){return i.jsx("svg",{viewBox:"0 0 10 10",width:"10",height:"10",fill:"currentColor",...e,children:i.jsx("path",{d:"M9.1603 1.12218C9.50684 1.34873 9.60427 1.81354 9.37792 2.16038L5.13603 8.66012C5.01614 8.8438 4.82192 8.96576 4.60451 8.99384C4.3871 9.02194 4.1683 8.95335 4.00574 8.80615L1.24664 6.30769C0.939709 6.02975 0.916013 5.55541 1.19372 5.24822C1.47142 4.94102 1.94536 4.91731 2.2523 5.19524L4.36085 7.10461L8.12299 1.33999C8.34934 0.993152 8.81376 0.895638 9.1603 1.12218Z"})})}function Uv(e){return i.jsx("svg",{viewBox:"0 0 10 10",width:"10",height:"10",fill:"currentColor",...e,children:i.jsx("path",{d:"M2 4.5h6v1H2z"})})}const dl=y.forwardRef(({size:e="md",label:t,className:a,indeterminate:c,...m},h)=>{const d=i.jsx(ud,{ref:h,className:I(Ov({size:e}),a),indeterminate:c,...m,children:i.jsx(md,{className:Pv,children:c?i.jsx(Uv,{}):i.jsx(jv,{})})});return t?i.jsxs("label",{className:Lv,children:[d,i.jsx("span",{className:Dv,children:t})]}):d});dl.displayName="Checkbox";const Mv=fe(["block min-w-0","border border-border bg-surface-1 text-content-primary","placeholder:text-content-muted/60","transition-colors duration-150","hover:border-border-strong hover:bg-surface-2/50","focus-visible:outline-none focus-visible:shadow-ring","disabled:cursor-not-allowed disabled:opacity-50 disabled:hover:border-border disabled:hover:bg-surface-1","rounded-[var(--control-radius)]"].join(" "),{variants:{size:{sm:"h-8 px-2.5 text-lg sm:text-xs",md:"h-field px-3 text-lg sm:text-sm"},invalid:{true:"border-[color-mix(in_oklab,var(--danger-600)_55%,var(--border))] focus-visible:shadow-[0_0_0_1px_var(--danger-600),var(--ring)]",false:""},withRightPadding:{true:"pr-10",false:""},fullWidth:{true:"w-full",false:"w-auto"}},defaultVariants:{size:"md",invalid:!1,withRightPadding:!1,fullWidth:!0}}),ul=y.forwardRef(({className:e,size:t,invalid:a,withRightPadding:c,fullWidth:m,...h},d)=>i.jsx("input",{ref:d,className:I(Mv({size:t,invalid:a,withRightPadding:c,fullWidth:m}),e),"aria-invalid":a||void 0,...h}));ul.displayName="Input";const Fv=fe(["w-full","rounded-xl","border border-border","bg-surface-1","text-content-primary","placeholder:text-content-muted/60","px-3 py-2","text-lg leading-relaxed sm:text-sm","transition-colors","focus-visible:outline-none focus-visible:shadow-ring","disabled:opacity-50 disabled:cursor-not-allowed"].join(" "),{variants:{invalid:{true:"border-danger-600 focus-visible:shadow-[0_0_0_1px_var(--danger-600),var(--ring)]",false:""},resize:{none:"resize-none",y:"resize-y",both:"resize"}},defaultVariants:{invalid:!1,resize:"y"}}),yr=y.forwardRef(({className:e,invalid:t,resize:a,...c},m)=>i.jsx("textarea",{ref:m,className:I(Fv({invalid:t,resize:a}),e),"aria-invalid":t||void 0,...c}));yr.displayName="Textarea";const Bv=fe(["group flex min-h-24 w-full items-start gap-3 rounded-sm border p-3 text-left","bg-surface-1 text-content-primary shadow-sm","transition-colors duration-150","hover:border-border-strong hover:bg-surface-2","focus-visible:outline-none focus-visible:shadow-ring","data-[pressed]:border-[color-mix(in_oklab,var(--library-primary)_42%,var(--border))]","data-[pressed]:bg-[color-mix(in_oklab,var(--library-primary)_9%,var(--surface-1))]"].join(" ")),Wo=["mt-0.5 inline-flex h-9 w-9 shrink-0 items-center justify-center rounded-sm","border border-border bg-surface-2 text-content-secondary","group-data-[pressed]:border-[color-mix(in_oklab,var(--library-primary)_34%,var(--border))]","group-data-[pressed]:bg-[color-mix(in_oklab,var(--library-primary)_12%,var(--surface-2))]","group-data-[pressed]:text-content-primary","[&_svg]:h-5 [&_svg]:w-5"].join(" "),$o=[{value:"permissions_missing",label:"I couldn't find Permissions or Other Websites"},{value:"toolbar_missing",label:"I couldn't find Trace in Safari"},{value:"verification_failed",label:"Everything said Allow, but Trace still failed"},{value:"other",label:"Something else"}],ml=y.createContext({openFeedback:()=>{}});function pl(){return y.useContext(ml)}function hl({children:e}){const[t,a]=y.useState(!1),[c,m]=y.useState({mode:"default"}),h=y.useMemo(()=>({openFeedback:d=>{m(d?.mode==="setup"?d:{mode:"default"}),a(!0)}}),[]);return i.jsxs(ml.Provider,{value:h,children:[e,i.jsx(Wv,{open:t,onOpenChange:a,options:c})]})}const Hv=[{value:"bug",label:"Bug",description:"Something broke, behaved oddly, or doesn't seem right.",icon:i.jsx(yd,{"aria-hidden":!0})},{value:"improvement",label:"Feature request",description:"Anything new or improved that would make Trace better.",icon:i.jsx(vd,{"aria-hidden":!0})},{value:"other",label:"Other",description:"Anything else.",icon:i.jsx(rn,{"aria-hidden":!0})}];function Vv(e,t){return{route:e,client_timestamp:new Date().toISOString(),viewport:{width:Math.max(0,Math.round(window.innerWidth||0)),height:Math.max(0,Math.round(window.innerHeight||0))},user_agent:navigator.userAgent||"unknown",theme:t,is_ios_shell:F()}}function Wv({open:e,onOpenChange:t,options:a}){const c=_e(),m=Te(),{preference:h}=Or(),[d,v]=y.useState("other"),[o,s]=y.useState(""),[l,b]=y.useState(null),[g,E]=y.useState(!1),[w,T]=y.useState(""),[D,R]=y.useState(!1),[k,W]=y.useState(null),X=Xt({mutationFn:j=>c.submitFeedback(j),onSuccess:()=>{R(!0),s(""),E(!1),T(""),W(null)},onError:j=>{W(j instanceof Error?j.message:"Could not send feedback.")}}),Z=X.reset;y.useEffect(()=>{e||(v("other"),s(""),b(null),E(!1),T(""),R(!1),W(null),Z())},[e,Z]);const K=o.trim(),ce=a.mode==="setup",qe=$o.find(j=>j.value===l),gn=ce?[`Setup issue (${a.setupState}): ${qe?.label??"Unknown"}
2`,K].filter(Boolean).join(`
3
4`):K,Ht=w.trim(),ge=/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(Ht),wt=c.isReady&&(ce?l!=null&&(l!=="other"||K.length>=5):K.length>=5)&&(!g||ge);function xe(){t(!1)}function Q(){!wt||X.isPending||X.mutate({type:ce?"bug":d,message:gn,follow_up_ok:g,contact_email:g?Ht:null,context:Vv(m.pathname||"/",h)})}return i.jsx(pd,{open:e,onOpenChange:t,children:i.jsxs(hd,{children:[i.jsx(fd,{className:"fixed inset-0 z-[4000] bg-black/40 backdrop-blur-sm transition-opacity data-[ending-style]:opacity-0 data-[starting-style]:opacity-0"}),i.jsxs(_d,{className:"fixed left-1/2 top-1/2 z-[4000] max-h-[calc(100dvh_-_2rem_-_env(safe-area-inset-top)_-_env(safe-area-inset-bottom))] w-[calc(100vw_-_2rem)] max-w-2xl -translate-x-1/2 -translate-y-1/2 overflow-y-auto overscroll-contain rounded border border-border bg-surface-1 p-4 shadow-xl [-webkit-overflow-scrolling:touch] sm:p-6",children:[i.jsxs("div",{className:"flex items-start justify-between gap-4",children:[i.jsxs("div",{className:"min-w-0",children:[i.jsx(gd,{className:"text-lg font-semibold text-content-primary",children:ce?"What went wrong during setup?":"Send feedback"}),i.jsx(bd,{className:"mt-1 text-sm text-content-muted",children:ce?"Choose the closest option. You only need to type for Something else.":"Tell us what broke, what would help, or what is already working."})]}),i.jsx(yt,{type:"button",variant:"ghost",size:"sm","aria-label":"Close feedback",title:"Close feedback",onClick:xe,children:i.jsx(os,{className:"h-5 w-5","aria-hidden":!0})})]}),D?i.jsxs("div",{className:"mt-6 rounded-sm border border-border bg-surface-2 p-4",children:[i.jsxs("div",{className:"flex items-start gap-3",children:[i.jsx("span",{className:Wo,children:i.jsx(rn,{className:"h-5 w-5","aria-hidden":!0})}),i.jsxs("div",{className:"min-w-0",children:[i.jsx("p",{className:"font-medium text-content-primary",children:"Feedback sent."}),i.jsx("p",{className:"mt-1 text-sm text-content-muted",children:"Thanks. We will review it soon."})]})]}),i.jsx("div",{className:"mt-5 flex justify-end",children:i.jsx(L,{variant:"solid",size:"lg",onClick:xe,children:"Done"})})]}):i.jsxs("div",{className:"mt-5 space-y-5",children:[ce?i.jsxs("div",{children:[i.jsx(Bi,{value:l?[l]:[],onValueChange:j=>{const pt=j[0];b(pt??null),pt!=="other"&&s("")},className:"grid gap-2 sm:grid-cols-2",role:"group","aria-label":"Where did setup stop?",children:$o.map(j=>i.jsx(Hi,{type:"button",value:j.value,className:"min-h-11 rounded-sm border border-border bg-surface-1 px-3 py-2.5 text-left text-sm font-medium leading-5 text-content-primary transition-colors hover:border-border-strong hover:bg-surface-2 focus-visible:outline-none focus-visible:shadow-ring data-[pressed]:border-[color-mix(in_oklab,var(--forest)_40%,var(--border))] data-[pressed]:bg-[color-mix(in_oklab,var(--forest)_8%,var(--surface-1))]",children:j.label},j.value))}),l==="other"?i.jsxs("div",{className:"mt-4",children:[i.jsx("label",{htmlFor:"setup-feedback-message",className:"text-sm font-medium text-content-primary",children:"What happened?"}),i.jsx(yr,{id:"setup-feedback-message",value:o,onChange:j=>s(j.target.value),rows:4,maxLength:4e3,className:"mt-2 min-h-28 rounded-sm text-sm",placeholder:"Tell us where setup stopped."}),i.jsx("p",{className:"mt-1 text-xs text-content-muted",children:K.length<5?"Add at least 5 characters.":`${o.length}/4000`})]}):null,i.jsx("p",{className:"mt-3 text-xs leading-5 text-content-muted",children:"Trace includes this 
4setup step, app version, and device type—never story content."})]}):i.jsxs(i.Fragment,{children:[i.jsxs("div",{children:[i.jsx("label",{className:"text-sm font-medium text-content-primary",children:"Type"}),i.jsx(Bi,{value:[d],onValueChange:j=>{const pt=j[0];pt&&v(pt)},className:"mt-2 grid gap-2 sm:grid-cols-2",role:"group","aria-label":"Feedback type",children:Hv.map(j=>i.jsxs(Hi,{type:"button",value:j.value,"aria-label":j.label,className:Bv(),children:[i.jsx("span",{className:Wo,children:i.jsx("span",{className:"h-5 w-5",children:j.icon})}),i.jsxs("span",{className:"min-w-0",children:[i.jsx("span",{className:"block text-sm font-semibold leading-snug",children:j.label}),i.jsx("span",{className:"mt-1 block text-xs leading-relaxed text-content-muted",children:j.description})]})]},j.value))})]}),i.jsxs("div",{children:[i.jsx("label",{htmlFor:"feedback-message",className:"text-sm font-medium text-content-primary",children:"Message"}),i.jsx(yr,{id:"feedback-message",value:o,onChange:j=>s(j.target.value),rows:6,maxLength:4e3,className:"mt-2 min-h-40 rounded-sm text-sm",placeholder:"What happened, what would make this better, or what should we keep doing?"}),i.jsx("p",{className:"mt-1 text-xs text-content-muted",children:K.length<5?"Add at least 5 characters.":`${o.length}/4000`})]})]}),ce?null:i.jsx(dl,{checked:g,onCheckedChange:j=>E(j===!0),label:"I'm happy to be emailed with follow-up questions or responses."}),!ce&&g?i.jsxs("div",{children:[i.jsx("label",{htmlFor:"feedback-contact-email",className:"text-sm font-medium text-content-primary",children:"Email for follow-up"}),i.jsx(ul,{id:"feedback-contact-email",type:"email",value:w,onChange:j=>T(j.target.value),maxLength:320,className:"mt-2 text-sm",placeholder:"[email protected]",autoComplete:"email"}),i.jsx("p",{className:"mt-1 text-xs text-content-muted",children:"Stored with this feedback submission only."})]}):null,k?i.jsx("p",{className:"text-sm text-[var(--library-danger)]",children:k}):null,i.jsxs("div",{className:"flex flex-wrap justify-end gap-2",children:[i.jsx(L,{type:"button",variant:"ghost",size:"lg",onClick:xe,disabled:X.isPending,children:"Cancel"}),i.jsx(L,{type:"button",variant:"solid",size:"lg",onClick:Q,disabled:!wt||X.isPending,loading:X.isPending,children:X.isPending?"Sending...":ce?"Send report":"Send feedback"})]})]})]})]})})}const $v=["sticky top-0 z-[1200] hidden shrink-0 flex-col bg-[var(--paper)] text-[var(--ink)] max-sm:flex"].join(" "),Yv="h-[max(env(safe-area-inset-top),44px)] shrink-0 bg-[var(--paper)]",Gv="hidden h-[max(env(safe-area-inset-top),44px)] shrink-0 bg-[var(--paper)] max-sm:block",zv="h-0 shrink-0 bg-[var(--paper)]",qv=["pointer-events-none fixed inset-x-0 top-0 z-[1200] hidden","h-[max(env(safe-area-inset-top),44px)] max-sm:block","before:absolute before:inset-x-0 before:top-0 before:bottom-[-16px] before:content-['']","before:bg-[linear-gradient(to_bottom,var(--paper)_0%,var(--paper)_42%,color-mix(in_oklab,var(--paper)_55%,transparent)_72%,transparent_100%)]","before:backdrop-blur-[8px] before:[mask-image:linear-gradient(to_bottom,#000_50%,transparent)]"].join(" "),Kv=["flex h-11 min-h-[44px] shrink-0 items-center justify-between","border-b border-[var(--line)] bg-[var(--paper)] py-0 pl-[
418px] pr-2"].join(" "),Qv=["inline-flex min-h-[44px] min-w-0 max-w-full items-center gap-2 border-0 bg-transparent py-2 pl-0 pr-1.5","font-mono text-[10.5px] font-medium uppercase tracking-[0.22em]","text-[var(--ink-3)] transition-colors hover:text-[var(--ink)]","focus-visible:outline-none focus-visible:shadow-[0_0_0_3px_color-mix(in_oklab,var(--honey)_22%,transparent)]","[&>span]:min-w-0 [&>span]:truncate [&>svg]:h-[15px] [&>svg]:w-[15px] [&>svg]:shrink-0"].join(" "),Jv="ml-auto flex min-h-[44px] items-center justify-end",Xv=["flex h-9 min-h-[36px] shrink-0 items-center justify-between","border-b border-[var(--line)] bg-[var(--paper)] px-[18px]"].join(" "),Zv=["inline-flex min-w-0 items-center gap-2.5","font-mono text-[10.5px] font-medium uppercase tracking-[0.22em]","text-[var(--ink-3)]"].join(" "),eS="h-px w-3 shrink-0 rounded-full bg-[var(--rust)] opacity-85";function tS(e){const t=e.trim().toLowerCase();return t&&t.split(/[?#]/)[0]||"/"}function nS(e){const t=tS(e);return t==="/"||t==="/library"||t==="library"||t==="my library"?{kind:"masthead"}:t.startsWith("/library/")?{kind:"detail",backLabel:"Library",parentHref:"/"}:t==="/collections"?{kind:"masthead"}:t.startsWith("/collections/")?{kind:"detail",backLabel:"Collections",parentHref:"/collections"}:t==="/suggestions"||t==="/stats"?{kind:"masthead"}:t==="/setup"||t==="/apps"?{kind:"tool",label:"Setup"}:t==="/updates"?{kind:"tool",label:"Updates"}:t==="/watches"?{kind:"tool",label:"Story updates"}:t==="/settings"?{kind:"tool",label:"Account"}:t==="/import"?{kind:"tool",label:"Import"}:t==="/admin"?{kind:"tool",label:"Admin"}:{kind:"tool",label:"Trace"}}function aS({config:e,className:t,endSlot:a,onBack:c,reserveSafeArea:m="browser"}){return e.kind==="none"?null:e.kind==="masthead"?m==="browser"?null:i.jsxs(i.Fragment,{children:[i.jsx("div",{"aria-hidden":"true",className:I(qv,t),"data-mobile-top-chrome":"masthead"}),i.jsx("div",{className:Gv,"aria-hidden":"true"})]}):i.jsxs("div",{className:I($v,t),"data-mobile-top-chrome":e.kind,children:[i.jsx("div",{className:m==="native"?Yv:zv,"aria-hidden":"true"}),e.kind==="detail"?i.jsxs("div",{className:Kv,"data-mobile-top-chrome-bar":"detail",children:[i.jsxs("button",{"aria-label":`Back to ${e.backLabel}`,className:Qv,onClick:c,type:"button",children:[i.jsx(Sd,{"aria-hidden":"true"}),i.jsx("span",{children:e.backLabel})]}),a?i.jsx("div",{className:Jv,children:a}):null]}):i.jsx("div",{className:Xv,"data-mobile-top-chrome-bar":"tool",children:i.jsxs("span",{className:Zv,children:[i.jsx("span",{className:eS,"aria-hidden":"true"}),i.jsx("span",{children:e.label})]})})]})}const fl="(display-mode: standalone)";function rS(){return typeof window>"u"||!window.matchMedia?!1:window.matchMedia(fl).matches}function iS(){return typeof navigator>"u"?!1:navigator.standalone===!0}function qa(){return F()||rS()||iS()?"app":"browser"}function _l(){const[e,t]=y.useState(()=>qa());return y.useEffect(()=>{if(t(qa()),typeof window>"u"||!window.matchMedia)return;const a=window.matchMedia(fl),c=()=>t(qa());return a.addEventListener?(a.addEventListener("change",c),()=>a.removeEventListener("change",c)):(a.addListener(c),()=>a.removeListener(c))},[]),e}const oS=fe(["sticky top-0 z-[1200] overflow-visible","border-b border-border","bg-[color-mix(in_oklab,var(--bg-1)_94%,transparent)]","backdrop-blur-md backdrop-saturate-[1.1]"].join(" "),{variants:{transparent:{true:"bg-transparent border-transparent backdrop-blur-0",false:""},variant:{default:"",archive:"border-transparent bg-[var(--paper)] pt-[env(safe-area-inset-top)] max-sm:shrink-0"},compactNativeShell:{true:"border-[color-mix(in_oklab,var(--library-outline)_16%,transparent)] bg-[color-mix(in_oklab,var(--library-surface-lowest)_88%,var(--library-bg))] py-0 shadow-[0_1px_0_color-mix(in_oklab,var(--library-outline)_10%,transparent)]",false:""}},defaultVariants:{transparent:!1,variant:"default",compactNativeShell:!1}}),sS=fe("mx-auto flex items-center gap-3 overflow-visible",{variants:{variant:{default:"max-w-[1360px] px-3.5",archive:"w-full px-4 sm:px-[22px]"},compactNativeShell:{true:"h-11 min-h-[44px]",false:"h-[60px]"}},compoundVariants:[{variant:"default",compactNativeShell:!0,class:"px-3"},{variant:"archive",compactNativeShell:!0,class:"!h-12 !min-h-[48px] !px-4 sm:!px-[22px]"},{variant:"archive",compactNativeShell:!1,class:"max-sm:!h-11 max-sm:!min-h-[44px] max-sm:!px-3"}],defaultVariants:{variant:"default",compactNativeShell:!1}}),cS=fe(["inline-flex min-w-0 items-center overflow-visible no-underline","shrink-0"].join(" "),{variants:{variant:{default:"gap-3",archive:"gap-2"}},defaultVariants:{variant:"default"}}),lS=fe("w-auto block",{variants:{variant:{default:"",archive:"rounded-[6px]"},compactNativeShell:{true:"h-7",false:"h-7"}},compoundVariants:[{variant:"default",compactNativeShell:!0,class:"h-9 rounded-sm"},{variant:"default",compactNativeShell:!1,class:"h-10 rounded"}],defaultVariants:{variant:"default",compactNativeShell:!1}}),dS=fe(["inline-block min-w-0 max-w-full truncate"].join(" "),{variants:{variant:{default:["text-[18px] sm:text-[20px]","font-bold tracking-[-0.02em]","text-content-primary opacity-95"].join(" "),archive:["font-landing-serif text-[21px] font-medium italic leading-none tracking-normal max-sm:text-[19px]","text-[var(--ink)]"].join(" ")}},defaultVariants:{variant:"default"}}),uS="ml-8 hidden sm:flex items-center gap-[22px]",mS="relative inline-flex items-center border-0 bg-transparent px-0.5 py-1.5 font-landing-sans text-[13.5px] font-normal tracking-normal text-[var(--ink-3)] transition-colors duration-200 hover:text-[var(--ink)]",pS="text-[var(--ink)] after:absolute after:bottom-[-2px] after:left-0.5 after:right-0.5 after:h-px after:rounded-full after:bg-[var(--rust)] after:opacity-70",hS=["f
4ixed inset-x-0 top-0 z-[1300] hidden h-[54px] shrink-0 grid-cols-[minmax(0,1fr)_auto_auto] items-center gap-2","border-b border-[var(--line)] bg-[color-mix(in_oklab,var(--paper)_93%,transparent)] px-3 text-[var(--ink)]","backdrop-blur-[16px] backdrop-saturate-[1.05]","shadow-[0_8px_20px_-18px_rgba(0,0,0,0.45)]","max-sm:grid motion-reduce:transition-opacity motion-reduce:duration-[80ms]"].join(" "),fS="grid-cols-[minmax(0,1fr)_auto_auto_auto]",_S="hidden h-[54px] shrink-0 bg-[var(--paper)] max-sm:block",gS=["inline-flex min-w-0 items-center gap-2 overflow-visible no-underline","rounded-sm py-1 pr-1 text-[var(--ink)]","focus-visible:outline-none focus-visible:shadow-[0_0_0_3px_color-mix(in_oklab,var(--honey)_26%,transparent)]"].join(" "),bS="block h-7 w-auto shrink-0 rounded-[7px]",yS="min-w-0 truncate font-landing-serif text-[20px] font-medium italic leading-none tracking-normal text-[var(--ink)]",vS=["inline-flex h-9 w-9 items-center justify-center overflow-hidden rounded-sm border border-[var(--line)]","bg-[var(--card-sunk,var(--paper-2))] text-[var(--rust)]","transition-[opacity,color,background-color,border-color] duration-150","hover:border-[var(--line-strong)] hover:bg-[var(--paper-2)]","disabled:cursor-default","focus-visible:outline-none focus-visible:shadow-[0_0_0_3px_color-mix(in_oklab,var(--honey)_26%,transparent)]"].join(" "),SS="pointer-events-none w-0 border-transparent p-0 opacity-0",xS="inline-flex items-center gap-1",ES=["inline-flex h-9 min-w-[4.75rem] items-center justify-between gap-1.5 rounded-sm","border border-[var(--line)] bg-[var(--card-sunk,var(--paper-2))] px-2 py-1 text-left","text-[var(--ink-2)] transition-colors duration-150","hover:border-[var(--line-strong)] hover:bg-[var(--paper-2)] hover:text-[var(--ink)]","aria-expanded:border-[var(--line-strong)] aria-expanded:bg-[var(--paper-2)] aria-expanded:text-[var(--ink)]","focus-visible:outline-none focus-visible:shadow-[0_0_0_3px_color-mix(in_oklab,var(--honey)_26%,transparent)]"].join(" "),wS="block max-w-full truncate font-landing-sans text-[12.5px] font-medium leading-none tracking-normal",AS="inline-flex shrink-0 items-center gap-0.5 text-[var(--ink-3)]",RS=["fixed inset-x-0 bottom-0 z-[1300] sm:hidden","grid min-h-[calc(60px_+_env(safe-area-inset-bottom))] grid-cols-5 items-start overflow-hidden","border-t border-[var(--line)]","bg-[color-mix(in_oklab,var(--paper)_94%,transparent)] px-2 pb-[max(12px,env(safe-area-inset-bottom))] pt-2","text-[var(--ink-4)]","shadow-[0_-10px_24px_-22px_rgba(0,0,0,0.58)]","backdrop-blur-[12px] backdrop-saturate-[1.04]","[--mobile-dock-duration:420ms] transition-[transform,translate,opacity] duration-[var(--mobile-dock-duration)] ease-[cubic-bezier(.25,.8,.25,1)] will-change-transform","motion-reduce:transition-opacity motion-reduce:duration-[80ms]"].join(" "),TS="",kS="[--mobile-dock-duration:420ms]",CS="translate-y-[calc(100%_+_4px)] opacity-[0.94] motion-reduce:translate-y-0 motion-reduce:opacity-0",Yo=["relative flex min-w-0 flex-col items-center justify-start gap-1","border-0 bg-transparent px-1 py-1 text-[var(--ink-4)] no-underline","font-landing-sans text-micro leading-tight tracking-normal","transition-colors duration-150 hover:text-[var(--ink-2)]","focus-visible:z-10 focus-visible:outline-none focus-visible:shadow-[inset_0_0_0_2px_color-mix(in_oklab,var(--honey)_32%,transparent)]"].join(" "),Go=["[&>span:first-child]:text-[var(--rust)]","[&>span:last-child]:text-[var(--ink-2)]"].join(" "),zo="relative inline-flex h-[23px] w-[23px] items-center justify-center",qo="block w-full truncate text-center",NS="absolute right-[1px] top-0 h-1.5 w-1.5 rounded-full bg-[var(--rust)] outline outline-2 outline-[var(--paper)]",IS="fixed inset-0 z-[1300] border-0 bg-[rgba(0,0,0,0.42)] p-0 sm:hidden",OS=["fixed inset-x-0 bottom-0 z-[1310] sm:hidden","rounded-t-[22px] border-t border-[var(--line-strong)] bg-[var(--paper-2)]","pb-[calc(24px_+_env(safe-area-inset-bottom))] pt-2 text-[var(--ink)]","shadow-[0_-18px_32px_-18px_rgba(0,0,0,0.55)]"].join(" "),PS="pb-3 pt-1",LS="h-1 w-9 rounded-full bg-[var(--ink-5)] opacity-50",Ka="grid px-1.5",et=["grid min-h-[58px] grid-cols-[36px_minmax(0,1fr)_auto] items-center gap-x-3","rounded-sm border-0 bg-transparent px-4 py-2 text-left text-[var(--ink)] no-underline","font-landing-sans text-[15px] transition-colors hover:bg-[var(--paper-3)]","focus-visible:outline-none focus-visible:shadow-[0_0_0_3px_color-mix(in_oklab,var(--honey)_22%,transparent)]"].join(" "),On="bg-[color-mix(in_oklab,var(--honey)_12%,transparent)] text-[var(--ink)] [&>span:first-child]:text-[var(--honey)]",tt="relative inline-flex h-9 w-9 items-center justify-center text-[var(--ink-3)] [&>svg]:h-[18px] [&>svg]:w-[18px]",DS="absolute right-1 top-1 h-1.5 w-1.5 rounded-full bg-[var(--rust)] outline outline-2 outline-[var(--paper-2)]",nt="grid min-w-0 gap-0.5",at="truncate text-[var(--ink)]",Pn="truncate font-mono text-[10px] uppercase tracking-[0.16em] text-[var(--ink-4)]",jS="font-mono text-[11px] uppercase tracking-[0.08em] text-[var(--ink-3)]",US="[&>span:first-child]:text-[var(--rust)] [&>span:nth-child(2)>span:first-child]:text-[var(--rust)]",Ko="mx-[22px] my-1.5 h-px bg-[var(--line)]",MS="flex justify-between px-[22px] pt-3 font-mono text-[10px] uppercase tracking-[0.22em] text-[var(--ink-4)]",FS=["ml-auto","flex items-center justify-end gap-3 max-sm:gap-2","min-w-[88px]"].join(" "),BS=["h-8 w-8 rounded-full","border border-border","bg-surface-2","animate-pulse"].join(" "),HS="relative",VS="!h-auto min-h-0 rounded-full !border-[var(--honey,var(--accent-archive-gold,var(--accent-gold)))] !bg-[color-mix(in_oklab,var(--honey,var(--accent-archive-gold,var(--accent-gold)))_8%,transparent)] px-3 py-1.5 font-landing-sans !text-[12.5px] !font-medium leading-none !text-[var(--honey,var(--accent-archive-gold,var(--accent-gold)))] shadow-none hover:!border-[var(--honey,var(--accent-archive-gold,var(--accent-gold)))] hover:!bg-[color-mix(in_oklab,var(--honey,var(--accent-archive-gold,var(--accent-gold)))_12%,transparent)] active:!bg-[color-mix(in_oklab,var(--honey,var(--accent-archive-gold,var(--accent-gold)))_14%,transparent)] focu
4s-visible:!shadow-[0_0_0_3px_color-mix(in_oklab,var(--honey,var(--accent-archive-gold,var(--accent-gold)))_22%,transparent)] max-sm:px-2.5",WS="inline-block h-1.5 w-1.5 rounded-full bg-[var(--honey,var(--accent-archive-gold,var(--accent-gold)))]",Qo="!h-8 !w-8 !rounded-xs !border-0 !bg-transparent !p-0 !font-landing-sans !text-[var(--ink-3,var(--content-muted))] shadow-none hover:!bg-[var(--paper-2,var(--surface-2))] hover:!text-[var(--ink,var(--content-primary))] active:!bg-[var(--paper-3,var(--surface-2))] aria-expanded:!bg-[var(--paper-2,var(--surface-2))] focus-visible:!shadow-[0_0_0_3px_color-mix(in_oklab,var(--honey,var(--accent-archive-gold,var(--accent-gold)))_22%,transparent)]",$S="!h-[30px] !w-[30px] !rounded-full !border-0 !bg-[var(--forest-deep,var(--accent-700))] !p-[2px] !text-[var(--paper,var(--surface-1))] shadow-none hover:!bg-[var(--forest,var(--accent-600))] active:!bg-[var(--forest-deep,var(--accent-700))] aria-expanded:!bg-[var(--forest-deep,var(--accent-700))] focus-visible:!shadow-[0_0_0_3px_color-mix(in_oklab,var(--honey,var(--accent-archive-gold,var(--accent-gold)))_22%,transparent)]",YS=fe(["absolute right-0 top-[calc(100%+8px)] z-[1300]","min-w-[200px] p-1"].join(" "),{variants:{variant:{default:["rounded-2xl border border-border bg-surface-1","shadow-[0_18px_50px_rgba(0,0,0,0.35)]"].join(" "),archive:["rounded-[12px] border border-[var(--line-strong)]","bg-[var(--card)] text-[var(--ink)]","shadow-[var(--shadow-modal)]","max-sm:fixed max-sm:left-3 max-sm:right-3 max-sm:top-[calc(env(safe-area-inset-top)+3.75rem)] max-sm:min-w-0 max-sm:p-2","[&_button]:rounded-[6px] [&_button]:px-[14px] [&_button]:py-[9px]","[&_button]:font-landing-sans [&_button]:text-[13.5px] [&_button]:font-medium [&_button]:text-[var(--ink-2)]","[&_button:hover]:bg-[var(--paper-2)] [&_button:hover]:text-[var(--ink)]","[&_a]:rounded-[6px] [&_a]:px-[14px] [&_a]:py-[9px]","[&_a]:font-landing-sans [&_a]:text-[13.5px] [&_a]:font-medium [&_a]:text-[var(--ink-2)]","[&_a:hover]:bg-[var(--paper-2)] [&_a:hover]:text-[var(--ink)]"].join(" ")}},defaultVariants:{variant:"default"}}),GS=fe("my-1 mx-1 h-px rounded",{variants:{variant:{default:"bg-border",archive:"bg-[color-mix(in_oklab,var(--library-outline,#42494e)_35%,transparent)]"}},defaultVariants:{variant:"default"}}),zS=["inline-flex h-full w-full items-center justify-center","rounded-full bg-[var(--paper,var(--surface-1))]","text-xs font-semibold text-[var(--forest-deep,var(--accent-700))]"].join(" "),qS=["bg-white text-[#0b0e14] border-transparent","shadow-[0_6px_24px_rgba(0,0,0,0.25)]","hover:brightness-[0.98]"].join(" ");function KS(e,t){const c=(e||t||"").trim().split(/\s+/).slice(0,2);return c.length?c.map(m=>m[0]?.toUpperCase()).join(""):"TR"}const Qa=["light","dark","system"],QS={light:rs,dark:is,system:xd},Ja={light:"Theme: Light (click for Dark)",dark:"Theme: Dark (click for System)",system:"Theme: System (click for Light)"},JS=!1;y.lazy(async()=>({default:(await M(()=>import("./story-updates-surfaces.component-fW5MaEt7.js"),__vite__mapDeps([5,1,3,6,7,8,9,2,10]))).StoryUpdatesInboxContent}));y.lazy(async()=>({default:(await M(()=>import("./story-updates-surfaces.component-fW5MaEt7.js"),__vite__mapDeps([5,1,3,6,7,8,9,2,10]))).StoryUpdatesInboxLauncher}));const XS=[{href:"/",label:"My Library",hasSuggestionDot:!1},{href:"/collections",label:"Collections",hasSuggestionDot:!1},{href:"/suggestions",label:"Check-in",hasSuggestionDot:!0},{href:"/stats",label:"Stats",hasSuggestionDot:!1},{href:"/setup",label:"Setup",hasSuggestionDot:!1},{href:"/updates",label:"Updates",hasSuggestionDot:!1}],vr=[{id:"library",href:"/",label:"Library",icon:as},{id:"collections",href:"/collections",label:"Collections",icon:Ad},{id:"checkin",href:"/suggestions",label:"Check-in",icon:Rd,hasSuggestionDot:!0},{id:"stats",href:"/stats",label:"Stats",icon:Td}],ZS=64,ex=2,tx=4,nx=36,ax=48,rx=10,ix=14,gl=56,ox=160,sx=250,xa="window",cx={library:()=>M(()=>import("./MyStories-DPVKcTCZ.js"),__vite__mapDeps([11,1,12,2,3,13,14,15,7,16,17,18,19,20,21,8,9,6,22,4])),collections:()=>M(()=>import("./index-FJnU_1X8.js"),__vite__mapDeps([23,1,2,3,15,12,7,18,16,17,20,13,14,4])),checkin:()=>M(()=>import("./SuggestionsPage-BGApgL5t.js"),__vite__mapDeps([24,1,2,3,17,21])),stats:()=>M(()=>import("./StatsPage-lvfyK-zQ.js"),__vite__mapDeps([25,1,2,12,3,16,17]))},Xa=new Set;function gt(e){Xa.has(e)||(Xa.add(e),cx[e]().catch(()=>{Xa.delete(e)}))}function lx(e){y.useEffect(()=>{if(!e)return;const t=()=>{vr.forEach(c=>gt(c.id))},a=window.setTimeout(t,250);return()=>window.clearTimeout(a)},[e])}function ta(e){return e.trim().toLowerCase()}function dx(e){const t=ta(e);return t==="/"||t==="/library"||t.startsWith("/library/")||t==="my library"||t==="library"?"library":t==="/collections"||t.startsWith("/collections/")?"collections":t==="/suggestions"?"checkin":t==="/stats"?"stats":t==="/setup"||t==="/apps"||t==="/updates"||t==="/settings"||t==="/watches"?"more":"library"}function ux(e){return ta(e).split(/[?#]/)[0]||"/"}function Ln(e,t){const a=ux(e);return t==="/"?a==="/"||a==="/library"||a.startsWith("/library/")||a==="my library"||a==="library":t==="/collections"?a==="/collections"||a.startsWith("/collections/"):t==="/setup"?a==="/setup"||a==="/apps":a===t}
4function mx({enabled:e,resetKey:t,scrollContainerSelector:a}){const[c,m]=y.useState(!1);return y.useEffect(()=>{m(!1)},[t]),y.useEffect(()=>{if(!e)return;const h=()=>m(!1),d=()=>{document.visibilityState==="visible"&&h()};return window.addEventListener("focus",h),window.addEventListener("pageshow",h),document.addEventListener("visibilitychange",d),()=>{window.removeEventListener("focus",h),window.removeEventListener("pageshow",h),document.removeEventListener("visibilitychange",d)}},[e]),y.useEffect(()=>{if(!e){m(!1);return}const h=a===xa,d=h?window:document.querySelector(a);if(!d)return;const v=h?tx:ex,o=h?ax:nx,s=h?ix:rx,l=()=>{const R=h?window.scrollY||document.documentElement.scrollTop||document.body.scrollTop||0:d.scrollTop;return Math.max(0,R)};let b=l(),g=0,E=0;const w=()=>{g=0,E=0,m(!1)},T=()=>{g=0,E=0,m(!0)},D=()=>{const R=l(),k=R-b;if(b=R,R<=ZS){w();return}if(!(Math.abs(k)<v)){if(k>0){g+=k,E=0,g>=o&&T();return}E+=Math.abs(k),g=0,E>=s&&w()}};return d.addEventListener("scroll",D,{passive:!0}),()=>{d.removeEventListener("scroll",D)}},[e,t,a]),{tucked:c,setTucked:m}}function px({enabled:e,resetKey:t,scrollContainerSelector:a}){const[c,m]=y.useState(!1);return y.useEffect(()=>{m(!1)},[t]),y.useEffect(()=>{if(!e){m(!1);return}const h=a===xa,d=h?window:document.querySelector(a);if(!d)return;const v=()=>{const s=h?window.scrollY||document.documentElement.scrollTop||document.body.scrollTop||0:d.scrollTop;return Math.max(0,s)},o=()=>{const s=v();if(s<=gl){m(!1);return}m(s>ox)};return d.addEventListener("scroll",o,{passive:!0}),()=>d.removeEventListener("scroll",o)},[e,t,a]),{scrolledFromTop:c,setScrolledFromTop:m}}function Jo(e){const t=window.matchMedia?.("(prefers-reduced-motion: reduce)").matches?"auto":"smooth",a={top:0,behavior:t},c=()=>{typeof window.scrollTo=="function"&&window.scrollTo({top:0,behavior:"auto"}),document.documentElement.scrollTop=0,document.body.scrollTop=0};if(e===xa){typeof window.scrollTo=="function"?window.scrollTo(a):(document.documentElement.scrollTop=0,document.body.scrollTop=0),t==="smooth"&&window.setTimeout(()=>{(window.scrollY||document.documentElement.scrollTop||document.body.scrollTop||0)>gl&&c()},sx);return}
4const m=document.querySelector(e);if(!m){typeof window.scrollTo=="function"&&window.scrollTo(a);return}if(typeof m.scrollTo=="function"){m.scrollTo(a);return}m.scrollTop=0}function bl({title:e="trace",transparent:t=!1,variant:a="default",compactNativeShell:c=!1,mobileScrollContainerSelector:m="[data-app-shell-scroll]",mobileDockHidden:h=!1,mobilePrimaryNavHidden:d=!1,mobileNavigationChassis:v,mobileBrowserActions:o,mobileBrowserActionsVisible:s=!1,archivePreview:l}){const b="/trace-mark.svg",g=Te(),E=na(),{pathname:w}=g,T=A=>{const U=l?.activeHref??w;return A==="/"?U==="/"||U==="/library"||ta(U).startsWith("/library/")||ta(U)==="my library":U===A||U.startsWith(`${A}/`)},{isAuthenticated:D,isLoading:R,user:k,loginWithRedirect:W,logout:X}=ke(),Z=_e(),{preference:K,setPreference:ce}=Or(),{openFeedback:qe}=pl(),gn=QS[K],[Ht,ge]=y.useState(!1),wt=y.useRef(null),[xe,Q]=y.useState(!1),[j,pt]=y.useState(!1),bn=y.useRef(null),At=y.useRef(null),Ea=y.useRef(!1),[Vt,Ri]=y.useState(!1),[yn,Ti]=y.useState(null),ki=()=>{if(Vt)return;const A=F();Ti(null),Ri(!0),(async()=>{try{await cl(X,ms(),{revokeDeviceSession:Z.revokeExtensionDeviceSession}),ge(!1),Q(!1),A&&E("/",{replace:!0})}catch(U){console.error("Failed to sign out",U),Ti("Sign out couldn't finish. Check your connection and try again.")}finally{Ri(!1)}})()};y.useEffect(()=>{ge(!1),Q(!1),pt(!1)},[w]),y.useEffect(()=>{const A=le=>{const Qe=le.target;wt.current&&!wt.current.contains(Qe)&&ge(!1),At.current&&!At.current.contains(Qe)&&!bn.current?.contains(Qe)&&Q(!1)},U=le=>{le.key==="Escape"&&(ge(!1),Q(!1))};return document.addEventListener("mousedown",A),document.addEventListener("keydown",U),()=>{document.removeEventListener("mousedown",A),document.removeEventListener("keydown",U)}},[]),y.useEffect(()=>{if(xe){ge(!1);const A=window.setTimeout(()=>{At.current?.querySelector("a[href], button:not([disabled])")?.focus()},0);return Ea.current=!0,()=>window.clearTimeout(A)}Ea.current&&(bn.current?.focus(),Ea.current=!1)},[xe]),y.useEffect(()=>{if(!xe)return;const A=U=>{if(U.key!=="Tab")return;const le=Array.from(At.current?.querySelectorAll("a[href], button:not([disabled])")??[]);if(!le.length)return;const Qe=le[0],Ui=le[le.length-1];U.shiftKey&&document.activeElement===Qe?(U.preventDefault(),Ui.focus()):!U.shiftKey&&document.activeElement===Ui&&(U.preventDefault(),Qe.focus())};return document.addEventListener("keydown",A),()=>document.removeEventListener("keydown",A)},[xe]);const{data:Ci}=an({queryKey:B.me,queryFn:()=>Z.me(),enabled:!!(Z.isReady&&D&&!l),staleTime:6e4}),Cl=!!Ci?.pro,Rt=D||!!l?.user;Ty(JS);const Ie=l?.user??k,Ni=l?l.isPro??!0:Cl,Ii=l?!0:!!Ci,wa=Ii&&!Ni,Nl=Ii&&Ni,Il=_l(),Wt=v??Il,{data:Oi}=an({queryKey:B.suggestions,queryFn:()=>Z.getSuggestions(),enabled:!!(Z.isReady&&D&&!l),staleTime:12e4}),Aa=Oi?Rv(Oi.suggestions):null,Tt=l?.suggestionCount??(Aa?Aa.gaps.length+(Aa.groupedEntry?1:0):0),{open:Ra}=My(),Ke=l?.activeHref??w,vn=nS(Ke),$t=a==="archive"&&Rt&&Wt==="app"&&!h&&!d,ht=a==="archive"&&Rt&&Wt==="browser"&&!h&&!d&&(vn.kind==="masthead"||vn.kind==="tool"),Pi=a==="archive"&&Rt&&!h&&(Wt==="app"||Wt==="browser"&&vn.kind==="detail"),Ol=Pi||ht,Pl=a==="archive"&&Rt&&h,Ll=m===xa,Ta=dx(Ke),{tucked:Sn,setTucked:ka}=mx({enabled:$t,resetKey:Ke,scrollContainerSelector:m}),{scrolledFromTop:kt,setScrolledFromTop:Dl}=px({enabled:ht,resetKey:Ke,scrollContainerSelector:m});lx($t||ht),y.useEffect(()=>{!$t&&!ht&&Q(!1)},[ht,$t]);const Ca=()=>{const A=Qa.indexOf(K);ce(Qa[(A+1)%Qa.length])},jl=K==="system"?"Auto":K==="dark"?"Dark":"Light",Li=Ln(Ke,"/setup"),Di=Ln(Ke,"/updates"),ji=Ln(Ke,"/settings");async function Ul(){try{const{url:A}=await Z.openPortal();window.location.assign(A)}catch{try{const{url:A}=await Z.createCheckout("month","header");window.location.assign(A)}catch{}}}const xn=vn,Ml=Pi&&xn.kind!=="none";return i.jsxs(i.Fragment,{children:[Ml?i.jsx(aS,{config:xn,reserveSafeArea:Wt==="app"?"native":"browser",onBack:()=>{xn.kind==="detail"&&E(xn.parentHref??"/")}}):null,i.jsx("header",{className:I(oS({transparent:t,variant:a,compactNativeShell:c}),(Ol||Pl)&&"max-sm:hidden"),role:"banner",children:i.jsxs("div",{className:sS({variant:a,c
4ompactNativeShell:c}),children:[i.jsxs(J,{to:"/",className:cS({variant:a}),"aria-label":"Home",children:[i.jsx("img",{src:b,alt:"",className:lS({variant:a,compactNativeShell:c})}),i.jsxs("span",{className:dS({variant:a}),children:[e,i.jsx($n,{surface:a==="archive"?"archive":"default"})]})]}),a==="archive"&&Rt&&i.jsx("nav",{className:uS,"aria-label":"Primary",children:XS.map(A=>{const U=T(A.href),le=A.href==="/setup"?No:J;return i.jsx(le,{to:A.href,"aria-current":U?"page":void 0,className:I(mS,U&&pS),children:i.jsxs("span",{className:"relative inline-block",children:[A.label,A.hasSuggestionDot&&Tt>0?i.jsx(gv,{variant:"subtle",className:"absolute left-full top-1/2 ml-1 -translate-y-1/2","aria-label":`${Tt} unresolved check-in suggestions`}):null]})},A.href)})}),i.jsx("div",{className:FS,children:R?i.jsx("div",{className:BS,"aria-hidden":!0}):Rt?i.jsxs(i.Fragment,{children:[null,i.jsx(yt,{variant:"ghost",size:"sm",onClick:()=>qe(),"aria-label":"Send feedback",title:"Send feedback",className:I("hidden sm:inline-flex",a==="archive"?Qo:"text-content-muted hover:bg-surface-2 hover:text-content-primary"),children:i.jsx(rn,{className:"h-[18px] w-[18px]","aria-hidden":!0})}),i.jsx(yt,{variant:"ghost",size:"sm",onClick:Ca,"aria-label":Ja[K],title:Ja[K],className:I(a==="archive"?"inline-flex":"hidden sm:inline-flex",a==="archive"?Qo:"text-content-muted hover:bg-surface-2 hover:text-content-primary"),children:i.jsx(gn,{className:"h-[18px] w-[18px]","aria-hidden":!0})}),wa&&i.jsx(L,{variant:"solid",size:"sm",className:I(VS,"hidden sm:inline-flex"),onClick:()=>Ra("header"),title:"Trace Unlimited",children:i.jsxs("span",{className:"inline-flex items-center gap-1.5",children:[i.jsx("span",{className:WS,"aria-hidden":!0}),"Unlimited"]})}),i.jsxs("div",{className:HS,ref:wt,children:[i.jsx(yt,{onClick:()=>{ge(A=>!A)},"aria-haspopup":"menu","aria-expanded":Ht,"aria-label":Ie?.name||Ie?.email||"Account",title:Ie?.name||Ie?.email||"Account",variant:"surface",size:"sm",className:$S,children:Ie?.picture?i.jsx("img",{src:Ie.picture,alt:"",referrerPolicy:"no-referrer",className:"h-full w-full rounded-full object-cover"}):i.jsx("span",{className:zS,children:KS(Ie?.name,Ie?.email)})}),Ht&&i.jsxs("div",{className:YS({variant:a}),role:"menu","aria-label":"Account menu",children:[i.jsx(L,{variant:"menu",render:i.jsx(J,{to:"/settings"}),nativeButton:!1,onClick:()=>ge(!1),children:"Account"}),i.jsx(L,{variant:"menu",onClick:Ca,children:Ja[K]}),i.jsx(L,{variant:"menu",onClick:()=>{ge(!1),qe()},children:"Send feedback"}),wa?i.jsx(L,{variant:"menu",onClick:()=>{ge(!1),Ra("header")},children:"Trace Unlimited"}):Nl?i.jsx(L,{variant:"menu",onClick:()=>{ge(!1),Ul()},children:"Manage subscription"}):null,i.jsx("div",{className:GS({variant:a})}),yn?i.jsx("p",{className:"px-3 py-2 text-xs leading-5 text-danger-700",role:"alert",children:yn}):null,i.jsx(L,{variant:"menu",onClick:ki,disabled:Vt,children:Vt?"Signing out…":"Sign out"})]})]})]}):i.jsx(L,{variant:"outline",size:"sm",className:t?qS:void 0,onClick:()=>{const A=Ir();Wn(A),W({appState:{returnTo:A}})},children:"Sign in"})})]})}),ht?i.jsxs(i.Fragment,{children:[i.jsxs("nav",{className:I(hS,o&&s&&fS),"aria-label":"Mobile browser navigation","data-state":"visible","data-scrolled-from-top":kt?"true":"false",children:[i.jsxs(J,{to:"/","aria-label":"Trace home",className:gS,children:[i.jsx("img",{src:b,alt:"",className:bS}),i.jsx("span",{className:yS,children:"trace"}),i.jsx($n,{surface:"archive"})]}),i.jsx("button",{type:"button","aria-label":"Back to top","aria-hidden":kt?void 0:!0,tabIndex:kt?0:-1,disabled:!kt,className:I(vS,!kt&&SS),onClick:()=>{kt&&(Dl(!1),Jo(m))},children:i.jsx(Ed,{"aria-hidden":!0,className:"h-[17px] w-[17px]"})}),o&&s?i.jsx("div",{className:xS,"data-mobile-browser-actions":!0,children:o}):null,i.jsxs("button",{ref:bn,type:"button","aria-label":"Open navigation menu","aria-expanded":xe,"aria-haspopup":"dialog",className:ES,onClick:()=>Q(A=>!A),children:[i.jsx("span",{className:wS,children:"Menu"}),i.jsxs("span",{className:AS,children:[i.jsx(Vi,{"aria-hidden":!0,className:"h-[17px] w-[17px]"}
4),i.jsx(wd,{"aria-hidden":!0,className:"h-[13px] w-[13px]"})]})]})]}),i.jsx("div",{className:_S,"aria-hidden":"true"})]}):null,$t?i.jsxs("nav",{className:I(RS,c&&TS,Ll&&kS,Sn&&CS),"aria-label":"Mobile primary navigation","data-state":Sn?"tucked":"visible",onFocusCapture:()=>{Sn&&ka(!1)},onClickCapture:A=>{Sn&&(A.preventDefault(),A.stopPropagation(),ka(!1))},children:[vr.map(A=>{const U=Ta===A.id,le=A.icon;return i.jsxs(J,{to:A.href,"aria-current":U?"page":void 0,className:I(Yo,U&&Go),onFocus:()=>gt(A.id),onClick:Qe=>{U&&(Qe.preventDefault(),ka(!1),Jo(m))},onPointerEnter:()=>gt(A.id),onTouchStart:()=>gt(A.id),children:[i.jsxs("span",{className:zo,children:[i.jsx(le,{"aria-hidden":!0,className:"h-[22px] w-[22px]"}),A.hasSuggestionDot&&Tt>0?i.jsx("span",{className:NS,"aria-label":`${Tt} unresolved check-in suggestions`}):null]}),i.jsx("span",{className:qo,children:A.label})]},A.id)}),i.jsxs("button",{ref:bn,type:"button","aria-current":Ta==="more"?"page":void 0,"aria-expanded":xe,"aria-haspopup":"dialog",className:I(Yo,Ta==="more"&&Go),onClick:()=>Q(A=>!A),children:[i.jsx("span",{className:zo,children:i.jsx(Vi,{"aria-hidden":!0,className:"h-[22px] w-[22px]"})}),i.jsx("span",{className:qo,children:"More"})]})]}):null,xe?i.jsxs(i.Fragment,{children:[i.jsx("button",{type:"button",className:IS,"aria-label":"Close More menu",onClick:()=>Q(!1)}),i.jsxs("div",{ref:At,"data-mobile-sheet-drag-target":"",className:OS,role:"dialog","aria-modal":"true","aria-label":"More",children:[i.jsx(wy,{className:PS,indicatorClassName:LS,targetRef:At,onDismiss:()=>Q(!1)}),ht?i.jsxs(i.Fragment,{children:[i.jsx("div",{className:Ka,children:vr.map(A=>{const U=Ln(Ke,A.href),le=A.icon;return i.jsxs(J,{className:I(et,U&&On),to:A.href,"aria-current":U?"page":void 0,onClick:()=>Q(!1),onFocus:()=>gt(A.id),onPointerEnter:()=>gt(A.id),onTouchStart:()=>gt(A.id),children:[i.jsxs("span",{className:tt,children:[i.jsx(le,{"aria-hidden":!0}),A.hasSuggestionDot&&Tt>0?i.jsx("span",{className:DS,"aria-label":`${Tt} unresolved check-in suggestions`}):null]}),i.jsx("span",{className:nt,children:i.jsx("span",{className:at,children:A.label})})]},A.id)})}),i.jsx("div",{className:Ko})]}):null,i.jsxs("div",{className:Ka,children:[null,i.jsxs(No,{className:I(et,Li&&On),to:"/setup","aria-current":Li?"page":void 0,onClick:()=>Q(!1),children:[i.jsx("span",{className:tt,children:i.jsx(kd,{"aria-hidden":!0})}),i.jsxs("span",{className:nt,children:[i.jsx("span",{className:at,children:"Extension setup"}),i.jsx("span",{className:Pn,children:"Get Trace working"})]})]}),i.jsxs(J,{className:I(et,Di&&On),to:"/updates","aria-current":Di?"page":void 0,onClick:()=>Q(!1),children:[i.jsx("span",{className:tt,children:i.jsx(Cd,{"aria-hidden":!0})}),i.jsxs("span",{className:nt,children:[i.jsx("span",{className:at,children:"Updates"}),i.jsx("span",{className:Pn,children:"What's new"})]})]}),i.jsxs("button",{type:"button",className:et,onClick:()=>{Q(!1),qe()},children:[i.jsx("span",{className:tt,children:i.jsx(rn,{"aria-hidden":!0})}),i.jsx("span",{className:nt,children:i.jsx("span",{className:at,children:"Feedback"})})]}),wa?i.jsxs("button",{type:"button",className:et,onClick:()=>{Q(!1),Ra("mobile_menu")},children:[i.jsx("span",{className:tt,children:i.jsx(Nd,{"aria-hidden":!0})}),i.jsxs("span",{className:nt,children:[i.jsx("span",{className:at,children:"Trace Unlimited"}),i.jsx("span",{className:Pn,children:"Upgrade library and stats"})]})]}):null]}),i.jsx("div",{className:Ko}),i.jsxs("div",{className:Ka,children:[i.jsxs("button",{type:"button",className:et,onClick:Ca,children:[i.jsx("span",{className:tt,children:i.jsx(gn,{"aria-hidden":!0})}),i.jsx("span",{className:nt,children:i.jsx("span",{className:at,children:"Theme"})}),i.jsx("span",{className:jS,children:jl})]}),i.jsxs(J,{className:I(et,ji&&On),to:"/settings","aria-current":ji?"page":void 0,onClick:()=>Q(!1),children:[i.jsx("span",{className:tt,children:i.jsx(Id,{"aria-hidden":!0})}),i.jsxs("span",{className:nt,children:[i.jsx("span",{className:at,children:"Account"}),Ie?.email?i.jsx("span",{className:Pn,children:Ie.email}):null]})]}),i.jsxs("button",{type:"button",className:I(et,US),onClick:ki,disabled:Vt,children:[i.jsx("span",{className:tt,children:i.jsx(Od,{"aria-hidden":!0})}),i.jsx("span",{className:nt,children:i.jsx("span",{className:at,children:Vt?"Signing out…":"Sign out"})})]}),yn?i.jsx("p",{className:"px-4 py-2 text-sm leading-5 text-danger-700",role:"alert",children:yn}):null]}),i.jsx("div",{className:MS,children:i.jsx("span",{children:"Trace beta"})})]})]}):null,null]})}function hx({children:e,detail:t,action:a,onDismiss:c,className:m}){return i.jsxs("div",{role:"status",className:I("relative border-b border-[color-mix(in_oklab,var(--accent)_30%,transparent)] bg-[
4color-mix(in_oklab,var(--accent)_8%,transparent)] px-4 py-3 text-center",m),children:[i.jsx("p",{className:"text-sm font-semibold text-content-primary",children:e}),t&&i.jsx("p",{className:"mt-0.5 text-xs text-content-muted",children:t}),a&&i.jsx("div",{className:"mt-2 flex flex-wrap justify-center gap-2",children:a}),c&&i.jsx(Ar,{onClick:c,className:"absolute right-3 top-1/2 -translate-y-1/2 rounded-md p-1 text-content-muted hover:text-content-primary","aria-label":"Dismiss",children:i.jsx("svg",{className:"h-4 w-4",viewBox:"0 0 20 20",fill:"currentColor","aria-hidden":!0,children:i.jsx("path",{d:"M6.28 5.22a.75.75 0 0 0-1.06 1.06L8.94 10l-3.72 3.72a.75.75 0 1 0 1.06 1.06L10 11.06l3.72 3.72a.75.75 0 1 0 1.06-1.06L11.06 10l3.72-3.72a.75.75 0 0 0-1.06-1.06L10 8.94 6.28 5.22Z"})})})]})}const qt="trace:billing-success-ts";function fx(){const[e,t]=y.useState("hidden");if(y.useEffect(()=>{const c=()=>{const o=String(Date.now());localStorage.setItem(qt,o),t("success")},m=()=>t("pending"),h=()=>t("delayed");window.addEventListener("trace:billingSuccess",c),window.addEventListener("trace:billingPending",m),window.addEventListener("trace:billingDelayed",h);const d=localStorage.getItem(qt),v=localStorage.getItem(qt+":dismissed");return d&&d!==v&&t("success"),()=>{window.removeEventListener("trace:billingSuccess",c),window.removeEventListener("trace:billingPending",m),window.removeEventListener("trace:billingDelayed",h)}},[]),e==="hidden")return null;const a=()=>{t("hidden");const c=localStorage.getItem(qt);c&&localStorage.setItem(qt+":dismissed",c)};return i.jsx(hx,{onDismiss:a,detail:e==="success"?"No story cap and reading stats are now unlocked.":e==="pending"?"We’re confirming your subscription with Stripe.":"Refresh shortly. If Unlimited remains locked, contact support and we’ll reconcile it.",children:e==="success"?"Trace Unlimited enabled":e==="pending"?"Payment received — enabling Trace Unlimited…":"Payment received — activation is taking longer than expected"})}function _x({disabled:e=!1}){const t=_e(),a=Te(),c=an({queryKey:B.me,queryFn:()=>t.me(),enabled:!e&&t.isReady,staleTime:6e4}),m=c.data?.billing,h=c.data?.pro===!0&&m?.stripe.present===!0&&m.stripe.active===!1&&m.apple.active===!1;return e||a.pathname==="/settings"||!h?null:i.jsx("div",{role:"status",className:"border-b border-[color-mix(in_oklab,var(--rust)_34%,transparent)] bg-[color-mix(in_oklab,var(--rust)_8%,var(--paper))] px-4 py-2.5",children:i.jsxs("div",{className:"mx-auto flex max-w-4xl flex-col items-start justify-between gap-2 sm:flex-row sm:items-center",children:[i.jsxs("p",{className:"text-sm leading-5 text-content-primary",children:[i.jsx("span",{className:"font-semibold",children:"Payment needs attention."})," ","We couldn’t process your latest payment. Unlimited access stays active while Stripe retries it."]}),i.jsx(J,{to:"/settings",className:I(ps({variant:"outline",size:"sm"}),"shrink-0"),children:"Review billing"})]})})}const gx=["mx-auto w-full max-w-7xl px-[18px] pt-3 sm:px-12"].join(" "),bx=["relative flex min-w-0 flex-col gap-3 overflow-hidden rounded-sm","border border-border border-l-2 border-l-[var(--accent)] bg-surface-1","px-3 py-3 shadow-sm sm:flex-row sm:items-center sm:gap-4 sm:px-4"].join(" "),yx=["flex h-8 w-8 shrink-0 items-center justify-center rounded-full sm:h-9 sm:w-9","border border-border bg-surface-2 text-content-primary","[&_svg]:h-4 [&_svg]:w-4"].join(" ");function vx(e,t){return e==="review"?{title:"Finding Trace useful?",body:`An honest ${t?.label??"store"} review helps me improve the app and lets others know if it can be trusted. Please consider leaving a review to help out!`,action:"Review Trace",icon:i.jsx(Pd,{"aria-hidden":!0})}:e==="share"?{title:"Think others might like Trace?",body:"If you're enjoying Trace please consider sharing with friends or communities you think might like it too!",icon:i.jsx(Ld,{"aria-hidden":!0})}:{title:"What should Trace keep or improve?",body:"Is there anything that annoys you, or that you really love? Any feedback helps me figure out what to work on next!",action:"Send feedback",icon:i.jsx(rn,{"aria-hidden":!0})}}function Sx({kind:e,reviewTarget:t,onAction:a,onDismiss:c}){const m=vx(e,t),h=m.action&&(e==="review"&&t?i.jsx(L,{nativeButton:!1,render:i.jsx("a",{href:t.href,target:"_blank",rel:"noopener noreferrer"}),variant:"outline",size:"sm",onClick:a,children:m.action}):i.jsx(L,{type:"button",variant:"outline",size:"sm",onClick:a,children:m.action}));return i.jsx("div",{className:gx,children:i.jsxs("aside",{className:bx,"aria-label":"A note from Trace",children:[i.jsxs("div",{className:"grid min-w-0 flex-1 grid-cols-[auto_minmax(0,1fr)] items-center gap-x-2 gap-y-1 sm:items-start sm:gap-x-3 sm:gap-y-0",children:[i.jsx("span",{className:`${yx} row-start-1 sm:row-span-2`,children:m.icon}),i.jsx("p",{className:"col-start-2 row-start-1 font-serif text-base font-semibold leading-snug text-content-primary",children:m.title}),i.jsx("p",{className:"col-span-2 row-start-2 text-xs leading-relaxed text-content-muted sm:col-span-1 sm:col-start-2 sm:mt-0.5",children:m.body})]}),i.jsxs("div",{className:"flex shrink-0 items-center justify-end gap-1 sm:pl-2",children:[h,i.jsx(yt,{type:"button",variant:"ghost",size:"sm","aria-label":"Not now",title:"Not now",onClick:c,children:i.jsx(os,{className:"h-5 w-5","aria-hidden":!0})})]})]})})}const Sr="trace:advocacy-activity";function tA(){typeof window>"u"||window.dispatchEvent(new Event(Sr))}function xx(e,t){if(!/iPhone|iPad|iPod/i.test(e)){if(/Firefox/i.test(e)&&t.firefoxAddonsUrl)return{label:"Firefox Add-ons",href:t.firefoxAddonsUrl};if(/Edg\//i.test(e)&&t.edgeAddonsUrl)return{label:"Microsoft Edge Add-ons",href:t.edgeAddonsUrl};if(/Chrome|Chromium/i.test(e)&&t.chromeWebStoreUrl)return{label:"Chrome Web Store",href:t.chromeWebStoreUrl};
4if(/Safari/i.test(e)&&!/Chrome|Chromium|Edg\//i.test(e)&&t.safariExtensionGalleryUrl)return{label:"Mac App Store",href:t.safariExtensionGalleryUrl}}}function Ex(e,t=""){return e==="/"}const wx=2500,Ax=1e3;function Xo(){return!!document.querySelector('[role="dialog"], [aria-modal="true"], [data-advocacy-prompt-blocker]')}function Rx({preview:e,disabled:t=!1}){const a=_e(),c=Te(),{openFeedback:m}=pl(),[h,d]=y.useState(e?.kind??null),[v,o]=y.useState(0),s=y.useRef(a);y.useEffect(()=>{s.current=a},[a]),y.useEffect(()=>{if(e||t||!a.isReady)return;let w=!1;const T=()=>{s.current.recordAdvocacyActivity().then(()=>{w||o(D=>D+1)}).catch(()=>{})};return window.addEventListener(Sr,T),()=>{w=!0,window.removeEventListener(Sr,T)}},[a.isReady,t,e]);const l=y.useMemo(()=>e?.reviewTarget??xx(navigator.userAgent,ls),[e?.reviewTarget]);y.useEffect(()=>{if(e||t||h||!a.isReady||F()||!Ex(c.pathname,c.search))return;let w=!1,T=null,D=null;const R=async()=>{if(!w){if(Xo()){D||(D=new MutationObserver(()=>{Xo()||(D?.disconnect(),D=null,T=window.setTimeout(()=>{R()},Ax))}),D.observe(document.body,{attributes:!0,childList:!0,subtree:!0,attributeFilter:["aria-modal","data-advocacy-prompt-blocker","role"]}));return}try{const k=await s.current.claimAdvocacyPrompt(l!==void 0);!w&&k.prompt&&d(k.prompt)}catch{}}};return T=window.setTimeout(()=>{R()},wx),()=>{w=!0,T!==null&&window.clearTimeout(T),D?.disconnect()}},[v,a.isReady,t,h,c.pathname,c.search,e,l]);const b=w=>{e||s.current.completeAdvocacyPrompt(w).catch(()=>{})};if(!h)return null;const g=()=>{d(null)},E=()=>
4{if(h==="feedback"){b(h),d(null),m();return}if(h==="review"){b(h),d(null);return}};return i.jsx(Sx,{kind:h,reviewTarget:l,onAction:E,onDismiss:g})}const Tx=["--paper","--library-bg","--bg-app"];function kx(){const e=y.useRef(null);return y.useLayoutEffect(()=>{if(typeof document>"u")return;const t=document.documentElement,a=document.body,c=document.getElementById("root"),m=document.querySelector('meta[name="theme-color"]'),h=t.style.backgroundColor,d=a.style.backgroundColor,v=c?.style.backgroundColor??null,o=m?.getAttribute("content")??null,s=()=>{const b=e.current?window.getComputedStyle(e.current):null,g=window.getComputedStyle(t),E=Tx.flatMap(w=>[b?.getPropertyValue(w).trim()??"",g.getPropertyValue(w).trim()]).find(Boolean)||g.getPropertyValue("--bg-app").trim()||"Canvas";t.style.backgroundColor=E,a.style.backgroundColor=E,c&&(c.style.backgroundColor=E),m?.setAttribute("content",E)};s();const l=new MutationObserver(s);return l.observe(t,{attributes:!0,attributeFilter:["data-theme"]}),()=>{l.disconnect(),t.style.backgroundColor=h,a.style.backgroundColor=d,c&&v!==null&&(c.style.backgroundColor=v),o===null?m?.removeAttribute("content"):m?.setAttribute("content",o)}},[]),e}function Cx({children:e,className:t,mobileHeader:a="default",mobileDockHidden:c=!1,mobilePrimaryNavHidden:m=!1,mobileBrowserActions:h,mobileBrowserActionsVisible:d=!1,archivePreview:v,advocacyPromptPreview:o}){const s=F(),l=_l(),b=kx();return i.jsx(hl,{children:i.jsxs("div",{ref:b,className:I("library-app flex min-h-dvh min-h-[-webkit-fill-available] w-full min-w-0 max-w-full flex-col bg-[var(--bg-app)] text-[var(--text-primary)]",s?"max-sm:fixed max-sm:inset-0 max-sm:flex max-sm:min-h-0 max-sm:flex-col max-sm:overflow-hidden":"max-sm:min-h-dvh max-sm:overflow-x-clip",t),children:[i.jsx("a",{href:"#main-content",className:I("sr-only focus:not-sr-only focus:fixed focus:left-4 focus:z-[100] focus:rounded-lg focus:bg-surface-1 focus:px-4 focus:py-2 focus:text-sm focus:font-medium focus:text-content-primary focus:shadow-lg focus:ring-2 focus:ring-[var(--accent)]",s?"focus:top-[calc(0.75rem+env(safe-area-inset-top))]":"focus:top-4"),children:"Skip to main content"}),i.jsx("div",{className:a==="page"?"max-sm:hidden":"contents",children:i.jsx(bl,{variant:"archive",compactNativeShell:s,mobileScrollContainerSelector:s?"[data-app-shell-scroll]":"window",mobileDockHidden:c,mobilePrimaryNavHidden:m,mobileNavigationChassis:l,mobileBrowserActions:h,mobileBrowserActionsVisible:d,archivePreview:v})}),i.jsx(_x,{disabled:!!v}),i.jsx(fx,{}),i.jsx(Rx,{preview:o,disabled:!!v}),i.jsx("div",{id:"main-content","data-app-shell-scroll":!0,className:I("min-w-0 flex-1 bg-[var(--bg-app)]",s?"max-sm:min-h-0 max-sm:w-full max-sm:max-w-full max-sm:flex-1 max-sm:overflow-x-clip max-sm:overflow-y-auto max-sm:overscroll-contain":"max-sm:w-full max-sm:max-w-full max-sm:overflow-x-clip max-sm:overflow-y-visible",l==="app"&&!m?"max-sm:pb-[calc(78px_+_env(safe-area-inset-bottom))]":"max-sm:pb-0"),children:e})]})})}function te({className:e}){return i.jsx("span",{className:["archive-state-shimmer block rounded-pill","animate-[archive-shimmer_1.4s_ease-in-out_infinite]","bg-[linear-gradient(90deg,var(--paper-2),var(--paper-3),var(--paper-2))]","bg-[length:200%_100%]",e].join(" ")})}function Nx(){return i.jsxs("div",{className:"grid min-h-[116px] gap-4 border-b border-[var(--line)] px-[18px] py-[18px] sm:grid-cols-[minmax(0,1fr)_220px] sm:px-8 sm:py-6",children:[i.jsxs("div",{className:"grid min-w-0 content-start gap-3",children:[i.jsx(te,{className:"h-[18px] w-3/5"}),i.jsx(te,{className:"h-2.5 w-4/5"}),i.jsx(te,{className:"h-2.5 w-[45%]"}),i.jsx(te,{className:"h-[22px] w-[90px]"})]}),i.jsxs("div",{className:"hidden content-start gap-3 sm:grid",children:[i.jsx(te,{className:"h-2.5 w-[120px]"}),i.jsx(te,{className:"h-[22px] w-[90px]"})]})]})}function Ix({loadingRows:e=3,statusLabel:t="Loading Trace view",archivePreview:a}){return i.jsx(Cx,{className:"archive-editorial-shell",archivePreview:a,children:i.jsx("div",{className:"library-main-canvas",children:i.jsx("main",{className:"relative z-0 mx-auto w-full pb-24 sm:pb-10",children:i.jsx("section",{className:"relative mx-auto w-full max-w-[96rem] px-[18px] pt-5 sm:px-12 sm:pt-12 lg:px-16",role:"status","aria-live":"polite","aria-label":t,children:i.jsxs("div",{className:"grid gap-6","aria-hidden":!0,"data-testid":"authenticated-route-skeleton",children:[i.jsxs("div",{className:"border-b border-[var(--line)] pb-7 sm:pb-9",children:[i.jsxs("div",{className:"border-l-2 border-[var(--forest-deep)] pl-5 sm:pl-7",children:[i.jsx(te,{className:"h-3 w-28"}),i.jsx(te,{className:"mt-4 h-10 w-full max-w-[30rem] rounded-[var(--radius-v9-md)]"}),i.jsx(te,{className:"mt-3 h-4 w-full max-w-[42rem]"}),i.jsx(te,{className:"mt-2 h-4 w-2/3 max-w-[30rem]"})]}),i.jsxs("div",{className:"mt-6 flex flex-wrap gap-3 pl-0 sm:pl-7",children:[i.jsx(te,{className:"h-10 w-[116px] rounded-[var(--radius-v9-md)]"}),i.jsx(te,{className:"h-10 w-[92px] rounded-[var(--radius-v9-md)]"}),i.jsx(te,{className:"h-10 w-[132px] rounded-[var(--radius-v9-md)]"})]})]}),i.jsxs("div",{className:"flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between",children:[i.jsx(te,{className:"h-10 w-full max-w-[28rem] rounded-[var(--radius-v9-md)]"}),i.jsxs("div",{className:"flex gap-2",children:[i.jsx(te,{className:"h-9 w-24 rounded-[var(--radius-v9-md)]"}),i.jsx(te,{className:"h-9 w-24 rounded-[var(--radius-v9-md)]"})]})]}),i.jsx("div",{className:"rounded-[var(--radius-v9-xl)] border border-[var(--line)] bg-[color-mix(in_oklab,var(--paper)_82%,var(--paper-2))]",children:Array.from({length:e}).map((c,m)=>i.jsx(Nx,{},m))})]})})})})})}const Ox=6,Px=1e3;function Lx(e){return new Promise(t=>window.setTimeout(t,e))}async function Dx(e){const t=e.attempts??Ox,a=e.waitForRetry??(()=>Lx(Px));for(let c=0;c<t;c+=1){c>0&&await a();try{const m=await e.getMe();if(e.onMe?.(m),m.pro)return!0}catch{}}return!1}function jx(){const e=Te(),t=_e(),a=jt(),c=y.useRef(t);return y.useLayoutEffect(()=>{c.current=t}),y.useEffect(()=>{if(!c.current.isReady)return;const m=new URLSearchParams(e.search);if(!m.has("billing"))return;const h=m.get("billing"),d=m.get("session_id"),v=ia.safeParse(m.get("source")),o=v.success?v.data:"unknown";let s=!1;return(async()=>
4{if(h==="success"&&d){window.dispatchEvent(new CustomEvent("trace:billingPending")),c.current.recordBillingEvent({event:"checkout_returned_success",source:o,platform:"web"}).catch(()=>{});try{await c.current.syncCheckoutSession(d)}catch{}const b=await Dx({getMe:()=>c.current.me(),onMe:g=>{a.setQueryData(B.me,g)}});if(s)return;b?(c.current.recordBillingEvent({event:"entitlement_confirmed",source:o,platform:"web"}).catch(()=>{}),window.dispatchEvent(new CustomEvent("trace:billingSuccess"))):(c.current.recordBillingEvent({event:"entitlement_not_confirmed",source:o,platform:"web"}).catch(()=>{}),window.dispatchEvent(new CustomEvent("trace:billingDelayed")))}else h==="cancel"&&c.current.recordBillingEvent({event:"checkout_cancelled",source:o,platform:"web"}).catch(()=>{});if(s)return;await a.invalidateQueries({queryKey:B.me}),await a.invalidateQueries({queryKey:B.library.all});const l=new URL(window.location.href);l.searchParams.delete("billing"),l.searchParams.delete("session_id"),l.searchParams.delete("source"),h==="success"&&l.searchParams.delete("panel"),window.history.replaceState({},"",l.toString())})(),()=>{s=!0}},[e.search,t.isReady,a]),null}function Ux(){const e=jt(),t=_e();return y.useEffect(()=>{if(F())return tl(a=>{a.status==="success"&&(async()=>{if(a.op==="manageSubscriptions"){e.invalidateQueries({queryKey:B.me});return}let c=a.pro===!0;try{const m=await e.fetchQuery({queryKey:B.me,queryFn:()=>t.me(),staleTime:0});c=c||!!m?.pro}catch{e.invalidateQueries({queryKey:B.me})}e.invalidateQueries({queryKey:B.library.all}),c&&(t.recordBillingEvent({event:"entitlement_confirmed",source:"unknown",platform:"apple"}).catch(()=>{}),window.dispatchEvent(new CustomEvent("trace:billingSuccess")))})()})},[t,e]),null}const Mx=[/ChunkLoadError/i,/CSS_CHUNK_LOAD_FAILED/i,/Loading chunk [\w-]+ failed/i,/dynamically imported module/i,/Failed to fetch dynamically imported module/i,/Failed to load module script/i,/Importing a module script failed/i,/MIME type .*module script/i,/not a valid JavaScript MIME type/i,/error loading dynamically imported module/i,/Unable to preload CSS/i],Fx="trace:page-load-recovery-v1:";function yl(e){if(e instanceof Error)return[e.name,e.message,e.stack].filter(Boolean).join(`
5`);if(typeof e=="string")return e;try{return JSON.stringify(e)}catch{return String(e)}}function vl(e){const t=yl(e);return Mx.some(a=>a.test(t))}function Bx(e){const t=yl(e),c=t.match(/(?:https?:\/\/[^\s'")]+)?\/assets\/[^\s'")]+/i)?.[0]??t.slice(0,320);return`${Fx}${window.location.pathname}${window.location.search}:${c}`}function Si(e){if(!vl(e))return!1;try{const t=Bx(e);if(window.sessionStorage.getItem(t)==="1")return!1;window.sessionStorage.setItem(t,"1")}catch{return!1}return xi(),!0}function Hx(){const e=t=>{const a=Reflect.get(t,"payload");Si(a)&&t.preventDefault()};return window.addEventListener("vite:preloadError",e),()=>window.removeEventListener("vite:preloadError",e)}function xi(){window.location.reload()}function Sl(){const e=`${window.location.origin}/`;if(window.location.href===e){window.location.reload();return}window.location.assign(e)}class Vx extends Y.Component{state={error:null,resetKey:0};static getDerivedStateFromError(t){return{error:t}}componentDidCatch(t,a){Si(t)||(console.error("[RouteErrorBoundary]",t,a),wr(t,{extra:{componentStack:a.componentStack}}))}handleRetry=()=>{if(vl(this.state.error)){xi();return}this.setState(t=>({error:null,resetKey:t.resetKey+1}))};handleGoHome=t=>{t.preventDefault(),Sl()};render(){return this.state.error?i.jsxs("div",{className:"mx-auto max-w-lg px-6 py-16 text-center",children:[i.jsx("h2",{className:"text-xl font-semibold text-content-primary",children:"Something went wrong"}),i.jsx("p",{className:"mt-2 text-sm text-content-muted",children:"An unexpected error occurred on this page."}),i.jsxs("div",{className:"mt-6 flex justify-center gap-3",children:[i.jsx(L,{variant:"solid",onClick:this.handleRetry,children:"Try again"}),i.jsx(L,{variant:"outline",render:i.jsx("a",{href:"/",onClick:this.handleGoHome}),nativeButton:!1,children:"Go home"})]})]}):i.jsx(Y.Fragment,{children:this.props.children},this.state.resetKey)}}const Wx="TRACE_NATIVE_STORY_DETAIL_ROUTE_REQUEST",$x="TRACE_NATIVE_STORY_DETAIL_ROUTE_RESPONSE",Yx="TRACE_NATIVE_STORY_DETAIL_AUTH_CONTEXT_CHANGED",Gx="TRACE_NATIVE_STORY_DETAIL_WEB_FALLBACK_REQUEST",zx=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;function qx(e){if(!e.startsWith("/")||e.startsWith("//"))return!1;try{const t=new URL(e,window.location.origin);return t.origin===window.location.origin&&t.pathname==="/"&&t.hash===""}catch{return!1}}function Kx(){return typeof window.crypto?.randomUUID=="function"?window.crypto.randomUUID():["trace-native-story-detail",Date.now().toString(36),Math.random().toString(36).slice(2)].join("-")}function xl(e){return e.source===window&&e.origin===window.location.origin}function El(){return!F()||window.__TRACE_NATIVE_APP__?.nativeStoryDetailRouteVersion!==1?null:window.webkit?.messageHandlers?.traceNativeStoryDetail??null}function Qx(e,t){const a=El();if(!a)return!1;try{return a.postMessage({type:Yx,subject:e,sessionGeneration:t}),!0}catch{return!1}}function nA(e){const t=a=>{if(!xl(a)||!a.data||typeof a.data!="object")return;const c=a.data;
5c.type!==Gx||c.source!=="library"||typeof c.entryId!="string"||!zx.test(c.entryId)||typeof c.returnTo!="string"||!qx(c.returnTo)||e({entryId:c.entryId,source:"library",returnTo:c.returnTo})};return window.addEventListener("message",t),()=>window.removeEventListener("message",t)}function aA(e,t=2500){const a=El();if(!a)return Promise.resolve(!1);const c=Kx();return new Promise(m=>{let h=!1,d=null;const v=s=>{h||(h=!0,d!=null&&window.clearTimeout(d),window.removeEventListener("message",o),m(s))},o=s=>{if(!xl(s)||!s.data||typeof s.data!="object")return;const l=s.data;l.type!==$x||l.nonce!==c||l.owner!=="native"&&l.owner!=="web"||v(l.owner==="native")};window.addEventListener("message",o);try{a.postMessage({type:Wx,nonce:c,entryId:e.entryId,source:e.source,returnTo:e.returnTo})}catch{v(!1);return}d=window.setTimeout(()=>v(!1),t)})}const Jx="TRACE_NATIVE_COLLECTIONS_ROUTE_REQUEST",Xx="TRACE_NATIVE_COLLECTIONS_ROUTE_RESPONSE",Zx="TRACE_NATIVE_COLLECTIONS_AUTH_CONTEXT_CHANGED",eE="TRACE_NATIVE_COLLECTIONS_WEB_FALLBACK_REQUEST",Ei=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;function wl(e){if(!e.startsWith("/")||e.startsWith("//"))return!1;try{const t=new URL(e,window.location.origin),a=t.pathname.startsWith("/collections/")?t.pathname.slice(13):null;return t.origin===window.location.origin&&(t.pathname==="/collections"||a!==null&&Ei.test(a))&&t.hash===""}catch{return!1}}function tE(e){if(wl(e))return!0;if(!e.startsWith("/")||e.startsWith("//"))return!1;try{const t=new URL(e,window.location.origin),a=t.pathname.startsWith("/library/")?t.pathname.slice(9):null;return t.origin===window.location.origin&&a!==null&&Ei.test(a)&&t.hash===""}catch{return!1}}function nE(){return typeof window.crypto?.randomUUID=="function"?window.crypto.randomUUID():["trace-native-collections",Date.now().toString(36),Math.random().toString(36).slice(2)].join("-")}function Al(e){return e.source===window&&e.origin===window.location.origin}function Rl(){return!F()||window.__TRACE_NATIVE_APP__?.nativeCollectionsRouteVersion!==1?null:window.webkit?.messageHandlers?.traceNativeCollections??null}function aE(e,t){const a=Rl();if(!a)return!1;try{return a.postMessage({type:Zx,subject:e,sessionGeneration:t}),!0}catch{return!1}}function rA(e){const t=a=>{if(!Al(a)||!a.data||typeof a.data!="object")return;const c=a.data;c.type!==eE||typeof c.path!="string"||!tE(c.path)||e(c.path)};return window.addEventListener("message",t),()=>window.removeEventListener("message",t)}function iA(e,t=2500){const a=Rl();if(!a||e.source!=="collections"||e.collectionId!==null&&!Ei.test(e.collectionId)||!wl(e.returnTo))return Promise.resolve(!1);const c=nE();return new Promise(m=>{let h=!1,d=null;const v=s=>{h||(h=!0,d!=null&&window.clearTimeout(d),window.removeEventListener("message",o),m(s))},o=s=>{if(!Al(s)||!s.data||typeof s.data!="object")return;const l=s.data;l.type!==Xx||l.nonce!==c||l.owner!=="native"&&l.owner!=="web"||v(l.owner==="native")};window.addEventListener("message",o);try{a.postMessage({type:Jx,nonce:c,collectionId:e.collectionId,source:e.source,returnTo:e.returnTo})}catch{v(!1);return}d=window.setTimeout(()=>v(!1),t)})}function Za(e,t){Qx(e,t),aE(e,t)}let Dn=null;function Zo(){return typeof window.crypto?.randomUUID=="function"?window.crypto.randomUUID():["trace-shell-session",Date.now().toString(36),Math.random().toString(36).slice(2)].join("-")}function rE(){const{getAccessTokenSilently:e,isAuthenticated:t,user:a}=ke();y.useEffect(()=>{const c=Zo();Dn=c;const m=t?a?.sub?.trim():void 0;if(!F()||!m){delete window.__traceShellGetAccessToken,Za(null,c);return}const h=async d=>{pi();const v=await e(d?.forceRefresh?{cacheMode:"off"}:void 0);if(window.__traceShellGetAccessToken!==h||Dn!==c)throw new Error("trace_shell_session_changed");return{accessToken:v,subject:m,sessionGeneration:c}};return window.__traceShellGetAccessToken=h,Za(m,c),()=>{window.__traceShellGetAccessToken===h&&delete window.__traceShellGetAccessToken,Dn===c&&(Dn=null),Za(null,Zo())}},[e,t,a?.sub])}const iE="TRACE_IOS_LIBRARY_ACTIVITY_COMPLETED",oE="TRACE_IOS_LIBRARY_ACTIVITY_OBSERVED",sE="TRACE_IOS_REVIEW_CONTEXT";function wi(){return F()?window.webkit?.messageHandlers?.traceReview??null:null}function cE(e){return e.status!==void 0||e.progress!==void 0||typeof e.rating=="number"&&e.rating>0}function oA(e,t){const a=e.trim();if(!a||!cE(t))return!1;const c=wi();if(!c)return!1;try{return c.postMessage({type:iE,entryId:a}),!0}catch{return!1}}function sA(e){const t=e.trim();if(!t)return!1;const a=wi();if(!a)return!1;try{return a.postMessage({type:oE,activityAt:t}),!0}catch{return!1}}function lE(e){const t=wi();if(!t)return!1;try{return t.postMessage({type:sE,context:e}),!0}catch{return!1}}function dE(e,t){return e==="/"&&t?"library":"other"}function uE(){const{pathname:e}=Te(),{isAuthenticated:t}=ke();return y.useEffect(()=>{lE(dE(e,t))},[t,e]),null}const es=new Set,mE=new Set(["access_token_unavailable","device_session_invali
5d_response","device_session_revoke_failed","device_session_unavailable","native_error","native_timeout","native_unavailable","provider_clear_failed","provider_unavailable","provider_update_failed"]);function pE(e){return mE.has(e)?e:"native_error"}function ts(e,t){const a=pE(t);es.has(a)||Er()&&(es.add(a),ns("ios_safari.credential_provider_sync_failed",{level:"warning",tags:{error:a,trigger:e}}))}const Tl=()=>M(()=>import("./MyStories-DPVKcTCZ.js"),__vite__mapDeps([11,1,12,2,3,13,14,15,7,16,17,18,19,20,21,8,9,6,22,4])),hE=()=>M(()=>import("./index-D09DlCsk.js"),__vite__mapDeps([26,1,2,15,3,12,7,18,8,9,22])),fE=()=>M(()=>import("./StatsPage-lvfyK-zQ.js"),__vite__mapDeps([25,1,2,12,3,16,17])),_E=()=>M(()=>import("./SettingsPage-CbRersiT.js"),__vite__mapDeps([27,1,2,16,3,4])),gE=()=>M(()=>import("./AppsPage-mcI6481d.js"),__vite__mapDeps([28,1,29,2,30,3])),bE=()=>M(()=>import("./SetupPage-DbbILx0z.js"),__vite__mapDeps([31,1,2,3,19,20,29,32,30])),Ai=()=>M(()=>import("./index-FJnU_1X8.js"),__vite__mapDeps([23,1,2,3,15,12,7,18,16,17,20,13,14,4])),yE=()=>M(()=>import("./ImportPage-uG0YfxhH.js"),__vite__mapDeps([33,1,2,18,3,20,4])),vE=()=>M(()=>import("./AdminPage-Zv03GluY.js"),__vite__mapDeps([34,1,6,3,7,14,35,2])),SE=()=>M(()=>import("./SuggestionsPage-BGApgL5t.js"),__vite__mapDeps([24,1,2,3,17,21])),xE=()=>M(()=>import("./UpdatesPage-B7YBtmEK.js"),__vite__mapDeps([36,1,2,29,30,16,3])),EE=y.lazy(Tl),wE=y.lazy(hE),AE=y.lazy(yE),RE=y.lazy(vE),kl=y.lazy(()=>M(()=>import("./Landing-kAmRRf46.js"),__vite__mapDeps([37,1,2,29,30,3]))),TE=y.lazy(()=>M(()=>import("./ReaderPage-D5bwifui.js"),__vite__mapDeps([38,1,2,29,30,3]))),kE=y.lazy(()=>M(()=>import("./MobileShellAuth-ad8bhLlM.js"),__vite__mapDeps([39,1,2,3,30]))),CE=y.lazy(_E),NE=y.lazy(fE),IE=y.lazy(()=>M(()=>import("./Privacy-C4v7STZ5.js"),__vite__mapDeps([40,1,2,3,41,29,32,30]))),OE=y.lazy(()=>M(()=>import("./Terms-CwwXB30A.js"),__vite__mapDeps([42,1,2,29,30,41,3]))),PE=y.lazy(()=>M(()=>import("./About-De470AU-.js"),__vite__mapDeps([43,1,2,29,30,41,3]))),LE=y.lazy(()=>M(()=>import("./Support-DpOe24aj.js"),__vite__mapDeps([44,1,2,29,30,41,3,4]))),DE=y.lazy(()=>M(()=>import("./NotFound-wqOTQyCV.js"),__vite__mapDeps([45,1,2,3])));y.lazy(()=>M(()=>import("./MaintenancePage-D-ATM8Kj.js"),__vite__mapDeps([46,1,2])));const jE=y.lazy(()=>M(()=>import("./AuthCallbackPage-CleLWd3j.js"),__vite__mapDeps([47,1,2,3]))),UE=y.lazy(gE),ME=y.lazy(bE),FE=null,BE=y.lazy(()=>Ai().then(e=>({default:e.CollectionsPage}))),HE=y.lazy(()=>Ai().then(e=>({default:e.CollectionDetailPage}))),VE=y.lazy(()=>Ai().then(e=>({default:e.PublicCollectionPage}))),WE=y.lazy(SE),$E=y.lazy(xE),YE=600*1e3,GE="TRACE_FICTION_TOKEN",zE="TRACE_FICTION_TOKEN_REQUEST",xr=1,qE=/^[A-Za-z0-9_-]{1,128}$/,KE="TRACE_EXTENSION_STATUS_READY",QE="TRACE_EXTENSION_FIRST_INSTALL_READY",JE="extension-installed";function XE(e){if(!e||typeof e!="object")return;const t=e;if(!(t.reason!=="credential_grant"||t.protocolVersion!==xr||typeof t.requestId!="string"||!qE.test(t.requestId)))return{protocolVersion:xr,requestId:t.requestId}}function ZE(){return i.jsx(gs,{})}function $(e,t=i.jsx(ZE,{})){return i.jsx(Vx,{children:i.jsx(y.Suspense,{fallback:t,children:e})})}function Ve({statusLabel:e,loadingRows:t=3}){return i.jsx(Ix,{statusLabel:e,loadingRows:t})}function ew(){const{pathname:e}=Te(),t=y.useRef(!0);return y.useLayoutEffect(()=>{if(t.current){t.current=!1;return}window.scrollTo(0,0)},[e]),null}function tw(){const{loginWithRedirect:e,logout:t,isAuthenticated:a}=ke(),c=jt(),m=y.useRef(!1);return y.useEffect(()=>{if(a){hr();return}m.current=!1},[a]),y.useLayoutEffect(()=>{const h=d=>{if(m.current)return;m.current=!0;const v=d.detail??{reason:"token_refresh_failed"};if(v.reason==="account_deleted"){c.clear(),Jt("account_deleted_logout_started",v),cl(t,ms(),{deviceSessionsAlreadyRemoved:!0}).catch(s=>{m.current=!1,Jt("account_deleted_logout_failed",{...v,errorCode:Zn(s),errorName:s instanceof Error?s.name:typeof s})});return}const o=Ir();Wn(o),c.clear(),Jt("redirect_started",v),(async()=>{try{await t({openUrl:!1}),await e({appState:{returnTo:o}})}catch(s){hr(),m.current=!1,Jt("redirect_failed",{...v,errorCode:Zn(s),errorName:s instanceof Error?s.name:typeof s}),console.error("Failed to recover auth session",s)}})()};return window.addEventListener(pr,h),()=>{window.removeEventListener(pr,h)}},[e,t,c]),null}function nw(){const{getAccessTokenSilently:e,isAuthenticated:t}=ke(),a=jt(),c=_e(),m=y.useRef(c);y.useLayoutEffect(()=>{m.current=c},[c]),rE(),y.useEffect(()=>av({resolve:v=>m.current.resolveExtensionDeviceSession(v),revoke:v=>m.current.revokeExtensionDeviceSession(v)}),[]);const h=Y.useCallback((v,o)=>{window.postMessage({type:GE,token:v,...o??{}},window.location.origin)},[]),d=Y.useCallback(async({context:v,trigger:o})=>{try{pi();const s=await e();if(h(s,v),ea()){const l=await ol(s,{resolve:b=>m.current.resolveExtensionDeviceSession(b),revoke:b=>m.current.revokeExtensionDeviceSession(b)});!l.ok&&l.error!=="superseded"&&(ts(o,l.error??"native_error"),console.error("Failed to sync token to the iOS Safari credential provider",l.error))}}
5catch(s){ea()&&!(s instanceof Qc)&&ts(o,"access_token_unavailable"),console.error("Failed to sync token to extension",s)}},[e,h]);return y.useEffect(()=>{t&&a.invalidateQueries({queryKey:B.me})},[t,a]),y.useEffect(()=>{t||h(null)},[t,h]),y.useEffect(()=>{if(!t)return;d({trigger:"authenticated"});const v=window.setInterval(()=>{d({trigger:"interval"})},YE);return()=>clearInterval(v)},[t,d]),y.useEffect(()=>{if(!t)return;const v=o=>{if(o.origin!==window.location.origin)return;const s=o.data;!s||typeof s!="object"||s.type!==zE||d({context:XE(s),trigger:"extension_request"})};return window.addEventListener("message",v),()=>{window.removeEventListener("message",v)}},[t,d]),y.useEffect(()=>{if(!t)return;const v=new URL(window.location.href);if(v.pathname!=="/"||v.searchParams.get("activation")!==JE)return;const o=()=>{window.postMessage({type:QE,protocolVersion:xr},window.location.origin)},s=l=>{if(l.origin!==window.location.origin)return;const b=l.data;!b||typeof b!="object"||b.type!==KE||o()};return window.addEventListener("message",s),o(),()=>{window.removeEventListener("message",s)}},[t]),y.useEffect(()=>{if(!t)return;const v=()=>{document.visibilityState!=="hidden"&&(d({trigger:"visibility_refresh"}),a.invalidateQueries({queryKey:B.me}),a.invalidateQueries({queryKey:B.suggestions}),a.invalidateQueries({queryKey:B.library.all}),a.invalidateQueries({queryKey:B.collections.all}),a.invalidateQueries({queryKey:B.stats.all}))};return window.addEventListener("pageshow",v),document.addEventListener("visibilitychange",v),()=>{window.removeEventListener("pageshow",v),document.removeEventListener("visibilitychange",v)}},[t,a,d]),null}function aw(){return _y(),null}function We({children:e}){const{isAuthenticated:t,isLoading:a}=ke(),[c,m]=y.useState(!a),[h,d]=y.useState(t);y.useEffect(()=>{a||(d(t),m(!0))},[t,a]);const v=a?h:t;return y.useEffect(()=>{v&&Tl()},[v]),a&&!c?i.jsx(gs,{}):i.jsxs(i.Fragment,{children:[v&&i.jsxs(i.Fragment,{children:[i.jsx(nw,{}),i.jsx(jx,{}),i.jsx(Ux,{})]}),v?e:F()?$(i.jsx(kE,{}),i.jsx(ue,{})):$(i.jsx(kl,{}),i.jsx(ue,{}))]})}function rw(){return i.jsxs(i.Fragment,{children:[i.jsx(ew,{}),i.jsx(uE,{}),i.jsx(tw,{}),i.jsx(aw,{}),i.jsx(Mu,{children:i.jsxs(Bl,{children:[FE,null,i.jsx(z,{path:"/auth/callback",element:$(i.jsx(jE,{}))}),null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,i.jsx(z,{path:"/",element:i.jsx(We,{children:$(i.jsx(EE,{}),Ve({statusLabel:"Loading library"}))})}),i.jsx(z,{path:"/library/:entryId",element:i.jsx(We,{children:$(i.jsx(wE,{}),Ve({statusLabel:"Loading story detail",loadingRows:3}))})}),i.jsx(z,{path:"/landing",element:$(i.jsx(kl,{}),i.jsx(ue,{}))}),i.jsx(z,{path:"/reader",element:$(i.jsx(TE,{}),i.jsx(ue,{}))}),i.jsx(z,{path:"/import",element:i.jsx(We,{children:$(i.jsx(AE,{}),Ve({statusLabel:"Loading import tools",loadingRows:2}))})}),i.jsx(z,{path:"/collections",element:i.jsx(We,{children:$(i.jsx(BE,{}),Ve({statusLabel:"Loading collections",loadingRows:2}))})}),i.jsx(z,{path:"/collections/:collectionId",element:i.jsx(We,{children:$(i.jsx(HE,{}),Ve({statusLabel:"Loading collection",loadingRows:4}))})}),i.jsx(z,{path:"/shared/collections/:shareSlug",element:$(i.jsx(VE,{}),i.jsx(Pu,{}))}),i.jsx(z,{path:"/stats",element:i.jsx(We,{children:$(i.jsx(NE,{}),Ve({statusLabel:"Loading stats",loadingRows:2}))})}),null,i.jsx(z,{path:"/settings",element:i.jsx(We,{children:$(i.jsx(CE,{}),Ve({statusLabel:"Loading settings",loadingRows:2}))})}),i.jsx(z,{path:"/suggestions",element:i.jsx(We,{children:$(i.jsx(WE,{}),Ve({statusLabel:"Loading check-in",loadingRows:2}))})}),i.jsx(z,{path:"/admin",element:i.jsx(We,{children:$(i.jsx(RE,{}),Ve({statusLabel:"Loading admin dashboard"}))})}),i.jsx(z,{path:"/privacy",element:$(i.jsx(IE,{}),i.jsx(ue,{}))}),i.jsx(z,{path:"/terms",element:$(i.jsx(OE,{}),i.jsx(ue,{}))}),i.jsx(z,{path:"/about",element:$(i.jsx(PE,{}),i.jsx(ue,{}))}),i.jsx(z,{path:"/support",element:$(i.jsx(LE,{}),i.jsx(ue,{}))}),i.jsx(z,{path:"/setup",element:$(i.jsx(hl,{children:i.jsx(ME,{})}),i.jsx(ue,{}))}),i.jsx(z,{path:"/apps",element:$(i.jsx(UE,{}),i.jsx(ue,{}))}),i.jsx(z,{path:"/updates",element:$(i.jsx($E,{}),i.jsx(ue,{}))}),i.jsx(z,{path:"*",element:$(i.jsx(DE,{}),i.jsx(ue,{}))})]})})]})}const iw="dev-3fgwdsvacrowjb87.uk.auth0.com",ow="ivRuX41ZUyrIAoBZYfa4nyxpNMSCMHp7",sw="https://api.tracefiction.com",er="/landing";function cw(e){if(/^https?:\/\//i.test(e))try{const t=new URL(e);return`${t.pathname}${t.search}${t.hash}`}catch{return e}return e.startsWith("/")?e:`/${e}`}function lw(e){return e===er||e.startsWith(`${er}?`)||e.startsWith(`${er}#`)?"/":e}function dw(e){try{const t=new URL(e.startsWith("/")?`${window.location.origin}${e}`:e);
5if(t.searchParams.has("code")||t.searchParams.has("state")){t.searchParams.delete("code"),t.searchParams.delete("state");const a=t.searchParams.toString();return`${t.pathname}${a?`?${a}`:""}${t.hash}`}}catch{}return e}function uw(){const{isAuthenticated:e,user:t}=ke();return Y.useEffect(()=>{Er()&&(e&&t?.sub?Mi({id:t.sub}):Mi(null))},[e,t?.sub]),null}function mw({children:e}){const t=na(),a=F();return i.jsxs(Yl,{domain:iw,clientId:ow,authorizationParams:{audience:sw,scope:"openid profile email offline_access",redirect_uri:Jd()},onRedirectCallback:c=>{hr(),au("oauth_callback_completed");const m=dw(`${window.location.pathname}${window.location.search}${window.location.hash}`),h=cu(c,m);let d=lw(cw(h));(d===nr||d.startsWith(`${nr}?`))&&(d="/"),t(d,{replace:!0})},cacheLocation:Gc,useCookiesForTransactions:!0,authorizeTimeoutInSeconds:a?Mb:void 0,sessionCheckExpiryDays:qc(),useRefreshTokens:zc,useRefreshTokensFallback:Kc(a),children:[i.jsx(uw,{}),e]})}class pw extends Y.Component{state={error:null};static getDerivedStateFromError(t){return{error:t}}componentDidCatch(t,a){Si(t)||(console.error("[ErrorBoundary]",t,a),wr(t,{extra:{componentStack:a.componentStack}}))}handleReload=()=>{xi()};handleGoHome=t=>{t.preventDefault(),Sl()};render(){return this.state.error?i.jsxs("div",{className:"bg-app min-h-dvh",children:[i.jsx(bl,{title:"trace"}),i.jsxs("main",{className:"container max-w-[900px] px-6 py-6",children:[i.jsx("h1",{className:"mb-2.5 text-2xl font-semibold tracking-tight text-content-primary",children:"Something went wrong"}),i.jsx("p",{className:"text-sm text-content-subtle",children:"An unexpected error occurred. You can try reloading the app."}),i.jsx("div",{className:"mt-4 rounded-xl border border-border bg-surface-1 p-3",children:i.jsx("pre",{className:"whitespace-pre-wrap overflow-x-auto text-xs opacity-80 m-0",children:this.state.error?.message})}),i.jsxs("div",{className:"mt-4 flex flex-wrap gap-2",children:[i.jsx(L,{variant:"solid",onClick:this.handleReload,children:"Reload app"}),i.jsx(L,{variant:"outline",render:i.jsx("a",{href:"/",onClick:this.handleGoHome}),nativeButton:!1,children:"Go home"}),i.jsx(L,{variant:"outline",render:i.jsx("a",{href:"mailto:[email protected]"}),nativeButton:!1,children:"Contact support"})]})]})]}):this.props.children}}function hw(){const e="https://b28704fe3186ff69d88636ba6fc41da0@o4511194745470976.ingest.de.sentry.io/4511194758447184";if(!e.trim())return;const t="trace-web@0017ecb533ed";try{Gl({dsn:e,environment:"production",release:t,debug:!1,tracesSampleRate:.1,replaysSessionSampleRate:0,replaysOnErrorSampleRate:0})}catch{}}Hx();hw();Qd();const fw=Hl.createRoot(document.getElementById("root")),_w=new zl;bu();fw.render(i.jsx(Y.StrictMode,{children:i.jsx(ql,{children:i.jsx(Vl,{children:i.jsx(mw,{children:i.jsx(Kl,{client:_w,children:i.jsx(Uy,{children:i.jsx(pw,{children:i.jsx(rw,{})})})})})})})}));export{Hw as $,Cx as A,L as B,dl as C,oA as D,Nn as E,Py as F,Mh as G,Fh as H,yt as I,Re as J,Uw as K,ig as L,wy as M,Iw as N,Ud as O,My as P,Or as Q,bv as R,No as S,yr as T,cl as U,ms as V,Gw as W,Fw as X,Bw as Y,tl as Z,M as _,ul as a,ls as a0,pl as a1,by as a2,Iu as a3,Hn as a4,vw as a5,Wn as a6,Hy as a7,ea as a8,Vw as a9,$i as aA,xw as aB,Md as aC,Ir as aD,Sw as aE,Wd as aF,Ew as aG,ww as aH,Aw as aI,hr as aJ,Jt as aK,Zn as aL,tu as aM,gs as aN,nr as aO,Cw as aP,Rw as aQ,gy as aR,Ww as aa,_i as ab,du as ac,kw as ad,Tw as ae,iA as af,rA as ag,Ow as ah,Bh as ai,Su as aj,Vu as ak,Bp as al,Os as am,aS as an,ju as ao,Pw as ap,Uc as aq,Rv as ar,Kw as as,Zw as at,eA as au,Qw as av,Xw as aw,Nv as ax,Jw as ay,Vd as az,ps as b,I as c,Mw as d,$w as e,mh as f,wv as g,jw as h,Sv as i,qw as j,Nw as k,F as l,Ps as m,sA as n,Ue as o,Dw as p,B as q,Yw as r,Lw as s,_l as t,_e as u,nA as v,zw as w,uu as x,aA as y,tA as z};

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.