friend-assistant 0.1.38 → 0.1.39
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.
|
@@ -62,8 +62,8 @@ some-mcp-server`})]}),(0,p.jsxs)(`label`,{className:`settings-field`,children:[(
|
|
|
62
62
|
|
|
63
63
|
`)}return o.write(`payload.value = newResult;`),o.write(`return payload;`),o.compile()},o,s=st,c=!rn.jitless,l=c&&ct.value,u=t.catchall,d;e._zod.parse=(i,f)=>{d??=r.value;let p=i.value;return s(p)?c&&l&&f?.async===!1&&f.jitless!==!0?(o||=a(t.shape),i=o(i,f),u?Pi([],p,i,f,d,e,f?.abortEarly===!0):i):n(i,f):(i.issues.push({expected:`object`,code:`invalid_type`,input:p,inst:e}),i)}});function Li(e,t,n,r){for(let n of e)if(n.issues.length===0)return t.value=n.value,t;let i=e.filter(e=>!Dt(e));return i.length===1?(t.value=i[0].value,i[0]):(t.issues.push({code:`invalid_union`,input:t.value,inst:n,errors:e.map(e=>e.issues.map(e=>Mt(e,r,an())))}),t)}var Ri=G(`$ZodUnion`,(e,t)=>{Pr.init(e,t),qt(e,`optin`,e=>e.def.options.some(e=>e._zod.optin===`defaulted`)?`defaulted`:e.def.options.some(e=>e._zod.optin!==void 0)?`optional`:void 0),qt(e,`optout`,e=>e.def.options.some(e=>e._zod.optout===`optional`)?`optional`:void 0),qt(e,`values`,e=>{if(e.def.options.every(e=>e._zod.values))return new Set(e.def.options.flatMap(e=>Array.from(e._zod.values)))}),qt(e,`pattern`,e=>{if(e.def.options.every(e=>e._zod.pattern)){let t=e.def.options.map(e=>e._zod.pattern);return RegExp(`^(${t.map(e=>Je(e.source)).join(`|`)})$`)}});let n=t.options.length===1?t.options[0]._zod.run:null;e._zod.parse=(r,i)=>{if(n)return n(r,i);let a=!1,o=[];for(let e of t.options){let t=e._zod.run({value:r.value,issues:[]},i);if(t instanceof Promise)o.push(t),a=!0;else{if(t.issues.length===0)return t;o.push(t)}}return a?Promise.all(o).then(t=>Li(t,r,e,i)):Li(o,r,e,i)}});function zi(e){let t=new Map;for(let n of e.options){let r=n._zod.propValues?.[e.discriminator];if(!r||r.size===0)throw Error(`Invalid discriminated union option at index "${e.options.indexOf(n)}"`);for(let e of r)if(t.has(e)){if(e!==void 0)throw Error(`Duplicate discriminator value "${String(e)}"`);t.set(e,null)}else t.set(e,n)}return t}var Bi=G(`$ZodDiscriminatedUnion`,(e,t)=>{t.inclusive=!1,Ri.init(e,t);let n=e._zod.parse;qt(e,`propValues`,e=>{let t={},n=0;for(let r of e.def.options){let i=r._zod.propValues;if(!i||Object.keys(i).length===0)throw Error(`Invalid discriminated union option at index "${e.def.options.indexOf(r)}"`);i[e.def.discriminator]?.has(void 0)&&n++;for(let[e,n]of Object.entries(i)){Object.prototype.hasOwnProperty.call(t,e)||Xe(t,e,new Set);for(let r of n)t[e].add(r)}}return!e.def.unionFallback&&n>1&&t[e.def.discriminator]?.delete(void 0),t}),t.options.forEach((e,n)=>{let r=Ze(e._zod.def);if(r&&!Object.prototype.hasOwnProperty.call(r,t.discriminator))throw Error(`Invalid discriminated union option at index "${n}"`)});let r=Ke(()=>zi(t));e._zod.parse=(i,a)=>{let o=i.value;if(!st(o))return i.issues.push({code:`invalid_type`,expected:`object`,input:o,inst:e}),i;let s=o?.[t.discriminator],c=r.value.get(s);return c&&(s!==void 0||a.direction!==`backward`)?c._zod.run(i,a):t.unionFallback||a.direction===`backward`?n(i,a):(i.issues.push({code:`invalid_union`,errors:[],note:`No matching discriminator`,discriminator:t.discriminator,options:Array.from(r.value.keys()).filter(e=>r.value.get(e)!==null),input:o,path:[t.discriminator],inst:e}),i)}}),Vi=G(`$ZodIntersection`,(e,t)=>{Pr.init(e,t),e._zod.parse=(e,n)=>{let r=e.value,i=t.left._zod.run({value:r,issues:[]},n),a=t.right._zod.run({value:r,issues:[]},n);return i instanceof Promise||a instanceof Promise?Promise.all([i,a]).then(([t,n])=>Ui(e,t,n)):Ui(e,i,a)}});function Hi(e,t){if(e===t||e instanceof Date&&t instanceof Date&&+e==+t)return{valid:!0,data:e};if(lt(e)&<(t)){let n=Object.keys(t),r=Object.keys(e).filter(e=>n.indexOf(e)!==-1),i={...e,...t};Object.prototype.hasOwnProperty.call(i,`__proto__`)&&delete i.__proto__;for(let n of r){if(n===`__proto__`)continue;let r=Hi(e[n],t[n]);if(!r.valid)return{valid:!1,mergeErrorPath:[n,...r.mergeErrorPath]};i[n]=r.data}return{valid:!0,data:i}}if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return{valid:!1,mergeErrorPath:[]};let n=[];for(let r=0;r<e.length;r++){let i=e[r],a=t[r],o=Hi(i,a);if(!o.valid)return{valid:!1,mergeErrorPath:[r,...o.mergeErrorPath]};n.push(o.data)}return{valid:!0,data:n}}return{valid:!1,mergeErrorPath:[]}}function Ui(e,t,n){let r=new Map,i,a=new Map,o=(e,t)=>{let n;if(e.code===`unrecognized_keys`&&!e.path?.length)i??=e,n=e.keys;else if(e.code===`invalid_key`&&e.origin===`record`&&e.path?.length===1){let t=String(e.path[0]);a.has(t)||a.set(t,e),n=[t]}else return!1;for(let e of n)r.has(e)||r.set(e,{}),r.get(e)[t]=!0;return!0};for(let n of t.issues)o(n,`l`)||e.issues.push(n);for(let t of n.issues)o(t,`r`)||e.issues.push(t);let s=[...r].filter(([,e])=>e.l&&e.r).map(([e])=>e);if(s.length){let t=i?s.filter(e=>i.keys.includes(e)):[];t.length&&e.issues.push({...i,keys:t});for(let n of s)!t.includes(n)&&a.has(n)&&e.issues.push(a.get(n))}let c=Hi(t.value,n.value);if(!c.valid){if(Dt(e))return e;throw Error(`Unmergable intersection. Error path: ${JSON.stringify(c.mergeErrorPath)}`)}return e.value=c.data,e}var Wi=G(`$ZodRecord`,(e,t)=>{Pr.init(e,t);let n=rn.memoizer;n?.attach(e),e._zod.parse=(r,i)=>{let a=r.value;if(!lt(a))return r.issues.push({expected:`record`,code:`invalid_type`,input:a,inst:e}),r;let o=[],s=t.keyType._zod.values;if(s&&!t.partial){r.value=n?n.alloc(e,r,{},i):{};let c=new Set;for(let n of s)if(typeof n==`string`||typeof n==`number`||typeof n==`symbol`){if(c.add(typeof n==`number`?n.toString():n),n===`__proto__`)continue;let s=t.keyType._zod.run({value:n,issues:[]},i);if(s instanceof Promise)throw Error(`Async schemas not supported in object keys currently`);if(s.issues.length){r.issues.push({code:`invalid_key`,origin:`record`,issues:s.issues.map(e=>Mt(e,i,an())),input:n,path:[n],inst:e});continue}let l=s.value;if(l===`__proto__`)continue;let u=t.valueType._zod.run({value:a[n],issues:[]},i);u instanceof Promise?o.push(u.then(e=>{e.issues.length&&r.issues.push(...kt(n,e.issues)),r.value[l]=e.value})):(u.issues.length&&r.issues.push(...kt(n,u.issues)),r.value[l]=u.value)}let l;for(let e in a)if(!c.has(e)){if(t.mode===`loose`){if(e===`__proto__`)continue;r.value[e]=a[e]}else l??=[],l.push(e)}l&&l.length>0&&r.issues.push({code:`unrecognized_keys`,input:a,inst:e,keys:l,continue:!0})}else{r.value=n?n.alloc(e,r,{},i):{};let c;for(let n of Reflect.ownKeys(a)){if(n===`__proto__`||!Object.prototype.propertyIsEnumerable.call(a,n))continue;let l=t.keyType._zod.run({value:n,issues:[]},i);if(l instanceof Promise)throw Error(`Async schemas not supported in object keys currently`);if(typeof n==`string`&&ur.test(n)&&l.issues.length){let e=t.keyType._zod.run({value:Number(n),issues:[]},i);if(e instanceof Promise)throw Error(`Async schemas not supported in object keys currently`);e.issues.length===0&&(l=e)}if(l.issues.length){t.mode===`loose`?r.value[n]=a[n]:s?(c??=[],c.push(n)):r.issues.push({code:`invalid_key`,origin:`record`,issues:l.issues.map(e=>Mt(e,i,an())),input:n,path:[n],inst:e});continue}let u=l.value;if(u===`__proto__`)continue;let d=t.valueType._zod.run({value:a[n],issues:[]},i);d instanceof Promise?o.push(d.then(e=>{e.issues.length&&r.issues.push(...kt(n,e.issues)),r.value[u]=e.value})):(d.issues.length&&r.issues.push(...kt(n,d.issues)),r.value[u]=d.value)}c&&c.length>0&&r.issues.push({code:`unrecognized_keys`,input:a,inst:e,keys:c,continue:!0})}return o.length?Promise.all(o).then(()=>r):r}}),Gi=G(`$ZodEnum`,(e,t)=>{Pr.init(e,t);let n=He(t.entries),r=new Set(n);e._zod.values=r,qt(e,`pattern`,e=>{let t=He(e.def.entries).filter(e=>dt.has(typeof e));return RegExp(t.length?`^(${t.map(e=>ft(e.toString())).join(`|`)})$`:`^[^\\s\\S]$`)}),e._zod.parse=(t,i)=>{let a=t.value;return r.has(a)||t.issues.push({code:`invalid_value`,values:n,input:a,inst:e}),t}}),Ki=G(`$ZodLiteral`,(e,t)=>{Pr.init(e,t);let n=new Set(t.values);e._zod.values=n,qt(e,`pattern`,e=>{let t=e.def.values;return RegExp(t.length?`^(${t.map(e=>typeof e==`string`?ft(e):e?ft(e.toString()):String(e)).join(`|`)})$`:`^[^\\s\\S]$`)}),e._zod.parse=(r,i)=>{let a=r.value;return n.has(a)||r.issues.push({code:`invalid_value`,values:t.values,input:a,inst:e}),r}}),qi=G(`$ZodTransform`,(e,t)=>{Pr.init(e,t),e._zod.optin=`optional`,rn.memoizer?.guard(e),e._zod.parse=(n,r)=>{if(r.direction===`backward`)throw new nn(e.constructor.name);let i=t.transform(n.value,n);if(r.async)return(i instanceof Promise?i:Promise.resolve(i)).then(e=>(n.value=e,n));if(i instanceof Promise)throw new tn;return n.value=i,n}});function Ji(e,t){return e.value=t.issues.length?void 0:t.value,e}var Yi=G(`$ZodOptional`,(e,t)=>{Pr.init(e,t),qt(e,`optin`,e=>e.def.innerType._zod.optin===`defaulted`?`defaulted`:`optional`),e._zod.optout=`optional`,qt(e,`values`,e=>{let t=e.def.innerType._zod.values;return t?new Set([...t,void 0]):void 0}),qt(e,`pattern`,e=>{let t=e.def.innerType._zod.pattern;return t?RegExp(`^(${Je(t.source)})?$`):void 0}),e._zod.parse=(e,n)=>{if(e.value===void 0){if(t.innerType._zod.optin!==`defaulted`)return e;let r=t.innerType._zod.run({value:e.value,issues:[]},n);return r instanceof Promise?r.then(t=>Ji(e,t)):Ji(e,r)}return t.innerType._zod.run(e,n)}}),Xi=G(`$ZodExactOptional`,(e,t)=>{Yi.init(e,t),qt(e,`values`,e=>e.def.innerType._zod.values),qt(e,`pattern`,e=>e.def.innerType._zod.pattern),e._zod.parse=(e,n)=>t.innerType._zod.run(e,n)}),Zi=G(`$ZodNullable`,(e,t)=>{Pr.init(e,t),qt(e,`optin`,e=>e.def.innerType._zod.optin),qt(e,`optout`,e=>e.def.innerType._zod.optout),qt(e,`pattern`,e=>{let t=e.def.innerType._zod.pattern;return t?RegExp(`^(${Je(t.source)}|null)$`):void 0}),qt(e,`values`,e=>e.def.innerType._zod.values?new Set([...e.def.innerType._zod.values,null]):void 0),e._zod.parse=(e,n)=>e.value===null?e:t.innerType._zod.run(e,n)}),Qi=G(`$ZodDefault`,(e,t)=>{Pr.init(e,t),e._zod.optin=`defaulted`,qt(e,`values`,e=>e.def.innerType._zod.values),e._zod.parse=(e,n)=>{if(n.direction===`backward`)return t.innerType._zod.run(e,n);if(e.value===void 0)return e.value=t.defaultValue,e;let r=t.innerType._zod.run(e,n);return r instanceof Promise?r.then(e=>$i(e,t)):$i(r,t)}});function $i(e,t){return e.value===void 0&&(e.value=t.defaultValue),e}var ea=G(`$ZodPrefault`,(e,t)=>{Pr.init(e,t),e._zod.optin=`defaulted`,qt(e,`values`,e=>e.def.innerType._zod.values),e._zod.parse=(e,n)=>(n.direction===`backward`||e.value===void 0&&(e.value=t.defaultValue),t.innerType._zod.run(e,n))}),ta=G(`$ZodNonOptional`,(e,t)=>{Pr.init(e,t),qt(e,`values`,e=>{let t=e.def.innerType._zod.values;return t?new Set([...t].filter(e=>e!==void 0)):void 0}),e._zod.parse=(n,r)=>{let i=t.innerType._zod.run(n,r);return i instanceof Promise?i.then(t=>na(t,e)):na(i,e)}});function na(e,t){return!e.issues.length&&e.value===void 0&&e.issues.push({code:`invalid_type`,expected:`nonoptional`,input:e.value,inst:t}),e}function ra(e,t,n,r){return t.issues.length?(e.value=n.catchValue({...t,value:e.value,error:{issues:t.issues.map(e=>Mt(e,r,an()))},input:e.value}),e):(e.value=t.value,t.memo&&(e.memo=!0),e)}var ia=G(`$ZodCatch`,(e,t)=>{Pr.init(e,t),qt(e,`optin`,e=>e.def.innerType._zod.optin===`defaulted`?`defaulted`:`optional`),qt(e,`optout`,e=>e.def.innerType._zod.optout),qt(e,`values`,e=>e.def.innerType._zod.values),e._zod.parse=(e,n)=>{if(n.direction===`backward`)return t.innerType._zod.run(e,n);let r=t.innerType._zod.run({value:e.value,issues:[]},n);return r instanceof Promise?r.then(r=>ra(e,r,t,n)):ra(e,r,t,n)}}),aa=G(`$ZodPipe`,(e,t)=>{Pr.init(e,t),qt(e,`values`,e=>e.def.in._zod.values),qt(e,`optin`,e=>e.def.in._zod.optin),qt(e,`optout`,e=>e.def.out._zod.optout),qt(e,`propValues`,e=>e.def.in._zod.propValues),e._zod.parse=(e,n)=>{if(n.direction===`backward`){let r=t.out._zod.run(e,n);return r instanceof Promise?r.then(e=>oa(e,t.in,n)):oa(r,t.in,n)}let r=t.in._zod.run(e,n);return r instanceof Promise?r.then(e=>oa(e,t.out,n)):oa(r,t.out,n)}});function oa(e,t,n){return e.issues.some(e=>e.code!==`unrecognized_keys`)?(e.aborted=!0,e):t._zod.run({value:e.value,issues:e.issues},n)}var sa=G(`$ZodReadonly`,(e,t)=>{Pr.init(e,t),qt(e,`propValues`,e=>e.def.innerType._zod.propValues),qt(e,`values`,e=>e.def.innerType._zod.values),qt(e,`optin`,e=>e.def.innerType?._zod?.optin),qt(e,`optout`,e=>e.def.innerType?._zod?.optout),e._zod.parse=(e,n)=>{if(n.direction===`backward`)return t.innerType._zod.run(e,n);let r=t.innerType._zod.run(e,n);return r instanceof Promise?r.then(ca):ca(r)}});function ca(e){return e.memo||(e.value=Object.freeze(e.value)),e}var la=G(`$ZodCustom`,(e,t)=>{mr.init(e,t),Pr.init(e,t),e._zod.parse=(e,t)=>e,e._zod.check=n=>{let r=n.value,i=t.fn(r);if(i instanceof Promise)return i.then(t=>ua(t,n,r,e));ua(i,n,r,e)}});function ua(e,t,n,r){if(!e){let e={code:`custom`,input:n,inst:r,path:[...r._zod.def.path??[]],continue:!r._zod.def.abort};r._zod.def.params&&(e.params=r._zod.def.params),t.issues.push(Lt(e))}}var da=class extends Error{constructor(){super(`Cannot parse a reference cycle that closes through a transform`),this.name=`ZodCyclicError`}},fa=`~memo`,pa=[];function ma(e){return typeof e==`object`&&!!e}function ha(e){return e.map(e=>e.path?{...e,path:e.path.slice()}:{...e})}var ga=new WeakMap,_a=0,va=1,ya=2;function ba(e,t,n){let r=ga.get(e);if(r!==void 0)return r?ya:_a;if(t.has(e))return ya;t.add(e);let i=_a,a=e=>{if(i!==ya&&e?._zod){let r=ba(e,t,n);r>i&&(i=r)}},o=(e,r)=>{let i=_a;for(let a of Reflect.ownKeys(e)){let o=Object.getOwnPropertyDescriptor(e,a);if(r&&!o.enumerable)continue;let s=o.get?va:o.value?._zod?ba(o.value,t,n):_a;s>i&&(i=s)}return i},s=e=>{e>i&&(i=e)},c=e._zod.def;switch(c.type){case`object`:{let e=Ze(c);s(e?o(e,!0):va),a(c.catchall);break}case`array`:a(c.element);break;case`tuple`:for(let e of c.items)a(e);a(c.rest);break;case`record`:case`map`:a(c.keyType),a(c.valueType);break;case`set`:a(c.valueType);break;case`union`:for(let e of c.options)a(e);break;case`intersection`:a(c.left),a(c.right);break;case`optional`:case`nullable`:case`default`:case`prefault`:case`catch`:case`readonly`:case`nonoptional`:case`promise`:case`success`:a(c.innerType);break;case`pipe`:a(c.in),a(c.out);break;case`function`:a(c.input),a(c.output);break;case`lazy`:{let r=c._cachedInner??(n?e._zod.innerType:void 0);s(r?ba(r,t,!1):va);break}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`:break;default:for(let e in c){let t=Object.getOwnPropertyDescriptor(c,e);if(!t||t.get)continue;let n=t.value;if(n&&typeof n==`object`){if(n._zod)a(n);else if(Array.isArray(n))for(let e of n)a(e)}}}return t.delete(e),xa(e,i)}function xa(e,t){return t!==va&&ga.set(e,t===ya),t}function Sa(e,t){let n=e.buckets.get(t);return n||(n=new WeakMap,e.buckets.set(t,n)),n}var Ca,wa=[],Ta={alloc(e,t,n){let r=Ca;if(!r)return n;Ca=void 0;let i={value:n,issues:null};return r.set(t.value,i),wa.push(i),n},guard(e){var t;(t=e._zod).deferred??(t.deferred=[]),e._zod.deferred.push(()=>{let t=e._zod.parse,n=(e,n)=>{if(n.direction!==`backward`&&Da(n,e.value))throw new da;return t(e,n)};e._zod.parse=n,e._zod.run===t&&(e._zod.run=n)})},attach(e){var t;let n,r=!1,i,a;(t=e._zod).deferred??(t.deferred=[]),e._zod.deferred.push(()=>{let t=e._zod.parse,o=(s,c)=>{if(n===void 0){let i=ba(e,new Set,!1);if(i===_a)return e._zod.parse=t,e._zod.run===o&&(e._zod.run=t),t(s,c);i===ya||r?n=!0:r=!0}let l=s.value;if(!ma(l))return t(s,c);let u=c[fa];u||(u={buckets:new WeakMap,backEdges:void 0},c[fa]=u);let d;i===c?d=a:(d=Sa(u,e),i=c,a=d);let f=d.get(l);if(f)return s.value=f.value,f.issues?f.issues.length&&s.issues.push(...ha(f.issues)):(s.memo=!0,u.backEdges??(u.backEdges=new WeakSet),u.backEdges.add(f.value)),s;Ca=d;let p=wa.length,m=t(s,c);Ca=void 0;let h=wa.length>p?wa.pop():void 0;return m instanceof Promise?m.then(e=>(h&&(h.issues=e.issues.length?ha(e.issues):pa),e)):(h&&(h.issues=m.issues.length?ha(m.issues):pa),m)};e._zod.parse=o,e._zod.run===t&&(e._zod.run=o)})}};function Ea(){return Ta}function Da(e,t){let n=e[fa]?.backEdges;return n!==void 0&&ma(t)&&n.has(t)}var Oa=()=>{let e={string:{unit:`characters`,verb:`to have`},file:{unit:`bytes`,verb:`to have`},array:{unit:`items`,verb:`to have`},set:{unit:`items`,verb:`to have`},map:{unit:`entries`,verb:`to have`}};function t(t){return e[t]??null}let n={regex:`input`,email:`email address`,url:`URL`,emoji:`emoji`,uuid:`UUID`,uuidv4:`UUIDv4`,uuidv6:`UUIDv6`,nanoid:`nanoid`,guid:`GUID`,cuid:`cuid`,cuid2:`cuid2`,ulid:`ULID`,xid:`XID`,ksuid:`KSUID`,datetime:`ISO datetime`,date:`ISO date`,time:`ISO time`,duration:`ISO duration`,ipv4:`IPv4 address`,ipv6:`IPv6 address`,mac:`MAC address`,cidrv4:`IPv4 range`,cidrv6:`IPv6 range`,base64:`base64-encoded string`,base64url:`base64url-encoded string`,json_string:`JSON string`,e164:`E.164 number`,currency_code:`currency code`,credit_card:`credit card number`,iban:`IBAN`,jwt:`JWT`,template_literal:`input`},r={nan:`NaN`};function i(e,t){return e===`number`&&typeof t==`number`&&!Number.isFinite(t)?String(t):r[e]??e}return e=>{switch(e.code){case`invalid_type`:return`Invalid input: expected ${i(e.expected)}, received ${i(It(e.input),e.input)}`;case`invalid_value`:return e.values.length===1?`Invalid input: expected ${mt(e.values[0])}`:`Invalid option: expected one of ${Ue(e.values,`|`)}`;case`too_big`:{let n=e.exact?`exactly `:e.inclusive?`<=`:`<`,r=t(e.origin);return r?`Too big: expected ${e.origin??`value`} to have ${n}${e.maximum.toString()} ${r.unit??`elements`}`:`Too big: expected ${e.origin??`value`} to be ${n}${e.maximum.toString()}`}case`too_small`:{let n=e.exact?`exactly `:e.inclusive?`>=`:`>`,r=t(e.origin);return r?`Too small: expected ${e.origin} to have ${n}${e.minimum.toString()} ${r.unit}`:`Too small: expected ${e.origin} to be ${n}${e.minimum.toString()}`}case`invalid_format`:{let t=e;return t.format===`starts_with`?`Invalid string: must start with "${t.prefix}"`:t.format===`ends_with`?`Invalid string: must end with "${t.suffix}"`:t.format===`includes`?`Invalid string: must include "${t.includes}"`:t.format===`regex`?`Invalid string: must match pattern ${t.pattern}`:`Invalid ${n[t.format]??e.format}`}case`not_multiple_of`:return`Invalid number: must be a multiple of ${e.divisor}`;case`unrecognized_keys`:return`Unrecognized key${e.keys.length>1?`s`:``}: ${Ue(e.keys,`, `)}`;case`invalid_key`:return`Invalid key in ${e.origin}`;case`invalid_union`:return e.options&&Array.isArray(e.options)&&e.options.length>0?`Invalid discriminator value. Expected ${e.options.map(e=>`'${e}'`).join(` | `)}`:e.inclusive===!1?`Invalid input: more than one option matched`:`Invalid input`;case`invalid_element`:return`Invalid value in ${e.origin}`;default:return`Invalid input`}}};function ka(){return{localeError:Oa()}}var Aa,ja=class{constructor(){this._map=new WeakMap,this._idmap=new Map}add(e,...t){let n=t[0];return this._map.set(e,n),n&&typeof n==`object`&&`id`in n&&this._idmap.set(n.id,e),this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove(e){let t=this._map.get(e);return t&&typeof t==`object`&&`id`in t&&this._idmap.delete(t.id),this._map.delete(e),this}get(e){let t=e._zod.parent;if(t){let n={...this.get(t)??{}};delete n.id;let r={...n,...this._map.get(e)};return Object.keys(r).length?r:void 0}return this._map.get(e)}has(e){return this._map.has(e)}};function Ma(){return new ja}(Aa=globalThis).__zod_globalRegistry??(Aa.__zod_globalRegistry=Ma());var Na=globalThis.__zod_globalRegistry;function Pa(e){return e.checks&&=[...e.checks],e}function Fa(e,t){return new e(Pa({type:`string`,...W(t)}))}function Ia(e,t){return new e({type:`string`,format:`email`,check:`string_format`,abort:!1,...W(t)})}function La(e,t){return new e({type:`string`,format:`guid`,check:`string_format`,abort:!1,...W(t)})}function Ra(e,t){return new e({type:`string`,format:`uuid`,check:`string_format`,abort:!1,...W(t)})}function za(e,t){return new e({type:`string`,format:`uuid`,check:`string_format`,abort:!1,version:`v4`,...W(t)})}function Ba(e,t){return new e({type:`string`,format:`uuid`,check:`string_format`,abort:!1,version:`v6`,...W(t)})}function Va(e,t){return new e({type:`string`,format:`uuid`,check:`string_format`,abort:!1,version:`v7`,...W(t)})}function Ha(e,t){return new e({type:`string`,format:`url`,check:`string_format`,abort:!1,...W(t)})}function Ua(e,t){return new e({type:`string`,format:`emoji`,check:`string_format`,abort:!1,...W(t)})}function Wa(e,t){return new e({type:`string`,format:`nanoid`,check:`string_format`,abort:!1,...W(t)})}function Ga(e,t){return new e({type:`string`,format:`cuid`,check:`string_format`,abort:!1,...W(t)})}function Ka(e,t){return new e({type:`string`,format:`cuid2`,check:`string_format`,abort:!1,...W(t)})}function qa(e,t){return new e({type:`string`,format:`ulid`,check:`string_format`,abort:!1,...W(t)})}function Ja(e,t){return new e({type:`string`,format:`xid`,check:`string_format`,abort:!1,...W(t)})}function Ya(e,t){return new e({type:`string`,format:`ksuid`,check:`string_format`,abort:!1,...W(t)})}function Xa(e,t){return new e({type:`string`,format:`ipv4`,check:`string_format`,abort:!1,...W(t)})}function Za(e,t){return new e({type:`string`,format:`ipv6`,check:`string_format`,abort:!1,...W(t)})}function Qa(e,t){return new e({type:`string`,format:`cidrv4`,check:`string_format`,abort:!1,...W(t)})}function $a(e,t){return new e({type:`string`,format:`cidrv6`,check:`string_format`,abort:!1,...W(t)})}function eo(e,t){return new e({type:`string`,format:`base64`,check:`string_format`,abort:!1,...W(t)})}function to(e,t){return new e({type:`string`,format:`base64url`,check:`string_format`,abort:!1,...W(t)})}function no(e,t){return new e({type:`string`,format:`e164`,check:`string_format`,abort:!1,...W(t)})}function ro(e,t){return new e({type:`string`,format:`jwt`,check:`string_format`,abort:!1,...W(t)})}function io(e,t){return new e({type:`string`,format:`datetime`,check:`string_format`,offset:!1,local:!1,precision:null,...W(t)})}function ao(e,t){return new e({type:`string`,format:`date`,check:`string_format`,...W(t)})}function oo(e,t){return new e({type:`string`,format:`time`,check:`string_format`,precision:null,...W(t)})}function so(e,t){return new e({type:`string`,format:`duration`,check:`string_format`,...W(t)})}function co(e,t){return new e(Pa({type:`number`,checks:[],...W(t)}))}function lo(e,t){return new e({type:`number`,check:`number_format`,abort:!1,format:`safeint`,...W(t)})}function uo(e,t){return new e({type:`boolean`,...W(t)})}function fo(e){return new e({type:`unknown`})}function po(e,t){return new e({type:`never`,...W(t)})}function mo(e,t){return new _r({check:`less_than`,...W(t),value:e,inclusive:!1})}function ho(e,t){return new _r({check:`less_than`,...W(t),value:e,inclusive:!0})}function go(e,t){return new vr({check:`greater_than`,...W(t),value:e,inclusive:!1})}function _o(e,t){return new vr({check:`greater_than`,...W(t),value:e,inclusive:!0})}function vo(e,t){return new yr({check:`multiple_of`,...W(t),value:e})}function yo(e,t){return new xr({check:`max_length`,...W(t),maximum:e})}function bo(e,t){return new Sr({check:`min_length`,...W(t),minimum:e})}function xo(e,t){return new Cr({check:`length_equals`,...W(t),length:e})}function So(e,t){return new Tr({check:`string_format`,format:`regex`,...W(t),pattern:e})}function Co(e){return new Er({check:`string_format`,format:`lowercase`,...W(e)})}function wo(e){return new Dr({check:`string_format`,format:`uppercase`,...W(e)})}function To(e,t){return new Or({check:`string_format`,format:`includes`,...W(t),includes:e})}function Eo(e,t){return new kr({check:`string_format`,format:`starts_with`,...W(t),prefix:e})}function Do(e,t){return new Ar({check:`string_format`,format:`ends_with`,...W(t),suffix:e})}function Oo(e){return new jr({check:`overwrite`,tx:e})}function ko(e){return Oo(t=>t.normalize(e))}function Ao(){return Oo(e=>e.trim())}function jo(){return Oo(e=>e.toLowerCase())}function Mo(){return Oo(e=>e.toUpperCase())}function No(){return Oo(e=>at(e))}function Po(e,t,n){return new e({type:`array`,element:t,...W(n)})}function Fo(e,t,n){return new e({type:`custom`,check:`custom`,fn:t,...W(n)})}function Io(e,t){let n=Lo(t=>(t.addIssue=e=>{if(typeof e==`string`)t.issues.push(Lt(e,t.value,n._zod.def));else{let r=e;r.fatal&&(r.continue=!1),r.code??=`custom`,`input`in r||(r.input=t.value),r.inst??=n,r.continue??=!n._zod.def.abort,t.issues.push(Lt(r))}},e(t.value,t)),t);return n}function Lo(e,t){let n=new mr({check:`custom`,...W(t)});return n._zod.check=e,n}function Ro(e,...t){for(let n of t)for(let t of Reflect.ownKeys(n))Object.prototype.propertyIsEnumerable.call(n,t)&&Xe(e,t,n[t]);return e}function zo(e){let t=e?.target??`draft-2020-12`;return t===`draft-4`&&(t=`draft-04`),t===`draft-7`&&(t=`draft-07`),{processors:e.processors??{},metadataRegistry:e?.metadata??Na,target:t,unrepresentable:e?.unrepresentable??`throw`,override:e?.override??(()=>{}),io:e?.io??`output`,counter:0,seen:new Map,sharedDefsExtractedFor:void 0,sharedEmitDoneFor:void 0,cycles:e?.cycles??`ref`,reused:e?.reused??`inline`,intersections:[],deferred:[],external:e?.external??void 0}}function Bo(e,t,n,r,i){let a=typeof t.unrepresentable==`function`?t.unrepresentable({zodSchema:e,path:r.path,message:i}):t.unrepresentable;if(a===`any`)return!1;if(a===void 0||a===`throw`)throw Error(i);return Object.assign(n,a),!0}function Vo(e,t,n={path:[],schemaPath:[]}){var r;let i=e._zod.def,a=t.seen.get(e);if(a)return a.count++,n.schemaPath.includes(e)&&(a.cycle=n.path),a.schema;let o={schema:{},count:1,cycle:void 0,path:n.path};t.seen.set(e,o),t.sharedDefsExtractedFor=void 0,t.sharedEmitDoneFor=void 0;let s=e._zod.toJSONSchema?.();if(s)o.schema=s;else{let r={...n,schemaPath:[...n.schemaPath,e],path:n.path};if(e._zod.processJSONSchema)e._zod.processJSONSchema(t,o.schema,r);else{let n=o.schema,a=t.processors[i.type];if(!a)throw Error(`[toJSONSchema]: Non-representable type encountered: ${i.type}`);a(e,t,n,r)}let a=e._zod.parent;a&&(o.ref||=a,Vo(a,t,r),t.seen.get(a).isParent=!0)}let c=t.metadataRegistry.get(e);return c&&Ro(o.schema,c),t.io===`input`&&Zo(e)&&(delete o.schema.examples,delete o.schema.default),t.io===`input`&&`_prefault`in o.schema&&((r=o.schema).default??(r.default=o.schema._prefault)),delete o.schema._prefault,t.seen.get(e).schema}function Ho(e){return e.replace(/~/g,`~0`).replace(/\//g,`~1`)}function Uo(e,t){let n=e.seen.get(t);if(!n)throw Error(`Unprocessed schema. This is a bug in Zod.`);if(e.external&&e.sharedDefsExtractedFor===e.external)return;let r=new Map;for(let t of e.seen.entries()){let n=e.metadataRegistry.get(t[0])?.id;if(n){let e=r.get(n);if(e&&e!==t[0])throw Error(`Duplicate schema id "${n}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);r.set(n,t[0])}}let i=t=>{let r=e.target===`draft-2020-12`?`$defs`:`definitions`;if(e.external){let n=e.external.registry.get(t[0])?.id,i=e.external.uri??(e=>e);if(n)return{ref:i(n)};let a=t[1].defId??t[1].schema.id??`schema${e.counter++}`;return t[1].defId=a,{defId:a,ref:`${i(`__shared`)}#/${r}/${Ho(a)}`}}let i=`#/${r}/`;if(t[1]===n&&!t[1].schema.id)return{ref:`#`};let a=t[1].schema.id??`__schema${e.counter++}`;return{defId:a,ref:i+Ho(a)}},a=e=>{if(e[1].schema.$ref)return;let t=e[1],{ref:n,defId:r}=i(e);t.def={...t.schema},r&&(t.defId=r);let a=t.schema;for(let e in a)delete a[e];a.$ref=n};if(e.cycles===`throw`)for(let t of e.seen.entries()){let e=t[1];if(e.cycle)throw Error(`Cycle detected: #/${e.cycle?.join(`/`)}/<root>
|
|
64
64
|
|
|
65
|
-
Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let n of e.seen.entries()){let r=n[1];if(t===n[0]){a(n);continue}if(e.external){let r=e.external.registry.get(n[0])?.id;if(t!==n[0]&&r){a(n);continue}}if(e.metadataRegistry.get(n[0])?.id){a(n);continue}if(r.cycle){a(n);continue}r.count>1&&e.reused===`ref`&&a(n)}e.external&&(e.sharedDefsExtractedFor=e.external)}function Wo(e){let t=e.anyOf;if(!Array.isArray(t)||t.length===0||e.type!==void 0)return;let n=[];for(let e of t){if(!e||typeof e!=`object`)return;Wo(e);let t=Object.keys(e);if(t.length!==1||t[0]!==`type`)return;let r=e.type;for(let e of Array.isArray(r)?r:[r]){if(typeof e!=`string`)return;n.includes(e)||n.push(e)}}delete e.anyOf,e.type=n.length===1?n[0]:n}var Go=new Set([`type`,`properties`,`required`,`additionalProperties`]),Ko=[`oneOf`,`anyOf`];function qo(e){let t=e.additionalProperties;return t===void 0||t===!1||typeof t!=`object`||!t?null:Object.keys(t).length?t:null}function Jo(e){let t=[];for(let n of e){if(typeof n!=`object`||n.type!==`object`)return null;for(let e in n)if(!Go.has(e))return null;t.push(n)}let n={},r=new Set;for(let e of t){for(let r in e.properties){if(Object.prototype.hasOwnProperty.call(n,r))continue;let e=[];for(let n of t){let t=n.properties?.[r]??qo(n);t!=null&&(e.some(e=>JSON.stringify(e)===JSON.stringify(t))||e.push(t))}Xe(n,r,e.length===1?e[0]:Jo(e)??{allOf:e})}for(let t of e.required??[])r.add(t)}let i={type:`object`,properties:n};if(r.size&&(i.required=[...r]),t.every(e=>e.additionalProperties===!1))i.additionalProperties=!1;else{let e=[];for(let n of t){let t=qo(n);t&&!e.some(e=>JSON.stringify(e)===JSON.stringify(t))&&e.push(t)}e.length===1?i.additionalProperties=e[0]:e.length>1&&(i.additionalProperties={allOf:e})}return i}function Yo(e){let t=e.allOf;if(!Array.isArray(t)||t.length<2)return;for(let t of Go)if(t in e)return;let n=t.filter(e=>Ko.some(t=>Array.isArray(e[t]))),r=null;if(!n.length)r=Jo(t);else{let e=n[0],i=Ko.find(t=>Array.isArray(e[t]));if(Object.keys(e).length!==1)return;let a=t.filter(t=>t!==e),o=e[i].map(e=>Jo([...a,e]));if(o.some(e=>!e))return;r={[i]:o}}r&&(delete e.allOf,Ro(e,r))}function Xo(e,t){let n=e.seen.get(t);if(!n)throw Error(`Unprocessed schema. This is a bug in Zod.`);let r=t=>{let n=e.seen.get(t);if(n.ref===null)return;let i=n.def??n.schema,a={...i},o=n.ref;if(n.ref=null,o){r(o);let n=e.seen.get(o),s=n.schema;if(s.$ref&&(e.target===`draft-07`||e.target===`draft-04`||e.target===`openapi-3.0`)?(i.allOf=i.allOf??[],i.allOf.push(s)):Ro(i,s),Ro(i,a),t._zod.parent===o)for(let e in i)e!==`$ref`&&e!==`allOf`&&(e in a||delete i[e]);if(s.$ref&&n.def)for(let e in i)e!==`$ref`&&e!==`allOf`&&e in n.def&&JSON.stringify(i[e])===JSON.stringify(n.def[e])&&delete i[e]}let s=t._zod.parent;if(s&&s!==o){r(s);let t=e.seen.get(s);if(t?.schema.$ref&&(i.$ref=t.schema.$ref,t.def))for(let e in i)e!==`$ref`&&e!==`allOf`&&e in t.def&&JSON.stringify(i[e])===JSON.stringify(t.def[e])&&delete i[e]}e.override({zodSchema:t,jsonSchema:i,path:n.path??[]})};if(!e.external||e.sharedEmitDoneFor!==e.external){for(let t of[...e.seen.entries()].reverse())r(t[0]);if(e.target!==`openapi-3.0`)for(let t of e.seen.entries())Wo(t[1].def??t[1].schema);for(let t of e.deferred)t();if(e.intersections.length){let t=new Map;for(let n of e.seen.values())for(let e of[n.schema,n.def]){let n=e?.allOf;if(!Array.isArray(n))continue;let r=t.get(n);r?r.push(e):t.set(n,[e])}for(let n of e.intersections)for(let e of t.get(n)??[])Yo(e)}}let i={};if(e.target===`draft-2020-12`?i.$schema=`https://json-schema.org/draft/2020-12/schema`:e.target===`draft-07`?i.$schema=`http://json-schema.org/draft-07/schema#`:e.target===`draft-04`?i.$schema=`http://json-schema.org/draft-04/schema#`:e.target,e.external?.uri){let n=e.external.registry.get(t)?.id;if(!n)throw Error("Schema is missing an `id` property");i.$id=e.external.uri(n)}Ro(i,n.defId?n.schema:n.def??n.schema);let a=e.metadataRegistry.get(t)?.id;a!==void 0&&i.id===a&&delete i.id;let o=e.external?.defs??{};if(!e.external||e.sharedEmitDoneFor!==e.external)for(let t of e.seen.entries()){let e=t[1];e.def&&e.defId&&(e.def.id===e.defId&&delete e.def.id,Xe(o,e.defId,e.def))}e.external&&(e.sharedEmitDoneFor=e.external),e.external||Object.keys(o).length>0&&(e.target===`draft-2020-12`?i.$defs=o:i.definitions=o);try{let n=JSON.parse(JSON.stringify(i));return Object.defineProperty(n,"~standard",{value:{...t[`~standard`],jsonSchema:{input:$o(t,`input`,e.processors),output:$o(t,`output`,e.processors)}},enumerable:!1,writable:!1}),n}catch{throw Error(`Error converting schema to JSON.`)}}function Zo(e,t){let n=t??{seen:new Set};if(n.seen.has(e))return!1;n.seen.add(e);let r=e._zod.def;if(r.type===`transform`)return!0;if(r.type===`array`)return Zo(r.element,n);if(r.type===`set`)return Zo(r.valueType,n);if(r.type===`lazy`)return Zo(r.getter(),n);if(r.type===`promise`||r.type===`optional`||r.type===`nonoptional`||r.type===`nullable`||r.type===`readonly`||r.type==="default"||r.type===`prefault`||r.type===`catch`)return Zo(r.innerType,n);if(r.type===`intersection`)return Zo(r.left,n)||Zo(r.right,n);if(r.type===`record`||r.type===`map`)return Zo(r.keyType,n)||Zo(r.valueType,n);if(r.type===`pipe`)return e._zod.traits.has(`$ZodCodec`)?!0:Zo(r.in,n)||Zo(r.out,n);if(r.type===`object`){for(let e in r.shape)if(Zo(r.shape[e],n))return!0;return!1}if(r.type===`union`){for(let e of r.options)if(Zo(e,n))return!0;return!1}if(r.type===`tuple`){for(let e of r.items)if(Zo(e,n))return!0;return!!(r.rest&&Zo(r.rest,n))}return!1}var Qo=(e,t={})=>n=>{let r=zo({...n,processors:t});return Vo(e,r),Uo(r,e),Xo(r,e)},$o=(e,t,n={})=>r=>{let{libraryOptions:i,target:a}=r??{},o=zo({...i??{},target:a,io:t,processors:n});return Vo(e,o),Uo(o,e),Xo(o,e)},es=(e,t,n)=>{(e[t]===void 0||n>e[t])&&(e[t]=n)},ts=(e,t,n)=>{(e[t]===void 0||n<e[t])&&(e[t]=n)},ns=(e,t)=>{es(e,`minimum`,t),ts(e,`maximum`,t)},rs=(e,t)=>{e.multipleOf??=[],e.multipleOf.includes(t)||e.multipleOf.push(t)},is=(e,t)=>{e.patterns??=new Set,e.patterns.add(t)},as=(e,t)=>{e.mime=e.mime?e.mime.filter(e=>t.includes(e)):[...t]},os=(e,t)=>{e.format=t,t.includes(`int`)&&(e.isInt=!0)},ss=(e,t)=>es(e,`minimum`,t.minimum),cs=(e,t)=>ts(e,`maximum`,t.maximum),ls=e=>(t,n)=>{os(t,n.format);let[r,i]=e[n.format];es(t,`minimum`,r),ts(t,`maximum`,i)},us={greater_than:(e,t)=>es(e,t.inclusive?`minimum`:`exclusiveMinimum`,t.value),less_than:(e,t)=>ts(e,t.inclusive?`maximum`:`exclusiveMaximum`,t.value),multiple_of:(e,t)=>rs(e,t.value),number_format:ls(gt),bigint_format:ls(_t),min_length:ss,max_length:cs,length_equals:(e,t)=>ns(e,t.length),min_size:ss,max_size:cs,size_equals:(e,t)=>ns(e,t.size),string_format:(e,t)=>{os(e,t.format),t.pattern&&is(e,t.pattern),(t.format===`base64`||t.format===`base64url`)&&(e.contentEncoding=t.format),(t.local||t.precision===-1)&&(e.laxFormat=!0)},mime_type:(e,t)=>as(e,t.mime)};function ds(e){let t={},n=e._zod.def,r=e._zod.traits.has(`$ZodCheck`)?[e,...n.checks??[]]:n.checks??[];for(let e of r)us[e._zod.def.check]?.(t,e._zod.def);let i=e._zod.bag;i.minimum!==void 0&&es(t,`minimum`,i.minimum),i.exclusiveMinimum!==void 0&&es(t,`exclusiveMinimum`,i.exclusiveMinimum),i.maximum!==void 0&&ts(t,`maximum`,i.maximum),i.exclusiveMaximum!==void 0&&ts(t,`exclusiveMaximum`,i.exclusiveMaximum),i.multipleOf!==void 0&&rs(t,i.multipleOf),i.format!==void 0&&(t.format??=i.format,i.format.includes(`int`)&&(t.isInt=!0)),i.mime&&as(t,i.mime);for(let e of i.patterns??[])is(t,e);return t}var fs={guid:`uuid`,url:`uri`,datetime:`date-time`,json_string:`json-string`,regex:``},ps=new Map([[gi,Qn],[vi,$n]]),ms=e=>ps.get(e)??e,hs=(e,t,n,r)=>{let i=n;i.type=`string`;let{minimum:a,maximum:o,format:s,patterns:c,contentEncoding:l,laxFormat:u}=ds(e);if(typeof a==`number`&&(i.minLength=a),typeof o==`number`&&(i.maxLength=o),s&&(i.format=fs[s]??s,i.format===``&&delete i.format,(s===`time`||u)&&delete i.format),l&&(i.contentEncoding=l),c&&c.size>0){let e=[...c].map(ms);e.length===1?i.pattern=e[0].source:e.length>1&&(i.allOf=[...e.map(e=>({...t.target===`draft-07`||t.target===`draft-04`||t.target===`openapi-3.0`?{type:`string`}:{},pattern:e.source}))])}},gs=(e,t,n,r)=>{let i=n,{minimum:a,maximum:o,multipleOf:s,exclusiveMaximum:c,exclusiveMinimum:l,isInt:u}=ds(e);i.type=u?`integer`:`number`;let d=typeof l==`number`&&l>=(a??-1/0),f=typeof c==`number`&&c<=(o??1/0),p=t.target===`draft-04`||t.target===`openapi-3.0`;if(d?p?(i.minimum=l,i.exclusiveMinimum=!0):i.exclusiveMinimum=l:typeof a==`number`&&(i.minimum=a),f?p?(i.maximum=c,i.exclusiveMaximum=!0):i.exclusiveMaximum=c:typeof o==`number`&&(i.maximum=o),s){let n=new Set;for(let a of s)Number.isFinite(a)&&a!==0?n.add(Math.abs(a)):Bo(e,t,i,r,`A multipleOf divisor of ${a} cannot be represented in JSON Schema`);let[a,...o]=n;a!==void 0&&(i.multipleOf=a),o.length&&(i.allOf=[...i.allOf??[],...o.map(e=>({multipleOf:e}))])}},_s=(e,t,n,r)=>{n.type=`boolean`},vs=(e,t,n,r)=>{n.not={}},ys=(e,t,n,r)=>{let i=e._zod.def,a=He(i.entries);if(a.length===0){n.not={};return}a.every(e=>typeof e==`number`)&&(n.type=`number`),a.every(e=>typeof e==`string`)&&(n.type=`string`),n.enum=a},bs=(e,t,n,r)=>{let i=e._zod.def;if(i.values.length===0){n.not={};return}let a=[];for(let o of i.values)if(o===void 0){if(Bo(e,t,n,r,"Literal `undefined` cannot be represented in JSON Schema"))return}else if(typeof o==`bigint`){if(Bo(e,t,n,r,`BigInt literals cannot be represented in JSON Schema`))return;a.push(Number(o))}else a.push(o);if(a.length!==0){if(a.length===1){let e=a[0];n.type=e===null?`null`:typeof e,t.target===`draft-04`||t.target===`openapi-3.0`?n.enum=[e]:n.const=e}else a.every(e=>typeof e==`number`)&&(n.type=`number`),a.every(e=>typeof e==`string`)&&(n.type=`string`),a.every(e=>typeof e==`boolean`)&&(n.type=`boolean`),a.every(e=>e===null)&&(n.type=`null`),n.enum=a}},xs=(e,t,n,r)=>{Bo(e,t,n,r,`Custom types cannot be represented in JSON Schema`)},Ss=(e,t,n,r)=>{Bo(e,t,n,r,`Transforms cannot be represented in JSON Schema`)},Cs=(e,t,n,r)=>{let i=n,a=e._zod.def,{minimum:o,maximum:s}=ds(e);typeof o==`number`&&(i.minItems=o),typeof s==`number`&&(i.maxItems=s),i.type=`array`,i.items=Vo(a.element,t,{...r,path:[...r.path,`items`]})};function ws(e){let t=e._zod.def;return t.type===`pipe`&&t.in._zod.traits.has(`$ZodTransform`)?ws(t.out):t.type===`catch`?ws(t.innerType):e._zod.optin}var Ts=(e,t,n,r)=>{let i=n,a=e._zod.def,o=a.shape;if(Object.getOwnPropertySymbols(o).length&&Bo(e,t,i,r,`Symbol keys cannot be represented in JSON Schema`))return;i.type=`object`,i.properties={};for(let e in o)Xe(i.properties,e,Vo(o[e],t,{...r,path:[...r.path,`properties`,e]}));let s=[];for(let e of Object.keys(o)){let n=a.shape[e];(t.io===`input`?ws(n)===void 0:n._zod.optout===void 0)&&s.push(e)}s.length>0&&(i.required=s),a.catchall?._zod.def.type===`never`?i.additionalProperties=!1:a.catchall?a.catchall&&(i.additionalProperties=Vo(a.catchall,t,{...r,path:[...r.path,`additionalProperties`]})):t.io===`output`&&(i.additionalProperties=!1)},Es=(e,t,n,r)=>{let i=e._zod.def,a=i.inclusive===!1,o=i.options.map((e,n)=>Vo(e,t,{...r,path:[...r.path,a?`oneOf`:`anyOf`,n]}));a?n.oneOf=o:n.anyOf=o},Ds=(e,t,n,r)=>{let i=e._zod.def,a=Vo(i.left,t,{...r,path:[...r.path,`allOf`,0]}),o=Vo(i.right,t,{...r,path:[...r.path,`allOf`,1]}),s=e=>`allOf`in e&&Object.keys(e).length===1,c=[...s(a)?a.allOf:[a],...s(o)?o.allOf:[o]];n.allOf=c,t.intersections.push(c)};function Os(e,t,n){if(t.$ref){if(n.has(t))return t;n.add(t);let r=e.get(t)?.def;if(!r)return t;let i=Os(e,r,n);return i===r?t:i}for(let r of[`anyOf`,`oneOf`]){let i=t[r];if(!Array.isArray(i))continue;let a=i.map(t=>Os(e,t,n));a.some((e,t)=>e!==i[t])&&(t={...t,[r]:a})}let r=Array.isArray(t.type)?t.type:[t.type],i=!r.includes(`string`)&&r.some(e=>e===`number`||e===`integer`),a=t.enum??(t.const===void 0?void 0:[t.const]);if(!i&&!a?.some(e=>typeof e==`number`))return t;let{minimum:o,maximum:s,exclusiveMinimum:c,exclusiveMaximum:l,multipleOf:u,format:d,id:f,...p}=t;return p.enum?p.enum=p.enum.map(e=>typeof e==`number`?String(e):e):typeof p.const==`number`&&(p.const=String(p.const)),i?(p.type=`string`,a||(p.pattern=(r.includes(`number`)?ur:lr).source),p):p}var ks=new WeakMap;function As(e){let t=new Map;for(let n of e.seen.values())n.def&&!t.has(n.schema)&&t.set(n.schema,n);let n=new Map;for(let r of ks.get(e)??[]){let i=e.seen.get(r),a=(i?.def??i?.schema)?.propertyNames;if(!a||a===!0||n.has(a))continue;let o=Os(t,a,new Set);o!==a&&n.set(a,o)}if(n.size)for(let t of e.seen.values())for(let e of[t.schema,t.def]){let t=e&&n.get(e.propertyNames);t&&(e.propertyNames=t)}}var js=(e,t,n,r)=>{let i=n,a=e._zod.def;i.type=`object`;let o=a.keyType,s=ds(o).patterns;if(a.mode===`loose`&&s&&s.size>0){let e=Vo(a.valueType,t,{...r,path:[...r.path,`patternProperties`,`*`]});i.patternProperties={};for(let t of s)Xe(i.patternProperties,ms(t).source,e)}else{if(t.target===`draft-07`||t.target===`draft-2020-12`){i.propertyNames=Vo(a.keyType,t,{...r,path:[...r.path,`propertyNames`]});let n=ks.get(t);n||(n=[],ks.set(t,n),t.deferred.push(()=>As(t))),n.push(e)}i.additionalProperties=Vo(a.valueType,t,{...r,path:[...r.path,`additionalProperties`]})}let c=o._zod.values,l=t.io===`input`&&ws(a.valueType)!==void 0;if(c&&!a.partial&&!l){let e=[...c].filter(e=>typeof e==`string`||typeof e==`number`);e.length>0&&(i.required=e.map(String))}},Ms=(e,t,n,r)=>{let i=e._zod.def,a=Vo(i.innerType,t,r),o=t.seen.get(e);t.target===`openapi-3.0`?(o.ref=i.innerType,n.nullable=!0):n.anyOf=[a,{type:`null`}]},Ns=(e,t,n,r)=>{let i=e._zod.def;Vo(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType},Ps=Symbol();function Fs(e,t,n,r,i){let a=!1,o=JSON.stringify(e,(e,t)=>typeof t==`bigint`?(a=!0,null):t);return a?(Bo(t,n,r,i,`BigInt defaults cannot be represented in JSON Schema`),Ps):JSON.parse(o)}var Is=(e,t,n,r)=>{let i=e._zod.def;Vo(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType;let o=Fs(i.defaultValue,e,t,n,r);o!==Ps&&(n.default=o)},Ls=(e,t,n,r)=>{let i=e._zod.def;Vo(i.innerType,t,r);let a=t.seen.get(e);if(a.ref=i.innerType,t.io!==`input`)return;let o=Fs(i.defaultValue,e,t,n,r);o!==Ps&&(n._prefault=o)},Rs=(e,t,n,r)=>{let i=e._zod.def;Vo(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType;let o;try{o=i.catchValue(void 0)}catch{Bo(e,t,n,r,`Dynamic catch values are not supported in JSON Schema`);return}n.default=o},zs=(e,t,n,r)=>{let i=e._zod.def,a=i.in._zod.traits.has(`$ZodTransform`),o=t.io===`input`?a?i.out:i.in:i.out;Vo(o,t,r);let s=t.seen.get(e);s.ref=o},Bs=(e,t,n,r)=>{let i=e._zod.def;Vo(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType,n.readOnly=!0},Vs=(e,t,n,r)=>{let i=e._zod.def;Vo(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType},Hs=new WeakSet([Object.prototype,Error.prototype]);function Us(e,t,n){Object.defineProperty(e,t,{configurable:!0,enumerable:!1,get(){let e=n(this);return Object.defineProperty(this,t,{value:e,configurable:!0,writable:!0}),e},set(e){Object.defineProperty(this,t,{value:e,configurable:!0,writable:!0})}})}var Ws=G(`ZodError`,(e,t)=>{fn.init(e,t),e.name=`ZodError`;let n=Object.getPrototypeOf(e);Hs.has(n)||(Hs.add(n),Us(n,`format`,e=>t=>hn(e,t)),Us(n,`flatten`,e=>t=>mn(e,t)),Us(n,`addIssue`,e=>t=>{e.issues.push(t),e.message=JSON.stringify(e.issues,We,2)}),Us(n,`addIssues`,e=>t=>{e.issues.push(...t),e.message=JSON.stringify(e.issues,We,2)}),Object.defineProperty(n,"isEmpty",{configurable:!0,enumerable:!1,get(){return this.issues.length===0}}))},void 0,{Parent:Error}),Gs=_n(Ws),Ks=vn(Ws),qs=yn(Ws),Js=xn(Ws),Ys=Dn(Ws),Xs=On(Ws),Zs=kn(Ws),Qs=An(Ws),$s=jn(Ws),ec=Mn(Ws),tc=Nn(Ws),nc=Pn(Ws);function rc(){rn.localeError||an(ka())}function ic(){rn.memoizer||an({memoizer:Ea()})}var ac=G(`ZodType`,(e,t)=>(rc(),Pr.init(e,t),e.def=t,e.type=t.type,e),{check(...e){let t=this.def;return this.clone(rt(t,{checks:[...t.checks??[],...e.map(e=>typeof e==`function`?{_zod:{check:e,def:{check:`custom`},onattach:[]}}:e)]}),{parent:!0})},with(...e){return this.check(...e)},clone(e,t){return pt(this,e,t)},brand(){return this},register(e,t){return e.add(this,t),this},refine(e,t){return this.check(Sl(e,t))},superRefine(e,t){return this.check(Cl(e,t))},overwrite(e){return this.check(Oo(e))},optional(){return il(this)},exactOptional(){return ol(this)},nullable(){return cl(this)},nullish(){return il(cl(this))},nonoptional(e){return ml(this,e)},array(){return Uc(this)},or(e){return Kc([this,e])},and(e){return Xc(this,e)},transform(e){return vl(this,nl(e))},default(e){return ul(this,e)},prefault(e){return fl(this,e)},catch(e){return gl(this,e)},pipe(e){return vl(this,e)},readonly(){return bl(this)},describe(e){let t=this.clone();return Na.add(t,{description:e}),t},meta(...e){if(e.length===0)return Na.get(this);let t=this.clone();return Na.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 Bt(this,`~standard`,{...Lr(this),jsonSchema:{input:$o(this,`input`),output:$o(this,`output`)}})},set"~standard"(e){zt(this,`~standard`,e)},parse:function e(t,n){return Gs(this,t,n,{callee:e})},parseAsync:async function e(t,n){return await Ks(this,t,n,{callee:e})},safeParse(e,t){return qs(this,e,t)},async safeParseAsync(e,t){return Js(this,e,t)},get spa(){return this?.safeParseAsync},set spa(e){zt(this,`spa`,e)},validate(e,t){return wn(this,e,t)},validateAsync(e,t){return En(this,e,t)},encode:function e(t,n){return Ys(this,t,n,{callee:e})},decode:function e(t,n){return Xs(this,t,n,{callee:e})},encodeAsync:async function e(t,n){return await Zs(this,t,n,{callee:e})},decodeAsync:async function e(t,n){return await Qs(this,t,n,{callee:e})},safeEncode(e,t){return $s(this,e,t)},safeDecode(e,t){return ec(this,e,t)},async safeEncodeAsync(e,t){return tc(this,e,t)},async safeDecodeAsync(e,t){return nc(this,e,t)},toJSONSchema(e){return Qo(this,{})(e)},get description(){return Na.get(this)?.description},get _def(){return this._zod.def}}),oc=G(`_ZodString`,(e,t)=>{Rr.init(e,t),ac.init(e,t),e._zod.processJSONSchema=(t,n,r)=>hs(e,t,n,r)},Vt({format:e=>ds(e).format??null,minLength:e=>ds(e).minimum??null,maxLength:e=>ds(e).maximum??null},{regex(...e){return this.check(So(...e))},includes(...e){return this.check(To(...e))},startsWith(...e){return this.check(Eo(...e))},endsWith(...e){return this.check(Do(...e))},min(...e){return this.check(bo(...e))},max(...e){return this.check(yo(...e))},length(...e){return this.check(xo(...e))},nonempty(...e){return this.check(bo(1,...e))},lowercase(e){return this.check(Co(e))},uppercase(e){return this.check(wo(e))},trim(){return this.check(Ao())},normalize(...e){return this.check(ko(...e))},toLowerCase(){return this.check(jo())},toUpperCase(){return this.check(Mo())},slugify(){return this.check(No())}})),sc=G(`ZodString`,(e,t)=>{Rr.init(e,t),oc.init(e,t)},{email(e){return this.check(Ia(pc,e))},url(e){return this.check(Ha(gc,e))},jwt(e){return this.check(ro(jc,e))},emoji(e){return this.check(Ua(_c,e))},guid(e){return this.check(La(mc,e))},uuid(e){return this.check(Ra(hc,e))},uuidv4(e){return this.check(za(hc,e))},uuidv6(e){return this.check(Ba(hc,e))},uuidv7(e){return this.check(Va(hc,e))},nanoid(e){return this.check(Wa(vc,e))},cuid(e){return this.check(Ga(yc,e))},cuid2(e){return this.check(Ka(bc,e))},ulid(e){return this.check(qa(xc,e))},base64(e){return this.check(eo(Oc,e))},base64url(e){return this.check(to(kc,e))},xid(e){return this.check(Ja(Sc,e))},ksuid(e){return this.check(Ya(Cc,e))},ipv4(e){return this.check(Xa(wc,e))},ipv6(e){return this.check(Za(Tc,e))},cidrv4(e){return this.check(Qa(Ec,e))},cidrv6(e){return this.check($a(Dc,e))},e164(e){return this.check(no(Ac,e))},datetime(e){return this.check(io(lc,e))},date(e){return this.check(ao(uc,e))},time(e){return this.check(oo(dc,e))},duration(e){return this.check(so(fc,e))}});function K(e){return Fa(sc,e)}var cc=G(`ZodStringFormat`,(e,t)=>{zr.init(e,t),oc.init(e,t)}),lc=G(`ZodISODateTime`,(e,t)=>{ii.init(e,t),cc.init(e,t)}),uc=G(`ZodISODate`,(e,t)=>{ai.init(e,t),cc.init(e,t)}),dc=G(`ZodISOTime`,(e,t)=>{oi.init(e,t),cc.init(e,t)}),fc=G(`ZodISODuration`,(e,t)=>{si.init(e,t),cc.init(e,t)}),pc=G(`ZodEmail`,(e,t)=>{Hr.init(e,t),cc.init(e,t)}),mc=G(`ZodGUID`,(e,t)=>{Br.init(e,t),cc.init(e,t)}),hc=G(`ZodUUID`,(e,t)=>{Vr.init(e,t),cc.init(e,t)}),gc=G(`ZodURL`,(e,t)=>{Xr.init(e,t),cc.init(e,t)}),_c=G(`ZodEmoji`,(e,t)=>{Zr.init(e,t),cc.init(e,t)}),vc=G(`ZodNanoID`,(e,t)=>{Qr.init(e,t),cc.init(e,t)}),yc=G(`ZodCUID`,(e,t)=>{$r.init(e,t),cc.init(e,t)}),bc=G(`ZodCUID2`,(e,t)=>{ei.init(e,t),cc.init(e,t)}),xc=G(`ZodULID`,(e,t)=>{ti.init(e,t),cc.init(e,t)}),Sc=G(`ZodXID`,(e,t)=>{ni.init(e,t),cc.init(e,t)}),Cc=G(`ZodKSUID`,(e,t)=>{ri.init(e,t),cc.init(e,t)}),wc=G(`ZodIPv4`,(e,t)=>{ci.init(e,t),cc.init(e,t)}),Tc=G(`ZodIPv6`,(e,t)=>{di.init(e,t),cc.init(e,t)}),Ec=G(`ZodCIDRv4`,(e,t)=>{fi.init(e,t),cc.init(e,t)}),Dc=G(`ZodCIDRv6`,(e,t)=>{mi.init(e,t),cc.init(e,t)}),Oc=G(`ZodBase64`,(e,t)=>{_i.init(e,t),cc.init(e,t)}),kc=G(`ZodBase64URL`,(e,t)=>{bi.init(e,t),cc.init(e,t)}),Ac=G(`ZodE164`,(e,t)=>{xi.init(e,t),cc.init(e,t)}),jc=G(`ZodJWT`,(e,t)=>{Ci.init(e,t),cc.init(e,t)}),Mc=G(`ZodNumber`,(e,t)=>{wi.init(e,t),ac.init(e,t),e._zod.processJSONSchema=(t,n,r)=>gs(e,t,n,r),e.isFinite=!0},Vt({minValue:e=>{let{minimum:t,exclusiveMinimum:n}=ds(e);return Math.max(t??-1/0,n??-1/0)},maxValue:e=>{let{maximum:t,exclusiveMaximum:n}=ds(e);return Math.min(t??1/0,n??1/0)},isInt:e=>{let{isInt:t,multipleOf:n}=ds(e);return!!t||!!n?.some(Number.isSafeInteger)},format:e=>ds(e).format??null},{gt(e,t){return this.check(go(e,t))},gte(e,t){return this.check(_o(e,t))},min(e,t){return this.check(_o(e,t))},lt(e,t){return this.check(mo(e,t))},lte(e,t){return this.check(ho(e,t))},max(e,t){return this.check(ho(e,t))},int(e){return this.check(Fc(e))},safe(e){return this.check(Fc(e))},positive(e){return this.check(go(0,e))},nonnegative(e){return this.check(_o(0,e))},negative(e){return this.check(mo(0,e))},nonpositive(e){return this.check(ho(0,e))},multipleOf(e,t){return this.check(vo(e,t))},step(e,t){return this.check(vo(e,t))},finite(){return this}}));function Nc(e){return co(Mc,e)}var Pc=G(`ZodNumberFormat`,(e,t)=>{Ti.init(e,t),Mc.init(e,t)});function Fc(e){return lo(Pc,e)}var Ic=G(`ZodBoolean`,(e,t)=>{Ei.init(e,t),ac.init(e,t),e._zod.processJSONSchema=(t,n,r)=>_s(e,t,n,r)});function Lc(e){return uo(Ic,e)}var Rc=G(`ZodUnknown`,(e,t)=>{Di.init(e,t),ac.init(e,t),e._zod.processJSONSchema=(e,t,n)=>void 0});function zc(){return fo(Rc)}var Bc=G(`ZodNever`,(e,t)=>{Oi.init(e,t),ac.init(e,t),e._zod.processJSONSchema=(t,n,r)=>vs(e,t,n,r)});function Vc(e){return po(Bc,e)}var Hc=G(`ZodArray`,(e,t)=>{ic(),Ai.init(e,t),ac.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Cs(e,t,n,r),e.element=t.element},{min(e,t){return this.check(bo(e,t))},nonempty(e){return this.check(bo(1,e))},max(e,t){return this.check(yo(e,t))},length(e,t){return this.check(xo(e,t))},unwrap(){return this.element}});function Uc(e,t){return Po(Hc,e,t)}var Wc=G(`ZodObject`,(e,t)=>{ic(),Ii.init(e,t),ac.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Ts(e,t,n,r),Jt(e,`shape`,e=>e._zod.def.shape,!1)},{keyof(){return J(Object.keys(this._zod.def.shape))},catchall(e){return this.clone(rt(this._zod.def,{catchall:e}))},passthrough(){return this.clone(rt(this._zod.def,{catchall:zc()}))},loose(){return this.clone(rt(this._zod.def,{catchall:zc()}))},strict(){return this.clone(rt(this._zod.def,{catchall:Vc()}))},strip(){return this.clone(rt(this._zod.def,{catchall:void 0}))},extend(e){return xt(this,e)},safeExtend(e){return Ct(this,e)},merge(e){return wt(this,e)},pick(e){return vt(this,e)},omit(e){return bt(this,e)},partial(...e){return Tt(rl,this,e[0])},exactPartial(...e){return Tt(al,this,e[0],`exactPartial`)},required(...e){return Et(pl,this,e[0])}});function q(e,t){return new Wc({type:`object`,shape:e??{},...W(t)})}var Gc=G(`ZodUnion`,(e,t)=>{Ri.init(e,t),ac.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Es(e,t,n,r),e.options=t.options});function Kc(e,t){return new Gc({type:`union`,options:e,...W(t)})}var qc=G(`ZodDiscriminatedUnion`,(e,t)=>{Gc.init(e,t),Bi.init(e,t)});function Jc(e,t,n){return new qc({type:`union`,options:t,discriminator:e,...W(n)})}var Yc=G(`ZodIntersection`,(e,t)=>{Vi.init(e,t),ac.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Ds(e,t,n,r)});function Xc(e,t){return new Yc({type:`intersection`,left:e,right:t})}var Zc=G(`ZodRecord`,(e,t)=>{ic(),Wi.init(e,t),ac.init(e,t),e._zod.processJSONSchema=(t,n,r)=>js(e,t,n,r),e.keyType=t.keyType,e.valueType=t.valueType});function Qc(e,t,n){return!t||!t._zod?new Zc({type:`record`,keyType:K(),valueType:e,...W(t)}):new Zc({type:`record`,keyType:e,valueType:t,...W(n)})}var $c=G(`ZodEnum`,(e,t)=>{Gi.init(e,t),ac.init(e,t),e._zod.processJSONSchema=(t,n,r)=>ys(e,t,n,r),e.enum=t.entries,e.options=[...e._zod.values];let n=new Set(Object.keys(t.entries));e.extract=(e,r)=>{let i={};for(let r of e)if(n.has(r))i[r]=t.entries[r];else throw Error(`Key ${r} not found in enum`);return new $c({...t,checks:[],...W(r),entries:i})},e.exclude=(e,r)=>{let i={...t.entries};for(let t of e)if(n.has(t))delete i[t];else throw Error(`Key ${t} not found in enum`);return new $c({...t,checks:[],...W(r),entries:i})}});function J(e,t){return new $c({type:`enum`,entries:Array.isArray(e)?Object.fromEntries(e.map(e=>[e,e])):e,...W(t)})}var el=G(`ZodLiteral`,(e,t)=>{Ki.init(e,t),ac.init(e,t),e._zod.processJSONSchema=(t,n,r)=>bs(e,t,n,r),e.values=new Set(t.values),Object.defineProperty(e,"value",{get(){if(t.values.length>1)throw Error("This schema contains multiple valid literal values. Use `.values` instead.");return t.values[0]}})});function Y(e,t){return new el({type:`literal`,values:Array.isArray(e)?e:[e],...W(t)})}var tl=G(`ZodTransform`,(e,t)=>{ic(),qi.init(e,t),ac.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Ss(e,t,n,r),e._zod.parse=(n,r)=>{if(r.direction===`backward`)throw new nn(e.constructor.name);n.addIssue=r=>{if(typeof r==`string`)n.issues.push(Lt(r,n.value,t));else{let t=r;t.fatal&&(t.continue=!1),t.code??=`custom`,`input`in t||(t.input=n.value),t.inst??=e,n.issues.push(Lt(t))}};let i=t.transform(n.value,n);return i instanceof Promise?i.then(e=>(n.value=e,n)):(n.value=i,n)}});function nl(e){return new tl({type:`transform`,transform:e})}var rl=G(`ZodOptional`,(e,t)=>{Yi.init(e,t),ac.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Vs(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function il(e){return new rl({type:`optional`,innerType:e})}var al=G(`ZodExactOptional`,(e,t)=>{Xi.init(e,t),ac.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Vs(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function ol(e){return new al({type:`optional`,innerType:e})}var sl=G(`ZodNullable`,(e,t)=>{Zi.init(e,t),ac.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Ms(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function cl(e){return new sl({type:`nullable`,innerType:e})}var ll=G(`ZodDefault`,(e,t)=>{Qi.init(e,t),ac.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Is(e,t,n,r),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function ul(e,t){return new ll({type:`default`,innerType:e,get defaultValue(){return typeof t==`function`?t():ut(t)}})}var dl=G(`ZodPrefault`,(e,t)=>{ea.init(e,t),ac.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Ls(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function fl(e,t){return new dl({type:`prefault`,innerType:e,get defaultValue(){return typeof t==`function`?t():ut(t)}})}var pl=G(`ZodNonOptional`,(e,t)=>{ta.init(e,t),ac.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Ns(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function ml(e,t){return new pl({type:`nonoptional`,innerType:e,...W(t)})}var hl=G(`ZodCatch`,(e,t)=>{ia.init(e,t),ac.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Rs(e,t,n,r),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function gl(e,t){return new hl({type:`catch`,innerType:e,catchValue:typeof t==`function`?t:Xt(t)})}var _l=G(`ZodPipe`,(e,t)=>{aa.init(e,t),ac.init(e,t),e._zod.processJSONSchema=(t,n,r)=>zs(e,t,n,r),e.in=t.in,e.out=t.out});function vl(e,t){return new _l({type:`pipe`,in:e,out:t})}var yl=G(`ZodReadonly`,(e,t)=>{sa.init(e,t),ac.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Bs(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function bl(e){return new yl({type:`readonly`,innerType:e})}var xl=G(`ZodCustom`,(e,t)=>{la.init(e,t),ac.init(e,t),e._zod.processJSONSchema=(t,n,r)=>xs(e,t,n,r)});function Sl(e,t={}){return Fo(xl,e,t)}function Cl(e,t){return Io(e,t)}var wl=J([`T0`,`T1`,`T2`,`T3`]);J([`owner`,`guest`,`member`,`voice-device`]);var Tl=Nc().min(0).max(1),El=Kc([J([`auto`,`center`,`left`,`right`,`top`,`bottom`]),q({x:Tl,y:Tl,w:Tl,h:Tl})]),Dl=J([`ambient`,`conversation`,`focus`,`multi`]),Ol=J([`idle`,`listening`,`thinking`,`speaking`]),kl=J([`sphere`,`orb`,`ring`]),Al=q({id:K().min(1).max(64),type:J([`card`,`stat`,`list`,`table`,`code`,`chart`,`gauge`,`timeline`,`graph`,`sandbox`,`markdown`,`image`,`video`,`pdf`,`gallery`,`group`,`tabs`,`progress`,`checklist`,`countdown`,`kv`]),props:Qc(K(),zc()),placement:El,ttl:Nc().positive().max(3600).optional(),style:J([`glass`,`alert`]).optional(),layer:J([`base`,`overlay`]).optional(),pinned:Lc().optional()}),jl=Jc(`cmd`,[q({cmd:Y(`scene`),mode:Dl}),q({cmd:Y(`show`),object:Al}),q({cmd:Y(`update`),id:K(),props:Qc(K(),zc())}),q({cmd:Y(`hide`),id:K()}),q({cmd:Y(`clear`)}),q({cmd:Y(`pin`),id:K()}),q({cmd:Y(`unpin`),id:K()}),q({cmd:Y(`place`),id:K(),placement:El}),q({cmd:Y(`presence`),state:Ol.optional(),style:kl.optional()}),q({cmd:Y(`mood`),accent:K().max(16).optional(),intensity:Tl.optional()})]),Ml=q({scene:Dl,objects:Uc(Al),presence:q({state:Ol,style:kl}),mood:q({accent:K(),intensity:Tl})}),Nl={center:[20,18,60,58],left:[3,12,30,70],right:[67,12,30,70],top:[20,4,60,30],bottom:[20,62,60,30]};Object.keys(Nl);var Pl=[{id:`en_US-amy-medium`,name:`Amy`,gender:`female`,accent:`American`},{id:`en_US-kristin-medium`,name:`Kristin`,gender:`female`,accent:`American`},{id:`en_US-hfc_female-medium`,name:`Hannah`,gender:`female`,accent:`American`,note:`clear and steady`},{id:`en_GB-jenny_dioco-medium`,name:`Jenny`,gender:`female`,accent:`British`},{id:`en_GB-alba-medium`,name:`Alba`,gender:`female`,accent:`Scottish`},{id:`en_US-kathleen-low`,name:`Kathleen`,gender:`female`,accent:`American`,note:`smaller and faster`},{id:`en_US-ryan-medium`,name:`Ryan`,gender:`male`,accent:`American`},{id:`en_US-joe-medium`,name:`Joe`,gender:`male`,accent:`American`},{id:`en_US-norman-medium`,name:`Norman`,gender:`male`,accent:`American`},{id:`en_US-hfc_male-medium`,name:`Henry`,gender:`male`,accent:`American`,note:`clear and steady`},{id:`en_GB-alan-medium`,name:`Alan`,gender:`male`,accent:`British`},{id:`en_GB-northern_english_male-medium`,name:`Tom`,gender:`male`,accent:`Northern English`}],Fl=[{id:`hi_IN-priyamvada-medium`,name:`Priyamvada`,gender:`female`,accent:`Hindi`,note:`for personal use (non-commercial licence)`},{id:`hi_IN-pratham-medium`,name:`Pratham`,gender:`male`,accent:`Hindi`,note:`for personal use (non-commercial licence)`},{id:`hi_IN-rohan-medium`,name:`Rohan`,gender:`male`,accent:`Hindi`}],Il=[{id:`mr_IN-google-medium`,name:`Marathi`,gender:`female`,accent:`Marathi`}],Ll={id:`en_US-lessac-medium`,name:`Lessac`,accent:`American`,note:`the original voice`},Rl=e=>e===Ll.id||Pl.some(t=>t.id===e),zl=[{id:`aurora`,name:`Aurora`,style:`sphere`,accent:`#3fd8ff`,intensity:.6},{id:`ocean`,name:`Ocean`,style:`sphere`,accent:`#2b7bff`,intensity:.6},{id:`ember`,name:`Ember`,style:`orb`,accent:`#ff9b3d`,intensity:.7},{id:`violet`,name:`Violet storm`,style:`orb`,accent:`#a066ff`,intensity:.8},{id:`matrix`,name:`Matrix`,style:`ring`,accent:`#3dff8c`,intensity:.6},{id:`rose`,name:`Rose`,style:`ring`,accent:`#ff6fae`,intensity:.7},{id:`ghost`,name:`Ghost`,style:`sphere`,accent:`#e8f4ff`,intensity:.4}],Bl=[`local`,`spotify`,`soundcloud`,`audius`],Vl=/^[0-9a-f]{16}$/,Hl=/^[0-9]{1,20}$/,Ul=/^[A-Za-z0-9_-]{1,64}$/;function Wl(e){if(typeof e!=`string`)return null;if(Vl.test(e))return{source:`local`,id:e};let t=e.indexOf(`:`);if(t<1)return null;let n=e.slice(0,t),r=e.slice(t+1);return!Bl.includes(n)||!(n===`local`?Vl:n===`soundcloud`?Hl:Ul).test(r)?null:{source:n,id:r}}var Gl=J([`minimal`,`companion`,`workspace`]),Kl=q({size:Nc().min(.5).max(1.5),reactivity:Nc().min(0).max(1),ambient:Lc(),captions:Lc(),captionSize:J([`small`,`medium`,`large`])}),ql={width:Nc().int().min(100).max(1e4),height:Nc().int().min(100).max(1e4),kind:J([`phone`,`tablet`,`desktop`]),orientation:J([`portrait`,`landscape`]),touch:Lc()};q(ql);var Jl=q({id:K(),tool:K(),summary:K(),tier:wl,needsPin:Lc()}),Yl=q({id:K().refine(e=>Wl(e)!==null,`A track id or a source:id ref`),title:K().max(200),artist:K().max(200),album:K().max(200),durationSec:Nc().nullable()}),Xl=q({playing:Lc(),trackId:K().max(80).nullable(),title:K().max(200),artist:K().max(200),album:K().max(200),position:Nc().min(0),duration:Nc().min(0),volume:Nc().min(0).max(100),muted:Lc(),shuffle:Lc(),repeat:J([`off`,`all`,`one`]),view:J([`mini`,`full`,`hidden`]),queue:Uc(q({id:K().max(80),title:K().max(200)})).max(50),index:Nc().int().min(-1),active:Lc()}),Zl=q({action:J([`play`,`pause`,`resume`,`toggle`,`stop`,`next`,`previous`,`seek`,`volume`,`mute`,`shuffle`,`repeat`,`view`,`queue.remove`,`queue.clear`,`jump`]),tracks:Uc(Yl).max(500).optional(),mode:J([`replace`,`add`,`next`,`off`,`all`,`one`]).optional(),shuffle:Lc().optional(),seconds:Nc().min(0).optional(),percent:Nc().min(0).max(100).optional(),level:Nc().min(0).max(100).optional(),delta:Nc().min(-100).max(100).optional(),on:Lc().optional(),view:J([`mini`,`full`,`hidden`]).optional(),index:Nc().int().min(0).optional()}),Ql=q({terminalLabel:K().max(24),clock:q({hour12:Lc(),seconds:Lc(),locale:K().max(35)}),launcher:Uc(q({id:K().max(20),label:K().max(24),icon:K().max(16),action:q({type:J([`url`,`prompt`,`panel`,`music`]),value:K().max(500)})})).max(12),animations:J([`full`,`reduced`,`off`])}),$l=q({folderSet:Lc(),volume:Nc().min(0).max(100),shuffle:Lc(),repeat:J([`off`,`all`,`one`]),visualizer:Lc(),startView:J([`mini`,`full`]),output:J([`screen`,`host`]).optional()}),eu=Jc(`type`,[q({type:Y(`music.command`)}).merge(Zl),q({type:Y(`music.host`),state:Xl}),q({type:Y(`stage`),command:jl}),q({type:Y(`caption.delta`),text:K()}),q({type:Y(`caption.end`)}),q({type:Y(`approval.request`)}).merge(Jl),q({type:Y(`approval.resolved`),id:K()}),q({type:Y(`alert`),level:J([`info`,`warn`,`error`]),text:K()}),q({type:Y(`chat.user`),text:K()}),q({type:Y(`ui`),view:Gl,look:Kl.optional(),ownerName:K().max(40).optional(),assistantName:K().max(40).optional(),hud:Ql.optional(),music:$l.optional()}),q({type:Y(`activity`),text:K().max(80).nullable()}),q({type:Y(`status`),busy:Lc(),deviceOnline:Lc(),voiceAvailable:Lc().optional(),voiceEnrolled:Lc().optional(),message:K().optional()}),q({type:Y(`voice.heard`),text:K(),trust:J([`owner`,`guest`,`unverified`,`member`]).optional(),speaker:K().max(60).optional()}),q({type:Y(`voice.challenge`),id:K(),text:K()}),q({type:Y(`voice.challenge.end`),id:K()}),q({type:Y(`audio.chunk`),id:K(),seq:Nc().int().min(0),last:Lc(),mime:K(),data:K()}),q({type:Y(`audio.stop`)}),q({type:Y(`camera.request`),id:K()}),q({type:Y(`camera.cancel`),id:K()}),q({type:Y(`ui.open`),panel:Y(`plugins`),integration:K().max(40).optional()}),q({type:Y(`screen.request`),id:K()}),q({type:Y(`screen.cancel`),id:K()}),q({type:Y(`snapshot`),stage:Ml,pendingApproval:Jl.nullable().optional()}),q({type:Y(`error`),message:K()})]),tu=q({type:Y(`approval.respond`),id:K(),decision:J([`approve`,`deny`,`approve_always`]),pin:K().max(32).optional()});Jc(`type`,[q({type:Y(`chat.send`),text:K().min(1).max(8e3)}),q({type:Y(`stage.event`),objectId:K(),event:K().max(64)}),tu,q({type:Y(`voice.interrupt`)}),q({type:Y(`voice.confirm`),id:K(),pin:K().max(32)}),q({type:Y(`voice.cancel`),id:K()}),q({type:Y(`camera.denied`),id:K(),reason:J([`off`,`no-camera`,`permission`,`busy`])}),q({type:Y(`screen.denied`),id:K(),reason:J([`unsupported`,`failed`,`busy`])}),q({type:Y(`ui.panels`),open:Uc(J([`chat`,`tasks`])).max(2)}),q({type:Y(`ui.screen`),...ql}),q({type:Y(`stage.move`),objectId:K().max(64),rect:q({x:Nc().min(0).max(1),y:Nc().min(0).max(1),w:Nc().min(0).max(1),h:Nc().min(0).max(1)})}),q({type:Y(`stage.pin`),objectId:K().max(64),pinned:Lc()}),q({type:Y(`music.state`),state:Xl}),q({type:Y(`music.remote`),command:Zl}),q({type:Y(`ping`)})]),q({type:Y(`tool.exec`),id:K(),tool:K(),args:zc(),approvedOutside:Lc().optional()}),Jc(`type`,[q({type:Y(`tool.result`),id:K(),result:q({output:K(),truncated:Lc()})}),q({type:Y(`tool.error`),id:K(),error:K()})]),q({path:K()}),q({path:K()}),q({path:K(),content:K()}),q({}),q({}),q({command:K().min(1),cwd:K().optional()}),q({city:K().min(1).max(80)}),q({plugin:K().min(1).max(40),name:K().min(1).max(40)}),q({language:J([`python`,`node`,`shell`]),code:K().min(1).max(5e4),timeoutSec:Nc().int().min(1).max(60).optional()}),q({text:K().min(1).max(4e3)}),q({query:K().min(1).max(200)}),q({id:Nc().int().positive()}),q({title:K().min(1).max(1e3),inMinutes:Nc().int().min(1).max(525600).optional(),dueAt:K().max(40).optional(),repeat:J([`hourly`,`daily`,`weekly`]).optional()}),q({}),q({id:Nc().int().positive()}),q({id:Nc().int().positive()}),q({}),q({path:K().min(1).max(1e3),id:K().min(1).max(64).optional(),title:K().max(120).optional(),placement:El.optional()}),q({}),q({}),q({id:K().min(1).max(40)}),q({id:J([`telegram`,`twilio`,`zerodha`,`alexa`]).optional()}),q({id:J([`telegram`,`twilio`,`zerodha`,`alexa`]),enabled:Lc().optional(),accountSid:K().max(64).optional(),smsFrom:K().max(30).optional(),whatsappFrom:K().max(30).optional(),ownerNumber:K().max(30).optional()}).strict(),q({id:J([`telegram`,`twilio`,`zerodha`,`alexa`])}),q({id:J([`telegram`,`twilio`,`zerodha`,`alexa`])}),q({channel:J([`telegram`,`sms`,`whatsapp`]),to:K().min(1).max(40),text:K().min(1).max(1500)}),q({channel:J([`telegram`,`whatsapp`]),to:Y(`me`),path:K().min(1).max(500),caption:K().max(1e3).optional()}).strict(),q({channel:J([`telegram`,`sms`,`whatsapp`]).optional(),unread:Lc().optional(),limit:Nc().int().min(1).max(20).optional()}),q({}).strict(),q({}).strict(),q({}).strict(),q({}).strict(),q({}).strict(),q({}).strict(),q({kind:J([`morning`,`close`,`custom`]).optional(),send:Lc().optional()}).strict(),q({name:K().min(1).max(60),kind:J([`morning`,`close`,`custom`]),time:K().regex(/^([01]\d|2[0-3]):[0-5]\d$/),days:Uc(Nc().int().min(1).max(7)).min(1).max(7).optional(),channel:J([`telegram`,`whatsapp`,`sms`]),commentary:Lc().optional()}).strict(),q({}).strict(),q({id:Nc().int().min(1)}).strict(),q({query:K().max(200).optional(),title:K().max(200).optional(),artist:K().max(200).optional(),album:K().max(200).optional(),shuffle:Lc().optional(),mode:J([`replace`,`add`,`next`]).optional(),limit:Nc().int().min(1).max(500).optional(),source:J([`local`,`spotify`,`soundcloud`,`audius`,`any`]).optional()}).strict(),q({action:J([`pause`,`resume`,`toggle`,`stop`,`next`,`previous`,`seek`,`volume`,`mute`,`shuffle`,`repeat`,`view`]),level:Nc().min(0).max(100).optional(),delta:Nc().min(-100).max(100).optional(),seconds:Nc().min(0).optional(),percent:Nc().min(0).max(100).optional(),on:Lc().optional(),mode:J([`off`,`all`,`one`]).optional(),view:J([`mini`,`full`,`hidden`]).optional()}).strict(),q({action:J([`add`,`remove`,`clear`,`show`]),query:K().max(200).optional(),index:Nc().int().min(1).optional(),source:J([`local`,`spotify`,`soundcloud`,`audius`,`any`]).optional()}).strict(),q({query:K().max(200),limit:Nc().int().min(1).max(15).optional(),source:J([`local`,`spotify`,`soundcloud`,`audius`,`any`]).optional()}).strict(),q({}).strict(),q({url:K().max(2e3).optional(),query:K().max(200).optional(),output:J([`screen`,`host`]).optional(),start:Nc().min(0).max(86400).optional()}).strict(),q({action:J([`pause`,`resume`,`stop`,`seek`,`volume`]),seconds:Nc().min(0).max(86400).optional(),level:Nc().min(0).max(100).optional()}).strict(),q({}).strict(),q({}),q({settings:Qc(K(),zc())}),q({style:kl.optional(),accent:K().regex(/^#[0-9a-fA-F]{6}$/).optional(),intensity:Nc().min(0).max(1).optional(),size:Nc().min(.5).max(1.5).optional(),reactivity:Nc().min(0).max(1).optional(),ambient:Lc().optional(),captions:Lc().optional(),captionSize:J([`small`,`medium`,`large`]).optional()}),q({view:Gl}),q({}),q({id:K().min(1).max(16),name:K().min(1).max(60),kind:J([`stdio`,`http`]),command:K().max(260).optional(),args:Uc(K().max(500)).max(20).optional(),url:K().max(2e3).optional()}),q({id:K().min(1).max(16)}),q({id:K().min(1).max(16)}),q({id:K().min(1).max(16)}),q({id:K().min(1).max(16)}),q({}),q({id:K().min(1).max(40),name:K().min(1).max(80),description:K().max(500).optional(),skills:Uc(q({name:K().min(1).max(40),description:K().min(1).max(300),text:K().min(1).max(2e4)})).max(10).optional(),tools:Uc(q({name:K().min(1).max(40),description:K().min(1).max(500),language:J([`python`,`node`,`shell`]),code:K().min(1).max(5e4),parameters:Qc(K(),q({type:J([`string`,`number`,`integer`,`boolean`]),description:K().max(300).optional(),enum:Uc(K().max(100)).max(50).optional()})).optional(),required:Uc(K()).optional()})).max(10).optional()}),q({}),q({id:K().min(1).max(40)}),q({id:K().min(1).max(40)}),q({id:K().min(1).max(40)}),q({mode:Dl}),q({object:Al}),q({topic:J([`all`,`widgets`,`layout`,`overlay`,`theme`,`files`,`recipes`]).optional()}),q({id:K(),props:Qc(K(),zc())}),q({id:K()}),q({}),q({id:K()}),q({id:K()}),q({state:Ol.optional(),style:kl.optional()}),q({accent:K().max(16).optional(),intensity:Nc().min(0).max(1).optional()});var nu=new Set([`alexa`,`amazon`,`echo`,`skill`,`app`,`ask`,`tell`,`open`,`start`,`run`,`enable`,`launch`,`load`,`begin`,`use`]),ru=50;function iu(e){let t=e.trim().split(/\s+/).filter(Boolean);if(t.length<1)return`Enter the name you will say after "Alexa, ask".`;if(e.length>ru)return`That is too long (at most ${ru} characters).`;if(!/^[a-z' ]+$/.test(e))return`Use lower-case letters, spaces and apostrophes only. Spell numbers out as words.`;let n=t.find(e=>nu.has(e));return n?`The word "${n}" cannot be in the name (it is reserved by Alexa).`:null}var au=[`mp3`,`m4a`,`aac`,`ogg`,`opus`,`wav`,`flac`],ou={maxTracks:{min:100,max:5e4,def:5e3},scanDepth:{min:1,max:12,def:6},volume:{min:0,max:100,def:70},searchLimit:{min:3,max:50,def:10}},su=[`chat`,`tasks`,`plugins`,`settings`,`music`],cu=[`toggle`,`play`,`pause`,`next`,`previous`],lu=[`url`,`prompt`,`panel`,`music`];function uu(e){let t=e&&typeof e==`object`?e:null;if(!t)return`A button needs a label and an action.`;let n=typeof t.label==`string`?t.label.trim():``;if(n.length<1||n.length>24)return`A button label is 1 to 24 characters.`;let r=typeof t.icon==`string`?t.icon.trim():``;if(r.length<1||[...r].length>4)return`A button icon is 1 to 4 characters (a symbol or an emoji).`;let i=t.action&&typeof t.action==`object`?t.action:null;if(!i||!lu.includes(i.type)||typeof i.value!=`string`)return`A button needs an action: an address, a question, a panel or a music control.`;let a=i.value.trim();switch(i.type){case`url`:if(a.length>500)return`A button address is at most 500 characters.`;try{let e=new URL(a);return e.protocol===`https:`||e.protocol===`http:`?null:`A button address must start with https:// or http://.`}catch{return`A button address must start with https:// or http://.`}case`prompt`:return a.length>=1&&a.length<=500?null:`A question for the assistant is 1 to 500 characters.`;case`panel`:return su.includes(a)?null:`A panel is one of: ${su.join(`, `)}.`;default:return cu.includes(a)?null:`A music control is one of: ${cu.join(`, `)}.`}}function du(e){return e===``?null:e.length>260?`That program name is too long.`:/\s/.test(e)?`Use the program's name, or a short path with no spaces (or add the program to your PATH). Arguments cannot be added here.`:e.startsWith(`-`)||!/^[A-Za-z0-9._:\\/~+-]+$/.test(e)?`A program is a name or a path made of letters, digits and . _ : / \\ ~ + - only, and cannot start with a dash.`:null}var fu=2e3,pu=3,mu=e=>({queue:[],index:-1,playing:!1,position:0,duration:0,volume:e.volume,muted:!1,shuffle:e.shuffle,repeat:e.repeat,view:e.view});function hu(e,t=Math.random){let n=[...e];for(let e=n.length-1;e>0;e--){let r=Math.floor(t()*(e+1));[n[e],n[r]]=[n[r],n[e]]}return n}var gu=(e,t,n)=>Math.min(n,Math.max(t,e)),_u=(e,t,n)=>({...e,index:t,playing:n,position:0,duration:0});function vu(e,t,n={}){let r=n.shuffle??hu,i=e.queue.length-1;switch(t.type){case`play`:{if(t.tracks.length===0)return e;let n=t.tracks.slice(0,fu);if(t.mode===`replace`){let i=t.shuffle?r(n):n;return{..._u(e,t.shuffle?0:gu(t.start??0,0,i.length-1),!0),queue:i,shuffle:t.shuffle?!0:e.shuffle}}if(e.queue.length===0)return{..._u(e,0,!0),queue:n};let i=t.mode===`next`?e.index+1:e.queue.length;return{...e,queue:[...e.queue.slice(0,i),...n,...e.queue.slice(i)].slice(0,fu)}}case`next`:return i<0?e:e.index<i?_u(e,e.index+1,!0):e.repeat===`off`?{...e,playing:!1,position:0}:_u(e,0,!0);case`previous`:return i<0?e:e.position>pu?{...e,position:0}:e.index>0?_u(e,e.index-1,e.playing||!0):e.repeat===`all`?_u(e,i,!0):{...e,position:0};case`ended`:return i<0?e:e.repeat===`one`?_u(e,e.index,!0):e.index<i?_u(e,e.index+1,!0):e.repeat===`all`?_u(e,0,!0):{...e,playing:!1,position:0};case`failed`:return i<0?e:e.index<i?_u(e,e.index+1,!0):{...e,playing:!1,position:0};case`pause`:return e.playing?{...e,playing:!1}:e;case`resume`:return e.index>=0&&!e.playing?{...e,playing:!0}:e;case`toggle`:return e.index<0?e:{...e,playing:!e.playing};case`stop`:return{...e,playing:!1,position:0};case`volume`:{let n=typeof t.level==`number`?Math.round(t.level):typeof t.delta==`number`?e.volume+Math.round(t.delta):e.volume;return{...e,volume:gu(n,0,100),muted:typeof t.level==`number`||(t.delta??0)>0?!1:e.muted}}case`mute`:return{...e,muted:t.on??!e.muted};case`seek`:{let n=typeof t.seconds==`number`?t.seconds:typeof t.percent==`number`?e.duration*gu(t.percent,0,100)/100:e.position;return{...e,position:gu(n,0,e.duration>0?e.duration:Math.max(n,0))}}case`repeat`:return{...e,repeat:t.mode};case`shuffle`:{if(!(t.on??!e.shuffle))return{...e,shuffle:!1};let n=e.queue.slice(0,e.index+1);return{...e,shuffle:!0,queue:[...n,...r(e.queue.slice(e.index+1))]}}case`view`:return{...e,view:t.view};case`remove`:{if(!Number.isInteger(t.index)||t.index<0||t.index>i)return e;let n=e.queue.filter((e,n)=>n!==t.index);return n.length===0?{...e,queue:n,index:-1,playing:!1,position:0,duration:0}:t.index<e.index?{...e,queue:n,index:e.index-1}:t.index>e.index?{...e,queue:n}:t.index<n.length?{..._u(e,t.index,e.playing),queue:n}:e.repeat===`all`?{..._u(e,0,e.playing),queue:n}:{...e,queue:n,index:n.length-1,playing:!1,position:0}}case`clear`:return{...e,queue:[],index:-1,playing:!1,position:0,duration:0};case`jump`:return Number.isInteger(t.index)&&t.index>=0&&t.index<=i?_u(e,t.index,!0):e;case`time`:return{...e,position:Math.max(0,t.position),duration:Math.max(0,t.duration)}}}function yu(e){switch(e.action){case`play`:return{type:`play`,tracks:e.tracks??[],mode:e.mode===`add`||e.mode===`next`?e.mode:`replace`,...e.shuffle?{shuffle:!0}:{},...e.index===void 0?{}:{start:e.index}};case`pause`:case`resume`:case`toggle`:case`stop`:case`next`:case`previous`:return{type:e.action};case`seek`:return{type:`seek`,...e.seconds===void 0?{}:{seconds:e.seconds},...e.percent===void 0?{}:{percent:e.percent}};case`volume`:return{type:`volume`,...e.level===void 0?{}:{level:e.level},...e.delta===void 0?{}:{delta:e.delta}};case`mute`:return{type:`mute`,...e.on===void 0?{}:{on:e.on}};case`shuffle`:return{type:`shuffle`,...e.on===void 0?{}:{on:e.on}};case`repeat`:return e.mode===`off`||e.mode===`all`||e.mode===`one`?{type:`repeat`,mode:e.mode}:null;case`view`:return e.view?{type:`view`,view:e.view}:null;case`queue.remove`:return e.index===void 0?null:{type:`remove`,index:e.index};case`queue.clear`:return{type:`clear`};case`jump`:return e.index===void 0?null:{type:`jump`,index:e.index};default:return null}}function bu(e){switch(e.type){case`play`:return{action:`play`,tracks:e.tracks,mode:e.mode,...e.shuffle?{shuffle:!0}:{},...e.start===void 0?{}:{index:e.start}};case`next`:case`previous`:case`pause`:case`resume`:case`toggle`:case`stop`:return{action:e.type};case`volume`:return{action:`volume`,...e.level===void 0?{}:{level:e.level},...e.delta===void 0?{}:{delta:e.delta}};case`mute`:return{action:`mute`,...e.on===void 0?{}:{on:e.on}};case`seek`:return{action:`seek`,...e.seconds===void 0?{}:{seconds:e.seconds},...e.percent===void 0?{}:{percent:e.percent}};case`repeat`:return{action:`repeat`,mode:e.mode};case`shuffle`:return{action:`shuffle`,...e.on===void 0?{}:{on:e.on}};case`view`:return{action:`view`,view:e.view};case`remove`:return{action:`queue.remove`,index:e.index};case`clear`:return{action:`queue.clear`};case`jump`:return{action:`jump`,index:e.index};default:return null}}function xu({label:e,value:t,onChange:n,min:r,max:i,step:a}){let[o,s]=(0,l.useState)(String(t));return(0,l.useEffect)(()=>{s(e=>Number(e)===t?e:String(t))},[t]),(0,p.jsxs)(`label`,{className:`settings-field`,children:[(0,p.jsx)(`span`,{children:e}),(0,p.jsx)(`input`,{type:`number`,min:r,max:i,step:a,value:o,onChange:e=>{s(e.target.value),e.target.value.trim()!==``&&Number.isFinite(Number(e.target.value))&&n(Number(e.target.value))},onBlur:()=>s(String(t)),style:d})]})}async function Su(e,t){let n;try{n=await fetch(e,t)}catch{throw Error(`Could not reach Friend. Check the connection.`)}let r={};try{r=await n.json()}catch{}if(!n.ok)throw Error(r.error??(n.status===401?`Please sign in again.`:`The request failed (${n.status}).`));return r}var Cu={status:()=>Su(`/api/alexa`),allow:async(e,t)=>void await Su(`/api/alexa/devices/allow`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({id:e,pin:t})}),forget:async e=>void await Su(`/api/alexa/devices/${encodeURIComponent(e)}`,{method:`DELETE`})},wu=/^amzn1\.ask\.skill\.[A-Za-z0-9-]{8,80}$/;function Tu(e){return e.skillId.trim()&&!wu.test(e.skillId.trim())?`A skill ID looks like amzn1.ask.skill.xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx (copy it from the console).`:e.invocationName.trim()?iu(e.invocationName):null}var Eu={"skill.json":`the skill's manifest (name, endpoint)`,"en-IN.json":`the English (India) interaction model`,"hi-IN.json":`the Hindi (India) interaction model`},Du={"en-IN":`English (India)`,"hi-IN":`Hindi (India)`},Ou=e=>{let t=Math.max(0,Math.round((Date.now()-e)/6e4));return t<1?`just now`:t<60?`${t} min ago`:`${Math.round(t/60)} h ago`};function ku({view:e,setView:t,api:n=Cu}){let[r,i]=(0,l.useState)(null),[a,o]=(0,l.useState)(null),[s,c]=(0,l.useState)(``),[u,f]=(0,l.useState)(null),[m,h]=(0,l.useState)(!1),[g,_]=(0,l.useState)(!1),v=(0,l.useRef)(!0),y=(0,l.useCallback)(()=>n.status().then(e=>v.current&&i(e)).catch(()=>{}),[n]);(0,l.useEffect)(()=>(v.current=!0,y(),()=>{v.current=!1}),[y]);let b=async e=>{_(!0),f(null);try{await e()}catch(e){v.current&&f(e.message)}finally{v.current&&_(!1)}},S=Tu(e),C=r?.invocationName||e.invocationName,w=!!r?.endpoint&&!!r.invocationName;return(0,p.jsxs)(`div`,{className:`settings-section`,children:[(0,p.jsx)(`p`,{className:`auth-note`,children:`Friend talks to a skill of your own on Alexa. It is free: the skill stays in development mode in your own Amazon developer account and is never published, and only the Echo devices you allow can use it. Alexa can look things up and answer; anything that changes something is refused, or sent to your phone for a yes.`}),(0,p.jsx)(`h4`,{className:`plugins-heading`,children:`In the Alexa developer console`}),r&&r.endpoint?(0,p.jsxs)(`p`,{className:`auth-note`,children:[`Endpoint to paste (HTTPS, "My development endpoint has a certificate from a trusted certificate authority"): `,(0,p.jsx)(`code`,{children:r.endpoint}),` `,(0,p.jsx)(`button`,{type:`button`,style:d,onClick:()=>{navigator.clipboard?.writeText(r.endpoint).then(()=>h(!0),()=>{})},children:m?`Copied`:`Copy`})]}):r&&(0,p.jsx)(`p`,{className:`auth-note`,children:`No public address is set yet, so Amazon cannot reach Friend (friend config set publicUrl https://…).`}),(0,p.jsx)(`p`,{className:`auth-note`,children:`If your address changes later, paste the new address into the console again. Nothing else needs to change.`}),w?(0,p.jsx)(`ul`,{className:`plugins-list`,children:r.files.map(e=>(0,p.jsxs)(`li`,{children:[(0,p.jsx)(`a`,{href:`/api/alexa/package/${e}`,download:e,children:e}),` `,(0,p.jsx)(`small`,{className:`auth-note`,children:Eu[e]??``})]},e))}):r&&r.endpoint&&(0,p.jsx)(`p`,{className:`auth-note`,children:`Save an invocation name first; the files are made with it.`}),(0,p.jsxs)(`label`,{className:`settings-field`,children:[(0,p.jsx)(`span`,{children:`Skill ID`}),(0,p.jsx)(`input`,{value:e.skillId,autoComplete:`off`,onChange:n=>t({...e,skillId:n.target.value}),placeholder:`amzn1.ask.skill.…`,style:d})]}),(0,p.jsxs)(`label`,{className:`settings-field`,children:[(0,p.jsx)(`span`,{children:`Invocation name`}),(0,p.jsx)(`input`,{value:e.invocationName,autoComplete:`off`,onChange:n=>t({...e,invocationName:n.target.value}),placeholder:`jarvis assistant`,style:d})]}),S&&(0,p.jsx)(`p`,{role:`alert`,className:`auth-error`,children:S}),(0,p.jsxs)(`details`,{children:[(0,p.jsx)(`summary`,{className:`plugins-heading`,children:`Advanced`}),(0,p.jsxs)(`label`,{className:`settings-field`,children:[(0,p.jsx)(`span`,{children:`Skill name`}),(0,p.jsx)(`input`,{value:e.skillName,onChange:n=>t({...e,skillName:n.target.value}),style:d})]}),(0,p.jsx)(`div`,{className:`settings-field`,role:`group`,"aria-label":`Languages`,children:Object.entries(Du).map(([n,r])=>(0,p.jsxs)(`label`,{className:`settings-check`,children:[(0,p.jsx)(`input`,{type:`checkbox`,checked:e.locales.includes(n),onChange:r=>{let i=r.target.checked?[...e.locales,n]:e.locales.filter(e=>e!==n);i.length>0&&t({...e,locales:Object.keys(Du).filter(e=>i.includes(e))})}}),(0,p.jsx)(`span`,{children:r})]},n))}),(0,p.jsx)(xu,{label:`Seconds to work on an answer`,value:e.answerSeconds,min:2,max:7.5,step:.5,onChange:n=>t({...e,answerSeconds:n})}),(0,p.jsx)(xu,{label:`Minutes to keep a late answer`,value:e.holdMinutes,min:1,max:60,onChange:n=>t({...e,holdMinutes:n})}),(0,p.jsx)(xu,{label:`Seconds to wait for your yes on your phone`,value:e.permissionSeconds,min:30,max:600,onChange:n=>t({...e,permissionSeconds:n})}),(0,p.jsx)(xu,{label:`Requests a minute allowed`,value:e.requestsPerMinute,min:10,max:600,onChange:n=>t({...e,requestsPerMinute:n})}),(0,p.jsx)(xu,{label:`Echo devices allowed`,value:e.maxDevices,min:1,max:50,onChange:n=>t({...e,maxDevices:n})}),(0,p.jsxs)(`label`,{className:`settings-field`,children:[(0,p.jsx)(`span`,{children:`Extra tools a voice may use without asking (one per line)`}),(0,p.jsx)(`textarea`,{rows:2,value:e.extraVoiceTools.join(`
|
|
66
|
-
`),onChange:n=>t({...e,extraVoiceTools:n.target.value.split(/[\s,]+/).filter(Boolean)})})]}),(0,p.jsx)(`small`,{className:`auth-note`,children:`Tools that reach your PC, files, settings, add-ons or camera, and anything that needs your PIN, can never be added.`})]}),(0,p.jsx)(`h4`,{className:`plugins-heading`,children:`Echo devices`}),r&&r.waiting.length===0&&r.allowed.length===0&&(0,p.jsxs)(`p`,{className:`auth-note`,children:[`Say "Alexa, ask `,C||`your invocation name`,`" on your Echo once; it will appear here for you to allow.`]}),(0,p.jsxs)(`ul`,{className:`plugins-list`,children:[(r?.waiting??[]).map(e=>(0,p.jsxs)(`li`,{children:[(0,p.jsxs)(`b`,{children:[`Echo …`,e.short]}),` `,(0,p.jsxs)(`small`,{className:`auth-note`,children:[`waiting (`,e.locale,`), asked `,Ou(e.at)]}),` `,(0,p.jsx)(`button`,{type:`button`,style:d,disabled:g,onClick:()=>{o(e.short),c(``),f(null)},children:`Allow`})]},e.short)),(r?.allowed??[]).map(e=>(0,p.jsxs)(`li`,{children:[(0,p.jsx)(`b`,{children:e.name}),` `,(0,p.jsxs)(`small`,{className:`auth-note`,children:[`…`,e.short]}),` `,(0,p.jsx)(`button`,{type:`button`,style:d,disabled:g,onClick:()=>void b(async()=>{await n.forget(e.short),await y()}),children:`Forget`})]},e.short))]}),a&&(0,p.jsxs)(p.Fragment,{children:[(0,p.jsxs)(`p`,{className:`auth-note`,children:[`Enter your PIN to allow Echo …`,a,`. Anyone who can speak to that Echo can then ask Friend things.`]}),(0,p.jsx)(x,{pin:s,onChange:c,onSubmit:()=>!g&&s.length>=6&&void b(async()=>{await n.allow(a,s),o(null),c(``),await y()})}),(0,p.jsxs)(`div`,{className:`approval-actions`,children:[(0,p.jsx)(`button`,{type:`button`,style:d,className:`primary`,disabled:g||s.length<6,onClick:()=>void b(async()=>{await n.allow(a,s),o(null),c(``),await y()}),children:`Allow this Echo`}),(0,p.jsx)(`button`,{type:`button`,style:d,onClick:()=>{o(null),c(``),f(null)},children:`Back`})]})]}),u&&!S&&(0,p.jsx)(`p`,{role:`alert`,className:`auth-error`,children:u})]})}async function Au(e,t){let n;try{n=await fetch(e,t)}catch{throw Error(`Could not reach Friend. Check the connection.`)}let r={};try{r=await n.json()}catch{}if(!n.ok)throw Error(r.error??(n.status===401?`Please sign in again.`:n.status===403?`Incorrect PIN`:`The request failed (${n.status}).`));return r}var ju={info:async()=>{let e=(await Au(`/api/plugins`)).integrations?.find(e=>e.id===`chrome`),t=e?.settings?.extensionFolder;return{state:e?.state??`not-installed`,detail:e?.detail??``,extensionFolder:typeof t==`string`&&t?t:null}},setUp:e=>Au(`/api/connectors/quick/chrome/install`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({pin:e})}),access:()=>Au(`/api/plugins/chrome/access`),setRemote:async(e,t)=>{await Au(`/api/plugins/chrome/remote`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({enabled:e,...t?{pin:t}:{}})})},revealKey:async e=>(await Au(`/api/plugins/chrome/token`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({pin:e})})).token};function Mu({label:e,value:t}){let[n,r]=(0,l.useState)(!1);return(0,p.jsxs)(`label`,{className:`settings-field`,children:[(0,p.jsx)(`span`,{children:e}),(0,p.jsxs)(`div`,{style:{display:`flex`,gap:6},children:[(0,p.jsx)(`input`,{type:`text`,readOnly:!0,value:t,style:{flex:1},onFocus:e=>e.currentTarget.select()}),(0,p.jsx)(`button`,{type:`button`,onClick:()=>{navigator.clipboard?.writeText(t).then(()=>r(!0),()=>{})},children:n?`Copied`:`Copy`})]})]})}function Nu({api:e=ju,pollMs:t=3e3}){let[n,r]=(0,l.useState)(null),[i,a]=(0,l.useState)(null),[o,s]=(0,l.useState)(null),[c,u]=(0,l.useState)(null),[f,m]=(0,l.useState)(``),[h,g]=(0,l.useState)(!1),[_,v]=(0,l.useState)(null),[y,b]=(0,l.useState)(null),[S,C]=(0,l.useState)(!1),w=(0,l.useRef)(!0),T=(0,l.useCallback)(async()=>{try{let[t,n]=await Promise.all([e.info(),e.access()]);if(!w.current)return;r(t),a(n)}catch{}},[e]);(0,l.useEffect)(()=>{w.current=!0,T();let e=t>0?setInterval(()=>void T(),t):null;return()=>{w.current=!1,e&&clearInterval(e)}},[T,t]);let E=async()=>{g(!0),v(null);try{if(c===`setup`){let t=await e.setUp(f);if(!w.current)return;b(t.message)}else if(c===`allow`)await e.setRemote(!0,f);else if(c===`key`){let t=await e.revealKey(f);if(!w.current)return;s(t)}if(!w.current)return;u(null),await T()}catch(e){w.current&&v(e.message)}finally{w.current&&(g(!1),m(``))}};return c?(0,p.jsxs)(p.Fragment,{children:[(0,p.jsx)(`p`,{className:`auth-note`,children:c===`setup`?`Enter your PIN to set up Chrome control.`:c===`allow`?`Enter your PIN to allow other PCs to use Chrome control through Friend.`:`Enter your PIN to show the key.`}),(0,p.jsx)(x,{pin:f,onChange:m,onSubmit:()=>!h&&f.length>=6&&void E()}),_&&(0,p.jsx)(`p`,{role:`alert`,className:`auth-error`,children:_}),(0,p.jsxs)(`div`,{className:`approval-actions`,children:[(0,p.jsx)(`button`,{type:`button`,style:d,className:`primary`,disabled:h||f.length<6,onClick:()=>void E(),children:`Continue`}),(0,p.jsx)(`button`,{type:`button`,style:d,onClick:()=>{u(null),m(``),v(null)},children:`Back`})]})]}):(0,p.jsxs)(`div`,{className:`settings-section`,children:[n?.detail&&(0,p.jsx)(`p`,{className:`auth-note`,style:{marginBottom:10},children:n.detail}),n?.extensionFolder&&(0,p.jsxs)(`label`,{className:`settings-field`,children:[(0,p.jsx)(`span`,{children:`Folder to load in Chrome (chrome://extensions, Developer mode, Load unpacked)`}),(0,p.jsxs)(`div`,{style:{display:`flex`,gap:6},children:[(0,p.jsx)(`input`,{type:`text`,readOnly:!0,value:n.extensionFolder,style:{flex:1},onFocus:e=>e.currentTarget.select()}),(0,p.jsx)(`button`,{type:`button`,onClick:()=>{navigator.clipboard?.writeText(n.extensionFolder??``).then(()=>C(!0),()=>{})},children:S?`Copied`:`Copy`})]})]}),(0,p.jsx)(`div`,{className:`approval-actions`,children:(0,p.jsx)(`button`,{type:`button`,style:d,className:n?.extensionFolder?void 0:`primary`,onClick:()=>u(`setup`),children:n?.extensionFolder?`Set up again`:`Set up Chrome control`})}),y&&(0,p.jsx)(`p`,{className:`auth-note`,children:y}),i&&n?.extensionFolder&&(0,p.jsxs)(p.Fragment,{children:[(0,p.jsx)(`h4`,{className:`plugins-heading`,children:`From another PC`}),i.extensionZip&&(0,p.jsxs)(`p`,{className:`auth-note`,children:[(0,p.jsx)(`a`,{href:i.extensionZip,download:`friend-chrome-extension.zip`,children:`Download the extension`}),` `,`to install it in Chrome on another PC: unzip it, open chrome://extensions, turn on Developer mode, press Load unpacked and choose the unzipped folder.`]}),i.remote?(0,p.jsxs)(p.Fragment,{children:[(0,p.jsx)(Mu,{label:`Server to type in the extension's popup on the other PC`,value:i.extensionAddress}),(0,p.jsx)(Mu,{label:`MCP address for apps on other PCs (Claude Code, Claude Desktop). Send the key as: Authorization: Bearer KEY`,value:i.mcpUrl}),/^(ws|http):\/\/(127\.0\.0\.1|localhost|\[::1\])/i.test(i.extensionAddress)&&(0,p.jsx)(`p`,{className:`auth-note`,children:`These use the address you opened Friend with, and another PC cannot reach 127.0.0.1. Open Friend by its network or public address and these will show that one.`}),o?(0,p.jsx)(Mu,{label:`The key (paste it in the extension's popup)`,value:o}):null,(0,p.jsxs)(`div`,{className:`approval-actions`,children:[!o&&(0,p.jsx)(`button`,{type:`button`,style:d,onClick:()=>u(`key`),children:`Show the key`}),(0,p.jsx)(`button`,{type:`button`,style:d,onClick:()=>{s(null),e.setRemote(!1).then(()=>T(),e=>v(e.message))},children:`Stop allowing other PCs`})]})]}):(0,p.jsx)(`div`,{className:`approval-actions`,children:(0,p.jsx)(`button`,{type:`button`,style:d,onClick:()=>u(`allow`),children:`Allow other PCs`})})]}),(0,p.jsx)(`small`,{className:`auth-note`,children:`Chrome does not allow programs to add an extension by themselves, so loading the folder above is the one step you do. While the extension is on, Friend can act as you on the sites it allows; every action still asks for your approval, and in the extension's popup you can limit it to certain sites.`})]})}async function Pu(e,t){let n;try{n=await fetch(e,t)}catch{throw Error(`Could not reach Friend. Check the connection.`)}let r={};try{r=await n.json()}catch{}if(!n.ok)throw Error(r.error??(n.status===401?`Please sign in again.`:`The request failed (${n.status}).`));return r}var Fu=(e,t)=>Pu(e,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify(t)}),Iu={info:async()=>{let e=await Pu(`/api/music/sources`);return{status:e.sources.find(e=>e.id===`soundcloud`)?.status??{connected:!1,needs:null,account:null},redirectUri:e.soundcloud.redirectUri,clientId:e.soundcloud.clientId,secretSet:e.soundcloud.secretSet}},saveCredentials:async(e,t,n)=>void await Fu(`/api/music/soundcloud/credentials`,{clientId:e,...t?{clientSecret:t}:{},pin:n}),connect:async e=>(await Fu(`/api/music/soundcloud/connect`,{pin:e})).url,disconnect:async e=>void await Fu(`/api/music/soundcloud/disconnect`,{pin:e})},Lu=e=>e.trim()===``||/^[A-Za-z0-9]{8,64}$/.test(e.trim())?null:`A client id is letters and digits only, copied from your app at soundcloud.com/you/apps.`;function Ru({api:e=Iu,navigate:t=e=>window.location.assign(e)}){let[n,r]=(0,l.useState)(null),[i,a]=(0,l.useState)(``),[o,s]=(0,l.useState)(``),[c,u]=(0,l.useState)(null),[f,m]=(0,l.useState)(``),[h,g]=(0,l.useState)(!1),[_,v]=(0,l.useState)(null),[y,b]=(0,l.useState)(!1),S=(0,l.useRef)(!0),C=(0,l.useCallback)(async()=>{try{let t=await e.info();if(!S.current)return;r(t),a(t.clientId)}catch(e){S.current&&v(e.message)}},[e]);(0,l.useEffect)(()=>(S.current=!0,C(),()=>{S.current=!1}),[C]);let w=async()=>{if(c){g(!0),v(null);try{c===`save`?(await e.saveCredentials(i.trim(),o.trim()||void 0,f),S.current&&s(``),await C()):c===`connect`?t(await e.connect(f)):(await e.disconnect(f),await C()),S.current&&u(null)}catch(e){S.current&&v(e.message)}finally{S.current&&(g(!1),m(``))}}};if(c)return(0,p.jsxs)(p.Fragment,{children:[(0,p.jsxs)(`p`,{className:`auth-note`,children:[`Enter your PIN `,c===`save`?`to save the SoundCloud app details`:c===`connect`?`to connect SoundCloud`:`to disconnect SoundCloud`,`.`]}),(0,p.jsx)(x,{pin:f,onChange:m,onSubmit:()=>!h&&f.length>=6&&void w()}),_&&(0,p.jsx)(`p`,{role:`alert`,className:`auth-error`,children:_}),(0,p.jsxs)(`div`,{className:`approval-actions`,children:[(0,p.jsx)(`button`,{type:`button`,style:d,className:`primary`,disabled:h||f.length<6,onClick:()=>void w(),children:c===`save`?`Save`:`Continue`}),(0,p.jsx)(`button`,{type:`button`,style:d,onClick:()=>{u(null),m(``),v(null)},children:`Back`})]})]});let T=Lu(i),E=!!n&&i.trim()!==n.clientId||o.trim()!==``,D=!!n?.clientId&&n.secretSet,O=n?.status;return(0,p.jsxs)(`div`,{className:`settings-section`,children:[(0,p.jsxs)(`label`,{className:`settings-field`,children:[(0,p.jsx)(`span`,{children:`Redirect address to add in your SoundCloud app`}),(0,p.jsxs)(`div`,{style:{display:`flex`,gap:6},children:[(0,p.jsx)(`input`,{type:`text`,readOnly:!0,value:n?.redirectUri??``,style:{flex:1},onFocus:e=>e.currentTarget.select()}),(0,p.jsx)(`button`,{type:`button`,onClick:()=>{navigator.clipboard?.writeText(n?.redirectUri??``).then(()=>b(!0),()=>{})},children:y?`Copied`:`Copy`})]})]}),(0,p.jsxs)(`label`,{className:`settings-field`,children:[(0,p.jsx)(`span`,{children:`Client id of your SoundCloud app`}),(0,p.jsx)(`input`,{type:`text`,value:i,maxLength:64,autoComplete:`off`,spellCheck:!1,onChange:e=>a(e.target.value)})]}),(0,p.jsxs)(`label`,{className:`settings-field`,children:[(0,p.jsx)(`span`,{children:`Client secret of your SoundCloud app`}),(0,p.jsx)(`input`,{type:`password`,value:o,maxLength:200,autoComplete:`new-password`,spellCheck:!1,onChange:e=>s(e.target.value)}),n?.secretSet&&(0,p.jsx)(`small`,{className:`auth-note`,children:`The secret is saved. Type a new one only to replace it.`})]}),T&&(0,p.jsx)(`p`,{role:`alert`,className:`auth-error`,children:T}),(0,p.jsxs)(`div`,{className:`approval-actions`,children:[(0,p.jsx)(`button`,{type:`button`,style:d,disabled:!E||!i.trim()||T!==null||!n?.secretSet&&!o.trim(),onClick:()=>u(`save`),children:`Save`}),O?.connected?(0,p.jsx)(`button`,{type:`button`,style:d,onClick:()=>u(`disconnect`),children:`Disconnect SoundCloud`}):(0,p.jsx)(`button`,{type:`button`,style:d,className:`primary`,disabled:!D||E,onClick:()=>u(`connect`),children:`Connect SoundCloud`})]}),O?.connected&&(0,p.jsxs)(`p`,{className:`auth-note`,children:[`Connected as `,O.account??`your account`,`.`]}),O?.needs&&(0,p.jsx)(`p`,{className:`auth-note`,children:O.needs}),_&&(0,p.jsx)(`p`,{role:`alert`,className:`auth-error`,children:_}),(0,p.jsx)(`small`,{className:`auth-note`,children:`Sign-in is on SoundCloud's own page: Friend never sees your SoundCloud password. SoundCloud decides who can register an app, and some tracks only play with the right SoundCloud plan.`})]})}async function zu(e,t){let n;try{n=await fetch(e,t)}catch{throw Error(`Could not reach Friend. Check the connection.`)}let r={};try{r=await n.json()}catch{}if(!n.ok)throw Error(r.error??(n.status===401?`Please sign in again.`:`The request failed (${n.status}).`));return r}var Bu=(e,t)=>zu(e,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify(t)}),Vu={info:async()=>{let e=await zu(`/api/music/sources`);return{status:e.sources.find(e=>e.id===`spotify`)?.status??{connected:!1,needs:null,account:null},redirectUri:e.spotify.redirectUri,clientId:e.spotify.clientId}},saveClientId:async(e,t)=>void await Bu(`/api/music/spotify/client-id`,{clientId:e,pin:t}),connect:async e=>(await Bu(`/api/music/spotify/connect`,{pin:e})).url,disconnect:async e=>void await Bu(`/api/music/spotify/disconnect`,{pin:e})},Hu=e=>e.trim()===``||/^[A-Za-z0-9]{8,64}$/.test(e.trim())?null:`A client id is letters and digits only, copied from your app at developer.spotify.com.`;function Uu({api:e=Vu,navigate:t=e=>window.location.assign(e)}){let[n,r]=(0,l.useState)(null),[i,a]=(0,l.useState)(``),[o,s]=(0,l.useState)(null),[c,u]=(0,l.useState)(``),[f,m]=(0,l.useState)(!1),[h,g]=(0,l.useState)(null),[_,v]=(0,l.useState)(!1),y=(0,l.useRef)(!0),b=(0,l.useCallback)(async()=>{try{let t=await e.info();if(!y.current)return;r(t),a(t.clientId)}catch(e){y.current&&g(e.message)}},[e]);(0,l.useEffect)(()=>(y.current=!0,b(),()=>{y.current=!1}),[b]);let S=async()=>{if(o){m(!0),g(null);try{o===`client`?(await e.saveClientId(i.trim(),c),await b()):o===`connect`?t(await e.connect(c)):(await e.disconnect(c),await b()),y.current&&s(null)}catch(e){y.current&&g(e.message)}finally{y.current&&(m(!1),u(``))}}};if(o)return(0,p.jsxs)(p.Fragment,{children:[(0,p.jsxs)(`p`,{className:`auth-note`,children:[`Enter your PIN `,o===`client`?`to save the client id`:o===`connect`?`to connect Spotify`:`to disconnect Spotify`,`.`]}),(0,p.jsx)(x,{pin:c,onChange:u,onSubmit:()=>!f&&c.length>=6&&void S()}),h&&(0,p.jsx)(`p`,{role:`alert`,className:`auth-error`,children:h}),(0,p.jsxs)(`div`,{className:`approval-actions`,children:[(0,p.jsx)(`button`,{type:`button`,style:d,className:`primary`,disabled:f||c.length<6,onClick:()=>void S(),children:o===`client`?`Save`:`Continue`}),(0,p.jsx)(`button`,{type:`button`,style:d,onClick:()=>{s(null),u(``),g(null)},children:`Back`})]})]});let C=Hu(i),w=!!n&&i.trim()!==n.clientId,T=!!n?.clientId,E=n?.status;return(0,p.jsxs)(`div`,{className:`settings-section`,children:[(0,p.jsxs)(`label`,{className:`settings-field`,children:[(0,p.jsx)(`span`,{children:`Redirect address to add in your Spotify app`}),(0,p.jsxs)(`div`,{style:{display:`flex`,gap:6},children:[(0,p.jsx)(`input`,{type:`text`,readOnly:!0,value:n?.redirectUri??``,style:{flex:1},onFocus:e=>e.currentTarget.select()}),(0,p.jsx)(`button`,{type:`button`,onClick:()=>{navigator.clipboard?.writeText(n?.redirectUri??``).then(()=>v(!0),()=>{})},children:_?`Copied`:`Copy`})]})]}),(0,p.jsxs)(`label`,{className:`settings-field`,children:[(0,p.jsx)(`span`,{children:`Client id of your Spotify app`}),(0,p.jsx)(`input`,{type:`text`,value:i,maxLength:64,autoComplete:`off`,spellCheck:!1,onChange:e=>a(e.target.value)})]}),C&&(0,p.jsx)(`p`,{role:`alert`,className:`auth-error`,children:C}),(0,p.jsxs)(`div`,{className:`approval-actions`,children:[(0,p.jsx)(`button`,{type:`button`,style:d,disabled:!w||!i.trim()||C!==null,onClick:()=>s(`client`),children:`Save client id`}),E?.connected?(0,p.jsx)(`button`,{type:`button`,style:d,onClick:()=>s(`disconnect`),children:`Disconnect Spotify`}):(0,p.jsx)(`button`,{type:`button`,style:d,className:`primary`,disabled:!T||w,onClick:()=>s(`connect`),children:`Connect Spotify`})]}),E?.connected&&(0,p.jsxs)(`p`,{className:`auth-note`,children:[`Connected as `,E.account??`your account`,`.`]}),E?.needs&&(0,p.jsx)(`p`,{className:`auth-note`,children:E.needs}),h&&(0,p.jsx)(`p`,{role:`alert`,className:`auth-error`,children:h}),(0,p.jsx)(`small`,{className:`auth-note`,children:`Sign-in is on Spotify's own page: Friend never sees your Spotify password. A development-mode Spotify app allows up to five people, and playing needs Spotify Premium on the account.`})]})}async function Wu(e,t){let n;try{n=await fetch(e,t)}catch{throw Error(`Could not reach Friend. Check the connection.`)}let r={};try{r=await n.json()}catch{}if(!n.ok)throw Error(r.error??(n.status===401?`Please sign in again.`:n.status===403?`Incorrect PIN`:`The request failed (${n.status}).`));return r}var Gu={output:`screen`,maxHeight:720,maxMinutes:240,allowedSites:[],ytdlp:``,ffmpeg:``,autoInstall:!0},Ku={info:async()=>{let[e,t]=await Promise.all([Wu(`/api/settings`),Wu(`/api/plugins/video/status`)]);return{settings:e.video??Gu,status:t}},recheck:()=>Wu(`/api/plugins/video/check`,{method:`POST`,headers:{"content-type":`application/json`},body:`{}`}),prepare:()=>Wu(`/api/plugins/video/prepare`,{method:`POST`,headers:{"content-type":`application/json`},body:`{}`}),save:async(e,t)=>{await Wu(`/api/settings`,{method:`PUT`,headers:{"content-type":`application/json`},body:JSON.stringify({pin:t,settings:{video:e}})})}},qu=[360,480,720,1080],Ju=1,Yu=600,Xu=e=>e.split(/[\s,;]+/).map(e=>e.trim()).filter(Boolean),Zu=e=>e.join(`, `);function Qu({name:e,h:t,need:n,auto:r}){return(0,p.jsx)(`li`,{className:t.found?`done`:void 0,children:t.found?(0,p.jsxs)(p.Fragment,{children:[e,` `,t.version??``,` found`]}):(0,p.jsxs)(p.Fragment,{children:[(0,p.jsxs)(`strong`,{children:[e,` not found`]}),` `,(0,p.jsxs)(`small`,{children:[`(`,n,`)`]}),r&&(0,p.jsx)(`div`,{className:`auth-note`,children:r}),t.install&&(0,p.jsx)(`div`,{className:`auth-note`,children:t.install})]})})}function $u({api:e=Ku,pollMs:t=2e3}){let[n,r]=(0,l.useState)(null),[i,a]=(0,l.useState)(Gu),[o,s]=(0,l.useState)(``),[c,u]=(0,l.useState)(`240`),[f,m]=(0,l.useState)(!1),[h,g]=(0,l.useState)(``),[_,v]=(0,l.useState)(!1),[y,b]=(0,l.useState)(null),[S,C]=(0,l.useState)(null),w=(0,l.useRef)(!0),T=(0,l.useCallback)(async()=>{try{let t=await e.info();if(!w.current)return;r(t),a(t.settings),s(Zu(t.settings.allowedSites)),u(String(t.settings.maxMinutes))}catch(e){w.current&&b(e.message)}},[e]);(0,l.useEffect)(()=>(w.current=!0,T(),()=>{w.current=!1}),[T]);let E=n?.status.setup?.busy===!0;(0,l.useEffect)(()=>{if(!E||t<=0)return;let n=setInterval(()=>{e.info().then(e=>w.current&&r(t=>t?{...t,status:e.status}:e)).catch(()=>{})},t);return()=>clearInterval(n)},[E,t,e]);let D=n?.settings??Gu,O=Number(c),k=!Number.isInteger(O)||O<Ju||O>Yu?`Use a whole number of minutes from ${Ju} to ${Yu}.`:null,A=(()=>{let e={};i.output!==D.output&&(e.output=i.output),i.maxHeight!==D.maxHeight&&(e.maxHeight=i.maxHeight),!k&&O!==D.maxMinutes&&(e.maxMinutes=O);let t=Xu(o);return JSON.stringify(t)!==JSON.stringify(D.allowedSites)&&(e.allowedSites=t),i.autoInstall!==D.autoInstall&&(e.autoInstall=i.autoInstall),i.ytdlp.trim()!==D.ytdlp&&(e.ytdlp=i.ytdlp.trim()),i.ffmpeg.trim()!==D.ffmpeg&&(e.ffmpeg=i.ffmpeg.trim()),e})(),j=Object.keys(A).length>0,ee=async()=>{v(!0),b(null);try{let t=await e.recheck();w.current&&r(e=>e&&{...e,status:t})}catch(e){w.current&&b(e.message)}finally{w.current&&v(!1)}},M=async()=>{v(!0),b(null);try{let t=await e.prepare();w.current&&r(e=>e&&{...e,status:t})}catch(e){w.current&&b(e.message)}finally{w.current&&v(!1)}},N=async()=>{v(!0),b(null);try{if(await e.save(A,h),!w.current)return;m(!1),C(`Saved.`),await T()}catch(e){w.current&&b(e.message)}finally{w.current&&(v(!1),g(``))}};if(f)return(0,p.jsxs)(p.Fragment,{children:[(0,p.jsx)(`p`,{className:`auth-note`,children:`Enter your PIN to save these changes.`}),(0,p.jsx)(x,{pin:h,onChange:g,onSubmit:()=>!_&&h.length>=6&&void N()}),y&&(0,p.jsx)(`p`,{role:`alert`,className:`auth-error`,children:y}),(0,p.jsxs)(`div`,{className:`approval-actions`,children:[(0,p.jsx)(`button`,{type:`button`,style:d,className:`primary`,disabled:_||h.length<6,onClick:()=>void N(),children:`Save`}),(0,p.jsx)(`button`,{type:`button`,style:d,onClick:()=>{m(!1),g(``),b(null)},children:`Back`})]})]});let P=n?.status,F=P?.setup,I=e=>i.autoInstall?`Friend downloads ${e} by itself when it is needed (or press Download now).`:null,te=!!P&&(!P.ytdlp.found||!P.ffmpeg.found);return(0,p.jsxs)(`div`,{className:`settings-section`,children:[P&&(0,p.jsxs)(p.Fragment,{children:[(0,p.jsx)(`h4`,{className:`plugins-heading`,children:`Helper programs on this PC`}),(0,p.jsxs)(`ol`,{className:`integration-steps`,children:[(0,p.jsx)(Qu,{name:`yt-dlp`,h:P.ytdlp,need:`finds the video, needed for every video`,auto:I(`it`)}),(0,p.jsx)(Qu,{name:`ffmpeg`,h:P.ffmpeg,need:`makes the video playable, needed for the Friend screen`,auto:I(`it`)}),(0,p.jsx)(Qu,{name:`mpv`,h:P.mpv,need:`optional: a window of its own on this PC; without it a browser window is used`,auto:null})]}),F?.busy&&(0,p.jsx)(`p`,{className:`auth-note`,children:F.message??`Setting up the video tools…`}),!F?.busy&&F?.error&&(0,p.jsx)(`p`,{role:`alert`,className:`auth-error`,children:F.error}),(0,p.jsxs)(`div`,{className:`approval-actions`,children:[te&&i.autoInstall&&!F?.busy&&(0,p.jsx)(`button`,{type:`button`,style:d,className:`primary`,disabled:_,onClick:()=>void M(),children:`Download now`}),(0,p.jsx)(`button`,{type:`button`,style:d,disabled:_,onClick:()=>void ee(),children:`Check again`})]})]}),(0,p.jsxs)(`label`,{className:`settings-field`,style:{flexDirection:`row`,alignItems:`center`,gap:8},children:[(0,p.jsx)(`input`,{type:`checkbox`,checked:i.autoInstall,onChange:e=>a({...i,autoInstall:e.target.checked})}),(0,p.jsx)(`span`,{children:`Let Friend download yt-dlp and ffmpeg by itself (recommended)`})]}),(0,p.jsxs)(`label`,{className:`settings-field`,children:[(0,p.jsx)(`span`,{children:`Where videos play`}),(0,p.jsxs)(`select`,{value:i.output,onChange:e=>a({...i,output:e.target.value}),children:[(0,p.jsx)(`option`,{value:`screen`,children:`On the Friend screen`}),(0,p.jsx)(`option`,{value:`host`,children:`In a window on this PC`})]})]}),(0,p.jsxs)(`label`,{className:`settings-field`,children:[(0,p.jsx)(`span`,{children:`Picture quality (the tallest picture)`}),(0,p.jsx)(`select`,{value:String(i.maxHeight),onChange:e=>a({...i,maxHeight:Number(e.target.value)}),children:(qu.includes(i.maxHeight)?qu:[...qu,i.maxHeight].sort((e,t)=>e-t)).map(e=>(0,p.jsxs)(`option`,{value:e,children:[e,`p`]},e))})]}),(0,p.jsxs)(`label`,{className:`settings-field`,children:[(0,p.jsx)(`span`,{children:`Longest video, in minutes`}),(0,p.jsx)(`input`,{type:`number`,min:Ju,max:Yu,value:c,onChange:e=>u(e.target.value)})]}),k&&(0,p.jsx)(`p`,{role:`alert`,className:`auth-error`,children:k}),(0,p.jsxs)(`label`,{className:`settings-field`,children:[(0,p.jsx)(`span`,{children:`Allowed sites (empty: any public site)`}),(0,p.jsx)(`textarea`,{rows:2,spellCheck:!1,placeholder:`youtube.com, vimeo.com`,value:o,onChange:e=>s(e.target.value)})]}),(0,p.jsxs)(`label`,{className:`settings-field`,children:[(0,p.jsx)(`span`,{children:`yt-dlp program (empty: find it by itself)`}),(0,p.jsx)(`input`,{type:`text`,value:i.ytdlp,maxLength:260,spellCheck:!1,autoComplete:`off`,placeholder:`yt-dlp`,onChange:e=>a({...i,ytdlp:e.target.value})})]}),(0,p.jsxs)(`label`,{className:`settings-field`,children:[(0,p.jsx)(`span`,{children:`ffmpeg program (empty: find it by itself)`}),(0,p.jsx)(`input`,{type:`text`,value:i.ffmpeg,maxLength:260,spellCheck:!1,autoComplete:`off`,placeholder:`ffmpeg`,onChange:e=>a({...i,ffmpeg:e.target.value})})]}),S&&!j&&(0,p.jsx)(`p`,{className:`auth-note`,children:S}),y&&!k&&(0,p.jsx)(`p`,{role:`alert`,className:`auth-error`,children:y}),(0,p.jsx)(`div`,{className:`approval-actions`,children:(0,p.jsx)(`button`,{type:`button`,style:d,className:`primary`,disabled:!j||_||k!==null,onClick:()=>m(!0),children:j?`Save…`:`Save`})}),(0,p.jsx)(`small`,{className:`auth-note`,children:`Friend downloads the two programs from their projects' own release pages (github.com), checks them against the published checksums and keeps them in its own folder, never anywhere else on your PC. Videos stay on the site; nothing is saved to your disk. Some sites need a login or are not available in every country, and those cannot be played.`})]})}async function ed(e,t){let n;try{n=await fetch(e,t)}catch{throw Error(`Could not reach Friend. Check the connection.`)}let r={};try{r=await n.json()}catch{}if(!n.ok)throw Error(r.error??(n.status===401?`Please sign in again.`:`The request failed (${n.status}).`));return r}var td=(e,t)=>({method:e,headers:{"content-type":`application/json`},body:JSON.stringify(t)}),nd={status:()=>ed(`/api/brokers`),loginLink:e=>ed(`/api/brokers/zerodha/login-link`,td(`POST`,{send:e})),runNow:e=>ed(`/api/brokers/run`,td(`POST`,{kind:`custom`,send:e===!0})),addSchedule:async(e,t)=>void await ed(`/api/brokers/schedules`,td(`POST`,{...e,pin:t})),removeSchedule:async e=>void await ed(`/api/brokers/schedules/${e}`,{method:`DELETE`})},rd=[`Mon`,`Tue`,`Wed`,`Thu`,`Fri`,`Sat`,`Sun`],id=[[`telegram`,`Telegram`],[`whatsapp`,`WhatsApp`],[`sms`,`SMS`]],ad={telegram:`Telegram`,whatsapp:`WhatsApp`,sms:`SMS`};function od({view:e,setView:t,secret:n,setSecret:r,api:i=nd}){let[a,o]=(0,l.useState)(null),[s,c]=(0,l.useState)(null),[u,f]=(0,l.useState)(null),[m,h]=(0,l.useState)(null),[g,_]=(0,l.useState)(!1),[v,y]=(0,l.useState)(!1),[b,S]=(0,l.useState)(``),[C,w]=(0,l.useState)({name:`Morning report`,kind:`morning`,time:`09:30`,days:[1,2,3,4,5],channel:`telegram`}),[T,E]=(0,l.useState)(!1),D=(0,l.useRef)(!0),O=(0,l.useCallback)(()=>i.status().then(e=>D.current&&o(e)).catch(()=>{}),[i]);(0,l.useEffect)(()=>(D.current=!0,O(),()=>{D.current=!1}),[O]);let k=async e=>{E(!0),f(null),c(null);try{await e()}catch(e){D.current&&f(e.message)}finally{D.current&&E(!1)}},A=e.zerodha,j=n=>t({...e,...n}),ee=a?.schedules[0]?.channel??`telegram`,M=()=>/^([01]\d|2[0-3]):[0-5]\d$/.test(C.time)?C.days.length===0?`Choose at least one day.`:C.name.trim()?null:`Give the report a name.`:`Write the time like 09:30 (HH:MM, 24 hour).`,N=()=>k(async()=>{await i.addSchedule({...C,name:C.name.trim()},b),_(!1),y(!1),S(``),await O()});return(0,p.jsxs)(`div`,{className:`settings-section`,children:[(0,p.jsx)(`p`,{className:`auth-note`,children:`Friend only reads your account. It cannot place orders. The figures you ask about pass through the AI model you chose (Claude from Anthropic, or Ollama on this PC), and a report you schedule goes to the messaging app you pick (Telegram or WhatsApp). Nothing else leaves this PC.`}),(0,p.jsx)(`p`,{className:`auth-note`,children:a?.redirectUrl?(0,p.jsxs)(p.Fragment,{children:[`In your Kite Connect app, set the redirect URL to `,(0,p.jsx)(`code`,{children:a.redirectUrl})]}):`No public address is set yet, so Zerodha cannot send you back to Friend after login (friend config set publicUrl https://…).`}),(0,p.jsxs)(`label`,{className:`settings-field`,children:[(0,p.jsx)(`span`,{children:`API key`}),(0,p.jsx)(`input`,{value:A.apiKey,autoComplete:`off`,onChange:e=>j({zerodha:{...A,apiKey:e.target.value}}),style:d})]}),(0,p.jsxs)(`label`,{className:`settings-field`,children:[(0,p.jsx)(`span`,{children:`API secret`}),(0,p.jsx)(`input`,{type:`password`,autoComplete:`off`,value:n,placeholder:A.secretSet?`A secret is saved. Type to replace it.`:``,onChange:e=>r(e.target.value),style:d})]}),(0,p.jsxs)(`label`,{className:`settings-field`,children:[(0,p.jsx)(`span`,{children:`Time zone`}),(0,p.jsx)(`input`,{value:e.timezone,onChange:e=>j({timezone:e.target.value}),style:d})]}),(0,p.jsxs)(`label`,{className:`settings-field`,children:[(0,p.jsx)(`span`,{children:`Days with no reports (one per line, YYYY-MM-DD)`}),(0,p.jsx)(`textarea`,{value:e.skipDates.join(`
|
|
65
|
+
Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let n of e.seen.entries()){let r=n[1];if(t===n[0]){a(n);continue}if(e.external){let r=e.external.registry.get(n[0])?.id;if(t!==n[0]&&r){a(n);continue}}if(e.metadataRegistry.get(n[0])?.id){a(n);continue}if(r.cycle){a(n);continue}r.count>1&&e.reused===`ref`&&a(n)}e.external&&(e.sharedDefsExtractedFor=e.external)}function Wo(e){let t=e.anyOf;if(!Array.isArray(t)||t.length===0||e.type!==void 0)return;let n=[];for(let e of t){if(!e||typeof e!=`object`)return;Wo(e);let t=Object.keys(e);if(t.length!==1||t[0]!==`type`)return;let r=e.type;for(let e of Array.isArray(r)?r:[r]){if(typeof e!=`string`)return;n.includes(e)||n.push(e)}}delete e.anyOf,e.type=n.length===1?n[0]:n}var Go=new Set([`type`,`properties`,`required`,`additionalProperties`]),Ko=[`oneOf`,`anyOf`];function qo(e){let t=e.additionalProperties;return t===void 0||t===!1||typeof t!=`object`||!t?null:Object.keys(t).length?t:null}function Jo(e){let t=[];for(let n of e){if(typeof n!=`object`||n.type!==`object`)return null;for(let e in n)if(!Go.has(e))return null;t.push(n)}let n={},r=new Set;for(let e of t){for(let r in e.properties){if(Object.prototype.hasOwnProperty.call(n,r))continue;let e=[];for(let n of t){let t=n.properties?.[r]??qo(n);t!=null&&(e.some(e=>JSON.stringify(e)===JSON.stringify(t))||e.push(t))}Xe(n,r,e.length===1?e[0]:Jo(e)??{allOf:e})}for(let t of e.required??[])r.add(t)}let i={type:`object`,properties:n};if(r.size&&(i.required=[...r]),t.every(e=>e.additionalProperties===!1))i.additionalProperties=!1;else{let e=[];for(let n of t){let t=qo(n);t&&!e.some(e=>JSON.stringify(e)===JSON.stringify(t))&&e.push(t)}e.length===1?i.additionalProperties=e[0]:e.length>1&&(i.additionalProperties={allOf:e})}return i}function Yo(e){let t=e.allOf;if(!Array.isArray(t)||t.length<2)return;for(let t of Go)if(t in e)return;let n=t.filter(e=>Ko.some(t=>Array.isArray(e[t]))),r=null;if(!n.length)r=Jo(t);else{let e=n[0],i=Ko.find(t=>Array.isArray(e[t]));if(Object.keys(e).length!==1)return;let a=t.filter(t=>t!==e),o=e[i].map(e=>Jo([...a,e]));if(o.some(e=>!e))return;r={[i]:o}}r&&(delete e.allOf,Ro(e,r))}function Xo(e,t){let n=e.seen.get(t);if(!n)throw Error(`Unprocessed schema. This is a bug in Zod.`);let r=t=>{let n=e.seen.get(t);if(n.ref===null)return;let i=n.def??n.schema,a={...i},o=n.ref;if(n.ref=null,o){r(o);let n=e.seen.get(o),s=n.schema;if(s.$ref&&(e.target===`draft-07`||e.target===`draft-04`||e.target===`openapi-3.0`)?(i.allOf=i.allOf??[],i.allOf.push(s)):Ro(i,s),Ro(i,a),t._zod.parent===o)for(let e in i)e!==`$ref`&&e!==`allOf`&&(e in a||delete i[e]);if(s.$ref&&n.def)for(let e in i)e!==`$ref`&&e!==`allOf`&&e in n.def&&JSON.stringify(i[e])===JSON.stringify(n.def[e])&&delete i[e]}let s=t._zod.parent;if(s&&s!==o){r(s);let t=e.seen.get(s);if(t?.schema.$ref&&(i.$ref=t.schema.$ref,t.def))for(let e in i)e!==`$ref`&&e!==`allOf`&&e in t.def&&JSON.stringify(i[e])===JSON.stringify(t.def[e])&&delete i[e]}e.override({zodSchema:t,jsonSchema:i,path:n.path??[]})};if(!e.external||e.sharedEmitDoneFor!==e.external){for(let t of[...e.seen.entries()].reverse())r(t[0]);if(e.target!==`openapi-3.0`)for(let t of e.seen.entries())Wo(t[1].def??t[1].schema);for(let t of e.deferred)t();if(e.intersections.length){let t=new Map;for(let n of e.seen.values())for(let e of[n.schema,n.def]){let n=e?.allOf;if(!Array.isArray(n))continue;let r=t.get(n);r?r.push(e):t.set(n,[e])}for(let n of e.intersections)for(let e of t.get(n)??[])Yo(e)}}let i={};if(e.target===`draft-2020-12`?i.$schema=`https://json-schema.org/draft/2020-12/schema`:e.target===`draft-07`?i.$schema=`http://json-schema.org/draft-07/schema#`:e.target===`draft-04`?i.$schema=`http://json-schema.org/draft-04/schema#`:e.target,e.external?.uri){let n=e.external.registry.get(t)?.id;if(!n)throw Error("Schema is missing an `id` property");i.$id=e.external.uri(n)}Ro(i,n.defId?n.schema:n.def??n.schema);let a=e.metadataRegistry.get(t)?.id;a!==void 0&&i.id===a&&delete i.id;let o=e.external?.defs??{};if(!e.external||e.sharedEmitDoneFor!==e.external)for(let t of e.seen.entries()){let e=t[1];e.def&&e.defId&&(e.def.id===e.defId&&delete e.def.id,Xe(o,e.defId,e.def))}e.external&&(e.sharedEmitDoneFor=e.external),e.external||Object.keys(o).length>0&&(e.target===`draft-2020-12`?i.$defs=o:i.definitions=o);try{let n=JSON.parse(JSON.stringify(i));return Object.defineProperty(n,"~standard",{value:{...t[`~standard`],jsonSchema:{input:$o(t,`input`,e.processors),output:$o(t,`output`,e.processors)}},enumerable:!1,writable:!1}),n}catch{throw Error(`Error converting schema to JSON.`)}}function Zo(e,t){let n=t??{seen:new Set};if(n.seen.has(e))return!1;n.seen.add(e);let r=e._zod.def;if(r.type===`transform`)return!0;if(r.type===`array`)return Zo(r.element,n);if(r.type===`set`)return Zo(r.valueType,n);if(r.type===`lazy`)return Zo(r.getter(),n);if(r.type===`promise`||r.type===`optional`||r.type===`nonoptional`||r.type===`nullable`||r.type===`readonly`||r.type==="default"||r.type===`prefault`||r.type===`catch`)return Zo(r.innerType,n);if(r.type===`intersection`)return Zo(r.left,n)||Zo(r.right,n);if(r.type===`record`||r.type===`map`)return Zo(r.keyType,n)||Zo(r.valueType,n);if(r.type===`pipe`)return e._zod.traits.has(`$ZodCodec`)?!0:Zo(r.in,n)||Zo(r.out,n);if(r.type===`object`){for(let e in r.shape)if(Zo(r.shape[e],n))return!0;return!1}if(r.type===`union`){for(let e of r.options)if(Zo(e,n))return!0;return!1}if(r.type===`tuple`){for(let e of r.items)if(Zo(e,n))return!0;return!!(r.rest&&Zo(r.rest,n))}return!1}var Qo=(e,t={})=>n=>{let r=zo({...n,processors:t});return Vo(e,r),Uo(r,e),Xo(r,e)},$o=(e,t,n={})=>r=>{let{libraryOptions:i,target:a}=r??{},o=zo({...i??{},target:a,io:t,processors:n});return Vo(e,o),Uo(o,e),Xo(o,e)},es=(e,t,n)=>{(e[t]===void 0||n>e[t])&&(e[t]=n)},ts=(e,t,n)=>{(e[t]===void 0||n<e[t])&&(e[t]=n)},ns=(e,t)=>{es(e,`minimum`,t),ts(e,`maximum`,t)},rs=(e,t)=>{e.multipleOf??=[],e.multipleOf.includes(t)||e.multipleOf.push(t)},is=(e,t)=>{e.patterns??=new Set,e.patterns.add(t)},as=(e,t)=>{e.mime=e.mime?e.mime.filter(e=>t.includes(e)):[...t]},os=(e,t)=>{e.format=t,t.includes(`int`)&&(e.isInt=!0)},ss=(e,t)=>es(e,`minimum`,t.minimum),cs=(e,t)=>ts(e,`maximum`,t.maximum),ls=e=>(t,n)=>{os(t,n.format);let[r,i]=e[n.format];es(t,`minimum`,r),ts(t,`maximum`,i)},us={greater_than:(e,t)=>es(e,t.inclusive?`minimum`:`exclusiveMinimum`,t.value),less_than:(e,t)=>ts(e,t.inclusive?`maximum`:`exclusiveMaximum`,t.value),multiple_of:(e,t)=>rs(e,t.value),number_format:ls(gt),bigint_format:ls(_t),min_length:ss,max_length:cs,length_equals:(e,t)=>ns(e,t.length),min_size:ss,max_size:cs,size_equals:(e,t)=>ns(e,t.size),string_format:(e,t)=>{os(e,t.format),t.pattern&&is(e,t.pattern),(t.format===`base64`||t.format===`base64url`)&&(e.contentEncoding=t.format),(t.local||t.precision===-1)&&(e.laxFormat=!0)},mime_type:(e,t)=>as(e,t.mime)};function ds(e){let t={},n=e._zod.def,r=e._zod.traits.has(`$ZodCheck`)?[e,...n.checks??[]]:n.checks??[];for(let e of r)us[e._zod.def.check]?.(t,e._zod.def);let i=e._zod.bag;i.minimum!==void 0&&es(t,`minimum`,i.minimum),i.exclusiveMinimum!==void 0&&es(t,`exclusiveMinimum`,i.exclusiveMinimum),i.maximum!==void 0&&ts(t,`maximum`,i.maximum),i.exclusiveMaximum!==void 0&&ts(t,`exclusiveMaximum`,i.exclusiveMaximum),i.multipleOf!==void 0&&rs(t,i.multipleOf),i.format!==void 0&&(t.format??=i.format,i.format.includes(`int`)&&(t.isInt=!0)),i.mime&&as(t,i.mime);for(let e of i.patterns??[])is(t,e);return t}var fs={guid:`uuid`,url:`uri`,datetime:`date-time`,json_string:`json-string`,regex:``},ps=new Map([[gi,Qn],[vi,$n]]),ms=e=>ps.get(e)??e,hs=(e,t,n,r)=>{let i=n;i.type=`string`;let{minimum:a,maximum:o,format:s,patterns:c,contentEncoding:l,laxFormat:u}=ds(e);if(typeof a==`number`&&(i.minLength=a),typeof o==`number`&&(i.maxLength=o),s&&(i.format=fs[s]??s,i.format===``&&delete i.format,(s===`time`||u)&&delete i.format),l&&(i.contentEncoding=l),c&&c.size>0){let e=[...c].map(ms);e.length===1?i.pattern=e[0].source:e.length>1&&(i.allOf=[...e.map(e=>({...t.target===`draft-07`||t.target===`draft-04`||t.target===`openapi-3.0`?{type:`string`}:{},pattern:e.source}))])}},gs=(e,t,n,r)=>{let i=n,{minimum:a,maximum:o,multipleOf:s,exclusiveMaximum:c,exclusiveMinimum:l,isInt:u}=ds(e);i.type=u?`integer`:`number`;let d=typeof l==`number`&&l>=(a??-1/0),f=typeof c==`number`&&c<=(o??1/0),p=t.target===`draft-04`||t.target===`openapi-3.0`;if(d?p?(i.minimum=l,i.exclusiveMinimum=!0):i.exclusiveMinimum=l:typeof a==`number`&&(i.minimum=a),f?p?(i.maximum=c,i.exclusiveMaximum=!0):i.exclusiveMaximum=c:typeof o==`number`&&(i.maximum=o),s){let n=new Set;for(let a of s)Number.isFinite(a)&&a!==0?n.add(Math.abs(a)):Bo(e,t,i,r,`A multipleOf divisor of ${a} cannot be represented in JSON Schema`);let[a,...o]=n;a!==void 0&&(i.multipleOf=a),o.length&&(i.allOf=[...i.allOf??[],...o.map(e=>({multipleOf:e}))])}},_s=(e,t,n,r)=>{n.type=`boolean`},vs=(e,t,n,r)=>{n.not={}},ys=(e,t,n,r)=>{let i=e._zod.def,a=He(i.entries);if(a.length===0){n.not={};return}a.every(e=>typeof e==`number`)&&(n.type=`number`),a.every(e=>typeof e==`string`)&&(n.type=`string`),n.enum=a},bs=(e,t,n,r)=>{let i=e._zod.def;if(i.values.length===0){n.not={};return}let a=[];for(let o of i.values)if(o===void 0){if(Bo(e,t,n,r,"Literal `undefined` cannot be represented in JSON Schema"))return}else if(typeof o==`bigint`){if(Bo(e,t,n,r,`BigInt literals cannot be represented in JSON Schema`))return;a.push(Number(o))}else a.push(o);if(a.length!==0){if(a.length===1){let e=a[0];n.type=e===null?`null`:typeof e,t.target===`draft-04`||t.target===`openapi-3.0`?n.enum=[e]:n.const=e}else a.every(e=>typeof e==`number`)&&(n.type=`number`),a.every(e=>typeof e==`string`)&&(n.type=`string`),a.every(e=>typeof e==`boolean`)&&(n.type=`boolean`),a.every(e=>e===null)&&(n.type=`null`),n.enum=a}},xs=(e,t,n,r)=>{Bo(e,t,n,r,`Custom types cannot be represented in JSON Schema`)},Ss=(e,t,n,r)=>{Bo(e,t,n,r,`Transforms cannot be represented in JSON Schema`)},Cs=(e,t,n,r)=>{let i=n,a=e._zod.def,{minimum:o,maximum:s}=ds(e);typeof o==`number`&&(i.minItems=o),typeof s==`number`&&(i.maxItems=s),i.type=`array`,i.items=Vo(a.element,t,{...r,path:[...r.path,`items`]})};function ws(e){let t=e._zod.def;return t.type===`pipe`&&t.in._zod.traits.has(`$ZodTransform`)?ws(t.out):t.type===`catch`?ws(t.innerType):e._zod.optin}var Ts=(e,t,n,r)=>{let i=n,a=e._zod.def,o=a.shape;if(Object.getOwnPropertySymbols(o).length&&Bo(e,t,i,r,`Symbol keys cannot be represented in JSON Schema`))return;i.type=`object`,i.properties={};for(let e in o)Xe(i.properties,e,Vo(o[e],t,{...r,path:[...r.path,`properties`,e]}));let s=[];for(let e of Object.keys(o)){let n=a.shape[e];(t.io===`input`?ws(n)===void 0:n._zod.optout===void 0)&&s.push(e)}s.length>0&&(i.required=s),a.catchall?._zod.def.type===`never`?i.additionalProperties=!1:a.catchall?a.catchall&&(i.additionalProperties=Vo(a.catchall,t,{...r,path:[...r.path,`additionalProperties`]})):t.io===`output`&&(i.additionalProperties=!1)},Es=(e,t,n,r)=>{let i=e._zod.def,a=i.inclusive===!1,o=i.options.map((e,n)=>Vo(e,t,{...r,path:[...r.path,a?`oneOf`:`anyOf`,n]}));a?n.oneOf=o:n.anyOf=o},Ds=(e,t,n,r)=>{let i=e._zod.def,a=Vo(i.left,t,{...r,path:[...r.path,`allOf`,0]}),o=Vo(i.right,t,{...r,path:[...r.path,`allOf`,1]}),s=e=>`allOf`in e&&Object.keys(e).length===1,c=[...s(a)?a.allOf:[a],...s(o)?o.allOf:[o]];n.allOf=c,t.intersections.push(c)};function Os(e,t,n){if(t.$ref){if(n.has(t))return t;n.add(t);let r=e.get(t)?.def;if(!r)return t;let i=Os(e,r,n);return i===r?t:i}for(let r of[`anyOf`,`oneOf`]){let i=t[r];if(!Array.isArray(i))continue;let a=i.map(t=>Os(e,t,n));a.some((e,t)=>e!==i[t])&&(t={...t,[r]:a})}let r=Array.isArray(t.type)?t.type:[t.type],i=!r.includes(`string`)&&r.some(e=>e===`number`||e===`integer`),a=t.enum??(t.const===void 0?void 0:[t.const]);if(!i&&!a?.some(e=>typeof e==`number`))return t;let{minimum:o,maximum:s,exclusiveMinimum:c,exclusiveMaximum:l,multipleOf:u,format:d,id:f,...p}=t;return p.enum?p.enum=p.enum.map(e=>typeof e==`number`?String(e):e):typeof p.const==`number`&&(p.const=String(p.const)),i?(p.type=`string`,a||(p.pattern=(r.includes(`number`)?ur:lr).source),p):p}var ks=new WeakMap;function As(e){let t=new Map;for(let n of e.seen.values())n.def&&!t.has(n.schema)&&t.set(n.schema,n);let n=new Map;for(let r of ks.get(e)??[]){let i=e.seen.get(r),a=(i?.def??i?.schema)?.propertyNames;if(!a||a===!0||n.has(a))continue;let o=Os(t,a,new Set);o!==a&&n.set(a,o)}if(n.size)for(let t of e.seen.values())for(let e of[t.schema,t.def]){let t=e&&n.get(e.propertyNames);t&&(e.propertyNames=t)}}var js=(e,t,n,r)=>{let i=n,a=e._zod.def;i.type=`object`;let o=a.keyType,s=ds(o).patterns;if(a.mode===`loose`&&s&&s.size>0){let e=Vo(a.valueType,t,{...r,path:[...r.path,`patternProperties`,`*`]});i.patternProperties={};for(let t of s)Xe(i.patternProperties,ms(t).source,e)}else{if(t.target===`draft-07`||t.target===`draft-2020-12`){i.propertyNames=Vo(a.keyType,t,{...r,path:[...r.path,`propertyNames`]});let n=ks.get(t);n||(n=[],ks.set(t,n),t.deferred.push(()=>As(t))),n.push(e)}i.additionalProperties=Vo(a.valueType,t,{...r,path:[...r.path,`additionalProperties`]})}let c=o._zod.values,l=t.io===`input`&&ws(a.valueType)!==void 0;if(c&&!a.partial&&!l){let e=[...c].filter(e=>typeof e==`string`||typeof e==`number`);e.length>0&&(i.required=e.map(String))}},Ms=(e,t,n,r)=>{let i=e._zod.def,a=Vo(i.innerType,t,r),o=t.seen.get(e);t.target===`openapi-3.0`?(o.ref=i.innerType,n.nullable=!0):n.anyOf=[a,{type:`null`}]},Ns=(e,t,n,r)=>{let i=e._zod.def;Vo(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType},Ps=Symbol();function Fs(e,t,n,r,i){let a=!1,o=JSON.stringify(e,(e,t)=>typeof t==`bigint`?(a=!0,null):t);return a?(Bo(t,n,r,i,`BigInt defaults cannot be represented in JSON Schema`),Ps):JSON.parse(o)}var Is=(e,t,n,r)=>{let i=e._zod.def;Vo(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType;let o=Fs(i.defaultValue,e,t,n,r);o!==Ps&&(n.default=o)},Ls=(e,t,n,r)=>{let i=e._zod.def;Vo(i.innerType,t,r);let a=t.seen.get(e);if(a.ref=i.innerType,t.io!==`input`)return;let o=Fs(i.defaultValue,e,t,n,r);o!==Ps&&(n._prefault=o)},Rs=(e,t,n,r)=>{let i=e._zod.def;Vo(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType;let o;try{o=i.catchValue(void 0)}catch{Bo(e,t,n,r,`Dynamic catch values are not supported in JSON Schema`);return}n.default=o},zs=(e,t,n,r)=>{let i=e._zod.def,a=i.in._zod.traits.has(`$ZodTransform`),o=t.io===`input`?a?i.out:i.in:i.out;Vo(o,t,r);let s=t.seen.get(e);s.ref=o},Bs=(e,t,n,r)=>{let i=e._zod.def;Vo(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType,n.readOnly=!0},Vs=(e,t,n,r)=>{let i=e._zod.def;Vo(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType},Hs=new WeakSet([Object.prototype,Error.prototype]);function Us(e,t,n){Object.defineProperty(e,t,{configurable:!0,enumerable:!1,get(){let e=n(this);return Object.defineProperty(this,t,{value:e,configurable:!0,writable:!0}),e},set(e){Object.defineProperty(this,t,{value:e,configurable:!0,writable:!0})}})}var Ws=G(`ZodError`,(e,t)=>{fn.init(e,t),e.name=`ZodError`;let n=Object.getPrototypeOf(e);Hs.has(n)||(Hs.add(n),Us(n,`format`,e=>t=>hn(e,t)),Us(n,`flatten`,e=>t=>mn(e,t)),Us(n,`addIssue`,e=>t=>{e.issues.push(t),e.message=JSON.stringify(e.issues,We,2)}),Us(n,`addIssues`,e=>t=>{e.issues.push(...t),e.message=JSON.stringify(e.issues,We,2)}),Object.defineProperty(n,"isEmpty",{configurable:!0,enumerable:!1,get(){return this.issues.length===0}}))},void 0,{Parent:Error}),Gs=_n(Ws),Ks=vn(Ws),qs=yn(Ws),Js=xn(Ws),Ys=Dn(Ws),Xs=On(Ws),Zs=kn(Ws),Qs=An(Ws),$s=jn(Ws),ec=Mn(Ws),tc=Nn(Ws),nc=Pn(Ws);function rc(){rn.localeError||an(ka())}function ic(){rn.memoizer||an({memoizer:Ea()})}var ac=G(`ZodType`,(e,t)=>(rc(),Pr.init(e,t),e.def=t,e.type=t.type,e),{check(...e){let t=this.def;return this.clone(rt(t,{checks:[...t.checks??[],...e.map(e=>typeof e==`function`?{_zod:{check:e,def:{check:`custom`},onattach:[]}}:e)]}),{parent:!0})},with(...e){return this.check(...e)},clone(e,t){return pt(this,e,t)},brand(){return this},register(e,t){return e.add(this,t),this},refine(e,t){return this.check(Sl(e,t))},superRefine(e,t){return this.check(Cl(e,t))},overwrite(e){return this.check(Oo(e))},optional(){return il(this)},exactOptional(){return ol(this)},nullable(){return cl(this)},nullish(){return il(cl(this))},nonoptional(e){return ml(this,e)},array(){return Uc(this)},or(e){return Kc([this,e])},and(e){return Xc(this,e)},transform(e){return vl(this,nl(e))},default(e){return ul(this,e)},prefault(e){return fl(this,e)},catch(e){return gl(this,e)},pipe(e){return vl(this,e)},readonly(){return bl(this)},describe(e){let t=this.clone();return Na.add(t,{description:e}),t},meta(...e){if(e.length===0)return Na.get(this);let t=this.clone();return Na.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 Bt(this,`~standard`,{...Lr(this),jsonSchema:{input:$o(this,`input`),output:$o(this,`output`)}})},set"~standard"(e){zt(this,`~standard`,e)},parse:function e(t,n){return Gs(this,t,n,{callee:e})},parseAsync:async function e(t,n){return await Ks(this,t,n,{callee:e})},safeParse(e,t){return qs(this,e,t)},async safeParseAsync(e,t){return Js(this,e,t)},get spa(){return this?.safeParseAsync},set spa(e){zt(this,`spa`,e)},validate(e,t){return wn(this,e,t)},validateAsync(e,t){return En(this,e,t)},encode:function e(t,n){return Ys(this,t,n,{callee:e})},decode:function e(t,n){return Xs(this,t,n,{callee:e})},encodeAsync:async function e(t,n){return await Zs(this,t,n,{callee:e})},decodeAsync:async function e(t,n){return await Qs(this,t,n,{callee:e})},safeEncode(e,t){return $s(this,e,t)},safeDecode(e,t){return ec(this,e,t)},async safeEncodeAsync(e,t){return tc(this,e,t)},async safeDecodeAsync(e,t){return nc(this,e,t)},toJSONSchema(e){return Qo(this,{})(e)},get description(){return Na.get(this)?.description},get _def(){return this._zod.def}}),oc=G(`_ZodString`,(e,t)=>{Rr.init(e,t),ac.init(e,t),e._zod.processJSONSchema=(t,n,r)=>hs(e,t,n,r)},Vt({format:e=>ds(e).format??null,minLength:e=>ds(e).minimum??null,maxLength:e=>ds(e).maximum??null},{regex(...e){return this.check(So(...e))},includes(...e){return this.check(To(...e))},startsWith(...e){return this.check(Eo(...e))},endsWith(...e){return this.check(Do(...e))},min(...e){return this.check(bo(...e))},max(...e){return this.check(yo(...e))},length(...e){return this.check(xo(...e))},nonempty(...e){return this.check(bo(1,...e))},lowercase(e){return this.check(Co(e))},uppercase(e){return this.check(wo(e))},trim(){return this.check(Ao())},normalize(...e){return this.check(ko(...e))},toLowerCase(){return this.check(jo())},toUpperCase(){return this.check(Mo())},slugify(){return this.check(No())}})),sc=G(`ZodString`,(e,t)=>{Rr.init(e,t),oc.init(e,t)},{email(e){return this.check(Ia(pc,e))},url(e){return this.check(Ha(gc,e))},jwt(e){return this.check(ro(jc,e))},emoji(e){return this.check(Ua(_c,e))},guid(e){return this.check(La(mc,e))},uuid(e){return this.check(Ra(hc,e))},uuidv4(e){return this.check(za(hc,e))},uuidv6(e){return this.check(Ba(hc,e))},uuidv7(e){return this.check(Va(hc,e))},nanoid(e){return this.check(Wa(vc,e))},cuid(e){return this.check(Ga(yc,e))},cuid2(e){return this.check(Ka(bc,e))},ulid(e){return this.check(qa(xc,e))},base64(e){return this.check(eo(Oc,e))},base64url(e){return this.check(to(kc,e))},xid(e){return this.check(Ja(Sc,e))},ksuid(e){return this.check(Ya(Cc,e))},ipv4(e){return this.check(Xa(wc,e))},ipv6(e){return this.check(Za(Tc,e))},cidrv4(e){return this.check(Qa(Ec,e))},cidrv6(e){return this.check($a(Dc,e))},e164(e){return this.check(no(Ac,e))},datetime(e){return this.check(io(lc,e))},date(e){return this.check(ao(uc,e))},time(e){return this.check(oo(dc,e))},duration(e){return this.check(so(fc,e))}});function K(e){return Fa(sc,e)}var cc=G(`ZodStringFormat`,(e,t)=>{zr.init(e,t),oc.init(e,t)}),lc=G(`ZodISODateTime`,(e,t)=>{ii.init(e,t),cc.init(e,t)}),uc=G(`ZodISODate`,(e,t)=>{ai.init(e,t),cc.init(e,t)}),dc=G(`ZodISOTime`,(e,t)=>{oi.init(e,t),cc.init(e,t)}),fc=G(`ZodISODuration`,(e,t)=>{si.init(e,t),cc.init(e,t)}),pc=G(`ZodEmail`,(e,t)=>{Hr.init(e,t),cc.init(e,t)}),mc=G(`ZodGUID`,(e,t)=>{Br.init(e,t),cc.init(e,t)}),hc=G(`ZodUUID`,(e,t)=>{Vr.init(e,t),cc.init(e,t)}),gc=G(`ZodURL`,(e,t)=>{Xr.init(e,t),cc.init(e,t)}),_c=G(`ZodEmoji`,(e,t)=>{Zr.init(e,t),cc.init(e,t)}),vc=G(`ZodNanoID`,(e,t)=>{Qr.init(e,t),cc.init(e,t)}),yc=G(`ZodCUID`,(e,t)=>{$r.init(e,t),cc.init(e,t)}),bc=G(`ZodCUID2`,(e,t)=>{ei.init(e,t),cc.init(e,t)}),xc=G(`ZodULID`,(e,t)=>{ti.init(e,t),cc.init(e,t)}),Sc=G(`ZodXID`,(e,t)=>{ni.init(e,t),cc.init(e,t)}),Cc=G(`ZodKSUID`,(e,t)=>{ri.init(e,t),cc.init(e,t)}),wc=G(`ZodIPv4`,(e,t)=>{ci.init(e,t),cc.init(e,t)}),Tc=G(`ZodIPv6`,(e,t)=>{di.init(e,t),cc.init(e,t)}),Ec=G(`ZodCIDRv4`,(e,t)=>{fi.init(e,t),cc.init(e,t)}),Dc=G(`ZodCIDRv6`,(e,t)=>{mi.init(e,t),cc.init(e,t)}),Oc=G(`ZodBase64`,(e,t)=>{_i.init(e,t),cc.init(e,t)}),kc=G(`ZodBase64URL`,(e,t)=>{bi.init(e,t),cc.init(e,t)}),Ac=G(`ZodE164`,(e,t)=>{xi.init(e,t),cc.init(e,t)}),jc=G(`ZodJWT`,(e,t)=>{Ci.init(e,t),cc.init(e,t)}),Mc=G(`ZodNumber`,(e,t)=>{wi.init(e,t),ac.init(e,t),e._zod.processJSONSchema=(t,n,r)=>gs(e,t,n,r),e.isFinite=!0},Vt({minValue:e=>{let{minimum:t,exclusiveMinimum:n}=ds(e);return Math.max(t??-1/0,n??-1/0)},maxValue:e=>{let{maximum:t,exclusiveMaximum:n}=ds(e);return Math.min(t??1/0,n??1/0)},isInt:e=>{let{isInt:t,multipleOf:n}=ds(e);return!!t||!!n?.some(Number.isSafeInteger)},format:e=>ds(e).format??null},{gt(e,t){return this.check(go(e,t))},gte(e,t){return this.check(_o(e,t))},min(e,t){return this.check(_o(e,t))},lt(e,t){return this.check(mo(e,t))},lte(e,t){return this.check(ho(e,t))},max(e,t){return this.check(ho(e,t))},int(e){return this.check(Fc(e))},safe(e){return this.check(Fc(e))},positive(e){return this.check(go(0,e))},nonnegative(e){return this.check(_o(0,e))},negative(e){return this.check(mo(0,e))},nonpositive(e){return this.check(ho(0,e))},multipleOf(e,t){return this.check(vo(e,t))},step(e,t){return this.check(vo(e,t))},finite(){return this}}));function Nc(e){return co(Mc,e)}var Pc=G(`ZodNumberFormat`,(e,t)=>{Ti.init(e,t),Mc.init(e,t)});function Fc(e){return lo(Pc,e)}var Ic=G(`ZodBoolean`,(e,t)=>{Ei.init(e,t),ac.init(e,t),e._zod.processJSONSchema=(t,n,r)=>_s(e,t,n,r)});function Lc(e){return uo(Ic,e)}var Rc=G(`ZodUnknown`,(e,t)=>{Di.init(e,t),ac.init(e,t),e._zod.processJSONSchema=(e,t,n)=>void 0});function zc(){return fo(Rc)}var Bc=G(`ZodNever`,(e,t)=>{Oi.init(e,t),ac.init(e,t),e._zod.processJSONSchema=(t,n,r)=>vs(e,t,n,r)});function Vc(e){return po(Bc,e)}var Hc=G(`ZodArray`,(e,t)=>{ic(),Ai.init(e,t),ac.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Cs(e,t,n,r),e.element=t.element},{min(e,t){return this.check(bo(e,t))},nonempty(e){return this.check(bo(1,e))},max(e,t){return this.check(yo(e,t))},length(e,t){return this.check(xo(e,t))},unwrap(){return this.element}});function Uc(e,t){return Po(Hc,e,t)}var Wc=G(`ZodObject`,(e,t)=>{ic(),Ii.init(e,t),ac.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Ts(e,t,n,r),Jt(e,`shape`,e=>e._zod.def.shape,!1)},{keyof(){return J(Object.keys(this._zod.def.shape))},catchall(e){return this.clone(rt(this._zod.def,{catchall:e}))},passthrough(){return this.clone(rt(this._zod.def,{catchall:zc()}))},loose(){return this.clone(rt(this._zod.def,{catchall:zc()}))},strict(){return this.clone(rt(this._zod.def,{catchall:Vc()}))},strip(){return this.clone(rt(this._zod.def,{catchall:void 0}))},extend(e){return xt(this,e)},safeExtend(e){return Ct(this,e)},merge(e){return wt(this,e)},pick(e){return vt(this,e)},omit(e){return bt(this,e)},partial(...e){return Tt(rl,this,e[0])},exactPartial(...e){return Tt(al,this,e[0],`exactPartial`)},required(...e){return Et(pl,this,e[0])}});function q(e,t){return new Wc({type:`object`,shape:e??{},...W(t)})}var Gc=G(`ZodUnion`,(e,t)=>{Ri.init(e,t),ac.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Es(e,t,n,r),e.options=t.options});function Kc(e,t){return new Gc({type:`union`,options:e,...W(t)})}var qc=G(`ZodDiscriminatedUnion`,(e,t)=>{Gc.init(e,t),Bi.init(e,t)});function Jc(e,t,n){return new qc({type:`union`,options:t,discriminator:e,...W(n)})}var Yc=G(`ZodIntersection`,(e,t)=>{Vi.init(e,t),ac.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Ds(e,t,n,r)});function Xc(e,t){return new Yc({type:`intersection`,left:e,right:t})}var Zc=G(`ZodRecord`,(e,t)=>{ic(),Wi.init(e,t),ac.init(e,t),e._zod.processJSONSchema=(t,n,r)=>js(e,t,n,r),e.keyType=t.keyType,e.valueType=t.valueType});function Qc(e,t,n){return!t||!t._zod?new Zc({type:`record`,keyType:K(),valueType:e,...W(t)}):new Zc({type:`record`,keyType:e,valueType:t,...W(n)})}var $c=G(`ZodEnum`,(e,t)=>{Gi.init(e,t),ac.init(e,t),e._zod.processJSONSchema=(t,n,r)=>ys(e,t,n,r),e.enum=t.entries,e.options=[...e._zod.values];let n=new Set(Object.keys(t.entries));e.extract=(e,r)=>{let i={};for(let r of e)if(n.has(r))i[r]=t.entries[r];else throw Error(`Key ${r} not found in enum`);return new $c({...t,checks:[],...W(r),entries:i})},e.exclude=(e,r)=>{let i={...t.entries};for(let t of e)if(n.has(t))delete i[t];else throw Error(`Key ${t} not found in enum`);return new $c({...t,checks:[],...W(r),entries:i})}});function J(e,t){return new $c({type:`enum`,entries:Array.isArray(e)?Object.fromEntries(e.map(e=>[e,e])):e,...W(t)})}var el=G(`ZodLiteral`,(e,t)=>{Ki.init(e,t),ac.init(e,t),e._zod.processJSONSchema=(t,n,r)=>bs(e,t,n,r),e.values=new Set(t.values),Object.defineProperty(e,"value",{get(){if(t.values.length>1)throw Error("This schema contains multiple valid literal values. Use `.values` instead.");return t.values[0]}})});function Y(e,t){return new el({type:`literal`,values:Array.isArray(e)?e:[e],...W(t)})}var tl=G(`ZodTransform`,(e,t)=>{ic(),qi.init(e,t),ac.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Ss(e,t,n,r),e._zod.parse=(n,r)=>{if(r.direction===`backward`)throw new nn(e.constructor.name);n.addIssue=r=>{if(typeof r==`string`)n.issues.push(Lt(r,n.value,t));else{let t=r;t.fatal&&(t.continue=!1),t.code??=`custom`,`input`in t||(t.input=n.value),t.inst??=e,n.issues.push(Lt(t))}};let i=t.transform(n.value,n);return i instanceof Promise?i.then(e=>(n.value=e,n)):(n.value=i,n)}});function nl(e){return new tl({type:`transform`,transform:e})}var rl=G(`ZodOptional`,(e,t)=>{Yi.init(e,t),ac.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Vs(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function il(e){return new rl({type:`optional`,innerType:e})}var al=G(`ZodExactOptional`,(e,t)=>{Xi.init(e,t),ac.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Vs(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function ol(e){return new al({type:`optional`,innerType:e})}var sl=G(`ZodNullable`,(e,t)=>{Zi.init(e,t),ac.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Ms(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function cl(e){return new sl({type:`nullable`,innerType:e})}var ll=G(`ZodDefault`,(e,t)=>{Qi.init(e,t),ac.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Is(e,t,n,r),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function ul(e,t){return new ll({type:`default`,innerType:e,get defaultValue(){return typeof t==`function`?t():ut(t)}})}var dl=G(`ZodPrefault`,(e,t)=>{ea.init(e,t),ac.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Ls(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function fl(e,t){return new dl({type:`prefault`,innerType:e,get defaultValue(){return typeof t==`function`?t():ut(t)}})}var pl=G(`ZodNonOptional`,(e,t)=>{ta.init(e,t),ac.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Ns(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function ml(e,t){return new pl({type:`nonoptional`,innerType:e,...W(t)})}var hl=G(`ZodCatch`,(e,t)=>{ia.init(e,t),ac.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Rs(e,t,n,r),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function gl(e,t){return new hl({type:`catch`,innerType:e,catchValue:typeof t==`function`?t:Xt(t)})}var _l=G(`ZodPipe`,(e,t)=>{aa.init(e,t),ac.init(e,t),e._zod.processJSONSchema=(t,n,r)=>zs(e,t,n,r),e.in=t.in,e.out=t.out});function vl(e,t){return new _l({type:`pipe`,in:e,out:t})}var yl=G(`ZodReadonly`,(e,t)=>{sa.init(e,t),ac.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Bs(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function bl(e){return new yl({type:`readonly`,innerType:e})}var xl=G(`ZodCustom`,(e,t)=>{la.init(e,t),ac.init(e,t),e._zod.processJSONSchema=(t,n,r)=>xs(e,t,n,r)});function Sl(e,t={}){return Fo(xl,e,t)}function Cl(e,t){return Io(e,t)}var wl=J([`T0`,`T1`,`T2`,`T3`]);J([`owner`,`guest`,`member`,`voice-device`]);var Tl=Nc().min(0).max(1),El=Kc([J([`auto`,`center`,`left`,`right`,`top`,`bottom`]),q({x:Tl,y:Tl,w:Tl,h:Tl})]),Dl=J([`ambient`,`conversation`,`focus`,`multi`]),Ol=J([`idle`,`listening`,`thinking`,`speaking`]),kl=J([`sphere`,`orb`,`ring`]),Al=q({id:K().min(1).max(64),type:J([`card`,`stat`,`list`,`table`,`code`,`chart`,`gauge`,`timeline`,`graph`,`sandbox`,`markdown`,`image`,`video`,`pdf`,`gallery`,`group`,`tabs`,`progress`,`checklist`,`countdown`,`kv`]),props:Qc(K(),zc()),placement:El,ttl:Nc().positive().max(3600).optional(),style:J([`glass`,`alert`]).optional(),layer:J([`base`,`overlay`]).optional(),pinned:Lc().optional()}),jl=Jc(`cmd`,[q({cmd:Y(`scene`),mode:Dl}),q({cmd:Y(`show`),object:Al}),q({cmd:Y(`update`),id:K(),props:Qc(K(),zc())}),q({cmd:Y(`hide`),id:K()}),q({cmd:Y(`clear`)}),q({cmd:Y(`pin`),id:K()}),q({cmd:Y(`unpin`),id:K()}),q({cmd:Y(`place`),id:K(),placement:El}),q({cmd:Y(`presence`),state:Ol.optional(),style:kl.optional()}),q({cmd:Y(`mood`),accent:K().max(16).optional(),intensity:Tl.optional()})]),Ml=q({scene:Dl,objects:Uc(Al),presence:q({state:Ol,style:kl}),mood:q({accent:K(),intensity:Tl})}),Nl={center:[20,18,60,58],left:[3,12,30,70],right:[67,12,30,70],top:[20,4,60,30],bottom:[20,62,60,30]};Object.keys(Nl);var Pl=[{id:`en_US-amy-medium`,name:`Amy`,gender:`female`,accent:`American`},{id:`en_US-kristin-medium`,name:`Kristin`,gender:`female`,accent:`American`},{id:`en_US-hfc_female-medium`,name:`Hannah`,gender:`female`,accent:`American`,note:`clear and steady`},{id:`en_GB-jenny_dioco-medium`,name:`Jenny`,gender:`female`,accent:`British`},{id:`en_GB-alba-medium`,name:`Alba`,gender:`female`,accent:`Scottish`},{id:`en_US-kathleen-low`,name:`Kathleen`,gender:`female`,accent:`American`,note:`smaller and faster`},{id:`en_US-ryan-medium`,name:`Ryan`,gender:`male`,accent:`American`},{id:`en_US-joe-medium`,name:`Joe`,gender:`male`,accent:`American`},{id:`en_US-norman-medium`,name:`Norman`,gender:`male`,accent:`American`},{id:`en_US-hfc_male-medium`,name:`Henry`,gender:`male`,accent:`American`,note:`clear and steady`},{id:`en_GB-alan-medium`,name:`Alan`,gender:`male`,accent:`British`},{id:`en_GB-northern_english_male-medium`,name:`Tom`,gender:`male`,accent:`Northern English`}],Fl=[{id:`hi_IN-priyamvada-medium`,name:`Priyamvada`,gender:`female`,accent:`Hindi`,note:`for personal use (non-commercial licence)`},{id:`hi_IN-pratham-medium`,name:`Pratham`,gender:`male`,accent:`Hindi`,note:`for personal use (non-commercial licence)`},{id:`hi_IN-rohan-medium`,name:`Rohan`,gender:`male`,accent:`Hindi`}],Il=[{id:`mr_IN-google-medium`,name:`Marathi`,gender:`female`,accent:`Marathi`}],Ll={id:`en_US-lessac-medium`,name:`Lessac`,accent:`American`,note:`the original voice`},Rl=e=>e===Ll.id||Pl.some(t=>t.id===e),zl=[{id:`aurora`,name:`Aurora`,style:`sphere`,accent:`#3fd8ff`,intensity:.6},{id:`ocean`,name:`Ocean`,style:`sphere`,accent:`#2b7bff`,intensity:.6},{id:`ember`,name:`Ember`,style:`orb`,accent:`#ff9b3d`,intensity:.7},{id:`violet`,name:`Violet storm`,style:`orb`,accent:`#a066ff`,intensity:.8},{id:`matrix`,name:`Matrix`,style:`ring`,accent:`#3dff8c`,intensity:.6},{id:`rose`,name:`Rose`,style:`ring`,accent:`#ff6fae`,intensity:.7},{id:`ghost`,name:`Ghost`,style:`sphere`,accent:`#e8f4ff`,intensity:.4}],Bl=[`local`,`spotify`,`soundcloud`,`audius`],Vl=/^[0-9a-f]{16}$/,Hl=/^[0-9]{1,20}$/,Ul=/^[A-Za-z0-9_-]{1,64}$/;function Wl(e){if(typeof e!=`string`)return null;if(Vl.test(e))return{source:`local`,id:e};let t=e.indexOf(`:`);if(t<1)return null;let n=e.slice(0,t),r=e.slice(t+1);return!Bl.includes(n)||!(n===`local`?Vl:n===`soundcloud`?Hl:Ul).test(r)?null:{source:n,id:r}}var Gl=J([`minimal`,`companion`,`workspace`]),Kl=q({size:Nc().min(.5).max(1.5),reactivity:Nc().min(0).max(1),ambient:Lc(),captions:Lc(),captionSize:J([`small`,`medium`,`large`])}),ql={width:Nc().int().min(100).max(1e4),height:Nc().int().min(100).max(1e4),kind:J([`phone`,`tablet`,`desktop`]),orientation:J([`portrait`,`landscape`]),touch:Lc()};q(ql);var Jl=q({id:K(),tool:K(),summary:K(),tier:wl,needsPin:Lc()}),Yl=q({id:K().refine(e=>Wl(e)!==null,`A track id or a source:id ref`),title:K().max(200),artist:K().max(200),album:K().max(200),durationSec:Nc().nullable()}),Xl=q({playing:Lc(),trackId:K().max(80).nullable(),title:K().max(200),artist:K().max(200),album:K().max(200),position:Nc().min(0),duration:Nc().min(0),volume:Nc().min(0).max(100),muted:Lc(),shuffle:Lc(),repeat:J([`off`,`all`,`one`]),view:J([`mini`,`full`,`hidden`]),queue:Uc(q({id:K().max(80),title:K().max(200)})).max(50),index:Nc().int().min(-1),active:Lc()}),Zl=q({action:J([`play`,`pause`,`resume`,`toggle`,`stop`,`next`,`previous`,`seek`,`volume`,`mute`,`shuffle`,`repeat`,`view`,`queue.remove`,`queue.clear`,`jump`]),tracks:Uc(Yl).max(500).optional(),mode:J([`replace`,`add`,`next`,`off`,`all`,`one`]).optional(),shuffle:Lc().optional(),seconds:Nc().min(0).optional(),percent:Nc().min(0).max(100).optional(),level:Nc().min(0).max(100).optional(),delta:Nc().min(-100).max(100).optional(),on:Lc().optional(),view:J([`mini`,`full`,`hidden`]).optional(),index:Nc().int().min(0).optional()}),Ql=q({terminalLabel:K().max(24),clock:q({hour12:Lc(),seconds:Lc(),locale:K().max(35)}),launcher:Uc(q({id:K().max(20),label:K().max(24),icon:K().max(16),action:q({type:J([`url`,`prompt`,`panel`,`music`]),value:K().max(500)})})).max(12),animations:J([`full`,`reduced`,`off`])}),$l=q({folderSet:Lc(),volume:Nc().min(0).max(100),shuffle:Lc(),repeat:J([`off`,`all`,`one`]),visualizer:Lc(),startView:J([`mini`,`full`]),output:J([`screen`,`host`]).optional()}),eu=Jc(`type`,[q({type:Y(`music.command`)}).merge(Zl),q({type:Y(`music.host`),state:Xl}),q({type:Y(`stage`),command:jl}),q({type:Y(`caption.delta`),text:K()}),q({type:Y(`caption.end`)}),q({type:Y(`approval.request`)}).merge(Jl),q({type:Y(`approval.resolved`),id:K()}),q({type:Y(`alert`),level:J([`info`,`warn`,`error`]),text:K()}),q({type:Y(`chat.user`),text:K()}),q({type:Y(`ui`),view:Gl,look:Kl.optional(),ownerName:K().max(40).optional(),assistantName:K().max(40).optional(),hud:Ql.optional(),music:$l.optional()}),q({type:Y(`activity`),text:K().max(80).nullable()}),q({type:Y(`status`),busy:Lc(),deviceOnline:Lc(),voiceAvailable:Lc().optional(),voiceEnrolled:Lc().optional(),message:K().optional()}),q({type:Y(`voice.heard`),text:K(),trust:J([`owner`,`guest`,`unverified`,`member`]).optional(),speaker:K().max(60).optional()}),q({type:Y(`voice.challenge`),id:K(),text:K()}),q({type:Y(`voice.challenge.end`),id:K()}),q({type:Y(`audio.chunk`),id:K(),seq:Nc().int().min(0),last:Lc(),mime:K(),data:K()}),q({type:Y(`audio.stop`)}),q({type:Y(`camera.request`),id:K()}),q({type:Y(`camera.cancel`),id:K()}),q({type:Y(`ui.open`),panel:Y(`plugins`),integration:K().max(40).optional()}),q({type:Y(`screen.request`),id:K()}),q({type:Y(`screen.cancel`),id:K()}),q({type:Y(`snapshot`),stage:Ml,pendingApproval:Jl.nullable().optional()}),q({type:Y(`error`),message:K()})]),tu=q({type:Y(`approval.respond`),id:K(),decision:J([`approve`,`deny`,`approve_always`]),pin:K().max(32).optional()});Jc(`type`,[q({type:Y(`chat.send`),text:K().min(1).max(8e3)}),q({type:Y(`stage.event`),objectId:K(),event:K().max(64)}),tu,q({type:Y(`voice.interrupt`)}),q({type:Y(`voice.confirm`),id:K(),pin:K().max(32)}),q({type:Y(`voice.cancel`),id:K()}),q({type:Y(`camera.denied`),id:K(),reason:J([`off`,`no-camera`,`permission`,`busy`])}),q({type:Y(`screen.denied`),id:K(),reason:J([`unsupported`,`failed`,`busy`])}),q({type:Y(`ui.panels`),open:Uc(J([`chat`,`tasks`])).max(2)}),q({type:Y(`ui.screen`),...ql}),q({type:Y(`stage.move`),objectId:K().max(64),rect:q({x:Nc().min(0).max(1),y:Nc().min(0).max(1),w:Nc().min(0).max(1),h:Nc().min(0).max(1)})}),q({type:Y(`stage.pin`),objectId:K().max(64),pinned:Lc()}),q({type:Y(`music.state`),state:Xl}),q({type:Y(`music.remote`),command:Zl}),q({type:Y(`ping`)})]),q({type:Y(`tool.exec`),id:K(),tool:K(),args:zc(),approvedOutside:Lc().optional()}),Jc(`type`,[q({type:Y(`tool.result`),id:K(),result:q({output:K(),truncated:Lc()})}),q({type:Y(`tool.error`),id:K(),error:K()})]),q({path:K()}),q({path:K()}),q({path:K(),content:K()}),q({}),q({}),q({command:K().min(1),cwd:K().optional()}),q({city:K().min(1).max(80)}),q({plugin:K().min(1).max(40),name:K().min(1).max(40)}),q({language:J([`python`,`node`,`shell`]),code:K().min(1).max(5e4),timeoutSec:Nc().int().min(1).max(60).optional()}),q({text:K().min(1).max(4e3)}),q({query:K().min(1).max(200)}),q({id:Nc().int().positive()}),q({title:K().min(1).max(1e3),inMinutes:Nc().int().min(1).max(525600).optional(),dueAt:K().max(40).optional(),repeat:J([`hourly`,`daily`,`weekly`]).optional()}),q({}),q({id:Nc().int().positive()}),q({id:Nc().int().positive()}),q({}),q({path:K().min(1).max(1e3),id:K().min(1).max(64).optional(),title:K().max(120).optional(),placement:El.optional()}),q({}),q({}),q({id:K().min(1).max(40)}),q({id:J([`telegram`,`twilio`,`zerodha`,`alexa`]).optional()}),q({id:J([`telegram`,`twilio`,`zerodha`,`alexa`]),enabled:Lc().optional(),accountSid:K().max(64).optional(),smsFrom:K().max(30).optional(),whatsappFrom:K().max(30).optional(),ownerNumber:K().max(30).optional()}).strict(),q({id:J([`telegram`,`twilio`,`zerodha`,`alexa`])}),q({id:J([`telegram`,`twilio`,`zerodha`,`alexa`])}),q({channel:J([`telegram`,`sms`,`whatsapp`]),to:K().min(1).max(40),text:K().min(1).max(1500)}),q({channel:J([`telegram`,`whatsapp`]),to:Y(`me`),path:K().min(1).max(500),caption:K().max(1e3).optional()}).strict(),q({channel:J([`telegram`,`sms`,`whatsapp`]).optional(),unread:Lc().optional(),limit:Nc().int().min(1).max(20).optional()}),q({}).strict(),q({}).strict(),q({}).strict(),q({}).strict(),q({}).strict(),q({}).strict(),q({kind:J([`morning`,`close`,`custom`]).optional(),send:Lc().optional()}).strict(),q({name:K().min(1).max(60),kind:J([`morning`,`close`,`custom`]),time:K().regex(/^([01]\d|2[0-3]):[0-5]\d$/),days:Uc(Nc().int().min(1).max(7)).min(1).max(7).optional(),channel:J([`telegram`,`whatsapp`,`sms`]),commentary:Lc().optional()}).strict(),q({}).strict(),q({id:Nc().int().min(1)}).strict(),q({query:K().max(200).optional(),title:K().max(200).optional(),artist:K().max(200).optional(),album:K().max(200).optional(),shuffle:Lc().optional(),mode:J([`replace`,`add`,`next`]).optional(),limit:Nc().int().min(1).max(500).optional(),source:J([`local`,`spotify`,`soundcloud`,`audius`,`any`]).optional()}).strict(),q({action:J([`pause`,`resume`,`toggle`,`stop`,`next`,`previous`,`seek`,`volume`,`mute`,`shuffle`,`repeat`,`view`]),level:Nc().min(0).max(100).optional(),delta:Nc().min(-100).max(100).optional(),seconds:Nc().min(0).optional(),percent:Nc().min(0).max(100).optional(),on:Lc().optional(),mode:J([`off`,`all`,`one`]).optional(),view:J([`mini`,`full`,`hidden`]).optional()}).strict(),q({action:J([`add`,`remove`,`clear`,`show`]),query:K().max(200).optional(),index:Nc().int().min(1).optional(),source:J([`local`,`spotify`,`soundcloud`,`audius`,`any`]).optional()}).strict(),q({query:K().max(200),limit:Nc().int().min(1).max(15).optional(),source:J([`local`,`spotify`,`soundcloud`,`audius`,`any`]).optional()}).strict(),q({}).strict(),q({url:K().max(2e3).optional(),query:K().max(200).optional(),output:J([`screen`,`host`]).optional(),start:Nc().min(0).max(86400).optional(),mode:J([`embed`,`stream`]).optional()}).strict(),q({action:J([`pause`,`resume`,`stop`,`seek`,`volume`]),seconds:Nc().min(0).max(86400).optional(),level:Nc().min(0).max(100).optional()}).strict(),q({}).strict(),q({}),q({settings:Qc(K(),zc())}),q({style:kl.optional(),accent:K().regex(/^#[0-9a-fA-F]{6}$/).optional(),intensity:Nc().min(0).max(1).optional(),size:Nc().min(.5).max(1.5).optional(),reactivity:Nc().min(0).max(1).optional(),ambient:Lc().optional(),captions:Lc().optional(),captionSize:J([`small`,`medium`,`large`]).optional()}),q({view:Gl}),q({}),q({id:K().min(1).max(16),name:K().min(1).max(60),kind:J([`stdio`,`http`]),command:K().max(260).optional(),args:Uc(K().max(500)).max(20).optional(),url:K().max(2e3).optional()}),q({id:K().min(1).max(16)}),q({id:K().min(1).max(16)}),q({id:K().min(1).max(16)}),q({id:K().min(1).max(16)}),q({}),q({id:K().min(1).max(40),name:K().min(1).max(80),description:K().max(500).optional(),skills:Uc(q({name:K().min(1).max(40),description:K().min(1).max(300),text:K().min(1).max(2e4)})).max(10).optional(),tools:Uc(q({name:K().min(1).max(40),description:K().min(1).max(500),language:J([`python`,`node`,`shell`]),code:K().min(1).max(5e4),parameters:Qc(K(),q({type:J([`string`,`number`,`integer`,`boolean`]),description:K().max(300).optional(),enum:Uc(K().max(100)).max(50).optional()})).optional(),required:Uc(K()).optional()})).max(10).optional()}),q({}),q({id:K().min(1).max(40)}),q({id:K().min(1).max(40)}),q({id:K().min(1).max(40)}),q({mode:Dl}),q({object:Al}),q({topic:J([`all`,`widgets`,`layout`,`overlay`,`theme`,`files`,`recipes`]).optional()}),q({id:K(),props:Qc(K(),zc())}),q({id:K()}),q({}),q({id:K()}),q({id:K()}),q({state:Ol.optional(),style:kl.optional()}),q({accent:K().max(16).optional(),intensity:Nc().min(0).max(1).optional()});var nu=new Set([`alexa`,`amazon`,`echo`,`skill`,`app`,`ask`,`tell`,`open`,`start`,`run`,`enable`,`launch`,`load`,`begin`,`use`]),ru=50;function iu(e){let t=e.trim().split(/\s+/).filter(Boolean);if(t.length<1)return`Enter the name you will say after "Alexa, ask".`;if(e.length>ru)return`That is too long (at most ${ru} characters).`;if(!/^[a-z' ]+$/.test(e))return`Use lower-case letters, spaces and apostrophes only. Spell numbers out as words.`;let n=t.find(e=>nu.has(e));return n?`The word "${n}" cannot be in the name (it is reserved by Alexa).`:null}var au=[`mp3`,`m4a`,`aac`,`ogg`,`opus`,`wav`,`flac`],ou={maxTracks:{min:100,max:5e4,def:5e3},scanDepth:{min:1,max:12,def:6},volume:{min:0,max:100,def:70},searchLimit:{min:3,max:50,def:10}},su=[`chat`,`tasks`,`plugins`,`settings`,`music`],cu=[`toggle`,`play`,`pause`,`next`,`previous`],lu=[`url`,`prompt`,`panel`,`music`];function uu(e){let t=e&&typeof e==`object`?e:null;if(!t)return`A button needs a label and an action.`;let n=typeof t.label==`string`?t.label.trim():``;if(n.length<1||n.length>24)return`A button label is 1 to 24 characters.`;let r=typeof t.icon==`string`?t.icon.trim():``;if(r.length<1||[...r].length>4)return`A button icon is 1 to 4 characters (a symbol or an emoji).`;let i=t.action&&typeof t.action==`object`?t.action:null;if(!i||!lu.includes(i.type)||typeof i.value!=`string`)return`A button needs an action: an address, a question, a panel or a music control.`;let a=i.value.trim();switch(i.type){case`url`:if(a.length>500)return`A button address is at most 500 characters.`;try{let e=new URL(a);return e.protocol===`https:`||e.protocol===`http:`?null:`A button address must start with https:// or http://.`}catch{return`A button address must start with https:// or http://.`}case`prompt`:return a.length>=1&&a.length<=500?null:`A question for the assistant is 1 to 500 characters.`;case`panel`:return su.includes(a)?null:`A panel is one of: ${su.join(`, `)}.`;default:return cu.includes(a)?null:`A music control is one of: ${cu.join(`, `)}.`}}function du(e){return e===``?null:e.length>260?`That program name is too long.`:/\s/.test(e)?`Use the program's name, or a short path with no spaces (or add the program to your PATH). Arguments cannot be added here.`:e.startsWith(`-`)||!/^[A-Za-z0-9._:\\/~+-]+$/.test(e)?`A program is a name or a path made of letters, digits and . _ : / \\ ~ + - only, and cannot start with a dash.`:null}var fu=2e3,pu=3,mu=e=>({queue:[],index:-1,playing:!1,position:0,duration:0,volume:e.volume,muted:!1,shuffle:e.shuffle,repeat:e.repeat,view:e.view});function hu(e,t=Math.random){let n=[...e];for(let e=n.length-1;e>0;e--){let r=Math.floor(t()*(e+1));[n[e],n[r]]=[n[r],n[e]]}return n}var gu=(e,t,n)=>Math.min(n,Math.max(t,e)),_u=(e,t,n)=>({...e,index:t,playing:n,position:0,duration:0});function vu(e,t,n={}){let r=n.shuffle??hu,i=e.queue.length-1;switch(t.type){case`play`:{if(t.tracks.length===0)return e;let n=t.tracks.slice(0,fu);if(t.mode===`replace`){let i=t.shuffle?r(n):n;return{..._u(e,t.shuffle?0:gu(t.start??0,0,i.length-1),!0),queue:i,shuffle:t.shuffle?!0:e.shuffle}}if(e.queue.length===0)return{..._u(e,0,!0),queue:n};let i=t.mode===`next`?e.index+1:e.queue.length;return{...e,queue:[...e.queue.slice(0,i),...n,...e.queue.slice(i)].slice(0,fu)}}case`next`:return i<0?e:e.index<i?_u(e,e.index+1,!0):e.repeat===`off`?{...e,playing:!1,position:0}:_u(e,0,!0);case`previous`:return i<0?e:e.position>pu?{...e,position:0}:e.index>0?_u(e,e.index-1,e.playing||!0):e.repeat===`all`?_u(e,i,!0):{...e,position:0};case`ended`:return i<0?e:e.repeat===`one`?_u(e,e.index,!0):e.index<i?_u(e,e.index+1,!0):e.repeat===`all`?_u(e,0,!0):{...e,playing:!1,position:0};case`failed`:return i<0?e:e.index<i?_u(e,e.index+1,!0):{...e,playing:!1,position:0};case`pause`:return e.playing?{...e,playing:!1}:e;case`resume`:return e.index>=0&&!e.playing?{...e,playing:!0}:e;case`toggle`:return e.index<0?e:{...e,playing:!e.playing};case`stop`:return{...e,playing:!1,position:0};case`volume`:{let n=typeof t.level==`number`?Math.round(t.level):typeof t.delta==`number`?e.volume+Math.round(t.delta):e.volume;return{...e,volume:gu(n,0,100),muted:typeof t.level==`number`||(t.delta??0)>0?!1:e.muted}}case`mute`:return{...e,muted:t.on??!e.muted};case`seek`:{let n=typeof t.seconds==`number`?t.seconds:typeof t.percent==`number`?e.duration*gu(t.percent,0,100)/100:e.position;return{...e,position:gu(n,0,e.duration>0?e.duration:Math.max(n,0))}}case`repeat`:return{...e,repeat:t.mode};case`shuffle`:{if(!(t.on??!e.shuffle))return{...e,shuffle:!1};let n=e.queue.slice(0,e.index+1);return{...e,shuffle:!0,queue:[...n,...r(e.queue.slice(e.index+1))]}}case`view`:return{...e,view:t.view};case`remove`:{if(!Number.isInteger(t.index)||t.index<0||t.index>i)return e;let n=e.queue.filter((e,n)=>n!==t.index);return n.length===0?{...e,queue:n,index:-1,playing:!1,position:0,duration:0}:t.index<e.index?{...e,queue:n,index:e.index-1}:t.index>e.index?{...e,queue:n}:t.index<n.length?{..._u(e,t.index,e.playing),queue:n}:e.repeat===`all`?{..._u(e,0,e.playing),queue:n}:{...e,queue:n,index:n.length-1,playing:!1,position:0}}case`clear`:return{...e,queue:[],index:-1,playing:!1,position:0,duration:0};case`jump`:return Number.isInteger(t.index)&&t.index>=0&&t.index<=i?_u(e,t.index,!0):e;case`time`:return{...e,position:Math.max(0,t.position),duration:Math.max(0,t.duration)}}}function yu(e){switch(e.action){case`play`:return{type:`play`,tracks:e.tracks??[],mode:e.mode===`add`||e.mode===`next`?e.mode:`replace`,...e.shuffle?{shuffle:!0}:{},...e.index===void 0?{}:{start:e.index}};case`pause`:case`resume`:case`toggle`:case`stop`:case`next`:case`previous`:return{type:e.action};case`seek`:return{type:`seek`,...e.seconds===void 0?{}:{seconds:e.seconds},...e.percent===void 0?{}:{percent:e.percent}};case`volume`:return{type:`volume`,...e.level===void 0?{}:{level:e.level},...e.delta===void 0?{}:{delta:e.delta}};case`mute`:return{type:`mute`,...e.on===void 0?{}:{on:e.on}};case`shuffle`:return{type:`shuffle`,...e.on===void 0?{}:{on:e.on}};case`repeat`:return e.mode===`off`||e.mode===`all`||e.mode===`one`?{type:`repeat`,mode:e.mode}:null;case`view`:return e.view?{type:`view`,view:e.view}:null;case`queue.remove`:return e.index===void 0?null:{type:`remove`,index:e.index};case`queue.clear`:return{type:`clear`};case`jump`:return e.index===void 0?null:{type:`jump`,index:e.index};default:return null}}function bu(e){switch(e.type){case`play`:return{action:`play`,tracks:e.tracks,mode:e.mode,...e.shuffle?{shuffle:!0}:{},...e.start===void 0?{}:{index:e.start}};case`next`:case`previous`:case`pause`:case`resume`:case`toggle`:case`stop`:return{action:e.type};case`volume`:return{action:`volume`,...e.level===void 0?{}:{level:e.level},...e.delta===void 0?{}:{delta:e.delta}};case`mute`:return{action:`mute`,...e.on===void 0?{}:{on:e.on}};case`seek`:return{action:`seek`,...e.seconds===void 0?{}:{seconds:e.seconds},...e.percent===void 0?{}:{percent:e.percent}};case`repeat`:return{action:`repeat`,mode:e.mode};case`shuffle`:return{action:`shuffle`,...e.on===void 0?{}:{on:e.on}};case`view`:return{action:`view`,view:e.view};case`remove`:return{action:`queue.remove`,index:e.index};case`clear`:return{action:`queue.clear`};case`jump`:return{action:`jump`,index:e.index};default:return null}}function xu({label:e,value:t,onChange:n,min:r,max:i,step:a}){let[o,s]=(0,l.useState)(String(t));return(0,l.useEffect)(()=>{s(e=>Number(e)===t?e:String(t))},[t]),(0,p.jsxs)(`label`,{className:`settings-field`,children:[(0,p.jsx)(`span`,{children:e}),(0,p.jsx)(`input`,{type:`number`,min:r,max:i,step:a,value:o,onChange:e=>{s(e.target.value),e.target.value.trim()!==``&&Number.isFinite(Number(e.target.value))&&n(Number(e.target.value))},onBlur:()=>s(String(t)),style:d})]})}async function Su(e,t){let n;try{n=await fetch(e,t)}catch{throw Error(`Could not reach Friend. Check the connection.`)}let r={};try{r=await n.json()}catch{}if(!n.ok)throw Error(r.error??(n.status===401?`Please sign in again.`:`The request failed (${n.status}).`));return r}var Cu={status:()=>Su(`/api/alexa`),allow:async(e,t)=>void await Su(`/api/alexa/devices/allow`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({id:e,pin:t})}),forget:async e=>void await Su(`/api/alexa/devices/${encodeURIComponent(e)}`,{method:`DELETE`})},wu=/^amzn1\.ask\.skill\.[A-Za-z0-9-]{8,80}$/;function Tu(e){return e.skillId.trim()&&!wu.test(e.skillId.trim())?`A skill ID looks like amzn1.ask.skill.xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx (copy it from the console).`:e.invocationName.trim()?iu(e.invocationName):null}var Eu={"skill.json":`the skill's manifest (name, endpoint)`,"en-IN.json":`the English (India) interaction model`,"hi-IN.json":`the Hindi (India) interaction model`},Du={"en-IN":`English (India)`,"hi-IN":`Hindi (India)`},Ou=e=>{let t=Math.max(0,Math.round((Date.now()-e)/6e4));return t<1?`just now`:t<60?`${t} min ago`:`${Math.round(t/60)} h ago`};function ku({view:e,setView:t,api:n=Cu}){let[r,i]=(0,l.useState)(null),[a,o]=(0,l.useState)(null),[s,c]=(0,l.useState)(``),[u,f]=(0,l.useState)(null),[m,h]=(0,l.useState)(!1),[g,_]=(0,l.useState)(!1),v=(0,l.useRef)(!0),y=(0,l.useCallback)(()=>n.status().then(e=>v.current&&i(e)).catch(()=>{}),[n]);(0,l.useEffect)(()=>(v.current=!0,y(),()=>{v.current=!1}),[y]);let b=async e=>{_(!0),f(null);try{await e()}catch(e){v.current&&f(e.message)}finally{v.current&&_(!1)}},S=Tu(e),C=r?.invocationName||e.invocationName,w=!!r?.endpoint&&!!r.invocationName;return(0,p.jsxs)(`div`,{className:`settings-section`,children:[(0,p.jsx)(`p`,{className:`auth-note`,children:`Friend talks to a skill of your own on Alexa. It is free: the skill stays in development mode in your own Amazon developer account and is never published, and only the Echo devices you allow can use it. Alexa can look things up and answer; anything that changes something is refused, or sent to your phone for a yes.`}),(0,p.jsx)(`h4`,{className:`plugins-heading`,children:`In the Alexa developer console`}),r&&r.endpoint?(0,p.jsxs)(`p`,{className:`auth-note`,children:[`Endpoint to paste (HTTPS, "My development endpoint has a certificate from a trusted certificate authority"): `,(0,p.jsx)(`code`,{children:r.endpoint}),` `,(0,p.jsx)(`button`,{type:`button`,style:d,onClick:()=>{navigator.clipboard?.writeText(r.endpoint).then(()=>h(!0),()=>{})},children:m?`Copied`:`Copy`})]}):r&&(0,p.jsx)(`p`,{className:`auth-note`,children:`No public address is set yet, so Amazon cannot reach Friend (friend config set publicUrl https://…).`}),(0,p.jsx)(`p`,{className:`auth-note`,children:`If your address changes later, paste the new address into the console again. Nothing else needs to change.`}),w?(0,p.jsx)(`ul`,{className:`plugins-list`,children:r.files.map(e=>(0,p.jsxs)(`li`,{children:[(0,p.jsx)(`a`,{href:`/api/alexa/package/${e}`,download:e,children:e}),` `,(0,p.jsx)(`small`,{className:`auth-note`,children:Eu[e]??``})]},e))}):r&&r.endpoint&&(0,p.jsx)(`p`,{className:`auth-note`,children:`Save an invocation name first; the files are made with it.`}),(0,p.jsxs)(`label`,{className:`settings-field`,children:[(0,p.jsx)(`span`,{children:`Skill ID`}),(0,p.jsx)(`input`,{value:e.skillId,autoComplete:`off`,onChange:n=>t({...e,skillId:n.target.value}),placeholder:`amzn1.ask.skill.…`,style:d})]}),(0,p.jsxs)(`label`,{className:`settings-field`,children:[(0,p.jsx)(`span`,{children:`Invocation name`}),(0,p.jsx)(`input`,{value:e.invocationName,autoComplete:`off`,onChange:n=>t({...e,invocationName:n.target.value}),placeholder:`jarvis assistant`,style:d})]}),S&&(0,p.jsx)(`p`,{role:`alert`,className:`auth-error`,children:S}),(0,p.jsxs)(`details`,{children:[(0,p.jsx)(`summary`,{className:`plugins-heading`,children:`Advanced`}),(0,p.jsxs)(`label`,{className:`settings-field`,children:[(0,p.jsx)(`span`,{children:`Skill name`}),(0,p.jsx)(`input`,{value:e.skillName,onChange:n=>t({...e,skillName:n.target.value}),style:d})]}),(0,p.jsx)(`div`,{className:`settings-field`,role:`group`,"aria-label":`Languages`,children:Object.entries(Du).map(([n,r])=>(0,p.jsxs)(`label`,{className:`settings-check`,children:[(0,p.jsx)(`input`,{type:`checkbox`,checked:e.locales.includes(n),onChange:r=>{let i=r.target.checked?[...e.locales,n]:e.locales.filter(e=>e!==n);i.length>0&&t({...e,locales:Object.keys(Du).filter(e=>i.includes(e))})}}),(0,p.jsx)(`span`,{children:r})]},n))}),(0,p.jsx)(xu,{label:`Seconds to work on an answer`,value:e.answerSeconds,min:2,max:7.5,step:.5,onChange:n=>t({...e,answerSeconds:n})}),(0,p.jsx)(xu,{label:`Minutes to keep a late answer`,value:e.holdMinutes,min:1,max:60,onChange:n=>t({...e,holdMinutes:n})}),(0,p.jsx)(xu,{label:`Seconds to wait for your yes on your phone`,value:e.permissionSeconds,min:30,max:600,onChange:n=>t({...e,permissionSeconds:n})}),(0,p.jsx)(xu,{label:`Requests a minute allowed`,value:e.requestsPerMinute,min:10,max:600,onChange:n=>t({...e,requestsPerMinute:n})}),(0,p.jsx)(xu,{label:`Echo devices allowed`,value:e.maxDevices,min:1,max:50,onChange:n=>t({...e,maxDevices:n})}),(0,p.jsxs)(`label`,{className:`settings-field`,children:[(0,p.jsx)(`span`,{children:`Extra tools a voice may use without asking (one per line)`}),(0,p.jsx)(`textarea`,{rows:2,value:e.extraVoiceTools.join(`
|
|
66
|
+
`),onChange:n=>t({...e,extraVoiceTools:n.target.value.split(/[\s,]+/).filter(Boolean)})})]}),(0,p.jsx)(`small`,{className:`auth-note`,children:`Tools that reach your PC, files, settings, add-ons or camera, and anything that needs your PIN, can never be added.`})]}),(0,p.jsx)(`h4`,{className:`plugins-heading`,children:`Echo devices`}),r&&r.waiting.length===0&&r.allowed.length===0&&(0,p.jsxs)(`p`,{className:`auth-note`,children:[`Say "Alexa, ask `,C||`your invocation name`,`" on your Echo once; it will appear here for you to allow.`]}),(0,p.jsxs)(`ul`,{className:`plugins-list`,children:[(r?.waiting??[]).map(e=>(0,p.jsxs)(`li`,{children:[(0,p.jsxs)(`b`,{children:[`Echo …`,e.short]}),` `,(0,p.jsxs)(`small`,{className:`auth-note`,children:[`waiting (`,e.locale,`), asked `,Ou(e.at)]}),` `,(0,p.jsx)(`button`,{type:`button`,style:d,disabled:g,onClick:()=>{o(e.short),c(``),f(null)},children:`Allow`})]},e.short)),(r?.allowed??[]).map(e=>(0,p.jsxs)(`li`,{children:[(0,p.jsx)(`b`,{children:e.name}),` `,(0,p.jsxs)(`small`,{className:`auth-note`,children:[`…`,e.short]}),` `,(0,p.jsx)(`button`,{type:`button`,style:d,disabled:g,onClick:()=>void b(async()=>{await n.forget(e.short),await y()}),children:`Forget`})]},e.short))]}),a&&(0,p.jsxs)(p.Fragment,{children:[(0,p.jsxs)(`p`,{className:`auth-note`,children:[`Enter your PIN to allow Echo …`,a,`. Anyone who can speak to that Echo can then ask Friend things.`]}),(0,p.jsx)(x,{pin:s,onChange:c,onSubmit:()=>!g&&s.length>=6&&void b(async()=>{await n.allow(a,s),o(null),c(``),await y()})}),(0,p.jsxs)(`div`,{className:`approval-actions`,children:[(0,p.jsx)(`button`,{type:`button`,style:d,className:`primary`,disabled:g||s.length<6,onClick:()=>void b(async()=>{await n.allow(a,s),o(null),c(``),await y()}),children:`Allow this Echo`}),(0,p.jsx)(`button`,{type:`button`,style:d,onClick:()=>{o(null),c(``),f(null)},children:`Back`})]})]}),u&&!S&&(0,p.jsx)(`p`,{role:`alert`,className:`auth-error`,children:u})]})}async function Au(e,t){let n;try{n=await fetch(e,t)}catch{throw Error(`Could not reach Friend. Check the connection.`)}let r={};try{r=await n.json()}catch{}if(!n.ok)throw Error(r.error??(n.status===401?`Please sign in again.`:n.status===403?`Incorrect PIN`:`The request failed (${n.status}).`));return r}var ju={info:async()=>{let e=(await Au(`/api/plugins`)).integrations?.find(e=>e.id===`chrome`),t=e?.settings?.extensionFolder;return{state:e?.state??`not-installed`,detail:e?.detail??``,extensionFolder:typeof t==`string`&&t?t:null}},setUp:e=>Au(`/api/connectors/quick/chrome/install`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({pin:e})}),access:()=>Au(`/api/plugins/chrome/access`),setRemote:async(e,t)=>{await Au(`/api/plugins/chrome/remote`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({enabled:e,...t?{pin:t}:{}})})},revealKey:async e=>(await Au(`/api/plugins/chrome/token`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({pin:e})})).token};function Mu({label:e,value:t}){let[n,r]=(0,l.useState)(!1);return(0,p.jsxs)(`label`,{className:`settings-field`,children:[(0,p.jsx)(`span`,{children:e}),(0,p.jsxs)(`div`,{style:{display:`flex`,gap:6},children:[(0,p.jsx)(`input`,{type:`text`,readOnly:!0,value:t,style:{flex:1},onFocus:e=>e.currentTarget.select()}),(0,p.jsx)(`button`,{type:`button`,onClick:()=>{navigator.clipboard?.writeText(t).then(()=>r(!0),()=>{})},children:n?`Copied`:`Copy`})]})]})}function Nu({api:e=ju,pollMs:t=3e3}){let[n,r]=(0,l.useState)(null),[i,a]=(0,l.useState)(null),[o,s]=(0,l.useState)(null),[c,u]=(0,l.useState)(null),[f,m]=(0,l.useState)(``),[h,g]=(0,l.useState)(!1),[_,v]=(0,l.useState)(null),[y,b]=(0,l.useState)(null),[S,C]=(0,l.useState)(!1),w=(0,l.useRef)(!0),T=(0,l.useCallback)(async()=>{try{let[t,n]=await Promise.all([e.info(),e.access()]);if(!w.current)return;r(t),a(n)}catch{}},[e]);(0,l.useEffect)(()=>{w.current=!0,T();let e=t>0?setInterval(()=>void T(),t):null;return()=>{w.current=!1,e&&clearInterval(e)}},[T,t]);let E=async()=>{g(!0),v(null);try{if(c===`setup`){let t=await e.setUp(f);if(!w.current)return;b(t.message)}else if(c===`allow`)await e.setRemote(!0,f);else if(c===`key`){let t=await e.revealKey(f);if(!w.current)return;s(t)}if(!w.current)return;u(null),await T()}catch(e){w.current&&v(e.message)}finally{w.current&&(g(!1),m(``))}};return c?(0,p.jsxs)(p.Fragment,{children:[(0,p.jsx)(`p`,{className:`auth-note`,children:c===`setup`?`Enter your PIN to set up Chrome control.`:c===`allow`?`Enter your PIN to allow other PCs to use Chrome control through Friend.`:`Enter your PIN to show the key.`}),(0,p.jsx)(x,{pin:f,onChange:m,onSubmit:()=>!h&&f.length>=6&&void E()}),_&&(0,p.jsx)(`p`,{role:`alert`,className:`auth-error`,children:_}),(0,p.jsxs)(`div`,{className:`approval-actions`,children:[(0,p.jsx)(`button`,{type:`button`,style:d,className:`primary`,disabled:h||f.length<6,onClick:()=>void E(),children:`Continue`}),(0,p.jsx)(`button`,{type:`button`,style:d,onClick:()=>{u(null),m(``),v(null)},children:`Back`})]})]}):(0,p.jsxs)(`div`,{className:`settings-section`,children:[n?.detail&&(0,p.jsx)(`p`,{className:`auth-note`,style:{marginBottom:10},children:n.detail}),n?.extensionFolder&&(0,p.jsxs)(`label`,{className:`settings-field`,children:[(0,p.jsx)(`span`,{children:`Folder to load in Chrome (chrome://extensions, Developer mode, Load unpacked)`}),(0,p.jsxs)(`div`,{style:{display:`flex`,gap:6},children:[(0,p.jsx)(`input`,{type:`text`,readOnly:!0,value:n.extensionFolder,style:{flex:1},onFocus:e=>e.currentTarget.select()}),(0,p.jsx)(`button`,{type:`button`,onClick:()=>{navigator.clipboard?.writeText(n.extensionFolder??``).then(()=>C(!0),()=>{})},children:S?`Copied`:`Copy`})]})]}),(0,p.jsx)(`div`,{className:`approval-actions`,children:(0,p.jsx)(`button`,{type:`button`,style:d,className:n?.extensionFolder?void 0:`primary`,onClick:()=>u(`setup`),children:n?.extensionFolder?`Set up again`:`Set up Chrome control`})}),y&&(0,p.jsx)(`p`,{className:`auth-note`,children:y}),i&&n?.extensionFolder&&(0,p.jsxs)(p.Fragment,{children:[(0,p.jsx)(`h4`,{className:`plugins-heading`,children:`From another PC`}),i.extensionZip&&(0,p.jsxs)(`p`,{className:`auth-note`,children:[(0,p.jsx)(`a`,{href:i.extensionZip,download:`friend-chrome-extension.zip`,children:`Download the extension`}),` `,`to install it in Chrome on another PC: unzip it, open chrome://extensions, turn on Developer mode, press Load unpacked and choose the unzipped folder.`]}),i.remote?(0,p.jsxs)(p.Fragment,{children:[(0,p.jsx)(Mu,{label:`Server to type in the extension's popup on the other PC`,value:i.extensionAddress}),(0,p.jsx)(Mu,{label:`MCP address for apps on other PCs (Claude Code, Claude Desktop). Send the key as: Authorization: Bearer KEY`,value:i.mcpUrl}),/^(ws|http):\/\/(127\.0\.0\.1|localhost|\[::1\])/i.test(i.extensionAddress)&&(0,p.jsx)(`p`,{className:`auth-note`,children:`These use the address you opened Friend with, and another PC cannot reach 127.0.0.1. Open Friend by its network or public address and these will show that one.`}),o?(0,p.jsx)(Mu,{label:`The key (paste it in the extension's popup)`,value:o}):null,(0,p.jsxs)(`div`,{className:`approval-actions`,children:[!o&&(0,p.jsx)(`button`,{type:`button`,style:d,onClick:()=>u(`key`),children:`Show the key`}),(0,p.jsx)(`button`,{type:`button`,style:d,onClick:()=>{s(null),e.setRemote(!1).then(()=>T(),e=>v(e.message))},children:`Stop allowing other PCs`})]})]}):(0,p.jsx)(`div`,{className:`approval-actions`,children:(0,p.jsx)(`button`,{type:`button`,style:d,onClick:()=>u(`allow`),children:`Allow other PCs`})})]}),(0,p.jsx)(`small`,{className:`auth-note`,children:`Chrome does not allow programs to add an extension by themselves, so loading the folder above is the one step you do. While the extension is on, Friend can act as you on the sites it allows; every action still asks for your approval, and in the extension's popup you can limit it to certain sites.`})]})}async function Pu(e,t){let n;try{n=await fetch(e,t)}catch{throw Error(`Could not reach Friend. Check the connection.`)}let r={};try{r=await n.json()}catch{}if(!n.ok)throw Error(r.error??(n.status===401?`Please sign in again.`:`The request failed (${n.status}).`));return r}var Fu=(e,t)=>Pu(e,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify(t)}),Iu={info:async()=>{let e=await Pu(`/api/music/sources`);return{status:e.sources.find(e=>e.id===`soundcloud`)?.status??{connected:!1,needs:null,account:null},redirectUri:e.soundcloud.redirectUri,clientId:e.soundcloud.clientId,secretSet:e.soundcloud.secretSet}},saveCredentials:async(e,t,n)=>void await Fu(`/api/music/soundcloud/credentials`,{clientId:e,...t?{clientSecret:t}:{},pin:n}),connect:async e=>(await Fu(`/api/music/soundcloud/connect`,{pin:e})).url,disconnect:async e=>void await Fu(`/api/music/soundcloud/disconnect`,{pin:e})},Lu=e=>e.trim()===``||/^[A-Za-z0-9]{8,64}$/.test(e.trim())?null:`A client id is letters and digits only, copied from your app at soundcloud.com/you/apps.`;function Ru({api:e=Iu,navigate:t=e=>window.location.assign(e)}){let[n,r]=(0,l.useState)(null),[i,a]=(0,l.useState)(``),[o,s]=(0,l.useState)(``),[c,u]=(0,l.useState)(null),[f,m]=(0,l.useState)(``),[h,g]=(0,l.useState)(!1),[_,v]=(0,l.useState)(null),[y,b]=(0,l.useState)(!1),S=(0,l.useRef)(!0),C=(0,l.useCallback)(async()=>{try{let t=await e.info();if(!S.current)return;r(t),a(t.clientId)}catch(e){S.current&&v(e.message)}},[e]);(0,l.useEffect)(()=>(S.current=!0,C(),()=>{S.current=!1}),[C]);let w=async()=>{if(c){g(!0),v(null);try{c===`save`?(await e.saveCredentials(i.trim(),o.trim()||void 0,f),S.current&&s(``),await C()):c===`connect`?t(await e.connect(f)):(await e.disconnect(f),await C()),S.current&&u(null)}catch(e){S.current&&v(e.message)}finally{S.current&&(g(!1),m(``))}}};if(c)return(0,p.jsxs)(p.Fragment,{children:[(0,p.jsxs)(`p`,{className:`auth-note`,children:[`Enter your PIN `,c===`save`?`to save the SoundCloud app details`:c===`connect`?`to connect SoundCloud`:`to disconnect SoundCloud`,`.`]}),(0,p.jsx)(x,{pin:f,onChange:m,onSubmit:()=>!h&&f.length>=6&&void w()}),_&&(0,p.jsx)(`p`,{role:`alert`,className:`auth-error`,children:_}),(0,p.jsxs)(`div`,{className:`approval-actions`,children:[(0,p.jsx)(`button`,{type:`button`,style:d,className:`primary`,disabled:h||f.length<6,onClick:()=>void w(),children:c===`save`?`Save`:`Continue`}),(0,p.jsx)(`button`,{type:`button`,style:d,onClick:()=>{u(null),m(``),v(null)},children:`Back`})]})]});let T=Lu(i),E=!!n&&i.trim()!==n.clientId||o.trim()!==``,D=!!n?.clientId&&n.secretSet,O=n?.status;return(0,p.jsxs)(`div`,{className:`settings-section`,children:[(0,p.jsxs)(`label`,{className:`settings-field`,children:[(0,p.jsx)(`span`,{children:`Redirect address to add in your SoundCloud app`}),(0,p.jsxs)(`div`,{style:{display:`flex`,gap:6},children:[(0,p.jsx)(`input`,{type:`text`,readOnly:!0,value:n?.redirectUri??``,style:{flex:1},onFocus:e=>e.currentTarget.select()}),(0,p.jsx)(`button`,{type:`button`,onClick:()=>{navigator.clipboard?.writeText(n?.redirectUri??``).then(()=>b(!0),()=>{})},children:y?`Copied`:`Copy`})]})]}),(0,p.jsxs)(`label`,{className:`settings-field`,children:[(0,p.jsx)(`span`,{children:`Client id of your SoundCloud app`}),(0,p.jsx)(`input`,{type:`text`,value:i,maxLength:64,autoComplete:`off`,spellCheck:!1,onChange:e=>a(e.target.value)})]}),(0,p.jsxs)(`label`,{className:`settings-field`,children:[(0,p.jsx)(`span`,{children:`Client secret of your SoundCloud app`}),(0,p.jsx)(`input`,{type:`password`,value:o,maxLength:200,autoComplete:`new-password`,spellCheck:!1,onChange:e=>s(e.target.value)}),n?.secretSet&&(0,p.jsx)(`small`,{className:`auth-note`,children:`The secret is saved. Type a new one only to replace it.`})]}),T&&(0,p.jsx)(`p`,{role:`alert`,className:`auth-error`,children:T}),(0,p.jsxs)(`div`,{className:`approval-actions`,children:[(0,p.jsx)(`button`,{type:`button`,style:d,disabled:!E||!i.trim()||T!==null||!n?.secretSet&&!o.trim(),onClick:()=>u(`save`),children:`Save`}),O?.connected?(0,p.jsx)(`button`,{type:`button`,style:d,onClick:()=>u(`disconnect`),children:`Disconnect SoundCloud`}):(0,p.jsx)(`button`,{type:`button`,style:d,className:`primary`,disabled:!D||E,onClick:()=>u(`connect`),children:`Connect SoundCloud`})]}),O?.connected&&(0,p.jsxs)(`p`,{className:`auth-note`,children:[`Connected as `,O.account??`your account`,`.`]}),O?.needs&&(0,p.jsx)(`p`,{className:`auth-note`,children:O.needs}),_&&(0,p.jsx)(`p`,{role:`alert`,className:`auth-error`,children:_}),(0,p.jsx)(`small`,{className:`auth-note`,children:`Sign-in is on SoundCloud's own page: Friend never sees your SoundCloud password. SoundCloud decides who can register an app, and some tracks only play with the right SoundCloud plan.`})]})}async function zu(e,t){let n;try{n=await fetch(e,t)}catch{throw Error(`Could not reach Friend. Check the connection.`)}let r={};try{r=await n.json()}catch{}if(!n.ok)throw Error(r.error??(n.status===401?`Please sign in again.`:`The request failed (${n.status}).`));return r}var Bu=(e,t)=>zu(e,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify(t)}),Vu={info:async()=>{let e=await zu(`/api/music/sources`);return{status:e.sources.find(e=>e.id===`spotify`)?.status??{connected:!1,needs:null,account:null},redirectUri:e.spotify.redirectUri,clientId:e.spotify.clientId}},saveClientId:async(e,t)=>void await Bu(`/api/music/spotify/client-id`,{clientId:e,pin:t}),connect:async e=>(await Bu(`/api/music/spotify/connect`,{pin:e})).url,disconnect:async e=>void await Bu(`/api/music/spotify/disconnect`,{pin:e})},Hu=e=>e.trim()===``||/^[A-Za-z0-9]{8,64}$/.test(e.trim())?null:`A client id is letters and digits only, copied from your app at developer.spotify.com.`;function Uu({api:e=Vu,navigate:t=e=>window.location.assign(e)}){let[n,r]=(0,l.useState)(null),[i,a]=(0,l.useState)(``),[o,s]=(0,l.useState)(null),[c,u]=(0,l.useState)(``),[f,m]=(0,l.useState)(!1),[h,g]=(0,l.useState)(null),[_,v]=(0,l.useState)(!1),y=(0,l.useRef)(!0),b=(0,l.useCallback)(async()=>{try{let t=await e.info();if(!y.current)return;r(t),a(t.clientId)}catch(e){y.current&&g(e.message)}},[e]);(0,l.useEffect)(()=>(y.current=!0,b(),()=>{y.current=!1}),[b]);let S=async()=>{if(o){m(!0),g(null);try{o===`client`?(await e.saveClientId(i.trim(),c),await b()):o===`connect`?t(await e.connect(c)):(await e.disconnect(c),await b()),y.current&&s(null)}catch(e){y.current&&g(e.message)}finally{y.current&&(m(!1),u(``))}}};if(o)return(0,p.jsxs)(p.Fragment,{children:[(0,p.jsxs)(`p`,{className:`auth-note`,children:[`Enter your PIN `,o===`client`?`to save the client id`:o===`connect`?`to connect Spotify`:`to disconnect Spotify`,`.`]}),(0,p.jsx)(x,{pin:c,onChange:u,onSubmit:()=>!f&&c.length>=6&&void S()}),h&&(0,p.jsx)(`p`,{role:`alert`,className:`auth-error`,children:h}),(0,p.jsxs)(`div`,{className:`approval-actions`,children:[(0,p.jsx)(`button`,{type:`button`,style:d,className:`primary`,disabled:f||c.length<6,onClick:()=>void S(),children:o===`client`?`Save`:`Continue`}),(0,p.jsx)(`button`,{type:`button`,style:d,onClick:()=>{s(null),u(``),g(null)},children:`Back`})]})]});let C=Hu(i),w=!!n&&i.trim()!==n.clientId,T=!!n?.clientId,E=n?.status;return(0,p.jsxs)(`div`,{className:`settings-section`,children:[(0,p.jsxs)(`label`,{className:`settings-field`,children:[(0,p.jsx)(`span`,{children:`Redirect address to add in your Spotify app`}),(0,p.jsxs)(`div`,{style:{display:`flex`,gap:6},children:[(0,p.jsx)(`input`,{type:`text`,readOnly:!0,value:n?.redirectUri??``,style:{flex:1},onFocus:e=>e.currentTarget.select()}),(0,p.jsx)(`button`,{type:`button`,onClick:()=>{navigator.clipboard?.writeText(n?.redirectUri??``).then(()=>v(!0),()=>{})},children:_?`Copied`:`Copy`})]})]}),(0,p.jsxs)(`label`,{className:`settings-field`,children:[(0,p.jsx)(`span`,{children:`Client id of your Spotify app`}),(0,p.jsx)(`input`,{type:`text`,value:i,maxLength:64,autoComplete:`off`,spellCheck:!1,onChange:e=>a(e.target.value)})]}),C&&(0,p.jsx)(`p`,{role:`alert`,className:`auth-error`,children:C}),(0,p.jsxs)(`div`,{className:`approval-actions`,children:[(0,p.jsx)(`button`,{type:`button`,style:d,disabled:!w||!i.trim()||C!==null,onClick:()=>s(`client`),children:`Save client id`}),E?.connected?(0,p.jsx)(`button`,{type:`button`,style:d,onClick:()=>s(`disconnect`),children:`Disconnect Spotify`}):(0,p.jsx)(`button`,{type:`button`,style:d,className:`primary`,disabled:!T||w,onClick:()=>s(`connect`),children:`Connect Spotify`})]}),E?.connected&&(0,p.jsxs)(`p`,{className:`auth-note`,children:[`Connected as `,E.account??`your account`,`.`]}),E?.needs&&(0,p.jsx)(`p`,{className:`auth-note`,children:E.needs}),h&&(0,p.jsx)(`p`,{role:`alert`,className:`auth-error`,children:h}),(0,p.jsx)(`small`,{className:`auth-note`,children:`Sign-in is on Spotify's own page: Friend never sees your Spotify password. A development-mode Spotify app allows up to five people, and playing needs Spotify Premium on the account.`})]})}async function Wu(e,t){let n;try{n=await fetch(e,t)}catch{throw Error(`Could not reach Friend. Check the connection.`)}let r={};try{r=await n.json()}catch{}if(!n.ok)throw Error(r.error??(n.status===401?`Please sign in again.`:n.status===403?`Incorrect PIN`:`The request failed (${n.status}).`));return r}var Gu={output:`screen`,maxHeight:720,maxMinutes:240,allowedSites:[],ytdlp:``,ffmpeg:``,autoInstall:!0,youtube:`embed`},Ku={info:async()=>{let[e,t]=await Promise.all([Wu(`/api/settings`),Wu(`/api/plugins/video/status`)]);return{settings:e.video??Gu,status:t}},recheck:()=>Wu(`/api/plugins/video/check`,{method:`POST`,headers:{"content-type":`application/json`},body:`{}`}),prepare:()=>Wu(`/api/plugins/video/prepare`,{method:`POST`,headers:{"content-type":`application/json`},body:`{}`}),save:async(e,t)=>{await Wu(`/api/settings`,{method:`PUT`,headers:{"content-type":`application/json`},body:JSON.stringify({pin:t,settings:{video:e}})})}},qu=[360,480,720,1080],Ju=1,Yu=600,Xu=e=>e.split(/[\s,;]+/).map(e=>e.trim()).filter(Boolean),Zu=e=>e.join(`, `);function Qu({name:e,h:t,need:n,auto:r}){return(0,p.jsx)(`li`,{className:t.found?`done`:void 0,children:t.found?(0,p.jsxs)(p.Fragment,{children:[e,` `,t.version??``,` found`]}):(0,p.jsxs)(p.Fragment,{children:[(0,p.jsxs)(`strong`,{children:[e,` not found`]}),` `,(0,p.jsxs)(`small`,{children:[`(`,n,`)`]}),r&&(0,p.jsx)(`div`,{className:`auth-note`,children:r}),t.install&&(0,p.jsx)(`div`,{className:`auth-note`,children:t.install})]})})}function $u({api:e=Ku,pollMs:t=2e3}){let[n,r]=(0,l.useState)(null),[i,a]=(0,l.useState)(Gu),[o,s]=(0,l.useState)(``),[c,u]=(0,l.useState)(`240`),[f,m]=(0,l.useState)(!1),[h,g]=(0,l.useState)(``),[_,v]=(0,l.useState)(!1),[y,b]=(0,l.useState)(null),[S,C]=(0,l.useState)(null),w=(0,l.useRef)(!0),T=(0,l.useCallback)(async()=>{try{let t=await e.info();if(!w.current)return;r(t),a(t.settings),s(Zu(t.settings.allowedSites)),u(String(t.settings.maxMinutes))}catch(e){w.current&&b(e.message)}},[e]);(0,l.useEffect)(()=>(w.current=!0,T(),()=>{w.current=!1}),[T]);let E=n?.status.setup?.busy===!0;(0,l.useEffect)(()=>{if(!E||t<=0)return;let n=setInterval(()=>{e.info().then(e=>w.current&&r(t=>t?{...t,status:e.status}:e)).catch(()=>{})},t);return()=>clearInterval(n)},[E,t,e]);let D=n?.settings??Gu,O=Number(c),k=!Number.isInteger(O)||O<Ju||O>Yu?`Use a whole number of minutes from ${Ju} to ${Yu}.`:null,A=(()=>{let e={};i.output!==D.output&&(e.output=i.output),i.maxHeight!==D.maxHeight&&(e.maxHeight=i.maxHeight),!k&&O!==D.maxMinutes&&(e.maxMinutes=O);let t=Xu(o);return JSON.stringify(t)!==JSON.stringify(D.allowedSites)&&(e.allowedSites=t),i.autoInstall!==D.autoInstall&&(e.autoInstall=i.autoInstall),i.youtube!==D.youtube&&(e.youtube=i.youtube),i.ytdlp.trim()!==D.ytdlp&&(e.ytdlp=i.ytdlp.trim()),i.ffmpeg.trim()!==D.ffmpeg&&(e.ffmpeg=i.ffmpeg.trim()),e})(),j=Object.keys(A).length>0,ee=async()=>{v(!0),b(null);try{let t=await e.recheck();w.current&&r(e=>e&&{...e,status:t})}catch(e){w.current&&b(e.message)}finally{w.current&&v(!1)}},M=async()=>{v(!0),b(null);try{let t=await e.prepare();w.current&&r(e=>e&&{...e,status:t})}catch(e){w.current&&b(e.message)}finally{w.current&&v(!1)}},N=async()=>{v(!0),b(null);try{if(await e.save(A,h),!w.current)return;m(!1),C(`Saved.`),await T()}catch(e){w.current&&b(e.message)}finally{w.current&&(v(!1),g(``))}};if(f)return(0,p.jsxs)(p.Fragment,{children:[(0,p.jsx)(`p`,{className:`auth-note`,children:`Enter your PIN to save these changes.`}),(0,p.jsx)(x,{pin:h,onChange:g,onSubmit:()=>!_&&h.length>=6&&void N()}),y&&(0,p.jsx)(`p`,{role:`alert`,className:`auth-error`,children:y}),(0,p.jsxs)(`div`,{className:`approval-actions`,children:[(0,p.jsx)(`button`,{type:`button`,style:d,className:`primary`,disabled:_||h.length<6,onClick:()=>void N(),children:`Save`}),(0,p.jsx)(`button`,{type:`button`,style:d,onClick:()=>{m(!1),g(``),b(null)},children:`Back`})]})]});let P=n?.status,F=P?.setup,I=e=>i.autoInstall?`Friend downloads ${e} by itself when it is needed (or press Download now).`:null,te=!!P&&(!P.ytdlp.found||!P.ffmpeg.found);return(0,p.jsxs)(`div`,{className:`settings-section`,children:[P&&(0,p.jsxs)(p.Fragment,{children:[(0,p.jsx)(`h4`,{className:`plugins-heading`,children:`Helper programs on this PC`}),(0,p.jsxs)(`ol`,{className:`integration-steps`,children:[(0,p.jsx)(Qu,{name:`yt-dlp`,h:P.ytdlp,need:`finds the video, needed for every video`,auto:I(`it`)}),(0,p.jsx)(Qu,{name:`ffmpeg`,h:P.ffmpeg,need:`makes the video playable, needed for the Friend screen`,auto:I(`it`)}),(0,p.jsx)(Qu,{name:`mpv`,h:P.mpv,need:`optional: a window of its own on this PC; without it a browser window is used`,auto:null})]}),F?.busy&&(0,p.jsx)(`p`,{className:`auth-note`,children:F.message??`Setting up the video tools…`}),!F?.busy&&F?.error&&(0,p.jsx)(`p`,{role:`alert`,className:`auth-error`,children:F.error}),(0,p.jsxs)(`div`,{className:`approval-actions`,children:[te&&i.autoInstall&&!F?.busy&&(0,p.jsx)(`button`,{type:`button`,style:d,className:`primary`,disabled:_,onClick:()=>void M(),children:`Download now`}),(0,p.jsx)(`button`,{type:`button`,style:d,disabled:_,onClick:()=>void ee(),children:`Check again`})]})]}),(0,p.jsxs)(`label`,{className:`settings-field`,style:{flexDirection:`row`,alignItems:`center`,gap:8},children:[(0,p.jsx)(`input`,{type:`checkbox`,checked:i.autoInstall,onChange:e=>a({...i,autoInstall:e.target.checked})}),(0,p.jsx)(`span`,{children:`Let Friend download yt-dlp and ffmpeg by itself (recommended)`})]}),(0,p.jsxs)(`label`,{className:`settings-field`,children:[(0,p.jsx)(`span`,{children:`Where videos play`}),(0,p.jsxs)(`select`,{value:i.output,onChange:e=>a({...i,output:e.target.value}),children:[(0,p.jsx)(`option`,{value:`screen`,children:`On the Friend screen`}),(0,p.jsx)(`option`,{value:`host`,children:`In a window on this PC`})]})]}),(0,p.jsxs)(`label`,{className:`settings-field`,children:[(0,p.jsx)(`span`,{children:`YouTube plays with`}),(0,p.jsxs)(`select`,{value:i.youtube,onChange:e=>a({...i,youtube:e.target.value}),children:[(0,p.jsx)(`option`,{value:`embed`,children:`YouTube's own player (recommended: nothing to download)`}),(0,p.jsx)(`option`,{value:`stream`,children:`Friend's player (made by Friend with ffmpeg)`})]})]}),(0,p.jsxs)(`label`,{className:`settings-field`,children:[(0,p.jsx)(`span`,{children:`Picture quality (the tallest picture)`}),(0,p.jsx)(`select`,{value:String(i.maxHeight),onChange:e=>a({...i,maxHeight:Number(e.target.value)}),children:(qu.includes(i.maxHeight)?qu:[...qu,i.maxHeight].sort((e,t)=>e-t)).map(e=>(0,p.jsxs)(`option`,{value:e,children:[e,`p`]},e))})]}),(0,p.jsxs)(`label`,{className:`settings-field`,children:[(0,p.jsx)(`span`,{children:`Longest video, in minutes`}),(0,p.jsx)(`input`,{type:`number`,min:Ju,max:Yu,value:c,onChange:e=>u(e.target.value)})]}),k&&(0,p.jsx)(`p`,{role:`alert`,className:`auth-error`,children:k}),(0,p.jsxs)(`label`,{className:`settings-field`,children:[(0,p.jsx)(`span`,{children:`Allowed sites (empty: any public site)`}),(0,p.jsx)(`textarea`,{rows:2,spellCheck:!1,placeholder:`youtube.com, vimeo.com`,value:o,onChange:e=>s(e.target.value)})]}),(0,p.jsxs)(`label`,{className:`settings-field`,children:[(0,p.jsx)(`span`,{children:`yt-dlp program (empty: find it by itself)`}),(0,p.jsx)(`input`,{type:`text`,value:i.ytdlp,maxLength:260,spellCheck:!1,autoComplete:`off`,placeholder:`yt-dlp`,onChange:e=>a({...i,ytdlp:e.target.value})})]}),(0,p.jsxs)(`label`,{className:`settings-field`,children:[(0,p.jsx)(`span`,{children:`ffmpeg program (empty: find it by itself)`}),(0,p.jsx)(`input`,{type:`text`,value:i.ffmpeg,maxLength:260,spellCheck:!1,autoComplete:`off`,placeholder:`ffmpeg`,onChange:e=>a({...i,ffmpeg:e.target.value})})]}),S&&!j&&(0,p.jsx)(`p`,{className:`auth-note`,children:S}),y&&!k&&(0,p.jsx)(`p`,{role:`alert`,className:`auth-error`,children:y}),(0,p.jsx)(`div`,{className:`approval-actions`,children:(0,p.jsx)(`button`,{type:`button`,style:d,className:`primary`,disabled:!j||_||k!==null,onClick:()=>m(!0),children:j?`Save…`:`Save`})}),(0,p.jsx)(`small`,{className:`auth-note`,children:`Friend downloads the two programs from their projects' own release pages (github.com), checks them against the published checksums and keeps them in its own folder, never anywhere else on your PC. Videos stay on the site; nothing is saved to your disk. Some sites need a login or are not available in every country, and those cannot be played.`})]})}async function ed(e,t){let n;try{n=await fetch(e,t)}catch{throw Error(`Could not reach Friend. Check the connection.`)}let r={};try{r=await n.json()}catch{}if(!n.ok)throw Error(r.error??(n.status===401?`Please sign in again.`:`The request failed (${n.status}).`));return r}var td=(e,t)=>({method:e,headers:{"content-type":`application/json`},body:JSON.stringify(t)}),nd={status:()=>ed(`/api/brokers`),loginLink:e=>ed(`/api/brokers/zerodha/login-link`,td(`POST`,{send:e})),runNow:e=>ed(`/api/brokers/run`,td(`POST`,{kind:`custom`,send:e===!0})),addSchedule:async(e,t)=>void await ed(`/api/brokers/schedules`,td(`POST`,{...e,pin:t})),removeSchedule:async e=>void await ed(`/api/brokers/schedules/${e}`,{method:`DELETE`})},rd=[`Mon`,`Tue`,`Wed`,`Thu`,`Fri`,`Sat`,`Sun`],id=[[`telegram`,`Telegram`],[`whatsapp`,`WhatsApp`],[`sms`,`SMS`]],ad={telegram:`Telegram`,whatsapp:`WhatsApp`,sms:`SMS`};function od({view:e,setView:t,secret:n,setSecret:r,api:i=nd}){let[a,o]=(0,l.useState)(null),[s,c]=(0,l.useState)(null),[u,f]=(0,l.useState)(null),[m,h]=(0,l.useState)(null),[g,_]=(0,l.useState)(!1),[v,y]=(0,l.useState)(!1),[b,S]=(0,l.useState)(``),[C,w]=(0,l.useState)({name:`Morning report`,kind:`morning`,time:`09:30`,days:[1,2,3,4,5],channel:`telegram`}),[T,E]=(0,l.useState)(!1),D=(0,l.useRef)(!0),O=(0,l.useCallback)(()=>i.status().then(e=>D.current&&o(e)).catch(()=>{}),[i]);(0,l.useEffect)(()=>(D.current=!0,O(),()=>{D.current=!1}),[O]);let k=async e=>{E(!0),f(null),c(null);try{await e()}catch(e){D.current&&f(e.message)}finally{D.current&&E(!1)}},A=e.zerodha,j=n=>t({...e,...n}),ee=a?.schedules[0]?.channel??`telegram`,M=()=>/^([01]\d|2[0-3]):[0-5]\d$/.test(C.time)?C.days.length===0?`Choose at least one day.`:C.name.trim()?null:`Give the report a name.`:`Write the time like 09:30 (HH:MM, 24 hour).`,N=()=>k(async()=>{await i.addSchedule({...C,name:C.name.trim()},b),_(!1),y(!1),S(``),await O()});return(0,p.jsxs)(`div`,{className:`settings-section`,children:[(0,p.jsx)(`p`,{className:`auth-note`,children:`Friend only reads your account. It cannot place orders. The figures you ask about pass through the AI model you chose (Claude from Anthropic, or Ollama on this PC), and a report you schedule goes to the messaging app you pick (Telegram or WhatsApp). Nothing else leaves this PC.`}),(0,p.jsx)(`p`,{className:`auth-note`,children:a?.redirectUrl?(0,p.jsxs)(p.Fragment,{children:[`In your Kite Connect app, set the redirect URL to `,(0,p.jsx)(`code`,{children:a.redirectUrl})]}):`No public address is set yet, so Zerodha cannot send you back to Friend after login (friend config set publicUrl https://…).`}),(0,p.jsxs)(`label`,{className:`settings-field`,children:[(0,p.jsx)(`span`,{children:`API key`}),(0,p.jsx)(`input`,{value:A.apiKey,autoComplete:`off`,onChange:e=>j({zerodha:{...A,apiKey:e.target.value}}),style:d})]}),(0,p.jsxs)(`label`,{className:`settings-field`,children:[(0,p.jsx)(`span`,{children:`API secret`}),(0,p.jsx)(`input`,{type:`password`,autoComplete:`off`,value:n,placeholder:A.secretSet?`A secret is saved. Type to replace it.`:``,onChange:e=>r(e.target.value),style:d})]}),(0,p.jsxs)(`label`,{className:`settings-field`,children:[(0,p.jsx)(`span`,{children:`Time zone`}),(0,p.jsx)(`input`,{value:e.timezone,onChange:e=>j({timezone:e.target.value}),style:d})]}),(0,p.jsxs)(`label`,{className:`settings-field`,children:[(0,p.jsx)(`span`,{children:`Days with no reports (one per line, YYYY-MM-DD)`}),(0,p.jsx)(`textarea`,{value:e.skipDates.join(`
|
|
67
67
|
`),rows:3,onChange:e=>j({skipDates:e.target.value.split(/[\s,]+/).filter(Boolean)})})]}),(0,p.jsxs)(`label`,{className:`settings-field`,children:[(0,p.jsx)(`span`,{children:`Remind me to log in (minutes before the first report, 0 = never)`}),(0,p.jsx)(`input`,{type:`number`,min:0,max:120,value:e.loginReminderMinutes,onChange:e=>j({loginReminderMinutes:Number(e.target.value)}),style:d})]}),(0,p.jsxs)(`details`,{children:[(0,p.jsx)(`summary`,{className:`plugins-heading`,children:`Report options`}),(0,p.jsxs)(`label`,{className:`settings-field`,children:[(0,p.jsx)(`span`,{children:`Currency sign`}),(0,p.jsx)(`input`,{value:e.currencySymbol,maxLength:4,onChange:e=>j({currencySymbol:e.target.value}),style:d})]}),(0,p.jsxs)(`label`,{className:`settings-field`,children:[(0,p.jsx)(`span`,{children:`Currency word (spoken)`}),(0,p.jsx)(`input`,{value:e.currencyName,maxLength:20,onChange:e=>j({currencyName:e.target.value}),style:d})]}),(0,p.jsxs)(`label`,{className:`settings-field`,children:[(0,p.jsx)(`span`,{children:`Number format (locale)`}),(0,p.jsx)(`input`,{value:e.numberLocale,onChange:e=>j({numberLocale:e.target.value}),placeholder:`en-IN, en-US, de-DE`,style:d})]}),(0,p.jsx)(xu,{label:`Mention a holding above this share of the portfolio (%)`,value:e.concentrationPct,min:5,max:90,onChange:e=>j({concentrationPct:e})}),(0,p.jsx)(xu,{label:`Mention a holding down more than this today (%)`,value:e.bigDropPct,min:1,max:50,onChange:e=>j({bigDropPct:e})}),(0,p.jsx)(xu,{label:`Seconds to keep an account read`,value:e.cacheSeconds,min:5,max:300,onChange:e=>j({cacheSeconds:e})}),(0,p.jsx)(xu,{label:`Most report schedules`,value:e.maxSchedules,min:1,max:50,onChange:e=>j({maxSchedules:e})}),(0,p.jsx)(xu,{label:`Tries a day for a report`,value:e.maxTriesPerDay,min:1,max:10,onChange:e=>j({maxTriesPerDay:e})})]}),(0,p.jsx)(`h4`,{className:`plugins-heading`,children:`Daily login`}),(0,p.jsx)(`p`,{className:(a?.zerodha.loggedIn,`auth-note`),children:a?.zerodha.detail??`Checking…`}),(0,p.jsxs)(`div`,{className:`approval-actions`,children:[(0,p.jsx)(`button`,{type:`button`,style:d,disabled:T,onClick:()=>void k(async()=>{let e=await i.loginLink(!1);e.url&&window.open(e.url,`_blank`,`noopener,noreferrer`)}),children:`Open Zerodha login`}),(0,p.jsxs)(`button`,{type:`button`,style:d,disabled:T,onClick:()=>void k(async()=>{let e=await i.loginLink(!0);c(`The login link was sent to your phone${e.via?` (${ad[e.via]??e.via})`:``}.`)}),children:[`Send me the login link on `,ad[ee]??`Telegram`]})]}),(0,p.jsx)(`h4`,{className:`plugins-heading`,children:`Reports`}),a&&a.schedules.length===0&&(0,p.jsx)(`p`,{className:`auth-note`,children:`No reports are scheduled.`}),(0,p.jsx)(`ul`,{className:`plugins-list`,children:(a?.schedules??[]).map(e=>(0,p.jsxs)(`li`,{children:[(0,p.jsx)(`b`,{children:e.name}),` `,(0,p.jsxs)(`small`,{className:`auth-note`,children:[e.time,`, `,e.days.map(e=>rd[e-1]).join(` `),` to `,ad[e.channel],e.lastRunDay?`, last sent ${e.lastRunDay}`:``]}),` `,(0,p.jsx)(`button`,{type:`button`,style:d,disabled:T,onClick:()=>void k(async()=>{await i.removeSchedule(e.id),await O()}),children:`Remove`})]},e.id))}),g&&!v&&(0,p.jsxs)(`div`,{className:`settings-section`,children:[(0,p.jsxs)(`label`,{className:`settings-field`,children:[(0,p.jsx)(`span`,{children:`Name`}),(0,p.jsx)(`input`,{value:C.name,onChange:e=>w({...C,name:e.target.value}),style:d})]}),(0,p.jsxs)(`label`,{className:`settings-field`,children:[(0,p.jsx)(`span`,{children:`Kind`}),(0,p.jsxs)(`select`,{value:C.kind,onChange:e=>w({...C,kind:e.target.value}),style:d,children:[(0,p.jsx)(`option`,{value:`morning`,children:`Morning`}),(0,p.jsx)(`option`,{value:`close`,children:`Market close`}),(0,p.jsx)(`option`,{value:`custom`,children:`Custom`})]})]}),(0,p.jsxs)(`label`,{className:`settings-field`,children:[(0,p.jsx)(`span`,{children:`Time (24 hour)`}),(0,p.jsx)(`input`,{value:C.time,onChange:e=>w({...C,time:e.target.value}),placeholder:`09:30`,style:d})]}),(0,p.jsx)(`div`,{className:`settings-field`,role:`group`,"aria-label":`Days`,children:rd.map((e,t)=>(0,p.jsxs)(`label`,{className:`settings-check`,children:[(0,p.jsx)(`input`,{type:`checkbox`,checked:C.days.includes(t+1),onChange:e=>w({...C,days:e.target.checked?[...C.days,t+1].sort():C.days.filter(e=>e!==t+1)})}),(0,p.jsx)(`span`,{children:e})]},e))}),(0,p.jsxs)(`label`,{className:`settings-field`,children:[(0,p.jsx)(`span`,{children:`Send it on`}),(0,p.jsx)(`select`,{value:C.channel,onChange:e=>w({...C,channel:e.target.value}),style:d,children:id.map(([e,t])=>(0,p.jsx)(`option`,{value:e,children:t},e))})]}),(0,p.jsxs)(`div`,{className:`approval-actions`,children:[(0,p.jsx)(`button`,{type:`button`,style:d,className:`primary`,onClick:()=>{let e=M();f(e),e||y(!0)},children:`Add report…`}),(0,p.jsx)(`button`,{type:`button`,style:d,onClick:()=>{_(!1),f(null)},children:`Cancel`})]})]}),g&&v&&(0,p.jsxs)(p.Fragment,{children:[(0,p.jsxs)(`p`,{className:`auth-note`,children:[`Enter your PIN to add this report. It sends your portfolio figures to `,ad[C.channel],`.`]}),(0,p.jsx)(x,{pin:b,onChange:S,onSubmit:()=>!T&&b.length>=6&&void N()}),(0,p.jsxs)(`div`,{className:`approval-actions`,children:[(0,p.jsx)(`button`,{type:`button`,style:d,className:`primary`,disabled:T||b.length<6,onClick:()=>void N(),children:`Add report`}),(0,p.jsx)(`button`,{type:`button`,style:d,onClick:()=>{y(!1),S(``)},children:`Back`})]})]}),!g&&(0,p.jsxs)(`div`,{className:`approval-actions`,children:[(0,p.jsx)(`button`,{type:`button`,style:d,onClick:()=>{_(!0),f(null),c(null)},children:`Add a report`}),(0,p.jsx)(`button`,{type:`button`,style:d,disabled:T,onClick:()=>void k(async()=>h((await i.runNow()).text)),children:`Show a report now`}),(0,p.jsx)(`button`,{type:`button`,style:d,disabled:T,onClick:()=>void k(async()=>{await i.runNow(!0),c(`The report was sent to your phone.`)}),children:`Send a report to my phone`})]}),m&&(0,p.jsx)(`pre`,{className:`auth-note`,style:{whiteSpace:`pre-wrap`},children:m}),s&&(0,p.jsx)(`p`,{className:`auth-note`,children:s}),u&&(0,p.jsx)(`p`,{role:`alert`,className:`auth-error`,children:u})]})}var sd={telegram:{installed:!1,enabled:!1,tokenSet:!1,linked:!1},twilio:{installed:!1,enabled:!1,accountSid:``,tokenSet:!1,smsFrom:``,whatsappFrom:``,ownerNumber:``}},cd={zerodha:{installed:!1,enabled:!1,apiKey:``,secretSet:!1},timezone:`Asia/Kolkata`,skipDates:[],loginReminderMinutes:15,currencySymbol:`₹`,currencyName:`rupees`,numberLocale:`en-IN`,concentrationPct:30,bigDropPct:5,cacheSeconds:30,maxSchedules:20,maxTriesPerDay:3},ld=[`currencySymbol`,`currencyName`,`numberLocale`,`concentrationPct`,`bigDropPct`,`cacheSeconds`,`maxSchedules`,`maxTriesPerDay`],ud=[`skillName`,`locales`,`answerSeconds`,`holdMinutes`,`permissionSeconds`,`requestsPerMinute`,`maxDevices`,`extraVoiceTools`],dd=(e,t,n)=>Object.fromEntries(n.filter(n=>JSON.stringify(e[n])!==JSON.stringify(t[n])).map(t=>[t,e[t]])),fd={installed:!1,enabled:!1,skillId:``,invocationName:``,allowed:[],skillName:`Friend Assistant`,locales:[`en-IN`,`hi-IN`],answerSeconds:6.5,holdMinutes:10,permissionSeconds:120,requestsPerMinute:60,maxDevices:10,extraVoiceTools:[]};function pd({integration:e,onBack:t,settingsApi:n=ze,channelsApi:r=Me,brokersApi:i=nd,alexaApi:a=Cu,spotifyApi:o=Vu,soundcloudApi:s=Iu,chromeApi:c=ju,videoApi:u=Ku}){let[f,m]=(0,l.useState)(null),[h,g]=(0,l.useState)(sd),[_,v]=(0,l.useState)(null),[y,b]=(0,l.useState)(cd),[S,C]=(0,l.useState)(null),[w,T]=(0,l.useState)(fd),[E,D]=(0,l.useState)(``),[O,k]=(0,l.useState)(null),[A,j]=(0,l.useState)(!1),[ee,M]=(0,l.useState)(``),[N,P]=(0,l.useState)(!1),[F,I]=(0,l.useState)(null),[te,ne]=(0,l.useState)(null),L=(0,l.useRef)(!0),re=e.id===`telegram`,ie=e.id===`zerodha`,ae=e.id===`alexa`,oe=e.id===`spotify`,se=e.id===`soundcloud`,ce=e.id===`audius`,le=e.id===`chrome`,ue=e.id===`video`,de=oe||se||ce||le||ue;(0,l.useEffect)(()=>(L.current=!0,n.get().then(e=>{if(!L.current)return;let t=e.channels??sd;m(t),g(structuredClone(t));let n=e.brokers??cd;v(n),b(structuredClone(n));let r=e.alexa??fd;C(r),T(structuredClone(r))}).catch(e=>L.current&&I(e.message)),r.status().then(e=>L.current&&k(e)).catch(()=>{}),()=>{L.current=!1}),[n,r]);let R=(()=>{if(de)return{};if(ae){if(!S)return{};let e=dd(w,S,ud);return w.skillId.trim()!==S.skillId&&(e.skillId=w.skillId.trim()),w.invocationName.trim()!==S.invocationName&&(e.invocationName=w.invocationName.trim()),Object.keys(e).length?{alexa:e}:{}}if(ie){if(!_)return{};let e={};y.zerodha.apiKey!==_.zerodha.apiKey&&(e.apiKey=y.zerodha.apiKey.trim()),E.trim()&&(e.apiSecret=E.trim());let t={};return Object.keys(e).length&&(t.zerodha=e),y.timezone!==_.timezone&&(t.timezone=y.timezone.trim()),JSON.stringify(y.skipDates)!==JSON.stringify(_.skipDates)&&(t.skipDates=y.skipDates),y.loginReminderMinutes!==_.loginReminderMinutes&&(t.loginReminderMinutes=y.loginReminderMinutes),Object.assign(t,dd(y,_,ld)),Object.keys(t).length?{brokers:t}:{}}if(!f)return{};if(re)return E.trim()?{channels:{telegram:{botToken:E.trim()}}}:{};let e={};for(let t of[`accountSid`,`smsFrom`,`whatsappFrom`,`ownerNumber`])h.twilio[t]!==f.twilio[t]&&(e[t]=h.twilio[t]);return E.trim()&&(e.authToken=E.trim()),Object.keys(e).length?{channels:{twilio:e}}:{}})(),z=Object.keys(R).length>0,B=async()=>{P(!0),I(null);try{let t=await n.save(R,ee);if(!L.current)return;let r=t.settings.channels??sd;m(r),g(structuredClone(r));let i=t.settings.brokers??cd;v(i),b(structuredClone(i));let a=t.settings.alexa??fd;C(a),T(structuredClone(a)),D(``),j(!1),ne(re&&!e.enabled?`Saved. Now press Turn on in the plugins list.`:`Saved.`)}catch(e){L.current&&I(e.message)}finally{L.current&&(P(!1),M(``))}};return A?(0,p.jsxs)(p.Fragment,{children:[(0,p.jsx)(`p`,{className:`auth-note`,children:`Enter your PIN to save these changes.`}),(0,p.jsx)(x,{pin:ee,onChange:M,onSubmit:()=>!N&&void B()}),F&&(0,p.jsx)(`p`,{role:`alert`,className:`auth-error`,children:F}),(0,p.jsxs)(`div`,{className:`approval-actions`,children:[(0,p.jsx)(`button`,{type:`button`,style:d,className:`primary`,disabled:N||ee.length<6,onClick:()=>void B(),children:`Save`}),(0,p.jsx)(`button`,{type:`button`,style:d,onClick:()=>{j(!1),M(``),I(null)},children:`Back`})]})]}):(0,p.jsxs)(p.Fragment,{children:[(0,p.jsx)(`h4`,{className:`plugins-heading`,children:e.name}),(0,p.jsx)(`p`,{className:`auth-note`,children:le?e.description:e.detail||e.description}),(0,p.jsx)(`ol`,{className:`integration-steps`,children:e.steps.map((e,t)=>(0,p.jsx)(`li`,{className:e.done?`done`:void 0,children:e.text},t))}),oe&&(0,p.jsx)(Uu,{api:o}),se&&(0,p.jsx)(Ru,{api:s}),le&&(0,p.jsx)(Nu,{api:c}),ue&&(0,p.jsx)($u,{api:u}),ae&&S&&(0,p.jsx)(ku,{view:w,setView:T,api:a}),ie&&_&&(0,p.jsx)(od,{view:y,setView:b,secret:E,setSecret:D,api:i}),!ie&&!ae&&!oe&&!se&&!ce&&!le&&!ue&&f&&(re?(0,p.jsx)(Ne,{view:{...h.telegram,enabled:e.enabled},secret:E,setSecret:D,api:r}):(0,p.jsx)(Pe,{view:h.twilio,setView:e=>g({...h,twilio:e}),secret:E,setSecret:D,webhook:O?.twilio.webhook??null})),te&&!z&&(0,p.jsx)(`p`,{className:`auth-note`,children:te}),F&&(0,p.jsx)(`p`,{role:`alert`,className:`auth-error`,children:F}),(0,p.jsxs)(`div`,{className:`approval-actions`,children:[!de&&(0,p.jsx)(`button`,{type:`button`,style:d,className:`primary`,disabled:!z||N||ae&&Tu(w)!==null,onClick:()=>j(!0),children:z?`Save…`:`Save`}),(0,p.jsx)(`button`,{type:`button`,style:d,onClick:t,children:`Back`})]})]})}async function md(e,t={}){let n;try{n=await fetch(`/api/plugins${e}`,t)}catch{throw Error(`Could not reach Friend. Check the connection.`)}if(!n.ok){let e=``;try{e=(await n.json()).error??``}catch{}throw Error(e||(n.status===401?`Please sign in again.`:n.status===429?`Too many attempts. Wait a moment.`:`The request failed (${n.status}).`))}return await n.json()}var hd=(e,t)=>({method:e,...t===void 0?{}:{headers:{"content-type":`application/json`},body:JSON.stringify(t)}}),gd={list:()=>md(``),install:async(e,t)=>{await md(`/install`,hd(`POST`,{id:e,pin:t}))},setEnabled:async(e,t,n)=>{await md(`/${encodeURIComponent(e)}/enabled`,hd(`POST`,{enabled:t,...n?{pin:n}:{}}))},remove:async e=>{await md(`/${encodeURIComponent(e)}`,hd(`DELETE`))},reload:async()=>{await md(`/reload`,hd(`POST`,{}))}},_d=(e,t)=>`${e} ${t}${e===1?``:`s`}`,vd={"not-installed":``,"needs-setup":`Needs setup`,off:`Off`,connecting:`Connecting…`,online:`On`,error:`Not working`},yd=e=>({id:e.id,name:e.name,version:``,description:e.description,tools:0,skills:0,error:null,installed:!1});function bd({api:e=gd,onClose:t,initialConfigure:n}){let[r,i]=(0,l.useState)(null),[a,o]=(0,l.useState)(null),[s,c]=(0,l.useState)(n??null),[u,f]=(0,l.useState)(``),[m,h]=(0,l.useState)(!1),[g,_]=(0,l.useState)(null),v=(0,l.useRef)(!0);(0,l.useEffect)(()=>{n&&c(n)},[n]);let y=(0,l.useCallback)(async()=>{try{let t=await e.list();v.current&&i(t)}catch(e){v.current&&_(e.message)}},[e]);(0,l.useEffect)(()=>(v.current=!0,y(),()=>{v.current=!1}),[y]);let b=async e=>{_(null),h(!0);try{if(await e(),!v.current)return;o(null),await y()}catch(e){v.current&&_(e.message)}finally{v.current&&(h(!1),f(``))}},S=()=>{a&&b(()=>a.kind===`install`?e.install(a.plugin.id,u):e.setEnabled(a.id,!0,u))},C=r?.integrations??[],w=(r?.catalog??[]).filter(e=>!e.installed),T=C.filter(e=>e.installed),E=C.filter(e=>!e.installed),D=s?C.find(e=>e.id===s&&e.installed):void 0;return(0,p.jsxs)(`div`,{className:`approval plugins glass`,role:`dialog`,"aria-label":`Plugins`,style:{pointerEvents:`auto`},children:[(0,p.jsx)(`div`,{className:`approval-head`,children:(0,p.jsx)(`span`,{className:`approval-title`,children:`Plugins`})}),(0,p.jsx)(`div`,{className:`plugins-body`,children:a?(0,p.jsxs)(p.Fragment,{children:[(0,p.jsx)(`p`,{className:`auth-note`,children:a.kind===`install`?a.integration?`Install ${a.plugin.name}? It connects Friend to an outside service, and you set it up afterwards. Enter your PIN to confirm.`:`Install ${a.plugin.name}? ${a.plugin.tools>0?`Its tools run in a Docker sandbox with no network and no access to your files, and ask for your approval every time. `:``}Enter your PIN to confirm.`:`Switch on ${a.name}? Enter your PIN to confirm.`}),(0,p.jsx)(x,{pin:u,onChange:f,onSubmit:()=>!m&&S()}),g&&(0,p.jsx)(`p`,{role:`alert`,className:`auth-error`,children:g}),(0,p.jsxs)(`div`,{className:`approval-actions`,children:[(0,p.jsx)(`button`,{type:`button`,style:d,className:`primary`,disabled:m||u.length<6,onClick:S,children:`Confirm`}),(0,p.jsx)(`button`,{type:`button`,style:d,onClick:()=>{o(null),f(``),_(null)},children:`Back`})]})]}):D?(0,p.jsx)(pd,{integration:D,onBack:()=>{c(null),y()}}):(0,p.jsxs)(p.Fragment,{children:[g&&(0,p.jsx)(`p`,{role:`alert`,className:`auth-error`,children:g}),(0,p.jsx)(`h4`,{className:`plugins-heading`,children:`Installed`}),r&&r.installed.length===0&&T.length===0&&(0,p.jsx)(`p`,{className:`auth-note`,children:`Nothing installed yet.`}),(0,p.jsxs)(`ul`,{className:`plugin-list`,children:[T.map(t=>(0,p.jsxs)(`li`,{"data-integration":t.id,children:[(0,p.jsxs)(`div`,{className:`plugin-info`,children:[(0,p.jsx)(`strong`,{children:t.name}),` `,(0,p.jsx)(`small`,{children:vd[t.state]}),(0,p.jsx)(`div`,{className:t.state===`error`?`auth-error`:`auth-note`,children:t.detail})]}),(0,p.jsxs)(`div`,{className:`plugin-actions`,children:[(0,p.jsx)(`button`,{type:`button`,style:d,className:`primary`,disabled:m,onClick:()=>c(t.id),children:`Configure`}),(0,p.jsx)(`button`,{type:`button`,style:d,disabled:m,onClick:()=>t.enabled?void b(()=>e.setEnabled(t.id,!1,void 0)):o({kind:`enable`,id:t.id,name:t.name}),children:t.enabled?`Turn off`:`Turn on`}),(0,p.jsx)(`button`,{type:`button`,style:d,className:`danger`,disabled:m,onClick:()=>void b(()=>e.remove(t.id)),children:`Remove`})]})]},t.id)),(r?.installed??[]).map(t=>(0,p.jsxs)(`li`,{children:[(0,p.jsxs)(`div`,{className:`plugin-info`,children:[(0,p.jsx)(`strong`,{children:t.name}),` `,(0,p.jsx)(`small`,{children:t.version}),(0,p.jsx)(`div`,{className:`auth-note`,children:t.error?`This plugin cannot be used: ${t.error}`:`${_d(t.skills.length,`skill`)}, ${_d(t.tools.length,`tool`)}${t.enabled?``:` (off)`}`})]}),(0,p.jsxs)(`div`,{className:`plugin-actions`,children:[(0,p.jsx)(`button`,{type:`button`,style:d,disabled:m,onClick:()=>t.enabled?void b(()=>e.setEnabled(t.id,!1,void 0)):o({kind:`enable`,id:t.id,name:t.name}),children:t.enabled?`Turn off`:`Turn on`}),(0,p.jsx)(`button`,{type:`button`,style:d,className:`danger`,disabled:m,onClick:()=>void b(()=>e.remove(t.id)),children:`Remove`})]})]},t.id))]}),(0,p.jsx)(`h4`,{className:`plugins-heading`,children:`Available`}),r&&w.length===0&&E.length===0&&(0,p.jsx)(`p`,{className:`auth-note`,children:`Everything in the catalog is installed.`}),(0,p.jsxs)(`ul`,{className:`plugin-list`,children:[E.map(e=>(0,p.jsxs)(`li`,{"data-integration":e.id,children:[(0,p.jsxs)(`div`,{className:`plugin-info`,children:[(0,p.jsx)(`strong`,{children:e.name}),` `,(0,p.jsx)(`small`,{children:`integration`}),(0,p.jsx)(`div`,{className:`auth-note`,children:e.description})]}),(0,p.jsx)(`div`,{className:`plugin-actions`,children:(0,p.jsx)(`button`,{type:`button`,style:d,className:`primary`,disabled:m,onClick:()=>o({kind:`install`,plugin:yd(e),integration:!0}),children:`Install`})})]},e.id)),w.map(e=>(0,p.jsxs)(`li`,{children:[(0,p.jsxs)(`div`,{className:`plugin-info`,children:[(0,p.jsx)(`strong`,{children:e.name}),` `,(0,p.jsx)(`small`,{children:e.version}),(0,p.jsx)(`div`,{className:`auth-note`,children:e.error?`Cannot be installed: ${e.error}`:`${e.description} (${_d(e.skills,`skill`)}, ${_d(e.tools,`tool`)})`})]}),(0,p.jsx)(`div`,{className:`plugin-actions`,children:(0,p.jsx)(`button`,{type:`button`,style:d,className:`primary`,disabled:m||!!e.error,onClick:()=>o({kind:`install`,plugin:e}),children:`Install`})})]},e.id))]}),(0,p.jsxs)(`div`,{className:`approval-actions`,children:[(0,p.jsx)(`button`,{type:`button`,style:d,disabled:m,onClick:()=>void b(()=>e.reload()),children:`Reload plugins`}),(0,p.jsx)(`button`,{type:`button`,style:d,onClick:t,children:`Close`})]})]})})]})}function xd(e){return e.webgl?e.reducedMotion?6e3:e.memoryGb===void 0?8e3:e.memoryGb>=8?12e3:e.memoryGb>=4?9e3:6e3:0}function Sd(){let e=!1;try{let t=document.createElement(`canvas`);e=!!(t.getContext(`webgl2`)||t.getContext(`webgl`))}catch{e=!1}return{webgl:e,memoryGb:navigator.deviceMemory,reducedMotion:typeof matchMedia==`function`&&matchMedia(`(prefers-reduced-motion: reduce)`).matches}}var Cd={idle:{speed:.15,noise:.05,brightness:.85,size:1.6,rotate:.08,tighten:0},listening:{speed:.4,noise:.1,brightness:1.1,size:1.9,rotate:.15,tighten:.08},thinking:{speed:1.1,noise:.22,brightness:1,size:1.7,rotate:.35,tighten:0},speaking:{speed:.6,noise:.12,brightness:1.25,size:1.8,rotate:.12,tighten:0}},wd=e=>Number.isFinite(e)?Math.min(1,Math.max(0,e)):0,Td=class{state=`idle`;amplitudeTarget=0;intensity=.6;amp=0;cur={...Cd.idle};phase=0;angle=0;motion;constructor(e={}){this.motion=e.reducedMotion?.25:1}setState(e){this.state=e}setAmplitude(e){this.amplitudeTarget=wd(e)}setIntensity(e){this.intensity=wd(e)}tick(e){let t=Cd[this.state],n=1-Math.exp(-e*3);for(let e of Object.keys(t))this.cur[e]+=(t[e]-this.cur[e])*n;this.amp+=(this.amplitudeTarget-this.amp)*(1-Math.exp(-e*12)),this.amplitudeTarget*=Math.exp(-e*3),this.phase+=e*this.cur.speed*this.motion,this.angle+=e*this.cur.rotate*this.motion}uniforms(){return{...this.cur,brightness:this.cur.brightness*(.5+this.intensity)/1.1,speed:this.cur.speed*this.motion,rotate:this.cur.rotate*this.motion,amplitude:this.amp*(this.motion===1?1:.5),phase:this.phase,angle:this.angle}}},Ed=1e3,Dd=1001,Od=1002,kd=1003,Ad=1004,jd=1005,Md=1006,Nd=1007,Pd=1008,Fd=1009,Id=1010,Ld=1011,Rd=1012,zd=1013,Bd=1014,Vd=1015,Hd=1016,Ud=1017,Wd=1018,Gd=1020,Kd=35902,qd=35899,Jd=1021,Yd=1022,Xd=1023,Zd=1026,Qd=1027,$d=1028,ef=1029,tf=1030,nf=1031,rf=1033,af=33776,of=33777,sf=33778,cf=33779,lf=35840,uf=35841,df=35842,ff=35843,pf=36196,mf=37492,hf=37496,gf=37488,_f=37489,vf=37490,yf=37491,bf=37808,xf=37809,Sf=37810,Cf=37811,wf=37812,Tf=37813,Ef=37814,Df=37815,Of=37816,kf=37817,Af=37818,jf=37819,Mf=37820,Nf=37821,Pf=36492,Ff=36494,If=36495,Lf=36283,Rf=36284,zf=36285,Bf=36286,Vf=2300,Hf=2301,Uf=2302,Wf=2303,Gf=2400,Kf=2401,qf=2402,Jf=3200,Yf=`srgb`,Xf=`srgb-linear`,Zf=`linear`,Qf=`srgb`,$f=7680,ep=35044,tp=2e3;function np(e){for(let t=e.length-1;t>=0;--t)if(e[t]>=65535)return!0;return!1}function rp(e){return ArrayBuffer.isView(e)&&!(e instanceof DataView)}function ip(e){return document.createElementNS(`http://www.w3.org/1999/xhtml`,e)}function ap(){let e=ip(`canvas`);return e.style.display=`block`,e}var op={};function sp(...e){let t=`THREE.`+e.shift();console.log(t,...e)}function cp(e){let t=e[0];if(typeof t==`string`&&t.startsWith(`TSL:`)){let t=e[1];t&&t.isStackTrace?e[0]+=` `+t.getLocation():e[1]=`Stack trace not available. Enable "THREE.Node.captureStackTrace" to capture stack traces.`}return e}function X(...e){e=cp(e);let t=`THREE.`+e.shift();{let n=e[0];n&&n.isStackTrace?console.warn(n.getError(t)):console.warn(t,...e)}}function Z(...e){e=cp(e);let t=`THREE.`+e.shift();{let n=e[0];n&&n.isStackTrace?console.error(n.getError(t)):console.error(t,...e)}}function lp(...e){let t=e.join(` `);t in op||(op[t]=!0,X(...e))}function up(e,t,n){return new Promise(function(r,i){function a(){switch(e.clientWaitSync(t,e.SYNC_FLUSH_COMMANDS_BIT,0)){case e.WAIT_FAILED:i();break;case e.TIMEOUT_EXPIRED:setTimeout(a,n);break;default:r()}}setTimeout(a,n)})}var dp={0:1,2:6,4:7,3:5,1:0,6:2,7:4,5:3},fp=class{addEventListener(e,t){this._listeners===void 0&&(this._listeners={});let n=this._listeners;n[e]===void 0&&(n[e]=[]),n[e].indexOf(t)===-1&&n[e].push(t)}hasEventListener(e,t){let n=this._listeners;return n!==void 0&&n[e]!==void 0&&n[e].indexOf(t)!==-1}removeEventListener(e,t){let n=this._listeners;if(n===void 0)return;let r=n[e];if(r!==void 0){let e=r.indexOf(t);e!==-1&&r.splice(e,1)}}dispatchEvent(e){let t=this._listeners;if(t===void 0)return;let n=t[e.type];if(n!==void 0){e.target=this;let t=n.slice(0);for(let n=0,r=t.length;n<r;n++)t[n].call(this,e);e.target=null}}},pp=`00.01.02.03.04.05.06.07.08.09.0a.0b.0c.0d.0e.0f.10.11.12.13.14.15.16.17.18.19.1a.1b.1c.1d.1e.1f.20.21.22.23.24.25.26.27.28.29.2a.2b.2c.2d.2e.2f.30.31.32.33.34.35.36.37.38.39.3a.3b.3c.3d.3e.3f.40.41.42.43.44.45.46.47.48.49.4a.4b.4c.4d.4e.4f.50.51.52.53.54.55.56.57.58.59.5a.5b.5c.5d.5e.5f.60.61.62.63.64.65.66.67.68.69.6a.6b.6c.6d.6e.6f.70.71.72.73.74.75.76.77.78.79.7a.7b.7c.7d.7e.7f.80.81.82.83.84.85.86.87.88.89.8a.8b.8c.8d.8e.8f.90.91.92.93.94.95.96.97.98.99.9a.9b.9c.9d.9e.9f.a0.a1.a2.a3.a4.a5.a6.a7.a8.a9.aa.ab.ac.ad.ae.af.b0.b1.b2.b3.b4.b5.b6.b7.b8.b9.ba.bb.bc.bd.be.bf.c0.c1.c2.c3.c4.c5.c6.c7.c8.c9.ca.cb.cc.cd.ce.cf.d0.d1.d2.d3.d4.d5.d6.d7.d8.d9.da.db.dc.dd.de.df.e0.e1.e2.e3.e4.e5.e6.e7.e8.e9.ea.eb.ec.ed.ee.ef.f0.f1.f2.f3.f4.f5.f6.f7.f8.f9.fa.fb.fc.fd.fe.ff`.split(`.`),mp=Math.PI/180,hp=180/Math.PI;function gp(){let e=Math.random()*4294967295|0,t=Math.random()*4294967295|0,n=Math.random()*4294967295|0,r=Math.random()*4294967295|0;return(pp[e&255]+pp[e>>8&255]+pp[e>>16&255]+pp[e>>24&255]+`-`+pp[t&255]+pp[t>>8&255]+`-`+pp[t>>16&15|64]+pp[t>>24&255]+`-`+pp[n&63|128]+pp[n>>8&255]+`-`+pp[n>>16&255]+pp[n>>24&255]+pp[r&255]+pp[r>>8&255]+pp[r>>16&255]+pp[r>>24&255]).toLowerCase()}function _p(e,t,n){return Math.max(t,Math.min(n,e))}function vp(e,t){return(e%t+t)%t}function yp(e,t,n){return(1-n)*e+n*t}function bp(e,t){switch(t.constructor){case Float32Array:return e;case Uint32Array:return e/4294967295;case Uint16Array:return e/65535;case Uint8Array:case Uint8ClampedArray:return e/255;case Int32Array:return Math.max(e/2147483647,-1);case Int16Array:return Math.max(e/32767,-1);case Int8Array:return Math.max(e/127,-1);default:throw Error(`THREE.MathUtils: Invalid component type.`)}}function xp(e,t){switch(t.constructor){case Float32Array:return e;case Uint32Array:return Math.round(e*4294967295);case Uint16Array:return Math.round(e*65535);case Uint8Array:case Uint8ClampedArray:return Math.round(e*255);case Int32Array:return Math.round(e*2147483647);case Int16Array:return Math.round(e*32767);case Int8Array:return Math.round(e*127);default:throw Error(`THREE.MathUtils: Invalid component type.`)}}var Sp=class e{static{e.prototype.isVector2=!0}constructor(e=0,t=0){this.x=e,this.y=t}get width(){return this.x}set width(e){this.x=e}get height(){return this.y}set height(e){this.y=e}set(e,t){return this.x=e,this.y=t,this}setScalar(e){return this.x=e,this.y=e,this}setX(e){return this.x=e,this}setY(e){return this.y=e,this}setComponent(e,t){switch(e){case 0:this.x=t;break;case 1:this.y=t;break;default:throw Error(`THREE.Vector2: index is out of range: `+e)}return this}getComponent(e){switch(e){case 0:return this.x;case 1:return this.y;default:throw Error(`THREE.Vector2: index is out of range: `+e)}}clone(){return new this.constructor(this.x,this.y)}copy(e){return this.x=e.x,this.y=e.y,this}add(e){return this.x+=e.x,this.y+=e.y,this}addScalar(e){return this.x+=e,this.y+=e,this}addVectors(e,t){return this.x=e.x+t.x,this.y=e.y+t.y,this}addScaledVector(e,t){return this.x+=e.x*t,this.y+=e.y*t,this}sub(e){return this.x-=e.x,this.y-=e.y,this}subScalar(e){return this.x-=e,this.y-=e,this}subVectors(e,t){return this.x=e.x-t.x,this.y=e.y-t.y,this}multiply(e){return this.x*=e.x,this.y*=e.y,this}multiplyScalar(e){return this.x*=e,this.y*=e,this}divide(e){return this.x/=e.x,this.y/=e.y,this}divideScalar(e){return this.multiplyScalar(1/e)}applyMatrix3(e){let t=this.x,n=this.y,r=e.elements;return this.x=r[0]*t+r[3]*n+r[6],this.y=r[1]*t+r[4]*n+r[7],this}min(e){return this.x=Math.min(this.x,e.x),this.y=Math.min(this.y,e.y),this}max(e){return this.x=Math.max(this.x,e.x),this.y=Math.max(this.y,e.y),this}clamp(e,t){return this.x=_p(this.x,e.x,t.x),this.y=_p(this.y,e.y,t.y),this}clampScalar(e,t){return this.x=_p(this.x,e,t),this.y=_p(this.y,e,t),this}clampLength(e,t){let n=this.length();return this.divideScalar(n||1).multiplyScalar(_p(n,e,t))}floor(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this}ceil(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this}round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this}roundToZero(){return this.x=Math.trunc(this.x),this.y=Math.trunc(this.y),this}negate(){return this.x=-this.x,this.y=-this.y,this}dot(e){return this.x*e.x+this.y*e.y}cross(e){return this.x*e.y-this.y*e.x}lengthSq(){return this.x*this.x+this.y*this.y}length(){return Math.sqrt(this.x*this.x+this.y*this.y)}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)}normalize(){return this.divideScalar(this.length()||1)}angle(){return Math.atan2(-this.y,-this.x)+Math.PI}angleTo(e){let t=Math.sqrt(this.lengthSq()*e.lengthSq());if(t===0)return Math.PI/2;let n=this.dot(e)/t;return Math.acos(_p(n,-1,1))}distanceTo(e){return Math.sqrt(this.distanceToSquared(e))}distanceToSquared(e){let t=this.x-e.x,n=this.y-e.y;return t*t+n*n}manhattanDistanceTo(e){return Math.abs(this.x-e.x)+Math.abs(this.y-e.y)}setLength(e){return this.normalize().multiplyScalar(e)}lerp(e,t){return this.x+=(e.x-this.x)*t,this.y+=(e.y-this.y)*t,this}lerpVectors(e,t,n){return this.x=e.x+(t.x-e.x)*n,this.y=e.y+(t.y-e.y)*n,this}equals(e){return e.x===this.x&&e.y===this.y}fromArray(e,t=0){return this.x=e[t],this.y=e[t+1],this}toArray(e=[],t=0){return e[t]=this.x,e[t+1]=this.y,e}fromBufferAttribute(e,t){return this.x=e.getX(t),this.y=e.getY(t),this}rotateAround(e,t){let n=Math.cos(t),r=Math.sin(t),i=this.x-e.x,a=this.y-e.y;return this.x=i*n-a*r+e.x,this.y=i*r+a*n+e.y,this}random(){return this.x=Math.random(),this.y=Math.random(),this}*[Symbol.iterator](){yield this.x,yield this.y}},Cp=class{constructor(e=0,t=0,n=0,r=1){this.isQuaternion=!0,this._x=e,this._y=t,this._z=n,this._w=r}static slerpFlat(e,t,n,r,i,a,o){let s=n[r+0],c=n[r+1],l=n[r+2],u=n[r+3],d=i[a+0],f=i[a+1],p=i[a+2],m=i[a+3];if(u!==m||s!==d||c!==f||l!==p){let e=s*d+c*f+l*p+u*m;e<0&&(d=-d,f=-f,p=-p,m=-m,e=-e);let t=1-o;if(e<.9995){let n=Math.acos(e),r=Math.sin(n);t=Math.sin(t*n)/r,o=Math.sin(o*n)/r,s=s*t+d*o,c=c*t+f*o,l=l*t+p*o,u=u*t+m*o}else{s=s*t+d*o,c=c*t+f*o,l=l*t+p*o,u=u*t+m*o;let e=1/Math.sqrt(s*s+c*c+l*l+u*u);s*=e,c*=e,l*=e,u*=e}}e[t]=s,e[t+1]=c,e[t+2]=l,e[t+3]=u}static multiplyQuaternionsFlat(e,t,n,r,i,a){let o=n[r],s=n[r+1],c=n[r+2],l=n[r+3],u=i[a],d=i[a+1],f=i[a+2],p=i[a+3];return e[t]=o*p+l*u+s*f-c*d,e[t+1]=s*p+l*d+c*u-o*f,e[t+2]=c*p+l*f+o*d-s*u,e[t+3]=l*p-o*u-s*d-c*f,e}get x(){return this._x}set x(e){this._x=e,this._onChangeCallback()}get y(){return this._y}set y(e){this._y=e,this._onChangeCallback()}get z(){return this._z}set z(e){this._z=e,this._onChangeCallback()}get w(){return this._w}set w(e){this._w=e,this._onChangeCallback()}set(e,t,n,r){return this._x=e,this._y=t,this._z=n,this._w=r,this._onChangeCallback(),this}clone(){return new this.constructor(this._x,this._y,this._z,this._w)}copy(e){return this._x=e.x,this._y=e.y,this._z=e.z,this._w=e.w,this._onChangeCallback(),this}setFromEuler(e,t=!0){let n=e._x,r=e._y,i=e._z,a=e._order,o=Math.cos,s=Math.sin,c=o(n/2),l=o(r/2),u=o(i/2),d=s(n/2),f=s(r/2),p=s(i/2);switch(a){case`XYZ`:this._x=d*l*u+c*f*p,this._y=c*f*u-d*l*p,this._z=c*l*p+d*f*u,this._w=c*l*u-d*f*p;break;case`YXZ`:this._x=d*l*u+c*f*p,this._y=c*f*u-d*l*p,this._z=c*l*p-d*f*u,this._w=c*l*u+d*f*p;break;case`ZXY`:this._x=d*l*u-c*f*p,this._y=c*f*u+d*l*p,this._z=c*l*p+d*f*u,this._w=c*l*u-d*f*p;break;case`ZYX`:this._x=d*l*u-c*f*p,this._y=c*f*u+d*l*p,this._z=c*l*p-d*f*u,this._w=c*l*u+d*f*p;break;case`YZX`:this._x=d*l*u+c*f*p,this._y=c*f*u+d*l*p,this._z=c*l*p-d*f*u,this._w=c*l*u-d*f*p;break;case`XZY`:this._x=d*l*u-c*f*p,this._y=c*f*u-d*l*p,this._z=c*l*p+d*f*u,this._w=c*l*u+d*f*p;break;default:X(`Quaternion: .setFromEuler() encountered an unknown order: `+a)}return t===!0&&this._onChangeCallback(),this}setFromAxisAngle(e,t){let n=t/2,r=Math.sin(n);return this._x=e.x*r,this._y=e.y*r,this._z=e.z*r,this._w=Math.cos(n),this._onChangeCallback(),this}setFromRotationMatrix(e){let t=e.elements,n=t[0],r=t[4],i=t[8],a=t[1],o=t[5],s=t[9],c=t[2],l=t[6],u=t[10],d=n+o+u;if(d>0){let e=.5/Math.sqrt(d+1);this._w=.25/e,this._x=(l-s)*e,this._y=(i-c)*e,this._z=(a-r)*e}else if(n>o&&n>u){let e=2*Math.sqrt(1+n-o-u);this._w=(l-s)/e,this._x=.25*e,this._y=(r+a)/e,this._z=(i+c)/e}else if(o>u){let e=2*Math.sqrt(1+o-n-u);this._w=(i-c)/e,this._x=(r+a)/e,this._y=.25*e,this._z=(s+l)/e}else{let e=2*Math.sqrt(1+u-n-o);this._w=(a-r)/e,this._x=(i+c)/e,this._y=(s+l)/e,this._z=.25*e}return this._onChangeCallback(),this}setFromUnitVectors(e,t){let n=e.dot(t)+1;return n<1e-8?(n=0,Math.abs(e.x)>Math.abs(e.z)?(this._x=-e.y,this._y=e.x,this._z=0,this._w=n):(this._x=0,this._y=-e.z,this._z=e.y,this._w=n)):(this._x=e.y*t.z-e.z*t.y,this._y=e.z*t.x-e.x*t.z,this._z=e.x*t.y-e.y*t.x,this._w=n),this.normalize()}angleTo(e){return 2*Math.acos(Math.abs(_p(this.dot(e),-1,1)))}rotateTowards(e,t){let n=this.angleTo(e);if(n===0)return this;let r=Math.min(1,t/n);return this.slerp(e,r),this}identity(){return this.set(0,0,0,1)}invert(){return this.conjugate()}conjugate(){return this._x*=-1,this._y*=-1,this._z*=-1,this._onChangeCallback(),this}dot(e){return this._x*e._x+this._y*e._y+this._z*e._z+this._w*e._w}lengthSq(){return this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w}length(){return Math.sqrt(this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w)}normalize(){let e=this.length();return e===0?(this._x=0,this._y=0,this._z=0,this._w=1):(e=1/e,this._x*=e,this._y*=e,this._z*=e,this._w*=e),this._onChangeCallback(),this}multiply(e){return this.multiplyQuaternions(this,e)}premultiply(e){return this.multiplyQuaternions(e,this)}multiplyQuaternions(e,t){let n=e._x,r=e._y,i=e._z,a=e._w,o=t._x,s=t._y,c=t._z,l=t._w;return this._x=n*l+a*o+r*c-i*s,this._y=r*l+a*s+i*o-n*c,this._z=i*l+a*c+n*s-r*o,this._w=a*l-n*o-r*s-i*c,this._onChangeCallback(),this}slerp(e,t){let n=e._x,r=e._y,i=e._z,a=e._w,o=this.dot(e);o<0&&(n=-n,r=-r,i=-i,a=-a,o=-o);let s=1-t;if(o<.9995){let e=Math.acos(o),c=Math.sin(e);s=Math.sin(s*e)/c,t=Math.sin(t*e)/c,this._x=this._x*s+n*t,this._y=this._y*s+r*t,this._z=this._z*s+i*t,this._w=this._w*s+a*t,this._onChangeCallback()}else this._x=this._x*s+n*t,this._y=this._y*s+r*t,this._z=this._z*s+i*t,this._w=this._w*s+a*t,this.normalize();return this}slerpQuaternions(e,t,n){return this.copy(e).slerp(t,n)}random(){let e=2*Math.PI*Math.random(),t=2*Math.PI*Math.random(),n=Math.random(),r=Math.sqrt(1-n),i=Math.sqrt(n);return this.set(r*Math.sin(e),r*Math.cos(e),i*Math.sin(t),i*Math.cos(t))}equals(e){return e._x===this._x&&e._y===this._y&&e._z===this._z&&e._w===this._w}fromArray(e,t=0){return this._x=e[t],this._y=e[t+1],this._z=e[t+2],this._w=e[t+3],this._onChangeCallback(),this}toArray(e=[],t=0){return e[t]=this._x,e[t+1]=this._y,e[t+2]=this._z,e[t+3]=this._w,e}fromBufferAttribute(e,t){return this._x=e.getX(t),this._y=e.getY(t),this._z=e.getZ(t),this._w=e.getW(t),this._onChangeCallback(),this}toJSON(){return this.toArray()}_onChange(e){return this._onChangeCallback=e,this}_onChangeCallback(){}*[Symbol.iterator](){yield this._x,yield this._y,yield this._z,yield this._w}},Q=class e{static{e.prototype.isVector3=!0}constructor(e=0,t=0,n=0){this.x=e,this.y=t,this.z=n}set(e,t,n){return n===void 0&&(n=this.z),this.x=e,this.y=t,this.z=n,this}setScalar(e){return this.x=e,this.y=e,this.z=e,this}setX(e){return this.x=e,this}setY(e){return this.y=e,this}setZ(e){return this.z=e,this}setComponent(e,t){switch(e){case 0:this.x=t;break;case 1:this.y=t;break;case 2:this.z=t;break;default:throw Error(`THREE.Vector3: index is out of range: `+e)}return this}getComponent(e){switch(e){case 0:return this.x;case 1:return this.y;case 2:return this.z;default:throw Error(`THREE.Vector3: index is out of range: `+e)}}clone(){return new this.constructor(this.x,this.y,this.z)}copy(e){return this.x=e.x,this.y=e.y,this.z=e.z,this}add(e){return this.x+=e.x,this.y+=e.y,this.z+=e.z,this}addScalar(e){return this.x+=e,this.y+=e,this.z+=e,this}addVectors(e,t){return this.x=e.x+t.x,this.y=e.y+t.y,this.z=e.z+t.z,this}addScaledVector(e,t){return this.x+=e.x*t,this.y+=e.y*t,this.z+=e.z*t,this}sub(e){return this.x-=e.x,this.y-=e.y,this.z-=e.z,this}subScalar(e){return this.x-=e,this.y-=e,this.z-=e,this}subVectors(e,t){return this.x=e.x-t.x,this.y=e.y-t.y,this.z=e.z-t.z,this}multiply(e){return this.x*=e.x,this.y*=e.y,this.z*=e.z,this}multiplyScalar(e){return this.x*=e,this.y*=e,this.z*=e,this}multiplyVectors(e,t){return this.x=e.x*t.x,this.y=e.y*t.y,this.z=e.z*t.z,this}applyEuler(e){return this.applyQuaternion(Tp.setFromEuler(e))}applyAxisAngle(e,t){return this.applyQuaternion(Tp.setFromAxisAngle(e,t))}applyMatrix3(e){let t=this.x,n=this.y,r=this.z,i=e.elements;return this.x=i[0]*t+i[3]*n+i[6]*r,this.y=i[1]*t+i[4]*n+i[7]*r,this.z=i[2]*t+i[5]*n+i[8]*r,this}applyNormalMatrix(e){return this.applyMatrix3(e).normalize()}applyMatrix4(e){let t=this.x,n=this.y,r=this.z,i=e.elements,a=1/(i[3]*t+i[7]*n+i[11]*r+i[15]);return this.x=(i[0]*t+i[4]*n+i[8]*r+i[12])*a,this.y=(i[1]*t+i[5]*n+i[9]*r+i[13])*a,this.z=(i[2]*t+i[6]*n+i[10]*r+i[14])*a,this}applyQuaternion(e){let t=this.x,n=this.y,r=this.z,i=e.x,a=e.y,o=e.z,s=e.w,c=2*(a*r-o*n),l=2*(o*t-i*r),u=2*(i*n-a*t);return this.x=t+s*c+a*u-o*l,this.y=n+s*l+o*c-i*u,this.z=r+s*u+i*l-a*c,this}project(e){return this.applyMatrix4(e.matrixWorldInverse).applyMatrix4(e.projectionMatrix)}unproject(e){return this.applyMatrix4(e.projectionMatrixInverse).applyMatrix4(e.matrixWorld)}transformDirection(e){let t=this.x,n=this.y,r=this.z,i=e.elements;return this.x=i[0]*t+i[4]*n+i[8]*r,this.y=i[1]*t+i[5]*n+i[9]*r,this.z=i[2]*t+i[6]*n+i[10]*r,this.normalize()}divide(e){return this.x/=e.x,this.y/=e.y,this.z/=e.z,this}divideScalar(e){return this.multiplyScalar(1/e)}min(e){return this.x=Math.min(this.x,e.x),this.y=Math.min(this.y,e.y),this.z=Math.min(this.z,e.z),this}max(e){return this.x=Math.max(this.x,e.x),this.y=Math.max(this.y,e.y),this.z=Math.max(this.z,e.z),this}clamp(e,t){return this.x=_p(this.x,e.x,t.x),this.y=_p(this.y,e.y,t.y),this.z=_p(this.z,e.z,t.z),this}clampScalar(e,t){return this.x=_p(this.x,e,t),this.y=_p(this.y,e,t),this.z=_p(this.z,e,t),this}clampLength(e,t){let n=this.length();return this.divideScalar(n||1).multiplyScalar(_p(n,e,t))}floor(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this.z=Math.floor(this.z),this}ceil(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this.z=Math.ceil(this.z),this}round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this.z=Math.round(this.z),this}roundToZero(){return this.x=Math.trunc(this.x),this.y=Math.trunc(this.y),this.z=Math.trunc(this.z),this}negate(){return this.x=-this.x,this.y=-this.y,this.z=-this.z,this}dot(e){return this.x*e.x+this.y*e.y+this.z*e.z}lengthSq(){return this.x*this.x+this.y*this.y+this.z*this.z}length(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z)}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)+Math.abs(this.z)}normalize(){return this.divideScalar(this.length()||1)}setLength(e){return this.normalize().multiplyScalar(e)}lerp(e,t){return this.x+=(e.x-this.x)*t,this.y+=(e.y-this.y)*t,this.z+=(e.z-this.z)*t,this}lerpVectors(e,t,n){return this.x=e.x+(t.x-e.x)*n,this.y=e.y+(t.y-e.y)*n,this.z=e.z+(t.z-e.z)*n,this}cross(e){return this.crossVectors(this,e)}crossVectors(e,t){let n=e.x,r=e.y,i=e.z,a=t.x,o=t.y,s=t.z;return this.x=r*s-i*o,this.y=i*a-n*s,this.z=n*o-r*a,this}projectOnVector(e){let t=e.lengthSq();if(t===0)return this.set(0,0,0);let n=e.dot(this)/t;return this.copy(e).multiplyScalar(n)}projectOnPlane(e){return wp.copy(this).projectOnVector(e),this.sub(wp)}reflect(e){return this.sub(wp.copy(e).multiplyScalar(2*this.dot(e)))}angleTo(e){let t=Math.sqrt(this.lengthSq()*e.lengthSq());if(t===0)return Math.PI/2;let n=this.dot(e)/t;return Math.acos(_p(n,-1,1))}distanceTo(e){return Math.sqrt(this.distanceToSquared(e))}distanceToSquared(e){let t=this.x-e.x,n=this.y-e.y,r=this.z-e.z;return t*t+n*n+r*r}manhattanDistanceTo(e){return Math.abs(this.x-e.x)+Math.abs(this.y-e.y)+Math.abs(this.z-e.z)}setFromSpherical(e){return this.setFromSphericalCoords(e.radius,e.phi,e.theta)}setFromSphericalCoords(e,t,n){let r=Math.sin(t)*e;return this.x=r*Math.sin(n),this.y=Math.cos(t)*e,this.z=r*Math.cos(n),this}setFromCylindrical(e){return this.setFromCylindricalCoords(e.radius,e.theta,e.y)}setFromCylindricalCoords(e,t,n){return this.x=e*Math.sin(t),this.y=n,this.z=e*Math.cos(t),this}setFromMatrixPosition(e){let t=e.elements;return this.x=t[12],this.y=t[13],this.z=t[14],this}setFromMatrixScale(e){let t=this.setFromMatrixColumn(e,0).length(),n=this.setFromMatrixColumn(e,1).length(),r=this.setFromMatrixColumn(e,2).length();return this.x=t,this.y=n,this.z=r,this}setFromMatrixColumn(e,t){return this.fromArray(e.elements,t*4)}setFromMatrix3Column(e,t){return this.fromArray(e.elements,t*3)}setFromEuler(e){return this.x=e._x,this.y=e._y,this.z=e._z,this}setFromColor(e){return this.x=e.r,this.y=e.g,this.z=e.b,this}equals(e){return e.x===this.x&&e.y===this.y&&e.z===this.z}fromArray(e,t=0){return this.x=e[t],this.y=e[t+1],this.z=e[t+2],this}toArray(e=[],t=0){return e[t]=this.x,e[t+1]=this.y,e[t+2]=this.z,e}fromBufferAttribute(e,t){return this.x=e.getX(t),this.y=e.getY(t),this.z=e.getZ(t),this}random(){return this.x=Math.random(),this.y=Math.random(),this.z=Math.random(),this}randomDirection(){let e=Math.random()*Math.PI*2,t=Math.random()*2-1,n=Math.sqrt(1-t*t);return this.x=n*Math.cos(e),this.y=t,this.z=n*Math.sin(e),this}*[Symbol.iterator](){yield this.x,yield this.y,yield this.z}},wp=new Q,Tp=new Cp,Ep=class e{static{e.prototype.isMatrix3=!0}constructor(e,t,n,r,i,a,o,s,c){this.elements=[1,0,0,0,1,0,0,0,1],e!==void 0&&this.set(e,t,n,r,i,a,o,s,c)}set(e,t,n,r,i,a,o,s,c){let l=this.elements;return l[0]=e,l[1]=r,l[2]=o,l[3]=t,l[4]=i,l[5]=s,l[6]=n,l[7]=a,l[8]=c,this}identity(){return this.set(1,0,0,0,1,0,0,0,1),this}copy(e){let t=this.elements,n=e.elements;return t[0]=n[0],t[1]=n[1],t[2]=n[2],t[3]=n[3],t[4]=n[4],t[5]=n[5],t[6]=n[6],t[7]=n[7],t[8]=n[8],this}extractBasis(e,t,n){return e.setFromMatrix3Column(this,0),t.setFromMatrix3Column(this,1),n.setFromMatrix3Column(this,2),this}setFromMatrix4(e){let t=e.elements;return this.set(t[0],t[4],t[8],t[1],t[5],t[9],t[2],t[6],t[10]),this}multiply(e){return this.multiplyMatrices(this,e)}premultiply(e){return this.multiplyMatrices(e,this)}multiplyMatrices(e,t){let n=e.elements,r=t.elements,i=this.elements,a=n[0],o=n[3],s=n[6],c=n[1],l=n[4],u=n[7],d=n[2],f=n[5],p=n[8],m=r[0],h=r[3],g=r[6],_=r[1],v=r[4],y=r[7],b=r[2],x=r[5],S=r[8];return i[0]=a*m+o*_+s*b,i[3]=a*h+o*v+s*x,i[6]=a*g+o*y+s*S,i[1]=c*m+l*_+u*b,i[4]=c*h+l*v+u*x,i[7]=c*g+l*y+u*S,i[2]=d*m+f*_+p*b,i[5]=d*h+f*v+p*x,i[8]=d*g+f*y+p*S,this}multiplyScalar(e){let t=this.elements;return t[0]*=e,t[3]*=e,t[6]*=e,t[1]*=e,t[4]*=e,t[7]*=e,t[2]*=e,t[5]*=e,t[8]*=e,this}determinant(){let e=this.elements,t=e[0],n=e[1],r=e[2],i=e[3],a=e[4],o=e[5],s=e[6],c=e[7],l=e[8];return t*a*l-t*o*c-n*i*l+n*o*s+r*i*c-r*a*s}invert(){let e=this.elements,t=e[0],n=e[1],r=e[2],i=e[3],a=e[4],o=e[5],s=e[6],c=e[7],l=e[8],u=l*a-o*c,d=o*s-l*i,f=c*i-a*s,p=t*u+n*d+r*f;if(p===0)return this.set(0,0,0,0,0,0,0,0,0);let m=1/p;return e[0]=u*m,e[1]=(r*c-l*n)*m,e[2]=(o*n-r*a)*m,e[3]=d*m,e[4]=(l*t-r*s)*m,e[5]=(r*i-o*t)*m,e[6]=f*m,e[7]=(n*s-c*t)*m,e[8]=(a*t-n*i)*m,this}transpose(){let e,t=this.elements;return e=t[1],t[1]=t[3],t[3]=e,e=t[2],t[2]=t[6],t[6]=e,e=t[5],t[5]=t[7],t[7]=e,this}getNormalMatrix(e){return this.setFromMatrix4(e).invert().transpose()}transposeIntoArray(e){let t=this.elements;return e[0]=t[0],e[1]=t[3],e[2]=t[6],e[3]=t[1],e[4]=t[4],e[5]=t[7],e[6]=t[2],e[7]=t[5],e[8]=t[8],this}setUvTransform(e,t,n,r,i,a,o){let s=Math.cos(i),c=Math.sin(i);return this.set(n*s,n*c,-n*(s*a+c*o)+a+e,-r*c,r*s,-r*(-c*a+s*o)+o+t,0,0,1),this}scale(e,t){return lp(`Matrix3: .scale() is deprecated. Use .makeScale() instead.`),this.premultiply(Dp.makeScale(e,t)),this}rotate(e){return lp(`Matrix3: .rotate() is deprecated. Use .makeRotation() instead.`),this.premultiply(Dp.makeRotation(-e)),this}translate(e,t){return lp(`Matrix3: .translate() is deprecated. Use .makeTranslation() instead.`),this.premultiply(Dp.makeTranslation(e,t)),this}makeTranslation(e,t){return e.isVector2?this.set(1,0,e.x,0,1,e.y,0,0,1):this.set(1,0,e,0,1,t,0,0,1),this}makeRotation(e){let t=Math.cos(e),n=Math.sin(e);return this.set(t,-n,0,n,t,0,0,0,1),this}makeScale(e,t){return this.set(e,0,0,0,t,0,0,0,1),this}equals(e){let t=this.elements,n=e.elements;for(let e=0;e<9;e++)if(t[e]!==n[e])return!1;return!0}fromArray(e,t=0){for(let n=0;n<9;n++)this.elements[n]=e[n+t];return this}toArray(e=[],t=0){let n=this.elements;return e[t]=n[0],e[t+1]=n[1],e[t+2]=n[2],e[t+3]=n[3],e[t+4]=n[4],e[t+5]=n[5],e[t+6]=n[6],e[t+7]=n[7],e[t+8]=n[8],e}clone(){return new this.constructor().fromArray(this.elements)}},Dp=new Ep,Op=new Ep().set(.4123908,.3575843,.1804808,.212639,.7151687,.0721923,.0193308,.1191948,.9505322),kp=new Ep().set(3.2409699,-1.5373832,-.4986108,-.9692436,1.8759675,.0415551,.0556301,-.203977,1.0569715);function Ap(){let e={enabled:!0,workingColorSpace:Xf,spaces:{},convert:function(e,t,n){return this.enabled===!1||t===n||!t||!n?e:(this.spaces[t].transfer===`srgb`&&(e.r=Mp(e.r),e.g=Mp(e.g),e.b=Mp(e.b)),this.spaces[t].primaries!==this.spaces[n].primaries&&(e.applyMatrix3(this.spaces[t].toXYZ),e.applyMatrix3(this.spaces[n].fromXYZ)),this.spaces[n].transfer===`srgb`&&(e.r=Np(e.r),e.g=Np(e.g),e.b=Np(e.b)),e)},workingToColorSpace:function(e,t){return this.convert(e,this.workingColorSpace,t)},colorSpaceToWorking:function(e,t){return this.convert(e,t,this.workingColorSpace)},getPrimaries:function(e){return this.spaces[e].primaries},getTransfer:function(e){return e===``?Zf:this.spaces[e].transfer},getToneMappingMode:function(e){return this.spaces[e].outputColorSpaceConfig.toneMappingMode||`standard`},getLuminanceCoefficients:function(e,t=this.workingColorSpace){return e.fromArray(this.spaces[t].luminanceCoefficients)},define:function(e){Object.assign(this.spaces,e)},_getMatrix:function(e,t,n){return e.copy(this.spaces[t].toXYZ).multiply(this.spaces[n].fromXYZ)},_getDrawingBufferColorSpace:function(e){return this.spaces[e].outputColorSpaceConfig.drawingBufferColorSpace},_getUnpackColorSpace:function(e=this.workingColorSpace){return this.spaces[e].workingColorSpaceConfig.unpackColorSpace},fromWorkingColorSpace:function(t,n){return lp(`ColorManagement: .fromWorkingColorSpace() has been renamed to .workingToColorSpace().`),e.workingToColorSpace(t,n)},toWorkingColorSpace:function(t,n){return lp(`ColorManagement: .toWorkingColorSpace() has been renamed to .colorSpaceToWorking().`),e.colorSpaceToWorking(t,n)}},t=[.64,.33,.3,.6,.15,.06],n=[.2126,.7152,.0722],r=[.3127,.329];return e.define({[Xf]:{primaries:t,whitePoint:r,transfer:Zf,toXYZ:Op,fromXYZ:kp,luminanceCoefficients:n,workingColorSpaceConfig:{unpackColorSpace:Yf},outputColorSpaceConfig:{drawingBufferColorSpace:Yf}},[Yf]:{primaries:t,whitePoint:r,transfer:Qf,toXYZ:Op,fromXYZ:kp,luminanceCoefficients:n,outputColorSpaceConfig:{drawingBufferColorSpace:Yf}}}),e}var jp=Ap();function Mp(e){return e<.04045?e*.0773993808:(e*.9478672986+.0521327014)**2.4}function Np(e){return e<.0031308?e*12.92:1.055*e**.41666-.055}var Pp,Fp=class{static getDataURL(e,t=`image/png`){if(/^data:/i.test(e.src)||typeof HTMLCanvasElement>`u`)return e.src;let n;if(e instanceof HTMLCanvasElement)n=e;else{Pp===void 0&&(Pp=ip(`canvas`)),Pp.width=e.width,Pp.height=e.height;let t=Pp.getContext(`2d`);e instanceof ImageData?t.putImageData(e,0,0):t.drawImage(e,0,0,e.width,e.height),n=Pp}return n.toDataURL(t)}static sRGBToLinear(e){if(typeof HTMLImageElement<`u`&&e instanceof HTMLImageElement||typeof HTMLCanvasElement<`u`&&e instanceof HTMLCanvasElement||typeof ImageBitmap<`u`&&e instanceof ImageBitmap){let t=ip(`canvas`);t.width=e.width,t.height=e.height;let n=t.getContext(`2d`);n.drawImage(e,0,0,e.width,e.height);let r=n.getImageData(0,0,e.width,e.height),i=r.data;for(let e=0;e<i.length;e++)i[e]=Mp(i[e]/255)*255;return n.putImageData(r,0,0),t}if(e.data){let t=e.data.slice(0);for(let e=0;e<t.length;e++)t instanceof Uint8Array||t instanceof Uint8ClampedArray?t[e]=Math.floor(Mp(t[e]/255)*255):t[e]=Mp(t[e]);return{data:t,width:e.width,height:e.height}}return X(`ImageUtils.sRGBToLinear(): Unsupported image type. No color space conversion applied.`),e}},Ip=0,Lp=class{constructor(e=null){this.isTextureSource=!0,Object.defineProperty(this,"id",{value:Ip++}),this.uuid=gp(),this.data=e,this.dataReady=!0,this.version=0}getSize(e){let t=this.data;return typeof HTMLVideoElement<`u`&&t instanceof HTMLVideoElement?e.set(t.videoWidth,t.videoHeight,0):typeof VideoFrame<`u`&&t instanceof VideoFrame?e.set(t.displayWidth,t.displayHeight,0):t===null?e.set(0,0,0):e.set(t.width,t.height,t.depth||0),e}set needsUpdate(e){e===!0&&this.version++}toJSON(e){let t=e===void 0||typeof e==`string`;if(!t&&e.images[this.uuid]!==void 0)return e.images[this.uuid];let n={uuid:this.uuid,url:``},r=this.data;if(r!==null){let e;if(Array.isArray(r)){e=[];for(let t=0,n=r.length;t<n;t++)r[t].isDataTexture?e.push(Rp(r[t].image)):e.push(Rp(r[t]))}else e=Rp(r);n.url=e}return t||(e.images[this.uuid]=n),n}};function Rp(e){return typeof HTMLImageElement<`u`&&e instanceof HTMLImageElement||typeof HTMLCanvasElement<`u`&&e instanceof HTMLCanvasElement||typeof ImageBitmap<`u`&&e instanceof ImageBitmap?Fp.getDataURL(e):e.data?{data:Array.from(e.data),width:e.width,height:e.height,type:e.data.constructor.name}:(X(`Texture: Unable to serialize Texture.`),{})}var zp=0,Bp=new Q,Vp=class e extends fp{constructor(t=e.DEFAULT_IMAGE,n=e.DEFAULT_MAPPING,r=Dd,i=Dd,a=Md,o=Pd,s=Xd,c=Fd,l=e.DEFAULT_ANISOTROPY,u=``){super(),this.isTexture=!0,Object.defineProperty(this,"id",{value:zp++}),this.uuid=gp(),this.name=``,this.source=new Lp(t),this.mipmaps=[],this.mapping=n,this.channel=0,this.wrapS=r,this.wrapT=i,this.magFilter=a,this.minFilter=o,this.anisotropy=l,this.format=s,this.internalFormat=null,this.type=c,this.offset=new Sp(0,0),this.repeat=new Sp(1,1),this.center=new Sp(0,0),this.rotation=0,this.matrixAutoUpdate=!0,this.matrix=new Ep,this.generateMipmaps=!0,this.premultiplyAlpha=!1,this.flipY=!0,this.unpackAlignment=4,this.colorSpace=u,this.userData={},this.updateRanges=[],this.version=0,this.onUpdate=null,this.renderTarget=null,this.isRenderTargetTexture=!1,this.isArrayTexture=!!(t&&t.depth&&t.depth>1),this.pmremVersion=0,this.normalized=!1}get width(){return this.source.getSize(Bp).x}get height(){return this.source.getSize(Bp).y}get depth(){return this.source.getSize(Bp).z}get image(){return this.source.data}set image(e){this.source.data=e}updateMatrix(){this.matrix.setUvTransform(this.offset.x,this.offset.y,this.repeat.x,this.repeat.y,this.rotation,this.center.x,this.center.y)}addUpdateRange(e,t){this.updateRanges.push({start:e,count:t})}clearUpdateRanges(){this.updateRanges.length=0}clone(){return new this.constructor().copy(this)}copy(e){return this.name=e.name,this.source=e.source,this.mipmaps=e.mipmaps.slice(0),this.mapping=e.mapping,this.channel=e.channel,this.wrapS=e.wrapS,this.wrapT=e.wrapT,this.magFilter=e.magFilter,this.minFilter=e.minFilter,this.anisotropy=e.anisotropy,this.format=e.format,this.internalFormat=e.internalFormat,this.type=e.type,this.normalized=e.normalized,this.offset.copy(e.offset),this.repeat.copy(e.repeat),this.center.copy(e.center),this.rotation=e.rotation,this.matrixAutoUpdate=e.matrixAutoUpdate,this.matrix.copy(e.matrix),this.generateMipmaps=e.generateMipmaps,this.premultiplyAlpha=e.premultiplyAlpha,this.flipY=e.flipY,this.unpackAlignment=e.unpackAlignment,this.colorSpace=e.colorSpace,this.renderTarget=e.renderTarget,this.isRenderTargetTexture=e.isRenderTargetTexture,this.isArrayTexture=e.isArrayTexture,this.userData=JSON.parse(JSON.stringify(e.userData)),this.needsUpdate=!0,this}setValues(e){for(let t in e){let n=e[t];if(n===void 0){X(`Texture.setValues(): parameter '${t}' has value of undefined.`);continue}let r=this[t];if(r===void 0){X(`Texture.setValues(): property '${t}' does not exist.`);continue}r&&n&&r.isVector2&&n.isVector2||r&&n&&r.isVector3&&n.isVector3||r&&n&&r.isMatrix3&&n.isMatrix3?r.copy(n):this[t]=n}}toJSON(e){let t=e===void 0||typeof e==`string`;if(!t&&e.textures[this.uuid]!==void 0)return e.textures[this.uuid];let n={metadata:{version:4.7,type:`Texture`,generator:`Texture.toJSON`},uuid:this.uuid,name:this.name,image:this.source.toJSON(e).uuid,mapping:this.mapping,channel:this.channel,repeat:[this.repeat.x,this.repeat.y],offset:[this.offset.x,this.offset.y],center:[this.center.x,this.center.y],rotation:this.rotation,wrap:[this.wrapS,this.wrapT],format:this.format,internalFormat:this.internalFormat,type:this.type,normalized:this.normalized,colorSpace:this.colorSpace,minFilter:this.minFilter,magFilter:this.magFilter,anisotropy:this.anisotropy,flipY:this.flipY,generateMipmaps:this.generateMipmaps,premultiplyAlpha:this.premultiplyAlpha,unpackAlignment:this.unpackAlignment};return Object.keys(this.userData).length>0&&(n.userData=this.userData),t||(e.textures[this.uuid]=n),n}dispose(){this.dispatchEvent({type:`dispose`})}transformUv(e){if(this.mapping!==300)return e;if(e.applyMatrix3(this.matrix),e.x<0||e.x>1)switch(this.wrapS){case Ed:e.x-=Math.floor(e.x);break;case Dd:e.x=e.x<0?0:1;break;case Od:Math.abs(Math.floor(e.x)%2)===1?e.x=Math.ceil(e.x)-e.x:e.x-=Math.floor(e.x)}if(e.y<0||e.y>1)switch(this.wrapT){case Ed:e.y-=Math.floor(e.y);break;case Dd:e.y=e.y<0?0:1;break;case Od:Math.abs(Math.floor(e.y)%2)===1?e.y=Math.ceil(e.y)-e.y:e.y-=Math.floor(e.y)}return this.flipY&&(e.y=1-e.y),e}set needsUpdate(e){e===!0&&(this.version++,this.source.needsUpdate=!0)}set needsPMREMUpdate(e){e===!0&&this.pmremVersion++}};Vp.DEFAULT_IMAGE=null,Vp.DEFAULT_MAPPING=300,Vp.DEFAULT_ANISOTROPY=1;var Hp=class e{static{e.prototype.isVector4=!0}constructor(e=0,t=0,n=0,r=1){this.x=e,this.y=t,this.z=n,this.w=r}get width(){return this.z}set width(e){this.z=e}get height(){return this.w}set height(e){this.w=e}set(e,t,n,r){return this.x=e,this.y=t,this.z=n,this.w=r,this}setScalar(e){return this.x=e,this.y=e,this.z=e,this.w=e,this}setX(e){return this.x=e,this}setY(e){return this.y=e,this}setZ(e){return this.z=e,this}setW(e){return this.w=e,this}setComponent(e,t){switch(e){case 0:this.x=t;break;case 1:this.y=t;break;case 2:this.z=t;break;case 3:this.w=t;break;default:throw Error(`THREE.Vector4: index is out of range: `+e)}return this}getComponent(e){switch(e){case 0:return this.x;case 1:return this.y;case 2:return this.z;case 3:return this.w;default:throw Error(`THREE.Vector4: index is out of range: `+e)}}clone(){return new this.constructor(this.x,this.y,this.z,this.w)}copy(e){return this.x=e.x,this.y=e.y,this.z=e.z,this.w=e.w===void 0?1:e.w,this}add(e){return this.x+=e.x,this.y+=e.y,this.z+=e.z,this.w+=e.w,this}addScalar(e){return this.x+=e,this.y+=e,this.z+=e,this.w+=e,this}addVectors(e,t){return this.x=e.x+t.x,this.y=e.y+t.y,this.z=e.z+t.z,this.w=e.w+t.w,this}addScaledVector(e,t){return this.x+=e.x*t,this.y+=e.y*t,this.z+=e.z*t,this.w+=e.w*t,this}sub(e){return this.x-=e.x,this.y-=e.y,this.z-=e.z,this.w-=e.w,this}subScalar(e){return this.x-=e,this.y-=e,this.z-=e,this.w-=e,this}subVectors(e,t){return this.x=e.x-t.x,this.y=e.y-t.y,this.z=e.z-t.z,this.w=e.w-t.w,this}multiply(e){return this.x*=e.x,this.y*=e.y,this.z*=e.z,this.w*=e.w,this}multiplyScalar(e){return this.x*=e,this.y*=e,this.z*=e,this.w*=e,this}applyMatrix4(e){let t=this.x,n=this.y,r=this.z,i=this.w,a=e.elements;return this.x=a[0]*t+a[4]*n+a[8]*r+a[12]*i,this.y=a[1]*t+a[5]*n+a[9]*r+a[13]*i,this.z=a[2]*t+a[6]*n+a[10]*r+a[14]*i,this.w=a[3]*t+a[7]*n+a[11]*r+a[15]*i,this}divide(e){return this.x/=e.x,this.y/=e.y,this.z/=e.z,this.w/=e.w,this}divideScalar(e){return this.multiplyScalar(1/e)}setAxisAngleFromQuaternion(e){this.w=2*Math.acos(e.w);let t=Math.sqrt(1-e.w*e.w);return t<1e-4?(this.x=1,this.y=0,this.z=0):(this.x=e.x/t,this.y=e.y/t,this.z=e.z/t),this}setAxisAngleFromRotationMatrix(e){let t,n,r,i,a=.01,o=.1,s=e.elements,c=s[0],l=s[4],u=s[8],d=s[1],f=s[5],p=s[9],m=s[2],h=s[6],g=s[10];if(Math.abs(l-d)<a&&Math.abs(u-m)<a&&Math.abs(p-h)<a){if(Math.abs(l+d)<o&&Math.abs(u+m)<o&&Math.abs(p+h)<o&&Math.abs(c+f+g-3)<o)return this.set(1,0,0,0),this;t=Math.PI;let e=(c+1)/2,s=(f+1)/2,_=(g+1)/2,v=(l+d)/4,y=(u+m)/4,b=(p+h)/4;return e>s&&e>_?e<a?(n=0,r=.707106781,i=.707106781):(n=Math.sqrt(e),r=v/n,i=y/n):s>_?s<a?(n=.707106781,r=0,i=.707106781):(r=Math.sqrt(s),n=v/r,i=b/r):_<a?(n=.707106781,r=.707106781,i=0):(i=Math.sqrt(_),n=y/i,r=b/i),this.set(n,r,i,t),this}let _=Math.sqrt((h-p)*(h-p)+(u-m)*(u-m)+(d-l)*(d-l));return Math.abs(_)<.001&&(_=1),this.x=(h-p)/_,this.y=(u-m)/_,this.z=(d-l)/_,this.w=Math.acos((c+f+g-1)/2),this}setFromMatrixPosition(e){let t=e.elements;return this.x=t[12],this.y=t[13],this.z=t[14],this.w=t[15],this}min(e){return this.x=Math.min(this.x,e.x),this.y=Math.min(this.y,e.y),this.z=Math.min(this.z,e.z),this.w=Math.min(this.w,e.w),this}max(e){return this.x=Math.max(this.x,e.x),this.y=Math.max(this.y,e.y),this.z=Math.max(this.z,e.z),this.w=Math.max(this.w,e.w),this}clamp(e,t){return this.x=_p(this.x,e.x,t.x),this.y=_p(this.y,e.y,t.y),this.z=_p(this.z,e.z,t.z),this.w=_p(this.w,e.w,t.w),this}clampScalar(e,t){return this.x=_p(this.x,e,t),this.y=_p(this.y,e,t),this.z=_p(this.z,e,t),this.w=_p(this.w,e,t),this}clampLength(e,t){let n=this.length();return this.divideScalar(n||1).multiplyScalar(_p(n,e,t))}floor(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this.z=Math.floor(this.z),this.w=Math.floor(this.w),this}ceil(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this.z=Math.ceil(this.z),this.w=Math.ceil(this.w),this}round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this.z=Math.round(this.z),this.w=Math.round(this.w),this}roundToZero(){return this.x=Math.trunc(this.x),this.y=Math.trunc(this.y),this.z=Math.trunc(this.z),this.w=Math.trunc(this.w),this}negate(){return this.x=-this.x,this.y=-this.y,this.z=-this.z,this.w=-this.w,this}dot(e){return this.x*e.x+this.y*e.y+this.z*e.z+this.w*e.w}lengthSq(){return this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w}length(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w)}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)+Math.abs(this.z)+Math.abs(this.w)}normalize(){return this.divideScalar(this.length()||1)}setLength(e){return this.normalize().multiplyScalar(e)}lerp(e,t){return this.x+=(e.x-this.x)*t,this.y+=(e.y-this.y)*t,this.z+=(e.z-this.z)*t,this.w+=(e.w-this.w)*t,this}lerpVectors(e,t,n){return this.x=e.x+(t.x-e.x)*n,this.y=e.y+(t.y-e.y)*n,this.z=e.z+(t.z-e.z)*n,this.w=e.w+(t.w-e.w)*n,this}equals(e){return e.x===this.x&&e.y===this.y&&e.z===this.z&&e.w===this.w}fromArray(e,t=0){return this.x=e[t],this.y=e[t+1],this.z=e[t+2],this.w=e[t+3],this}toArray(e=[],t=0){return e[t]=this.x,e[t+1]=this.y,e[t+2]=this.z,e[t+3]=this.w,e}fromBufferAttribute(e,t){return this.x=e.getX(t),this.y=e.getY(t),this.z=e.getZ(t),this.w=e.getW(t),this}random(){return this.x=Math.random(),this.y=Math.random(),this.z=Math.random(),this.w=Math.random(),this}*[Symbol.iterator](){yield this.x,yield this.y,yield this.z,yield this.w}},Up=class extends fp{constructor(e=1,t=1,n={}){super(),n=Object.assign({generateMipmaps:!1,internalFormat:null,minFilter:Md,depthBuffer:!0,stencilBuffer:!1,resolveColorBuffer:!0,resolveDepthBuffer:!0,resolveStencilBuffer:!0,storeMultisampledColorBuffer:!0,storeMultisampledDepthBuffer:!0,storeMultisampledStencilBuffer:!0,depthTexture:null,samples:0,count:1,depth:1,multiview:!1,useArrayDepthTexture:!1},n),this.isRenderTarget=!0,this.width=e,this.height=t,this.depth=n.depth,this.scissor=new Hp(0,0,e,t),this.scissorTest=!1,this.viewport=new Hp(0,0,e,t),this.textures=[];let r=new Vp({width:e,height:t,depth:n.depth}),i=n.count;for(let e=0;e<i;e++)this.textures[e]=r.clone(),this.textures[e].isRenderTargetTexture=!0,this.textures[e].renderTarget=this;this._setTextureOptions(n),this.depthBuffer=n.depthBuffer,this.stencilBuffer=n.stencilBuffer,this.resolveColorBuffer=n.resolveColorBuffer,this.resolveDepthBuffer=n.resolveDepthBuffer,this.resolveStencilBuffer=n.resolveStencilBuffer,this.storeMultisampledColorBuffer=n.storeMultisampledColorBuffer,this.storeMultisampledDepthBuffer=n.storeMultisampledDepthBuffer,this.storeMultisampledStencilBuffer=n.storeMultisampledStencilBuffer,this._depthTexture=null,this.depthTexture=n.depthTexture,this.samples=n.samples,this.multiview=n.multiview,this.useArrayDepthTexture=n.useArrayDepthTexture}_setTextureOptions(e={}){let t={minFilter:Md,generateMipmaps:!1,flipY:!1,internalFormat:null};e.mapping!==void 0&&(t.mapping=e.mapping),e.wrapS!==void 0&&(t.wrapS=e.wrapS),e.wrapT!==void 0&&(t.wrapT=e.wrapT),e.wrapR!==void 0&&(t.wrapR=e.wrapR),e.magFilter!==void 0&&(t.magFilter=e.magFilter),e.minFilter!==void 0&&(t.minFilter=e.minFilter),e.format!==void 0&&(t.format=e.format),e.type!==void 0&&(t.type=e.type),e.anisotropy!==void 0&&(t.anisotropy=e.anisotropy),e.colorSpace!==void 0&&(t.colorSpace=e.colorSpace),e.flipY!==void 0&&(t.flipY=e.flipY),e.generateMipmaps!==void 0&&(t.generateMipmaps=e.generateMipmaps),e.internalFormat!==void 0&&(t.internalFormat=e.internalFormat);for(let e=0;e<this.textures.length;e++)this.textures[e].setValues(t)}get texture(){return this.textures[0]}set texture(e){this.textures[0]=e}set depthTexture(e){this._depthTexture!==null&&this._depthTexture.renderTarget===this&&(this._depthTexture.renderTarget=null),e!==null&&e.renderTarget===null&&(e.renderTarget=this),this._depthTexture=e}get depthTexture(){return this._depthTexture}setSize(e,t,n=1){if(this.width!==e||this.height!==t||this.depth!==n){this.width=e,this.height=t,this.depth=n;for(let r=0,i=this.textures.length;r<i;r++)this.textures[r].image.width=e,this.textures[r].image.height=t,this.textures[r].image.depth=n,this.textures[r].isData3DTexture!==!0&&(this.textures[r].isArrayTexture=this.textures[r].image.depth>1);this.dispose()}this.viewport.set(0,0,e,t),this.scissor.set(0,0,e,t)}clone(){return new this.constructor().copy(this)}copy(e){this.width=e.width,this.height=e.height,this.depth=e.depth,this.scissor.copy(e.scissor),this.scissorTest=e.scissorTest,this.viewport.copy(e.viewport),this.textures.length=0;for(let t=0,n=e.textures.length;t<n;t++){this.textures[t]=e.textures[t].clone(),this.textures[t].isRenderTargetTexture=!0,this.textures[t].renderTarget=this;let n=Object.assign({},e.textures[t].image);this.textures[t].source=new Lp(n)}if(this.depthBuffer=e.depthBuffer,this.stencilBuffer=e.stencilBuffer,this.resolveColorBuffer=e.resolveColorBuffer,this.resolveDepthBuffer=e.resolveDepthBuffer,this.resolveStencilBuffer=e.resolveStencilBuffer,this.storeMultisampledColorBuffer=e.storeMultisampledColorBuffer,this.storeMultisampledDepthBuffer=e.storeMultisampledDepthBuffer,this.storeMultisampledStencilBuffer=e.storeMultisampledStencilBuffer,e.depthTexture!==null){if(e.depthTexture.renderTarget===e){let t=e.depthTexture.clone();t.renderTarget=null,this.depthTexture=t}else this.depthTexture=e.depthTexture}return this.samples=e.samples,this.multiview=e.multiview,this.useArrayDepthTexture=e.useArrayDepthTexture,this}dispose(){this.dispatchEvent({type:`dispose`})}},Wp=class extends Up{constructor(e=1,t=1,n={}){super(e,t,n),this.isWebGLRenderTarget=!0}},Gp=class extends Vp{constructor(e=null,t=1,n=1,r=1){super(null),this.isDataArrayTexture=!0,this.image={data:e,width:t,height:n,depth:r},this.magFilter=kd,this.minFilter=kd,this.wrapR=Dd,this.generateMipmaps=!1,this.flipY=!1,this.unpackAlignment=1,this.layerUpdates=new Set}copy(e){return super.copy(e),this.wrapR=e.wrapR,this}addLayerUpdate(e){this.layerUpdates.add(e)}clearLayerUpdates(){this.layerUpdates.clear()}},Kp=class extends Vp{constructor(e=null,t=1,n=1,r=1){super(null),this.isData3DTexture=!0,this.image={data:e,width:t,height:n,depth:r},this.magFilter=kd,this.minFilter=kd,this.wrapR=Dd,this.generateMipmaps=!1,this.flipY=!1,this.unpackAlignment=1}copy(e){return super.copy(e),this.wrapR=e.wrapR,this}},qp=class e{static{e.prototype.isMatrix4=!0}constructor(e,t,n,r,i,a,o,s,c,l,u,d,f,p,m,h){this.elements=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],e!==void 0&&this.set(e,t,n,r,i,a,o,s,c,l,u,d,f,p,m,h)}set(e,t,n,r,i,a,o,s,c,l,u,d,f,p,m,h){let g=this.elements;return g[0]=e,g[4]=t,g[8]=n,g[12]=r,g[1]=i,g[5]=a,g[9]=o,g[13]=s,g[2]=c,g[6]=l,g[10]=u,g[14]=d,g[3]=f,g[7]=p,g[11]=m,g[15]=h,this}identity(){return this.set(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1),this}clone(){return new e().fromArray(this.elements)}copy(e){let t=this.elements,n=e.elements;return t[0]=n[0],t[1]=n[1],t[2]=n[2],t[3]=n[3],t[4]=n[4],t[5]=n[5],t[6]=n[6],t[7]=n[7],t[8]=n[8],t[9]=n[9],t[10]=n[10],t[11]=n[11],t[12]=n[12],t[13]=n[13],t[14]=n[14],t[15]=n[15],this}copyPosition(e){let t=this.elements,n=e.elements;return t[12]=n[12],t[13]=n[13],t[14]=n[14],this}setFromMatrix3(e){let t=e.elements;return this.set(t[0],t[3],t[6],0,t[1],t[4],t[7],0,t[2],t[5],t[8],0,0,0,0,1),this}extractBasis(e,t,n){return this.determinantAffine()===0?(e.set(1,0,0),t.set(0,1,0),n.set(0,0,1),this):(e.setFromMatrixColumn(this,0),t.setFromMatrixColumn(this,1),n.setFromMatrixColumn(this,2),this)}makeBasis(e,t,n){return this.set(e.x,t.x,n.x,0,e.y,t.y,n.y,0,e.z,t.z,n.z,0,0,0,0,1),this}extractRotation(e){if(e.determinantAffine()===0)return this.identity();let t=this.elements,n=e.elements,r=1/Jp.setFromMatrixColumn(e,0).length(),i=1/Jp.setFromMatrixColumn(e,1).length(),a=1/Jp.setFromMatrixColumn(e,2).length();return t[0]=n[0]*r,t[1]=n[1]*r,t[2]=n[2]*r,t[3]=0,t[4]=n[4]*i,t[5]=n[5]*i,t[6]=n[6]*i,t[7]=0,t[8]=n[8]*a,t[9]=n[9]*a,t[10]=n[10]*a,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,this}makeRotationFromEuler(e){let t=this.elements,n=e.x,r=e.y,i=e.z,a=Math.cos(n),o=Math.sin(n),s=Math.cos(r),c=Math.sin(r),l=Math.cos(i),u=Math.sin(i);if(e.order===`XYZ`){let e=a*l,n=a*u,r=o*l,i=o*u;t[0]=s*l,t[4]=-s*u,t[8]=c,t[1]=n+r*c,t[5]=e-i*c,t[9]=-o*s,t[2]=i-e*c,t[6]=r+n*c,t[10]=a*s}else if(e.order===`YXZ`){let e=s*l,n=s*u,r=c*l,i=c*u;t[0]=e+i*o,t[4]=r*o-n,t[8]=a*c,t[1]=a*u,t[5]=a*l,t[9]=-o,t[2]=n*o-r,t[6]=i+e*o,t[10]=a*s}else if(e.order===`ZXY`){let e=s*l,n=s*u,r=c*l,i=c*u;t[0]=e-i*o,t[4]=-a*u,t[8]=r+n*o,t[1]=n+r*o,t[5]=a*l,t[9]=i-e*o,t[2]=-a*c,t[6]=o,t[10]=a*s}else if(e.order===`ZYX`){let e=a*l,n=a*u,r=o*l,i=o*u;t[0]=s*l,t[4]=r*c-n,t[8]=e*c+i,t[1]=s*u,t[5]=i*c+e,t[9]=n*c-r,t[2]=-c,t[6]=o*s,t[10]=a*s}else if(e.order===`YZX`){let e=a*s,n=a*c,r=o*s,i=o*c;t[0]=s*l,t[4]=i-e*u,t[8]=r*u+n,t[1]=u,t[5]=a*l,t[9]=-o*l,t[2]=-c*l,t[6]=n*u+r,t[10]=e-i*u}else if(e.order===`XZY`){let e=a*s,n=a*c,r=o*s,i=o*c;t[0]=s*l,t[4]=-u,t[8]=c*l,t[1]=e*u+i,t[5]=a*l,t[9]=n*u-r,t[2]=r*u-n,t[6]=o*l,t[10]=i*u+e}return t[3]=0,t[7]=0,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,this}makeRotationFromQuaternion(e){return this.compose(Xp,e,Zp)}lookAt(e,t,n){let r=this.elements;return em.subVectors(e,t),em.lengthSq()===0&&(em.z=1),em.normalize(),Qp.crossVectors(n,em),Qp.lengthSq()===0&&(Math.abs(n.z)===1?em.x+=1e-4:em.z+=1e-4,em.normalize(),Qp.crossVectors(n,em)),Qp.normalize(),$p.crossVectors(em,Qp),r[0]=Qp.x,r[4]=$p.x,r[8]=em.x,r[1]=Qp.y,r[5]=$p.y,r[9]=em.y,r[2]=Qp.z,r[6]=$p.z,r[10]=em.z,this}multiply(e){return this.multiplyMatrices(this,e)}premultiply(e){return this.multiplyMatrices(e,this)}multiplyMatrices(e,t){let n=e.elements,r=t.elements,i=this.elements,a=n[0],o=n[4],s=n[8],c=n[12],l=n[1],u=n[5],d=n[9],f=n[13],p=n[2],m=n[6],h=n[10],g=n[14],_=n[3],v=n[7],y=n[11],b=n[15],x=r[0],S=r[4],C=r[8],w=r[12],T=r[1],E=r[5],D=r[9],O=r[13],k=r[2],A=r[6],j=r[10],ee=r[14],M=r[3],N=r[7],P=r[11],F=r[15];return i[0]=a*x+o*T+s*k+c*M,i[4]=a*S+o*E+s*A+c*N,i[8]=a*C+o*D+s*j+c*P,i[12]=a*w+o*O+s*ee+c*F,i[1]=l*x+u*T+d*k+f*M,i[5]=l*S+u*E+d*A+f*N,i[9]=l*C+u*D+d*j+f*P,i[13]=l*w+u*O+d*ee+f*F,i[2]=p*x+m*T+h*k+g*M,i[6]=p*S+m*E+h*A+g*N,i[10]=p*C+m*D+h*j+g*P,i[14]=p*w+m*O+h*ee+g*F,i[3]=_*x+v*T+y*k+b*M,i[7]=_*S+v*E+y*A+b*N,i[11]=_*C+v*D+y*j+b*P,i[15]=_*w+v*O+y*ee+b*F,this}multiplyScalar(e){let t=this.elements;return t[0]*=e,t[4]*=e,t[8]*=e,t[12]*=e,t[1]*=e,t[5]*=e,t[9]*=e,t[13]*=e,t[2]*=e,t[6]*=e,t[10]*=e,t[14]*=e,t[3]*=e,t[7]*=e,t[11]*=e,t[15]*=e,this}determinant(){let e=this.elements,t=e[0],n=e[4],r=e[8],i=e[12],a=e[1],o=e[5],s=e[9],c=e[13],l=e[2],u=e[6],d=e[10],f=e[14],p=e[3],m=e[7],h=e[11],g=e[15],_=s*f-c*d,v=o*f-c*u,y=o*d-s*u,b=a*f-c*l,x=a*d-s*l,S=a*u-o*l;return t*(m*_-h*v+g*y)-n*(p*_-h*b+g*x)+r*(p*v-m*b+g*S)-i*(p*y-m*x+h*S)}determinantAffine(){let e=this.elements,t=e[0],n=e[4],r=e[8],i=e[1],a=e[5],o=e[9],s=e[2],c=e[6],l=e[10];return t*(a*l-o*c)-n*(i*l-o*s)+r*(i*c-a*s)}transpose(){let e=this.elements,t;return t=e[1],e[1]=e[4],e[4]=t,t=e[2],e[2]=e[8],e[8]=t,t=e[6],e[6]=e[9],e[9]=t,t=e[3],e[3]=e[12],e[12]=t,t=e[7],e[7]=e[13],e[13]=t,t=e[11],e[11]=e[14],e[14]=t,this}setPosition(e,t,n){let r=this.elements;return e.isVector3?(r[12]=e.x,r[13]=e.y,r[14]=e.z):(r[12]=e,r[13]=t,r[14]=n),this}invert(){let e=this.elements,t=e[0],n=e[1],r=e[2],i=e[3],a=e[4],o=e[5],s=e[6],c=e[7],l=e[8],u=e[9],d=e[10],f=e[11],p=e[12],m=e[13],h=e[14],g=e[15],_=t*o-n*a,v=t*s-r*a,y=t*c-i*a,b=n*s-r*o,x=n*c-i*o,S=r*c-i*s,C=l*m-u*p,w=l*h-d*p,T=l*g-f*p,E=u*h-d*m,D=u*g-f*m,O=d*g-f*h,k=_*O-v*D+y*E+b*T-x*w+S*C;if(k===0)return this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0);let A=1/k;return e[0]=(o*O-s*D+c*E)*A,e[1]=(r*D-n*O-i*E)*A,e[2]=(m*S-h*x+g*b)*A,e[3]=(d*x-u*S-f*b)*A,e[4]=(s*T-a*O-c*w)*A,e[5]=(t*O-r*T+i*w)*A,e[6]=(h*y-p*S-g*v)*A,e[7]=(l*S-d*y+f*v)*A,e[8]=(a*D-o*T+c*C)*A,e[9]=(n*T-t*D-i*C)*A,e[10]=(p*x-m*y+g*_)*A,e[11]=(u*y-l*x-f*_)*A,e[12]=(o*w-a*E-s*C)*A,e[13]=(t*E-n*w+r*C)*A,e[14]=(m*v-p*b-h*_)*A,e[15]=(l*b-u*v+d*_)*A,this}scale(e){let t=this.elements,n=e.x,r=e.y,i=e.z;return t[0]*=n,t[4]*=r,t[8]*=i,t[1]*=n,t[5]*=r,t[9]*=i,t[2]*=n,t[6]*=r,t[10]*=i,t[3]*=n,t[7]*=r,t[11]*=i,this}getMaxScaleOnAxis(){let e=this.elements,t=e[0]*e[0]+e[1]*e[1]+e[2]*e[2],n=e[4]*e[4]+e[5]*e[5]+e[6]*e[6],r=e[8]*e[8]+e[9]*e[9]+e[10]*e[10];return Math.sqrt(Math.max(t,n,r))}makeTranslation(e,t,n){return e.isVector3?this.set(1,0,0,e.x,0,1,0,e.y,0,0,1,e.z,0,0,0,1):this.set(1,0,0,e,0,1,0,t,0,0,1,n,0,0,0,1),this}makeRotationX(e){let t=Math.cos(e),n=Math.sin(e);return this.set(1,0,0,0,0,t,-n,0,0,n,t,0,0,0,0,1),this}makeRotationY(e){let t=Math.cos(e),n=Math.sin(e);return this.set(t,0,n,0,0,1,0,0,-n,0,t,0,0,0,0,1),this}makeRotationZ(e){let t=Math.cos(e),n=Math.sin(e);return this.set(t,-n,0,0,n,t,0,0,0,0,1,0,0,0,0,1),this}makeRotationAxis(e,t){let n=Math.cos(t),r=Math.sin(t),i=1-n,a=e.x,o=e.y,s=e.z,c=i*a,l=i*o;return this.set(c*a+n,c*o-r*s,c*s+r*o,0,c*o+r*s,l*o+n,l*s-r*a,0,c*s-r*o,l*s+r*a,i*s*s+n,0,0,0,0,1),this}makeScale(e,t,n){return this.set(e,0,0,0,0,t,0,0,0,0,n,0,0,0,0,1),this}makeShear(e,t,n,r,i,a){return this.set(1,n,i,0,e,1,a,0,t,r,1,0,0,0,0,1),this}compose(e,t,n){let r=this.elements,i=t._x,a=t._y,o=t._z,s=t._w,c=i+i,l=a+a,u=o+o,d=i*c,f=i*l,p=i*u,m=a*l,h=a*u,g=o*u,_=s*c,v=s*l,y=s*u,b=n.x,x=n.y,S=n.z;return r[0]=(1-(m+g))*b,r[1]=(f+y)*b,r[2]=(p-v)*b,r[3]=0,r[4]=(f-y)*x,r[5]=(1-(d+g))*x,r[6]=(h+_)*x,r[7]=0,r[8]=(p+v)*S,r[9]=(h-_)*S,r[10]=(1-(d+m))*S,r[11]=0,r[12]=e.x,r[13]=e.y,r[14]=e.z,r[15]=1,this}decompose(e,t,n){let r=this.elements;e.x=r[12],e.y=r[13],e.z=r[14];let i=this.determinantAffine();if(i===0)return n.set(1,1,1),t.identity(),this;let a=Jp.set(r[0],r[1],r[2]).length(),o=Jp.set(r[4],r[5],r[6]).length(),s=Jp.set(r[8],r[9],r[10]).length();i<0&&(a=-a),Yp.copy(this);let c=1/a,l=1/o,u=1/s;return Yp.elements[0]*=c,Yp.elements[1]*=c,Yp.elements[2]*=c,Yp.elements[4]*=l,Yp.elements[5]*=l,Yp.elements[6]*=l,Yp.elements[8]*=u,Yp.elements[9]*=u,Yp.elements[10]*=u,t.setFromRotationMatrix(Yp),n.x=a,n.y=o,n.z=s,this}makePerspective(e,t,n,r,i,a,o=tp,s=!1){let c=this.elements,l=2*i/(t-e),u=2*i/(n-r),d=(t+e)/(t-e),f=(n+r)/(n-r),p,m;if(s)p=i/(a-i),m=a*i/(a-i);else if(o===2e3)p=-(a+i)/(a-i),m=-2*a*i/(a-i);else if(o===2001)p=-a/(a-i),m=-a*i/(a-i);else throw Error(`THREE.Matrix4.makePerspective(): Invalid coordinate system: `+o);return c[0]=l,c[4]=0,c[8]=d,c[12]=0,c[1]=0,c[5]=u,c[9]=f,c[13]=0,c[2]=0,c[6]=0,c[10]=p,c[14]=m,c[3]=0,c[7]=0,c[11]=-1,c[15]=0,this}makeOrthographic(e,t,n,r,i,a,o=tp,s=!1){let c=this.elements,l=2/(t-e),u=2/(n-r),d=-(t+e)/(t-e),f=-(n+r)/(n-r),p,m;if(s)p=1/(a-i),m=a/(a-i);else if(o===2e3)p=-2/(a-i),m=-(a+i)/(a-i);else if(o===2001)p=-1/(a-i),m=-i/(a-i);else throw Error(`THREE.Matrix4.makeOrthographic(): Invalid coordinate system: `+o);return c[0]=l,c[4]=0,c[8]=0,c[12]=d,c[1]=0,c[5]=u,c[9]=0,c[13]=f,c[2]=0,c[6]=0,c[10]=p,c[14]=m,c[3]=0,c[7]=0,c[11]=0,c[15]=1,this}equals(e){let t=this.elements,n=e.elements;for(let e=0;e<16;e++)if(t[e]!==n[e])return!1;return!0}fromArray(e,t=0){for(let n=0;n<16;n++)this.elements[n]=e[n+t];return this}toArray(e=[],t=0){let n=this.elements;return e[t]=n[0],e[t+1]=n[1],e[t+2]=n[2],e[t+3]=n[3],e[t+4]=n[4],e[t+5]=n[5],e[t+6]=n[6],e[t+7]=n[7],e[t+8]=n[8],e[t+9]=n[9],e[t+10]=n[10],e[t+11]=n[11],e[t+12]=n[12],e[t+13]=n[13],e[t+14]=n[14],e[t+15]=n[15],e}},Jp=new Q,Yp=new qp,Xp=new Q(0,0,0),Zp=new Q(1,1,1),Qp=new Q,$p=new Q,em=new Q,tm=new qp,nm=new Cp,rm=class e{constructor(t=0,n=0,r=0,i=e.DEFAULT_ORDER){this.isEuler=!0,this._x=t,this._y=n,this._z=r,this._order=i}get x(){return this._x}set x(e){this._x=e,this._onChangeCallback()}get y(){return this._y}set y(e){this._y=e,this._onChangeCallback()}get z(){return this._z}set z(e){this._z=e,this._onChangeCallback()}get order(){return this._order}set order(e){this._order=e,this._onChangeCallback()}set(e,t,n,r=this._order){return this._x=e,this._y=t,this._z=n,this._order=r,this._onChangeCallback(),this}clone(){return new this.constructor(this._x,this._y,this._z,this._order)}copy(e){return this._x=e._x,this._y=e._y,this._z=e._z,this._order=e._order,this._onChangeCallback(),this}setFromRotationMatrix(e,t=this._order,n=!0){let r=e.elements,i=r[0],a=r[4],o=r[8],s=r[1],c=r[5],l=r[9],u=r[2],d=r[6],f=r[10];switch(t){case`XYZ`:this._y=Math.asin(_p(o,-1,1)),Math.abs(o)<.9999999?(this._x=Math.atan2(-l,f),this._z=Math.atan2(-a,i)):(this._x=Math.atan2(d,c),this._z=0);break;case`YXZ`:this._x=Math.asin(-_p(l,-1,1)),Math.abs(l)<.9999999?(this._y=Math.atan2(o,f),this._z=Math.atan2(s,c)):(this._y=Math.atan2(-u,i),this._z=0);break;case`ZXY`:this._x=Math.asin(_p(d,-1,1)),Math.abs(d)<.9999999?(this._y=Math.atan2(-u,f),this._z=Math.atan2(-a,c)):(this._y=0,this._z=Math.atan2(s,i));break;case`ZYX`:this._y=Math.asin(-_p(u,-1,1)),Math.abs(u)<.9999999?(this._x=Math.atan2(d,f),this._z=Math.atan2(s,i)):(this._x=0,this._z=Math.atan2(-a,c));break;case`YZX`:this._z=Math.asin(_p(s,-1,1)),Math.abs(s)<.9999999?(this._x=Math.atan2(-l,c),this._y=Math.atan2(-u,i)):(this._x=0,this._y=Math.atan2(o,f));break;case`XZY`:this._z=Math.asin(-_p(a,-1,1)),Math.abs(a)<.9999999?(this._x=Math.atan2(d,c),this._y=Math.atan2(o,i)):(this._x=Math.atan2(-l,f),this._y=0);break;default:X(`Euler: .setFromRotationMatrix() encountered an unknown order: `+t)}return this._order=t,n===!0&&this._onChangeCallback(),this}setFromQuaternion(e,t,n){return tm.makeRotationFromQuaternion(e),this.setFromRotationMatrix(tm,t,n)}setFromVector3(e,t=this._order){return this.set(e.x,e.y,e.z,t)}reorder(e){return nm.setFromEuler(this),this.setFromQuaternion(nm,e)}equals(e){return e._x===this._x&&e._y===this._y&&e._z===this._z&&e._order===this._order}fromArray(e){return this._x=e[0],this._y=e[1],this._z=e[2],e[3]!==void 0&&(this._order=e[3]),this._onChangeCallback(),this}toArray(e=[],t=0){return e[t]=this._x,e[t+1]=this._y,e[t+2]=this._z,e[t+3]=this._order,e}_onChange(e){return this._onChangeCallback=e,this}_onChangeCallback(){}*[Symbol.iterator](){yield this._x,yield this._y,yield this._z,yield this._order}};rm.DEFAULT_ORDER=`XYZ`;var im=class{constructor(){this.mask=1}set(e){this.mask=(1<<e|0)>>>0}enable(e){this.mask|=1<<e|0}enableAll(){this.mask=-1}toggle(e){this.mask^=1<<e|0}disable(e){this.mask&=~(1<<e|0)}disableAll(){this.mask=0}test(e){return(this.mask&e.mask)!==0}isEnabled(e){return!!(this.mask&(1<<e|0))}},am=0,om=new Q,sm=new Cp,cm=new qp,lm=new Q,um=new Q,dm=new Q,fm=new Cp,pm=new Q(1,0,0),mm=new Q(0,1,0),hm=new Q(0,0,1),gm={type:`added`},_m={type:`removed`},vm={type:`childadded`,child:null},ym={type:`childremoved`,child:null},bm=class e extends fp{constructor(){super(),this.isObject3D=!0,Object.defineProperty(this,"id",{value:am++}),this.uuid=gp(),this.name=``,this.type=`Object3D`,this.parent=null,this.children=[],this.up=e.DEFAULT_UP.clone();let t=new Q,n=new rm,r=new Cp,i=new Q(1,1,1);function a(){r.setFromEuler(n,!1)}function o(){n.setFromQuaternion(r,void 0,!1)}n._onChange(a),r._onChange(o),Object.defineProperties(this,{position:{configurable:!0,enumerable:!0,value:t},rotation:{configurable:!0,enumerable:!0,value:n},quaternion:{configurable:!0,enumerable:!0,value:r},scale:{configurable:!0,enumerable:!0,value:i},modelViewMatrix:{value:new qp},normalMatrix:{value:new Ep}}),this.matrix=new qp,this.matrixWorld=new qp,this.matrixAutoUpdate=e.DEFAULT_MATRIX_AUTO_UPDATE,this.matrixWorldAutoUpdate=e.DEFAULT_MATRIX_WORLD_AUTO_UPDATE,this.matrixWorldNeedsUpdate=!1,this.layers=new im,this.visible=!0,this.castShadow=!1,this.receiveShadow=!1,this.frustumCulled=!0,this.renderOrder=0,this.animations=[],this.customDepthMaterial=void 0,this.customDistanceMaterial=void 0,this.static=!1,this.userData={},this.pivot=null}onBeforeShadow(){}onAfterShadow(){}onBeforeRender(){}onAfterRender(){}applyMatrix4(e){this.matrixAutoUpdate&&this.updateMatrix(),this.matrix.premultiply(e),this.matrix.decompose(this.position,this.quaternion,this.scale)}applyQuaternion(e){return this.quaternion.premultiply(e),this}setRotationFromAxisAngle(e,t){this.quaternion.setFromAxisAngle(e,t)}setRotationFromEuler(e){this.quaternion.setFromEuler(e,!0)}setRotationFromMatrix(e){this.quaternion.setFromRotationMatrix(e)}setRotationFromQuaternion(e){this.quaternion.copy(e)}rotateOnAxis(e,t){return sm.setFromAxisAngle(e,t),this.quaternion.multiply(sm),this}rotateOnWorldAxis(e,t){return sm.setFromAxisAngle(e,t),this.quaternion.premultiply(sm),this}rotateX(e){return this.rotateOnAxis(pm,e)}rotateY(e){return this.rotateOnAxis(mm,e)}rotateZ(e){return this.rotateOnAxis(hm,e)}translateOnAxis(e,t){return om.copy(e).applyQuaternion(this.quaternion),this.position.add(om.multiplyScalar(t)),this}translateX(e){return this.translateOnAxis(pm,e)}translateY(e){return this.translateOnAxis(mm,e)}translateZ(e){return this.translateOnAxis(hm,e)}localToWorld(e){return this.updateWorldMatrix(!0,!1),e.applyMatrix4(this.matrixWorld)}worldToLocal(e){return this.updateWorldMatrix(!0,!1),e.applyMatrix4(cm.copy(this.matrixWorld).invert())}lookAt(e,t,n){e.isVector3?lm.copy(e):lm.set(e,t,n);let r=this.parent;this.updateWorldMatrix(!0,!1),um.setFromMatrixPosition(this.matrixWorld),this.isCamera||this.isLight?cm.lookAt(um,lm,this.up):cm.lookAt(lm,um,this.up),this.quaternion.setFromRotationMatrix(cm),r&&(cm.extractRotation(r.matrixWorld),sm.setFromRotationMatrix(cm),this.quaternion.premultiply(sm.invert()))}add(e){if(arguments.length>1){for(let e=0;e<arguments.length;e++)this.add(arguments[e]);return this}return e===this?(Z(`Object3D.add: object can't be added as a child of itself.`,e),this):(e&&e.isObject3D?(e.removeFromParent(),e.parent=this,this.children.push(e),e.dispatchEvent(gm),vm.child=e,this.dispatchEvent(vm),vm.child=null):Z(`Object3D.add: object not an instance of THREE.Object3D.`,e),this)}remove(e){if(arguments.length>1){for(let e=0;e<arguments.length;e++)this.remove(arguments[e]);return this}let t=this.children.indexOf(e);return t!==-1&&(e.parent=null,this.children.splice(t,1),e.dispatchEvent(_m),ym.child=e,this.dispatchEvent(ym),ym.child=null),this}removeFromParent(){let e=this.parent;return e!==null&&e.remove(this),this}clear(){return this.remove(...this.children)}attach(e){return this.updateWorldMatrix(!0,!1),cm.copy(this.matrixWorld).invert(),e.parent!==null&&(e.parent.updateWorldMatrix(!0,!1),cm.multiply(e.parent.matrixWorld)),e.applyMatrix4(cm),e.removeFromParent(),e.parent=this,this.children.push(e),e.updateWorldMatrix(!1,!0),e.dispatchEvent(gm),vm.child=e,this.dispatchEvent(vm),vm.child=null,this}getObjectById(e){return this.getObjectByProperty(`id`,e)}getObjectByName(e){return this.getObjectByProperty(`name`,e)}getObjectByProperty(e,t){if(this[e]===t)return this;for(let n=0,r=this.children.length;n<r;n++){let r=this.children[n].getObjectByProperty(e,t);if(r!==void 0)return r}}getObjectsByProperty(e,t,n=[]){this[e]===t&&n.push(this);let r=this.children;for(let i=0,a=r.length;i<a;i++)r[i].getObjectsByProperty(e,t,n);return n}getWorldPosition(e){return this.updateWorldMatrix(!0,!1),e.setFromMatrixPosition(this.matrixWorld)}getWorldQuaternion(e){return this.updateWorldMatrix(!0,!1),this.matrixWorld.decompose(um,e,dm),e}getWorldScale(e){return this.updateWorldMatrix(!0,!1),this.matrixWorld.decompose(um,fm,e),e}getWorldDirection(e){this.updateWorldMatrix(!0,!1);let t=this.matrixWorld.elements;return e.set(t[8],t[9],t[10]).normalize()}raycast(){}intersectsFrustum(){}traverse(e){e(this);let t=this.children;for(let n=0,r=t.length;n<r;n++)t[n].traverse(e)}traverseVisible(e){if(this.visible===!1)return;e(this);let t=this.children;for(let n=0,r=t.length;n<r;n++)t[n].traverseVisible(e)}traverseAncestors(e){let t=this.parent;t!==null&&(e(t),t.traverseAncestors(e))}updateMatrix(){this.matrix.compose(this.position,this.quaternion,this.scale);let e=this.pivot;if(e!==null){let t=e.x,n=e.y,r=e.z,i=this.matrix.elements;i[12]+=t-i[0]*t-i[4]*n-i[8]*r,i[13]+=n-i[1]*t-i[5]*n-i[9]*r,i[14]+=r-i[2]*t-i[6]*n-i[10]*r}this.matrixWorldNeedsUpdate=!0}updateMatrixWorld(e){this.matrixAutoUpdate&&this.updateMatrix(),(this.matrixWorldNeedsUpdate||e)&&(this.matrixWorldAutoUpdate===!0&&(this.parent===null?this.matrixWorld.copy(this.matrix):this.matrixWorld.multiplyMatrices(this.parent.matrixWorld,this.matrix)),this.matrixWorldNeedsUpdate=!1,e=!0);let t=this.children;for(let n=0,r=t.length;n<r;n++)t[n].updateMatrixWorld(e)}updateWorldMatrix(e,t,n=!1){let r=this.parent;if(e===!0&&r!==null&&r.updateWorldMatrix(!0,!1),this.matrixAutoUpdate&&this.updateMatrix(),(this.matrixWorldNeedsUpdate||n)&&(this.matrixWorldAutoUpdate===!0&&(this.parent===null?this.matrixWorld.copy(this.matrix):this.matrixWorld.multiplyMatrices(this.parent.matrixWorld,this.matrix)),this.matrixWorldNeedsUpdate=!1,n=!0),t===!0){let e=this.children;for(let t=0,r=e.length;t<r;t++)e[t].updateWorldMatrix(!1,!0,n)}}toJSON(e){let t=e===void 0||typeof e==`string`,n={};t&&(e={geometries:{},materials:{},textures:{},images:{},shapes:{},skeletons:{},animations:{},nodes:{}},n.metadata={version:4.7,type:`Object`,generator:`Object3D.toJSON`});let r={};r.uuid=this.uuid,r.type=this.type,r.name=this.name,r.castShadow=this.castShadow,r.receiveShadow=this.receiveShadow,r.visible=this.visible,r.frustumCulled=this.frustumCulled,r.renderOrder=this.renderOrder,r.static=this.static,r.matrixAutoUpdate=this.matrixAutoUpdate,Object.keys(this.userData).length>0&&(r.userData=this.userData),r.layers=this.layers.mask,r.matrix=this.matrix.toArray(),r.up=this.up.toArray(),this.pivot!==null&&(r.pivot=this.pivot.toArray()),this.morphTargetDictionary!==void 0&&(r.morphTargetDictionary=Object.assign({},this.morphTargetDictionary)),this.morphTargetInfluences!==void 0&&(r.morphTargetInfluences=this.morphTargetInfluences.slice()),this.isInstancedMesh&&(r.type=`InstancedMesh`,r.count=this.count,r.instanceMatrix=this.instanceMatrix.toJSON(),this.instanceColor!==null&&(r.instanceColor=this.instanceColor.toJSON())),this.isBatchedMesh&&(r.type=`BatchedMesh`,r.perObjectFrustumCulled=this.perObjectFrustumCulled,r.sortObjects=this.sortObjects,r.drawRanges=this._drawRanges,r.reservedRanges=this._reservedRanges,r.geometryInfo=this._geometryInfo.map(e=>({...e,boundingBox:e.boundingBox?e.boundingBox.toJSON():void 0,boundingSphere:e.boundingSphere?e.boundingSphere.toJSON():void 0})),r.instanceInfo=this._instanceInfo.map(e=>({...e})),r.availableInstanceIds=this._availableInstanceIds.slice(),r.availableGeometryIds=this._availableGeometryIds.slice(),r.nextIndexStart=this._nextIndexStart,r.nextVertexStart=this._nextVertexStart,r.geometryCount=this._geometryCount,r.maxInstanceCount=this._maxInstanceCount,r.maxVertexCount=this._maxVertexCount,r.maxIndexCount=this._maxIndexCount,r.geometryInitialized=this._geometryInitialized,r.matricesTexture=this._matricesTexture.toJSON(e),r.indirectTexture=this._indirectTexture.toJSON(e),this._colorsTexture!==null&&(r.colorsTexture=this._colorsTexture.toJSON(e)),this.boundingSphere!==null&&(r.boundingSphere=this.boundingSphere.toJSON()),this.boundingBox!==null&&(r.boundingBox=this.boundingBox.toJSON()));function i(t,n){return t[n.uuid]===void 0&&(t[n.uuid]=n.toJSON(e)),n.uuid}if(this.isScene)this.background&&(this.background.isColor?r.background=this.background.toJSON():this.background.isTexture&&(r.background=this.background.toJSON(e).uuid)),this.environment&&this.environment.isTexture&&this.environment.isRenderTargetTexture!==!0&&(r.environment=this.environment.toJSON(e).uuid);else if(this.isMesh||this.isLine||this.isPoints){r.geometry=i(e.geometries,this.geometry);let t=this.geometry.parameters;if(t!==void 0&&t.shapes!==void 0){let n=t.shapes;if(Array.isArray(n))for(let t=0,r=n.length;t<r;t++){let r=n[t];i(e.shapes,r)}else i(e.shapes,n)}}if(this.isSkinnedMesh&&(r.bindMode=this.bindMode,r.bindMatrix=this.bindMatrix.toArray(),this.skeleton!==void 0&&(i(e.skeletons,this.skeleton),r.skeleton=this.skeleton.uuid)),this.material!==void 0){if(Array.isArray(this.material)){let t=[];for(let n=0,r=this.material.length;n<r;n++)t.push(i(e.materials,this.material[n]));r.material=t}else r.material=i(e.materials,this.material)}if(this.children.length>0){r.children=[];for(let t=0;t<this.children.length;t++)r.children.push(this.children[t].toJSON(e).object)}if(this.animations.length>0){r.animations=[];for(let t=0;t<this.animations.length;t++){let n=this.animations[t];r.animations.push(i(e.animations,n))}}if(t){let t=a(e.geometries),r=a(e.materials),i=a(e.textures),o=a(e.images),s=a(e.shapes),c=a(e.skeletons),l=a(e.animations),u=a(e.nodes);t.length>0&&(n.geometries=t),r.length>0&&(n.materials=r),i.length>0&&(n.textures=i),o.length>0&&(n.images=o),s.length>0&&(n.shapes=s),c.length>0&&(n.skeletons=c),l.length>0&&(n.animations=l),u.length>0&&(n.nodes=u)}return n.object=r,n;function a(e){let t=[];for(let n in e){let r=e[n];delete r.metadata,t.push(r)}return t}}clone(e){return new this.constructor().copy(this,e)}copy(e,t=!0){if(this.name=e.name,this.up.copy(e.up),this.position.copy(e.position),this.rotation.order=e.rotation.order,this.quaternion.copy(e.quaternion),this.scale.copy(e.scale),this.pivot=e.pivot===null?null:e.pivot.clone(),this.matrix.copy(e.matrix),this.matrixWorld.copy(e.matrixWorld),this.matrixAutoUpdate=e.matrixAutoUpdate,this.matrixWorldAutoUpdate=e.matrixWorldAutoUpdate,this.matrixWorldNeedsUpdate=e.matrixWorldNeedsUpdate,this.layers.mask=e.layers.mask,this.visible=e.visible,this.castShadow=e.castShadow,this.receiveShadow=e.receiveShadow,this.frustumCulled=e.frustumCulled,this.renderOrder=e.renderOrder,this.static=e.static,this.animations=e.animations.slice(),this.userData=JSON.parse(JSON.stringify(e.userData)),t===!0)for(let t=0;t<e.children.length;t++){let n=e.children[t];this.add(n.clone())}return this}dispose(){this.dispatchEvent({type:`dispose`})}};bm.DEFAULT_UP=new Q(0,1,0),bm.DEFAULT_MATRIX_AUTO_UPDATE=!0,bm.DEFAULT_MATRIX_WORLD_AUTO_UPDATE=!0;var xm=class extends bm{constructor(){super(),this.isGroup=!0,this.type=`Group`}},Sm={type:`move`},Cm=class{constructor(){this._targetRay=null,this._grip=null,this._hand=null}getHandSpace(){return this._hand===null&&(this._hand=new xm,this._hand.matrixAutoUpdate=!1,this._hand.visible=!1,this._hand.joints={},this._hand.inputState={pinching:!1}),this._hand}getTargetRaySpace(){return this._targetRay===null&&(this._targetRay=new xm,this._targetRay.matrixAutoUpdate=!1,this._targetRay.visible=!1,this._targetRay.hasLinearVelocity=!1,this._targetRay.linearVelocity=new Q,this._targetRay.hasAngularVelocity=!1,this._targetRay.angularVelocity=new Q),this._targetRay}getGripSpace(){return this._grip===null&&(this._grip=new xm,this._grip.matrixAutoUpdate=!1,this._grip.visible=!1,this._grip.hasLinearVelocity=!1,this._grip.linearVelocity=new Q,this._grip.hasAngularVelocity=!1,this._grip.angularVelocity=new Q,this._grip.eventsEnabled=!1),this._grip}dispatchEvent(e){return this._targetRay!==null&&this._targetRay.dispatchEvent(e),this._grip!==null&&this._grip.dispatchEvent(e),this._hand!==null&&this._hand.dispatchEvent(e),this}connect(e){if(e&&e.hand){let t=this._hand;if(t)for(let n of e.hand.values())this._getHandJoint(t,n)}return this.dispatchEvent({type:`connected`,data:e}),this}disconnect(e){return this.dispatchEvent({type:`disconnected`,data:e}),this._targetRay!==null&&(this._targetRay.visible=!1),this._grip!==null&&(this._grip.visible=!1),this._hand!==null&&(this._hand.visible=!1),this}update(e,t,n){let r=null,i=null,a=null,o=this._targetRay,s=this._grip,c=this._hand;if(e&&t.session.visibilityState!==`visible-blurred`){if(c&&e.hand){a=!0;for(let r of e.hand.values()){let e=t.getJointPose(r,n),i=this._getHandJoint(c,r);e!==null&&(i.matrix.fromArray(e.transform.matrix),i.matrix.decompose(i.position,i.rotation,i.scale),i.matrixWorldNeedsUpdate=!0,i.jointRadius=e.radius),i.visible=e!==null}let r=c.joints[`index-finger-tip`],i=c.joints[`thumb-tip`],o=r.position.distanceTo(i.position);c.inputState.pinching&&o>.025?(c.inputState.pinching=!1,this.dispatchEvent({type:`pinchend`,handedness:e.handedness,target:this})):!c.inputState.pinching&&o<=.015&&(c.inputState.pinching=!0,this.dispatchEvent({type:`pinchstart`,handedness:e.handedness,target:this}))}else s!==null&&e.gripSpace&&(i=t.getPose(e.gripSpace,n),i!==null&&(s.matrix.fromArray(i.transform.matrix),s.matrix.decompose(s.position,s.rotation,s.scale),s.matrixWorldNeedsUpdate=!0,i.linearVelocity?(s.hasLinearVelocity=!0,s.linearVelocity.copy(i.linearVelocity)):s.hasLinearVelocity=!1,i.angularVelocity?(s.hasAngularVelocity=!0,s.angularVelocity.copy(i.angularVelocity)):s.hasAngularVelocity=!1,s.eventsEnabled&&s.dispatchEvent({type:`gripUpdated`,data:e,target:this})));o!==null&&(r=t.getPose(e.targetRaySpace,n),r===null&&i!==null&&(r=i),r!==null&&(o.matrix.fromArray(r.transform.matrix),o.matrix.decompose(o.position,o.rotation,o.scale),o.matrixWorldNeedsUpdate=!0,r.linearVelocity?(o.hasLinearVelocity=!0,o.linearVelocity.copy(r.linearVelocity)):o.hasLinearVelocity=!1,r.angularVelocity?(o.hasAngularVelocity=!0,o.angularVelocity.copy(r.angularVelocity)):o.hasAngularVelocity=!1,this.dispatchEvent(Sm)))}return o!==null&&(o.visible=r!==null),s!==null&&(s.visible=i!==null),c!==null&&(c.visible=a!==null),this}_getHandJoint(e,t){if(e.joints[t.jointName]===void 0){let n=new xm;n.matrixAutoUpdate=!1,n.visible=!1,e.joints[t.jointName]=n,e.add(n)}return e.joints[t.jointName]}},wm={aliceblue:15792383,antiquewhite:16444375,aqua:65535,aquamarine:8388564,azure:15794175,beige:16119260,bisque:16770244,black:0,blanchedalmond:16772045,blue:255,blueviolet:9055202,brown:10824234,burlywood:14596231,cadetblue:6266528,chartreuse:8388352,chocolate:13789470,coral:16744272,cornflowerblue:6591981,cornsilk:16775388,crimson:14423100,cyan:65535,darkblue:139,darkcyan:35723,darkgoldenrod:12092939,darkgray:11119017,darkgreen:25600,darkgrey:11119017,darkkhaki:12433259,darkmagenta:9109643,darkolivegreen:5597999,darkorange:16747520,darkorchid:10040012,darkred:9109504,darksalmon:15308410,darkseagreen:9419919,darkslateblue:4734347,darkslategray:3100495,darkslategrey:3100495,darkturquoise:52945,darkviolet:9699539,deeppink:16716947,deepskyblue:49151,dimgray:6908265,dimgrey:6908265,dodgerblue:2003199,firebrick:11674146,floralwhite:16775920,forestgreen:2263842,fuchsia:16711935,gainsboro:14474460,ghostwhite:16316671,gold:16766720,goldenrod:14329120,gray:8421504,green:32768,greenyellow:11403055,grey:8421504,honeydew:15794160,hotpink:16738740,indianred:13458524,indigo:4915330,ivory:16777200,khaki:15787660,lavender:15132410,lavenderblush:16773365,lawngreen:8190976,lemonchiffon:16775885,lightblue:11393254,lightcoral:15761536,lightcyan:14745599,lightgoldenrodyellow:16448210,lightgray:13882323,lightgreen:9498256,lightgrey:13882323,lightpink:16758465,lightsalmon:16752762,lightseagreen:2142890,lightskyblue:8900346,lightslategray:7833753,lightslategrey:7833753,lightsteelblue:11584734,lightyellow:16777184,lime:65280,limegreen:3329330,linen:16445670,magenta:16711935,maroon:8388608,mediumaquamarine:6737322,mediumblue:205,mediumorchid:12211667,mediumpurple:9662683,mediumseagreen:3978097,mediumslateblue:8087790,mediumspringgreen:64154,mediumturquoise:4772300,mediumvioletred:13047173,midnightblue:1644912,mintcream:16121850,mistyrose:16770273,moccasin:16770229,navajowhite:16768685,navy:128,oldlace:16643558,olive:8421376,olivedrab:7048739,orange:16753920,orangered:16729344,orchid:14315734,palegoldenrod:15657130,palegreen:10025880,paleturquoise:11529966,palevioletred:14381203,papayawhip:16773077,peachpuff:16767673,peru:13468991,pink:16761035,plum:14524637,powderblue:11591910,purple:8388736,rebeccapurple:6697881,red:16711680,rosybrown:12357519,royalblue:4286945,saddlebrown:9127187,salmon:16416882,sandybrown:16032864,seagreen:3050327,seashell:16774638,sienna:10506797,silver:12632256,skyblue:8900331,slateblue:6970061,slategray:7372944,slategrey:7372944,snow:16775930,springgreen:65407,steelblue:4620980,tan:13808780,teal:32896,thistle:14204888,tomato:16737095,turquoise:4251856,violet:15631086,wheat:16113331,white:16777215,whitesmoke:16119285,yellow:16776960,yellowgreen:10145074},Tm={h:0,s:0,l:0},Em={h:0,s:0,l:0};function Dm(e,t,n){return n<0&&(n+=1),n>1&&--n,n<1/6?e+(t-e)*6*n:n<1/2?t:n<2/3?e+(t-e)*6*(2/3-n):e}var Om=class{constructor(e,t,n){return this.isColor=!0,this.r=1,this.g=1,this.b=1,this.set(e,t,n)}set(e,t,n){if(t===void 0&&n===void 0){let t=e;t&&t.isColor?this.copy(t):typeof t==`number`?this.setHex(t):typeof t==`string`&&this.setStyle(t)}else this.setRGB(e,t,n);return this}setScalar(e){return this.r=e,this.g=e,this.b=e,this}setHex(e,t=Yf){return e=Math.floor(e),this.r=(e>>16&255)/255,this.g=(e>>8&255)/255,this.b=(e&255)/255,jp.colorSpaceToWorking(this,t),this}setRGB(e,t,n,r=jp.workingColorSpace){return this.r=e,this.g=t,this.b=n,jp.colorSpaceToWorking(this,r),this}setHSL(e,t,n,r=jp.workingColorSpace){if(e=vp(e,1),t=_p(t,0,1),n=_p(n,0,1),t===0)this.r=this.g=this.b=n;else{let r=n<=.5?n*(1+t):n+t-n*t,i=2*n-r;this.r=Dm(i,r,e+1/3),this.g=Dm(i,r,e),this.b=Dm(i,r,e-1/3)}return jp.colorSpaceToWorking(this,r),this}setStyle(e,t=Yf){function n(t){t!==void 0&&parseFloat(t)<1&&X(`Color: Alpha component of `+e+` will be ignored.`)}let r;if(r=/^(\w+)\(([^\)]*)\)/.exec(e)){let i,a=r[1],o=r[2];switch(a){case`rgb`:case`rgba`:if(i=/^\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(o))return n(i[4]),this.setRGB(Math.min(255,parseInt(i[1],10))/255,Math.min(255,parseInt(i[2],10))/255,Math.min(255,parseInt(i[3],10))/255,t);if(i=/^\s*(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(o))return n(i[4]),this.setRGB(Math.min(100,parseInt(i[1],10))/100,Math.min(100,parseInt(i[2],10))/100,Math.min(100,parseInt(i[3],10))/100,t);break;case`hsl`:case`hsla`:if(i=/^\s*(\d*\.?\d+)\s*,\s*(\d*\.?\d+)\%\s*,\s*(\d*\.?\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(o))return n(i[4]),this.setHSL(parseFloat(i[1])/360,parseFloat(i[2])/100,parseFloat(i[3])/100,t);break;default:X(`Color: Unknown color model `+e)}}else if(r=/^\#([A-Fa-f\d]+)$/.exec(e)){let n=r[1],i=n.length;if(i===3)return this.setRGB(parseInt(n.charAt(0),16)/15,parseInt(n.charAt(1),16)/15,parseInt(n.charAt(2),16)/15,t);if(i===6)return this.setHex(parseInt(n,16),t);X(`Color: Invalid hex color `+e)}else if(e&&e.length>0)return this.setColorName(e,t);return this}setColorName(e,t=Yf){let n=wm[e.toLowerCase()];return n===void 0?X(`Color: Unknown color `+e):this.setHex(n,t),this}clone(){return new this.constructor(this.r,this.g,this.b)}copy(e){return this.r=e.r,this.g=e.g,this.b=e.b,this}copySRGBToLinear(e){return this.r=Mp(e.r),this.g=Mp(e.g),this.b=Mp(e.b),this}copyLinearToSRGB(e){return this.r=Np(e.r),this.g=Np(e.g),this.b=Np(e.b),this}convertSRGBToLinear(){return this.copySRGBToLinear(this),this}convertLinearToSRGB(){return this.copyLinearToSRGB(this),this}getHex(e=Yf){return jp.workingToColorSpace(km.copy(this),e),Math.round(_p(km.r*255,0,255))*65536+Math.round(_p(km.g*255,0,255))*256+Math.round(_p(km.b*255,0,255))}getHexString(e=Yf){return(`000000`+this.getHex(e).toString(16)).slice(-6)}getHSL(e,t=jp.workingColorSpace){jp.workingToColorSpace(km.copy(this),t);let n=km.r,r=km.g,i=km.b,a=Math.max(n,r,i),o=Math.min(n,r,i),s,c,l=(o+a)/2;if(o===a)s=0,c=0;else{let e=a-o;switch(c=l<=.5?e/(a+o):e/(2-a-o),a){case n:s=(r-i)/e+(r<i?6:0);break;case r:s=(i-n)/e+2;break;case i:s=(n-r)/e+4}s/=6}return e.h=s,e.s=c,e.l=l,e}getRGB(e,t=jp.workingColorSpace){return jp.workingToColorSpace(km.copy(this),t),e.r=km.r,e.g=km.g,e.b=km.b,e}getStyle(e=Yf){jp.workingToColorSpace(km.copy(this),e);let t=km.r,n=km.g,r=km.b;return e===`srgb`?`rgb(${Math.round(t*255)},${Math.round(n*255)},${Math.round(r*255)})`:`color(${e} ${t.toFixed(3)} ${n.toFixed(3)} ${r.toFixed(3)})`}offsetHSL(e,t,n){return this.getHSL(Tm),this.setHSL(Tm.h+e,Tm.s+t,Tm.l+n)}add(e){return this.r+=e.r,this.g+=e.g,this.b+=e.b,this}addColors(e,t){return this.r=e.r+t.r,this.g=e.g+t.g,this.b=e.b+t.b,this}addScalar(e){return this.r+=e,this.g+=e,this.b+=e,this}sub(e){return this.r=Math.max(0,this.r-e.r),this.g=Math.max(0,this.g-e.g),this.b=Math.max(0,this.b-e.b),this}multiply(e){return this.r*=e.r,this.g*=e.g,this.b*=e.b,this}multiplyScalar(e){return this.r*=e,this.g*=e,this.b*=e,this}lerp(e,t){return this.r+=(e.r-this.r)*t,this.g+=(e.g-this.g)*t,this.b+=(e.b-this.b)*t,this}lerpColors(e,t,n){return this.r=e.r+(t.r-e.r)*n,this.g=e.g+(t.g-e.g)*n,this.b=e.b+(t.b-e.b)*n,this}lerpHSL(e,t){this.getHSL(Tm),e.getHSL(Em);let n=yp(Tm.h,Em.h,t),r=yp(Tm.s,Em.s,t),i=yp(Tm.l,Em.l,t);return this.setHSL(n,r,i),this}setFromVector3(e){return this.r=e.x,this.g=e.y,this.b=e.z,this}applyMatrix3(e){let t=this.r,n=this.g,r=this.b,i=e.elements;return this.r=i[0]*t+i[3]*n+i[6]*r,this.g=i[1]*t+i[4]*n+i[7]*r,this.b=i[2]*t+i[5]*n+i[8]*r,this}equals(e){return e.r===this.r&&e.g===this.g&&e.b===this.b}fromArray(e,t=0){return this.r=e[t],this.g=e[t+1],this.b=e[t+2],this}toArray(e=[],t=0){return e[t]=this.r,e[t+1]=this.g,e[t+2]=this.b,e}fromBufferAttribute(e,t){return this.r=e.getX(t),this.g=e.getY(t),this.b=e.getZ(t),this}toJSON(){return this.getHex()}*[Symbol.iterator](){yield this.r,yield this.g,yield this.b}},km=new Om;Om.NAMES=wm;var Am=class extends bm{constructor(){super(),this.isScene=!0,this.type=`Scene`,this.background=null,this.environment=null,this.fog=null,this.backgroundBlurriness=0,this.backgroundIntensity=1,this.backgroundRotation=new rm,this.environmentIntensity=1,this.environmentRotation=new rm,this.overrideMaterial=null,typeof __THREE_DEVTOOLS__<`u`&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent(`observe`,{detail:this}))}copy(e,t){return super.copy(e,t),e.background!==null&&(this.background=e.background.clone()),e.environment!==null&&(this.environment=e.environment.clone()),e.fog!==null&&(this.fog=e.fog.clone()),this.backgroundBlurriness=e.backgroundBlurriness,this.backgroundIntensity=e.backgroundIntensity,this.backgroundRotation.copy(e.backgroundRotation),this.environmentIntensity=e.environmentIntensity,this.environmentRotation.copy(e.environmentRotation),e.overrideMaterial!==null&&(this.overrideMaterial=e.overrideMaterial.clone()),this.matrixAutoUpdate=e.matrixAutoUpdate,this}toJSON(e){let t=super.toJSON(e);return this.fog!==null&&(t.object.fog=this.fog.toJSON()),t.object.backgroundBlurriness=this.backgroundBlurriness,t.object.backgroundIntensity=this.backgroundIntensity,t.object.backgroundRotation=this.backgroundRotation.toArray(),t.object.environmentIntensity=this.environmentIntensity,t.object.environmentRotation=this.environmentRotation.toArray(),t}},jm=new Q,Mm=new Q,Nm=new Q,Pm=new Q,Fm=new Q,Im=new Q,Lm=new Q,Rm=new Q,zm=new Q,Bm=new Q,Vm=new Hp,Hm=new Hp,Um=new Hp,Wm=class e{constructor(e=new Q,t=new Q,n=new Q){this.a=e,this.b=t,this.c=n}static getNormal(e,t,n,r){r.subVectors(n,t),jm.subVectors(e,t),r.cross(jm);let i=r.lengthSq();return i>0?r.multiplyScalar(1/Math.sqrt(i)):r.set(0,0,0)}static getBarycoord(e,t,n,r,i){jm.subVectors(r,t),Mm.subVectors(n,t),Nm.subVectors(e,t);let a=jm.dot(jm),o=jm.dot(Mm),s=jm.dot(Nm),c=Mm.dot(Mm),l=Mm.dot(Nm),u=a*c-o*o;if(u===0)return i.set(0,0,0),null;let d=1/u,f=(c*s-o*l)*d,p=(a*l-o*s)*d;return i.set(1-f-p,p,f)}static containsPoint(e,t,n,r){return this.getBarycoord(e,t,n,r,Pm)!==null&&Pm.x>=0&&Pm.y>=0&&Pm.x+Pm.y<=1}static getInterpolation(e,t,n,r,i,a,o,s){return this.getBarycoord(e,t,n,r,Pm)===null?(s.x=0,s.y=0,`z`in s&&(s.z=0),`w`in s&&(s.w=0),null):(s.setScalar(0),s.addScaledVector(i,Pm.x),s.addScaledVector(a,Pm.y),s.addScaledVector(o,Pm.z),s)}static getInterpolatedAttribute(e,t,n,r,i,a){return Vm.setScalar(0),Hm.setScalar(0),Um.setScalar(0),Vm.fromBufferAttribute(e,t),Hm.fromBufferAttribute(e,n),Um.fromBufferAttribute(e,r),a.setScalar(0),a.addScaledVector(Vm,i.x),a.addScaledVector(Hm,i.y),a.addScaledVector(Um,i.z),a}static isFrontFacing(e,t,n,r){return jm.subVectors(n,t),Mm.subVectors(e,t),jm.cross(Mm).dot(r)<0}set(e,t,n){return this.a.copy(e),this.b.copy(t),this.c.copy(n),this}setFromPointsAndIndices(e,t,n,r){return this.a.copy(e[t]),this.b.copy(e[n]),this.c.copy(e[r]),this}setFromAttributeAndIndices(e,t,n,r){return this.a.fromBufferAttribute(e,t),this.b.fromBufferAttribute(e,n),this.c.fromBufferAttribute(e,r),this}clone(){return new this.constructor().copy(this)}copy(e){return this.a.copy(e.a),this.b.copy(e.b),this.c.copy(e.c),this}getArea(){return jm.subVectors(this.c,this.b),Mm.subVectors(this.a,this.b),jm.cross(Mm).length()*.5}getMidpoint(e){return e.addVectors(this.a,this.b).add(this.c).multiplyScalar(1/3)}getNormal(t){return e.getNormal(this.a,this.b,this.c,t)}getPlane(e){return e.setFromCoplanarPoints(this.a,this.b,this.c)}getBarycoord(t,n){return e.getBarycoord(t,this.a,this.b,this.c,n)}getInterpolation(t,n,r,i,a){return e.getInterpolation(t,this.a,this.b,this.c,n,r,i,a)}containsPoint(t){return e.containsPoint(t,this.a,this.b,this.c)}isFrontFacing(t){return e.isFrontFacing(this.a,this.b,this.c,t)}intersectsBox(e){return e.intersectsTriangle(this)}closestPointToPoint(e,t){let n=this.a,r=this.b,i=this.c,a,o;Fm.subVectors(r,n),Im.subVectors(i,n),Rm.subVectors(e,n);let s=Fm.dot(Rm),c=Im.dot(Rm);if(s<=0&&c<=0)return t.copy(n);zm.subVectors(e,r);let l=Fm.dot(zm),u=Im.dot(zm);if(l>=0&&u<=l)return t.copy(r);let d=s*u-l*c;if(d<=0&&s>=0&&l<=0)return a=s/(s-l),t.copy(n).addScaledVector(Fm,a);Bm.subVectors(e,i);let f=Fm.dot(Bm),p=Im.dot(Bm);if(p>=0&&f<=p)return t.copy(i);let m=f*c-s*p;if(m<=0&&c>=0&&p<=0)return o=c/(c-p),t.copy(n).addScaledVector(Im,o);let h=l*p-f*u;if(h<=0&&u-l>=0&&f-p>=0)return Lm.subVectors(i,r),o=(u-l)/(u-l+(f-p)),t.copy(r).addScaledVector(Lm,o);let g=1/(h+m+d);return a=m*g,o=d*g,t.copy(n).addScaledVector(Fm,a).addScaledVector(Im,o)}equals(e){return e.a.equals(this.a)&&e.b.equals(this.b)&&e.c.equals(this.c)}},Gm=class{constructor(e=new Q(1/0,1/0,1/0),t=new Q(-1/0,-1/0,-1/0)){this.isBox3=!0,this.min=e,this.max=t}set(e,t){return this.min.copy(e),this.max.copy(t),this}setFromArray(e){this.makeEmpty();for(let t=0,n=e.length;t<n;t+=3)this.expandByPoint(qm.fromArray(e,t));return this}setFromBufferAttribute(e){this.makeEmpty();for(let t=0,n=e.count;t<n;t++)this.expandByPoint(qm.fromBufferAttribute(e,t));return this}setFromPoints(e){this.makeEmpty();for(let t=0,n=e.length;t<n;t++)this.expandByPoint(e[t]);return this}setFromCenterAndSize(e,t){let n=qm.copy(t).multiplyScalar(.5);return this.min.copy(e).sub(n),this.max.copy(e).add(n),this}setFromObject(e,t=!1){return this.makeEmpty(),this.expandByObject(e,t)}clone(){return new this.constructor().copy(this)}copy(e){return this.min.copy(e.min),this.max.copy(e.max),this}makeEmpty(){return this.min.x=this.min.y=this.min.z=1/0,this.max.x=this.max.y=this.max.z=-1/0,this}isEmpty(){return this.max.x<this.min.x||this.max.y<this.min.y||this.max.z<this.min.z}getCenter(e){return this.isEmpty()?e.set(0,0,0):e.addVectors(this.min,this.max).multiplyScalar(.5)}getSize(e){return this.isEmpty()?e.set(0,0,0):e.subVectors(this.max,this.min)}expandByPoint(e){return this.min.min(e),this.max.max(e),this}expandByVector(e){return this.min.sub(e),this.max.add(e),this}expandByScalar(e){return this.min.addScalar(-e),this.max.addScalar(e),this}expandByObject(e,t=!1){e.updateWorldMatrix(!1,!1);let n=e.geometry;if(n!==void 0){let r=n.getAttribute(`position`);if(t===!0&&r!==void 0&&e.isInstancedMesh!==!0)for(let t=0,n=r.count;t<n;t++)e.isMesh===!0?e.getVertexPosition(t,qm):qm.fromBufferAttribute(r,t),qm.applyMatrix4(e.matrixWorld),this.expandByPoint(qm);else e.boundingBox===void 0?(n.boundingBox===null&&n.computeBoundingBox(),Jm.copy(n.boundingBox)):(e.boundingBox===null&&e.computeBoundingBox(),Jm.copy(e.boundingBox)),Jm.applyMatrix4(e.matrixWorld),this.union(Jm)}let r=e.children;for(let e=0,n=r.length;e<n;e++)this.expandByObject(r[e],t);return this}containsPoint(e){return e.x>=this.min.x&&e.x<=this.max.x&&e.y>=this.min.y&&e.y<=this.max.y&&e.z>=this.min.z&&e.z<=this.max.z}containsBox(e){return this.min.x<=e.min.x&&e.max.x<=this.max.x&&this.min.y<=e.min.y&&e.max.y<=this.max.y&&this.min.z<=e.min.z&&e.max.z<=this.max.z}getParameter(e,t){return t.set((e.x-this.min.x)/(this.max.x-this.min.x),(e.y-this.min.y)/(this.max.y-this.min.y),(e.z-this.min.z)/(this.max.z-this.min.z))}intersectsBox(e){return e.max.x>=this.min.x&&e.min.x<=this.max.x&&e.max.y>=this.min.y&&e.min.y<=this.max.y&&e.max.z>=this.min.z&&e.min.z<=this.max.z}intersectsSphere(e){return this.clampPoint(e.center,qm),qm.distanceToSquared(e.center)<=e.radius*e.radius}intersectsPlane(e){let t,n;return e.normal.x>0?(t=e.normal.x*this.min.x,n=e.normal.x*this.max.x):(t=e.normal.x*this.max.x,n=e.normal.x*this.min.x),e.normal.y>0?(t+=e.normal.y*this.min.y,n+=e.normal.y*this.max.y):(t+=e.normal.y*this.max.y,n+=e.normal.y*this.min.y),e.normal.z>0?(t+=e.normal.z*this.min.z,n+=e.normal.z*this.max.z):(t+=e.normal.z*this.max.z,n+=e.normal.z*this.min.z),t<=-e.constant&&n>=-e.constant}intersectsTriangle(e){if(this.isEmpty())return!1;this.getCenter(th),nh.subVectors(this.max,th),Ym.subVectors(e.a,th),Xm.subVectors(e.b,th),Zm.subVectors(e.c,th),Qm.subVectors(Xm,Ym),$m.subVectors(Zm,Xm),eh.subVectors(Ym,Zm);let t=[0,-Qm.z,Qm.y,0,-$m.z,$m.y,0,-eh.z,eh.y,Qm.z,0,-Qm.x,$m.z,0,-$m.x,eh.z,0,-eh.x,-Qm.y,Qm.x,0,-$m.y,$m.x,0,-eh.y,eh.x,0];return!ah(t,Ym,Xm,Zm,nh)||(t=[1,0,0,0,1,0,0,0,1],!ah(t,Ym,Xm,Zm,nh))?!1:(rh.crossVectors(Qm,$m),t=[rh.x,rh.y,rh.z],ah(t,Ym,Xm,Zm,nh))}clampPoint(e,t){return t.copy(e).clamp(this.min,this.max)}distanceToPoint(e){return this.clampPoint(e,qm).distanceTo(e)}getBoundingSphere(e){return this.isEmpty()?e.makeEmpty():(this.getCenter(e.center),e.radius=this.getSize(qm).length()*.5),e}intersect(e){return this.min.max(e.min),this.max.min(e.max),this.isEmpty()&&this.makeEmpty(),this}union(e){return this.min.min(e.min),this.max.max(e.max),this}applyMatrix4(e){return this.isEmpty()?this:(Km[0].set(this.min.x,this.min.y,this.min.z).applyMatrix4(e),Km[1].set(this.min.x,this.min.y,this.max.z).applyMatrix4(e),Km[2].set(this.min.x,this.max.y,this.min.z).applyMatrix4(e),Km[3].set(this.min.x,this.max.y,this.max.z).applyMatrix4(e),Km[4].set(this.max.x,this.min.y,this.min.z).applyMatrix4(e),Km[5].set(this.max.x,this.min.y,this.max.z).applyMatrix4(e),Km[6].set(this.max.x,this.max.y,this.min.z).applyMatrix4(e),Km[7].set(this.max.x,this.max.y,this.max.z).applyMatrix4(e),this.setFromPoints(Km),this)}translate(e){return this.min.add(e),this.max.add(e),this}equals(e){return e.min.equals(this.min)&&e.max.equals(this.max)}toJSON(){return{min:this.min.toArray(),max:this.max.toArray()}}fromJSON(e){return this.min.fromArray(e.min),this.max.fromArray(e.max),this}},Km=[new Q,new Q,new Q,new Q,new Q,new Q,new Q,new Q],qm=new Q,Jm=new Gm,Ym=new Q,Xm=new Q,Zm=new Q,Qm=new Q,$m=new Q,eh=new Q,th=new Q,nh=new Q,rh=new Q,ih=new Q;function ah(e,t,n,r,i){for(let a=0,o=e.length-3;a<=o;a+=3){ih.fromArray(e,a);let o=i.x*Math.abs(ih.x)+i.y*Math.abs(ih.y)+i.z*Math.abs(ih.z),s=t.dot(ih),c=n.dot(ih),l=r.dot(ih);if(Math.max(-Math.max(s,c,l),Math.min(s,c,l))>o)return!1}return!0}var oh=new Q,sh=new Sp,ch=0,lh=class extends fp{constructor(e,t,n=!1){if(super(),Array.isArray(e))throw TypeError(`THREE.BufferAttribute: array should be a Typed Array.`);this.isBufferAttribute=!0,Object.defineProperty(this,"id",{value:ch++}),this.name=``,this.array=e,this.itemSize=t,this.count=e===void 0?0:e.length/t,this.normalized=n,this.usage=ep,this.updateRanges=[],this.gpuType=Vd,this.version=0}onUploadCallback(){}set needsUpdate(e){e===!0&&this.version++}setUsage(e){return this.usage=e,this}addUpdateRange(e,t){this.updateRanges.push({start:e,count:t})}clearUpdateRanges(){this.updateRanges.length=0}copy(e){return this.name=e.name,this.array=new e.array.constructor(e.array),this.itemSize=e.itemSize,this.count=e.count,this.normalized=e.normalized,this.usage=e.usage,this.gpuType=e.gpuType,this}copyAt(e,t,n){e*=this.itemSize,n*=t.itemSize;for(let r=0,i=this.itemSize;r<i;r++)this.array[e+r]=t.array[n+r];return this}copyArray(e){return this.array.set(e),this}applyMatrix3(e){if(this.itemSize===2)for(let t=0,n=this.count;t<n;t++)sh.fromBufferAttribute(this,t),sh.applyMatrix3(e),this.setXY(t,sh.x,sh.y);else if(this.itemSize===3)for(let t=0,n=this.count;t<n;t++)oh.fromBufferAttribute(this,t),oh.applyMatrix3(e),this.setXYZ(t,oh.x,oh.y,oh.z);return this}applyMatrix4(e){for(let t=0,n=this.count;t<n;t++)oh.fromBufferAttribute(this,t),oh.applyMatrix4(e),this.setXYZ(t,oh.x,oh.y,oh.z);return this}applyNormalMatrix(e){for(let t=0,n=this.count;t<n;t++)oh.fromBufferAttribute(this,t),oh.applyNormalMatrix(e),this.setXYZ(t,oh.x,oh.y,oh.z);return this}transformDirection(e){for(let t=0,n=this.count;t<n;t++)oh.fromBufferAttribute(this,t),oh.transformDirection(e),this.setXYZ(t,oh.x,oh.y,oh.z);return this}set(e,t=0){return this.array.set(e,t),this}getComponent(e,t){let n=this.array[e*this.itemSize+t];return this.normalized&&(n=bp(n,this.array)),n}setComponent(e,t,n){return this.normalized&&(n=xp(n,this.array)),this.array[e*this.itemSize+t]=n,this}getX(e){let t=this.array[e*this.itemSize];return this.normalized&&(t=bp(t,this.array)),t}setX(e,t){return this.normalized&&(t=xp(t,this.array)),this.array[e*this.itemSize]=t,this}getY(e){let t=this.array[e*this.itemSize+1];return this.normalized&&(t=bp(t,this.array)),t}setY(e,t){return this.normalized&&(t=xp(t,this.array)),this.array[e*this.itemSize+1]=t,this}getZ(e){let t=this.array[e*this.itemSize+2];return this.normalized&&(t=bp(t,this.array)),t}setZ(e,t){return this.normalized&&(t=xp(t,this.array)),this.array[e*this.itemSize+2]=t,this}getW(e){let t=this.array[e*this.itemSize+3];return this.normalized&&(t=bp(t,this.array)),t}setW(e,t){return this.normalized&&(t=xp(t,this.array)),this.array[e*this.itemSize+3]=t,this}setXY(e,t,n){return e*=this.itemSize,this.normalized&&(t=xp(t,this.array),n=xp(n,this.array)),this.array[e+0]=t,this.array[e+1]=n,this}setXYZ(e,t,n,r){return e*=this.itemSize,this.normalized&&(t=xp(t,this.array),n=xp(n,this.array),r=xp(r,this.array)),this.array[e+0]=t,this.array[e+1]=n,this.array[e+2]=r,this}setXYZW(e,t,n,r,i){return e*=this.itemSize,this.normalized&&(t=xp(t,this.array),n=xp(n,this.array),r=xp(r,this.array),i=xp(i,this.array)),this.array[e+0]=t,this.array[e+1]=n,this.array[e+2]=r,this.array[e+3]=i,this}onUpload(e){return this.onUploadCallback=e,this}clone(){return new this.constructor(this.array,this.itemSize).copy(this)}toJSON(){let e={itemSize:this.itemSize,type:this.array.constructor.name,array:Array.from(this.array),normalized:this.normalized};return e.name=this.name,e.usage=this.usage,e.gpuType=this.gpuType,e}dispose(){this.dispatchEvent({type:`dispose`})}},uh=class extends lh{constructor(e,t,n){super(new Uint16Array(e),t,n)}},dh=class extends lh{constructor(e,t,n){super(new Uint32Array(e),t,n)}},fh=class extends lh{constructor(e,t,n){super(new Float32Array(e),t,n)}},ph=new Gm,mh=new Q,hh=new Q,gh=class{constructor(e=new Q,t=-1){this.isSphere=!0,this.center=e,this.radius=t}set(e,t){return this.center.copy(e),this.radius=t,this}setFromPoints(e,t){let n=this.center;t===void 0?ph.setFromPoints(e).getCenter(n):n.copy(t);let r=0;for(let t=0,i=e.length;t<i;t++)r=Math.max(r,n.distanceToSquared(e[t]));return this.radius=Math.sqrt(r),this}copy(e){return this.center.copy(e.center),this.radius=e.radius,this}isEmpty(){return this.radius<0}makeEmpty(){return this.center.set(0,0,0),this.radius=-1,this}containsPoint(e){return e.distanceToSquared(this.center)<=this.radius*this.radius}distanceToPoint(e){return e.distanceTo(this.center)-this.radius}intersectsSphere(e){let t=this.radius+e.radius;return e.center.distanceToSquared(this.center)<=t*t}intersectsBox(e){return e.intersectsSphere(this)}intersectsPlane(e){return Math.abs(e.distanceToPoint(this.center))<=this.radius}clampPoint(e,t){let n=this.center.distanceToSquared(e);return t.copy(e),n>this.radius*this.radius&&(t.sub(this.center).normalize(),t.multiplyScalar(this.radius).add(this.center)),t}getBoundingBox(e){return this.isEmpty()?(e.makeEmpty(),e):(e.set(this.center,this.center),e.expandByScalar(this.radius),e)}applyMatrix4(e){return this.center.applyMatrix4(e),this.radius*=e.getMaxScaleOnAxis(),this}translate(e){return this.center.add(e),this}expandByPoint(e){if(this.isEmpty())return this.center.copy(e),this.radius=0,this;mh.subVectors(e,this.center);let t=mh.lengthSq();if(t>this.radius*this.radius){let e=Math.sqrt(t),n=(e-this.radius)*.5;this.center.addScaledVector(mh,n/e),this.radius+=n}return this}union(e){return e.isEmpty()?this:this.isEmpty()?(this.copy(e),this):(this.center.equals(e.center)===!0?this.radius=Math.max(this.radius,e.radius):(hh.subVectors(e.center,this.center).setLength(e.radius),this.expandByPoint(mh.copy(e.center).add(hh)),this.expandByPoint(mh.copy(e.center).sub(hh))),this)}equals(e){return e.center.equals(this.center)&&e.radius===this.radius}clone(){return new this.constructor().copy(this)}toJSON(){return{radius:this.radius,center:this.center.toArray()}}fromJSON(e){return this.radius=e.radius,this.center.fromArray(e.center),this}},_h=0,vh=new qp,yh=new bm,bh=new Q,xh=new Gm,Sh=new Gm,Ch=new Q,wh=class e extends fp{constructor(){super(),this.isBufferGeometry=!0,Object.defineProperty(this,"id",{value:_h++}),this.uuid=gp(),this.name=``,this.type=`BufferGeometry`,this.index=null,this.indirect=null,this.indirectOffset=0,this.attributes={},this.morphAttributes={},this.morphTargetsRelative=!1,this.groups=[],this.boundingBox=null,this.boundingSphere=null,this.drawRange={start:0,count:1/0},this.userData={},this._transformed=!1}getIndex(){return this.index}setIndex(e){return this.index=Array.isArray(e)?new(np(e)?dh:uh)(e,1):e,this}setIndirect(e,t=0){return this.indirect=e,this.indirectOffset=t,this}getIndirect(){return this.indirect}getAttribute(e){return this.attributes[e]}setAttribute(e,t){return this.attributes[e]=t,this}deleteAttribute(e){return delete this.attributes[e],this}hasAttribute(e){return this.attributes[e]!==void 0}addGroup(e,t,n=0){this.groups.push({start:e,count:t,materialIndex:n})}clearGroups(){this.groups=[]}setDrawRange(e,t){this.drawRange.start=e,this.drawRange.count=t}applyMatrix4(e){let t=this.attributes.position;t!==void 0&&(t.applyMatrix4(e),t.needsUpdate=!0);let n=this.attributes.normal;if(n!==void 0){let t=new Ep().getNormalMatrix(e);n.applyNormalMatrix(t),n.needsUpdate=!0}let r=this.attributes.tangent;return r!==void 0&&(r.transformDirection(e),r.needsUpdate=!0),this.boundingBox!==null&&this.computeBoundingBox(),this.boundingSphere!==null&&this.computeBoundingSphere(),this._transformed=!0,this}applyQuaternion(e){return vh.makeRotationFromQuaternion(e),this.applyMatrix4(vh),this}rotateX(e){return vh.makeRotationX(e),this.applyMatrix4(vh),this}rotateY(e){return vh.makeRotationY(e),this.applyMatrix4(vh),this}rotateZ(e){return vh.makeRotationZ(e),this.applyMatrix4(vh),this}translate(e,t,n){return vh.makeTranslation(e,t,n),this.applyMatrix4(vh),this}scale(e,t,n){return vh.makeScale(e,t,n),this.applyMatrix4(vh),this}lookAt(e){return yh.lookAt(e),yh.updateMatrix(),this.applyMatrix4(yh.matrix),this}center(){return this.computeBoundingBox(),this.boundingBox.getCenter(bh).negate(),this.translate(bh.x,bh.y,bh.z),this}setFromPoints(e){let t=this.getAttribute(`position`);if(t===void 0){let t=[];for(let n=0,r=e.length;n<r;n++){let r=e[n];t.push(r.x,r.y,r.z||0)}this.setAttribute(`position`,new fh(t,3))}else{let n=Math.min(e.length,t.count);for(let r=0;r<n;r++){let n=e[r];t.setXYZ(r,n.x,n.y,n.z||0)}e.length>t.count&&X(`BufferGeometry: Buffer size too small for points data. Use .dispose() and create a new geometry.`),t.needsUpdate=!0}return this}computeBoundingBox(){this.boundingBox===null&&(this.boundingBox=new Gm);let e=this.attributes.position,t=this.morphAttributes.position;if(e&&e.isGLBufferAttribute){Z(`BufferGeometry.computeBoundingBox(): GLBufferAttribute requires a manual bounding box.`,this),this.boundingBox.set(new Q(-1/0,-1/0,-1/0),new Q(1/0,1/0,1/0));return}if(e!==void 0){if(this.boundingBox.setFromBufferAttribute(e),t)for(let e=0,n=t.length;e<n;e++){let n=t[e];xh.setFromBufferAttribute(n),this.morphTargetsRelative?(Ch.addVectors(this.boundingBox.min,xh.min),this.boundingBox.expandByPoint(Ch),Ch.addVectors(this.boundingBox.max,xh.max),this.boundingBox.expandByPoint(Ch)):(this.boundingBox.expandByPoint(xh.min),this.boundingBox.expandByPoint(xh.max))}}else this.boundingBox.makeEmpty();(isNaN(this.boundingBox.min.x)||isNaN(this.boundingBox.min.y)||isNaN(this.boundingBox.min.z))&&Z(`BufferGeometry.computeBoundingBox(): Computed min/max have NaN values. The "position" attribute is likely to have NaN values.`,this)}computeBoundingSphere(){this.boundingSphere===null&&(this.boundingSphere=new gh);let e=this.attributes.position,t=this.morphAttributes.position;if(e&&e.isGLBufferAttribute){Z(`BufferGeometry.computeBoundingSphere(): GLBufferAttribute requires a manual bounding sphere.`,this),this.boundingSphere.set(new Q,1/0);return}if(e){let n=this.boundingSphere.center;if(xh.setFromBufferAttribute(e),t)for(let e=0,n=t.length;e<n;e++){let n=t[e];Sh.setFromBufferAttribute(n),this.morphTargetsRelative?(Ch.addVectors(xh.min,Sh.min),xh.expandByPoint(Ch),Ch.addVectors(xh.max,Sh.max),xh.expandByPoint(Ch)):(xh.expandByPoint(Sh.min),xh.expandByPoint(Sh.max))}xh.getCenter(n);let r=0;for(let t=0,i=e.count;t<i;t++)Ch.fromBufferAttribute(e,t),r=Math.max(r,n.distanceToSquared(Ch));if(t)for(let i=0,a=t.length;i<a;i++){let a=t[i],o=this.morphTargetsRelative;for(let t=0,i=a.count;t<i;t++)Ch.fromBufferAttribute(a,t),o&&(bh.fromBufferAttribute(e,t),Ch.add(bh)),r=Math.max(r,n.distanceToSquared(Ch))}this.boundingSphere.radius=Math.sqrt(r),isNaN(this.boundingSphere.radius)&&Z(`BufferGeometry.computeBoundingSphere(): Computed radius is NaN. The "position" attribute is likely to have NaN values.`,this)}}computeTangents(){let e=this.index,t=this.attributes;if(e===null||t.position===void 0||t.normal===void 0||t.uv===void 0){Z(`BufferGeometry: .computeTangents() failed. Missing required attributes (index, position, normal or uv)`);return}let n=t.position,r=t.normal,i=t.uv,a=this.getAttribute(`tangent`);(a===void 0||a.count!==n.count)&&(a=new lh(new Float32Array(4*n.count),4),this.setAttribute(`tangent`,a));let o=[],s=[];for(let e=0;e<n.count;e++)o[e]=new Q,s[e]=new Q;let c=new Q,l=new Q,u=new Q,d=new Sp,f=new Sp,p=new Sp,m=new Q,h=new Q;function g(e,t,r){c.fromBufferAttribute(n,e),l.fromBufferAttribute(n,t),u.fromBufferAttribute(n,r),d.fromBufferAttribute(i,e),f.fromBufferAttribute(i,t),p.fromBufferAttribute(i,r),l.sub(c),u.sub(c),f.sub(d),p.sub(d);let a=1/(f.x*p.y-p.x*f.y);isFinite(a)&&(m.copy(l).multiplyScalar(p.y).addScaledVector(u,-f.y).multiplyScalar(a),h.copy(u).multiplyScalar(f.x).addScaledVector(l,-p.x).multiplyScalar(a),o[e].add(m),o[t].add(m),o[r].add(m),s[e].add(h),s[t].add(h),s[r].add(h))}let _=this.groups;_.length===0&&(_=[{start:0,count:e.count}]);for(let t=0,n=_.length;t<n;++t){let n=_[t],r=n.start,i=n.count;for(let t=r,n=r+i;t<n;t+=3)g(e.getX(t+0),e.getX(t+1),e.getX(t+2))}let v=new Q,y=new Q,b=new Q,x=new Q;function S(e){b.fromBufferAttribute(r,e),x.copy(b);let t=o[e];v.copy(t),v.sub(b.multiplyScalar(b.dot(t))).normalize(),y.crossVectors(x,t);let n=y.dot(s[e])<0?-1:1;a.setXYZW(e,v.x,v.y,v.z,n)}for(let t=0,n=_.length;t<n;++t){let n=_[t],r=n.start,i=n.count;for(let t=r,n=r+i;t<n;t+=3)S(e.getX(t+0)),S(e.getX(t+1)),S(e.getX(t+2))}this._transformed=!0}computeVertexNormals(){let e=this.index,t=this.getAttribute(`position`);if(t!==void 0){let n=this.getAttribute(`normal`);if(n===void 0||n.count!==t.count)n=new lh(new Float32Array(t.count*3),3),this.setAttribute(`normal`,n);else for(let e=0,t=n.count;e<t;e++)n.setXYZ(e,0,0,0);let r=new Q,i=new Q,a=new Q,o=new Q,s=new Q,c=new Q,l=new Q,u=new Q;if(e)for(let d=0,f=e.count;d<f;d+=3){let f=e.getX(d+0),p=e.getX(d+1),m=e.getX(d+2);r.fromBufferAttribute(t,f),i.fromBufferAttribute(t,p),a.fromBufferAttribute(t,m),l.subVectors(a,i),u.subVectors(r,i),l.cross(u),o.fromBufferAttribute(n,f),s.fromBufferAttribute(n,p),c.fromBufferAttribute(n,m),o.add(l),s.add(l),c.add(l),n.setXYZ(f,o.x,o.y,o.z),n.setXYZ(p,s.x,s.y,s.z),n.setXYZ(m,c.x,c.y,c.z)}else for(let e=0,o=t.count;e<o;e+=3)r.fromBufferAttribute(t,e+0),i.fromBufferAttribute(t,e+1),a.fromBufferAttribute(t,e+2),l.subVectors(a,i),u.subVectors(r,i),l.cross(u),n.setXYZ(e+0,l.x,l.y,l.z),n.setXYZ(e+1,l.x,l.y,l.z),n.setXYZ(e+2,l.x,l.y,l.z);this.normalizeNormals(),n.needsUpdate=!0}}normalizeNormals(){let e=this.attributes.normal;for(let t=0,n=e.count;t<n;t++)Ch.fromBufferAttribute(e,t),Ch.normalize(),e.setXYZ(t,Ch.x,Ch.y,Ch.z)}toNonIndexed(){function t(e,t){let n=e.array,r=e.itemSize,i=e.normalized,a=new n.constructor(t.length*r),o=0,s=0;for(let i=0,c=t.length;i<c;i++){o=e.isInterleavedBufferAttribute?t[i]*e.data.stride+e.offset:t[i]*r;for(let e=0;e<r;e++)a[s++]=n[o++]}return new lh(a,r,i)}if(this.index===null)return X(`BufferGeometry.toNonIndexed(): BufferGeometry is already non-indexed.`),this;let n=new e,r=this.index.array,i=this.attributes;for(let e in i){let a=i[e],o=t(a,r);n.setAttribute(e,o)}let a=this.morphAttributes;for(let e in a){let i=[],o=a[e];for(let e=0,n=o.length;e<n;e++){let n=o[e],a=t(n,r);i.push(a)}n.morphAttributes[e]=i}n.morphTargetsRelative=this.morphTargetsRelative;let o=this.groups;for(let e=0,t=o.length;e<t;e++){let t=o[e];n.addGroup(t.start,t.count,t.materialIndex)}return n}toJSON(){let e={metadata:{version:4.7,type:`BufferGeometry`,generator:`BufferGeometry.toJSON`}};if(e.uuid=this.uuid,e.type=this.parameters!==void 0&&this._transformed===!0?`BufferGeometry`:this.type,e.name=this.name,Object.keys(this.userData).length>0&&(e.userData=this.userData),this.parameters!==void 0&&this._transformed!==!0){let t=this.parameters;for(let n in t)t[n]!==void 0&&(e[n]=t[n]);return e}e.data={attributes:{}};let t=this.index;t!==null&&(e.data.index={type:t.array.constructor.name,array:Array.prototype.slice.call(t.array)});let n=this.attributes;for(let t in n){let r=n[t];e.data.attributes[t]=r.toJSON(e.data)}let r={},i=!1;for(let t in this.morphAttributes){let n=this.morphAttributes[t],a=[];for(let t=0,r=n.length;t<r;t++){let r=n[t];a.push(r.toJSON(e.data))}a.length>0&&(r[t]=a,i=!0)}i&&(e.data.morphAttributes=r,e.data.morphTargetsRelative=this.morphTargetsRelative);let a=this.groups;a.length>0&&(e.data.groups=JSON.parse(JSON.stringify(a)));let o=this.boundingSphere;return o!==null&&(e.data.boundingSphere=o.toJSON()),e}clone(){return new this.constructor().copy(this)}copy(e){this.index=null,this.attributes={},this.morphAttributes={},this.groups=[],this.boundingBox=null,this.boundingSphere=null;let t={};this.name=e.name;let n=e.index;n!==null&&this.setIndex(n.clone());let r=e.attributes;for(let e in r){let n=r[e];this.setAttribute(e,n.clone(t))}let i=e.morphAttributes;for(let e in i){let n=[],r=i[e];for(let e=0,i=r.length;e<i;e++)n.push(r[e].clone(t));this.morphAttributes[e]=n}this.morphTargetsRelative=e.morphTargetsRelative;let a=e.groups;for(let e=0,t=a.length;e<t;e++){let t=a[e];this.addGroup(t.start,t.count,t.materialIndex)}let o=e.boundingBox;o!==null&&(this.boundingBox=o.clone());let s=e.boundingSphere;return s!==null&&(this.boundingSphere=s.clone()),this.drawRange.start=e.drawRange.start,this.drawRange.count=e.drawRange.count,this.userData=e.userData,this._transformed=e._transformed,this}dispose(){this.dispatchEvent({type:`dispose`})}},Th=new Q,Eh=new Q,Dh=new Ep,Oh=class{constructor(e=new Q(1,0,0),t=0){this.isPlane=!0,this.normal=e,this.constant=t}set(e,t){return this.normal.copy(e),this.constant=t,this}setComponents(e,t,n,r){return this.normal.set(e,t,n),this.constant=r,this}setFromNormalAndCoplanarPoint(e,t){return this.normal.copy(e),this.constant=-t.dot(this.normal),this}setFromCoplanarPoints(e,t,n){let r=Th.subVectors(n,t).cross(Eh.subVectors(e,t)).normalize();return this.setFromNormalAndCoplanarPoint(r,e),this}copy(e){return this.normal.copy(e.normal),this.constant=e.constant,this}normalize(){let e=1/this.normal.length();return this.normal.multiplyScalar(e),this.constant*=e,this}negate(){return this.constant*=-1,this.normal.negate(),this}distanceToPoint(e){return this.normal.dot(e)+this.constant}distanceToSphere(e){return this.distanceToPoint(e.center)-e.radius}projectPoint(e,t){return t.copy(e).addScaledVector(this.normal,-this.distanceToPoint(e))}intersectLine(e,t,n=!0){let r=e.delta(Th),i=this.normal.dot(r);if(i===0)return this.distanceToPoint(e.start)===0?t.copy(e.start):null;let a=-(e.start.dot(this.normal)+this.constant)/i;return n===!0&&(a<0||a>1)?null:t.copy(e.start).addScaledVector(r,a)}intersectsLine(e){let t=this.distanceToPoint(e.start),n=this.distanceToPoint(e.end);return t<0&&n>0||n<0&&t>0}intersectsBox(e){return e.intersectsPlane(this)}intersectsSphere(e){return e.intersectsPlane(this)}coplanarPoint(e){return e.copy(this.normal).multiplyScalar(-this.constant)}applyMatrix4(e,t){let n=t||Dh.getNormalMatrix(e),r=this.coplanarPoint(Th).applyMatrix4(e),i=this.normal.applyMatrix3(n).normalize();return this.constant=-r.dot(i),this}translate(e){return this.constant-=e.dot(this.normal),this}equals(e){return e.normal.equals(this.normal)&&e.constant===this.constant}clone(){return new this.constructor().copy(this)}toJSON(){return{normal:this.normal.toArray(),constant:this.constant}}fromJSON(e){return this.normal.fromArray(e.normal),this.constant=e.constant,this}},kh=0,Ah=class extends fp{constructor(){super(),this.isMaterial=!0,Object.defineProperty(this,"id",{value:kh++}),this.uuid=gp(),this.name=``,this.type=`Material`,this.blending=1,this.side=0,this.vertexColors=!1,this.opacity=1,this.transparent=!1,this.alphaHash=!1,this.blendSrc=204,this.blendDst=205,this.blendEquation=100,this.blendSrcAlpha=null,this.blendDstAlpha=null,this.blendEquationAlpha=null,this.blendColor=new Om(0,0,0),this.blendAlpha=0,this.depthFunc=3,this.depthTest=!0,this.depthWrite=!0,this.stencilWriteMask=255,this.stencilFunc=519,this.stencilRef=0,this.stencilFuncMask=255,this.stencilFail=$f,this.stencilZFail=$f,this.stencilZPass=$f,this.stencilWrite=!1,this.clippingPlanes=null,this.clipIntersection=!1,this.clipShadows=!1,this.shadowSide=null,this.colorWrite=!0,this.precision=null,this.polygonOffset=!1,this.polygonOffsetFactor=0,this.polygonOffsetUnits=0,this.dithering=!1,this.alphaToCoverage=!1,this.premultipliedAlpha=!1,this.forceSinglePass=!1,this.allowOverride=!0,this.visible=!0,this.toneMapped=!0,this.userData={},this.version=0,this._alphaTest=0}get alphaTest(){return this._alphaTest}set alphaTest(e){this._alphaTest>0!=e>0&&this.version++,this._alphaTest=e}onBeforeRender(){}onBeforeCompile(){}customProgramCacheKey(){return this.onBeforeCompile.toString()}setValues(e){if(e!==void 0)for(let t in e){let n=e[t];if(n===void 0){X(`Material: parameter '${t}' has value of undefined.`);continue}let r=this[t];if(r===void 0){X(`Material: '${t}' is not a property of THREE.${this.type}.`);continue}r&&r.isColor?r.set(n):r&&r.isVector2&&n&&n.isVector2||r&&r.isEuler&&n&&n.isEuler||r&&r.isVector3&&n&&n.isVector3?r.copy(n):this[t]=n}}toJSON(e){let t=e===void 0||typeof e==`string`;t&&(e={textures:{},images:{}});let n={metadata:{version:4.7,type:`Material`,generator:`Material.toJSON`}};n.uuid=this.uuid,n.type=this.type,n.blending=this.blending,n.side=this.side,n.shadowSide=this.shadowSide,n.vertexColors=this.vertexColors,n.opacity=this.opacity,n.transparent=this.transparent,n.blendSrc=this.blendSrc,n.blendDst=this.blendDst,n.blendEquation=this.blendEquation,n.blendSrcAlpha=this.blendSrcAlpha,n.blendDstAlpha=this.blendDstAlpha,n.blendEquationAlpha=this.blendEquationAlpha,n.blendColor=this.blendColor.getHex(),n.blendAlpha=this.blendAlpha,n.depthFunc=this.depthFunc,n.depthTest=this.depthTest,n.depthWrite=this.depthWrite,n.colorWrite=this.colorWrite,n.clipIntersection=this.clipIntersection,n.clipShadows=this.clipShadows,n.stencilWriteMask=this.stencilWriteMask,n.stencilFunc=this.stencilFunc,n.stencilRef=this.stencilRef,n.stencilFuncMask=this.stencilFuncMask,n.stencilFail=this.stencilFail,n.stencilZFail=this.stencilZFail,n.stencilZPass=this.stencilZPass,n.stencilWrite=this.stencilWrite,n.polygonOffset=this.polygonOffset,n.polygonOffsetFactor=this.polygonOffsetFactor,n.polygonOffsetUnits=this.polygonOffsetUnits,n.dithering=this.dithering,n.alphaTest=this.alphaTest,n.alphaHash=this.alphaHash,n.alphaToCoverage=this.alphaToCoverage,n.premultipliedAlpha=this.premultipliedAlpha,n.forceSinglePass=this.forceSinglePass,n.allowOverride=this.allowOverride,n.visible=this.visible,n.toneMapped=this.toneMapped,n.name=this.name,this.color&&this.color.isColor&&(n.color=this.color.getHex()),this.roughness!==void 0&&(n.roughness=this.roughness),this.metalness!==void 0&&(n.metalness=this.metalness),this.sheen!==void 0&&(n.sheen=this.sheen),this.sheenColor&&this.sheenColor.isColor&&(n.sheenColor=this.sheenColor.getHex()),this.sheenRoughness!==void 0&&(n.sheenRoughness=this.sheenRoughness),this.emissive&&this.emissive.isColor&&(n.emissive=this.emissive.getHex()),this.emissiveIntensity!==void 0&&(n.emissiveIntensity=this.emissiveIntensity),this.specular&&this.specular.isColor&&(n.specular=this.specular.getHex()),this.specularIntensity!==void 0&&(n.specularIntensity=this.specularIntensity),this.specularColor&&this.specularColor.isColor&&(n.specularColor=this.specularColor.getHex()),this.shininess!==void 0&&(n.shininess=this.shininess),this.clearcoat!==void 0&&(n.clearcoat=this.clearcoat),this.clearcoatRoughness!==void 0&&(n.clearcoatRoughness=this.clearcoatRoughness),this.clearcoatMap&&this.clearcoatMap.isTexture&&(n.clearcoatMap=this.clearcoatMap.toJSON(e).uuid),this.clearcoatRoughnessMap&&this.clearcoatRoughnessMap.isTexture&&(n.clearcoatRoughnessMap=this.clearcoatRoughnessMap.toJSON(e).uuid),this.clearcoatNormalMap&&this.clearcoatNormalMap.isTexture&&(n.clearcoatNormalMap=this.clearcoatNormalMap.toJSON(e).uuid,n.clearcoatNormalScale=this.clearcoatNormalScale.toArray()),this.sheenColorMap&&this.sheenColorMap.isTexture&&(n.sheenColorMap=this.sheenColorMap.toJSON(e).uuid),this.sheenRoughnessMap&&this.sheenRoughnessMap.isTexture&&(n.sheenRoughnessMap=this.sheenRoughnessMap.toJSON(e).uuid),this.dispersion!==void 0&&(n.dispersion=this.dispersion),this.retroreflectivity!==void 0&&(n.retroreflectivity=this.retroreflectivity),this.iridescence!==void 0&&(n.iridescence=this.iridescence),this.iridescenceIOR!==void 0&&(n.iridescenceIOR=this.iridescenceIOR),this.iridescenceThicknessRange!==void 0&&(n.iridescenceThicknessRange=this.iridescenceThicknessRange),this.iridescenceMap&&this.iridescenceMap.isTexture&&(n.iridescenceMap=this.iridescenceMap.toJSON(e).uuid),this.iridescenceThicknessMap&&this.iridescenceThicknessMap.isTexture&&(n.iridescenceThicknessMap=this.iridescenceThicknessMap.toJSON(e).uuid),this.anisotropy!==void 0&&(n.anisotropy=this.anisotropy),this.anisotropyRotation!==void 0&&(n.anisotropyRotation=this.anisotropyRotation),this.anisotropyMap&&this.anisotropyMap.isTexture&&(n.anisotropyMap=this.anisotropyMap.toJSON(e).uuid),this.map&&this.map.isTexture&&(n.map=this.map.toJSON(e).uuid),this.matcap&&this.matcap.isTexture&&(n.matcap=this.matcap.toJSON(e).uuid),this.alphaMap&&this.alphaMap.isTexture&&(n.alphaMap=this.alphaMap.toJSON(e).uuid),this.lightMap&&this.lightMap.isTexture&&(n.lightMap=this.lightMap.toJSON(e).uuid,n.lightMapIntensity=this.lightMapIntensity),this.aoMap&&this.aoMap.isTexture&&(n.aoMap=this.aoMap.toJSON(e).uuid,n.aoMapIntensity=this.aoMapIntensity),this.bumpMap&&this.bumpMap.isTexture&&(n.bumpMap=this.bumpMap.toJSON(e).uuid,n.bumpScale=this.bumpScale),this.normalMap&&this.normalMap.isTexture&&(n.normalMap=this.normalMap.toJSON(e).uuid,n.normalMapType=this.normalMapType,n.normalScale=this.normalScale.toArray()),this.displacementMap&&this.displacementMap.isTexture&&(n.displacementMap=this.displacementMap.toJSON(e).uuid,n.displacementScale=this.displacementScale,n.displacementBias=this.displacementBias),this.roughnessMap&&this.roughnessMap.isTexture&&(n.roughnessMap=this.roughnessMap.toJSON(e).uuid),this.metalnessMap&&this.metalnessMap.isTexture&&(n.metalnessMap=this.metalnessMap.toJSON(e).uuid),this.emissiveMap&&this.emissiveMap.isTexture&&(n.emissiveMap=this.emissiveMap.toJSON(e).uuid),this.specularMap&&this.specularMap.isTexture&&(n.specularMap=this.specularMap.toJSON(e).uuid),this.specularIntensityMap&&this.specularIntensityMap.isTexture&&(n.specularIntensityMap=this.specularIntensityMap.toJSON(e).uuid),this.specularColorMap&&this.specularColorMap.isTexture&&(n.specularColorMap=this.specularColorMap.toJSON(e).uuid),this.envMap&&this.envMap.isTexture&&(n.envMap=this.envMap.toJSON(e).uuid,this.combine!==void 0&&(n.combine=this.combine)),this.envMapRotation!==void 0&&(n.envMapRotation=this.envMapRotation.toArray()),this.envMapIntensity!==void 0&&(n.envMapIntensity=this.envMapIntensity),this.reflectivity!==void 0&&(n.reflectivity=this.reflectivity),this.refractionRatio!==void 0&&(n.refractionRatio=this.refractionRatio),this.gradientMap&&this.gradientMap.isTexture&&(n.gradientMap=this.gradientMap.toJSON(e).uuid),this.transmission!==void 0&&(n.transmission=this.transmission),this.transmissionMap&&this.transmissionMap.isTexture&&(n.transmissionMap=this.transmissionMap.toJSON(e).uuid),this.thickness!==void 0&&(n.thickness=this.thickness),this.thicknessMap&&this.thicknessMap.isTexture&&(n.thicknessMap=this.thicknessMap.toJSON(e).uuid),this.attenuationDistance!==void 0&&(n.attenuationDistance=this.attenuationDistance),this.attenuationColor!==void 0&&(n.attenuationColor=this.attenuationColor.getHex()),this.size!==void 0&&(n.size=this.size),this.sizeAttenuation!==void 0&&(n.sizeAttenuation=this.sizeAttenuation),Array.isArray(this.clippingPlanes)&&this.clippingPlanes.length>0&&(n.clippingPlanes=this.clippingPlanes.map(e=>e.toJSON())),this.rotation!==void 0&&(n.rotation=this.rotation),this.depthPacking!==void 0&&(n.depthPacking=this.depthPacking),this.linewidth!==void 0&&(n.linewidth=this.linewidth),this.linecap!==void 0&&(n.linecap=this.linecap),this.linejoin!==void 0&&(n.linejoin=this.linejoin),this.dashSize!==void 0&&(n.dashSize=this.dashSize),this.gapSize!==void 0&&(n.gapSize=this.gapSize),this.scale!==void 0&&(n.scale=this.scale),this.wireframe!==void 0&&(n.wireframe=this.wireframe),this.wireframeLinewidth!==void 0&&(n.wireframeLinewidth=this.wireframeLinewidth),this.wireframeLinecap!==void 0&&(n.wireframeLinecap=this.wireframeLinecap),this.wireframeLinejoin!==void 0&&(n.wireframeLinejoin=this.wireframeLinejoin),this.flatShading!==void 0&&(n.flatShading=this.flatShading),this.fog!==void 0&&(n.fog=this.fog),Object.keys(this.userData).length>0&&(n.userData=this.userData);function r(e){let t=[];for(let n in e){let r=e[n];delete r.metadata,t.push(r)}return t}if(t){let t=r(e.textures),i=r(e.images);t.length>0&&(n.textures=t),i.length>0&&(n.images=i)}return n}fromJSON(e,t){if(e.uuid!==void 0&&(this.uuid=e.uuid),e.name!==void 0&&(this.name=e.name),e.color!==void 0&&this.color!==void 0&&this.color.setHex(e.color),e.roughness!==void 0&&(this.roughness=e.roughness),e.metalness!==void 0&&(this.metalness=e.metalness),e.sheen!==void 0&&(this.sheen=e.sheen),e.sheenColor!==void 0&&(this.sheenColor=new Om().setHex(e.sheenColor)),e.sheenRoughness!==void 0&&(this.sheenRoughness=e.sheenRoughness),e.emissive!==void 0&&this.emissive!==void 0&&this.emissive.setHex(e.emissive),e.specular!==void 0&&this.specular!==void 0&&this.specular.setHex(e.specular),e.specularIntensity!==void 0&&(this.specularIntensity=e.specularIntensity),e.specularColor!==void 0&&this.specularColor!==void 0&&this.specularColor.setHex(e.specularColor),e.shininess!==void 0&&(this.shininess=e.shininess),e.clearcoat!==void 0&&(this.clearcoat=e.clearcoat),e.clearcoatRoughness!==void 0&&(this.clearcoatRoughness=e.clearcoatRoughness),e.dispersion!==void 0&&(this.dispersion=e.dispersion),e.retroreflectivity!==void 0&&(this.retroreflectivity=e.retroreflectivity),e.iridescence!==void 0&&(this.iridescence=e.iridescence),e.iridescenceIOR!==void 0&&(this.iridescenceIOR=e.iridescenceIOR),e.iridescenceThicknessRange!==void 0&&(this.iridescenceThicknessRange=e.iridescenceThicknessRange),e.transmission!==void 0&&(this.transmission=e.transmission),e.thickness!==void 0&&(this.thickness=e.thickness),e.attenuationDistance!==void 0&&(this.attenuationDistance=e.attenuationDistance),e.attenuationColor!==void 0&&this.attenuationColor!==void 0&&this.attenuationColor.setHex(e.attenuationColor),e.anisotropy!==void 0&&(this.anisotropy=e.anisotropy),e.anisotropyRotation!==void 0&&(this.anisotropyRotation=e.anisotropyRotation),e.fog!==void 0&&(this.fog=e.fog),e.flatShading!==void 0&&(this.flatShading=e.flatShading),e.blending!==void 0&&(this.blending=e.blending),e.combine!==void 0&&(this.combine=e.combine),e.side!==void 0&&(this.side=e.side),e.shadowSide!==void 0&&(this.shadowSide=e.shadowSide),e.opacity!==void 0&&(this.opacity=e.opacity),e.transparent!==void 0&&(this.transparent=e.transparent),e.alphaTest!==void 0&&(this.alphaTest=e.alphaTest),e.alphaHash!==void 0&&(this.alphaHash=e.alphaHash),e.depthFunc!==void 0&&(this.depthFunc=e.depthFunc),e.depthTest!==void 0&&(this.depthTest=e.depthTest),e.depthWrite!==void 0&&(this.depthWrite=e.depthWrite),e.colorWrite!==void 0&&(this.colorWrite=e.colorWrite),e.clippingPlanes!==void 0&&(this.clippingPlanes=e.clippingPlanes.map(e=>new Oh().fromJSON(e))),e.clipIntersection!==void 0&&(this.clipIntersection=e.clipIntersection),e.clipShadows!==void 0&&(this.clipShadows=e.clipShadows),e.depthPacking!==void 0&&(this.depthPacking=e.depthPacking),e.blendSrc!==void 0&&(this.blendSrc=e.blendSrc),e.blendDst!==void 0&&(this.blendDst=e.blendDst),e.blendEquation!==void 0&&(this.blendEquation=e.blendEquation),e.blendSrcAlpha!==void 0&&(this.blendSrcAlpha=e.blendSrcAlpha),e.blendDstAlpha!==void 0&&(this.blendDstAlpha=e.blendDstAlpha),e.blendEquationAlpha!==void 0&&(this.blendEquationAlpha=e.blendEquationAlpha),e.blendColor!==void 0&&this.blendColor!==void 0&&this.blendColor.setHex(e.blendColor),e.blendAlpha!==void 0&&(this.blendAlpha=e.blendAlpha),e.stencilWriteMask!==void 0&&(this.stencilWriteMask=e.stencilWriteMask),e.stencilFunc!==void 0&&(this.stencilFunc=e.stencilFunc),e.stencilRef!==void 0&&(this.stencilRef=e.stencilRef),e.stencilFuncMask!==void 0&&(this.stencilFuncMask=e.stencilFuncMask),e.stencilFail!==void 0&&(this.stencilFail=e.stencilFail),e.stencilZFail!==void 0&&(this.stencilZFail=e.stencilZFail),e.stencilZPass!==void 0&&(this.stencilZPass=e.stencilZPass),e.stencilWrite!==void 0&&(this.stencilWrite=e.stencilWrite),e.wireframe!==void 0&&(this.wireframe=e.wireframe),e.wireframeLinewidth!==void 0&&(this.wireframeLinewidth=e.wireframeLinewidth),e.wireframeLinecap!==void 0&&(this.wireframeLinecap=e.wireframeLinecap),e.wireframeLinejoin!==void 0&&(this.wireframeLinejoin=e.wireframeLinejoin),e.rotation!==void 0&&(this.rotation=e.rotation),e.linewidth!==void 0&&(this.linewidth=e.linewidth),e.linecap!==void 0&&(this.linecap=e.linecap),e.linejoin!==void 0&&(this.linejoin=e.linejoin),e.dashSize!==void 0&&(this.dashSize=e.dashSize),e.gapSize!==void 0&&(this.gapSize=e.gapSize),e.scale!==void 0&&(this.scale=e.scale),e.polygonOffset!==void 0&&(this.polygonOffset=e.polygonOffset),e.polygonOffsetFactor!==void 0&&(this.polygonOffsetFactor=e.polygonOffsetFactor),e.polygonOffsetUnits!==void 0&&(this.polygonOffsetUnits=e.polygonOffsetUnits),e.dithering!==void 0&&(this.dithering=e.dithering),e.alphaToCoverage!==void 0&&(this.alphaToCoverage=e.alphaToCoverage),e.premultipliedAlpha!==void 0&&(this.premultipliedAlpha=e.premultipliedAlpha),e.forceSinglePass!==void 0&&(this.forceSinglePass=e.forceSinglePass),e.allowOverride!==void 0&&(this.allowOverride=e.allowOverride),e.visible!==void 0&&(this.visible=e.visible),e.toneMapped!==void 0&&(this.toneMapped=e.toneMapped),e.userData!==void 0&&(this.userData=e.userData),e.vertexColors!==void 0&&(this.vertexColors=typeof e.vertexColors==`number`?e.vertexColors>0:e.vertexColors),e.size!==void 0&&(this.size=e.size),e.sizeAttenuation!==void 0&&(this.sizeAttenuation=e.sizeAttenuation),e.map!==void 0&&(this.map=t[e.map]||null),e.matcap!==void 0&&(this.matcap=t[e.matcap]||null),e.alphaMap!==void 0&&(this.alphaMap=t[e.alphaMap]||null),e.bumpMap!==void 0&&(this.bumpMap=t[e.bumpMap]||null),e.bumpScale!==void 0&&(this.bumpScale=e.bumpScale),e.normalMap!==void 0&&(this.normalMap=t[e.normalMap]||null),e.normalMapType!==void 0&&(this.normalMapType=e.normalMapType),e.normalScale!==void 0){let t=e.normalScale;Array.isArray(t)===!1&&(t=[t,t]),this.normalScale=new Sp().fromArray(t)}return e.displacementMap!==void 0&&(this.displacementMap=t[e.displacementMap]||null),e.displacementScale!==void 0&&(this.displacementScale=e.displacementScale),e.displacementBias!==void 0&&(this.displacementBias=e.displacementBias),e.roughnessMap!==void 0&&(this.roughnessMap=t[e.roughnessMap]||null),e.metalnessMap!==void 0&&(this.metalnessMap=t[e.metalnessMap]||null),e.emissiveMap!==void 0&&(this.emissiveMap=t[e.emissiveMap]||null),e.emissiveIntensity!==void 0&&(this.emissiveIntensity=e.emissiveIntensity),e.specularMap!==void 0&&(this.specularMap=t[e.specularMap]||null),e.specularIntensityMap!==void 0&&(this.specularIntensityMap=t[e.specularIntensityMap]||null),e.specularColorMap!==void 0&&(this.specularColorMap=t[e.specularColorMap]||null),e.envMap!==void 0&&(this.envMap=t[e.envMap]||null),e.envMapRotation!==void 0&&this.envMapRotation.fromArray(e.envMapRotation),e.envMapIntensity!==void 0&&(this.envMapIntensity=e.envMapIntensity),e.reflectivity!==void 0&&(this.reflectivity=e.reflectivity),e.refractionRatio!==void 0&&(this.refractionRatio=e.refractionRatio),e.lightMap!==void 0&&(this.lightMap=t[e.lightMap]||null),e.lightMapIntensity!==void 0&&(this.lightMapIntensity=e.lightMapIntensity),e.aoMap!==void 0&&(this.aoMap=t[e.aoMap]||null),e.aoMapIntensity!==void 0&&(this.aoMapIntensity=e.aoMapIntensity),e.gradientMap!==void 0&&(this.gradientMap=t[e.gradientMap]||null),e.clearcoatMap!==void 0&&(this.clearcoatMap=t[e.clearcoatMap]||null),e.clearcoatRoughnessMap!==void 0&&(this.clearcoatRoughnessMap=t[e.clearcoatRoughnessMap]||null),e.clearcoatNormalMap!==void 0&&(this.clearcoatNormalMap=t[e.clearcoatNormalMap]||null),e.clearcoatNormalScale!==void 0&&(this.clearcoatNormalScale=new Sp().fromArray(e.clearcoatNormalScale)),e.iridescenceMap!==void 0&&(this.iridescenceMap=t[e.iridescenceMap]||null),e.iridescenceThicknessMap!==void 0&&(this.iridescenceThicknessMap=t[e.iridescenceThicknessMap]||null),e.transmissionMap!==void 0&&(this.transmissionMap=t[e.transmissionMap]||null),e.thicknessMap!==void 0&&(this.thicknessMap=t[e.thicknessMap]||null),e.anisotropyMap!==void 0&&(this.anisotropyMap=t[e.anisotropyMap]||null),e.sheenColorMap!==void 0&&(this.sheenColorMap=t[e.sheenColorMap]||null),e.sheenRoughnessMap!==void 0&&(this.sheenRoughnessMap=t[e.sheenRoughnessMap]||null),this}clone(){return new this.constructor().copy(this)}copy(e){this.name=e.name,this.blending=e.blending,this.side=e.side,this.vertexColors=e.vertexColors,this.opacity=e.opacity,this.transparent=e.transparent,this.blendSrc=e.blendSrc,this.blendDst=e.blendDst,this.blendEquation=e.blendEquation,this.blendSrcAlpha=e.blendSrcAlpha,this.blendDstAlpha=e.blendDstAlpha,this.blendEquationAlpha=e.blendEquationAlpha,this.blendColor.copy(e.blendColor),this.blendAlpha=e.blendAlpha,this.depthFunc=e.depthFunc,this.depthTest=e.depthTest,this.depthWrite=e.depthWrite,this.stencilWriteMask=e.stencilWriteMask,this.stencilFunc=e.stencilFunc,this.stencilRef=e.stencilRef,this.stencilFuncMask=e.stencilFuncMask,this.stencilFail=e.stencilFail,this.stencilZFail=e.stencilZFail,this.stencilZPass=e.stencilZPass,this.stencilWrite=e.stencilWrite;let t=e.clippingPlanes,n=null;if(t!==null){let e=t.length;n=Array(e);for(let r=0;r!==e;++r)n[r]=t[r].clone()}return this.clippingPlanes=n,this.clipIntersection=e.clipIntersection,this.clipShadows=e.clipShadows,this.shadowSide=e.shadowSide,this.colorWrite=e.colorWrite,this.precision=e.precision,this.polygonOffset=e.polygonOffset,this.polygonOffsetFactor=e.polygonOffsetFactor,this.polygonOffsetUnits=e.polygonOffsetUnits,this.dithering=e.dithering,this.alphaTest=e.alphaTest,this.alphaHash=e.alphaHash,this.alphaToCoverage=e.alphaToCoverage,this.premultipliedAlpha=e.premultipliedAlpha,this.forceSinglePass=e.forceSinglePass,this.allowOverride=e.allowOverride,this.visible=e.visible,this.toneMapped=e.toneMapped,this.userData=JSON.parse(JSON.stringify(e.userData)),this}dispose(){this.dispatchEvent({type:`dispose`})}set needsUpdate(e){e===!0&&this.version++}},jh=new Q,Mh=new Q,Nh=new Q,Ph=new Q,Fh=class{constructor(e=new Q,t=new Q(0,0,-1)){this.origin=e,this.direction=t}set(e,t){return this.origin.copy(e),this.direction.copy(t),this}copy(e){return this.origin.copy(e.origin),this.direction.copy(e.direction),this}at(e,t){return t.copy(this.origin).addScaledVector(this.direction,e)}lookAt(e){return this.direction.copy(e).sub(this.origin).normalize(),this}recast(e){return this.origin.copy(this.at(e,jh)),this}closestPointToPoint(e,t){t.subVectors(e,this.origin);let n=t.dot(this.direction);return n<0?t.copy(this.origin):t.copy(this.origin).addScaledVector(this.direction,n)}distanceToPoint(e){return Math.sqrt(this.distanceSqToPoint(e))}distanceSqToPoint(e){let t=jh.subVectors(e,this.origin).dot(this.direction);return t<0?this.origin.distanceToSquared(e):(jh.copy(this.origin).addScaledVector(this.direction,t),jh.distanceToSquared(e))}distanceSqToSegment(e,t,n,r){Mh.copy(e).add(t).multiplyScalar(.5),Nh.copy(t).sub(e).normalize(),Ph.copy(this.origin).sub(Mh);let i=e.distanceTo(t)*.5,a=-this.direction.dot(Nh),o=Ph.dot(this.direction),s=-Ph.dot(Nh),c=Ph.lengthSq(),l=Math.abs(1-a*a),u,d,f,p;if(l>0){if(u=a*s-o,d=a*o-s,p=i*l,u>=0){if(d>=-p){if(d<=p){let e=1/l;u*=e,d*=e,f=u*(u+a*d+2*o)+d*(a*u+d+2*s)+c}else d=i,u=Math.max(0,-(a*d+o)),f=-u*u+d*(d+2*s)+c}else d=-i,u=Math.max(0,-(a*d+o)),f=-u*u+d*(d+2*s)+c}else d<=-p?(u=Math.max(0,-(-a*i+o)),d=u>0?-i:Math.min(Math.max(-i,-s),i),f=-u*u+d*(d+2*s)+c):d<=p?(u=0,d=Math.min(Math.max(-i,-s),i),f=d*(d+2*s)+c):(u=Math.max(0,-(a*i+o)),d=u>0?i:Math.min(Math.max(-i,-s),i),f=-u*u+d*(d+2*s)+c)}else d=a>0?-i:i,u=Math.max(0,-(a*d+o)),f=-u*u+d*(d+2*s)+c;return n&&n.copy(this.origin).addScaledVector(this.direction,u),r&&r.copy(Mh).addScaledVector(Nh,d),f}intersectSphere(e,t){if(e.radius<0)return null;jh.subVectors(e.center,this.origin);let n=jh.dot(this.direction),r=jh.dot(jh)-n*n,i=e.radius*e.radius;if(r>i)return null;let a=Math.sqrt(i-r),o=n-a,s=n+a;return s<0?null:o<0?this.at(s,t):this.at(o,t)}intersectsSphere(e){return e.radius<0?!1:this.distanceSqToPoint(e.center)<=e.radius*e.radius}distanceToPlane(e){let t=e.normal.dot(this.direction);if(t===0)return e.distanceToPoint(this.origin)===0?0:null;let n=-(this.origin.dot(e.normal)+e.constant)/t;return n>=0?n:null}intersectPlane(e,t){let n=this.distanceToPlane(e);return n===null?null:this.at(n,t)}intersectsPlane(e){let t=e.distanceToPoint(this.origin);return t===0||e.normal.dot(this.direction)*t<0}intersectBox(e,t){let n,r,i,a,o,s,c=1/this.direction.x,l=1/this.direction.y,u=1/this.direction.z,d=this.origin;return c>=0?(n=(e.min.x-d.x)*c,r=(e.max.x-d.x)*c):(n=(e.max.x-d.x)*c,r=(e.min.x-d.x)*c),l>=0?(i=(e.min.y-d.y)*l,a=(e.max.y-d.y)*l):(i=(e.max.y-d.y)*l,a=(e.min.y-d.y)*l),n>a||i>r||((i>n||isNaN(n))&&(n=i),(a<r||isNaN(r))&&(r=a),u>=0?(o=(e.min.z-d.z)*u,s=(e.max.z-d.z)*u):(o=(e.max.z-d.z)*u,s=(e.min.z-d.z)*u),n>s||o>r)||((o>n||n!==n)&&(n=o),(s<r||r!==r)&&(r=s),r<0)?null:this.at(n>=0?n:r,t)}intersectsBox(e){return this.intersectBox(e,jh)!==null}intersectTriangle(e,t,n,r,i){let a=this.origin,o=this.direction,s=o.x,c=o.y,l=o.z,u=e.x-a.x,d=e.y-a.y,f=e.z-a.z,p=t.x-a.x,m=t.y-a.y,h=t.z-a.z,g=n.x-a.x,_=n.y-a.y,v=n.z-a.z,y=Math.abs(s),b=Math.abs(c),x=Math.abs(l),S,C,w,T,E,D,O,k,A,j,ee,M;if(y>=b&&y>=x?(w=s,D=u,A=p,M=g,s>=0?(S=c,C=l,T=d,E=f,O=m,k=h,j=_,ee=v):(S=l,C=c,T=f,E=d,O=h,k=m,j=v,ee=_)):b>=x?(w=c,D=d,A=m,M=_,c>=0?(S=l,C=s,T=f,E=u,O=h,k=p,j=v,ee=g):(S=s,C=l,T=u,E=f,O=p,k=h,j=g,ee=v)):(w=l,D=f,A=h,M=v,l>=0?(S=s,C=c,T=u,E=d,O=p,k=m,j=g,ee=_):(S=c,C=s,T=d,E=u,O=m,k=p,j=_,ee=g)),w===0)return null;let N=S/w,P=C/w,F=1/w,I=T-N*D,te=E-P*D,ne=O-N*A,L=k-P*A,re=j-N*M,ie=ee-P*M,ae=re*L-ie*ne,oe=I*ie-te*re,se=ne*te-L*I;if(r){if(ae<0||oe<0||se<0)return null}else if((ae<0||oe<0||se<0)&&(ae>0||oe>0||se>0))return null;let ce=ae+oe+se;if(ce===0)return null;let le=F*(ae*D+oe*A+se*M);return(ce>0?le<0:le>0)?null:this.at(le/ce,i)}applyMatrix4(e){return this.origin.applyMatrix4(e),this.direction.transformDirection(e),this}equals(e){return e.origin.equals(this.origin)&&e.direction.equals(this.direction)}clone(){return new this.constructor().copy(this)}},Ih=class extends Ah{constructor(e){super(),this.isMeshBasicMaterial=!0,this.type=`MeshBasicMaterial`,this.color=new Om(16777215),this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.specularMap=null,this.alphaMap=null,this.envMap=null,this.envMapRotation=new rm,this.combine=0,this.reflectivity=1,this.refractionRatio=.98,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap=`round`,this.wireframeLinejoin=`round`,this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.color.copy(e.color),this.map=e.map,this.lightMap=e.lightMap,this.lightMapIntensity=e.lightMapIntensity,this.aoMap=e.aoMap,this.aoMapIntensity=e.aoMapIntensity,this.specularMap=e.specularMap,this.alphaMap=e.alphaMap,this.envMap=e.envMap,this.envMapRotation.copy(e.envMapRotation),this.combine=e.combine,this.reflectivity=e.reflectivity,this.refractionRatio=e.refractionRatio,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.wireframeLinecap=e.wireframeLinecap,this.wireframeLinejoin=e.wireframeLinejoin,this.fog=e.fog,this}},Lh=new qp,Rh=new Fh,zh=new gh,Bh=new Q,Vh=new Q,Hh=new Q,Uh=new Q,Wh=new Q,Gh=new Q,Kh=new Q,qh=new Q,Jh=class extends bm{constructor(e=new wh,t=new Ih){super(),this.isMesh=!0,this.type=`Mesh`,this.geometry=e,this.material=t,this.morphTargetDictionary=void 0,this.morphTargetInfluences=void 0,this.count=1,this.updateMorphTargets()}copy(e,t){return super.copy(e,t),e.morphTargetInfluences!==void 0&&(this.morphTargetInfluences=e.morphTargetInfluences.slice()),e.morphTargetDictionary!==void 0&&(this.morphTargetDictionary=Object.assign({},e.morphTargetDictionary)),this.material=Array.isArray(e.material)?e.material.slice():e.material,this.geometry=e.geometry,this}updateMorphTargets(){let e=this.geometry.morphAttributes,t=Object.keys(e);if(t.length>0){let n=e[t[0]];if(n!==void 0){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let e=0,t=n.length;e<t;e++){let t=n[e].name||String(e);this.morphTargetInfluences.push(0),this.morphTargetDictionary[t]=e}}}}getVertexPosition(e,t){let n=this.geometry,r=n.attributes.position,i=n.morphAttributes.position,a=n.morphTargetsRelative;t.fromBufferAttribute(r,e);let o=this.morphTargetInfluences;if(i&&o){Gh.set(0,0,0);for(let n=0,r=i.length;n<r;n++){let r=o[n],s=i[n];r!==0&&(Wh.fromBufferAttribute(s,e),a?Gh.addScaledVector(Wh,r):Gh.addScaledVector(Wh.sub(t),r))}t.add(Gh)}return t}intersectsFrustum(e){return e.intersectsObject(this)}raycast(e,t){let n=this.geometry,r=this.material,i=this.matrixWorld;r!==void 0&&(n.boundingSphere===null&&n.computeBoundingSphere(),zh.copy(n.boundingSphere),zh.applyMatrix4(i),Rh.copy(e.ray).recast(e.near),!(zh.containsPoint(Rh.origin)===!1&&(Rh.intersectSphere(zh,Bh)===null||Rh.origin.distanceToSquared(Bh)>(e.far-e.near)**2))&&(Lh.copy(i).invert(),Rh.copy(e.ray).applyMatrix4(Lh),(n.boundingBox===null||Rh.intersectsBox(n.boundingBox)!==!1)&&this._computeIntersections(e,t,Rh)))}_computeIntersections(e,t,n){let r,i=this.geometry,a=this.material,o=i.index,s=i.attributes.position,c=i.attributes.uv,l=i.attributes.uv1,u=i.attributes.normal,d=i.groups,f=i.drawRange;if(o!==null){if(Array.isArray(a))for(let i=0,s=d.length;i<s;i++){let s=d[i],p=a[s.materialIndex],m=Math.max(s.start,f.start),h=Math.min(o.count,Math.min(s.start+s.count,f.start+f.count));for(let i=m,a=h;i<a;i+=3){let a=o.getX(i),d=o.getX(i+1),f=o.getX(i+2);r=Xh(this,p,e,n,c,l,u,a,d,f),r&&(r.faceIndex=Math.floor(i/3),r.face.materialIndex=s.materialIndex,t.push(r))}}else{let i=Math.max(0,f.start),s=Math.min(o.count,f.start+f.count);for(let d=i,f=s;d<f;d+=3){let i=o.getX(d),s=o.getX(d+1),f=o.getX(d+2);r=Xh(this,a,e,n,c,l,u,i,s,f),r&&(r.faceIndex=Math.floor(d/3),t.push(r))}}}else if(s!==void 0){if(Array.isArray(a))for(let i=0,o=d.length;i<o;i++){let o=d[i],p=a[o.materialIndex],m=Math.max(o.start,f.start),h=Math.min(s.count,Math.min(o.start+o.count,f.start+f.count));for(let i=m,a=h;i<a;i+=3){let a=i,s=i+1,d=i+2;r=Xh(this,p,e,n,c,l,u,a,s,d),r&&(r.faceIndex=Math.floor(i/3),r.face.materialIndex=o.materialIndex,t.push(r))}}else{let i=Math.max(0,f.start),o=Math.min(s.count,f.start+f.count);for(let s=i,d=o;s<d;s+=3){let i=s,o=s+1,d=s+2;r=Xh(this,a,e,n,c,l,u,i,o,d),r&&(r.faceIndex=Math.floor(s/3),t.push(r))}}}}};function Yh(e,t,n,r,i,a,o,s){let c;if(c=t.side===1?r.intersectTriangle(o,a,i,!0,s):r.intersectTriangle(i,a,o,t.side===0,s),c===null)return null;qh.copy(s),qh.applyMatrix4(e.matrixWorld);let l=n.ray.origin.distanceTo(qh);return l<n.near||l>n.far?null:{distance:l,point:qh.clone(),object:e}}function Xh(e,t,n,r,i,a,o,s,c,l){e.getVertexPosition(s,Vh),e.getVertexPosition(c,Hh),e.getVertexPosition(l,Uh);let u=Yh(e,t,n,r,Vh,Hh,Uh,Kh);if(u){let e=new Q;Wm.getBarycoord(Kh,Vh,Hh,Uh,e),i&&(u.uv=Wm.getInterpolatedAttribute(i,s,c,l,e,new Sp)),a&&(u.uv1=Wm.getInterpolatedAttribute(a,s,c,l,e,new Sp)),o&&(u.normal=Wm.getInterpolatedAttribute(o,s,c,l,e,new Q),u.normal.dot(r.direction)>0&&u.normal.multiplyScalar(-1));let t={a:s,b:c,c:l,normal:new Q,materialIndex:0};Wm.getNormal(Vh,Hh,Uh,t.normal),u.face=t,u.barycoord=e}return u}var Zh=class extends Vp{constructor(e=null,t=1,n=1,r,i,a,o,s,c=kd,l=kd,u,d){super(null,a,o,s,c,l,r,i,u,d),this.isDataTexture=!0,this.image={data:e,width:t,height:n},this.generateMipmaps=!1,this.flipY=!1,this.unpackAlignment=1}},Qh=new gh,$h=new Sp(.5,.5),eg=new Q,tg=class{constructor(e=new Oh,t=new Oh,n=new Oh,r=new Oh,i=new Oh,a=new Oh){this.planes=[e,t,n,r,i,a]}set(e,t,n,r,i,a){let o=this.planes;return o[0].copy(e),o[1].copy(t),o[2].copy(n),o[3].copy(r),o[4].copy(i),o[5].copy(a),this}copy(e){let t=this.planes;for(let n=0;n<6;n++)t[n].copy(e.planes[n]);return this}setFromProjectionMatrix(e,t=tp,n=!1){let r=this.planes,i=e.elements,a=i[0],o=i[1],s=i[2],c=i[3],l=i[4],u=i[5],d=i[6],f=i[7],p=i[8],m=i[9],h=i[10],g=i[11],_=i[12],v=i[13],y=i[14],b=i[15];if(r[0].setComponents(c-a,f-l,g-p,b-_).normalize(),r[1].setComponents(c+a,f+l,g+p,b+_).normalize(),r[2].setComponents(c+o,f+u,g+m,b+v).normalize(),r[3].setComponents(c-o,f-u,g-m,b-v).normalize(),n)r[4].setComponents(s,d,h,y).normalize(),r[5].setComponents(c-s,f-d,g-h,b-y).normalize();else if(r[4].setComponents(c-s,f-d,g-h,b-y).normalize(),t===2e3)r[5].setComponents(c+s,f+d,g+h,b+y).normalize();else if(t===2001)r[5].setComponents(s,d,h,y).normalize();else throw Error(`THREE.Frustum.setFromProjectionMatrix(): Invalid coordinate system: `+t);return this}intersectsObject(e){if(e.boundingSphere!==void 0)e.boundingSphere===null&&e.computeBoundingSphere(),Qh.copy(e.boundingSphere).applyMatrix4(e.matrixWorld);else{let t=e.geometry;t.boundingSphere===null&&t.computeBoundingSphere(),Qh.copy(t.boundingSphere).applyMatrix4(e.matrixWorld)}return this.intersectsSphere(Qh)}intersectsSprite(e){return Qh.center.set(0,0,0),Qh.radius=.7071067811865476+$h.distanceTo(e.center),Qh.applyMatrix4(e.matrixWorld),this.intersectsSphere(Qh)}intersectsSphere(e){let t=this.planes,n=e.center,r=-e.radius;for(let e=0;e<6;e++)if(t[e].distanceToPoint(n)<r)return!1;return!0}intersectsBox(e){let t=this.planes;for(let n=0;n<6;n++){let r=t[n];if(eg.x=r.normal.x>0?e.max.x:e.min.x,eg.y=r.normal.y>0?e.max.y:e.min.y,eg.z=r.normal.z>0?e.max.z:e.min.z,r.distanceToPoint(eg)<0)return!1}return!0}containsPoint(e){let t=this.planes;for(let n=0;n<6;n++)if(t[n].distanceToPoint(e)<0)return!1;return!0}clone(){return new this.constructor().copy(this)}},ng=class extends Ah{constructor(e){super(),this.isPointsMaterial=!0,this.type=`PointsMaterial`,this.color=new Om(16777215),this.map=null,this.alphaMap=null,this.size=1,this.sizeAttenuation=!0,this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.color.copy(e.color),this.map=e.map,this.alphaMap=e.alphaMap,this.size=e.size,this.sizeAttenuation=e.sizeAttenuation,this.fog=e.fog,this}},rg=new qp,ig=new Fh,ag=new gh,og=new Q,sg=class extends bm{constructor(e=new wh,t=new ng){super(),this.isPoints=!0,this.type=`Points`,this.geometry=e,this.material=t,this.morphTargetDictionary=void 0,this.morphTargetInfluences=void 0,this.updateMorphTargets()}copy(e,t){return super.copy(e,t),this.material=Array.isArray(e.material)?e.material.slice():e.material,this.geometry=e.geometry,this}intersectsFrustum(e){return e.intersectsObject(this)}raycast(e,t){let n=this.geometry,r=this.matrixWorld,i=e.params.Points.threshold,a=n.drawRange;if(n.boundingSphere===null&&n.computeBoundingSphere(),ag.copy(n.boundingSphere),ag.applyMatrix4(r),ag.radius+=i,e.ray.intersectsSphere(ag)===!1)return;rg.copy(r).invert(),ig.copy(e.ray).applyMatrix4(rg);let o=i/((this.scale.x+this.scale.y+this.scale.z)/3),s=o*o,c=n.index,l=n.attributes.position;if(c!==null){let n=Math.max(0,a.start),i=Math.min(c.count,a.start+a.count);for(let a=n,o=i;a<o;a++){let n=c.getX(a);og.fromBufferAttribute(l,n),cg(og,n,s,r,e,t,this)}}else{let n=Math.max(0,a.start),i=Math.min(l.count,a.start+a.count);for(let a=n,o=i;a<o;a++)og.fromBufferAttribute(l,a),cg(og,a,s,r,e,t,this)}}updateMorphTargets(){let e=this.geometry.morphAttributes,t=Object.keys(e);if(t.length>0){let n=e[t[0]];if(n!==void 0){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let e=0,t=n.length;e<t;e++){let t=n[e].name||String(e);this.morphTargetInfluences.push(0),this.morphTargetDictionary[t]=e}}}}};function cg(e,t,n,r,i,a,o){let s=ig.distanceSqToPoint(e);if(s<n){let n=new Q;ig.closestPointToPoint(e,n),n.applyMatrix4(r);let c=i.ray.origin.distanceTo(n);if(c<i.near||c>i.far)return;a.push({distance:c,distanceToRay:Math.sqrt(s),point:n,index:t,face:null,faceIndex:null,barycoord:null,object:o})}}var lg=class extends Vp{constructor(e=[],t=301,n,r,i,a,o,s,c,l){super(e,t,n,r,i,a,o,s,c,l),this.isCubeTexture=!0,this.flipY=!1}get images(){return this.image}set images(e){this.image=e}},ug=class extends Vp{constructor(e,t,n=Bd,r,i,a,o=kd,s=kd,c,l=Zd,u=1){if(l!==1026&&l!==1027)throw Error(`THREE.DepthTexture: format must be either THREE.DepthFormat or THREE.DepthStencilFormat`);super({width:e,height:t,depth:u},r,i,a,o,s,l,n,c),this.isDepthTexture=!0,this.flipY=!1,this.generateMipmaps=!1,this.compareFunction=null}copy(e){return super.copy(e),this.source=new Lp(Object.assign({},e.image)),this.compareFunction=e.compareFunction,this}toJSON(e){let t=super.toJSON(e);return t.compareFunction=this.compareFunction,t}},dg=class extends ug{constructor(e,t=Bd,n=301,r,i,a=kd,o=kd,s,c=Zd){let l={width:e,height:e,depth:1},u=[l,l,l,l,l,l];super(e,e,t,n,r,i,a,o,s,c),this.image=u,this.isCubeDepthTexture=!0,this.isCubeTexture=!0}get images(){return this.image}set images(e){this.image=e}},fg=class extends Vp{constructor(e=null){super(),this.sourceTexture=e,this.isExternalTexture=!0}copy(e){return super.copy(e),this.sourceTexture=e.sourceTexture,this}},pg=class e extends wh{constructor(e=1,t=1,n=1,r=1,i=1,a=1){super(),this.type=`BoxGeometry`,this.parameters={width:e,height:t,depth:n,widthSegments:r,heightSegments:i,depthSegments:a};let o=this;r=Math.floor(r),i=Math.floor(i),a=Math.floor(a);let s=[],c=[],l=[],u=[],d=0,f=0;p(`z`,`y`,`x`,-1,-1,n,t,e,a,i,0),p(`z`,`y`,`x`,1,-1,n,t,-e,a,i,1),p(`x`,`z`,`y`,1,1,e,n,t,r,a,2),p(`x`,`z`,`y`,1,-1,e,n,-t,r,a,3),p(`x`,`y`,`z`,1,-1,e,t,n,r,i,4),p(`x`,`y`,`z`,-1,-1,e,t,-n,r,i,5),this.setIndex(s),this.setAttribute(`position`,new fh(c,3)),this.setAttribute(`normal`,new fh(l,3)),this.setAttribute(`uv`,new fh(u,2));function p(e,t,n,r,i,a,p,m,h,g,_){let v=a/h,y=p/g,b=a/2,x=p/2,S=m/2,C=h+1,w=g+1,T=0,E=0,D=new Q;for(let a=0;a<w;a++){let o=a*y-x;for(let s=0;s<C;s++)D[e]=(s*v-b)*r,D[t]=o*i,D[n]=S,c.push(D.x,D.y,D.z),D[e]=0,D[t]=0,D[n]=m>0?1:-1,l.push(D.x,D.y,D.z),u.push(s/h),u.push(1-a/g),T+=1}for(let e=0;e<g;e++)for(let t=0;t<h;t++){let n=d+t+C*e,r=d+t+C*(e+1),i=d+(t+1)+C*(e+1),a=d+(t+1)+C*e;s.push(n,r,a),s.push(r,i,a),E+=6}o.addGroup(f,E,_),f+=E,d+=T}}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}static fromJSON(t){return new e(t.width,t.height,t.depth,t.widthSegments,t.heightSegments,t.depthSegments)}},mg=class e extends wh{constructor(e=1,t=1,n=1,r=1){super(),this.type=`PlaneGeometry`,this.parameters={width:e,height:t,widthSegments:n,heightSegments:r};let i=e/2,a=t/2,o=Math.floor(n),s=Math.floor(r),c=o+1,l=s+1,u=e/o,d=t/s,f=[],p=[],m=[],h=[];for(let e=0;e<l;e++){let t=e*d-a;for(let n=0;n<c;n++){let r=n*u-i;p.push(r,-t,0),m.push(0,0,1),h.push(n/o),h.push(1-e/s)}}for(let e=0;e<s;e++)for(let t=0;t<o;t++){let n=t+c*e,r=t+c*(e+1),i=t+1+c*(e+1),a=t+1+c*e;f.push(n,r,a),f.push(r,i,a)}this.setIndex(f),this.setAttribute(`position`,new fh(p,3)),this.setAttribute(`normal`,new fh(m,3)),this.setAttribute(`uv`,new fh(h,2))}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}static fromJSON(t){return new e(t.width,t.height,t.widthSegments,t.heightSegments)}};function hg(e){let t={};for(let n in e){t[n]={};for(let r in e[n]){let i=e[n][r];if(_g(i))i.isRenderTargetTexture?(X(`UniformsUtils: Textures of render targets cannot be cloned via cloneUniforms() or mergeUniforms().`),t[n][r]=null):t[n][r]=i.clone();else if(Array.isArray(i)){if(_g(i[0])){let e=[];for(let t=0,n=i.length;t<n;t++)e[t]=i[t].clone();t[n][r]=e}else t[n][r]=i.slice()}else t[n][r]=i}}return t}function gg(e){let t={};for(let n=0;n<e.length;n++){let r=hg(e[n]);for(let e in r)t[e]=r[e]}return t}function _g(e){return e&&(e.isColor||e.isMatrix3||e.isMatrix4||e.isVector2||e.isVector3||e.isVector4||e.isTexture||e.isQuaternion)}function vg(e){let t=[];for(let n=0;n<e.length;n++)t.push(e[n].clone());return t}function yg(e){let t=e.getRenderTarget();return t===null?e.outputColorSpace:t.isXRRenderTarget===!0?t.texture.colorSpace:jp.workingColorSpace}var bg={clone:hg,merge:gg},xg=`void main() {
|
|
68
68
|
gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
|
|
69
69
|
}`,Sg=`void main() {
|
|
@@ -4452,5 +4452,5 @@ ${this.parser.parse(e)}</blockquote>
|
|
|
4452
4452
|
${e}</tr>
|
|
4453
4453
|
`}tablecell(e){let t=this.parser.parseInline(e.tokens),n=e.header?`th`:`td`;return(e.align?`<${n} align="${e.align}">`:`<${n}>`)+t+`</${n}>
|
|
4454
4454
|
`}strong({tokens:e}){return`<strong>${this.parser.parseInline(e)}</strong>`}em({tokens:e}){return`<em>${this.parser.parseInline(e)}</em>`}codespan({text:e}){return`<code>${Sw(e,!0)}</code>`}br(e){return`<br>`}del({tokens:e}){return`<del>${this.parser.parseInline(e)}</del>`}link({href:e,title:t,text:n,tokens:r,autolink:i}){let a=i?Sw(n,!0):this.parser.parseInline(r),o=ww(e);if(o===null)return a;e=Sw(o,i);let s=`<a href="`+e+`"`;return t&&(s+=` title="`+Sw(t)+`"`),s+=`>`+a+`</a>`,s}image({href:e,title:t,text:n,tokens:r}){r&&(n=this.parser.parseInline(r,this.parser.textRenderer));let i=ww(e);if(i===null)return Sw(n);e=i;let a=`<img src="${Sw(e)}" alt="${Sw(n)}"`;return t&&(a+=` title="${Sw(t)}"`),a+=`>`,a}text(e){return`tokens`in e&&e.tokens?this.parser.parseInline(e.tokens):`escaped`in e&&e.escaped?e.text:Sw(e.text)}},Lw=class{strong({text:e}){return e}em({text:e}){return e}codespan({text:e}){return e}del({text:e}){return e}html({text:e}){return e}text({text:e}){return e}link({text:e}){return``+e}image({text:e}){return``+e}br(){return``}checkbox({raw:e}){return e}},Rw=class e{options;renderer;textRenderer;constructor(e){this.options=e||QS,this.options.renderer=this.options.renderer||new Iw,this.renderer=this.options.renderer,this.renderer.options=this.options,this.renderer.parser=this,this.textRenderer=new Lw}static parse(t,n){return new e(n).parse(t)}static parseInline(t,n){return new e(n).parseInline(t)}parse(e){this.renderer.parser=this;let t=``;for(let n=0;n<e.length;n++){let r=e[n];if(this.options.extensions?.renderers?.[r.type]){let e=r,n=this.options.extensions.renderers[e.type].call({parser:this},e);if(n!==!1||![`space`,`hr`,`heading`,`code`,`table`,`blockquote`,`list`,`checkbox`,`html`,`def`,`paragraph`,`text`].includes(e.type)){t+=n||``;continue}}let i=r;switch(i.type){case`space`:t+=this.renderer.space(i);break;case`hr`:t+=this.renderer.hr(i);break;case`heading`:t+=this.renderer.heading(i);break;case`code`:t+=this.renderer.code(i);break;case`table`:t+=this.renderer.table(i);break;case`blockquote`:t+=this.renderer.blockquote(i);break;case`list`:t+=this.renderer.list(i);break;case`checkbox`:t+=this.renderer.checkbox(i);break;case`html`:t+=this.renderer.html(i);break;case`def`:t+=this.renderer.def(i);break;case`paragraph`:t+=this.renderer.paragraph(i);break;case`text`:t+=this.renderer.text(i);break;default:{let e=`Token with "`+i.type+`" type was not found.`;if(this.options.silent)return console.error(e),``;throw Error(e)}}}return t}parseInline(e,t=this.renderer){this.renderer.parser=this;let n=``;for(let r=0;r<e.length;r++){let i=e[r];if(this.options.extensions?.renderers?.[i.type]){let e=this.options.extensions.renderers[i.type].call({parser:this},i);if(e!==!1||![`escape`,`html`,`link`,`image`,`checkbox`,`strong`,`em`,`codespan`,`br`,`del`,`text`].includes(i.type)){n+=e||``;continue}}let a=i;switch(a.type){case`escape`:n+=t.text(a);break;case`html`:n+=t.html(a);break;case`link`:n+=t.link(a);break;case`image`:n+=t.image(a);break;case`checkbox`:n+=t.checkbox(a);break;case`strong`:n+=t.strong(a);break;case`em`:n+=t.em(a);break;case`codespan`:n+=t.codespan(a);break;case`br`:n+=t.br(a);break;case`del`:n+=t.del(a);break;case`text`:n+=t.text(a);break;default:{let e=`Token with "`+a.type+`" type was not found.`;if(this.options.silent)return console.error(e),``;throw Error(e)}}}return n}},zw=class{options;block;constructor(e){this.options=e||QS}static passThroughHooks=new Set([`preprocess`,`postprocess`,`processAllTokens`,`emStrongMask`]);static passThroughHooksRespectAsync=new Set([`preprocess`,`postprocess`,`processAllTokens`]);preprocess(e){return e}postprocess(e){return e}processAllTokens(e){return e}emStrongMask(e){return e}provideLexer(e=this.block){return e?Fw.lex:Fw.lexInline}provideParser(e=this.block){return e?Rw.parse:Rw.parseInline}},Bw=new class{defaults=ZS();options=this.setOptions;parse=this.parseMarkdown(!0);parseInline=this.parseMarkdown(!1);Parser=Rw;Renderer=Iw;TextRenderer=Lw;Lexer=Fw;Tokenizer=Pw;Hooks=zw;constructor(...e){this.use(...e)}walkTokens(e,t){let n=[];for(let r of e)switch(n=n.concat(t.call(this,r)),r.type){case`table`:{let e=r;for(let r of e.header)n=n.concat(this.walkTokens(r.tokens,t));for(let r of e.rows)for(let e of r)n=n.concat(this.walkTokens(e.tokens,t));break}case`list`:{let e=r;n=n.concat(this.walkTokens(e.items,t));break}default:{let e=r;this.defaults.extensions?.childTokens?.[e.type]?this.defaults.extensions.childTokens[e.type].forEach(r=>{let i=e[r].flat(1/0);n=n.concat(this.walkTokens(i,t))}):e.tokens&&(n=n.concat(this.walkTokens(e.tokens,t)))}}return n}use(...e){let t=this.defaults.extensions||{renderers:{},childTokens:{}};return e.forEach(e=>{let n={...e};if(n.async=this.defaults.async||n.async||!1,e.extensions&&(e.extensions.forEach(e=>{if(!e.name)throw Error(`extension name required`);if(`renderer`in e){let n=t.renderers[e.name];n?t.renderers[e.name]=function(...t){let r=e.renderer.apply(this,t);return r===!1&&(r=n.apply(this,t)),r}:t.renderers[e.name]=e.renderer}if(`tokenizer`in e){if(!e.level||e.level!==`block`&&e.level!==`inline`)throw Error(`extension level must be 'block' or 'inline'`);let n=t[e.level];n?n.unshift(e.tokenizer):t[e.level]=[e.tokenizer],e.start&&(e.level===`block`?t.startBlock?t.startBlock.push(e.start):t.startBlock=[e.start]:e.level===`inline`&&(t.startInline?t.startInline.push(e.start):t.startInline=[e.start]))}`childTokens`in e&&e.childTokens&&(t.childTokens[e.name]=e.childTokens)}),n.extensions=t),e.renderer){let t=this.defaults.renderer||new Iw(this.defaults);for(let n in e.renderer){if(!(n in t))throw Error(`renderer '${n}' does not exist`);if([`options`,`parser`].includes(n))continue;let r=n,i=e.renderer[r],a=t[r];t[r]=(...e)=>{let n=i.apply(t,e);return n===!1&&(n=a.apply(t,e)),n||``}}n.renderer=t}if(e.tokenizer){let t=this.defaults.tokenizer||new Pw(this.defaults);for(let n in e.tokenizer){if(!(n in t))throw Error(`tokenizer '${n}' does not exist`);if([`options`,`rules`,`lexer`].includes(n))continue;let r=n,i=e.tokenizer[r],a=t[r];t[r]=(...e)=>{let n=i.apply(t,e);return n===!1&&(n=a.apply(t,e)),n}}n.tokenizer=t}if(e.hooks){let t=this.defaults.hooks||new zw;for(let n in e.hooks){if(!(n in t))throw Error(`hook '${n}' does not exist`);if([`options`,`block`].includes(n))continue;let r=n,i=e.hooks[r],a=t[r];t[r]=zw.passThroughHooks.has(n)?e=>{if(this.defaults.async&&zw.passThroughHooksRespectAsync.has(n))return(async()=>{let n=await i.call(t,e);return a.call(t,n)})();let r=i.call(t,e);return a.call(t,r)}:(...e)=>{if(this.defaults.async)return(async()=>{let n=await i.apply(t,e);return n===!1&&(n=await a.apply(t,e)),n})();let n=i.apply(t,e);return n===!1&&(n=a.apply(t,e)),n}}n.hooks=t}if(e.walkTokens){let t=this.defaults.walkTokens,r=e.walkTokens;n.walkTokens=function(e){let n=[];return n.push(r.call(this,e)),t&&(n=n.concat(t.call(this,e))),n}}this.defaults={...this.defaults,...n}}),this}setOptions(e){return this.defaults={...this.defaults,...e},this}lexer(e,t){return Fw.lex(e,t??this.defaults)}parser(e,t){return Rw.parse(e,t??this.defaults)}parseMarkdown(e){return(t,n)=>{let r={...n},i={...this.defaults,...r},a=this.onError(!!i.silent,!!i.async);if(this.defaults.async===!0&&r.async===!1)return a(Error(`marked(): The async option was set to true by an extension. Remove async: false from the parse options object to return a Promise.`));if(typeof t>`u`||t===null)return a(Error(`marked(): input parameter is undefined or null`));if(typeof t!=`string`)return a(Error(`marked(): input parameter is of type `+Object.prototype.toString.call(t)+`, string expected`));if(i.hooks&&(i.hooks.options=i,i.hooks.block=e),i.async)return(async()=>{let n=i.hooks?await i.hooks.preprocess(t):t,r=await(i.hooks?await i.hooks.provideLexer(e):e?Fw.lex:Fw.lexInline)(n,i),a=i.hooks?await i.hooks.processAllTokens(r):r;i.walkTokens&&await Promise.all(this.walkTokens(a,i.walkTokens));let o=await(i.hooks?await i.hooks.provideParser(e):e?Rw.parse:Rw.parseInline)(a,i);return i.hooks?await i.hooks.postprocess(o):o})().catch(a);try{i.hooks&&(t=i.hooks.preprocess(t));let n=(i.hooks?i.hooks.provideLexer(e):e?Fw.lex:Fw.lexInline)(t,i);i.hooks&&(n=i.hooks.processAllTokens(n)),i.walkTokens&&this.walkTokens(n,i.walkTokens);let r=(i.hooks?i.hooks.provideParser(e):e?Rw.parse:Rw.parseInline)(n,i);return i.hooks&&(r=i.hooks.postprocess(r)),r}catch(e){return a(e)}}}onError(e,t){return n=>{if(n.message+=`
|
|
4455
|
-
Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error occurred:</p><pre>`+Sw(n.message+``,!0)+`</pre>`;return t?Promise.resolve(e):e}if(t)return Promise.reject(n);throw n}}};function Vw(e,t){return Bw.parse(e,t)}Vw.options=Vw.setOptions=function(e){return Bw.setOptions(e),Vw.defaults=Bw.defaults,$S(Vw.defaults),Vw},Vw.getDefaults=ZS,Vw.defaults=QS;function Hw(...e){return Bw.use(...e),Vw.defaults=Bw.defaults,$S(Vw.defaults),Vw}Vw.use=Hw,Vw.walkTokens=function(e,t){return Bw.walkTokens(e,t)},Vw.parseInline=Bw.parseInline,Vw.Parser=Rw,Vw.parser=Rw.parse,Vw.Renderer=Iw,Vw.TextRenderer=Lw,Vw.Lexer=Fw,Vw.lexer=Fw.lex,Vw.Tokenizer=Pw,Vw.Hooks=zw,Vw.parse=Vw,Vw.options,Vw.setOptions,Vw.walkTokens,Vw.parseInline,Rw.parse,Fw.lex;var Uw=!1;function Ww(){Uw||(Uw=!0,XS.addHook(`afterSanitizeAttributes`,e=>{e instanceof Element&&e.tagName===`A`&&(e.setAttribute(`rel`,`noopener noreferrer`),e.setAttribute(`target`,`_blank`))}))}function Gw(e){Ww();let t=Vw.parse(e,{async:!1,breaks:!0});return XS.sanitize(t,{ALLOWED_TAGS:[`p`,`br`,`strong`,`em`,`code`,`pre`,`ul`,`ol`,`li`,`a`,`h1`,`h2`,`h3`,`h4`,`h5`,`h6`,`blockquote`,`hr`,`del`,`table`,`thead`,`tbody`,`tr`,`th`,`td`],ALLOWED_ATTR:[`href`,`rel`,`target`],ALLOWED_URI_REGEXP:/^(?:https?:|mailto:)/i})}var Kw=e=>Number.isFinite(e);function qw(e){let t=Math.floor(Math.log10(e)),n=e/10**t;return(n<=1?1:n<=2?2:n<=2.5?2.5:n<=5?5:10)*10**t}function Jw(e,t,n=5){let r=Kw(e)?e:0,i=Kw(t)?t:r+1;r>i&&([r,i]=[i,r]),r===i&&(i=r+(Math.abs(r)||1));let a=qw((i-r)/Math.max(1,n-1)),o=Math.floor(r/a)*a,s=Math.ceil(i/a)*a,c=[];for(let e=o;e<=s+a/2;e+=a)c.push(Math.round(e*1e9)/1e9);return{min:o,max:s,ticks:c}}function Yw(e,t){let[n,r]=e,[i,a]=t;return r===n?()=>i:e=>i+(e-n)/(r-n)*(a-i)}function Xw(e){return e.map(([e,t],n)=>`${n===0?`M`:`L`}${e.toFixed(2)} ${t.toFixed(2)}`).join(` `)}function Zw(e,t,n,r,i){let a=r=>{let i=r*Math.PI/180;return`${(e+n*Math.cos(i)).toFixed(2)} ${(t+n*Math.sin(i)).toFixed(2)}`},o=+(Math.abs(i-r)>180);return`M ${a(r)} A ${n} ${n} 0 ${o} 1 ${a(i)}`}function Qw(e,t,n){return!Kw(e)||!Kw(t)||!Kw(n)||n<=t?0:Math.min(1,Math.max(0,(e-t)/(n-t)))*240}function $w(e,t,n,r){let i=t.x-e.x,a=t.y-e.y,o=Math.hypot(i,a);if(o===0||o<=n+r)return{from:{...e},to:{...t}};let s=i/o,c=a/o;return{from:{x:e.x+s*n,y:e.y+c*n},to:{x:t.x-s*r,y:t.y-c*r}}}function eT(e,t,n){if(e<=0)return[];if(e===1)return[{x:t/2,y:n/2}];let r=Math.min(t,n)*.36;return Array.from({length:e},(i,a)=>{let o=-Math.PI/2+a*2*Math.PI/e;return{x:t/2+r*Math.cos(o),y:n/2+r*Math.sin(o)}})}var tT=e=>typeof e==`object`&&!!e&&!Array.isArray(e),nT=e=>typeof e==`string`?e:typeof e==`number`?String(e):``,rT=e=>Array.isArray(e)?e:[],iT=e=>typeof e==`number`?Number.isFinite(e)?e:null:typeof e==`string`&&e.trim()!==``&&Number.isFinite(Number(e))?Number(e):null,aT=(e,t)=>e.length>t?e.slice(0,t)+`…`:e,oT=[`var(--accent)`,`#ffb454`,`#7b8cff`,`#5ef0b0`,`#ff6b7a`,`#c792ea`],sT=({text:e})=>e?(0,p.jsx)(`h3`,{className:`obj-title`,children:e}):null,cT=({text:e=`No data`})=>(0,p.jsx)(`p`,{className:`obj-empty`,children:e}),lT=400,uT=220,dT={l:44,r:12,t:10,b:28};function fT({props:e}){let t=e.kind===`bar`||e.kind===`area`?e.kind:`line`,n=rT(e.labels).slice(0,120).map(nT),r=rT(e.series).slice(0,6).map((e,t)=>{let n=tT(e)?e:{},r=rT(n.values).slice(0,120).map((e,t)=>({idx:t,v:iT(e)})).filter(e=>e.v!==null);return{name:nT(n.name)||`series ${t+1}`,points:r}}).filter(e=>e.points.length>0);if(r.length===0)return(0,p.jsxs)(p.Fragment,{children:[(0,p.jsx)(sT,{text:nT(e.title)}),(0,p.jsx)(cT,{})]});let i=r.flatMap(e=>e.points.map(e=>e.v)),a=Math.min(...i),o=Math.max(...i),s=Jw(t===`line`?a:Math.min(0,a),t===`line`?o:Math.max(0,o),5),c=Math.max(n.length,...r.map(e=>e.points[e.points.length-1].idx+1),2),l=Yw([s.min,s.max],[uT-dT.b,dT.t]),u=Yw([0,c-1],[dT.l,lT-dT.r]),d=(lT-dT.l-dT.r)/c,f=Math.max(1,d*.7/r.length),m=(e,t)=>dT.l+e*d+d*.15+t*f,h=Math.max(1,Math.ceil(c/6)),g=nT(e.unit);return(0,p.jsxs)(p.Fragment,{children:[(0,p.jsx)(sT,{text:nT(e.title)}),(0,p.jsxs)(`svg`,{className:`obj-chart`,viewBox:`0 0 ${lT} ${uT}`,role:`img`,"aria-label":nT(e.title)||`chart`,children:[s.ticks.map(e=>(0,p.jsxs)(`g`,{children:[(0,p.jsx)(`line`,{className:`grid`,x1:dT.l,x2:lT-dT.r,y1:l(e),y2:l(e)}),(0,p.jsxs)(`text`,{className:`tick`,x:dT.l-6,y:l(e)+3,textAnchor:`end`,children:[e,g&&e===s.max?g:``]})]},e)),Array.from({length:c},(e,t)=>t).filter(e=>e%h===0&&n[e]).map(e=>(0,p.jsx)(`text`,{className:`tick`,x:t===`bar`?m(e,0)+f*r.length/2:u(e),y:212,textAnchor:`middle`,children:aT(n[e],8)},e)),r.map((e,n)=>{let r=oT[n%oT.length];if(t===`bar`)return(0,p.jsx)(`g`,{children:e.points.map(e=>(0,p.jsx)(`rect`,{className:`bar`,x:m(e.idx,n),y:Math.min(l(e.v),l(0)),width:f,height:Math.abs(l(e.v)-l(0)),fill:r},e.idx))},n);let i=e.points.map(e=>[u(e.idx),l(e.v)]),a=Xw(i),o=`${a} L${i[i.length-1][0].toFixed(2)} ${l(s.min).toFixed(2)} L${i[0][0].toFixed(2)} ${l(s.min).toFixed(2)} Z`;return(0,p.jsxs)(`g`,{children:[t===`area`&&(0,p.jsx)(`path`,{className:`series-area`,d:o,fill:r,opacity:.18}),(0,p.jsx)(`path`,{className:`series-line`,d:a,fill:`none`,stroke:r,strokeWidth:2,strokeLinejoin:`round`})]},n)})]}),r.length>1&&(0,p.jsx)(`ul`,{className:`legend`,children:r.map((e,t)=>(0,p.jsxs)(`li`,{children:[(0,p.jsx)(`i`,{style:{background:oT[t%oT.length]}}),(0,p.jsx)(`span`,{children:e.name})]},t))})]})}function pT({props:e}){let t=iT(e.min)??0,n=iT(e.max)??100,r=iT(e.value)??t,i=Qw(r,t,n),a=i/240;return(0,p.jsxs)(`div`,{className:`obj-gauge ${a>.95?`gauge-crit`:a>.8?`gauge-warn`:``}`,children:[(0,p.jsxs)(`svg`,{viewBox:`0 0 200 150`,role:`img`,"aria-label":`${nT(e.label)} ${r}`,children:[(0,p.jsx)(`path`,{className:`track`,d:Zw(100,100,70,150,390),fill:`none`,strokeWidth:12,strokeLinecap:`round`}),i>0&&(0,p.jsx)(`path`,{className:`value`,d:Zw(100,100,70,150,150+i),fill:`none`,strokeWidth:12,strokeLinecap:`round`})]}),(0,p.jsxs)(`div`,{className:`gauge-read`,children:[(0,p.jsx)(`span`,{className:`gauge-value`,children:String(Math.round(r*100)/100)}),nT(e.unit)&&(0,p.jsx)(`small`,{className:`gauge-unit`,children:nT(e.unit)})]}),(0,p.jsx)(`span`,{className:`obj-label`,children:nT(e.label)})]})}function mT({props:e}){let t=rT(e.items).slice(0,30).map(e=>tT(e)?e:{}).map(e=>({time:nT(e.time),title:nT(e.title),detail:nT(e.detail)})).filter(e=>e.title||e.time);return t.length===0?(0,p.jsxs)(p.Fragment,{children:[(0,p.jsx)(sT,{text:nT(e.title)}),(0,p.jsx)(cT,{text:`Nothing to show`})]}):(0,p.jsxs)(p.Fragment,{children:[(0,p.jsx)(sT,{text:nT(e.title)}),(0,p.jsx)(`ol`,{className:`obj-timeline`,children:t.map((e,t)=>(0,p.jsxs)(`li`,{children:[(0,p.jsx)(`time`,{children:e.time}),(0,p.jsx)(`strong`,{children:e.title}),e.detail&&(0,p.jsx)(`span`,{children:e.detail})]},t))})]})}var hT=400,gT=300,_T=12;function vT({props:e}){let t=(0,l.useId)(),n=new Set,r=[];for(let t of rT(e.nodes)){let e=tT(t)?t:{},i=nT(e.id);if(i&&!n.has(i)&&(n.add(i),r.push({id:i,label:nT(e.label)||i}),r.length>=40))break}if(r.length===0)return(0,p.jsxs)(p.Fragment,{children:[(0,p.jsx)(sT,{text:nT(e.title)}),(0,p.jsx)(cT,{text:`Nothing to show`})]});let i=new Map(r.map((e,t)=>[e.id,eT(r.length,hT,gT)[t]])),a=[];for(let t of rT(e.edges)){let e=tT(t)?t:{},n=nT(e.from),r=nT(e.to);if(i.has(n)&&i.has(r)&&n!==r&&(a.push({from:n,to:r,label:nT(e.label)}),a.length>=80))break}return(0,p.jsxs)(p.Fragment,{children:[(0,p.jsx)(sT,{text:nT(e.title)}),(0,p.jsxs)(`svg`,{className:`obj-graph`,viewBox:`0 0 ${hT} ${gT}`,role:`img`,"aria-label":nT(e.title)||`graph`,children:[(0,p.jsx)(`defs`,{children:(0,p.jsx)(`marker`,{id:t,viewBox:`0 0 10 10`,refX:`9`,refY:`5`,markerWidth:`6`,markerHeight:`6`,orient:`auto-start-reverse`,children:(0,p.jsx)(`path`,{d:`M0 0 L10 5 L0 10 z`,className:`arrow`})})}),a.map((e,n)=>{let{from:r,to:a}=$w(i.get(e.from),i.get(e.to),14,17),o=(r.x+a.x)/2+(hT/2-(r.x+a.x)/2)*.25,s=(r.y+a.y)/2+(gT/2-(r.y+a.y)/2)*.25;return(0,p.jsxs)(`g`,{children:[(0,p.jsx)(`path`,{className:`edge`,d:`M ${r.x.toFixed(1)} ${r.y.toFixed(1)} Q ${o.toFixed(1)} ${s.toFixed(1)} ${a.x.toFixed(1)} ${a.y.toFixed(1)}`,fill:`none`,markerEnd:`url(#${t})`}),e.label&&(0,p.jsx)(`text`,{className:`edge-label`,x:o,y:s,textAnchor:`middle`,children:aT(e.label,12)})]},n)}),r.map(e=>{let t=i.get(e.id);return(0,p.jsxs)(`g`,{children:[(0,p.jsx)(`circle`,{className:`node`,cx:t.x,cy:t.y,r:_T}),(0,p.jsx)(`text`,{className:`node-label`,x:t.x,y:t.y+26,textAnchor:`middle`,children:aT(e.label,18)})]},e.id)})]})]})}var yT=e=>typeof e==`string`?e:typeof e==`number`?String(e):``,bT=e=>Array.isArray(e)?e:[],xT=e=>typeof e==`object`&&e?e:{},ST=/^\/api\/media\/[0-9a-f]{32}$/,CT=e=>typeof e==`string`&&ST.test(e)?e:null,wT=/^\/api\/video\/[0-9a-f]{32}$/,TT=e=>typeof e==`string`&&wT.test(e)?e:null,ET=({props:e})=>yT(e.title)?(0,p.jsx)(`h3`,{className:`obj-title`,children:yT(e.title)}):null;function DT({props:e}){let t=(0,l.useMemo)(()=>Gw(yT(e.text)),[e.text]);return(0,p.jsxs)(p.Fragment,{children:[(0,p.jsx)(ET,{props:e}),(0,p.jsx)(`div`,{className:`obj-md obj-doc`,dangerouslySetInnerHTML:{__html:t}})]})}function OT({props:e}){let t=Math.min(100,Math.max(0,Number(e.value)||0));return(0,p.jsxs)(`div`,{className:`obj-progress`,children:[(0,p.jsxs)(`div`,{className:`obj-progress-head`,children:[(0,p.jsx)(`span`,{className:`obj-label`,children:yT(e.label)}),(0,p.jsxs)(`span`,{className:`obj-progress-pct`,children:[Math.round(t),`%`]})]}),(0,p.jsx)(`div`,{className:`obj-progress-bar`,role:`progressbar`,"aria-valuemin":0,"aria-valuemax":100,"aria-valuenow":Math.round(t),"aria-label":yT(e.label)||`Progress`,children:(0,p.jsx)(`i`,{style:{width:`${t}%`}})}),yT(e.detail)&&(0,p.jsx)(`span`,{className:`obj-progress-detail`,children:yT(e.detail)})]})}function kT({props:e}){let t=bT(e.items).map(e=>xT(typeof e==`object`&&e?e:{text:e})),n=t.filter(e=>e.done===!0).length;return(0,p.jsxs)(p.Fragment,{children:[(0,p.jsx)(ET,{props:e}),(0,p.jsx)(`ul`,{className:`obj-checklist`,children:t.map((e,t)=>(0,p.jsxs)(`li`,{className:e.done===!0?`done`:void 0,children:[(0,p.jsx)(`span`,{className:`box`,"aria-hidden":`true`,children:e.done===!0?`✓`:``}),(0,p.jsx)(`span`,{children:yT(e.text)})]},t))}),t.length>0&&(0,p.jsxs)(`small`,{className:`obj-progress-detail`,children:[n,` of `,t.length,` done`]})]})}function AT({props:e}){return(0,p.jsxs)(p.Fragment,{children:[(0,p.jsx)(ET,{props:e}),(0,p.jsx)(`dl`,{className:`obj-kv`,children:bT(e.rows).map((e,t)=>{let n=xT(e);return(0,p.jsxs)(`div`,{children:[(0,p.jsx)(`dt`,{children:yT(n.key)}),(0,p.jsx)(`dd`,{children:yT(n.value)})]},t)})})]})}var jT=e=>String(Math.floor(e)).padStart(2,`0`);function MT(e){let t=Math.max(0,Math.ceil(e));return`${jT(t/3600)}:${jT(t%3600/60)}:${jT(t%60)}`}function NT({props:e}){let t=(0,l.useRef)(null);if(t.current===null){let n=typeof e.to==`string`?Date.parse(e.to):NaN,r=Number(e.seconds);t.current=Number.isFinite(n)?n:Date.now()+(Number.isFinite(r)?r:0)*1e3}let[n,r]=(0,l.useState)(Date.now());(0,l.useEffect)(()=>{let e=setInterval(()=>r(Date.now()),250);return()=>clearInterval(e)},[]);let i=(t.current-n)/1e3;return(0,p.jsxs)(`div`,{className:`obj-countdown${i<=0?` done`:``}`,children:[(0,p.jsx)(`span`,{className:`obj-label`,children:yT(e.title)||yT(e.label)}),(0,p.jsx)(`span`,{className:`obj-countdown-time`,role:`timer`,children:MT(i)})]})}function PT({props:e}){let t=CT(e.src);return(0,p.jsxs)(`div`,{className:`obj-media`,children:[(0,p.jsx)(ET,{props:e}),t?(0,p.jsx)(`img`,{src:t,alt:yT(e.title)||`Picture`,loading:`lazy`}):(0,p.jsx)(`p`,{className:`obj-empty`,children:`This picture is not available.`})]})}function FT({src:e,web:t,title:n}){let[r,i]=(0,l.useState)(t?`loading`:`ready`);return r===`failed`?(0,p.jsx)(`p`,{className:`obj-empty`,children:`This video could not be played. Ask Friend to try again, or to play it in a window on the PC.`}):(0,p.jsxs)(p.Fragment,{children:[(0,p.jsx)(`video`,{src:e,controls:!0,playsInline:!0,autoPlay:t,preload:t?`auto`:`metadata`,"aria-label":n,onLoadedData:()=>i(`ready`),onError:()=>i(`failed`)}),t&&r===`loading`&&(0,p.jsx)(`p`,{className:`obj-empty`,children:`Preparing the video…`})]})}function IT({props:e}){let t=TT(e.src),n=t??CT(e.src);return(0,p.jsxs)(`div`,{className:`obj-media`,children:[(0,p.jsx)(ET,{props:e}),n?(0,p.jsx)(FT,{src:n,web:t!==null,title:yT(e.title)||`Video`},n):(0,p.jsx)(`p`,{className:`obj-empty`,children:`This clip is not available.`})]})}function LT({props:e}){let t=CT(e.src);return(0,p.jsxs)(`div`,{className:`obj-media obj-pdf`,children:[(0,p.jsx)(ET,{props:e}),t?(0,p.jsxs)(p.Fragment,{children:[(0,p.jsx)(`iframe`,{src:t,title:yT(e.title)||`Document`}),(0,p.jsx)(`a`,{className:`obj-open`,href:t,target:`_blank`,rel:`noopener noreferrer`,children:`Open in a new tab`})]}):(0,p.jsx)(`p`,{className:`obj-empty`,children:`This document is not available.`})]})}function RT({props:e}){let t=bT(e.items).map(xT).filter(e=>CT(e.src)),[n,r]=(0,l.useState)(0),i=Math.min(n,Math.max(0,t.length-1)),a=t[i];if(!a)return(0,p.jsx)(`p`,{className:`obj-empty`,children:`Nothing to show.`});let o=CT(a.src),s=a.kind===`video`;return(0,p.jsxs)(`div`,{className:`obj-media obj-gallery`,children:[(0,p.jsx)(ET,{props:e}),s?(0,p.jsx)(`video`,{src:o,controls:!0,playsInline:!0,preload:`metadata`},o):(0,p.jsx)(`img`,{src:o,alt:yT(a.caption)||`Picture ${i+1}`},o),(0,p.jsxs)(`div`,{className:`obj-gallery-bar`,children:[(0,p.jsx)(`button`,{type:`button`,"aria-label":`Previous`,disabled:t.length<2,onClick:()=>r((i+t.length-1)%t.length),children:`‹`}),(0,p.jsxs)(`span`,{children:[yT(a.caption),(0,p.jsxs)(`small`,{children:[i+1,` / `,t.length]})]}),(0,p.jsx)(`button`,{type:`button`,"aria-label":`Next`,disabled:t.length<2,onClick:()=>r((i+1)%t.length),children:`›`})]})]})}var zT=[`default-src 'none'`,`script-src 'unsafe-inline'`,`style-src 'unsafe-inline'`,`img-src data: blob:`,`form-action 'none'`,`base-uri 'none'`].join(`; `),BT=`html,body{margin:0;min-height:100%;background:#050b10;color:var(--ink,#d8f6ff);font:15px/1.5 var(--ui,system-ui,sans-serif)}`,VT=[`--accent`,`--ink`,`--muted`,`--ok`,`--warn`,`--bad`,`--glass`,`--edge`,`--ui`,`--mono`],HT=/^[\w\s#().,%'"/-]+$/;function UT(){if(typeof document>`u`)return``;let e=getComputedStyle(document.documentElement),t=VT.map(t=>[t,e.getPropertyValue(t).trim()]).filter(([,e])=>e&&HT.test(e));return t.length?`:root{${t.map(([e,t])=>`${e}:${t}`).join(`;`)}}`:``}function WT(e,t=``){return`<!doctype html><html><head><meta charset="utf-8"><meta http-equiv="Content-Security-Policy" content="${zT}"><meta name="viewport" content="width=device-width,initial-scale=1"><style>${t}${BT}</style></head><body>${e}</body></html>`}function GT({props:e}){let t=typeof e.html==`string`?e.html:``,n=typeof e.title==`string`?e.title:``,r=(0,l.useMemo)(()=>WT(t,UT()),[t]);return(0,p.jsxs)(`div`,{className:`obj-sandbox`,children:[n&&(0,p.jsx)(`h3`,{className:`obj-title`,children:n}),(0,p.jsx)(`iframe`,{title:n||`Page made by Friend`,sandbox:`allow-scripts`,referrerPolicy:`no-referrer`,allow:``,srcDoc:r})]})}var KT=e=>typeof e==`string`?e:typeof e==`number`?String(e):``,qT=e=>Array.isArray(e)?e:[];function JT({props:e}){let t=(0,l.useMemo)(()=>Gw(KT(e.text)),[e.text]);return(0,p.jsxs)(p.Fragment,{children:[KT(e.title)&&(0,p.jsx)(`h3`,{className:`obj-title`,children:KT(e.title)}),(0,p.jsx)(`div`,{className:`obj-md`,dangerouslySetInnerHTML:{__html:t}})]})}function YT({props:e}){return(0,p.jsxs)(`div`,{className:`obj-stat`,children:[(0,p.jsx)(`span`,{className:`obj-label`,children:KT(e.label)}),(0,p.jsxs)(`span`,{className:`obj-value`,children:[(0,p.jsx)(`span`,{children:KT(e.value)}),KT(e.unit)&&(0,p.jsx)(`small`,{children:KT(e.unit)})]}),KT(e.delta)&&(0,p.jsx)(`span`,{className:`obj-delta`,children:KT(e.delta)})]})}function XT({props:e}){return(0,p.jsxs)(p.Fragment,{children:[KT(e.title)&&(0,p.jsx)(`h3`,{className:`obj-title`,children:KT(e.title)}),(0,p.jsx)(`ul`,{className:`obj-list`,children:qT(e.items).map((e,t)=>{let n=typeof e==`object`&&e?e:{text:e};return(0,p.jsx)(`li`,{className:n.done?`done`:void 0,children:KT(n.text)},t)})})]})}function ZT({props:e}){let t=qT(e.columns),n=qT(e.rows);return(0,p.jsxs)(p.Fragment,{children:[KT(e.title)&&(0,p.jsx)(`h3`,{className:`obj-title`,children:KT(e.title)}),(0,p.jsx)(`div`,{className:`obj-table-wrap`,children:(0,p.jsxs)(`table`,{className:`obj-table`,children:[(0,p.jsx)(`thead`,{children:(0,p.jsx)(`tr`,{children:t.map((e,t)=>(0,p.jsx)(`th`,{children:KT(e)},t))})}),(0,p.jsx)(`tbody`,{children:n.map((e,t)=>(0,p.jsx)(`tr`,{children:qT(e).map((e,t)=>(0,p.jsx)(`td`,{children:KT(e)},t))},t))})]})})]})}function QT({props:e}){return(0,p.jsxs)(p.Fragment,{children:[KT(e.title)&&(0,p.jsx)(`h3`,{className:`obj-title`,children:KT(e.title)}),(0,p.jsx)(`pre`,{className:`obj-code`,"data-lang":KT(e.language),children:(0,p.jsx)(`code`,{children:KT(e.code)})})]})}function $T({part:e}){let t=typeof e==`object`&&e?e:{},n=typeof t.type==`string`?t.type:``;if(n===`group`||n===`tabs`||n===`sandbox`)return null;let r=nE[n];return r?(0,p.jsx)(`div`,{className:`obj-part obj-part-${n}`,children:(0,p.jsx)(r,{props:typeof t.props==`object`&&t.props!==null?t.props:{}})}):null}function eE({props:e}){let t=e.layout===`row`||e.layout===`column`?e.layout:`grid`;return(0,p.jsxs)(p.Fragment,{children:[KT(e.title)&&(0,p.jsx)(`h3`,{className:`obj-title`,children:KT(e.title)}),(0,p.jsx)(`div`,{className:`obj-group obj-group-${t}`,children:qT(e.items).map((e,t)=>(0,p.jsx)($T,{part:e},t))})]})}function tE({props:e}){let t=qT(e.tabs).map(e=>typeof e==`object`&&e?e:{}),[n,r]=(0,l.useState)(0),i=Math.min(n,Math.max(0,t.length-1));return(0,p.jsxs)(p.Fragment,{children:[KT(e.title)&&(0,p.jsx)(`h3`,{className:`obj-title`,children:KT(e.title)}),(0,p.jsx)(`div`,{className:`obj-tabs`,role:`tablist`,children:t.map((e,t)=>(0,p.jsx)(`button`,{type:`button`,role:`tab`,"aria-selected":t===i,className:t===i?`on`:void 0,onClick:()=>r(t),children:KT(e.title)||`Tab ${t+1}`},t))}),t[i]&&(0,p.jsx)($T,{part:t[i]})]})}var nE={card:JT,stat:YT,list:XT,table:ZT,code:QT,chart:fT,gauge:pT,timeline:mT,graph:vT,sandbox:GT,markdown:DT,image:PT,video:IT,pdf:LT,gallery:RT,group:eE,tabs:tE,progress:OT,checklist:kT,countdown:NT,kv:AT};function rE(e,t){let n=new Map(t.map(e=>[e.id,e])),r=[],i=new Set;for(let t of e){if(i.has(t.object.id))continue;i.add(t.object.id);let e=n.get(t.object.id);r.push(e?{object:e,leaving:!1}:{object:t.object,leaving:!0})}for(let e of t)i.has(e.id)||(i.add(e.id),r.push({object:e,leaving:!1}));return r}function iE(e,t){let[n,r]=(0,l.useState)(()=>e.map(e=>({object:e,leaving:!1}))),i=(0,l.useRef)(new Map);return(0,l.useEffect)(()=>{r(n=>{let a=rE(n,e),o=new Set(n.filter(e=>e.leaving).map(e=>e.object.id));for(let e of a){let n=i.current.get(e.object.id);if(!e.leaving)n&&clearTimeout(n),i.current.delete(e.object.id);else if(!o.has(e.object.id)&&!n){let n=e.object.id;i.current.set(n,setTimeout(()=>{i.current.delete(n),r(e=>e.filter(e=>!(e.object.id===n&&e.leaving)))},Math.max(t,0)))}}return t<=0?a.filter(e=>!e.leaving):a})},[e,t]),(0,l.useEffect)(()=>()=>{for(let e of i.current.values())clearTimeout(e);i.current.clear()},[]),n}var aE=.12,oE=.1,sE=.02,cE=(e,t,n)=>Math.min(Math.max(e,t),n);function lE(e){let t=cE(e.w,aE,1),n=cE(e.h,oE,1);return{x:cE(e.x,0,1-t),y:cE(e.y,0,1-n),w:t,h:n}}function uE(e,t){let n=t.getBoundingClientRect(),r=e.getBoundingClientRect();return n.width<=0||n.height<=0?null:lE({x:(r.left-n.left)/n.width,y:(r.top-n.top)/n.height,w:r.width/n.width,h:r.height/n.height})}function dE(e,t,n){let r=(0,l.useRef)(null),[i,a]=(0,l.useState)(null),o=(0,l.useCallback)((n,r)=>{let i=lE(r);t({type:`object.place`,id:n,placement:{x:i.x,y:i.y,w:i.w,h:i.h}}),e({type:`stage.move`,objectId:n,rect:i})},[e,t]),s=(0,l.useCallback)((e,t,i)=>{if(e.pointerType===`mouse`&&e.button!==0)return;let o=n(),s=e.currentTarget.closest(`[data-object]`);if(!o||!s||r.current)return;let c=uE(s,o);if(!c)return;let l=o.getBoundingClientRect();r.current={id:t.id,mode:i,pointer:e.pointerId,startX:e.clientX,startY:e.clientY,from:c,stageW:l.width,stageH:l.height};try{e.currentTarget.setPointerCapture(e.pointerId)}catch{}e.stopPropagation(),e.preventDefault(),a({id:t.id,box:c})},[n]),c=(e,t)=>{let n=(t.clientX-e.startX)/e.stageW,r=(t.clientY-e.startY)/e.stageH;return e.mode===`move`?lE({...e.from,x:e.from.x+n,y:e.from.y+r}):lE({...e.from,w:e.from.w+n,h:e.from.h+r})};return{preview:i,begin:s,move:(0,l.useCallback)(e=>{let t=r.current;t&&t.pointer===e.pointerId&&a({id:t.id,box:c(t,e)})},[]),end:(0,l.useCallback)((e,t)=>{let n=r.current;n&&n.pointer===e.pointerId&&(r.current=null,a(null),t||o(n.id,c(n,e)))},[o]),key:(0,l.useCallback)((e,t)=>{let r={ArrowLeft:[-.02,0],ArrowRight:[sE,0],ArrowUp:[0,-.02],ArrowDown:[0,sE]}[e.key],i=n(),a=e.currentTarget.closest(`[data-object]`);if(!r||!i||!a)return;let s=uE(a,i);s&&(e.preventDefault(),o(t.id,e.shiftKey?{...s,w:s.w+r[0],h:s.h+r[1]}:{...s,x:s.x+r[0],y:s.y+r[1]}))},[o,n])}}function fE(e,t){if(e===`auto`)return{position:`relative`};if(t.w<600)return{position:`relative`,width:`100%`};let[n,r,i,a]=typeof e==`string`?Nl[e]:[e.x*100,e.y*100,e.w*100,e.h*100],o={position:`absolute`,left:`${n}%`,top:`${r}%`,width:`${i}%`};return e===`top`||e===`bottom`?{...o,maxHeight:`${a}%`}:{...o,height:`${a}%`}}var pE=350,mE=()=>typeof matchMedia==`function`&&matchMedia(`(prefers-reduced-motion: reduce)`).matches,hE=class extends l.Component{state={failed:!1};static getDerivedStateFromError(){return{failed:!0}}render(){return this.state.failed?null:this.props.children}};function gE(){let e=()=>({w:window.innerWidth,h:window.innerHeight}),[t,n]=(0,l.useState)(e);return(0,l.useEffect)(()=>{let t=()=>n(e());return window.addEventListener(`resize`,t),()=>window.removeEventListener(`resize`,t)},[]),t}var _E=350;function vE({state:e,send:t,dispatch:n,voice:r,slash:i,onMenu:a}){let o=gE(),[s,c]=(0,l.useState)(0),[u,d]=(0,l.useState)(!1),f=ne(),m=o.w<600,h=e.scene===`focus`||e.scene===`multi`,g={"--accent":e.mood.accent,"--intensity":e.mood.intensity},_=e.voice.mode,v=_===`listening`?`listening`:_===`speaking`?`speaking`:_===`transcribing`?`thinking`:e.presence.state,y=Qb(e.look.reactivity),b=Math.min(1,(_===`listening`||_===`speaking`?e.voice.level:e.presence.amplitude)*y),x=(0,l.useRef)({timer:null,down:!1,talking:!1,id:null}),S=e=>{if(!(e.target===e.currentTarget||e.target.closest(`[data-presence]`))||e.pointerType===`mouse`&&e.button!==0)return;let t=x.current;if(!(t.down&&t.id!==null&&e.pointerId!==t.id)){t.timer&&clearTimeout(t.timer),t.down=!0,t.talking=!1,t.id=typeof e.pointerId==`number`?e.pointerId:null;try{t.id!==null&&e.currentTarget.setPointerCapture?.(t.id)}catch{}t.timer=r?setTimeout(()=>{t.down&&(t.talking=!0,r.pressStart())},_E):null}},C=(e,t)=>{let n=x.current;n.down&&(n.id===null||typeof e.pointerId!=`number`||e.pointerId===n.id)&&(n.down=!1,n.id=null,n.timer&&clearTimeout(n.timer),n.timer=null,n.talking?(n.talking=!1,t?r?.blur?.():r?.pressEnd()):t||c(e=>e+1))},w=(0,l.useRef)(null),T=dE(t,n,()=>w.current),E=iE(e.objects,mE()?0:pE),D=E.filter(e=>e.object.layer===`overlay`),O=E.filter(e=>e.object.layer!==`overlay`&&e.object.placement===`auto`),k=E.filter(e=>e.object.layer!==`overlay`&&e.object.placement!==`auto`),A=({object:e,leaving:r})=>{let i=nE[e.type];if(!i)return null;let a=e.layer===`overlay`,s=!m&&!r&&!a,c=T.preview?.id===e.id?T.preview.box:null,l=c?{x:c.x,y:c.y,w:c.w,h:c.h}:e.placement;return(0,p.jsxs)(`section`,{"data-object":e.id,className:`obj glass${e.style===`alert`?` alert`:``}${a?` overlay`:``}${e.pinned?` pinned`:``}${c?` dragging`:``}${r?` leaving`:``}`,style:a?void 0:fE(l,o),children:[s&&(0,p.jsx)(`div`,{className:`obj-grip`,role:`button`,tabIndex:0,"aria-label":`Move ${e.id}. Drag, or use the arrow keys; hold Shift to resize.`,onPointerDown:t=>T.begin(t,e,`move`),onPointerMove:T.move,onPointerUp:e=>T.end(e,!1),onPointerCancel:e=>T.end(e,!0),onKeyDown:t=>T.key(t,e)}),!a&&(0,p.jsx)(`button`,{className:`obj-pin${e.pinned?` on`:``}`,"aria-label":e.pinned?`Unpin ${e.id}`:`Pin ${e.id} to the screen`,"aria-pressed":!!e.pinned,title:e.pinned?`Pinned: stays on the screen. Click to unpin.`:`Pin: keep this on the screen.`,disabled:r,onClick:()=>t({type:`stage.pin`,objectId:e.id,pinned:!e.pinned}),children:(0,p.jsx)(`svg`,{width:`14`,height:`14`,viewBox:`0 0 24 24`,fill:e.pinned?`currentColor`:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,"aria-hidden":`true`,children:(0,p.jsx)(`path`,{d:`M12 17v5M9 3h6l-1 7 3 3H7l3-3-1-7z`})})}),(0,p.jsx)(`button`,{className:`obj-close`,"aria-label":`Dismiss ${e.id}`,title:e.pinned?`Remove this widget`:`Dismiss`,disabled:r,onClick:()=>{t({type:`stage.event`,objectId:e.id,event:`dismiss`}),n({type:`object.dismiss`,id:e.id})},children:`×`}),s&&(0,p.jsx)(`div`,{className:`obj-resize`,"aria-hidden":`true`,onPointerDown:t=>T.begin(t,e,`resize`),onPointerMove:T.move,onPointerUp:e=>T.end(e,!1),onPointerCancel:e=>T.end(e,!0)}),(0,p.jsx)(hE,{children:(0,p.jsx)(i,{props:e.props})})]},e.id)};return(0,p.jsxs)(`div`,{ref:w,"data-testid":`stage`,className:`stage`,style:g,onPointerDown:S,onPointerUp:e=>C(e,!1),onPointerCancel:e=>C(e,!0),onContextMenu:e=>r&&e.preventDefault(),children:[e.look.ambient&&(0,p.jsx)(`div`,{className:`ambient`,"aria-hidden":`true`,style:{opacity:.35+.65*e.mood.intensity}}),(0,p.jsx)(Zb,{state:v,amplitude:b,pulse:e.presence.pulse,mode:h?`corner`:`full`,accent:e.mood.accent,style:e.presence.style,intensity:e.mood.intensity,scale:e.look.size}),(0,p.jsxs)(`div`,{className:m?`objects objects-stack`:`objects`,style:{zIndex:10},children:[O.length>0&&(0,p.jsx)(`div`,{className:`auto-grid`,children:O.map(A)}),k.map(A)]}),D.length>0&&(0,p.jsxs)(`div`,{className:`overlay-layer`,"data-testid":`overlay`,children:[(0,p.jsx)(`div`,{className:`overlay-backdrop`,onClick:()=>D.forEach(({object:e})=>{t({type:`stage.event`,objectId:e.id,event:`dismiss`}),n({type:`object.dismiss`,id:e.id})})}),D.map(A)]}),e.look.captions&&e.captions&&(0,p.jsx)(`p`,{className:`captions captions-${e.look.captionSize}${e.captionDone?` done`:``}`,"aria-live":`polite`,children:e.captions}),f&&r&&!u&&(0,p.jsx)(xx,{voice:r,mode:_,onType:()=>c(e=>e+1),onMenu:()=>a?.()}),(0,p.jsx)(vx,{requestOpen:s,slash:i,onOpenChange:d,onSend:e=>t({type:`chat.send`,text:e})})]})}function yE(){let e=()=>Math.random().toString(36).slice(2,12)+Date.now().toString(36);try{let t=sessionStorage.getItem(`friend.tab`);return t||(t=e(),sessionStorage.setItem(`friend.tab`,t)),t}catch{return e()}}function bE(){return`${location.protocol===`https:`?`wss`:`ws`}://${location.host}/ws`}function xE(e=bE()){let t=null,n=`connecting`,r=!1,i=0,a=!1,o=yE(),s=null,c=new Set,l=new Set,u=e=>{n=e,l.forEach(t=>t(e))};function d(){if(r)return;u(`connecting`);let n=new WebSocket(`${e}${e.includes(`?`)?`&`:`?`}tab=${o}${a?`&takeover=1`:``}`);t=n,n.onopen=()=>{i=0,a=!1,u(`open`)},n.onmessage=e=>{try{let t=JSON.parse(String(e.data));c.forEach(e=>e(t))}catch{}},n.onclose=e=>{if(!r){if(e.code===4401)return u(`unauthorized`);if(e.code===4409||e.code===4410)return u(`elsewhere`);u(`closed`),s=setTimeout(d,Math.min(500*2**i++,8e3))}},n.onerror=()=>{}}return d(),{send(e){t?.readyState===WebSocket.OPEN&&t.send(JSON.stringify(e))},onMessage(e){return c.add(e),()=>c.delete(e)},onState(e){return l.add(e),()=>l.delete(e)},state:()=>n,takeOver(){r||n!==`elsewhere`||(a=!0,i=0,d())},close(){r=!0,s&&clearTimeout(s),t?.close()}}}var SE={scene:`conversation`,objects:[],captions:``,captionDone:!0,presence:{state:`idle`,style:`sphere`,amplitude:0,pulse:0},mood:{accent:`#3fd8ff`,intensity:.6},approval:null,alerts:[],connection:`connecting`,chat:[],chatLive:!1,view:`companion`,look:{size:1,reactivity:.7,ambient:!0,captions:!0,captionSize:`medium`},viewKnown:!1,busy:!1,activity:null,deviceOnline:!1,voice:{mode:`idle`,level:0,available:!1,enrolled:!1},challenge:null,camera:{enabled:!1,stream:null},speaker:null,ownerName:``,assistantName:``,hud:null,music:null,hostMusic:null,musicCmd:null,uiOpen:null},CE=200,wE=e=>e.length>CE?e.slice(-200):e,TE=0,EE=e=>Math.min(1,Math.max(0,e));function DE(e,t){switch(t.cmd){case`scene`:return{...e,scene:t.mode};case`show`:{let n=e.objects.findIndex(e=>e.id===t.object.id),r=n===-1?[...e.objects,t.object]:e.objects.map((e,r)=>r===n?t.object:e);return{...e,objects:r}}case`update`:return{...e,objects:e.objects.map(e=>e.id===t.id?{...e,props:{...e.props,...t.props}}:e)};case`hide`:return{...e,objects:e.objects.filter(e=>e.id!==t.id)};case`clear`:return{...e,objects:e.objects.filter(e=>e.pinned),scene:`conversation`};case`pin`:return{...e,objects:e.objects.map(e=>e.id===t.id?{...e,pinned:!0}:e)};case`unpin`:return{...e,objects:e.objects.map(e=>e.id===t.id?(({pinned:e,...t})=>t)(e):e)};case`place`:return{...e,objects:e.objects.map(e=>e.id===t.id?{...e,placement:t.placement}:e)};case`presence`:return{...e,presence:{...e.presence,state:t.state??e.presence.state,style:t.style??e.presence.style}};case`mood`:return{...e,mood:{accent:t.accent??e.mood.accent,intensity:t.intensity??e.mood.intensity}}}}function OE(e,t){let n=t;if(n&&typeof n==`object`){if(n.type===`conn`)return{...e,connection:n.value};if(n.type===`chat.seed`){let t=Array.isArray(n.lines)?n.lines:[];return e.chat.length===0?{...e,chat:wE(t)}:{...e,chat:wE([...t,...e.chat])}}if(n.type===`alert.add`)return{...e,alerts:[...e.alerts.slice(-3),{id:++TE,level:n.level,text:n.text}]};if(n.type===`camera.enable`)return{...e,camera:{enabled:n.value,stream:n.value?e.camera.stream:null}};if(n.type===`camera.open`)return{...e,camera:{...e.camera,stream:n.stream}};if(n.type===`camera.closed`)return{...e,camera:{...e.camera,stream:null}};if(n.type===`challenge.dismiss`)return e.challenge?.id===n.id?{...e,challenge:null}:e;if(n.type===`voice.mode`)return{...e,voice:{...e.voice,mode:n.mode,level:n.mode===`idle`?0:e.voice.level}};if(n.type===`voice.level`){let t=Number.isFinite(n.level)?Math.min(1,Math.max(0,n.level)):0;return{...e,voice:{...e.voice,level:t}}}if(n.type===`object.dismiss`)return{...e,objects:e.objects.filter(e=>e.id!==n.id)};if(n.type===`object.place`)return{...e,objects:e.objects.map(e=>e.id===n.id?{...e,placement:n.placement}:e)};if(n.type===`alert.dismiss`)return{...e,alerts:e.alerts.filter(e=>e.id!==n.id)}}let r=eu.safeParse(t);if(!r.success)return e;let i=r.data;switch(i.type){case`snapshot`:return{...e,scene:i.stage.scene,objects:i.stage.objects,presence:{...e.presence,state:i.stage.presence.state,style:i.stage.presence.style},mood:i.stage.mood,approval:i.pendingApproval??null};case`stage`:return DE(e,i.command);case`chat.user`:return{...e,chat:wE([...e.chat,{role:`user`,text:i.text}]),chatLive:!1};case`ui.open`:return{...e,uiOpen:{n:(e.uiOpen?.n??0)+1,...i.integration?{integration:i.integration}:{}}};case`ui`:return{...e,view:i.view,look:i.look??e.look,ownerName:i.ownerName??e.ownerName,assistantName:i.assistantName??e.assistantName,hud:i.hud??e.hud,music:i.music??e.music,viewKnown:!0};case`music.host`:return{...e,hostMusic:i.state};case`music.command`:{let{type:t,...n}=i;return{...e,musicCmd:{n:(e.musicCmd?.n??0)+1,command:n}}}case`caption.delta`:{let t=e.captionDone,n=e.chat.at(-1),r=e.chatLive&&n?.role===`assistant`?[...e.chat.slice(0,-1),{role:`assistant`,text:n.text+i.text}]:wE([...e.chat,{role:`assistant`,text:i.text}]);return{...e,chat:r,chatLive:!0,captions:(t?``:e.captions)+i.text,captionDone:!1,presence:{...e.presence,amplitude:EE(.3+i.text.length*.04),pulse:e.presence.pulse+1}}}case`caption.end`:return{...e,chatLive:!1,captionDone:!0,presence:{...e.presence,amplitude:0}};case`approval.request`:{let{type:t,...n}=i;return{...e,approval:n}}case`approval.resolved`:return e.approval?.id===i.id?{...e,approval:null}:e;case`alert`:return{...e,alerts:[...e.alerts.slice(-3),{id:++TE,level:i.level,text:i.text}]};case`activity`:return{...e,activity:i.text};case`status`:return{...e,busy:i.busy,activity:i.busy?e.activity:null,deviceOnline:i.deviceOnline,voice:{...e.voice,available:i.voiceAvailable??e.voice.available,enrolled:i.voiceEnrolled??e.voice.enrolled}};case`error`:return{...e,alerts:[...e.alerts.slice(-3),{id:++TE,level:`error`,text:i.message}]};case`voice.heard`:return{...e,captions:i.trust===`guest`?`Guest: ${i.text}`:i.trust===`member`&&i.speaker?`${i.speaker}: ${i.text}`:i.text,captionDone:!0,speaker:{name:i.trust===`member`?i.speaker??null:null,trust:i.trust??`unverified`,seq:(e.speaker?.seq??0)+1}};case`voice.challenge`:return{...e,challenge:{id:i.id,text:i.text}};case`voice.challenge.end`:return e.challenge?.id===i.id?{...e,challenge:null}:e;case`audio.chunk`:case`audio.stop`:return e;case`camera.request`:case`camera.cancel`:case`screen.request`:case`screen.cancel`:return e}}var kE=1024,AE=.8,jE=300;function ME(e,t){let n=Math.min(1,kE/Math.max(e,t));return{width:Math.round(e*n),height:Math.round(t*n)}}function NE(e){let t=e?.name;return t===`NotAllowedError`||t===`SecurityError`?`permission`:t===`NotFoundError`||t===`OverconstrainedError`?`no-camera`:`busy`}async function PE(){if(!navigator.mediaDevices?.getUserMedia)throw Object.assign(Error(`This browser cannot use the camera here (use localhost or HTTPS).`),{name:`NotFoundError`});return navigator.mediaDevices.getUserMedia({video:{width:{ideal:1280}},audio:!1})}async function FE(e,t=jE){let n=document.createElement(`video`);n.muted=!0,n.playsInline=!0,n.srcObject=e,await n.play(),await new Promise(e=>setTimeout(e,t));let{width:r,height:i}=ME(n.videoWidth||640,n.videoHeight||480),a=document.createElement(`canvas`);return a.width=r,a.height=i,a.getContext(`2d`).drawImage(n,0,0,r,i),n.srcObject=null,new Promise((e,t)=>a.toBlob(n=>n?e(n):t(Error(`Could not encode the picture.`)),`image/jpeg`,AE))}var IE=class{opts;active=null;constructor(e){this.opts=e}async handle(e){if(e.type===`camera.cancel`){let t=this.active;t&&t.id===e.id&&(t.cancelled=!0,this.release(t));return}if(!this.opts.enabled())return this.opts.send({type:`camera.denied`,id:e.id,reason:`off`});if(this.active)return this.opts.send({type:`camera.denied`,id:e.id,reason:`busy`});let t={id:e.id,cancelled:!1,stream:null,opened:!1,released:!1};this.active=t;try{let n=await(this.opts.open??PE)();if(t.stream=n,t.cancelled){n.getTracks().forEach(e=>e.stop());return}t.opened=!0,this.opts.dispatch({type:`camera.open`,stream:n});let r=await(this.opts.frame??(e=>FE(e)))(n);if(t.cancelled)return;this.release(t);try{await this.opts.upload(e.id,r)}catch{this.opts.dispatch({type:`alert.add`,level:`warn`,text:`Could not send the camera picture to Friend.`})}}catch(n){t.cancelled||this.opts.send({type:`camera.denied`,id:e.id,reason:NE(n)})}finally{this.release(t),this.active===t&&(this.active=null)}}dispose(){let e=this.active;e&&(e.cancelled=!0,this.release(e))}release(e){e.released||(e.released=!0,e.stream?.getTracks().forEach(e=>e.stop()),e.opened&&this.opts.dispatch({type:`camera.closed`}))}};function LE(e,t){if(e.match(/^[a-z]+:\/\//i))return e;if(e.match(/^\/\//))return window.location.protocol+e;if(e.match(/^[a-z]+:/i))return e;let n=document.implementation.createHTMLDocument(),r=n.createElement(`base`),i=n.createElement(`a`);return n.head.appendChild(r),n.body.appendChild(i),t&&(r.href=t),i.href=e,i.href}var RE=(()=>{let e=0,t=()=>`0000${(Math.random()*36**4<<0).toString(36)}`.slice(-4);return()=>(e+=1,`u${t()}${e}`)})();function zE(e){let t=[];for(let n=0,r=e.length;n<r;n++)t.push(e[n]);return t}var BE=null;function VE(e={}){return BE||(e.includeStyleProperties?(BE=e.includeStyleProperties,BE):(BE=zE(window.getComputedStyle(document.documentElement)),BE))}function HE(e,t){let n=(e.ownerDocument.defaultView||window).getComputedStyle(e).getPropertyValue(t);return n?parseFloat(n.replace(`px`,``)):0}function UE(e){let t=HE(e,`border-left-width`),n=HE(e,`border-right-width`);return e.clientWidth+t+n}function WE(e){let t=HE(e,`border-top-width`),n=HE(e,`border-bottom-width`);return e.clientHeight+t+n}function GE(e,t={}){return{width:t.width||UE(e),height:t.height||WE(e)}}function KE(){let e,t;try{t=process}catch{}let n=t&&t.env?t.env.devicePixelRatio:null;return n&&(e=parseInt(n,10),Number.isNaN(e)&&(e=1)),e||window.devicePixelRatio||1}var qE=16384;function JE(e){(e.width>qE||e.height>qE)&&(e.width>qE&&e.height>qE?e.width>e.height?(e.height*=qE/e.width,e.width=qE):(e.width*=qE/e.height,e.height=qE):e.width>qE?(e.height*=qE/e.width,e.width=qE):(e.width*=qE/e.height,e.height=qE))}function YE(e){return new Promise((t,n)=>{let r=new Image;r.onload=()=>{r.decode().then(()=>{requestAnimationFrame(()=>t(r))})},r.onerror=n,r.crossOrigin=`anonymous`,r.decoding=`async`,r.src=e})}async function XE(e){return Promise.resolve().then(()=>new XMLSerializer().serializeToString(e)).then(encodeURIComponent).then(e=>`data:image/svg+xml;charset=utf-8,${e}`)}async function ZE(e,t,n){let r=`http://www.w3.org/2000/svg`,i=document.createElementNS(r,`svg`),a=document.createElementNS(r,`foreignObject`);return i.setAttribute(`width`,`${t}`),i.setAttribute(`height`,`${n}`),i.setAttribute(`viewBox`,`0 0 ${t} ${n}`),a.setAttribute(`width`,`100%`),a.setAttribute(`height`,`100%`),a.setAttribute(`x`,`0`),a.setAttribute(`y`,`0`),a.setAttribute(`externalResourcesRequired`,`true`),i.appendChild(a),a.appendChild(e),XE(i)}var QE=(e,t)=>{if(e instanceof t)return!0;let n=Object.getPrototypeOf(e);return n===null?!1:n.constructor.name===t.name||QE(n,t)};function $E(e){let t=e.getPropertyValue(`content`);return`${e.cssText} content: '${t.replace(/'|"/g,``)}';`}function eD(e,t){return VE(t).map(t=>`${t}: ${e.getPropertyValue(t)}${e.getPropertyPriority(t)?` !important`:``};`).join(` `)}function tD(e,t,n,r){let i=`.${e}:${t}`,a=n.cssText?$E(n):eD(n,r);return document.createTextNode(`${i}{${a}}`)}function nD(e,t,n,r){let i=window.getComputedStyle(e,n),a=i.getPropertyValue(`content`);if(a===``||a===`none`)return;let o=RE();try{t.className=`${t.className} ${o}`}catch{return}let s=document.createElement(`style`);s.appendChild(tD(o,n,i,r)),t.appendChild(s)}function rD(e,t,n){nD(e,t,`:before`,n),nD(e,t,`:after`,n)}var iD=`application/font-woff`,aD=`image/jpeg`,oD={woff:iD,woff2:iD,ttf:`application/font-truetype`,eot:`application/vnd.ms-fontobject`,png:`image/png`,jpg:aD,jpeg:aD,gif:`image/gif`,tiff:`image/tiff`,svg:`image/svg+xml`,webp:`image/webp`};function sD(e){let t=/\.([^./]*?)$/g.exec(e);return t?t[1]:``}function cD(e){return oD[sD(e).toLowerCase()]||``}function lD(e){return e.split(/,/)[1]}function uD(e){return e.search(/^(data:)/)!==-1}function dD(e,t){return`data:${t};base64,${e}`}async function fD(e,t,n){let r=await fetch(e,t);if(r.status===404)throw Error(`Resource "${r.url}" not found`);let i=await r.blob();return new Promise((e,t)=>{let a=new FileReader;a.onerror=t,a.onloadend=()=>{try{e(n({res:r,result:a.result}))}catch(e){t(e)}},a.readAsDataURL(i)})}var pD={};function mD(e,t,n){let r=e.replace(/\?.*/,``);return n&&(r=e),/ttf|otf|eot|woff2?/i.test(r)&&(r=r.replace(/.*\//,``)),t?`[${t}]${r}`:r}async function hD(e,t,n){let r=mD(e,t,n.includeQueryParams);if(pD[r]!=null)return pD[r];n.cacheBust&&(e+=(/\?/.test(e)?`&`:`?`)+new Date().getTime());let i;try{i=dD(await fD(e,n.fetchRequestInit,({res:e,result:n})=>(t||=e.headers.get(`Content-Type`)||``,lD(n))),t)}catch(t){i=n.imagePlaceholder||``;let r=`Failed to fetch resource: ${e}`;t&&(r=typeof t==`string`?t:t.message),r&&console.warn(r)}return pD[r]=i,i}async function gD(e){let t=e.toDataURL();return t===`data:,`?e.cloneNode(!1):YE(t)}async function _D(e,t){if(e.currentSrc){let t=document.createElement(`canvas`),n=t.getContext(`2d`);return t.width=e.clientWidth,t.height=e.clientHeight,n?.drawImage(e,0,0,t.width,t.height),YE(t.toDataURL())}let n=e.poster;return YE(await hD(n,cD(n),t))}async function vD(e,t){try{if(e?.contentDocument?.body)return await OD(e.contentDocument.body,t,!0)}catch{}return e.cloneNode(!1)}async function yD(e,t){return QE(e,HTMLCanvasElement)?gD(e):QE(e,HTMLVideoElement)?_D(e,t):QE(e,HTMLIFrameElement)?vD(e,t):e.cloneNode(xD(e))}var bD=e=>e.tagName!=null&&e.tagName.toUpperCase()===`SLOT`,xD=e=>e.tagName!=null&&e.tagName.toUpperCase()===`SVG`;async function SD(e,t,n){if(xD(t))return t;let r=[];return r=bD(e)&&e.assignedNodes?zE(e.assignedNodes()):QE(e,HTMLIFrameElement)&&e.contentDocument?.body?zE(e.contentDocument.body.childNodes):zE((e.shadowRoot??e).childNodes),r.length===0||QE(e,HTMLVideoElement)||await r.reduce((e,r)=>e.then(()=>OD(r,n)).then(e=>{e&&t.appendChild(e)}),Promise.resolve()),t}function CD(e,t,n){let r=t.style;if(!r)return;let i=window.getComputedStyle(e);i.cssText?(r.cssText=i.cssText,r.transformOrigin=i.transformOrigin):VE(n).forEach(n=>{let a=i.getPropertyValue(n);n===`font-size`&&a.endsWith(`px`)&&(a=`${Math.floor(parseFloat(a.substring(0,a.length-2)))-.1}px`),QE(e,HTMLIFrameElement)&&n===`display`&&a===`inline`&&(a=`block`),n===`d`&&t.getAttribute(`d`)&&(a=`path(${t.getAttribute(`d`)})`),r.setProperty(n,a,i.getPropertyPriority(n))})}function wD(e,t){QE(e,HTMLTextAreaElement)&&(t.innerHTML=e.value),QE(e,HTMLInputElement)&&t.setAttribute(`value`,e.value)}function TD(e,t){if(QE(e,HTMLSelectElement)){let n=t,r=Array.from(n.children).find(t=>e.value===t.getAttribute(`value`));r&&r.setAttribute(`selected`,``)}}function ED(e,t,n){return QE(t,Element)&&(CD(e,t,n),rD(e,t,n),wD(e,t),TD(e,t)),t}async function DD(e,t){let n=e.querySelectorAll?e.querySelectorAll(`use`):[];if(n.length===0)return e;let r={};for(let i=0;i<n.length;i++){let a=n[i].getAttribute(`xlink:href`);if(a){let n=e.querySelector(a),i=document.querySelector(a);!n&&i&&!r[a]&&(r[a]=await OD(i,t,!0))}}let i=Object.values(r);if(i.length){let t=`http://www.w3.org/1999/xhtml`,n=document.createElementNS(t,`svg`);n.setAttribute(`xmlns`,t),n.style.position=`absolute`,n.style.width=`0`,n.style.height=`0`,n.style.overflow=`hidden`,n.style.display=`none`;let r=document.createElementNS(t,`defs`);n.appendChild(r);for(let e=0;e<i.length;e++)r.appendChild(i[e]);e.appendChild(n)}return e}async function OD(e,t,n){return!n&&t.filter&&!t.filter(e)?null:Promise.resolve(e).then(e=>yD(e,t)).then(n=>SD(e,n,t)).then(n=>ED(e,n,t)).then(e=>DD(e,t))}var kD=/url\((['"]?)([^'"]+?)\1\)/g,AD=/url\([^)]+\)\s*format\((["']?)([^"']+)\1\)/g,jD=/src:\s*(?:url\([^)]+\)\s*format\([^)]+\)[,;]\s*)+/g;function MD(e){let t=e.replace(/([.*+?^${}()|\[\]\/\\])/g,`\\$1`);return RegExp(`(url\\(['"]?)(${t})(['"]?\\))`,`g`)}function ND(e){let t=[];return e.replace(kD,(e,n,r)=>(t.push(r),e)),t.filter(e=>!uD(e))}async function PD(e,t,n,r,i){try{let a=n?LE(t,n):t,o=cD(t),s;return s=i?dD(await i(a),o):await hD(a,o,r),e.replace(MD(t),`$1${s}$3`)}catch{}return e}function FD(e,{preferredFontFormat:t}){return t?e.replace(jD,e=>{for(;;){let[n,,r]=AD.exec(e)||[];if(!r)return``;if(r===t)return`src: ${n};`}}):e}function ID(e){return e.search(kD)!==-1}async function LD(e,t,n){if(!ID(e))return e;let r=FD(e,n);return ND(r).reduce((e,r)=>e.then(e=>PD(e,r,t,n)),Promise.resolve(r))}async function RD(e,t,n){let r=t.style?.getPropertyValue(e);if(r){let i=await LD(r,null,n);return t.style.setProperty(e,i,t.style.getPropertyPriority(e)),!0}return!1}async function zD(e,t){await RD(`background`,e,t)||await RD(`background-image`,e,t),await RD(`mask`,e,t)||await RD(`-webkit-mask`,e,t)||await RD(`mask-image`,e,t)||await RD(`-webkit-mask-image`,e,t)}async function BD(e,t){let n=QE(e,HTMLImageElement);if((!n||uD(e.src))&&(!QE(e,SVGImageElement)||uD(e.href.baseVal)))return;let r=n?e.src:e.href.baseVal,i=await hD(r,cD(r),t);await new Promise((r,a)=>{e.onload=r,e.onerror=t.onImageErrorHandler?(...e)=>{try{r(t.onImageErrorHandler(...e))}catch(e){a(e)}}:a;let o=e;o.decode&&=r,o.loading===`lazy`&&(o.loading=`eager`),n?(e.srcset=``,e.src=i):e.href.baseVal=i})}async function VD(e,t){let n=zE(e.childNodes).map(e=>HD(e,t));await Promise.all(n).then(()=>e)}async function HD(e,t){QE(e,Element)&&(await zD(e,t),await BD(e,t),await VD(e,t))}function UD(e,t){let{style:n}=e;t.backgroundColor&&(n.backgroundColor=t.backgroundColor),t.width&&(n.width=`${t.width}px`),t.height&&(n.height=`${t.height}px`);let r=t.style;return r!=null&&Object.keys(r).forEach(e=>{n[e]=r[e]}),e}var WD={};async function GD(e){let t=WD[e];return t??(t={url:e,cssText:await(await fetch(e)).text()},WD[e]=t,t)}async function KD(e,t){let n=e.cssText,r=/url\(["']?([^"')]+)["']?\)/g,i=(n.match(/url\([^)]+\)/g)||[]).map(async i=>{let a=i.replace(r,`$1`);return a.startsWith(`https://`)||(a=new URL(a,e.url).href),fD(a,t.fetchRequestInit,({result:e})=>(n=n.replace(i,`url(${e})`),[i,e]))});return Promise.all(i).then(()=>n)}function qD(e){if(e==null)return[];let t=[],n=e.replace(/(\/\*[\s\S]*?\*\/)/gi,``),r=RegExp(`((@.*?keyframes [\\s\\S]*?){([\\s\\S]*?}\\s*?)})`,`gi`);for(;;){let e=r.exec(n);if(e===null)break;t.push(e[0])}n=n.replace(r,``);let i=/@import[\s\S]*?url\([^)]*\)[\s\S]*?;/gi,a=RegExp(`((\\s*?(?:\\/\\*[\\s\\S]*?\\*\\/)?\\s*?@media[\\s\\S]*?){([\\s\\S]*?)}\\s*?})|(([\\s\\S]*?){([\\s\\S]*?)})`,`gi`);for(;;){let e=i.exec(n);if(e===null){if(e=a.exec(n),e===null)break;i.lastIndex=a.lastIndex}else a.lastIndex=i.lastIndex;t.push(e[0])}return t}async function JD(e,t){let n=[],r=[];return e.forEach(n=>{if(`cssRules`in n)try{zE(n.cssRules||[]).forEach((e,i)=>{if(e.type===CSSRule.IMPORT_RULE){let a=i+1,o=e.href,s=GD(o).then(e=>KD(e,t)).then(e=>qD(e).forEach(e=>{try{n.insertRule(e,e.startsWith(`@import`)?a+=1:n.cssRules.length)}catch(t){console.error(`Error inserting rule from remote css`,{rule:e,error:t})}})).catch(e=>{console.error(`Error loading remote css`,e.toString())});r.push(s)}})}catch(i){let a=e.find(e=>e.href==null)||document.styleSheets[0];n.href!=null&&r.push(GD(n.href).then(e=>KD(e,t)).then(e=>qD(e).forEach(e=>{a.insertRule(e,a.cssRules.length)})).catch(e=>{console.error(`Error loading remote stylesheet`,e)})),console.error(`Error inlining remote css file`,i)}}),Promise.all(r).then(()=>(e.forEach(e=>{if(`cssRules`in e)try{zE(e.cssRules||[]).forEach(e=>{n.push(e)})}catch(t){console.error(`Error while reading CSS rules from ${e.href}`,t)}}),n))}function YD(e){return e.filter(e=>e.type===CSSRule.FONT_FACE_RULE).filter(e=>ID(e.style.getPropertyValue(`src`)))}async function XD(e,t){if(e.ownerDocument==null)throw Error(`Provided element is not within a Document`);return YD(await JD(zE(e.ownerDocument.styleSheets),t))}function ZD(e){return e.trim().replace(/["']/g,``)}function QD(e){let t=new Set;function n(e){(e.style.fontFamily||getComputedStyle(e).fontFamily).split(`,`).forEach(e=>{t.add(ZD(e))}),Array.from(e.children).forEach(e=>{e instanceof HTMLElement&&n(e)})}return n(e),t}async function $D(e,t){let n=await XD(e,t),r=QD(e);return(await Promise.all(n.filter(e=>r.has(ZD(e.style.fontFamily))).map(e=>{let n=e.parentStyleSheet?e.parentStyleSheet.href:null;return LD(e.cssText,n,t)}))).join(`
|
|
4456
|
-
`)}async function eO(e,t){let n=t.fontEmbedCSS==null?t.skipFonts?null:await $D(e,t):t.fontEmbedCSS;if(n){let t=document.createElement(`style`),r=document.createTextNode(n);t.appendChild(r),e.firstChild?e.insertBefore(t,e.firstChild):e.appendChild(t)}}async function tO(e,t={}){let{width:n,height:r}=GE(e,t),i=await OD(e,t,!0);return await eO(i,t),await HD(i,t),UD(i,t),await ZE(i,n,r)}async function nO(e,t={}){let{width:n,height:r}=GE(e,t),i=await YE(await tO(e,t)),a=document.createElement(`canvas`),o=a.getContext(`2d`),s=t.pixelRatio||KE(),c=t.canvasWidth||n,l=t.canvasHeight||r;return a.width=c*s,a.height=l*s,t.skipAutoScale||JE(a),a.style.width=`${c}`,a.style.height=`${l}`,t.backgroundColor&&(o.fillStyle=t.backgroundColor,o.fillRect(0,0,a.width,a.height)),o.drawImage(i,0,0,a.width,a.height),a}var rO=1600,iO=.85;function aO(e,t){let n=Math.min(1,rO/Math.max(e,t,1));return{width:Math.max(1,Math.round(e*n)),height:Math.max(1,Math.round(t*n))}}async function oO(){let e=document.documentElement.getBoundingClientRect(),t=await nO(document.body,{width:Math.round(e.width),height:Math.round(e.height),pixelRatio:1,backgroundColor:`#050b10`,filter:e=>!(e instanceof HTMLElement&&e.dataset.noCapture!==void 0)}),n=aO(t.width,t.height),r=document.createElement(`canvas`);return r.width=n.width,r.height=n.height,r.getContext(`2d`).drawImage(t,0,0,n.width,n.height),new Promise((e,t)=>r.toBlob(n=>n?e(n):t(Error(`Could not encode the picture.`)),`image/jpeg`,iO))}var sO=class{opts;active=null;constructor(e){this.opts=e}async handle(e){if(e.type===`screen.cancel`){this.active&&this.active.id===e.id&&(this.active.cancelled=!0);return}if(this.active)return this.opts.send({type:`screen.denied`,id:e.id,reason:`busy`});let t={id:e.id,cancelled:!1};this.active=t;try{let n=await(this.opts.capture??oO)();if(t.cancelled)return;try{await this.opts.upload(e.id,n)}catch{this.opts.dispatch({type:`alert.add`,level:`warn`,text:`Could not send the picture of the screen to Friend.`})}}catch(n){t.cancelled||this.opts.send({type:`screen.denied`,id:e.id,reason:cO(n)})}finally{this.active===t&&(this.active=null)}}dispose(){this.active&&(this.active.cancelled=!0)}};function cO(e){return e?.name===`NotSupportedError`?`unsupported`:`failed`}var lO={401:`Please sign in again.`,413:`That recording was too long.`,409:`Friend is busy with the last request. Try again in a moment.`,429:`You're talking too fast. Wait a moment.`,503:`Voice is not available. Run: friend voice setup`};async function uO(e,t){let n;try{n=await fetch(`/api/voice/utterance`,{method:`POST`,headers:{"content-type":e.type||`audio/webm`},body:e,signal:t})}catch(e){throw e.name===`AbortError`?e:Error(`Could not reach Friend. Check the connection.`)}if(!n.ok){let e=``;try{e=(await n.json()).error??``}catch{}throw Error(e||lO[n.status]||`The voice request failed (${n.status}).`)}let r=await n.json();return{text:typeof r.text==`string`?r.text:``}}var dO=0,fO=new Set;function pO(e){return fO.add(e),()=>fO.delete(e)}var mO=e=>fO.forEach(t=>{try{t(e)}catch{}}),hO=e=>/not compatible|audio capture|audiosession/i.test(String(e?.message??e));function gO(e){try{let t=navigator.audioSession;t&&t.type!==e&&(t.type=e)}catch{}}function _O(){dO===0&&gO(`playback`)}function vO(){dO++,dO===1&&mO(!0),gO(`play-and-record`);let e=!1;return()=>{e||(e=!0,dO=Math.max(0,dO-1),dO===0&&(gO(`playback`),mO(!1)))}}var yO=4096,bO=8,xO=20,SO=6e6;function CO(e){try{let t=atob(e),n=new Uint8Array(t.length);for(let e=0;e<t.length;e++)n[e]=t.charCodeAt(e);return n}catch{return null}}var wO=class{ctx=null;analyser=null;pending=new Map;queue=[];current=null;busy=!1;gen=0;isPlaying=!1;unwatch=null;listeners=new Set;unlock(){_O();let e=this.ensureContext();e.state!==`running`&&e.resume().catch(()=>{})}locked(){return!this.ctx||this.ctx.state!==`running`}enqueue(e){if(!Number.isInteger(e.seq)||e.seq<0||e.seq>yO)return;let t=CO(e.data);if(!t)return;let n=this.pending.get(e.id);if(n||(this.pending.size>=bO&&this.pending.delete(this.pending.keys().next().value),n={parts:new Map,lastSeq:null,bytes:0},this.pending.set(e.id,n)),n.bytes+=t.length,n.bytes>SO){this.pending.delete(e.id);return}if(n.parts.set(e.seq,t),e.last&&(n.lastSeq=e.seq),n.lastSeq===null||n.parts.size!==n.lastSeq+1)return;this.pending.delete(e.id);let r=new Uint8Array([...n.parts.values()].reduce((e,t)=>e+t.length,0)),i=0;for(let e=0;e<=n.lastSeq;e++){let t=n.parts.get(e);if(!t)return;r.set(t,i),i+=t.length}for(this.queue.push(r.buffer);this.queue.length>xO;)this.queue.shift();this.pump()}stop(){this.gen++,this.queue=[],this.pending.clear(),this.busy=!1;let e=this.current;if(this.current=null,e){e.onended=null;try{e.stop()}catch{}}this.setPlaying(!1)}dispose(){this.stop(),this.ctx?.close().catch(()=>{}),this.unwatch?.(),this.unwatch=null,this.ctx=null,this.analyser=null}playing(){return this.isPlaying}onChange(e){return this.listeners.add(e),()=>this.listeners.delete(e)}level(){if(!this.analyser||!this.isPlaying)return 0;let e=new Uint8Array(this.analyser.fftSize);this.analyser.getByteTimeDomainData(e);let t=0;for(let n of e)t+=((n-128)/128)**2;return Math.min(1,Math.sqrt(t/e.length)*4)}ensureContext(){if(!this.ctx){let e=window.AudioContext??window.webkitAudioContext;this.ctx=new e,this.analyser=this.ctx.createAnalyser(),this.analyser.fftSize=1024,this.analyser.connect(this.ctx.destination);let t=this.ctx;this.unwatch?.(),this.unwatch=pO(e=>{e&&t.state===`running`?t.suspend().catch(()=>{}):!e&&t.state!==`running`&&t.state!==`closed`&&t.resume().catch(()=>{})})}return this.ctx}setPlaying(e){this.isPlaying!==e&&(this.isPlaying=e,this.listeners.forEach(t=>t(e)))}async pump(){if(this.busy)return;let e=this.queue.shift();if(!e){this.setPlaying(!1);return}this.busy=!0;let t=this.gen;try{let n=this.ensureContext();if(n.state!==`running`){try{await n.resume()}catch{}if(t!==this.gen)return;if(n.state!==`running`){this.queue.unshift(e),this.busy=!1;return}}let r=await n.decodeAudioData(e);if(t!==this.gen)return;let i=n.createBufferSource();i.buffer=r,i.connect(this.analyser),i.onended=()=>{this.current===i&&(this.current=null,this.busy=!1,this.pump())},this.current=i,this.setPlaying(!0),i.start()}catch{if(t!==this.gen)return;this.busy=!1,this.pump()}}},TO=e=>new Promise(t=>setTimeout(t,e)),EO=[`audio/webm;codecs=opus`,`audio/webm`,`audio/mp4`,`audio/ogg;codecs=opus`],DO=3e3;function OO(e){let t=e;return t?.name===`NotAllowedError`||t?.name===`SecurityError`?Error(`Microphone permission was denied. Allow it in the browser to talk.`):t?.name===`NotFoundError`||t?.name===`OverconstrainedError`?Error(`No microphone was found.`):Error(t?.message||`Could not open the microphone.`)}var kO=class e{opts;stream=null;rec=null;chunks=[];ctx=null;analyser=null;timer=null;starting=!1;leaveSession=null;constructor(e={}){this.opts=e}static supported(){return typeof navigator<`u`&&!!navigator.mediaDevices?.getUserMedia&&typeof MediaRecorder<`u`}get active(){return this.rec!==null}async start(){if(!(this.rec||this.starting)){if(!e.supported())throw Error(`This browser cannot record audio here (use localhost or HTTPS).`);this.starting=!0;try{this.leaveSession=vO();try{let e=()=>navigator.mediaDevices.getUserMedia({audio:{echoCancellation:!0,noiseSuppression:!0}});try{this.stream=await e()}catch(t){if(!hO(t))throw t;await TO(250),this.leaveSession?.(),this.leaveSession=vO(),this.stream=await e()}}catch(e){throw this.leaveSession?.(),this.leaveSession=null,OO(e)}try{let e=EO.find(e=>MediaRecorder.isTypeSupported(e));this.chunks=[];let t=new MediaRecorder(this.stream,e?{mimeType:e}:void 0);t.ondataavailable=e=>{e.data&&e.data.size>0&&this.chunks.push(e.data)},t.onerror=()=>this.failed();for(let e of this.stream.getTracks())e.onended=()=>this.failed();this.openMeter(this.stream),t.start(250),this.rec=t,this.opts.maxMs&&(this.timer=setTimeout(()=>{this.timer=null,this.opts.onLimit?.()},this.opts.maxMs))}catch(e){throw this.release(),OO(e)}}finally{this.starting=!1}}}stop(){let e=this.rec;return e?new Promise(t=>{let n=!1,r=null,i=()=>{if(n)return;n=!0,r&&clearTimeout(r);let i=new Blob(this.chunks,{type:e.mimeType||`audio/webm`});this.release(),t(i)};if(r=setTimeout(i,DO),e.onstop=i,e.state===`inactive`)return i();try{e.stop()}catch{i()}}):Promise.reject(Error(`Not recording.`))}cancel(){let e=this.rec;if(e){e.ondataavailable=null,e.onstop=null,e.onerror=null;try{e.state!==`inactive`&&e.stop()}catch{}}this.release()}level(){if(!this.analyser||!this.rec)return 0;let e=new Uint8Array(this.analyser.fftSize);this.analyser.getByteTimeDomainData(e);let t=0;for(let n of e)t+=((n-128)/128)**2;return Math.min(1,Math.sqrt(t/e.length)*4)}failed(){this.rec&&(this.cancel(),this.opts.onError?.())}openMeter(e){try{this.ctx=new AudioContext,this.analyser=this.ctx.createAnalyser(),this.analyser.fftSize=1024,this.ctx.createMediaStreamSource(e).connect(this.analyser)}catch{this.analyser=null}}release(){this.timer&&clearTimeout(this.timer),this.timer=null,this.stream?.getTracks().forEach(e=>{e.onended=null,e.stop()}),this.ctx?.close().catch(()=>{}),this.stream=null,this.rec=null,this.ctx=null,this.analyser=null,this.chunks=[],this.leaveSession?.(),this.leaveSession=null}},AO=2e3,jO=()=>typeof window<`u`&&window.isSecureContext===!1,MO=50,NO=class{deps;recorder;player;mode=`idle`;pressed=!1;disposed=!1;uploads=0;toldAboutSound=!1;abort=null;poll=null;unsubscribe;constructor(e){this.deps=e;let t=()=>this.recorderFailed();this.recorder=e.recorder??e.makeRecorder?.(t)??new kO({maxMs:6e4,onLimit:()=>void this.pressEnd(),onError:t}),this.player=e.player??new wO,this.unsubscribe=this.player.onChange(e=>{this.mode!==`listening`&&this.mode!==`transcribing`&&this.setMode(e?`speaking`:`idle`)})}async pressStart(){if(!(this.pressed||this.disposed)){if(!this.deps.available()){this.alert(`warn`,`Voice is not available. Run: friend voice setup`);return}if(!(this.deps.supported?.()??kO.supported())){this.alert(`warn`,jO()?`This page is not secure, so the browser blocks the microphone. On the PC run: friend lan https on, restart Friend, and open the https:// address.`:`This browser cannot record audio here (use localhost or HTTPS).`);return}this.pressed=!0,this.player.unlock(),this.player.playing()&&(this.deps.send({type:`voice.interrupt`}),this.player.stop());try{await this.recorder.start()}catch(e){this.pressed=!1,this.alert(`error`,e.message),this.setMode(`idle`);return}if(!this.pressed){this.recorder.cancel(),this.setMode(`idle`);return}this.setMode(`listening`)}}async pressEnd(){if(!this.pressed||(this.pressed=!1,!this.recorder.active))return;let e=await this.recorder.stop();if(e.size<AO){this.alert(`info`,`Hold the key a little longer while you speak.`),this.setMode(`idle`);return}this.setMode(`transcribing`);let t=new AbortController;this.abort=t,this.uploads++;try{let{text:n}=await this.deps.post(e,t.signal);n.trim()||this.alert(`info`,`I didn't catch that.`)}catch(e){e.name!==`AbortError`&&this.alert(`error`,e.message)}finally{this.uploads--,this.abort===t&&(this.abort=null),this.settle()}}blur(){this.pressed&&(this.pressed=!1,this.recorder.cancel(),this.setMode(`idle`))}handleServer(e){if(e.type!==`audio.chunk`)return this.player.stop();this.player.enqueue(e),!this.toldAboutSound&&this.player.locked?.()&&(this.toldAboutSound=!0,this.deps.dispatch({type:`alert.add`,level:`info`,text:`Sound is blocked by the browser. Click or press a key once anywhere on the page to hear me.`}))}unlock(){this.player.unlock()}dispose(){this.disposed=!0,this.pressed=!1,this.stopPolling(),this.abort?.abort(),this.recorder.cancel(),this.player.stop(),this.player.dispose?.(),this.unsubscribe()}recorderFailed(){this.pressed=!1,this.recorder.cancel(),this.alert(`error`,`The microphone stopped working.`),this.setMode(`idle`)}settle(){this.uploads>0||this.mode!==`transcribing`||this.setMode(this.player.playing()?`speaking`:`idle`)}setMode(e){this.disposed||(this.mode=e,this.deps.dispatch({type:`voice.mode`,mode:e}),e===`listening`||e===`speaking`?this.startPolling():this.stopPolling())}startPolling(){this.stopPolling(),this.poll=setInterval(()=>{let e=this.mode===`listening`?this.recorder.level():this.player.level();this.deps.dispatch({type:`voice.level`,level:e})},MO)}stopPolling(){this.poll&&clearInterval(this.poll),this.poll=null}alert(e,t){this.disposed||this.deps.dispatch({type:`alert.add`,level:e,text:t})}};function PO(e){let[t,n]=(0,l.useReducer)(OE,SE),r=(0,l.useRef)(null),i=(0,l.useRef)(null),a=(0,l.useRef)(null),o=(0,l.useRef)(e);o.current=e;let s=(0,l.useRef)(t);return s.current=t,(0,l.useEffect)(()=>{let e=xE();r.current=e;let t=new NO({send:t=>e.send(t),dispatch:e=>n(e),post:uO,available:()=>s.current.voice.available});i.current=t;let c=new IE({send:t=>e.send(t),dispatch:e=>n(e),enabled:()=>s.current.camera.enabled,upload:async(e,t)=>{let n=await fetch(`/api/camera/frame/${encodeURIComponent(e)}`,{method:`POST`,headers:{"content-type":`image/jpeg`},body:t});if(!n.ok)throw Error(`upload failed (${n.status})`)}});a.current=c;let l=new sO({send:t=>e.send(t),dispatch:e=>n(e),upload:async(e,t)=>{let n=await fetch(`/api/screen/frame/${encodeURIComponent(e)}`,{method:`POST`,headers:{"content-type":`image/jpeg`},body:t});if(!n.ok)throw Error(`upload failed (${n.status})`)}}),u=e.onMessage(e=>{n(e);let r=e?.type,i=e?.id;(r===`camera.request`||r===`camera.cancel`)&&typeof i==`string`&&c.handle({type:r,id:i}),(r===`screen.request`||r===`screen.cancel`)&&typeof i==`string`&&l.handle({type:r,id:i}),(r===`audio.chunk`||r===`audio.stop`)&&t.handleServer(e)}),d=e.onState(e=>{n({type:`conn`,value:e}),e===`unauthorized`&&o.current(),e===`elsewhere`&&(t.blur(),c.dispose(),l.dispose())});return()=>{u(),d(),t.dispose(),c.dispose(),l.dispose(),e.close(),i.current=null,a.current=null,r.current=null}},[]),(0,l.useEffect)(()=>{t.camera.enabled||a.current?.dispose()},[t.camera.enabled]),{state:t,send:(0,l.useCallback)(e=>r.current?.send(e),[]),dispatch:(0,l.useCallback)(e=>n(e),[]),voice:(0,l.useMemo)(()=>({pressStart:()=>void i.current?.pressStart(),pressEnd:()=>void i.current?.pressEnd(),blur:()=>i.current?.blur(),unlock:()=>i.current?.unlock()}),[]),useHere:(0,l.useCallback)(()=>r.current?.takeOver(),[])}}var FO={401:`Please sign in again.`,403:`Incorrect PIN.`,413:`That recording was too long.`,429:`Too many attempts. Wait a moment.`,503:`Voice is not available. Run: friend voice setup`};async function IO(e,t){let n;try{n=await fetch(e,t)}catch{throw Error(`Could not reach Friend. Check the connection.`)}if(!n.ok){let e=``;try{e=(await n.json()).error??``}catch{}throw Error(e||FO[n.status]||`The request failed (${n.status}).`)}return await n.json()}var LO=(e,t)=>({method:e,headers:{"content-type":`application/json`},body:JSON.stringify(t)}),RO={state:()=>IO(`/api/voice/enroll`,{}),sample:e=>IO(`/api/voice/enroll/sample`,{method:`POST`,headers:{"content-type":e.type||`audio/webm`},body:e}),finish:e=>IO(`/api/voice/enroll/finish`,LO(`POST`,{pin:e})),cancel:async()=>{await IO(`/api/voice/enroll/cancel`,LO(`POST`,{}))},remove:async e=>{await IO(`/api/voice/enroll`,LO(`DELETE`,{pin:e}))}},zO=[`Friend, good evening. It is a pleasant day to get things done.`,`Open my projects and show me what changed today.`,`My voice is my key, so please remember it well.`,`Check the weather and read me the latest headlines.`,`Always protect the boss, and never trust a stranger.`],BO=15e3;function VO({api:e=RO,createRecorder:t=e=>new kO(e),onClose:n,who:r}){let[i,a]=(0,l.useState)(null),[o,s]=(0,l.useState)(0),[c,u]=(0,l.useState)(null),[f,m]=(0,l.useState)(`record`),[h,g]=(0,l.useState)(!1),[_,v]=(0,l.useState)(!1),[y,b]=(0,l.useState)(null),[S,C]=(0,l.useState)(``),w=(0,l.useRef)(!0),T=(0,l.useRef)(null);(0,l.useEffect)(()=>(w.current=!0,e.state().then(e=>{w.current&&(a(e),s(e.samples))}).catch(e=>w.current&&b(e.message)),()=>{w.current=!1,T.current?.cancel(),T.current=null}),[e]);let E=(0,l.useCallback)(async()=>{let t=T.current;if(t){T.current=null,g(!1),v(!0);try{let n=await t.stop(),r=await e.sample(n);if(!w.current)return;s(r.count),u(r.note)}catch(e){w.current&&b(e.message)}finally{w.current&&v(!1)}}},[e]),D=async()=>{b(null),u(null);let e=t({maxMs:BO,onLimit:()=>void E(),onError:()=>{T.current=null,w.current&&(g(!1),b(`The microphone stopped working. Try again.`))}});try{await e.start()}catch(e){w.current&&b(e.message);return}if(!w.current)return e.cancel();T.current=e,g(!0)},O=async e=>{b(null),v(!0);try{await e()}catch(e){w.current&&b(e.message)}finally{w.current&&(v(!1),C(``))}},k=async()=>{T.current?.cancel(),T.current=null,await e.cancel().catch(()=>{}),n()},A=i?.min??3,j=o%zO.length,ee=o<zO.length?`Phrase ${o+1} of ${zO.length}`:`Extra recording (${o} so far)`;return(0,p.jsxs)(`div`,{className:`approval enroll glass`,role:`dialog`,"aria-label":`Voice enrollment`,style:{pointerEvents:`auto`},children:[(0,p.jsx)(`div`,{className:`approval-head`,children:(0,p.jsx)(`span`,{className:`approval-title`,children:r?`Teach Friend ${r}'s voice`:`Teach Friend your voice`})}),f===`record`&&(0,p.jsxs)(p.Fragment,{children:[!r&&i?.enrolled&&(0,p.jsx)(`p`,{className:`auth-note`,children:`Your voice is already saved. Saving a new one replaces it.`}),r&&(0,p.jsxs)(`p`,{className:`auth-note`,children:[`Hand the device to `,r,`. `,r,` reads each sentence aloud, close to the microphone, in a quiet room.`]}),(0,p.jsxs)(`p`,{className:`auth-note`,children:[ee,`. Press Record, read this aloud in a quiet room, then press Stop.`]}),(0,p.jsx)(`pre`,{className:`approval-summary`,"data-testid":`enroll-phrase`,style:{whiteSpace:`pre-wrap`},children:zO[j]}),(0,p.jsxs)(`div`,{role:`status`,className:`auth-note`,children:[o,` recorded`,o>=A?` — enough to save`:` — at least ${A} needed`,`.`,c?` ${c}`:``]}),y&&(0,p.jsx)(`p`,{role:`alert`,className:`auth-error`,children:y}),(0,p.jsxs)(`div`,{className:`approval-actions`,children:[h?(0,p.jsx)(`button`,{type:`button`,style:d,className:`danger`,onClick:()=>void E(),children:`Stop`}):(0,p.jsx)(`button`,{type:`button`,style:d,className:`primary`,disabled:_||!i||o>=(i?.max??8),onClick:()=>void D(),children:_?`Uploading…`:`Record`}),(0,p.jsx)(`button`,{type:`button`,style:d,disabled:h||_||o<A,onClick:()=>m(`pin-save`),children:r?`Save ${r}'s voice`:`Save my voice`}),!r&&i?.enrolled&&(0,p.jsx)(`button`,{type:`button`,style:d,className:`danger`,disabled:h||_,onClick:()=>m(`pin-delete`),children:`Delete my voice`}),(0,p.jsx)(`button`,{type:`button`,style:d,onClick:()=>void k(),children:`Cancel`})]})]}),(f===`pin-save`||f===`pin-delete`)&&(0,p.jsxs)(p.Fragment,{children:[(0,p.jsx)(`p`,{className:`auth-note`,children:f===`pin-save`?r?`Enter your PIN to save ${r}'s voice.`:`Enter your PIN to save your voice.`:`Enter your PIN to delete your saved voice.`}),(0,p.jsx)(x,{pin:S,onChange:C,onSubmit:f===`pin-save`?()=>!_&&void O(async()=>{await e.finish(S),w.current&&m(`saved`)}):void 0}),y&&(0,p.jsx)(`p`,{role:`alert`,className:`auth-error`,children:y}),(0,p.jsxs)(`div`,{className:`approval-actions`,children:[f===`pin-save`?(0,p.jsx)(`button`,{type:`button`,style:d,className:`primary`,disabled:_||S.length<6,onClick:()=>void O(async()=>{await e.finish(S),w.current&&m(`saved`)}),children:`Save`}):(0,p.jsx)(`button`,{type:`button`,style:d,className:`danger`,disabled:_||S.length<6,onClick:()=>void O(async()=>{await e.remove(S),w.current&&m(`deleted`)}),children:`Delete`}),(0,p.jsx)(`button`,{type:`button`,style:d,onClick:()=>{C(``),b(null),m(`record`)},children:`Back`})]})]}),(f===`saved`||f===`deleted`)&&(0,p.jsxs)(p.Fragment,{children:[(0,p.jsx)(`p`,{className:`auth-note`,children:f===`saved`?r?`${r}'s voice is saved. From now on I will know when ${r} is talking.`:`Your voice is saved. From now on I will tell you apart from other speakers.`:`Your voice was deleted. Every voice is treated as yours until you enroll again.`}),(0,p.jsx)(`div`,{className:`approval-actions`,children:(0,p.jsx)(`button`,{type:`button`,style:d,className:`primary`,onClick:n,children:`Done`})})]})]})}var HO=new Set([`INPUT`,`TEXTAREA`,`SELECT`,`BUTTON`,`A`,`SUMMARY`]),UO=new Set([`button`,`checkbox`,`switch`,`tab`,`menuitem`,`link`,`radio`,`option`,`textbox`,`combobox`,`slider`]),WO=e=>e instanceof HTMLElement&&(HO.has(e.tagName)||e.isContentEditable||UO.has(e.getAttribute(`role`)??``)),GO=e=>e.code===`Space`||e.key===` `;function KO(e){let t=(0,l.useRef)(e);t.current=e,(0,l.useEffect)(()=>{let e=!1,n=n=>{!GO(n)||n.ctrlKey||n.metaKey||n.altKey||WO(n.target)||WO(document.activeElement)||(n.preventDefault(),!(n.repeat||e)&&(e=!0,t.current.pressStart()))},r=n=>{GO(n)&&e&&(e=!1,n.preventDefault(),t.current.pressEnd())},i=()=>{e=!1,t.current.blur()},a=()=>{document.hidden&&i()};return window.addEventListener(`keydown`,n),window.addEventListener(`keyup`,r),window.addEventListener(`blur`,i),document.addEventListener(`visibilitychange`,a),()=>{window.removeEventListener(`keydown`,n),window.removeEventListener(`keyup`,r),window.removeEventListener(`blur`,i),document.removeEventListener(`visibilitychange`,a)}},[])}function qO(e){let t=(0,l.useRef)(e);t.current=e,(0,l.useEffect)(()=>{let e=()=>t.current.unlock(),n=[`pointerdown`,`keydown`,`touchend`];for(let t of n)window.addEventListener(t,e,{passive:!0});return()=>{for(let t of n)window.removeEventListener(t,e)}},[])}function JO({onUseHere:e}){return(0,p.jsx)(`div`,{className:`elsewhere`,role:`alertdialog`,"aria-labelledby":`elsewhere-title`,"data-testid":`elsewhere`,children:(0,p.jsxs)(`div`,{className:`elsewhere-card`,children:[(0,p.jsx)(`h2`,{id:`elsewhere-title`,children:`Friend is open in another window`}),(0,p.jsx)(`p`,{children:`Friend works in one window at a time. Click “Use here” to use it in this window instead; the other one will stop.`}),(0,p.jsx)(`button`,{type:`button`,className:`elsewhere-btn`,onClick:e,autoFocus:!0,children:`Use here`})]})})}function YO(e,t,n){let r=Math.max(100,Math.round(e)),i=Math.max(100,Math.round(t));return{width:r,height:i,kind:r<=599?`phone`:n||r<1024?`tablet`:`desktop`,orientation:i>r?`portrait`:`landscape`,touch:n}}var XO=()=>typeof matchMedia==`function`&&matchMedia(`(pointer: coarse)`).matches;function ZO(){return YO(window.innerWidth,window.innerHeight,XO())}var QO=(e,t)=>!!e&&e.width===t.width&&e.height===t.height&&e.kind===t.kind&&e.orientation===t.orientation&&e.touch===t.touch;function $O(e,t){let n=(0,l.useRef)(null),r=(0,l.useRef)(e);r.current=e,(0,l.useEffect)(()=>{if(t!==`open`){n.current=null;return}let e=()=>{let e=ZO();QO(n.current,e)||(n.current=e,r.current({type:`ui.screen`,...e}))};e();let i=null,a=()=>{i&&clearTimeout(i),i=setTimeout(e,400)};return window.addEventListener(`resize`,a),window.addEventListener(`orientationchange`,a),()=>{i&&clearTimeout(i),window.removeEventListener(`resize`,a),window.removeEventListener(`orientationchange`,a)}},[t])}var ek={401:`Please sign in again.`,403:`Incorrect PIN.`,413:`That recording was too long.`,429:`Too many attempts. Wait a moment.`,503:`Voice is not available. Run: friend voice setup`};async function tk(e,t={}){let n;try{n=await fetch(e,t)}catch{throw Error(`Could not reach Friend. Check the connection.`)}if(!n.ok){let e=``;try{e=(await n.json()).error??``}catch{}throw Error(e||ek[n.status]||`The request failed (${n.status}).`)}return await n.json()}var nk=(e,t)=>({method:e,headers:{"content-type":`application/json`},body:JSON.stringify(t)}),rk={overview:()=>tk(`/api/voice/people`),begin:e=>tk(`/api/voice/people/begin`,nk(`POST`,{name:e})),recording:{state:async()=>(await tk(`/api/voice/people`)).enrolling??{enrolled:!1,samples:0,min:3,max:8},sample:e=>tk(`/api/voice/people/sample`,{method:`POST`,headers:{"content-type":e.type||`audio/webm`},body:e}),finish:e=>tk(`/api/voice/people/finish`,nk(`POST`,{pin:e})),cancel:async()=>{await tk(`/api/voice/people/cancel`,nk(`POST`,{}))},remove:async()=>{}},removePerson:async(e,t)=>{await tk(`/api/voice/people/${e}`,nk(`DELETE`,{pin:t}))}};function ik({api:e=rk,createRecorder:t,onClose:n}){let[r,i]=(0,l.useState)(null),[a,o]=(0,l.useState)({kind:`list`}),[s,c]=(0,l.useState)(``),[u,f]=(0,l.useState)(``),[m,h]=(0,l.useState)(!1),[g,_]=(0,l.useState)(null),v=(0,l.useRef)(!0),y=(0,l.useCallback)(()=>{e.overview().then(e=>v.current&&i(e)).catch(e=>v.current&&_(e.message))},[e]);(0,l.useEffect)(()=>(v.current=!0,y(),()=>{v.current=!1}),[y]);let b=async()=>{_(null),h(!0);try{let t=await e.begin(s.trim());v.current&&o({kind:`record`,name:t.name})}catch(e){v.current&&_(e.message)}finally{v.current&&h(!1)}},S=async t=>{_(null),h(!0);try{if(await e.removePerson(t.id,u),!v.current)return;o({kind:`list`}),y()}catch(e){v.current&&_(e.message)}finally{v.current&&(h(!1),f(``))}};return a.kind===`record`?(0,p.jsx)(VO,{api:e.recording,who:a.name,...t?{createRecorder:t}:{},onClose:()=>{c(``),o({kind:`list`}),y()}}):(0,p.jsxs)(`div`,{className:`approval enroll glass`,role:`dialog`,"aria-label":`Family voices`,style:{pointerEvents:`auto`},children:[(0,p.jsx)(`div`,{className:`approval-head`,children:(0,p.jsx)(`span`,{className:`approval-title`,children:`Family voices`})}),a.kind===`list`&&(0,p.jsxs)(p.Fragment,{children:[(0,p.jsx)(`p`,{className:`auth-note`,children:`Friend knows your voice. Add the people at home, so it knows who is talking and answers them by name. They can chat and ask for the weather, but cannot use your PC or see your private things.`}),r&&!r.ownerEnrolled&&(0,p.jsx)(`p`,{className:`auth-note`,children:`First teach Friend your own voice (Esc, then Enroll my voice).`}),r&&r.people.length===0&&r.ownerEnrolled&&(0,p.jsx)(`p`,{className:`auth-note`,children:`Nobody added yet.`}),r&&r.people.length>0&&(0,p.jsx)(`ul`,{className:`household-list`,"aria-label":`People Friend knows`,children:r.people.map(e=>(0,p.jsxs)(`li`,{className:`household-row`,children:[(0,p.jsx)(`span`,{children:e.name}),(0,p.jsx)(`button`,{type:`button`,style:d,className:`danger`,onClick:()=>o({kind:`remove`,person:e}),"aria-label":`Remove ${e.name}`,children:`Remove`})]},e.id))}),r&&r.ownerEnrolled&&r.people.length<r.max&&(0,p.jsxs)(`label`,{className:`settings-field`,children:[(0,p.jsx)(`span`,{children:`Add a person`}),(0,p.jsx)(`input`,{value:s,maxLength:40,placeholder:`Name, for example Priya`,onChange:e=>c(e.target.value),onKeyDown:e=>e.key===`Enter`&&s.trim()&&!m&&void b()})]}),g&&(0,p.jsx)(`p`,{role:`alert`,className:`auth-error`,children:g}),(0,p.jsxs)(`div`,{className:`approval-actions`,children:[r&&r.ownerEnrolled&&r.people.length<r.max&&(0,p.jsx)(`button`,{type:`button`,style:d,className:`primary`,disabled:m||!s.trim(),onClick:()=>void b(),children:`Record their voice`}),(0,p.jsx)(`button`,{type:`button`,style:d,onClick:n,children:`Close`})]})]}),a.kind===`remove`&&(0,p.jsxs)(p.Fragment,{children:[(0,p.jsxs)(`p`,{className:`auth-note`,children:[`Enter your PIN to remove `,a.person.name,`’s voice. Friend will treat their voice as a stranger’s.`]}),(0,p.jsx)(x,{pin:u,onChange:f}),g&&(0,p.jsx)(`p`,{role:`alert`,className:`auth-error`,children:g}),(0,p.jsxs)(`div`,{className:`approval-actions`,children:[(0,p.jsx)(`button`,{type:`button`,style:d,className:`danger`,disabled:m||u.length<6,onClick:()=>void S(a.person),children:`Remove`}),(0,p.jsx)(`button`,{type:`button`,style:d,onClick:()=>{f(``),_(null),o({kind:`list`})},children:`Back`})]})]})]})}var ak=`▌▍▎▏█▓▒░<>/\\|+-=*#%&0123456789ABCDEF`;function ok(e,t,n=Math.random){let r=[...e];if(t>=1)return e;let i=Math.floor(r.length*Math.max(0,t));return r.map((e,t)=>t<i||e===` `?e:ak[Math.floor(n()*36)]).join(``)}var sk=e=>e.length===0?0:Math.min(24,Math.max(6,Math.ceil([...e].length/2)));function ck(e,t){let[n,r]=(0,l.useState)(e),i=(0,l.useRef)(e);return(0,l.useEffect)(()=>{if(!t||e===i.current){i.current=e,r(e);return}i.current=e;let n=sk(e);if(n===0){r(e);return}let a=0,o=setInterval(()=>{a++,r(ok(e,a/n)),a>=n&&clearInterval(o)},320/n);return()=>clearInterval(o)},[e,t]),n}function lk(e){let t=e.currentTarget,n=t.getBoundingClientRect(),r=document.createElement(`span`);r.className=`hud-ripple`;let i=Math.max(n.width,n.height)*2;r.style.width=r.style.height=`${i}px`,r.style.left=`${e.clientX-n.left-i/2}px`,r.style.top=`${e.clientY-n.top-i/2}px`,t.appendChild(r),r.addEventListener(`animationend`,()=>r.remove(),{once:!0}),setTimeout(()=>r.remove(),900)}function uk({items:e,animations:t,onAction:n}){let[r,i]=(0,l.useState)(null),a=(0,l.useRef)(void 0);if((0,l.useEffect)(()=>()=>clearTimeout(a.current),[]),e.length===0)return null;let o=e=>{t!==`off`&&(i(e.id),clearTimeout(a.current),a.current=setTimeout(()=>i(null),650)),n(e)};return(0,p.jsxs)(B,{id:`launcher`,label:`Quick launch`,wholeBox:!0,testId:`launcher`,className:`hud hud-launcher${t===`full`?` hud-boot`:``}`,children:[(0,p.jsx)(`div`,{className:`hud-kicker`,children:`Quick launch`}),(0,p.jsx)(`ul`,{className:`hud-stack`,children:e.map((e,n)=>(0,p.jsx)(`li`,{className:`hud-tab hud-cut${r===e.id?` engaged`:``}${t===`full`?` hud-boot`:``}`,style:{"--i":n+1},children:(0,p.jsxs)(`button`,{type:`button`,className:`hud-tab-main`,"aria-label":e.label,onPointerDown:t===`off`?void 0:lk,onClick:()=>o(e),children:[(0,p.jsx)(`span`,{className:`hud-icon`,"aria-hidden":`true`,children:e.icon}),(0,p.jsx)(`span`,{className:`hud-tab-label`,children:e.label}),(0,p.jsx)(`span`,{className:`hud-tab-engaged`,"aria-hidden":`true`,children:`ENGAGED`}),(0,p.jsx)(`span`,{className:`hud-sweep`,"aria-hidden":`true`}),(0,p.jsx)(`span`,{className:`hud-scan`,"aria-hidden":`true`})]})},e.id))})]})}var dk=(e,t=18)=>(0,p.jsx)(`svg`,{width:t,height:t,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`1.8`,strokeLinecap:`round`,strokeLinejoin:`round`,"aria-hidden":`true`,children:e}),fk=()=>dk((0,p.jsx)(`path`,{d:`M7 4.5v15l12-7.5z`,fill:`currentColor`})),pk=()=>dk((0,p.jsxs)(p.Fragment,{children:[(0,p.jsx)(`rect`,{x:`6`,y:`4.5`,width:`4`,height:`15`,fill:`currentColor`}),(0,p.jsx)(`rect`,{x:`14`,y:`4.5`,width:`4`,height:`15`,fill:`currentColor`})]})),mk=()=>dk((0,p.jsxs)(p.Fragment,{children:[(0,p.jsx)(`path`,{d:`M5 5v14l10-7z`,fill:`currentColor`}),(0,p.jsx)(`path`,{d:`M18 5v14`})]})),hk=()=>dk((0,p.jsxs)(p.Fragment,{children:[(0,p.jsx)(`path`,{d:`M19 5v14L9 12z`,fill:`currentColor`}),(0,p.jsx)(`path`,{d:`M6 5v14`})]})),gk=()=>dk((0,p.jsxs)(p.Fragment,{children:[(0,p.jsx)(`path`,{d:`M3 7h3.5c3 0 4 2 5.5 5s2.500 5 5.500 5H21`}),(0,p.jsx)(`path`,{d:`M3 17h3.5c1.500 0 2.500-.6 3.400-1.800M13.500 8.800C14.500 7.600 15.500 7 17 7h4`}),(0,p.jsx)(`path`,{d:`m18.500 4.500 2.500 2.500-2.500 2.500M18.500 14.500l2.500 2.500-2.500 2.500`})]})),_k=()=>dk((0,p.jsxs)(p.Fragment,{children:[(0,p.jsx)(`path`,{d:`M17 3l3 3-3 3`}),(0,p.jsx)(`path`,{d:`M4 11V9a3 3 0 0 1 3-3h13M7 21l-3-3 3-3`}),(0,p.jsx)(`path`,{d:`M20 13v2a3 3 0 0 1-3 3H4`})]})),vk=()=>dk((0,p.jsxs)(p.Fragment,{children:[(0,p.jsx)(`path`,{d:`M4 9.500v5h3.500L12 18.500v-13L7.500 9.500z`,fill:`currentColor`}),(0,p.jsx)(`path`,{d:`M15.500 9a4 4 0 0 1 0 6M18 6.500a7.500 7.500 0 0 1 0 11`})]})),yk=()=>dk((0,p.jsxs)(p.Fragment,{children:[(0,p.jsx)(`path`,{d:`M4 9.500v5h3.500L12 18.500v-13L7.500 9.500z`,fill:`currentColor`}),(0,p.jsx)(`path`,{d:`m16 9 5 6M21 9l-5 6`})]})),bk=()=>dk((0,p.jsx)(`path`,{d:`M4 9V4h5M20 9V4h-5M4 15v5h5M20 15v5h-5`})),xk=()=>dk((0,p.jsx)(`path`,{d:`M9 4v5H4M15 4v5h5M9 20v-5H4M15 20v-5h5`})),Sk=()=>dk((0,p.jsx)(`path`,{d:`M6 6l12 12M18 6 6 18`})),Ck=()=>dk((0,p.jsx)(`path`,{d:`M9 18V6l10-2v12`}),22),wk=56,Tk=()=>({bars:new Float32Array(wk),bass:0,left:0,right:0});function Ek(e,t,n,r,i){let a=n?.82:.9;if(t&&n){t.getByteFrequencyData(i);let n=Math.min(i.length,96);for(let t=0;t<wk;t++){let r=Math.min(n-1,Math.floor((t/wk)**1.6*n));e.bars[t]=Math.max((i[r]??0)/255,e.bars[t]*a)}}else if(n)for(let t=0;t<wk;t++)e.bars[t]=Math.max(.12+.28*Math.abs(Math.sin(r/420+t*.55)*Math.cos(r/900+t*.21)),e.bars[t]*a);else for(let t=0;t<wk;t++)e.bars[t]=e.bars[t]*a;let o=0;for(let t=0;t<6;t++)o+=e.bars[t];e.bass=Math.min(1,o/6*1.15);let s=0,c=0;for(let t=0;t<wk/2;t++)s+=e.bars[t],c+=e.bars[t+wk/2];e.left=Math.min(1,s/(wk/2)*1.6),e.right=Math.min(1,c/(wk/2)*3.2)}function Dk({progress:e,playing:t,cover:n,analyser:r,levels:i,visualizer:a,animate:o,size:s}){let c=(0,l.useRef)(null),u=(0,l.useRef)(null),d=(0,l.useRef)(new Uint8Array(new ArrayBuffer(128)));(0,l.useEffect)(()=>{let e=c.current,n=e?.getContext(`2d`);if(!e||!n||!o)return;let l=0,f=Math.min(2,window.devicePixelRatio||1);e.width=e.height=Math.round(s*f);let p=getComputedStyle(e).getPropertyValue(`--accent`).trim()||`#3fd8ff`,m=e=>{if(Ek(i,r,t,e,d.current),u.current?.style.setProperty(`--bass`,i.bass.toFixed(3)),n.setTransform(f,0,0,f,0,0),n.clearRect(0,0,s,s),a){let e=s/2,t=s*.335,r=s*.135;n.lineCap=`round`,n.lineWidth=Math.max(1.5,s/90);for(let a=0;a<wk;a++){let o=a/wk*Math.PI*2-Math.PI/2,s=i.bars[a],c=2+s*r;n.strokeStyle=p,n.globalAlpha=.35+s*.65,n.beginPath(),n.moveTo(e+Math.cos(o)*t,e+Math.sin(o)*t),n.lineTo(e+Math.cos(o)*(t+c),e+Math.sin(o)*(t+c)),n.stroke()}n.globalAlpha=1}(t||!i.bars.every(e=>e<.01)||a)&&(l=requestAnimationFrame(m))};return l=requestAnimationFrame(m),()=>cancelAnimationFrame(l)},[r,t,a,o,s,i]);let f=Math.max(0,Math.min(1,e))*100;return(0,p.jsxs)(`div`,{ref:u,className:`hud-dial${t?` playing`:``}`,style:{width:s,height:s},role:`img`,"aria-label":`Playback dial`,children:[(0,p.jsxs)(`svg`,{className:`hud-dial-svg`,viewBox:`0 0 200 200`,"aria-hidden":`true`,children:[(0,p.jsx)(`circle`,{className:`hud-dial-ticks`,cx:`100`,cy:`100`,r:`96`}),(0,p.jsx)(`circle`,{className:`hud-dial-track`,cx:`100`,cy:`100`,r:`88`}),(0,p.jsx)(`circle`,{className:`hud-dial-arc`,cx:`100`,cy:`100`,r:`88`,pathLength:`100`,strokeDasharray:`${f} 100`,transform:`rotate(-90 100 100)`}),(0,p.jsx)(`circle`,{className:`hud-dial-inner`,cx:`100`,cy:`100`,r:`62`}),(0,p.jsxs)(`g`,{className:`hud-needle`,children:[(0,p.jsx)(`line`,{x1:`100`,y1:`100`,x2:`100`,y2:`14`}),(0,p.jsx)(`circle`,{cx:`100`,cy:`14`,r:`2.500`})]})]}),(0,p.jsx)(`canvas`,{ref:c,className:`hud-spectrum`,style:{width:s,height:s},"aria-hidden":`true`}),(0,p.jsx)(`div`,{className:`hud-cover`,style:n?{backgroundImage:`url("${n}")`}:void 0,children:!n&&(0,p.jsx)(Ck,{})})]})}var Ok=e=>{let t=Math.max(0,Math.floor(Number.isFinite(e)?e:0));return`${Math.floor(t/60)}:${String(t%60).padStart(2,`0`)}`},kk=new Map,Ak=e=>{let t=Wl(e);return t&&t.source===`local`?t.id:null},jk=e=>Wl(e)?.source===`spotify`,Mk=e=>Wl(e)?.source===`soundcloud`,Nk=e=>Wl(e)?.source===`audius`,Pk={spotify:`Spotify`,soundcloud:`SoundCloud`,audius:`Audius`};function Fk(e){let[t,n]=(0,l.useState)(e?kk.get(e)??!1:!1);return(0,l.useEffect)(()=>{if(!e)return n(!1);if(kk.has(e))return n(kk.get(e));let t=!0,r=new Image;r.onload=()=>{kk.set(e,!0),t&&n(!0)},r.onerror=()=>{kk.set(e,!1),t&&n(!1)};let i=Ak(e);return i?(r.src=`/api/music/cover/${i}`,()=>{t=!1}):n(!1)},[e]),e&&t?`/api/music/cover/${Ak(e)}`:null}async function Ik(e,t){let n=await fetch(`/api/music/library?q=${encodeURIComponent(e)}&limit=${t}`);return n.ok?await n.json():{tracks:[],total:0}}function Lk(){let[e,t]=(0,l.useState)(null);return(0,l.useEffect)(()=>{let e=!0;return fetch(`/api/music/sources`).then(e=>e.ok?e.json():null).then(n=>{let r={};for(let e of[`spotify`,`soundcloud`,`audius`]){let t=n?.sources?.find(t=>t.id===e)?.status;t&&(r[e]={connected:t.connected,needs:t.needs})}e&&n&&t(r)}).catch(()=>{}),()=>{e=!1}},[]),e}async function Rk(e,t,n){let r=await fetch(`/api/music/search?q=${encodeURIComponent(t)}&source=${e}&limit=${n}`);if(!r.ok)return{tracks:[],total:0};let i=((await r.json()).tracks??[]).map(e=>({id:e.ref,title:e.title,artist:e.artist,album:e.album,durationSec:e.durationSec}));return{tracks:i,total:i.length}}var zk=e=>({id:e.id,title:e.title,artist:e.artist,album:e.album,durationSec:e.durationSec});function Bk({levels:e,animate:t,side:n}){let r=(0,l.useRef)(null);return(0,l.useEffect)(()=>{if(!t)return;let i=0,a=r.current,o=()=>{if(a){let t=n===`left`?e.left:e.right,r=Math.round(t*12);a.querySelectorAll(`i`).forEach((e,t)=>e.classList.toggle(`on`,t<r))}i=requestAnimationFrame(o)};return i=requestAnimationFrame(o),()=>cancelAnimationFrame(i)},[e,t,n]),(0,p.jsx)(`div`,{ref:r,className:`hud-levels ${n}`,"aria-hidden":`true`,children:Array.from({length:12},(e,t)=>(0,p.jsx)(`i`,{},t))})}function Vk({player:e,anim:t}){let{state:n,dispatch:r}=e,i=(0,l.useCallback)(async()=>{if(n.queue.length>0)return r({type:`resume`});let e=await Ik(``,500);r({type:`play`,tracks:e.tracks.map(zk),mode:`replace`,...n.shuffle?{shuffle:!0}:{}})},[n.queue.length,n.shuffle,r]),a=e=>n=>{t!==`off`&&lk(n),e()};return(0,p.jsxs)(`div`,{className:`hud-controls`,role:`group`,"aria-label":`Player controls`,children:[(0,p.jsx)(`button`,{type:`button`,className:`hud-btn`,"aria-label":`Shuffle`,"aria-pressed":n.shuffle,title:`Shuffle`,onClick:()=>r({type:`shuffle`}),children:(0,p.jsx)(gk,{})}),(0,p.jsx)(`button`,{type:`button`,className:`hud-btn`,"aria-label":`Previous track`,title:`Previous`,onPointerDown:a(()=>{}),onClick:()=>r({type:`previous`}),children:(0,p.jsx)(hk,{})}),(0,p.jsx)(`button`,{type:`button`,className:`hud-btn hud-btn-main`,"aria-label":n.playing?`Pause`:`Play`,title:n.playing?`Pause`:`Play`,onPointerDown:a(()=>{}),onClick:()=>n.playing?r({type:`pause`}):void i(),children:n.playing?(0,p.jsx)(pk,{}):(0,p.jsx)(fk,{})}),(0,p.jsx)(`button`,{type:`button`,className:`hud-btn`,"aria-label":`Next track`,title:`Next`,onPointerDown:a(()=>{}),onClick:()=>r({type:`next`}),children:(0,p.jsx)(mk,{})}),(0,p.jsxs)(`button`,{type:`button`,className:`hud-btn${n.repeat===`off`?``:` on`}`,"aria-label":`Repeat: ${n.repeat}`,title:`Repeat: ${n.repeat}`,onClick:()=>r({type:`repeat`,mode:n.repeat===`off`?`all`:n.repeat===`all`?`one`:`off`}),children:[(0,p.jsx)(_k,{}),n.repeat===`one`&&(0,p.jsx)(`sup`,{children:`1`})]})]})}function Hk({player:e}){let{state:t,dispatch:n}=e,r=t.duration>0?t.position/t.duration*100:0;return(0,p.jsxs)(`div`,{className:`hud-timeline`,children:[(0,p.jsx)(`span`,{className:`hud-time`,children:Ok(t.position)}),(0,p.jsx)(`input`,{type:`range`,className:`hud-range`,"aria-label":`Position`,min:0,max:Math.max(1,Math.floor(t.duration)),step:1,value:Math.min(Math.floor(t.position),Math.max(1,Math.floor(t.duration))),style:{"--fill":`${r}%`},disabled:t.duration<=0,onChange:e=>n({type:`seek`,seconds:Number(e.target.value)})}),(0,p.jsxs)(`span`,{className:`hud-time`,children:[`-`,Ok(Math.max(0,t.duration-t.position))]})]})}function Uk({player:e}){let{state:t,dispatch:n}=e;return(0,p.jsxs)(`div`,{className:`hud-volume`,children:[(0,p.jsx)(`button`,{type:`button`,className:`hud-btn`,"aria-label":t.muted?`Unmute`:`Mute`,onClick:()=>n({type:`mute`}),children:t.muted||t.volume===0?(0,p.jsx)(yk,{}):(0,p.jsx)(vk,{})}),(0,p.jsx)(`input`,{type:`range`,className:`hud-range`,"aria-label":`Volume`,min:0,max:100,value:t.muted?0:t.volume,style:{"--fill":`${t.muted?0:t.volume}%`},onChange:e=>n({type:`volume`,level:Number(e.target.value)})})]})}function Wk({player:e,anim:t}){let{state:n,dispatch:r}=e,[i,a]=(0,l.useState)(n.queue.length?`queue`:`library`),[o,s]=(0,l.useState)(``),[c,u]=(0,l.useState)(`folder`),[d,f]=(0,l.useState)(null),m=Lk(),h=[`spotify`,`soundcloud`,`audius`].filter(e=>m?.[e]?.connected),g=c!==`folder`&&h.includes(c)?c:null,_=g?m?.[g]?.needs:null;(0,l.useEffect)(()=>{if(i!==`library`)return;let e=!0;if(g&&!o.trim()){f(null);return}let t=()=>g?Rk(g,o.trim(),30):Ik(o,100),n=setTimeout(()=>void t().then(t=>e&&f(t)),o?250:0);return()=>{e=!1,clearTimeout(n)}},[i,o,g]);let v=i===`queue`?n.queue.map((e,t)=>({track:e,index:t})):(d?.tracks??[]).map((e,t)=>({track:zk(e),index:t}));return(0,p.jsxs)(`div`,{className:`hud-playlist`,children:[(0,p.jsxs)(`div`,{className:`hud-tabs`,role:`tablist`,children:[[`queue`,`library`].map(e=>(0,p.jsx)(`button`,{type:`button`,role:`tab`,"aria-selected":i===e,className:`hud-chip${i===e?` on`:``}`,onClick:()=>a(e),children:e===`queue`?`Queue (${n.queue.length})`:`Library`},e)),i===`queue`&&n.queue.length>0&&(0,p.jsx)(`button`,{type:`button`,className:`hud-chip`,onClick:()=>r({type:`clear`}),children:`Clear`})]}),i===`library`&&h.length>0&&(0,p.jsx)(`div`,{className:`hud-tabs`,role:`tablist`,"aria-label":`Where to look`,children:[`folder`,...h].map(e=>(0,p.jsx)(`button`,{type:`button`,role:`tab`,"aria-selected":c===e,className:`hud-chip${c===e?` on`:``}`,onClick:()=>{u(e),f(null)},children:e===`folder`?`Folder`:Pk[e]},e))}),i===`library`&&(0,p.jsx)(`input`,{className:`hud-search`,type:`search`,placeholder:`Search title, artist or album`,"aria-label":`Search the music`,value:o,onChange:e=>s(e.target.value)}),(0,p.jsxs)(`ul`,{className:`hud-list`,children:[v.length===0&&(0,p.jsx)(`li`,{className:`hud-empty`,children:i===`queue`?`The queue is empty.`:g&&!o.trim()?`Type to search ${Pk[g]}.`:d?`No music matches.`:`Loading…`}),i===`library`&&g&&_&&(0,p.jsx)(`li`,{className:`hud-empty`,children:_}),v.map(({track:e,index:a},o)=>{let s=i===`queue`&&a===n.index;return(0,p.jsxs)(`li`,{className:`hud-tab hud-cut${s?` current`:``}${t===`full`?` hud-boot`:``}`,style:{"--i":Math.min(o,12)},children:[(0,p.jsxs)(`button`,{type:`button`,className:`hud-tab-main`,"aria-current":s?`true`:void 0,onPointerDown:t===`off`?void 0:lk,onClick:()=>r(i===`queue`?{type:`jump`,index:a}:{type:`play`,tracks:(d?.tracks??[]).map(zk),mode:`replace`,start:a}),children:[(0,p.jsx)(`span`,{className:`hud-tab-title`,children:e.title}),(0,p.jsxs)(`small`,{children:[e.artist||e.album,jk(e.id)&&(0,p.jsx)(`em`,{className:`hud-source`,children:`SPOTIFY`}),Mk(e.id)&&(0,p.jsx)(`em`,{className:`hud-source`,children:`SOUNDCLOUD`}),Nk(e.id)&&(0,p.jsx)(`em`,{className:`hud-source`,children:`AUDIUS`})]})]}),i===`library`&&(0,p.jsx)(`button`,{type:`button`,className:`hud-mini`,"aria-label":`Add ${e.title} to the queue`,title:`Add to the queue`,onClick:()=>r({type:`play`,tracks:[e],mode:`add`}),children:`+`}),i===`queue`&&(0,p.jsx)(`button`,{type:`button`,className:`hud-mini`,"aria-label":`Remove ${e.title} from the queue`,title:`Remove`,onClick:()=>r({type:`remove`,index:a}),children:`×`})]},`${e.id}-${a}`)})]})]})}function Gk({player:e,music:t,animations:n}){let{state:r,dispatch:i,current:a,blocked:o,notice:s,analyser:c,unlock:u}=e,d=(0,l.useMemo)(Tk,[]),f=Fk(a?.id),m=r.view===`full`,h=ck(a?.title??``,n===`full`);if(!t?.folderSet||r.view===`hidden`)return null;let g=r.duration>0?r.position/r.duration:0,_=n!==`off`;return(0,p.jsxs)(B,{id:`music`,label:`Music player`,wholeBox:!0,testId:`music`,className:`hud hud-music hud-cut ${m?`full`:`mini`}${r.playing?` playing`:``}${n===`full`?` hud-boot`:``}`,children:[(0,p.jsxs)(`header`,{className:`hud-music-head`,children:[(0,p.jsx)(`span`,{className:`hud-kicker`,children:`Media player`}),(0,p.jsxs)(`span`,{className:`hud-head-actions`,children:[(0,p.jsx)(`button`,{type:`button`,className:`hud-btn`,"aria-label":m?`Smaller player`:`Bigger player`,title:m?`Smaller`:`Bigger`,onClick:()=>i({type:`view`,view:m?`mini`:`full`}),children:m?(0,p.jsx)(xk,{}):(0,p.jsx)(bk,{})}),(0,p.jsx)(`button`,{type:`button`,className:`hud-btn`,"aria-label":`Hide the player`,title:`Hide (the music keeps playing)`,onClick:()=>i({type:`view`,view:`hidden`}),children:(0,p.jsx)(Sk,{})})]})]}),(0,p.jsxs)(`div`,{className:`hud-music-body`,children:[(0,p.jsxs)(`div`,{className:`hud-music-left`,children:[m&&(0,p.jsx)(Bk,{levels:d,animate:_,side:`left`}),(0,p.jsx)(Dk,{progress:g,playing:r.playing,cover:f,analyser:c,levels:d,visualizer:t.visualizer,animate:_,size:m?250:112}),m&&(0,p.jsx)(Bk,{levels:d,animate:_,side:`right`})]}),(0,p.jsxs)(`div`,{className:`hud-music-main`,children:[(0,p.jsxs)(`div`,{className:`hud-now`,"aria-live":`polite`,children:[(0,p.jsx)(`b`,{className:`hud-title`,children:a?h:`Nothing playing`}),(0,p.jsxs)(`small`,{className:`hud-sub`,children:[a?[a.artist,a.album].filter(Boolean).join(` — `):`Press play, or ask for some music.`,a&&jk(a.id)&&(0,p.jsx)(`em`,{className:`hud-source`,children:`SPOTIFY`}),a&&Mk(a.id)&&(0,p.jsx)(`em`,{className:`hud-source`,children:`SOUNDCLOUD`}),a&&Nk(a.id)&&(0,p.jsx)(`em`,{className:`hud-source`,children:`AUDIUS`}),e.remote&&(0,p.jsx)(`em`,{className:`hud-source`,children:`THIS PC`})]})]}),(0,p.jsx)(Hk,{player:e}),(0,p.jsx)(Vk,{player:e,anim:n}),m&&(0,p.jsx)(Uk,{player:e}),s&&(0,p.jsx)(`p`,{className:`hud-notice`,role:`status`,children:s}),o&&(0,p.jsx)(`button`,{type:`button`,className:`hud-unlock`,onClick:u,children:`Tap to enable sound`})]}),m&&(0,p.jsx)(Wk,{player:e,anim:n})]})]})}var Kk=/^spotify:/,qk=class{local;makeSpotify;active;spotify=null;listeners=new Map;wrapped=new Map;vol=1;mute=!1;pre=``;constructor(e,t){this.local=e,this.makeSpotify=t,this.active=e}get element(){return this.local}get error(){return this.active.error??null}wrap(e){let t=this.wrapped.get(e);return t||(t={local:()=>{this.active===this.local&&e()},spot:()=>{this.spotify&&this.active===this.spotify&&e()}},this.wrapped.set(e,t)),t}spot(){if(!this.spotify){let e=this.makeSpotify();e.volume=this.vol,e.muted=this.mute,e.preload=this.pre;for(let[t,n]of this.listeners)for(let r of n)e.addEventListener(t,this.wrap(r).spot);this.spotify=e}return this.spotify}dispose(){this.spotify?.dispose?.(),this.spotify=null,this.active=this.local}get src(){return this.active.src}set src(e){let t=Kk.test(e)?this.spot():this.local;t===this.active?e===``&&this.active.pause():(this.active.pause(),this.active=t),this.active.src=e}get currentTime(){return this.active.currentTime}set currentTime(e){this.active.currentTime=e}get duration(){return this.active.duration}get paused(){return this.active.paused}get volume(){return this.vol}set volume(e){this.vol=e,this.local.volume=e,this.spotify&&(this.spotify.volume=e)}get muted(){return this.mute}set muted(e){this.mute=e,this.local.muted=e,this.spotify&&(this.spotify.muted=e)}get preload(){return this.pre}set preload(e){this.pre=e,this.local.preload=e,this.spotify&&(this.spotify.preload=e)}play(){return this.active.play()}pause(){this.active.pause()}addEventListener(e,t){let n=this.listeners.get(e);n||this.listeners.set(e,n=new Set),n.add(t);let r=this.wrap(t);this.local.addEventListener(e,r.local),this.spotify?.addEventListener(e,r.spot)}removeEventListener(e,t){this.listeners.get(e)?.delete(t);let n=this.wrap(t);this.local.removeEventListener(e,n.local),this.spotify?.removeEventListener(e,n.spot)}},Jk=/^spotify:([A-Za-z0-9_-]{1,64})$/,Yk=`Spotify Premium is needed to play on this screen.`;async function Xk(){let e=await fetch(`/api/music/spotify/token`,{cache:`no-store`});if(!e.ok)throw Error(`Spotify is not connected.`);return(await e.json()).accessToken}function Zk(){let e=window;return e.Spotify?Promise.resolve(e.Spotify):new Promise((t,n)=>{e.onSpotifyWebPlaybackSDKReady=()=>e.Spotify?t(e.Spotify):n(Error(`no sdk`));let r=document.createElement(`script`);r.src=`https://sdk.scdn.co/spotify-player.js`,r.async=!0,r.onerror=()=>n(Error(`blocked`)),document.head.appendChild(r)})}function Qk(e){let t=e.fetch??((...e)=>fetch(...e)),n=e.now??Date.now,r=new Map,i=null,a=null,o=null,s=null,c=!1,l=null,u=null,d=0,f=0,p=0,m=!0,h=1,g=!1,_,v=e=>{for(let t of r.get(e)??[])t()},y=()=>g?0:h,b=()=>{_&&clearInterval(_),_=void 0},x=()=>{_||=setInterval(()=>v(`timeupdate`),250)},S={error:null,preload:``,get src(){return s??``},set src(e){let t=Jk.exec(e);c=e!==``&&!t,s=t?e:null,l=null,u=null,d=0,p=0,S.error=null,t||b()},get currentTime(){return m?d:d+(n()-f)/1e3},set currentTime(e){d=e,f=n(),i?.seek(Math.round(e*1e3)).catch(()=>{})},get duration(){return p},get paused(){return m},get volume(){return h},set volume(e){h=e,i?.setVolume(y()).catch(()=>{})},get muted(){return g},set muted(e){g=e,i?.setVolume(y()).catch(()=>{})},async play(){if(c||!s)throw Error(`That is not a Spotify track.`);let r=Jk.exec(s),a=s,o=await T();if(s!==a)return;if(l===s){await i?.resume().catch(()=>{}),m=!1,f=n(),x();return}let u=await e.getToken().catch(()=>null);if(!u)throw C(`Spotify is not connected. Connect it in Plugins, Spotify.`);let d;try{d=await t(`https://api.spotify.com/v1/me/player/play?device_id=${encodeURIComponent(o)}`,{method:`PUT`,headers:{authorization:`Bearer ${u}`,"content-type":`application/json`},body:JSON.stringify({uris:[`spotify:track:${r[1]}`]})})}catch{throw C(`Friend could not reach Spotify right now.`)}if(d.status===403)throw C(Yk);if(d.status===401)throw C(`Spotify sign-in has ended. Reconnect Spotify in Plugins, Spotify.`);if(d.status===404)throw C(`Spotify could not find this screen or that track.`);if(d.status===429)throw C(`Spotify is asking Friend to slow down. Try again in a minute.`);if(!d.ok)throw C(`Spotify could not play that.`);s===a&&(l=a,m=!1,f=n(),x())},pause(){m=!0,d+=(n()-f)/1e3,f=n(),b(),i?.pause().catch(()=>{})},dispose(){b();try{i?.disconnect()}catch{}i=null,a=null,s=null,l=null},addEventListener(e,t){let n=r.get(e);n||r.set(e,n=new Set),n.add(t)},removeEventListener(e,t){r.get(e)?.delete(t)}};function C(e){S.error=e,m=!0,b(),v(`error`);let t=Error(e),n=o;return o=null,n?.reject(t),t}function w(e){if(!e)return;d=e.position/1e3,f=n(),p=e.duration/1e3,m=e.paused,v(`timeupdate`),v(`loadedmetadata`),v(`durationchange`);let t=s?Jk.exec(s)?.[1]:void 0;t&&e.paused&&e.position===0&&u!==s&&(e.track_window.previous_tracks??[]).some(e=>e.id===t)&&(u=s,b(),v(`ended`))}function T(){if(a)return Promise.resolve(a);if(o)return o.promise;let t,n,r=new Promise((e,r)=>{t=e,n=r}),s={promise:r,resolve:t,reject:n};o=s;let c=setTimeout(()=>{o===s&&C(`Spotify's player did not start. Check that this browser allows Spotify's player, then try again.`)},e.readyTimeoutMs??15e3),l=()=>clearTimeout(c);return r.then(l,l),(async()=>{try{if(!i){let t;try{t=await(e.loadSdk??Zk)()}catch{o===s&&C(`Spotify's player could not be loaded. Check that nothing blocks sdk.scdn.co.`);return}let n=new t.Player({name:e.deviceName??`Friend`,volume:y(),getOAuthToken:t=>{e.getToken().then(t,()=>{})}});i=n,n.addListener(`ready`,(e=>{a=e.device_id;let t=o;o=null,t?.resolve(e.device_id)})),n.addListener(`not_ready`,(()=>{a=null})),n.addListener(`player_state_changed`,(e=>w(e))),n.addListener(`account_error`,(()=>void C(Yk))),n.addListener(`authentication_error`,(()=>void C(`Spotify sign-in has ended. Reconnect Spotify in Plugins, Spotify.`))),n.addListener(`initialization_error`,(()=>void C(`Spotify's player does not work in this browser.`))),n.addListener(`playback_error`,(()=>void C(`Spotify could not play that.`)))}!await i.connect()&&o===s&&C(`Spotify's player could not connect.`)}catch{o===s&&C(`Spotify's player could not connect.`)}})(),r}return S}var $k=e=>{let t=Wl(e);return t?t.source===`local`?`/api/music/track/${t.id}`:t.source===`soundcloud`||t.source===`audius`?`/api/music/stream/${e}`:e:`/api/music/track/${e}`},eA=(e,t)=>vu(e,t),tA=`friend.music`,nA=1e3,rA=1.5,iA=()=>{try{return JSON.parse(localStorage.getItem(tA)??`{}`)}catch{return{}}},aA=e=>{try{localStorage.setItem(tA,JSON.stringify({volume:e.volume,muted:e.muted,shuffle:e.shuffle,repeat:e.repeat,view:e.view}))}catch{}};function oA({music:e,cmd:t,send:n,connection:r,createAudio:i,createSpotify:a,remote:o=!1}){let[s,c]=(0,l.useReducer)(eA,void 0,()=>{let e=iA();return mu({volume:e.volume??70,shuffle:e.shuffle??!1,repeat:e.repeat??`all`,view:e.view??`mini`})}),[u,d]=(0,l.useState)(!1),[f,p]=(0,l.useState)(null),[m,h]=(0,l.useState)(null),g=(0,l.useRef)(null),_=(0,l.useRef)(!1),v=(0,l.useRef)(s);v.current=s;let y=(0,l.useRef)(!1),b=(0,l.useRef)(null),x=(0,l.useRef)(0),S=(0,l.useRef)(!1);(0,l.useEffect)(()=>{if(!e||S.current)return;S.current=!0;let t=iA();c({type:`volume`,level:t.volume??e.volume}),c({type:`repeat`,mode:t.repeat??e.repeat}),(t.shuffle??e.shuffle)&&c({type:`shuffle`,on:!0}),c({type:`view`,view:t.view??e.startView}),t.muted&&c({type:`mute`,on:!0})},[e]);let C=()=>{if(!g.current){let e=new qk(i?i():new Audio,a??(()=>Qk({getToken:Xk})));e.preload=`auto`,g.current=e}return g.current},w=(0,l.useRef)(!1),T=(0,l.useCallback)(()=>{let e=g.current;if(e&&e.src){w.current=!0;try{let t=e.play();t&&typeof t.then==`function`?t.then(()=>{w.current=!1,d(!1)},()=>{w.current=!1;let e=g.current?.error??null;e?p(e):d(!0)}):(w.current=!1,d(!1))}catch{w.current=!1,d(!0)}E.current||O()}},[]),E=(0,l.useRef)(!1),D=(0,l.useRef)(null),O=()=>{let e=g.current,t=e instanceof qk?e.element:e,n=typeof window<`u`?window.AudioContext??window.webkitAudioContext:void 0;if(t&&n&&typeof t.play==`function`)try{let e=new n;D.current=e;let r=e.createMediaElementSource(t),i=e.createAnalyser();i.fftSize=256,i.smoothingTimeConstant=.82,r.connect(i),i.connect(e.destination),E.current=!0,h(i)}catch{E.current=!0}};(0,l.useEffect)(()=>{if(o)return;let e=C(),t=0,n=()=>{let n=Date.now();n-t<250||(t=n,c({type:`time`,position:e.currentTime||0,duration:Number.isFinite(e.duration)?e.duration:0}))},r=()=>c({type:`time`,position:e.currentTime||0,duration:Number.isFinite(e.duration)?e.duration:0}),i=()=>c({type:`ended`}),a=()=>{let t=e.error??null;p(t),c(t?{type:`pause`}:{type:`failed`})};return e.addEventListener(`timeupdate`,n),e.addEventListener(`loadedmetadata`,r),e.addEventListener(`durationchange`,r),e.addEventListener(`ended`,i),e.addEventListener(`error`,a),()=>{e.removeEventListener(`timeupdate`,n),e.removeEventListener(`loadedmetadata`,r),e.removeEventListener(`durationchange`,r),e.removeEventListener(`ended`,i),e.removeEventListener(`error`,a),e.pause(),D.current?.close().catch(()=>{}),D.current=null,e.dispose(),b.current=null,g.current=null,E.current=!1,h(null)}},[o]),(0,l.useEffect)(()=>{o&&c({type:`stop`})},[o]);let k=s.index>=0?s.queue[s.index]??null:null;(0,l.useEffect)(()=>{let e=g.current;if(o||!e)return;let t=k?.id??null;if(t!==b.current){if(b.current=t,!t){e.pause(),e.src=``;return}p(null),e.src=$k(t),s.playing&&T()}},[k?.id,s.playing,T,o]),(0,l.useEffect)(()=>{let e=g.current;!o&&e&&e.src&&(s.playing&&e.paused&&!_.current&&!w.current?T():!s.playing&&!e.paused&&e.pause())},[s.playing,s.position,T,o]),(0,l.useEffect)(()=>{let e=g.current;e&&(e.volume=s.volume/100,e.muted=s.muted)},[s.volume,s.muted]),(0,l.useEffect)(()=>{let e=g.current;e&&e.src&&Math.abs((e.currentTime||0)-s.position)>rA&&(e.currentTime=s.position)},[s.position]),(0,l.useEffect)(()=>aA(s),[s.volume,s.muted,s.shuffle,s.repeat,s.view]),(0,l.useEffect)(()=>{if(!t||t.n===x.current)return;x.current=t.n;let e=yu(t.command);e&&c(e)},[t]),(0,l.useEffect)(()=>{let e=()=>{y.current=!0,_.current&&T()};return window.addEventListener(`pointerdown`,e,{passive:!0}),window.addEventListener(`keydown`,e),()=>{window.removeEventListener(`pointerdown`,e),window.removeEventListener(`keydown`,e)}},[T]),_.current=u;let A=(0,l.useRef)(0);return(0,l.useEffect)(()=>{if(r!==`open`||o)return;let e=()=>{let e=v.current,t=e.index>=0?e.queue[e.index]:void 0;A.current=Date.now(),n({type:`music.state`,state:{playing:e.playing,trackId:t?.id??null,title:t?.title??``,artist:t?.artist??``,album:t?.album??``,position:e.position,duration:e.duration,volume:e.volume,muted:e.muted,shuffle:e.shuffle,repeat:e.repeat,view:e.view,queue:e.queue.slice(0,50).map(e=>({id:e.id,title:e.title.slice(0,200)})),index:e.index,active:(typeof document>`u`||document.visibilityState===`visible`)&&y.current}})};e();let t=setInterval(()=>s.playing&&Date.now()-A.current>=nA&&e(),nA);return()=>clearInterval(t)},[r,o,k?.id,s.playing,s.volume,s.muted,s.shuffle,s.repeat,s.view,s.queue.length,s.index]),(0,l.useEffect)(()=>{let e=typeof navigator<`u`?navigator.mediaSession:void 0;if(e&&!o)try{k&&typeof MediaMetadata<`u`&&(e.metadata=new MediaMetadata({title:k.title,artist:k.artist,album:k.album,artwork:[{src:`/api/music/cover/${k.id}`}]})),e.playbackState=s.playing?`playing`:k?`paused`:`none`,e.setActionHandler(`play`,()=>c({type:`resume`})),e.setActionHandler(`pause`,()=>c({type:`pause`})),e.setActionHandler(`previoustrack`,()=>c({type:`previous`})),e.setActionHandler(`nexttrack`,()=>c({type:`next`})),e.setActionHandler(`seekto`,e=>typeof e.seekTime==`number`&&c({type:`seek`,seconds:e.seekTime}))}catch{}},[k?.id,s.playing,o]),{remote:!1,state:s,dispatch:c,current:k,blocked:u,notice:f,analyser:m,unlock:T,audio:g}}function sA(e,t){if(!e)return{state:{queue:[],index:-1,playing:!1,position:0,duration:0,volume:70,muted:!1,shuffle:!1,repeat:`all`,view:t},current:null};let n=e.queue.map((t,n)=>n===e.index?{id:t.id,title:e.title||t.title,artist:e.artist,album:e.album,durationSec:e.duration>0?e.duration:null}:{id:t.id,title:t.title,artist:``,album:``,durationSec:null});return{state:{queue:n,index:e.index,playing:e.playing,position:e.position,duration:e.duration,volume:e.volume,muted:e.muted,shuffle:e.shuffle,repeat:e.repeat,view:t},current:e.index>=0?n[e.index]??null:null}}function cA({local:e,host:t,send:n}){let r=e.state.view,{state:i,current:a}=(0,l.useMemo)(()=>sA(t,r),[t,r]),o=e.dispatch,s=(0,l.useCallback)(e=>{if(e.type===`view`)return o(e);let t=bu(e);t&&n({type:`music.remote`,command:t})},[o,n]);return(0,l.useMemo)(()=>({...e,remote:!0,state:i,dispatch:s,current:a,blocked:!1,notice:null,analyser:null,unlock:()=>{}}),[e,i,s,a])}function lA(e){let t=new URLSearchParams(e).get(`music`);return t===`connected`?{level:`info`,text:`Spotify is connected. Ask Friend to play something.`}:t===`failed`?{level:`warn`,text:`Spotify did not connect. Open Plugins, Spotify and press Connect again.`}:null}function uA({onSignedOut:e}){let{state:t,send:n,dispatch:r,voice:i,useHere:a}=PO(e);KO(i),qO(i),$O(n,t.connection);let[o,s]=(0,l.useState)(!1),[c,u]=(0,l.useState)(!1),[d,f]=(0,l.useState)(!1),[m,h]=(0,l.useState)(!1),[g,_]=(0,l.useState)(void 0),[v,y]=(0,l.useState)(null),[b,x]=(0,l.useState)(!1),[S,C]=(0,l.useState)(0),[w,T]=(0,l.useState)(null),E=de(t.view),D=t.music?.output===`host`,O=oA({music:t.music,cmd:t.musicCmd,send:n,connection:t.connection,remote:D}),k=cA({local:O,host:t.hostMusic,send:n}),j=D?k:O,ee=t.hud?.animations??`full`,M=e=>{let{type:i,value:a}=e.action;if(i===`url`)window.open(a,`_blank`,`noopener,noreferrer`);else if(i===`prompt`)n({type:`chat.send`,text:a});else if(i===`music`||i===`panel`&&a===`music`){if(!t.music?.folderSet){r({type:`alert.add`,level:`info`,text:`No music folder is chosen yet. Pick one in Settings, Widgets, and the player opens.`}),y(`widgets`);return}if(i===`panel`){E.toggle(`music`,!0),j.state.view===`hidden`&&j.dispatch({type:`view`,view:`mini`});return}let e=yu({action:a});e&&j.dispatch(e)}else a===`plugins`?h(!0):a===`settings`?y(`model`):(a===`chat`||a===`tasks`)&&E.toggle(a,!0)},N=(0,l.useMemo)(()=>o?{...t,objects:[],captions:``}:t,[o,t]),P=(0,l.useRef)(!1);(0,l.useEffect)(()=>{P.current||!t.voice.available||t.voice.enrolled||(P.current=!0,r({type:`alert.add`,level:`info`,text:`Voice recognition is not set up. Press Esc, then Enroll my voice.`}))},[t.voice.available,t.voice.enrolled,r]);let te=ne(),L=(0,l.useRef)(!1);(0,l.useEffect)(()=>{if(!te||L.current||t.connection!==`open`)return;L.current=!0;let e=!1;try{e=localStorage.getItem(`friend.touchHint`)===`1`,localStorage.setItem(`friend.touchHint`,`1`)}catch{}e||r({type:`alert.add`,level:`info`,text:`Hold the round mic button to talk, or tap it once to start and again to send. The keyboard button types; the menu button opens settings.`})},[te,t.connection,r]);let re=t.uiOpen?.n??0,ie=t.uiOpen?.integration;(0,l.useEffect)(()=>{re!==0&&(_(ie),h(!0))},[re,ie]);let ae=(0,l.useRef)(!1);(0,l.useEffect)(()=>{if(ae.current)return;ae.current=!0;let e=lA(window.location.search);e&&(r({type:`alert.add`,level:e.level,text:e.text}),window.history.replaceState(null,``,window.location.pathname))},[r]);let oe=(0,l.useRef)(!1);(0,l.useEffect)(()=>{oe.current||t.connection!==`open`||(oe.current=!0,fetch(`/api/history`).then(e=>e.ok?e.json():[]).then(e=>r({type:`chat.seed`,lines:e})).catch(()=>{}))},[t.connection,r]),(0,l.useEffect)(()=>{t.connection===`open`&&n({type:`ui.panels`,open:[...E.show.chat?[`chat`]:[],...E.show.tasks?[`tasks`]:[]]})},[t.connection,E.show.chat,E.show.tasks,n]);let se=(0,l.useRef)(!1);(0,l.useEffect)(()=>{t.viewKnown&&t.view===`minimal`&&!se.current&&(se.current=!0,r({type:`alert.add`,level:`info`,text:`The view is Minimal, so the status line and clock are hidden. Press Esc, then View, to bring them back.`}))},[t.viewKnown,t.view,r]);let ce=e=>{ze.save({view:e}).catch(e=>r({type:`alert.add`,level:`warn`,text:e.message}))},le=(0,l.useMemo)(()=>F({notify:e=>r({type:`alert.add`,level:`info`,text:e}),openSettings:()=>y(`model`),openLook:()=>y(`look`),openConnectors:()=>x(!0),openPlugins:()=>h(!0),openVoice:t.voice.available?()=>u(!0):null,muted:o,setMuted:s,cameraOn:t.camera.enabled,setCamera:e=>r({type:`camera.enable`,value:e}),clearScreen:()=>{for(let e of t.objects)n({type:`stage.event`,objectId:e.id,event:`dismiss`})},statusLine:()=>Ee({connection:t.connection,deviceOnline:t.deviceOnline,approval:t.approval,voiceMode:t.voice.mode,busy:t.busy,activity:t.activity}).text,endSession:t=>{fetch(t===`lock`?`/api/lock`:`/api/logout`,{method:`POST`,headers:{"content-type":`application/json`},body:`{}`}).catch(()=>{}).finally(e)},panelOn:e=>E.show[e],setPanel:(e,t)=>E.toggle(e,t),view:t.view,setView:ce,openHelp:T,resetLayout:()=>{ue(),window.location.reload()}}),[r,n,o,e,E.show,E.toggle,t.view,t.voice.available,t.voice.mode,t.camera.enabled,t.objects,t.connection,t.deviceOnline,t.approval,t.busy,t.activity]);return(0,p.jsxs)(p.Fragment,{children:[(0,p.jsx)(vE,{state:N,send:n,dispatch:r,voice:i,slash:le,onMenu:()=>C(e=>e+1)}),(0,p.jsxs)(ke,{approval:t.approval,challenge:t.challenge,cameraStream:t.camera.stream,alerts:t.alerts,connection:t.connection,deviceOnline:t.deviceOnline,voiceMode:t.voice.mode,busy:t.busy,activity:t.activity,showStatus:t.viewKnown&&E.show.status,showClock:t.viewKnown&&E.show.clock,profile:t.viewKnown&&E.show.profile?{ownerName:t.ownerName,speaker:t.speaker}:null,assistantName:t.assistantName,hud:t.hud,send:n,dispatch:r,children:[t.viewKnown&&E.show.chat&&(0,p.jsx)(fe,{lines:t.chat,live:t.chatLive,onSend:e=>n({type:`chat.send`,text:e}),onClose:()=>E.toggle(`chat`,!1)}),t.viewKnown&&E.show.tasks&&(0,p.jsx)(he,{busy:t.busy,onClose:()=>E.toggle(`tasks`,!1)}),t.viewKnown&&E.show.launcher&&t.hud&&(0,p.jsx)(uk,{items:t.hud.launcher,animations:ee,onAction:M}),t.viewKnown&&E.show.music&&(0,p.jsx)(Gk,{player:j,music:t.music,animations:ee}),c&&(0,p.jsx)(VO,{onClose:()=>u(!1)}),d&&(0,p.jsx)(ik,{onClose:()=>f(!1)}),m&&(0,p.jsx)(bd,{...g?{initialConfigure:g}:{},onClose:()=>{h(!1),_(void 0)}}),v&&(0,p.jsx)(gx,{initialTab:v,onClose:()=>y(null)}),b&&(0,p.jsx)(A,{onClose:()=>x(!1)}),w&&(0,p.jsx)(I,{commands:w,onClose:()=>T(null)})]}),(0,p.jsx)(V,{muted:o,onToggleMute:()=>s(e=>!e),onSignedOut:e,voiceAvailable:t.voice.available,voiceEnrolled:t.voice.enrolled,onEnroll:()=>u(!0),onHousehold:()=>f(!0),onPlugins:()=>h(!0),onSettings:()=>y(`model`),onConnectors:()=>x(!0),cameraOn:t.camera.enabled,onToggleCamera:()=>r({type:`camera.enable`,value:!t.camera.enabled}),chatOn:E.show.chat,onToggleChat:()=>E.toggle(`chat`),tasksOn:E.show.tasks,onToggleTasks:()=>E.toggle(`tasks`),musicOn:E.show.music,onToggleMusic:()=>E.toggle(`music`),launcherOn:E.show.launcher,onToggleLauncher:()=>E.toggle(`launcher`),view:t.view,onView:ce,openRequest:S}),t.connection===`elsewhere`&&(0,p.jsx)(JO,{onUseHere:a})]})}function dA(){let[e,t]=(0,l.useState)(`loading`);return(0,l.useEffect)(()=>{let e=!0,n=n=>e&&t(n);return(async()=>{try{if(!(await(await fetch(`/api/state`)).json()).hasOwner)return n(`setup`);let e=await(await fetch(`/api/session`,{cache:`no-store`})).json();n(e.signedIn===!0?`stage`:`login`)}catch{n(`login`)}})(),()=>{e=!1}},[]),e===`loading`?(0,p.jsx)(`div`,{className:`boot`,"aria-busy":`true`}):e===`setup`?(0,p.jsx)(g,{onDone:()=>t(`login`)}):e===`login`?(0,p.jsx)(h,{onLoggedIn:()=>t(`stage`)}):(0,p.jsx)(uA,{onSignedOut:()=>t(`login`)})}(0,u.createRoot)(document.getElementById(`root`)).render((0,p.jsx)(l.StrictMode,{children:(0,p.jsx)(dA,{})}));
|
|
4455
|
+
Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error occurred:</p><pre>`+Sw(n.message+``,!0)+`</pre>`;return t?Promise.resolve(e):e}if(t)return Promise.reject(n);throw n}}};function Vw(e,t){return Bw.parse(e,t)}Vw.options=Vw.setOptions=function(e){return Bw.setOptions(e),Vw.defaults=Bw.defaults,$S(Vw.defaults),Vw},Vw.getDefaults=ZS,Vw.defaults=QS;function Hw(...e){return Bw.use(...e),Vw.defaults=Bw.defaults,$S(Vw.defaults),Vw}Vw.use=Hw,Vw.walkTokens=function(e,t){return Bw.walkTokens(e,t)},Vw.parseInline=Bw.parseInline,Vw.Parser=Rw,Vw.parser=Rw.parse,Vw.Renderer=Iw,Vw.TextRenderer=Lw,Vw.Lexer=Fw,Vw.lexer=Fw.lex,Vw.Tokenizer=Pw,Vw.Hooks=zw,Vw.parse=Vw,Vw.options,Vw.setOptions,Vw.walkTokens,Vw.parseInline,Rw.parse,Fw.lex;var Uw=!1;function Ww(){Uw||(Uw=!0,XS.addHook(`afterSanitizeAttributes`,e=>{e instanceof Element&&e.tagName===`A`&&(e.setAttribute(`rel`,`noopener noreferrer`),e.setAttribute(`target`,`_blank`))}))}function Gw(e){Ww();let t=Vw.parse(e,{async:!1,breaks:!0});return XS.sanitize(t,{ALLOWED_TAGS:[`p`,`br`,`strong`,`em`,`code`,`pre`,`ul`,`ol`,`li`,`a`,`h1`,`h2`,`h3`,`h4`,`h5`,`h6`,`blockquote`,`hr`,`del`,`table`,`thead`,`tbody`,`tr`,`th`,`td`],ALLOWED_ATTR:[`href`,`rel`,`target`],ALLOWED_URI_REGEXP:/^(?:https?:|mailto:)/i})}var Kw=e=>Number.isFinite(e);function qw(e){let t=Math.floor(Math.log10(e)),n=e/10**t;return(n<=1?1:n<=2?2:n<=2.5?2.5:n<=5?5:10)*10**t}function Jw(e,t,n=5){let r=Kw(e)?e:0,i=Kw(t)?t:r+1;r>i&&([r,i]=[i,r]),r===i&&(i=r+(Math.abs(r)||1));let a=qw((i-r)/Math.max(1,n-1)),o=Math.floor(r/a)*a,s=Math.ceil(i/a)*a,c=[];for(let e=o;e<=s+a/2;e+=a)c.push(Math.round(e*1e9)/1e9);return{min:o,max:s,ticks:c}}function Yw(e,t){let[n,r]=e,[i,a]=t;return r===n?()=>i:e=>i+(e-n)/(r-n)*(a-i)}function Xw(e){return e.map(([e,t],n)=>`${n===0?`M`:`L`}${e.toFixed(2)} ${t.toFixed(2)}`).join(` `)}function Zw(e,t,n,r,i){let a=r=>{let i=r*Math.PI/180;return`${(e+n*Math.cos(i)).toFixed(2)} ${(t+n*Math.sin(i)).toFixed(2)}`},o=+(Math.abs(i-r)>180);return`M ${a(r)} A ${n} ${n} 0 ${o} 1 ${a(i)}`}function Qw(e,t,n){return!Kw(e)||!Kw(t)||!Kw(n)||n<=t?0:Math.min(1,Math.max(0,(e-t)/(n-t)))*240}function $w(e,t,n,r){let i=t.x-e.x,a=t.y-e.y,o=Math.hypot(i,a);if(o===0||o<=n+r)return{from:{...e},to:{...t}};let s=i/o,c=a/o;return{from:{x:e.x+s*n,y:e.y+c*n},to:{x:t.x-s*r,y:t.y-c*r}}}function eT(e,t,n){if(e<=0)return[];if(e===1)return[{x:t/2,y:n/2}];let r=Math.min(t,n)*.36;return Array.from({length:e},(i,a)=>{let o=-Math.PI/2+a*2*Math.PI/e;return{x:t/2+r*Math.cos(o),y:n/2+r*Math.sin(o)}})}var tT=e=>typeof e==`object`&&!!e&&!Array.isArray(e),nT=e=>typeof e==`string`?e:typeof e==`number`?String(e):``,rT=e=>Array.isArray(e)?e:[],iT=e=>typeof e==`number`?Number.isFinite(e)?e:null:typeof e==`string`&&e.trim()!==``&&Number.isFinite(Number(e))?Number(e):null,aT=(e,t)=>e.length>t?e.slice(0,t)+`…`:e,oT=[`var(--accent)`,`#ffb454`,`#7b8cff`,`#5ef0b0`,`#ff6b7a`,`#c792ea`],sT=({text:e})=>e?(0,p.jsx)(`h3`,{className:`obj-title`,children:e}):null,cT=({text:e=`No data`})=>(0,p.jsx)(`p`,{className:`obj-empty`,children:e}),lT=400,uT=220,dT={l:44,r:12,t:10,b:28};function fT({props:e}){let t=e.kind===`bar`||e.kind===`area`?e.kind:`line`,n=rT(e.labels).slice(0,120).map(nT),r=rT(e.series).slice(0,6).map((e,t)=>{let n=tT(e)?e:{},r=rT(n.values).slice(0,120).map((e,t)=>({idx:t,v:iT(e)})).filter(e=>e.v!==null);return{name:nT(n.name)||`series ${t+1}`,points:r}}).filter(e=>e.points.length>0);if(r.length===0)return(0,p.jsxs)(p.Fragment,{children:[(0,p.jsx)(sT,{text:nT(e.title)}),(0,p.jsx)(cT,{})]});let i=r.flatMap(e=>e.points.map(e=>e.v)),a=Math.min(...i),o=Math.max(...i),s=Jw(t===`line`?a:Math.min(0,a),t===`line`?o:Math.max(0,o),5),c=Math.max(n.length,...r.map(e=>e.points[e.points.length-1].idx+1),2),l=Yw([s.min,s.max],[uT-dT.b,dT.t]),u=Yw([0,c-1],[dT.l,lT-dT.r]),d=(lT-dT.l-dT.r)/c,f=Math.max(1,d*.7/r.length),m=(e,t)=>dT.l+e*d+d*.15+t*f,h=Math.max(1,Math.ceil(c/6)),g=nT(e.unit);return(0,p.jsxs)(p.Fragment,{children:[(0,p.jsx)(sT,{text:nT(e.title)}),(0,p.jsxs)(`svg`,{className:`obj-chart`,viewBox:`0 0 ${lT} ${uT}`,role:`img`,"aria-label":nT(e.title)||`chart`,children:[s.ticks.map(e=>(0,p.jsxs)(`g`,{children:[(0,p.jsx)(`line`,{className:`grid`,x1:dT.l,x2:lT-dT.r,y1:l(e),y2:l(e)}),(0,p.jsxs)(`text`,{className:`tick`,x:dT.l-6,y:l(e)+3,textAnchor:`end`,children:[e,g&&e===s.max?g:``]})]},e)),Array.from({length:c},(e,t)=>t).filter(e=>e%h===0&&n[e]).map(e=>(0,p.jsx)(`text`,{className:`tick`,x:t===`bar`?m(e,0)+f*r.length/2:u(e),y:212,textAnchor:`middle`,children:aT(n[e],8)},e)),r.map((e,n)=>{let r=oT[n%oT.length];if(t===`bar`)return(0,p.jsx)(`g`,{children:e.points.map(e=>(0,p.jsx)(`rect`,{className:`bar`,x:m(e.idx,n),y:Math.min(l(e.v),l(0)),width:f,height:Math.abs(l(e.v)-l(0)),fill:r},e.idx))},n);let i=e.points.map(e=>[u(e.idx),l(e.v)]),a=Xw(i),o=`${a} L${i[i.length-1][0].toFixed(2)} ${l(s.min).toFixed(2)} L${i[0][0].toFixed(2)} ${l(s.min).toFixed(2)} Z`;return(0,p.jsxs)(`g`,{children:[t===`area`&&(0,p.jsx)(`path`,{className:`series-area`,d:o,fill:r,opacity:.18}),(0,p.jsx)(`path`,{className:`series-line`,d:a,fill:`none`,stroke:r,strokeWidth:2,strokeLinejoin:`round`})]},n)})]}),r.length>1&&(0,p.jsx)(`ul`,{className:`legend`,children:r.map((e,t)=>(0,p.jsxs)(`li`,{children:[(0,p.jsx)(`i`,{style:{background:oT[t%oT.length]}}),(0,p.jsx)(`span`,{children:e.name})]},t))})]})}function pT({props:e}){let t=iT(e.min)??0,n=iT(e.max)??100,r=iT(e.value)??t,i=Qw(r,t,n),a=i/240;return(0,p.jsxs)(`div`,{className:`obj-gauge ${a>.95?`gauge-crit`:a>.8?`gauge-warn`:``}`,children:[(0,p.jsxs)(`svg`,{viewBox:`0 0 200 150`,role:`img`,"aria-label":`${nT(e.label)} ${r}`,children:[(0,p.jsx)(`path`,{className:`track`,d:Zw(100,100,70,150,390),fill:`none`,strokeWidth:12,strokeLinecap:`round`}),i>0&&(0,p.jsx)(`path`,{className:`value`,d:Zw(100,100,70,150,150+i),fill:`none`,strokeWidth:12,strokeLinecap:`round`})]}),(0,p.jsxs)(`div`,{className:`gauge-read`,children:[(0,p.jsx)(`span`,{className:`gauge-value`,children:String(Math.round(r*100)/100)}),nT(e.unit)&&(0,p.jsx)(`small`,{className:`gauge-unit`,children:nT(e.unit)})]}),(0,p.jsx)(`span`,{className:`obj-label`,children:nT(e.label)})]})}function mT({props:e}){let t=rT(e.items).slice(0,30).map(e=>tT(e)?e:{}).map(e=>({time:nT(e.time),title:nT(e.title),detail:nT(e.detail)})).filter(e=>e.title||e.time);return t.length===0?(0,p.jsxs)(p.Fragment,{children:[(0,p.jsx)(sT,{text:nT(e.title)}),(0,p.jsx)(cT,{text:`Nothing to show`})]}):(0,p.jsxs)(p.Fragment,{children:[(0,p.jsx)(sT,{text:nT(e.title)}),(0,p.jsx)(`ol`,{className:`obj-timeline`,children:t.map((e,t)=>(0,p.jsxs)(`li`,{children:[(0,p.jsx)(`time`,{children:e.time}),(0,p.jsx)(`strong`,{children:e.title}),e.detail&&(0,p.jsx)(`span`,{children:e.detail})]},t))})]})}var hT=400,gT=300,_T=12;function vT({props:e}){let t=(0,l.useId)(),n=new Set,r=[];for(let t of rT(e.nodes)){let e=tT(t)?t:{},i=nT(e.id);if(i&&!n.has(i)&&(n.add(i),r.push({id:i,label:nT(e.label)||i}),r.length>=40))break}if(r.length===0)return(0,p.jsxs)(p.Fragment,{children:[(0,p.jsx)(sT,{text:nT(e.title)}),(0,p.jsx)(cT,{text:`Nothing to show`})]});let i=new Map(r.map((e,t)=>[e.id,eT(r.length,hT,gT)[t]])),a=[];for(let t of rT(e.edges)){let e=tT(t)?t:{},n=nT(e.from),r=nT(e.to);if(i.has(n)&&i.has(r)&&n!==r&&(a.push({from:n,to:r,label:nT(e.label)}),a.length>=80))break}return(0,p.jsxs)(p.Fragment,{children:[(0,p.jsx)(sT,{text:nT(e.title)}),(0,p.jsxs)(`svg`,{className:`obj-graph`,viewBox:`0 0 ${hT} ${gT}`,role:`img`,"aria-label":nT(e.title)||`graph`,children:[(0,p.jsx)(`defs`,{children:(0,p.jsx)(`marker`,{id:t,viewBox:`0 0 10 10`,refX:`9`,refY:`5`,markerWidth:`6`,markerHeight:`6`,orient:`auto-start-reverse`,children:(0,p.jsx)(`path`,{d:`M0 0 L10 5 L0 10 z`,className:`arrow`})})}),a.map((e,n)=>{let{from:r,to:a}=$w(i.get(e.from),i.get(e.to),14,17),o=(r.x+a.x)/2+(hT/2-(r.x+a.x)/2)*.25,s=(r.y+a.y)/2+(gT/2-(r.y+a.y)/2)*.25;return(0,p.jsxs)(`g`,{children:[(0,p.jsx)(`path`,{className:`edge`,d:`M ${r.x.toFixed(1)} ${r.y.toFixed(1)} Q ${o.toFixed(1)} ${s.toFixed(1)} ${a.x.toFixed(1)} ${a.y.toFixed(1)}`,fill:`none`,markerEnd:`url(#${t})`}),e.label&&(0,p.jsx)(`text`,{className:`edge-label`,x:o,y:s,textAnchor:`middle`,children:aT(e.label,12)})]},n)}),r.map(e=>{let t=i.get(e.id);return(0,p.jsxs)(`g`,{children:[(0,p.jsx)(`circle`,{className:`node`,cx:t.x,cy:t.y,r:_T}),(0,p.jsx)(`text`,{className:`node-label`,x:t.x,y:t.y+26,textAnchor:`middle`,children:aT(e.label,18)})]},e.id)})]})]})}var yT=e=>typeof e==`string`?e:typeof e==`number`?String(e):``,bT=e=>Array.isArray(e)?e:[],xT=e=>typeof e==`object`&&e?e:{},ST=/^\/api\/media\/[0-9a-f]{32}$/,CT=e=>typeof e==`string`&&ST.test(e)?e:null,wT=/^\/api\/video\/[0-9a-f]{32}$/,TT=e=>typeof e==`string`&&wT.test(e)?e:null,ET=({props:e})=>yT(e.title)?(0,p.jsx)(`h3`,{className:`obj-title`,children:yT(e.title)}):null;function DT({props:e}){let t=(0,l.useMemo)(()=>Gw(yT(e.text)),[e.text]);return(0,p.jsxs)(p.Fragment,{children:[(0,p.jsx)(ET,{props:e}),(0,p.jsx)(`div`,{className:`obj-md obj-doc`,dangerouslySetInnerHTML:{__html:t}})]})}function OT({props:e}){let t=Math.min(100,Math.max(0,Number(e.value)||0));return(0,p.jsxs)(`div`,{className:`obj-progress`,children:[(0,p.jsxs)(`div`,{className:`obj-progress-head`,children:[(0,p.jsx)(`span`,{className:`obj-label`,children:yT(e.label)}),(0,p.jsxs)(`span`,{className:`obj-progress-pct`,children:[Math.round(t),`%`]})]}),(0,p.jsx)(`div`,{className:`obj-progress-bar`,role:`progressbar`,"aria-valuemin":0,"aria-valuemax":100,"aria-valuenow":Math.round(t),"aria-label":yT(e.label)||`Progress`,children:(0,p.jsx)(`i`,{style:{width:`${t}%`}})}),yT(e.detail)&&(0,p.jsx)(`span`,{className:`obj-progress-detail`,children:yT(e.detail)})]})}function kT({props:e}){let t=bT(e.items).map(e=>xT(typeof e==`object`&&e?e:{text:e})),n=t.filter(e=>e.done===!0).length;return(0,p.jsxs)(p.Fragment,{children:[(0,p.jsx)(ET,{props:e}),(0,p.jsx)(`ul`,{className:`obj-checklist`,children:t.map((e,t)=>(0,p.jsxs)(`li`,{className:e.done===!0?`done`:void 0,children:[(0,p.jsx)(`span`,{className:`box`,"aria-hidden":`true`,children:e.done===!0?`✓`:``}),(0,p.jsx)(`span`,{children:yT(e.text)})]},t))}),t.length>0&&(0,p.jsxs)(`small`,{className:`obj-progress-detail`,children:[n,` of `,t.length,` done`]})]})}function AT({props:e}){return(0,p.jsxs)(p.Fragment,{children:[(0,p.jsx)(ET,{props:e}),(0,p.jsx)(`dl`,{className:`obj-kv`,children:bT(e.rows).map((e,t)=>{let n=xT(e);return(0,p.jsxs)(`div`,{children:[(0,p.jsx)(`dt`,{children:yT(n.key)}),(0,p.jsx)(`dd`,{children:yT(n.value)})]},t)})})]})}var jT=e=>String(Math.floor(e)).padStart(2,`0`);function MT(e){let t=Math.max(0,Math.ceil(e));return`${jT(t/3600)}:${jT(t%3600/60)}:${jT(t%60)}`}function NT({props:e}){let t=(0,l.useRef)(null);if(t.current===null){let n=typeof e.to==`string`?Date.parse(e.to):NaN,r=Number(e.seconds);t.current=Number.isFinite(n)?n:Date.now()+(Number.isFinite(r)?r:0)*1e3}let[n,r]=(0,l.useState)(Date.now());(0,l.useEffect)(()=>{let e=setInterval(()=>r(Date.now()),250);return()=>clearInterval(e)},[]);let i=(t.current-n)/1e3;return(0,p.jsxs)(`div`,{className:`obj-countdown${i<=0?` done`:``}`,children:[(0,p.jsx)(`span`,{className:`obj-label`,children:yT(e.title)||yT(e.label)}),(0,p.jsx)(`span`,{className:`obj-countdown-time`,role:`timer`,children:MT(i)})]})}function PT({props:e}){let t=CT(e.src);return(0,p.jsxs)(`div`,{className:`obj-media`,children:[(0,p.jsx)(ET,{props:e}),t?(0,p.jsx)(`img`,{src:t,alt:yT(e.title)||`Picture`,loading:`lazy`}):(0,p.jsx)(`p`,{className:`obj-empty`,children:`This picture is not available.`})]})}function FT({src:e,web:t,title:n}){let[r,i]=(0,l.useState)(t?`loading`:`ready`);return r===`failed`?(0,p.jsx)(`p`,{className:`obj-empty`,children:`This video could not be played. Ask Friend to try again, or to play it in a window on the PC.`}):(0,p.jsxs)(p.Fragment,{children:[(0,p.jsx)(`video`,{src:e,controls:!0,playsInline:!0,autoPlay:t,preload:t?`auto`:`metadata`,"aria-label":n,onLoadedData:()=>i(`ready`),onError:()=>i(`failed`)}),t&&r===`loading`&&(0,p.jsx)(`p`,{className:`obj-empty`,children:`Preparing the video…`})]})}var IT=/^[A-Za-z0-9_-]{11}$/;function LT({id:e,start:t,title:n}){let[r,i]=(0,l.useState)(!1),a=new URLSearchParams({autoplay:`1`,rel:`0`,playsinline:`1`,modestbranding:`1`});return t>0&&a.set(`start`,String(t)),(0,p.jsxs)(p.Fragment,{children:[(0,p.jsx)(`iframe`,{className:`obj-youtube`,src:`https://www.youtube-nocookie.com/embed/${e}?${a.toString()}`,title:n,allow:`autoplay; encrypted-media; fullscreen; picture-in-picture`,allowFullScreen:!0,referrerPolicy:`strict-origin-when-cross-origin`,onLoad:()=>i(!0)}),!r&&(0,p.jsx)(`p`,{className:`obj-empty`,children:`Loading the player…`})]})}function RT({props:e}){if(e.embed!==void 0){let t=typeof e.embed==`string`&&IT.test(e.embed)?e.embed:null,n=typeof e.start==`number`&&e.start>0&&e.start<=86400?Math.floor(e.start):0;return(0,p.jsxs)(`div`,{className:`obj-media`,children:[(0,p.jsx)(ET,{props:e}),t?(0,p.jsx)(LT,{id:t,start:n,title:yT(e.title)||`YouTube video`},`${t}-${n}`):(0,p.jsx)(`p`,{className:`obj-empty`,children:`This clip is not available.`})]})}let t=TT(e.src),n=t??CT(e.src);return(0,p.jsxs)(`div`,{className:`obj-media`,children:[(0,p.jsx)(ET,{props:e}),n?(0,p.jsx)(FT,{src:n,web:t!==null,title:yT(e.title)||`Video`},n):(0,p.jsx)(`p`,{className:`obj-empty`,children:`This clip is not available.`})]})}function zT({props:e}){let t=CT(e.src);return(0,p.jsxs)(`div`,{className:`obj-media obj-pdf`,children:[(0,p.jsx)(ET,{props:e}),t?(0,p.jsxs)(p.Fragment,{children:[(0,p.jsx)(`iframe`,{src:t,title:yT(e.title)||`Document`}),(0,p.jsx)(`a`,{className:`obj-open`,href:t,target:`_blank`,rel:`noopener noreferrer`,children:`Open in a new tab`})]}):(0,p.jsx)(`p`,{className:`obj-empty`,children:`This document is not available.`})]})}function BT({props:e}){let t=bT(e.items).map(xT).filter(e=>CT(e.src)),[n,r]=(0,l.useState)(0),i=Math.min(n,Math.max(0,t.length-1)),a=t[i];if(!a)return(0,p.jsx)(`p`,{className:`obj-empty`,children:`Nothing to show.`});let o=CT(a.src),s=a.kind===`video`;return(0,p.jsxs)(`div`,{className:`obj-media obj-gallery`,children:[(0,p.jsx)(ET,{props:e}),s?(0,p.jsx)(`video`,{src:o,controls:!0,playsInline:!0,preload:`metadata`},o):(0,p.jsx)(`img`,{src:o,alt:yT(a.caption)||`Picture ${i+1}`},o),(0,p.jsxs)(`div`,{className:`obj-gallery-bar`,children:[(0,p.jsx)(`button`,{type:`button`,"aria-label":`Previous`,disabled:t.length<2,onClick:()=>r((i+t.length-1)%t.length),children:`‹`}),(0,p.jsxs)(`span`,{children:[yT(a.caption),(0,p.jsxs)(`small`,{children:[i+1,` / `,t.length]})]}),(0,p.jsx)(`button`,{type:`button`,"aria-label":`Next`,disabled:t.length<2,onClick:()=>r((i+1)%t.length),children:`›`})]})]})}var VT=[`default-src 'none'`,`script-src 'unsafe-inline'`,`style-src 'unsafe-inline'`,`img-src data: blob:`,`form-action 'none'`,`base-uri 'none'`].join(`; `),HT=`html,body{margin:0;min-height:100%;background:#050b10;color:var(--ink,#d8f6ff);font:15px/1.5 var(--ui,system-ui,sans-serif)}`,UT=[`--accent`,`--ink`,`--muted`,`--ok`,`--warn`,`--bad`,`--glass`,`--edge`,`--ui`,`--mono`],WT=/^[\w\s#().,%'"/-]+$/;function GT(){if(typeof document>`u`)return``;let e=getComputedStyle(document.documentElement),t=UT.map(t=>[t,e.getPropertyValue(t).trim()]).filter(([,e])=>e&&WT.test(e));return t.length?`:root{${t.map(([e,t])=>`${e}:${t}`).join(`;`)}}`:``}function KT(e,t=``){return`<!doctype html><html><head><meta charset="utf-8"><meta http-equiv="Content-Security-Policy" content="${VT}"><meta name="viewport" content="width=device-width,initial-scale=1"><style>${t}${HT}</style></head><body>${e}</body></html>`}function qT({props:e}){let t=typeof e.html==`string`?e.html:``,n=typeof e.title==`string`?e.title:``,r=(0,l.useMemo)(()=>KT(t,GT()),[t]);return(0,p.jsxs)(`div`,{className:`obj-sandbox`,children:[n&&(0,p.jsx)(`h3`,{className:`obj-title`,children:n}),(0,p.jsx)(`iframe`,{title:n||`Page made by Friend`,sandbox:`allow-scripts`,referrerPolicy:`no-referrer`,allow:``,srcDoc:r})]})}var JT=e=>typeof e==`string`?e:typeof e==`number`?String(e):``,YT=e=>Array.isArray(e)?e:[];function XT({props:e}){let t=(0,l.useMemo)(()=>Gw(JT(e.text)),[e.text]);return(0,p.jsxs)(p.Fragment,{children:[JT(e.title)&&(0,p.jsx)(`h3`,{className:`obj-title`,children:JT(e.title)}),(0,p.jsx)(`div`,{className:`obj-md`,dangerouslySetInnerHTML:{__html:t}})]})}function ZT({props:e}){return(0,p.jsxs)(`div`,{className:`obj-stat`,children:[(0,p.jsx)(`span`,{className:`obj-label`,children:JT(e.label)}),(0,p.jsxs)(`span`,{className:`obj-value`,children:[(0,p.jsx)(`span`,{children:JT(e.value)}),JT(e.unit)&&(0,p.jsx)(`small`,{children:JT(e.unit)})]}),JT(e.delta)&&(0,p.jsx)(`span`,{className:`obj-delta`,children:JT(e.delta)})]})}function QT({props:e}){return(0,p.jsxs)(p.Fragment,{children:[JT(e.title)&&(0,p.jsx)(`h3`,{className:`obj-title`,children:JT(e.title)}),(0,p.jsx)(`ul`,{className:`obj-list`,children:YT(e.items).map((e,t)=>{let n=typeof e==`object`&&e?e:{text:e};return(0,p.jsx)(`li`,{className:n.done?`done`:void 0,children:JT(n.text)},t)})})]})}function $T({props:e}){let t=YT(e.columns),n=YT(e.rows);return(0,p.jsxs)(p.Fragment,{children:[JT(e.title)&&(0,p.jsx)(`h3`,{className:`obj-title`,children:JT(e.title)}),(0,p.jsx)(`div`,{className:`obj-table-wrap`,children:(0,p.jsxs)(`table`,{className:`obj-table`,children:[(0,p.jsx)(`thead`,{children:(0,p.jsx)(`tr`,{children:t.map((e,t)=>(0,p.jsx)(`th`,{children:JT(e)},t))})}),(0,p.jsx)(`tbody`,{children:n.map((e,t)=>(0,p.jsx)(`tr`,{children:YT(e).map((e,t)=>(0,p.jsx)(`td`,{children:JT(e)},t))},t))})]})})]})}function eE({props:e}){return(0,p.jsxs)(p.Fragment,{children:[JT(e.title)&&(0,p.jsx)(`h3`,{className:`obj-title`,children:JT(e.title)}),(0,p.jsx)(`pre`,{className:`obj-code`,"data-lang":JT(e.language),children:(0,p.jsx)(`code`,{children:JT(e.code)})})]})}function tE({part:e}){let t=typeof e==`object`&&e?e:{},n=typeof t.type==`string`?t.type:``;if(n===`group`||n===`tabs`||n===`sandbox`)return null;let r=iE[n];return r?(0,p.jsx)(`div`,{className:`obj-part obj-part-${n}`,children:(0,p.jsx)(r,{props:typeof t.props==`object`&&t.props!==null?t.props:{}})}):null}function nE({props:e}){let t=e.layout===`row`||e.layout===`column`?e.layout:`grid`;return(0,p.jsxs)(p.Fragment,{children:[JT(e.title)&&(0,p.jsx)(`h3`,{className:`obj-title`,children:JT(e.title)}),(0,p.jsx)(`div`,{className:`obj-group obj-group-${t}`,children:YT(e.items).map((e,t)=>(0,p.jsx)(tE,{part:e},t))})]})}function rE({props:e}){let t=YT(e.tabs).map(e=>typeof e==`object`&&e?e:{}),[n,r]=(0,l.useState)(0),i=Math.min(n,Math.max(0,t.length-1));return(0,p.jsxs)(p.Fragment,{children:[JT(e.title)&&(0,p.jsx)(`h3`,{className:`obj-title`,children:JT(e.title)}),(0,p.jsx)(`div`,{className:`obj-tabs`,role:`tablist`,children:t.map((e,t)=>(0,p.jsx)(`button`,{type:`button`,role:`tab`,"aria-selected":t===i,className:t===i?`on`:void 0,onClick:()=>r(t),children:JT(e.title)||`Tab ${t+1}`},t))}),t[i]&&(0,p.jsx)(tE,{part:t[i]})]})}var iE={card:XT,stat:ZT,list:QT,table:$T,code:eE,chart:fT,gauge:pT,timeline:mT,graph:vT,sandbox:qT,markdown:DT,image:PT,video:RT,pdf:zT,gallery:BT,group:nE,tabs:rE,progress:OT,checklist:kT,countdown:NT,kv:AT};function aE(e,t){let n=new Map(t.map(e=>[e.id,e])),r=[],i=new Set;for(let t of e){if(i.has(t.object.id))continue;i.add(t.object.id);let e=n.get(t.object.id);r.push(e?{object:e,leaving:!1}:{object:t.object,leaving:!0})}for(let e of t)i.has(e.id)||(i.add(e.id),r.push({object:e,leaving:!1}));return r}function oE(e,t){let[n,r]=(0,l.useState)(()=>e.map(e=>({object:e,leaving:!1}))),i=(0,l.useRef)(new Map);return(0,l.useEffect)(()=>{r(n=>{let a=aE(n,e),o=new Set(n.filter(e=>e.leaving).map(e=>e.object.id));for(let e of a){let n=i.current.get(e.object.id);if(!e.leaving)n&&clearTimeout(n),i.current.delete(e.object.id);else if(!o.has(e.object.id)&&!n){let n=e.object.id;i.current.set(n,setTimeout(()=>{i.current.delete(n),r(e=>e.filter(e=>!(e.object.id===n&&e.leaving)))},Math.max(t,0)))}}return t<=0?a.filter(e=>!e.leaving):a})},[e,t]),(0,l.useEffect)(()=>()=>{for(let e of i.current.values())clearTimeout(e);i.current.clear()},[]),n}var sE=.12,cE=.1,lE=.02,uE=(e,t,n)=>Math.min(Math.max(e,t),n);function dE(e){let t=uE(e.w,sE,1),n=uE(e.h,cE,1);return{x:uE(e.x,0,1-t),y:uE(e.y,0,1-n),w:t,h:n}}function fE(e,t){let n=t.getBoundingClientRect(),r=e.getBoundingClientRect();return n.width<=0||n.height<=0?null:dE({x:(r.left-n.left)/n.width,y:(r.top-n.top)/n.height,w:r.width/n.width,h:r.height/n.height})}function pE(e,t,n){let r=(0,l.useRef)(null),[i,a]=(0,l.useState)(null),o=(0,l.useCallback)((n,r)=>{let i=dE(r);t({type:`object.place`,id:n,placement:{x:i.x,y:i.y,w:i.w,h:i.h}}),e({type:`stage.move`,objectId:n,rect:i})},[e,t]),s=(0,l.useCallback)((e,t,i)=>{if(e.pointerType===`mouse`&&e.button!==0)return;let o=n(),s=e.currentTarget.closest(`[data-object]`);if(!o||!s||r.current)return;let c=fE(s,o);if(!c)return;let l=o.getBoundingClientRect();r.current={id:t.id,mode:i,pointer:e.pointerId,startX:e.clientX,startY:e.clientY,from:c,stageW:l.width,stageH:l.height};try{e.currentTarget.setPointerCapture(e.pointerId)}catch{}e.stopPropagation(),e.preventDefault(),a({id:t.id,box:c})},[n]),c=(e,t)=>{let n=(t.clientX-e.startX)/e.stageW,r=(t.clientY-e.startY)/e.stageH;return e.mode===`move`?dE({...e.from,x:e.from.x+n,y:e.from.y+r}):dE({...e.from,w:e.from.w+n,h:e.from.h+r})};return{preview:i,begin:s,move:(0,l.useCallback)(e=>{let t=r.current;t&&t.pointer===e.pointerId&&a({id:t.id,box:c(t,e)})},[]),end:(0,l.useCallback)((e,t)=>{let n=r.current;n&&n.pointer===e.pointerId&&(r.current=null,a(null),t||o(n.id,c(n,e)))},[o]),key:(0,l.useCallback)((e,t)=>{let r={ArrowLeft:[-.02,0],ArrowRight:[lE,0],ArrowUp:[0,-.02],ArrowDown:[0,lE]}[e.key],i=n(),a=e.currentTarget.closest(`[data-object]`);if(!r||!i||!a)return;let s=fE(a,i);s&&(e.preventDefault(),o(t.id,e.shiftKey?{...s,w:s.w+r[0],h:s.h+r[1]}:{...s,x:s.x+r[0],y:s.y+r[1]}))},[o,n])}}function mE(e,t){if(e===`auto`)return{position:`relative`};if(t.w<600)return{position:`relative`,width:`100%`};let[n,r,i,a]=typeof e==`string`?Nl[e]:[e.x*100,e.y*100,e.w*100,e.h*100],o={position:`absolute`,left:`${n}%`,top:`${r}%`,width:`${i}%`};return e===`top`||e===`bottom`?{...o,maxHeight:`${a}%`}:{...o,height:`${a}%`}}var hE=350,gE=()=>typeof matchMedia==`function`&&matchMedia(`(prefers-reduced-motion: reduce)`).matches,_E=class extends l.Component{state={failed:!1};static getDerivedStateFromError(){return{failed:!0}}render(){return this.state.failed?null:this.props.children}};function vE(){let e=()=>({w:window.innerWidth,h:window.innerHeight}),[t,n]=(0,l.useState)(e);return(0,l.useEffect)(()=>{let t=()=>n(e());return window.addEventListener(`resize`,t),()=>window.removeEventListener(`resize`,t)},[]),t}var yE=350;function bE({state:e,send:t,dispatch:n,voice:r,slash:i,onMenu:a}){let o=vE(),[s,c]=(0,l.useState)(0),[u,d]=(0,l.useState)(!1),f=ne(),m=o.w<600,h=e.scene===`focus`||e.scene===`multi`,g={"--accent":e.mood.accent,"--intensity":e.mood.intensity},_=e.voice.mode,v=_===`listening`?`listening`:_===`speaking`?`speaking`:_===`transcribing`?`thinking`:e.presence.state,y=Qb(e.look.reactivity),b=Math.min(1,(_===`listening`||_===`speaking`?e.voice.level:e.presence.amplitude)*y),x=(0,l.useRef)({timer:null,down:!1,talking:!1,id:null}),S=e=>{if(!(e.target===e.currentTarget||e.target.closest(`[data-presence]`))||e.pointerType===`mouse`&&e.button!==0)return;let t=x.current;if(!(t.down&&t.id!==null&&e.pointerId!==t.id)){t.timer&&clearTimeout(t.timer),t.down=!0,t.talking=!1,t.id=typeof e.pointerId==`number`?e.pointerId:null;try{t.id!==null&&e.currentTarget.setPointerCapture?.(t.id)}catch{}t.timer=r?setTimeout(()=>{t.down&&(t.talking=!0,r.pressStart())},yE):null}},C=(e,t)=>{let n=x.current;n.down&&(n.id===null||typeof e.pointerId!=`number`||e.pointerId===n.id)&&(n.down=!1,n.id=null,n.timer&&clearTimeout(n.timer),n.timer=null,n.talking?(n.talking=!1,t?r?.blur?.():r?.pressEnd()):t||c(e=>e+1))},w=(0,l.useRef)(null),T=pE(t,n,()=>w.current),E=oE(e.objects,gE()?0:hE),D=E.filter(e=>e.object.layer===`overlay`),O=E.filter(e=>e.object.layer!==`overlay`&&e.object.placement===`auto`),k=E.filter(e=>e.object.layer!==`overlay`&&e.object.placement!==`auto`),A=({object:e,leaving:r})=>{let i=iE[e.type];if(!i)return null;let a=e.layer===`overlay`,s=!m&&!r&&!a,c=T.preview?.id===e.id?T.preview.box:null,l=c?{x:c.x,y:c.y,w:c.w,h:c.h}:e.placement;return(0,p.jsxs)(`section`,{"data-object":e.id,className:`obj glass${e.style===`alert`?` alert`:``}${a?` overlay`:``}${e.pinned?` pinned`:``}${c?` dragging`:``}${r?` leaving`:``}`,style:a?void 0:mE(l,o),children:[s&&(0,p.jsx)(`div`,{className:`obj-grip`,role:`button`,tabIndex:0,"aria-label":`Move ${e.id}. Drag, or use the arrow keys; hold Shift to resize.`,onPointerDown:t=>T.begin(t,e,`move`),onPointerMove:T.move,onPointerUp:e=>T.end(e,!1),onPointerCancel:e=>T.end(e,!0),onKeyDown:t=>T.key(t,e)}),!a&&(0,p.jsx)(`button`,{className:`obj-pin${e.pinned?` on`:``}`,"aria-label":e.pinned?`Unpin ${e.id}`:`Pin ${e.id} to the screen`,"aria-pressed":!!e.pinned,title:e.pinned?`Pinned: stays on the screen. Click to unpin.`:`Pin: keep this on the screen.`,disabled:r,onClick:()=>t({type:`stage.pin`,objectId:e.id,pinned:!e.pinned}),children:(0,p.jsx)(`svg`,{width:`14`,height:`14`,viewBox:`0 0 24 24`,fill:e.pinned?`currentColor`:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,"aria-hidden":`true`,children:(0,p.jsx)(`path`,{d:`M12 17v5M9 3h6l-1 7 3 3H7l3-3-1-7z`})})}),(0,p.jsx)(`button`,{className:`obj-close`,"aria-label":`Dismiss ${e.id}`,title:e.pinned?`Remove this widget`:`Dismiss`,disabled:r,onClick:()=>{t({type:`stage.event`,objectId:e.id,event:`dismiss`}),n({type:`object.dismiss`,id:e.id})},children:`×`}),s&&(0,p.jsx)(`div`,{className:`obj-resize`,"aria-hidden":`true`,onPointerDown:t=>T.begin(t,e,`resize`),onPointerMove:T.move,onPointerUp:e=>T.end(e,!1),onPointerCancel:e=>T.end(e,!0)}),(0,p.jsx)(_E,{children:(0,p.jsx)(i,{props:e.props})})]},e.id)};return(0,p.jsxs)(`div`,{ref:w,"data-testid":`stage`,className:`stage`,style:g,onPointerDown:S,onPointerUp:e=>C(e,!1),onPointerCancel:e=>C(e,!0),onContextMenu:e=>r&&e.preventDefault(),children:[e.look.ambient&&(0,p.jsx)(`div`,{className:`ambient`,"aria-hidden":`true`,style:{opacity:.35+.65*e.mood.intensity}}),(0,p.jsx)(Zb,{state:v,amplitude:b,pulse:e.presence.pulse,mode:h?`corner`:`full`,accent:e.mood.accent,style:e.presence.style,intensity:e.mood.intensity,scale:e.look.size}),(0,p.jsxs)(`div`,{className:m?`objects objects-stack`:`objects`,style:{zIndex:10},children:[O.length>0&&(0,p.jsx)(`div`,{className:`auto-grid`,children:O.map(A)}),k.map(A)]}),D.length>0&&(0,p.jsxs)(`div`,{className:`overlay-layer`,"data-testid":`overlay`,children:[(0,p.jsx)(`div`,{className:`overlay-backdrop`,onClick:()=>D.forEach(({object:e})=>{t({type:`stage.event`,objectId:e.id,event:`dismiss`}),n({type:`object.dismiss`,id:e.id})})}),D.map(A)]}),e.look.captions&&e.captions&&(0,p.jsx)(`p`,{className:`captions captions-${e.look.captionSize}${e.captionDone?` done`:``}`,"aria-live":`polite`,children:e.captions}),f&&r&&!u&&(0,p.jsx)(xx,{voice:r,mode:_,onType:()=>c(e=>e+1),onMenu:()=>a?.()}),(0,p.jsx)(vx,{requestOpen:s,slash:i,onOpenChange:d,onSend:e=>t({type:`chat.send`,text:e})})]})}function xE(){let e=()=>Math.random().toString(36).slice(2,12)+Date.now().toString(36);try{let t=sessionStorage.getItem(`friend.tab`);return t||(t=e(),sessionStorage.setItem(`friend.tab`,t)),t}catch{return e()}}function SE(){return`${location.protocol===`https:`?`wss`:`ws`}://${location.host}/ws`}function CE(e=SE()){let t=null,n=`connecting`,r=!1,i=0,a=!1,o=xE(),s=null,c=new Set,l=new Set,u=e=>{n=e,l.forEach(t=>t(e))};function d(){if(r)return;u(`connecting`);let n=new WebSocket(`${e}${e.includes(`?`)?`&`:`?`}tab=${o}${a?`&takeover=1`:``}`);t=n,n.onopen=()=>{i=0,a=!1,u(`open`)},n.onmessage=e=>{try{let t=JSON.parse(String(e.data));c.forEach(e=>e(t))}catch{}},n.onclose=e=>{if(!r){if(e.code===4401)return u(`unauthorized`);if(e.code===4409||e.code===4410)return u(`elsewhere`);u(`closed`),s=setTimeout(d,Math.min(500*2**i++,8e3))}},n.onerror=()=>{}}return d(),{send(e){t?.readyState===WebSocket.OPEN&&t.send(JSON.stringify(e))},onMessage(e){return c.add(e),()=>c.delete(e)},onState(e){return l.add(e),()=>l.delete(e)},state:()=>n,takeOver(){r||n!==`elsewhere`||(a=!0,i=0,d())},close(){r=!0,s&&clearTimeout(s),t?.close()}}}var wE={scene:`conversation`,objects:[],captions:``,captionDone:!0,presence:{state:`idle`,style:`sphere`,amplitude:0,pulse:0},mood:{accent:`#3fd8ff`,intensity:.6},approval:null,alerts:[],connection:`connecting`,chat:[],chatLive:!1,view:`companion`,look:{size:1,reactivity:.7,ambient:!0,captions:!0,captionSize:`medium`},viewKnown:!1,busy:!1,activity:null,deviceOnline:!1,voice:{mode:`idle`,level:0,available:!1,enrolled:!1},challenge:null,camera:{enabled:!1,stream:null},speaker:null,ownerName:``,assistantName:``,hud:null,music:null,hostMusic:null,musicCmd:null,uiOpen:null},TE=200,EE=e=>e.length>TE?e.slice(-200):e,DE=0,OE=e=>Math.min(1,Math.max(0,e));function kE(e,t){switch(t.cmd){case`scene`:return{...e,scene:t.mode};case`show`:{let n=e.objects.findIndex(e=>e.id===t.object.id),r=n===-1?[...e.objects,t.object]:e.objects.map((e,r)=>r===n?t.object:e);return{...e,objects:r}}case`update`:return{...e,objects:e.objects.map(e=>e.id===t.id?{...e,props:{...e.props,...t.props}}:e)};case`hide`:return{...e,objects:e.objects.filter(e=>e.id!==t.id)};case`clear`:return{...e,objects:e.objects.filter(e=>e.pinned),scene:`conversation`};case`pin`:return{...e,objects:e.objects.map(e=>e.id===t.id?{...e,pinned:!0}:e)};case`unpin`:return{...e,objects:e.objects.map(e=>e.id===t.id?(({pinned:e,...t})=>t)(e):e)};case`place`:return{...e,objects:e.objects.map(e=>e.id===t.id?{...e,placement:t.placement}:e)};case`presence`:return{...e,presence:{...e.presence,state:t.state??e.presence.state,style:t.style??e.presence.style}};case`mood`:return{...e,mood:{accent:t.accent??e.mood.accent,intensity:t.intensity??e.mood.intensity}}}}function AE(e,t){let n=t;if(n&&typeof n==`object`){if(n.type===`conn`)return{...e,connection:n.value};if(n.type===`chat.seed`){let t=Array.isArray(n.lines)?n.lines:[];return e.chat.length===0?{...e,chat:EE(t)}:{...e,chat:EE([...t,...e.chat])}}if(n.type===`alert.add`)return{...e,alerts:[...e.alerts.slice(-3),{id:++DE,level:n.level,text:n.text}]};if(n.type===`camera.enable`)return{...e,camera:{enabled:n.value,stream:n.value?e.camera.stream:null}};if(n.type===`camera.open`)return{...e,camera:{...e.camera,stream:n.stream}};if(n.type===`camera.closed`)return{...e,camera:{...e.camera,stream:null}};if(n.type===`challenge.dismiss`)return e.challenge?.id===n.id?{...e,challenge:null}:e;if(n.type===`voice.mode`)return{...e,voice:{...e.voice,mode:n.mode,level:n.mode===`idle`?0:e.voice.level}};if(n.type===`voice.level`){let t=Number.isFinite(n.level)?Math.min(1,Math.max(0,n.level)):0;return{...e,voice:{...e.voice,level:t}}}if(n.type===`object.dismiss`)return{...e,objects:e.objects.filter(e=>e.id!==n.id)};if(n.type===`object.place`)return{...e,objects:e.objects.map(e=>e.id===n.id?{...e,placement:n.placement}:e)};if(n.type===`alert.dismiss`)return{...e,alerts:e.alerts.filter(e=>e.id!==n.id)}}let r=eu.safeParse(t);if(!r.success)return e;let i=r.data;switch(i.type){case`snapshot`:return{...e,scene:i.stage.scene,objects:i.stage.objects,presence:{...e.presence,state:i.stage.presence.state,style:i.stage.presence.style},mood:i.stage.mood,approval:i.pendingApproval??null};case`stage`:return kE(e,i.command);case`chat.user`:return{...e,chat:EE([...e.chat,{role:`user`,text:i.text}]),chatLive:!1};case`ui.open`:return{...e,uiOpen:{n:(e.uiOpen?.n??0)+1,...i.integration?{integration:i.integration}:{}}};case`ui`:return{...e,view:i.view,look:i.look??e.look,ownerName:i.ownerName??e.ownerName,assistantName:i.assistantName??e.assistantName,hud:i.hud??e.hud,music:i.music??e.music,viewKnown:!0};case`music.host`:return{...e,hostMusic:i.state};case`music.command`:{let{type:t,...n}=i;return{...e,musicCmd:{n:(e.musicCmd?.n??0)+1,command:n}}}case`caption.delta`:{let t=e.captionDone,n=e.chat.at(-1),r=e.chatLive&&n?.role===`assistant`?[...e.chat.slice(0,-1),{role:`assistant`,text:n.text+i.text}]:EE([...e.chat,{role:`assistant`,text:i.text}]);return{...e,chat:r,chatLive:!0,captions:(t?``:e.captions)+i.text,captionDone:!1,presence:{...e.presence,amplitude:OE(.3+i.text.length*.04),pulse:e.presence.pulse+1}}}case`caption.end`:return{...e,chatLive:!1,captionDone:!0,presence:{...e.presence,amplitude:0}};case`approval.request`:{let{type:t,...n}=i;return{...e,approval:n}}case`approval.resolved`:return e.approval?.id===i.id?{...e,approval:null}:e;case`alert`:return{...e,alerts:[...e.alerts.slice(-3),{id:++DE,level:i.level,text:i.text}]};case`activity`:return{...e,activity:i.text};case`status`:return{...e,busy:i.busy,activity:i.busy?e.activity:null,deviceOnline:i.deviceOnline,voice:{...e.voice,available:i.voiceAvailable??e.voice.available,enrolled:i.voiceEnrolled??e.voice.enrolled}};case`error`:return{...e,alerts:[...e.alerts.slice(-3),{id:++DE,level:`error`,text:i.message}]};case`voice.heard`:return{...e,captions:i.trust===`guest`?`Guest: ${i.text}`:i.trust===`member`&&i.speaker?`${i.speaker}: ${i.text}`:i.text,captionDone:!0,speaker:{name:i.trust===`member`?i.speaker??null:null,trust:i.trust??`unverified`,seq:(e.speaker?.seq??0)+1}};case`voice.challenge`:return{...e,challenge:{id:i.id,text:i.text}};case`voice.challenge.end`:return e.challenge?.id===i.id?{...e,challenge:null}:e;case`audio.chunk`:case`audio.stop`:return e;case`camera.request`:case`camera.cancel`:case`screen.request`:case`screen.cancel`:return e}}var jE=1024,ME=.8,NE=300;function PE(e,t){let n=Math.min(1,jE/Math.max(e,t));return{width:Math.round(e*n),height:Math.round(t*n)}}function FE(e){let t=e?.name;return t===`NotAllowedError`||t===`SecurityError`?`permission`:t===`NotFoundError`||t===`OverconstrainedError`?`no-camera`:`busy`}async function IE(){if(!navigator.mediaDevices?.getUserMedia)throw Object.assign(Error(`This browser cannot use the camera here (use localhost or HTTPS).`),{name:`NotFoundError`});return navigator.mediaDevices.getUserMedia({video:{width:{ideal:1280}},audio:!1})}async function LE(e,t=NE){let n=document.createElement(`video`);n.muted=!0,n.playsInline=!0,n.srcObject=e,await n.play(),await new Promise(e=>setTimeout(e,t));let{width:r,height:i}=PE(n.videoWidth||640,n.videoHeight||480),a=document.createElement(`canvas`);return a.width=r,a.height=i,a.getContext(`2d`).drawImage(n,0,0,r,i),n.srcObject=null,new Promise((e,t)=>a.toBlob(n=>n?e(n):t(Error(`Could not encode the picture.`)),`image/jpeg`,ME))}var RE=class{opts;active=null;constructor(e){this.opts=e}async handle(e){if(e.type===`camera.cancel`){let t=this.active;t&&t.id===e.id&&(t.cancelled=!0,this.release(t));return}if(!this.opts.enabled())return this.opts.send({type:`camera.denied`,id:e.id,reason:`off`});if(this.active)return this.opts.send({type:`camera.denied`,id:e.id,reason:`busy`});let t={id:e.id,cancelled:!1,stream:null,opened:!1,released:!1};this.active=t;try{let n=await(this.opts.open??IE)();if(t.stream=n,t.cancelled){n.getTracks().forEach(e=>e.stop());return}t.opened=!0,this.opts.dispatch({type:`camera.open`,stream:n});let r=await(this.opts.frame??(e=>LE(e)))(n);if(t.cancelled)return;this.release(t);try{await this.opts.upload(e.id,r)}catch{this.opts.dispatch({type:`alert.add`,level:`warn`,text:`Could not send the camera picture to Friend.`})}}catch(n){t.cancelled||this.opts.send({type:`camera.denied`,id:e.id,reason:FE(n)})}finally{this.release(t),this.active===t&&(this.active=null)}}dispose(){let e=this.active;e&&(e.cancelled=!0,this.release(e))}release(e){e.released||(e.released=!0,e.stream?.getTracks().forEach(e=>e.stop()),e.opened&&this.opts.dispatch({type:`camera.closed`}))}};function zE(e,t){if(e.match(/^[a-z]+:\/\//i))return e;if(e.match(/^\/\//))return window.location.protocol+e;if(e.match(/^[a-z]+:/i))return e;let n=document.implementation.createHTMLDocument(),r=n.createElement(`base`),i=n.createElement(`a`);return n.head.appendChild(r),n.body.appendChild(i),t&&(r.href=t),i.href=e,i.href}var BE=(()=>{let e=0,t=()=>`0000${(Math.random()*36**4<<0).toString(36)}`.slice(-4);return()=>(e+=1,`u${t()}${e}`)})();function VE(e){let t=[];for(let n=0,r=e.length;n<r;n++)t.push(e[n]);return t}var HE=null;function UE(e={}){return HE||(e.includeStyleProperties?(HE=e.includeStyleProperties,HE):(HE=VE(window.getComputedStyle(document.documentElement)),HE))}function WE(e,t){let n=(e.ownerDocument.defaultView||window).getComputedStyle(e).getPropertyValue(t);return n?parseFloat(n.replace(`px`,``)):0}function GE(e){let t=WE(e,`border-left-width`),n=WE(e,`border-right-width`);return e.clientWidth+t+n}function KE(e){let t=WE(e,`border-top-width`),n=WE(e,`border-bottom-width`);return e.clientHeight+t+n}function qE(e,t={}){return{width:t.width||GE(e),height:t.height||KE(e)}}function JE(){let e,t;try{t=process}catch{}let n=t&&t.env?t.env.devicePixelRatio:null;return n&&(e=parseInt(n,10),Number.isNaN(e)&&(e=1)),e||window.devicePixelRatio||1}var YE=16384;function XE(e){(e.width>YE||e.height>YE)&&(e.width>YE&&e.height>YE?e.width>e.height?(e.height*=YE/e.width,e.width=YE):(e.width*=YE/e.height,e.height=YE):e.width>YE?(e.height*=YE/e.width,e.width=YE):(e.width*=YE/e.height,e.height=YE))}function ZE(e){return new Promise((t,n)=>{let r=new Image;r.onload=()=>{r.decode().then(()=>{requestAnimationFrame(()=>t(r))})},r.onerror=n,r.crossOrigin=`anonymous`,r.decoding=`async`,r.src=e})}async function QE(e){return Promise.resolve().then(()=>new XMLSerializer().serializeToString(e)).then(encodeURIComponent).then(e=>`data:image/svg+xml;charset=utf-8,${e}`)}async function $E(e,t,n){let r=`http://www.w3.org/2000/svg`,i=document.createElementNS(r,`svg`),a=document.createElementNS(r,`foreignObject`);return i.setAttribute(`width`,`${t}`),i.setAttribute(`height`,`${n}`),i.setAttribute(`viewBox`,`0 0 ${t} ${n}`),a.setAttribute(`width`,`100%`),a.setAttribute(`height`,`100%`),a.setAttribute(`x`,`0`),a.setAttribute(`y`,`0`),a.setAttribute(`externalResourcesRequired`,`true`),i.appendChild(a),a.appendChild(e),QE(i)}var eD=(e,t)=>{if(e instanceof t)return!0;let n=Object.getPrototypeOf(e);return n===null?!1:n.constructor.name===t.name||eD(n,t)};function tD(e){let t=e.getPropertyValue(`content`);return`${e.cssText} content: '${t.replace(/'|"/g,``)}';`}function nD(e,t){return UE(t).map(t=>`${t}: ${e.getPropertyValue(t)}${e.getPropertyPriority(t)?` !important`:``};`).join(` `)}function rD(e,t,n,r){let i=`.${e}:${t}`,a=n.cssText?tD(n):nD(n,r);return document.createTextNode(`${i}{${a}}`)}function iD(e,t,n,r){let i=window.getComputedStyle(e,n),a=i.getPropertyValue(`content`);if(a===``||a===`none`)return;let o=BE();try{t.className=`${t.className} ${o}`}catch{return}let s=document.createElement(`style`);s.appendChild(rD(o,n,i,r)),t.appendChild(s)}function aD(e,t,n){iD(e,t,`:before`,n),iD(e,t,`:after`,n)}var oD=`application/font-woff`,sD=`image/jpeg`,cD={woff:oD,woff2:oD,ttf:`application/font-truetype`,eot:`application/vnd.ms-fontobject`,png:`image/png`,jpg:sD,jpeg:sD,gif:`image/gif`,tiff:`image/tiff`,svg:`image/svg+xml`,webp:`image/webp`};function lD(e){let t=/\.([^./]*?)$/g.exec(e);return t?t[1]:``}function uD(e){return cD[lD(e).toLowerCase()]||``}function dD(e){return e.split(/,/)[1]}function fD(e){return e.search(/^(data:)/)!==-1}function pD(e,t){return`data:${t};base64,${e}`}async function mD(e,t,n){let r=await fetch(e,t);if(r.status===404)throw Error(`Resource "${r.url}" not found`);let i=await r.blob();return new Promise((e,t)=>{let a=new FileReader;a.onerror=t,a.onloadend=()=>{try{e(n({res:r,result:a.result}))}catch(e){t(e)}},a.readAsDataURL(i)})}var hD={};function gD(e,t,n){let r=e.replace(/\?.*/,``);return n&&(r=e),/ttf|otf|eot|woff2?/i.test(r)&&(r=r.replace(/.*\//,``)),t?`[${t}]${r}`:r}async function _D(e,t,n){let r=gD(e,t,n.includeQueryParams);if(hD[r]!=null)return hD[r];n.cacheBust&&(e+=(/\?/.test(e)?`&`:`?`)+new Date().getTime());let i;try{i=pD(await mD(e,n.fetchRequestInit,({res:e,result:n})=>(t||=e.headers.get(`Content-Type`)||``,dD(n))),t)}catch(t){i=n.imagePlaceholder||``;let r=`Failed to fetch resource: ${e}`;t&&(r=typeof t==`string`?t:t.message),r&&console.warn(r)}return hD[r]=i,i}async function vD(e){let t=e.toDataURL();return t===`data:,`?e.cloneNode(!1):ZE(t)}async function yD(e,t){if(e.currentSrc){let t=document.createElement(`canvas`),n=t.getContext(`2d`);return t.width=e.clientWidth,t.height=e.clientHeight,n?.drawImage(e,0,0,t.width,t.height),ZE(t.toDataURL())}let n=e.poster;return ZE(await _D(n,uD(n),t))}async function bD(e,t){try{if(e?.contentDocument?.body)return await AD(e.contentDocument.body,t,!0)}catch{}return e.cloneNode(!1)}async function xD(e,t){return eD(e,HTMLCanvasElement)?vD(e):eD(e,HTMLVideoElement)?yD(e,t):eD(e,HTMLIFrameElement)?bD(e,t):e.cloneNode(CD(e))}var SD=e=>e.tagName!=null&&e.tagName.toUpperCase()===`SLOT`,CD=e=>e.tagName!=null&&e.tagName.toUpperCase()===`SVG`;async function wD(e,t,n){if(CD(t))return t;let r=[];return r=SD(e)&&e.assignedNodes?VE(e.assignedNodes()):eD(e,HTMLIFrameElement)&&e.contentDocument?.body?VE(e.contentDocument.body.childNodes):VE((e.shadowRoot??e).childNodes),r.length===0||eD(e,HTMLVideoElement)||await r.reduce((e,r)=>e.then(()=>AD(r,n)).then(e=>{e&&t.appendChild(e)}),Promise.resolve()),t}function TD(e,t,n){let r=t.style;if(!r)return;let i=window.getComputedStyle(e);i.cssText?(r.cssText=i.cssText,r.transformOrigin=i.transformOrigin):UE(n).forEach(n=>{let a=i.getPropertyValue(n);n===`font-size`&&a.endsWith(`px`)&&(a=`${Math.floor(parseFloat(a.substring(0,a.length-2)))-.1}px`),eD(e,HTMLIFrameElement)&&n===`display`&&a===`inline`&&(a=`block`),n===`d`&&t.getAttribute(`d`)&&(a=`path(${t.getAttribute(`d`)})`),r.setProperty(n,a,i.getPropertyPriority(n))})}function ED(e,t){eD(e,HTMLTextAreaElement)&&(t.innerHTML=e.value),eD(e,HTMLInputElement)&&t.setAttribute(`value`,e.value)}function DD(e,t){if(eD(e,HTMLSelectElement)){let n=t,r=Array.from(n.children).find(t=>e.value===t.getAttribute(`value`));r&&r.setAttribute(`selected`,``)}}function OD(e,t,n){return eD(t,Element)&&(TD(e,t,n),aD(e,t,n),ED(e,t),DD(e,t)),t}async function kD(e,t){let n=e.querySelectorAll?e.querySelectorAll(`use`):[];if(n.length===0)return e;let r={};for(let i=0;i<n.length;i++){let a=n[i].getAttribute(`xlink:href`);if(a){let n=e.querySelector(a),i=document.querySelector(a);!n&&i&&!r[a]&&(r[a]=await AD(i,t,!0))}}let i=Object.values(r);if(i.length){let t=`http://www.w3.org/1999/xhtml`,n=document.createElementNS(t,`svg`);n.setAttribute(`xmlns`,t),n.style.position=`absolute`,n.style.width=`0`,n.style.height=`0`,n.style.overflow=`hidden`,n.style.display=`none`;let r=document.createElementNS(t,`defs`);n.appendChild(r);for(let e=0;e<i.length;e++)r.appendChild(i[e]);e.appendChild(n)}return e}async function AD(e,t,n){return!n&&t.filter&&!t.filter(e)?null:Promise.resolve(e).then(e=>xD(e,t)).then(n=>wD(e,n,t)).then(n=>OD(e,n,t)).then(e=>kD(e,t))}var jD=/url\((['"]?)([^'"]+?)\1\)/g,MD=/url\([^)]+\)\s*format\((["']?)([^"']+)\1\)/g,ND=/src:\s*(?:url\([^)]+\)\s*format\([^)]+\)[,;]\s*)+/g;function PD(e){let t=e.replace(/([.*+?^${}()|\[\]\/\\])/g,`\\$1`);return RegExp(`(url\\(['"]?)(${t})(['"]?\\))`,`g`)}function FD(e){let t=[];return e.replace(jD,(e,n,r)=>(t.push(r),e)),t.filter(e=>!fD(e))}async function ID(e,t,n,r,i){try{let a=n?zE(t,n):t,o=uD(t),s;return s=i?pD(await i(a),o):await _D(a,o,r),e.replace(PD(t),`$1${s}$3`)}catch{}return e}function LD(e,{preferredFontFormat:t}){return t?e.replace(ND,e=>{for(;;){let[n,,r]=MD.exec(e)||[];if(!r)return``;if(r===t)return`src: ${n};`}}):e}function RD(e){return e.search(jD)!==-1}async function zD(e,t,n){if(!RD(e))return e;let r=LD(e,n);return FD(r).reduce((e,r)=>e.then(e=>ID(e,r,t,n)),Promise.resolve(r))}async function BD(e,t,n){let r=t.style?.getPropertyValue(e);if(r){let i=await zD(r,null,n);return t.style.setProperty(e,i,t.style.getPropertyPriority(e)),!0}return!1}async function VD(e,t){await BD(`background`,e,t)||await BD(`background-image`,e,t),await BD(`mask`,e,t)||await BD(`-webkit-mask`,e,t)||await BD(`mask-image`,e,t)||await BD(`-webkit-mask-image`,e,t)}async function HD(e,t){let n=eD(e,HTMLImageElement);if((!n||fD(e.src))&&(!eD(e,SVGImageElement)||fD(e.href.baseVal)))return;let r=n?e.src:e.href.baseVal,i=await _D(r,uD(r),t);await new Promise((r,a)=>{e.onload=r,e.onerror=t.onImageErrorHandler?(...e)=>{try{r(t.onImageErrorHandler(...e))}catch(e){a(e)}}:a;let o=e;o.decode&&=r,o.loading===`lazy`&&(o.loading=`eager`),n?(e.srcset=``,e.src=i):e.href.baseVal=i})}async function UD(e,t){let n=VE(e.childNodes).map(e=>WD(e,t));await Promise.all(n).then(()=>e)}async function WD(e,t){eD(e,Element)&&(await VD(e,t),await HD(e,t),await UD(e,t))}function GD(e,t){let{style:n}=e;t.backgroundColor&&(n.backgroundColor=t.backgroundColor),t.width&&(n.width=`${t.width}px`),t.height&&(n.height=`${t.height}px`);let r=t.style;return r!=null&&Object.keys(r).forEach(e=>{n[e]=r[e]}),e}var KD={};async function qD(e){let t=KD[e];return t??(t={url:e,cssText:await(await fetch(e)).text()},KD[e]=t,t)}async function JD(e,t){let n=e.cssText,r=/url\(["']?([^"')]+)["']?\)/g,i=(n.match(/url\([^)]+\)/g)||[]).map(async i=>{let a=i.replace(r,`$1`);return a.startsWith(`https://`)||(a=new URL(a,e.url).href),mD(a,t.fetchRequestInit,({result:e})=>(n=n.replace(i,`url(${e})`),[i,e]))});return Promise.all(i).then(()=>n)}function YD(e){if(e==null)return[];let t=[],n=e.replace(/(\/\*[\s\S]*?\*\/)/gi,``),r=RegExp(`((@.*?keyframes [\\s\\S]*?){([\\s\\S]*?}\\s*?)})`,`gi`);for(;;){let e=r.exec(n);if(e===null)break;t.push(e[0])}n=n.replace(r,``);let i=/@import[\s\S]*?url\([^)]*\)[\s\S]*?;/gi,a=RegExp(`((\\s*?(?:\\/\\*[\\s\\S]*?\\*\\/)?\\s*?@media[\\s\\S]*?){([\\s\\S]*?)}\\s*?})|(([\\s\\S]*?){([\\s\\S]*?)})`,`gi`);for(;;){let e=i.exec(n);if(e===null){if(e=a.exec(n),e===null)break;i.lastIndex=a.lastIndex}else a.lastIndex=i.lastIndex;t.push(e[0])}return t}async function XD(e,t){let n=[],r=[];return e.forEach(n=>{if(`cssRules`in n)try{VE(n.cssRules||[]).forEach((e,i)=>{if(e.type===CSSRule.IMPORT_RULE){let a=i+1,o=e.href,s=qD(o).then(e=>JD(e,t)).then(e=>YD(e).forEach(e=>{try{n.insertRule(e,e.startsWith(`@import`)?a+=1:n.cssRules.length)}catch(t){console.error(`Error inserting rule from remote css`,{rule:e,error:t})}})).catch(e=>{console.error(`Error loading remote css`,e.toString())});r.push(s)}})}catch(i){let a=e.find(e=>e.href==null)||document.styleSheets[0];n.href!=null&&r.push(qD(n.href).then(e=>JD(e,t)).then(e=>YD(e).forEach(e=>{a.insertRule(e,a.cssRules.length)})).catch(e=>{console.error(`Error loading remote stylesheet`,e)})),console.error(`Error inlining remote css file`,i)}}),Promise.all(r).then(()=>(e.forEach(e=>{if(`cssRules`in e)try{VE(e.cssRules||[]).forEach(e=>{n.push(e)})}catch(t){console.error(`Error while reading CSS rules from ${e.href}`,t)}}),n))}function ZD(e){return e.filter(e=>e.type===CSSRule.FONT_FACE_RULE).filter(e=>RD(e.style.getPropertyValue(`src`)))}async function QD(e,t){if(e.ownerDocument==null)throw Error(`Provided element is not within a Document`);return ZD(await XD(VE(e.ownerDocument.styleSheets),t))}function $D(e){return e.trim().replace(/["']/g,``)}function eO(e){let t=new Set;function n(e){(e.style.fontFamily||getComputedStyle(e).fontFamily).split(`,`).forEach(e=>{t.add($D(e))}),Array.from(e.children).forEach(e=>{e instanceof HTMLElement&&n(e)})}return n(e),t}async function tO(e,t){let n=await QD(e,t),r=eO(e);return(await Promise.all(n.filter(e=>r.has($D(e.style.fontFamily))).map(e=>{let n=e.parentStyleSheet?e.parentStyleSheet.href:null;return zD(e.cssText,n,t)}))).join(`
|
|
4456
|
+
`)}async function nO(e,t){let n=t.fontEmbedCSS==null?t.skipFonts?null:await tO(e,t):t.fontEmbedCSS;if(n){let t=document.createElement(`style`),r=document.createTextNode(n);t.appendChild(r),e.firstChild?e.insertBefore(t,e.firstChild):e.appendChild(t)}}async function rO(e,t={}){let{width:n,height:r}=qE(e,t),i=await AD(e,t,!0);return await nO(i,t),await WD(i,t),GD(i,t),await $E(i,n,r)}async function iO(e,t={}){let{width:n,height:r}=qE(e,t),i=await ZE(await rO(e,t)),a=document.createElement(`canvas`),o=a.getContext(`2d`),s=t.pixelRatio||JE(),c=t.canvasWidth||n,l=t.canvasHeight||r;return a.width=c*s,a.height=l*s,t.skipAutoScale||XE(a),a.style.width=`${c}`,a.style.height=`${l}`,t.backgroundColor&&(o.fillStyle=t.backgroundColor,o.fillRect(0,0,a.width,a.height)),o.drawImage(i,0,0,a.width,a.height),a}var aO=1600,oO=.85;function sO(e,t){let n=Math.min(1,aO/Math.max(e,t,1));return{width:Math.max(1,Math.round(e*n)),height:Math.max(1,Math.round(t*n))}}async function cO(){let e=document.documentElement.getBoundingClientRect(),t=await iO(document.body,{width:Math.round(e.width),height:Math.round(e.height),pixelRatio:1,backgroundColor:`#050b10`,filter:e=>!(e instanceof HTMLElement&&e.dataset.noCapture!==void 0)}),n=sO(t.width,t.height),r=document.createElement(`canvas`);return r.width=n.width,r.height=n.height,r.getContext(`2d`).drawImage(t,0,0,n.width,n.height),new Promise((e,t)=>r.toBlob(n=>n?e(n):t(Error(`Could not encode the picture.`)),`image/jpeg`,oO))}var lO=class{opts;active=null;constructor(e){this.opts=e}async handle(e){if(e.type===`screen.cancel`){this.active&&this.active.id===e.id&&(this.active.cancelled=!0);return}if(this.active)return this.opts.send({type:`screen.denied`,id:e.id,reason:`busy`});let t={id:e.id,cancelled:!1};this.active=t;try{let n=await(this.opts.capture??cO)();if(t.cancelled)return;try{await this.opts.upload(e.id,n)}catch{this.opts.dispatch({type:`alert.add`,level:`warn`,text:`Could not send the picture of the screen to Friend.`})}}catch(n){t.cancelled||this.opts.send({type:`screen.denied`,id:e.id,reason:uO(n)})}finally{this.active===t&&(this.active=null)}}dispose(){this.active&&(this.active.cancelled=!0)}};function uO(e){return e?.name===`NotSupportedError`?`unsupported`:`failed`}var dO={401:`Please sign in again.`,413:`That recording was too long.`,409:`Friend is busy with the last request. Try again in a moment.`,429:`You're talking too fast. Wait a moment.`,503:`Voice is not available. Run: friend voice setup`};async function fO(e,t){let n;try{n=await fetch(`/api/voice/utterance`,{method:`POST`,headers:{"content-type":e.type||`audio/webm`},body:e,signal:t})}catch(e){throw e.name===`AbortError`?e:Error(`Could not reach Friend. Check the connection.`)}if(!n.ok){let e=``;try{e=(await n.json()).error??``}catch{}throw Error(e||dO[n.status]||`The voice request failed (${n.status}).`)}let r=await n.json();return{text:typeof r.text==`string`?r.text:``}}var pO=0,mO=new Set;function hO(e){return mO.add(e),()=>mO.delete(e)}var gO=e=>mO.forEach(t=>{try{t(e)}catch{}}),_O=e=>/not compatible|audio capture|audiosession/i.test(String(e?.message??e));function vO(e){try{let t=navigator.audioSession;t&&t.type!==e&&(t.type=e)}catch{}}function yO(){pO===0&&vO(`playback`)}function bO(){pO++,pO===1&&gO(!0),vO(`play-and-record`);let e=!1;return()=>{e||(e=!0,pO=Math.max(0,pO-1),pO===0&&(vO(`playback`),gO(!1)))}}var xO=4096,SO=8,CO=20,wO=6e6;function TO(e){try{let t=atob(e),n=new Uint8Array(t.length);for(let e=0;e<t.length;e++)n[e]=t.charCodeAt(e);return n}catch{return null}}var EO=class{ctx=null;analyser=null;pending=new Map;queue=[];current=null;busy=!1;gen=0;isPlaying=!1;unwatch=null;listeners=new Set;unlock(){yO();let e=this.ensureContext();e.state!==`running`&&e.resume().catch(()=>{})}locked(){return!this.ctx||this.ctx.state!==`running`}enqueue(e){if(!Number.isInteger(e.seq)||e.seq<0||e.seq>xO)return;let t=TO(e.data);if(!t)return;let n=this.pending.get(e.id);if(n||(this.pending.size>=SO&&this.pending.delete(this.pending.keys().next().value),n={parts:new Map,lastSeq:null,bytes:0},this.pending.set(e.id,n)),n.bytes+=t.length,n.bytes>wO){this.pending.delete(e.id);return}if(n.parts.set(e.seq,t),e.last&&(n.lastSeq=e.seq),n.lastSeq===null||n.parts.size!==n.lastSeq+1)return;this.pending.delete(e.id);let r=new Uint8Array([...n.parts.values()].reduce((e,t)=>e+t.length,0)),i=0;for(let e=0;e<=n.lastSeq;e++){let t=n.parts.get(e);if(!t)return;r.set(t,i),i+=t.length}for(this.queue.push(r.buffer);this.queue.length>CO;)this.queue.shift();this.pump()}stop(){this.gen++,this.queue=[],this.pending.clear(),this.busy=!1;let e=this.current;if(this.current=null,e){e.onended=null;try{e.stop()}catch{}}this.setPlaying(!1)}dispose(){this.stop(),this.ctx?.close().catch(()=>{}),this.unwatch?.(),this.unwatch=null,this.ctx=null,this.analyser=null}playing(){return this.isPlaying}onChange(e){return this.listeners.add(e),()=>this.listeners.delete(e)}level(){if(!this.analyser||!this.isPlaying)return 0;let e=new Uint8Array(this.analyser.fftSize);this.analyser.getByteTimeDomainData(e);let t=0;for(let n of e)t+=((n-128)/128)**2;return Math.min(1,Math.sqrt(t/e.length)*4)}ensureContext(){if(!this.ctx){let e=window.AudioContext??window.webkitAudioContext;this.ctx=new e,this.analyser=this.ctx.createAnalyser(),this.analyser.fftSize=1024,this.analyser.connect(this.ctx.destination);let t=this.ctx;this.unwatch?.(),this.unwatch=hO(e=>{e&&t.state===`running`?t.suspend().catch(()=>{}):!e&&t.state!==`running`&&t.state!==`closed`&&t.resume().catch(()=>{})})}return this.ctx}setPlaying(e){this.isPlaying!==e&&(this.isPlaying=e,this.listeners.forEach(t=>t(e)))}async pump(){if(this.busy)return;let e=this.queue.shift();if(!e){this.setPlaying(!1);return}this.busy=!0;let t=this.gen;try{let n=this.ensureContext();if(n.state!==`running`){try{await n.resume()}catch{}if(t!==this.gen)return;if(n.state!==`running`){this.queue.unshift(e),this.busy=!1;return}}let r=await n.decodeAudioData(e);if(t!==this.gen)return;let i=n.createBufferSource();i.buffer=r,i.connect(this.analyser),i.onended=()=>{this.current===i&&(this.current=null,this.busy=!1,this.pump())},this.current=i,this.setPlaying(!0),i.start()}catch{if(t!==this.gen)return;this.busy=!1,this.pump()}}},DO=e=>new Promise(t=>setTimeout(t,e)),OO=[`audio/webm;codecs=opus`,`audio/webm`,`audio/mp4`,`audio/ogg;codecs=opus`],kO=3e3;function AO(e){let t=e;return t?.name===`NotAllowedError`||t?.name===`SecurityError`?Error(`Microphone permission was denied. Allow it in the browser to talk.`):t?.name===`NotFoundError`||t?.name===`OverconstrainedError`?Error(`No microphone was found.`):Error(t?.message||`Could not open the microphone.`)}var jO=class e{opts;stream=null;rec=null;chunks=[];ctx=null;analyser=null;timer=null;starting=!1;leaveSession=null;constructor(e={}){this.opts=e}static supported(){return typeof navigator<`u`&&!!navigator.mediaDevices?.getUserMedia&&typeof MediaRecorder<`u`}get active(){return this.rec!==null}async start(){if(!(this.rec||this.starting)){if(!e.supported())throw Error(`This browser cannot record audio here (use localhost or HTTPS).`);this.starting=!0;try{this.leaveSession=bO();try{let e=()=>navigator.mediaDevices.getUserMedia({audio:{echoCancellation:!0,noiseSuppression:!0}});try{this.stream=await e()}catch(t){if(!_O(t))throw t;await DO(250),this.leaveSession?.(),this.leaveSession=bO(),this.stream=await e()}}catch(e){throw this.leaveSession?.(),this.leaveSession=null,AO(e)}try{let e=OO.find(e=>MediaRecorder.isTypeSupported(e));this.chunks=[];let t=new MediaRecorder(this.stream,e?{mimeType:e}:void 0);t.ondataavailable=e=>{e.data&&e.data.size>0&&this.chunks.push(e.data)},t.onerror=()=>this.failed();for(let e of this.stream.getTracks())e.onended=()=>this.failed();this.openMeter(this.stream),t.start(250),this.rec=t,this.opts.maxMs&&(this.timer=setTimeout(()=>{this.timer=null,this.opts.onLimit?.()},this.opts.maxMs))}catch(e){throw this.release(),AO(e)}}finally{this.starting=!1}}}stop(){let e=this.rec;return e?new Promise(t=>{let n=!1,r=null,i=()=>{if(n)return;n=!0,r&&clearTimeout(r);let i=new Blob(this.chunks,{type:e.mimeType||`audio/webm`});this.release(),t(i)};if(r=setTimeout(i,kO),e.onstop=i,e.state===`inactive`)return i();try{e.stop()}catch{i()}}):Promise.reject(Error(`Not recording.`))}cancel(){let e=this.rec;if(e){e.ondataavailable=null,e.onstop=null,e.onerror=null;try{e.state!==`inactive`&&e.stop()}catch{}}this.release()}level(){if(!this.analyser||!this.rec)return 0;let e=new Uint8Array(this.analyser.fftSize);this.analyser.getByteTimeDomainData(e);let t=0;for(let n of e)t+=((n-128)/128)**2;return Math.min(1,Math.sqrt(t/e.length)*4)}failed(){this.rec&&(this.cancel(),this.opts.onError?.())}openMeter(e){try{this.ctx=new AudioContext,this.analyser=this.ctx.createAnalyser(),this.analyser.fftSize=1024,this.ctx.createMediaStreamSource(e).connect(this.analyser)}catch{this.analyser=null}}release(){this.timer&&clearTimeout(this.timer),this.timer=null,this.stream?.getTracks().forEach(e=>{e.onended=null,e.stop()}),this.ctx?.close().catch(()=>{}),this.stream=null,this.rec=null,this.ctx=null,this.analyser=null,this.chunks=[],this.leaveSession?.(),this.leaveSession=null}},MO=2e3,NO=()=>typeof window<`u`&&window.isSecureContext===!1,PO=50,FO=class{deps;recorder;player;mode=`idle`;pressed=!1;disposed=!1;uploads=0;toldAboutSound=!1;abort=null;poll=null;unsubscribe;constructor(e){this.deps=e;let t=()=>this.recorderFailed();this.recorder=e.recorder??e.makeRecorder?.(t)??new jO({maxMs:6e4,onLimit:()=>void this.pressEnd(),onError:t}),this.player=e.player??new EO,this.unsubscribe=this.player.onChange(e=>{this.mode!==`listening`&&this.mode!==`transcribing`&&this.setMode(e?`speaking`:`idle`)})}async pressStart(){if(!(this.pressed||this.disposed)){if(!this.deps.available()){this.alert(`warn`,`Voice is not available. Run: friend voice setup`);return}if(!(this.deps.supported?.()??jO.supported())){this.alert(`warn`,NO()?`This page is not secure, so the browser blocks the microphone. On the PC run: friend lan https on, restart Friend, and open the https:// address.`:`This browser cannot record audio here (use localhost or HTTPS).`);return}this.pressed=!0,this.player.unlock(),this.player.playing()&&(this.deps.send({type:`voice.interrupt`}),this.player.stop());try{await this.recorder.start()}catch(e){this.pressed=!1,this.alert(`error`,e.message),this.setMode(`idle`);return}if(!this.pressed){this.recorder.cancel(),this.setMode(`idle`);return}this.setMode(`listening`)}}async pressEnd(){if(!this.pressed||(this.pressed=!1,!this.recorder.active))return;let e=await this.recorder.stop();if(e.size<MO){this.alert(`info`,`Hold the key a little longer while you speak.`),this.setMode(`idle`);return}this.setMode(`transcribing`);let t=new AbortController;this.abort=t,this.uploads++;try{let{text:n}=await this.deps.post(e,t.signal);n.trim()||this.alert(`info`,`I didn't catch that.`)}catch(e){e.name!==`AbortError`&&this.alert(`error`,e.message)}finally{this.uploads--,this.abort===t&&(this.abort=null),this.settle()}}blur(){this.pressed&&(this.pressed=!1,this.recorder.cancel(),this.setMode(`idle`))}handleServer(e){if(e.type!==`audio.chunk`)return this.player.stop();this.player.enqueue(e),!this.toldAboutSound&&this.player.locked?.()&&(this.toldAboutSound=!0,this.deps.dispatch({type:`alert.add`,level:`info`,text:`Sound is blocked by the browser. Click or press a key once anywhere on the page to hear me.`}))}unlock(){this.player.unlock()}dispose(){this.disposed=!0,this.pressed=!1,this.stopPolling(),this.abort?.abort(),this.recorder.cancel(),this.player.stop(),this.player.dispose?.(),this.unsubscribe()}recorderFailed(){this.pressed=!1,this.recorder.cancel(),this.alert(`error`,`The microphone stopped working.`),this.setMode(`idle`)}settle(){this.uploads>0||this.mode!==`transcribing`||this.setMode(this.player.playing()?`speaking`:`idle`)}setMode(e){this.disposed||(this.mode=e,this.deps.dispatch({type:`voice.mode`,mode:e}),e===`listening`||e===`speaking`?this.startPolling():this.stopPolling())}startPolling(){this.stopPolling(),this.poll=setInterval(()=>{let e=this.mode===`listening`?this.recorder.level():this.player.level();this.deps.dispatch({type:`voice.level`,level:e})},PO)}stopPolling(){this.poll&&clearInterval(this.poll),this.poll=null}alert(e,t){this.disposed||this.deps.dispatch({type:`alert.add`,level:e,text:t})}};function IO(e){let[t,n]=(0,l.useReducer)(AE,wE),r=(0,l.useRef)(null),i=(0,l.useRef)(null),a=(0,l.useRef)(null),o=(0,l.useRef)(e);o.current=e;let s=(0,l.useRef)(t);return s.current=t,(0,l.useEffect)(()=>{let e=CE();r.current=e;let t=new FO({send:t=>e.send(t),dispatch:e=>n(e),post:fO,available:()=>s.current.voice.available});i.current=t;let c=new RE({send:t=>e.send(t),dispatch:e=>n(e),enabled:()=>s.current.camera.enabled,upload:async(e,t)=>{let n=await fetch(`/api/camera/frame/${encodeURIComponent(e)}`,{method:`POST`,headers:{"content-type":`image/jpeg`},body:t});if(!n.ok)throw Error(`upload failed (${n.status})`)}});a.current=c;let l=new lO({send:t=>e.send(t),dispatch:e=>n(e),upload:async(e,t)=>{let n=await fetch(`/api/screen/frame/${encodeURIComponent(e)}`,{method:`POST`,headers:{"content-type":`image/jpeg`},body:t});if(!n.ok)throw Error(`upload failed (${n.status})`)}}),u=e.onMessage(e=>{n(e);let r=e?.type,i=e?.id;(r===`camera.request`||r===`camera.cancel`)&&typeof i==`string`&&c.handle({type:r,id:i}),(r===`screen.request`||r===`screen.cancel`)&&typeof i==`string`&&l.handle({type:r,id:i}),(r===`audio.chunk`||r===`audio.stop`)&&t.handleServer(e)}),d=e.onState(e=>{n({type:`conn`,value:e}),e===`unauthorized`&&o.current(),e===`elsewhere`&&(t.blur(),c.dispose(),l.dispose())});return()=>{u(),d(),t.dispose(),c.dispose(),l.dispose(),e.close(),i.current=null,a.current=null,r.current=null}},[]),(0,l.useEffect)(()=>{t.camera.enabled||a.current?.dispose()},[t.camera.enabled]),{state:t,send:(0,l.useCallback)(e=>r.current?.send(e),[]),dispatch:(0,l.useCallback)(e=>n(e),[]),voice:(0,l.useMemo)(()=>({pressStart:()=>void i.current?.pressStart(),pressEnd:()=>void i.current?.pressEnd(),blur:()=>i.current?.blur(),unlock:()=>i.current?.unlock()}),[]),useHere:(0,l.useCallback)(()=>r.current?.takeOver(),[])}}var LO={401:`Please sign in again.`,403:`Incorrect PIN.`,413:`That recording was too long.`,429:`Too many attempts. Wait a moment.`,503:`Voice is not available. Run: friend voice setup`};async function RO(e,t){let n;try{n=await fetch(e,t)}catch{throw Error(`Could not reach Friend. Check the connection.`)}if(!n.ok){let e=``;try{e=(await n.json()).error??``}catch{}throw Error(e||LO[n.status]||`The request failed (${n.status}).`)}return await n.json()}var zO=(e,t)=>({method:e,headers:{"content-type":`application/json`},body:JSON.stringify(t)}),BO={state:()=>RO(`/api/voice/enroll`,{}),sample:e=>RO(`/api/voice/enroll/sample`,{method:`POST`,headers:{"content-type":e.type||`audio/webm`},body:e}),finish:e=>RO(`/api/voice/enroll/finish`,zO(`POST`,{pin:e})),cancel:async()=>{await RO(`/api/voice/enroll/cancel`,zO(`POST`,{}))},remove:async e=>{await RO(`/api/voice/enroll`,zO(`DELETE`,{pin:e}))}},VO=[`Friend, good evening. It is a pleasant day to get things done.`,`Open my projects and show me what changed today.`,`My voice is my key, so please remember it well.`,`Check the weather and read me the latest headlines.`,`Always protect the boss, and never trust a stranger.`],HO=15e3;function UO({api:e=BO,createRecorder:t=e=>new jO(e),onClose:n,who:r}){let[i,a]=(0,l.useState)(null),[o,s]=(0,l.useState)(0),[c,u]=(0,l.useState)(null),[f,m]=(0,l.useState)(`record`),[h,g]=(0,l.useState)(!1),[_,v]=(0,l.useState)(!1),[y,b]=(0,l.useState)(null),[S,C]=(0,l.useState)(``),w=(0,l.useRef)(!0),T=(0,l.useRef)(null);(0,l.useEffect)(()=>(w.current=!0,e.state().then(e=>{w.current&&(a(e),s(e.samples))}).catch(e=>w.current&&b(e.message)),()=>{w.current=!1,T.current?.cancel(),T.current=null}),[e]);let E=(0,l.useCallback)(async()=>{let t=T.current;if(t){T.current=null,g(!1),v(!0);try{let n=await t.stop(),r=await e.sample(n);if(!w.current)return;s(r.count),u(r.note)}catch(e){w.current&&b(e.message)}finally{w.current&&v(!1)}}},[e]),D=async()=>{b(null),u(null);let e=t({maxMs:HO,onLimit:()=>void E(),onError:()=>{T.current=null,w.current&&(g(!1),b(`The microphone stopped working. Try again.`))}});try{await e.start()}catch(e){w.current&&b(e.message);return}if(!w.current)return e.cancel();T.current=e,g(!0)},O=async e=>{b(null),v(!0);try{await e()}catch(e){w.current&&b(e.message)}finally{w.current&&(v(!1),C(``))}},k=async()=>{T.current?.cancel(),T.current=null,await e.cancel().catch(()=>{}),n()},A=i?.min??3,j=o%VO.length,ee=o<VO.length?`Phrase ${o+1} of ${VO.length}`:`Extra recording (${o} so far)`;return(0,p.jsxs)(`div`,{className:`approval enroll glass`,role:`dialog`,"aria-label":`Voice enrollment`,style:{pointerEvents:`auto`},children:[(0,p.jsx)(`div`,{className:`approval-head`,children:(0,p.jsx)(`span`,{className:`approval-title`,children:r?`Teach Friend ${r}'s voice`:`Teach Friend your voice`})}),f===`record`&&(0,p.jsxs)(p.Fragment,{children:[!r&&i?.enrolled&&(0,p.jsx)(`p`,{className:`auth-note`,children:`Your voice is already saved. Saving a new one replaces it.`}),r&&(0,p.jsxs)(`p`,{className:`auth-note`,children:[`Hand the device to `,r,`. `,r,` reads each sentence aloud, close to the microphone, in a quiet room.`]}),(0,p.jsxs)(`p`,{className:`auth-note`,children:[ee,`. Press Record, read this aloud in a quiet room, then press Stop.`]}),(0,p.jsx)(`pre`,{className:`approval-summary`,"data-testid":`enroll-phrase`,style:{whiteSpace:`pre-wrap`},children:VO[j]}),(0,p.jsxs)(`div`,{role:`status`,className:`auth-note`,children:[o,` recorded`,o>=A?` — enough to save`:` — at least ${A} needed`,`.`,c?` ${c}`:``]}),y&&(0,p.jsx)(`p`,{role:`alert`,className:`auth-error`,children:y}),(0,p.jsxs)(`div`,{className:`approval-actions`,children:[h?(0,p.jsx)(`button`,{type:`button`,style:d,className:`danger`,onClick:()=>void E(),children:`Stop`}):(0,p.jsx)(`button`,{type:`button`,style:d,className:`primary`,disabled:_||!i||o>=(i?.max??8),onClick:()=>void D(),children:_?`Uploading…`:`Record`}),(0,p.jsx)(`button`,{type:`button`,style:d,disabled:h||_||o<A,onClick:()=>m(`pin-save`),children:r?`Save ${r}'s voice`:`Save my voice`}),!r&&i?.enrolled&&(0,p.jsx)(`button`,{type:`button`,style:d,className:`danger`,disabled:h||_,onClick:()=>m(`pin-delete`),children:`Delete my voice`}),(0,p.jsx)(`button`,{type:`button`,style:d,onClick:()=>void k(),children:`Cancel`})]})]}),(f===`pin-save`||f===`pin-delete`)&&(0,p.jsxs)(p.Fragment,{children:[(0,p.jsx)(`p`,{className:`auth-note`,children:f===`pin-save`?r?`Enter your PIN to save ${r}'s voice.`:`Enter your PIN to save your voice.`:`Enter your PIN to delete your saved voice.`}),(0,p.jsx)(x,{pin:S,onChange:C,onSubmit:f===`pin-save`?()=>!_&&void O(async()=>{await e.finish(S),w.current&&m(`saved`)}):void 0}),y&&(0,p.jsx)(`p`,{role:`alert`,className:`auth-error`,children:y}),(0,p.jsxs)(`div`,{className:`approval-actions`,children:[f===`pin-save`?(0,p.jsx)(`button`,{type:`button`,style:d,className:`primary`,disabled:_||S.length<6,onClick:()=>void O(async()=>{await e.finish(S),w.current&&m(`saved`)}),children:`Save`}):(0,p.jsx)(`button`,{type:`button`,style:d,className:`danger`,disabled:_||S.length<6,onClick:()=>void O(async()=>{await e.remove(S),w.current&&m(`deleted`)}),children:`Delete`}),(0,p.jsx)(`button`,{type:`button`,style:d,onClick:()=>{C(``),b(null),m(`record`)},children:`Back`})]})]}),(f===`saved`||f===`deleted`)&&(0,p.jsxs)(p.Fragment,{children:[(0,p.jsx)(`p`,{className:`auth-note`,children:f===`saved`?r?`${r}'s voice is saved. From now on I will know when ${r} is talking.`:`Your voice is saved. From now on I will tell you apart from other speakers.`:`Your voice was deleted. Every voice is treated as yours until you enroll again.`}),(0,p.jsx)(`div`,{className:`approval-actions`,children:(0,p.jsx)(`button`,{type:`button`,style:d,className:`primary`,onClick:n,children:`Done`})})]})]})}var WO=new Set([`INPUT`,`TEXTAREA`,`SELECT`,`BUTTON`,`A`,`SUMMARY`]),GO=new Set([`button`,`checkbox`,`switch`,`tab`,`menuitem`,`link`,`radio`,`option`,`textbox`,`combobox`,`slider`]),KO=e=>e instanceof HTMLElement&&(WO.has(e.tagName)||e.isContentEditable||GO.has(e.getAttribute(`role`)??``)),qO=e=>e.code===`Space`||e.key===` `;function JO(e){let t=(0,l.useRef)(e);t.current=e,(0,l.useEffect)(()=>{let e=!1,n=n=>{!qO(n)||n.ctrlKey||n.metaKey||n.altKey||KO(n.target)||KO(document.activeElement)||(n.preventDefault(),!(n.repeat||e)&&(e=!0,t.current.pressStart()))},r=n=>{qO(n)&&e&&(e=!1,n.preventDefault(),t.current.pressEnd())},i=()=>{e=!1,t.current.blur()},a=()=>{document.hidden&&i()};return window.addEventListener(`keydown`,n),window.addEventListener(`keyup`,r),window.addEventListener(`blur`,i),document.addEventListener(`visibilitychange`,a),()=>{window.removeEventListener(`keydown`,n),window.removeEventListener(`keyup`,r),window.removeEventListener(`blur`,i),document.removeEventListener(`visibilitychange`,a)}},[])}function YO(e){let t=(0,l.useRef)(e);t.current=e,(0,l.useEffect)(()=>{let e=()=>t.current.unlock(),n=[`pointerdown`,`keydown`,`touchend`];for(let t of n)window.addEventListener(t,e,{passive:!0});return()=>{for(let t of n)window.removeEventListener(t,e)}},[])}function XO({onUseHere:e}){return(0,p.jsx)(`div`,{className:`elsewhere`,role:`alertdialog`,"aria-labelledby":`elsewhere-title`,"data-testid":`elsewhere`,children:(0,p.jsxs)(`div`,{className:`elsewhere-card`,children:[(0,p.jsx)(`h2`,{id:`elsewhere-title`,children:`Friend is open in another window`}),(0,p.jsx)(`p`,{children:`Friend works in one window at a time. Click “Use here” to use it in this window instead; the other one will stop.`}),(0,p.jsx)(`button`,{type:`button`,className:`elsewhere-btn`,onClick:e,autoFocus:!0,children:`Use here`})]})})}function ZO(e,t,n){let r=Math.max(100,Math.round(e)),i=Math.max(100,Math.round(t));return{width:r,height:i,kind:r<=599?`phone`:n||r<1024?`tablet`:`desktop`,orientation:i>r?`portrait`:`landscape`,touch:n}}var QO=()=>typeof matchMedia==`function`&&matchMedia(`(pointer: coarse)`).matches;function $O(){return ZO(window.innerWidth,window.innerHeight,QO())}var ek=(e,t)=>!!e&&e.width===t.width&&e.height===t.height&&e.kind===t.kind&&e.orientation===t.orientation&&e.touch===t.touch;function tk(e,t){let n=(0,l.useRef)(null),r=(0,l.useRef)(e);r.current=e,(0,l.useEffect)(()=>{if(t!==`open`){n.current=null;return}let e=()=>{let e=$O();ek(n.current,e)||(n.current=e,r.current({type:`ui.screen`,...e}))};e();let i=null,a=()=>{i&&clearTimeout(i),i=setTimeout(e,400)};return window.addEventListener(`resize`,a),window.addEventListener(`orientationchange`,a),()=>{i&&clearTimeout(i),window.removeEventListener(`resize`,a),window.removeEventListener(`orientationchange`,a)}},[t])}var nk={401:`Please sign in again.`,403:`Incorrect PIN.`,413:`That recording was too long.`,429:`Too many attempts. Wait a moment.`,503:`Voice is not available. Run: friend voice setup`};async function rk(e,t={}){let n;try{n=await fetch(e,t)}catch{throw Error(`Could not reach Friend. Check the connection.`)}if(!n.ok){let e=``;try{e=(await n.json()).error??``}catch{}throw Error(e||nk[n.status]||`The request failed (${n.status}).`)}return await n.json()}var ik=(e,t)=>({method:e,headers:{"content-type":`application/json`},body:JSON.stringify(t)}),ak={overview:()=>rk(`/api/voice/people`),begin:e=>rk(`/api/voice/people/begin`,ik(`POST`,{name:e})),recording:{state:async()=>(await rk(`/api/voice/people`)).enrolling??{enrolled:!1,samples:0,min:3,max:8},sample:e=>rk(`/api/voice/people/sample`,{method:`POST`,headers:{"content-type":e.type||`audio/webm`},body:e}),finish:e=>rk(`/api/voice/people/finish`,ik(`POST`,{pin:e})),cancel:async()=>{await rk(`/api/voice/people/cancel`,ik(`POST`,{}))},remove:async()=>{}},removePerson:async(e,t)=>{await rk(`/api/voice/people/${e}`,ik(`DELETE`,{pin:t}))}};function ok({api:e=ak,createRecorder:t,onClose:n}){let[r,i]=(0,l.useState)(null),[a,o]=(0,l.useState)({kind:`list`}),[s,c]=(0,l.useState)(``),[u,f]=(0,l.useState)(``),[m,h]=(0,l.useState)(!1),[g,_]=(0,l.useState)(null),v=(0,l.useRef)(!0),y=(0,l.useCallback)(()=>{e.overview().then(e=>v.current&&i(e)).catch(e=>v.current&&_(e.message))},[e]);(0,l.useEffect)(()=>(v.current=!0,y(),()=>{v.current=!1}),[y]);let b=async()=>{_(null),h(!0);try{let t=await e.begin(s.trim());v.current&&o({kind:`record`,name:t.name})}catch(e){v.current&&_(e.message)}finally{v.current&&h(!1)}},S=async t=>{_(null),h(!0);try{if(await e.removePerson(t.id,u),!v.current)return;o({kind:`list`}),y()}catch(e){v.current&&_(e.message)}finally{v.current&&(h(!1),f(``))}};return a.kind===`record`?(0,p.jsx)(UO,{api:e.recording,who:a.name,...t?{createRecorder:t}:{},onClose:()=>{c(``),o({kind:`list`}),y()}}):(0,p.jsxs)(`div`,{className:`approval enroll glass`,role:`dialog`,"aria-label":`Family voices`,style:{pointerEvents:`auto`},children:[(0,p.jsx)(`div`,{className:`approval-head`,children:(0,p.jsx)(`span`,{className:`approval-title`,children:`Family voices`})}),a.kind===`list`&&(0,p.jsxs)(p.Fragment,{children:[(0,p.jsx)(`p`,{className:`auth-note`,children:`Friend knows your voice. Add the people at home, so it knows who is talking and answers them by name. They can chat and ask for the weather, but cannot use your PC or see your private things.`}),r&&!r.ownerEnrolled&&(0,p.jsx)(`p`,{className:`auth-note`,children:`First teach Friend your own voice (Esc, then Enroll my voice).`}),r&&r.people.length===0&&r.ownerEnrolled&&(0,p.jsx)(`p`,{className:`auth-note`,children:`Nobody added yet.`}),r&&r.people.length>0&&(0,p.jsx)(`ul`,{className:`household-list`,"aria-label":`People Friend knows`,children:r.people.map(e=>(0,p.jsxs)(`li`,{className:`household-row`,children:[(0,p.jsx)(`span`,{children:e.name}),(0,p.jsx)(`button`,{type:`button`,style:d,className:`danger`,onClick:()=>o({kind:`remove`,person:e}),"aria-label":`Remove ${e.name}`,children:`Remove`})]},e.id))}),r&&r.ownerEnrolled&&r.people.length<r.max&&(0,p.jsxs)(`label`,{className:`settings-field`,children:[(0,p.jsx)(`span`,{children:`Add a person`}),(0,p.jsx)(`input`,{value:s,maxLength:40,placeholder:`Name, for example Priya`,onChange:e=>c(e.target.value),onKeyDown:e=>e.key===`Enter`&&s.trim()&&!m&&void b()})]}),g&&(0,p.jsx)(`p`,{role:`alert`,className:`auth-error`,children:g}),(0,p.jsxs)(`div`,{className:`approval-actions`,children:[r&&r.ownerEnrolled&&r.people.length<r.max&&(0,p.jsx)(`button`,{type:`button`,style:d,className:`primary`,disabled:m||!s.trim(),onClick:()=>void b(),children:`Record their voice`}),(0,p.jsx)(`button`,{type:`button`,style:d,onClick:n,children:`Close`})]})]}),a.kind===`remove`&&(0,p.jsxs)(p.Fragment,{children:[(0,p.jsxs)(`p`,{className:`auth-note`,children:[`Enter your PIN to remove `,a.person.name,`’s voice. Friend will treat their voice as a stranger’s.`]}),(0,p.jsx)(x,{pin:u,onChange:f}),g&&(0,p.jsx)(`p`,{role:`alert`,className:`auth-error`,children:g}),(0,p.jsxs)(`div`,{className:`approval-actions`,children:[(0,p.jsx)(`button`,{type:`button`,style:d,className:`danger`,disabled:m||u.length<6,onClick:()=>void S(a.person),children:`Remove`}),(0,p.jsx)(`button`,{type:`button`,style:d,onClick:()=>{f(``),_(null),o({kind:`list`})},children:`Back`})]})]})]})}var sk=`▌▍▎▏█▓▒░<>/\\|+-=*#%&0123456789ABCDEF`;function ck(e,t,n=Math.random){let r=[...e];if(t>=1)return e;let i=Math.floor(r.length*Math.max(0,t));return r.map((e,t)=>t<i||e===` `?e:sk[Math.floor(n()*36)]).join(``)}var lk=e=>e.length===0?0:Math.min(24,Math.max(6,Math.ceil([...e].length/2)));function uk(e,t){let[n,r]=(0,l.useState)(e),i=(0,l.useRef)(e);return(0,l.useEffect)(()=>{if(!t||e===i.current){i.current=e,r(e);return}i.current=e;let n=lk(e);if(n===0){r(e);return}let a=0,o=setInterval(()=>{a++,r(ck(e,a/n)),a>=n&&clearInterval(o)},320/n);return()=>clearInterval(o)},[e,t]),n}function dk(e){let t=e.currentTarget,n=t.getBoundingClientRect(),r=document.createElement(`span`);r.className=`hud-ripple`;let i=Math.max(n.width,n.height)*2;r.style.width=r.style.height=`${i}px`,r.style.left=`${e.clientX-n.left-i/2}px`,r.style.top=`${e.clientY-n.top-i/2}px`,t.appendChild(r),r.addEventListener(`animationend`,()=>r.remove(),{once:!0}),setTimeout(()=>r.remove(),900)}function fk({items:e,animations:t,onAction:n}){let[r,i]=(0,l.useState)(null),a=(0,l.useRef)(void 0);if((0,l.useEffect)(()=>()=>clearTimeout(a.current),[]),e.length===0)return null;let o=e=>{t!==`off`&&(i(e.id),clearTimeout(a.current),a.current=setTimeout(()=>i(null),650)),n(e)};return(0,p.jsxs)(B,{id:`launcher`,label:`Quick launch`,wholeBox:!0,testId:`launcher`,className:`hud hud-launcher${t===`full`?` hud-boot`:``}`,children:[(0,p.jsx)(`div`,{className:`hud-kicker`,children:`Quick launch`}),(0,p.jsx)(`ul`,{className:`hud-stack`,children:e.map((e,n)=>(0,p.jsx)(`li`,{className:`hud-tab hud-cut${r===e.id?` engaged`:``}${t===`full`?` hud-boot`:``}`,style:{"--i":n+1},children:(0,p.jsxs)(`button`,{type:`button`,className:`hud-tab-main`,"aria-label":e.label,onPointerDown:t===`off`?void 0:dk,onClick:()=>o(e),children:[(0,p.jsx)(`span`,{className:`hud-icon`,"aria-hidden":`true`,children:e.icon}),(0,p.jsx)(`span`,{className:`hud-tab-label`,children:e.label}),(0,p.jsx)(`span`,{className:`hud-tab-engaged`,"aria-hidden":`true`,children:`ENGAGED`}),(0,p.jsx)(`span`,{className:`hud-sweep`,"aria-hidden":`true`}),(0,p.jsx)(`span`,{className:`hud-scan`,"aria-hidden":`true`})]})},e.id))})]})}var pk=(e,t=18)=>(0,p.jsx)(`svg`,{width:t,height:t,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`1.8`,strokeLinecap:`round`,strokeLinejoin:`round`,"aria-hidden":`true`,children:e}),mk=()=>pk((0,p.jsx)(`path`,{d:`M7 4.5v15l12-7.5z`,fill:`currentColor`})),hk=()=>pk((0,p.jsxs)(p.Fragment,{children:[(0,p.jsx)(`rect`,{x:`6`,y:`4.5`,width:`4`,height:`15`,fill:`currentColor`}),(0,p.jsx)(`rect`,{x:`14`,y:`4.5`,width:`4`,height:`15`,fill:`currentColor`})]})),gk=()=>pk((0,p.jsxs)(p.Fragment,{children:[(0,p.jsx)(`path`,{d:`M5 5v14l10-7z`,fill:`currentColor`}),(0,p.jsx)(`path`,{d:`M18 5v14`})]})),_k=()=>pk((0,p.jsxs)(p.Fragment,{children:[(0,p.jsx)(`path`,{d:`M19 5v14L9 12z`,fill:`currentColor`}),(0,p.jsx)(`path`,{d:`M6 5v14`})]})),vk=()=>pk((0,p.jsxs)(p.Fragment,{children:[(0,p.jsx)(`path`,{d:`M3 7h3.5c3 0 4 2 5.5 5s2.500 5 5.500 5H21`}),(0,p.jsx)(`path`,{d:`M3 17h3.5c1.500 0 2.500-.6 3.400-1.800M13.500 8.800C14.500 7.600 15.500 7 17 7h4`}),(0,p.jsx)(`path`,{d:`m18.500 4.500 2.500 2.500-2.500 2.500M18.500 14.500l2.500 2.500-2.500 2.500`})]})),yk=()=>pk((0,p.jsxs)(p.Fragment,{children:[(0,p.jsx)(`path`,{d:`M17 3l3 3-3 3`}),(0,p.jsx)(`path`,{d:`M4 11V9a3 3 0 0 1 3-3h13M7 21l-3-3 3-3`}),(0,p.jsx)(`path`,{d:`M20 13v2a3 3 0 0 1-3 3H4`})]})),bk=()=>pk((0,p.jsxs)(p.Fragment,{children:[(0,p.jsx)(`path`,{d:`M4 9.500v5h3.500L12 18.500v-13L7.500 9.500z`,fill:`currentColor`}),(0,p.jsx)(`path`,{d:`M15.500 9a4 4 0 0 1 0 6M18 6.500a7.500 7.500 0 0 1 0 11`})]})),xk=()=>pk((0,p.jsxs)(p.Fragment,{children:[(0,p.jsx)(`path`,{d:`M4 9.500v5h3.500L12 18.500v-13L7.500 9.500z`,fill:`currentColor`}),(0,p.jsx)(`path`,{d:`m16 9 5 6M21 9l-5 6`})]})),Sk=()=>pk((0,p.jsx)(`path`,{d:`M4 9V4h5M20 9V4h-5M4 15v5h5M20 15v5h-5`})),Ck=()=>pk((0,p.jsx)(`path`,{d:`M9 4v5H4M15 4v5h5M9 20v-5H4M15 20v-5h5`})),wk=()=>pk((0,p.jsx)(`path`,{d:`M6 6l12 12M18 6 6 18`})),Tk=()=>pk((0,p.jsx)(`path`,{d:`M9 18V6l10-2v12`}),22),Ek=56,Dk=()=>({bars:new Float32Array(Ek),bass:0,left:0,right:0});function Ok(e,t,n,r,i){let a=n?.82:.9;if(t&&n){t.getByteFrequencyData(i);let n=Math.min(i.length,96);for(let t=0;t<Ek;t++){let r=Math.min(n-1,Math.floor((t/Ek)**1.6*n));e.bars[t]=Math.max((i[r]??0)/255,e.bars[t]*a)}}else if(n)for(let t=0;t<Ek;t++)e.bars[t]=Math.max(.12+.28*Math.abs(Math.sin(r/420+t*.55)*Math.cos(r/900+t*.21)),e.bars[t]*a);else for(let t=0;t<Ek;t++)e.bars[t]=e.bars[t]*a;let o=0;for(let t=0;t<6;t++)o+=e.bars[t];e.bass=Math.min(1,o/6*1.15);let s=0,c=0;for(let t=0;t<Ek/2;t++)s+=e.bars[t],c+=e.bars[t+Ek/2];e.left=Math.min(1,s/(Ek/2)*1.6),e.right=Math.min(1,c/(Ek/2)*3.2)}function kk({progress:e,playing:t,cover:n,analyser:r,levels:i,visualizer:a,animate:o,size:s}){let c=(0,l.useRef)(null),u=(0,l.useRef)(null),d=(0,l.useRef)(new Uint8Array(new ArrayBuffer(128)));(0,l.useEffect)(()=>{let e=c.current,n=e?.getContext(`2d`);if(!e||!n||!o)return;let l=0,f=Math.min(2,window.devicePixelRatio||1);e.width=e.height=Math.round(s*f);let p=getComputedStyle(e).getPropertyValue(`--accent`).trim()||`#3fd8ff`,m=e=>{if(Ok(i,r,t,e,d.current),u.current?.style.setProperty(`--bass`,i.bass.toFixed(3)),n.setTransform(f,0,0,f,0,0),n.clearRect(0,0,s,s),a){let e=s/2,t=s*.335,r=s*.135;n.lineCap=`round`,n.lineWidth=Math.max(1.5,s/90);for(let a=0;a<Ek;a++){let o=a/Ek*Math.PI*2-Math.PI/2,s=i.bars[a],c=2+s*r;n.strokeStyle=p,n.globalAlpha=.35+s*.65,n.beginPath(),n.moveTo(e+Math.cos(o)*t,e+Math.sin(o)*t),n.lineTo(e+Math.cos(o)*(t+c),e+Math.sin(o)*(t+c)),n.stroke()}n.globalAlpha=1}(t||!i.bars.every(e=>e<.01)||a)&&(l=requestAnimationFrame(m))};return l=requestAnimationFrame(m),()=>cancelAnimationFrame(l)},[r,t,a,o,s,i]);let f=Math.max(0,Math.min(1,e))*100;return(0,p.jsxs)(`div`,{ref:u,className:`hud-dial${t?` playing`:``}`,style:{width:s,height:s},role:`img`,"aria-label":`Playback dial`,children:[(0,p.jsxs)(`svg`,{className:`hud-dial-svg`,viewBox:`0 0 200 200`,"aria-hidden":`true`,children:[(0,p.jsx)(`circle`,{className:`hud-dial-ticks`,cx:`100`,cy:`100`,r:`96`}),(0,p.jsx)(`circle`,{className:`hud-dial-track`,cx:`100`,cy:`100`,r:`88`}),(0,p.jsx)(`circle`,{className:`hud-dial-arc`,cx:`100`,cy:`100`,r:`88`,pathLength:`100`,strokeDasharray:`${f} 100`,transform:`rotate(-90 100 100)`}),(0,p.jsx)(`circle`,{className:`hud-dial-inner`,cx:`100`,cy:`100`,r:`62`}),(0,p.jsxs)(`g`,{className:`hud-needle`,children:[(0,p.jsx)(`line`,{x1:`100`,y1:`100`,x2:`100`,y2:`14`}),(0,p.jsx)(`circle`,{cx:`100`,cy:`14`,r:`2.500`})]})]}),(0,p.jsx)(`canvas`,{ref:c,className:`hud-spectrum`,style:{width:s,height:s},"aria-hidden":`true`}),(0,p.jsx)(`div`,{className:`hud-cover`,style:n?{backgroundImage:`url("${n}")`}:void 0,children:!n&&(0,p.jsx)(Tk,{})})]})}var Ak=e=>{let t=Math.max(0,Math.floor(Number.isFinite(e)?e:0));return`${Math.floor(t/60)}:${String(t%60).padStart(2,`0`)}`},jk=new Map,Mk=e=>{let t=Wl(e);return t&&t.source===`local`?t.id:null},Nk=e=>Wl(e)?.source===`spotify`,Pk=e=>Wl(e)?.source===`soundcloud`,Fk=e=>Wl(e)?.source===`audius`,Ik={spotify:`Spotify`,soundcloud:`SoundCloud`,audius:`Audius`};function Lk(e){let[t,n]=(0,l.useState)(e?jk.get(e)??!1:!1);return(0,l.useEffect)(()=>{if(!e)return n(!1);if(jk.has(e))return n(jk.get(e));let t=!0,r=new Image;r.onload=()=>{jk.set(e,!0),t&&n(!0)},r.onerror=()=>{jk.set(e,!1),t&&n(!1)};let i=Mk(e);return i?(r.src=`/api/music/cover/${i}`,()=>{t=!1}):n(!1)},[e]),e&&t?`/api/music/cover/${Mk(e)}`:null}async function Rk(e,t){let n=await fetch(`/api/music/library?q=${encodeURIComponent(e)}&limit=${t}`);return n.ok?await n.json():{tracks:[],total:0}}function zk(){let[e,t]=(0,l.useState)(null);return(0,l.useEffect)(()=>{let e=!0;return fetch(`/api/music/sources`).then(e=>e.ok?e.json():null).then(n=>{let r={};for(let e of[`spotify`,`soundcloud`,`audius`]){let t=n?.sources?.find(t=>t.id===e)?.status;t&&(r[e]={connected:t.connected,needs:t.needs})}e&&n&&t(r)}).catch(()=>{}),()=>{e=!1}},[]),e}async function Bk(e,t,n){let r=await fetch(`/api/music/search?q=${encodeURIComponent(t)}&source=${e}&limit=${n}`);if(!r.ok)return{tracks:[],total:0};let i=((await r.json()).tracks??[]).map(e=>({id:e.ref,title:e.title,artist:e.artist,album:e.album,durationSec:e.durationSec}));return{tracks:i,total:i.length}}var Vk=e=>({id:e.id,title:e.title,artist:e.artist,album:e.album,durationSec:e.durationSec});function Hk({levels:e,animate:t,side:n}){let r=(0,l.useRef)(null);return(0,l.useEffect)(()=>{if(!t)return;let i=0,a=r.current,o=()=>{if(a){let t=n===`left`?e.left:e.right,r=Math.round(t*12);a.querySelectorAll(`i`).forEach((e,t)=>e.classList.toggle(`on`,t<r))}i=requestAnimationFrame(o)};return i=requestAnimationFrame(o),()=>cancelAnimationFrame(i)},[e,t,n]),(0,p.jsx)(`div`,{ref:r,className:`hud-levels ${n}`,"aria-hidden":`true`,children:Array.from({length:12},(e,t)=>(0,p.jsx)(`i`,{},t))})}function Uk({player:e,anim:t}){let{state:n,dispatch:r}=e,i=(0,l.useCallback)(async()=>{if(n.queue.length>0)return r({type:`resume`});let e=await Rk(``,500);r({type:`play`,tracks:e.tracks.map(Vk),mode:`replace`,...n.shuffle?{shuffle:!0}:{}})},[n.queue.length,n.shuffle,r]),a=e=>n=>{t!==`off`&&dk(n),e()};return(0,p.jsxs)(`div`,{className:`hud-controls`,role:`group`,"aria-label":`Player controls`,children:[(0,p.jsx)(`button`,{type:`button`,className:`hud-btn`,"aria-label":`Shuffle`,"aria-pressed":n.shuffle,title:`Shuffle`,onClick:()=>r({type:`shuffle`}),children:(0,p.jsx)(vk,{})}),(0,p.jsx)(`button`,{type:`button`,className:`hud-btn`,"aria-label":`Previous track`,title:`Previous`,onPointerDown:a(()=>{}),onClick:()=>r({type:`previous`}),children:(0,p.jsx)(_k,{})}),(0,p.jsx)(`button`,{type:`button`,className:`hud-btn hud-btn-main`,"aria-label":n.playing?`Pause`:`Play`,title:n.playing?`Pause`:`Play`,onPointerDown:a(()=>{}),onClick:()=>n.playing?r({type:`pause`}):void i(),children:n.playing?(0,p.jsx)(hk,{}):(0,p.jsx)(mk,{})}),(0,p.jsx)(`button`,{type:`button`,className:`hud-btn`,"aria-label":`Next track`,title:`Next`,onPointerDown:a(()=>{}),onClick:()=>r({type:`next`}),children:(0,p.jsx)(gk,{})}),(0,p.jsxs)(`button`,{type:`button`,className:`hud-btn${n.repeat===`off`?``:` on`}`,"aria-label":`Repeat: ${n.repeat}`,title:`Repeat: ${n.repeat}`,onClick:()=>r({type:`repeat`,mode:n.repeat===`off`?`all`:n.repeat===`all`?`one`:`off`}),children:[(0,p.jsx)(yk,{}),n.repeat===`one`&&(0,p.jsx)(`sup`,{children:`1`})]})]})}function Wk({player:e}){let{state:t,dispatch:n}=e,r=t.duration>0?t.position/t.duration*100:0;return(0,p.jsxs)(`div`,{className:`hud-timeline`,children:[(0,p.jsx)(`span`,{className:`hud-time`,children:Ak(t.position)}),(0,p.jsx)(`input`,{type:`range`,className:`hud-range`,"aria-label":`Position`,min:0,max:Math.max(1,Math.floor(t.duration)),step:1,value:Math.min(Math.floor(t.position),Math.max(1,Math.floor(t.duration))),style:{"--fill":`${r}%`},disabled:t.duration<=0,onChange:e=>n({type:`seek`,seconds:Number(e.target.value)})}),(0,p.jsxs)(`span`,{className:`hud-time`,children:[`-`,Ak(Math.max(0,t.duration-t.position))]})]})}function Gk({player:e}){let{state:t,dispatch:n}=e;return(0,p.jsxs)(`div`,{className:`hud-volume`,children:[(0,p.jsx)(`button`,{type:`button`,className:`hud-btn`,"aria-label":t.muted?`Unmute`:`Mute`,onClick:()=>n({type:`mute`}),children:t.muted||t.volume===0?(0,p.jsx)(xk,{}):(0,p.jsx)(bk,{})}),(0,p.jsx)(`input`,{type:`range`,className:`hud-range`,"aria-label":`Volume`,min:0,max:100,value:t.muted?0:t.volume,style:{"--fill":`${t.muted?0:t.volume}%`},onChange:e=>n({type:`volume`,level:Number(e.target.value)})})]})}function Kk({player:e,anim:t}){let{state:n,dispatch:r}=e,[i,a]=(0,l.useState)(n.queue.length?`queue`:`library`),[o,s]=(0,l.useState)(``),[c,u]=(0,l.useState)(`folder`),[d,f]=(0,l.useState)(null),m=zk(),h=[`spotify`,`soundcloud`,`audius`].filter(e=>m?.[e]?.connected),g=c!==`folder`&&h.includes(c)?c:null,_=g?m?.[g]?.needs:null;(0,l.useEffect)(()=>{if(i!==`library`)return;let e=!0;if(g&&!o.trim()){f(null);return}let t=()=>g?Bk(g,o.trim(),30):Rk(o,100),n=setTimeout(()=>void t().then(t=>e&&f(t)),o?250:0);return()=>{e=!1,clearTimeout(n)}},[i,o,g]);let v=i===`queue`?n.queue.map((e,t)=>({track:e,index:t})):(d?.tracks??[]).map((e,t)=>({track:Vk(e),index:t}));return(0,p.jsxs)(`div`,{className:`hud-playlist`,children:[(0,p.jsxs)(`div`,{className:`hud-tabs`,role:`tablist`,children:[[`queue`,`library`].map(e=>(0,p.jsx)(`button`,{type:`button`,role:`tab`,"aria-selected":i===e,className:`hud-chip${i===e?` on`:``}`,onClick:()=>a(e),children:e===`queue`?`Queue (${n.queue.length})`:`Library`},e)),i===`queue`&&n.queue.length>0&&(0,p.jsx)(`button`,{type:`button`,className:`hud-chip`,onClick:()=>r({type:`clear`}),children:`Clear`})]}),i===`library`&&h.length>0&&(0,p.jsx)(`div`,{className:`hud-tabs`,role:`tablist`,"aria-label":`Where to look`,children:[`folder`,...h].map(e=>(0,p.jsx)(`button`,{type:`button`,role:`tab`,"aria-selected":c===e,className:`hud-chip${c===e?` on`:``}`,onClick:()=>{u(e),f(null)},children:e===`folder`?`Folder`:Ik[e]},e))}),i===`library`&&(0,p.jsx)(`input`,{className:`hud-search`,type:`search`,placeholder:`Search title, artist or album`,"aria-label":`Search the music`,value:o,onChange:e=>s(e.target.value)}),(0,p.jsxs)(`ul`,{className:`hud-list`,children:[v.length===0&&(0,p.jsx)(`li`,{className:`hud-empty`,children:i===`queue`?`The queue is empty.`:g&&!o.trim()?`Type to search ${Ik[g]}.`:d?`No music matches.`:`Loading…`}),i===`library`&&g&&_&&(0,p.jsx)(`li`,{className:`hud-empty`,children:_}),v.map(({track:e,index:a},o)=>{let s=i===`queue`&&a===n.index;return(0,p.jsxs)(`li`,{className:`hud-tab hud-cut${s?` current`:``}${t===`full`?` hud-boot`:``}`,style:{"--i":Math.min(o,12)},children:[(0,p.jsxs)(`button`,{type:`button`,className:`hud-tab-main`,"aria-current":s?`true`:void 0,onPointerDown:t===`off`?void 0:dk,onClick:()=>r(i===`queue`?{type:`jump`,index:a}:{type:`play`,tracks:(d?.tracks??[]).map(Vk),mode:`replace`,start:a}),children:[(0,p.jsx)(`span`,{className:`hud-tab-title`,children:e.title}),(0,p.jsxs)(`small`,{children:[e.artist||e.album,Nk(e.id)&&(0,p.jsx)(`em`,{className:`hud-source`,children:`SPOTIFY`}),Pk(e.id)&&(0,p.jsx)(`em`,{className:`hud-source`,children:`SOUNDCLOUD`}),Fk(e.id)&&(0,p.jsx)(`em`,{className:`hud-source`,children:`AUDIUS`})]})]}),i===`library`&&(0,p.jsx)(`button`,{type:`button`,className:`hud-mini`,"aria-label":`Add ${e.title} to the queue`,title:`Add to the queue`,onClick:()=>r({type:`play`,tracks:[e],mode:`add`}),children:`+`}),i===`queue`&&(0,p.jsx)(`button`,{type:`button`,className:`hud-mini`,"aria-label":`Remove ${e.title} from the queue`,title:`Remove`,onClick:()=>r({type:`remove`,index:a}),children:`×`})]},`${e.id}-${a}`)})]})]})}function qk({player:e,music:t,animations:n}){let{state:r,dispatch:i,current:a,blocked:o,notice:s,analyser:c,unlock:u}=e,d=(0,l.useMemo)(Dk,[]),f=Lk(a?.id),m=r.view===`full`,h=uk(a?.title??``,n===`full`);if(!t?.folderSet||r.view===`hidden`)return null;let g=r.duration>0?r.position/r.duration:0,_=n!==`off`;return(0,p.jsxs)(B,{id:`music`,label:`Music player`,wholeBox:!0,testId:`music`,className:`hud hud-music hud-cut ${m?`full`:`mini`}${r.playing?` playing`:``}${n===`full`?` hud-boot`:``}`,children:[(0,p.jsxs)(`header`,{className:`hud-music-head`,children:[(0,p.jsx)(`span`,{className:`hud-kicker`,children:`Media player`}),(0,p.jsxs)(`span`,{className:`hud-head-actions`,children:[(0,p.jsx)(`button`,{type:`button`,className:`hud-btn`,"aria-label":m?`Smaller player`:`Bigger player`,title:m?`Smaller`:`Bigger`,onClick:()=>i({type:`view`,view:m?`mini`:`full`}),children:m?(0,p.jsx)(Ck,{}):(0,p.jsx)(Sk,{})}),(0,p.jsx)(`button`,{type:`button`,className:`hud-btn`,"aria-label":`Hide the player`,title:`Hide (the music keeps playing)`,onClick:()=>i({type:`view`,view:`hidden`}),children:(0,p.jsx)(wk,{})})]})]}),(0,p.jsxs)(`div`,{className:`hud-music-body`,children:[(0,p.jsxs)(`div`,{className:`hud-music-left`,children:[m&&(0,p.jsx)(Hk,{levels:d,animate:_,side:`left`}),(0,p.jsx)(kk,{progress:g,playing:r.playing,cover:f,analyser:c,levels:d,visualizer:t.visualizer,animate:_,size:m?250:112}),m&&(0,p.jsx)(Hk,{levels:d,animate:_,side:`right`})]}),(0,p.jsxs)(`div`,{className:`hud-music-main`,children:[(0,p.jsxs)(`div`,{className:`hud-now`,"aria-live":`polite`,children:[(0,p.jsx)(`b`,{className:`hud-title`,children:a?h:`Nothing playing`}),(0,p.jsxs)(`small`,{className:`hud-sub`,children:[a?[a.artist,a.album].filter(Boolean).join(` — `):`Press play, or ask for some music.`,a&&Nk(a.id)&&(0,p.jsx)(`em`,{className:`hud-source`,children:`SPOTIFY`}),a&&Pk(a.id)&&(0,p.jsx)(`em`,{className:`hud-source`,children:`SOUNDCLOUD`}),a&&Fk(a.id)&&(0,p.jsx)(`em`,{className:`hud-source`,children:`AUDIUS`}),e.remote&&(0,p.jsx)(`em`,{className:`hud-source`,children:`THIS PC`})]})]}),(0,p.jsx)(Wk,{player:e}),(0,p.jsx)(Uk,{player:e,anim:n}),m&&(0,p.jsx)(Gk,{player:e}),s&&(0,p.jsx)(`p`,{className:`hud-notice`,role:`status`,children:s}),o&&(0,p.jsx)(`button`,{type:`button`,className:`hud-unlock`,onClick:u,children:`Tap to enable sound`})]}),m&&(0,p.jsx)(Kk,{player:e,anim:n})]})]})}var Jk=/^spotify:/,Yk=class{local;makeSpotify;active;spotify=null;listeners=new Map;wrapped=new Map;vol=1;mute=!1;pre=``;constructor(e,t){this.local=e,this.makeSpotify=t,this.active=e}get element(){return this.local}get error(){return this.active.error??null}wrap(e){let t=this.wrapped.get(e);return t||(t={local:()=>{this.active===this.local&&e()},spot:()=>{this.spotify&&this.active===this.spotify&&e()}},this.wrapped.set(e,t)),t}spot(){if(!this.spotify){let e=this.makeSpotify();e.volume=this.vol,e.muted=this.mute,e.preload=this.pre;for(let[t,n]of this.listeners)for(let r of n)e.addEventListener(t,this.wrap(r).spot);this.spotify=e}return this.spotify}dispose(){this.spotify?.dispose?.(),this.spotify=null,this.active=this.local}get src(){return this.active.src}set src(e){let t=Jk.test(e)?this.spot():this.local;t===this.active?e===``&&this.active.pause():(this.active.pause(),this.active=t),this.active.src=e}get currentTime(){return this.active.currentTime}set currentTime(e){this.active.currentTime=e}get duration(){return this.active.duration}get paused(){return this.active.paused}get volume(){return this.vol}set volume(e){this.vol=e,this.local.volume=e,this.spotify&&(this.spotify.volume=e)}get muted(){return this.mute}set muted(e){this.mute=e,this.local.muted=e,this.spotify&&(this.spotify.muted=e)}get preload(){return this.pre}set preload(e){this.pre=e,this.local.preload=e,this.spotify&&(this.spotify.preload=e)}play(){return this.active.play()}pause(){this.active.pause()}addEventListener(e,t){let n=this.listeners.get(e);n||this.listeners.set(e,n=new Set),n.add(t);let r=this.wrap(t);this.local.addEventListener(e,r.local),this.spotify?.addEventListener(e,r.spot)}removeEventListener(e,t){this.listeners.get(e)?.delete(t);let n=this.wrap(t);this.local.removeEventListener(e,n.local),this.spotify?.removeEventListener(e,n.spot)}},Xk=/^spotify:([A-Za-z0-9_-]{1,64})$/,Zk=`Spotify Premium is needed to play on this screen.`;async function Qk(){let e=await fetch(`/api/music/spotify/token`,{cache:`no-store`});if(!e.ok)throw Error(`Spotify is not connected.`);return(await e.json()).accessToken}function $k(){let e=window;return e.Spotify?Promise.resolve(e.Spotify):new Promise((t,n)=>{e.onSpotifyWebPlaybackSDKReady=()=>e.Spotify?t(e.Spotify):n(Error(`no sdk`));let r=document.createElement(`script`);r.src=`https://sdk.scdn.co/spotify-player.js`,r.async=!0,r.onerror=()=>n(Error(`blocked`)),document.head.appendChild(r)})}function eA(e){let t=e.fetch??((...e)=>fetch(...e)),n=e.now??Date.now,r=new Map,i=null,a=null,o=null,s=null,c=!1,l=null,u=null,d=0,f=0,p=0,m=!0,h=1,g=!1,_,v=e=>{for(let t of r.get(e)??[])t()},y=()=>g?0:h,b=()=>{_&&clearInterval(_),_=void 0},x=()=>{_||=setInterval(()=>v(`timeupdate`),250)},S={error:null,preload:``,get src(){return s??``},set src(e){let t=Xk.exec(e);c=e!==``&&!t,s=t?e:null,l=null,u=null,d=0,p=0,S.error=null,t||b()},get currentTime(){return m?d:d+(n()-f)/1e3},set currentTime(e){d=e,f=n(),i?.seek(Math.round(e*1e3)).catch(()=>{})},get duration(){return p},get paused(){return m},get volume(){return h},set volume(e){h=e,i?.setVolume(y()).catch(()=>{})},get muted(){return g},set muted(e){g=e,i?.setVolume(y()).catch(()=>{})},async play(){if(c||!s)throw Error(`That is not a Spotify track.`);let r=Xk.exec(s),a=s,o=await T();if(s!==a)return;if(l===s){await i?.resume().catch(()=>{}),m=!1,f=n(),x();return}let u=await e.getToken().catch(()=>null);if(!u)throw C(`Spotify is not connected. Connect it in Plugins, Spotify.`);let d;try{d=await t(`https://api.spotify.com/v1/me/player/play?device_id=${encodeURIComponent(o)}`,{method:`PUT`,headers:{authorization:`Bearer ${u}`,"content-type":`application/json`},body:JSON.stringify({uris:[`spotify:track:${r[1]}`]})})}catch{throw C(`Friend could not reach Spotify right now.`)}if(d.status===403)throw C(Zk);if(d.status===401)throw C(`Spotify sign-in has ended. Reconnect Spotify in Plugins, Spotify.`);if(d.status===404)throw C(`Spotify could not find this screen or that track.`);if(d.status===429)throw C(`Spotify is asking Friend to slow down. Try again in a minute.`);if(!d.ok)throw C(`Spotify could not play that.`);s===a&&(l=a,m=!1,f=n(),x())},pause(){m=!0,d+=(n()-f)/1e3,f=n(),b(),i?.pause().catch(()=>{})},dispose(){b();try{i?.disconnect()}catch{}i=null,a=null,s=null,l=null},addEventListener(e,t){let n=r.get(e);n||r.set(e,n=new Set),n.add(t)},removeEventListener(e,t){r.get(e)?.delete(t)}};function C(e){S.error=e,m=!0,b(),v(`error`);let t=Error(e),n=o;return o=null,n?.reject(t),t}function w(e){if(!e)return;d=e.position/1e3,f=n(),p=e.duration/1e3,m=e.paused,v(`timeupdate`),v(`loadedmetadata`),v(`durationchange`);let t=s?Xk.exec(s)?.[1]:void 0;t&&e.paused&&e.position===0&&u!==s&&(e.track_window.previous_tracks??[]).some(e=>e.id===t)&&(u=s,b(),v(`ended`))}function T(){if(a)return Promise.resolve(a);if(o)return o.promise;let t,n,r=new Promise((e,r)=>{t=e,n=r}),s={promise:r,resolve:t,reject:n};o=s;let c=setTimeout(()=>{o===s&&C(`Spotify's player did not start. Check that this browser allows Spotify's player, then try again.`)},e.readyTimeoutMs??15e3),l=()=>clearTimeout(c);return r.then(l,l),(async()=>{try{if(!i){let t;try{t=await(e.loadSdk??$k)()}catch{o===s&&C(`Spotify's player could not be loaded. Check that nothing blocks sdk.scdn.co.`);return}let n=new t.Player({name:e.deviceName??`Friend`,volume:y(),getOAuthToken:t=>{e.getToken().then(t,()=>{})}});i=n,n.addListener(`ready`,(e=>{a=e.device_id;let t=o;o=null,t?.resolve(e.device_id)})),n.addListener(`not_ready`,(()=>{a=null})),n.addListener(`player_state_changed`,(e=>w(e))),n.addListener(`account_error`,(()=>void C(Zk))),n.addListener(`authentication_error`,(()=>void C(`Spotify sign-in has ended. Reconnect Spotify in Plugins, Spotify.`))),n.addListener(`initialization_error`,(()=>void C(`Spotify's player does not work in this browser.`))),n.addListener(`playback_error`,(()=>void C(`Spotify could not play that.`)))}!await i.connect()&&o===s&&C(`Spotify's player could not connect.`)}catch{o===s&&C(`Spotify's player could not connect.`)}})(),r}return S}var tA=e=>{let t=Wl(e);return t?t.source===`local`?`/api/music/track/${t.id}`:t.source===`soundcloud`||t.source===`audius`?`/api/music/stream/${e}`:e:`/api/music/track/${e}`},nA=(e,t)=>vu(e,t),rA=`friend.music`,iA=1e3,aA=1.5,oA=()=>{try{return JSON.parse(localStorage.getItem(rA)??`{}`)}catch{return{}}},sA=e=>{try{localStorage.setItem(rA,JSON.stringify({volume:e.volume,muted:e.muted,shuffle:e.shuffle,repeat:e.repeat,view:e.view}))}catch{}};function cA({music:e,cmd:t,send:n,connection:r,createAudio:i,createSpotify:a,remote:o=!1}){let[s,c]=(0,l.useReducer)(nA,void 0,()=>{let e=oA();return mu({volume:e.volume??70,shuffle:e.shuffle??!1,repeat:e.repeat??`all`,view:e.view??`mini`})}),[u,d]=(0,l.useState)(!1),[f,p]=(0,l.useState)(null),[m,h]=(0,l.useState)(null),g=(0,l.useRef)(null),_=(0,l.useRef)(!1),v=(0,l.useRef)(s);v.current=s;let y=(0,l.useRef)(!1),b=(0,l.useRef)(null),x=(0,l.useRef)(0),S=(0,l.useRef)(!1);(0,l.useEffect)(()=>{if(!e||S.current)return;S.current=!0;let t=oA();c({type:`volume`,level:t.volume??e.volume}),c({type:`repeat`,mode:t.repeat??e.repeat}),(t.shuffle??e.shuffle)&&c({type:`shuffle`,on:!0}),c({type:`view`,view:t.view??e.startView}),t.muted&&c({type:`mute`,on:!0})},[e]);let C=()=>{if(!g.current){let e=new Yk(i?i():new Audio,a??(()=>eA({getToken:Qk})));e.preload=`auto`,g.current=e}return g.current},w=(0,l.useRef)(!1),T=(0,l.useCallback)(()=>{let e=g.current;if(e&&e.src){w.current=!0;try{let t=e.play();t&&typeof t.then==`function`?t.then(()=>{w.current=!1,d(!1)},()=>{w.current=!1;let e=g.current?.error??null;e?p(e):d(!0)}):(w.current=!1,d(!1))}catch{w.current=!1,d(!0)}E.current||O()}},[]),E=(0,l.useRef)(!1),D=(0,l.useRef)(null),O=()=>{let e=g.current,t=e instanceof Yk?e.element:e,n=typeof window<`u`?window.AudioContext??window.webkitAudioContext:void 0;if(t&&n&&typeof t.play==`function`)try{let e=new n;D.current=e;let r=e.createMediaElementSource(t),i=e.createAnalyser();i.fftSize=256,i.smoothingTimeConstant=.82,r.connect(i),i.connect(e.destination),E.current=!0,h(i)}catch{E.current=!0}};(0,l.useEffect)(()=>{if(o)return;let e=C(),t=0,n=()=>{let n=Date.now();n-t<250||(t=n,c({type:`time`,position:e.currentTime||0,duration:Number.isFinite(e.duration)?e.duration:0}))},r=()=>c({type:`time`,position:e.currentTime||0,duration:Number.isFinite(e.duration)?e.duration:0}),i=()=>c({type:`ended`}),a=()=>{let t=e.error??null;p(t),c(t?{type:`pause`}:{type:`failed`})};return e.addEventListener(`timeupdate`,n),e.addEventListener(`loadedmetadata`,r),e.addEventListener(`durationchange`,r),e.addEventListener(`ended`,i),e.addEventListener(`error`,a),()=>{e.removeEventListener(`timeupdate`,n),e.removeEventListener(`loadedmetadata`,r),e.removeEventListener(`durationchange`,r),e.removeEventListener(`ended`,i),e.removeEventListener(`error`,a),e.pause(),D.current?.close().catch(()=>{}),D.current=null,e.dispose(),b.current=null,g.current=null,E.current=!1,h(null)}},[o]),(0,l.useEffect)(()=>{o&&c({type:`stop`})},[o]);let k=s.index>=0?s.queue[s.index]??null:null;(0,l.useEffect)(()=>{let e=g.current;if(o||!e)return;let t=k?.id??null;if(t!==b.current){if(b.current=t,!t){e.pause(),e.src=``;return}p(null),e.src=tA(t),s.playing&&T()}},[k?.id,s.playing,T,o]),(0,l.useEffect)(()=>{let e=g.current;!o&&e&&e.src&&(s.playing&&e.paused&&!_.current&&!w.current?T():!s.playing&&!e.paused&&e.pause())},[s.playing,s.position,T,o]),(0,l.useEffect)(()=>{let e=g.current;e&&(e.volume=s.volume/100,e.muted=s.muted)},[s.volume,s.muted]),(0,l.useEffect)(()=>{let e=g.current;e&&e.src&&Math.abs((e.currentTime||0)-s.position)>aA&&(e.currentTime=s.position)},[s.position]),(0,l.useEffect)(()=>sA(s),[s.volume,s.muted,s.shuffle,s.repeat,s.view]),(0,l.useEffect)(()=>{if(!t||t.n===x.current)return;x.current=t.n;let e=yu(t.command);e&&c(e)},[t]),(0,l.useEffect)(()=>{let e=()=>{y.current=!0,_.current&&T()};return window.addEventListener(`pointerdown`,e,{passive:!0}),window.addEventListener(`keydown`,e),()=>{window.removeEventListener(`pointerdown`,e),window.removeEventListener(`keydown`,e)}},[T]),_.current=u;let A=(0,l.useRef)(0);return(0,l.useEffect)(()=>{if(r!==`open`||o)return;let e=()=>{let e=v.current,t=e.index>=0?e.queue[e.index]:void 0;A.current=Date.now(),n({type:`music.state`,state:{playing:e.playing,trackId:t?.id??null,title:t?.title??``,artist:t?.artist??``,album:t?.album??``,position:e.position,duration:e.duration,volume:e.volume,muted:e.muted,shuffle:e.shuffle,repeat:e.repeat,view:e.view,queue:e.queue.slice(0,50).map(e=>({id:e.id,title:e.title.slice(0,200)})),index:e.index,active:(typeof document>`u`||document.visibilityState===`visible`)&&y.current}})};e();let t=setInterval(()=>s.playing&&Date.now()-A.current>=iA&&e(),iA);return()=>clearInterval(t)},[r,o,k?.id,s.playing,s.volume,s.muted,s.shuffle,s.repeat,s.view,s.queue.length,s.index]),(0,l.useEffect)(()=>{let e=typeof navigator<`u`?navigator.mediaSession:void 0;if(e&&!o)try{k&&typeof MediaMetadata<`u`&&(e.metadata=new MediaMetadata({title:k.title,artist:k.artist,album:k.album,artwork:[{src:`/api/music/cover/${k.id}`}]})),e.playbackState=s.playing?`playing`:k?`paused`:`none`,e.setActionHandler(`play`,()=>c({type:`resume`})),e.setActionHandler(`pause`,()=>c({type:`pause`})),e.setActionHandler(`previoustrack`,()=>c({type:`previous`})),e.setActionHandler(`nexttrack`,()=>c({type:`next`})),e.setActionHandler(`seekto`,e=>typeof e.seekTime==`number`&&c({type:`seek`,seconds:e.seekTime}))}catch{}},[k?.id,s.playing,o]),{remote:!1,state:s,dispatch:c,current:k,blocked:u,notice:f,analyser:m,unlock:T,audio:g}}function lA(e,t){if(!e)return{state:{queue:[],index:-1,playing:!1,position:0,duration:0,volume:70,muted:!1,shuffle:!1,repeat:`all`,view:t},current:null};let n=e.queue.map((t,n)=>n===e.index?{id:t.id,title:e.title||t.title,artist:e.artist,album:e.album,durationSec:e.duration>0?e.duration:null}:{id:t.id,title:t.title,artist:``,album:``,durationSec:null});return{state:{queue:n,index:e.index,playing:e.playing,position:e.position,duration:e.duration,volume:e.volume,muted:e.muted,shuffle:e.shuffle,repeat:e.repeat,view:t},current:e.index>=0?n[e.index]??null:null}}function uA({local:e,host:t,send:n}){let r=e.state.view,{state:i,current:a}=(0,l.useMemo)(()=>lA(t,r),[t,r]),o=e.dispatch,s=(0,l.useCallback)(e=>{if(e.type===`view`)return o(e);let t=bu(e);t&&n({type:`music.remote`,command:t})},[o,n]);return(0,l.useMemo)(()=>({...e,remote:!0,state:i,dispatch:s,current:a,blocked:!1,notice:null,analyser:null,unlock:()=>{}}),[e,i,s,a])}function dA(e){let t=new URLSearchParams(e).get(`music`);return t===`connected`?{level:`info`,text:`Spotify is connected. Ask Friend to play something.`}:t===`failed`?{level:`warn`,text:`Spotify did not connect. Open Plugins, Spotify and press Connect again.`}:null}function fA({onSignedOut:e}){let{state:t,send:n,dispatch:r,voice:i,useHere:a}=IO(e);JO(i),YO(i),tk(n,t.connection);let[o,s]=(0,l.useState)(!1),[c,u]=(0,l.useState)(!1),[d,f]=(0,l.useState)(!1),[m,h]=(0,l.useState)(!1),[g,_]=(0,l.useState)(void 0),[v,y]=(0,l.useState)(null),[b,x]=(0,l.useState)(!1),[S,C]=(0,l.useState)(0),[w,T]=(0,l.useState)(null),E=de(t.view),D=t.music?.output===`host`,O=cA({music:t.music,cmd:t.musicCmd,send:n,connection:t.connection,remote:D}),k=uA({local:O,host:t.hostMusic,send:n}),j=D?k:O,ee=t.hud?.animations??`full`,M=e=>{let{type:i,value:a}=e.action;if(i===`url`)window.open(a,`_blank`,`noopener,noreferrer`);else if(i===`prompt`)n({type:`chat.send`,text:a});else if(i===`music`||i===`panel`&&a===`music`){if(!t.music?.folderSet){r({type:`alert.add`,level:`info`,text:`No music folder is chosen yet. Pick one in Settings, Widgets, and the player opens.`}),y(`widgets`);return}if(i===`panel`){E.toggle(`music`,!0),j.state.view===`hidden`&&j.dispatch({type:`view`,view:`mini`});return}let e=yu({action:a});e&&j.dispatch(e)}else a===`plugins`?h(!0):a===`settings`?y(`model`):(a===`chat`||a===`tasks`)&&E.toggle(a,!0)},N=(0,l.useMemo)(()=>o?{...t,objects:[],captions:``}:t,[o,t]),P=(0,l.useRef)(!1);(0,l.useEffect)(()=>{P.current||!t.voice.available||t.voice.enrolled||(P.current=!0,r({type:`alert.add`,level:`info`,text:`Voice recognition is not set up. Press Esc, then Enroll my voice.`}))},[t.voice.available,t.voice.enrolled,r]);let te=ne(),L=(0,l.useRef)(!1);(0,l.useEffect)(()=>{if(!te||L.current||t.connection!==`open`)return;L.current=!0;let e=!1;try{e=localStorage.getItem(`friend.touchHint`)===`1`,localStorage.setItem(`friend.touchHint`,`1`)}catch{}e||r({type:`alert.add`,level:`info`,text:`Hold the round mic button to talk, or tap it once to start and again to send. The keyboard button types; the menu button opens settings.`})},[te,t.connection,r]);let re=t.uiOpen?.n??0,ie=t.uiOpen?.integration;(0,l.useEffect)(()=>{re!==0&&(_(ie),h(!0))},[re,ie]);let ae=(0,l.useRef)(!1);(0,l.useEffect)(()=>{if(ae.current)return;ae.current=!0;let e=dA(window.location.search);e&&(r({type:`alert.add`,level:e.level,text:e.text}),window.history.replaceState(null,``,window.location.pathname))},[r]);let oe=(0,l.useRef)(!1);(0,l.useEffect)(()=>{oe.current||t.connection!==`open`||(oe.current=!0,fetch(`/api/history`).then(e=>e.ok?e.json():[]).then(e=>r({type:`chat.seed`,lines:e})).catch(()=>{}))},[t.connection,r]),(0,l.useEffect)(()=>{t.connection===`open`&&n({type:`ui.panels`,open:[...E.show.chat?[`chat`]:[],...E.show.tasks?[`tasks`]:[]]})},[t.connection,E.show.chat,E.show.tasks,n]);let se=(0,l.useRef)(!1);(0,l.useEffect)(()=>{t.viewKnown&&t.view===`minimal`&&!se.current&&(se.current=!0,r({type:`alert.add`,level:`info`,text:`The view is Minimal, so the status line and clock are hidden. Press Esc, then View, to bring them back.`}))},[t.viewKnown,t.view,r]);let ce=e=>{ze.save({view:e}).catch(e=>r({type:`alert.add`,level:`warn`,text:e.message}))},le=(0,l.useMemo)(()=>F({notify:e=>r({type:`alert.add`,level:`info`,text:e}),openSettings:()=>y(`model`),openLook:()=>y(`look`),openConnectors:()=>x(!0),openPlugins:()=>h(!0),openVoice:t.voice.available?()=>u(!0):null,muted:o,setMuted:s,cameraOn:t.camera.enabled,setCamera:e=>r({type:`camera.enable`,value:e}),clearScreen:()=>{for(let e of t.objects)n({type:`stage.event`,objectId:e.id,event:`dismiss`})},statusLine:()=>Ee({connection:t.connection,deviceOnline:t.deviceOnline,approval:t.approval,voiceMode:t.voice.mode,busy:t.busy,activity:t.activity}).text,endSession:t=>{fetch(t===`lock`?`/api/lock`:`/api/logout`,{method:`POST`,headers:{"content-type":`application/json`},body:`{}`}).catch(()=>{}).finally(e)},panelOn:e=>E.show[e],setPanel:(e,t)=>E.toggle(e,t),view:t.view,setView:ce,openHelp:T,resetLayout:()=>{ue(),window.location.reload()}}),[r,n,o,e,E.show,E.toggle,t.view,t.voice.available,t.voice.mode,t.camera.enabled,t.objects,t.connection,t.deviceOnline,t.approval,t.busy,t.activity]);return(0,p.jsxs)(p.Fragment,{children:[(0,p.jsx)(bE,{state:N,send:n,dispatch:r,voice:i,slash:le,onMenu:()=>C(e=>e+1)}),(0,p.jsxs)(ke,{approval:t.approval,challenge:t.challenge,cameraStream:t.camera.stream,alerts:t.alerts,connection:t.connection,deviceOnline:t.deviceOnline,voiceMode:t.voice.mode,busy:t.busy,activity:t.activity,showStatus:t.viewKnown&&E.show.status,showClock:t.viewKnown&&E.show.clock,profile:t.viewKnown&&E.show.profile?{ownerName:t.ownerName,speaker:t.speaker}:null,assistantName:t.assistantName,hud:t.hud,send:n,dispatch:r,children:[t.viewKnown&&E.show.chat&&(0,p.jsx)(fe,{lines:t.chat,live:t.chatLive,onSend:e=>n({type:`chat.send`,text:e}),onClose:()=>E.toggle(`chat`,!1)}),t.viewKnown&&E.show.tasks&&(0,p.jsx)(he,{busy:t.busy,onClose:()=>E.toggle(`tasks`,!1)}),t.viewKnown&&E.show.launcher&&t.hud&&(0,p.jsx)(fk,{items:t.hud.launcher,animations:ee,onAction:M}),t.viewKnown&&E.show.music&&(0,p.jsx)(qk,{player:j,music:t.music,animations:ee}),c&&(0,p.jsx)(UO,{onClose:()=>u(!1)}),d&&(0,p.jsx)(ok,{onClose:()=>f(!1)}),m&&(0,p.jsx)(bd,{...g?{initialConfigure:g}:{},onClose:()=>{h(!1),_(void 0)}}),v&&(0,p.jsx)(gx,{initialTab:v,onClose:()=>y(null)}),b&&(0,p.jsx)(A,{onClose:()=>x(!1)}),w&&(0,p.jsx)(I,{commands:w,onClose:()=>T(null)})]}),(0,p.jsx)(V,{muted:o,onToggleMute:()=>s(e=>!e),onSignedOut:e,voiceAvailable:t.voice.available,voiceEnrolled:t.voice.enrolled,onEnroll:()=>u(!0),onHousehold:()=>f(!0),onPlugins:()=>h(!0),onSettings:()=>y(`model`),onConnectors:()=>x(!0),cameraOn:t.camera.enabled,onToggleCamera:()=>r({type:`camera.enable`,value:!t.camera.enabled}),chatOn:E.show.chat,onToggleChat:()=>E.toggle(`chat`),tasksOn:E.show.tasks,onToggleTasks:()=>E.toggle(`tasks`),musicOn:E.show.music,onToggleMusic:()=>E.toggle(`music`),launcherOn:E.show.launcher,onToggleLauncher:()=>E.toggle(`launcher`),view:t.view,onView:ce,openRequest:S}),t.connection===`elsewhere`&&(0,p.jsx)(XO,{onUseHere:a})]})}function pA(){let[e,t]=(0,l.useState)(`loading`);return(0,l.useEffect)(()=>{let e=!0,n=n=>e&&t(n);return(async()=>{try{if(!(await(await fetch(`/api/state`)).json()).hasOwner)return n(`setup`);let e=await(await fetch(`/api/session`,{cache:`no-store`})).json();n(e.signedIn===!0?`stage`:`login`)}catch{n(`login`)}})(),()=>{e=!1}},[]),e===`loading`?(0,p.jsx)(`div`,{className:`boot`,"aria-busy":`true`}):e===`setup`?(0,p.jsx)(g,{onDone:()=>t(`login`)}):e===`login`?(0,p.jsx)(h,{onLoggedIn:()=>t(`stage`)}):(0,p.jsx)(fA,{onSignedOut:()=>t(`login`)})}(0,u.createRoot)(document.getElementById(`root`)).render((0,p.jsx)(l.StrictMode,{children:(0,p.jsx)(pA,{})}));
|