@firetable/project-xiaochun 0.1.18 → 0.1.20

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,11 +1,11 @@
1
- /*! @firetable/project-xiaochun v0.1.18 | MIT | https://github.com/FireTable/project-xiaochun */
1
+ /*! @firetable/project-xiaochun v0.1.20 | MIT | https://github.com/FireTable/project-xiaochun */
2
2
  import {
3
3
  XIAOCHUN_ELEMENT_TAG,
4
4
  defineXiaochunElement
5
- } from "./chunks/chunk-Y5MRWV67.js";
5
+ } from "./chunks/chunk-VEO4L6VJ.js";
6
6
  import {
7
7
  createXiaochun
8
- } from "./chunks/chunk-BN4H52OR.js";
8
+ } from "./chunks/chunk-OUHLLXLG.js";
9
9
  import {
10
10
  XC_CAMERA_RANGES,
11
11
  XC_DEFAULT_ORIGIN,
@@ -34,7 +34,7 @@ import {
34
34
  xcHasOwn,
35
35
  xcMessage,
36
36
  xcUiAutoHideActive
37
- } from "./chunks/chunk-KL7L3MGQ.js";
37
+ } from "./chunks/chunk-VPAQ4UMD.js";
38
38
 
39
39
  // src/protocol-url.ts
40
40
  var XIAOCHUN_PROTOCOL_SCHEME = "xiaochun";
