@bdky/aaas-pilot-kit 1.0.3 → 1.0.4
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.cjs.js +3 -3
- package/dist/index.esm.js +1 -1
- package/dist/index.umd.js +3 -3
- package/dist/ky-aaas-pilot-kit.umd.js +3 -3
- package/package.json +1 -1
package/dist/index.esm.js
CHANGED
|
@@ -41,4 +41,4 @@ ${e2(r)}`;throw new ej(C.planning,i)}function e1(e,n){return void 0===n?`${ec(e)
|
|
|
41
41
|
- ${[...e.tags.keys()].map(e=>e.toString()).join("\n - ")}`;return`Binding constraints:
|
|
42
42
|
- service identifier: ${ec(e.serviceIdentifier)}
|
|
43
43
|
- name: ${null!=(r=null==(n=e.name)?void 0:n.toString())?r:"-"}${i}`}function e3(e,n,r){if(Array.isArray(e.bindings)&&1===e.bindings.length){let[i]=e.bindings;eY(i)&&function e(n,r,i){if(1!==n.redirections.length)eZ(n.redirections,r,n,i);else{let[o]=n.redirections;eY(o)&&e(o,r,i)}}(i,n,r)}else eZ(e.bindings,n,e,r)}function e6(e,n,r){if(r.kind===I.unmanaged)return;let i=eu.is(r.value)?r.value.unwrap():r.value,o=n.concat({name:r.name,serviceIdentifier:i,tags:r.tags}),s=new eJ(o.last),a=eQ(e,s),c=[],l={bindings:c,parent:e.node,serviceIdentifier:i};if(c.push(...e5(e,o,a,l)),r.kind===I.singleInjection){e3(l,r.optional,s);let[e]=c;l.bindings=e}return l}function e5(e,n,r,i){let o=eY(i)?i.binding.targetServiceIdentifier:i.serviceIdentifier;e.servicesBranch.push(o);let s=[];for(let o of r)switch(o.type){case ev.Instance:s.push(function(e,n,r,i){let o={binding:n,classMetadata:e.getClassMetadata(n.implementationType),constructorParams:[],parent:i,propertyParams:new Map};return e4({autobindOptions:e.autobindOptions,getBindings:e.getBindings,getClassMetadata:e.getClassMetadata,node:o,servicesBranch:e.servicesBranch,setBinding:e.setBinding},r)}(e,o,n,i));break;case ev.ResolvedValue:s.push(e4({autobindOptions:e.autobindOptions,getBindings:e.getBindings,getClassMetadata:e.getClassMetadata,node:{binding:o,params:[],parent:i},servicesBranch:e.servicesBranch,setBinding:e.setBinding},n));break;case ev.ServiceRedirection:{let r=function(e,n,r,i){let o={binding:r,parent:i,redirections:[]},s=eQ(e,new eJ(n.last),{customServiceIdentifier:r.targetServiceIdentifier});return o.redirections.push(...e5(e,n,s,o)),o}(e,n,o,i);s.push(r);break}default:s.push({binding:o,parent:i})}return e.servicesBranch.pop(),s}function e4(e,n){return e.node.binding.type===ev.Instance?function(e,n,r){let i=n.classMetadata;for(let[o,s]of i.constructorArguments.entries())n.constructorParams[o]=e6(e,r,s);for(let[o,s]of i.properties){let i=e6(e,r,s);void 0!==i&&n.propertyParams.set(o,i)}return e.node}(e,e.node,n):function(e,n,r){for(let[i,o]of n.binding.metadata.arguments.entries())n.params[i]=function(e,n,r){let i=eu.is(r.value)?r.value.unwrap():r.value,o=n.concat({name:r.name,serviceIdentifier:i,tags:r.tags}),s=new eJ(o.last),a=eQ(e,s),c=[],l={bindings:c,parent:e.node,serviceIdentifier:i};if(c.push(...e5(e,o,a,l)),r.kind===k.singleInjection){e3(l,r.optional,s);let[e]=c;l.bindings=e}return l}(e,r,o);return e.node}(e,e.node,n)}class e8{#y;#b;#w;constructor(){this.#y=[],this.#b=8,this.#w=1024}*[Symbol.iterator](){let e=0;for(let n of this.#y){let r=n.deref();void 0===r?++e:yield r}this.#y.length>=this.#b&&this.#O(e)&&this.#_(e)}push(e){let n=new WeakRef(e);if(this.#y.push(n),this.#y.length>=this.#b&&this.#y.length%this.#w==0){let e=0;for(let n of this.#y)void 0===n.deref()&&++e;this.#O(e)&&this.#_(e)}}#_(e){let n=Array(this.#y.length-e),r=0;for(let e of this.#y)e.deref()&&(n[r++]=e);this.#y=n}#O(e){return e>=.5*this.#y.length}}(d=A||(A={}))[d.singleMandatory=0]="singleMandatory",d[d.singleOptional=1]="singleOptional",d[d.multipleMandatory=2]="multipleMandatory",d[d.multipleOptional=3]="multipleOptional",d[d.length=4]="length";class e9{#R;#S;#T;#E;#M;constructor(){this.#R=this.#x(),this.#S=this.#x(),this.#T=this.#x(),this.#E=this.#x(),this.#M=new e8}clearCache(){for(let e of this.#C())e.clear();for(let e of this.#M)e.clearCache()}get(e){var n,r,i,o,s,a;return void 0===e.name?void 0===e.tag?this.#j(this.#R,e).get(e.serviceIdentifier):null==(r=this.#j(this.#E,e).get(e.serviceIdentifier))||null==(n=r.get(e.tag.key))?void 0:n.get(e.tag.value):void 0===e.tag?null==(i=this.#j(this.#S,e).get(e.serviceIdentifier))?void 0:i.get(e.name):null==(a=this.#j(this.#T,e).get(e.serviceIdentifier))||null==(s=a.get(e.name))||null==(o=s.get(e.tag.key))?void 0:o.get(e.tag.value)}set(e,n){void 0===e.name?void 0===e.tag?this.#j(this.#R,e).set(e.serviceIdentifier,n):this.#I(this.#I(this.#j(this.#E,e),e.serviceIdentifier),e.tag.key).set(e.tag.value,n):void 0===e.tag?this.#I(this.#j(this.#S,e),e.serviceIdentifier).set(e.name,n):this.#I(this.#I(this.#I(this.#j(this.#T,e),e.serviceIdentifier),e.name),e.tag.key).set(e.tag.value,n)}subscribe(e){this.#M.push(e)}#x(){let e=Array(A.length);for(let n=0;n<e.length;++n)e[n]=new Map;return e}#I(e,n){let r=e.get(n);return void 0===r&&(r=new Map,e.set(n,r)),r}#j(e,n){return e[this.#B(n)]}#C(){return[...this.#R,...this.#S,...this.#T,...this.#E]}#B(e){return e.isMultiple?!0===e.optional?A.multipleOptional:A.multipleMandatory:!0===e.optional?A.singleOptional:A.singleMandatory}}function e7(e,n){return ea(n)?(e.cache={isRight:!0,value:n},n.then(n=>te(e,n))):te(e,n)}function te(e,n){return e.cache={isRight:!0,value:n},n}async function tt(e,n,r){let i=await n,o=r.next();for(;!0!==o.done;)i=await o.value(e.context,i),o=r.next();return i}function tn(e,n,r){let i=r;if(void 0!==n.onActivation){let r=n.onActivation;i=ea(i)?i.then(n=>r(e.context,n)):r(e.context,i)}var o=n.serviceIdentifier,s=i;let a=e.getActivations(o);return void 0===a?s:ea(s)?tt(e,s,a[Symbol.iterator]()):function(e,n,r){let i=n,o=r.next();for(;!0!==o.done;){let n=o.value(e.context,i);if(ea(n))return tt(e,n,r);i=n,o=r.next()}return i}(e,s,a[Symbol.iterator]())}function tr(e){return(n,r)=>r.cache.isRight?r.cache.value:e7(r,tn(n,r,e(n,r)))}let ti=tr(function(e,n){return n.value});function to(e,n){return(r,i)=>{let o=e(i);switch(o.scope){case eg.Singleton:if(o.cache.isRight)return o.cache.value;return e7(o,tn(r,o,n(r,i)));case eg.Request:{if(r.requestScopeCache.has(o.id))return r.requestScopeCache.get(o.id);let e=tn(r,o,n(r,i));return r.requestScopeCache.set(o.id,e),e}case eg.Transient:return tn(r,o,n(r,i))}}}let ts=to(function(e){return e},function(e,n){return n.value(e.context)}),ta=tr(function(e,n){return n.factory(e.context)});function tc(e,n,r){let i=function(e,n,r){if(void 0!==r){if(!(r in e))throw new ej(C.resolution,`Expecting a "${r.toString()}" property when resolving "${n.implementationType.name}" class @postConstruct decorated method, none found.`);if("function"!=typeof e[r])throw new ej(C.resolution,`Expecting a "${r.toString()}" method when resolving "${n.implementationType.name}" class @postConstruct decorated method, a non function property was found instead.`);{let i;try{i=e[r]()}catch(e){throw new ej(C.resolution,`Unexpected error found when calling "${r.toString()}" @postConstruct decorated method on class "${n.implementationType.name}"`,{cause:e})}if(ea(i))return async function(e,n,r){try{await r}catch(r){throw new ej(C.resolution,`Unexpected error found when calling "${n.toString()}" @postConstruct decorated method on class "${e.implementationType.name}"`,{cause:r})}}(n,r,i)}}}(e,n,r);return ea(i)?i.then(()=>e):e}function tl(e){return(n,r,i)=>{let o=new i.binding.implementationType(...n),s=e(r,o,i);return ea(s)?s.then(()=>tc(o,i.binding,i.classMetadata.lifecycle.postConstructMethodName)):tc(o,i.binding,i.classMetadata.lifecycle.postConstructMethodName)}}let tu=tr(function(e,n){return n.provider(e.context)}),td=(p=ty,(e,n,r)=>{let i=[];for(let[o,s]of r.propertyParams){let a=r.classMetadata.properties.get(o);if(void 0===a)throw new ej(C.resolution,`Expecting metadata at property "${o.toString()}", none found`);a.kind!==I.unmanaged&&void 0!==s.bindings&&(n[o]=p(e,s),ea(n[o])&&i.push((async()=>{n[o]=await n[o]})()))}if(i.length>0)return Promise.all(i).then(()=>{})}),tp=(h=tv,function e(n,r){let i=[];for(let o of r.redirections)eY(o)?i.push(...e(n,o)):i.push(h(n,o));return i}),th=(f=ty,g=(e,n)=>{let r=[];for(let i of n.constructorParams)void 0===i?r.push(void 0):r.push(f(e,i));return r.some(ea)?Promise.all(r):r},m=tl(td),v=async(e,n,r)=>m(await e,n,r),y=tl(td),(e,n)=>{let r=g(e,n);return ea(r)?v(r,e,n):y(r,e,n)}),tf=(b=ty,w=(e,n)=>{let r=[];for(let i of n.params)r.push(b(e,i));return r.some(ea)?Promise.all(r):r},(e,n)=>{let r=w(e,n);return ea(r)?r.then(e=>n.binding.factory(...e)):n.binding.factory(...r)}),tm=to(function(e){return e.binding},th),tg=to(function(e){return e.binding},tf);function tv(e,n){switch(n.binding.type){case ev.ConstantValue:return ti(e,n.binding);case ev.DynamicValue:return ts(e,n.binding);case ev.Factory:return ta(e,n.binding);case ev.Instance:return tm(e,n);case ev.Provider:return tu(e,n.binding);case ev.ResolvedValue:return tg(e,n)}}function ty(e,n){if(void 0!==n.bindings)return Array.isArray(n.bindings)?function(e,n){let r=[];for(let i of n)eY(i)?r.push(...tp(e,i)):r.push(tv(e,i));return r.some(ea)?Promise.all(r):r}(e,n.bindings):function(e,n){if(eY(n)){let r=tp(e,n);if(1===r.length)return r[0];throw new ej(C.resolution,"Unexpected multiple resolved values on single injection")}return tv(e,n)}(e,n.bindings)}function tb(e,n){if(void 0!==e.lifecycle.preDestroyMethodName&&"function"==typeof n[e.lifecycle.preDestroyMethodName])return n[e.lifecycle.preDestroyMethodName]()}function tw(e,n,r){let i=e.getDeactivations(n);if(void 0!==i)return ea(r)?tO(r,i[Symbol.iterator]()):function(e,n){let r=n.next();for(;!0!==r.done;){if(ea(r.value(e)))return tO(e,n);r=n.next()}}(r,i[Symbol.iterator]())}async function tO(e,n){let r=await e,i=n.next();for(;!0!==i.done;)await i.value(r),i=n.next()}function t_(e,n){let r=n.cache;return ea(r.value)?r.value.then(r=>tR(e,n,r)):tR(e,n,r.value)}function tR(e,n,r){let i;return void 0!==n.onDeactivation&&(i=(0,n.onDeactivation)(r)),void 0===i?tw(e,n.serviceIdentifier,r):i.then(()=>tw(e,n.serviceIdentifier,r))}function tS(e,n){if(void 0===n)return;let r=function(e){let n=[];for(let r of e)void 0!==r.scope&&r.scope===eg.Singleton&&r.cache.isRight&&n.push(r);return n}(n),i=[];for(let n of r){let r=function(e,n){let r=function(e,n){if(n.type===ev.Instance){let r=e.getClassMetadata(n.implementationType),i=n.cache.value;return ea(i)?i.then(e=>tb(r,e)):tb(r,i)}}(e,n);return void 0===r?t_(e,n):r.then(()=>t_(e,n))}(e,n);void 0!==r&&i.push(r)}return i.length>0?Promise.all(i).then(()=>{}):void 0}function tT(e,n){let r=e.getBindings(n);return tS(e,r)}let tE=Symbol.for("@inversifyjs/plugin/isPlugin"),tM=Symbol.for("@inversifyjs/container/bindingIdentifier");function tx(e){return"object"==typeof e&&null!==e&&!0===e[tM]}class tC{static #k=this.always=e=>!0}function tj(e){return{[tM]:!0,id:e.id}}function tI(e){return n=>{for(let r=n.getAncestor();void 0!==r;r=r.getAncestor())if(e(r))return!0;return!1}}function tB(e){return n=>n.name===e}function tk(e){return n=>n.serviceIdentifier===e}function tA(e,n){return r=>r.tags.has(e)&&r.tags.get(e)===n}function tP(e){return void 0===e.name&&0===e.tags.size}function tN(e){let n=tI(e);return e=>!n(e)}function tL(e){return n=>{let r=n.getAncestor();return void 0===r||!e(r)}}function tD(e){return n=>{let r=n.getAncestor();return void 0!==r&&e(r)}}class tF{#r;constructor(e){this.#r=e}getIdentifier(){return tj(this.#r)}inRequestScope(){return this.#r.scope=eg.Request,new tV(this.#r)}inSingletonScope(){return this.#r.scope=eg.Singleton,new tV(this.#r)}inTransientScope(){return this.#r.scope=eg.Transient,new tV(this.#r)}}class tU{#t;#o;#s;#a;constructor(e,n,r,i){this.#t=e,this.#o=n,this.#s=r,this.#a=i}to(e){var n;let r=eI(e),i={cache:{isRight:!1,value:void 0},id:em(),implementationType:e,isSatisfiedBy:tC.always,moduleId:this.#o,onActivation:void 0,onDeactivation:void 0,scope:null!=(n=r.scope)?n:this.#s,serviceIdentifier:this.#a,type:ev.Instance};return this.#t(i),new tX(i)}toSelf(){if("function"!=typeof this.#a)throw Error('"toSelf" function can only be applied when a newable function is used as service identifier');return this.to(this.#a)}toConstantValue(e){let n={cache:{isRight:!1,value:void 0},id:em(),isSatisfiedBy:tC.always,moduleId:this.#o,onActivation:void 0,onDeactivation:void 0,scope:eg.Singleton,serviceIdentifier:this.#a,type:ev.ConstantValue,value:e};return this.#t(n),new tV(n)}toDynamicValue(e){let n={cache:{isRight:!1,value:void 0},id:em(),isSatisfiedBy:tC.always,moduleId:this.#o,onActivation:void 0,onDeactivation:void 0,scope:this.#s,serviceIdentifier:this.#a,type:ev.DynamicValue,value:e};return this.#t(n),new tX(n)}toResolvedValue(e,n){let r={cache:{isRight:!1,value:void 0},factory:e,id:em(),isSatisfiedBy:tC.always,metadata:this.#i(n),moduleId:this.#o,onActivation:void 0,onDeactivation:void 0,scope:this.#s,serviceIdentifier:this.#a,type:ev.ResolvedValue};return this.#t(r),new tX(r)}toFactory(e){let n={cache:{isRight:!1,value:void 0},factory:e,id:em(),isSatisfiedBy:tC.always,moduleId:this.#o,onActivation:void 0,onDeactivation:void 0,scope:eg.Singleton,serviceIdentifier:this.#a,type:ev.Factory};return this.#t(n),new tV(n)}toProvider(e){let n={cache:{isRight:!1,value:void 0},id:em(),isSatisfiedBy:tC.always,moduleId:this.#o,onActivation:void 0,onDeactivation:void 0,provider:e,scope:eg.Singleton,serviceIdentifier:this.#a,type:ev.Provider};return this.#t(n),new tV(n)}toService(e){let n={id:em(),isSatisfiedBy:tC.always,moduleId:this.#o,serviceIdentifier:this.#a,targetServiceIdentifier:e,type:ev.ServiceRedirection};this.#t(n)}#i(e){return{arguments:(null!=e?e:[]).map(e=>{var n,r;return"object"!=typeof e||eu.is(e)?{kind:k.singleInjection,name:void 0,optional:!1,tags:new Map,value:e}:{kind:!0===e.isMultiple?k.multipleInjection:k.singleInjection,name:e.name,optional:null!=(n=e.optional)&&n,tags:new Map((null!=(r=e.tags)?r:[]).map(e=>[e.key,e.value])),value:e.serviceIdentifier}})}}}class tH{#r;constructor(e){this.#r=e}getIdentifier(){return tj(this.#r)}onActivation(e){return this.#r.onActivation=e,new tq(this.#r)}onDeactivation(e){return this.#r.onDeactivation=e,new tq(this.#r)}}class tq{#r;constructor(e){this.#r=e}getIdentifier(){return tj(this.#r)}when(e){return this.#r.isSatisfiedBy=e,new tH(this.#r)}whenAnyAncestor(e){return this.when(tI(e))}whenAnyAncestorIs(e){return this.when(tI(tk(e)))}whenAnyAncestorNamed(e){return this.when(tI(tB(e)))}whenAnyAncestorTagged(e,n){return this.when(tI(tA(e,n)))}whenDefault(){return this.when(tP)}whenNamed(e){return this.when(tB(e))}whenNoParent(e){return this.when(tL(e))}whenNoParentIs(e){return this.when(tL(tk(e)))}whenNoParentNamed(e){return this.when(tL(tB(e)))}whenNoParentTagged(e,n){return this.when(tL(tA(e,n)))}whenParent(e){return this.when(tD(e))}whenParentIs(e){return this.when(tD(tk(e)))}whenParentNamed(e){return this.when(tD(tB(e)))}whenParentTagged(e,n){return this.when(tD(tA(e,n)))}whenTagged(e,n){return this.when(tA(e,n))}whenNoAncestor(e){return this.when(tN(e))}whenNoAncestorIs(e){return this.when(tN(tk(e)))}whenNoAncestorNamed(e){return this.when(tN(tB(e)))}whenNoAncestorTagged(e,n){return this.when(tN(tA(e,n)))}}class tV extends tq{#c;constructor(e){super(e),this.#c=new tH(e)}onActivation(e){return this.#c.onActivation(e)}onDeactivation(e){return this.#c.onDeactivation(e)}}class tX extends tV{#u;constructor(e){super(e),this.#u=new tF(e)}inRequestScope(){return this.#u.inRequestScope()}inSingletonScope(){return this.#u.inSingletonScope()}inTransientScope(){return this.#u.inTransientScope()}}let tW=Symbol.for("@inversifyjs/container/InversifyContainerError");class t$ extends Error{constructor(e,n,r){super(n,r),this[tW]=!0,this.kind=e}static is(e){return"object"==typeof e&&null!==e&&!0===e[tW]}static isErrorOfKind(e,n){return t$.is(e)&&e.kind===n}}(O=P||(P={}))[O.invalidOperation=0]="invalidOperation";class tz{#d;#s;#l;constructor(e,n,r){this.#d=e,this.#s=n,this.#l=r}bind(e){return new tU(e=>{this.#m(e)},void 0,this.#s,e)}isBound(e,n){let r=this.#l.bindingService.get(e);return this.#v(e,r,n)}isCurrentBound(e,n){let r=this.#l.bindingService.getNonParentBindings(e);return this.#v(e,r,n)}async rebind(e){return await this.unbind(e),this.bind(e)}rebindSync(e){return this.unbindSync(e),this.bind(e)}async unbind(e){await this.#f(e)}async unbindAll(){let e=[...this.#l.bindingService.getNonParentBoundServices()];for(let n of(await Promise.all(e.map(async e=>tT(this.#d,e))),e))this.#l.activationService.removeAllByServiceId(n),this.#l.bindingService.removeAllByServiceId(n),this.#l.deactivationService.removeAllByServiceId(n);this.#l.planResultCacheService.clearCache()}unbindSync(e){void 0!==this.#f(e)&&this.#h(e)}#m(e){this.#l.bindingService.set(e),this.#l.planResultCacheService.clearCache()}#h(e){var n;let r;if(tx(e)){let i=this.#l.bindingService.getById(e.id),o=null==(n=function(e){if(void 0===e)return;let n=e.next();return!0!==n.done?n.value:void 0}(null==i?void 0:i[Symbol.iterator]()))?void 0:n.serviceIdentifier;r=void 0===o?"Unexpected asynchronous deactivation when unbinding binding identifier. Consider using Container.unbind() instead.":`Unexpected asynchronous deactivation when unbinding "${ec(o)}" binding. Consider using Container.unbind() instead.`}else r=`Unexpected asynchronous deactivation when unbinding "${ec(e)}" service. Consider using Container.unbind() instead.`;throw new t$(P.invalidOperation,r)}#f(e){return tx(e)?this.#_(e):this.#p(e)}#_(e){let n=this.#l.bindingService.getById(e.id),r=tS(this.#d,n);if(void 0!==r)return r.then(()=>{this.#R(e)});this.#R(e)}#R(e){this.#l.bindingService.removeById(e.id),this.#l.planResultCacheService.clearCache()}#p(e){let n=tT(this.#d,e);if(void 0!==n)return n.then(()=>{this.#b(e)});this.#b(e)}#b(e){this.#l.activationService.removeAllByServiceId(e),this.#l.bindingService.removeAllByServiceId(e),this.#l.deactivationService.removeAllByServiceId(e),this.#l.planResultCacheService.clearCache()}#v(e,n,r){if(void 0===n)return!1;let i={getAncestor:()=>{},name:null==r?void 0:r.name,serviceIdentifier:e,tags:new Map};for(let e of(void 0!==(null==r?void 0:r.tag)&&i.tags.set(r.tag.key,r.tag.value),n))if(e.isSatisfiedBy(i))return!0;return!1}}class tG{#y;#d;#s;#l;constructor(e,n,r,i){this.#y=e,this.#d=n,this.#s=r,this.#l=i}async load(){for(var e=arguments.length,n=Array(e),r=0;r<e;r++)n[r]=arguments[r];await Promise.all(this.#n(...n))}loadSync(){for(var e=arguments.length,n=Array(e),r=0;r<e;r++)n[r]=arguments[r];for(let e of this.#n(...n))if(void 0!==e)throw new t$(P.invalidOperation,"Unexpected asynchronous module load. Consider using Container.load() instead.")}async unload(){for(var e=arguments.length,n=Array(e),r=0;r<e;r++)n[r]=arguments[r];await Promise.all(this.#T(...n)),this.#O(n)}unloadSync(){for(var e=arguments.length,n=Array(e),r=0;r<e;r++)n[r]=arguments[r];for(let e of this.#T(...n))if(void 0!==e)throw new t$(P.invalidOperation,"Unexpected asynchronous module unload. Consider using Container.unload() instead.");this.#O(n)}#g(e){return{bind:n=>new tU(e=>{this.#m(e)},e,this.#s,n),isBound:this.#y.isBound.bind(this.#y),onActivation:(n,r)=>{this.#l.activationService.add(r,{moduleId:e,serviceId:n})},onDeactivation:(n,r)=>{this.#l.deactivationService.add(r,{moduleId:e,serviceId:n})},rebind:this.#y.rebind.bind(this.#y),rebindSync:this.#y.rebindSync.bind(this.#y),unbind:this.#y.unbind.bind(this.#y),unbindSync:this.#y.unbindSync.bind(this.#y)}}#O(e){for(let n of e)this.#l.activationService.removeAllByModuleId(n.id),this.#l.bindingService.removeAllByModuleId(n.id),this.#l.deactivationService.removeAllByModuleId(n.id);this.#l.planResultCacheService.clearCache()}#n(){for(var e=arguments.length,n=Array(e),r=0;r<e;r++)n[r]=arguments[r];return n.map(e=>e.load(this.#g(e.id)))}#m(e){this.#l.bindingService.set(e),this.#l.planResultCacheService.clearCache()}#T(){for(var e=arguments.length,n=Array(e),r=0;r<e;r++)n[r]=arguments[r];return n.map(e=>(function(e,n){let r=e.getBindingsFromModule(n);return tS(e,r)})(this.#d,e.id))}}class tJ{#w;#M;#A;#l;constructor(e,n,r){this.#l=n,this.#A=r,this.#w=this.#x(e),this.#M=this.#C()}register(e,n){let r=new n(e,this.#M);if(!0!==r[tE])throw new t$(P.invalidOperation,"Invalid plugin. The plugin must extend the Plugin class");r.load(this.#w)}#x(e){return{define:(n,r)=>{if(Object.prototype.hasOwnProperty.call(e,n))throw new t$(P.invalidOperation,`Container already has a method named "${String(n)}"`);e[n]=r},onPlan:this.#A.onPlan.bind(this.#A)}}#C(){let e=this.#l;return{get activationService(){return e.activationService},get bindingService(){return e.bindingService},get deactivationService(){return e.deactivationService},get planResultCacheService(){return e.planResultCacheService}}}}class tK{#I;constructor(e,n,r,i){this.activationService=e,this.bindingService=n,this.deactivationService=r,this.planResultCacheService=i,this.#I=[]}reset(e,n,r){for(let i of(this.activationService=e,this.bindingService=n,this.deactivationService=r,this.planResultCacheService.clearCache(),this.#I))i()}onReset(e){this.#I.push(e)}}class tQ{#P;#s;#N;#L;#D;#F;#l;#S;constructor(e,n,r){this.#l=e,this.#D=this.#B(),this.#P=n,this.#s=r,this.#N=e=>this.#l.activationService.get(e),this.#L=this.#l.bindingService.get.bind(this.#l.bindingService),this.#F=[],this.#S=this.#m.bind(this),this.#l.onReset(()=>{this.#E()})}get(e,n){let r=this.#U(!1,e,n),i=this.#H(r);if(ea(i))throw new t$(P.invalidOperation,`Unexpected asynchronous service when resolving service "${ec(e)}"`);return i}getAll(e,n){let r=this.#U(!0,e,n),i=this.#H(r);if(ea(i))throw new t$(P.invalidOperation,`Unexpected asynchronous service when resolving service "${ec(e)}"`);return i}async getAllAsync(e,n){let r=this.#U(!0,e,n);return this.#H(r)}async getAsync(e,n){let r=this.#U(!1,e,n);return this.#H(r)}onPlan(e){this.#F.push(e)}#E(){this.#L=this.#l.bindingService.get.bind(this.#l.bindingService),this.#S=this.#m.bind(this),this.#D=this.#B()}#q(e,n,r){return{isMultiple:e,name:null==r?void 0:r.name,optional:null==r?void 0:r.optional,serviceIdentifier:n,tag:null==r?void 0:r.tag}}#V(e,n,r){var i;let o={autobindOptions:(null!=(i=null==r?void 0:r.autobind)?i:this.#P)?{scope:this.#s}:void 0,getBindings:this.#L,getClassMetadata:eI,rootConstraints:{isMultiple:n,serviceIdentifier:e},servicesBranch:[],setBinding:this.#S};return this.#j(o,r),o}#U(e,n,r){let i=this.#q(e,n,r),o=this.#l.planResultCacheService.get(i);if(void 0!==o)return o;let s=function(e){try{let r=new Map;void 0!==e.rootConstraints.tag&&r.set(e.rootConstraints.tag.key,e.rootConstraints.tag.value);let i=new eK({elem:{name:e.rootConstraints.name,serviceIdentifier:e.rootConstraints.serviceIdentifier,tags:r},previous:void 0}),o=new eJ(i.last),s=eQ(e,o),a=[],c={bindings:a,parent:void 0,serviceIdentifier:e.rootConstraints.serviceIdentifier};if(a.push(...e5(e,i,s,c)),!e.rootConstraints.isMultiple){var n;e3(c,null!=(n=e.rootConstraints.isOptional)&&n,o);let[r]=a;c.bindings=r}return{tree:{root:c}}}catch(n){if(n instanceof Error&&(n instanceof RangeError&&/stack space|call stack|too much recursion/i.test(n.message)||"InternalError"===n.name&&/too much recursion/.test(n.message))){let r=function(e){let n=[...e];return 0===n.length?"(No dependency trace)":n.map(ec).join(" -> ")}(function(e){let n=new Set;for(let r of e.servicesBranch){if(n.has(r))return[...n,r];n.add(r)}return[...n]}(e));throw new ej(C.planning,`Circular dependency found: ${r}`,{cause:n})}throw n}}(this.#V(n,e,r));for(let e of(this.#l.planResultCacheService.set(i,s),this.#F))e(i,s);return s}#B(){return{get:this.get.bind(this),getAll:this.getAll.bind(this),getAllAsync:this.getAllAsync.bind(this),getAsync:this.getAsync.bind(this)}}#H(e){var n;return ty(n={context:this.#D,getActivations:this.#N,planResult:e,requestScopeCache:new Map},n.planResult.tree.root)}#j(e,n){void 0!==n&&(void 0!==n.name&&(e.rootConstraints.name=n.name),!0===n.optional&&(e.rootConstraints.isOptional=!0),void 0!==n.tag&&(e.rootConstraints.tag={key:n.tag.key,value:n.tag.value}))}#m(e){this.#l.bindingService.set(e),this.#l.planResultCacheService.clearCache()}}class tY{#l;#X;constructor(e){this.#l=e,this.#X=[]}restore(){let e=this.#X.pop();if(void 0===e)throw new t$(P.invalidOperation,"No snapshot available to restore");this.#l.reset(e.activationService,e.bindingService,e.deactivationService)}snapshot(){this.#X.push({activationService:this.#l.activationService.clone(),bindingService:this.#l.bindingService.clone(),deactivationService:this.#l.deactivationService.clone()})}}let tZ=eg.Transient;class t0{#y;#W;#k;#l;#A;#$;constructor(e){var n,r,i;this.#l=this.#z(e);let o=null!=(n=null==e?void 0:e.autobind)&&n,s=null!=(r=null==e?void 0:e.defaultScope)?r:tZ,a={getBindings:(i=this.#l).bindingService.get.bind(i.bindingService),getBindingsFromModule:i.bindingService.getByModuleId.bind(i.bindingService),getClassMetadata:eI,getDeactivations:i.deactivationService.get.bind(i.deactivationService)};this.#y=new tz(a,s,this.#l),this.#W=new tG(this.#y,a,s,this.#l),this.#A=new tQ(this.#l,o,s),this.#k=new tJ(this,this.#l,this.#A),this.#$=new tY(this.#l)}bind(e){return this.#y.bind(e)}get(e,n){return this.#A.get(e,n)}getAll(e,n){return this.#A.getAll(e,n)}async getAllAsync(e,n){return this.#A.getAllAsync(e,n)}async getAsync(e,n){return this.#A.getAsync(e,n)}isBound(e,n){return this.#y.isBound(e,n)}isCurrentBound(e,n){return this.#y.isCurrentBound(e,n)}async load(){for(var e=arguments.length,n=Array(e),r=0;r<e;r++)n[r]=arguments[r];return this.#W.load(...n)}loadSync(){for(var e=arguments.length,n=Array(e),r=0;r<e;r++)n[r]=arguments[r];this.#W.loadSync(...n)}onActivation(e,n){this.#l.activationService.add(n,{serviceId:e})}onDeactivation(e,n){this.#l.deactivationService.add(n,{serviceId:e})}register(e){this.#k.register(this,e)}restore(){this.#$.restore()}async rebind(e){return this.#y.rebind(e)}rebindSync(e){return this.#y.rebindSync(e)}snapshot(){this.#$.snapshot()}async unbind(e){await this.#y.unbind(e)}async unbindAll(){return this.#y.unbindAll()}unbindSync(e){this.#y.unbindSync(e)}async unload(){for(var e=arguments.length,n=Array(e),r=0;r<e;r++)n[r]=arguments[r];return this.#W.unload(...n)}unloadSync(){for(var e=arguments.length,n=Array(e),r=0;r<e;r++)n[r]=arguments[r];this.#W.unloadSync(...n)}#z(e){if(void 0===(null==e?void 0:e.parent))return new tK(ew.build(void 0),eR.build(void 0),eS.build(void 0),new e9);let n=new e9;return e.parent.#l.planResultCacheService.subscribe(n),new tK(ew.build(e.parent.#l.activationService),eR.build(e.parent.#l.bindingService),eS.build(e.parent.#l.deactivationService),n)}}let t1=new WeakMap,t2=new WeakMap,t3=new WeakMap,t6=Symbol("anyProducer"),t5=Promise.resolve(),t4=Symbol("listenerAdded"),t8=Symbol("listenerRemoved"),t9=!1,t7=!1,ne=e=>"string"==typeof e||"symbol"==typeof e||"number"==typeof e;function nt(e){if(!ne(e))throw TypeError("`eventName` must be a string, symbol, or number")}function nn(e){if("function"!=typeof e)throw TypeError("listener must be a function")}function nr(e,n){let r=t2.get(e);if(r.has(n))return r.get(n)}function ni(e,n){let r=ne(n)?n:t6,i=t3.get(e);if(i.has(r))return i.get(r)}function no(e,n){n=Array.isArray(n)?n:[n];let r=!1,i=()=>{},o=[],s={enqueue(e){o.push(e),i()},finish(){r=!0,i()}};for(let r of n){let n=ni(e,r);n||(n=new Set,t3.get(e).set(r,n)),n.add(s)}return{async next(){return o?0===o.length?(r?o=void 0:await new Promise(e=>{i=e}),this.next()):{done:!1,value:await o.shift()}:{done:!0}},async return(r){for(let r of(o=void 0,n)){let n=ni(e,r);n&&(n.delete(s),0===n.size&&t3.get(e).delete(r))}return i(),arguments.length>0?{done:!0,value:await r}:{done:!0}},[Symbol.asyncIterator](){return this}}}function ns(e){if(void 0===e)return nu;if(!Array.isArray(e))throw TypeError("`methodNames` must be an array of strings");for(let n of e)if(!nu.includes(n)){if("string"!=typeof n)throw TypeError("`methodNames` element must be a string");throw Error(`${n} is not Emittery method`)}return e}let na=e=>e===t4||e===t8;function nc(e,n,r){if(na(n))try{t9=!0,e.emit(n,r)}finally{t9=!1}}class nl{static mixin(e,n){return n=ns(n),r=>{if("function"!=typeof r)throw TypeError("`target` must be function");for(let e of n)if(void 0!==r.prototype[e])throw Error(`The property \`${e}\` already exists on \`target\``);Object.defineProperty(r.prototype,e,{enumerable:!1,get:function(){return Object.defineProperty(this,e,{enumerable:!1,value:new nl}),this[e]}});let i=n=>function(){for(var r=arguments.length,i=Array(r),o=0;o<r;o++)i[o]=arguments[o];return this[e][n](...i)};for(let e of n)Object.defineProperty(r.prototype,e,{enumerable:!1,value:i(e)});return r}}static get isDebugEnabled(){var e,n;if("object"!=typeof(null==(e=globalThis.process)?void 0:e.env))return t7;let{env:r}=null!=(n=globalThis.process)?n:{env:{}};return"emittery"===r.DEBUG||"*"===r.DEBUG||t7}static set isDebugEnabled(e){t7=e}constructor(e={}){var n;t1.set(this,new Set),t2.set(this,new Map),t3.set(this,new Map),t3.get(this).set(t6,new Set),this.debug=null!=(n=e.debug)?n:{},void 0===this.debug.enabled&&(this.debug.enabled=!1),this.debug.logger||(this.debug.logger=(e,n,r,i)=>{try{i=JSON.stringify(i)}catch{i=`Object with the following keys failed to stringify: ${Object.keys(i).join(",")}`}("symbol"==typeof r||"number"==typeof r)&&(r=r.toString());let o=new Date,s=`${o.getHours()}:${o.getMinutes()}:${o.getSeconds()}.${o.getMilliseconds()}`;console.log(`[${s}][emittery:${e}][${n}] Event Name: ${r}
|
|
44
|
-
data: ${i}`)})}logIfDebugEnabled(e,n,r){(nl.isDebugEnabled||this.debug.enabled)&&this.debug.logger(e,this.debug.name,n,r)}on(e,n){let{signal:r}=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};for(let r of(nn(n),e=Array.isArray(e)?e:[e])){nt(r);let e=nr(this,r);e||(e=new Set,t2.get(this).set(r,e)),e.add(n),this.logIfDebugEnabled("subscribe",r,void 0),na(r)||nc(this,t4,{eventName:r,listener:n})}let i=()=>{this.off(e,n),null==r||r.removeEventListener("abort",i)};return null==r||r.addEventListener("abort",i,{once:!0}),(null==r?void 0:r.aborted)&&i(),i}off(e,n){for(let r of(nn(n),e=Array.isArray(e)?e:[e])){nt(r);let e=nr(this,r);e&&(e.delete(n),0===e.size&&t2.get(this).delete(r)),this.logIfDebugEnabled("unsubscribe",r,void 0),na(r)||nc(this,t8,{eventName:r,listener:n})}}once(e,n){let r;if(void 0!==n&&"function"!=typeof n)throw TypeError("predicate must be a function");let i=new Promise(i=>{r=this.on(e,e=>{(!n||n(e))&&(r(),i(e))})});return i.off=r,i}events(e){for(let n of e=Array.isArray(e)?e:[e])nt(n);return no(this,e)}async emit(e,n){var r;if(nt(e),na(e)&&!t9)throw TypeError("`eventName` cannot be meta event `listenerAdded` or `listenerRemoved`");this.logIfDebugEnabled("emit",e,n);let i=t3.get(this);if(i.has(e))for(let r of i.get(e))r.enqueue(n);if(i.has(t6)){let r=Promise.all([e,n]);for(let e of i.get(t6))e.enqueue(r)}let o=null!=(r=nr(this,e))?r:new Set,s=t1.get(this),a=[...o],c=na(e)?[]:[...s];await t5,await Promise.all([...a.map(async e=>{if(o.has(e))return e(n)}),...c.map(async r=>{if(s.has(r))return r(e,n)})])}async emitSerial(e,n){var r;if(nt(e),na(e)&&!t9)throw TypeError("`eventName` cannot be meta event `listenerAdded` or `listenerRemoved`");this.logIfDebugEnabled("emitSerial",e,n);let i=null!=(r=nr(this,e))?r:new Set,o=t1.get(this),s=[...i],a=[...o];for(let e of(await t5,s))i.has(e)&&await e(n);for(let r of a)o.has(r)&&await r(e,n)}onAny(e){let{signal:n}=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};nn(e),this.logIfDebugEnabled("subscribeAny",void 0,void 0),t1.get(this).add(e),nc(this,t4,{listener:e});let r=()=>{this.offAny(e),null==n||n.removeEventListener("abort",r)};return null==n||n.addEventListener("abort",r,{once:!0}),(null==n?void 0:n.aborted)&&r(),r}anyEvent(){return no(this)}offAny(e){nn(e),this.logIfDebugEnabled("unsubscribeAny",void 0,void 0),nc(this,t8,{listener:e}),t1.get(this).delete(e)}clearListeners(e){for(let n of e=Array.isArray(e)?e:[e])if(this.logIfDebugEnabled("clear",n,void 0),ne(n)){let e=nr(this,n);e&&e.clear();let r=ni(this,n);if(r){for(let e of r)e.finish();r.clear()}}else{for(let[e,n]of(t1.get(this).clear(),t2.get(this).entries()))n.clear(),t2.get(this).delete(e);for(let[e,n]of t3.get(this).entries()){for(let e of n)e.finish();n.clear(),t3.get(this).delete(e)}}}listenerCount(e){e=Array.isArray(e)?e:[e];let n=0;for(let l of e){if(ne(l)){var r,i,o,s,a,c;n+=t1.get(this).size+(null!=(s=null==(r=nr(this,l))?void 0:r.size)?s:0)+(null!=(a=null==(i=ni(this,l))?void 0:i.size)?a:0)+(null!=(c=null==(o=ni(this))?void 0:o.size)?c:0);continue}for(let e of(void 0!==l&&nt(l),n+=t1.get(this).size,t2.get(this).values()))n+=e.size;for(let e of t3.get(this).values())n+=e.size}return n}bindMethods(e,n){if("object"!=typeof e||null===e)throw TypeError("`target` must be an object");for(let r of n=ns(n)){if(void 0!==e[r])throw Error(`The property \`${r}\` already exists on \`target\``);Object.defineProperty(e,r,{enumerable:!1,value:this[r].bind(this)})}}}let nu=Object.getOwnPropertyNames(nl.prototype).filter(e=>"constructor"!==e);Object.defineProperty(nl,"listenerAdded",{value:t4,writable:!1,enumerable:!0,configurable:!1}),Object.defineProperty(nl,"listenerRemoved",{value:t8,writable:!1,enumerable:!0,configurable:!1});let nd={AaaSPilotKitController:Symbol.for("AaaSPilotKitController"),SignalingService:Symbol.for("SignalingService"),ASRService:Symbol.for("ASRService"),AgentService:Symbol.for("AgentService"),DigitalHumanService:Symbol.for("DigitalHumanService"),ConversationService:Symbol.for("ConversationService"),CommonRequest:Symbol.for("CommonRequest"),ErrorManager:Symbol.for("ErrorManager"),IOptions:Symbol.for("IOptions")};class np extends Error{constructor(e,n,r){let i=e.status||0===e.status?e.status:"",o=e.statusText||"",s=`${i} ${o}`.trim();super(`Request failed with ${s?`status code ${s}`:"an unknown error"}: ${n.method} ${n.url}`),this.name="HTTPError",this.response=e,this.request=n,this.options=r}}class nh extends Error{constructor(e){super(`Request timed out: ${e.method} ${e.url}`),this.name="TimeoutError",this.request=e}}et("../../node_modules/core-js/modules/es.typed-array.set.js");let nf=(()=>{let e=!1,n=!1,r="function"==typeof globalThis.Request;if("function"==typeof globalThis.ReadableStream&&r)try{n=new globalThis.Request("https://empty.invalid",{body:new globalThis.ReadableStream,method:"POST",get duplex(){return e=!0,"half"}}).headers.has("Content-Type")}catch(e){if(e instanceof Error&&"unsupported BodyInit type"===e.message)return!1;throw e}return e&&!n})(),nm="function"==typeof globalThis.AbortController,ng="function"==typeof globalThis.ReadableStream,nv="function"==typeof globalThis.FormData,ny=["get","post","put","patch","head","delete"],nb={json:"application/json",text:"text/*",formData:"multipart/form-data",arrayBuffer:"*/*",blob:"*/*"},nw=new TextEncoder().encode("------WebKitFormBoundaryaxpyiPgbbPti10Rw").length,nO=Symbol("stop"),n_={json:!0,parseJson:!0,stringifyJson:!0,searchParams:!0,prefixUrl:!0,retry:!0,timeout:!0,hooks:!0,throwHttpErrors:!0,onDownloadProgress:!0,onUploadProgress:!0,fetch:!0},nR={method:!0,headers:!0,body:!0,mode:!0,credentials:!0,cache:!0,redirect:!0,referrer:!0,referrerPolicy:!0,integrity:!0,keepalive:!0,signal:!0,window:!0,dispatcher:!0,duplex:!0,priority:!0},nS=e=>{if(!e)return 0;if(e instanceof FormData){let n=0;for(let[r,i]of e)n+=nw,n+=new TextEncoder().encode(`Content-Disposition: form-data; name="${r}"`).length,n+="string"==typeof i?new TextEncoder().encode(i).length:i.size;return n}if(e instanceof Blob)return e.size;if(e instanceof ArrayBuffer)return e.byteLength;if("string"==typeof e)return new TextEncoder().encode(e).length;if(e instanceof URLSearchParams)return new TextEncoder().encode(e.toString()).length;if("byteLength"in e)return e.byteLength;if("object"==typeof e&&null!==e)try{let n=JSON.stringify(e);return new TextEncoder().encode(n).length}catch{}return 0},nT=(e,n)=>{let r=Number(e.headers.get("content-length"))||0,i=0;return 204===e.status?(n&&n({percent:1,totalBytes:r,transferredBytes:i},new Uint8Array),new Response(null,{status:e.status,statusText:e.statusText,headers:e.headers})):new Response(new ReadableStream({async start(o){let s=e.body.getReader();async function a(){let{done:e,value:c}=await s.read();if(e)return void o.close();n&&(i+=c.byteLength,n({percent:0===r?0:i/r,transferredBytes:i,totalBytes:r},c)),o.enqueue(c),await a()}n&&n({percent:0,transferredBytes:0,totalBytes:r},new Uint8Array),await a()}}),{status:e.status,statusText:e.statusText,headers:e.headers})},nE=(e,n)=>{let r=nS(e.body),i=0;return new Request(e,{duplex:"half",body:new ReadableStream({async start(o){let s=e.body instanceof ReadableStream?e.body.getReader():new Response("").body.getReader();async function a(){let{done:e,value:c}=await s.read();if(e){n&&n({percent:1,transferredBytes:i,totalBytes:Math.max(r,i)},new Uint8Array),o.close();return}i+=c.byteLength;let l=0===r?0:i/r;(r<i||1===l)&&(l=.99),n&&n({percent:Number(l.toFixed(2)),transferredBytes:i,totalBytes:r},c),o.enqueue(c),await a()}await a()}})})},nM=e=>null!==e&&"object"==typeof e,nx=function(){for(var e=arguments.length,n=Array(e),r=0;r<e;r++)n[r]=arguments[r];for(let e of n)if((!nM(e)||Array.isArray(e))&&void 0!==e)throw TypeError("The `options` argument must be an object");return nB({},...n)},nC=function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=new globalThis.Headers(e),i=n instanceof globalThis.Headers;for(let[e,o]of new globalThis.Headers(n).entries())i&&"undefined"===o||void 0===o?r.delete(e):r.set(e,o);return r};function nj(e,n,r){var i,o;return Object.hasOwn(n,r)&&void 0===n[r]?[]:nB(null!=(i=e[r])?i:[],null!=(o=n[r])?o:[])}let nI=function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return{beforeRequest:nj(e,n,"beforeRequest"),beforeRetry:nj(e,n,"beforeRetry"),afterResponse:nj(e,n,"afterResponse"),beforeError:nj(e,n,"beforeError")}},nB=function(){for(var e=arguments.length,n=Array(e),r=0;r<e;r++)n[r]=arguments[r];let i={},o={},s={};for(let e of n)if(Array.isArray(e))Array.isArray(i)||(i=[]),i=[...i,...e];else if(nM(e)){for(let[n,r]of Object.entries(e))nM(r)&&n in i&&(r=nB(i[n],r)),i={...i,[n]:r};nM(e.hooks)&&(s=nI(s,e.hooks),i.hooks=s),nM(e.headers)&&(o=nC(o,e.headers),i.headers=o)}return i},nk=e=>ny.includes(e)?e.toUpperCase():e,nA={limit:2,methods:["get","put","head","delete","options","trace"],statusCodes:[408,413,429,500,502,503,504],afterStatusCodes:[413,429,503],maxRetryAfter:Number.POSITIVE_INFINITY,backoffLimit:Number.POSITIVE_INFINITY,delay:e=>.3*2**(e-1)*1e3},nP=function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};if("number"==typeof e)return{...nA,limit:e};if(e.methods&&!Array.isArray(e.methods))throw Error("retry.methods must be an array");if(e.statusCodes&&!Array.isArray(e.statusCodes))throw Error("retry.statusCodes must be an array");return{...nA,...e}};async function nN(e,n,r,i){return new Promise((o,s)=>{let a=setTimeout(()=>{r&&r.abort(),s(new nh(e))},i.timeout);i.fetch(e,n).then(o).catch(s).then(()=>{clearTimeout(a)})})}async function nL(e,n){let{signal:r}=n;return new Promise((n,i)=>{function o(){clearTimeout(s),i(r.reason)}r&&(r.throwIfAborted(),r.addEventListener("abort",o,{once:!0}));let s=setTimeout(()=>{null==r||r.removeEventListener("abort",o),n()},e)})}let nD=(e,n)=>{let r={};for(let i in n)i in nR||i in n_||i in e||(r[i]=n[i]);return r};class nF{static create(e,n){let r=new nF(e,n),i=async()=>{if("number"==typeof r._options.timeout&&r._options.timeout>0x7fffffff)throw RangeError("The `timeout` option cannot be greater than 2147483647");await Promise.resolve();let e=await r._fetch();for(let n of r._options.hooks.afterResponse){let i=await n(r.request,r._options,r._decorateResponse(e.clone()));i instanceof globalThis.Response&&(e=i)}if(r._decorateResponse(e),!e.ok&&r._options.throwHttpErrors){let n=new np(e,r.request,r._options);for(let e of r._options.hooks.beforeError)n=await e(n);throw n}if(r._options.onDownloadProgress){if("function"!=typeof r._options.onDownloadProgress)throw TypeError("The `onDownloadProgress` option must be a function");if(!ng)throw Error("Streams are not supported in your environment. `ReadableStream` is missing.");return nT(e.clone(),r._options.onDownloadProgress)}return e},o=(r._options.retry.methods.includes(r.request.method.toLowerCase())?r._retry(i):i()).finally(async()=>{if(!r.request.bodyUsed){var e;await (null==(e=r.request.body)?void 0:e.cancel())}});for(let[e,i]of Object.entries(nb))o[e]=async()=>{r.request.headers.set("accept",r.request.headers.get("accept")||i);let s=await o;if("json"===e){if(204===s.status||0===(await s.clone().arrayBuffer()).byteLength)return"";if(n.parseJson)return n.parseJson(await s.text())}return s[e]()};return o}constructor(e,n={}){var r,i,o,s,a,c,l,u,d;if(this._retryCount=0,this._input=e,this._options={...n,headers:nC(this._input.headers,n.headers),hooks:nI({beforeRequest:[],beforeRetry:[],beforeError:[],afterResponse:[]},n.hooks),method:nk(null!=(i=null!=(r=n.method)?r:this._input.method)?i:"GET"),prefixUrl:String(n.prefixUrl||""),retry:nP(n.retry),throwHttpErrors:!1!==n.throwHttpErrors,timeout:null!=(o=n.timeout)?o:1e4,fetch:null!=(s=n.fetch)?s:globalThis.fetch.bind(globalThis)},"string"!=typeof this._input&&!(this._input instanceof URL||this._input instanceof globalThis.Request))throw TypeError("`input` must be a string, URL, or Request");if(this._options.prefixUrl&&"string"==typeof this._input){if(this._input.startsWith("/"))throw Error("`input` must not begin with a slash when using `prefixUrl`");this._options.prefixUrl.endsWith("/")||(this._options.prefixUrl+="/"),this._input=this._options.prefixUrl+this._input}if(nm){let e=null!=(a=this._options.signal)?a:this._input.signal;this.abortController=new globalThis.AbortController,this._options.signal=e?AbortSignal.any([e,this.abortController.signal]):this.abortController.signal}if(nf&&(this._options.duplex="half"),void 0!==this._options.json&&(this._options.body=null!=(u=null==(c=(l=this._options).stringifyJson)?void 0:c.call(l,this._options.json))?u:JSON.stringify(this._options.json),this._options.headers.set("content-type",null!=(d=this._options.headers.get("content-type"))?d:"application/json")),this.request=new globalThis.Request(this._input,this._options),this._options.searchParams){let e="string"==typeof this._options.searchParams?this._options.searchParams.replace(/^\?/,""):new URLSearchParams(this._options.searchParams).toString(),n=this.request.url.replace(/(?:\?.*?)?(?=#|$)/,"?"+e);(nv&&this._options.body instanceof globalThis.FormData||this._options.body instanceof URLSearchParams)&&!(this._options.headers&&this._options.headers["content-type"])&&this.request.headers.delete("content-type"),this.request=new globalThis.Request(new globalThis.Request(n,{...this.request}),this._options)}if(this._options.onUploadProgress){if("function"!=typeof this._options.onUploadProgress)throw TypeError("The `onUploadProgress` option must be a function");if(!nf)throw Error("Request streams are not supported in your environment. The `duplex` option for `Request` is not available.");this.request.body&&(this.request=nE(this.request,this._options.onUploadProgress))}}_calculateRetryDelay(e){if(this._retryCount++,this._retryCount>this._options.retry.limit||e instanceof nh)throw e;if(e instanceof np){var n,r,i,o;if(!this._options.retry.statusCodes.includes(e.response.status))throw e;let s=null!=(i=null!=(r=null!=(n=e.response.headers.get("Retry-After"))?n:e.response.headers.get("RateLimit-Reset"))?r:e.response.headers.get("X-RateLimit-Reset"))?i:e.response.headers.get("X-Rate-Limit-Reset");if(s&&this._options.retry.afterStatusCodes.includes(e.response.status)){let e=1e3*Number(s);Number.isNaN(e)?e=Date.parse(s)-Date.now():e>=Date.parse("2024-01-01")&&(e-=Date.now());let n=null!=(o=this._options.retry.maxRetryAfter)?o:e;return e<n?e:n}if(413===e.response.status)throw e}let s=this._options.retry.delay(this._retryCount);return Math.min(this._options.retry.backoffLimit,s)}_decorateResponse(e){return this._options.parseJson&&(e.json=async()=>this._options.parseJson(await e.text())),e}async _retry(e){try{return await e()}catch(r){let n=Math.min(this._calculateRetryDelay(r),0x7fffffff);if(this._retryCount<1)throw r;for(let e of(await nL(n,{signal:this._options.signal}),this._options.hooks.beforeRetry))if(await e({request:this.request,options:this._options,error:r,retryCount:this._retryCount})===nO)return;return this._retry(e)}}async _fetch(){for(let e of this._options.hooks.beforeRequest){let n=await e(this.request,this._options);if(n instanceof Request){this.request=n;break}if(n instanceof Response)return n}let e=nD(this.request,this._options),n=this.request;return(this.request=n.clone(),!1===this._options.timeout)?this._options.fetch(n,e):nN(n,e,this.abortController,this._options)}}let nU=e=>{let n=(n,r)=>nF.create(n,nx(e,r));for(let r of ny)n[r]=(n,i)=>nF.create(n,nx(e,i,{method:r}));return n.create=e=>nU(nx(e)),n.extend=n=>("function"==typeof n&&(n=n(null!=e?e:{})),nU(nx(e,n))),n.stop=nO,n},nH=nU();function nq(e,n){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,n)}function nV(e,n){return function(r,i){n(r,i,e)}}class nX{static #k=this.ONLINE_HOST="https://ky.cloud.baidu.com";static #G=this.SANDBOX_HOST="https://ky-test.cloud.baidu.com";constructor(e){this.opts=e,"production"===this.opts.env?this.client=nH.create({prefixUrl:nX.ONLINE_HOST}):this.client=nH.create({prefixUrl:nX.SANDBOX_HOST})}}nX=function(e,n,r,i){var o,s=arguments.length,a=s<3?n:null===i?i=Object.getOwnPropertyDescriptor(n,r):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)a=Reflect.decorate(e,n,r,i);else for(var c=e.length-1;c>=0;c--)(o=e[c])&&(a=(s<3?o(a):s>3?o(n,r,a):o(n,r))||a);return s>3&&a&&Object.defineProperty(n,r,a),a}([eV(),nV(0,eU(nd.IOptions)),nV(0,ez()),nq("design:type",Function),nq("design:paramtypes",["undefined"==typeof IResolvedOptions?Object:IResolvedOptions])],nX);var nW=((_={}).NETWORK="NETWORK",_.TIMEOUT="TIMEOUT",_.AUTHENTICATION="AUTHENTICATION",_.AUTHORIZATION="AUTHORIZATION",_.RESOURCE="RESOURCE",_.CONFIGURATION="CONFIGURATION",_.PARSING="PARSING",_.SERVICE="SERVICE",_.VALIDATION="VALIDATION",_.INTERNAL="INTERNAL",_),n$=((R={}).LOW="LOW",R.MEDIUM="MEDIUM",R.HIGH="HIGH",R.CRITICAL="CRITICAL",R);class nz extends Error{constructor(e,n,r,i=n$.MEDIUM,o={},s){super(n),this.name=this.constructor.name,this.code=e,this.category=r,this.severity=i,this.actionRequired=s,this.metadata={timestamp:Date.now(),stack:this.stack,...o},Object.setPrototypeOf(this,new.target.prototype),Error.captureStackTrace?Error.captureStackTrace(this,this.constructor):this.stack=Error(n).stack}static fromError(e,n,r){let i=arguments.length>3&&void 0!==arguments[3]?arguments[3]:n$.MEDIUM;return new nz(n,e.message,r,i,{originalError:e,stack:e.stack})}toJSON(){return{code:this.code,message:this.message,category:this.category,severity:this.severity,metadata:this.metadata,actionRequired:this.actionRequired}}toString(){return`${this.name} [${this.code}]: ${this.message}`}}let nG={1e3:"发生未知错误",1001:"网络连接错误",1002:"请求超时",1003:"配置无效",1004:"身份验证失败",1005:"权限验证失败",1006:"数据验证失败",1007:"资源未找到",1008:"资源不可用",1009:"内部错误",2001:"Agent查询失败",2002:"Agent响应解析错误",2003:"Agent请求超时",2004:"Agent响应无效",2005:"Agent连接失败",2006:"Agent指令无效",3001:"ASR初始化失败",3002:"ASR启动失败",3003:"ASR停止失败",3004:"ASR信令错误",3005:"ASR音频捕获错误",3006:"ASR识别错误",3007:"ASR网络错误",3008:"ASR权限被拒绝",3009:"ASR设备未找到",3010:"ASR消息解析错误",3011:"ASR会话无效",3012:"ASR静音失败",3013:"ASR消息间隔超时",3014:"ASR运行时错误",4001:"数字人挂载失败",4002:"数字人iframe加载错误",4003:"数字人渲染错误",4004:"数字人WebSocket错误",4005:"数字人RTC错误",4006:"数字人认证错误",4007:"数字人会话数量达到上限",4008:"数字人资源不足",4009:"数字人超时",4010:"数字人中断失败",4011:"数字人SSML解析错误",4012:"数字人形象ID无效",4013:"数字人token无效",4014:"数字人流式渲染错误",4015:"数字人控制器未就绪",4016:"数字人播报文本长度不匹配",5001:"会话创建失败",5002:"会话类型无效",5003:"会话快照无效",5004:"会话Bean未找到",5005:"会话序列化错误",5006:"会话反序列化错误",5007:"会话状态无效",5008:"会话清除失败"};class nJ extends nz{constructor(e,n,r=n$.MEDIUM,i={},o){super(e,n||nG[e]||"Agent服务错误",nW.SERVICE,r,i,o)}}class nK extends nJ{constructor(e,n={}){super("2001",e,n$.HIGH,n)}}class nQ extends nJ{constructor(e,n={}){super("2002",e,n$.HIGH,n)}}class nY extends nJ{constructor(e,n={}){super("2005",e,n$.HIGH,n)}}class nZ extends nJ{constructor(e,n={}){super("2006",e,n$.MEDIUM,n)}}var n0=et("../../node_modules/ua-parser-js/src/ua-parser.js"),n1=et.n(n0);let n2=()=>{let e=new(n1()),n=e.getBrowser(),r=e.getOS(),i=e.getDevice();return{userAgent:e.getUA(),browser:{name:n.name,version:n.version},os:{name:r.name,version:r.version},device:{type:i.type,vendor:i.vendor,model:i.model}}},n3=()=>{let e=new(n1()),n=e.getUA();return"WeChat"===e.getBrowser().name||/MicroMessenger/i.test(n)},n6=()=>"iOS"===new(n1())().getOS().name,n5=()=>{let e=new(n1()),n=e.getOS(),r=e.getDevice();return"Mac OS"===n.name&&"tablet"===r.type};class n4 extends nz{constructor(e,n,r=n$.MEDIUM,i={}){super(e,n||nG[e]||"ASR服务错误",nW.SERVICE,r,i)}}class n8 extends n4{constructor(e,n={}){super("3001",e,n$.HIGH,n)}}class n9 extends n4{constructor(e,n={}){super("3003",e,n$.MEDIUM,n)}}class n7 extends n4{constructor(e,n={}){super("3008",e,n$.MEDIUM,{...n,context:{...n.context,browserInfo:n2()}})}}class re extends n4{constructor(e,n={}){super("3010",e,n$.MEDIUM,n)}}class rt extends n4{constructor(e,n={}){super("3013",e,n$.MEDIUM,n)}}class rn extends n4{constructor(e,n={}){super("3014",e,n$.HIGH,n)}}class rr extends nz{constructor(e,n,r=n$.MEDIUM,i={}){super(e,n||nG[e]||"数字人服务错误",nW.SERVICE,r,i)}}class ri extends rr{constructor(e,n={}){super("4001",e,n$.HIGH,n)}}class ro extends rr{constructor(e,n={}){super("4002",e,n$.HIGH,n)}}class rs extends rr{constructor(e,n={}){super("4003",e,n$.MEDIUM,n)}}class ra extends rr{constructor(e,n={}){super("4004",e,n$.HIGH,n)}}class rc extends rr{constructor(e,n={}){super("4005",e,n$.HIGH,n)}}class rl extends rr{constructor(e,n={}){super("4006",e,n$.CRITICAL,n)}}class ru extends rr{constructor(e,n={}){super("4008",e,n$.CRITICAL,n)}}class rd{constructor(e){this.opts=e,this.reporters=[]}addReporter(e){this.reporters.push(e)}removeReporter(e){let n=this.reporters.indexOf(e);n>-1&&this.reporters.splice(n,1)}async handle(e){let n;n=e instanceof nz?e.toJSON():this.isErrorDetails(e)?e:nz.fromError(e,"UNKNOWN_ERROR","INTERNAL").toJSON(),await this.processError(n)}async processError(e){try{this.shouldLogError()&&this.logError(e),this.shouldReportError(e)&&await this.reportError(e)}catch(e){console.error("Error in error handler:",e)}}shouldLogError(){var e;return(null==(e=this.opts)?void 0:e.enableErrorLogging)!==!1}shouldReportError(e){var n;return(null==(n=this.opts)?void 0:n.enableErrorReporting)!==!1&&e.severity!==n$.LOW&&this.reporters.length>0}logError(e){let n=this.getLogLevel(e.severity),r=`[${e.code}] ${e.message}`;"error"===n?console.error(r,e):"warn"===n?console.warn(r,e):console.log(r,e)}getLogLevel(e){switch(e){case n$.CRITICAL:case n$.HIGH:return"error";case n$.MEDIUM:return"warn";case n$.LOW:default:return"log"}}async reportError(e){let n=this.reporters.map(n=>n.report(e).catch(e=>{console.error("Error reporter failed:",e)}));await Promise.allSettled(n)}isErrorDetails(e){return e&&"object"==typeof e&&"code"in e&&"message"in e&&"category"in e&&"severity"in e}}class rp{async report(e){console.error("Error Report:",{code:e.code,message:e.message,category:e.category,severity:e.severity,timestamp:new Date(e.metadata.timestamp).toISOString(),sessionId:e.metadata.sessionId,requestId:e.metadata.requestId,context:e.metadata.context})}}class rh{constructor(e){this.options={timeout:5e3,headers:{"Content-Type":"application/json"},retryCount:3,retryDelay:1e3,...e}}async report(e){let n=this.buildPayload(e);for(let e=0;e<=this.options.retryCount;e++)try{await this.sendRequest(n);return}catch(n){if(e===this.options.retryCount)throw n;await this.delay(this.options.retryDelay*(e+1))}}buildPayload(e){return{error:{code:e.code,message:e.message,category:e.category,severity:e.severity,actionRequired:e.actionRequired},metadata:{timestamp:e.metadata.timestamp,sessionId:e.metadata.sessionId,requestId:e.metadata.requestId,userId:e.metadata.userId,context:e.metadata.context,userAgent:navigator.userAgent,url:window.location.href}}}async sendRequest(e){let n=new AbortController,r=setTimeout(()=>n.abort(),this.options.timeout);try{let r=await fetch(this.options.endpoint,{method:"POST",headers:this.options.headers,body:JSON.stringify(e),signal:n.signal});if(!r.ok)throw Error(`HTTP ${r.status}: ${r.statusText}`)}finally{clearTimeout(r)}}delay(e){return new Promise(n=>setTimeout(n,e))}}class rf{static getErrorSeverity(e){if(e instanceof nz)return e.severity;let n=e.message.toLowerCase();return n.includes("permission")||n.includes("unauthorized")||n.includes("forbidden")?n$.CRITICAL:n.includes("network")||n.includes("timeout")||n.includes("connection")?n$.HIGH:n$.MEDIUM}static shouldReport(e){return!(e instanceof nz)||e.severity!==n$.LOW}static extractMetadata(e){let n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r={timestamp:Date.now(),context:n,stack:e.stack};return e instanceof nz?{...r,...e.metadata}:r}static getActionRequired(e){if(e instanceof nz){var n;return null!=(n=e.actionRequired)?n:null}let r=e.message.toLowerCase();return r.includes("permission")||r.includes("unauthorized")?"请检查用户权限":r.includes("network")||r.includes("timeout")?"请检查网络连接后重试":r.includes("validation")||r.includes("invalid")?"请检查输入数据的格式和有效性":null}}class rm{constructor(){this.emitter=new nl,this.emit=e=>{let n=this.transformErrorToPayload(e);this.emitter.emit("error",n)},this.on=e=>{this.emitter.on("error",e)},this.off=e=>{this.emitter.off("error",e)},this.clearListeners=()=>{this.emitter.clearListeners()},this.transformErrorToPayload=e=>{if(e instanceof nz){var n;return{code:e.code,message:e.toString(),stack:e.stack,actionRequired:null!=(n=e.actionRequired)?n:null,severity:e.severity,metadata:{timestamp:e.metadata.timestamp,sessionId:e.metadata.sessionId,requestId:e.metadata.requestId,userId:e.metadata.userId,context:e.metadata.context,service:this.extractServiceFromError(e)},originalError:e}}return{code:"UNKNOWN_ERROR",message:e.toString(),stack:e.stack,actionRequired:rf.getActionRequired(e),severity:rf.getErrorSeverity(e),metadata:{timestamp:Date.now(),context:{errorName:e.name}},originalError:e}},this.extractServiceFromError=e=>{let n=e.constructor.name.toLowerCase();return n.includes("agent")?"agent":n.includes("asr")?"asr":n.includes("digitalHuman")||n.includes("dh")?"digital-human":n.includes("conversation")?"conversation":"unknown"}}}class rg extends Error{constructor(e,n,r={}){super(n),this.name=e||"AaaSPilotKitError",this.message=n,this.data=r,Error.captureStackTrace?Error.captureStackTrace(this,rg):this.stack=Error().stack||"",Object.setPrototypeOf(this,rg.prototype)}static createForMonitoring(e,n,r){return new rg(e,n,r)}getMonitoringData(){return{type:this.name,message:this.message,stack:this.stack,timestamp:Date.now(),...this.data}}getSimplifiedData(){return{type:this.name,message:this.message,userId:this.data.userId,sessionId:this.data.sessionId,page:this.data.page}}toString(){return this.message}toJSON(){return this.getMonitoringData()}}function rv(e,n){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,n)}function ry(e,n){return function(r,i){n(r,i,e)}}class rb extends rm{constructor(e){super(),this.opts=e,this.handleError=async e=>{await this.errorHandler.handle(e),this.emit(e)},this.getErrorHandler=()=>this.errorHandler,this.getActionRequired=e=>rf.getActionRequired(e),this.createMonitoringError=e=>{var n,r;let i=this.buildEnhancedMessage(e),o={page:null==(n=e.metadata.context)?void 0:n.page,userId:e.metadata.userId,sessionId:e.metadata.sessionId,requestId:e.metadata.requestId,context:e.metadata.context,severity:e.severity,category:e.metadata.service||"unknown",code:e.code,originalMessage:null==(r=e.originalError)?void 0:r.message};return rg.createForMonitoring(e.code,i,o)},this.buildEnhancedMessage=e=>{let n=[],r=e.severity.toUpperCase();n.push(`[${r}]: ${e.message}`),e.metadata.service&&n.push(`category=${e.metadata.service}`);let i=new Date(e.metadata.timestamp||Date.now()),o=i.getFullYear()+"-"+String(i.getMonth()+1).padStart(2,"0")+"-"+String(i.getDate()).padStart(2,"0")+" "+String(i.getHours()).padStart(2,"0")+":"+String(i.getMinutes()).padStart(2,"0")+":"+String(i.getSeconds()).padStart(2,"0");if(n.push(`time=${o}`),e.metadata&&Object.keys(e.metadata).length>0){let r=this.stringifyMetadata(e.metadata);r&&"{}"!==r&&n.push(`metadata=${r}`)}return n.join(" | ")},this.stringifyMetadata=e=>{if(!e||"object"!=typeof e)return"{}";let n=new Set(["timestamp","stack"]),r={};for(let[i,o]of Object.entries(e))n.has(i)||null==o||(r[i]=o);try{return JSON.stringify(r)}catch{return"{}"}},this.initializeReporters=()=>{this.options.enableConsoleReporter&&this.errorHandler.addReporter(new rp),this.options.enableHttpReporter&&this.options.httpReporterEndpoint&&this.errorHandler.addReporter(new rh({endpoint:this.options.httpReporterEndpoint}))},this.options={enableConsoleReporter:this.opts.enableDebugMode,enableHttpReporter:!1,enableErrorLogging:this.opts.enableDebugMode,enableErrorReporting:!0},this.errorHandler=new rd(this.options),this.initializeReporters()}}function rw(e,n){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,n)}function rO(e,n){return function(r,i){n(r,i,e)}}rb=function(e,n,r,i){var o,s=arguments.length,a=s<3?n:null===i?i=Object.getOwnPropertyDescriptor(n,r):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)a=Reflect.decorate(e,n,r,i);else for(var c=e.length-1;c>=0;c--)(o=e[c])&&(a=(s<3?o(a):s>3?o(n,r,a):o(n,r))||a);return s>3&&a&&Object.defineProperty(n,r,a),a}([eV(),ry(0,eU(nd.IOptions)),ry(0,ez()),rv("design:type",Function),rv("design:paramtypes",["undefined"==typeof IOptions?Object:IOptions])],rb);class r_{constructor(e,n,r){this.request=e,this.errorManager=n,this.opts=r,this.emitter=new nl,this.conversationSessionId="",this.abortController=null,this._queryId="",this._lastQueryId="",this.setSessionId=e=>{this.conversationSessionId=e},this.setQueryId=e=>{this._queryId=e},this.setLastQueryId=e=>{this._lastQueryId=e},this.abort=e=>{var n;null==(n=this.abortController)||n.abort(e),this.abortController&&(this.abortController=null)},this.checkIsRepeat=()=>{let e=!!this.lastQueryId&&this.lastQueryId===this.queryId;return e&&this.opts.enableDebugMode&&console.warn("重复的completed查询被忽略:",this.queryId),e},this.onData=e=>{this.emitter.emit("data",e)},this.onCompleted=e=>{this.emitter.emit("completed",e)},this.onHangup=e=>{this.emitter.emit("hangup",e)},this.onTimeout=e=>{this.emitter.emit("timeout",e)},this.onInstructionReceived=e=>{this.emitter.emit("instruction_received",e)},this.onUsageQuotaReached=e=>{this.emitter.emit("usage_quota_reached",e)},this.onQuotaExpired=e=>{this.emitter.emit("quota_expired",e)},this._dispose=()=>{this.abort(),this.conversationSessionId="",this._queryId="",this._lastQueryId=""}}get sessionId(){return this.conversationSessionId}get queryId(){return this._queryId}get lastQueryId(){return this._lastQueryId}}r_=function(e,n,r,i){var o,s=arguments.length,a=s<3?n:null===i?i=Object.getOwnPropertyDescriptor(n,r):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)a=Reflect.decorate(e,n,r,i);else for(var c=e.length-1;c>=0;c--)(o=e[c])&&(a=(s<3?o(a):s>3?o(n,r,a):o(n,r))||a);return s>3&&a&&Object.defineProperty(n,r,a),a}([eV(),rO(0,eU(nd.CommonRequest)),rO(1,eU(nd.ErrorManager)),rO(2,eU(nd.IOptions)),rO(2,ez()),rw("design:type",Function),rw("design:paramtypes",[void 0===nX?Object:nX,void 0===rb?Object:rb,"undefined"==typeof IResolvedOptions?Object:IResolvedOptions])],r_),et("../../node_modules/core-js/modules/es.array.reduce.js");let rR=[{pattern:/客悦\s*one/gi,replacement:"客悦\xb7ONE"},{pattern:/\bSARS\b/gi,replacement:"SaaS"},{pattern:/\bSAS\b/gi,replacement:"SaaS"}],rS=function(e){let n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:rR;return n.reduce((e,n)=>{let{pattern:r,replacement:i}=n;return e.replace(r,i)},e)},rT={enableDebugMode:!1,minSplitLen:5,ttsModel:"02-turbo",env:"production",asrVad:600,interruptible:!0,rendererMode:"cloud",autoChromaKey:!0,typeDelay:163,enTypeDelay:45,inactivityPrompt:"您这么久没讲话,是不是有其它事情要忙,那我先挂断了",getMountContainer:()=>document.body,hotWordReplacementRules:rR,rtcID:"appreimunmd7utp"},rE={randomUUID:"undefined"!=typeof crypto&&crypto.randomUUID&&crypto.randomUUID.bind(crypto)},rM=new Uint8Array(16),rx=[];for(let e=0;e<256;++e)rx.push((e+256).toString(16).slice(1));let rC=function(n,r,i){if(rE.randomUUID&&!r&&!n)return rE.randomUUID();var o=n,s=i;let a=(o=o||{}).random??o.rng?.()??function(){if(!e){if("undefined"==typeof crypto||!crypto.getRandomValues)throw Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");e=crypto.getRandomValues.bind(crypto)}return e(rM)}();if(a.length<16)throw Error("Random bytes length must be >= 16");if(a[6]=15&a[6]|64,a[8]=63&a[8]|128,r){if((s=s||0)<0||s+16>r.length)throw RangeError(`UUID byte range ${s}:${s+15} is out of buffer bounds`);for(let e=0;e<16;++e)r[s+e]=a[e];return r}return function(e,n=0){return(rx[e[n+0]]+rx[e[n+1]]+rx[e[n+2]]+rx[e[n+3]]+"-"+rx[e[n+4]]+rx[e[n+5]]+"-"+rx[e[n+6]]+rx[e[n+7]]+"-"+rx[e[n+8]]+rx[e[n+9]]+"-"+rx[e[n+10]]+rx[e[n+11]]+rx[e[n+12]]+rx[e[n+13]]+rx[e[n+14]]+rx[e[n+15]]).toLowerCase()}(a)};class rj{constructor(e,n){this.opts=n,this.emitter=new nl,this.id="",this.text="",this.update=e=>{let{id:n,...r}=e;n?this.id=n:this.id||(this.id=rC()),Object.assign(this,r)},this.toJSON=()=>({id:this.id,type:this.type,text:this.text}),this.type=e.type,this.update(e)}}let rI=()=>{};class rB extends rj{constructor(e,n){super({...e,type:"client"},n),this.opts=n,this.appendText=e=>{this.text=e,this.emitter.emit("content_change",{mod:"text",content:e,completed:!0}).catch(rI)},this.dispose=()=>{},this.interrupt=()=>{}}static create(e){return new rB({},e)}}var rk=et("../../node_modules/p-queue/node_modules/eventemitter3/index.js"),rA=et.n(rk);class rP extends Error{constructor(e){super(e),this.name="TimeoutError"}}class rN extends Error{constructor(e){super(),this.name="AbortError",this.message=e}}let rL=e=>void 0===globalThis.DOMException?new rN(e):new DOMException(e),rD=e=>{let n=void 0===e.reason?rL("This operation was aborted."):e.reason;return n instanceof Error?n:rL(n)};class rF{#J=[];enqueue(e,n){let r={priority:(n={priority:0,...n}).priority,id:n.id,run:e};if(0===this.size||this.#J[this.size-1].priority>=n.priority)return void this.#J.push(r);let i=function(e,n,r){let i=0,o=e.length;for(;o>0;){let s=Math.trunc(o/2),a=i+s;0>=r(e[a],n)?(i=++a,o-=s+1):o=s}return i}(this.#J,r,(e,n)=>n.priority-e.priority);this.#J.splice(i,0,r)}setPriority(e,n){let r=this.#J.findIndex(n=>n.id===e);if(-1===r)throw ReferenceError(`No promise function with the id "${e}" exists in the queue.`);let[i]=this.#J.splice(r,1);this.enqueue(i.run,{priority:n,id:e})}dequeue(){let e=this.#J.shift();return e?.run}filter(e){return this.#J.filter(n=>n.priority===e.priority).map(e=>e.run)}get size(){return this.#J.length}}class rU extends rA(){#K;#Q;#Y=0;#Z;#ee;#et=0;#en;#er;#J;#ei;#eo=0;#es;#ea;#ec;#el=1n;timeout;constructor(e){if(super(),!("number"==typeof(e={carryoverConcurrencyCount:!1,intervalCap:Number.POSITIVE_INFINITY,interval:0,concurrency:Number.POSITIVE_INFINITY,autoStart:!0,queueClass:rF,...e}).intervalCap&&e.intervalCap>=1))throw TypeError(`Expected \`intervalCap\` to be a number from 1 and up, got \`${e.intervalCap?.toString()??""}\` (${typeof e.intervalCap})`);if(void 0===e.interval||!(Number.isFinite(e.interval)&&e.interval>=0))throw TypeError(`Expected \`interval\` to be a finite number >= 0, got \`${e.interval?.toString()??""}\` (${typeof e.interval})`);this.#K=e.carryoverConcurrencyCount,this.#Q=e.intervalCap===Number.POSITIVE_INFINITY||0===e.interval,this.#Z=e.intervalCap,this.#ee=e.interval,this.#J=new e.queueClass,this.#ei=e.queueClass,this.concurrency=e.concurrency,this.timeout=e.timeout,this.#ec=!0===e.throwOnTimeout,this.#ea=!1===e.autoStart}get #eu(){return this.#Q||this.#Y<this.#Z}get #ed(){return this.#eo<this.#es}#ep(){this.#eo--,this.#eh(),this.emit("next")}#ef(){this.#em(),this.#eg(),this.#er=void 0}get #ev(){let e=Date.now();if(void 0===this.#en){let n=this.#et-e;if(!(n<0))return void 0===this.#er&&(this.#er=setTimeout(()=>{this.#ef()},n)),!0;this.#Y=this.#K?this.#eo:0}return!1}#eh(){if(0===this.#J.size)return this.#en&&clearInterval(this.#en),this.#en=void 0,this.emit("empty"),0===this.#eo&&this.emit("idle"),!1;if(!this.#ea){let e=!this.#ev;if(this.#eu&&this.#ed){let n=this.#J.dequeue();return!!n&&(this.emit("active"),n(),e&&this.#eg(),!0)}}return!1}#eg(){this.#Q||void 0!==this.#en||(this.#en=setInterval(()=>{this.#em()},this.#ee),this.#et=Date.now()+this.#ee)}#em(){0===this.#Y&&0===this.#eo&&this.#en&&(clearInterval(this.#en),this.#en=void 0),this.#Y=this.#K?this.#eo:0,this.#ey()}#ey(){for(;this.#eh(););}get concurrency(){return this.#es}set concurrency(e){if(!("number"==typeof e&&e>=1))throw TypeError(`Expected \`concurrency\` to be a number from 1 and up, got \`${e}\` (${typeof e})`);this.#es=e,this.#ey()}async #eb(e){return new Promise((n,r)=>{e.addEventListener("abort",()=>{r(e.reason)},{once:!0})})}setPriority(e,n){this.#J.setPriority(e,n)}async add(e,n={}){return n.id??=(this.#el++).toString(),n={timeout:this.timeout,throwOnTimeout:this.#ec,...n},new Promise((r,i)=>{this.#J.enqueue(async()=>{this.#eo++,this.#Y++;try{n.signal?.throwIfAborted();let i=e({signal:n.signal});n.timeout&&(i=function(e,n){let r,i,{milliseconds:o,fallback:s,message:a,customTimers:c={setTimeout,clearTimeout}}=n,l=new Promise((l,u)=>{if("number"!=typeof o||1!==Math.sign(o))throw TypeError(`Expected \`milliseconds\` to be a positive number, got \`${o}\``);if(n.signal){let{signal:e}=n;e.aborted&&u(rD(e)),i=()=>{u(rD(e))},e.addEventListener("abort",i,{once:!0})}if(o===Number.POSITIVE_INFINITY)return void e.then(l,u);let d=new rP;r=c.setTimeout.call(void 0,()=>{if(s){try{l(s())}catch(e){u(e)}return}"function"==typeof e.cancel&&e.cancel(),!1===a?l():a instanceof Error?u(a):(d.message=a??`Promise timed out after ${o} milliseconds`,u(d))},o),(async()=>{try{l(await e)}catch(e){u(e)}})()}).finally(()=>{l.clear(),i&&n.signal&&n.signal.removeEventListener("abort",i)});return l.clear=()=>{c.clearTimeout.call(void 0,r),r=void 0},l}(Promise.resolve(i),{milliseconds:n.timeout})),n.signal&&(i=Promise.race([i,this.#eb(n.signal)]));let o=await i;r(o),this.emit("completed",o)}catch(e){if(e instanceof rP&&!n.throwOnTimeout)return void r();i(e),this.emit("error",e)}finally{this.#ep()}},n),this.emit("add"),this.#eh()})}async addAll(e,n){return Promise.all(e.map(async e=>this.add(e,n)))}start(){return this.#ea&&(this.#ea=!1,this.#ey()),this}pause(){this.#ea=!0}clear(){this.#J=new this.#ei}async onEmpty(){0!==this.#J.size&&await this.#ew("empty")}async onSizeLessThan(e){this.#J.size<e||await this.#ew("next",()=>this.#J.size<e)}async onIdle(){(0!==this.#eo||0!==this.#J.size)&&await this.#ew("idle")}async #ew(e,n){return new Promise(r=>{let i=()=>{(!n||n())&&(this.off(e,i),r())};this.on(e,i)})}get size(){return this.#J.size}sizeBy(e){return this.#J.filter(e).length}get pending(){return this.#eo}get isPaused(){return this.#ea}}class rH{constructor(e){this.id=rC(),this.createdAt=Date.now(),this.updatedAt=Date.now(),this.emitter=new nl,this.getConfig=()=>({...this.config}),this.updateConfig=e=>{this.config={...this.config,...e},this.updatedAt=Date.now()},this.toJSON=()=>({id:this.id,mod:this.mod,config:this.getConfig(),createdAt:this.createdAt,updatedAt:this.updatedAt}),this.updateTimestamp=()=>{this.updatedAt=Date.now()},this._dispose=()=>{this.emitter.clearListeners()},this.config={...e},this.config.timestamp||(this.config.timestamp=this.createdAt)}}var rq=et("../../node_modules/typewriter-effect/dist/core.js"),rV=et.n(rq);let rX=e=>/[\u3400-\u4DBF\u4E00-\u9FFF\uF900-\uFAFF\u3000-\u303F]/.test(e);class rW extends rH{get mod(){return"text"}static fromSnapshot(e){return new rW(e.config)}static fromString(e){let n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return new rW({content:e,...n})}setTargetElement(e){this.targetElement=e}isEmpty(){return!this.config.content}constructor(...e){super(...e),this.typewriter=null,this.targetElement=null,this.index=0,this.stopTypewriter=()=>{this.typewriter&&(this.typewriter.stop(),this.typewriter=null)},this.runTask=()=>new Promise((e,n)=>{if(this.ensureTarget(),this.isEmpty())return void e({mod:"text",content:""});try{var r,i,o,s,a;let n=null!=(o=null==(r=this.config.typewriterOptions)?void 0:r.delay)?o:163,c=null!=(s=null==(i=this.config.typewriterOptions)?void 0:i.enDelay)?s:n;this.typewriter=new(rV())(this.targetElement,{autoStart:!0,loop:!1,...this.config.typewriterOptions,delay:0,onCreateTextNode:e=>{let n=this.index===this.config.content.length-1;return this.emitter.emit("data",{char:e,index:this.index++,done:n}),document.createTextNode(e)}});let l=[],u="",d=null;for(let e of Array.from(this.config.content)){let n=rX(e);null===d||n===d?u+=e:(l.push({s:u,cn:d}),u=e),d=n}u&&l.push({s:u,cn:d});let p=this.typewriter;if(0===l.length)p=p.changeDelay(n).typeString(this.config.content);else for(let e=0;e<l.length;e++){let{s:r,cn:i}=l[e];if(0===e){let e=null!=(a=r[0])?a:"",o=r.slice(1);p=p.typeString(e),o&&(p=p.changeDelay(i?n:c).typeString(o));continue}p=p.changeDelay(i?n:c).typeString(r)}p.callFunction(()=>{e({mod:"text",content:this.config.content})}).start()}catch(e){n(e)}}),this.dispose=()=>{this._dispose(),this.stopTypewriter(),this.targetElement=null,this.index=0},this.interrupt=()=>{this.stopTypewriter()},this.ensureTarget=()=>{if(this.targetElement)return;let e=document.createElement("span");e.className="text-content-typewriter",this.targetElement=e}}}class r$ extends rH{get mod(){return"image"}static fromSnapshot(e){return new r$(e.config)}static fromSrc(e){let n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return new r$({src:e,...n})}isEmpty(){return!this.config.src}ensureImageElement(){if(this.imgElement)return this.imgElement;let e=document.createElement("img");return this.imgElement=e,e}constructor(...e){super(...e),this.imgElement=null,this.setTargetElement=e=>{this.imgElement=e},this.runTask=()=>new Promise((e,n)=>{var r;if(this.isEmpty())return void e({mod:"image",src:""});let i=this.ensureImageElement(),o=()=>{e({mod:"image",...this.config}),i.removeEventListener("load",o)},s=()=>{n(Error(`Failed to load image: ${this.config.src}`)),i.removeEventListener("error",s)};i.addEventListener("load",o,{once:!0}),i.addEventListener("error",s,{once:!0}),i.alt=null!=(r=this.config.alt)?r:"",this.config.width&&(i.width=this.config.width),this.config.height&&(i.height=this.config.height),i.src=this.config.src}),this.dispose=()=>{this._dispose(),this.imgElement&&(this.imgElement.src="",this.imgElement=null)},this.interrupt=()=>{}}}class rz extends rH{get mod(){return"video"}static fromSnapshot(e){return new rz(e.config)}static fromSrc(e){let n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return new rz({src:e,...n})}isEmpty(){return!this.config.src}ensureVideoElement(){if(this.videoElement)return this.videoElement;let e=document.createElement("video");return e.muted=!0,e.playsInline=!0,this.videoElement=e,e}constructor(...e){super(...e),this.videoElement=null,this.setTargetElement=e=>{this.videoElement=e},this.runTask=()=>new Promise((e,n)=>{if(this.isEmpty())return void e({mod:"video",src:""});let r=this.ensureVideoElement(),i=()=>{e({mod:"video",...this.config}),r.removeEventListener("loadedmetadata",i)},o=()=>{n(Error(`Failed to load video: ${this.config.src}`)),r.removeEventListener("error",o)};r.addEventListener("loadedmetadata",i,{once:!0}),r.addEventListener("error",o,{once:!0}),this.config.poster&&(r.poster=this.config.poster),this.config.preload&&(r.preload=this.config.preload),this.config.width&&(r.width=this.config.width),this.config.height&&(r.height=this.config.height),r.src=this.config.src,r.load()}),this.dispose=()=>{this._dispose(),this.videoElement&&(this.videoElement.src="",this.videoElement.load(),this.videoElement=null)},this.interrupt=()=>{}}}let rG={preserveOrder:!1,attributeNamePrefix:"@_",attributesGroupName:!1,textNodeName:"#text",ignoreAttributes:!0,removeNSPrefix:!1,allowBooleanAttributes:!1,parseTagValue:!0,parseAttributeValue:!1,trimValues:!0,cdataPropName:!1,numberParseOptions:{hex:!0,leadingZeros:!0,eNotation:!0},tagValueProcessor:function(e,n){return n},attributeValueProcessor:function(e,n){return n},stopNodes:[],alwaysCreateTextNode:!1,isArray:()=>!1,commentPropName:!1,unpairedTags:[],processEntities:!0,htmlEntities:!1,ignoreDeclaration:!1,ignorePiTags:!1,transformTagName:!1,transformAttributeName:!1,updateTag:function(e,n,r){return e},captureMetaData:!1},rJ=":A-Za-z_\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD",rK=RegExp("^"+("["+rJ+"]["+rJ)+"\\-.\\d\\u00B7\\u0300-\\u036F\\u203F-\\u2040]*$");function rQ(e,n){let r=[],i=n.exec(e);for(;i;){let o=[];o.startIndex=n.lastIndex-i[0].length;let s=i.length;for(let e=0;e<s;e++)o.push(i[e]);r.push(o),i=n.exec(e)}return r}let rY=function(e){return null!=rK.exec(e)};n="function"!=typeof Symbol?"@@xmlMetadata":Symbol("XML Node Metadata");class rZ{constructor(e){this.tagname=e,this.child=[],this[":@"]={}}add(e,n){"__proto__"===e&&(e="#__proto__"),this.child.push({[e]:n})}addChild(e,r){"__proto__"===e.tagname&&(e.tagname="#__proto__"),e[":@"]&&Object.keys(e[":@"]).length>0?this.child.push({[e.tagname]:e.child,":@":e[":@"]}):this.child.push({[e.tagname]:e.child}),void 0!==r&&(this.child[this.child.length-1][n]={startIndex:r})}static getMetaDataSymbol(){return n}}let r0=(e,n)=>{for(;n<e.length&&/\s/.test(e[n]);)n++;return n};function r1(e,n,r){let i="",o=e[n];if('"'!==o&&"'"!==o)throw Error(`Expected quoted string, found "${o}"`);for(n++;n<e.length&&e[n]!==o;)i+=e[n],n++;if(e[n]!==o)throw Error(`Unterminated ${r} value`);return[++n,i]}function r2(e,n,r){for(let i=0;i<n.length;i++)if(n[i]!==e[r+i+1])return!1;return!0}function r3(e){if(rY(e))return e;throw Error(`Invalid entity name ${e}`)}let r6=/^[-+]?0x[a-fA-F0-9]+$/,r5=/^([\-\+])?(0*)([0-9]*(\.[0-9]*)?)$/,r4={hex:!0,leadingZeros:!0,decimalPoint:".",eNotation:!0},r8=/^([-+])?(0*)(\d*(\.\d*)?[eE][-\+]?\d+)$/;class r9{constructor(e){var n;this.options=e,this.currentNode=null,this.tagsNodeStack=[],this.docTypeEntities={},this.lastEntities={apos:{regex:/&(apos|#39|#x27);/g,val:"'"},gt:{regex:/&(gt|#62|#x3E);/g,val:">"},lt:{regex:/&(lt|#60|#x3C);/g,val:"<"},quot:{regex:/&(quot|#34|#x22);/g,val:'"'}},this.ampEntity={regex:/&(amp|#38|#x26);/g,val:"&"},this.htmlEntities={space:{regex:/&(nbsp|#160);/g,val:" "},cent:{regex:/&(cent|#162);/g,val:"\xa2"},pound:{regex:/&(pound|#163);/g,val:"\xa3"},yen:{regex:/&(yen|#165);/g,val:"\xa5"},euro:{regex:/&(euro|#8364);/g,val:"€"},copyright:{regex:/&(copy|#169);/g,val:"\xa9"},reg:{regex:/&(reg|#174);/g,val:"\xae"},inr:{regex:/&(inr|#8377);/g,val:"₹"},num_dec:{regex:/&#([0-9]{1,7});/g,val:(e,n)=>String.fromCodePoint(Number.parseInt(n,10))},num_hex:{regex:/&#x([0-9a-fA-F]{1,6});/g,val:(e,n)=>String.fromCodePoint(Number.parseInt(n,16))}},this.addExternalEntities=r7,this.parseXml=io,this.parseTextData=ie,this.resolveNameSpace=it,this.buildAttributesMap=ii,this.isItStopNode=il,this.replaceEntitiesValue=ia,this.readStopNodeData=ip,this.saveTextToParentTag=ic,this.addChild=is,this.ignoreAttributesFn="function"==typeof(n=this.options.ignoreAttributes)?n:Array.isArray(n)?e=>{for(let r of n)if("string"==typeof r&&e===r||r instanceof RegExp&&r.test(e))return!0}:()=>!1}}function r7(e){let n=Object.keys(e);for(let r=0;r<n.length;r++){let i=n[r];this.lastEntities[i]={regex:RegExp("&"+i+";","g"),val:e[i]}}}function ie(e,n,r,i,o,s,a){if(void 0!==e&&(this.options.trimValues&&!i&&(e=e.trim()),e.length>0)){a||(e=this.replaceEntitiesValue(e));let i=this.options.tagValueProcessor(n,e,r,o,s);return null==i?e:typeof i!=typeof e||i!==e?i:this.options.trimValues||e.trim()===e?ih(e,this.options.parseTagValue,this.options.numberParseOptions):e}}function it(e){if(this.options.removeNSPrefix){let n=e.split(":"),r="/"===e.charAt(0)?"/":"";if("xmlns"===n[0])return"";2===n.length&&(e=r+n[1])}return e}let ir=RegExp("([^\\s=]+)\\s*(=\\s*(['\"])([\\s\\S]*?)\\3)?","gm");function ii(e,n,r){if(!0!==this.options.ignoreAttributes&&"string"==typeof e){let r=rQ(e,ir),i=r.length,o={};for(let e=0;e<i;e++){let i=this.resolveNameSpace(r[e][1]);if(this.ignoreAttributesFn(i,n))continue;let s=r[e][4],a=this.options.attributeNamePrefix+i;if(i.length)if(this.options.transformAttributeName&&(a=this.options.transformAttributeName(a)),"__proto__"===a&&(a="#__proto__"),void 0!==s){this.options.trimValues&&(s=s.trim()),s=this.replaceEntitiesValue(s);let e=this.options.attributeValueProcessor(i,s,n);null==e?o[a]=s:typeof e!=typeof s||e!==s?o[a]=e:o[a]=ih(s,this.options.parseAttributeValue,this.options.numberParseOptions)}else this.options.allowBooleanAttributes&&(o[a]=!0)}if(Object.keys(o).length){if(this.options.attributesGroupName){let e={};return e[this.options.attributesGroupName]=o,e}return o}}}let io=function(e){e=e.replace(/\r\n?/g,"\n");let n=new rZ("!xml"),r=n,i="",o="";for(let s=0;s<e.length;s++)if("<"===e[s])if("/"===e[s+1]){let n=iu(e,">",s,"Closing Tag is not closed."),a=e.substring(s+2,n).trim();if(this.options.removeNSPrefix){let e=a.indexOf(":");-1!==e&&(a=a.substr(e+1))}this.options.transformTagName&&(a=this.options.transformTagName(a)),r&&(i=this.saveTextToParentTag(i,r,o));let c=o.substring(o.lastIndexOf(".")+1);if(a&&-1!==this.options.unpairedTags.indexOf(a))throw Error(`Unpaired tag can not be used as closing tag: </${a}>`);let l=0;c&&-1!==this.options.unpairedTags.indexOf(c)?(l=o.lastIndexOf(".",o.lastIndexOf(".")-1),this.tagsNodeStack.pop()):l=o.lastIndexOf("."),o=o.substring(0,l),r=this.tagsNodeStack.pop(),i="",s=n}else if("?"===e[s+1]){let n=id(e,s,!1,"?>");if(!n)throw Error("Pi Tag is not closed.");if(i=this.saveTextToParentTag(i,r,o),this.options.ignoreDeclaration&&"?xml"===n.tagName||this.options.ignorePiTags);else{let e=new rZ(n.tagName);e.add(this.options.textNodeName,""),n.tagName!==n.tagExp&&n.attrExpPresent&&(e[":@"]=this.buildAttributesMap(n.tagExp,o,n.tagName)),this.addChild(r,e,o,s)}s=n.closeIndex+1}else if("!--"===e.substr(s+1,3)){let n=iu(e,"--\x3e",s+4,"Comment is not closed.");if(this.options.commentPropName){let a=e.substring(s+4,n-2);i=this.saveTextToParentTag(i,r,o),r.add(this.options.commentPropName,[{[this.options.textNodeName]:a}])}s=n}else if("!D"===e.substr(s+1,2)){let n=function(e,n){let r={};if("O"===e[n+3]&&"C"===e[n+4]&&"T"===e[n+5]&&"Y"===e[n+6]&&"P"===e[n+7]&&"E"===e[n+8]){n+=9;let i=1,o=!1,s=!1,a="";for(;n<e.length;n++)if("<"!==e[n]||s)if(">"===e[n]){if(s?"-"===e[n-1]&&"-"===e[n-2]&&(s=!1,i--):i--,0===i)break}else"["===e[n]?o=!0:e[n];else{if(o&&r2(e,"!ENTITY",n)){let i,o;n+=7,[i,o,n]=function(e,n){n=r0(e,n);let r="";for(;n<e.length&&!/\s/.test(e[n])&&'"'!==e[n]&&"'"!==e[n];)r+=e[n],n++;if(r3(r),n=r0(e,n),"SYSTEM"===e.substring(n,n+6).toUpperCase())throw Error("External entities are not supported");if("%"===e[n])throw Error("Parameter entities are not supported");let i="";return[n,i]=r1(e,n,"entity"),[r,i,--n]}(e,n+1),-1===o.indexOf("&")&&(r[i]={regx:RegExp(`&${i};`,"g"),val:o})}else if(o&&r2(e,"!ELEMENT",n)){let{index:r}=function(e,n){n=r0(e,n);let r="";for(;n<e.length&&!/\s/.test(e[n]);)r+=e[n],n++;if(!r3(r))throw Error(`Invalid element name: "${r}"`);n=r0(e,n);let i="";if("E"===e[n]&&r2(e,"MPTY",n))n+=4;else if("A"===e[n]&&r2(e,"NY",n))n+=2;else if("("===e[n]){for(n++;n<e.length&&")"!==e[n];)i+=e[n],n++;if(")"!==e[n])throw Error("Unterminated content model")}else throw Error(`Invalid Element Expression, found "${e[n]}"`);return{elementName:r,contentModel:i.trim(),index:n}}(e,(n+=8)+1);n=r}else if(o&&r2(e,"!ATTLIST",n))n+=8;else if(o&&r2(e,"!NOTATION",n)){let{index:r}=function(e,n){n=r0(e,n);let r="";for(;n<e.length&&!/\s/.test(e[n]);)r+=e[n],n++;r3(r),n=r0(e,n);let i=e.substring(n,n+6).toUpperCase();if("SYSTEM"!==i&&"PUBLIC"!==i)throw Error(`Expected SYSTEM or PUBLIC, found "${i}"`);n+=i.length,n=r0(e,n);let o=null,s=null;if("PUBLIC"===i)[n,o]=r1(e,n,"publicIdentifier"),n=r0(e,n),('"'===e[n]||"'"===e[n])&&([n,s]=r1(e,n,"systemIdentifier"));else if("SYSTEM"===i&&([n,s]=r1(e,n,"systemIdentifier"),!s))throw Error("Missing mandatory system identifier for SYSTEM notation");return{notationName:r,publicIdentifier:o,systemIdentifier:s,index:--n}}(e,(n+=9)+1);n=r}else if(r2(e,"!--",n))s=!0;else throw Error("Invalid DOCTYPE");i++}if(0!==i)throw Error("Unclosed DOCTYPE")}else throw Error("Invalid Tag instead of DOCTYPE");return{entities:r,i:n}}(e,s);this.docTypeEntities=n.entities,s=n.i}else if("!["===e.substr(s+1,2)){let n=iu(e,"]]>",s,"CDATA is not closed.")-2,a=e.substring(s+9,n);i=this.saveTextToParentTag(i,r,o);let c=this.parseTextData(a,r.tagname,o,!0,!1,!0,!0);void 0==c&&(c=""),this.options.cdataPropName?r.add(this.options.cdataPropName,[{[this.options.textNodeName]:a}]):r.add(this.options.textNodeName,c),s=n+2}else{let a=id(e,s,this.options.removeNSPrefix),c=a.tagName,l=a.rawTagName,u=a.tagExp,d=a.attrExpPresent,p=a.closeIndex;this.options.transformTagName&&(c=this.options.transformTagName(c)),r&&i&&"!xml"!==r.tagname&&(i=this.saveTextToParentTag(i,r,o,!1));let h=r;h&&-1!==this.options.unpairedTags.indexOf(h.tagname)&&(r=this.tagsNodeStack.pop(),o=o.substring(0,o.lastIndexOf("."))),c!==n.tagname&&(o+=o?"."+c:c);let f=s;if(this.isItStopNode(this.options.stopNodes,o,c)){let n="";if(u.length>0&&u.lastIndexOf("/")===u.length-1)"/"===c[c.length-1]?(c=c.substr(0,c.length-1),o=o.substr(0,o.length-1),u=c):u=u.substr(0,u.length-1),s=a.closeIndex;else if(-1!==this.options.unpairedTags.indexOf(c))s=a.closeIndex;else{let r=this.readStopNodeData(e,l,p+1);if(!r)throw Error(`Unexpected end of ${l}`);s=r.i,n=r.tagContent}let i=new rZ(c);c!==u&&d&&(i[":@"]=this.buildAttributesMap(u,o,c)),n&&(n=this.parseTextData(n,c,o,!0,d,!0,!0)),o=o.substr(0,o.lastIndexOf(".")),i.add(this.options.textNodeName,n),this.addChild(r,i,o,f)}else{if(u.length>0&&u.lastIndexOf("/")===u.length-1){"/"===c[c.length-1]?(c=c.substr(0,c.length-1),o=o.substr(0,o.length-1),u=c):u=u.substr(0,u.length-1),this.options.transformTagName&&(c=this.options.transformTagName(c));let e=new rZ(c);c!==u&&d&&(e[":@"]=this.buildAttributesMap(u,o,c)),this.addChild(r,e,o,f),o=o.substr(0,o.lastIndexOf("."))}else{let e=new rZ(c);this.tagsNodeStack.push(r),c!==u&&d&&(e[":@"]=this.buildAttributesMap(u,o,c)),this.addChild(r,e,o,f),r=e}i="",s=p}}else i+=e[s];return n.child};function is(e,n,r,i){this.options.captureMetaData||(i=void 0);let o=this.options.updateTag(n.tagname,r,n[":@"]);!1===o||("string"==typeof o&&(n.tagname=o),e.addChild(n,i))}let ia=function(e){if(this.options.processEntities){for(let n in this.docTypeEntities){let r=this.docTypeEntities[n];e=e.replace(r.regx,r.val)}for(let n in this.lastEntities){let r=this.lastEntities[n];e=e.replace(r.regex,r.val)}if(this.options.htmlEntities)for(let n in this.htmlEntities){let r=this.htmlEntities[n];e=e.replace(r.regex,r.val)}e=e.replace(this.ampEntity.regex,this.ampEntity.val)}return e};function ic(e,n,r,i){return e&&(void 0===i&&(i=0===n.child.length),void 0!==(e=this.parseTextData(e,n.tagname,r,!1,!!n[":@"]&&0!==Object.keys(n[":@"]).length,i))&&""!==e&&n.add(this.options.textNodeName,e),e=""),e}function il(e,n,r){let i="*."+r;for(let r in e){let o=e[r];if(i===o||n===o)return!0}return!1}function iu(e,n,r,i){let o=e.indexOf(n,r);if(-1!==o)return o+n.length-1;throw Error(i)}function id(e,n,r,i=">"){let o=function(e,n,r=">"){let i,o="";for(let s=n;s<e.length;s++){let n=e[s];if(i)n===i&&(i="");else if('"'===n||"'"===n)i=n;else if(n===r[0]){if(!r[1])return{data:o,index:s};else if(e[s+1]===r[1])return{data:o,index:s}}else" "===n&&(n=" ");o+=n}}(e,n+1,i);if(!o)return;let s=o.data,a=o.index,c=s.search(/\s/),l=s,u=!0;-1!==c&&(l=s.substring(0,c),s=s.substring(c+1).trimStart());let d=l;if(r){let e=l.indexOf(":");-1!==e&&(u=(l=l.substr(e+1))!==o.data.substr(e+1))}return{tagName:l,tagExp:s,closeIndex:a,attrExpPresent:u,rawTagName:d}}function ip(e,n,r){let i=r,o=1;for(;r<e.length;r++)if("<"===e[r])if("/"===e[r+1]){let s=iu(e,">",r,`${n} is not closed`);if(e.substring(r+2,s).trim()===n&&0==--o)return{tagContent:e.substring(i,r),i:s};r=s}else if("?"===e[r+1])r=iu(e,"?>",r+1,"StopNode is not closed.");else if("!--"===e.substr(r+1,3))r=iu(e,"--\x3e",r+3,"StopNode is not closed.");else if("!["===e.substr(r+1,2))r=iu(e,"]]>",r,"StopNode is not closed.")-2;else{let i=id(e,r,">");i&&((i&&i.tagName)===n&&"/"!==i.tagExp[i.tagExp.length-1]&&o++,r=i.closeIndex)}}function ih(e,n,r){if(n&&"string"==typeof e){let n=e.trim();return"true"===n||"false"!==n&&function(e,n={}){if(n=Object.assign({},r4,n),!e||"string"!=typeof e)return e;let r=e.trim();if(void 0!==n.skipLike&&n.skipLike.test(r))return e;{if("0"===e)return 0;if(n.hex&&r6.test(r)){var i,o=r,s=16;if(parseInt)return parseInt(o,16);if(Number.parseInt)return Number.parseInt(o,s);if(window&&window.parseInt)return window.parseInt(o,s);throw Error("parseInt, Number.parseInt, window.parseInt are not supported")}if(-1!==r.search(/.+[eE].+/))return function(e,n,r){if(!r.eNotation)return e;let i=n.match(r8);if(!i)return e;{let o=i[1]||"",s=-1===i[3].indexOf("e")?"E":"e",a=i[2],c=o?e[a.length+1]===s:e[a.length]===s;return a.length>1&&c?e:1===a.length&&(i[3].startsWith(`.${s}`)||i[3][0]===s)?Number(n):r.leadingZeros&&!c?Number(n=(i[1]||"")+i[3]):e}}(e,r,n);let a=r5.exec(r);if(!a)return e;{let o=a[1]||"",s=a[2],c=((i=a[3])&&-1!==i.indexOf(".")&&("."===(i=i.replace(/0+$/,""))?i="0":"."===i[0]?i="0"+i:"."===i[i.length-1]&&(i=i.substring(0,i.length-1))),i),l=o?"."===e[s.length+1]:"."===e[s.length];if(!n.leadingZeros&&(s.length>1||1===s.length&&!l))return e;{let i=Number(r),a=String(i);if(0===i)return i;if(-1!==a.search(/[eE]/))if(n.eNotation)return i;else return e;if(-1!==r.indexOf("."))if("0"===a)return i;else if(a===c)return i;else if(a===`${o}${c}`)return i;else return e;let l=s?c:r;return s?l===a||o+l===a?i:e:l===a||l===o+a?i:e}}}}(e,r)}return void 0!==e?e:""}let im=rZ.getMetaDataSymbol(),ig={allowBooleanAttributes:!1,unpairedTags:[]};function iv(e,n){n=Object.assign({},ig,n);let r=[],i=!1,o=!1;"\uFEFF"===e[0]&&(e=e.substr(1));for(let s=0;s<e.length;s++)if("<"===e[s]&&"?"===e[s+1]){if(s+=2,(s=ib(e,s)).err)return s}else if("<"===e[s]){let a=s;if("!"===e[++s]){s=iw(e,s);continue}{let c=!1;"/"===e[s]&&(c=!0,s++);let l="";for(;s<e.length&&">"!==e[s]&&" "!==e[s]&&" "!==e[s]&&"\n"!==e[s]&&"\r"!==e[s];s++)l+=e[s];if("/"===(l=l.trim())[l.length-1]&&(l=l.substring(0,l.length-1),s--),!rY(l)){let n;return iR("InvalidTag",0===l.trim().length?"Invalid space after '<'.":"Tag '"+l+"' is an invalid name.",iS(e,s))}let u=function(e,n){let r="",i="",o=!1;for(;n<e.length;n++){if('"'===e[n]||"'"===e[n])""===i?i=e[n]:i!==e[n]||(i="");else if(">"===e[n]&&""===i){o=!0;break}r+=e[n]}return""===i&&{value:r,index:n,tagClosed:o}}(e,s);if(!1===u)return iR("InvalidAttr","Attributes for '"+l+"' have open quote.",iS(e,s));let d=u.value;if(s=u.index,"/"===d[d.length-1]){let r=s-d.length,o=i_(d=d.substring(0,d.length-1),n);if(!0!==o)return iR(o.err.code,o.err.msg,iS(e,r+o.err.line));i=!0}else if(c)if(!u.tagClosed)return iR("InvalidTag","Closing tag '"+l+"' doesn't have proper closing.",iS(e,s));else{if(d.trim().length>0)return iR("InvalidTag","Closing tag '"+l+"' can't have attributes or invalid starting.",iS(e,a));if(0===r.length)return iR("InvalidTag","Closing tag '"+l+"' has not been opened.",iS(e,a));let n=r.pop();if(l!==n.tagName){let r=iS(e,n.tagStartPos);return iR("InvalidTag","Expected closing tag '"+n.tagName+"' (opened in line "+r.line+", col "+r.col+") instead of closing tag '"+l+"'.",iS(e,a))}0==r.length&&(o=!0)}else{let c=i_(d,n);if(!0!==c)return iR(c.err.code,c.err.msg,iS(e,s-d.length+c.err.line));if(!0===o)return iR("InvalidXml","Multiple possible root nodes found.",iS(e,s));-1!==n.unpairedTags.indexOf(l)||r.push({tagName:l,tagStartPos:a}),i=!0}for(s++;s<e.length;s++)if("<"===e[s])if("!"===e[s+1]){s=iw(e,++s);continue}else if("?"===e[s+1]){if((s=ib(e,++s)).err)return s}else break;else if("&"===e[s]){let n=function(e,n){if(";"===e[++n])return -1;if("#"===e[n]){var r=++n;let i=/\d/;for("x"===e[r]&&(r++,i=/[\da-fA-F]/);r<e.length;r++){if(";"===e[r])return r;if(!e[r].match(i))break}return -1}let i=0;for(;n<e.length;n++,i++)if(!e[n].match(/\w/)||!(i<20)){if(";"===e[n])break;return -1}return n}(e,s);if(-1==n)return iR("InvalidChar","char '&' is not expected.",iS(e,s));s=n}else if(!0===o&&!iy(e[s]))return iR("InvalidXml","Extra text at the end",iS(e,s));"<"===e[s]&&s--}}else{if(iy(e[s]))continue;return iR("InvalidChar","char '"+e[s]+"' is not expected.",iS(e,s))}return i?1==r.length?iR("InvalidTag","Unclosed tag '"+r[0].tagName+"'.",iS(e,r[0].tagStartPos)):!(r.length>0)||iR("InvalidXml","Invalid '"+JSON.stringify(r.map(e=>e.tagName),null,4).replace(/\r?\n/g,"")+"' found.",{line:1,col:1}):iR("InvalidXml","Start tag expected.",1)}function iy(e){return" "===e||" "===e||"\n"===e||"\r"===e}function ib(e,n){let r=n;for(;n<e.length;n++)if("?"==e[n]||" "==e[n]){let i=e.substr(r,n-r);if(n>5&&"xml"===i)return iR("InvalidXml","XML declaration allowed only at the start of the document.",iS(e,n));if("?"!=e[n]||">"!=e[n+1])continue;n++;break}return n}function iw(e,n){if(e.length>n+5&&"-"===e[n+1]&&"-"===e[n+2]){for(n+=3;n<e.length;n++)if("-"===e[n]&&"-"===e[n+1]&&">"===e[n+2]){n+=2;break}}else if(e.length>n+8&&"D"===e[n+1]&&"O"===e[n+2]&&"C"===e[n+3]&&"T"===e[n+4]&&"Y"===e[n+5]&&"P"===e[n+6]&&"E"===e[n+7]){let r=1;for(n+=8;n<e.length;n++)if("<"===e[n])r++;else if(">"===e[n]&&0==--r)break}else if(e.length>n+9&&"["===e[n+1]&&"C"===e[n+2]&&"D"===e[n+3]&&"A"===e[n+4]&&"T"===e[n+5]&&"A"===e[n+6]&&"["===e[n+7]){for(n+=8;n<e.length;n++)if("]"===e[n]&&"]"===e[n+1]&&">"===e[n+2]){n+=2;break}}return n}let iO=RegExp("(\\s*)([^\\s=]+)(\\s*=)?(\\s*(['\"])(([\\s\\S])*?)\\5)?","g");function i_(e,n){let r=rQ(e,iO),i={};for(let e=0;e<r.length;e++){if(0===r[e][1].length)return iR("InvalidAttr","Attribute '"+r[e][2]+"' has no space in starting.",iT(r[e]));if(void 0!==r[e][3]&&void 0===r[e][4])return iR("InvalidAttr","Attribute '"+r[e][2]+"' is without value.",iT(r[e]));if(void 0===r[e][3]&&!n.allowBooleanAttributes)return iR("InvalidAttr","boolean attribute '"+r[e][2]+"' is not allowed.",iT(r[e]));let o=r[e][2];if(!rY(o))return iR("InvalidAttr","Attribute '"+o+"' is an invalid name.",iT(r[e]));if(i.hasOwnProperty(o))return iR("InvalidAttr","Attribute '"+o+"' is repeated.",iT(r[e]));i[o]=1}return!0}function iR(e,n,r){return{err:{code:e,msg:n,line:r.line||r,col:r.col}}}function iS(e,n){let r=e.substring(0,n).split(/\r?\n/);return{line:r.length,col:r[r.length-1].length+1}}function iT(e){return e.startIndex+e[1].length}class iE{constructor(e){this.externalEntities={},this.options=Object.assign({},rG,e)}parse(e,n){if("string"==typeof e);else if(e.toString)e=e.toString();else throw Error("XML data is accepted in String or Bytes[] form.");if(n){!0===n&&(n={});let r=iv(e,n);if(!0!==r)throw Error(`${r.err.msg}:${r.err.line}:${r.err.col}`)}let r=new r9(this.options);r.addExternalEntities(this.externalEntities);let i=r.parseXml(e);return this.options.preserveOrder||void 0===i?i:function e(n,r,i){let o,s={};for(let a=0;a<n.length;a++){let c=n[a],l=function(e){let n=Object.keys(e);for(let e=0;e<n.length;e++){let r=n[e];if(":@"!==r)return r}}(c),u="";if(u=void 0===i?l:i+"."+l,l===r.textNodeName)void 0===o?o=c[l]:o+=""+c[l];else if(void 0===l)continue;else if(c[l]){let n=e(c[l],r,u),i=function(e,n){let{textNodeName:r}=n,i=Object.keys(e).length;return 0===i||1===i&&(!!e[r]||"boolean"==typeof e[r]||0===e[r])}(n,r);void 0!==c[im]&&(n[im]=c[im]),c[":@"]?function(e,n,r,i){if(n){let o=Object.keys(n),s=o.length;for(let a=0;a<s;a++){let s=o[a];i.isArray(s,r+"."+s,!0,!0)?e[s]=[n[s]]:e[s]=n[s]}}}(n,c[":@"],u,r):1!==Object.keys(n).length||void 0===n[r.textNodeName]||r.alwaysCreateTextNode?0===Object.keys(n).length&&(r.alwaysCreateTextNode?n[r.textNodeName]="":n=""):n=n[r.textNodeName],void 0!==s[l]&&s.hasOwnProperty(l)?(Array.isArray(s[l])||(s[l]=[s[l]]),s[l].push(n)):r.isArray(l,u,i)?s[l]=[n]:s[l]=n}}return"string"==typeof o?o.length>0&&(s[r.textNodeName]=o):void 0!==o&&(s[r.textNodeName]=o),s}(i,this.options)}addEntity(e,n){if(-1!==n.indexOf("&"))throw Error("Entity value can't have '&'");if(-1!==e.indexOf("&")||-1!==e.indexOf(";"))throw Error("An entity must be set without '&' and ';'. Eg. use '#xD' for '
'");if("&"===n)throw Error("An entity with value '&' is not permitted");this.externalEntities[e]=n}static getMetaDataSymbol(){return rZ.getMetaDataSymbol()}}let iM={validate:iv};class ix{constructor(){this.isXml=e=>ix.isXml(e),this.parseXmlOrText=e=>{try{let n=this.xmlParser.parse(e);if(Array.isArray(n)&&!n.length);else if(Array.isArray(n)&&n.length)return n;return e}catch(n){return e}},this.hasMixContentByParsedXml=e=>Array.isArray(e),this.xmlParser=new iE({preserveOrder:!0,ignoreAttributes:!1,attributeNamePrefix:"",textNodeName:"#text",alwaysCreateTextNode:!0})}static #k=this.isTextNode=e=>"text"in e;static #G=this.isImageNode=e=>"image"in e;static #eO=this.isVideoNode=e=>"video"in e;static #e_=this.isXml=e=>"string"==typeof e&&!0===iM.validate(e,{allowBooleanAttributes:!0})}class iC extends rj{constructor(e,n){super({...e,type:"aiWorker"},n),this.opts=n,this.contents=[],this.addContentRenderTask=e=>{iC.isTextContent(e)?(e.emitter.on("data",e=>{this.emitter.emit("content_change",{mod:"text",content:e.char,completed:e.done})}),this.queue.add(e.runTask).finally(()=>{e.dispose()})):iC.isImageContent(e)?this.queue.add(e.runTask).then(e=>{e&&this.emitter.emit("content_change",{mod:"image",content:e.src,completed:!0})}).finally(()=>{e.dispose()}):iC.isVideoContent(e)&&this.queue.add(e.runTask).then(e=>{e&&this.emitter.emit("content_change",{mod:"video",content:e.src,completed:!0})}).finally(()=>{e.dispose()})},this.addAllContents=e=>{for(let n of(this.contents=e,e))this.addContentRenderTask(n)},this.createContentsFromXmlString=e=>{let n=this.customXmlParser.parseXmlOrText(e);return this.customXmlParser.hasMixContentByParsedXml(n)?n[0].root[0].content.map(e=>ix.isTextNode(e)?rW.fromString(e.text[0]["#text"],{typewriterOptions:{delay:this.opts.typeDelay,enDelay:this.opts.enTypeDelay}}):ix.isImageNode(e)?r$.fromSrc(e.image[0]["#text"]):ix.isVideoNode(e)?rz.fromSrc(e.video[0]["#text"]):null).filter(Boolean):[]},this.appendText=e=>{if(this.customXmlParser.isXml(e)){let n=this.createContentsFromXmlString(e);this.addAllContents(n)}else{let n=rW.fromString(e,{typewriterOptions:{delay:this.opts.typeDelay,enDelay:this.opts.enTypeDelay}});this.addContentRenderTask(n),this.contents.push(n)}},this.dispose=()=>{this.queue.removeAllListeners(),this.contents=[]},this.interrupt=()=>{for(let e of this.contents)e.interrupt();this.queue.clear(),this.emitter.emit("interrupt")},this.bindEvents=()=>{this.queue.on("empty",()=>{this.emitter.emit("queue_empty")})},this.queue=new rU({concurrency:1}),this.customXmlParser=new ix,this.bindEvents()}get fulltext(){return this.contents.map(e=>iC.isTextContent(e)?e.getConfig().content:"").join("")}static #k=this.create=e=>new iC({},e);static #G=this.isAllTextContents=e=>e.every(e=>"text"===e.mod);static #eO=this.isTextContent=e=>e instanceof rW&&"text"===e.mod;static #e_=this.isImageContent=e=>e instanceof r$&&"image"===e.mod;static #eR=this.isVideoContent=e=>e instanceof rz&&"video"===e.mod}function ij(e,n){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,n)}function iI(e,n){return function(r,i){n(r,i,e)}}class iB{constructor(e){var n=this;this.opts=e,this.beans=[],this.currentConversation=null,this.aiWorkerConversationFormatters=[],this.add=e=>{this.beans.push(e)},this.addBySnapshot=function(){let e,r=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};switch(r.type){case"client":e=new rB(r,n.opts);break;case"aiWorker":e=new iC(r,n.opts);break;default:throw Error(`Unknown conversation type: ${r.type}`)}return n.beans.push(e),e},this.setCurrentConversation=e=>{this.currentConversation=e},this.clear=()=>{this.beans=[]},this.toJSON=()=>this.beans.map(e=>e.toJSON()),this.dispose=()=>{for(let e of this.beans)e.dispose();this.beans=[],this.currentConversation=null,this.aiWorkerConversationFormatters=[]},this.registerAIWorkerConversationFormatter=e=>{this.aiWorkerConversationFormatters.push(e)},this.runAIWorkerConversationFormatters=e=>{let n=e;for(let e of this.aiWorkerConversationFormatters)n=e(n);return n},this.interruptAll=()=>{for(let e of this.beans)e.interrupt()}}get last(){var e;return null!=(e=this.beans[this.beans.length-1])?e:null}get currentClientConversation(){return iB.isClientConversation(this.currentConversation)?this.currentConversation:null}get currentAIWorkerConversation(){return iB.isAIWorkerConversation(this.currentConversation)?this.currentConversation:null}static isClientConversation(e){return(null==e?void 0:e.type)==="client"}static isAIWorkerConversation(e){return(null==e?void 0:e.type)==="aiWorker"}}iB=function(e,n,r,i){var o,s=arguments.length,a=s<3?n:null===i?i=Object.getOwnPropertyDescriptor(n,r):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)a=Reflect.decorate(e,n,r,i);else for(var c=e.length-1;c>=0;c--)(o=e[c])&&(a=(s<3?o(a):s>3?o(n,r,a):o(n,r))||a);return s>3&&a&&Object.defineProperty(n,r,a),a}([eV(),iI(0,eU(nd.IOptions)),iI(0,ez()),ij("design:type",Function),ij("design:paramtypes",["undefined"==typeof IResolvedOptions?Object:IResolvedOptions])],iB);var ik=et("../../node_modules/abort-signal-polyfill/dist/staticMethods/any.js"),iA=et("../../node_modules/abort-signal-polyfill/dist/staticMethods/timeout.js"),iP=et("../../node_modules/abort-signal-polyfill/dist/staticMethods/abort.js");let iN=(e,n)=>{e in AbortSignal||Object.defineProperty(AbortSignal,e,{value:n,configurable:!0,writable:!0})};var iL=function(){return(iL=Object.assign||function(e){for(var n,r=1,i=arguments.length;r<i;r++)for(var o in n=arguments[r])Object.prototype.hasOwnProperty.call(n,o)&&(e[o]=n[o]);return e}).apply(this,arguments)},iD=et("../../node_modules/@baidu/weirwood-perf/esm/index.js"),iF=function(){return(iF=Object.assign||function(e){for(var n,r=1,i=arguments.length;r<i;r++)for(var o in n=arguments[r])Object.prototype.hasOwnProperty.call(n,o)&&(e[o]=n[o]);return e}).apply(this,arguments)};function iU(e){var n="function"==typeof Symbol&&Symbol.iterator,r=n&&e[n],i=0;if(r)return r.call(e);if(e&&"number"==typeof e.length)return{next:function(){return e&&i>=e.length&&(e=void 0),{value:e&&e[i++],done:!e}}};throw TypeError(n?"Object is not iterable.":"Symbol.iterator is not defined.")}function iH(){for(var e=[],n=0;n<arguments.length;n++)e=e.concat(function(e,n){var r="function"==typeof Symbol&&e[Symbol.iterator];if(!r)return e;var i,o,s=r.call(e),a=[];try{for(;(void 0===n||n-- >0)&&!(i=s.next()).done;)a.push(i.value)}catch(e){o={error:e}}finally{try{i&&!i.done&&(r=s.return)&&r.call(s)}finally{if(o)throw o.error}}return a}(arguments[n]));return e}function iq(e){switch(Object.prototype.toString.call(e)){case"[object Error]":case"[object Exception]":case"[object DOMException]":return!0;default:return e instanceof Error}}function iV(e){return"[object ErrorEvent]"===Object.prototype.toString.call(e)}function iX(e){return void 0===e}function iW(e){return"function"==typeof e}function i$(e){return"[object String]"===Object.prototype.toString.call(e)}function iz(e){return"[object Number]"===Object.prototype.toString.call(e)}function iG(e){return"[object Array]"===Object.prototype.toString.call(e)}function iJ(e){return"[object Object]"===Object.prototype.toString.call(e)}function iK(e){if(!iJ(e))return!1;for(var n in e)if(e.hasOwnProperty(n))return!1;return!0}var iQ={};function iY(){return"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:void 0!==et.g?et.g:"undefined"!=typeof self?self:iQ}var iZ=iY(),i0={wrap:function(){return function(){}},report:!1,collectWindowErrors:!1,computeStackTrace:!1,remoteFetching:!1,linesOfContext:!1,extendToAsynchronousCallbacks:!1},i1=[].slice,i2=/^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?(.*)$/;function i3(e,n){return Object.prototype.hasOwnProperty.call(e,n)}function i6(){return"undefined"==typeof document||null==document.location?"":document.location.href}i0.wrap=function(e){return function(){try{return e.apply(this,arguments)}catch(e){throw i0.report(e),e}}},i0.report=function(){var e,n,r,i,o=[],s=null,a=null;function c(e,n,r,i,s,a){var c=null;if(!n||i0.collectWindowErrors){for(var l in o)if(i3(o,l))try{o[l](e,n,r,i,s,a)}catch(e){c=e}if(c)throw c}}function l(n,r,i,o,s){var l=null;if(s=iV(s)?s.error:s,n=iV(n)?n.message:n,a)i0.computeStackTrace.augmentStackTraceWithInitialElement(a,r,i,n),d();else if(s&&iq(s))(l=i0.computeStackTrace(s)).mechanism="onerror",c(l,!0,s,r,i,o);else{var u,p={url:r,line:i,column:o},h=n;if("[object String]"===({}).toString.call(n)){var f=n.match(i2);f&&(u=f[1],h=f[2])}p.func=i0.computeStackTrace.guessFunctionName(p.url,p.line),p.context=i0.computeStackTrace.gatherContext(p.url,p.line),c(l={name:u,message:h,mode:"onerror",mechanism:"onerror",stack:[iF(iF({},p),{url:p.url||i6()})]},!0,null,r,i,o)}return!!e&&e.apply(this,arguments)}function u(e){var n=e&&(e.detail?e.detail.reason:e.reason)||e,r=i0.computeStackTrace(n);r.mechanism="onunhandledrejection",c(r,!0,n)}function d(){var e=a,n=s;a=null,s=null,c(e,!1,n)}function p(e){if(a)if(s===e)return;else d();var n=i0.computeStackTrace(e);throw a=n,s=e,setTimeout(function(){s===e&&d()},2e3*!!n.incomplete),e}return p.subscribe=function(e){o.push(e)},p.unsubscribe=function(s){for(var a=o.length-1;a>=0;--a)o[a]===s&&o.splice(a,1);0===o.length&&(n&&(iZ.onerror=e,n=!1),i&&(iZ.onunhandledrejection=r,i=!1))},p.installGlobalHandler=function(){!0!==n&&(e=iZ.onerror,iZ.onerror=l,n=!0)},p.installGlobalUnhandledRejectionHandler=function(){!0!==i&&(r=iZ.onunhandledrejection,iZ.onunhandledrejection=u,i=!0)},p}(),i0.computeStackTrace=function(){var e={};function n(n){if("string"!=typeof n)return[];if(!i3(e,n)){var r="",i="";try{i=iZ.document.domain}catch(e){}var o=/(.*)\:\/\/([^:\/]+)([:\d]*)\/{0,1}([\s\S]*)/.exec(n);o&&o[2]===i&&(r=function(e){if(!i0.remoteFetching)return"";try{var n=function(){try{return new iZ.XMLHttpRequest}catch(e){return new iZ.ActiveXObject("Microsoft.XMLHTTP")}}();return n.open("GET",e,!1),n.send(""),n.responseText}catch(e){return""}}(n)),e[n]=r?r.split("\n"):[]}return e[n]}function r(e,r){var i,o=/function ([^(]*)\(([^)]*)\)/,s=/['"]?([0-9A-Za-z$_]+)['"]?\s*[:=]\s*(function|eval|new Function)/,a="",c=n(e);if(!c.length)return"?";for(var l=0;l<10;++l)if(!iX(a=c[r-l]+a)){if(i=s.exec(a))return i[1];else if(i=o.exec(a))return i[1]}return"?"}function i(e,r){var i=n(e);if(!i.length)return null;var o=[],s=Math.floor(i0.linesOfContext/2),a=s+i0.linesOfContext%2,c=Math.max(0,r-s-1),l=Math.min(i.length,r+a-1);r-=1;for(var u=c;u<l;++u)iX(i[u])||o.push(i[u]);return o.length>0?o:null}function o(e){return e.replace(/[\-\[\]{}()*+?.,\\\^$|#]/g,"\\$&")}function s(e){return o(e).replace("<","(?:<|<)").replace(">","(?:>|>)").replace("&","(?:&|&)").replace('"','(?:"|")').replace(/\s+/g,"\\s+")}function a(e,r){for(var i,o,s=0,a=r.length;s<a;++s)if((i=n(r[s])).length&&(i=i.join("\n"),o=e.exec(i)))return{url:r[s],line:i.substring(0,o.index).split("\n").length,column:o.index-i.lastIndexOf("\n",o.index)-1};return null}function c(e,r,i){var s,a=n(r),c=RegExp("\\b"+o(e)+"\\b");return(i-=1,a&&a.length>i&&(s=c.exec(a[i])))?s.index:null}function l(e){if(!e.stack)return null;for(var n,o,s,a,l=/^\s*at (?:(.*?) ?\()?((?:file|https?|blob|chrome-extension|native|eval|webpack|<anonymous>|[a-z]:|\/).*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i,u=/^\s*(.*?)(?:\((.*?)\))?(?:^|@)((?:file|https?|blob|chrome|webpack|resource|moz-extension).*?:\/.*?|\[native code\]|[^@]*bundle)(?::(\d+))?(?::(\d+))?\s*$/i,d=/^\s*at (?:((?:\[object object\])?.+) )?\(?((?:file|ms-appx|https?|webpack|blob):.*?):(\d+)(?::(\d+))?\)?\s*$/i,p=/(\S+) line (\d+)(?: > eval line \d+)* > eval/i,h=/\((\S*)(?::(\d+))(?::(\d+))\)/,f=e.stack.split("\n"),m=[],g=/^(.*) is undefined$/.exec(e.message),v=0,y=f.length;v<y;++v){if(s=l.exec(f[v])){var b=s[2]&&0===s[2].indexOf("native");s[2]&&0===s[2].indexOf("eval")&&(o=h.exec(s[2]))&&(s[2]=o[1]),a={url:b?null:s[2],func:s[1]||"?",args:b?[s[2]]:[],line:s[3]?+s[3]:null,column:s[4]?+s[4]:null}}else if(s=d.exec(f[v]))a={url:s[2],func:s[1]||"?",args:[],line:+s[3],column:s[4]?+s[4]:null};else{if(!(s=u.exec(f[v])))continue;s[3]&&s[3].indexOf(" > eval")>-1&&(o=p.exec(s[3]))?s[3]=o[1]:0!==v||s[5]||iX(e.columnNumber)||(m[0].column=e.columnNumber+1),a={url:s[3],func:s[1]||"?",args:s[2]?s[2].split(","):[],line:s[4]?+s[4]:null,column:s[5]?+s[5]:null}}if(!a.func&&a.line&&(a.func=r(a.url,a.line)),i0.remoteFetching&&a.url&&"blob:"===a.url.substr(0,5)){var w=new XMLHttpRequest;if(w.open("GET",a.url,!1),w.send(""),200===w.status){var O=w.responseText||"",_=(O=O.slice(-300)).match(/\/\/# sourceMappingURL=(.*)$/);if(_){var R=_[1];"~"===R.charAt(0)&&(R=("undefined"==typeof document||null==document.location?"":document.location.origin?document.location.origin:document.location.protocol+"//"+document.location.hostname+(document.location.port?":"+document.location.port:""))+R.slice(1)),a.url=R.slice(0,-4)}}}a.context=a.line?i(a.url,a.line):null,m.push(a)}return m.length?(m[0]&&m[0].line&&!m[0].column&&g&&(m[0].column=c(g[1],m[0].url,m[0].line)),{mode:"stack",name:e.name,message:e.message,stack:m}):null}function u(e,n,o,s){var a={url:n,line:o};if(a.url&&a.line){e.incomplete=!1,a.func||(a.func=r(a.url,a.line)),a.context||(a.context=i(a.url,a.line));var l=/ '([^']+)' /.exec(s);if(l&&(a.column=c(l[1],a.url,a.line)),e.stack.length>0&&e.stack[0].url===a.url){if(e.stack[0].line===a.line)return!1;else if(!e.stack[0].line&&e.stack[0].func===a.func)return e.stack[0].line=a.line,e.stack[0].context=a.context,!1}return e.stack.unshift(a),e.partial=!0,!0}return e.incomplete=!0,!1}function d(e,p){var h=null;p=null==p?0:+p;try{if(h=function(e){var n=e.stacktrace;if(n){for(var o,s=/ line (\d+).*script (?:in )?(\S+)(?:: in function (\S+))?$/i,a=/ line (\d+), column (\d+)\s*(?:in (?:<anonymous function: ([^>]+)>|([^\)]+))\((.*)\))? in (.*):\s*$/i,c=n.split("\n"),l=[],u=0;u<c.length;u+=2){var d=null;if((o=s.exec(c[u]))?d={url:o[2],line:+o[1],column:null,func:o[3],args:[]}:(o=a.exec(c[u]))&&(d={url:o[6],line:+o[1],column:+o[2],func:o[3]||o[4],args:o[5]?o[5].split(","):[]}),d){if(!d.func&&d.line&&(d.func=r(d.url,d.line)),d.line)try{d.context=i(d.url,d.line)}catch(e){}d.context||(d.context=[c[u+1]]),l.push(d)}}return l.length?{mode:"stacktrace",name:e.name,message:e.message,stack:l}:null}}(e))return h}catch(e){}try{if(h=l(e))return h}catch(e){}try{if(h=function(e){var o=e.message.split("\n");if(o.length<4)return null;var c,l=/^\s*Line (\d+) of linked script ((?:file|https?|blob)\S+)(?:: in function (\S+))?\s*$/i,u=/^\s*Line (\d+) of inline#(\d+) script in ((?:file|https?|blob)\S+)(?:: in function (\S+))?\s*$/i,d=/^\s*Line (\d+) of function script\s*$/i,p=[],h=iZ&&iZ.document&&iZ.document.getElementsByTagName("script"),f=[];for(var m in h)i3(h,m)&&!h[m].src&&f.push(h[m]);for(var g=2;g<o.length;g+=2){var v=null;if(c=l.exec(o[g]))v={url:c[2],func:c[3],args:[],line:+c[1],column:null};else if(c=u.exec(o[g])){v={url:c[3],func:c[4],args:[],line:+c[1],column:null};var y=+c[1],b=f[c[2]-1];if(b){var w=n(v.url);if(w){var O=(w=w.join("\n")).indexOf(b.innerText);O>=0&&(v.line=y+w.substring(0,O).split("\n").length)}}}else if(c=d.exec(o[g])){var _=i6().replace(/#.*$/,""),R=a(new RegExp(s(o[g+1])),[_]);v={url:_,func:"",args:[],line:R?R.line:c[1],column:null}}if(v){v.func||(v.func=r(v.url,v.line));var S=i(v.url,v.line),T=S?S[Math.floor(S.length/2)]:null;S&&T.replace(/^\s*/,"")===o[g+1].replace(/^\s*/,"")?v.context=S:v.context=[o[g+1]],p.push(v)}}return p.length?{mode:"multiline",name:e.name,message:o[0],stack:p}:null}(e))return h}catch(e){}try{if(h=function e(n,i){for(var l,p,h,f=/function\s+([_$a-zA-Z\xA0-\uFFFF][_$a-zA-Z0-9\xA0-\uFFFF]*)?\s*\(/i,m=[],g={},v=!1,y=e.caller;y&&!v;y=y.caller)if(y!==d&&y!==i0.report){if(p={url:null,func:"?",args:[],line:null,column:null},y.name?p.func=y.name:(l=f.exec(y.toString()))&&(p.func=l[1]),void 0===p.func)try{p.func=l.input.substring(0,l.input.indexOf("{"))}catch(e){}if(h=function(e){if(!iX(iZ&&iZ.document)){for(var n,r,i,c,l=[i6()],u=iZ.document.getElementsByTagName("script"),d=""+e,p=0;p<u.length;++p){var h=u[p];h.src&&l.push(h.src)}if(i=/^function(?:\s+([\w$]+))?\s*\(([\w\s,]*)\)\s*\{\s*(\S[\s\S]*\S)\s*\}\s*$/.exec(d)){var f=i[1]?"\\s+"+i[1]:"",m=i[2].split(",").join("\\s*,\\s*");r=RegExp("function"+f+"\\s*\\(\\s*"+m+"\\s*\\)\\s*{\\s*"+(n=o(i[3]).replace(/;$/,";?"))+"\\s*}")}else r=new RegExp(o(d).replace(/\s+/g,"\\s+"));if(c=a(r,l))return c;if(i=/^function on([\w$]+)\s*\(event\)\s*\{\s*(\S[\s\S]*\S)\s*\}\s*$/.exec(d)){var g=i[1];if((c=a(r=RegExp("on"+g+"=[\\'\"]\\s*"+(n=s(i[2]))+"\\s*[\\'\"]","i"),l[0]))||(c=a(r=new RegExp(n),l)))return c}return null}}(y)){p.url=h.url,p.line=h.line,"?"===p.func&&(p.func=r(p.url,p.line));var b=/ '([^']+)' /.exec(n.message||n.description);b&&(p.column=c(b[1],h.url,h.line))}g[""+y]?v=!0:g[""+y]=!0,m.push(p)}i&&m.splice(0,i);var w={mode:"callers",name:n.name,message:n.message,stack:m};return u(w,n.sourceURL||n.fileName,n.line||n.lineNumber,n.message||n.description),w}(e,p+1))return h}catch(e){}return{original:e,name:e.name,message:e.message,mode:"failed"}}return d.augmentStackTraceWithInitialElement=u,d.computeStackTraceFromStackProp=l,d.guessFunctionName=r,d.gatherContext=i,d.ofCaller=function(e){e=(null==e?0:+e)+1;try{throw Error()}catch(n){return d(n,e+1)}},d.getSource=n,d}(),i0.extendToAsynchronousCallbacks=function(){var e=function(e){var n=iZ[e];iZ[e]=function(){var e=i1.call(arguments),r=e[0];return("function"==typeof r&&(e[0]=i0.wrap(r)),n.apply)?n.apply(this,e):n(e[0],e[1])}};e("setTimeout"),e("setInterval")},i0.remoteFetching=!1,i0.collectWindowErrors=!0,i0.linesOfContext=11,i0.report;var i5=i0.report.subscribe,i4=i0.report.unsubscribe,i8=i0.report.installGlobalHandler,i9=i0.report.installGlobalUnhandledRejectionHandler,i7=i0.computeStackTrace;function oe(e,n){var r=(65535&e)+(65535&n);return(e>>16)+(n>>16)+(r>>16)<<16|65535&r}function ot(e,n,r,i,o,s){var a;return oe((a=oe(oe(n,e),oe(i,s)))<<o|a>>>32-o,r)}function on(e,n,r,i,o,s,a){return ot(n&r|~n&i,e,n,o,s,a)}function or(e,n,r,i,o,s,a){return ot(n&i|r&~i,e,n,o,s,a)}function oi(e,n,r,i,o,s,a){return ot(n^r^i,e,n,o,s,a)}function oo(e,n,r,i,o,s,a){return ot(r^(n|~i),e,n,o,s,a)}function os(e,n){e[n>>5]|=128<<n%32,e[(n+64>>>9<<4)+14]=n;var r,i,o,s,a,c=0x67452301,l=-0x10325477,u=-0x67452302,d=0x10325476;for(r=0;r<e.length;r+=16)i=c,o=l,s=u,a=d,c=on(c,l,u,d,e[r],7,-0x28955b88),d=on(d,c,l,u,e[r+1],12,-0x173848aa),u=on(u,d,c,l,e[r+2],17,0x242070db),l=on(l,u,d,c,e[r+3],22,-0x3e423112),c=on(c,l,u,d,e[r+4],7,-0xa83f051),d=on(d,c,l,u,e[r+5],12,0x4787c62a),u=on(u,d,c,l,e[r+6],17,-0x57cfb9ed),l=on(l,u,d,c,e[r+7],22,-0x2b96aff),c=on(c,l,u,d,e[r+8],7,0x698098d8),d=on(d,c,l,u,e[r+9],12,-0x74bb0851),u=on(u,d,c,l,e[r+10],17,-42063),l=on(l,u,d,c,e[r+11],22,-0x76a32842),c=on(c,l,u,d,e[r+12],7,0x6b901122),d=on(d,c,l,u,e[r+13],12,-0x2678e6d),u=on(u,d,c,l,e[r+14],17,-0x5986bc72),l=on(l,u,d,c,e[r+15],22,0x49b40821),c=or(c,l,u,d,e[r+1],5,-0x9e1da9e),d=or(d,c,l,u,e[r+6],9,-0x3fbf4cc0),u=or(u,d,c,l,e[r+11],14,0x265e5a51),l=or(l,u,d,c,e[r],20,-0x16493856),c=or(c,l,u,d,e[r+5],5,-0x29d0efa3),d=or(d,c,l,u,e[r+10],9,0x2441453),u=or(u,d,c,l,e[r+15],14,-0x275e197f),l=or(l,u,d,c,e[r+4],20,-0x182c0438),c=or(c,l,u,d,e[r+9],5,0x21e1cde6),d=or(d,c,l,u,e[r+14],9,-0x3cc8f82a),u=or(u,d,c,l,e[r+3],14,-0xb2af279),l=or(l,u,d,c,e[r+8],20,0x455a14ed),c=or(c,l,u,d,e[r+13],5,-0x561c16fb),d=or(d,c,l,u,e[r+2],9,-0x3105c08),u=or(u,d,c,l,e[r+7],14,0x676f02d9),l=or(l,u,d,c,e[r+12],20,-0x72d5b376),c=oi(c,l,u,d,e[r+5],4,-378558),d=oi(d,c,l,u,e[r+8],11,-0x788e097f),u=oi(u,d,c,l,e[r+11],16,0x6d9d6122),l=oi(l,u,d,c,e[r+14],23,-0x21ac7f4),c=oi(c,l,u,d,e[r+1],4,-0x5b4115bc),d=oi(d,c,l,u,e[r+4],11,0x4bdecfa9),u=oi(u,d,c,l,e[r+7],16,-0x944b4a0),l=oi(l,u,d,c,e[r+10],23,-0x41404390),c=oi(c,l,u,d,e[r+13],4,0x289b7ec6),d=oi(d,c,l,u,e[r],11,-0x155ed806),u=oi(u,d,c,l,e[r+3],16,-0x2b10cf7b),l=oi(l,u,d,c,e[r+6],23,0x4881d05),c=oi(c,l,u,d,e[r+9],4,-0x262b2fc7),d=oi(d,c,l,u,e[r+12],11,-0x1924661b),u=oi(u,d,c,l,e[r+15],16,0x1fa27cf8),l=oi(l,u,d,c,e[r+2],23,-0x3b53a99b),c=oo(c,l,u,d,e[r],6,-0xbd6ddbc),d=oo(d,c,l,u,e[r+7],10,0x432aff97),u=oo(u,d,c,l,e[r+14],15,-0x546bdc59),l=oo(l,u,d,c,e[r+5],21,-0x36c5fc7),c=oo(c,l,u,d,e[r+12],6,0x655b59c3),d=oo(d,c,l,u,e[r+3],10,-0x70f3336e),u=oo(u,d,c,l,e[r+10],15,-1051523),l=oo(l,u,d,c,e[r+1],21,-0x7a7ba22f),c=oo(c,l,u,d,e[r+8],6,0x6fa87e4f),d=oo(d,c,l,u,e[r+15],10,-0x1d31920),u=oo(u,d,c,l,e[r+6],15,-0x5cfebcec),l=oo(l,u,d,c,e[r+13],21,0x4e0811a1),c=oo(c,l,u,d,e[r+4],6,-0x8ac817e),d=oo(d,c,l,u,e[r+11],10,-0x42c50dcb),u=oo(u,d,c,l,e[r+2],15,0x2ad7d2bb),l=oo(l,u,d,c,e[r+9],21,-0x14792c6f),c=oe(c,i),l=oe(l,o),u=oe(u,s),d=oe(d,a);return[c,l,u,d]}function oa(e){var n,r="",i=32*e.length;for(n=0;n<i;n+=8)r+=String.fromCharCode(e[n>>5]>>>n%32&255);return r}function oc(e){var n,r=[];for(n=0,r[(e.length>>2)-1]=void 0;n<r.length;n+=1)r[n]=0;var i=8*e.length;for(n=0;n<i;n+=8)r[n>>5]|=(255&e.charCodeAt(n/8))<<n%32;return r}function ol(e){var n,r,i="0123456789abcdef",o="";for(r=0;r<e.length;r+=1)o+=i.charAt((n=e.charCodeAt(r))>>>4&15)+i.charAt(15&n);return o}function ou(e){return unescape(encodeURIComponent(e))}function od(e){var n;return oa(os(oc(n=ou(e)),8*n.length))}function op(e,n){return function(e,n){var r,i,o=oc(e),s=[],a=[];for(s[15]=a[15]=void 0,o.length>16&&(o=os(o,8*e.length)),r=0;r<16;r+=1)s[r]=0x36363636^o[r],a[r]=0x5c5c5c5c^o[r];return i=os(s.concat(oc(n)),512+8*n.length),oa(os(a.concat(i),640))}(ou(e),ou(n))}function oh(e,n,r){if(!n)return r?od(e):ol(od(e));return r?op(n,e):ol(op(n,e))}function of(e){return(e||"").replace(/#.*$/,"").replace(/\?.*$/,"")}function om(){if(!("fetch"in iY()))return!1;try{return new Headers,new Request(""),new Response,!0}catch(e){return!1}}function og(e,n){for(var r=0;r<e.length;++r)if(e[r]===n)return r;return -1}function ov(e,n,r,i){var o,s,a,c;return JSON.stringify(e,(o=n,a=[],c=[],null==(s=i)&&(s=function(e,n){return a[0]===n?"[Circular ~]":"[Circular ~."+c.slice(0,og(a,n)).join(".")+"]"}),function(e,n){if(a.length>0){var r=og(a,this);~r?a.splice(r+1):a.push(this),~r?c.splice(r,1/0,e):c.push(e),~og(a,n)&&(n=s.call(this,e,n))}else a.push(n);return null==o?n instanceof Error?function(e){var n={stack:e.stack,message:e.message,name:e.name};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(n[r]=e[r]);return n}(n):n:o.call(this,e,n)}),r)}function oy(e,n){if(Array.isArray(e))for(var r=e.length,i=0;i<r;i++)n.call(null,i,e[i]);else for(var o in e)Reflect.has(e,o)&&n.call(null,o,e[o])}function ob(e){var n={};for(var r in e)if(e.hasOwnProperty(r)){var i=e[r];n[r]=iW(i)?i():i}return n}function ow(e){return i$(e)?oO(e,40):iz(e)||"[object Boolean]"===Object.prototype.toString.call(e)||iX(e)?e+"":iJ(e)?"[Object]":iG(e)?"[Array]":iW(e)?e.name?"[Function: "+e.name+"]":"[Function]":e}function oO(e,n){return 0===n||e.length<=n?e:e.substr(0,n)+"…"}function o_(e){var n={protocol:"",host:"",path:"",relative:""};if("string"!=typeof e)return n;var r=e.match(/^(([^:\/?#]+):)?(\/\/([^\/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?$/);if(r&&r.length){var i=r[6]||"",o=r[8]||"";return{protocol:r[2]||"",host:r[4]||"",path:r[5]||"",relative:(r[5]||"")+i+o}}return n}function oR(e){var n=e.exception,r=[];return r.push("token="+n.token),r.push("type="+n.type),r.push("mechanism="+n.mechanism),r.push("value="+n.value),r.push("url="+n.url),n.stacktrace&&n.stacktrace.forEach(function(e){r.push("filename="+e.filename),r.push("lineno="+e.lineno),r.push("colno="+e.colno)}),r.join("***")}function oS(e){return e&&Array.isArray(e)&&e.length>0}function oT(e){for(var n=[],r=e.length,i=0;i<r;i++){var o=e[i];i$(o)?n.push(o.replace(/([.*+?^=!:${}()|\[\]\/\\])/g,"\\$1")):o&&o.source&&n.push(o.source)}return RegExp(n.join("|"),"i")}function oE(e,n){return!!i$(n)&&e.some(function(e){if(!e)return!1;if(i$(e))return -1!==n.indexOf(e);if("[object RegExp]"===Object.prototype.toString.call(e))try{return e.test(n)}catch(n){return console.error(e+"正则书写有误"),!1}return console.error(e+"忽略匹配项类型应该是String、RegExp"),!1})}function oM(e){return(i$(e)?e:JSON.stringify(e)).slice(0,256)}function ox(e,n,r){var i,o,s=[];if(e.stack&&e.stack.length){try{for(var a=iU(e.stack),c=a.next();!c.done;c=a.next()){var l=c.value,u=function(e,n,r){var i={filename:e.url||n,lineno:e.line,colno:e.column,function:e.func||"?"};if(r&&r.length>0){var o=oT(r).test(i.filename),s=/(Weirwood|Tracekit)/.test(i.function),a=/weirwood\-sdk/.test(i.filename);i.in_app=o,(s||a)&&(i.in_app=!1)}else i.in_app=!1;return i}(l,e.url||"",n.includePaths);s.push(u)}}catch(e){i={error:e}}finally{try{c&&!c.done&&(o=a.return)&&o.call(a)}finally{if(i)throw i.error}}if(n&&n.trimHeadFrames)for(var d=0;d<n.trimHeadFrames&&d<s.length;d++)s[d].in_app=!1}return(s=s.filter(function(e){var n,r,i;return r=-1!==(n=e.filename||"").indexOf("weirwood-sdk"),i=/captureException$/.test(n),!r&&!i})).slice(0,r)}function oC(e,n,r,i){if(null!=e){var o=e[n];return e[n]=r(o),e[n].__raven__=!0,e[n].__orig__=o,o.__raven_wrapper__=e[n],i&&i.push([e,n,o]),e[n]}}function oj(e,n,r){if(void 0===e&&(e={}),iX(n)&&!iW(e))return e;if(iW(e)&&(n=e,e=void 0),!iW(n))return n;try{if(n.__raven__)return n;if(n.__raven_wrapper__)return n.__raven_wrapper__}catch(e){return n}function i(){for(var i=[],o=0;o<arguments.length;o++)i[o]=arguments[o];var s=[],a=i.length,c=!e||e&&!1!==e.deep;for(r&&iW(r)&&r.apply(this,i);a--;)s[a]=c?oj(e,i[a]):i[a];try{return n.apply(this,s)}catch(e){throw e}}for(var o in n)n.hasOwnProperty(o)&&(i[o]=n[o]);return i.prototype=n.prototype,n.__raven_wrapper__=i,i.__raven__=!0,i.__orig__=n,i}function oI(e){return function(){for(var n=[],r=0;r<arguments.length;r++)n[r]=arguments[r];var i=n[0];return(iW(i)&&(n[0]=oj({mechanism:{type:"instrument",data:{function:(null==e?void 0:e.name)||"<anonymous>"}}},i)),e.apply)?e.apply(this,n):e(n[0],n[1])}}function oB(e,n){return function(r){if(N=void 0,L!==r){L=r;try{i=function(e){for(var n,r=[],i=0,o=0;e&&i++<5;){var s="html"===(n=function(e){if(!e||!e.tagName)return"";var n,r,i,o,s=[e.tagName.toLowerCase()];e.id&&s.push("#"+e.id);var a=e.className?e.className.split(/\s+/):[];try{for(var c=iU(a),l=c.next();!l.done;l=c.next()){var u=l.value;s.push("."+u)}}catch(e){n={error:e}}finally{try{l&&!l.done&&(r=c.return)&&r.call(c)}finally{if(n)throw n.error}}try{for(var d=iU(["type","name","title","alt"]),p=d.next();!p.done;p=d.next()){var h=p.value,f=e.getAttribute(h);f&&s.push("["+h+"="+f+"]")}}catch(e){i={error:e}}finally{try{p&&!p.done&&(o=d.return)&&o.call(d)}finally{if(i)throw i.error}}return s.join("")}(e)),a=i>1&&o+3*r.length+n.length>=80;if(s||a)break;r.push(n),o+=n.length,e=e.parentNode}return r.reverse().join(" > ")}(r.target)}catch(e){i="<unknown>"}if(i){var i,o={category:"ui."+n,message:i,name:n};"input"===n&&"password"!==i.type&&(o.data=r.target.value||""),e.captureBehavior(o)}}}}function ok(e){return function(n){try{r=n.target}catch(e){return}var r,i=r&&r.tagName;i&&("INPUT"===i||"TEXTAREA"===i||r.isContentEditable)&&(N||oB(e,"input")(n),clearTimeout(N),N=setTimeout(function(){N=void 0},1e3))}}et("../../node_modules/@baidu/weirwood-error/esm/plugins/Plugin.js");var oA=iY(),oP=[301,302,304],oN=function(){function e(n){this.name=e.id,this.options=iF({beacon:!0,console:!0,dom:!0,fetch:!0,history:!0,weirwood:!0,xhr:!0},n)}return e.prototype.setupOnce=function(e){this.client=e;var n,r,i=Object.keys(this.options);try{for(var o=iU(i),s=o.next();!s.done;s=o.next()){var a=s.value,c="instrument"+a[0].toUpperCase()+a.slice(1);this.options[a]&&this[c]&&"function"==typeof this[c]&&this[c].call(this)}}catch(e){n={error:e}}finally{try{s&&!s.done&&(r=o.return)&&r.call(o)}finally{if(n)throw n.error}}},e.prototype.instrumentDom=function(){if("document"in iY()){var e=oA.document;e.addEventListener("click",oB.call(this,this.client,"click"),!1),e.addEventListener("keypress",ok.call(this,this.client),!1)}},e.prototype.instrumentXhr=function(){var e=this.client,n=e.options,r=n.collectAutoAPIException,i=n.isApiException;if("XMLHttpRequest"in oA){var o=XMLHttpRequest.prototype,s=e._globalKey||"";oC(o,"open",function(e){return function(n,r){return i$(r)&&-1===r.indexOf(s)&&(this.__raven_xhr={method:n,url:r,status_code:null}),e.apply(this,arguments)}},e._wrappedBuiltIns),oC(o,"abort",function(e){return function(){return this.__raven_xhr&&(this.__raven_xhr.abortedFlag=!0),e.apply(this,arguments)}},e._wrappedBuiltIns),oC(o,"send",function(n){return function(){var o=this,s=arguments;function a(){if(o.__raven_xhr&&4===o.readyState){try{o.__raven_xhr.status_code=o.status}catch(e){}var n=function(e,n){if(void 0===e&&(e=""),void 0===n&&(n=""),(""===e||"text"===e)&&i$(n)&&n.length)try{return JSON.parse(n)}catch(e){return n}return"json"===e?JSON.parse(JSON.stringify(n)):""}(o.responseType,o.response);if((e.captureBehavior({type:"http",category:"xhr",data:iF(iF({},o.__raven_xhr),{response:oM(n),params:oM(s&&s[0]?s[0]:"")})}),r)&&(!o.__raven_xhr||!o.__raven_xhr.abortedFlag)){var a=!1,c=o.status>=200&&o.status<=299,l=-1!==oP.indexOf(o.status);if(c||l||(a=!0),c&&i&&iW(i)&&(a=!!i({method:o.__raven_xhr.method,url:o.responseURL,status:o.status,responseType:o.responseType,response:n})),a){var u="";iW(o.getAllResponseHeaders)&&(u=o.getAllResponseHeaders().trim().replace(/[\r\n]+/g,"***")),e.captureAPIException({url:o.responseURL||o.__raven_xhr.url,method:o.__raven_xhr.method,params:s&&s[0]?s[0]:"",status:o.status,response:(i$(n)?n:JSON.stringify(n)).slice(0,8192),responseHeaders:u,user:"",extra:"AUTO_XHR"})}}}}for(var c=["onload","onerror","onprogress"],l=0;l<c.length;l++)!function(e,n){e in n&&iW(n[e])&&oC(n,e,function(n){return oj({mechanism:{data:{function:e,handler:n&&n.name||"<anonymous>"},handled:!0,type:"instrument"}},n)})}(c[l],o);return"onreadystatechange"in o&&iW(o.onreadystatechange)?oC(o,"onreadystatechange",function(e){return oj({mechanism:{type:"instrument",data:{function:"onreadystatechange",handler:e&&e.name||"<anonymous>"}}},e,a)}):o.onreadystatechange=a,n.apply(this,arguments)}},e._wrappedBuiltIns)}},e.prototype.instrumentFetch=function(){if(om()){var e=iY(),n=this.client,r=n.options,i=r.collectAutoAPIException,o=r.isApiException,s=n._globalKey;oC(oA,"fetch",function(r){return function(){for(var a,c=Array(arguments.length),l=0;l<c.length;++l)c[l]=arguments[l];var u=c[0],d="GET";if("string"==typeof u?a=u:"Request"in e&&u instanceof e.Request?(a=u.url,(null==u?void 0:u.method)&&(d=u.method)):a=""+u,-1!==a.indexOf(s))return r.apply(this,c);c[1]&&c[1].method&&(d=c[1].method);var p={method:d,url:a,status_code:null};return r.apply(this,c).then(function(e){p.status_code=e.status;var r,s,a="";c[1]&&c[1].body&&(a=c[1].body);var l=iW(e.clone)?e.clone():null,u={type:"http",category:"fetch",data:iF(iF({},p),{params:oM(a),response:""})};if(l?l.text().then(function(e){var r;try{r=JSON.parse(e)}catch(n){r=e}u.data.response=oM(r),n.captureBehavior(u)}):n.captureBehavior(u),!i)return e;var d=!1,h=iW(e.clone)?e.clone():null,f=oP.includes(e.status);e.ok||f||(d=!0);var m={method:p.method,url:p.url,status:e.status,response:""},g=[];try{for(var v=iU(e.headers.entries()),y=v.next();!y.done;y=v.next()){var b=y.value;g.push(b[0]+": "+b[1])}}catch(e){r={error:e}}finally{try{y&&!y.done&&(s=v.return)&&s.call(v)}finally{if(r)throw r.error}}var w=iF(iF({},m),{params:a,responseHeaders:g.join("***"),user:"",extra:"AUTO_FETCH"});return h?h.text().then(function(r){var i;try{i=JSON.parse(r)}catch(e){i=r}e.ok&&iW(o)&&(d=!!o(iF(iF({},m),{response:i}))),d&&n.captureAPIException(iF(iF({},w),{response:r.slice(0,8192)}))}).catch(function(e){console.error(e)}):(e.ok&&iW(o)&&(d=!!o(m)),d&&n.captureAPIException(w)),e}).catch(function(e){throw n.captureBehavior({type:"http",category:"fetch",data:p,level:"error"}),e})}},n._wrappedBuiltIns)}},e.prototype.instrumentHistory=function(){var e,n,r,i,o=this.client;if(r=(n=(e=iY()).chrome)&&n.app&&n.app.runtime,i="history"in e&&!!e.history.pushState&&!!e.history.replaceState,!r&&i){var s=function(e,n){var r=o_(oA.location.href),i=o_(n),s=o_(e);s.path||(s=r),D=n,r.protocol===i.protocol&&r.host===i.host&&(n=i.relative),r.protocol===s.protocol&&r.host===s.host&&(e=s.relative),o.captureBehavior({category:"navigation",data:{from:e,to:n}})},a=oA.onpopstate;oA.onpopstate=function(e){var n=oA.location.href;if(s(D,n),a)return a.apply(oA,e)},oC(oA.history,"pushState",c),oC(oA.history,"replaceState",c)}function c(e){return function(){for(var n=[],r=0;r<arguments.length;r++)n[r]=arguments[r];var i=n.length>2?n[2]:void 0;return i&&s(D,String(i)),e.apply(this,n)}}},e.prototype.instrumentConsole=function(){},e.prototype.instrumentBeacon=function(){},e.id="behaviors",e}(),oL=iY(),oD=function(){function e(n){this.name=e.id,this.options=iF({active:!0},n)}return e.prototype.setupOnce=function(e){this.client=e,this.options.active&&oC(oL,"setTimeout",oI,this.client._wrappedBuiltIns)},e.id="trycatch",e}(),oF=iY(),oU=function(){function e(){this.name=e.id}return e.prototype.setupOnce=function(e){this.client=e,this.client.captureUserAgent(this.getUserAgent())},e.prototype.getUserAgent=function(){return"navigator"in oF&&"document"in oF?{url:oF.location.href,headers:{"User-Agent":oF.navigator.userAgent,Referrer:oF.document.referrer}}:{}},e.id="UserAgent",e}(),oH={collectWindowErrors:!0,collectUnhandledRejections:!0,collectResourceLoadErrors:!1,collectAutoAPIException:!0,sampleRate:1,maxUrlLength:250,maxMessageLength:0,allowDuplicates:!1,stackTraceLimit:50,behaviorLimit:10,plugins:[],ignoreErrors:[],ignoreKeys:[],whitelistUrls:[],apiWhitelistUrls:[],resourceWhitelistUrls:[],ignoreUrls:[],ignoreJsUrls:[],ignoreApiUrls:[],ignoreApiStatus:[],ignoreResourceUrls:[],maxMessagePerMinute:10,endpoint:"https://fclog.baidu.com/log/weirwood?type=error"},oq="https://dmpstatic.cdn.bcebos.com/weirwood",oV=function(){function e(e){this.options=oH,this._globalContext={env:{},user:{},session_id:""},this._globalKey="fclog.baidu.com/log",this._currentExceptionContext={},this._currentExceptionStartTime=Date.now(),this._behaviors=[],this._lastData=null,this._lastAPIData=null,this._messagesSendLastMinute=0,this._messagesSendEmptyStartTime=Date.now(),this._installed=!1,this._globalErrorHandler=null,this._fetchDefaults={method:"POST",credentials:"include",referrerPolicy:!function(){if(!om())return!1;try{return new Request("pickleRick",{referrerPolicy:"origin"}),!0}catch(e){return!1}}()?"":"origin"},this._wrappedBuiltIns=[],this._requestInfo=null,e&&this.config(e)}return e.prototype.init=function(e){return this.config(e)},e.prototype.config=function(e){this.options=iF(iF({},this.options),e),this.options.sendWindow=this.options.sendWindow||iY(),this._globalContext.session_id=this.options.uuid4();var n=this.options,r=n.token,i=n.buildid;if(!r||!i)throw Error("error: token and buildid must be provided");return this.setFilters(),this.install(),this},e.prototype.install=function(){var e,n=this;return this._installed?(console.error("error: Weirwood Error SDK has been installed and configured"),!1):(this.options.collectWindowErrors&&i8(),this.options.maxMessagePerMinute>=60&&(this.options.maxMessagePerMinute=60),this.options.collectUnhandledRejections&&i9(),this._globalErrorHandler=this._getErrorHandler().bind(this),i5(this._globalErrorHandler),this.options.collectResourceLoadErrors&&(e=function(e){if(window.performance&&window.performance.getEntriesByName){var r,i=window.performance.getEntriesByName(e.asset);i.length>0&&(r=i[0],["name","serverTiming"].forEach(function(e){delete r[e]}))}var o={mechanism:e.type,name:"ResourceError",message:e.asset,stack:[],mode:"onerror",timing:r,page:e.page,element:e.element,elementPath:e.path.slice(0,255)};n._handleStackInfo(o,{trimHeadFrames:0,mechanism:o.mechanism||"generic",includePaths:n.options.includePaths})},window.addEventListener("error",function(n){if(n&&n.target&&n.target!==window){var r,i=n.target,o=null!=(r=null==i?void 0:i.tagName)?r:"unknown tagname";if(-1!==["SCRIPT","LINK","IMG"].indexOf(o)){var s=i.src||i.href,a=window.location.href,c=function(e){for(var n=e.path||[],r="",i=0;i<n.length;i++){var o=n[i];if(o===window){r+="Window";continue}r+=o.nodeName,r+=o.id?"#"+o.id:"",r+=o.className?"."+o.className.split(" ").join("."):"",i<n.length&&(r+=" > ")}return r}(n),l={type:o,asset:of(s)===of(a)?"空资源":s,integrity:i.integrity,element:i&&i.outerHTML&&i.outerHTML.replace(/"/g,""),path:c.replace(/"/g,""),page:window.location.href.slice(0,255)};e&&e(l)}}},!0)),this._installed=!0,this.installPlugins(),this)},e.prototype.installPlugins=function(){var e,n;this.options.plugins=iH([new oN(this.options.behaviorOptions),new oD(this.options.tryCatchOptions),new oU],this.options.plugins||[]);try{for(var r=iU(this.options.plugins),i=r.next();!i.done;i=r.next())i.value.setupOnce(this)}catch(n){e={error:n}}finally{try{i&&!i.done&&(n=r.return)&&n.call(r)}finally{if(e)throw e.error}}},e.prototype.setFilters=function(){var e=this.options;e.ignoreErrors&&(e.ignoreErrors=iH([/^Script error\.?$/,/^Javascript error: Script error\.? on line 0$/,'{"isTrusted":true}','{"isTrusted":false}',"Network Error","ResizeObserver loop"],e.ignoreErrors||[])),e.ignoreJsUrls=iH(["chrome-extension","safari-extension","moz-extension",oq],e.ignoreJsUrls||[])},e.prototype._getErrorHandler=function(){var e=this;return function(n,r,i,o,s,a){if(i&&(i.stack||i.stacktrace)&&(n.originalStack=((i.stack||i.stacktrace)+"").slice(0,1e4)),n.stack&&!n.stack.length&&o&&(n.stack[0]={url:o,line:s,column:a}),!n.name&&!n.message&&"onunhandledrejection"===n.mechanism){var c=iY();n.name="unhandledrejection",n.url=n.url||c.location.href,n.message=i}e._handleStackInfo(n,{trimHeadFrames:0,mechanism:n.mechanism||"generic",includePaths:e.options.includePaths})}},e.prototype._handleStackInfo=function(e,n){var r=ox(e,n,this.options.stackTraceLimit);this._processException(e,r,n)},e.prototype._processException=function(e,n,r){var i=this.options,o=i.ignoreErrors,s=void 0===o?[]:o,a=i.ignoreKeys,c=void 0===a?[]:a,l=i.whitelistUrls,u=void 0===l?[]:l,d=i.resourceWhitelistUrls,p=void 0===d?[]:d,h=i.ignoreUrls,f=void 0===h?[]:h,m=i.ignoreJsUrls,g=void 0===m?[]:m,v=i.ignoreResourceUrls,y=void 0===v?[]:v,b=e.name,w=e.message,O=e.url,_=void 0===O?"":O,R=e.page,S=void 0===R?window.location.href:R,T=e.lineno,E=e.originalStack;if(!(s.length&&oE(s,w)||f.length&&oE(f,S))){var M=n&&n.length&&n[0].filename||_;if("ResourceError"===b){if(y.length&&oE(y,w)||p.length&&!oE(p,w))return}else if(c.length&&oE(c,b)||g.length&&oE(g,M)||u.length&&!oE(u,M))return;if(n&&n.length>0){var x=n[0].filename||"",C=-1!==x.indexOf("@baidu/weirwood-error"),j=-1!==x.indexOf(oq);if(C||j)return}if(-1===M.indexOf(oq)){var I,B=(I=void 0===T?0:T,n&&n.length?n.reverse():_?[{filename:_,lineno:I||0,in_app:!0}]:[]),k=iF(iF({},r),{exception:{type:b,value:w,originalStack:void 0===E?"":E,stacktrace:B,url:"ResourceError"===b?w:M,page:e.page,element:e.element,timing:e.timing,elementPath:e.elementPath}}),A=k.exception;null==A.type&&""===A.value&&(A.value="Unrecoverable error caught"),!k.exception.mechanism&&k.mechanism&&(k.exception.mechanism=k.mechanism,delete k.mechanism),this._send(k)}}},e.prototype.mergeGlobalContext=function(e){var n,r,i,o=iY();e.env=iF(iF(iF({},this._globalContext.env),e.env),{network:null==(i=o.navigator.connection)?void 0:i.effectiveType,windowHeight:(o.document.documentElement||o.document.body).clientHeight,windowWidth:(o.document.documentElement||o.document.body).clientWidth,documentTitle:o.document.title});try{for(var s=iU(Object.keys(this._currentExceptionContext)),a=s.next();!a.done;a=s.next()){var c=a.value;e.env[c]=this._currentExceptionContext[c]}}catch(e){n={error:e}}finally{try{a&&!a.done&&(r=s.return)&&r.call(s)}finally{if(n)throw n.error}}e.env["session:duration"]=Date.now()-this._currentExceptionStartTime,this._globalContext.user&&(e.user=this._globalContext.user),this._globalContext.session_id&&(e.session_id=this._globalContext.session_id)},e.prototype._send=function(e){var n={request:this._requestInfo};if(iX(e.trimHeadFrames)||delete e.trimHeadFrames,e=iF(iF({},n),e),this.mergeGlobalContext(e),this._behaviors&&this._behaviors.length>0){var r=[].slice.call(this._behaviors,0);this.options.behaviorDataCallback&&(r=this.options.behaviorDataCallback(r)),e.behaviors=r}var i=this.options;if(i.token&&(e.token=i.token),i.buildid&&(e.buildid=i.buildid),Object.keys(e=this._sanitizeData(e)).forEach(function(n){(null==e[n]||""===e[n]||iK(e[n]))&&delete e[n]}),iW(i.dataCallback)&&(e=i.dataCallback(e)),!(!e||iK(e))){var o=Date.now()-this._messagesSendEmptyStartTime,s=this._messagesSendLastMinute>this.options.maxMessagePerMinute;if(o<6e4){if(s)return}else this._messagesSendEmptyStartTime=Date.now(),this._messagesSendLastMinute=1;"number"==typeof i.sampleRate?Math.random()<i.sampleRate&&(this._sendProcessedPayload(e),this._messagesSendLastMinute+=1):(this._sendProcessedPayload(e),this._messagesSendLastMinute+=1)}},e.prototype.isSetup=function(){return this._installed},e.prototype._trimPacket=function(e){var n,r,i=this.options.maxUrlLength||0,o=this.options.maxMessageLength||0;if(e.exception&&(e.exception.value=oO(e.exception.value,o)),e.request){var s=iY();e.request.url=oO(s.location.href,i);var a=e.request.headers.Referrer;e.request.headers.Referrer=oO(a,i)}if(e.behaviors&&e.behaviors.length){var c=["url","to","from"];try{for(var l=iU(e.behaviors),u=l.next();!u.done;u=l.next()){var d=u.value;!function(e){var n=e.data||{},r=function(e){n.hasOwnProperty(e)&&c.forEach(function(r){e===r&&(n[e]=oO(n[e],i))})};for(var o in n)r(o)}(d)}}catch(e){n={error:e}}finally{try{u&&!u.done&&(r=l.return)&&r.call(l)}finally{if(n)throw n.error}}}return e},e.prototype._sendProcessedPayload=function(e,n){var r,i=this,o=this.options;if(e=this._trimPacket(e),!this.options.allowDuplicates&&this._isRepeatData(e))return void console.warn("Weirwood error SDK dropped repeat event:",e);var s=o.issueGroupby;s&&iW(s)&&(r=s(e.exception)),r&&i$(r)?(e.fingerprint=r.substr(0,255),e.event_id=oh(e.fingerprint)):e.event_id=oh(oR(e)),e.data_id=oh(function(e){var n=oR(e),r=[],i=e.request,o=e.env,s=e.behaviors;if(!i)return JSON.stringify(e);var a=i.headers,c=i.url;return r.push("Referrer="+a.Referrer),r.push("ua="+a["User-Agent"]),r.push("url="+c),oy(o,function(e,n){"session:duration"!==e&&r.push(e+"="+n)}),oy(s,function(e){r.push("behavior.category="+e.category),r.push("behavior.name="+e.name),r.push("behavior.message="+e.message)}),n+r.join("***")}(e)),e.version=this.options.version||"",e.sdkTimestamp=Date.now(),this._lastData=e;var a={weirwood_version:this.options.version||""};(o.transport||this._makeRequest).call(this,{url:this.options.endpoint,auth:a,data:e,options:o,onSuccess:function(){i._resetBackoff(),n&&n()},onError:function(e){e.request&&i._setBackoffState(e.request),e=e||Error("Raven send failed (no additional details provided)"),n&&n(e)}})},e.prototype._makeRequest=function(e){var n,r,i=this,o=e.url,s=null,a={};e.options.headers&&(s=ob(e.options.headers)),e.options.fetchParameters&&(a=ob(e.options.fetchParameters));var c=this.options.sendWindow;if(om()){a.body=ov(e.data);var l=iF(iF({},this._fetchDefaults),a);if(s){var u=new Headers;try{for(var d=iU(Object.keys(s)),p=d.next();!p.done;p=d.next()){var h=p.value;u.append(h,s[h])}}catch(e){n={error:e}}finally{try{p&&!p.done&&(r=d.return)&&r.call(d)}finally{if(n)throw n.error}}u.append("Content-Type","text/plain"),l.headers=u}return c.fetch(o,l).then(function(n){if(n.ok)e.onSuccess&&e.onSuccess(),i._resetBackoff();else{var r=Error("Weirwood error SDK error code: "+n.status);r.request=n,e.onError&&e.onError(r)}}).catch(function(){e.onError&&e.onError(Error("Weirwood error SDK error code: network unavailable")),i._resetBackoff()})}var f=c.XMLHttpRequest&&new c.XMLHttpRequest;f&&("withCredentials"in f||"undefined"!=typeof XDomainRequest)&&("withCredentials"in f?f.onreadystatechange=function(){if(4!==f.readyState)return void i._resetBackoff();if(200===f.status)e.onSuccess&&e.onSuccess();else if(e.onError){i._resetBackoff();var n=Error("Weirwood error SDK error code: "+f.status);n.request=f,e.onError(n)}}:(f=new XDomainRequest,o=o.replace(/^https?:/,""),e.onSuccess&&(f.onload=e.onSuccess),e.onError&&(f.onerror=function(){var n=Error("Weirwood error SDK error code: XDomainRequest");n.request=f,e.onError(n)})),f.open("POST",o),s&&oy(s,function(e,n){f.setRequestHeader(e,n)}),f.send(ov(e.data)))},e.prototype._sanitizeData=function(e){var n=this.options.sanitizeKeys||[];if(n.length){if(!Array.isArray(n)||Array.isArray(n)&&0===n.length)return e;var r,i=oT(n);try{r=JSON.parse(ov(e))}catch(n){return e}return function e(n){return Array.isArray(n)?n.map(function(n){return e(n)}):iJ(n)?Object.keys(n).reduce(function(r,o){return i.test(o)?r[o]="********":r[o]=e(n[o]),r},{}):n}(r)}return e},e.prototype.captureUserAgent=function(e){this._requestInfo=e},e.prototype.captureException=function(e,n){if(n||(n={trimHeadFrames:0,includePaths:[],mechanism:"generic",message:""}),iq(e));else if(iV(e))e=e.error;else if(iJ(e))e=Error((n=this._getCaptureExceptionOptionsFromPlainObject(n,e)).message);else{if(r=e,"[object DOMException]"!==Object.prototype.toString.call(r))return this.captureMessage(e,iF(iF({},n),{stacktrace:!0,trimHeadFrames:n.trimHeadFrames+1}));var r,i=e.name||"DOMException",o=e.message?i+": "+e.message:i;return this.captureMessage(o,n)}try{n=iF({trimHeadFrames:0,mechanism:"generic",includePaths:this.options.includePaths||[]},n);var s=i7(e);this._handleStackInfo(s,n)}catch(n){if(e!==n)throw n}return this},e.prototype._isRepeatData=function(e){var n=this._lastData,r=e.exception,i=n?n.exception:{};return r.mechanism===i.mechanism&&r.type===i.type&&r.value===i.value&&r.url===i.url&&(0===r.stacktrace.length&&0===i.stacktrace.length||function(e,n){if(oS(e)&&oS(n)){var r,i,o=e.length;if(o!==n.length)return!1;for(var s=0;s<o;s++){if(r=e[s],i=n[s],r.filename!==i.filename||r.lineno!==i.lineno||r.colno!==i.colno||r.function!==i.function)return!1}return!0}return!1}(r.stacktrace,i.stacktrace))},e.prototype._resetBackoff=function(){this._currentExceptionStartTime=Date.now(),this._currentExceptionContext={}},e.prototype._setBackoffState=function(e){console.log(e)},e.prototype.captureMessage=function(e,n){void 0===n&&(n={});var r,i,o=this.options,s=o.ignoreErrors||[],a=o.ignoreKeys||[],c=o.whitelistUrls||[],l=o.ignoreUrls||[],u=o.ignoreJsUrls||[];if(!(s.length&&oE(s,e))){try{throw Error(e)}catch(e){i=e}var d=i7(i),p=Array.isArray(d.stack)&&d.stack[1];(null==(r=null==p?void 0:p.func)?void 0:r.indexOf("captureException"))!==-1&&(p=d.stack[2]);var h=p&&p.url||"";if(!(l.length&&oE(l,window.location.href)||a.length&&oE(a,i.name)||u.length&&oE(u,h))&&(!c.length||oE(c,h))){n=iF(iF({},n),{trimHeadFrames:0,includePaths:o.includePaths}),n.trimHeadFrames+=1;var f=ox(d,n),m={exception:{mechanism:"manual",type:i.name,value:i.message,stacktrace:f.slice(1).reverse(),url:h}};return this._send(m),this}}},e.prototype.captureAPIException=function(e){var n,r=this,i=iY(),o=this.options,s=o.ignoreUrls,a=void 0===s?[]:s,c=o.ignoreApiUrls,l=void 0===c?[]:c,u=o.ignoreApiStatus,d=void 0===u?[]:u,p=o.buildid,h=o.token,f=o.version,m=o.apiWhitelistUrls;if(!(e.url&&e.method&&!iX(e.status)))return void console.error("API异常参数至少需要包含 method、url、status 参数。");if(!(a.length&&oE(a,i.location.href)||l.length&&oE(l,e.url))&&(!m.length||oE(m,e.url))&&(!d.length||-1===d.indexOf(Number(e.status)))){var g=iF(iF({},e),{type:"APIError"}),v={request:{headers:{"User-Agent":i.navigator.userAgent},url:i.location.href},exception:g,buildid:p,token:h,version:f||""},y=this.options;if(iW(y.dataCallback)&&(v=y.dataCallback(v)),!(!v||iK(v))){this.mergeGlobalContext(v);var b=this.options.issueGroupby;if((b&&iW(b)&&(n=b(v.exception)),n&&i$(n))?(v.fingerprint=n.substr(0,255),v.event_id=oh(v.fingerprint)):v.event_id=oh(e.method+"***"+function(e){if(!i$(e))return"";var n=e.split("?");return n[1]?(n[1]=n[1].replace(/\d+/g,"*").replace(/[\u4e00-\u9fa5]+/gi,"*"),n.join("?")):e}(e.url)),v.data_id=oh(ov(v)),this._lastAPIData!==v.data_id){this._lastAPIData=v.data_id;var w=function(){var e;((null==(e=r.options.globalOptions)?void 0:e.transport)||r._makeRequest).call(r,{url:r.options.endpoint,data:v,options:{},onSuccess:function(){},onError:function(){}})};"number"==typeof y.sampleRate?Math.random()<y.sampleRate&&w():w()}}}},e.prototype.captureEvent=function(){},e.prototype.afterLoad=function(){var e=iY().RavenConfig;e&&this.init(e)},e.prototype._getCaptureExceptionOptionsFromPlainObject=function(e,n){var r=Object.keys(n).sort(),i=iF(iF({},e),{message:"Non-Error exception captured with keys: "+function(e,n){if(void 0===n&&(n=40),iz(e)||i$(e))return e.toString();if(!iG(e))return"";if(0===(e=e.filter(function(e){return i$(e)})).length)return"[object has no keys]";if(n=iz(n)?n:40,e[0].length>=n)return e[0];for(var r=e.length;r>0;r--){var i=e.slice(0,r).join(", ");if(!(i.length>n)){if(r===e.length)return i;return i+"…"}}return""}(r),fingerprint:[oh(r.join(""))],env:e&&e.env||{}});return i.env.__serialized__=function e(n,r,i){if(void 0===r&&(r=3),void 0===i&&(i=51200),!iJ(n))return n+"";var o=function e(n,r){return 0===r?ow(n):iJ(n)?Object.keys(n).reduce(function(i,o){return i[o]=e(n[o],r-1),i},{}):Array.isArray(n)?n.map(function(n){return e(n,r-1)}):ow(n)}(n,r);return~-encodeURI(JSON.stringify(ov(o))).split(/%..|./).length>i?e(n,r-1):o}(n),i},e.prototype.captureBehavior=function(e){var n=iF(iF({},e),{timestamp:Date.now()/1e3});if(iW(this.options.breadcrumbCallback)){var r=this.options.breadcrumbCallback(n);if("object"!=typeof r||null===r||iK(r)){if(!1===r)return this}else n=r}return this._behaviors.push(n),this._behaviors.length>(this.options.behaviorLimit||10)&&this._behaviors.shift(),this},e.prototype.setContext=function(e,n){for(var r in void 0===n&&(n={persist:!0}),e)Reflect.has(e,r)&&(n.persist?this._globalContext.env[r]=e[r]:this._currentExceptionContext[r]=e[r])},e.prototype.clearContext=function(){this._globalContext.env={},this._currentExceptionContext={}},e.prototype._restoreBuiltIns=function(){for(var e;this._wrappedBuiltIns.length;){var n=(e=this._wrappedBuiltIns.shift())[0],r=e[1],i=e[2];n[r]=i}},e.prototype.noConflict=function(){},e.prototype.uninstall=function(){this.dispose()},e.prototype.dispose=function(){i4(this._globalErrorHandler),this._restoreBuiltIns(),this._globalErrorHandler=null,this._installed=!1},e}(),oX={};function oW(){var e=window.crypto||window.msCrypto;if(void 0===e||!e.getRandomValues)return"xxxxxxxxxxxx4xxxyxxxxxxxxxxxxxxx".replace(/[xy]/g,function(e){var n=16*Math.random()|0;return("x"===e?n:3&n|8).toString(16)});var n=new Uint16Array(8);e.getRandomValues(n),n[3]=4095&n[3]|16384,n[4]=16383&n[4]|32768;var r=function(e){for(var n=e.toString(16);n.length<4;)n="0"+n;return n};return r(n[0])+r(n[1])+r(n[2])+r(n[3])+r(n[4])+r(n[5])+r(n[6])+r(n[7])}var o$=function(){function e(e){this.version="1.3.15",this.lastRouteTime=0,e&&this.init(e)}return e.prototype.init=function(e){var n,r,i,o,s=this.getSendWindow();if(!e.perf||e.perf&&!e.perf.disable){var a=iL(iL(iL({},e.perf),e.common),{version:this.version,sendWindow:s});this.perf=new iD.PerfClient(a)}if(!e.error||e.error&&!e.error.disable){var c=iL(iL(iL({},e.error),e.common),{version:this.version,sendWindow:s,uuid4:oW});this.error=new oV(c)}this.routeChange(window.document.URL),n=this.routeChange.bind(this),"function"==typeof(r=window.history).pushState&&(i=r.pushState,r.pushState=function(e,r,o){return n(o),i.apply(this,arguments)}),"function"==typeof r.replaceState&&(o=r.replaceState,r.replaceState=function(e,r,i){return i!==window.document.URL&&n(i),o.apply(this,arguments)}),window.addEventListener("hashchange",function(e){n((e||{}).newURL)}),window.addEventListener("popstate",function(e){n(window.document.URL)})},e.prototype.routeChange=function(e){var n=new Date().getTime();if(n-this.lastRouteTime>100){this.lastRouteTime=n;var r=oW()+"-"+n;this.error&&this.error.setContext({pageId:r})}},e.prototype.getSendWindow=function(){var e="undefined"!=typeof window?window:void 0!==et.g?et.g:"undefined"!=typeof self?self:oX;if(["fetch","ajax","sendBeacon"].some(function(e){var n;return!((n=window[e])&&n.toString&&!n.hasOwnProperty("toString")&&/\[native code\]/.test(String(n)))})&&document.body){var n=document.createElement("iframe");n.style.setProperty("display","none","important"),document.body.appendChild(n),e=n?n.contentWindow:e}return e},e.prototype.afterLoad=function(){},e}();function oz(e,n){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,n)}function oG(e,n){return function(r,i){n(r,i,e)}}(T=(S=F||(F={})).EMessageType||(S.EMessageType={}))[T.Query=0]="Query",T[T.Event=1]="Event";class oJ{constructor(e,n,r){this.opts=e,this.signalingService=n,this.errorManager=r,this.disabled=!1,this.mutedByUser=!1,this.muted=!1,this.emitter=new nl,this.started=!1,this.mute=e=>{this.signalingService.Mute(e),this.muted=e},this.setMutedByUser=e=>{this.mutedByUser=e},this.tryUnmuteAsr=()=>!this.disabled&&!this.mutedByUser&&(this.muted&&this.mute(!1),!0),this.disable=()=>{this.disabled=!0},this.enable=()=>{this.disabled=!1},this._stop=async()=>{this.started&&(await this.signalingService.Stop(),this.started=!1)},this._dispose=()=>{this.stop().finally(()=>{this.signalingService.Dispose()}).catch(rI),this.emitter.clearListeners()},this._ensureMicPermission=async()=>{var e;if("function"==typeof(null==(e=navigator.permissions)?void 0:e.query)){try{switch((await navigator.permissions.query({name:"microphone"})).state){case"granted":case"prompt":break;case"denied":this.errorManager.handleError(new n7("麦克风权限被浏览器/系统禁用,请检查后重试"))}}catch{await this._ensureMicPermissionPolyfill()}return}await this._ensureMicPermissionPolyfill()},this._ensureMicPermissionPolyfill=async()=>{try{(await navigator.mediaDevices.getUserMedia({audio:!0})).getTracks().forEach(e=>e.stop())}catch(e){e instanceof Error&&("NotAllowedError"===e.name||"SecurityError"===e.name?this.errorManager.handleError(new n7(`\u{7528}\u{6237}\u{62D2}\u{7EDD}\u{9EA6}\u{514B}\u{98CE}\u{6743}\u{9650}: ${e.message}`)):"NotFoundError"===e.name?this.errorManager.handleError(new n7(`\u{672A}\u{68C0}\u{6D4B}\u{5230}\u{9EA6}\u{514B}\u{98CE}\u{8BBE}\u{5907}: ${e.message}`)):this.errorManager.handleError(new n7(e.message)))}}}get sessionId(){return this.started?this.signalingService.GetSessionID():null}}function oK(e,n){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,n)}function oQ(e,n){return function(r,i){n(r,i,e)}}oJ=function(e,n,r,i){var o,s=arguments.length,a=s<3?n:null===i?i=Object.getOwnPropertyDescriptor(n,r):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)a=Reflect.decorate(e,n,r,i);else for(var c=e.length-1;c>=0;c--)(o=e[c])&&(a=(s<3?o(a):s>3?o(n,r,a):o(n,r))||a);return s>3&&a&&Object.defineProperty(n,r,a),a}([eV(),oG(0,eU(nd.IOptions)),oG(0,ez()),oG(1,eU(nd.SignalingService)),oG(2,eU(nd.ErrorManager)),oz("design:type",Function),oz("design:paramtypes",["undefined"==typeof IResolvedOptions?Object:IResolvedOptions,"undefined"==typeof BaseSignalingService?Object:BaseSignalingService,void 0===rb?Object:rb])],oJ);class oY{static #k=this.GET_ACCESS_TOKEN_REQUEST_URI="employee-console/v1/access/r/ai-agent/get_digital_token";constructor(e,n,r){this.opts=e,this.request=n,this.errorManager=r,this.emitter=new nl,this._isRendering=!1,this._isMuted=!1,this._canInterrupt=!0,this.ssmlHandlers=[],this.token="",this.getAccessToken=async()=>{try{let{data:e}=await this.request.client.get(oY.GET_ACCESS_TOKEN_REQUEST_URI,{retry:3,timeout:15e3}).json();return e.authorization}catch(e){throw e instanceof Error&&this.errorManager.handleError(new rl(e.message)),e}}}get isRendering(){return this._isRendering}get isMuted(){return this._isMuted}get canInterrupt(){return this._canInterrupt}setIsRendering(e){this._isRendering=e}setIsMuted(e){this._isMuted=e}setCanInterrupt(e){this._canInterrupt=e}registerSSMLHandler(e){return this.ssmlHandlers.push(e),this}runSsmlHandlers(e){let n=e;for(let e of this.ssmlHandlers)n=e(n);return n}}oY=function(e,n,r,i){var o,s=arguments.length,a=s<3?n:null===i?i=Object.getOwnPropertyDescriptor(n,r):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)a=Reflect.decorate(e,n,r,i);else for(var c=e.length-1;c>=0;c--)(o=e[c])&&(a=(s<3?o(a):s>3?o(n,r,a):o(n,r))||a);return s>3&&a&&Object.defineProperty(n,r,a),a}([eV(),oQ(0,eU(nd.IOptions)),oQ(1,eU(nd.CommonRequest)),oQ(2,eU(nd.ErrorManager)),oK("design:type",Function),oK("design:paramtypes",["undefined"==typeof IOptions?Object:IOptions,void 0===nX?Object:nX,void 0===rb?Object:rb])],oY);let oZ=function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:500;return new Promise(n=>setTimeout(n,e))};function o0(e,n){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);n&&(i=i.filter(function(n){return Object.getOwnPropertyDescriptor(e,n).enumerable})),r.push.apply(r,i)}return r}function o1(e){for(var n=1;n<arguments.length;n++){var r=null!=arguments[n]?arguments[n]:{};n%2?o0(Object(r),!0).forEach(function(n){o4(e,n,r[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):o0(Object(r)).forEach(function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(r,n))})}return e}function o2(e){return(o2="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(e)}function o3(e,n){if(!(e instanceof n))throw TypeError("Cannot call a class as a function")}function o6(e,n){for(var r=0;r<n.length;r++){var i=n[r];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(e,o8(i.key),i)}}function o5(e,n,r){return n&&o6(e.prototype,n),r&&o6(e,r),Object.defineProperty(e,"prototype",{writable:!1}),e}function o4(e,n,r){return(n=o8(n))in e?Object.defineProperty(e,n,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[n]=r,e}function o8(e){var n=function(e,n){if("object"!=typeof e||null===e)return e;var r=e[Symbol.toPrimitive];if(void 0!==r){var i=r.call(e,n||"default");if("object"!=typeof i)return i;throw TypeError("@@toPrimitive must return a primitive value.")}return("string"===n?String:Number)(e)}(e,"string");return"symbol"==typeof n?n:String(n)}(U||(U={})).INIT="INIT";var o9=function(){function e(n){o3(this,e),o4(this,"iframeId",void 0),this.iframeId=n}return o5(e,[{key:"registerMessageReceived",value:function(e){void 0!==window.addEventListener&&"function"==typeof e&&window.addEventListener("message",e,!1)}},{key:"removeMessageReceived",value:function(e){void 0!==window.addEventListener&&window.removeEventListener("message",e,!1)}},{key:"sendMessageToIframe",value:function(e,n){if(this.iframeId){var r=document.getElementById(this.iframeId);e&&null!==r&&r.contentWindow.postMessage({type:e,content:n},"*")}else if(window.self!==window.top&&window&&window.parent&&window.parent.postMessage){var i=JSON.parse(JSON.stringify(n||{}));window.parent.postMessage({type:e,content:i},"*")}}},{key:"sendCommand",value:function(e){this.sendMessageToIframe("command",e)}},{key:"sendMessage",value:function(e){var n=e.requestId,r=void 0===n?rC():n;return this.sendMessageToIframe("message",o1(o1({},e),{},{requestId:r})),r}},{key:"textRender",value:function(e){return this.sendMessage({action:"TEXT_RENDER",body:e})}},{key:"textQuery",value:function(e){return this.sendMessage({action:"TEXT_QUERY",body:e})}},{key:"changeBackGround",value:function(e){return this.textRender("<display><background><type>image</type><source>http</source><value>".concat(e,"</value></background></display>"))}},{key:"mute",value:function(e){this.sendCommand({subType:"mute",subContent:e})}},{key:"muteAudio",value:function(e){this.sendCommand({subType:"muteAudio",subContent:e})}},{key:"muteRemoteAudio",value:function(e){this.sendCommand({subType:"muteRemoteAudio",subContent:e})}},{key:"playVideo",value:function(e){this.sendCommand({subType:"playVideo",subContent:e})}},{key:"sendAudioData",value:function(e){this.sendMessageToIframe("audioData",e)}},{key:"onStateUpdate",value:function(e){this.sendMessageToIframe("state",e)}},{key:"sendRtcState",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.sendMessageToIframe("rtcState",e)}},{key:"sendWsState",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.sendMessageToIframe("wsState",e)}}]),e}();o5(function e(n){o3(this,e),o4(this,"iframeId",void 0),o4(this,"namespace","dhIframeNameSpace"),o4(this,"listener",null),this.iframeId=n},[{key:"onEventListener",value:function(e){var n=this;return function(r){if("object"===o2(r.data))if("onListener"===r.data.type&&r.data.content.listenerId){var i=window[n.namespace][r.data.content.listenerId];null==i||i(r.data.content.data)}else"onListenerRemove"===r.data.type&&r.data.content.listenerId?delete window[n.namespace][r.data.content.listenerId]:r.data.listenerId?e(r.data,function(e){n.sendMessage("onListener",{listenerId:r.data.listenerId,data:e})},function(){n.sendMessage("onListenerRemove",{listenerId:r.data.listenerId})}):e(r.data)}}},{key:"registerMessageReceived",value:function(e){void 0!==window.addEventListener&&"function"==typeof e&&(this.listener=this.onEventListener(e),window.addEventListener("message",this.listener,!1))}},{key:"removeMessageReceived",value:function(){void 0!==window.addEventListener&&this.listener&&(window[this.namespace]=void 0,window.removeEventListener("message",this.listener,!1))}},{key:"sendMessage",value:function(e,n,r){var i=this;if(this.iframeId){var o="";r&&(o=rC(),window[this.namespace]||(window[this.namespace]={}),window[this.namespace][o]=r);var s=document.getElementById(this.iframeId);return e&&null!==s&&s.contentWindow.postMessage({type:e,content:n,listenerId:o},"*"),function(){o&&(window[i.namespace][o]=void 0)}}if(window.self!==window.top&&window&&window.parent&&window.parent.postMessage){var a=JSON.parse(JSON.stringify(n||{}));window.parent.postMessage({type:e,content:a},"*")}}},{key:"textRender",value:function(e,n){return this.sendMessage("TEXT_RENDER",e,n)}},{key:"textMTRender",value:function(e,n){return this.sendMessage("TEXT_MT_RENDER",e,n)}},{key:"audioRender",value:function(e,n){return this.sendMessage("AUDIO_RENDER",e,n)}},{key:"textQuery",value:function(e,n){return this.sendMessage("TEXT_QUERY",e,n)}},{key:"startAudioQuery",value:function(e,n){return this.sendMessage("AUDIO_QUERY_START",e,n)}},{key:"stopAudioQuery",value:function(){return this.sendMessage("AUDIO_QUERY_STOP",{})}},{key:"setModelPackage",value:function(e,n){return this.sendMessage("SET_MODEL_URLS",{urls:e,needInitConfig:n})}},{key:"changeCamera",value:function(e){return this.sendMessage("CHANGE_CAMERA",e)}},{key:"changeParts",value:function(e){return this.sendMessage("CHANGE_PARTS",e)}},{key:"setRenderConfig",value:function(e){return this.sendMessage("SET_RENDER_CONFIG",e)}},{key:"animojiRender",value:function(e,n){return this.sendMessage("ANIMOJI_RENDER",e,n)}},{key:"destroy",value:function(){return this.sendMessage("DESTROY",{})}},{key:"startAudioRender",value:function(e,n){return this.sendMessage("AUDIO_RENDER_START",e,n)}},{key:"stopAudioRender",value:function(){return this.sendMessage("AUDIO_RENDER_STOP",{})}},{key:"interrupt",value:function(){return this.sendMessage("INTERRUPT",{})}},{key:"load",value:function(e){return this.sendMessage("LOAD",e)}},{key:"onStateUpdate",value:function(e){this.sendMessage("state",e)}}]);let o7=e=>new URLSearchParams(Object.entries(e).filter(e=>{let[,n]=e;return null!=n&&""!==n}).reduce((e,n)=>{let[r,i]=n;return e[r]=String(i),e},{})).toString();var se=((H={})[H.Success=0]="Success",H[H.ReachSessionLimit=1004]="ReachSessionLimit",H[H.ResourceNotEnough=3001]="ResourceNotEnough",H),st=((q={})[q.UNINSTANTIATED=-1]="UNINSTANTIATED",q[q.CONNECTING=0]="CONNECTING",q[q.OPEN=1]="OPEN",q[q.CLOSING=2]="CLOSING",q[q.CLOSED=3]="CLOSED",q);class sn extends oY{get ready(){return!!this.iframeController&&!!this.token}constructor(...e){super(...e),this.origin="https://open.xiling.baidu.com",this.iframeId=rC(),this.iframeController=null,this.iframe=null,this.$iframeContainer=null,this.requestId=rC(),this.isWSConnected=!1,this.isRtcReady=!1,this.silenceMessageRequestIds=[],this.isStreamTextRendering=!1,this.wsClosedCount=0,this.mount=async e=>{if(!e)return void this.errorManager.handleError(new ri("容器元素不能为空"));if(this.$iframeContainer=e,this.iframe){e.contains(this.iframe)||e.appendChild(this.iframe);return}this.opts.enableDebugMode&&"development"===this.opts.env&&!this.opts.token?this.token=await this.getAccessToken():this.token=this.opts.token,this.iframe=document.createElement("iframe"),this.applyOptions(),e.appendChild(this.iframe),this.iframeController=new o9(this.iframeId),this.bindEvents()},this.bindEvents=()=>{var e,n;return this.ready&&(null==(e=this.iframe)||e.addEventListener("error",this.onIFrameErrorHandler),null==(n=this.iframeController)||n.registerMessageReceived(this.onMessageHandler)),this},this.unbindEvents=()=>{var e,n;return this.ready&&(null==(e=this.iframe)||e.removeEventListener("error",this.onIFrameErrorHandler),null==(n=this.iframeController)||n.removeMessageReceived(this.onMessageHandler)),this},this.cancelMute=()=>{var e;null==(e=this.iframeController)||e.sendCommand({subType:"muteAudio",subContent:!1}),setTimeout(()=>{this._isMuted=!1},1500)},this.renderPlainText=e=>{var n;if(!this.ready)return this;let r=this.runSsmlHandlers(e);return this.refreshRequestId(),null==(n=this.iframeController)||n.sendMessage({action:"TEXT_RENDER",body:r,requestId:this.requestId}),this},this.renderStreamText=(e,n)=>{var r,i,o;if(!this.ready)return this;let s=this.runSsmlHandlers(e);return n?(this.isStreamTextRendering||this.refreshRequestId(),null==(i=this.iframeController)||i.sendMessage({action:"TEXT_STREAM_RENDER",body:JSON.stringify({first:!this.isStreamTextRendering,last:!0,text:s}),requestId:this.requestId}),this.isStreamTextRendering=!1):this.isStreamTextRendering?null==(r=this.iframeController)||r.sendMessage({action:"TEXT_STREAM_RENDER",body:JSON.stringify({first:!1,last:!1,text:s}),requestId:this.requestId}):(this.refreshRequestId(),this.isStreamTextRendering=!0,null==(o=this.iframeController)||o.sendMessage({action:"TEXT_STREAM_RENDER",body:JSON.stringify({first:!0,last:!1,text:s}),requestId:this.requestId})),this},this.interrupt=()=>{var e;return this.ready&&(null==(e=this.iframeController)||e.sendMessage({action:"TEXT_RENDER",body:"<interrupt></interrupt>",requestId:this.requestId}),this.isRendering||this.onRenderFinished(this.requestId)),this},this.sendSilenceMessage=()=>{var e;if(!this.ready)return this;let n=rC();return null==(e=this.iframeController)||e.sendMessage({action:"TEXT_RENDER",body:"",requestId:n}),this.silenceMessageRequestIds.push(n),this.emitter.emit("send_silence_message",{requestId:n}).catch(rI),this},this.dispose=()=>{if(this.unbindEvents(),this.silenceMessageRequestIds=[],this.ssmlHandlers=[],this.wsClosedCount=0,this.emitter.clearListeners(),this.iframe){var e;null==(e=this.$iframeContainer)||e.removeChild(this.iframe),this.iframe=null,this.iframeController=null}return this},this.GetRequestId=()=>this.requestId,this.checkIsReady=()=>{let e=this.isWSConnected&&this.isRtcReady;return e&&this.emitter.emit("ready").catch(rI),e},this.onIFrameErrorHandler=e=>{let n=new ro(`\u{6570}\u{5B57}\u{4EBA}iframe\u{52A0}\u{8F7D}\u{5931}\u{8D25}: ${e.message}`,{context:{method:"onIFrameErrorHandler",iframeId:this.iframeId,filename:e.filename,lineno:e.lineno,colno:e.colno,type:e.type,target:e.target}});this.errorManager.handleError(n)},this.onMessageHandler=e=>{if(e.origin!==this.origin)return;let n=e.data;switch(n.type){case"msg":this.onReceiveMsgTypedMessageHandler(n);break;case"rtcState":this.onReceiveRtcStateTypedMessageHandler(n);break;case"wsState":this.onReceiveWsStateTypedMessageHandler(n)}},this.onReceiveMsgTypedMessageHandler=e=>{let n=e.content.requestId;if((e.content.code===se.ReachSessionLimit||e.content.code===se.ResourceNotEnough)&&(this.emitter.emit("reach_session_limit",{requestId:n}).catch(rI),this.errorManager.handleError(new ru("资源配额已用尽,请联系技术支持申请扩容"))),["RENDER_START","FINISHED","DOWN_SUBTITLE","RENDER_INTERRUPTED","DOWN_SUBTITLE","TEXT_RENDER","TEXT_STREAM_RENDER"].includes(e.content.action)){if(n!==this.requestId)return;switch(e.content.action){case"RENDER_START":this._isRendering=!0,this.emitter.emit("is_rendering_change",!0).catch(rI);break;case"FINISHED":case"RENDER_INTERRUPTED":this.onRenderFinished(n);break;case"DOWN_SUBTITLE":{let r=JSON.parse(e.content.body);this.silenceMessageRequestIds.includes(n)?this.silenceMessageRequestIds=this.silenceMessageRequestIds.filter(e=>e!==n):this.emitter.emit("render_subtitle",{subtitle:r,requestId:n}).catch(rI);break}case"TEXT_RENDER":case"TEXT_STREAM_RENDER":0!==e.content.code&&this.onRenderFinished(n)}return}switch(e.content.action){case"RENDER_ERROR":this.onRenderFinished(n),this.errorManager.handleError(new rs("数字员工文本驱动渲染失败,请确认配置后重试",{requestId:n,context:{msg:e.content.message}}));break;case"DISCONNECT_ALERT":this.emitter.emit("disconnect_alert",{requestId:n}).catch(rI);break;case"TIMEOUT_EXIT":this.onRenderFinished(n),this.emitter.emit("timeout",{requestId:e.content.requestId}).catch(rI)}},this.onReceiveRtcStateTypedMessageHandler=e=>{e.content.action,"localVideoMuted"===e.content.action&&e.content.body&&(this._isMuted=!0),"remotevideoon"===e.content.action&&(this.isRtcReady=!0,this.checkIsReady(),this.iframe&&(this.iframe.style.opacity="1")),"error"===e.content.action&&this.errorManager.handleError(new rc("RTC 房间连接失败,请检查网络后重试"))},this.onReceiveWsStateTypedMessageHandler=e=>{e.content.readyState===st.OPEN?(this.isWSConnected=!0,this.wsClosedCount=0,this.checkIsReady()):(e.content.readyState===st.CLOSED||e.content.readyState===st.CLOSING)&&(this.isWSConnected=!1),e.content.readyState===st.CLOSED&&(this.wsClosedCount++,this.wsClosedCount>=3&&(this.emitter.emit("reconnect_failed").catch(rI),this.errorManager.handleError(new ra("检测到 Websocket 链接异常断开,如长时间无法恢复,请联系技术支持。"))))},this.applyOptions=()=>{var e,n,r,i,o,s,a,c,l,u,d,p,h,f;if(!this.iframe)return;this.iframe.id=this.iframeId,this.iframe.allow="autoplay",this.iframe.style.border="none",this.iframe.style.opacity="0",this.iframe.style.pointerEvents="none",this.iframe.style.overflow="hidden";let m=null!=(o=null==(e=this.opts)?void 0:e.scaleX)?o:1,g=null!=(s=null==(n=this.opts)?void 0:n.scaleY)?s:1,v=null!=(a=null==(r=this.opts)?void 0:r.translateX)?a:0,y=null!=(c=null==(i=this.opts)?void 0:i.translateY)?c:0;this.iframe.style.width=`${100*m}% `,this.iframe.style.height=`${100*g}%`,this.iframe.style.transform=`translate(${v}px, ${y}px)`;let b=o7({figureId:this.opts.figureId,ttsPer:this.opts.ttsPer,initMode:"noAudio","cp-inactiveDisconnectSec":null!=(l=this.opts.timeoutSec)?l:130,"cp-preAlertSec":null!=(u=this.opts.disconnectAlertSec)?u:10,mode:"crop",resolutionWidth:null!=(d=this.opts.figureResolutionWidth)?d:1920,resolutionHeight:null!=(p=this.opts.figureResolutionHeight)?p:1080,ttsSpeed:null!=(h=this.opts.speechSpeed)?h:6,"cp-ttsSample":this.opts.ttsSample,"cp-minSplitLen":this.opts.minSplitLen,"cp-ttsModel":this.opts.ttsModel,"cp-positionV2":JSON.stringify(this.opts.position),autoChromaKey:this.opts.autoChromaKey,closeLog:null==(f=this.opts.enableDebugMode)||f,token:this.token});this.iframe.src=`${this.origin}/cloud/realtime?${b}`},this.refreshRequestId=()=>{this.requestId=rC()},this.onRenderFinished=e=>{this._isRendering=!1,this.emitter.emit("is_rendering_change",!1).catch(rI),this.refreshRequestId(),this.emitter.emit("render_finished",{requestId:e}).catch(rI)}}}function sr(e,n){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,n)}function si(e,n){return function(r,i){n(r,i,e)}}sn=function(e,n,r,i){var o,s=arguments.length,a=s<3?n:null===i?i=Object.getOwnPropertyDescriptor(n,r):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)a=Reflect.decorate(e,n,r,i);else for(var c=e.length-1;c>=0;c--)(o=e[c])&&(a=(s<3?o(a):s>3?o(n,r,a):o(n,r))||a);return s>3&&a&&Object.defineProperty(n,r,a),a}([eV(),eX()],sn);class so{static #k=this.ENTRY_EMITTER_NAME="AaaSPilotKitEmitter";constructor(e,n,r,i,o,s){this.opts=e,this.errorManager=n,this.agentService=r,this.asrService=i,this.digitalHumanService=o,this.conversationService=s,this.interruptible=!0,this.isRenderingMultiModConversation=!1,this.isDigitalHumanServiceReady=!1,this.isAsrServiceReady=!1,this.aiWorkerMessageCache=null,this.multiModAbortControllers=[],this.playWaitForListener=null,this.mount=async e=>{var n,r;let i=null!=e?e:null==(n=(r=this.opts).getMountContainer)?void 0:n.call(r);i&&(await Promise.all([this.digitalHumanService.mount(i),this.asrService.preloadDeps()]),this.asrService.start(),this.isAsrServiceReady=!0,this.checkServiceReady())},this.getOptions=()=>this.opts,this.checkNeedsManualActivation=()=>n6()||n5(),this.activateManually=async()=>{this.digitalHumanService instanceof sn&&(this.digitalHumanService.cancelMute(),n3()&&(n6()||n5())&&await oZ(500))},this.keepAlive=()=>(this.digitalHumanService.sendSilenceMessage(),this),this.playWaitFor=async(e,n)=>(this.playWaitForListener&&this.digitalHumanService.emitter.off("render_finished",this.playWaitForListener),this.digitalHumanService.isRendering)?await new Promise(r=>{this.playWaitForListener=()=>{if(n&&!n())return void r(!1);this.digitalHumanService.renderPlainText(e),this.playWaitForListener&&this.digitalHumanService.emitter.off("render_finished",this.playWaitForListener),r(!0)},this.digitalHumanService.emitter.on("render_finished",this.playWaitForListener)}):(this.digitalHumanService.renderPlainText(e),!0),this.playFromFullText=e=>(this.digitalHumanService.renderPlainText(e),this),this.playFromStreamText=(e,n)=>(this.digitalHumanService.renderStreamText(e,n),this),this.mute=e=>(this.asrService.setMutedByUser(e),this.emitter.emit("mute",e).catch(rI),e?(this.asrService.mute(!0),this.conversationService.currentClientConversation&&this.query(this.conversationService.currentClientConversation.text,!0).catch(rI)):this.asrService.muted&&this.asrService.mute(!1),this),this.interrupt=()=>(this.interruptAIWorkerConversation(),this),this.playPrologue=()=>{if(this.opts.prologue&&this.opts.prologue.length>0)return void this.playFromFullText(this.opts.prologue);this.agentService.query("").catch(rI)},this.query=async(e,n)=>{if(this.checkServiceReady()){if(this.agentService.sessionId||this.agentService.setSessionId(rC()),this.digitalHumanService.sendSilenceMessage(),this.agentService.queryId||this.agentService.setQueryId(rC()),n){if(this.agentService.checkIsRepeat())return;this.agentService.setLastQueryId(this.agentService.queryId)}if(await this.emitter.emit("asr_message",{text:e,completed:n,id:this.agentService.queryId,sessionId:this.agentService.sessionId}),await this.handleClientConversation(e),n){this.asrService.mute(!0);let n=async()=>{this.agentService.setQueryId(""),this.digitalHumanService.canInterrupt&&(this.asrService.tryUnmuteAsr(),await this.emitter.emit("asr_start"),this.digitalHumanService.emitter.off("render_subtitle",n))};this.digitalHumanService.emitter.on("render_subtitle",n);let r=async()=>{this.agentService.setQueryId(""),this.asrService.tryUnmuteAsr(),await this.emitter.emit("asr_start"),this.digitalHumanService.emitter.off("render_finished",r)};this.digitalHumanService.emitter.on("render_finished",r),this.handleClientConversationCompleted(),await this.agentService.query(e)}}},this.input=e=>(this.digitalHumanService.isRendering&&!this.interruptible||this.query(e,!0).catch(rI),this),this.dispose=()=>(this.agentService.dispose(),this.asrService.dispose(),this.digitalHumanService.dispose(),this.conversationService.dispose(),this.emitter.clearListeners(),this.isDigitalHumanServiceReady=!1,this.isAsrServiceReady=!1,this.aiWorkerMessageCache=null,this.isRenderingMultiModConversation=!1,this.multiModAbortControllers=[],this),this.setInterruptible=e=>(this.interruptible=e,this),this.bindAsrServiceEvents=()=>{this.asrService.emitter.on("start",this.handleAsrServiceStarted),this.asrService.emitter.on("message",this.handleAsrMessage)},this.bindAgentServiceEvents=()=>{this.agentService.emitter.on("data",this.handleAgentAnswer),this.agentService.emitter.on("completed",this.handleAgentAnswerCompleted),this.agentService.emitter.on("instruction_received",this.handleAgentInstructionReceived),this.agentService.emitter.on("usage_quota_reached",async e=>{await this.emitter.emit("busy",{...e})})},this.bindDigitalHumanServiceEvents=()=>{this.digitalHumanService.bindEvents(),this.digitalHumanService.emitter.once("ready").then(()=>{this.isDigitalHumanServiceReady=!0,this.checkServiceReady()}),this.digitalHumanService.emitter.on("render_subtitle",this.aiWorkerSubtitleToConversation),this.digitalHumanService.emitter.on("is_rendering_change",e=>{this.emitter.emit("is_rendering_change",e).catch(rI)}),this.digitalHumanService.emitter.on("render_subtitle",async e=>{await this.emitter.emit("render_start",{...e,sessionId:this.agentService.sessionId,queryId:this.agentService.queryId})}),this.digitalHumanService.emitter.on("disconnect_alert",e=>{let n=this.digitalHumanService.emitter.on("render_finished",()=>{this.asrService.mute(!0),this.emitter.emit("inactivity",e).catch(rI),n()}),r=this.digitalHumanService.emitter.on("send_silence_message",()=>{n(),r()});this.playFromFullText(this.opts.inactivityPrompt)}),this.digitalHumanService.emitter.on("reach_session_limit",async e=>{this.isDigitalHumanServiceReady&&this.isAsrServiceReady&&await this.emitter.emit("busy",{...e})}),this.digitalHumanService.emitter.on("reconnect_failed",async()=>{await this.emitter.emit("busy",{requestId:"reconnect_failed"})});let e=this.digitalHumanService.emitter.on("render_finished",()=>{this.asrService.tryUnmuteAsr(),e()})},this.bindErrorEvents=()=>{this.errorManager.on(e=>{let n=this.errorManager.createMonitoringError(e);this.emitter.emit("error",e).catch(rI);try{this.weirwood.error.captureException(n)}catch(e){console.error(e)}})},this.bindEvents=()=>{this.bindErrorEvents(),this.bindAsrServiceEvents(),this.bindAgentServiceEvents(),this.bindDigitalHumanServiceEvents()},this.registerFormatters=()=>{var e,n;let r=null!=(e=this.opts.speechFormatters)?e:[],i=null!=(n=this.opts.conversationFormatters)?n:[];for(let e of r)this.digitalHumanService.registerSSMLHandler(e);for(let e of i)this.conversationService.registerAIWorkerConversationFormatter(e)},this.aiWorkerSubtitleToConversation=async e=>{let n=e.subtitle;if(this.isRenderingMultiModConversation)return;let r=this.conversationService;await this.createNewAIWorkerConversation();let i=r.currentAIWorkerConversation;i&&this.handleAIWorkerConversationChange(i);let o=r.runAIWorkerConversationFormatters(n.content);null==i||i.appendText(o),n.completed&&r.setCurrentConversation(null)},this.handleAgentAnswer=e=>{let{answer:n}=e;if(ix.isXml(n))return void this.handleXmlAgentAnswer(e).catch(rI);this.aiWorkerMessageCache&&this.playFromStreamText(this.aiWorkerMessageCache,!1),this.aiWorkerMessageCache=n},this.handleXmlAgentAnswer=async e=>{let{answer:n}=e,r=this.conversationService;await this.createNewAIWorkerConversation();let i=r.currentAIWorkerConversation;if(!i)return;let o=()=>{this.emitter.emit("conversation_change",{...i.toJSON(),text:i.fulltext,completed:!1})};i.emitter.on("content_change",o),this.isRenderingMultiModConversation=!0;let s=r.runAIWorkerConversationFormatters(n),a=i.createContentsFromXmlString(s),c=new AbortController;for(let e of(this.multiModAbortControllers.push(c),a)){if(c.signal.aborted){i.emitter.off("content_change",o);break}if(iC.isTextContent(e)){let n=e.getConfig().content;this.playFromFullText(n),await this.digitalHumanService.emitter.once("render_subtitle")}i.addContentRenderTask(e),i.contents.push(e),await i.emitter.once("queue_empty")}this.isRenderingMultiModConversation=!1,i.emitter.off("content_change",o),await this.emitter.emit("conversation_change",{...i.toJSON(),text:i.fulltext,completed:!0})},this.createNewAIWorkerConversation=async()=>{let e=this.conversationService;if(!e.currentAIWorkerConversation){let n=iC.create(this.opts);e.setCurrentConversation(n),e.add(n),await this.emitter.emit("conversation_add",n)}},this.handleAgentAnswerCompleted=()=>{if(this.aiWorkerMessageCache){this.playFromStreamText(this.aiWorkerMessageCache,!0),this.aiWorkerMessageCache=null;return}this.asrService.tryUnmuteAsr()},this.handleAgentInstructionReceived=e=>{this.emitter.emit("instruction_received",e).catch(rI)},this.handleAsrServiceStarted=async()=>{await oZ(800),this.asrService.mute(!0),this.interruptible&&this.emitter.once("render_start").then(()=>{this.asrService.tryUnmuteAsr()})},this.handleAsrMessage=async e=>{this.digitalHumanService.isRendering&&!this.digitalHumanService.canInterrupt||this.asrService.mutedByUser||e.type===F.EMessageType.Query&&(this.opts.enableDebugMode&&console.log("message",e,this.agentService.sessionId,Date.now()),await this.query(rS(e.data,this.opts.hotWordReplacementRules),e.completed))},this.handleClientConversation=async e=>{let n=this.conversationService;if(!n.currentClientConversation){let e=rB.create(this.opts);n.setCurrentConversation(e),n.add(e),await this.emitter.emit("conversation_add",e)}let r=n.currentClientConversation;(this.digitalHumanService.isRendering||this.isRenderingMultiModConversation)&&this.interruptAIWorkerConversation(),null==r||r.appendText(e)},this.handleClientConversationCompleted=()=>{this.conversationService.setCurrentConversation(null)},this.interruptAIWorkerConversation=()=>{for(let e of(this.aiWorkerMessageCache&&this.digitalHumanService.renderStreamText(this.aiWorkerMessageCache,!0),this.multiModAbortControllers))e.abort();this.multiModAbortControllers=[];let e=this.digitalHumanService.GetRequestId();this.digitalHumanService.interrupt(),this.conversationService.interruptAll(),this.agentService.abort(),this.aiWorkerMessageCache=null,this.emitter.emit("interrupt",{requestId:e,queryId:this.agentService.queryId?this.agentService.queryId:this.agentService.lastQueryId,sessionId:this.agentService.sessionId}).catch(rI)},this.checkServiceReady=()=>!!this.isDigitalHumanServiceReady&&!!this.isAsrServiceReady&&(this.emitter.emit("ready").catch(rI),!0),this.handleAIWorkerConversationChange=e=>{let n=r=>{this.emitter.emit("conversation_change",{...e.toJSON(),text:e.fulltext,completed:r.completed}).catch(rI),r.completed&&e.emitter.off("content_change",n)},r=()=>{e.emitter.off("interrupt",r),e.emitter.off("content_change",n)};e.emitter.on("content_change",n),e.emitter.on("interrupt",r)},this.weirwood=new o$({common:{buildid:"AAAS_PILOT_KIT_1.0.0",token:"8f3abab4743f4114bd632999224323af"},error:{collectWindowErrors:!1,collectUnhandledRejections:!1,collectResourceLoadErrors:!1,ignoreUrls:["localhost","127.0.0.1"]},perf:{disable:!0}}),this.emitter=new nl(this.opts.enableDebugMode?{debug:{name:so.ENTRY_EMITTER_NAME,enabled:!0}}:void 0),this.bindEvents(),this.registerFormatters(),this.interruptible=this.opts.interruptible}}so=function(e,n,r,i){var o,s=arguments.length,a=s<3?n:null===i?i=Object.getOwnPropertyDescriptor(n,r):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)a=Reflect.decorate(e,n,r,i);else for(var c=e.length-1;c>=0;c--)(o=e[c])&&(a=(s<3?o(a):s>3?o(n,r,a):o(n,r))||a);return s>3&&a&&Object.defineProperty(n,r,a),a}([eV(),si(0,eU(nd.IOptions)),si(0,ez()),si(1,eU(nd.ErrorManager)),si(2,eU(nd.AgentService)),si(3,eU(nd.ASRService)),si(4,eU(nd.DigitalHumanService)),si(5,eU(nd.ConversationService)),sr("design:type",Function),sr("design:paramtypes",["undefined"==typeof IResolvedOptions?Object:IResolvedOptions,void 0===rb?Object:rb,"undefined"==typeof AS?Object:AS,void 0===oJ?Object:oJ,void 0===oY?Object:oY,void 0===iB?Object:iB])],so);let ss=[239,187,191],sa=e=>async(n,r,i)=>{if(!i.ok||!i.body)return;let o=!1,s=n=>{var r;o||(o=!0,null==(r=e.onCompleted)||r.call(e,n))},a=i.body.getReader(),c=new TextDecoder("utf8"),l=function(e){let n,r,i,o,s,a,c;return l(),{feed:function(l){var u;r=r?r+l:l,n&&(u=r,ss.every((e,n)=>u.charCodeAt(n)===e))&&(r=r.slice(ss.length)),n=!1;let d=r.length,p=0,h=!1;for(;p<d;){let n;h&&("\n"===r[p]&&++p,h=!1);let l=-1,u=o;for(let e=i;l<0&&e<d;++e)":"===(n=r[e])&&u<0?u=e-p:"\r"===n?(h=!0,l=e-p):"\n"===n&&(l=e-p);if(l<0){i=d-p,o=u;break}i=0,o=-1,function(n,r,i,o){if(0===o){c.length>0&&(e({type:"event",id:s,event:a||void 0,data:c.slice(0,-1)}),c="",s=void 0),a=void 0;return}let l=i<0,u=n.slice(r,r+(l?o:i)),d=0;d=l?o:" "===n[r+i+1]?i+2:i+1;let p=r+d,h=o-d,f=n.slice(p,p+h).toString();if("data"===u)c+=f?"".concat(f,"\n"):"\n";else if("event"===u)a=f;else if("id"!==u||f.includes("\0")){if("retry"===u){let n=parseInt(f,10);Number.isNaN(n)||e({type:"reconnect-interval",value:n})}}else s=f}(r,p,u,l),p+=l+1}p===d?r="":p>0&&(r=r.slice(p))},reset:l};function l(){n=!0,r="",i=0,o=-1,s=void 0,a=void 0,c=""}}(n=>{var r,i,o;if("event"===n.type&&(null==(r=e.onMessage)||r.call(e,n)),"event"===n.type&&n.data)for(let r of(null==(i=e.onEvent)||i.call(e,n),n.data.split("\n")))e.onData(r);else"reconnect-interval"===n.type&&(null==(o=e.onReconnectInterval)||o.call(e,n.value))}),u=()=>{a.read().then(e=>{if(e.done)return void s();l.feed(c.decode(e.value,{stream:!0})),u()}).catch(r=>{var i;if(n.signal.aborted){null==(i=e.onAborted)||i.call(e);return}s(r)})};return u(),i};(X=(V=K||(K={})).EAiobAction||(V.EAiobAction={}))[X.silence=1]="silence",X[X.Interrupt=2]="Interrupt",X[X.Hangup=3]="Hangup",(W=V.EResponseType||(V.EResponseType={}))[W.Welcome=1]="Welcome",W[W.Normal=2]="Normal",W[W.Command=3]="Command",W[W.TakeOver=4]="TakeOver",($=V.ETextType||(V.ETextType={}))[$.unit=0]="unit",$[$.llm=1]="llm";class sc extends r_{static #k=this.REQUEST_URI="aicc-service/aiob-server/text/stream/query2";constructor(...e){super(...e),this.query=async e=>{this.abortController=new AbortController;let n=sa({onData:e=>{try{let{answer:n,sessionId:r,action:i}=JSON.parse(e);if(r&&(this.conversationSessionId=r),i===K.EAiobAction.Hangup)return void this.onHangup({sessionId:this.conversationSessionId});n&&this.onData({sessionId:this.conversationSessionId,answer:n})}catch(e){e instanceof Error&&this.errorManager.handleError(new nQ(e.message,{sessionId:this.conversationSessionId}))}},onCompleted:()=>{this.onCompleted({sessionId:this.conversationSessionId})}}),r=this.opts.agentConfig;if(!(null==r?void 0:r.robotId))return void this.errorManager.handleError(new nK(`\u{8C03}\u{7528} Agent API ${sc.REQUEST_URI} \u{65F6}\u{5FC5}\u{987B}\u{4F20}\u{5165} robotId \u{53C2}\u{6570}\u{FF0C}\u{8BF7}\u{786E}\u{8BA4}\u{540E}\u{91CD}\u{8BD5}\u{3002}`));let i={query:e,sessionId:this.conversationSessionId,robotId:r.robotId,isComplete:1,queryId:this.queryId};try{var o;await this.request.client.post(sc.REQUEST_URI,{retry:0,timeout:3e5,signal:null==(o=this.abortController)?void 0:o.signal,hooks:{afterResponse:[n]},json:{...i}})}catch(e){e instanceof nh?this.onTimeout({sessionId:this.conversationSessionId}):e instanceof Error&&this.errorManager.handleError(new nY(e.message,{sessionId:this.conversationSessionId}))}},this.hangup=async()=>{let e=this.opts.agentConfig;if(!(null==e?void 0:e.robotId))return void await this.errorManager.handleError(new nK(`\u{8C03}\u{7528} Agent API ${sc.REQUEST_URI} \u{65F6}\u{5FC5}\u{987B}\u{4F20}\u{5165} robotId \u{53C2}\u{6570}\u{FF0C}\u{8BF7}\u{786E}\u{8BA4}\u{540E}\u{91CD}\u{8BD5}\u{3002}`));let n={query:"",robotId:e.robotId,sessionId:this.conversationSessionId,action:K.EAiobAction.Hangup,isComplete:1};try{await this.request.client.post(sc.REQUEST_URI,{retry:0,timeout:3e5,json:{...n},keepalive:!0})}catch(e){e instanceof Error&&this.errorManager.handleError(new nY(e.message,{sessionId:this.conversationSessionId}))}},this.dispose=()=>{this._dispose(),this.hangup().finally(()=>{this.conversationSessionId=""})}}}sc=function(e,n,r,i){var o,s=arguments.length,a=s<3?n:null===i?i=Object.getOwnPropertyDescriptor(n,r):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)a=Reflect.decorate(e,n,r,i);else for(var c=e.length-1;c>=0;c--)(o=e[c])&&(a=(s<3?o(a):s>3?o(n,r,a):o(n,r))||a);return s>3&&a&&Object.defineProperty(n,r,a),a}([eV(),eX()],sc),(G=(z=Q||(Q={})).EReplyType||(z.EReplyType={}))[G.PlainText=1]="PlainText",G[G.RichText=3]="RichText",G[G.Image=4]="Image",G[G.List=8]="List",z.REPLY_TYPE_MAPPING={1:"plainText",3:"richText",8:"list",4:"image"};class sl extends r_{static #k=this.REQUEST_URI="csp-service/online/core/v5/stream/query";constructor(...e){super(...e),this.query=async e=>{var n,r;this.abortController=new AbortController;let i=sa({onData:e=>{try{var n,r;let i=JSON.parse(e).answer[0],o=null!=(r=null==(n=i.reply)?void 0:n.text)?r:"";i&&o?this.onData({sessionId:this.conversationSessionId,answer:o}):i&&i.instruction&&(function(e){if("object"!=typeof e||null===e||"[object Object]"!==Object.prototype.toString.call(e))return!1;let n=Object.getPrototypeOf(e);return null===n||!!(Object.prototype.hasOwnProperty.call(n,"constructor")&&"function"==typeof n.constructor)&&Function.prototype.toString.call(n.constructor)===Function.prototype.toString.call(Object)}(i.instruction)?this.onInstructionReceived({sessionId:this.conversationSessionId,instruction:i.instruction}):this.errorManager.handleError(new nZ("指令格式非法,请检查后重试",{sessionId:this.conversationSessionId})))}catch(e){e instanceof Error&&this.errorManager.handleError(new nQ(e.message,{sessionId:this.conversationSessionId}))}},onCompleted:()=>{this.onCompleted({sessionId:this.conversationSessionId})}});this.conversationSessionId||(this.conversationSessionId=rC());let o=null==(n=this.opts.agentConfig)?void 0:n.token;if(!o)return void this.errorManager.handleError(new nK(`\u{8C03}\u{7528} Agent API ${sl.REQUEST_URI} \u{65F6}\u{5FC5}\u{987B}\u{4F20}\u{5165} token \u{53C2}\u{6570}\u{FF0C}\u{8BF7}\u{786E}\u{8BA4}\u{540E}\u{91CD}\u{8BD5}\u{3002}`));let s={query:e,sessionId:this.conversationSessionId};try{await this.request.client.post(sl.REQUEST_URI,{headers:{token:o},retry:0,timeout:3e5,signal:null==(r=this.abortController)?void 0:r.signal,hooks:{afterResponse:[i]},json:{...s}})}catch(e){e instanceof nh?this.onTimeout({sessionId:this.conversationSessionId}):e instanceof Error&&this.errorManager.handleError(new nY(e.message,{sessionId:this.conversationSessionId}))}},this.dispose=()=>{this._dispose()}}}function su(e,n){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,n)}function sd(e,n){return function(r,i){n(r,i,e)}}sl=function(e,n,r,i){var o,s=arguments.length,a=s<3?n:null===i?i=Object.getOwnPropertyDescriptor(n,r):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)a=Reflect.decorate(e,n,r,i);else for(var c=e.length-1;c>=0;c--)(o=e[c])&&(a=(s<3?o(a):s>3?o(n,r,a):o(n,r))||a);return s>3&&a&&Object.defineProperty(n,r,a),a}([eV(),eX()],sl);class sp{constructor(e,n){this.opts=e,this.errorManager=n,this.started=!1,this.sessionId="",this._dispose=()=>{this.started=!1,this.sessionId=""}}}sp=function(e,n,r,i){var o,s=arguments.length,a=s<3?n:null===i?i=Object.getOwnPropertyDescriptor(n,r):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)a=Reflect.decorate(e,n,r,i);else for(var c=e.length-1;c>=0;c--)(o=e[c])&&(a=(s<3?o(a):s>3?o(n,r,a):o(n,r))||a);return s>3&&a&&Object.defineProperty(n,r,a),a}([eV(),sd(0,eU(nd.IOptions)),sd(0,ez()),sd(1,eU(nd.ErrorManager)),su("design:type",Function),su("design:paramtypes",["undefined"==typeof IResolvedOptions?Object:IResolvedOptions,void 0===rb?Object:rb])],sp);let sh=e=>{if(e)return"string"==typeof e?e:e.id};class sf extends sp{static #k=this.ONLINE_PREFIX_URL="https://ky.cloud.baidu.com/employee-console";static #G=this.SANDBOX_PREFIX_URL="https://ai.agent.kaywang.cn/api";static #eO=this.AUTH_URL="https://ky.cloud.baidu.com/employee-console/v1/access/r/ai-agent/get-authorization";get prefixUrl(){return"production"===this.opts.env?sf.ONLINE_PREFIX_URL:sf.SANDBOX_PREFIX_URL}loginBRTC(e){if("function"!=typeof window.BRTC_Start)throw Error("BRTC_Start global function is missing. Ensure baidu.rtc.sdk.js is loaded.");let n={aspublisher:!0,usingdatachannel:!0,usingvideo:!1,usingaudio:!0,showvideobps:!1,autosubscribe:!0,autoplaymuted:!1,autopublish:!0,showspinner:!1,shownovideo:!1,userevent:!0,sessionevent:!0,logintimeout:1e4,linkdownevent:rI,linkupevent:rI,logintimeoutevent:rI,mediastate:rI,remotevideoon:rI,remotevideooff:rI,remotevideocoming:rI,remotevideoloading:rI,remotevideoconnected_state:rI,remotevideoleaving:rI,remotevideounpublished:rI,localvideoconnected_state:rI,localvideopublished_ok:rI,destroyed:rI,onlocalstream:rI,onlocalstream_end:rI,remotevideo_closed:rI,onmessage:e.onmessage,userevent_joinedroom:e.userevent_joinedroom,userevent_leavingroom:e.userevent_leavingroom,remotemediastating:e.remotemediastating,remotevideoviewid:sh(e.remotevideoviewid),localvideoviewid:sh(e.localvideoviewid)};window.BRTC_Start({...n,...e})}constructor(...e){super(...e),this.currentAppId="",this.Start=async e=>{var n,r,i,o,s;this.currentAppId=this.opts.rtcID;let a=this.prefixUrl,c={};"production"===this.opts.env&&(c.authorization=await this.getAuthToken("/api/v1/aiagent/generateAIAgentCall"));let l="production"===this.opts.env?"/v1/open/ai-agent/generateAIAgentCall":"/v1/aiagent/generateAIAgentCall",u=await nH.post(`${a}${l}`,{json:{app_id:this.currentAppId,quick_start:!0,config:JSON.stringify({...e.cfg})},headers:c}).json();if(!u.ai_agent_instance_id)throw Error("ai_agent_instance_id missing in response");this.started=!0,this.sessionId=u.ai_agent_instance_id;let d=this.sessionId,p=null!=(s=null==(n=u.context)?void 0:n.token)?s:"";(null==(r=u.context)?void 0:r.uid)&&(d=u.context.uid),(null==(i=u.context)?void 0:i.appid)&&(this.currentAppId=u.context.appid),this.loginBRTC({...e,appid:this.currentAppId,roomname:this.sessionId,userid:d,token:p}),null==(o=e.success)||o.call(e)},this.Stop=async()=>{if(this.started){this.started=!1;try{let e=this.prefixUrl,n={};"production"===this.opts.env&&(n.authorization=await this.getAuthToken("/api/v1/aiagent/stopAIAgentInstance"));let r="production"===this.opts.env?"/v1/open/ai-agent/stopAIAgentInstance":"/v1/aiagent/stopAIAgentInstance";await nH.post(`${e}${r}`,{json:{app_id:this.currentAppId,ai_agent_instance_id:this.sessionId},headers:n})}catch(e){if(e instanceof np)throw Error(`stopAIAgentInstance failed (${e.response.status})`);throw e}"function"==typeof window.BRTC_Stop&&window.BRTC_Stop()}},this.Mute=e=>{"function"==typeof window.BRTC_MuteMicphone&&window.BRTC_MuteMicphone(e)},this.GetSessionID=()=>this.sessionId,this.Dispose=()=>{this._dispose()},this.getAuthToken=async e=>{try{let{data:n}=await nH.post(sf.AUTH_URL,{json:{http_method:"POST",path:e,headers:{host:"rtc-aiagent.baidubce.com"}}}).json();return n}catch(e){if(e instanceof np)throw Error(`getAuthToken failed (${e.response.status})`);throw e}}}}sf=function(e,n,r,i){var o,s=arguments.length,a=s<3?n:null===i?i=Object.getOwnPropertyDescriptor(n,r):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)a=Reflect.decorate(e,n,r,i);else for(var c=e.length-1;c>=0;c--)(o=e[c])&&(a=(s<3?o(a):s>3?o(n,r,a):o(n,r))||a);return s>3&&a&&Object.defineProperty(n,r,a),a}([eV(),eX()],sf);let sm=!0,sg=!0;function sv(e,n,r){let i=e.match(n);return i&&i.length>=r&&parseFloat(i[r],10)}function sy(e,n,r){if(!e.RTCPeerConnection)return;let i=e.RTCPeerConnection.prototype,o=i.addEventListener;i.addEventListener=function(e,i){if(e!==n)return o.apply(this,arguments);let s=e=>{let n=r(e);n&&(i.handleEvent?i.handleEvent(n):i(n))};return this._eventMap=this._eventMap||{},this._eventMap[n]||(this._eventMap[n]=new Map),this._eventMap[n].set(i,s),o.apply(this,[e,s])};let s=i.removeEventListener;i.removeEventListener=function(e,r){if(e!==n||!this._eventMap||!this._eventMap[n]||!this._eventMap[n].has(r))return s.apply(this,arguments);let i=this._eventMap[n].get(r);return this._eventMap[n].delete(r),0===this._eventMap[n].size&&delete this._eventMap[n],0===Object.keys(this._eventMap).length&&delete this._eventMap,s.apply(this,[e,i])},Object.defineProperty(i,"on"+n,{get(){return this["_on"+n]},set(e){this["_on"+n]&&(this.removeEventListener(n,this["_on"+n]),delete this["_on"+n]),e&&this.addEventListener(n,this["_on"+n]=e)},enumerable:!0,configurable:!0})}function sb(e){return"boolean"!=typeof e?Error("Argument type: "+typeof e+". Please use a boolean."):(sm=e,e?"adapter.js logging disabled":"adapter.js logging enabled")}function sw(e){return"boolean"!=typeof e?Error("Argument type: "+typeof e+". Please use a boolean."):(sg=!e,"adapter.js deprecation warnings "+(e?"disabled":"enabled"))}function sO(){"object"==typeof window&&(sm||"undefined"!=typeof console&&"function"==typeof console.log&&console.log.apply(console,arguments))}function s_(e,n){sg&&console.warn(e+" is deprecated, please use "+n+" instead.")}function sR(e){return"[object Object]"===Object.prototype.toString.call(e)}function sS(e,n,r){let i=r?"outbound-rtp":"inbound-rtp",o=new Map;if(null===n)return o;let s=[];return e.forEach(e=>{"track"===e.type&&e.trackIdentifier===n.id&&s.push(e)}),s.forEach(n=>{e.forEach(r=>{r.type===i&&r.trackId===n.id&&function e(n,r,i){!r||i.has(r.id)||(i.set(r.id,r),Object.keys(r).forEach(o=>{o.endsWith("Id")?e(n,n.get(r[o]),i):o.endsWith("Ids")&&r[o].forEach(r=>{e(n,n.get(r),i)})}))}(e,r,o)})}),o}function sT(e,n){let r=e&&e.navigator;if(!r.mediaDevices)return;let i=function(e){if("object"!=typeof e||e.mandatory||e.optional)return e;let n={};return Object.keys(e).forEach(r=>{if("require"===r||"advanced"===r||"mediaSource"===r)return;let i="object"==typeof e[r]?e[r]:{ideal:e[r]};void 0!==i.exact&&"number"==typeof i.exact&&(i.min=i.max=i.exact);let o=function(e,n){return e?e+n.charAt(0).toUpperCase()+n.slice(1):"deviceId"===n?"sourceId":n};if(void 0!==i.ideal){n.optional=n.optional||[];let e={};"number"==typeof i.ideal?(e[o("min",r)]=i.ideal,n.optional.push(e),(e={})[o("max",r)]=i.ideal):e[o("",r)]=i.ideal,n.optional.push(e)}void 0!==i.exact&&"number"!=typeof i.exact?(n.mandatory=n.mandatory||{},n.mandatory[o("",r)]=i.exact):["min","max"].forEach(e=>{void 0!==i[e]&&(n.mandatory=n.mandatory||{},n.mandatory[o(e,r)]=i[e])})}),e.advanced&&(n.optional=(n.optional||[]).concat(e.advanced)),n},o=function(e,o){if(n.version>=61)return o(e);if((e=JSON.parse(JSON.stringify(e)))&&"object"==typeof e.audio){let n=function(e,n,r){n in e&&!(r in e)&&(e[r]=e[n],delete e[n])};n((e=JSON.parse(JSON.stringify(e))).audio,"autoGainControl","googAutoGainControl"),n(e.audio,"noiseSuppression","googNoiseSuppression"),e.audio=i(e.audio)}if(e&&"object"==typeof e.video){let s=e.video.facingMode;s=s&&("object"==typeof s?s:{ideal:s});let a=n.version<66;if(s&&("user"===s.exact||"environment"===s.exact||"user"===s.ideal||"environment"===s.ideal)&&!(r.mediaDevices.getSupportedConstraints&&r.mediaDevices.getSupportedConstraints().facingMode&&!a)){let n;if(delete e.video.facingMode,"environment"===s.exact||"environment"===s.ideal?n=["back","rear"]:("user"===s.exact||"user"===s.ideal)&&(n=["front"]),n)return r.mediaDevices.enumerateDevices().then(r=>{let a=(r=r.filter(e=>"videoinput"===e.kind)).find(e=>n.some(n=>e.label.toLowerCase().includes(n)));return!a&&r.length&&n.includes("back")&&(a=r[r.length-1]),a&&(e.video.deviceId=s.exact?{exact:a.deviceId}:{ideal:a.deviceId}),e.video=i(e.video),sO("chrome: "+JSON.stringify(e)),o(e)})}e.video=i(e.video)}return sO("chrome: "+JSON.stringify(e)),o(e)},s=function(e){return n.version>=64?e:{name:({PermissionDeniedError:"NotAllowedError",PermissionDismissedError:"NotAllowedError",InvalidStateError:"NotAllowedError",DevicesNotFoundError:"NotFoundError",ConstraintNotSatisfiedError:"OverconstrainedError",TrackStartError:"NotReadableError",MediaDeviceFailedDueToShutdown:"NotAllowedError",MediaDeviceKillSwitchOn:"NotAllowedError",TabCaptureError:"AbortError",ScreenCaptureError:"AbortError",DeviceCaptureError:"AbortError"})[e.name]||e.name,message:e.message,constraint:e.constraint||e.constraintName,toString(){return this.name+(this.message&&": ")+this.message}}};if(r.getUserMedia=(function(e,n,i){o(e,e=>{r.webkitGetUserMedia(e,n,e=>{i&&i(s(e))})})}).bind(r),r.mediaDevices.getUserMedia){let e=r.mediaDevices.getUserMedia.bind(r.mediaDevices);r.mediaDevices.getUserMedia=function(n){return o(n,n=>e(n).then(e=>{if(n.audio&&!e.getAudioTracks().length||n.video&&!e.getVideoTracks().length)throw e.getTracks().forEach(e=>{e.stop()}),new DOMException("","NotFoundError");return e},e=>Promise.reject(s(e))))}}}function sE(e){e.MediaStream=e.MediaStream||e.webkitMediaStream}function sM(e){if("object"!=typeof e||!e.RTCPeerConnection||"ontrack"in e.RTCPeerConnection.prototype)sy(e,"track",e=>(e.transceiver||Object.defineProperty(e,"transceiver",{value:{receiver:e.receiver}}),e));else{Object.defineProperty(e.RTCPeerConnection.prototype,"ontrack",{get(){return this._ontrack},set(e){this._ontrack&&this.removeEventListener("track",this._ontrack),this.addEventListener("track",this._ontrack=e)},enumerable:!0,configurable:!0});let n=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(){return this._ontrackpoly||(this._ontrackpoly=n=>{n.stream.addEventListener("addtrack",r=>{let i;i=e.RTCPeerConnection.prototype.getReceivers?this.getReceivers().find(e=>e.track&&e.track.id===r.track.id):{track:r.track};let o=new Event("track");o.track=r.track,o.receiver=i,o.transceiver={receiver:i},o.streams=[n.stream],this.dispatchEvent(o)}),n.stream.getTracks().forEach(r=>{let i;i=e.RTCPeerConnection.prototype.getReceivers?this.getReceivers().find(e=>e.track&&e.track.id===r.id):{track:r};let o=new Event("track");o.track=r,o.receiver=i,o.transceiver={receiver:i},o.streams=[n.stream],this.dispatchEvent(o)})},this.addEventListener("addstream",this._ontrackpoly)),n.apply(this,arguments)}}}function sx(e){if("object"==typeof e&&e.RTCPeerConnection&&!("getSenders"in e.RTCPeerConnection.prototype)&&"createDTMFSender"in e.RTCPeerConnection.prototype){let n=function(e,n){return{track:n,get dtmf(){return void 0===this._dtmf&&("audio"===n.kind?this._dtmf=e.createDTMFSender(n):this._dtmf=null),this._dtmf},_pc:e}};if(!e.RTCPeerConnection.prototype.getSenders){e.RTCPeerConnection.prototype.getSenders=function(){return this._senders=this._senders||[],this._senders.slice()};let r=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addTrack=function(e,i){let o=r.apply(this,arguments);return o||(o=n(this,e),this._senders.push(o)),o};let i=e.RTCPeerConnection.prototype.removeTrack;e.RTCPeerConnection.prototype.removeTrack=function(e){i.apply(this,arguments);let n=this._senders.indexOf(e);-1!==n&&this._senders.splice(n,1)}}let r=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(e){this._senders=this._senders||[],r.apply(this,[e]),e.getTracks().forEach(e=>{this._senders.push(n(this,e))})};let i=e.RTCPeerConnection.prototype.removeStream;e.RTCPeerConnection.prototype.removeStream=function(e){this._senders=this._senders||[],i.apply(this,[e]),e.getTracks().forEach(e=>{let n=this._senders.find(n=>n.track===e);n&&this._senders.splice(this._senders.indexOf(n),1)})}}else if("object"==typeof e&&e.RTCPeerConnection&&"getSenders"in e.RTCPeerConnection.prototype&&"createDTMFSender"in e.RTCPeerConnection.prototype&&e.RTCRtpSender&&!("dtmf"in e.RTCRtpSender.prototype)){let n=e.RTCPeerConnection.prototype.getSenders;e.RTCPeerConnection.prototype.getSenders=function(){let e=n.apply(this,[]);return e.forEach(e=>e._pc=this),e},Object.defineProperty(e.RTCRtpSender.prototype,"dtmf",{get(){return void 0===this._dtmf&&("audio"===this.track.kind?this._dtmf=this._pc.createDTMFSender(this.track):this._dtmf=null),this._dtmf}})}}function sC(e){if(!("object"==typeof e&&e.RTCPeerConnection&&e.RTCRtpSender&&e.RTCRtpReceiver))return;if(!("getStats"in e.RTCRtpSender.prototype)){let n=e.RTCPeerConnection.prototype.getSenders;n&&(e.RTCPeerConnection.prototype.getSenders=function(){let e=n.apply(this,[]);return e.forEach(e=>e._pc=this),e});let r=e.RTCPeerConnection.prototype.addTrack;r&&(e.RTCPeerConnection.prototype.addTrack=function(){let e=r.apply(this,arguments);return e._pc=this,e}),e.RTCRtpSender.prototype.getStats=function(){let e=this;return this._pc.getStats().then(n=>sS(n,e.track,!0))}}if(!("getStats"in e.RTCRtpReceiver.prototype)){let n=e.RTCPeerConnection.prototype.getReceivers;n&&(e.RTCPeerConnection.prototype.getReceivers=function(){let e=n.apply(this,[]);return e.forEach(e=>e._pc=this),e}),sy(e,"track",e=>(e.receiver._pc=e.srcElement,e)),e.RTCRtpReceiver.prototype.getStats=function(){let e=this;return this._pc.getStats().then(n=>sS(n,e.track,!1))}}if(!("getStats"in e.RTCRtpSender.prototype&&"getStats"in e.RTCRtpReceiver.prototype))return;let n=e.RTCPeerConnection.prototype.getStats;e.RTCPeerConnection.prototype.getStats=function(){if(arguments.length>0&&arguments[0]instanceof e.MediaStreamTrack){let e,n,r,i=arguments[0];return(this.getSenders().forEach(n=>{n.track===i&&(e?r=!0:e=n)}),this.getReceivers().forEach(e=>(e.track===i&&(n?r=!0:n=e),e.track===i)),r||e&&n)?Promise.reject(new DOMException("There are more than one sender or receiver for the track.","InvalidAccessError")):e?e.getStats():n?n.getStats():Promise.reject(new DOMException("There is no sender or receiver for the track.","InvalidAccessError"))}return n.apply(this,arguments)}}function sj(e){e.RTCPeerConnection.prototype.getLocalStreams=function(){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},Object.keys(this._shimmedLocalStreams).map(e=>this._shimmedLocalStreams[e][0])};let n=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addTrack=function(e,r){if(!r)return n.apply(this,arguments);this._shimmedLocalStreams=this._shimmedLocalStreams||{};let i=n.apply(this,arguments);return this._shimmedLocalStreams[r.id]?-1===this._shimmedLocalStreams[r.id].indexOf(i)&&this._shimmedLocalStreams[r.id].push(i):this._shimmedLocalStreams[r.id]=[r,i],i};let r=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(e){this._shimmedLocalStreams=this._shimmedLocalStreams||{},e.getTracks().forEach(e=>{if(this.getSenders().find(n=>n.track===e))throw new DOMException("Track already exists.","InvalidAccessError")});let n=this.getSenders();r.apply(this,arguments);let i=this.getSenders().filter(e=>-1===n.indexOf(e));this._shimmedLocalStreams[e.id]=[e].concat(i)};let i=e.RTCPeerConnection.prototype.removeStream;e.RTCPeerConnection.prototype.removeStream=function(e){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},delete this._shimmedLocalStreams[e.id],i.apply(this,arguments)};let o=e.RTCPeerConnection.prototype.removeTrack;e.RTCPeerConnection.prototype.removeTrack=function(e){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},e&&Object.keys(this._shimmedLocalStreams).forEach(n=>{let r=this._shimmedLocalStreams[n].indexOf(e);-1!==r&&this._shimmedLocalStreams[n].splice(r,1),1===this._shimmedLocalStreams[n].length&&delete this._shimmedLocalStreams[n]}),o.apply(this,arguments)}}function sI(e,n){if(!e.RTCPeerConnection)return;if(e.RTCPeerConnection.prototype.addTrack&&n.version>=65)return sj(e);let r=e.RTCPeerConnection.prototype.getLocalStreams;e.RTCPeerConnection.prototype.getLocalStreams=function(){let e=r.apply(this);return this._reverseStreams=this._reverseStreams||{},e.map(e=>this._reverseStreams[e.id])};let i=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(n){if(this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},n.getTracks().forEach(e=>{if(this.getSenders().find(n=>n.track===e))throw new DOMException("Track already exists.","InvalidAccessError")}),!this._reverseStreams[n.id]){let r=new e.MediaStream(n.getTracks());this._streams[n.id]=r,this._reverseStreams[r.id]=n,n=r}i.apply(this,[n])};let o=e.RTCPeerConnection.prototype.removeStream;function s(e,n){let r=n.sdp;return Object.keys(e._reverseStreams||[]).forEach(n=>{let i=e._reverseStreams[n],o=e._streams[i.id];r=r.replace(RegExp(o.id,"g"),i.id)}),new RTCSessionDescription({type:n.type,sdp:r})}e.RTCPeerConnection.prototype.removeStream=function(e){this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},o.apply(this,[this._streams[e.id]||e]),delete this._reverseStreams[this._streams[e.id]?this._streams[e.id].id:e.id],delete this._streams[e.id]},e.RTCPeerConnection.prototype.addTrack=function(n,r){if("closed"===this.signalingState)throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");let i=[].slice.call(arguments,1);if(1!==i.length||!i[0].getTracks().find(e=>e===n))throw new DOMException("The adapter.js addTrack polyfill only supports a single stream which is associated with the specified track.","NotSupportedError");if(this.getSenders().find(e=>e.track===n))throw new DOMException("Track already exists.","InvalidAccessError");this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{};let o=this._streams[r.id];if(o)o.addTrack(n),Promise.resolve().then(()=>{this.dispatchEvent(new Event("negotiationneeded"))});else{let i=new e.MediaStream([n]);this._streams[r.id]=i,this._reverseStreams[i.id]=r,this.addStream(i)}return this.getSenders().find(e=>e.track===n)},["createOffer","createAnswer"].forEach(function(n){let r=e.RTCPeerConnection.prototype[n];e.RTCPeerConnection.prototype[n]=({[n](){let e=arguments,n=arguments.length&&"function"==typeof arguments[0];return n?r.apply(this,[n=>{let r=s(this,n);e[0].apply(null,[r])},n=>{e[1]&&e[1].apply(null,n)},arguments[2]]):r.apply(this,arguments).then(e=>s(this,e))}})[n]});let a=e.RTCPeerConnection.prototype.setLocalDescription;e.RTCPeerConnection.prototype.setLocalDescription=function(){var e,n;let r;return arguments.length&&arguments[0].type?(arguments[0]=(e=this,n=arguments[0],r=n.sdp,Object.keys(e._reverseStreams||[]).forEach(n=>{let i=e._reverseStreams[n],o=e._streams[i.id];r=r.replace(RegExp(i.id,"g"),o.id)}),new RTCSessionDescription({type:n.type,sdp:r})),a.apply(this,arguments)):a.apply(this,arguments)};let c=Object.getOwnPropertyDescriptor(e.RTCPeerConnection.prototype,"localDescription");Object.defineProperty(e.RTCPeerConnection.prototype,"localDescription",{get(){let e=c.get.apply(this);return""===e.type?e:s(this,e)}}),e.RTCPeerConnection.prototype.removeTrack=function(e){let n;if("closed"===this.signalingState)throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");if(!e._pc)throw new DOMException("Argument 1 of RTCPeerConnection.removeTrack does not implement interface RTCRtpSender.","TypeError");if(e._pc!==this)throw new DOMException("Sender was not created by this connection.","InvalidAccessError");this._streams=this._streams||{},Object.keys(this._streams).forEach(r=>{this._streams[r].getTracks().find(n=>e.track===n)&&(n=this._streams[r])}),n&&(1===n.getTracks().length?this.removeStream(this._reverseStreams[n.id]):n.removeTrack(e.track),this.dispatchEvent(new Event("negotiationneeded")))}}function sB(e,n){!e.RTCPeerConnection&&e.webkitRTCPeerConnection&&(e.RTCPeerConnection=e.webkitRTCPeerConnection),e.RTCPeerConnection&&n.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach(function(n){let r=e.RTCPeerConnection.prototype[n];e.RTCPeerConnection.prototype[n]=({[n](){return arguments[0]=new("addIceCandidate"===n?e.RTCIceCandidate:e.RTCSessionDescription)(arguments[0]),r.apply(this,arguments)}})[n]})}function sk(e,n){sy(e,"negotiationneeded",e=>{let r=e.target;if(!(n.version<72)&&(!r.getConfiguration||"plan-b"!==r.getConfiguration().sdpSemantics)||"stable"===r.signalingState)return e})}function sA(e,n){let r=e&&e.navigator,i=e&&e.MediaStreamTrack;if(r.getUserMedia=function(e,n,i){s_("navigator.getUserMedia","navigator.mediaDevices.getUserMedia"),r.mediaDevices.getUserMedia(e).then(n,i)},!(n.version>55&&"autoGainControl"in r.mediaDevices.getSupportedConstraints())){let e=function(e,n,r){n in e&&!(r in e)&&(e[r]=e[n],delete e[n])},n=r.mediaDevices.getUserMedia.bind(r.mediaDevices);if(r.mediaDevices.getUserMedia=function(r){return"object"==typeof r&&"object"==typeof r.audio&&(e((r=JSON.parse(JSON.stringify(r))).audio,"autoGainControl","mozAutoGainControl"),e(r.audio,"noiseSuppression","mozNoiseSuppression")),n(r)},i&&i.prototype.getSettings){let n=i.prototype.getSettings;i.prototype.getSettings=function(){let r=n.apply(this,arguments);return e(r,"mozAutoGainControl","autoGainControl"),e(r,"mozNoiseSuppression","noiseSuppression"),r}}if(i&&i.prototype.applyConstraints){let n=i.prototype.applyConstraints;i.prototype.applyConstraints=function(r){return"audio"===this.kind&&"object"==typeof r&&(e(r=JSON.parse(JSON.stringify(r)),"autoGainControl","mozAutoGainControl"),e(r,"noiseSuppression","mozNoiseSuppression")),n.apply(this,[r])}}}}function sP(e,n){e.navigator.mediaDevices&&"getDisplayMedia"in e.navigator.mediaDevices||e.navigator.mediaDevices&&(e.navigator.mediaDevices.getDisplayMedia=function(r){if(!(r&&r.video)){let e=new DOMException("getDisplayMedia without video constraints is undefined");return e.name="NotFoundError",e.code=8,Promise.reject(e)}return!0===r.video?r.video={mediaSource:n}:r.video.mediaSource=n,e.navigator.mediaDevices.getUserMedia(r)})}function sN(e){"object"==typeof e&&e.RTCTrackEvent&&"receiver"in e.RTCTrackEvent.prototype&&!("transceiver"in e.RTCTrackEvent.prototype)&&Object.defineProperty(e.RTCTrackEvent.prototype,"transceiver",{get(){return{receiver:this.receiver}}})}function sL(e,n){if("object"!=typeof e||!(e.RTCPeerConnection||e.mozRTCPeerConnection))return;!e.RTCPeerConnection&&e.mozRTCPeerConnection&&(e.RTCPeerConnection=e.mozRTCPeerConnection),n.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach(function(n){let r=e.RTCPeerConnection.prototype[n];e.RTCPeerConnection.prototype[n]=({[n](){return arguments[0]=new("addIceCandidate"===n?e.RTCIceCandidate:e.RTCSessionDescription)(arguments[0]),r.apply(this,arguments)}})[n]});let r={inboundrtp:"inbound-rtp",outboundrtp:"outbound-rtp",candidatepair:"candidate-pair",localcandidate:"local-candidate",remotecandidate:"remote-candidate"},i=e.RTCPeerConnection.prototype.getStats;e.RTCPeerConnection.prototype.getStats=function(){let[e,o,s]=arguments;return i.apply(this,[e||null]).then(e=>{if(n.version<53&&!o)try{e.forEach(e=>{e.type=r[e.type]||e.type})}catch(n){if("TypeError"!==n.name)throw n;e.forEach((n,i)=>{e.set(i,Object.assign({},n,{type:r[n.type]||n.type}))})}return e}).then(o,s)}}function sD(e){if(!("object"==typeof e&&e.RTCPeerConnection&&e.RTCRtpSender)||e.RTCRtpSender&&"getStats"in e.RTCRtpSender.prototype)return;let n=e.RTCPeerConnection.prototype.getSenders;n&&(e.RTCPeerConnection.prototype.getSenders=function(){let e=n.apply(this,[]);return e.forEach(e=>e._pc=this),e});let r=e.RTCPeerConnection.prototype.addTrack;r&&(e.RTCPeerConnection.prototype.addTrack=function(){let e=r.apply(this,arguments);return e._pc=this,e}),e.RTCRtpSender.prototype.getStats=function(){return this.track?this._pc.getStats(this.track):Promise.resolve(new Map)}}function sF(e){if(!("object"==typeof e&&e.RTCPeerConnection&&e.RTCRtpSender)||e.RTCRtpSender&&"getStats"in e.RTCRtpReceiver.prototype)return;let n=e.RTCPeerConnection.prototype.getReceivers;n&&(e.RTCPeerConnection.prototype.getReceivers=function(){let e=n.apply(this,[]);return e.forEach(e=>e._pc=this),e}),sy(e,"track",e=>(e.receiver._pc=e.srcElement,e)),e.RTCRtpReceiver.prototype.getStats=function(){return this._pc.getStats(this.track)}}function sU(e){!e.RTCPeerConnection||"removeStream"in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.removeStream=function(e){s_("removeStream","removeTrack"),this.getSenders().forEach(n=>{n.track&&e.getTracks().includes(n.track)&&this.removeTrack(n)})})}function sH(e){e.DataChannel&&!e.RTCDataChannel&&(e.RTCDataChannel=e.DataChannel)}function sq(e){if(!("object"==typeof e&&e.RTCPeerConnection))return;let n=e.RTCPeerConnection.prototype.addTransceiver;n&&(e.RTCPeerConnection.prototype.addTransceiver=function(){this.setParametersPromises=[];let e=arguments[1]&&arguments[1].sendEncodings;void 0===e&&(e=[]);let r=(e=[...e]).length>0;r&&e.forEach(e=>{if("rid"in e&&!/^[a-z0-9]{0,16}$/i.test(e.rid))throw TypeError("Invalid RID value provided.");if("scaleResolutionDownBy"in e&&!(parseFloat(e.scaleResolutionDownBy)>=1))throw RangeError("scale_resolution_down_by must be >= 1.0");if("maxFramerate"in e&&!(parseFloat(e.maxFramerate)>=0))throw RangeError("max_framerate must be >= 0.0")});let i=n.apply(this,arguments);if(r){let{sender:n}=i,r=n.getParameters();"encodings"in r&&(1!==r.encodings.length||0!==Object.keys(r.encodings[0]).length)||(r.encodings=e,n.sendEncodings=e,this.setParametersPromises.push(n.setParameters(r).then(()=>{delete n.sendEncodings}).catch(()=>{delete n.sendEncodings})))}return i})}function sV(e){if(!("object"==typeof e&&e.RTCRtpSender))return;let n=e.RTCRtpSender.prototype.getParameters;n&&(e.RTCRtpSender.prototype.getParameters=function(){let e=n.apply(this,arguments);return"encodings"in e||(e.encodings=[].concat(this.sendEncodings||[{}])),e})}function sX(e){if(!("object"==typeof e&&e.RTCPeerConnection))return;let n=e.RTCPeerConnection.prototype.createOffer;e.RTCPeerConnection.prototype.createOffer=function(){return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then(()=>n.apply(this,arguments)).finally(()=>{this.setParametersPromises=[]}):n.apply(this,arguments)}}function sW(e){if(!("object"==typeof e&&e.RTCPeerConnection))return;let n=e.RTCPeerConnection.prototype.createAnswer;e.RTCPeerConnection.prototype.createAnswer=function(){return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then(()=>n.apply(this,arguments)).finally(()=>{this.setParametersPromises=[]}):n.apply(this,arguments)}}function s$(e){if("object"==typeof e&&e.RTCPeerConnection){if("getLocalStreams"in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.getLocalStreams=function(){return this._localStreams||(this._localStreams=[]),this._localStreams}),!("addStream"in e.RTCPeerConnection.prototype)){let n=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addStream=function(e){this._localStreams||(this._localStreams=[]),this._localStreams.includes(e)||this._localStreams.push(e),e.getAudioTracks().forEach(r=>n.call(this,r,e)),e.getVideoTracks().forEach(r=>n.call(this,r,e))},e.RTCPeerConnection.prototype.addTrack=function(e,...r){return r&&r.forEach(e=>{this._localStreams?this._localStreams.includes(e)||this._localStreams.push(e):this._localStreams=[e]}),n.apply(this,arguments)}}"removeStream"in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.removeStream=function(e){this._localStreams||(this._localStreams=[]);let n=this._localStreams.indexOf(e);if(-1===n)return;this._localStreams.splice(n,1);let r=e.getTracks();this.getSenders().forEach(e=>{r.includes(e.track)&&this.removeTrack(e)})})}}function sz(e){if("object"==typeof e&&e.RTCPeerConnection&&("getRemoteStreams"in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.getRemoteStreams=function(){return this._remoteStreams?this._remoteStreams:[]}),!("onaddstream"in e.RTCPeerConnection.prototype))){Object.defineProperty(e.RTCPeerConnection.prototype,"onaddstream",{get(){return this._onaddstream},set(e){this._onaddstream&&(this.removeEventListener("addstream",this._onaddstream),this.removeEventListener("track",this._onaddstreampoly)),this.addEventListener("addstream",this._onaddstream=e),this.addEventListener("track",this._onaddstreampoly=e=>{e.streams.forEach(e=>{if(this._remoteStreams||(this._remoteStreams=[]),this._remoteStreams.includes(e))return;this._remoteStreams.push(e);let n=new Event("addstream");n.stream=e,this.dispatchEvent(n)})})}});let n=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(){let e=this;return this._onaddstreampoly||this.addEventListener("track",this._onaddstreampoly=function(n){n.streams.forEach(n=>{if(e._remoteStreams||(e._remoteStreams=[]),e._remoteStreams.indexOf(n)>=0)return;e._remoteStreams.push(n);let r=new Event("addstream");r.stream=n,e.dispatchEvent(r)})}),n.apply(e,arguments)}}}function sG(e){if("object"!=typeof e||!e.RTCPeerConnection)return;let n=e.RTCPeerConnection.prototype,r=n.createOffer,i=n.createAnswer,o=n.setLocalDescription,s=n.setRemoteDescription,a=n.addIceCandidate;n.createOffer=function(e,n){let i=arguments.length>=2?arguments[2]:arguments[0],o=r.apply(this,[i]);return n?(o.then(e,n),Promise.resolve()):o},n.createAnswer=function(e,n){let r=arguments.length>=2?arguments[2]:arguments[0],o=i.apply(this,[r]);return n?(o.then(e,n),Promise.resolve()):o};let c=function(e,n,r){let i=o.apply(this,[e]);return r?(i.then(n,r),Promise.resolve()):i};n.setLocalDescription=c,n.setRemoteDescription=c=function(e,n,r){let i=s.apply(this,[e]);return r?(i.then(n,r),Promise.resolve()):i},n.addIceCandidate=function(e,n,r){let i=a.apply(this,[e]);return r?(i.then(n,r),Promise.resolve()):i}}function sJ(e){let n=e&&e.navigator;if(n.mediaDevices&&n.mediaDevices.getUserMedia){let e=n.mediaDevices,r=e.getUserMedia.bind(e);n.mediaDevices.getUserMedia=e=>r(sK(e))}!n.getUserMedia&&n.mediaDevices&&n.mediaDevices.getUserMedia&&(n.getUserMedia=(function(e,r,i){n.mediaDevices.getUserMedia(e).then(r,i)}).bind(n))}function sK(e){return e&&void 0!==e.video?Object.assign({},e,{video:function e(n){return sR(n)?Object.keys(n).reduce(function(r,i){let o=sR(n[i]),s=o?e(n[i]):n[i],a=o&&!Object.keys(s).length;return void 0===s||a?r:Object.assign(r,{[i]:s})},{}):n}(e.video)}):e}function sQ(e){if(!e.RTCPeerConnection)return;let n=e.RTCPeerConnection;e.RTCPeerConnection=function(e,r){if(e&&e.iceServers){let n=[];for(let r=0;r<e.iceServers.length;r++){let i=e.iceServers[r];void 0===i.urls&&i.url?(s_("RTCIceServer.url","RTCIceServer.urls"),(i=JSON.parse(JSON.stringify(i))).urls=i.url,delete i.url,n.push(i)):n.push(e.iceServers[r])}e.iceServers=n}return new n(e,r)},e.RTCPeerConnection.prototype=n.prototype,"generateCertificate"in n&&Object.defineProperty(e.RTCPeerConnection,"generateCertificate",{get:()=>n.generateCertificate})}function sY(e){"object"==typeof e&&e.RTCTrackEvent&&"receiver"in e.RTCTrackEvent.prototype&&!("transceiver"in e.RTCTrackEvent.prototype)&&Object.defineProperty(e.RTCTrackEvent.prototype,"transceiver",{get(){return{receiver:this.receiver}}})}function sZ(e){let n=e.RTCPeerConnection.prototype.createOffer;e.RTCPeerConnection.prototype.createOffer=function(e){if(e){void 0!==e.offerToReceiveAudio&&(e.offerToReceiveAudio=!!e.offerToReceiveAudio);let n=this.getTransceivers().find(e=>"audio"===e.receiver.track.kind);!1===e.offerToReceiveAudio&&n?"sendrecv"===n.direction?n.setDirection?n.setDirection("sendonly"):n.direction="sendonly":"recvonly"===n.direction&&(n.setDirection?n.setDirection("inactive"):n.direction="inactive"):!0!==e.offerToReceiveAudio||n||this.addTransceiver("audio",{direction:"recvonly"}),void 0!==e.offerToReceiveVideo&&(e.offerToReceiveVideo=!!e.offerToReceiveVideo);let r=this.getTransceivers().find(e=>"video"===e.receiver.track.kind);!1===e.offerToReceiveVideo&&r?"sendrecv"===r.direction?r.setDirection?r.setDirection("sendonly"):r.direction="sendonly":"recvonly"===r.direction&&(r.setDirection?r.setDirection("inactive"):r.direction="inactive"):!0!==e.offerToReceiveVideo||r||this.addTransceiver("video",{direction:"recvonly"})}return n.apply(this,arguments)}}function s0(e){"object"!=typeof e||e.AudioContext||(e.AudioContext=e.webkitAudioContext)}var s1=et("../../node_modules/sdp/sdp.js"),s2=et.n(s1);function s3(e){if(!e.RTCIceCandidate||e.RTCIceCandidate&&"foundation"in e.RTCIceCandidate.prototype)return;let n=e.RTCIceCandidate;e.RTCIceCandidate=function(e){if("object"==typeof e&&e.candidate&&0===e.candidate.indexOf("a=")&&((e=JSON.parse(JSON.stringify(e))).candidate=e.candidate.substring(2)),e.candidate&&e.candidate.length){let r=new n(e),i=s2().parseCandidate(e.candidate);for(let e in i)e in r||Object.defineProperty(r,e,{value:i[e]});return r.toJSON=function(){return{candidate:r.candidate,sdpMid:r.sdpMid,sdpMLineIndex:r.sdpMLineIndex,usernameFragment:r.usernameFragment}},r}return new n(e)},e.RTCIceCandidate.prototype=n.prototype,sy(e,"icecandidate",n=>(n.candidate&&Object.defineProperty(n,"candidate",{value:new e.RTCIceCandidate(n.candidate),writable:"false"}),n))}function s6(e){!e.RTCIceCandidate||e.RTCIceCandidate&&"relayProtocol"in e.RTCIceCandidate.prototype||sy(e,"icecandidate",e=>{if(e.candidate){let n=s2().parseCandidate(e.candidate.candidate);"relay"===n.type&&(e.candidate.relayProtocol=({0:"tls",1:"tcp",2:"udp"})[n.priority>>24])}return e})}function s5(e,n){if(!e.RTCPeerConnection)return;"sctp"in e.RTCPeerConnection.prototype||Object.defineProperty(e.RTCPeerConnection.prototype,"sctp",{get(){return void 0===this._sctp?null:this._sctp}});let r=function(e){if(!e||!e.sdp)return!1;let n=s2().splitSections(e.sdp);return n.shift(),n.some(e=>{let n=s2().parseMLine(e);return n&&"application"===n.kind&&-1!==n.protocol.indexOf("SCTP")})},i=function(e){let n=e.sdp.match(/mozilla...THIS_IS_SDPARTA-(\d+)/);if(null===n||n.length<2)return -1;let r=parseInt(n[1],10);return r!=r?-1:r},o=function(e){let r=65536;return"firefox"===n.browser&&(r=n.version<57?-1===e?16384:0x7ffffff5:n.version<60?57===n.version?65535:65536:0x7ffffff5),r},s=function(e,r){let i=65536;"firefox"===n.browser&&57===n.version&&(i=65535);let o=s2().matchPrefix(e.sdp,"a=max-message-size:");return o.length>0?i=parseInt(o[0].substring(19),10):"firefox"===n.browser&&-1!==r&&(i=0x7ffffff5),i},a=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(){if(this._sctp=null,"chrome"===n.browser&&n.version>=76){let{sdpSemantics:e}=this.getConfiguration();"plan-b"===e&&Object.defineProperty(this,"sctp",{get(){return void 0===this._sctp?null:this._sctp},enumerable:!0,configurable:!0})}if(r(arguments[0])){let e,n=i(arguments[0]),r=o(n),a=s(arguments[0],n);e=0===r&&0===a?Number.POSITIVE_INFINITY:0===r||0===a?Math.max(r,a):Math.min(r,a);let c={};Object.defineProperty(c,"maxMessageSize",{get:()=>e}),this._sctp=c}return a.apply(this,arguments)}}function s4(e){if(!(e.RTCPeerConnection&&"createDataChannel"in e.RTCPeerConnection.prototype))return;function n(e,n){let r=e.send;e.send=function(){let i=arguments[0],o=i.length||i.size||i.byteLength;if("open"===e.readyState&&n.sctp&&o>n.sctp.maxMessageSize)throw TypeError("Message too large (can send a maximum of "+n.sctp.maxMessageSize+" bytes)");return r.apply(e,arguments)}}let r=e.RTCPeerConnection.prototype.createDataChannel;e.RTCPeerConnection.prototype.createDataChannel=function(){let e=r.apply(this,arguments);return n(e,this),e},sy(e,"datachannel",e=>(n(e.channel,e.target),e))}function s8(e){if(!e.RTCPeerConnection||"connectionState"in e.RTCPeerConnection.prototype)return;let n=e.RTCPeerConnection.prototype;Object.defineProperty(n,"connectionState",{get(){return({completed:"connected",checking:"connecting"})[this.iceConnectionState]||this.iceConnectionState},enumerable:!0,configurable:!0}),Object.defineProperty(n,"onconnectionstatechange",{get(){return this._onconnectionstatechange||null},set(e){this._onconnectionstatechange&&(this.removeEventListener("connectionstatechange",this._onconnectionstatechange),delete this._onconnectionstatechange),e&&this.addEventListener("connectionstatechange",this._onconnectionstatechange=e)},enumerable:!0,configurable:!0}),["setLocalDescription","setRemoteDescription"].forEach(e=>{let r=n[e];n[e]=function(){return this._connectionstatechangepoly||(this._connectionstatechangepoly=e=>{let n=e.target;if(n._lastConnectionState!==n.connectionState){n._lastConnectionState=n.connectionState;let r=new Event("connectionstatechange",e);n.dispatchEvent(r)}return e},this.addEventListener("iceconnectionstatechange",this._connectionstatechangepoly)),r.apply(this,arguments)}})}function s9(e,n){if(!e.RTCPeerConnection||"chrome"===n.browser&&n.version>=71||"safari"===n.browser&&n._safariVersion>=13.1)return;let r=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(n){if(n&&n.sdp&&-1!==n.sdp.indexOf("\na=extmap-allow-mixed")){let r=n.sdp.split("\n").filter(e=>"a=extmap-allow-mixed"!==e.trim()).join("\n");e.RTCSessionDescription&&n instanceof e.RTCSessionDescription?arguments[0]=new e.RTCSessionDescription({type:n.type,sdp:r}):n.sdp=r}return r.apply(this,arguments)}}function s7(e,n){if(!(e.RTCPeerConnection&&e.RTCPeerConnection.prototype))return;let r=e.RTCPeerConnection.prototype.addIceCandidate;r&&0!==r.length&&(e.RTCPeerConnection.prototype.addIceCandidate=function(){return arguments[0]?("chrome"===n.browser&&n.version<78||"firefox"===n.browser&&n.version<68||"safari"===n.browser)&&arguments[0]&&""===arguments[0].candidate?Promise.resolve():r.apply(this,arguments):(arguments[1]&&arguments[1].apply(null),Promise.resolve())})}function ae(e,n){if(!(e.RTCPeerConnection&&e.RTCPeerConnection.prototype))return;let r=e.RTCPeerConnection.prototype.setLocalDescription;r&&0!==r.length&&(e.RTCPeerConnection.prototype.setLocalDescription=function(){let e=arguments[0]||{};if("object"!=typeof e||e.type&&e.sdp)return r.apply(this,arguments);if(!(e={type:e.type,sdp:e.sdp}).type)switch(this.signalingState){case"stable":case"have-local-offer":case"have-remote-pranswer":e.type="offer";break;default:e.type="answer"}return e.sdp||"offer"!==e.type&&"answer"!==e.type?r.apply(this,[e]):("offer"===e.type?this.createOffer:this.createAnswer).apply(this).then(e=>r.apply(this,[e]))})}let at=function({window:e}={},n={shimChrome:!0,shimFirefox:!0,shimSafari:!0}){let r=function(e){let n={browser:null,version:null};if(void 0===e||!e.navigator||!e.navigator.userAgent)return n.browser="Not a browser.",n;let{navigator:r}=e;if(r.userAgentData&&r.userAgentData.brands){let e=r.userAgentData.brands.find(e=>"Chromium"===e.brand);if(e)return{browser:"chrome",version:parseInt(e.version,10)}}return r.mozGetUserMedia?(n.browser="firefox",n.version=parseInt(sv(r.userAgent,/Firefox\/(\d+)\./,1))):r.webkitGetUserMedia||!1===e.isSecureContext&&e.webkitRTCPeerConnection?(n.browser="chrome",n.version=parseInt(sv(r.userAgent,/Chrom(e|ium)\/(\d+)\./,2))):e.RTCPeerConnection&&r.userAgent.match(/AppleWebKit\/(\d+)\./)?(n.browser="safari",n.version=parseInt(sv(r.userAgent,/AppleWebKit\/(\d+)\./,1)),n.supportsUnifiedPlan=e.RTCRtpTransceiver&&"currentDirection"in e.RTCRtpTransceiver.prototype,n._safariVersion=sv(r.userAgent,/Version\/(\d+(\.?\d+))/,1)):n.browser="Not a supported browser.",n}(e),i={browserDetails:r,commonShim:eo,extractVersion:sv,disableLog:sb,disableWarnings:sw,sdp:s1};switch(r.browser){case"chrome":if(!en||!sB||!n.shimChrome){sO("Chrome shim is not included in this adapter release.");break}if(null===r.version){sO("Chrome shim can not determine version, not shimming.");break}sO("adapter.js shimming chrome."),i.browserShim=en,s7(e,r),ae(e,r),sT(e,r),sE(e,r),sB(e,r),sM(e,r),sI(e,r),sx(e,r),sC(e,r),sk(e,r),s3(e,r),s6(e,r),s8(e,r),s5(e,r),s4(e,r),s9(e,r);break;case"firefox":if(!er||!sL||!n.shimFirefox){sO("Firefox shim is not included in this adapter release.");break}sO("adapter.js shimming firefox."),i.browserShim=er,s7(e,r),ae(e,r),sA(e,r),sL(e,r),sN(e,r),sU(e,r),sD(e,r),sF(e,r),sH(e,r),sq(e,r),sV(e,r),sX(e,r),sW(e,r),s3(e,r),s8(e,r),s5(e,r),s4(e,r);break;case"safari":if(!ei||!n.shimSafari){sO("Safari shim is not included in this adapter release.");break}sO("adapter.js shimming safari."),i.browserShim=ei,s7(e,r),ae(e,r),sQ(e,r),sZ(e,r),sG(e,r),s$(e,r),sz(e,r),sY(e,r),sJ(e,r),s0(e,r),s3(e,r),s6(e,r),s5(e,r),s4(e,r),s9(e,r);break;default:sO("Unsupported browser!")}return i}({window:"undefined"==typeof window?void 0:window});(J=Y||(Y={})).DEFAULT_BRTC_SDK_URL="https://brtc-sdk.cdn.bcebos.com/npm/baidurtc@1.2.19/baidu.rtc.sdk.js",J.DEFAULT_BRTC_CLIENT_CONFIG={displayName:"AaaSPilot Kit",debugLevel:!1,rtcOptions:{},cfg:{tag:"H5.SDK",llm:"LLMMute",tts:"MUTE"},silenceTimeoutMs:1e4};let an=e=>{if(e)return"string"==typeof e?e:e.id};class ar extends oJ{static #k=this.MESSAGE_INTERVAL_THRESHOLD=5e3;preloadDeps(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:Y.DEFAULT_BRTC_SDK_URL;return"undefined"==typeof window||window.adapter||(window.adapter=null!=at?at:es),"function"==typeof window.BRTC_Start?Promise.resolve():(this.brtcLoadPromise||(this.brtcLoadPromise=new Promise((n,r)=>{let i=document.createElement("script");i.src=e,i.async=!0,i.onload=()=>n(),i.onerror=()=>{this.errorManager.handleError(new n8(`Failed to load BRTC SDK: ${e}`)),r(Error(`Failed to load BRTC SDK: ${e}`))},document.head.appendChild(i)})),this.brtcLoadPromise)}makeStartOptions(){return{...Y.DEFAULT_BRTC_CLIENT_CONFIG,cfg:{...Y.DEFAULT_BRTC_CLIENT_CONFIG.cfg,asr_vad:this.opts.asrVad}}}parseMessage(e){let n=e.replace(/\[Q\]:?|\[M\]:?|\[C\]:?|\[A\]:?|\[H\]:?|\[E\]:?|\[B\]:?|\[T\]:?/g,"").trim(),r=F.EMessageType.Event,i=!0,o=!1,s=!1;return s=e.includes("VOICE_COMING"),e.includes("[Q]")&&(r=F.EMessageType.Query),e.includes("[E]")&&(r=F.EMessageType.Event),i=!e.includes("[M]"),{type:r,continued:e.includes("[C]"),data:n,completed:i,isCollectingSounds:s}}constructor(...e){super(...e),this.brtcLoadPromise=null,this.silenceTimer=null,this.lastMessageTime=0,this.messageIntervalTimer=null,this.start=async()=>{if(this.started)return;await this._ensureMicPermission();let{displayName:e,debugLevel:n,rtcOptions:{remoteVideoElement:r,localVideoElement:i},cfg:o,silenceTimeoutMs:s}=this.makeStartOptions();return new Promise((a,c)=>{this.signalingService.Start({debuglevel:n,cfg:o,displayname:e,remotevideoviewid:an(r),localvideoviewid:an(i),usingremotemediastate:!0,success:()=>{this.started=!0,this.emitter.emit("start",{sessionId:this.sessionId}).catch(rI),a()},error:e=>{this.errorManager.handleError(new rn(e||"",{sessionId:this.sessionId})),c(Error(e||""))},onmessage:e=>{try{let n=this.parseMessage(e.data);if(e.data.includes("VOICE_COMING")||(this.emitter.emitSerial("message",{...n,sessionId:this.sessionId}).catch(rI),this.checkMessageInterval(n)),0!==s){let r=""===n.data;(e.data.includes("[E]")||e.data.includes("VOICE_COMING"))&&r?this.triggerSilence():this.resetSilenceTimer()}}catch(e){e instanceof Error&&this.errorManager.handleError(new re(e.message,{sessionId:this.sessionId}))}},userevent_joinedroom:(e,n,r)=>{this.emitter.emit("user_joined_room",{id:e,display:n,attribute:r,sessionId:this.sessionId})},userevent_leavingroom:(e,n)=>{this.emitter.emit("user_leaving_room",{id:e,display:n,sessionId:this.sessionId})},remotemediastating:(e,n,r)=>{this.emitter.emit("media_state_changed",{id:e,medium:n,on:r,sessionId:this.sessionId})}})})},this.stop=async()=>{try{await this._stop()}catch(e){e instanceof Error&&this.errorManager.handleError(new n9(e.message,{sessionId:this.sessionId}))}this.emitter.emit("stop",{sessionId:this.signalingService.GetSessionID()})},this.dispose=()=>{this._dispose(),this.brtcLoadPromise=null,this.silenceTimer&&(window.clearTimeout(this.silenceTimer),this.silenceTimer=null),this.messageIntervalTimer&&(window.clearTimeout(this.messageIntervalTimer),this.messageIntervalTimer=null),this.lastMessageTime=0},this.resetSilenceTimer=()=>{null!==this.silenceTimer&&window.clearTimeout(this.silenceTimer),this.silenceTimer=window.setTimeout(()=>{this.emitter.emit("silence",{sessionId:this.signalingService.GetSessionID()})},this.makeStartOptions().silenceTimeoutMs)},this.triggerSilence=()=>{this.emitter.emit("silence",{sessionId:this.signalingService.GetSessionID()}),this.resetSilenceTimer()},this.checkMessageInterval=e=>{let n=Date.now();if(e.completed){this.messageIntervalTimer&&(window.clearTimeout(this.messageIntervalTimer),this.messageIntervalTimer=null),this.lastMessageTime=0;return}if(0===this.lastMessageTime)this.lastMessageTime=n,this.messageIntervalTimer=window.setTimeout(()=>{this.errorManager.handleError(new rt(`ASR\u{6D88}\u{606F}\u{95F4}\u{9694}\u{8D85}\u{8FC7}${ar.MESSAGE_INTERVAL_THRESHOLD}ms\u{9608}\u{503C}`,{sessionId:this.sessionId,context:{lastMessageTime:this.lastMessageTime,currentTime:n,threshold:ar.MESSAGE_INTERVAL_THRESHOLD}}))},ar.MESSAGE_INTERVAL_THRESHOLD);else{let e=n-this.lastMessageTime;e>ar.MESSAGE_INTERVAL_THRESHOLD&&this.errorManager.handleError(new rt(`ASR\u{6D88}\u{606F}\u{95F4}\u{9694}${e}ms\u{8D85}\u{8FC7}${ar.MESSAGE_INTERVAL_THRESHOLD}ms\u{9608}\u{503C}`,{sessionId:this.sessionId,context:{lastMessageTime:this.lastMessageTime,currentTime:n,interval:e,threshold:ar.MESSAGE_INTERVAL_THRESHOLD}})),this.lastMessageTime=n,this.messageIntervalTimer&&window.clearTimeout(this.messageIntervalTimer),this.messageIntervalTimer=window.setTimeout(()=>{this.errorManager.handleError(new rt(`ASR\u{6D88}\u{606F}\u{95F4}\u{9694}\u{8D85}\u{8FC7}${ar.MESSAGE_INTERVAL_THRESHOLD}ms\u{9608}\u{503C}`,{sessionId:this.sessionId,context:{lastMessageTime:this.lastMessageTime,currentTime:Date.now(),threshold:ar.MESSAGE_INTERVAL_THRESHOLD}}))},ar.MESSAGE_INTERVAL_THRESHOLD)}}}}ar=function(e,n,r,i){var o,s=arguments.length,a=s<3?n:null===i?i=Object.getOwnPropertyDescriptor(n,r):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)a=Reflect.decorate(e,n,r,i);else for(var c=e.length-1;c>=0;c--)(o=e[c])&&(a=(s<3?o(a):s>3?o(n,r,a):o(n,r))||a);return s>3&&a&&Object.defineProperty(n,r,a),a}([eV(),eX()],ar),function(){if("undefined"==typeof AbortSignal)return console.warn("AbortSignal is not defined in this environment. The polyfill will not be installed.");iN("any",ik.abortSignalAny),iN("timeout",iA.abortSignalTimeout),iN("abort",iP.abortSignalAbort)}();let ai=e=>{var n;let r=new t0({defaultScope:"Singleton"}),i={...rT,...e,hotWordReplacementRules:[...rR,...null!=(n=e.hotWordReplacementRules)?n:[]]};r.bind(nd.IOptions).toConstantValue(i),r.bind(nd.ErrorManager).to(rb),r.bind(nd.CommonRequest).to(nX);let{agentConfig:o,agentService:s,enableDebugMode:a}=i,c=!!(null==o?void 0:o.robotId),l=!!(null==o?void 0:o.token),u=!!s;if(u&&o&&a&&console.warn("[createAaaSPilotKit] agentService 已提供,agentConfig 配置将被忽略。"),!u&&!c&&!l)throw Error("[createAaaSPilotKit] 未检测到有效的 agent 配置,请至少提供 agentService 或 agentConfig 中的 robotId/token。");s?(Reflect.hasOwnMetadata("@inversifyjs/core/classIsInjectableFlagReflectKey",s)||(eT(eX(),s),eT(eV(),s)),r.bind(nd.AgentService).to(s)):l?r.bind(nd.AgentService).to(sl):c&&r.bind(nd.AgentService).to(sc),r.bind(nd.SignalingService).to(sf),r.bind(nd.ASRService).to(ar);let{rendererMode:d}=i;return r.bind(nd.DigitalHumanService).to(sn),r.bind(nd.ConversationService).to(iB),r.bind(nd.AaaSPilotKitController).to(so),r.get(nd.AaaSPilotKitController)};export{iC as AIWorkerConversationBean,so as AaaSPilotKitController,r_ as BaseAgentService,rB as ClientConversationBean,rj as ConversationBean,iB as ConversationService,rT as DEFAULT_OPTIONS,ai as createAaaSPilotKit};
|
|
44
|
+
data: ${i}`)})}logIfDebugEnabled(e,n,r){(nl.isDebugEnabled||this.debug.enabled)&&this.debug.logger(e,this.debug.name,n,r)}on(e,n){let{signal:r}=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};for(let r of(nn(n),e=Array.isArray(e)?e:[e])){nt(r);let e=nr(this,r);e||(e=new Set,t2.get(this).set(r,e)),e.add(n),this.logIfDebugEnabled("subscribe",r,void 0),na(r)||nc(this,t4,{eventName:r,listener:n})}let i=()=>{this.off(e,n),null==r||r.removeEventListener("abort",i)};return null==r||r.addEventListener("abort",i,{once:!0}),(null==r?void 0:r.aborted)&&i(),i}off(e,n){for(let r of(nn(n),e=Array.isArray(e)?e:[e])){nt(r);let e=nr(this,r);e&&(e.delete(n),0===e.size&&t2.get(this).delete(r)),this.logIfDebugEnabled("unsubscribe",r,void 0),na(r)||nc(this,t8,{eventName:r,listener:n})}}once(e,n){let r;if(void 0!==n&&"function"!=typeof n)throw TypeError("predicate must be a function");let i=new Promise(i=>{r=this.on(e,e=>{(!n||n(e))&&(r(),i(e))})});return i.off=r,i}events(e){for(let n of e=Array.isArray(e)?e:[e])nt(n);return no(this,e)}async emit(e,n){var r;if(nt(e),na(e)&&!t9)throw TypeError("`eventName` cannot be meta event `listenerAdded` or `listenerRemoved`");this.logIfDebugEnabled("emit",e,n);let i=t3.get(this);if(i.has(e))for(let r of i.get(e))r.enqueue(n);if(i.has(t6)){let r=Promise.all([e,n]);for(let e of i.get(t6))e.enqueue(r)}let o=null!=(r=nr(this,e))?r:new Set,s=t1.get(this),a=[...o],c=na(e)?[]:[...s];await t5,await Promise.all([...a.map(async e=>{if(o.has(e))return e(n)}),...c.map(async r=>{if(s.has(r))return r(e,n)})])}async emitSerial(e,n){var r;if(nt(e),na(e)&&!t9)throw TypeError("`eventName` cannot be meta event `listenerAdded` or `listenerRemoved`");this.logIfDebugEnabled("emitSerial",e,n);let i=null!=(r=nr(this,e))?r:new Set,o=t1.get(this),s=[...i],a=[...o];for(let e of(await t5,s))i.has(e)&&await e(n);for(let r of a)o.has(r)&&await r(e,n)}onAny(e){let{signal:n}=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};nn(e),this.logIfDebugEnabled("subscribeAny",void 0,void 0),t1.get(this).add(e),nc(this,t4,{listener:e});let r=()=>{this.offAny(e),null==n||n.removeEventListener("abort",r)};return null==n||n.addEventListener("abort",r,{once:!0}),(null==n?void 0:n.aborted)&&r(),r}anyEvent(){return no(this)}offAny(e){nn(e),this.logIfDebugEnabled("unsubscribeAny",void 0,void 0),nc(this,t8,{listener:e}),t1.get(this).delete(e)}clearListeners(e){for(let n of e=Array.isArray(e)?e:[e])if(this.logIfDebugEnabled("clear",n,void 0),ne(n)){let e=nr(this,n);e&&e.clear();let r=ni(this,n);if(r){for(let e of r)e.finish();r.clear()}}else{for(let[e,n]of(t1.get(this).clear(),t2.get(this).entries()))n.clear(),t2.get(this).delete(e);for(let[e,n]of t3.get(this).entries()){for(let e of n)e.finish();n.clear(),t3.get(this).delete(e)}}}listenerCount(e){e=Array.isArray(e)?e:[e];let n=0;for(let l of e){if(ne(l)){var r,i,o,s,a,c;n+=t1.get(this).size+(null!=(s=null==(r=nr(this,l))?void 0:r.size)?s:0)+(null!=(a=null==(i=ni(this,l))?void 0:i.size)?a:0)+(null!=(c=null==(o=ni(this))?void 0:o.size)?c:0);continue}for(let e of(void 0!==l&&nt(l),n+=t1.get(this).size,t2.get(this).values()))n+=e.size;for(let e of t3.get(this).values())n+=e.size}return n}bindMethods(e,n){if("object"!=typeof e||null===e)throw TypeError("`target` must be an object");for(let r of n=ns(n)){if(void 0!==e[r])throw Error(`The property \`${r}\` already exists on \`target\``);Object.defineProperty(e,r,{enumerable:!1,value:this[r].bind(this)})}}}let nu=Object.getOwnPropertyNames(nl.prototype).filter(e=>"constructor"!==e);Object.defineProperty(nl,"listenerAdded",{value:t4,writable:!1,enumerable:!0,configurable:!1}),Object.defineProperty(nl,"listenerRemoved",{value:t8,writable:!1,enumerable:!0,configurable:!1});let nd={AaaSPilotKitController:Symbol.for("AaaSPilotKitController"),SignalingService:Symbol.for("SignalingService"),ASRService:Symbol.for("ASRService"),AgentService:Symbol.for("AgentService"),DigitalHumanService:Symbol.for("DigitalHumanService"),ConversationService:Symbol.for("ConversationService"),CommonRequest:Symbol.for("CommonRequest"),ErrorManager:Symbol.for("ErrorManager"),IOptions:Symbol.for("IOptions")};class np extends Error{constructor(e,n,r){let i=e.status||0===e.status?e.status:"",o=e.statusText||"",s=`${i} ${o}`.trim();super(`Request failed with ${s?`status code ${s}`:"an unknown error"}: ${n.method} ${n.url}`),this.name="HTTPError",this.response=e,this.request=n,this.options=r}}class nh extends Error{constructor(e){super(`Request timed out: ${e.method} ${e.url}`),this.name="TimeoutError",this.request=e}}et("../../node_modules/core-js/modules/es.typed-array.set.js");let nf=(()=>{let e=!1,n=!1,r="function"==typeof globalThis.Request;if("function"==typeof globalThis.ReadableStream&&r)try{n=new globalThis.Request("https://empty.invalid",{body:new globalThis.ReadableStream,method:"POST",get duplex(){return e=!0,"half"}}).headers.has("Content-Type")}catch(e){if(e instanceof Error&&"unsupported BodyInit type"===e.message)return!1;throw e}return e&&!n})(),nm="function"==typeof globalThis.AbortController,ng="function"==typeof globalThis.ReadableStream,nv="function"==typeof globalThis.FormData,ny=["get","post","put","patch","head","delete"],nb={json:"application/json",text:"text/*",formData:"multipart/form-data",arrayBuffer:"*/*",blob:"*/*"},nw=new TextEncoder().encode("------WebKitFormBoundaryaxpyiPgbbPti10Rw").length,nO=Symbol("stop"),n_={json:!0,parseJson:!0,stringifyJson:!0,searchParams:!0,prefixUrl:!0,retry:!0,timeout:!0,hooks:!0,throwHttpErrors:!0,onDownloadProgress:!0,onUploadProgress:!0,fetch:!0},nR={method:!0,headers:!0,body:!0,mode:!0,credentials:!0,cache:!0,redirect:!0,referrer:!0,referrerPolicy:!0,integrity:!0,keepalive:!0,signal:!0,window:!0,dispatcher:!0,duplex:!0,priority:!0},nS=e=>{if(!e)return 0;if(e instanceof FormData){let n=0;for(let[r,i]of e)n+=nw,n+=new TextEncoder().encode(`Content-Disposition: form-data; name="${r}"`).length,n+="string"==typeof i?new TextEncoder().encode(i).length:i.size;return n}if(e instanceof Blob)return e.size;if(e instanceof ArrayBuffer)return e.byteLength;if("string"==typeof e)return new TextEncoder().encode(e).length;if(e instanceof URLSearchParams)return new TextEncoder().encode(e.toString()).length;if("byteLength"in e)return e.byteLength;if("object"==typeof e&&null!==e)try{let n=JSON.stringify(e);return new TextEncoder().encode(n).length}catch{}return 0},nT=(e,n)=>{let r=Number(e.headers.get("content-length"))||0,i=0;return 204===e.status?(n&&n({percent:1,totalBytes:r,transferredBytes:i},new Uint8Array),new Response(null,{status:e.status,statusText:e.statusText,headers:e.headers})):new Response(new ReadableStream({async start(o){let s=e.body.getReader();async function a(){let{done:e,value:c}=await s.read();if(e)return void o.close();n&&(i+=c.byteLength,n({percent:0===r?0:i/r,transferredBytes:i,totalBytes:r},c)),o.enqueue(c),await a()}n&&n({percent:0,transferredBytes:0,totalBytes:r},new Uint8Array),await a()}}),{status:e.status,statusText:e.statusText,headers:e.headers})},nE=(e,n)=>{let r=nS(e.body),i=0;return new Request(e,{duplex:"half",body:new ReadableStream({async start(o){let s=e.body instanceof ReadableStream?e.body.getReader():new Response("").body.getReader();async function a(){let{done:e,value:c}=await s.read();if(e){n&&n({percent:1,transferredBytes:i,totalBytes:Math.max(r,i)},new Uint8Array),o.close();return}i+=c.byteLength;let l=0===r?0:i/r;(r<i||1===l)&&(l=.99),n&&n({percent:Number(l.toFixed(2)),transferredBytes:i,totalBytes:r},c),o.enqueue(c),await a()}await a()}})})},nM=e=>null!==e&&"object"==typeof e,nx=function(){for(var e=arguments.length,n=Array(e),r=0;r<e;r++)n[r]=arguments[r];for(let e of n)if((!nM(e)||Array.isArray(e))&&void 0!==e)throw TypeError("The `options` argument must be an object");return nB({},...n)},nC=function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=new globalThis.Headers(e),i=n instanceof globalThis.Headers;for(let[e,o]of new globalThis.Headers(n).entries())i&&"undefined"===o||void 0===o?r.delete(e):r.set(e,o);return r};function nj(e,n,r){var i,o;return Object.hasOwn(n,r)&&void 0===n[r]?[]:nB(null!=(i=e[r])?i:[],null!=(o=n[r])?o:[])}let nI=function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return{beforeRequest:nj(e,n,"beforeRequest"),beforeRetry:nj(e,n,"beforeRetry"),afterResponse:nj(e,n,"afterResponse"),beforeError:nj(e,n,"beforeError")}},nB=function(){for(var e=arguments.length,n=Array(e),r=0;r<e;r++)n[r]=arguments[r];let i={},o={},s={};for(let e of n)if(Array.isArray(e))Array.isArray(i)||(i=[]),i=[...i,...e];else if(nM(e)){for(let[n,r]of Object.entries(e))nM(r)&&n in i&&(r=nB(i[n],r)),i={...i,[n]:r};nM(e.hooks)&&(s=nI(s,e.hooks),i.hooks=s),nM(e.headers)&&(o=nC(o,e.headers),i.headers=o)}return i},nk=e=>ny.includes(e)?e.toUpperCase():e,nA={limit:2,methods:["get","put","head","delete","options","trace"],statusCodes:[408,413,429,500,502,503,504],afterStatusCodes:[413,429,503],maxRetryAfter:Number.POSITIVE_INFINITY,backoffLimit:Number.POSITIVE_INFINITY,delay:e=>.3*2**(e-1)*1e3},nP=function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};if("number"==typeof e)return{...nA,limit:e};if(e.methods&&!Array.isArray(e.methods))throw Error("retry.methods must be an array");if(e.statusCodes&&!Array.isArray(e.statusCodes))throw Error("retry.statusCodes must be an array");return{...nA,...e}};async function nN(e,n,r,i){return new Promise((o,s)=>{let a=setTimeout(()=>{r&&r.abort(),s(new nh(e))},i.timeout);i.fetch(e,n).then(o).catch(s).then(()=>{clearTimeout(a)})})}async function nL(e,n){let{signal:r}=n;return new Promise((n,i)=>{function o(){clearTimeout(s),i(r.reason)}r&&(r.throwIfAborted(),r.addEventListener("abort",o,{once:!0}));let s=setTimeout(()=>{null==r||r.removeEventListener("abort",o),n()},e)})}let nD=(e,n)=>{let r={};for(let i in n)i in nR||i in n_||i in e||(r[i]=n[i]);return r};class nF{static create(e,n){let r=new nF(e,n),i=async()=>{if("number"==typeof r._options.timeout&&r._options.timeout>0x7fffffff)throw RangeError("The `timeout` option cannot be greater than 2147483647");await Promise.resolve();let e=await r._fetch();for(let n of r._options.hooks.afterResponse){let i=await n(r.request,r._options,r._decorateResponse(e.clone()));i instanceof globalThis.Response&&(e=i)}if(r._decorateResponse(e),!e.ok&&r._options.throwHttpErrors){let n=new np(e,r.request,r._options);for(let e of r._options.hooks.beforeError)n=await e(n);throw n}if(r._options.onDownloadProgress){if("function"!=typeof r._options.onDownloadProgress)throw TypeError("The `onDownloadProgress` option must be a function");if(!ng)throw Error("Streams are not supported in your environment. `ReadableStream` is missing.");return nT(e.clone(),r._options.onDownloadProgress)}return e},o=(r._options.retry.methods.includes(r.request.method.toLowerCase())?r._retry(i):i()).finally(async()=>{if(!r.request.bodyUsed){var e;await (null==(e=r.request.body)?void 0:e.cancel())}});for(let[e,i]of Object.entries(nb))o[e]=async()=>{r.request.headers.set("accept",r.request.headers.get("accept")||i);let s=await o;if("json"===e){if(204===s.status||0===(await s.clone().arrayBuffer()).byteLength)return"";if(n.parseJson)return n.parseJson(await s.text())}return s[e]()};return o}constructor(e,n={}){var r,i,o,s,a,c,l,u,d;if(this._retryCount=0,this._input=e,this._options={...n,headers:nC(this._input.headers,n.headers),hooks:nI({beforeRequest:[],beforeRetry:[],beforeError:[],afterResponse:[]},n.hooks),method:nk(null!=(i=null!=(r=n.method)?r:this._input.method)?i:"GET"),prefixUrl:String(n.prefixUrl||""),retry:nP(n.retry),throwHttpErrors:!1!==n.throwHttpErrors,timeout:null!=(o=n.timeout)?o:1e4,fetch:null!=(s=n.fetch)?s:globalThis.fetch.bind(globalThis)},"string"!=typeof this._input&&!(this._input instanceof URL||this._input instanceof globalThis.Request))throw TypeError("`input` must be a string, URL, or Request");if(this._options.prefixUrl&&"string"==typeof this._input){if(this._input.startsWith("/"))throw Error("`input` must not begin with a slash when using `prefixUrl`");this._options.prefixUrl.endsWith("/")||(this._options.prefixUrl+="/"),this._input=this._options.prefixUrl+this._input}if(nm){let e=null!=(a=this._options.signal)?a:this._input.signal;this.abortController=new globalThis.AbortController,this._options.signal=e?AbortSignal.any([e,this.abortController.signal]):this.abortController.signal}if(nf&&(this._options.duplex="half"),void 0!==this._options.json&&(this._options.body=null!=(u=null==(c=(l=this._options).stringifyJson)?void 0:c.call(l,this._options.json))?u:JSON.stringify(this._options.json),this._options.headers.set("content-type",null!=(d=this._options.headers.get("content-type"))?d:"application/json")),this.request=new globalThis.Request(this._input,this._options),this._options.searchParams){let e="string"==typeof this._options.searchParams?this._options.searchParams.replace(/^\?/,""):new URLSearchParams(this._options.searchParams).toString(),n=this.request.url.replace(/(?:\?.*?)?(?=#|$)/,"?"+e);(nv&&this._options.body instanceof globalThis.FormData||this._options.body instanceof URLSearchParams)&&!(this._options.headers&&this._options.headers["content-type"])&&this.request.headers.delete("content-type"),this.request=new globalThis.Request(new globalThis.Request(n,{...this.request}),this._options)}if(this._options.onUploadProgress){if("function"!=typeof this._options.onUploadProgress)throw TypeError("The `onUploadProgress` option must be a function");if(!nf)throw Error("Request streams are not supported in your environment. The `duplex` option for `Request` is not available.");this.request.body&&(this.request=nE(this.request,this._options.onUploadProgress))}}_calculateRetryDelay(e){if(this._retryCount++,this._retryCount>this._options.retry.limit||e instanceof nh)throw e;if(e instanceof np){var n,r,i,o;if(!this._options.retry.statusCodes.includes(e.response.status))throw e;let s=null!=(i=null!=(r=null!=(n=e.response.headers.get("Retry-After"))?n:e.response.headers.get("RateLimit-Reset"))?r:e.response.headers.get("X-RateLimit-Reset"))?i:e.response.headers.get("X-Rate-Limit-Reset");if(s&&this._options.retry.afterStatusCodes.includes(e.response.status)){let e=1e3*Number(s);Number.isNaN(e)?e=Date.parse(s)-Date.now():e>=Date.parse("2024-01-01")&&(e-=Date.now());let n=null!=(o=this._options.retry.maxRetryAfter)?o:e;return e<n?e:n}if(413===e.response.status)throw e}let s=this._options.retry.delay(this._retryCount);return Math.min(this._options.retry.backoffLimit,s)}_decorateResponse(e){return this._options.parseJson&&(e.json=async()=>this._options.parseJson(await e.text())),e}async _retry(e){try{return await e()}catch(r){let n=Math.min(this._calculateRetryDelay(r),0x7fffffff);if(this._retryCount<1)throw r;for(let e of(await nL(n,{signal:this._options.signal}),this._options.hooks.beforeRetry))if(await e({request:this.request,options:this._options,error:r,retryCount:this._retryCount})===nO)return;return this._retry(e)}}async _fetch(){for(let e of this._options.hooks.beforeRequest){let n=await e(this.request,this._options);if(n instanceof Request){this.request=n;break}if(n instanceof Response)return n}let e=nD(this.request,this._options),n=this.request;return(this.request=n.clone(),!1===this._options.timeout)?this._options.fetch(n,e):nN(n,e,this.abortController,this._options)}}let nU=e=>{let n=(n,r)=>nF.create(n,nx(e,r));for(let r of ny)n[r]=(n,i)=>nF.create(n,nx(e,i,{method:r}));return n.create=e=>nU(nx(e)),n.extend=n=>("function"==typeof n&&(n=n(null!=e?e:{})),nU(nx(e,n))),n.stop=nO,n},nH=nU();function nq(e,n){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,n)}function nV(e,n){return function(r,i){n(r,i,e)}}class nX{static #k=this.ONLINE_HOST="https://ky.cloud.baidu.com";static #G=this.SANDBOX_HOST="https://ky-test.cloud.baidu.com";constructor(e){this.opts=e,"production"===this.opts.env?this.client=nH.create({prefixUrl:nX.ONLINE_HOST}):this.client=nH.create({prefixUrl:nX.SANDBOX_HOST})}}nX=function(e,n,r,i){var o,s=arguments.length,a=s<3?n:null===i?i=Object.getOwnPropertyDescriptor(n,r):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)a=Reflect.decorate(e,n,r,i);else for(var c=e.length-1;c>=0;c--)(o=e[c])&&(a=(s<3?o(a):s>3?o(n,r,a):o(n,r))||a);return s>3&&a&&Object.defineProperty(n,r,a),a}([eV(),nV(0,eU(nd.IOptions)),nV(0,ez()),nq("design:type",Function),nq("design:paramtypes",["undefined"==typeof IResolvedOptions?Object:IResolvedOptions])],nX);var nW=((_={}).NETWORK="NETWORK",_.TIMEOUT="TIMEOUT",_.AUTHENTICATION="AUTHENTICATION",_.AUTHORIZATION="AUTHORIZATION",_.RESOURCE="RESOURCE",_.CONFIGURATION="CONFIGURATION",_.PARSING="PARSING",_.SERVICE="SERVICE",_.VALIDATION="VALIDATION",_.INTERNAL="INTERNAL",_),n$=((R={}).LOW="LOW",R.MEDIUM="MEDIUM",R.HIGH="HIGH",R.CRITICAL="CRITICAL",R);class nz extends Error{constructor(e,n,r,i=n$.MEDIUM,o={},s){super(n),this.name=this.constructor.name,this.code=e,this.category=r,this.severity=i,this.actionRequired=s,this.metadata={timestamp:Date.now(),stack:this.stack,...o},Object.setPrototypeOf(this,new.target.prototype),Error.captureStackTrace?Error.captureStackTrace(this,this.constructor):this.stack=Error(n).stack}static fromError(e,n,r){let i=arguments.length>3&&void 0!==arguments[3]?arguments[3]:n$.MEDIUM;return new nz(n,e.message,r,i,{originalError:e,stack:e.stack})}toJSON(){return{code:this.code,message:this.message,category:this.category,severity:this.severity,metadata:this.metadata,actionRequired:this.actionRequired}}toString(){return`${this.name} [${this.code}]: ${this.message}`}}let nG={1e3:"发生未知错误",1001:"网络连接错误",1002:"请求超时",1003:"配置无效",1004:"身份验证失败",1005:"权限验证失败",1006:"数据验证失败",1007:"资源未找到",1008:"资源不可用",1009:"内部错误",2001:"Agent查询失败",2002:"Agent响应解析错误",2003:"Agent请求超时",2004:"Agent响应无效",2005:"Agent连接失败",2006:"Agent指令无效",3001:"ASR初始化失败",3002:"ASR启动失败",3003:"ASR停止失败",3004:"ASR信令错误",3005:"ASR音频捕获错误",3006:"ASR识别错误",3007:"ASR网络错误",3008:"ASR权限被拒绝",3009:"ASR设备未找到",3010:"ASR消息解析错误",3011:"ASR会话无效",3012:"ASR静音失败",3013:"ASR消息间隔超时",3014:"ASR运行时错误",4001:"数字人挂载失败",4002:"数字人iframe加载错误",4003:"数字人渲染错误",4004:"数字人WebSocket错误",4005:"数字人RTC错误",4006:"数字人认证错误",4007:"数字人会话数量达到上限",4008:"数字人资源不足",4009:"数字人超时",4010:"数字人中断失败",4011:"数字人SSML解析错误",4012:"数字人形象ID无效",4013:"数字人token无效",4014:"数字人流式渲染错误",4015:"数字人控制器未就绪",4016:"数字人播报文本长度不匹配",5001:"会话创建失败",5002:"会话类型无效",5003:"会话快照无效",5004:"会话Bean未找到",5005:"会话序列化错误",5006:"会话反序列化错误",5007:"会话状态无效",5008:"会话清除失败"};class nJ extends nz{constructor(e,n,r=n$.MEDIUM,i={},o){super(e,n||nG[e]||"Agent服务错误",nW.SERVICE,r,i,o)}}class nK extends nJ{constructor(e,n={}){super("2001",e,n$.HIGH,n)}}class nQ extends nJ{constructor(e,n={}){super("2002",e,n$.HIGH,n)}}class nY extends nJ{constructor(e,n={}){super("2005",e,n$.HIGH,n)}}class nZ extends nJ{constructor(e,n={}){super("2006",e,n$.MEDIUM,n)}}var n0=et("../../node_modules/ua-parser-js/src/ua-parser.js"),n1=et.n(n0);let n2=()=>{let e=new(n1()),n=e.getBrowser(),r=e.getOS(),i=e.getDevice();return{userAgent:e.getUA(),browser:{name:n.name,version:n.version},os:{name:r.name,version:r.version},device:{type:i.type,vendor:i.vendor,model:i.model}}},n3=()=>{let e=new(n1()),n=e.getUA();return"WeChat"===e.getBrowser().name||/MicroMessenger/i.test(n)},n6=()=>"iOS"===new(n1())().getOS().name,n5=()=>{let e=new(n1()),n=e.getOS(),r=e.getDevice();return"Mac OS"===n.name&&"tablet"===r.type};class n4 extends nz{constructor(e,n,r=n$.MEDIUM,i={}){super(e,n||nG[e]||"ASR服务错误",nW.SERVICE,r,i)}}class n8 extends n4{constructor(e,n={}){super("3001",e,n$.HIGH,n)}}class n9 extends n4{constructor(e,n={}){super("3003",e,n$.MEDIUM,n)}}class n7 extends n4{constructor(e,n={}){super("3008",e,n$.MEDIUM,{...n,context:{...n.context,browserInfo:n2()}})}}class re extends n4{constructor(e,n={}){super("3010",e,n$.MEDIUM,n)}}class rt extends n4{constructor(e,n={}){super("3013",e,n$.MEDIUM,n)}}class rn extends n4{constructor(e,n={}){super("3014",e,n$.HIGH,n)}}class rr extends nz{constructor(e,n,r=n$.MEDIUM,i={}){super(e,n||nG[e]||"数字人服务错误",nW.SERVICE,r,i)}}class ri extends rr{constructor(e,n={}){super("4001",e,n$.HIGH,n)}}class ro extends rr{constructor(e,n={}){super("4002",e,n$.HIGH,n)}}class rs extends rr{constructor(e,n={}){super("4003",e,n$.MEDIUM,n)}}class ra extends rr{constructor(e,n={}){super("4004",e,n$.HIGH,n)}}class rc extends rr{constructor(e,n={}){super("4005",e,n$.HIGH,n)}}class rl extends rr{constructor(e,n={}){super("4006",e,n$.CRITICAL,n)}}class ru extends rr{constructor(e,n={}){super("4008",e,n$.CRITICAL,n)}}class rd{constructor(e){this.opts=e,this.reporters=[]}addReporter(e){this.reporters.push(e)}removeReporter(e){let n=this.reporters.indexOf(e);n>-1&&this.reporters.splice(n,1)}async handle(e){let n;n=e instanceof nz?e.toJSON():this.isErrorDetails(e)?e:nz.fromError(e,"UNKNOWN_ERROR","INTERNAL").toJSON(),await this.processError(n)}async processError(e){try{this.shouldLogError()&&this.logError(e),this.shouldReportError(e)&&await this.reportError(e)}catch(e){console.error("Error in error handler:",e)}}shouldLogError(){var e;return(null==(e=this.opts)?void 0:e.enableErrorLogging)!==!1}shouldReportError(e){var n;return(null==(n=this.opts)?void 0:n.enableErrorReporting)!==!1&&e.severity!==n$.LOW&&this.reporters.length>0}logError(e){let n=this.getLogLevel(e.severity),r=`[${e.code}] ${e.message}`;"error"===n?console.error(r,e):"warn"===n?console.warn(r,e):console.log(r,e)}getLogLevel(e){switch(e){case n$.CRITICAL:case n$.HIGH:return"error";case n$.MEDIUM:return"warn";case n$.LOW:default:return"log"}}async reportError(e){let n=this.reporters.map(n=>n.report(e).catch(e=>{console.error("Error reporter failed:",e)}));await Promise.allSettled(n)}isErrorDetails(e){return e&&"object"==typeof e&&"code"in e&&"message"in e&&"category"in e&&"severity"in e}}class rp{async report(e){console.error("Error Report:",{code:e.code,message:e.message,category:e.category,severity:e.severity,timestamp:new Date(e.metadata.timestamp).toISOString(),sessionId:e.metadata.sessionId,requestId:e.metadata.requestId,context:e.metadata.context})}}class rh{constructor(e){this.options={timeout:5e3,headers:{"Content-Type":"application/json"},retryCount:3,retryDelay:1e3,...e}}async report(e){let n=this.buildPayload(e);for(let e=0;e<=this.options.retryCount;e++)try{await this.sendRequest(n);return}catch(n){if(e===this.options.retryCount)throw n;await this.delay(this.options.retryDelay*(e+1))}}buildPayload(e){return{error:{code:e.code,message:e.message,category:e.category,severity:e.severity,actionRequired:e.actionRequired},metadata:{timestamp:e.metadata.timestamp,sessionId:e.metadata.sessionId,requestId:e.metadata.requestId,userId:e.metadata.userId,context:e.metadata.context,userAgent:navigator.userAgent,url:window.location.href}}}async sendRequest(e){let n=new AbortController,r=setTimeout(()=>n.abort(),this.options.timeout);try{let r=await fetch(this.options.endpoint,{method:"POST",headers:this.options.headers,body:JSON.stringify(e),signal:n.signal});if(!r.ok)throw Error(`HTTP ${r.status}: ${r.statusText}`)}finally{clearTimeout(r)}}delay(e){return new Promise(n=>setTimeout(n,e))}}class rf{static getErrorSeverity(e){if(e instanceof nz)return e.severity;let n=e.message.toLowerCase();return n.includes("permission")||n.includes("unauthorized")||n.includes("forbidden")?n$.CRITICAL:n.includes("network")||n.includes("timeout")||n.includes("connection")?n$.HIGH:n$.MEDIUM}static shouldReport(e){return!(e instanceof nz)||e.severity!==n$.LOW}static extractMetadata(e){let n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r={timestamp:Date.now(),context:n,stack:e.stack};return e instanceof nz?{...r,...e.metadata}:r}static getActionRequired(e){if(e instanceof nz){var n;return null!=(n=e.actionRequired)?n:null}let r=e.message.toLowerCase();return r.includes("permission")||r.includes("unauthorized")?"请检查用户权限":r.includes("network")||r.includes("timeout")?"请检查网络连接后重试":r.includes("validation")||r.includes("invalid")?"请检查输入数据的格式和有效性":null}}class rm{constructor(){this.emitter=new nl,this.emit=e=>{let n=this.transformErrorToPayload(e);this.emitter.emit("error",n)},this.on=e=>{this.emitter.on("error",e)},this.off=e=>{this.emitter.off("error",e)},this.clearListeners=()=>{this.emitter.clearListeners()},this.transformErrorToPayload=e=>{if(e instanceof nz){var n;return{code:e.code,message:e.toString(),stack:e.stack,actionRequired:null!=(n=e.actionRequired)?n:null,severity:e.severity,metadata:{timestamp:e.metadata.timestamp,sessionId:e.metadata.sessionId,requestId:e.metadata.requestId,userId:e.metadata.userId,context:e.metadata.context,service:this.extractServiceFromError(e)},originalError:e}}return{code:"UNKNOWN_ERROR",message:e.toString(),stack:e.stack,actionRequired:rf.getActionRequired(e),severity:rf.getErrorSeverity(e),metadata:{timestamp:Date.now(),context:{errorName:e.name}},originalError:e}},this.extractServiceFromError=e=>{let n=e.constructor.name.toLowerCase();return n.includes("agent")?"agent":n.includes("asr")?"asr":n.includes("digitalHuman")||n.includes("dh")?"digital-human":n.includes("conversation")?"conversation":"unknown"}}}class rg extends Error{constructor(e,n,r={}){super(n),this.name=e||"AaaSPilotKitError",this.message=n,this.data=r,Error.captureStackTrace?Error.captureStackTrace(this,rg):this.stack=Error().stack||"",Object.setPrototypeOf(this,rg.prototype)}static createForMonitoring(e,n,r){return new rg(e,n,r)}getMonitoringData(){return{type:this.name,message:this.message,stack:this.stack,timestamp:Date.now(),...this.data}}getSimplifiedData(){return{type:this.name,message:this.message,userId:this.data.userId,sessionId:this.data.sessionId,page:this.data.page}}toString(){return this.message}toJSON(){return this.getMonitoringData()}}function rv(e,n){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,n)}function ry(e,n){return function(r,i){n(r,i,e)}}class rb extends rm{constructor(e){super(),this.opts=e,this.handleError=async e=>{await this.errorHandler.handle(e),this.emit(e)},this.getErrorHandler=()=>this.errorHandler,this.getActionRequired=e=>rf.getActionRequired(e),this.createMonitoringError=e=>{var n,r;let i=this.buildEnhancedMessage(e),o={page:null==(n=e.metadata.context)?void 0:n.page,userId:e.metadata.userId,sessionId:e.metadata.sessionId,requestId:e.metadata.requestId,context:e.metadata.context,severity:e.severity,category:e.metadata.service||"unknown",code:e.code,originalMessage:null==(r=e.originalError)?void 0:r.message};return rg.createForMonitoring(e.code,i,o)},this.buildEnhancedMessage=e=>{let n=[],r=e.severity.toUpperCase();n.push(`[${r}]: ${e.message}`),e.metadata.service&&n.push(`category=${e.metadata.service}`);let i=new Date(e.metadata.timestamp||Date.now()),o=i.getFullYear()+"-"+String(i.getMonth()+1).padStart(2,"0")+"-"+String(i.getDate()).padStart(2,"0")+" "+String(i.getHours()).padStart(2,"0")+":"+String(i.getMinutes()).padStart(2,"0")+":"+String(i.getSeconds()).padStart(2,"0");if(n.push(`time=${o}`),e.metadata&&Object.keys(e.metadata).length>0){let r=this.stringifyMetadata(e.metadata);r&&"{}"!==r&&n.push(`metadata=${r}`)}return n.join(" | ")},this.stringifyMetadata=e=>{if(!e||"object"!=typeof e)return"{}";let n=new Set(["timestamp","stack"]),r={};for(let[i,o]of Object.entries(e))n.has(i)||null==o||(r[i]=o);try{return JSON.stringify(r)}catch{return"{}"}},this.initializeReporters=()=>{this.options.enableConsoleReporter&&this.errorHandler.addReporter(new rp),this.options.enableHttpReporter&&this.options.httpReporterEndpoint&&this.errorHandler.addReporter(new rh({endpoint:this.options.httpReporterEndpoint}))},this.options={enableConsoleReporter:this.opts.enableDebugMode,enableHttpReporter:!1,enableErrorLogging:this.opts.enableDebugMode,enableErrorReporting:!0},this.errorHandler=new rd(this.options),this.initializeReporters()}}function rw(e,n){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,n)}function rO(e,n){return function(r,i){n(r,i,e)}}rb=function(e,n,r,i){var o,s=arguments.length,a=s<3?n:null===i?i=Object.getOwnPropertyDescriptor(n,r):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)a=Reflect.decorate(e,n,r,i);else for(var c=e.length-1;c>=0;c--)(o=e[c])&&(a=(s<3?o(a):s>3?o(n,r,a):o(n,r))||a);return s>3&&a&&Object.defineProperty(n,r,a),a}([eV(),ry(0,eU(nd.IOptions)),ry(0,ez()),rv("design:type",Function),rv("design:paramtypes",["undefined"==typeof IOptions?Object:IOptions])],rb);class r_{constructor(e,n,r){this.request=e,this.errorManager=n,this.opts=r,this.emitter=new nl,this.conversationSessionId="",this.abortController=null,this._queryId="",this._lastQueryId="",this.setSessionId=e=>{this.conversationSessionId=e},this.setQueryId=e=>{this._queryId=e},this.setLastQueryId=e=>{this._lastQueryId=e},this.abort=e=>{var n;null==(n=this.abortController)||n.abort(e),this.abortController&&(this.abortController=null)},this.checkIsRepeat=()=>{let e=!!this.lastQueryId&&this.lastQueryId===this.queryId;return e&&this.opts.enableDebugMode&&console.warn("重复的completed查询被忽略:",this.queryId),e},this.onData=e=>{this.emitter.emit("data",e)},this.onCompleted=e=>{this.emitter.emit("completed",e)},this.onHangup=e=>{this.emitter.emit("hangup",e)},this.onTimeout=e=>{this.emitter.emit("timeout",e)},this.onInstructionReceived=e=>{this.emitter.emit("instruction_received",e)},this.onUsageQuotaReached=e=>{this.emitter.emit("usage_quota_reached",e)},this.onQuotaExpired=e=>{this.emitter.emit("quota_expired",e)},this._dispose=()=>{this.abort(),this.conversationSessionId="",this._queryId="",this._lastQueryId=""}}get sessionId(){return this.conversationSessionId}get queryId(){return this._queryId}get lastQueryId(){return this._lastQueryId}}r_=function(e,n,r,i){var o,s=arguments.length,a=s<3?n:null===i?i=Object.getOwnPropertyDescriptor(n,r):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)a=Reflect.decorate(e,n,r,i);else for(var c=e.length-1;c>=0;c--)(o=e[c])&&(a=(s<3?o(a):s>3?o(n,r,a):o(n,r))||a);return s>3&&a&&Object.defineProperty(n,r,a),a}([eV(),rO(0,eU(nd.CommonRequest)),rO(1,eU(nd.ErrorManager)),rO(2,eU(nd.IOptions)),rO(2,ez()),rw("design:type",Function),rw("design:paramtypes",[void 0===nX?Object:nX,void 0===rb?Object:rb,"undefined"==typeof IResolvedOptions?Object:IResolvedOptions])],r_),et("../../node_modules/core-js/modules/es.array.reduce.js");let rR=[{pattern:/客悦\s*one/gi,replacement:"客悦\xb7ONE"},{pattern:/\bSARS\b/gi,replacement:"SaaS"},{pattern:/\bSAS\b/gi,replacement:"SaaS"}],rS=function(e){let n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:rR;return n.reduce((e,n)=>{let{pattern:r,replacement:i}=n;return e.replace(r,i)},e)},rT={enableDebugMode:!1,minSplitLen:5,ttsModel:"02-turbo",env:"production",asrVad:600,interruptible:!0,rendererMode:"cloud",autoChromaKey:!0,typeDelay:163,enTypeDelay:45,inactivityPrompt:"您这么久没讲话,是不是有其它事情要忙,那我先挂断了",getMountContainer:()=>document.body,hotWordReplacementRules:rR,rtcID:"appreimunmd7utp"},rE={randomUUID:"undefined"!=typeof crypto&&crypto.randomUUID&&crypto.randomUUID.bind(crypto)},rM=new Uint8Array(16),rx=[];for(let e=0;e<256;++e)rx.push((e+256).toString(16).slice(1));let rC=function(n,r,i){if(rE.randomUUID&&!r&&!n)return rE.randomUUID();var o=n,s=i;let a=(o=o||{}).random??o.rng?.()??function(){if(!e){if("undefined"==typeof crypto||!crypto.getRandomValues)throw Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");e=crypto.getRandomValues.bind(crypto)}return e(rM)}();if(a.length<16)throw Error("Random bytes length must be >= 16");if(a[6]=15&a[6]|64,a[8]=63&a[8]|128,r){if((s=s||0)<0||s+16>r.length)throw RangeError(`UUID byte range ${s}:${s+15} is out of buffer bounds`);for(let e=0;e<16;++e)r[s+e]=a[e];return r}return function(e,n=0){return(rx[e[n+0]]+rx[e[n+1]]+rx[e[n+2]]+rx[e[n+3]]+"-"+rx[e[n+4]]+rx[e[n+5]]+"-"+rx[e[n+6]]+rx[e[n+7]]+"-"+rx[e[n+8]]+rx[e[n+9]]+"-"+rx[e[n+10]]+rx[e[n+11]]+rx[e[n+12]]+rx[e[n+13]]+rx[e[n+14]]+rx[e[n+15]]).toLowerCase()}(a)};class rj{constructor(e,n){this.opts=n,this.emitter=new nl,this.id="",this.text="",this.update=e=>{let{id:n,...r}=e;n?this.id=n:this.id||(this.id=rC()),Object.assign(this,r)},this.toJSON=()=>({id:this.id,type:this.type,text:this.text}),this.type=e.type,this.update(e)}}let rI=()=>{};class rB extends rj{constructor(e,n){super({...e,type:"client"},n),this.opts=n,this.appendText=e=>{this.text=e,this.emitter.emit("content_change",{mod:"text",content:e,completed:!0}).catch(rI)},this.dispose=()=>{},this.interrupt=()=>{}}static create(e){return new rB({},e)}}var rk=et("../../node_modules/p-queue/node_modules/eventemitter3/index.js"),rA=et.n(rk);class rP extends Error{constructor(e){super(e),this.name="TimeoutError"}}class rN extends Error{constructor(e){super(),this.name="AbortError",this.message=e}}let rL=e=>void 0===globalThis.DOMException?new rN(e):new DOMException(e),rD=e=>{let n=void 0===e.reason?rL("This operation was aborted."):e.reason;return n instanceof Error?n:rL(n)};class rF{#J=[];enqueue(e,n){let r={priority:(n={priority:0,...n}).priority,id:n.id,run:e};if(0===this.size||this.#J[this.size-1].priority>=n.priority)return void this.#J.push(r);let i=function(e,n,r){let i=0,o=e.length;for(;o>0;){let s=Math.trunc(o/2),a=i+s;0>=r(e[a],n)?(i=++a,o-=s+1):o=s}return i}(this.#J,r,(e,n)=>n.priority-e.priority);this.#J.splice(i,0,r)}setPriority(e,n){let r=this.#J.findIndex(n=>n.id===e);if(-1===r)throw ReferenceError(`No promise function with the id "${e}" exists in the queue.`);let[i]=this.#J.splice(r,1);this.enqueue(i.run,{priority:n,id:e})}dequeue(){let e=this.#J.shift();return e?.run}filter(e){return this.#J.filter(n=>n.priority===e.priority).map(e=>e.run)}get size(){return this.#J.length}}class rU extends rA(){#K;#Q;#Y=0;#Z;#ee;#et=0;#en;#er;#J;#ei;#eo=0;#es;#ea;#ec;#el=1n;timeout;constructor(e){if(super(),!("number"==typeof(e={carryoverConcurrencyCount:!1,intervalCap:Number.POSITIVE_INFINITY,interval:0,concurrency:Number.POSITIVE_INFINITY,autoStart:!0,queueClass:rF,...e}).intervalCap&&e.intervalCap>=1))throw TypeError(`Expected \`intervalCap\` to be a number from 1 and up, got \`${e.intervalCap?.toString()??""}\` (${typeof e.intervalCap})`);if(void 0===e.interval||!(Number.isFinite(e.interval)&&e.interval>=0))throw TypeError(`Expected \`interval\` to be a finite number >= 0, got \`${e.interval?.toString()??""}\` (${typeof e.interval})`);this.#K=e.carryoverConcurrencyCount,this.#Q=e.intervalCap===Number.POSITIVE_INFINITY||0===e.interval,this.#Z=e.intervalCap,this.#ee=e.interval,this.#J=new e.queueClass,this.#ei=e.queueClass,this.concurrency=e.concurrency,this.timeout=e.timeout,this.#ec=!0===e.throwOnTimeout,this.#ea=!1===e.autoStart}get #eu(){return this.#Q||this.#Y<this.#Z}get #ed(){return this.#eo<this.#es}#ep(){this.#eo--,this.#eh(),this.emit("next")}#ef(){this.#em(),this.#eg(),this.#er=void 0}get #ev(){let e=Date.now();if(void 0===this.#en){let n=this.#et-e;if(!(n<0))return void 0===this.#er&&(this.#er=setTimeout(()=>{this.#ef()},n)),!0;this.#Y=this.#K?this.#eo:0}return!1}#eh(){if(0===this.#J.size)return this.#en&&clearInterval(this.#en),this.#en=void 0,this.emit("empty"),0===this.#eo&&this.emit("idle"),!1;if(!this.#ea){let e=!this.#ev;if(this.#eu&&this.#ed){let n=this.#J.dequeue();return!!n&&(this.emit("active"),n(),e&&this.#eg(),!0)}}return!1}#eg(){this.#Q||void 0!==this.#en||(this.#en=setInterval(()=>{this.#em()},this.#ee),this.#et=Date.now()+this.#ee)}#em(){0===this.#Y&&0===this.#eo&&this.#en&&(clearInterval(this.#en),this.#en=void 0),this.#Y=this.#K?this.#eo:0,this.#ey()}#ey(){for(;this.#eh(););}get concurrency(){return this.#es}set concurrency(e){if(!("number"==typeof e&&e>=1))throw TypeError(`Expected \`concurrency\` to be a number from 1 and up, got \`${e}\` (${typeof e})`);this.#es=e,this.#ey()}async #eb(e){return new Promise((n,r)=>{e.addEventListener("abort",()=>{r(e.reason)},{once:!0})})}setPriority(e,n){this.#J.setPriority(e,n)}async add(e,n={}){return n.id??=(this.#el++).toString(),n={timeout:this.timeout,throwOnTimeout:this.#ec,...n},new Promise((r,i)=>{this.#J.enqueue(async()=>{this.#eo++,this.#Y++;try{n.signal?.throwIfAborted();let i=e({signal:n.signal});n.timeout&&(i=function(e,n){let r,i,{milliseconds:o,fallback:s,message:a,customTimers:c={setTimeout,clearTimeout}}=n,l=new Promise((l,u)=>{if("number"!=typeof o||1!==Math.sign(o))throw TypeError(`Expected \`milliseconds\` to be a positive number, got \`${o}\``);if(n.signal){let{signal:e}=n;e.aborted&&u(rD(e)),i=()=>{u(rD(e))},e.addEventListener("abort",i,{once:!0})}if(o===Number.POSITIVE_INFINITY)return void e.then(l,u);let d=new rP;r=c.setTimeout.call(void 0,()=>{if(s){try{l(s())}catch(e){u(e)}return}"function"==typeof e.cancel&&e.cancel(),!1===a?l():a instanceof Error?u(a):(d.message=a??`Promise timed out after ${o} milliseconds`,u(d))},o),(async()=>{try{l(await e)}catch(e){u(e)}})()}).finally(()=>{l.clear(),i&&n.signal&&n.signal.removeEventListener("abort",i)});return l.clear=()=>{c.clearTimeout.call(void 0,r),r=void 0},l}(Promise.resolve(i),{milliseconds:n.timeout})),n.signal&&(i=Promise.race([i,this.#eb(n.signal)]));let o=await i;r(o),this.emit("completed",o)}catch(e){if(e instanceof rP&&!n.throwOnTimeout)return void r();i(e),this.emit("error",e)}finally{this.#ep()}},n),this.emit("add"),this.#eh()})}async addAll(e,n){return Promise.all(e.map(async e=>this.add(e,n)))}start(){return this.#ea&&(this.#ea=!1,this.#ey()),this}pause(){this.#ea=!0}clear(){this.#J=new this.#ei}async onEmpty(){0!==this.#J.size&&await this.#ew("empty")}async onSizeLessThan(e){this.#J.size<e||await this.#ew("next",()=>this.#J.size<e)}async onIdle(){(0!==this.#eo||0!==this.#J.size)&&await this.#ew("idle")}async #ew(e,n){return new Promise(r=>{let i=()=>{(!n||n())&&(this.off(e,i),r())};this.on(e,i)})}get size(){return this.#J.size}sizeBy(e){return this.#J.filter(e).length}get pending(){return this.#eo}get isPaused(){return this.#ea}}class rH{constructor(e){this.id=rC(),this.createdAt=Date.now(),this.updatedAt=Date.now(),this.emitter=new nl,this.getConfig=()=>({...this.config}),this.updateConfig=e=>{this.config={...this.config,...e},this.updatedAt=Date.now()},this.toJSON=()=>({id:this.id,mod:this.mod,config:this.getConfig(),createdAt:this.createdAt,updatedAt:this.updatedAt}),this.updateTimestamp=()=>{this.updatedAt=Date.now()},this._dispose=()=>{this.emitter.clearListeners()},this.config={...e},this.config.timestamp||(this.config.timestamp=this.createdAt)}}var rq=et("../../node_modules/typewriter-effect/dist/core.js"),rV=et.n(rq);let rX=e=>/[\u3400-\u4DBF\u4E00-\u9FFF\uF900-\uFAFF\u3000-\u303F]/.test(e);class rW extends rH{get mod(){return"text"}static fromSnapshot(e){return new rW(e.config)}static fromString(e){let n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return new rW({content:e,...n})}setTargetElement(e){this.targetElement=e}isEmpty(){return!this.config.content}constructor(...e){super(...e),this.typewriter=null,this.targetElement=null,this.index=0,this.stopTypewriter=()=>{this.typewriter&&(this.typewriter.stop(),this.typewriter=null)},this.runTask=()=>new Promise((e,n)=>{if(this.ensureTarget(),this.isEmpty())return void e({mod:"text",content:""});try{var r,i,o,s,a;let n=null!=(o=null==(r=this.config.typewriterOptions)?void 0:r.delay)?o:163,c=null!=(s=null==(i=this.config.typewriterOptions)?void 0:i.enDelay)?s:n;this.typewriter=new(rV())(this.targetElement,{autoStart:!0,loop:!1,...this.config.typewriterOptions,delay:0,onCreateTextNode:e=>{let n=this.index===this.config.content.length-1;return this.emitter.emit("data",{char:e,index:this.index++,done:n}),document.createTextNode(e)}});let l=[],u="",d=null;for(let e of Array.from(this.config.content)){let n=rX(e);null===d||n===d?u+=e:(l.push({s:u,cn:d}),u=e),d=n}u&&l.push({s:u,cn:d});let p=this.typewriter;if(0===l.length)p=p.changeDelay(n).typeString(this.config.content);else for(let e=0;e<l.length;e++){let{s:r,cn:i}=l[e];if(0===e){let e=null!=(a=r[0])?a:"",o=r.slice(1);p=p.typeString(e),o&&(p=p.changeDelay(i?n:c).typeString(o));continue}p=p.changeDelay(i?n:c).typeString(r)}p.callFunction(()=>{e({mod:"text",content:this.config.content})}).start()}catch(e){n(e)}}),this.dispose=()=>{this._dispose(),this.stopTypewriter(),this.targetElement=null,this.index=0},this.interrupt=()=>{this.stopTypewriter()},this.ensureTarget=()=>{if(this.targetElement)return;let e=document.createElement("span");e.className="text-content-typewriter",this.targetElement=e}}}class r$ extends rH{get mod(){return"image"}static fromSnapshot(e){return new r$(e.config)}static fromSrc(e){let n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return new r$({src:e,...n})}isEmpty(){return!this.config.src}ensureImageElement(){if(this.imgElement)return this.imgElement;let e=document.createElement("img");return this.imgElement=e,e}constructor(...e){super(...e),this.imgElement=null,this.setTargetElement=e=>{this.imgElement=e},this.runTask=()=>new Promise((e,n)=>{var r;if(this.isEmpty())return void e({mod:"image",src:""});let i=this.ensureImageElement(),o=()=>{e({mod:"image",...this.config}),i.removeEventListener("load",o)},s=()=>{n(Error(`Failed to load image: ${this.config.src}`)),i.removeEventListener("error",s)};i.addEventListener("load",o,{once:!0}),i.addEventListener("error",s,{once:!0}),i.alt=null!=(r=this.config.alt)?r:"",this.config.width&&(i.width=this.config.width),this.config.height&&(i.height=this.config.height),i.src=this.config.src}),this.dispose=()=>{this._dispose(),this.imgElement&&(this.imgElement.src="",this.imgElement=null)},this.interrupt=()=>{}}}class rz extends rH{get mod(){return"video"}static fromSnapshot(e){return new rz(e.config)}static fromSrc(e){let n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return new rz({src:e,...n})}isEmpty(){return!this.config.src}ensureVideoElement(){if(this.videoElement)return this.videoElement;let e=document.createElement("video");return e.muted=!0,e.playsInline=!0,this.videoElement=e,e}constructor(...e){super(...e),this.videoElement=null,this.setTargetElement=e=>{this.videoElement=e},this.runTask=()=>new Promise((e,n)=>{if(this.isEmpty())return void e({mod:"video",src:""});let r=this.ensureVideoElement(),i=()=>{e({mod:"video",...this.config}),r.removeEventListener("loadedmetadata",i)},o=()=>{n(Error(`Failed to load video: ${this.config.src}`)),r.removeEventListener("error",o)};r.addEventListener("loadedmetadata",i,{once:!0}),r.addEventListener("error",o,{once:!0}),this.config.poster&&(r.poster=this.config.poster),this.config.preload&&(r.preload=this.config.preload),this.config.width&&(r.width=this.config.width),this.config.height&&(r.height=this.config.height),r.src=this.config.src,r.load()}),this.dispose=()=>{this._dispose(),this.videoElement&&(this.videoElement.src="",this.videoElement.load(),this.videoElement=null)},this.interrupt=()=>{}}}let rG={preserveOrder:!1,attributeNamePrefix:"@_",attributesGroupName:!1,textNodeName:"#text",ignoreAttributes:!0,removeNSPrefix:!1,allowBooleanAttributes:!1,parseTagValue:!0,parseAttributeValue:!1,trimValues:!0,cdataPropName:!1,numberParseOptions:{hex:!0,leadingZeros:!0,eNotation:!0},tagValueProcessor:function(e,n){return n},attributeValueProcessor:function(e,n){return n},stopNodes:[],alwaysCreateTextNode:!1,isArray:()=>!1,commentPropName:!1,unpairedTags:[],processEntities:!0,htmlEntities:!1,ignoreDeclaration:!1,ignorePiTags:!1,transformTagName:!1,transformAttributeName:!1,updateTag:function(e,n,r){return e},captureMetaData:!1},rJ=":A-Za-z_\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD",rK=RegExp("^"+("["+rJ+"]["+rJ)+"\\-.\\d\\u00B7\\u0300-\\u036F\\u203F-\\u2040]*$");function rQ(e,n){let r=[],i=n.exec(e);for(;i;){let o=[];o.startIndex=n.lastIndex-i[0].length;let s=i.length;for(let e=0;e<s;e++)o.push(i[e]);r.push(o),i=n.exec(e)}return r}let rY=function(e){return null!=rK.exec(e)};n="function"!=typeof Symbol?"@@xmlMetadata":Symbol("XML Node Metadata");class rZ{constructor(e){this.tagname=e,this.child=[],this[":@"]={}}add(e,n){"__proto__"===e&&(e="#__proto__"),this.child.push({[e]:n})}addChild(e,r){"__proto__"===e.tagname&&(e.tagname="#__proto__"),e[":@"]&&Object.keys(e[":@"]).length>0?this.child.push({[e.tagname]:e.child,":@":e[":@"]}):this.child.push({[e.tagname]:e.child}),void 0!==r&&(this.child[this.child.length-1][n]={startIndex:r})}static getMetaDataSymbol(){return n}}let r0=(e,n)=>{for(;n<e.length&&/\s/.test(e[n]);)n++;return n};function r1(e,n,r){let i="",o=e[n];if('"'!==o&&"'"!==o)throw Error(`Expected quoted string, found "${o}"`);for(n++;n<e.length&&e[n]!==o;)i+=e[n],n++;if(e[n]!==o)throw Error(`Unterminated ${r} value`);return[++n,i]}function r2(e,n,r){for(let i=0;i<n.length;i++)if(n[i]!==e[r+i+1])return!1;return!0}function r3(e){if(rY(e))return e;throw Error(`Invalid entity name ${e}`)}let r6=/^[-+]?0x[a-fA-F0-9]+$/,r5=/^([\-\+])?(0*)([0-9]*(\.[0-9]*)?)$/,r4={hex:!0,leadingZeros:!0,decimalPoint:".",eNotation:!0},r8=/^([-+])?(0*)(\d*(\.\d*)?[eE][-\+]?\d+)$/;class r9{constructor(e){var n;this.options=e,this.currentNode=null,this.tagsNodeStack=[],this.docTypeEntities={},this.lastEntities={apos:{regex:/&(apos|#39|#x27);/g,val:"'"},gt:{regex:/&(gt|#62|#x3E);/g,val:">"},lt:{regex:/&(lt|#60|#x3C);/g,val:"<"},quot:{regex:/&(quot|#34|#x22);/g,val:'"'}},this.ampEntity={regex:/&(amp|#38|#x26);/g,val:"&"},this.htmlEntities={space:{regex:/&(nbsp|#160);/g,val:" "},cent:{regex:/&(cent|#162);/g,val:"\xa2"},pound:{regex:/&(pound|#163);/g,val:"\xa3"},yen:{regex:/&(yen|#165);/g,val:"\xa5"},euro:{regex:/&(euro|#8364);/g,val:"€"},copyright:{regex:/&(copy|#169);/g,val:"\xa9"},reg:{regex:/&(reg|#174);/g,val:"\xae"},inr:{regex:/&(inr|#8377);/g,val:"₹"},num_dec:{regex:/&#([0-9]{1,7});/g,val:(e,n)=>String.fromCodePoint(Number.parseInt(n,10))},num_hex:{regex:/&#x([0-9a-fA-F]{1,6});/g,val:(e,n)=>String.fromCodePoint(Number.parseInt(n,16))}},this.addExternalEntities=r7,this.parseXml=io,this.parseTextData=ie,this.resolveNameSpace=it,this.buildAttributesMap=ii,this.isItStopNode=il,this.replaceEntitiesValue=ia,this.readStopNodeData=ip,this.saveTextToParentTag=ic,this.addChild=is,this.ignoreAttributesFn="function"==typeof(n=this.options.ignoreAttributes)?n:Array.isArray(n)?e=>{for(let r of n)if("string"==typeof r&&e===r||r instanceof RegExp&&r.test(e))return!0}:()=>!1}}function r7(e){let n=Object.keys(e);for(let r=0;r<n.length;r++){let i=n[r];this.lastEntities[i]={regex:RegExp("&"+i+";","g"),val:e[i]}}}function ie(e,n,r,i,o,s,a){if(void 0!==e&&(this.options.trimValues&&!i&&(e=e.trim()),e.length>0)){a||(e=this.replaceEntitiesValue(e));let i=this.options.tagValueProcessor(n,e,r,o,s);return null==i?e:typeof i!=typeof e||i!==e?i:this.options.trimValues||e.trim()===e?ih(e,this.options.parseTagValue,this.options.numberParseOptions):e}}function it(e){if(this.options.removeNSPrefix){let n=e.split(":"),r="/"===e.charAt(0)?"/":"";if("xmlns"===n[0])return"";2===n.length&&(e=r+n[1])}return e}let ir=RegExp("([^\\s=]+)\\s*(=\\s*(['\"])([\\s\\S]*?)\\3)?","gm");function ii(e,n,r){if(!0!==this.options.ignoreAttributes&&"string"==typeof e){let r=rQ(e,ir),i=r.length,o={};for(let e=0;e<i;e++){let i=this.resolveNameSpace(r[e][1]);if(this.ignoreAttributesFn(i,n))continue;let s=r[e][4],a=this.options.attributeNamePrefix+i;if(i.length)if(this.options.transformAttributeName&&(a=this.options.transformAttributeName(a)),"__proto__"===a&&(a="#__proto__"),void 0!==s){this.options.trimValues&&(s=s.trim()),s=this.replaceEntitiesValue(s);let e=this.options.attributeValueProcessor(i,s,n);null==e?o[a]=s:typeof e!=typeof s||e!==s?o[a]=e:o[a]=ih(s,this.options.parseAttributeValue,this.options.numberParseOptions)}else this.options.allowBooleanAttributes&&(o[a]=!0)}if(Object.keys(o).length){if(this.options.attributesGroupName){let e={};return e[this.options.attributesGroupName]=o,e}return o}}}let io=function(e){e=e.replace(/\r\n?/g,"\n");let n=new rZ("!xml"),r=n,i="",o="";for(let s=0;s<e.length;s++)if("<"===e[s])if("/"===e[s+1]){let n=iu(e,">",s,"Closing Tag is not closed."),a=e.substring(s+2,n).trim();if(this.options.removeNSPrefix){let e=a.indexOf(":");-1!==e&&(a=a.substr(e+1))}this.options.transformTagName&&(a=this.options.transformTagName(a)),r&&(i=this.saveTextToParentTag(i,r,o));let c=o.substring(o.lastIndexOf(".")+1);if(a&&-1!==this.options.unpairedTags.indexOf(a))throw Error(`Unpaired tag can not be used as closing tag: </${a}>`);let l=0;c&&-1!==this.options.unpairedTags.indexOf(c)?(l=o.lastIndexOf(".",o.lastIndexOf(".")-1),this.tagsNodeStack.pop()):l=o.lastIndexOf("."),o=o.substring(0,l),r=this.tagsNodeStack.pop(),i="",s=n}else if("?"===e[s+1]){let n=id(e,s,!1,"?>");if(!n)throw Error("Pi Tag is not closed.");if(i=this.saveTextToParentTag(i,r,o),this.options.ignoreDeclaration&&"?xml"===n.tagName||this.options.ignorePiTags);else{let e=new rZ(n.tagName);e.add(this.options.textNodeName,""),n.tagName!==n.tagExp&&n.attrExpPresent&&(e[":@"]=this.buildAttributesMap(n.tagExp,o,n.tagName)),this.addChild(r,e,o,s)}s=n.closeIndex+1}else if("!--"===e.substr(s+1,3)){let n=iu(e,"--\x3e",s+4,"Comment is not closed.");if(this.options.commentPropName){let a=e.substring(s+4,n-2);i=this.saveTextToParentTag(i,r,o),r.add(this.options.commentPropName,[{[this.options.textNodeName]:a}])}s=n}else if("!D"===e.substr(s+1,2)){let n=function(e,n){let r={};if("O"===e[n+3]&&"C"===e[n+4]&&"T"===e[n+5]&&"Y"===e[n+6]&&"P"===e[n+7]&&"E"===e[n+8]){n+=9;let i=1,o=!1,s=!1,a="";for(;n<e.length;n++)if("<"!==e[n]||s)if(">"===e[n]){if(s?"-"===e[n-1]&&"-"===e[n-2]&&(s=!1,i--):i--,0===i)break}else"["===e[n]?o=!0:e[n];else{if(o&&r2(e,"!ENTITY",n)){let i,o;n+=7,[i,o,n]=function(e,n){n=r0(e,n);let r="";for(;n<e.length&&!/\s/.test(e[n])&&'"'!==e[n]&&"'"!==e[n];)r+=e[n],n++;if(r3(r),n=r0(e,n),"SYSTEM"===e.substring(n,n+6).toUpperCase())throw Error("External entities are not supported");if("%"===e[n])throw Error("Parameter entities are not supported");let i="";return[n,i]=r1(e,n,"entity"),[r,i,--n]}(e,n+1),-1===o.indexOf("&")&&(r[i]={regx:RegExp(`&${i};`,"g"),val:o})}else if(o&&r2(e,"!ELEMENT",n)){let{index:r}=function(e,n){n=r0(e,n);let r="";for(;n<e.length&&!/\s/.test(e[n]);)r+=e[n],n++;if(!r3(r))throw Error(`Invalid element name: "${r}"`);n=r0(e,n);let i="";if("E"===e[n]&&r2(e,"MPTY",n))n+=4;else if("A"===e[n]&&r2(e,"NY",n))n+=2;else if("("===e[n]){for(n++;n<e.length&&")"!==e[n];)i+=e[n],n++;if(")"!==e[n])throw Error("Unterminated content model")}else throw Error(`Invalid Element Expression, found "${e[n]}"`);return{elementName:r,contentModel:i.trim(),index:n}}(e,(n+=8)+1);n=r}else if(o&&r2(e,"!ATTLIST",n))n+=8;else if(o&&r2(e,"!NOTATION",n)){let{index:r}=function(e,n){n=r0(e,n);let r="";for(;n<e.length&&!/\s/.test(e[n]);)r+=e[n],n++;r3(r),n=r0(e,n);let i=e.substring(n,n+6).toUpperCase();if("SYSTEM"!==i&&"PUBLIC"!==i)throw Error(`Expected SYSTEM or PUBLIC, found "${i}"`);n+=i.length,n=r0(e,n);let o=null,s=null;if("PUBLIC"===i)[n,o]=r1(e,n,"publicIdentifier"),n=r0(e,n),('"'===e[n]||"'"===e[n])&&([n,s]=r1(e,n,"systemIdentifier"));else if("SYSTEM"===i&&([n,s]=r1(e,n,"systemIdentifier"),!s))throw Error("Missing mandatory system identifier for SYSTEM notation");return{notationName:r,publicIdentifier:o,systemIdentifier:s,index:--n}}(e,(n+=9)+1);n=r}else if(r2(e,"!--",n))s=!0;else throw Error("Invalid DOCTYPE");i++}if(0!==i)throw Error("Unclosed DOCTYPE")}else throw Error("Invalid Tag instead of DOCTYPE");return{entities:r,i:n}}(e,s);this.docTypeEntities=n.entities,s=n.i}else if("!["===e.substr(s+1,2)){let n=iu(e,"]]>",s,"CDATA is not closed.")-2,a=e.substring(s+9,n);i=this.saveTextToParentTag(i,r,o);let c=this.parseTextData(a,r.tagname,o,!0,!1,!0,!0);void 0==c&&(c=""),this.options.cdataPropName?r.add(this.options.cdataPropName,[{[this.options.textNodeName]:a}]):r.add(this.options.textNodeName,c),s=n+2}else{let a=id(e,s,this.options.removeNSPrefix),c=a.tagName,l=a.rawTagName,u=a.tagExp,d=a.attrExpPresent,p=a.closeIndex;this.options.transformTagName&&(c=this.options.transformTagName(c)),r&&i&&"!xml"!==r.tagname&&(i=this.saveTextToParentTag(i,r,o,!1));let h=r;h&&-1!==this.options.unpairedTags.indexOf(h.tagname)&&(r=this.tagsNodeStack.pop(),o=o.substring(0,o.lastIndexOf("."))),c!==n.tagname&&(o+=o?"."+c:c);let f=s;if(this.isItStopNode(this.options.stopNodes,o,c)){let n="";if(u.length>0&&u.lastIndexOf("/")===u.length-1)"/"===c[c.length-1]?(c=c.substr(0,c.length-1),o=o.substr(0,o.length-1),u=c):u=u.substr(0,u.length-1),s=a.closeIndex;else if(-1!==this.options.unpairedTags.indexOf(c))s=a.closeIndex;else{let r=this.readStopNodeData(e,l,p+1);if(!r)throw Error(`Unexpected end of ${l}`);s=r.i,n=r.tagContent}let i=new rZ(c);c!==u&&d&&(i[":@"]=this.buildAttributesMap(u,o,c)),n&&(n=this.parseTextData(n,c,o,!0,d,!0,!0)),o=o.substr(0,o.lastIndexOf(".")),i.add(this.options.textNodeName,n),this.addChild(r,i,o,f)}else{if(u.length>0&&u.lastIndexOf("/")===u.length-1){"/"===c[c.length-1]?(c=c.substr(0,c.length-1),o=o.substr(0,o.length-1),u=c):u=u.substr(0,u.length-1),this.options.transformTagName&&(c=this.options.transformTagName(c));let e=new rZ(c);c!==u&&d&&(e[":@"]=this.buildAttributesMap(u,o,c)),this.addChild(r,e,o,f),o=o.substr(0,o.lastIndexOf("."))}else{let e=new rZ(c);this.tagsNodeStack.push(r),c!==u&&d&&(e[":@"]=this.buildAttributesMap(u,o,c)),this.addChild(r,e,o,f),r=e}i="",s=p}}else i+=e[s];return n.child};function is(e,n,r,i){this.options.captureMetaData||(i=void 0);let o=this.options.updateTag(n.tagname,r,n[":@"]);!1===o||("string"==typeof o&&(n.tagname=o),e.addChild(n,i))}let ia=function(e){if(this.options.processEntities){for(let n in this.docTypeEntities){let r=this.docTypeEntities[n];e=e.replace(r.regx,r.val)}for(let n in this.lastEntities){let r=this.lastEntities[n];e=e.replace(r.regex,r.val)}if(this.options.htmlEntities)for(let n in this.htmlEntities){let r=this.htmlEntities[n];e=e.replace(r.regex,r.val)}e=e.replace(this.ampEntity.regex,this.ampEntity.val)}return e};function ic(e,n,r,i){return e&&(void 0===i&&(i=0===n.child.length),void 0!==(e=this.parseTextData(e,n.tagname,r,!1,!!n[":@"]&&0!==Object.keys(n[":@"]).length,i))&&""!==e&&n.add(this.options.textNodeName,e),e=""),e}function il(e,n,r){let i="*."+r;for(let r in e){let o=e[r];if(i===o||n===o)return!0}return!1}function iu(e,n,r,i){let o=e.indexOf(n,r);if(-1!==o)return o+n.length-1;throw Error(i)}function id(e,n,r,i=">"){let o=function(e,n,r=">"){let i,o="";for(let s=n;s<e.length;s++){let n=e[s];if(i)n===i&&(i="");else if('"'===n||"'"===n)i=n;else if(n===r[0]){if(!r[1])return{data:o,index:s};else if(e[s+1]===r[1])return{data:o,index:s}}else" "===n&&(n=" ");o+=n}}(e,n+1,i);if(!o)return;let s=o.data,a=o.index,c=s.search(/\s/),l=s,u=!0;-1!==c&&(l=s.substring(0,c),s=s.substring(c+1).trimStart());let d=l;if(r){let e=l.indexOf(":");-1!==e&&(u=(l=l.substr(e+1))!==o.data.substr(e+1))}return{tagName:l,tagExp:s,closeIndex:a,attrExpPresent:u,rawTagName:d}}function ip(e,n,r){let i=r,o=1;for(;r<e.length;r++)if("<"===e[r])if("/"===e[r+1]){let s=iu(e,">",r,`${n} is not closed`);if(e.substring(r+2,s).trim()===n&&0==--o)return{tagContent:e.substring(i,r),i:s};r=s}else if("?"===e[r+1])r=iu(e,"?>",r+1,"StopNode is not closed.");else if("!--"===e.substr(r+1,3))r=iu(e,"--\x3e",r+3,"StopNode is not closed.");else if("!["===e.substr(r+1,2))r=iu(e,"]]>",r,"StopNode is not closed.")-2;else{let i=id(e,r,">");i&&((i&&i.tagName)===n&&"/"!==i.tagExp[i.tagExp.length-1]&&o++,r=i.closeIndex)}}function ih(e,n,r){if(n&&"string"==typeof e){let n=e.trim();return"true"===n||"false"!==n&&function(e,n={}){if(n=Object.assign({},r4,n),!e||"string"!=typeof e)return e;let r=e.trim();if(void 0!==n.skipLike&&n.skipLike.test(r))return e;{if("0"===e)return 0;if(n.hex&&r6.test(r)){var i,o=r,s=16;if(parseInt)return parseInt(o,16);if(Number.parseInt)return Number.parseInt(o,s);if(window&&window.parseInt)return window.parseInt(o,s);throw Error("parseInt, Number.parseInt, window.parseInt are not supported")}if(-1!==r.search(/.+[eE].+/))return function(e,n,r){if(!r.eNotation)return e;let i=n.match(r8);if(!i)return e;{let o=i[1]||"",s=-1===i[3].indexOf("e")?"E":"e",a=i[2],c=o?e[a.length+1]===s:e[a.length]===s;return a.length>1&&c?e:1===a.length&&(i[3].startsWith(`.${s}`)||i[3][0]===s)?Number(n):r.leadingZeros&&!c?Number(n=(i[1]||"")+i[3]):e}}(e,r,n);let a=r5.exec(r);if(!a)return e;{let o=a[1]||"",s=a[2],c=((i=a[3])&&-1!==i.indexOf(".")&&("."===(i=i.replace(/0+$/,""))?i="0":"."===i[0]?i="0"+i:"."===i[i.length-1]&&(i=i.substring(0,i.length-1))),i),l=o?"."===e[s.length+1]:"."===e[s.length];if(!n.leadingZeros&&(s.length>1||1===s.length&&!l))return e;{let i=Number(r),a=String(i);if(0===i)return i;if(-1!==a.search(/[eE]/))if(n.eNotation)return i;else return e;if(-1!==r.indexOf("."))if("0"===a)return i;else if(a===c)return i;else if(a===`${o}${c}`)return i;else return e;let l=s?c:r;return s?l===a||o+l===a?i:e:l===a||l===o+a?i:e}}}}(e,r)}return void 0!==e?e:""}let im=rZ.getMetaDataSymbol(),ig={allowBooleanAttributes:!1,unpairedTags:[]};function iv(e,n){n=Object.assign({},ig,n);let r=[],i=!1,o=!1;"\uFEFF"===e[0]&&(e=e.substr(1));for(let s=0;s<e.length;s++)if("<"===e[s]&&"?"===e[s+1]){if(s+=2,(s=ib(e,s)).err)return s}else if("<"===e[s]){let a=s;if("!"===e[++s]){s=iw(e,s);continue}{let c=!1;"/"===e[s]&&(c=!0,s++);let l="";for(;s<e.length&&">"!==e[s]&&" "!==e[s]&&" "!==e[s]&&"\n"!==e[s]&&"\r"!==e[s];s++)l+=e[s];if("/"===(l=l.trim())[l.length-1]&&(l=l.substring(0,l.length-1),s--),!rY(l)){let n;return iR("InvalidTag",0===l.trim().length?"Invalid space after '<'.":"Tag '"+l+"' is an invalid name.",iS(e,s))}let u=function(e,n){let r="",i="",o=!1;for(;n<e.length;n++){if('"'===e[n]||"'"===e[n])""===i?i=e[n]:i!==e[n]||(i="");else if(">"===e[n]&&""===i){o=!0;break}r+=e[n]}return""===i&&{value:r,index:n,tagClosed:o}}(e,s);if(!1===u)return iR("InvalidAttr","Attributes for '"+l+"' have open quote.",iS(e,s));let d=u.value;if(s=u.index,"/"===d[d.length-1]){let r=s-d.length,o=i_(d=d.substring(0,d.length-1),n);if(!0!==o)return iR(o.err.code,o.err.msg,iS(e,r+o.err.line));i=!0}else if(c)if(!u.tagClosed)return iR("InvalidTag","Closing tag '"+l+"' doesn't have proper closing.",iS(e,s));else{if(d.trim().length>0)return iR("InvalidTag","Closing tag '"+l+"' can't have attributes or invalid starting.",iS(e,a));if(0===r.length)return iR("InvalidTag","Closing tag '"+l+"' has not been opened.",iS(e,a));let n=r.pop();if(l!==n.tagName){let r=iS(e,n.tagStartPos);return iR("InvalidTag","Expected closing tag '"+n.tagName+"' (opened in line "+r.line+", col "+r.col+") instead of closing tag '"+l+"'.",iS(e,a))}0==r.length&&(o=!0)}else{let c=i_(d,n);if(!0!==c)return iR(c.err.code,c.err.msg,iS(e,s-d.length+c.err.line));if(!0===o)return iR("InvalidXml","Multiple possible root nodes found.",iS(e,s));-1!==n.unpairedTags.indexOf(l)||r.push({tagName:l,tagStartPos:a}),i=!0}for(s++;s<e.length;s++)if("<"===e[s])if("!"===e[s+1]){s=iw(e,++s);continue}else if("?"===e[s+1]){if((s=ib(e,++s)).err)return s}else break;else if("&"===e[s]){let n=function(e,n){if(";"===e[++n])return -1;if("#"===e[n]){var r=++n;let i=/\d/;for("x"===e[r]&&(r++,i=/[\da-fA-F]/);r<e.length;r++){if(";"===e[r])return r;if(!e[r].match(i))break}return -1}let i=0;for(;n<e.length;n++,i++)if(!e[n].match(/\w/)||!(i<20)){if(";"===e[n])break;return -1}return n}(e,s);if(-1==n)return iR("InvalidChar","char '&' is not expected.",iS(e,s));s=n}else if(!0===o&&!iy(e[s]))return iR("InvalidXml","Extra text at the end",iS(e,s));"<"===e[s]&&s--}}else{if(iy(e[s]))continue;return iR("InvalidChar","char '"+e[s]+"' is not expected.",iS(e,s))}return i?1==r.length?iR("InvalidTag","Unclosed tag '"+r[0].tagName+"'.",iS(e,r[0].tagStartPos)):!(r.length>0)||iR("InvalidXml","Invalid '"+JSON.stringify(r.map(e=>e.tagName),null,4).replace(/\r?\n/g,"")+"' found.",{line:1,col:1}):iR("InvalidXml","Start tag expected.",1)}function iy(e){return" "===e||" "===e||"\n"===e||"\r"===e}function ib(e,n){let r=n;for(;n<e.length;n++)if("?"==e[n]||" "==e[n]){let i=e.substr(r,n-r);if(n>5&&"xml"===i)return iR("InvalidXml","XML declaration allowed only at the start of the document.",iS(e,n));if("?"!=e[n]||">"!=e[n+1])continue;n++;break}return n}function iw(e,n){if(e.length>n+5&&"-"===e[n+1]&&"-"===e[n+2]){for(n+=3;n<e.length;n++)if("-"===e[n]&&"-"===e[n+1]&&">"===e[n+2]){n+=2;break}}else if(e.length>n+8&&"D"===e[n+1]&&"O"===e[n+2]&&"C"===e[n+3]&&"T"===e[n+4]&&"Y"===e[n+5]&&"P"===e[n+6]&&"E"===e[n+7]){let r=1;for(n+=8;n<e.length;n++)if("<"===e[n])r++;else if(">"===e[n]&&0==--r)break}else if(e.length>n+9&&"["===e[n+1]&&"C"===e[n+2]&&"D"===e[n+3]&&"A"===e[n+4]&&"T"===e[n+5]&&"A"===e[n+6]&&"["===e[n+7]){for(n+=8;n<e.length;n++)if("]"===e[n]&&"]"===e[n+1]&&">"===e[n+2]){n+=2;break}}return n}let iO=RegExp("(\\s*)([^\\s=]+)(\\s*=)?(\\s*(['\"])(([\\s\\S])*?)\\5)?","g");function i_(e,n){let r=rQ(e,iO),i={};for(let e=0;e<r.length;e++){if(0===r[e][1].length)return iR("InvalidAttr","Attribute '"+r[e][2]+"' has no space in starting.",iT(r[e]));if(void 0!==r[e][3]&&void 0===r[e][4])return iR("InvalidAttr","Attribute '"+r[e][2]+"' is without value.",iT(r[e]));if(void 0===r[e][3]&&!n.allowBooleanAttributes)return iR("InvalidAttr","boolean attribute '"+r[e][2]+"' is not allowed.",iT(r[e]));let o=r[e][2];if(!rY(o))return iR("InvalidAttr","Attribute '"+o+"' is an invalid name.",iT(r[e]));if(i.hasOwnProperty(o))return iR("InvalidAttr","Attribute '"+o+"' is repeated.",iT(r[e]));i[o]=1}return!0}function iR(e,n,r){return{err:{code:e,msg:n,line:r.line||r,col:r.col}}}function iS(e,n){let r=e.substring(0,n).split(/\r?\n/);return{line:r.length,col:r[r.length-1].length+1}}function iT(e){return e.startIndex+e[1].length}class iE{constructor(e){this.externalEntities={},this.options=Object.assign({},rG,e)}parse(e,n){if("string"==typeof e);else if(e.toString)e=e.toString();else throw Error("XML data is accepted in String or Bytes[] form.");if(n){!0===n&&(n={});let r=iv(e,n);if(!0!==r)throw Error(`${r.err.msg}:${r.err.line}:${r.err.col}`)}let r=new r9(this.options);r.addExternalEntities(this.externalEntities);let i=r.parseXml(e);return this.options.preserveOrder||void 0===i?i:function e(n,r,i){let o,s={};for(let a=0;a<n.length;a++){let c=n[a],l=function(e){let n=Object.keys(e);for(let e=0;e<n.length;e++){let r=n[e];if(":@"!==r)return r}}(c),u="";if(u=void 0===i?l:i+"."+l,l===r.textNodeName)void 0===o?o=c[l]:o+=""+c[l];else if(void 0===l)continue;else if(c[l]){let n=e(c[l],r,u),i=function(e,n){let{textNodeName:r}=n,i=Object.keys(e).length;return 0===i||1===i&&(!!e[r]||"boolean"==typeof e[r]||0===e[r])}(n,r);void 0!==c[im]&&(n[im]=c[im]),c[":@"]?function(e,n,r,i){if(n){let o=Object.keys(n),s=o.length;for(let a=0;a<s;a++){let s=o[a];i.isArray(s,r+"."+s,!0,!0)?e[s]=[n[s]]:e[s]=n[s]}}}(n,c[":@"],u,r):1!==Object.keys(n).length||void 0===n[r.textNodeName]||r.alwaysCreateTextNode?0===Object.keys(n).length&&(r.alwaysCreateTextNode?n[r.textNodeName]="":n=""):n=n[r.textNodeName],void 0!==s[l]&&s.hasOwnProperty(l)?(Array.isArray(s[l])||(s[l]=[s[l]]),s[l].push(n)):r.isArray(l,u,i)?s[l]=[n]:s[l]=n}}return"string"==typeof o?o.length>0&&(s[r.textNodeName]=o):void 0!==o&&(s[r.textNodeName]=o),s}(i,this.options)}addEntity(e,n){if(-1!==n.indexOf("&"))throw Error("Entity value can't have '&'");if(-1!==e.indexOf("&")||-1!==e.indexOf(";"))throw Error("An entity must be set without '&' and ';'. Eg. use '#xD' for '
'");if("&"===n)throw Error("An entity with value '&' is not permitted");this.externalEntities[e]=n}static getMetaDataSymbol(){return rZ.getMetaDataSymbol()}}let iM={validate:iv};class ix{constructor(){this.isXml=e=>ix.isXml(e),this.parseXmlOrText=e=>{try{let n=this.xmlParser.parse(e);if(Array.isArray(n)&&!n.length);else if(Array.isArray(n)&&n.length)return n;return e}catch(n){return e}},this.hasMixContentByParsedXml=e=>Array.isArray(e),this.xmlParser=new iE({preserveOrder:!0,ignoreAttributes:!1,attributeNamePrefix:"",textNodeName:"#text",alwaysCreateTextNode:!0})}static #k=this.isTextNode=e=>"text"in e;static #G=this.isImageNode=e=>"image"in e;static #eO=this.isVideoNode=e=>"video"in e;static #e_=this.isXml=e=>"string"==typeof e&&!0===iM.validate(e,{allowBooleanAttributes:!0})}class iC extends rj{constructor(e,n){super({...e,type:"aiWorker"},n),this.opts=n,this.contents=[],this.addContentRenderTask=e=>{iC.isTextContent(e)?(e.emitter.on("data",e=>{this.emitter.emit("content_change",{mod:"text",content:e.char,completed:e.done})}),this.queue.add(e.runTask).finally(()=>{e.dispose()})):iC.isImageContent(e)?this.queue.add(e.runTask).then(e=>{e&&this.emitter.emit("content_change",{mod:"image",content:e.src,completed:!0})}).finally(()=>{e.dispose()}):iC.isVideoContent(e)&&this.queue.add(e.runTask).then(e=>{e&&this.emitter.emit("content_change",{mod:"video",content:e.src,completed:!0})}).finally(()=>{e.dispose()})},this.addAllContents=e=>{for(let n of(this.contents=e,e))this.addContentRenderTask(n)},this.createContentsFromXmlString=e=>{let n=this.customXmlParser.parseXmlOrText(e);return this.customXmlParser.hasMixContentByParsedXml(n)?n[0].root[0].content.map(e=>ix.isTextNode(e)?rW.fromString(e.text[0]["#text"],{typewriterOptions:{delay:this.opts.typeDelay,enDelay:this.opts.enTypeDelay}}):ix.isImageNode(e)?r$.fromSrc(e.image[0]["#text"]):ix.isVideoNode(e)?rz.fromSrc(e.video[0]["#text"]):null).filter(Boolean):[]},this.appendText=e=>{if(this.customXmlParser.isXml(e)){let n=this.createContentsFromXmlString(e);this.addAllContents(n)}else{let n=rW.fromString(e,{typewriterOptions:{delay:this.opts.typeDelay,enDelay:this.opts.enTypeDelay}});this.addContentRenderTask(n),this.contents.push(n)}},this.dispose=()=>{this.queue.removeAllListeners(),this.contents=[]},this.interrupt=()=>{for(let e of this.contents)e.interrupt();this.queue.clear(),this.emitter.emit("interrupt")},this.bindEvents=()=>{this.queue.on("empty",()=>{this.emitter.emit("queue_empty")})},this.queue=new rU({concurrency:1}),this.customXmlParser=new ix,this.bindEvents()}get fulltext(){return this.contents.map(e=>iC.isTextContent(e)?e.getConfig().content:"").join("")}static #k=this.create=e=>new iC({},e);static #G=this.isAllTextContents=e=>e.every(e=>"text"===e.mod);static #eO=this.isTextContent=e=>e instanceof rW&&"text"===e.mod;static #e_=this.isImageContent=e=>e instanceof r$&&"image"===e.mod;static #eR=this.isVideoContent=e=>e instanceof rz&&"video"===e.mod}function ij(e,n){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,n)}function iI(e,n){return function(r,i){n(r,i,e)}}class iB{constructor(e){var n=this;this.opts=e,this.beans=[],this.currentConversation=null,this.aiWorkerConversationFormatters=[],this.add=e=>{this.beans.push(e)},this.addBySnapshot=function(){let e,r=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};switch(r.type){case"client":e=new rB(r,n.opts);break;case"aiWorker":e=new iC(r,n.opts);break;default:throw Error(`Unknown conversation type: ${r.type}`)}return n.beans.push(e),e},this.setCurrentConversation=e=>{this.currentConversation=e},this.clear=()=>{this.beans=[]},this.toJSON=()=>this.beans.map(e=>e.toJSON()),this.dispose=()=>{for(let e of this.beans)e.dispose();this.beans=[],this.currentConversation=null,this.aiWorkerConversationFormatters=[]},this.registerAIWorkerConversationFormatter=e=>{this.aiWorkerConversationFormatters.push(e)},this.runAIWorkerConversationFormatters=e=>{let n=e;for(let e of this.aiWorkerConversationFormatters)n=e(n);return n},this.interruptAll=()=>{for(let e of this.beans)e.interrupt()}}get last(){var e;return null!=(e=this.beans[this.beans.length-1])?e:null}get currentClientConversation(){return iB.isClientConversation(this.currentConversation)?this.currentConversation:null}get currentAIWorkerConversation(){return iB.isAIWorkerConversation(this.currentConversation)?this.currentConversation:null}static isClientConversation(e){return(null==e?void 0:e.type)==="client"}static isAIWorkerConversation(e){return(null==e?void 0:e.type)==="aiWorker"}}iB=function(e,n,r,i){var o,s=arguments.length,a=s<3?n:null===i?i=Object.getOwnPropertyDescriptor(n,r):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)a=Reflect.decorate(e,n,r,i);else for(var c=e.length-1;c>=0;c--)(o=e[c])&&(a=(s<3?o(a):s>3?o(n,r,a):o(n,r))||a);return s>3&&a&&Object.defineProperty(n,r,a),a}([eV(),iI(0,eU(nd.IOptions)),iI(0,ez()),ij("design:type",Function),ij("design:paramtypes",["undefined"==typeof IResolvedOptions?Object:IResolvedOptions])],iB);var ik=et("../../node_modules/abort-signal-polyfill/dist/staticMethods/any.js"),iA=et("../../node_modules/abort-signal-polyfill/dist/staticMethods/timeout.js"),iP=et("../../node_modules/abort-signal-polyfill/dist/staticMethods/abort.js");let iN=(e,n)=>{e in AbortSignal||Object.defineProperty(AbortSignal,e,{value:n,configurable:!0,writable:!0})};var iL=function(){return(iL=Object.assign||function(e){for(var n,r=1,i=arguments.length;r<i;r++)for(var o in n=arguments[r])Object.prototype.hasOwnProperty.call(n,o)&&(e[o]=n[o]);return e}).apply(this,arguments)},iD=et("../../node_modules/@baidu/weirwood-perf/esm/index.js"),iF=function(){return(iF=Object.assign||function(e){for(var n,r=1,i=arguments.length;r<i;r++)for(var o in n=arguments[r])Object.prototype.hasOwnProperty.call(n,o)&&(e[o]=n[o]);return e}).apply(this,arguments)};function iU(e){var n="function"==typeof Symbol&&Symbol.iterator,r=n&&e[n],i=0;if(r)return r.call(e);if(e&&"number"==typeof e.length)return{next:function(){return e&&i>=e.length&&(e=void 0),{value:e&&e[i++],done:!e}}};throw TypeError(n?"Object is not iterable.":"Symbol.iterator is not defined.")}function iH(){for(var e=[],n=0;n<arguments.length;n++)e=e.concat(function(e,n){var r="function"==typeof Symbol&&e[Symbol.iterator];if(!r)return e;var i,o,s=r.call(e),a=[];try{for(;(void 0===n||n-- >0)&&!(i=s.next()).done;)a.push(i.value)}catch(e){o={error:e}}finally{try{i&&!i.done&&(r=s.return)&&r.call(s)}finally{if(o)throw o.error}}return a}(arguments[n]));return e}function iq(e){switch(Object.prototype.toString.call(e)){case"[object Error]":case"[object Exception]":case"[object DOMException]":return!0;default:return e instanceof Error}}function iV(e){return"[object ErrorEvent]"===Object.prototype.toString.call(e)}function iX(e){return void 0===e}function iW(e){return"function"==typeof e}function i$(e){return"[object String]"===Object.prototype.toString.call(e)}function iz(e){return"[object Number]"===Object.prototype.toString.call(e)}function iG(e){return"[object Array]"===Object.prototype.toString.call(e)}function iJ(e){return"[object Object]"===Object.prototype.toString.call(e)}function iK(e){if(!iJ(e))return!1;for(var n in e)if(e.hasOwnProperty(n))return!1;return!0}var iQ={};function iY(){return"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:void 0!==et.g?et.g:"undefined"!=typeof self?self:iQ}var iZ=iY(),i0={wrap:function(){return function(){}},report:!1,collectWindowErrors:!1,computeStackTrace:!1,remoteFetching:!1,linesOfContext:!1,extendToAsynchronousCallbacks:!1},i1=[].slice,i2=/^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?(.*)$/;function i3(e,n){return Object.prototype.hasOwnProperty.call(e,n)}function i6(){return"undefined"==typeof document||null==document.location?"":document.location.href}i0.wrap=function(e){return function(){try{return e.apply(this,arguments)}catch(e){throw i0.report(e),e}}},i0.report=function(){var e,n,r,i,o=[],s=null,a=null;function c(e,n,r,i,s,a){var c=null;if(!n||i0.collectWindowErrors){for(var l in o)if(i3(o,l))try{o[l](e,n,r,i,s,a)}catch(e){c=e}if(c)throw c}}function l(n,r,i,o,s){var l=null;if(s=iV(s)?s.error:s,n=iV(n)?n.message:n,a)i0.computeStackTrace.augmentStackTraceWithInitialElement(a,r,i,n),d();else if(s&&iq(s))(l=i0.computeStackTrace(s)).mechanism="onerror",c(l,!0,s,r,i,o);else{var u,p={url:r,line:i,column:o},h=n;if("[object String]"===({}).toString.call(n)){var f=n.match(i2);f&&(u=f[1],h=f[2])}p.func=i0.computeStackTrace.guessFunctionName(p.url,p.line),p.context=i0.computeStackTrace.gatherContext(p.url,p.line),c(l={name:u,message:h,mode:"onerror",mechanism:"onerror",stack:[iF(iF({},p),{url:p.url||i6()})]},!0,null,r,i,o)}return!!e&&e.apply(this,arguments)}function u(e){var n=e&&(e.detail?e.detail.reason:e.reason)||e,r=i0.computeStackTrace(n);r.mechanism="onunhandledrejection",c(r,!0,n)}function d(){var e=a,n=s;a=null,s=null,c(e,!1,n)}function p(e){if(a)if(s===e)return;else d();var n=i0.computeStackTrace(e);throw a=n,s=e,setTimeout(function(){s===e&&d()},2e3*!!n.incomplete),e}return p.subscribe=function(e){o.push(e)},p.unsubscribe=function(s){for(var a=o.length-1;a>=0;--a)o[a]===s&&o.splice(a,1);0===o.length&&(n&&(iZ.onerror=e,n=!1),i&&(iZ.onunhandledrejection=r,i=!1))},p.installGlobalHandler=function(){!0!==n&&(e=iZ.onerror,iZ.onerror=l,n=!0)},p.installGlobalUnhandledRejectionHandler=function(){!0!==i&&(r=iZ.onunhandledrejection,iZ.onunhandledrejection=u,i=!0)},p}(),i0.computeStackTrace=function(){var e={};function n(n){if("string"!=typeof n)return[];if(!i3(e,n)){var r="",i="";try{i=iZ.document.domain}catch(e){}var o=/(.*)\:\/\/([^:\/]+)([:\d]*)\/{0,1}([\s\S]*)/.exec(n);o&&o[2]===i&&(r=function(e){if(!i0.remoteFetching)return"";try{var n=function(){try{return new iZ.XMLHttpRequest}catch(e){return new iZ.ActiveXObject("Microsoft.XMLHTTP")}}();return n.open("GET",e,!1),n.send(""),n.responseText}catch(e){return""}}(n)),e[n]=r?r.split("\n"):[]}return e[n]}function r(e,r){var i,o=/function ([^(]*)\(([^)]*)\)/,s=/['"]?([0-9A-Za-z$_]+)['"]?\s*[:=]\s*(function|eval|new Function)/,a="",c=n(e);if(!c.length)return"?";for(var l=0;l<10;++l)if(!iX(a=c[r-l]+a)){if(i=s.exec(a))return i[1];else if(i=o.exec(a))return i[1]}return"?"}function i(e,r){var i=n(e);if(!i.length)return null;var o=[],s=Math.floor(i0.linesOfContext/2),a=s+i0.linesOfContext%2,c=Math.max(0,r-s-1),l=Math.min(i.length,r+a-1);r-=1;for(var u=c;u<l;++u)iX(i[u])||o.push(i[u]);return o.length>0?o:null}function o(e){return e.replace(/[\-\[\]{}()*+?.,\\\^$|#]/g,"\\$&")}function s(e){return o(e).replace("<","(?:<|<)").replace(">","(?:>|>)").replace("&","(?:&|&)").replace('"','(?:"|")').replace(/\s+/g,"\\s+")}function a(e,r){for(var i,o,s=0,a=r.length;s<a;++s)if((i=n(r[s])).length&&(i=i.join("\n"),o=e.exec(i)))return{url:r[s],line:i.substring(0,o.index).split("\n").length,column:o.index-i.lastIndexOf("\n",o.index)-1};return null}function c(e,r,i){var s,a=n(r),c=RegExp("\\b"+o(e)+"\\b");return(i-=1,a&&a.length>i&&(s=c.exec(a[i])))?s.index:null}function l(e){if(!e.stack)return null;for(var n,o,s,a,l=/^\s*at (?:(.*?) ?\()?((?:file|https?|blob|chrome-extension|native|eval|webpack|<anonymous>|[a-z]:|\/).*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i,u=/^\s*(.*?)(?:\((.*?)\))?(?:^|@)((?:file|https?|blob|chrome|webpack|resource|moz-extension).*?:\/.*?|\[native code\]|[^@]*bundle)(?::(\d+))?(?::(\d+))?\s*$/i,d=/^\s*at (?:((?:\[object object\])?.+) )?\(?((?:file|ms-appx|https?|webpack|blob):.*?):(\d+)(?::(\d+))?\)?\s*$/i,p=/(\S+) line (\d+)(?: > eval line \d+)* > eval/i,h=/\((\S*)(?::(\d+))(?::(\d+))\)/,f=e.stack.split("\n"),m=[],g=/^(.*) is undefined$/.exec(e.message),v=0,y=f.length;v<y;++v){if(s=l.exec(f[v])){var b=s[2]&&0===s[2].indexOf("native");s[2]&&0===s[2].indexOf("eval")&&(o=h.exec(s[2]))&&(s[2]=o[1]),a={url:b?null:s[2],func:s[1]||"?",args:b?[s[2]]:[],line:s[3]?+s[3]:null,column:s[4]?+s[4]:null}}else if(s=d.exec(f[v]))a={url:s[2],func:s[1]||"?",args:[],line:+s[3],column:s[4]?+s[4]:null};else{if(!(s=u.exec(f[v])))continue;s[3]&&s[3].indexOf(" > eval")>-1&&(o=p.exec(s[3]))?s[3]=o[1]:0!==v||s[5]||iX(e.columnNumber)||(m[0].column=e.columnNumber+1),a={url:s[3],func:s[1]||"?",args:s[2]?s[2].split(","):[],line:s[4]?+s[4]:null,column:s[5]?+s[5]:null}}if(!a.func&&a.line&&(a.func=r(a.url,a.line)),i0.remoteFetching&&a.url&&"blob:"===a.url.substr(0,5)){var w=new XMLHttpRequest;if(w.open("GET",a.url,!1),w.send(""),200===w.status){var O=w.responseText||"",_=(O=O.slice(-300)).match(/\/\/# sourceMappingURL=(.*)$/);if(_){var R=_[1];"~"===R.charAt(0)&&(R=("undefined"==typeof document||null==document.location?"":document.location.origin?document.location.origin:document.location.protocol+"//"+document.location.hostname+(document.location.port?":"+document.location.port:""))+R.slice(1)),a.url=R.slice(0,-4)}}}a.context=a.line?i(a.url,a.line):null,m.push(a)}return m.length?(m[0]&&m[0].line&&!m[0].column&&g&&(m[0].column=c(g[1],m[0].url,m[0].line)),{mode:"stack",name:e.name,message:e.message,stack:m}):null}function u(e,n,o,s){var a={url:n,line:o};if(a.url&&a.line){e.incomplete=!1,a.func||(a.func=r(a.url,a.line)),a.context||(a.context=i(a.url,a.line));var l=/ '([^']+)' /.exec(s);if(l&&(a.column=c(l[1],a.url,a.line)),e.stack.length>0&&e.stack[0].url===a.url){if(e.stack[0].line===a.line)return!1;else if(!e.stack[0].line&&e.stack[0].func===a.func)return e.stack[0].line=a.line,e.stack[0].context=a.context,!1}return e.stack.unshift(a),e.partial=!0,!0}return e.incomplete=!0,!1}function d(e,p){var h=null;p=null==p?0:+p;try{if(h=function(e){var n=e.stacktrace;if(n){for(var o,s=/ line (\d+).*script (?:in )?(\S+)(?:: in function (\S+))?$/i,a=/ line (\d+), column (\d+)\s*(?:in (?:<anonymous function: ([^>]+)>|([^\)]+))\((.*)\))? in (.*):\s*$/i,c=n.split("\n"),l=[],u=0;u<c.length;u+=2){var d=null;if((o=s.exec(c[u]))?d={url:o[2],line:+o[1],column:null,func:o[3],args:[]}:(o=a.exec(c[u]))&&(d={url:o[6],line:+o[1],column:+o[2],func:o[3]||o[4],args:o[5]?o[5].split(","):[]}),d){if(!d.func&&d.line&&(d.func=r(d.url,d.line)),d.line)try{d.context=i(d.url,d.line)}catch(e){}d.context||(d.context=[c[u+1]]),l.push(d)}}return l.length?{mode:"stacktrace",name:e.name,message:e.message,stack:l}:null}}(e))return h}catch(e){}try{if(h=l(e))return h}catch(e){}try{if(h=function(e){var o=e.message.split("\n");if(o.length<4)return null;var c,l=/^\s*Line (\d+) of linked script ((?:file|https?|blob)\S+)(?:: in function (\S+))?\s*$/i,u=/^\s*Line (\d+) of inline#(\d+) script in ((?:file|https?|blob)\S+)(?:: in function (\S+))?\s*$/i,d=/^\s*Line (\d+) of function script\s*$/i,p=[],h=iZ&&iZ.document&&iZ.document.getElementsByTagName("script"),f=[];for(var m in h)i3(h,m)&&!h[m].src&&f.push(h[m]);for(var g=2;g<o.length;g+=2){var v=null;if(c=l.exec(o[g]))v={url:c[2],func:c[3],args:[],line:+c[1],column:null};else if(c=u.exec(o[g])){v={url:c[3],func:c[4],args:[],line:+c[1],column:null};var y=+c[1],b=f[c[2]-1];if(b){var w=n(v.url);if(w){var O=(w=w.join("\n")).indexOf(b.innerText);O>=0&&(v.line=y+w.substring(0,O).split("\n").length)}}}else if(c=d.exec(o[g])){var _=i6().replace(/#.*$/,""),R=a(new RegExp(s(o[g+1])),[_]);v={url:_,func:"",args:[],line:R?R.line:c[1],column:null}}if(v){v.func||(v.func=r(v.url,v.line));var S=i(v.url,v.line),T=S?S[Math.floor(S.length/2)]:null;S&&T.replace(/^\s*/,"")===o[g+1].replace(/^\s*/,"")?v.context=S:v.context=[o[g+1]],p.push(v)}}return p.length?{mode:"multiline",name:e.name,message:o[0],stack:p}:null}(e))return h}catch(e){}try{if(h=function e(n,i){for(var l,p,h,f=/function\s+([_$a-zA-Z\xA0-\uFFFF][_$a-zA-Z0-9\xA0-\uFFFF]*)?\s*\(/i,m=[],g={},v=!1,y=e.caller;y&&!v;y=y.caller)if(y!==d&&y!==i0.report){if(p={url:null,func:"?",args:[],line:null,column:null},y.name?p.func=y.name:(l=f.exec(y.toString()))&&(p.func=l[1]),void 0===p.func)try{p.func=l.input.substring(0,l.input.indexOf("{"))}catch(e){}if(h=function(e){if(!iX(iZ&&iZ.document)){for(var n,r,i,c,l=[i6()],u=iZ.document.getElementsByTagName("script"),d=""+e,p=0;p<u.length;++p){var h=u[p];h.src&&l.push(h.src)}if(i=/^function(?:\s+([\w$]+))?\s*\(([\w\s,]*)\)\s*\{\s*(\S[\s\S]*\S)\s*\}\s*$/.exec(d)){var f=i[1]?"\\s+"+i[1]:"",m=i[2].split(",").join("\\s*,\\s*");r=RegExp("function"+f+"\\s*\\(\\s*"+m+"\\s*\\)\\s*{\\s*"+(n=o(i[3]).replace(/;$/,";?"))+"\\s*}")}else r=new RegExp(o(d).replace(/\s+/g,"\\s+"));if(c=a(r,l))return c;if(i=/^function on([\w$]+)\s*\(event\)\s*\{\s*(\S[\s\S]*\S)\s*\}\s*$/.exec(d)){var g=i[1];if((c=a(r=RegExp("on"+g+"=[\\'\"]\\s*"+(n=s(i[2]))+"\\s*[\\'\"]","i"),l[0]))||(c=a(r=new RegExp(n),l)))return c}return null}}(y)){p.url=h.url,p.line=h.line,"?"===p.func&&(p.func=r(p.url,p.line));var b=/ '([^']+)' /.exec(n.message||n.description);b&&(p.column=c(b[1],h.url,h.line))}g[""+y]?v=!0:g[""+y]=!0,m.push(p)}i&&m.splice(0,i);var w={mode:"callers",name:n.name,message:n.message,stack:m};return u(w,n.sourceURL||n.fileName,n.line||n.lineNumber,n.message||n.description),w}(e,p+1))return h}catch(e){}return{original:e,name:e.name,message:e.message,mode:"failed"}}return d.augmentStackTraceWithInitialElement=u,d.computeStackTraceFromStackProp=l,d.guessFunctionName=r,d.gatherContext=i,d.ofCaller=function(e){e=(null==e?0:+e)+1;try{throw Error()}catch(n){return d(n,e+1)}},d.getSource=n,d}(),i0.extendToAsynchronousCallbacks=function(){var e=function(e){var n=iZ[e];iZ[e]=function(){var e=i1.call(arguments),r=e[0];return("function"==typeof r&&(e[0]=i0.wrap(r)),n.apply)?n.apply(this,e):n(e[0],e[1])}};e("setTimeout"),e("setInterval")},i0.remoteFetching=!1,i0.collectWindowErrors=!0,i0.linesOfContext=11,i0.report;var i5=i0.report.subscribe,i4=i0.report.unsubscribe,i8=i0.report.installGlobalHandler,i9=i0.report.installGlobalUnhandledRejectionHandler,i7=i0.computeStackTrace;function oe(e,n){var r=(65535&e)+(65535&n);return(e>>16)+(n>>16)+(r>>16)<<16|65535&r}function ot(e,n,r,i,o,s){var a;return oe((a=oe(oe(n,e),oe(i,s)))<<o|a>>>32-o,r)}function on(e,n,r,i,o,s,a){return ot(n&r|~n&i,e,n,o,s,a)}function or(e,n,r,i,o,s,a){return ot(n&i|r&~i,e,n,o,s,a)}function oi(e,n,r,i,o,s,a){return ot(n^r^i,e,n,o,s,a)}function oo(e,n,r,i,o,s,a){return ot(r^(n|~i),e,n,o,s,a)}function os(e,n){e[n>>5]|=128<<n%32,e[(n+64>>>9<<4)+14]=n;var r,i,o,s,a,c=0x67452301,l=-0x10325477,u=-0x67452302,d=0x10325476;for(r=0;r<e.length;r+=16)i=c,o=l,s=u,a=d,c=on(c,l,u,d,e[r],7,-0x28955b88),d=on(d,c,l,u,e[r+1],12,-0x173848aa),u=on(u,d,c,l,e[r+2],17,0x242070db),l=on(l,u,d,c,e[r+3],22,-0x3e423112),c=on(c,l,u,d,e[r+4],7,-0xa83f051),d=on(d,c,l,u,e[r+5],12,0x4787c62a),u=on(u,d,c,l,e[r+6],17,-0x57cfb9ed),l=on(l,u,d,c,e[r+7],22,-0x2b96aff),c=on(c,l,u,d,e[r+8],7,0x698098d8),d=on(d,c,l,u,e[r+9],12,-0x74bb0851),u=on(u,d,c,l,e[r+10],17,-42063),l=on(l,u,d,c,e[r+11],22,-0x76a32842),c=on(c,l,u,d,e[r+12],7,0x6b901122),d=on(d,c,l,u,e[r+13],12,-0x2678e6d),u=on(u,d,c,l,e[r+14],17,-0x5986bc72),l=on(l,u,d,c,e[r+15],22,0x49b40821),c=or(c,l,u,d,e[r+1],5,-0x9e1da9e),d=or(d,c,l,u,e[r+6],9,-0x3fbf4cc0),u=or(u,d,c,l,e[r+11],14,0x265e5a51),l=or(l,u,d,c,e[r],20,-0x16493856),c=or(c,l,u,d,e[r+5],5,-0x29d0efa3),d=or(d,c,l,u,e[r+10],9,0x2441453),u=or(u,d,c,l,e[r+15],14,-0x275e197f),l=or(l,u,d,c,e[r+4],20,-0x182c0438),c=or(c,l,u,d,e[r+9],5,0x21e1cde6),d=or(d,c,l,u,e[r+14],9,-0x3cc8f82a),u=or(u,d,c,l,e[r+3],14,-0xb2af279),l=or(l,u,d,c,e[r+8],20,0x455a14ed),c=or(c,l,u,d,e[r+13],5,-0x561c16fb),d=or(d,c,l,u,e[r+2],9,-0x3105c08),u=or(u,d,c,l,e[r+7],14,0x676f02d9),l=or(l,u,d,c,e[r+12],20,-0x72d5b376),c=oi(c,l,u,d,e[r+5],4,-378558),d=oi(d,c,l,u,e[r+8],11,-0x788e097f),u=oi(u,d,c,l,e[r+11],16,0x6d9d6122),l=oi(l,u,d,c,e[r+14],23,-0x21ac7f4),c=oi(c,l,u,d,e[r+1],4,-0x5b4115bc),d=oi(d,c,l,u,e[r+4],11,0x4bdecfa9),u=oi(u,d,c,l,e[r+7],16,-0x944b4a0),l=oi(l,u,d,c,e[r+10],23,-0x41404390),c=oi(c,l,u,d,e[r+13],4,0x289b7ec6),d=oi(d,c,l,u,e[r],11,-0x155ed806),u=oi(u,d,c,l,e[r+3],16,-0x2b10cf7b),l=oi(l,u,d,c,e[r+6],23,0x4881d05),c=oi(c,l,u,d,e[r+9],4,-0x262b2fc7),d=oi(d,c,l,u,e[r+12],11,-0x1924661b),u=oi(u,d,c,l,e[r+15],16,0x1fa27cf8),l=oi(l,u,d,c,e[r+2],23,-0x3b53a99b),c=oo(c,l,u,d,e[r],6,-0xbd6ddbc),d=oo(d,c,l,u,e[r+7],10,0x432aff97),u=oo(u,d,c,l,e[r+14],15,-0x546bdc59),l=oo(l,u,d,c,e[r+5],21,-0x36c5fc7),c=oo(c,l,u,d,e[r+12],6,0x655b59c3),d=oo(d,c,l,u,e[r+3],10,-0x70f3336e),u=oo(u,d,c,l,e[r+10],15,-1051523),l=oo(l,u,d,c,e[r+1],21,-0x7a7ba22f),c=oo(c,l,u,d,e[r+8],6,0x6fa87e4f),d=oo(d,c,l,u,e[r+15],10,-0x1d31920),u=oo(u,d,c,l,e[r+6],15,-0x5cfebcec),l=oo(l,u,d,c,e[r+13],21,0x4e0811a1),c=oo(c,l,u,d,e[r+4],6,-0x8ac817e),d=oo(d,c,l,u,e[r+11],10,-0x42c50dcb),u=oo(u,d,c,l,e[r+2],15,0x2ad7d2bb),l=oo(l,u,d,c,e[r+9],21,-0x14792c6f),c=oe(c,i),l=oe(l,o),u=oe(u,s),d=oe(d,a);return[c,l,u,d]}function oa(e){var n,r="",i=32*e.length;for(n=0;n<i;n+=8)r+=String.fromCharCode(e[n>>5]>>>n%32&255);return r}function oc(e){var n,r=[];for(n=0,r[(e.length>>2)-1]=void 0;n<r.length;n+=1)r[n]=0;var i=8*e.length;for(n=0;n<i;n+=8)r[n>>5]|=(255&e.charCodeAt(n/8))<<n%32;return r}function ol(e){var n,r,i="0123456789abcdef",o="";for(r=0;r<e.length;r+=1)o+=i.charAt((n=e.charCodeAt(r))>>>4&15)+i.charAt(15&n);return o}function ou(e){return unescape(encodeURIComponent(e))}function od(e){var n;return oa(os(oc(n=ou(e)),8*n.length))}function op(e,n){return function(e,n){var r,i,o=oc(e),s=[],a=[];for(s[15]=a[15]=void 0,o.length>16&&(o=os(o,8*e.length)),r=0;r<16;r+=1)s[r]=0x36363636^o[r],a[r]=0x5c5c5c5c^o[r];return i=os(s.concat(oc(n)),512+8*n.length),oa(os(a.concat(i),640))}(ou(e),ou(n))}function oh(e,n,r){if(!n)return r?od(e):ol(od(e));return r?op(n,e):ol(op(n,e))}function of(e){return(e||"").replace(/#.*$/,"").replace(/\?.*$/,"")}function om(){if(!("fetch"in iY()))return!1;try{return new Headers,new Request(""),new Response,!0}catch(e){return!1}}function og(e,n){for(var r=0;r<e.length;++r)if(e[r]===n)return r;return -1}function ov(e,n,r,i){var o,s,a,c;return JSON.stringify(e,(o=n,a=[],c=[],null==(s=i)&&(s=function(e,n){return a[0]===n?"[Circular ~]":"[Circular ~."+c.slice(0,og(a,n)).join(".")+"]"}),function(e,n){if(a.length>0){var r=og(a,this);~r?a.splice(r+1):a.push(this),~r?c.splice(r,1/0,e):c.push(e),~og(a,n)&&(n=s.call(this,e,n))}else a.push(n);return null==o?n instanceof Error?function(e){var n={stack:e.stack,message:e.message,name:e.name};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(n[r]=e[r]);return n}(n):n:o.call(this,e,n)}),r)}function oy(e,n){if(Array.isArray(e))for(var r=e.length,i=0;i<r;i++)n.call(null,i,e[i]);else for(var o in e)Reflect.has(e,o)&&n.call(null,o,e[o])}function ob(e){var n={};for(var r in e)if(e.hasOwnProperty(r)){var i=e[r];n[r]=iW(i)?i():i}return n}function ow(e){return i$(e)?oO(e,40):iz(e)||"[object Boolean]"===Object.prototype.toString.call(e)||iX(e)?e+"":iJ(e)?"[Object]":iG(e)?"[Array]":iW(e)?e.name?"[Function: "+e.name+"]":"[Function]":e}function oO(e,n){return 0===n||e.length<=n?e:e.substr(0,n)+"…"}function o_(e){var n={protocol:"",host:"",path:"",relative:""};if("string"!=typeof e)return n;var r=e.match(/^(([^:\/?#]+):)?(\/\/([^\/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?$/);if(r&&r.length){var i=r[6]||"",o=r[8]||"";return{protocol:r[2]||"",host:r[4]||"",path:r[5]||"",relative:(r[5]||"")+i+o}}return n}function oR(e){var n=e.exception,r=[];return r.push("token="+n.token),r.push("type="+n.type),r.push("mechanism="+n.mechanism),r.push("value="+n.value),r.push("url="+n.url),n.stacktrace&&n.stacktrace.forEach(function(e){r.push("filename="+e.filename),r.push("lineno="+e.lineno),r.push("colno="+e.colno)}),r.join("***")}function oS(e){return e&&Array.isArray(e)&&e.length>0}function oT(e){for(var n=[],r=e.length,i=0;i<r;i++){var o=e[i];i$(o)?n.push(o.replace(/([.*+?^=!:${}()|\[\]\/\\])/g,"\\$1")):o&&o.source&&n.push(o.source)}return RegExp(n.join("|"),"i")}function oE(e,n){return!!i$(n)&&e.some(function(e){if(!e)return!1;if(i$(e))return -1!==n.indexOf(e);if("[object RegExp]"===Object.prototype.toString.call(e))try{return e.test(n)}catch(n){return console.error(e+"正则书写有误"),!1}return console.error(e+"忽略匹配项类型应该是String、RegExp"),!1})}function oM(e){return(i$(e)?e:JSON.stringify(e)).slice(0,256)}function ox(e,n,r){var i,o,s=[];if(e.stack&&e.stack.length){try{for(var a=iU(e.stack),c=a.next();!c.done;c=a.next()){var l=c.value,u=function(e,n,r){var i={filename:e.url||n,lineno:e.line,colno:e.column,function:e.func||"?"};if(r&&r.length>0){var o=oT(r).test(i.filename),s=/(Weirwood|Tracekit)/.test(i.function),a=/weirwood\-sdk/.test(i.filename);i.in_app=o,(s||a)&&(i.in_app=!1)}else i.in_app=!1;return i}(l,e.url||"",n.includePaths);s.push(u)}}catch(e){i={error:e}}finally{try{c&&!c.done&&(o=a.return)&&o.call(a)}finally{if(i)throw i.error}}if(n&&n.trimHeadFrames)for(var d=0;d<n.trimHeadFrames&&d<s.length;d++)s[d].in_app=!1}return(s=s.filter(function(e){var n,r,i;return r=-1!==(n=e.filename||"").indexOf("weirwood-sdk"),i=/captureException$/.test(n),!r&&!i})).slice(0,r)}function oC(e,n,r,i){if(null!=e){var o=e[n];return e[n]=r(o),e[n].__raven__=!0,e[n].__orig__=o,o.__raven_wrapper__=e[n],i&&i.push([e,n,o]),e[n]}}function oj(e,n,r){if(void 0===e&&(e={}),iX(n)&&!iW(e))return e;if(iW(e)&&(n=e,e=void 0),!iW(n))return n;try{if(n.__raven__)return n;if(n.__raven_wrapper__)return n.__raven_wrapper__}catch(e){return n}function i(){for(var i=[],o=0;o<arguments.length;o++)i[o]=arguments[o];var s=[],a=i.length,c=!e||e&&!1!==e.deep;for(r&&iW(r)&&r.apply(this,i);a--;)s[a]=c?oj(e,i[a]):i[a];try{return n.apply(this,s)}catch(e){throw e}}for(var o in n)n.hasOwnProperty(o)&&(i[o]=n[o]);return i.prototype=n.prototype,n.__raven_wrapper__=i,i.__raven__=!0,i.__orig__=n,i}function oI(e){return function(){for(var n=[],r=0;r<arguments.length;r++)n[r]=arguments[r];var i=n[0];return(iW(i)&&(n[0]=oj({mechanism:{type:"instrument",data:{function:(null==e?void 0:e.name)||"<anonymous>"}}},i)),e.apply)?e.apply(this,n):e(n[0],n[1])}}function oB(e,n){return function(r){if(N=void 0,L!==r){L=r;try{i=function(e){for(var n,r=[],i=0,o=0;e&&i++<5;){var s="html"===(n=function(e){if(!e||!e.tagName)return"";var n,r,i,o,s=[e.tagName.toLowerCase()];e.id&&s.push("#"+e.id);var a=e.className?e.className.split(/\s+/):[];try{for(var c=iU(a),l=c.next();!l.done;l=c.next()){var u=l.value;s.push("."+u)}}catch(e){n={error:e}}finally{try{l&&!l.done&&(r=c.return)&&r.call(c)}finally{if(n)throw n.error}}try{for(var d=iU(["type","name","title","alt"]),p=d.next();!p.done;p=d.next()){var h=p.value,f=e.getAttribute(h);f&&s.push("["+h+"="+f+"]")}}catch(e){i={error:e}}finally{try{p&&!p.done&&(o=d.return)&&o.call(d)}finally{if(i)throw i.error}}return s.join("")}(e)),a=i>1&&o+3*r.length+n.length>=80;if(s||a)break;r.push(n),o+=n.length,e=e.parentNode}return r.reverse().join(" > ")}(r.target)}catch(e){i="<unknown>"}if(i){var i,o={category:"ui."+n,message:i,name:n};"input"===n&&"password"!==i.type&&(o.data=r.target.value||""),e.captureBehavior(o)}}}}function ok(e){return function(n){try{r=n.target}catch(e){return}var r,i=r&&r.tagName;i&&("INPUT"===i||"TEXTAREA"===i||r.isContentEditable)&&(N||oB(e,"input")(n),clearTimeout(N),N=setTimeout(function(){N=void 0},1e3))}}et("../../node_modules/@baidu/weirwood-error/esm/plugins/Plugin.js");var oA=iY(),oP=[301,302,304],oN=function(){function e(n){this.name=e.id,this.options=iF({beacon:!0,console:!0,dom:!0,fetch:!0,history:!0,weirwood:!0,xhr:!0},n)}return e.prototype.setupOnce=function(e){this.client=e;var n,r,i=Object.keys(this.options);try{for(var o=iU(i),s=o.next();!s.done;s=o.next()){var a=s.value,c="instrument"+a[0].toUpperCase()+a.slice(1);this.options[a]&&this[c]&&"function"==typeof this[c]&&this[c].call(this)}}catch(e){n={error:e}}finally{try{s&&!s.done&&(r=o.return)&&r.call(o)}finally{if(n)throw n.error}}},e.prototype.instrumentDom=function(){if("document"in iY()){var e=oA.document;e.addEventListener("click",oB.call(this,this.client,"click"),!1),e.addEventListener("keypress",ok.call(this,this.client),!1)}},e.prototype.instrumentXhr=function(){var e=this.client,n=e.options,r=n.collectAutoAPIException,i=n.isApiException;if("XMLHttpRequest"in oA){var o=XMLHttpRequest.prototype,s=e._globalKey||"";oC(o,"open",function(e){return function(n,r){return i$(r)&&-1===r.indexOf(s)&&(this.__raven_xhr={method:n,url:r,status_code:null}),e.apply(this,arguments)}},e._wrappedBuiltIns),oC(o,"abort",function(e){return function(){return this.__raven_xhr&&(this.__raven_xhr.abortedFlag=!0),e.apply(this,arguments)}},e._wrappedBuiltIns),oC(o,"send",function(n){return function(){var o=this,s=arguments;function a(){if(o.__raven_xhr&&4===o.readyState){try{o.__raven_xhr.status_code=o.status}catch(e){}var n=function(e,n){if(void 0===e&&(e=""),void 0===n&&(n=""),(""===e||"text"===e)&&i$(n)&&n.length)try{return JSON.parse(n)}catch(e){return n}return"json"===e?JSON.parse(JSON.stringify(n)):""}(o.responseType,o.response);if((e.captureBehavior({type:"http",category:"xhr",data:iF(iF({},o.__raven_xhr),{response:oM(n),params:oM(s&&s[0]?s[0]:"")})}),r)&&(!o.__raven_xhr||!o.__raven_xhr.abortedFlag)){var a=!1,c=o.status>=200&&o.status<=299,l=-1!==oP.indexOf(o.status);if(c||l||(a=!0),c&&i&&iW(i)&&(a=!!i({method:o.__raven_xhr.method,url:o.responseURL,status:o.status,responseType:o.responseType,response:n})),a){var u="";iW(o.getAllResponseHeaders)&&(u=o.getAllResponseHeaders().trim().replace(/[\r\n]+/g,"***")),e.captureAPIException({url:o.responseURL||o.__raven_xhr.url,method:o.__raven_xhr.method,params:s&&s[0]?s[0]:"",status:o.status,response:(i$(n)?n:JSON.stringify(n)).slice(0,8192),responseHeaders:u,user:"",extra:"AUTO_XHR"})}}}}for(var c=["onload","onerror","onprogress"],l=0;l<c.length;l++)!function(e,n){e in n&&iW(n[e])&&oC(n,e,function(n){return oj({mechanism:{data:{function:e,handler:n&&n.name||"<anonymous>"},handled:!0,type:"instrument"}},n)})}(c[l],o);return"onreadystatechange"in o&&iW(o.onreadystatechange)?oC(o,"onreadystatechange",function(e){return oj({mechanism:{type:"instrument",data:{function:"onreadystatechange",handler:e&&e.name||"<anonymous>"}}},e,a)}):o.onreadystatechange=a,n.apply(this,arguments)}},e._wrappedBuiltIns)}},e.prototype.instrumentFetch=function(){if(om()){var e=iY(),n=this.client,r=n.options,i=r.collectAutoAPIException,o=r.isApiException,s=n._globalKey;oC(oA,"fetch",function(r){return function(){for(var a,c=Array(arguments.length),l=0;l<c.length;++l)c[l]=arguments[l];var u=c[0],d="GET";if("string"==typeof u?a=u:"Request"in e&&u instanceof e.Request?(a=u.url,(null==u?void 0:u.method)&&(d=u.method)):a=""+u,-1!==a.indexOf(s))return r.apply(this,c);c[1]&&c[1].method&&(d=c[1].method);var p={method:d,url:a,status_code:null};return r.apply(this,c).then(function(e){p.status_code=e.status;var r,s,a="";c[1]&&c[1].body&&(a=c[1].body);var l=iW(e.clone)?e.clone():null,u={type:"http",category:"fetch",data:iF(iF({},p),{params:oM(a),response:""})};if(l?l.text().then(function(e){var r;try{r=JSON.parse(e)}catch(n){r=e}u.data.response=oM(r),n.captureBehavior(u)}):n.captureBehavior(u),!i)return e;var d=!1,h=iW(e.clone)?e.clone():null,f=oP.includes(e.status);e.ok||f||(d=!0);var m={method:p.method,url:p.url,status:e.status,response:""},g=[];try{for(var v=iU(e.headers.entries()),y=v.next();!y.done;y=v.next()){var b=y.value;g.push(b[0]+": "+b[1])}}catch(e){r={error:e}}finally{try{y&&!y.done&&(s=v.return)&&s.call(v)}finally{if(r)throw r.error}}var w=iF(iF({},m),{params:a,responseHeaders:g.join("***"),user:"",extra:"AUTO_FETCH"});return h?h.text().then(function(r){var i;try{i=JSON.parse(r)}catch(e){i=r}e.ok&&iW(o)&&(d=!!o(iF(iF({},m),{response:i}))),d&&n.captureAPIException(iF(iF({},w),{response:r.slice(0,8192)}))}).catch(function(e){console.error(e)}):(e.ok&&iW(o)&&(d=!!o(m)),d&&n.captureAPIException(w)),e}).catch(function(e){throw n.captureBehavior({type:"http",category:"fetch",data:p,level:"error"}),e})}},n._wrappedBuiltIns)}},e.prototype.instrumentHistory=function(){var e,n,r,i,o=this.client;if(r=(n=(e=iY()).chrome)&&n.app&&n.app.runtime,i="history"in e&&!!e.history.pushState&&!!e.history.replaceState,!r&&i){var s=function(e,n){var r=o_(oA.location.href),i=o_(n),s=o_(e);s.path||(s=r),D=n,r.protocol===i.protocol&&r.host===i.host&&(n=i.relative),r.protocol===s.protocol&&r.host===s.host&&(e=s.relative),o.captureBehavior({category:"navigation",data:{from:e,to:n}})},a=oA.onpopstate;oA.onpopstate=function(e){var n=oA.location.href;if(s(D,n),a)return a.apply(oA,e)},oC(oA.history,"pushState",c),oC(oA.history,"replaceState",c)}function c(e){return function(){for(var n=[],r=0;r<arguments.length;r++)n[r]=arguments[r];var i=n.length>2?n[2]:void 0;return i&&s(D,String(i)),e.apply(this,n)}}},e.prototype.instrumentConsole=function(){},e.prototype.instrumentBeacon=function(){},e.id="behaviors",e}(),oL=iY(),oD=function(){function e(n){this.name=e.id,this.options=iF({active:!0},n)}return e.prototype.setupOnce=function(e){this.client=e,this.options.active&&oC(oL,"setTimeout",oI,this.client._wrappedBuiltIns)},e.id="trycatch",e}(),oF=iY(),oU=function(){function e(){this.name=e.id}return e.prototype.setupOnce=function(e){this.client=e,this.client.captureUserAgent(this.getUserAgent())},e.prototype.getUserAgent=function(){return"navigator"in oF&&"document"in oF?{url:oF.location.href,headers:{"User-Agent":oF.navigator.userAgent,Referrer:oF.document.referrer}}:{}},e.id="UserAgent",e}(),oH={collectWindowErrors:!0,collectUnhandledRejections:!0,collectResourceLoadErrors:!1,collectAutoAPIException:!0,sampleRate:1,maxUrlLength:250,maxMessageLength:0,allowDuplicates:!1,stackTraceLimit:50,behaviorLimit:10,plugins:[],ignoreErrors:[],ignoreKeys:[],whitelistUrls:[],apiWhitelistUrls:[],resourceWhitelistUrls:[],ignoreUrls:[],ignoreJsUrls:[],ignoreApiUrls:[],ignoreApiStatus:[],ignoreResourceUrls:[],maxMessagePerMinute:10,endpoint:"https://fclog.baidu.com/log/weirwood?type=error"},oq="https://dmpstatic.cdn.bcebos.com/weirwood",oV=function(){function e(e){this.options=oH,this._globalContext={env:{},user:{},session_id:""},this._globalKey="fclog.baidu.com/log",this._currentExceptionContext={},this._currentExceptionStartTime=Date.now(),this._behaviors=[],this._lastData=null,this._lastAPIData=null,this._messagesSendLastMinute=0,this._messagesSendEmptyStartTime=Date.now(),this._installed=!1,this._globalErrorHandler=null,this._fetchDefaults={method:"POST",credentials:"include",referrerPolicy:!function(){if(!om())return!1;try{return new Request("pickleRick",{referrerPolicy:"origin"}),!0}catch(e){return!1}}()?"":"origin"},this._wrappedBuiltIns=[],this._requestInfo=null,e&&this.config(e)}return e.prototype.init=function(e){return this.config(e)},e.prototype.config=function(e){this.options=iF(iF({},this.options),e),this.options.sendWindow=this.options.sendWindow||iY(),this._globalContext.session_id=this.options.uuid4();var n=this.options,r=n.token,i=n.buildid;if(!r||!i)throw Error("error: token and buildid must be provided");return this.setFilters(),this.install(),this},e.prototype.install=function(){var e,n=this;return this._installed?(console.error("error: Weirwood Error SDK has been installed and configured"),!1):(this.options.collectWindowErrors&&i8(),this.options.maxMessagePerMinute>=60&&(this.options.maxMessagePerMinute=60),this.options.collectUnhandledRejections&&i9(),this._globalErrorHandler=this._getErrorHandler().bind(this),i5(this._globalErrorHandler),this.options.collectResourceLoadErrors&&(e=function(e){if(window.performance&&window.performance.getEntriesByName){var r,i=window.performance.getEntriesByName(e.asset);i.length>0&&(r=i[0],["name","serverTiming"].forEach(function(e){delete r[e]}))}var o={mechanism:e.type,name:"ResourceError",message:e.asset,stack:[],mode:"onerror",timing:r,page:e.page,element:e.element,elementPath:e.path.slice(0,255)};n._handleStackInfo(o,{trimHeadFrames:0,mechanism:o.mechanism||"generic",includePaths:n.options.includePaths})},window.addEventListener("error",function(n){if(n&&n.target&&n.target!==window){var r,i=n.target,o=null!=(r=null==i?void 0:i.tagName)?r:"unknown tagname";if(-1!==["SCRIPT","LINK","IMG"].indexOf(o)){var s=i.src||i.href,a=window.location.href,c=function(e){for(var n=e.path||[],r="",i=0;i<n.length;i++){var o=n[i];if(o===window){r+="Window";continue}r+=o.nodeName,r+=o.id?"#"+o.id:"",r+=o.className?"."+o.className.split(" ").join("."):"",i<n.length&&(r+=" > ")}return r}(n),l={type:o,asset:of(s)===of(a)?"空资源":s,integrity:i.integrity,element:i&&i.outerHTML&&i.outerHTML.replace(/"/g,""),path:c.replace(/"/g,""),page:window.location.href.slice(0,255)};e&&e(l)}}},!0)),this._installed=!0,this.installPlugins(),this)},e.prototype.installPlugins=function(){var e,n;this.options.plugins=iH([new oN(this.options.behaviorOptions),new oD(this.options.tryCatchOptions),new oU],this.options.plugins||[]);try{for(var r=iU(this.options.plugins),i=r.next();!i.done;i=r.next())i.value.setupOnce(this)}catch(n){e={error:n}}finally{try{i&&!i.done&&(n=r.return)&&n.call(r)}finally{if(e)throw e.error}}},e.prototype.setFilters=function(){var e=this.options;e.ignoreErrors&&(e.ignoreErrors=iH([/^Script error\.?$/,/^Javascript error: Script error\.? on line 0$/,'{"isTrusted":true}','{"isTrusted":false}',"Network Error","ResizeObserver loop"],e.ignoreErrors||[])),e.ignoreJsUrls=iH(["chrome-extension","safari-extension","moz-extension",oq],e.ignoreJsUrls||[])},e.prototype._getErrorHandler=function(){var e=this;return function(n,r,i,o,s,a){if(i&&(i.stack||i.stacktrace)&&(n.originalStack=((i.stack||i.stacktrace)+"").slice(0,1e4)),n.stack&&!n.stack.length&&o&&(n.stack[0]={url:o,line:s,column:a}),!n.name&&!n.message&&"onunhandledrejection"===n.mechanism){var c=iY();n.name="unhandledrejection",n.url=n.url||c.location.href,n.message=i}e._handleStackInfo(n,{trimHeadFrames:0,mechanism:n.mechanism||"generic",includePaths:e.options.includePaths})}},e.prototype._handleStackInfo=function(e,n){var r=ox(e,n,this.options.stackTraceLimit);this._processException(e,r,n)},e.prototype._processException=function(e,n,r){var i=this.options,o=i.ignoreErrors,s=void 0===o?[]:o,a=i.ignoreKeys,c=void 0===a?[]:a,l=i.whitelistUrls,u=void 0===l?[]:l,d=i.resourceWhitelistUrls,p=void 0===d?[]:d,h=i.ignoreUrls,f=void 0===h?[]:h,m=i.ignoreJsUrls,g=void 0===m?[]:m,v=i.ignoreResourceUrls,y=void 0===v?[]:v,b=e.name,w=e.message,O=e.url,_=void 0===O?"":O,R=e.page,S=void 0===R?window.location.href:R,T=e.lineno,E=e.originalStack;if(!(s.length&&oE(s,w)||f.length&&oE(f,S))){var M=n&&n.length&&n[0].filename||_;if("ResourceError"===b){if(y.length&&oE(y,w)||p.length&&!oE(p,w))return}else if(c.length&&oE(c,b)||g.length&&oE(g,M)||u.length&&!oE(u,M))return;if(n&&n.length>0){var x=n[0].filename||"",C=-1!==x.indexOf("@baidu/weirwood-error"),j=-1!==x.indexOf(oq);if(C||j)return}if(-1===M.indexOf(oq)){var I,B=(I=void 0===T?0:T,n&&n.length?n.reverse():_?[{filename:_,lineno:I||0,in_app:!0}]:[]),k=iF(iF({},r),{exception:{type:b,value:w,originalStack:void 0===E?"":E,stacktrace:B,url:"ResourceError"===b?w:M,page:e.page,element:e.element,timing:e.timing,elementPath:e.elementPath}}),A=k.exception;null==A.type&&""===A.value&&(A.value="Unrecoverable error caught"),!k.exception.mechanism&&k.mechanism&&(k.exception.mechanism=k.mechanism,delete k.mechanism),this._send(k)}}},e.prototype.mergeGlobalContext=function(e){var n,r,i,o=iY();e.env=iF(iF(iF({},this._globalContext.env),e.env),{network:null==(i=o.navigator.connection)?void 0:i.effectiveType,windowHeight:(o.document.documentElement||o.document.body).clientHeight,windowWidth:(o.document.documentElement||o.document.body).clientWidth,documentTitle:o.document.title});try{for(var s=iU(Object.keys(this._currentExceptionContext)),a=s.next();!a.done;a=s.next()){var c=a.value;e.env[c]=this._currentExceptionContext[c]}}catch(e){n={error:e}}finally{try{a&&!a.done&&(r=s.return)&&r.call(s)}finally{if(n)throw n.error}}e.env["session:duration"]=Date.now()-this._currentExceptionStartTime,this._globalContext.user&&(e.user=this._globalContext.user),this._globalContext.session_id&&(e.session_id=this._globalContext.session_id)},e.prototype._send=function(e){var n={request:this._requestInfo};if(iX(e.trimHeadFrames)||delete e.trimHeadFrames,e=iF(iF({},n),e),this.mergeGlobalContext(e),this._behaviors&&this._behaviors.length>0){var r=[].slice.call(this._behaviors,0);this.options.behaviorDataCallback&&(r=this.options.behaviorDataCallback(r)),e.behaviors=r}var i=this.options;if(i.token&&(e.token=i.token),i.buildid&&(e.buildid=i.buildid),Object.keys(e=this._sanitizeData(e)).forEach(function(n){(null==e[n]||""===e[n]||iK(e[n]))&&delete e[n]}),iW(i.dataCallback)&&(e=i.dataCallback(e)),!(!e||iK(e))){var o=Date.now()-this._messagesSendEmptyStartTime,s=this._messagesSendLastMinute>this.options.maxMessagePerMinute;if(o<6e4){if(s)return}else this._messagesSendEmptyStartTime=Date.now(),this._messagesSendLastMinute=1;"number"==typeof i.sampleRate?Math.random()<i.sampleRate&&(this._sendProcessedPayload(e),this._messagesSendLastMinute+=1):(this._sendProcessedPayload(e),this._messagesSendLastMinute+=1)}},e.prototype.isSetup=function(){return this._installed},e.prototype._trimPacket=function(e){var n,r,i=this.options.maxUrlLength||0,o=this.options.maxMessageLength||0;if(e.exception&&(e.exception.value=oO(e.exception.value,o)),e.request){var s=iY();e.request.url=oO(s.location.href,i);var a=e.request.headers.Referrer;e.request.headers.Referrer=oO(a,i)}if(e.behaviors&&e.behaviors.length){var c=["url","to","from"];try{for(var l=iU(e.behaviors),u=l.next();!u.done;u=l.next()){var d=u.value;!function(e){var n=e.data||{},r=function(e){n.hasOwnProperty(e)&&c.forEach(function(r){e===r&&(n[e]=oO(n[e],i))})};for(var o in n)r(o)}(d)}}catch(e){n={error:e}}finally{try{u&&!u.done&&(r=l.return)&&r.call(l)}finally{if(n)throw n.error}}}return e},e.prototype._sendProcessedPayload=function(e,n){var r,i=this,o=this.options;if(e=this._trimPacket(e),!this.options.allowDuplicates&&this._isRepeatData(e))return void console.warn("Weirwood error SDK dropped repeat event:",e);var s=o.issueGroupby;s&&iW(s)&&(r=s(e.exception)),r&&i$(r)?(e.fingerprint=r.substr(0,255),e.event_id=oh(e.fingerprint)):e.event_id=oh(oR(e)),e.data_id=oh(function(e){var n=oR(e),r=[],i=e.request,o=e.env,s=e.behaviors;if(!i)return JSON.stringify(e);var a=i.headers,c=i.url;return r.push("Referrer="+a.Referrer),r.push("ua="+a["User-Agent"]),r.push("url="+c),oy(o,function(e,n){"session:duration"!==e&&r.push(e+"="+n)}),oy(s,function(e){r.push("behavior.category="+e.category),r.push("behavior.name="+e.name),r.push("behavior.message="+e.message)}),n+r.join("***")}(e)),e.version=this.options.version||"",e.sdkTimestamp=Date.now(),this._lastData=e;var a={weirwood_version:this.options.version||""};(o.transport||this._makeRequest).call(this,{url:this.options.endpoint,auth:a,data:e,options:o,onSuccess:function(){i._resetBackoff(),n&&n()},onError:function(e){e.request&&i._setBackoffState(e.request),e=e||Error("Raven send failed (no additional details provided)"),n&&n(e)}})},e.prototype._makeRequest=function(e){var n,r,i=this,o=e.url,s=null,a={};e.options.headers&&(s=ob(e.options.headers)),e.options.fetchParameters&&(a=ob(e.options.fetchParameters));var c=this.options.sendWindow;if(om()){a.body=ov(e.data);var l=iF(iF({},this._fetchDefaults),a);if(s){var u=new Headers;try{for(var d=iU(Object.keys(s)),p=d.next();!p.done;p=d.next()){var h=p.value;u.append(h,s[h])}}catch(e){n={error:e}}finally{try{p&&!p.done&&(r=d.return)&&r.call(d)}finally{if(n)throw n.error}}u.append("Content-Type","text/plain"),l.headers=u}return c.fetch(o,l).then(function(n){if(n.ok)e.onSuccess&&e.onSuccess(),i._resetBackoff();else{var r=Error("Weirwood error SDK error code: "+n.status);r.request=n,e.onError&&e.onError(r)}}).catch(function(){e.onError&&e.onError(Error("Weirwood error SDK error code: network unavailable")),i._resetBackoff()})}var f=c.XMLHttpRequest&&new c.XMLHttpRequest;f&&("withCredentials"in f||"undefined"!=typeof XDomainRequest)&&("withCredentials"in f?f.onreadystatechange=function(){if(4!==f.readyState)return void i._resetBackoff();if(200===f.status)e.onSuccess&&e.onSuccess();else if(e.onError){i._resetBackoff();var n=Error("Weirwood error SDK error code: "+f.status);n.request=f,e.onError(n)}}:(f=new XDomainRequest,o=o.replace(/^https?:/,""),e.onSuccess&&(f.onload=e.onSuccess),e.onError&&(f.onerror=function(){var n=Error("Weirwood error SDK error code: XDomainRequest");n.request=f,e.onError(n)})),f.open("POST",o),s&&oy(s,function(e,n){f.setRequestHeader(e,n)}),f.send(ov(e.data)))},e.prototype._sanitizeData=function(e){var n=this.options.sanitizeKeys||[];if(n.length){if(!Array.isArray(n)||Array.isArray(n)&&0===n.length)return e;var r,i=oT(n);try{r=JSON.parse(ov(e))}catch(n){return e}return function e(n){return Array.isArray(n)?n.map(function(n){return e(n)}):iJ(n)?Object.keys(n).reduce(function(r,o){return i.test(o)?r[o]="********":r[o]=e(n[o]),r},{}):n}(r)}return e},e.prototype.captureUserAgent=function(e){this._requestInfo=e},e.prototype.captureException=function(e,n){if(n||(n={trimHeadFrames:0,includePaths:[],mechanism:"generic",message:""}),iq(e));else if(iV(e))e=e.error;else if(iJ(e))e=Error((n=this._getCaptureExceptionOptionsFromPlainObject(n,e)).message);else{if(r=e,"[object DOMException]"!==Object.prototype.toString.call(r))return this.captureMessage(e,iF(iF({},n),{stacktrace:!0,trimHeadFrames:n.trimHeadFrames+1}));var r,i=e.name||"DOMException",o=e.message?i+": "+e.message:i;return this.captureMessage(o,n)}try{n=iF({trimHeadFrames:0,mechanism:"generic",includePaths:this.options.includePaths||[]},n);var s=i7(e);this._handleStackInfo(s,n)}catch(n){if(e!==n)throw n}return this},e.prototype._isRepeatData=function(e){var n=this._lastData,r=e.exception,i=n?n.exception:{};return r.mechanism===i.mechanism&&r.type===i.type&&r.value===i.value&&r.url===i.url&&(0===r.stacktrace.length&&0===i.stacktrace.length||function(e,n){if(oS(e)&&oS(n)){var r,i,o=e.length;if(o!==n.length)return!1;for(var s=0;s<o;s++){if(r=e[s],i=n[s],r.filename!==i.filename||r.lineno!==i.lineno||r.colno!==i.colno||r.function!==i.function)return!1}return!0}return!1}(r.stacktrace,i.stacktrace))},e.prototype._resetBackoff=function(){this._currentExceptionStartTime=Date.now(),this._currentExceptionContext={}},e.prototype._setBackoffState=function(e){console.log(e)},e.prototype.captureMessage=function(e,n){void 0===n&&(n={});var r,i,o=this.options,s=o.ignoreErrors||[],a=o.ignoreKeys||[],c=o.whitelistUrls||[],l=o.ignoreUrls||[],u=o.ignoreJsUrls||[];if(!(s.length&&oE(s,e))){try{throw Error(e)}catch(e){i=e}var d=i7(i),p=Array.isArray(d.stack)&&d.stack[1];(null==(r=null==p?void 0:p.func)?void 0:r.indexOf("captureException"))!==-1&&(p=d.stack[2]);var h=p&&p.url||"";if(!(l.length&&oE(l,window.location.href)||a.length&&oE(a,i.name)||u.length&&oE(u,h))&&(!c.length||oE(c,h))){n=iF(iF({},n),{trimHeadFrames:0,includePaths:o.includePaths}),n.trimHeadFrames+=1;var f=ox(d,n),m={exception:{mechanism:"manual",type:i.name,value:i.message,stacktrace:f.slice(1).reverse(),url:h}};return this._send(m),this}}},e.prototype.captureAPIException=function(e){var n,r=this,i=iY(),o=this.options,s=o.ignoreUrls,a=void 0===s?[]:s,c=o.ignoreApiUrls,l=void 0===c?[]:c,u=o.ignoreApiStatus,d=void 0===u?[]:u,p=o.buildid,h=o.token,f=o.version,m=o.apiWhitelistUrls;if(!(e.url&&e.method&&!iX(e.status)))return void console.error("API异常参数至少需要包含 method、url、status 参数。");if(!(a.length&&oE(a,i.location.href)||l.length&&oE(l,e.url))&&(!m.length||oE(m,e.url))&&(!d.length||-1===d.indexOf(Number(e.status)))){var g=iF(iF({},e),{type:"APIError"}),v={request:{headers:{"User-Agent":i.navigator.userAgent},url:i.location.href},exception:g,buildid:p,token:h,version:f||""},y=this.options;if(iW(y.dataCallback)&&(v=y.dataCallback(v)),!(!v||iK(v))){this.mergeGlobalContext(v);var b=this.options.issueGroupby;if((b&&iW(b)&&(n=b(v.exception)),n&&i$(n))?(v.fingerprint=n.substr(0,255),v.event_id=oh(v.fingerprint)):v.event_id=oh(e.method+"***"+function(e){if(!i$(e))return"";var n=e.split("?");return n[1]?(n[1]=n[1].replace(/\d+/g,"*").replace(/[\u4e00-\u9fa5]+/gi,"*"),n.join("?")):e}(e.url)),v.data_id=oh(ov(v)),this._lastAPIData!==v.data_id){this._lastAPIData=v.data_id;var w=function(){var e;((null==(e=r.options.globalOptions)?void 0:e.transport)||r._makeRequest).call(r,{url:r.options.endpoint,data:v,options:{},onSuccess:function(){},onError:function(){}})};"number"==typeof y.sampleRate?Math.random()<y.sampleRate&&w():w()}}}},e.prototype.captureEvent=function(){},e.prototype.afterLoad=function(){var e=iY().RavenConfig;e&&this.init(e)},e.prototype._getCaptureExceptionOptionsFromPlainObject=function(e,n){var r=Object.keys(n).sort(),i=iF(iF({},e),{message:"Non-Error exception captured with keys: "+function(e,n){if(void 0===n&&(n=40),iz(e)||i$(e))return e.toString();if(!iG(e))return"";if(0===(e=e.filter(function(e){return i$(e)})).length)return"[object has no keys]";if(n=iz(n)?n:40,e[0].length>=n)return e[0];for(var r=e.length;r>0;r--){var i=e.slice(0,r).join(", ");if(!(i.length>n)){if(r===e.length)return i;return i+"…"}}return""}(r),fingerprint:[oh(r.join(""))],env:e&&e.env||{}});return i.env.__serialized__=function e(n,r,i){if(void 0===r&&(r=3),void 0===i&&(i=51200),!iJ(n))return n+"";var o=function e(n,r){return 0===r?ow(n):iJ(n)?Object.keys(n).reduce(function(i,o){return i[o]=e(n[o],r-1),i},{}):Array.isArray(n)?n.map(function(n){return e(n,r-1)}):ow(n)}(n,r);return~-encodeURI(JSON.stringify(ov(o))).split(/%..|./).length>i?e(n,r-1):o}(n),i},e.prototype.captureBehavior=function(e){var n=iF(iF({},e),{timestamp:Date.now()/1e3});if(iW(this.options.breadcrumbCallback)){var r=this.options.breadcrumbCallback(n);if("object"!=typeof r||null===r||iK(r)){if(!1===r)return this}else n=r}return this._behaviors.push(n),this._behaviors.length>(this.options.behaviorLimit||10)&&this._behaviors.shift(),this},e.prototype.setContext=function(e,n){for(var r in void 0===n&&(n={persist:!0}),e)Reflect.has(e,r)&&(n.persist?this._globalContext.env[r]=e[r]:this._currentExceptionContext[r]=e[r])},e.prototype.clearContext=function(){this._globalContext.env={},this._currentExceptionContext={}},e.prototype._restoreBuiltIns=function(){for(var e;this._wrappedBuiltIns.length;){var n=(e=this._wrappedBuiltIns.shift())[0],r=e[1],i=e[2];n[r]=i}},e.prototype.noConflict=function(){},e.prototype.uninstall=function(){this.dispose()},e.prototype.dispose=function(){i4(this._globalErrorHandler),this._restoreBuiltIns(),this._globalErrorHandler=null,this._installed=!1},e}(),oX={};function oW(){var e=window.crypto||window.msCrypto;if(void 0===e||!e.getRandomValues)return"xxxxxxxxxxxx4xxxyxxxxxxxxxxxxxxx".replace(/[xy]/g,function(e){var n=16*Math.random()|0;return("x"===e?n:3&n|8).toString(16)});var n=new Uint16Array(8);e.getRandomValues(n),n[3]=4095&n[3]|16384,n[4]=16383&n[4]|32768;var r=function(e){for(var n=e.toString(16);n.length<4;)n="0"+n;return n};return r(n[0])+r(n[1])+r(n[2])+r(n[3])+r(n[4])+r(n[5])+r(n[6])+r(n[7])}var o$=function(){function e(e){this.version="1.3.15",this.lastRouteTime=0,e&&this.init(e)}return e.prototype.init=function(e){var n,r,i,o,s=this.getSendWindow();if(!e.perf||e.perf&&!e.perf.disable){var a=iL(iL(iL({},e.perf),e.common),{version:this.version,sendWindow:s});this.perf=new iD.PerfClient(a)}if(!e.error||e.error&&!e.error.disable){var c=iL(iL(iL({},e.error),e.common),{version:this.version,sendWindow:s,uuid4:oW});this.error=new oV(c)}this.routeChange(window.document.URL),n=this.routeChange.bind(this),"function"==typeof(r=window.history).pushState&&(i=r.pushState,r.pushState=function(e,r,o){return n(o),i.apply(this,arguments)}),"function"==typeof r.replaceState&&(o=r.replaceState,r.replaceState=function(e,r,i){return i!==window.document.URL&&n(i),o.apply(this,arguments)}),window.addEventListener("hashchange",function(e){n((e||{}).newURL)}),window.addEventListener("popstate",function(e){n(window.document.URL)})},e.prototype.routeChange=function(e){var n=new Date().getTime();if(n-this.lastRouteTime>100){this.lastRouteTime=n;var r=oW()+"-"+n;this.error&&this.error.setContext({pageId:r})}},e.prototype.getSendWindow=function(){var e="undefined"!=typeof window?window:void 0!==et.g?et.g:"undefined"!=typeof self?self:oX;if(["fetch","ajax","sendBeacon"].some(function(e){var n;return!((n=window[e])&&n.toString&&!n.hasOwnProperty("toString")&&/\[native code\]/.test(String(n)))})&&document.body){var n=document.createElement("iframe");n.style.setProperty("display","none","important"),document.body.appendChild(n),e=n?n.contentWindow:e}return e},e.prototype.afterLoad=function(){},e}();function oz(e,n){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,n)}function oG(e,n){return function(r,i){n(r,i,e)}}(T=(S=F||(F={})).EMessageType||(S.EMessageType={}))[T.Query=0]="Query",T[T.Event=1]="Event";class oJ{constructor(e,n,r){this.opts=e,this.signalingService=n,this.errorManager=r,this.disabled=!1,this.mutedByUser=!1,this.muted=!1,this.emitter=new nl,this.started=!1,this.mute=e=>{this.signalingService.Mute(e),this.muted=e},this.setMutedByUser=e=>{this.mutedByUser=e},this.tryUnmuteAsr=()=>!this.disabled&&!this.mutedByUser&&(this.muted&&this.mute(!1),!0),this.disable=()=>{this.disabled=!0},this.enable=()=>{this.disabled=!1},this._stop=async()=>{this.started&&(await this.signalingService.Stop(),this.started=!1)},this._dispose=()=>{this.stop().finally(()=>{this.signalingService.Dispose()}).catch(rI),this.emitter.clearListeners()},this._ensureMicPermission=async()=>{var e;if("function"==typeof(null==(e=navigator.permissions)?void 0:e.query)){try{switch((await navigator.permissions.query({name:"microphone"})).state){case"granted":case"prompt":break;case"denied":this.errorManager.handleError(new n7("麦克风权限被浏览器/系统禁用,请检查后重试"))}}catch{await this._ensureMicPermissionPolyfill()}return}await this._ensureMicPermissionPolyfill()},this._ensureMicPermissionPolyfill=async()=>{try{(await navigator.mediaDevices.getUserMedia({audio:!0})).getTracks().forEach(e=>e.stop())}catch(e){e instanceof Error&&("NotAllowedError"===e.name||"SecurityError"===e.name?this.errorManager.handleError(new n7(`\u{7528}\u{6237}\u{62D2}\u{7EDD}\u{9EA6}\u{514B}\u{98CE}\u{6743}\u{9650}: ${e.message}`)):"NotFoundError"===e.name?this.errorManager.handleError(new n7(`\u{672A}\u{68C0}\u{6D4B}\u{5230}\u{9EA6}\u{514B}\u{98CE}\u{8BBE}\u{5907}: ${e.message}`)):this.errorManager.handleError(new n7(e.message)))}}}get sessionId(){return this.started?this.signalingService.GetSessionID():null}}function oK(e,n){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,n)}function oQ(e,n){return function(r,i){n(r,i,e)}}oJ=function(e,n,r,i){var o,s=arguments.length,a=s<3?n:null===i?i=Object.getOwnPropertyDescriptor(n,r):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)a=Reflect.decorate(e,n,r,i);else for(var c=e.length-1;c>=0;c--)(o=e[c])&&(a=(s<3?o(a):s>3?o(n,r,a):o(n,r))||a);return s>3&&a&&Object.defineProperty(n,r,a),a}([eV(),oG(0,eU(nd.IOptions)),oG(0,ez()),oG(1,eU(nd.SignalingService)),oG(2,eU(nd.ErrorManager)),oz("design:type",Function),oz("design:paramtypes",["undefined"==typeof IResolvedOptions?Object:IResolvedOptions,"undefined"==typeof BaseSignalingService?Object:BaseSignalingService,void 0===rb?Object:rb])],oJ);class oY{static #k=this.GET_ACCESS_TOKEN_REQUEST_URI="employee-console/v1/access/r/ai-agent/get_digital_token";constructor(e,n,r){this.opts=e,this.request=n,this.errorManager=r,this.emitter=new nl,this._isRendering=!1,this._isMuted=!1,this._canInterrupt=!0,this.ssmlHandlers=[],this.token="",this.getAccessToken=async()=>{try{let{data:e}=await this.request.client.get(oY.GET_ACCESS_TOKEN_REQUEST_URI,{retry:3,timeout:15e3}).json();return e.authorization}catch(e){throw e instanceof Error&&this.errorManager.handleError(new rl(e.message)),e}}}get isRendering(){return this._isRendering}get isMuted(){return this._isMuted}get canInterrupt(){return this._canInterrupt}setIsRendering(e){this._isRendering=e}setIsMuted(e){this._isMuted=e}setCanInterrupt(e){this._canInterrupt=e}registerSSMLHandler(e){return this.ssmlHandlers.push(e),this}runSsmlHandlers(e){let n=e;for(let e of this.ssmlHandlers)n=e(n);return n}}oY=function(e,n,r,i){var o,s=arguments.length,a=s<3?n:null===i?i=Object.getOwnPropertyDescriptor(n,r):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)a=Reflect.decorate(e,n,r,i);else for(var c=e.length-1;c>=0;c--)(o=e[c])&&(a=(s<3?o(a):s>3?o(n,r,a):o(n,r))||a);return s>3&&a&&Object.defineProperty(n,r,a),a}([eV(),oQ(0,eU(nd.IOptions)),oQ(1,eU(nd.CommonRequest)),oQ(2,eU(nd.ErrorManager)),oK("design:type",Function),oK("design:paramtypes",["undefined"==typeof IOptions?Object:IOptions,void 0===nX?Object:nX,void 0===rb?Object:rb])],oY);let oZ=function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:500;return new Promise(n=>setTimeout(n,e))};function o0(e,n){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);n&&(i=i.filter(function(n){return Object.getOwnPropertyDescriptor(e,n).enumerable})),r.push.apply(r,i)}return r}function o1(e){for(var n=1;n<arguments.length;n++){var r=null!=arguments[n]?arguments[n]:{};n%2?o0(Object(r),!0).forEach(function(n){o4(e,n,r[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):o0(Object(r)).forEach(function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(r,n))})}return e}function o2(e){return(o2="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(e)}function o3(e,n){if(!(e instanceof n))throw TypeError("Cannot call a class as a function")}function o6(e,n){for(var r=0;r<n.length;r++){var i=n[r];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(e,o8(i.key),i)}}function o5(e,n,r){return n&&o6(e.prototype,n),r&&o6(e,r),Object.defineProperty(e,"prototype",{writable:!1}),e}function o4(e,n,r){return(n=o8(n))in e?Object.defineProperty(e,n,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[n]=r,e}function o8(e){var n=function(e,n){if("object"!=typeof e||null===e)return e;var r=e[Symbol.toPrimitive];if(void 0!==r){var i=r.call(e,n||"default");if("object"!=typeof i)return i;throw TypeError("@@toPrimitive must return a primitive value.")}return("string"===n?String:Number)(e)}(e,"string");return"symbol"==typeof n?n:String(n)}(U||(U={})).INIT="INIT";var o9=function(){function e(n){o3(this,e),o4(this,"iframeId",void 0),this.iframeId=n}return o5(e,[{key:"registerMessageReceived",value:function(e){void 0!==window.addEventListener&&"function"==typeof e&&window.addEventListener("message",e,!1)}},{key:"removeMessageReceived",value:function(e){void 0!==window.addEventListener&&window.removeEventListener("message",e,!1)}},{key:"sendMessageToIframe",value:function(e,n){if(this.iframeId){var r=document.getElementById(this.iframeId);e&&null!==r&&r.contentWindow.postMessage({type:e,content:n},"*")}else if(window.self!==window.top&&window&&window.parent&&window.parent.postMessage){var i=JSON.parse(JSON.stringify(n||{}));window.parent.postMessage({type:e,content:i},"*")}}},{key:"sendCommand",value:function(e){this.sendMessageToIframe("command",e)}},{key:"sendMessage",value:function(e){var n=e.requestId,r=void 0===n?rC():n;return this.sendMessageToIframe("message",o1(o1({},e),{},{requestId:r})),r}},{key:"textRender",value:function(e){return this.sendMessage({action:"TEXT_RENDER",body:e})}},{key:"textQuery",value:function(e){return this.sendMessage({action:"TEXT_QUERY",body:e})}},{key:"changeBackGround",value:function(e){return this.textRender("<display><background><type>image</type><source>http</source><value>".concat(e,"</value></background></display>"))}},{key:"mute",value:function(e){this.sendCommand({subType:"mute",subContent:e})}},{key:"muteAudio",value:function(e){this.sendCommand({subType:"muteAudio",subContent:e})}},{key:"muteRemoteAudio",value:function(e){this.sendCommand({subType:"muteRemoteAudio",subContent:e})}},{key:"playVideo",value:function(e){this.sendCommand({subType:"playVideo",subContent:e})}},{key:"sendAudioData",value:function(e){this.sendMessageToIframe("audioData",e)}},{key:"onStateUpdate",value:function(e){this.sendMessageToIframe("state",e)}},{key:"sendRtcState",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.sendMessageToIframe("rtcState",e)}},{key:"sendWsState",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.sendMessageToIframe("wsState",e)}}]),e}();o5(function e(n){o3(this,e),o4(this,"iframeId",void 0),o4(this,"namespace","dhIframeNameSpace"),o4(this,"listener",null),this.iframeId=n},[{key:"onEventListener",value:function(e){var n=this;return function(r){if("object"===o2(r.data))if("onListener"===r.data.type&&r.data.content.listenerId){var i=window[n.namespace][r.data.content.listenerId];null==i||i(r.data.content.data)}else"onListenerRemove"===r.data.type&&r.data.content.listenerId?delete window[n.namespace][r.data.content.listenerId]:r.data.listenerId?e(r.data,function(e){n.sendMessage("onListener",{listenerId:r.data.listenerId,data:e})},function(){n.sendMessage("onListenerRemove",{listenerId:r.data.listenerId})}):e(r.data)}}},{key:"registerMessageReceived",value:function(e){void 0!==window.addEventListener&&"function"==typeof e&&(this.listener=this.onEventListener(e),window.addEventListener("message",this.listener,!1))}},{key:"removeMessageReceived",value:function(){void 0!==window.addEventListener&&this.listener&&(window[this.namespace]=void 0,window.removeEventListener("message",this.listener,!1))}},{key:"sendMessage",value:function(e,n,r){var i=this;if(this.iframeId){var o="";r&&(o=rC(),window[this.namespace]||(window[this.namespace]={}),window[this.namespace][o]=r);var s=document.getElementById(this.iframeId);return e&&null!==s&&s.contentWindow.postMessage({type:e,content:n,listenerId:o},"*"),function(){o&&(window[i.namespace][o]=void 0)}}if(window.self!==window.top&&window&&window.parent&&window.parent.postMessage){var a=JSON.parse(JSON.stringify(n||{}));window.parent.postMessage({type:e,content:a},"*")}}},{key:"textRender",value:function(e,n){return this.sendMessage("TEXT_RENDER",e,n)}},{key:"textMTRender",value:function(e,n){return this.sendMessage("TEXT_MT_RENDER",e,n)}},{key:"audioRender",value:function(e,n){return this.sendMessage("AUDIO_RENDER",e,n)}},{key:"textQuery",value:function(e,n){return this.sendMessage("TEXT_QUERY",e,n)}},{key:"startAudioQuery",value:function(e,n){return this.sendMessage("AUDIO_QUERY_START",e,n)}},{key:"stopAudioQuery",value:function(){return this.sendMessage("AUDIO_QUERY_STOP",{})}},{key:"setModelPackage",value:function(e,n){return this.sendMessage("SET_MODEL_URLS",{urls:e,needInitConfig:n})}},{key:"changeCamera",value:function(e){return this.sendMessage("CHANGE_CAMERA",e)}},{key:"changeParts",value:function(e){return this.sendMessage("CHANGE_PARTS",e)}},{key:"setRenderConfig",value:function(e){return this.sendMessage("SET_RENDER_CONFIG",e)}},{key:"animojiRender",value:function(e,n){return this.sendMessage("ANIMOJI_RENDER",e,n)}},{key:"destroy",value:function(){return this.sendMessage("DESTROY",{})}},{key:"startAudioRender",value:function(e,n){return this.sendMessage("AUDIO_RENDER_START",e,n)}},{key:"stopAudioRender",value:function(){return this.sendMessage("AUDIO_RENDER_STOP",{})}},{key:"interrupt",value:function(){return this.sendMessage("INTERRUPT",{})}},{key:"load",value:function(e){return this.sendMessage("LOAD",e)}},{key:"onStateUpdate",value:function(e){this.sendMessage("state",e)}}]);let o7=e=>new URLSearchParams(Object.entries(e).filter(e=>{let[,n]=e;return null!=n&&""!==n}).reduce((e,n)=>{let[r,i]=n;return e[r]=String(i),e},{})).toString();var se=((H={})[H.Success=0]="Success",H[H.ReachSessionLimit=1004]="ReachSessionLimit",H[H.ResourceNotEnough=3001]="ResourceNotEnough",H),st=((q={})[q.UNINSTANTIATED=-1]="UNINSTANTIATED",q[q.CONNECTING=0]="CONNECTING",q[q.OPEN=1]="OPEN",q[q.CLOSING=2]="CLOSING",q[q.CLOSED=3]="CLOSED",q);class sn extends oY{get ready(){return!!this.iframeController&&!!this.token}constructor(...e){super(...e),this.origin="https://open.xiling.baidu.com",this.iframeId=rC(),this.iframeController=null,this.iframe=null,this.$iframeContainer=null,this.requestId=rC(),this.isWSConnected=!1,this.isRtcReady=!1,this.silenceMessageRequestIds=[],this.isStreamTextRendering=!1,this.wsClosedCount=0,this.mount=async e=>{if(!e)return void this.errorManager.handleError(new ri("容器元素不能为空"));if(this.$iframeContainer=e,this.iframe){e.contains(this.iframe)||e.appendChild(this.iframe);return}this.opts.enableDebugMode&&"development"===this.opts.env&&!this.opts.token?this.token=await this.getAccessToken():this.token=this.opts.token,this.iframe=document.createElement("iframe"),this.applyOptions(),e.appendChild(this.iframe),this.iframeController=new o9(this.iframeId),this.bindEvents()},this.bindEvents=()=>{var e,n;return this.ready&&(null==(e=this.iframe)||e.addEventListener("error",this.onIFrameErrorHandler),null==(n=this.iframeController)||n.registerMessageReceived(this.onMessageHandler)),this},this.unbindEvents=()=>{var e,n;return this.ready&&(null==(e=this.iframe)||e.removeEventListener("error",this.onIFrameErrorHandler),null==(n=this.iframeController)||n.removeMessageReceived(this.onMessageHandler)),this},this.cancelMute=()=>{var e;null==(e=this.iframeController)||e.sendCommand({subType:"muteAudio",subContent:!1}),setTimeout(()=>{this._isMuted=!1},1500)},this.renderPlainText=e=>{var n;if(!this.ready)return this;let r=this.runSsmlHandlers(e);return this.refreshRequestId(),null==(n=this.iframeController)||n.sendMessage({action:"TEXT_RENDER",body:r,requestId:this.requestId}),this},this.renderStreamText=(e,n)=>{var r,i,o;if(!this.ready)return this;let s=this.runSsmlHandlers(e);return n?(this.isStreamTextRendering||this.refreshRequestId(),null==(i=this.iframeController)||i.sendMessage({action:"TEXT_STREAM_RENDER",body:JSON.stringify({first:!this.isStreamTextRendering,last:!0,text:s}),requestId:this.requestId}),this.isStreamTextRendering=!1):this.isStreamTextRendering?null==(r=this.iframeController)||r.sendMessage({action:"TEXT_STREAM_RENDER",body:JSON.stringify({first:!1,last:!1,text:s}),requestId:this.requestId}):(this.refreshRequestId(),this.isStreamTextRendering=!0,null==(o=this.iframeController)||o.sendMessage({action:"TEXT_STREAM_RENDER",body:JSON.stringify({first:!0,last:!1,text:s}),requestId:this.requestId})),this},this.interrupt=()=>{var e;return this.ready&&(null==(e=this.iframeController)||e.sendMessage({action:"TEXT_RENDER",body:"<interrupt></interrupt>",requestId:this.requestId}),this.isRendering||this.onRenderFinished(this.requestId)),this},this.sendSilenceMessage=()=>{var e;if(!this.ready)return this;let n=rC();return null==(e=this.iframeController)||e.sendMessage({action:"TEXT_RENDER",body:"",requestId:n}),this.silenceMessageRequestIds.push(n),this.emitter.emit("send_silence_message",{requestId:n}).catch(rI),this},this.dispose=()=>{if(this.unbindEvents(),this.silenceMessageRequestIds=[],this.ssmlHandlers=[],this.wsClosedCount=0,this.emitter.clearListeners(),this.iframe){var e;null==(e=this.$iframeContainer)||e.removeChild(this.iframe),this.iframe=null,this.iframeController=null}return this},this.GetRequestId=()=>this.requestId,this.checkIsReady=()=>{let e=this.isWSConnected&&this.isRtcReady;return e&&this.emitter.emit("ready").catch(rI),e},this.onIFrameErrorHandler=e=>{let n=new ro(`\u{6570}\u{5B57}\u{4EBA}iframe\u{52A0}\u{8F7D}\u{5931}\u{8D25}: ${e.message}`,{context:{method:"onIFrameErrorHandler",iframeId:this.iframeId,filename:e.filename,lineno:e.lineno,colno:e.colno,type:e.type,target:e.target}});this.errorManager.handleError(n)},this.onMessageHandler=e=>{if(e.origin!==this.origin)return;let n=e.data;switch(n.type){case"msg":this.onReceiveMsgTypedMessageHandler(n);break;case"rtcState":this.onReceiveRtcStateTypedMessageHandler(n);break;case"wsState":this.onReceiveWsStateTypedMessageHandler(n)}},this.onReceiveMsgTypedMessageHandler=e=>{let n=e.content.requestId;if((e.content.code===se.ReachSessionLimit||e.content.code===se.ResourceNotEnough)&&(this.emitter.emit("reach_session_limit",{requestId:n}).catch(rI),this.errorManager.handleError(new ru("资源配额已用尽,请联系技术支持申请扩容"))),["RENDER_START","FINISHED","DOWN_SUBTITLE","RENDER_INTERRUPTED","DOWN_SUBTITLE","TEXT_RENDER","TEXT_STREAM_RENDER"].includes(e.content.action)){if(n!==this.requestId)return;switch(e.content.action){case"RENDER_START":this._isRendering=!0,this.emitter.emit("is_rendering_change",!0).catch(rI);break;case"FINISHED":case"RENDER_INTERRUPTED":this.onRenderFinished(n);break;case"DOWN_SUBTITLE":{let r=JSON.parse(e.content.body);this.silenceMessageRequestIds.includes(n)?this.silenceMessageRequestIds=this.silenceMessageRequestIds.filter(e=>e!==n):this.emitter.emit("render_subtitle",{subtitle:r,requestId:n}).catch(rI);break}case"TEXT_RENDER":case"TEXT_STREAM_RENDER":0!==e.content.code&&this.onRenderFinished(n)}return}switch(e.content.action){case"RENDER_ERROR":this.onRenderFinished(n),this.errorManager.handleError(new rs("数字员工文本驱动渲染失败,请确认配置后重试",{requestId:n,context:{msg:e.content.message}}));break;case"DISCONNECT_ALERT":this.emitter.emit("disconnect_alert",{requestId:n}).catch(rI);break;case"TIMEOUT_EXIT":this.onRenderFinished(n),this.emitter.emit("timeout",{requestId:e.content.requestId}).catch(rI)}},this.onReceiveRtcStateTypedMessageHandler=e=>{e.content.action,"localVideoMuted"===e.content.action&&e.content.body&&(this._isMuted=!0),"remotevideoon"===e.content.action&&(this.isRtcReady=!0,this.checkIsReady(),this.iframe&&(this.iframe.style.opacity="1")),"error"===e.content.action&&this.errorManager.handleError(new rc("RTC 房间连接失败,请检查网络后重试"))},this.onReceiveWsStateTypedMessageHandler=e=>{e.content.readyState===st.OPEN?(this.isWSConnected=!0,this.wsClosedCount=0,this.checkIsReady()):(e.content.readyState===st.CLOSED||e.content.readyState===st.CLOSING)&&(this.isWSConnected=!1),e.content.readyState===st.CLOSED&&(this.wsClosedCount++,this.wsClosedCount>=3&&(this.emitter.emit("reconnect_failed").catch(rI),this.errorManager.handleError(new ra("检测到 Websocket 链接异常断开,如长时间无法恢复,请联系技术支持。"))))},this.applyOptions=()=>{var e,n,r,i,o,s,a,c,l,u,d,p,h,f;if(!this.iframe)return;this.iframe.id=this.iframeId,this.iframe.allow="autoplay",this.iframe.style.border="none",this.iframe.style.opacity="0",this.iframe.style.pointerEvents="none",this.iframe.style.overflow="hidden";let m=null!=(o=null==(e=this.opts)?void 0:e.scaleX)?o:1,g=null!=(s=null==(n=this.opts)?void 0:n.scaleY)?s:1,v=null!=(a=null==(r=this.opts)?void 0:r.translateX)?a:0,y=null!=(c=null==(i=this.opts)?void 0:i.translateY)?c:0;this.iframe.style.width=`${100*m}% `,this.iframe.style.height=`${100*g}%`,this.iframe.style.transform=`translate(${v}px, ${y}px)`;let b=o7({figureId:this.opts.figureId,ttsPer:this.opts.ttsPer,initMode:"noAudio","cp-inactiveDisconnectSec":null!=(l=this.opts.timeoutSec)?l:130,"cp-preAlertSec":null!=(u=this.opts.disconnectAlertSec)?u:10,mode:"crop",resolutionWidth:null!=(d=this.opts.figureResolutionWidth)?d:1920,resolutionHeight:null!=(p=this.opts.figureResolutionHeight)?p:1080,ttsSpeed:null!=(h=this.opts.speechSpeed)?h:6,"cp-ttsSample":this.opts.ttsSample,"cp-minSplitLen":this.opts.minSplitLen,"cp-ttsModel":this.opts.ttsModel,"cp-positionV2":JSON.stringify(this.opts.position),autoChromaKey:this.opts.autoChromaKey,closeLog:null==(f=this.opts.enableDebugMode)||f,token:this.token});this.iframe.src=`${this.origin}/cloud/realtime?${b}`},this.refreshRequestId=()=>{this.requestId=rC()},this.onRenderFinished=e=>{this._isRendering=!1,this.emitter.emit("is_rendering_change",!1).catch(rI),this.refreshRequestId(),this.emitter.emit("render_finished",{requestId:e}).catch(rI)}}}function sr(e,n){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,n)}function si(e,n){return function(r,i){n(r,i,e)}}sn=function(e,n,r,i){var o,s=arguments.length,a=s<3?n:null===i?i=Object.getOwnPropertyDescriptor(n,r):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)a=Reflect.decorate(e,n,r,i);else for(var c=e.length-1;c>=0;c--)(o=e[c])&&(a=(s<3?o(a):s>3?o(n,r,a):o(n,r))||a);return s>3&&a&&Object.defineProperty(n,r,a),a}([eV(),eX()],sn);class so{static #k=this.ENTRY_EMITTER_NAME="AaaSPilotKitEmitter";constructor(e,n,r,i,o,s){this.opts=e,this.errorManager=n,this.agentService=r,this.asrService=i,this.digitalHumanService=o,this.conversationService=s,this.interruptible=!0,this.isRenderingMultiModConversation=!1,this.isDigitalHumanServiceReady=!1,this.isAsrServiceReady=!1,this.aiWorkerMessageCache=null,this.multiModAbortControllers=[],this.playWaitForListener=null,this.mount=async e=>{var n,r;let i=null!=e?e:null==(n=(r=this.opts).getMountContainer)?void 0:n.call(r);i&&(await Promise.all([this.digitalHumanService.mount(i),this.asrService.preloadDeps()]),this.asrService.start(),this.isAsrServiceReady=!0,this.checkServiceReady())},this.getOptions=()=>this.opts,this.checkNeedsManualActivation=()=>n6()||n5(),this.activateManually=async()=>{this.digitalHumanService instanceof sn&&(this.digitalHumanService.cancelMute(),n3()&&(n6()||n5())&&await oZ(500))},this.keepAlive=()=>(this.digitalHumanService.sendSilenceMessage(),this),this.playWaitFor=async(e,n)=>(this.playWaitForListener&&this.digitalHumanService.emitter.off("render_finished",this.playWaitForListener),this.digitalHumanService.isRendering)?await new Promise(r=>{this.playWaitForListener=()=>{if(n&&!n())return void r(!1);this.digitalHumanService.renderPlainText(e),this.playWaitForListener&&this.digitalHumanService.emitter.off("render_finished",this.playWaitForListener),r(!0)},this.digitalHumanService.emitter.on("render_finished",this.playWaitForListener)}):(this.digitalHumanService.renderPlainText(e),!0),this.playFromFullText=e=>(this.digitalHumanService.renderPlainText(e),this),this.playFromStreamText=(e,n)=>(this.digitalHumanService.renderStreamText(e,n),this),this.mute=e=>(this.asrService.setMutedByUser(e),this.emitter.emit("mute",e).catch(rI),e?(this.asrService.mute(!0),this.conversationService.currentClientConversation&&this.query(this.conversationService.currentClientConversation.text,!0).catch(rI)):this.asrService.muted&&this.asrService.mute(!1),this),this.interrupt=()=>(this.interruptAIWorkerConversation(),this),this.playPrologue=()=>{if(this.opts.prologue&&this.opts.prologue.length>0)return void this.playFromFullText(this.opts.prologue);this.agentService.query("").catch(rI)},this.query=async(e,n)=>{if(this.checkServiceReady()){if(this.agentService.sessionId||this.agentService.setSessionId(rC()),this.digitalHumanService.sendSilenceMessage(),this.agentService.queryId||this.agentService.setQueryId(rC()),n){if(this.agentService.checkIsRepeat())return;this.agentService.setLastQueryId(this.agentService.queryId)}if(await this.emitter.emit("asr_message",{text:e,completed:n,id:this.agentService.queryId,sessionId:this.agentService.sessionId}),await this.handleClientConversation(e),n){this.asrService.mute(!0);let n=async()=>{this.agentService.setQueryId(""),this.digitalHumanService.canInterrupt&&(this.asrService.tryUnmuteAsr(),await this.emitter.emit("asr_start"),this.digitalHumanService.emitter.off("render_subtitle",n))};this.digitalHumanService.emitter.on("render_subtitle",n);let r=async()=>{this.agentService.setQueryId(""),this.asrService.tryUnmuteAsr(),await this.emitter.emit("asr_start"),this.digitalHumanService.emitter.off("render_finished",r)};this.digitalHumanService.emitter.on("render_finished",r),this.handleClientConversationCompleted(),await this.agentService.query(e)}}},this.input=e=>(this.digitalHumanService.isRendering&&!this.interruptible||this.query(e,!0).catch(rI),this),this.dispose=()=>(this.agentService.dispose(),this.asrService.dispose(),this.digitalHumanService.dispose(),this.conversationService.dispose(),this.emitter.clearListeners(),this.isDigitalHumanServiceReady=!1,this.isAsrServiceReady=!1,this.aiWorkerMessageCache=null,this.isRenderingMultiModConversation=!1,this.multiModAbortControllers=[],this),this.setInterruptible=e=>(this.interruptible=e,this),this.bindAsrServiceEvents=()=>{this.asrService.emitter.on("start",this.handleAsrServiceStarted),this.asrService.emitter.on("message",this.handleAsrMessage)},this.bindAgentServiceEvents=()=>{this.agentService.emitter.on("data",this.handleAgentAnswer),this.agentService.emitter.on("completed",this.handleAgentAnswerCompleted),this.agentService.emitter.on("instruction_received",this.handleAgentInstructionReceived),this.agentService.emitter.on("usage_quota_reached",async e=>{await this.emitter.emit("busy",{...e})})},this.bindDigitalHumanServiceEvents=()=>{this.digitalHumanService.bindEvents(),this.digitalHumanService.emitter.once("ready").then(()=>{this.isDigitalHumanServiceReady=!0,this.checkServiceReady()}),this.digitalHumanService.emitter.on("render_subtitle",this.aiWorkerSubtitleToConversation),this.digitalHumanService.emitter.on("is_rendering_change",e=>{this.emitter.emit("is_rendering_change",e).catch(rI)}),this.digitalHumanService.emitter.on("render_subtitle",async e=>{await this.emitter.emit("render_start",{...e,sessionId:this.agentService.sessionId,queryId:this.agentService.queryId})}),this.digitalHumanService.emitter.on("disconnect_alert",e=>{let n=this.digitalHumanService.emitter.on("render_finished",()=>{this.asrService.mute(!0),this.emitter.emit("inactivity",e).catch(rI),n()}),r=this.digitalHumanService.emitter.on("send_silence_message",()=>{n(),r()});this.playFromFullText(this.opts.inactivityPrompt)}),this.digitalHumanService.emitter.on("reach_session_limit",async e=>{this.isDigitalHumanServiceReady&&this.isAsrServiceReady&&await this.emitter.emit("busy",{...e})}),this.digitalHumanService.emitter.on("reconnect_failed",async()=>{await this.emitter.emit("busy",{requestId:"reconnect_failed"})});let e=this.digitalHumanService.emitter.on("render_finished",()=>{this.asrService.tryUnmuteAsr(),e()})},this.bindErrorEvents=()=>{this.errorManager.on(e=>{let n=this.errorManager.createMonitoringError(e);this.emitter.emit("error",e).catch(rI);try{this.weirwood.error.captureException(n)}catch(e){console.error(e)}})},this.bindEvents=()=>{this.bindErrorEvents(),this.bindAsrServiceEvents(),this.bindAgentServiceEvents(),this.bindDigitalHumanServiceEvents()},this.registerFormatters=()=>{var e,n;let r=null!=(e=this.opts.speechFormatters)?e:[],i=null!=(n=this.opts.conversationFormatters)?n:[];for(let e of r)this.digitalHumanService.registerSSMLHandler(e);for(let e of i)this.conversationService.registerAIWorkerConversationFormatter(e)},this.aiWorkerSubtitleToConversation=async e=>{let n=e.subtitle;if(this.isRenderingMultiModConversation)return;let r=this.conversationService;await this.createNewAIWorkerConversation();let i=r.currentAIWorkerConversation;i&&this.handleAIWorkerConversationChange(i);let o=r.runAIWorkerConversationFormatters(n.content);null==i||i.appendText(o),n.completed&&r.setCurrentConversation(null)},this.handleAgentAnswer=e=>{let{answer:n}=e;if(ix.isXml(n))return void this.handleXmlAgentAnswer(e).catch(rI);this.aiWorkerMessageCache&&this.playFromStreamText(this.aiWorkerMessageCache,!1),this.aiWorkerMessageCache=n},this.handleXmlAgentAnswer=async e=>{let{answer:n}=e,r=this.conversationService;await this.createNewAIWorkerConversation();let i=r.currentAIWorkerConversation;if(!i)return;let o=()=>{this.emitter.emit("conversation_change",{...i.toJSON(),text:i.fulltext,completed:!1})};i.emitter.on("content_change",o),this.isRenderingMultiModConversation=!0;let s=r.runAIWorkerConversationFormatters(n),a=i.createContentsFromXmlString(s),c=new AbortController;for(let e of(this.multiModAbortControllers.push(c),a)){if(c.signal.aborted){i.emitter.off("content_change",o);break}if(iC.isTextContent(e)){let n=e.getConfig().content;this.playFromFullText(n),await this.digitalHumanService.emitter.once("render_subtitle")}i.addContentRenderTask(e),i.contents.push(e),await i.emitter.once("queue_empty")}this.isRenderingMultiModConversation=!1,i.emitter.off("content_change",o),await this.emitter.emit("conversation_change",{...i.toJSON(),text:i.fulltext,completed:!0})},this.createNewAIWorkerConversation=async()=>{let e=this.conversationService;if(!e.currentAIWorkerConversation){let n=iC.create(this.opts);e.setCurrentConversation(n),e.add(n),await this.emitter.emit("conversation_add",n)}},this.handleAgentAnswerCompleted=async()=>{if(this.aiWorkerMessageCache){this.playFromStreamText(this.aiWorkerMessageCache,!0),this.aiWorkerMessageCache=null;return}this.agentService.setQueryId(""),this.asrService.tryUnmuteAsr(),await this.emitter.emit("asr_start")},this.handleAgentInstructionReceived=e=>{this.emitter.emit("instruction_received",e).catch(rI)},this.handleAsrServiceStarted=async()=>{await oZ(800),this.asrService.mute(!0),this.interruptible&&this.emitter.once("render_start").then(()=>{this.asrService.tryUnmuteAsr()})},this.handleAsrMessage=async e=>{this.digitalHumanService.isRendering&&!this.digitalHumanService.canInterrupt||this.asrService.mutedByUser||e.type===F.EMessageType.Query&&(this.opts.enableDebugMode&&console.log("message",e,this.agentService.sessionId,Date.now()),await this.query(rS(e.data,this.opts.hotWordReplacementRules),e.completed))},this.handleClientConversation=async e=>{let n=this.conversationService;if(!n.currentClientConversation){let e=rB.create(this.opts);n.setCurrentConversation(e),n.add(e),await this.emitter.emit("conversation_add",e)}let r=n.currentClientConversation;(this.digitalHumanService.isRendering||this.isRenderingMultiModConversation)&&this.interruptAIWorkerConversation(),null==r||r.appendText(e)},this.handleClientConversationCompleted=()=>{this.conversationService.setCurrentConversation(null)},this.interruptAIWorkerConversation=()=>{for(let e of(this.aiWorkerMessageCache&&this.digitalHumanService.renderStreamText(this.aiWorkerMessageCache,!0),this.multiModAbortControllers))e.abort();this.multiModAbortControllers=[];let e=this.digitalHumanService.GetRequestId();this.digitalHumanService.interrupt(),this.conversationService.interruptAll(),this.agentService.abort(),this.aiWorkerMessageCache=null,this.emitter.emit("interrupt",{requestId:e,queryId:this.agentService.queryId?this.agentService.queryId:this.agentService.lastQueryId,sessionId:this.agentService.sessionId}).catch(rI)},this.checkServiceReady=()=>!!this.isDigitalHumanServiceReady&&!!this.isAsrServiceReady&&(this.emitter.emit("ready").catch(rI),!0),this.handleAIWorkerConversationChange=e=>{let n=r=>{this.emitter.emit("conversation_change",{...e.toJSON(),text:e.fulltext,completed:r.completed}).catch(rI),r.completed&&e.emitter.off("content_change",n)},r=()=>{e.emitter.off("interrupt",r),e.emitter.off("content_change",n)};e.emitter.on("content_change",n),e.emitter.on("interrupt",r)},this.weirwood=new o$({common:{buildid:"AAAS_PILOT_KIT_1.0.0",token:"8f3abab4743f4114bd632999224323af"},error:{collectWindowErrors:!1,collectUnhandledRejections:!1,collectResourceLoadErrors:!1,ignoreUrls:["localhost","127.0.0.1"]},perf:{disable:!0}}),this.emitter=new nl(this.opts.enableDebugMode?{debug:{name:so.ENTRY_EMITTER_NAME,enabled:!0}}:void 0),this.bindEvents(),this.registerFormatters(),this.interruptible=this.opts.interruptible}}so=function(e,n,r,i){var o,s=arguments.length,a=s<3?n:null===i?i=Object.getOwnPropertyDescriptor(n,r):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)a=Reflect.decorate(e,n,r,i);else for(var c=e.length-1;c>=0;c--)(o=e[c])&&(a=(s<3?o(a):s>3?o(n,r,a):o(n,r))||a);return s>3&&a&&Object.defineProperty(n,r,a),a}([eV(),si(0,eU(nd.IOptions)),si(0,ez()),si(1,eU(nd.ErrorManager)),si(2,eU(nd.AgentService)),si(3,eU(nd.ASRService)),si(4,eU(nd.DigitalHumanService)),si(5,eU(nd.ConversationService)),sr("design:type",Function),sr("design:paramtypes",["undefined"==typeof IResolvedOptions?Object:IResolvedOptions,void 0===rb?Object:rb,"undefined"==typeof AS?Object:AS,void 0===oJ?Object:oJ,void 0===oY?Object:oY,void 0===iB?Object:iB])],so);let ss=[239,187,191],sa=e=>async(n,r,i)=>{if(!i.ok||!i.body)return;let o=!1,s=n=>{var r;o||(o=!0,null==(r=e.onCompleted)||r.call(e,n))},a=i.body.getReader(),c=new TextDecoder("utf8"),l=function(e){let n,r,i,o,s,a,c;return l(),{feed:function(l){var u;r=r?r+l:l,n&&(u=r,ss.every((e,n)=>u.charCodeAt(n)===e))&&(r=r.slice(ss.length)),n=!1;let d=r.length,p=0,h=!1;for(;p<d;){let n;h&&("\n"===r[p]&&++p,h=!1);let l=-1,u=o;for(let e=i;l<0&&e<d;++e)":"===(n=r[e])&&u<0?u=e-p:"\r"===n?(h=!0,l=e-p):"\n"===n&&(l=e-p);if(l<0){i=d-p,o=u;break}i=0,o=-1,function(n,r,i,o){if(0===o){c.length>0&&(e({type:"event",id:s,event:a||void 0,data:c.slice(0,-1)}),c="",s=void 0),a=void 0;return}let l=i<0,u=n.slice(r,r+(l?o:i)),d=0;d=l?o:" "===n[r+i+1]?i+2:i+1;let p=r+d,h=o-d,f=n.slice(p,p+h).toString();if("data"===u)c+=f?"".concat(f,"\n"):"\n";else if("event"===u)a=f;else if("id"!==u||f.includes("\0")){if("retry"===u){let n=parseInt(f,10);Number.isNaN(n)||e({type:"reconnect-interval",value:n})}}else s=f}(r,p,u,l),p+=l+1}p===d?r="":p>0&&(r=r.slice(p))},reset:l};function l(){n=!0,r="",i=0,o=-1,s=void 0,a=void 0,c=""}}(n=>{var r,i,o;if("event"===n.type&&(null==(r=e.onMessage)||r.call(e,n)),"event"===n.type&&n.data)for(let r of(null==(i=e.onEvent)||i.call(e,n),n.data.split("\n")))e.onData(r);else"reconnect-interval"===n.type&&(null==(o=e.onReconnectInterval)||o.call(e,n.value))}),u=()=>{a.read().then(e=>{if(e.done)return void s();l.feed(c.decode(e.value,{stream:!0})),u()}).catch(r=>{var i;if(n.signal.aborted){null==(i=e.onAborted)||i.call(e);return}s(r)})};return u(),i};(X=(V=K||(K={})).EAiobAction||(V.EAiobAction={}))[X.silence=1]="silence",X[X.Interrupt=2]="Interrupt",X[X.Hangup=3]="Hangup",(W=V.EResponseType||(V.EResponseType={}))[W.Welcome=1]="Welcome",W[W.Normal=2]="Normal",W[W.Command=3]="Command",W[W.TakeOver=4]="TakeOver",($=V.ETextType||(V.ETextType={}))[$.unit=0]="unit",$[$.llm=1]="llm";class sc extends r_{static #k=this.REQUEST_URI="aicc-service/aiob-server/text/stream/query2";constructor(...e){super(...e),this.query=async e=>{this.abortController=new AbortController;let n=sa({onData:e=>{try{let{answer:n,sessionId:r,action:i}=JSON.parse(e);if(r&&(this.conversationSessionId=r),i===K.EAiobAction.Hangup)return void this.onHangup({sessionId:this.conversationSessionId});n&&this.onData({sessionId:this.conversationSessionId,answer:n})}catch(e){e instanceof Error&&this.errorManager.handleError(new nQ(e.message,{sessionId:this.conversationSessionId}))}},onCompleted:()=>{this.onCompleted({sessionId:this.conversationSessionId})}}),r=this.opts.agentConfig;if(!(null==r?void 0:r.robotId))return void this.errorManager.handleError(new nK(`\u{8C03}\u{7528} Agent API ${sc.REQUEST_URI} \u{65F6}\u{5FC5}\u{987B}\u{4F20}\u{5165} robotId \u{53C2}\u{6570}\u{FF0C}\u{8BF7}\u{786E}\u{8BA4}\u{540E}\u{91CD}\u{8BD5}\u{3002}`));let i={query:e,sessionId:this.conversationSessionId,robotId:r.robotId,isComplete:1,queryId:this.queryId};try{var o;await this.request.client.post(sc.REQUEST_URI,{retry:0,timeout:3e5,signal:null==(o=this.abortController)?void 0:o.signal,hooks:{afterResponse:[n]},json:{...i}})}catch(e){e instanceof nh?this.onTimeout({sessionId:this.conversationSessionId}):e instanceof Error&&this.errorManager.handleError(new nY(e.message,{sessionId:this.conversationSessionId}))}},this.hangup=async()=>{let e=this.opts.agentConfig;if(!(null==e?void 0:e.robotId))return void await this.errorManager.handleError(new nK(`\u{8C03}\u{7528} Agent API ${sc.REQUEST_URI} \u{65F6}\u{5FC5}\u{987B}\u{4F20}\u{5165} robotId \u{53C2}\u{6570}\u{FF0C}\u{8BF7}\u{786E}\u{8BA4}\u{540E}\u{91CD}\u{8BD5}\u{3002}`));let n={query:"",robotId:e.robotId,sessionId:this.conversationSessionId,action:K.EAiobAction.Hangup,isComplete:1};try{await this.request.client.post(sc.REQUEST_URI,{retry:0,timeout:3e5,json:{...n},keepalive:!0})}catch(e){e instanceof Error&&this.errorManager.handleError(new nY(e.message,{sessionId:this.conversationSessionId}))}},this.dispose=()=>{this._dispose(),this.hangup().finally(()=>{this.conversationSessionId=""})}}}sc=function(e,n,r,i){var o,s=arguments.length,a=s<3?n:null===i?i=Object.getOwnPropertyDescriptor(n,r):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)a=Reflect.decorate(e,n,r,i);else for(var c=e.length-1;c>=0;c--)(o=e[c])&&(a=(s<3?o(a):s>3?o(n,r,a):o(n,r))||a);return s>3&&a&&Object.defineProperty(n,r,a),a}([eV(),eX()],sc),(G=(z=Q||(Q={})).EReplyType||(z.EReplyType={}))[G.PlainText=1]="PlainText",G[G.RichText=3]="RichText",G[G.Image=4]="Image",G[G.List=8]="List",z.REPLY_TYPE_MAPPING={1:"plainText",3:"richText",8:"list",4:"image"};class sl extends r_{static #k=this.REQUEST_URI="csp-service/online/core/v5/stream/query";constructor(...e){super(...e),this.query=async e=>{var n,r;this.abortController=new AbortController;let i=sa({onData:e=>{try{var n,r;let i=JSON.parse(e).answer[0],o=null!=(r=null==(n=i.reply)?void 0:n.text)?r:"";i&&o?this.onData({sessionId:this.conversationSessionId,answer:o}):i&&i.instruction&&(function(e){if("object"!=typeof e||null===e||"[object Object]"!==Object.prototype.toString.call(e))return!1;let n=Object.getPrototypeOf(e);return null===n||!!(Object.prototype.hasOwnProperty.call(n,"constructor")&&"function"==typeof n.constructor)&&Function.prototype.toString.call(n.constructor)===Function.prototype.toString.call(Object)}(i.instruction)?this.onInstructionReceived({sessionId:this.conversationSessionId,instruction:i.instruction}):this.errorManager.handleError(new nZ("指令格式非法,请检查后重试",{sessionId:this.conversationSessionId})))}catch(e){e instanceof Error&&this.errorManager.handleError(new nQ(e.message,{sessionId:this.conversationSessionId}))}},onCompleted:()=>{this.onCompleted({sessionId:this.conversationSessionId})}});this.conversationSessionId||(this.conversationSessionId=rC());let o=null==(n=this.opts.agentConfig)?void 0:n.token;if(!o)return void this.errorManager.handleError(new nK(`\u{8C03}\u{7528} Agent API ${sl.REQUEST_URI} \u{65F6}\u{5FC5}\u{987B}\u{4F20}\u{5165} token \u{53C2}\u{6570}\u{FF0C}\u{8BF7}\u{786E}\u{8BA4}\u{540E}\u{91CD}\u{8BD5}\u{3002}`));let s={query:e,sessionId:this.conversationSessionId};try{await this.request.client.post(sl.REQUEST_URI,{headers:{token:o},retry:0,timeout:3e5,signal:null==(r=this.abortController)?void 0:r.signal,hooks:{afterResponse:[i]},json:{...s}})}catch(e){e instanceof nh?this.onTimeout({sessionId:this.conversationSessionId}):e instanceof Error&&this.errorManager.handleError(new nY(e.message,{sessionId:this.conversationSessionId}))}},this.dispose=()=>{this._dispose()}}}function su(e,n){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,n)}function sd(e,n){return function(r,i){n(r,i,e)}}sl=function(e,n,r,i){var o,s=arguments.length,a=s<3?n:null===i?i=Object.getOwnPropertyDescriptor(n,r):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)a=Reflect.decorate(e,n,r,i);else for(var c=e.length-1;c>=0;c--)(o=e[c])&&(a=(s<3?o(a):s>3?o(n,r,a):o(n,r))||a);return s>3&&a&&Object.defineProperty(n,r,a),a}([eV(),eX()],sl);class sp{constructor(e,n){this.opts=e,this.errorManager=n,this.started=!1,this.sessionId="",this._dispose=()=>{this.started=!1,this.sessionId=""}}}sp=function(e,n,r,i){var o,s=arguments.length,a=s<3?n:null===i?i=Object.getOwnPropertyDescriptor(n,r):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)a=Reflect.decorate(e,n,r,i);else for(var c=e.length-1;c>=0;c--)(o=e[c])&&(a=(s<3?o(a):s>3?o(n,r,a):o(n,r))||a);return s>3&&a&&Object.defineProperty(n,r,a),a}([eV(),sd(0,eU(nd.IOptions)),sd(0,ez()),sd(1,eU(nd.ErrorManager)),su("design:type",Function),su("design:paramtypes",["undefined"==typeof IResolvedOptions?Object:IResolvedOptions,void 0===rb?Object:rb])],sp);let sh=e=>{if(e)return"string"==typeof e?e:e.id};class sf extends sp{static #k=this.ONLINE_PREFIX_URL="https://ky.cloud.baidu.com/employee-console";static #G=this.SANDBOX_PREFIX_URL="https://ai.agent.kaywang.cn/api";static #eO=this.AUTH_URL="https://ky.cloud.baidu.com/employee-console/v1/access/r/ai-agent/get-authorization";get prefixUrl(){return"production"===this.opts.env?sf.ONLINE_PREFIX_URL:sf.SANDBOX_PREFIX_URL}loginBRTC(e){if("function"!=typeof window.BRTC_Start)throw Error("BRTC_Start global function is missing. Ensure baidu.rtc.sdk.js is loaded.");let n={aspublisher:!0,usingdatachannel:!0,usingvideo:!1,usingaudio:!0,showvideobps:!1,autosubscribe:!0,autoplaymuted:!1,autopublish:!0,showspinner:!1,shownovideo:!1,userevent:!0,sessionevent:!0,logintimeout:1e4,linkdownevent:rI,linkupevent:rI,logintimeoutevent:rI,mediastate:rI,remotevideoon:rI,remotevideooff:rI,remotevideocoming:rI,remotevideoloading:rI,remotevideoconnected_state:rI,remotevideoleaving:rI,remotevideounpublished:rI,localvideoconnected_state:rI,localvideopublished_ok:rI,destroyed:rI,onlocalstream:rI,onlocalstream_end:rI,remotevideo_closed:rI,onmessage:e.onmessage,userevent_joinedroom:e.userevent_joinedroom,userevent_leavingroom:e.userevent_leavingroom,remotemediastating:e.remotemediastating,remotevideoviewid:sh(e.remotevideoviewid),localvideoviewid:sh(e.localvideoviewid)};window.BRTC_Start({...n,...e})}constructor(...e){super(...e),this.currentAppId="",this.Start=async e=>{var n,r,i,o,s;this.currentAppId=this.opts.rtcID;let a=this.prefixUrl,c={};"production"===this.opts.env&&(c.authorization=await this.getAuthToken("/api/v1/aiagent/generateAIAgentCall"));let l="production"===this.opts.env?"/v1/open/ai-agent/generateAIAgentCall":"/v1/aiagent/generateAIAgentCall",u=await nH.post(`${a}${l}`,{json:{app_id:this.currentAppId,quick_start:!0,config:JSON.stringify({...e.cfg})},headers:c}).json();if(!u.ai_agent_instance_id)throw Error("ai_agent_instance_id missing in response");this.started=!0,this.sessionId=u.ai_agent_instance_id;let d=this.sessionId,p=null!=(s=null==(n=u.context)?void 0:n.token)?s:"";(null==(r=u.context)?void 0:r.uid)&&(d=u.context.uid),(null==(i=u.context)?void 0:i.appid)&&(this.currentAppId=u.context.appid),this.loginBRTC({...e,appid:this.currentAppId,roomname:this.sessionId,userid:d,token:p}),null==(o=e.success)||o.call(e)},this.Stop=async()=>{if(this.started){this.started=!1;try{let e=this.prefixUrl,n={};"production"===this.opts.env&&(n.authorization=await this.getAuthToken("/api/v1/aiagent/stopAIAgentInstance"));let r="production"===this.opts.env?"/v1/open/ai-agent/stopAIAgentInstance":"/v1/aiagent/stopAIAgentInstance";await nH.post(`${e}${r}`,{json:{app_id:this.currentAppId,ai_agent_instance_id:this.sessionId},headers:n})}catch(e){if(e instanceof np)throw Error(`stopAIAgentInstance failed (${e.response.status})`);throw e}"function"==typeof window.BRTC_Stop&&window.BRTC_Stop()}},this.Mute=e=>{"function"==typeof window.BRTC_MuteMicphone&&window.BRTC_MuteMicphone(e)},this.GetSessionID=()=>this.sessionId,this.Dispose=()=>{this._dispose()},this.getAuthToken=async e=>{try{let{data:n}=await nH.post(sf.AUTH_URL,{json:{http_method:"POST",path:e,headers:{host:"rtc-aiagent.baidubce.com"}}}).json();return n}catch(e){if(e instanceof np)throw Error(`getAuthToken failed (${e.response.status})`);throw e}}}}sf=function(e,n,r,i){var o,s=arguments.length,a=s<3?n:null===i?i=Object.getOwnPropertyDescriptor(n,r):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)a=Reflect.decorate(e,n,r,i);else for(var c=e.length-1;c>=0;c--)(o=e[c])&&(a=(s<3?o(a):s>3?o(n,r,a):o(n,r))||a);return s>3&&a&&Object.defineProperty(n,r,a),a}([eV(),eX()],sf);let sm=!0,sg=!0;function sv(e,n,r){let i=e.match(n);return i&&i.length>=r&&parseFloat(i[r],10)}function sy(e,n,r){if(!e.RTCPeerConnection)return;let i=e.RTCPeerConnection.prototype,o=i.addEventListener;i.addEventListener=function(e,i){if(e!==n)return o.apply(this,arguments);let s=e=>{let n=r(e);n&&(i.handleEvent?i.handleEvent(n):i(n))};return this._eventMap=this._eventMap||{},this._eventMap[n]||(this._eventMap[n]=new Map),this._eventMap[n].set(i,s),o.apply(this,[e,s])};let s=i.removeEventListener;i.removeEventListener=function(e,r){if(e!==n||!this._eventMap||!this._eventMap[n]||!this._eventMap[n].has(r))return s.apply(this,arguments);let i=this._eventMap[n].get(r);return this._eventMap[n].delete(r),0===this._eventMap[n].size&&delete this._eventMap[n],0===Object.keys(this._eventMap).length&&delete this._eventMap,s.apply(this,[e,i])},Object.defineProperty(i,"on"+n,{get(){return this["_on"+n]},set(e){this["_on"+n]&&(this.removeEventListener(n,this["_on"+n]),delete this["_on"+n]),e&&this.addEventListener(n,this["_on"+n]=e)},enumerable:!0,configurable:!0})}function sb(e){return"boolean"!=typeof e?Error("Argument type: "+typeof e+". Please use a boolean."):(sm=e,e?"adapter.js logging disabled":"adapter.js logging enabled")}function sw(e){return"boolean"!=typeof e?Error("Argument type: "+typeof e+". Please use a boolean."):(sg=!e,"adapter.js deprecation warnings "+(e?"disabled":"enabled"))}function sO(){"object"==typeof window&&(sm||"undefined"!=typeof console&&"function"==typeof console.log&&console.log.apply(console,arguments))}function s_(e,n){sg&&console.warn(e+" is deprecated, please use "+n+" instead.")}function sR(e){return"[object Object]"===Object.prototype.toString.call(e)}function sS(e,n,r){let i=r?"outbound-rtp":"inbound-rtp",o=new Map;if(null===n)return o;let s=[];return e.forEach(e=>{"track"===e.type&&e.trackIdentifier===n.id&&s.push(e)}),s.forEach(n=>{e.forEach(r=>{r.type===i&&r.trackId===n.id&&function e(n,r,i){!r||i.has(r.id)||(i.set(r.id,r),Object.keys(r).forEach(o=>{o.endsWith("Id")?e(n,n.get(r[o]),i):o.endsWith("Ids")&&r[o].forEach(r=>{e(n,n.get(r),i)})}))}(e,r,o)})}),o}function sT(e,n){let r=e&&e.navigator;if(!r.mediaDevices)return;let i=function(e){if("object"!=typeof e||e.mandatory||e.optional)return e;let n={};return Object.keys(e).forEach(r=>{if("require"===r||"advanced"===r||"mediaSource"===r)return;let i="object"==typeof e[r]?e[r]:{ideal:e[r]};void 0!==i.exact&&"number"==typeof i.exact&&(i.min=i.max=i.exact);let o=function(e,n){return e?e+n.charAt(0).toUpperCase()+n.slice(1):"deviceId"===n?"sourceId":n};if(void 0!==i.ideal){n.optional=n.optional||[];let e={};"number"==typeof i.ideal?(e[o("min",r)]=i.ideal,n.optional.push(e),(e={})[o("max",r)]=i.ideal):e[o("",r)]=i.ideal,n.optional.push(e)}void 0!==i.exact&&"number"!=typeof i.exact?(n.mandatory=n.mandatory||{},n.mandatory[o("",r)]=i.exact):["min","max"].forEach(e=>{void 0!==i[e]&&(n.mandatory=n.mandatory||{},n.mandatory[o(e,r)]=i[e])})}),e.advanced&&(n.optional=(n.optional||[]).concat(e.advanced)),n},o=function(e,o){if(n.version>=61)return o(e);if((e=JSON.parse(JSON.stringify(e)))&&"object"==typeof e.audio){let n=function(e,n,r){n in e&&!(r in e)&&(e[r]=e[n],delete e[n])};n((e=JSON.parse(JSON.stringify(e))).audio,"autoGainControl","googAutoGainControl"),n(e.audio,"noiseSuppression","googNoiseSuppression"),e.audio=i(e.audio)}if(e&&"object"==typeof e.video){let s=e.video.facingMode;s=s&&("object"==typeof s?s:{ideal:s});let a=n.version<66;if(s&&("user"===s.exact||"environment"===s.exact||"user"===s.ideal||"environment"===s.ideal)&&!(r.mediaDevices.getSupportedConstraints&&r.mediaDevices.getSupportedConstraints().facingMode&&!a)){let n;if(delete e.video.facingMode,"environment"===s.exact||"environment"===s.ideal?n=["back","rear"]:("user"===s.exact||"user"===s.ideal)&&(n=["front"]),n)return r.mediaDevices.enumerateDevices().then(r=>{let a=(r=r.filter(e=>"videoinput"===e.kind)).find(e=>n.some(n=>e.label.toLowerCase().includes(n)));return!a&&r.length&&n.includes("back")&&(a=r[r.length-1]),a&&(e.video.deviceId=s.exact?{exact:a.deviceId}:{ideal:a.deviceId}),e.video=i(e.video),sO("chrome: "+JSON.stringify(e)),o(e)})}e.video=i(e.video)}return sO("chrome: "+JSON.stringify(e)),o(e)},s=function(e){return n.version>=64?e:{name:({PermissionDeniedError:"NotAllowedError",PermissionDismissedError:"NotAllowedError",InvalidStateError:"NotAllowedError",DevicesNotFoundError:"NotFoundError",ConstraintNotSatisfiedError:"OverconstrainedError",TrackStartError:"NotReadableError",MediaDeviceFailedDueToShutdown:"NotAllowedError",MediaDeviceKillSwitchOn:"NotAllowedError",TabCaptureError:"AbortError",ScreenCaptureError:"AbortError",DeviceCaptureError:"AbortError"})[e.name]||e.name,message:e.message,constraint:e.constraint||e.constraintName,toString(){return this.name+(this.message&&": ")+this.message}}};if(r.getUserMedia=(function(e,n,i){o(e,e=>{r.webkitGetUserMedia(e,n,e=>{i&&i(s(e))})})}).bind(r),r.mediaDevices.getUserMedia){let e=r.mediaDevices.getUserMedia.bind(r.mediaDevices);r.mediaDevices.getUserMedia=function(n){return o(n,n=>e(n).then(e=>{if(n.audio&&!e.getAudioTracks().length||n.video&&!e.getVideoTracks().length)throw e.getTracks().forEach(e=>{e.stop()}),new DOMException("","NotFoundError");return e},e=>Promise.reject(s(e))))}}}function sE(e){e.MediaStream=e.MediaStream||e.webkitMediaStream}function sM(e){if("object"!=typeof e||!e.RTCPeerConnection||"ontrack"in e.RTCPeerConnection.prototype)sy(e,"track",e=>(e.transceiver||Object.defineProperty(e,"transceiver",{value:{receiver:e.receiver}}),e));else{Object.defineProperty(e.RTCPeerConnection.prototype,"ontrack",{get(){return this._ontrack},set(e){this._ontrack&&this.removeEventListener("track",this._ontrack),this.addEventListener("track",this._ontrack=e)},enumerable:!0,configurable:!0});let n=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(){return this._ontrackpoly||(this._ontrackpoly=n=>{n.stream.addEventListener("addtrack",r=>{let i;i=e.RTCPeerConnection.prototype.getReceivers?this.getReceivers().find(e=>e.track&&e.track.id===r.track.id):{track:r.track};let o=new Event("track");o.track=r.track,o.receiver=i,o.transceiver={receiver:i},o.streams=[n.stream],this.dispatchEvent(o)}),n.stream.getTracks().forEach(r=>{let i;i=e.RTCPeerConnection.prototype.getReceivers?this.getReceivers().find(e=>e.track&&e.track.id===r.id):{track:r};let o=new Event("track");o.track=r,o.receiver=i,o.transceiver={receiver:i},o.streams=[n.stream],this.dispatchEvent(o)})},this.addEventListener("addstream",this._ontrackpoly)),n.apply(this,arguments)}}}function sx(e){if("object"==typeof e&&e.RTCPeerConnection&&!("getSenders"in e.RTCPeerConnection.prototype)&&"createDTMFSender"in e.RTCPeerConnection.prototype){let n=function(e,n){return{track:n,get dtmf(){return void 0===this._dtmf&&("audio"===n.kind?this._dtmf=e.createDTMFSender(n):this._dtmf=null),this._dtmf},_pc:e}};if(!e.RTCPeerConnection.prototype.getSenders){e.RTCPeerConnection.prototype.getSenders=function(){return this._senders=this._senders||[],this._senders.slice()};let r=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addTrack=function(e,i){let o=r.apply(this,arguments);return o||(o=n(this,e),this._senders.push(o)),o};let i=e.RTCPeerConnection.prototype.removeTrack;e.RTCPeerConnection.prototype.removeTrack=function(e){i.apply(this,arguments);let n=this._senders.indexOf(e);-1!==n&&this._senders.splice(n,1)}}let r=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(e){this._senders=this._senders||[],r.apply(this,[e]),e.getTracks().forEach(e=>{this._senders.push(n(this,e))})};let i=e.RTCPeerConnection.prototype.removeStream;e.RTCPeerConnection.prototype.removeStream=function(e){this._senders=this._senders||[],i.apply(this,[e]),e.getTracks().forEach(e=>{let n=this._senders.find(n=>n.track===e);n&&this._senders.splice(this._senders.indexOf(n),1)})}}else if("object"==typeof e&&e.RTCPeerConnection&&"getSenders"in e.RTCPeerConnection.prototype&&"createDTMFSender"in e.RTCPeerConnection.prototype&&e.RTCRtpSender&&!("dtmf"in e.RTCRtpSender.prototype)){let n=e.RTCPeerConnection.prototype.getSenders;e.RTCPeerConnection.prototype.getSenders=function(){let e=n.apply(this,[]);return e.forEach(e=>e._pc=this),e},Object.defineProperty(e.RTCRtpSender.prototype,"dtmf",{get(){return void 0===this._dtmf&&("audio"===this.track.kind?this._dtmf=this._pc.createDTMFSender(this.track):this._dtmf=null),this._dtmf}})}}function sC(e){if(!("object"==typeof e&&e.RTCPeerConnection&&e.RTCRtpSender&&e.RTCRtpReceiver))return;if(!("getStats"in e.RTCRtpSender.prototype)){let n=e.RTCPeerConnection.prototype.getSenders;n&&(e.RTCPeerConnection.prototype.getSenders=function(){let e=n.apply(this,[]);return e.forEach(e=>e._pc=this),e});let r=e.RTCPeerConnection.prototype.addTrack;r&&(e.RTCPeerConnection.prototype.addTrack=function(){let e=r.apply(this,arguments);return e._pc=this,e}),e.RTCRtpSender.prototype.getStats=function(){let e=this;return this._pc.getStats().then(n=>sS(n,e.track,!0))}}if(!("getStats"in e.RTCRtpReceiver.prototype)){let n=e.RTCPeerConnection.prototype.getReceivers;n&&(e.RTCPeerConnection.prototype.getReceivers=function(){let e=n.apply(this,[]);return e.forEach(e=>e._pc=this),e}),sy(e,"track",e=>(e.receiver._pc=e.srcElement,e)),e.RTCRtpReceiver.prototype.getStats=function(){let e=this;return this._pc.getStats().then(n=>sS(n,e.track,!1))}}if(!("getStats"in e.RTCRtpSender.prototype&&"getStats"in e.RTCRtpReceiver.prototype))return;let n=e.RTCPeerConnection.prototype.getStats;e.RTCPeerConnection.prototype.getStats=function(){if(arguments.length>0&&arguments[0]instanceof e.MediaStreamTrack){let e,n,r,i=arguments[0];return(this.getSenders().forEach(n=>{n.track===i&&(e?r=!0:e=n)}),this.getReceivers().forEach(e=>(e.track===i&&(n?r=!0:n=e),e.track===i)),r||e&&n)?Promise.reject(new DOMException("There are more than one sender or receiver for the track.","InvalidAccessError")):e?e.getStats():n?n.getStats():Promise.reject(new DOMException("There is no sender or receiver for the track.","InvalidAccessError"))}return n.apply(this,arguments)}}function sj(e){e.RTCPeerConnection.prototype.getLocalStreams=function(){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},Object.keys(this._shimmedLocalStreams).map(e=>this._shimmedLocalStreams[e][0])};let n=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addTrack=function(e,r){if(!r)return n.apply(this,arguments);this._shimmedLocalStreams=this._shimmedLocalStreams||{};let i=n.apply(this,arguments);return this._shimmedLocalStreams[r.id]?-1===this._shimmedLocalStreams[r.id].indexOf(i)&&this._shimmedLocalStreams[r.id].push(i):this._shimmedLocalStreams[r.id]=[r,i],i};let r=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(e){this._shimmedLocalStreams=this._shimmedLocalStreams||{},e.getTracks().forEach(e=>{if(this.getSenders().find(n=>n.track===e))throw new DOMException("Track already exists.","InvalidAccessError")});let n=this.getSenders();r.apply(this,arguments);let i=this.getSenders().filter(e=>-1===n.indexOf(e));this._shimmedLocalStreams[e.id]=[e].concat(i)};let i=e.RTCPeerConnection.prototype.removeStream;e.RTCPeerConnection.prototype.removeStream=function(e){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},delete this._shimmedLocalStreams[e.id],i.apply(this,arguments)};let o=e.RTCPeerConnection.prototype.removeTrack;e.RTCPeerConnection.prototype.removeTrack=function(e){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},e&&Object.keys(this._shimmedLocalStreams).forEach(n=>{let r=this._shimmedLocalStreams[n].indexOf(e);-1!==r&&this._shimmedLocalStreams[n].splice(r,1),1===this._shimmedLocalStreams[n].length&&delete this._shimmedLocalStreams[n]}),o.apply(this,arguments)}}function sI(e,n){if(!e.RTCPeerConnection)return;if(e.RTCPeerConnection.prototype.addTrack&&n.version>=65)return sj(e);let r=e.RTCPeerConnection.prototype.getLocalStreams;e.RTCPeerConnection.prototype.getLocalStreams=function(){let e=r.apply(this);return this._reverseStreams=this._reverseStreams||{},e.map(e=>this._reverseStreams[e.id])};let i=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(n){if(this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},n.getTracks().forEach(e=>{if(this.getSenders().find(n=>n.track===e))throw new DOMException("Track already exists.","InvalidAccessError")}),!this._reverseStreams[n.id]){let r=new e.MediaStream(n.getTracks());this._streams[n.id]=r,this._reverseStreams[r.id]=n,n=r}i.apply(this,[n])};let o=e.RTCPeerConnection.prototype.removeStream;function s(e,n){let r=n.sdp;return Object.keys(e._reverseStreams||[]).forEach(n=>{let i=e._reverseStreams[n],o=e._streams[i.id];r=r.replace(RegExp(o.id,"g"),i.id)}),new RTCSessionDescription({type:n.type,sdp:r})}e.RTCPeerConnection.prototype.removeStream=function(e){this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},o.apply(this,[this._streams[e.id]||e]),delete this._reverseStreams[this._streams[e.id]?this._streams[e.id].id:e.id],delete this._streams[e.id]},e.RTCPeerConnection.prototype.addTrack=function(n,r){if("closed"===this.signalingState)throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");let i=[].slice.call(arguments,1);if(1!==i.length||!i[0].getTracks().find(e=>e===n))throw new DOMException("The adapter.js addTrack polyfill only supports a single stream which is associated with the specified track.","NotSupportedError");if(this.getSenders().find(e=>e.track===n))throw new DOMException("Track already exists.","InvalidAccessError");this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{};let o=this._streams[r.id];if(o)o.addTrack(n),Promise.resolve().then(()=>{this.dispatchEvent(new Event("negotiationneeded"))});else{let i=new e.MediaStream([n]);this._streams[r.id]=i,this._reverseStreams[i.id]=r,this.addStream(i)}return this.getSenders().find(e=>e.track===n)},["createOffer","createAnswer"].forEach(function(n){let r=e.RTCPeerConnection.prototype[n];e.RTCPeerConnection.prototype[n]=({[n](){let e=arguments,n=arguments.length&&"function"==typeof arguments[0];return n?r.apply(this,[n=>{let r=s(this,n);e[0].apply(null,[r])},n=>{e[1]&&e[1].apply(null,n)},arguments[2]]):r.apply(this,arguments).then(e=>s(this,e))}})[n]});let a=e.RTCPeerConnection.prototype.setLocalDescription;e.RTCPeerConnection.prototype.setLocalDescription=function(){var e,n;let r;return arguments.length&&arguments[0].type?(arguments[0]=(e=this,n=arguments[0],r=n.sdp,Object.keys(e._reverseStreams||[]).forEach(n=>{let i=e._reverseStreams[n],o=e._streams[i.id];r=r.replace(RegExp(i.id,"g"),o.id)}),new RTCSessionDescription({type:n.type,sdp:r})),a.apply(this,arguments)):a.apply(this,arguments)};let c=Object.getOwnPropertyDescriptor(e.RTCPeerConnection.prototype,"localDescription");Object.defineProperty(e.RTCPeerConnection.prototype,"localDescription",{get(){let e=c.get.apply(this);return""===e.type?e:s(this,e)}}),e.RTCPeerConnection.prototype.removeTrack=function(e){let n;if("closed"===this.signalingState)throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");if(!e._pc)throw new DOMException("Argument 1 of RTCPeerConnection.removeTrack does not implement interface RTCRtpSender.","TypeError");if(e._pc!==this)throw new DOMException("Sender was not created by this connection.","InvalidAccessError");this._streams=this._streams||{},Object.keys(this._streams).forEach(r=>{this._streams[r].getTracks().find(n=>e.track===n)&&(n=this._streams[r])}),n&&(1===n.getTracks().length?this.removeStream(this._reverseStreams[n.id]):n.removeTrack(e.track),this.dispatchEvent(new Event("negotiationneeded")))}}function sB(e,n){!e.RTCPeerConnection&&e.webkitRTCPeerConnection&&(e.RTCPeerConnection=e.webkitRTCPeerConnection),e.RTCPeerConnection&&n.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach(function(n){let r=e.RTCPeerConnection.prototype[n];e.RTCPeerConnection.prototype[n]=({[n](){return arguments[0]=new("addIceCandidate"===n?e.RTCIceCandidate:e.RTCSessionDescription)(arguments[0]),r.apply(this,arguments)}})[n]})}function sk(e,n){sy(e,"negotiationneeded",e=>{let r=e.target;if(!(n.version<72)&&(!r.getConfiguration||"plan-b"!==r.getConfiguration().sdpSemantics)||"stable"===r.signalingState)return e})}function sA(e,n){let r=e&&e.navigator,i=e&&e.MediaStreamTrack;if(r.getUserMedia=function(e,n,i){s_("navigator.getUserMedia","navigator.mediaDevices.getUserMedia"),r.mediaDevices.getUserMedia(e).then(n,i)},!(n.version>55&&"autoGainControl"in r.mediaDevices.getSupportedConstraints())){let e=function(e,n,r){n in e&&!(r in e)&&(e[r]=e[n],delete e[n])},n=r.mediaDevices.getUserMedia.bind(r.mediaDevices);if(r.mediaDevices.getUserMedia=function(r){return"object"==typeof r&&"object"==typeof r.audio&&(e((r=JSON.parse(JSON.stringify(r))).audio,"autoGainControl","mozAutoGainControl"),e(r.audio,"noiseSuppression","mozNoiseSuppression")),n(r)},i&&i.prototype.getSettings){let n=i.prototype.getSettings;i.prototype.getSettings=function(){let r=n.apply(this,arguments);return e(r,"mozAutoGainControl","autoGainControl"),e(r,"mozNoiseSuppression","noiseSuppression"),r}}if(i&&i.prototype.applyConstraints){let n=i.prototype.applyConstraints;i.prototype.applyConstraints=function(r){return"audio"===this.kind&&"object"==typeof r&&(e(r=JSON.parse(JSON.stringify(r)),"autoGainControl","mozAutoGainControl"),e(r,"noiseSuppression","mozNoiseSuppression")),n.apply(this,[r])}}}}function sP(e,n){e.navigator.mediaDevices&&"getDisplayMedia"in e.navigator.mediaDevices||e.navigator.mediaDevices&&(e.navigator.mediaDevices.getDisplayMedia=function(r){if(!(r&&r.video)){let e=new DOMException("getDisplayMedia without video constraints is undefined");return e.name="NotFoundError",e.code=8,Promise.reject(e)}return!0===r.video?r.video={mediaSource:n}:r.video.mediaSource=n,e.navigator.mediaDevices.getUserMedia(r)})}function sN(e){"object"==typeof e&&e.RTCTrackEvent&&"receiver"in e.RTCTrackEvent.prototype&&!("transceiver"in e.RTCTrackEvent.prototype)&&Object.defineProperty(e.RTCTrackEvent.prototype,"transceiver",{get(){return{receiver:this.receiver}}})}function sL(e,n){if("object"!=typeof e||!(e.RTCPeerConnection||e.mozRTCPeerConnection))return;!e.RTCPeerConnection&&e.mozRTCPeerConnection&&(e.RTCPeerConnection=e.mozRTCPeerConnection),n.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach(function(n){let r=e.RTCPeerConnection.prototype[n];e.RTCPeerConnection.prototype[n]=({[n](){return arguments[0]=new("addIceCandidate"===n?e.RTCIceCandidate:e.RTCSessionDescription)(arguments[0]),r.apply(this,arguments)}})[n]});let r={inboundrtp:"inbound-rtp",outboundrtp:"outbound-rtp",candidatepair:"candidate-pair",localcandidate:"local-candidate",remotecandidate:"remote-candidate"},i=e.RTCPeerConnection.prototype.getStats;e.RTCPeerConnection.prototype.getStats=function(){let[e,o,s]=arguments;return i.apply(this,[e||null]).then(e=>{if(n.version<53&&!o)try{e.forEach(e=>{e.type=r[e.type]||e.type})}catch(n){if("TypeError"!==n.name)throw n;e.forEach((n,i)=>{e.set(i,Object.assign({},n,{type:r[n.type]||n.type}))})}return e}).then(o,s)}}function sD(e){if(!("object"==typeof e&&e.RTCPeerConnection&&e.RTCRtpSender)||e.RTCRtpSender&&"getStats"in e.RTCRtpSender.prototype)return;let n=e.RTCPeerConnection.prototype.getSenders;n&&(e.RTCPeerConnection.prototype.getSenders=function(){let e=n.apply(this,[]);return e.forEach(e=>e._pc=this),e});let r=e.RTCPeerConnection.prototype.addTrack;r&&(e.RTCPeerConnection.prototype.addTrack=function(){let e=r.apply(this,arguments);return e._pc=this,e}),e.RTCRtpSender.prototype.getStats=function(){return this.track?this._pc.getStats(this.track):Promise.resolve(new Map)}}function sF(e){if(!("object"==typeof e&&e.RTCPeerConnection&&e.RTCRtpSender)||e.RTCRtpSender&&"getStats"in e.RTCRtpReceiver.prototype)return;let n=e.RTCPeerConnection.prototype.getReceivers;n&&(e.RTCPeerConnection.prototype.getReceivers=function(){let e=n.apply(this,[]);return e.forEach(e=>e._pc=this),e}),sy(e,"track",e=>(e.receiver._pc=e.srcElement,e)),e.RTCRtpReceiver.prototype.getStats=function(){return this._pc.getStats(this.track)}}function sU(e){!e.RTCPeerConnection||"removeStream"in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.removeStream=function(e){s_("removeStream","removeTrack"),this.getSenders().forEach(n=>{n.track&&e.getTracks().includes(n.track)&&this.removeTrack(n)})})}function sH(e){e.DataChannel&&!e.RTCDataChannel&&(e.RTCDataChannel=e.DataChannel)}function sq(e){if(!("object"==typeof e&&e.RTCPeerConnection))return;let n=e.RTCPeerConnection.prototype.addTransceiver;n&&(e.RTCPeerConnection.prototype.addTransceiver=function(){this.setParametersPromises=[];let e=arguments[1]&&arguments[1].sendEncodings;void 0===e&&(e=[]);let r=(e=[...e]).length>0;r&&e.forEach(e=>{if("rid"in e&&!/^[a-z0-9]{0,16}$/i.test(e.rid))throw TypeError("Invalid RID value provided.");if("scaleResolutionDownBy"in e&&!(parseFloat(e.scaleResolutionDownBy)>=1))throw RangeError("scale_resolution_down_by must be >= 1.0");if("maxFramerate"in e&&!(parseFloat(e.maxFramerate)>=0))throw RangeError("max_framerate must be >= 0.0")});let i=n.apply(this,arguments);if(r){let{sender:n}=i,r=n.getParameters();"encodings"in r&&(1!==r.encodings.length||0!==Object.keys(r.encodings[0]).length)||(r.encodings=e,n.sendEncodings=e,this.setParametersPromises.push(n.setParameters(r).then(()=>{delete n.sendEncodings}).catch(()=>{delete n.sendEncodings})))}return i})}function sV(e){if(!("object"==typeof e&&e.RTCRtpSender))return;let n=e.RTCRtpSender.prototype.getParameters;n&&(e.RTCRtpSender.prototype.getParameters=function(){let e=n.apply(this,arguments);return"encodings"in e||(e.encodings=[].concat(this.sendEncodings||[{}])),e})}function sX(e){if(!("object"==typeof e&&e.RTCPeerConnection))return;let n=e.RTCPeerConnection.prototype.createOffer;e.RTCPeerConnection.prototype.createOffer=function(){return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then(()=>n.apply(this,arguments)).finally(()=>{this.setParametersPromises=[]}):n.apply(this,arguments)}}function sW(e){if(!("object"==typeof e&&e.RTCPeerConnection))return;let n=e.RTCPeerConnection.prototype.createAnswer;e.RTCPeerConnection.prototype.createAnswer=function(){return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then(()=>n.apply(this,arguments)).finally(()=>{this.setParametersPromises=[]}):n.apply(this,arguments)}}function s$(e){if("object"==typeof e&&e.RTCPeerConnection){if("getLocalStreams"in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.getLocalStreams=function(){return this._localStreams||(this._localStreams=[]),this._localStreams}),!("addStream"in e.RTCPeerConnection.prototype)){let n=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addStream=function(e){this._localStreams||(this._localStreams=[]),this._localStreams.includes(e)||this._localStreams.push(e),e.getAudioTracks().forEach(r=>n.call(this,r,e)),e.getVideoTracks().forEach(r=>n.call(this,r,e))},e.RTCPeerConnection.prototype.addTrack=function(e,...r){return r&&r.forEach(e=>{this._localStreams?this._localStreams.includes(e)||this._localStreams.push(e):this._localStreams=[e]}),n.apply(this,arguments)}}"removeStream"in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.removeStream=function(e){this._localStreams||(this._localStreams=[]);let n=this._localStreams.indexOf(e);if(-1===n)return;this._localStreams.splice(n,1);let r=e.getTracks();this.getSenders().forEach(e=>{r.includes(e.track)&&this.removeTrack(e)})})}}function sz(e){if("object"==typeof e&&e.RTCPeerConnection&&("getRemoteStreams"in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.getRemoteStreams=function(){return this._remoteStreams?this._remoteStreams:[]}),!("onaddstream"in e.RTCPeerConnection.prototype))){Object.defineProperty(e.RTCPeerConnection.prototype,"onaddstream",{get(){return this._onaddstream},set(e){this._onaddstream&&(this.removeEventListener("addstream",this._onaddstream),this.removeEventListener("track",this._onaddstreampoly)),this.addEventListener("addstream",this._onaddstream=e),this.addEventListener("track",this._onaddstreampoly=e=>{e.streams.forEach(e=>{if(this._remoteStreams||(this._remoteStreams=[]),this._remoteStreams.includes(e))return;this._remoteStreams.push(e);let n=new Event("addstream");n.stream=e,this.dispatchEvent(n)})})}});let n=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(){let e=this;return this._onaddstreampoly||this.addEventListener("track",this._onaddstreampoly=function(n){n.streams.forEach(n=>{if(e._remoteStreams||(e._remoteStreams=[]),e._remoteStreams.indexOf(n)>=0)return;e._remoteStreams.push(n);let r=new Event("addstream");r.stream=n,e.dispatchEvent(r)})}),n.apply(e,arguments)}}}function sG(e){if("object"!=typeof e||!e.RTCPeerConnection)return;let n=e.RTCPeerConnection.prototype,r=n.createOffer,i=n.createAnswer,o=n.setLocalDescription,s=n.setRemoteDescription,a=n.addIceCandidate;n.createOffer=function(e,n){let i=arguments.length>=2?arguments[2]:arguments[0],o=r.apply(this,[i]);return n?(o.then(e,n),Promise.resolve()):o},n.createAnswer=function(e,n){let r=arguments.length>=2?arguments[2]:arguments[0],o=i.apply(this,[r]);return n?(o.then(e,n),Promise.resolve()):o};let c=function(e,n,r){let i=o.apply(this,[e]);return r?(i.then(n,r),Promise.resolve()):i};n.setLocalDescription=c,n.setRemoteDescription=c=function(e,n,r){let i=s.apply(this,[e]);return r?(i.then(n,r),Promise.resolve()):i},n.addIceCandidate=function(e,n,r){let i=a.apply(this,[e]);return r?(i.then(n,r),Promise.resolve()):i}}function sJ(e){let n=e&&e.navigator;if(n.mediaDevices&&n.mediaDevices.getUserMedia){let e=n.mediaDevices,r=e.getUserMedia.bind(e);n.mediaDevices.getUserMedia=e=>r(sK(e))}!n.getUserMedia&&n.mediaDevices&&n.mediaDevices.getUserMedia&&(n.getUserMedia=(function(e,r,i){n.mediaDevices.getUserMedia(e).then(r,i)}).bind(n))}function sK(e){return e&&void 0!==e.video?Object.assign({},e,{video:function e(n){return sR(n)?Object.keys(n).reduce(function(r,i){let o=sR(n[i]),s=o?e(n[i]):n[i],a=o&&!Object.keys(s).length;return void 0===s||a?r:Object.assign(r,{[i]:s})},{}):n}(e.video)}):e}function sQ(e){if(!e.RTCPeerConnection)return;let n=e.RTCPeerConnection;e.RTCPeerConnection=function(e,r){if(e&&e.iceServers){let n=[];for(let r=0;r<e.iceServers.length;r++){let i=e.iceServers[r];void 0===i.urls&&i.url?(s_("RTCIceServer.url","RTCIceServer.urls"),(i=JSON.parse(JSON.stringify(i))).urls=i.url,delete i.url,n.push(i)):n.push(e.iceServers[r])}e.iceServers=n}return new n(e,r)},e.RTCPeerConnection.prototype=n.prototype,"generateCertificate"in n&&Object.defineProperty(e.RTCPeerConnection,"generateCertificate",{get:()=>n.generateCertificate})}function sY(e){"object"==typeof e&&e.RTCTrackEvent&&"receiver"in e.RTCTrackEvent.prototype&&!("transceiver"in e.RTCTrackEvent.prototype)&&Object.defineProperty(e.RTCTrackEvent.prototype,"transceiver",{get(){return{receiver:this.receiver}}})}function sZ(e){let n=e.RTCPeerConnection.prototype.createOffer;e.RTCPeerConnection.prototype.createOffer=function(e){if(e){void 0!==e.offerToReceiveAudio&&(e.offerToReceiveAudio=!!e.offerToReceiveAudio);let n=this.getTransceivers().find(e=>"audio"===e.receiver.track.kind);!1===e.offerToReceiveAudio&&n?"sendrecv"===n.direction?n.setDirection?n.setDirection("sendonly"):n.direction="sendonly":"recvonly"===n.direction&&(n.setDirection?n.setDirection("inactive"):n.direction="inactive"):!0!==e.offerToReceiveAudio||n||this.addTransceiver("audio",{direction:"recvonly"}),void 0!==e.offerToReceiveVideo&&(e.offerToReceiveVideo=!!e.offerToReceiveVideo);let r=this.getTransceivers().find(e=>"video"===e.receiver.track.kind);!1===e.offerToReceiveVideo&&r?"sendrecv"===r.direction?r.setDirection?r.setDirection("sendonly"):r.direction="sendonly":"recvonly"===r.direction&&(r.setDirection?r.setDirection("inactive"):r.direction="inactive"):!0!==e.offerToReceiveVideo||r||this.addTransceiver("video",{direction:"recvonly"})}return n.apply(this,arguments)}}function s0(e){"object"!=typeof e||e.AudioContext||(e.AudioContext=e.webkitAudioContext)}var s1=et("../../node_modules/sdp/sdp.js"),s2=et.n(s1);function s3(e){if(!e.RTCIceCandidate||e.RTCIceCandidate&&"foundation"in e.RTCIceCandidate.prototype)return;let n=e.RTCIceCandidate;e.RTCIceCandidate=function(e){if("object"==typeof e&&e.candidate&&0===e.candidate.indexOf("a=")&&((e=JSON.parse(JSON.stringify(e))).candidate=e.candidate.substring(2)),e.candidate&&e.candidate.length){let r=new n(e),i=s2().parseCandidate(e.candidate);for(let e in i)e in r||Object.defineProperty(r,e,{value:i[e]});return r.toJSON=function(){return{candidate:r.candidate,sdpMid:r.sdpMid,sdpMLineIndex:r.sdpMLineIndex,usernameFragment:r.usernameFragment}},r}return new n(e)},e.RTCIceCandidate.prototype=n.prototype,sy(e,"icecandidate",n=>(n.candidate&&Object.defineProperty(n,"candidate",{value:new e.RTCIceCandidate(n.candidate),writable:"false"}),n))}function s6(e){!e.RTCIceCandidate||e.RTCIceCandidate&&"relayProtocol"in e.RTCIceCandidate.prototype||sy(e,"icecandidate",e=>{if(e.candidate){let n=s2().parseCandidate(e.candidate.candidate);"relay"===n.type&&(e.candidate.relayProtocol=({0:"tls",1:"tcp",2:"udp"})[n.priority>>24])}return e})}function s5(e,n){if(!e.RTCPeerConnection)return;"sctp"in e.RTCPeerConnection.prototype||Object.defineProperty(e.RTCPeerConnection.prototype,"sctp",{get(){return void 0===this._sctp?null:this._sctp}});let r=function(e){if(!e||!e.sdp)return!1;let n=s2().splitSections(e.sdp);return n.shift(),n.some(e=>{let n=s2().parseMLine(e);return n&&"application"===n.kind&&-1!==n.protocol.indexOf("SCTP")})},i=function(e){let n=e.sdp.match(/mozilla...THIS_IS_SDPARTA-(\d+)/);if(null===n||n.length<2)return -1;let r=parseInt(n[1],10);return r!=r?-1:r},o=function(e){let r=65536;return"firefox"===n.browser&&(r=n.version<57?-1===e?16384:0x7ffffff5:n.version<60?57===n.version?65535:65536:0x7ffffff5),r},s=function(e,r){let i=65536;"firefox"===n.browser&&57===n.version&&(i=65535);let o=s2().matchPrefix(e.sdp,"a=max-message-size:");return o.length>0?i=parseInt(o[0].substring(19),10):"firefox"===n.browser&&-1!==r&&(i=0x7ffffff5),i},a=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(){if(this._sctp=null,"chrome"===n.browser&&n.version>=76){let{sdpSemantics:e}=this.getConfiguration();"plan-b"===e&&Object.defineProperty(this,"sctp",{get(){return void 0===this._sctp?null:this._sctp},enumerable:!0,configurable:!0})}if(r(arguments[0])){let e,n=i(arguments[0]),r=o(n),a=s(arguments[0],n);e=0===r&&0===a?Number.POSITIVE_INFINITY:0===r||0===a?Math.max(r,a):Math.min(r,a);let c={};Object.defineProperty(c,"maxMessageSize",{get:()=>e}),this._sctp=c}return a.apply(this,arguments)}}function s4(e){if(!(e.RTCPeerConnection&&"createDataChannel"in e.RTCPeerConnection.prototype))return;function n(e,n){let r=e.send;e.send=function(){let i=arguments[0],o=i.length||i.size||i.byteLength;if("open"===e.readyState&&n.sctp&&o>n.sctp.maxMessageSize)throw TypeError("Message too large (can send a maximum of "+n.sctp.maxMessageSize+" bytes)");return r.apply(e,arguments)}}let r=e.RTCPeerConnection.prototype.createDataChannel;e.RTCPeerConnection.prototype.createDataChannel=function(){let e=r.apply(this,arguments);return n(e,this),e},sy(e,"datachannel",e=>(n(e.channel,e.target),e))}function s8(e){if(!e.RTCPeerConnection||"connectionState"in e.RTCPeerConnection.prototype)return;let n=e.RTCPeerConnection.prototype;Object.defineProperty(n,"connectionState",{get(){return({completed:"connected",checking:"connecting"})[this.iceConnectionState]||this.iceConnectionState},enumerable:!0,configurable:!0}),Object.defineProperty(n,"onconnectionstatechange",{get(){return this._onconnectionstatechange||null},set(e){this._onconnectionstatechange&&(this.removeEventListener("connectionstatechange",this._onconnectionstatechange),delete this._onconnectionstatechange),e&&this.addEventListener("connectionstatechange",this._onconnectionstatechange=e)},enumerable:!0,configurable:!0}),["setLocalDescription","setRemoteDescription"].forEach(e=>{let r=n[e];n[e]=function(){return this._connectionstatechangepoly||(this._connectionstatechangepoly=e=>{let n=e.target;if(n._lastConnectionState!==n.connectionState){n._lastConnectionState=n.connectionState;let r=new Event("connectionstatechange",e);n.dispatchEvent(r)}return e},this.addEventListener("iceconnectionstatechange",this._connectionstatechangepoly)),r.apply(this,arguments)}})}function s9(e,n){if(!e.RTCPeerConnection||"chrome"===n.browser&&n.version>=71||"safari"===n.browser&&n._safariVersion>=13.1)return;let r=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(n){if(n&&n.sdp&&-1!==n.sdp.indexOf("\na=extmap-allow-mixed")){let r=n.sdp.split("\n").filter(e=>"a=extmap-allow-mixed"!==e.trim()).join("\n");e.RTCSessionDescription&&n instanceof e.RTCSessionDescription?arguments[0]=new e.RTCSessionDescription({type:n.type,sdp:r}):n.sdp=r}return r.apply(this,arguments)}}function s7(e,n){if(!(e.RTCPeerConnection&&e.RTCPeerConnection.prototype))return;let r=e.RTCPeerConnection.prototype.addIceCandidate;r&&0!==r.length&&(e.RTCPeerConnection.prototype.addIceCandidate=function(){return arguments[0]?("chrome"===n.browser&&n.version<78||"firefox"===n.browser&&n.version<68||"safari"===n.browser)&&arguments[0]&&""===arguments[0].candidate?Promise.resolve():r.apply(this,arguments):(arguments[1]&&arguments[1].apply(null),Promise.resolve())})}function ae(e,n){if(!(e.RTCPeerConnection&&e.RTCPeerConnection.prototype))return;let r=e.RTCPeerConnection.prototype.setLocalDescription;r&&0!==r.length&&(e.RTCPeerConnection.prototype.setLocalDescription=function(){let e=arguments[0]||{};if("object"!=typeof e||e.type&&e.sdp)return r.apply(this,arguments);if(!(e={type:e.type,sdp:e.sdp}).type)switch(this.signalingState){case"stable":case"have-local-offer":case"have-remote-pranswer":e.type="offer";break;default:e.type="answer"}return e.sdp||"offer"!==e.type&&"answer"!==e.type?r.apply(this,[e]):("offer"===e.type?this.createOffer:this.createAnswer).apply(this).then(e=>r.apply(this,[e]))})}let at=function({window:e}={},n={shimChrome:!0,shimFirefox:!0,shimSafari:!0}){let r=function(e){let n={browser:null,version:null};if(void 0===e||!e.navigator||!e.navigator.userAgent)return n.browser="Not a browser.",n;let{navigator:r}=e;if(r.userAgentData&&r.userAgentData.brands){let e=r.userAgentData.brands.find(e=>"Chromium"===e.brand);if(e)return{browser:"chrome",version:parseInt(e.version,10)}}return r.mozGetUserMedia?(n.browser="firefox",n.version=parseInt(sv(r.userAgent,/Firefox\/(\d+)\./,1))):r.webkitGetUserMedia||!1===e.isSecureContext&&e.webkitRTCPeerConnection?(n.browser="chrome",n.version=parseInt(sv(r.userAgent,/Chrom(e|ium)\/(\d+)\./,2))):e.RTCPeerConnection&&r.userAgent.match(/AppleWebKit\/(\d+)\./)?(n.browser="safari",n.version=parseInt(sv(r.userAgent,/AppleWebKit\/(\d+)\./,1)),n.supportsUnifiedPlan=e.RTCRtpTransceiver&&"currentDirection"in e.RTCRtpTransceiver.prototype,n._safariVersion=sv(r.userAgent,/Version\/(\d+(\.?\d+))/,1)):n.browser="Not a supported browser.",n}(e),i={browserDetails:r,commonShim:eo,extractVersion:sv,disableLog:sb,disableWarnings:sw,sdp:s1};switch(r.browser){case"chrome":if(!en||!sB||!n.shimChrome){sO("Chrome shim is not included in this adapter release.");break}if(null===r.version){sO("Chrome shim can not determine version, not shimming.");break}sO("adapter.js shimming chrome."),i.browserShim=en,s7(e,r),ae(e,r),sT(e,r),sE(e,r),sB(e,r),sM(e,r),sI(e,r),sx(e,r),sC(e,r),sk(e,r),s3(e,r),s6(e,r),s8(e,r),s5(e,r),s4(e,r),s9(e,r);break;case"firefox":if(!er||!sL||!n.shimFirefox){sO("Firefox shim is not included in this adapter release.");break}sO("adapter.js shimming firefox."),i.browserShim=er,s7(e,r),ae(e,r),sA(e,r),sL(e,r),sN(e,r),sU(e,r),sD(e,r),sF(e,r),sH(e,r),sq(e,r),sV(e,r),sX(e,r),sW(e,r),s3(e,r),s8(e,r),s5(e,r),s4(e,r);break;case"safari":if(!ei||!n.shimSafari){sO("Safari shim is not included in this adapter release.");break}sO("adapter.js shimming safari."),i.browserShim=ei,s7(e,r),ae(e,r),sQ(e,r),sZ(e,r),sG(e,r),s$(e,r),sz(e,r),sY(e,r),sJ(e,r),s0(e,r),s3(e,r),s6(e,r),s5(e,r),s4(e,r),s9(e,r);break;default:sO("Unsupported browser!")}return i}({window:"undefined"==typeof window?void 0:window});(J=Y||(Y={})).DEFAULT_BRTC_SDK_URL="https://brtc-sdk.cdn.bcebos.com/npm/baidurtc@1.2.19/baidu.rtc.sdk.js",J.DEFAULT_BRTC_CLIENT_CONFIG={displayName:"AaaSPilot Kit",debugLevel:!1,rtcOptions:{},cfg:{tag:"H5.SDK",llm:"LLMMute",tts:"MUTE"},silenceTimeoutMs:1e4};let an=e=>{if(e)return"string"==typeof e?e:e.id};class ar extends oJ{static #k=this.MESSAGE_INTERVAL_THRESHOLD=5e3;preloadDeps(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:Y.DEFAULT_BRTC_SDK_URL;return"undefined"==typeof window||window.adapter||(window.adapter=null!=at?at:es),"function"==typeof window.BRTC_Start?Promise.resolve():(this.brtcLoadPromise||(this.brtcLoadPromise=new Promise((n,r)=>{let i=document.createElement("script");i.src=e,i.async=!0,i.onload=()=>n(),i.onerror=()=>{this.errorManager.handleError(new n8(`Failed to load BRTC SDK: ${e}`)),r(Error(`Failed to load BRTC SDK: ${e}`))},document.head.appendChild(i)})),this.brtcLoadPromise)}makeStartOptions(){return{...Y.DEFAULT_BRTC_CLIENT_CONFIG,cfg:{...Y.DEFAULT_BRTC_CLIENT_CONFIG.cfg,asr_vad:this.opts.asrVad}}}parseMessage(e){let n=e.replace(/\[Q\]:?|\[M\]:?|\[C\]:?|\[A\]:?|\[H\]:?|\[E\]:?|\[B\]:?|\[T\]:?/g,"").trim(),r=F.EMessageType.Event,i=!0,o=!1,s=!1;return s=e.includes("VOICE_COMING"),e.includes("[Q]")&&(r=F.EMessageType.Query),e.includes("[E]")&&(r=F.EMessageType.Event),i=!e.includes("[M]"),{type:r,continued:e.includes("[C]"),data:n,completed:i,isCollectingSounds:s}}constructor(...e){super(...e),this.brtcLoadPromise=null,this.silenceTimer=null,this.lastMessageTime=0,this.messageIntervalTimer=null,this.start=async()=>{if(this.started)return;await this._ensureMicPermission();let{displayName:e,debugLevel:n,rtcOptions:{remoteVideoElement:r,localVideoElement:i},cfg:o,silenceTimeoutMs:s}=this.makeStartOptions();return new Promise((a,c)=>{this.signalingService.Start({debuglevel:n,cfg:o,displayname:e,remotevideoviewid:an(r),localvideoviewid:an(i),usingremotemediastate:!0,success:()=>{this.started=!0,this.emitter.emit("start",{sessionId:this.sessionId}).catch(rI),a()},error:e=>{this.errorManager.handleError(new rn(e||"",{sessionId:this.sessionId})),c(Error(e||""))},onmessage:e=>{try{let n=this.parseMessage(e.data);if(e.data.includes("VOICE_COMING")||(this.emitter.emitSerial("message",{...n,sessionId:this.sessionId}).catch(rI),this.checkMessageInterval(n)),0!==s){let r=""===n.data;(e.data.includes("[E]")||e.data.includes("VOICE_COMING"))&&r?this.triggerSilence():this.resetSilenceTimer()}}catch(e){e instanceof Error&&this.errorManager.handleError(new re(e.message,{sessionId:this.sessionId}))}},userevent_joinedroom:(e,n,r)=>{this.emitter.emit("user_joined_room",{id:e,display:n,attribute:r,sessionId:this.sessionId})},userevent_leavingroom:(e,n)=>{this.emitter.emit("user_leaving_room",{id:e,display:n,sessionId:this.sessionId})},remotemediastating:(e,n,r)=>{this.emitter.emit("media_state_changed",{id:e,medium:n,on:r,sessionId:this.sessionId})}})})},this.stop=async()=>{try{await this._stop()}catch(e){e instanceof Error&&this.errorManager.handleError(new n9(e.message,{sessionId:this.sessionId}))}this.emitter.emit("stop",{sessionId:this.signalingService.GetSessionID()})},this.dispose=()=>{this._dispose(),this.brtcLoadPromise=null,this.silenceTimer&&(window.clearTimeout(this.silenceTimer),this.silenceTimer=null),this.messageIntervalTimer&&(window.clearTimeout(this.messageIntervalTimer),this.messageIntervalTimer=null),this.lastMessageTime=0},this.resetSilenceTimer=()=>{null!==this.silenceTimer&&window.clearTimeout(this.silenceTimer),this.silenceTimer=window.setTimeout(()=>{this.emitter.emit("silence",{sessionId:this.signalingService.GetSessionID()})},this.makeStartOptions().silenceTimeoutMs)},this.triggerSilence=()=>{this.emitter.emit("silence",{sessionId:this.signalingService.GetSessionID()}),this.resetSilenceTimer()},this.checkMessageInterval=e=>{let n=Date.now();if(e.completed){this.messageIntervalTimer&&(window.clearTimeout(this.messageIntervalTimer),this.messageIntervalTimer=null),this.lastMessageTime=0;return}if(0===this.lastMessageTime)this.lastMessageTime=n,this.messageIntervalTimer=window.setTimeout(()=>{this.errorManager.handleError(new rt(`ASR\u{6D88}\u{606F}\u{95F4}\u{9694}\u{8D85}\u{8FC7}${ar.MESSAGE_INTERVAL_THRESHOLD}ms\u{9608}\u{503C}`,{sessionId:this.sessionId,context:{lastMessageTime:this.lastMessageTime,currentTime:n,threshold:ar.MESSAGE_INTERVAL_THRESHOLD}}))},ar.MESSAGE_INTERVAL_THRESHOLD);else{let e=n-this.lastMessageTime;e>ar.MESSAGE_INTERVAL_THRESHOLD&&this.errorManager.handleError(new rt(`ASR\u{6D88}\u{606F}\u{95F4}\u{9694}${e}ms\u{8D85}\u{8FC7}${ar.MESSAGE_INTERVAL_THRESHOLD}ms\u{9608}\u{503C}`,{sessionId:this.sessionId,context:{lastMessageTime:this.lastMessageTime,currentTime:n,interval:e,threshold:ar.MESSAGE_INTERVAL_THRESHOLD}})),this.lastMessageTime=n,this.messageIntervalTimer&&window.clearTimeout(this.messageIntervalTimer),this.messageIntervalTimer=window.setTimeout(()=>{this.errorManager.handleError(new rt(`ASR\u{6D88}\u{606F}\u{95F4}\u{9694}\u{8D85}\u{8FC7}${ar.MESSAGE_INTERVAL_THRESHOLD}ms\u{9608}\u{503C}`,{sessionId:this.sessionId,context:{lastMessageTime:this.lastMessageTime,currentTime:Date.now(),threshold:ar.MESSAGE_INTERVAL_THRESHOLD}}))},ar.MESSAGE_INTERVAL_THRESHOLD)}}}}ar=function(e,n,r,i){var o,s=arguments.length,a=s<3?n:null===i?i=Object.getOwnPropertyDescriptor(n,r):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)a=Reflect.decorate(e,n,r,i);else for(var c=e.length-1;c>=0;c--)(o=e[c])&&(a=(s<3?o(a):s>3?o(n,r,a):o(n,r))||a);return s>3&&a&&Object.defineProperty(n,r,a),a}([eV(),eX()],ar),function(){if("undefined"==typeof AbortSignal)return console.warn("AbortSignal is not defined in this environment. The polyfill will not be installed.");iN("any",ik.abortSignalAny),iN("timeout",iA.abortSignalTimeout),iN("abort",iP.abortSignalAbort)}();let ai=e=>{var n;let r=new t0({defaultScope:"Singleton"}),i={...rT,...e,hotWordReplacementRules:[...rR,...null!=(n=e.hotWordReplacementRules)?n:[]]};r.bind(nd.IOptions).toConstantValue(i),r.bind(nd.ErrorManager).to(rb),r.bind(nd.CommonRequest).to(nX);let{agentConfig:o,agentService:s,enableDebugMode:a}=i,c=!!(null==o?void 0:o.robotId),l=!!(null==o?void 0:o.token),u=!!s;if(u&&o&&a&&console.warn("[createAaaSPilotKit] agentService 已提供,agentConfig 配置将被忽略。"),!u&&!c&&!l)throw Error("[createAaaSPilotKit] 未检测到有效的 agent 配置,请至少提供 agentService 或 agentConfig 中的 robotId/token。");s?(Reflect.hasOwnMetadata("@inversifyjs/core/classIsInjectableFlagReflectKey",s)||(eT(eX(),s),eT(eV(),s)),r.bind(nd.AgentService).to(s)):l?r.bind(nd.AgentService).to(sl):c&&r.bind(nd.AgentService).to(sc),r.bind(nd.SignalingService).to(sf),r.bind(nd.ASRService).to(ar);let{rendererMode:d}=i;return r.bind(nd.DigitalHumanService).to(sn),r.bind(nd.ConversationService).to(iB),r.bind(nd.AaaSPilotKitController).to(so),r.get(nd.AaaSPilotKitController)};export{iC as AIWorkerConversationBean,so as AaaSPilotKitController,r_ as BaseAgentService,rB as ClientConversationBean,rj as ConversationBean,iB as ConversationService,rT as DEFAULT_OPTIONS,ai as createAaaSPilotKit};
|