@ainyc/canonry 1.37.1 → 1.39.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -92,7 +92,7 @@ For more information, see https://radix-ui.com/primitives/docs/components/${t.do
92
92
  `)}y.write("payload.value = newResult;"),y.write("return payload;");const A=y.compile();return(k,O)=>A(v,k,O)};let s;const l=cm,c=!aD.jitless,h=c&&z7.value,p=t.catchall;let g;e._zod.parse=(v,y)=>{g??(g=r.value);const S=v.value;return l(S)?c&&h&&y?.async===!1&&y.jitless!==!0?(s||(s=i(t.shape)),v=s(v,y),p?SD([],S,v,y,g,e):v):n(v,y):(v.issues.push({expected:"object",code:"invalid_type",input:S,inst:e}),v)}});function $A(e,t,n,r){for(const s of e)if(s.issues.length===0)return t.value=s.value,t;const i=e.filter(s=>!hc(s));return i.length===1?(t.value=i[0].value,i[0]):(t.issues.push({code:"invalid_union",input:t.value,inst:n,errors:e.map(s=>s.issues.map(l=>Rs(l,r,Ms())))}),t)}const bV=ue("$ZodUnion",(e,t)=>{Ft.init(e,t),bt(e._zod,"optin",()=>t.options.some(i=>i._zod.optin==="optional")?"optional":void 0),bt(e._zod,"optout",()=>t.options.some(i=>i._zod.optout==="optional")?"optional":void 0),bt(e._zod,"values",()=>{if(t.options.every(i=>i._zod.values))return new Set(t.options.flatMap(i=>Array.from(i._zod.values)))}),bt(e._zod,"pattern",()=>{if(t.options.every(i=>i._zod.pattern)){const i=t.options.map(s=>s._zod.pattern);return new RegExp(`^(${i.map(s=>d1(s.source)).join("|")})$`)}});const n=t.options.length===1,r=t.options[0]._zod.run;e._zod.parse=(i,s)=>{if(n)return r(i,s);let l=!1;const c=[];for(const f of t.options){const h=f._zod.run({value:i.value,issues:[]},s);if(h instanceof Promise)c.push(h),l=!0;else{if(h.issues.length===0)return h;c.push(h)}}return l?Promise.all(c).then(f=>$A(f,i,e,s)):$A(c,i,e,s)}}),xV=ue("$ZodIntersection",(e,t)=>{Ft.init(e,t),e._zod.parse=(n,r)=>{const i=n.value,s=t.left._zod.run({value:i,issues:[]},r),l=t.right._zod.run({value:i,issues:[]},r);return s instanceof Promise||l instanceof Promise?Promise.all([s,l]).then(([f,h])=>UA(n,f,h)):UA(n,s,l)}});function xw(e,t){if(e===t)return{valid:!0,data:e};if(e instanceof Date&&t instanceof Date&&+e==+t)return{valid:!0,data:e};if(Ec(e)&&Ec(t)){const n=Object.keys(t),r=Object.keys(e).filter(s=>n.indexOf(s)!==-1),i={...e,...t};for(const s of r){const l=xw(e[s],t[s]);if(!l.valid)return{valid:!1,mergeErrorPath:[s,...l.mergeErrorPath]};i[s]=l.data}return{valid:!0,data:i}}if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return{valid:!1,mergeErrorPath:[]};const n=[];for(let r=0;r<e.length;r++){const i=e[r],s=t[r],l=xw(i,s);if(!l.valid)return{valid:!1,mergeErrorPath:[r,...l.mergeErrorPath]};n.push(l.data)}return{valid:!0,data:n}}return{valid:!1,mergeErrorPath:[]}}function UA(e,t,n){const r=new Map;let i;for(const c of t.issues)if(c.code==="unrecognized_keys"){i??(i=c);for(const f of c.keys)r.has(f)||r.set(f,{}),r.get(f).l=!0}else e.issues.push(c);for(const c of n.issues)if(c.code==="unrecognized_keys")for(const f of c.keys)r.has(f)||r.set(f,{}),r.get(f).r=!0;else e.issues.push(c);const s=[...r].filter(([,c])=>c.l&&c.r).map(([c])=>c);if(s.length&&i&&e.issues.push({...i,keys:s}),hc(e))return e;const l=xw(t.value,n.value);if(!l.valid)throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(l.mergeErrorPath)}`);return e.value=l.data,e}const wV=ue("$ZodRecord",(e,t)=>{Ft.init(e,t),e._zod.parse=(n,r)=>{const i=n.value;if(!Ec(i))return n.issues.push({expected:"record",code:"invalid_type",input:i,inst:e}),n;const s=[],l=t.keyType._zod.values;if(l){n.value={};const c=new Set;for(const h of l)if(typeof h=="string"||typeof h=="number"||typeof h=="symbol"){c.add(typeof h=="number"?h.toString():h);const p=t.valueType._zod.run({value:i[h],issues:[]},r);p instanceof Promise?s.push(p.then(g=>{g.issues.length&&n.issues.push(...pc(h,g.issues)),n.value[h]=g.value})):(p.issues.length&&n.issues.push(...pc(h,p.issues)),n.value[h]=p.value)}let f;for(const h in i)c.has(h)||(f=f??[],f.push(h));f&&f.length>0&&n.issues.push({code:"unrecognized_keys",input:i,inst:e,keys:f})}else{n.value={};for(const c of Reflect.ownKeys(i)){if(c==="__proto__")continue;let f=t.keyType._zod.run({value:c,issues:[]},r);if(f instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(typeof c=="string"&&mD.test(c)&&f.issues.length){const g=t.keyType._zod.run({value:Number(c),issues:[]},r);if(g instanceof Promise)throw new Error("Async schemas not supported in object keys currently");g.issues.length===0&&(f=g)}if(f.issues.length){t.mode==="loose"?n.value[c]=i[c]:n.issues.push({code:"invalid_key",origin:"record",issues:f.issues.map(g=>Rs(g,r,Ms())),input:c,path:[c],inst:e});continue}const p=t.valueType._zod.run({value:i[c],issues:[]},r);p instanceof Promise?s.push(p.then(g=>{g.issues.length&&n.issues.push(...pc(c,g.issues)),n.value[f.value]=g.value})):(p.issues.length&&n.issues.push(...pc(c,p.issues)),n.value[f.value]=p.value)}}return s.length?Promise.all(s).then(()=>n):n}}),SV=ue("$ZodEnum",(e,t)=>{Ft.init(e,t);const n=sD(t.entries),r=new Set(n);e._zod.values=r,e._zod.pattern=new RegExp(`^(${n.filter(i=>M7.has(typeof i)).map(i=>typeof i=="string"?Tc(i):i.toString()).join("|")})$`),e._zod.parse=(i,s)=>{const l=i.value;return r.has(l)||i.issues.push({code:"invalid_value",values:n,input:l,inst:e}),i}}),jV=ue("$ZodLiteral",(e,t)=>{if(Ft.init(e,t),t.values.length===0)throw new Error("Cannot create literal schema with no valid values");const n=new Set(t.values);e._zod.values=n,e._zod.pattern=new RegExp(`^(${t.values.map(r=>typeof r=="string"?Tc(r):r?Tc(r.toString()):String(r)).join("|")})$`),e._zod.parse=(r,i)=>{const s=r.value;return n.has(s)||r.issues.push({code:"invalid_value",values:t.values,input:s,inst:e}),r}}),NV=ue("$ZodTransform",(e,t)=>{Ft.init(e,t),e._zod.parse=(n,r)=>{if(r.direction==="backward")throw new iD(e.constructor.name);const i=t.transform(n.value,n);if(r.async)return(i instanceof Promise?i:Promise.resolve(i)).then(l=>(n.value=l,n));if(i instanceof Promise)throw new Sc;return n.value=i,n}});function BA(e,t){return e.issues.length&&t===void 0?{issues:[],value:void 0}:e}const jD=ue("$ZodOptional",(e,t)=>{Ft.init(e,t),e._zod.optin="optional",e._zod.optout="optional",bt(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0),bt(e._zod,"pattern",()=>{const n=t.innerType._zod.pattern;return n?new RegExp(`^(${d1(n.source)})?$`):void 0}),e._zod.parse=(n,r)=>{if(t.innerType._zod.optin==="optional"){const i=t.innerType._zod.run(n,r);return i instanceof Promise?i.then(s=>BA(s,n.value)):BA(i,n.value)}return n.value===void 0?n:t.innerType._zod.run(n,r)}}),CV=ue("$ZodExactOptional",(e,t)=>{jD.init(e,t),bt(e._zod,"values",()=>t.innerType._zod.values),bt(e._zod,"pattern",()=>t.innerType._zod.pattern),e._zod.parse=(n,r)=>t.innerType._zod.run(n,r)}),OV=ue("$ZodNullable",(e,t)=>{Ft.init(e,t),bt(e._zod,"optin",()=>t.innerType._zod.optin),bt(e._zod,"optout",()=>t.innerType._zod.optout),bt(e._zod,"pattern",()=>{const n=t.innerType._zod.pattern;return n?new RegExp(`^(${d1(n.source)}|null)$`):void 0}),bt(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,null]):void 0),e._zod.parse=(n,r)=>n.value===null?n:t.innerType._zod.run(n,r)}),_V=ue("$ZodDefault",(e,t)=>{Ft.init(e,t),e._zod.optin="optional",bt(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(n,r)=>{if(r.direction==="backward")return t.innerType._zod.run(n,r);if(n.value===void 0)return n.value=t.defaultValue,n;const i=t.innerType._zod.run(n,r);return i instanceof Promise?i.then(s=>qA(s,t)):qA(i,t)}});function qA(e,t){return e.value===void 0&&(e.value=t.defaultValue),e}const kV=ue("$ZodPrefault",(e,t)=>{Ft.init(e,t),e._zod.optin="optional",bt(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(n,r)=>(r.direction==="backward"||n.value===void 0&&(n.value=t.defaultValue),t.innerType._zod.run(n,r))}),AV=ue("$ZodNonOptional",(e,t)=>{Ft.init(e,t),bt(e._zod,"values",()=>{const n=t.innerType._zod.values;return n?new Set([...n].filter(r=>r!==void 0)):void 0}),e._zod.parse=(n,r)=>{const i=t.innerType._zod.run(n,r);return i instanceof Promise?i.then(s=>FA(s,e)):FA(i,e)}});function FA(e,t){return!e.issues.length&&e.value===void 0&&e.issues.push({code:"invalid_type",expected:"nonoptional",input:e.value,inst:t}),e}const EV=ue("$ZodCatch",(e,t)=>{Ft.init(e,t),bt(e._zod,"optin",()=>t.innerType._zod.optin),bt(e._zod,"optout",()=>t.innerType._zod.optout),bt(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(n,r)=>{if(r.direction==="backward")return t.innerType._zod.run(n,r);const i=t.innerType._zod.run(n,r);return i instanceof Promise?i.then(s=>(n.value=s.value,s.issues.length&&(n.value=t.catchValue({...n,error:{issues:s.issues.map(l=>Rs(l,r,Ms()))},input:n.value}),n.issues=[]),n)):(n.value=i.value,i.issues.length&&(n.value=t.catchValue({...n,error:{issues:i.issues.map(s=>Rs(s,r,Ms()))},input:n.value}),n.issues=[]),n)}}),TV=ue("$ZodPipe",(e,t)=>{Ft.init(e,t),bt(e._zod,"values",()=>t.in._zod.values),bt(e._zod,"optin",()=>t.in._zod.optin),bt(e._zod,"optout",()=>t.out._zod.optout),bt(e._zod,"propValues",()=>t.in._zod.propValues),e._zod.parse=(n,r)=>{if(r.direction==="backward"){const s=t.out._zod.run(n,r);return s instanceof Promise?s.then(l=>ap(l,t.in,r)):ap(s,t.in,r)}const i=t.in._zod.run(n,r);return i instanceof Promise?i.then(s=>ap(s,t.out,r)):ap(i,t.out,r)}});function ap(e,t,n){return e.issues.length?(e.aborted=!0,e):t._zod.run({value:e.value,issues:e.issues},n)}const PV=ue("$ZodReadonly",(e,t)=>{Ft.init(e,t),bt(e._zod,"propValues",()=>t.innerType._zod.propValues),bt(e._zod,"values",()=>t.innerType._zod.values),bt(e._zod,"optin",()=>t.innerType?._zod?.optin),bt(e._zod,"optout",()=>t.innerType?._zod?.optout),e._zod.parse=(n,r)=>{if(r.direction==="backward")return t.innerType._zod.run(n,r);const i=t.innerType._zod.run(n,r);return i instanceof Promise?i.then(KA):KA(i)}});function KA(e){return e.value=Object.freeze(e.value),e}const zV=ue("$ZodCustom",(e,t)=>{yr.init(e,t),Ft.init(e,t),e._zod.parse=(n,r)=>n,e._zod.check=n=>{const r=n.value,i=t.fn(r);if(i instanceof Promise)return i.then(s=>HA(s,n,r,e));HA(i,n,r,e)}});function HA(e,t,n,r){if(!e){const i={code:"custom",input:n,inst:r,path:[...r._zod.def.path??[]],continue:!r._zod.def.abort};r._zod.def.params&&(i.params=r._zod.def.params),t.issues.push(Dd(i))}}var GA;class MV{constructor(){this._map=new WeakMap,this._idmap=new Map}add(t,...n){const r=n[0];return this._map.set(t,r),r&&typeof r=="object"&&"id"in r&&this._idmap.set(r.id,t),this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove(t){const n=this._map.get(t);return n&&typeof n=="object"&&"id"in n&&this._idmap.delete(n.id),this._map.delete(t),this}get(t){const n=t._zod.parent;if(n){const r={...this.get(n)??{}};delete r.id;const i={...r,...this._map.get(t)};return Object.keys(i).length?i:void 0}return this._map.get(t)}has(t){return this._map.has(t)}}function RV(){return new MV}(GA=globalThis).__zod_globalRegistry??(GA.__zod_globalRegistry=RV());const gd=globalThis.__zod_globalRegistry;function DV(e,t){return new e({type:"string",...De(t)})}function IV(e,t){return new e({type:"string",format:"email",check:"string_format",abort:!1,...De(t)})}function VA(e,t){return new e({type:"string",format:"guid",check:"string_format",abort:!1,...De(t)})}function LV(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,...De(t)})}function $V(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...De(t)})}function UV(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...De(t)})}function BV(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...De(t)})}function qV(e,t){return new e({type:"string",format:"url",check:"string_format",abort:!1,...De(t)})}function FV(e,t){return new e({type:"string",format:"emoji",check:"string_format",abort:!1,...De(t)})}function KV(e,t){return new e({type:"string",format:"nanoid",check:"string_format",abort:!1,...De(t)})}function HV(e,t){return new e({type:"string",format:"cuid",check:"string_format",abort:!1,...De(t)})}function GV(e,t){return new e({type:"string",format:"cuid2",check:"string_format",abort:!1,...De(t)})}function VV(e,t){return new e({type:"string",format:"ulid",check:"string_format",abort:!1,...De(t)})}function ZV(e,t){return new e({type:"string",format:"xid",check:"string_format",abort:!1,...De(t)})}function YV(e,t){return new e({type:"string",format:"ksuid",check:"string_format",abort:!1,...De(t)})}function WV(e,t){return new e({type:"string",format:"ipv4",check:"string_format",abort:!1,...De(t)})}function QV(e,t){return new e({type:"string",format:"ipv6",check:"string_format",abort:!1,...De(t)})}function XV(e,t){return new e({type:"string",format:"cidrv4",check:"string_format",abort:!1,...De(t)})}function JV(e,t){return new e({type:"string",format:"cidrv6",check:"string_format",abort:!1,...De(t)})}function eZ(e,t){return new e({type:"string",format:"base64",check:"string_format",abort:!1,...De(t)})}function tZ(e,t){return new e({type:"string",format:"base64url",check:"string_format",abort:!1,...De(t)})}function nZ(e,t){return new e({type:"string",format:"e164",check:"string_format",abort:!1,...De(t)})}function rZ(e,t){return new e({type:"string",format:"jwt",check:"string_format",abort:!1,...De(t)})}function iZ(e,t){return new e({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...De(t)})}function aZ(e,t){return new e({type:"string",format:"date",check:"string_format",...De(t)})}function sZ(e,t){return new e({type:"string",format:"time",check:"string_format",precision:null,...De(t)})}function oZ(e,t){return new e({type:"string",format:"duration",check:"string_format",...De(t)})}function lZ(e,t){return new e({type:"number",checks:[],...De(t)})}function cZ(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"safeint",...De(t)})}function uZ(e,t){return new e({type:"boolean",...De(t)})}function dZ(e){return new e({type:"unknown"})}function fZ(e,t){return new e({type:"never",...De(t)})}function ZA(e,t){return new vD({check:"less_than",...De(t),value:e,inclusive:!1})}function pb(e,t){return new vD({check:"less_than",...De(t),value:e,inclusive:!0})}function YA(e,t){return new yD({check:"greater_than",...De(t),value:e,inclusive:!1})}function mb(e,t){return new yD({check:"greater_than",...De(t),value:e,inclusive:!0})}function WA(e,t){return new _G({check:"multiple_of",...De(t),value:e})}function ND(e,t){return new AG({check:"max_length",...De(t),maximum:e})}function dm(e,t){return new EG({check:"min_length",...De(t),minimum:e})}function CD(e,t){return new TG({check:"length_equals",...De(t),length:e})}function hZ(e,t){return new PG({check:"string_format",format:"regex",...De(t),pattern:e})}function pZ(e){return new zG({check:"string_format",format:"lowercase",...De(e)})}function mZ(e){return new MG({check:"string_format",format:"uppercase",...De(e)})}function gZ(e,t){return new RG({check:"string_format",format:"includes",...De(t),includes:e})}function vZ(e,t){return new DG({check:"string_format",format:"starts_with",...De(t),prefix:e})}function yZ(e,t){return new IG({check:"string_format",format:"ends_with",...De(t),suffix:e})}function Kc(e){return new LG({check:"overwrite",tx:e})}function bZ(e){return Kc(t=>t.normalize(e))}function xZ(){return Kc(e=>e.trim())}function wZ(){return Kc(e=>e.toLowerCase())}function SZ(){return Kc(e=>e.toUpperCase())}function jZ(){return Kc(e=>P7(e))}function NZ(e,t,n){return new e({type:"array",element:t,...De(n)})}function CZ(e,t,n){return new e({type:"custom",check:"custom",fn:t,...De(n)})}function OZ(e){const t=_Z(n=>(n.addIssue=r=>{if(typeof r=="string")n.issues.push(Dd(r,n.value,t._zod.def));else{const i=r;i.fatal&&(i.continue=!1),i.code??(i.code="custom"),i.input??(i.input=n.value),i.inst??(i.inst=t),i.continue??(i.continue=!t._zod.def.abort),n.issues.push(Dd(i))}},e(n.value,n)));return t}function _Z(e,t){const n=new yr({check:"custom",...De(t)});return n._zod.check=e,n}function OD(e){let t=e?.target??"draft-2020-12";return t==="draft-4"&&(t="draft-04"),t==="draft-7"&&(t="draft-07"),{processors:e.processors??{},metadataRegistry:e?.metadata??gd,target:t,unrepresentable:e?.unrepresentable??"throw",override:e?.override??(()=>{}),io:e?.io??"output",counter:0,seen:new Map,cycles:e?.cycles??"ref",reused:e?.reused??"inline",external:e?.external??void 0}}function cn(e,t,n={path:[],schemaPath:[]}){var r;const i=e._zod.def,s=t.seen.get(e);if(s)return s.count++,n.schemaPath.includes(e)&&(s.cycle=n.path),s.schema;const l={schema:{},count:1,cycle:void 0,path:n.path};t.seen.set(e,l);const c=e._zod.toJSONSchema?.();if(c)l.schema=c;else{const p={...n,schemaPath:[...n.schemaPath,e],path:n.path};if(e._zod.processJSONSchema)e._zod.processJSONSchema(t,l.schema,p);else{const v=l.schema,y=t.processors[i.type];if(!y)throw new Error(`[toJSONSchema]: Non-representable type encountered: ${i.type}`);y(e,t,v,p)}const g=e._zod.parent;g&&(l.ref||(l.ref=g),cn(g,t,p),t.seen.get(g).isParent=!0)}const f=t.metadataRegistry.get(e);return f&&Object.assign(l.schema,f),t.io==="input"&&Wn(e)&&(delete l.schema.examples,delete l.schema.default),t.io==="input"&&l.schema._prefault&&((r=l.schema).default??(r.default=l.schema._prefault)),delete l.schema._prefault,t.seen.get(e).schema}function _D(e,t){const n=e.seen.get(t);if(!n)throw new Error("Unprocessed schema. This is a bug in Zod.");const r=new Map;for(const l of e.seen.entries()){const c=e.metadataRegistry.get(l[0])?.id;if(c){const f=r.get(c);if(f&&f!==l[0])throw new Error(`Duplicate schema id "${c}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);r.set(c,l[0])}}const i=l=>{const c=e.target==="draft-2020-12"?"$defs":"definitions";if(e.external){const g=e.external.registry.get(l[0])?.id,v=e.external.uri??(S=>S);if(g)return{ref:v(g)};const y=l[1].defId??l[1].schema.id??`schema${e.counter++}`;return l[1].defId=y,{defId:y,ref:`${v("__shared")}#/${c}/${y}`}}if(l[1]===n)return{ref:"#"};const h=`#/${c}/`,p=l[1].schema.id??`__schema${e.counter++}`;return{defId:p,ref:h+p}},s=l=>{if(l[1].schema.$ref)return;const c=l[1],{ref:f,defId:h}=i(l);c.def={...c.schema},h&&(c.defId=h);const p=c.schema;for(const g in p)delete p[g];p.$ref=f};if(e.cycles==="throw")for(const l of e.seen.entries()){const c=l[1];if(c.cycle)throw new Error(`Cycle detected: #/${c.cycle?.join("/")}/<root>
93
93
 
94
94
  Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(const l of e.seen.entries()){const c=l[1];if(t===l[0]){s(l);continue}if(e.external){const h=e.external.registry.get(l[0])?.id;if(t!==l[0]&&h){s(l);continue}}if(e.metadataRegistry.get(l[0])?.id){s(l);continue}if(c.cycle){s(l);continue}if(c.count>1&&e.reused==="ref"){s(l);continue}}}function kD(e,t){const n=e.seen.get(t);if(!n)throw new Error("Unprocessed schema. This is a bug in Zod.");const r=l=>{const c=e.seen.get(l);if(c.ref===null)return;const f=c.def??c.schema,h={...f},p=c.ref;if(c.ref=null,p){r(p);const v=e.seen.get(p),y=v.schema;if(y.$ref&&(e.target==="draft-07"||e.target==="draft-04"||e.target==="openapi-3.0")?(f.allOf=f.allOf??[],f.allOf.push(y)):Object.assign(f,y),Object.assign(f,h),l._zod.parent===p)for(const w in f)w==="$ref"||w==="allOf"||w in h||delete f[w];if(y.$ref&&v.def)for(const w in f)w==="$ref"||w==="allOf"||w in v.def&&JSON.stringify(f[w])===JSON.stringify(v.def[w])&&delete f[w]}const g=l._zod.parent;if(g&&g!==p){r(g);const v=e.seen.get(g);if(v?.schema.$ref&&(f.$ref=v.schema.$ref,v.def))for(const y in f)y==="$ref"||y==="allOf"||y in v.def&&JSON.stringify(f[y])===JSON.stringify(v.def[y])&&delete f[y]}e.override({zodSchema:l,jsonSchema:f,path:c.path??[]})};for(const l of[...e.seen.entries()].reverse())r(l[0]);const i={};if(e.target==="draft-2020-12"?i.$schema="https://json-schema.org/draft/2020-12/schema":e.target==="draft-07"?i.$schema="http://json-schema.org/draft-07/schema#":e.target==="draft-04"?i.$schema="http://json-schema.org/draft-04/schema#":e.target,e.external?.uri){const l=e.external.registry.get(t)?.id;if(!l)throw new Error("Schema is missing an `id` property");i.$id=e.external.uri(l)}Object.assign(i,n.def??n.schema);const s=e.external?.defs??{};for(const l of e.seen.entries()){const c=l[1];c.def&&c.defId&&(s[c.defId]=c.def)}e.external||Object.keys(s).length>0&&(e.target==="draft-2020-12"?i.$defs=s:i.definitions=s);try{const l=JSON.parse(JSON.stringify(i));return Object.defineProperty(l,"~standard",{value:{...t["~standard"],jsonSchema:{input:fm(t,"input",e.processors),output:fm(t,"output",e.processors)}},enumerable:!1,writable:!1}),l}catch{throw new Error("Error converting schema to JSON.")}}function Wn(e,t){const n=t??{seen:new Set};if(n.seen.has(e))return!1;n.seen.add(e);const r=e._zod.def;if(r.type==="transform")return!0;if(r.type==="array")return Wn(r.element,n);if(r.type==="set")return Wn(r.valueType,n);if(r.type==="lazy")return Wn(r.getter(),n);if(r.type==="promise"||r.type==="optional"||r.type==="nonoptional"||r.type==="nullable"||r.type==="readonly"||r.type==="default"||r.type==="prefault")return Wn(r.innerType,n);if(r.type==="intersection")return Wn(r.left,n)||Wn(r.right,n);if(r.type==="record"||r.type==="map")return Wn(r.keyType,n)||Wn(r.valueType,n);if(r.type==="pipe")return Wn(r.in,n)||Wn(r.out,n);if(r.type==="object"){for(const i in r.shape)if(Wn(r.shape[i],n))return!0;return!1}if(r.type==="union"){for(const i of r.options)if(Wn(i,n))return!0;return!1}if(r.type==="tuple"){for(const i of r.items)if(Wn(i,n))return!0;return!!(r.rest&&Wn(r.rest,n))}return!1}const kZ=(e,t={})=>n=>{const r=OD({...n,processors:t});return cn(e,r),_D(r,e),kD(r,e)},fm=(e,t,n={})=>r=>{const{libraryOptions:i,target:s}=r??{},l=OD({...i??{},target:s,io:t,processors:n});return cn(e,l),_D(l,e),kD(l,e)},AZ={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},EZ=(e,t,n,r)=>{const i=n;i.type="string";const{minimum:s,maximum:l,format:c,patterns:f,contentEncoding:h}=e._zod.bag;if(typeof s=="number"&&(i.minLength=s),typeof l=="number"&&(i.maxLength=l),c&&(i.format=AZ[c]??c,i.format===""&&delete i.format,c==="time"&&delete i.format),h&&(i.contentEncoding=h),f&&f.size>0){const p=[...f];p.length===1?i.pattern=p[0].source:p.length>1&&(i.allOf=[...p.map(g=>({...t.target==="draft-07"||t.target==="draft-04"||t.target==="openapi-3.0"?{type:"string"}:{},pattern:g.source}))])}},TZ=(e,t,n,r)=>{const i=n,{minimum:s,maximum:l,format:c,multipleOf:f,exclusiveMaximum:h,exclusiveMinimum:p}=e._zod.bag;typeof c=="string"&&c.includes("int")?i.type="integer":i.type="number",typeof p=="number"&&(t.target==="draft-04"||t.target==="openapi-3.0"?(i.minimum=p,i.exclusiveMinimum=!0):i.exclusiveMinimum=p),typeof s=="number"&&(i.minimum=s,typeof p=="number"&&t.target!=="draft-04"&&(p>=s?delete i.minimum:delete i.exclusiveMinimum)),typeof h=="number"&&(t.target==="draft-04"||t.target==="openapi-3.0"?(i.maximum=h,i.exclusiveMaximum=!0):i.exclusiveMaximum=h),typeof l=="number"&&(i.maximum=l,typeof h=="number"&&t.target!=="draft-04"&&(h<=l?delete i.maximum:delete i.exclusiveMaximum)),typeof f=="number"&&(i.multipleOf=f)},PZ=(e,t,n,r)=>{n.type="boolean"},zZ=(e,t,n,r)=>{n.not={}},MZ=(e,t,n,r)=>{},RZ=(e,t,n,r)=>{const i=e._zod.def,s=sD(i.entries);s.every(l=>typeof l=="number")&&(n.type="number"),s.every(l=>typeof l=="string")&&(n.type="string"),n.enum=s},DZ=(e,t,n,r)=>{const i=e._zod.def,s=[];for(const l of i.values)if(l===void 0){if(t.unrepresentable==="throw")throw new Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof l=="bigint"){if(t.unrepresentable==="throw")throw new Error("BigInt literals cannot be represented in JSON Schema");s.push(Number(l))}else s.push(l);if(s.length!==0)if(s.length===1){const l=s[0];n.type=l===null?"null":typeof l,t.target==="draft-04"||t.target==="openapi-3.0"?n.enum=[l]:n.const=l}else s.every(l=>typeof l=="number")&&(n.type="number"),s.every(l=>typeof l=="string")&&(n.type="string"),s.every(l=>typeof l=="boolean")&&(n.type="boolean"),s.every(l=>l===null)&&(n.type="null"),n.enum=s},IZ=(e,t,n,r)=>{if(t.unrepresentable==="throw")throw new Error("Custom types cannot be represented in JSON Schema")},LZ=(e,t,n,r)=>{if(t.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema")},$Z=(e,t,n,r)=>{const i=n,s=e._zod.def,{minimum:l,maximum:c}=e._zod.bag;typeof l=="number"&&(i.minItems=l),typeof c=="number"&&(i.maxItems=c),i.type="array",i.items=cn(s.element,t,{...r,path:[...r.path,"items"]})},UZ=(e,t,n,r)=>{const i=n,s=e._zod.def;i.type="object",i.properties={};const l=s.shape;for(const h in l)i.properties[h]=cn(l[h],t,{...r,path:[...r.path,"properties",h]});const c=new Set(Object.keys(l)),f=new Set([...c].filter(h=>{const p=s.shape[h]._zod;return t.io==="input"?p.optin===void 0:p.optout===void 0}));f.size>0&&(i.required=Array.from(f)),s.catchall?._zod.def.type==="never"?i.additionalProperties=!1:s.catchall?s.catchall&&(i.additionalProperties=cn(s.catchall,t,{...r,path:[...r.path,"additionalProperties"]})):t.io==="output"&&(i.additionalProperties=!1)},BZ=(e,t,n,r)=>{const i=e._zod.def,s=i.inclusive===!1,l=i.options.map((c,f)=>cn(c,t,{...r,path:[...r.path,s?"oneOf":"anyOf",f]}));s?n.oneOf=l:n.anyOf=l},qZ=(e,t,n,r)=>{const i=e._zod.def,s=cn(i.left,t,{...r,path:[...r.path,"allOf",0]}),l=cn(i.right,t,{...r,path:[...r.path,"allOf",1]}),c=h=>"allOf"in h&&Object.keys(h).length===1,f=[...c(s)?s.allOf:[s],...c(l)?l.allOf:[l]];n.allOf=f},FZ=(e,t,n,r)=>{const i=n,s=e._zod.def;i.type="object";const l=s.keyType,f=l._zod.bag?.patterns;if(s.mode==="loose"&&f&&f.size>0){const p=cn(s.valueType,t,{...r,path:[...r.path,"patternProperties","*"]});i.patternProperties={};for(const g of f)i.patternProperties[g.source]=p}else(t.target==="draft-07"||t.target==="draft-2020-12")&&(i.propertyNames=cn(s.keyType,t,{...r,path:[...r.path,"propertyNames"]})),i.additionalProperties=cn(s.valueType,t,{...r,path:[...r.path,"additionalProperties"]});const h=l._zod.values;if(h){const p=[...h].filter(g=>typeof g=="string"||typeof g=="number");p.length>0&&(i.required=p)}},KZ=(e,t,n,r)=>{const i=e._zod.def,s=cn(i.innerType,t,r),l=t.seen.get(e);t.target==="openapi-3.0"?(l.ref=i.innerType,n.nullable=!0):n.anyOf=[s,{type:"null"}]},HZ=(e,t,n,r)=>{const i=e._zod.def;cn(i.innerType,t,r);const s=t.seen.get(e);s.ref=i.innerType},GZ=(e,t,n,r)=>{const i=e._zod.def;cn(i.innerType,t,r);const s=t.seen.get(e);s.ref=i.innerType,n.default=JSON.parse(JSON.stringify(i.defaultValue))},VZ=(e,t,n,r)=>{const i=e._zod.def;cn(i.innerType,t,r);const s=t.seen.get(e);s.ref=i.innerType,t.io==="input"&&(n._prefault=JSON.parse(JSON.stringify(i.defaultValue)))},ZZ=(e,t,n,r)=>{const i=e._zod.def;cn(i.innerType,t,r);const s=t.seen.get(e);s.ref=i.innerType;let l;try{l=i.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}n.default=l},YZ=(e,t,n,r)=>{const i=e._zod.def,s=t.io==="input"?i.in._zod.def.type==="transform"?i.out:i.in:i.out;cn(s,t,r);const l=t.seen.get(e);l.ref=s},WZ=(e,t,n,r)=>{const i=e._zod.def;cn(i.innerType,t,r);const s=t.seen.get(e);s.ref=i.innerType,n.readOnly=!0},AD=(e,t,n,r)=>{const i=e._zod.def;cn(i.innerType,t,r);const s=t.seen.get(e);s.ref=i.innerType},QZ=ue("ZodISODateTime",(e,t)=>{XG.init(e,t),Ht.init(e,t)});function XZ(e){return iZ(QZ,e)}const JZ=ue("ZodISODate",(e,t)=>{JG.init(e,t),Ht.init(e,t)});function eY(e){return aZ(JZ,e)}const tY=ue("ZodISOTime",(e,t)=>{eV.init(e,t),Ht.init(e,t)});function nY(e){return sZ(tY,e)}const rY=ue("ZodISODuration",(e,t)=>{tV.init(e,t),Ht.init(e,t)});function iY(e){return oZ(rY,e)}const aY=(e,t)=>{uD.init(e,t),e.name="ZodError",Object.defineProperties(e,{format:{value:n=>H7(e,n)},flatten:{value:n=>K7(e,n)},addIssue:{value:n=>{e.issues.push(n),e.message=JSON.stringify(e.issues,bw,2)}},addIssues:{value:n=>{e.issues.push(...n),e.message=JSON.stringify(e.issues,bw,2)}},isEmpty:{get(){return e.issues.length===0}}})},si=ue("ZodError",aY,{Parent:Error}),sY=h1(si),oY=p1(si),lY=Eg(si),cY=Tg(si),uY=Z7(si),dY=Y7(si),fY=W7(si),hY=Q7(si),pY=X7(si),mY=J7(si),gY=eG(si),vY=tG(si),Kt=ue("ZodType",(e,t)=>(Ft.init(e,t),Object.assign(e["~standard"],{jsonSchema:{input:fm(e,"input"),output:fm(e,"output")}}),e.toJSONSchema=kZ(e,{}),e.def=t,e.type=t.type,Object.defineProperty(e,"_def",{value:t}),e.check=(...n)=>e.clone(qs(t,{checks:[...t.checks??[],...n.map(r=>typeof r=="function"?{_zod:{check:r,def:{check:"custom"},onattach:[]}}:r)]}),{parent:!0}),e.with=e.check,e.clone=(n,r)=>Fs(e,n,r),e.brand=()=>e,e.register=((n,r)=>(n.add(e,r),e)),e.parse=(n,r)=>sY(e,n,r,{callee:e.parse}),e.safeParse=(n,r)=>lY(e,n,r),e.parseAsync=async(n,r)=>oY(e,n,r,{callee:e.parseAsync}),e.safeParseAsync=async(n,r)=>cY(e,n,r),e.spa=e.safeParseAsync,e.encode=(n,r)=>uY(e,n,r),e.decode=(n,r)=>dY(e,n,r),e.encodeAsync=async(n,r)=>fY(e,n,r),e.decodeAsync=async(n,r)=>hY(e,n,r),e.safeEncode=(n,r)=>pY(e,n,r),e.safeDecode=(n,r)=>mY(e,n,r),e.safeEncodeAsync=async(n,r)=>gY(e,n,r),e.safeDecodeAsync=async(n,r)=>vY(e,n,r),e.refine=(n,r)=>e.check(dW(n,r)),e.superRefine=n=>e.check(fW(n)),e.overwrite=n=>e.check(Kc(n)),e.optional=()=>JA(e),e.exactOptional=()=>XY(e),e.nullable=()=>eE(e),e.nullish=()=>JA(eE(e)),e.nonoptional=n=>iW(e,n),e.array=()=>Ce(e),e.or=n=>KY([e,n]),e.and=n=>GY(e,n),e.transform=n=>tE(e,WY(n)),e.default=n=>tW(e,n),e.prefault=n=>rW(e,n),e.catch=n=>sW(e,n),e.pipe=n=>tE(e,n),e.readonly=()=>cW(e),e.describe=n=>{const r=e.clone();return gd.add(r,{description:n}),r},Object.defineProperty(e,"description",{get(){return gd.get(e)?.description},configurable:!0}),e.meta=(...n)=>{if(n.length===0)return gd.get(e);const r=e.clone();return gd.add(r,n[0]),r},e.isOptional=()=>e.safeParse(void 0).success,e.isNullable=()=>e.safeParse(null).success,e.apply=n=>n(e),e)),ED=ue("_ZodString",(e,t)=>{m1.init(e,t),Kt.init(e,t),e._zod.processJSONSchema=(r,i,s)=>EZ(e,r,i);const n=e._zod.bag;e.format=n.format??null,e.minLength=n.minimum??null,e.maxLength=n.maximum??null,e.regex=(...r)=>e.check(hZ(...r)),e.includes=(...r)=>e.check(gZ(...r)),e.startsWith=(...r)=>e.check(vZ(...r)),e.endsWith=(...r)=>e.check(yZ(...r)),e.min=(...r)=>e.check(dm(...r)),e.max=(...r)=>e.check(ND(...r)),e.length=(...r)=>e.check(CD(...r)),e.nonempty=(...r)=>e.check(dm(1,...r)),e.lowercase=r=>e.check(pZ(r)),e.uppercase=r=>e.check(mZ(r)),e.trim=()=>e.check(xZ()),e.normalize=(...r)=>e.check(bZ(...r)),e.toLowerCase=()=>e.check(wZ()),e.toUpperCase=()=>e.check(SZ()),e.slugify=()=>e.check(jZ())}),yY=ue("ZodString",(e,t)=>{m1.init(e,t),ED.init(e,t),e.email=n=>e.check(IV(bY,n)),e.url=n=>e.check(qV(xY,n)),e.jwt=n=>e.check(rZ(RY,n)),e.emoji=n=>e.check(FV(wY,n)),e.guid=n=>e.check(VA(QA,n)),e.uuid=n=>e.check(LV(sp,n)),e.uuidv4=n=>e.check($V(sp,n)),e.uuidv6=n=>e.check(UV(sp,n)),e.uuidv7=n=>e.check(BV(sp,n)),e.nanoid=n=>e.check(KV(SY,n)),e.guid=n=>e.check(VA(QA,n)),e.cuid=n=>e.check(HV(jY,n)),e.cuid2=n=>e.check(GV(NY,n)),e.ulid=n=>e.check(VV(CY,n)),e.base64=n=>e.check(eZ(PY,n)),e.base64url=n=>e.check(tZ(zY,n)),e.xid=n=>e.check(ZV(OY,n)),e.ksuid=n=>e.check(YV(_Y,n)),e.ipv4=n=>e.check(WV(kY,n)),e.ipv6=n=>e.check(QV(AY,n)),e.cidrv4=n=>e.check(XV(EY,n)),e.cidrv6=n=>e.check(JV(TY,n)),e.e164=n=>e.check(nZ(MY,n)),e.datetime=n=>e.check(XZ(n)),e.date=n=>e.check(eY(n)),e.time=n=>e.check(nY(n)),e.duration=n=>e.check(iY(n))});function I(e){return DV(yY,e)}const Ht=ue("ZodStringFormat",(e,t)=>{$t.init(e,t),ED.init(e,t)}),bY=ue("ZodEmail",(e,t)=>{FG.init(e,t),Ht.init(e,t)}),QA=ue("ZodGUID",(e,t)=>{BG.init(e,t),Ht.init(e,t)}),sp=ue("ZodUUID",(e,t)=>{qG.init(e,t),Ht.init(e,t)}),xY=ue("ZodURL",(e,t)=>{KG.init(e,t),Ht.init(e,t)}),wY=ue("ZodEmoji",(e,t)=>{HG.init(e,t),Ht.init(e,t)}),SY=ue("ZodNanoID",(e,t)=>{GG.init(e,t),Ht.init(e,t)}),jY=ue("ZodCUID",(e,t)=>{VG.init(e,t),Ht.init(e,t)}),NY=ue("ZodCUID2",(e,t)=>{ZG.init(e,t),Ht.init(e,t)}),CY=ue("ZodULID",(e,t)=>{YG.init(e,t),Ht.init(e,t)}),OY=ue("ZodXID",(e,t)=>{WG.init(e,t),Ht.init(e,t)}),_Y=ue("ZodKSUID",(e,t)=>{QG.init(e,t),Ht.init(e,t)}),kY=ue("ZodIPv4",(e,t)=>{nV.init(e,t),Ht.init(e,t)}),AY=ue("ZodIPv6",(e,t)=>{rV.init(e,t),Ht.init(e,t)}),EY=ue("ZodCIDRv4",(e,t)=>{iV.init(e,t),Ht.init(e,t)}),TY=ue("ZodCIDRv6",(e,t)=>{aV.init(e,t),Ht.init(e,t)}),PY=ue("ZodBase64",(e,t)=>{sV.init(e,t),Ht.init(e,t)}),zY=ue("ZodBase64URL",(e,t)=>{lV.init(e,t),Ht.init(e,t)}),MY=ue("ZodE164",(e,t)=>{cV.init(e,t),Ht.init(e,t)}),RY=ue("ZodJWT",(e,t)=>{dV.init(e,t),Ht.init(e,t)}),TD=ue("ZodNumber",(e,t)=>{xD.init(e,t),Kt.init(e,t),e._zod.processJSONSchema=(r,i,s)=>TZ(e,r,i),e.gt=(r,i)=>e.check(YA(r,i)),e.gte=(r,i)=>e.check(mb(r,i)),e.min=(r,i)=>e.check(mb(r,i)),e.lt=(r,i)=>e.check(ZA(r,i)),e.lte=(r,i)=>e.check(pb(r,i)),e.max=(r,i)=>e.check(pb(r,i)),e.int=r=>e.check(XA(r)),e.safe=r=>e.check(XA(r)),e.positive=r=>e.check(YA(0,r)),e.nonnegative=r=>e.check(mb(0,r)),e.negative=r=>e.check(ZA(0,r)),e.nonpositive=r=>e.check(pb(0,r)),e.multipleOf=(r,i)=>e.check(WA(r,i)),e.step=(r,i)=>e.check(WA(r,i)),e.finite=()=>e;const n=e._zod.bag;e.minValue=Math.max(n.minimum??Number.NEGATIVE_INFINITY,n.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,e.maxValue=Math.min(n.maximum??Number.POSITIVE_INFINITY,n.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,e.isInt=(n.format??"").includes("int")||Number.isSafeInteger(n.multipleOf??.5),e.isFinite=!0,e.format=n.format??null});function Me(e){return lZ(TD,e)}const DY=ue("ZodNumberFormat",(e,t)=>{fV.init(e,t),TD.init(e,t)});function XA(e){return cZ(DY,e)}const IY=ue("ZodBoolean",(e,t)=>{hV.init(e,t),Kt.init(e,t),e._zod.processJSONSchema=(n,r,i)=>PZ(e,n,r)});function qt(e){return uZ(IY,e)}const LY=ue("ZodUnknown",(e,t)=>{pV.init(e,t),Kt.init(e,t),e._zod.processJSONSchema=(n,r,i)=>MZ()});function hm(){return dZ(LY)}const $Y=ue("ZodNever",(e,t)=>{mV.init(e,t),Kt.init(e,t),e._zod.processJSONSchema=(n,r,i)=>zZ(e,n,r)});function UY(e){return fZ($Y,e)}const BY=ue("ZodArray",(e,t)=>{gV.init(e,t),Kt.init(e,t),e._zod.processJSONSchema=(n,r,i)=>$Z(e,n,r,i),e.element=t.element,e.min=(n,r)=>e.check(dm(n,r)),e.nonempty=n=>e.check(dm(1,n)),e.max=(n,r)=>e.check(ND(n,r)),e.length=(n,r)=>e.check(CD(n,r)),e.unwrap=()=>e.element});function Ce(e,t){return NZ(BY,e,t)}const qY=ue("ZodObject",(e,t)=>{yV.init(e,t),Kt.init(e,t),e._zod.processJSONSchema=(n,r,i)=>UZ(e,n,r,i),bt(e,"shape",()=>t.shape),e.keyof=()=>zt(Object.keys(e._zod.def.shape)),e.catchall=n=>e.clone({...e._zod.def,catchall:n}),e.passthrough=()=>e.clone({...e._zod.def,catchall:hm()}),e.loose=()=>e.clone({...e._zod.def,catchall:hm()}),e.strict=()=>e.clone({...e._zod.def,catchall:UY()}),e.strip=()=>e.clone({...e._zod.def,catchall:void 0}),e.extend=n=>$7(e,n),e.safeExtend=n=>U7(e,n),e.merge=n=>B7(e,n),e.pick=n=>I7(e,n),e.omit=n=>L7(e,n),e.partial=(...n)=>q7(PD,e,n[0]),e.required=(...n)=>F7(zD,e,n[0])});function Ne(e,t){const n={type:"object",shape:e??{},...De(t)};return new qY(n)}const FY=ue("ZodUnion",(e,t)=>{bV.init(e,t),Kt.init(e,t),e._zod.processJSONSchema=(n,r,i)=>BZ(e,n,r,i),e.options=t.options});function KY(e,t){return new FY({type:"union",options:e,...De(t)})}const HY=ue("ZodIntersection",(e,t)=>{xV.init(e,t),Kt.init(e,t),e._zod.processJSONSchema=(n,r,i)=>qZ(e,n,r,i)});function GY(e,t){return new HY({type:"intersection",left:e,right:t})}const VY=ue("ZodRecord",(e,t)=>{wV.init(e,t),Kt.init(e,t),e._zod.processJSONSchema=(n,r,i)=>FZ(e,n,r,i),e.keyType=t.keyType,e.valueType=t.valueType});function rf(e,t,n){return new VY({type:"record",keyType:e,valueType:t,...De(n)})}const ww=ue("ZodEnum",(e,t)=>{SV.init(e,t),Kt.init(e,t),e._zod.processJSONSchema=(r,i,s)=>RZ(e,r,i),e.enum=t.entries,e.options=Object.values(t.entries);const n=new Set(Object.keys(t.entries));e.extract=(r,i)=>{const s={};for(const l of r)if(n.has(l))s[l]=t.entries[l];else throw new Error(`Key ${l} not found in enum`);return new ww({...t,checks:[],...De(i),entries:s})},e.exclude=(r,i)=>{const s={...t.entries};for(const l of r)if(n.has(l))delete s[l];else throw new Error(`Key ${l} not found in enum`);return new ww({...t,checks:[],...De(i),entries:s})}});function zt(e,t){const n=Array.isArray(e)?Object.fromEntries(e.map(r=>[r,r])):e;return new ww({type:"enum",entries:n,...De(t)})}const ZY=ue("ZodLiteral",(e,t)=>{jV.init(e,t),Kt.init(e,t),e._zod.processJSONSchema=(n,r,i)=>DZ(e,n,r),e.values=new Set(t.values),Object.defineProperty(e,"value",{get(){if(t.values.length>1)throw new Error("This schema contains multiple valid literal values. Use `.values` instead.");return t.values[0]}})});function Id(e,t){return new ZY({type:"literal",values:Array.isArray(e)?e:[e],...De(t)})}const YY=ue("ZodTransform",(e,t)=>{NV.init(e,t),Kt.init(e,t),e._zod.processJSONSchema=(n,r,i)=>LZ(e,n),e._zod.parse=(n,r)=>{if(r.direction==="backward")throw new iD(e.constructor.name);n.addIssue=s=>{if(typeof s=="string")n.issues.push(Dd(s,n.value,t));else{const l=s;l.fatal&&(l.continue=!1),l.code??(l.code="custom"),l.input??(l.input=n.value),l.inst??(l.inst=e),n.issues.push(Dd(l))}};const i=t.transform(n.value,n);return i instanceof Promise?i.then(s=>(n.value=s,n)):(n.value=i,n)}});function WY(e){return new YY({type:"transform",transform:e})}const PD=ue("ZodOptional",(e,t)=>{jD.init(e,t),Kt.init(e,t),e._zod.processJSONSchema=(n,r,i)=>AD(e,n,r,i),e.unwrap=()=>e._zod.def.innerType});function JA(e){return new PD({type:"optional",innerType:e})}const QY=ue("ZodExactOptional",(e,t)=>{CV.init(e,t),Kt.init(e,t),e._zod.processJSONSchema=(n,r,i)=>AD(e,n,r,i),e.unwrap=()=>e._zod.def.innerType});function XY(e){return new QY({type:"optional",innerType:e})}const JY=ue("ZodNullable",(e,t)=>{OV.init(e,t),Kt.init(e,t),e._zod.processJSONSchema=(n,r,i)=>KZ(e,n,r,i),e.unwrap=()=>e._zod.def.innerType});function eE(e){return new JY({type:"nullable",innerType:e})}const eW=ue("ZodDefault",(e,t)=>{_V.init(e,t),Kt.init(e,t),e._zod.processJSONSchema=(n,r,i)=>GZ(e,n,r,i),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function tW(e,t){return new eW({type:"default",innerType:e,get defaultValue(){return typeof t=="function"?t():lD(t)}})}const nW=ue("ZodPrefault",(e,t)=>{kV.init(e,t),Kt.init(e,t),e._zod.processJSONSchema=(n,r,i)=>VZ(e,n,r,i),e.unwrap=()=>e._zod.def.innerType});function rW(e,t){return new nW({type:"prefault",innerType:e,get defaultValue(){return typeof t=="function"?t():lD(t)}})}const zD=ue("ZodNonOptional",(e,t)=>{AV.init(e,t),Kt.init(e,t),e._zod.processJSONSchema=(n,r,i)=>HZ(e,n,r,i),e.unwrap=()=>e._zod.def.innerType});function iW(e,t){return new zD({type:"nonoptional",innerType:e,...De(t)})}const aW=ue("ZodCatch",(e,t)=>{EV.init(e,t),Kt.init(e,t),e._zod.processJSONSchema=(n,r,i)=>ZZ(e,n,r,i),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function sW(e,t){return new aW({type:"catch",innerType:e,catchValue:typeof t=="function"?t:()=>t})}const oW=ue("ZodPipe",(e,t)=>{TV.init(e,t),Kt.init(e,t),e._zod.processJSONSchema=(n,r,i)=>YZ(e,n,r,i),e.in=t.in,e.out=t.out});function tE(e,t){return new oW({type:"pipe",in:e,out:t})}const lW=ue("ZodReadonly",(e,t)=>{PV.init(e,t),Kt.init(e,t),e._zod.processJSONSchema=(n,r,i)=>WZ(e,n,r,i),e.unwrap=()=>e._zod.def.innerType});function cW(e){return new lW({type:"readonly",innerType:e})}const uW=ue("ZodCustom",(e,t)=>{zV.init(e,t),Kt.init(e,t),e._zod.processJSONSchema=(n,r,i)=>IZ(e,n)});function dW(e,t={}){return CZ(uW,e,t)}function fW(e){return OZ(e)}Ne({maxConcurrency:Me().int().positive(),maxRequestsPerMinute:Me().int().positive(),maxRequestsPerDay:Me().int().positive()});const Hc=I().min(1);I().min(1);const g1=Ne({label:I().min(1),city:I().min(1),region:I().min(1),country:I().length(2),timezone:I().optional()}),MD=zt(["citation.lost","citation.gained","run.completed","run.failed"]);Ne({id:I(),projectId:I(),channel:Id("webhook"),url:I().url(),urlDisplay:I(),urlHost:I(),events:Ce(MD),enabled:qt().default(!0),webhookSecret:I().optional(),createdAt:I(),updatedAt:I()});const RD=zt(["cli","api","config-file"]);function hW(e){const t=new Set,n=new Set;for(const r of e){if(t.has(r.label)){n.add(r.label);continue}t.add(r.label)}return[...n]}function pW(e,t){return t?e.some(n=>n.label===t):!0}Ne({displayName:I().min(1),canonicalDomain:I().min(1),ownedDomains:Ce(I().min(1)).optional(),country:I().length(2),language:I().min(2),tags:Ce(I()).optional(),labels:rf(I(),I()).optional(),providers:Ce(Hc).optional(),locations:Ce(g1).optional(),defaultLocation:I().nullable().optional(),configSource:RD.optional()});Ne({id:I(),name:I(),displayName:I().optional(),canonicalDomain:I(),ownedDomains:Ce(I()).default([]),country:I().length(2),language:I().min(2),tags:Ce(I()).default([]),labels:rf(I(),I()).default({}),locations:Ce(g1).default([]),defaultLocation:I().nullable().optional(),configSource:RD.default("cli"),configRevision:Me().int().positive().default(1),createdAt:I().optional(),updatedAt:I().optional()});function Sw(e){let t=e.trim().toLowerCase();try{t.includes("://")&&(t=new URL(t).hostname.toLowerCase())}catch{}return t.replace(/^www\./,"")}function mW(e){const t=[e.canonicalDomain,...e.ownedDomains??[]],n=new Set,r=[];for(const i of t){const s=i.trim();if(!s)continue;const l=Sw(s);n.has(l)||(n.add(l),r.push(s))}return r}const gW=Ne({name:I().min(1).max(63).regex(/^[a-z0-9]([a-z0-9-]*[a-z0-9])?$/,{message:"Name must be a lowercase slug (letters, numbers, hyphens)"}),labels:rf(I(),I()).optional().default({})}),vW=Ne({preset:I().optional(),cron:I().optional(),timezone:I().optional().default("UTC"),providers:Ce(Hc).optional().default([])}).refine(e=>e.preset&&!e.cron||!e.preset&&e.cron,{message:'Exactly one of "preset" or "cron" must be provided'}).optional(),yW=Ne({channel:Id("webhook"),url:I().url(),events:Ce(MD).min(1)}),bW=Ne({gsc:Ne({propertyUrl:I()}).optional(),syncSchedule:Ne({preset:I().optional(),cron:I().optional()}).optional()}).optional(),xW=Ne({displayName:I().min(1),canonicalDomain:I().min(1),ownedDomains:Ce(I().min(1)).optional().default([]),country:I().length(2),language:I().min(2),keywords:Ce(I().min(1)).optional().default([]),competitors:Ce(I().min(1)).optional().default([]),providers:Ce(Hc).optional().default([]),locations:Ce(g1).optional().default([]),defaultLocation:I().optional(),schedule:vW,notifications:Ce(yW).optional().default([]),google:bW}).superRefine((e,t)=>{const n=hW(e.locations);n.length>0&&t.addIssue({code:"custom",message:`Duplicate location labels are not allowed: ${n.join(", ")}`,path:["locations"]}),pW(e.locations,e.defaultLocation)||t.addIssue({code:"custom",message:`defaultLocation "${e.defaultLocation}" must match a configured location label`,path:["defaultLocation"]})});Ne({apiVersion:Id("canonry/v1"),kind:Id("Project"),metadata:gW,spec:xW});const wW=zt(["gsc","ga4"]);Ne({id:I(),domain:I(),connectionType:wW,propertyId:I().nullable().optional(),sitemapUrl:I().nullable().optional(),scopes:Ce(I()).default([]),createdAt:I(),updatedAt:I()});Ne({date:I(),query:I(),page:I(),country:I().nullable().optional(),device:I().nullable().optional(),clicks:Me(),impressions:Me(),ctr:Me(),position:Me()});const jw=Ne({id:I(),url:I(),indexingState:I().nullable().optional(),verdict:I().nullable().optional(),coverageState:I().nullable().optional(),pageFetchState:I().nullable().optional(),robotsTxtState:I().nullable().optional(),crawlTime:I().nullable().optional(),lastCrawlResult:I().nullable().optional(),isMobileFriendly:qt().nullable().optional(),richResults:Ce(I()).default([]),inspectedAt:I()});zt(["stable","reindexed","deindexed","still-missing","new"]);const SW=Ne({url:I(),previousState:I().nullable(),currentState:I().nullable(),transitionDate:I()}),jW=Ne({reason:I(),count:Me(),urls:Ce(jw).default([])});Ne({summary:Ne({total:Me(),indexed:Me(),notIndexed:Me(),deindexed:Me(),percentage:Me()}),lastInspectedAt:I().nullable(),indexed:Ce(jw).default([]),notIndexed:Ce(jw).default([]),deindexed:Ce(SW).default([]),reasonGroups:Ce(jW).default([])});Ne({url:I(),type:zt(["URL_UPDATED","URL_DELETED"]),notifiedAt:I()});Ne({url:I(),type:zt(["URL_UPDATED","URL_DELETED"]),notifiedAt:I(),status:zt(["success","error"]),error:I().optional()});Ne({date:I(),indexed:Me(),notIndexed:Me(),reasonBreakdown:rf(I(),Me()).default({})});Ne({id:I(),domain:I(),siteUrl:I().nullable().optional(),createdAt:I(),updatedAt:I()});const gb=Ne({id:I(),url:I(),httpCode:Me().nullable().optional(),inIndex:qt().nullable().optional(),lastCrawledDate:I().nullable().optional(),inIndexDate:I().nullable().optional(),inspectedAt:I(),documentSize:Me().nullable().optional(),anchorCount:Me().nullable().optional(),discoveryDate:I().nullable().optional()});Ne({summary:Ne({total:Me(),indexed:Me(),notIndexed:Me(),unknown:Me().optional(),percentage:Me()}),lastInspectedAt:I().nullable(),indexed:Ce(gb).default([]),notIndexed:Ce(gb).default([]),unknown:Ce(gb).default([]).optional()});Ne({query:I(),impressions:Me(),clicks:Me(),ctr:Me(),averagePosition:Me()});Ne({url:I(),status:zt(["success","error"]),submittedAt:I(),error:I().optional()});const Gc=zt(["live","staging"]);Ne({projectName:I(),url:I(),stagingUrl:I().optional(),username:I(),defaultEnv:Gc,createdAt:I(),updatedAt:I()});const nE=Ne({url:I(),reachable:qt(),pageCount:Me().nullable().optional(),version:I().nullable().optional(),error:I().nullable().optional(),plugins:Ce(I()).optional(),authenticatedUser:Ne({id:Me(),slug:I()}).nullable().optional()});Ne({connected:qt(),projectName:I(),defaultEnv:Gc,live:nE.nullable(),staging:nE.nullable(),adminUrl:I().nullable().optional()});const NW=Ne({id:Me(),slug:I(),title:I(),status:I(),modifiedAt:I().nullable().optional(),link:I().nullable().optional()}),DD=Ne({title:I().nullable(),description:I().nullable(),noindex:qt().nullable(),writable:qt().default(!1),writeTargets:Ce(I()).default([])}),CW=Ne({type:I(),json:rf(I(),hm())}),OW=NW.extend({env:Gc,content:I(),seo:DD,schemaBlocks:Ce(CW).default([])}),rE=OW.extend({contentHash:I(),contentSnippet:I()}),ID=Ne({manualRequired:Id(!0),targetUrl:I(),adminUrl:I().nullable().optional(),content:I(),nextSteps:Ce(I()).default([])}),_W=Ne({slug:I(),severity:zt(["high","medium","low"]),code:zt(["noindex","missing-seo-title","missing-meta-description","missing-schema","thin-content"]),message:I()});Ne({slug:I(),title:I(),status:I(),wordCount:Me(),seo:DD,schemaPresent:qt(),issues:Ce(_W).default([])});const kW=Ne({slug:I(),status:zt(["applied","skipped","manual"]),error:I().optional(),manualAssist:ID.optional()});Ne({env:Gc,strategy:zt(["plugin","manual"]),results:Ce(kW)});const AW=Ne({slug:I(),status:zt(["deployed","stripped","skipped","failed"]),schemasInjected:Ce(I()).optional(),manualAssist:ID.optional(),error:I().optional()});Ne({env:Gc,results:Ce(AW)});const EW=Ne({slug:I(),title:I(),canonrySchemas:Ce(I()),thirdPartySchemas:Ce(I()),hasCanonrySchema:qt()});Ne({env:Gc,pages:Ce(EW)});const TW=Ne({name:I(),status:zt(["completed","skipped","failed"]),summary:I().optional(),error:I().optional()});Ne({projectName:I(),steps:Ce(TW)});Ne({slug:I(),live:rE,staging:rE,hasDifferences:qt(),differences:Ne({title:qt(),slug:qt(),content:qt(),seoTitle:qt(),seoDescription:qt(),noindex:qt(),schema:qt()})});const PW=zt(["queued","running","completed","partial","failed","cancelled"]),zW=zt(["answer-visibility","site-audit","gsc-sync","inspect-sitemap"]),MW=zt(["manual","scheduled","config-apply"]),RW=zt(["cited","not-cited"]),DW=zt(["visible","not-visible"]),IW=zt(["new","cited","lost","emerging","not-cited"]);Ne({id:I(),projectId:I(),kind:zW,status:PW,trigger:MW.default("manual"),location:I().nullable().optional(),startedAt:I().nullable().optional(),finishedAt:I().nullable().optional(),error:I().nullable().optional(),createdAt:I()});const LD=Ne({uri:I(),title:I()});Ne({id:I(),runId:I(),keywordId:I(),keyword:I().optional(),provider:Hc,citationState:RW,answerMentioned:qt().optional(),visibilityState:DW.optional(),transition:IW.optional(),answerText:I().nullable().optional(),citedDomains:Ce(I()).default([]),competitorOverlap:Ce(I()).default([]),recommendedCompetitors:Ce(I()).default([]),matchedTerms:Ce(I()).default([]),groundingSources:Ce(LD).default([]),searchQueries:Ce(I()).default([]),model:I().nullable().optional(),location:I().nullable().optional(),createdAt:I()});Ne({id:I(),projectId:I().nullable().optional(),actor:I(),action:I(),entityType:I(),entityId:I().nullable().optional(),diff:hm().optional(),createdAt:I()});const LW=zt(["yes","no","unknown","not-mentioned"]);Ne({companyName:I().min(1),domain:I().min(1),phrases:Ce(I().min(1)).optional().default([]),competitors:Ce(I().min(1)).optional().default([])});const $W=Ne({name:I(),count:Me().int().nonnegative()}),UW=Ne({id:I(),name:I(),weight:Me(),score:Me(),grade:I(),status:zt(["pass","partial","fail"]),findings:Ce(Ne({type:I(),message:I()})).default([]),recommendations:Ce(I()).default([])}),BW=Ne({url:I(),finalUrl:I(),auditedAt:I(),overallScore:Me(),overallGrade:I(),summary:I(),factors:Ce(UW).default([])}),qW=Ne({industry:I(),summary:I(),services:Ce(I()).default([]),categoryTerms:Ce(I()).default([])}),FW=Ne({provider:I(),displayName:I(),model:I().nullable().optional(),mentioned:qt(),cited:qt(),describedAccurately:LW,accuracyNotes:I().nullable().optional(),incorrectClaims:Ce(I()).default([]),recommendedCompetitors:Ce(I()).default([]),citedDomains:Ce(I()).default([]),groundingSources:Ce(LD).default([]),searchQueries:Ce(I()).default([]),answerText:I(),error:I().nullable().optional()}),KW=Ne({phrase:I(),providerResults:Ce(FW).default([])}),HW=Ne({totalQueries:Me().int().nonnegative(),totalProviders:Me().int().nonnegative(),totalComparisons:Me().int().nonnegative(),mentionCount:Me().int().nonnegative(),citationCount:Me().int().nonnegative(),topCompetitors:Ce($W).default([]),visibilityGap:I(),whatThisMeans:Ce(I()).default([]),recommendedActions:Ce(I()).default([])});Ne({companyName:I(),domain:I(),homepageUrl:I(),generatedAt:I(),phrases:Ce(I()).default([]),competitors:Ce(I()).default([]),profile:qW,audit:BW,queryResults:Ce(KW).default([]),summary:HW});Ne({id:I(),projectId:I(),cronExpr:I(),preset:I().nullable().optional(),timezone:I().default("UTC"),enabled:qt().default(!0),providers:Ce(Hc).default([]),lastRunAt:I().nullable().optional(),nextRunAt:I().nullable().optional(),createdAt:I(),updatedAt:I()});Ne({preset:I().optional(),cron:I().optional(),timezone:I().optional().default("UTC"),enabled:qt().optional().default(!0),providers:Ce(Hc).optional().default([])}).refine(e=>e.preset&&!e.cron||!e.preset&&e.cron,{message:'Exactly one of "preset" or "cron" must be provided'});Ne({id:I(),projectId:I(),propertyId:I(),clientEmail:I(),connected:qt(),createdAt:I(),updatedAt:I()});Ne({date:I(),landingPage:I(),sessions:Me(),organicSessions:Me(),users:Me()});const $D=zt(["session","first_user","manual_utm"]),GW=Ne({source:I(),medium:I(),sessions:Me(),users:Me(),sourceDimension:$D});Ne({totalSessions:Me(),totalOrganicSessions:Me(),totalUsers:Me(),topPages:Ce(Ne({landingPage:I(),sessions:Me(),organicSessions:Me(),users:Me()})),aiReferrals:Ce(GW),aiSessionsDeduped:Me(),aiUsersDeduped:Me(),lastSyncedAt:I().nullable()});Ne({date:I(),source:I(),medium:I(),sessions:Me(),users:Me(),sourceDimension:$D});Ne({date:I(),sessions:Me(),organicSessions:Me(),users:Me()});function iE(e){return e.toLowerCase().replace(/[^a-z0-9]/g,"")}function Kn({text:e}){const[t,n]=x.useState(null),r=x.useRef(null),i=x.useCallback(()=>{if(!r.current)return;const l=r.current.getBoundingClientRect();n({top:l.top,left:l.left+l.width/2})},[]),s=x.useCallback(()=>n(null),[]);return u.jsxs("span",{className:"info-tooltip-wrapper",onMouseEnter:i,onMouseLeave:s,onFocus:i,onBlur:s,children:[u.jsxs("svg",{ref:r,className:"info-tooltip-icon",viewBox:"0 0 16 16",fill:"none","aria-hidden":"true",children:[u.jsx("circle",{cx:"8",cy:"8",r:"7",stroke:"currentColor",strokeWidth:"1.5"}),u.jsx("path",{d:"M8 7v4M8 5.5v0",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round"})]}),t!==null&&nl.createPortal(u.jsx("span",{role:"tooltip",style:{position:"fixed",top:t.top,left:t.left,transform:"translateX(-50%) translateY(calc(-100% - 8px))",zIndex:9999,pointerEvents:"none",width:"14rem",padding:"0.5rem 0.75rem",fontSize:"11px",fontWeight:400,textTransform:"none",letterSpacing:"normal",lineHeight:"1rem",color:"#d4d4d8",backgroundColor:"#18181b",border:"1px solid rgba(63, 63, 70, 0.6)",borderRadius:"0.5rem",boxShadow:"0 10px 15px -3px rgba(0,0,0,.1), 0 4px 6px -4px rgba(0,0,0,.1)"},children:e}),document.body)]})}function aE(e,t){const n=VW(t),r=e.split(/(\*\*[^*]+\*\*)/).filter(Boolean).map(h=>h.startsWith("**")&&h.endsWith("**")?{type:"bold",value:h.slice(2,-2)}:{type:"text",value:h}),i=n.flatMap(h=>h.terms).filter(h=>h.trim().length>1);if(i.length===0)return r.map((h,p)=>h.type==="bold"?gi.createElement("strong",{key:`b-${p}`,className:"text-zinc-200 font-semibold"},h.value):h.value).filter(Boolean);const l=[...i].sort((h,p)=>p.length-h.length).map(h=>h.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")),c=new RegExp(`(${l.join("|")})`,"gi"),f=new Map;for(const h of n)for(const p of h.terms){const g=p.toLowerCase();f.has(g)||f.set(g,h.className)}return r.flatMap((h,p)=>h.value.split(c).map((v,y)=>{if(!v)return null;if(y%2===1){const w=f.get(v.toLowerCase())??"answer-highlight";return h.type==="bold"?gi.createElement("mark",{key:`hl-${p}-${y}`,className:w},gi.createElement("strong",{className:"text-zinc-200 font-semibold"},v)):gi.createElement("mark",{key:`hl-${p}-${y}`,className:w},v)}return h.type==="bold"?gi.createElement("strong",{key:`b-${p}-${y}`,className:"text-zinc-200 font-semibold"},v):v})).filter(Boolean)}function VW(e){return e.length===0?[]:typeof e[0]=="string"?[{terms:e,className:"answer-highlight"}]:e}function vb(e,t){switch(e){case"new":return"First observation";case"emerging":return"First visibility";case"lost":return"Lost since last run";default:return t==="visible"?"Visible in latest run":t==="pending"?"Awaiting first run":"Not visible in latest run"}}function ZW({evidence:e,project:t,onClose:n}){const[r,i]=x.useState(!1),[s,l]=x.useState("mentions"),[c,f]=x.useState(-1),[h,p]=x.useState(null),[g,v]=x.useState(!1),[y,S]=x.useState({}),w=mW(t.project),N=new Set(w.map(Sw)),C=e.runHistory,A=C.length>1,[k,O]=x.useState(null),T=x.useRef(!1);x.useEffect(()=>{if(T.current||e.answerSnippet&&(e.visibilityState!=null||e.answerMentioned!=null))return;const W=C.at(-1);W&&(T.current=!0,Ac(W.runId).then(X=>{const Q=X.snapshots.find(de=>de.keyword===e.keyword&&de.provider===e.provider);Q&&O({citationState:Q.citationState,answerMentioned:Q.answerMentioned,visibilityState:Q.visibilityState,visibilityTransition:W.visibilityTransition,provider:Q.provider,model:Q.model??e.model,answerSnippet:Q.answerText??e.answerSnippet,citedDomains:Q.citedDomains??e.citedDomains,competitorDomains:Q.competitorOverlap??e.competitorDomains,recommendedCompetitors:Q.recommendedCompetitors??e.recommendedCompetitors??[],matchedTerms:Q.matchedTerms??e.matchedTerms??[],groundingSources:Q.groundingSources??e.groundingSources,evidenceUrls:[],changeLabel:e.visibilityChangeLabel??e.changeLabel,summary:e.summary})}).catch(()=>{}))},[e,C]);const P=c>=0&&h!==null,E=P?h:k||{citationState:e.citationState,answerMentioned:e.answerMentioned,visibilityState:e.visibilityState,visibilityTransition:C.at(-1)?.visibilityTransition,provider:e.provider,model:e.model,answerSnippet:e.answerSnippet,citedDomains:e.citedDomains,competitorDomains:e.competitorDomains,recommendedCompetitors:e.recommendedCompetitors??[],matchedTerms:e.matchedTerms??[],groundingSources:e.groundingSources,evidenceUrls:e.evidenceUrls,changeLabel:e.visibilityChangeLabel??e.changeLabel,summary:e.summary},z=E.visibilityState==="pending"||E.citationState==="pending",D=z?!1:E.visibilityState!=null?E.visibilityState==="visible":E.answerMentioned!=null?E.answerMentioned:E.citationState==="cited"||E.citationState==="emerging",K=E.answerMentioned!=null||E.visibilityState!=null||E.recommendedCompetitors.length>0,U=E.citedDomains.length>0||E.groundingSources.length>0||E.evidenceUrls.length>0,L=t.project.displayName||t.project.name,ae=[...w.map(Sw),L,L.split(" ").slice(0,2).join(" "),...E.matchedTerms].filter(W=>W.trim().length>2),ye=[...E.competitorDomains.flatMap(W=>{const X=W.split(".")[0];return X&&X.length>=4?[X]:[]}),...E.recommendedCompetitors].filter(W=>W.trim().length>2),me=[{terms:ae,className:"answer-highlight-brand"},...ye.length>0?[{terms:ye,className:"answer-highlight-competitor"}]:[]],G=z?"pending":E.visibilityTransition==="lost"?"lost":D?"cited":"not-cited",re=x.useRef(0),ge=x.useCallback(async W=>{const X=++re.current;if(W===-1||W===C.length-1){f(-1),p(null),i(!1);return}f(W),i(!1);const Q=C[W],de=`${Q.runId}::${e.keyword}::${e.provider}`;if(y[de]){p(y[de]);return}v(!0);try{const ve=await Ac(Q.runId);if(X!==re.current)return;const Z=ve.snapshots.find(Se=>Se.keyword===e.keyword&&Se.provider===e.provider)??ve.snapshots.find(Se=>Se.keyword===e.keyword),le=Z?{citationState:Z.citationState,answerMentioned:Z.answerMentioned,visibilityState:Z.visibilityState,visibilityTransition:Q.visibilityTransition,provider:Z.provider,model:Z.model??null,answerSnippet:Z.answerText??"",citedDomains:Z.citedDomains,competitorDomains:Z.competitorOverlap,recommendedCompetitors:Z.recommendedCompetitors??[],matchedTerms:Z.matchedTerms??[],groundingSources:Z.groundingSources,evidenceUrls:[],changeLabel:vb(Q.visibilityTransition,Q.visibilityState),summary:""}:{citationState:Q.citationState,answerMentioned:Q.answerMentioned,visibilityState:Q.visibilityState,visibilityTransition:Q.visibilityTransition,provider:e.provider,model:Q.model??null,answerSnippet:"",citedDomains:[],competitorDomains:[],recommendedCompetitors:[],matchedTerms:[],groundingSources:[],evidenceUrls:[],changeLabel:vb(Q.visibilityTransition,Q.visibilityState),summary:"Snapshot data not available for this run."};S(Se=>({...Se,[de]:le})),p(le)}catch{if(X!==re.current)return;p({citationState:Q.citationState,answerMentioned:Q.answerMentioned,visibilityState:Q.visibilityState,visibilityTransition:Q.visibilityTransition,provider:e.provider,model:Q.model??null,answerSnippet:"",citedDomains:[],competitorDomains:[],recommendedCompetitors:[],matchedTerms:[],groundingSources:[],evidenceUrls:[],changeLabel:vb(Q.visibilityTransition,Q.visibilityState),summary:"Failed to load historical run data."})}finally{X===re.current&&v(!1)}},[C,e.keyword,e.provider,y]),B=(P||e.historyScope!=="provider")&&E.model?`${E.provider} (${E.model}) · ${E.changeLabel.toLowerCase()}`:`${E.provider} · ${E.changeLabel.toLowerCase()}`,R=!P&&e.historyScope==="provider"?[e.model?`Current model: ${e.model}`:null,e.modelsSeen&&e.modelsSeen.length>1?`History spans ${e.modelsSeen.length} models`:null].filter(Boolean).join(" · "):"",H=D?{label:"Visible in answer",title:"Your brand or domain is mentioned in this answer",meta:B}:E.visibilityTransition==="lost"?{label:"Visibility lost",title:"Your brand no longer appears in this answer",meta:B}:z?{label:"Pending",title:"Awaiting first visibility run",meta:"No provider data yet"}:{label:"Not visible in answer",title:"Your brand or domain was not mentioned in this answer",meta:B},oe=()=>{if(!E.answerSnippet)return null;const W=E.answerSnippet.split(`
95
- `),X=[];let Q=[],de=0;const ve=()=>{if(Q.length===0)return;const Z=Q.join(" ").trim();Z&&X.push(u.jsx("p",{className:X.length>0?"mt-2.5":"",children:aE(Z,me)},de++)),Q=[]};for(const Z of W){const le=Z.trim();if(/^[-\u2013\u2014]{3,}$/.test(le)){ve(),X.push(u.jsx("hr",{className:"border-zinc-800/60 my-3"},de++));continue}const Se=le.match(/^(#{1,3})\s+(.+)$/);if(Se){ve();const q=Se[1].length,Ae=Se[2].replace(/^[\p{Emoji}\p{Emoji_Component}\s#]+/u,"").trim()||Se[2],Oe=q===1?"text-[13px] font-semibold text-zinc-100 mt-4 mb-1":q===2?"text-xs font-semibold text-zinc-200 mt-3 mb-0.5":"text-xs font-medium text-zinc-300 mt-2";X.push(u.jsx("p",{className:Oe,children:aE(Ae,me)},de++));continue}if(le===""){ve();continue}Q.push(le)}return ve(),X};return u.jsx(WR,{open:!0,onOpenChange:W=>{W||n()},children:u.jsxs(QR,{children:[u.jsx(s1,{className:"fixed inset-0 z-50 bg-black/80 backdrop-blur-sm"}),u.jsxs(o1,{className:"evidence-modal","aria-describedby":void 0,children:[u.jsxs("div",{className:"evidence-modal-header",children:[u.jsxs("div",{className:"min-w-0 flex-1",children:[u.jsxs("p",{className:"eyebrow eyebrow-soft",children:[t.project.name," ","·"," ",E.provider||"All providers"]}),u.jsx(l1,{className:"text-lg font-semibold text-zinc-50 truncate",children:e.keyword})]}),u.jsxs(JR,{className:"inline-flex size-8 items-center justify-center rounded-md text-zinc-500 transition hover:bg-zinc-800 hover:text-zinc-100 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-zinc-400 shrink-0",children:[u.jsx(Sg,{className:"size-4"}),u.jsx("span",{className:"sr-only",children:"Close"})]})]}),A&&u.jsxs("div",{className:"evidence-modal-timeline",children:[u.jsx("p",{className:"drawer-section-label mb-1.5",children:"Run history"}),u.jsx("div",{className:"flex items-center gap-1 overflow-x-auto pb-1",children:C.map((W,X)=>{const Q=c===-1&&X===C.length-1||c===X,de=W.visibilityState??(W.answerMentioned?"visible":"not-visible"),ve=W.visibilityTransition??de,Z=de==="visible"?"bg-emerald-400":ve==="emerging"?"bg-amber-400":ve==="lost"?"bg-rose-400":"bg-zinc-600",Se=new Date(W.createdAt).toLocaleDateString(void 0,{month:"short",day:"numeric"}),q=!!(W.model&&X>0&&C[X-1]?.model&&C[X-1].model!==W.model);return u.jsxs("button",{type:"button",className:`evidence-run-dot ${Q?"evidence-run-dot--selected":""}`,onClick:()=>ge(X===C.length-1?-1:X),"aria-label":[`Run ${Se}: ${de}`,W.model?`model ${W.model}`:null,q?"model changed":null].filter(Boolean).join(" — "),"aria-pressed":Q,children:[u.jsx("span",{className:`size-2 rounded-full ${Z} ${q?"ring-1 ring-amber-300/80 ring-offset-2 ring-offset-zinc-950":""}`,"aria-hidden":"true"}),u.jsx("span",{className:"text-[10px] text-zinc-500",children:Se})]},X)})}),c>=0&&c<C.length&&u.jsxs("p",{className:"text-[11px] text-zinc-500 mt-1",children:["Viewing run from ",new Date(C[c].createdAt).toLocaleString()," ","—"," ",u.jsx("span",{className:"capitalize",children:C[c].visibilityState??(C[c].answerMentioned?"visible":"not-visible")}),u.jsxs("button",{type:"button",className:"text-zinc-400 hover:text-zinc-200 ml-2",onClick:()=>ge(-1),children:["←"," Back to latest"]})]}),!P&&(e.modelTransitions?.length??0)>0&&u.jsx("div",{className:"mt-2 flex flex-wrap gap-2",children:e.modelTransitions.map(W=>u.jsx("span",{className:"inline-flex items-center rounded-full border border-amber-400/30 bg-amber-400/10 px-2 py-1 text-[10px] text-amber-100",children:`${W.fromModel??"unknown"} -> ${W.toModel??"unknown"} on ${new Date(W.createdAt).toLocaleDateString()}`},`${W.runId}:${W.toModel??"unknown"}`))})]}),u.jsxs("div",{className:"evidence-modal-body",children:[g&&u.jsxs("div",{className:"md:col-span-2 flex items-center justify-center py-12 text-zinc-500 text-sm",children:["Loading historical run data","…"]}),!g&&u.jsxs(u.Fragment,{children:[u.jsxs("div",{className:"evidence-modal-main",children:[u.jsxs("div",{className:`evidence-position-hero evidence-position-hero--${G}`,children:[u.jsx("p",{className:`evidence-position-label evidence-position-label--${G}`,children:H.label}),u.jsx("p",{className:`evidence-position-title evidence-position-title--${G}`,children:H.title}),u.jsx("p",{className:"evidence-position-meta",children:H.meta}),R&&u.jsx("p",{className:"mt-1 text-[11px] text-zinc-500",children:R})]}),E.answerSnippet&&u.jsxs("div",{children:[u.jsx("p",{className:"drawer-section-label",children:"What the AI said"}),u.jsx("div",{className:`answer-snippet-block ${r?"evidence-answer-expanded":"evidence-answer-collapsed"}`,children:oe()}),E.answerSnippet.length>280&&u.jsx("button",{type:"button",className:"mt-1.5 text-xs text-zinc-500 hover:text-zinc-300 transition-colors",onClick:()=>i(!r),children:r?"↑ Collapse":"↓ Show full answer"})]}),!E.answerSnippet&&!g&&u.jsx("div",{className:"rounded-lg border border-zinc-800/40 bg-zinc-900/20 px-4 py-8 text-center text-zinc-600 text-sm",children:"No answer text recorded for this run"}),!P&&e.relatedTechnicalSignals.length>0&&u.jsxs("div",{children:[u.jsx("p",{className:"drawer-section-label",children:D?"Why you're visible":"What to fix"}),u.jsx("div",{className:"action-items-list",children:e.relatedTechnicalSignals.map((W,X)=>u.jsxs("div",{className:"action-item",children:[u.jsx("svg",{className:`action-item-icon ${D?"text-emerald-400":"text-amber-400"}`,viewBox:"0 0 16 16",fill:"none","aria-hidden":"true",children:D?u.jsx("path",{d:"M3 8l3.5 3.5L13 4.5",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"}):u.jsxs(u.Fragment,{children:[u.jsx("circle",{cx:"8",cy:"8",r:"7",stroke:"currentColor",strokeWidth:"1.5"}),u.jsx("path",{d:"M8 5v3.5M8 10.5v0",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round"})]})}),u.jsx("span",{className:"action-item-text",children:W})]},X))})]}),E.summary&&u.jsx("p",{className:"text-xs text-zinc-600 border-t border-zinc-800/40 pt-3 mt-1",children:E.summary})]}),u.jsxs("div",{className:"evidence-modal-sidebar",children:[(K||U)&&u.jsxs("div",{className:"sidebar-tabs",children:[u.jsx("button",{className:`sidebar-tab ${s==="mentions"?"sidebar-tab--active":""}`,onClick:()=>l("mentions"),type:"button",title:"Canonry's answer-level visibility assessment and any company names extracted from the answer text.",children:"Mentions"}),u.jsx("button",{className:`sidebar-tab ${s==="sources"?"sidebar-tab--active":""}`,onClick:()=>l("sources"),type:"button",title:"Grounding links the model used to build the answer. These are supporting sources, not the primary visibility signal.",children:"Sources"})]}),s==="mentions"&&u.jsxs(u.Fragment,{children:[u.jsxs("div",{children:[u.jsxs("div",{className:"drawer-section-label flex items-center",children:[u.jsx("span",{children:"Answer visibility"}),u.jsx(Kn,{text:"Canonry scans the AI answer for your owned domains and project name. This is independent from grounding or citation sources."})]}),u.jsxs("div",{className:`mention-status mention-status--${D?"visible":"not-visible"}`,children:[u.jsx("span",{className:"mention-status-icon",children:z?"…":D?"✓":"—"}),u.jsx("span",{className:"mention-status-label",children:z?"Pending":D?"Visible":"Not visible"})]}),E.matchedTerms.length>0&&u.jsxs("div",{className:"mt-2",children:[u.jsx("p",{className:"text-[10px] uppercase tracking-wide text-zinc-500 mb-1.5",children:"Matched in answer"}),u.jsx("div",{className:"flex flex-wrap gap-1.5",children:E.matchedTerms.map(W=>u.jsx("span",{className:"mention-chip mention-chip--brand",children:W},W))})]}),!z&&!D&&E.matchedTerms.length===0&&u.jsxs("div",{className:"mt-2",children:[u.jsx("p",{className:"text-[10px] uppercase tracking-wide text-zinc-500 mb-1.5",children:"Searched for"}),u.jsx("div",{className:"flex flex-wrap gap-1.5",children:ae.map(W=>u.jsx("span",{className:"mention-chip mention-chip--muted",children:W},W))}),u.jsx("p",{className:"text-[11px] text-zinc-600 mt-1.5",children:"None of these appear in the answer text."})]})]}),(E.recommendedCompetitors.length>0||E.competitorDomains.length>0)&&u.jsxs("div",{children:[u.jsxs("div",{className:"drawer-section-label flex items-center",children:[u.jsx("span",{children:"Competitors in answer"}),u.jsx(Kn,{text:"Competitors detected in the answer text or cited source links. Includes both tracked competitors and names extracted by Canonry."})]}),u.jsx("div",{className:"flex flex-wrap gap-1.5",children:(()=>{const W=E.competitorDomains.map(de=>de.replace(/^www\./,"")),X=new Set(W.map(de=>iE(de.replace(/\.[^.]+$/,""))));return[...E.recommendedCompetitors.filter(de=>!X.has(iE(de))),...W].map(de=>u.jsx("span",{className:"mention-chip mention-chip--competitor",children:de},de))})()})]})]}),s==="sources"&&u.jsxs(u.Fragment,{children:[E.citedDomains.length>0&&u.jsxs("div",{children:[u.jsxs("div",{className:"drawer-section-label flex items-center",children:[u.jsx("span",{children:"Domains from source links"}),u.jsx(Kn,{text:"These domains were extracted from grounding or citation URLs. They are supporting-source metadata, not proof that the answer text mentioned them."})]}),u.jsx("div",{className:"citation-leaderboard",children:E.citedDomains.map((W,X)=>{const Q=W.toLowerCase().replace(/^www\./,""),de=N.has(Q),ve=!de&&E.competitorDomains.some(le=>le.toLowerCase().replace(/^www\./,"")===Q),Z=de?"you":ve?"competitor":"other";return u.jsxs("div",{className:`citation-leaderboard-item citation-leaderboard-item--${Z}`,children:[u.jsxs("span",{className:"citation-leaderboard-rank",children:["#",X+1]}),u.jsx("span",{className:"citation-leaderboard-domain",children:W}),de&&u.jsx("span",{className:"citation-leaderboard-tag",children:"You"}),ve&&u.jsx("span",{className:"citation-leaderboard-tag",children:"Competitor"})]},W)})})]}),E.groundingSources.length>0&&u.jsxs("div",{children:[u.jsxs("div",{className:"drawer-section-label flex items-center",children:[u.jsxs("span",{children:["Grounding source links (",E.groundingSources.length,")"]}),u.jsx(Kn,{text:"Links the model used as grounding or supporting context while producing the answer. These are not the same thing as answer visibility."})]}),u.jsx("ul",{className:"grid gap-0.5",children:E.groundingSources.map((W,X)=>u.jsx("li",{className:"truncate text-sm",children:u.jsx("a",{href:W.uri,target:"_blank",rel:"noreferrer",className:"text-zinc-400 hover:text-zinc-200 transition-colors",children:W.title||W.uri})},X))})]}),E.evidenceUrls.length>0&&u.jsxs("div",{children:[u.jsx("p",{className:"drawer-section-label",children:"Evidence URLs"}),u.jsx("ul",{className:"grid gap-1",children:E.evidenceUrls.map(W=>u.jsx("li",{className:"truncate text-sm",children:u.jsx("a",{href:W,target:"_blank",rel:"noreferrer",className:"text-zinc-400 hover:text-zinc-200 transition-colors",children:W})},W))})]}),E.citedDomains.length===0&&E.groundingSources.length===0&&E.evidenceUrls.length===0&&u.jsxs("div",{className:"flex items-center justify-center h-24 text-zinc-600 text-sm",children:["No source data ",P?"for this run":"yet"]})]}),!K&&!U&&u.jsxs("div",{className:"flex items-center justify-center h-24 text-zinc-600 text-sm",children:["No answer visibility data ",P?"for this run":"yet"]})]})]})]})]})]})})}function pi(e){const t=new Date("2026-02-20");return e.map((n,r)=>({runId:`run_mock_${r+1}`,citationState:n,createdAt:new Date(t.getTime()+r*2*24*60*60*1e3).toISOString()}))}const yb=[{id:"project_citypoint",name:"Citypoint Dental NYC",canonicalDomain:"citypointdental.com",ownedDomains:[],country:"US",language:"en",tags:["local intent","priority"],labels:{},locations:[],defaultLocation:null,configSource:"cli",configRevision:1},{id:"project_harbor",name:"Harbor Legal Group",canonicalDomain:"harborlegal.com",ownedDomains:[],country:"US",language:"en",tags:["lead gen"],labels:{},locations:[],defaultLocation:null,configSource:"cli",configRevision:1},{id:"project_northstar",name:"Northstar Orthopedics",canonicalDomain:"northstarortho.com",ownedDomains:[],country:"US",language:"en",tags:["multi-location"],labels:{},locations:[],defaultLocation:null,configSource:"cli",configRevision:1}];function zg(e){return{id:e.id,projectId:e.projectId,projectName:e.projectName,kind:e.kind,kindLabel:e.kindLabel,status:e.status,trigger:e.trigger??"manual",createdAt:e.createdAt,startedAt:e.startedAt,duration:e.duration,statusDetail:e.statusDetail,summary:e.summary,triggerLabel:e.triggerLabel}}const YW=zg({id:"run_citypoint_visibility_20260308",projectId:"project_citypoint",projectName:"Citypoint Dental NYC",kind:"answer-visibility",kindLabel:"Answer visibility sweep",status:"completed",createdAt:"2026-03-08T12:15:00.000Z",startedAt:"Mar 8, 12:15 PM",duration:"6m 12s",statusDetail:"18 tracked queries checked; 3 citation losses detected on emergency-intent prompts.",summary:"Citation losses on emergency-intent prompts",triggerLabel:"Scheduled"}),WW=zg({id:"run_citypoint_queued_20260309",projectId:"project_citypoint",projectName:"Citypoint Dental NYC",kind:"answer-visibility",kindLabel:"Answer visibility sweep",status:"queued",createdAt:"2026-03-09T08:05:00.000Z",startedAt:"Mar 9, 8:05 AM",duration:"Waiting for slot",statusDetail:"Ready to enqueue after the next provider rate window clears.",summary:"Queued follow-up after local ranking movement",triggerLabel:"Manual"}),QW=zg({id:"run_harbor_visibility_20260308",projectId:"project_harbor",projectName:"Harbor Legal Group",kind:"answer-visibility",kindLabel:"Answer visibility sweep",status:"completed",createdAt:"2026-03-08T11:05:00.000Z",startedAt:"Mar 8, 11:05 AM",duration:"5m 07s",statusDetail:"12 tracked queries checked; local-intent visibility held steady across branded prompts.",summary:"Branded prompts remain stable",triggerLabel:"Scheduled"}),XW=zg({id:"run_northstar_visibility_20260308",projectId:"project_northstar",projectName:"Northstar Orthopedics",kind:"answer-visibility",kindLabel:"Answer visibility sweep",status:"running",createdAt:"2026-03-08T13:40:00.000Z",startedAt:"Mar 8, 1:40 PM",duration:"3m 10s",statusDetail:"Provider responses still in flight for 9 multi-location prompts.",summary:"Mid-run on treatment-location prompts",triggerLabel:"Manual"}),JW=[{id:"evidence_citypoint_emergency_gemini",keyword:"emergency dentist brooklyn",provider:"gemini",model:"gemini-3-flash",location:null,citationState:"lost",changeLabel:"Lost since Mar 5",answerSnippet:"For urgent dental care in Brooklyn, Downtown Smiles and Harbor Dental are now cited first for emergency availability and same-day booking.",citedDomains:["downtownsmiles.com","harbordental.com"],evidenceUrls:["https://downtownsmiles.com/emergency-dentist-brooklyn","https://harbordental.com/same-day-emergency-care"],competitorDomains:["downtownsmiles.com","harbordental.com"],groundingSources:[],relatedTechnicalSignals:["FAQ schema missing on the emergency service page","llms.txt not found during latest site audit","Location pages link weakly into the emergency care hub"],summary:"AI answers now cite two competitors while your emergency page is no longer grounded.",runHistory:pi(["cited","cited","cited","cited","cited","cited","cited","not-cited","not-cited"])},{id:"evidence_citypoint_emergency_openai",keyword:"emergency dentist brooklyn",provider:"openai",model:"gpt-5.4",location:null,citationState:"cited",changeLabel:"Cited for 6 runs",answerSnippet:"Citypoint Dental is listed as a top emergency dentist in Brooklyn for same-day appointments and walk-in availability.",citedDomains:["citypointdental.com","downtownsmiles.com"],evidenceUrls:["https://citypointdental.com/emergency-dentist-brooklyn"],competitorDomains:["downtownsmiles.com"],groundingSources:[],relatedTechnicalSignals:["Emergency page indexed with structured data"],summary:"OpenAI cites your emergency page consistently alongside one competitor.",runHistory:pi(["not-cited","cited","cited","cited","cited","cited","cited"])},{id:"evidence_citypoint_emergency_claude",keyword:"emergency dentist brooklyn",provider:"claude",model:"claude-sonnet-4-6",location:null,citationState:"not-cited",changeLabel:"No citation across 12 runs",answerSnippet:"Based on the search results, top-rated emergency dental practices in Brooklyn include Downtown Smiles and Harbor Dental.",citedDomains:["downtownsmiles.com","harbordental.com"],evidenceUrls:[],competitorDomains:["downtownsmiles.com","harbordental.com"],groundingSources:[],relatedTechnicalSignals:["FAQ schema missing","llms.txt not found"],summary:"Claude does not cite your domain for this emergency query.",runHistory:pi(["not-cited","not-cited","not-cited","not-cited","not-cited","not-cited","not-cited","not-cited","not-cited","not-cited","not-cited","not-cited"])},{id:"evidence_citypoint_invisalign_openai",keyword:"best invisalign dentist downtown brooklyn",provider:"openai",model:"gpt-5.4",location:null,citationState:"emerging",changeLabel:"First citation in 7 days",answerSnippet:"Citypoint Dental appears as an emerging recommendation for Invisalign in Downtown Brooklyn, supported by recent before-and-after case pages.",citedDomains:["citypointdental.com","clearlineortho.com"],evidenceUrls:["https://citypointdental.com/invisalign-downtown-brooklyn","https://citypointdental.com/case-studies/invisalign-open-bite"],competitorDomains:["clearlineortho.com"],groundingSources:[],relatedTechnicalSignals:["Structured data now present on two case-study pages","Internal links from service pages to case studies improved crawl depth"],summary:"Fresh case-study content is starting to earn citations on Invisalign prompts.",runHistory:pi(["not-cited","not-cited","not-cited","not-cited","not-cited","not-cited","cited"])},{id:"evidence_citypoint_invisalign_gemini",keyword:"best invisalign dentist downtown brooklyn",provider:"gemini",model:"gemini-3-flash",location:null,citationState:"cited",changeLabel:"Cited for 8 runs",answerSnippet:"Citypoint Dental in Downtown Brooklyn is highlighted for its Invisalign expertise and patient outcomes.",citedDomains:["citypointdental.com"],evidenceUrls:["https://citypointdental.com/invisalign-downtown-brooklyn"],competitorDomains:[],groundingSources:[],relatedTechnicalSignals:["Case study pages well-indexed"],summary:"Gemini consistently cites your Invisalign page with no competitor overlap.",runHistory:pi(["cited","cited","cited","cited","cited","cited","cited","cited"])},{id:"evidence_citypoint_invisalign_claude",keyword:"best invisalign dentist downtown brooklyn",provider:"claude",model:"claude-sonnet-4-6",location:null,citationState:"not-cited",changeLabel:"No citation across 12 runs",answerSnippet:"For Invisalign in Downtown Brooklyn, Clear Line Ortho and Brooklyn Smiles are frequently recommended for their experienced orthodontists.",citedDomains:["clearlineortho.com","brooklynsmiles.com"],evidenceUrls:[],competitorDomains:["clearlineortho.com"],groundingSources:[],relatedTechnicalSignals:["No before/after schema on case study pages"],summary:"Claude does not surface your Invisalign content despite strong page quality.",runHistory:pi(["not-cited","not-cited","not-cited","not-cited","not-cited","not-cited","not-cited","not-cited","not-cited","not-cited","not-cited","not-cited"])},{id:"evidence_citypoint_children_claude",keyword:"pediatric dentist brooklyn heights",provider:"claude",model:"claude-sonnet-4-6",location:null,citationState:"not-cited",changeLabel:"No citation across 4 runs",answerSnippet:"Answers cite neighborhood-specific pediatric practices with stronger family-focused FAQ content and clearer insurance details.",citedDomains:["brightkidsdental.com","parkpediatricdental.com"],evidenceUrls:["https://brightkidsdental.com/pediatric-dentist-brooklyn-heights","https://parkpediatricdental.com/insurance"],competitorDomains:["brightkidsdental.com","parkpediatricdental.com"],groundingSources:[],relatedTechnicalSignals:["No dedicated pediatric service page exists for Brooklyn Heights","Insurance content is buried three clicks deep"],summary:"Coverage gap is content-driven, not purely technical.",runHistory:pi(["not-cited","not-cited","not-cited","not-cited"])},{id:"evidence_citypoint_children_gemini",keyword:"pediatric dentist brooklyn heights",provider:"gemini",model:"gemini-3-flash",location:null,citationState:"not-cited",changeLabel:"No citation across 12 runs",answerSnippet:"For pediatric dentistry in Brooklyn Heights, Bright Kids Dental and Park Pediatric Dental are cited for family-friendly care.",citedDomains:["brightkidsdental.com","parkpediatricdental.com"],evidenceUrls:[],competitorDomains:["brightkidsdental.com","parkpediatricdental.com"],groundingSources:[],relatedTechnicalSignals:["No dedicated pediatric page for Brooklyn Heights"],summary:"Gemini does not surface your domain for pediatric queries in this area.",runHistory:pi(["not-cited","not-cited","not-cited","not-cited","not-cited","not-cited","not-cited","not-cited","not-cited","not-cited","not-cited","not-cited"])},{id:"evidence_citypoint_children_openai",keyword:"pediatric dentist brooklyn heights",provider:"openai",model:"gpt-5.4",location:null,citationState:"cited",changeLabel:"First citation this month",answerSnippet:"Citypoint Dental is mentioned as offering pediatric services in Brooklyn, though specialized pediatric-only practices are also highlighted.",citedDomains:["citypointdental.com","brightkidsdental.com"],evidenceUrls:["https://citypointdental.com/family-dentistry"],competitorDomains:["brightkidsdental.com"],groundingSources:[],relatedTechnicalSignals:["Family dentistry page recently updated"],summary:"OpenAI recently started citing your family dentistry page for this query.",runHistory:pi(["not-cited","not-cited","not-cited","not-cited","not-cited","cited"])}];yb[0],yb[1],pi(["cited","cited","cited","cited","cited"]),yb[2],2/7,pi(["not-cited","not-cited","not-cited","cited"]);function eQ(e,t){return e.projects.find(n=>n.project.id===t)}function tQ(e,t){return e.runs.find(n=>n.id===t)}function nQ(e,t){for(const n of e.projects){const r=n.visibilityEvidence.find(i=>i.id===t);if(r)return{project:n,evidence:r}}}function UD(e){return{id:e.id,name:e.name,displayName:e.displayName,canonicalDomain:e.canonicalDomain,ownedDomains:e.ownedDomains??[],country:e.country,language:e.language,tags:e.tags,labels:e.labels,locations:e.locations??[],defaultLocation:e.defaultLocation??null,configSource:e.configSource,configRevision:e.configRevision,createdAt:e.createdAt,updatedAt:e.updatedAt}}function sE(e){try{return new Date(e).toLocaleDateString("en-US",{month:"short",day:"numeric",hour:"numeric",minute:"2-digit"})}catch{return e}}function rQ(e,t){if(!e)return"Waiting";if(!t)return"Running";const n=new Date(t).getTime()-new Date(e).getTime();if(n<1e3)return"<1s";const r=Math.floor(n/1e3);if(r<60)return`${r}s`;const i=Math.floor(r/60),s=r%60;return`${i}m ${s}s`}function BD(e){return e==="answer-visibility"?"Answer visibility sweep":e}function iQ(e){return e==="manual"?"Manual":e==="scheduled"?"Scheduled":e==="config-apply"?"Config apply":e}function v1(e,t){return{id:e.id,projectId:e.projectId,projectName:t,kind:e.kind,kindLabel:BD(e.kind),status:e.status,trigger:e.trigger??"manual",location:e.location??null,createdAt:e.createdAt,startedAt:e.startedAt?sE(e.startedAt):sE(e.createdAt),duration:rQ(e.startedAt,e.finishedAt),statusDetail:e.error?qD(e.error):aQ(e),summary:sQ(e),triggerLabel:iQ(e.trigger)}}function qD(e){try{const n=JSON.parse(e);if(typeof n=="object"&&n!==null){const r=n.message??n.error?.message??n[0]?.error?.message;if(typeof r=="string"&&r.length>0)return r.length>200?r.slice(0,200)+"…":r}}catch{}const t=e.match(/\[.*?\]\s*(.+)/);if(t){const n=t[1];return n.length>200?n.slice(0,200)+"…":n}return e.length>200?e.slice(0,200)+"…":e}function aQ(e){switch(e.status){case"queued":return"Waiting for execution slot.";case"running":return"Provider queries in progress.";case"completed":return"All key phrases checked.";case"partial":return"Run completed with some key phrases skipped.";case"failed":return e.error?qD(e.error):"Run failed.";default:return""}}function sQ(e){switch(e.status){case"queued":return"Queued for execution";case"running":return"In progress";case"completed":return"Visibility sweep completed";case"partial":return"Partial completion";case"failed":return"Run failed";default:return e.status}}function FD(e){if(e.length===0)return{score:0,citedCount:0,totalCount:0};const t=new Map;for(const s of e){const l=s.keyword??s.id;t.has(l)||t.set(l,!1),s.citationState==="cited"&&t.set(l,!0)}const n=t.size,r=[...t.values()].filter(Boolean).length;return{score:n>0?Math.round(r/n*100):0,citedCount:r,totalCount:n}}function oQ(e){return e>=70?"positive":e>=40?"caution":"negative"}function lQ(e){return e==="High"?"negative":e==="Moderate"?"caution":"neutral"}function cQ(e,t){return e===0?"positive":(t>0?e/t:0)>=.3?"negative":"caution"}function uQ(e){if(e.length===0)return{label:"Gap Key Phrases",value:"No data",delta:"Run a sweep first",tone:"neutral",description:"Run a visibility sweep to identify key phrases where competitors are cited and your domain is not.",tooltip:"Tracked key phrases where a competitor is cited in the latest run but your domain is not.",trend:[]};const t=new Map;for(const s of e){const l=s.keywordId,c=t.get(l)??{cited:!1,competitorOverlap:new Set};s.citationState==="cited"&&(c.cited=!0);for(const f of s.competitorOverlap)c.competitorOverlap.add(f);t.set(l,c)}const n=t.size,r=[...t.values()].filter(s=>!s.cited&&s.competitorOverlap.size>0).length,i=r===1?"key phrase":"key phrases";return{label:"Gap Key Phrases",value:`${r}`,delta:`${r} of ${n} key phrases at risk`,tone:cQ(r,n),description:r>0?`${r} tracked ${i} currently cite competitors without citing your domain.`:"No competitive key phrase gaps detected in the latest visibility run.",tooltip:"Tracked key phrases where a competitor is cited in the latest run but your domain is not.",trend:[],progress:n>0?r/n:0}}function dQ(e,t){return e&&e.summary.total>0?{provider:"Google",...e.summary}:t&&t.summary.total>0?{provider:"Bing",...t.summary,deindexed:0}:e?{provider:"Google",...e.summary}:t?{provider:"Bing",...t.summary,deindexed:0}:null}function fQ(e){return e.provider==="Google"&&e.deindexed>0?"negative":e.percentage>=90?"positive":e.percentage>=70?"caution":"negative"}function hQ(e,t){const n=dQ(e,t);if(!n||n.total===0)return{label:"Index Coverage",value:"No data",delta:"Connect GSC or Bing",tone:"neutral",description:"Connect Google Search Console or Bing Webmaster Tools and inspect your sitemap to populate coverage.",tooltip:"Percentage of inspected URLs currently indexed. Google Search Console is preferred when available, otherwise Bing Webmaster Tools is used.",trend:[]};const r=n.notIndexed===1?"URL is":"URLs are",i=n.deindexed===1?"URL":"URLs";return{label:"Index Coverage",value:`${Math.round(n.percentage)}`,delta:`${n.provider} · ${n.indexed} of ${n.total} indexed`,tone:fQ(n),description:n.provider==="Google"&&n.deindexed>0?`${n.deindexed} deindexed ${i} detected in the latest Google Search Console inspection.`:`${n.notIndexed} ${r} not indexed in ${n.provider==="Google"?"Google Search Console":"Bing Webmaster Tools"}.`,tooltip:"Percentage of inspected URLs currently indexed. Google Search Console is preferred when available, otherwise Bing Webmaster Tools is used.",trend:[]}}function KD(e,t){if(e.length===0||t.length===0)return{label:"None",count:0};const n=new Set(t);let r=0;for(const s of e)s.competitorOverlap.some(l=>n.has(l))&&r++;const i=r/e.length;return i>=.5?{label:"High",count:r}:i>=.2?{label:"Moderate",count:r}:{label:"Low",count:r}}function pQ(e,t,n,r){const i=[];let s=0;const l=new Set;if(n){const c=new Map;for(const v of n.snapshots)if(v.keyword){const y=`${v.keyword}::${v.provider}`;c.set(y,v)}const f=new Set(n.snapshots.map(v=>v.provider)),h=new Set(t.flatMap(v=>Object.keys(v.providerRuns??{}))),p=[...new Set([...f,...h])].sort(),g=p.length>0?p:["gemini"];for(const v of t){if(v.runs.length===0)continue;l.add(v.keyword);const y=v.runs.at(-1),S=y?.transition??"not-cited";for(const w of g){const N=c.get(`${v.keyword}::${w}`),C=(v.providerRuns?.[w]?.length??0)>0;if(!N&&!C)continue;const A=N?.model??null,k=A?`${w}:${A}`:null,O=k?v.modelRuns?.[k]:void 0,T=v.providerRuns?.[w],P=(T?.length?T:null)??(O?.length?O:null),E=T?.length?"provider":O?.length?"model":"keyword",z=P?P.at(-1).transition:S,D=P?P.at(-1).visibilityTransition??(P.at(-1).visibilityState==="visible"?"visible":"not-visible"):y?.visibilityTransition??(y?.visibilityState==="visible"?"visible":"not-visible"),K=P?.at(-1)?.citationState,U=P?.at(-1)?.visibilityState,L=N?z==="lost"?"lost":z==="emerging"?"emerging":N.citationState==="cited"?"cited":"not-cited":K==="cited"?"cited":"not-cited",ae=N?.visibilityState??(U==="visible"?"visible":U==="pending"?"pending":"not-visible"),ye=Nw(P||v.runs),me=oE(P||v.runs),G=mQ(v,w),re=(P??v.runs).map(R=>({runId:R.runId,citationState:R.citationState,createdAt:R.createdAt,model:G.get(R.runId)??null,answerMentioned:R.answerMentioned,visibilityState:R.visibilityState,visibilityTransition:R.visibilityTransition})),ge=gQ(re),we=E==="provider"&&ge.length<=1?"model":E,B=vQ(re);i.push({id:`evidence_${e}_${s++}`,keyword:v.keyword,provider:N?.provider??w,model:N?.model??null,location:N?.location??null,citationState:L,answerMentioned:N?.answerMentioned,visibilityState:ae,visibilityChangeLabel:lE(D,me,{positive:"visible",negative:"not visible",first:"first visibility"}),changeLabel:lE(z,ye),answerSnippet:N?.answerText??"",citedDomains:N?.citedDomains??[],evidenceUrls:[],competitorDomains:N?.competitorOverlap??[],recommendedCompetitors:N?.recommendedCompetitors??[],matchedTerms:N?.matchedTerms??[],relatedTechnicalSignals:[],groundingSources:N?.groundingSources??[],summary:yQ(ae,D,v.keyword),runHistory:re,historyScope:we,modelsSeen:ge,modelTransitions:B})}}}for(const c of r)l.has(c.keyword)||i.push({id:`evidence_${e}_${s++}`,keyword:c.keyword,provider:"",model:null,location:null,citationState:"pending",visibilityState:"pending",visibilityChangeLabel:"Awaiting first run",changeLabel:"Awaiting first run",answerSnippet:"",citedDomains:[],evidenceUrls:[],competitorDomains:[],recommendedCompetitors:[],matchedTerms:[],relatedTechnicalSignals:[],groundingSources:[],summary:`"${c.keyword}" has been added but no visibility run has been triggered yet.`,runHistory:[],historyScope:"keyword",modelsSeen:[],modelTransitions:[]});return i}function mQ(e,t){const n=new Map,r=`${t}:`;for(const[i,s]of Object.entries(e.modelRuns??{})){if(!i.startsWith(r))continue;const l=i.slice(r.length),c=l==="unknown"?null:l;for(const f of s)n.set(f.runId,c)}return n}function gQ(e){const t=new Set;for(const n of e)n.model&&t.add(n.model);return[...t]}function vQ(e){const t=[];let n=null;for(const r of e){const i=r.model??null;i!==n&&n!==null&&t.push({runId:r.runId,createdAt:r.createdAt,fromModel:n,toModel:i}),n=i}return t}function Nw(e){if(e.length===0)return 0;const t=e[e.length-1].citationState;let n=0;for(let r=e.length-1;r>=0&&e[r].citationState===t;r--)n++;return n}function oE(e){if(e.length===0)return 0;const t=e[e.length-1].visibilityState??"not-visible";let n=0;for(let r=e.length-1;r>=0&&(e[r].visibilityState??"not-visible")===t;r--)n++;return n}function lE(e,t,n){const r={positive:n?.positive??"cited",negative:n?.negative??"not cited",first:n?.first??"first citation"};switch(e){case"new":return"First observation";case"cited":case"visible":return t<=1?`${id(r.positive)} in latest run`:`${id(r.positive)} for ${t} runs`;case"lost":return"Lost since last run";case"emerging":return id(r.first);case"not-cited":case"not-visible":return t<=1?`${id(r.negative)} in latest run`:`${id(r.negative)} across ${t} runs`;default:return e}}function id(e){return e.charAt(0).toUpperCase()+e.slice(1)}function yQ(e,t,n){switch(t){case"lost":return`Visibility was lost for "${n}". Your brand no longer appeared in the latest answer.`;case"emerging":return`Your brand started appearing in AI answers for "${n}".`}switch(e){case"visible":return`Your brand or domain is visible in AI answers for "${n}".`;case"pending":return`"${n}" has been added but no visibility run has been triggered yet.`;default:return`Your brand or domain was not mentioned in AI answers for "${n}".`}}function cE(e,t){const n=new Set(t),r=new Map;for(const i of e)if(i.keyword)for(const s of i.competitorOverlap){if(!n.has(s))continue;const l=r.get(s)??new Set;l.add(i.keyword),r.set(s,l)}return r}const bb=3;function bQ(e){const{evidence:t,timeline:n,latestSnapshots:r,previousSnapshots:i,trackedCompetitors:s}=e,l=[],c=[],f=new Set;for(const C of t)C.citationState==="lost"&&(f.has(C.keyword)||(f.add(C.keyword),c.push({keyword:C.keyword,evidenceId:C.id,provider:C.provider,citationState:"lost"})));c.length>0&&l.push({id:"insight_lost",tone:"negative",title:`Lost citation on ${c.length} key phrase${c.length>1?"s":""}`,detail:"Citations dropped since the last run.",actionLabel:"Lost",affectedPhrases:c});const h=cE(r,s),p=cE(i,s);for(const C of s){const A=h.get(C)??new Set,k=p.get(C)??new Set,O=[...A].filter(T=>!k.has(T));O.length>0&&l.push({id:`insight_comp_gained_${C}`,tone:"negative",title:`${C} appeared on ${O.length} key phrase${O.length>1?"s":""}`,detail:"A tracked competitor gained new citations.",actionLabel:"Competitor",affectedPhrases:O.map(T=>{const P=t.find(E=>E.keyword===T);return{keyword:T,evidenceId:P?.id??"",citationState:"cited"}})})}const g=new Map;for(const C of n){const A=C.runs.at(-1);A&&g.set(C.keyword,{transition:A.transition,citationState:A.citationState})}const v=[],y=[],S=new Set;for(const[C,{transition:A,citationState:k}]of g){if(!(A==="emerging"||A==="new"&&k==="cited"))continue;S.add(C);const T=t.find(P=>P.keyword===C&&(P.citationState==="emerging"||P.citationState==="cited"));v.push({keyword:C,evidenceId:T?.id??"",provider:T?.provider,citationState:"emerging"})}for(const C of t)C.citationState==="emerging"&&(S.has(C.keyword)||y.push({keyword:C.keyword,evidenceId:C.id,provider:C.provider,citationState:"emerging"}));if(y.length>0){const C=new Set(y.map(A=>A.keyword)).size;l.push({id:"insight_provider_pickup",tone:"positive",title:`Picked up by new provider on ${C} key phrase${C>1?"s":""}`,detail:"Your domain started appearing on additional providers.",actionLabel:"Pickup",affectedPhrases:y})}v.length>0&&l.push({id:"insight_first_citation",tone:"positive",title:`First citation on ${S.size} key phrase${S.size>1?"s":""}`,detail:"Your domain appeared in AI answers for the first time.",actionLabel:"New",affectedPhrases:v});const w=new Set(t.map(C=>C.keyword)),N=[];for(const C of n){if(!w.has(C.keyword)||C.runs.length<bb||C.runs.at(-1)?.citationState!=="not-cited")continue;if(Nw(C.runs)>=bb){const O=t.find(T=>T.keyword===C.keyword);N.push({keyword:C.keyword,evidenceId:O?.id??"",citationState:"not-cited"})}}N.length>0&&l.push({id:"insight_persistent_gap",tone:"caution",title:`${N.length} key phrase${N.length>1?"s":""} uncited for ${bb}+ runs`,detail:"These key phrases have not been cited by any provider across multiple consecutive runs.",actionLabel:"Gap",affectedPhrases:N});for(const C of s){const A=h.get(C)??new Set,O=[...p.get(C)??new Set].filter(T=>!A.has(T));O.length>0&&l.push({id:`insight_comp_lost_${C}`,tone:"neutral",title:`${C} dropped from ${O.length} key phrase${O.length>1?"s":""}`,detail:"A tracked competitor lost citations.",actionLabel:"Competitor",affectedPhrases:O.map(T=>{const P=t.find(E=>E.keyword===T);return{keyword:T,evidenceId:P?.id??"",citationState:"not-cited"}})})}return l.length===0&&l.push({id:"insight_stable",tone:"neutral",title:"No significant changes",detail:"Citation state is stable across all tracked key phrases.",actionLabel:"Stable",affectedPhrases:[]}),l}function xQ(e,t){if(t.length===0){const f=new Set(e.filter(h=>h.citationState==="cited").map(h=>h.keyword)).size;return{gained:f,lost:0,tone:f>0?"positive":"neutral",hasPreviousRun:!1}}const n=f=>{const h=new Set;for(const p of f)p.citationState==="cited"&&p.keyword&&h.add(p.keyword);return h},r=n(e),i=n(t);let s=0,l=0;for(const f of r)i.has(f)||s++;for(const f of i)r.has(f)||l++;const c=l>s?"negative":s>l?"positive":"neutral";return{gained:s,lost:l,tone:c,hasPreviousRun:!0}}function wQ(e){const t=e[0];if(!t)return{label:"Run Status",value:"None",delta:"No runs yet",tone:"neutral",description:"Trigger a visibility sweep to start tracking.",tooltip:"Current execution state of visibility sweeps. Shows the status of the most recent run and total run count.",trend:[]};const n=t.status==="completed"?"Healthy":t.status==="running"?"Running":t.status==="queued"?"Queued":t.status==="partial"?"Partial":"Failed",r=t.status==="completed"?"positive":t.status==="failed"?"negative":t.status==="partial"?"caution":"neutral";return{label:"Run Status",value:n,delta:`${e.length} total runs`,tone:r,description:`Latest: ${BD(t.kind)} — ${t.status}`,tooltip:"Current execution state of visibility sweeps. Shows the status of the most recent run and total run count.",trend:[]}}function SQ(e){const t=UD(e.project),n=pQ(t.name,e.timeline,e.latestRunDetail,e.keywords),r=e.latestRunDetail?.snapshots??[],i=FD(r),s=uQ(r),l=hQ(e.gscCoverage,e.bingCoverage),c=KD(r,e.competitors.map(y=>y.domain)),f=bQ({evidence:n,timeline:e.timeline,latestSnapshots:e.latestRunDetail?.snapshots??[],previousSnapshots:e.previousRunDetail?.snapshots??[],trackedCompetitors:e.competitors.map(y=>y.domain)}),h=[...e.runs].sort((y,S)=>S.createdAt.localeCompare(y.createdAt)),p=h.map(y=>v1(y,e.project.displayName||e.project.name)),g=new Map;for(const y of r){const S=y.provider||"gemini",w=y.model??null,N=`${S}::${w??"unknown"}`,C=g.get(N)??{provider:S,model:w,cited:0,total:0};C.total++,y.citationState==="cited"&&C.cited++,g.set(N,C)}const v=[...g.values()].sort((y,S)=>y.provider.localeCompare(S.provider)||(y.model??"").localeCompare(S.model??"")).map(({provider:y,model:S,cited:w,total:N})=>({provider:y,model:S,score:N>0?Math.round(w/N*100):0,cited:w,total:N}));return{project:t,dateRangeLabel:"All time",contextLabel:`${t.country} / ${t.language.toUpperCase()}`,visibilitySummary:{label:"Answer Visibility",value:r.length>0?`${i.score}`:"No data",delta:r.length>0?`${i.citedCount} of ${i.totalCount} key phrases visible`:"Run a sweep first",tone:r.length>0?oQ(i.score):"neutral",description:r.length>0?`${i.citedCount} of ${i.totalCount} tracked key phrases found your domain in at least one AI answer engine.`:"No visibility data yet. Trigger a run to start tracking.",tooltip:'Percentage of tracked key phrases where your domain is cited by at least one AI answer engine. A key phrase is "visible" if any configured provider includes your site in its response.',trend:[]},keywordCounts:{cited:i.citedCount,total:i.totalCount},gapKeyPhrases:s,indexCoverage:l,providerScores:v,competitorPressure:{label:"Competitor Pressure",value:c.label,delta:c.count>0?`${c.count} overlapping citations`:"No overlap detected",tone:lQ(c.label),description:e.competitors.length>0?`${e.competitors.length} competitor${e.competitors.length>1?"s":""} tracked.`:"No competitors configured.",tooltip:"How often competitor domains appear alongside yours in AI answers. High pressure means competitors are frequently cited for the same key phrases.",trend:[]},runStatus:wQ(h),movementSummary:xQ(e.latestRunDetail?.snapshots??[],e.previousRunDetail?.snapshots??[]),insights:f,visibilityEvidence:n,competitors:e.competitors.map((y,S)=>{const w=new Set;for(const O of r)(O.competitorOverlap.includes(y.domain)||O.citedDomains.includes(y.domain))&&O.keyword&&w.add(O.keyword);const N=[...w],C=new Set(r.map(O=>O.keyword).filter(Boolean)),A=C.size>0?N.length/C.size:0,k=A>=.5?"High":A>=.2?"Moderate":N.length>0?"Low":"None";return{id:y.id||`comp_${S}`,domain:y.domain,citationCount:N.length,totalKeywords:C.size,pressureLabel:k,citedKeywords:N,movement:"",notes:""}}),recentRuns:p.slice(0,5)}}function jQ(e){const t=UD(e.project),n=e.latestRunDetail?.snapshots??[],r=FD(n),i=KD(n,e.competitors.map(f=>f.domain)),l=[...e.runs].sort((f,h)=>h.createdAt.localeCompare(f.createdAt))[0],c=l?v1(l,e.project.displayName||e.project.name):{id:"none",projectId:e.project.id,projectName:e.project.displayName||e.project.name,kind:"answer-visibility",kindLabel:"No runs yet",status:"queued",trigger:"manual",createdAt:"",startedAt:"",duration:"",statusDetail:"",summary:"No runs yet",triggerLabel:""};return{project:t,visibilityScore:r.score,visibilityDelta:n.length>0?`${r.citedCount} of ${r.totalCount} key phrases`:"No data",lastRun:c,insight:n.length>0?`${r.citedCount} of ${r.totalCount} key phrases visible across ${new Set(n.map(f=>f.provider)).size} provider${new Set(n.map(f=>f.provider)).size>1?"s":""}.`:"No runs completed yet.",trend:[],competitorPressureLabel:i.label}}function NQ(e,t){const n=[],r=[],i=[];for(const l of e){r.push(SQ(l)),i.push(jQ(l));const c=[...l.runs].sort((f,h)=>h.createdAt.localeCompare(f.createdAt));for(const f of c)n.push(v1(f,l.project.displayName||l.project.name))}n.sort((l,c)=>c.createdAt.localeCompare(l.createdAt));const s=e.length>0;return{portfolioOverview:{projects:i,attentionItems:s?CQ(r):[{id:"attention_setup",tone:"neutral",title:"No projects yet",detail:"Create your first project using the setup wizard, CLI, or API.",actionLabel:"Open setup",href:"/setup"}],recentRuns:n.slice(0,5),systemHealth:[{id:"api",label:"API",tone:"positive",detail:"Connected",meta:"Real-time data"},{id:"provider",label:"Gemini",tone:"positive",detail:"Configured",meta:"Provider active"}],lastUpdatedAt:new Date().toLocaleString("en-US",{month:"short",day:"numeric",hour:"numeric",minute:"2-digit",timeZoneName:"short"}),...s?{}:{emptyState:{title:"No projects yet",detail:"Canonry becomes useful after one project, a small key phrase set, and one competitor list are in place.",ctaLabel:"Launch setup",ctaHref:"/setup"}}},projects:r,runs:n,setup:{healthChecks:[{id:"api",label:"API reachable",detail:"API is responding.",state:"ready",guidance:"Required for project creation and run history."},{id:"provider",label:"Provider configured",detail:"Gemini key is configured.",state:"ready",guidance:"Required for answer-visibility sweeps."}],projectDraft:{name:"",canonicalDomain:"",country:"US",language:"en"},keywordImportState:{mode:"paste",keywordCount:0,preview:[]},competitorDraft:{domains:[],notes:"Use the CLI to add competitors."},launchState:{enabled:s,ctaLabel:s?"Trigger run":"Create a project first",summary:s?"Ready to run.":"Create a project first to launch a run."}},settings:{providerStatuses:(t?.providers??[]).map(l=>({name:l.name,displayName:l.displayName,keyUrl:l.keyUrl,modelHint:l.modelHint,model:l.model,state:l.configured?"ready":"needs-config",detail:l.configured?"Provider is configured.":"API key is missing.",quota:l.quota})),google:{state:t?.google?.configured?"ready":"needs-config",detail:t?.google?.configured?"Google OAuth app credentials are configured. Project-level GSC connections can be created from the dashboard.":"Google OAuth client ID and client secret are not configured yet."},bing:{state:t?.bing?.configured?"ready":"needs-config",detail:t?.bing?.configured?"Bing Webmaster Tools API key is configured. Project-level Bing connections can be created from the dashboard.":"Bing Webmaster Tools API key is not configured yet."},selfHostNotes:["Configuration is stored in ~/.canonry/config.yaml.","The local config file is the source of truth for authentication credentials.","Google OAuth app credentials and per-domain Google tokens are stored in local config, not the database.","Database is SQLite at ~/.canonry/data.db.","API key was auto-generated during canonry init."],bootstrapNote:"Use the UI, CLI, or ~/.canonry/config.yaml to manage settings. Authentication credentials persist to local config."}}}function CQ(e){const t=[];for(const n of e){const r=n.visibilityEvidence.filter(s=>s.citationState==="lost");r.length>0&&t.push({id:`attention_${n.project.id}_lost`,tone:"negative",title:`${n.project.displayName||n.project.name} lost citations`,detail:`${r.length} key phrase${r.length>1?"s":""} lost citation.`,actionLabel:"Open project",href:`/projects/${n.project.id}`});const i=n.recentRuns.filter(s=>s.status==="running"||s.status==="queued");i.length>0&&t.push({id:`attention_${n.project.id}_active`,tone:"neutral",title:`${n.project.displayName||n.project.name} has active runs`,detail:`${i.length} run${i.length>1?"s":""} in progress.`,actionLabel:"View runs",href:"/runs"})}return t.length===0&&t.push({id:"attention_stable",tone:"positive",title:"All projects stable",detail:"No citation losses or active runs to flag.",actionLabel:"View portfolio",href:"/"}),t}const Yr={projects:{all:["projects"],detail:(e,t)=>["projects",e,t],keywords:e=>["projects",e,"keywords"],competitors:e=>["projects",e,"competitors"],timeline:(e,t)=>["projects",e,"timeline",t]},runs:{all:["runs"],detail:e=>["runs",e]},settings:["settings"],health:["health"]},HD=x.createContext(null);HD.Provider;function af(){return x.useContext(HD)}function sl(e){const n=af()?.dashboard??null,r=zo({queryKey:Yr.projects.all,queryFn:IM,enabled:!n}),i=zo({queryKey:Yr.runs.all,queryFn:$M,enabled:!n,refetchInterval:S=>S.state.data?.some(C=>C.status==="running"||C.status==="queued")?3e3:!1}),s=zo({queryKey:Yr.settings,queryFn:()=>WS().catch(()=>null),enabled:!n}),l=r.data??[],c=i.data??[],f=qB({queries:l.map(S=>{const w=c.filter(C=>C.projectId===S.id),N=w.filter(C=>(C.status==="completed"||C.status==="partial")&&C.kind==="answer-visibility").sort((C,A)=>A.createdAt.localeCompare(C.createdAt));return{queryKey:Yr.projects.detail(S.id,N[0]?.id),queryFn:async()=>{const[C,A,k,O,T,P,E]=await Promise.all([Zq(S.name).catch(()=>[]),UM(S.name).catch(()=>[]),BM(S.name).catch(()=>[]),N[0]?Ac(N[0].id).catch(()=>null):Promise.resolve(null),N[1]?Ac(N[1].id).catch(()=>null):Promise.resolve(null),QS(S.name).catch(()=>null),XS(S.name).catch(()=>null)]);return{project:S,runs:w,keywords:C,competitors:A,timeline:k,latestRunDetail:O,previousRunDetail:T,gscCoverage:P,bingCoverage:E}},enabled:!n&&r.isSuccess&&i.isSuccess}})}),h=f.every(S=>S.isSuccess),p=x.useMemo(()=>{if(n)return n;if(!r.data||!i.data||l.length>0&&!h)return null;const S=f.map(w=>w.data).filter(w=>w!=null);return NQ(S,s.data??null)},[n,r.data,i.data,s.data,h,f,l.length]),g=!n&&(r.isError||i.isError),v=!n&&!p&&!g,y=x.useCallback(async()=>{await Promise.all([r.refetch(),i.refetch(),s.refetch()])},[r.refetch,i.refetch,s.refetch]);return{dashboard:p,isLoading:v,isError:g,refetch:y}}function OQ(){return typeof window<"u"&&window.__CANONRY_CONFIG__?.basePath?window.__CANONRY_CONFIG__.basePath:"/"}const uE=OQ(),Cw=uE==="/"?"":uE.replace(/\/$/,"");async function _Q(){const e=Cw?`${Cw}/health`:"/health",t=await F9(e,"API"),n=t.state==="ok"?{label:"Runner",state:"ok",detail:"In-process job runner"}:{label:"Runner",state:t.state,detail:"Depends on API"};return{apiStatus:t,workerStatus:n}}function Mg(e,t){return zo({queryKey:Yr.health,queryFn:_Q,enabled:e,refetchInterval:15e3,initialData:t})}function kQ(e){return zo({queryKey:Yr.runs.detail(e??""),queryFn:()=>Ac(e),enabled:!!e,refetchInterval:t=>{const n=t.state.data?.status;return n==="running"||n==="queued"?3e3:!1}})}function Vc(){const e=Us(),t=bg({strict:!1}),n=gr({select:f=>f.location.pathname}),r=t.runId??null,i=t.evidenceId??null;return{runId:r,evidenceId:i,openRun:f=>e({to:n,from:xi.to,search:h=>({...h,runId:f,evidenceId:void 0})}),openEvidence:f=>e({to:n,from:xi.to,search:h=>({...h,evidenceId:f,runId:void 0})}),closeDrawer:()=>e({to:n,from:xi.to,search:f=>({...f,runId:void 0,evidenceId:void 0})})}}const AQ={negative:"toast-card-negative",caution:"toast-card-caution",positive:"toast-card-positive",neutral:"toast-card-neutral"};function EQ(e){if(e.cta)return`${e.cta.label}: ${e.title}`}function TQ(){const e=x.useSyncExternalStore(Y9,sA,sA),t=Us(),{openRun:n}=Vc(),r=x.useCallback(s=>{hw(s)},[]),i=x.useCallback(s=>{s.cta&&(s.cta.intent==="open-run-drawer"?n(s.cta.runId):t({to:"/runs"}),hw(s.id))},[t,n]);return e.length===0?null:u.jsx("div",{className:"toast-viewport","aria-label":"Notifications",children:e.map(s=>u.jsxs("section",{role:s.tone==="negative"?"alert":"status","aria-live":s.tone==="negative"?"assertive":"polite","data-state":s.state,className:`toast-card ${AQ[s.tone]}`,children:[u.jsxs("div",{className:"toast-copy",children:[u.jsx("p",{className:"toast-title",children:s.title}),s.detail?u.jsx("p",{className:"toast-detail",children:s.detail}):null,s.cta?u.jsx("button",{type:"button",className:"toast-action",onClick:()=>i(s),"aria-label":EQ(s),children:s.cta.label}):null]}),u.jsx("button",{type:"button",onClick:()=>r(s.id),className:"toast-dismiss","aria-label":"Dismiss",children:u.jsx(Sg,{className:"size-3.5"})})]},s.id))})}const dE=[{label:"Architecture",href:"https://github.com/AINYC/canonry/blob/main/docs/architecture.md"},{label:"Testing Guide",href:"https://github.com/AINYC/canonry/blob/main/docs/testing.md"}],fE=e=>({label:e,state:"checking",detail:"Checking service health"}),PQ={apiStatus:fE("API"),workerStatus:fE("Worker")};function zQ(e){return e==="gsc-sync"?"GSC sync":e==="inspect-sitemap"?"Sitemap inspection":"Visibility sweep"}function MQ(e){return e==="completed"?"positive":e==="partial"?"caution":"negative"}function RQ(e){const t=zQ(e.kind);return e.status==="completed"?`${t} completed`:e.status==="partial"?`${t} completed with partial results`:e.status==="cancelled"?`${t} cancelled`:`${t} failed`}function DQ(e,t){return e.error?`${t}: ${e.error}`:e.location?`${t} · ${e.location}`:t}function IQ(e,t,n){if(t)return t;const r=n.find(i=>i.id===e);return r?.displayName||r?.name||e}function LQ(e,t){return[e.completed>0?`${e.completed} completed`:null,e.partial>0?`${e.partial} partial`:null,e.failed>0?`${e.failed} failed`:null,e.cancelled>0?`${e.cancelled} cancelled`:null,t>0?`${t} skipped at queue time`:null].filter(Boolean).join(", ")}function $Q(e){return e.failed>0||e.cancelled>0?"negative":e.partial>0?"caution":"positive"}function UQ(){const e=x.useSyncExternalStore($F,Ko,Ko),t=Object.keys(e.runs).length>0||Object.keys(e.batches).length>0,n=zo({queryKey:Yr.runs.all,queryFn:$M,enabled:t}),r=zo({queryKey:Yr.projects.all,queryFn:IM,enabled:t}),i=x.useRef({}),s=x.useCallback(()=>{n.refetch()},[n.refetch]);return x.useEffect(()=>{t&&s()},[t,s]),x.useEffect(()=>{if(!t||typeof window>"u")return;const l=()=>{document.visibilityState==="visible"&&s()};return window.addEventListener("focus",s),document.addEventListener("visibilitychange",l),()=>{window.removeEventListener("focus",s),document.removeEventListener("visibilitychange",l)}},[t,s]),x.useEffect(()=>{const l=n.data??[],c=r.data??[],f=Object.fromEntries(l.map(p=>[p.id,p])),h=Object.fromEntries(l.map(p=>[p.id,p.status]));for(const p of Object.values(e.runs)){const g=f[p.runId];if(!g||!qF(g.status)||(i.current[g.id]??p.lastAnnouncedStatus)===g.status)continue;if(p.sourceAction==="run-all"){fA(g.id);continue}const y=IQ(g.projectId,p.projectLabel,c);Qe({title:RQ(g),detail:DQ(g,y),tone:MQ(g.status),dedupeKey:`run:${g.id}`,dedupeMode:"replace",cta:{label:"View run",intent:"open-run-drawer",runId:g.id}}),fA(g.id)}for(const p of Object.values(e.batches)){const g=FF(p.runIds,f);g.finished&&(Qe({title:"Run-all batch finished",detail:LQ(g,p.skippedCount),tone:$Q(g),dedupeKey:`batch:${p.batchId}`,dedupeMode:"replace",cta:{label:"View runs",intent:"go-to-runs"}}),BF(p.batchId))}i.current=h},[r.data,n.data,e]),null}function BQ(){const e=af(),{dashboard:t,isLoading:n,refetch:r}=sl(),l=Mg(!e,e?.health).data??e?.health??PQ,c=Kq(),{runId:f,evidenceId:h,closeDrawer:p}=Vc(),[g,v]=x.useState(!1),y=kQ(f),S=y.data??null,w=y.isLoading;x.useEffect(()=>{S&&S.status!=="running"&&S.status!=="queued"&&r()},[S?.status,r]),x.useEffect(()=>{v(!1)},[c.pathname]),x.useEffect(()=>{if(typeof window>"u"||!f&&!h)return;const O=T=>{T.key==="Escape"&&p()};return window.addEventListener("keydown",O),()=>{window.removeEventListener("keydown",O)}},[f,h,p]);const N=t??e?.dashboard??null,C=f&&N?tQ(N,f):void 0,A=h&&N?nQ(N,h):void 0,k=(()=>{const O=c.pathname;if(O==="/")return"Portfolio";if(O==="/projects")return"Projects";if(O==="/runs")return"Runs";if(O==="/settings")return"Settings";if(O==="/setup")return"Setup";if(O.startsWith("/projects/")){const P=O.split("/").filter(Boolean)[1];if(P&&N){const E=N.projects.find(z=>z.project.id===P);if(E)return E.project.name}return"Project"}return"Not found"})();return u.jsxs("div",{className:"app-shell",children:[u.jsx("a",{className:"skip-link",href:"#content",children:"Skip to content"}),u.jsxs("aside",{className:"sidebar","aria-label":"Primary navigation",children:[u.jsx("div",{className:"sidebar-brand",children:u.jsx(SA,{})}),u.jsxs("nav",{className:"sidebar-nav",children:[u.jsxs(Dt,{to:"/",className:"sidebar-link",activeProps:{className:"sidebar-link sidebar-link-active"},activeOptions:{exact:!0},children:[u.jsx(uF,{className:"sidebar-icon"}),u.jsx("span",{children:"Overview"})]}),u.jsxs(Dt,{to:"/projects",className:"sidebar-link",activeProps:{className:"sidebar-link sidebar-link-active"},activeOptions:{exact:!1},children:[u.jsx(lF,{className:"sidebar-icon"}),u.jsx("span",{children:"Projects"})]}),u.jsxs(Dt,{to:"/runs",className:"sidebar-link",activeProps:{className:"sidebar-link sidebar-link-active"},activeOptions:{exact:!0},children:[u.jsx(pF,{className:"sidebar-icon"}),u.jsx("span",{children:"Runs"})]}),u.jsxs(Dt,{to:"/settings",className:"sidebar-link",activeProps:{className:"sidebar-link sidebar-link-active"},activeOptions:{exact:!0},children:[u.jsx(SF,{className:"sidebar-icon"}),u.jsx("span",{children:"Settings"})]}),n?u.jsxs(u.Fragment,{children:[u.jsx("p",{className:"sidebar-section-title",children:"Projects"}),[1,2,3].map(O=>u.jsxs("div",{className:"sidebar-skeleton-item",children:[u.jsx("span",{className:"skeleton-circle size-2"}),u.jsx("span",{className:"skeleton-text flex-1",style:{width:`${50+O*15}%`}})]},O))]}):N&&N.projects.length>0?u.jsxs(u.Fragment,{children:[u.jsx("p",{className:"sidebar-section-title",children:"Projects"}),N.projects.map(O=>{const T=O.visibilitySummary.tone;return u.jsxs(Dt,{to:"/projects/$projectId",params:{projectId:O.project.id},className:"sidebar-project",activeProps:{className:"sidebar-project sidebar-project-active"},children:[u.jsx("span",{className:`sidebar-dot sidebar-dot-${T}`}),u.jsx("span",{children:O.project.name})]},O.project.id)})]}):n?null:u.jsxs(u.Fragment,{children:[u.jsx("p",{className:"sidebar-section-title",children:"Resources"}),u.jsxs(Dt,{to:"/setup",className:"sidebar-link",activeProps:{className:"sidebar-link sidebar-link-active"},activeOptions:{exact:!0},children:[u.jsx(yF,{className:"sidebar-icon"}),u.jsx("span",{children:"Setup"})]})]})]}),u.jsx("div",{className:"sidebar-footer",children:dE.map(O=>u.jsx("a",{className:"sidebar-footer-link",href:O.href,target:"_blank",rel:"noreferrer",children:O.label},O.href))})]}),u.jsxs("div",{className:"main-area",children:[u.jsxs("header",{className:"topbar",children:[u.jsxs("div",{className:"topbar-left",children:[u.jsx("div",{className:"topbar-brand-mobile",children:u.jsx(SA,{compact:!0})}),u.jsxs("nav",{className:"breadcrumb","aria-label":"Breadcrumb",children:[u.jsx(Dt,{to:"/",children:"Home"}),u.jsx(wg,{className:"breadcrumb-sep size-3"}),u.jsx("span",{className:"breadcrumb-current",children:k})]})]}),u.jsxs("div",{className:"topbar-actions",children:[u.jsxs("div",{className:"health-pill-row",children:[u.jsxs("span",{className:`health-pill health-pill-${l.apiStatus.state}`,children:["API ",l.apiStatus.state==="ok"?"ok":l.apiStatus.state]}),u.jsxs("span",{className:`health-pill health-pill-${l.workerStatus.state}`,children:["Worker ",l.workerStatus.state==="ok"?"ok":l.workerStatus.state]})]}),u.jsxs(pe,{className:"nav-toggle",variant:"secondary",size:"icon",type:"button","aria-expanded":g,"aria-controls":"mobile-nav",onClick:()=>v(O=>!O),children:[u.jsx(fF,{className:"size-4"}),u.jsx("span",{className:"sr-only",children:"Open navigation"})]})]})]}),u.jsxs("div",{id:"mobile-nav",className:`mobile-nav ${g?"mobile-nav-open":""}`,children:[u.jsxs(pe,{className:"mobile-nav-close",variant:"ghost",size:"icon",type:"button",onClick:()=>v(!1),children:[u.jsx(Sg,{className:"size-5"}),u.jsx("span",{className:"sr-only",children:"Close navigation"})]}),u.jsx(Dt,{to:"/",className:"mobile-nav-link",activeProps:{className:"mobile-nav-link mobile-nav-link-active"},activeOptions:{exact:!0},children:"Overview"}),u.jsx(Dt,{to:"/projects",className:"mobile-nav-link",activeProps:{className:"mobile-nav-link mobile-nav-link-active"},activeOptions:{exact:!1},children:"Projects"}),u.jsx(Dt,{to:"/runs",className:"mobile-nav-link",activeProps:{className:"mobile-nav-link mobile-nav-link-active"},activeOptions:{exact:!0},children:"Runs"}),u.jsx(Dt,{to:"/settings",className:"mobile-nav-link",activeProps:{className:"mobile-nav-link mobile-nav-link-active"},activeOptions:{exact:!0},children:"Settings"}),N&&N.projects.length>0?u.jsxs("div",{className:"mobile-nav-section",children:[u.jsx("p",{className:"mobile-nav-section-title",children:"Projects"}),N.projects.map(O=>u.jsx(Dt,{to:"/projects/$projectId",params:{projectId:O.project.id},className:"mobile-nav-link",children:O.project.name},O.project.id))]}):null]}),u.jsx("main",{id:"content",className:"page-shell",children:n&&!e?u.jsxs("div",{className:"page-skeleton",children:[u.jsxs("div",{className:"page-skeleton-header",children:[u.jsx("div",{className:"skeleton-text h-6 w-40"}),u.jsx("div",{className:"skeleton-text-sm w-72"})]}),u.jsx("div",{className:"page-skeleton-grid",children:[1,2,3].map(O=>u.jsxs("div",{className:"page-skeleton-card",children:[u.jsx("div",{className:"skeleton-text w-24"}),u.jsx("div",{className:"skeleton-text w-full"}),u.jsx("div",{className:"skeleton-text-sm w-3/4"})]},O))}),u.jsx("div",{className:"page-skeleton-grid",style:{gridTemplateColumns:"1fr 1fr"},children:[1,2].map(O=>u.jsxs("div",{className:"page-skeleton-card",children:[u.jsx("div",{className:"skeleton-text w-20"}),u.jsx("div",{className:"space-y-2",children:[1,2,3].map(T=>u.jsx("div",{className:"skeleton-text-sm w-full"},T))})]},O))})]}):u.jsx(YS,{})}),u.jsxs("footer",{className:"footer",children:[u.jsxs("a",{href:"https://github.com/AINYC/canonry",target:"_blank",rel:"noreferrer",className:"footer-brand",children:[u.jsx(sF,{className:"size-3.5"}),u.jsx("span",{children:"Canonry"})]}),u.jsx("div",{className:"footer-links",children:dE.map(O=>u.jsx("a",{href:O.href,target:"_blank",rel:"noreferrer",children:O.label},O.href))})]})]}),C?u.jsxs(E7,{open:C!==void 0,title:C.summary,subtitle:`${C.projectName} · ${C.kindLabel}`,onClose:p,children:[u.jsxs("div",{className:"flex flex-wrap items-center gap-x-5 gap-y-1 text-sm",children:[u.jsx(Og,{status:C.status}),u.jsx("span",{className:"text-zinc-400",children:C.startedAt}),u.jsx("span",{className:"text-zinc-500",children:C.duration}),u.jsx("span",{className:"text-zinc-600",children:C.triggerLabel})]}),C.status==="failed"&&C.statusDetail&&u.jsx("p",{className:"text-sm text-rose-300/80 mt-2",children:C.statusDetail}),u.jsxs("div",{className:"mt-4",children:[u.jsx("p",{className:"text-[10px] font-semibold uppercase tracking-wider text-zinc-500 mb-2",children:"Activity Log"}),w?u.jsx("p",{className:"text-sm text-zinc-500",children:"Loading run details..."}):S&&S.snapshots.length>0?u.jsxs("div",{className:"space-y-2",children:[S.snapshots.map(O=>u.jsxs("div",{className:"rounded-lg border border-zinc-800/60 bg-zinc-900/30 p-3",children:[u.jsxs("div",{className:"flex items-center justify-between gap-2 mb-1",children:[u.jsx("p",{className:"text-sm font-medium text-zinc-200 truncate",children:O.keyword??"Unknown key phrase"}),u.jsxs("div",{className:"flex items-center gap-1.5",children:[u.jsx(zd,{provider:O.provider}),u.jsx(vR,{variant:O.citationState==="cited"?"success":"neutral",children:O.citationState})]})]}),O.model&&u.jsx("p",{className:"text-[11px] text-zinc-500 font-mono",children:O.model}),O.citedDomains.length>0&&u.jsxs("p",{className:"text-xs text-zinc-500 mt-1",children:[u.jsx("span",{className:"text-zinc-400",children:"Sources:"})," ",O.citedDomains.join(", ")]}),O.competitorOverlap.length>0&&u.jsxs("p",{className:"text-xs text-rose-400/80 mt-0.5",children:["Competitor cited: ",O.competitorOverlap.join(", ")]}),O.groundingSources&&O.groundingSources.length>0&&u.jsxs("details",{className:"mt-2",children:[u.jsxs("summary",{className:"text-xs text-zinc-500 cursor-pointer hover:text-zinc-400",children:[O.groundingSources.length," grounding source",O.groundingSources.length!==1?"s":""]}),u.jsx("ul",{className:"mt-1 space-y-0.5",children:O.groundingSources.map((T,P)=>u.jsx("li",{className:"text-xs text-zinc-500 truncate",children:u.jsx("a",{href:T.uri,target:"_blank",rel:"noreferrer",className:"hover:text-zinc-300",children:T.title||T.uri})},P))})]}),O.answerText&&u.jsxs("details",{className:"mt-1",children:[u.jsx("summary",{className:"text-xs text-zinc-500 cursor-pointer hover:text-zinc-400",children:"Answer preview"}),u.jsx("p",{className:"mt-1 text-xs text-zinc-400 leading-relaxed whitespace-pre-wrap",children:O.answerText})]})]},O.id)),S.status==="running"&&u.jsxs("div",{className:"flex items-center gap-2 p-3 text-sm text-zinc-500",children:[u.jsx("span",{className:"inline-block h-2 w-2 rounded-full bg-amber-500 animate-pulse"}),"Querying remaining key phrases..."]})]}):S&&S.status==="running"?u.jsxs("div",{className:"flex items-center gap-2 p-3 text-sm text-zinc-500",children:[u.jsx("span",{className:"inline-block h-2 w-2 rounded-full bg-amber-500 animate-pulse"}),"Waiting for first key phrase result..."]}):S&&S.status==="queued"?u.jsxs("div",{className:"flex items-center gap-2 p-3 text-sm text-zinc-500",children:[u.jsx("span",{className:"inline-block h-2 w-2 rounded-full bg-zinc-500 animate-pulse"}),"Run queued, waiting for execution slot..."]}):S&&S.error?u.jsxs("div",{className:"rounded-lg border border-rose-800/40 bg-rose-950/20 p-3",children:[u.jsx("p",{className:"text-sm font-medium text-rose-300 mb-2",children:"Run failed"}),u.jsx("pre",{className:"text-xs text-rose-300/80 whitespace-pre-wrap break-words max-h-48 overflow-y-auto font-mono leading-5",children:PF(S.error)})]}):u.jsx("p",{className:"text-sm text-zinc-500",children:"No snapshot data available."})]})]}):null,A?u.jsx(ZW,{evidence:A.evidence,project:A.project,onClose:p}):null,u.jsx(UQ,{}),u.jsx(TQ,{})]})}class qQ extends x.Component{state={error:null};static getDerivedStateFromError(t){return{error:t}}componentDidCatch(t,n){console.error("[ErrorBoundary]",t,n.componentStack)}handleReset=()=>{this.setState({error:null})};render(){return this.state.error?u.jsx("div",{className:"page-container",children:u.jsxs("div",{className:"flex flex-col items-center justify-center gap-4 py-20 text-center",children:[u.jsx("div",{className:"rounded-full bg-rose-950/40 p-3",children:u.jsx(OF,{className:"size-6 text-rose-400"})}),u.jsx("h2",{className:"text-lg font-semibold text-zinc-100",children:"Something went wrong"}),u.jsx("p",{className:"text-sm text-zinc-400 max-w-md",children:this.state.error.message||"An unexpected error occurred while rendering this page."}),u.jsxs("div",{className:"flex gap-3 mt-2",children:[u.jsxs(pe,{variant:"secondary",size:"sm",onClick:this.handleReset,children:[u.jsx(xF,{className:"size-3.5 mr-1.5"}),"Try again"]}),u.jsx(pe,{variant:"secondary",size:"sm",onClick:()=>{window.location.href="/"},children:"Go home"})]})]})}):this.props.children}}const Ue=x.forwardRef(({className:e,...t},n)=>u.jsx("div",{ref:n,className:ai("rounded-xl border border-zinc-800 bg-zinc-950/75 shadow-[0_0_0_1px_rgba(255,255,255,0.01)] backdrop-blur",e),...t}));Ue.displayName="Card";const Ow=x.forwardRef(({className:e,...t},n)=>u.jsx("div",{ref:n,className:ai("flex flex-col gap-1.5 p-5",e),...t}));Ow.displayName="CardHeader";const _w=x.forwardRef(({className:e,...t},n)=>u.jsx("h3",{ref:n,className:ai("font-medium tracking-tight text-zinc-50",e),...t}));_w.displayName="CardTitle";const kw=x.forwardRef(({className:e,...t},n)=>u.jsx("p",{ref:n,className:ai("text-sm text-zinc-500",e),...t}));kw.displayName="CardDescription";const Lp=x.forwardRef(({className:e,...t},n)=>u.jsx("div",{ref:n,className:ai("p-5 pt-0",e),...t}));Lp.displayName="CardContent";function FQ({points:e,tone:t}){const n=x.useId();if(e.length===0)return null;const r=42,i=132,s=5,l=Math.min(...e),f=Math.max(...e)-l||1,h=i-s*2,p=r-s*2,g=e.map((v,y)=>{const S=s+y/Math.max(e.length-1,1)*h,w=s+(1-(v-l)/f)*p;return`${S},${w}`}).join(" ");return u.jsxs("svg",{className:`sparkline sparkline-${t}`,viewBox:`0 0 ${i} ${r}`,"aria-hidden":"true",children:[u.jsx("defs",{children:u.jsx("clipPath",{id:n,children:u.jsx("rect",{x:s,y:s,width:h,height:p,rx:"8"})})}),u.jsx("line",{className:"sparkline-guide",x1:s,x2:i-s,y1:r-s,y2:r-s}),u.jsx("polyline",{clipPath:`url(#${n})`,points:g,vectorEffect:"non-scaling-stroke"})]})}function KQ(e){return e.displayName??e.name.charAt(0).toUpperCase()+e.name.slice(1)}function HQ(e,t,n){return e.map(r=>{if(r.id==="api")return{...r,tone:om(t.apiStatus),detail:t.apiStatus.state==="ok"?"Healthy":"Needs attention",meta:t.apiStatus.detail};if(r.id==="worker")return{...r,tone:om(t.workerStatus),detail:t.workerStatus.state==="ok"?"Healthy":"Needs attention",meta:t.workerStatus.detail};const i=n.providerStatuses.filter(f=>f.state==="ready").length,s=n.providerStatuses.length,l=i>0,c=n.providerStatuses.filter(f=>f.state==="ready").map(f=>KQ(f)).join(" · ");return{...r,label:"Providers",tone:l?"positive":"caution",detail:`${i} of ${s} configured`,meta:c||"None configured"}})}function GQ(e,t){if(e.apiStatus.state!=="ok")return"Launch is blocked until the API responds cleanly.";if(e.apiStatus.databaseConfigured===!1)return"Launch is blocked until the API has a database connection configured.";if(e.workerStatus.state!=="ok")return"Launch is blocked until the worker is healthy and heartbeats are current.";if(!t.providerStatuses.some(n=>n.state==="ready"))return"Launch is blocked until at least one provider is configured."}function VQ(e,t,n){const r=GQ(t,n),i=structuredClone(e);return i.healthChecks=i.healthChecks.map(s=>{if(s.id==="api")return{...s,detail:t.apiStatus.detail,state:t.apiStatus.state==="ok"?"ready":"attention"};if(s.id==="worker")return{...s,detail:t.workerStatus.detail,state:t.workerStatus.state==="ok"?"ready":"attention"};const l=n.providerStatuses.some(c=>c.state==="ready");return{...s,detail:l?"At least one provider configured.":"No providers configured.",state:l?"ready":"attention"}}),i.launchState.enabled=r===void 0,i.launchState.blockedReason=r,i.launchState.summary=r??"Queue a visibility sweep first, then follow with a site audit to explain movement.",i}function ZQ({project:e}){return u.jsxs(Dt,{to:"/projects/$projectId",params:{projectId:e.project.id},className:"project-row cursor-pointer",children:[u.jsxs("div",{className:"project-row-primary",children:[u.jsxs("div",{children:[u.jsx("p",{className:"project-name",children:e.project.name}),u.jsx("p",{className:"project-domain",children:e.project.canonicalDomain})]}),u.jsx("p",{className:"project-insight",children:e.insight})]}),u.jsx("div",{className:"project-row-stat",children:u.jsxs("div",{className:"metric-inline-block",children:[u.jsx("p",{className:"metric-inline-label",children:"Answer Visibility"}),u.jsx("p",{className:"metric-inline-value",children:e.visibilityScore}),u.jsx("p",{className:"metric-inline-delta",children:e.visibilityDelta})]})}),u.jsx("div",{className:"project-row-stat",children:u.jsxs("div",{className:"metric-inline-block",children:[u.jsx("p",{className:"metric-inline-label",children:"Competitor Pressure"}),u.jsx("p",{className:"metric-inline-value",children:e.competitorPressureLabel}),u.jsxs("p",{className:"metric-inline-delta",children:[e.lastRun.kindLabel," · ",jg(e.lastRun.status)]})]})}),u.jsx("div",{className:"project-row-chart",children:u.jsx(FQ,{points:e.trend,tone:yR(e.lastRun.status)})}),u.jsx("span",{className:"project-row-link",children:u.jsx(wg,{className:"h-4 w-4 text-zinc-500"})})]})}function YQ(){const e=af(),{dashboard:t,isLoading:n}=sl(),r=t??e?.dashboard;if(!r||n)return u.jsxs("div",{className:"page-skeleton",children:[u.jsxs("div",{className:"page-skeleton-header",children:[u.jsx("div",{className:"skeleton-text h-6 w-32"}),u.jsx("div",{className:"skeleton-text-sm w-64"})]}),u.jsx("div",{className:"space-y-3",children:[1,2,3].map(p=>u.jsxs("div",{className:"rounded-xl border border-zinc-800/60 bg-zinc-900/30 p-4 flex items-center gap-4",children:[u.jsxs("div",{className:"flex-1 space-y-2",children:[u.jsx("div",{className:"skeleton-text w-36"}),u.jsx("div",{className:"skeleton-text-sm w-48"})]}),u.jsx("div",{className:"skeleton-text w-16"}),u.jsx("div",{className:"skeleton-text w-16"}),u.jsx("div",{className:"skeleton h-8 w-20 rounded"})]},p))})]});const i=r.portfolioOverview,c=Mg(!e,e?.health).data??e?.health??{apiStatus:{label:"API",state:"checking",detail:"Checking service health"},workerStatus:{label:"Worker",state:"checking",detail:"Checking service health"}},f=HQ(i.systemHealth,c,r.settings),{openRun:h}=Vc();return u.jsxs("div",{className:"page-container",children:[u.jsxs("div",{className:"page-header",children:[u.jsxs("div",{className:"page-header-left",children:[u.jsx("h1",{className:"page-title",children:"Portfolio"}),u.jsx("p",{className:"page-subtitle",children:"Visibility and execution state across all projects"})]}),u.jsx("div",{className:"page-header-right",children:u.jsx("p",{className:"text-[11px] text-zinc-600",children:i.lastUpdatedAt})})]}),i.projects.length>0?u.jsx("div",{className:"project-list project-list-scrollable",children:i.projects.map(p=>u.jsx(ZQ,{project:p},p.project.id))}):u.jsxs(Ue,{className:"surface-card empty-card",children:[u.jsx("h3",{children:i.emptyState?.title??"No projects yet"}),u.jsx("p",{className:"supporting-copy",children:i.emptyState?.detail}),u.jsx(pe,{size:"sm",asChild:!0,children:u.jsx(Dt,{to:i.emptyState?.ctaHref==="/setup"||!i.emptyState?.ctaHref?"/setup":"/",children:i.emptyState?.ctaLabel??"Launch setup"})})]}),u.jsxs("div",{className:"overview-secondary-grid",children:[i.attentionItems.length>0&&u.jsxs("section",{className:"overview-secondary-section",children:[u.jsx("div",{className:"section-head section-head-inline",children:u.jsxs("div",{children:[u.jsx("p",{className:"eyebrow eyebrow-soft",children:"Needs attention"}),u.jsx("h2",{className:"section-title-sm",children:"What changed"})]})}),u.jsx("div",{className:"attention-list attention-list-scrollable",children:i.attentionItems.map(p=>u.jsxs(Dt,{to:p.href,className:`attention-item attention-item-${p.tone}`,children:[u.jsxs("div",{children:[u.jsx("p",{className:"attention-title",children:p.title}),u.jsx("p",{className:"attention-detail",children:p.detail})]}),u.jsx("span",{className:"attention-action",children:p.actionLabel})]},p.id))})]}),u.jsxs("section",{className:"overview-secondary-section",children:[u.jsx("div",{className:"section-head section-head-inline",children:u.jsxs("div",{children:[u.jsx("p",{className:"eyebrow eyebrow-soft",children:"Recent runs"}),u.jsx("h2",{className:"section-title-sm",children:"Activity"})]})}),u.jsx("div",{className:"compact-stack compact-stack-scrollable",children:i.recentRuns.length>0?i.recentRuns.map(p=>u.jsxs("button",{className:"compact-run",type:"button",onClick:()=>h(p.id),children:[u.jsxs("div",{children:[u.jsx("p",{className:"compact-run-title",children:p.projectName}),u.jsx("p",{className:"compact-run-detail",children:p.summary})]}),u.jsx(Og,{status:p.status})]},p.id)):u.jsx("p",{className:"supporting-copy",children:"Run history appears here after the first launch."})})]})]}),u.jsxs("section",{className:"page-section",children:[u.jsx("div",{className:"section-head section-head-inline",children:u.jsxs("div",{children:[u.jsx("p",{className:"eyebrow eyebrow-soft",children:"System health"}),u.jsx("h2",{className:"section-title-sm",children:"Infrastructure"})]})}),u.jsx("div",{className:"health-grid",children:f.map(p=>u.jsxs(Ue,{className:"surface-card compact-card",children:[u.jsxs("div",{className:"section-head",children:[u.jsxs("div",{children:[u.jsx("p",{className:"eyebrow eyebrow-soft",children:p.label}),u.jsx("h3",{children:p.detail})]}),u.jsx(yt,{tone:p.tone,children:p.label})]}),u.jsx("p",{className:"supporting-copy",children:p.meta})]},p.id))})]})]})}const y1=Symbol.for("yaml.alias"),Aw=Symbol.for("yaml.document"),Es=Symbol.for("yaml.map"),GD=Symbol.for("yaml.pair"),Gi=Symbol.for("yaml.scalar"),Zc=Symbol.for("yaml.seq"),ei=Symbol.for("yaml.node.type"),ol=e=>!!e&&typeof e=="object"&&e[ei]===y1,Rg=e=>!!e&&typeof e=="object"&&e[ei]===Aw,sf=e=>!!e&&typeof e=="object"&&e[ei]===Es,nn=e=>!!e&&typeof e=="object"&&e[ei]===GD,kt=e=>!!e&&typeof e=="object"&&e[ei]===Gi,of=e=>!!e&&typeof e=="object"&&e[ei]===Zc;function en(e){if(e&&typeof e=="object")switch(e[ei]){case Es:case Zc:return!0}return!1}function tn(e){if(e&&typeof e=="object")switch(e[ei]){case y1:case Es:case Gi:case Zc:return!0}return!1}const VD=e=>(kt(e)||en(e))&&!!e.anchor,bo=Symbol("break visit"),WQ=Symbol("skip children"),Nd=Symbol("remove node");function Yc(e,t){const n=QQ(t);Rg(e)?mc(null,e.contents,n,Object.freeze([e]))===Nd&&(e.contents=null):mc(null,e,n,Object.freeze([]))}Yc.BREAK=bo;Yc.SKIP=WQ;Yc.REMOVE=Nd;function mc(e,t,n,r){const i=XQ(e,t,n,r);if(tn(i)||nn(i))return JQ(e,r,i),mc(e,i,n,r);if(typeof i!="symbol"){if(en(t)){r=Object.freeze(r.concat(t));for(let s=0;s<t.items.length;++s){const l=mc(s,t.items[s],n,r);if(typeof l=="number")s=l-1;else{if(l===bo)return bo;l===Nd&&(t.items.splice(s,1),s-=1)}}}else if(nn(t)){r=Object.freeze(r.concat(t));const s=mc("key",t.key,n,r);if(s===bo)return bo;s===Nd&&(t.key=null);const l=mc("value",t.value,n,r);if(l===bo)return bo;l===Nd&&(t.value=null)}}return i}function QQ(e){return typeof e=="object"&&(e.Collection||e.Node||e.Value)?Object.assign({Alias:e.Node,Map:e.Node,Scalar:e.Node,Seq:e.Node},e.Value&&{Map:e.Value,Scalar:e.Value,Seq:e.Value},e.Collection&&{Map:e.Collection,Seq:e.Collection},e):e}function XQ(e,t,n,r){if(typeof n=="function")return n(e,t,r);if(sf(t))return n.Map?.(e,t,r);if(of(t))return n.Seq?.(e,t,r);if(nn(t))return n.Pair?.(e,t,r);if(kt(t))return n.Scalar?.(e,t,r);if(ol(t))return n.Alias?.(e,t,r)}function JQ(e,t,n){const r=t[t.length-1];if(en(r))r.items[e]=n;else if(nn(r))e==="key"?r.key=n:r.value=n;else if(Rg(r))r.contents=n;else{const i=ol(r)?"alias":"scalar";throw new Error(`Cannot replace node with ${i} parent`)}}const eX={"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"},tX=e=>e.replace(/[!,[\]{}]/g,t=>eX[t]);class Qn{constructor(t,n){this.docStart=null,this.docEnd=!1,this.yaml=Object.assign({},Qn.defaultYaml,t),this.tags=Object.assign({},Qn.defaultTags,n)}clone(){const t=new Qn(this.yaml,this.tags);return t.docStart=this.docStart,t}atDocument(){const t=new Qn(this.yaml,this.tags);switch(this.yaml.version){case"1.1":this.atNextDocument=!0;break;case"1.2":this.atNextDocument=!1,this.yaml={explicit:Qn.defaultYaml.explicit,version:"1.2"},this.tags=Object.assign({},Qn.defaultTags);break}return t}add(t,n){this.atNextDocument&&(this.yaml={explicit:Qn.defaultYaml.explicit,version:"1.1"},this.tags=Object.assign({},Qn.defaultTags),this.atNextDocument=!1);const r=t.trim().split(/[ \t]+/),i=r.shift();switch(i){case"%TAG":{if(r.length!==2&&(n(0,"%TAG directive should contain exactly two parts"),r.length<2))return!1;const[s,l]=r;return this.tags[s]=l,!0}case"%YAML":{if(this.yaml.explicit=!0,r.length!==1)return n(0,"%YAML directive should contain exactly one part"),!1;const[s]=r;if(s==="1.1"||s==="1.2")return this.yaml.version=s,!0;{const l=/^\d+\.\d+$/.test(s);return n(6,`Unsupported YAML version ${s}`,l),!1}}default:return n(0,`Unknown directive ${i}`,!0),!1}}tagName(t,n){if(t==="!")return"!";if(t[0]!=="!")return n(`Not a valid tag: ${t}`),null;if(t[1]==="<"){const l=t.slice(2,-1);return l==="!"||l==="!!"?(n(`Verbatim tags aren't resolved, so ${t} is invalid.`),null):(t[t.length-1]!==">"&&n("Verbatim tags must end with a >"),l)}const[,r,i]=t.match(/^(.*!)([^!]*)$/s);i||n(`The ${t} tag has no suffix`);const s=this.tags[r];if(s)try{return s+decodeURIComponent(i)}catch(l){return n(String(l)),null}return r==="!"?t:(n(`Could not resolve tag: ${t}`),null)}tagString(t){for(const[n,r]of Object.entries(this.tags))if(t.startsWith(r))return n+tX(t.substring(r.length));return t[0]==="!"?t:`!<${t}>`}toString(t){const n=this.yaml.explicit?[`%YAML ${this.yaml.version||"1.2"}`]:[],r=Object.entries(this.tags);let i;if(t&&r.length>0&&tn(t.contents)){const s={};Yc(t.contents,(l,c)=>{tn(c)&&c.tag&&(s[c.tag]=!0)}),i=Object.keys(s)}else i=[];for(const[s,l]of r)s==="!!"&&l==="tag:yaml.org,2002:"||(!t||i.some(c=>c.startsWith(l)))&&n.push(`%TAG ${s} ${l}`);return n.join(`
95
+ `),X=[];let Q=[],de=0;const ve=()=>{if(Q.length===0)return;const Z=Q.join(" ").trim();Z&&X.push(u.jsx("p",{className:X.length>0?"mt-2.5":"",children:aE(Z,me)},de++)),Q=[]};for(const Z of W){const le=Z.trim();if(/^[-\u2013\u2014]{3,}$/.test(le)){ve(),X.push(u.jsx("hr",{className:"border-zinc-800/60 my-3"},de++));continue}const Se=le.match(/^(#{1,3})\s+(.+)$/);if(Se){ve();const q=Se[1].length,Ae=Se[2].replace(/^[\p{Emoji}\p{Emoji_Component}\s#]+/u,"").trim()||Se[2],Oe=q===1?"text-[13px] font-semibold text-zinc-100 mt-4 mb-1":q===2?"text-xs font-semibold text-zinc-200 mt-3 mb-0.5":"text-xs font-medium text-zinc-300 mt-2";X.push(u.jsx("p",{className:Oe,children:aE(Ae,me)},de++));continue}if(le===""){ve();continue}Q.push(le)}return ve(),X};return u.jsx(WR,{open:!0,onOpenChange:W=>{W||n()},children:u.jsxs(QR,{children:[u.jsx(s1,{className:"fixed inset-0 z-50 bg-black/80 backdrop-blur-sm"}),u.jsxs(o1,{className:"evidence-modal","aria-describedby":void 0,children:[u.jsxs("div",{className:"evidence-modal-header",children:[u.jsxs("div",{className:"min-w-0 flex-1",children:[u.jsxs("p",{className:"eyebrow eyebrow-soft",children:[t.project.name," ","·"," ",E.provider||"All providers"]}),u.jsx(l1,{className:"text-lg font-semibold text-zinc-50 truncate",children:e.keyword})]}),u.jsxs(JR,{className:"inline-flex size-8 items-center justify-center rounded-md text-zinc-500 transition hover:bg-zinc-800 hover:text-zinc-100 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-zinc-400 shrink-0",children:[u.jsx(Sg,{className:"size-4"}),u.jsx("span",{className:"sr-only",children:"Close"})]})]}),A&&u.jsxs("div",{className:"evidence-modal-timeline",children:[u.jsx("p",{className:"drawer-section-label mb-1.5",children:"Run history"}),u.jsx("div",{className:"flex items-center gap-1 overflow-x-auto pb-1",children:C.map((W,X)=>{const Q=c===-1&&X===C.length-1||c===X,de=W.visibilityState??(W.answerMentioned?"visible":"not-visible"),ve=W.visibilityTransition??de,Z=de==="visible"?"bg-emerald-400":ve==="emerging"?"bg-amber-400":ve==="lost"?"bg-rose-400":"bg-zinc-600",Se=new Date(W.createdAt).toLocaleDateString(void 0,{month:"short",day:"numeric"}),q=!!(W.model&&X>0&&C[X-1]?.model&&C[X-1].model!==W.model);return u.jsxs("button",{type:"button",className:`evidence-run-dot ${Q?"evidence-run-dot--selected":""}`,onClick:()=>ge(X===C.length-1?-1:X),"aria-label":[`Run ${Se}: ${de}`,W.model?`model ${W.model}`:null,q?"model changed":null].filter(Boolean).join(" — "),"aria-pressed":Q,children:[u.jsx("span",{className:`size-2 rounded-full ${Z} ${q?"ring-1 ring-amber-300/80 ring-offset-2 ring-offset-zinc-950":""}`,"aria-hidden":"true"}),u.jsx("span",{className:"text-[10px] text-zinc-500",children:Se})]},X)})}),c>=0&&c<C.length&&u.jsxs("p",{className:"text-[11px] text-zinc-500 mt-1",children:["Viewing run from ",new Date(C[c].createdAt).toLocaleString()," ","—"," ",u.jsx("span",{className:"capitalize",children:C[c].visibilityState??(C[c].answerMentioned?"visible":"not-visible")}),u.jsxs("button",{type:"button",className:"text-zinc-400 hover:text-zinc-200 ml-2",onClick:()=>ge(-1),children:["←"," Back to latest"]})]}),!P&&(e.modelTransitions?.length??0)>0&&u.jsx("div",{className:"mt-2 flex flex-wrap gap-2",children:e.modelTransitions.map(W=>u.jsx("span",{className:"inline-flex items-center rounded-full border border-amber-400/30 bg-amber-400/10 px-2 py-1 text-[10px] text-amber-100",children:`${W.fromModel??"unknown"} -> ${W.toModel??"unknown"} on ${new Date(W.createdAt).toLocaleDateString()}`},`${W.runId}:${W.toModel??"unknown"}`))})]}),u.jsxs("div",{className:"evidence-modal-body",children:[g&&u.jsxs("div",{className:"md:col-span-2 flex items-center justify-center py-12 text-zinc-500 text-sm",children:["Loading historical run data","…"]}),!g&&u.jsxs(u.Fragment,{children:[u.jsxs("div",{className:"evidence-modal-main",children:[u.jsxs("div",{className:`evidence-position-hero evidence-position-hero--${G}`,children:[u.jsx("p",{className:`evidence-position-label evidence-position-label--${G}`,children:H.label}),u.jsx("p",{className:`evidence-position-title evidence-position-title--${G}`,children:H.title}),u.jsx("p",{className:"evidence-position-meta",children:H.meta}),R&&u.jsx("p",{className:"mt-1 text-[11px] text-zinc-500",children:R})]}),E.answerSnippet&&u.jsxs("div",{children:[u.jsx("p",{className:"drawer-section-label",children:"What the AI said"}),u.jsx("div",{className:`answer-snippet-block ${r?"evidence-answer-expanded":"evidence-answer-collapsed"}`,children:oe()}),E.answerSnippet.length>280&&u.jsx("button",{type:"button",className:"mt-1.5 text-xs text-zinc-500 hover:text-zinc-300 transition-colors",onClick:()=>i(!r),children:r?"↑ Collapse":"↓ Show full answer"})]}),!E.answerSnippet&&!g&&u.jsx("div",{className:"rounded-lg border border-zinc-800/40 bg-zinc-900/20 px-4 py-8 text-center text-zinc-600 text-sm",children:"No answer text recorded for this run"}),!P&&e.relatedTechnicalSignals.length>0&&u.jsxs("div",{children:[u.jsx("p",{className:"drawer-section-label",children:D?"Why you're visible":"What to fix"}),u.jsx("div",{className:"action-items-list",children:e.relatedTechnicalSignals.map((W,X)=>u.jsxs("div",{className:"action-item",children:[u.jsx("svg",{className:`action-item-icon ${D?"text-emerald-400":"text-amber-400"}`,viewBox:"0 0 16 16",fill:"none","aria-hidden":"true",children:D?u.jsx("path",{d:"M3 8l3.5 3.5L13 4.5",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"}):u.jsxs(u.Fragment,{children:[u.jsx("circle",{cx:"8",cy:"8",r:"7",stroke:"currentColor",strokeWidth:"1.5"}),u.jsx("path",{d:"M8 5v3.5M8 10.5v0",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round"})]})}),u.jsx("span",{className:"action-item-text",children:W})]},X))})]}),E.summary&&u.jsx("p",{className:"text-xs text-zinc-600 border-t border-zinc-800/40 pt-3 mt-1",children:E.summary})]}),u.jsxs("div",{className:"evidence-modal-sidebar",children:[(K||U)&&u.jsxs("div",{className:"sidebar-tabs",children:[u.jsx("button",{className:`sidebar-tab ${s==="mentions"?"sidebar-tab--active":""}`,onClick:()=>l("mentions"),type:"button",title:"Canonry's answer-level visibility assessment and any company names extracted from the answer text.",children:"Mentions"}),u.jsx("button",{className:`sidebar-tab ${s==="sources"?"sidebar-tab--active":""}`,onClick:()=>l("sources"),type:"button",title:"Grounding links the model used to build the answer. These are supporting sources, not the primary visibility signal.",children:"Sources"})]}),s==="mentions"&&u.jsxs(u.Fragment,{children:[u.jsxs("div",{children:[u.jsxs("div",{className:"drawer-section-label flex items-center",children:[u.jsx("span",{children:"Answer visibility"}),u.jsx(Kn,{text:"Canonry scans the AI answer for your owned domains and project name. This is independent from grounding or citation sources."})]}),u.jsxs("div",{className:`mention-status mention-status--${D?"visible":"not-visible"}`,children:[u.jsx("span",{className:"mention-status-icon",children:z?"…":D?"✓":"—"}),u.jsx("span",{className:"mention-status-label",children:z?"Pending":D?"Visible":"Not visible"})]}),E.matchedTerms.length>0&&u.jsxs("div",{className:"mt-2",children:[u.jsx("p",{className:"text-[10px] uppercase tracking-wide text-zinc-500 mb-1.5",children:"Matched in answer"}),u.jsx("div",{className:"flex flex-wrap gap-1.5",children:E.matchedTerms.map(W=>u.jsx("span",{className:"mention-chip mention-chip--brand",children:W},W))})]}),!z&&!D&&E.matchedTerms.length===0&&u.jsxs("div",{className:"mt-2",children:[u.jsx("p",{className:"text-[10px] uppercase tracking-wide text-zinc-500 mb-1.5",children:"Searched for"}),u.jsx("div",{className:"flex flex-wrap gap-1.5",children:ae.map(W=>u.jsx("span",{className:"mention-chip mention-chip--muted",children:W},W))}),u.jsx("p",{className:"text-[11px] text-zinc-600 mt-1.5",children:"None of these appear in the answer text."})]})]}),(E.recommendedCompetitors.length>0||E.competitorDomains.length>0)&&u.jsxs("div",{children:[u.jsxs("div",{className:"drawer-section-label flex items-center",children:[u.jsx("span",{children:"Competitors in answer"}),u.jsx(Kn,{text:"Competitors detected in the answer text or cited source links. Includes both tracked competitors and names extracted by Canonry."})]}),u.jsx("div",{className:"flex flex-wrap gap-1.5",children:(()=>{const W=E.competitorDomains.map(de=>de.replace(/^www\./,"")),X=new Set(W.map(de=>iE(de.replace(/\.[^.]+$/,""))));return[...E.recommendedCompetitors.filter(de=>!X.has(iE(de))),...W].map(de=>u.jsx("span",{className:"mention-chip mention-chip--competitor",children:de},de))})()})]})]}),s==="sources"&&u.jsxs(u.Fragment,{children:[E.citedDomains.length>0&&u.jsxs("div",{children:[u.jsxs("div",{className:"drawer-section-label flex items-center",children:[u.jsx("span",{children:"Domains from source links"}),u.jsx(Kn,{text:"These domains were extracted from grounding or citation URLs. They are supporting-source metadata, not proof that the answer text mentioned them."})]}),u.jsx("div",{className:"citation-leaderboard",children:E.citedDomains.map((W,X)=>{const Q=W.toLowerCase().replace(/^www\./,""),de=N.has(Q),ve=!de&&E.competitorDomains.some(le=>le.toLowerCase().replace(/^www\./,"")===Q),Z=de?"you":ve?"competitor":"other";return u.jsxs("div",{className:`citation-leaderboard-item citation-leaderboard-item--${Z}`,children:[u.jsxs("span",{className:"citation-leaderboard-rank",children:["#",X+1]}),u.jsx("span",{className:"citation-leaderboard-domain",children:W}),de&&u.jsx("span",{className:"citation-leaderboard-tag",children:"You"}),ve&&u.jsx("span",{className:"citation-leaderboard-tag",children:"Competitor"})]},W)})})]}),E.groundingSources.length>0&&u.jsxs("div",{children:[u.jsxs("div",{className:"drawer-section-label flex items-center",children:[u.jsxs("span",{children:["Grounding source links (",E.groundingSources.length,")"]}),u.jsx(Kn,{text:"Links the model used as grounding or supporting context while producing the answer. These are not the same thing as answer visibility."})]}),u.jsx("ul",{className:"grid gap-0.5",children:E.groundingSources.map((W,X)=>u.jsx("li",{className:"truncate text-sm",children:u.jsx("a",{href:W.uri,target:"_blank",rel:"noopener noreferrer",className:"text-zinc-400 hover:text-zinc-200 transition-colors",children:W.title||W.uri})},X))})]}),E.evidenceUrls.length>0&&u.jsxs("div",{children:[u.jsx("p",{className:"drawer-section-label",children:"Evidence URLs"}),u.jsx("ul",{className:"grid gap-1",children:E.evidenceUrls.map(W=>u.jsx("li",{className:"truncate text-sm",children:u.jsx("a",{href:W,target:"_blank",rel:"noopener noreferrer",className:"text-zinc-400 hover:text-zinc-200 transition-colors",children:W})},W))})]}),E.citedDomains.length===0&&E.groundingSources.length===0&&E.evidenceUrls.length===0&&u.jsxs("div",{className:"flex items-center justify-center h-24 text-zinc-600 text-sm",children:["No source data ",P?"for this run":"yet"]})]}),!K&&!U&&u.jsxs("div",{className:"flex items-center justify-center h-24 text-zinc-600 text-sm",children:["No answer visibility data ",P?"for this run":"yet"]})]})]})]})]})]})})}function pi(e){const t=new Date("2026-02-20");return e.map((n,r)=>({runId:`run_mock_${r+1}`,citationState:n,createdAt:new Date(t.getTime()+r*2*24*60*60*1e3).toISOString()}))}const yb=[{id:"project_citypoint",name:"Citypoint Dental NYC",canonicalDomain:"citypointdental.com",ownedDomains:[],country:"US",language:"en",tags:["local intent","priority"],labels:{},locations:[],defaultLocation:null,configSource:"cli",configRevision:1},{id:"project_harbor",name:"Harbor Legal Group",canonicalDomain:"harborlegal.com",ownedDomains:[],country:"US",language:"en",tags:["lead gen"],labels:{},locations:[],defaultLocation:null,configSource:"cli",configRevision:1},{id:"project_northstar",name:"Northstar Orthopedics",canonicalDomain:"northstarortho.com",ownedDomains:[],country:"US",language:"en",tags:["multi-location"],labels:{},locations:[],defaultLocation:null,configSource:"cli",configRevision:1}];function zg(e){return{id:e.id,projectId:e.projectId,projectName:e.projectName,kind:e.kind,kindLabel:e.kindLabel,status:e.status,trigger:e.trigger??"manual",createdAt:e.createdAt,startedAt:e.startedAt,duration:e.duration,statusDetail:e.statusDetail,summary:e.summary,triggerLabel:e.triggerLabel}}const YW=zg({id:"run_citypoint_visibility_20260308",projectId:"project_citypoint",projectName:"Citypoint Dental NYC",kind:"answer-visibility",kindLabel:"Answer visibility sweep",status:"completed",createdAt:"2026-03-08T12:15:00.000Z",startedAt:"Mar 8, 12:15 PM",duration:"6m 12s",statusDetail:"18 tracked queries checked; 3 citation losses detected on emergency-intent prompts.",summary:"Citation losses on emergency-intent prompts",triggerLabel:"Scheduled"}),WW=zg({id:"run_citypoint_queued_20260309",projectId:"project_citypoint",projectName:"Citypoint Dental NYC",kind:"answer-visibility",kindLabel:"Answer visibility sweep",status:"queued",createdAt:"2026-03-09T08:05:00.000Z",startedAt:"Mar 9, 8:05 AM",duration:"Waiting for slot",statusDetail:"Ready to enqueue after the next provider rate window clears.",summary:"Queued follow-up after local ranking movement",triggerLabel:"Manual"}),QW=zg({id:"run_harbor_visibility_20260308",projectId:"project_harbor",projectName:"Harbor Legal Group",kind:"answer-visibility",kindLabel:"Answer visibility sweep",status:"completed",createdAt:"2026-03-08T11:05:00.000Z",startedAt:"Mar 8, 11:05 AM",duration:"5m 07s",statusDetail:"12 tracked queries checked; local-intent visibility held steady across branded prompts.",summary:"Branded prompts remain stable",triggerLabel:"Scheduled"}),XW=zg({id:"run_northstar_visibility_20260308",projectId:"project_northstar",projectName:"Northstar Orthopedics",kind:"answer-visibility",kindLabel:"Answer visibility sweep",status:"running",createdAt:"2026-03-08T13:40:00.000Z",startedAt:"Mar 8, 1:40 PM",duration:"3m 10s",statusDetail:"Provider responses still in flight for 9 multi-location prompts.",summary:"Mid-run on treatment-location prompts",triggerLabel:"Manual"}),JW=[{id:"evidence_citypoint_emergency_gemini",keyword:"emergency dentist brooklyn",provider:"gemini",model:"gemini-3-flash",location:null,citationState:"lost",changeLabel:"Lost since Mar 5",answerSnippet:"For urgent dental care in Brooklyn, Downtown Smiles and Harbor Dental are now cited first for emergency availability and same-day booking.",citedDomains:["downtownsmiles.com","harbordental.com"],evidenceUrls:["https://downtownsmiles.com/emergency-dentist-brooklyn","https://harbordental.com/same-day-emergency-care"],competitorDomains:["downtownsmiles.com","harbordental.com"],groundingSources:[],relatedTechnicalSignals:["FAQ schema missing on the emergency service page","llms.txt not found during latest site audit","Location pages link weakly into the emergency care hub"],summary:"AI answers now cite two competitors while your emergency page is no longer grounded.",runHistory:pi(["cited","cited","cited","cited","cited","cited","cited","not-cited","not-cited"])},{id:"evidence_citypoint_emergency_openai",keyword:"emergency dentist brooklyn",provider:"openai",model:"gpt-5.4",location:null,citationState:"cited",changeLabel:"Cited for 6 runs",answerSnippet:"Citypoint Dental is listed as a top emergency dentist in Brooklyn for same-day appointments and walk-in availability.",citedDomains:["citypointdental.com","downtownsmiles.com"],evidenceUrls:["https://citypointdental.com/emergency-dentist-brooklyn"],competitorDomains:["downtownsmiles.com"],groundingSources:[],relatedTechnicalSignals:["Emergency page indexed with structured data"],summary:"OpenAI cites your emergency page consistently alongside one competitor.",runHistory:pi(["not-cited","cited","cited","cited","cited","cited","cited"])},{id:"evidence_citypoint_emergency_claude",keyword:"emergency dentist brooklyn",provider:"claude",model:"claude-sonnet-4-6",location:null,citationState:"not-cited",changeLabel:"No citation across 12 runs",answerSnippet:"Based on the search results, top-rated emergency dental practices in Brooklyn include Downtown Smiles and Harbor Dental.",citedDomains:["downtownsmiles.com","harbordental.com"],evidenceUrls:[],competitorDomains:["downtownsmiles.com","harbordental.com"],groundingSources:[],relatedTechnicalSignals:["FAQ schema missing","llms.txt not found"],summary:"Claude does not cite your domain for this emergency query.",runHistory:pi(["not-cited","not-cited","not-cited","not-cited","not-cited","not-cited","not-cited","not-cited","not-cited","not-cited","not-cited","not-cited"])},{id:"evidence_citypoint_invisalign_openai",keyword:"best invisalign dentist downtown brooklyn",provider:"openai",model:"gpt-5.4",location:null,citationState:"emerging",changeLabel:"First citation in 7 days",answerSnippet:"Citypoint Dental appears as an emerging recommendation for Invisalign in Downtown Brooklyn, supported by recent before-and-after case pages.",citedDomains:["citypointdental.com","clearlineortho.com"],evidenceUrls:["https://citypointdental.com/invisalign-downtown-brooklyn","https://citypointdental.com/case-studies/invisalign-open-bite"],competitorDomains:["clearlineortho.com"],groundingSources:[],relatedTechnicalSignals:["Structured data now present on two case-study pages","Internal links from service pages to case studies improved crawl depth"],summary:"Fresh case-study content is starting to earn citations on Invisalign prompts.",runHistory:pi(["not-cited","not-cited","not-cited","not-cited","not-cited","not-cited","cited"])},{id:"evidence_citypoint_invisalign_gemini",keyword:"best invisalign dentist downtown brooklyn",provider:"gemini",model:"gemini-3-flash",location:null,citationState:"cited",changeLabel:"Cited for 8 runs",answerSnippet:"Citypoint Dental in Downtown Brooklyn is highlighted for its Invisalign expertise and patient outcomes.",citedDomains:["citypointdental.com"],evidenceUrls:["https://citypointdental.com/invisalign-downtown-brooklyn"],competitorDomains:[],groundingSources:[],relatedTechnicalSignals:["Case study pages well-indexed"],summary:"Gemini consistently cites your Invisalign page with no competitor overlap.",runHistory:pi(["cited","cited","cited","cited","cited","cited","cited","cited"])},{id:"evidence_citypoint_invisalign_claude",keyword:"best invisalign dentist downtown brooklyn",provider:"claude",model:"claude-sonnet-4-6",location:null,citationState:"not-cited",changeLabel:"No citation across 12 runs",answerSnippet:"For Invisalign in Downtown Brooklyn, Clear Line Ortho and Brooklyn Smiles are frequently recommended for their experienced orthodontists.",citedDomains:["clearlineortho.com","brooklynsmiles.com"],evidenceUrls:[],competitorDomains:["clearlineortho.com"],groundingSources:[],relatedTechnicalSignals:["No before/after schema on case study pages"],summary:"Claude does not surface your Invisalign content despite strong page quality.",runHistory:pi(["not-cited","not-cited","not-cited","not-cited","not-cited","not-cited","not-cited","not-cited","not-cited","not-cited","not-cited","not-cited"])},{id:"evidence_citypoint_children_claude",keyword:"pediatric dentist brooklyn heights",provider:"claude",model:"claude-sonnet-4-6",location:null,citationState:"not-cited",changeLabel:"No citation across 4 runs",answerSnippet:"Answers cite neighborhood-specific pediatric practices with stronger family-focused FAQ content and clearer insurance details.",citedDomains:["brightkidsdental.com","parkpediatricdental.com"],evidenceUrls:["https://brightkidsdental.com/pediatric-dentist-brooklyn-heights","https://parkpediatricdental.com/insurance"],competitorDomains:["brightkidsdental.com","parkpediatricdental.com"],groundingSources:[],relatedTechnicalSignals:["No dedicated pediatric service page exists for Brooklyn Heights","Insurance content is buried three clicks deep"],summary:"Coverage gap is content-driven, not purely technical.",runHistory:pi(["not-cited","not-cited","not-cited","not-cited"])},{id:"evidence_citypoint_children_gemini",keyword:"pediatric dentist brooklyn heights",provider:"gemini",model:"gemini-3-flash",location:null,citationState:"not-cited",changeLabel:"No citation across 12 runs",answerSnippet:"For pediatric dentistry in Brooklyn Heights, Bright Kids Dental and Park Pediatric Dental are cited for family-friendly care.",citedDomains:["brightkidsdental.com","parkpediatricdental.com"],evidenceUrls:[],competitorDomains:["brightkidsdental.com","parkpediatricdental.com"],groundingSources:[],relatedTechnicalSignals:["No dedicated pediatric page for Brooklyn Heights"],summary:"Gemini does not surface your domain for pediatric queries in this area.",runHistory:pi(["not-cited","not-cited","not-cited","not-cited","not-cited","not-cited","not-cited","not-cited","not-cited","not-cited","not-cited","not-cited"])},{id:"evidence_citypoint_children_openai",keyword:"pediatric dentist brooklyn heights",provider:"openai",model:"gpt-5.4",location:null,citationState:"cited",changeLabel:"First citation this month",answerSnippet:"Citypoint Dental is mentioned as offering pediatric services in Brooklyn, though specialized pediatric-only practices are also highlighted.",citedDomains:["citypointdental.com","brightkidsdental.com"],evidenceUrls:["https://citypointdental.com/family-dentistry"],competitorDomains:["brightkidsdental.com"],groundingSources:[],relatedTechnicalSignals:["Family dentistry page recently updated"],summary:"OpenAI recently started citing your family dentistry page for this query.",runHistory:pi(["not-cited","not-cited","not-cited","not-cited","not-cited","cited"])}];yb[0],yb[1],pi(["cited","cited","cited","cited","cited"]),yb[2],2/7,pi(["not-cited","not-cited","not-cited","cited"]);function eQ(e,t){return e.projects.find(n=>n.project.id===t)}function tQ(e,t){return e.runs.find(n=>n.id===t)}function nQ(e,t){for(const n of e.projects){const r=n.visibilityEvidence.find(i=>i.id===t);if(r)return{project:n,evidence:r}}}function UD(e){return{id:e.id,name:e.name,displayName:e.displayName,canonicalDomain:e.canonicalDomain,ownedDomains:e.ownedDomains??[],country:e.country,language:e.language,tags:e.tags,labels:e.labels,locations:e.locations??[],defaultLocation:e.defaultLocation??null,configSource:e.configSource,configRevision:e.configRevision,createdAt:e.createdAt,updatedAt:e.updatedAt}}function sE(e){try{return new Date(e).toLocaleDateString("en-US",{month:"short",day:"numeric",hour:"numeric",minute:"2-digit"})}catch{return e}}function rQ(e,t){if(!e)return"Waiting";if(!t)return"Running";const n=new Date(t).getTime()-new Date(e).getTime();if(n<1e3)return"<1s";const r=Math.floor(n/1e3);if(r<60)return`${r}s`;const i=Math.floor(r/60),s=r%60;return`${i}m ${s}s`}function BD(e){return e==="answer-visibility"?"Answer visibility sweep":e}function iQ(e){return e==="manual"?"Manual":e==="scheduled"?"Scheduled":e==="config-apply"?"Config apply":e}function v1(e,t){return{id:e.id,projectId:e.projectId,projectName:t,kind:e.kind,kindLabel:BD(e.kind),status:e.status,trigger:e.trigger??"manual",location:e.location??null,createdAt:e.createdAt,startedAt:e.startedAt?sE(e.startedAt):sE(e.createdAt),duration:rQ(e.startedAt,e.finishedAt),statusDetail:e.error?qD(e.error):aQ(e),summary:sQ(e),triggerLabel:iQ(e.trigger)}}function qD(e){try{const n=JSON.parse(e);if(typeof n=="object"&&n!==null){const r=n.message??n.error?.message??n[0]?.error?.message;if(typeof r=="string"&&r.length>0)return r.length>200?r.slice(0,200)+"…":r}}catch{}const t=e.match(/\[.*?\]\s*(.+)/);if(t){const n=t[1];return n.length>200?n.slice(0,200)+"…":n}return e.length>200?e.slice(0,200)+"…":e}function aQ(e){switch(e.status){case"queued":return"Waiting for execution slot.";case"running":return"Provider queries in progress.";case"completed":return"All key phrases checked.";case"partial":return"Run completed with some key phrases skipped.";case"failed":return e.error?qD(e.error):"Run failed.";default:return""}}function sQ(e){switch(e.status){case"queued":return"Queued for execution";case"running":return"In progress";case"completed":return"Visibility sweep completed";case"partial":return"Partial completion";case"failed":return"Run failed";default:return e.status}}function FD(e){if(e.length===0)return{score:0,citedCount:0,totalCount:0};const t=new Map;for(const s of e){const l=s.keyword??s.id;t.has(l)||t.set(l,!1),s.citationState==="cited"&&t.set(l,!0)}const n=t.size,r=[...t.values()].filter(Boolean).length;return{score:n>0?Math.round(r/n*100):0,citedCount:r,totalCount:n}}function oQ(e){return e>=70?"positive":e>=40?"caution":"negative"}function lQ(e){return e==="High"?"negative":e==="Moderate"?"caution":"neutral"}function cQ(e,t){return e===0?"positive":(t>0?e/t:0)>=.3?"negative":"caution"}function uQ(e){if(e.length===0)return{label:"Gap Key Phrases",value:"No data",delta:"Run a sweep first",tone:"neutral",description:"Run a visibility sweep to identify key phrases where competitors are cited and your domain is not.",tooltip:"Tracked key phrases where a competitor is cited in the latest run but your domain is not.",trend:[]};const t=new Map;for(const s of e){const l=s.keywordId,c=t.get(l)??{cited:!1,competitorOverlap:new Set};s.citationState==="cited"&&(c.cited=!0);for(const f of s.competitorOverlap)c.competitorOverlap.add(f);t.set(l,c)}const n=t.size,r=[...t.values()].filter(s=>!s.cited&&s.competitorOverlap.size>0).length,i=r===1?"key phrase":"key phrases";return{label:"Gap Key Phrases",value:`${r}`,delta:`${r} of ${n} key phrases at risk`,tone:cQ(r,n),description:r>0?`${r} tracked ${i} currently cite competitors without citing your domain.`:"No competitive key phrase gaps detected in the latest visibility run.",tooltip:"Tracked key phrases where a competitor is cited in the latest run but your domain is not.",trend:[],progress:n>0?r/n:0}}function dQ(e,t){return e&&e.summary.total>0?{provider:"Google",...e.summary}:t&&t.summary.total>0?{provider:"Bing",...t.summary,deindexed:0}:e?{provider:"Google",...e.summary}:t?{provider:"Bing",...t.summary,deindexed:0}:null}function fQ(e){return e.provider==="Google"&&e.deindexed>0?"negative":e.percentage>=90?"positive":e.percentage>=70?"caution":"negative"}function hQ(e,t){const n=dQ(e,t);if(!n||n.total===0)return{label:"Index Coverage",value:"No data",delta:"Connect GSC or Bing",tone:"neutral",description:"Connect Google Search Console or Bing Webmaster Tools and inspect your sitemap to populate coverage.",tooltip:"Percentage of inspected URLs currently indexed. Google Search Console is preferred when available, otherwise Bing Webmaster Tools is used.",trend:[]};const r=n.notIndexed===1?"URL is":"URLs are",i=n.deindexed===1?"URL":"URLs";return{label:"Index Coverage",value:`${Math.round(n.percentage)}`,delta:`${n.provider} · ${n.indexed} of ${n.total} indexed`,tone:fQ(n),description:n.provider==="Google"&&n.deindexed>0?`${n.deindexed} deindexed ${i} detected in the latest Google Search Console inspection.`:`${n.notIndexed} ${r} not indexed in ${n.provider==="Google"?"Google Search Console":"Bing Webmaster Tools"}.`,tooltip:"Percentage of inspected URLs currently indexed. Google Search Console is preferred when available, otherwise Bing Webmaster Tools is used.",trend:[]}}function KD(e,t){if(e.length===0||t.length===0)return{label:"None",count:0};const n=new Set(t);let r=0;for(const s of e)s.competitorOverlap.some(l=>n.has(l))&&r++;const i=r/e.length;return i>=.5?{label:"High",count:r}:i>=.2?{label:"Moderate",count:r}:{label:"Low",count:r}}function pQ(e,t,n,r){const i=[];let s=0;const l=new Set;if(n){const c=new Map;for(const v of n.snapshots)if(v.keyword){const y=`${v.keyword}::${v.provider}`;c.set(y,v)}const f=new Set(n.snapshots.map(v=>v.provider)),h=new Set(t.flatMap(v=>Object.keys(v.providerRuns??{}))),p=[...new Set([...f,...h])].sort(),g=p.length>0?p:["gemini"];for(const v of t){if(v.runs.length===0)continue;l.add(v.keyword);const y=v.runs.at(-1),S=y?.transition??"not-cited";for(const w of g){const N=c.get(`${v.keyword}::${w}`),C=(v.providerRuns?.[w]?.length??0)>0;if(!N&&!C)continue;const A=N?.model??null,k=A?`${w}:${A}`:null,O=k?v.modelRuns?.[k]:void 0,T=v.providerRuns?.[w],P=(T?.length?T:null)??(O?.length?O:null),E=T?.length?"provider":O?.length?"model":"keyword",z=P?P.at(-1).transition:S,D=P?P.at(-1).visibilityTransition??(P.at(-1).visibilityState==="visible"?"visible":"not-visible"):y?.visibilityTransition??(y?.visibilityState==="visible"?"visible":"not-visible"),K=P?.at(-1)?.citationState,U=P?.at(-1)?.visibilityState,L=N?z==="lost"?"lost":z==="emerging"?"emerging":N.citationState==="cited"?"cited":"not-cited":K==="cited"?"cited":"not-cited",ae=N?.visibilityState??(U==="visible"?"visible":U==="pending"?"pending":"not-visible"),ye=Nw(P||v.runs),me=oE(P||v.runs),G=mQ(v,w),re=(P??v.runs).map(R=>({runId:R.runId,citationState:R.citationState,createdAt:R.createdAt,model:G.get(R.runId)??null,answerMentioned:R.answerMentioned,visibilityState:R.visibilityState,visibilityTransition:R.visibilityTransition})),ge=gQ(re),we=E==="provider"&&ge.length<=1?"model":E,B=vQ(re);i.push({id:`evidence_${e}_${s++}`,keyword:v.keyword,provider:N?.provider??w,model:N?.model??null,location:N?.location??null,citationState:L,answerMentioned:N?.answerMentioned,visibilityState:ae,visibilityChangeLabel:lE(D,me,{positive:"visible",negative:"not visible",first:"first visibility"}),changeLabel:lE(z,ye),answerSnippet:N?.answerText??"",citedDomains:N?.citedDomains??[],evidenceUrls:[],competitorDomains:N?.competitorOverlap??[],recommendedCompetitors:N?.recommendedCompetitors??[],matchedTerms:N?.matchedTerms??[],relatedTechnicalSignals:[],groundingSources:N?.groundingSources??[],summary:yQ(ae,D,v.keyword),runHistory:re,historyScope:we,modelsSeen:ge,modelTransitions:B})}}}for(const c of r)l.has(c.keyword)||i.push({id:`evidence_${e}_${s++}`,keyword:c.keyword,provider:"",model:null,location:null,citationState:"pending",visibilityState:"pending",visibilityChangeLabel:"Awaiting first run",changeLabel:"Awaiting first run",answerSnippet:"",citedDomains:[],evidenceUrls:[],competitorDomains:[],recommendedCompetitors:[],matchedTerms:[],relatedTechnicalSignals:[],groundingSources:[],summary:`"${c.keyword}" has been added but no visibility run has been triggered yet.`,runHistory:[],historyScope:"keyword",modelsSeen:[],modelTransitions:[]});return i}function mQ(e,t){const n=new Map,r=`${t}:`;for(const[i,s]of Object.entries(e.modelRuns??{})){if(!i.startsWith(r))continue;const l=i.slice(r.length),c=l==="unknown"?null:l;for(const f of s)n.set(f.runId,c)}return n}function gQ(e){const t=new Set;for(const n of e)n.model&&t.add(n.model);return[...t]}function vQ(e){const t=[];let n=null;for(const r of e){const i=r.model??null;i!==n&&n!==null&&t.push({runId:r.runId,createdAt:r.createdAt,fromModel:n,toModel:i}),n=i}return t}function Nw(e){if(e.length===0)return 0;const t=e[e.length-1].citationState;let n=0;for(let r=e.length-1;r>=0&&e[r].citationState===t;r--)n++;return n}function oE(e){if(e.length===0)return 0;const t=e[e.length-1].visibilityState??"not-visible";let n=0;for(let r=e.length-1;r>=0&&(e[r].visibilityState??"not-visible")===t;r--)n++;return n}function lE(e,t,n){const r={positive:n?.positive??"cited",negative:n?.negative??"not cited",first:n?.first??"first citation"};switch(e){case"new":return"First observation";case"cited":case"visible":return t<=1?`${id(r.positive)} in latest run`:`${id(r.positive)} for ${t} runs`;case"lost":return"Lost since last run";case"emerging":return id(r.first);case"not-cited":case"not-visible":return t<=1?`${id(r.negative)} in latest run`:`${id(r.negative)} across ${t} runs`;default:return e}}function id(e){return e.charAt(0).toUpperCase()+e.slice(1)}function yQ(e,t,n){switch(t){case"lost":return`Visibility was lost for "${n}". Your brand no longer appeared in the latest answer.`;case"emerging":return`Your brand started appearing in AI answers for "${n}".`}switch(e){case"visible":return`Your brand or domain is visible in AI answers for "${n}".`;case"pending":return`"${n}" has been added but no visibility run has been triggered yet.`;default:return`Your brand or domain was not mentioned in AI answers for "${n}".`}}function cE(e,t){const n=new Set(t),r=new Map;for(const i of e)if(i.keyword)for(const s of i.competitorOverlap){if(!n.has(s))continue;const l=r.get(s)??new Set;l.add(i.keyword),r.set(s,l)}return r}const bb=3;function bQ(e){const{evidence:t,timeline:n,latestSnapshots:r,previousSnapshots:i,trackedCompetitors:s}=e,l=[],c=[],f=new Set;for(const C of t)C.citationState==="lost"&&(f.has(C.keyword)||(f.add(C.keyword),c.push({keyword:C.keyword,evidenceId:C.id,provider:C.provider,citationState:"lost"})));c.length>0&&l.push({id:"insight_lost",tone:"negative",title:`Lost citation on ${c.length} key phrase${c.length>1?"s":""}`,detail:"Citations dropped since the last run.",actionLabel:"Lost",affectedPhrases:c});const h=cE(r,s),p=cE(i,s);for(const C of s){const A=h.get(C)??new Set,k=p.get(C)??new Set,O=[...A].filter(T=>!k.has(T));O.length>0&&l.push({id:`insight_comp_gained_${C}`,tone:"negative",title:`${C} appeared on ${O.length} key phrase${O.length>1?"s":""}`,detail:"A tracked competitor gained new citations.",actionLabel:"Competitor",affectedPhrases:O.map(T=>{const P=t.find(E=>E.keyword===T);return{keyword:T,evidenceId:P?.id??"",citationState:"cited"}})})}const g=new Map;for(const C of n){const A=C.runs.at(-1);A&&g.set(C.keyword,{transition:A.transition,citationState:A.citationState})}const v=[],y=[],S=new Set;for(const[C,{transition:A,citationState:k}]of g){if(!(A==="emerging"||A==="new"&&k==="cited"))continue;S.add(C);const T=t.find(P=>P.keyword===C&&(P.citationState==="emerging"||P.citationState==="cited"));v.push({keyword:C,evidenceId:T?.id??"",provider:T?.provider,citationState:"emerging"})}for(const C of t)C.citationState==="emerging"&&(S.has(C.keyword)||y.push({keyword:C.keyword,evidenceId:C.id,provider:C.provider,citationState:"emerging"}));if(y.length>0){const C=new Set(y.map(A=>A.keyword)).size;l.push({id:"insight_provider_pickup",tone:"positive",title:`Picked up by new provider on ${C} key phrase${C>1?"s":""}`,detail:"Your domain started appearing on additional providers.",actionLabel:"Pickup",affectedPhrases:y})}v.length>0&&l.push({id:"insight_first_citation",tone:"positive",title:`First citation on ${S.size} key phrase${S.size>1?"s":""}`,detail:"Your domain appeared in AI answers for the first time.",actionLabel:"New",affectedPhrases:v});const w=new Set(t.map(C=>C.keyword)),N=[];for(const C of n){if(!w.has(C.keyword)||C.runs.length<bb||C.runs.at(-1)?.citationState!=="not-cited")continue;if(Nw(C.runs)>=bb){const O=t.find(T=>T.keyword===C.keyword);N.push({keyword:C.keyword,evidenceId:O?.id??"",citationState:"not-cited"})}}N.length>0&&l.push({id:"insight_persistent_gap",tone:"caution",title:`${N.length} key phrase${N.length>1?"s":""} uncited for ${bb}+ runs`,detail:"These key phrases have not been cited by any provider across multiple consecutive runs.",actionLabel:"Gap",affectedPhrases:N});for(const C of s){const A=h.get(C)??new Set,O=[...p.get(C)??new Set].filter(T=>!A.has(T));O.length>0&&l.push({id:`insight_comp_lost_${C}`,tone:"neutral",title:`${C} dropped from ${O.length} key phrase${O.length>1?"s":""}`,detail:"A tracked competitor lost citations.",actionLabel:"Competitor",affectedPhrases:O.map(T=>{const P=t.find(E=>E.keyword===T);return{keyword:T,evidenceId:P?.id??"",citationState:"not-cited"}})})}return l.length===0&&l.push({id:"insight_stable",tone:"neutral",title:"No significant changes",detail:"Citation state is stable across all tracked key phrases.",actionLabel:"Stable",affectedPhrases:[]}),l}function xQ(e,t){if(t.length===0){const f=new Set(e.filter(h=>h.citationState==="cited").map(h=>h.keyword)).size;return{gained:f,lost:0,tone:f>0?"positive":"neutral",hasPreviousRun:!1}}const n=f=>{const h=new Set;for(const p of f)p.citationState==="cited"&&p.keyword&&h.add(p.keyword);return h},r=n(e),i=n(t);let s=0,l=0;for(const f of r)i.has(f)||s++;for(const f of i)r.has(f)||l++;const c=l>s?"negative":s>l?"positive":"neutral";return{gained:s,lost:l,tone:c,hasPreviousRun:!0}}function wQ(e){const t=e[0];if(!t)return{label:"Run Status",value:"None",delta:"No runs yet",tone:"neutral",description:"Trigger a visibility sweep to start tracking.",tooltip:"Current execution state of visibility sweeps. Shows the status of the most recent run and total run count.",trend:[]};const n=t.status==="completed"?"Healthy":t.status==="running"?"Running":t.status==="queued"?"Queued":t.status==="partial"?"Partial":"Failed",r=t.status==="completed"?"positive":t.status==="failed"?"negative":t.status==="partial"?"caution":"neutral";return{label:"Run Status",value:n,delta:`${e.length} total runs`,tone:r,description:`Latest: ${BD(t.kind)} — ${t.status}`,tooltip:"Current execution state of visibility sweeps. Shows the status of the most recent run and total run count.",trend:[]}}function SQ(e){const t=UD(e.project),n=pQ(t.name,e.timeline,e.latestRunDetail,e.keywords),r=e.latestRunDetail?.snapshots??[],i=FD(r),s=uQ(r),l=hQ(e.gscCoverage,e.bingCoverage),c=KD(r,e.competitors.map(y=>y.domain)),f=bQ({evidence:n,timeline:e.timeline,latestSnapshots:e.latestRunDetail?.snapshots??[],previousSnapshots:e.previousRunDetail?.snapshots??[],trackedCompetitors:e.competitors.map(y=>y.domain)}),h=[...e.runs].sort((y,S)=>S.createdAt.localeCompare(y.createdAt)),p=h.map(y=>v1(y,e.project.displayName||e.project.name)),g=new Map;for(const y of r){const S=y.provider||"gemini",w=y.model??null,N=`${S}::${w??"unknown"}`,C=g.get(N)??{provider:S,model:w,cited:0,total:0};C.total++,y.citationState==="cited"&&C.cited++,g.set(N,C)}const v=[...g.values()].sort((y,S)=>y.provider.localeCompare(S.provider)||(y.model??"").localeCompare(S.model??"")).map(({provider:y,model:S,cited:w,total:N})=>({provider:y,model:S,score:N>0?Math.round(w/N*100):0,cited:w,total:N}));return{project:t,dateRangeLabel:"All time",contextLabel:`${t.country} / ${t.language.toUpperCase()}`,visibilitySummary:{label:"Answer Visibility",value:r.length>0?`${i.score}`:"No data",delta:r.length>0?`${i.citedCount} of ${i.totalCount} key phrases visible`:"Run a sweep first",tone:r.length>0?oQ(i.score):"neutral",description:r.length>0?`${i.citedCount} of ${i.totalCount} tracked key phrases found your domain in at least one AI answer engine.`:"No visibility data yet. Trigger a run to start tracking.",tooltip:'Percentage of tracked key phrases where your domain is cited by at least one AI answer engine. A key phrase is "visible" if any configured provider includes your site in its response.',trend:[]},keywordCounts:{cited:i.citedCount,total:i.totalCount},gapKeyPhrases:s,indexCoverage:l,providerScores:v,competitorPressure:{label:"Competitor Pressure",value:c.label,delta:c.count>0?`${c.count} overlapping citations`:"No overlap detected",tone:lQ(c.label),description:e.competitors.length>0?`${e.competitors.length} competitor${e.competitors.length>1?"s":""} tracked.`:"No competitors configured.",tooltip:"How often competitor domains appear alongside yours in AI answers. High pressure means competitors are frequently cited for the same key phrases.",trend:[]},runStatus:wQ(h),movementSummary:xQ(e.latestRunDetail?.snapshots??[],e.previousRunDetail?.snapshots??[]),insights:f,visibilityEvidence:n,competitors:e.competitors.map((y,S)=>{const w=new Set;for(const O of r)(O.competitorOverlap.includes(y.domain)||O.citedDomains.includes(y.domain))&&O.keyword&&w.add(O.keyword);const N=[...w],C=new Set(r.map(O=>O.keyword).filter(Boolean)),A=C.size>0?N.length/C.size:0,k=A>=.5?"High":A>=.2?"Moderate":N.length>0?"Low":"None";return{id:y.id||`comp_${S}`,domain:y.domain,citationCount:N.length,totalKeywords:C.size,pressureLabel:k,citedKeywords:N,movement:"",notes:""}}),recentRuns:p.slice(0,5)}}function jQ(e){const t=UD(e.project),n=e.latestRunDetail?.snapshots??[],r=FD(n),i=KD(n,e.competitors.map(f=>f.domain)),l=[...e.runs].sort((f,h)=>h.createdAt.localeCompare(f.createdAt))[0],c=l?v1(l,e.project.displayName||e.project.name):{id:"none",projectId:e.project.id,projectName:e.project.displayName||e.project.name,kind:"answer-visibility",kindLabel:"No runs yet",status:"queued",trigger:"manual",createdAt:"",startedAt:"",duration:"",statusDetail:"",summary:"No runs yet",triggerLabel:""};return{project:t,visibilityScore:r.score,visibilityDelta:n.length>0?`${r.citedCount} of ${r.totalCount} key phrases`:"No data",lastRun:c,insight:n.length>0?`${r.citedCount} of ${r.totalCount} key phrases visible across ${new Set(n.map(f=>f.provider)).size} provider${new Set(n.map(f=>f.provider)).size>1?"s":""}.`:"No runs completed yet.",trend:[],competitorPressureLabel:i.label}}function NQ(e,t){const n=[],r=[],i=[];for(const l of e){r.push(SQ(l)),i.push(jQ(l));const c=[...l.runs].sort((f,h)=>h.createdAt.localeCompare(f.createdAt));for(const f of c)n.push(v1(f,l.project.displayName||l.project.name))}n.sort((l,c)=>c.createdAt.localeCompare(l.createdAt));const s=e.length>0;return{portfolioOverview:{projects:i,attentionItems:s?CQ(r):[{id:"attention_setup",tone:"neutral",title:"No projects yet",detail:"Create your first project using the setup wizard, CLI, or API.",actionLabel:"Open setup",href:"/setup"}],recentRuns:n.slice(0,5),systemHealth:[{id:"api",label:"API",tone:"positive",detail:"Connected",meta:"Real-time data"},{id:"provider",label:"Gemini",tone:"positive",detail:"Configured",meta:"Provider active"}],lastUpdatedAt:new Date().toLocaleString("en-US",{month:"short",day:"numeric",hour:"numeric",minute:"2-digit",timeZoneName:"short"}),...s?{}:{emptyState:{title:"No projects yet",detail:"Canonry becomes useful after one project, a small key phrase set, and one competitor list are in place.",ctaLabel:"Launch setup",ctaHref:"/setup"}}},projects:r,runs:n,setup:{healthChecks:[{id:"api",label:"API reachable",detail:"API is responding.",state:"ready",guidance:"Required for project creation and run history."},{id:"provider",label:"Provider configured",detail:"Gemini key is configured.",state:"ready",guidance:"Required for answer-visibility sweeps."}],projectDraft:{name:"",canonicalDomain:"",country:"US",language:"en"},keywordImportState:{mode:"paste",keywordCount:0,preview:[]},competitorDraft:{domains:[],notes:"Use the CLI to add competitors."},launchState:{enabled:s,ctaLabel:s?"Trigger run":"Create a project first",summary:s?"Ready to run.":"Create a project first to launch a run."}},settings:{providerStatuses:(t?.providers??[]).map(l=>({name:l.name,displayName:l.displayName,keyUrl:l.keyUrl,modelHint:l.modelHint,model:l.model,state:l.configured?"ready":"needs-config",detail:l.configured?"Provider is configured.":"API key is missing.",quota:l.quota})),google:{state:t?.google?.configured?"ready":"needs-config",detail:t?.google?.configured?"Google OAuth app credentials are configured. Project-level GSC connections can be created from the dashboard.":"Google OAuth client ID and client secret are not configured yet."},bing:{state:t?.bing?.configured?"ready":"needs-config",detail:t?.bing?.configured?"Bing Webmaster Tools API key is configured. Project-level Bing connections can be created from the dashboard.":"Bing Webmaster Tools API key is not configured yet."},selfHostNotes:["Configuration is stored in ~/.canonry/config.yaml.","The local config file is the source of truth for authentication credentials.","Google OAuth app credentials and per-domain Google tokens are stored in local config, not the database.","Database is SQLite at ~/.canonry/data.db.","API key was auto-generated during canonry init."],bootstrapNote:"Use the UI, CLI, or ~/.canonry/config.yaml to manage settings. Authentication credentials persist to local config."}}}function CQ(e){const t=[];for(const n of e){const r=n.visibilityEvidence.filter(s=>s.citationState==="lost");r.length>0&&t.push({id:`attention_${n.project.id}_lost`,tone:"negative",title:`${n.project.displayName||n.project.name} lost citations`,detail:`${r.length} key phrase${r.length>1?"s":""} lost citation.`,actionLabel:"Open project",href:`/projects/${n.project.id}`});const i=n.recentRuns.filter(s=>s.status==="running"||s.status==="queued");i.length>0&&t.push({id:`attention_${n.project.id}_active`,tone:"neutral",title:`${n.project.displayName||n.project.name} has active runs`,detail:`${i.length} run${i.length>1?"s":""} in progress.`,actionLabel:"View runs",href:"/runs"})}return t.length===0&&t.push({id:"attention_stable",tone:"positive",title:"All projects stable",detail:"No citation losses or active runs to flag.",actionLabel:"View portfolio",href:"/"}),t}const Yr={projects:{all:["projects"],detail:(e,t)=>["projects",e,t],keywords:e=>["projects",e,"keywords"],competitors:e=>["projects",e,"competitors"],timeline:(e,t)=>["projects",e,"timeline",t]},runs:{all:["runs"],detail:e=>["runs",e]},settings:["settings"],health:["health"]},HD=x.createContext(null);HD.Provider;function af(){return x.useContext(HD)}function sl(e){const n=af()?.dashboard??null,r=zo({queryKey:Yr.projects.all,queryFn:IM,enabled:!n}),i=zo({queryKey:Yr.runs.all,queryFn:$M,enabled:!n,refetchInterval:S=>S.state.data?.some(C=>C.status==="running"||C.status==="queued")?3e3:!1}),s=zo({queryKey:Yr.settings,queryFn:()=>WS().catch(()=>null),enabled:!n}),l=r.data??[],c=i.data??[],f=qB({queries:l.map(S=>{const w=c.filter(C=>C.projectId===S.id),N=w.filter(C=>(C.status==="completed"||C.status==="partial")&&C.kind==="answer-visibility").sort((C,A)=>A.createdAt.localeCompare(C.createdAt));return{queryKey:Yr.projects.detail(S.id,N[0]?.id),queryFn:async()=>{const[C,A,k,O,T,P,E]=await Promise.all([Zq(S.name).catch(()=>[]),UM(S.name).catch(()=>[]),BM(S.name).catch(()=>[]),N[0]?Ac(N[0].id).catch(()=>null):Promise.resolve(null),N[1]?Ac(N[1].id).catch(()=>null):Promise.resolve(null),QS(S.name).catch(()=>null),XS(S.name).catch(()=>null)]);return{project:S,runs:w,keywords:C,competitors:A,timeline:k,latestRunDetail:O,previousRunDetail:T,gscCoverage:P,bingCoverage:E}},enabled:!n&&r.isSuccess&&i.isSuccess}})}),h=f.every(S=>S.isSuccess),p=x.useMemo(()=>{if(n)return n;if(!r.data||!i.data||l.length>0&&!h)return null;const S=f.map(w=>w.data).filter(w=>w!=null);return NQ(S,s.data??null)},[n,r.data,i.data,s.data,h,f,l.length]),g=!n&&(r.isError||i.isError),v=!n&&!p&&!g,y=x.useCallback(async()=>{await Promise.all([r.refetch(),i.refetch(),s.refetch()])},[r.refetch,i.refetch,s.refetch]);return{dashboard:p,isLoading:v,isError:g,refetch:y}}function OQ(){return typeof window<"u"&&window.__CANONRY_CONFIG__?.basePath?window.__CANONRY_CONFIG__.basePath:"/"}const uE=OQ(),Cw=uE==="/"?"":uE.replace(/\/$/,"");async function _Q(){const e=Cw?`${Cw}/health`:"/health",t=await F9(e,"API"),n=t.state==="ok"?{label:"Runner",state:"ok",detail:"In-process job runner"}:{label:"Runner",state:t.state,detail:"Depends on API"};return{apiStatus:t,workerStatus:n}}function Mg(e,t){return zo({queryKey:Yr.health,queryFn:_Q,enabled:e,refetchInterval:15e3,initialData:t})}function kQ(e){return zo({queryKey:Yr.runs.detail(e??""),queryFn:()=>Ac(e),enabled:!!e,refetchInterval:t=>{const n=t.state.data?.status;return n==="running"||n==="queued"?3e3:!1}})}function Vc(){const e=Us(),t=bg({strict:!1}),n=gr({select:f=>f.location.pathname}),r=t.runId??null,i=t.evidenceId??null;return{runId:r,evidenceId:i,openRun:f=>e({to:n,from:xi.to,search:h=>({...h,runId:f,evidenceId:void 0})}),openEvidence:f=>e({to:n,from:xi.to,search:h=>({...h,evidenceId:f,runId:void 0})}),closeDrawer:()=>e({to:n,from:xi.to,search:f=>({...f,runId:void 0,evidenceId:void 0})})}}const AQ={negative:"toast-card-negative",caution:"toast-card-caution",positive:"toast-card-positive",neutral:"toast-card-neutral"};function EQ(e){if(e.cta)return`${e.cta.label}: ${e.title}`}function TQ(){const e=x.useSyncExternalStore(Y9,sA,sA),t=Us(),{openRun:n}=Vc(),r=x.useCallback(s=>{hw(s)},[]),i=x.useCallback(s=>{s.cta&&(s.cta.intent==="open-run-drawer"?n(s.cta.runId):t({to:"/runs"}),hw(s.id))},[t,n]);return e.length===0?null:u.jsx("div",{className:"toast-viewport","aria-label":"Notifications",children:e.map(s=>u.jsxs("section",{role:s.tone==="negative"?"alert":"status","aria-live":s.tone==="negative"?"assertive":"polite","data-state":s.state,className:`toast-card ${AQ[s.tone]}`,children:[u.jsxs("div",{className:"toast-copy",children:[u.jsx("p",{className:"toast-title",children:s.title}),s.detail?u.jsx("p",{className:"toast-detail",children:s.detail}):null,s.cta?u.jsx("button",{type:"button",className:"toast-action",onClick:()=>i(s),"aria-label":EQ(s),children:s.cta.label}):null]}),u.jsx("button",{type:"button",onClick:()=>r(s.id),className:"toast-dismiss","aria-label":"Dismiss",children:u.jsx(Sg,{className:"size-3.5"})})]},s.id))})}const dE=[{label:"Architecture",href:"https://github.com/AINYC/canonry/blob/main/docs/architecture.md"},{label:"Testing Guide",href:"https://github.com/AINYC/canonry/blob/main/docs/testing.md"}],fE=e=>({label:e,state:"checking",detail:"Checking service health"}),PQ={apiStatus:fE("API"),workerStatus:fE("Worker")};function zQ(e){return e==="gsc-sync"?"GSC sync":e==="inspect-sitemap"?"Sitemap inspection":"Visibility sweep"}function MQ(e){return e==="completed"?"positive":e==="partial"?"caution":"negative"}function RQ(e){const t=zQ(e.kind);return e.status==="completed"?`${t} completed`:e.status==="partial"?`${t} completed with partial results`:e.status==="cancelled"?`${t} cancelled`:`${t} failed`}function DQ(e,t){return e.error?`${t}: ${e.error}`:e.location?`${t} · ${e.location}`:t}function IQ(e,t,n){if(t)return t;const r=n.find(i=>i.id===e);return r?.displayName||r?.name||e}function LQ(e,t){return[e.completed>0?`${e.completed} completed`:null,e.partial>0?`${e.partial} partial`:null,e.failed>0?`${e.failed} failed`:null,e.cancelled>0?`${e.cancelled} cancelled`:null,t>0?`${t} skipped at queue time`:null].filter(Boolean).join(", ")}function $Q(e){return e.failed>0||e.cancelled>0?"negative":e.partial>0?"caution":"positive"}function UQ(){const e=x.useSyncExternalStore($F,Ko,Ko),t=Object.keys(e.runs).length>0||Object.keys(e.batches).length>0,n=zo({queryKey:Yr.runs.all,queryFn:$M,enabled:t}),r=zo({queryKey:Yr.projects.all,queryFn:IM,enabled:t}),i=x.useRef({}),s=x.useCallback(()=>{n.refetch()},[n.refetch]);return x.useEffect(()=>{t&&s()},[t,s]),x.useEffect(()=>{if(!t||typeof window>"u")return;const l=()=>{document.visibilityState==="visible"&&s()};return window.addEventListener("focus",s),document.addEventListener("visibilitychange",l),()=>{window.removeEventListener("focus",s),document.removeEventListener("visibilitychange",l)}},[t,s]),x.useEffect(()=>{const l=n.data??[],c=r.data??[],f=Object.fromEntries(l.map(p=>[p.id,p])),h=Object.fromEntries(l.map(p=>[p.id,p.status]));for(const p of Object.values(e.runs)){const g=f[p.runId];if(!g||!qF(g.status)||(i.current[g.id]??p.lastAnnouncedStatus)===g.status)continue;if(p.sourceAction==="run-all"){fA(g.id);continue}const y=IQ(g.projectId,p.projectLabel,c);Qe({title:RQ(g),detail:DQ(g,y),tone:MQ(g.status),dedupeKey:`run:${g.id}`,dedupeMode:"replace",cta:{label:"View run",intent:"open-run-drawer",runId:g.id}}),fA(g.id)}for(const p of Object.values(e.batches)){const g=FF(p.runIds,f);g.finished&&(Qe({title:"Run-all batch finished",detail:LQ(g,p.skippedCount),tone:$Q(g),dedupeKey:`batch:${p.batchId}`,dedupeMode:"replace",cta:{label:"View runs",intent:"go-to-runs"}}),BF(p.batchId))}i.current=h},[r.data,n.data,e]),null}function BQ(){const e=af(),{dashboard:t,isLoading:n,refetch:r}=sl(),l=Mg(!e,e?.health).data??e?.health??PQ,c=Kq(),{runId:f,evidenceId:h,closeDrawer:p}=Vc(),[g,v]=x.useState(!1),y=kQ(f),S=y.data??null,w=y.isLoading;x.useEffect(()=>{S&&S.status!=="running"&&S.status!=="queued"&&r()},[S?.status,r]),x.useEffect(()=>{v(!1)},[c.pathname]),x.useEffect(()=>{if(typeof window>"u"||!f&&!h)return;const O=T=>{T.key==="Escape"&&p()};return window.addEventListener("keydown",O),()=>{window.removeEventListener("keydown",O)}},[f,h,p]);const N=t??e?.dashboard??null,C=f&&N?tQ(N,f):void 0,A=h&&N?nQ(N,h):void 0,k=(()=>{const O=c.pathname;if(O==="/")return"Portfolio";if(O==="/projects")return"Projects";if(O==="/runs")return"Runs";if(O==="/settings")return"Settings";if(O==="/setup")return"Setup";if(O.startsWith("/projects/")){const P=O.split("/").filter(Boolean)[1];if(P&&N){const E=N.projects.find(z=>z.project.id===P);if(E)return E.project.name}return"Project"}return"Not found"})();return u.jsxs("div",{className:"app-shell",children:[u.jsx("a",{className:"skip-link",href:"#content",children:"Skip to content"}),u.jsxs("aside",{className:"sidebar","aria-label":"Primary navigation",children:[u.jsx("div",{className:"sidebar-brand",children:u.jsx(SA,{})}),u.jsxs("nav",{className:"sidebar-nav",children:[u.jsxs(Dt,{to:"/",className:"sidebar-link",activeProps:{className:"sidebar-link sidebar-link-active"},activeOptions:{exact:!0},children:[u.jsx(uF,{className:"sidebar-icon"}),u.jsx("span",{children:"Overview"})]}),u.jsxs(Dt,{to:"/projects",className:"sidebar-link",activeProps:{className:"sidebar-link sidebar-link-active"},activeOptions:{exact:!1},children:[u.jsx(lF,{className:"sidebar-icon"}),u.jsx("span",{children:"Projects"})]}),u.jsxs(Dt,{to:"/runs",className:"sidebar-link",activeProps:{className:"sidebar-link sidebar-link-active"},activeOptions:{exact:!0},children:[u.jsx(pF,{className:"sidebar-icon"}),u.jsx("span",{children:"Runs"})]}),u.jsxs(Dt,{to:"/settings",className:"sidebar-link",activeProps:{className:"sidebar-link sidebar-link-active"},activeOptions:{exact:!0},children:[u.jsx(SF,{className:"sidebar-icon"}),u.jsx("span",{children:"Settings"})]}),n?u.jsxs(u.Fragment,{children:[u.jsx("p",{className:"sidebar-section-title",children:"Projects"}),[1,2,3].map(O=>u.jsxs("div",{className:"sidebar-skeleton-item",children:[u.jsx("span",{className:"skeleton-circle size-2"}),u.jsx("span",{className:"skeleton-text flex-1",style:{width:`${50+O*15}%`}})]},O))]}):N&&N.projects.length>0?u.jsxs(u.Fragment,{children:[u.jsx("p",{className:"sidebar-section-title",children:"Projects"}),N.projects.map(O=>{const T=O.visibilitySummary.tone;return u.jsxs(Dt,{to:"/projects/$projectId",params:{projectId:O.project.id},className:"sidebar-project",activeProps:{className:"sidebar-project sidebar-project-active"},children:[u.jsx("span",{className:`sidebar-dot sidebar-dot-${T}`}),u.jsx("span",{children:O.project.name})]},O.project.id)})]}):n?null:u.jsxs(u.Fragment,{children:[u.jsx("p",{className:"sidebar-section-title",children:"Resources"}),u.jsxs(Dt,{to:"/setup",className:"sidebar-link",activeProps:{className:"sidebar-link sidebar-link-active"},activeOptions:{exact:!0},children:[u.jsx(yF,{className:"sidebar-icon"}),u.jsx("span",{children:"Setup"})]})]})]}),u.jsx("div",{className:"sidebar-footer",children:dE.map(O=>u.jsx("a",{className:"sidebar-footer-link",href:O.href,target:"_blank",rel:"noopener noreferrer",children:O.label},O.href))})]}),u.jsxs("div",{className:"main-area",children:[u.jsxs("header",{className:"topbar",children:[u.jsxs("div",{className:"topbar-left",children:[u.jsx("div",{className:"topbar-brand-mobile",children:u.jsx(SA,{compact:!0})}),u.jsxs("nav",{className:"breadcrumb","aria-label":"Breadcrumb",children:[u.jsx(Dt,{to:"/",children:"Home"}),u.jsx(wg,{className:"breadcrumb-sep size-3"}),u.jsx("span",{className:"breadcrumb-current",children:k})]})]}),u.jsxs("div",{className:"topbar-actions",children:[u.jsxs("div",{className:"health-pill-row",children:[u.jsxs("span",{className:`health-pill health-pill-${l.apiStatus.state}`,children:["API ",l.apiStatus.state==="ok"?"ok":l.apiStatus.state]}),u.jsxs("span",{className:`health-pill health-pill-${l.workerStatus.state}`,children:["Worker ",l.workerStatus.state==="ok"?"ok":l.workerStatus.state]})]}),u.jsxs(pe,{className:"nav-toggle",variant:"secondary",size:"icon",type:"button","aria-expanded":g,"aria-controls":"mobile-nav",onClick:()=>v(O=>!O),children:[u.jsx(fF,{className:"size-4"}),u.jsx("span",{className:"sr-only",children:"Open navigation"})]})]})]}),u.jsxs("div",{id:"mobile-nav",className:`mobile-nav ${g?"mobile-nav-open":""}`,children:[u.jsxs(pe,{className:"mobile-nav-close",variant:"ghost",size:"icon",type:"button",onClick:()=>v(!1),children:[u.jsx(Sg,{className:"size-5"}),u.jsx("span",{className:"sr-only",children:"Close navigation"})]}),u.jsx(Dt,{to:"/",className:"mobile-nav-link",activeProps:{className:"mobile-nav-link mobile-nav-link-active"},activeOptions:{exact:!0},children:"Overview"}),u.jsx(Dt,{to:"/projects",className:"mobile-nav-link",activeProps:{className:"mobile-nav-link mobile-nav-link-active"},activeOptions:{exact:!1},children:"Projects"}),u.jsx(Dt,{to:"/runs",className:"mobile-nav-link",activeProps:{className:"mobile-nav-link mobile-nav-link-active"},activeOptions:{exact:!0},children:"Runs"}),u.jsx(Dt,{to:"/settings",className:"mobile-nav-link",activeProps:{className:"mobile-nav-link mobile-nav-link-active"},activeOptions:{exact:!0},children:"Settings"}),N&&N.projects.length>0?u.jsxs("div",{className:"mobile-nav-section",children:[u.jsx("p",{className:"mobile-nav-section-title",children:"Projects"}),N.projects.map(O=>u.jsx(Dt,{to:"/projects/$projectId",params:{projectId:O.project.id},className:"mobile-nav-link",children:O.project.name},O.project.id))]}):null]}),u.jsx("main",{id:"content",className:"page-shell",children:n&&!e?u.jsxs("div",{className:"page-skeleton",children:[u.jsxs("div",{className:"page-skeleton-header",children:[u.jsx("div",{className:"skeleton-text h-6 w-40"}),u.jsx("div",{className:"skeleton-text-sm w-72"})]}),u.jsx("div",{className:"page-skeleton-grid",children:[1,2,3].map(O=>u.jsxs("div",{className:"page-skeleton-card",children:[u.jsx("div",{className:"skeleton-text w-24"}),u.jsx("div",{className:"skeleton-text w-full"}),u.jsx("div",{className:"skeleton-text-sm w-3/4"})]},O))}),u.jsx("div",{className:"page-skeleton-grid",style:{gridTemplateColumns:"1fr 1fr"},children:[1,2].map(O=>u.jsxs("div",{className:"page-skeleton-card",children:[u.jsx("div",{className:"skeleton-text w-20"}),u.jsx("div",{className:"space-y-2",children:[1,2,3].map(T=>u.jsx("div",{className:"skeleton-text-sm w-full"},T))})]},O))})]}):u.jsx(YS,{})}),u.jsxs("footer",{className:"footer",children:[u.jsxs("a",{href:"https://github.com/AINYC/canonry",target:"_blank",rel:"noopener noreferrer",className:"footer-brand",children:[u.jsx(sF,{className:"size-3.5"}),u.jsx("span",{children:"Canonry"})]}),u.jsx("div",{className:"footer-links",children:dE.map(O=>u.jsx("a",{href:O.href,target:"_blank",rel:"noopener noreferrer",children:O.label},O.href))})]})]}),C?u.jsxs(E7,{open:C!==void 0,title:C.summary,subtitle:`${C.projectName} · ${C.kindLabel}`,onClose:p,children:[u.jsxs("div",{className:"flex flex-wrap items-center gap-x-5 gap-y-1 text-sm",children:[u.jsx(Og,{status:C.status}),u.jsx("span",{className:"text-zinc-400",children:C.startedAt}),u.jsx("span",{className:"text-zinc-500",children:C.duration}),u.jsx("span",{className:"text-zinc-600",children:C.triggerLabel})]}),C.status==="failed"&&C.statusDetail&&u.jsx("p",{className:"text-sm text-rose-300/80 mt-2",children:C.statusDetail}),u.jsxs("div",{className:"mt-4",children:[u.jsx("p",{className:"text-[10px] font-semibold uppercase tracking-wider text-zinc-500 mb-2",children:"Activity Log"}),w?u.jsx("p",{className:"text-sm text-zinc-500",children:"Loading run details..."}):S&&S.snapshots.length>0?u.jsxs("div",{className:"space-y-2",children:[S.snapshots.map(O=>u.jsxs("div",{className:"rounded-lg border border-zinc-800/60 bg-zinc-900/30 p-3",children:[u.jsxs("div",{className:"flex items-center justify-between gap-2 mb-1",children:[u.jsx("p",{className:"text-sm font-medium text-zinc-200 truncate",children:O.keyword??"Unknown key phrase"}),u.jsxs("div",{className:"flex items-center gap-1.5",children:[u.jsx(zd,{provider:O.provider}),u.jsx(vR,{variant:O.citationState==="cited"?"success":"neutral",children:O.citationState})]})]}),O.model&&u.jsx("p",{className:"text-[11px] text-zinc-500 font-mono",children:O.model}),O.citedDomains.length>0&&u.jsxs("p",{className:"text-xs text-zinc-500 mt-1",children:[u.jsx("span",{className:"text-zinc-400",children:"Sources:"})," ",O.citedDomains.join(", ")]}),O.competitorOverlap.length>0&&u.jsxs("p",{className:"text-xs text-rose-400/80 mt-0.5",children:["Competitor cited: ",O.competitorOverlap.join(", ")]}),O.groundingSources&&O.groundingSources.length>0&&u.jsxs("details",{className:"mt-2",children:[u.jsxs("summary",{className:"text-xs text-zinc-500 cursor-pointer hover:text-zinc-400",children:[O.groundingSources.length," grounding source",O.groundingSources.length!==1?"s":""]}),u.jsx("ul",{className:"mt-1 space-y-0.5",children:O.groundingSources.map((T,P)=>u.jsx("li",{className:"text-xs text-zinc-500 truncate",children:u.jsx("a",{href:T.uri,target:"_blank",rel:"noopener noreferrer",className:"hover:text-zinc-300",children:T.title||T.uri})},P))})]}),O.answerText&&u.jsxs("details",{className:"mt-1",children:[u.jsx("summary",{className:"text-xs text-zinc-500 cursor-pointer hover:text-zinc-400",children:"Answer preview"}),u.jsx("p",{className:"mt-1 text-xs text-zinc-400 leading-relaxed whitespace-pre-wrap",children:O.answerText})]})]},O.id)),S.status==="running"&&u.jsxs("div",{className:"flex items-center gap-2 p-3 text-sm text-zinc-500",children:[u.jsx("span",{className:"inline-block h-2 w-2 rounded-full bg-amber-500 animate-pulse"}),"Querying remaining key phrases..."]})]}):S&&S.status==="running"?u.jsxs("div",{className:"flex items-center gap-2 p-3 text-sm text-zinc-500",children:[u.jsx("span",{className:"inline-block h-2 w-2 rounded-full bg-amber-500 animate-pulse"}),"Waiting for first key phrase result..."]}):S&&S.status==="queued"?u.jsxs("div",{className:"flex items-center gap-2 p-3 text-sm text-zinc-500",children:[u.jsx("span",{className:"inline-block h-2 w-2 rounded-full bg-zinc-500 animate-pulse"}),"Run queued, waiting for execution slot..."]}):S&&S.error?u.jsxs("div",{className:"rounded-lg border border-rose-800/40 bg-rose-950/20 p-3",children:[u.jsx("p",{className:"text-sm font-medium text-rose-300 mb-2",children:"Run failed"}),u.jsx("pre",{className:"text-xs text-rose-300/80 whitespace-pre-wrap break-words max-h-48 overflow-y-auto font-mono leading-5",children:PF(S.error)})]}):u.jsx("p",{className:"text-sm text-zinc-500",children:"No snapshot data available."})]})]}):null,A?u.jsx(ZW,{evidence:A.evidence,project:A.project,onClose:p}):null,u.jsx(UQ,{}),u.jsx(TQ,{})]})}class qQ extends x.Component{state={error:null};static getDerivedStateFromError(t){return{error:t}}componentDidCatch(t,n){console.error("[ErrorBoundary]",t,n.componentStack)}handleReset=()=>{this.setState({error:null})};render(){return this.state.error?u.jsx("div",{className:"page-container",children:u.jsxs("div",{className:"flex flex-col items-center justify-center gap-4 py-20 text-center",children:[u.jsx("div",{className:"rounded-full bg-rose-950/40 p-3",children:u.jsx(OF,{className:"size-6 text-rose-400"})}),u.jsx("h2",{className:"text-lg font-semibold text-zinc-100",children:"Something went wrong"}),u.jsx("p",{className:"text-sm text-zinc-400 max-w-md",children:this.state.error.message||"An unexpected error occurred while rendering this page."}),u.jsxs("div",{className:"flex gap-3 mt-2",children:[u.jsxs(pe,{variant:"secondary",size:"sm",onClick:this.handleReset,children:[u.jsx(xF,{className:"size-3.5 mr-1.5"}),"Try again"]}),u.jsx(pe,{variant:"secondary",size:"sm",onClick:()=>{window.location.href="/"},children:"Go home"})]})]})}):this.props.children}}const Ue=x.forwardRef(({className:e,...t},n)=>u.jsx("div",{ref:n,className:ai("rounded-xl border border-zinc-800 bg-zinc-950/75 shadow-[0_0_0_1px_rgba(255,255,255,0.01)] backdrop-blur",e),...t}));Ue.displayName="Card";const Ow=x.forwardRef(({className:e,...t},n)=>u.jsx("div",{ref:n,className:ai("flex flex-col gap-1.5 p-5",e),...t}));Ow.displayName="CardHeader";const _w=x.forwardRef(({className:e,...t},n)=>u.jsx("h3",{ref:n,className:ai("font-medium tracking-tight text-zinc-50",e),...t}));_w.displayName="CardTitle";const kw=x.forwardRef(({className:e,...t},n)=>u.jsx("p",{ref:n,className:ai("text-sm text-zinc-500",e),...t}));kw.displayName="CardDescription";const Lp=x.forwardRef(({className:e,...t},n)=>u.jsx("div",{ref:n,className:ai("p-5 pt-0",e),...t}));Lp.displayName="CardContent";function FQ({points:e,tone:t}){const n=x.useId();if(e.length===0)return null;const r=42,i=132,s=5,l=Math.min(...e),f=Math.max(...e)-l||1,h=i-s*2,p=r-s*2,g=e.map((v,y)=>{const S=s+y/Math.max(e.length-1,1)*h,w=s+(1-(v-l)/f)*p;return`${S},${w}`}).join(" ");return u.jsxs("svg",{className:`sparkline sparkline-${t}`,viewBox:`0 0 ${i} ${r}`,"aria-hidden":"true",children:[u.jsx("defs",{children:u.jsx("clipPath",{id:n,children:u.jsx("rect",{x:s,y:s,width:h,height:p,rx:"8"})})}),u.jsx("line",{className:"sparkline-guide",x1:s,x2:i-s,y1:r-s,y2:r-s}),u.jsx("polyline",{clipPath:`url(#${n})`,points:g,vectorEffect:"non-scaling-stroke"})]})}function KQ(e){return e.displayName??e.name.charAt(0).toUpperCase()+e.name.slice(1)}function HQ(e,t,n){return e.map(r=>{if(r.id==="api")return{...r,tone:om(t.apiStatus),detail:t.apiStatus.state==="ok"?"Healthy":"Needs attention",meta:t.apiStatus.detail};if(r.id==="worker")return{...r,tone:om(t.workerStatus),detail:t.workerStatus.state==="ok"?"Healthy":"Needs attention",meta:t.workerStatus.detail};const i=n.providerStatuses.filter(f=>f.state==="ready").length,s=n.providerStatuses.length,l=i>0,c=n.providerStatuses.filter(f=>f.state==="ready").map(f=>KQ(f)).join(" · ");return{...r,label:"Providers",tone:l?"positive":"caution",detail:`${i} of ${s} configured`,meta:c||"None configured"}})}function GQ(e,t){if(e.apiStatus.state!=="ok")return"Launch is blocked until the API responds cleanly.";if(e.apiStatus.databaseConfigured===!1)return"Launch is blocked until the API has a database connection configured.";if(e.workerStatus.state!=="ok")return"Launch is blocked until the worker is healthy and heartbeats are current.";if(!t.providerStatuses.some(n=>n.state==="ready"))return"Launch is blocked until at least one provider is configured."}function VQ(e,t,n){const r=GQ(t,n),i=structuredClone(e);return i.healthChecks=i.healthChecks.map(s=>{if(s.id==="api")return{...s,detail:t.apiStatus.detail,state:t.apiStatus.state==="ok"?"ready":"attention"};if(s.id==="worker")return{...s,detail:t.workerStatus.detail,state:t.workerStatus.state==="ok"?"ready":"attention"};const l=n.providerStatuses.some(c=>c.state==="ready");return{...s,detail:l?"At least one provider configured.":"No providers configured.",state:l?"ready":"attention"}}),i.launchState.enabled=r===void 0,i.launchState.blockedReason=r,i.launchState.summary=r??"Queue a visibility sweep first, then follow with a site audit to explain movement.",i}function ZQ({project:e}){return u.jsxs(Dt,{to:"/projects/$projectId",params:{projectId:e.project.id},className:"project-row cursor-pointer",children:[u.jsxs("div",{className:"project-row-primary",children:[u.jsxs("div",{children:[u.jsx("p",{className:"project-name",children:e.project.name}),u.jsx("p",{className:"project-domain",children:e.project.canonicalDomain})]}),u.jsx("p",{className:"project-insight",children:e.insight})]}),u.jsx("div",{className:"project-row-stat",children:u.jsxs("div",{className:"metric-inline-block",children:[u.jsx("p",{className:"metric-inline-label",children:"Answer Visibility"}),u.jsx("p",{className:"metric-inline-value",children:e.visibilityScore}),u.jsx("p",{className:"metric-inline-delta",children:e.visibilityDelta})]})}),u.jsx("div",{className:"project-row-stat",children:u.jsxs("div",{className:"metric-inline-block",children:[u.jsx("p",{className:"metric-inline-label",children:"Competitor Pressure"}),u.jsx("p",{className:"metric-inline-value",children:e.competitorPressureLabel}),u.jsxs("p",{className:"metric-inline-delta",children:[e.lastRun.kindLabel," · ",jg(e.lastRun.status)]})]})}),u.jsx("div",{className:"project-row-chart",children:u.jsx(FQ,{points:e.trend,tone:yR(e.lastRun.status)})}),u.jsx("span",{className:"project-row-link",children:u.jsx(wg,{className:"h-4 w-4 text-zinc-500"})})]})}function YQ(){const e=af(),{dashboard:t,isLoading:n}=sl(),r=t??e?.dashboard;if(!r||n)return u.jsxs("div",{className:"page-skeleton",children:[u.jsxs("div",{className:"page-skeleton-header",children:[u.jsx("div",{className:"skeleton-text h-6 w-32"}),u.jsx("div",{className:"skeleton-text-sm w-64"})]}),u.jsx("div",{className:"space-y-3",children:[1,2,3].map(p=>u.jsxs("div",{className:"rounded-xl border border-zinc-800/60 bg-zinc-900/30 p-4 flex items-center gap-4",children:[u.jsxs("div",{className:"flex-1 space-y-2",children:[u.jsx("div",{className:"skeleton-text w-36"}),u.jsx("div",{className:"skeleton-text-sm w-48"})]}),u.jsx("div",{className:"skeleton-text w-16"}),u.jsx("div",{className:"skeleton-text w-16"}),u.jsx("div",{className:"skeleton h-8 w-20 rounded"})]},p))})]});const i=r.portfolioOverview,c=Mg(!e,e?.health).data??e?.health??{apiStatus:{label:"API",state:"checking",detail:"Checking service health"},workerStatus:{label:"Worker",state:"checking",detail:"Checking service health"}},f=HQ(i.systemHealth,c,r.settings),{openRun:h}=Vc();return u.jsxs("div",{className:"page-container",children:[u.jsxs("div",{className:"page-header",children:[u.jsxs("div",{className:"page-header-left",children:[u.jsx("h1",{className:"page-title",children:"Portfolio"}),u.jsx("p",{className:"page-subtitle",children:"Visibility and execution state across all projects"})]}),u.jsx("div",{className:"page-header-right",children:u.jsx("p",{className:"text-[11px] text-zinc-600",children:i.lastUpdatedAt})})]}),i.projects.length>0?u.jsx("div",{className:"project-list project-list-scrollable",children:i.projects.map(p=>u.jsx(ZQ,{project:p},p.project.id))}):u.jsxs(Ue,{className:"surface-card empty-card",children:[u.jsx("h3",{children:i.emptyState?.title??"No projects yet"}),u.jsx("p",{className:"supporting-copy",children:i.emptyState?.detail}),u.jsx(pe,{size:"sm",asChild:!0,children:u.jsx(Dt,{to:i.emptyState?.ctaHref==="/setup"||!i.emptyState?.ctaHref?"/setup":"/",children:i.emptyState?.ctaLabel??"Launch setup"})})]}),u.jsxs("div",{className:"overview-secondary-grid",children:[i.attentionItems.length>0&&u.jsxs("section",{className:"overview-secondary-section",children:[u.jsx("div",{className:"section-head section-head-inline",children:u.jsxs("div",{children:[u.jsx("p",{className:"eyebrow eyebrow-soft",children:"Needs attention"}),u.jsx("h2",{className:"section-title-sm",children:"What changed"})]})}),u.jsx("div",{className:"attention-list attention-list-scrollable",children:i.attentionItems.map(p=>u.jsxs(Dt,{to:p.href,className:`attention-item attention-item-${p.tone}`,children:[u.jsxs("div",{children:[u.jsx("p",{className:"attention-title",children:p.title}),u.jsx("p",{className:"attention-detail",children:p.detail})]}),u.jsx("span",{className:"attention-action",children:p.actionLabel})]},p.id))})]}),u.jsxs("section",{className:"overview-secondary-section",children:[u.jsx("div",{className:"section-head section-head-inline",children:u.jsxs("div",{children:[u.jsx("p",{className:"eyebrow eyebrow-soft",children:"Recent runs"}),u.jsx("h2",{className:"section-title-sm",children:"Activity"})]})}),u.jsx("div",{className:"compact-stack compact-stack-scrollable",children:i.recentRuns.length>0?i.recentRuns.map(p=>u.jsxs("button",{className:"compact-run",type:"button",onClick:()=>h(p.id),children:[u.jsxs("div",{children:[u.jsx("p",{className:"compact-run-title",children:p.projectName}),u.jsx("p",{className:"compact-run-detail",children:p.summary})]}),u.jsx(Og,{status:p.status})]},p.id)):u.jsx("p",{className:"supporting-copy",children:"Run history appears here after the first launch."})})]})]}),u.jsxs("section",{className:"page-section",children:[u.jsx("div",{className:"section-head section-head-inline",children:u.jsxs("div",{children:[u.jsx("p",{className:"eyebrow eyebrow-soft",children:"System health"}),u.jsx("h2",{className:"section-title-sm",children:"Infrastructure"})]})}),u.jsx("div",{className:"health-grid",children:f.map(p=>u.jsxs(Ue,{className:"surface-card compact-card",children:[u.jsxs("div",{className:"section-head",children:[u.jsxs("div",{children:[u.jsx("p",{className:"eyebrow eyebrow-soft",children:p.label}),u.jsx("h3",{children:p.detail})]}),u.jsx(yt,{tone:p.tone,children:p.label})]}),u.jsx("p",{className:"supporting-copy",children:p.meta})]},p.id))})]})]})}const y1=Symbol.for("yaml.alias"),Aw=Symbol.for("yaml.document"),Es=Symbol.for("yaml.map"),GD=Symbol.for("yaml.pair"),Gi=Symbol.for("yaml.scalar"),Zc=Symbol.for("yaml.seq"),ei=Symbol.for("yaml.node.type"),ol=e=>!!e&&typeof e=="object"&&e[ei]===y1,Rg=e=>!!e&&typeof e=="object"&&e[ei]===Aw,sf=e=>!!e&&typeof e=="object"&&e[ei]===Es,nn=e=>!!e&&typeof e=="object"&&e[ei]===GD,kt=e=>!!e&&typeof e=="object"&&e[ei]===Gi,of=e=>!!e&&typeof e=="object"&&e[ei]===Zc;function en(e){if(e&&typeof e=="object")switch(e[ei]){case Es:case Zc:return!0}return!1}function tn(e){if(e&&typeof e=="object")switch(e[ei]){case y1:case Es:case Gi:case Zc:return!0}return!1}const VD=e=>(kt(e)||en(e))&&!!e.anchor,bo=Symbol("break visit"),WQ=Symbol("skip children"),Nd=Symbol("remove node");function Yc(e,t){const n=QQ(t);Rg(e)?mc(null,e.contents,n,Object.freeze([e]))===Nd&&(e.contents=null):mc(null,e,n,Object.freeze([]))}Yc.BREAK=bo;Yc.SKIP=WQ;Yc.REMOVE=Nd;function mc(e,t,n,r){const i=XQ(e,t,n,r);if(tn(i)||nn(i))return JQ(e,r,i),mc(e,i,n,r);if(typeof i!="symbol"){if(en(t)){r=Object.freeze(r.concat(t));for(let s=0;s<t.items.length;++s){const l=mc(s,t.items[s],n,r);if(typeof l=="number")s=l-1;else{if(l===bo)return bo;l===Nd&&(t.items.splice(s,1),s-=1)}}}else if(nn(t)){r=Object.freeze(r.concat(t));const s=mc("key",t.key,n,r);if(s===bo)return bo;s===Nd&&(t.key=null);const l=mc("value",t.value,n,r);if(l===bo)return bo;l===Nd&&(t.value=null)}}return i}function QQ(e){return typeof e=="object"&&(e.Collection||e.Node||e.Value)?Object.assign({Alias:e.Node,Map:e.Node,Scalar:e.Node,Seq:e.Node},e.Value&&{Map:e.Value,Scalar:e.Value,Seq:e.Value},e.Collection&&{Map:e.Collection,Seq:e.Collection},e):e}function XQ(e,t,n,r){if(typeof n=="function")return n(e,t,r);if(sf(t))return n.Map?.(e,t,r);if(of(t))return n.Seq?.(e,t,r);if(nn(t))return n.Pair?.(e,t,r);if(kt(t))return n.Scalar?.(e,t,r);if(ol(t))return n.Alias?.(e,t,r)}function JQ(e,t,n){const r=t[t.length-1];if(en(r))r.items[e]=n;else if(nn(r))e==="key"?r.key=n:r.value=n;else if(Rg(r))r.contents=n;else{const i=ol(r)?"alias":"scalar";throw new Error(`Cannot replace node with ${i} parent`)}}const eX={"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"},tX=e=>e.replace(/[!,[\]{}]/g,t=>eX[t]);class Qn{constructor(t,n){this.docStart=null,this.docEnd=!1,this.yaml=Object.assign({},Qn.defaultYaml,t),this.tags=Object.assign({},Qn.defaultTags,n)}clone(){const t=new Qn(this.yaml,this.tags);return t.docStart=this.docStart,t}atDocument(){const t=new Qn(this.yaml,this.tags);switch(this.yaml.version){case"1.1":this.atNextDocument=!0;break;case"1.2":this.atNextDocument=!1,this.yaml={explicit:Qn.defaultYaml.explicit,version:"1.2"},this.tags=Object.assign({},Qn.defaultTags);break}return t}add(t,n){this.atNextDocument&&(this.yaml={explicit:Qn.defaultYaml.explicit,version:"1.1"},this.tags=Object.assign({},Qn.defaultTags),this.atNextDocument=!1);const r=t.trim().split(/[ \t]+/),i=r.shift();switch(i){case"%TAG":{if(r.length!==2&&(n(0,"%TAG directive should contain exactly two parts"),r.length<2))return!1;const[s,l]=r;return this.tags[s]=l,!0}case"%YAML":{if(this.yaml.explicit=!0,r.length!==1)return n(0,"%YAML directive should contain exactly one part"),!1;const[s]=r;if(s==="1.1"||s==="1.2")return this.yaml.version=s,!0;{const l=/^\d+\.\d+$/.test(s);return n(6,`Unsupported YAML version ${s}`,l),!1}}default:return n(0,`Unknown directive ${i}`,!0),!1}}tagName(t,n){if(t==="!")return"!";if(t[0]!=="!")return n(`Not a valid tag: ${t}`),null;if(t[1]==="<"){const l=t.slice(2,-1);return l==="!"||l==="!!"?(n(`Verbatim tags aren't resolved, so ${t} is invalid.`),null):(t[t.length-1]!==">"&&n("Verbatim tags must end with a >"),l)}const[,r,i]=t.match(/^(.*!)([^!]*)$/s);i||n(`The ${t} tag has no suffix`);const s=this.tags[r];if(s)try{return s+decodeURIComponent(i)}catch(l){return n(String(l)),null}return r==="!"?t:(n(`Could not resolve tag: ${t}`),null)}tagString(t){for(const[n,r]of Object.entries(this.tags))if(t.startsWith(r))return n+tX(t.substring(r.length));return t[0]==="!"?t:`!<${t}>`}toString(t){const n=this.yaml.explicit?[`%YAML ${this.yaml.version||"1.2"}`]:[],r=Object.entries(this.tags);let i;if(t&&r.length>0&&tn(t.contents)){const s={};Yc(t.contents,(l,c)=>{tn(c)&&c.tag&&(s[c.tag]=!0)}),i=Object.keys(s)}else i=[];for(const[s,l]of r)s==="!!"&&l==="tag:yaml.org,2002:"||(!t||i.some(c=>c.startsWith(l)))&&n.push(`%TAG ${s} ${l}`);return n.join(`
96
96
  `)}}Qn.defaultYaml={explicit:!1,version:"1.2"};Qn.defaultTags={"!!":"tag:yaml.org,2002:"};function ZD(e){if(/[\x00-\x19\s,[\]{}]/.test(e)){const n=`Anchor must not contain whitespace or control characters: ${JSON.stringify(e)}`;throw new Error(n)}return!0}function YD(e){const t=new Set;return Yc(e,{Value(n,r){r.anchor&&t.add(r.anchor)}}),t}function WD(e,t){for(let n=1;;++n){const r=`${e}${n}`;if(!t.has(r))return r}}function nX(e,t){const n=[],r=new Map;let i=null;return{onAnchor:s=>{n.push(s),i??(i=YD(e));const l=WD(t,i);return i.add(l),l},setAnchors:()=>{for(const s of n){const l=r.get(s);if(typeof l=="object"&&l.anchor&&(kt(l.node)||en(l.node)))l.node.anchor=l.anchor;else{const c=new Error("Failed to resolve repeated object (this should not happen)");throw c.source=s,c}}},sourceObjects:r}}function gc(e,t,n,r){if(r&&typeof r=="object")if(Array.isArray(r))for(let i=0,s=r.length;i<s;++i){const l=r[i],c=gc(e,r,String(i),l);c===void 0?delete r[i]:c!==l&&(r[i]=c)}else if(r instanceof Map)for(const i of Array.from(r.keys())){const s=r.get(i),l=gc(e,r,i,s);l===void 0?r.delete(i):l!==s&&r.set(i,l)}else if(r instanceof Set)for(const i of Array.from(r)){const s=gc(e,r,i,i);s===void 0?r.delete(i):s!==i&&(r.delete(i),r.add(s))}else for(const[i,s]of Object.entries(r)){const l=gc(e,r,i,s);l===void 0?delete r[i]:l!==s&&(r[i]=l)}return e.call(t,n,r)}function Jr(e,t,n){if(Array.isArray(e))return e.map((r,i)=>Jr(r,String(i),n));if(e&&typeof e.toJSON=="function"){if(!n||!VD(e))return e.toJSON(t,n);const r={aliasCount:0,count:1,res:void 0};n.anchors.set(e,r),n.onCreate=s=>{r.res=s,delete n.onCreate};const i=e.toJSON(t,n);return n.onCreate&&n.onCreate(i),i}return typeof e=="bigint"&&!n?.keep?Number(e):e}class b1{constructor(t){Object.defineProperty(this,ei,{value:t})}clone(){const t=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return this.range&&(t.range=this.range.slice()),t}toJS(t,{mapAsMap:n,maxAliasCount:r,onAnchor:i,reviver:s}={}){if(!Rg(t))throw new TypeError("A document argument is required");const l={anchors:new Map,doc:t,keep:!0,mapAsMap:n===!0,mapKeyWarned:!1,maxAliasCount:typeof r=="number"?r:100},c=Jr(this,"",l);if(typeof i=="function")for(const{count:f,res:h}of l.anchors.values())i(h,f);return typeof s=="function"?gc(s,{"":c},"",c):c}}class x1 extends b1{constructor(t){super(y1),this.source=t,Object.defineProperty(this,"tag",{set(){throw new Error("Alias nodes cannot have tags")}})}resolve(t,n){let r;n?.aliasResolveCache?r=n.aliasResolveCache:(r=[],Yc(t,{Node:(s,l)=>{(ol(l)||VD(l))&&r.push(l)}}),n&&(n.aliasResolveCache=r));let i;for(const s of r){if(s===this)break;s.anchor===this.source&&(i=s)}return i}toJSON(t,n){if(!n)return{source:this.source};const{anchors:r,doc:i,maxAliasCount:s}=n,l=this.resolve(i,n);if(!l){const f=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new ReferenceError(f)}let c=r.get(l);if(c||(Jr(l,null,n),c=r.get(l)),c?.res===void 0){const f="This should not happen: Alias anchor was not resolved?";throw new ReferenceError(f)}if(s>=0&&(c.count+=1,c.aliasCount===0&&(c.aliasCount=$p(i,l,r)),c.count*c.aliasCount>s)){const f="Excessive alias count indicates a resource exhaustion attack";throw new ReferenceError(f)}return c.res}toString(t,n,r){const i=`*${this.source}`;if(t){if(ZD(this.source),t.options.verifyAliasOrder&&!t.anchors.has(this.source)){const s=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new Error(s)}if(t.implicitKey)return`${i} `}return i}}function $p(e,t,n){if(ol(t)){const r=t.resolve(e),i=n&&r&&n.get(r);return i?i.count*i.aliasCount:0}else if(en(t)){let r=0;for(const i of t.items){const s=$p(e,i,n);s>r&&(r=s)}return r}else if(nn(t)){const r=$p(e,t.key,n),i=$p(e,t.value,n);return Math.max(r,i)}return 1}const QD=e=>!e||typeof e!="function"&&typeof e!="object";class Be extends b1{constructor(t){super(Gi),this.value=t}toJSON(t,n){return n?.keep?this.value:Jr(this.value,t,n)}toString(){return String(this.value)}}Be.BLOCK_FOLDED="BLOCK_FOLDED";Be.BLOCK_LITERAL="BLOCK_LITERAL";Be.PLAIN="PLAIN";Be.QUOTE_DOUBLE="QUOTE_DOUBLE";Be.QUOTE_SINGLE="QUOTE_SINGLE";const rX="tag:yaml.org,2002:";function iX(e,t,n){if(t){const r=n.filter(s=>s.tag===t),i=r.find(s=>!s.format)??r[0];if(!i)throw new Error(`Tag ${t} not found`);return i}return n.find(r=>r.identify?.(e)&&!r.format)}function Ld(e,t,n){if(Rg(e)&&(e=e.contents),tn(e))return e;if(nn(e)){const g=n.schema[Es].createNode?.(n.schema,null,n);return g.items.push(e),g}(e instanceof String||e instanceof Number||e instanceof Boolean||typeof BigInt<"u"&&e instanceof BigInt)&&(e=e.valueOf());const{aliasDuplicateObjects:r,onAnchor:i,onTagObj:s,schema:l,sourceObjects:c}=n;let f;if(r&&e&&typeof e=="object"){if(f=c.get(e),f)return f.anchor??(f.anchor=i(e)),new x1(f.anchor);f={anchor:null,node:null},c.set(e,f)}t?.startsWith("!!")&&(t=rX+t.slice(2));let h=iX(e,t,l.tags);if(!h){if(e&&typeof e.toJSON=="function"&&(e=e.toJSON()),!e||typeof e!="object"){const g=new Be(e);return f&&(f.node=g),g}h=e instanceof Map?l[Es]:Symbol.iterator in Object(e)?l[Zc]:l[Es]}s&&(s(h),delete n.onTagObj);const p=h?.createNode?h.createNode(n.schema,e,n):typeof h?.nodeClass?.from=="function"?h.nodeClass.from(n.schema,e,n):new Be(e);return t?p.tag=t:h.default||(p.tag=h.tag),f&&(f.node=p),p}function pm(e,t,n){let r=n;for(let i=t.length-1;i>=0;--i){const s=t[i];if(typeof s=="number"&&Number.isInteger(s)&&s>=0){const l=[];l[s]=r,r=l}else r=new Map([[s,r]])}return Ld(r,void 0,{aliasDuplicateObjects:!1,keepUndefined:!1,onAnchor:()=>{throw new Error("This should not happen, please report a bug.")},schema:e,sourceObjects:new Map})}const vd=e=>e==null||typeof e=="object"&&!!e[Symbol.iterator]().next().done;class XD extends b1{constructor(t,n){super(t),Object.defineProperty(this,"schema",{value:n,configurable:!0,enumerable:!1,writable:!0})}clone(t){const n=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return t&&(n.schema=t),n.items=n.items.map(r=>tn(r)||nn(r)?r.clone(t):r),this.range&&(n.range=this.range.slice()),n}addIn(t,n){if(vd(t))this.add(n);else{const[r,...i]=t,s=this.get(r,!0);if(en(s))s.addIn(i,n);else if(s===void 0&&this.schema)this.set(r,pm(this.schema,i,n));else throw new Error(`Expected YAML collection at ${r}. Remaining path: ${i}`)}}deleteIn(t){const[n,...r]=t;if(r.length===0)return this.delete(n);const i=this.get(n,!0);if(en(i))return i.deleteIn(r);throw new Error(`Expected YAML collection at ${n}. Remaining path: ${r}`)}getIn(t,n){const[r,...i]=t,s=this.get(r,!0);return i.length===0?!n&&kt(s)?s.value:s:en(s)?s.getIn(i,n):void 0}hasAllNullValues(t){return this.items.every(n=>{if(!nn(n))return!1;const r=n.value;return r==null||t&&kt(r)&&r.value==null&&!r.commentBefore&&!r.comment&&!r.tag})}hasIn(t){const[n,...r]=t;if(r.length===0)return this.has(n);const i=this.get(n,!0);return en(i)?i.hasIn(r):!1}setIn(t,n){const[r,...i]=t;if(i.length===0)this.set(r,n);else{const s=this.get(r,!0);if(en(s))s.setIn(i,n);else if(s===void 0&&this.schema)this.set(r,pm(this.schema,i,n));else throw new Error(`Expected YAML collection at ${r}. Remaining path: ${i}`)}}}const aX=e=>e.replace(/^(?!$)(?: $)?/gm,"#");function Ca(e,t){return/^\n+$/.test(e)?e.substring(1):t?e.replace(/^(?! *$)/gm,t):e}const _o=(e,t,n)=>e.endsWith(`
97
97
  `)?Ca(n,t):n.includes(`
98
98
  `)?`