@@ -1,3 +1,3 @@
1
- /*! @firetable/project-xiaochun v0.1.18 | MIT | https://github.com/FireTable/project-xiaochun */
2
- "use strict";var Xiaochun=(()=>{var Ke=Object.defineProperty;var dn=Object.getOwnPropertyDescriptor;var fn=Object.getOwnPropertyNames;var pn=Object.prototype.hasOwnProperty;var hn=(t,r)=>{for(var a in r)Ke(t,a,{get:r[a],enumerable:!0})},mn=(t,r,a,i)=>{if(r&&typeof r=="object"||typeof r=="function")for(let s of fn(r))!pn.call(t,s)&&s!==a&&Ke(t,s,{get:()=>r[s],enumerable:!(i=dn(r,s))||i.enumerable});return t};var gn=t=>mn(Ke({},"__esModule",{value:!0}),t);var Nn={};hn(Nn,{XC_CAMERA_RANGES:()=>V,XC_DEFAULT_ORIGIN:()=>Bt,XC_DEFAULT_SRC:()=>Ve,XC_FRAME_TO_HOST:()=>bn,XC_HOST_TO_FRAME:()=>xn,XC_ID_RE:()=>Nt,XC_IMPLEMENTED_COMMANDS:()=>Xn,XC_LANGS:()=>Mn,XC_PROTOCOL_MAPPING:()=>vn,XC_PROTOCOL_VERSION:()=>yn,XC_UI_AUTOHIDE_DEFAULT:()=>En,XC_UI_LEGACY_PARTS:()=>Je,XC_UI_PARTS:()=>pe,XC_UNSUPPORTED_COMMANDS:()=>wn,XC_WINDOW_CORNER_RADIUS:()=>Ye,XIAOCHUN_ELEMENT_TAG:()=>st,XIAOCHUN_PROTOCOL_SCHEME:()=>ze,createXiaochun:()=>Re,defineXiaochunElement:()=>Le,isXcEnvelope:()=>Ee,isXcId:()=>T,normalizeOrigin:()=>Se,normalizeXcCamera:()=>et,normalizeXcUiOption:()=>Qe,parseProtocolUrl:()=>Jt,parseXcCameraParams:()=>Cn,parseXcUiAutoHide:()=>he,parseXcUiList:()=>Ze,parseXcUiParam:()=>An,toProtocolUrl:()=>Yt,xcHasOwn:()=>kn,xcMessage:()=>N,xcUiAutoHideActive:()=>Sn});var yn=1,Bt="https://xiaochun.firetable.tech",Ve=`${Bt}/embed`,xn=["xc.init","xc.say","xc.audio","xc.audio.chunk","xc.audio.end","xc.motion","xc.expression","xc.lookAt","xc.pointer","xc.setModel","xc.setOutfit","xc.setScene","xc.prefetch","xc.setConfig","xc.mic","xc.pause","xc.resume","xc.destroy"],bn=["xc.ready","xc.load.progress","xc.loaded","xc.outfit-changed","xc.scene-changed","xc.lang-changed","xc.prefetched","xc.state","xc.stt","xc.utterance","xc.hit-region","xc.gesture-move","xc.gesture-resize","xc.error"],Xn=["xc.say","xc.audio","xc.audio.chunk","xc.audio.end","xc.motion","xc.expression","xc.pointer","xc.setModel","xc.setOutfit","xc.setScene","xc.prefetch","xc.setConfig","xc.mic","xc.pause","xc.resume","xc.destroy"],wn=["xc.lookAt"],vn=[{xc:"xc.say",note:'mode:"speak" (\u9ED8\u8BA4)',action:"speak",url:"xiaochun://speak?text=\u2026"},{xc:"xc.say",note:'mode:"chat" (\u8D70 LLM)',action:null,url:null},{xc:"xc.audio",note:"source \u4E3A URL \u5B57\u7B26\u4E32",action:"speak",url:"xiaochun://speak?audioUrl=\u2026[&text=\u2026]"},{xc:"xc.audio",note:"source \u4E3A ArrayBuffer / Blob",action:"audio",url:null},{xc:"xc.audio.chunk / xc.audio.end",note:"\u6D41\u5F0F PCM",action:"audio",url:null}],Ye=20,pe=["chat","bubble","outfit","scene","lang","github"],Pn=new Set(pe),Je=["chat","bubble"];function Ze(t){let r=new Set,a=[];for(let i of t){let s=typeof i=="string"?i.trim().toLowerCase():"";Pn.has(s)?r.add(s):a.push(typeof i=="string"?i.slice(0,40):typeof i)}return{parts:pe.filter(i=>r.has(i)),unknown:a,legacy:!1}}function An(t){let r=(t??"").trim().toLowerCase();return r===""||r==="0"||r==="false"?{parts:[],unknown:[],legacy:!1}:r==="1"||r==="true"?{parts:[...Je],unknown:[],legacy:!0}:Ze(r.split(",").filter(a=>a.trim()!==""))}function Qe(t){return t===!0?{parts:[...Je],unknown:[],legacy:!0}:Array.isArray(t)?Ze(t):{parts:[],unknown:[],legacy:!1}}var En="transparent";function he(t){if(t===!0||t===!1||t==="transparent")return t;if(typeof t!="string")return;let r=t.trim().toLowerCase();if(r==="1"||r==="true")return!0;if(r==="0"||r==="false")return!1;if(r==="transparent")return"transparent"}function Sn(t,r){return t==="transparent"?r:t}var V={fov:[15,60],distance:[1,15],height:[-1,1]},$t=["fov","distance","height"],Ut=["fov","distance","height","intro"];function et(t){if(t===null||typeof t!="object"||Array.isArray(t))return{ok:!1,error:"camera must be an object"};let r=t;for(let s of Object.keys(r))if(!Ut.includes(s))return{ok:!1,error:`unknown camera key: ${s} (expected ${Ut.join(" | ")})`};let a={},i=[];for(let s of $t){let u=r[s];if(u===void 0)continue;if(u===null){a[s]=null;continue}if(typeof u!="number"||!Number.isFinite(u))return{ok:!1,error:`camera.${s} must be a finite number or null`};let[d,g]=V[s],X=Math.min(g,Math.max(d,u));X!==u&&i.push(s),a[s]=X}if(r.intro!==void 0){if(r.intro!==null&&typeof r.intro!="boolean")return{ok:!1,error:"camera.intro must be a boolean or null"};a.intro=r.intro}return{ok:!0,camera:a,clamped:i}}function Cn(t){let r={},a=[],i={fov:"cameraFov",distance:"cameraDistance",height:"cameraHeight"};for(let u of $t){let d=t(i[u]);if(d===null)continue;let g=d.trim(),X=g===""?NaN:Number(g);if(!Number.isFinite(X)){a.push(`ignoring invalid ?${i[u]}=${d}`);continue}let[S,y]=V[u],z=Math.min(y,Math.max(S,X));z!==X&&a.push(`?${i[u]}=${d} is out of range [${S}, ${y}], clamped to ${z}`),r[u]=z}let s=t("cameraIntro");if(s!==null){let u=s.trim().toLowerCase();u==="1"||u==="true"?r.intro=!0:u==="0"||u==="false"?r.intro=!1:a.push(`ignoring invalid ?cameraIntro=${s}`)}return{camera:r,warnings:a}}var Nt=/^[a-z][a-z0-9_]{0,63}$/,T=t=>typeof t=="string"&&Nt.test(t),kn=(t,r)=>Object.prototype.hasOwnProperty.call(t,r),Mn=["zh-CN","en","ja"];function N(t,r,a){let i={type:t,v:1,payload:r};return a!==void 0&&(i.id=a),i}function Ee(t){if(!t||typeof t!="object")return!1;let r=t;return typeof r.type=="string"&&r.type.startsWith("xc.")&&r.v===1}function Se(t){if(!t||t==="*"||t==="null")return null;try{let r=new URL(t);return r.protocol!=="https:"&&r.protocol!=="http:"?null:r.origin}catch{return null}}var Me=Object.freeze({minWidth:120,minHeight:180,maxWidth:1/0,maxHeight:1/0}),Ce=t=>typeof t=="number"&&Number.isFinite(t)&&t>0;function tt(t){if(!t)return null;let r=t===!0?{}:t,a=Ce(r.minWidth)?r.minWidth:Me.minWidth,i=Ce(r.minHeight)?r.minHeight:Me.minHeight,s=Ce(r.maxWidth)?Math.max(r.maxWidth,a):1/0,u=Ce(r.maxHeight)?Math.max(r.maxHeight,i):1/0;return{minWidth:a,minHeight:i,maxWidth:s,maxHeight:u}}var oe=(t,r,a)=>Math.min(Math.max(t,r),Math.max(r,a));function Wt(t,r,a,i){return{left:oe(t.left+r,0,i.width-t.width),top:oe(t.top+a,0,i.height-t.height),width:t.width,height:t.height}}function Ft(t,r,a,i,s,u){let d=r==="NW"||r==="SW",g=r==="NW"||r==="NE",X=t.left+t.width,S=t.top+t.height,y=d?t.width-a:t.width+a,z=g?t.height-i:t.height+i,D=d?X:u.width-t.left,M=g?S:u.height-t.top,Ie=oe(y,s.minWidth,Math.min(s.maxWidth,D)),ie=oe(z,s.minHeight,Math.min(s.maxHeight,M));return{left:d?X-Ie:t.left,top:g?S-ie:t.top,width:Ie,height:ie}}function Oe(t,r){let a=Math.min(t.width,Math.max(1,r.width)),i=Math.min(t.height,Math.max(1,r.height));return{left:oe(t.left,0,r.width-a),top:oe(t.top,0,r.height-i),width:a,height:i}}var On=new Set(["NW","NE","SW","SE"]),Rn=new Set(["start","move","end"]),Ln=new Set(["up","cancel","blur"]),zn=2e4,ke=t=>typeof t=="number"&&Number.isFinite(t)&&Math.abs(t)<=zn,jt=t=>typeof t=="number"&&Number.isSafeInteger(t)&&t>=0;function Gt(t,r){if(r===null||typeof r!="object")return null;let a=r;if(!jt(a.gesture)||!jt(a.seq)||typeof a.phase!="string"||!Rn.has(a.phase)||!ke(a.dx)||!ke(a.dy)||!ke(a.totalDx)||!ke(a.totalDy)||a.reason!==void 0&&(typeof a.reason!="string"||!Ln.has(a.reason)))return null;let i={gesture:a.gesture,seq:a.seq,phase:a.phase,totalDx:a.totalDx,totalDy:a.totalDy};if(t==="resize"){if(typeof a.corner!="string"||!On.has(a.corner))return null;i.corner=a.corner}return i}var me=class{constructor(){this.lastGesture=0;this.lastSeq=-1;this.open=!1}get active(){return this.open}accept(r){return r.phase==="start"?r.gesture<=this.lastGesture||r.seq!==0?!1:(this.lastGesture=r.gesture,this.lastSeq=0,this.open=!0,!0):!this.open||r.gesture!==this.lastGesture||r.seq<=this.lastSeq?!1:(this.lastSeq=r.seq,r.phase==="end"&&(this.open=!1),!0)}close(){this.open=!1}};var In="data:image/svg+xml;utf8,"+encodeURIComponent('<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 120 180"><defs><linearGradient id="g" x1="0" y1="0" x2="0" y2="1"><stop offset="0" stop-color="#f6b8ae"/><stop offset="1" stop-color="#ea8377"/></linearGradient></defs><ellipse cx="60" cy="170" rx="34" ry="6" fill="#000" opacity=".12"/><circle cx="60" cy="48" r="26" fill="url(#g)" opacity=".75"/><path d="M26 160c2-40 18-62 34-62s32 22 34 62z" fill="url(#g)" opacity=".6"/></svg>'),nt=t=>{t.setProperty("user-select","none"),t.setProperty("-webkit-user-select","none"),t.setProperty("-webkit-touch-callout","none"),t.setProperty("-webkit-tap-highlight-color","transparent")},Y=(t,r)=>t===void 0?r:typeof t=="number"?`${t}px`:t,it=600,at=1080,rt=(t=!1)=>t?`min(${it}px, calc(100vw - 2 * var(--xc-offset-x, 16px)))`:`min(${it}px, 100vw)`,ot=(t=!1)=>{let r=typeof CSS<"u"&&typeof CSS.supports=="function"&&CSS.supports("height","1svh")?"svh":"vh";return t?`min(${at}px, calc(100${r} - 2 * var(--xc-offset-y, 16px)))`:`min(${at}px, 100${r})`};function Re(t){if(typeof window>"u"||typeof document>"u")throw new Error("[project-xiaochun] createXiaochun must run in a browser");let r=typeof t.container=="string"?document.querySelector(t.container):t.container;if(!r)throw new Error(`[project-xiaochun] container not found: ${String(t.container)}`);let a=t.src??Ve,i;try{i=new URL(a,window.location.href)}catch{throw new Error(`[project-xiaochun] invalid src: ${a}`)}let s=Se(t.origin??i.origin);if(!s)throw new Error("[project-xiaochun] invalid origin (wildcards are not allowed)");let u=new Set([s]);for(let e of t.allowedOrigins??[]){let n=Se(e);if(!n)throw new Error(`[project-xiaochun] invalid allowedOrigins entry: ${e} (wildcards are not allowed)`);u.add(n)}let d=t.persist==="host"?"xiaochun:prefs":typeof t.persist=="string"&&t.persist?t.persist:null,g=()=>{if(!d)return{};try{let e=JSON.parse(window.localStorage.getItem(d)??"null"),n={};return e&&typeof e=="object"&&(T(e.outfit)&&(n.outfit=e.outfit),T(e.scene)&&(n.scene=e.scene)),n}catch{return{}}},X=e=>{if(d)try{let n={...g()};for(let[o,c]of Object.entries(e))c?n[o]=c:delete n[o];window.localStorage.setItem(d,JSON.stringify(n))}catch{}},S=g();t.model!==void 0&&t.outfit===void 0&&console.warn('[project-xiaochun] option "model" is deprecated, use "outfit" (built-in outfit id).');let y=Qe(t.ui),z=y.parts,D=he(t.uiAutoHide);t.uiAutoHide!==void 0&&D===void 0&&console.warn(`[project-xiaochun] ignoring invalid uiAutoHide: ${String(t.uiAutoHide)} (use true | false | 'transparent')`);let M={};if(t.camera!==void 0){let e=et(t.camera);e.ok?(M=e.camera,e.clamped.length&&console.warn(`[project-xiaochun] camera.${e.clamped.join(", camera.")} out of range, clamped (fov ${V.fov.join("\u2013")}, distance ${V.distance.join("\u2013")}, height ${V.height.join("\u2013")})`)):console.warn(`[project-xiaochun] ignoring invalid camera option: ${e.error}`)}y.legacy&&console.warn(`[project-xiaochun] option "ui: true" is deprecated, use an array of parts, e.g. ui: ['chat', 'bubble', 'outfit', 'scene'].`),y.unknown.length&&console.warn(`[project-xiaochun] ignoring unknown ui part(s): ${y.unknown.join(", ")} (known: ${pe.join(", ")})`);let ie=t.outfit??(T(t.model)?t.model:void 0)??S.outfit,J=t.scene??S.scene??(t.transparent?"transparent":void 0),Z=J==="transparent"||J!=="light"&&J!=="dark"&&(t.transparent??!1),Q=t.passthrough??Z,He=t.lazy??!0,x=t.position??"inline",ut=t.handshakeTimeout??2e4,I=document.createElement("div");I.setAttribute("data-xiaochun","");let l=I.style;l.position=x==="inline"?"relative":"fixed",l.width=Y(t.width,rt(x!=="inline")),l.height=Y(t.height,ot(x!=="inline")),l.maxWidth="100%",l.overflow="visible",l.contain="layout style",nt(l),l.boxShadow="var(--xc-shadow, none)";let lt=()=>{l.background=Z?"":"var(--xc-bg, transparent)"};lt();let _e=t.borderRadius,ge=()=>_e!==void 0?Y(_e,"0px"):Z?"0px":`${Ye}px`,dt=()=>{let e=`var(--xc-radius, ${ge()})`;l.borderRadius=e,O&&(O.style.borderRadius=e),m&&(m.style.borderRadius=e)};l.borderRadius=`var(--xc-radius, ${ge()})`,x==="bottom-right"&&(l.right="var(--xc-offset-x, 16px)",l.bottom="var(--xc-offset-y, 16px)"),x==="bottom-left"&&(l.left="var(--xc-offset-x, 16px)",l.bottom="var(--xc-offset-y, 16px)"),x!=="inline"&&(l.zIndex=`var(--xc-z-index, ${t.zIndex??2147483e3})`),l.pointerEvents="none",I.setAttribute("part","wrapper"),r.appendChild(I);let O=null;if(t.placeholder!==!1){if(t.placeholder instanceof HTMLElement)O=t.placeholder;else{let n=document.createElement("img");n.src=t.placeholder||In,n.alt="Project XiaoChun",n.decoding="async",n.width=it,n.height=at,O=n}let e=O.style;O.setAttribute("part","placeholder"),e.borderRadius=`var(--xc-radius, ${ge()})`,e.position="absolute",e.inset="0",e.width="100%",e.height="100%",e.objectFit="contain",e.transition="opacity .25s ease",e.pointerEvents="auto",e.cursor=He===!1?"default":"pointer",nt(e),O.addEventListener("click",()=>$()),I.appendChild(O)}let ye=new Map,b=(e,n)=>{ye.get(e)?.forEach(o=>{try{o(n)}catch(c){console.error("[project-xiaochun] listener error",c)}})},ft,pt,ht=new Promise((e,n)=>{ft=e,pt=n});ht.catch(()=>{});let m=null,w=null,v=!1,Te=!1,mt=!1,Ue=!1,ae=!1,P=null,gt=null,yt=null,Be=[],H=new Map,$e=0,ee=null,q=null,te=null,Ne,xt=new Promise(e=>{Ne=e}),Zt=(e,n,o,c)=>{b("error",{code:o,message:c,command:e});let p=n?H.get(n):void 0;p&&n&&(H.delete(n),p.reject(new Error(`[${o}] ${c}`)))},bt=(e,n)=>Zt(e,n,"unsupported",`${e} is not supported by this /embed deployment (older version; its xc.ready has no capabilities for it)`),se=(e,n,o,c,p)=>{if(!w){Be.push({type:e,payload:n,id:o,transfer:c,requires:p});return}if(p&&!P?.[p]){bt(e,o);return}w.postMessage(N(e,n,o),c??[])},C=(e,n,o=!1,c,p,f)=>{if(v)return Promise.reject(new Error("[project-xiaochun] instance destroyed"));m||$();let h=p??`c${++$e}`,A=o?new Promise((L,k)=>H.set(h,{resolve:L,reject:k,sawEnd:!1})):Promise.resolve();return se(e,n,h,c,f),A},Xt=e=>e instanceof ArrayBuffer?e:e.buffer.slice(e.byteOffset,e.byteOffset+e.byteLength),wt=(e,n)=>{if(!e)return;let o=()=>{v||se("xc.audio.end",{abort:!0},n)};e.aborted?o():e.addEventListener("abort",o,{once:!0})},Qt=async(e,n={})=>{if(v)throw new Error("[project-xiaochun] instance destroyed");m||$();let{signal:o,transfer:c,fetch:p,...f}=n,h={...f},A=[];if(typeof e=="string")if(p==="frame")h.source=e;else{let E=await fetch(e);if(!E.ok)throw new Error(`[project-xiaochun] audio fetch failed: HTTP ${E.status}`);let K=await E.arrayBuffer();h.source=K,A.push(K),h.mimeType??(h.mimeType=E.headers.get("content-type")??void 0)}else if(typeof Blob<"u"&&e instanceof Blob)h.source=e,h.mimeType??(h.mimeType=e.type||void 0);else{let E=Xt(e);h.source=E,(!(e instanceof ArrayBuffer)||c!==!1)&&A.push(E)}if(v)throw new Error("[project-xiaochun] instance destroyed");let L=`c${++$e}`,k=C("xc.audio",h,!0,A,L);return wt(o,L),k},en=e=>{if(v)throw new Error("[project-xiaochun] instance destroyed");let{signal:n,transfer:o,fetch:c,mimeType:p,...f}=e,h=`c${++$e}`,A=!1,L=!1,k=f.format==="pcm16"||f.format==="float32"?f.format:null,E=Promise.resolve();return{write(Ae){if(L)throw new Error("[project-xiaochun] audio stream already ended");if(v)throw new Error("[project-xiaochun] instance destroyed");if(Ae instanceof Int16Array?k??(k="pcm16"):Ae instanceof Float32Array&&(k??(k="float32")),!k)throw new Error("[project-xiaochun] speakAudioStream: set opts.format when writing raw ArrayBuffers");let qe=Xt(Ae),fe={data:qe,format:k,sampleRate:f.sampleRate,channels:f.channels};A?se("xc.audio.chunk",fe,h,!(Ae instanceof ArrayBuffer)||o!==!1?[qe]:[]):(A=!0,fe.text=f.text,fe.motion=f.motion,fe.lipsync=f.lipsync,E=C("xc.audio.chunk",fe,!0,[qe],h),wt(n,h))},end(){L||(L=!0,A&&se("xc.audio.end",{},h))},abort(){L&&!A||(L=!0,A&&se("xc.audio.end",{abort:!0},h))},get done(){return E}}};function tn(){let e=new URL(i.href);return e.searchParams.set("host",window.location.origin),Z&&e.searchParams.set("transparent","1"),z.length&&e.searchParams.set("ui",z.join(",")),t.lang&&e.searchParams.set("lang",t.lang),D!==void 0&&e.searchParams.set("uiAutoHide",String(D)),typeof M.fov=="number"&&e.searchParams.set("cameraFov",String(M.fov)),typeof M.distance=="number"&&e.searchParams.set("cameraDistance",String(M.distance)),typeof M.height=="number"&&e.searchParams.set("cameraHeight",String(M.height)),typeof M.intro=="boolean"&&e.searchParams.set("cameraIntro",M.intro?"1":"0"),t.heavy&&e.searchParams.set("heavy",t.heavy),t.controls===!1&&e.searchParams.set("controls","0"),J&&T(J)&&e.searchParams.set("scene",J),ie&&e.searchParams.set("outfit",ie),e.href}function $(){if(v||m)return;kt(),q?.disconnect(),q=null;let e=document.createElement("iframe");e.title="Project XiaoChun",e.loading="lazy",e.allow=t.crossOriginIsolated===!0?"microphone; autoplay; cross-origin-isolated":"microphone; autoplay",e.referrerPolicy="strict-origin-when-cross-origin",t.sandbox!==!1&&e.setAttribute("sandbox",t.sandbox??"allow-scripts allow-same-origin allow-popups allow-popups-to-escape-sandbox"),e.setAttribute("allowtransparency","true"),e.setAttribute("scrolling","no");let n=e.style;n.position="absolute",n.inset="0",n.width="100%",n.height="100%",n.border="0",n.background="transparent",n.colorScheme="normal",n.borderRadius=`var(--xc-radius, ${ge()})`,e.setAttribute("part","iframe"),nt(n),n.opacity="0",n.transition="opacity .25s ease",n.pointerEvents=Q?"none":"auto",e.src=tn(),m=e,I.appendChild(e),O&&(O.style.cursor="default"),ee=setTimeout(()=>{w||b("error",{code:"timeout",message:`no xc.ready from ${s} within ${ut}ms`})},ut),sn(),Q&&Et()}let vt=e=>{if(v||!m||e.source!==m.contentWindow)return;if(!u.has(e.origin)){b("error",{code:"origin_denied",message:`ignored message from untrusted origin ${e.origin}`});return}let n=e.data;if(!Ee(n)||n.type!=="xc.ready"||w)return;let o=new MessageChannel;w=o.port1,w.onmessage=nn,P=n.payload?.capabilities??null;let c=Rt();de=c;let p={...t.allowCustomModel?{allowCustomModel:!0}:{},...c.move||c.resize?{gestures:c}:{}};m.contentWindow.postMessage(N("xc.init",{hostOrigin:window.location.origin,...Object.keys(p).length?{config:p}:{}}),e.origin,[o.port2]),It(),ee&&(clearTimeout(ee),ee=null),b("handshake",n.payload),Ne();for(let f of Be.splice(0))f.requires&&!P?.[f.requires]?bt(f.type,f.id):w.postMessage(N(f.type,f.payload,f.id),f.transfer??[]);we()};window.addEventListener("message",vt);function je(e,n){let o=e?H.get(e):void 0;o&&e&&(H.delete(e),o.resolve(n))}function nn(e){let n=e.data;if(Ee(n))switch(n.type){case"xc.load.progress":b("progress",n.payload);break;case"xc.loaded":if(!Ue){if(Ue=!0,t.prefetch&&t.heavy==="eager"&&P?.prefetch){let o=Array.isArray(t.prefetch)?t.prefetch:void 0;Tt.prefetch(o).catch(()=>{})}if(m&&(m.style.opacity="1"),O){let o=O;o.style.opacity="0",o.style.pointerEvents="none",setTimeout(()=>o.remove(),300),O=null}ft()}b("ready",n.payload);break;case"xc.outfit-changed":{let o=n.payload;o.noop||(gt=o.id,b("outfit-changed",o),!o.initial&&o.id&&X({outfit:o.id})),je(n.id);break}case"xc.scene-changed":{let o=n.payload;yt=o.id,o.transparent!==Z&&an(o.transparent),o.noop||(b("scene-changed",o),o.initial||X({scene:o.id})),je(n.id);break}case"xc.lang-changed":b("lang-changed",n.payload);break;case"xc.prefetched":je(n.id,n.payload);break;case"xc.state":b("state",n.payload);break;case"xc.stt":b("stt",n.payload);break;case"xc.utterance":{b("utterance",n.payload);let o=n.id?H.get(n.id):void 0;o&&n.payload.phase==="end"&&(H.delete(n.id),o.resolve());break}case"xc.hit-region":{let{hit:o}=n.payload;b("hit-region",n.payload),Q&&m&&o!==ae&&(ae=o,m.style.pointerEvents=o?"auto":"none");break}case"xc.gesture-move":Lt("move",n.payload);break;case"xc.gesture-resize":Lt("resize",n.payload);break;case"xc.error":{let{code:o,message:c,command:p}=n.payload;b("error",{code:o,message:c,command:p}),o==="unknown_id"&&(p==="outfit"||p==="scene")&&X({[p]:null});let f=n.id?H.get(n.id):void 0;f&&n.id&&(H.delete(n.id),f.reject(new Error(`[${o}] ${c}`)));break}default:break}}let rn=32,Pt=2,j=0,ce=null,W=null,ue=null,xe=null,At=0,F=()=>{ue=null},on=()=>{if(!m)return null;let e=performance.now();return(!ue||e-At>400)&&(ue=m.getBoundingClientRect(),At=e),ue},be=e=>{!m||!w||m.style.pointerEvents==="auto"||(ce={x:e.clientX,y:e.clientY},!j&&(j=requestAnimationFrame(()=>{if(j=0,!m||!w||!ce)return;let n=on();if(!n)return;let o=ce.x-n.left,c=ce.y-n.top;if(o<0||c<0||o>n.width||c>n.height){W=null,ae&&(ae=!1,m.style.pointerEvents="none");return}let p=performance.now();W&&p-W.t<rn||W&&Math.abs(o-W.x)<Pt&&Math.abs(c-W.y)<Pt||(W={x:o,y:c,t:p},w.postMessage(N("xc.pointer",{x:o,y:c})))})))},Xe=!1;function Et(){Xe||!m||(Xe=!0,window.addEventListener("pointermove",be,{passive:!0}),window.addEventListener("pointerdown",be,{passive:!0}),window.addEventListener("scroll",F,{passive:!0,capture:!0}),window.addEventListener("resize",F,{passive:!0}),typeof ResizeObserver<"u"&&(xe=new ResizeObserver(F),xe.observe(m)))}function St(){Xe&&(Xe=!1,window.removeEventListener("pointermove",be),window.removeEventListener("pointerdown",be),window.removeEventListener("scroll",F,!0),window.removeEventListener("resize",F),xe?.disconnect(),xe=null,j&&(cancelAnimationFrame(j),j=0),ce=null)}function an(e){Z=e,lt(),dt(),Q=e?t.passthrough??!0:!1,ae=!1,W=null,ue=null,Q?Et():St(),m&&(m.style.pointerEvents=Q?"none":"auto")}let We=null;function sn(){t.autoPause===!1||typeof IntersectionObserver>"u"||(We=new IntersectionObserver(e=>{mt=!(e[e.length-1]?.isIntersecting??!0),we()}),We.observe(I))}let Ct=!1;function we(){if(!w)return;let e=Te||mt;e!==Ct&&(Ct=e,w.postMessage(N(e?"xc.pause":"xc.resume")))}function kt(){if(te===null)return;let e=window;e.cancelIdleCallback?e.cancelIdleCallback(te):clearTimeout(te),te=null}function cn(){if(He===!1){$();return}if(He==="click")return;let e=()=>{let n=window;te=n.requestIdleCallback?n.requestIdleCallback(()=>{te=null,$()},{timeout:3e3}):setTimeout($,1200)};if(typeof IntersectionObserver>"u"){e();return}q=new IntersectionObserver(n=>{n.some(o=>o.isIntersecting)&&(q?.disconnect(),q=null,e())},{rootMargin:`${t.lazyMargin??200}px`}),q.observe(I)}let le=t.draggable===!0,B=tt(t.resizable),Mt={move:new me,resize:new me},_=null,R={x:0,y:0},Fe=!1,de=null,Ot=!1,Ge=()=>({width:document.documentElement.clientWidth||window.innerWidth,height:document.documentElement.clientHeight||window.innerHeight}),ne=()=>{let e=I.getBoundingClientRect();return{left:e.left,top:e.top,width:e.width,height:e.height}},Rt=()=>({move:le&&P?.gestures?.move===!0,resize:B!==null&&P?.gestures?.resize===!0});function ve(e,n,o){if(o&&(l.width=`${e.width}px`,l.height=`${e.height}px`,l.maxWidth="none"),x==="inline"){let c=n??{left:e.left-R.x,top:e.top-R.y};R={x:e.left-c.left,y:e.top-c.top},l.setProperty("translate",`${R.x}px ${R.y}px`)}else l.left=`${e.left}px`,l.top=`${e.top}px`,l.right="auto",l.bottom="auto";Fe=!0,F()}let re=null;function Pe(e){let n=document.documentElement;if(e&&!re){re={us:n.style.getPropertyValue("user-select"),wus:n.style.getPropertyValue("-webkit-user-select")},n.style.setProperty("user-select","none"),n.style.setProperty("-webkit-user-select","none");try{window.getSelection()?.removeAllRanges()}catch{}}else!e&&re&&(n.style.setProperty("user-select",re.us),n.style.setProperty("-webkit-user-select",re.wus),re=null)}function De(e){if(!_||e&&_.kind!==e)return;Mt[_.kind].close();let n=ne();b(_.kind,{phase:"end",...n}),_=null,Pe(!1),_t()}function Lt(e,n){if(v||!P?.gestures||(e==="move"?!le:B===null))return;let o=Gt(e,n);if(!o||(o.phase==="start"?_!==null:_?.kind!==e)||!Mt[e].accept(o))return;if(o.phase==="start"){let h=ne();_={kind:e,start:h,corner:o.corner,inlineBase:x==="inline"?{left:h.left-R.x,top:h.top-R.y}:null},Pe(!0),b(e,{phase:"start",...h});return}let c=_,p=Ge(),f=e==="move"?Wt(c.start,o.totalDx,o.totalDy,p):Ft(c.start,c.corner,o.totalDx,o.totalDy,B,p);ve(f,c.inlineBase,e==="resize"),b(e,{phase:o.phase,...f}),o.phase==="end"&&(_=null,Pe(!1),_t())}function zt(){if(v)return;let e=Rt();e.move||De("move"),e.resize||De("resize"),!(!w||!P)&&(It(),!(de&&de.move===e.move&&de.resize===e.resize)&&(de=e,P.gestures&&w.postMessage(N("xc.setConfig",{gestures:e}))))}function It(){if(Ot||!P||P.gestures)return;let e=le;if(!e&&B===null)return;Ot=!0;let n=[e?"draggable":"",B!==null?"resizable":""].filter(Boolean).join(" / ");b("error",{code:"unsupported",message:`${n} needs gesture support (capabilities.gestures), which this /embed deployment does not advertise (older version)`,command:"gestures"})}let Ht=()=>{if(!Fe||_||v)return;let e=ne(),n=Ge(),o=x==="inline"?{...Oe({...e,top:0},{width:n.width,height:Number.MAX_SAFE_INTEGER}),top:Math.max(e.top,-window.scrollY)}:Oe(e,n);o.left===e.left&&o.top===e.top&&o.width===e.width&&o.height===e.height||ve(o,x==="inline"?{left:e.left-R.x,top:e.top-R.y}:null,o.width!==e.width||o.height!==e.height)};window.addEventListener("resize",Ht,{passive:!0});let G=t.persistBox===!0?"xiaochun:box":typeof t.persistBox=="string"&&t.persistBox?`xiaochun:box:${t.persistBox}`:null,_t=()=>{if(G)try{let e=ne(),n=x==="inline"?R:{x:e.left,y:e.top};window.localStorage.setItem(G,JSON.stringify({v:1,mode:x,x:Math.round(n.x),y:Math.round(n.y),width:Math.round(e.width),height:Math.round(e.height)}))}catch{}},un=()=>{if(!G)return null;try{let e=window.localStorage.getItem(G);if(e===null)return null;let n=null;try{n=JSON.parse(e)}catch{}let o=(c,p,f)=>typeof c=="number"&&Number.isFinite(c)&&c>=p&&c<=f;if(n&&n.v===1&&n.mode===x&&o(n.x,-1e5,1e5)&&o(n.y,-1e5,1e5)&&o(n.width,1,1e5)&&o(n.height,1,1e5))return{x:n.x,y:n.y,width:n.width,height:n.height};window.localStorage.removeItem(G)}catch{}return null};function ln(){if(!G||!le&&B===null)return;let e=un();if(!e)return;let n=Ge(),o=B??Me,c=ne(),p=B!==null&&t.width===void 0,f=B!==null&&t.height===void 0,h=(k,E,K)=>Math.min(Math.max(k,E),Math.max(E,K)),A=p?h(e.width,o.minWidth,Math.min(o.maxWidth,n.width)):c.width,L=f?h(e.height,o.minHeight,Math.min(o.maxHeight,n.height)):c.height;if(x==="inline"){let k={left:c.left-R.x,top:c.top-R.y},E=h(k.left+e.x,0,n.width-A),K=Math.max(k.top+e.y,-window.scrollY);ve({left:E,top:K,width:A,height:L},k,p||f)}else ve(Oe({left:e.x,top:e.y,width:A,height:L},n),null,p||f)}ln(),cn();let Tt={element:I,get iframe(){return m},ready:ht,activate:$,say:(e,n)=>C("xc.say",{text:e,mode:n?.mode},!0),speakAudio:Qt,speakAudioStream:en,motion:e=>C("xc.motion",typeof e=="string"?e.startsWith("http")||e.startsWith("/")?{url:e}:{name:e}:e),expression:e=>C("xc.expression",{name:e}),lookAt:(e,n)=>C("xc.lookAt",{x:e,y:n}),setOutfit:e=>T(e)?C("xc.setOutfit",{id:e},!0,void 0,void 0,"outfits"):Promise.reject(new Error("[bad_request] invalid outfit id")),setScene:e=>T(e)?C("xc.setScene",{id:e},!0,void 0,void 0,"scenes"):Promise.reject(new Error("[bad_request] invalid scene id")),prefetch:e=>e!==void 0&&(!Array.isArray(e)||e.some(n=>!T(n)))?Promise.reject(new Error("[bad_request] prefetch ids must be an array of outfit ids")):C("xc.prefetch",e?{ids:e}:{},!0,void 0,void 0,"prefetch"),getOutfits:async()=>(m||$(),await xt,P?.outfits?P.outfits.slice():[]),getScenes:async()=>(m||$(),await xt,P?.scenes?P.scenes.slice():[]),get outfit(){return gt},get scene(){return yt},setModel:e=>{let n=typeof e=="string"?/^(https?:)?\/|\.vrm/i.test(e)?{url:e}:{outfit:e}:e;if(n.url!==void 0&&n.outfit===void 0&&!t.allowCustomModel){let o="custom model URLs are disabled; pass allowCustomModel: true to createXiaochun() (only for URLs you trust) or use setOutfit() with a built-in id";return b("error",{code:"unsupported",message:o,command:"xc.setModel"}),Promise.reject(new Error(`[unsupported] ${o}`))}return C("xc.setModel",n)},setConfig:e=>C("xc.setConfig",e),setSize(e,n){v||(l.width=Y(e,rt(x!=="inline")),l.height=Y(n,ot(x!=="inline")),l.maxWidth==="none"&&(l.maxWidth="100%"),F())},getBox:()=>ne(),clearPersistedBox(e){if(G)try{window.localStorage.removeItem(G)}catch{}v||e?.reset!==!0||(De(),l.width=Y(t.width,rt(x!=="inline")),l.height=Y(t.height,ot(x!=="inline")),l.maxWidth="100%",x==="inline"?(R={x:0,y:0},l.removeProperty("translate")):(l.left="",l.top="",l.right="",l.bottom="",x==="bottom-right"&&(l.right="var(--xc-offset-x, 16px)",l.bottom="var(--xc-offset-y, 16px)"),x==="bottom-left"&&(l.left="var(--xc-offset-x, 16px)",l.bottom="var(--xc-offset-y, 16px)")),Fe=!1,F())},setBorderRadius(e){_e=e,dt()},setDraggable(e){le=e===!0,zt()},setResizable(e){B=tt(e),zt()},startListening:()=>C("xc.mic",{enabled:!0}),stopListening:()=>C("xc.mic",{enabled:!1}),mic:e=>C("xc.mic",{enabled:e}),pause(){Te=!0,we()},resume(){Te=!1,we()},destroy(){if(!v){try{w?.postMessage(N("xc.destroy"))}catch{}v=!0,kt(),q?.disconnect(),We?.disconnect(),ee&&clearTimeout(ee),j&&cancelAnimationFrame(j),window.removeEventListener("message",vt),window.removeEventListener("resize",Ht),Pe(!1),St(),Ne();try{w?.close()}catch{}w=null;for(let e of H.values())e.reject(new Error("[project-xiaochun] instance destroyed"));H.clear(),Be.length=0,Ue||pt(new Error("[project-xiaochun] destroyed before ready")),I.remove(),m=null,b("destroy",void 0),ye.clear()}},on(e,n){let o=ye.get(e);return o||(o=new Set,ye.set(e,o)),o.add(n),()=>{o.delete(n)}}};return Tt}var Hn=["src","outfit","scene","model","lang","mic","transparent","draggable","resizable","min-size","max-size","border-radius","position","size","lazy","paused","placeholder","heavy","ui","ui-autohide","camera-fov","camera-distance","camera-height","camera-intro","controls","allowed-origins","cross-origin-isolated","persist","persist-box","allow-custom-model","prefetch"],_n=new Set(["src","position","lazy","placeholder","heavy","ui","ui-autohide","controls","allowed-origins","transparent","cross-origin-isolated","persist","persist-box","allow-custom-model","prefetch"]);function Dt(t){if(t===null||t.trim()==="")return;let r=t.trim();return/^\d+(\.\d+)?$/.test(r)?Number(r):r}function U(t,r,a){let i=t.getAttribute(r);return i===null?a:i!=="false"}function Tn(t){return t===null||t==="false"?!1:t===""||t==="true"?!0:t.split(",").map(r=>r.trim()).filter(Boolean)}function Un(t){if(!(t===null||t==="false"||t==="0"))return t===""||t==="true"||t==="1"?!0:t}function Bn(t){if(!(t===null||t==="false"||t==="0"))return t===""||t==="true"||t==="1"?!0:t.split(",").map(r=>r.trim()).filter(Boolean)}function qt(t){let r=i=>{let s=t.getAttribute(i);if(s===null||s.trim()==="")return null;let u=Number(s);return Number.isFinite(u)?u:null},a=t.getAttribute("camera-intro");return{fov:r("camera-fov"),distance:r("camera-distance"),height:r("camera-height"),intro:a===null?null:a!=="false"&&a!=="0"}}function Kt(t){let r=t?.trim().match(/^(\d+(?:\.\d+)?)\s*x\s*(\d+(?:\.\d+)?)$/i);return r?{w:Number(r[1]),h:Number(r[2])}:void 0}function Vt(t){if(!t)return{width:void 0,height:void 0};let r=t.trim().split(/x/i),a=s=>/^\d+(\.\d+)?$/.test(s)?`${s}px`:s;if(r.length>=2)return{width:a(r[0]),height:a(r[1])};let i=parseFloat(r[0]);return Number.isFinite(i)&&/^\d+(\.\d+)?$/.test(r[0])?{width:`${i}px`,height:`${Math.round(i*1.5)}px`}:{width:r[0],height:void 0}}function $n(){class t extends HTMLElement{constructor(){super(...arguments);this.client=null;this.mountEl=null;this.rebuildScheduled=!1}static get observedAttributes(){return[...Hn]}connectedCallback(){if(!this.shadowRoot){let i=this.attachShadow({mode:"open"});i.innerHTML='<style>:host{display:inline-block;max-width:100%}:host([hidden]){display:none}</style><div part="mount"></div>'}this.mountEl=this.shadowRoot.querySelector("div"),this.build()}disconnectedCallback(){this.destroy()}attributeChangedCallback(i,s,u){if(!this.client||s===u)return;if(_n.has(i)){this.rebuildScheduled||(this.rebuildScheduled=!0,queueMicrotask(()=>{this.rebuildScheduled=!1,this.isConnected&&(this.destroy(),this.build())}));return}let d=this.client;if((i==="outfit"||i==="model")&&u){let g=i==="model"&&this.hasAttribute("outfit")?null:u;g&&(T(g)?d.setOutfit(g):d.setModel(g)).catch(()=>{})}else if(i==="scene"&&u)d.setScene(u).catch(()=>{});else if(i==="lang"&&u)d.setConfig({lang:u}).catch(()=>{});else if(i==="size"){let{width:g,height:X}=Vt(u);d.setSize(g,X)}else i==="border-radius"?d.setBorderRadius(Dt(u)):i==="draggable"?d.setDraggable(U(this,"draggable",!1)):i==="resizable"||i==="min-size"||i==="max-size"?d.setResizable(this.resizableOption()):i.startsWith("camera-")?d.setConfig({camera:qt(this)}).catch(()=>{}):i==="mic"?d.mic(U(this,"mic",!1)).catch(()=>{}):i==="paused"&&(U(this,"paused",!1)?d.pause():d.resume())}build(){if(!this.mountEl||this.client)return;let{width:i,height:s}=Vt(this.getAttribute("size")),u=this.getAttribute("placeholder"),d=this.getAttribute("allowed-origins"),g=this.getAttribute("lazy"),X=g==="click"?"click":g!=="false",S=Re({container:this.mountEl,src:this.getAttribute("src")||void 0,allowedOrigins:d?d.split(",").map(z=>z.trim()).filter(Boolean):void 0,lazy:X,placeholder:u==="none"?!1:u||void 0,transparent:U(this,"transparent",!0),width:i,height:s,position:this.getAttribute("position")??"inline",draggable:U(this,"draggable",!1),resizable:this.resizableOption(),borderRadius:Dt(this.getAttribute("border-radius")),lang:this.getAttribute("lang")??void 0,outfit:this.getAttribute("outfit")??this.getAttribute("model")??void 0,scene:this.getAttribute("scene")??void 0,persist:this.getAttribute("persist")||void 0,persistBox:Un(this.getAttribute("persist-box")),allowCustomModel:U(this,"allow-custom-model",!1),prefetch:Tn(this.getAttribute("prefetch")),heavy:this.getAttribute("heavy")??void 0,ui:Bn(this.getAttribute("ui")),uiAutoHide:he(this.getAttribute("ui-autohide")),camera:qt(this),controls:U(this,"controls",!0),crossOriginIsolated:U(this,"cross-origin-isolated",!1)});this.client=S;let y=(z,D)=>S.on(z,M=>this.dispatchEvent(new CustomEvent(D,{detail:M,bubbles:!0,composed:!0})));y("ready","xc-ready"),y("progress","xc-progress"),y("state","xc-state"),y("stt","xc-stt"),y("utterance","xc-utterance"),y("error","xc-error"),y("outfit-changed","xc-outfit-changed"),y("scene-changed","xc-scene-changed"),y("lang-changed","xc-lang-changed"),y("move","xc-move"),y("resize","xc-resize"),U(this,"paused",!1)&&S.pause(),U(this,"mic",!1)&&S.ready.then(()=>S.mic(!0)).catch(()=>{})}resizableOption(){if(!U(this,"resizable",!1))return!1;let i=Kt(this.getAttribute("min-size")),s=Kt(this.getAttribute("max-size"));return{minWidth:i?.w,minHeight:i?.h,maxWidth:s?.w,maxHeight:s?.h}}say(i,s){return this.requireClient().say(i,s)}speakAudio(i,s){return this.requireClient().speakAudio(i,s)}speakAudioStream(i){return this.requireClient().speakAudioStream(i)}motion(i){return this.requireClient().motion(i)}expression(i){return this.requireClient().expression(i)}setOutfit(i){return this.requireClient().setOutfit(i)}setScene(i){return this.requireClient().setScene(i)}getOutfits(){return this.requireClient().getOutfits()}getScenes(){return this.requireClient().getScenes()}clearPersistedBox(i){this.client?.clearPersistedBox(i)}prefetch(i){return this.requireClient().prefetch(i)}destroy(){this.client?.destroy(),this.client=null}requireClient(){if(!this.client)throw new Error("<xiaochun-avatar> is not connected");return this.client}}return t}var st="xiaochun-avatar";function Le(t=st){if(typeof customElements>"u"||typeof HTMLElement>"u")return null;let r=customElements.get(t);if(r)return r;let a=$n();return customElements.define(t,a),a}var ze="xiaochun";function Yt(t){if(t.action!=="speak")throw new Error(`[project-xiaochun] unsupported action: ${String(t.action)}`);if(!t.text&&!t.audioUrl&&!t.file)throw new Error("[project-xiaochun] speak needs text, audioUrl or file");if(t.audioUrl&&!/^https?:\/\//i.test(t.audioUrl))throw new Error("[project-xiaochun] audioUrl must be http(s)");let r=new URLSearchParams;return t.text&&r.set("text",t.text),t.audioUrl&&r.set("audioUrl",t.audioUrl),t.file&&r.set("file",t.file),`${ze}://speak?${r.toString().replace(/\+/g,"%20")}`}function Jt(t){let r;try{r=new URL(t)}catch{return null}if(r.protocol!==`${ze}:`)return null;let a=r.hostname||r.pathname.replace(/^\/+/,"");if((a==="action"?r.searchParams.get("action"):a)!=="speak")return null;let s={action:"speak"},u=r.searchParams.get("text"),d=r.searchParams.get("audioUrl"),g=r.searchParams.get("file");return u&&(s.text=u),d&&(s.audioUrl=d),g&&(s.file=g),s.text||s.audioUrl||s.file?s:null}Le();var ct=document.currentScript;if(ct&&ct.hasAttribute("data-auto")){let t=()=>{let r=document.createElement("xiaochun-avatar");for(let a of Array.from(ct.attributes))a.name.startsWith("data-")&&a.name!=="data-auto"&&r.setAttribute(a.name.slice(5),a.value);r.hasAttribute("position")||r.setAttribute("position","bottom-right"),document.body.appendChild(r)};document.readyState==="loading"?document.addEventListener("DOMContentLoaded",t,{once:!0}):t()}return gn(Nn);})();
1
+ /*! @firetable/project-xiaochun v0.1.20 | MIT | https://github.com/FireTable/project-xiaochun */
2
+ "use strict";var Xiaochun=(()=>{var Ke=Object.defineProperty;var dn=Object.getOwnPropertyDescriptor;var fn=Object.getOwnPropertyNames;var pn=Object.prototype.hasOwnProperty;var hn=(t,r)=>{for(var a in r)Ke(t,a,{get:r[a],enumerable:!0})},mn=(t,r,a,i)=>{if(r&&typeof r=="object"||typeof r=="function")for(let s of fn(r))!pn.call(t,s)&&s!==a&&Ke(t,s,{get:()=>r[s],enumerable:!(i=dn(r,s))||i.enumerable});return t};var gn=t=>mn(Ke({},"__esModule",{value:!0}),t);var Nn={};hn(Nn,{XC_CAMERA_RANGES:()=>Z,XC_DEFAULT_ORIGIN:()=>Bt,XC_DEFAULT_SRC:()=>Ve,XC_FRAME_TO_HOST:()=>bn,XC_HOST_TO_FRAME:()=>xn,XC_ID_RE:()=>Nt,XC_IMPLEMENTED_COMMANDS:()=>Xn,XC_LANGS:()=>Mn,XC_PROTOCOL_MAPPING:()=>vn,XC_PROTOCOL_VERSION:()=>yn,XC_UI_AUTOHIDE_DEFAULT:()=>En,XC_UI_LEGACY_PARTS:()=>Je,XC_UI_PARTS:()=>pe,XC_UNSUPPORTED_COMMANDS:()=>wn,XC_WINDOW_CORNER_RADIUS:()=>Ye,XIAOCHUN_ELEMENT_TAG:()=>st,XIAOCHUN_PROTOCOL_SCHEME:()=>ze,createXiaochun:()=>Oe,defineXiaochunElement:()=>Le,isXcEnvelope:()=>Ee,isXcId:()=>T,normalizeOrigin:()=>Se,normalizeXcCamera:()=>et,normalizeXcUiOption:()=>Qe,parseProtocolUrl:()=>Jt,parseXcCameraParams:()=>Cn,parseXcUiAutoHide:()=>he,parseXcUiList:()=>Ze,parseXcUiParam:()=>An,toProtocolUrl:()=>Yt,xcHasOwn:()=>kn,xcMessage:()=>N,xcUiAutoHideActive:()=>Sn});var yn=1,Bt="https://xiaochun.firetable.tech",Ve=`${Bt}/embed`,xn=["xc.init","xc.say","xc.audio","xc.audio.chunk","xc.audio.end","xc.motion","xc.expression","xc.lookAt","xc.pointer","xc.setModel","xc.setOutfit","xc.setScene","xc.prefetch","xc.setConfig","xc.mic","xc.transport","xc.pause","xc.resume","xc.destroy"],bn=["xc.ready","xc.load.progress","xc.loaded","xc.outfit-changed","xc.scene-changed","xc.lang-changed","xc.prefetched","xc.state","xc.stt","xc.utterance","xc.hit-region","xc.gesture-move","xc.gesture-resize","xc.error"],Xn=["xc.say","xc.audio","xc.audio.chunk","xc.audio.end","xc.motion","xc.expression","xc.pointer","xc.setModel","xc.setOutfit","xc.setScene","xc.prefetch","xc.setConfig","xc.mic","xc.transport","xc.pause","xc.resume","xc.destroy"],wn=["xc.lookAt"],vn=[{xc:"xc.say",note:'mode:"speak" (\u9ED8\u8BA4)',action:"speak",url:"xiaochun://speak?text=\u2026"},{xc:"xc.say",note:'mode:"chat" (\u8D70 LLM)',action:null,url:null},{xc:"xc.audio",note:"source \u4E3A URL \u5B57\u7B26\u4E32",action:"speak",url:"xiaochun://speak?audioUrl=\u2026[&text=\u2026]"},{xc:"xc.audio",note:"source \u4E3A ArrayBuffer / Blob",action:"audio",url:null},{xc:"xc.audio.chunk / xc.audio.end",note:"\u6D41\u5F0F PCM",action:"audio",url:null},{xc:"xc.transport",note:"\u6539\u5BBF\u4E3B\u97F3\u9891\u500D\u901F / \u97F3\u91CF, \u65E0 deep link",action:null,url:null}],Ye=20,pe=["chat","bubble","outfit","scene","lang","github"],Pn=new Set(pe),Je=["chat","bubble"];function Ze(t){let r=new Set,a=[];for(let i of t){let s=typeof i=="string"?i.trim().toLowerCase():"";Pn.has(s)?r.add(s):a.push(typeof i=="string"?i.slice(0,40):typeof i)}return{parts:pe.filter(i=>r.has(i)),unknown:a,legacy:!1}}function An(t){let r=(t??"").trim().toLowerCase();return r===""||r==="0"||r==="false"?{parts:[],unknown:[],legacy:!1}:r==="1"||r==="true"?{parts:[...Je],unknown:[],legacy:!0}:Ze(r.split(",").filter(a=>a.trim()!==""))}function Qe(t){return t===!0?{parts:[...Je],unknown:[],legacy:!0}:Array.isArray(t)?Ze(t):{parts:[],unknown:[],legacy:!1}}var En="transparent";function he(t){if(t===!0||t===!1||t==="transparent")return t;if(typeof t!="string")return;let r=t.trim().toLowerCase();if(r==="1"||r==="true")return!0;if(r==="0"||r==="false")return!1;if(r==="transparent")return"transparent"}function Sn(t,r){return t==="transparent"?r:t}var Z={fov:[15,60],distance:[1,15],height:[-1,1]},$t=["fov","distance","height"],Ut=["fov","distance","height","intro"];function et(t){if(t===null||typeof t!="object"||Array.isArray(t))return{ok:!1,error:"camera must be an object"};let r=t;for(let s of Object.keys(r))if(!Ut.includes(s))return{ok:!1,error:`unknown camera key: ${s} (expected ${Ut.join(" | ")})`};let a={},i=[];for(let s of $t){let u=r[s];if(u===void 0)continue;if(u===null){a[s]=null;continue}if(typeof u!="number"||!Number.isFinite(u))return{ok:!1,error:`camera.${s} must be a finite number or null`};let[f,g]=Z[s],X=Math.min(g,Math.max(f,u));X!==u&&i.push(s),a[s]=X}if(r.intro!==void 0){if(r.intro!==null&&typeof r.intro!="boolean")return{ok:!1,error:"camera.intro must be a boolean or null"};a.intro=r.intro}return{ok:!0,camera:a,clamped:i}}function Cn(t){let r={},a=[],i={fov:"cameraFov",distance:"cameraDistance",height:"cameraHeight"};for(let u of $t){let f=t(i[u]);if(f===null)continue;let g=f.trim(),X=g===""?NaN:Number(g);if(!Number.isFinite(X)){a.push(`ignoring invalid ?${i[u]}=${f}`);continue}let[S,y]=Z[u],z=Math.min(y,Math.max(S,X));z!==X&&a.push(`?${i[u]}=${f} is out of range [${S}, ${y}], clamped to ${z}`),r[u]=z}let s=t("cameraIntro");if(s!==null){let u=s.trim().toLowerCase();u==="1"||u==="true"?r.intro=!0:u==="0"||u==="false"?r.intro=!1:a.push(`ignoring invalid ?cameraIntro=${s}`)}return{camera:r,warnings:a}}var Nt=/^[a-z][a-z0-9_]{0,63}$/,T=t=>typeof t=="string"&&Nt.test(t),kn=(t,r)=>Object.prototype.hasOwnProperty.call(t,r),Mn=["zh-CN","en","ja"];function N(t,r,a){let i={type:t,v:1,payload:r};return a!==void 0&&(i.id=a),i}function Ee(t){if(!t||typeof t!="object")return!1;let r=t;return typeof r.type=="string"&&r.type.startsWith("xc.")&&r.v===1}function Se(t){if(!t||t==="*"||t==="null")return null;try{let r=new URL(t);return r.protocol!=="https:"&&r.protocol!=="http:"?null:r.origin}catch{return null}}var Me=Object.freeze({minWidth:120,minHeight:180,maxWidth:1/0,maxHeight:1/0}),Ce=t=>typeof t=="number"&&Number.isFinite(t)&&t>0;function tt(t){if(!t)return null;let r=t===!0?{}:t,a=Ce(r.minWidth)?r.minWidth:Me.minWidth,i=Ce(r.minHeight)?r.minHeight:Me.minHeight,s=Ce(r.maxWidth)?Math.max(r.maxWidth,a):1/0,u=Ce(r.maxHeight)?Math.max(r.maxHeight,i):1/0;return{minWidth:a,minHeight:i,maxWidth:s,maxHeight:u}}var ae=(t,r,a)=>Math.min(Math.max(t,r),Math.max(r,a));function Wt(t,r,a,i){return{left:ae(t.left+r,0,i.width-t.width),top:ae(t.top+a,0,i.height-t.height),width:t.width,height:t.height}}function Ft(t,r,a,i,s,u){let f=r==="NW"||r==="SW",g=r==="NW"||r==="NE",X=t.left+t.width,S=t.top+t.height,y=f?t.width-a:t.width+a,z=g?t.height-i:t.height+i,q=f?X:u.width-t.left,M=g?S:u.height-t.top,Ie=ae(y,s.minWidth,Math.min(s.maxWidth,q)),se=ae(z,s.minHeight,Math.min(s.maxHeight,M));return{left:f?X-Ie:t.left,top:g?S-se:t.top,width:Ie,height:se}}function Re(t,r){let a=Math.min(t.width,Math.max(1,r.width)),i=Math.min(t.height,Math.max(1,r.height));return{left:ae(t.left,0,r.width-a),top:ae(t.top,0,r.height-i),width:a,height:i}}var Rn=new Set(["NW","NE","SW","SE"]),On=new Set(["start","move","end"]),Ln=new Set(["up","cancel","blur"]),zn=2e4,ke=t=>typeof t=="number"&&Number.isFinite(t)&&Math.abs(t)<=zn,jt=t=>typeof t=="number"&&Number.isSafeInteger(t)&&t>=0;function Gt(t,r){if(r===null||typeof r!="object")return null;let a=r;if(!jt(a.gesture)||!jt(a.seq)||typeof a.phase!="string"||!On.has(a.phase)||!ke(a.dx)||!ke(a.dy)||!ke(a.totalDx)||!ke(a.totalDy)||a.reason!==void 0&&(typeof a.reason!="string"||!Ln.has(a.reason)))return null;let i={gesture:a.gesture,seq:a.seq,phase:a.phase,totalDx:a.totalDx,totalDy:a.totalDy};if(t==="resize"){if(typeof a.corner!="string"||!Rn.has(a.corner))return null;i.corner=a.corner}return i}var me=class{constructor(){this.lastGesture=0;this.lastSeq=-1;this.open=!1}get active(){return this.open}accept(r){return r.phase==="start"?r.gesture<=this.lastGesture||r.seq!==0?!1:(this.lastGesture=r.gesture,this.lastSeq=0,this.open=!0,!0):!this.open||r.gesture!==this.lastGesture||r.seq<=this.lastSeq?!1:(this.lastSeq=r.seq,r.phase==="end"&&(this.open=!1),!0)}close(){this.open=!1}};var In="data:image/svg+xml;utf8,"+encodeURIComponent('<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 120 180"><defs><linearGradient id="g" x1="0" y1="0" x2="0" y2="1"><stop offset="0" stop-color="#f6b8ae"/><stop offset="1" stop-color="#ea8377"/></linearGradient></defs><ellipse cx="60" cy="170" rx="34" ry="6" fill="#000" opacity=".12"/><circle cx="60" cy="48" r="26" fill="url(#g)" opacity=".75"/><path d="M26 160c2-40 18-62 34-62s32 22 34 62z" fill="url(#g)" opacity=".6"/></svg>'),nt=t=>{t.setProperty("user-select","none"),t.setProperty("-webkit-user-select","none"),t.setProperty("-webkit-touch-callout","none"),t.setProperty("-webkit-tap-highlight-color","transparent")},Q=(t,r)=>t===void 0?r:typeof t=="number"?`${t}px`:t,it=600,at=1080,rt=(t=!1)=>t?`min(${it}px, calc(100vw - 2 * var(--xc-offset-x, 16px)))`:`min(${it}px, 100vw)`,ot=(t=!1)=>{let r=typeof CSS<"u"&&typeof CSS.supports=="function"&&CSS.supports("height","1svh")?"svh":"vh";return t?`min(${at}px, calc(100${r} - 2 * var(--xc-offset-y, 16px)))`:`min(${at}px, 100${r})`};function Oe(t){if(typeof window>"u"||typeof document>"u")throw new Error("[project-xiaochun] createXiaochun must run in a browser");let r=typeof t.container=="string"?document.querySelector(t.container):t.container;if(!r)throw new Error(`[project-xiaochun] container not found: ${String(t.container)}`);let a=t.src??Ve,i;try{i=new URL(a,window.location.href)}catch{throw new Error(`[project-xiaochun] invalid src: ${a}`)}let s=Se(t.origin??i.origin);if(!s)throw new Error("[project-xiaochun] invalid origin (wildcards are not allowed)");let u=new Set([s]);for(let e of t.allowedOrigins??[]){let n=Se(e);if(!n)throw new Error(`[project-xiaochun] invalid allowedOrigins entry: ${e} (wildcards are not allowed)`);u.add(n)}let f=t.persist==="host"?"xiaochun:prefs":typeof t.persist=="string"&&t.persist?t.persist:null,g=()=>{if(!f)return{};try{let e=JSON.parse(window.localStorage.getItem(f)??"null"),n={};return e&&typeof e=="object"&&(T(e.outfit)&&(n.outfit=e.outfit),T(e.scene)&&(n.scene=e.scene)),n}catch{return{}}},X=e=>{if(f)try{let n={...g()};for(let[o,c]of Object.entries(e))c?n[o]=c:delete n[o];window.localStorage.setItem(f,JSON.stringify(n))}catch{}},S=g();t.model!==void 0&&t.outfit===void 0&&console.warn('[project-xiaochun] option "model" is deprecated, use "outfit" (built-in outfit id).');let y=Qe(t.ui),z=y.parts,q=he(t.uiAutoHide);t.uiAutoHide!==void 0&&q===void 0&&console.warn(`[project-xiaochun] ignoring invalid uiAutoHide: ${String(t.uiAutoHide)} (use true | false | 'transparent')`);let M={};if(t.camera!==void 0){let e=et(t.camera);e.ok?(M=e.camera,e.clamped.length&&console.warn(`[project-xiaochun] camera.${e.clamped.join(", camera.")} out of range, clamped (fov ${Z.fov.join("\u2013")}, distance ${Z.distance.join("\u2013")}, height ${Z.height.join("\u2013")})`)):console.warn(`[project-xiaochun] ignoring invalid camera option: ${e.error}`)}y.legacy&&console.warn(`[project-xiaochun] option "ui: true" is deprecated, use an array of parts, e.g. ui: ['chat', 'bubble', 'outfit', 'scene'].`),y.unknown.length&&console.warn(`[project-xiaochun] ignoring unknown ui part(s): ${y.unknown.join(", ")} (known: ${pe.join(", ")})`);let se=t.outfit??(T(t.model)?t.model:void 0)??S.outfit,K=t.scene??S.scene??(t.transparent?"transparent":void 0),ee=K==="transparent"||K!=="light"&&K!=="dark"&&K!=="beach3d"&&(t.transparent??!1),te=t.passthrough??ee,He=t.lazy??!0,x=t.position??"inline",ut=t.handshakeTimeout??2e4,I=document.createElement("div");I.setAttribute("data-xiaochun","");let l=I.style;l.position=x==="inline"?"relative":"fixed",l.width=Q(t.width,rt(x!=="inline")),l.height=Q(t.height,ot(x!=="inline")),l.maxWidth="100%",l.overflow="visible",l.contain="layout style",nt(l),l.boxShadow="var(--xc-shadow, none)";let lt=()=>{l.background=ee?"":"var(--xc-bg, transparent)"};lt();let _e=t.borderRadius,ge=()=>_e!==void 0?Q(_e,"0px"):ee?"0px":`${Ye}px`,dt=()=>{let e=`var(--xc-radius, ${ge()})`;l.borderRadius=e,R&&(R.style.borderRadius=e),m&&(m.style.borderRadius=e)};l.borderRadius=`var(--xc-radius, ${ge()})`,x==="bottom-right"&&(l.right="var(--xc-offset-x, 16px)",l.bottom="var(--xc-offset-y, 16px)"),x==="bottom-left"&&(l.left="var(--xc-offset-x, 16px)",l.bottom="var(--xc-offset-y, 16px)"),x!=="inline"&&(l.zIndex=`var(--xc-z-index, ${t.zIndex??2147483e3})`),l.pointerEvents="none",I.setAttribute("part","wrapper"),r.appendChild(I);let R=null;if(t.placeholder!==!1){if(t.placeholder instanceof HTMLElement)R=t.placeholder;else{let n=document.createElement("img");n.src=t.placeholder||In,n.alt="Project XiaoChun",n.decoding="async",n.width=it,n.height=at,R=n}let e=R.style;R.setAttribute("part","placeholder"),e.borderRadius=`var(--xc-radius, ${ge()})`,e.position="absolute",e.inset="0",e.width="100%",e.height="100%",e.objectFit="contain",e.transition="opacity .25s ease",e.pointerEvents="auto",e.cursor=He===!1?"default":"pointer",nt(e),R.addEventListener("click",()=>$()),I.appendChild(R)}let ye=new Map,b=(e,n)=>{ye.get(e)?.forEach(o=>{try{o(n)}catch(c){console.error("[project-xiaochun] listener error",c)}})},ft,pt,ht=new Promise((e,n)=>{ft=e,pt=n});ht.catch(()=>{});let m=null,w=null,v=!1,Te=!1,mt=!1,Ue=!1,ce=!1,P=null,gt=null,yt=null,Be=[],H=new Map,$e=0,ne=null,V=null,re=null,Ne,xt=new Promise(e=>{Ne=e}),Zt=(e,n,o,c)=>{b("error",{code:o,message:c,command:e});let p=n?H.get(n):void 0;p&&n&&(H.delete(n),p.reject(new Error(`[${o}] ${c}`)))},bt=(e,n)=>Zt(e,n,"unsupported",`${e} is not supported by this /embed deployment (older version; its xc.ready has no capabilities for it)`),Y=(e,n,o,c,p)=>{if(!w){Be.push({type:e,payload:n,id:o,transfer:c,requires:p});return}if(p&&!P?.[p]){bt(e,o);return}w.postMessage(N(e,n,o),c??[])},C=(e,n,o=!1,c,p,d)=>{if(v)return Promise.reject(new Error("[project-xiaochun] instance destroyed"));m||$();let h=p??`c${++$e}`,A=o?new Promise((L,k)=>H.set(h,{resolve:L,reject:k,sawEnd:!1})):Promise.resolve();return Y(e,n,h,c,d),A},Xt=e=>e instanceof ArrayBuffer?e:e.buffer.slice(e.byteOffset,e.byteOffset+e.byteLength),wt=(e,n)=>{if(!e)return;let o=()=>{v||Y("xc.audio.end",{abort:!0},n)};e.aborted?o():e.addEventListener("abort",o,{once:!0})},Qt=async(e,n={})=>{if(v)throw new Error("[project-xiaochun] instance destroyed");m||$();let{signal:o,transfer:c,fetch:p,...d}=n,h={...d},A=[];if(typeof e=="string")if(p==="frame")h.source=e;else{let E=await fetch(e);if(!E.ok)throw new Error(`[project-xiaochun] audio fetch failed: HTTP ${E.status}`);let J=await E.arrayBuffer();h.source=J,A.push(J),h.mimeType??(h.mimeType=E.headers.get("content-type")??void 0)}else if(typeof Blob<"u"&&e instanceof Blob)h.source=e,h.mimeType??(h.mimeType=e.type||void 0);else{let E=Xt(e);h.source=E,(!(e instanceof ArrayBuffer)||c!==!1)&&A.push(E)}if(v)throw new Error("[project-xiaochun] instance destroyed");let L=`c${++$e}`,k=C("xc.audio",h,!0,A,L);return wt(o,L),k},en=e=>{if(v)throw new Error("[project-xiaochun] instance destroyed");let{signal:n,transfer:o,fetch:c,mimeType:p,...d}=e,h=`c${++$e}`,A=!1,L=!1,k=d.format==="pcm16"||d.format==="float32"?d.format:null,E=Promise.resolve();return{write(Ae){if(L)throw new Error("[project-xiaochun] audio stream already ended");if(v)throw new Error("[project-xiaochun] instance destroyed");if(Ae instanceof Int16Array?k??(k="pcm16"):Ae instanceof Float32Array&&(k??(k="float32")),!k)throw new Error("[project-xiaochun] speakAudioStream: set opts.format when writing raw ArrayBuffers");let qe=Xt(Ae),D={data:qe,format:k,sampleRate:d.sampleRate,channels:d.channels};A?Y("xc.audio.chunk",D,h,!(Ae instanceof ArrayBuffer)||o!==!1?[qe]:[]):(A=!0,D.text=d.text,D.motion=d.motion,D.lipsync=d.lipsync,D.audible=d.audible,D.playbackRate=d.playbackRate,D.volume=d.volume,E=C("xc.audio.chunk",D,!0,[qe],h),wt(n,h))},end(){L||(L=!0,A&&Y("xc.audio.end",{},h))},abort(){L&&!A||(L=!0,A&&Y("xc.audio.end",{abort:!0},h))},get done(){return E}}};function tn(){let e=new URL(i.href);return e.searchParams.set("host",window.location.origin),ee&&e.searchParams.set("transparent","1"),z.length&&e.searchParams.set("ui",z.join(",")),t.lang&&e.searchParams.set("lang",t.lang),q!==void 0&&e.searchParams.set("uiAutoHide",String(q)),typeof M.fov=="number"&&e.searchParams.set("cameraFov",String(M.fov)),typeof M.distance=="number"&&e.searchParams.set("cameraDistance",String(M.distance)),typeof M.height=="number"&&e.searchParams.set("cameraHeight",String(M.height)),typeof M.intro=="boolean"&&e.searchParams.set("cameraIntro",M.intro?"1":"0"),t.heavy&&e.searchParams.set("heavy",t.heavy),t.controls===!1&&e.searchParams.set("controls","0"),K&&T(K)&&e.searchParams.set("scene",K),se&&e.searchParams.set("outfit",se),e.href}function $(){if(v||m)return;kt(),V?.disconnect(),V=null;let e=document.createElement("iframe");e.title="Project XiaoChun",e.loading="lazy",e.allow=t.crossOriginIsolated===!0?"microphone; autoplay; cross-origin-isolated":"microphone; autoplay",e.referrerPolicy="strict-origin-when-cross-origin",t.sandbox!==!1&&e.setAttribute("sandbox",t.sandbox??"allow-scripts allow-same-origin allow-popups allow-popups-to-escape-sandbox"),e.setAttribute("allowtransparency","true"),e.setAttribute("scrolling","no");let n=e.style;n.position="absolute",n.inset="0",n.width="100%",n.height="100%",n.border="0",n.background="transparent",n.colorScheme="normal",n.borderRadius=`var(--xc-radius, ${ge()})`,e.setAttribute("part","iframe"),nt(n),n.opacity="0",n.transition="opacity .25s ease",n.pointerEvents=te?"none":"auto",e.src=tn(),m=e,I.appendChild(e),R&&(R.style.cursor="default"),ne=setTimeout(()=>{w||b("error",{code:"timeout",message:`no xc.ready from ${s} within ${ut}ms`})},ut),sn(),te&&Et()}let vt=e=>{if(v||!m||e.source!==m.contentWindow)return;if(!u.has(e.origin)){b("error",{code:"origin_denied",message:`ignored message from untrusted origin ${e.origin}`});return}let n=e.data;if(!Ee(n)||n.type!=="xc.ready"||w)return;let o=new MessageChannel;w=o.port1,w.onmessage=nn,P=n.payload?.capabilities??null;let c=Ot();fe=c;let p={...t.allowCustomModel?{allowCustomModel:!0}:{},...c.move||c.resize?{gestures:c}:{}};m.contentWindow.postMessage(N("xc.init",{hostOrigin:window.location.origin,...Object.keys(p).length?{config:p}:{}}),e.origin,[o.port2]),It(),ne&&(clearTimeout(ne),ne=null),b("handshake",n.payload),Ne();for(let d of Be.splice(0))d.requires&&!P?.[d.requires]?bt(d.type,d.id):w.postMessage(N(d.type,d.payload,d.id),d.transfer??[]);we()};window.addEventListener("message",vt);function je(e,n){let o=e?H.get(e):void 0;o&&e&&(H.delete(e),o.resolve(n))}function nn(e){let n=e.data;if(Ee(n))switch(n.type){case"xc.load.progress":b("progress",n.payload);break;case"xc.loaded":if(!Ue){if(Ue=!0,t.prefetch&&t.heavy==="eager"&&P?.prefetch){let o=Array.isArray(t.prefetch)?t.prefetch:void 0;Tt.prefetch(o).catch(()=>{})}if(m&&(m.style.opacity="1"),R){let o=R;o.style.opacity="0",o.style.pointerEvents="none",setTimeout(()=>o.remove(),300),R=null}ft()}b("ready",n.payload);break;case"xc.outfit-changed":{let o=n.payload;o.noop||(gt=o.id,b("outfit-changed",o),!o.initial&&o.id&&X({outfit:o.id})),je(n.id);break}case"xc.scene-changed":{let o=n.payload;yt=o.id,o.transparent!==ee&&an(o.transparent),o.noop||(b("scene-changed",o),o.initial||X({scene:o.id})),je(n.id);break}case"xc.lang-changed":b("lang-changed",n.payload);break;case"xc.prefetched":je(n.id,n.payload);break;case"xc.state":b("state",n.payload);break;case"xc.stt":b("stt",n.payload);break;case"xc.utterance":{b("utterance",n.payload);let o=n.id?H.get(n.id):void 0;o&&n.payload.phase==="end"&&(H.delete(n.id),o.resolve());break}case"xc.hit-region":{let{hit:o}=n.payload;b("hit-region",n.payload),te&&m&&o!==ce&&(ce=o,m.style.pointerEvents=o?"auto":"none");break}case"xc.gesture-move":Lt("move",n.payload);break;case"xc.gesture-resize":Lt("resize",n.payload);break;case"xc.error":{let{code:o,message:c,command:p}=n.payload;b("error",{code:o,message:c,command:p}),o==="unknown_id"&&(p==="outfit"||p==="scene")&&X({[p]:null});let d=n.id?H.get(n.id):void 0;d&&n.id&&(H.delete(n.id),d.reject(new Error(`[${o}] ${c}`)));break}default:break}}let rn=32,Pt=2,j=0,ue=null,W=null,le=null,xe=null,At=0,F=()=>{le=null},on=()=>{if(!m)return null;let e=performance.now();return(!le||e-At>400)&&(le=m.getBoundingClientRect(),At=e),le},be=e=>{!m||!w||m.style.pointerEvents==="auto"||(ue={x:e.clientX,y:e.clientY},!j&&(j=requestAnimationFrame(()=>{if(j=0,!m||!w||!ue)return;let n=on();if(!n)return;let o=ue.x-n.left,c=ue.y-n.top;if(o<0||c<0||o>n.width||c>n.height){W=null,ce&&(ce=!1,m.style.pointerEvents="none");return}let p=performance.now();W&&p-W.t<rn||W&&Math.abs(o-W.x)<Pt&&Math.abs(c-W.y)<Pt||(W={x:o,y:c,t:p},w.postMessage(N("xc.pointer",{x:o,y:c})))})))},Xe=!1;function Et(){Xe||!m||(Xe=!0,window.addEventListener("pointermove",be,{passive:!0}),window.addEventListener("pointerdown",be,{passive:!0}),window.addEventListener("scroll",F,{passive:!0,capture:!0}),window.addEventListener("resize",F,{passive:!0}),typeof ResizeObserver<"u"&&(xe=new ResizeObserver(F),xe.observe(m)))}function St(){Xe&&(Xe=!1,window.removeEventListener("pointermove",be),window.removeEventListener("pointerdown",be),window.removeEventListener("scroll",F,!0),window.removeEventListener("resize",F),xe?.disconnect(),xe=null,j&&(cancelAnimationFrame(j),j=0),ue=null)}function an(e){ee=e,lt(),dt(),te=e?t.passthrough??!0:!1,ce=!1,W=null,le=null,te?Et():St(),m&&(m.style.pointerEvents=te?"none":"auto")}let We=null;function sn(){t.autoPause===!1||typeof IntersectionObserver>"u"||(We=new IntersectionObserver(e=>{mt=!(e[e.length-1]?.isIntersecting??!0),we()}),We.observe(I))}let Ct=!1;function we(){if(!w)return;let e=Te||mt;e!==Ct&&(Ct=e,w.postMessage(N(e?"xc.pause":"xc.resume")))}function kt(){if(re===null)return;let e=window;e.cancelIdleCallback?e.cancelIdleCallback(re):clearTimeout(re),re=null}function cn(){if(He===!1){$();return}if(He==="click")return;let e=()=>{let n=window;re=n.requestIdleCallback?n.requestIdleCallback(()=>{re=null,$()},{timeout:3e3}):setTimeout($,1200)};if(typeof IntersectionObserver>"u"){e();return}V=new IntersectionObserver(n=>{n.some(o=>o.isIntersecting)&&(V?.disconnect(),V=null,e())},{rootMargin:`${t.lazyMargin??200}px`}),V.observe(I)}let de=t.draggable===!0,B=tt(t.resizable),Mt={move:new me,resize:new me},_=null,O={x:0,y:0},Fe=!1,fe=null,Rt=!1,Ge=()=>({width:document.documentElement.clientWidth||window.innerWidth,height:document.documentElement.clientHeight||window.innerHeight}),oe=()=>{let e=I.getBoundingClientRect();return{left:e.left,top:e.top,width:e.width,height:e.height}},Ot=()=>({move:de&&P?.gestures?.move===!0,resize:B!==null&&P?.gestures?.resize===!0});function ve(e,n,o){if(o&&(l.width=`${e.width}px`,l.height=`${e.height}px`,l.maxWidth="none"),x==="inline"){let c=n??{left:e.left-O.x,top:e.top-O.y};O={x:e.left-c.left,y:e.top-c.top},l.setProperty("translate",`${O.x}px ${O.y}px`)}else l.left=`${e.left}px`,l.top=`${e.top}px`,l.right="auto",l.bottom="auto";Fe=!0,F()}let ie=null;function Pe(e){let n=document.documentElement;if(e&&!ie){ie={us:n.style.getPropertyValue("user-select"),wus:n.style.getPropertyValue("-webkit-user-select")},n.style.setProperty("user-select","none"),n.style.setProperty("-webkit-user-select","none");try{window.getSelection()?.removeAllRanges()}catch{}}else!e&&ie&&(n.style.setProperty("user-select",ie.us),n.style.setProperty("-webkit-user-select",ie.wus),ie=null)}function De(e){if(!_||e&&_.kind!==e)return;Mt[_.kind].close();let n=oe();b(_.kind,{phase:"end",...n}),_=null,Pe(!1),_t()}function Lt(e,n){if(v||!P?.gestures||(e==="move"?!de:B===null))return;let o=Gt(e,n);if(!o||(o.phase==="start"?_!==null:_?.kind!==e)||!Mt[e].accept(o))return;if(o.phase==="start"){let h=oe();_={kind:e,start:h,corner:o.corner,inlineBase:x==="inline"?{left:h.left-O.x,top:h.top-O.y}:null},Pe(!0),b(e,{phase:"start",...h});return}let c=_,p=Ge(),d=e==="move"?Wt(c.start,o.totalDx,o.totalDy,p):Ft(c.start,c.corner,o.totalDx,o.totalDy,B,p);ve(d,c.inlineBase,e==="resize"),b(e,{phase:o.phase,...d}),o.phase==="end"&&(_=null,Pe(!1),_t())}function zt(){if(v)return;let e=Ot();e.move||De("move"),e.resize||De("resize"),!(!w||!P)&&(It(),!(fe&&fe.move===e.move&&fe.resize===e.resize)&&(fe=e,P.gestures&&w.postMessage(N("xc.setConfig",{gestures:e}))))}function It(){if(Rt||!P||P.gestures)return;let e=de;if(!e&&B===null)return;Rt=!0;let n=[e?"draggable":"",B!==null?"resizable":""].filter(Boolean).join(" / ");b("error",{code:"unsupported",message:`${n} needs gesture support (capabilities.gestures), which this /embed deployment does not advertise (older version)`,command:"gestures"})}let Ht=()=>{if(!Fe||_||v)return;let e=oe(),n=Ge(),o=x==="inline"?{...Re({...e,top:0},{width:n.width,height:Number.MAX_SAFE_INTEGER}),top:Math.max(e.top,-window.scrollY)}:Re(e,n);o.left===e.left&&o.top===e.top&&o.width===e.width&&o.height===e.height||ve(o,x==="inline"?{left:e.left-O.x,top:e.top-O.y}:null,o.width!==e.width||o.height!==e.height)};window.addEventListener("resize",Ht,{passive:!0});let G=t.persistBox===!0?"xiaochun:box":typeof t.persistBox=="string"&&t.persistBox?`xiaochun:box:${t.persistBox}`:null,_t=()=>{if(G)try{let e=oe(),n=x==="inline"?O:{x:e.left,y:e.top};window.localStorage.setItem(G,JSON.stringify({v:1,mode:x,x:Math.round(n.x),y:Math.round(n.y),width:Math.round(e.width),height:Math.round(e.height)}))}catch{}},un=()=>{if(!G)return null;try{let e=window.localStorage.getItem(G);if(e===null)return null;let n=null;try{n=JSON.parse(e)}catch{}let o=(c,p,d)=>typeof c=="number"&&Number.isFinite(c)&&c>=p&&c<=d;if(n&&n.v===1&&n.mode===x&&o(n.x,-1e5,1e5)&&o(n.y,-1e5,1e5)&&o(n.width,1,1e5)&&o(n.height,1,1e5))return{x:n.x,y:n.y,width:n.width,height:n.height};window.localStorage.removeItem(G)}catch{}return null};function ln(){if(!G||!de&&B===null)return;let e=un();if(!e)return;let n=Ge(),o=B??Me,c=oe(),p=B!==null&&t.width===void 0,d=B!==null&&t.height===void 0,h=(k,E,J)=>Math.min(Math.max(k,E),Math.max(E,J)),A=p?h(e.width,o.minWidth,Math.min(o.maxWidth,n.width)):c.width,L=d?h(e.height,o.minHeight,Math.min(o.maxHeight,n.height)):c.height;if(x==="inline"){let k={left:c.left-O.x,top:c.top-O.y},E=h(k.left+e.x,0,n.width-A),J=Math.max(k.top+e.y,-window.scrollY);ve({left:E,top:J,width:A,height:L},k,p||d)}else ve(Re({left:e.x,top:e.y,width:A,height:L},n),null,p||d)}ln(),cn();let Tt={element:I,get iframe(){return m},ready:ht,activate:$,say:(e,n)=>C("xc.say",{text:e,mode:n?.mode},!0),speakAudio:Qt,speakAudioStream:en,motion:e=>C("xc.motion",typeof e=="string"?e.startsWith("http")||e.startsWith("/")?{url:e}:{name:e}:e),expression:e=>C("xc.expression",{name:e}),lookAt:(e,n)=>C("xc.lookAt",{x:e,y:n}),setOutfit:e=>T(e)?C("xc.setOutfit",{id:e},!0,void 0,void 0,"outfits"):Promise.reject(new Error("[bad_request] invalid outfit id")),setScene:e=>T(e)?C("xc.setScene",{id:e},!0,void 0,void 0,"scenes"):Promise.reject(new Error("[bad_request] invalid scene id")),prefetch:e=>e!==void 0&&(!Array.isArray(e)||e.some(n=>!T(n)))?Promise.reject(new Error("[bad_request] prefetch ids must be an array of outfit ids")):C("xc.prefetch",e?{ids:e}:{},!0,void 0,void 0,"prefetch"),getOutfits:async()=>(m||$(),await xt,P?.outfits?P.outfits.slice():[]),getScenes:async()=>(m||$(),await xt,P?.scenes?P.scenes.slice():[]),get outfit(){return gt},get scene(){return yt},setModel:e=>{let n=typeof e=="string"?/^(https?:)?\/|\.vrm/i.test(e)?{url:e}:{outfit:e}:e;if(n.url!==void 0&&n.outfit===void 0&&!t.allowCustomModel){let o="custom model URLs are disabled; pass allowCustomModel: true to createXiaochun() (only for URLs you trust) or use setOutfit() with a built-in id";return b("error",{code:"unsupported",message:o,command:"xc.setModel"}),Promise.reject(new Error(`[unsupported] ${o}`))}return C("xc.setModel",n)},setConfig:e=>C("xc.setConfig",e),setSize(e,n){v||(l.width=Q(e,rt(x!=="inline")),l.height=Q(n,ot(x!=="inline")),l.maxWidth==="none"&&(l.maxWidth="100%"),F())},getBox:()=>oe(),clearPersistedBox(e){if(G)try{window.localStorage.removeItem(G)}catch{}v||e?.reset!==!0||(De(),l.width=Q(t.width,rt(x!=="inline")),l.height=Q(t.height,ot(x!=="inline")),l.maxWidth="100%",x==="inline"?(O={x:0,y:0},l.removeProperty("translate")):(l.left="",l.top="",l.right="",l.bottom="",x==="bottom-right"&&(l.right="var(--xc-offset-x, 16px)",l.bottom="var(--xc-offset-y, 16px)"),x==="bottom-left"&&(l.left="var(--xc-offset-x, 16px)",l.bottom="var(--xc-offset-y, 16px)")),Fe=!1,F())},setBorderRadius(e){_e=e,dt()},setDraggable(e){de=e===!0,zt()},setResizable(e){B=tt(e),zt()},startListening:()=>C("xc.mic",{enabled:!0}),stopListening:()=>C("xc.mic",{enabled:!1}),mic:e=>C("xc.mic",{enabled:e}),pause(){Te=!0,we()},resume(){Te=!1,we()},setPlaybackRate(e){v||typeof e!="number"||!Number.isFinite(e)||Y("xc.transport",{playbackRate:e})},setVolume(e){v||typeof e!="number"||!Number.isFinite(e)||Y("xc.transport",{volume:e})},destroy(){if(!v){try{w?.postMessage(N("xc.destroy"))}catch{}v=!0,kt(),V?.disconnect(),We?.disconnect(),ne&&clearTimeout(ne),j&&cancelAnimationFrame(j),window.removeEventListener("message",vt),window.removeEventListener("resize",Ht),Pe(!1),St(),Ne();try{w?.close()}catch{}w=null;for(let e of H.values())e.reject(new Error("[project-xiaochun] instance destroyed"));H.clear(),Be.length=0,Ue||pt(new Error("[project-xiaochun] destroyed before ready")),I.remove(),m=null,b("destroy",void 0),ye.clear()}},on(e,n){let o=ye.get(e);return o||(o=new Set,ye.set(e,o)),o.add(n),()=>{o.delete(n)}}};return Tt}var Hn=["src","outfit","scene","model","lang","mic","transparent","draggable","resizable","min-size","max-size","border-radius","position","size","lazy","paused","placeholder","heavy","ui","ui-autohide","camera-fov","camera-distance","camera-height","camera-intro","controls","allowed-origins","cross-origin-isolated","persist","persist-box","allow-custom-model","prefetch"],_n=new Set(["src","position","lazy","placeholder","heavy","ui","ui-autohide","controls","allowed-origins","transparent","cross-origin-isolated","persist","persist-box","allow-custom-model","prefetch"]);function Dt(t){if(t===null||t.trim()==="")return;let r=t.trim();return/^\d+(\.\d+)?$/.test(r)?Number(r):r}function U(t,r,a){let i=t.getAttribute(r);return i===null?a:i!=="false"}function Tn(t){return t===null||t==="false"?!1:t===""||t==="true"?!0:t.split(",").map(r=>r.trim()).filter(Boolean)}function Un(t){if(!(t===null||t==="false"||t==="0"))return t===""||t==="true"||t==="1"?!0:t}function Bn(t){if(!(t===null||t==="false"||t==="0"))return t===""||t==="true"||t==="1"?!0:t.split(",").map(r=>r.trim()).filter(Boolean)}function qt(t){let r=i=>{let s=t.getAttribute(i);if(s===null||s.trim()==="")return null;let u=Number(s);return Number.isFinite(u)?u:null},a=t.getAttribute("camera-intro");return{fov:r("camera-fov"),distance:r("camera-distance"),height:r("camera-height"),intro:a===null?null:a!=="false"&&a!=="0"}}function Kt(t){let r=t?.trim().match(/^(\d+(?:\.\d+)?)\s*x\s*(\d+(?:\.\d+)?)$/i);return r?{w:Number(r[1]),h:Number(r[2])}:void 0}function Vt(t){if(!t)return{width:void 0,height:void 0};let r=t.trim().split(/x/i),a=s=>/^\d+(\.\d+)?$/.test(s)?`${s}px`:s;if(r.length>=2)return{width:a(r[0]),height:a(r[1])};let i=parseFloat(r[0]);return Number.isFinite(i)&&/^\d+(\.\d+)?$/.test(r[0])?{width:`${i}px`,height:`${Math.round(i*1.5)}px`}:{width:r[0],height:void 0}}function $n(){class t extends HTMLElement{constructor(){super(...arguments);this.client=null;this.mountEl=null;this.rebuildScheduled=!1}static get observedAttributes(){return[...Hn]}connectedCallback(){if(!this.shadowRoot){let i=this.attachShadow({mode:"open"});i.innerHTML='<style>:host{display:inline-block;max-width:100%}:host([hidden]){display:none}</style><div part="mount"></div>'}this.mountEl=this.shadowRoot.querySelector("div"),this.build()}disconnectedCallback(){this.destroy()}attributeChangedCallback(i,s,u){if(!this.client||s===u)return;if(_n.has(i)){this.rebuildScheduled||(this.rebuildScheduled=!0,queueMicrotask(()=>{this.rebuildScheduled=!1,this.isConnected&&(this.destroy(),this.build())}));return}let f=this.client;if((i==="outfit"||i==="model")&&u){let g=i==="model"&&this.hasAttribute("outfit")?null:u;g&&(T(g)?f.setOutfit(g):f.setModel(g)).catch(()=>{})}else if(i==="scene"&&u)f.setScene(u).catch(()=>{});else if(i==="lang"&&u)f.setConfig({lang:u}).catch(()=>{});else if(i==="size"){let{width:g,height:X}=Vt(u);f.setSize(g,X)}else i==="border-radius"?f.setBorderRadius(Dt(u)):i==="draggable"?f.setDraggable(U(this,"draggable",!1)):i==="resizable"||i==="min-size"||i==="max-size"?f.setResizable(this.resizableOption()):i.startsWith("camera-")?f.setConfig({camera:qt(this)}).catch(()=>{}):i==="mic"?f.mic(U(this,"mic",!1)).catch(()=>{}):i==="paused"&&(U(this,"paused",!1)?f.pause():f.resume())}build(){if(!this.mountEl||this.client)return;let{width:i,height:s}=Vt(this.getAttribute("size")),u=this.getAttribute("placeholder"),f=this.getAttribute("allowed-origins"),g=this.getAttribute("lazy"),X=g==="click"?"click":g!=="false",S=Oe({container:this.mountEl,src:this.getAttribute("src")||void 0,allowedOrigins:f?f.split(",").map(z=>z.trim()).filter(Boolean):void 0,lazy:X,placeholder:u==="none"?!1:u||void 0,transparent:U(this,"transparent",!0),width:i,height:s,position:this.getAttribute("position")??"inline",draggable:U(this,"draggable",!1),resizable:this.resizableOption(),borderRadius:Dt(this.getAttribute("border-radius")),lang:this.getAttribute("lang")??void 0,outfit:this.getAttribute("outfit")??this.getAttribute("model")??void 0,scene:this.getAttribute("scene")??void 0,persist:this.getAttribute("persist")||void 0,persistBox:Un(this.getAttribute("persist-box")),allowCustomModel:U(this,"allow-custom-model",!1),prefetch:Tn(this.getAttribute("prefetch")),heavy:this.getAttribute("heavy")??void 0,ui:Bn(this.getAttribute("ui")),uiAutoHide:he(this.getAttribute("ui-autohide")),camera:qt(this),controls:U(this,"controls",!0),crossOriginIsolated:U(this,"cross-origin-isolated",!1)});this.client=S;let y=(z,q)=>S.on(z,M=>this.dispatchEvent(new CustomEvent(q,{detail:M,bubbles:!0,composed:!0})));y("ready","xc-ready"),y("progress","xc-progress"),y("state","xc-state"),y("stt","xc-stt"),y("utterance","xc-utterance"),y("error","xc-error"),y("outfit-changed","xc-outfit-changed"),y("scene-changed","xc-scene-changed"),y("lang-changed","xc-lang-changed"),y("move","xc-move"),y("resize","xc-resize"),U(this,"paused",!1)&&S.pause(),U(this,"mic",!1)&&S.ready.then(()=>S.mic(!0)).catch(()=>{})}resizableOption(){if(!U(this,"resizable",!1))return!1;let i=Kt(this.getAttribute("min-size")),s=Kt(this.getAttribute("max-size"));return{minWidth:i?.w,minHeight:i?.h,maxWidth:s?.w,maxHeight:s?.h}}say(i,s){return this.requireClient().say(i,s)}speakAudio(i,s){return this.requireClient().speakAudio(i,s)}speakAudioStream(i){return this.requireClient().speakAudioStream(i)}setPlaybackRate(i){this.client?.setPlaybackRate(i)}setVolume(i){this.client?.setVolume(i)}motion(i){return this.requireClient().motion(i)}expression(i){return this.requireClient().expression(i)}setOutfit(i){return this.requireClient().setOutfit(i)}setScene(i){return this.requireClient().setScene(i)}getOutfits(){return this.requireClient().getOutfits()}getScenes(){return this.requireClient().getScenes()}clearPersistedBox(i){this.client?.clearPersistedBox(i)}prefetch(i){return this.requireClient().prefetch(i)}destroy(){this.client?.destroy(),this.client=null}requireClient(){if(!this.client)throw new Error("<xiaochun-avatar> is not connected");return this.client}}return t}var st="xiaochun-avatar";function Le(t=st){if(typeof customElements>"u"||typeof HTMLElement>"u")return null;let r=customElements.get(t);if(r)return r;let a=$n();return customElements.define(t,a),a}var ze="xiaochun";function Yt(t){if(t.action!=="speak")throw new Error(`[project-xiaochun] unsupported action: ${String(t.action)}`);if(!t.text&&!t.audioUrl&&!t.file)throw new Error("[project-xiaochun] speak needs text, audioUrl or file");if(t.audioUrl&&!/^https?:\/\//i.test(t.audioUrl))throw new Error("[project-xiaochun] audioUrl must be http(s)");let r=new URLSearchParams;return t.text&&r.set("text",t.text),t.audioUrl&&r.set("audioUrl",t.audioUrl),t.file&&r.set("file",t.file),`${ze}://speak?${r.toString().replace(/\+/g,"%20")}`}function Jt(t){let r;try{r=new URL(t)}catch{return null}if(r.protocol!==`${ze}:`)return null;let a=r.hostname||r.pathname.replace(/^\/+/,"");if((a==="action"?r.searchParams.get("action"):a)!=="speak")return null;let s={action:"speak"},u=r.searchParams.get("text"),f=r.searchParams.get("audioUrl"),g=r.searchParams.get("file");return u&&(s.text=u),f&&(s.audioUrl=f),g&&(s.file=g),s.text||s.audioUrl||s.file?s:null}Le();var ct=document.currentScript;if(ct&&ct.hasAttribute("data-auto")){let t=()=>{let r=document.createElement("xiaochun-avatar");for(let a of Array.from(ct.attributes))a.name.startsWith("data-")&&a.name!=="data-auto"&&r.setAttribute(a.name.slice(5),a.value);r.hasAttribute("position")||r.setAttribute("position","bottom-right"),document.body.appendChild(r)};document.readyState==="loading"?document.addEventListener("DOMContentLoaded",t,{once:!0}):t()}return gn(Nn);})();
3
3
  //# sourceMappingURL=loader.global.js.map