@sentry/junior-dashboard 0.255.0 → 0.256.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.
package/dist/client.js CHANGED
@@ -67,7 +67,7 @@ ${u}
67
67
 
68
68
  Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let i of e.seen.entries()){let s=i[1];if(t===i[0]){o(i);continue}if(e.external){let c=e.external.registry.get(i[0])?.id;if(t!==i[0]&&c){o(i);continue}}if(e.metadataRegistry.get(i[0])?.id){o(i);continue}if(s.cycle){o(i);continue}if(s.count>1&&e.reused==="ref"){o(i);continue}}e.external&&(e.sharedDefsExtractedFor=e.external)}function P8(e){let t=e.anyOf;if(!Array.isArray(t)||t.length===0||e.type!==void 0)return;let a=[];for(let r of t){if(!r||typeof r!="object")return;P8(r);let n=Object.keys(r);if(n.length!==1||n[0]!=="type")return;let o=r.type;for(let i of Array.isArray(o)?o:[o]){if(typeof i!="string")return;a.includes(i)||a.push(i)}}delete e.anyOf,e.type=a.length===1?a[0]:a}var D8=new Set(["type","properties","required","additionalProperties"]),A8=["oneOf","anyOf"];function $8(e){let t=e.additionalProperties;return t===void 0||t===!1||typeof t!="object"||t===null?null:Object.keys(t).length?t:null}function dD(e){let t=[];for(let o of e){if(typeof o!="object"||o.type!=="object")return null;for(let i in o)if(!D8.has(i))return null;t.push(o)}let a={},r=new Set;for(let o of t){for(let i in o.properties){if(Object.prototype.hasOwnProperty.call(a,i))continue;let s=[];for(let c of t){let d=c.properties?.[i]??$8(c);d!=null&&(s.some(f=>JSON.stringify(f)===JSON.stringify(d))||s.push(d))}let u=s.length===1?s[0]:dD(s)??{allOf:s};sn(a,i,u)}for(let i of o.required??[])r.add(i)}let n={type:"object",properties:a};if(r.size&&(n.required=[...r]),t.every(o=>o.additionalProperties===!1))n.additionalProperties=!1;else{let o=[];for(let i of t){let s=$8(i);s&&!o.some(u=>JSON.stringify(u)===JSON.stringify(s))&&o.push(s)}o.length===1?n.additionalProperties=o[0]:o.length>1&&(n.additionalProperties={allOf:o})}return n}function Ehe(e){let t=e.allOf;if(!Array.isArray(t)||t.length<2)return;for(let n of D8)if(n in e)return;let a=t.filter(n=>A8.some(o=>Array.isArray(n[o]))),r=null;if(!a.length)r=dD(t);else{let n=a[0],o=A8.find(u=>Array.isArray(n[u]));if(Object.keys(n).length!==1)return;let i=t.filter(u=>u!==n),s=n[o].map(u=>dD([...i,u]));if(s.some(u=>!u))return;r={[o]:s}}r&&(delete e.allOf,Sx(e,r))}function Fd(e,t){let a=e.seen.get(t);if(!a)throw new Error("Unprocessed schema. This is a bug in Zod.");let r=s=>{let u=e.seen.get(s);if(u.ref===null)return;let c=u.def??u.schema,d={...c},f=u.ref;if(u.ref=null,f){r(f);let h=e.seen.get(f),p=h.schema;if(p.$ref&&(e.target==="draft-07"||e.target==="draft-04"||e.target==="openapi-3.0")?(c.allOf=c.allOf??[],c.allOf.push(p)):Sx(c,p),Sx(c,d),s._zod.parent===f)for(let x in c)x==="$ref"||x==="allOf"||x in d||delete c[x];if(p.$ref&&h.def)for(let x in c)x==="$ref"||x==="allOf"||x in h.def&&JSON.stringify(c[x])===JSON.stringify(h.def[x])&&delete c[x]}let m=s._zod.parent;if(m&&m!==f){r(m);let h=e.seen.get(m);if(h?.schema.$ref&&(c.$ref=h.schema.$ref,h.def))for(let p in c)p==="$ref"||p==="allOf"||p in h.def&&JSON.stringify(c[p])===JSON.stringify(h.def[p])&&delete c[p]}e.override({zodSchema:s,jsonSchema:c,path:u.path??[]})};if(!e.external||e.sharedEmitDoneFor!==e.external){for(let s of[...e.seen.entries()].reverse())r(s[0]);if(e.target!=="openapi-3.0")for(let s of e.seen.entries())P8(s[1].def??s[1].schema);for(let s of e.deferred)s();if(e.intersections.length){let s=new Map;for(let u of e.seen.values())for(let c of[u.schema,u.def]){let d=c?.allOf;if(!Array.isArray(d))continue;let f=s.get(d);f?f.push(c):s.set(d,[c])}for(let u of e.intersections)for(let c of s.get(u)??[])Ehe(c)}}let n={};if(e.target==="draft-2020-12"?n.$schema="https://json-schema.org/draft/2020-12/schema":e.target==="draft-07"?n.$schema="http://json-schema.org/draft-07/schema#":e.target==="draft-04"?n.$schema="http://json-schema.org/draft-04/schema#":e.target,e.external?.uri){let s=e.external.registry.get(t)?.id;if(!s)throw new Error("Schema is missing an `id` property");n.$id=e.external.uri(s)}Sx(n,a.defId?a.schema:a.def??a.schema);let o=e.metadataRegistry.get(t)?.id;o!==void 0&&n.id===o&&delete n.id;let i=e.external?.defs??{};if(!e.external||e.sharedEmitDoneFor!==e.external)for(let s of e.seen.entries()){let u=s[1];u.def&&u.defId&&(u.def.id===u.defId&&delete u.def.id,sn(i,u.defId,u.def))}e.external&&(e.sharedEmitDoneFor=e.external),e.external||Object.keys(i).length>0&&(e.target==="draft-2020-12"?n.$defs=i:n.definitions=i);try{let s=JSON.parse(JSON.stringify(n));return Object.defineProperty(s,"~standard",{value:{...t["~standard"],jsonSchema:{input:vg(t,"input",e.processors),output:vg(t,"output",e.processors)}},enumerable:!1,writable:!1}),s}catch{throw new Error("Error converting schema to JSON.")}}function Ro(e,t){let a=t??{seen:new Set};if(a.seen.has(e))return!1;a.seen.add(e);let r=e._zod.def;if(r.type==="transform")return!0;if(r.type==="array")return Ro(r.element,a);if(r.type==="set")return Ro(r.valueType,a);if(r.type==="lazy")return Ro(r.getter(),a);if(r.type==="promise"||r.type==="optional"||r.type==="nonoptional"||r.type==="nullable"||r.type==="readonly"||r.type==="default"||r.type==="prefault"||r.type==="catch")return Ro(r.innerType,a);if(r.type==="intersection")return Ro(r.left,a)||Ro(r.right,a);if(r.type==="record"||r.type==="map")return Ro(r.keyType,a)||Ro(r.valueType,a);if(r.type==="pipe")return e._zod.traits.has("$ZodCodec")?!0:Ro(r.in,a)||Ro(r.out,a);if(r.type==="object"){for(let n in r.shape)if(Ro(r.shape[n],a))return!0;return!1}if(r.type==="union"){for(let n of r.options)if(Ro(n,a))return!0;return!1}if(r.type==="tuple"){for(let n of r.items)if(Ro(n,a))return!0;return!!(r.rest&&Ro(r.rest,a))}return!1}var fD=(e,t={})=>a=>{let r=jd({...a,processors:t});return ra(e,r),Bd(r,e),Fd(r,e)},vg=(e,t,a={})=>r=>{let{libraryOptions:n,target:o}=r??{},i=jd({...n??{},target:o,io:t,processors:a});return ra(e,i),Bd(i,e),Fd(i,e)};var Mhe={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},hD=(e,t,a,r)=>{let n=a;n.type="string";let{minimum:o,maximum:i,format:s,patterns:u,contentEncoding:c,laxFormat:d}=e._zod.bag;if(typeof o=="number"&&(n.minLength=o),typeof i=="number"&&(n.maxLength=i),s&&(n.format=Mhe[s]??s,n.format===""&&delete n.format,(s==="time"||d)&&delete n.format),c&&(n.contentEncoding=c),u&&u.size>0){let f=[...u];f.length===1?n.pattern=f[0].source:f.length>1&&(n.allOf=[...f.map(m=>({...t.target==="draft-07"||t.target==="draft-04"||t.target==="openapi-3.0"?{type:"string"}:{},pattern:m.source}))])}},gD=(e,t,a,r)=>{let n=a,{minimum:o,maximum:i,format:s,multipleOf:u,exclusiveMaximum:c,exclusiveMinimum:d}=e._zod.bag;typeof s=="string"&&s.includes("int")?n.type="integer":n.type="number";let f=typeof d=="number"&&d>=(o??Number.NEGATIVE_INFINITY),m=typeof c=="number"&&c<=(i??Number.POSITIVE_INFINITY),h=t.target==="draft-04"||t.target==="openapi-3.0";f?h?(n.minimum=d,n.exclusiveMinimum=!0):n.exclusiveMinimum=d:typeof o=="number"&&(n.minimum=o),m?h?(n.maximum=c,n.exclusiveMaximum=!0):n.exclusiveMaximum=c:typeof i=="number"&&(n.maximum=i),typeof u=="number"&&(Number.isFinite(u)&&u!==0?n.multipleOf=Math.abs(u):ir(e,t,n,r,`A multipleOf divisor of ${u} cannot be represented in JSON Schema`))},vD=(e,t,a,r)=>{a.type="boolean"},yD=(e,t,a,r)=>{ir(e,t,a,r,"BigInt cannot be represented in JSON Schema")},bD=(e,t,a,r)=>{ir(e,t,a,r,"Symbols cannot be represented in JSON Schema")},xD=(e,t,a,r)=>{t.target==="openapi-3.0"?(a.type="string",a.nullable=!0,a.enum=[null]):a.type="null"},SD=(e,t,a,r)=>{ir(e,t,a,r,"Undefined cannot be represented in JSON Schema")},wD=(e,t,a,r)=>{ir(e,t,a,r,"Void cannot be represented in JSON Schema")},CD=(e,t,a,r)=>{a.not={}},kD=(e,t,a,r)=>{},ID=(e,t,a,r)=>{},LD=(e,t,a,r)=>{ir(e,t,a,r,"Date cannot be represented in JSON Schema")},TD=(e,t,a,r)=>{let n=e._zod.def,o=Kb(n.entries);if(o.length===0){a.not={};return}o.every(i=>typeof i=="number")&&(a.type="number"),o.every(i=>typeof i=="string")&&(a.type="string"),a.enum=o},_D=(e,t,a,r)=>{let n=e._zod.def;if(n.values.length===0){a.not={};return}let o=[];for(let i of n.values)if(i===void 0){if(ir(e,t,a,r,"Literal `undefined` cannot be represented in JSON Schema"))return}else if(typeof i=="bigint"){if(ir(e,t,a,r,"BigInt literals cannot be represented in JSON Schema"))return;o.push(Number(i))}else o.push(i);if(o.length!==0)if(o.length===1){let i=o[0];a.type=i===null?"null":typeof i,t.target==="draft-04"||t.target==="openapi-3.0"?a.enum=[i]:a.const=i}else o.every(i=>typeof i=="number")&&(a.type="number"),o.every(i=>typeof i=="string")&&(a.type="string"),o.every(i=>typeof i=="boolean")&&(a.type="boolean"),o.every(i=>i===null)&&(a.type="null"),a.enum=o},ND=(e,t,a,r)=>{ir(e,t,a,r,"NaN cannot be represented in JSON Schema")},RD=(e,t,a,r)=>{let n=a,o=e._zod.pattern;if(!o)throw new Error("Pattern not found in template literal");n.type="string",n.pattern=o.source},AD=(e,t,a,r)=>{let n=a,o={type:"string",format:"binary",contentEncoding:"binary"},{minimum:i,maximum:s,mime:u}=e._zod.bag;i!==void 0&&(o.minLength=i),s!==void 0&&(o.maxLength=s),u?u.length===1?(o.contentMediaType=u[0],Object.assign(n,o)):(Object.assign(n,o),n.anyOf=u.map(c=>({contentMediaType:c}))):Object.assign(n,o)},$D=(e,t,a,r)=>{a.type="boolean"},PD=(e,t,a,r)=>{ir(e,t,a,r,"Custom types cannot be represented in JSON Schema")},DD=(e,t,a,r)=>{ir(e,t,a,r,"Function types cannot be represented in JSON Schema")},ED=(e,t,a,r)=>{ir(e,t,a,r,"Transforms cannot be represented in JSON Schema")},MD=(e,t,a,r)=>{ir(e,t,a,r,"Map cannot be represented in JSON Schema")},OD=(e,t,a,r)=>{ir(e,t,a,r,"Set cannot be represented in JSON Schema")},zD=(e,t,a,r)=>{let n=a,o=e._zod.def,{minimum:i,maximum:s}=e._zod.bag;typeof i=="number"&&(n.minItems=i),typeof s=="number"&&(n.maxItems=s),n.type="array",n.items=ra(o.element,t,{...r,path:[...r.path,"items"]})};function wx(e){let t=e._zod.def;return t.type==="pipe"&&t.in._zod.traits.has("$ZodTransform")?wx(t.out):t.type==="catch"?wx(t.innerType):e._zod.optin}var UD=(e,t,a,r)=>{let n=a,o=e._zod.def,i=o.shape;if(Object.getOwnPropertySymbols(i).length&&ir(e,t,n,r,"Symbol keys cannot be represented in JSON Schema"))return;n.type="object",n.properties={};for(let d in i)sn(n.properties,d,ra(i[d],t,{...r,path:[...r.path,"properties",d]}));let u=new Set(Object.keys(i)),c=new Set([...u].filter(d=>{let f=o.shape[d];return t.io==="input"?wx(f)===void 0:f._zod.optout===void 0}));c.size>0&&(n.required=Array.from(c)),o.catchall?._zod.def.type==="never"?n.additionalProperties=!1:o.catchall?o.catchall&&(n.additionalProperties=ra(o.catchall,t,{...r,path:[...r.path,"additionalProperties"]})):t.io==="output"&&(n.additionalProperties=!1)},Jk=(e,t,a,r)=>{let n=e._zod.def,o=n.inclusive===!1,i=n.options.map((s,u)=>ra(s,t,{...r,path:[...r.path,o?"oneOf":"anyOf",u]}));o?a.oneOf=i:a.anyOf=i},jD=(e,t,a,r)=>{let n=e._zod.def,o=ra(n.left,t,{...r,path:[...r.path,"allOf",0]}),i=ra(n.right,t,{...r,path:[...r.path,"allOf",1]}),s=c=>"allOf"in c&&Object.keys(c).length===1,u=[...s(o)?o.allOf:[o],...s(i)?i.allOf:[i]];a.allOf=u,t.intersections.push(u)},BD=(e,t,a,r)=>{let n=a,o=e._zod.def;n.type="array";let i=t.target==="draft-2020-12"?"prefixItems":"items",s=t.target==="draft-2020-12"||t.target==="openapi-3.0"?"items":"additionalItems",u=o.items.map((v,x)=>ra(v,t,{...r,path:[...r.path,i,x]})),c=o.rest?ra(o.rest,t,{...r,path:[...r.path,s,...t.target==="openapi-3.0"?[o.items.length]:[]]}):null,d=o.items.length;for(;d>0;){let v=o.items[d-1];if(!(t.io==="input"?wx(v)!==void 0:v._zod.optout==="optional"))break;d--}let f=o.items.length,m=!o.rest;t.target==="draft-2020-12"?(n.prefixItems=u,m?n.items=!1:c&&(n.items=c),d>0&&(n.minItems=d),m&&(n.maxItems=f)):t.target==="openapi-3.0"?(n.items={anyOf:u},c&&n.items.anyOf.push(c),d>0&&(n.minItems=d),m&&(n.maxItems=f)):(n.items=u,m?n.additionalItems=!1:c&&(n.additionalItems=c),d>0&&(n.minItems=d),m&&(n.maxItems=f));let{minimum:h,maximum:p}=e._zod.bag;typeof h=="number"&&(n.minItems=h),typeof p=="number"&&(n.maxItems=p)};function mD(e,t,a){if(t.$ref){if(a.has(t))return t;a.add(t);let p=e.get(t)?.def;if(!p)return t;let v=mD(e,p,a);return v===p?t:v}for(let p of["anyOf","oneOf"]){let v=t[p];if(!Array.isArray(v))continue;let x=v.map(g=>mD(e,g,a));x.some((g,y)=>g!==v[y])&&(t={...t,[p]:x})}let r=Array.isArray(t.type)?t.type:[t.type],n=!r.includes("string")&&r.some(p=>p==="number"||p==="integer"),o=t.enum??(t.const!==void 0?[t.const]:void 0);if(!n&&!o?.some(p=>typeof p=="number"))return t;let{minimum:i,maximum:s,exclusiveMinimum:u,exclusiveMaximum:c,multipleOf:d,format:f,id:m,...h}=t;return h.enum?h.enum=h.enum.map(p=>typeof p=="number"?String(p):p):typeof h.const=="number"&&(h.const=String(h.const)),n&&(h.type="string",o||(h.pattern=(r.includes("number")?Od:rx).source)),h}var pD=new WeakMap;function Ohe(e){let t=new Map;for(let r of e.seen.values())r.def&&!t.has(r.schema)&&t.set(r.schema,r);let a=new Map;for(let r of pD.get(e)??[]){let n=e.seen.get(r),o=(n?.def??n?.schema)?.propertyNames;if(!o||o===!0||a.has(o))continue;let i=mD(t,o,new Set);i!==o&&a.set(o,i)}if(a.size)for(let r of e.seen.values())for(let n of[r.schema,r.def]){let o=n&&a.get(n.propertyNames);o&&(n.propertyNames=o)}}var FD=(e,t,a,r)=>{let n=a,o=e._zod.def;n.type="object";let i=o.keyType,u=i._zod.bag?.patterns;if(o.mode==="loose"&&u&&u.size>0){let f=ra(o.valueType,t,{...r,path:[...r.path,"patternProperties","*"]});n.patternProperties={};for(let m of u)sn(n.patternProperties,m.source,f)}else{if(t.target==="draft-07"||t.target==="draft-2020-12"){n.propertyNames=ra(o.keyType,t,{...r,path:[...r.path,"propertyNames"]});let f=pD.get(t);f||(f=[],pD.set(t,f),t.deferred.push(()=>Ohe(t))),f.push(e)}n.additionalProperties=ra(o.valueType,t,{...r,path:[...r.path,"additionalProperties"]})}let c=i._zod.values,d=t.io==="input"&&wx(o.valueType)!==void 0;if(c&&!o.partial&&!d){let f=[...c].filter(m=>typeof m=="string"||typeof m=="number");f.length>0&&(n.required=f.map(String))}},HD=(e,t,a,r)=>{let n=e._zod.def,o=ra(n.innerType,t,r),i=t.seen.get(e);t.target==="openapi-3.0"?(i.ref=n.innerType,a.nullable=!0):a.anyOf=[o,{type:"null"}]},VD=(e,t,a,r)=>{let n=e._zod.def;ra(n.innerType,t,r);let o=t.seen.get(e);o.ref=n.innerType},qD=Symbol();function E8(e,t,a,r,n){let o=!1,i=JSON.stringify(e,(s,u)=>typeof u!="bigint"?u:(o=!0,null));return o?(ir(t,a,r,n,"BigInt defaults cannot be represented in JSON Schema"),qD):JSON.parse(i)}var ZD=(e,t,a,r)=>{let n=e._zod.def;ra(n.innerType,t,r);let o=t.seen.get(e);o.ref=n.innerType;let i=E8(n.defaultValue,e,t,a,r);i!==qD&&(a.default=i)},GD=(e,t,a,r)=>{let n=e._zod.def;ra(n.innerType,t,r);let o=t.seen.get(e);if(o.ref=n.innerType,t.io!=="input")return;let i=E8(n.defaultValue,e,t,a,r);i!==qD&&(a._prefault=i)},KD=(e,t,a,r)=>{let n=e._zod.def;ra(n.innerType,t,r);let o=t.seen.get(e);o.ref=n.innerType;let i;try{i=n.catchValue(void 0)}catch{ir(e,t,a,r,"Dynamic catch values are not supported in JSON Schema");return}a.default=i},WD=(e,t,a,r)=>{let n=e._zod.def,o=n.in._zod.traits.has("$ZodTransform"),i=t.io==="input"?o?n.out:n.in:n.out;ra(i,t,r);let s=t.seen.get(e);s.ref=i},JD=(e,t,a,r)=>{let n=e._zod.def;ra(n.innerType,t,r);let o=t.seen.get(e);o.ref=n.innerType,a.readOnly=!0},QD=(e,t,a,r)=>{let n=e._zod.def;ra(n.innerType,t,r);let o=t.seen.get(e);o.ref=n.innerType},Qk=(e,t,a,r)=>{let n=e._zod.def;ra(n.innerType,t,r);let o=t.seen.get(e);o.ref=n.innerType},XD=(e,t,a,r)=>{let n=e._zod.innerType;ra(n,t,r);let o=t.seen.get(e);o.ref=n},Wk={string:hD,number:gD,boolean:vD,bigint:yD,symbol:bD,null:xD,undefined:SD,void:wD,never:CD,any:kD,unknown:ID,date:LD,enum:TD,literal:_D,nan:ND,template_literal:RD,file:AD,success:$D,custom:PD,function:DD,transform:ED,map:MD,set:OD,array:zD,object:UD,union:Jk,intersection:jD,tuple:BD,record:FD,nullable:HD,nonoptional:VD,default:ZD,prefault:GD,catch:KD,pipe:WD,readonly:JD,promise:QD,optional:Qk,lazy:XD};function Xk(e,t){if("_idmap"in e){let r=e,n=jd({...t,processors:Wk}),o={};for(let u of r._idmap.entries()){let[c,d]=u;ra(d,n)}let i={},s={registry:r,uri:t?.uri,defs:o};n.external=s;for(let u of r._idmap.entries()){let[c,d]=u;Bd(n,d),sn(i,c,Fd(n,d))}if(Object.keys(o).length>0){let u=n.target==="draft-2020-12"?"$defs":"definitions";i.__shared={[u]:o}}return{schemas:i}}let a=jd({...t,processors:Wk});return ra(e,a),Bd(a,e),Fd(a,e)}var Yk=class{get metadataRegistry(){return this.ctx.metadataRegistry}get target(){return this.ctx.target}get unrepresentable(){return this.ctx.unrepresentable}get override(){return this.ctx.override}get io(){return this.ctx.io}get counter(){return this.ctx.counter}set counter(t){this.ctx.counter=t}get seen(){return this.ctx.seen}constructor(t){let a=t?.target??"draft-2020-12";a==="draft-4"&&(a="draft-04"),a==="draft-7"&&(a="draft-07"),this.ctx=jd({processors:Wk,target:a,...t?.metadata&&{metadata:t.metadata},...t?.unrepresentable&&{unrepresentable:t.unrepresentable},...t?.override&&{override:t.override},...t?.io&&{io:t.io}})}process(t,a={path:[],schemaPath:[]}){return ra(t,this.ctx,a)}emit(t,a){a&&(a.cycles&&(this.ctx.cycles=a.cycles),a.reused&&(this.ctx.reused=a.reused),a.external&&(this.ctx.external=a.external)),this.ctx.sharedDefsExtractedFor=void 0,this.ctx.sharedEmitDoneFor=void 0,Bd(this.ctx,t);let r=Fd(this.ctx,t),{"~standard":n,...o}=r;return o}};var M8={};var Lg={};Ml(Lg,{ZodAny:()=>bE,ZodArray:()=>CE,ZodBase64:()=>y1,ZodBase64URL:()=>b1,ZodBigInt:()=>kg,ZodBigIntFormat:()=>w1,ZodBoolean:()=>Cg,ZodCIDRv4:()=>g1,ZodCIDRv6:()=>v1,ZodCUID:()=>u1,ZodCUID2:()=>c1,ZodCatch:()=>VE,ZodCodec:()=>$x,ZodCreditCard:()=>fE,ZodCustom:()=>Px,ZodCustomStringFormat:()=>Sg,ZodDate:()=>Lx,ZodDefault:()=>zE,ZodDiscriminatedUnion:()=>IE,ZodE164:()=>x1,ZodEmail:()=>o1,ZodEmoji:()=>s1,ZodEnum:()=>bg,ZodExactOptional:()=>L1,ZodFile:()=>DE,ZodFunction:()=>eM,ZodGUID:()=>i1,ZodIPv4:()=>p1,ZodIPv6:()=>h1,ZodISODate:()=>Vd,ZodISODateTime:()=>Hd,ZodISODuration:()=>Zd,ZodISOTime:()=>qd,ZodIntersection:()=>LE,ZodJWT:()=>S1,ZodKSUID:()=>m1,ZodLazy:()=>QE,ZodLiteral:()=>PE,ZodMAC:()=>dE,ZodMap:()=>AE,ZodNaN:()=>ZE,ZodNanoID:()=>l1,ZodNever:()=>SE,ZodNonOptional:()=>T1,ZodNull:()=>vE,ZodNullable:()=>OE,ZodNumber:()=>wg,ZodNumberFormat:()=>Om,ZodObject:()=>_x,ZodOptional:()=>Rx,ZodPipe:()=>Ax,ZodPrefault:()=>jE,ZodPreprocess:()=>GE,ZodPromise:()=>YE,ZodReadonly:()=>KE,ZodRecord:()=>yg,ZodSet:()=>$E,ZodString:()=>xg,ZodStringFormat:()=>va,ZodSuccess:()=>HE,ZodSymbol:()=>hE,ZodTemplateLiteral:()=>JE,ZodTransform:()=>EE,ZodTuple:()=>_E,ZodType:()=>st,ZodULID:()=>d1,ZodURL:()=>Ix,ZodUUID:()=>au,ZodUndefined:()=>gE,ZodUnion:()=>Nx,ZodUnknown:()=>xE,ZodVoid:()=>wE,ZodXID:()=>f1,ZodXor:()=>kE,_ZodString:()=>r1,_default:()=>UE,_function:()=>Z9,any:()=>C9,array:()=>Tx,base64:()=>o9,base64url:()=>i9,bigint:()=>y9,boolean:()=>pE,catch:()=>qE,check:()=>G9,cidrv4:()=>n9,cidrv6:()=>r9,codec:()=>F9,creditCard:()=>l9,cuid:()=>W8,cuid2:()=>J8,custom:()=>K9,date:()=>I9,describe:()=>W9,discriminatedUnion:()=>A9,e164:()=>s9,email:()=>U8,emoji:()=>G8,enum:()=>k1,exactOptional:()=>ME,file:()=>z9,float32:()=>p9,float64:()=>h9,function:()=>Z9,guid:()=>j8,hash:()=>m9,hex:()=>f9,hostname:()=>d9,httpUrl:()=>Z8,instanceof:()=>Q9,int:()=>a1,int32:()=>g9,int64:()=>b9,intersection:()=>TE,invertCodec:()=>H9,ipv4:()=>e9,ipv6:()=>a9,json:()=>Y9,jwt:()=>u9,keyof:()=>L9,ksuid:()=>Y8,lazy:()=>XE,literal:()=>O9,looseObject:()=>N9,looseRecord:()=>P9,mac:()=>t9,map:()=>D9,meta:()=>J9,nan:()=>B9,nanoid:()=>K8,nativeEnum:()=>M9,never:()=>C1,nonoptional:()=>FE,null:()=>yE,nullable:()=>kx,nullish:()=>U9,number:()=>mE,object:()=>T9,optional:()=>Em,partialRecord:()=>$9,pipe:()=>n1,prefault:()=>BE,preprocess:()=>eZ,promise:()=>q9,readonly:()=>WE,record:()=>RE,refine:()=>tM,set:()=>E9,strictObject:()=>_9,string:()=>Cx,stringFormat:()=>c9,stringbool:()=>X9,success:()=>j9,superRefine:()=>aM,symbol:()=>S9,templateLiteral:()=>V9,transform:()=>I1,tuple:()=>NE,uint32:()=>v9,uint64:()=>x9,ulid:()=>Q8,undefined:()=>w9,union:()=>Ig,unknown:()=>Dm,url:()=>q8,uuid:()=>B8,uuidv4:()=>F8,uuidv6:()=>H8,uuidv7:()=>V8,void:()=>k9,xid:()=>X8,xor:()=>R9});var e1={};Ml(e1,{endsWith:()=>ug,gt:()=>eu,gte:()=>Ki,includes:()=>sg,length:()=>Pm,lowercase:()=>og,lt:()=>Yl,lte:()=>Gi,maxLength:()=>$m,maxSize:()=>Ud,mime:()=>cg,minLength:()=>mc,minSize:()=>tu,multipleOf:()=>zd,negative:()=>Vk,nonnegative:()=>Zk,nonpositive:()=>qk,normalize:()=>dg,overwrite:()=>fl,positive:()=>Hk,properties:()=>Kk,property:()=>Gk,regex:()=>rg,size:()=>Am,slugify:()=>hg,startsWith:()=>lg,toLowerCase:()=>mg,toUpperCase:()=>pg,trim:()=>fg,uppercase:()=>ig});var O8=new WeakSet([Object.prototype,Error.prototype]);function t1(e,t,a){Object.defineProperty(e,t,{configurable:!0,enumerable:!1,get(){let r=a(this);return Object.defineProperty(this,t,{value:r,configurable:!0,writable:!0}),r},set(r){Object.defineProperty(this,t,{value:r,configurable:!0,writable:!0})}})}var z8=(e,t)=>{tx.init(e,t),e.name="ZodError";let a=Object.getPrototypeOf(e);O8.has(a)||(O8.add(a),t1(a,"format",r=>n=>nx(r,n)),t1(a,"flatten",r=>n=>ax(r,n)),t1(a,"addIssue",r=>n=>{r.issues.push(n),r.message=JSON.stringify(r.issues,Kh,2)}),t1(a,"addIssues",r=>n=>{r.issues.push(...n),r.message=JSON.stringify(r.issues,Kh,2)}),Object.defineProperty(a,"isEmpty",{configurable:!0,enumerable:!1,get(){return this.issues.length===0}}))},Uhe=A("ZodError",z8),bi=A("ZodError",z8,void 0,{Parent:Error});var YD=Qh(bi),eE=Xh(bi),tE=Yh(bi),aE=eg(bi),nE=DC(bi),rE=EC(bi),oE=MC(bi),iE=OC(bi),sE=zC(bi),lE=UC(bi),uE=jC(bi),cE=BC(bi);function Bhe(){Lr.localeError||wn(gk())}function Mm(){Lr.memoizer||wn({memoizer:mx()})}var st=A("ZodType",(e,t)=>(Bhe(),Ke.init(e,t),e.def=t,e.type=t.type,e),{check(...e){let t=this.def;return this.clone(Z.mergeDefs(t,{checks:[...t.checks??[],...e.map(a=>typeof a=="function"?{_zod:{check:a,def:{check:"custom"},onattach:[]}}:a)]}),{parent:!0})},with(...e){return this.check(...e)},clone(e,t){return na(this,e,t)},brand(){return this},register(e,t){return e.add(this,t),this},refine(e,t){return this.check(tM(e,t))},superRefine(e,t){return this.check(aM(e,t))},overwrite(e){return this.check(fl(e))},optional(){return Em(this)},exactOptional(){return ME(this)},nullable(){return kx(this)},nullish(){return Em(kx(this))},nonoptional(e){return FE(this,e)},array(){return Tx(this)},or(e){return Ig([this,e])},and(e){return TE(this,e)},transform(e){return n1(this,I1(e))},default(e){return UE(this,e)},prefault(e){return BE(this,e)},catch(e){return qE(this,e)},pipe(e){return n1(this,e)},readonly(){return WE(this)},describe(e){let t=this.clone();return Ur.add(t,{description:e}),t},meta(...e){if(e.length===0)return Ur.get(this);let t=this.clone();return Ur.add(t,e[0]),t},isOptional(){return this.safeParse(void 0).success},isNullable(){return this.safeParse(null).success},apply(e,...t){return t.length===0?e(this):e(this,...t)},get"~standard"(){return Z.hide(this,"~standard",{...XC(this),jsonSchema:{input:vg(this,"input"),output:vg(this,"output")}})},set"~standard"(e){Z.own(this,"~standard",e)},parse:function e(t,a){return YD(this,t,a,{callee:e})},parseAsync:async function e(t,a){return await eE(this,t,a,{callee:e})},safeParse(e,t){return tE(this,e,t)},async safeParseAsync(e,t){return aE(this,e,t)},get spa(){return this?.safeParseAsync},set spa(e){Z.own(this,"spa",e)},encode:function e(t,a){return nE(this,t,a,{callee:e})},decode:function e(t,a){return rE(this,t,a,{callee:e})},encodeAsync:async function e(t,a){return await oE(this,t,a,{callee:e})},decodeAsync:async function e(t,a){return await iE(this,t,a,{callee:e})},safeEncode(e,t){return sE(this,e,t)},safeDecode(e,t){return lE(this,e,t)},async safeEncodeAsync(e,t){return uE(this,e,t)},async safeDecodeAsync(e,t){return cE(this,e,t)},toJSONSchema(e){return fD(this,{})(e)},get description(){return Ur.get(this)?.description},get _def(){return this._zod.def}}),r1=A("_ZodString",(e,t)=>{Lm.init(e,t),st.init(e,t),e._zod.processJSONSchema=(r,n,o)=>hD(e,r,n,o);let a=e._zod.bag;e.format=a.format??null,e.minLength=a.minimum??null,e.maxLength=a.maximum??null},{regex(...e){return this.check(rg(...e))},includes(...e){return this.check(sg(...e))},startsWith(...e){return this.check(lg(...e))},endsWith(...e){return this.check(ug(...e))},min(...e){return this.check(mc(...e))},max(...e){return this.check($m(...e))},length(...e){return this.check(Pm(...e))},nonempty(...e){return this.check(mc(1,...e))},lowercase(e){return this.check(og(e))},uppercase(e){return this.check(ig(e))},trim(){return this.check(fg())},normalize(...e){return this.check(dg(...e))},toLowerCase(){return this.check(mg())},toUpperCase(){return this.check(pg())},slugify(){return this.check(hg())}}),xg=A("ZodString",(e,t)=>{Lm.init(e,t),r1.init(e,t)},{email(e){return this.check(wk(o1,e))},url(e){return this.check(gx(Ix,e))},jwt(e){return this.check(Fk(S1,e))},emoji(e){return this.check(_k(s1,e))},guid(e){return this.check(Ck(i1,e))},uuid(e){return this.check(kk(au,e))},uuidv4(e){return this.check(Ik(au,e))},uuidv6(e){return this.check(Lk(au,e))},uuidv7(e){return this.check(Tk(au,e))},nanoid(e){return this.check(Nk(l1,e))},cuid(e){return this.check(Rk(u1,e))},cuid2(e){return this.check(Ak(c1,e))},ulid(e){return this.check($k(d1,e))},base64(e){return this.check(Uk(y1,e))},base64url(e){return this.check(jk(b1,e))},xid(e){return this.check(Pk(f1,e))},ksuid(e){return this.check(Dk(m1,e))},ipv4(e){return this.check(Ek(p1,e))},ipv6(e){return this.check(Mk(h1,e))},cidrv4(e){return this.check(Ok(g1,e))},cidrv6(e){return this.check(zk(v1,e))},e164(e){return this.check(Bk(x1,e))},datetime(e){return this.check(vx(Hd,e))},date(e){return this.check(yx(Vd,e))},time(e){return this.check(bx(qd,e))},duration(e){return this.check(xx(Zd,e))}});function Cx(e){return NP(xg,e)}var va=A("ZodStringFormat",(e,t)=>{la.init(e,t),r1.init(e,t)}),Hd=A("ZodISODateTime",(e,t)=>{x$.init(e,t),va.init(e,t)}),Vd=A("ZodISODate",(e,t)=>{S$.init(e,t),va.init(e,t)}),qd=A("ZodISOTime",(e,t)=>{w$.init(e,t),va.init(e,t)}),Zd=A("ZodISODuration",(e,t)=>{C$.init(e,t),va.init(e,t)}),o1=A("ZodEmail",(e,t)=>{u$.init(e,t),va.init(e,t)});function U8(e){return wk(o1,e)}var i1=A("ZodGUID",(e,t)=>{s$.init(e,t),va.init(e,t)});function j8(e){return Ck(i1,e)}var au=A("ZodUUID",(e,t)=>{l$.init(e,t),va.init(e,t)});function B8(e){return kk(au,e)}function F8(e){return Ik(au,e)}function H8(e){return Lk(au,e)}function V8(e){return Tk(au,e)}var Ix=A("ZodURL",(e,t)=>{f$.init(e,t),va.init(e,t)});function q8(e){return gx(Ix,e)}function Z8(e){return gx(Ix,{protocol:_o.httpProtocol,hostname:_o.domain,...Z.normalizeParams(e)})}var s1=A("ZodEmoji",(e,t)=>{m$.init(e,t),va.init(e,t)});function G8(e){return _k(s1,e)}var l1=A("ZodNanoID",(e,t)=>{p$.init(e,t),va.init(e,t)});function K8(e){return Nk(l1,e)}var u1=A("ZodCUID",(e,t)=>{h$.init(e,t),va.init(e,t)});function W8(e){return Rk(u1,e)}var c1=A("ZodCUID2",(e,t)=>{g$.init(e,t),va.init(e,t)});function J8(e){return Ak(c1,e)}var d1=A("ZodULID",(e,t)=>{v$.init(e,t),va.init(e,t)});function Q8(e){return $k(d1,e)}var f1=A("ZodXID",(e,t)=>{y$.init(e,t),va.init(e,t)});function X8(e){return Pk(f1,e)}var m1=A("ZodKSUID",(e,t)=>{b$.init(e,t),va.init(e,t)});function Y8(e){return Dk(m1,e)}var p1=A("ZodIPv4",(e,t)=>{k$.init(e,t),va.init(e,t)});function e9(e){return Ek(p1,e)}var dE=A("ZodMAC",(e,t)=>{L$.init(e,t),va.init(e,t)});function t9(e){return AP(dE,e)}var h1=A("ZodIPv6",(e,t)=>{I$.init(e,t),va.init(e,t)});function a9(e){return Mk(h1,e)}var g1=A("ZodCIDRv4",(e,t)=>{T$.init(e,t),va.init(e,t)});function n9(e){return Ok(g1,e)}var v1=A("ZodCIDRv6",(e,t)=>{_$.init(e,t),va.init(e,t)});function r9(e){return zk(v1,e)}var y1=A("ZodBase64",(e,t)=>{N$.init(e,t),va.init(e,t)});function o9(e){return Uk(y1,e)}var b1=A("ZodBase64URL",(e,t)=>{R$.init(e,t),va.init(e,t)});function i9(e){return jk(b1,e)}var x1=A("ZodE164",(e,t)=>{A$.init(e,t),va.init(e,t)});function s9(e){return Bk(x1,e)}var fE=A("ZodCreditCard",(e,t)=>{$$.init(e,t),va.init(e,t)});function l9(e){return $P(fE,e)}var S1=A("ZodJWT",(e,t)=>{P$.init(e,t),va.init(e,t)});function u9(e){return Fk(S1,e)}var Sg=A("ZodCustomStringFormat",(e,t)=>{D$.init(e,t),va.init(e,t)});function c9(e,t,a={}){return gg(Sg,e,t,a)}function d9(e){return gg(Sg,"hostname",_o.hostname,e)}function f9(e){return gg(Sg,"hex",_o.hex,e)}function m9(e,t){let a=t?.enc??"hex",r=`${e}_${a}`,n=_o[r];if(!n)throw new Error(`Unrecognized hash format: ${r}`);return gg(Sg,r,n,t)}var wg=A("ZodNumber",(e,t)=>{sk.init(e,t),st.init(e,t),e._zod.processJSONSchema=(r,n,o)=>gD(e,r,n,o);let a=e._zod.bag;e.minValue=Math.max(a.minimum??Number.NEGATIVE_INFINITY,a.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,e.maxValue=Math.min(a.maximum??Number.POSITIVE_INFINITY,a.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,e.isInt=(a.format??"").includes("int")||Number.isSafeInteger(a.multipleOf??.5),e.isFinite=!0,e.format=a.format??null},{gt(e,t){return this.check(eu(e,t))},gte(e,t){return this.check(Ki(e,t))},min(e,t){return this.check(Ki(e,t))},lt(e,t){return this.check(Yl(e,t))},lte(e,t){return this.check(Gi(e,t))},max(e,t){return this.check(Gi(e,t))},int(e){return this.check(a1(e))},safe(e){return this.check(a1(e))},positive(e){return this.check(eu(0,e))},nonnegative(e){return this.check(Ki(0,e))},negative(e){return this.check(Yl(0,e))},nonpositive(e){return this.check(Gi(0,e))},multipleOf(e,t){return this.check(zd(e,t))},step(e,t){return this.check(zd(e,t))},finite(){return this}});function mE(e){return DP(wg,e)}var Om=A("ZodNumberFormat",(e,t)=>{E$.init(e,t),wg.init(e,t)});function a1(e){return MP(Om,e)}function p9(e){return OP(Om,e)}function h9(e){return zP(Om,e)}function g9(e){return UP(Om,e)}function v9(e){return jP(Om,e)}var Cg=A("ZodBoolean",(e,t)=>{ux.init(e,t),st.init(e,t),e._zod.processJSONSchema=(a,r,n)=>vD(e,a,r,n)});function pE(e){return BP(Cg,e)}var kg=A("ZodBigInt",(e,t)=>{lk.init(e,t),st.init(e,t),e._zod.processJSONSchema=(r,n,o)=>yD(e,r,n,o);let a=e._zod.bag;e.minValue=a.minimum??null,e.maxValue=a.maximum??null,e.format=a.format??null},{gte(e,t){return this.check(Ki(e,t))},min(e,t){return this.check(Ki(e,t))},gt(e,t){return this.check(eu(e,t))},lt(e,t){return this.check(Yl(e,t))},lte(e,t){return this.check(Gi(e,t))},max(e,t){return this.check(Gi(e,t))},positive(e){return this.check(eu(BigInt(0),e))},negative(e){return this.check(Yl(BigInt(0),e))},nonpositive(e){return this.check(Gi(BigInt(0),e))},nonnegative(e){return this.check(Ki(BigInt(0),e))},multipleOf(e,t){return this.check(zd(e,t))}});function y9(e){return HP(kg,e)}var w1=A("ZodBigIntFormat",(e,t)=>{M$.init(e,t),kg.init(e,t)});function b9(e){return qP(w1,e)}function x9(e){return ZP(w1,e)}var hE=A("ZodSymbol",(e,t)=>{O$.init(e,t),st.init(e,t),e._zod.processJSONSchema=(a,r,n)=>bD(e,a,r,n)});function S9(e){return GP(hE,e)}var gE=A("ZodUndefined",(e,t)=>{z$.init(e,t),st.init(e,t),e._zod.processJSONSchema=(a,r,n)=>SD(e,a,r,n)});function w9(e){return KP(gE,e)}var vE=A("ZodNull",(e,t)=>{U$.init(e,t),st.init(e,t),e._zod.processJSONSchema=(a,r,n)=>xD(e,a,r,n)});function yE(e){return WP(vE,e)}var bE=A("ZodAny",(e,t)=>{j$.init(e,t),st.init(e,t),e._zod.processJSONSchema=(a,r,n)=>kD(e,a,r,n)});function C9(){return JP(bE)}var xE=A("ZodUnknown",(e,t)=>{B$.init(e,t),st.init(e,t),e._zod.processJSONSchema=(a,r,n)=>ID(e,a,r,n)});function Dm(){return QP(xE)}var SE=A("ZodNever",(e,t)=>{F$.init(e,t),st.init(e,t),e._zod.processJSONSchema=(a,r,n)=>CD(e,a,r,n)});function C1(e){return XP(SE,e)}var wE=A("ZodVoid",(e,t)=>{H$.init(e,t),st.init(e,t),e._zod.processJSONSchema=(a,r,n)=>wD(e,a,r,n)});function k9(e){return YP(wE,e)}var Lx=A("ZodDate",(e,t)=>{V$.init(e,t),st.init(e,t),e._zod.processJSONSchema=(r,n,o)=>LD(e,r,n,o),e.min=(r,n)=>e.check(Ki(r,n)),e.max=(r,n)=>e.check(Gi(r,n));let a=e._zod.bag;e.minDate=a.minimum?new Date(a.minimum):null,e.maxDate=a.maximum?new Date(a.maximum):null});function I9(e){return eD(Lx,e)}var CE=A("ZodArray",(e,t)=>{Mm(),q$.init(e,t),st.init(e,t),e._zod.processJSONSchema=(a,r,n)=>zD(e,a,r,n),e.element=t.element},{min(e,t){return this.check(mc(e,t))},nonempty(e){return this.check(mc(1,e))},max(e,t){return this.check($m(e,t))},length(e,t){return this.check(Pm(e,t))},unwrap(){return this.element}});function Tx(e,t){return nD(CE,e,t)}function L9(e){let t=e._zod.def.shape;return k1(Object.keys(t))}var _x=A("ZodObject",(e,t)=>{Mm(),Z$.init(e,t),st.init(e,t),e._zod.processJSONSchema=(a,r,n)=>UD(e,a,r,n),Z.installLazyProp(e,"shape",a=>a._zod.def.shape,!1)},{keyof(){return k1(Object.keys(this._zod.def.shape))},catchall(e){return this.clone({...this._zod.def,catchall:e})},passthrough(){return this.clone({...this._zod.def,catchall:Dm()})},loose(){return this.clone({...this._zod.def,catchall:Dm()})},strict(){return this.clone({...this._zod.def,catchall:C1()})},strip(){return this.clone({...this._zod.def,catchall:void 0})},extend(e){return Z.extend(this,e)},safeExtend(e){return Z.safeExtend(this,e)},merge(e){return Z.merge(this,e)},pick(e){return Z.pick(this,e)},omit(e){return Z.omit(this,e)},partial(...e){return Z.partial(Rx,this,e[0])},exactPartial(...e){return Z.partial(L1,this,e[0],"exactPartial")},required(...e){return Z.required(T1,this,e[0])}});function T9(e,t){let a={type:"object",shape:e??{},...Z.normalizeParams(t)};return new _x(a)}function _9(e,t){return new _x({type:"object",shape:e,catchall:C1(),...Z.normalizeParams(t)})}function N9(e,t){return new _x({type:"object",shape:e,catchall:Dm(),...Z.normalizeParams(t)})}var Nx=A("ZodUnion",(e,t)=>{cx.init(e,t),st.init(e,t),e._zod.processJSONSchema=(a,r,n)=>Jk(e,a,r,n),e.options=t.options});function Ig(e,t){return new Nx({type:"union",options:e,...Z.normalizeParams(t)})}var kE=A("ZodXor",(e,t)=>{Nx.init(e,t),G$.init(e,t),e._zod.processJSONSchema=(a,r,n)=>Jk(e,a,r,n),e.options=t.options});function R9(e,t){return new kE({type:"union",options:e,inclusive:!1,...Z.normalizeParams(t)})}var IE=A("ZodDiscriminatedUnion",(e,t)=>{Nx.init(e,t),W$.init(e,t)});function A9(e,t,a){return new IE({type:"union",options:t,discriminator:e,...Z.normalizeParams(a)})}var LE=A("ZodIntersection",(e,t)=>{J$.init(e,t),st.init(e,t),e._zod.processJSONSchema=(a,r,n)=>jD(e,a,r,n)});function TE(e,t){return new LE({type:"intersection",left:e,right:t})}var _E=A("ZodTuple",(e,t)=>{Mm(),uk.init(e,t),st.init(e,t),e._zod.processJSONSchema=(a,r,n)=>BD(e,a,r,n)},{rest(e){return this.clone({...this._zod.def,rest:e})},partial(){let e=this._zod.def;if(e.checks?.length)throw new Error(".partial() cannot be used on tuple schemas containing refinements");return this.clone({...e,items:e.items.map(t=>new Rx({type:"optional",innerType:t}))})}});function NE(e,t,a){let r=t instanceof Ke,n=r?a:t,o=r?t:null;return new _E({type:"tuple",items:e,rest:o,...Z.normalizeParams(n)})}var yg=A("ZodRecord",(e,t)=>{Mm(),Q$.init(e,t),st.init(e,t),e._zod.processJSONSchema=(a,r,n)=>FD(e,a,r,n),e.keyType=t.keyType,e.valueType=t.valueType});function RE(e,t,a){return!t||!t._zod?new yg({type:"record",keyType:Cx(),valueType:e,...Z.normalizeParams(t)}):new yg({type:"record",keyType:e,valueType:t,...Z.normalizeParams(a)})}function $9(e,t,a){return new yg({type:"record",keyType:e,valueType:t,...Z.normalizeParams(a),partial:!0})}function P9(e,t,a){return new yg({type:"record",keyType:e,valueType:t,mode:"loose",...Z.normalizeParams(a)})}var AE=A("ZodMap",(e,t)=>{Mm(),X$.init(e,t),st.init(e,t),e._zod.processJSONSchema=(a,r,n)=>MD(e,a,r,n),e.keyType=t.keyType,e.valueType=t.valueType,e.min=(...a)=>e.check(tu(...a)),e.nonempty=a=>e.check(tu(1,a)),e.max=(...a)=>e.check(Ud(...a)),e.size=(...a)=>e.check(Am(...a))});function D9(e,t,a){return new AE({type:"map",keyType:e,valueType:t,...Z.normalizeParams(a)})}var $E=A("ZodSet",(e,t)=>{Mm(),Y$.init(e,t),st.init(e,t),e._zod.processJSONSchema=(a,r,n)=>OD(e,a,r,n),e.min=(...a)=>e.check(tu(...a)),e.nonempty=a=>e.check(tu(1,a)),e.max=(...a)=>e.check(Ud(...a)),e.size=(...a)=>e.check(Am(...a))});function E9(e,t){return new $E({type:"set",valueType:e,...Z.normalizeParams(t)})}var bg=A("ZodEnum",(e,t)=>{eP.init(e,t),st.init(e,t),e._zod.processJSONSchema=(r,n,o)=>TD(e,r,n,o),e.enum=t.entries,e.options=Object.values(t.entries);let a=new Set(Object.keys(t.entries));e.extract=(r,n)=>{let o={};for(let i of r)if(a.has(i))o[i]=t.entries[i];else throw new Error(`Key ${i} not found in enum`);return new bg({...t,checks:[],...Z.normalizeParams(n),entries:o})},e.exclude=(r,n)=>{let o={...t.entries};for(let i of r)if(a.has(i))delete o[i];else throw new Error(`Key ${i} not found in enum`);return new bg({...t,checks:[],...Z.normalizeParams(n),entries:o})}});function k1(e,t){let a=Array.isArray(e)?Object.fromEntries(e.map(r=>[r,r])):e;return new bg({type:"enum",entries:a,...Z.normalizeParams(t)})}function M9(e,t){return new bg({type:"enum",entries:e,...Z.normalizeParams(t)})}var PE=A("ZodLiteral",(e,t)=>{tP.init(e,t),st.init(e,t),e._zod.processJSONSchema=(a,r,n)=>_D(e,a,r,n),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 O9(e,t){return new PE({type:"literal",values:Array.isArray(e)?e:[e],...Z.normalizeParams(t)})}var DE=A("ZodFile",(e,t)=>{aP.init(e,t),st.init(e,t),e._zod.processJSONSchema=(a,r,n)=>AD(e,a,r,n),e.min=(a,r)=>e.check(tu(a,r)),e.max=(a,r)=>e.check(Ud(a,r)),e.mime=(a,r)=>e.check(cg(Array.isArray(a)?a:[a],r))});function z9(e){return rD(DE,e)}var EE=A("ZodTransform",(e,t)=>{Mm(),nP.init(e,t),st.init(e,t),e._zod.processJSONSchema=(a,r,n)=>ED(e,a,r,n),e._zod.parse=(a,r)=>{if(r.direction==="backward")throw new Md(e.constructor.name);a.addIssue=o=>{if(typeof o=="string")a.issues.push(Z.issue(o,a.value,t));else{let i=o;i.fatal&&(i.continue=!1),i.code??(i.code="custom"),"input"in i||(i.input=a.value),i.inst??(i.inst=e),a.issues.push(Z.issue(i))}};let n=t.transform(a.value,a);return n instanceof Promise?n.then(o=>(a.value=o,a)):(a.value=n,a)}});function I1(e){return new EE({type:"transform",transform:e})}var Rx=A("ZodOptional",(e,t)=>{ck.init(e,t),st.init(e,t),e._zod.processJSONSchema=(a,r,n)=>Qk(e,a,r,n),e.unwrap=()=>e._zod.def.innerType});function Em(e){return new Rx({type:"optional",innerType:e})}var L1=A("ZodExactOptional",(e,t)=>{rP.init(e,t),st.init(e,t),e._zod.processJSONSchema=(a,r,n)=>Qk(e,a,r,n),e.unwrap=()=>e._zod.def.innerType});function ME(e){return new L1({type:"optional",innerType:e})}var OE=A("ZodNullable",(e,t)=>{oP.init(e,t),st.init(e,t),e._zod.processJSONSchema=(a,r,n)=>HD(e,a,r,n),e.unwrap=()=>e._zod.def.innerType});function kx(e){return new OE({type:"nullable",innerType:e})}function U9(e){return Em(kx(e))}var zE=A("ZodDefault",(e,t)=>{iP.init(e,t),st.init(e,t),e._zod.processJSONSchema=(a,r,n)=>ZD(e,a,r,n),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function UE(e,t){return new zE({type:"default",innerType:e,get defaultValue(){return typeof t=="function"?t():Z.shallowClone(t)}})}var jE=A("ZodPrefault",(e,t)=>{sP.init(e,t),st.init(e,t),e._zod.processJSONSchema=(a,r,n)=>GD(e,a,r,n),e.unwrap=()=>e._zod.def.innerType});function BE(e,t){return new jE({type:"prefault",innerType:e,get defaultValue(){return typeof t=="function"?t():Z.shallowClone(t)}})}var T1=A("ZodNonOptional",(e,t)=>{lP.init(e,t),st.init(e,t),e._zod.processJSONSchema=(a,r,n)=>VD(e,a,r,n),e.unwrap=()=>e._zod.def.innerType});function FE(e,t){return new T1({type:"nonoptional",innerType:e,...Z.normalizeParams(t)})}var HE=A("ZodSuccess",(e,t)=>{uP.init(e,t),st.init(e,t),e._zod.processJSONSchema=(a,r,n)=>$D(e,a,r,n),e.unwrap=()=>e._zod.def.innerType});function j9(e){return new HE({type:"success",innerType:e})}var VE=A("ZodCatch",(e,t)=>{cP.init(e,t),st.init(e,t),e._zod.processJSONSchema=(a,r,n)=>KD(e,a,r,n),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function qE(e,t){return new VE({type:"catch",innerType:e,catchValue:typeof t=="function"?t:Z.constantCatch(t)})}var ZE=A("ZodNaN",(e,t)=>{dP.init(e,t),st.init(e,t),e._zod.processJSONSchema=(a,r,n)=>ND(e,a,r,n)});function B9(e){return aD(ZE,e)}var Ax=A("ZodPipe",(e,t)=>{dk.init(e,t),st.init(e,t),e._zod.processJSONSchema=(a,r,n)=>WD(e,a,r,n),e.in=t.in,e.out=t.out});function n1(e,t){return new Ax({type:"pipe",in:e,out:t})}var $x=A("ZodCodec",(e,t)=>{Ax.init(e,t),dx.init(e,t)});function F9(e,t,a){return new $x({type:"pipe",in:e,out:t,transform:a.decode,reverseTransform:a.encode})}function H9(e){let t=e._zod.def;return new $x({type:"pipe",in:t.out,out:t.in,transform:t.reverseTransform,reverseTransform:t.transform})}var GE=A("ZodPreprocess",(e,t)=>{Ax.init(e,t),fP.init(e,t)}),KE=A("ZodReadonly",(e,t)=>{mP.init(e,t),st.init(e,t),e._zod.processJSONSchema=(a,r,n)=>JD(e,a,r,n),e.unwrap=()=>e._zod.def.innerType});function WE(e){return new KE({type:"readonly",innerType:e})}var JE=A("ZodTemplateLiteral",(e,t)=>{pP.init(e,t),st.init(e,t),e._zod.processJSONSchema=(a,r,n)=>RD(e,a,r,n)});function V9(e,t){return new JE({type:"template_literal",parts:e,...Z.normalizeParams(t)})}var QE=A("ZodLazy",(e,t)=>{fx.init(e,t),st.init(e,t),e._zod.processJSONSchema=(a,r,n)=>XD(e,a,r,n),e.unwrap=()=>e._zod.def.getter()});function XE(e){return new QE({type:"lazy",getter:e})}var YE=A("ZodPromise",(e,t)=>{gP.init(e,t),st.init(e,t),e._zod.processJSONSchema=(a,r,n)=>QD(e,a,r,n),e.unwrap=()=>e._zod.def.innerType});function q9(e){return new YE({type:"promise",innerType:e})}var eM=A("ZodFunction",(e,t)=>{hP.init(e,t),st.init(e,t),e._zod.processJSONSchema=(a,r,n)=>DD(e,a,r,n)});function Z9(e){return new eM({type:"function",input:Array.isArray(e?.input)?NE(e?.input):e?.input??Tx(Dm()),output:e?.output??Dm()})}var Px=A("ZodCustom",(e,t)=>{vP.init(e,t),st.init(e,t),e._zod.processJSONSchema=(a,r,n)=>PD(e,a,r,n)});function G9(e){let t=new La({check:"custom"});return t._zod.check=e,t}function K9(e,t){return oD(Px,e??(()=>!0),t)}function tM(e,t={}){return iD(Px,e,t)}function aM(e,t){return sD(e,t)}var W9=lD,J9=uD;function Q9(e,t={}){let a=new Px({type:"custom",check:"custom",fn:r=>r instanceof e,abort:!0,...Z.normalizeParams(t)});return a._zod.bag.Class=e,a._zod.check=r=>{r.value instanceof e||r.issues.push({code:"invalid_type",expected:e.name,input:r.value,inst:a,path:[...a._zod.def.path??[]]})},a}var X9=(...e)=>cD({Codec:$x,Boolean:Cg,String:xg},...e);function Y9(e){let t=XE(()=>Ig([Cx(e),mE(),pE(),yE(),Tx(t),RE(Cx(),t)]));return t}function eZ(e,t){return new GE({type:"pipe",in:I1(e),out:t})}var Fhe={invalid_type:"invalid_type",too_big:"too_big",too_small:"too_small",invalid_format:"invalid_format",not_multiple_of:"not_multiple_of",unrecognized_keys:"unrecognized_keys",invalid_union:"invalid_union",invalid_key:"invalid_key",invalid_element:"invalid_element",invalid_value:"invalid_value",custom:"custom"};function Hhe(e){wn({customError:e})}function Vhe(){return wn().customError}var nM;nM||(nM={});var Dx={};Ml(Dx,{ZodISODate:()=>Vd,ZodISODateTime:()=>Hd,ZodISODuration:()=>Zd,ZodISOTime:()=>qd,date:()=>Zhe,datetime:()=>qhe,duration:()=>Khe,time:()=>Ghe});function qhe(e){return vx(Hd,e)}function Zhe(e){return yx(Vd,e)}function Ghe(e){return bx(qd,e)}function Khe(e){return xx(Zd,e)}var se={...Lg,...e1,iso:Dx},Whe=new Set(["$schema","$ref","$defs","definitions","$id","id","$comment","$anchor","$vocabulary","$dynamicRef","$dynamicAnchor","type","enum","const","anyOf","oneOf","allOf","not","properties","required","additionalProperties","patternProperties","propertyNames","minProperties","maxProperties","items","prefixItems","additionalItems","minItems","maxItems","uniqueItems","contains","minContains","maxContains","minLength","maxLength","pattern","format","minimum","maximum","exclusiveMinimum","exclusiveMaximum","multipleOf","description","default","contentEncoding","contentMediaType","contentSchema","unevaluatedItems","unevaluatedProperties","if","then","else","dependentSchemas","dependentRequired","nullable","readOnly"]);function Jhe(e,t){let a=e.$schema;return a==="https://json-schema.org/draft/2020-12/schema"?"draft-2020-12":a==="http://json-schema.org/draft-07/schema#"?"draft-7":a==="http://json-schema.org/draft-04/schema#"?"draft-4":t??"draft-2020-12"}function tZ(e,t){return e.map((a,r)=>r<t?a:a.optional())}function Qhe(e){return e.replace(/~1/g,"/").replace(/~0/g,"~")}function Xhe(e,t){if(!e.startsWith("#"))throw new Error("External $ref is not supported, only local refs (#/...) are allowed");let a=e.slice(1).split("/").filter(Boolean);if(a.length===0)return t.rootSchema;let r=t.version==="draft-2020-12"?"$defs":"definitions";if(a[0]===r){let n=a[1]===void 0?void 0:Qhe(a[1]);if(!n||!t.defs[n])throw new Error(`Reference not found: ${e}`);return t.defs[n]}throw new Error(`Reference not found: ${e}`)}function Yhe(e,t){return se.transform(r=>r).check(r=>{let n=r.value;if(!(typeof n!="object"||n===null||Array.isArray(n)))for(let o of Object.getOwnPropertyNames(n)){let i=t.safeParse(o);i.success||r.issues.push({code:"invalid_key",origin:"record",issues:i.error.issues,input:o,path:[o],continue:!0})}}).pipe(e)}function aZ(e,t){if(e!==!1)return e===void 0||e===!0?se.any():xi(e,t)}var ege=/^(?:[01]\d|2[0-3]):[0-5]\d:[0-5]\d(?:\.\d+)?(?:Z|[+-](?:[01]\d|2[0-3]):[0-5]\d)$/;function nZ(e,t){if(e.not!==void 0){if(typeof e.not=="object"&&Object.keys(e.not).length===0)return se.never();throw new Error("not is not supported in Zod (except { not: {} } for never)")}if(e.unevaluatedItems!==void 0)throw new Error("unevaluatedItems is not supported");if(e.unevaluatedProperties!==void 0)throw new Error("unevaluatedProperties is not supported");if(e.if!==void 0||e.then!==void 0||e.else!==void 0)throw new Error("Conditional schemas (if/then/else) are not supported");if(e.dependentSchemas!==void 0||e.dependentRequired!==void 0)throw new Error("dependentSchemas and dependentRequired are not supported");if(e.$ref){let n=e.$ref;if(t.refs.has(n))return t.refs.get(n);if(t.processing.has(n))return se.lazy(()=>{if(!t.refs.has(n))throw new Error(`Circular reference not resolved: ${n}`);return t.refs.get(n)});t.processing.add(n);let o=Xhe(n,t),i=xi(o,t);return t.refs.set(n,i),t.processing.delete(n),i}if(e.enum!==void 0){let n=e.enum;if(t.version==="openapi-3.0"&&e.nullable===!0&&n.length===1&&n[0]===null)return se.null();if(n.length===0)return se.never();if(n.length===1)return se.literal(n[0]);if(n.every(i=>typeof i=="string"))return se.enum(n);let o=n.map(i=>se.literal(i));return o.length<2?o[0]:se.union([o[0],o[1],...o.slice(2)])}if(e.const!==void 0)return se.literal(e.const);let a=e.type;if(Array.isArray(a)){let n=a.map(o=>{let i={...e,type:o};return nZ(i,t)});return n.length===0?se.never():n.length===1?n[0]:se.union(n)}if(!a)return se.any();let r;switch(a){case"string":{let n=se.string();if(e.format){let o=e.format;o==="email"?n=n.check(se.email()):o==="uri"||o==="uri-reference"?n=n.check(se.url()):o==="uuid"||o==="guid"?n=n.check(se.uuid()):o==="date-time"?n=n.check(se.iso.datetime({offset:!0})):o==="date"?n=n.check(se.iso.date()):o==="time"?n=n.check(se.regex(ege)):o==="duration"?n=n.check(se.iso.duration()):o==="hostname"?n=n.check(se.hostname()):o==="ipv4"?n=n.check(se.ipv4()):o==="ipv6"?n=n.check(se.ipv6()):o==="mac"?n=n.check(se.mac()):o==="cidr"?n=n.check(se.cidrv4()):o==="cidr-v6"?n=n.check(se.cidrv6()):o==="base64"?n=n.check(se.base64()):o==="base64url"?n=n.check(se.base64url()):o==="e164"?n=n.check(se.e164()):o==="credit_card"?n=n.check(se.creditCard()):o==="jwt"?n=n.check(se.jwt()):o==="emoji"?n=n.check(se.emoji()):o==="nanoid"?n=n.check(se.nanoid()):o==="cuid"?n=n.check(se.cuid()):o==="cuid2"?n=n.check(se.cuid2()):o==="ulid"?n=n.check(se.ulid()):o==="xid"?n=n.check(se.xid()):o==="ksuid"&&(n=n.check(se.ksuid()))}typeof e.minLength=="number"&&(n=n.min(e.minLength)),typeof e.maxLength=="number"&&(n=n.max(e.maxLength)),e.pattern&&(n=n.regex(new RegExp(e.pattern))),r=n;break}case"number":case"integer":{let n=a==="integer"?se.number().int():se.number();typeof e.minimum=="number"&&e.exclusiveMinimum!==!0&&(n=n.min(e.minimum)),typeof e.maximum=="number"&&e.exclusiveMaximum!==!0&&(n=n.max(e.maximum)),typeof e.exclusiveMinimum=="number"?n=n.gt(e.exclusiveMinimum):e.exclusiveMinimum===!0&&typeof e.minimum=="number"&&(n=n.gt(e.minimum)),typeof e.exclusiveMaximum=="number"?n=n.lt(e.exclusiveMaximum):e.exclusiveMaximum===!0&&typeof e.maximum=="number"&&(n=n.lt(e.maximum)),typeof e.multipleOf=="number"&&(n=n.multipleOf(e.multipleOf)),r=n;break}case"boolean":{r=se.boolean();break}case"null":{r=se.null();break}case"object":{let n={},o=e.properties||{},i=new Set(e.required||[]),s=typeof e.additionalProperties=="object"?xi(e.additionalProperties,t):void 0;for(let[u,c]of Object.entries(o)){let d=xi(c,t);sn(n,u,i.has(u)?d:d.optional())}if(e.patternProperties){let u=e.patternProperties,c=Object.keys(u),d=[];for(let m of c){let h=xi(u[m],t),p=se.string().regex(new RegExp(m));d.push(se.looseRecord(p,h))}let f=[];if(Object.keys(n).length>0&&f.push(se.object(n).passthrough()),f.push(...d),f.length===0)r=se.object({}).passthrough();else if(f.length===1)r=f[0];else{let m=se.intersection(f[0],f[1]);for(let h=2;h<f.length;h++)m=se.intersection(m,f[h]);r=m}if(e.additionalProperties===!1){let m=Object.keys(n),h=c.map(v=>new RegExp(v)),p=r;r=r.check(v=>{if(!Ts(v.value))return;let x=[];for(let g of Object.keys(v.value))m.includes(g)||h.some(y=>y.test(g))||x.push(g);x.length&&v.issues.push({code:"unrecognized_keys",keys:x,input:v.value,inst:p})})}}else{let u=se.object(n);e.additionalProperties===!1?r=u.strict():s?r=u.catchall(s):r=u.passthrough()}if(e.propertyNames!==void 0&&e.propertyNames!==!0){let u=typeof e.propertyNames=="object"&&e.propertyNames.type===void 0?{type:"string",...e.propertyNames}:e.propertyNames;r=Yhe(r,xi(u,t))}break}case"array":{let n=e.prefixItems,o=e.items;if(n&&Array.isArray(n)){let i=typeof e.minItems=="number"?e.minItems:0,s=n.map(f=>xi(f,t)),u=tZ(s,i),c=Array.isArray(o)?void 0:aZ(o,t),d=se.tuple(u);r=c?d.rest(c):d,typeof e.minItems=="number"&&(r=r.check(se.minLength(e.minItems))),typeof e.maxItems=="number"&&(r=r.check(se.maxLength(e.maxItems)))}else if(Array.isArray(o)){let i=typeof e.minItems=="number"?e.minItems:0,s=o.map(f=>xi(f,t)),u=tZ(s,i),c=aZ(e.additionalItems,t),d=se.tuple(u);r=c?d.rest(c):d,typeof e.minItems=="number"&&(r=r.check(se.minLength(e.minItems))),typeof e.maxItems=="number"&&(r=r.check(se.maxLength(e.maxItems)))}else if(o!==void 0){let i=xi(o,t),s=se.array(i);typeof e.minItems=="number"&&(s=s.min(e.minItems)),typeof e.maxItems=="number"&&(s=s.max(e.maxItems)),r=s}else r=se.array(se.any());break}default:throw new Error(`Unsupported type: ${a}`)}return r}function xi(e,t){if(typeof e=="boolean")return e?se.any():se.never();let a=nZ(e,t),r=e.type||e.enum!==void 0||e.const!==void 0;if(e.anyOf&&Array.isArray(e.anyOf)){let s=e.anyOf.map(c=>xi(c,t)),u=se.union(s);a=r?se.intersection(a,u):u}if(e.oneOf&&Array.isArray(e.oneOf)){let s=e.oneOf.map(c=>xi(c,t)),u=se.xor(s);a=r?se.intersection(a,u):u}if(e.allOf&&Array.isArray(e.allOf))if(e.allOf.length===0)a=r?a:se.any();else{let s=r?a:xi(e.allOf[0],t),u=r?0:1;for(let c=u;c<e.allOf.length;c++)s=se.intersection(s,xi(e.allOf[c],t));a=s}e.nullable===!0&&t.version==="openapi-3.0"&&(a=se.nullable(a)),e.readOnly===!0&&(a=se.readonly(a)),e.default!==void 0&&(a=a.default(e.default));let n={},o=["$id","id","$comment","$anchor","$vocabulary","$dynamicRef","$dynamicAnchor"];for(let s of o)s in e&&(n[s]=e[s]);let i=["contentEncoding","contentMediaType","contentSchema"];for(let s of i)s in e&&(n[s]=e[s]);e.propertyNames!==void 0&&e.type==="object"&&e.$ref===void 0&&(n.propertyNames=e.propertyNames);for(let s of Object.keys(e))Whe.has(s)||sn(n,s,e[s]);return Object.keys(n).length>0&&t.registry.add(a,n),e.description&&(a=a.describe(e.description)),a}function rZ(e,t){if(typeof e=="boolean")return e?se.any():se.never();let a;try{a=JSON.parse(JSON.stringify(e))}catch{throw new Error("fromJSONSchema input is not valid JSON (possibly cyclic); use $defs/$ref for recursive schemas")}let r=Jhe(a,t?.defaultTarget),n=a.$defs||a.definitions||{},o={version:r,defs:n,refs:new Map,processing:new Set,rootSchema:a,registry:t?.registry??Ur};return xi(a,o)}var oZ=Symbol("z.visit/resolving");function Ex(e,t){let a=typeof t=="function"?t:(i,s)=>{let u=t[i._zod.def.type];return u?u(i,s):i},r=new Map;function n(i){let s=r.get(i);if(s===oZ)return new fx({type:"lazy",getter:()=>r.get(i)});if(s!==void 0)return s;r.set(i,oZ);let u=o(i),c=a(u,u!==i);return r.set(i,c),c}function o(i){let s=i._zod.def,u=s.type;switch(u){case"object":{let c=s.shape,d=Object.keys(c),f=!1,m={};for(let p of d){let v=n(c[p]);v!==c[p]&&(f=!0),m[p]=v}let h=s.catchall;return s.catchall&&(h=n(s.catchall),h!==s.catchall&&(f=!0)),f?na(i,{...s,shape:m,catchall:h}):i}case"array":{let c=n(s.element);return c===s.element?i:na(i,{...s,element:c})}case"tuple":{let c=s.items,d=!1,f=[];for(let h of c){let p=n(h);p!==h&&(d=!0),f.push(p)}let m=s.rest;return s.rest&&(m=n(s.rest),m!==s.rest&&(d=!0)),d?na(i,{...s,items:f,rest:m}):i}case"record":case"map":{let c=n(s.keyType),d=n(s.valueType);return c===s.keyType&&d===s.valueType?i:na(i,{...s,keyType:c,valueType:d})}case"set":{let c=n(s.valueType);return c===s.valueType?i:na(i,{...s,valueType:c})}case"union":{let c=s.options,d=!1,f=[];for(let m of c){let h=n(m);h!==m&&(d=!0),f.push(h)}return d?na(i,{...s,options:f}):i}case"intersection":{let c=n(s.left),d=n(s.right);return c===s.left&&d===s.right?i:na(i,{...s,left:c,right:d})}case"optional":case"nullable":case"default":case"prefault":case"catch":case"readonly":case"nonoptional":case"promise":case"success":{let c=n(s.innerType);return c===s.innerType?i:na(i,{...s,innerType:c})}case"pipe":{let c=n(s.in),d=n(s.out);return c===s.in&&d===s.out?i:na(i,{...s,in:c,out:d})}case"function":{let c=n(s.input),d=n(s.output);return c===s.input&&d===s.output?i:na(i,{...s,input:c,output:d})}case"lazy":{let c=s.getter,{_cachedInner:d,...f}=s;return na(i,{...f,getter:()=>n(c())})}case"template_literal":case"string":case"number":case"int":case"boolean":case"bigint":case"symbol":case"undefined":case"null":case"void":case"never":case"any":case"unknown":case"date":case"nan":case"enum":case"literal":case"file":case"transform":case"custom":return i;default:return i}}return n(e)}function iZ(e){return Ex(e,{object:t=>t.partial(),union:t=>{let a=t._zod.def;return a.discriminator===void 0?t:Ig(a.options)}})}function tge(e,t){if(!t?.length)return e;let a=e._zod.def;return na(e,cl(a,{checks:[...a.checks??[],...t]}),{parent:!0})}function sZ(e){return tge(e.out,e.checks)}function age(e){return e.in._zod.traits.has("$ZodTransform")?sZ(e):e.in}function lZ(e){return Ex(e,{pipe:t=>age(t._zod.def),default:(t,a)=>a?Em(t._zod.def.innerType):t,catch:(t,a)=>a?t._zod.def.innerType:t})}function uZ(e){return Ex(e,{pipe:t=>sZ(t._zod.def),prefault:(t,a)=>a?t._zod.def.innerType:t})}var rM={};Ml(rM,{bigint:()=>ige,boolean:()=>oge,date:()=>sge,number:()=>rge,string:()=>nge});function nge(e){return RP(xg,e)}function rge(e){return EP(wg,e)}function oge(e){return FP(Cg,e)}function ige(e){return VP(kg,e)}function sge(e){return tD(Lx,e)}var cZ=["none","low","medium","high","xhigh"];var _1=l.string().regex(/^[a-z][a-z0-9_-]*$/);var Ao=l.string().trim().min(1).max(160),Tg=l.number().int().nonnegative(),lge=l.discriminatedUnion("type",[l.strictObject({type:l.literal("code_change"),author:Ao.optional(),sourceBranch:Ao.optional(),targetBranch:Ao.optional(),reviewers:l.array(Ao).max(5).optional(),review:l.enum(["required","approved","changes_requested"]).optional(),checks:l.strictObject({passed:Tg,failed:Tg,pending:Tg}).optional(),mergeable:l.boolean().optional(),changedFiles:Tg.optional(),additions:Tg.optional(),deletions:Tg.optional()}),l.strictObject({type:l.literal("task"),assignees:l.array(Ao).max(5).optional(),priority:Ao.optional(),project:Ao.optional(),cycle:Ao.optional(),dueDate:l.iso.date().optional(),labels:l.array(Ao).max(5).optional()}),l.strictObject({type:l.literal("deployment"),project:Ao.optional(),environment:Ao.optional(),revision:Ao.optional(),branch:Ao.optional()}),l.strictObject({type:l.literal("calendar_event"),when:Ao.optional(),attendees:l.array(Ao).max(5).optional()})]);function fZ(e){if(!e)return[];let t=[],a=n=>n?.length?`${n.join(", ")}${n.length===5?" (up to 5 shown)":""}`:void 0;function r(n,o,i){i!==void 0&&i!==""&&t.push({key:n,label:o,value:String(i)})}switch(e.type){case"code_change":r("sourceBranch","Branch",e.sourceBranch);break;case"task":r("assignees","Assignees",e.assignees?.length===0?"Unassigned":a(e.assignees)),r("priority","Priority",e.priority),r("project","Project",e.project),r("cycle","Cycle",e.cycle),r("dueDate","Due",e.dueDate),r("labels","Labels",a(e.labels));break;case"deployment":r("environment","Environment",e.environment),r("project","Project",e.project),r("revision","Revision",e.revision),r("branch","Branch",e.branch);break;case"calendar_event":r("when","When",e.when),r("attendees","Attendees",a(e.attendees));break}return t.slice(0,4)}var Ng=l.enum(["task","code_change","automation","deployment","calendar_event","item"]);var oM=l.object({kind:l.literal("object"),key:l.string().trim().min(1).max(256),label:l.string().trim().min(1).max(256),objectType:Ng,title:l.string().trim().min(1).max(512),url:l.url().max(2048).refine(e=>["http:","https:"].includes(new URL(e).protocol)).nullable(),description:l.string().max(4e3).optional(),status:l.string().trim().min(1).max(100).optional(),trigger:l.string().max(4e3).optional(),warning:l.string().max(1e3).optional(),displayType:l.string().trim().min(1).max(80).optional(),sourceUpdatedAt:l.iso.datetime({offset:!0}).optional(),facts:lge.refine(e=>new TextEncoder().encode(JSON.stringify(e)).length<=4096,"Object facts must not exceed 4 KiB").optional()}).strict().refine(e=>!e.facts||(e.facts.type==="deployment"?e.objectType==="deployment"||e.objectType==="item":e.facts.type===e.objectType),"Object facts must match the object type"),u5e=oM.safeExtend({plugin:l.string().min(1)});function uge(e){try{let t=new URL(e).protocol;return t==="http:"||t==="https:"}catch{return!1}}var cge=l.object({kind:l.literal("resource_link"),objectType:Ng.optional(),key:l.string().trim().min(1).max(256),label:l.string().trim().min(1).max(256),url:l.string().url().max(2048).refine(uge,"URL must use HTTP or HTTPS."),description:l.string().trim().min(1).max(512).optional(),status:l.enum(["open","draft","closed","merged","warning"]).optional()}).strict(),mZ=l.discriminatedUnion("kind",[cge,oM]),dge=l.enum(["circle-dot","circle-dashed","circle-x","git-merge","git-pull-request","triangle-alert"]),pZ=l.object({icon:dge.optional(),objectType:Ng.optional(),status:l.string().trim().min(1).max(100).optional(),key:l.string().trim().min(1).max(256),label:l.string().trim().min(1).max(256)}).strict(),Ox=l.enum(["closed","merged","open"]),f5e=l.object({closedAt:l.date().optional(),conversationIds:l.array(l.string().min(1)).default([]),mergedAt:l.date().optional(),number:l.number().int().positive(),openedAt:l.date(),providerId:l.string().min(1),repository:l.object({name:l.string().min(1),providerId:l.string().min(1),url:l.string().url().optional()}).strict(),state:Ox,title:l.string().min(1).optional(),updatedAt:l.date(),url:l.string().url().optional()}).strict(),p5e=l.string().trim().min(1).max(64).regex(/^[a-z][a-z0-9_]*$/),fge=l.enum(["activity","brain","calendar","check","database","info","key","link","sparkles","warning"]),mge=l.object({content:l.string().min(1).max(32*1024).optional(),description:l.string().trim().min(1).max(2e3).optional(),metadata:l.array(l.string().trim().min(1).max(120)).max(8).optional(),title:l.string().trim().min(1).max(4e3)}).strict(),hZ=l.object({details:l.array(mge).max(100).optional(),icon:fge.optional(),preview:l.string().trim().min(1).max(500).optional(),title:l.string().trim().min(1).max(120)}).strict();var R1=l.string().regex(/^T[A-Z0-9]+$/),iM=l.string().regex(/^(C|G|D)[A-Z0-9]+$/),gZ=l.string().regex(/^local:[a-z0-9_-]+:[a-z0-9][a-z0-9_-]*$/),A1=l.string().min(1).refine(e=>e===e.trim()&&e.toLowerCase()!=="unknown"),N1=A1,Ue=l.string().refine(e=>e.trim().length>0),io=Ue.refine(e=>e===e.trim()),pge=l.object({id:Ue,provider:io}).strict(),hge=pge.extend({provider:l.literal("slack"),teamId:R1,channelId:iM,threadTs:io.optional()}).strict(),g5e=l.discriminatedUnion("provider",[hge]),v5e=l.enum(["slack","local"]),vZ=l.enum(["public","private"]),sM=l.enum(["public","private"]),gge=l.object({platform:l.literal("slack"),teamId:R1,channelId:iM,threadTs:io.optional()}).strict(),Rg=gge,vge=l.object({platform:l.literal("local"),conversationId:gZ}).strict(),yge=l.discriminatedUnion("platform",[Rg,vge]),zx=l.object({action:l.literal("send_message"),destination:Rg}).strict(),bge=l.object({kind:l.literal("slack"),teamId:R1,channelId:iM,visibility:vZ,messageTs:Ue.optional(),threadTs:Ue.optional()}).strict(),xge=l.object({kind:l.literal("local"),visibility:l.literal("private"),conversationId:gZ}).strict(),Sge=l.object({kind:l.literal("web"),visibility:vZ,conversationId:io}).strict(),wge=l.object({kind:l.literal("event"),eventKey:io,eventType:io,identifier:io,namespace:io}).strict(),Cge=l.object({kind:l.literal("scheduled_automation")}).strict(),kge=l.object({kind:l.literal("event_automation")}).strict(),Ige=l.object({kind:l.literal("plugin_dispatch")}).strict(),Lge=l.object({kind:l.literal("agent_invocation")}).strict(),Tge=l.discriminatedUnion("kind",[bge,xge,Sge,wge,Cge,kge,Ige,Lge]);function _ge(e){if(!e||typeof e!="object"||Array.isArray(e))return e;let t=e;if("kind"in t){let o={event_task:"event_automation",resource_event:"event",scheduled_task:"scheduled_automation"},i=typeof t.kind=="string"?o[t.kind]:void 0;return i?{...t,kind:i}:e}if(t.platform!=="slack"&&t.platform!=="local"&&t.platform!=="web")return e;let{location:a,platform:r,...n}=t;return{...n,kind:r}}var Nge=l.preprocess(_ge,Tge),Rge=l.discriminatedUnion("allowedWhen",[l.object({type:l.literal("user"),userId:N1,allowedWhen:l.literal("private-direct-conversation")}).strict(),l.object({type:l.literal("user"),userId:N1,allowedWhen:l.literal("scheduled-automation"),taskId:io}).strict()]),lM={email:Ue.optional(),fullName:Ue.optional(),userId:N1,userName:Ue.optional()},Age=l.object({...lM,platform:l.literal("slack"),teamId:R1}).strict(),$ge=l.object({...lM,platform:l.literal("local")}).strict(),Pge=l.object({...lM,platform:l.literal("web")}).strict(),Dge=l.object({platform:l.literal("system"),name:N1}).strict(),Mx=l.discriminatedUnion("platform",[Age,$ge,Pge,Dge]),Ege=l.object({displayName:Ue.optional(),handle:Ue.optional(),id:io,provider:io,providerSubjectId:io,providerTenantId:io.optional()}).strict(),y5e=l.object({displayName:Ue.optional(),email:Ue.max(320),id:io,identities:l.array(Ege).max(100),isAdmin:l.literal(!0).optional()}).strict(),Mge=l.record(l.string(),l.string()).superRefine((e,t)=>{let a=Object.entries(e);if(a.length>20){t.addIssue({code:l.ZodIssueCode.custom,message:"Dispatch metadata has too many keys"});return}for(let[r,n]of a){if(!r.trim()){t.addIssue({code:l.ZodIssueCode.custom,message:"Dispatch metadata values must be strings",path:[r]});continue}r.length>128&&t.addIssue({code:l.ZodIssueCode.custom,message:"Dispatch metadata key exceeds the maximum length",path:[r]}),/[\r\n]/.test(r)&&t.addIssue({code:l.ZodIssueCode.custom,message:"Dispatch metadata keys must be single-line strings",path:[r]}),/[\r\n]/.test(n)&&t.addIssue({code:l.ZodIssueCode.custom,message:"Dispatch metadata values must be single-line strings",path:[r]}),n.length>512&&t.addIssue({code:l.ZodIssueCode.custom,message:"Dispatch metadata value exceeds the maximum length",path:[r]})}}),Oge=l.object({label:io.pipe(l.string().max(48)).refine(e=>!/[\r\n]/.test(e)),detail:io.pipe(l.string().max(128)).refine(e=>!/[\r\n]/.test(e)).optional()}).strict(),b5e=l.object({idempotencyKey:Ue.pipe(l.string().max(512)),credentialSubject:Rge.optional(),destination:Rg,destinationVisibility:sM,input:Ue.pipe(l.string().max(32e3)),metadata:Mge.optional(),replyAttribution:Oge.optional()}).strict();var zge=l.string().trim().min(1).max(64).regex(/^[a-z][a-z0-9_-]*$/),S5e=l.object({text:l.string().trim().min(1).max(8e3)}).strict(),w5e=l.object({kind:zge,version:l.number().int().positive(),content:l.record(l.string(),l.unknown())}).strict();var Uge=4e3,jge=8e3,_g=32,dZ=4e3,Bge=1e3,Fge=l.record(l.string(),l.unknown()).superRefine((e,t)=>{Object.keys(e).length>_g&&t.addIssue({code:"custom",message:`Event data may include at most ${_g} keys.`}),new TextEncoder().encode(JSON.stringify(e)).byteLength>dZ&&t.addIssue({code:"custom",message:`Event data may be at most ${dZ} JSON bytes.`})}),hc=l.string().regex(/^[a-z][a-z0-9_-]*(?:\.[a-z][a-z0-9_-]*)+$/).describe("Canonical dotted event type, such as issue.closed or pull_request.review.changes_requested."),yZ=l.string().regex(/^[a-z][a-z0-9_]*$/).describe("Canonical plugin-defined resource type, such as issue or pull_request."),bZ=/^[a-z][a-zA-Z0-9]*$/,Hge=l.object({kind:l.enum(["boolean","string","number"]),description:l.string().trim().min(1).max(200),enum:l.array(l.string().min(1)).min(1).optional()}).strict().superRefine((e,t)=>{e.enum&&e.kind!=="string"&&t.addIssue({code:"custom",message:'Event match field enum requires kind "string".',path:["enum"]})}),Vge=l.record(l.string().regex(bZ),Hge).superRefine((e,t)=>{Object.keys(e).length>_g&&t.addIssue({code:"custom",message:`Event match keys may include at most ${_g} keys.`})}),uM=l.record(l.string().regex(bZ),l.union([l.boolean(),l.number().finite(),l.string().min(1),l.array(l.union([l.number().finite(),l.string().min(1)])).min(1)])).superRefine((e,t)=>{Object.keys(e).length>_g&&t.addIssue({code:"custom",message:`Event match may include at most ${_g} keys.`});for(let[a,r]of Object.entries(e))Array.isArray(r)&&r.some(n=>typeof n=="boolean")&&t.addIssue({code:"custom",message:`Event match field "${a}" cannot use a boolean list.`,path:[a]})});var qge=l.object({format:l.string().trim().min(1).max(200),pattern:l.instanceof(RegExp)}).strict(),cM=l.object({type:yZ,identifier:qge.optional(),supportedEvents:l.array(hc).min(1),suggestedEvents:l.array(hc).optional(),matchFields:Vge.optional(),guidance:l.record(hc,l.string().trim().min(1).max(Bge)).optional()}).strict().superRefine((e,t)=>{let a=new Set;e.supportedEvents.forEach((n,o)=>{a.has(n)&&t.addIssue({code:"custom",message:`Duplicate supported event type "${n}".`,path:["supportedEvents",o]}),a.add(n)});for(let n of Object.keys(e.guidance??{}))a.has(n)||t.addIssue({code:"custom",message:`Guidance event type "${n}" is not supported.`,path:["guidance",n]});let r=new Set;e.suggestedEvents?.forEach((n,o)=>{r.has(n)&&t.addIssue({code:"custom",message:`Duplicate suggested event type "${n}".`,path:["suggestedEvents",o]}),a.has(n)||t.addIssue({code:"custom",message:`Suggested event type "${n}" is not supported.`,path:["suggestedEvents",o]}),r.add(n)})}),k5e=l.object({resourceTypes:l.array(cM).min(1),isEnabled:l.function({input:[],output:l.boolean()}).optional(),normalizeIdentifier:l.function({input:[l.string()],output:l.string()}).optional()}).strict().superRefine((e,t)=>{let a=new Set;e.resourceTypes.forEach((r,n)=>{a.has(r.type)&&t.addIssue({code:"custom",message:`Duplicate resource type "${r.type}".`,path:["resourceTypes",n,"type"]}),a.add(r.type)})});var I5e=l.object({identifier:l.string().min(1),label:l.string().min(1),namespace:l.string().min(1),suggestedEvents:l.array(hc).optional(),supportedEvents:l.array(hc),type:yZ}).strict(),L5e=l.object({events:l.array(hc).min(1),id:l.string().min(1)}).strict(),Zge=l.union([l.object({provider:l.string().min(1),handle:l.string().min(1)}).strict(),l.object({email:l.string().trim().min(3)}).strict()]),Gge=l.object({objectType:Ng.optional(),eventKey:l.string().min(1),eventType:hc,identifier:l.string().min(1),occurredAtMs:l.number().finite(),terminal:l.boolean().optional(),trustedSummary:l.string().min(1).transform(e=>e.slice(0,Uge)),data:Fge.optional(),untrustedText:l.string().transform(e=>e.slice(0,jge)).optional(),people:l.array(Zge).max(20).optional()}).strict(),T5e=Gge.extend({namespace:l.string().min(1)}),Kge=l.object({authority:l.enum(["instruction","context"]),actor:Mx.optional()}).strict(),Wge=l.discriminatedUnion("type",[l.object({type:l.literal("message"),role:l.enum(["user","assistant"]),text:l.string().min(1),provenance:Kge.optional(),isRunActor:l.boolean().optional()}).strict(),l.object({type:l.literal("toolResult"),toolName:l.string().min(1),isError:l.boolean(),text:l.string().min(1).optional()}).strict()]),N5e=l.object({actorUserId:l.string().min(1).optional(),completedAtMs:l.number().finite(),conversationId:l.string().min(1),destination:yge,locationId:l.string().min(1).optional(),actors:l.array(Mx),actor:Mx.optional(),runId:l.string().min(1),source:Nge,transcript:l.array(Wge)}).strict();var A5e=l.discriminatedUnion("type",[l.object({type:l.literal("text"),text:l.string()}).strict(),l.object({type:l.literal("image"),data:l.string(),mimeType:l.string()}).strict()]),Jge=l.object({arguments:l.record(l.string(),l.unknown()),reason:l.string().min(1).optional()}).strict(),$5e=l.object({objectAnnotations:l.array(oM).optional(),target:l.string().min(1).optional(),truncated:l.boolean().optional(),continuation:Jge.optional()}).passthrough(),P5e=l.enum(["auto","review","approve"]);var E5e=l.object({auth:l.object({user:l.object({email:l.string().nullable().optional(),emailVerified:l.boolean().optional(),isAdmin:l.boolean(),name:l.string().nullable().optional()}).strict()}).strict(),pluginName:Ue}).strict(),Qge=l.string().regex(/^[a-z][a-z0-9-]*$/),Xge=l.string().regex(/^[a-z][a-z0-9.-]*$/),Yge=l.union([l.literal("read"),l.literal("write")]),xZ=l.object({provider:Qge,scope:Ue.optional(),type:l.literal("oauth")}).strict(),SZ=l.object({displayName:Ue.optional(),handle:Ue.optional(),id:Ue,label:Ue.optional(),url:Ue.optional()}).strict(),O5e=l.object({account:SZ.optional(),accessToken:Ue,expiresAt:l.number().finite().optional(),refreshToken:Ue,refreshTokenExpiresAt:l.number().finite().optional(),scope:Ue.optional()}).strict(),z5e=l.object({access:Yge,leaseScope:Ue.optional(),name:Xge,reason:Ue.optional(),requirements:l.array(Ue).min(1).optional()}).strict(),eve=l.object({domain:l.string().min(1),headers:l.record(l.string(),l.string()).refine(e=>Object.keys(e).length>0)}).strict(),tve=l.object({account:SZ.optional(),authorization:xZ.optional(),expiresAt:l.string().refine(e=>Number.isFinite(Date.parse(e))),headerTransforms:l.array(eve).min(1)}).strict(),U5e=l.discriminatedUnion("type",[l.object({lease:tve,type:l.literal("lease")}).strict(),l.object({authorization:xZ.optional(),message:Ue,type:l.literal("needed")}).strict(),l.object({message:Ue,type:l.literal("unavailable")}).strict()]);var ave=Ue.max(64).regex(/^[a-z][a-z0-9-]*$/),nve=Ue.max(80),rve=Ue.max(500),ove=l.enum(["primary","profile","admin"]),ive=l.object({detail:Ue.max(500).optional(),label:Ue.max(80),tone:l.enum(["good","neutral","warning"]).optional(),value:Ue.max(120)}).strict(),sve=l.object({label:Ue.max(80),value:Ue.max(500)}).strict(),lve=l.object({confirmation:Ue.max(500).optional(),href:Ue.max(500).regex(/^\/api\/plugins\/[a-z][a-z0-9-]*(?:\/|$)/),label:Ue.max(80),method:l.enum(["DELETE","GET"]),tone:l.enum(["danger","neutral"]).optional()}).strict(),uve=l.object({actions:l.array(lve).max(4).optional(),description:Ue.max(1e3).optional(),id:Ue.max(128),metadata:l.array(sve).max(8).optional(),title:Ue.max(4e3)}).strict(),B5e=l.object({emptyText:Ue.max(500).optional(),metrics:l.array(ive).max(6).optional(),nextCursor:Ue.max(1e3).optional(),records:l.array(uve).max(100),searchPlaceholder:Ue.max(120).optional(),type:l.literal("list")}).strict(),cve=l.object({description:rve,id:ave,label:nve,navigation:ove,pluginDisplayName:Ue.max(200),pluginName:Ue.max(100)}).strict(),F5e=l.array(cve),dve=Ue.max(1e3).optional(),fve=Ue.max(64).optional(),mve=l.string().trim().max(200).optional(),H5e=l.object({cursor:dve,filter:fve,limit:l.number().int().min(1).max(50),query:mve}).strict();var pve=l.object({input:l.number().finite().nonnegative().optional(),output:l.number().finite().nonnegative().optional(),cacheRead:l.number().finite().nonnegative().optional(),cacheWrite:l.number().finite().nonnegative().optional(),total:l.number().finite().nonnegative().optional()}).strict(),fM=l.object({inputTokens:l.number().int().nonnegative().optional(),outputTokens:l.number().int().nonnegative().optional(),cachedInputTokens:l.number().int().nonnegative().optional(),cacheCreationTokens:l.number().int().nonnegative().optional(),reasoningTokens:l.number().int().nonnegative().optional(),totalTokens:l.number().int().nonnegative().optional(),cost:pve.optional()}).strict(),hve=l.union([l.literal("instruction"),l.literal("context")]),gve=l.object({authority:hve,actor:Mx.optional()}).strict();var K5e=l.record(l.string(),l.unknown()),W5e=l.object({item:l.string()}).passthrough();function vve(e){return e==="user_message"||e==="assistant_message"||e==="tool_result"||e==="handoff"||e==="compaction"}var yve=l.object({type:l.literal("user_message"),role:l.never().optional(),provenance:gve}).passthrough(),bve=l.object({type:l.literal("assistant_message"),role:l.never().optional()}).passthrough(),xve=l.object({type:l.literal("tool_result"),role:l.never().optional()}).passthrough(),CZ=l.discriminatedUnion("type",[yve,bve,xve]),Sve=l.object({item:CZ,sourceEventSeq:l.number().int().nonnegative().optional()}).strict(),wZ=l.array(Sve),wve=l.object({reason:l.literal("capacity"),estimatedInputTokens:l.number().int().nonnegative(),replacementInputTokens:l.number().int().nonnegative().optional(),triggerTokens:l.number().int().nonnegative(),inputLimitTokens:l.number().int().positive(),inputMessageCount:l.number().int().nonnegative(),retainedMessageCount:l.number().int().nonnegative(),summaryChars:l.number().int().nonnegative()}).strict(),kZ=l.discriminatedUnion("type",[l.object({type:l.literal("handoff"),modelProfile:_1,modelId:l.string().min(1),reasoningLevel:l.string().min(1).optional(),triggeringToolCallId:l.string().min(1).optional(),summary:l.string().min(1).optional(),replacementHistory:wZ}).strict(),l.object({type:l.literal("compaction"),modelProfile:_1,modelId:l.string().min(1),details:wve.optional(),summary:l.string().min(1).optional(),replacementHistory:wZ}).strict()]),J5e=l.object({data:kZ,createdAtMs:l.number().finite()}).strict(),Cve=l.object({type:l.literal("mcp_provider_connected"),provider:l.string().min(1),credentialSubjectId:l.string().min(1)}).strict(),kve=l.object({type:l.literal("mcp_provider_connected_unowned"),provider:l.string().min(1)}).strict(),IZ=l.union([l.literal("plugin"),l.literal("mcp")]),Ive=l.object({type:l.literal("authorization_requested"),kind:IZ,provider:l.string().min(1),actorId:l.string().min(1),authorizationId:l.string().min(1),delivery:l.union([l.literal("private_link_sent"),l.literal("private_link_reused")])}).strict(),Lve=l.object({type:l.literal("authorization_completed"),kind:IZ,provider:l.string().min(1),actorId:l.string().min(1),authorizationId:l.string().min(1)}).strict(),Tve=l.object({type:l.literal("tool_execution_started"),toolCallId:l.string().min(1),toolName:l.string().min(1)}).strict(),_ve=l.object({type:l.literal("guardian_action_reviewed"),turnId:l.string().min(1),toolCallId:l.string().min(1),toolName:l.string().min(1),costUsd:l.number().finite().nonnegative().optional(),decision:l.enum(["allow","ask","deny"]),riskLevel:l.enum(["low","medium","high","critical"]),userAuthorization:l.enum(["high","medium","low","unknown"])}).strict(),Nve=l.union([l.literal("user"),l.literal("assistant"),l.literal("system")]),LZ=l.object({type:l.literal("message"),messageId:l.string().min(1),role:Nve,text:l.string(),authorIdentityId:l.string().min(1).optional(),meta:l.record(l.string(),l.unknown()).optional()}).strict(),Rve=LZ.extend({type:l.literal("message_updated")}),Ave=l.object({type:l.literal("message_handled"),messageId:l.string().min(1)}).strict(),$ve=l.object({type:l.literal("messages_summarized"),historyFromSeq:l.number().int().nonnegative(),compactions:l.array(l.object({coveredMessageCount:l.number().int().nonnegative(),createdAtMs:l.number(),id:l.string().min(1),summary:l.string()}).strict())}).strict(),Pve=l.enum(["slack","api","scheduler","internal"]),$1=l.enum(["agent_run_failed","delivery_failed","model_execution_failed","persistence_failed"]),P1=l.enum(["auth","permission","rate_limit","capacity","timeout","network","server","invalid_request","invalid_response","quota","content_policy","unknown","empty_output","tool_errors","suppressed_output"]),Dve=l.object({type:l.literal("turn_started"),turnId:l.string().min(1),inputMessageIds:l.array(l.string().min(1)).min(1),surface:Pve}).strict().refine(e=>new Set(e.inputMessageIds).size===e.inputMessageIds.length,"turn input message ids must be unique"),Eve=l.object({type:l.literal("turn_routed"),turnId:l.string().min(1),modelProfile:_1,modelId:l.string().min(1),costUsd:l.number().finite().nonnegative().optional(),reasoningLevel:l.enum(cZ),confidence:l.number().min(0).max(1).optional(),source:l.enum(["configured","inherited","router"])}).strict(),Mve=l.object({type:l.literal("turn_context"),turnId:l.string().min(1),pluginName:l.string().min(1),kind:l.string().min(1).max(64),version:l.number().int().positive(),content:l.record(l.string(),l.unknown())}).strict(),Ove=l.object({type:l.literal("structured_event"),namespace:l.string().regex(/^[a-z][a-z0-9-]*$/),name:l.string().regex(/^[a-z][a-z0-9_]*$/),version:l.number().int().positive(),turnId:l.string().min(1).optional(),content:l.record(l.string(),l.unknown())}).strict(),zve=l.object({id:l.string().min(1),filename:l.string().min(1),contentType:l.string().min(1),bytes:l.number().int().nonnegative()}).strict(),Uve=l.object({type:l.literal("attachments_delivered"),attachments:l.array(zve).min(1),toolCallId:l.string().min(1).optional(),turnId:l.string().min(1).optional()}).strict(),jve=l.object({type:l.literal("turn_completed"),turnId:l.string().min(1),outcome:l.enum(["success","no_reply","cancelled"])}).strict(),Bve=l.object({type:l.literal("turn_failed"),turnId:l.string().min(1),failureCode:$1,failureReason:P1.optional(),eventId:l.string().regex(/^[a-f0-9]{32}$/i).optional()}).strict(),Fve=l.object({type:l.literal("subagent_started"),subagentInvocationId:l.string().min(1),subagentKind:l.string().min(1),agentName:l.string().min(1).optional(),task:l.string().min(1).optional(),title:l.string().min(1).optional(),modelId:l.string().min(1).optional(),parentToolCallId:l.string().min(1).optional(),reasoningLevel:l.string().min(1).optional(),childConversationId:l.string().min(1)}).strict(),Hve=l.object({type:l.literal("subagent_ended"),subagentInvocationId:l.string().min(1),outcome:l.union([l.literal("success"),l.literal("blocked"),l.literal("error"),l.literal("aborted")]),errorCode:l.string().min(1).optional()}).strict(),TZ=l.union([LZ,Rve,CZ,Cve,Ive,Lve,Tve,_ve,Ave,$ve,Dve,Mve,Ove,Uve,Eve,jve,Bve,Fve,Hve]),Vve=l.union([TZ,kZ,kve]),qve=["message","message_updated","user_message","assistant_message","tool_result","mcp_provider_connected","mcp_provider_connected_unowned","authorization_requested","authorization_completed","tool_execution_started","guardian_action_reviewed","message_handled","messages_summarized","turn_started","turn_context","structured_event","attachments_delivered","turn_routed","turn_completed","turn_failed","subagent_started","subagent_ended","handoff","compaction"],Q5e=l.enum(qve),Zve=l.object({type:l.literal("unknown"),originalType:l.string().min(1),payload:l.unknown()}).strict(),dM=l.object({schemaVersion:l.number().int().nonnegative(),seq:l.number().int().nonnegative(),historyVersion:l.number().int().nonnegative(),idempotencyKey:l.string().min(1).optional(),createdAtMs:l.number().finite()}).strict(),X5e=l.union([dM.extend({schemaVersion:l.union([l.literal(1),l.literal(2)]),data:Vve}).refine(e=>e.schemaVersion===1||vve(e.data.type)),dM.extend({data:Zve})]),Y5e=dM.extend({type:l.string().min(1),payload:l.unknown()});var e3e=l.object({data:TZ,idempotencyKey:l.string().min(1).optional(),createdAtMs:l.number().finite()}).strict();var Gve=l.object({kind:l.literal("automation"),id:l.string().min(1),title:l.string().min(1).max(160),url:l.string().url().nullable(),instruction:l.string().max(4e3),trigger:l.string().min(1),warning:l.string().nullable()}).strict();function Kve(e){return[e.title,e.warning,e.trigger,e.instruction,e.url,`Automation ID: ${e.id}`].filter(Boolean).join(`
69
69
  `)}var o3e=Gve.extend({operation:l.enum(["created","updated","deleted"]).optional()});function hM(e){switch(e.kind){case"object":return[e.title,e.label!==e.title?e.label:void 0,e.description,e.status,...fZ(e.facts).map(t=>`${t.label}: ${t.value}`),e.trigger,e.warning,e.url].filter(Boolean).join(`
70
- `);case"automation":return Kve(e)}}var Wve=l.object({plugin:l.string().min(1),key:l.string().min(1)}).strict(),Jve=Wve.extend({kind:l.literal("object")});function gM(e,t){return e.map(a=>{let r=t.find(n=>n.kind===a.kind&&n.plugin===a.plugin&&n.key===a.key);return r?Qve(r):{...a,objectType:"item",title:a.key,label:a.key,url:null,warning:"Saved annotation is unavailable."}})}function Qve(e){let{createdAt:t,updatedAt:a,...r}=e;return r.kind==="object"?r:{...r,kind:"object",objectType:r.objectType??"item",title:r.label}}var so=l.string().trim().min(1).max(400),vM=l.string().url().max(2048),Ux=l.string().datetime(),_Z=l.object({provider:l.string().trim().min(1).max(100),channelName:so.optional()}).strict(),Xve=l.enum(["in_progress","answered","done","partial","blocked","abandoned"]),NZ=l.object({repository:so,number:l.number().int().positive(),title:so.optional(),url:vM,state:Ox,openedAt:Ux.optional(),mergedAt:Ux.optional(),closedAt:Ux.optional()}).strict(),Yve=l.object({kind:l.enum(["code_change","resource","url"]),label:so,url:vM,status:so.optional()}).strict(),eye=l.object({startedAt:Ux,lastActivityAt:Ux,durationMs:l.number().int().nonnegative(),participants:l.array(l.object({name:so,messages:l.number().int().positive()}).strict()),userMessages:l.number().int().nonnegative(),assistantMessages:l.number().int().nonnegative(),toolResults:l.number().int().nonnegative(),events:l.number().int().nonnegative(),turns:l.number().int().positive().optional(),location:_Z.optional(),codeChanges:l.array(NZ)}).strict(),tye=l.object({schemaVersion:l.literal(1),record:eye,summary:l.string().trim().min(1).max(600),intent:so,outcome:l.object({status:Xve,text:l.string().trim().min(1).max(600)}).strict(),decisions:l.array(l.object({text:so,by:so.optional(),kind:l.enum(["stated","confirmed","assumed"])}).strict()).max(20),openDecisions:l.array(l.object({text:so,owner:so.optional()}).strict()).max(20),facts:l.array(so).max(30),links:l.array(Yve).max(40),keywords:l.array(l.string().trim().toLowerCase().min(1).max(400)).max(12)}).strict(),aye=l.object({index:l.number().int().nonnegative(),role:l.enum(["user","assistant","tool","event"]),author:so.optional(),text:l.string().min(1),createdAtMs:l.number().int().nonnegative(),turnId:l.string().min(1).optional()}).strict(),nye=l.object({label:so,url:vM,status:so.optional()}).strict(),i3e=l.object({conversationId:l.string().min(1),title:so.optional(),visibility:l.enum(["private","public"]),location:_Z.optional(),entries:l.array(aye),codeChanges:l.array(NZ),resources:l.array(nye)}).strict();var Gd=["image/png","image/jpeg","image/gif","image/webp"];var jx=3145728,yM=3,rye=l.object({filename:l.string().trim().min(1).max(255),contentType:l.enum(Gd),data:l.string().min(4).max(jx*4/3).regex(/^[A-Za-z0-9+/]*={0,2}$/).refine(e=>e.length%4===0)}).strict(),bM=l.object({id:l.string().min(1),filename:l.string().min(1),contentType:l.string().min(1),bytes:l.number().int().nonnegative()}).strict();var D1=l.object({auxiliaryCostUsd:l.number().finite().nonnegative().optional(),count:l.number().int().positive(),cumulativeDurationMs:l.number(),cumulativeUsage:fM.optional()}).strict(),oye=l.enum(["active","completed","failed"]),iye=l.enum(["api","internal","scheduler","slack"]),Bx=fM,sye=l.object({conversationId:l.string().min(1)}).strict(),s3e=l.object({attachmentId:l.string().min(1),conversationId:l.string().min(1)}).strict(),lye=l.object({limit:l.coerce.number().int().min(1).max(1e3).default(500)}).strict(),uye=l.object({before:l.string().min(1),limit:l.coerce.number().int().min(1).max(1e3).default(500)}).strict(),cye=l.object({actorEmail:l.string().trim().email().transform(e=>e.toLowerCase()).optional(),codeRepositoryId:l.string().uuid().optional(),q:l.string().trim().max(200).optional(),status:l.enum(["active","archived"]).default("active")}).strict(),dye=l.object({archived:l.boolean(),lastSeenAt:l.string().datetime()}).strict(),xM=l.object({archivedAt:l.string().datetime().nullable()}).strict(),RZ=l.object({idempotencyKey:l.string().trim().min(1).max(200),message:l.string().trim().max(32e3),images:l.array(rye).max(3).optional()}).strict().refine(e=>!!(e.message||e.images?.length),"Add a message or an image.").refine(e=>(e.images??[]).reduce((t,a)=>t+a.data.length,0)<=jx*4/3,"Images must total 3 MB or less."),fye=RZ.safeExtend({visibility:l.enum(["private","public"]).optional()}),Fx=l.object({conversationId:l.string().min(1),messageId:l.string().min(1),status:l.enum(["accepted","duplicate"])}).strict(),zm=l.object({email:l.string().optional(),fullName:l.string().optional(),slackUserId:l.string().optional(),slackUserName:l.string().optional()}).strict(),AZ=l.enum(["defer","interrupt"]),$Z=l.object({actorIdentity:zm.optional(),createdAt:l.string().datetime(),delivery:AZ,inboundMessageId:l.string().min(1),messageId:l.string().min(1),receivedAt:l.string().datetime(),role:l.literal("user"),source:l.enum(["slack","web"]),text:l.string().optional(),attachments:l.array(bM).optional(),redacted:l.literal(!0).optional()}).strict().superRefine((e,t)=>{e.text===void 0==(e.redacted!==!0)&&t.addIssue({code:"custom",message:"pending message content must be text or explicitly redacted"}),e.redacted&&(e.actorIdentity||e.attachments)&&t.addIssue({code:"custom",message:"redacted pending messages must not expose actor identity or attachments"})}),PZ=l.object({authorizationUrl:l.string().url(),completionText:l.string().min(1),label:l.string().min(1)}).strict(),SM=l.object({authorization:PZ.optional(),conversationId:l.string().min(1),generatedAt:l.string().datetime(),messages:l.array($Z)}).strict(),mye=l.object({inboundMessageIds:l.array(l.string().min(1)).min(1).optional(),receivedBefore:l.string().datetime().optional()}).strict(),wM=l.object({cancelledCount:l.number().int().nonnegative(),cancelledInboundMessageIds:l.array(l.string().min(1)),conversationId:l.string().min(1)}).strict(),E1=l.object({costUsd:l.number().finite().nonnegative(),operations:l.array(l.object({costUsd:l.number().finite().nonnegative(),events:l.number().int().positive(),name:l.string().min(1),namespace:l.string().min(1)}).strict()).min(1)}).strict(),pye=l.object({id:l.string().min(1).optional(),kind:l.enum(["scheduled","event"]),label:l.string().min(1).optional(),title:l.string().min(1).optional(),triggerMessageId:l.string().min(1).optional(),triggerLabel:l.string().min(1).optional(),credentialMode:l.enum(["creator","system"]).optional(),credentialUser:l.string().min(1).optional()}).strict().superRefine((e,t)=>{!!e.id!=!!e.label&&t.addIssue({code:"custom",message:"sourceTask id and label must both be set or both omitted"})}),hye=mZ.and(l.object({plugin:l.string().min(1),createdAt:l.string().datetime(),updatedAt:l.string().datetime()})),DZ=l.object({createdAt:l.string().datetime(),role:l.enum(["assistant","user"]),text:l.string().min(1)}).strict(),Ag=l.object({displayTitle:l.string(),activityPreview:DZ.optional(),cumulativeDurationMs:l.number(),cumulativeUsage:Bx.optional(),auxiliaryCosts:E1.optional(),childAgentTotals:D1.optional(),conversationId:l.string(),isParticipant:l.boolean(),visibility:l.enum(["private","public"]).optional(),status:oye,startedAt:l.string(),lastSeenAt:l.string(),lastProgressAt:l.string(),surface:iye,actorIdentity:zm.optional(),participants:l.array(zm).optional(),archivedAt:l.string().datetime().nullable().optional(),channel:l.string().optional(),channelName:l.string().optional(),channelNameRedacted:l.boolean().optional(),locationId:l.string().optional(),sentryTraceUrl:l.string().optional(),locationUrl:l.string().url().optional(),traceId:l.string().optional(),annotations:l.array(hye).optional(),sidebarAnnotations:l.array(pZ).optional(),assignedWork:l.boolean().optional(),finishedWorkAt:l.string().datetime().optional(),isPriority:l.boolean().optional(),unfinishedWork:l.boolean().optional()}).strict(),gye=l.object({type:l.literal("message"),messageId:l.string().min(1),role:l.enum(["assistant","system","user"]),source:l.enum(["slack","web"]).optional(),actorIdentity:zm.optional(),eventType:l.string().min(1).optional(),eventObjectType:Ng.optional(),explicitMention:l.boolean().optional(),trustedSummary:l.string().min(1).optional(),cards:l.array(Jve).optional(),text:l.string().optional(),attachments:l.array(bM).optional(),redacted:l.literal(!0).optional()}).strict().superRefine((e,t)=>{e.text===void 0==(e.redacted!==!0)&&t.addIssue({code:"custom",message:"message content must be text or explicitly redacted"}),e.redacted&&(e.actorIdentity||e.cards||e.attachments)&&t.addIssue({code:"custom",message:"redacted messages must not expose actor identity, cards, or attachments"})}),vye=l.object({type:l.literal("message_handled"),messageId:l.string().min(1)}).strict(),yye=l.object({toolCallId:l.string().min(1),name:l.string().min(1),status:l.enum(["running","completed","error"]),startedAt:l.string().datetime().optional(),startedSeq:l.number().int().nonnegative().optional(),input:l.unknown().optional(),output:l.unknown().optional()}).strict().superRefine((e,t)=>{e.startedAt===void 0!=(e.startedSeq===void 0)&&t.addIssue({code:"custom",message:"tool start sequence and timestamp must be provided together"})}),EZ=l.object({type:l.literal("reasoning"),text:l.string().min(1).optional(),redacted:l.literal(!0).optional()}).strict().superRefine((e,t)=>{e.text===void 0==(e.redacted!==!0)&&t.addIssue({code:"custom",message:"reasoning content must be text or explicitly redacted"})}),bye=l.object({type:l.literal("tool_call"),toolCallId:l.string().min(1)}).strict(),xye=l.object({parts:l.array(l.discriminatedUnion("type",[EZ,bye])).min(1)}).strict(),Sye=l.object({type:l.literal("tool_calls"),calls:l.array(yye).min(1),assistant:xye.optional()}).strict().superRefine((e,t)=>{if(!e.assistant)return;let a=new Map;for(let n of e.calls)a.set(n.toolCallId,(a.get(n.toolCallId)??0)+1);let r=new Map;for(let n of e.assistant.parts)n.type==="tool_call"&&r.set(n.toolCallId,(r.get(n.toolCallId)??0)+1);(a.size!==r.size||[...a].some(([n,o])=>r.get(n)!==o))&&t.addIssue({code:"custom",path:["assistant","parts"],message:"assistant tool parts must reference every call exactly once"})}),wye=l.object({type:l.literal("assistant_message"),parts:l.array(EZ)}).strict(),Cye=l.discriminatedUnion("state",[l.object({type:l.literal("turn_lifecycle"),turnId:l.string().min(1),state:l.enum(["succeeded","no_reply"])}).strict(),l.object({type:l.literal("turn_lifecycle"),turnId:l.string().min(1),state:l.literal("started"),inputMessageIds:l.array(l.string().min(1)).min(1).optional()}).strict(),l.object({type:l.literal("turn_lifecycle"),turnId:l.string().min(1),state:l.literal("failed"),failureCode:$1,failureReason:P1.optional(),eventId:l.string().regex(/^[a-f0-9]{32}$/i).optional(),sentryEventUrl:l.string().url().optional()}).strict()]),kye=l.object({type:l.literal("turn_routed"),turnId:l.string().min(1),modelProfile:l.string().min(1),modelId:l.string().min(1),costUsd:l.number().finite().nonnegative().optional(),reasoningLevel:l.string().min(1),confidence:l.number().min(0).max(1).optional(),source:l.enum(["configured","inherited","router"])}).strict(),Iye=l.object({type:l.literal("guardian_action_reviewed"),turnId:l.string().min(1),toolCallId:l.string().min(1),toolName:l.string().min(1),decision:l.enum(["allow","ask","deny"]),riskLevel:l.enum(["low","medium","high","critical"]),userAuthorization:l.enum(["high","medium","low","unknown"])}).strict(),Lye=l.object({type:l.literal("turn_context"),turnId:l.string().min(1),pluginName:l.string().min(1),kind:l.string().min(1),version:l.number().int().positive(),content:l.record(l.string(),l.unknown())}).strict(),Tye=l.object({type:l.literal("structured_event"),namespace:l.string().min(1),name:l.string().min(1),version:l.number().int().positive(),turnId:l.string().min(1).optional(),presentation:hZ}).strict(),_ye=l.object({type:l.literal("attachments_delivered"),attachments:l.array(bM).min(1)}).strict(),Nye=l.object({type:l.literal("compaction"),modelProfile:l.string().min(1).optional(),modelId:l.string().min(1).optional(),summary:l.string().min(1).optional(),details:l.object({reason:l.literal("capacity"),estimatedInputTokens:l.number().int().nonnegative(),replacementInputTokens:l.number().int().nonnegative().optional(),triggerTokens:l.number().int().nonnegative(),inputLimitTokens:l.number().int().positive(),inputMessageCount:l.number().int().nonnegative(),retainedMessageCount:l.number().int().nonnegative(),summaryChars:l.number().int().nonnegative()}).strict().optional()}).strict(),Rye=l.object({type:l.literal("handoff"),modelProfile:l.string().min(1),modelId:l.string().min(1),reasoningLevel:l.string().min(1).optional(),triggeringToolCallId:l.string().min(1).optional(),summary:l.string().min(1).optional()}).strict(),Aye=l.object({type:l.literal("subagent"),startedSeq:l.number().int().nonnegative(),startedAt:l.string().datetime(),childConversationId:l.string().min(1),subagentKind:l.string().min(1),agentName:l.string().min(1).optional(),task:l.string().min(1).optional(),title:l.string().min(1).optional(),parentToolCallId:l.string().min(1).optional(),status:l.enum(["running","completed","blocked","error","aborted"])}).strict(),MZ=l.discriminatedUnion("type",[gye,vye,wye,Sye,Cye,Lye,Tye,_ye,kye,Iye,Nye,Rye,Aye]),CM=l.object({seq:l.number().int().nonnegative(),createdAt:l.string().datetime(),data:MZ,model:l.object({modelId:l.string().min(1),modelProfile:l.string().min(1).optional(),reasoningLevel:l.string().min(1).optional()}).strict().optional(),modelCall:l.object({provider:l.string().min(1).optional(),api:l.string().min(1).optional(),stopReason:l.string().min(1).optional(),usage:Bx.optional()}).strict().optional()}).strict(),kM=l.discriminatedUnion("status",[l.object({status:l.literal("available")}).strict(),l.object({status:l.literal("redacted"),reason:l.literal("non_public_conversation")}).strict(),l.object({status:l.literal("expired"),expiredAt:l.string().datetime()}).strict()]),$ye=l.object({modelId:l.string(),usage:Bx}).strict();function OZ(e,t){e.eventHistory.status==="expired"&&e.events.length>0&&t.addIssue({code:"custom",path:["events"],message:"expired event history must not contain events"});for(let a=1;a<e.events.length;a+=1)e.events[a].seq<=e.events[a-1].seq&&t.addIssue({code:"custom",path:["events",a,"seq"],message:"report event sequences must be strictly increasing"});for(let[a,r]of e.events.entries())r.data.type==="message"&&(e.eventHistory.status==="redacted"&&r.data.redacted!==!0&&t.addIssue({code:"custom",path:["events",a,"data"],message:"redacted event history must redact messages"}),e.eventHistory.status==="available"&&r.data.redacted===!0&&t.addIssue({code:"custom",path:["events",a,"data"],message:"available event history must expose messages"})),e.eventHistory.status==="redacted"&&r.data.type==="tool_calls"&&r.data.calls.some(n=>n.input!==void 0||n.output!==void 0)&&t.addIssue({code:"custom",path:["events",a,"data"],message:"redacted event history must redact tool payloads"}),e.eventHistory.status==="redacted"&&r.data.type==="assistant_message"&&r.data.parts.some(n=>n.text!==void 0)&&t.addIssue({code:"custom",path:["events",a,"data"],message:"redacted event history must redact assistant messages"}),e.eventHistory.status==="available"&&r.data.type==="assistant_message"&&r.data.parts.some(n=>n.redacted===!0)&&t.addIssue({code:"custom",path:["events",a,"data"],message:"available event history must expose reasoning"}),r.data.type==="tool_calls"&&(e.eventHistory.status==="redacted"&&r.data.assistant?.parts.some(n=>n.type==="reasoning"&&n.text!==void 0)||e.eventHistory.status==="available"&&r.data.assistant?.parts.some(n=>n.type==="reasoning"&&n.redacted===!0))&&t.addIssue({code:"custom",path:["events",a,"data","assistant"],message:"assistant reasoning must match event history visibility"})}var Pye=l.object({messageId:l.string().min(1).max(500),idempotencyKey:l.string().trim().min(1).max(200)}).strict(),IM=l.object({conversationId:l.string()}).strict(),Dye=l.object({conversationId:l.string().min(1),label:l.string().min(1)}).strict(),LM=Ag.extend({agentTree:l.array(Dye).min(2).optional(),canFork:l.boolean().optional(),forkedFromConversationId:l.string().optional(),forkedFromTitle:l.string().optional(),forks:l.array(l.string()).optional(),brief:l.object({content:tye,updatedAt:l.string().datetime(),version:l.number().int().positive()}).strict().optional(),modelUsage:l.array($ye).optional(),events:l.array(CM),eventHistory:kM,previousCursor:l.string().min(1).optional(),generatedAt:l.string(),sentryConversationUrl:l.string().optional(),sourceTask:pye.optional()}).strict().superRefine(OZ),TM=l.object({events:l.array(CM),eventHistory:kM,previousCursor:l.string().min(1).optional(),generatedAt:l.string()}).strict().superRefine(OZ),M1=l.object({conversations:l.array(Ag),source:l.literal("conversation_index"),generatedAt:l.string()}).strict(),Um=l.object({active:l.number(),conversations:l.number(),durationMs:l.number(),failed:l.number(),label:l.string(),costUsd:l.number().optional(),tokens:l.number().optional()}).strict(),zZ=l.string().regex(/^\d{4}-\d{2}-\d{2}(T\d{2})?$/),mM=l.object({cachedInputTokens:l.number().optional(),cacheCreationTokens:l.number().optional(),conversations:l.number(),costUsd:l.number().optional(),date:zZ,durationMs:l.number(),inputTokens:l.number().optional(),tokens:l.number().optional()}).strict(),pM=l.object({allow:l.number(),ask:l.number(),costUsd:l.number().optional(),date:zZ,deny:l.number(),requests:l.number()}).strict(),Eye=l.object({allow:l.number(),ask:l.number(),costUsd:l.number().optional(),deny:l.number(),metricDays:l.array(pM),metricHours:l.array(pM).optional(),metricSixHours:l.array(pM).optional(),requests:l.number()}).strict(),_M=l.object({active:l.number(),cachedInputTokens:l.number().optional(),cacheCreationTokens:l.number().optional(),conversations:l.number(),durationMs:l.number(),failed:l.number(),generatedAt:l.string(),guardian:Eye,metricDays:l.array(mM),metricHours:l.array(mM).optional(),metricSixHours:l.array(mM).optional(),locations:l.array(Um),actors:l.array(Um),source:l.literal("conversation_index"),costUsd:l.number().optional(),inputTokens:l.number().optional(),tokens:l.number().optional(),windowEnd:l.string(),windowStart:l.string()}).strict();var Mye=l.enum(["current_conversation","task_creator"]).describe("Where to send the message. Use current_conversation for posts, digests, summaries, and channel reminders. Use task_creator only when the user asks for a direct reminder or notification."),Oye=l.object({action:l.literal("send_message"),destination:Mye}).strict(),HZ=l.string().regex(/^\d{4}-\d{2}-\d{2}$/,"Use a local date in YYYY-MM-DD format."),VZ=l.string().regex(/^([01]\d|2[0-3]):[0-5]\d$/,"Use local time in HH:MM format."),qZ=l.string().min(1).max(80).describe("IANA timezone the user asked for, for example America/New_York. Omit or use null to use the creator's timezone on create, or to keep the saved timezone on update. Do not guess it from office locations.").nullable().optional(),zye=l.enum(["sunday","monday","tuesday","wednesday","thursday","friday","saturday"]),Uye=l.object({kind:l.literal("one_off").describe("A schedule that runs once."),timezone:qZ,timing:l.discriminatedUnion("type",[l.object({type:l.literal("after").describe("Run after a relative delay from the server clock."),value:l.number().int().positive().max(1e5),unit:l.enum(["second","minute","hour","day","week"])}).strict(),l.object({type:l.literal("at").describe("Run at an explicit local calendar date and time."),date:HZ.describe("Requested local calendar date in YYYY-MM-DD format."),time:VZ.describe("Requested local wall-clock time in HH:MM format.")}).strict()]).describe("Relative delay or explicit local time for the one-off run.")}).strict(),jye=l.object({kind:l.literal("recurring").describe("A repeating calendar schedule."),frequency:l.enum(["daily","weekly","monthly","yearly"]).describe("Recurring tasks can run at most once per day."),interval:l.number().int().positive().max(365).describe("Repeat every N frequency units. Defaults to 1.").nullable().optional(),time:VZ.describe("Local wall-clock time for each occurrence in HH:MM format."),weekdays:l.array(zye).min(1).max(7).describe("Required for weekly schedules.").nullable().optional(),dayOfMonth:l.number().int().min(1).max(31).describe("Required for monthly and yearly schedules.").nullable().optional(),month:l.number().int().min(1).max(12).describe("Required for yearly schedules, where January is 1.").nullable().optional(),startDate:HZ.describe("Optional local calendar date that anchors the recurrence. Omit to start with the next matching occurrence.").nullable().optional(),timezone:qZ}).strict().superRefine((e,t)=>{e.frequency==="weekly"&&e.weekdays==null&&t.addIssue({code:"custom",message:"Weekly schedules require weekdays.",path:["weekdays"]}),(e.frequency==="monthly"||e.frequency==="yearly")&&e.dayOfMonth==null&&t.addIssue({code:"custom",message:`${e.frequency} schedules require dayOfMonth.`,path:["dayOfMonth"]}),e.frequency==="yearly"&&e.month==null&&t.addIssue({code:"custom",message:"Yearly schedules require month.",path:["month"]}),e.frequency!=="weekly"&&e.weekdays!=null&&t.addIssue({code:"custom",message:"weekdays applies only to weekly schedules.",path:["weekdays"]}),e.frequency!=="monthly"&&e.frequency!=="yearly"&&e.dayOfMonth!=null&&t.addIssue({code:"custom",message:"dayOfMonth applies only to monthly or yearly schedules.",path:["dayOfMonth"]}),e.frequency!=="yearly"&&e.month!=null&&t.addIssue({code:"custom",message:"month applies only to yearly schedules.",path:["month"]})}),ZZ=l.union([Uye,jye]);var GZ=l.object({slackUserId:A1,fullName:l.string().optional(),userName:l.string().optional()}).strict(),RM=l.object({events:l.array(hc).min(1),label:l.string().min(1),match:uM.optional(),namespace:l.string().min(1),identifier:l.string().min(1).max(300),resourceType:l.string().min(1)}).strict(),KZ=Rg.omit({threadTs:!0}),Bye=zx.extend({destination:KZ}),Fye=l.object({id:l.string().min(1),createdAtMs:l.number().finite(),createdBy:GZ,creatorIdentityId:l.string().min(1),credentialMode:l.enum(["system","creator"]),destination:KZ,destinationVisibility:sM,outcomes:l.array(Bye).max(5),task:l.object({text:l.string().min(1)}).strict(),trigger:RM}).strict(),Hye=l.string().trim().min(1).max(60),WZ=l.string().trim().min(1).max(4e3),v3e=WZ.describe("Work to perform when the Automation runs. It runs later without this conversation, so write it to stand alone: name each person with their Slack mention, such as <@U123>, instead of me, my, or you. Preserve the user's scope, targets, and constraints. Do not add permissions or side effects the user did not request."),JZ=l.object({title:Hye.optional(),instruction:WZ.optional(),credentialMode:l.enum(["system","creator"]).optional(),outcomes:l.array(l.union([Oye,zx])).max(5).optional()}),Vye=JZ.extend({schedule:ZZ.optional(),status:l.enum(["active","blocked"]).optional()}).strict(),qye=JZ.extend({trigger:RM.extend({identifier:l.string().trim().min(1).max(300),label:l.string().trim().min(1).max(500)}).optional()}).strict(),Zye=l.enum(["active","blocked","paused","completed","deleted"]),Gye=l.enum(["system","creator"]),Kye=l.enum(["pending","running","completed","failed","blocked","skipped"]),Wye=l.object({slackUserId:A1,fullName:l.string().optional(),userName:l.string().optional()}).strict(),Jye=l.object({dayOfMonth:l.number().optional(),frequency:l.enum(["daily","weekly","monthly","yearly"]),interval:l.number(),month:l.number().optional(),startDate:l.string(),time:l.object({hour:l.number(),minute:l.number()}).strict(),weekdays:l.array(l.number()).optional()}).strict(),Qye=l.object({description:l.string(),kind:l.enum(["one_off","recurring"]),recurrence:Jye.optional(),timezone:l.string()}).strict(),Xye=l.object({platform:l.literal("system"),name:l.string()}).strict(),QZ=Rg.omit({threadTs:!0}),Yye=l.object({action:l.literal("send_message"),destination:QZ}).strict(),z1=l.object({id:l.string(),conversationAccess:l.object({audience:l.enum(["direct","group","channel"]),visibility:l.enum(["private","public"])}).strict(),createdAtMs:l.number(),createdBy:Wye,creatorIdentityId:l.string(),credentialMode:Gye,destination:QZ,executionActor:Xye.optional(),lastRunAtMs:l.number().optional(),nextRunAtMs:l.number().optional(),originalRequest:l.string().optional(),runNowAtMs:l.number().optional(),schedule:Qye,status:Zye,statusReason:l.string().optional(),outcomes:l.array(Yye).max(5),task:l.object({text:l.string()}).strict(),title:l.string().optional(),updatedAtMs:l.number()}).strict(),y3e=l.object({id:l.string(),attempt:l.number(),claimedAtMs:l.number(),completedAtMs:l.number().optional(),dispatchId:l.string().optional(),errorMessage:l.string().optional(),resultMessageTs:l.string().optional(),scheduledForMs:l.number(),startedAtMs:l.number().optional(),status:Kye,taskId:l.string()}).strict(),b3e=Object.freeze({platform:"system",name:"scheduled-automation"}),ebe=l.object({channelId:l.string().min(1),label:l.string().min(1),teamId:l.string().min(1),visibility:l.enum(["private","public"])}).strict(),XZ=l.object({1:l.number().int().nonnegative(),7:l.number().int().nonnegative(),30:l.number().int().nonnegative(),90:l.number().int().nonnegative()}).strict(),YZ=l.object({credentialMode:l.enum(["creator","system"]),createdAt:l.string().datetime(),createdBy:l.string().min(1),createdByAvatarUrl:l.string().url().optional(),createdByEmail:l.string().trim().email().optional(),destination:ebe,id:l.string().min(1),instruction:l.string().min(1),lastConversationId:l.string().min(1).optional(),lastRunAt:l.string().datetime().optional(),lastRunStatus:l.enum(["blocked","completed","failed"]).optional(),ownedByViewer:l.boolean(),runs:XZ,outcomes:l.array(zx).max(5),title:l.string().min(1),totalRuns:l.number().int().nonnegative()}),eG=YZ.extend({kind:l.literal("scheduled"),nextRunAt:l.string().datetime().optional(),schedule:l.string().min(1),timezone:l.string().min(1),statusReason:l.string().optional(),status:l.enum(["active","blocked","paused","completed"])}).strict(),tG=YZ.extend({events:l.array(l.string().min(1)).min(1),match:uM.optional(),kind:l.literal("event"),resource:l.string().min(1),source:l.string().min(1),triggerAvailable:l.boolean(),statusReason:l.string().optional(),status:l.enum(["active","blocked","paused"])}).strict(),Vx=l.discriminatedUnion("kind",[eG,tG]),aG=l.string().regex(/^\d{4}-\d{2}-\d{2}(T\d{2})?$/),NM=l.object({costUsd:l.number().finite().nonnegative(),date:aG,event:l.number().int().nonnegative(),scheduled:l.number().int().nonnegative()}).strict(),U1=l.object({q:l.string().trim().max(200).optional(),scope:l.enum(["all","mine","public","attention"]).default("all"),type:l.enum(["all","scheduled","event"]).default("all"),state:l.enum(["all","active","blocked","paused","completed","unavailable"]).default("all"),creator:l.string().max(300).optional(),destination:l.string().max(300).optional(),sort:l.enum(["newest","oldest","title"]).default("newest"),page:l.coerce.number().int().min(1).max(1e6).default(1),pageSize:l.coerce.number().int().min(1).max(100).default(25)}).strict(),UZ=l.object({value:l.string(),label:l.string()}).strict(),AM=l.object({executionDays:l.array(NM),executionHours:l.array(NM).optional(),executionSixHours:l.array(NM).optional(),automations:l.array(Vx),total:l.number().int().nonnegative(),page:l.number().int().positive(),pageSize:l.number().int().positive(),counts:l.object({all:l.number().int().nonnegative(),mine:l.number().int().nonnegative(),public:l.number().int().nonnegative(),private:l.number().int().nonnegative()}).strict(),creators:l.array(UZ),destinations:l.array(UZ)}).strict(),nG=l.object({id:l.string().min(1)}).strict(),rG=l.enum(["blocked","completed","failed"]),$M=l.object({conversationId:l.string().min(1).optional(),costUsd:l.number().finite().nonnegative().optional(),durationMs:l.number().finite().nonnegative().optional(),executedAt:l.string().datetime(),executionId:l.string().min(1),status:rG,title:l.string().min(1).optional(),totalTokens:l.number().int().nonnegative().optional()}).strict(),O1=l.object({blocked:l.number().int().nonnegative(),completed:l.number().int().nonnegative(),date:aG,failed:l.number().int().nonnegative()}).strict(),PM=l.object({executionDays:l.array(O1),executionHours:l.array(O1).optional(),executionSixHours:l.array(O1).optional(),executions:l.array($M),automation:Vx,truncated:l.boolean()}).strict(),oG=$M.extend({kind:l.enum(["scheduled","event"]),automationId:l.string().min(1),automationTitle:l.string().min(1)}).strict(),DM=l.object({runs:l.array(oG),truncated:l.boolean()}).strict(),jZ={title:l.string().nullable(),instruction:l.string()},BZ={version:l.number().int().positive(),createdAt:l.string().datetime(),editedBy:GZ.nullable()},iG=l.discriminatedUnion("kind",[l.object({...BZ,kind:l.literal("scheduled"),definition:z1.pick({credentialMode:!0,destination:!0,outcomes:!0,schedule:!0}).extend(jZ).strict()}).strict(),l.object({...BZ,kind:l.literal("event"),definition:Fye.pick({credentialMode:!0,destination:!0,outcomes:!0,trigger:!0}).extend(jZ).strict()}).strict()]),EM=l.object({versions:l.array(iG),activeVersion:l.number().int().positive().nullable(),truncated:l.boolean()}).strict(),tbe=nG.extend({version:l.coerce.number().int().positive()}).strict(),Hx=l.string().regex(/^[a-f0-9]{64}$/),abe=l.object({revision:Hx}).strict(),x3e=l.object({action:l.enum(["pause","resume"]),revision:Hx}).strict(),FZ=z1.pick({destination:!0,createdBy:!0}).extend({id:l.string().min(1),revision:Hx,title:l.string().nullable(),instruction:l.string(),credentialMode:l.enum(["system","creator"]),outcomes:l.array(zx).max(5),ownedByViewer:l.boolean()}),Ns=l.discriminatedUnion("kind",[FZ.merge(z1.pick({schedule:!0})).extend({kind:l.literal("scheduled"),nextRunAtMs:l.number().optional(),status:l.enum(["active","blocked","paused","completed"])}).strict(),FZ.extend({kind:l.literal("event"),trigger:RM,triggerAvailable:l.boolean(),status:l.enum(["active","blocked","paused"])}).strict()]),MM=l.discriminatedUnion("kind",[Vye.omit({status:!0}).extend({kind:l.literal("scheduled"),revision:Hx}).strict(),qye.extend({kind:l.literal("event"),revision:Hx}).strict()]),nbe=l.object({error:l.string(),code:l.enum(["invalid_edit","conflict","not_found"]),fields:l.record(l.string(),l.array(l.string())).optional()}).strict(),OM=l.array(cM.safeExtend({namespace:l.string()})),zM=ZZ,UM=z1.pick({schedule:!0}).extend({nextRunAtMs:l.number()}).strict();var rbe=l.object({status:l.literal("ok"),service:l.string(),timestamp:l.string()}).strict(),sG=l.object({configKeys:l.array(l.string()),description:l.string(),displayName:l.string(),name:l.string()}).strict(),jM=l.array(sG),BM=l.object({name:l.string(),pluginProvider:l.string().optional()}).strict(),FM=l.array(BM),lG=l.object({dir:l.string(),hasMigrationsDir:l.boolean(),hasSkillsDir:l.boolean(),packageName:l.string()}).strict(),uG=l.object({packageNames:l.array(l.string()),packages:l.array(lG),manifestRoots:l.array(l.string()),skillRoots:l.array(l.string()),tracingIncludes:l.array(l.string())}).strict(),obe=l.object({cwd:l.string(),homeDir:l.string(),descriptionText:l.string().optional(),providers:l.array(l.string()),skills:l.array(BM),packagedContent:uG}).strict(),HM=l.enum(["danger","good","neutral","warning"]),ibe=l.object({label:l.string(),tone:HM.optional(),value:l.string()}).strict(),sbe=l.object({key:l.string(),label:l.string()}).strict(),lbe=l.object({id:l.string(),tone:HM.optional(),values:l.record(l.string(),l.string())}).strict(),ube=l.object({fields:l.array(sbe).optional(),emptyText:l.string().optional(),records:l.array(lbe).optional(),title:l.string()}).strict(),cbe=l.object({categories:l.array(l.object({id:l.string().min(1),label:l.string().min(1),values:l.record(l.string(),l.number().finite())}).strict()).max(100),description:l.string().optional(),emptyText:l.string().optional(),id:l.string().min(1),series:l.array(l.object({format:l.literal("usd").optional(),key:l.string().min(1),label:l.string().min(1),tone:HM.optional()}).strict()).min(1).max(8),timeRangeDays:l.array(l.union([l.literal(1),l.literal(7),l.literal(30),l.literal(90)])).min(1).max(4).optional(),title:l.string().min(1),type:l.literal("bar_chart")}).strict(),cG=l.object({generatedAt:l.string().optional(),metrics:l.array(ibe).optional(),recordSets:l.array(ube).optional(),title:l.string().optional(),pluginName:l.string(),widgets:l.array(cbe).max(12).optional()}).strict(),j1=l.object({generatedAt:l.string(),reports:l.array(cG),source:l.literal("plugins")}).strict(),dG=36e5,C3e=6*dG,k3e=24*dG;async function VM(e){let t=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(`${e.conversationId}\0${e.idempotencyKey}`));return`api-msg:${Array.from(new Uint8Array(t),a=>a.toString(16).padStart(2,"0")).join("").slice(0,24)}`}var E=Symbol.for("drizzle:entityKind");function Wn(e,t){if(!e||typeof e!="object")return!1;if(e instanceof t)return!0;if(!Object.prototype.hasOwnProperty.call(t,E))throw new Error(`Class "${t.name??"<unknown>"}" doesn't look like a Drizzle entity. If this is incorrect and the class is provided by Drizzle, please report this as a bug.`);let a=Object.getPrototypeOf(e).constructor;if(a)for(;a;){if(E in a&&a[E]===t[E])return!0;a=Object.getPrototypeOf(a)}return!1}var jm=class{constructor(t,a){this.table=t,this.config=a,this.name=a.name,this.keyAsName=a.keyAsName,this.notNull=a.notNull,this.default=a.default,this.defaultFn=a.defaultFn,this.onUpdateFn=a.onUpdateFn,this.hasDefault=a.hasDefault,this.primary=a.primaryKey,this.isUnique=a.isUnique,this.uniqueName=a.uniqueName,this.uniqueType=a.uniqueType,this.dataType=a.dataType,this.columnType=a.columnType,this.generated=a.generated,this.generatedIdentity=a.generatedIdentity}static[E]="Column";name;keyAsName;primary;notNull;default;defaultFn;onUpdateFn;hasDefault;isUnique;uniqueName;uniqueType;dataType;columnType;enumValues=void 0;generated=void 0;generatedIdentity=void 0;config;mapFromDriverValue(t){return t}mapToDriverValue(t){return t}shouldDisableInsert(){return this.config.generated!==void 0&&this.config.generated.type!=="byDefault"}};var B1=class{static[E]="ColumnBuilder";config;constructor(t,a,r){this.config={name:t,keyAsName:t==="",notNull:!1,default:void 0,hasDefault:!1,primaryKey:!1,isUnique:!1,uniqueName:void 0,uniqueType:void 0,dataType:a,columnType:r,generated:void 0}}$type(){return this}notNull(){return this.config.notNull=!0,this}default(t){return this.config.default=t,this.config.hasDefault=!0,this}$defaultFn(t){return this.config.defaultFn=t,this.config.hasDefault=!0,this}$default=this.$defaultFn;$onUpdateFn(t){return this.config.onUpdateFn=t,this.config.hasDefault=!0,this}$onUpdate=this.$onUpdateFn;primaryKey(){return this.config.primaryKey=!0,this.config.notNull=!0,this}setName(t){this.config.name===""&&(this.config.name=t)}};var gc=Symbol.for("drizzle:Name");var F1=class{static[E]="PgForeignKeyBuilder";reference;_onUpdate="no action";_onDelete="no action";constructor(t,a){this.reference=()=>{let{name:r,columns:n,foreignColumns:o}=t();return{name:r,columns:n,foreignTable:o[0].table,foreignColumns:o}},a&&(this._onUpdate=a.onUpdate,this._onDelete=a.onDelete)}onUpdate(t){return this._onUpdate=t===void 0?"no action":t,this}onDelete(t){return this._onDelete=t===void 0?"no action":t,this}build(t){return new qM(t,this)}},qM=class{constructor(t,a){this.table=t,this.reference=a.reference,this.onUpdate=a._onUpdate,this.onDelete=a._onDelete}static[E]="PgForeignKey";reference;onUpdate;onDelete;getName(){let{name:t,columns:a,foreignColumns:r}=this.reference(),n=a.map(s=>s.name),o=r.map(s=>s.name),i=[this.table[gc],...n,r[0].table[gc],...o];return t??`${i.join("_")}_fk`}};function H1(e,...t){return e(...t)}function KM(e,t){return`${e[gc]}_${t.join("_")}_unique`}var ZM=class{constructor(t,a){this.name=a,this.columns=t}static[E]="PgUniqueConstraintBuilder";columns;nullsNotDistinctConfig=!1;nullsNotDistinct(){return this.nullsNotDistinctConfig=!0,this}build(t){return new GM(t,this.columns,this.nullsNotDistinctConfig,this.name)}},fG=class{static[E]="PgUniqueOnConstraintBuilder";name;constructor(t){this.name=t}on(...t){return new ZM(t,this.name)}},GM=class{constructor(t,a,r,n){this.table=t,this.columns=a,this.name=n??KM(this.table,this.columns.map(o=>o.name)),this.nullsNotDistinct=r}static[E]="PgUniqueConstraint";columns;name;nullsNotDistinct=!1;getName(){return this.name}};function mG(e,t,a){for(let r=t;r<e.length;r++){let n=e[r];if(n==="\\"){r++;continue}if(n==='"')return[e.slice(t,r).replace(/\\/g,""),r+1];if(!a&&(n===","||n==="}"))return[e.slice(t,r).replace(/\\/g,""),r]}return[e.slice(t).replace(/\\/g,""),e.length]}function pG(e,t=0){let a=[],r=t,n=!1;for(;r<e.length;){let o=e[r];if(o===","){(n||r===t)&&a.push(""),n=!0,r++;continue}if(n=!1,o==="\\"){r+=2;continue}if(o==='"'){let[u,c]=mG(e,r+1,!0);a.push(u),r=c;continue}if(o==="}")return[a,r+1];if(o==="{"){let[u,c]=pG(e,r+1);a.push(u),r=c;continue}let[i,s]=mG(e,r,!1);a.push(i),r=s}return[a,r]}function hG(e){let[t]=pG(e,1);return t}function WM(e){return`{${e.map(t=>Array.isArray(t)?WM(t):typeof t=="string"?`"${t.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`:`${t}`).join(",")}}`}var de=class extends B1{foreignKeyConfigs=[];static[E]="PgColumnBuilder";array(t){return new QM(this.config.name,this,t)}references(t,a={}){return this.foreignKeyConfigs.push({ref:t,actions:a}),this}unique(t,a){return this.config.isUnique=!0,this.config.uniqueName=t,this.config.uniqueType=a?.nulls,this}generatedAlwaysAs(t){return this.config.generated={as:t,type:"always",mode:"stored"},this}buildForeignKeys(t,a){return this.foreignKeyConfigs.map(({ref:r,actions:n})=>H1((o,i)=>{let s=new F1(()=>{let u=o();return{columns:[t],foreignColumns:[u]}});return i.onUpdate&&s.onUpdate(i.onUpdate),i.onDelete&&s.onDelete(i.onDelete),s.build(a)},r,n))}buildExtraConfigColumn(t){return new JM(t,this.config)}},ne=class extends jm{constructor(t,a){a.uniqueName||(a.uniqueName=KM(t,[a.name])),super(t,a),this.table=t}static[E]="PgColumn"},JM=class extends ne{static[E]="ExtraConfigColumn";getSQLType(){return this.getSQLType()}indexConfig={order:this.config.order??"asc",nulls:this.config.nulls??"last",opClass:this.config.opClass};defaultConfig={order:"asc",nulls:"last",opClass:void 0};asc(){return this.indexConfig.order="asc",this}desc(){return this.indexConfig.order="desc",this}nullsFirst(){return this.indexConfig.nulls="first",this}nullsLast(){return this.indexConfig.nulls="last",this}op(t){return this.indexConfig.opClass=t,this}},$g=class{static[E]="IndexedColumn";constructor(t,a,r,n){this.name=t,this.keyAsName=a,this.type=r,this.indexConfig=n}name;keyAsName;type;indexConfig},QM=class extends de{static[E]="PgArrayBuilder";constructor(t,a,r){super(t,"array","PgArray"),this.config.baseBuilder=a,this.config.size=r}build(t){let a=this.config.baseBuilder.build(t);return new XM(t,this.config,a)}},XM=class e extends ne{constructor(t,a,r,n){super(t,a),this.baseColumn=r,this.range=n,this.size=a.size}size;static[E]="PgArray";getSQLType(){return`${this.baseColumn.getSQLType()}[${typeof this.size=="number"?this.size:""}]`}mapFromDriverValue(t){return typeof t=="string"&&(t=hG(t)),t.map(a=>this.baseColumn.mapFromDriverValue(a))}mapToDriverValue(t,a=!1){let r=t.map(n=>n===null?null:Wn(this.baseColumn,e)?this.baseColumn.mapToDriverValue(n,!0):this.baseColumn.mapToDriverValue(n));return a?r:WM(r)}};var gG=class extends de{static[E]="PgEnumObjectColumnBuilder";constructor(t,a){super(t,"string","PgEnumObjectColumn"),this.config.enum=a}build(t){return new YM(t,this.config)}},YM=class extends ne{static[E]="PgEnumObjectColumn";enum;enumValues=this.config.enum.enumValues;constructor(t,a){super(t,a),this.enum=a.enum}getSQLType(){return this.enum.enumName}},vG=Symbol.for("drizzle:isPgEnum");function bG(e){return!!e&&typeof e=="function"&&vG in e&&e[vG]===!0}var yG=class extends de{static[E]="PgEnumColumnBuilder";constructor(t,a){super(t,"string","PgEnumColumn"),this.config.enum=a}build(t){return new eO(t,this.config)}},eO=class extends ne{static[E]="PgEnumColumn";enum=this.config.enum;enumValues=this.config.enum.enumValues;constructor(t,a){super(t,a),this.enum=a.enum}getSQLType(){return this.enum.enumName}};var Pg=class{static[E]="Subquery";constructor(t,a,r,n=!1,o=[]){this._={brand:"Subquery",sql:t,selectedFields:a,alias:r,isWith:n,usedTables:o}}},xG=class extends Pg{static[E]="WithSubquery"};var SG="0.45.2";var tO,aO,wG={startActiveSpan(e,t){return tO?(aO||(aO=tO.trace.getTracer("drizzle-orm",SG)),H1((a,r)=>r.startActiveSpan(e,n=>{try{return t(n)}catch(o){throw n.setStatus({code:a.SpanStatusCode.ERROR,message:o instanceof Error?o.message:"Unknown error"}),o}finally{n.end()}}),tO,aO)):t()}};var Dg=Symbol.for("drizzle:ViewBaseConfig");var nO=Symbol.for("drizzle:Schema"),CG=Symbol.for("drizzle:Columns"),kG=Symbol.for("drizzle:ExtraConfigColumns"),rO=Symbol.for("drizzle:OriginalName"),oO=Symbol.for("drizzle:BaseName"),qx=Symbol.for("drizzle:IsAlias"),IG=Symbol.for("drizzle:ExtraConfigBuilder"),dbe=Symbol.for("drizzle:IsDrizzleTable"),$n=class{static[E]="Table";static Symbol={Name:gc,Schema:nO,OriginalName:rO,Columns:CG,ExtraConfigColumns:kG,BaseName:oO,IsAlias:qx,ExtraConfigBuilder:IG};[gc];[rO];[nO];[CG];[kG];[oO];[qx]=!1;[dbe]=!0;[IG]=void 0;constructor(t,a,r){this[gc]=this[rO]=t,this[nO]=a,this[oO]=r}};var LG=class{static[E]="FakePrimitiveParam"};function fbe(e){return e!=null&&typeof e.getSQL=="function"}function mbe(e){let t={sql:"",params:[]};for(let a of e)t.sql+=a.sql,t.params.push(...a.params),a.typings?.length&&(t.typings||(t.typings=[]),t.typings.push(...a.typings));return t}var Wi=class{static[E]="StringChunk";value;constructor(t){this.value=Array.isArray(t)?t:[t]}getSQL(){return new Pn([this])}},Pn=class e{constructor(t){this.queryChunks=t;for(let a of t)if(Wn(a,$n)){let r=a[$n.Symbol.Schema];this.usedTables.push(r===void 0?a[$n.Symbol.Name]:r+"."+a[$n.Symbol.Name])}}static[E]="SQL";decoder=TG;shouldInlineParams=!1;usedTables=[];append(t){return this.queryChunks.push(...t.queryChunks),this}toQuery(t){return wG.startActiveSpan("drizzle.buildSQL",a=>{let r=this.buildQueryFromSourceParams(this.queryChunks,t);return a?.setAttributes({"drizzle.query.text":r.sql,"drizzle.query.params":JSON.stringify(r.params)}),r})}buildQueryFromSourceParams(t,a){let r=Object.assign({},a,{inlineParams:a.inlineParams||this.shouldInlineParams,paramStartIndex:a.paramStartIndex||{value:0}}),{casing:n,escapeName:o,escapeParam:i,prepareTyping:s,inlineParams:u,paramStartIndex:c}=r;return mbe(t.map(d=>{if(Wn(d,Wi))return{sql:d.value.join(""),params:[]};if(Wn(d,Zx))return{sql:o(d.value),params:[]};if(d===void 0)return{sql:"",params:[]};if(Array.isArray(d)){let f=[new Wi("(")];for(let[m,h]of d.entries())f.push(h),m<d.length-1&&f.push(new Wi(", "));return f.push(new Wi(")")),this.buildQueryFromSourceParams(f,r)}if(Wn(d,e))return this.buildQueryFromSourceParams(d.queryChunks,{...r,inlineParams:u||d.shouldInlineParams});if(Wn(d,$n)){let f=d[$n.Symbol.Schema],m=d[$n.Symbol.Name];return{sql:f===void 0||d[qx]?o(m):o(f)+"."+o(m),params:[]}}if(Wn(d,jm)){let f=n.getColumnCasing(d);if(a.invokeSource==="indexes")return{sql:o(f),params:[]};let m=d.table[$n.Symbol.Schema];return{sql:d.table[qx]||m===void 0?o(d.table[$n.Symbol.Name])+"."+o(f):o(m)+"."+o(d.table[$n.Symbol.Name])+"."+o(f),params:[]}}if(Wn(d,iO)){let f=d[Dg].schema,m=d[Dg].name;return{sql:f===void 0||d[Dg].isAlias?o(m):o(f)+"."+o(m),params:[]}}if(Wn(d,V1)){if(Wn(d.value,Gx))return{sql:i(c.value++,d),params:[d],typings:["none"]};let f=d.value===null?null:d.encoder.mapToDriverValue(d.value);if(Wn(f,e))return this.buildQueryFromSourceParams([f],r);if(u)return{sql:this.mapInlineParam(f,r),params:[]};let m=["none"];return s&&(m=[s(d.encoder)]),{sql:i(c.value++,f),params:[f],typings:m}}return Wn(d,Gx)?{sql:i(c.value++,d),params:[d],typings:["none"]}:Wn(d,e.Aliased)&&d.fieldAlias!==void 0?{sql:o(d.fieldAlias),params:[]}:Wn(d,Pg)?d._.isWith?{sql:o(d._.alias),params:[]}:this.buildQueryFromSourceParams([new Wi("("),d._.sql,new Wi(") "),new Zx(d._.alias)],r):bG(d)?d.schema?{sql:o(d.schema)+"."+o(d.enumName),params:[]}:{sql:o(d.enumName),params:[]}:fbe(d)?d.shouldOmitSQLParens?.()?this.buildQueryFromSourceParams([d.getSQL()],r):this.buildQueryFromSourceParams([new Wi("("),d.getSQL(),new Wi(")")],r):u?{sql:this.mapInlineParam(d,r),params:[]}:{sql:i(c.value++,d),params:[d],typings:["none"]}}))}mapInlineParam(t,{escapeString:a}){if(t===null)return"null";if(typeof t=="number"||typeof t=="boolean")return t.toString();if(typeof t=="string")return a(t);if(typeof t=="object"){let r=t.toString();return a(r==="[object Object]"?JSON.stringify(t):r)}throw new Error("Unexpected param value: "+t)}getSQL(){return this}as(t){return t===void 0?this:new e.Aliased(this,t)}mapWith(t){return this.decoder=typeof t=="function"?{mapFromDriverValue:t}:t,this}inlineParams(){return this.shouldInlineParams=!0,this}if(t){return t?this:void 0}},Zx=class{constructor(t){this.value=t}static[E]="Name";brand;getSQL(){return new Pn([this])}};var TG={mapFromDriverValue:e=>e},_G={mapToDriverValue:e=>e},pje={...TG,..._G},V1=class{constructor(t,a=_G){this.value=t,this.encoder=a}static[E]="Param";brand;getSQL(){return new Pn([this])}};function nu(e,...t){let a=[];(t.length>0||e.length>0&&e[0]!=="")&&a.push(new Wi(e[0]));for(let[r,n]of t.entries())a.push(n,new Wi(e[r+1]));return new Pn(a)}(e=>{function t(){return new Pn([])}e.empty=t;function a(u){return new Pn(u)}e.fromList=a;function r(u){return new Pn([new Wi(u)])}e.raw=r;function n(u,c){let d=[];for(let[f,m]of u.entries())f>0&&c!==void 0&&d.push(c),d.push(m);return new Pn(d)}e.join=n;function o(u){return new Zx(u)}e.identifier=o;function i(u){return new Gx(u)}e.placeholder=i;function s(u,c){return new V1(u,c)}e.param=s})(nu||(nu={}));(e=>{class t{constructor(r,n){this.sql=r,this.fieldAlias=n}static[E]="SQL.Aliased";isSelectionField=!1;getSQL(){return this.sql}clone(){return new t(this.sql,this.fieldAlias)}}e.Aliased=t})(Pn||(Pn={}));var Gx=class{constructor(t){this.name=t}static[E]="Placeholder";getSQL(){return new Pn([this])}};var pbe=Symbol.for("drizzle:IsDrizzleView"),iO=class{static[E]="View";[Dg];[pbe]=!0;constructor({name:t,schema:a,selectedFields:r,query:n}){this[Dg]={name:t,originalName:t,schema:a,selectedFields:r,query:n,isExisting:!n,isAlias:!1}}getSQL(){return new Pn([this])}};jm.prototype.getSQL=function(){return new Pn([this])};$n.prototype.getSQL=function(){return new Pn([this])};Pg.prototype.getSQL=function(){return new Pn([this])};function $t(e,t){return{name:typeof e=="string"&&e.length>0?e:"",config:typeof e=="object"?e:t}}var gje=typeof TextDecoder>"u"?null:new TextDecoder;var vc=class extends de{static[E]="PgIntColumnBaseBuilder";generatedAlwaysAsIdentity(t){if(t){let{name:a,...r}=t;this.config.generatedIdentity={type:"always",sequenceName:a,sequenceOptions:r}}else this.config.generatedIdentity={type:"always"};return this.config.hasDefault=!0,this.config.notNull=!0,this}generatedByDefaultAsIdentity(t){if(t){let{name:a,...r}=t;this.config.generatedIdentity={type:"byDefault",sequenceName:a,sequenceOptions:r}}else this.config.generatedIdentity={type:"byDefault"};return this.config.hasDefault=!0,this.config.notNull=!0,this}};var sO=class extends vc{static[E]="PgBigInt53Builder";constructor(t){super(t,"number","PgBigInt53")}build(t){return new lO(t,this.config)}},lO=class extends ne{static[E]="PgBigInt53";getSQLType(){return"bigint"}mapFromDriverValue(t){return typeof t=="number"?t:Number(t)}},uO=class extends vc{static[E]="PgBigInt64Builder";constructor(t){super(t,"bigint","PgBigInt64")}build(t){return new cO(t,this.config)}},cO=class extends ne{static[E]="PgBigInt64";getSQLType(){return"bigint"}mapFromDriverValue(t){return BigInt(t)}};function NG(e,t){let{name:a,config:r}=$t(e,t);return r.mode==="number"?new sO(a):new uO(a)}var dO=class extends de{static[E]="PgBigSerial53Builder";constructor(t){super(t,"number","PgBigSerial53"),this.config.hasDefault=!0,this.config.notNull=!0}build(t){return new fO(t,this.config)}},fO=class extends ne{static[E]="PgBigSerial53";getSQLType(){return"bigserial"}mapFromDriverValue(t){return typeof t=="number"?t:Number(t)}},mO=class extends de{static[E]="PgBigSerial64Builder";constructor(t){super(t,"bigint","PgBigSerial64"),this.config.hasDefault=!0}build(t){return new pO(t,this.config)}},pO=class extends ne{static[E]="PgBigSerial64";getSQLType(){return"bigserial"}mapFromDriverValue(t){return BigInt(t)}};function RG(e,t){let{name:a,config:r}=$t(e,t);return r.mode==="number"?new dO(a):new mO(a)}var hO=class extends de{static[E]="PgBooleanBuilder";constructor(t){super(t,"boolean","PgBoolean")}build(t){return new gO(t,this.config)}},gO=class extends ne{static[E]="PgBoolean";getSQLType(){return"boolean"}};function Kx(e){return new hO(e??"")}var vO=class extends de{static[E]="PgCharBuilder";constructor(t,a){super(t,"string","PgChar"),this.config.length=a.length,this.config.enumValues=a.enum}build(t){return new yO(t,this.config)}},yO=class extends ne{static[E]="PgChar";length=this.config.length;enumValues=this.config.enumValues;getSQLType(){return this.length===void 0?"char":`char(${this.length})`}};function AG(e,t={}){let{name:a,config:r}=$t(e,t);return new vO(a,r)}var bO=class extends de{static[E]="PgCidrBuilder";constructor(t){super(t,"string","PgCidr")}build(t){return new xO(t,this.config)}},xO=class extends ne{static[E]="PgCidr";getSQLType(){return"cidr"}};function $G(e){return new bO(e??"")}var SO=class extends de{static[E]="PgCustomColumnBuilder";constructor(t,a,r){super(t,"custom","PgCustomColumn"),this.config.fieldConfig=a,this.config.customTypeParams=r}build(t){return new wO(t,this.config)}},wO=class extends ne{static[E]="PgCustomColumn";sqlName;mapTo;mapFrom;constructor(t,a){super(t,a),this.sqlName=a.customTypeParams.dataType(a.fieldConfig),this.mapTo=a.customTypeParams.toDriver,this.mapFrom=a.customTypeParams.fromDriver}getSQLType(){return this.sqlName}mapFromDriverValue(t){return typeof this.mapFrom=="function"?this.mapFrom(t):t}mapToDriverValue(t){return typeof this.mapTo=="function"?this.mapTo(t):t}};function PG(e){return(t,a)=>{let{name:r,config:n}=$t(t,a);return new SO(r,n,e)}}var ru=class extends de{static[E]="PgDateColumnBaseBuilder";defaultNow(){return this.default(nu`now()`)}};var CO=class extends ru{static[E]="PgDateBuilder";constructor(t){super(t,"date","PgDate")}build(t){return new kO(t,this.config)}},kO=class extends ne{static[E]="PgDate";getSQLType(){return"date"}mapFromDriverValue(t){return typeof t=="string"?new Date(t):t}mapToDriverValue(t){return t.toISOString()}},IO=class extends ru{static[E]="PgDateStringBuilder";constructor(t){super(t,"string","PgDateString")}build(t){return new LO(t,this.config)}},LO=class extends ne{static[E]="PgDateString";getSQLType(){return"date"}mapFromDriverValue(t){return typeof t=="string"?t:t.toISOString().slice(0,-14)}};function DG(e,t){let{name:a,config:r}=$t(e,t);return r?.mode==="date"?new CO(a):new IO(a)}var TO=class extends de{static[E]="PgDoublePrecisionBuilder";constructor(t){super(t,"number","PgDoublePrecision")}build(t){return new _O(t,this.config)}},_O=class extends ne{static[E]="PgDoublePrecision";getSQLType(){return"double precision"}mapFromDriverValue(t){return typeof t=="string"?Number.parseFloat(t):t}};function EG(e){return new TO(e??"")}var NO=class extends de{static[E]="PgInetBuilder";constructor(t){super(t,"string","PgInet")}build(t){return new RO(t,this.config)}},RO=class extends ne{static[E]="PgInet";getSQLType(){return"inet"}};function MG(e){return new NO(e??"")}var AO=class extends vc{static[E]="PgIntegerBuilder";constructor(t){super(t,"number","PgInteger")}build(t){return new $O(t,this.config)}},$O=class extends ne{static[E]="PgInteger";getSQLType(){return"integer"}mapFromDriverValue(t){return typeof t=="string"?Number.parseInt(t):t}};function Eg(e){return new AO(e??"")}var PO=class extends de{static[E]="PgIntervalBuilder";constructor(t,a){super(t,"string","PgInterval"),this.config.intervalConfig=a}build(t){return new DO(t,this.config)}},DO=class extends ne{static[E]="PgInterval";fields=this.config.intervalConfig.fields;precision=this.config.intervalConfig.precision;getSQLType(){let t=this.fields?` ${this.fields}`:"",a=this.precision?`(${this.precision})`:"";return`interval${t}${a}`}};function OG(e,t={}){let{name:a,config:r}=$t(e,t);return new PO(a,r)}var EO=class extends de{static[E]="PgJsonBuilder";constructor(t){super(t,"json","PgJson")}build(t){return new MO(t,this.config)}},MO=class extends ne{static[E]="PgJson";constructor(t,a){super(t,a)}getSQLType(){return"json"}mapToDriverValue(t){return JSON.stringify(t)}mapFromDriverValue(t){if(typeof t=="string")try{return JSON.parse(t)}catch{return t}return t}};function zG(e){return new EO(e??"")}var OO=class extends de{static[E]="PgJsonbBuilder";constructor(t){super(t,"json","PgJsonb")}build(t){return new zO(t,this.config)}},zO=class extends ne{static[E]="PgJsonb";constructor(t,a){super(t,a)}getSQLType(){return"jsonb"}mapToDriverValue(t){return JSON.stringify(t)}mapFromDriverValue(t){if(typeof t=="string")try{return JSON.parse(t)}catch{return t}return t}};function $o(e){return new OO(e??"")}var UO=class extends de{static[E]="PgLineBuilder";constructor(t){super(t,"array","PgLine")}build(t){return new jO(t,this.config)}},jO=class extends ne{static[E]="PgLine";getSQLType(){return"line"}mapFromDriverValue(t){let[a,r,n]=t.slice(1,-1).split(",");return[Number.parseFloat(a),Number.parseFloat(r),Number.parseFloat(n)]}mapToDriverValue(t){return`{${t[0]},${t[1]},${t[2]}}`}},BO=class extends de{static[E]="PgLineABCBuilder";constructor(t){super(t,"json","PgLineABC")}build(t){return new FO(t,this.config)}},FO=class extends ne{static[E]="PgLineABC";getSQLType(){return"line"}mapFromDriverValue(t){let[a,r,n]=t.slice(1,-1).split(",");return{a:Number.parseFloat(a),b:Number.parseFloat(r),c:Number.parseFloat(n)}}mapToDriverValue(t){return`{${t.a},${t.b},${t.c}}`}};function UG(e,t){let{name:a,config:r}=$t(e,t);return!r?.mode||r.mode==="tuple"?new UO(a):new BO(a)}var HO=class extends de{static[E]="PgMacaddrBuilder";constructor(t){super(t,"string","PgMacaddr")}build(t){return new VO(t,this.config)}},VO=class extends ne{static[E]="PgMacaddr";getSQLType(){return"macaddr"}};function jG(e){return new HO(e??"")}var qO=class extends de{static[E]="PgMacaddr8Builder";constructor(t){super(t,"string","PgMacaddr8")}build(t){return new ZO(t,this.config)}},ZO=class extends ne{static[E]="PgMacaddr8";getSQLType(){return"macaddr8"}};function BG(e){return new qO(e??"")}var GO=class extends de{static[E]="PgNumericBuilder";constructor(t,a,r){super(t,"string","PgNumeric"),this.config.precision=a,this.config.scale=r}build(t){return new KO(t,this.config)}},KO=class extends ne{static[E]="PgNumeric";precision;scale;constructor(t,a){super(t,a),this.precision=a.precision,this.scale=a.scale}mapFromDriverValue(t){return typeof t=="string"?t:String(t)}getSQLType(){return this.precision!==void 0&&this.scale!==void 0?`numeric(${this.precision}, ${this.scale})`:this.precision===void 0?"numeric":`numeric(${this.precision})`}},WO=class extends de{static[E]="PgNumericNumberBuilder";constructor(t,a,r){super(t,"number","PgNumericNumber"),this.config.precision=a,this.config.scale=r}build(t){return new JO(t,this.config)}},JO=class extends ne{static[E]="PgNumericNumber";precision;scale;constructor(t,a){super(t,a),this.precision=a.precision,this.scale=a.scale}mapFromDriverValue(t){return typeof t=="number"?t:Number(t)}mapToDriverValue=String;getSQLType(){return this.precision!==void 0&&this.scale!==void 0?`numeric(${this.precision}, ${this.scale})`:this.precision===void 0?"numeric":`numeric(${this.precision})`}},QO=class extends de{static[E]="PgNumericBigIntBuilder";constructor(t,a,r){super(t,"bigint","PgNumericBigInt"),this.config.precision=a,this.config.scale=r}build(t){return new XO(t,this.config)}},XO=class extends ne{static[E]="PgNumericBigInt";precision;scale;constructor(t,a){super(t,a),this.precision=a.precision,this.scale=a.scale}mapFromDriverValue=BigInt;mapToDriverValue=String;getSQLType(){return this.precision!==void 0&&this.scale!==void 0?`numeric(${this.precision}, ${this.scale})`:this.precision===void 0?"numeric":`numeric(${this.precision})`}};function FG(e,t){let{name:a,config:r}=$t(e,t),n=r?.mode;return n==="number"?new WO(a,r?.precision,r?.scale):n==="bigint"?new QO(a,r?.precision,r?.scale):new GO(a,r?.precision,r?.scale)}var YO=class extends de{static[E]="PgPointTupleBuilder";constructor(t){super(t,"array","PgPointTuple")}build(t){return new ez(t,this.config)}},ez=class extends ne{static[E]="PgPointTuple";getSQLType(){return"point"}mapFromDriverValue(t){if(typeof t=="string"){let[a,r]=t.slice(1,-1).split(",");return[Number.parseFloat(a),Number.parseFloat(r)]}return[t.x,t.y]}mapToDriverValue(t){return`(${t[0]},${t[1]})`}},tz=class extends de{static[E]="PgPointObjectBuilder";constructor(t){super(t,"json","PgPointObject")}build(t){return new az(t,this.config)}},az=class extends ne{static[E]="PgPointObject";getSQLType(){return"point"}mapFromDriverValue(t){if(typeof t=="string"){let[a,r]=t.slice(1,-1).split(",");return{x:Number.parseFloat(a),y:Number.parseFloat(r)}}return t}mapToDriverValue(t){return`(${t.x},${t.y})`}};function HG(e,t){let{name:a,config:r}=$t(e,t);return!r?.mode||r.mode==="tuple"?new YO(a):new tz(a)}function hbe(e){let t=[];for(let a=0;a<e.length;a+=2)t.push(Number.parseInt(e.slice(a,a+2),16));return new Uint8Array(t)}function VG(e,t){let a=new ArrayBuffer(8),r=new DataView(a);for(let n=0;n<8;n++)r.setUint8(n,e[t+n]);return r.getFloat64(0,!0)}function nz(e){let t=hbe(e),a=0,r=t[a];a+=1;let n=new DataView(t.buffer),o=n.getUint32(a,r===1);a+=4;let i;if(o&536870912&&(i=n.getUint32(a,r===1),a+=4),(o&65535)===1){let s=VG(t,a);a+=8;let u=VG(t,a);return a+=8,[s,u]}throw new Error("Unsupported geometry type")}var rz=class extends de{static[E]="PgGeometryBuilder";constructor(t){super(t,"array","PgGeometry")}build(t){return new oz(t,this.config)}},oz=class extends ne{static[E]="PgGeometry";getSQLType(){return"geometry(point)"}mapFromDriverValue(t){return nz(t)}mapToDriverValue(t){return`point(${t[0]} ${t[1]})`}},iz=class extends de{static[E]="PgGeometryObjectBuilder";constructor(t){super(t,"json","PgGeometryObject")}build(t){return new sz(t,this.config)}},sz=class extends ne{static[E]="PgGeometryObject";getSQLType(){return"geometry(point)"}mapFromDriverValue(t){let a=nz(t);return{x:a[0],y:a[1]}}mapToDriverValue(t){return`point(${t.x} ${t.y})`}};function qG(e,t){let{name:a,config:r}=$t(e,t);return!r?.mode||r.mode==="tuple"?new rz(a):new iz(a)}var lz=class extends de{static[E]="PgRealBuilder";constructor(t,a){super(t,"number","PgReal"),this.config.length=a}build(t){return new uz(t,this.config)}},uz=class extends ne{static[E]="PgReal";constructor(t,a){super(t,a)}getSQLType(){return"real"}mapFromDriverValue=t=>typeof t=="string"?Number.parseFloat(t):t};function ZG(e){return new lz(e??"")}var cz=class extends de{static[E]="PgSerialBuilder";constructor(t){super(t,"number","PgSerial"),this.config.hasDefault=!0,this.config.notNull=!0}build(t){return new dz(t,this.config)}},dz=class extends ne{static[E]="PgSerial";getSQLType(){return"serial"}};function GG(e){return new cz(e??"")}var fz=class extends vc{static[E]="PgSmallIntBuilder";constructor(t){super(t,"number","PgSmallInt")}build(t){return new mz(t,this.config)}},mz=class extends ne{static[E]="PgSmallInt";getSQLType(){return"smallint"}mapFromDriverValue=t=>typeof t=="string"?Number(t):t};function KG(e){return new fz(e??"")}var pz=class extends de{static[E]="PgSmallSerialBuilder";constructor(t){super(t,"number","PgSmallSerial"),this.config.hasDefault=!0,this.config.notNull=!0}build(t){return new hz(t,this.config)}},hz=class extends ne{static[E]="PgSmallSerial";getSQLType(){return"smallserial"}};function WG(e){return new pz(e??"")}var gz=class extends de{static[E]="PgTextBuilder";constructor(t,a){super(t,"string","PgText"),this.config.enumValues=a.enum}build(t){return new vz(t,this.config)}},vz=class extends ne{static[E]="PgText";enumValues=this.config.enumValues;getSQLType(){return"text"}};function ye(e,t={}){let{name:a,config:r}=$t(e,t);return new gz(a,r)}var yz=class extends ru{constructor(t,a,r){super(t,"string","PgTime"),this.withTimezone=a,this.precision=r,this.config.withTimezone=a,this.config.precision=r}static[E]="PgTimeBuilder";build(t){return new bz(t,this.config)}},bz=class extends ne{static[E]="PgTime";withTimezone;precision;constructor(t,a){super(t,a),this.withTimezone=a.withTimezone,this.precision=a.precision}getSQLType(){return`time${this.precision===void 0?"":`(${this.precision})`}${this.withTimezone?" with time zone":""}`}};function JG(e,t={}){let{name:a,config:r}=$t(e,t);return new yz(a,r.withTimezone??!1,r.precision)}var xz=class extends ru{static[E]="PgTimestampBuilder";constructor(t,a,r){super(t,"date","PgTimestamp"),this.config.withTimezone=a,this.config.precision=r}build(t){return new Sz(t,this.config)}},Sz=class extends ne{static[E]="PgTimestamp";withTimezone;precision;constructor(t,a){super(t,a),this.withTimezone=a.withTimezone,this.precision=a.precision}getSQLType(){return`timestamp${this.precision===void 0?"":` (${this.precision})`}${this.withTimezone?" with time zone":""}`}mapFromDriverValue(t){return typeof t=="string"?new Date(this.withTimezone?t:t+"+0000"):t}mapToDriverValue=t=>t.toISOString()},wz=class extends ru{static[E]="PgTimestampStringBuilder";constructor(t,a,r){super(t,"string","PgTimestampString"),this.config.withTimezone=a,this.config.precision=r}build(t){return new Cz(t,this.config)}},Cz=class extends ne{static[E]="PgTimestampString";withTimezone;precision;constructor(t,a){super(t,a),this.withTimezone=a.withTimezone,this.precision=a.precision}getSQLType(){return`timestamp${this.precision===void 0?"":`(${this.precision})`}${this.withTimezone?" with time zone":""}`}mapFromDriverValue(t){if(typeof t=="string")return t;let a=t.toISOString().slice(0,-1).replace("T"," ");if(this.withTimezone){let r=t.getTimezoneOffset(),n=r<=0?"+":"-";return`${a}${n}${Math.floor(Math.abs(r)/60).toString().padStart(2,"0")}`}return a}};function q1(e,t={}){let{name:a,config:r}=$t(e,t);return r?.mode==="string"?new wz(a,r.withTimezone??!1,r.precision):new xz(a,r?.withTimezone??!1,r?.precision)}var kz=class extends de{static[E]="PgUUIDBuilder";constructor(t){super(t,"string","PgUUID")}defaultRandom(){return this.default(nu`gen_random_uuid()`)}build(t){return new Iz(t,this.config)}},Iz=class extends ne{static[E]="PgUUID";getSQLType(){return"uuid"}};function QG(e){return new kz(e??"")}var Lz=class extends de{static[E]="PgVarcharBuilder";constructor(t,a){super(t,"string","PgVarchar"),this.config.length=a.length,this.config.enumValues=a.enum}build(t){return new Tz(t,this.config)}},Tz=class extends ne{static[E]="PgVarchar";length=this.config.length;enumValues=this.config.enumValues;getSQLType(){return this.length===void 0?"varchar":`varchar(${this.length})`}};function XG(e,t={}){let{name:a,config:r}=$t(e,t);return new Lz(a,r)}var _z=class extends de{static[E]="PgBinaryVectorBuilder";constructor(t,a){super(t,"string","PgBinaryVector"),this.config.dimensions=a.dimensions}build(t){return new Nz(t,this.config)}},Nz=class extends ne{static[E]="PgBinaryVector";dimensions=this.config.dimensions;getSQLType(){return`bit(${this.dimensions})`}};function YG(e,t){let{name:a,config:r}=$t(e,t);return new _z(a,r)}var Rz=class extends de{static[E]="PgHalfVectorBuilder";constructor(t,a){super(t,"array","PgHalfVector"),this.config.dimensions=a.dimensions}build(t){return new Az(t,this.config)}},Az=class extends ne{static[E]="PgHalfVector";dimensions=this.config.dimensions;getSQLType(){return`halfvec(${this.dimensions})`}mapToDriverValue(t){return JSON.stringify(t)}mapFromDriverValue(t){return t.slice(1,-1).split(",").map(a=>Number.parseFloat(a))}};function eK(e,t){let{name:a,config:r}=$t(e,t);return new Rz(a,r)}var $z=class extends de{static[E]="PgSparseVectorBuilder";constructor(t,a){super(t,"string","PgSparseVector"),this.config.dimensions=a.dimensions}build(t){return new Pz(t,this.config)}},Pz=class extends ne{static[E]="PgSparseVector";dimensions=this.config.dimensions;getSQLType(){return`sparsevec(${this.dimensions})`}};function tK(e,t){let{name:a,config:r}=$t(e,t);return new $z(a,r)}var Dz=class extends de{static[E]="PgVectorBuilder";constructor(t,a){super(t,"array","PgVector"),this.config.dimensions=a.dimensions}build(t){return new Ez(t,this.config)}},Ez=class extends ne{static[E]="PgVector";dimensions=this.config.dimensions;getSQLType(){return`vector(${this.dimensions})`}mapToDriverValue(t){return JSON.stringify(t)}mapFromDriverValue(t){return t.slice(1,-1).split(",").map(a=>Number.parseFloat(a))}};function aK(e,t){let{name:a,config:r}=$t(e,t);return new Dz(a,r)}function nK(){return{bigint:NG,bigserial:RG,boolean:Kx,char:AG,cidr:$G,customType:PG,date:DG,doublePrecision:EG,inet:MG,integer:Eg,interval:OG,json:zG,jsonb:$o,line:UG,macaddr:jG,macaddr8:BG,numeric:FG,point:HG,geometry:qG,real:ZG,serial:GG,smallint:KG,smallserial:WG,text:ye,time:JG,timestamp:q1,uuid:QG,varchar:XG,bit:YG,halfvec:eK,sparsevec:tK,vector:aK}}var Mz=Symbol.for("drizzle:PgInlineForeignKeys"),rK=Symbol.for("drizzle:EnableRLS"),Bm=class extends $n{static[E]="PgTable";static Symbol=Object.assign({},$n.Symbol,{InlineForeignKeys:Mz,EnableRLS:rK});[Mz]=[];[rK]=!1;[$n.Symbol.ExtraConfigBuilder]=void 0;[$n.Symbol.ExtraConfigColumns]={}};function gbe(e,t,a,r,n=e){let o=new Bm(e,r,n),i=typeof t=="function"?t(nK()):t,s=Object.fromEntries(Object.entries(i).map(([d,f])=>{let m=f;m.setName(d);let h=m.build(o);return o[Mz].push(...m.buildForeignKeys(h,o)),[d,h]})),u=Object.fromEntries(Object.entries(i).map(([d,f])=>{let m=f;m.setName(d);let h=m.buildExtraConfigColumn(o);return[d,h]})),c=Object.assign(o,s);return c[$n.Symbol.Columns]=s,c[$n.Symbol.ExtraConfigColumns]=u,a&&(c[Bm.Symbol.ExtraConfigBuilder]=a),Object.assign(c,{enableRLS:()=>(c[Bm.Symbol.EnableRLS]=!0,c)})}var Fm=(e,t,a)=>gbe(e,t,a,void 0);function oK(...e){return e[0].columns?new Z1(e[0].columns,e[0].name):new Z1(e)}var Z1=class{static[E]="PgPrimaryKeyBuilder";columns;name;constructor(t,a){this.columns=t,this.name=a}build(t){return new Oz(t,this.columns,this.name)}},Oz=class{constructor(t,a,r){this.table=t,this.columns=a,this.name=r}static[E]="PgPrimaryKey";columns;name;getName(){return this.name??`${this.table[Bm.Symbol.Name]}_${this.columns.map(t=>t.name).join("_")}_pk`}};var G1=class{constructor(t,a){this.unique=t,this.name=a}static[E]="PgIndexBuilderOn";on(...t){return new Wx(t.map(a=>{if(Wn(a,Pn))return a;a=a;let r=new $g(a.name,!!a.keyAsName,a.columnType,a.indexConfig);return a.indexConfig=JSON.parse(JSON.stringify(a.defaultConfig)),r}),this.unique,!1,this.name)}onOnly(...t){return new Wx(t.map(a=>{if(Wn(a,Pn))return a;a=a;let r=new $g(a.name,!!a.keyAsName,a.columnType,a.indexConfig);return a.indexConfig=a.defaultConfig,r}),this.unique,!0,this.name)}using(t,...a){return new Wx(a.map(r=>{if(Wn(r,Pn))return r;r=r;let n=new $g(r.name,!!r.keyAsName,r.columnType,r.indexConfig);return r.indexConfig=JSON.parse(JSON.stringify(r.defaultConfig)),n}),this.unique,!0,this.name,t)}},Wx=class{static[E]="PgIndexBuilder";config;constructor(t,a,r,n,o="btree"){this.config={name:n,columns:t,unique:a,only:r,method:o}}concurrently(){return this.config.concurrently=!0,this}with(t){return this.config.with=t,this}where(t){return this.config.where=t,this}build(t){return new zz(this.config,t)}},zz=class{static[E]="PgIndex";config;constructor(t,a){this.config={...t,table:a}}};function Po(e){return new G1(!1,e)}function Jx(e){return new G1(!0,e)}var Tr=e=>q1(e,{withTimezone:!0}),iK=l.enum(["channel","dm","group","local_conversation","thread","web_session"]),vbe=Fm("junior_destinations",{id:ye("id").primaryKey(),provider:ye("provider").notNull(),providerTenantId:ye("provider_tenant_id").notNull().default(""),providerDestinationId:ye("provider_destination_id").notNull(),kind:ye("kind").$type().notNull(),parentDestinationId:ye("parent_destination_id"),displayName:ye("display_name"),visibility:ye("visibility").$type().notNull().default("unknown"),metadata:$o("metadata_json"),createdAt:Tr("created_at").notNull(),updatedAt:Tr("updated_at").notNull()},e=>[Jx("junior_destinations_provider_destination_uidx").on(e.provider,e.providerTenantId,e.providerDestinationId),Po("junior_destinations_provider_kind_idx").on(e.provider,e.kind)]),ybe=Fm("junior_users",{id:ye("id").primaryKey(),primaryEmail:ye("primary_email").notNull(),primaryEmailNormalized:ye("primary_email_normalized").notNull(),displayName:ye("display_name"),timezone:ye("timezone"),isAdmin:Kx("is_admin").notNull().default(!1),createdAt:Tr("created_at").notNull(),updatedAt:Tr("updated_at").notNull()},e=>[Jx("junior_users_primary_email_normalized_uidx").on(e.primaryEmailNormalized)]),Uz=Fm("junior_identities",{id:ye("id").primaryKey(),kind:ye("kind").$type().notNull(),provider:ye("provider").notNull(),providerTenantId:ye("provider_tenant_id").notNull().default(""),providerSubjectId:ye("provider_subject_id").notNull(),displayName:ye("display_name"),handle:ye("handle"),email:ye("email"),avatarUrl:ye("avatar_url"),metadata:$o("metadata_json"),createdAt:Tr("created_at").notNull(),updatedAt:Tr("updated_at").notNull(),userId:ye("user_id").references(()=>ybe.id),emailNormalized:ye("email_normalized"),emailVerified:Kx("email_verified").notNull().default(!1)},e=>[Jx("junior_identities_provider_subject_uidx").on(e.provider,e.providerTenantId,e.providerSubjectId),Po("junior_identities_user_idx").on(e.userId),Po("junior_identities_verified_email_idx").on(e.emailNormalized).where(nu`${e.emailVerified} = true AND ${e.emailNormalized} IS NOT NULL`),Po("junior_identities_kind_provider_idx").on(e.kind,e.provider)]),Hm=Fm("junior_conversations",{conversationId:ye("conversation_id").primaryKey(),schemaVersion:Eg("schema_version").notNull().default(1),source:ye("source").$type(),sessionSource:$o("source_json").$type(),location:$o("location_json").$type(),destinationId:ye("destination_id").references(()=>vbe.id),destination:$o("destination_json").$type(),actorIdentityId:ye("actor_identity_id").references(()=>Uz.id),creatorIdentityId:ye("creator_identity_id").references(()=>Uz.id),credentialSubjectIdentityId:ye("credential_subject_identity_id").references(()=>Uz.id),actor:$o("actor_json").$type(),channelName:ye("channel_name"),title:ye("title"),createdAt:Tr("created_at").notNull(),lastActivityAt:Tr("last_activity_at").notNull(),updatedAt:Tr("updated_at").notNull(),executionUpdatedAt:Tr("execution_updated_at"),executionStatus:ye("execution_status").$type().notNull(),runId:ye("run_id"),lastCheckpointAt:Tr("last_checkpoint_at"),lastEnqueuedAt:Tr("last_enqueued_at"),parentConversationId:ye("parent_conversation_id").references(()=>Hm.conversationId),forkedFromConversationId:ye("forked_from_conversation_id").references(()=>Hm.conversationId,{onDelete:"set null"}),rootConversationId:ye("root_conversation_id").references(()=>Hm.conversationId),transcriptPurgedAt:Tr("transcript_purged_at"),stoppedAt:Tr("stopped_at"),durationMs:Eg("duration_ms").notNull().default(0),usage:$o("usage_json").$type(),executionDurationMs:Eg("execution_duration_ms").notNull().default(0),executionUsage:$o("execution_usage_json").$type(),metricRunId:ye("metric_run_id"),legacyArchivedAt:Tr("archived_at")},e=>[Po("junior_conversations_last_activity_idx").on(e.lastActivityAt.desc(),e.conversationId),Po("junior_conversations_active_idx").using("btree",nu`coalesce(${e.executionUpdatedAt}, ${e.updatedAt})`,e.conversationId).where(nu`${e.executionStatus} <> 'idle'`),Po("junior_conversations_destination_activity_idx").on(e.destinationId,e.lastActivityAt.desc()),Po("junior_conversations_actor_activity_idx").on(e.actorIdentityId,e.lastActivityAt.desc()),Po("junior_conversations_parent_idx").on(e.parentConversationId),Po("junior_conversations_forked_from_idx").on(e.forkedFromConversationId),Po("junior_conversations_root_idx").on(e.rootConversationId)]);var sK=["pending","running","paused","blocked","completed","failed","stopped"];var DFe=Fm("junior_agent_bindings",{parentConversationId:ye("parent_conversation_id").notNull().references(()=>Hm.conversationId),name:ye("name").notNull(),childConversationId:ye("child_conversation_id").notNull().references(()=>Hm.conversationId)},e=>[oK({columns:[e.parentConversationId,e.name]}),Jx("junior_agent_bindings_child_idx").on(e.childConversationId)]),EFe=Fm("junior_agent_invocations",{invocationId:ye("invocation_id").primaryKey(),parentConversationId:ye("parent_conversation_id").notNull().references(()=>Hm.conversationId),childConversationId:ye("child_conversation_id").notNull().references(()=>Hm.conversationId),agentName:ye("agent_name"),input:ye("input").notNull(),title:ye("title"),actor:$o("actor_json").$type().notNull(),credentialContext:$o("credential_context_json").$type(),source:$o("source_json").$type().notNull(),destination:$o("destination_json").$type().notNull(),destinationVisibility:ye("destination_visibility").$type(),modelProfile:ye("model_profile").$type(),reasoningLevel:ye("reasoning_level").$type(),parentToolCallId:ye("parent_tool_call_id"),status:ye("status").$type().notNull(),mailboxStatus:ye("mailbox_status").$type().notNull(),parentMailboxStatus:ye("parent_mailbox_status").$type(),result:ye("result"),errorMessage:ye("error_message"),createdAt:Tr("created_at").notNull(),updatedAt:Tr("updated_at").notNull(),terminalAt:Tr("terminal_at")},e=>[Po("junior_agent_invocations_child_idx").on(e.childConversationId),Po("junior_agent_invocations_mailbox_idx").on(e.mailboxStatus,e.createdAt),Po("junior_agent_invocations_parent_mailbox_idx").on(e.parentMailboxStatus,e.terminalAt)]);var bbe=l.object({error:l.string().min(1)}).strict(),xbe=l.object({inboundMessageId:l.string().min(1),text:l.string().min(1)}).strict(),Fz=l.object({conversationId:l.string().min(1),status:l.enum(["no_work","requested"]),stoppedInboundMessageIds:l.array(l.string().min(1)),stoppedMessages:l.array(xbe)}).strict(),uK=l.object({auxiliaryCosts:E1.optional(),childAgentTotals:D1.optional(),conversationId:l.string().min(1),cumulativeDurationMs:l.number(),cumulativeUsage:Bx.optional(),error:l.string().min(1).optional(),name:l.string().min(1).optional(),redacted:l.literal(!0).optional(),status:l.enum(sK),task:l.string().optional(),title:l.string().min(1).optional(),updatedAt:l.string().datetime()}).strict().superRefine((e,t)=>{e.task===void 0==(e.redacted!==!0)&&t.addIssue({code:"custom",message:"child agent task must be text or explicitly redacted"}),e.redacted&&(e.name||e.title||e.error)&&t.addIssue({code:"custom",message:"redacted child agents must not expose a name, title, or error"})}),Hz=l.object({agents:l.array(uK),conversationId:l.string().min(1)}).strict(),Q1=l.object({closed:l.number().int().nonnegative(),costUsd:l.number().nonnegative().optional(),created:l.number().int().nonnegative(),medianCostUsd:l.number().nonnegative().optional(),medianMergeTimeMs:l.number().nonnegative().optional(),merged:l.number().int().nonnegative(),mergeRate:l.number().min(0).max(1).optional(),open:l.number().int().nonnegative()}).strict(),Sbe=l.string().regex(/^\d{4}-\d{2}-\d{2}(T\d{2})?$/),ou=l.object({closed:l.number().int().nonnegative(),created:l.number().int().nonnegative(),date:Sbe,merged:l.number().int().nonnegative()}).strict(),cK=l.object({closed:l.number().int().nonnegative(),created:l.number().int().nonnegative(),id:l.string().uuid(),medianCostUsd:l.number().nonnegative().optional(),merged:l.number().int().nonnegative(),mergeRate:l.number().min(0).max(1).optional(),name:l.string().min(1),open:l.number().int().nonnegative(),provider:l.string().min(1),url:l.string().url().optional()}).strict(),Vz=l.object({closedAt:l.string().optional(),id:l.string().uuid(),mergedAt:l.string().optional(),number:l.number().int().positive(),openedAt:l.string(),provider:l.string().min(1),repository:l.string().min(1),state:Ox,title:l.string().optional(),url:l.string().url().optional()}).strict(),qz=l.object({activityDays:l.array(ou),activityHours:l.array(ou).optional(),activitySixHours:l.array(ou).optional(),changes:l.array(Vz),generatedAt:l.string(),repositories:l.array(cK),summary:Q1,windowEnd:l.string(),windowStart:l.string()}).strict(),wbe=l.object({repositoryId:l.string().uuid()}).strict(),Zz=l.object({activityDays:l.array(ou),activityHours:l.array(ou).optional(),activitySixHours:l.array(ou).optional(),changes:l.array(Vz),generatedAt:l.string(),repository:l.object({id:l.string().uuid(),name:l.string().min(1),provider:l.string().min(1),url:l.string().url().optional()}).strict(),summary:Q1,windowEnd:l.string(),windowStart:l.string(),workspaces:l.array(l.object({id:l.string().min(1),name:l.string().min(1)}).strict())}).strict(),Gz=l.object({activityDays:l.array(ou),activityHours:l.array(ou).optional(),activitySixHours:l.array(ou).optional(),generatedAt:l.string(),summary:Q1,windowEnd:l.string(),windowStart:l.string()}).strict(),dK=l.object({provider:l.string(),displayName:l.string(),description:l.string(),account:l.object({label:l.string(),url:l.string().optional()}).strict().optional(),connected:l.boolean()}).strict(),Kz=l.object({connections:l.array(dK)}).strict(),Cbe=l.object({provider:l.string().regex(/^[a-z][a-z0-9-]*$/).max(64)}).strict(),Wz=l.object({authorizationUrl:l.string().url()}).strict(),Jz=l.object({disconnected:l.literal(!0)}).strict(),W1=l.object({active:l.number(),conversations:l.number(),date:l.string(),durationMs:l.number(),failed:l.number(),tokens:l.number().optional()}).strict();var kbe=l.object({locationId:l.string().min(1)}).strict(),fK=Um.extend({id:l.string(),firstSeenAt:l.string(),kind:iK,lastSeenAt:l.string(),provider:l.string(),providerDestinationId:l.string(),visibility:l.literal("public")}).strict(),Ibe=Um.extend({actor:zm}).strict(),Lbe=l.string().regex(/^\d{4}-\d{2}-\d{2}(T\d{2})?$/),J1=l.object({date:Lbe,privateConversations:l.number(),publicConversations:l.number()}).strict(),Qz=l.object({activityDays:l.array(J1),activityHours:l.array(J1).optional(),activitySixHours:l.array(J1).optional(),generatedAt:l.string(),locations:l.array(fK),privateActivity:Um,source:l.literal("conversation_index"),windowEnd:l.string(),windowStart:l.string()}).strict(),Xz=fK.extend({activityDays:l.array(W1),activityHours:l.array(W1).optional(),activitySixHours:l.array(W1).optional(),actors:l.array(Ibe),generatedAt:l.string(),recentConversations:l.array(Ag),source:l.literal("conversation_index"),windowEnd:l.string(),windowStart:l.string()}).strict(),Tbe=l.object({email:l.string().trim().min(1)}).strict(),lK=Um.omit({costUsd:!0}),mK=l.string().regex(/^\d{4}-\d{2}-\d{2}(T\d{2})?$/),jz=l.object({active:l.number(),conversations:l.number(),costUsd:l.number().optional(),date:mK,durationMs:l.number(),failed:l.number(),tokens:l.number().optional()}).strict(),Bz=l.object({activePeople:l.number(),conversations:l.number(),date:mK}).strict(),pK=l.object({active:l.number(),activeDays:l.number(),conversations:l.number(),durationMs:l.number(),failed:l.number(),tokens:l.number().optional()}).strict(),K1=l.object({conversations:l.number().int().nonnegative(),costUsd:l.number().finite().nonnegative(),durationMs:l.number().finite().nonnegative(),priorCostUsd:l.number().finite().nonnegative()}).strict(),_be=l.object({1:K1,7:K1,30:K1,90:K1}).strict(),hK=zm.extend({email:l.string().min(1)}).strict(),Nbe=pK.extend({firstSeenAt:l.string(),lastSeenAt:l.string(),actor:hK,windows:_be}).strict(),Yz=l.object({activityDays:l.array(Bz),activityHours:l.array(Bz).optional(),activitySixHours:l.array(Bz).optional(),generatedAt:l.string(),people:l.array(Nbe),source:l.literal("conversation_index"),windowEnd:l.string(),windowStart:l.string()}).strict(),e4=l.object({activityDays:l.array(jz),activityHours:l.array(jz).optional(),activitySixHours:l.array(jz).optional(),generatedAt:l.string(),locations:l.array(lK),recentConversations:l.array(Ag),actor:hK,source:l.literal("conversation_index"),surfaces:l.array(lK),totals:pK,windowEnd:l.string(),windowStart:l.string()}).strict(),t4=l.object({generatedAt:l.string(),sevenDaysUsd:l.number().finite().nonnegative(),source:l.literal("conversation_index"),thirtyDaysUsd:l.number().finite().nonnegative(),windowEnd:l.string(),windowStart:l.string()}).strict(),a4=l.object({id:l.string().uuid(),name:l.string(),tokenSuffix:l.string(),createdAt:l.string().datetime(),expiresAt:l.string().datetime(),lastUsedAt:l.string().datetime().nullable()}).strict(),n4=l.object({tokens:l.array(a4)}).strict(),Rbe=l.object({name:l.string().trim().min(1).max(80)}).strict(),r4=a4.extend({token:l.string().startsWith("jr_pat_")}).strict(),Abe=l.object({id:l.string().uuid()}).strict(),$be=l.object({revoked:l.literal(!0)}).strict(),Pbe=l.object({provider:l.string(),repo:l.string()}).strict(),gK=l.object({provider:l.string(),repo:l.string(),checkoutPath:l.string()}).strict(),Dbe=l.object({id:l.string(),generatedAt:l.iso.datetime(),buildDurationMs:l.number().int().nonnegative(),sizeBytes:l.number().int().nonnegative().nullable()}).strict(),vK=l.object({id:l.string(),generatedAt:l.iso.datetime(),buildDurationMs:l.number().int().nonnegative(),dependencyCount:l.number().int().nonnegative()}).strict(),Mg=l.object({id:l.string().uuid(),name:l.string(),setupScript:l.string(),repos:l.array(gK),snapshot:Dbe.nullable()}).strict(),o4=l.object({baselineSnapshot:vK.nullable(),workspaces:l.array(Mg)}).strict(),Ebe=l.object({name:l.string(),setupScript:l.string().optional(),repos:l.array(Pbe)}).strict(),Mbe=l.object({id:l.string().uuid()}).strict(),Obe=l.object({deleted:l.literal(!0)}).strict(),yK=l.object({count:l.number().int().nonnegative(),date:l.string(),metric:l.string().min(1),name:l.string().min(1),namespace:l.string().min(1)}).strict(),i4=l.object({generatedAt:l.string().datetime(),stats:l.array(yK),windowEnd:l.string(),windowStart:l.string()}).strict();var Do=l.string().trim().min(1).max(160),Og=l.number().int().nonnegative(),zbe=l.discriminatedUnion("type",[l.strictObject({type:l.literal("code_change"),author:Do.optional(),sourceBranch:Do.optional(),targetBranch:Do.optional(),reviewers:l.array(Do).max(5).optional(),review:l.enum(["required","approved","changes_requested"]).optional(),checks:l.strictObject({passed:Og,failed:Og,pending:Og}).optional(),mergeable:l.boolean().optional(),changedFiles:Og.optional(),additions:Og.optional(),deletions:Og.optional()}),l.strictObject({type:l.literal("task"),assignees:l.array(Do).max(5).optional(),priority:Do.optional(),project:Do.optional(),cycle:Do.optional(),dueDate:l.iso.date().optional(),labels:l.array(Do).max(5).optional()}),l.strictObject({type:l.literal("deployment"),project:Do.optional(),environment:Do.optional(),revision:Do.optional(),branch:Do.optional()}),l.strictObject({type:l.literal("calendar_event"),when:Do.optional(),attendees:l.array(Do).max(5).optional()})]);function xK(e){if(!e)return[];let t=[],a=n=>n?.length?`${n.join(", ")}${n.length===5?" (up to 5 shown)":""}`:void 0;function r(n,o,i){i!==void 0&&i!==""&&t.push({key:n,label:o,value:String(i)})}switch(e.type){case"code_change":r("sourceBranch","Branch",e.sourceBranch);break;case"task":r("assignees","Assignees",e.assignees?.length===0?"Unassigned":a(e.assignees)),r("priority","Priority",e.priority),r("project","Project",e.project),r("cycle","Cycle",e.cycle),r("dueDate","Due",e.dueDate),r("labels","Labels",a(e.labels));break;case"deployment":r("environment","Environment",e.environment),r("project","Project",e.project),r("revision","Revision",e.revision),r("branch","Branch",e.branch);break;case"calendar_event":r("when","When",e.when),r("attendees","Attendees",a(e.attendees));break}return t.slice(0,4)}var Y1=l.enum(["task","code_change","automation","deployment","calendar_event","item"]),Ube={task:"Ticket",code_change:"Code change",automation:"Automation",deployment:"Deployment",calendar_event:"Calendar event",item:"Item"};function Rs(e){let t=e.objectType==="item"&&e.facts?.type==="deployment"?"deployment":e.objectType,a=e.status?.toLowerCase(),r={task:"issue-opened",code_change:"git-pull-request",automation:"workflow",deployment:"rocket",calendar_event:"calendar",item:"package"}[t],n=t==="automation"?"info":"neutral";return t==="code_change"?(a==="draft"&&(r="git-pull-request-draft"),a==="closed"&&(r="git-pull-request-closed",n="danger"),a==="merged"&&(r="git-merge",n="accent"),a==="open"&&(n="success")):t==="task"?(a==="closed"&&(r="issue-closed",n="accent"),a==="open"&&(n="success")):t==="deployment"&&((a==="ready"||a==="succeeded")&&(n="success"),(a==="error"||a==="failed")&&(n="danger"),(a==="building"||a==="in_progress")&&(n="info")),(a==="warning"||a==="blocked")&&(n="warning"),{icon:r,tone:n,label:Ube[t]}}function SK(e){return`/_junior/dashboard/object-icons/v1/${e}.png`}var l4=l.object({kind:l.literal("object"),key:l.string().trim().min(1).max(256),label:l.string().trim().min(1).max(256),objectType:Y1,title:l.string().trim().min(1).max(512),url:l.url().max(2048).refine(e=>["http:","https:"].includes(new URL(e).protocol)).nullable(),description:l.string().max(4e3).optional(),status:l.string().trim().min(1).max(100).optional(),trigger:l.string().max(4e3).optional(),warning:l.string().max(1e3).optional(),displayType:l.string().trim().min(1).max(80).optional(),sourceUpdatedAt:l.iso.datetime({offset:!0}).optional(),facts:zbe.refine(e=>new TextEncoder().encode(JSON.stringify(e)).length<=4096,"Object facts must not exceed 4 KiB").optional()}).strict().refine(e=>!e.facts||(e.facts.type==="deployment"?e.objectType==="deployment"||e.objectType==="item":e.facts.type===e.objectType),"Object facts must match the object type"),aHe=l4.safeExtend({plugin:l.string().min(1)}),wK={"issue-opened":["M8 9.5a1.5 1.5 0 1 0 0-3 1.5 1.5 0 0 0 0 3Z","M8 0a8 8 0 1 1 0 16A8 8 0 0 1 8 0ZM1.5 8a6.5 6.5 0 1 0 13 0 6.5 6.5 0 0 0-13 0Z"],"issue-closed":["M11.28 6.78a.75.75 0 0 0-1.06-1.06L7.25 8.69 5.78 7.22a.75.75 0 0 0-1.06 1.06l2 2a.75.75 0 0 0 1.06 0l3.5-3.5Z","M16 8A8 8 0 1 1 0 8a8 8 0 0 1 16 0Zm-1.5 0a6.5 6.5 0 1 0-13 0 6.5 6.5 0 0 0 13 0Z"],"git-pull-request":["M1.5 3.25a2.25 2.25 0 1 1 3 2.122v5.256a2.251 2.251 0 1 1-1.5 0V5.372A2.25 2.25 0 0 1 1.5 3.25Zm5.677-.177L9.573.677A.25.25 0 0 1 10 .854V2.5h1A2.5 2.5 0 0 1 13.5 5v5.628a2.251 2.251 0 1 1-1.5 0V5a1 1 0 0 0-1-1h-1v1.646a.25.25 0 0 1-.427.177L7.177 3.427a.25.25 0 0 1 0-.354ZM3.75 2.5a.75.75 0 1 0 0 1.5.75.75 0 0 0 0-1.5Zm0 9.5a.75.75 0 1 0 0 1.5.75.75 0 0 0 0-1.5Zm8.25.75a.75.75 0 1 0 1.5 0 .75.75 0 0 0-1.5 0Z"],"git-pull-request-draft":["M3.25 1A2.25 2.25 0 0 1 4 5.372v5.256a2.251 2.251 0 1 1-1.5 0V5.372A2.251 2.251 0 0 1 3.25 1Zm9.5 14a2.25 2.25 0 1 1 0-4.5 2.25 2.25 0 0 1 0 4.5ZM2.5 3.25a.75.75 0 1 0 1.5 0 .75.75 0 0 0-1.5 0ZM3.25 12a.75.75 0 1 0 0 1.5.75.75 0 0 0 0-1.5Zm9.5 0a.75.75 0 1 0 0 1.5.75.75 0 0 0 0-1.5ZM14 7.5a1.25 1.25 0 1 1-2.5 0 1.25 1.25 0 0 1 2.5 0Zm0-4.25a1.25 1.25 0 1 1-2.5 0 1.25 1.25 0 0 1 2.5 0Z"],"git-pull-request-closed":["M3.25 1A2.25 2.25 0 0 1 4 5.372v5.256a2.251 2.251 0 1 1-1.5 0V5.372A2.251 2.251 0 0 1 3.25 1Zm9.5 5.5a.75.75 0 0 1 .75.75v3.378a2.251 2.251 0 1 1-1.5 0V7.25a.75.75 0 0 1 .75-.75Zm-2.03-5.273a.75.75 0 0 1 1.06 0l.97.97.97-.97a.748.748 0 0 1 1.265.332.75.75 0 0 1-.205.729l-.97.97.97.97a.751.751 0 0 1-.018 1.042.751.751 0 0 1-1.042.018l-.97-.97-.97.97a.749.749 0 0 1-1.275-.326.749.749 0 0 1 .215-.734l.97-.97-.97-.97a.75.75 0 0 1 0-1.06ZM2.5 3.25a.75.75 0 1 0 1.5 0 .75.75 0 0 0-1.5 0ZM3.25 12a.75.75 0 1 0 0 1.5.75.75 0 0 0 0-1.5Zm9.5 0a.75.75 0 1 0 0 1.5.75.75 0 0 0 0-1.5Z"],"git-merge":["M5.45 5.154A4.25 4.25 0 0 0 9.25 7.5h1.378a2.251 2.251 0 1 1 0 1.5H9.25A5.734 5.734 0 0 1 5 7.123v3.505a2.25 2.25 0 1 1-1.5 0V5.372a2.25 2.25 0 1 1 1.95-.218ZM4.25 13.5a.75.75 0 1 0 0-1.5.75.75 0 0 0 0 1.5Zm8.5-4.5a.75.75 0 1 0 0-1.5.75.75 0 0 0 0 1.5ZM5 3.25a.75.75 0 1 0 0 .005V3.25Z"],workflow:["M0 1.75C0 .784.784 0 1.75 0h3.5C6.216 0 7 .784 7 1.75v3.5A1.75 1.75 0 0 1 5.25 7H4v4a1 1 0 0 0 1 1h4v-1.25C9 9.784 9.784 9 10.75 9h3.5c.966 0 1.75.784 1.75 1.75v3.5A1.75 1.75 0 0 1 14.25 16h-3.5A1.75 1.75 0 0 1 9 14.25v-.75H5A2.5 2.5 0 0 1 2.5 11V7h-.75A1.75 1.75 0 0 1 0 5.25Zm1.75-.25a.25.25 0 0 0-.25.25v3.5c0 .138.112.25.25.25h3.5a.25.25 0 0 0 .25-.25v-3.5a.25.25 0 0 0-.25-.25Zm9 9a.25.25 0 0 0-.25.25v3.5c0 .138.112.25.25.25h3.5a.25.25 0 0 0 .25-.25v-3.5a.25.25 0 0 0-.25-.25Z"],rocket:["M14.064 0h.186C15.216 0 16 .784 16 1.75v.186a8.752 8.752 0 0 1-2.564 6.186l-.458.459c-.314.314-.641.616-.979.904v3.207c0 .608-.315 1.172-.833 1.49l-2.774 1.707a.749.749 0 0 1-1.11-.418l-.954-3.102a1.214 1.214 0 0 1-.145-.125L3.754 9.816a1.218 1.218 0 0 1-.124-.145L.528 8.717a.749.749 0 0 1-.418-1.11l1.71-2.774A1.748 1.748 0 0 1 3.31 4h3.204c.288-.338.59-.665.904-.979l.459-.458A8.749 8.749 0 0 1 14.064 0ZM8.938 3.623h-.002l-.458.458c-.76.76-1.437 1.598-2.02 2.5l-1.5 2.317 2.143 2.143 2.317-1.5c.902-.583 1.74-1.26 2.499-2.02l.459-.458a7.25 7.25 0 0 0 2.123-5.127V1.75a.25.25 0 0 0-.25-.25h-.186a7.249 7.249 0 0 0-5.125 2.123ZM3.56 14.56c-.732.732-2.334 1.045-3.005 1.148a.234.234 0 0 1-.201-.064.234.234 0 0 1-.064-.201c.103-.671.416-2.273 1.15-3.003a1.502 1.502 0 1 1 2.12 2.12Zm6.94-3.935c-.088.06-.177.118-.266.175l-2.35 1.521.548 1.783 1.949-1.2a.25.25 0 0 0 .119-.213ZM3.678 8.116 5.2 5.766c.058-.09.117-.178.176-.266H3.309a.25.25 0 0 0-.213.119l-1.2 1.95ZM12 5a1 1 0 1 1-2 0 1 1 0 0 1 2 0Z"],calendar:["M4.75 0a.75.75 0 0 1 .75.75V2h5V.75a.75.75 0 0 1 1.5 0V2h1.25c.966 0 1.75.784 1.75 1.75v10.5A1.75 1.75 0 0 1 13.25 16H2.75A1.75 1.75 0 0 1 1 14.25V3.75C1 2.784 1.784 2 2.75 2H4V.75A.75.75 0 0 1 4.75 0ZM2.5 7.5v6.75c0 .138.112.25.25.25h10.5a.25.25 0 0 0 .25-.25V7.5Zm10.75-4H2.75a.25.25 0 0 0-.25.25V6h11V3.75a.25.25 0 0 0-.25-.25Z"],package:["m8.878.392 5.25 3.045c.54.314.872.89.872 1.514v6.098a1.75 1.75 0 0 1-.872 1.514l-5.25 3.045a1.75 1.75 0 0 1-1.756 0l-5.25-3.045A1.75 1.75 0 0 1 1 11.049V4.951c0-.624.332-1.201.872-1.514L7.122.392a1.75 1.75 0 0 1 1.756 0ZM7.875 1.69l-4.63 2.685L8 7.133l4.755-2.758-4.63-2.685a.248.248 0 0 0-.25 0ZM2.5 5.677v5.372c0 .09.047.171.125.216l4.625 2.683V8.432Zm6.25 8.271 4.625-2.683a.25.25 0 0 0 .125-.216V5.677L8.75 8.432Z"]};function jbe(e){try{let t=new URL(e).protocol;return t==="http:"||t==="https:"}catch{return!1}}var Bbe=l.object({kind:l.literal("resource_link"),objectType:Y1.optional(),key:l.string().trim().min(1).max(256),label:l.string().trim().min(1).max(256),url:l.string().url().max(2048).refine(jbe,"URL must use HTTP or HTTPS."),description:l.string().trim().min(1).max(512).optional(),status:l.enum(["open","draft","closed","merged","warning"]).optional()}).strict(),rHe=l.discriminatedUnion("kind",[Bbe,l4]),Fbe=l.enum(["circle-dot","circle-dashed","circle-x","git-merge","git-pull-request","triangle-alert"]),oHe=l.object({icon:Fbe.optional(),objectType:Y1.optional(),status:l.string().trim().min(1).max(100).optional(),key:l.string().trim().min(1).max(256),label:l.string().trim().min(1).max(256)}).strict(),Hbe=l.enum(["closed","merged","open"]),sHe=l.object({closedAt:l.date().optional(),conversationIds:l.array(l.string().min(1)).default([]),mergedAt:l.date().optional(),number:l.number().int().positive(),openedAt:l.date(),providerId:l.string().min(1),repository:l.object({name:l.string().min(1),providerId:l.string().min(1),url:l.string().url().optional()}).strict(),state:Hbe,title:l.string().min(1).optional(),updatedAt:l.date(),url:l.string().url().optional()}).strict(),uHe=l.string().trim().min(1).max(64).regex(/^[a-z][a-z0-9_]*$/),Vbe=l.enum(["activity","brain","calendar","check","database","info","key","link","sparkles","warning"]),qbe=l.object({content:l.string().min(1).max(32*1024).optional(),description:l.string().trim().min(1).max(2e3).optional(),metadata:l.array(l.string().trim().min(1).max(120)).max(8).optional(),title:l.string().trim().min(1).max(4e3)}).strict(),cHe=l.object({details:l.array(qbe).max(100).optional(),icon:Vbe.optional(),preview:l.string().trim().min(1).max(500).optional(),title:l.string().trim().min(1).max(120)}).strict();var eI=l.string().regex(/^T[A-Z0-9]+$/),u4=l.string().regex(/^(C|G|D)[A-Z0-9]+$/),CK=l.string().regex(/^local:[a-z0-9_-]+:[a-z0-9][a-z0-9_-]*$/),Zbe=l.string().min(1).refine(e=>e===e.trim()&&e.toLowerCase()!=="unknown"),X1=Zbe,je=l.string().refine(e=>e.trim().length>0),lo=je.refine(e=>e===e.trim()),Gbe=l.object({id:je,provider:lo}).strict(),Kbe=Gbe.extend({provider:l.literal("slack"),teamId:eI,channelId:u4,threadTs:lo.optional()}).strict(),fHe=l.discriminatedUnion("provider",[Kbe]),mHe=l.enum(["slack","local"]),kK=l.enum(["public","private"]),Wbe=l.enum(["public","private"]),Jbe=l.object({platform:l.literal("slack"),teamId:eI,channelId:u4,threadTs:lo.optional()}).strict(),c4=Jbe,Qbe=l.object({platform:l.literal("local"),conversationId:CK}).strict(),Xbe=l.discriminatedUnion("platform",[c4,Qbe]),pHe=l.object({action:l.literal("send_message"),destination:c4}).strict(),Ybe=l.object({kind:l.literal("slack"),teamId:eI,channelId:u4,visibility:kK,messageTs:je.optional(),threadTs:je.optional()}).strict(),exe=l.object({kind:l.literal("local"),visibility:l.literal("private"),conversationId:CK}).strict(),txe=l.object({kind:l.literal("web"),visibility:kK,conversationId:lo}).strict(),axe=l.object({kind:l.literal("event"),eventKey:lo,eventType:lo,identifier:lo,namespace:lo}).strict(),nxe=l.object({kind:l.literal("scheduled_automation")}).strict(),rxe=l.object({kind:l.literal("event_automation")}).strict(),oxe=l.object({kind:l.literal("plugin_dispatch")}).strict(),ixe=l.object({kind:l.literal("agent_invocation")}).strict(),sxe=l.discriminatedUnion("kind",[Ybe,exe,txe,axe,nxe,rxe,oxe,ixe]);function lxe(e){if(!e||typeof e!="object"||Array.isArray(e))return e;let t=e;if("kind"in t){let o={event_task:"event_automation",resource_event:"event",scheduled_task:"scheduled_automation"},i=typeof t.kind=="string"?o[t.kind]:void 0;return i?{...t,kind:i}:e}if(t.platform!=="slack"&&t.platform!=="local"&&t.platform!=="web")return e;let{location:a,platform:r,...n}=t;return{...n,kind:r}}var uxe=l.preprocess(lxe,sxe),cxe=l.discriminatedUnion("allowedWhen",[l.object({type:l.literal("user"),userId:X1,allowedWhen:l.literal("private-direct-conversation")}).strict(),l.object({type:l.literal("user"),userId:X1,allowedWhen:l.literal("scheduled-automation"),taskId:lo}).strict()]),d4={email:je.optional(),fullName:je.optional(),userId:X1,userName:je.optional()},dxe=l.object({...d4,platform:l.literal("slack"),teamId:eI}).strict(),fxe=l.object({...d4,platform:l.literal("local")}).strict(),mxe=l.object({...d4,platform:l.literal("web")}).strict(),pxe=l.object({platform:l.literal("system"),name:X1}).strict(),s4=l.discriminatedUnion("platform",[dxe,fxe,mxe,pxe]),hxe=l.object({displayName:je.optional(),handle:je.optional(),id:lo,provider:lo,providerSubjectId:lo,providerTenantId:lo.optional()}).strict(),hHe=l.object({displayName:je.optional(),email:je.max(320),id:lo,identities:l.array(hxe).max(100),isAdmin:l.literal(!0).optional()}).strict(),gxe=l.record(l.string(),l.string()).superRefine((e,t)=>{let a=Object.entries(e);if(a.length>20){t.addIssue({code:l.ZodIssueCode.custom,message:"Dispatch metadata has too many keys"});return}for(let[r,n]of a){if(!r.trim()){t.addIssue({code:l.ZodIssueCode.custom,message:"Dispatch metadata values must be strings",path:[r]});continue}r.length>128&&t.addIssue({code:l.ZodIssueCode.custom,message:"Dispatch metadata key exceeds the maximum length",path:[r]}),/[\r\n]/.test(r)&&t.addIssue({code:l.ZodIssueCode.custom,message:"Dispatch metadata keys must be single-line strings",path:[r]}),/[\r\n]/.test(n)&&t.addIssue({code:l.ZodIssueCode.custom,message:"Dispatch metadata values must be single-line strings",path:[r]}),n.length>512&&t.addIssue({code:l.ZodIssueCode.custom,message:"Dispatch metadata value exceeds the maximum length",path:[r]})}}),vxe=l.object({label:lo.pipe(l.string().max(48)).refine(e=>!/[\r\n]/.test(e)),detail:lo.pipe(l.string().max(128)).refine(e=>!/[\r\n]/.test(e)).optional()}).strict(),gHe=l.object({idempotencyKey:je.pipe(l.string().max(512)),credentialSubject:cxe.optional(),destination:c4,destinationVisibility:Wbe,input:je.pipe(l.string().max(32e3)),metadata:gxe.optional(),replyAttribution:vxe.optional()}).strict();var yxe=l.string().trim().min(1).max(64).regex(/^[a-z][a-z0-9_-]*$/),yHe=l.object({text:l.string().trim().min(1).max(8e3)}).strict(),bHe=l.object({kind:yxe,version:l.number().int().positive(),content:l.record(l.string(),l.unknown())}).strict();var bxe=4e3,xxe=8e3,zg=32,bK=4e3,Sxe=1e3,wxe=l.record(l.string(),l.unknown()).superRefine((e,t)=>{Object.keys(e).length>zg&&t.addIssue({code:"custom",message:`Event data may include at most ${zg} keys.`}),new TextEncoder().encode(JSON.stringify(e)).byteLength>bK&&t.addIssue({code:"custom",message:`Event data may be at most ${bK} JSON bytes.`})}),Vm=l.string().regex(/^[a-z][a-z0-9_-]*(?:\.[a-z][a-z0-9_-]*)+$/).describe("Canonical dotted event type, such as issue.closed or pull_request.review.changes_requested."),IK=l.string().regex(/^[a-z][a-z0-9_]*$/).describe("Canonical plugin-defined resource type, such as issue or pull_request."),LK=/^[a-z][a-zA-Z0-9]*$/,Cxe=l.object({kind:l.enum(["boolean","string","number"]),description:l.string().trim().min(1).max(200),enum:l.array(l.string().min(1)).min(1).optional()}).strict().superRefine((e,t)=>{e.enum&&e.kind!=="string"&&t.addIssue({code:"custom",message:'Event match field enum requires kind "string".',path:["enum"]})}),kxe=l.record(l.string().regex(LK),Cxe).superRefine((e,t)=>{Object.keys(e).length>zg&&t.addIssue({code:"custom",message:`Event match keys may include at most ${zg} keys.`})}),SHe=l.record(l.string().regex(LK),l.union([l.boolean(),l.number().finite(),l.string().min(1),l.array(l.union([l.number().finite(),l.string().min(1)])).min(1)])).superRefine((e,t)=>{Object.keys(e).length>zg&&t.addIssue({code:"custom",message:`Event match may include at most ${zg} keys.`});for(let[a,r]of Object.entries(e))Array.isArray(r)&&r.some(n=>typeof n=="boolean")&&t.addIssue({code:"custom",message:`Event match field "${a}" cannot use a boolean list.`,path:[a]})});var Ixe=l.object({format:l.string().trim().min(1).max(200),pattern:l.instanceof(RegExp)}).strict(),Lxe=l.object({type:IK,identifier:Ixe.optional(),supportedEvents:l.array(Vm).min(1),suggestedEvents:l.array(Vm).optional(),matchFields:kxe.optional(),guidance:l.record(Vm,l.string().trim().min(1).max(Sxe)).optional()}).strict().superRefine((e,t)=>{let a=new Set;e.supportedEvents.forEach((n,o)=>{a.has(n)&&t.addIssue({code:"custom",message:`Duplicate supported event type "${n}".`,path:["supportedEvents",o]}),a.add(n)});for(let n of Object.keys(e.guidance??{}))a.has(n)||t.addIssue({code:"custom",message:`Guidance event type "${n}" is not supported.`,path:["guidance",n]});let r=new Set;e.suggestedEvents?.forEach((n,o)=>{r.has(n)&&t.addIssue({code:"custom",message:`Duplicate suggested event type "${n}".`,path:["suggestedEvents",o]}),a.has(n)||t.addIssue({code:"custom",message:`Suggested event type "${n}" is not supported.`,path:["suggestedEvents",o]}),r.add(n)})}),wHe=l.object({resourceTypes:l.array(Lxe).min(1),isEnabled:l.function({input:[],output:l.boolean()}).optional(),normalizeIdentifier:l.function({input:[l.string()],output:l.string()}).optional()}).strict().superRefine((e,t)=>{let a=new Set;e.resourceTypes.forEach((r,n)=>{a.has(r.type)&&t.addIssue({code:"custom",message:`Duplicate resource type "${r.type}".`,path:["resourceTypes",n,"type"]}),a.add(r.type)})});var CHe=l.object({identifier:l.string().min(1),label:l.string().min(1),namespace:l.string().min(1),suggestedEvents:l.array(Vm).optional(),supportedEvents:l.array(Vm),type:IK}).strict(),kHe=l.object({events:l.array(Vm).min(1),id:l.string().min(1)}).strict(),Txe=l.union([l.object({provider:l.string().min(1),handle:l.string().min(1)}).strict(),l.object({email:l.string().trim().min(3)}).strict()]),_xe=l.object({objectType:Y1.optional(),eventKey:l.string().min(1),eventType:Vm,identifier:l.string().min(1),occurredAtMs:l.number().finite(),terminal:l.boolean().optional(),trustedSummary:l.string().min(1).transform(e=>e.slice(0,bxe)),data:wxe.optional(),untrustedText:l.string().transform(e=>e.slice(0,xxe)).optional(),people:l.array(Txe).max(20).optional()}).strict(),IHe=_xe.extend({namespace:l.string().min(1)}),Nxe=l.object({authority:l.enum(["instruction","context"]),actor:s4.optional()}).strict(),Rxe=l.discriminatedUnion("type",[l.object({type:l.literal("message"),role:l.enum(["user","assistant"]),text:l.string().min(1),provenance:Nxe.optional(),isRunActor:l.boolean().optional()}).strict(),l.object({type:l.literal("toolResult"),toolName:l.string().min(1),isError:l.boolean(),text:l.string().min(1).optional()}).strict()]),THe=l.object({actorUserId:l.string().min(1).optional(),completedAtMs:l.number().finite(),conversationId:l.string().min(1),destination:Xbe,locationId:l.string().min(1).optional(),actors:l.array(s4),actor:s4.optional(),runId:l.string().min(1),source:uxe,transcript:l.array(Rxe)}).strict();var NHe=l.discriminatedUnion("type",[l.object({type:l.literal("text"),text:l.string()}).strict(),l.object({type:l.literal("image"),data:l.string(),mimeType:l.string()}).strict()]),Axe=l.object({arguments:l.record(l.string(),l.unknown()),reason:l.string().min(1).optional()}).strict(),RHe=l.object({objectAnnotations:l.array(l4).optional(),target:l.string().min(1).optional(),truncated:l.boolean().optional(),continuation:Axe.optional()}).passthrough(),AHe=l.enum(["auto","review","approve"]);var PHe=l.object({auth:l.object({user:l.object({email:l.string().nullable().optional(),emailVerified:l.boolean().optional(),isAdmin:l.boolean(),name:l.string().nullable().optional()}).strict()}).strict(),pluginName:je}).strict(),$xe=l.string().regex(/^[a-z][a-z0-9-]*$/),Pxe=l.string().regex(/^[a-z][a-z0-9.-]*$/),Dxe=l.union([l.literal("read"),l.literal("write")]),TK=l.object({provider:$xe,scope:je.optional(),type:l.literal("oauth")}).strict(),_K=l.object({displayName:je.optional(),handle:je.optional(),id:je,label:je.optional(),url:je.optional()}).strict(),EHe=l.object({account:_K.optional(),accessToken:je,expiresAt:l.number().finite().optional(),refreshToken:je,refreshTokenExpiresAt:l.number().finite().optional(),scope:je.optional()}).strict(),MHe=l.object({access:Dxe,leaseScope:je.optional(),name:Pxe,reason:je.optional(),requirements:l.array(je).min(1).optional()}).strict(),Exe=l.object({domain:l.string().min(1),headers:l.record(l.string(),l.string()).refine(e=>Object.keys(e).length>0)}).strict(),Mxe=l.object({account:_K.optional(),authorization:TK.optional(),expiresAt:l.string().refine(e=>Number.isFinite(Date.parse(e))),headerTransforms:l.array(Exe).min(1)}).strict(),OHe=l.discriminatedUnion("type",[l.object({lease:Mxe,type:l.literal("lease")}).strict(),l.object({authorization:TK.optional(),message:je,type:l.literal("needed")}).strict(),l.object({message:je,type:l.literal("unavailable")}).strict()]);var Oxe=je.max(64).regex(/^[a-z][a-z0-9-]*$/),zxe=je.max(80),Uxe=je.max(500),jxe=l.enum(["primary","profile","admin"]),Bxe=l.object({detail:je.max(500).optional(),label:je.max(80),tone:l.enum(["good","neutral","warning"]).optional(),value:je.max(120)}).strict(),Fxe=l.object({label:je.max(80),value:je.max(500)}).strict(),Hxe=l.object({confirmation:je.max(500).optional(),href:je.max(500).regex(/^\/api\/plugins\/[a-z][a-z0-9-]*(?:\/|$)/),label:je.max(80),method:l.enum(["DELETE","GET"]),tone:l.enum(["danger","neutral"]).optional()}).strict(),Vxe=l.object({actions:l.array(Hxe).max(4).optional(),description:je.max(1e3).optional(),id:je.max(128),metadata:l.array(Fxe).max(8).optional(),title:je.max(4e3)}).strict(),NK=l.object({emptyText:je.max(500).optional(),metrics:l.array(Bxe).max(6).optional(),nextCursor:je.max(1e3).optional(),records:l.array(Vxe).max(100),searchPlaceholder:je.max(120).optional(),type:l.literal("list")}).strict(),qxe=l.object({description:Uxe,id:Oxe,label:zxe,navigation:jxe,pluginDisplayName:je.max(200),pluginName:je.max(100)}).strict(),RK=l.array(qxe),Zxe=je.max(1e3).optional(),Gxe=je.max(64).optional(),Kxe=l.string().trim().max(200).optional(),UHe=l.object({cursor:Zxe,filter:Gxe,limit:l.number().int().min(1).max(50),query:Kxe}).strict();var AK=l.object({email:l.string().trim().email(),emailVerified:l.boolean().optional(),name:l.string().nullable().optional()}).strict(),FHe=l.object({user:AK}).strict(),tI=l.object({user:AK.extend({isAdmin:l.boolean()}).strict()}).strict(),HHe=l.object({displayName:l.string().trim().min(1).max(80)}).strict(),$K=l.object({allowedEmailCount:l.number(),allowedGoogleDomainCount:l.number(),authRequired:l.boolean(),authPath:l.string(),basePath:l.string(),componentGallery:l.boolean(),sentryConversationLinks:l.boolean(),timeZone:l.string().optional(),version:l.string().min(1)}).strict();var Qx=b(V(),1);var PK="x-junior-version";var f4="junior:dashboard-version";function DK(e){let t=e.headers.get(PK)?.trim();!t||typeof window>"u"||window.dispatchEvent(new CustomEvent(f4,{detail:t}))}function EK(e){let[t,a]=(0,Qx.useState)(e);return(0,Qx.useEffect)(()=>{e&&a(e)},[e]),(0,Qx.useEffect)(()=>{let r=n=>{a(n.detail)};return window.addEventListener(f4,r),()=>window.removeEventListener(f4,r)},[]),t}var Cn=class extends Error{status;fields;code;apiError;constructor(t,a,r,n){super(`${t} returned ${a}`),this.status=a,this.fields=n?.fields,this.code=n?.code,r?.trim()&&(this.apiError=r.trim())}};async function Ug(e,t){let a,r,n;try{let o=await t.json();typeof o.error=="string"&&(a=o.error),typeof o.code=="string"&&(n=o.code),o.fields&&typeof o.fields=="object"&&(r=Object.fromEntries(Object.entries(o.fields).filter(i=>Array.isArray(i[1])&&i[1].every(s=>typeof s=="string"))))}catch{}throw new Cn(e,t.status,a,{fields:r,code:n})}function jg(){if(typeof window>"u")return;let e=window.__JUNIOR_DASHBOARD_BASE_PATH__??"/",t=e==="/"?"/auth/login":`${e}/auth/login`;if(window.location.pathname!==t){let a=`${window.location.pathname}${window.location.search||""}`,r=new URLSearchParams;a!=="/"&&r.set("next",a);let n=r.toString();window.location.assign(n?`${t}?${n}`:t)}}async function Bg(e,t,a){let r=await Fg(t,{body:JSON.stringify(a),credentials:"same-origin",headers:{"content-type":"application/json"},method:"PATCH"});return r.status===401&&jg(),r.ok||await Ug(t,r),e.parse(await r.json())}async function _r(e,t,a){let r=await Fg(t,{body:JSON.stringify(a),credentials:"same-origin",headers:{"content-type":"application/json"},method:"POST"});return r.status===401&&jg(),r.ok||await Ug(t,r),e.parse(await r.json())}async function MK(e,t,a){let r=await Fg(t,{body:JSON.stringify(a),credentials:"same-origin",headers:{"content-type":"application/json"},method:"PUT"});return r.status===401&&jg(),r.ok||await Ug(t,r),e.parse(await r.json())}async function Kd(e){let t=await Fg(e,{credentials:"same-origin",method:"DELETE"});t.status===401&&jg(),t.ok||await Ug(e,t)}async function aI(e,t,a={}){let r=await Fg(t,{body:JSON.stringify(a),credentials:"same-origin",headers:{"content-type":"application/json"},method:"DELETE"});return r.status===401&&jg(),r.ok||await Ug(t,r),e.parse(await r.json())}async function Fg(e,t){let a=await fetch(e,t);return DK(a),a}async function Se(e,t,a){let r=await m4(t,a);return e.parse(await r.json())}async function m4(e,t,a){let r=await Fg(e,{credentials:"same-origin",...t?{signal:t}:void 0,...a?{cache:"no-store",headers:{"if-none-match":a}}:void 0});return r.status===401&&jg(),!r.ok&&!(a&&r.status===304)&&await Ug(e,r),r}var nI=5*6e4,p4=5*6e4,Wxe=1e3;function Jxe(e,t=Date.now()){if(!e)return p4;let a=Date.parse(e);if(!Number.isFinite(a))return p4;let r=Math.max(0,t-a);return Math.max(Wxe,p4-r)}function OK(){return _e({queryKey:["dashboard","core"],queryFn:async({signal:e})=>{let[t,a]=await Promise.all([Se(tI,"/api/me",e),Se($K,"/api/config",e)]);return{config:a,me:t}},retry:!1,staleTime:nI})}function Qxe(){return _e({queryKey:["dashboard","plugins"],queryFn:({signal:e})=>Se(jM,"/api/plugins",e),retry:!1,staleTime:nI})}function zK(){return _e({queryKey:["dashboard","plugin-user-pages"],queryFn:({signal:e})=>Se(RK,"/api/user-pages",e),retry:!1,staleTime:nI})}function rI(e=""){return _e({queryKey:["dashboard","conversations","viewer",{search:e}],queryFn:({signal:t})=>Se(M1,`/api/conversations${e?`?q=${encodeURIComponent(e)}`:""}`,t),placeholderData:Of,retry:!1})}function UK(){return _e({queryKey:["dashboard","code"],queryFn:({signal:e})=>Se(qz,"/api/code",e),retry:!1})}function jK(e){return _e({enabled:!!e,queryKey:["dashboard","code","repositories",e],queryFn:({signal:t})=>Se(Zz,`/api/code/repositories/${encodeURIComponent(e)}`,t),retry:!1})}function oI(e,t=""){return _e({enabled:!!e,queryKey:["dashboard","conversations","code-repository",{repositoryId:e,search:t}],queryFn:({signal:a})=>{let r=new URLSearchParams({codeRepositoryId:e});return t&&r.set("q",t),Se(M1,`/api/conversations?${r.toString()}`,a)},placeholderData:Of,retry:!1})}function BK(e,t){return _e({enabled:e,queryKey:["dashboard","automations",t],queryFn:({signal:a})=>Se(AM,`/api/automations${t?`?${t}`:""}`,a),placeholderData:Of,retry:!1})}function Hg(e,t){return _e({enabled:e&&!!t,queryKey:["dashboard","automations","detail",t],queryFn:({signal:a})=>Se(Vx,`/api/automations/${encodeURIComponent(t)}`,a),retry:!1})}function FK(e){return _e({enabled:e,queryKey:["dashboard","automations","runs"],queryFn:({signal:t})=>Se(DM,"/api/automations/runs",t),retry:!1})}function HK(e,t){return _e({enabled:e&&!!t,queryKey:["dashboard","automations",t,"executions"],queryFn:({signal:a})=>Se(PM,`/api/automations/${encodeURIComponent(t)}/executions`,a),retry:!1})}function VK(e,t){return _e({enabled:e&&!!t,queryKey:["dashboard","automations",t,"versions"],queryFn:({signal:a})=>Se(EM,`/api/automations/${encodeURIComponent(t)}/versions`,a),retry:!1})}function qK(){return _e({queryKey:["dashboard","people"],queryFn:({signal:e})=>Se(Yz,"/api/people",e),retry:!1})}function ZK(e){return _e({enabled:!!e,queryKey:["dashboard","people",e],queryFn:async({signal:t})=>Se(e4,`/api/people/${encodeURIComponent(e)}`,t),retry:!1})}function GK(e){return _e({enabled:!!e,queryKey:["dashboard","people",e,"plugin-reports"],queryFn:({signal:t})=>Se(j1,`/api/people/${encodeURIComponent(e)}/plugin-reports`,t),retry:!1})}function KK(e){return _e({enabled:!!e,queryKey:["dashboard","people",e,"code"],queryFn:({signal:t})=>Se(Gz,`/api/people/${encodeURIComponent(e)}/code`,t),retry:!1})}function WK(e){return _e({enabled:e,queryKey:["dashboard","personal-spend"],queryFn:({signal:t})=>Se(t4,"/api/people/me/spend",t),refetchInterval:t=>Jxe(t.state.data?.generatedAt),retry:!1,staleTime:0})}function JK(){return _e({queryKey:["dashboard","locations"],queryFn:({signal:e})=>Se(Qz,"/api/locations",e),retry:!1})}function QK(e){return _e({enabled:!!e,queryKey:["dashboard","locations",e],queryFn:async({signal:t})=>Se(Xz,`/api/locations/${encodeURIComponent(e)}`,t),retry:!1})}function Xxe(){return _e({queryKey:["dashboard","skills"],queryFn:({signal:e})=>Se(FM,"/api/skills",e),retry:!1,staleTime:nI})}function Yxe(){return _e({queryKey:["dashboard","plugin-reports"],queryFn:({signal:e})=>Se(j1,"/api/plugin-reports",e),retry:!1})}function XK(){return _e({queryKey:["dashboard","stats"],queryFn:({signal:e})=>Se(i4,"/api/stats",e),retry:!1})}function YK(e){let t=Qxe(),a=_e({queryKey:["dashboard","conversation-stats"],queryFn:({signal:i})=>Se(_M,"/api/conversations/stats",i),retry:!1}),r=Xxe(),n=Yxe();return{data:t.data&&r.data?{...e,conversationStatsError:!!a.error,...a.data?{conversationStats:a.data}:void 0,conversationStatsLoading:a.isPending,pluginReportsError:!!n.error,...n.data?{pluginReports:n.data}:void 0,pluginReportsLoading:n.isPending,plugins:t.data,skills:r.data}:void 0,error:t.error??r.error,isPending:t.isPending||r.isPending}}var nW=b(V(),1);var eW="Junior";function Pt(){return typeof window>"u"?eW:window.__JUNIOR_DASHBOARD_AGENT_NAME__?.trim()||eW}function tW(e=Pt()){return e.endsWith("s")?`${e}'`:`${e}'s`}function aW(e,t=Pt()){let a=e?.trim();return a?`${a} - ${t}`:t}function Si(e){(0,nW.useEffect)(()=>{if(e?.trim())return document.title=aW(e),()=>{document.title=aW(void 0)}},[e])}function L(...e){return e.filter(Boolean).join(" ")}var Ba="mx-auto w-full min-w-0 max-w-screen-xl",iu="text-dashboard-text underline decoration-dashboard-border-heavy underline-offset-2 transition-colors hover:decoration-dashboard-text-muted",qm="text-dashboard-text-muted hover:text-dashboard-text",rW="rounded-xl border border-dashboard-border-emphasis bg-dashboard-surface-raised shadow-[0_8px_32px_rgba(0,0,0,0.35)] transition-colors";var iI=b(w(),1),oW="inline-flex h-9 max-w-full items-center justify-center gap-2 rounded-md border border-dashboard-border-emphasis bg-dashboard-surface-raised px-3 font-sans text-sm font-medium leading-none text-dashboard-text transition-colors hover:border-dashboard-border-heavy hover:bg-dashboard-surface-hover hover:text-dashboard-text focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-dashboard-focus",eSe="inline-flex h-9 max-w-full items-center justify-center gap-2 rounded-md border border-dashboard-border-strong bg-transparent px-3 font-sans text-sm font-medium leading-none text-dashboard-text-muted transition-colors hover:border-rose-300/40 hover:text-rose-300 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-rose-300/55";function oe({className:e,size:t="default",tone:a="default",type:r="button",...n}){let o=a==="danger";return(0,iI.jsx)("button",{...n,className:L("font-sans transition-colors disabled:cursor-not-allowed disabled:opacity-50",t==="icon"?L("grid size-9 place-items-center rounded-md border-0 bg-transparent p-0 focus-visible:outline-2 focus-visible:outline-offset-1 disabled:hover:!bg-transparent",o?"text-dashboard-text-muted hover:!bg-rose-300/10 hover:!text-rose-300 focus-visible:outline-rose-300/55 disabled:hover:!text-dashboard-text-muted":"text-dashboard-text-muted hover:!bg-dashboard-fill-strong hover:!text-dashboard-text focus-visible:outline-dashboard-focus disabled:hover:!text-dashboard-text-muted"):a==="primary"?"inline-flex h-9 items-center justify-center gap-2 rounded-md border border-dashboard-text-solid bg-dashboard-text-solid px-3 font-sans text-sm font-medium leading-none text-dashboard-text-inverse hover:border-dashboard-text-subtle hover:bg-dashboard-text-subtle disabled:hover:border-dashboard-text-solid disabled:hover:bg-dashboard-text-solid focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-dashboard-focus":o?L(eSe,"disabled:hover:border-dashboard-border-strong disabled:hover:text-dashboard-text-muted"):L(oW,"disabled:hover:border-dashboard-border-emphasis disabled:hover:bg-dashboard-surface-raised disabled:hover:text-dashboard-text"),n.disabled?"":"cursor-pointer",e),type:r})}function su({className:e,...t}){return(0,iI.jsx)(te,{...t,className:L(oW,"no-underline",e)})}function Dn({className:e,pressed:t,type:a="button",variant:r,...n}){return(0,iI.jsx)("button",{...n,"aria-pressed":t,className:L(tSe[r],t?aSe[r]:nSe[r],e),type:a})}var tSe={pill:"cursor-pointer rounded-md border px-2 py-1 font-sans text-xs font-medium leading-tight transition-colors focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-dashboard-focus",segment:"inline-flex h-7 min-w-10 cursor-pointer items-center justify-center rounded-md border px-2 font-sans text-xs font-medium transition-colors focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-dashboard-focus",text:"cursor-pointer rounded-sm border-0 bg-transparent px-1.5 py-1 font-sans font-medium underline-offset-4 transition-colors focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-dashboard-focus"},aSe={pill:"border-dashboard-border-heavy bg-dashboard-text-solid text-dashboard-text-inverse",segment:"border-dashboard-border-interactive bg-dashboard-surface-active text-dashboard-text",text:"text-dashboard-text underline decoration-dashboard-text-solid"},nSe={pill:"border-dashboard-border-strong bg-dashboard-surface-raised text-dashboard-text-muted hover:border-dashboard-border-interactive hover:bg-dashboard-surface-hover hover:text-dashboard-text",segment:"border-transparent bg-transparent text-dashboard-text-muted hover:bg-dashboard-fill-hover hover:text-dashboard-text",text:"text-dashboard-text-muted hover:text-dashboard-text"};var Zm=b(w(),1);function uo(e){let t=e.tone==="error";return(0,Zm.jsxs)("div",{role:t?"alert":"status",className:L("flex min-w-0 gap-3 rounded-md border p-4",t?"border-rose-300/25 bg-rose-300/5":"border-amber-300/25 bg-amber-300/5"),children:[(0,Zm.jsx)(ro,{"aria-hidden":!0,size:18,className:L("mt-0.5 shrink-0",t?"text-rose-300":"text-amber-300")}),(0,Zm.jsxs)("div",{className:"min-w-0",children:[(0,Zm.jsx)("p",{className:"m-0 text-sm font-medium",children:e.title}),e.children?(0,Zm.jsx)("div",{className:"mt-1 text-sm leading-relaxed text-dashboard-text-muted",children:e.children}):null]})]})}var Xx=b(w(),1),rSe={accent:"text-dashboard-accent",danger:"text-rose-300",info:"text-cyan-300",neutral:"text-dashboard-text-muted",success:"text-emerald-300",warning:"text-amber-300"},oSe={compact:"text-xs",default:"text-sm"};function Zt(e){return(0,Xx.jsxs)("span",{className:L("inline-flex w-fit items-center gap-1.5 font-sans font-medium normal-case leading-snug tracking-normal",oSe[e.size??"default"],rSe[e.tone??"neutral"],e.className),children:[(0,Xx.jsx)("span",{"aria-hidden":"true",className:"size-1.5 shrink-0 rounded-full bg-current"}),(0,Xx.jsx)("span",{className:"block first-letter:uppercase",children:e.children})]})}var iW=b(w(),1);function j(e){let t=e.as??"div",a={none:"",sm:"p-4",md:"p-5 sm:p-6"}[e.padding??"none"],r=e.variant==="section"?"mb-4 border-dashboard-border-subtle bg-dashboard-fill-faint shadow-[0_24px_80px_rgba(0,0,0,0.18)]":e.variant==="raised"?"border-dashboard-border-emphasis bg-dashboard-surface-raised":"border-dashboard-border-subtle bg-dashboard-fill-faint";return(0,iW.jsx)(t,{className:L("min-w-0 overflow-hidden rounded-lg border",r,a,e.className),children:e.children})}var sW=b(w(),1);function et(e){let t=e.as??"div";return(0,sW.jsx)(t,{"aria-hidden":"true",className:L("animate-pulse rounded-md bg-dashboard-fill-soft motion-reduce:animate-none",e.className)})}var lt=b(w(),1);function sr(e){let t=e.variant??"panel";return(0,lt.jsxs)("div",{"aria-busy":"true","aria-live":"polite",className:L("grid gap-4",e.className),role:"status",children:[(0,lt.jsx)("span",{className:"sr-only",children:e.label}),iSe(t)]})}function iSe(e){switch(e){case"stats":return(0,lt.jsx)(sSe,{});case"overview":return(0,lt.jsx)(lSe,{});case"list":return(0,lt.jsx)(uSe,{});case"library":return(0,lt.jsx)(cSe,{});case"panel":return(0,lt.jsx)(lu,{className:"min-h-64"})}}function sSe(){return(0,lt.jsxs)(lt.Fragment,{children:[(0,lt.jsx)("div",{className:"grid grid-cols-2 gap-3 lg:grid-cols-4",children:Array.from({length:4},(e,t)=>(0,lt.jsx)(lu,{className:"min-h-[7.5rem] p-4 sm:min-h-32 sm:p-5"},t))}),(0,lt.jsx)(lu,{className:"min-h-[17rem]"})]})}function lSe(){return(0,lt.jsxs)(lt.Fragment,{children:[(0,lt.jsxs)("div",{className:"grid gap-4 xl:grid-cols-2",children:[(0,lt.jsx)(lu,{className:"min-h-[17rem]"}),(0,lt.jsx)(lu,{className:"min-h-[17rem]"})]}),(0,lt.jsx)(Vg,{className:"h-24 border-y border-dashboard-border-subtle bg-dashboard-fill-faint"}),(0,lt.jsxs)("div",{className:"grid gap-4 md:grid-cols-2",children:[(0,lt.jsx)(lu,{className:"min-h-56"}),(0,lt.jsx)(lu,{className:"min-h-56"})]})]})}function uSe(){return(0,lt.jsxs)(lt.Fragment,{children:[(0,lt.jsx)(lu,{className:"min-h-20 p-4"}),(0,lt.jsx)(Vg,{className:"h-10 border-b border-dashboard-border-subtle"}),(0,lt.jsx)(lu,{className:"min-h-80"})]})}function cSe(){return(0,lt.jsxs)(lt.Fragment,{children:[(0,lt.jsxs)("div",{className:"flex flex-wrap items-end justify-between gap-4",children:[(0,lt.jsx)(Vg,{className:"h-7 w-56 rounded-md bg-dashboard-fill-soft"}),(0,lt.jsx)(Vg,{className:"h-10 w-full max-w-md rounded-lg border border-dashboard-border-subtle bg-dashboard-fill-faint sm:w-72"})]}),(0,lt.jsx)("div",{"aria-hidden":"true",className:"grid min-w-0 grid-cols-3 gap-1 border-b border-dashboard-border-subtle sm:flex",children:Array.from({length:3},(e,t)=>(0,lt.jsxs)("div",{className:"flex items-center justify-between gap-2 px-3 py-2.5 sm:justify-start",children:[(0,lt.jsx)(Vg,{className:"h-3 w-12 rounded-md bg-dashboard-fill-soft"}),(0,lt.jsx)(Vg,{className:"h-5 w-8 rounded-sm border border-dashboard-border-subtle bg-dashboard-fill-faint"})]},t))}),(0,lt.jsx)(lu,{className:"min-h-80"})]})}function lu(e){return(0,lt.jsx)(j,{className:L("animate-pulse motion-reduce:animate-none",e.className),children:(0,lt.jsx)("span",{"aria-hidden":"true"})})}function Vg(e){return(0,lt.jsx)(et,{className:e.className})}var h4=b(w(),1),dSe=[1,7,30,90];function g4(e){return e===1?"24h":`${e}d`}function qg(e){return e===1?"last 24 hours":`last ${e} days`}function Xa(e){return e===1?"hour":e===7?"6hour":"day"}function lW(e){return e===1}function fSe(e){return e===7}function co(e){return e==="hour"?"hour":e==="6hour"?"6h":"day"}function Zg(e){return e==="hour"?"hour":e==="6hour"?"6 hours":"day"}function Yx(e){return e==="hour"?"Hourly":e==="6hour"?"6-hour":"Daily"}function ln(e){return lW(e.range)&&e.hours?.length?e.hours.slice(-24):lW(e.range)?e.days.slice(-1):fSe(e.range)?e.sixHours?.length?[...e.sixHours]:e.hours?.length&&e.emptySixHour?mSe({empty:e.emptySixHour,hours:e.hours}):e.days.slice(-e.range):e.days.slice(-e.range)}function mSe(e){let t=new Map;for(let a of e.hours){let r=Date.parse(`${a.date}:00:00.000Z`);if(Number.isNaN(r))continue;let n=new Date(r);n.setUTCMinutes(0,0,0),n.setUTCHours(Math.floor(n.getUTCHours()/6)*6,0,0,0);let o=n.toISOString().slice(0,13),s={...t.get(o)??e.empty(o),date:o};for(let[u,c]of Object.entries(a))if(u!=="date"&&typeof c=="number"){let d=s[u];s[u]=(typeof d=="number"?d:0)+c}t.set(o,s)}if(e.hours.length>=24){let a=e.hours[e.hours.length-1]?.date,r=a?Date.parse(`${a}:00:00.000Z`):Date.now(),n=new Date(r);n.setUTCMinutes(0,0,0),n.setUTCHours(Math.floor(n.getUTCHours()/6)*6,0,0,0);let o=new Date(n.getTime()-9720*60*1e3),i=[];for(let s=new Date(o);s.getTime()<=n.getTime();s.setTime(s.getTime()+360*60*1e3)){let u=s.toISOString().slice(0,13);i.push(t.get(u)??e.empty(u))}return i}return[...t.values()].sort((a,r)=>a.date.localeCompare(r.date))}function Gg(e){return(0,h4.jsx)("div",{"aria-label":"Reporting period",className:"flex items-center gap-1",role:"group",children:(e.options??dSe).map(t=>(0,h4.jsx)(Dn,{onClick:()=>e.onChange(t),pressed:e.value===t,variant:"segment",children:g4(t)},t))})}var Wd=b(w(),1);function We(e){Si(e.documentTitle??(typeof e.title=="string"?e.title:void 0));let t=e.range!==void 0&&e.onRangeChange?(0,Wd.jsx)(Gg,{onChange:e.onRangeChange,...e.rangeOptions?{options:e.rangeOptions}:{},value:e.range}):void 0,a=e.actions??t;return(0,Wd.jsxs)("header",{className:"flex min-w-0 items-center justify-between gap-6 border-b border-dashboard-border-subtle pb-4 sm:pb-6 max-md:flex-col max-md:items-stretch",children:[(0,Wd.jsxs)("div",{className:"min-w-0",children:[(0,Wd.jsx)("h2",{className:"m-0 font-display text-3xl font-light leading-none tracking-[-0.03em] text-dashboard-text sm:text-4xl",children:e.title}),(0,Wd.jsx)("div",{className:"mt-2 max-w-2xl font-sans text-xs leading-relaxed text-dashboard-text-muted sm:text-sm",children:e.description})]}),a?(0,Wd.jsx)("div",{className:"shrink-0",children:a}):null]})}var uW=b(w(),1);function Eo(e){return(0,uW.jsx)("div",{className:L(Ba,"grid min-w-0 content-start gap-4 px-4 py-4 pb-[max(1rem,env(safe-area-inset-bottom))] sm:gap-6 sm:px-8 sm:py-8 sm:pb-8",e.className),children:e.children})}var Km=b(V(),1);var Gm=b(V(),1);function Ji(e,t){let a=typeof t=="string"?t.startsWith("?")?t.slice(1):t:t?.toString()??"",r=e.indexOf("?"),n=r===-1?e:e.slice(0,r),o=r===-1?"":e.slice(r+1).replace(/^\?+/,""),i=new URLSearchParams(a);for(let[u,c]of new URLSearchParams(o))i.set(u,c);let s=i.toString();return s?`${n}?${s}`:n}function pSe(e,t){let a=e?.trim();return a&&t.includes(a)?a:void 0}function uu(e="q",t={}){let a=t.delayMs??250,r=t.resetPage??!1,[n,o]=li(),i=n.get(e)?.trim()??"",[s,u]=(0,Gm.useState)(i);return(0,Gm.useEffect)(()=>{u(c=>c.trim()===i?c:i)},[i]),(0,Gm.useEffect)(()=>{let c=window.setTimeout(()=>{let d=s.trim();d!==i&&o(f=>{let m=new URLSearchParams(f);return r&&m.delete("page"),d?m.set(e,d):m.delete(e),m},{replace:!0})},a);return()=>window.clearTimeout(c)},[i,a,e,r,o,s]),[s,u,i]}function yc(e,t,a){let[r,n]=li(),o=pSe(r.get(e),a)??t,i=(0,Gm.useCallback)(s=>{n(u=>{let c=new URLSearchParams(u);return s===t?c.delete(e):c.set(e,s),c},{replace:!0})},[t,e,n]);return[o,i]}var Kg=b(w(),1);function y4(e){let{className:t,item:a}=e,r=xt(),n=Ji(a.to,r.search);if(a.isActive){let o=a.isActive(r.pathname);return(0,Kg.jsx)(te,{"aria-current":o?"page":void 0,className:t({isActive:o}),to:n,children:a.label})}return(0,Kg.jsx)(um,{className:t,end:a.end,to:n,children:a.label})}var v4=24;function dW(e){let t=e.scrollWidth-e.clientWidth;return{end:e.scrollLeft<t-1,start:e.scrollLeft>1}}function cW(e){let t=e.querySelector('[aria-current="page"]');if(!t||e.clientWidth===0)return;let a=dW(e),r=e.scrollLeft+(a.start?v4:0),n=e.scrollLeft+e.clientWidth-(a.end?v4:0),o=t.offsetLeft,i=o+t.offsetWidth;o>=r&&i<=n||(e.scrollLeft=o-(e.clientWidth-t.offsetWidth)/2)}function hSe(e){if(!e.start&&!e.end)return;let t=`${v4}px`,a=e.start?`transparent, black ${t}`:"black",r=e.end?`black calc(100% - ${t}), transparent`:"black",n=`linear-gradient(to right, ${a}, ${r})`;return{maskImage:n,WebkitMaskImage:n}}function Wm(e){let{pathname:t}=xt(),a=(0,Km.useRef)(null),[r,n]=(0,Km.useState)({end:!1,start:!1});(0,Km.useLayoutEffect)(()=>{let i=a.current;if(!i)return;let s=()=>{let{end:c,start:d}=dW(i);n(f=>f.start===d&&f.end===c?f:{end:c,start:d})},u=new ResizeObserver(()=>{i.scrollLeft=0,cW(i),s()});s(),i.addEventListener("scroll",s,{passive:!0}),u.observe(i);for(let c of i.children)u.observe(c);return()=>{i.removeEventListener("scroll",s),u.disconnect()}},[]),(0,Km.useLayoutEffect)(()=>{a.current&&cW(a.current)},[t]);let o=({isActive:i})=>L("relative flex h-10 items-center justify-center whitespace-nowrap font-sans text-sm font-medium no-underline transition-colors after:absolute after:inset-x-0 after:bottom-0 after:h-0.5 focus-visible:outline-2 focus-visible:-outline-offset-2 focus-visible:outline-dashboard-focus",i?"text-dashboard-text after:bg-dashboard-text-solid":"text-dashboard-text-muted hover:text-dashboard-text",e.fill?"min-w-max flex-[1_0_0]":"shrink-0");return(0,Kg.jsx)("nav",{"aria-label":e.ariaLabel,className:L("flex min-w-0 max-w-full",!e.fill&&"w-fit"),children:(0,Kg.jsx)("div",{className:L("relative -mx-1 flex gap-5 px-1 min-w-0 flex-1 overflow-x-auto [scrollbar-width:none] [&::-webkit-scrollbar]:hidden"),ref:a,style:hSe(r),children:e.items.map(i=>(0,Kg.jsx)(y4,{className:o,item:i},i.to))})})}var ta=b(V(),1),eS=b(Fl(),1),As=b(w(),1),cu=(0,ta.createContext)(null);function sI(e){let[t,a]=(0,ta.useState)(null),[r,n]=(0,ta.useState)(null),[o,i]=(0,ta.useState)(null),[s,u]=(0,ta.useState)(null),c=(0,ta.useRef)(null),d=(0,ta.useCallback)(g=>{a(g)},[]),f=(0,ta.useCallback)(g=>{n(g)},[]),m=(0,ta.useCallback)(g=>{i(g)},[]),h=(0,ta.useCallback)(g=>{u(g)},[]),p=(0,ta.useCallback)(g=>{c.current=g},[]),v=(0,ta.useCallback)(()=>{c.current?.()},[]),x=(0,ta.useMemo)(()=>({mobileHeaderActionsSlot:o,mobileHeaderActionsSlotRef:m,mobileHeaderLiveSlot:s,mobileHeaderLiveSlotRef:h,mobileSecondarySlot:r,mobileSecondarySlotRef:f,openMobileNavigation:v,registerOpenMobileNavigation:p,secondarySlot:t,secondarySlotRef:d}),[o,m,s,h,r,f,v,p,t,d]);return(0,As.jsx)(cu.Provider,{value:x,children:e.children})}function fW(e){let t=(0,ta.useContext)(cu);if(!t)throw new Error("DashboardChrome requires DashboardChromeProvider");return(0,As.jsxs)("div",{className:"sticky top-0 z-30 bg-dashboard-bg/95 pt-[env(safe-area-inset-top)]",children:[(0,As.jsxs)("div",{className:"border-b border-dashboard-border-strong",children:[e.header,(0,As.jsx)("div",{className:"hidden md:block",ref:t.secondarySlotRef})]}),e.banner]})}function mW(){let e=(0,ta.useContext)(cu);if(!e)throw new Error("MobileSecondaryNavigationSlot requires DashboardChromeProvider");return(0,As.jsx)("div",{ref:e.mobileSecondarySlotRef})}function pW(){let e=(0,ta.useContext)(cu);if(!e)throw new Error("MobileHeaderActionsSlot requires DashboardChromeProvider");return(0,As.jsx)("div",{className:"col-start-3 row-start-1 flex min-w-0 items-center justify-self-end md:hidden",ref:e.mobileHeaderActionsSlotRef})}function hW(){let e=(0,ta.useContext)(cu);if(!e)throw new Error("MobileHeaderLiveSlot requires DashboardChromeProvider");return(0,As.jsx)("div",{className:"flex shrink-0 items-center md:hidden",ref:e.mobileHeaderLiveSlotRef})}function gW(e){let t=(0,ta.useContext)(cu);return t?.mobileHeaderActionsSlot?(0,eS.createPortal)(e.children,t.mobileHeaderActionsSlot):null}function vW(e){let t=(0,ta.useContext)(cu);return t?.mobileHeaderLiveSlot?(0,eS.createPortal)(e.children,t.mobileHeaderLiveSlot):null}function yW(){let e=(0,ta.useContext)(cu);return e?e.openMobileNavigation:null}function bW(e){let t=(0,ta.useContext)(cu),a=(0,ta.useRef)(e);a.current=e,(0,ta.useEffect)(()=>{if(!t)return;let r=()=>{a.current?.()};return t.registerOpenMobileNavigation(e?r:null),()=>{t.registerOpenMobileNavigation(null)}},[t,e])}function xW(e){let t=(0,ta.useContext)(cu);return t?t.secondarySlot?(0,As.jsxs)(As.Fragment,{children:[(0,eS.createPortal)(e.desktop,t.secondarySlot),t.mobileSecondarySlot?(0,eS.createPortal)(e.mobile,t.mobileSecondarySlot):null]}):null:e.desktop}var du=b(w(),1);function Jd(e){let t=({isActive:a})=>L("rounded-lg px-3 py-3 pl-6 font-sans text-sm font-medium no-underline transition-colors",a?"bg-dashboard-accent/[0.1] text-dashboard-accent-text":L("hover:bg-dashboard-fill-faint",qm));return(0,du.jsxs)("div",{className:"min-w-0",children:[(0,du.jsx)(xW,{desktop:(0,du.jsx)("div",{className:L(Ba,"min-w-0 px-4 md:px-8"),children:(0,du.jsx)(Wm,{ariaLabel:e.ariaLabel,items:e.items})}),mobile:(0,du.jsx)("nav",{"aria-label":e.ariaLabel,className:"mt-3 grid gap-1 border-t border-dashboard-border pt-3",children:e.items.map(a=>(0,du.jsx)(y4,{className:t,item:a},a.to))})}),(0,du.jsx)("div",{className:"border-b border-dashboard-border px-4 pt-2 sm:px-8 md:hidden",children:(0,du.jsx)(Wm,{ariaLabel:e.ariaLabel,fill:!0,items:e.items})}),e.children]})}var fu=b(w(),1),gSe=new Set(["list","runs"]);function vSe(e){if(e==="/automations/list"||/^\/automations\/(scheduled|event)\/[^/]+\/edit$/.test(e))return!0;let t=e.match(/^\/automations\/([^/]+)$/);return!!(t?.[1]&&!gSe.has(t[1]))}var ySe=[{end:!0,label:"Overview",to:"/automations"},{isActive:vSe,label:"Automations",to:"/automations/list"},{label:"Runs",to:"/automations/runs"}];function b4(e){return(0,fu.jsx)(Jd,{ariaLabel:"Automations navigation",items:ySe,children:e.children})}function Qi(e){return(0,fu.jsx)(b4,{children:(0,fu.jsx)(Eo,{children:e.children})})}function Jm(e){return(0,fu.jsxs)(fu.Fragment,{children:[(0,fu.jsx)(We,{description:e.description,title:e.title}),(0,fu.jsx)(sr,{label:e.label,variant:e.variant})]})}var Ps=b(V(),1);var Wg=b(w(),1),bSe={compact:"font-sans font-medium text-xs text-dashboard-text-muted",default:"text-sm font-semibold text-dashboard-text"},xSe={compact:"grid gap-1.5",default:"grid gap-2"};function Gt(e){let t=e.size??"default";return(0,Wg.jsxs)("div",{className:L(xSe[t],e.className),children:[(0,Wg.jsx)("label",{className:bSe[t],htmlFor:e.htmlFor,children:e.label}),e.children,e.error?(0,Wg.jsx)("p",{id:e.htmlFor?`${e.htmlFor}-error`:void 0,role:"alert",className:"m-0 text-xs leading-relaxed text-rose-300",children:e.error}):null,e.help?(0,Wg.jsx)("p",{id:e.htmlFor?`${e.htmlFor}-help`:void 0,className:"m-0 text-xs leading-relaxed text-dashboard-text-muted sm:text-sm",children:e.help}):null]})}var x4=b(w(),1),SW="block w-full rounded-md border border-dashboard-border-emphasis bg-dashboard-ink px-3 py-2 font-sans text-sm text-dashboard-text placeholder:text-dashboard-text-muted/70 focus:border-dashboard-focus focus:outline-none focus:ring-1 focus:ring-dashboard-focus/25 aria-invalid:border-rose-300 disabled:cursor-not-allowed disabled:opacity-50";function Ta({className:e,type:t="text",size:a="default",...r}){return(0,x4.jsx)("input",{...r,className:L(SW,a==="comfortable"&&"min-h-11 text-base sm:min-h-10 sm:text-sm",e),type:t})}function bc({className:e,prose:t=!1,...a}){return(0,x4.jsx)("textarea",{...a,className:L(SW,"min-h-36",t?"font-sans leading-relaxed":"font-mono",e)})}var Qm=b(w(),1);function $s(e){return(0,Qm.jsxs)("section",{className:"grid min-w-0 gap-5 border-t border-dashboard-border-emphasis py-8 md:grid-cols-[12rem_minmax(0,1fr)] md:gap-10",children:[(0,Qm.jsxs)("div",{children:[(0,Qm.jsx)("h2",{className:"m-0 font-display text-lg font-medium",children:e.title}),e.detail?(0,Qm.jsx)("p",{className:"mt-2 mb-0 text-sm leading-relaxed text-dashboard-text-muted",children:e.detail}):null]}),(0,Qm.jsx)("div",{className:"grid min-w-0 content-start gap-5",children:e.children})]})}var dI=b(V(),1);var wW=b(w(),1);function mu({className:e,...t}){return(0,wW.jsx)("select",{...t,className:L("block min-h-11 w-full min-w-0 rounded-md border border-dashboard-border-emphasis bg-dashboard-ink px-3 py-2 text-base text-dashboard-text focus:border-dashboard-focus focus:outline-none aria-invalid:border-rose-300 disabled:cursor-not-allowed disabled:opacity-60 sm:min-h-10 sm:text-sm",e)})}var lI=["sunday","monday","tuesday","wednesday","thursday","friday","saturday"];function uI(e){return{title:e.title??"",instruction:e.instruction,credentialMode:e.credentialMode,outcomes:e.outcomes,trigger:e.kind==="event"?e.trigger:void 0}}function cI(e){let t=e.schedule.recurrence;if(e.schedule.kind==="recurring"&&t){let{time:a,weekdays:r,...n}=t;return{kind:"recurring",...n,timezone:e.schedule.timezone,time:`${String(a.hour).padStart(2,"0")}:${String(a.minute).padStart(2,"0")}`,weekdays:r?.map(o=>lI[o])}}if(e.nextRunAtMs){let a=new Intl.DateTimeFormat("en-CA",{timeZone:e.schedule.timezone,year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",hourCycle:"h23"}).formatToParts(e.nextRunAtMs),r=n=>a.find(o=>o.type===n)?.value??"";return{kind:"one_off",timezone:e.schedule.timezone,timing:{type:"at",date:`${r("year")}-${r("month")}-${r("day")}`,time:`${r("hour")}:${r("minute")}`}}}return{kind:"recurring",frequency:"daily",time:"09:00",timezone:e.schedule.timezone}}function CW(e,t){let a={};return t.title!==(e.title??"")&&(a.title=t.title),t.instruction!==e.instruction&&(a.instruction=t.instruction),t.credentialMode!==e.credentialMode&&(a.credentialMode=t.credentialMode),JSON.stringify(t.outcomes)!==JSON.stringify(e.outcomes)&&(a.outcomes=t.outcomes),e.kind==="scheduled"&&t.schedule&&(a.schedule=t.schedule),e.kind==="event"&&JSON.stringify(t.trigger)!==JSON.stringify(e.trigger)&&(a.trigger=t.trigger),a}var He=b(w(),1);function kW(e){let t=e.value??cI(e.automation),[a,r]=(0,dI.useState)(e.value);(0,dI.useEffect)(()=>{let f=setTimeout(()=>r(e.value),300);return()=>clearTimeout(f)},[e.value]);let n=zM.safeParse(a),o=_e({queryKey:["dashboard","automation-schedule-preview",e.automation.id,a],enabled:!!a&&n.success,retry:!1,queryFn:()=>_r(UM,`/api/automations/${encodeURIComponent(e.automation.id)}/preview`,a)}),i=t.kind==="recurring"?t.frequency:"once",s=t.kind==="recurring"?t.time:t.timing.time,u=e.value?o.data?.nextRunAtMs:e.automation.nextRunAtMs,c=e.value!==a||o.isFetching,d=o.error instanceof Cn?o.error.apiError:o.error?"Schedule preview could not be loaded. Try again.":e.value&&!n.success&&!c?n.error.issues[0]?.message:void 0;return(0,He.jsxs)(He.Fragment,{children:[(0,He.jsxs)("div",{className:"grid grid-cols-1 items-start gap-4 sm:grid-cols-2",children:[(0,He.jsx)(Gt,{label:"Repeat",htmlFor:"schedule-frequency",children:(0,He.jsxs)(mu,{id:"schedule-frequency",value:i,onChange:f=>{let m=f.target.value;m!=="once"&&m!=="daily"&&m!=="weekly"&&m!=="monthly"&&m!=="yearly"||e.onChange(m==="once"?{kind:"one_off",timezone:t.timezone??e.automation.schedule.timezone,timing:{type:"at",date:"",time:s}}:{kind:"recurring",timezone:t.timezone,time:s,frequency:m,interval:1,weekdays:m==="weekly"?["monday"]:void 0,dayOfMonth:["monthly","yearly"].includes(m)?1:void 0,month:m==="yearly"?1:void 0})},children:[(0,He.jsx)("option",{value:"once",children:"Once"}),(0,He.jsx)("option",{value:"daily",children:"Every day"}),(0,He.jsx)("option",{value:"weekly",children:"Every week"}),(0,He.jsx)("option",{value:"monthly",children:"Every month"}),(0,He.jsx)("option",{value:"yearly",children:"Every year"})]})}),(0,He.jsx)(Gt,{label:"Time",htmlFor:"schedule-time",children:(0,He.jsx)(Ta,{size:"comfortable",id:"schedule-time",type:"time",value:s,onChange:f=>e.onChange(t.kind==="recurring"?{...t,time:f.target.value}:{...t,timing:{type:"at",date:t.timing.date,time:f.target.value}})})})]}),t.kind==="recurring"?(0,He.jsxs)(He.Fragment,{children:[t.frequency==="weekly"?(0,He.jsxs)("fieldset",{children:[(0,He.jsx)("legend",{className:"mb-2 text-sm font-semibold",children:"On"}),(0,He.jsx)("div",{className:"grid grid-cols-7 gap-1.5",children:[...lI.slice(1),lI[0]].map(f=>(0,He.jsx)("button",{type:"button","aria-label":f,"aria-pressed":t.weekdays?.includes(f)??!1,onClick:()=>e.onChange({...t,weekdays:t.weekdays?.includes(f)?t.weekdays.filter(m=>m!==f):[...t.weekdays??[],f]}),className:L("min-h-11 cursor-pointer rounded-md border px-1 text-xs font-medium capitalize focus-visible:outline-2 focus-visible:outline-dashboard-focus sm:min-h-10 sm:text-sm",t.weekdays?.includes(f)?"border-dashboard-focus/50 bg-dashboard-focus/10 text-dashboard-focus":"border-dashboard-border-emphasis text-dashboard-text-muted hover:bg-dashboard-fill-hover"),children:f.slice(0,3)},f))})]}):null,(0,He.jsxs)("div",{className:"grid grid-cols-1 items-start gap-4 sm:grid-cols-2",children:[(0,He.jsx)(Gt,{label:"Interval",htmlFor:"schedule-interval",help:"Number of calendar periods between runs.",children:(0,He.jsx)(Ta,{size:"comfortable",id:"schedule-interval",type:"number",min:1,max:365,value:t.interval??1,onChange:f=>e.onChange({...t,interval:f.target.valueAsNumber})})}),(0,He.jsx)(Gt,{label:"Start date",htmlFor:"schedule-start",children:(0,He.jsx)(Ta,{size:"comfortable",id:"schedule-start",type:"date",value:t.startDate??"",onChange:f=>e.onChange({...t,startDate:f.target.value||void 0})})})]}),t.frequency==="monthly"||t.frequency==="yearly"?(0,He.jsxs)("div",{className:"grid grid-cols-1 gap-4 sm:grid-cols-2",children:[(0,He.jsx)(Gt,{label:"Day of month",htmlFor:"schedule-day",children:(0,He.jsx)(Ta,{size:"comfortable",id:"schedule-day",type:"number",min:1,max:31,value:t.dayOfMonth??1,onChange:f=>e.onChange({...t,dayOfMonth:f.target.valueAsNumber})})}),t.frequency==="yearly"?(0,He.jsx)(Gt,{label:"Month",htmlFor:"schedule-month",children:(0,He.jsx)(mu,{id:"schedule-month",value:t.month??1,onChange:f=>e.onChange({...t,month:Number(f.target.value)}),children:Array.from({length:12},(f,m)=>(0,He.jsx)("option",{value:m+1,children:new Intl.DateTimeFormat("en",{month:"long",timeZone:"UTC"}).format(new Date(Date.UTC(2026,m,1)))},m))})}):null]}):null]}):(0,He.jsx)(Gt,{label:"Date",htmlFor:"schedule-date",children:(0,He.jsx)(Ta,{size:"comfortable",id:"schedule-date",type:"date",value:t.timing.date,onChange:f=>e.onChange({...t,timing:{type:"at",time:s,date:f.target.value}})})}),(0,He.jsxs)(Gt,{label:"Timezone",htmlFor:"schedule-timezone",help:"Use an IANA timezone. The schedule follows local time, including daylight saving time.",children:[(0,He.jsx)(Ta,{size:"comfortable",id:"schedule-timezone",list:"automation-timezones",value:t.timezone??"",onChange:f=>e.onChange({...t,timezone:f.target.value})}),(0,He.jsx)("datalist",{id:"automation-timezones",children:["UTC",...Intl.supportedValuesOf("timeZone")].map(f=>(0,He.jsx)("option",{children:f},f))})]}),(0,He.jsxs)("div",{role:"status",className:"flex gap-3 rounded-md bg-dashboard-fill-soft p-3 text-sm leading-relaxed",children:[(0,He.jsx)(ol,{"aria-hidden":!0,size:17,className:"mt-0.5 shrink-0 text-dashboard-text-muted"}),(0,He.jsx)("div",{children:c?"Checking schedule\u2026":d?(0,He.jsxs)(He.Fragment,{children:[(0,He.jsx)("span",{className:"text-rose-300",children:d}),o.error?(0,He.jsx)(oe,{onClick:()=>{o.refetch()},children:"Try again"}):null]}):u?(0,He.jsxs)(He.Fragment,{children:["Next run"," ",new Intl.DateTimeFormat(void 0,{year:"numeric",month:"short",day:"numeric",hour:"numeric",minute:"2-digit",timeZoneName:"short",timeZone:e.value?o.data?.schedule.timezone??"UTC":e.automation.schedule.timezone}).format(u)]}):"No next run."})]}),e.value?(0,He.jsx)(oe,{className:"w-fit",onClick:()=>e.onChange(void 0),children:"Keep saved schedule"}):null]})}var vt=b(w(),1);function IW(e){let t=_e({queryKey:["dashboard","automation-event-catalog"],queryFn:({signal:o})=>Se(OM,"/api/automations/event-catalog",o),retry:!1}),a=t.data?.find(o=>o.namespace===e.value.namespace&&o.type===e.value.resourceType),r=!a||e.value.events.some(o=>!a.supportedEvents.includes(o))||Object.entries(e.value.match??{}).some(([o,i])=>{let s=a.matchFields?.[o];return s?(Array.isArray(i)?i:[i]).some(u=>typeof u!==s.kind||s.enum&&!s.enum.includes(String(u))):!0}),n=(o,i)=>{let s={...e.value.match};i===void 0?delete s[o]:s[o]=i,e.onChange({...e.value,match:s})};return(0,vt.jsxs)(vt.Fragment,{children:[t.error?(0,vt.jsxs)(uo,{title:"Event choices could not be loaded.",children:["Saved values are kept."," ",(0,vt.jsx)(oe,{onClick:()=>{t.refetch()},children:"Try again"})]}):t.isPending?(0,vt.jsx)("p",{role:"status",children:"Loading event choices\u2026"}):null,r&&t.data?(0,vt.jsxs)(uo,{title:"Saved trigger \xB7 Kept unchanged",children:["Some saved values are not in the current catalog. You can edit other fields, or select a new resource type to replace the trigger.",(0,vt.jsx)("pre",{className:"whitespace-pre-wrap break-all text-xs",children:JSON.stringify(e.value,null,2)})]}):null,(0,vt.jsx)(Gt,{label:r?"Replace trigger":"Resource type",htmlFor:"trigger-resource",children:(0,vt.jsxs)(mu,{id:"trigger-resource",value:r?"":`${e.value.namespace}:${e.value.resourceType}`,onChange:o=>{let i=t.data?.find(s=>`${s.namespace}:${s.type}`===o.target.value);i&&window.confirm("Replace the saved trigger? Its resource, events, and conditions will be cleared.")&&e.onChange({namespace:i.namespace,resourceType:i.type,identifier:"",label:"",events:[]})},children:[(0,vt.jsx)("option",{value:"",disabled:!0,children:"Keep saved trigger"}),t.data?.map(o=>(0,vt.jsxs)("option",{value:`${o.namespace}:${o.type}`,children:[o.namespace," \xB7 ",o.type.replaceAll("_"," ")]},`${o.namespace}:${o.type}`))]})}),!r&&a?(0,vt.jsxs)(vt.Fragment,{children:[(0,vt.jsx)(Gt,{label:"Resource name",htmlFor:"trigger-label",children:(0,vt.jsx)(Ta,{size:"comfortable",id:"trigger-label",value:e.value.label,onChange:o=>e.onChange({...e.value,label:o.target.value})})}),(0,vt.jsx)(Gt,{label:"Resource identifier",htmlFor:"trigger-identifier",help:"Use the exact provider resource identifier, not its display name.",children:(0,vt.jsx)(Ta,{size:"comfortable",id:"trigger-identifier",value:e.value.identifier,onChange:o=>e.onChange({...e.value,identifier:o.target.value})})}),(0,vt.jsxs)("fieldset",{children:[(0,vt.jsx)("legend",{className:"mb-2 text-sm font-semibold",children:"Run on these events"}),(0,vt.jsx)("div",{className:"divide-y divide-dashboard-border-subtle rounded-md border border-dashboard-border-emphasis",children:a.supportedEvents.map(o=>(0,vt.jsxs)("label",{className:"flex min-h-11 cursor-pointer items-start gap-3 px-3 py-3 text-sm",children:[(0,vt.jsx)("input",{type:"checkbox",className:"mt-0.5 size-4 shrink-0 accent-dashboard-focus",checked:e.value.events.includes(o),onChange:()=>e.onChange({...e.value,events:e.value.events.includes(o)?e.value.events.filter(i=>i!==o):[...e.value.events,o]})}),(0,vt.jsxs)("span",{className:"min-w-0 break-words",children:[o.replaceAll("_"," ").replaceAll("."," \xB7 "),a.guidance?.[o]?(0,vt.jsx)("span",{className:"mt-1 block text-xs leading-relaxed text-dashboard-text-muted",children:a.guidance[o]}):null]})]},o))})]}),Object.keys(a.matchFields??{}).length?(0,vt.jsxs)("fieldset",{className:"grid gap-4",children:[(0,vt.jsx)("legend",{className:"mb-3 text-sm font-semibold",children:"Only when"}),(0,vt.jsx)("p",{className:"m-0 text-xs leading-relaxed text-dashboard-text-muted",children:"All conditions must match. Leave a field blank to match any value. Existing lists match any one listed value."}),Object.entries(a.matchFields??{}).map(([o,i])=>{let s=e.value.match?.[o];return(0,vt.jsx)(Gt,{label:o,htmlFor:`match-${o}`,help:i.description,children:Array.isArray(s)?(0,vt.jsxs)("div",{className:"text-sm",children:[(0,vt.jsx)("span",{className:"break-all",children:s.join(", ")})," ",(0,vt.jsx)(oe,{onClick:()=>n(o,void 0),children:"Remove condition"})]}):i.kind==="boolean"||i.enum?(0,vt.jsxs)(mu,{id:`match-${o}`,value:s===void 0?"":String(s),onChange:u=>n(o,u.target.value===""?void 0:i.kind==="boolean"?u.target.value==="true":u.target.value),children:[(0,vt.jsx)("option",{value:"",children:"Any value"}),(i.enum??["true","false"]).map(u=>(0,vt.jsx)("option",{children:u},u))]}):(0,vt.jsx)(Ta,{size:"comfortable",id:`match-${o}`,type:i.kind==="number"?"number":"text",step:"any",value:s===void 0?"":String(s),onChange:u=>n(o,u.target.value===""?void 0:i.kind==="number"?u.target.valueAsNumber:u.target.value)})},o)})]}):null]}):null,JSON.stringify(e.value)!==JSON.stringify(e.original)?(0,vt.jsx)(oe,{className:"w-fit",onClick:()=>e.onChange(e.original),children:"Keep saved trigger"}):null]})}function Xm(e,t){return typeof e.destination=="string"?e.destination==="task_creator"?"Creator \xB7 Direct message":`${t.label} \xB7 ${t.visibility}`:e.destination.channelId===t.channelId&&e.destination.teamId===t.teamId?`${t.label} \xB7 ${t.visibility}`:`Saved destination \xB7 ${e.destination.channelId}`}var ua=b(w(),1);function fI(e){return e.outcomes.length?(0,ua.jsx)("ol",{className:"m-0 grid gap-2 pl-5 text-sm",children:e.outcomes.map((t,a)=>(0,ua.jsx)("li",{children:Xm(t,e.destination)},a))}):(0,ua.jsx)("p",{className:"m-0 text-sm",children:"No success message"})}function LW(e){let t=e.original.length?e.original:[{action:"send_message",destination:"current_conversation"}],a=[...e.original.flatMap((r,n)=>typeof r.destination=="string"?[]:[{value:`saved:${n}`,label:Xm(r,e.destination),outcome:r}]),{value:"current_conversation",label:`${e.destination.label} \xB7 ${e.destination.visibility}`,outcome:{action:"send_message",destination:"current_conversation"}},{value:"task_creator",label:"Creator \xB7 Direct message",outcome:{action:"send_message",destination:"task_creator"}}];return(0,ua.jsxs)(ua.Fragment,{children:[(0,ua.jsxs)("fieldset",{children:[(0,ua.jsx)("legend",{className:"sr-only",children:"Success messages"}),(0,ua.jsx)("div",{className:"flex flex-wrap gap-x-6 gap-y-3",children:[!0,!1].map(r=>(0,ua.jsxs)("label",{className:"inline-flex min-h-8 cursor-pointer items-center gap-2 text-sm",children:[(0,ua.jsx)("input",{type:"radio",name:"messages",className:"size-4 accent-dashboard-focus",checked:!!e.value.length===r,onChange:()=>e.onChange(r?t:[])}),r?"Send a message":"No success message"]},String(r)))})]}),e.value.length?(0,ua.jsxs)("div",{className:"grid gap-4 sm:gap-2",children:[e.value.map((r,n)=>{let o=e.original.findIndex(i=>JSON.stringify(i)===JSON.stringify(r));return(0,ua.jsxs)("div",{className:"flex min-w-0 flex-wrap items-center gap-2",children:[(0,ua.jsxs)("span",{className:"w-4 text-xs text-dashboard-text-muted",children:[n+1,"."]}),(0,ua.jsx)("div",{className:L("min-w-0 flex-1",e.value.length>1&&"order-last basis-full sm:order-none sm:basis-auto"),children:(0,ua.jsx)(mu,{"aria-label":`Message ${n+1} destination`,value:typeof r.destination=="string"?r.destination:`saved:${o}`,onChange:i=>{let s=a.find(u=>u.value===i.target.value);s&&e.onChange(e.value.map((u,c)=>c===n?s.outcome:u))},children:a.map(i=>(0,ua.jsx)("option",{value:i.value,children:i.label},i.value))})}),e.value.length>1?(0,ua.jsxs)(ua.Fragment,{children:[(0,ua.jsx)(oe,{size:"icon",className:"ml-auto sm:ml-0","aria-label":`Move message ${n+1} up`,disabled:n===0,onClick:()=>{let i=[...e.value];[i[n-1],i[n]]=[i[n],i[n-1]],e.onChange(i)},children:(0,ua.jsx)(mb,{size:16})}),(0,ua.jsx)(oe,{size:"icon","aria-label":`Remove message ${n+1}`,onClick:()=>e.onChange(e.value.filter((i,s)=>s!==n)),children:(0,ua.jsx)(Kn,{size:16})})]}):null]},n)}),e.value.length<5?(0,ua.jsxs)(oe,{className:"w-fit",onClick:()=>e.onChange([...e.value,{action:"send_message",destination:"task_creator"}]),children:[(0,ua.jsx)(fc,{size:15}),"Add message"]}):null]}):(0,ua.jsx)("p",{className:"m-0 text-sm leading-relaxed text-dashboard-text-muted",children:"Junior still does the work. No message is sent after success."}),(0,ua.jsxs)("p",{className:"m-0 text-xs leading-relaxed text-dashboard-text-muted",children:[e.value.length?"Messages are sent in this order. ":"","This does not limit actions in the instruction."]})]})}var ce=b(w(),1);function _W(e){let[t,a]=(0,Ps.useState)(e.automation),[r,n]=(0,Ps.useState)(()=>uI(e.automation)),[o,i]=(0,Ps.useState)({}),[s,u]=(0,Ps.useState)(),c=(0,Ps.useRef)(null),d=(0,Ps.useRef)(!1),f=Sn(),m=Ut(),h=CW(t,r),p=Object.keys(h).length>0,v={kind:t.kind,revision:t.revision,...h},x=RA(()=>p&&!d.current),g=(0,Ps.useRef)(null);(0,Ps.useEffect)(()=>{x.state==="blocked"&&g.current?.focus()},[x.state]);let y=`/api/automations/${encodeURIComponent(t.id)}`;(0,Ps.useEffect)(()=>{let G=fe=>{p&&!d.current&&(fe.preventDefault(),fe.returnValue="")};return window.addEventListener("beforeunload",G),()=>window.removeEventListener("beforeunload",G)},[p]);let S=()=>requestAnimationFrame(()=>(c.current?.querySelector('[aria-invalid="true"]')??c.current?.querySelector("[data-save-error]"))?.focus()),C=Xt({mutationFn:()=>Bg(Ns,y,v),onSuccess:async()=>{d.current=!0,await m.invalidateQueries({queryKey:["dashboard","automations"]}),f(e.returnPath,{state:{automationSaved:!0}})},onError:G=>{i(G instanceof Cn?G.fields??{}:{}),S()}});function I(G){s&&(n(G?{...uI(s),...h}:uI(s)),a(s),u(void 0),C.reset(),i({}))}let T=Xt({mutationFn:()=>Se(Ns,`${y}/edit`),onSuccess:u}),N=C.error instanceof Cn&&C.error.code==="conflict",k=G=>n(fe=>({...fe,...G})),U=G=>Object.entries(o).filter(([fe])=>fe===G||fe.startsWith(`${G}.`)).flatMap(([,fe])=>fe).join(" ")||void 0,B=t.kind==="scheduled"?"schedule":"trigger",le=t.ownedByViewer,z=e.summary.createdBy,J=!le&&t.credentialMode==="creator"&&(h.instruction!==void 0||t.kind==="event"&&h.trigger!==void 0),ee=U(B),ve=G=>({"aria-invalid":!!U(G)||void 0,"aria-describedby":U(G)?`${G}-error`:void 0});return(0,ce.jsxs)("form",{ref:c,noValidate:!0,onSubmit:G=>{if(G.preventDefault(),C.isPending||N||!p)return;let fe=MM.safeParse(v);if(!fe.success){let X={};for(let ue of fe.error.issues)(X[ue.path.join(".")]??=[]).push(ue.message);i(X),S();return}i({}),C.mutate()},children:[x.state==="blocked"?(0,ce.jsx)("div",{tabIndex:-1,ref:g,className:"mb-6 outline-none",children:(0,ce.jsxs)(uo,{title:"Discard unsaved changes?",children:[(0,ce.jsx)("p",{children:"Your changes have not been saved."}),(0,ce.jsxs)("div",{className:"flex gap-2",children:[(0,ce.jsx)(oe,{onClick:()=>x.reset(),children:"Keep editing"}),(0,ce.jsx)(oe,{onClick:()=>x.proceed(),children:"Discard changes"})]})]})}):null,C.error||Object.keys(o).length?(0,ce.jsx)("div",{tabIndex:-1,"data-save-error":!0,className:"mb-6 outline-none",children:(0,ce.jsxs)(uo,{tone:N?"warning":"error",title:N?"This automation changed while you were editing.":"Changes could not be saved.",children:[(0,ce.jsxs)("p",{className:"mt-1",children:["Your edits are still here."," ",N?"Review the latest version before saving again.":C.error instanceof Cn?C.error.apiError:"Check the fields below, or try again."]}),N?(0,ce.jsx)(oe,{disabled:T.isPending,onClick:()=>T.mutate(),children:T.isPending?"Loading\u2026":"Review latest version"}):null,T.error?(0,ce.jsx)("p",{role:"alert",children:"The latest version could not be loaded. Try again."}):null]})}):null,s?(0,ce.jsx)("div",{className:"mb-6",children:(0,ce.jsxs)(uo,{title:"Compare your edits with the latest saved version",children:[(0,ce.jsx)("p",{children:"Only the fields you changed are shown. Keeping your edits will replace these fields. Other saved fields stay unchanged."}),Object.entries(h).map(([G,fe])=>(0,ce.jsxs)("section",{className:"my-4",children:[(0,ce.jsx)("h3",{className:"text-sm font-semibold capitalize",children:G==="credentialMode"?"Credentials":G}),(0,ce.jsxs)("div",{className:"grid gap-3 sm:grid-cols-2",children:[(0,ce.jsxs)("div",{children:[(0,ce.jsx)("p",{children:"Latest saved"}),(0,ce.jsx)("pre",{className:"whitespace-pre-wrap break-words font-sans text-sm",children:TW(G==="schedule"&&s.kind==="scheduled"?cI(s):s[G])})]}),(0,ce.jsxs)("div",{children:[(0,ce.jsx)("p",{children:"Your edit"}),(0,ce.jsx)("pre",{className:"whitespace-pre-wrap break-words font-sans text-sm",children:TW(fe)})]})]})]},G)),(0,ce.jsxs)("div",{className:"flex flex-wrap gap-2",children:[(0,ce.jsx)(oe,{onClick:()=>I(!0),children:"Keep my changed fields"}),(0,ce.jsx)(oe,{onClick:()=>I(!1),children:"Use latest saved version"})]})]})}):null,le?null:(0,ce.jsxs)("p",{className:"mt-0 mb-6 max-w-2xl text-sm leading-relaxed text-dashboard-text-muted",children:[z," created this automation. You can edit it because it is in a public channel. Only ",z," can change where results go or turn on their connected accounts. Version history keeps every saved change."]}),(0,ce.jsxs)("fieldset",{disabled:C.isPending,className:"min-w-0",children:[(0,ce.jsxs)($s,{title:"What to do",detail:"Give Junior a clear instruction and a name you can find later.",children:[(0,ce.jsx)(Gt,{label:"Title",htmlFor:"title",error:U("title"),children:(0,ce.jsx)(Ta,{size:"comfortable",id:"title",value:r.title,placeholder:e.summary.title,onChange:G=>k({title:G.target.value}),...ve("title")})}),(0,ce.jsxs)(Gt,{label:"Instruction",htmlFor:"instruction",error:U("instruction"),children:[(0,ce.jsx)(bc,{prose:!0,id:"instruction",rows:8,value:r.instruction,onChange:G=>k({instruction:G.target.value}),...ve("instruction"),className:"resize-y text-base sm:text-sm"}),(0,ce.jsxs)("p",{className:"m-0 text-right text-xs text-dashboard-text-muted",children:[r.instruction.length.toLocaleString()," / 4,000"]})]})]}),(0,ce.jsx)($s,{title:"When to run",detail:t.kind==="scheduled"?"Choose a schedule in a specific timezone.":"Run when a matching event occurs.",children:(0,ce.jsxs)("div",{id:`${B}-error`,tabIndex:-1,"aria-invalid":!!ee||void 0,className:"grid min-w-0 gap-5 outline-none",children:[ee?(0,ce.jsx)("p",{role:"alert",className:"m-0 text-sm text-rose-300",children:ee}):null,t.kind==="scheduled"?(0,ce.jsx)(kW,{automation:t,value:r.schedule,onChange:G=>k({schedule:G})}):(0,ce.jsx)(IW,{value:r.trigger??t.trigger,original:t.trigger,onChange:G=>k({trigger:G})})]})}),(0,ce.jsxs)($s,{title:"Where results go",detail:"Choose who gets a message after successful work.",children:[U("outcomes")?(0,ce.jsx)("p",{role:"alert",className:"m-0 text-sm text-rose-300",children:U("outcomes")}):null,le?(0,ce.jsx)(LW,{value:r.outcomes,original:t.outcomes,destination:e.summary.destination,onChange:G=>k({outcomes:G})}):(0,ce.jsxs)(ce.Fragment,{children:[(0,ce.jsx)(fI,{outcomes:t.outcomes,destination:e.summary.destination}),(0,ce.jsxs)("p",{className:"m-0 text-xs text-dashboard-text-muted",children:["Only ",z," can change where results go."]})]})]}),(0,ce.jsxs)($s,{title:"Credentials",detail:"Choose which connected accounts Junior can use.",children:[(0,ce.jsxs)("fieldset",{className:"divide-y divide-dashboard-border-subtle rounded-md border border-dashboard-border-emphasis",children:[(0,ce.jsx)("legend",{className:"sr-only",children:"Credential mode"}),[["creator",le?"Your connected accounts":`${z}\u2019s connected accounts`,le?"Uses accounts connected by you, the creator.":`Uses accounts connected by ${z}. Only ${z} can turn this on.`],["system","System credentials only",le?"Does not use your connected accounts. Some work may not be possible.":"Does not use anyone\u2019s connected accounts. Some work may not be possible."]].map(([G,fe,X])=>(0,ce.jsxs)("label",{className:"flex cursor-pointer items-start gap-3 px-4 py-4 has-checked:bg-dashboard-fill-soft has-disabled:cursor-not-allowed has-disabled:opacity-60",children:[(0,ce.jsx)("input",{type:"radio",name:"credentials",className:"mt-0.5 size-4 shrink-0 accent-dashboard-focus",checked:J?G==="system":r.credentialMode===G,disabled:G==="creator"&&!le&&(t.credentialMode!=="creator"||J),onChange:()=>k({credentialMode:G})}),(0,ce.jsxs)("span",{children:[(0,ce.jsx)("span",{className:"block text-sm font-medium",children:fe}),(0,ce.jsx)("span",{className:"mt-1 block text-xs leading-relaxed text-dashboard-text-muted",children:X})]})]},G))]}),J?(0,ce.jsxs)(uo,{title:"Saving switches this automation to system credentials.",children:["Only ",z," can let a changed instruction",t.kind==="event"?" or trigger":""," use their connected accounts."]}):null,U("credentialMode")?(0,ce.jsx)("p",{role:"alert",children:U("credentialMode")}):null]})]}),(0,ce.jsx)("p",{className:"mb-5 text-xs leading-relaxed text-dashboard-text-muted sm:hidden",children:"Changes apply to future work. Saving does not run this automation."}),(0,ce.jsx)("div",{className:"sticky bottom-0 z-20 -mx-4 border-t border-dashboard-border-emphasis bg-dashboard-bg px-4 py-4 sm:-mx-8 sm:px-8",children:(0,ce.jsxs)("div",{className:"flex items-center justify-between gap-3",children:[(0,ce.jsxs)("div",{className:"min-w-0 flex-1",role:"status",children:[(0,ce.jsx)("p",{className:"m-0 text-xs font-medium sm:text-sm",children:C.isPending?"Saving\u2026":p?"Unsaved changes":"Unchanged"}),(0,ce.jsx)("p",{className:"mt-1 mb-0 hidden text-xs text-dashboard-text-muted sm:block",children:"Changes apply to future work. Saving does not run it."})]}),(0,ce.jsxs)("div",{className:"flex shrink-0 gap-2",children:[(0,ce.jsx)(te,{to:e.returnPath,className:"inline-flex min-h-11 items-center rounded-md border border-dashboard-border-emphasis px-3 text-sm text-dashboard-text no-underline sm:min-h-9",children:"Cancel"}),(0,ce.jsx)(oe,{type:"submit",tone:"primary",className:"min-h-11 sm:min-h-9",disabled:!p||C.isPending||N,children:"Save changes"})]})]})})]})}function TW(e){return e==null?"Not set":typeof e=="string"?e:JSON.stringify(e,null,2)}var Jg=b(w(),1);function NW(){return(0,Jg.jsx)("div",{role:"status","aria-label":"Loading automation editor",children:["What to do","When to run","Where results go","Credentials"].map((e,t)=>(0,Jg.jsxs)($s,{title:e,children:[(0,Jg.jsx)(et,{className:"h-4 w-24"}),(0,Jg.jsx)(et,{className:t===0?"h-48 w-full":"h-20 w-full"})]},e))})}var Vt=b(w(),1);function RW(e){let{automationId:t}=Ja(),a=xt(),r=Hg(e.enabled,t),n=r.data&&!(r.data.kind==="scheduled"&&r.data.status==="completed"),o=_e({queryKey:["dashboard","automations","edit",t],enabled:e.enabled&&!!n,retry:!1,queryFn:({signal:d})=>Se(Ns,`/api/automations/${encodeURIComponent(t)}/edit`,d)}),i=`/automations/list${a.search}`,s=r.data;Si(s?n?`${s.title} \xB7 Edit`:s.title:"Edit automation");let u=s?.kind==="event"?s.status!=="active"?s.status:s.triggerAvailable?"active":"unavailable":s?.status,c=u==="active"?"success":u==="blocked"||u==="unavailable"?"warning":"neutral";return(0,Vt.jsx)(b4,{children:(0,Vt.jsxs)("div",{className:"mx-auto w-full min-w-0 max-w-5xl px-4 pt-7 sm:px-8 sm:pt-9",children:[(0,Vt.jsxs)(te,{to:i,className:"inline-flex min-h-8 items-center gap-2 text-sm text-dashboard-text-muted no-underline hover:text-dashboard-text",children:[(0,Vt.jsx)(ao,{"aria-hidden":!0,size:15}),"All automations"]}),(0,Vt.jsxs)("div",{className:"mt-4 mb-8 flex flex-wrap items-start justify-between gap-4",children:[(0,Vt.jsxs)("div",{className:"min-w-0",children:[(0,Vt.jsx)("h1",{className:"m-0 break-words font-display text-3xl font-light tracking-tight",children:s&&!n?s.title:"Edit automation"}),s?(0,Vt.jsxs)("p",{className:"mt-2 mb-0 text-sm text-dashboard-text-muted",children:["Created by ",s.ownedByViewer?"you":s.createdBy," \xB7"," ",s.destination.label]}):null]}),s?(0,Vt.jsxs)("div",{className:"flex items-center gap-4",children:[(0,Vt.jsx)(te,{to:`/automations/${encodeURIComponent(s.id)}/versions${a.search}`,className:"text-sm text-dashboard-text-muted underline underline-offset-2 hover:text-dashboard-text",children:"Version history"}),(0,Vt.jsx)(Zt,{tone:c,children:u==="unavailable"?"Trigger unavailable":u})]}):null]}),!s&&r.error||!o.data&&o.error?(0,Vt.jsxs)(uo,{tone:"error",title:"Automation could not be loaded.",children:["It may no longer be available, or you may not have access."," ",(0,Vt.jsx)(oe,{onClick:()=>{r.refetch(),n&&o.refetch()},children:"Try again"})]}):!s||n&&!o.data?(0,Vt.jsx)(NW,{}):n&&o.data?(0,Vt.jsx)(_W,{automation:o.data,summary:s,returnPath:i},t):(0,Vt.jsx)(SSe,{automation:s})]})})}function SSe({automation:e}){return(0,Vt.jsxs)(Vt.Fragment,{children:[(0,Vt.jsx)("p",{className:"mb-6 text-sm text-dashboard-text-muted",children:"This automation has completed and cannot be edited. It will not run again."}),(0,Vt.jsx)($s,{title:"What to do",detail:"The saved instruction.",children:(0,Vt.jsx)("p",{className:"m-0 whitespace-pre-wrap break-words text-sm leading-relaxed",children:e.instruction})}),(0,Vt.jsx)($s,{title:"When to run",detail:"The saved trigger.",children:e.kind==="scheduled"?(0,Vt.jsxs)("p",{className:"m-0 text-sm",children:[e.schedule," \xB7 ",e.timezone]}):(0,Vt.jsxs)("div",{className:"grid gap-3 text-sm",children:[(0,Vt.jsx)("p",{className:"m-0 break-words",children:e.resource}),(0,Vt.jsx)("p",{className:"m-0 break-words",children:e.events.join(", ")}),e.match?(0,Vt.jsx)("pre",{className:"whitespace-pre-wrap break-words text-xs",children:JSON.stringify(e.match,null,2)}):null]})}),(0,Vt.jsx)($s,{title:"Where results go",detail:"Messages after successful work.",children:(0,Vt.jsx)(fI,{outcomes:e.outcomes,destination:e.destination})}),(0,Vt.jsx)($s,{title:"Credentials",detail:"The accounts Junior can use.",children:(0,Vt.jsx)("p",{className:"m-0 text-sm",children:e.credentialMode==="creator"?`Uses ${e.ownedByViewer?"your":`${e.createdBy}\u2019s`} connected accounts.`:"System credentials only."})})]})}var Pp=b(V(),1);var AW=b(V(),1);function mI(){return(0,AW.useSyncExternalStore)(e=>jl.subscribe(e),()=>jl.isOnline(),()=>!0)}var PW=b(w(),1);function $W(){return mI()?null:(0,PW.jsx)("div",{"aria-live":"polite",className:"border-t border-amber-300/15 bg-amber-300/[0.07] px-3 py-1.5 text-center font-sans text-xs text-amber-100/80",role:"status",children:"You\u2019re offline. Drafts stay on this device."})}var S4=b(w(),1);function pI(){return(0,S4.jsx)("div",{className:"relative grid size-10 shrink-0 select-none place-items-center overflow-visible",children:(0,S4.jsx)("img",{alt:"",className:"relative size-11 max-w-none -translate-y-0.5 object-contain opacity-90 drop-shadow-[0_0_7px_rgba(255,255,255,0.16)]",draggable:!1,src:"/_junior/dashboard/avatar.png"})})}var DW=["relative","overflow-hidden","bg-white/15","before:absolute","before:inset-0","before:content-['']","before:bg-[linear-gradient(90deg,#ff4d6d,#ffb703,#56f39a,#4cc9f0,#9b5de5,#ff4d6d)]","before:bg-[length:200%_100%]","before:animate-[junior-rainbow-flow_1.2s_linear_infinite]","motion-reduce:before:animate-none"].join(" ");var Qd=b(w(),1);function En(e){return(0,Qd.jsx)("div",{className:L(Ba,"grid min-h-[calc(100dvh-5rem)] place-items-center px-4 py-8 md:px-8"),children:(0,Qd.jsxs)("section",{className:"grid w-full max-w-lg grid-cols-[auto_minmax(0,1fr)] items-center gap-3 rounded-lg border border-dashboard-border-emphasis bg-dashboard-surface-raised p-4",children:[(0,Qd.jsx)(pI,{}),(0,Qd.jsxs)("div",{children:[(0,Qd.jsx)("div",{className:"font-bold",children:e.label}),(0,Qd.jsx)("div",{"aria-label":e.label,className:`${DW} mt-3 h-1.5 w-full`,role:"progressbar"})]})]})})}var w4="0.255.0",hI=typeof w4=="string"&&w4.trim()?w4:"unknown";var tS=b(w(),1);function EW(e){return wSe(e.serverVersion)?(0,tS.jsxs)("div",{"aria-live":"polite",className:"flex flex-wrap items-center justify-center gap-x-3 gap-y-1 border-t border-dashboard-accent/15 bg-dashboard-accent/[0.07] px-3 py-1.5 text-center font-sans text-xs text-dashboard-accent-text/80",role:"status",children:[(0,tS.jsx)("span",{children:"The dashboard changed. Refresh to load the latest version."}),(0,tS.jsx)("button",{className:"cursor-pointer border-0 bg-transparent p-0 font-sans font-semibold text-dashboard-accent-text underline decoration-dashboard-accent/40 underline-offset-2 hover:text-dashboard-text-solid",onClick:()=>window.location.reload(),type:"button",children:"Refresh"})]}):null}function wSe(e){return!!e&&hI!=="unknown"&&e!=="unknown"&&e!==hI}var aS=b(w(),1);function pu(e){return(0,aS.jsxs)(Eo,{children:[(0,aS.jsx)(We,{description:e.description,title:e.title}),(0,aS.jsx)(sr,{label:e.label,variant:e.variant})]})}var ku=b(V(),1);var gI={"angular-html":()=>import("./chunks/angular-html-ZNDXTZDN.js"),"angular-ts":()=>import("./chunks/angular-ts-ON3WFVNV.js"),astro:()=>import("./chunks/astro-TCFNN3TA.js"),blade:()=>import("./chunks/blade-XRKVUGGE.js"),c:()=>import("./chunks/c-WHCDUHJR.js"),coffee:()=>import("./chunks/coffee-NWMA7ZVV.js"),coffeescript:()=>import("./chunks/coffee-NWMA7ZVV.js"),cpp:()=>import("./chunks/cpp-7ZDYJCCI.js"),"c++":()=>import("./chunks/cpp-7ZDYJCCI.js"),css:()=>import("./chunks/css-XF3SDJYW.js"),csv:()=>import("./chunks/csv-I2Y5BPVG.js"),glsl:()=>import("./chunks/glsl-SDKJ4MVB.js"),graphql:()=>import("./chunks/graphql-XJBKAS4G.js"),gql:()=>import("./chunks/graphql-XJBKAS4G.js"),haml:()=>import("./chunks/haml-QQIA6ZDV.js"),handlebars:()=>import("./chunks/handlebars-A4STSCQ6.js"),hbs:()=>import("./chunks/handlebars-A4STSCQ6.js"),html:()=>import("./chunks/html-T3MIDC6T.js"),"html-derivative":()=>import("./chunks/html-derivative-A5ABNIZH.js"),http:()=>import("./chunks/http-VGZ3EXS5.js"),hurl:()=>import("./chunks/hurl-TO4NQQLI.js"),imba:()=>import("./chunks/imba-P3ARIZRP.js"),java:()=>import("./chunks/java-WCBM5OUU.js"),javascript:()=>import("./chunks/javascript-TQH7GGAM.js"),js:()=>import("./chunks/javascript-TQH7GGAM.js"),cjs:()=>import("./chunks/javascript-TQH7GGAM.js"),mjs:()=>import("./chunks/javascript-TQH7GGAM.js"),jinja:()=>import("./chunks/jinja-UYMB4X6S.js"),jison:()=>import("./chunks/jison-ED4UFXGK.js"),json:()=>import("./chunks/json-XRHV7G5W.js"),json5:()=>import("./chunks/json5-2OA2ZMVI.js"),jsonc:()=>import("./chunks/jsonc-KO53QF6Y.js"),jsonl:()=>import("./chunks/jsonl-GHTNFMM6.js"),jsx:()=>import("./chunks/jsx-V5TSP3NI.js"),julia:()=>import("./chunks/julia-EI7BACOV.js"),jl:()=>import("./chunks/julia-EI7BACOV.js"),less:()=>import("./chunks/less-FPWZXUDW.js"),markdown:()=>import("./chunks/markdown-QWIM2DOI.js"),md:()=>import("./chunks/markdown-QWIM2DOI.js"),marko:()=>import("./chunks/marko-3POAQSZY.js"),mdc:()=>import("./chunks/mdc-KT6TTBUF.js"),mdx:()=>import("./chunks/mdx-CWS3UMSH.js"),php:()=>import("./chunks/php-3CK4FBZI.js"),postcss:()=>import("./chunks/postcss-7K34RN34.js"),pug:()=>import("./chunks/pug-IEW5PJRA.js"),jade:()=>import("./chunks/pug-IEW5PJRA.js"),python:()=>import("./chunks/python-GCPXLELR.js"),py:()=>import("./chunks/python-GCPXLELR.js"),r:()=>import("./chunks/r-XV5O7BSV.js"),regexp:()=>import("./chunks/regexp-655IUQFI.js"),regex:()=>import("./chunks/regexp-655IUQFI.js"),sass:()=>import("./chunks/sass-MSBN6O54.js"),scss:()=>import("./chunks/scss-N73GNFL4.js"),shellscript:()=>import("./chunks/shellscript-OPDT4ZZ3.js"),bash:()=>import("./chunks/shellscript-OPDT4ZZ3.js"),sh:()=>import("./chunks/shellscript-OPDT4ZZ3.js"),shell:()=>import("./chunks/shellscript-OPDT4ZZ3.js"),zsh:()=>import("./chunks/shellscript-OPDT4ZZ3.js"),sql:()=>import("./chunks/sql-ZR72I7RP.js"),stylus:()=>import("./chunks/stylus-NVEQWGLA.js"),styl:()=>import("./chunks/stylus-NVEQWGLA.js"),svelte:()=>import("./chunks/svelte-ZZAXFLSI.js"),"ts-tags":()=>import("./chunks/ts-tags-MCSPJMMM.js"),lit:()=>import("./chunks/ts-tags-MCSPJMMM.js"),tsx:()=>import("./chunks/tsx-ZTNB67YL.js"),typescript:()=>import("./chunks/typescript-HV6B525T.js"),ts:()=>import("./chunks/typescript-HV6B525T.js"),cts:()=>import("./chunks/typescript-HV6B525T.js"),mts:()=>import("./chunks/typescript-HV6B525T.js"),vue:()=>import("./chunks/vue-WXFFFGZ3.js"),"vue-html":()=>import("./chunks/vue-html-SKWAUQDE.js"),"vue-vine":()=>import("./chunks/vue-vine-V3A5HTCZ.js"),wasm:()=>import("./chunks/wasm-JWJ5BADC.js"),wgsl:()=>import("./chunks/wgsl-ZCQ7MKDM.js"),wit:()=>import("./chunks/wit-MLLAONFF.js"),xml:()=>import("./chunks/xml-VST5CLIL.js"),yaml:()=>import("./chunks/yaml-BX3BWN2A.js"),yml:()=>import("./chunks/yaml-BX3BWN2A.js")};var vI=b(w(),1);function fo(e){if(typeof e!="number"||!Number.isFinite(e))return"";let t=Math.max(0,Math.floor(e));if(t<1e3)return`${t}ms`;if(t<6e4){let n=t/1e3;return`${n.toFixed(n<10?1:0)}s`}let a=[],r=[["mo",2592e6],["d",864e5],["h",36e5],["m",6e4],["s",1e3]];for(let[n,o]of r){let i=Math.floor(t/o);if(i!==0){if(a.push(`${i}${n}`),a.length===2)break;t%=o}}return a.join(" ")}function xc(e){return(0,vI.jsx)(vI.Fragment,{children:fo(e.value)||e.fallback||null})}function Qg(e){return Date.parse(e.createdAt)}function Xd(e,t,a){return{parts:a,role:t,sourceSeq:e.seq,timestamp:Qg(e)}}function CSe(e){let t=new Set;for(let a of e){let r=a.data;r.type==="handoff"&&r.triggeringToolCallId&&t.add(r.triggeringToolCallId),r.type==="subagent"&&r.parentToolCallId&&t.add(r.parentToolCallId)}return t}function kSe(e){let t=new Set;for(let a of e)a.messageId&&t.add(a.messageId);return t}function ISe(e,t){return{delivery:e.delivery,messageId:e.messageId,parts:e.redacted?[{type:"text",redacted:!0}]:[{type:"text",text:e.text??""}],...e.attachments?{attachments:e.attachments}:void 0,pending:!0,role:"user",source:e.source,sourceSeq:Number.MAX_SAFE_INTEGER-1e6+t,timestamp:Date.parse(e.createdAt),...e.actorIdentity?{actorIdentity:e.actorIdentity}:void 0}}function LSe(e,t){if(!t?.length)return e;let a=TSe(e,t);return a.length===0?e:[...e,...a]}function TSe(e,t){if(!t?.length)return[];let a=kSe(e);return t.filter(r=>!a.has(r.messageId)).map((r,n)=>ISe(r,n))}function C4(e,t){return k4(e.events,e.annotations,t)}function k4(e,t,a){let r=CSe(e),n=new Map,o=new Map,i=new Map,s=[],u=new Map,c=new Map,d,f=(h,p)=>{if(r.has(p.toolCallId))return;let v="output"in p?p.output:void 0,x=n.get(p.toolCallId);if(x){x.name=p.name,x.status=p.status,p.input!==void 0&&(x.input=p.input),v!==void 0&&(x.output=v),x.startedTimestamp===void 0&&p.startedAt&&(x.startedTimestamp=Date.parse(p.startedAt)),p.status!=="running"&&(x.resultTimestamp=Qg(h));return}let g={type:"tool_call",id:p.toolCallId,name:p.name,status:p.status,...p.input===void 0?void 0:{input:p.input},...v===void 0?void 0:{output:v},...p.status==="running"?void 0:{resultTimestamp:Qg(h)}},y={...Xd(h,"tool",[g]),sourceSeq:p.startedSeq??h.seq,timestamp:p.startedAt?Date.parse(p.startedAt):Qg(h)};n.set(p.toolCallId,g),o.set(p.toolCallId,y),s.push(y)};for(let h of e){let p=h.data;if(p.type==="message"){let v={...Xd(h,p.role,[p.redacted?{type:"text",redacted:!0}:{type:"text",text:p.text}]),messageId:p.messageId,...p.attachments?{attachments:p.attachments}:void 0,...p.cards?{cards:gM(p.cards,t??[])}:void 0,...p.actorIdentity?{actorIdentity:p.actorIdentity}:void 0,...p.eventType?{eventType:p.eventType}:void 0,eventObjectType:p.eventObjectType,...p.trustedSummary?{trustedSummary:p.trustedSummary}:void 0,...p.explicitMention!==void 0?{explicitMention:p.explicitMention}:void 0,...p.source?{source:p.source}:void 0};s.push(v),u.set(v.messageId,v),v.role==="user"&&(d=v);continue}if(p.type==="message_handled"){let v=u.get(p.messageId);v?.role==="user"&&v.explicitMention===!1&&!v.eventType&&(v.context=!0);continue}if(p.type==="assistant_message"){if(p.parts.length===0)continue;s.push(Xd(h,"assistant",p.parts.map(v=>v.redacted?{type:"reasoning",redacted:!0}:{type:"reasoning",text:v.text})));continue}if(p.type==="turn_lifecycle"&&p.state==="started"){let v=p.inputMessageIds?.map(g=>u.get(g)).filter(g=>g!==void 0),x=v?.slice().reverse().find(g=>g.role==="user");x?c.set(p.turnId,x):d&&c.set(p.turnId,d);for(let g of v??[])g.role==="user"&&g.explicitMention===!1&&!g.eventType&&(g.context=!0);continue}if(p.type==="turn_routed"){let v=c.get(p.turnId);v&&(v.route={modelProfile:p.modelProfile,modelId:p.modelId,reasoningLevel:p.reasoningLevel,...p.confidence!==void 0?{confidence:p.confidence}:void 0,source:p.source});continue}if(p.type==="turn_context"){let v=c.get(p.turnId);v&&(v.contexts??=[],v.contexts.push({content:p.content,kind:p.kind,loadedAt:h.createdAt,pluginName:p.pluginName,version:p.version}));continue}if(p.type==="tool_calls"){for(let v of p.calls)f(h,v);if(p.assistant){let v=[];for(let x of p.assistant.parts){if(x.type==="reasoning"){v.push(x.redacted?{type:"reasoning",redacted:!0}:{type:"reasoning",text:x.text});continue}if(r.has(x.toolCallId))continue;let g=n.get(x.toolCallId);if(!g)continue;let y=o.get(x.toolCallId);if(y){y.sourceSeq!==h.seq&&(g.startedTimestamp=y.timestamp);let S=s.indexOf(y);S>=0&&s.splice(S,1),o.delete(x.toolCallId)}v.push(g)}v.length>0&&s.push(Xd(h,"assistant",v))}continue}if(p.type==="subagent"){let v=`${p.childConversationId}:${p.startedSeq}`,x=i.get(v),g=p.status==="running"?void 0:Qg(h);if(x){x.status=p.status,g===void 0?delete x.finishedTimestamp:x.finishedTimestamp=g;continue}let y={type:"subagent",id:v,childConversationId:p.childConversationId,subagentKind:p.subagentKind,status:p.status,...g===void 0?void 0:{finishedTimestamp:g},...p.agentName?{agentName:p.agentName}:void 0,...p.task?{task:p.task}:void 0,...p.title?{title:p.title}:void 0};i.set(v,y),s.push({...Xd(h,"tool",[y]),sourceSeq:p.startedSeq,timestamp:Date.parse(p.startedAt)});continue}if(p.type==="structured_event"){s.push(Xd(h,"system",[{type:"structured_event",namespace:p.namespace,name:p.name,version:p.version,presentation:p.presentation}]));continue}if(p.type==="attachments_delivered"){s.push(Xd(h,"system",[{type:"attachments_delivered",attachments:p.attachments}]));continue}if(p.type==="compaction"||p.type==="handoff"){s.push(Xd(h,"system",[{type:"context_event",event:p.type==="handoff"?{type:p.type,createdAt:h.createdAt,modelId:p.modelId,modelProfile:p.modelProfile,...p.summary?{summary:p.summary}:void 0,...p.reasoningLevel?{reasoningLevel:p.reasoningLevel}:void 0}:{type:p.type,createdAt:h.createdAt,...p.modelId?{modelId:p.modelId}:void 0,...p.modelProfile?{modelProfile:p.modelProfile}:void 0,...p.summary?{summary:p.summary}:void 0,...p.details?{details:p.details}:void 0}}]));continue}if(p.type==="turn_lifecycle"&&p.state==="failed"){s.push({role:p.failureCode==="delivery_failed"?"system":"assistant",failureCode:p.failureCode,...p.failureReason?{failureReason:p.failureReason}:void 0,...p.eventId?{eventId:p.eventId}:void 0,...p.sentryEventUrl?{sentryEventUrl:p.sentryEventUrl}:void 0,parts:[],sourceSeq:h.seq,timestamp:Qg(h)});continue}}let m=s.filter(h=>h.role!=="user"||h.eventType!==void 0||h.explicitMention!==!1||h.context===!0).sort((h,p)=>h.sourceSeq-p.sourceSeq);return LSe(m,a)}function MW(){try{return Intl.DateTimeFormat().resolvedOptions().timeZone}catch{return"UTC"}}var L4=MW();function OW(e){L4=e||MW()}function ef(){return L4}function bI(){return L4}function _Se(e){return e.status==="active"}function NSe(e){return e.status==="failed"}function RSe(e){return e.status==="active"}function ASe(e){return e.status==="failed"}function xI(e){if(!e)return null;let t=Date.parse(e);return Number.isFinite(t)?t:null}function un(e,t){let a=xI(e);return a==null?"none":new Date(a).toLocaleString(void 0,{...t,timeZone:bI()})}function Jn(e){let t=xI(e);if(t==null)return"not updated yet";let a=Math.round((t-Date.now())/1e3),r=Math.abs(a),n=[["year",3600*24*365],["month",3600*24*30],["week",3600*24*7],["day",3600*24],["hour",3600],["minute",60]];for(let[o,i]of n)if(r>=i)return new Intl.RelativeTimeFormat(void 0,{numeric:"auto"}).format(Math.round(a/i),o);return"just now"}function ep(e){if(typeof e!="number"||!Number.isFinite(e))return"none";let t=Math.max(0,Math.floor(e));if(t<1e3)return`${t}ms`;let a=t/1e3;if(a<60)return`${a.toFixed(a<10?1:0)}s`;let r=Math.round(a),n=Math.floor(r/60),o=r%60;return`${n}m ${o}s`}function zW(e){if(e===void 0)return;let t=typeof e=="string"?e:JSON.stringify(e);if(t===void 0)return;let a=new TextEncoder().encode(t).byteLength;return a<1e3?`${a}b`:`${Math.round(a/1e3)}kb`}function Xg(e,t){if(!(typeof e!="number"||typeof t!="number"||t<e))return ep(t-e)}function Sc(e){if(typeof e!="number"||!Number.isFinite(e))return"";let t=Math.max(0,Math.floor(e));return t===0?"":fo(t)}function $a(e,t=!1){if(typeof e!="number"||!Number.isFinite(e))return"no timestamp";let a=new Date(e);return t?a.toLocaleString(void 0,{dateStyle:"medium",timeStyle:"medium",timeZone:bI()}):a.toLocaleTimeString(void 0,{timeZone:bI()})}function SI(e){if(typeof e!="number"||!Number.isFinite(e))return"no timestamp";let t=Math.round((e-Date.now())/1e3),a=Math.abs(t),r=[["year",3600*24*365],["month",3600*24*30],["week",3600*24*7],["day",3600*24],["hour",3600]],[n,o]=r.find(([,i])=>a>=i)??r.at(-1);return new Intl.RelativeTimeFormat(void 0,{numeric:"auto"}).format(Math.round(t/o),n)}function UW(e){let t=new Date(e),a={dateStyle:"medium",timeStyle:"long"};return{local:t.toLocaleString(void 0,{...a,timeZone:bI()}),utc:t.toLocaleString(void 0,{...a,timeZone:"UTC"})}}function jW(e){if(typeof e!="number"||!Number.isFinite(e))return"0";let t=Math.max(0,Math.floor(e));if(t<1e3)return String(t);let a=[["t",1e12],["b",1e9],["m",1e6],["k",1e3]],[r,n]=a.find(([,s])=>t>=s)??a[1],o=t/n;return`${o>=100||Number.isInteger(o)||o>=10?Math.round(o).toString():(Math.floor(o*10)/10).toFixed(1).replace(/\.0$/,"")}${r}`}function Ym(e){return typeof e=="number"&&Number.isFinite(e)?Math.max(0,Math.floor(e)):void 0}function $Se(e){return[e.inputTokens,e.outputTokens,e.cachedInputTokens,e.cacheCreationTokens].reduce((t,a)=>{let r=Ym(a);return r===void 0?t:(t??0)+r},void 0)}function tp(e){let t=e.toLowerCase();return t==="assistant"?"assistant":t==="user"?"user":t==="system"?"system":t.includes("tool")?"tool":"other"}function tf(e,t){let a=tp(t.role);return a==="assistant"?Pt():a==="user"?Yd(t.actorIdentity)??Yd(e.actorIdentity)??"User":a==="system"?"System":a==="tool"?"Tool":t.role||"Unknown"}function re(e){return jW(e)}function wi(e){return typeof e!="number"||!Number.isFinite(e)||e<=0?"0":e<10?(Math.round(e*10)/10).toFixed(1).replace(/\.0$/,""):re(e)}function ml(e){if(!e)return;let t={totalTokens:0};t.reasoningTokens=Ym(e.reasoningTokens);let a=$Se(e);if(a!==void 0)t.totalTokens=a,t.inputTokens=Ym(e.inputTokens),t.outputTokens=Ym(e.outputTokens),t.cachedInputTokens=Ym(e.cachedInputTokens),t.cacheCreationTokens=Ym(e.cacheCreationTokens);else{let r=Ym(e.totalTokens);r!==void 0&&(t.totalTokens=r,t.providerTotalTokens=r)}return t.totalTokens>0?t:void 0}function wI(e){if(!e?.length)return;let t={totalTokens:0};for(let a of e){let r=ml(a.usage);if(r){t.totalTokens+=r.totalTokens;for(let n of["inputTokens","outputTokens","cachedInputTokens","cacheCreationTokens","reasoningTokens"]){let o=r[n];o!==void 0&&(t[n]=(t[n]??0)+o)}}}return t.totalTokens>0?t:void 0}function T4(e){return e?`${jW(e.totalTokens)} tokens`:""}function CI(e){return T4(ml(e))}function nS(e){return typeof e=="number"&&Number.isFinite(e)&&e>=0?e:void 0}function _4(e,t){return Math.round((e+t)*1e12)/1e12}function Mo(e){if(!e?.cost)return;let t={total:0},a=e.cost,r=nS(a.total),n={input:nS(a.input),output:nS(a.output),cacheRead:nS(a.cacheRead),cacheWrite:nS(a.cacheWrite)},o=Object.values(n).reduce((i,s)=>i+(s??0),0);return t.total=_4(t.total,r??o),t.input=n.input,t.output=n.output,t.cacheRead=n.cacheRead,t.cacheWrite=n.cacheWrite,r!==void 0||o>0?t:void 0}function kI(e){let t;for(let a of e??[]){let r=Mo(a.usage);r&&(t=_4(t??0,r.total))}return t===void 0?void 0:{total:t}}function ze(e){if(!e)return"";let t=e.total>0&&e.total<.01?4:2;return new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",minimumFractionDigits:2,maximumFractionDigits:t}).format(e.total)}function ap(e){return e?new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",minimumFractionDigits:2,maximumFractionDigits:4}).format(e.total):""}function Yg(e,t){if(!(!e&&!t))return{...e,total:_4(e?.total??0,t?.costUsd??0)}}function II(e,t){return ze(Yg(Mo(e),t))}function BW(e){return Sc(e.cumulativeDurationMs)||"none"}function PSe(e,t){return(xI(t)??0)-(xI(e)??0)}function ev(e){return e?.agentTree?.at(-1)?.label??(e?.displayTitle?.trim()||void 0)}function jr(e){return e?.displayTitle??"Conversation"}function Yd(e){let t=e?.email?.trim()||void 0,a=e?.fullName?.trim()||void 0,r=e?.slackUserName?.trim()||void 0;return t??a??r??e?.slackUserId}function pl(e,t={}){let a=e.channel;if(!a)return;let n=t.includeId??!0?` (${a})`:"";if(e.channelNameRedacted&&e.channelName)return`${e.channelName}${n}`;let o=e.channelName?.replace(/^#/,"");return a.startsWith("D")?`Direct Message${n}`:a.startsWith("C")?o?`#${o}${n}`:`Public Channel${n}`:a.startsWith("G")?o?.startsWith("mpdm-")?`Group DM${n}`:`Private Channel${n}`:o?`${o}${n}`:a}function DSe(e){return NSe(e)?"failed":_Se(e)?"active":"idle"}function af(e){return RSe(e)?"active":ASe(e)?"failed":"idle"}function rS(e){return e.eventHistory.status==="redacted"?"Transcript hidden because this conversation is not public.":e.eventHistory.status==="expired"?"Transcript expired for this conversation.":DSe(e)==="active"?"Transcript pending while this conversation is active.":"Transcript unavailable for this conversation."}function hl(e){return`/people/${encodeURIComponent(e)}`}function FW(e){return`/system/locations/${encodeURIComponent(e)}`}function Xi(e){return`/automations/${encodeURIComponent(e)}`}function ESe(e){let t=e?.trim().toLowerCase();if(!t)return"markdown";let r={console:"shellscript",htm:"html",js:"javascript",jsonl:"json",md:"markdown",ndjson:"json",sh:"shellscript",text:"markdown",txt:"markdown",xml:"xml",yml:"yaml"}[t]??t;return Object.hasOwn(gI,r)?r:"markdown"}function HW(e){let t=e.trim();if(t)try{return JSON.stringify(JSON.parse(t),null,2)}catch{return}}function VW(e){let t=e.trim().split(/\r?\n/).filter(r=>r.trim().length>0);if(t.length<2)return;let a=[];for(let r of t){let n=HW(r);if(!n)return;a.push(n)}return a.join(`
70
+ `);case"automation":return Kve(e)}}var Wve=l.object({plugin:l.string().min(1),key:l.string().min(1)}).strict(),Jve=Wve.extend({kind:l.literal("object")});function gM(e,t){return e.map(a=>{let r=t.find(n=>n.kind===a.kind&&n.plugin===a.plugin&&n.key===a.key);return r?Qve(r):{...a,objectType:"item",title:a.key,label:a.key,url:null,warning:"Saved annotation is unavailable."}})}function Qve(e){let{createdAt:t,updatedAt:a,...r}=e;return r.kind==="object"?r:{...r,kind:"object",objectType:r.objectType??"item",title:r.label}}var so=l.string().trim().min(1).max(400),vM=l.string().url().max(2048),Ux=l.string().datetime(),_Z=l.object({provider:l.string().trim().min(1).max(100),channelName:so.optional()}).strict(),Xve=l.enum(["in_progress","answered","done","partial","blocked","abandoned"]),NZ=l.object({repository:so,number:l.number().int().positive(),title:so.optional(),url:vM,state:Ox,openedAt:Ux.optional(),mergedAt:Ux.optional(),closedAt:Ux.optional()}).strict(),Yve=l.object({kind:l.enum(["code_change","resource","url"]),label:so,url:vM,status:so.optional()}).strict(),eye=l.object({startedAt:Ux,lastActivityAt:Ux,durationMs:l.number().int().nonnegative(),participants:l.array(l.object({name:so,messages:l.number().int().positive()}).strict()),userMessages:l.number().int().nonnegative(),assistantMessages:l.number().int().nonnegative(),toolResults:l.number().int().nonnegative(),events:l.number().int().nonnegative(),turns:l.number().int().positive().optional(),location:_Z.optional(),codeChanges:l.array(NZ)}).strict(),tye=l.object({schemaVersion:l.literal(1),record:eye,summary:l.string().trim().min(1).max(600),intent:so,outcome:l.object({status:Xve,text:l.string().trim().min(1).max(600)}).strict(),decisions:l.array(l.object({text:so,by:so.optional(),kind:l.enum(["stated","confirmed","assumed"])}).strict()).max(20),openDecisions:l.array(l.object({text:so,owner:so.optional()}).strict()).max(20),facts:l.array(so).max(30),links:l.array(Yve).max(40),keywords:l.array(l.string().trim().toLowerCase().min(1).max(400)).max(12)}).strict(),aye=l.object({index:l.number().int().nonnegative(),role:l.enum(["user","assistant","tool","event"]),author:so.optional(),text:l.string().min(1),createdAtMs:l.number().int().nonnegative(),turnId:l.string().min(1).optional()}).strict(),nye=l.object({label:so,url:vM,status:so.optional()}).strict(),i3e=l.object({conversationId:l.string().min(1),title:so.optional(),visibility:l.enum(["private","public"]),location:_Z.optional(),entries:l.array(aye),codeChanges:l.array(NZ),resources:l.array(nye)}).strict();var Gd=["image/png","image/jpeg","image/gif","image/webp"];var jx=3145728,yM=3,rye=l.object({filename:l.string().trim().min(1).max(255),contentType:l.enum(Gd),data:l.string().min(4).max(jx*4/3).regex(/^[A-Za-z0-9+/]*={0,2}$/).refine(e=>e.length%4===0)}).strict(),bM=l.object({id:l.string().min(1),filename:l.string().min(1),contentType:l.string().min(1),bytes:l.number().int().nonnegative()}).strict();var D1=l.object({auxiliaryCostUsd:l.number().finite().nonnegative().optional(),count:l.number().int().positive(),cumulativeDurationMs:l.number(),cumulativeUsage:fM.optional()}).strict(),oye=l.enum(["active","completed","failed"]),iye=l.enum(["api","internal","scheduler","slack"]),Bx=fM,sye=l.object({conversationId:l.string().min(1)}).strict(),s3e=l.object({attachmentId:l.string().min(1),conversationId:l.string().min(1)}).strict(),lye=l.object({limit:l.coerce.number().int().min(1).max(1e3).default(500)}).strict(),uye=l.object({before:l.string().min(1),limit:l.coerce.number().int().min(1).max(1e3).default(500)}).strict(),cye=l.object({actorEmail:l.string().trim().email().transform(e=>e.toLowerCase()).optional(),codeRepositoryId:l.string().uuid().optional(),q:l.string().trim().max(200).optional(),status:l.enum(["active","archived"]).default("active")}).strict(),dye=l.object({archived:l.boolean(),lastSeenAt:l.string().datetime()}).strict(),xM=l.object({archivedAt:l.string().datetime().nullable()}).strict(),RZ=l.object({idempotencyKey:l.string().trim().min(1).max(200),message:l.string().trim().max(32e3),images:l.array(rye).max(3).optional()}).strict().refine(e=>!!(e.message||e.images?.length),"Add a message or an image.").refine(e=>(e.images??[]).reduce((t,a)=>t+a.data.length,0)<=jx*4/3,"Images must total 3 MB or less."),fye=RZ.safeExtend({visibility:l.enum(["private","public"]).optional()}),Fx=l.object({conversationId:l.string().min(1),messageId:l.string().min(1),status:l.enum(["accepted","duplicate"])}).strict(),zm=l.object({email:l.string().optional(),fullName:l.string().optional(),slackUserId:l.string().optional(),slackUserName:l.string().optional()}).strict(),AZ=l.enum(["defer","interrupt"]),$Z=l.object({actorIdentity:zm.optional(),createdAt:l.string().datetime(),delivery:AZ,inboundMessageId:l.string().min(1),messageId:l.string().min(1),receivedAt:l.string().datetime(),role:l.literal("user"),source:l.enum(["slack","web"]),text:l.string().optional(),attachments:l.array(bM).optional(),redacted:l.literal(!0).optional()}).strict().superRefine((e,t)=>{e.text===void 0==(e.redacted!==!0)&&t.addIssue({code:"custom",message:"pending message content must be text or explicitly redacted"}),e.redacted&&(e.actorIdentity||e.attachments)&&t.addIssue({code:"custom",message:"redacted pending messages must not expose actor identity or attachments"})}),PZ=l.object({authorizationUrl:l.string().url(),completionText:l.string().min(1),label:l.string().min(1)}).strict(),SM=l.object({authorization:PZ.optional(),conversationId:l.string().min(1),generatedAt:l.string().datetime(),messages:l.array($Z)}).strict(),mye=l.object({inboundMessageIds:l.array(l.string().min(1)).min(1).optional(),receivedBefore:l.string().datetime().optional()}).strict(),wM=l.object({cancelledCount:l.number().int().nonnegative(),cancelledInboundMessageIds:l.array(l.string().min(1)),conversationId:l.string().min(1)}).strict(),E1=l.object({costUsd:l.number().finite().nonnegative(),operations:l.array(l.object({costUsd:l.number().finite().nonnegative(),events:l.number().int().positive(),name:l.string().min(1),namespace:l.string().min(1)}).strict()).min(1)}).strict(),pye=l.object({id:l.string().min(1).optional(),kind:l.enum(["scheduled","event"]),label:l.string().min(1).optional(),title:l.string().min(1).optional(),triggerMessageId:l.string().min(1).optional(),triggerLabel:l.string().min(1).optional(),credentialMode:l.enum(["creator","system"]).optional(),credentialUser:l.string().min(1).optional()}).strict().superRefine((e,t)=>{!!e.id!=!!e.label&&t.addIssue({code:"custom",message:"sourceTask id and label must both be set or both omitted"})}),hye=mZ.and(l.object({plugin:l.string().min(1),createdAt:l.string().datetime(),updatedAt:l.string().datetime()})),DZ=l.object({createdAt:l.string().datetime(),role:l.enum(["assistant","user"]),text:l.string().min(1)}).strict(),Ag=l.object({displayTitle:l.string(),activityPreview:DZ.optional(),cumulativeDurationMs:l.number(),cumulativeUsage:Bx.optional(),auxiliaryCosts:E1.optional(),childAgentTotals:D1.optional(),conversationId:l.string(),isParticipant:l.boolean(),visibility:l.enum(["private","public"]).optional(),status:oye,startedAt:l.string(),lastSeenAt:l.string(),lastProgressAt:l.string(),surface:iye,actorIdentity:zm.optional(),participants:l.array(zm).optional(),archivedAt:l.string().datetime().nullable().optional(),channel:l.string().optional(),channelName:l.string().optional(),channelNameRedacted:l.boolean().optional(),locationId:l.string().optional(),sentryTraceUrl:l.string().optional(),locationUrl:l.string().url().optional(),traceId:l.string().optional(),annotations:l.array(hye).optional(),sidebarAnnotations:l.array(pZ).optional(),assignedWork:l.boolean().optional(),finishedWorkAt:l.string().datetime().optional(),isPriority:l.boolean().optional(),unfinishedWork:l.boolean().optional()}).strict(),gye=l.object({type:l.literal("message"),messageId:l.string().min(1),role:l.enum(["assistant","system","user"]),source:l.enum(["slack","web"]).optional(),actorIdentity:zm.optional(),eventType:l.string().min(1).optional(),eventObjectType:Ng.optional(),explicitMention:l.boolean().optional(),trustedSummary:l.string().min(1).optional(),cards:l.array(Jve).optional(),text:l.string().optional(),attachments:l.array(bM).optional(),redacted:l.literal(!0).optional()}).strict().superRefine((e,t)=>{e.text===void 0==(e.redacted!==!0)&&t.addIssue({code:"custom",message:"message content must be text or explicitly redacted"}),e.redacted&&(e.actorIdentity||e.cards||e.attachments)&&t.addIssue({code:"custom",message:"redacted messages must not expose actor identity, cards, or attachments"})}),vye=l.object({type:l.literal("message_handled"),messageId:l.string().min(1)}).strict(),yye=l.object({toolCallId:l.string().min(1),name:l.string().min(1),status:l.enum(["running","completed","error"]),startedAt:l.string().datetime().optional(),startedSeq:l.number().int().nonnegative().optional(),input:l.unknown().optional(),output:l.unknown().optional()}).strict().superRefine((e,t)=>{e.startedAt===void 0!=(e.startedSeq===void 0)&&t.addIssue({code:"custom",message:"tool start sequence and timestamp must be provided together"})}),EZ=l.object({type:l.literal("reasoning"),text:l.string().min(1).optional(),redacted:l.literal(!0).optional()}).strict().superRefine((e,t)=>{e.text===void 0==(e.redacted!==!0)&&t.addIssue({code:"custom",message:"reasoning content must be text or explicitly redacted"})}),bye=l.object({type:l.literal("tool_call"),toolCallId:l.string().min(1)}).strict(),xye=l.object({parts:l.array(l.discriminatedUnion("type",[EZ,bye])).min(1)}).strict(),Sye=l.object({type:l.literal("tool_calls"),calls:l.array(yye).min(1),assistant:xye.optional()}).strict().superRefine((e,t)=>{if(!e.assistant)return;let a=new Map;for(let n of e.calls)a.set(n.toolCallId,(a.get(n.toolCallId)??0)+1);let r=new Map;for(let n of e.assistant.parts)n.type==="tool_call"&&r.set(n.toolCallId,(r.get(n.toolCallId)??0)+1);(a.size!==r.size||[...a].some(([n,o])=>r.get(n)!==o))&&t.addIssue({code:"custom",path:["assistant","parts"],message:"assistant tool parts must reference every call exactly once"})}),wye=l.object({type:l.literal("assistant_message"),parts:l.array(EZ)}).strict(),Cye=l.discriminatedUnion("state",[l.object({type:l.literal("turn_lifecycle"),turnId:l.string().min(1),state:l.enum(["succeeded","no_reply"])}).strict(),l.object({type:l.literal("turn_lifecycle"),turnId:l.string().min(1),state:l.literal("started"),inputMessageIds:l.array(l.string().min(1)).min(1).optional()}).strict(),l.object({type:l.literal("turn_lifecycle"),turnId:l.string().min(1),state:l.literal("failed"),failureCode:$1,failureReason:P1.optional(),eventId:l.string().regex(/^[a-f0-9]{32}$/i).optional(),sentryEventUrl:l.string().url().optional()}).strict()]),kye=l.object({type:l.literal("turn_routed"),turnId:l.string().min(1),modelProfile:l.string().min(1),modelId:l.string().min(1),costUsd:l.number().finite().nonnegative().optional(),reasoningLevel:l.string().min(1),confidence:l.number().min(0).max(1).optional(),source:l.enum(["configured","inherited","router"])}).strict(),Iye=l.object({type:l.literal("guardian_action_reviewed"),turnId:l.string().min(1),toolCallId:l.string().min(1),toolName:l.string().min(1),decision:l.enum(["allow","ask","deny"]),riskLevel:l.enum(["low","medium","high","critical"]),userAuthorization:l.enum(["high","medium","low","unknown"])}).strict(),Lye=l.object({type:l.literal("turn_context"),turnId:l.string().min(1),pluginName:l.string().min(1),kind:l.string().min(1),version:l.number().int().positive(),content:l.record(l.string(),l.unknown())}).strict(),Tye=l.object({type:l.literal("structured_event"),namespace:l.string().min(1),name:l.string().min(1),version:l.number().int().positive(),turnId:l.string().min(1).optional(),presentation:hZ}).strict(),_ye=l.object({type:l.literal("attachments_delivered"),attachments:l.array(bM).min(1)}).strict(),Nye=l.object({type:l.literal("compaction"),modelProfile:l.string().min(1).optional(),modelId:l.string().min(1).optional(),summary:l.string().min(1).optional(),details:l.object({reason:l.literal("capacity"),estimatedInputTokens:l.number().int().nonnegative(),replacementInputTokens:l.number().int().nonnegative().optional(),triggerTokens:l.number().int().nonnegative(),inputLimitTokens:l.number().int().positive(),inputMessageCount:l.number().int().nonnegative(),retainedMessageCount:l.number().int().nonnegative(),summaryChars:l.number().int().nonnegative()}).strict().optional()}).strict(),Rye=l.object({type:l.literal("handoff"),modelProfile:l.string().min(1),modelId:l.string().min(1),reasoningLevel:l.string().min(1).optional(),triggeringToolCallId:l.string().min(1).optional(),summary:l.string().min(1).optional()}).strict(),Aye=l.object({type:l.literal("subagent"),startedSeq:l.number().int().nonnegative(),startedAt:l.string().datetime(),childConversationId:l.string().min(1),subagentKind:l.string().min(1),agentName:l.string().min(1).optional(),task:l.string().min(1).optional(),title:l.string().min(1).optional(),parentToolCallId:l.string().min(1).optional(),status:l.enum(["running","completed","blocked","error","aborted"])}).strict(),MZ=l.discriminatedUnion("type",[gye,vye,wye,Sye,Cye,Lye,Tye,_ye,kye,Iye,Nye,Rye,Aye]),CM=l.object({seq:l.number().int().nonnegative(),createdAt:l.string().datetime(),data:MZ,model:l.object({modelId:l.string().min(1),modelProfile:l.string().min(1).optional(),reasoningLevel:l.string().min(1).optional()}).strict().optional(),modelCall:l.object({provider:l.string().min(1).optional(),api:l.string().min(1).optional(),stopReason:l.string().min(1).optional(),usage:Bx.optional()}).strict().optional()}).strict(),kM=l.discriminatedUnion("status",[l.object({status:l.literal("available")}).strict(),l.object({status:l.literal("redacted"),reason:l.literal("non_public_conversation")}).strict(),l.object({status:l.literal("expired"),expiredAt:l.string().datetime()}).strict()]),$ye=l.object({modelId:l.string(),usage:Bx}).strict();function OZ(e,t){e.eventHistory.status==="expired"&&e.events.length>0&&t.addIssue({code:"custom",path:["events"],message:"expired event history must not contain events"});for(let a=1;a<e.events.length;a+=1)e.events[a].seq<=e.events[a-1].seq&&t.addIssue({code:"custom",path:["events",a,"seq"],message:"report event sequences must be strictly increasing"});for(let[a,r]of e.events.entries())r.data.type==="message"&&(e.eventHistory.status==="redacted"&&r.data.redacted!==!0&&t.addIssue({code:"custom",path:["events",a,"data"],message:"redacted event history must redact messages"}),e.eventHistory.status==="available"&&r.data.redacted===!0&&t.addIssue({code:"custom",path:["events",a,"data"],message:"available event history must expose messages"})),e.eventHistory.status==="redacted"&&r.data.type==="tool_calls"&&r.data.calls.some(n=>n.input!==void 0||n.output!==void 0)&&t.addIssue({code:"custom",path:["events",a,"data"],message:"redacted event history must redact tool payloads"}),e.eventHistory.status==="redacted"&&r.data.type==="assistant_message"&&r.data.parts.some(n=>n.text!==void 0)&&t.addIssue({code:"custom",path:["events",a,"data"],message:"redacted event history must redact assistant messages"}),e.eventHistory.status==="available"&&r.data.type==="assistant_message"&&r.data.parts.some(n=>n.redacted===!0)&&t.addIssue({code:"custom",path:["events",a,"data"],message:"available event history must expose reasoning"}),r.data.type==="tool_calls"&&(e.eventHistory.status==="redacted"&&r.data.assistant?.parts.some(n=>n.type==="reasoning"&&n.text!==void 0)||e.eventHistory.status==="available"&&r.data.assistant?.parts.some(n=>n.type==="reasoning"&&n.redacted===!0))&&t.addIssue({code:"custom",path:["events",a,"data","assistant"],message:"assistant reasoning must match event history visibility"})}var Pye=l.object({messageId:l.string().min(1).max(500),idempotencyKey:l.string().trim().min(1).max(200)}).strict(),IM=l.object({conversationId:l.string()}).strict(),Dye=l.object({conversationId:l.string().min(1),label:l.string().min(1)}).strict(),LM=Ag.extend({agentTree:l.array(Dye).min(2).optional(),canFork:l.boolean().optional(),forkedFromConversationId:l.string().optional(),forkedFromTitle:l.string().optional(),forks:l.array(l.string()).optional(),brief:l.object({content:tye,updatedAt:l.string().datetime(),version:l.number().int().positive()}).strict().optional(),modelUsage:l.array($ye).optional(),events:l.array(CM),eventHistory:kM,previousCursor:l.string().min(1).optional(),generatedAt:l.string(),sentryConversationUrl:l.string().optional(),sourceTask:pye.optional()}).strict().superRefine(OZ),TM=l.object({events:l.array(CM),eventHistory:kM,previousCursor:l.string().min(1).optional(),generatedAt:l.string()}).strict().superRefine(OZ),M1=l.object({conversations:l.array(Ag),source:l.literal("conversation_index"),generatedAt:l.string()}).strict(),Um=l.object({active:l.number(),conversations:l.number(),durationMs:l.number(),failed:l.number(),label:l.string(),costUsd:l.number().optional(),tokens:l.number().optional()}).strict(),zZ=l.string().regex(/^\d{4}-\d{2}-\d{2}(T\d{2})?$/),mM=l.object({cachedInputTokens:l.number().optional(),cacheCreationTokens:l.number().optional(),conversations:l.number(),costUsd:l.number().optional(),date:zZ,durationMs:l.number(),inputTokens:l.number().optional(),tokens:l.number().optional()}).strict(),pM=l.object({allow:l.number(),ask:l.number(),costUsd:l.number().optional(),date:zZ,deny:l.number(),requests:l.number()}).strict(),Eye=l.object({allow:l.number(),ask:l.number(),costUsd:l.number().optional(),deny:l.number(),metricDays:l.array(pM),metricHours:l.array(pM).optional(),metricSixHours:l.array(pM).optional(),requests:l.number()}).strict(),_M=l.object({active:l.number(),cachedInputTokens:l.number().optional(),cacheCreationTokens:l.number().optional(),conversations:l.number(),durationMs:l.number(),failed:l.number(),generatedAt:l.string(),guardian:Eye,metricDays:l.array(mM),metricHours:l.array(mM).optional(),metricSixHours:l.array(mM).optional(),locations:l.array(Um),actors:l.array(Um),source:l.literal("conversation_index"),costUsd:l.number().optional(),inputTokens:l.number().optional(),tokens:l.number().optional(),windowEnd:l.string(),windowStart:l.string()}).strict();var Mye=l.enum(["current_conversation","task_creator"]).describe("Where to send the message. Use current_conversation for posts, digests, summaries, and channel reminders. Use task_creator only when the user asks for a direct reminder or notification."),Oye=l.object({action:l.literal("send_message"),destination:Mye}).strict(),HZ=l.string().regex(/^\d{4}-\d{2}-\d{2}$/,"Use a local date in YYYY-MM-DD format."),VZ=l.string().regex(/^([01]\d|2[0-3]):[0-5]\d$/,"Use local time in HH:MM format."),qZ=l.string().min(1).max(80).describe("IANA timezone the user asked for, for example America/New_York. Omit or use null to use the creator's timezone on create, or to keep the saved timezone on update. Do not guess it from office locations.").nullable().optional(),zye=l.enum(["sunday","monday","tuesday","wednesday","thursday","friday","saturday"]),Uye=l.object({kind:l.literal("one_off").describe("A schedule that runs once."),timezone:qZ,timing:l.discriminatedUnion("type",[l.object({type:l.literal("after").describe("Run after a relative delay from the server clock."),value:l.number().int().positive().max(1e5),unit:l.enum(["second","minute","hour","day","week"])}).strict(),l.object({type:l.literal("at").describe("Run at an explicit local calendar date and time."),date:HZ.describe("Requested local calendar date in YYYY-MM-DD format."),time:VZ.describe("Requested local wall-clock time in HH:MM format.")}).strict()]).describe("Relative delay or explicit local time for the one-off run.")}).strict(),jye=l.object({kind:l.literal("recurring").describe("A repeating calendar schedule."),frequency:l.enum(["daily","weekly","monthly","yearly"]).describe("Recurring tasks can run at most once per day."),interval:l.number().int().positive().max(365).describe("Repeat every N frequency units. Defaults to 1.").nullable().optional(),time:VZ.describe("Local wall-clock time for each occurrence in HH:MM format."),weekdays:l.array(zye).min(1).max(7).describe("Required for weekly schedules.").nullable().optional(),dayOfMonth:l.number().int().min(1).max(31).describe("Required for monthly and yearly schedules.").nullable().optional(),month:l.number().int().min(1).max(12).describe("Required for yearly schedules, where January is 1.").nullable().optional(),startDate:HZ.describe("Optional local calendar date that anchors the recurrence. Omit to start with the next matching occurrence.").nullable().optional(),timezone:qZ}).strict().superRefine((e,t)=>{e.frequency==="weekly"&&e.weekdays==null&&t.addIssue({code:"custom",message:"Weekly schedules require weekdays.",path:["weekdays"]}),(e.frequency==="monthly"||e.frequency==="yearly")&&e.dayOfMonth==null&&t.addIssue({code:"custom",message:`${e.frequency} schedules require dayOfMonth.`,path:["dayOfMonth"]}),e.frequency==="yearly"&&e.month==null&&t.addIssue({code:"custom",message:"Yearly schedules require month.",path:["month"]}),e.frequency!=="weekly"&&e.weekdays!=null&&t.addIssue({code:"custom",message:"weekdays applies only to weekly schedules.",path:["weekdays"]}),e.frequency!=="monthly"&&e.frequency!=="yearly"&&e.dayOfMonth!=null&&t.addIssue({code:"custom",message:"dayOfMonth applies only to monthly or yearly schedules.",path:["dayOfMonth"]}),e.frequency!=="yearly"&&e.month!=null&&t.addIssue({code:"custom",message:"month applies only to yearly schedules.",path:["month"]})}),ZZ=l.union([Uye,jye]);var GZ=l.object({slackUserId:A1,fullName:l.string().optional(),userName:l.string().optional()}).strict(),RM=l.object({events:l.array(hc).min(1),label:l.string().min(1),match:uM.optional(),namespace:l.string().min(1),identifier:l.string().min(1).max(300),resourceType:l.string().min(1)}).strict(),KZ=Rg.omit({threadTs:!0}),Bye=zx.extend({destination:KZ}),Fye=l.object({id:l.string().min(1),createdAtMs:l.number().finite(),createdBy:GZ,creatorIdentityId:l.string().min(1),credentialMode:l.enum(["system","creator"]),destination:KZ,destinationVisibility:sM,outcomes:l.array(Bye).max(5),task:l.object({text:l.string().min(1)}).strict(),trigger:RM}).strict(),Hye=l.string().trim().min(1).max(60),WZ=l.string().trim().min(1).max(4e3),v3e=WZ.describe("Work to perform when the Automation runs. It runs later without this conversation, so write it to stand alone: name each person with their Slack mention, such as <@U123>, instead of me, my, or you. Preserve the user's scope, targets, and constraints. Do not add permissions or side effects the user did not request."),JZ=l.object({title:Hye.optional(),instruction:WZ.optional(),credentialMode:l.enum(["system","creator"]).optional(),outcomes:l.array(l.union([Oye,zx])).max(5).optional()}),Vye=JZ.extend({schedule:ZZ.optional(),status:l.enum(["active","blocked"]).optional()}).strict(),qye=JZ.extend({trigger:RM.extend({identifier:l.string().trim().min(1).max(300),label:l.string().trim().min(1).max(500)}).optional()}).strict(),Zye=l.enum(["active","blocked","paused","completed","deleted"]),Gye=l.enum(["system","creator"]),Kye=l.enum(["pending","running","completed","failed","blocked","skipped"]),Wye=l.object({slackUserId:A1,fullName:l.string().optional(),userName:l.string().optional()}).strict(),Jye=l.object({dayOfMonth:l.number().optional(),frequency:l.enum(["daily","weekly","monthly","yearly"]),interval:l.number(),month:l.number().optional(),startDate:l.string(),time:l.object({hour:l.number(),minute:l.number()}).strict(),weekdays:l.array(l.number()).optional()}).strict(),Qye=l.object({description:l.string(),kind:l.enum(["one_off","recurring"]),recurrence:Jye.optional(),timezone:l.string()}).strict(),Xye=l.object({platform:l.literal("system"),name:l.string()}).strict(),QZ=Rg.omit({threadTs:!0}),Yye=l.object({action:l.literal("send_message"),destination:QZ}).strict(),z1=l.object({id:l.string(),conversationAccess:l.object({audience:l.enum(["direct","group","channel"]),visibility:l.enum(["private","public"])}).strict(),createdAtMs:l.number(),createdBy:Wye,creatorIdentityId:l.string(),credentialMode:Gye,destination:QZ,executionActor:Xye.optional(),lastRunAtMs:l.number().optional(),nextRunAtMs:l.number().optional(),originalRequest:l.string().optional(),runNowAtMs:l.number().optional(),schedule:Qye,status:Zye,statusReason:l.string().optional(),outcomes:l.array(Yye).max(5),task:l.object({text:l.string()}).strict(),title:l.string().optional(),updatedAtMs:l.number()}).strict(),y3e=l.object({id:l.string(),attempt:l.number(),claimedAtMs:l.number(),completedAtMs:l.number().optional(),dispatchId:l.string().optional(),errorMessage:l.string().optional(),resultMessageTs:l.string().optional(),scheduledForMs:l.number(),startedAtMs:l.number().optional(),status:Kye,taskId:l.string()}).strict(),b3e=Object.freeze({platform:"system",name:"scheduled-automation"}),ebe=l.object({channelId:l.string().min(1),label:l.string().min(1),teamId:l.string().min(1),visibility:l.enum(["private","public"])}).strict(),XZ=l.object({1:l.number().int().nonnegative(),7:l.number().int().nonnegative(),30:l.number().int().nonnegative(),90:l.number().int().nonnegative()}).strict(),YZ=l.object({credentialMode:l.enum(["creator","system"]),createdAt:l.string().datetime(),createdBy:l.string().min(1),createdByAvatarUrl:l.string().url().optional(),createdByEmail:l.string().trim().email().optional(),destination:ebe,id:l.string().min(1),instruction:l.string().min(1),lastConversationId:l.string().min(1).optional(),lastRunAt:l.string().datetime().optional(),lastRunStatus:l.enum(["blocked","completed","failed"]).optional(),ownedByViewer:l.boolean(),runs:XZ,outcomes:l.array(zx).max(5),title:l.string().min(1),totalRuns:l.number().int().nonnegative()}),eG=YZ.extend({kind:l.literal("scheduled"),nextRunAt:l.string().datetime().optional(),schedule:l.string().min(1),timezone:l.string().min(1),statusReason:l.string().optional(),status:l.enum(["active","blocked","paused","completed"])}).strict(),tG=YZ.extend({events:l.array(l.string().min(1)).min(1),match:uM.optional(),kind:l.literal("event"),resource:l.string().min(1),source:l.string().min(1),triggerAvailable:l.boolean(),statusReason:l.string().optional(),status:l.enum(["active","blocked","paused"])}).strict(),Vx=l.discriminatedUnion("kind",[eG,tG]),aG=l.string().regex(/^\d{4}-\d{2}-\d{2}(T\d{2})?$/),NM=l.object({costUsd:l.number().finite().nonnegative(),date:aG,event:l.number().int().nonnegative(),scheduled:l.number().int().nonnegative()}).strict(),U1=l.object({q:l.string().trim().max(200).optional(),scope:l.enum(["all","mine","public","attention"]).default("all"),type:l.enum(["all","scheduled","event"]).default("all"),state:l.enum(["all","active","blocked","paused","completed","unavailable"]).default("all"),creator:l.string().max(300).optional(),destination:l.string().max(300).optional(),sort:l.enum(["newest","oldest","title"]).default("newest"),page:l.coerce.number().int().min(1).max(1e6).default(1),pageSize:l.coerce.number().int().min(1).max(100).default(25)}).strict(),UZ=l.object({value:l.string(),label:l.string()}).strict(),AM=l.object({executionDays:l.array(NM),executionHours:l.array(NM).optional(),executionSixHours:l.array(NM).optional(),automations:l.array(Vx),total:l.number().int().nonnegative(),page:l.number().int().positive(),pageSize:l.number().int().positive(),counts:l.object({all:l.number().int().nonnegative(),mine:l.number().int().nonnegative(),public:l.number().int().nonnegative(),private:l.number().int().nonnegative()}).strict(),creators:l.array(UZ),destinations:l.array(UZ)}).strict(),nG=l.object({id:l.string().min(1)}).strict(),rG=l.enum(["blocked","completed","failed"]),$M=l.object({conversationId:l.string().min(1).optional(),costUsd:l.number().finite().nonnegative().optional(),durationMs:l.number().finite().nonnegative().optional(),executedAt:l.string().datetime(),executionId:l.string().min(1),status:rG,title:l.string().min(1).optional(),totalTokens:l.number().int().nonnegative().optional()}).strict(),O1=l.object({blocked:l.number().int().nonnegative(),completed:l.number().int().nonnegative(),date:aG,failed:l.number().int().nonnegative()}).strict(),PM=l.object({executionDays:l.array(O1),executionHours:l.array(O1).optional(),executionSixHours:l.array(O1).optional(),executions:l.array($M),automation:Vx,truncated:l.boolean()}).strict(),oG=$M.extend({kind:l.enum(["scheduled","event"]),automationId:l.string().min(1),automationTitle:l.string().min(1)}).strict(),DM=l.object({runs:l.array(oG),truncated:l.boolean()}).strict(),jZ={title:l.string().nullable(),instruction:l.string()},BZ={version:l.number().int().positive(),createdAt:l.string().datetime(),editedBy:GZ.nullable()},iG=l.discriminatedUnion("kind",[l.object({...BZ,kind:l.literal("scheduled"),definition:z1.pick({credentialMode:!0,destination:!0,outcomes:!0,schedule:!0}).extend(jZ).strict()}).strict(),l.object({...BZ,kind:l.literal("event"),definition:Fye.pick({credentialMode:!0,destination:!0,outcomes:!0,trigger:!0}).extend(jZ).strict()}).strict()]),EM=l.object({versions:l.array(iG),activeVersion:l.number().int().positive().nullable(),truncated:l.boolean()}).strict(),tbe=nG.extend({version:l.coerce.number().int().positive()}).strict(),Hx=l.string().regex(/^[a-f0-9]{64}$/),abe=l.object({revision:Hx}).strict(),x3e=l.object({action:l.enum(["pause","resume"]),revision:Hx}).strict(),FZ=z1.pick({destination:!0,createdBy:!0}).extend({id:l.string().min(1),revision:Hx,title:l.string().nullable(),instruction:l.string(),credentialMode:l.enum(["system","creator"]),outcomes:l.array(zx).max(5),ownedByViewer:l.boolean()}),Ns=l.discriminatedUnion("kind",[FZ.merge(z1.pick({schedule:!0})).extend({kind:l.literal("scheduled"),nextRunAtMs:l.number().optional(),status:l.enum(["active","blocked","paused","completed"])}).strict(),FZ.extend({kind:l.literal("event"),trigger:RM,triggerAvailable:l.boolean(),status:l.enum(["active","blocked","paused"])}).strict()]),MM=l.discriminatedUnion("kind",[Vye.omit({status:!0}).extend({kind:l.literal("scheduled"),revision:Hx}).strict(),qye.extend({kind:l.literal("event"),revision:Hx}).strict()]),nbe=l.object({error:l.string(),code:l.enum(["invalid_edit","conflict","not_found"]),fields:l.record(l.string(),l.array(l.string())).optional()}).strict(),OM=l.array(cM.safeExtend({namespace:l.string()})),zM=ZZ,UM=z1.pick({schedule:!0}).extend({nextRunAtMs:l.number()}).strict();var rbe=l.object({status:l.literal("ok"),service:l.string(),timestamp:l.string()}).strict(),sG=l.object({configKeys:l.array(l.string()),description:l.string(),displayName:l.string(),name:l.string()}).strict(),jM=l.array(sG),BM=l.object({name:l.string(),pluginProvider:l.string().optional()}).strict(),FM=l.array(BM),lG=l.object({dir:l.string(),hasMigrationsDir:l.boolean(),hasSkillsDir:l.boolean(),packageName:l.string()}).strict(),uG=l.object({packageNames:l.array(l.string()),packages:l.array(lG),manifestRoots:l.array(l.string()),skillRoots:l.array(l.string()),tracingIncludes:l.array(l.string())}).strict(),obe=l.object({cwd:l.string(),homeDir:l.string(),descriptionText:l.string().optional(),providers:l.array(l.string()),skills:l.array(BM),packagedContent:uG}).strict(),HM=l.enum(["danger","good","neutral","warning"]),ibe=l.object({label:l.string(),tone:HM.optional(),value:l.string()}).strict(),sbe=l.object({key:l.string(),label:l.string()}).strict(),lbe=l.object({id:l.string(),tone:HM.optional(),values:l.record(l.string(),l.string())}).strict(),ube=l.object({fields:l.array(sbe).optional(),emptyText:l.string().optional(),records:l.array(lbe).optional(),title:l.string()}).strict(),cbe=l.object({categories:l.array(l.object({id:l.string().min(1),label:l.string().min(1),values:l.record(l.string(),l.number().finite())}).strict()).max(100),description:l.string().optional(),emptyText:l.string().optional(),id:l.string().min(1),series:l.array(l.object({format:l.literal("usd").optional(),key:l.string().min(1),label:l.string().min(1),tone:HM.optional()}).strict()).min(1).max(8),timeRangeDays:l.array(l.union([l.literal(1),l.literal(7),l.literal(30),l.literal(90)])).min(1).max(4).optional(),title:l.string().min(1),type:l.literal("bar_chart")}).strict(),cG=l.object({generatedAt:l.string().optional(),metrics:l.array(ibe).optional(),recordSets:l.array(ube).optional(),title:l.string().optional(),pluginName:l.string(),widgets:l.array(cbe).max(12).optional()}).strict(),j1=l.object({generatedAt:l.string(),reports:l.array(cG),source:l.literal("plugins")}).strict(),dG=36e5,C3e=6*dG,k3e=24*dG;async function VM(e){let t=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(`${e.conversationId}\0${e.idempotencyKey}`));return`api-msg:${Array.from(new Uint8Array(t),a=>a.toString(16).padStart(2,"0")).join("").slice(0,24)}`}var E=Symbol.for("drizzle:entityKind");function Wn(e,t){if(!e||typeof e!="object")return!1;if(e instanceof t)return!0;if(!Object.prototype.hasOwnProperty.call(t,E))throw new Error(`Class "${t.name??"<unknown>"}" doesn't look like a Drizzle entity. If this is incorrect and the class is provided by Drizzle, please report this as a bug.`);let a=Object.getPrototypeOf(e).constructor;if(a)for(;a;){if(E in a&&a[E]===t[E])return!0;a=Object.getPrototypeOf(a)}return!1}var jm=class{constructor(t,a){this.table=t,this.config=a,this.name=a.name,this.keyAsName=a.keyAsName,this.notNull=a.notNull,this.default=a.default,this.defaultFn=a.defaultFn,this.onUpdateFn=a.onUpdateFn,this.hasDefault=a.hasDefault,this.primary=a.primaryKey,this.isUnique=a.isUnique,this.uniqueName=a.uniqueName,this.uniqueType=a.uniqueType,this.dataType=a.dataType,this.columnType=a.columnType,this.generated=a.generated,this.generatedIdentity=a.generatedIdentity}static[E]="Column";name;keyAsName;primary;notNull;default;defaultFn;onUpdateFn;hasDefault;isUnique;uniqueName;uniqueType;dataType;columnType;enumValues=void 0;generated=void 0;generatedIdentity=void 0;config;mapFromDriverValue(t){return t}mapToDriverValue(t){return t}shouldDisableInsert(){return this.config.generated!==void 0&&this.config.generated.type!=="byDefault"}};var B1=class{static[E]="ColumnBuilder";config;constructor(t,a,r){this.config={name:t,keyAsName:t==="",notNull:!1,default:void 0,hasDefault:!1,primaryKey:!1,isUnique:!1,uniqueName:void 0,uniqueType:void 0,dataType:a,columnType:r,generated:void 0}}$type(){return this}notNull(){return this.config.notNull=!0,this}default(t){return this.config.default=t,this.config.hasDefault=!0,this}$defaultFn(t){return this.config.defaultFn=t,this.config.hasDefault=!0,this}$default=this.$defaultFn;$onUpdateFn(t){return this.config.onUpdateFn=t,this.config.hasDefault=!0,this}$onUpdate=this.$onUpdateFn;primaryKey(){return this.config.primaryKey=!0,this.config.notNull=!0,this}setName(t){this.config.name===""&&(this.config.name=t)}};var gc=Symbol.for("drizzle:Name");var F1=class{static[E]="PgForeignKeyBuilder";reference;_onUpdate="no action";_onDelete="no action";constructor(t,a){this.reference=()=>{let{name:r,columns:n,foreignColumns:o}=t();return{name:r,columns:n,foreignTable:o[0].table,foreignColumns:o}},a&&(this._onUpdate=a.onUpdate,this._onDelete=a.onDelete)}onUpdate(t){return this._onUpdate=t===void 0?"no action":t,this}onDelete(t){return this._onDelete=t===void 0?"no action":t,this}build(t){return new qM(t,this)}},qM=class{constructor(t,a){this.table=t,this.reference=a.reference,this.onUpdate=a._onUpdate,this.onDelete=a._onDelete}static[E]="PgForeignKey";reference;onUpdate;onDelete;getName(){let{name:t,columns:a,foreignColumns:r}=this.reference(),n=a.map(s=>s.name),o=r.map(s=>s.name),i=[this.table[gc],...n,r[0].table[gc],...o];return t??`${i.join("_")}_fk`}};function H1(e,...t){return e(...t)}function KM(e,t){return`${e[gc]}_${t.join("_")}_unique`}var ZM=class{constructor(t,a){this.name=a,this.columns=t}static[E]="PgUniqueConstraintBuilder";columns;nullsNotDistinctConfig=!1;nullsNotDistinct(){return this.nullsNotDistinctConfig=!0,this}build(t){return new GM(t,this.columns,this.nullsNotDistinctConfig,this.name)}},fG=class{static[E]="PgUniqueOnConstraintBuilder";name;constructor(t){this.name=t}on(...t){return new ZM(t,this.name)}},GM=class{constructor(t,a,r,n){this.table=t,this.columns=a,this.name=n??KM(this.table,this.columns.map(o=>o.name)),this.nullsNotDistinct=r}static[E]="PgUniqueConstraint";columns;name;nullsNotDistinct=!1;getName(){return this.name}};function mG(e,t,a){for(let r=t;r<e.length;r++){let n=e[r];if(n==="\\"){r++;continue}if(n==='"')return[e.slice(t,r).replace(/\\/g,""),r+1];if(!a&&(n===","||n==="}"))return[e.slice(t,r).replace(/\\/g,""),r]}return[e.slice(t).replace(/\\/g,""),e.length]}function pG(e,t=0){let a=[],r=t,n=!1;for(;r<e.length;){let o=e[r];if(o===","){(n||r===t)&&a.push(""),n=!0,r++;continue}if(n=!1,o==="\\"){r+=2;continue}if(o==='"'){let[u,c]=mG(e,r+1,!0);a.push(u),r=c;continue}if(o==="}")return[a,r+1];if(o==="{"){let[u,c]=pG(e,r+1);a.push(u),r=c;continue}let[i,s]=mG(e,r,!1);a.push(i),r=s}return[a,r]}function hG(e){let[t]=pG(e,1);return t}function WM(e){return`{${e.map(t=>Array.isArray(t)?WM(t):typeof t=="string"?`"${t.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`:`${t}`).join(",")}}`}var de=class extends B1{foreignKeyConfigs=[];static[E]="PgColumnBuilder";array(t){return new QM(this.config.name,this,t)}references(t,a={}){return this.foreignKeyConfigs.push({ref:t,actions:a}),this}unique(t,a){return this.config.isUnique=!0,this.config.uniqueName=t,this.config.uniqueType=a?.nulls,this}generatedAlwaysAs(t){return this.config.generated={as:t,type:"always",mode:"stored"},this}buildForeignKeys(t,a){return this.foreignKeyConfigs.map(({ref:r,actions:n})=>H1((o,i)=>{let s=new F1(()=>{let u=o();return{columns:[t],foreignColumns:[u]}});return i.onUpdate&&s.onUpdate(i.onUpdate),i.onDelete&&s.onDelete(i.onDelete),s.build(a)},r,n))}buildExtraConfigColumn(t){return new JM(t,this.config)}},ne=class extends jm{constructor(t,a){a.uniqueName||(a.uniqueName=KM(t,[a.name])),super(t,a),this.table=t}static[E]="PgColumn"},JM=class extends ne{static[E]="ExtraConfigColumn";getSQLType(){return this.getSQLType()}indexConfig={order:this.config.order??"asc",nulls:this.config.nulls??"last",opClass:this.config.opClass};defaultConfig={order:"asc",nulls:"last",opClass:void 0};asc(){return this.indexConfig.order="asc",this}desc(){return this.indexConfig.order="desc",this}nullsFirst(){return this.indexConfig.nulls="first",this}nullsLast(){return this.indexConfig.nulls="last",this}op(t){return this.indexConfig.opClass=t,this}},$g=class{static[E]="IndexedColumn";constructor(t,a,r,n){this.name=t,this.keyAsName=a,this.type=r,this.indexConfig=n}name;keyAsName;type;indexConfig},QM=class extends de{static[E]="PgArrayBuilder";constructor(t,a,r){super(t,"array","PgArray"),this.config.baseBuilder=a,this.config.size=r}build(t){let a=this.config.baseBuilder.build(t);return new XM(t,this.config,a)}},XM=class e extends ne{constructor(t,a,r,n){super(t,a),this.baseColumn=r,this.range=n,this.size=a.size}size;static[E]="PgArray";getSQLType(){return`${this.baseColumn.getSQLType()}[${typeof this.size=="number"?this.size:""}]`}mapFromDriverValue(t){return typeof t=="string"&&(t=hG(t)),t.map(a=>this.baseColumn.mapFromDriverValue(a))}mapToDriverValue(t,a=!1){let r=t.map(n=>n===null?null:Wn(this.baseColumn,e)?this.baseColumn.mapToDriverValue(n,!0):this.baseColumn.mapToDriverValue(n));return a?r:WM(r)}};var gG=class extends de{static[E]="PgEnumObjectColumnBuilder";constructor(t,a){super(t,"string","PgEnumObjectColumn"),this.config.enum=a}build(t){return new YM(t,this.config)}},YM=class extends ne{static[E]="PgEnumObjectColumn";enum;enumValues=this.config.enum.enumValues;constructor(t,a){super(t,a),this.enum=a.enum}getSQLType(){return this.enum.enumName}},vG=Symbol.for("drizzle:isPgEnum");function bG(e){return!!e&&typeof e=="function"&&vG in e&&e[vG]===!0}var yG=class extends de{static[E]="PgEnumColumnBuilder";constructor(t,a){super(t,"string","PgEnumColumn"),this.config.enum=a}build(t){return new eO(t,this.config)}},eO=class extends ne{static[E]="PgEnumColumn";enum=this.config.enum;enumValues=this.config.enum.enumValues;constructor(t,a){super(t,a),this.enum=a.enum}getSQLType(){return this.enum.enumName}};var Pg=class{static[E]="Subquery";constructor(t,a,r,n=!1,o=[]){this._={brand:"Subquery",sql:t,selectedFields:a,alias:r,isWith:n,usedTables:o}}},xG=class extends Pg{static[E]="WithSubquery"};var SG="0.45.2";var tO,aO,wG={startActiveSpan(e,t){return tO?(aO||(aO=tO.trace.getTracer("drizzle-orm",SG)),H1((a,r)=>r.startActiveSpan(e,n=>{try{return t(n)}catch(o){throw n.setStatus({code:a.SpanStatusCode.ERROR,message:o instanceof Error?o.message:"Unknown error"}),o}finally{n.end()}}),tO,aO)):t()}};var Dg=Symbol.for("drizzle:ViewBaseConfig");var nO=Symbol.for("drizzle:Schema"),CG=Symbol.for("drizzle:Columns"),kG=Symbol.for("drizzle:ExtraConfigColumns"),rO=Symbol.for("drizzle:OriginalName"),oO=Symbol.for("drizzle:BaseName"),qx=Symbol.for("drizzle:IsAlias"),IG=Symbol.for("drizzle:ExtraConfigBuilder"),dbe=Symbol.for("drizzle:IsDrizzleTable"),$n=class{static[E]="Table";static Symbol={Name:gc,Schema:nO,OriginalName:rO,Columns:CG,ExtraConfigColumns:kG,BaseName:oO,IsAlias:qx,ExtraConfigBuilder:IG};[gc];[rO];[nO];[CG];[kG];[oO];[qx]=!1;[dbe]=!0;[IG]=void 0;constructor(t,a,r){this[gc]=this[rO]=t,this[nO]=a,this[oO]=r}};var LG=class{static[E]="FakePrimitiveParam"};function fbe(e){return e!=null&&typeof e.getSQL=="function"}function mbe(e){let t={sql:"",params:[]};for(let a of e)t.sql+=a.sql,t.params.push(...a.params),a.typings?.length&&(t.typings||(t.typings=[]),t.typings.push(...a.typings));return t}var Wi=class{static[E]="StringChunk";value;constructor(t){this.value=Array.isArray(t)?t:[t]}getSQL(){return new Pn([this])}},Pn=class e{constructor(t){this.queryChunks=t;for(let a of t)if(Wn(a,$n)){let r=a[$n.Symbol.Schema];this.usedTables.push(r===void 0?a[$n.Symbol.Name]:r+"."+a[$n.Symbol.Name])}}static[E]="SQL";decoder=TG;shouldInlineParams=!1;usedTables=[];append(t){return this.queryChunks.push(...t.queryChunks),this}toQuery(t){return wG.startActiveSpan("drizzle.buildSQL",a=>{let r=this.buildQueryFromSourceParams(this.queryChunks,t);return a?.setAttributes({"drizzle.query.text":r.sql,"drizzle.query.params":JSON.stringify(r.params)}),r})}buildQueryFromSourceParams(t,a){let r=Object.assign({},a,{inlineParams:a.inlineParams||this.shouldInlineParams,paramStartIndex:a.paramStartIndex||{value:0}}),{casing:n,escapeName:o,escapeParam:i,prepareTyping:s,inlineParams:u,paramStartIndex:c}=r;return mbe(t.map(d=>{if(Wn(d,Wi))return{sql:d.value.join(""),params:[]};if(Wn(d,Zx))return{sql:o(d.value),params:[]};if(d===void 0)return{sql:"",params:[]};if(Array.isArray(d)){let f=[new Wi("(")];for(let[m,h]of d.entries())f.push(h),m<d.length-1&&f.push(new Wi(", "));return f.push(new Wi(")")),this.buildQueryFromSourceParams(f,r)}if(Wn(d,e))return this.buildQueryFromSourceParams(d.queryChunks,{...r,inlineParams:u||d.shouldInlineParams});if(Wn(d,$n)){let f=d[$n.Symbol.Schema],m=d[$n.Symbol.Name];return{sql:f===void 0||d[qx]?o(m):o(f)+"."+o(m),params:[]}}if(Wn(d,jm)){let f=n.getColumnCasing(d);if(a.invokeSource==="indexes")return{sql:o(f),params:[]};let m=d.table[$n.Symbol.Schema];return{sql:d.table[qx]||m===void 0?o(d.table[$n.Symbol.Name])+"."+o(f):o(m)+"."+o(d.table[$n.Symbol.Name])+"."+o(f),params:[]}}if(Wn(d,iO)){let f=d[Dg].schema,m=d[Dg].name;return{sql:f===void 0||d[Dg].isAlias?o(m):o(f)+"."+o(m),params:[]}}if(Wn(d,V1)){if(Wn(d.value,Gx))return{sql:i(c.value++,d),params:[d],typings:["none"]};let f=d.value===null?null:d.encoder.mapToDriverValue(d.value);if(Wn(f,e))return this.buildQueryFromSourceParams([f],r);if(u)return{sql:this.mapInlineParam(f,r),params:[]};let m=["none"];return s&&(m=[s(d.encoder)]),{sql:i(c.value++,f),params:[f],typings:m}}return Wn(d,Gx)?{sql:i(c.value++,d),params:[d],typings:["none"]}:Wn(d,e.Aliased)&&d.fieldAlias!==void 0?{sql:o(d.fieldAlias),params:[]}:Wn(d,Pg)?d._.isWith?{sql:o(d._.alias),params:[]}:this.buildQueryFromSourceParams([new Wi("("),d._.sql,new Wi(") "),new Zx(d._.alias)],r):bG(d)?d.schema?{sql:o(d.schema)+"."+o(d.enumName),params:[]}:{sql:o(d.enumName),params:[]}:fbe(d)?d.shouldOmitSQLParens?.()?this.buildQueryFromSourceParams([d.getSQL()],r):this.buildQueryFromSourceParams([new Wi("("),d.getSQL(),new Wi(")")],r):u?{sql:this.mapInlineParam(d,r),params:[]}:{sql:i(c.value++,d),params:[d],typings:["none"]}}))}mapInlineParam(t,{escapeString:a}){if(t===null)return"null";if(typeof t=="number"||typeof t=="boolean")return t.toString();if(typeof t=="string")return a(t);if(typeof t=="object"){let r=t.toString();return a(r==="[object Object]"?JSON.stringify(t):r)}throw new Error("Unexpected param value: "+t)}getSQL(){return this}as(t){return t===void 0?this:new e.Aliased(this,t)}mapWith(t){return this.decoder=typeof t=="function"?{mapFromDriverValue:t}:t,this}inlineParams(){return this.shouldInlineParams=!0,this}if(t){return t?this:void 0}},Zx=class{constructor(t){this.value=t}static[E]="Name";brand;getSQL(){return new Pn([this])}};var TG={mapFromDriverValue:e=>e},_G={mapToDriverValue:e=>e},pje={...TG,..._G},V1=class{constructor(t,a=_G){this.value=t,this.encoder=a}static[E]="Param";brand;getSQL(){return new Pn([this])}};function nu(e,...t){let a=[];(t.length>0||e.length>0&&e[0]!=="")&&a.push(new Wi(e[0]));for(let[r,n]of t.entries())a.push(n,new Wi(e[r+1]));return new Pn(a)}(e=>{function t(){return new Pn([])}e.empty=t;function a(u){return new Pn(u)}e.fromList=a;function r(u){return new Pn([new Wi(u)])}e.raw=r;function n(u,c){let d=[];for(let[f,m]of u.entries())f>0&&c!==void 0&&d.push(c),d.push(m);return new Pn(d)}e.join=n;function o(u){return new Zx(u)}e.identifier=o;function i(u){return new Gx(u)}e.placeholder=i;function s(u,c){return new V1(u,c)}e.param=s})(nu||(nu={}));(e=>{class t{constructor(r,n){this.sql=r,this.fieldAlias=n}static[E]="SQL.Aliased";isSelectionField=!1;getSQL(){return this.sql}clone(){return new t(this.sql,this.fieldAlias)}}e.Aliased=t})(Pn||(Pn={}));var Gx=class{constructor(t){this.name=t}static[E]="Placeholder";getSQL(){return new Pn([this])}};var pbe=Symbol.for("drizzle:IsDrizzleView"),iO=class{static[E]="View";[Dg];[pbe]=!0;constructor({name:t,schema:a,selectedFields:r,query:n}){this[Dg]={name:t,originalName:t,schema:a,selectedFields:r,query:n,isExisting:!n,isAlias:!1}}getSQL(){return new Pn([this])}};jm.prototype.getSQL=function(){return new Pn([this])};$n.prototype.getSQL=function(){return new Pn([this])};Pg.prototype.getSQL=function(){return new Pn([this])};function $t(e,t){return{name:typeof e=="string"&&e.length>0?e:"",config:typeof e=="object"?e:t}}var gje=typeof TextDecoder>"u"?null:new TextDecoder;var vc=class extends de{static[E]="PgIntColumnBaseBuilder";generatedAlwaysAsIdentity(t){if(t){let{name:a,...r}=t;this.config.generatedIdentity={type:"always",sequenceName:a,sequenceOptions:r}}else this.config.generatedIdentity={type:"always"};return this.config.hasDefault=!0,this.config.notNull=!0,this}generatedByDefaultAsIdentity(t){if(t){let{name:a,...r}=t;this.config.generatedIdentity={type:"byDefault",sequenceName:a,sequenceOptions:r}}else this.config.generatedIdentity={type:"byDefault"};return this.config.hasDefault=!0,this.config.notNull=!0,this}};var sO=class extends vc{static[E]="PgBigInt53Builder";constructor(t){super(t,"number","PgBigInt53")}build(t){return new lO(t,this.config)}},lO=class extends ne{static[E]="PgBigInt53";getSQLType(){return"bigint"}mapFromDriverValue(t){return typeof t=="number"?t:Number(t)}},uO=class extends vc{static[E]="PgBigInt64Builder";constructor(t){super(t,"bigint","PgBigInt64")}build(t){return new cO(t,this.config)}},cO=class extends ne{static[E]="PgBigInt64";getSQLType(){return"bigint"}mapFromDriverValue(t){return BigInt(t)}};function NG(e,t){let{name:a,config:r}=$t(e,t);return r.mode==="number"?new sO(a):new uO(a)}var dO=class extends de{static[E]="PgBigSerial53Builder";constructor(t){super(t,"number","PgBigSerial53"),this.config.hasDefault=!0,this.config.notNull=!0}build(t){return new fO(t,this.config)}},fO=class extends ne{static[E]="PgBigSerial53";getSQLType(){return"bigserial"}mapFromDriverValue(t){return typeof t=="number"?t:Number(t)}},mO=class extends de{static[E]="PgBigSerial64Builder";constructor(t){super(t,"bigint","PgBigSerial64"),this.config.hasDefault=!0}build(t){return new pO(t,this.config)}},pO=class extends ne{static[E]="PgBigSerial64";getSQLType(){return"bigserial"}mapFromDriverValue(t){return BigInt(t)}};function RG(e,t){let{name:a,config:r}=$t(e,t);return r.mode==="number"?new dO(a):new mO(a)}var hO=class extends de{static[E]="PgBooleanBuilder";constructor(t){super(t,"boolean","PgBoolean")}build(t){return new gO(t,this.config)}},gO=class extends ne{static[E]="PgBoolean";getSQLType(){return"boolean"}};function Kx(e){return new hO(e??"")}var vO=class extends de{static[E]="PgCharBuilder";constructor(t,a){super(t,"string","PgChar"),this.config.length=a.length,this.config.enumValues=a.enum}build(t){return new yO(t,this.config)}},yO=class extends ne{static[E]="PgChar";length=this.config.length;enumValues=this.config.enumValues;getSQLType(){return this.length===void 0?"char":`char(${this.length})`}};function AG(e,t={}){let{name:a,config:r}=$t(e,t);return new vO(a,r)}var bO=class extends de{static[E]="PgCidrBuilder";constructor(t){super(t,"string","PgCidr")}build(t){return new xO(t,this.config)}},xO=class extends ne{static[E]="PgCidr";getSQLType(){return"cidr"}};function $G(e){return new bO(e??"")}var SO=class extends de{static[E]="PgCustomColumnBuilder";constructor(t,a,r){super(t,"custom","PgCustomColumn"),this.config.fieldConfig=a,this.config.customTypeParams=r}build(t){return new wO(t,this.config)}},wO=class extends ne{static[E]="PgCustomColumn";sqlName;mapTo;mapFrom;constructor(t,a){super(t,a),this.sqlName=a.customTypeParams.dataType(a.fieldConfig),this.mapTo=a.customTypeParams.toDriver,this.mapFrom=a.customTypeParams.fromDriver}getSQLType(){return this.sqlName}mapFromDriverValue(t){return typeof this.mapFrom=="function"?this.mapFrom(t):t}mapToDriverValue(t){return typeof this.mapTo=="function"?this.mapTo(t):t}};function PG(e){return(t,a)=>{let{name:r,config:n}=$t(t,a);return new SO(r,n,e)}}var ru=class extends de{static[E]="PgDateColumnBaseBuilder";defaultNow(){return this.default(nu`now()`)}};var CO=class extends ru{static[E]="PgDateBuilder";constructor(t){super(t,"date","PgDate")}build(t){return new kO(t,this.config)}},kO=class extends ne{static[E]="PgDate";getSQLType(){return"date"}mapFromDriverValue(t){return typeof t=="string"?new Date(t):t}mapToDriverValue(t){return t.toISOString()}},IO=class extends ru{static[E]="PgDateStringBuilder";constructor(t){super(t,"string","PgDateString")}build(t){return new LO(t,this.config)}},LO=class extends ne{static[E]="PgDateString";getSQLType(){return"date"}mapFromDriverValue(t){return typeof t=="string"?t:t.toISOString().slice(0,-14)}};function DG(e,t){let{name:a,config:r}=$t(e,t);return r?.mode==="date"?new CO(a):new IO(a)}var TO=class extends de{static[E]="PgDoublePrecisionBuilder";constructor(t){super(t,"number","PgDoublePrecision")}build(t){return new _O(t,this.config)}},_O=class extends ne{static[E]="PgDoublePrecision";getSQLType(){return"double precision"}mapFromDriverValue(t){return typeof t=="string"?Number.parseFloat(t):t}};function EG(e){return new TO(e??"")}var NO=class extends de{static[E]="PgInetBuilder";constructor(t){super(t,"string","PgInet")}build(t){return new RO(t,this.config)}},RO=class extends ne{static[E]="PgInet";getSQLType(){return"inet"}};function MG(e){return new NO(e??"")}var AO=class extends vc{static[E]="PgIntegerBuilder";constructor(t){super(t,"number","PgInteger")}build(t){return new $O(t,this.config)}},$O=class extends ne{static[E]="PgInteger";getSQLType(){return"integer"}mapFromDriverValue(t){return typeof t=="string"?Number.parseInt(t):t}};function Eg(e){return new AO(e??"")}var PO=class extends de{static[E]="PgIntervalBuilder";constructor(t,a){super(t,"string","PgInterval"),this.config.intervalConfig=a}build(t){return new DO(t,this.config)}},DO=class extends ne{static[E]="PgInterval";fields=this.config.intervalConfig.fields;precision=this.config.intervalConfig.precision;getSQLType(){let t=this.fields?` ${this.fields}`:"",a=this.precision?`(${this.precision})`:"";return`interval${t}${a}`}};function OG(e,t={}){let{name:a,config:r}=$t(e,t);return new PO(a,r)}var EO=class extends de{static[E]="PgJsonBuilder";constructor(t){super(t,"json","PgJson")}build(t){return new MO(t,this.config)}},MO=class extends ne{static[E]="PgJson";constructor(t,a){super(t,a)}getSQLType(){return"json"}mapToDriverValue(t){return JSON.stringify(t)}mapFromDriverValue(t){if(typeof t=="string")try{return JSON.parse(t)}catch{return t}return t}};function zG(e){return new EO(e??"")}var OO=class extends de{static[E]="PgJsonbBuilder";constructor(t){super(t,"json","PgJsonb")}build(t){return new zO(t,this.config)}},zO=class extends ne{static[E]="PgJsonb";constructor(t,a){super(t,a)}getSQLType(){return"jsonb"}mapToDriverValue(t){return JSON.stringify(t)}mapFromDriverValue(t){if(typeof t=="string")try{return JSON.parse(t)}catch{return t}return t}};function $o(e){return new OO(e??"")}var UO=class extends de{static[E]="PgLineBuilder";constructor(t){super(t,"array","PgLine")}build(t){return new jO(t,this.config)}},jO=class extends ne{static[E]="PgLine";getSQLType(){return"line"}mapFromDriverValue(t){let[a,r,n]=t.slice(1,-1).split(",");return[Number.parseFloat(a),Number.parseFloat(r),Number.parseFloat(n)]}mapToDriverValue(t){return`{${t[0]},${t[1]},${t[2]}}`}},BO=class extends de{static[E]="PgLineABCBuilder";constructor(t){super(t,"json","PgLineABC")}build(t){return new FO(t,this.config)}},FO=class extends ne{static[E]="PgLineABC";getSQLType(){return"line"}mapFromDriverValue(t){let[a,r,n]=t.slice(1,-1).split(",");return{a:Number.parseFloat(a),b:Number.parseFloat(r),c:Number.parseFloat(n)}}mapToDriverValue(t){return`{${t.a},${t.b},${t.c}}`}};function UG(e,t){let{name:a,config:r}=$t(e,t);return!r?.mode||r.mode==="tuple"?new UO(a):new BO(a)}var HO=class extends de{static[E]="PgMacaddrBuilder";constructor(t){super(t,"string","PgMacaddr")}build(t){return new VO(t,this.config)}},VO=class extends ne{static[E]="PgMacaddr";getSQLType(){return"macaddr"}};function jG(e){return new HO(e??"")}var qO=class extends de{static[E]="PgMacaddr8Builder";constructor(t){super(t,"string","PgMacaddr8")}build(t){return new ZO(t,this.config)}},ZO=class extends ne{static[E]="PgMacaddr8";getSQLType(){return"macaddr8"}};function BG(e){return new qO(e??"")}var GO=class extends de{static[E]="PgNumericBuilder";constructor(t,a,r){super(t,"string","PgNumeric"),this.config.precision=a,this.config.scale=r}build(t){return new KO(t,this.config)}},KO=class extends ne{static[E]="PgNumeric";precision;scale;constructor(t,a){super(t,a),this.precision=a.precision,this.scale=a.scale}mapFromDriverValue(t){return typeof t=="string"?t:String(t)}getSQLType(){return this.precision!==void 0&&this.scale!==void 0?`numeric(${this.precision}, ${this.scale})`:this.precision===void 0?"numeric":`numeric(${this.precision})`}},WO=class extends de{static[E]="PgNumericNumberBuilder";constructor(t,a,r){super(t,"number","PgNumericNumber"),this.config.precision=a,this.config.scale=r}build(t){return new JO(t,this.config)}},JO=class extends ne{static[E]="PgNumericNumber";precision;scale;constructor(t,a){super(t,a),this.precision=a.precision,this.scale=a.scale}mapFromDriverValue(t){return typeof t=="number"?t:Number(t)}mapToDriverValue=String;getSQLType(){return this.precision!==void 0&&this.scale!==void 0?`numeric(${this.precision}, ${this.scale})`:this.precision===void 0?"numeric":`numeric(${this.precision})`}},QO=class extends de{static[E]="PgNumericBigIntBuilder";constructor(t,a,r){super(t,"bigint","PgNumericBigInt"),this.config.precision=a,this.config.scale=r}build(t){return new XO(t,this.config)}},XO=class extends ne{static[E]="PgNumericBigInt";precision;scale;constructor(t,a){super(t,a),this.precision=a.precision,this.scale=a.scale}mapFromDriverValue=BigInt;mapToDriverValue=String;getSQLType(){return this.precision!==void 0&&this.scale!==void 0?`numeric(${this.precision}, ${this.scale})`:this.precision===void 0?"numeric":`numeric(${this.precision})`}};function FG(e,t){let{name:a,config:r}=$t(e,t),n=r?.mode;return n==="number"?new WO(a,r?.precision,r?.scale):n==="bigint"?new QO(a,r?.precision,r?.scale):new GO(a,r?.precision,r?.scale)}var YO=class extends de{static[E]="PgPointTupleBuilder";constructor(t){super(t,"array","PgPointTuple")}build(t){return new ez(t,this.config)}},ez=class extends ne{static[E]="PgPointTuple";getSQLType(){return"point"}mapFromDriverValue(t){if(typeof t=="string"){let[a,r]=t.slice(1,-1).split(",");return[Number.parseFloat(a),Number.parseFloat(r)]}return[t.x,t.y]}mapToDriverValue(t){return`(${t[0]},${t[1]})`}},tz=class extends de{static[E]="PgPointObjectBuilder";constructor(t){super(t,"json","PgPointObject")}build(t){return new az(t,this.config)}},az=class extends ne{static[E]="PgPointObject";getSQLType(){return"point"}mapFromDriverValue(t){if(typeof t=="string"){let[a,r]=t.slice(1,-1).split(",");return{x:Number.parseFloat(a),y:Number.parseFloat(r)}}return t}mapToDriverValue(t){return`(${t.x},${t.y})`}};function HG(e,t){let{name:a,config:r}=$t(e,t);return!r?.mode||r.mode==="tuple"?new YO(a):new tz(a)}function hbe(e){let t=[];for(let a=0;a<e.length;a+=2)t.push(Number.parseInt(e.slice(a,a+2),16));return new Uint8Array(t)}function VG(e,t){let a=new ArrayBuffer(8),r=new DataView(a);for(let n=0;n<8;n++)r.setUint8(n,e[t+n]);return r.getFloat64(0,!0)}function nz(e){let t=hbe(e),a=0,r=t[a];a+=1;let n=new DataView(t.buffer),o=n.getUint32(a,r===1);a+=4;let i;if(o&536870912&&(i=n.getUint32(a,r===1),a+=4),(o&65535)===1){let s=VG(t,a);a+=8;let u=VG(t,a);return a+=8,[s,u]}throw new Error("Unsupported geometry type")}var rz=class extends de{static[E]="PgGeometryBuilder";constructor(t){super(t,"array","PgGeometry")}build(t){return new oz(t,this.config)}},oz=class extends ne{static[E]="PgGeometry";getSQLType(){return"geometry(point)"}mapFromDriverValue(t){return nz(t)}mapToDriverValue(t){return`point(${t[0]} ${t[1]})`}},iz=class extends de{static[E]="PgGeometryObjectBuilder";constructor(t){super(t,"json","PgGeometryObject")}build(t){return new sz(t,this.config)}},sz=class extends ne{static[E]="PgGeometryObject";getSQLType(){return"geometry(point)"}mapFromDriverValue(t){let a=nz(t);return{x:a[0],y:a[1]}}mapToDriverValue(t){return`point(${t.x} ${t.y})`}};function qG(e,t){let{name:a,config:r}=$t(e,t);return!r?.mode||r.mode==="tuple"?new rz(a):new iz(a)}var lz=class extends de{static[E]="PgRealBuilder";constructor(t,a){super(t,"number","PgReal"),this.config.length=a}build(t){return new uz(t,this.config)}},uz=class extends ne{static[E]="PgReal";constructor(t,a){super(t,a)}getSQLType(){return"real"}mapFromDriverValue=t=>typeof t=="string"?Number.parseFloat(t):t};function ZG(e){return new lz(e??"")}var cz=class extends de{static[E]="PgSerialBuilder";constructor(t){super(t,"number","PgSerial"),this.config.hasDefault=!0,this.config.notNull=!0}build(t){return new dz(t,this.config)}},dz=class extends ne{static[E]="PgSerial";getSQLType(){return"serial"}};function GG(e){return new cz(e??"")}var fz=class extends vc{static[E]="PgSmallIntBuilder";constructor(t){super(t,"number","PgSmallInt")}build(t){return new mz(t,this.config)}},mz=class extends ne{static[E]="PgSmallInt";getSQLType(){return"smallint"}mapFromDriverValue=t=>typeof t=="string"?Number(t):t};function KG(e){return new fz(e??"")}var pz=class extends de{static[E]="PgSmallSerialBuilder";constructor(t){super(t,"number","PgSmallSerial"),this.config.hasDefault=!0,this.config.notNull=!0}build(t){return new hz(t,this.config)}},hz=class extends ne{static[E]="PgSmallSerial";getSQLType(){return"smallserial"}};function WG(e){return new pz(e??"")}var gz=class extends de{static[E]="PgTextBuilder";constructor(t,a){super(t,"string","PgText"),this.config.enumValues=a.enum}build(t){return new vz(t,this.config)}},vz=class extends ne{static[E]="PgText";enumValues=this.config.enumValues;getSQLType(){return"text"}};function ye(e,t={}){let{name:a,config:r}=$t(e,t);return new gz(a,r)}var yz=class extends ru{constructor(t,a,r){super(t,"string","PgTime"),this.withTimezone=a,this.precision=r,this.config.withTimezone=a,this.config.precision=r}static[E]="PgTimeBuilder";build(t){return new bz(t,this.config)}},bz=class extends ne{static[E]="PgTime";withTimezone;precision;constructor(t,a){super(t,a),this.withTimezone=a.withTimezone,this.precision=a.precision}getSQLType(){return`time${this.precision===void 0?"":`(${this.precision})`}${this.withTimezone?" with time zone":""}`}};function JG(e,t={}){let{name:a,config:r}=$t(e,t);return new yz(a,r.withTimezone??!1,r.precision)}var xz=class extends ru{static[E]="PgTimestampBuilder";constructor(t,a,r){super(t,"date","PgTimestamp"),this.config.withTimezone=a,this.config.precision=r}build(t){return new Sz(t,this.config)}},Sz=class extends ne{static[E]="PgTimestamp";withTimezone;precision;constructor(t,a){super(t,a),this.withTimezone=a.withTimezone,this.precision=a.precision}getSQLType(){return`timestamp${this.precision===void 0?"":` (${this.precision})`}${this.withTimezone?" with time zone":""}`}mapFromDriverValue(t){return typeof t=="string"?new Date(this.withTimezone?t:t+"+0000"):t}mapToDriverValue=t=>t.toISOString()},wz=class extends ru{static[E]="PgTimestampStringBuilder";constructor(t,a,r){super(t,"string","PgTimestampString"),this.config.withTimezone=a,this.config.precision=r}build(t){return new Cz(t,this.config)}},Cz=class extends ne{static[E]="PgTimestampString";withTimezone;precision;constructor(t,a){super(t,a),this.withTimezone=a.withTimezone,this.precision=a.precision}getSQLType(){return`timestamp${this.precision===void 0?"":`(${this.precision})`}${this.withTimezone?" with time zone":""}`}mapFromDriverValue(t){if(typeof t=="string")return t;let a=t.toISOString().slice(0,-1).replace("T"," ");if(this.withTimezone){let r=t.getTimezoneOffset(),n=r<=0?"+":"-";return`${a}${n}${Math.floor(Math.abs(r)/60).toString().padStart(2,"0")}`}return a}};function q1(e,t={}){let{name:a,config:r}=$t(e,t);return r?.mode==="string"?new wz(a,r.withTimezone??!1,r.precision):new xz(a,r?.withTimezone??!1,r?.precision)}var kz=class extends de{static[E]="PgUUIDBuilder";constructor(t){super(t,"string","PgUUID")}defaultRandom(){return this.default(nu`gen_random_uuid()`)}build(t){return new Iz(t,this.config)}},Iz=class extends ne{static[E]="PgUUID";getSQLType(){return"uuid"}};function QG(e){return new kz(e??"")}var Lz=class extends de{static[E]="PgVarcharBuilder";constructor(t,a){super(t,"string","PgVarchar"),this.config.length=a.length,this.config.enumValues=a.enum}build(t){return new Tz(t,this.config)}},Tz=class extends ne{static[E]="PgVarchar";length=this.config.length;enumValues=this.config.enumValues;getSQLType(){return this.length===void 0?"varchar":`varchar(${this.length})`}};function XG(e,t={}){let{name:a,config:r}=$t(e,t);return new Lz(a,r)}var _z=class extends de{static[E]="PgBinaryVectorBuilder";constructor(t,a){super(t,"string","PgBinaryVector"),this.config.dimensions=a.dimensions}build(t){return new Nz(t,this.config)}},Nz=class extends ne{static[E]="PgBinaryVector";dimensions=this.config.dimensions;getSQLType(){return`bit(${this.dimensions})`}};function YG(e,t){let{name:a,config:r}=$t(e,t);return new _z(a,r)}var Rz=class extends de{static[E]="PgHalfVectorBuilder";constructor(t,a){super(t,"array","PgHalfVector"),this.config.dimensions=a.dimensions}build(t){return new Az(t,this.config)}},Az=class extends ne{static[E]="PgHalfVector";dimensions=this.config.dimensions;getSQLType(){return`halfvec(${this.dimensions})`}mapToDriverValue(t){return JSON.stringify(t)}mapFromDriverValue(t){return t.slice(1,-1).split(",").map(a=>Number.parseFloat(a))}};function eK(e,t){let{name:a,config:r}=$t(e,t);return new Rz(a,r)}var $z=class extends de{static[E]="PgSparseVectorBuilder";constructor(t,a){super(t,"string","PgSparseVector"),this.config.dimensions=a.dimensions}build(t){return new Pz(t,this.config)}},Pz=class extends ne{static[E]="PgSparseVector";dimensions=this.config.dimensions;getSQLType(){return`sparsevec(${this.dimensions})`}};function tK(e,t){let{name:a,config:r}=$t(e,t);return new $z(a,r)}var Dz=class extends de{static[E]="PgVectorBuilder";constructor(t,a){super(t,"array","PgVector"),this.config.dimensions=a.dimensions}build(t){return new Ez(t,this.config)}},Ez=class extends ne{static[E]="PgVector";dimensions=this.config.dimensions;getSQLType(){return`vector(${this.dimensions})`}mapToDriverValue(t){return JSON.stringify(t)}mapFromDriverValue(t){return t.slice(1,-1).split(",").map(a=>Number.parseFloat(a))}};function aK(e,t){let{name:a,config:r}=$t(e,t);return new Dz(a,r)}function nK(){return{bigint:NG,bigserial:RG,boolean:Kx,char:AG,cidr:$G,customType:PG,date:DG,doublePrecision:EG,inet:MG,integer:Eg,interval:OG,json:zG,jsonb:$o,line:UG,macaddr:jG,macaddr8:BG,numeric:FG,point:HG,geometry:qG,real:ZG,serial:GG,smallint:KG,smallserial:WG,text:ye,time:JG,timestamp:q1,uuid:QG,varchar:XG,bit:YG,halfvec:eK,sparsevec:tK,vector:aK}}var Mz=Symbol.for("drizzle:PgInlineForeignKeys"),rK=Symbol.for("drizzle:EnableRLS"),Bm=class extends $n{static[E]="PgTable";static Symbol=Object.assign({},$n.Symbol,{InlineForeignKeys:Mz,EnableRLS:rK});[Mz]=[];[rK]=!1;[$n.Symbol.ExtraConfigBuilder]=void 0;[$n.Symbol.ExtraConfigColumns]={}};function gbe(e,t,a,r,n=e){let o=new Bm(e,r,n),i=typeof t=="function"?t(nK()):t,s=Object.fromEntries(Object.entries(i).map(([d,f])=>{let m=f;m.setName(d);let h=m.build(o);return o[Mz].push(...m.buildForeignKeys(h,o)),[d,h]})),u=Object.fromEntries(Object.entries(i).map(([d,f])=>{let m=f;m.setName(d);let h=m.buildExtraConfigColumn(o);return[d,h]})),c=Object.assign(o,s);return c[$n.Symbol.Columns]=s,c[$n.Symbol.ExtraConfigColumns]=u,a&&(c[Bm.Symbol.ExtraConfigBuilder]=a),Object.assign(c,{enableRLS:()=>(c[Bm.Symbol.EnableRLS]=!0,c)})}var Fm=(e,t,a)=>gbe(e,t,a,void 0);function oK(...e){return e[0].columns?new Z1(e[0].columns,e[0].name):new Z1(e)}var Z1=class{static[E]="PgPrimaryKeyBuilder";columns;name;constructor(t,a){this.columns=t,this.name=a}build(t){return new Oz(t,this.columns,this.name)}},Oz=class{constructor(t,a,r){this.table=t,this.columns=a,this.name=r}static[E]="PgPrimaryKey";columns;name;getName(){return this.name??`${this.table[Bm.Symbol.Name]}_${this.columns.map(t=>t.name).join("_")}_pk`}};var G1=class{constructor(t,a){this.unique=t,this.name=a}static[E]="PgIndexBuilderOn";on(...t){return new Wx(t.map(a=>{if(Wn(a,Pn))return a;a=a;let r=new $g(a.name,!!a.keyAsName,a.columnType,a.indexConfig);return a.indexConfig=JSON.parse(JSON.stringify(a.defaultConfig)),r}),this.unique,!1,this.name)}onOnly(...t){return new Wx(t.map(a=>{if(Wn(a,Pn))return a;a=a;let r=new $g(a.name,!!a.keyAsName,a.columnType,a.indexConfig);return a.indexConfig=a.defaultConfig,r}),this.unique,!0,this.name)}using(t,...a){return new Wx(a.map(r=>{if(Wn(r,Pn))return r;r=r;let n=new $g(r.name,!!r.keyAsName,r.columnType,r.indexConfig);return r.indexConfig=JSON.parse(JSON.stringify(r.defaultConfig)),n}),this.unique,!0,this.name,t)}},Wx=class{static[E]="PgIndexBuilder";config;constructor(t,a,r,n,o="btree"){this.config={name:n,columns:t,unique:a,only:r,method:o}}concurrently(){return this.config.concurrently=!0,this}with(t){return this.config.with=t,this}where(t){return this.config.where=t,this}build(t){return new zz(this.config,t)}},zz=class{static[E]="PgIndex";config;constructor(t,a){this.config={...t,table:a}}};function Po(e){return new G1(!1,e)}function Jx(e){return new G1(!0,e)}var Tr=e=>q1(e,{withTimezone:!0}),iK=l.enum(["channel","dm","group","local_conversation","thread","web_session"]),vbe=Fm("junior_destinations",{id:ye("id").primaryKey(),provider:ye("provider").notNull(),providerTenantId:ye("provider_tenant_id").notNull().default(""),providerDestinationId:ye("provider_destination_id").notNull(),kind:ye("kind").$type().notNull(),parentDestinationId:ye("parent_destination_id"),displayName:ye("display_name"),visibility:ye("visibility").$type().notNull().default("unknown"),metadata:$o("metadata_json"),createdAt:Tr("created_at").notNull(),updatedAt:Tr("updated_at").notNull()},e=>[Jx("junior_destinations_provider_destination_uidx").on(e.provider,e.providerTenantId,e.providerDestinationId),Po("junior_destinations_provider_kind_idx").on(e.provider,e.kind)]),ybe=Fm("junior_users",{id:ye("id").primaryKey(),primaryEmail:ye("primary_email").notNull(),primaryEmailNormalized:ye("primary_email_normalized").notNull(),displayName:ye("display_name"),timezone:ye("timezone"),isAdmin:Kx("is_admin").notNull().default(!1),createdAt:Tr("created_at").notNull(),updatedAt:Tr("updated_at").notNull()},e=>[Jx("junior_users_primary_email_normalized_uidx").on(e.primaryEmailNormalized)]),Uz=Fm("junior_identities",{id:ye("id").primaryKey(),kind:ye("kind").$type().notNull(),provider:ye("provider").notNull(),providerTenantId:ye("provider_tenant_id").notNull().default(""),providerSubjectId:ye("provider_subject_id").notNull(),displayName:ye("display_name"),handle:ye("handle"),email:ye("email"),avatarUrl:ye("avatar_url"),metadata:$o("metadata_json"),createdAt:Tr("created_at").notNull(),updatedAt:Tr("updated_at").notNull(),userId:ye("user_id").references(()=>ybe.id),emailNormalized:ye("email_normalized"),emailVerified:Kx("email_verified").notNull().default(!1)},e=>[Jx("junior_identities_provider_subject_uidx").on(e.provider,e.providerTenantId,e.providerSubjectId),Po("junior_identities_user_idx").on(e.userId),Po("junior_identities_verified_email_idx").on(e.emailNormalized).where(nu`${e.emailVerified} = true AND ${e.emailNormalized} IS NOT NULL`),Po("junior_identities_kind_provider_idx").on(e.kind,e.provider)]),Hm=Fm("junior_conversations",{conversationId:ye("conversation_id").primaryKey(),schemaVersion:Eg("schema_version").notNull().default(1),source:ye("source").$type(),sessionSource:$o("source_json").$type(),location:$o("location_json").$type(),destinationId:ye("destination_id").references(()=>vbe.id),destination:$o("destination_json").$type(),actorIdentityId:ye("actor_identity_id").references(()=>Uz.id),creatorIdentityId:ye("creator_identity_id").references(()=>Uz.id),credentialSubjectIdentityId:ye("credential_subject_identity_id").references(()=>Uz.id),actor:$o("actor_json").$type(),channelName:ye("channel_name"),title:ye("title"),createdAt:Tr("created_at").notNull(),lastActivityAt:Tr("last_activity_at").notNull(),updatedAt:Tr("updated_at").notNull(),executionUpdatedAt:Tr("execution_updated_at"),executionStatus:ye("execution_status").$type().notNull(),runId:ye("run_id"),lastCheckpointAt:Tr("last_checkpoint_at"),lastEnqueuedAt:Tr("last_enqueued_at"),parentConversationId:ye("parent_conversation_id").references(()=>Hm.conversationId),forkedFromConversationId:ye("forked_from_conversation_id").references(()=>Hm.conversationId,{onDelete:"set null"}),rootConversationId:ye("root_conversation_id").references(()=>Hm.conversationId),transcriptPurgedAt:Tr("transcript_purged_at"),stoppedAt:Tr("stopped_at"),durationMs:Eg("duration_ms").notNull().default(0),usage:$o("usage_json").$type(),executionDurationMs:Eg("execution_duration_ms").notNull().default(0),executionUsage:$o("execution_usage_json").$type(),metricRunId:ye("metric_run_id"),legacyArchivedAt:Tr("archived_at")},e=>[Po("junior_conversations_last_activity_idx").on(e.lastActivityAt.desc(),e.conversationId),Po("junior_conversations_active_idx").using("btree",nu`coalesce(${e.executionUpdatedAt}, ${e.updatedAt})`,e.conversationId).where(nu`${e.executionStatus} <> 'idle'`),Po("junior_conversations_destination_activity_idx").on(e.destinationId,e.lastActivityAt.desc()),Po("junior_conversations_actor_activity_idx").on(e.actorIdentityId,e.lastActivityAt.desc()),Po("junior_conversations_parent_idx").on(e.parentConversationId),Po("junior_conversations_forked_from_idx").on(e.forkedFromConversationId),Po("junior_conversations_root_idx").on(e.rootConversationId)]);var sK=["pending","running","paused","blocked","completed","failed","stopped"];var DFe=Fm("junior_agent_bindings",{parentConversationId:ye("parent_conversation_id").notNull().references(()=>Hm.conversationId),name:ye("name").notNull(),childConversationId:ye("child_conversation_id").notNull().references(()=>Hm.conversationId)},e=>[oK({columns:[e.parentConversationId,e.name]}),Jx("junior_agent_bindings_child_idx").on(e.childConversationId)]),EFe=Fm("junior_agent_invocations",{invocationId:ye("invocation_id").primaryKey(),parentConversationId:ye("parent_conversation_id").notNull().references(()=>Hm.conversationId),childConversationId:ye("child_conversation_id").notNull().references(()=>Hm.conversationId),agentName:ye("agent_name"),input:ye("input").notNull(),title:ye("title"),actor:$o("actor_json").$type().notNull(),credentialContext:$o("credential_context_json").$type(),source:$o("source_json").$type().notNull(),destination:$o("destination_json").$type().notNull(),destinationVisibility:ye("destination_visibility").$type(),modelProfile:ye("model_profile").$type(),reasoningLevel:ye("reasoning_level").$type(),parentToolCallId:ye("parent_tool_call_id"),status:ye("status").$type().notNull(),mailboxStatus:ye("mailbox_status").$type().notNull(),parentMailboxStatus:ye("parent_mailbox_status").$type(),result:ye("result"),errorMessage:ye("error_message"),createdAt:Tr("created_at").notNull(),updatedAt:Tr("updated_at").notNull(),terminalAt:Tr("terminal_at")},e=>[Po("junior_agent_invocations_child_idx").on(e.childConversationId),Po("junior_agent_invocations_mailbox_idx").on(e.mailboxStatus,e.createdAt),Po("junior_agent_invocations_parent_mailbox_idx").on(e.parentMailboxStatus,e.terminalAt)]);var bbe=l.object({error:l.string().min(1)}).strict(),xbe=l.object({inboundMessageId:l.string().min(1),text:l.string().min(1)}).strict(),Fz=l.object({conversationId:l.string().min(1),status:l.enum(["no_work","requested"]),stoppedInboundMessageIds:l.array(l.string().min(1)),stoppedMessages:l.array(xbe)}).strict(),uK=l.object({auxiliaryCosts:E1.optional(),childAgentTotals:D1.optional(),conversationId:l.string().min(1),cumulativeDurationMs:l.number(),cumulativeUsage:Bx.optional(),error:l.string().min(1).optional(),name:l.string().min(1).optional(),redacted:l.literal(!0).optional(),status:l.enum(sK),task:l.string().optional(),title:l.string().min(1).optional(),updatedAt:l.string().datetime()}).strict().superRefine((e,t)=>{e.task===void 0==(e.redacted!==!0)&&t.addIssue({code:"custom",message:"child agent task must be text or explicitly redacted"}),e.redacted&&(e.name||e.title||e.error)&&t.addIssue({code:"custom",message:"redacted child agents must not expose a name, title, or error"})}),Hz=l.object({agents:l.array(uK),conversationId:l.string().min(1)}).strict(),Q1=l.object({closed:l.number().int().nonnegative(),costUsd:l.number().nonnegative().optional(),created:l.number().int().nonnegative(),medianCostUsd:l.number().nonnegative().optional(),medianMergeTimeMs:l.number().nonnegative().optional(),merged:l.number().int().nonnegative(),mergeRate:l.number().min(0).max(1).optional(),open:l.number().int().nonnegative()}).strict(),Sbe=l.string().regex(/^\d{4}-\d{2}-\d{2}(T\d{2})?$/),ou=l.object({closed:l.number().int().nonnegative(),created:l.number().int().nonnegative(),date:Sbe,merged:l.number().int().nonnegative()}).strict(),cK=l.object({closed:l.number().int().nonnegative(),created:l.number().int().nonnegative(),id:l.string().uuid(),medianCostUsd:l.number().nonnegative().optional(),merged:l.number().int().nonnegative(),mergeRate:l.number().min(0).max(1).optional(),name:l.string().min(1),open:l.number().int().nonnegative(),provider:l.string().min(1),url:l.string().url().optional()}).strict(),Vz=l.object({closedAt:l.string().optional(),id:l.string().uuid(),mergedAt:l.string().optional(),number:l.number().int().positive(),openedAt:l.string(),provider:l.string().min(1),repository:l.string().min(1),state:Ox,title:l.string().optional(),url:l.string().url().optional()}).strict(),qz=l.object({activityDays:l.array(ou),activityHours:l.array(ou).optional(),activitySixHours:l.array(ou).optional(),changes:l.array(Vz),generatedAt:l.string(),repositories:l.array(cK),summary:Q1,windowEnd:l.string(),windowStart:l.string()}).strict(),wbe=l.object({repositoryId:l.string().uuid()}).strict(),Zz=l.object({activityDays:l.array(ou),activityHours:l.array(ou).optional(),activitySixHours:l.array(ou).optional(),changes:l.array(Vz),generatedAt:l.string(),repository:l.object({id:l.string().uuid(),name:l.string().min(1),provider:l.string().min(1),url:l.string().url().optional()}).strict(),summary:Q1,windowEnd:l.string(),windowStart:l.string(),workspaces:l.array(l.object({id:l.string().min(1),name:l.string().min(1)}).strict())}).strict(),Gz=l.object({activityDays:l.array(ou),activityHours:l.array(ou).optional(),activitySixHours:l.array(ou).optional(),generatedAt:l.string(),summary:Q1,windowEnd:l.string(),windowStart:l.string()}).strict(),dK=l.object({provider:l.string(),displayName:l.string(),description:l.string(),account:l.object({label:l.string(),url:l.string().optional()}).strict().optional(),connected:l.boolean()}).strict(),Kz=l.object({connections:l.array(dK)}).strict(),Cbe=l.object({provider:l.string().regex(/^[a-z][a-z0-9-]*$/).max(64)}).strict(),Wz=l.object({authorizationUrl:l.string().url()}).strict(),Jz=l.object({disconnected:l.literal(!0)}).strict(),W1=l.object({active:l.number(),conversations:l.number(),date:l.string(),durationMs:l.number(),failed:l.number(),tokens:l.number().optional()}).strict();var kbe=l.object({locationId:l.string().min(1)}).strict(),fK=Um.extend({id:l.string(),firstSeenAt:l.string(),kind:iK,lastSeenAt:l.string(),provider:l.string(),providerDestinationId:l.string(),visibility:l.literal("public")}).strict(),Ibe=Um.extend({actor:zm}).strict(),Lbe=l.string().regex(/^\d{4}-\d{2}-\d{2}(T\d{2})?$/),J1=l.object({date:Lbe,privateConversations:l.number(),publicConversations:l.number()}).strict(),Qz=l.object({activityDays:l.array(J1),activityHours:l.array(J1).optional(),activitySixHours:l.array(J1).optional(),generatedAt:l.string(),locations:l.array(fK),privateActivity:Um,source:l.literal("conversation_index"),windowEnd:l.string(),windowStart:l.string()}).strict(),Xz=fK.extend({activityDays:l.array(W1),activityHours:l.array(W1).optional(),activitySixHours:l.array(W1).optional(),actors:l.array(Ibe),generatedAt:l.string(),recentConversations:l.array(Ag),source:l.literal("conversation_index"),windowEnd:l.string(),windowStart:l.string()}).strict(),Tbe=l.object({email:l.string().trim().min(1)}).strict(),lK=Um.omit({costUsd:!0}),mK=l.string().regex(/^\d{4}-\d{2}-\d{2}(T\d{2})?$/),jz=l.object({active:l.number(),conversations:l.number(),costUsd:l.number().optional(),date:mK,durationMs:l.number(),failed:l.number(),tokens:l.number().optional()}).strict(),Bz=l.object({activePeople:l.number(),conversations:l.number(),date:mK}).strict(),pK=l.object({active:l.number(),activeDays:l.number(),conversations:l.number(),durationMs:l.number(),failed:l.number(),tokens:l.number().optional()}).strict(),K1=l.object({conversations:l.number().int().nonnegative(),costUsd:l.number().finite().nonnegative(),durationMs:l.number().finite().nonnegative(),priorCostUsd:l.number().finite().nonnegative()}).strict(),_be=l.object({1:K1,7:K1,30:K1,90:K1}).strict(),hK=zm.extend({email:l.string().min(1)}).strict(),Nbe=pK.extend({firstSeenAt:l.string(),lastSeenAt:l.string(),actor:hK,windows:_be}).strict(),Yz=l.object({activityDays:l.array(Bz),activityHours:l.array(Bz).optional(),activitySixHours:l.array(Bz).optional(),generatedAt:l.string(),people:l.array(Nbe),source:l.literal("conversation_index"),windowEnd:l.string(),windowStart:l.string()}).strict(),e4=l.object({activityDays:l.array(jz),activityHours:l.array(jz).optional(),activitySixHours:l.array(jz).optional(),generatedAt:l.string(),locations:l.array(lK),recentConversations:l.array(Ag),actor:hK,source:l.literal("conversation_index"),surfaces:l.array(lK),totals:pK,windowEnd:l.string(),windowStart:l.string()}).strict(),t4=l.object({generatedAt:l.string(),sevenDaysUsd:l.number().finite().nonnegative(),source:l.literal("conversation_index"),thirtyDaysUsd:l.number().finite().nonnegative(),windowEnd:l.string(),windowStart:l.string()}).strict(),a4=l.object({id:l.string().uuid(),name:l.string(),tokenSuffix:l.string(),createdAt:l.string().datetime(),expiresAt:l.string().datetime(),lastUsedAt:l.string().datetime().nullable()}).strict(),n4=l.object({tokens:l.array(a4)}).strict(),Rbe=l.object({name:l.string().trim().min(1).max(80)}).strict(),r4=a4.extend({token:l.string().startsWith("jr_pat_")}).strict(),Abe=l.object({id:l.string().uuid()}).strict(),$be=l.object({revoked:l.literal(!0)}).strict(),Pbe=l.object({provider:l.string(),repo:l.string()}).strict(),gK=l.object({provider:l.string(),repo:l.string(),checkoutPath:l.string()}).strict(),Dbe=l.object({id:l.string(),generatedAt:l.iso.datetime(),buildDurationMs:l.number().int().nonnegative(),sizeBytes:l.number().int().nonnegative().nullable()}).strict(),vK=l.object({id:l.string(),generatedAt:l.iso.datetime(),buildDurationMs:l.number().int().nonnegative(),dependencyCount:l.number().int().nonnegative()}).strict(),Mg=l.object({id:l.string().uuid(),name:l.string(),setupScript:l.string(),repos:l.array(gK),snapshot:Dbe.nullable()}).strict(),o4=l.object({baselineSnapshot:vK.nullable(),workspaces:l.array(Mg)}).strict(),Ebe=l.object({name:l.string(),setupScript:l.string().optional(),repos:l.array(Pbe)}).strict(),Mbe=l.object({id:l.string().uuid()}).strict(),Obe=l.object({deleted:l.literal(!0)}).strict(),yK=l.object({count:l.number().int().nonnegative(),date:l.string(),metric:l.string().min(1),name:l.string().min(1),namespace:l.string().min(1)}).strict(),i4=l.object({generatedAt:l.string().datetime(),stats:l.array(yK),windowEnd:l.string(),windowStart:l.string()}).strict();var Do=l.string().trim().min(1).max(160),Og=l.number().int().nonnegative(),zbe=l.discriminatedUnion("type",[l.strictObject({type:l.literal("code_change"),author:Do.optional(),sourceBranch:Do.optional(),targetBranch:Do.optional(),reviewers:l.array(Do).max(5).optional(),review:l.enum(["required","approved","changes_requested"]).optional(),checks:l.strictObject({passed:Og,failed:Og,pending:Og}).optional(),mergeable:l.boolean().optional(),changedFiles:Og.optional(),additions:Og.optional(),deletions:Og.optional()}),l.strictObject({type:l.literal("task"),assignees:l.array(Do).max(5).optional(),priority:Do.optional(),project:Do.optional(),cycle:Do.optional(),dueDate:l.iso.date().optional(),labels:l.array(Do).max(5).optional()}),l.strictObject({type:l.literal("deployment"),project:Do.optional(),environment:Do.optional(),revision:Do.optional(),branch:Do.optional()}),l.strictObject({type:l.literal("calendar_event"),when:Do.optional(),attendees:l.array(Do).max(5).optional()})]);function xK(e){if(!e)return[];let t=[],a=n=>n?.length?`${n.join(", ")}${n.length===5?" (up to 5 shown)":""}`:void 0;function r(n,o,i){i!==void 0&&i!==""&&t.push({key:n,label:o,value:String(i)})}switch(e.type){case"code_change":r("sourceBranch","Branch",e.sourceBranch);break;case"task":r("assignees","Assignees",e.assignees?.length===0?"Unassigned":a(e.assignees)),r("priority","Priority",e.priority),r("project","Project",e.project),r("cycle","Cycle",e.cycle),r("dueDate","Due",e.dueDate),r("labels","Labels",a(e.labels));break;case"deployment":r("environment","Environment",e.environment),r("project","Project",e.project),r("revision","Revision",e.revision),r("branch","Branch",e.branch);break;case"calendar_event":r("when","When",e.when),r("attendees","Attendees",a(e.attendees));break}return t.slice(0,4)}var Y1=l.enum(["task","code_change","automation","deployment","calendar_event","item"]),Ube={task:"Ticket",code_change:"Code change",automation:"Automation",deployment:"Deployment",calendar_event:"Calendar event",item:"Item"};function Rs(e){let t=e.objectType==="item"&&e.facts?.type==="deployment"?"deployment":e.objectType,a=e.status?.toLowerCase(),r={task:"issue-opened",code_change:"git-pull-request",automation:"workflow",deployment:"rocket",calendar_event:"calendar",item:"package"}[t],n=t==="automation"?"info":"neutral";return t==="code_change"?(a==="draft"&&(r="git-pull-request-draft"),a==="closed"&&(r="git-pull-request-closed",n="danger"),a==="merged"&&(r="git-merge",n="accent"),a==="open"&&(n="success")):t==="task"?(a==="closed"&&(r="issue-closed",n="accent"),a==="open"&&(n="success")):t==="deployment"&&((a==="ready"||a==="succeeded")&&(n="success"),(a==="error"||a==="failed")&&(n="danger"),(a==="building"||a==="in_progress")&&(n="info")),(a==="warning"||a==="blocked")&&(n="warning"),{icon:r,tone:n,label:Ube[t]}}function SK(e){return`/_junior/dashboard/object-icons/v1/${e}.png`}var l4=l.object({kind:l.literal("object"),key:l.string().trim().min(1).max(256),label:l.string().trim().min(1).max(256),objectType:Y1,title:l.string().trim().min(1).max(512),url:l.url().max(2048).refine(e=>["http:","https:"].includes(new URL(e).protocol)).nullable(),description:l.string().max(4e3).optional(),status:l.string().trim().min(1).max(100).optional(),trigger:l.string().max(4e3).optional(),warning:l.string().max(1e3).optional(),displayType:l.string().trim().min(1).max(80).optional(),sourceUpdatedAt:l.iso.datetime({offset:!0}).optional(),facts:zbe.refine(e=>new TextEncoder().encode(JSON.stringify(e)).length<=4096,"Object facts must not exceed 4 KiB").optional()}).strict().refine(e=>!e.facts||(e.facts.type==="deployment"?e.objectType==="deployment"||e.objectType==="item":e.facts.type===e.objectType),"Object facts must match the object type"),aHe=l4.safeExtend({plugin:l.string().min(1)}),wK={"issue-opened":["M8 9.5a1.5 1.5 0 1 0 0-3 1.5 1.5 0 0 0 0 3Z","M8 0a8 8 0 1 1 0 16A8 8 0 0 1 8 0ZM1.5 8a6.5 6.5 0 1 0 13 0 6.5 6.5 0 0 0-13 0Z"],"issue-closed":["M11.28 6.78a.75.75 0 0 0-1.06-1.06L7.25 8.69 5.78 7.22a.75.75 0 0 0-1.06 1.06l2 2a.75.75 0 0 0 1.06 0l3.5-3.5Z","M16 8A8 8 0 1 1 0 8a8 8 0 0 1 16 0Zm-1.5 0a6.5 6.5 0 1 0-13 0 6.5 6.5 0 0 0 13 0Z"],"git-pull-request":["M1.5 3.25a2.25 2.25 0 1 1 3 2.122v5.256a2.251 2.251 0 1 1-1.5 0V5.372A2.25 2.25 0 0 1 1.5 3.25Zm5.677-.177L9.573.677A.25.25 0 0 1 10 .854V2.5h1A2.5 2.5 0 0 1 13.5 5v5.628a2.251 2.251 0 1 1-1.5 0V5a1 1 0 0 0-1-1h-1v1.646a.25.25 0 0 1-.427.177L7.177 3.427a.25.25 0 0 1 0-.354ZM3.75 2.5a.75.75 0 1 0 0 1.5.75.75 0 0 0 0-1.5Zm0 9.5a.75.75 0 1 0 0 1.5.75.75 0 0 0 0-1.5Zm8.25.75a.75.75 0 1 0 1.5 0 .75.75 0 0 0-1.5 0Z"],"git-pull-request-draft":["M3.25 1A2.25 2.25 0 0 1 4 5.372v5.256a2.251 2.251 0 1 1-1.5 0V5.372A2.251 2.251 0 0 1 3.25 1Zm9.5 14a2.25 2.25 0 1 1 0-4.5 2.25 2.25 0 0 1 0 4.5ZM2.5 3.25a.75.75 0 1 0 1.5 0 .75.75 0 0 0-1.5 0ZM3.25 12a.75.75 0 1 0 0 1.5.75.75 0 0 0 0-1.5Zm9.5 0a.75.75 0 1 0 0 1.5.75.75 0 0 0 0-1.5ZM14 7.5a1.25 1.25 0 1 1-2.5 0 1.25 1.25 0 0 1 2.5 0Zm0-4.25a1.25 1.25 0 1 1-2.5 0 1.25 1.25 0 0 1 2.5 0Z"],"git-pull-request-closed":["M3.25 1A2.25 2.25 0 0 1 4 5.372v5.256a2.251 2.251 0 1 1-1.5 0V5.372A2.251 2.251 0 0 1 3.25 1Zm9.5 5.5a.75.75 0 0 1 .75.75v3.378a2.251 2.251 0 1 1-1.5 0V7.25a.75.75 0 0 1 .75-.75Zm-2.03-5.273a.75.75 0 0 1 1.06 0l.97.97.97-.97a.748.748 0 0 1 1.265.332.75.75 0 0 1-.205.729l-.97.97.97.97a.751.751 0 0 1-.018 1.042.751.751 0 0 1-1.042.018l-.97-.97-.97.97a.749.749 0 0 1-1.275-.326.749.749 0 0 1 .215-.734l.97-.97-.97-.97a.75.75 0 0 1 0-1.06ZM2.5 3.25a.75.75 0 1 0 1.5 0 .75.75 0 0 0-1.5 0ZM3.25 12a.75.75 0 1 0 0 1.5.75.75 0 0 0 0-1.5Zm9.5 0a.75.75 0 1 0 0 1.5.75.75 0 0 0 0-1.5Z"],"git-merge":["M5.45 5.154A4.25 4.25 0 0 0 9.25 7.5h1.378a2.251 2.251 0 1 1 0 1.5H9.25A5.734 5.734 0 0 1 5 7.123v3.505a2.25 2.25 0 1 1-1.5 0V5.372a2.25 2.25 0 1 1 1.95-.218ZM4.25 13.5a.75.75 0 1 0 0-1.5.75.75 0 0 0 0 1.5Zm8.5-4.5a.75.75 0 1 0 0-1.5.75.75 0 0 0 0 1.5ZM5 3.25a.75.75 0 1 0 0 .005V3.25Z"],workflow:["M0 1.75C0 .784.784 0 1.75 0h3.5C6.216 0 7 .784 7 1.75v3.5A1.75 1.75 0 0 1 5.25 7H4v4a1 1 0 0 0 1 1h4v-1.25C9 9.784 9.784 9 10.75 9h3.5c.966 0 1.75.784 1.75 1.75v3.5A1.75 1.75 0 0 1 14.25 16h-3.5A1.75 1.75 0 0 1 9 14.25v-.75H5A2.5 2.5 0 0 1 2.5 11V7h-.75A1.75 1.75 0 0 1 0 5.25Zm1.75-.25a.25.25 0 0 0-.25.25v3.5c0 .138.112.25.25.25h3.5a.25.25 0 0 0 .25-.25v-3.5a.25.25 0 0 0-.25-.25Zm9 9a.25.25 0 0 0-.25.25v3.5c0 .138.112.25.25.25h3.5a.25.25 0 0 0 .25-.25v-3.5a.25.25 0 0 0-.25-.25Z"],rocket:["M14.064 0h.186C15.216 0 16 .784 16 1.75v.186a8.752 8.752 0 0 1-2.564 6.186l-.458.459c-.314.314-.641.616-.979.904v3.207c0 .608-.315 1.172-.833 1.49l-2.774 1.707a.749.749 0 0 1-1.11-.418l-.954-3.102a1.214 1.214 0 0 1-.145-.125L3.754 9.816a1.218 1.218 0 0 1-.124-.145L.528 8.717a.749.749 0 0 1-.418-1.11l1.71-2.774A1.748 1.748 0 0 1 3.31 4h3.204c.288-.338.59-.665.904-.979l.459-.458A8.749 8.749 0 0 1 14.064 0ZM8.938 3.623h-.002l-.458.458c-.76.76-1.437 1.598-2.02 2.5l-1.5 2.317 2.143 2.143 2.317-1.5c.902-.583 1.74-1.26 2.499-2.02l.459-.458a7.25 7.25 0 0 0 2.123-5.127V1.75a.25.25 0 0 0-.25-.25h-.186a7.249 7.249 0 0 0-5.125 2.123ZM3.56 14.56c-.732.732-2.334 1.045-3.005 1.148a.234.234 0 0 1-.201-.064.234.234 0 0 1-.064-.201c.103-.671.416-2.273 1.15-3.003a1.502 1.502 0 1 1 2.12 2.12Zm6.94-3.935c-.088.06-.177.118-.266.175l-2.35 1.521.548 1.783 1.949-1.2a.25.25 0 0 0 .119-.213ZM3.678 8.116 5.2 5.766c.058-.09.117-.178.176-.266H3.309a.25.25 0 0 0-.213.119l-1.2 1.95ZM12 5a1 1 0 1 1-2 0 1 1 0 0 1 2 0Z"],calendar:["M4.75 0a.75.75 0 0 1 .75.75V2h5V.75a.75.75 0 0 1 1.5 0V2h1.25c.966 0 1.75.784 1.75 1.75v10.5A1.75 1.75 0 0 1 13.25 16H2.75A1.75 1.75 0 0 1 1 14.25V3.75C1 2.784 1.784 2 2.75 2H4V.75A.75.75 0 0 1 4.75 0ZM2.5 7.5v6.75c0 .138.112.25.25.25h10.5a.25.25 0 0 0 .25-.25V7.5Zm10.75-4H2.75a.25.25 0 0 0-.25.25V6h11V3.75a.25.25 0 0 0-.25-.25Z"],package:["m8.878.392 5.25 3.045c.54.314.872.89.872 1.514v6.098a1.75 1.75 0 0 1-.872 1.514l-5.25 3.045a1.75 1.75 0 0 1-1.756 0l-5.25-3.045A1.75 1.75 0 0 1 1 11.049V4.951c0-.624.332-1.201.872-1.514L7.122.392a1.75 1.75 0 0 1 1.756 0ZM7.875 1.69l-4.63 2.685L8 7.133l4.755-2.758-4.63-2.685a.248.248 0 0 0-.25 0ZM2.5 5.677v5.372c0 .09.047.171.125.216l4.625 2.683V8.432Zm6.25 8.271 4.625-2.683a.25.25 0 0 0 .125-.216V5.677L8.75 8.432Z"]};function jbe(e){try{let t=new URL(e).protocol;return t==="http:"||t==="https:"}catch{return!1}}var Bbe=l.object({kind:l.literal("resource_link"),objectType:Y1.optional(),key:l.string().trim().min(1).max(256),label:l.string().trim().min(1).max(256),url:l.string().url().max(2048).refine(jbe,"URL must use HTTP or HTTPS."),description:l.string().trim().min(1).max(512).optional(),status:l.enum(["open","draft","closed","merged","warning"]).optional()}).strict(),rHe=l.discriminatedUnion("kind",[Bbe,l4]),Fbe=l.enum(["circle-dot","circle-dashed","circle-x","git-merge","git-pull-request","triangle-alert"]),oHe=l.object({icon:Fbe.optional(),objectType:Y1.optional(),status:l.string().trim().min(1).max(100).optional(),key:l.string().trim().min(1).max(256),label:l.string().trim().min(1).max(256)}).strict(),Hbe=l.enum(["closed","merged","open"]),sHe=l.object({closedAt:l.date().optional(),conversationIds:l.array(l.string().min(1)).default([]),mergedAt:l.date().optional(),number:l.number().int().positive(),openedAt:l.date(),providerId:l.string().min(1),repository:l.object({name:l.string().min(1),providerId:l.string().min(1),url:l.string().url().optional()}).strict(),state:Hbe,title:l.string().min(1).optional(),updatedAt:l.date(),url:l.string().url().optional()}).strict(),uHe=l.string().trim().min(1).max(64).regex(/^[a-z][a-z0-9_]*$/),Vbe=l.enum(["activity","brain","calendar","check","database","info","key","link","sparkles","warning"]),qbe=l.object({content:l.string().min(1).max(32*1024).optional(),description:l.string().trim().min(1).max(2e3).optional(),metadata:l.array(l.string().trim().min(1).max(120)).max(8).optional(),title:l.string().trim().min(1).max(4e3)}).strict(),cHe=l.object({details:l.array(qbe).max(100).optional(),icon:Vbe.optional(),preview:l.string().trim().min(1).max(500).optional(),title:l.string().trim().min(1).max(120)}).strict();var eI=l.string().regex(/^T[A-Z0-9]+$/),u4=l.string().regex(/^(C|G|D)[A-Z0-9]+$/),CK=l.string().regex(/^local:[a-z0-9_-]+:[a-z0-9][a-z0-9_-]*$/),Zbe=l.string().min(1).refine(e=>e===e.trim()&&e.toLowerCase()!=="unknown"),X1=Zbe,je=l.string().refine(e=>e.trim().length>0),lo=je.refine(e=>e===e.trim()),Gbe=l.object({id:je,provider:lo}).strict(),Kbe=Gbe.extend({provider:l.literal("slack"),teamId:eI,channelId:u4,threadTs:lo.optional()}).strict(),fHe=l.discriminatedUnion("provider",[Kbe]),mHe=l.enum(["slack","local"]),kK=l.enum(["public","private"]),Wbe=l.enum(["public","private"]),Jbe=l.object({platform:l.literal("slack"),teamId:eI,channelId:u4,threadTs:lo.optional()}).strict(),c4=Jbe,Qbe=l.object({platform:l.literal("local"),conversationId:CK}).strict(),Xbe=l.discriminatedUnion("platform",[c4,Qbe]),pHe=l.object({action:l.literal("send_message"),destination:c4}).strict(),Ybe=l.object({kind:l.literal("slack"),teamId:eI,channelId:u4,visibility:kK,messageTs:je.optional(),threadTs:je.optional()}).strict(),exe=l.object({kind:l.literal("local"),visibility:l.literal("private"),conversationId:CK}).strict(),txe=l.object({kind:l.literal("web"),visibility:kK,conversationId:lo}).strict(),axe=l.object({kind:l.literal("event"),eventKey:lo,eventType:lo,identifier:lo,namespace:lo}).strict(),nxe=l.object({kind:l.literal("scheduled_automation")}).strict(),rxe=l.object({kind:l.literal("event_automation")}).strict(),oxe=l.object({kind:l.literal("plugin_dispatch")}).strict(),ixe=l.object({kind:l.literal("agent_invocation")}).strict(),sxe=l.discriminatedUnion("kind",[Ybe,exe,txe,axe,nxe,rxe,oxe,ixe]);function lxe(e){if(!e||typeof e!="object"||Array.isArray(e))return e;let t=e;if("kind"in t){let o={event_task:"event_automation",resource_event:"event",scheduled_task:"scheduled_automation"},i=typeof t.kind=="string"?o[t.kind]:void 0;return i?{...t,kind:i}:e}if(t.platform!=="slack"&&t.platform!=="local"&&t.platform!=="web")return e;let{location:a,platform:r,...n}=t;return{...n,kind:r}}var uxe=l.preprocess(lxe,sxe),cxe=l.discriminatedUnion("allowedWhen",[l.object({type:l.literal("user"),userId:X1,allowedWhen:l.literal("private-direct-conversation")}).strict(),l.object({type:l.literal("user"),userId:X1,allowedWhen:l.literal("scheduled-automation"),taskId:lo}).strict()]),d4={email:je.optional(),fullName:je.optional(),userId:X1,userName:je.optional()},dxe=l.object({...d4,platform:l.literal("slack"),teamId:eI}).strict(),fxe=l.object({...d4,platform:l.literal("local")}).strict(),mxe=l.object({...d4,platform:l.literal("web")}).strict(),pxe=l.object({platform:l.literal("system"),name:X1}).strict(),s4=l.discriminatedUnion("platform",[dxe,fxe,mxe,pxe]),hxe=l.object({displayName:je.optional(),handle:je.optional(),id:lo,provider:lo,providerSubjectId:lo,providerTenantId:lo.optional()}).strict(),hHe=l.object({displayName:je.optional(),email:je.max(320),id:lo,identities:l.array(hxe).max(100),isAdmin:l.literal(!0).optional()}).strict(),gxe=l.record(l.string(),l.string()).superRefine((e,t)=>{let a=Object.entries(e);if(a.length>20){t.addIssue({code:l.ZodIssueCode.custom,message:"Dispatch metadata has too many keys"});return}for(let[r,n]of a){if(!r.trim()){t.addIssue({code:l.ZodIssueCode.custom,message:"Dispatch metadata values must be strings",path:[r]});continue}r.length>128&&t.addIssue({code:l.ZodIssueCode.custom,message:"Dispatch metadata key exceeds the maximum length",path:[r]}),/[\r\n]/.test(r)&&t.addIssue({code:l.ZodIssueCode.custom,message:"Dispatch metadata keys must be single-line strings",path:[r]}),/[\r\n]/.test(n)&&t.addIssue({code:l.ZodIssueCode.custom,message:"Dispatch metadata values must be single-line strings",path:[r]}),n.length>512&&t.addIssue({code:l.ZodIssueCode.custom,message:"Dispatch metadata value exceeds the maximum length",path:[r]})}}),vxe=l.object({label:lo.pipe(l.string().max(48)).refine(e=>!/[\r\n]/.test(e)),detail:lo.pipe(l.string().max(128)).refine(e=>!/[\r\n]/.test(e)).optional()}).strict(),gHe=l.object({idempotencyKey:je.pipe(l.string().max(512)),credentialSubject:cxe.optional(),destination:c4,destinationVisibility:Wbe,input:je.pipe(l.string().max(32e3)),metadata:gxe.optional(),replyAttribution:vxe.optional()}).strict();var yxe=l.string().trim().min(1).max(64).regex(/^[a-z][a-z0-9_-]*$/),yHe=l.object({text:l.string().trim().min(1).max(8e3)}).strict(),bHe=l.object({kind:yxe,version:l.number().int().positive(),content:l.record(l.string(),l.unknown())}).strict();var bxe=4e3,xxe=8e3,zg=32,bK=4e3,Sxe=1e3,wxe=l.record(l.string(),l.unknown()).superRefine((e,t)=>{Object.keys(e).length>zg&&t.addIssue({code:"custom",message:`Event data may include at most ${zg} keys.`}),new TextEncoder().encode(JSON.stringify(e)).byteLength>bK&&t.addIssue({code:"custom",message:`Event data may be at most ${bK} JSON bytes.`})}),Vm=l.string().regex(/^[a-z][a-z0-9_-]*(?:\.[a-z][a-z0-9_-]*)+$/).describe("Canonical dotted event type, such as issue.closed or pull_request.review.changes_requested."),IK=l.string().regex(/^[a-z][a-z0-9_]*$/).describe("Canonical plugin-defined resource type, such as issue or pull_request."),LK=/^[a-z][a-zA-Z0-9]*$/,Cxe=l.object({kind:l.enum(["boolean","string","number"]),description:l.string().trim().min(1).max(200),enum:l.array(l.string().min(1)).min(1).optional()}).strict().superRefine((e,t)=>{e.enum&&e.kind!=="string"&&t.addIssue({code:"custom",message:'Event match field enum requires kind "string".',path:["enum"]})}),kxe=l.record(l.string().regex(LK),Cxe).superRefine((e,t)=>{Object.keys(e).length>zg&&t.addIssue({code:"custom",message:`Event match keys may include at most ${zg} keys.`})}),SHe=l.record(l.string().regex(LK),l.union([l.boolean(),l.number().finite(),l.string().min(1),l.array(l.union([l.number().finite(),l.string().min(1)])).min(1)])).superRefine((e,t)=>{Object.keys(e).length>zg&&t.addIssue({code:"custom",message:`Event match may include at most ${zg} keys.`});for(let[a,r]of Object.entries(e))Array.isArray(r)&&r.some(n=>typeof n=="boolean")&&t.addIssue({code:"custom",message:`Event match field "${a}" cannot use a boolean list.`,path:[a]})});var Ixe=l.object({format:l.string().trim().min(1).max(200),pattern:l.instanceof(RegExp)}).strict(),Lxe=l.object({type:IK,identifier:Ixe.optional(),supportedEvents:l.array(Vm).min(1),suggestedEvents:l.array(Vm).optional(),matchFields:kxe.optional(),guidance:l.record(Vm,l.string().trim().min(1).max(Sxe)).optional()}).strict().superRefine((e,t)=>{let a=new Set;e.supportedEvents.forEach((n,o)=>{a.has(n)&&t.addIssue({code:"custom",message:`Duplicate supported event type "${n}".`,path:["supportedEvents",o]}),a.add(n)});for(let n of Object.keys(e.guidance??{}))a.has(n)||t.addIssue({code:"custom",message:`Guidance event type "${n}" is not supported.`,path:["guidance",n]});let r=new Set;e.suggestedEvents?.forEach((n,o)=>{r.has(n)&&t.addIssue({code:"custom",message:`Duplicate suggested event type "${n}".`,path:["suggestedEvents",o]}),a.has(n)||t.addIssue({code:"custom",message:`Suggested event type "${n}" is not supported.`,path:["suggestedEvents",o]}),r.add(n)})}),wHe=l.object({resourceTypes:l.array(Lxe).min(1),isEnabled:l.function({input:[],output:l.boolean()}).optional(),normalizeIdentifier:l.function({input:[l.string()],output:l.string()}).optional()}).strict().superRefine((e,t)=>{let a=new Set;e.resourceTypes.forEach((r,n)=>{a.has(r.type)&&t.addIssue({code:"custom",message:`Duplicate resource type "${r.type}".`,path:["resourceTypes",n,"type"]}),a.add(r.type)})});var CHe=l.object({identifier:l.string().min(1),label:l.string().min(1),namespace:l.string().min(1),suggestedEvents:l.array(Vm).optional(),supportedEvents:l.array(Vm),type:IK}).strict(),kHe=l.object({events:l.array(Vm).min(1),id:l.string().min(1)}).strict(),Txe=l.union([l.object({provider:l.string().min(1),handle:l.string().min(1)}).strict(),l.object({email:l.string().trim().min(3)}).strict()]),_xe=l.object({objectType:Y1.optional(),eventKey:l.string().min(1),eventType:Vm,identifier:l.string().min(1),occurredAtMs:l.number().finite(),terminal:l.boolean().optional(),trustedSummary:l.string().min(1).transform(e=>e.slice(0,bxe)),data:wxe.optional(),untrustedText:l.string().transform(e=>e.slice(0,xxe)).optional(),people:l.array(Txe).max(20).optional()}).strict(),IHe=_xe.extend({namespace:l.string().min(1)}),Nxe=l.object({authority:l.enum(["instruction","context"]),actor:s4.optional()}).strict(),Rxe=l.discriminatedUnion("type",[l.object({type:l.literal("message"),role:l.enum(["user","assistant"]),text:l.string().min(1),provenance:Nxe.optional(),isRunActor:l.boolean().optional()}).strict(),l.object({type:l.literal("toolResult"),toolName:l.string().min(1),isError:l.boolean(),text:l.string().min(1).optional()}).strict()]),THe=l.object({actorUserId:l.string().min(1).optional(),completedAtMs:l.number().finite(),conversationId:l.string().min(1),destination:Xbe,locationId:l.string().min(1).optional(),actors:l.array(s4),actor:s4.optional(),runId:l.string().min(1),source:uxe,transcript:l.array(Rxe)}).strict();var NHe=l.discriminatedUnion("type",[l.object({type:l.literal("text"),text:l.string()}).strict(),l.object({type:l.literal("image"),data:l.string(),mimeType:l.string()}).strict()]),Axe=l.object({arguments:l.record(l.string(),l.unknown()),reason:l.string().min(1).optional()}).strict(),RHe=l.object({objectAnnotations:l.array(l4).optional(),target:l.string().min(1).optional(),truncated:l.boolean().optional(),continuation:Axe.optional()}).passthrough(),AHe=l.enum(["auto","review","approve"]);var PHe=l.object({auth:l.object({user:l.object({email:l.string().nullable().optional(),emailVerified:l.boolean().optional(),isAdmin:l.boolean(),name:l.string().nullable().optional()}).strict()}).strict(),pluginName:je}).strict(),$xe=l.string().regex(/^[a-z][a-z0-9-]*$/),Pxe=l.string().regex(/^[a-z][a-z0-9.-]*$/),Dxe=l.union([l.literal("read"),l.literal("write")]),TK=l.object({provider:$xe,scope:je.optional(),type:l.literal("oauth")}).strict(),_K=l.object({displayName:je.optional(),handle:je.optional(),id:je,label:je.optional(),url:je.optional()}).strict(),EHe=l.object({account:_K.optional(),accessToken:je,expiresAt:l.number().finite().optional(),refreshToken:je,refreshTokenExpiresAt:l.number().finite().optional(),scope:je.optional()}).strict(),MHe=l.object({access:Dxe,leaseScope:je.optional(),name:Pxe,reason:je.optional(),requirements:l.array(je).min(1).optional()}).strict(),Exe=l.object({domain:l.string().min(1),headers:l.record(l.string(),l.string()).refine(e=>Object.keys(e).length>0)}).strict(),Mxe=l.object({account:_K.optional(),authorization:TK.optional(),expiresAt:l.string().refine(e=>Number.isFinite(Date.parse(e))),headerTransforms:l.array(Exe).min(1)}).strict(),OHe=l.discriminatedUnion("type",[l.object({lease:Mxe,type:l.literal("lease")}).strict(),l.object({authorization:TK.optional(),message:je,type:l.literal("needed")}).strict(),l.object({message:je,type:l.literal("unavailable")}).strict()]);var Oxe=je.max(64).regex(/^[a-z][a-z0-9-]*$/),zxe=je.max(80),Uxe=je.max(500),jxe=l.enum(["primary","profile","admin"]),Bxe=l.object({detail:je.max(500).optional(),label:je.max(80),tone:l.enum(["good","neutral","warning"]).optional(),value:je.max(120)}).strict(),Fxe=l.object({label:je.max(80),value:je.max(500)}).strict(),Hxe=l.object({confirmation:je.max(500).optional(),href:je.max(500).regex(/^\/api\/plugins\/[a-z][a-z0-9-]*(?:\/|$)/),label:je.max(80),method:l.enum(["DELETE","GET"]),tone:l.enum(["danger","neutral"]).optional()}).strict(),Vxe=l.object({actions:l.array(Hxe).max(4).optional(),description:je.max(1e3).optional(),id:je.max(128),metadata:l.array(Fxe).max(8).optional(),title:je.max(4e3)}).strict(),NK=l.object({emptyText:je.max(500).optional(),metrics:l.array(Bxe).max(6).optional(),nextCursor:je.max(1e3).optional(),records:l.array(Vxe).max(100),searchPlaceholder:je.max(120).optional(),type:l.literal("list")}).strict(),qxe=l.object({description:Uxe,id:Oxe,label:zxe,navigation:jxe,pluginDisplayName:je.max(200),pluginName:je.max(100)}).strict(),RK=l.array(qxe),Zxe=je.max(1e3).optional(),Gxe=je.max(64).optional(),Kxe=l.string().trim().max(200).optional(),UHe=l.object({cursor:Zxe,filter:Gxe,limit:l.number().int().min(1).max(50),query:Kxe}).strict();var AK=l.object({email:l.string().trim().email(),emailVerified:l.boolean().optional(),name:l.string().nullable().optional()}).strict(),FHe=l.object({user:AK}).strict(),tI=l.object({user:AK.extend({isAdmin:l.boolean()}).strict()}).strict(),HHe=l.object({displayName:l.string().trim().min(1).max(80)}).strict(),$K=l.object({allowedEmailCount:l.number(),allowedGoogleDomainCount:l.number(),authRequired:l.boolean(),authPath:l.string(),basePath:l.string(),componentGallery:l.boolean(),sentryConversationLinks:l.boolean(),timeZone:l.string().optional(),version:l.string().min(1)}).strict();var Qx=b(V(),1);var PK="x-junior-version";var f4="junior:dashboard-version";function DK(e){let t=e.headers.get(PK)?.trim();!t||typeof window>"u"||window.dispatchEvent(new CustomEvent(f4,{detail:t}))}function EK(e){let[t,a]=(0,Qx.useState)(e);return(0,Qx.useEffect)(()=>{e&&a(e)},[e]),(0,Qx.useEffect)(()=>{let r=n=>{a(n.detail)};return window.addEventListener(f4,r),()=>window.removeEventListener(f4,r)},[]),t}var Cn=class extends Error{status;fields;code;apiError;constructor(t,a,r,n){super(`${t} returned ${a}`),this.status=a,this.fields=n?.fields,this.code=n?.code,r?.trim()&&(this.apiError=r.trim())}};async function Ug(e,t){let a,r,n;try{let o=await t.json();typeof o.error=="string"&&(a=o.error),typeof o.code=="string"&&(n=o.code),o.fields&&typeof o.fields=="object"&&(r=Object.fromEntries(Object.entries(o.fields).filter(i=>Array.isArray(i[1])&&i[1].every(s=>typeof s=="string"))))}catch{}throw new Cn(e,t.status,a,{fields:r,code:n})}function jg(){if(typeof window>"u")return;let e=window.__JUNIOR_DASHBOARD_BASE_PATH__??"/",t=e==="/"?"/auth/login":`${e}/auth/login`;if(window.location.pathname!==t){let a=`${window.location.pathname}${window.location.search||""}`,r=new URLSearchParams;a!=="/"&&r.set("next",a);let n=r.toString();window.location.assign(n?`${t}?${n}`:t)}}async function Bg(e,t,a){let r=await Fg(t,{body:JSON.stringify(a),credentials:"same-origin",headers:{"content-type":"application/json"},method:"PATCH"});return r.status===401&&jg(),r.ok||await Ug(t,r),e.parse(await r.json())}async function _r(e,t,a){let r=await Fg(t,{body:JSON.stringify(a),credentials:"same-origin",headers:{"content-type":"application/json"},method:"POST"});return r.status===401&&jg(),r.ok||await Ug(t,r),e.parse(await r.json())}async function MK(e,t,a){let r=await Fg(t,{body:JSON.stringify(a),credentials:"same-origin",headers:{"content-type":"application/json"},method:"PUT"});return r.status===401&&jg(),r.ok||await Ug(t,r),e.parse(await r.json())}async function Kd(e){let t=await Fg(e,{credentials:"same-origin",method:"DELETE"});t.status===401&&jg(),t.ok||await Ug(e,t)}async function aI(e,t,a={}){let r=await Fg(t,{body:JSON.stringify(a),credentials:"same-origin",headers:{"content-type":"application/json"},method:"DELETE"});return r.status===401&&jg(),r.ok||await Ug(t,r),e.parse(await r.json())}async function Fg(e,t){let a=await fetch(e,t);return DK(a),a}async function Se(e,t,a){let r=await m4(t,a);return e.parse(await r.json())}async function m4(e,t,a){let r=await Fg(e,{credentials:"same-origin",...t?{signal:t}:void 0,...a?{cache:"no-store",headers:{"if-none-match":a}}:void 0});return r.status===401&&jg(),!r.ok&&!(a&&r.status===304)&&await Ug(e,r),r}var nI=5*6e4,p4=5*6e4,Wxe=1e3;function Jxe(e,t=Date.now()){if(!e)return p4;let a=Date.parse(e);if(!Number.isFinite(a))return p4;let r=Math.max(0,t-a);return Math.max(Wxe,p4-r)}function OK(){return _e({queryKey:["dashboard","core"],queryFn:async({signal:e})=>{let[t,a]=await Promise.all([Se(tI,"/api/me",e),Se($K,"/api/config",e)]);return{config:a,me:t}},retry:!1,staleTime:nI})}function Qxe(){return _e({queryKey:["dashboard","plugins"],queryFn:({signal:e})=>Se(jM,"/api/plugins",e),retry:!1,staleTime:nI})}function zK(){return _e({queryKey:["dashboard","plugin-user-pages"],queryFn:({signal:e})=>Se(RK,"/api/user-pages",e),retry:!1,staleTime:nI})}function rI(e=""){return _e({queryKey:["dashboard","conversations","viewer",{search:e}],queryFn:({signal:t})=>Se(M1,`/api/conversations${e?`?q=${encodeURIComponent(e)}`:""}`,t),placeholderData:Of,retry:!1})}function UK(){return _e({queryKey:["dashboard","code"],queryFn:({signal:e})=>Se(qz,"/api/code",e),retry:!1})}function jK(e){return _e({enabled:!!e,queryKey:["dashboard","code","repositories",e],queryFn:({signal:t})=>Se(Zz,`/api/code/repositories/${encodeURIComponent(e)}`,t),retry:!1})}function oI(e,t=""){return _e({enabled:!!e,queryKey:["dashboard","conversations","code-repository",{repositoryId:e,search:t}],queryFn:({signal:a})=>{let r=new URLSearchParams({codeRepositoryId:e});return t&&r.set("q",t),Se(M1,`/api/conversations?${r.toString()}`,a)},placeholderData:Of,retry:!1})}function BK(e,t){return _e({enabled:e,queryKey:["dashboard","automations",t],queryFn:({signal:a})=>Se(AM,`/api/automations${t?`?${t}`:""}`,a),placeholderData:Of,retry:!1})}function Hg(e,t){return _e({enabled:e&&!!t,queryKey:["dashboard","automations","detail",t],queryFn:({signal:a})=>Se(Vx,`/api/automations/${encodeURIComponent(t)}`,a),retry:!1})}function FK(e){return _e({enabled:e,queryKey:["dashboard","automations","runs"],queryFn:({signal:t})=>Se(DM,"/api/automations/runs",t),retry:!1})}function HK(e,t){return _e({enabled:e&&!!t,queryKey:["dashboard","automations",t,"executions"],queryFn:({signal:a})=>Se(PM,`/api/automations/${encodeURIComponent(t)}/executions`,a),retry:!1})}function VK(e,t){return _e({enabled:e&&!!t,queryKey:["dashboard","automations",t,"versions"],queryFn:({signal:a})=>Se(EM,`/api/automations/${encodeURIComponent(t)}/versions`,a),retry:!1})}function qK(){return _e({queryKey:["dashboard","people"],queryFn:({signal:e})=>Se(Yz,"/api/people",e),retry:!1})}function ZK(e){return _e({enabled:!!e,queryKey:["dashboard","people",e],queryFn:async({signal:t})=>Se(e4,`/api/people/${encodeURIComponent(e)}`,t),retry:!1})}function GK(e){return _e({enabled:!!e,queryKey:["dashboard","people",e,"plugin-reports"],queryFn:({signal:t})=>Se(j1,`/api/people/${encodeURIComponent(e)}/plugin-reports`,t),retry:!1})}function KK(e){return _e({enabled:!!e,queryKey:["dashboard","people",e,"code"],queryFn:({signal:t})=>Se(Gz,`/api/people/${encodeURIComponent(e)}/code`,t),retry:!1})}function WK(e){return _e({enabled:e,queryKey:["dashboard","personal-spend"],queryFn:({signal:t})=>Se(t4,"/api/people/me/spend",t),refetchInterval:t=>Jxe(t.state.data?.generatedAt),retry:!1,staleTime:0})}function JK(){return _e({queryKey:["dashboard","locations"],queryFn:({signal:e})=>Se(Qz,"/api/locations",e),retry:!1})}function QK(e){return _e({enabled:!!e,queryKey:["dashboard","locations",e],queryFn:async({signal:t})=>Se(Xz,`/api/locations/${encodeURIComponent(e)}`,t),retry:!1})}function Xxe(){return _e({queryKey:["dashboard","skills"],queryFn:({signal:e})=>Se(FM,"/api/skills",e),retry:!1,staleTime:nI})}function Yxe(){return _e({queryKey:["dashboard","plugin-reports"],queryFn:({signal:e})=>Se(j1,"/api/plugin-reports",e),retry:!1})}function XK(){return _e({queryKey:["dashboard","stats"],queryFn:({signal:e})=>Se(i4,"/api/stats",e),retry:!1})}function YK(e){let t=Qxe(),a=_e({queryKey:["dashboard","conversation-stats"],queryFn:({signal:i})=>Se(_M,"/api/conversations/stats",i),retry:!1}),r=Xxe(),n=Yxe();return{data:t.data&&r.data?{...e,conversationStatsError:!!a.error,...a.data?{conversationStats:a.data}:void 0,conversationStatsLoading:a.isPending,pluginReportsError:!!n.error,...n.data?{pluginReports:n.data}:void 0,pluginReportsLoading:n.isPending,plugins:t.data,skills:r.data}:void 0,error:t.error??r.error,isPending:t.isPending||r.isPending}}var nW=b(V(),1);var eW="Junior";function Pt(){return typeof window>"u"?eW:window.__JUNIOR_DASHBOARD_AGENT_NAME__?.trim()||eW}function tW(e=Pt()){return e.endsWith("s")?`${e}'`:`${e}'s`}function aW(e,t=Pt()){let a=e?.trim();return a?`${a} - ${t}`:t}function Si(e){(0,nW.useEffect)(()=>{if(e?.trim())return document.title=aW(e),()=>{document.title=aW(void 0)}},[e])}function L(...e){return e.filter(Boolean).join(" ")}var Ba="mx-auto w-full min-w-0 max-w-screen-xl",iu="text-dashboard-text underline decoration-dashboard-border-heavy underline-offset-2 transition-colors hover:decoration-dashboard-text-muted",qm="text-dashboard-text-muted hover:text-dashboard-text",rW="rounded-xl border border-dashboard-border-emphasis bg-dashboard-surface-raised shadow-[0_8px_32px_rgba(0,0,0,0.35)] transition-colors";var iI=b(w(),1),oW="inline-flex h-9 max-w-full items-center justify-center gap-2 rounded-md border border-dashboard-border-emphasis bg-dashboard-surface-raised px-3 font-sans text-sm font-medium leading-none text-dashboard-text transition-colors hover:border-dashboard-border-heavy hover:bg-dashboard-surface-hover hover:text-dashboard-text focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-dashboard-focus",eSe="inline-flex h-9 max-w-full items-center justify-center gap-2 rounded-md border border-dashboard-border-strong bg-transparent px-3 font-sans text-sm font-medium leading-none text-dashboard-text-muted transition-colors hover:border-rose-300/40 hover:text-rose-300 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-rose-300/55";function oe({className:e,size:t="default",tone:a="default",type:r="button",...n}){let o=a==="danger";return(0,iI.jsx)("button",{...n,className:L("font-sans transition-colors disabled:cursor-not-allowed disabled:opacity-50",t==="icon"?L("grid size-9 place-items-center rounded-md border-0 bg-transparent p-0 focus-visible:outline-2 focus-visible:outline-offset-1 disabled:hover:!bg-transparent",o?"text-dashboard-text-muted hover:!bg-rose-300/10 hover:!text-rose-300 focus-visible:outline-rose-300/55 disabled:hover:!text-dashboard-text-muted":"text-dashboard-text-muted hover:!bg-dashboard-fill-strong hover:!text-dashboard-text focus-visible:outline-dashboard-focus disabled:hover:!text-dashboard-text-muted"):a==="primary"?"inline-flex h-9 items-center justify-center gap-2 rounded-md border border-dashboard-text-solid bg-dashboard-text-solid px-3 font-sans text-sm font-medium leading-none text-dashboard-text-inverse hover:border-dashboard-text-subtle hover:bg-dashboard-text-subtle disabled:hover:border-dashboard-text-solid disabled:hover:bg-dashboard-text-solid focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-dashboard-focus":o?L(eSe,"disabled:hover:border-dashboard-border-strong disabled:hover:text-dashboard-text-muted"):L(oW,"disabled:hover:border-dashboard-border-emphasis disabled:hover:bg-dashboard-surface-raised disabled:hover:text-dashboard-text"),n.disabled?"":"cursor-pointer",e),type:r})}function su({className:e,...t}){return(0,iI.jsx)(te,{...t,className:L(oW,"no-underline",e)})}function Dn({className:e,pressed:t,type:a="button",variant:r,...n}){return(0,iI.jsx)("button",{...n,"aria-pressed":t,className:L(tSe[r],t?aSe[r]:nSe[r],e),type:a})}var tSe={pill:"cursor-pointer rounded-md border px-2 py-1 font-sans text-xs font-medium leading-tight transition-colors focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-dashboard-focus",segment:"inline-flex h-7 min-w-10 cursor-pointer items-center justify-center rounded-md border px-2 font-sans text-xs font-medium transition-colors focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-dashboard-focus",text:"cursor-pointer rounded-sm border-0 bg-transparent px-1.5 py-1 font-sans font-medium underline-offset-4 transition-colors focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-dashboard-focus"},aSe={pill:"border-dashboard-border-heavy bg-dashboard-text-solid text-dashboard-text-inverse",segment:"border-dashboard-border-interactive bg-dashboard-surface-active text-dashboard-text",text:"text-dashboard-text underline decoration-dashboard-text-solid"},nSe={pill:"border-dashboard-border-strong bg-dashboard-surface-raised text-dashboard-text-muted hover:border-dashboard-border-interactive hover:bg-dashboard-surface-hover hover:text-dashboard-text",segment:"border-transparent bg-transparent text-dashboard-text-muted hover:bg-dashboard-fill-hover hover:text-dashboard-text",text:"text-dashboard-text-muted hover:text-dashboard-text"};var Zm=b(w(),1);function uo(e){let t=e.tone==="error";return(0,Zm.jsxs)("div",{role:t?"alert":"status",className:L("flex min-w-0 gap-3 rounded-md border p-4",t?"border-rose-300/25 bg-rose-300/5":"border-amber-300/25 bg-amber-300/5"),children:[(0,Zm.jsx)(ro,{"aria-hidden":!0,size:18,className:L("mt-0.5 shrink-0",t?"text-rose-300":"text-amber-300")}),(0,Zm.jsxs)("div",{className:"min-w-0",children:[(0,Zm.jsx)("p",{className:"m-0 text-sm font-medium",children:e.title}),e.children?(0,Zm.jsx)("div",{className:"mt-1 text-sm leading-relaxed text-dashboard-text-muted",children:e.children}):null]})]})}var Xx=b(w(),1),rSe={accent:"text-dashboard-accent",danger:"text-rose-300",info:"text-cyan-300",neutral:"text-dashboard-text-muted",success:"text-emerald-300",warning:"text-amber-300"},oSe={compact:"text-xs",default:"text-sm"};function Zt(e){return(0,Xx.jsxs)("span",{className:L("inline-flex w-fit items-center gap-1.5 font-sans font-medium normal-case leading-snug tracking-normal",oSe[e.size??"default"],rSe[e.tone??"neutral"],e.className),children:[(0,Xx.jsx)("span",{"aria-hidden":"true",className:"size-1.5 shrink-0 rounded-full bg-current"}),(0,Xx.jsx)("span",{className:"block first-letter:uppercase",children:e.children})]})}var iW=b(w(),1);function j(e){let t=e.as??"div",a={none:"",sm:"p-4",md:"p-5 sm:p-6"}[e.padding??"none"],r=e.variant==="section"?"mb-4 border-dashboard-border-subtle bg-dashboard-fill-faint shadow-[0_24px_80px_rgba(0,0,0,0.18)]":e.variant==="raised"?"border-dashboard-border-emphasis bg-dashboard-surface-raised":"border-dashboard-border-subtle bg-dashboard-fill-faint";return(0,iW.jsx)(t,{className:L("min-w-0 overflow-hidden rounded-lg border",r,a,e.className),children:e.children})}var sW=b(w(),1);function et(e){let t=e.as??"div";return(0,sW.jsx)(t,{"aria-hidden":"true",className:L("animate-pulse rounded-md bg-dashboard-fill-soft motion-reduce:animate-none",e.className)})}var lt=b(w(),1);function sr(e){let t=e.variant??"panel";return(0,lt.jsxs)("div",{"aria-busy":"true","aria-live":"polite",className:L("grid gap-4",e.className),role:"status",children:[(0,lt.jsx)("span",{className:"sr-only",children:e.label}),iSe(t)]})}function iSe(e){switch(e){case"stats":return(0,lt.jsx)(sSe,{});case"overview":return(0,lt.jsx)(lSe,{});case"list":return(0,lt.jsx)(uSe,{});case"library":return(0,lt.jsx)(cSe,{});case"panel":return(0,lt.jsx)(lu,{className:"min-h-64"})}}function sSe(){return(0,lt.jsxs)(lt.Fragment,{children:[(0,lt.jsx)("div",{className:"grid grid-cols-2 gap-3 lg:grid-cols-4",children:Array.from({length:4},(e,t)=>(0,lt.jsx)(lu,{className:"min-h-[7.5rem] p-4 sm:min-h-32 sm:p-5"},t))}),(0,lt.jsx)(lu,{className:"min-h-[17rem]"})]})}function lSe(){return(0,lt.jsxs)(lt.Fragment,{children:[(0,lt.jsxs)("div",{className:"grid gap-4 xl:grid-cols-2",children:[(0,lt.jsx)(lu,{className:"min-h-[17rem]"}),(0,lt.jsx)(lu,{className:"min-h-[17rem]"})]}),(0,lt.jsx)(Vg,{className:"h-24 border-y border-dashboard-border-subtle bg-dashboard-fill-faint"}),(0,lt.jsxs)("div",{className:"grid gap-4 md:grid-cols-2",children:[(0,lt.jsx)(lu,{className:"min-h-56"}),(0,lt.jsx)(lu,{className:"min-h-56"})]})]})}function uSe(){return(0,lt.jsxs)(lt.Fragment,{children:[(0,lt.jsx)(lu,{className:"min-h-20 p-4"}),(0,lt.jsx)(Vg,{className:"h-10 border-b border-dashboard-border-subtle"}),(0,lt.jsx)(lu,{className:"min-h-80"})]})}function cSe(){return(0,lt.jsxs)(lt.Fragment,{children:[(0,lt.jsxs)("div",{className:"flex flex-wrap items-end justify-between gap-4",children:[(0,lt.jsx)(Vg,{className:"h-7 w-56 rounded-md bg-dashboard-fill-soft"}),(0,lt.jsx)(Vg,{className:"h-10 w-full max-w-md rounded-lg border border-dashboard-border-subtle bg-dashboard-fill-faint sm:w-72"})]}),(0,lt.jsx)("div",{"aria-hidden":"true",className:"grid min-w-0 grid-cols-3 gap-1 border-b border-dashboard-border-subtle sm:flex",children:Array.from({length:3},(e,t)=>(0,lt.jsxs)("div",{className:"flex items-center justify-between gap-2 px-3 py-2.5 sm:justify-start",children:[(0,lt.jsx)(Vg,{className:"h-3 w-12 rounded-md bg-dashboard-fill-soft"}),(0,lt.jsx)(Vg,{className:"h-5 w-8 rounded-sm border border-dashboard-border-subtle bg-dashboard-fill-faint"})]},t))}),(0,lt.jsx)(lu,{className:"min-h-80"})]})}function lu(e){return(0,lt.jsx)(j,{className:L("animate-pulse motion-reduce:animate-none",e.className),children:(0,lt.jsx)("span",{"aria-hidden":"true"})})}function Vg(e){return(0,lt.jsx)(et,{className:e.className})}var h4=b(w(),1),dSe=[1,7,30,90];function g4(e){return e===1?"24h":`${e}d`}function qg(e){return e===1?"last 24 hours":`last ${e} days`}function Xa(e){return e===1?"hour":e===7?"6hour":"day"}function lW(e){return e===1}function fSe(e){return e===7}function co(e){return e==="hour"?"hour":e==="6hour"?"6h":"day"}function Zg(e){return e==="hour"?"hour":e==="6hour"?"6 hours":"day"}function Yx(e){return e==="hour"?"Hourly":e==="6hour"?"6-hour":"Daily"}function ln(e){return lW(e.range)&&e.hours?.length?e.hours.slice(-24):lW(e.range)?e.days.slice(-1):fSe(e.range)?e.sixHours?.length?[...e.sixHours]:e.hours?.length&&e.emptySixHour?mSe({empty:e.emptySixHour,hours:e.hours}):e.days.slice(-e.range):e.days.slice(-e.range)}function mSe(e){let t=new Map;for(let a of e.hours){let r=Date.parse(`${a.date}:00:00.000Z`);if(Number.isNaN(r))continue;let n=new Date(r);n.setUTCMinutes(0,0,0),n.setUTCHours(Math.floor(n.getUTCHours()/6)*6,0,0,0);let o=n.toISOString().slice(0,13),s={...t.get(o)??e.empty(o),date:o};for(let[u,c]of Object.entries(a))if(u!=="date"&&typeof c=="number"){let d=s[u];s[u]=(typeof d=="number"?d:0)+c}t.set(o,s)}if(e.hours.length>=24){let a=e.hours[e.hours.length-1]?.date,r=a?Date.parse(`${a}:00:00.000Z`):Date.now(),n=new Date(r);n.setUTCMinutes(0,0,0),n.setUTCHours(Math.floor(n.getUTCHours()/6)*6,0,0,0);let o=new Date(n.getTime()-9720*60*1e3),i=[];for(let s=new Date(o);s.getTime()<=n.getTime();s.setTime(s.getTime()+360*60*1e3)){let u=s.toISOString().slice(0,13);i.push(t.get(u)??e.empty(u))}return i}return[...t.values()].sort((a,r)=>a.date.localeCompare(r.date))}function Gg(e){return(0,h4.jsx)("div",{"aria-label":"Reporting period",className:"flex items-center gap-1",role:"group",children:(e.options??dSe).map(t=>(0,h4.jsx)(Dn,{onClick:()=>e.onChange(t),pressed:e.value===t,variant:"segment",children:g4(t)},t))})}var Wd=b(w(),1);function We(e){Si(e.documentTitle??(typeof e.title=="string"?e.title:void 0));let t=e.range!==void 0&&e.onRangeChange?(0,Wd.jsx)(Gg,{onChange:e.onRangeChange,...e.rangeOptions?{options:e.rangeOptions}:{},value:e.range}):void 0,a=e.actions??t;return(0,Wd.jsxs)("header",{className:"flex min-w-0 items-center justify-between gap-6 border-b border-dashboard-border-subtle pb-4 sm:pb-6 max-md:flex-col max-md:items-stretch",children:[(0,Wd.jsxs)("div",{className:"min-w-0",children:[(0,Wd.jsx)("h2",{className:"m-0 font-display text-3xl font-light leading-none tracking-[-0.03em] text-dashboard-text sm:text-4xl",children:e.title}),(0,Wd.jsx)("div",{className:"mt-2 max-w-2xl font-sans text-xs leading-relaxed text-dashboard-text-muted sm:text-sm",children:e.description})]}),a?(0,Wd.jsx)("div",{className:"shrink-0",children:a}):null]})}var uW=b(w(),1);function Eo(e){return(0,uW.jsx)("div",{className:L(Ba,"grid min-w-0 content-start gap-4 px-4 py-4 pb-[max(1rem,env(safe-area-inset-bottom))] sm:gap-6 sm:px-8 sm:py-8 sm:pb-8",e.className),children:e.children})}var Km=b(V(),1);var Gm=b(V(),1);function Ji(e,t){let a=typeof t=="string"?t.startsWith("?")?t.slice(1):t:t?.toString()??"",r=e.indexOf("?"),n=r===-1?e:e.slice(0,r),o=r===-1?"":e.slice(r+1).replace(/^\?+/,""),i=new URLSearchParams(a);for(let[u,c]of new URLSearchParams(o))i.set(u,c);let s=i.toString();return s?`${n}?${s}`:n}function pSe(e,t){let a=e?.trim();return a&&t.includes(a)?a:void 0}function uu(e="q",t={}){let a=t.delayMs??250,r=t.resetPage??!1,[n,o]=li(),i=n.get(e)?.trim()??"",[s,u]=(0,Gm.useState)(i);return(0,Gm.useEffect)(()=>{u(c=>c.trim()===i?c:i)},[i]),(0,Gm.useEffect)(()=>{let c=window.setTimeout(()=>{let d=s.trim();d!==i&&o(f=>{let m=new URLSearchParams(f);return r&&m.delete("page"),d?m.set(e,d):m.delete(e),m},{replace:!0})},a);return()=>window.clearTimeout(c)},[i,a,e,r,o,s]),[s,u,i]}function yc(e,t,a){let[r,n]=li(),o=pSe(r.get(e),a)??t,i=(0,Gm.useCallback)(s=>{n(u=>{let c=new URLSearchParams(u);return s===t?c.delete(e):c.set(e,s),c},{replace:!0})},[t,e,n]);return[o,i]}var Kg=b(w(),1);function y4(e){let{className:t,item:a}=e,r=xt(),n=Ji(a.to,r.search);if(a.isActive){let o=a.isActive(r.pathname);return(0,Kg.jsx)(te,{"aria-current":o?"page":void 0,className:t({isActive:o}),to:n,children:a.label})}return(0,Kg.jsx)(um,{className:t,end:a.end,to:n,children:a.label})}var v4=24;function dW(e){let t=e.scrollWidth-e.clientWidth;return{end:e.scrollLeft<t-1,start:e.scrollLeft>1}}function cW(e){let t=e.querySelector('[aria-current="page"]');if(!t||e.clientWidth===0)return;let a=dW(e),r=e.scrollLeft+(a.start?v4:0),n=e.scrollLeft+e.clientWidth-(a.end?v4:0),o=t.offsetLeft,i=o+t.offsetWidth;o>=r&&i<=n||(e.scrollLeft=o-(e.clientWidth-t.offsetWidth)/2)}function hSe(e){if(!e.start&&!e.end)return;let t=`${v4}px`,a=e.start?`transparent, black ${t}`:"black",r=e.end?`black calc(100% - ${t}), transparent`:"black",n=`linear-gradient(to right, ${a}, ${r})`;return{maskImage:n,WebkitMaskImage:n}}function Wm(e){let{pathname:t}=xt(),a=(0,Km.useRef)(null),[r,n]=(0,Km.useState)({end:!1,start:!1});(0,Km.useLayoutEffect)(()=>{let i=a.current;if(!i)return;let s=()=>{let{end:c,start:d}=dW(i);n(f=>f.start===d&&f.end===c?f:{end:c,start:d})},u=new ResizeObserver(()=>{i.scrollLeft=0,cW(i),s()});s(),i.addEventListener("scroll",s,{passive:!0}),u.observe(i);for(let c of i.children)u.observe(c);return()=>{i.removeEventListener("scroll",s),u.disconnect()}},[]),(0,Km.useLayoutEffect)(()=>{a.current&&cW(a.current)},[t]);let o=({isActive:i})=>L("relative flex h-10 items-center justify-center whitespace-nowrap font-sans text-sm font-medium no-underline transition-colors after:absolute after:inset-x-0 after:bottom-0 after:h-0.5 focus-visible:outline-2 focus-visible:-outline-offset-2 focus-visible:outline-dashboard-focus",i?"text-dashboard-text after:bg-dashboard-text-solid":"text-dashboard-text-muted hover:text-dashboard-text",e.fill?"min-w-max flex-[1_0_0]":"shrink-0");return(0,Kg.jsx)("nav",{"aria-label":e.ariaLabel,className:L("flex min-w-0 max-w-full",!e.fill&&"w-fit"),children:(0,Kg.jsx)("div",{className:L("relative -mx-1 flex gap-5 px-1 min-w-0 flex-1 overflow-x-auto [scrollbar-width:none] [&::-webkit-scrollbar]:hidden"),ref:a,style:hSe(r),children:e.items.map(i=>(0,Kg.jsx)(y4,{className:o,item:i},i.to))})})}var ta=b(V(),1),eS=b(Fl(),1),As=b(w(),1),cu=(0,ta.createContext)(null);function sI(e){let[t,a]=(0,ta.useState)(null),[r,n]=(0,ta.useState)(null),[o,i]=(0,ta.useState)(null),[s,u]=(0,ta.useState)(null),c=(0,ta.useRef)(null),d=(0,ta.useCallback)(g=>{a(g)},[]),f=(0,ta.useCallback)(g=>{n(g)},[]),m=(0,ta.useCallback)(g=>{i(g)},[]),h=(0,ta.useCallback)(g=>{u(g)},[]),p=(0,ta.useCallback)(g=>{c.current=g},[]),v=(0,ta.useCallback)(()=>{c.current?.()},[]),x=(0,ta.useMemo)(()=>({mobileHeaderActionsSlot:o,mobileHeaderActionsSlotRef:m,mobileHeaderLiveSlot:s,mobileHeaderLiveSlotRef:h,mobileSecondarySlot:r,mobileSecondarySlotRef:f,openMobileNavigation:v,registerOpenMobileNavigation:p,secondarySlot:t,secondarySlotRef:d}),[o,m,s,h,r,f,v,p,t,d]);return(0,As.jsx)(cu.Provider,{value:x,children:e.children})}function fW(e){let t=(0,ta.useContext)(cu);if(!t)throw new Error("DashboardChrome requires DashboardChromeProvider");return(0,As.jsxs)("div",{className:"sticky top-0 z-30 bg-dashboard-bg/95 pt-[env(safe-area-inset-top)]",children:[(0,As.jsxs)("div",{className:"border-b border-dashboard-border-strong",children:[e.header,(0,As.jsx)("div",{className:"hidden md:block",ref:t.secondarySlotRef})]}),e.banner]})}function mW(){let e=(0,ta.useContext)(cu);if(!e)throw new Error("MobileSecondaryNavigationSlot requires DashboardChromeProvider");return(0,As.jsx)("div",{ref:e.mobileSecondarySlotRef})}function pW(){let e=(0,ta.useContext)(cu);if(!e)throw new Error("MobileHeaderActionsSlot requires DashboardChromeProvider");return(0,As.jsx)("div",{className:"col-start-3 row-start-1 flex min-w-0 items-center justify-self-end md:hidden",ref:e.mobileHeaderActionsSlotRef})}function hW(){let e=(0,ta.useContext)(cu);if(!e)throw new Error("MobileHeaderLiveSlot requires DashboardChromeProvider");return(0,As.jsx)("div",{className:"flex shrink-0 items-center md:hidden",ref:e.mobileHeaderLiveSlotRef})}function gW(e){let t=(0,ta.useContext)(cu);return t?.mobileHeaderActionsSlot?(0,eS.createPortal)(e.children,t.mobileHeaderActionsSlot):null}function vW(e){let t=(0,ta.useContext)(cu);return t?.mobileHeaderLiveSlot?(0,eS.createPortal)(e.children,t.mobileHeaderLiveSlot):null}function yW(){let e=(0,ta.useContext)(cu);return e?e.openMobileNavigation:null}function bW(e){let t=(0,ta.useContext)(cu),a=(0,ta.useRef)(e);a.current=e,(0,ta.useEffect)(()=>{if(!t)return;let r=()=>{a.current?.()};return t.registerOpenMobileNavigation(e?r:null),()=>{t.registerOpenMobileNavigation(null)}},[t,e])}function xW(e){let t=(0,ta.useContext)(cu);return t?t.secondarySlot?(0,As.jsxs)(As.Fragment,{children:[(0,eS.createPortal)(e.desktop,t.secondarySlot),t.mobileSecondarySlot?(0,eS.createPortal)(e.mobile,t.mobileSecondarySlot):null]}):null:e.desktop}var du=b(w(),1);function Jd(e){let t=({isActive:a})=>L("rounded-lg px-3 py-3 pl-6 font-sans text-sm font-medium no-underline transition-colors",a?"bg-dashboard-accent/[0.1] text-dashboard-accent-text":L("hover:bg-dashboard-fill-faint",qm));return(0,du.jsxs)("div",{className:"min-w-0",children:[(0,du.jsx)(xW,{desktop:(0,du.jsx)("div",{className:L(Ba,"min-w-0 px-4 md:px-8"),children:(0,du.jsx)(Wm,{ariaLabel:e.ariaLabel,items:e.items})}),mobile:(0,du.jsx)("nav",{"aria-label":e.ariaLabel,className:"mt-3 grid gap-1 border-t border-dashboard-border pt-3",children:e.items.map(a=>(0,du.jsx)(y4,{className:t,item:a},a.to))})}),(0,du.jsx)("div",{className:"border-b border-dashboard-border px-4 pt-2 sm:px-8 md:hidden",children:(0,du.jsx)(Wm,{ariaLabel:e.ariaLabel,fill:!0,items:e.items})}),e.children]})}var fu=b(w(),1),gSe=new Set(["list","runs"]);function vSe(e){if(e==="/automations/list"||/^\/automations\/(scheduled|event)\/[^/]+\/edit$/.test(e))return!0;let t=e.match(/^\/automations\/([^/]+)$/);return!!(t?.[1]&&!gSe.has(t[1]))}var ySe=[{end:!0,label:"Overview",to:"/automations"},{isActive:vSe,label:"Automations",to:"/automations/list"},{label:"Runs",to:"/automations/runs"}];function b4(e){return(0,fu.jsx)(Jd,{ariaLabel:"Automations navigation",items:ySe,children:e.children})}function Qi(e){return(0,fu.jsx)(b4,{children:(0,fu.jsx)(Eo,{children:e.children})})}function Jm(e){return(0,fu.jsxs)(fu.Fragment,{children:[(0,fu.jsx)(We,{description:e.description,title:e.title}),(0,fu.jsx)(sr,{label:e.label,variant:e.variant})]})}var Ps=b(V(),1);var Wg=b(w(),1),bSe={compact:"font-sans font-medium text-xs text-dashboard-text-muted",default:"text-sm font-semibold text-dashboard-text"},xSe={compact:"grid gap-1.5",default:"grid gap-2"};function Gt(e){let t=e.size??"default";return(0,Wg.jsxs)("div",{className:L(xSe[t],e.className),children:[(0,Wg.jsx)("label",{className:bSe[t],htmlFor:e.htmlFor,children:e.label}),e.children,e.error?(0,Wg.jsx)("p",{id:e.htmlFor?`${e.htmlFor}-error`:void 0,role:"alert",className:"m-0 text-xs leading-relaxed text-rose-300",children:e.error}):null,e.help?(0,Wg.jsx)("p",{id:e.htmlFor?`${e.htmlFor}-help`:void 0,className:"m-0 text-xs leading-relaxed text-dashboard-text-muted sm:text-sm",children:e.help}):null]})}var x4=b(w(),1),SW="block w-full rounded-md border border-dashboard-border-emphasis bg-dashboard-ink px-3 py-2 font-sans text-sm text-dashboard-text placeholder:text-dashboard-text-muted/70 focus:border-dashboard-focus focus:outline-none focus:ring-1 focus:ring-dashboard-focus/25 aria-invalid:border-rose-300 disabled:cursor-not-allowed disabled:opacity-50";function Ta({className:e,type:t="text",size:a="default",...r}){return(0,x4.jsx)("input",{...r,className:L(SW,a==="comfortable"&&"min-h-11 text-base sm:min-h-10 sm:text-sm",e),type:t})}function bc({className:e,prose:t=!1,...a}){return(0,x4.jsx)("textarea",{...a,className:L(SW,"min-h-36",t?"font-sans leading-relaxed":"font-mono",e)})}var Qm=b(w(),1);function $s(e){return(0,Qm.jsxs)("section",{className:"grid min-w-0 gap-5 border-t border-dashboard-border-emphasis py-8 md:grid-cols-[12rem_minmax(0,1fr)] md:gap-10",children:[(0,Qm.jsxs)("div",{children:[(0,Qm.jsx)("h2",{className:"m-0 font-display text-lg font-medium",children:e.title}),e.detail?(0,Qm.jsx)("p",{className:"mt-2 mb-0 text-sm leading-relaxed text-dashboard-text-muted",children:e.detail}):null]}),(0,Qm.jsx)("div",{className:"grid min-w-0 content-start gap-5",children:e.children})]})}var dI=b(V(),1);var wW=b(w(),1);function mu({className:e,...t}){return(0,wW.jsx)("select",{...t,className:L("block min-h-11 w-full min-w-0 rounded-md border border-dashboard-border-emphasis bg-dashboard-ink px-3 py-2 text-base text-dashboard-text focus:border-dashboard-focus focus:outline-none aria-invalid:border-rose-300 disabled:cursor-not-allowed disabled:opacity-60 sm:min-h-10 sm:text-sm",e)})}var lI=["sunday","monday","tuesday","wednesday","thursday","friday","saturday"];function uI(e){return{title:e.title??"",instruction:e.instruction,credentialMode:e.credentialMode,outcomes:e.outcomes,trigger:e.kind==="event"?e.trigger:void 0}}function cI(e){let t=e.schedule.recurrence;if(e.schedule.kind==="recurring"&&t){let{time:a,weekdays:r,...n}=t;return{kind:"recurring",...n,timezone:e.schedule.timezone,time:`${String(a.hour).padStart(2,"0")}:${String(a.minute).padStart(2,"0")}`,weekdays:r?.map(o=>lI[o])}}if(e.nextRunAtMs){let a=new Intl.DateTimeFormat("en-CA",{timeZone:e.schedule.timezone,year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",hourCycle:"h23"}).formatToParts(e.nextRunAtMs),r=n=>a.find(o=>o.type===n)?.value??"";return{kind:"one_off",timezone:e.schedule.timezone,timing:{type:"at",date:`${r("year")}-${r("month")}-${r("day")}`,time:`${r("hour")}:${r("minute")}`}}}return{kind:"recurring",frequency:"daily",time:"09:00",timezone:e.schedule.timezone}}function CW(e,t){let a={};return t.title!==(e.title??"")&&(a.title=t.title),t.instruction!==e.instruction&&(a.instruction=t.instruction),t.credentialMode!==e.credentialMode&&(a.credentialMode=t.credentialMode),JSON.stringify(t.outcomes)!==JSON.stringify(e.outcomes)&&(a.outcomes=t.outcomes),e.kind==="scheduled"&&t.schedule&&(a.schedule=t.schedule),e.kind==="event"&&JSON.stringify(t.trigger)!==JSON.stringify(e.trigger)&&(a.trigger=t.trigger),a}var He=b(w(),1);function kW(e){let t=e.value??cI(e.automation),[a,r]=(0,dI.useState)(e.value);(0,dI.useEffect)(()=>{let f=setTimeout(()=>r(e.value),300);return()=>clearTimeout(f)},[e.value]);let n=zM.safeParse(a),o=_e({queryKey:["dashboard","automation-schedule-preview",e.automation.id,a],enabled:!!a&&n.success,retry:!1,queryFn:()=>_r(UM,`/api/automations/${encodeURIComponent(e.automation.id)}/preview`,a)}),i=t.kind==="recurring"?t.frequency:"once",s=t.kind==="recurring"?t.time:t.timing.time,u=e.value?o.data?.nextRunAtMs:e.automation.nextRunAtMs,c=e.value!==a||o.isFetching,d=o.error instanceof Cn?o.error.apiError:o.error?"Schedule preview could not be loaded. Try again.":e.value&&!n.success&&!c?n.error.issues[0]?.message:void 0;return(0,He.jsxs)(He.Fragment,{children:[(0,He.jsxs)("div",{className:"grid grid-cols-1 items-start gap-4 sm:grid-cols-2",children:[(0,He.jsx)(Gt,{label:"Repeat",htmlFor:"schedule-frequency",children:(0,He.jsxs)(mu,{id:"schedule-frequency",value:i,onChange:f=>{let m=f.target.value;m!=="once"&&m!=="daily"&&m!=="weekly"&&m!=="monthly"&&m!=="yearly"||e.onChange(m==="once"?{kind:"one_off",timezone:t.timezone??e.automation.schedule.timezone,timing:{type:"at",date:"",time:s}}:{kind:"recurring",timezone:t.timezone,time:s,frequency:m,interval:1,weekdays:m==="weekly"?["monday"]:void 0,dayOfMonth:["monthly","yearly"].includes(m)?1:void 0,month:m==="yearly"?1:void 0})},children:[(0,He.jsx)("option",{value:"once",children:"Once"}),(0,He.jsx)("option",{value:"daily",children:"Every day"}),(0,He.jsx)("option",{value:"weekly",children:"Every week"}),(0,He.jsx)("option",{value:"monthly",children:"Every month"}),(0,He.jsx)("option",{value:"yearly",children:"Every year"})]})}),(0,He.jsx)(Gt,{label:"Time",htmlFor:"schedule-time",children:(0,He.jsx)(Ta,{size:"comfortable",id:"schedule-time",type:"time",value:s,onChange:f=>e.onChange(t.kind==="recurring"?{...t,time:f.target.value}:{...t,timing:{type:"at",date:t.timing.date,time:f.target.value}})})})]}),t.kind==="recurring"?(0,He.jsxs)(He.Fragment,{children:[t.frequency==="weekly"?(0,He.jsxs)("fieldset",{children:[(0,He.jsx)("legend",{className:"mb-2 text-sm font-semibold",children:"On"}),(0,He.jsx)("div",{className:"grid grid-cols-7 gap-1.5",children:[...lI.slice(1),lI[0]].map(f=>(0,He.jsx)("button",{type:"button","aria-label":f,"aria-pressed":t.weekdays?.includes(f)??!1,onClick:()=>e.onChange({...t,weekdays:t.weekdays?.includes(f)?t.weekdays.filter(m=>m!==f):[...t.weekdays??[],f]}),className:L("min-h-11 cursor-pointer rounded-md border px-1 text-xs font-medium capitalize focus-visible:outline-2 focus-visible:outline-dashboard-focus sm:min-h-10 sm:text-sm",t.weekdays?.includes(f)?"border-dashboard-focus/50 bg-dashboard-focus/10 text-dashboard-focus":"border-dashboard-border-emphasis text-dashboard-text-muted hover:bg-dashboard-fill-hover"),children:f.slice(0,3)},f))})]}):null,(0,He.jsxs)("div",{className:"grid grid-cols-1 items-start gap-4 sm:grid-cols-2",children:[(0,He.jsx)(Gt,{label:"Interval",htmlFor:"schedule-interval",help:"Number of calendar periods between runs.",children:(0,He.jsx)(Ta,{size:"comfortable",id:"schedule-interval",type:"number",min:1,max:365,value:t.interval??1,onChange:f=>e.onChange({...t,interval:f.target.valueAsNumber})})}),(0,He.jsx)(Gt,{label:"Start date",htmlFor:"schedule-start",children:(0,He.jsx)(Ta,{size:"comfortable",id:"schedule-start",type:"date",value:t.startDate??"",onChange:f=>e.onChange({...t,startDate:f.target.value||void 0})})})]}),t.frequency==="monthly"||t.frequency==="yearly"?(0,He.jsxs)("div",{className:"grid grid-cols-1 gap-4 sm:grid-cols-2",children:[(0,He.jsx)(Gt,{label:"Day of month",htmlFor:"schedule-day",children:(0,He.jsx)(Ta,{size:"comfortable",id:"schedule-day",type:"number",min:1,max:31,value:t.dayOfMonth??1,onChange:f=>e.onChange({...t,dayOfMonth:f.target.valueAsNumber})})}),t.frequency==="yearly"?(0,He.jsx)(Gt,{label:"Month",htmlFor:"schedule-month",children:(0,He.jsx)(mu,{id:"schedule-month",value:t.month??1,onChange:f=>e.onChange({...t,month:Number(f.target.value)}),children:Array.from({length:12},(f,m)=>(0,He.jsx)("option",{value:m+1,children:new Intl.DateTimeFormat("en",{month:"long",timeZone:"UTC"}).format(new Date(Date.UTC(2026,m,1)))},m))})}):null]}):null]}):(0,He.jsx)(Gt,{label:"Date",htmlFor:"schedule-date",children:(0,He.jsx)(Ta,{size:"comfortable",id:"schedule-date",type:"date",value:t.timing.date,onChange:f=>e.onChange({...t,timing:{type:"at",time:s,date:f.target.value}})})}),(0,He.jsxs)(Gt,{label:"Timezone",htmlFor:"schedule-timezone",help:"Use an IANA timezone. The schedule follows local time, including daylight saving time.",children:[(0,He.jsx)(Ta,{size:"comfortable",id:"schedule-timezone",list:"automation-timezones",value:t.timezone??"",onChange:f=>e.onChange({...t,timezone:f.target.value})}),(0,He.jsx)("datalist",{id:"automation-timezones",children:["UTC",...Intl.supportedValuesOf("timeZone")].map(f=>(0,He.jsx)("option",{children:f},f))})]}),(0,He.jsxs)("div",{role:"status",className:"flex gap-3 rounded-md bg-dashboard-fill-soft p-3 text-sm leading-relaxed",children:[(0,He.jsx)(ol,{"aria-hidden":!0,size:17,className:"mt-0.5 shrink-0 text-dashboard-text-muted"}),(0,He.jsx)("div",{children:c?"Checking schedule\u2026":d?(0,He.jsxs)(He.Fragment,{children:[(0,He.jsx)("span",{className:"text-rose-300",children:d}),o.error?(0,He.jsx)(oe,{onClick:()=>{o.refetch()},children:"Try again"}):null]}):u?(0,He.jsxs)(He.Fragment,{children:["Next run"," ",new Intl.DateTimeFormat(void 0,{year:"numeric",month:"short",day:"numeric",hour:"numeric",minute:"2-digit",timeZoneName:"short",timeZone:e.value?o.data?.schedule.timezone??"UTC":e.automation.schedule.timezone}).format(u)]}):"No next run."})]}),e.value?(0,He.jsx)(oe,{className:"w-fit",onClick:()=>e.onChange(void 0),children:"Keep saved schedule"}):null]})}var vt=b(w(),1);function IW(e){let t=_e({queryKey:["dashboard","automation-event-catalog"],queryFn:({signal:o})=>Se(OM,"/api/automations/event-catalog",o),retry:!1}),a=t.data?.find(o=>o.namespace===e.value.namespace&&o.type===e.value.resourceType),r=!a||e.value.events.some(o=>!a.supportedEvents.includes(o))||Object.entries(e.value.match??{}).some(([o,i])=>{let s=a.matchFields?.[o];return s?(Array.isArray(i)?i:[i]).some(u=>typeof u!==s.kind||s.enum&&!s.enum.includes(String(u))):!0}),n=(o,i)=>{let s={...e.value.match};i===void 0?delete s[o]:s[o]=i,e.onChange({...e.value,match:s})};return(0,vt.jsxs)(vt.Fragment,{children:[t.error?(0,vt.jsxs)(uo,{title:"Event choices could not be loaded.",children:["Saved values are kept."," ",(0,vt.jsx)(oe,{onClick:()=>{t.refetch()},children:"Try again"})]}):t.isPending?(0,vt.jsx)("p",{role:"status",children:"Loading event choices\u2026"}):null,r&&t.data?(0,vt.jsxs)(uo,{title:"Saved trigger \xB7 Kept unchanged",children:["Some saved values are not in the current catalog. You can edit other fields, or select a new resource type to replace the trigger.",(0,vt.jsx)("pre",{className:"whitespace-pre-wrap break-all text-xs",children:JSON.stringify(e.value,null,2)})]}):null,(0,vt.jsx)(Gt,{label:r?"Replace trigger":"Resource type",htmlFor:"trigger-resource",children:(0,vt.jsxs)(mu,{id:"trigger-resource",value:r?"":`${e.value.namespace}:${e.value.resourceType}`,onChange:o=>{let i=t.data?.find(s=>`${s.namespace}:${s.type}`===o.target.value);i&&window.confirm("Replace the saved trigger? Its resource, events, and conditions will be cleared.")&&e.onChange({namespace:i.namespace,resourceType:i.type,identifier:"",label:"",events:[]})},children:[(0,vt.jsx)("option",{value:"",disabled:!0,children:"Keep saved trigger"}),t.data?.map(o=>(0,vt.jsxs)("option",{value:`${o.namespace}:${o.type}`,children:[o.namespace," \xB7 ",o.type.replaceAll("_"," ")]},`${o.namespace}:${o.type}`))]})}),!r&&a?(0,vt.jsxs)(vt.Fragment,{children:[(0,vt.jsx)(Gt,{label:"Resource name",htmlFor:"trigger-label",children:(0,vt.jsx)(Ta,{size:"comfortable",id:"trigger-label",value:e.value.label,onChange:o=>e.onChange({...e.value,label:o.target.value})})}),(0,vt.jsx)(Gt,{label:"Resource identifier",htmlFor:"trigger-identifier",help:"Use the exact provider resource identifier, not its display name.",children:(0,vt.jsx)(Ta,{size:"comfortable",id:"trigger-identifier",value:e.value.identifier,onChange:o=>e.onChange({...e.value,identifier:o.target.value})})}),(0,vt.jsxs)("fieldset",{children:[(0,vt.jsx)("legend",{className:"mb-2 text-sm font-semibold",children:"Run on these events"}),(0,vt.jsx)("div",{className:"divide-y divide-dashboard-border-subtle rounded-md border border-dashboard-border-emphasis",children:a.supportedEvents.map(o=>(0,vt.jsxs)("label",{className:"flex min-h-11 cursor-pointer items-start gap-3 px-3 py-3 text-sm",children:[(0,vt.jsx)("input",{type:"checkbox",className:"mt-0.5 size-4 shrink-0 accent-dashboard-focus",checked:e.value.events.includes(o),onChange:()=>e.onChange({...e.value,events:e.value.events.includes(o)?e.value.events.filter(i=>i!==o):[...e.value.events,o]})}),(0,vt.jsxs)("span",{className:"min-w-0 break-words",children:[o.replaceAll("_"," ").replaceAll("."," \xB7 "),a.guidance?.[o]?(0,vt.jsx)("span",{className:"mt-1 block text-xs leading-relaxed text-dashboard-text-muted",children:a.guidance[o]}):null]})]},o))})]}),Object.keys(a.matchFields??{}).length?(0,vt.jsxs)("fieldset",{className:"grid gap-4",children:[(0,vt.jsx)("legend",{className:"mb-3 text-sm font-semibold",children:"Only when"}),(0,vt.jsx)("p",{className:"m-0 text-xs leading-relaxed text-dashboard-text-muted",children:"All conditions must match. Leave a field blank to match any value. Existing lists match any one listed value."}),Object.entries(a.matchFields??{}).map(([o,i])=>{let s=e.value.match?.[o];return(0,vt.jsx)(Gt,{label:o,htmlFor:`match-${o}`,help:i.description,children:Array.isArray(s)?(0,vt.jsxs)("div",{className:"text-sm",children:[(0,vt.jsx)("span",{className:"break-all",children:s.join(", ")})," ",(0,vt.jsx)(oe,{onClick:()=>n(o,void 0),children:"Remove condition"})]}):i.kind==="boolean"||i.enum?(0,vt.jsxs)(mu,{id:`match-${o}`,value:s===void 0?"":String(s),onChange:u=>n(o,u.target.value===""?void 0:i.kind==="boolean"?u.target.value==="true":u.target.value),children:[(0,vt.jsx)("option",{value:"",children:"Any value"}),(i.enum??["true","false"]).map(u=>(0,vt.jsx)("option",{children:u},u))]}):(0,vt.jsx)(Ta,{size:"comfortable",id:`match-${o}`,type:i.kind==="number"?"number":"text",step:"any",value:s===void 0?"":String(s),onChange:u=>n(o,u.target.value===""?void 0:i.kind==="number"?u.target.valueAsNumber:u.target.value)})},o)})]}):null]}):null,JSON.stringify(e.value)!==JSON.stringify(e.original)?(0,vt.jsx)(oe,{className:"w-fit",onClick:()=>e.onChange(e.original),children:"Keep saved trigger"}):null]})}function Xm(e,t){return typeof e.destination=="string"?e.destination==="task_creator"?"Creator \xB7 Direct message":`${t.label} \xB7 ${t.visibility}`:e.destination.channelId===t.channelId&&e.destination.teamId===t.teamId?`${t.label} \xB7 ${t.visibility}`:`Saved destination \xB7 ${e.destination.channelId}`}var ua=b(w(),1);function fI(e){return e.outcomes.length?(0,ua.jsx)("ol",{className:"m-0 grid gap-2 pl-5 text-sm",children:e.outcomes.map((t,a)=>(0,ua.jsx)("li",{children:Xm(t,e.destination)},a))}):(0,ua.jsx)("p",{className:"m-0 text-sm",children:"No success message"})}function LW(e){let t=e.original.length?e.original:[{action:"send_message",destination:"current_conversation"}],a=[...e.original.flatMap((r,n)=>typeof r.destination=="string"?[]:[{value:`saved:${n}`,label:Xm(r,e.destination),outcome:r}]),{value:"current_conversation",label:`${e.destination.label} \xB7 ${e.destination.visibility}`,outcome:{action:"send_message",destination:"current_conversation"}},{value:"task_creator",label:"Creator \xB7 Direct message",outcome:{action:"send_message",destination:"task_creator"}}];return(0,ua.jsxs)(ua.Fragment,{children:[(0,ua.jsxs)("fieldset",{children:[(0,ua.jsx)("legend",{className:"sr-only",children:"Success messages"}),(0,ua.jsx)("div",{className:"flex flex-wrap gap-x-6 gap-y-3",children:[!0,!1].map(r=>(0,ua.jsxs)("label",{className:"inline-flex min-h-8 cursor-pointer items-center gap-2 text-sm",children:[(0,ua.jsx)("input",{type:"radio",name:"messages",className:"size-4 accent-dashboard-focus",checked:!!e.value.length===r,onChange:()=>e.onChange(r?t:[])}),r?"Send a message":"No success message"]},String(r)))})]}),e.value.length?(0,ua.jsxs)("div",{className:"grid gap-4 sm:gap-2",children:[e.value.map((r,n)=>{let o=e.original.findIndex(i=>JSON.stringify(i)===JSON.stringify(r));return(0,ua.jsxs)("div",{className:"flex min-w-0 flex-wrap items-center gap-2",children:[(0,ua.jsxs)("span",{className:"w-4 text-xs text-dashboard-text-muted",children:[n+1,"."]}),(0,ua.jsx)("div",{className:L("min-w-0 flex-1",e.value.length>1&&"order-last basis-full sm:order-none sm:basis-auto"),children:(0,ua.jsx)(mu,{"aria-label":`Message ${n+1} destination`,value:typeof r.destination=="string"?r.destination:`saved:${o}`,onChange:i=>{let s=a.find(u=>u.value===i.target.value);s&&e.onChange(e.value.map((u,c)=>c===n?s.outcome:u))},children:a.map(i=>(0,ua.jsx)("option",{value:i.value,children:i.label},i.value))})}),e.value.length>1?(0,ua.jsxs)(ua.Fragment,{children:[(0,ua.jsx)(oe,{size:"icon",className:"ml-auto sm:ml-0","aria-label":`Move message ${n+1} up`,disabled:n===0,onClick:()=>{let i=[...e.value];[i[n-1],i[n]]=[i[n],i[n-1]],e.onChange(i)},children:(0,ua.jsx)(mb,{size:16})}),(0,ua.jsx)(oe,{size:"icon","aria-label":`Remove message ${n+1}`,onClick:()=>e.onChange(e.value.filter((i,s)=>s!==n)),children:(0,ua.jsx)(Kn,{size:16})})]}):null]},n)}),e.value.length<5?(0,ua.jsxs)(oe,{className:"w-fit",onClick:()=>e.onChange([...e.value,{action:"send_message",destination:"task_creator"}]),children:[(0,ua.jsx)(fc,{size:15}),"Add message"]}):null]}):(0,ua.jsx)("p",{className:"m-0 text-sm leading-relaxed text-dashboard-text-muted",children:"Junior still does the work. No message is sent after success."}),(0,ua.jsxs)("p",{className:"m-0 text-xs leading-relaxed text-dashboard-text-muted",children:[e.value.length?"Messages are sent in this order. ":"","This does not limit actions in the instruction."]})]})}var ce=b(w(),1);function _W(e){let[t,a]=(0,Ps.useState)(e.automation),[r,n]=(0,Ps.useState)(()=>uI(e.automation)),[o,i]=(0,Ps.useState)({}),[s,u]=(0,Ps.useState)(),c=(0,Ps.useRef)(null),d=(0,Ps.useRef)(!1),f=Sn(),m=Ut(),h=CW(t,r),p=Object.keys(h).length>0,v={kind:t.kind,revision:t.revision,...h},x=RA(()=>p&&!d.current),g=(0,Ps.useRef)(null);(0,Ps.useEffect)(()=>{x.state==="blocked"&&g.current?.focus()},[x.state]);let y=`/api/automations/${encodeURIComponent(t.id)}`;(0,Ps.useEffect)(()=>{let G=fe=>{p&&!d.current&&(fe.preventDefault(),fe.returnValue="")};return window.addEventListener("beforeunload",G),()=>window.removeEventListener("beforeunload",G)},[p]);let S=()=>requestAnimationFrame(()=>(c.current?.querySelector('[aria-invalid="true"]')??c.current?.querySelector("[data-save-error]"))?.focus()),C=Xt({mutationFn:()=>Bg(Ns,y,v),onSuccess:async()=>{d.current=!0,await m.invalidateQueries({queryKey:["dashboard","automations"]}),f(e.returnPath,{state:{automationSaved:!0}})},onError:G=>{i(G instanceof Cn?G.fields??{}:{}),S()}});function I(G){s&&(n(G?{...uI(s),...h}:uI(s)),a(s),u(void 0),C.reset(),i({}))}let T=Xt({mutationFn:()=>Se(Ns,`${y}/edit`),onSuccess:u}),N=C.error instanceof Cn&&C.error.code==="conflict",k=G=>n(fe=>({...fe,...G})),U=G=>Object.entries(o).filter(([fe])=>fe===G||fe.startsWith(`${G}.`)).flatMap(([,fe])=>fe).join(" ")||void 0,B=t.kind==="scheduled"?"schedule":"trigger",le=t.ownedByViewer,z=e.summary.createdBy,J=!le&&t.credentialMode==="creator"&&(h.instruction!==void 0||t.kind==="event"&&h.trigger!==void 0),ee=U(B),ve=G=>({"aria-invalid":!!U(G)||void 0,"aria-describedby":U(G)?`${G}-error`:void 0});return(0,ce.jsxs)("form",{ref:c,noValidate:!0,onSubmit:G=>{if(G.preventDefault(),C.isPending||N||!p)return;let fe=MM.safeParse(v);if(!fe.success){let X={};for(let ue of fe.error.issues)(X[ue.path.join(".")]??=[]).push(ue.message);i(X),S();return}i({}),C.mutate()},children:[x.state==="blocked"?(0,ce.jsx)("div",{tabIndex:-1,ref:g,className:"mb-6 outline-none",children:(0,ce.jsxs)(uo,{title:"Discard unsaved changes?",children:[(0,ce.jsx)("p",{children:"Your changes have not been saved."}),(0,ce.jsxs)("div",{className:"flex gap-2",children:[(0,ce.jsx)(oe,{onClick:()=>x.reset(),children:"Keep editing"}),(0,ce.jsx)(oe,{onClick:()=>x.proceed(),children:"Discard changes"})]})]})}):null,C.error||Object.keys(o).length?(0,ce.jsx)("div",{tabIndex:-1,"data-save-error":!0,className:"mb-6 outline-none",children:(0,ce.jsxs)(uo,{tone:N?"warning":"error",title:N?"This automation changed while you were editing.":"Changes could not be saved.",children:[(0,ce.jsxs)("p",{className:"mt-1",children:["Your edits are still here."," ",N?"Review the latest version before saving again.":C.error instanceof Cn?C.error.apiError:"Check the fields below, or try again."]}),N?(0,ce.jsx)(oe,{disabled:T.isPending,onClick:()=>T.mutate(),children:T.isPending?"Loading\u2026":"Review latest version"}):null,T.error?(0,ce.jsx)("p",{role:"alert",children:"The latest version could not be loaded. Try again."}):null]})}):null,s?(0,ce.jsx)("div",{className:"mb-6",children:(0,ce.jsxs)(uo,{title:"Compare your edits with the latest saved version",children:[(0,ce.jsx)("p",{children:"Only the fields you changed are shown. Keeping your edits will replace these fields. Other saved fields stay unchanged."}),Object.entries(h).map(([G,fe])=>(0,ce.jsxs)("section",{className:"my-4",children:[(0,ce.jsx)("h3",{className:"text-sm font-semibold capitalize",children:G==="credentialMode"?"Credentials":G}),(0,ce.jsxs)("div",{className:"grid gap-3 sm:grid-cols-2",children:[(0,ce.jsxs)("div",{children:[(0,ce.jsx)("p",{children:"Latest saved"}),(0,ce.jsx)("pre",{className:"whitespace-pre-wrap break-words font-sans text-sm",children:TW(G==="schedule"&&s.kind==="scheduled"?cI(s):s[G])})]}),(0,ce.jsxs)("div",{children:[(0,ce.jsx)("p",{children:"Your edit"}),(0,ce.jsx)("pre",{className:"whitespace-pre-wrap break-words font-sans text-sm",children:TW(fe)})]})]})]},G)),(0,ce.jsxs)("div",{className:"flex flex-wrap gap-2",children:[(0,ce.jsx)(oe,{onClick:()=>I(!0),children:"Keep my changed fields"}),(0,ce.jsx)(oe,{onClick:()=>I(!1),children:"Use latest saved version"})]})]})}):null,le?null:(0,ce.jsxs)("p",{className:"mt-0 mb-6 max-w-2xl text-sm leading-relaxed text-dashboard-text-muted",children:[z," created this automation. You can edit it because it is in a public channel. Only ",z," can change where results go or turn on their connected accounts. Version history keeps every saved change."]}),(0,ce.jsxs)("fieldset",{disabled:C.isPending,className:"min-w-0",children:[(0,ce.jsxs)($s,{title:"What to do",detail:"Give Junior a clear instruction and a name you can find later.",children:[(0,ce.jsx)(Gt,{label:"Title",htmlFor:"title",error:U("title"),children:(0,ce.jsx)(Ta,{size:"comfortable",id:"title",value:r.title,placeholder:e.summary.title,onChange:G=>k({title:G.target.value}),...ve("title")})}),(0,ce.jsxs)(Gt,{label:"Instruction",htmlFor:"instruction",error:U("instruction"),children:[(0,ce.jsx)(bc,{prose:!0,id:"instruction",rows:8,value:r.instruction,onChange:G=>k({instruction:G.target.value}),...ve("instruction"),className:"resize-y text-base sm:text-sm"}),(0,ce.jsxs)("p",{className:"m-0 text-right text-xs text-dashboard-text-muted",children:[r.instruction.length.toLocaleString()," / 4,000"]})]})]}),(0,ce.jsx)($s,{title:"When to run",detail:t.kind==="scheduled"?"Choose a schedule in a specific timezone.":"Run when a matching event occurs.",children:(0,ce.jsxs)("div",{id:`${B}-error`,tabIndex:-1,"aria-invalid":!!ee||void 0,className:"grid min-w-0 gap-5 outline-none",children:[ee?(0,ce.jsx)("p",{role:"alert",className:"m-0 text-sm text-rose-300",children:ee}):null,t.kind==="scheduled"?(0,ce.jsx)(kW,{automation:t,value:r.schedule,onChange:G=>k({schedule:G})}):(0,ce.jsx)(IW,{value:r.trigger??t.trigger,original:t.trigger,onChange:G=>k({trigger:G})})]})}),(0,ce.jsxs)($s,{title:"Where results go",detail:"Choose who gets a message after successful work.",children:[U("outcomes")?(0,ce.jsx)("p",{role:"alert",className:"m-0 text-sm text-rose-300",children:U("outcomes")}):null,le?(0,ce.jsx)(LW,{value:r.outcomes,original:t.outcomes,destination:e.summary.destination,onChange:G=>k({outcomes:G})}):(0,ce.jsxs)(ce.Fragment,{children:[(0,ce.jsx)(fI,{outcomes:t.outcomes,destination:e.summary.destination}),(0,ce.jsxs)("p",{className:"m-0 text-xs text-dashboard-text-muted",children:["Only ",z," can change where results go."]})]})]}),(0,ce.jsxs)($s,{title:"Credentials",detail:"Choose which connected accounts Junior can use.",children:[(0,ce.jsxs)("fieldset",{className:"divide-y divide-dashboard-border-subtle rounded-md border border-dashboard-border-emphasis",children:[(0,ce.jsx)("legend",{className:"sr-only",children:"Credential mode"}),[["creator",le?"Your connected accounts":`${z}\u2019s connected accounts`,le?"Uses accounts connected by you, the creator.":`Uses accounts connected by ${z}. Only ${z} can turn this on.`],["system","System credentials only",le?"Does not use your connected accounts. Some work may not be possible.":"Does not use anyone\u2019s connected accounts. Some work may not be possible."]].map(([G,fe,X])=>(0,ce.jsxs)("label",{className:"flex cursor-pointer items-start gap-3 px-4 py-4 has-checked:bg-dashboard-fill-soft has-disabled:cursor-not-allowed has-disabled:opacity-60",children:[(0,ce.jsx)("input",{type:"radio",name:"credentials",className:"mt-0.5 size-4 shrink-0 accent-dashboard-focus",checked:J?G==="system":r.credentialMode===G,disabled:G==="creator"&&!le&&(t.credentialMode!=="creator"||J),onChange:()=>k({credentialMode:G})}),(0,ce.jsxs)("span",{children:[(0,ce.jsx)("span",{className:"block text-sm font-medium",children:fe}),(0,ce.jsx)("span",{className:"mt-1 block text-xs leading-relaxed text-dashboard-text-muted",children:X})]})]},G))]}),J?(0,ce.jsxs)(uo,{title:"Saving switches this automation to system credentials.",children:["Only ",z," can let a changed instruction",t.kind==="event"?" or trigger":""," use their connected accounts."]}):null,U("credentialMode")?(0,ce.jsx)("p",{role:"alert",children:U("credentialMode")}):null]})]}),(0,ce.jsx)("p",{className:"mb-5 text-xs leading-relaxed text-dashboard-text-muted sm:hidden",children:"Changes apply to future work. Saving does not run this automation."}),(0,ce.jsx)("div",{className:"sticky bottom-0 z-20 -mx-4 border-t border-dashboard-border-emphasis bg-dashboard-bg px-4 py-4 sm:-mx-8 sm:px-8",children:(0,ce.jsxs)("div",{className:"flex items-center justify-between gap-3",children:[(0,ce.jsxs)("div",{className:"min-w-0 flex-1",role:"status",children:[(0,ce.jsx)("p",{className:"m-0 text-xs font-medium sm:text-sm",children:C.isPending?"Saving\u2026":p?"Unsaved changes":"Unchanged"}),(0,ce.jsx)("p",{className:"mt-1 mb-0 hidden text-xs text-dashboard-text-muted sm:block",children:"Changes apply to future work. Saving does not run it."})]}),(0,ce.jsxs)("div",{className:"flex shrink-0 gap-2",children:[(0,ce.jsx)(te,{to:e.returnPath,className:"inline-flex min-h-11 items-center rounded-md border border-dashboard-border-emphasis px-3 text-sm text-dashboard-text no-underline sm:min-h-9",children:"Cancel"}),(0,ce.jsx)(oe,{type:"submit",tone:"primary",className:"min-h-11 sm:min-h-9",disabled:!p||C.isPending||N,children:"Save changes"})]})]})})]})}function TW(e){return e==null?"Not set":typeof e=="string"?e:JSON.stringify(e,null,2)}var Jg=b(w(),1);function NW(){return(0,Jg.jsx)("div",{role:"status","aria-label":"Loading automation editor",children:["What to do","When to run","Where results go","Credentials"].map((e,t)=>(0,Jg.jsxs)($s,{title:e,children:[(0,Jg.jsx)(et,{className:"h-4 w-24"}),(0,Jg.jsx)(et,{className:t===0?"h-48 w-full":"h-20 w-full"})]},e))})}var Vt=b(w(),1);function RW(e){let{automationId:t}=Ja(),a=xt(),r=Hg(e.enabled,t),n=r.data&&!(r.data.kind==="scheduled"&&r.data.status==="completed"),o=_e({queryKey:["dashboard","automations","edit",t],enabled:e.enabled&&!!n,retry:!1,queryFn:({signal:d})=>Se(Ns,`/api/automations/${encodeURIComponent(t)}/edit`,d)}),i=`/automations/list${a.search}`,s=r.data;Si(s?n?`${s.title} \xB7 Edit`:s.title:"Edit automation");let u=s?.kind==="event"?s.status!=="active"?s.status:s.triggerAvailable?"active":"unavailable":s?.status,c=u==="active"?"success":u==="blocked"||u==="unavailable"?"warning":"neutral";return(0,Vt.jsx)(b4,{children:(0,Vt.jsxs)("div",{className:"mx-auto w-full min-w-0 max-w-5xl px-4 pt-7 sm:px-8 sm:pt-9",children:[(0,Vt.jsxs)(te,{to:i,className:"inline-flex min-h-8 items-center gap-2 text-sm text-dashboard-text-muted no-underline hover:text-dashboard-text",children:[(0,Vt.jsx)(ao,{"aria-hidden":!0,size:15}),"All automations"]}),(0,Vt.jsxs)("div",{className:"mt-4 mb-8 flex flex-wrap items-start justify-between gap-4",children:[(0,Vt.jsxs)("div",{className:"min-w-0",children:[(0,Vt.jsx)("h1",{className:"m-0 break-words font-display text-3xl font-light tracking-tight",children:s&&!n?s.title:"Edit automation"}),s?(0,Vt.jsxs)("p",{className:"mt-2 mb-0 text-sm text-dashboard-text-muted",children:["Created by ",s.ownedByViewer?"you":s.createdBy," \xB7"," ",s.destination.label]}):null]}),s?(0,Vt.jsxs)("div",{className:"flex items-center gap-4",children:[(0,Vt.jsx)(te,{to:`/automations/${encodeURIComponent(s.id)}/versions${a.search}`,className:"text-sm text-dashboard-text-muted underline underline-offset-2 hover:text-dashboard-text",children:"Version history"}),(0,Vt.jsx)(Zt,{tone:c,children:u==="unavailable"?"Trigger unavailable":u})]}):null]}),!s&&r.error||!o.data&&o.error?(0,Vt.jsxs)(uo,{tone:"error",title:"Automation could not be loaded.",children:["It may no longer be available, or you may not have access."," ",(0,Vt.jsx)(oe,{onClick:()=>{r.refetch(),n&&o.refetch()},children:"Try again"})]}):!s||n&&!o.data?(0,Vt.jsx)(NW,{}):n&&o.data?(0,Vt.jsx)(_W,{automation:o.data,summary:s,returnPath:i},t):(0,Vt.jsx)(SSe,{automation:s})]})})}function SSe({automation:e}){return(0,Vt.jsxs)(Vt.Fragment,{children:[(0,Vt.jsx)("p",{className:"mb-6 text-sm text-dashboard-text-muted",children:"This automation has completed and cannot be edited. It will not run again."}),(0,Vt.jsx)($s,{title:"What to do",detail:"The saved instruction.",children:(0,Vt.jsx)("p",{className:"m-0 whitespace-pre-wrap break-words text-sm leading-relaxed",children:e.instruction})}),(0,Vt.jsx)($s,{title:"When to run",detail:"The saved trigger.",children:e.kind==="scheduled"?(0,Vt.jsxs)("p",{className:"m-0 text-sm",children:[e.schedule," \xB7 ",e.timezone]}):(0,Vt.jsxs)("div",{className:"grid gap-3 text-sm",children:[(0,Vt.jsx)("p",{className:"m-0 break-words",children:e.resource}),(0,Vt.jsx)("p",{className:"m-0 break-words",children:e.events.join(", ")}),e.match?(0,Vt.jsx)("pre",{className:"whitespace-pre-wrap break-words text-xs",children:JSON.stringify(e.match,null,2)}):null]})}),(0,Vt.jsx)($s,{title:"Where results go",detail:"Messages after successful work.",children:(0,Vt.jsx)(fI,{outcomes:e.outcomes,destination:e.destination})}),(0,Vt.jsx)($s,{title:"Credentials",detail:"The accounts Junior can use.",children:(0,Vt.jsx)("p",{className:"m-0 text-sm",children:e.credentialMode==="creator"?`Uses ${e.ownedByViewer?"your":`${e.createdBy}\u2019s`} connected accounts.`:"System credentials only."})})]})}var Pp=b(V(),1);var AW=b(V(),1);function mI(){return(0,AW.useSyncExternalStore)(e=>jl.subscribe(e),()=>jl.isOnline(),()=>!0)}var PW=b(w(),1);function $W(){return mI()?null:(0,PW.jsx)("div",{"aria-live":"polite",className:"border-t border-amber-300/15 bg-amber-300/[0.07] px-3 py-1.5 text-center font-sans text-xs text-amber-100/80",role:"status",children:"You\u2019re offline. Drafts stay on this device."})}var S4=b(w(),1);function pI(){return(0,S4.jsx)("div",{className:"relative grid size-10 shrink-0 select-none place-items-center overflow-visible",children:(0,S4.jsx)("img",{alt:"",className:"relative size-11 max-w-none -translate-y-0.5 object-contain opacity-90 drop-shadow-[0_0_7px_rgba(255,255,255,0.16)]",draggable:!1,src:"/_junior/dashboard/avatar.png"})})}var DW=["relative","overflow-hidden","bg-white/15","before:absolute","before:inset-0","before:content-['']","before:bg-[linear-gradient(90deg,#ff4d6d,#ffb703,#56f39a,#4cc9f0,#9b5de5,#ff4d6d)]","before:bg-[length:200%_100%]","before:animate-[junior-rainbow-flow_1.2s_linear_infinite]","motion-reduce:before:animate-none"].join(" ");var Qd=b(w(),1);function En(e){return(0,Qd.jsx)("div",{className:L(Ba,"grid min-h-[calc(100dvh-5rem)] place-items-center px-4 py-8 md:px-8"),children:(0,Qd.jsxs)("section",{className:"grid w-full max-w-lg grid-cols-[auto_minmax(0,1fr)] items-center gap-3 rounded-lg border border-dashboard-border-emphasis bg-dashboard-surface-raised p-4",children:[(0,Qd.jsx)(pI,{}),(0,Qd.jsxs)("div",{children:[(0,Qd.jsx)("div",{className:"font-bold",children:e.label}),(0,Qd.jsx)("div",{"aria-label":e.label,className:`${DW} mt-3 h-1.5 w-full`,role:"progressbar"})]})]})})}var w4="0.256.0",hI=typeof w4=="string"&&w4.trim()?w4:"unknown";var tS=b(w(),1);function EW(e){return wSe(e.serverVersion)?(0,tS.jsxs)("div",{"aria-live":"polite",className:"flex flex-wrap items-center justify-center gap-x-3 gap-y-1 border-t border-dashboard-accent/15 bg-dashboard-accent/[0.07] px-3 py-1.5 text-center font-sans text-xs text-dashboard-accent-text/80",role:"status",children:[(0,tS.jsx)("span",{children:"The dashboard changed. Refresh to load the latest version."}),(0,tS.jsx)("button",{className:"cursor-pointer border-0 bg-transparent p-0 font-sans font-semibold text-dashboard-accent-text underline decoration-dashboard-accent/40 underline-offset-2 hover:text-dashboard-text-solid",onClick:()=>window.location.reload(),type:"button",children:"Refresh"})]}):null}function wSe(e){return!!e&&hI!=="unknown"&&e!=="unknown"&&e!==hI}var aS=b(w(),1);function pu(e){return(0,aS.jsxs)(Eo,{children:[(0,aS.jsx)(We,{description:e.description,title:e.title}),(0,aS.jsx)(sr,{label:e.label,variant:e.variant})]})}var ku=b(V(),1);var gI={"angular-html":()=>import("./chunks/angular-html-ZNDXTZDN.js"),"angular-ts":()=>import("./chunks/angular-ts-ON3WFVNV.js"),astro:()=>import("./chunks/astro-TCFNN3TA.js"),blade:()=>import("./chunks/blade-XRKVUGGE.js"),c:()=>import("./chunks/c-WHCDUHJR.js"),coffee:()=>import("./chunks/coffee-NWMA7ZVV.js"),coffeescript:()=>import("./chunks/coffee-NWMA7ZVV.js"),cpp:()=>import("./chunks/cpp-7ZDYJCCI.js"),"c++":()=>import("./chunks/cpp-7ZDYJCCI.js"),css:()=>import("./chunks/css-XF3SDJYW.js"),csv:()=>import("./chunks/csv-I2Y5BPVG.js"),glsl:()=>import("./chunks/glsl-SDKJ4MVB.js"),graphql:()=>import("./chunks/graphql-XJBKAS4G.js"),gql:()=>import("./chunks/graphql-XJBKAS4G.js"),haml:()=>import("./chunks/haml-QQIA6ZDV.js"),handlebars:()=>import("./chunks/handlebars-A4STSCQ6.js"),hbs:()=>import("./chunks/handlebars-A4STSCQ6.js"),html:()=>import("./chunks/html-T3MIDC6T.js"),"html-derivative":()=>import("./chunks/html-derivative-A5ABNIZH.js"),http:()=>import("./chunks/http-VGZ3EXS5.js"),hurl:()=>import("./chunks/hurl-TO4NQQLI.js"),imba:()=>import("./chunks/imba-P3ARIZRP.js"),java:()=>import("./chunks/java-WCBM5OUU.js"),javascript:()=>import("./chunks/javascript-TQH7GGAM.js"),js:()=>import("./chunks/javascript-TQH7GGAM.js"),cjs:()=>import("./chunks/javascript-TQH7GGAM.js"),mjs:()=>import("./chunks/javascript-TQH7GGAM.js"),jinja:()=>import("./chunks/jinja-UYMB4X6S.js"),jison:()=>import("./chunks/jison-ED4UFXGK.js"),json:()=>import("./chunks/json-XRHV7G5W.js"),json5:()=>import("./chunks/json5-2OA2ZMVI.js"),jsonc:()=>import("./chunks/jsonc-KO53QF6Y.js"),jsonl:()=>import("./chunks/jsonl-GHTNFMM6.js"),jsx:()=>import("./chunks/jsx-V5TSP3NI.js"),julia:()=>import("./chunks/julia-EI7BACOV.js"),jl:()=>import("./chunks/julia-EI7BACOV.js"),less:()=>import("./chunks/less-FPWZXUDW.js"),markdown:()=>import("./chunks/markdown-QWIM2DOI.js"),md:()=>import("./chunks/markdown-QWIM2DOI.js"),marko:()=>import("./chunks/marko-3POAQSZY.js"),mdc:()=>import("./chunks/mdc-KT6TTBUF.js"),mdx:()=>import("./chunks/mdx-CWS3UMSH.js"),php:()=>import("./chunks/php-3CK4FBZI.js"),postcss:()=>import("./chunks/postcss-7K34RN34.js"),pug:()=>import("./chunks/pug-IEW5PJRA.js"),jade:()=>import("./chunks/pug-IEW5PJRA.js"),python:()=>import("./chunks/python-GCPXLELR.js"),py:()=>import("./chunks/python-GCPXLELR.js"),r:()=>import("./chunks/r-XV5O7BSV.js"),regexp:()=>import("./chunks/regexp-655IUQFI.js"),regex:()=>import("./chunks/regexp-655IUQFI.js"),sass:()=>import("./chunks/sass-MSBN6O54.js"),scss:()=>import("./chunks/scss-N73GNFL4.js"),shellscript:()=>import("./chunks/shellscript-OPDT4ZZ3.js"),bash:()=>import("./chunks/shellscript-OPDT4ZZ3.js"),sh:()=>import("./chunks/shellscript-OPDT4ZZ3.js"),shell:()=>import("./chunks/shellscript-OPDT4ZZ3.js"),zsh:()=>import("./chunks/shellscript-OPDT4ZZ3.js"),sql:()=>import("./chunks/sql-ZR72I7RP.js"),stylus:()=>import("./chunks/stylus-NVEQWGLA.js"),styl:()=>import("./chunks/stylus-NVEQWGLA.js"),svelte:()=>import("./chunks/svelte-ZZAXFLSI.js"),"ts-tags":()=>import("./chunks/ts-tags-MCSPJMMM.js"),lit:()=>import("./chunks/ts-tags-MCSPJMMM.js"),tsx:()=>import("./chunks/tsx-ZTNB67YL.js"),typescript:()=>import("./chunks/typescript-HV6B525T.js"),ts:()=>import("./chunks/typescript-HV6B525T.js"),cts:()=>import("./chunks/typescript-HV6B525T.js"),mts:()=>import("./chunks/typescript-HV6B525T.js"),vue:()=>import("./chunks/vue-WXFFFGZ3.js"),"vue-html":()=>import("./chunks/vue-html-SKWAUQDE.js"),"vue-vine":()=>import("./chunks/vue-vine-V3A5HTCZ.js"),wasm:()=>import("./chunks/wasm-JWJ5BADC.js"),wgsl:()=>import("./chunks/wgsl-ZCQ7MKDM.js"),wit:()=>import("./chunks/wit-MLLAONFF.js"),xml:()=>import("./chunks/xml-VST5CLIL.js"),yaml:()=>import("./chunks/yaml-BX3BWN2A.js"),yml:()=>import("./chunks/yaml-BX3BWN2A.js")};var vI=b(w(),1);function fo(e){if(typeof e!="number"||!Number.isFinite(e))return"";let t=Math.max(0,Math.floor(e));if(t<1e3)return`${t}ms`;if(t<6e4){let n=t/1e3;return`${n.toFixed(n<10?1:0)}s`}let a=[],r=[["mo",2592e6],["d",864e5],["h",36e5],["m",6e4],["s",1e3]];for(let[n,o]of r){let i=Math.floor(t/o);if(i!==0){if(a.push(`${i}${n}`),a.length===2)break;t%=o}}return a.join(" ")}function xc(e){return(0,vI.jsx)(vI.Fragment,{children:fo(e.value)||e.fallback||null})}function Qg(e){return Date.parse(e.createdAt)}function Xd(e,t,a){return{parts:a,role:t,sourceSeq:e.seq,timestamp:Qg(e)}}function CSe(e){let t=new Set;for(let a of e){let r=a.data;r.type==="handoff"&&r.triggeringToolCallId&&t.add(r.triggeringToolCallId),r.type==="subagent"&&r.parentToolCallId&&t.add(r.parentToolCallId)}return t}function kSe(e){let t=new Set;for(let a of e)a.messageId&&t.add(a.messageId);return t}function ISe(e,t){return{delivery:e.delivery,messageId:e.messageId,parts:e.redacted?[{type:"text",redacted:!0}]:[{type:"text",text:e.text??""}],...e.attachments?{attachments:e.attachments}:void 0,pending:!0,role:"user",source:e.source,sourceSeq:Number.MAX_SAFE_INTEGER-1e6+t,timestamp:Date.parse(e.createdAt),...e.actorIdentity?{actorIdentity:e.actorIdentity}:void 0}}function LSe(e,t){if(!t?.length)return e;let a=TSe(e,t);return a.length===0?e:[...e,...a]}function TSe(e,t){if(!t?.length)return[];let a=kSe(e);return t.filter(r=>!a.has(r.messageId)).map((r,n)=>ISe(r,n))}function C4(e,t){return k4(e.events,e.annotations,t)}function k4(e,t,a){let r=CSe(e),n=new Map,o=new Map,i=new Map,s=[],u=new Map,c=new Map,d,f=(h,p)=>{if(r.has(p.toolCallId))return;let v="output"in p?p.output:void 0,x=n.get(p.toolCallId);if(x){x.name=p.name,x.status=p.status,p.input!==void 0&&(x.input=p.input),v!==void 0&&(x.output=v),x.startedTimestamp===void 0&&p.startedAt&&(x.startedTimestamp=Date.parse(p.startedAt)),p.status!=="running"&&(x.resultTimestamp=Qg(h));return}let g={type:"tool_call",id:p.toolCallId,name:p.name,status:p.status,...p.input===void 0?void 0:{input:p.input},...v===void 0?void 0:{output:v},...p.status==="running"?void 0:{resultTimestamp:Qg(h)}},y={...Xd(h,"tool",[g]),sourceSeq:p.startedSeq??h.seq,timestamp:p.startedAt?Date.parse(p.startedAt):Qg(h)};n.set(p.toolCallId,g),o.set(p.toolCallId,y),s.push(y)};for(let h of e){let p=h.data;if(p.type==="message"){let v={...Xd(h,p.role,[p.redacted?{type:"text",redacted:!0}:{type:"text",text:p.text}]),messageId:p.messageId,...p.attachments?{attachments:p.attachments}:void 0,...p.cards?{cards:gM(p.cards,t??[])}:void 0,...p.actorIdentity?{actorIdentity:p.actorIdentity}:void 0,...p.eventType?{eventType:p.eventType}:void 0,eventObjectType:p.eventObjectType,...p.trustedSummary?{trustedSummary:p.trustedSummary}:void 0,...p.explicitMention!==void 0?{explicitMention:p.explicitMention}:void 0,...p.source?{source:p.source}:void 0};s.push(v),u.set(v.messageId,v),v.role==="user"&&(d=v);continue}if(p.type==="message_handled"){let v=u.get(p.messageId);v?.role==="user"&&v.explicitMention===!1&&!v.eventType&&(v.context=!0);continue}if(p.type==="assistant_message"){if(p.parts.length===0)continue;s.push(Xd(h,"assistant",p.parts.map(v=>v.redacted?{type:"reasoning",redacted:!0}:{type:"reasoning",text:v.text})));continue}if(p.type==="turn_lifecycle"&&p.state==="started"){let v=p.inputMessageIds?.map(g=>u.get(g)).filter(g=>g!==void 0),x=v?.slice().reverse().find(g=>g.role==="user");x?c.set(p.turnId,x):d&&c.set(p.turnId,d);for(let g of v??[])g.role==="user"&&g.explicitMention===!1&&!g.eventType&&(g.context=!0);continue}if(p.type==="turn_routed"){let v=c.get(p.turnId);v&&(v.route={modelProfile:p.modelProfile,modelId:p.modelId,reasoningLevel:p.reasoningLevel,...p.confidence!==void 0?{confidence:p.confidence}:void 0,source:p.source});continue}if(p.type==="turn_context"){let v=c.get(p.turnId);v&&(v.contexts??=[],v.contexts.push({content:p.content,kind:p.kind,loadedAt:h.createdAt,pluginName:p.pluginName,version:p.version}));continue}if(p.type==="tool_calls"){for(let v of p.calls)f(h,v);if(p.assistant){let v=[];for(let x of p.assistant.parts){if(x.type==="reasoning"){v.push(x.redacted?{type:"reasoning",redacted:!0}:{type:"reasoning",text:x.text});continue}if(r.has(x.toolCallId))continue;let g=n.get(x.toolCallId);if(!g)continue;let y=o.get(x.toolCallId);if(y){y.sourceSeq!==h.seq&&(g.startedTimestamp=y.timestamp);let S=s.indexOf(y);S>=0&&s.splice(S,1),o.delete(x.toolCallId)}v.push(g)}v.length>0&&s.push(Xd(h,"assistant",v))}continue}if(p.type==="subagent"){let v=`${p.childConversationId}:${p.startedSeq}`,x=i.get(v),g=p.status==="running"?void 0:Qg(h);if(x){x.status=p.status,g===void 0?delete x.finishedTimestamp:x.finishedTimestamp=g;continue}let y={type:"subagent",id:v,childConversationId:p.childConversationId,subagentKind:p.subagentKind,status:p.status,...g===void 0?void 0:{finishedTimestamp:g},...p.agentName?{agentName:p.agentName}:void 0,...p.task?{task:p.task}:void 0,...p.title?{title:p.title}:void 0};i.set(v,y),s.push({...Xd(h,"tool",[y]),sourceSeq:p.startedSeq,timestamp:Date.parse(p.startedAt)});continue}if(p.type==="structured_event"){s.push(Xd(h,"system",[{type:"structured_event",namespace:p.namespace,name:p.name,version:p.version,presentation:p.presentation}]));continue}if(p.type==="attachments_delivered"){s.push(Xd(h,"system",[{type:"attachments_delivered",attachments:p.attachments}]));continue}if(p.type==="compaction"||p.type==="handoff"){s.push(Xd(h,"system",[{type:"context_event",event:p.type==="handoff"?{type:p.type,createdAt:h.createdAt,modelId:p.modelId,modelProfile:p.modelProfile,...p.summary?{summary:p.summary}:void 0,...p.reasoningLevel?{reasoningLevel:p.reasoningLevel}:void 0}:{type:p.type,createdAt:h.createdAt,...p.modelId?{modelId:p.modelId}:void 0,...p.modelProfile?{modelProfile:p.modelProfile}:void 0,...p.summary?{summary:p.summary}:void 0,...p.details?{details:p.details}:void 0}}]));continue}if(p.type==="turn_lifecycle"&&p.state==="failed"){s.push({role:p.failureCode==="delivery_failed"?"system":"assistant",failureCode:p.failureCode,...p.failureReason?{failureReason:p.failureReason}:void 0,...p.eventId?{eventId:p.eventId}:void 0,...p.sentryEventUrl?{sentryEventUrl:p.sentryEventUrl}:void 0,parts:[],sourceSeq:h.seq,timestamp:Qg(h)});continue}}let m=s.filter(h=>h.role!=="user"||h.eventType!==void 0||h.explicitMention!==!1||h.context===!0).sort((h,p)=>h.sourceSeq-p.sourceSeq);return LSe(m,a)}function MW(){try{return Intl.DateTimeFormat().resolvedOptions().timeZone}catch{return"UTC"}}var L4=MW();function OW(e){L4=e||MW()}function ef(){return L4}function bI(){return L4}function _Se(e){return e.status==="active"}function NSe(e){return e.status==="failed"}function RSe(e){return e.status==="active"}function ASe(e){return e.status==="failed"}function xI(e){if(!e)return null;let t=Date.parse(e);return Number.isFinite(t)?t:null}function un(e,t){let a=xI(e);return a==null?"none":new Date(a).toLocaleString(void 0,{...t,timeZone:bI()})}function Jn(e){let t=xI(e);if(t==null)return"not updated yet";let a=Math.round((t-Date.now())/1e3),r=Math.abs(a),n=[["year",3600*24*365],["month",3600*24*30],["week",3600*24*7],["day",3600*24],["hour",3600],["minute",60]];for(let[o,i]of n)if(r>=i)return new Intl.RelativeTimeFormat(void 0,{numeric:"auto"}).format(Math.round(a/i),o);return"just now"}function ep(e){if(typeof e!="number"||!Number.isFinite(e))return"none";let t=Math.max(0,Math.floor(e));if(t<1e3)return`${t}ms`;let a=t/1e3;if(a<60)return`${a.toFixed(a<10?1:0)}s`;let r=Math.round(a),n=Math.floor(r/60),o=r%60;return`${n}m ${o}s`}function zW(e){if(e===void 0)return;let t=typeof e=="string"?e:JSON.stringify(e);if(t===void 0)return;let a=new TextEncoder().encode(t).byteLength;return a<1e3?`${a}b`:`${Math.round(a/1e3)}kb`}function Xg(e,t){if(!(typeof e!="number"||typeof t!="number"||t<e))return ep(t-e)}function Sc(e){if(typeof e!="number"||!Number.isFinite(e))return"";let t=Math.max(0,Math.floor(e));return t===0?"":fo(t)}function $a(e,t=!1){if(typeof e!="number"||!Number.isFinite(e))return"no timestamp";let a=new Date(e);return t?a.toLocaleString(void 0,{dateStyle:"medium",timeStyle:"medium",timeZone:bI()}):a.toLocaleTimeString(void 0,{timeZone:bI()})}function SI(e){if(typeof e!="number"||!Number.isFinite(e))return"no timestamp";let t=Math.round((e-Date.now())/1e3),a=Math.abs(t),r=[["year",3600*24*365],["month",3600*24*30],["week",3600*24*7],["day",3600*24],["hour",3600]],[n,o]=r.find(([,i])=>a>=i)??r.at(-1);return new Intl.RelativeTimeFormat(void 0,{numeric:"auto"}).format(Math.round(t/o),n)}function UW(e){let t=new Date(e),a={dateStyle:"medium",timeStyle:"long"};return{local:t.toLocaleString(void 0,{...a,timeZone:bI()}),utc:t.toLocaleString(void 0,{...a,timeZone:"UTC"})}}function jW(e){if(typeof e!="number"||!Number.isFinite(e))return"0";let t=Math.max(0,Math.floor(e));if(t<1e3)return String(t);let a=[["t",1e12],["b",1e9],["m",1e6],["k",1e3]],[r,n]=a.find(([,s])=>t>=s)??a[1],o=t/n;return`${o>=100||Number.isInteger(o)||o>=10?Math.round(o).toString():(Math.floor(o*10)/10).toFixed(1).replace(/\.0$/,"")}${r}`}function Ym(e){return typeof e=="number"&&Number.isFinite(e)?Math.max(0,Math.floor(e)):void 0}function $Se(e){return[e.inputTokens,e.outputTokens,e.cachedInputTokens,e.cacheCreationTokens].reduce((t,a)=>{let r=Ym(a);return r===void 0?t:(t??0)+r},void 0)}function tp(e){let t=e.toLowerCase();return t==="assistant"?"assistant":t==="user"?"user":t==="system"?"system":t.includes("tool")?"tool":"other"}function tf(e,t){let a=tp(t.role);return a==="assistant"?Pt():a==="user"?Yd(t.actorIdentity)??Yd(e.actorIdentity)??"User":a==="system"?"System":a==="tool"?"Tool":t.role||"Unknown"}function re(e){return jW(e)}function wi(e){return typeof e!="number"||!Number.isFinite(e)||e<=0?"0":e<10?(Math.round(e*10)/10).toFixed(1).replace(/\.0$/,""):re(e)}function ml(e){if(!e)return;let t={totalTokens:0};t.reasoningTokens=Ym(e.reasoningTokens);let a=$Se(e);if(a!==void 0)t.totalTokens=a,t.inputTokens=Ym(e.inputTokens),t.outputTokens=Ym(e.outputTokens),t.cachedInputTokens=Ym(e.cachedInputTokens),t.cacheCreationTokens=Ym(e.cacheCreationTokens);else{let r=Ym(e.totalTokens);r!==void 0&&(t.totalTokens=r,t.providerTotalTokens=r)}return t.totalTokens>0?t:void 0}function wI(e){if(!e?.length)return;let t={totalTokens:0};for(let a of e){let r=ml(a.usage);if(r){t.totalTokens+=r.totalTokens;for(let n of["inputTokens","outputTokens","cachedInputTokens","cacheCreationTokens","reasoningTokens"]){let o=r[n];o!==void 0&&(t[n]=(t[n]??0)+o)}}}return t.totalTokens>0?t:void 0}function T4(e){return e?`${jW(e.totalTokens)} tokens`:""}function CI(e){return T4(ml(e))}function nS(e){return typeof e=="number"&&Number.isFinite(e)&&e>=0?e:void 0}function _4(e,t){return Math.round((e+t)*1e12)/1e12}function Mo(e){if(!e?.cost)return;let t={total:0},a=e.cost,r=nS(a.total),n={input:nS(a.input),output:nS(a.output),cacheRead:nS(a.cacheRead),cacheWrite:nS(a.cacheWrite)},o=Object.values(n).reduce((i,s)=>i+(s??0),0);return t.total=_4(t.total,r??o),t.input=n.input,t.output=n.output,t.cacheRead=n.cacheRead,t.cacheWrite=n.cacheWrite,r!==void 0||o>0?t:void 0}function kI(e){let t;for(let a of e??[]){let r=Mo(a.usage);r&&(t=_4(t??0,r.total))}return t===void 0?void 0:{total:t}}function ze(e){if(!e)return"";let t=e.total>0&&e.total<.01?4:2;return new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",minimumFractionDigits:2,maximumFractionDigits:t}).format(e.total)}function ap(e){return e?new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",minimumFractionDigits:2,maximumFractionDigits:4}).format(e.total):""}function Yg(e,t){if(!(!e&&!t))return{...e,total:_4(e?.total??0,t?.costUsd??0)}}function II(e,t){return ze(Yg(Mo(e),t))}function BW(e){return Sc(e.cumulativeDurationMs)||"none"}function PSe(e,t){return(xI(t)??0)-(xI(e)??0)}function ev(e){return e?.agentTree?.at(-1)?.label??(e?.displayTitle?.trim()||void 0)}function jr(e){return e?.displayTitle??"Conversation"}function Yd(e){let t=e?.email?.trim()||void 0,a=e?.fullName?.trim()||void 0,r=e?.slackUserName?.trim()||void 0;return t??a??r??e?.slackUserId}function pl(e,t={}){let a=e.channel;if(!a)return;let n=t.includeId??!0?` (${a})`:"";if(e.channelNameRedacted&&e.channelName)return`${e.channelName}${n}`;let o=e.channelName?.replace(/^#/,"");return a.startsWith("D")?`Direct Message${n}`:a.startsWith("C")?o?`#${o}${n}`:`Public Channel${n}`:a.startsWith("G")?o?.startsWith("mpdm-")?`Group DM${n}`:`Private Channel${n}`:o?`${o}${n}`:a}function DSe(e){return NSe(e)?"failed":_Se(e)?"active":"idle"}function af(e){return RSe(e)?"active":ASe(e)?"failed":"idle"}function rS(e){return e.eventHistory.status==="redacted"?"Transcript hidden because this conversation is not public.":e.eventHistory.status==="expired"?"Transcript expired for this conversation.":DSe(e)==="active"?"Transcript pending while this conversation is active.":"Transcript unavailable for this conversation."}function hl(e){return`/people/${encodeURIComponent(e)}`}function FW(e){return`/system/locations/${encodeURIComponent(e)}`}function Xi(e){return`/automations/${encodeURIComponent(e)}`}function ESe(e){let t=e?.trim().toLowerCase();if(!t)return"markdown";let r={console:"shellscript",htm:"html",js:"javascript",jsonl:"json",md:"markdown",ndjson:"json",sh:"shellscript",text:"markdown",txt:"markdown",xml:"xml",yml:"yaml"}[t]??t;return Object.hasOwn(gI,r)?r:"markdown"}function HW(e){let t=e.trim();if(t)try{return JSON.stringify(JSON.parse(t),null,2)}catch{return}}function VW(e){let t=e.trim().split(/\r?\n/).filter(r=>r.trim().length>0);if(t.length<2)return;let a=[];for(let r of t){let n=HW(r);if(!n)return;a.push(n)}return a.join(`
71
71
  `)}function qW(e){return HW(e)??VW(e)}function yI(e,t){return t==="json"?qW(e)??e:e}function I4(e){let t=e.trim();if(!t)return"markdown";try{return JSON.parse(t),"json"}catch{}return VW(t)?"json":"markdown"}function ZW(e){let t=[],a=/```([A-Za-z0-9_-]+)?\n([\s\S]*?)```/g,r=0,n;for(;n=a.exec(e);){let s=e.slice(r,n.index).trim();if(s){let c=I4(s);t.push({code:yI(s,c),fenced:!1,language:c})}let u=ESe(n[1]);t.push({code:yI(n[2]??"",u),fenced:!0,language:u}),r=n.index+n[0].length}let o=e.slice(r).trim();if(o){let s=I4(o);t.push({code:yI(o,s),fenced:!1,language:s})}if(t.length>0)return t;let i=I4(e);return[{code:yI(e,i),fenced:!1,language:i}]}function Yi(e){return e.map(t=>({activityPreview:t.activityPreview,annotations:t.annotations,sidebarAnnotations:t.sidebarAnnotations,archivedAt:t.archivedAt,auxiliaryCosts:t.auxiliaryCosts,channel:t.channel,channelName:t.channelName,channelNameRedacted:t.channelNameRedacted,childAgentTotals:t.childAgentTotals,cumulativeDurationMs:t.cumulativeDurationMs,cumulativeUsage:t.cumulativeUsage,displayTitle:t.displayTitle,id:t.conversationId,lastProgressAt:t.lastProgressAt,lastSeenAt:t.lastSeenAt,locationId:t.locationId,locationUrl:t.locationUrl,actorIdentity:t.actorIdentity,participants:t.participants,sentryTraceUrl:t.sentryTraceUrl,startedAt:t.startedAt,status:t.status,surface:t.surface,traceId:t.traceId,isPriority:t.isPriority,unfinishedWork:t.unfinishedWork,visibility:t.visibility})).sort((t,a)=>PSe(t.lastSeenAt,a.lastSeenAt))}function GW(e){if(!e)return;let t=Yi([e])[0];return t?{...t,displayTitle:e.displayTitle}:void 0}function hu(e){return e==null||e===""?"":typeof e=="string"?qW(e)??e:JSON.stringify(e,null,2)??""}var KW=b(w(),1);function Fa(e){return(0,KW.jsx)("p",{className:L("m-0 text-sm text-rose-300",e.className),role:"alert",children:e.children})}var gl=b(w(),1);function LI(e){return e.hasMore?(0,gl.jsx)(oe,{className:L("justify-self-center",e.className),disabled:e.loading,onClick:e.onLoadMore,children:e.loading?"Loading\u2026":"Load more"}):null}function np(e,t,a){let n=(Math.max(1,t)-1)*a;return e.slice(n,n+a)}function wc(e,t){return e<=0?1:Math.max(1,Math.ceil(e/t))}function Cc(e){if(e.total<=e.pageSize||e.pageCount<=1)return null;let t=Math.min(Math.max(1,e.page),e.pageCount),a=(t-1)*e.pageSize+1,r=Math.min(e.total,t*e.pageSize);return(0,gl.jsxs)("div",{"aria-label":"Pagination",className:L("flex flex-wrap items-center justify-between gap-3",e.className),children:[(0,gl.jsxs)("p",{className:"m-0 font-sans tabular-nums text-xs text-dashboard-text-muted",children:["Showing ",a.toLocaleString("en-US"),"-",r.toLocaleString("en-US")," of"," ",e.total.toLocaleString("en-US")]}),(0,gl.jsxs)("div",{className:"flex items-center gap-2",children:[(0,gl.jsx)(oe,{"aria-label":"Previous page",disabled:t<=1,onClick:()=>e.onPageChange(t-1),size:"icon",children:(0,gl.jsx)(vb,{"aria-hidden":"true",size:16})}),(0,gl.jsxs)("span",{className:"min-w-16 text-center font-sans tabular-nums text-xs text-dashboard-text-muted",children:[t," / ",e.pageCount]}),(0,gl.jsx)(oe,{"aria-label":"Next page",disabled:t>=e.pageCount,onClick:()=>e.onPageChange(t+1),size:"icon",children:(0,gl.jsx)(sa,{"aria-hidden":"true",size:16})})]})]})}var oS=b(w(),1);function cn(e){let t=e.size??"compact";return(0,oS.jsxs)("div",{className:L("relative min-w-0",e.className),children:[(0,oS.jsx)(Pd,{"aria-hidden":"true",className:L("pointer-events-none absolute top-1/2 -translate-y-1/2 text-dashboard-text-muted",MSe[t]),size:t==="compact"?13:14,strokeWidth:2.5}),(0,oS.jsx)("input",{"aria-label":e.label,className:L("w-full rounded-md border border-dashboard-border font-sans text-sm text-dashboard-text outline-none transition-colors placeholder:text-dashboard-text-muted/70 hover:border-dashboard-border-emphasis focus:border-dashboard-focus",OSe[t]),onChange:a=>e.onChange(a.currentTarget.value),placeholder:e.placeholder,ref:e.inputRef,type:"search",value:e.value})]})}var MSe={compact:"left-2.5",default:"left-3"},OSe={compact:"h-9 bg-dashboard-overlay-soft pr-3 pl-8 focus:ring-1 focus:ring-dashboard-focus/25",default:"h-10 bg-dashboard-overlay-soft pr-3 pl-9 focus:ring-1 focus:ring-dashboard-focus/25"};var LL=b(V(),1);var vl=b(w(),1);function WW(e){return(0,vl.jsxs)(j,{className:L("flex flex-wrap items-end gap-4 p-4",e.className),children:[e.children,e.search?(0,vl.jsx)(rp,{className:"min-w-[16rem] flex-1",label:"Search",children:(0,vl.jsx)(cn,{className:"w-full max-w-md",label:e.search.label,onChange:e.search.onChange,placeholder:e.search.placeholder,value:e.search.value})}):null]})}function rp(e){return(0,vl.jsxs)("div",{className:L("min-w-0",e.className),children:[(0,vl.jsx)("div",{className:"mb-2 font-sans font-medium text-xs text-dashboard-text-muted",children:e.label}),(0,vl.jsx)("div",{"aria-label":e.label,className:"flex flex-wrap gap-2",role:"group",children:e.children})]})}function TI(e){return(0,vl.jsx)("div",{"aria-label":e.ariaLabel,className:"grid min-w-0 grid-cols-3 gap-1 border-b border-dashboard-border-subtle sm:flex sm:overflow-x-auto",role:"tablist",children:e.items.map(t=>{let a=e.value===t.value;return(0,vl.jsxs)("button",{"aria-selected":a,className:L("relative flex min-w-0 cursor-pointer items-center justify-between gap-2 border-0 bg-transparent px-3 py-2.5 font-sans font-medium text-xs transition-colors after:absolute after:inset-x-2 after:bottom-0 after:h-px sm:shrink-0 sm:justify-start",a?"text-dashboard-accent-text after:bg-dashboard-accent":"text-dashboard-text-muted after:bg-transparent hover:text-dashboard-text"),onClick:()=>e.onChange(t.value),role:"tab",type:"button",children:[t.label,t.count!==void 0?(0,vl.jsx)("span",{className:L("rounded-sm border px-1.5 py-0.5 text-xs",a?"border-dashboard-accent/20 bg-dashboard-accent/10 text-dashboard-accent-text":"border-dashboard-border bg-dashboard-fill-soft text-dashboard-text-muted"),children:t.count.toLocaleString("en-US")}):null]},t.value||"all")})})}var JW=b(w(),1),zSe="a, button, input, select, textarea, [role='button'], [role='link']";function tv(e){function t(a){a.target instanceof Element&&a.target.closest(zSe)||e.onSelect()}return(0,JW.jsx)("div",{className:L("group cursor-pointer transition-colors",e.selected?"bg-dashboard-accent/[0.045]":"hover:bg-dashboard-fill-soft focus-within:bg-dashboard-fill-soft",e.className),onClick:t,children:e.children})}var _I=b(V(),1);function NI(e){let[t,a]=li(),r=Ut(),n=(0,_I.useRef)(!1),o=t.get("filter")?.trim()??"",[i,s,u]=uu(),c=Qv({initialPageParam:void 0,queryKey:["dashboard","plugin-user-page",e.pluginName,e.id,o,u],queryFn:({pageParam:p,signal:v})=>{let x=new URLSearchParams;o&&x.set("filter",o),u&&x.set("q",u),p&&x.set("cursor",p);let g=x.toString();return Se(NK,`/api/user-pages/${encodeURIComponent(e.pluginName)}/${encodeURIComponent(e.id)}${g?`?${g}`:""}`,v)},getNextPageParam:p=>p.nextCursor,placeholderData:p=>p,retry:!1}),d=(0,_I.useMemo)(()=>[...new Map((c.data?.pages??[]).flatMap(p=>p.records).map(p=>[p.id,p])).values()],[c.data?.pages]),f=Xt({mutationFn:p=>Kd(p.href),onMutate:()=>({pluginName:e.pluginName}),onSuccess:async(p,v,x)=>{r.removeQueries({queryKey:["dashboard","plugin-user-page",x.pluginName,"record"]}),await r.invalidateQueries({queryKey:["dashboard","plugin-user-page",x.pluginName]})},onSettled:()=>{n.current=!1}});function m(p){n.current||p.confirmation&&!window.confirm(p.confirmation)||(n.current=!0,f.mutate(p))}function h(p){let v=new URLSearchParams(t);p?v.set("filter",p):v.delete("filter"),a(v,{replace:!0})}return{action:f,content:c.data?.pages[0],filter:o,query:c,records:d,runAction:m,searchQuery:u,searchText:i,setFilter:h,setSearchText:s}}var XW=l.string().regex(/^\d{4}-\d{2}-\d{2}(T\d{2})?$/),QW=l.object({date:XW,personal:l.number().int().min(0),public:l.number().int().min(0)}).strict(),RI=l.object({costUsd:l.number().finite().min(0),date:XW,events:l.number().int().min(0)}).strict(),USe=l.object({days:l.array(QW).length(90),extractionDays:l.array(RI).length(90),extractionHours:l.array(RI).min(24).optional(),generatedAt:l.iso.datetime(),hours:l.array(QW).min(24).optional(),recallDays:l.array(RI).length(90),recallHours:l.array(RI).min(24).optional(),stats:l.object({active:l.number().int().min(0),automatic:l.number().int().min(0),createdThirtyDays:l.number().int().min(0),embedded:l.number().int().min(0),explicit:l.number().int().min(0),knowledge:l.number().int().min(0),personal:l.number().int().min(0),preference:l.number().int().min(0),procedure:l.number().int().min(0),public:l.number().int().min(0)}).strict()}).strict();function N4(){return _e({queryFn:({signal:e})=>Se(USe,"/api/plugins/memory/dashboard",e),queryKey:["dashboard","plugin-user-page","memory","summary"],retry:!1})}var jSe=l.object({active:l.number().int().min(0),personal:l.number().int().min(0),public:l.number().int().min(0)}).strict();function YW(e){return _e({enabled:!!e,placeholderData:Of,queryFn:({signal:t})=>Se(jSe,`/api/plugins/memory/counts?${new URLSearchParams({q:e})}`,t),queryKey:["dashboard","plugin-user-page","memory","counts",e],retry:!1})}var jQ=b(V(),1);var av=b(w(),1);function es(e){return(0,av.jsx)("dl",{className:L("grid gap-px overflow-hidden rounded-md border border-dashboard-border-subtle bg-dashboard-fill-hover",e.className),children:e.children})}function ya(e){return(0,av.jsxs)("div",{className:"min-w-0 bg-dashboard-bg-elevated px-3 py-3",children:[(0,av.jsx)("dt",{className:"font-sans font-medium text-xs text-dashboard-text-muted",children:e.label}),(0,av.jsx)("dd",{className:L("mt-1.5 ml-0 break-words text-sm leading-relaxed text-dashboard-text",e.valueClassName),children:e.children})]})}var nv=b(V(),1);function BSe(){let e=0,t;return{acquire(){if(!(typeof document>"u")){if(e===0){let a=document.documentElement,r=document.body,n=typeof window>"u"?0:window.scrollX||window.pageXOffset||0,o=typeof window>"u"?0:window.scrollY||window.pageYOffset||0;t={bodyHeight:r.style.height,bodyLeft:r.style.left,bodyOverflow:r.style.overflow,bodyOverscroll:r.style.overscrollBehavior,bodyPosition:r.style.position,bodyRight:r.style.right,bodyTop:r.style.top,bodyWidth:r.style.width,htmlHeight:a.style.height,htmlOverflow:a.style.overflow,htmlOverscroll:a.style.overscrollBehavior,scrollX:n,scrollY:o},a.style.overflow="hidden",a.style.overscrollBehavior="none",a.style.height="100%",r.style.overflow="hidden",r.style.overscrollBehavior="none",r.style.position="fixed",r.style.top=`-${o}px`,r.style.left=`-${n}px`,r.style.right="0",r.style.width="100%",r.style.height="100%"}e+=1}},release(){if(typeof document>"u"||e===0||(e=Math.max(0,e-1),e>0||t===void 0))return;let a=document.documentElement,r=document.body;a.style.overflow=t.htmlOverflow,a.style.overscrollBehavior=t.htmlOverscroll,a.style.height=t.htmlHeight,r.style.overflow=t.bodyOverflow,r.style.overscrollBehavior=t.bodyOverscroll,r.style.position=t.bodyPosition,r.style.top=t.bodyTop,r.style.left=t.bodyLeft,r.style.right=t.bodyRight,r.style.width=t.bodyWidth,r.style.height=t.bodyHeight;let{scrollX:n,scrollY:o}=t;t=void 0,typeof window<"u"&&window.scrollTo(n,o)}}}var eJ=BSe();function nf(){eJ.acquire()}function rf(){eJ.release()}var yl=b(w(),1),FSe=["a[href]","button:not([disabled])","input:not([disabled]):not([type='hidden'])","select:not([disabled])","textarea:not([disabled])","summary","[tabindex]:not([tabindex='-1'])"].join(",");function Br(e){let t=(0,nv.useRef)(null),a=(0,nv.useRef)(e.onClose),r=(0,nv.useRef)(void 0);return a.current=e.onClose,(0,nv.useEffect)(()=>{r.current=document.activeElement instanceof HTMLElement?document.activeElement:void 0,nf();let n=requestAnimationFrame(()=>{t.current?.querySelector("[data-drawer-close]")?.focus()}),o=i=>{let s=document.querySelectorAll("[data-dashboard-drawer]");if(s[s.length-1]!==t.current)return;if(i.key==="Escape"){i.preventDefault(),a.current();return}if(i.key!=="Tab")return;let u=t.current,c=Array.from(u?.querySelectorAll(FSe)??[]).filter(h=>h.tabIndex>=0&&h.getClientRects().length>0),d=c.at(0),f=c.at(-1);if(!u||!d||!f){i.preventDefault();return}let m=document.activeElement;i.shiftKey&&(m===d||!u.contains(m))?(i.preventDefault(),f.focus()):!i.shiftKey&&(m===f||!u.contains(m))&&(i.preventDefault(),d.focus())};return window.addEventListener("keydown",o),()=>{cancelAnimationFrame(n),window.removeEventListener("keydown",o),rf();let i=r.current;r.current=void 0,i?.isConnected&&i.focus()}},[e.openKey]),(0,yl.jsxs)("div",{"aria-labelledby":e.titleId,"aria-modal":"true","data-dashboard-drawer":"",className:"fixed inset-0 z-50",ref:t,role:"dialog",children:[(0,yl.jsx)("button",{"aria-label":e.dismissLabel,className:"absolute inset-0 cursor-default bg-dashboard-overlay",onClick:e.onClose,tabIndex:-1,type:"button"}),(0,yl.jsxs)("aside",{className:L("absolute top-0 right-0 grid h-full w-full grid-rows-[auto_minmax(0,1fr)] bg-dashboard-bg-elevated shadow-[-20px_0_60px_rgba(0,0,0,0.45)] md:border-l md:border-dashboard-border-strong",e.width==="wide"?"md:w-[min(760px,94vw)]":e.width==="narrow"?"md:w-[min(440px,94vw)]":"md:w-[min(560px,94vw)]"),children:[(0,yl.jsxs)("header",{className:"relative grid grid-cols-[minmax(0,1fr)_auto] gap-3 border-b border-dashboard-border bg-dashboard-bg-elevated px-4 py-3 pt-[max(0.75rem,env(safe-area-inset-top))] md:px-5",children:[(0,yl.jsx)("div",{className:"min-w-0",children:e.header}),(0,yl.jsxs)("div",{className:"flex items-start gap-1.5",children:[e.actions,(0,yl.jsx)(oe,{"aria-label":e.closeLabel,"data-drawer-close":!0,onClick:e.onClose,size:"icon",title:"Close",children:(0,yl.jsx)(oo,{"aria-hidden":"true",size:15,strokeWidth:2.25})})]})]}),(0,yl.jsx)("div",{className:"min-h-0 overflow-auto px-4 py-4 pb-[max(1rem,env(safe-area-inset-bottom))] md:px-5",children:e.children})]})]})}var UQ=b(V(),1);var ca=class extends Error{constructor(e){super(e),this.name="ShikiError"}};function HSe(e){return U4(e)}function U4(e){return Array.isArray(e)?VSe(e):e instanceof RegExp?e:typeof e=="object"?qSe(e):e}function VSe(e){let t=[];for(let a=0,r=e.length;a<r;a++)t[a]=U4(e[a]);return t}function qSe(e){let t={};for(let a in e)t[a]=U4(e[a]);return t}function uJ(e,...t){return t.forEach(a=>{for(let r in a)e[r]=a[r]}),e}function cJ(e){let t=~e.lastIndexOf("/")||~e.lastIndexOf("\\");return t===0?e:~t===e.length-1?cJ(e.substring(0,e.length-1)):e.substr(~t+1)}var R4=/\$(\d+)|\${(\d+):\/(downcase|upcase)}/g,AI=class{static hasCaptures(e){return e===null?!1:(R4.lastIndex=0,R4.test(e))}static replaceCaptures(e,t,a){return e.replace(R4,(r,n,o,i)=>{let s=a[parseInt(n||o,10)];if(s){let u=t.substring(s.start,s.end);for(;u[0]===".";)u=u.substring(1);switch(i){case"downcase":return u.toLowerCase();case"upcase":return u.toUpperCase();default:return u}}else return r})}};function dJ(e,t){return e<t?-1:e>t?1:0}function fJ(e,t){if(e===null&&t===null)return 0;if(!e)return-1;if(!t)return 1;let a=e.length,r=t.length;if(a===r){for(let n=0;n<a;n++){let o=dJ(e[n],t[n]);if(o!==0)return o}return 0}return a-r}function tJ(e){return!!(/^#[0-9a-f]{6}$/i.test(e)||/^#[0-9a-f]{8}$/i.test(e)||/^#[0-9a-f]{3}$/i.test(e)||/^#[0-9a-f]{4}$/i.test(e))}function mJ(e){return e.replace(/[\-\\\{\}\*\+\?\|\^\$\.\,\[\]\(\)\#\s]/g,"\\$&")}var pJ=class{constructor(e){this.fn=e}cache=new Map;get(e){if(this.cache.has(e))return this.cache.get(e);let t=this.fn(e);return this.cache.set(e,t),t}},lS=class{constructor(e,t,a){this._colorMap=e,this._defaults=t,this._root=a}static createFromRawTheme(e,t){return this.createFromParsedTheme(KSe(e),t)}static createFromParsedTheme(e,t){return JSe(e,t)}_cachedMatchRoot=new pJ(e=>this._root.match(e));getColorMap(){return this._colorMap.getColorMap()}getDefaults(){return this._defaults}match(e){if(e===null)return this._defaults;let t=e.scopeName,r=this._cachedMatchRoot.get(t).find(n=>ZSe(e.parent,n.parentScopes));return r?new hJ(r.fontStyle,r.foreground,r.background):null}},A4=class $I{constructor(t,a){this.parent=t,this.scopeName=a}static push(t,a){for(let r of a)t=new $I(t,r);return t}static from(...t){let a=null;for(let r=0;r<t.length;r++)a=new $I(a,t[r]);return a}push(t){return new $I(this,t)}getSegments(){let t=this,a=[];for(;t;)a.push(t.scopeName),t=t.parent;return a.reverse(),a}toString(){return this.getSegments().join(" ")}extends(t){return this===t?!0:this.parent===null?!1:this.parent.extends(t)}getExtensionIfDefined(t){let a=[],r=this;for(;r&&r!==t;)a.push(r.scopeName),r=r.parent;return r===t?a.reverse():void 0}};function ZSe(e,t){if(t.length===0)return!0;for(let a=0;a<t.length;a++){let r=t[a],n=!1;if(r===">"){if(a===t.length-1)return!1;r=t[++a],n=!0}for(;e&&!GSe(e.scopeName,r);){if(n)return!1;e=e.parent}if(!e)return!1;e=e.parent}return!0}function GSe(e,t){return t===e||e.startsWith(t)&&e[t.length]==="."}var hJ=class{constructor(e,t,a){this.fontStyle=e,this.foregroundId=t,this.backgroundId=a}};function KSe(e){if(!e)return[];if(!e.settings||!Array.isArray(e.settings))return[];let t=e.settings,a=[],r=0;for(let n=0,o=t.length;n<o;n++){let i=t[n];if(!i.settings)continue;let s;if(typeof i.scope=="string"){let f=i.scope;f=f.replace(/^[,]+/,""),f=f.replace(/[,]+$/,""),s=f.split(",")}else Array.isArray(i.scope)?s=i.scope:s=[""];let u=-1;if(typeof i.settings.fontStyle=="string"){u=0;let f=i.settings.fontStyle.split(" ");for(let m=0,h=f.length;m<h;m++)switch(f[m]){case"italic":u=u|1;break;case"bold":u=u|2;break;case"underline":u=u|4;break;case"strikethrough":u=u|8;break}}let c=null;typeof i.settings.foreground=="string"&&tJ(i.settings.foreground)&&(c=i.settings.foreground);let d=null;typeof i.settings.background=="string"&&tJ(i.settings.background)&&(d=i.settings.background);for(let f=0,m=s.length;f<m;f++){let p=s[f].trim().split(" "),v=p[p.length-1],x=null;p.length>1&&(x=p.slice(0,p.length-1),x.reverse()),a[r++]=new WSe(v,x,n,u,c,d)}}return a}var WSe=class{constructor(e,t,a,r,n,o){this.scope=e,this.parentScopes=t,this.index=a,this.fontStyle=r,this.foreground=n,this.background=o}},Fr=(e=>(e[e.NotSet=-1]="NotSet",e[e.None=0]="None",e[e.Italic=1]="Italic",e[e.Bold=2]="Bold",e[e.Underline=4]="Underline",e[e.Strikethrough=8]="Strikethrough",e))(Fr||{});function JSe(e,t){e.sort((u,c)=>{let d=dJ(u.scope,c.scope);return d!==0||(d=fJ(u.parentScopes,c.parentScopes),d!==0)?d:u.index-c.index});let a=0,r="#000000",n="#ffffff";for(;e.length>=1&&e[0].scope==="";){let u=e.shift();u.fontStyle!==-1&&(a=u.fontStyle),u.foreground!==null&&(r=u.foreground),u.background!==null&&(n=u.background)}let o=new QSe(t),i=new hJ(a,o.getId(r),o.getId(n)),s=new YSe(new P4(0,null,-1,0,0),[]);for(let u=0,c=e.length;u<c;u++){let d=e[u];s.insert(0,d.scope,d.parentScopes,d.fontStyle,o.getId(d.foreground),o.getId(d.background))}return new lS(o,i,s)}var QSe=class{_isFrozen;_lastColorId;_id2color;_color2id;constructor(e){if(this._lastColorId=0,this._id2color=[],this._color2id=Object.create(null),Array.isArray(e)){this._isFrozen=!0;for(let t=0,a=e.length;t<a;t++)this._color2id[e[t]]=t,this._id2color[t]=e[t]}else this._isFrozen=!1}getId(e){if(e===null)return 0;e=e.toUpperCase();let t=this._color2id[e];if(t)return t;if(this._isFrozen)throw new Error(`Missing color in color map - ${e}`);return t=++this._lastColorId,this._color2id[e]=t,this._id2color[t]=e,t}getColorMap(){return this._id2color.slice(0)}},XSe=Object.freeze([]),P4=class gJ{scopeDepth;parentScopes;fontStyle;foreground;background;constructor(t,a,r,n,o){this.scopeDepth=t,this.parentScopes=a||XSe,this.fontStyle=r,this.foreground=n,this.background=o}clone(){return new gJ(this.scopeDepth,this.parentScopes,this.fontStyle,this.foreground,this.background)}static cloneArr(t){let a=[];for(let r=0,n=t.length;r<n;r++)a[r]=t[r].clone();return a}acceptOverwrite(t,a,r,n){this.scopeDepth>t?console.log("how did this happen?"):this.scopeDepth=t,a!==-1&&(this.fontStyle=a),r!==0&&(this.foreground=r),n!==0&&(this.background=n)}},YSe=class D4{constructor(t,a=[],r={}){this._mainRule=t,this._children=r,this._rulesWithParentScopes=a}_rulesWithParentScopes;static _cmpBySpecificity(t,a){if(t.scopeDepth!==a.scopeDepth)return a.scopeDepth-t.scopeDepth;let r=0,n=0;for(;t.parentScopes[r]===">"&&r++,a.parentScopes[n]===">"&&n++,!(r>=t.parentScopes.length||n>=a.parentScopes.length);){let o=a.parentScopes[n].length-t.parentScopes[r].length;if(o!==0)return o;r++,n++}return a.parentScopes.length-t.parentScopes.length}match(t){if(t!==""){let r=t.indexOf("."),n,o;if(r===-1?(n=t,o=""):(n=t.substring(0,r),o=t.substring(r+1)),this._children.hasOwnProperty(n))return this._children[n].match(o)}let a=this._rulesWithParentScopes.concat(this._mainRule);return a.sort(D4._cmpBySpecificity),a}insert(t,a,r,n,o,i){if(a===""){this._doInsertHere(t,r,n,o,i);return}let s=a.indexOf("."),u,c;s===-1?(u=a,c=""):(u=a.substring(0,s),c=a.substring(s+1));let d;this._children.hasOwnProperty(u)?d=this._children[u]:(d=new D4(this._mainRule.clone(),P4.cloneArr(this._rulesWithParentScopes)),this._children[u]=d),d.insert(t+1,c,r,n,o,i)}_doInsertHere(t,a,r,n,o){if(a===null){this._mainRule.acceptOverwrite(t,r,n,o);return}for(let i=0,s=this._rulesWithParentScopes.length;i<s;i++){let u=this._rulesWithParentScopes[i];if(fJ(u.parentScopes,a)===0){u.acceptOverwrite(t,r,n,o);return}}r===-1&&(r=this._mainRule.fontStyle),n===0&&(n=this._mainRule.foreground),o===0&&(o=this._mainRule.background),this._rulesWithParentScopes.push(new P4(t,a,r,n,o))}},ip=class Ds{static toBinaryStr(t){return t.toString(2).padStart(32,"0")}static print(t){let a=Ds.getLanguageId(t),r=Ds.getTokenType(t),n=Ds.getFontStyle(t),o=Ds.getForeground(t),i=Ds.getBackground(t);console.log({languageId:a,tokenType:r,fontStyle:n,foreground:o,background:i})}static getLanguageId(t){return(t&255)>>>0}static getTokenType(t){return(t&768)>>>8}static containsBalancedBrackets(t){return(t&1024)!==0}static getFontStyle(t){return(t&30720)>>>11}static getForeground(t){return(t&16744448)>>>15}static getBackground(t){return(t&4278190080)>>>24}static set(t,a,r,n,o,i,s){let u=Ds.getLanguageId(t),c=Ds.getTokenType(t),d=Ds.containsBalancedBrackets(t)?1:0,f=Ds.getFontStyle(t),m=Ds.getForeground(t),h=Ds.getBackground(t);return a!==0&&(u=a),r!==8&&(c=r),n!==null&&(d=n?1:0),o!==-1&&(f=o),i!==0&&(m=i),s!==0&&(h=s),(u<<0|c<<8|d<<10|f<<11|m<<15|h<<24)>>>0}};function DI(e,t){let a=[],r=e0e(e),n=r.next();for(;n!==null;){let u=0;if(n.length===2&&n.charAt(1)===":"){switch(n.charAt(0)){case"R":u=1;break;case"L":u=-1;break;default:console.log(`Unknown priority ${n} in scope selector`)}n=r.next()}let c=i();if(a.push({matcher:c,priority:u}),n!==",")break;n=r.next()}return a;function o(){if(n==="-"){n=r.next();let u=o();return c=>!!u&&!u(c)}if(n==="("){n=r.next();let u=s();return n===")"&&(n=r.next()),u}if(aJ(n)){let u=[];do u.push(n),n=r.next();while(aJ(n));return c=>t(u,c)}return null}function i(){let u=[],c=o();for(;c;)u.push(c),c=o();return d=>u.every(f=>f(d))}function s(){let u=[],c=i();for(;c&&(u.push(c),n==="|"||n===",");){do n=r.next();while(n==="|"||n===",");c=i()}return d=>u.some(f=>f(d))}}function aJ(e){return!!e&&!!e.match(/[\w\.:]+/)}function e0e(e){let t=/([LR]:|[\w\.:][\w\.:\-]*|[\,\|\-\(\)])/g,a=t.exec(e);return{next:()=>{if(!a)return null;let r=a[0];return a=t.exec(e),r}}}function vJ(e){typeof e.dispose=="function"&&e.dispose()}var uS=class{constructor(e){this.scopeName=e}toKey(){return this.scopeName}},t0e=class{constructor(e,t){this.scopeName=e,this.ruleName=t}toKey(){return`${this.scopeName}#${this.ruleName}`}},a0e=class{_references=[];_seenReferenceKeys=new Set;get references(){return this._references}visitedRule=new Set;add(e){let t=e.toKey();this._seenReferenceKeys.has(t)||(this._seenReferenceKeys.add(t),this._references.push(e))}},n0e=class{constructor(e,t){this.repo=e,this.initialScopeName=t,this.seenFullScopeRequests.add(this.initialScopeName),this.Q=[new uS(this.initialScopeName)]}seenFullScopeRequests=new Set;seenPartialScopeRequests=new Set;Q;processQueue(){let e=this.Q;this.Q=[];let t=new a0e;for(let a of e)r0e(a,this.initialScopeName,this.repo,t);for(let a of t.references)if(a instanceof uS){if(this.seenFullScopeRequests.has(a.scopeName))continue;this.seenFullScopeRequests.add(a.scopeName),this.Q.push(a)}else{if(this.seenFullScopeRequests.has(a.scopeName)||this.seenPartialScopeRequests.has(a.toKey()))continue;this.seenPartialScopeRequests.add(a.toKey()),this.Q.push(a)}}};function r0e(e,t,a,r){let n=a.lookup(e.scopeName);if(!n){if(e.scopeName===t)throw new Error(`No grammar provided for <${t}>`);return}let o=a.lookup(t);e instanceof uS?PI({baseGrammar:o,selfGrammar:n},r):E4(e.ruleName,{baseGrammar:o,selfGrammar:n,repository:n.repository},r);let i=a.injections(e.scopeName);if(i)for(let s of i)r.add(new uS(s))}function E4(e,t,a){if(t.repository&&t.repository[e]){let r=t.repository[e];EI([r],t,a)}}function PI(e,t){e.selfGrammar.patterns&&Array.isArray(e.selfGrammar.patterns)&&EI(e.selfGrammar.patterns,{...e,repository:e.selfGrammar.repository},t),e.selfGrammar.injections&&EI(Object.values(e.selfGrammar.injections),{...e,repository:e.selfGrammar.repository},t)}function EI(e,t,a){for(let r of e){if(a.visitedRule.has(r))continue;a.visitedRule.add(r);let n=r.repository?uJ({},t.repository,r.repository):t.repository;Array.isArray(r.patterns)&&EI(r.patterns,{...t,repository:n},a);let o=r.include;if(!o)continue;let i=yJ(o);switch(i.kind){case 0:PI({...t,selfGrammar:t.baseGrammar},a);break;case 1:PI(t,a);break;case 2:E4(i.ruleName,{...t,repository:n},a);break;case 3:case 4:let s=i.scopeName===t.selfGrammar.scopeName?t.selfGrammar:i.scopeName===t.baseGrammar.scopeName?t.baseGrammar:void 0;if(s){let u={baseGrammar:t.baseGrammar,selfGrammar:s,repository:n};i.kind===4?E4(i.ruleName,u,a):PI(u,a)}else i.kind===4?a.add(new t0e(i.scopeName,i.ruleName)):a.add(new uS(i.scopeName));break}}}var o0e=class{kind=0},i0e=class{kind=1},s0e=class{constructor(e){this.ruleName=e}kind=2},l0e=class{constructor(e){this.scopeName=e}kind=3},u0e=class{constructor(e,t){this.scopeName=e,this.ruleName=t}kind=4};function yJ(e){if(e==="$base")return new o0e;if(e==="$self")return new i0e;let t=e.indexOf("#");if(t===-1)return new l0e(e);if(t===0)return new s0e(e.substring(1));{let a=e.substring(0,t),r=e.substring(t+1);return new u0e(a,r)}}var c0e=/\\(\d+)/,nJ=/\\(\d+)/g;var d0e=-1,bJ=-2;var fS=class{$location;id;_nameIsCapturing;_name;_contentNameIsCapturing;_contentName;constructor(e,t,a,r){this.$location=e,this.id=t,this._name=a||null,this._nameIsCapturing=AI.hasCaptures(this._name),this._contentName=r||null,this._contentNameIsCapturing=AI.hasCaptures(this._contentName)}get debugName(){let e=this.$location?`${cJ(this.$location.filename)}:${this.$location.line}`:"unknown";return`${this.constructor.name}#${this.id} @ ${e}`}getName(e,t){return!this._nameIsCapturing||this._name===null||e===null||t===null?this._name:AI.replaceCaptures(this._name,e,t)}getContentName(e,t){return!this._contentNameIsCapturing||this._contentName===null?this._contentName:AI.replaceCaptures(this._contentName,e,t)}},f0e=class extends fS{retokenizeCapturedWithRuleId;constructor(e,t,a,r,n){super(e,t,a,r),this.retokenizeCapturedWithRuleId=n}dispose(){}collectPatterns(e,t){throw new Error("Not supported!")}compile(e,t){throw new Error("Not supported!")}compileAG(e,t,a,r){throw new Error("Not supported!")}},m0e=class extends fS{_match;captures;_cachedCompiledPatterns;constructor(e,t,a,r,n){super(e,t,a,null),this._match=new cS(r,this.id),this.captures=n,this._cachedCompiledPatterns=null}dispose(){this._cachedCompiledPatterns&&(this._cachedCompiledPatterns.dispose(),this._cachedCompiledPatterns=null)}get debugMatchRegExp(){return`${this._match.source}`}collectPatterns(e,t){t.push(this._match)}compile(e,t){return this._getCachedCompiledPatterns(e).compile(e)}compileAG(e,t,a,r){return this._getCachedCompiledPatterns(e).compileAG(e,a,r)}_getCachedCompiledPatterns(e){return this._cachedCompiledPatterns||(this._cachedCompiledPatterns=new dS,this.collectPatterns(e,this._cachedCompiledPatterns)),this._cachedCompiledPatterns}},rJ=class extends fS{hasMissingPatterns;patterns;_cachedCompiledPatterns;constructor(e,t,a,r,n){super(e,t,a,r),this.patterns=n.patterns,this.hasMissingPatterns=n.hasMissingPatterns,this._cachedCompiledPatterns=null}dispose(){this._cachedCompiledPatterns&&(this._cachedCompiledPatterns.dispose(),this._cachedCompiledPatterns=null)}collectPatterns(e,t){for(let a of this.patterns)e.getRule(a).collectPatterns(e,t)}compile(e,t){return this._getCachedCompiledPatterns(e).compile(e)}compileAG(e,t,a,r){return this._getCachedCompiledPatterns(e).compileAG(e,a,r)}_getCachedCompiledPatterns(e){return this._cachedCompiledPatterns||(this._cachedCompiledPatterns=new dS,this.collectPatterns(e,this._cachedCompiledPatterns)),this._cachedCompiledPatterns}},M4=class extends fS{_begin;beginCaptures;_end;endHasBackReferences;endCaptures;applyEndPatternLast;hasMissingPatterns;patterns;_cachedCompiledPatterns;constructor(e,t,a,r,n,o,i,s,u,c){super(e,t,a,r),this._begin=new cS(n,this.id),this.beginCaptures=o,this._end=new cS(i||"\uFFFF",-1),this.endHasBackReferences=this._end.hasBackReferences,this.endCaptures=s,this.applyEndPatternLast=u||!1,this.patterns=c.patterns,this.hasMissingPatterns=c.hasMissingPatterns,this._cachedCompiledPatterns=null}dispose(){this._cachedCompiledPatterns&&(this._cachedCompiledPatterns.dispose(),this._cachedCompiledPatterns=null)}get debugBeginRegExp(){return`${this._begin.source}`}get debugEndRegExp(){return`${this._end.source}`}getEndWithResolvedBackReferences(e,t){return this._end.resolveBackReferences(e,t)}collectPatterns(e,t){t.push(this._begin)}compile(e,t){return this._getCachedCompiledPatterns(e,t).compile(e)}compileAG(e,t,a,r){return this._getCachedCompiledPatterns(e,t).compileAG(e,a,r)}_getCachedCompiledPatterns(e,t){if(!this._cachedCompiledPatterns){this._cachedCompiledPatterns=new dS;for(let a of this.patterns)e.getRule(a).collectPatterns(e,this._cachedCompiledPatterns);this.applyEndPatternLast?this._cachedCompiledPatterns.push(this._end.hasBackReferences?this._end.clone():this._end):this._cachedCompiledPatterns.unshift(this._end.hasBackReferences?this._end.clone():this._end)}return this._end.hasBackReferences&&(this.applyEndPatternLast?this._cachedCompiledPatterns.setSource(this._cachedCompiledPatterns.length()-1,t):this._cachedCompiledPatterns.setSource(0,t)),this._cachedCompiledPatterns}},MI=class extends fS{_begin;beginCaptures;whileCaptures;_while;whileHasBackReferences;hasMissingPatterns;patterns;_cachedCompiledPatterns;_cachedCompiledWhilePatterns;constructor(e,t,a,r,n,o,i,s,u){super(e,t,a,r),this._begin=new cS(n,this.id),this.beginCaptures=o,this.whileCaptures=s,this._while=new cS(i,bJ),this.whileHasBackReferences=this._while.hasBackReferences,this.patterns=u.patterns,this.hasMissingPatterns=u.hasMissingPatterns,this._cachedCompiledPatterns=null,this._cachedCompiledWhilePatterns=null}dispose(){this._cachedCompiledPatterns&&(this._cachedCompiledPatterns.dispose(),this._cachedCompiledPatterns=null),this._cachedCompiledWhilePatterns&&(this._cachedCompiledWhilePatterns.dispose(),this._cachedCompiledWhilePatterns=null)}get debugBeginRegExp(){return`${this._begin.source}`}get debugWhileRegExp(){return`${this._while.source}`}getWhileWithResolvedBackReferences(e,t){return this._while.resolveBackReferences(e,t)}collectPatterns(e,t){t.push(this._begin)}compile(e,t){return this._getCachedCompiledPatterns(e).compile(e)}compileAG(e,t,a,r){return this._getCachedCompiledPatterns(e).compileAG(e,a,r)}_getCachedCompiledPatterns(e){if(!this._cachedCompiledPatterns){this._cachedCompiledPatterns=new dS;for(let t of this.patterns)e.getRule(t).collectPatterns(e,this._cachedCompiledPatterns)}return this._cachedCompiledPatterns}compileWhile(e,t){return this._getCachedCompiledWhilePatterns(e,t).compile(e)}compileWhileAG(e,t,a,r){return this._getCachedCompiledWhilePatterns(e,t).compileAG(e,a,r)}_getCachedCompiledWhilePatterns(e,t){return this._cachedCompiledWhilePatterns||(this._cachedCompiledWhilePatterns=new dS,this._cachedCompiledWhilePatterns.push(this._while.hasBackReferences?this._while.clone():this._while)),this._while.hasBackReferences&&this._cachedCompiledWhilePatterns.setSource(0,t||"\uFFFF"),this._cachedCompiledWhilePatterns}},xJ=class mo{static createCaptureRule(t,a,r,n,o){return t.registerRule(i=>new f0e(a,i,r,n,o))}static getCompiledRuleId(t,a,r){return t.id||a.registerRule(n=>{if(t.id=n,t.match)return new m0e(t.$vscodeTextmateLocation,t.id,t.name,t.match,mo._compileCaptures(t.captures,a,r));if(typeof t.begin>"u"){t.repository&&(r=uJ({},r,t.repository));let o=t.patterns;return typeof o>"u"&&t.include&&(o=[{include:t.include}]),new rJ(t.$vscodeTextmateLocation,t.id,t.name,t.contentName,mo._compilePatterns(o,a,r))}return t.while?new MI(t.$vscodeTextmateLocation,t.id,t.name,t.contentName,t.begin,mo._compileCaptures(t.beginCaptures||t.captures,a,r),t.while,mo._compileCaptures(t.whileCaptures||t.captures,a,r),mo._compilePatterns(t.patterns,a,r)):new M4(t.$vscodeTextmateLocation,t.id,t.name,t.contentName,t.begin,mo._compileCaptures(t.beginCaptures||t.captures,a,r),t.end,mo._compileCaptures(t.endCaptures||t.captures,a,r),t.applyEndPatternLast,mo._compilePatterns(t.patterns,a,r))}),t.id}static _compileCaptures(t,a,r){let n=[];if(t){let o=0;for(let i in t){if(i==="$vscodeTextmateLocation")continue;let s=parseInt(i,10);s>o&&(o=s)}for(let i=0;i<=o;i++)n[i]=null;for(let i in t){if(i==="$vscodeTextmateLocation")continue;let s=parseInt(i,10),u=0;t[i].patterns&&(u=mo.getCompiledRuleId(t[i],a,r)),n[s]=mo.createCaptureRule(a,t[i].$vscodeTextmateLocation,t[i].name,t[i].contentName,u)}}return n}static _compilePatterns(t,a,r){let n=[];if(t)for(let o=0,i=t.length;o<i;o++){let s=t[o],u=-1;if(s.include){let c=yJ(s.include);switch(c.kind){case 0:case 1:u=mo.getCompiledRuleId(r[s.include],a,r);break;case 2:let d=r[c.ruleName];d&&(u=mo.getCompiledRuleId(d,a,r));break;case 3:case 4:let f=c.scopeName,m=c.kind===4?c.ruleName:null,h=a.getExternalGrammar(f,r);if(h)if(m){let p=h.repository[m];p&&(u=mo.getCompiledRuleId(p,a,h.repository))}else u=mo.getCompiledRuleId(h.repository.$self,a,h.repository);break}}else u=mo.getCompiledRuleId(s,a,r);if(u!==-1){let c=a.getRule(u),d=!1;if((c instanceof rJ||c instanceof M4||c instanceof MI)&&c.hasMissingPatterns&&c.patterns.length===0&&(d=!0),d)continue;n.push(u)}}return{patterns:n,hasMissingPatterns:(t?t.length:0)!==n.length}}},cS=class SJ{source;ruleId;hasAnchor;hasBackReferences;_anchorCache;constructor(t,a){if(t&&typeof t=="string"){let r=t.length,n=0,o=[],i=!1;for(let s=0;s<r;s++)if(t.charAt(s)==="\\"&&s+1<r){let c=t.charAt(s+1);c==="z"?(o.push(t.substring(n,s)),o.push("$(?!\\n)(?<!\\n)"),n=s+2):(c==="A"||c==="G")&&(i=!0),s++}this.hasAnchor=i,n===0?this.source=t:(o.push(t.substring(n,r)),this.source=o.join(""))}else this.hasAnchor=!1,this.source=t;this.hasAnchor?this._anchorCache=this._buildAnchorCache():this._anchorCache=null,this.ruleId=a,typeof this.source=="string"?this.hasBackReferences=c0e.test(this.source):this.hasBackReferences=!1}clone(){return new SJ(this.source,this.ruleId)}setSource(t){this.source!==t&&(this.source=t,this.hasAnchor&&(this._anchorCache=this._buildAnchorCache()))}resolveBackReferences(t,a){if(typeof this.source!="string")throw new Error("This method should only be called if the source is a string");let r=a.map(n=>t.substring(n.start,n.end));return nJ.lastIndex=0,this.source.replace(nJ,(n,o)=>mJ(r[parseInt(o,10)]||""))}_buildAnchorCache(){if(typeof this.source!="string")throw new Error("This method should only be called if the source is a string");let t=[],a=[],r=[],n=[],o,i,s,u;for(o=0,i=this.source.length;o<i;o++)s=this.source.charAt(o),t[o]=s,a[o]=s,r[o]=s,n[o]=s,s==="\\"&&o+1<i&&(u=this.source.charAt(o+1),u==="A"?(t[o+1]="\uFFFF",a[o+1]="\uFFFF",r[o+1]="A",n[o+1]="A"):u==="G"?(t[o+1]="\uFFFF",a[o+1]="G",r[o+1]="\uFFFF",n[o+1]="G"):(t[o+1]=u,a[o+1]=u,r[o+1]=u,n[o+1]=u),o++);return{A0_G0:t.join(""),A0_G1:a.join(""),A1_G0:r.join(""),A1_G1:n.join("")}}resolveAnchors(t,a){return!this.hasAnchor||!this._anchorCache||typeof this.source!="string"?this.source:t?a?this._anchorCache.A1_G1:this._anchorCache.A1_G0:a?this._anchorCache.A0_G1:this._anchorCache.A0_G0}},dS=class{_items;_hasAnchors;_cached;_anchorCache;constructor(){this._items=[],this._hasAnchors=!1,this._cached=null,this._anchorCache={A0_G0:null,A0_G1:null,A1_G0:null,A1_G1:null}}dispose(){this._disposeCaches()}_disposeCaches(){this._cached&&(this._cached.dispose(),this._cached=null),this._anchorCache.A0_G0&&(this._anchorCache.A0_G0.dispose(),this._anchorCache.A0_G0=null),this._anchorCache.A0_G1&&(this._anchorCache.A0_G1.dispose(),this._anchorCache.A0_G1=null),this._anchorCache.A1_G0&&(this._anchorCache.A1_G0.dispose(),this._anchorCache.A1_G0=null),this._anchorCache.A1_G1&&(this._anchorCache.A1_G1.dispose(),this._anchorCache.A1_G1=null)}push(e){this._items.push(e),this._hasAnchors=this._hasAnchors||e.hasAnchor}unshift(e){this._items.unshift(e),this._hasAnchors=this._hasAnchors||e.hasAnchor}length(){return this._items.length}setSource(e,t){this._items[e].source!==t&&(this._disposeCaches(),this._items[e].setSource(t))}compile(e){if(!this._cached){let t=this._items.map(a=>a.source);this._cached=new oJ(e,t,this._items.map(a=>a.ruleId))}return this._cached}compileAG(e,t,a){return this._hasAnchors?t?a?(this._anchorCache.A1_G1||(this._anchorCache.A1_G1=this._resolveAnchors(e,t,a)),this._anchorCache.A1_G1):(this._anchorCache.A1_G0||(this._anchorCache.A1_G0=this._resolveAnchors(e,t,a)),this._anchorCache.A1_G0):a?(this._anchorCache.A0_G1||(this._anchorCache.A0_G1=this._resolveAnchors(e,t,a)),this._anchorCache.A0_G1):(this._anchorCache.A0_G0||(this._anchorCache.A0_G0=this._resolveAnchors(e,t,a)),this._anchorCache.A0_G0):this.compile(e)}_resolveAnchors(e,t,a){let r=this._items.map(n=>n.resolveAnchors(t,a));return new oJ(e,r,this._items.map(n=>n.ruleId))}},oJ=class{constructor(e,t,a){this.regExps=t,this.rules=a,this.scanner=e.createOnigScanner(t)}scanner;dispose(){typeof this.scanner.dispose=="function"&&this.scanner.dispose()}toString(){let e=[];for(let t=0,a=this.rules.length;t<a;t++)e.push(" - "+this.rules[t]+": "+this.regExps[t]);return e.join(`
72
72
  `)}findNextMatchSync(e,t,a){let r=this.scanner.findNextMatchSync(e,t,a);return r?{ruleId:this.rules[r.index],captureIndices:r.captureIndices}:null}},$4=class{constructor(e,t){this.languageId=e,this.tokenType=t}},p0e=class O4{_defaultAttributes;_embeddedLanguagesMatcher;constructor(t,a){this._defaultAttributes=new $4(t,8),this._embeddedLanguagesMatcher=new h0e(Object.entries(a||{}))}getDefaultAttributes(){return this._defaultAttributes}getBasicScopeAttributes(t){return t===null?O4._NULL_SCOPE_METADATA:this._getBasicScopeAttributes.get(t)}static _NULL_SCOPE_METADATA=new $4(0,0);_getBasicScopeAttributes=new pJ(t=>{let a=this._scopeToLanguage(t),r=this._toStandardTokenType(t);return new $4(a,r)});_scopeToLanguage(t){return this._embeddedLanguagesMatcher.match(t)||0}_toStandardTokenType(t){let a=t.match(O4.STANDARD_TOKEN_TYPE_REGEXP);if(!a)return 8;switch(a[1]){case"comment":return 1;case"string":return 2;case"regex":return 3;case"meta.embedded":return 0}throw new Error("Unexpected match for standard token type!")}static STANDARD_TOKEN_TYPE_REGEXP=/\b(comment|string|regex|meta\.embedded)\b/},h0e=class{values;scopesRegExp;constructor(e){if(e.length===0)this.values=null,this.scopesRegExp=null;else{this.values=new Map(e);let t=e.map(([a,r])=>mJ(a));t.sort(),t.reverse(),this.scopesRegExp=new RegExp(`^((${t.join(")|(")}))($|\\.)`,"")}}match(e){if(!this.scopesRegExp)return;let t=e.match(this.scopesRegExp);if(t)return this.values.get(t[1])}},g8e={InDebugMode:typeof process<"u"&&!!process.env.VSCODE_TEXTMATE_DEBUG},wJ=!1,iJ=class{constructor(e,t){this.stack=e,this.stoppedEarly=t}};function CJ(e,t,a,r,n,o,i,s){let u=t.content.length,c=!1,d=-1;if(i){let h=g0e(e,t,a,r,n,o);n=h.stack,r=h.linePos,a=h.isFirstLine,d=h.anchorPosition}let f=Date.now();for(;!c;){if(s!==0&&Date.now()-f>s)return new iJ(n,!0);m()}return new iJ(n,!1);function m(){let h=v0e(e,t,a,r,n,d);if(!h){o.produce(n,u),c=!0;return}let p=h.captureIndices,v=h.matchedRuleId,x=p&&p.length>0?p[0].end>r:!1;if(v===d0e){let g=n.getRule(e);o.produce(n,p[0].start),n=n.withContentNameScopesList(n.nameScopesList),iS(e,t,a,n,o,g.endCaptures,p),o.produce(n,p[0].end);let y=n;if(n=n.parent,d=y.getAnchorPos(),!x&&y.getEnterPos()===r){n=y,o.produce(n,u),c=!0;return}}else{let g=e.getRule(v);o.produce(n,p[0].start);let y=n,S=g.getName(t.content,p),C=n.contentNameScopesList.pushAttributed(S,e);if(n=n.push(v,r,d,p[0].end===u,null,C,C),g instanceof M4){let I=g;iS(e,t,a,n,o,I.beginCaptures,p),o.produce(n,p[0].end),d=p[0].end;let T=I.getContentName(t.content,p),N=C.pushAttributed(T,e);if(n=n.withContentNameScopesList(N),I.endHasBackReferences&&(n=n.withEndRule(I.getEndWithResolvedBackReferences(t.content,p))),!x&&y.hasSameRuleAs(n)){n=n.pop(),o.produce(n,u),c=!0;return}}else if(g instanceof MI){let I=g;iS(e,t,a,n,o,I.beginCaptures,p),o.produce(n,p[0].end),d=p[0].end;let T=I.getContentName(t.content,p),N=C.pushAttributed(T,e);if(n=n.withContentNameScopesList(N),I.whileHasBackReferences&&(n=n.withEndRule(I.getWhileWithResolvedBackReferences(t.content,p))),!x&&y.hasSameRuleAs(n)){n=n.pop(),o.produce(n,u),c=!0;return}}else if(iS(e,t,a,n,o,g.captures,p),o.produce(n,p[0].end),n=n.pop(),!x){n=n.safePop(),o.produce(n,u),c=!0;return}}p[0].end>r&&(r=p[0].end,a=!1)}}function g0e(e,t,a,r,n,o){let i=n.beginRuleCapturedEOL?0:-1,s=[];for(let u=n;u;u=u.pop()){let c=u.getRule(e);c instanceof MI&&s.push({rule:c,stack:u})}for(let u=s.pop();u;u=s.pop()){let{ruleScanner:c,findOptions:d}=x0e(u.rule,e,u.stack.endRule,a,r===i),f=c.findNextMatchSync(t,r,d);if(f){if(f.ruleId!==bJ){n=u.stack.pop();break}f.captureIndices&&f.captureIndices.length&&(o.produce(u.stack,f.captureIndices[0].start),iS(e,t,a,u.stack,o,u.rule.whileCaptures,f.captureIndices),o.produce(u.stack,f.captureIndices[0].end),i=f.captureIndices[0].end,f.captureIndices[0].end>r&&(r=f.captureIndices[0].end,a=!1))}else{n=u.stack.pop();break}}return{stack:n,linePos:r,anchorPosition:i,isFirstLine:a}}function v0e(e,t,a,r,n,o){let i=y0e(e,t,a,r,n,o),s=e.getInjections();if(s.length===0)return i;let u=b0e(s,e,t,a,r,n,o);if(!u)return i;if(!i)return u;let c=i.captureIndices[0].start,d=u.captureIndices[0].start;return d<c||u.priorityMatch&&d===c?u:i}function y0e(e,t,a,r,n,o){let i=n.getRule(e),{ruleScanner:s,findOptions:u}=kJ(i,e,n.endRule,a,r===o),c=s.findNextMatchSync(t,r,u);return c?{captureIndices:c.captureIndices,matchedRuleId:c.ruleId}:null}function b0e(e,t,a,r,n,o,i){let s=Number.MAX_VALUE,u=null,c,d=0,f=o.contentNameScopesList.getScopeNames();for(let m=0,h=e.length;m<h;m++){let p=e[m];if(!p.matcher(f))continue;let v=t.getRule(p.ruleId),{ruleScanner:x,findOptions:g}=kJ(v,t,null,r,n===i),y=x.findNextMatchSync(a,n,g);if(!y)continue;let S=y.captureIndices[0].start;if(!(S>=s)&&(s=S,u=y.captureIndices,c=y.ruleId,d=p.priority,s===n))break}return u?{priorityMatch:d===-1,captureIndices:u,matchedRuleId:c}:null}function kJ(e,t,a,r,n){if(wJ){let i=e.compile(t,a),s=IJ(r,n);return{ruleScanner:i,findOptions:s}}return{ruleScanner:e.compileAG(t,a,r,n),findOptions:0}}function x0e(e,t,a,r,n){if(wJ){let i=e.compileWhile(t,a),s=IJ(r,n);return{ruleScanner:i,findOptions:s}}return{ruleScanner:e.compileWhileAG(t,a,r,n),findOptions:0}}function IJ(e,t){let a=0;return e||(a|=1),t||(a|=4),a}function iS(e,t,a,r,n,o,i){if(o.length===0)return;let s=t.content,u=Math.min(o.length,i.length),c=[],d=i[0].end;for(let f=0;f<u;f++){let m=o[f];if(m===null)continue;let h=i[f];if(h.length===0)continue;if(h.start>d)break;for(;c.length>0&&c[c.length-1].endPos<=h.start;)n.produceFromScopes(c[c.length-1].scopes,c[c.length-1].endPos),c.pop();if(c.length>0?n.produceFromScopes(c[c.length-1].scopes,h.start):n.produce(r,h.start),m.retokenizeCapturedWithRuleId){let v=m.getName(s,i),x=r.contentNameScopesList.pushAttributed(v,e),g=m.getContentName(s,i),y=x.pushAttributed(g,e),S=r.push(m.retokenizeCapturedWithRuleId,h.start,-1,!1,null,x,y),C=e.createOnigString(s.substring(0,h.end));CJ(e,C,a&&h.start===0,h.start,S,n,!1,0),vJ(C);continue}let p=m.getName(s,i);if(p!==null){let x=(c.length>0?c[c.length-1].scopes:r.contentNameScopesList).pushAttributed(p,e);c.push(new S0e(x,h.end))}}for(;c.length>0;)n.produceFromScopes(c[c.length-1].scopes,c[c.length-1].endPos),c.pop()}var S0e=class{scopes;endPos;constructor(e,t){this.scopes=e,this.endPos=t}};function w0e(e,t,a,r,n,o,i,s){return new k0e(e,t,a,r,n,o,i,s)}function sJ(e,t,a,r,n){let o=DI(t,OI),i=xJ.getCompiledRuleId(a,r,n.repository);for(let s of o)e.push({debugSelector:t,matcher:s.matcher,ruleId:i,grammar:n,priority:s.priority})}function OI(e,t){if(t.length<e.length)return!1;let a=0;return e.every(r=>{for(let n=a;n<t.length;n++)if(C0e(t[n],r))return a=n+1,!0;return!1})}function C0e(e,t){if(!e)return!1;if(e===t)return!0;let a=t.length;return e.length>a&&e.substr(0,a)===t&&e[a]==="."}var k0e=class{constructor(e,t,a,r,n,o,i,s){if(this._rootScopeName=e,this.balancedBracketSelectors=o,this._onigLib=s,this._basicScopeAttributesProvider=new p0e(a,r),this._rootId=-1,this._lastRuleId=0,this._ruleId2desc=[null],this._includedGrammars={},this._grammarRepository=i,this._grammar=lJ(t,null),this._injections=null,this._tokenTypeMatchers=[],n)for(let u of Object.keys(n)){let c=DI(u,OI);for(let d of c)this._tokenTypeMatchers.push({matcher:d.matcher,type:n[u]})}}_rootId;_lastRuleId;_ruleId2desc;_includedGrammars;_grammarRepository;_grammar;_injections;_basicScopeAttributesProvider;_tokenTypeMatchers;get themeProvider(){return this._grammarRepository}dispose(){for(let e of this._ruleId2desc)e&&e.dispose()}createOnigScanner(e){return this._onigLib.createOnigScanner(e)}createOnigString(e){return this._onigLib.createOnigString(e)}getMetadataForScope(e){return this._basicScopeAttributesProvider.getBasicScopeAttributes(e)}_collectInjections(){let e={lookup:n=>n===this._rootScopeName?this._grammar:this.getExternalGrammar(n),injections:n=>this._grammarRepository.injections(n)},t=[],a=this._rootScopeName,r=e.lookup(a);if(r){let n=r.injections;if(n)for(let i in n)sJ(t,i,n[i],this,r);let o=this._grammarRepository.injections(a);o&&o.forEach(i=>{let s=this.getExternalGrammar(i);if(s){let u=s.injectionSelector;u&&sJ(t,u,s,this,s)}})}return t.sort((n,o)=>n.priority-o.priority),t}getInjections(){return this._injections===null&&(this._injections=this._collectInjections()),this._injections}registerRule(e){let t=++this._lastRuleId,a=e(t);return this._ruleId2desc[t]=a,a}getRule(e){return this._ruleId2desc[e]}getExternalGrammar(e,t){if(this._includedGrammars[e])return this._includedGrammars[e];if(this._grammarRepository){let a=this._grammarRepository.lookup(e);if(a)return this._includedGrammars[e]=lJ(a,t&&t.$base),this._includedGrammars[e]}}tokenizeLine(e,t,a=0){let r=this._tokenize(e,t,!1,a);return{tokens:r.lineTokens.getResult(r.ruleStack,r.lineLength),ruleStack:r.ruleStack,stoppedEarly:r.stoppedEarly}}tokenizeLine2(e,t,a=0){let r=this._tokenize(e,t,!0,a);return{tokens:r.lineTokens.getBinaryResult(r.ruleStack,r.lineLength),ruleStack:r.ruleStack,stoppedEarly:r.stoppedEarly}}_tokenize(e,t,a,r){this._rootId===-1&&(this._rootId=xJ.getCompiledRuleId(this._grammar.repository.$self,this,this._grammar.repository),this.getInjections());let n;if(!t||t===z4.NULL){n=!0;let c=this._basicScopeAttributesProvider.getDefaultAttributes(),d=this.themeProvider.getDefaults(),f=ip.set(0,c.languageId,c.tokenType,null,d.fontStyle,d.foregroundId,d.backgroundId),m=this.getRule(this._rootId).getName(null,null),h;m?h=sS.createRootAndLookUpScopeName(m,f,this):h=sS.createRoot("unknown",f),t=new z4(null,this._rootId,-1,-1,!1,null,h,h)}else n=!1,t.reset();e=e+`
73
73
  `;let o=this.createOnigString(e),i=o.content.length,s=new L0e(a,e,this._tokenTypeMatchers,this.balancedBracketSelectors),u=CJ(this,o,n,0,t,s,!0,r);return vJ(o),{lineLength:i,lineTokens:s,ruleStack:u.stack,stoppedEarly:u.stoppedEarly}}};function lJ(e,t){return e=HSe(e),e.repository=e.repository||{},e.repository.$self={$vscodeTextmateLocation:e.$vscodeTextmateLocation,patterns:e.patterns,name:e.scopeName},e.repository.$base=t||e.repository.$self,e}var sS=class gu{constructor(t,a,r){this.parent=t,this.scopePath=a,this.tokenAttributes=r}static fromExtension(t,a){let r=t,n=t?.scopePath??null;for(let o of a)n=A4.push(n,o.scopeNames),r=new gu(r,n,o.encodedTokenAttributes);return r}static createRoot(t,a){return new gu(null,new A4(null,t),a)}static createRootAndLookUpScopeName(t,a,r){let n=r.getMetadataForScope(t),o=new A4(null,t),i=r.themeProvider.themeMatch(o),s=gu.mergeAttributes(a,n,i);return new gu(null,o,s)}get scopeName(){return this.scopePath.scopeName}toString(){return this.getScopeNames().join(" ")}equals(t){return gu.equals(this,t)}static equals(t,a){do{if(t===a||!t&&!a)return!0;if(!t||!a||t.scopeName!==a.scopeName||t.tokenAttributes!==a.tokenAttributes)return!1;t=t.parent,a=a.parent}while(!0)}static mergeAttributes(t,a,r){let n=-1,o=0,i=0;return r!==null&&(n=r.fontStyle,o=r.foregroundId,i=r.backgroundId),ip.set(t,a.languageId,a.tokenType,null,n,o,i)}pushAttributed(t,a){if(t===null)return this;if(t.indexOf(" ")===-1)return gu._pushAttributed(this,t,a);let r=t.split(/ /g),n=this;for(let o of r)n=gu._pushAttributed(n,o,a);return n}static _pushAttributed(t,a,r){let n=r.getMetadataForScope(a),o=t.scopePath.push(a),i=r.themeProvider.themeMatch(o),s=gu.mergeAttributes(t.tokenAttributes,n,i);return new gu(t,o,s)}getScopeNames(){return this.scopePath.getSegments()}getExtensionIfDefined(t){let a=[],r=this;for(;r&&r!==t;)a.push({encodedTokenAttributes:r.tokenAttributes,scopeNames:r.scopePath.getExtensionIfDefined(r.parent?.scopePath??null)}),r=r.parent;return r===t?a.reverse():void 0}},z4=class op{constructor(t,a,r,n,o,i,s,u){this.parent=t,this.ruleId=a,this.beginRuleCapturedEOL=o,this.endRule=i,this.nameScopesList=s,this.contentNameScopesList=u,this.depth=this.parent?this.parent.depth+1:1,this._enterPos=r,this._anchorPos=n}_stackElementBrand=void 0;static NULL=new op(null,0,0,0,!1,null,null,null);_enterPos;_anchorPos;depth;equals(t){return t===null?!1:op._equals(this,t)}static _equals(t,a){return t===a?!0:this._structuralEquals(t,a)?sS.equals(t.contentNameScopesList,a.contentNameScopesList):!1}static _structuralEquals(t,a){do{if(t===a||!t&&!a)return!0;if(!t||!a||t.depth!==a.depth||t.ruleId!==a.ruleId||t.endRule!==a.endRule)return!1;t=t.parent,a=a.parent}while(!0)}clone(){return this}static _reset(t){for(;t;)t._enterPos=-1,t._anchorPos=-1,t=t.parent}reset(){op._reset(this)}pop(){return this.parent}safePop(){return this.parent?this.parent:this}push(t,a,r,n,o,i,s){return new op(this,t,a,r,n,o,i,s)}getEnterPos(){return this._enterPos}getAnchorPos(){return this._anchorPos}getRule(t){return t.getRule(this.ruleId)}toString(){let t=[];return this._writeString(t,0),"["+t.join(",")+"]"}_writeString(t,a){return this.parent&&(a=this.parent._writeString(t,a)),t[a++]=`(${this.ruleId}, ${this.nameScopesList?.toString()}, ${this.contentNameScopesList?.toString()})`,a}withContentNameScopesList(t){return this.contentNameScopesList===t?this:this.parent.push(this.ruleId,this._enterPos,this._anchorPos,this.beginRuleCapturedEOL,this.endRule,this.nameScopesList,t)}withEndRule(t){return this.endRule===t?this:new op(this.parent,this.ruleId,this._enterPos,this._anchorPos,this.beginRuleCapturedEOL,t,this.nameScopesList,this.contentNameScopesList)}hasSameRuleAs(t){let a=this;for(;a&&a._enterPos===t._enterPos;){if(a.ruleId===t.ruleId)return!0;a=a.parent}return!1}toStateStackFrame(){return{ruleId:this.ruleId,beginRuleCapturedEOL:this.beginRuleCapturedEOL,endRule:this.endRule,nameScopesList:this.nameScopesList?.getExtensionIfDefined(this.parent?.nameScopesList??null)??[],contentNameScopesList:this.contentNameScopesList?.getExtensionIfDefined(this.nameScopesList)??[]}}static pushFrame(t,a){let r=sS.fromExtension(t?.nameScopesList??null,a.nameScopesList);return new op(t,a.ruleId,a.enterPos??-1,a.anchorPos??-1,a.beginRuleCapturedEOL,a.endRule,r,sS.fromExtension(r,a.contentNameScopesList))}},I0e=class{balancedBracketScopes;unbalancedBracketScopes;allowAny=!1;constructor(e,t){this.balancedBracketScopes=e.flatMap(a=>a==="*"?(this.allowAny=!0,[]):DI(a,OI).map(r=>r.matcher)),this.unbalancedBracketScopes=t.flatMap(a=>DI(a,OI).map(r=>r.matcher))}get matchesAlways(){return this.allowAny&&this.unbalancedBracketScopes.length===0}get matchesNever(){return this.balancedBracketScopes.length===0&&!this.allowAny}match(e){for(let t of this.unbalancedBracketScopes)if(t(e))return!1;for(let t of this.balancedBracketScopes)if(t(e))return!0;return this.allowAny}},L0e=class{constructor(e,t,a,r){this.balancedBracketSelectors=r,this._emitBinaryTokens=e,this._tokenTypeOverrides=a,this._lineText=null,this._tokens=[],this._binaryTokens=[],this._lastTokenEndIndex=0}_emitBinaryTokens;_lineText;_tokens;_binaryTokens;_lastTokenEndIndex;_tokenTypeOverrides;produce(e,t){this.produceFromScopes(e.contentNameScopesList,t)}produceFromScopes(e,t){if(this._lastTokenEndIndex>=t)return;if(this._emitBinaryTokens){let r=e?.tokenAttributes??0,n=!1;if(this.balancedBracketSelectors?.matchesAlways&&(n=!0),this._tokenTypeOverrides.length>0||this.balancedBracketSelectors&&!this.balancedBracketSelectors.matchesAlways&&!this.balancedBracketSelectors.matchesNever){let o=e?.getScopeNames()??[];for(let i of this._tokenTypeOverrides)i.matcher(o)&&(r=ip.set(r,0,i.type,null,-1,0,0));this.balancedBracketSelectors&&(n=this.balancedBracketSelectors.match(o))}if(n&&(r=ip.set(r,0,8,n,-1,0,0)),this._binaryTokens.length>0&&this._binaryTokens[this._binaryTokens.length-1]===r){this._lastTokenEndIndex=t;return}this._binaryTokens.push(this._lastTokenEndIndex),this._binaryTokens.push(r),this._lastTokenEndIndex=t;return}let a=e?.getScopeNames()??[];this._tokens.push({startIndex:this._lastTokenEndIndex,endIndex:t,scopes:a}),this._lastTokenEndIndex=t}getResult(e,t){return this._tokens.length>0&&this._tokens[this._tokens.length-1].startIndex===t-1&&this._tokens.pop(),this._tokens.length===0&&(this._lastTokenEndIndex=-1,this.produce(e,t),this._tokens[this._tokens.length-1].startIndex=0),this._tokens}getBinaryResult(e,t){this._binaryTokens.length>0&&this._binaryTokens[this._binaryTokens.length-2]===t-1&&(this._binaryTokens.pop(),this._binaryTokens.pop()),this._binaryTokens.length===0&&(this._lastTokenEndIndex=-1,this.produce(e,t),this._binaryTokens[this._binaryTokens.length-2]=0);let a=new Uint32Array(this._binaryTokens.length);for(let r=0,n=this._binaryTokens.length;r<n;r++)a[r]=this._binaryTokens[r];return a}},T0e=class{constructor(e,t){this._onigLib=t,this._theme=e}_grammars=new Map;_rawGrammars=new Map;_injectionGrammars=new Map;_theme;dispose(){for(let e of this._grammars.values())e.dispose()}setTheme(e){this._theme=e}getColorMap(){return this._theme.getColorMap()}addGrammar(e,t){this._rawGrammars.set(e.scopeName,e),t&&this._injectionGrammars.set(e.scopeName,t)}lookup(e){return this._rawGrammars.get(e)}injections(e){return this._injectionGrammars.get(e)}getDefaults(){return this._theme.getDefaults()}themeMatch(e){return this._theme.match(e)}grammarForScopeName(e,t,a,r,n){if(!this._grammars.has(e)){let o=this._rawGrammars.get(e);if(!o)return null;this._grammars.set(e,w0e(e,o,t,a,r,n,this,this._onigLib))}return this._grammars.get(e)}},LJ=class{_options;_syncRegistry;_ensureGrammarCache;constructor(e){this._options=e,this._syncRegistry=new T0e(lS.createFromRawTheme(e.theme,e.colorMap),e.onigLib),this._ensureGrammarCache=new Map}dispose(){this._syncRegistry.dispose()}setTheme(e,t){this._syncRegistry.setTheme(lS.createFromRawTheme(e,t))}getColorMap(){return this._syncRegistry.getColorMap()}loadGrammarWithEmbeddedLanguages(e,t,a){return this.loadGrammarWithConfiguration(e,t,{embeddedLanguages:a})}loadGrammarWithConfiguration(e,t,a){return this._loadGrammar(e,t,a.embeddedLanguages,a.tokenTypes,new I0e(a.balancedBracketSelectors||[],a.unbalancedBracketSelectors||[]))}loadGrammar(e){return this._loadGrammar(e,0,null,null,null)}_loadGrammar(e,t,a,r,n){let o=new n0e(this._syncRegistry,e);for(;o.Q.length>0;)o.Q.map(i=>this._loadSingleGrammar(i.scopeName)),o.processQueue();return this._grammarForScopeName(e,t,a,r,n)}_loadSingleGrammar(e){this._ensureGrammarCache.has(e)||(this._doLoadSingleGrammar(e),this._ensureGrammarCache.set(e,!0))}_doLoadSingleGrammar(e){let t=this._options.loadGrammar(e);if(t){let a=typeof this._options.getInjections=="function"?this._options.getInjections(e):void 0;this._syncRegistry.addGrammar(t,a)}}addGrammar(e,t=[],a=0,r=null){return this._syncRegistry.addGrammar(e,t),this._grammarForScopeName(e.scopeName,a,r)}_grammarForScopeName(e,t=0,a=null,r=null,n=null){return this._syncRegistry.grammarForScopeName(e,t,a,r,n)}},zI=z4.NULL;function pS(e,t){let a=typeof e=="string"?{}:{...e.colorReplacements},r=typeof e=="string"?e:e.name;for(let[n,o]of Object.entries(t?.colorReplacements||{}))typeof o=="string"?a[n]=o:n===r&&Object.assign(a,o);return a}function kc(e,t){return e&&(t?.[e?.toLowerCase()]||e)}function AJ(e){return Array.isArray(e)?e:[e]}async function j4(e){return Promise.resolve(typeof e=="function"?e():e).then(t=>t.default||t)}function hS(e){return!e||["plaintext","txt","text","plain"].includes(e)}function B4(e){return e==="ansi"||hS(e)}function gS(e){return e==="none"}function F4(e){return gS(e)}var _0e=/(\r?\n)/g;function rv(e,t=!1){if(e.length===0)return[["",0]];let a=e.split(_0e),r=0,n=[];for(let o=0;o<a.length;o+=2){let i=t?a[o]+(a[o+1]||""):a[o];n.push([i,r]),r+=a[o].length,r+=a[o+1]?.length||0}return n}var TJ={light:"#333333",dark:"#bbbbbb"},_J={light:"#fffffe",dark:"#1e1e1e"},NJ="__shiki_resolved";function UI(e){if(e?.[NJ])return e;let t={...e};t.tokenColors&&!t.settings&&(t.settings=t.tokenColors,delete t.tokenColors),t.type||="dark",t.colorReplacements={...t.colorReplacements},t.settings||=[];let{bg:a,fg:r}=t;if(!a||!r){let s=t.settings?t.settings.find(u=>!u.name&&!u.scope):void 0;s?.settings?.foreground&&(r=s.settings.foreground),s?.settings?.background&&(a=s.settings.background),!r&&t?.colors?.["editor.foreground"]&&(r=t.colors["editor.foreground"]),!a&&t?.colors?.["editor.background"]&&(a=t.colors["editor.background"]),r||(r=t.type==="light"?TJ.light:TJ.dark),a||(a=t.type==="light"?_J.light:_J.dark),t.fg=r,t.bg=a}t.settings[0]&&t.settings[0].settings&&!t.settings[0].scope||t.settings.unshift({settings:{foreground:t.fg,background:t.bg}});let n=0,o=new Map;function i(s){if(o.has(s))return o.get(s);n+=1;let u=`#${n.toString(16).padStart(8,"0").toLowerCase()}`;return t.colorReplacements?.[`#${u}`]?i(s):(o.set(s,u),u)}t.settings=t.settings.map(s=>{let u=s.settings?.foreground&&!s.settings.foreground.startsWith("#"),c=s.settings?.background&&!s.settings.background.startsWith("#");if(!u&&!c)return s;let d={...s,settings:{...s.settings}};if(u){let f=i(s.settings.foreground);t.colorReplacements[f]=s.settings.foreground,d.settings.foreground=f}if(c){let f=i(s.settings.background);t.colorReplacements[f]=s.settings.background,d.settings.background=f}return d});for(let s of Object.keys(t.colors||{}))if((s==="editor.foreground"||s==="editor.background"||s.startsWith("terminal.ansi"))&&!t.colors[s]?.startsWith("#")){let u=i(t.colors[s]);t.colorReplacements[u]=t.colors[s],t.colors[s]=u}return Object.defineProperty(t,NJ,{enumerable:!1,writable:!1,value:!0}),t}async function $J(e){return[...new Set((await Promise.all(e.filter(t=>!B4(t)).map(async t=>await j4(t).then(a=>Array.isArray(a)?a:[a])))).flat())]}async function PJ(e){return(await Promise.all(e.map(async t=>F4(t)?null:UI(await j4(t))))).filter(t=>!!t)}function DJ(e,t){if(!t)return e;if(t[e]){let a=new Set([e]);for(;t[e];){if(e=t[e],a.has(e))throw new ca(`Circular alias \`${[...a].join(" -> ")} -> ${e}\``);a.add(e)}}return e}var N0e=class extends LJ{_resolver;_themes;_langs;_alias;_resolvedThemes=new Map;_resolvedGrammars=new Map;_langMap=new Map;_langGraph=new Map;_textmateThemeCache=new WeakMap;_loadedThemesCache=null;_loadedLanguagesCache=null;constructor(e,t,a,r={}){super(e),this._resolver=e,this._themes=t,this._langs=a,this._alias=r,this._themes.map(n=>this.loadTheme(n)),this.loadLanguages(this._langs)}getTheme(e){return typeof e=="string"?this._resolvedThemes.get(e):this.loadTheme(e)}loadTheme(e){let t=UI(e);return t.name&&(this._resolvedThemes.set(t.name,t),this._loadedThemesCache=null),t}getLoadedThemes(){return this._loadedThemesCache||(this._loadedThemesCache=[...this._resolvedThemes.keys()]),this._loadedThemesCache}setTheme(e){let t=this._textmateThemeCache.get(e);t||(t=lS.createFromRawTheme(e),this._textmateThemeCache.set(e,t)),this._syncRegistry.setTheme(t)}getGrammar(e){return e=DJ(e,this._alias),this._resolvedGrammars.get(e)}loadLanguage(e){if(this.getGrammar(e.name))return;let t=new Set([...this._langMap.values()].filter(n=>n.embeddedLangsLazy?.includes(e.name)));this._resolver.addLanguage(e);let a={balancedBracketSelectors:e.balancedBracketSelectors||["*"],unbalancedBracketSelectors:e.unbalancedBracketSelectors||[]};this._syncRegistry._rawGrammars.set(e.scopeName,e);let r=this.loadGrammarWithConfiguration(e.scopeName,1,a);if(r.name=e.name,this._resolvedGrammars.set(e.name,r),e.aliases&&e.aliases.forEach(n=>{this._alias[n]=e.name}),this._loadedLanguagesCache=null,t.size)for(let n of t)this._resolvedGrammars.delete(n.name),this._loadedLanguagesCache=null,this._syncRegistry?._injectionGrammars?.delete(n.scopeName),this._syncRegistry?._grammars?.delete(n.scopeName),this.loadLanguage(this._langMap.get(n.name))}dispose(){super.dispose(),this._resolvedThemes.clear(),this._resolvedGrammars.clear(),this._langMap.clear(),this._langGraph.clear(),this._loadedThemesCache=null}loadLanguages(e){for(let r of e)this.resolveEmbeddedLanguages(r);let t=[...this._langGraph.entries()],a=t.filter(([r,n])=>!n);if(a.length){let r=t.filter(([n,o])=>o?(o.embeddedLanguages||o.embeddedLangs)?.some(i=>a.map(([s])=>s).includes(i)):!1).filter(n=>!a.includes(n));throw new ca(`Missing languages ${a.map(([n])=>`\`${n}\``).join(", ")}, required by ${r.map(([n])=>`\`${n}\``).join(", ")}`)}for(let[r,n]of t)this._resolver.addLanguage(n);for(let[r,n]of t)this.loadLanguage(n)}getLoadedLanguages(){return this._loadedLanguagesCache||(this._loadedLanguagesCache=[...new Set([...this._resolvedGrammars.keys(),...Object.keys(this._alias)])]),this._loadedLanguagesCache}resolveEmbeddedLanguages(e){this._langMap.set(e.name,e),this._langGraph.set(e.name,e);let t=e.embeddedLanguages??e.embeddedLangs;if(t)for(let a of t)this._langGraph.set(a,this._langMap.get(a))}},R0e=class{_langs=new Map;_scopeToLang=new Map;_injections=new Map;_onigLib;constructor(e,t){this._onigLib={createOnigScanner:a=>e.createScanner(a),createOnigString:a=>e.createString(a)},t.forEach(a=>this.addLanguage(a))}get onigLib(){return this._onigLib}getLangRegistration(e){return this._langs.get(e)}loadGrammar(e){return this._scopeToLang.get(e)}addLanguage(e){this._langs.set(e.name,e),e.aliases&&e.aliases.forEach(t=>{this._langs.set(t,e)}),this._scopeToLang.set(e.scopeName,e),e.injectTo&&e.injectTo.forEach(t=>{this._injections.get(t)||this._injections.set(t,[]),this._injections.get(t).push(e.scopeName)})}getInjections(e){let t=e.split("."),a=[];for(let r=1;r<=t.length;r++){let n=t.slice(0,r).join(".");a=[...a,...this._injections.get(n)||[]]}return a}},mS=0;function H4(e){mS+=1,e.warnings!==!1&&mS>=10&&mS%10===0&&console.warn(`[Shiki] ${mS} instances have been created. Shiki is supposed to be used as a singleton, consider refactoring your code to cache your highlighter instance; Or call \`highlighter.dispose()\` to release unused instances.`);let t=!1;if(!e.engine)throw new ca("`engine` option is required for synchronous mode");let a=(e.langs||[]).flat(1),r=(e.themes||[]).flat(1).map(UI),n=new N0e(new R0e(e.engine,a),r,a,e.langAlias),o;function i(y){return DJ(y,e.langAlias)}function s(y){x();let S=n.getGrammar(typeof y=="string"?y:y.name);if(!S)throw new ca(`Language \`${y}\` not found, you may need to load it first`);return S}function u(y){if(y==="none")return{bg:"",fg:"",name:"none",settings:[],type:"dark"};x();let S=n.getTheme(y);if(!S)throw new ca(`Theme \`${y}\` not found, you may need to load it first`);return S}function c(y){x();let S=u(y);return o!==y&&(n.setTheme(S),o=y),{theme:S,colorMap:n.getColorMap()}}function d(){return x(),n.getLoadedThemes()}function f(){return x(),n.getLoadedLanguages()}function m(...y){x(),n.loadLanguages(y.flat(1))}async function h(...y){return m(await $J(y))}function p(...y){x();for(let S of y.flat(1))n.loadTheme(S)}async function v(...y){return x(),p(await PJ(y))}function x(){if(t)throw new ca("Shiki instance has been disposed")}function g(){t||(t=!0,n.dispose(),mS-=1)}return{setTheme:c,getTheme:u,getLanguage:s,getLoadedThemes:d,getLoadedLanguages:f,resolveLangAlias:i,loadLanguage:h,loadLanguageSync:m,loadTheme:v,loadThemeSync:p,dispose:g,[Symbol.dispose]:g}}async function V4(e){e.engine||console.warn("`engine` option is required. Use `createOnigurumaEngine` or `createJavaScriptRegexEngine` to create an engine.");let[t,a,r]=await Promise.all([PJ(e.themes||[]),$J(e.langs||[]),e.engine]);return H4({...e,themes:t,langs:a,engine:r})}var EJ=new WeakMap;function vS(e,t){EJ.set(e,t)}function ov(e){return EJ.get(e)}var jI=class MJ{_stacks={};lang;get themes(){return Object.keys(this._stacks)}get theme(){return this.themes[0]}get _stack(){return this._stacks[this.theme]}static initial(t,a){return new MJ(Object.fromEntries(AJ(a).map(r=>[r,zI])),t)}constructor(...t){if(t.length===2){let[a,r]=t;this.lang=r,this._stacks=a}else{let[a,r,n]=t;this.lang=r,this._stacks={[n]:a}}}getInternalStack(t=this.theme){return this._stacks[t]}getScopes(t=this.theme){return A0e(this._stacks[t])}toJSON(){return{lang:this.lang,theme:this.theme,themes:this.themes,scopes:this.getScopes()}}};function A0e(e){let t=[],a=new Set;function r(n){if(a.has(n))return;a.add(n);let o=n?.nameScopesList?.scopeName;o&&t.push(o),n.parent&&r(n.parent)}return r(e),t}function $0e(e,t){if(!(e instanceof jI))throw new ca("Invalid grammar state");return e.getInternalStack(t)}var P0e=/,/,D0e=/ /;function q4(e,t,a={}){let{theme:r=e.getLoadedThemes()[0]}=a;if(hS(e.resolveLangAlias(a.lang||"text"))||gS(r))return rv(t).map(s=>[{content:s[0],offset:s[1]}]);let{theme:n,colorMap:o}=e.setTheme(r),i=e.getLanguage(a.lang||"text");if(a.grammarState){if(a.grammarState.lang!==i.name)throw new ca(`Grammar state language "${a.grammarState.lang}" does not match highlight language "${i.name}"`);if(!a.grammarState.themes.includes(n.name))throw new ca(`Grammar state themes "${a.grammarState.themes}" do not contain highlight theme "${n.name}"`)}return zJ(t,i,n,o,a)}function OJ(...e){if(e.length===2)return ov(e[1]);let[t,a,r={}]=e,{lang:n="text",theme:o=t.getLoadedThemes()[0]}=r;if(hS(n)||gS(o))throw new ca("Plain language does not have grammar state");if(n==="ansi")throw new ca("ANSI language does not have grammar state");let{theme:i,colorMap:s}=t.setTheme(o),u=t.getLanguage(n);return new jI(Z4(a,u,i,s,r).stateStack,u.name,i.name)}function zJ(e,t,a,r,n){let o=Z4(e,t,a,r,n),i=new jI(o.stateStack,t.name,a.name);return vS(o.tokens,i),o.tokens}function Z4(e,t,a,r,n){let o=pS(a,n),{tokenizeMaxLineLength:i=0,tokenizeTimeLimit:s=500}=n,u=rv(e),c=n.grammarState?$0e(n.grammarState,a.name)??zI:n.grammarContextCode!=null?Z4(n.grammarContextCode,t,a,r,{...n,grammarState:void 0,grammarContextCode:void 0}).stateStack:zI,d=[],f=[];for(let m=0,h=u.length;m<h;m++){let[p,v]=u[m];if(p===""){d=[],f.push([]);continue}if(i>0&&p.length>=i){d=[],f.push([{content:p,offset:v,color:"",fontStyle:0}]);continue}let x,g,y;n.includeExplanation&&(x=t.tokenizeLine(p,c,s),g=x.tokens,y=0);let S=t.tokenizeLine2(p,c,s),C=S.tokens.length/2;for(let I=0;I<C;I++){let T=S.tokens[2*I],N=I+1<C?S.tokens[2*I+2]:p.length;if(T===N)continue;let k=S.tokens[2*I+1],U=kc(r[ip.getForeground(k)],o),B=ip.getFontStyle(k),le={content:p.substring(T,N),offset:v+T,color:U,fontStyle:B};if(n.includeExplanation){let z=[];if(n.includeExplanation!=="scopeName")for(let ee of a.settings){let ve;switch(typeof ee.scope){case"string":ve=ee.scope.split(P0e).map(G=>G.trim());break;case"object":ve=ee.scope;break;default:continue}z.push({settings:ee,selectors:ve.map(G=>G.split(D0e))})}le.explanation=[];let J=0;for(;T+J<N;){let ee=g[y],ve=p.substring(ee.startIndex,ee.endIndex);J+=ve.length,le.explanation.push({content:ve,scopes:n.includeExplanation==="scopeName"?E0e(ee.scopes):M0e(z,ee.scopes)}),y+=1}}d.push(le)}f.push(d),d=[],c=S.ruleStack}return{tokens:f,stateStack:c}}function E0e(e){return e.map(t=>({scopeName:t}))}function M0e(e,t){let a=[];for(let r=0,n=t.length;r<n;r++){let o=t[r];a[r]={scopeName:o,themeMatches:z0e(e,o,t.slice(0,r))}}return a}function RJ(e,t){return e===t||t.substring(0,e.length)===e&&t[e.length]==="."}function O0e(e,t,a){if(!RJ(e.at(-1),t))return!1;let r=e.length-2,n=a.length-1;for(;r>=0&&n>=0;)RJ(e[r],a[n])&&(r-=1),n-=1;return r===-1}function z0e(e,t,a){let r=[];for(let{selectors:n,settings:o}of e)for(let i of n)if(O0e(i,t,a)){r.push(o);break}return r}function BI(e,t,a,r=q4){let n=Object.entries(a.themes).filter(c=>c[1]).map(c=>({color:c[0],theme:c[1]})),o=n.map(c=>{let d=r(e,t,{...a,theme:c.theme});return{tokens:d,state:ov(d),theme:typeof c.theme=="string"?c.theme:c.theme.name}}),i=U0e(...o.map(c=>c.tokens)),s=i[0].map((c,d)=>c.map((f,m)=>{let h={content:f.content,variants:{},offset:f.offset};return"includeExplanation"in a&&a.includeExplanation&&(h.explanation=f.explanation),i.forEach((p,v)=>{let{content:x,explanation:g,offset:y,...S}=p[d][m];h.variants[n[v].color]=S}),h})),u=o[0].state?new jI(Object.fromEntries(o.map(c=>[c.theme,c.state?.getInternalStack(c.theme)])),o[0].state.lang):void 0;return u&&vS(s,u),s}function U0e(...e){let t=e.map(()=>[]),a=e.length;for(let r=0;r<e[0].length;r++){let n=e.map(u=>u[r]),o=t.map(()=>[]);t.forEach((u,c)=>u.push(o[c]));let i=n.map(()=>0),s=n.map(u=>u[0]);for(;s.every(u=>u);){let u=Math.min(...s.map(c=>c.content.length));for(let c=0;c<a;c++){let d=s[c];d.content.length===u?(o[c].push(d),i[c]+=1,s[c]=n[c][i[c]]):(o[c].push({...d,content:d.content.slice(0,u)}),s[c]={...d,content:d.content.slice(u),offset:d.offset+u})}}}return t}var UJ=["area","base","basefont","bgsound","br","col","command","embed","frame","hr","image","img","input","keygen","link","meta","param","source","track","wbr"];var Ic=class{constructor(t,a,r){this.normal=a,this.property=t,r&&(this.space=r)}};Ic.prototype.normal={};Ic.prototype.property={};Ic.prototype.space=void 0;function G4(e,t){let a={},r={};for(let n of e)Object.assign(a,n.property),Object.assign(r,n.normal);return new Ic(a,r,t)}function yS(e){return e.toLowerCase()}var Nr=class{constructor(t,a){this.attribute=a,this.property=t}};Nr.prototype.attribute="";Nr.prototype.booleanish=!1;Nr.prototype.boolean=!1;Nr.prototype.commaOrSpaceSeparated=!1;Nr.prototype.commaSeparated=!1;Nr.prototype.defined=!1;Nr.prototype.mustUseProperty=!1;Nr.prototype.number=!1;Nr.prototype.overloadedBoolean=!1;Nr.prototype.property="";Nr.prototype.spaceSeparated=!1;Nr.prototype.space=void 0;var bS={};Ml(bS,{boolean:()=>nt,booleanish:()=>kn,commaOrSpaceSeparated:()=>Ci,commaSeparated:()=>of,number:()=>Q,overloadedBoolean:()=>FI,spaceSeparated:()=>da});var j0e=0,nt=sp(),kn=sp(),FI=sp(),Q=sp(),da=sp(),of=sp(),Ci=sp();function sp(){return 2**++j0e}var K4=Object.keys(bS),lp=class extends Nr{constructor(t,a,r,n){let o=-1;if(super(t,a),jJ(this,"space",n),typeof r=="number")for(;++o<K4.length;){let i=K4[o];jJ(this,K4[o],(r&bS[i])===bS[i])}}};lp.prototype.defined=!0;function jJ(e,t,a){a&&(e[t]=a)}function Es(e){let t={},a={};for(let[r,n]of Object.entries(e.properties)){let o=new lp(r,e.transform(e.attributes||{},r),n,e.space);e.mustUseProperty&&e.mustUseProperty.includes(r)&&(o.mustUseProperty=!0),t[r]=o,a[yS(r)]=r,a[yS(o.attribute)]=r}return new Ic(t,a,e.space)}var W4=Es({properties:{ariaActiveDescendant:null,ariaAtomic:kn,ariaAutoComplete:null,ariaBusy:kn,ariaChecked:kn,ariaColCount:Q,ariaColIndex:Q,ariaColSpan:Q,ariaControls:da,ariaCurrent:null,ariaDescribedBy:da,ariaDetails:null,ariaDisabled:kn,ariaDropEffect:da,ariaErrorMessage:null,ariaExpanded:kn,ariaFlowTo:da,ariaGrabbed:kn,ariaHasPopup:null,ariaHidden:kn,ariaInvalid:null,ariaKeyShortcuts:null,ariaLabel:null,ariaLabelledBy:da,ariaLevel:Q,ariaLive:null,ariaModal:kn,ariaMultiLine:kn,ariaMultiSelectable:kn,ariaOrientation:null,ariaOwns:da,ariaPlaceholder:null,ariaPosInSet:Q,ariaPressed:kn,ariaReadOnly:kn,ariaRelevant:null,ariaRequired:kn,ariaRoleDescription:da,ariaRowCount:Q,ariaRowIndex:Q,ariaRowSpan:Q,ariaSelected:kn,ariaSetSize:Q,ariaSort:null,ariaValueMax:Q,ariaValueMin:Q,ariaValueNow:Q,ariaValueText:null,role:null},transform(e,t){return t==="role"?t:"aria-"+t.slice(4).toLowerCase()}});function HI(e,t){return t in e?e[t]:t}function VI(e,t){return HI(e,t.toLowerCase())}var BJ=Es({attributes:{acceptcharset:"accept-charset",classname:"class",htmlfor:"for",httpequiv:"http-equiv"},mustUseProperty:["checked","multiple","muted","selected"],properties:{abbr:null,accept:of,acceptCharset:da,accessKey:da,action:null,allow:null,allowFullScreen:nt,allowPaymentRequest:nt,allowUserMedia:nt,alt:null,as:null,async:nt,autoCapitalize:null,autoComplete:da,autoFocus:nt,autoPlay:nt,blocking:da,capture:null,charSet:null,checked:nt,cite:null,className:da,cols:Q,colSpan:null,content:null,contentEditable:kn,controls:nt,controlsList:da,coords:Q|of,crossOrigin:null,data:null,dateTime:null,decoding:null,default:nt,defer:nt,dir:null,dirName:null,disabled:nt,download:FI,draggable:kn,encType:null,enterKeyHint:null,fetchPriority:null,form:null,formAction:null,formEncType:null,formMethod:null,formNoValidate:nt,formTarget:null,headers:da,height:Q,hidden:FI,high:Q,href:null,hrefLang:null,htmlFor:da,httpEquiv:da,id:null,imageSizes:null,imageSrcSet:null,inert:nt,inputMode:null,integrity:null,is:null,isMap:nt,itemId:null,itemProp:da,itemRef:da,itemScope:nt,itemType:da,kind:null,label:null,lang:null,language:null,list:null,loading:null,loop:nt,low:Q,manifest:null,max:null,maxLength:Q,media:null,method:null,min:null,minLength:Q,multiple:nt,muted:nt,name:null,nonce:null,noModule:nt,noValidate:nt,onAbort:null,onAfterPrint:null,onAuxClick:null,onBeforeMatch:null,onBeforePrint:null,onBeforeToggle:null,onBeforeUnload:null,onBlur:null,onCancel:null,onCanPlay:null,onCanPlayThrough:null,onChange:null,onClick:null,onClose:null,onContextLost:null,onContextMenu:null,onContextRestored:null,onCopy:null,onCueChange:null,onCut:null,onDblClick:null,onDrag:null,onDragEnd:null,onDragEnter:null,onDragExit:null,onDragLeave:null,onDragOver:null,onDragStart:null,onDrop:null,onDurationChange:null,onEmptied:null,onEnded:null,onError:null,onFocus:null,onFormData:null,onHashChange:null,onInput:null,onInvalid:null,onKeyDown:null,onKeyPress:null,onKeyUp:null,onLanguageChange:null,onLoad:null,onLoadedData:null,onLoadedMetadata:null,onLoadEnd:null,onLoadStart:null,onMessage:null,onMessageError:null,onMouseDown:null,onMouseEnter:null,onMouseLeave:null,onMouseMove:null,onMouseOut:null,onMouseOver:null,onMouseUp:null,onOffline:null,onOnline:null,onPageHide:null,onPageShow:null,onPaste:null,onPause:null,onPlay:null,onPlaying:null,onPopState:null,onProgress:null,onRateChange:null,onRejectionHandled:null,onReset:null,onResize:null,onScroll:null,onScrollEnd:null,onSecurityPolicyViolation:null,onSeeked:null,onSeeking:null,onSelect:null,onSlotChange:null,onStalled:null,onStorage:null,onSubmit:null,onSuspend:null,onTimeUpdate:null,onToggle:null,onUnhandledRejection:null,onUnload:null,onVolumeChange:null,onWaiting:null,onWheel:null,open:nt,optimum:Q,pattern:null,ping:da,placeholder:null,playsInline:nt,popover:null,popoverTarget:null,popoverTargetAction:null,poster:null,preload:null,readOnly:nt,referrerPolicy:null,rel:da,required:nt,reversed:nt,rows:Q,rowSpan:Q,sandbox:da,scope:null,scoped:nt,seamless:nt,selected:nt,shadowRootClonable:nt,shadowRootDelegatesFocus:nt,shadowRootMode:null,shape:null,size:Q,sizes:null,slot:null,span:Q,spellCheck:kn,src:null,srcDoc:null,srcLang:null,srcSet:null,start:Q,step:null,style:null,tabIndex:Q,target:null,title:null,translate:null,type:null,typeMustMatch:nt,useMap:null,value:kn,width:Q,wrap:null,writingSuggestions:null,align:null,aLink:null,archive:da,axis:null,background:null,bgColor:null,border:Q,borderColor:null,bottomMargin:Q,cellPadding:null,cellSpacing:null,char:null,charOff:null,classId:null,clear:null,code:null,codeBase:null,codeType:null,color:null,compact:nt,declare:nt,event:null,face:null,frame:null,frameBorder:null,hSpace:Q,leftMargin:Q,link:null,longDesc:null,lowSrc:null,marginHeight:Q,marginWidth:Q,noResize:nt,noHref:nt,noShade:nt,noWrap:nt,object:null,profile:null,prompt:null,rev:null,rightMargin:Q,rules:null,scheme:null,scrolling:kn,standby:null,summary:null,text:null,topMargin:Q,valueType:null,version:null,vAlign:null,vLink:null,vSpace:Q,allowTransparency:null,autoCorrect:null,autoSave:null,disablePictureInPicture:nt,disableRemotePlayback:nt,prefix:null,property:null,results:Q,security:null,unselectable:null},space:"html",transform:VI});var FJ=Es({attributes:{accentHeight:"accent-height",alignmentBaseline:"alignment-baseline",arabicForm:"arabic-form",baselineShift:"baseline-shift",capHeight:"cap-height",className:"class",clipPath:"clip-path",clipRule:"clip-rule",colorInterpolation:"color-interpolation",colorInterpolationFilters:"color-interpolation-filters",colorProfile:"color-profile",colorRendering:"color-rendering",crossOrigin:"crossorigin",dataType:"datatype",dominantBaseline:"dominant-baseline",enableBackground:"enable-background",fillOpacity:"fill-opacity",fillRule:"fill-rule",floodColor:"flood-color",floodOpacity:"flood-opacity",fontFamily:"font-family",fontSize:"font-size",fontSizeAdjust:"font-size-adjust",fontStretch:"font-stretch",fontStyle:"font-style",fontVariant:"font-variant",fontWeight:"font-weight",glyphName:"glyph-name",glyphOrientationHorizontal:"glyph-orientation-horizontal",glyphOrientationVertical:"glyph-orientation-vertical",hrefLang:"hreflang",horizAdvX:"horiz-adv-x",horizOriginX:"horiz-origin-x",horizOriginY:"horiz-origin-y",imageRendering:"image-rendering",letterSpacing:"letter-spacing",lightingColor:"lighting-color",markerEnd:"marker-end",markerMid:"marker-mid",markerStart:"marker-start",navDown:"nav-down",navDownLeft:"nav-down-left",navDownRight:"nav-down-right",navLeft:"nav-left",navNext:"nav-next",navPrev:"nav-prev",navRight:"nav-right",navUp:"nav-up",navUpLeft:"nav-up-left",navUpRight:"nav-up-right",onAbort:"onabort",onActivate:"onactivate",onAfterPrint:"onafterprint",onBeforePrint:"onbeforeprint",onBegin:"onbegin",onCancel:"oncancel",onCanPlay:"oncanplay",onCanPlayThrough:"oncanplaythrough",onChange:"onchange",onClick:"onclick",onClose:"onclose",onCopy:"oncopy",onCueChange:"oncuechange",onCut:"oncut",onDblClick:"ondblclick",onDrag:"ondrag",onDragEnd:"ondragend",onDragEnter:"ondragenter",onDragExit:"ondragexit",onDragLeave:"ondragleave",onDragOver:"ondragover",onDragStart:"ondragstart",onDrop:"ondrop",onDurationChange:"ondurationchange",onEmptied:"onemptied",onEnd:"onend",onEnded:"onended",onError:"onerror",onFocus:"onfocus",onFocusIn:"onfocusin",onFocusOut:"onfocusout",onHashChange:"onhashchange",onInput:"oninput",onInvalid:"oninvalid",onKeyDown:"onkeydown",onKeyPress:"onkeypress",onKeyUp:"onkeyup",onLoad:"onload",onLoadedData:"onloadeddata",onLoadedMetadata:"onloadedmetadata",onLoadStart:"onloadstart",onMessage:"onmessage",onMouseDown:"onmousedown",onMouseEnter:"onmouseenter",onMouseLeave:"onmouseleave",onMouseMove:"onmousemove",onMouseOut:"onmouseout",onMouseOver:"onmouseover",onMouseUp:"onmouseup",onMouseWheel:"onmousewheel",onOffline:"onoffline",onOnline:"ononline",onPageHide:"onpagehide",onPageShow:"onpageshow",onPaste:"onpaste",onPause:"onpause",onPlay:"onplay",onPlaying:"onplaying",onPopState:"onpopstate",onProgress:"onprogress",onRateChange:"onratechange",onRepeat:"onrepeat",onReset:"onreset",onResize:"onresize",onScroll:"onscroll",onSeeked:"onseeked",onSeeking:"onseeking",onSelect:"onselect",onShow:"onshow",onStalled:"onstalled",onStorage:"onstorage",onSubmit:"onsubmit",onSuspend:"onsuspend",onTimeUpdate:"ontimeupdate",onToggle:"ontoggle",onUnload:"onunload",onVolumeChange:"onvolumechange",onWaiting:"onwaiting",onZoom:"onzoom",overlinePosition:"overline-position",overlineThickness:"overline-thickness",paintOrder:"paint-order",panose1:"panose-1",pointerEvents:"pointer-events",referrerPolicy:"referrerpolicy",renderingIntent:"rendering-intent",shapeRendering:"shape-rendering",stopColor:"stop-color",stopOpacity:"stop-opacity",strikethroughPosition:"strikethrough-position",strikethroughThickness:"strikethrough-thickness",strokeDashArray:"stroke-dasharray",strokeDashOffset:"stroke-dashoffset",strokeLineCap:"stroke-linecap",strokeLineJoin:"stroke-linejoin",strokeMiterLimit:"stroke-miterlimit",strokeOpacity:"stroke-opacity",strokeWidth:"stroke-width",tabIndex:"tabindex",textAnchor:"text-anchor",textDecoration:"text-decoration",textRendering:"text-rendering",transformOrigin:"transform-origin",typeOf:"typeof",underlinePosition:"underline-position",underlineThickness:"underline-thickness",unicodeBidi:"unicode-bidi",unicodeRange:"unicode-range",unitsPerEm:"units-per-em",vAlphabetic:"v-alphabetic",vHanging:"v-hanging",vIdeographic:"v-ideographic",vMathematical:"v-mathematical",vectorEffect:"vector-effect",vertAdvY:"vert-adv-y",vertOriginX:"vert-origin-x",vertOriginY:"vert-origin-y",wordSpacing:"word-spacing",writingMode:"writing-mode",xHeight:"x-height",playbackOrder:"playbackorder",timelineBegin:"timelinebegin"},properties:{about:Ci,accentHeight:Q,accumulate:null,additive:null,alignmentBaseline:null,alphabetic:Q,amplitude:Q,arabicForm:null,ascent:Q,attributeName:null,attributeType:null,azimuth:Q,bandwidth:null,baselineShift:null,baseFrequency:null,baseProfile:null,bbox:null,begin:null,bias:Q,by:null,calcMode:null,capHeight:Q,className:da,clip:null,clipPath:null,clipPathUnits:null,clipRule:null,color:null,colorInterpolation:null,colorInterpolationFilters:null,colorProfile:null,colorRendering:null,content:null,contentScriptType:null,contentStyleType:null,crossOrigin:null,cursor:null,cx:null,cy:null,d:null,dataType:null,defaultAction:null,descent:Q,diffuseConstant:Q,direction:null,display:null,dur:null,divisor:Q,dominantBaseline:null,download:nt,dx:null,dy:null,edgeMode:null,editable:null,elevation:Q,enableBackground:null,end:null,event:null,exponent:Q,externalResourcesRequired:null,fill:null,fillOpacity:Q,fillRule:null,filter:null,filterRes:null,filterUnits:null,floodColor:null,floodOpacity:null,focusable:null,focusHighlight:null,fontFamily:null,fontSize:null,fontSizeAdjust:null,fontStretch:null,fontStyle:null,fontVariant:null,fontWeight:null,format:null,fr:null,from:null,fx:null,fy:null,g1:of,g2:of,glyphName:of,glyphOrientationHorizontal:null,glyphOrientationVertical:null,glyphRef:null,gradientTransform:null,gradientUnits:null,handler:null,hanging:Q,hatchContentUnits:null,hatchUnits:null,height:null,href:null,hrefLang:null,horizAdvX:Q,horizOriginX:Q,horizOriginY:Q,id:null,ideographic:Q,imageRendering:null,initialVisibility:null,in:null,in2:null,intercept:Q,k:Q,k1:Q,k2:Q,k3:Q,k4:Q,kernelMatrix:Ci,kernelUnitLength:null,keyPoints:null,keySplines:null,keyTimes:null,kerning:null,lang:null,lengthAdjust:null,letterSpacing:null,lightingColor:null,limitingConeAngle:Q,local:null,markerEnd:null,markerMid:null,markerStart:null,markerHeight:null,markerUnits:null,markerWidth:null,mask:null,maskContentUnits:null,maskUnits:null,mathematical:null,max:null,media:null,mediaCharacterEncoding:null,mediaContentEncodings:null,mediaSize:Q,mediaTime:null,method:null,min:null,mode:null,name:null,navDown:null,navDownLeft:null,navDownRight:null,navLeft:null,navNext:null,navPrev:null,navRight:null,navUp:null,navUpLeft:null,navUpRight:null,numOctaves:null,observer:null,offset:null,onAbort:null,onActivate:null,onAfterPrint:null,onBeforePrint:null,onBegin:null,onCancel:null,onCanPlay:null,onCanPlayThrough:null,onChange:null,onClick:null,onClose:null,onCopy:null,onCueChange:null,onCut:null,onDblClick:null,onDrag:null,onDragEnd:null,onDragEnter:null,onDragExit:null,onDragLeave:null,onDragOver:null,onDragStart:null,onDrop:null,onDurationChange:null,onEmptied:null,onEnd:null,onEnded:null,onError:null,onFocus:null,onFocusIn:null,onFocusOut:null,onHashChange:null,onInput:null,onInvalid:null,onKeyDown:null,onKeyPress:null,onKeyUp:null,onLoad:null,onLoadedData:null,onLoadedMetadata:null,onLoadStart:null,onMessage:null,onMouseDown:null,onMouseEnter:null,onMouseLeave:null,onMouseMove:null,onMouseOut:null,onMouseOver:null,onMouseUp:null,onMouseWheel:null,onOffline:null,onOnline:null,onPageHide:null,onPageShow:null,onPaste:null,onPause:null,onPlay:null,onPlaying:null,onPopState:null,onProgress:null,onRateChange:null,onRepeat:null,onReset:null,onResize:null,onScroll:null,onSeeked:null,onSeeking:null,onSelect:null,onShow:null,onStalled:null,onStorage:null,onSubmit:null,onSuspend:null,onTimeUpdate:null,onToggle:null,onUnload:null,onVolumeChange:null,onWaiting:null,onZoom:null,opacity:null,operator:null,order:null,orient:null,orientation:null,origin:null,overflow:null,overlay:null,overlinePosition:Q,overlineThickness:Q,paintOrder:null,panose1:null,path:null,pathLength:Q,patternContentUnits:null,patternTransform:null,patternUnits:null,phase:null,ping:da,pitch:null,playbackOrder:null,pointerEvents:null,points:null,pointsAtX:Q,pointsAtY:Q,pointsAtZ:Q,preserveAlpha:null,preserveAspectRatio:null,primitiveUnits:null,propagate:null,property:Ci,r:null,radius:null,referrerPolicy:null,refX:null,refY:null,rel:Ci,rev:Ci,renderingIntent:null,repeatCount:null,repeatDur:null,requiredExtensions:Ci,requiredFeatures:Ci,requiredFonts:Ci,requiredFormats:Ci,resource:null,restart:null,result:null,rotate:null,rx:null,ry:null,scale:null,seed:null,shapeRendering:null,side:null,slope:null,snapshotTime:null,specularConstant:Q,specularExponent:Q,spreadMethod:null,spacing:null,startOffset:null,stdDeviation:null,stemh:null,stemv:null,stitchTiles:null,stopColor:null,stopOpacity:null,strikethroughPosition:Q,strikethroughThickness:Q,string:null,stroke:null,strokeDashArray:Ci,strokeDashOffset:null,strokeLineCap:null,strokeLineJoin:null,strokeMiterLimit:Q,strokeOpacity:Q,strokeWidth:null,style:null,surfaceScale:Q,syncBehavior:null,syncBehaviorDefault:null,syncMaster:null,syncTolerance:null,syncToleranceDefault:null,systemLanguage:Ci,tabIndex:Q,tableValues:null,target:null,targetX:Q,targetY:Q,textAnchor:null,textDecoration:null,textRendering:null,textLength:null,timelineBegin:null,title:null,transformBehavior:null,type:null,typeOf:Ci,to:null,transform:null,transformOrigin:null,u1:null,u2:null,underlinePosition:Q,underlineThickness:Q,unicode:null,unicodeBidi:null,unicodeRange:null,unitsPerEm:Q,values:null,vAlphabetic:Q,vMathematical:Q,vectorEffect:null,vHanging:Q,vIdeographic:Q,version:null,vertAdvY:Q,vertOriginX:Q,vertOriginY:Q,viewBox:null,viewTarget:null,visibility:null,width:null,widths:null,wordSpacing:null,writingMode:null,x:null,x1:null,x2:null,xChannelSelector:null,xHeight:Q,y:null,y1:null,y2:null,yChannelSelector:null,z:null,zoomAndPan:null},space:"svg",transform:HI});var J4=Es({properties:{xLinkActuate:null,xLinkArcRole:null,xLinkHref:null,xLinkRole:null,xLinkShow:null,xLinkTitle:null,xLinkType:null},space:"xlink",transform(e,t){return"xlink:"+t.slice(5).toLowerCase()}});var Q4=Es({attributes:{xmlnsxlink:"xmlns:xlink"},properties:{xmlnsXLink:null,xmlns:null},space:"xmlns",transform:VI});var X4=Es({properties:{xmlBase:null,xmlLang:null,xmlSpace:null},space:"xml",transform(e,t){return"xml:"+t.slice(3).toLowerCase()}});var B0e=/[A-Z]/g,HJ=/-[a-z]/g,F0e=/^data[-\w.:]+$/i;function Y4(e,t){let a=yS(t),r=t,n=Nr;if(a in e.normal)return e.property[e.normal[a]];if(a.length>4&&a.slice(0,4)==="data"&&F0e.test(t)){if(t.charAt(4)==="-"){let o=t.slice(5).replace(HJ,V0e);r="data"+o.charAt(0).toUpperCase()+o.slice(1)}else{let o=t.slice(4);if(!HJ.test(o)){let i=o.replace(B0e,H0e);i.charAt(0)!=="-"&&(i="-"+i),t="data"+i}}n=lp}return new n(r,t)}function H0e(e){return"-"+e.toLowerCase()}function V0e(e){return e.charAt(1).toUpperCase()}var VJ=G4([W4,BJ,J4,Q4,X4],"html"),qI=G4([W4,FJ,J4,Q4,X4],"svg");var qJ={}.hasOwnProperty;function ZJ(e,t){let a=t||{};function r(n,...o){let i=r.invalid,s=r.handlers;if(n&&qJ.call(n,e)){let u=String(n[e]);i=qJ.call(s,u)?s[u]:r.unknown}if(i)return i.call(this,n,...o)}return r.handlers=a.handlers||{},r.invalid=a.invalid,r.unknown=a.unknown,r}var q0e=/["&'<>`]/g,Z0e=/[\uD800-\uDBFF][\uDC00-\uDFFF]/g,G0e=/[\x01-\t\v\f\x0E-\x1F\x7F\x81\x8D\x8F\x90\x9D\xA0-\uFFFF]/g,K0e=/[|\\{}()[\]^$+*?.]/g,GJ=new WeakMap;function KJ(e,t){if(e=e.replace(t.subset?W0e(t.subset):q0e,r),t.subset||t.escapeOnly)return e;return e.replace(Z0e,a).replace(G0e,r);function a(n,o,i){return t.format((n.charCodeAt(0)-55296)*1024+n.charCodeAt(1)-56320+65536,i.charCodeAt(o+2),t)}function r(n,o,i){return t.format(n.charCodeAt(0),i.charCodeAt(o+1),t)}}function W0e(e){let t=GJ.get(e);return t||(t=J0e(e),GJ.set(e,t)),t}function J0e(e){let t=[],a=-1;for(;++a<e.length;)t.push(e[a].replace(K0e,"\\$&"));return new RegExp("(?:"+t.join("|")+")","g")}var Q0e=/[\dA-Fa-f]/;function WJ(e,t,a){let r="&#x"+e.toString(16).toUpperCase();return a&&t&&!Q0e.test(String.fromCharCode(t))?r:r+";"}var X0e=/\d/;function JJ(e,t,a){let r="&#"+String(e);return a&&t&&!X0e.test(String.fromCharCode(t))?r:r+";"}var QJ=["AElig","AMP","Aacute","Acirc","Agrave","Aring","Atilde","Auml","COPY","Ccedil","ETH","Eacute","Ecirc","Egrave","Euml","GT","Iacute","Icirc","Igrave","Iuml","LT","Ntilde","Oacute","Ocirc","Ograve","Oslash","Otilde","Ouml","QUOT","REG","THORN","Uacute","Ucirc","Ugrave","Uuml","Yacute","aacute","acirc","acute","aelig","agrave","amp","aring","atilde","auml","brvbar","ccedil","cedil","cent","copy","curren","deg","divide","eacute","ecirc","egrave","eth","euml","frac12","frac14","frac34","gt","iacute","icirc","iexcl","igrave","iquest","iuml","laquo","lt","macr","micro","middot","nbsp","not","ntilde","oacute","ocirc","ograve","ordf","ordm","oslash","otilde","ouml","para","plusmn","pound","quot","raquo","reg","sect","shy","sup1","sup2","sup3","szlig","thorn","times","uacute","ucirc","ugrave","uml","uuml","yacute","yen","yuml"];var ZI={nbsp:"\xA0",iexcl:"\xA1",cent:"\xA2",pound:"\xA3",curren:"\xA4",yen:"\xA5",brvbar:"\xA6",sect:"\xA7",uml:"\xA8",copy:"\xA9",ordf:"\xAA",laquo:"\xAB",not:"\xAC",shy:"\xAD",reg:"\xAE",macr:"\xAF",deg:"\xB0",plusmn:"\xB1",sup2:"\xB2",sup3:"\xB3",acute:"\xB4",micro:"\xB5",para:"\xB6",middot:"\xB7",cedil:"\xB8",sup1:"\xB9",ordm:"\xBA",raquo:"\xBB",frac14:"\xBC",frac12:"\xBD",frac34:"\xBE",iquest:"\xBF",Agrave:"\xC0",Aacute:"\xC1",Acirc:"\xC2",Atilde:"\xC3",Auml:"\xC4",Aring:"\xC5",AElig:"\xC6",Ccedil:"\xC7",Egrave:"\xC8",Eacute:"\xC9",Ecirc:"\xCA",Euml:"\xCB",Igrave:"\xCC",Iacute:"\xCD",Icirc:"\xCE",Iuml:"\xCF",ETH:"\xD0",Ntilde:"\xD1",Ograve:"\xD2",Oacute:"\xD3",Ocirc:"\xD4",Otilde:"\xD5",Ouml:"\xD6",times:"\xD7",Oslash:"\xD8",Ugrave:"\xD9",Uacute:"\xDA",Ucirc:"\xDB",Uuml:"\xDC",Yacute:"\xDD",THORN:"\xDE",szlig:"\xDF",agrave:"\xE0",aacute:"\xE1",acirc:"\xE2",atilde:"\xE3",auml:"\xE4",aring:"\xE5",aelig:"\xE6",ccedil:"\xE7",egrave:"\xE8",eacute:"\xE9",ecirc:"\xEA",euml:"\xEB",igrave:"\xEC",iacute:"\xED",icirc:"\xEE",iuml:"\xEF",eth:"\xF0",ntilde:"\xF1",ograve:"\xF2",oacute:"\xF3",ocirc:"\xF4",otilde:"\xF5",ouml:"\xF6",divide:"\xF7",oslash:"\xF8",ugrave:"\xF9",uacute:"\xFA",ucirc:"\xFB",uuml:"\xFC",yacute:"\xFD",thorn:"\xFE",yuml:"\xFF",fnof:"\u0192",Alpha:"\u0391",Beta:"\u0392",Gamma:"\u0393",Delta:"\u0394",Epsilon:"\u0395",Zeta:"\u0396",Eta:"\u0397",Theta:"\u0398",Iota:"\u0399",Kappa:"\u039A",Lambda:"\u039B",Mu:"\u039C",Nu:"\u039D",Xi:"\u039E",Omicron:"\u039F",Pi:"\u03A0",Rho:"\u03A1",Sigma:"\u03A3",Tau:"\u03A4",Upsilon:"\u03A5",Phi:"\u03A6",Chi:"\u03A7",Psi:"\u03A8",Omega:"\u03A9",alpha:"\u03B1",beta:"\u03B2",gamma:"\u03B3",delta:"\u03B4",epsilon:"\u03B5",zeta:"\u03B6",eta:"\u03B7",theta:"\u03B8",iota:"\u03B9",kappa:"\u03BA",lambda:"\u03BB",mu:"\u03BC",nu:"\u03BD",xi:"\u03BE",omicron:"\u03BF",pi:"\u03C0",rho:"\u03C1",sigmaf:"\u03C2",sigma:"\u03C3",tau:"\u03C4",upsilon:"\u03C5",phi:"\u03C6",chi:"\u03C7",psi:"\u03C8",omega:"\u03C9",thetasym:"\u03D1",upsih:"\u03D2",piv:"\u03D6",bull:"\u2022",hellip:"\u2026",prime:"\u2032",Prime:"\u2033",oline:"\u203E",frasl:"\u2044",weierp:"\u2118",image:"\u2111",real:"\u211C",trade:"\u2122",alefsym:"\u2135",larr:"\u2190",uarr:"\u2191",rarr:"\u2192",darr:"\u2193",harr:"\u2194",crarr:"\u21B5",lArr:"\u21D0",uArr:"\u21D1",rArr:"\u21D2",dArr:"\u21D3",hArr:"\u21D4",forall:"\u2200",part:"\u2202",exist:"\u2203",empty:"\u2205",nabla:"\u2207",isin:"\u2208",notin:"\u2209",ni:"\u220B",prod:"\u220F",sum:"\u2211",minus:"\u2212",lowast:"\u2217",radic:"\u221A",prop:"\u221D",infin:"\u221E",ang:"\u2220",and:"\u2227",or:"\u2228",cap:"\u2229",cup:"\u222A",int:"\u222B",there4:"\u2234",sim:"\u223C",cong:"\u2245",asymp:"\u2248",ne:"\u2260",equiv:"\u2261",le:"\u2264",ge:"\u2265",sub:"\u2282",sup:"\u2283",nsub:"\u2284",sube:"\u2286",supe:"\u2287",oplus:"\u2295",otimes:"\u2297",perp:"\u22A5",sdot:"\u22C5",lceil:"\u2308",rceil:"\u2309",lfloor:"\u230A",rfloor:"\u230B",lang:"\u2329",rang:"\u232A",loz:"\u25CA",spades:"\u2660",clubs:"\u2663",hearts:"\u2665",diams:"\u2666",quot:'"',amp:"&",lt:"<",gt:">",OElig:"\u0152",oelig:"\u0153",Scaron:"\u0160",scaron:"\u0161",Yuml:"\u0178",circ:"\u02C6",tilde:"\u02DC",ensp:"\u2002",emsp:"\u2003",thinsp:"\u2009",zwnj:"\u200C",zwj:"\u200D",lrm:"\u200E",rlm:"\u200F",ndash:"\u2013",mdash:"\u2014",lsquo:"\u2018",rsquo:"\u2019",sbquo:"\u201A",ldquo:"\u201C",rdquo:"\u201D",bdquo:"\u201E",dagger:"\u2020",Dagger:"\u2021",permil:"\u2030",lsaquo:"\u2039",rsaquo:"\u203A",euro:"\u20AC"};var XJ=["cent","copy","divide","gt","lt","not","para","times"];var YJ={}.hasOwnProperty,eU={},GI;for(GI in ZI)YJ.call(ZI,GI)&&(eU[ZI[GI]]=GI);var Y0e=/[^\dA-Za-z]/;function eQ(e,t,a,r){let n=String.fromCharCode(e);if(YJ.call(eU,n)){let o=eU[n],i="&"+o;return a&&QJ.includes(o)&&!XJ.includes(o)&&(!r||t&&t!==61&&Y0e.test(String.fromCharCode(t)))?i:i+";"}return""}function tQ(e,t,a){let r=WJ(e,t,a.omitOptionalSemicolons),n;if((a.useNamedReferences||a.useShortestReferences)&&(n=eQ(e,t,a.omitOptionalSemicolons,a.attribute)),(a.useShortestReferences||!n)&&a.useShortestReferences){let o=JJ(e,t,a.omitOptionalSemicolons);o.length<r.length&&(r=o)}return n&&(!a.useShortestReferences||n.length<r.length)?n:r}function Lc(e,t){return KJ(e,Object.assign({format:tQ},t))}var ewe=/^>|^->|<!--|-->|--!>|<!-$/g,twe=[">"],awe=["<",">"];function aQ(e,t,a,r){return r.settings.bogusComments?"<?"+Lc(e.value,Object.assign({},r.settings.characterReferences,{subset:twe}))+">":"<!--"+e.value.replace(ewe,n)+"-->";function n(o){return Lc(o,Object.assign({},r.settings.characterReferences,{subset:awe}))}}function nQ(e,t,a,r){return"<!"+(r.settings.upperDoctype?"DOCTYPE":"doctype")+(r.settings.tightDoctype?"":" ")+"html>"}function tU(e,t){let a=String(e);if(typeof t!="string")throw new TypeError("Expected character");let r=0,n=a.indexOf(t);for(;n!==-1;)r++,n=a.indexOf(t,n+t.length);return r}function rQ(e,t){let a=t||{};return(e[e.length-1]===""?[...e,""]:e).join((a.padRight?" ":"")+","+(a.padLeft===!1?"":" ")).trim()}function oQ(e){return e.join(" ").trim()}var nwe=/[ \t\n\f\r]/g;function up(e){return typeof e=="object"?e.type==="text"?iQ(e.value):!1:iQ(e)}function iQ(e){return e.replace(nwe,"")===""}var Mn=sQ(1),aU=sQ(-1),rwe=[];function sQ(e){return t;function t(a,r,n){let o=a?a.children:rwe,i=(r||0)+e,s=o[i];if(!n)for(;s&&up(s);)i+=e,s=o[i];return s}}var owe={}.hasOwnProperty;function KI(e){return t;function t(a,r,n){return owe.call(e,a.tagName)&&e[a.tagName](a,r,n)}}var xS=KI({body:swe,caption:nU,colgroup:nU,dd:dwe,dt:cwe,head:nU,html:iwe,li:uwe,optgroup:fwe,option:mwe,p:lwe,rp:lQ,rt:lQ,tbody:hwe,td:uQ,tfoot:gwe,th:uQ,thead:pwe,tr:vwe});function nU(e,t,a){let r=Mn(a,t,!0);return!r||r.type!=="comment"&&!(r.type==="text"&&up(r.value.charAt(0)))}function iwe(e,t,a){let r=Mn(a,t);return!r||r.type!=="comment"}function swe(e,t,a){let r=Mn(a,t);return!r||r.type!=="comment"}function lwe(e,t,a){let r=Mn(a,t);return r?r.type==="element"&&(r.tagName==="address"||r.tagName==="article"||r.tagName==="aside"||r.tagName==="blockquote"||r.tagName==="details"||r.tagName==="div"||r.tagName==="dl"||r.tagName==="fieldset"||r.tagName==="figcaption"||r.tagName==="figure"||r.tagName==="footer"||r.tagName==="form"||r.tagName==="h1"||r.tagName==="h2"||r.tagName==="h3"||r.tagName==="h4"||r.tagName==="h5"||r.tagName==="h6"||r.tagName==="header"||r.tagName==="hgroup"||r.tagName==="hr"||r.tagName==="main"||r.tagName==="menu"||r.tagName==="nav"||r.tagName==="ol"||r.tagName==="p"||r.tagName==="pre"||r.tagName==="section"||r.tagName==="table"||r.tagName==="ul"):!a||!(a.type==="element"&&(a.tagName==="a"||a.tagName==="audio"||a.tagName==="del"||a.tagName==="ins"||a.tagName==="map"||a.tagName==="noscript"||a.tagName==="video"))}function uwe(e,t,a){let r=Mn(a,t);return!r||r.type==="element"&&r.tagName==="li"}function cwe(e,t,a){let r=Mn(a,t);return!!(r&&r.type==="element"&&(r.tagName==="dt"||r.tagName==="dd"))}function dwe(e,t,a){let r=Mn(a,t);return!r||r.type==="element"&&(r.tagName==="dt"||r.tagName==="dd")}function lQ(e,t,a){let r=Mn(a,t);return!r||r.type==="element"&&(r.tagName==="rp"||r.tagName==="rt")}function fwe(e,t,a){let r=Mn(a,t);return!r||r.type==="element"&&r.tagName==="optgroup"}function mwe(e,t,a){let r=Mn(a,t);return!r||r.type==="element"&&(r.tagName==="option"||r.tagName==="optgroup")}function pwe(e,t,a){let r=Mn(a,t);return!!(r&&r.type==="element"&&(r.tagName==="tbody"||r.tagName==="tfoot"))}function hwe(e,t,a){let r=Mn(a,t);return!r||r.type==="element"&&(r.tagName==="tbody"||r.tagName==="tfoot")}function gwe(e,t,a){return!Mn(a,t)}function vwe(e,t,a){let r=Mn(a,t);return!r||r.type==="element"&&r.tagName==="tr"}function uQ(e,t,a){let r=Mn(a,t);return!r||r.type==="element"&&(r.tagName==="td"||r.tagName==="th")}var cQ=KI({body:xwe,colgroup:Swe,head:bwe,html:ywe,tbody:wwe});function ywe(e){let t=Mn(e,-1);return!t||t.type!=="comment"}function bwe(e){let t=new Set;for(let r of e.children)if(r.type==="element"&&(r.tagName==="base"||r.tagName==="title")){if(t.has(r.tagName))return!1;t.add(r.tagName)}let a=e.children[0];return!a||a.type==="element"}function xwe(e){let t=Mn(e,-1,!0);return!t||t.type!=="comment"&&!(t.type==="text"&&up(t.value.charAt(0)))&&!(t.type==="element"&&(t.tagName==="meta"||t.tagName==="link"||t.tagName==="script"||t.tagName==="style"||t.tagName==="template"))}function Swe(e,t,a){let r=aU(a,t),n=Mn(e,-1,!0);return a&&r&&r.type==="element"&&r.tagName==="colgroup"&&xS(r,a.children.indexOf(r),a)?!1:!!(n&&n.type==="element"&&n.tagName==="col")}function wwe(e,t,a){let r=aU(a,t),n=Mn(e,-1);return a&&r&&r.type==="element"&&(r.tagName==="thead"||r.tagName==="tbody")&&xS(r,a.children.indexOf(r),a)?!1:!!(n&&n.type==="element"&&n.tagName==="tr")}var WI={name:[[`