@microsoft/agents-copilotstudio-client 1.3.1 → 1.4.0-beta.3.g02b192de00
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 +2 -2
- package/dist/src/browser.mjs +1 -1
- package/dist/src/browser.mjs.map +2 -2
- package/package.json +2 -2
package/dist/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@microsoft/agents-copilotstudio-client",
|
|
3
|
-
"version": "1.3.
|
|
3
|
+
"version": "1.4.0-beta.3.g02b192de00",
|
|
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.3.
|
|
30
|
+
"@microsoft/agents-activity": "1.4.0-beta.3.g02b192de00",
|
|
31
31
|
"eventsource-client": "^1.2.0",
|
|
32
32
|
"rxjs": "7.8.2",
|
|
33
33
|
"uuid": "^11.1.0"
|
package/dist/src/browser.mjs
CHANGED
|
@@ -2,7 +2,7 @@ var ks=Object.create;var mo=Object.defineProperty;var Us=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 "${v.length>20?`${v.slice(0,20)}\u2026`:v}"`,{type:"unknown-field",field:v,value:S,line:A}));break}}function C(){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(v={}){i&&v.consume&&m(i),s=!0,a=void 0,d="",l="",i=""}return{feed:f,reset:O}}function Ls(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 vo="connecting",zs="open",Xr="closed",rr=()=>{};function qs(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}=Fs(r),m={...r.headers},g=[],C=n?[n]:[],O=U=>C.forEach(se=>se(U)),v=yo({onEvent:Es,onRetry:js,onComment:o}),S,A=l.toString(),P=new AbortController,R=f,V=2e3,ie,$=Xr;return Y(),{close:Oe,connect:Y,[Symbol.iterator]:()=>{throw new Error("EventSource does not support synchronous iteration. Use `for await` instead.")},[Symbol.asyncIterator]:Kr,get lastEventId(){return R},get url(){return A},get readyState(){return $}};function Y(){S||($=vo,P=new AbortController,S=d(l,Zs()).then(Ps).catch(U=>{S=null,!(U.name==="AbortError"||U.type==="aborted"||P.signal.aborted)&&fo()}))}function Oe(){$=Xr,P.abort(),v.reset(),clearTimeout(ie),g.forEach(U=>U())}function Kr(){let U=[],se=[];function Zt(){return new Promise(H=>{let ae=se.shift();ae?H({value:ae,done:!1}):U.push(H)})}let et=function(H){let ae=U.shift();ae?ae({value:H,done:!1}):se.push(H)};function Pe(){for(C.splice(C.indexOf(et),1);U.shift(););for(;se.shift(););}function kt(){let H=U.shift();H&&(H({done:!0,value:void 0}),Pe())}return g.push(kt),C.push(et),{next(){return $===Xr?this.return():Zt()},return(){return Pe(),Promise.resolve({done:!0,value:void 0})},throw(H){return Pe(),Promise.reject(H)},[Symbol.asyncIterator](){return this}}}function fo(){a({delay:V}),!P.signal.aborted&&($=vo,ie=setTimeout(Y,V))}async function Ps(U){i(),v.reset();let{body:se,redirected:Zt,status:et}=U;if(et===204){s(),Oe();return}if(!se)throw new Error("Missing response body");Zt&&(A=U.url);let Pe=e(se),kt=new TextDecoder,H=Pe.getReader(),ae=!0;$=zs;do{let{done:po,value:ho}=await H.read();ho&&v.feed(kt.decode(ho,{stream:!po})),po&&(ae=!1,S=null,v.reset(),fo(),s())}while(ae)}function Es(U){typeof U.id=="string"&&(R=U.id),O(U)}function js(U){V=U}function Zs(){let{mode:U,credentials:se,body:Zt,method:et,redirect:Pe,referrer:kt,referrerPolicy:H}=r,ae={Accept:"text/event-stream",...m,...R?{"Last-Event-ID":R}:void 0};return{mode:U,credentials:se,body:Zt,method:et,redirect:Pe,referrer:kt,referrerPolicy:H,headers:ae,cache:"no-store",signal:P.signal}}}function Fs(t){let e=t.fetch||globalThis.fetch;if(!Vs(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 Vs(t){return typeof t=="function"}var $s={getStream:Hs};function go(t){return qs(t,$s)}function Hs(t){if(!(t instanceof ReadableStream))throw new Error("Invalid stream, expected a web ReadableStream");return t}var To=Ut(Mt());var sr=class{constructor(e){this.API_VERSION="2022-03-01-preview";let r="schema"in e?e.schema:e.identifier,n=e.host;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 ot=(0,To.debug)("copilot-studio:power-platform");function ur(t,e){var d,l,f,m,g,C,O,v;let r=((d=t.schemaName)==null?void 0:d.trim())||((l=t.agentIdentifier)==null?void 0:l.trim());if(!((f=t.directConnectUrl)!=null&&f.trim())&&(!((m=t.environmentId)!=null&&m.trim())||!(r!=null&&r.trim())))throw new Error("Either directConnectUrl OR both environmentId and schemaName/agentIdentifier must be provided");if((g=t.directConnectUrl)!=null&&g.trim()){if(ot.debug(`Using direct connection: ${t.directConnectUrl}`),!Dt(t.directConnectUrl))throw new Error("directConnectUrl must be a valid URL");return t.directConnectUrl.toLowerCase().includes("tenants/00000000-0000-0000-0000-000000000000")?(ot.warn(`Direct connection cannot be used, forcing default settings flow. Tenant ID is missing in the URL: ${t.directConnectUrl}`),ur({...t,directConnectUrl:""},e)):ca(t.directConnectUrl,e).href}let n=(C=t.cloud)!=null?C:"Prod",o=(O=t.copilotAgentType)!=null?O:"Published";if(ot.debug(`Using cloud setting: ${n}`),ot.debug(`Using agent type: ${o}`),n==="Other")if((v=t.customPowerPlatformCloud)!=null&&v.trim())if(Dt(t.customPowerPlatformCloud))ot.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 i=ua(n,t.environmentId,t.customPowerPlatformCloud),a={Published:()=>new ar({host:i,schema:r}),Prebuilt:()=>new sr({host:i,schema:r})}[o]().getConversationUrl(e);return ot.debug(`Generated Copilot Studio connection URL: ${a}`),a}function So(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&&Dt(r))e="Other";else if(t!=null&&t.customPowerPlatformCloud&&Dt(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&&Dt(n)){if(Io(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(Io(new URL(n)),"")}/.default`}else throw new Error("DirectConnectUrl must be provided when DirectConnectUrl is set")}function Dt(t){try{let e=t.startsWith("http")?t:`https://${t}`;return!!new URL(e)}catch{return!1}}function ca(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 ua(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=da(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 da(t){switch(t){case"FirstRelease":case"Prod":return 2;default:return 1}}function Io(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 Tt=Ut(Yn());var qr=class{constructor(e){this.activity=e}};var ls=Ut(Mt());var us="1.3.1";var Fr={};var G=(0,ls.debug)("copilot-studio:client"),ve=class ve{constructor(e,r){this.conversationId="";this.settings=e,this.token=r}async*postRequestAsync(e,r,n="POST"){var s,a,d,l,f,m,g,C,O,v;G.debug(`>>> SEND TO ${e}`);let o=new Map,i=go({url:e,headers:{Authorization:`Bearer ${this.token}`,"User-Agent":ve.getProductInfo(),"Content-Type":"application/json",Accept:"text/event-stream"},body:r?JSON.stringify(r):void 0,method:n,fetch:async(S,A)=>{let P=await fetch(S,A);return this.processResponseHeaders(P.headers),P}});try{for await(let{data:S,event:A}of i){if(S&&A==="activity")try{let P=Tt.Activity.fromJson(S),R=(s=P.entities)==null?void 0:s.find(V=>V.type==="streaminfo"&&V.streamType==="streaming");switch(P.type){case Tt.ActivityTypes.Message:this.conversationId.trim()||(this.conversationId=(d=(a=P.conversation)==null?void 0:a.id)!=null?d:"",G.debug(`Conversation ID: ${this.conversationId}`)),yield P;break;case Tt.ActivityTypes.Typing:if(G.debug(`Activity type: ${P.type}`),R||((l=P.channelData)==null?void 0:l.streamType)==="streaming"){let V=(f=P.text)!=null?f:"",ie=(g=R==null?void 0:R.streamId)!=null?g:(m=P.channelData)==null?void 0:m.streamId,$=(O=R==null?void 0:R.streamSequence)!=null?O:(C=P.channelData)==null?void 0:C.streamSequence;if(ie&&$){if(o.has(ie)){let Y=o.get(ie);Y.push({text:V,sequence:$}),o.set(ie,Y)}else o.set(ie,[{text:V,sequence:$}]);P.text=((v=o.get(ie))==null?void 0:v.sort((Y,Oe)=>Y.sequence-Oe.sequence).map(Y=>Y.text).join(""))||""}}yield P;break;default:G.debug(`Activity type: ${P.type}`),yield P;break}}catch(P){G.error("Failed to parse activity:",P)}else if(A==="end"){G.debug("Stream complete");break}if(i.readyState==="closed"){G.debug("Connection closed");break}}}finally{i.close()}}static getProductInfo(){let e=`CopilotStudioClient.agents-sdk-js/${us}`,r;return typeof window!="undefined"&&window.navigator?r=`${e} ${navigator.userAgent}`:r=`${e} nodejs/${process.version} ${Fr.platform()}-${Fr.arch()}/${Fr.release()}`,G.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(ve.islandExperimentalUrlHeaderKey);i&&(this.settings.directConnectUrl=i,G.debug(`Island Experimental URL: ${i}`))}this.conversationId=(o=e==null?void 0:e.get(ve.conversationIdHeaderKey))!=null?o:"",this.conversationId&&G.debug(`Conversation ID: ${this.conversationId}`);let r=new Headers;e.forEach((i,s)=>{s.toLowerCase()!=="authorization"&&s.toLowerCase()!==ve.conversationIdHeaderKey.toLowerCase()&&r.set(s,i)}),G.debug("Headers received:",r)}async*startConversationStreaming(e=!0){let r=ur(this.settings),n={emitStartConversationEvent:e};G.info("Starting conversation ..."),yield*this.postRequestAsync(r,n,"POST")}async*sendActivityStreaming(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 qr(e);G.info("Sending activity...",e),yield*this.postRequestAsync(o,i,"POST")}async startConversationAsync(e=!0){let r=[];for await(let n of this.startConversationStreaming(e))r.push(n);return r}async askQuestionAsync(e,r){let o={id:r!=null&&r.trim()?r:this.conversationId},i={type:"message",text:e,conversation:o},s=Tt.Activity.fromObject(i),a=[];for await(let d of this.sendActivityStreaming(s,r))a.push(d);return a}async sendActivity(e,r=this.conversationId){let n=[];for await(let o of this.sendActivityStreaming(e,r))n.push(o);return n}};ve.conversationIdHeaderKey="x-ms-conversationid",ve.islandExperimentalUrlHeaderKey="x-ms-d2e-experimental",ve.scopeFromSettings=So;var ds=ve;var M=[];for(let t=0;t<256;++t)M.push((t+256).toString(16).slice(1));function fs(t,e=0){return(M[t[e+0]]+M[t[e+1]]+M[t[e+2]]+M[t[e+3]]+"-"+M[t[e+4]]+M[t[e+5]]+"-"+M[t[e+6]]+M[t[e+7]]+"-"+M[t[e+8]]+M[t[e+9]]+"-"+M[t[e+10]]+M[t[e+11]]+M[t[e+12]]+M[t[e+13]]+M[t[e+14]]+M[t[e+15]]).toLowerCase()}var Xn,Nd=new Uint8Array(16);function Qn(){if(!Xn){if(typeof crypto=="undefined"||!crypto.getRandomValues)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");Xn=crypto.getRandomValues.bind(crypto)}return Xn(Nd)}var Md=typeof crypto!="undefined"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto),eo={randomUUID:Md};function Dd(t,e,r){var o,i,s;if(eo.randomUUID&&!e&&!t)return eo.randomUUID();t=t||{};let n=(s=(i=t.random)!=null?i:(o=t.rng)==null?void 0:o.call(t))!=null?s:Qn();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 fs(n)}var to=Dd;var As=Ut(Yn());var ro=function(t,e){return ro=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])},ro(t,e)};function Ae(t,e){if(typeof e!="function"&&e!==null)throw new TypeError("Class extends value "+String(e)+" is not a constructor or null");ro(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 St(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 At(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 te(t){return typeof t=="function"}function Vr(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 $r=Vr(function(t){return function(r){t(this),this.message=r?r.length+` errors occurred during unsubscription:
|
|
5
|
+
`&&n++}}return[e,r]}var vo="connecting",zs="open",Xr="closed",rr=()=>{};function qs(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}=Fs(r),m={...r.headers},g=[],C=n?[n]:[],O=U=>C.forEach(se=>se(U)),v=yo({onEvent:Es,onRetry:js,onComment:o}),S,A=l.toString(),P=new AbortController,R=f,V=2e3,ie,$=Xr;return Y(),{close:Oe,connect:Y,[Symbol.iterator]:()=>{throw new Error("EventSource does not support synchronous iteration. Use `for await` instead.")},[Symbol.asyncIterator]:Kr,get lastEventId(){return R},get url(){return A},get readyState(){return $}};function Y(){S||($=vo,P=new AbortController,S=d(l,Zs()).then(Ps).catch(U=>{S=null,!(U.name==="AbortError"||U.type==="aborted"||P.signal.aborted)&&fo()}))}function Oe(){$=Xr,P.abort(),v.reset(),clearTimeout(ie),g.forEach(U=>U())}function Kr(){let U=[],se=[];function Zt(){return new Promise(H=>{let ae=se.shift();ae?H({value:ae,done:!1}):U.push(H)})}let et=function(H){let ae=U.shift();ae?ae({value:H,done:!1}):se.push(H)};function Pe(){for(C.splice(C.indexOf(et),1);U.shift(););for(;se.shift(););}function kt(){let H=U.shift();H&&(H({done:!0,value:void 0}),Pe())}return g.push(kt),C.push(et),{next(){return $===Xr?this.return():Zt()},return(){return Pe(),Promise.resolve({done:!0,value:void 0})},throw(H){return Pe(),Promise.reject(H)},[Symbol.asyncIterator](){return this}}}function fo(){a({delay:V}),!P.signal.aborted&&($=vo,ie=setTimeout(Y,V))}async function Ps(U){i(),v.reset();let{body:se,redirected:Zt,status:et}=U;if(et===204){s(),Oe();return}if(!se)throw new Error("Missing response body");Zt&&(A=U.url);let Pe=e(se),kt=new TextDecoder,H=Pe.getReader(),ae=!0;$=zs;do{let{done:po,value:ho}=await H.read();ho&&v.feed(kt.decode(ho,{stream:!po})),po&&(ae=!1,S=null,v.reset(),fo(),s())}while(ae)}function Es(U){typeof U.id=="string"&&(R=U.id),O(U)}function js(U){V=U}function Zs(){let{mode:U,credentials:se,body:Zt,method:et,redirect:Pe,referrer:kt,referrerPolicy:H}=r,ae={Accept:"text/event-stream",...m,...R?{"Last-Event-ID":R}:void 0};return{mode:U,credentials:se,body:Zt,method:et,redirect:Pe,referrer:kt,referrerPolicy:H,headers:ae,cache:"no-store",signal:P.signal}}}function Fs(t){let e=t.fetch||globalThis.fetch;if(!Vs(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 Vs(t){return typeof t=="function"}var $s={getStream:Hs};function go(t){return qs(t,$s)}function Hs(t){if(!(t instanceof ReadableStream))throw new Error("Invalid stream, expected a web ReadableStream");return t}var To=Ut(Mt());var sr=class{constructor(e){this.API_VERSION="2022-03-01-preview";let r="schema"in e?e.schema:e.identifier,n=e.host;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 ot=(0,To.debug)("copilot-studio:power-platform");function ur(t,e){var d,l,f,m,g,C,O,v;let r=((d=t.schemaName)==null?void 0:d.trim())||((l=t.agentIdentifier)==null?void 0:l.trim());if(!((f=t.directConnectUrl)!=null&&f.trim())&&(!((m=t.environmentId)!=null&&m.trim())||!(r!=null&&r.trim())))throw new Error("Either directConnectUrl OR both environmentId and schemaName/agentIdentifier must be provided");if((g=t.directConnectUrl)!=null&&g.trim()){if(ot.debug(`Using direct connection: ${t.directConnectUrl}`),!Dt(t.directConnectUrl))throw new Error("directConnectUrl must be a valid URL");return t.directConnectUrl.toLowerCase().includes("tenants/00000000-0000-0000-0000-000000000000")?(ot.warn(`Direct connection cannot be used, forcing default settings flow. Tenant ID is missing in the URL: ${t.directConnectUrl}`),ur({...t,directConnectUrl:""},e)):ca(t.directConnectUrl,e).href}let n=(C=t.cloud)!=null?C:"Prod",o=(O=t.copilotAgentType)!=null?O:"Published";if(ot.debug(`Using cloud setting: ${n}`),ot.debug(`Using agent type: ${o}`),n==="Other")if((v=t.customPowerPlatformCloud)!=null&&v.trim())if(Dt(t.customPowerPlatformCloud))ot.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 i=ua(n,t.environmentId,t.customPowerPlatformCloud),a={Published:()=>new ar({host:i,schema:r}),Prebuilt:()=>new sr({host:i,schema:r})}[o]().getConversationUrl(e);return ot.debug(`Generated Copilot Studio connection URL: ${a}`),a}function So(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&&Dt(r))e="Other";else if(t!=null&&t.customPowerPlatformCloud&&Dt(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&&Dt(n)){if(Io(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(Io(new URL(n)),"")}/.default`}else throw new Error("DirectConnectUrl must be provided when DirectConnectUrl is set")}function Dt(t){try{let e=t.startsWith("http")?t:`https://${t}`;return!!new URL(e)}catch{return!1}}function ca(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 ua(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=da(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 da(t){switch(t){case"FirstRelease":case"Prod":return 2;default:return 1}}function Io(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 Tt=Ut(Yn());var qr=class{constructor(e){this.activity=e}};var ls=Ut(Mt());var us="1.4.0-beta.3.g02b192de00";var Fr={};var G=(0,ls.debug)("copilot-studio:client"),ve=class ve{constructor(e,r){this.conversationId="";this.settings=e,this.token=r}async*postRequestAsync(e,r,n="POST"){var s,a,d,l,f,m,g,C,O,v;G.debug(`>>> SEND TO ${e}`);let o=new Map,i=go({url:e,headers:{Authorization:`Bearer ${this.token}`,"User-Agent":ve.getProductInfo(),"Content-Type":"application/json",Accept:"text/event-stream"},body:r?JSON.stringify(r):void 0,method:n,fetch:async(S,A)=>{let P=await fetch(S,A);return this.processResponseHeaders(P.headers),P}});try{for await(let{data:S,event:A}of i){if(S&&A==="activity")try{let P=Tt.Activity.fromJson(S),R=(s=P.entities)==null?void 0:s.find(V=>V.type==="streaminfo"&&V.streamType==="streaming");switch(P.type){case Tt.ActivityTypes.Message:this.conversationId.trim()||(this.conversationId=(d=(a=P.conversation)==null?void 0:a.id)!=null?d:"",G.debug(`Conversation ID: ${this.conversationId}`)),yield P;break;case Tt.ActivityTypes.Typing:if(G.debug(`Activity type: ${P.type}`),R||((l=P.channelData)==null?void 0:l.streamType)==="streaming"){let V=(f=P.text)!=null?f:"",ie=(g=R==null?void 0:R.streamId)!=null?g:(m=P.channelData)==null?void 0:m.streamId,$=(O=R==null?void 0:R.streamSequence)!=null?O:(C=P.channelData)==null?void 0:C.streamSequence;if(ie&&$){if(o.has(ie)){let Y=o.get(ie);Y.push({text:V,sequence:$}),o.set(ie,Y)}else o.set(ie,[{text:V,sequence:$}]);P.text=((v=o.get(ie))==null?void 0:v.sort((Y,Oe)=>Y.sequence-Oe.sequence).map(Y=>Y.text).join(""))||""}}yield P;break;default:G.debug(`Activity type: ${P.type}`),yield P;break}}catch(P){G.error("Failed to parse activity:",P)}else if(A==="end"){G.debug("Stream complete");break}if(i.readyState==="closed"){G.debug("Connection closed");break}}}finally{i.close()}}static getProductInfo(){let e=`CopilotStudioClient.agents-sdk-js/${us}`,r;return typeof window!="undefined"&&window.navigator?r=`${e} ${navigator.userAgent}`:r=`${e} nodejs/${process.version} ${Fr.platform()}-${Fr.arch()}/${Fr.release()}`,G.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(ve.islandExperimentalUrlHeaderKey);i&&(this.settings.directConnectUrl=i,G.debug(`Island Experimental URL: ${i}`))}this.conversationId=(o=e==null?void 0:e.get(ve.conversationIdHeaderKey))!=null?o:"",this.conversationId&&G.debug(`Conversation ID: ${this.conversationId}`);let r=new Headers;e.forEach((i,s)=>{s.toLowerCase()!=="authorization"&&s.toLowerCase()!==ve.conversationIdHeaderKey.toLowerCase()&&r.set(s,i)}),G.debug("Headers received:",r)}async*startConversationStreaming(e=!0){let r=ur(this.settings),n={emitStartConversationEvent:e};G.info("Starting conversation ..."),yield*this.postRequestAsync(r,n,"POST")}async*sendActivityStreaming(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 qr(e);G.info("Sending activity...",e),yield*this.postRequestAsync(o,i,"POST")}async startConversationAsync(e=!0){let r=[];for await(let n of this.startConversationStreaming(e))r.push(n);return r}async askQuestionAsync(e,r){let o={id:r!=null&&r.trim()?r:this.conversationId},i={type:"message",text:e,conversation:o},s=Tt.Activity.fromObject(i),a=[];for await(let d of this.sendActivityStreaming(s,r))a.push(d);return a}async sendActivity(e,r=this.conversationId){let n=[];for await(let o of this.sendActivityStreaming(e,r))n.push(o);return n}};ve.conversationIdHeaderKey="x-ms-conversationid",ve.islandExperimentalUrlHeaderKey="x-ms-d2e-experimental",ve.scopeFromSettings=So;var ds=ve;var M=[];for(let t=0;t<256;++t)M.push((t+256).toString(16).slice(1));function fs(t,e=0){return(M[t[e+0]]+M[t[e+1]]+M[t[e+2]]+M[t[e+3]]+"-"+M[t[e+4]]+M[t[e+5]]+"-"+M[t[e+6]]+M[t[e+7]]+"-"+M[t[e+8]]+M[t[e+9]]+"-"+M[t[e+10]]+M[t[e+11]]+M[t[e+12]]+M[t[e+13]]+M[t[e+14]]+M[t[e+15]]).toLowerCase()}var Xn,Nd=new Uint8Array(16);function Qn(){if(!Xn){if(typeof crypto=="undefined"||!crypto.getRandomValues)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");Xn=crypto.getRandomValues.bind(crypto)}return Xn(Nd)}var Md=typeof crypto!="undefined"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto),eo={randomUUID:Md};function Dd(t,e,r){var o,i,s;if(eo.randomUUID&&!e&&!t)return eo.randomUUID();t=t||{};let n=(s=(i=t.random)!=null?i:(o=t.rng)==null?void 0:o.call(t))!=null?s:Qn();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 fs(n)}var to=Dd;var As=Ut(Yn());var ro=function(t,e){return ro=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])},ro(t,e)};function Ae(t,e){if(typeof e!="function"&&e!==null)throw new TypeError("Class extends value "+String(e)+" is not a constructor or null");ro(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 St(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 At(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 te(t){return typeof t=="function"}function Vr(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 $r=Vr(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 Ot=(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(v){e={error:v}}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(te(f))try{f()}catch(v){i=v instanceof $r?v.errors:[v]}var m=this._finalizers;if(m){this._finalizers=null;try{for(var g=Qt(m),C=g.next();!C.done;C=g.next()){var O=C.value;try{ps(O)}catch(v){i=i!=null?i:[],v instanceof $r?i=At(At([],St(i)),St(v.errors)):i.push(v)}}}catch(v){n={error:v}}finally{try{C&&!C.done&&(o=g.return)&&o.call(g)}finally{if(n)throw n.error}}}if(i)throw new $r(i)}},t.prototype.add=function(e){var r;if(e&&e!==this)if(this.closed)ps(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 no=Ot.EMPTY;function Hr(t){return t instanceof Ot||t&&"closed"in t&&te(t.remove)&&te(t.add)&&te(t.unsubscribe)}function ps(t){te(t)?t():t.unsubscribe()}var oe={onUnhandledError:null,onStoppedNotification:null,Promise:void 0,useDeprecatedSynchronousErrorHandling:!1,useDeprecatedNextContext:!1};var Pt={setTimeout:function(t,e){for(var r=[],n=2;n<arguments.length;n++)r[n-2]=arguments[n];var o=Pt.delegate;return o!=null&&o.setTimeout?o.setTimeout.apply(o,At([t,e],St(r))):setTimeout.apply(void 0,At([t,e],St(r)))},clearTimeout:function(t){var e=Pt.delegate;return((e==null?void 0:e.clearTimeout)||clearTimeout)(t)},delegate:void 0};function hs(t){Pt.setTimeout(function(){var e=oe.onUnhandledError;if(e)e(t);else throw t})}function oo(){}var ms=(function(){return io("C",void 0,void 0)})();function ys(t){return io("E",void 0,t)}function vs(t){return io("N",t,void 0)}function io(t,e,r){return{kind:t,value:e,error:r}}var Qe=null;function Et(t){if(oe.useDeprecatedSynchronousErrorHandling){var e=!Qe;if(e&&(Qe={errorThrown:!1,error:null}),t(),e){var r=Qe,n=r.errorThrown,o=r.error;if(Qe=null,n)throw o}}else t()}function gs(t){oe.useDeprecatedSynchronousErrorHandling&&Qe&&(Qe.errorThrown=!0,Qe.error=t)}var co=(function(t){Ae(e,t);function e(r){var n=t.call(this)||this;return n.isStopped=!1,r?(n.destination=r,Hr(r)&&r.add(n)):n.destination=Fd,n}return e.create=function(r,n,o){return new Br(r,n,o)},e.prototype.next=function(r){this.isStopped?ao(vs(r),this):this._next(r)},e.prototype.error=function(r){this.isStopped?ao(ys(r),this):(this.isStopped=!0,this._error(r))},e.prototype.complete=function(){this.isStopped?ao(ms,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})(Ot);var Ld=Function.prototype.bind;function so(t,e){return Ld.call(t,e)}var zd=(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){Wr(n)}},t.prototype.error=function(e){var r=this.partialObserver;if(r.error)try{r.error(e)}catch(n){Wr(n)}else Wr(e)},t.prototype.complete=function(){var e=this.partialObserver;if(e.complete)try{e.complete()}catch(r){Wr(r)}},t})(),Br=(function(t){Ae(e,t);function e(r,n,o){var i=t.call(this)||this,s;if(te(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&&oe.useDeprecatedNextContext?(a=Object.create(r),a.unsubscribe=function(){return i.unsubscribe()},s={next:r.next&&so(r.next,a),error:r.error&&so(r.error,a),complete:r.complete&&so(r.complete,a)}):s=r}return i.destination=new zd(s),i}return e})(co);function Wr(t){oe.useDeprecatedSynchronousErrorHandling?gs(t):hs(t)}function qd(t){throw t}function ao(t,e){var r=oe.onStoppedNotification;r&&Pt.setTimeout(function(){return r(t,e)})}var Fd={closed:!0,next:oo,error:qd,complete:oo};var _s=(function(){return typeof Symbol=="function"&&Symbol.observable||"@@observable"})();function bs(t){return t}function xs(t){return t.length===0?bs:t.length===1?t[0]:function(r){return t.reduce(function(n,o){return o(n)},r)}}var jt=(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=$d(e)?e:new Br(e,r,n);return Et(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=ws(r),new r(function(o,i){var s=new Br({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[_s]=function(){return this},t.prototype.pipe=function(){for(var e=[],r=0;r<arguments.length;r++)e[r]=arguments[r];return xs(e)(this)},t.prototype.toPromise=function(e){var r=this;return e=ws(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 ws(t){var e;return(e=t!=null?t:oe.Promise)!==null&&e!==void 0?e:Promise}function Vd(t){return t&&te(t.next)&&te(t.error)&&te(t.complete)}function $d(t){return t&&t instanceof co||Vd(t)&&Hr(t)}var Cs=Vr(function(t){return function(){t(this),this.name="ObjectUnsubscribedError",this.message="object unsubscribed"}});var uo=(function(t){Ae(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 Is(this,this);return n.operator=r,n},e.prototype._throwIfClosed=function(){if(this.closed)throw new Cs},e.prototype.next=function(r){var n=this;Et(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;Et(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;Et(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?no:(this.currentObservers=null,a.push(r),new Ot(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 jt;return r.source=this,r},e.create=function(r,n){return new Is(r,n)},e})(jt);var Is=(function(t){Ae(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:no},e})(uo);var lo=(function(t){Ae(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})(uo);var Os=Ut(Mt()),ge=(0,Os.debug)("copilot-studio:webchat");function Hd(t){let e=!1;return r=>{if(!e)return e=!0,t(r)}}var Ts=class{static createConnection(e,r){ge.info("--> Creating connection between Copilot Studio and WebChat ...");let n=0,o,i,s=new lo(0),a=Ss(async f=>{o=f;let m=Hd(async()=>{s.next(2),await Promise.resolve()});if(ge.debug("--> Connection established."),l(),s.value<2){for await(let g of e.startConversationStreaming())delete g.replyToId,!i&&g.conversation&&(i=g.conversation,await m()),d(g);await m()}}),d=f=>{let m={...f,timestamp:new Date().toISOString(),channelData:{...f.channelData,"webchat:sequence-id":n}};n++,ge.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(ge.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 Ss(async m=>{try{ge.info("--> Sending activity to Copilot Studio ...");let g=As.Activity.fromObject({...f,id:to(),attachments:await Wd(f)});d(g),l(),m.next(g.id);for await(let C of e.sendActivityStreaming(g))d(C),ge.info("<-- Activity received correctly from Copilot Studio.");m.complete()}catch(g){ge.error("Error sending Activity to Copilot Studio:",g),m.error(g)}})},end(){ge.info("--> Ending connection between Copilot Studio and WebChat ..."),s.complete(),o&&(o.complete(),o=void 0)}}}};async function Wd(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 Bd(n);e.push(o)}return e}async function Bd(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=Kd(o);e=`data:${n.type};base64,${i}`}catch(r){e=t.contentUrl,ge.error("Error processing blob attachment:",e,r)}return{...t,contentUrl:e}}function Kd(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 Ss(t){return new jt(e=>{Promise.resolve(t(e)).catch(r=>e.error(r))})}export{Rt as AgentType,Gr as ConnectionSettings,ds as CopilotStudioClient,Ts as CopilotStudioWebChat,qr as ExecuteTurnRequest,Nt as PowerPlatformCloud,ur as getCopilotStudioConnectionUrl,So as getTokenAudience,el as loadCopilotStudioConnectionSettingsFromEnv};
|
|
8
8
|
//# sourceMappingURL=browser.mjs.map
|