@cimulate/copilot-sdk 3.0.0 → 3.2.0

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/src/copilot.ts CHANGED
@@ -49,6 +49,10 @@ export default class CimulateCopilot<
49
49
  > {
50
50
  private socket: Socket;
51
51
  private sessionIdKey: string = "x-cimulate-copilot-session-id";
52
+ private reconnectAttempts = 0;
53
+ private maxReconnectAttempts = 5;
54
+ private maxReconnectDelay = 30000;
55
+ private reconnectTimeout?: ReturnType<typeof setTimeout>;
52
56
 
53
57
  constructor({
54
58
  apiKey,
@@ -87,25 +91,104 @@ export default class CimulateCopilot<
87
91
  this.socket = io(socketioEndpoint, deepmerge.all(options));
88
92
  }
89
93
 
94
+ private readonly handleConnectAck = (event: ConnectAck) => {
95
+ console.log("[Copilot SDK] Connect Ack:", event);
96
+ this.socket.auth = {
97
+ [this.sessionIdKey]: event.sessionId,
98
+ };
99
+ this.reconnectAttempts = 0;
100
+ };
101
+
102
+ private readonly handleDisconnect = (reason: Socket.DisconnectReason) => {
103
+ console.warn(`[Copilot SDK] Disconnected: ${reason}`);
104
+ if (reason !== "io client disconnect") {
105
+ console.log(`[Copilot SDK] Disconnected due to ${reason}. Attempting reconnect...`);
106
+ this.retryConnect();
107
+ }
108
+ };
109
+
110
+ private readonly handleConnectError = (err: Error) => {
111
+ console.error(`[Copilot SDK] Connect error: ${err.message}`);
112
+
113
+ if (err.message === "Invalid API Key") {
114
+ this.disconnect();
115
+ }
116
+
117
+ // Trigger reconnect logic with backoff
118
+ if (!this.socket.connected && !this.socket.active) {
119
+ console.log(`[Copilot SDK] Retrying connect attempt...`);
120
+ this.retryConnect();
121
+ }
122
+ };
123
+
124
+ private readonly offInternalHandlers = () => {
125
+ this.socket.off("connect_ack", this.handleConnectAck);
126
+ this.socket.off("disconnect", this.handleDisconnect);
127
+ this.socket.off("connect_error", this.handleConnectError);
128
+ }
129
+
90
130
  connect() {
91
131
 
132
+ if (this.reconnectTimeout) {
133
+ clearTimeout(this.reconnectTimeout);
134
+ this.reconnectTimeout = undefined;
135
+ }
136
+
137
+ // Clear old handlers to avoid duplicates
138
+ this.offInternalHandlers();
139
+
140
+ // Add fresh handlers
141
+ this.on("connect_ack", this.handleConnectAck);
142
+ this.socket.on("disconnect", this.handleDisconnect);
143
+ this.socket.on("connect_error", this.handleConnectError);
144
+
145
+ // Clear old auth state
92
146
  if (this.socket.auth && this.sessionIdKey in this.socket.auth) {
93
147
  this.socket.auth = {};
94
148
  }
95
-
149
+
96
150
  this.socket.connect();
151
+ }
97
152
 
98
- this.on("connect_ack", (event) => {
99
- this.socket.auth = {
100
- [this.sessionIdKey]: event.sessionId
101
- };
102
- });
153
+ private retryConnect() {
154
+ // Don't retry connect if connected or currently trying to connect
155
+ if (this.socket.connected || this.socket.active || this.reconnectAttempts >= this.maxReconnectAttempts) {
156
+ return;
157
+ }
158
+
159
+ if (this.reconnectTimeout) {
160
+ clearTimeout(this.reconnectTimeout);
161
+ this.reconnectTimeout = undefined;
162
+ }
163
+
164
+ if (this.reconnectAttempts < this.maxReconnectAttempts) {
165
+ const delay = Math.min(1000 * 2 ** this.reconnectAttempts, this.maxReconnectDelay);
166
+ console.info(`[Copilot SDK] Retry #${this.reconnectAttempts + 1} in ${delay}ms...`);
167
+
168
+ this.reconnectTimeout = setTimeout(() => {
169
+ if (!this.socket.connected && !this.socket.active) {
170
+ this.reconnectAttempts++;
171
+ this.reconnect();
172
+ }
173
+ }, delay);
174
+ } else {
175
+ console.error("[Copilot SDK] Max reconnect attempts reached.");
176
+ }
103
177
  }
104
178
 
105
179
  reconnect() {
106
- if (!this.socket.active) {
107
- this.socket.connect();
180
+ // Don't reconnect if connected or currently trying to connect
181
+ if (this.socket.connected || this.socket.active || this.reconnectAttempts >= this.maxReconnectAttempts) {
182
+ return;
108
183
  }
184
+
185
+ // Clear any existing scheduled reconnect to debounce
186
+ if (this.reconnectTimeout) {
187
+ clearTimeout(this.reconnectTimeout);
188
+ this.reconnectTimeout = undefined;
189
+ }
190
+
191
+ this.socket.connect();
109
192
  }
110
193
 
111
194
  async search(
@@ -201,8 +284,15 @@ export default class CimulateCopilot<
201
284
  }
202
285
 
203
286
  disconnect() {
287
+
288
+ if (this.reconnectTimeout) {
289
+ clearTimeout(this.reconnectTimeout);
290
+ this.reconnectTimeout = undefined;
291
+ }
292
+
293
+ this.offInternalHandlers();
204
294
  this.socket.disconnect();
205
- }
295
+ }
206
296
 
207
297
  onDisconnect(handler: (reason: string) => void) {
208
298
  this.socket.on("disconnect", handler);
@@ -7,6 +7,9 @@ interface DisplayProducts<TReturnedFields extends ReturnedFields = ReturnedField
7
7
  eventSourceId: string;
8
8
  message: string;
9
9
  name: 'display_products';
10
+ title?: string;
11
+ attributes?: string[];
12
+ displayAttributes?: Record<string, string>;
10
13
  products: TReturnedFields;
11
14
  }
12
15
  export { DisplayProducts };
@@ -0,0 +1,13 @@
1
+ import { ProgressToolKwargs } from './ProgressToolKwargs';
2
+ interface Progress {
3
+ sessionId: string;
4
+ id: string;
5
+ createdAt: string;
6
+ eventSourceId: string;
7
+ message: string;
8
+ name: 'progress';
9
+ thought?: string;
10
+ toolName?: string;
11
+ toolKwargs?: ProgressToolKwargs;
12
+ }
13
+ export { Progress };
@@ -0,0 +1,6 @@
1
+
2
+ interface ProgressToolKwargs {
3
+ query?: string;
4
+ numResults?: number;
5
+ }
6
+ export { ProgressToolKwargs };
@@ -23,6 +23,8 @@ export * from './FollowUp';
23
23
  export * from './Inquiry';
24
24
  export * from './OperationAck';
25
25
  export * from './PartialInquiry';
26
+ export * from './Progress';
27
+ export * from './ProgressToolKwargs';
26
28
  export * from './RefinedSearch';
27
29
  export * from './ReturnedFields';
28
30
  export * from './SearchParams';
@@ -1,2 +0,0 @@
1
- import t from"socket.io-client";var e=function(t){return function(t){return!!t&&"object"==typeof t}(t)&&!function(t){var e=Object.prototype.toString.call(t);return"[object RegExp]"===e||"[object Date]"===e||function(t){return t.$$typeof===r}(t)}(t)};var r="function"==typeof Symbol&&Symbol.for?Symbol.for("react.element"):60103;function n(t,e){return!1!==e.clone&&e.isMergeableObject(t)?a((r=t,Array.isArray(r)?[]:{}),t,e):t;var r}function o(t,e,r){return t.concat(e).map((function(t){return n(t,r)}))}function s(t){return Object.keys(t).concat(function(t){return Object.getOwnPropertySymbols?Object.getOwnPropertySymbols(t).filter((function(e){return Object.propertyIsEnumerable.call(t,e)})):[]}(t))}function c(t,e){try{return e in t}catch(t){return!1}}function i(t,e,r){var o={};return r.isMergeableObject(t)&&s(t).forEach((function(e){o[e]=n(t[e],r)})),s(e).forEach((function(s){(function(t,e){return c(t,e)&&!(Object.hasOwnProperty.call(t,e)&&Object.propertyIsEnumerable.call(t,e))})(t,s)||(c(t,s)&&r.isMergeableObject(e[s])?o[s]=function(t,e){if(!e.customMerge)return a;var r=e.customMerge(t);return"function"==typeof r?r:a}(s,r)(t[s],e[s],r):o[s]=n(e[s],r))})),o}function a(t,r,s){(s=s||{}).arrayMerge=s.arrayMerge||o,s.isMergeableObject=s.isMergeableObject||e,s.cloneUnlessOtherwiseSpecified=n;var c=Array.isArray(r);return c===Array.isArray(t)?c?s.arrayMerge(t,r,s):i(t,r,s):n(r,s)}a.all=function(t,e){if(!Array.isArray(t))throw new Error("first argument should be an array");return t.reduce((function(t,r){return a(t,r,e)}),{})};var u=a;function l(t){if(t)return function(t){for(var e in l.prototype)t[e]=l.prototype[e];return t}(t)}l.prototype.on=l.prototype.addEventListener=function(t,e){return this._callbacks=this._callbacks||{},(this._callbacks["$"+t]=this._callbacks["$"+t]||[]).push(e),this},l.prototype.once=function(t,e){function r(){this.off(t,r),e.apply(this,arguments)}return r.fn=e,this.on(t,r),this},l.prototype.off=l.prototype.removeListener=l.prototype.removeAllListeners=l.prototype.removeEventListener=function(t,e){if(this._callbacks=this._callbacks||{},0==arguments.length)return this._callbacks={},this;var r,n=this._callbacks["$"+t];if(!n)return this;if(1==arguments.length)return delete this._callbacks["$"+t],this;for(var o=0;o<n.length;o++)if((r=n[o])===e||r.fn===e){n.splice(o,1);break}return 0===n.length&&delete this._callbacks["$"+t],this},l.prototype.emit=function(t){this._callbacks=this._callbacks||{};for(var e=new Array(arguments.length-1),r=this._callbacks["$"+t],n=1;n<arguments.length;n++)e[n-1]=arguments[n];if(r){n=0;for(var o=(r=r.slice(0)).length;n<o;++n)r[n].apply(this,e)}return this},l.prototype.emitReserved=l.prototype.emit,l.prototype.listeners=function(t){return this._callbacks=this._callbacks||{},this._callbacks["$"+t]||[]},l.prototype.hasListeners=function(t){return!!this.listeners(t).length};const f="function"==typeof ArrayBuffer,h=Object.prototype.toString,p="function"==typeof Blob||"undefined"!=typeof Blob&&"[object BlobConstructor]"===h.call(Blob),y="function"==typeof File||"undefined"!=typeof File&&"[object FileConstructor]"===h.call(File);function d(t){return f&&(t instanceof ArrayBuffer||(t=>"function"==typeof ArrayBuffer.isView?ArrayBuffer.isView(t):t.buffer instanceof ArrayBuffer)(t))||p&&t instanceof Blob||y&&t instanceof File}function b(t,e){if(!t||"object"!=typeof t)return!1;if(Array.isArray(t)){for(let e=0,r=t.length;e<r;e++)if(b(t[e]))return!0;return!1}if(d(t))return!0;if(t.toJSON&&"function"==typeof t.toJSON&&1===arguments.length)return b(t.toJSON(),!0);for(const e in t)if(Object.prototype.hasOwnProperty.call(t,e)&&b(t[e]))return!0;return!1}function A(t){const e=[],r=t.data,n=t;return n.data=g(r,e),n.attachments=e.length,{packet:n,buffers:e}}function g(t,e){if(!t)return t;if(d(t)){const r={_placeholder:!0,num:e.length};return e.push(t),r}if(Array.isArray(t)){const r=new Array(t.length);for(let n=0;n<t.length;n++)r[n]=g(t[n],e);return r}if("object"==typeof t&&!(t instanceof Date)){const r={};for(const n in t)Object.prototype.hasOwnProperty.call(t,n)&&(r[n]=g(t[n],e));return r}return t}function m(t,e){return t.data=k(t.data,e),delete t.attachments,t}function k(t,e){if(!t)return t;if(t&&!0===t._placeholder){if("number"==typeof t.num&&t.num>=0&&t.num<e.length)return e[t.num];throw new Error("illegal attachments")}if(Array.isArray(t))for(let r=0;r<t.length;r++)t[r]=k(t[r],e);else if("object"==typeof t)for(const r in t)Object.prototype.hasOwnProperty.call(t,r)&&(t[r]=k(t[r],e));return t}const N=["connect","connect_error","disconnect","disconnecting","newListener","removeListener"];var E;!function(t){t[t.CONNECT=0]="CONNECT",t[t.DISCONNECT=1]="DISCONNECT",t[t.EVENT=2]="EVENT",t[t.ACK=3]="ACK",t[t.CONNECT_ERROR=4]="CONNECT_ERROR",t[t.BINARY_EVENT=5]="BINARY_EVENT",t[t.BINARY_ACK=6]="BINARY_ACK"}(E||(E={}));class O{constructor(t){this.replacer=t}encode(t){return t.type!==E.EVENT&&t.type!==E.ACK||!b(t)?[this.encodeAsString(t)]:this.encodeAsBinary({type:t.type===E.EVENT?E.BINARY_EVENT:E.BINARY_ACK,nsp:t.nsp,data:t.data,id:t.id})}encodeAsString(t){let e=""+t.type;return t.type!==E.BINARY_EVENT&&t.type!==E.BINARY_ACK||(e+=t.attachments+"-"),t.nsp&&"/"!==t.nsp&&(e+=t.nsp+","),null!=t.id&&(e+=t.id),null!=t.data&&(e+=JSON.stringify(t.data,this.replacer)),e}encodeAsBinary(t){const e=A(t),r=this.encodeAsString(e.packet),n=e.buffers;return n.unshift(r),n}}function w(t){return"[object Object]"===Object.prototype.toString.call(t)}class _ extends l{constructor(t){super(),this.reviver=t}add(t){let e;if("string"==typeof t){if(this.reconstructor)throw new Error("got plaintext data when reconstructing a packet");e=this.decodeString(t);const r=e.type===E.BINARY_EVENT;r||e.type===E.BINARY_ACK?(e.type=r?E.EVENT:E.ACK,this.reconstructor=new v(e),0===e.attachments&&super.emitReserved("decoded",e)):super.emitReserved("decoded",e)}else{if(!d(t)&&!t.base64)throw new Error("Unknown type: "+t);if(!this.reconstructor)throw new Error("got binary data when not reconstructing a packet");e=this.reconstructor.takeBinaryData(t),e&&(this.reconstructor=null,super.emitReserved("decoded",e))}}decodeString(t){let e=0;const r={type:Number(t.charAt(0))};if(void 0===E[r.type])throw new Error("unknown packet type "+r.type);if(r.type===E.BINARY_EVENT||r.type===E.BINARY_ACK){const n=e+1;for(;"-"!==t.charAt(++e)&&e!=t.length;);const o=t.substring(n,e);if(o!=Number(o)||"-"!==t.charAt(e))throw new Error("Illegal attachments");r.attachments=Number(o)}if("/"===t.charAt(e+1)){const n=e+1;for(;++e;){if(","===t.charAt(e))break;if(e===t.length)break}r.nsp=t.substring(n,e)}else r.nsp="/";const n=t.charAt(e+1);if(""!==n&&Number(n)==n){const n=e+1;for(;++e;){const r=t.charAt(e);if(null==r||Number(r)!=r){--e;break}if(e===t.length)break}r.id=Number(t.substring(n,e+1))}if(t.charAt(++e)){const n=this.tryParse(t.substr(e));if(!_.isPayloadValid(r.type,n))throw new Error("invalid payload");r.data=n}return r}tryParse(t){try{return JSON.parse(t,this.reviver)}catch(t){return!1}}static isPayloadValid(t,e){switch(t){case E.CONNECT:return w(e);case E.DISCONNECT:return void 0===e;case E.CONNECT_ERROR:return"string"==typeof e||w(e);case E.EVENT:case E.BINARY_EVENT:return Array.isArray(e)&&("number"==typeof e[0]||"string"==typeof e[0]&&-1===N.indexOf(e[0]));case E.ACK:case E.BINARY_ACK:return Array.isArray(e)}}destroy(){this.reconstructor&&(this.reconstructor.finishedReconstruction(),this.reconstructor=null)}}class v{constructor(t){this.packet=t,this.buffers=[],this.reconPack=t}takeBinaryData(t){if(this.buffers.push(t),this.buffers.length===this.reconPack.attachments){const t=m(this.reconPack,this.buffers);return this.finishedReconstruction(),t}return null}finishedReconstruction(){this.reconPack=null,this.buffers=[]}}const C=["searchParams.facetFilters","hits","products"];const R=(t,e,r)=>function n(o,s=[]){const c=Object.entries(o).map((([o,c])=>{const i=[...s,e(o)];return[t(o),c instanceof Object&&!r?.includes(i.join("."))?n(c,i):c]}));return Array.isArray(o)?c.map((t=>t[1])):Object.fromEntries(c)},j=t=>t.replace(/_([a-z])/g,((t,e)=>e.toUpperCase())),B=R((t=>t.replace(/([A-Z])/g,"_$1").toLowerCase()),(t=>t),C),I=R(j,j,C),S={Encoder:class extends O{encode(t){return super.encode({...t,data:2==t.data?.length?[t.data[0],B(t.data[1])]:1==t.data?.length?[t.data[0]]:"object"==typeof t.data&&null!=t.data?t.data:void 0})}},Decoder:class extends _{constructor(){super(((t,e)=>""==t&&Array.isArray(e)?e.map((t=>t instanceof Object?I(t):t)):e))}}};const T={path:"/api/v1/socket.io",autoConnect:!1,transports:["polling","websocket"],upgrade:!0,timeout:1e4};class P{constructor({apiKey:e,apiToken:r,baseUrl:n,namespace:o="/copilot",socketOptions:s={}}){if(this.sessionIdKey="x-cimulate-copilot-session-id",e&&r||!e&&!r)throw new Error("Provide exactly one authentication method: either 'apiKey' or 'apiToken', but not both.");const c=`${n}${o}`,i={};e?i["x-cimulate-api-key"]=e:r&&(i.Authorization=`Bearer ${r}`);const a=[T,s,{parser:S,withCredentials:!0,transportOptions:{polling:{extraHeaders:i}}}];this.socket=t(c,u.all(a))}connect(){this.socket.auth&&this.sessionIdKey in this.socket.auth&&(this.socket.auth={}),this.socket.connect(),this.on("connect_ack",(t=>{this.socket.auth={[this.sessionIdKey]:t.sessionId}}))}reconnect(){this.socket.active||this.socket.connect()}async search(t,e){return this.asyncResponse("copilot_search",t,e)}async facetedNavigation(t,e){return this.asyncResponse("faceted_navigation",t,e)}cancelRequest(t,e){return this.asyncResponse("cancel",t,e)}async requestSessionInformation(t){return new Promise((e=>{this.socket.emit("session_info",(r=>{t&&t(r),e(r)}))}))}on(t,e){return this.socket.on(t,e),e}once(t,e){this.socket.once(t,e)}off(t,e){this.socket.off(t,e)}disconnect(){this.socket.disconnect()}onDisconnect(t){this.socket.on("disconnect",t)}async asyncResponse(t,e,r){if(r)return void this.socket.emit(t,e,r);let n="";const o=async function*(t){const e=[];let r=!1,n=null;const o=await t({emit:t=>{e.push(t),n&&(n(),n=null)},cancel:()=>{r=!0}});try{for(;!r;)e.length>0?yield e.shift():await new Promise((t=>{n=t}));for(;e.length>0;)yield e.shift()}finally{await(o?.())}}((({emit:t,cancel:e})=>{const r=(r,o)=>{"done"==o.name&&e(),o.eventSourceId==n&&t(o)};return this.socket.onAny(r),async()=>{this.socket.offAny(r)}}));return{result:await new Promise((r=>this.socket.emit(t,e,(t=>{n=t?.id,r(t)})))),events:o}}}export{P as CimulateCopilot,C as RAW_PROPERTY_VALUES};
2
- //# sourceMappingURL=bundle.cimulate.copilot-sdk.1891f5f7.esm.js.map
@@ -1,2 +0,0 @@
1
- !function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports,require("socket.io-client")):"function"==typeof define&&define.amd?define(["exports","socket.io-client"],e):e((t="undefined"!=typeof globalThis?globalThis:t||self).CimulateCopilot={},t.io)}(this,(function(t,e){"use strict";function r(t){return t&&"object"==typeof t&&"default"in t?t:{default:t}}var n=r(e),o=function(t){return function(t){return!!t&&"object"==typeof t}(t)&&!function(t){var e=Object.prototype.toString.call(t);return"[object RegExp]"===e||"[object Date]"===e||function(t){return t.$$typeof===s}(t)}(t)};var s="function"==typeof Symbol&&Symbol.for?Symbol.for("react.element"):60103;function c(t,e){return!1!==e.clone&&e.isMergeableObject(t)?f((r=t,Array.isArray(r)?[]:{}),t,e):t;var r}function i(t,e,r){return t.concat(e).map((function(t){return c(t,r)}))}function a(t){return Object.keys(t).concat(function(t){return Object.getOwnPropertySymbols?Object.getOwnPropertySymbols(t).filter((function(e){return Object.propertyIsEnumerable.call(t,e)})):[]}(t))}function u(t,e){try{return e in t}catch(t){return!1}}function l(t,e,r){var n={};return r.isMergeableObject(t)&&a(t).forEach((function(e){n[e]=c(t[e],r)})),a(e).forEach((function(o){(function(t,e){return u(t,e)&&!(Object.hasOwnProperty.call(t,e)&&Object.propertyIsEnumerable.call(t,e))})(t,o)||(u(t,o)&&r.isMergeableObject(e[o])?n[o]=function(t,e){if(!e.customMerge)return f;var r=e.customMerge(t);return"function"==typeof r?r:f}(o,r)(t[o],e[o],r):n[o]=c(e[o],r))})),n}function f(t,e,r){(r=r||{}).arrayMerge=r.arrayMerge||i,r.isMergeableObject=r.isMergeableObject||o,r.cloneUnlessOtherwiseSpecified=c;var n=Array.isArray(e);return n===Array.isArray(t)?n?r.arrayMerge(t,e,r):l(t,e,r):c(e,r)}f.all=function(t,e){if(!Array.isArray(t))throw new Error("first argument should be an array");return t.reduce((function(t,r){return f(t,r,e)}),{})};var h=f;function p(t){if(t)return function(t){for(var e in p.prototype)t[e]=p.prototype[e];return t}(t)}p.prototype.on=p.prototype.addEventListener=function(t,e){return this._callbacks=this._callbacks||{},(this._callbacks["$"+t]=this._callbacks["$"+t]||[]).push(e),this},p.prototype.once=function(t,e){function r(){this.off(t,r),e.apply(this,arguments)}return r.fn=e,this.on(t,r),this},p.prototype.off=p.prototype.removeListener=p.prototype.removeAllListeners=p.prototype.removeEventListener=function(t,e){if(this._callbacks=this._callbacks||{},0==arguments.length)return this._callbacks={},this;var r,n=this._callbacks["$"+t];if(!n)return this;if(1==arguments.length)return delete this._callbacks["$"+t],this;for(var o=0;o<n.length;o++)if((r=n[o])===e||r.fn===e){n.splice(o,1);break}return 0===n.length&&delete this._callbacks["$"+t],this},p.prototype.emit=function(t){this._callbacks=this._callbacks||{};for(var e=new Array(arguments.length-1),r=this._callbacks["$"+t],n=1;n<arguments.length;n++)e[n-1]=arguments[n];if(r){n=0;for(var o=(r=r.slice(0)).length;n<o;++n)r[n].apply(this,e)}return this},p.prototype.emitReserved=p.prototype.emit,p.prototype.listeners=function(t){return this._callbacks=this._callbacks||{},this._callbacks["$"+t]||[]},p.prototype.hasListeners=function(t){return!!this.listeners(t).length};const y="function"==typeof ArrayBuffer,d=Object.prototype.toString,b="function"==typeof Blob||"undefined"!=typeof Blob&&"[object BlobConstructor]"===d.call(Blob),A="function"==typeof File||"undefined"!=typeof File&&"[object FileConstructor]"===d.call(File);function g(t){return y&&(t instanceof ArrayBuffer||(t=>"function"==typeof ArrayBuffer.isView?ArrayBuffer.isView(t):t.buffer instanceof ArrayBuffer)(t))||b&&t instanceof Blob||A&&t instanceof File}function m(t,e){if(!t||"object"!=typeof t)return!1;if(Array.isArray(t)){for(let e=0,r=t.length;e<r;e++)if(m(t[e]))return!0;return!1}if(g(t))return!0;if(t.toJSON&&"function"==typeof t.toJSON&&1===arguments.length)return m(t.toJSON(),!0);for(const e in t)if(Object.prototype.hasOwnProperty.call(t,e)&&m(t[e]))return!0;return!1}function k(t){const e=[],r=t.data,n=t;return n.data=E(r,e),n.attachments=e.length,{packet:n,buffers:e}}function E(t,e){if(!t)return t;if(g(t)){const r={_placeholder:!0,num:e.length};return e.push(t),r}if(Array.isArray(t)){const r=new Array(t.length);for(let n=0;n<t.length;n++)r[n]=E(t[n],e);return r}if("object"==typeof t&&!(t instanceof Date)){const r={};for(const n in t)Object.prototype.hasOwnProperty.call(t,n)&&(r[n]=E(t[n],e));return r}return t}function N(t,e){return t.data=O(t.data,e),delete t.attachments,t}function O(t,e){if(!t)return t;if(t&&!0===t._placeholder){if("number"==typeof t.num&&t.num>=0&&t.num<e.length)return e[t.num];throw new Error("illegal attachments")}if(Array.isArray(t))for(let r=0;r<t.length;r++)t[r]=O(t[r],e);else if("object"==typeof t)for(const r in t)Object.prototype.hasOwnProperty.call(t,r)&&(t[r]=O(t[r],e));return t}const w=["connect","connect_error","disconnect","disconnecting","newListener","removeListener"];var _;!function(t){t[t.CONNECT=0]="CONNECT",t[t.DISCONNECT=1]="DISCONNECT",t[t.EVENT=2]="EVENT",t[t.ACK=3]="ACK",t[t.CONNECT_ERROR=4]="CONNECT_ERROR",t[t.BINARY_EVENT=5]="BINARY_EVENT",t[t.BINARY_ACK=6]="BINARY_ACK"}(_||(_={}));class v{constructor(t){this.replacer=t}encode(t){return t.type!==_.EVENT&&t.type!==_.ACK||!m(t)?[this.encodeAsString(t)]:this.encodeAsBinary({type:t.type===_.EVENT?_.BINARY_EVENT:_.BINARY_ACK,nsp:t.nsp,data:t.data,id:t.id})}encodeAsString(t){let e=""+t.type;return t.type!==_.BINARY_EVENT&&t.type!==_.BINARY_ACK||(e+=t.attachments+"-"),t.nsp&&"/"!==t.nsp&&(e+=t.nsp+","),null!=t.id&&(e+=t.id),null!=t.data&&(e+=JSON.stringify(t.data,this.replacer)),e}encodeAsBinary(t){const e=k(t),r=this.encodeAsString(e.packet),n=e.buffers;return n.unshift(r),n}}function C(t){return"[object Object]"===Object.prototype.toString.call(t)}class R extends p{constructor(t){super(),this.reviver=t}add(t){let e;if("string"==typeof t){if(this.reconstructor)throw new Error("got plaintext data when reconstructing a packet");e=this.decodeString(t);const r=e.type===_.BINARY_EVENT;r||e.type===_.BINARY_ACK?(e.type=r?_.EVENT:_.ACK,this.reconstructor=new j(e),0===e.attachments&&super.emitReserved("decoded",e)):super.emitReserved("decoded",e)}else{if(!g(t)&&!t.base64)throw new Error("Unknown type: "+t);if(!this.reconstructor)throw new Error("got binary data when not reconstructing a packet");e=this.reconstructor.takeBinaryData(t),e&&(this.reconstructor=null,super.emitReserved("decoded",e))}}decodeString(t){let e=0;const r={type:Number(t.charAt(0))};if(void 0===_[r.type])throw new Error("unknown packet type "+r.type);if(r.type===_.BINARY_EVENT||r.type===_.BINARY_ACK){const n=e+1;for(;"-"!==t.charAt(++e)&&e!=t.length;);const o=t.substring(n,e);if(o!=Number(o)||"-"!==t.charAt(e))throw new Error("Illegal attachments");r.attachments=Number(o)}if("/"===t.charAt(e+1)){const n=e+1;for(;++e;){if(","===t.charAt(e))break;if(e===t.length)break}r.nsp=t.substring(n,e)}else r.nsp="/";const n=t.charAt(e+1);if(""!==n&&Number(n)==n){const n=e+1;for(;++e;){const r=t.charAt(e);if(null==r||Number(r)!=r){--e;break}if(e===t.length)break}r.id=Number(t.substring(n,e+1))}if(t.charAt(++e)){const n=this.tryParse(t.substr(e));if(!R.isPayloadValid(r.type,n))throw new Error("invalid payload");r.data=n}return r}tryParse(t){try{return JSON.parse(t,this.reviver)}catch(t){return!1}}static isPayloadValid(t,e){switch(t){case _.CONNECT:return C(e);case _.DISCONNECT:return void 0===e;case _.CONNECT_ERROR:return"string"==typeof e||C(e);case _.EVENT:case _.BINARY_EVENT:return Array.isArray(e)&&("number"==typeof e[0]||"string"==typeof e[0]&&-1===w.indexOf(e[0]));case _.ACK:case _.BINARY_ACK:return Array.isArray(e)}}destroy(){this.reconstructor&&(this.reconstructor.finishedReconstruction(),this.reconstructor=null)}}class j{constructor(t){this.packet=t,this.buffers=[],this.reconPack=t}takeBinaryData(t){if(this.buffers.push(t),this.buffers.length===this.reconPack.attachments){const t=N(this.reconPack,this.buffers);return this.finishedReconstruction(),t}return null}finishedReconstruction(){this.reconPack=null,this.buffers=[]}}const B=["searchParams.facetFilters","hits","products"];const T=(t,e,r)=>function n(o,s=[]){const c=Object.entries(o).map((([o,c])=>{const i=[...s,e(o)];return[t(o),c instanceof Object&&!r?.includes(i.join("."))?n(c,i):c]}));return Array.isArray(o)?c.map((t=>t[1])):Object.fromEntries(c)},I=t=>t.replace(/_([a-z])/g,((t,e)=>e.toUpperCase())),S=T((t=>t.replace(/([A-Z])/g,"_$1").toLowerCase()),(t=>t),B),P=T(I,I,B),V={Encoder:class extends v{encode(t){return super.encode({...t,data:2==t.data?.length?[t.data[0],S(t.data[1])]:1==t.data?.length?[t.data[0]]:"object"==typeof t.data&&null!=t.data?t.data:void 0})}},Decoder:class extends R{constructor(){super(((t,e)=>""==t&&Array.isArray(e)?e.map((t=>t instanceof Object?P(t):t)):e))}}};const K={path:"/api/v1/socket.io",autoConnect:!1,transports:["polling","websocket"],upgrade:!0,timeout:1e4};t.CimulateCopilot=class{constructor({apiKey:t,apiToken:e,baseUrl:r,namespace:o="/copilot",socketOptions:s={}}){if(this.sessionIdKey="x-cimulate-copilot-session-id",t&&e||!t&&!e)throw new Error("Provide exactly one authentication method: either 'apiKey' or 'apiToken', but not both.");const c=`${r}${o}`,i={};t?i["x-cimulate-api-key"]=t:e&&(i.Authorization=`Bearer ${e}`);const a=[K,s,{parser:V,withCredentials:!0,transportOptions:{polling:{extraHeaders:i}}}];this.socket=n.default(c,h.all(a))}connect(){this.socket.auth&&this.sessionIdKey in this.socket.auth&&(this.socket.auth={}),this.socket.connect(),this.on("connect_ack",(t=>{this.socket.auth={[this.sessionIdKey]:t.sessionId}}))}reconnect(){this.socket.active||this.socket.connect()}async search(t,e){return this.asyncResponse("copilot_search",t,e)}async facetedNavigation(t,e){return this.asyncResponse("faceted_navigation",t,e)}cancelRequest(t,e){return this.asyncResponse("cancel",t,e)}async requestSessionInformation(t){return new Promise((e=>{this.socket.emit("session_info",(r=>{t&&t(r),e(r)}))}))}on(t,e){return this.socket.on(t,e),e}once(t,e){this.socket.once(t,e)}off(t,e){this.socket.off(t,e)}disconnect(){this.socket.disconnect()}onDisconnect(t){this.socket.on("disconnect",t)}async asyncResponse(t,e,r){if(r)return void this.socket.emit(t,e,r);let n="";const o=async function*(t){const e=[];let r=!1,n=null;const o=await t({emit:t=>{e.push(t),n&&(n(),n=null)},cancel:()=>{r=!0}});try{for(;!r;)e.length>0?yield e.shift():await new Promise((t=>{n=t}));for(;e.length>0;)yield e.shift()}finally{await(o?.())}}((({emit:t,cancel:e})=>{const r=(r,o)=>{"done"==o.name&&e(),o.eventSourceId==n&&t(o)};return this.socket.onAny(r),async()=>{this.socket.offAny(r)}}));return{result:await new Promise((r=>this.socket.emit(t,e,(t=>{n=t?.id,r(t)})))),events:o}}},t.RAW_PROPERTY_VALUES=B,Object.defineProperty(t,"__esModule",{value:!0})}));
2
- //# sourceMappingURL=bundle.cimulate.copilot-sdk.a321ac32.umd.js.map
@@ -1,2 +0,0 @@
1
- "use strict";function t(t){return t&&"object"==typeof t&&"default"in t?t:{default:t}}Object.defineProperty(exports,"__esModule",{value:!0});var e=t(require("socket.io-client")),r=function(t){return function(t){return!!t&&"object"==typeof t}(t)&&!function(t){var e=Object.prototype.toString.call(t);return"[object RegExp]"===e||"[object Date]"===e||function(t){return t.$$typeof===n}(t)}(t)};var n="function"==typeof Symbol&&Symbol.for?Symbol.for("react.element"):60103;function o(t,e){return!1!==e.clone&&e.isMergeableObject(t)?u((r=t,Array.isArray(r)?[]:{}),t,e):t;var r}function s(t,e,r){return t.concat(e).map((function(t){return o(t,r)}))}function c(t){return Object.keys(t).concat(function(t){return Object.getOwnPropertySymbols?Object.getOwnPropertySymbols(t).filter((function(e){return Object.propertyIsEnumerable.call(t,e)})):[]}(t))}function i(t,e){try{return e in t}catch(t){return!1}}function a(t,e,r){var n={};return r.isMergeableObject(t)&&c(t).forEach((function(e){n[e]=o(t[e],r)})),c(e).forEach((function(s){(function(t,e){return i(t,e)&&!(Object.hasOwnProperty.call(t,e)&&Object.propertyIsEnumerable.call(t,e))})(t,s)||(i(t,s)&&r.isMergeableObject(e[s])?n[s]=function(t,e){if(!e.customMerge)return u;var r=e.customMerge(t);return"function"==typeof r?r:u}(s,r)(t[s],e[s],r):n[s]=o(e[s],r))})),n}function u(t,e,n){(n=n||{}).arrayMerge=n.arrayMerge||s,n.isMergeableObject=n.isMergeableObject||r,n.cloneUnlessOtherwiseSpecified=o;var c=Array.isArray(e);return c===Array.isArray(t)?c?n.arrayMerge(t,e,n):a(t,e,n):o(e,n)}u.all=function(t,e){if(!Array.isArray(t))throw new Error("first argument should be an array");return t.reduce((function(t,r){return u(t,r,e)}),{})};var l=u;function f(t){if(t)return function(t){for(var e in f.prototype)t[e]=f.prototype[e];return t}(t)}f.prototype.on=f.prototype.addEventListener=function(t,e){return this._callbacks=this._callbacks||{},(this._callbacks["$"+t]=this._callbacks["$"+t]||[]).push(e),this},f.prototype.once=function(t,e){function r(){this.off(t,r),e.apply(this,arguments)}return r.fn=e,this.on(t,r),this},f.prototype.off=f.prototype.removeListener=f.prototype.removeAllListeners=f.prototype.removeEventListener=function(t,e){if(this._callbacks=this._callbacks||{},0==arguments.length)return this._callbacks={},this;var r,n=this._callbacks["$"+t];if(!n)return this;if(1==arguments.length)return delete this._callbacks["$"+t],this;for(var o=0;o<n.length;o++)if((r=n[o])===e||r.fn===e){n.splice(o,1);break}return 0===n.length&&delete this._callbacks["$"+t],this},f.prototype.emit=function(t){this._callbacks=this._callbacks||{};for(var e=new Array(arguments.length-1),r=this._callbacks["$"+t],n=1;n<arguments.length;n++)e[n-1]=arguments[n];if(r){n=0;for(var o=(r=r.slice(0)).length;n<o;++n)r[n].apply(this,e)}return this},f.prototype.emitReserved=f.prototype.emit,f.prototype.listeners=function(t){return this._callbacks=this._callbacks||{},this._callbacks["$"+t]||[]},f.prototype.hasListeners=function(t){return!!this.listeners(t).length};const h="function"==typeof ArrayBuffer,p=Object.prototype.toString,y="function"==typeof Blob||"undefined"!=typeof Blob&&"[object BlobConstructor]"===p.call(Blob),d="function"==typeof File||"undefined"!=typeof File&&"[object FileConstructor]"===p.call(File);function b(t){return h&&(t instanceof ArrayBuffer||(t=>"function"==typeof ArrayBuffer.isView?ArrayBuffer.isView(t):t.buffer instanceof ArrayBuffer)(t))||y&&t instanceof Blob||d&&t instanceof File}function A(t,e){if(!t||"object"!=typeof t)return!1;if(Array.isArray(t)){for(let e=0,r=t.length;e<r;e++)if(A(t[e]))return!0;return!1}if(b(t))return!0;if(t.toJSON&&"function"==typeof t.toJSON&&1===arguments.length)return A(t.toJSON(),!0);for(const e in t)if(Object.prototype.hasOwnProperty.call(t,e)&&A(t[e]))return!0;return!1}function g(t){const e=[],r=t.data,n=t;return n.data=m(r,e),n.attachments=e.length,{packet:n,buffers:e}}function m(t,e){if(!t)return t;if(b(t)){const r={_placeholder:!0,num:e.length};return e.push(t),r}if(Array.isArray(t)){const r=new Array(t.length);for(let n=0;n<t.length;n++)r[n]=m(t[n],e);return r}if("object"==typeof t&&!(t instanceof Date)){const r={};for(const n in t)Object.prototype.hasOwnProperty.call(t,n)&&(r[n]=m(t[n],e));return r}return t}function k(t,e){return t.data=E(t.data,e),delete t.attachments,t}function E(t,e){if(!t)return t;if(t&&!0===t._placeholder){if("number"==typeof t.num&&t.num>=0&&t.num<e.length)return e[t.num];throw new Error("illegal attachments")}if(Array.isArray(t))for(let r=0;r<t.length;r++)t[r]=E(t[r],e);else if("object"==typeof t)for(const r in t)Object.prototype.hasOwnProperty.call(t,r)&&(t[r]=E(t[r],e));return t}const N=["connect","connect_error","disconnect","disconnecting","newListener","removeListener"];var O;!function(t){t[t.CONNECT=0]="CONNECT",t[t.DISCONNECT=1]="DISCONNECT",t[t.EVENT=2]="EVENT",t[t.ACK=3]="ACK",t[t.CONNECT_ERROR=4]="CONNECT_ERROR",t[t.BINARY_EVENT=5]="BINARY_EVENT",t[t.BINARY_ACK=6]="BINARY_ACK"}(O||(O={}));class w{constructor(t){this.replacer=t}encode(t){return t.type!==O.EVENT&&t.type!==O.ACK||!A(t)?[this.encodeAsString(t)]:this.encodeAsBinary({type:t.type===O.EVENT?O.BINARY_EVENT:O.BINARY_ACK,nsp:t.nsp,data:t.data,id:t.id})}encodeAsString(t){let e=""+t.type;return t.type!==O.BINARY_EVENT&&t.type!==O.BINARY_ACK||(e+=t.attachments+"-"),t.nsp&&"/"!==t.nsp&&(e+=t.nsp+","),null!=t.id&&(e+=t.id),null!=t.data&&(e+=JSON.stringify(t.data,this.replacer)),e}encodeAsBinary(t){const e=g(t),r=this.encodeAsString(e.packet),n=e.buffers;return n.unshift(r),n}}function _(t){return"[object Object]"===Object.prototype.toString.call(t)}class v extends f{constructor(t){super(),this.reviver=t}add(t){let e;if("string"==typeof t){if(this.reconstructor)throw new Error("got plaintext data when reconstructing a packet");e=this.decodeString(t);const r=e.type===O.BINARY_EVENT;r||e.type===O.BINARY_ACK?(e.type=r?O.EVENT:O.ACK,this.reconstructor=new R(e),0===e.attachments&&super.emitReserved("decoded",e)):super.emitReserved("decoded",e)}else{if(!b(t)&&!t.base64)throw new Error("Unknown type: "+t);if(!this.reconstructor)throw new Error("got binary data when not reconstructing a packet");e=this.reconstructor.takeBinaryData(t),e&&(this.reconstructor=null,super.emitReserved("decoded",e))}}decodeString(t){let e=0;const r={type:Number(t.charAt(0))};if(void 0===O[r.type])throw new Error("unknown packet type "+r.type);if(r.type===O.BINARY_EVENT||r.type===O.BINARY_ACK){const n=e+1;for(;"-"!==t.charAt(++e)&&e!=t.length;);const o=t.substring(n,e);if(o!=Number(o)||"-"!==t.charAt(e))throw new Error("Illegal attachments");r.attachments=Number(o)}if("/"===t.charAt(e+1)){const n=e+1;for(;++e;){if(","===t.charAt(e))break;if(e===t.length)break}r.nsp=t.substring(n,e)}else r.nsp="/";const n=t.charAt(e+1);if(""!==n&&Number(n)==n){const n=e+1;for(;++e;){const r=t.charAt(e);if(null==r||Number(r)!=r){--e;break}if(e===t.length)break}r.id=Number(t.substring(n,e+1))}if(t.charAt(++e)){const n=this.tryParse(t.substr(e));if(!v.isPayloadValid(r.type,n))throw new Error("invalid payload");r.data=n}return r}tryParse(t){try{return JSON.parse(t,this.reviver)}catch(t){return!1}}static isPayloadValid(t,e){switch(t){case O.CONNECT:return _(e);case O.DISCONNECT:return void 0===e;case O.CONNECT_ERROR:return"string"==typeof e||_(e);case O.EVENT:case O.BINARY_EVENT:return Array.isArray(e)&&("number"==typeof e[0]||"string"==typeof e[0]&&-1===N.indexOf(e[0]));case O.ACK:case O.BINARY_ACK:return Array.isArray(e)}}destroy(){this.reconstructor&&(this.reconstructor.finishedReconstruction(),this.reconstructor=null)}}class R{constructor(t){this.packet=t,this.buffers=[],this.reconPack=t}takeBinaryData(t){if(this.buffers.push(t),this.buffers.length===this.reconPack.attachments){const t=k(this.reconPack,this.buffers);return this.finishedReconstruction(),t}return null}finishedReconstruction(){this.reconPack=null,this.buffers=[]}}const C=["searchParams.facetFilters","hits","products"];const j=(t,e,r)=>function n(o,s=[]){const c=Object.entries(o).map((([o,c])=>{const i=[...s,e(o)];return[t(o),c instanceof Object&&!r?.includes(i.join("."))?n(c,i):c]}));return Array.isArray(o)?c.map((t=>t[1])):Object.fromEntries(c)},B=t=>t.replace(/_([a-z])/g,((t,e)=>e.toUpperCase())),I=j((t=>t.replace(/([A-Z])/g,"_$1").toLowerCase()),(t=>t),C),S=j(B,B,C),T={Encoder:class extends w{encode(t){return super.encode({...t,data:2==t.data?.length?[t.data[0],I(t.data[1])]:1==t.data?.length?[t.data[0]]:"object"==typeof t.data&&null!=t.data?t.data:void 0})}},Decoder:class extends v{constructor(){super(((t,e)=>""==t&&Array.isArray(e)?e.map((t=>t instanceof Object?S(t):t)):e))}}};const P={path:"/api/v1/socket.io",autoConnect:!1,transports:["polling","websocket"],upgrade:!0,timeout:1e4};exports.CimulateCopilot=class{constructor({apiKey:t,apiToken:r,baseUrl:n,namespace:o="/copilot",socketOptions:s={}}){if(this.sessionIdKey="x-cimulate-copilot-session-id",t&&r||!t&&!r)throw new Error("Provide exactly one authentication method: either 'apiKey' or 'apiToken', but not both.");const c=`${n}${o}`,i={};t?i["x-cimulate-api-key"]=t:r&&(i.Authorization=`Bearer ${r}`);const a=[P,s,{parser:T,withCredentials:!0,transportOptions:{polling:{extraHeaders:i}}}];this.socket=e.default(c,l.all(a))}connect(){this.socket.auth&&this.sessionIdKey in this.socket.auth&&(this.socket.auth={}),this.socket.connect(),this.on("connect_ack",(t=>{this.socket.auth={[this.sessionIdKey]:t.sessionId}}))}reconnect(){this.socket.active||this.socket.connect()}async search(t,e){return this.asyncResponse("copilot_search",t,e)}async facetedNavigation(t,e){return this.asyncResponse("faceted_navigation",t,e)}cancelRequest(t,e){return this.asyncResponse("cancel",t,e)}async requestSessionInformation(t){return new Promise((e=>{this.socket.emit("session_info",(r=>{t&&t(r),e(r)}))}))}on(t,e){return this.socket.on(t,e),e}once(t,e){this.socket.once(t,e)}off(t,e){this.socket.off(t,e)}disconnect(){this.socket.disconnect()}onDisconnect(t){this.socket.on("disconnect",t)}async asyncResponse(t,e,r){if(r)return void this.socket.emit(t,e,r);let n="";const o=async function*(t){const e=[];let r=!1,n=null;const o=await t({emit:t=>{e.push(t),n&&(n(),n=null)},cancel:()=>{r=!0}});try{for(;!r;)e.length>0?yield e.shift():await new Promise((t=>{n=t}));for(;e.length>0;)yield e.shift()}finally{await(o?.())}}((({emit:t,cancel:e})=>{const r=(r,o)=>{"done"==o.name&&e(),o.eventSourceId==n&&t(o)};return this.socket.onAny(r),async()=>{this.socket.offAny(r)}}));return{result:await new Promise((r=>this.socket.emit(t,e,(t=>{n=t?.id,r(t)})))),events:o}}},exports.RAW_PROPERTY_VALUES=C;
2
- //# sourceMappingURL=bundle.cimulate.copilot-sdk.c98a0a82.cjs.js.map