@microsoft/agents-copilotstudio-client 1.1.0-alpha.78 → 1.1.0-alpha.85

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@microsoft/agents-copilotstudio-client",
3
- "version": "1.1.0-alpha.78",
3
+ "version": "1.1.0-alpha.85",
4
4
  "homepage": "https://github.com/microsoft/Agents-for-js",
5
5
  "repository": {
6
6
  "type": "git",
@@ -27,7 +27,7 @@
27
27
  "build:browser": "esbuild --platform=browser --target=es2019 --format=esm --bundle --sourcemap --minify --outfile=dist/src/browser.mjs src/index.ts"
28
28
  },
29
29
  "dependencies": {
30
- "@microsoft/agents-activity": "1.1.0-alpha.78",
30
+ "@microsoft/agents-activity": "1.1.0-alpha.85",
31
31
  "eventsource-client": "^1.2.0",
32
32
  "rxjs": "7.8.2",
33
33
  "uuid": "^11.1.0"
@@ -2,7 +2,7 @@ var Os=Object.create;var uo=Object.defineProperty;var Ps=Object.getOwnPropertyDe
2
2
  `;break;case"id":a=S.includes("\0")?void 0:S;break;case"retry":/^\d+$/.test(S)?n(parseInt(S,10)):r(new tr(`Invalid \`retry\` value: "${S}"`,{type:"invalid-retry",value:S,line:A}));break;default:r(new tr(`Unknown field "${g.length>20?`${g.slice(0,20)}\u2026`:g}"`,{type:"unknown-field",field:g,value:S,line:A}));break}}function T(){d.length>0&&e({id:a,event:l||void 0,data:d.endsWith(`
3
3
  `)?d.slice(0,-1):d}),a=void 0,d="",l=""}function O(g={}){i&&g.consume&&m(i),s=!0,a=void 0,d="",l="",i=""}return{feed:f,reset:O}}function Us(t){let e=[],r="",n=0;for(;n<t.length;){let o=t.indexOf("\r",n),i=t.indexOf(`
4
4
  `,n),s=-1;if(o!==-1&&i!==-1?s=Math.min(o,i):o!==-1?o===t.length-1?s=-1:s=o:i!==-1&&(s=i),s===-1){r=t.slice(n);break}else{let a=t.slice(n,s);e.push(a),n=s+1,t[n-1]==="\r"&&t[n]===`
5
- `&&n++}}return[e,r]}var fo="connecting",Rs="open",Kr="closed",rr=()=>{};function Ms(t,{getStream:e}){let r=typeof t=="string"||t instanceof URL?{url:t}:t,{onMessage:n,onComment:o=rr,onConnect:i=rr,onDisconnect:s=rr,onScheduleReconnect:a=rr}=r,{fetch:d,url:l,initialLastEventId:f}=Ns(r),m={...r.headers},_=[],T=n?[n]:[],O=E=>T.forEach(ne=>ne(E)),g=lo({onEvent:Ts,onRetry:Ss,onComment:o}),S,A=l.toString(),q=new AbortController,te=f,ye=2e3,Vr,re=Kr;return Pt(),{close:Zt,connect:Pt,[Symbol.iterator]:()=>{throw new Error("EventSource does not support synchronous iteration. Use `for await` instead.")},[Symbol.asyncIterator]:$r,get lastEventId(){return te},get url(){return A},get readyState(){return re}};function Pt(){S||(re=fo,q=new AbortController,S=d(l,As()).then(Is).catch(E=>{S=null,!(E.name==="AbortError"||E.type==="aborted"||q.signal.aborted)&&so()}))}function Zt(){re=Kr,q.abort(),g.reset(),clearTimeout(Vr),_.forEach(E=>E())}function $r(){let E=[],ne=[];function jt(){return new Promise(F=>{let oe=ne.shift();oe?F({value:oe,done:!1}):E.push(F)})}let Ge=function(F){let oe=E.shift();oe?oe({value:F,done:!1}):ne.push(F)};function Ie(){for(T.splice(T.indexOf(Ge),1);E.shift(););for(;ne.shift(););}function kt(){let F=E.shift();F&&(F({done:!0,value:void 0}),Ie())}return _.push(kt),T.push(Ge),{next(){return re===Kr?this.return():jt()},return(){return Ie(),Promise.resolve({done:!0,value:void 0})},throw(F){return Ie(),Promise.reject(F)},[Symbol.asyncIterator](){return this}}}function so(){a({delay:ye}),!q.signal.aborted&&(re=fo,Vr=setTimeout(Pt,ye))}async function Is(E){i(),g.reset();let{body:ne,redirected:jt,status:Ge}=E;if(Ge===204){s(),Zt();return}if(!ne)throw new Error("Missing response body");jt&&(A=E.url);let Ie=e(ne),kt=new TextDecoder,F=Ie.getReader(),oe=!0;re=Rs;do{let{done:ao,value:co}=await F.read();co&&g.feed(kt.decode(co,{stream:!ao})),ao&&(oe=!1,S=null,g.reset(),so(),s())}while(oe)}function Ts(E){typeof E.id=="string"&&(te=E.id),O(E)}function Ss(E){ye=E}function As(){let{mode:E,credentials:ne,body:jt,method:Ge,redirect:Ie,referrer:kt,referrerPolicy:F}=r,oe={Accept:"text/event-stream",...m,...te?{"Last-Event-ID":te}:void 0};return{mode:E,credentials:ne,body:jt,method:Ge,redirect:Ie,referrer:kt,referrerPolicy:F,headers:oe,cache:"no-store",signal:q.signal}}}function Ns(t){let e=t.fetch||globalThis.fetch;if(!Ds(e))throw new Error("No fetch implementation provided, and one was not found on the global object.");if(typeof AbortController!="function")throw new Error("Missing AbortController implementation");let{url:r,initialLastEventId:n}=t;if(typeof r!="string"&&!(r instanceof URL))throw new Error("Invalid URL provided - must be string or URL instance");if(typeof n!="string"&&n!==void 0)throw new Error("Invalid initialLastEventId provided - must be string or undefined");return{fetch:e,url:r,initialLastEventId:n}}function Ds(t){return typeof t=="function"}var zs={getStream:Ls};function po(t){return Ms(t,zs)}function Ls(t){if(!(t instanceof ReadableStream))throw new Error("Invalid stream, expected a web ReadableStream");return t}var bo=Et(Mt());var sr=class{constructor(e){this.API_VERSION="2022-03-01-preview";let{identifier:r,host:n}=e;this.baseURL=new URL(`/copilotstudio/prebuilt/authenticated/bots/${r}`,n),this.baseURL.searchParams.append("api-version",this.API_VERSION)}getConversationUrl(e){let r=new URL(this.baseURL.href);return r.pathname=`${r.pathname}/conversations`,e&&(r.pathname=`${r.pathname}/${e}`),r.href}};var ar=class{constructor(e){this.API_VERSION="2022-03-01-preview";let{schema:r,host:n}=e;this.baseURL=new URL(`/copilotstudio/dataverse-backed/authenticated/bots/${r}`,n),this.baseURL.searchParams.append("api-version",this.API_VERSION)}getConversationUrl(e){let r=new URL(this.baseURL.href);return r.pathname=`${r.pathname}/conversations`,e&&(r.pathname=`${r.pathname}/${e}`),r.href}};var Qe=(0,bo.debug)("copilot-studio:power-platform");function ur(t,e){var a,d,l,f,m,_;if((a=t.directConnectUrl)!=null&&a.trim()){if(Qe.debug(`Using direct connection: ${t.directConnectUrl}`),!Nt(t.directConnectUrl))throw new Error("directConnectUrl must be a valid URL");return t.directConnectUrl.toLowerCase().includes("tenants/00000000-0000-0000-0000-000000000000")?(Qe.debug(`Direct connection cannot be used, forcing default settings flow. Tenant ID is missing in the URL: ${t.directConnectUrl}`),ur({...t,directConnectUrl:""},e)):na(t.directConnectUrl,e).href}let r=(d=t.cloud)!=null?d:"Prod",n=(l=t.copilotAgentType)!=null?l:"Published";if(Qe.debug(`Using cloud setting: ${r}`),Qe.debug(`Using agent type: ${n}`),!((f=t.environmentId)!=null&&f.trim()))throw new Error("EnvironmentId must be provided");if(!((m=t.agentIdentifier)!=null&&m.trim()))throw new Error("AgentIdentifier must be provided");if(r==="Other")if((_=t.customPowerPlatformCloud)!=null&&_.trim())if(Nt(t.customPowerPlatformCloud))Qe.debug(`Using custom Power Platform cloud: ${t.customPowerPlatformCloud}`);else throw new Error("customPowerPlatformCloud must be a valid URL");else throw new Error("customPowerPlatformCloud must be provided when PowerPlatformCloud is Other");let o=oa(r,t.environmentId,t.customPowerPlatformCloud),s={Published:()=>new ar({host:o,schema:t.agentIdentifier}),Prebuilt:()=>new sr({host:o,identifier:t.agentIdentifier})}[n]().getConversationUrl(e);return Qe.debug(`Generated Copilot Studio connection URL: ${s}`),s}function xo(t,e="Unknown",r="",n=""){var o,i;if(!n&&!(t!=null&&t.directConnectUrl)){if(e==="Other"&&!r)throw new Error("cloudBaseAddress must be provided when PowerPlatformCloudCategory is Other");if(!t&&e==="Unknown")throw new Error("Either settings or cloud must be provided");if(t&&t.cloud&&t.cloud!=="Unknown"&&(e=t.cloud),e==="Other")if(r&&Nt(r))e="Other";else if(t!=null&&t.customPowerPlatformCloud&&Nt(t.customPowerPlatformCloud))e="Other",r=t.customPowerPlatformCloud;else throw new Error("Either CustomPowerPlatformCloud or cloudBaseAddress must be provided when PowerPlatformCloudCategory is Other");return r!=null||(r="api.unknown.powerplatform.com"),`https://${cr(e,r)}/.default`}else if(n||(n=(o=t==null?void 0:t.directConnectUrl)!=null?o:""),n&&Nt(n)){if(_o(new URL(n))==="Unknown"){let s=(i=t==null?void 0:t.cloud)!=null?i:e;if(s==="Other"||s==="Unknown")throw new Error("Unable to resolve the PowerPlatform Cloud from DirectConnectUrl. The Token Audience resolver requires a specific PowerPlatformCloudCategory.");if(s!=="Unknown")return`https://${cr(s,"")}/.default`;throw new Error("Unable to resolve the PowerPlatform Cloud from DirectConnectUrl. The Token Audience resolver requires a specific PowerPlatformCloudCategory.")}return`https://${cr(_o(new URL(n)),"")}/.default`}else throw new Error("DirectConnectUrl must be provided when DirectConnectUrl is set")}function Nt(t){try{let e=t.startsWith("http")?t:`https://${t}`;return!!new URL(e)}catch{return!1}}function na(t,e){let r=new URL(t);return r.searchParams.has("api-version")||r.searchParams.append("api-version","2022-03-01-preview"),r.pathname.endsWith("/")&&(r.pathname=r.pathname.slice(0,-1)),r.pathname.includes("/conversations")&&(r.pathname=r.pathname.substring(0,r.pathname.indexOf("/conversations"))),r.pathname=`${r.pathname}/conversations`,e&&(r.pathname=`${r.pathname}/${e}`),r}function oa(t,e,r){if(t==="Other"&&(!r||!r.trim()))throw new Error("cloudBaseAddress must be provided when PowerPlatformCloud is Other");r=r!=null?r:"api.unknown.powerplatform.com";let n=e.toLowerCase().replaceAll("-",""),o=ia(t),i=n.substring(0,n.length-o),s=n.substring(n.length-o);return new URL(`https://${i}.${s}.environment.${cr(t,r)}`)}function cr(t,e){switch(t){case"Local":return"api.powerplatform.localhost";case"Exp":return"api.exp.powerplatform.com";case"Dev":return"api.dev.powerplatform.com";case"Prv":return"api.prv.powerplatform.com";case"Test":return"api.test.powerplatform.com";case"Preprod":return"api.preprod.powerplatform.com";case"FirstRelease":case"Prod":return"api.powerplatform.com";case"GovFR":return"api.gov.powerplatform.microsoft.us";case"Gov":return"api.gov.powerplatform.microsoft.us";case"High":return"api.high.powerplatform.microsoft.us";case"DoD":return"api.appsplatform.us";case"Mooncake":return"api.powerplatform.partner.microsoftonline.cn";case"Ex":return"api.powerplatform.eaglex.ic.gov";case"Rx":return"api.powerplatform.microsoft.scloud";case"Other":return e;default:throw new Error(`Invalid cluster category value: ${t}`)}}function ia(t){switch(t){case"FirstRelease":case"Prod":return 2;default:return 1}}function _o(t){switch(t.host.toLowerCase()){case"api.powerplatform.localhost":return"Local";case"api.exp.powerplatform.com":return"Exp";case"api.dev.powerplatform.com":return"Dev";case"api.prv.powerplatform.com":return"Prv";case"api.test.powerplatform.com":return"Test";case"api.preprod.powerplatform.com":return"Preprod";case"api.powerplatform.com":return"Prod";case"api.gov.powerplatform.microsoft.us":return"GovFR";case"api.high.powerplatform.microsoft.us":return"High";case"api.appsplatform.us":return"DoD";case"api.powerplatform.partner.microsoftonline.cn":return"Mooncake";default:return"Unknown"}}var Xt=Et(Hn());var Mr=class{constructor(e){this.activity=e}};var ss=Et(Mt());var os="1.1.0-alpha.78";var Nr={};var J=(0,ss.debug)("copilot-studio:client"),he=class he{constructor(e,r){this.conversationId="";this.settings=e,this.token=r}async*postRequestAsync(e,r,n="POST"){var i,s;J.debug(`>>> SEND TO ${e}`);let o=po({url:e,headers:{Authorization:`Bearer ${this.token}`,"User-Agent":he.getProductInfo(),"Content-Type":"application/json",Accept:"text/event-stream"},body:r?JSON.stringify(r):void 0,method:n,fetch:async(a,d)=>{let l=await fetch(a,d);return this.processResponseHeaders(l.headers),l}});try{for await(let{data:a,event:d}of o){if(a&&d==="activity")try{let l=Xt.Activity.fromJson(a);switch(l.type){case Xt.ActivityTypes.Message:this.conversationId.trim()||(this.conversationId=(s=(i=l.conversation)==null?void 0:i.id)!=null?s:"",J.debug(`Conversation ID: ${this.conversationId}`)),yield l;break;default:J.debug(`Activity type: ${l.type}`),yield l;break}}catch(l){J.error("Failed to parse activity:",l)}else if(d==="end"){J.debug("Stream complete");break}if(o.readyState==="closed"){J.debug("Connection closed");break}}}finally{o.close()}}static getProductInfo(){let e=`CopilotStudioClient.agents-sdk-js/${os}`,r;return typeof window!="undefined"&&window.navigator?r=`${e} ${navigator.userAgent}`:r=`${e} nodejs/${process.version} ${Nr.platform()}-${Nr.arch()}/${Nr.release()}`,J.debug(`User-Agent: ${r}`),r}processResponseHeaders(e){var n,o;if(this.settings.useExperimentalEndpoint&&!((n=this.settings.directConnectUrl)!=null&&n.trim())){let i=e==null?void 0:e.get(he.islandExperimentalUrlHeaderKey);i&&(this.settings.directConnectUrl=i,J.debug(`Island Experimental URL: ${i}`))}this.conversationId=(o=e==null?void 0:e.get(he.conversationIdHeaderKey))!=null?o:"",this.conversationId&&J.debug(`Conversation ID: ${this.conversationId}`);let r=new Headers;e.forEach((i,s)=>{s.toLowerCase()!=="authorization"&&s.toLowerCase()!==he.conversationIdHeaderKey.toLowerCase()&&r.set(s,i)}),J.debug("Headers received:",r)}async*startConversationAsync(e=!0){let r=ur(this.settings),n={emitStartConversationEvent:e};J.info("Starting conversation ..."),yield*this.postRequestAsync(r,n,"POST")}async*askQuestionAsync(e,r=this.conversationId){let o={type:"message",text:e,conversation:{id:r}},i=Xt.Activity.fromObject(o);yield*this.sendActivity(i)}async*sendActivity(e,r=this.conversationId){var s,a;let n=(a=(s=e.conversation)==null?void 0:s.id)!=null?a:r,o=ur(this.settings,n),i=new Mr(e);J.info("Sending activity...",e),yield*this.postRequestAsync(o,i,"POST")}};he.conversationIdHeaderKey="x-ms-conversationid",he.islandExperimentalUrlHeaderKey="x-ms-d2e-experimental",he.scopeFromSettings=xo;var is=he;var R=[];for(let t=0;t<256;++t)R.push((t+256).toString(16).slice(1));function as(t,e=0){return(R[t[e+0]]+R[t[e+1]]+R[t[e+2]]+R[t[e+3]]+"-"+R[t[e+4]]+R[t[e+5]]+"-"+R[t[e+6]]+R[t[e+7]]+"-"+R[t[e+8]]+R[t[e+9]]+"-"+R[t[e+10]]+R[t[e+11]]+R[t[e+12]]+R[t[e+13]]+R[t[e+14]]+R[t[e+15]]).toLowerCase()}var Bn,Ed=new Uint8Array(16);function Kn(){if(!Bn){if(typeof crypto=="undefined"||!crypto.getRandomValues)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");Bn=crypto.getRandomValues.bind(crypto)}return Bn(Ed)}var Ud=typeof crypto!="undefined"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto),Gn={randomUUID:Ud};function Rd(t,e,r){var o,i,s;if(Gn.randomUUID&&!e&&!t)return Gn.randomUUID();t=t||{};let n=(s=(i=t.random)!=null?i:(o=t.rng)==null?void 0:o.call(t))!=null?s:Kn();if(n.length<16)throw new Error("Random bytes length must be >= 16");if(n[6]=n[6]&15|64,n[8]=n[8]&63|128,e){if(r=r||0,r<0||r+16>e.length)throw new RangeError(`UUID byte range ${r}:${r+15} is out of buffer bounds`);for(let a=0;a<16;++a)e[r+a]=n[a];return e}return as(n)}var Jn=Rd;var ws=Et(Hn());var Yn=function(t,e){return Yn=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(r,n){r.__proto__=n}||function(r,n){for(var o in n)Object.prototype.hasOwnProperty.call(n,o)&&(r[o]=n[o])},Yn(t,e)};function Ce(t,e){if(typeof e!="function"&&e!==null)throw new TypeError("Class extends value "+String(e)+" is not a constructor or null");Yn(t,e);function r(){this.constructor=t}t.prototype=e===null?Object.create(e):(r.prototype=e.prototype,new r)}function Qt(t){var e=typeof Symbol=="function"&&Symbol.iterator,r=e&&t[e],n=0;if(r)return r.call(t);if(t&&typeof t.length=="number")return{next:function(){return t&&n>=t.length&&(t=void 0),{value:t&&t[n++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")}function Ct(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var n=r.call(t),o,i=[],s;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(a){s={error:a}}finally{try{o&&!o.done&&(r=n.return)&&r.call(n)}finally{if(s)throw s.error}}return i}function It(t,e,r){if(r||arguments.length===2)for(var n=0,o=e.length,i;n<o;n++)(i||!(n in e))&&(i||(i=Array.prototype.slice.call(e,0,n)),i[n]=e[n]);return t.concat(i||Array.prototype.slice.call(e))}function Y(t){return typeof t=="function"}function Dr(t){var e=function(n){Error.call(n),n.stack=new Error().stack},r=t(e);return r.prototype=Object.create(Error.prototype),r.prototype.constructor=r,r}var zr=Dr(function(t){return function(r){t(this),this.message=r?r.length+` errors occurred during unsubscription:
5
+ `&&n++}}return[e,r]}var fo="connecting",Rs="open",Kr="closed",rr=()=>{};function Ms(t,{getStream:e}){let r=typeof t=="string"||t instanceof URL?{url:t}:t,{onMessage:n,onComment:o=rr,onConnect:i=rr,onDisconnect:s=rr,onScheduleReconnect:a=rr}=r,{fetch:d,url:l,initialLastEventId:f}=Ns(r),m={...r.headers},_=[],T=n?[n]:[],O=E=>T.forEach(ne=>ne(E)),g=lo({onEvent:Ts,onRetry:Ss,onComment:o}),S,A=l.toString(),q=new AbortController,te=f,ye=2e3,Vr,re=Kr;return Pt(),{close:Zt,connect:Pt,[Symbol.iterator]:()=>{throw new Error("EventSource does not support synchronous iteration. Use `for await` instead.")},[Symbol.asyncIterator]:$r,get lastEventId(){return te},get url(){return A},get readyState(){return re}};function Pt(){S||(re=fo,q=new AbortController,S=d(l,As()).then(Is).catch(E=>{S=null,!(E.name==="AbortError"||E.type==="aborted"||q.signal.aborted)&&so()}))}function Zt(){re=Kr,q.abort(),g.reset(),clearTimeout(Vr),_.forEach(E=>E())}function $r(){let E=[],ne=[];function jt(){return new Promise(F=>{let oe=ne.shift();oe?F({value:oe,done:!1}):E.push(F)})}let Ge=function(F){let oe=E.shift();oe?oe({value:F,done:!1}):ne.push(F)};function Ie(){for(T.splice(T.indexOf(Ge),1);E.shift(););for(;ne.shift(););}function kt(){let F=E.shift();F&&(F({done:!0,value:void 0}),Ie())}return _.push(kt),T.push(Ge),{next(){return re===Kr?this.return():jt()},return(){return Ie(),Promise.resolve({done:!0,value:void 0})},throw(F){return Ie(),Promise.reject(F)},[Symbol.asyncIterator](){return this}}}function so(){a({delay:ye}),!q.signal.aborted&&(re=fo,Vr=setTimeout(Pt,ye))}async function Is(E){i(),g.reset();let{body:ne,redirected:jt,status:Ge}=E;if(Ge===204){s(),Zt();return}if(!ne)throw new Error("Missing response body");jt&&(A=E.url);let Ie=e(ne),kt=new TextDecoder,F=Ie.getReader(),oe=!0;re=Rs;do{let{done:ao,value:co}=await F.read();co&&g.feed(kt.decode(co,{stream:!ao})),ao&&(oe=!1,S=null,g.reset(),so(),s())}while(oe)}function Ts(E){typeof E.id=="string"&&(te=E.id),O(E)}function Ss(E){ye=E}function As(){let{mode:E,credentials:ne,body:jt,method:Ge,redirect:Ie,referrer:kt,referrerPolicy:F}=r,oe={Accept:"text/event-stream",...m,...te?{"Last-Event-ID":te}:void 0};return{mode:E,credentials:ne,body:jt,method:Ge,redirect:Ie,referrer:kt,referrerPolicy:F,headers:oe,cache:"no-store",signal:q.signal}}}function Ns(t){let e=t.fetch||globalThis.fetch;if(!Ds(e))throw new Error("No fetch implementation provided, and one was not found on the global object.");if(typeof AbortController!="function")throw new Error("Missing AbortController implementation");let{url:r,initialLastEventId:n}=t;if(typeof r!="string"&&!(r instanceof URL))throw new Error("Invalid URL provided - must be string or URL instance");if(typeof n!="string"&&n!==void 0)throw new Error("Invalid initialLastEventId provided - must be string or undefined");return{fetch:e,url:r,initialLastEventId:n}}function Ds(t){return typeof t=="function"}var zs={getStream:Ls};function po(t){return Ms(t,zs)}function Ls(t){if(!(t instanceof ReadableStream))throw new Error("Invalid stream, expected a web ReadableStream");return t}var bo=Et(Mt());var sr=class{constructor(e){this.API_VERSION="2022-03-01-preview";let{identifier:r,host:n}=e;this.baseURL=new URL(`/copilotstudio/prebuilt/authenticated/bots/${r}`,n),this.baseURL.searchParams.append("api-version",this.API_VERSION)}getConversationUrl(e){let r=new URL(this.baseURL.href);return r.pathname=`${r.pathname}/conversations`,e&&(r.pathname=`${r.pathname}/${e}`),r.href}};var ar=class{constructor(e){this.API_VERSION="2022-03-01-preview";let{schema:r,host:n}=e;this.baseURL=new URL(`/copilotstudio/dataverse-backed/authenticated/bots/${r}`,n),this.baseURL.searchParams.append("api-version",this.API_VERSION)}getConversationUrl(e){let r=new URL(this.baseURL.href);return r.pathname=`${r.pathname}/conversations`,e&&(r.pathname=`${r.pathname}/${e}`),r.href}};var Qe=(0,bo.debug)("copilot-studio:power-platform");function ur(t,e){var a,d,l,f,m,_;if((a=t.directConnectUrl)!=null&&a.trim()){if(Qe.debug(`Using direct connection: ${t.directConnectUrl}`),!Nt(t.directConnectUrl))throw new Error("directConnectUrl must be a valid URL");return t.directConnectUrl.toLowerCase().includes("tenants/00000000-0000-0000-0000-000000000000")?(Qe.debug(`Direct connection cannot be used, forcing default settings flow. Tenant ID is missing in the URL: ${t.directConnectUrl}`),ur({...t,directConnectUrl:""},e)):na(t.directConnectUrl,e).href}let r=(d=t.cloud)!=null?d:"Prod",n=(l=t.copilotAgentType)!=null?l:"Published";if(Qe.debug(`Using cloud setting: ${r}`),Qe.debug(`Using agent type: ${n}`),!((f=t.environmentId)!=null&&f.trim()))throw new Error("EnvironmentId must be provided");if(!((m=t.agentIdentifier)!=null&&m.trim()))throw new Error("AgentIdentifier must be provided");if(r==="Other")if((_=t.customPowerPlatformCloud)!=null&&_.trim())if(Nt(t.customPowerPlatformCloud))Qe.debug(`Using custom Power Platform cloud: ${t.customPowerPlatformCloud}`);else throw new Error("customPowerPlatformCloud must be a valid URL");else throw new Error("customPowerPlatformCloud must be provided when PowerPlatformCloud is Other");let o=oa(r,t.environmentId,t.customPowerPlatformCloud),s={Published:()=>new ar({host:o,schema:t.agentIdentifier}),Prebuilt:()=>new sr({host:o,identifier:t.agentIdentifier})}[n]().getConversationUrl(e);return Qe.debug(`Generated Copilot Studio connection URL: ${s}`),s}function xo(t,e="Unknown",r="",n=""){var o,i;if(!n&&!(t!=null&&t.directConnectUrl)){if(e==="Other"&&!r)throw new Error("cloudBaseAddress must be provided when PowerPlatformCloudCategory is Other");if(!t&&e==="Unknown")throw new Error("Either settings or cloud must be provided");if(t&&t.cloud&&t.cloud!=="Unknown"&&(e=t.cloud),e==="Other")if(r&&Nt(r))e="Other";else if(t!=null&&t.customPowerPlatformCloud&&Nt(t.customPowerPlatformCloud))e="Other",r=t.customPowerPlatformCloud;else throw new Error("Either CustomPowerPlatformCloud or cloudBaseAddress must be provided when PowerPlatformCloudCategory is Other");return r!=null||(r="api.unknown.powerplatform.com"),`https://${cr(e,r)}/.default`}else if(n||(n=(o=t==null?void 0:t.directConnectUrl)!=null?o:""),n&&Nt(n)){if(_o(new URL(n))==="Unknown"){let s=(i=t==null?void 0:t.cloud)!=null?i:e;if(s==="Other"||s==="Unknown")throw new Error("Unable to resolve the PowerPlatform Cloud from DirectConnectUrl. The Token Audience resolver requires a specific PowerPlatformCloudCategory.");if(s!=="Unknown")return`https://${cr(s,"")}/.default`;throw new Error("Unable to resolve the PowerPlatform Cloud from DirectConnectUrl. The Token Audience resolver requires a specific PowerPlatformCloudCategory.")}return`https://${cr(_o(new URL(n)),"")}/.default`}else throw new Error("DirectConnectUrl must be provided when DirectConnectUrl is set")}function Nt(t){try{let e=t.startsWith("http")?t:`https://${t}`;return!!new URL(e)}catch{return!1}}function na(t,e){let r=new URL(t);return r.searchParams.has("api-version")||r.searchParams.append("api-version","2022-03-01-preview"),r.pathname.endsWith("/")&&(r.pathname=r.pathname.slice(0,-1)),r.pathname.includes("/conversations")&&(r.pathname=r.pathname.substring(0,r.pathname.indexOf("/conversations"))),r.pathname=`${r.pathname}/conversations`,e&&(r.pathname=`${r.pathname}/${e}`),r}function oa(t,e,r){if(t==="Other"&&(!r||!r.trim()))throw new Error("cloudBaseAddress must be provided when PowerPlatformCloud is Other");r=r!=null?r:"api.unknown.powerplatform.com";let n=e.toLowerCase().replaceAll("-",""),o=ia(t),i=n.substring(0,n.length-o),s=n.substring(n.length-o);return new URL(`https://${i}.${s}.environment.${cr(t,r)}`)}function cr(t,e){switch(t){case"Local":return"api.powerplatform.localhost";case"Exp":return"api.exp.powerplatform.com";case"Dev":return"api.dev.powerplatform.com";case"Prv":return"api.prv.powerplatform.com";case"Test":return"api.test.powerplatform.com";case"Preprod":return"api.preprod.powerplatform.com";case"FirstRelease":case"Prod":return"api.powerplatform.com";case"GovFR":return"api.gov.powerplatform.microsoft.us";case"Gov":return"api.gov.powerplatform.microsoft.us";case"High":return"api.high.powerplatform.microsoft.us";case"DoD":return"api.appsplatform.us";case"Mooncake":return"api.powerplatform.partner.microsoftonline.cn";case"Ex":return"api.powerplatform.eaglex.ic.gov";case"Rx":return"api.powerplatform.microsoft.scloud";case"Other":return e;default:throw new Error(`Invalid cluster category value: ${t}`)}}function ia(t){switch(t){case"FirstRelease":case"Prod":return 2;default:return 1}}function _o(t){switch(t.host.toLowerCase()){case"api.powerplatform.localhost":return"Local";case"api.exp.powerplatform.com":return"Exp";case"api.dev.powerplatform.com":return"Dev";case"api.prv.powerplatform.com":return"Prv";case"api.test.powerplatform.com":return"Test";case"api.preprod.powerplatform.com":return"Preprod";case"api.powerplatform.com":return"Prod";case"api.gov.powerplatform.microsoft.us":return"GovFR";case"api.high.powerplatform.microsoft.us":return"High";case"api.appsplatform.us":return"DoD";case"api.powerplatform.partner.microsoftonline.cn":return"Mooncake";default:return"Unknown"}}var Xt=Et(Hn());var Mr=class{constructor(e){this.activity=e}};var ss=Et(Mt());var os="1.1.0-alpha.85";var Nr={};var J=(0,ss.debug)("copilot-studio:client"),he=class he{constructor(e,r){this.conversationId="";this.settings=e,this.token=r}async*postRequestAsync(e,r,n="POST"){var i,s;J.debug(`>>> SEND TO ${e}`);let o=po({url:e,headers:{Authorization:`Bearer ${this.token}`,"User-Agent":he.getProductInfo(),"Content-Type":"application/json",Accept:"text/event-stream"},body:r?JSON.stringify(r):void 0,method:n,fetch:async(a,d)=>{let l=await fetch(a,d);return this.processResponseHeaders(l.headers),l}});try{for await(let{data:a,event:d}of o){if(a&&d==="activity")try{let l=Xt.Activity.fromJson(a);switch(l.type){case Xt.ActivityTypes.Message:this.conversationId.trim()||(this.conversationId=(s=(i=l.conversation)==null?void 0:i.id)!=null?s:"",J.debug(`Conversation ID: ${this.conversationId}`)),yield l;break;default:J.debug(`Activity type: ${l.type}`),yield l;break}}catch(l){J.error("Failed to parse activity:",l)}else if(d==="end"){J.debug("Stream complete");break}if(o.readyState==="closed"){J.debug("Connection closed");break}}}finally{o.close()}}static getProductInfo(){let e=`CopilotStudioClient.agents-sdk-js/${os}`,r;return typeof window!="undefined"&&window.navigator?r=`${e} ${navigator.userAgent}`:r=`${e} nodejs/${process.version} ${Nr.platform()}-${Nr.arch()}/${Nr.release()}`,J.debug(`User-Agent: ${r}`),r}processResponseHeaders(e){var n,o;if(this.settings.useExperimentalEndpoint&&!((n=this.settings.directConnectUrl)!=null&&n.trim())){let i=e==null?void 0:e.get(he.islandExperimentalUrlHeaderKey);i&&(this.settings.directConnectUrl=i,J.debug(`Island Experimental URL: ${i}`))}this.conversationId=(o=e==null?void 0:e.get(he.conversationIdHeaderKey))!=null?o:"",this.conversationId&&J.debug(`Conversation ID: ${this.conversationId}`);let r=new Headers;e.forEach((i,s)=>{s.toLowerCase()!=="authorization"&&s.toLowerCase()!==he.conversationIdHeaderKey.toLowerCase()&&r.set(s,i)}),J.debug("Headers received:",r)}async*startConversationAsync(e=!0){let r=ur(this.settings),n={emitStartConversationEvent:e};J.info("Starting conversation ..."),yield*this.postRequestAsync(r,n,"POST")}async*askQuestionAsync(e,r=this.conversationId){let o={type:"message",text:e,conversation:{id:r}},i=Xt.Activity.fromObject(o);yield*this.sendActivity(i)}async*sendActivity(e,r=this.conversationId){var s,a;let n=(a=(s=e.conversation)==null?void 0:s.id)!=null?a:r,o=ur(this.settings,n),i=new Mr(e);J.info("Sending activity...",e),yield*this.postRequestAsync(o,i,"POST")}};he.conversationIdHeaderKey="x-ms-conversationid",he.islandExperimentalUrlHeaderKey="x-ms-d2e-experimental",he.scopeFromSettings=xo;var is=he;var R=[];for(let t=0;t<256;++t)R.push((t+256).toString(16).slice(1));function as(t,e=0){return(R[t[e+0]]+R[t[e+1]]+R[t[e+2]]+R[t[e+3]]+"-"+R[t[e+4]]+R[t[e+5]]+"-"+R[t[e+6]]+R[t[e+7]]+"-"+R[t[e+8]]+R[t[e+9]]+"-"+R[t[e+10]]+R[t[e+11]]+R[t[e+12]]+R[t[e+13]]+R[t[e+14]]+R[t[e+15]]).toLowerCase()}var Bn,Ed=new Uint8Array(16);function Kn(){if(!Bn){if(typeof crypto=="undefined"||!crypto.getRandomValues)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");Bn=crypto.getRandomValues.bind(crypto)}return Bn(Ed)}var Ud=typeof crypto!="undefined"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto),Gn={randomUUID:Ud};function Rd(t,e,r){var o,i,s;if(Gn.randomUUID&&!e&&!t)return Gn.randomUUID();t=t||{};let n=(s=(i=t.random)!=null?i:(o=t.rng)==null?void 0:o.call(t))!=null?s:Kn();if(n.length<16)throw new Error("Random bytes length must be >= 16");if(n[6]=n[6]&15|64,n[8]=n[8]&63|128,e){if(r=r||0,r<0||r+16>e.length)throw new RangeError(`UUID byte range ${r}:${r+15} is out of buffer bounds`);for(let a=0;a<16;++a)e[r+a]=n[a];return e}return as(n)}var Jn=Rd;var ws=Et(Hn());var Yn=function(t,e){return Yn=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(r,n){r.__proto__=n}||function(r,n){for(var o in n)Object.prototype.hasOwnProperty.call(n,o)&&(r[o]=n[o])},Yn(t,e)};function Ce(t,e){if(typeof e!="function"&&e!==null)throw new TypeError("Class extends value "+String(e)+" is not a constructor or null");Yn(t,e);function r(){this.constructor=t}t.prototype=e===null?Object.create(e):(r.prototype=e.prototype,new r)}function Qt(t){var e=typeof Symbol=="function"&&Symbol.iterator,r=e&&t[e],n=0;if(r)return r.call(t);if(t&&typeof t.length=="number")return{next:function(){return t&&n>=t.length&&(t=void 0),{value:t&&t[n++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")}function Ct(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var n=r.call(t),o,i=[],s;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(a){s={error:a}}finally{try{o&&!o.done&&(r=n.return)&&r.call(n)}finally{if(s)throw s.error}}return i}function It(t,e,r){if(r||arguments.length===2)for(var n=0,o=e.length,i;n<o;n++)(i||!(n in e))&&(i||(i=Array.prototype.slice.call(e,0,n)),i[n]=e[n]);return t.concat(i||Array.prototype.slice.call(e))}function Y(t){return typeof t=="function"}function Dr(t){var e=function(n){Error.call(n),n.stack=new Error().stack},r=t(e);return r.prototype=Object.create(Error.prototype),r.prototype.constructor=r,r}var zr=Dr(function(t){return function(r){t(this),this.message=r?r.length+` errors occurred during unsubscription:
6
6
  `+r.map(function(n,o){return o+1+") "+n.toString()}).join(`
7
7
  `):"",this.name="UnsubscriptionError",this.errors=r}});function er(t,e){if(t){var r=t.indexOf(e);0<=r&&t.splice(r,1)}}var Tt=(function(){function t(e){this.initialTeardown=e,this.closed=!1,this._parentage=null,this._finalizers=null}return t.prototype.unsubscribe=function(){var e,r,n,o,i;if(!this.closed){this.closed=!0;var s=this._parentage;if(s)if(this._parentage=null,Array.isArray(s))try{for(var a=Qt(s),d=a.next();!d.done;d=a.next()){var l=d.value;l.remove(this)}}catch(g){e={error:g}}finally{try{d&&!d.done&&(r=a.return)&&r.call(a)}finally{if(e)throw e.error}}else s.remove(this);var f=this.initialTeardown;if(Y(f))try{f()}catch(g){i=g instanceof zr?g.errors:[g]}var m=this._finalizers;if(m){this._finalizers=null;try{for(var _=Qt(m),T=_.next();!T.done;T=_.next()){var O=T.value;try{cs(O)}catch(g){i=i!=null?i:[],g instanceof zr?i=It(It([],Ct(i)),Ct(g.errors)):i.push(g)}}}catch(g){n={error:g}}finally{try{T&&!T.done&&(o=_.return)&&o.call(_)}finally{if(n)throw n.error}}}if(i)throw new zr(i)}},t.prototype.add=function(e){var r;if(e&&e!==this)if(this.closed)cs(e);else{if(e instanceof t){if(e.closed||e._hasParent(this))return;e._addParent(this)}(this._finalizers=(r=this._finalizers)!==null&&r!==void 0?r:[]).push(e)}},t.prototype._hasParent=function(e){var r=this._parentage;return r===e||Array.isArray(r)&&r.includes(e)},t.prototype._addParent=function(e){var r=this._parentage;this._parentage=Array.isArray(r)?(r.push(e),r):r?[r,e]:e},t.prototype._removeParent=function(e){var r=this._parentage;r===e?this._parentage=null:Array.isArray(r)&&er(r,e)},t.prototype.remove=function(e){var r=this._finalizers;r&&er(r,e),e instanceof t&&e._removeParent(this)},t.EMPTY=(function(){var e=new t;return e.closed=!0,e})(),t})();var Xn=Tt.EMPTY;function Lr(t){return t instanceof Tt||t&&"closed"in t&&Y(t.remove)&&Y(t.add)&&Y(t.unsubscribe)}function cs(t){Y(t)?t():t.unsubscribe()}var ee={onUnhandledError:null,onStoppedNotification:null,Promise:void 0,useDeprecatedSynchronousErrorHandling:!1,useDeprecatedNextContext:!1};var St={setTimeout:function(t,e){for(var r=[],n=2;n<arguments.length;n++)r[n-2]=arguments[n];var o=St.delegate;return o!=null&&o.setTimeout?o.setTimeout.apply(o,It([t,e],Ct(r))):setTimeout.apply(void 0,It([t,e],Ct(r)))},clearTimeout:function(t){var e=St.delegate;return((e==null?void 0:e.clearTimeout)||clearTimeout)(t)},delegate:void 0};function us(t){St.setTimeout(function(){var e=ee.onUnhandledError;if(e)e(t);else throw t})}function Qn(){}var ds=(function(){return eo("C",void 0,void 0)})();function ls(t){return eo("E",void 0,t)}function fs(t){return eo("N",t,void 0)}function eo(t,e,r){return{kind:t,value:e,error:r}}var Ke=null;function At(t){if(ee.useDeprecatedSynchronousErrorHandling){var e=!Ke;if(e&&(Ke={errorThrown:!1,error:null}),t(),e){var r=Ke,n=r.errorThrown,o=r.error;if(Ke=null,n)throw o}}else t()}function ps(t){ee.useDeprecatedSynchronousErrorHandling&&Ke&&(Ke.errorThrown=!0,Ke.error=t)}var no=(function(t){Ce(e,t);function e(r){var n=t.call(this)||this;return n.isStopped=!1,r?(n.destination=r,Lr(r)&&r.add(n)):n.destination=zd,n}return e.create=function(r,n,o){return new Fr(r,n,o)},e.prototype.next=function(r){this.isStopped?ro(fs(r),this):this._next(r)},e.prototype.error=function(r){this.isStopped?ro(ls(r),this):(this.isStopped=!0,this._error(r))},e.prototype.complete=function(){this.isStopped?ro(ds,this):(this.isStopped=!0,this._complete())},e.prototype.unsubscribe=function(){this.closed||(this.isStopped=!0,t.prototype.unsubscribe.call(this),this.destination=null)},e.prototype._next=function(r){this.destination.next(r)},e.prototype._error=function(r){try{this.destination.error(r)}finally{this.unsubscribe()}},e.prototype._complete=function(){try{this.destination.complete()}finally{this.unsubscribe()}},e})(Tt);var Md=Function.prototype.bind;function to(t,e){return Md.call(t,e)}var Nd=(function(){function t(e){this.partialObserver=e}return t.prototype.next=function(e){var r=this.partialObserver;if(r.next)try{r.next(e)}catch(n){qr(n)}},t.prototype.error=function(e){var r=this.partialObserver;if(r.error)try{r.error(e)}catch(n){qr(n)}else qr(e)},t.prototype.complete=function(){var e=this.partialObserver;if(e.complete)try{e.complete()}catch(r){qr(r)}},t})(),Fr=(function(t){Ce(e,t);function e(r,n,o){var i=t.call(this)||this,s;if(Y(r)||!r)s={next:r!=null?r:void 0,error:n!=null?n:void 0,complete:o!=null?o:void 0};else{var a;i&&ee.useDeprecatedNextContext?(a=Object.create(r),a.unsubscribe=function(){return i.unsubscribe()},s={next:r.next&&to(r.next,a),error:r.error&&to(r.error,a),complete:r.complete&&to(r.complete,a)}):s=r}return i.destination=new Nd(s),i}return e})(no);function qr(t){ee.useDeprecatedSynchronousErrorHandling?ps(t):us(t)}function Dd(t){throw t}function ro(t,e){var r=ee.onStoppedNotification;r&&St.setTimeout(function(){return r(t,e)})}var zd={closed:!0,next:Qn,error:Dd,complete:Qn};var hs=(function(){return typeof Symbol=="function"&&Symbol.observable||"@@observable"})();function ms(t){return t}function ys(t){return t.length===0?ms:t.length===1?t[0]:function(r){return t.reduce(function(n,o){return o(n)},r)}}var Ot=(function(){function t(e){e&&(this._subscribe=e)}return t.prototype.lift=function(e){var r=new t;return r.source=this,r.operator=e,r},t.prototype.subscribe=function(e,r,n){var o=this,i=qd(e)?e:new Fr(e,r,n);return At(function(){var s=o,a=s.operator,d=s.source;i.add(a?a.call(i,d):d?o._subscribe(i):o._trySubscribe(i))}),i},t.prototype._trySubscribe=function(e){try{return this._subscribe(e)}catch(r){e.error(r)}},t.prototype.forEach=function(e,r){var n=this;return r=vs(r),new r(function(o,i){var s=new Fr({next:function(a){try{e(a)}catch(d){i(d),s.unsubscribe()}},error:i,complete:o});n.subscribe(s)})},t.prototype._subscribe=function(e){var r;return(r=this.source)===null||r===void 0?void 0:r.subscribe(e)},t.prototype[hs]=function(){return this},t.prototype.pipe=function(){for(var e=[],r=0;r<arguments.length;r++)e[r]=arguments[r];return ys(e)(this)},t.prototype.toPromise=function(e){var r=this;return e=vs(e),new e(function(n,o){var i;r.subscribe(function(s){return i=s},function(s){return o(s)},function(){return n(i)})})},t.create=function(e){return new t(e)},t})();function vs(t){var e;return(e=t!=null?t:ee.Promise)!==null&&e!==void 0?e:Promise}function Ld(t){return t&&Y(t.next)&&Y(t.error)&&Y(t.complete)}function qd(t){return t&&t instanceof no||Ld(t)&&Lr(t)}var gs=Dr(function(t){return function(){t(this),this.name="ObjectUnsubscribedError",this.message="object unsubscribed"}});var oo=(function(t){Ce(e,t);function e(){var r=t.call(this)||this;return r.closed=!1,r.currentObservers=null,r.observers=[],r.isStopped=!1,r.hasError=!1,r.thrownError=null,r}return e.prototype.lift=function(r){var n=new _s(this,this);return n.operator=r,n},e.prototype._throwIfClosed=function(){if(this.closed)throw new gs},e.prototype.next=function(r){var n=this;At(function(){var o,i;if(n._throwIfClosed(),!n.isStopped){n.currentObservers||(n.currentObservers=Array.from(n.observers));try{for(var s=Qt(n.currentObservers),a=s.next();!a.done;a=s.next()){var d=a.value;d.next(r)}}catch(l){o={error:l}}finally{try{a&&!a.done&&(i=s.return)&&i.call(s)}finally{if(o)throw o.error}}}})},e.prototype.error=function(r){var n=this;At(function(){if(n._throwIfClosed(),!n.isStopped){n.hasError=n.isStopped=!0,n.thrownError=r;for(var o=n.observers;o.length;)o.shift().error(r)}})},e.prototype.complete=function(){var r=this;At(function(){if(r._throwIfClosed(),!r.isStopped){r.isStopped=!0;for(var n=r.observers;n.length;)n.shift().complete()}})},e.prototype.unsubscribe=function(){this.isStopped=this.closed=!0,this.observers=this.currentObservers=null},Object.defineProperty(e.prototype,"observed",{get:function(){var r;return((r=this.observers)===null||r===void 0?void 0:r.length)>0},enumerable:!1,configurable:!0}),e.prototype._trySubscribe=function(r){return this._throwIfClosed(),t.prototype._trySubscribe.call(this,r)},e.prototype._subscribe=function(r){return this._throwIfClosed(),this._checkFinalizedStatuses(r),this._innerSubscribe(r)},e.prototype._innerSubscribe=function(r){var n=this,o=this,i=o.hasError,s=o.isStopped,a=o.observers;return i||s?Xn:(this.currentObservers=null,a.push(r),new Tt(function(){n.currentObservers=null,er(a,r)}))},e.prototype._checkFinalizedStatuses=function(r){var n=this,o=n.hasError,i=n.thrownError,s=n.isStopped;o?r.error(i):s&&r.complete()},e.prototype.asObservable=function(){var r=new Ot;return r.source=this,r},e.create=function(r,n){return new _s(r,n)},e})(Ot);var _s=(function(t){Ce(e,t);function e(r,n){var o=t.call(this)||this;return o.destination=r,o.source=n,o}return e.prototype.next=function(r){var n,o;(o=(n=this.destination)===null||n===void 0?void 0:n.next)===null||o===void 0||o.call(n,r)},e.prototype.error=function(r){var n,o;(o=(n=this.destination)===null||n===void 0?void 0:n.error)===null||o===void 0||o.call(n,r)},e.prototype.complete=function(){var r,n;(n=(r=this.destination)===null||r===void 0?void 0:r.complete)===null||n===void 0||n.call(r)},e.prototype._subscribe=function(r){var n,o;return(o=(n=this.source)===null||n===void 0?void 0:n.subscribe(r))!==null&&o!==void 0?o:Xn},e})(oo);var io=(function(t){Ce(e,t);function e(r){var n=t.call(this)||this;return n._value=r,n}return Object.defineProperty(e.prototype,"value",{get:function(){return this.getValue()},enumerable:!1,configurable:!0}),e.prototype._subscribe=function(r){var n=t.prototype._subscribe.call(this,r);return!n.closed&&r.next(this._value),n},e.prototype.getValue=function(){var r=this,n=r.hasError,o=r.thrownError,i=r._value;if(n)throw o;return this._throwIfClosed(),i},e.prototype.next=function(r){t.prototype.next.call(this,this._value=r)},e})(oo);var Cs=Et(Mt()),me=(0,Cs.debug)("copilot-studio:webchat"),bs=class{static createConnection(e,r){me.info("--> Creating connection between Copilot Studio and WebChat ...");let n=0,o,i,s=new io(0),a=xs(async f=>{if(o=f,s.value<2){s.next(2);return}me.debug("--> Connection established."),l();for await(let m of e.startConversationAsync())delete m.replyToId,i=m.conversation,d(m)}),d=f=>{let m={...f,timestamp:new Date().toISOString(),channelData:{...f.channelData,"webchat:sequence-id":n}};n++,me.debug(`Notify '${m.type}' activity to WebChat:`,m),o==null||o.next(m)},l=()=>{if(!(r!=null&&r.showTyping))return;let f=i?{id:i.id,name:i.name}:{id:"agent",name:"Agent"};d({type:"typing",from:f})};return{connectionStatus$:s,activity$:a,postActivity(f){if(me.info("--> Preparing to send activity to Copilot Studio ..."),!f)throw new Error("Activity cannot be null.");if(!o)throw new Error("Activity subscriber is not initialized.");return xs(async m=>{try{me.info("--> Sending activity to Copilot Studio ...");let _=ws.Activity.fromObject({...f,id:Jn(),attachments:await Fd(f)});d(_),l(),m.next(_.id);for await(let T of e.sendActivity(_))d(T),me.info("<-- Activity received correctly from Copilot Studio.");m.complete()}catch(_){me.error("Error sending Activity to Copilot Studio:",_),m.error(_)}})},end(){me.info("--> Ending connection between Copilot Studio and WebChat ..."),s.complete(),o&&(o.complete(),o=void 0)}}}};async function Fd(t){var r;if(t.type!=="message"||!((r=t.attachments)!=null&&r.length))return t.attachments||[];let e=[];for(let n of t.attachments){let o=await Vd(n);e.push(o)}return e}async function Vd(t){let e=t.contentUrl;if(!(e!=null&&e.startsWith("blob:")))return t;try{let r=await fetch(e);if(!r.ok)throw new Error(`Failed to fetch blob URL: ${r.status} ${r.statusText}`);let n=await r.blob(),o=await n.arrayBuffer(),i=$d(o);e=`data:${n.type};base64,${i}`}catch(r){e=t.contentUrl,me.error("Error processing blob attachment:",e,r)}return{...t,contentUrl:e}}function $d(t){let e=typeof globalThis.Buffer=="function"?globalThis.Buffer:void 0;if(e&&typeof e.from=="function")return e.from(t).toString("base64");let r="";for(let n of new Uint8Array(t))r+=String.fromCharCode(n);return btoa(r)}function xs(t){return new Ot(e=>{Promise.resolve(t(e)).catch(r=>e.error(r))})}export{Ut as AgentType,Hr as ConnectionSettings,is as CopilotStudioClient,bs as CopilotStudioWebChat,Mr as ExecuteTurnRequest,Rt as PowerPlatformCloud,ur as getCopilotStudioConnectionUrl,xo as getTokenAudience,Jd as loadCopilotStudioConnectionSettingsFromEnv};
8
8
  //# sourceMappingURL=browser.mjs.map