@piedata/pieui 1.1.9 → 1.1.10
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/components/index.js +39 -45
- package/dist/index.esm.js +1 -1
- package/dist/index.js +1 -1
- package/package.json +1 -1
package/dist/index.esm.js
CHANGED
|
@@ -26,4 +26,4 @@ var yX=Object.create;var{getPrototypeOf:mX,defineProperty:E0,getOwnPropertyNames
|
|
|
26
26
|
`)throw Error("size integer not terminated by '\\n'");let H=new CY;while(G.haveBytes()){let z=G.getInt(),U;switch(G.getChar()){case"@":if(U=G.getInt(),G.haveBytes()&&G.getChar()!==",")throw Error("copy command not terminated by ','");if(Y+=z,Y>W)throw Error("copy exceeds output file size");if(U+z>Q)throw Error("copy extends past end of input");H.putArray(Z,U,U+z);break;case":":if(Y+=z,Y>W)throw Error("insert command gives an output larger than predicted");if(z>X)throw Error("insert count exceeds size of delta");H.putArray(G.a,G.pos,G.pos+z),G.pos+=z;break;case";":{let B=H.toByteArray(Z);if(z!==WK(B))throw Error("bad checksum");if(Y!==W)throw Error("generated size does not match predicted size");return B}default:throw Error("unknown delta operator")}}throw Error("unterminated delta")}class z9{name(){return"json"}encodeCommands(Z){return Z.map((J)=>JSON.stringify(J)).join(`
|
|
27
27
|
`)}decodeReplies(Z){return Z.trim().split(`
|
|
28
28
|
`).map((J)=>JSON.parse(J))}applyDeltaIfNeeded(Z,J){let Y,G;if(Z.delta){let Q=HK(J,new TextEncoder().encode(Z.data));Y=JSON.parse(new TextDecoder().decode(Q)),G=Q}else Y=JSON.parse(Z.data),G=new TextEncoder().encode(Z.data);return{newData:Y,newPrevValue:G}}}var zK={headers:{},token:"",getToken:null,data:null,getData:null,debug:!1,name:"js",version:"",fetch:null,readableStream:null,websocket:null,eventsource:null,sockjs:null,sockjsOptions:{},emulationEndpoint:"/emulation",minReconnectDelay:500,maxReconnectDelay:20000,timeout:5000,maxServerPingDelay:1e4,networkEventTarget:null};class q1 extends Error{constructor(Z){super(Z);this.name=this.constructor.name}}class G0 extends RY{constructor(Z,J){super();if(this._reconnectTimeout=null,this._refreshTimeout=null,this._serverPingTimeout=null,this.state=h.Disconnected,this._transportIsOpen=!1,this._endpoint=Z,this._emulation=!1,this._transports=[],this._currentTransportIndex=0,this._triedAllTransports=!1,this._transportWasOpen=!1,this._transport=null,this._transportId=0,this._deviceWentOffline=!1,this._transportClosed=!0,this._codec=new z9,this._reconnecting=!1,this._reconnectTimeout=null,this._reconnectAttempts=0,this._client=null,this._session="",this._node="",this._subs={},this._serverSubs={},this._commandId=0,this._commands=[],this._batching=!1,this._refreshRequired=!1,this._refreshTimeout=null,this._callbacks={},this._token="",this._data=null,this._dispatchPromise=Promise.resolve(),this._serverPing=0,this._serverPingTimeout=null,this._sendPong=!1,this._promises={},this._promiseId=0,this._debugEnabled=!1,this._networkEventsSet=!1,this._config=Object.assign(Object.assign({},zK),J),this._configure(),this._debugEnabled)this.on("state",(Y)=>{this._debug("client state",Y.oldState,"->",Y.newState)}),this.on("error",(Y)=>{this._debug("client error",Y)});else this.on("error",function(){Function.prototype()})}newSubscription(Z,J){if(this.getSubscription(Z)!==null)throw Error("Subscription to the channel "+Z+" already exists");let Y=new TY(this,Z,J);return this._subs[Z]=Y,Y}getSubscription(Z){return this._getSub(Z)}removeSubscription(Z){if(!Z)return;if(Z.state!==r.Unsubscribed)Z.unsubscribe();this._removeSubscription(Z)}subscriptions(){return this._subs}ready(Z){return o(this,void 0,void 0,function*(){switch(this.state){case h.Disconnected:throw{code:_.clientDisconnected,message:"client disconnected"};case h.Connected:return;default:return new Promise((J,Y)=>{let G={resolve:J,reject:Y};if(Z)G.timeout=setTimeout(()=>{Y({code:_.timeout,message:"timeout"})},Z);this._promises[this._nextPromiseId()]=G})}})}connect(){if(this._isConnected()){this._debug("connect called when already connected");return}if(this._isConnecting()){this._debug("connect called when already connecting");return}this._debug("connect called"),this._reconnectAttempts=0,this._startConnecting()}disconnect(){this._disconnect(a0.disconnectCalled,"disconnect called",!1)}setToken(Z){this._token=Z}setData(Z){this._data=Z}setHeaders(Z){this._config.headers=Z}send(Z){return o(this,void 0,void 0,function*(){let J={send:{data:Z}};if(yield this._methodCall(),!this._transportSendCommands([J]))throw this._createErrorObject(_.transportWriteError,"transport write error")})}rpc(Z,J){return o(this,void 0,void 0,function*(){let Y={rpc:{method:Z,data:J}};return yield this._methodCall(),{data:(yield this._callPromise(Y,(Q)=>Q.rpc)).data}})}publish(Z,J){return o(this,void 0,void 0,function*(){let Y={publish:{channel:Z,data:J}};return yield this._methodCall(),yield this._callPromise(Y,()=>({})),{}})}history(Z,J){return o(this,void 0,void 0,function*(){let Y={history:this._getHistoryRequest(Z,J)};yield this._methodCall();let G=yield this._callPromise(Y,(X)=>X.history),Q=[];if(G.publications)for(let X=0;X<G.publications.length;X++)Q.push(this._getPublicationContext(Z,G.publications[X]));return{publications:Q,epoch:G.epoch||"",offset:G.offset||0}})}presence(Z){return o(this,void 0,void 0,function*(){let J={presence:{channel:Z}};yield this._methodCall();let G=(yield this._callPromise(J,(Q)=>Q.presence)).presence;for(let Q in G)if(Object.prototype.hasOwnProperty.call(G,Q)){let X=G[Q],W=X.conn_info,H=X.chan_info;if(W)X.connInfo=W;if(H)X.chanInfo=H}return{clients:G}})}presenceStats(Z){return o(this,void 0,void 0,function*(){let J={presence_stats:{channel:Z}};yield this._methodCall();let Y=yield this._callPromise(J,(G)=>{return G.presence_stats});return{numUsers:Y.num_users,numClients:Y.num_clients}})}startBatching(){this._batching=!0}stopBatching(){let Z=this;Promise.resolve().then(function(){Promise.resolve().then(function(){Z._batching=!1,Z._flush()})})}_debug(...Z){if(!this._debugEnabled)return;YK("debug",Z)}_codecName(){return this._codec.name()}_formatOverride(){return}_configure(){if(!("Promise"in globalThis))throw Error("Promise polyfill required");if(!this._endpoint)throw Error("endpoint configuration required");if(this._config.token!==null)this._token=this._config.token;if(this._config.data!==null)this._data=this._config.data;if(this._codec=new z9,this._formatOverride(),this._config.debug===!0||typeof localStorage<"u"&&typeof localStorage.getItem==="function"&&localStorage.getItem("centrifuge.debug"))this._debugEnabled=!0;if(this._debug("config",this._config),typeof this._endpoint==="string");else if(Array.isArray(this._endpoint)){this._transports=this._endpoint,this._emulation=!0;for(let Z in this._transports)if(this._transports.hasOwnProperty(Z)){let J=this._transports[Z];if(!J.endpoint||!J.transport)throw Error("malformed transport configuration");let Y=J.transport;if(["websocket","http_stream","sse","sockjs","webtransport"].indexOf(Y)<0)throw Error("unsupported transport name: "+Y)}}else throw Error("unsupported url configuration type: only string or array of objects are supported")}_setState(Z){if(this.state!==Z){this._reconnecting=!1;let J=this.state;return this.state=Z,this.emit("state",{newState:Z,oldState:J}),!0}return!1}_isDisconnected(){return this.state===h.Disconnected}_isConnecting(){return this.state===h.Connecting}_isConnected(){return this.state===h.Connected}_nextCommandId(){return++this._commandId}_setNetworkEvents(){if(this._networkEventsSet)return;let Z=null;if(this._config.networkEventTarget!==null)Z=this._config.networkEventTarget;else if(typeof globalThis.addEventListener<"u")Z=globalThis;if(Z)Z.addEventListener("offline",()=>{if(this._debug("offline event triggered"),this.state===h.Connected||this.state===h.Connecting)this._disconnect(p1.transportClosed,"transport closed",!0),this._deviceWentOffline=!0}),Z.addEventListener("online",()=>{if(this._debug("online event triggered"),this.state!==h.Connecting)return;if(this._deviceWentOffline&&!this._transportClosed)this._deviceWentOffline=!1,this._transportClosed=!0;this._clearReconnectTimeout(),this._startReconnecting()}),this._networkEventsSet=!0}_getReconnectDelay(){let Z=o5(this._reconnectAttempts,this._config.minReconnectDelay,this._config.maxReconnectDelay);return this._reconnectAttempts+=1,Z}_clearOutgoingRequests(){for(let Z in this._callbacks)if(this._callbacks.hasOwnProperty(Z)){let J=this._callbacks[Z];clearTimeout(J.timeout);let Y=J.errback;if(!Y)continue;Y({error:this._createErrorObject(_.connectionClosed,"connection closed")})}this._callbacks={}}_clearConnectedState(){this._client=null,this._clearServerPingTimeout(),this._clearRefreshTimeout();for(let Z in this._subs){if(!this._subs.hasOwnProperty(Z))continue;let J=this._subs[Z];if(J.state===r.Subscribed)J._setSubscribing(i5.transportClosed,"transport closed")}for(let Z in this._serverSubs)if(this._serverSubs.hasOwnProperty(Z))this.emit("subscribing",{channel:Z})}_handleWriteError(Z){for(let J of Z){let Y=J.id;if(!(Y in this._callbacks))continue;let G=this._callbacks[Y];clearTimeout(this._callbacks[Y].timeout),delete this._callbacks[Y];let Q=G.errback;Q({error:this._createErrorObject(_.transportWriteError,"transport write error")})}}_transportSendCommands(Z){if(!Z.length)return!0;if(!this._transport)return!1;try{this._transport.send(this._codec.encodeCommands(Z),this._session,this._node)}catch(J){return this._debug("error writing commands",J),this._handleWriteError(Z),!1}return!0}_initializeTransport(){let Z;if(this._config.websocket!==null)Z=this._config.websocket;else if(!(typeof globalThis.WebSocket!=="function"&&typeof globalThis.WebSocket!=="object"))Z=globalThis.WebSocket;let J=null;if(this._config.sockjs!==null)J=this._config.sockjs;else if(typeof globalThis.SockJS<"u")J=globalThis.SockJS;let Y=null;if(this._config.eventsource!==null)Y=this._config.eventsource;else if(typeof globalThis.EventSource<"u")Y=globalThis.EventSource;let G=null;if(this._config.fetch!==null)G=this._config.fetch;else if(typeof globalThis.fetch<"u")G=globalThis.fetch;let Q=null;if(this._config.readableStream!==null)Q=this._config.readableStream;else if(typeof globalThis.ReadableStream<"u")Q=globalThis.ReadableStream;if(!this._emulation){if(JK(this._endpoint,"http"))throw Error("Provide explicit transport endpoints configuration in case of using HTTP (i.e. using array of TransportEndpoint instead of a single string), or use ws(s):// scheme in an endpoint if you aimed using WebSocket transport");else if(this._debug("client will use websocket"),this._transport=new H9(this._endpoint,{websocket:Z}),!this._transport.supported())throw Error("WebSocket constructor not found, make sure it is available globally or passed as a dependency in Centrifuge options")}else{if(this._currentTransportIndex>=this._transports.length)this._triedAllTransports=!0,this._currentTransportIndex=0;let F=0;while(!0){if(F>=this._transports.length)throw Error("no supported transport found");let M=this._transports[this._currentTransportIndex],K=M.transport,$=M.endpoint;if(K==="websocket"){if(this._debug("trying websocket transport"),this._transport=new H9($,{websocket:Z}),!this._transport.supported()){this._debug("websocket transport not available"),this._currentTransportIndex++,F++;continue}}else if(K==="webtransport"){if(this._debug("trying webtransport transport"),this._transport=new xY($,{webtransport:globalThis.WebTransport,decoder:this._codec,encoder:this._codec}),!this._transport.supported()){this._debug("webtransport transport not available"),this._currentTransportIndex++,F++;continue}}else if(K==="http_stream"){if(this._debug("trying http_stream transport"),this._transport=new EY($,{fetch:G,readableStream:Q,emulationEndpoint:this._config.emulationEndpoint,decoder:this._codec,encoder:this._codec}),!this._transport.supported()){this._debug("http_stream transport not available"),this._currentTransportIndex++,F++;continue}}else if(K==="sse"){if(this._debug("trying sse transport"),this._transport=new SY($,{eventsource:Y,fetch:G,emulationEndpoint:this._config.emulationEndpoint}),!this._transport.supported()){this._debug("sse transport not available"),this._currentTransportIndex++,F++;continue}}else if(K==="sockjs"){if(this._debug("trying sockjs"),this._transport=new wY($,{sockjs:J,sockjsOptions:this._config.sockjsOptions}),!this._transport.supported()){this._debug("sockjs transport not available"),this._currentTransportIndex++,F++;continue}}else throw Error("unknown transport "+K);break}}let X=this,W=this._transport,H=this._nextTransportId();X._debug("id of transport",H);let z=!1,U=[];if(this._transport.emulation()){let F=X._sendConnect(!0);U.push(F)}this._setNetworkEvents();let B=this._codec.encodeCommands(U);this._transportClosed=!1;let L;L=setTimeout(function(){W.close()},this._config.timeout),this._transport.initialize(this._codecName(),{onOpen:function(){if(L)clearTimeout(L),L=null;if(X._transportId!=H){X._debug("open callback from non-actual transport"),W.close();return}if(z=!0,X._debug(W.subName(),"transport open"),W.emulation())return;X._transportIsOpen=!0,X._transportWasOpen=!0,X.startBatching(),X._sendConnect(!1),X._sendSubscribeCommands(),X.stopBatching(),X.emit("__centrifuge_debug:connect_frame_sent",{})},onError:function(F){if(X._transportId!=H){X._debug("error callback from non-actual transport");return}X._debug("transport level error",F)},onClose:function(F){if(L)clearTimeout(L),L=null;if(X._transportId!=H){X._debug("close callback from non-actual transport");return}X._debug(W.subName(),"transport closed"),X._transportClosed=!0,X._transportIsOpen=!1;let M="connection closed",K=!0,$=0;if(F&&"code"in F&&F.code)$=F.code;if(F&&F.reason)try{let O=JSON.parse(F.reason);M=O.reason,K=O.reconnect}catch(O){if(M=F.reason,$>=3500&&$<4000||$>=4500&&$<5000)K=!1}if($<3000){if($===1009)$=a0.messageSizeLimit,M="message size limit exceeded",K=!1;else $=p1.transportClosed,M="transport closed";if(X._emulation&&!X._transportWasOpen){if(X._currentTransportIndex++,X._currentTransportIndex>=X._transports.length)X._triedAllTransports=!0,X._currentTransportIndex=0}}else X._transportWasOpen=!0;if(X._isConnecting()&&!z)X.emit("error",{type:"transport",error:{code:_.transportClosed,message:"transport closed"},transport:W.name()});X._reconnecting=!1,X._disconnect($,M,K)},onMessage:function(F){X._dataReceived(F)}},B),X.emit("__centrifuge_debug:transport_initialized",{})}_sendConnect(Z){let J=this._constructConnectCommand(),Y=this;return this._call(J,Z).then((G)=>{let Q=G.reply.connect;if(Y._connectResponse(Q),G.next)G.next()},(G)=>{if(Y._connectError(G.error),G.next)G.next()}),J}_startReconnecting(){if(this._debug("start reconnecting"),!this._isConnecting()){this._debug("stop reconnecting: client not in connecting state");return}if(this._reconnecting){this._debug("reconnect already in progress, return from reconnect routine");return}if(this._transportClosed===!1){this._debug("waiting for transport close");return}this._reconnecting=!0;let Z=this._token==="";if(!(this._refreshRequired||Z&&this._config.getToken!==null)){if(this._config.getData)this._config.getData().then((G)=>{if(!this._isConnecting())return;this._data=G,this._initializeTransport()}).catch((G)=>this._handleGetDataError(G));else this._initializeTransport();return}let Y=this;this._getToken().then(function(G){if(!Y._isConnecting())return;if(G==null||G==null){Y._failUnauthorized();return}if(Y._token=G,Y._debug("connection token refreshed"),Y._config.getData)Y._config.getData().then(function(Q){if(!Y._isConnecting())return;Y._data=Q,Y._initializeTransport()}).catch((Q)=>Y._handleGetDataError(Q));else Y._initializeTransport()}).catch(function(G){if(!Y._isConnecting())return;if(G instanceof q1){Y._failUnauthorized();return}Y.emit("error",{type:"connectToken",error:{code:_.clientConnectToken,message:G!==void 0?G.toString():""}});let Q=Y._getReconnectDelay();Y._debug("error on getting connection token, reconnect after "+Q+" milliseconds",G),Y._reconnecting=!1,Y._reconnectTimeout=setTimeout(()=>{Y._startReconnecting()},Q)})}_handleGetDataError(Z){if(Z instanceof q1){this._failUnauthorized();return}this.emit("error",{type:"connectData",error:{code:_.badConfiguration,message:(Z===null||Z===void 0?void 0:Z.toString())||""}});let J=this._getReconnectDelay();this._debug("error on getting connect data, reconnect after "+J+" milliseconds",Z),this._reconnecting=!1,this._reconnectTimeout=setTimeout(()=>{this._startReconnecting()},J)}_connectError(Z){if(this.state!==h.Connecting)return;if(Z.code===109)this._refreshRequired=!0;if(Z.code<100||Z.temporary===!0||Z.code===109)this.emit("error",{type:"connect",error:Z}),this._debug("closing transport due to connect error"),this._disconnect(Z.code,Z.message,!0);else this._disconnect(Z.code,Z.message,!1)}_scheduleReconnect(){if(!this._isConnecting())return;let Z=!1;if(this._emulation&&!this._transportWasOpen&&!this._triedAllTransports)Z=!0;let J=this._getReconnectDelay();if(Z)J=0;this._debug("reconnect after "+J+" milliseconds"),this._clearReconnectTimeout(),this._reconnectTimeout=setTimeout(()=>{this._startReconnecting()},J)}_constructConnectCommand(){let Z={};if(this._token)Z.token=this._token;if(this._data)Z.data=this._data;if(this._config.name)Z.name=this._config.name;if(this._config.version)Z.version=this._config.version;if(Object.keys(this._config.headers).length>0)Z.headers=this._config.headers;let J={},Y=!1;for(let G in this._serverSubs)if(this._serverSubs.hasOwnProperty(G)&&this._serverSubs[G].recoverable){Y=!0;let Q={recover:!0};if(this._serverSubs[G].offset)Q.offset=this._serverSubs[G].offset;if(this._serverSubs[G].epoch)Q.epoch=this._serverSubs[G].epoch;J[G]=Q}if(Y)Z.subs=J;return{connect:Z}}_getHistoryRequest(Z,J){let Y={channel:Z};if(J!==void 0){if(J.since){if(Y.since={offset:J.since.offset},J.since.epoch)Y.since.epoch=J.since.epoch}if(J.limit!==void 0)Y.limit=J.limit;if(J.reverse===!0)Y.reverse=!0}return Y}_methodCall(){if(this._isConnected())return Promise.resolve();return new Promise((Z,J)=>{let Y=setTimeout(function(){J({code:_.timeout,message:"timeout"})},this._config.timeout);this._promises[this._nextPromiseId()]={timeout:Y,resolve:Z,reject:J}})}_callPromise(Z,J){return new Promise((Y,G)=>{this._call(Z,!1).then((Q)=>{var X;let W=J(Q.reply);Y(W),(X=Q.next)===null||X===void 0||X.call(Q)},(Q)=>{var X;G(Q.error),(X=Q.next)===null||X===void 0||X.call(Q)})})}_dataReceived(Z){if(this._serverPing>0)this._waitServerPing();let J=this._codec.decodeReplies(Z);this._dispatchPromise=this._dispatchPromise.then(()=>{let Y;this._dispatchPromise=new Promise((G)=>{Y=G}),this._dispatchSynchronized(J,Y)})}_dispatchSynchronized(Z,J){let Y=Promise.resolve();for(let G in Z)if(Z.hasOwnProperty(G))Y=Y.then(()=>{return this._dispatchReply(Z[G])});Y=Y.then(()=>{J()})}_dispatchReply(Z){let J,Y=new Promise((Q)=>{J=Q});if(Z===void 0||Z===null)return this._debug("dispatch: got undefined or null reply"),J(),Y;let G=Z.id;if(G&&G>0)this._handleReply(Z,J);else if(!Z.push)this._handleServerPing(J);else this._handlePush(Z.push,J);return Y}_call(Z,J){return new Promise((Y,G)=>{if(Z.id=this._nextCommandId(),this._registerCall(Z.id,Y,G),!J)this._addCommand(Z)})}_startConnecting(){if(this._debug("start connecting"),this._setState(h.Connecting))this.emit("connecting",{code:p1.connectCalled,reason:"connect called"});this._client=null,this._startReconnecting()}_disconnect(Z,J,Y){if(this._isDisconnected())return;this._transportIsOpen=!1;let G=this.state;this._reconnecting=!1;let Q={code:Z,reason:J},X=!1;if(Y)X=this._setState(h.Connecting);else X=this._setState(h.Disconnected),this._rejectPromises({code:_.clientDisconnected,message:"disconnected"});if(this._clearOutgoingRequests(),G===h.Connecting)this._clearReconnectTimeout();if(G===h.Connected)this._clearConnectedState();if(X)if(this._isConnecting())this.emit("connecting",Q);else this.emit("disconnected",Q);if(this._transport){this._debug("closing existing transport");let W=this._transport;this._transport=null,W.close(),this._transportClosed=!0,this._nextTransportId()}else this._debug("no transport to close");this._scheduleReconnect()}_failUnauthorized(){this._disconnect(a0.unauthorized,"unauthorized",!1)}_getToken(){if(this._debug("get connection token"),!this._config.getToken)return this.emit("error",{type:"configuration",error:{code:_.badConfiguration,message:"token expired but no getToken function set in the configuration"}}),Promise.reject(new q1(""));return this._config.getToken({})}_refresh(){let Z=this._client,J=this;this._getToken().then(function(Y){if(Z!==J._client)return;if(!Y){J._failUnauthorized();return}if(J._token=Y,J._debug("connection token refreshed"),!J._isConnected())return;let G={refresh:{token:J._token}};J._call(G,!1).then((Q)=>{let X=Q.reply.refresh;if(J._refreshResponse(X),Q.next)Q.next()},(Q)=>{if(J._refreshError(Q.error),Q.next)Q.next()})}).catch(function(Y){if(!J._isConnected())return;if(Y instanceof q1){J._failUnauthorized();return}J.emit("error",{type:"refreshToken",error:{code:_.clientRefreshToken,message:Y!==void 0?Y.toString():""}}),J._refreshTimeout=setTimeout(()=>J._refresh(),J._getRefreshRetryDelay())})}_refreshError(Z){if(Z.code<100||Z.temporary===!0)this.emit("error",{type:"refresh",error:Z}),this._refreshTimeout=setTimeout(()=>this._refresh(),this._getRefreshRetryDelay());else this._disconnect(Z.code,Z.message,!1)}_getRefreshRetryDelay(){return o5(0,5000,1e4)}_refreshResponse(Z){if(this._refreshTimeout)clearTimeout(this._refreshTimeout),this._refreshTimeout=null;if(Z.expires)this._client=Z.client,this._refreshTimeout=setTimeout(()=>this._refresh(),a5(Z.ttl))}_removeSubscription(Z){if(Z===null)return;delete this._subs[Z.channel]}_unsubscribe(Z){if(!this._transportIsOpen)return Promise.resolve();let Y={unsubscribe:{channel:Z.channel}},G=this;return new Promise((X,W)=>{this._call(Y,!1).then((H)=>{if(X(),H.next)H.next()},(H)=>{if(X(),H.next)H.next();G._disconnect(p1.unsubscribeError,"unsubscribe error",!0)})})}_getSub(Z,J){if(J&&J>0){for(let G in this._subs)if(this._subs.hasOwnProperty(G)){let Q=this._subs[G];if(Q._id===J)return Q}return null}let Y=this._subs[Z];if(!Y)return null;return Y}_isServerSub(Z){return this._serverSubs[Z]!==void 0}_sendSubscribeCommands(){let Z=[];for(let J in this._subs){if(!this._subs.hasOwnProperty(J))continue;let Y=this._subs[J];if(Y._inflight===!0)continue;if(Y.state===r.Subscribing){let G=Y._subscribe();if(G)Z.push(G)}}return Z}_connectResponse(Z){if(this._transportIsOpen=!0,this._transportWasOpen=!0,this._reconnectAttempts=0,this._refreshRequired=!1,this._isConnected())return;if(this._client=Z.client,this._setState(h.Connected),this._refreshTimeout)clearTimeout(this._refreshTimeout);if(Z.expires)this._refreshTimeout=setTimeout(()=>this._refresh(),a5(Z.ttl));this._session=Z.session,this._node=Z.node,this.startBatching(),this._sendSubscribeCommands(),this.stopBatching();let J={client:Z.client,transport:this._transport.subName()};if(Z.data)J.data=Z.data;if(this.emit("connected",J),this._resolvePromises(),this._processServerSubs(Z.subs||{}),Z.ping&&Z.ping>0)this._serverPing=Z.ping*1000,this._sendPong=Z.pong===!0,this._waitServerPing();else this._serverPing=0}_processServerSubs(Z){for(let J in Z){if(!Z.hasOwnProperty(J))continue;let Y=Z[J];this._serverSubs[J]={offset:Y.offset,epoch:Y.epoch,recoverable:Y.recoverable||!1};let G=this._getSubscribeContext(J,Y);this.emit("subscribed",G)}for(let J in Z){if(!Z.hasOwnProperty(J))continue;let Y=Z[J];if(Y.recovered){let G=Y.publications;if(G&&G.length>0){for(let Q in G)if(G.hasOwnProperty(Q))this._handlePublication(J,G[Q])}}}for(let J in this._serverSubs){if(!this._serverSubs.hasOwnProperty(J))continue;if(!Z[J])this.emit("unsubscribed",{channel:J}),delete this._serverSubs[J]}}_clearRefreshTimeout(){if(this._refreshTimeout!==null)clearTimeout(this._refreshTimeout),this._refreshTimeout=null}_clearReconnectTimeout(){if(this._reconnectTimeout!==null)clearTimeout(this._reconnectTimeout),this._reconnectTimeout=null}_clearServerPingTimeout(){if(this._serverPingTimeout!==null)clearTimeout(this._serverPingTimeout),this._serverPingTimeout=null}_waitServerPing(){if(this._config.maxServerPingDelay===0)return;if(!this._isConnected())return;this._clearServerPingTimeout(),this._serverPingTimeout=setTimeout(()=>{if(!this._isConnected())return;this._disconnect(p1.noPing,"no ping",!0)},this._serverPing+this._config.maxServerPingDelay)}_getSubscribeContext(Z,J){let Y={channel:Z,positioned:!1,recoverable:!1,wasRecovering:!1,recovered:!1,hasRecoveredPublications:!1};if(J.recovered)Y.recovered=!0;if(J.positioned)Y.positioned=!0;if(J.recoverable)Y.recoverable=!0;if(J.was_recovering)Y.wasRecovering=!0;let G="";if("epoch"in J)G=J.epoch;let Q=0;if("offset"in J)Q=J.offset;if(Y.positioned||Y.recoverable)Y.streamPosition={offset:Q,epoch:G};if(Array.isArray(J.publications)&&J.publications.length>0)Y.hasRecoveredPublications=!0;if(J.data)Y.data=J.data;return Y}_handleReply(Z,J){let Y=Z.id;if(!(Y in this._callbacks)){J();return}let G=this._callbacks[Y];if(clearTimeout(this._callbacks[Y].timeout),delete this._callbacks[Y],!QK(Z)){let Q=G.callback;if(!Q)return;Q({reply:Z,next:J})}else{let Q=G.errback;if(!Q){J();return}let X={code:Z.error.code,message:Z.error.message||"",temporary:Z.error.temporary||!1};Q({error:X,next:J})}}_handleJoin(Z,J,Y){let G=this._getSub(Z,Y);if(!G&&Z){if(this._isServerSub(Z)){let Q={channel:Z,info:this._getJoinLeaveContext(J.info)};this.emit("join",Q)}return}G._handleJoin(J)}_handleLeave(Z,J,Y){let G=this._getSub(Z,Y);if(!G&&Z){if(this._isServerSub(Z)){let Q={channel:Z,info:this._getJoinLeaveContext(J.info)};this.emit("leave",Q)}return}G._handleLeave(J)}_handleUnsubscribe(Z,J){let Y=this._getSub(Z,0);if(!Y&&Z){if(this._isServerSub(Z))delete this._serverSubs[Z],this.emit("unsubscribed",{channel:Z});return}if(J.code<2500)Y._setUnsubscribed(J.code,J.reason,!1);else Y._setSubscribing(J.code,J.reason)}_handleSubscribe(Z,J){this._serverSubs[Z]={offset:J.offset,epoch:J.epoch,recoverable:J.recoverable||!1},this.emit("subscribed",this._getSubscribeContext(Z,J))}_handleDisconnect(Z){let J=Z.code,Y=!0;if(J>=3500&&J<4000||J>=4500&&J<5000)Y=!1;this._disconnect(J,Z.reason,Y)}_getPublicationContext(Z,J){let Y={channel:Z,data:J.data};if(J.offset)Y.offset=J.offset;if(J.info)Y.info=this._getJoinLeaveContext(J.info);if(J.tags)Y.tags=J.tags;return Y}_getJoinLeaveContext(Z){let J={client:Z.client,user:Z.user},Y=Z.conn_info;if(Y)J.connInfo=Y;let G=Z.chan_info;if(G)J.chanInfo=G;return J}_handlePublication(Z,J,Y){let G=this._getSub(Z,Y);if(!G&&Z){if(this._isServerSub(Z)){let Q=this._getPublicationContext(Z,J);if(this.emit("publication",Q),J.offset!==void 0)this._serverSubs[Z].offset=J.offset}return}G._handlePublication(J)}_handleMessage(Z){this.emit("message",{data:Z.data})}_handleServerPing(Z){if(this._sendPong){let J={};this._transportSendCommands([J])}Z()}_handlePush(Z,J){let{channel:Y,id:G}=Z;if(Z.pub)this._handlePublication(Y,Z.pub,G);else if(Z.message)this._handleMessage(Z.message);else if(Z.join)this._handleJoin(Y,Z.join,G);else if(Z.leave)this._handleLeave(Y,Z.leave,G);else if(Z.unsubscribe)this._handleUnsubscribe(Y,Z.unsubscribe);else if(Z.subscribe)this._handleSubscribe(Y,Z.subscribe);else if(Z.disconnect)this._handleDisconnect(Z.disconnect);J()}_flush(){let Z=this._commands.slice(0);this._commands=[],this._transportSendCommands(Z)}_createErrorObject(Z,J,Y){let G={code:Z,message:J};if(Y)G.temporary=!0;return G}_registerCall(Z,J,Y){this._callbacks[Z]={callback:J,errback:Y,timeout:null},this._callbacks[Z].timeout=setTimeout(()=>{if(delete this._callbacks[Z],PY(Y))Y({error:this._createErrorObject(_.timeout,"timeout")})},this._config.timeout)}_addCommand(Z){if(this._batching)this._commands.push(Z);else this._transportSendCommands([Z])}_nextPromiseId(){return++this._promiseId}_nextTransportId(){return++this._transportId}_resolvePromises(){for(let Z in this._promises){if(!this._promises.hasOwnProperty(Z))continue;if(this._promises[Z].timeout)clearTimeout(this._promises[Z].timeout);this._promises[Z].resolve(),delete this._promises[Z]}}_rejectPromises(Z){for(let J in this._promises){if(!this._promises.hasOwnProperty(J))continue;if(this._promises[J].timeout)clearTimeout(this._promises[J].timeout);this._promises[J].reject(Z),delete this._promises[J]}}}G0.SubscriptionState=r;G0.State=h;G0.UnauthorizedError=q1;var r5=(Z,J)=>{async function Y(){let G=await fetch(Z+"api/centrifuge/gen_token");if(!G.ok){if(G.status===403)throw new G0.UnauthorizedError("Backend is not answering");throw Error(`Unexpected status code ${G.status}`)}return(await G.json()).token}return J?new G0(J||"",{getToken:Y}):null},BK=UK(null),l1=BK;import{useContext as LK,useEffect as MK}from"react";import{useEffect as KK,useState as jY}from"react";function t5(Z,J){let[Y,G]=jY(null),[Q,X]=jY(!1);return KK(()=>{if(!Q)X(!0),fetch(Z+`api/support/${J}`,{method:"GET"}).then((W)=>W.json()).then((W)=>{G(W)})},[]),Y}var $K=({children:Z})=>{let J=LK(c1),Y=h1(),G=t5(Y,"socketIO"),Q=(X)=>{if(typeof window<"u")window.sid=X.sid,console.log(`SocketIO initialized: ${window.sid}`)};return MK(()=>{if(!J)return;let X=()=>{console.log("SocketIO connected")},W=(H)=>{console.log(`SocketIO disconnected: ${H}`),J.connect()};if(G)J.on("pieinit",Q),J.on("connect",X),J.on("disconnect",W),J.connect();return()=>{if(G)J.off("pieinit",Q),J.off("connect",X),J.off("disconnect",W),J.disconnect()}},[J,G]),Z},e5=$K;import{useContext as FK,useEffect as OK}from"react";var VK=({children:Z})=>{let J=FK(l1),Y=h1(),G=t5(Y,"centrifuge");return OK(()=>{if(!J)return;let Q=()=>{console.log("Centrifuge connected")},X=(W)=>{console.log("Centrifuge disconnected:",W)};if(G)J.on("connected",Q),J.on("disconnected",X),J.connect();return()=>{if(G)J.disconnect()}},[J,G]),Z},Z6=VK;var hX=S(x9(),1);import{useContext as f9,useEffect as C9}from"react";var zM=({card:Z,data:J,children:Y,useSocketioSupport:G=!1,useCentrifugeSupport:Q=!1,useMittSupport:X=!1,centrifugeChannel:W=void 0,methods:H=void 0})=>{let z=b1();if(z)console.log("[PieCard] Rendering card:",Z),console.log("[PieCard] Card data:",J),console.log("[PieCard] Component name:",J?.name),console.log("[PieCard] Real-time support:",{socketio:G,centrifuge:Q,mitt:X,centrifugeChannel:W}),console.log("[PieCard] Methods:",H?Object.keys(H):"none"),console.log("[PieCard] Has children:",!!Y);let U=f9(c1),B=f9(l1),L=f9(u1);if(C9(()=>{if(!U||!G||!H||!J.name){if(z&&G)console.log("[PieCard] Socket.IO setup skipped:",{hasSocket:!!U,useSocketioSupport:G,hasMethods:!!H,hasDataName:!!J?.name});return}return Object.entries(H).forEach(([F,M])=>{let K=`pie${F}_${J.name}`;if(z)console.log(`[PieCard] Socket.IO registering event: ${K}`);U.on(K,M)}),()=>{Object.entries(H).forEach(([F,M])=>{let K=`pie${F}_${J.name}`;if(z)console.log(`[PieCard] Socket.IO unregistering event: ${K}`);U.off(K,M)})}},[U,H,J.name]),C9(()=>{if(!B||!Q||!W||!H||!J.name){if(z&&Q)console.log("[PieCard] Centrifuge setup skipped:",{hasCentrifuge:!!B,useCentrifugeSupport:Q,hasCentrifugeChannel:!!W,hasMethods:!!H,hasDataName:!!J?.name});return}let F=Object.entries(H).map(([M,K])=>{let $=`pie${M}_${J.name}_${W}`;if(z)console.log(`[PieCard] Centrifuge subscribing to channel: ${$}`);let O=B.newSubscription($);return O.on("publication",(N)=>{if(z)console.log(`[PieCard] Centrifuge received data on ${$}:`,N.data);K(N.data)}),O.subscribe(),O});return()=>{F.forEach((M)=>{if(z)console.log("[PieCard] Centrifuge unsubscribing from channel");M.unsubscribe(),B.removeSubscription(M)})}},[B,W,H,J.name]),C9(()=>{if(!L||!X||!H||!J.name){if(z&&X)console.log("[PieCard] Mitt setup skipped:",{hasMitt:!!L,useMittSupport:X,hasMethods:!!H,hasDataName:!!J?.name});return}return Object.entries(H).forEach(([F,M])=>{let K=`pie${F}_${J.name}`;if(z)console.log(`[PieCard] Mitt registering event: ${K}`);L.on(K,M)}),()=>{Object.entries(H).forEach(([F,M])=>{let K=`pie${F}_${J.name}`;if(z)console.log(`[PieCard] Mitt unregistering event: ${K}`);L.off(K,M)})}},[L,H,J.name]),z)console.log("[PieCard] Rendering complete, returning children");return Y},y=zM;function R0(Z){if(!Z)return{};let J={...Z};if("animationName"in J&&typeof J.animationName==="object"){let Y="radiumAnimation_"+Math.random().toString(36).substring(2,8);J.animationName=n.keyframes(J.animationName,Y)}return J}import{jsx as j9}from"react/jsx-runtime";var UM=({data:Z,content:J,setUiAjaxConfiguration:Y})=>{let{name:G,sx:Q}=Z;return j9(y,{card:G,data:Z,children:j9("div",{style:R0(Q),id:G,children:J.map((X,W)=>{return j9(G1,{uiConfig:X,setUiAjaxConfiguration:Y},`children-${W}`)})})})},sG=n(UM);import{jsx as rG}from"react/jsx-runtime";var BM=({data:Z,content:J,setUiAjaxConfiguration:Y})=>{let{name:G}=Z;return rG(y,{card:G,data:Z,children:J.map((Q,X)=>{return rG(G1,{uiConfig:Q,setUiAjaxConfiguration:Y},`children-${X}`)})})},tG=BM;import{useContext as eG,useEffect as KM,useRef as LM,useState as ZQ}from"react";import{jsx as JQ}from"react/jsx-runtime";var MM=({data:Z,content:J})=>{let{useLoader:Y,noReturn:G,returnType:Q,useSocketioSupport:X,useCentrifugeSupport:W,useMittSupport:H,centrifugeChannel:z}=Z,U=eG(v1),[B,L]=ZQ(!1),[F,M]=ZQ(null),K=LM(J),$=eG(u1),O=(D)=>{if(D===null)L(!0);else if(L(!1),!G)K.current=D;if(!G)M(D)},N=(D)=>{K.current=D.content,M(D.content)},P=(D)=>{if(D===null)L(!0);else if(L(!1),!G)for(let q of D)$.emit(q.name,q.data)};if(KM(()=>{M(J),L(!1)},[J]),!F&&Y)return U;return JQ(y,{card:"AjaxGroupCard",data:Z,methods:{changeContent:N},useSocketioSupport:X,useCentrifugeSupport:W,useMittSupport:H,centrifugeChannel:z,children:JQ(G1,{uiConfig:F??K.current,setUiAjaxConfiguration:Q==="events"?P:O})})},YQ=n(MM);function _9(Z=1000){return new Promise((J)=>{if(typeof window>"u"){J();return}let Y=()=>{if(typeof window.sid<"u")J();else setTimeout(Y,Z)};Y()})}import{useMemo as $M}from"react";var FM=(Z,J={},Y=[],G,Q)=>{let X=Q?.renderingLogEnabled??!1,W=Q?.apiServer??"";if(X)console.log("Registering AJAX: ",G,J,Y);if(!G||!Z){if(X)console.warn("Registration FAILED: pathname or setUiAjaxConfiguration is missing!");return()=>{}}return async(H={})=>{if(typeof window>"u"||typeof document>"u"){if(X)console.warn("getAjaxSubmit called on server, skipping DOM-dependent logic");return}if(Y.includes("sid"))await _9();let z=new FormData;for(let[B,L]of Object.entries({...J,...H}))z.append(B,L);for(let B of Y)if(B==="sid"){if(!window.sid)throw Error("SocketIO isn't initialized properly");z.append("sid",window.sid)}else{let L=document.getElementsByName(B);if(!L.length){if(X)console.warn(`No input found with name ${B}`);continue}let F=L[0];if(F instanceof HTMLInputElement)if(F.type==="file"&&F.files)Array.from(F.files).forEach((M)=>z.append(B,M));else z.append(B,F.value);else if(F instanceof HTMLTextAreaElement)z.append(B,F.value)}let U=W+"api/ajax_content"+G;return Z(null),await fetch(U,{method:"POST",body:z}).then(async(B)=>{let F=(B.headers.get("content-type")||"").includes("application/json");if(!!B.body?.getReader&&!F){let K=B.body.getReader(),$=new TextDecoder,O="";while(!0){let{done:N,value:P}=await K.read();if(N)break;O+=$.decode(P,{stream:!0});let D=O.split(`
|
|
29
|
-
`);O=D.pop()??"";for(let q of D){let T=q.trim();if(!T)continue;try{let f=JSON.parse(T);Z([f])}catch(f){if(X)console.warn("Failed to parse streamed line:",T)}}}if(O.trim())try{let N=JSON.parse(O);Z([N])}catch(N){if(X)console.warn("Failed to parse final streamed line:",O)}return{}}else{let K=await B.json();return Z(K),K}}).catch((B)=>{if(X)console.error("AJAX request failed:",B);return Z(null),B})}},G5=(Z,J={},Y=[],G)=>{let{apiServer:Q,enableRenderingLog:X}=U0();return $M(()=>FM(Z,J,Y,G,{apiServer:Q,renderingLogEnabled:X}),[Z,J,Y,G,Q,X])};var Z7=S(e9(),1),H0=S(e9(),1),o1=Z7.default.default||Z7.default;import{jsx as J7,jsxs as L$}from"react/jsx-runtime";var K$=({data:Z,setUiAjaxConfiguration:J})=>{let{name:Y,title:G,iconUrl:Q,iconPosition:X,sx:W,pathname:H,kwargs:z,depsNames:U}=Z,B=G5(J,z,U,H);return J7(y,{card:"AjaxButtonCard",data:Z,children:L$("button",{id:Y,className:"box-border flex min-h-12 w-full min-w-min cursor-pointer items-center justify-center gap-4 rounded-l border border-black bg-white text-center text-black hover:bg-neutral-300",value:Y,onClick:()=>B(),style:R0(W),type:"button",children:[Q&&X==="start"&&J7("img",{src:Q,alt:""}),o1(G),Q&&X==="end"&&J7("img",{src:Q,alt:""})]})})},WX=n(K$);import{forwardRef as k$,useEffect as AX,useImperativeHandle as v$,useRef as h$,useState as T6}from"react";import{useRef as M$,useState as $$}from"react";import{jsx as F$}from"react/jsx-runtime";function Y7(Z){let[J,Y]=$$(!1),G=M$(null);return F$("textarea",{ref:G,...Z,onKeyUp:()=>{Y(!1)},onKeyDown:(H)=>{if(H.key==="Enter"&&H.shiftKey){if(Y(!0),G.current&&typeof window<"u"){let z=window.getComputedStyle(G.current),U=parseFloat(z.lineHeight);G.current.style.height=G.current.scrollHeight+U+"px"}}if(H.key==="Backspace"){if(Y(!0),G.current&&typeof window<"u"){let z=window.getComputedStyle(G.current),U=parseFloat(z.lineHeight);if(G.current.scrollHeight>U)G.current.style.height=G.current.scrollHeight-U+"px"}}Z.onKeyDown&&Z.onKeyDown(H)},onBlur:(H)=>{Y(!1),Z.onBlur&&Z.onBlur(H)},style:{resize:J?"vertical":"none",overflowY:"auto",...Z.style}})}import{useRef as V$,useCallback as I$}from"react";import{jsx as HX}from"react/jsx-runtime";var O$=()=>HX("svg",{xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",strokeWidth:"1.5",stroke:"currentColor",className:"size-5",children:HX("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M6 12L3.269 3.126A59.768 59.768 0 0121.485 12 59.77 59.77 0 013.27 20.876L5.999 12zm0 0h7.5"})}),zX=O$;import{jsx as G7}from"react/jsx-runtime";var q$=({type:Z="button",onClick:J,icons:Y})=>{let G=V$(null),Q=I$(()=>{let W=G.current;if(W)W.style.transform="scale(0.8)",setTimeout(()=>{W.style.transform="scale(1)"},600)},[]);return G7("button",{ref:G,type:Z,onClick:(W)=>{if(J)J(W);Q()},className:"mr-1.5 rounded-md p-1 text-gray-500 ring-0 hover:bg-gray-100 disabled:opacity-40 disabled:hover:bg-transparent",style:{transition:"transform 300ms ease"},children:Y.sendIcon?G7("img",{src:Y.sendIcon,alt:""}):G7(zX,{})})},UX=q$;import{jsx as BX}from"react/jsx-runtime";var D$=()=>BX("svg",{xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",strokeWidth:"1.5",stroke:"currentColor",className:"size-5",children:BX("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M18.375 12.739l-7.693 7.693a4.5 4.5 0 01-6.364-6.364l10.94-10.94A3 3 0 1119.5 7.372L8.552 18.32m.009-.01l-.01.01m5.699-9.941l-7.81 7.81a1.5 1.5 0 002.112 2.13"})}),KX=D$;import{jsx as A6,jsxs as R$,Fragment as A$}from"react/jsx-runtime";var N$=({name:Z,accept:J,fileInputRef:Y,onSelectFile:G,icons:Q})=>{return R$(A$,{children:[A6("button",{className:"rounded-md p-1 text-gray-500 ring-0 hover:bg-gray-100 disabled:opacity-40 disabled:hover:bg-transparent",type:"button",onClick:()=>{if(Y.current)Y.current.click()},children:Q.attachFileIcon?A6("img",{src:Q.attachFileIcon,alt:""}):A6(KX,{})}),A6("input",{id:Z+"__pie__file",name:Z+"__pie__file",className:"hidden",type:"file",accept:J,ref:Y,onChange:(X)=>{if(X.target.files)G(X.target.files[0])}})]})},LX=N$;import{jsx as MX}from"react/jsx-runtime";var P$=()=>MX("svg",{xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",strokeWidth:"1.5",stroke:"currentColor",className:"size-5 text-gray-500",children:MX("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M19.5 14.25v-2.625a3.375 3.375 0 00-3.375-3.375h-1.5A1.125 1.125 0 0113.5 7.125v-1.5a3.375 3.375 0 00-3.375-3.375H8.25m2.25 0H5.625c-.621 0-1.125.504-1.125 1.125v17.25c0 .621.504 1.125 1.125 1.125h12.75c.621 0 1.125-.504 1.125-1.125V11.25a9 9 0 00-9-9z"})}),$X=P$;import{jsx as FX}from"react/jsx-runtime";var T$=()=>FX("svg",{xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",strokeWidth:"1.5",stroke:"currentColor",className:"size-5",children:FX("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M6 18L18 6M6 6l12 12"})}),R6=T$;import{jsx as L5,jsxs as E$}from"react/jsx-runtime";var w$=({name:Z,selectedFile:J,onDropFile:Y})=>{return E$("div",{className:"flex w-full cursor-default flex-row items-center gap-2",children:[L5($X,{}),L5("span",{className:"flex-1",children:J.name}),L5("input",{type:"hidden",name:Z,value:""}),L5("button",{className:"rounded-md p-1 text-gray-500 ring-0 hover:bg-gray-100 disabled:opacity-40 disabled:hover:bg-transparent",type:"button",onClick:Y,children:L5(R6,{})})]})},OX=w$;import{jsx as VX,jsxs as x$}from"react/jsx-runtime";var S$=()=>x$("svg",{xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",strokeWidth:"1.5",stroke:"currentColor",className:"size-5",children:[VX("path",{d:"M8 5C8 2.79086 9.79086 1 12 1C14.2091 1 16 2.79086 16 5V12C16 14.2091 14.2091 16 12 16C9.79086 16 8 14.2091 8 12V5Z"}),VX("path",{d:"M6.25 11.8438V12C6.25 13.525 6.8558 14.9875 7.93414 16.0659C9.01247 17.1442 10.475 17.75 12 17.75C13.525 17.75 14.9875 17.1442 16.0659 16.0659C17.1442 14.9875 17.75 13.525 17.75 12V11.8438C17.75 11.2915 18.1977 10.8438 18.75 10.8438H19.25C19.8023 10.8438 20.25 11.2915 20.25 11.8437V12C20.25 14.188 19.3808 16.2865 17.8336 17.8336C16.5842 19.0831 14.9753 19.8903 13.25 20.1548V22C13.25 22.5523 12.8023 23 12.25 23H11.75C11.1977 23 10.75 22.5523 10.75 22V20.1548C9.02471 19.8903 7.41579 19.0831 6.16637 17.8336C4.61919 16.2865 3.75 14.188 3.75 12V11.8438C3.75 11.2915 4.19772 10.8438 4.75 10.8438H5.25C5.80228 10.8438 6.25 11.2915 6.25 11.8438Z"})]}),IX=S$;import{jsx as M5}from"react/jsx-runtime";var f$=({isListening:Z,toggleListening:J,icons:Y})=>{return M5("button",{className:"rounded-md p-1 text-gray-500 ring-0 hover:bg-gray-100 disabled:opacity-40 disabled:hover:bg-transparent",type:"button",onClick:J,children:Z?Y.cancelIcon?M5("img",{src:Y.cancelIcon,alt:""}):M5(R6,{}):Y.voiceRecordingIcon?M5("img",{src:Y.voiceRecordingIcon,alt:""}):M5(IX,{})})},qX=f$;import{jsx as DX,jsxs as j$}from"react/jsx-runtime";var C$=({option:Z,onClickOption:J})=>{return j$("div",{className:"flex w-fit cursor-pointer flex-row place-content-center items-center gap-1 rounded-md border border-black bg-white px-2 py-1 text-black",onClick:()=>{J(Z.title)},style:Z.sx,children:[Z.iconPosition==="start"&&DX("img",{src:Z.iconUrl,alt:""}),Z.title,Z.iconPosition==="end"&&DX("img",{src:Z.iconUrl,alt:""})]})},P6=C$;import{jsx as NX}from"react/jsx-runtime";var _$=({options:Z,handleOptionClick:J})=>{return NX("div",{className:"flex w-full flex-row flex-wrap justify-start gap-[5px]",children:Z.map((Y,G)=>{return NX(P6,{option:Y,onClickOption:J},G)})})},Q7=_$;import{jsx as x1,jsxs as RX}from"react/jsx-runtime";var b$=k$(({name:Z,defaultValue:J,defaultOptions:Y,isArea:G,placeholder:Q,fileAccept:X,optionsPosition:W,icons:H,handleOptionClick:z,handleSendMessage:U,sx:B},L)=>{let F=h$(null),[M,K]=T6(null),[$,O]=T6(J),[N,P]=T6(Y),[D,q]=T6(!1);v$(L,()=>({clear:()=>{if(O(""),K(null),F.current)F.current.value=""},setValue:(f)=>O(f),setOptions:(f)=>P(f)})),AX(()=>{O(J)},[J]),AX(()=>{},[]);let T=()=>{};return RX("div",{className:"flex flex-col items-center gap-[0.1rem]",id:Z+"_chat_input",style:B,children:[N&&W==="top"&&x1(Q7,{options:N,handleOptionClick:z}),x1("div",{className:"stretch relative flex size-full flex-1 flex-row items-stretch gap-3 last:mb-2 md:mx-4 md:flex-col md:last:mb-6 lg:mx-auto",children:RX("div",{className:"flex w-full grow flex-row items-center rounded-md bg-transparent",children:[M?x1(OX,{name:Z,selectedFile:M,onDropFile:()=>{if(K(null),F.current)F.current.value=""}}):!G?x1("input",{name:Z,value:$,onChange:(f)=>O(f.target.value),onKeyDown:(f)=>{if(f.key==="Enter")f.preventDefault(),U()},tabIndex:0,placeholder:Q,className:"m-0 w-full resize-none border-0 bg-transparent outline-none",style:{maxHeight:200,height:"100%",overflowY:"hidden"}}):x1(Y7,{name:Z,value:$,onChange:(f)=>O(f.target.value),onKeyDown:(f)=>{if(f.key==="Enter"&&!f.shiftKey)f.preventDefault(),U()},tabIndex:0,rows:2,placeholder:Q,className:"m-0 w-full resize-none border-0 bg-transparent p-0 pl-2 pr-7 outline-none md:pl-0",style:{maxHeight:200,height:"100%",minHeight:24}}),x1(qX,{isListening:D,toggleListening:T,icons:H}),x1(LX,{name:Z,fileInputRef:F,accept:X,onSelectFile:K,icons:H}),x1(UX,{onClick:U,icons:H})]})}),N&&W==="bottom"&&x1(Q7,{options:N,handleOptionClick:z})]})}),PX=b$;import{useState as p$,useEffect as l$}from"react";import{useEffect as g$,useState as y$}from"react";import{jsx as u$}from"react/jsx-runtime";function m$({children:Z}){let[J,Y]=y$(Z);return g$(()=>{Y(Z)},[Z]),u$("div",{className:"max-w-full first:mt-0",children:J})}var TX=m$;import{jsx as wX}from"react/jsx-runtime";var d$=()=>wX("svg",{width:"30",height:"30",viewBox:"0 0 16 16",xmlns:"http://www.w3.org/2000/svg",children:wX("path",{d:"m 8 1 c -1.65625 0 -3 1.34375 -3 3 s 1.34375 3 3 3 s 3 -1.34375 3 -3 s -1.34375 -3 -3 -3 z m -1.5 7 c -2.492188 0 -4.5 2.007812 -4.5 4.5 v 0.5 c 0 1.109375 0.890625 2 2 2 h 8 c 1.109375 0 2 -0.890625 2 -2 v -0.5 c 0 -2.492188 -2.007812 -4.5 -4.5 -4.5 z m 0 0",fill:"#2e3436"})}),EX=d$;import{jsx as w6}from"react/jsx-runtime";function c$({username:Z,avatar:J}){return w6("div",{className:"w-[30px]",children:w6("div",{className:"relative flex size-[30px] items-center justify-center rounded-sm p-1 text-white",children:J?w6("img",{src:J,className:"absolute inset-0 rounded",alt:Z}):w6(EX,{})})})}var X7=c$;import{jsx as N1,jsxs as SX}from"react/jsx-runtime";var i$=({message:Z,handleOptionClick:J,setUiAjaxConfiguration:Y})=>{let[G,Q]=p$(!1);return l$(()=>{let X=setTimeout(()=>{if(G)Q(!1)},1000);return()=>clearTimeout(X)},[G]),N1("div",{className:"group w-full border-b border-black/10",id:Z.id,children:SX("div",{className:`flex gap-4 p-4 text-base md:max-w-2xl md:gap-6 md:py-6 lg:max-w-3xl xl:max-w-5xl ${Z.align==="center"?"m-auto":""} ${Z.align==="right"?"ml-auto justify-end":""} ${Z.align==="left"?"mr-auto":""} `,children:[(Z.align==="left"||Z.align==="center")&&N1("div",{className:"relative flex shrink-0 flex-col items-end",children:N1(X7,{username:Z.username,avatar:Z.avatar})}),SX("div",{className:"relative flex w-[calc(100%-50px)] flex-col gap-1 md:gap-3 lg:w-[calc(100%-115px)]",children:[N1("div",{className:`markdown light prose w-full break-words dark:prose-invert first:mt-0 ${Z.align==="right"?"flex justify-end self-end":""}`,children:typeof Z.content==="string"?Z.parseMode.toLowerCase()==="markdown"?N1(TX,{children:Z.content},Date.now()+Math.random()):Z.parseMode.toLowerCase()==="html"?o1(Z.content):Z.content:N1(G1,{uiConfig:Z.content,setUiAjaxConfiguration:Y})}),N1("div",{className:"flex flex-row flex-wrap justify-start gap-1",children:Z.options.map((X,W)=>N1(P6,{onClickOption:J,option:X},W))})]}),Z.align==="right"&&N1("div",{className:"relative flex shrink-0 flex-col items-end",children:N1(X7,{username:Z.username,avatar:Z.avatar})})]})})},xX=i$;import{forwardRef as n$,useEffect as o$,useImperativeHandle as a$,useRef as s$,useState as r$}from"react";import{jsx as fX}from"react/jsx-runtime";var t$=n$(({name:Z,handleOptionClick:J,defaultMessages:Y,sx:G,setUiAjaxConfiguration:Q},X)=>{let[W,H]=r$(Y),z=s$(null),U=()=>{if(z.current)z.current.scrollTop=z.current.scrollHeight};return o$(()=>{U()},[W]),a$(X,()=>({setMessages:(B)=>H(B),addMessage:(B)=>H((L)=>[...L,B]),scrollToBottom:U})),fX("div",{id:Z+"_messages",className:"flex flex-col items-center overflow-y-scroll",style:G,ref:z,children:W.map((B)=>fX(xX,{message:B,handleOptionClick:J,setUiAjaxConfiguration:Q},B.id))})}),CX=t$;import{useEffect as e$,useRef as jX,useState as ZF}from"react";import{jsx as W7,jsxs as YF}from"react/jsx-runtime";var JF=({data:Z,setUiAjaxConfiguration:J})=>{let{name:Y,defaultValue:G,defaultMessages:Q,defaultOptions:X,isArea:W,fileAccept:H,placeholder:z,icons:U,optionsPosition:B,sxMap:L={container:{},chatInput:{},messages:{}},depsNames:F,pathname:M,kwargs:K,useSocketioSupport:$,useCentrifugeSupport:O,centrifugeChannel:N}=Z,P=jX(null),D=jX(null),[q,T]=ZF(!1),f=G5(J,K,F,M);e$(()=>{if(q)requestAnimationFrame(()=>{f(),T(!1)})},[q]);let u=(p)=>{if(P.current)P.current.setValue(p),T(!0)},a1=()=>{if(P.current)P.current.clear()},C1=(p)=>{if(P.current)P.current.setOptions(p.options)},j1=(p)=>{if(D.current)D.current.addMessage(p.message)},k=(p)=>{if(D.current)D.current.setMessages(p.messages)},R1=()=>{T(!0)};return W7(y,{card:"ChatCard",data:Z,methods:{clearInput:a1,setOptions:C1,addMessage:j1,setMessages:k},useSocketioSupport:$,useCentrifugeSupport:O,centrifugeChannel:N,children:YF("div",{className:"flex size-full flex-col",style:L.container,children:[W7(CX,{ref:D,name:Y,defaultMessages:Q,sx:L.messages,handleOptionClick:u,setUiAjaxConfiguration:J}),W7(PX,{ref:P,name:Y,isArea:W,defaultOptions:X,placeholder:z,defaultValue:G,fileAccept:H,sx:L.chatInput,handleSendMessage:R1,handleOptionClick:u,optionsPosition:B,icons:U})]})})},_X=JF;import{useEffect as GF,useState as QF}from"react";import{jsx as kX}from"react/jsx-runtime";var XF=({data:Z})=>{let{name:J,value:Y,useSocketioSupport:G,useCentrifugeSupport:Q,useMittSupport:X,centrifugeChannel:W}=Z,[H,z]=QF(Y);return GF(()=>{z(Y)},[Y]),kX(y,{card:"HiddenCard",data:Z,useSocketioSupport:G,useCentrifugeSupport:Q,useMittSupport:X,centrifugeChannel:W,methods:{update:({value:U})=>{z(U)}},children:kX("input",{type:"hidden",id:J,name:J,value:H})})},H7=XF;import{useContext as zF,useEffect as UF}from"react";import{createContext as WF}from"react";var HF=WF(void 0),A1=HF;import{jsx as LF,Fragment as KF}from"react/jsx-runtime";var BF=({data:Z})=>{let{url:J}=Z,Y=zF(A1);return UF(()=>{if(/^[a-zA-Z][a-zA-Z\d+\-.]*:\/\//.test(J))window.location.href=J;else Y?.(J)},[J,Y]),LF(KF,{})},z7=BF;import{useEffect as OF,useState as VF}from"react";import{useCallback as E6,useEffect as MF,useRef as U7,useState as $F}from"react";function FF(){let Z=new AudioContext,J=Z.createOscillator(),Y=J.connect(Z.createMediaStreamDestination());J.start();let G=Y.stream.getAudioTracks()[0];return G.enabled=!1,G}function B7(Z=null,J){let[Y,G]=$F(!1),Q=U7(null),X=U7(null),W=U7(null),H=E6(async(L,F=!0)=>{if(Q.current)z();let M=new RTCPeerConnection;if(M.onconnectionstatechange=()=>{if(M.connectionState==="connected")G(!0);else if(["disconnected","failed","closed"].includes(M.connectionState))G(!1)},M.ontrack=(q)=>{if(Z)Z.srcObject=q.streams[0]},F){let q=await navigator.mediaDevices.getUserMedia({audio:!0});M.addTrack(q.getTracks()[0],q)}else{let q=FF();M.addTrack(q)}let K=M.createDataChannel("oai-events");X.current=K,W.current=new Promise((q)=>{K.addEventListener("open",()=>{q()})});let $=await M.createOffer();await M.setLocalDescription($);let D=await(await fetch(`${"https://api.openai.com/v1/realtime/calls"}?model=${"gpt-realtime"}`,{method:"POST",body:$.sdp,headers:{Authorization:`Bearer ${L}`,"Content-Type":"application/sdp"}})).text();await M.setRemoteDescription({type:"answer",sdp:D}),Q.current=M,await W.current},[Z]),z=E6(()=>{let L=X.current;if(L)L.close();Q.current?.getSenders()?.forEach((F)=>F.track?.stop()),Q.current?.close(),G(!1),Q.current=null,X.current=null,W.current=null},[Z]),U=E6((L)=>{let F=X.current;if(!F){console.error("Data channel is not ready",L);return}let M=new Date().toLocaleTimeString();if(L.event_id=L.event_id||crypto.randomUUID(),F.send(JSON.stringify(L)),!L.timestamp)L.timestamp=M;J?.(L)},[J,Z]),B=E6((L)=>{if(!X.current){console.error("Data channel is not ready");return}let M=()=>{U({type:"conversation.item.create",item:{type:"message",role:"user",content:[{type:"input_text",text:L}]}}),U({type:"response.create"})};if(W.current)W.current.then(M);else M()},[J,Z]);return MF(()=>{let L=X.current;if(!L)return;let F=(M)=>{let K=JSON.parse(M.data);if(!K.timestamp)K.timestamp=new Date().toLocaleTimeString();J?.(K)};return L.addEventListener("message",F),()=>{L.removeEventListener("message",F)}},[J,Z]),{isSessionActive:Y,startSession:H,stopSession:z,sendTextMessage:B}}import{jsx as qF}from"react/jsx-runtime";var IF=({data:Z})=>{let{html:J,useSocketioSupport:Y,useCentrifugeSupport:G,useMittSupport:Q,centrifugeChannel:X}=Z,[W,H]=VF(J),{isSessionActive:z,startSession:U,sendTextMessage:B}=B7(null,(K)=>{if(console.log(K.type,K.type==="response.output_text.delta"&&K.delta),K.type==="response.output_text.delta"&&K.delta)H(($)=>$+K.delta)});return OF(()=>{H(J)},[J]),qF(y,{card:"HTMLEmbedCard",data:Z,methods:{update:(K)=>{H(K.value)},generateUsingAI:async(K)=>{try{if(!z&&K.token)await U(K.token,!1);B(K.prompt)}catch($){console.error("Failed to generate using AI",$)}},initializeAI:async(K)=>{if(!z&&K.token)await U(K.token,!1)}},useCentrifugeSupport:G,useSocketioSupport:Y,useMittSupport:Q,centrifugeChannel:X,children:o1(W)})},K7=n(IF);import{useContext as DF}from"react";import{jsx as L7,Fragment as vX}from"react/jsx-runtime";var NF=({data:Z})=>{let{useCentrifugeSupport:J,useSocketioSupport:Y,useMittSupport:G,centrifugeChannel:Q}=Z,X=DF(A1);return L7(vX,{children:L7(y,{card:"IOEventsCard",data:Z,useCentrifugeSupport:J,useSocketioSupport:Y,useMittSupport:G,centrifugeChannel:Q,methods:{log:(z)=>{console.log("Log event",z)},redirect:(z)=>{if(z.to){let U=z.to;if(/^[a-zA-Z][a-zA-Z\d+\-.]*:\/\//.test(U))window.location.href=U;else X?.(U)}else window.location.reload()}},children:L7(vX,{})})})},M7=NF;import{useContext as AF}from"react";import{jsx as $7,jsxs as PF}from"react/jsx-runtime";var RF=({data:Z})=>{let{name:J,title:Y,url:G,iconUrl:Q,iconPosition:X,sx:W}=Z,H=AF(A1);return $7(y,{card:"RedirectButtonCard",data:Z,children:PF("button",{id:J,className:"box-border flex min-h-12 w-full min-w-min cursor-pointer items-center justify-center gap-4 rounded-l border border-black bg-white text-center text-black hover:bg-neutral-300",value:J,onClick:(U)=>{if(G)if(U.stopPropagation(),/^[a-zA-Z][a-zA-Z\d+\-.]*:\/\//.test(G))window.location.href=G;else H?.(G)},style:R0(W),type:"button",children:[Q&&X==="start"&&$7("img",{src:Q,alt:""}),o1(Y),Q&&X==="end"&&$7("img",{src:Q,alt:""})]})})},F7=n(RF);var O7=!1;function $5(){if(O7)return;U1({name:"SequenceCard",component:sG,metadata:{author:"PieData",description:"Simple div with styles joining few components"}}),U1({name:"UnionCard",component:tG,metadata:{author:"PieData",description:"Renders one of many components"}}),U1({name:"AjaxGroupCard",component:YQ,metadata:{author:"PieData",description:"Group card with AJAX support"}}),U1({name:"AjaxButtonCard",component:WX,metadata:{author:"PieData",description:"Button with AJAX support"}}),U1({name:"RedirectButtonCard",component:F7,metadata:{author:"PieData",description:"Button with Redirect on click"}}),U1({name:"ChatCard",component:_X,metadata:{author:"PieData"}}),U1({name:"HiddenCard",component:H7,metadata:{author:"PieData"}}),U1({name:"AutoRedirectCard",component:z7,metadata:{author:"PieData"}}),U1({name:"HTMLEmbedCard",component:K7,metadata:{author:"PieData"}}),U1({name:"IOEventsCard",component:M7,metadata:{author:"PieData"}}),O7=!0}function f1(){return O7}import{jsx as H1,Fragment as jF}from"react/jsx-runtime";var fF=({location:Z,fallback:J,onError:Y,initializePie:G})=>{let Q=h1(),X=O5(),W=b1();TF(()=>{if(f1())return;$5(),G()},[]);let H=wF(()=>hX.createAxiosDateTransformer({baseURL:Q||""}),[Q]),{data:z,isLoading:U,error:B}=xF({queryKey:["uiConfig",Z.pathname+Z.search,f1(),Q],queryFn:async()=>{if(!Q||!f1())return;let L="/api/content"+Z.pathname+Z.search;if(W)console.log("[PieRoot] Fetching UI configuration from:",L);let F=await H.get(L,{headers:{"Access-Control-Allow-Origin":"*","Access-Control-Allow-Methods":"GET,PUT,POST,DELETE,PATCH,OPTIONS","Content-type":"application/json"},withCredentials:!0});if(W)console.log("[PieRoot] Received UI configuration:",F.data);return F.data},staleTime:1/0,gcTime:1/0,refetchOnWindowFocus:!1,refetchOnMount:!1,refetchOnReconnect:!1,retry:!0,retryDelay:(L)=>Math.min(1000*2**L,30000)});if(!Q)return J??null;if(W)console.log("[PieRoot] Rendering with location:",Z),console.log("[PieRoot] API_SERVER:",Q),console.log("[PieRoot] Fallback provided:",!!J);if(B){if(W)console.error("[PieRoot] Error fetching UI configuration:",B),console.error("[PieRoot] Error details:",{message:B.message,status:B.response?.status,data:B.response?.data});return Y?.(),J}if(U||!z){if(W)console.log("[PieRoot] Loading state:",{isLoading:U,hasUiConfiguration:!!z});return J}if(W)console.log("[PieRoot] UI configuration loaded successfully:",z),console.log("[PieRoot] Rendering UI with configuration");return H1(u1.Provider,{value:v0,children:H1(c1.Provider,{value:p5(Q),children:H1(l1.Provider,{value:r5(Q,X),children:H1(v1.Provider,{value:J??H1(jF,{}),children:H1(e5,{children:H1(Z6,{children:H1(n.StyleRoot,{style:{display:"contents"},children:H1(G1,{uiConfig:z})})})})})})})})},CF=(Z)=>{let J=new EF;return H1(A1.Provider,{value:Z.onNavigate,children:H1(S0.Provider,{value:Z.config,children:H1(SF,{client:J,children:H1(fF,{...Z})})})})},_F=CF;import{useEffect as hF,useMemo as bF}from"react";import{QueryClient as gF,QueryClientProvider as yF,useQuery as mF}from"@tanstack/react-query";var gX=S(x9(),1);import{useEffect as kF,useState as vF}from"react";var bX=()=>{let[Z,J]=vF(null),Y=w7();return kF(()=>{if(typeof window>"u")return;let G=window.Telegram.WebApp;if(G.ready(),Y==="telegram_expanded"&&(G.platform==="ios"||G.platform==="android"))G.expand();J(G)},[]),Z};import{jsx as z1,Fragment as cF}from"react/jsx-runtime";var uF=({location:Z,fallback:J,onError:Y,initializePie:G})=>{let Q=h1(),X=O5(),W=b1();hF(()=>{if(f1())return;$5(),G()},[]);let H=bF(()=>gX.createAxiosDateTransformer({baseURL:Q}),[]);if(W)console.log("[PieRoot] Rendering with location:",Z),console.log("[PieRoot] API_SERVER:",Q),console.log("[PieRoot] Fallback provided:",!!J);if(!Q)throw Error("Set PIE_API_SERVER and PIE_CENTRIFUGE_SERVER");let z=bX(),{data:U,isLoading:B,error:L}=mF({queryKey:["uiConfig",Z.pathname+Z.search,z?.initData,f1()],queryFn:async()=>{if(!f1())return;let F=Z.search?"&":"?",M=z?.initData?`${F}initData=${encodeURIComponent(z.initData)}`:"",K="/api/content"+Z.pathname+Z.search+M;if(W)console.log("[PieRoot] Fetching UI configuration from:",K);let $=await H.get(K,{headers:{"Access-Control-Allow-Origin":"*","Access-Control-Allow-Methods":"GET,PUT,POST,DELETE,PATCH,OPTIONS","Content-type":"application/json"},withCredentials:!0});if(W)console.log("[PieRoot] Received UI configuration:",$.data);return $.data},staleTime:1/0,gcTime:1/0,refetchOnWindowFocus:!1,refetchOnMount:!1,refetchOnReconnect:!1,retry:!0,retryDelay:(F)=>Math.min(1000*2**F,30000)});if(L&&W)return console.error("[PieRoot] Error fetching UI configuration:",L),console.error("[PieRoot] Error details:",{message:L.message,status:L.response?.status,data:L.response?.data}),Y?.(),J;if(B||!U){if(W)console.log("[PieRoot] Loading state:",{isLoading:B,hasUiConfiguration:!!U});return J}if(W)console.log("[PieRoot] UI configuration loaded successfully:",U),console.log("[PieRoot] Rendering UI with configuration");return z1(u1.Provider,{value:v0,children:z1(c1.Provider,{value:p5(Q),children:z1(l1.Provider,{value:r5(Q,X),children:z1(v1.Provider,{value:J??z1(cF,{}),children:z1(e5,{children:z1(Z6,{children:z1(n.StyleRoot,{children:z1(G1,{uiConfig:U})})})})})})})})},dF=(Z)=>{let J=new gF;return z1(A1.Provider,{value:Z.onNavigate,children:z1(S0.Provider,{value:Z.config,children:z1(yF,{client:J,children:z1(uF,{...Z})})})})},pF=dF;export{G5 as useAjaxSubmit,U1 as registerPieComponent,f1 as isPieComponentsInitialized,$5 as initializePieComponents,G1 as UI,pF as PieTelegramRoot,_F as PieRoot,y as PieCard};
|
|
29
|
+
`);O=D.pop()??"";for(let q of D){let T=q.trim();if(!T)continue;try{let f=JSON.parse(T);Z([f])}catch(f){if(X)console.warn("Failed to parse streamed line:",T)}}}if(O.trim())try{let N=JSON.parse(O);Z([N])}catch(N){if(X)console.warn("Failed to parse final streamed line:",O)}return{}}else{let K=await B.json();return Z(K),K}}).catch((B)=>{if(X)console.error("AJAX request failed:",B);return Z(null),B})}},G5=(Z,J={},Y=[],G)=>{let{apiServer:Q,enableRenderingLog:X}=U0();return $M(()=>FM(Z,J,Y,G,{apiServer:Q,renderingLogEnabled:X}),[Z,J,Y,G,Q,X])};var Z7=S(e9(),1),H0=S(e9(),1),o1=Z7.default.default||Z7.default;import{jsx as J7,jsxs as L$}from"react/jsx-runtime";var K$=({data:Z,setUiAjaxConfiguration:J})=>{let{name:Y,title:G,iconUrl:Q,iconPosition:X,sx:W,pathname:H,kwargs:z,depsNames:U}=Z,B=G5(J,z,U,H);return J7(y,{card:"AjaxButtonCard",data:Z,children:L$("button",{id:Y,className:"box-border flex min-h-12 w-full min-w-min cursor-pointer items-center justify-center gap-4 rounded-l border border-black bg-white text-center text-black hover:bg-neutral-300",value:Y,onClick:()=>B(),style:R0(W),type:"button",children:[Q&&X==="start"&&J7("img",{src:Q,alt:""}),o1(G),Q&&X==="end"&&J7("img",{src:Q,alt:""})]})})},WX=n(K$);import{forwardRef as k$,useEffect as AX,useImperativeHandle as v$,useRef as h$,useState as T6}from"react";import{useRef as M$,useState as $$}from"react";import{jsx as F$}from"react/jsx-runtime";function Y7(Z){let[J,Y]=$$(!1),G=M$(null);return F$("textarea",{ref:G,...Z,onKeyUp:()=>{Y(!1)},onKeyDown:(H)=>{if(H.key==="Enter"&&H.shiftKey){if(Y(!0),G.current&&typeof window<"u"){let z=window.getComputedStyle(G.current),U=parseFloat(z.lineHeight);G.current.style.height=G.current.scrollHeight+U+"px"}}if(H.key==="Backspace"){if(Y(!0),G.current&&typeof window<"u"){let z=window.getComputedStyle(G.current),U=parseFloat(z.lineHeight);if(G.current.scrollHeight>U)G.current.style.height=G.current.scrollHeight-U+"px"}}Z.onKeyDown&&Z.onKeyDown(H)},onBlur:(H)=>{Y(!1),Z.onBlur&&Z.onBlur(H)},style:{resize:J?"vertical":"none",overflowY:"auto",...Z.style}})}import{useRef as V$,useCallback as I$}from"react";import{jsx as HX}from"react/jsx-runtime";var O$=()=>HX("svg",{xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",strokeWidth:"1.5",stroke:"currentColor",className:"size-5",children:HX("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M6 12L3.269 3.126A59.768 59.768 0 0121.485 12 59.77 59.77 0 013.27 20.876L5.999 12zm0 0h7.5"})}),zX=O$;import{jsx as G7}from"react/jsx-runtime";var q$=({type:Z="button",onClick:J,icons:Y})=>{let G=V$(null),Q=I$(()=>{let W=G.current;if(W)W.style.transform="scale(0.8)",setTimeout(()=>{W.style.transform="scale(1)"},600)},[]);return G7("button",{ref:G,type:Z,onClick:(W)=>{if(J)J(W);Q()},className:"mr-1.5 rounded-md p-1 text-gray-500 ring-0 hover:bg-gray-100 disabled:opacity-40 disabled:hover:bg-transparent",style:{transition:"transform 300ms ease"},children:Y.sendIcon?G7("img",{src:Y.sendIcon,alt:""}):G7(zX,{})})},UX=q$;import{jsx as BX}from"react/jsx-runtime";var D$=()=>BX("svg",{xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",strokeWidth:"1.5",stroke:"currentColor",className:"size-5",children:BX("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M18.375 12.739l-7.693 7.693a4.5 4.5 0 01-6.364-6.364l10.94-10.94A3 3 0 1119.5 7.372L8.552 18.32m.009-.01l-.01.01m5.699-9.941l-7.81 7.81a1.5 1.5 0 002.112 2.13"})}),KX=D$;import{jsx as A6,jsxs as R$,Fragment as A$}from"react/jsx-runtime";var N$=({name:Z,accept:J,fileInputRef:Y,onSelectFile:G,icons:Q})=>{return R$(A$,{children:[A6("button",{className:"rounded-md p-1 text-gray-500 ring-0 hover:bg-gray-100 disabled:opacity-40 disabled:hover:bg-transparent",type:"button",onClick:()=>{if(Y.current)Y.current.click()},children:Q.attachFileIcon?A6("img",{src:Q.attachFileIcon,alt:""}):A6(KX,{})}),A6("input",{id:Z+"__pie__file",name:Z+"__pie__file",className:"hidden",type:"file",accept:J,ref:Y,onChange:(X)=>{if(X.target.files)G(X.target.files[0])}})]})},LX=N$;import{jsx as MX}from"react/jsx-runtime";var P$=()=>MX("svg",{xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",strokeWidth:"1.5",stroke:"currentColor",className:"size-5 text-gray-500",children:MX("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M19.5 14.25v-2.625a3.375 3.375 0 00-3.375-3.375h-1.5A1.125 1.125 0 0113.5 7.125v-1.5a3.375 3.375 0 00-3.375-3.375H8.25m2.25 0H5.625c-.621 0-1.125.504-1.125 1.125v17.25c0 .621.504 1.125 1.125 1.125h12.75c.621 0 1.125-.504 1.125-1.125V11.25a9 9 0 00-9-9z"})}),$X=P$;import{jsx as FX}from"react/jsx-runtime";var T$=()=>FX("svg",{xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",strokeWidth:"1.5",stroke:"currentColor",className:"size-5",children:FX("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M6 18L18 6M6 6l12 12"})}),R6=T$;import{jsx as L5,jsxs as E$}from"react/jsx-runtime";var w$=({name:Z,selectedFile:J,onDropFile:Y})=>{return E$("div",{className:"flex w-full cursor-default flex-row items-center gap-2",children:[L5($X,{}),L5("span",{className:"flex-1",children:J.name}),L5("input",{type:"hidden",name:Z,value:""}),L5("button",{className:"rounded-md p-1 text-gray-500 ring-0 hover:bg-gray-100 disabled:opacity-40 disabled:hover:bg-transparent",type:"button",onClick:Y,children:L5(R6,{})})]})},OX=w$;import{jsx as VX,jsxs as x$}from"react/jsx-runtime";var S$=()=>x$("svg",{xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",strokeWidth:"1.5",stroke:"currentColor",className:"size-5",children:[VX("path",{d:"M8 5C8 2.79086 9.79086 1 12 1C14.2091 1 16 2.79086 16 5V12C16 14.2091 14.2091 16 12 16C9.79086 16 8 14.2091 8 12V5Z"}),VX("path",{d:"M6.25 11.8438V12C6.25 13.525 6.8558 14.9875 7.93414 16.0659C9.01247 17.1442 10.475 17.75 12 17.75C13.525 17.75 14.9875 17.1442 16.0659 16.0659C17.1442 14.9875 17.75 13.525 17.75 12V11.8438C17.75 11.2915 18.1977 10.8438 18.75 10.8438H19.25C19.8023 10.8438 20.25 11.2915 20.25 11.8437V12C20.25 14.188 19.3808 16.2865 17.8336 17.8336C16.5842 19.0831 14.9753 19.8903 13.25 20.1548V22C13.25 22.5523 12.8023 23 12.25 23H11.75C11.1977 23 10.75 22.5523 10.75 22V20.1548C9.02471 19.8903 7.41579 19.0831 6.16637 17.8336C4.61919 16.2865 3.75 14.188 3.75 12V11.8438C3.75 11.2915 4.19772 10.8438 4.75 10.8438H5.25C5.80228 10.8438 6.25 11.2915 6.25 11.8438Z"})]}),IX=S$;import{jsx as M5}from"react/jsx-runtime";var f$=({isListening:Z,toggleListening:J,icons:Y})=>{return M5("button",{className:"rounded-md p-1 text-gray-500 ring-0 hover:bg-gray-100 disabled:opacity-40 disabled:hover:bg-transparent",type:"button",onClick:J,children:Z?Y.cancelIcon?M5("img",{src:Y.cancelIcon,alt:""}):M5(R6,{}):Y.voiceRecordingIcon?M5("img",{src:Y.voiceRecordingIcon,alt:""}):M5(IX,{})})},qX=f$;import{jsx as DX,jsxs as j$}from"react/jsx-runtime";var C$=({option:Z,onClickOption:J})=>{return j$("div",{className:"flex w-fit cursor-pointer flex-row place-content-center items-center gap-1 rounded-md border border-black bg-white px-2 py-1 text-black",onClick:()=>{J(Z.title)},style:Z.sx,children:[Z.iconPosition==="start"&&DX("img",{src:Z.iconUrl,alt:""}),Z.title,Z.iconPosition==="end"&&DX("img",{src:Z.iconUrl,alt:""})]})},P6=C$;import{jsx as NX}from"react/jsx-runtime";var _$=({options:Z,handleOptionClick:J})=>{return NX("div",{className:"flex w-full flex-row flex-wrap justify-start gap-[5px]",children:Z.map((Y,G)=>{return NX(P6,{option:Y,onClickOption:J},G)})})},Q7=_$;import{jsx as x1,jsxs as RX}from"react/jsx-runtime";var b$=k$(({name:Z,defaultValue:J,defaultOptions:Y,isArea:G,placeholder:Q,fileAccept:X,optionsPosition:W,icons:H,handleOptionClick:z,handleSendMessage:U,sx:B},L)=>{let F=h$(null),[M,K]=T6(null),[$,O]=T6(J),[N,P]=T6(Y),[D,q]=T6(!1);v$(L,()=>({clear:()=>{if(O(""),K(null),F.current)F.current.value=""},setValue:(f)=>O(f),setOptions:(f)=>P(f)})),AX(()=>{O(J)},[J]),AX(()=>{},[]);let T=()=>{};return RX("div",{className:"flex flex-col items-center gap-[0.1rem]",id:Z+"_chat_input",style:B,children:[N&&W==="top"&&x1(Q7,{options:N,handleOptionClick:z}),x1("div",{className:"stretch relative flex size-full flex-1 flex-row items-stretch gap-3 last:mb-2 md:mx-4 md:flex-col md:last:mb-6 lg:mx-auto",children:RX("div",{className:"flex w-full grow flex-row items-center rounded-md bg-transparent",children:[M?x1(OX,{name:Z,selectedFile:M,onDropFile:()=>{if(K(null),F.current)F.current.value=""}}):!G?x1("input",{name:Z,value:$,onChange:(f)=>O(f.target.value),onKeyDown:(f)=>{if(f.key==="Enter")f.preventDefault(),U()},tabIndex:0,placeholder:Q,className:"m-0 w-full resize-none border-0 bg-transparent outline-none",style:{maxHeight:200,height:"100%",overflowY:"hidden"}}):x1(Y7,{name:Z,value:$,onChange:(f)=>O(f.target.value),onKeyDown:(f)=>{if(f.key==="Enter"&&!f.shiftKey)f.preventDefault(),U()},tabIndex:0,rows:2,placeholder:Q,className:"m-0 w-full resize-none border-0 bg-transparent p-0 pl-2 pr-7 outline-none md:pl-0",style:{maxHeight:200,height:"100%",minHeight:24}}),x1(qX,{isListening:D,toggleListening:T,icons:H}),x1(LX,{name:Z,fileInputRef:F,accept:X,onSelectFile:K,icons:H}),x1(UX,{onClick:U,icons:H})]})}),N&&W==="bottom"&&x1(Q7,{options:N,handleOptionClick:z})]})}),PX=b$;import{useState as p$,useEffect as l$}from"react";import{useEffect as g$,useState as y$}from"react";import{jsx as u$}from"react/jsx-runtime";function m$({children:Z}){let[J,Y]=y$(Z);return g$(()=>{Y(Z)},[Z]),u$("div",{className:"max-w-full first:mt-0",children:J})}var TX=m$;import{jsx as wX}from"react/jsx-runtime";var d$=()=>wX("svg",{width:"30",height:"30",viewBox:"0 0 16 16",xmlns:"http://www.w3.org/2000/svg",children:wX("path",{d:"m 8 1 c -1.65625 0 -3 1.34375 -3 3 s 1.34375 3 3 3 s 3 -1.34375 3 -3 s -1.34375 -3 -3 -3 z m -1.5 7 c -2.492188 0 -4.5 2.007812 -4.5 4.5 v 0.5 c 0 1.109375 0.890625 2 2 2 h 8 c 1.109375 0 2 -0.890625 2 -2 v -0.5 c 0 -2.492188 -2.007812 -4.5 -4.5 -4.5 z m 0 0",fill:"#2e3436"})}),EX=d$;import{jsx as w6}from"react/jsx-runtime";function c$({username:Z,avatar:J}){return w6("div",{className:"w-[30px]",children:w6("div",{className:"relative flex size-[30px] items-center justify-center rounded-sm p-1 text-white",children:J?w6("img",{src:J,className:"absolute inset-0 rounded",alt:Z}):w6(EX,{})})})}var X7=c$;import{jsx as N1,jsxs as SX}from"react/jsx-runtime";var i$=({message:Z,handleOptionClick:J,setUiAjaxConfiguration:Y})=>{let[G,Q]=p$(!1);return l$(()=>{let X=setTimeout(()=>{if(G)Q(!1)},1000);return()=>clearTimeout(X)},[G]),N1("div",{className:"group w-full border-b border-black/10",id:Z.id,children:SX("div",{className:`flex gap-4 p-4 text-base md:max-w-2xl md:gap-6 md:py-6 lg:max-w-3xl xl:max-w-5xl ${Z.align==="center"?"m-auto":""} ${Z.align==="right"?"ml-auto justify-end":""} ${Z.align==="left"?"mr-auto":""} `,children:[(Z.align==="left"||Z.align==="center")&&N1("div",{className:"relative flex shrink-0 flex-col items-end",children:N1(X7,{username:Z.username,avatar:Z.avatar})}),SX("div",{className:"relative flex w-[calc(100%-50px)] flex-col gap-1 md:gap-3 lg:w-[calc(100%-115px)]",children:[N1("div",{className:`markdown light prose w-full break-words dark:prose-invert first:mt-0 ${Z.align==="right"?"flex justify-end self-end":""}`,children:typeof Z.content==="string"?Z.parseMode.toLowerCase()==="markdown"?N1(TX,{children:Z.content},Date.now()+Math.random()):Z.parseMode.toLowerCase()==="html"?o1(Z.content):Z.content:N1(G1,{uiConfig:Z.content,setUiAjaxConfiguration:Y})}),N1("div",{className:"flex flex-row flex-wrap justify-start gap-1",children:Z.options.map((X,W)=>N1(P6,{onClickOption:J,option:X},W))})]}),Z.align==="right"&&N1("div",{className:"relative flex shrink-0 flex-col items-end",children:N1(X7,{username:Z.username,avatar:Z.avatar})})]})})},xX=i$;import{forwardRef as n$,useEffect as o$,useImperativeHandle as a$,useRef as s$,useState as r$}from"react";import{jsx as fX}from"react/jsx-runtime";var t$=n$(({name:Z,handleOptionClick:J,defaultMessages:Y,sx:G,setUiAjaxConfiguration:Q},X)=>{let[W,H]=r$(Y),z=s$(null),U=()=>{if(z.current)z.current.scrollTop=z.current.scrollHeight};return o$(()=>{U()},[W]),a$(X,()=>({setMessages:(B)=>H(B),addMessage:(B)=>H((L)=>[...L,B]),scrollToBottom:U})),fX("div",{id:Z+"_messages",className:"flex flex-col items-center overflow-y-scroll",style:G,ref:z,children:W.map((B)=>fX(xX,{message:B,handleOptionClick:J,setUiAjaxConfiguration:Q},B.id))})}),CX=t$;import{useEffect as e$,useRef as jX,useState as ZF}from"react";import{jsx as W7,jsxs as YF}from"react/jsx-runtime";var JF=({data:Z,setUiAjaxConfiguration:J})=>{let{name:Y,defaultValue:G,defaultMessages:Q,defaultOptions:X,isArea:W,fileAccept:H,placeholder:z,icons:U,optionsPosition:B,sxMap:L={container:{},chatInput:{},messages:{}},depsNames:F,pathname:M,kwargs:K,useSocketioSupport:$,useCentrifugeSupport:O,centrifugeChannel:N}=Z,P=jX(null),D=jX(null),[q,T]=ZF(!1),f=G5(J,K,F,M);e$(()=>{if(q)requestAnimationFrame(()=>{f(),T(!1)})},[q]);let u=(p)=>{if(P.current)P.current.setValue(p),T(!0)},a1=()=>{if(P.current)P.current.clear()},C1=(p)=>{if(P.current)P.current.setOptions(p.options)},j1=(p)=>{if(D.current)D.current.addMessage(p.message)},k=(p)=>{if(D.current)D.current.setMessages(p.messages)},R1=()=>{T(!0)};return W7(y,{card:"ChatCard",data:Z,methods:{clearInput:a1,setOptions:C1,addMessage:j1,setMessages:k},useSocketioSupport:$,useCentrifugeSupport:O,centrifugeChannel:N,children:YF("div",{className:"flex size-full flex-col",style:L.container,children:[W7(CX,{ref:D,name:Y,defaultMessages:Q,sx:L.messages,handleOptionClick:u,setUiAjaxConfiguration:J}),W7(PX,{ref:P,name:Y,isArea:W,defaultOptions:X,placeholder:z,defaultValue:G,fileAccept:H,sx:L.chatInput,handleSendMessage:R1,handleOptionClick:u,optionsPosition:B,icons:U})]})})},_X=JF;import{useEffect as GF,useState as QF}from"react";import{jsx as kX}from"react/jsx-runtime";var XF=({data:Z})=>{let{name:J,value:Y,useSocketioSupport:G,useCentrifugeSupport:Q,useMittSupport:X,centrifugeChannel:W}=Z,[H,z]=QF(Y);return GF(()=>{z(Y)},[Y]),kX(y,{card:"HiddenCard",data:Z,useSocketioSupport:G,useCentrifugeSupport:Q,useMittSupport:X,centrifugeChannel:W,methods:{update:({value:U})=>{z(U)}},children:kX("input",{type:"hidden",id:J,name:J,value:H})})},H7=XF;import{useContext as zF,useEffect as UF}from"react";import{createContext as WF}from"react";var HF=WF(void 0),A1=HF;import{jsx as LF,Fragment as KF}from"react/jsx-runtime";var BF=({data:Z})=>{let{url:J}=Z,Y=zF(A1);return UF(()=>{if(/^[a-zA-Z][a-zA-Z\d+\-.]*:\/\//.test(J))window.location.href=J;else Y?.(J)},[J,Y]),LF(KF,{})},z7=BF;import{useEffect as OF,useState as VF}from"react";import{useCallback as E6,useEffect as MF,useRef as U7,useState as $F}from"react";function FF(){let Z=new AudioContext,J=Z.createOscillator(),Y=J.connect(Z.createMediaStreamDestination());J.start();let G=Y.stream.getAudioTracks()[0];return G.enabled=!1,G}function B7(Z=null,J){let[Y,G]=$F(!1),Q=U7(null),X=U7(null),W=U7(null),H=E6(async(L,F=!0)=>{if(Q.current)z();let M=new RTCPeerConnection;if(M.onconnectionstatechange=()=>{if(M.connectionState==="connected")G(!0);else if(["disconnected","failed","closed"].includes(M.connectionState))G(!1)},M.ontrack=(q)=>{if(Z)Z.srcObject=q.streams[0]},F){let q=await navigator.mediaDevices.getUserMedia({audio:!0});M.addTrack(q.getTracks()[0],q)}else{let q=FF();M.addTrack(q)}let K=M.createDataChannel("oai-events");X.current=K,W.current=new Promise((q)=>{K.addEventListener("open",()=>{q()})});let $=await M.createOffer();await M.setLocalDescription($);let D=await(await fetch(`${"https://api.openai.com/v1/realtime/calls"}?model=${"gpt-realtime"}`,{method:"POST",body:$.sdp,headers:{Authorization:`Bearer ${L}`,"Content-Type":"application/sdp"}})).text();await M.setRemoteDescription({type:"answer",sdp:D}),Q.current=M,await W.current},[Z]),z=E6(()=>{let L=X.current;if(L)L.close();Q.current?.getSenders()?.forEach((F)=>F.track?.stop()),Q.current?.close(),G(!1),Q.current=null,X.current=null,W.current=null},[Z]),U=E6((L)=>{let F=X.current;if(!F){console.error("Data channel is not ready",L);return}let M=new Date().toLocaleTimeString();if(L.event_id=L.event_id||crypto.randomUUID(),F.send(JSON.stringify(L)),!L.timestamp)L.timestamp=M;J?.(L)},[J,Z]),B=E6((L)=>{if(!X.current){console.error("Data channel is not ready");return}let M=()=>{U({type:"conversation.item.create",item:{type:"message",role:"user",content:[{type:"input_text",text:L}]}}),U({type:"response.create"})};if(W.current)W.current.then(M);else M()},[J,Z]);return MF(()=>{let L=X.current;if(!L)return;let F=(M)=>{let K=JSON.parse(M.data);if(!K.timestamp)K.timestamp=new Date().toLocaleTimeString();J?.(K)};return L.addEventListener("message",F),()=>{L.removeEventListener("message",F)}},[J,Z]),{isSessionActive:Y,startSession:H,stopSession:z,sendTextMessage:B}}import{jsx as qF}from"react/jsx-runtime";var IF=({data:Z})=>{let{html:J,useSocketioSupport:Y,useCentrifugeSupport:G,useMittSupport:Q,centrifugeChannel:X}=Z,[W,H]=VF(J),{isSessionActive:z,startSession:U,sendTextMessage:B}=B7(null,(K)=>{if(console.log(K.type,K.type==="response.output_text.delta"&&K.delta),K.type==="response.output_text.delta"&&K.delta)H(($)=>$+K.delta)});return OF(()=>{H(J)},[J]),qF(y,{card:"HTMLEmbedCard",data:Z,methods:{update:(K)=>{H(K.value)},generateUsingAI:async(K)=>{try{if(!z&&K.token)await U(K.token,!1);B(K.prompt)}catch($){console.error("Failed to generate using AI",$)}},initializeAI:async(K)=>{if(!z&&K.token)await U(K.token,!1)}},useCentrifugeSupport:G,useSocketioSupport:Y,useMittSupport:Q,centrifugeChannel:X,children:o1(W)})},K7=n(IF);import{useContext as DF}from"react";import{jsx as L7,Fragment as vX}from"react/jsx-runtime";var NF=({data:Z})=>{let{useCentrifugeSupport:J,useSocketioSupport:Y,useMittSupport:G,centrifugeChannel:Q}=Z,X=DF(A1);return L7(vX,{children:L7(y,{card:"IOEventsCard",data:Z,useCentrifugeSupport:J,useSocketioSupport:Y,useMittSupport:G,centrifugeChannel:Q,methods:{log:(z)=>{console.log("Log event",z)},redirect:(z)=>{if(z.to){let U=z.to;if(/^[a-zA-Z][a-zA-Z\d+\-.]*:\/\//.test(U))window.location.href=U;else X?.(U)}else window.location.reload()}},children:L7(vX,{})})})},M7=NF;import{useContext as AF}from"react";import{jsx as $7,jsxs as PF}from"react/jsx-runtime";var RF=({data:Z})=>{let{name:J,title:Y,url:G,iconUrl:Q,iconPosition:X,sx:W}=Z,H=AF(A1);return $7(y,{card:"RedirectButtonCard",data:Z,children:PF("button",{id:J,className:"box-border flex min-h-12 w-full min-w-min cursor-pointer items-center justify-center gap-4 rounded-l border border-black bg-white text-center text-black hover:bg-neutral-300",value:J,onClick:(U)=>{if(G)if(U.stopPropagation(),/^[a-zA-Z][a-zA-Z\d+\-.]*:\/\//.test(G))window.location.href=G;else H?.(G)},style:R0(W),type:"button",children:[Q&&X==="start"&&$7("img",{src:Q,alt:""}),o1(Y),Q&&X==="end"&&$7("img",{src:Q,alt:""})]})})},F7=n(RF);var O7=!1;function $5(){if(O7)return;U1({name:"SequenceCard",component:sG,metadata:{author:"PieData",description:"Simple div with styles joining few components"}}),U1({name:"UnionCard",component:tG,metadata:{author:"PieData",description:"Renders one of many components"}}),U1({name:"AjaxGroupCard",component:YQ,metadata:{author:"PieData",description:"Group card with AJAX support"}}),U1({name:"AjaxButtonCard",component:WX,metadata:{author:"PieData",description:"Button with AJAX support"}}),U1({name:"RedirectButtonCard",component:F7,metadata:{author:"PieData",description:"Button with Redirect on click"}}),U1({name:"ChatCard",component:_X,metadata:{author:"PieData"}}),U1({name:"HiddenCard",component:H7,metadata:{author:"PieData"}}),U1({name:"AutoRedirectCard",component:z7,metadata:{author:"PieData"}}),U1({name:"HTMLEmbedCard",component:K7,metadata:{author:"PieData"}}),U1({name:"IOEventsCard",component:M7,metadata:{author:"PieData"}}),O7=!0}function f1(){return O7}import{jsx as H1,Fragment as jF}from"react/jsx-runtime";var fF=({location:Z,fallback:J,onError:Y,initializePie:G})=>{let Q=h1(),X=O5(),W=b1();TF(()=>{if(f1())return;$5(),G()},[]);let H=wF(()=>hX.createAxiosDateTransformer({baseURL:Q||""}),[Q]),{data:z,isLoading:U,error:B}=xF({queryKey:["uiConfig",Z.pathname+Z.search,f1(),Q],queryFn:async()=>{if(!Q||!f1())return;let L="/api/content"+Z.pathname+(Z.search.startsWith("?")?Z.search:`?${Z.search}`);if(W)console.log("[PieRoot] Fetching UI configuration from:",L);let F=await H.get(L,{headers:{"Access-Control-Allow-Origin":"*","Access-Control-Allow-Methods":"GET,PUT,POST,DELETE,PATCH,OPTIONS","Content-type":"application/json"},withCredentials:!0});if(W)console.log("[PieRoot] Received UI configuration:",F.data);return F.data},staleTime:1/0,gcTime:1/0,refetchOnWindowFocus:!1,refetchOnMount:!1,refetchOnReconnect:!1,retry:!0,retryDelay:(L)=>Math.min(1000*2**L,30000)});if(!Q)return J??null;if(W)console.log("[PieRoot] Rendering with location:",Z),console.log("[PieRoot] API_SERVER:",Q),console.log("[PieRoot] Fallback provided:",!!J);if(B){if(W)console.error("[PieRoot] Error fetching UI configuration:",B),console.error("[PieRoot] Error details:",{message:B.message,status:B.response?.status,data:B.response?.data});return Y?.(),J}if(U||!z){if(W)console.log("[PieRoot] Loading state:",{isLoading:U,hasUiConfiguration:!!z});return J}if(W)console.log("[PieRoot] UI configuration loaded successfully:",z),console.log("[PieRoot] Rendering UI with configuration");return H1(u1.Provider,{value:v0,children:H1(c1.Provider,{value:p5(Q),children:H1(l1.Provider,{value:r5(Q,X),children:H1(v1.Provider,{value:J??H1(jF,{}),children:H1(e5,{children:H1(Z6,{children:H1(n.StyleRoot,{style:{display:"contents"},children:H1(G1,{uiConfig:z})})})})})})})})},CF=(Z)=>{let J=new EF;return H1(A1.Provider,{value:Z.onNavigate,children:H1(S0.Provider,{value:Z.config,children:H1(SF,{client:J,children:H1(fF,{...Z})})})})},_F=CF;import{useEffect as hF,useMemo as bF}from"react";import{QueryClient as gF,QueryClientProvider as yF,useQuery as mF}from"@tanstack/react-query";var gX=S(x9(),1);import{useEffect as kF,useState as vF}from"react";var bX=()=>{let[Z,J]=vF(null),Y=w7();return kF(()=>{if(typeof window>"u")return;let G=window.Telegram.WebApp;if(G.ready(),Y==="telegram_expanded"&&(G.platform==="ios"||G.platform==="android"))G.expand();J(G)},[]),Z};import{jsx as z1,Fragment as cF}from"react/jsx-runtime";var uF=({location:Z,fallback:J,onError:Y,initializePie:G})=>{let Q=h1(),X=O5(),W=b1();hF(()=>{if(f1())return;$5(),G()},[]);let H=bF(()=>gX.createAxiosDateTransformer({baseURL:Q}),[]);if(W)console.log("[PieRoot] Rendering with location:",Z),console.log("[PieRoot] API_SERVER:",Q),console.log("[PieRoot] Fallback provided:",!!J);if(!Q)throw Error("Set PIE_API_SERVER and PIE_CENTRIFUGE_SERVER");let z=bX(),{data:U,isLoading:B,error:L}=mF({queryKey:["uiConfig",Z.pathname+Z.search,z?.initData,f1()],queryFn:async()=>{if(!f1())return;let F=Z.search?"&":"",M=z?.initData?`${F}initData=${encodeURIComponent(z.initData)}`:"",K="/api/content"+Z.pathname+(Z.search.startsWith("?")?Z.search:`?${Z.search}`)+M;if(W)console.log("[PieRoot] Fetching UI configuration from:",K);let $=await H.get(K,{headers:{"Access-Control-Allow-Origin":"*","Access-Control-Allow-Methods":"GET,PUT,POST,DELETE,PATCH,OPTIONS","Content-type":"application/json"},withCredentials:!0});if(W)console.log("[PieRoot] Received UI configuration:",$.data);return $.data},staleTime:1/0,gcTime:1/0,refetchOnWindowFocus:!1,refetchOnMount:!1,refetchOnReconnect:!1,retry:!0,retryDelay:(F)=>Math.min(1000*2**F,30000)});if(L&&W)return console.error("[PieRoot] Error fetching UI configuration:",L),console.error("[PieRoot] Error details:",{message:L.message,status:L.response?.status,data:L.response?.data}),Y?.(),J;if(B||!U){if(W)console.log("[PieRoot] Loading state:",{isLoading:B,hasUiConfiguration:!!U});return J}if(W)console.log("[PieRoot] UI configuration loaded successfully:",U),console.log("[PieRoot] Rendering UI with configuration");return z1(u1.Provider,{value:v0,children:z1(c1.Provider,{value:p5(Q),children:z1(l1.Provider,{value:r5(Q,X),children:z1(v1.Provider,{value:J??z1(cF,{}),children:z1(e5,{children:z1(Z6,{children:z1(n.StyleRoot,{children:z1(G1,{uiConfig:U})})})})})})})})},dF=(Z)=>{let J=new gF;return z1(A1.Provider,{value:Z.onNavigate,children:z1(S0.Provider,{value:Z.config,children:z1(yF,{client:J,children:z1(uF,{...Z})})})})},pF=dF;export{G5 as useAjaxSubmit,U1 as registerPieComponent,f1 as isPieComponentsInitialized,$5 as initializePieComponents,G1 as UI,pF as PieTelegramRoot,_F as PieRoot,y as PieCard};
|
package/dist/index.js
CHANGED
|
@@ -49,4 +49,4 @@ var Dm=Object.create;var{getPrototypeOf:Tm,defineProperty:Z0,getOwnPropertyNames
|
|
|
49
49
|
`)throw Error("size integer not terminated by '\\n'");let Y=new VX;while(v.haveBytes()){let G=v.getInt(),X;switch(v.getChar()){case"@":if(X=v.getInt(),v.haveBytes()&&v.getChar()!==",")throw Error("copy command not terminated by ','");if(x+=G,x>J)throw Error("copy exceeds output file size");if(X+G>z)throw Error("copy extends past end of input");Y.putArray(i,X,X+G);break;case":":if(x+=G,x>J)throw Error("insert command gives an output larger than predicted");if(G>Z)throw Error("insert count exceeds size of delta");Y.putArray(v.a,v.pos,v.pos+G),v.pos+=G;break;case";":{let Q=Y.toByteArray(i);if(G!==aq(Q))throw Error("bad checksum");if(x!==J)throw Error("generated size does not match predicted size");return Q}default:throw Error("unknown delta operator")}}throw Error("unterminated delta")}class F9{name(){return"json"}encodeCommands(i){return i.map((c)=>JSON.stringify(c)).join(`
|
|
50
50
|
`)}decodeReplies(i){return i.trim().split(`
|
|
51
51
|
`).map((c)=>JSON.parse(c))}applyDeltaIfNeeded(i,c){let x,v;if(i.delta){let z=jq(c,new TextEncoder().encode(i.data));x=JSON.parse(new TextDecoder().decode(z)),v=z}else x=JSON.parse(i.data),v=new TextEncoder().encode(i.data);return{newData:x,newPrevValue:v}}}var Eq={headers:{},token:"",getToken:null,data:null,getData:null,debug:!1,name:"js",version:"",fetch:null,readableStream:null,websocket:null,eventsource:null,sockjs:null,sockjsOptions:{},emulationEndpoint:"/emulation",minReconnectDelay:500,maxReconnectDelay:20000,timeout:5000,maxServerPingDelay:1e4,networkEventTarget:null};class Dc extends Error{constructor(i){super(i);this.name=this.constructor.name}}class hx extends XX{constructor(i,c){super();if(this._reconnectTimeout=null,this._refreshTimeout=null,this._serverPingTimeout=null,this.state=Qi.Disconnected,this._transportIsOpen=!1,this._endpoint=i,this._emulation=!1,this._transports=[],this._currentTransportIndex=0,this._triedAllTransports=!1,this._transportWasOpen=!1,this._transport=null,this._transportId=0,this._deviceWentOffline=!1,this._transportClosed=!0,this._codec=new F9,this._reconnecting=!1,this._reconnectTimeout=null,this._reconnectAttempts=0,this._client=null,this._session="",this._node="",this._subs={},this._serverSubs={},this._commandId=0,this._commands=[],this._batching=!1,this._refreshRequired=!1,this._refreshTimeout=null,this._callbacks={},this._token="",this._data=null,this._dispatchPromise=Promise.resolve(),this._serverPing=0,this._serverPingTimeout=null,this._sendPong=!1,this._promises={},this._promiseId=0,this._debugEnabled=!1,this._networkEventsSet=!1,this._config=Object.assign(Object.assign({},Eq),c),this._configure(),this._debugEnabled)this.on("state",(x)=>{this._debug("client state",x.oldState,"->",x.newState)}),this.on("error",(x)=>{this._debug("client error",x)});else this.on("error",function(){Function.prototype()})}newSubscription(i,c){if(this.getSubscription(i)!==null)throw Error("Subscription to the channel "+i+" already exists");let x=new pX(this,i,c);return this._subs[i]=x,x}getSubscription(i){return this._getSub(i)}removeSubscription(i){if(!i)return;if(i.state!==Ci.Unsubscribed)i.unsubscribe();this._removeSubscription(i)}subscriptions(){return this._subs}ready(i){return Ti(this,void 0,void 0,function*(){switch(this.state){case Qi.Disconnected:throw{code:t.clientDisconnected,message:"client disconnected"};case Qi.Connected:return;default:return new Promise((c,x)=>{let v={resolve:c,reject:x};if(i)v.timeout=setTimeout(()=>{x({code:t.timeout,message:"timeout"})},i);this._promises[this._nextPromiseId()]=v})}})}connect(){if(this._isConnected()){this._debug("connect called when already connected");return}if(this._isConnecting()){this._debug("connect called when already connecting");return}this._debug("connect called"),this._reconnectAttempts=0,this._startConnecting()}disconnect(){this._disconnect(a0.disconnectCalled,"disconnect called",!1)}setToken(i){this._token=i}setData(i){this._data=i}setHeaders(i){this._config.headers=i}send(i){return Ti(this,void 0,void 0,function*(){let c={send:{data:i}};if(yield this._methodCall(),!this._transportSendCommands([c]))throw this._createErrorObject(t.transportWriteError,"transport write error")})}rpc(i,c){return Ti(this,void 0,void 0,function*(){let x={rpc:{method:i,data:c}};return yield this._methodCall(),{data:(yield this._callPromise(x,(z)=>z.rpc)).data}})}publish(i,c){return Ti(this,void 0,void 0,function*(){let x={publish:{channel:i,data:c}};return yield this._methodCall(),yield this._callPromise(x,()=>({})),{}})}history(i,c){return Ti(this,void 0,void 0,function*(){let x={history:this._getHistoryRequest(i,c)};yield this._methodCall();let v=yield this._callPromise(x,(Z)=>Z.history),z=[];if(v.publications)for(let Z=0;Z<v.publications.length;Z++)z.push(this._getPublicationContext(i,v.publications[Z]));return{publications:z,epoch:v.epoch||"",offset:v.offset||0}})}presence(i){return Ti(this,void 0,void 0,function*(){let c={presence:{channel:i}};yield this._methodCall();let v=(yield this._callPromise(c,(z)=>z.presence)).presence;for(let z in v)if(Object.prototype.hasOwnProperty.call(v,z)){let Z=v[z],J=Z.conn_info,Y=Z.chan_info;if(J)Z.connInfo=J;if(Y)Z.chanInfo=Y}return{clients:v}})}presenceStats(i){return Ti(this,void 0,void 0,function*(){let c={presence_stats:{channel:i}};yield this._methodCall();let x=yield this._callPromise(c,(v)=>{return v.presence_stats});return{numUsers:x.num_users,numClients:x.num_clients}})}startBatching(){this._batching=!0}stopBatching(){let i=this;Promise.resolve().then(function(){Promise.resolve().then(function(){i._batching=!1,i._flush()})})}_debug(...i){if(!this._debugEnabled)return;Dq("debug",i)}_codecName(){return this._codec.name()}_formatOverride(){return}_configure(){if(!("Promise"in globalThis))throw Error("Promise polyfill required");if(!this._endpoint)throw Error("endpoint configuration required");if(this._config.token!==null)this._token=this._config.token;if(this._config.data!==null)this._data=this._config.data;if(this._codec=new F9,this._formatOverride(),this._config.debug===!0||typeof localStorage<"u"&&typeof localStorage.getItem==="function"&&localStorage.getItem("centrifuge.debug"))this._debugEnabled=!0;if(this._debug("config",this._config),typeof this._endpoint==="string");else if(Array.isArray(this._endpoint)){this._transports=this._endpoint,this._emulation=!0;for(let i in this._transports)if(this._transports.hasOwnProperty(i)){let c=this._transports[i];if(!c.endpoint||!c.transport)throw Error("malformed transport configuration");let x=c.transport;if(["websocket","http_stream","sse","sockjs","webtransport"].indexOf(x)<0)throw Error("unsupported transport name: "+x)}}else throw Error("unsupported url configuration type: only string or array of objects are supported")}_setState(i){if(this.state!==i){this._reconnecting=!1;let c=this.state;return this.state=i,this.emit("state",{newState:i,oldState:c}),!0}return!1}_isDisconnected(){return this.state===Qi.Disconnected}_isConnecting(){return this.state===Qi.Connecting}_isConnected(){return this.state===Qi.Connected}_nextCommandId(){return++this._commandId}_setNetworkEvents(){if(this._networkEventsSet)return;let i=null;if(this._config.networkEventTarget!==null)i=this._config.networkEventTarget;else if(typeof globalThis.addEventListener<"u")i=globalThis;if(i)i.addEventListener("offline",()=>{if(this._debug("offline event triggered"),this.state===Qi.Connected||this.state===Qi.Connecting)this._disconnect(Ux.transportClosed,"transport closed",!0),this._deviceWentOffline=!0}),i.addEventListener("online",()=>{if(this._debug("online event triggered"),this.state!==Qi.Connecting)return;if(this._deviceWentOffline&&!this._transportClosed)this._deviceWentOffline=!1,this._transportClosed=!0;this._clearReconnectTimeout(),this._startReconnecting()}),this._networkEventsSet=!0}_getReconnectDelay(){let i=H6(this._reconnectAttempts,this._config.minReconnectDelay,this._config.maxReconnectDelay);return this._reconnectAttempts+=1,i}_clearOutgoingRequests(){for(let i in this._callbacks)if(this._callbacks.hasOwnProperty(i)){let c=this._callbacks[i];clearTimeout(c.timeout);let x=c.errback;if(!x)continue;x({error:this._createErrorObject(t.connectionClosed,"connection closed")})}this._callbacks={}}_clearConnectedState(){this._client=null,this._clearServerPingTimeout(),this._clearRefreshTimeout();for(let i in this._subs){if(!this._subs.hasOwnProperty(i))continue;let c=this._subs[i];if(c.state===Ci.Subscribed)c._setSubscribing(W6.transportClosed,"transport closed")}for(let i in this._serverSubs)if(this._serverSubs.hasOwnProperty(i))this.emit("subscribing",{channel:i})}_handleWriteError(i){for(let c of i){let x=c.id;if(!(x in this._callbacks))continue;let v=this._callbacks[x];clearTimeout(this._callbacks[x].timeout),delete this._callbacks[x];let z=v.errback;z({error:this._createErrorObject(t.transportWriteError,"transport write error")})}}_transportSendCommands(i){if(!i.length)return!0;if(!this._transport)return!1;try{this._transport.send(this._codec.encodeCommands(i),this._session,this._node)}catch(c){return this._debug("error writing commands",c),this._handleWriteError(i),!1}return!0}_initializeTransport(){let i;if(this._config.websocket!==null)i=this._config.websocket;else if(!(typeof globalThis.WebSocket!=="function"&&typeof globalThis.WebSocket!=="object"))i=globalThis.WebSocket;let c=null;if(this._config.sockjs!==null)c=this._config.sockjs;else if(typeof globalThis.SockJS<"u")c=globalThis.SockJS;let x=null;if(this._config.eventsource!==null)x=this._config.eventsource;else if(typeof globalThis.EventSource<"u")x=globalThis.EventSource;let v=null;if(this._config.fetch!==null)v=this._config.fetch;else if(typeof globalThis.fetch<"u")v=globalThis.fetch;let z=null;if(this._config.readableStream!==null)z=this._config.readableStream;else if(typeof globalThis.ReadableStream<"u")z=globalThis.ReadableStream;if(!this._emulation){if(Pq(this._endpoint,"http"))throw Error("Provide explicit transport endpoints configuration in case of using HTTP (i.e. using array of TransportEndpoint instead of a single string), or use ws(s):// scheme in an endpoint if you aimed using WebSocket transport");else if(this._debug("client will use websocket"),this._transport=new $9(this._endpoint,{websocket:i}),!this._transport.supported())throw Error("WebSocket constructor not found, make sure it is available globally or passed as a dependency in Centrifuge options")}else{if(this._currentTransportIndex>=this._transports.length)this._triedAllTransports=!0,this._currentTransportIndex=0;let W=0;while(!0){if(W>=this._transports.length)throw Error("no supported transport found");let H=this._transports[this._currentTransportIndex],K=H.transport,m=H.endpoint;if(K==="websocket"){if(this._debug("trying websocket transport"),this._transport=new $9(m,{websocket:i}),!this._transport.supported()){this._debug("websocket transport not available"),this._currentTransportIndex++,W++;continue}}else if(K==="webtransport"){if(this._debug("trying webtransport transport"),this._transport=new HX(m,{webtransport:globalThis.WebTransport,decoder:this._codec,encoder:this._codec}),!this._transport.supported()){this._debug("webtransport transport not available"),this._currentTransportIndex++,W++;continue}}else if(K==="http_stream"){if(this._debug("trying http_stream transport"),this._transport=new WX(m,{fetch:v,readableStream:z,emulationEndpoint:this._config.emulationEndpoint,decoder:this._codec,encoder:this._codec}),!this._transport.supported()){this._debug("http_stream transport not available"),this._currentTransportIndex++,W++;continue}}else if(K==="sse"){if(this._debug("trying sse transport"),this._transport=new mX(m,{eventsource:x,fetch:v,emulationEndpoint:this._config.emulationEndpoint}),!this._transport.supported()){this._debug("sse transport not available"),this._currentTransportIndex++,W++;continue}}else if(K==="sockjs"){if(this._debug("trying sockjs"),this._transport=new KX(m,{sockjs:c,sockjsOptions:this._config.sockjsOptions}),!this._transport.supported()){this._debug("sockjs transport not available"),this._currentTransportIndex++,W++;continue}}else throw Error("unknown transport "+K);break}}let Z=this,J=this._transport,Y=this._nextTransportId();Z._debug("id of transport",Y);let G=!1,X=[];if(this._transport.emulation()){let W=Z._sendConnect(!0);X.push(W)}this._setNetworkEvents();let Q=this._codec.encodeCommands(X);this._transportClosed=!1;let p;p=setTimeout(function(){J.close()},this._config.timeout),this._transport.initialize(this._codecName(),{onOpen:function(){if(p)clearTimeout(p),p=null;if(Z._transportId!=Y){Z._debug("open callback from non-actual transport"),J.close();return}if(G=!0,Z._debug(J.subName(),"transport open"),J.emulation())return;Z._transportIsOpen=!0,Z._transportWasOpen=!0,Z.startBatching(),Z._sendConnect(!1),Z._sendSubscribeCommands(),Z.stopBatching(),Z.emit("__centrifuge_debug:connect_frame_sent",{})},onError:function(W){if(Z._transportId!=Y){Z._debug("error callback from non-actual transport");return}Z._debug("transport level error",W)},onClose:function(W){if(p)clearTimeout(p),p=null;if(Z._transportId!=Y){Z._debug("close callback from non-actual transport");return}Z._debug(J.subName(),"transport closed"),Z._transportClosed=!0,Z._transportIsOpen=!1;let H="connection closed",K=!0,m=0;if(W&&"code"in W&&W.code)m=W.code;if(W&&W.reason)try{let U=JSON.parse(W.reason);H=U.reason,K=U.reconnect}catch(U){if(H=W.reason,m>=3500&&m<4000||m>=4500&&m<5000)K=!1}if(m<3000){if(m===1009)m=a0.messageSizeLimit,H="message size limit exceeded",K=!1;else m=Ux.transportClosed,H="transport closed";if(Z._emulation&&!Z._transportWasOpen){if(Z._currentTransportIndex++,Z._currentTransportIndex>=Z._transports.length)Z._triedAllTransports=!0,Z._currentTransportIndex=0}}else Z._transportWasOpen=!0;if(Z._isConnecting()&&!G)Z.emit("error",{type:"transport",error:{code:t.transportClosed,message:"transport closed"},transport:J.name()});Z._reconnecting=!1,Z._disconnect(m,H,K)},onMessage:function(W){Z._dataReceived(W)}},Q),Z.emit("__centrifuge_debug:transport_initialized",{})}_sendConnect(i){let c=this._constructConnectCommand(),x=this;return this._call(c,i).then((v)=>{let z=v.reply.connect;if(x._connectResponse(z),v.next)v.next()},(v)=>{if(x._connectError(v.error),v.next)v.next()}),c}_startReconnecting(){if(this._debug("start reconnecting"),!this._isConnecting()){this._debug("stop reconnecting: client not in connecting state");return}if(this._reconnecting){this._debug("reconnect already in progress, return from reconnect routine");return}if(this._transportClosed===!1){this._debug("waiting for transport close");return}this._reconnecting=!0;let i=this._token==="";if(!(this._refreshRequired||i&&this._config.getToken!==null)){if(this._config.getData)this._config.getData().then((v)=>{if(!this._isConnecting())return;this._data=v,this._initializeTransport()}).catch((v)=>this._handleGetDataError(v));else this._initializeTransport();return}let x=this;this._getToken().then(function(v){if(!x._isConnecting())return;if(v==null||v==null){x._failUnauthorized();return}if(x._token=v,x._debug("connection token refreshed"),x._config.getData)x._config.getData().then(function(z){if(!x._isConnecting())return;x._data=z,x._initializeTransport()}).catch((z)=>x._handleGetDataError(z));else x._initializeTransport()}).catch(function(v){if(!x._isConnecting())return;if(v instanceof Dc){x._failUnauthorized();return}x.emit("error",{type:"connectToken",error:{code:t.clientConnectToken,message:v!==void 0?v.toString():""}});let z=x._getReconnectDelay();x._debug("error on getting connection token, reconnect after "+z+" milliseconds",v),x._reconnecting=!1,x._reconnectTimeout=setTimeout(()=>{x._startReconnecting()},z)})}_handleGetDataError(i){if(i instanceof Dc){this._failUnauthorized();return}this.emit("error",{type:"connectData",error:{code:t.badConfiguration,message:(i===null||i===void 0?void 0:i.toString())||""}});let c=this._getReconnectDelay();this._debug("error on getting connect data, reconnect after "+c+" milliseconds",i),this._reconnecting=!1,this._reconnectTimeout=setTimeout(()=>{this._startReconnecting()},c)}_connectError(i){if(this.state!==Qi.Connecting)return;if(i.code===109)this._refreshRequired=!0;if(i.code<100||i.temporary===!0||i.code===109)this.emit("error",{type:"connect",error:i}),this._debug("closing transport due to connect error"),this._disconnect(i.code,i.message,!0);else this._disconnect(i.code,i.message,!1)}_scheduleReconnect(){if(!this._isConnecting())return;let i=!1;if(this._emulation&&!this._transportWasOpen&&!this._triedAllTransports)i=!0;let c=this._getReconnectDelay();if(i)c=0;this._debug("reconnect after "+c+" milliseconds"),this._clearReconnectTimeout(),this._reconnectTimeout=setTimeout(()=>{this._startReconnecting()},c)}_constructConnectCommand(){let i={};if(this._token)i.token=this._token;if(this._data)i.data=this._data;if(this._config.name)i.name=this._config.name;if(this._config.version)i.version=this._config.version;if(Object.keys(this._config.headers).length>0)i.headers=this._config.headers;let c={},x=!1;for(let v in this._serverSubs)if(this._serverSubs.hasOwnProperty(v)&&this._serverSubs[v].recoverable){x=!0;let z={recover:!0};if(this._serverSubs[v].offset)z.offset=this._serverSubs[v].offset;if(this._serverSubs[v].epoch)z.epoch=this._serverSubs[v].epoch;c[v]=z}if(x)i.subs=c;return{connect:i}}_getHistoryRequest(i,c){let x={channel:i};if(c!==void 0){if(c.since){if(x.since={offset:c.since.offset},c.since.epoch)x.since.epoch=c.since.epoch}if(c.limit!==void 0)x.limit=c.limit;if(c.reverse===!0)x.reverse=!0}return x}_methodCall(){if(this._isConnected())return Promise.resolve();return new Promise((i,c)=>{let x=setTimeout(function(){c({code:t.timeout,message:"timeout"})},this._config.timeout);this._promises[this._nextPromiseId()]={timeout:x,resolve:i,reject:c}})}_callPromise(i,c){return new Promise((x,v)=>{this._call(i,!1).then((z)=>{var Z;let J=c(z.reply);x(J),(Z=z.next)===null||Z===void 0||Z.call(z)},(z)=>{var Z;v(z.error),(Z=z.next)===null||Z===void 0||Z.call(z)})})}_dataReceived(i){if(this._serverPing>0)this._waitServerPing();let c=this._codec.decodeReplies(i);this._dispatchPromise=this._dispatchPromise.then(()=>{let x;this._dispatchPromise=new Promise((v)=>{x=v}),this._dispatchSynchronized(c,x)})}_dispatchSynchronized(i,c){let x=Promise.resolve();for(let v in i)if(i.hasOwnProperty(v))x=x.then(()=>{return this._dispatchReply(i[v])});x=x.then(()=>{c()})}_dispatchReply(i){let c,x=new Promise((z)=>{c=z});if(i===void 0||i===null)return this._debug("dispatch: got undefined or null reply"),c(),x;let v=i.id;if(v&&v>0)this._handleReply(i,c);else if(!i.push)this._handleServerPing(c);else this._handlePush(i.push,c);return x}_call(i,c){return new Promise((x,v)=>{if(i.id=this._nextCommandId(),this._registerCall(i.id,x,v),!c)this._addCommand(i)})}_startConnecting(){if(this._debug("start connecting"),this._setState(Qi.Connecting))this.emit("connecting",{code:Ux.connectCalled,reason:"connect called"});this._client=null,this._startReconnecting()}_disconnect(i,c,x){if(this._isDisconnected())return;this._transportIsOpen=!1;let v=this.state;this._reconnecting=!1;let z={code:i,reason:c},Z=!1;if(x)Z=this._setState(Qi.Connecting);else Z=this._setState(Qi.Disconnected),this._rejectPromises({code:t.clientDisconnected,message:"disconnected"});if(this._clearOutgoingRequests(),v===Qi.Connecting)this._clearReconnectTimeout();if(v===Qi.Connected)this._clearConnectedState();if(Z)if(this._isConnecting())this.emit("connecting",z);else this.emit("disconnected",z);if(this._transport){this._debug("closing existing transport");let J=this._transport;this._transport=null,J.close(),this._transportClosed=!0,this._nextTransportId()}else this._debug("no transport to close");this._scheduleReconnect()}_failUnauthorized(){this._disconnect(a0.unauthorized,"unauthorized",!1)}_getToken(){if(this._debug("get connection token"),!this._config.getToken)return this.emit("error",{type:"configuration",error:{code:t.badConfiguration,message:"token expired but no getToken function set in the configuration"}}),Promise.reject(new Dc(""));return this._config.getToken({})}_refresh(){let i=this._client,c=this;this._getToken().then(function(x){if(i!==c._client)return;if(!x){c._failUnauthorized();return}if(c._token=x,c._debug("connection token refreshed"),!c._isConnected())return;let v={refresh:{token:c._token}};c._call(v,!1).then((z)=>{let Z=z.reply.refresh;if(c._refreshResponse(Z),z.next)z.next()},(z)=>{if(c._refreshError(z.error),z.next)z.next()})}).catch(function(x){if(!c._isConnected())return;if(x instanceof Dc){c._failUnauthorized();return}c.emit("error",{type:"refreshToken",error:{code:t.clientRefreshToken,message:x!==void 0?x.toString():""}}),c._refreshTimeout=setTimeout(()=>c._refresh(),c._getRefreshRetryDelay())})}_refreshError(i){if(i.code<100||i.temporary===!0)this.emit("error",{type:"refresh",error:i}),this._refreshTimeout=setTimeout(()=>this._refresh(),this._getRefreshRetryDelay());else this._disconnect(i.code,i.message,!1)}_getRefreshRetryDelay(){return H6(0,5000,1e4)}_refreshResponse(i){if(this._refreshTimeout)clearTimeout(this._refreshTimeout),this._refreshTimeout=null;if(i.expires)this._client=i.client,this._refreshTimeout=setTimeout(()=>this._refresh(),U6(i.ttl))}_removeSubscription(i){if(i===null)return;delete this._subs[i.channel]}_unsubscribe(i){if(!this._transportIsOpen)return Promise.resolve();let x={unsubscribe:{channel:i.channel}},v=this;return new Promise((Z,J)=>{this._call(x,!1).then((Y)=>{if(Z(),Y.next)Y.next()},(Y)=>{if(Z(),Y.next)Y.next();v._disconnect(Ux.unsubscribeError,"unsubscribe error",!0)})})}_getSub(i,c){if(c&&c>0){for(let v in this._subs)if(this._subs.hasOwnProperty(v)){let z=this._subs[v];if(z._id===c)return z}return null}let x=this._subs[i];if(!x)return null;return x}_isServerSub(i){return this._serverSubs[i]!==void 0}_sendSubscribeCommands(){let i=[];for(let c in this._subs){if(!this._subs.hasOwnProperty(c))continue;let x=this._subs[c];if(x._inflight===!0)continue;if(x.state===Ci.Subscribing){let v=x._subscribe();if(v)i.push(v)}}return i}_connectResponse(i){if(this._transportIsOpen=!0,this._transportWasOpen=!0,this._reconnectAttempts=0,this._refreshRequired=!1,this._isConnected())return;if(this._client=i.client,this._setState(Qi.Connected),this._refreshTimeout)clearTimeout(this._refreshTimeout);if(i.expires)this._refreshTimeout=setTimeout(()=>this._refresh(),U6(i.ttl));this._session=i.session,this._node=i.node,this.startBatching(),this._sendSubscribeCommands(),this.stopBatching();let c={client:i.client,transport:this._transport.subName()};if(i.data)c.data=i.data;if(this.emit("connected",c),this._resolvePromises(),this._processServerSubs(i.subs||{}),i.ping&&i.ping>0)this._serverPing=i.ping*1000,this._sendPong=i.pong===!0,this._waitServerPing();else this._serverPing=0}_processServerSubs(i){for(let c in i){if(!i.hasOwnProperty(c))continue;let x=i[c];this._serverSubs[c]={offset:x.offset,epoch:x.epoch,recoverable:x.recoverable||!1};let v=this._getSubscribeContext(c,x);this.emit("subscribed",v)}for(let c in i){if(!i.hasOwnProperty(c))continue;let x=i[c];if(x.recovered){let v=x.publications;if(v&&v.length>0){for(let z in v)if(v.hasOwnProperty(z))this._handlePublication(c,v[z])}}}for(let c in this._serverSubs){if(!this._serverSubs.hasOwnProperty(c))continue;if(!i[c])this.emit("unsubscribed",{channel:c}),delete this._serverSubs[c]}}_clearRefreshTimeout(){if(this._refreshTimeout!==null)clearTimeout(this._refreshTimeout),this._refreshTimeout=null}_clearReconnectTimeout(){if(this._reconnectTimeout!==null)clearTimeout(this._reconnectTimeout),this._reconnectTimeout=null}_clearServerPingTimeout(){if(this._serverPingTimeout!==null)clearTimeout(this._serverPingTimeout),this._serverPingTimeout=null}_waitServerPing(){if(this._config.maxServerPingDelay===0)return;if(!this._isConnected())return;this._clearServerPingTimeout(),this._serverPingTimeout=setTimeout(()=>{if(!this._isConnected())return;this._disconnect(Ux.noPing,"no ping",!0)},this._serverPing+this._config.maxServerPingDelay)}_getSubscribeContext(i,c){let x={channel:i,positioned:!1,recoverable:!1,wasRecovering:!1,recovered:!1,hasRecoveredPublications:!1};if(c.recovered)x.recovered=!0;if(c.positioned)x.positioned=!0;if(c.recoverable)x.recoverable=!0;if(c.was_recovering)x.wasRecovering=!0;let v="";if("epoch"in c)v=c.epoch;let z=0;if("offset"in c)z=c.offset;if(x.positioned||x.recoverable)x.streamPosition={offset:z,epoch:v};if(Array.isArray(c.publications)&&c.publications.length>0)x.hasRecoveredPublications=!0;if(c.data)x.data=c.data;return x}_handleReply(i,c){let x=i.id;if(!(x in this._callbacks)){c();return}let v=this._callbacks[x];if(clearTimeout(this._callbacks[x].timeout),delete this._callbacks[x],!fq(i)){let z=v.callback;if(!z)return;z({reply:i,next:c})}else{let z=v.errback;if(!z){c();return}let Z={code:i.error.code,message:i.error.message||"",temporary:i.error.temporary||!1};z({error:Z,next:c})}}_handleJoin(i,c,x){let v=this._getSub(i,x);if(!v&&i){if(this._isServerSub(i)){let z={channel:i,info:this._getJoinLeaveContext(c.info)};this.emit("join",z)}return}v._handleJoin(c)}_handleLeave(i,c,x){let v=this._getSub(i,x);if(!v&&i){if(this._isServerSub(i)){let z={channel:i,info:this._getJoinLeaveContext(c.info)};this.emit("leave",z)}return}v._handleLeave(c)}_handleUnsubscribe(i,c){let x=this._getSub(i,0);if(!x&&i){if(this._isServerSub(i))delete this._serverSubs[i],this.emit("unsubscribed",{channel:i});return}if(c.code<2500)x._setUnsubscribed(c.code,c.reason,!1);else x._setSubscribing(c.code,c.reason)}_handleSubscribe(i,c){this._serverSubs[i]={offset:c.offset,epoch:c.epoch,recoverable:c.recoverable||!1},this.emit("subscribed",this._getSubscribeContext(i,c))}_handleDisconnect(i){let c=i.code,x=!0;if(c>=3500&&c<4000||c>=4500&&c<5000)x=!1;this._disconnect(c,i.reason,x)}_getPublicationContext(i,c){let x={channel:i,data:c.data};if(c.offset)x.offset=c.offset;if(c.info)x.info=this._getJoinLeaveContext(c.info);if(c.tags)x.tags=c.tags;return x}_getJoinLeaveContext(i){let c={client:i.client,user:i.user},x=i.conn_info;if(x)c.connInfo=x;let v=i.chan_info;if(v)c.chanInfo=v;return c}_handlePublication(i,c,x){let v=this._getSub(i,x);if(!v&&i){if(this._isServerSub(i)){let z=this._getPublicationContext(i,c);if(this.emit("publication",z),c.offset!==void 0)this._serverSubs[i].offset=c.offset}return}v._handlePublication(c)}_handleMessage(i){this.emit("message",{data:i.data})}_handleServerPing(i){if(this._sendPong){let c={};this._transportSendCommands([c])}i()}_handlePush(i,c){let{channel:x,id:v}=i;if(i.pub)this._handlePublication(x,i.pub,v);else if(i.message)this._handleMessage(i.message);else if(i.join)this._handleJoin(x,i.join,v);else if(i.leave)this._handleLeave(x,i.leave,v);else if(i.unsubscribe)this._handleUnsubscribe(x,i.unsubscribe);else if(i.subscribe)this._handleSubscribe(x,i.subscribe);else if(i.disconnect)this._handleDisconnect(i.disconnect);c()}_flush(){let i=this._commands.slice(0);this._commands=[],this._transportSendCommands(i)}_createErrorObject(i,c,x){let v={code:i,message:c};if(x)v.temporary=!0;return v}_registerCall(i,c,x){this._callbacks[i]={callback:c,errback:x,timeout:null},this._callbacks[i].timeout=setTimeout(()=>{if(delete this._callbacks[i],QX(x))x({error:this._createErrorObject(t.timeout,"timeout")})},this._config.timeout)}_addCommand(i){if(this._batching)this._commands.push(i);else this._transportSendCommands([i])}_nextPromiseId(){return++this._promiseId}_nextTransportId(){return++this._transportId}_resolvePromises(){for(let i in this._promises){if(!this._promises.hasOwnProperty(i))continue;if(this._promises[i].timeout)clearTimeout(this._promises[i].timeout);this._promises[i].resolve(),delete this._promises[i]}}_rejectPromises(i){for(let c in this._promises){if(!this._promises.hasOwnProperty(c))continue;if(this._promises[c].timeout)clearTimeout(this._promises[c].timeout);this._promises[c].reject(i),delete this._promises[c]}}}hx.SubscriptionState=Ci;hx.State=Qi;hx.UnauthorizedError=Dc;var B6=(i,c)=>{async function x(){let v=await fetch(i+"api/centrifuge/gen_token");if(!v.ok){if(v.status===403)throw new hx.UnauthorizedError("Backend is not answering");throw Error(`Unexpected status code ${v.status}`)}return(await v.json()).token}return c?new hx(c||"",{getToken:x}):null},Sq=BX.createContext(null),Vx=Sq;var F6=require("react");var j0=require("react");function $6(i,c){let[x,v]=j0.useState(null),[z,Z]=j0.useState(!1);return j0.useEffect(()=>{if(!z)Z(!0),fetch(i+`api/support/${c}`,{method:"GET"}).then((J)=>J.json()).then((J)=>{v(J)})},[]),x}var Cq=({children:i})=>{let c=F6.useContext(Hx),x=zx(),v=$6(x,"socketIO"),z=(Z)=>{if(typeof window<"u")window.sid=Z.sid,console.log(`SocketIO initialized: ${window.sid}`)};return F6.useEffect(()=>{if(!c)return;let Z=()=>{console.log("SocketIO connected")},J=(Y)=>{console.log(`SocketIO disconnected: ${Y}`),c.connect()};if(v)c.on("pieinit",z),c.on("connect",Z),c.on("disconnect",J),c.connect();return()=>{if(v)c.off("pieinit",z),c.off("connect",Z),c.off("disconnect",J),c.disconnect()}},[c,v]),i},N6=Cq;var M6=require("react");var bq=({children:i})=>{let c=M6.useContext(Vx),x=zx(),v=$6(x,"centrifuge");return M6.useEffect(()=>{if(!c)return;let z=()=>{console.log("Centrifuge connected")},Z=(J)=>{console.log("Centrifuge disconnected:",J)};if(v)c.on("connected",z),c.on("disconnected",Z),c.connect();return()=>{if(v)c.disconnect()}},[c,v]),i},q6=bq;var wm=b($v(),1);var Fx=require("react");var pA=({card:i,data:c,children:x,useSocketioSupport:v=!1,useCentrifugeSupport:z=!1,useMittSupport:Z=!1,centrifugeChannel:J=void 0,methods:Y=void 0})=>{let G=Zx();if(G)console.log("[PieCard] Rendering card:",i),console.log("[PieCard] Card data:",c),console.log("[PieCard] Component name:",c?.name),console.log("[PieCard] Real-time support:",{socketio:v,centrifuge:z,mitt:Z,centrifugeChannel:J}),console.log("[PieCard] Methods:",Y?Object.keys(Y):"none"),console.log("[PieCard] Has children:",!!x);let X=Fx.useContext(Hx),Q=Fx.useContext(Vx),p=Fx.useContext(Xx);if(Fx.useEffect(()=>{if(!X||!v||!Y||!c.name){if(G&&v)console.log("[PieCard] Socket.IO setup skipped:",{hasSocket:!!X,useSocketioSupport:v,hasMethods:!!Y,hasDataName:!!c?.name});return}return Object.entries(Y).forEach(([W,H])=>{let K=`pie${W}_${c.name}`;if(G)console.log(`[PieCard] Socket.IO registering event: ${K}`);X.on(K,H)}),()=>{Object.entries(Y).forEach(([W,H])=>{let K=`pie${W}_${c.name}`;if(G)console.log(`[PieCard] Socket.IO unregistering event: ${K}`);X.off(K,H)})}},[X,Y,c.name]),Fx.useEffect(()=>{if(!Q||!z||!J||!Y||!c.name){if(G&&z)console.log("[PieCard] Centrifuge setup skipped:",{hasCentrifuge:!!Q,useCentrifugeSupport:z,hasCentrifugeChannel:!!J,hasMethods:!!Y,hasDataName:!!c?.name});return}let W=Object.entries(Y).map(([H,K])=>{let m=`pie${H}_${c.name}_${J}`;if(G)console.log(`[PieCard] Centrifuge subscribing to channel: ${m}`);let U=Q.newSubscription(m);return U.on("publication",(O)=>{if(G)console.log(`[PieCard] Centrifuge received data on ${m}:`,O.data);K(O.data)}),U.subscribe(),U});return()=>{W.forEach((H)=>{if(G)console.log("[PieCard] Centrifuge unsubscribing from channel");H.unsubscribe(),Q.removeSubscription(H)})}},[Q,J,Y,c.name]),Fx.useEffect(()=>{if(!p||!Z||!Y||!c.name){if(G&&Z)console.log("[PieCard] Mitt setup skipped:",{hasMitt:!!p,useMittSupport:Z,hasMethods:!!Y,hasDataName:!!c?.name});return}return Object.entries(Y).forEach(([W,H])=>{let K=`pie${W}_${c.name}`;if(G)console.log(`[PieCard] Mitt registering event: ${K}`);p.on(K,H)}),()=>{Object.entries(Y).forEach(([W,H])=>{let K=`pie${W}_${c.name}`;if(G)console.log(`[PieCard] Mitt unregistering event: ${K}`);p.off(K,H)})}},[p,Y,c.name]),G)console.log("[PieCard] Rendering complete, returning children");return x},Ki=pA;var Y2=b(lc(),1);var J2=b(lc(),1);function h1(i){if(!i)return{};let c={...i};if("animationName"in c&&typeof c.animationName==="object"){let x="radiumAnimation_"+Math.random().toString(36).substring(2,8);c.animationName=J2.default.keyframes(c.animationName,x)}return c}var r6=require("react/jsx-runtime"),KA=({data:i,content:c,setUiAjaxConfiguration:x})=>{let{name:v,sx:z}=i;return r6.jsx(Ki,{card:v,data:i,children:r6.jsx("div",{style:h1(z),id:v,children:c.map((Z,J)=>{return r6.jsx(yi,{uiConfig:Z,setUiAjaxConfiguration:x},`children-${J}`)})})})},G2=Y2.default(KA);var Fv=require("react/jsx-runtime"),WA=({data:i,content:c,setUiAjaxConfiguration:x})=>{let{name:v}=i;return Fv.jsx(Ki,{card:v,data:i,children:c.map((z,Z)=>{return Fv.jsx(yi,{uiConfig:z,setUiAjaxConfiguration:x},`children-${Z}`)})})},X2=WA;var fc=require("react");var Q2=b(lc(),1),Nv=require("react/jsx-runtime"),mA=({data:i,content:c})=>{let{useLoader:x,noReturn:v,returnType:z,useSocketioSupport:Z,useCentrifugeSupport:J,useMittSupport:Y,centrifugeChannel:G}=i,X=fc.useContext(vx),[Q,p]=fc.useState(!1),[W,H]=fc.useState(null),K=fc.useRef(c),m=fc.useContext(Xx),U=($)=>{if($===null)p(!0);else if(p(!1),!v)K.current=$;if(!v)H($)},O=($)=>{K.current=$.content,H($.content)},M=($)=>{if($===null)p(!0);else if(p(!1),!v)for(let N of $)m.emit(N.name,N.data)};if(fc.useEffect(()=>{H(c),p(!1)},[c]),!W&&x)return X;return Nv.jsx(Ki,{card:"AjaxGroupCard",data:i,methods:{changeContent:O},useSocketioSupport:Z,useCentrifugeSupport:J,useMittSupport:Y,centrifugeChannel:G,children:Nv.jsx(yi,{uiConfig:W??K.current,setUiAjaxConfiguration:z==="events"?M:U})})},p2=Q2.default(mA);function Mv(i=1000){return new Promise((c)=>{if(typeof window>"u"){c();return}let x=()=>{if(typeof window.sid<"u")c();else setTimeout(x,i)};x()})}var K2=require("react"),HA=(i,c={},x=[],v,z)=>{let Z=z?.renderingLogEnabled??!1,J=z?.apiServer??"";if(Z)console.log("Registering AJAX: ",v,c,x);if(!v||!i){if(Z)console.warn("Registration FAILED: pathname or setUiAjaxConfiguration is missing!");return()=>{}}return async(Y={})=>{if(typeof window>"u"||typeof document>"u"){if(Z)console.warn("getAjaxSubmit called on server, skipping DOM-dependent logic");return}if(x.includes("sid"))await Mv();let G=new FormData;for(let[Q,p]of Object.entries({...c,...Y}))G.append(Q,p);for(let Q of x)if(Q==="sid"){if(!window.sid)throw Error("SocketIO isn't initialized properly");G.append("sid",window.sid)}else{let p=document.getElementsByName(Q);if(!p.length){if(Z)console.warn(`No input found with name ${Q}`);continue}let W=p[0];if(W instanceof HTMLInputElement)if(W.type==="file"&&W.files)Array.from(W.files).forEach((H)=>G.append(Q,H));else G.append(Q,W.value);else if(W instanceof HTMLTextAreaElement)G.append(Q,W.value)}let X=J+"api/ajax_content"+v;return i(null),await fetch(X,{method:"POST",body:G}).then(async(Q)=>{let W=(Q.headers.get("content-type")||"").includes("application/json");if(!!Q.body?.getReader&&!W){let K=Q.body.getReader(),m=new TextDecoder,U="";while(!0){let{done:O,value:M}=await K.read();if(O)break;U+=m.decode(M,{stream:!0});let $=U.split(`
|
|
52
|
-
`);U=$.pop()??"";for(let N of $){let w=N.trim();if(!w)continue;try{let L=JSON.parse(w);i([L])}catch(L){if(Z)console.warn("Failed to parse streamed line:",w)}}}if(U.trim())try{let O=JSON.parse(U);i([O])}catch(O){if(Z)console.warn("Failed to parse final streamed line:",U)}return{}}else{let K=await Q.json();return i(K),K}}).catch((Q)=>{if(Z)console.error("AJAX request failed:",Q);return i(null),Q})}},g1=(i,c={},x=[],v)=>{let{apiServer:z,enableRenderingLog:Z}=Q1();return K2.useMemo(()=>HA(i,c,x,v,{apiServer:z,renderingLogEnabled:Z}),[i,c,x,v,z,Z])};var Nz=b(Fz(),1),J1=b(Fz(),1),ux=Nz.default.default||Nz.default;var cm=b(lc(),1);var t1=require("react/jsx-runtime"),IP=({data:i,setUiAjaxConfiguration:c})=>{let{name:x,title:v,iconUrl:z,iconPosition:Z,sx:J,pathname:Y,kwargs:G,depsNames:X}=i,Q=g1(c,G,X,Y);return t1.jsx(Ki,{card:"AjaxButtonCard",data:i,children:t1.jsxs("button",{id:x,className:"box-border flex min-h-12 w-full min-w-min cursor-pointer items-center justify-center gap-4 rounded-l border border-black bg-white text-center text-black hover:bg-neutral-300",value:x,onClick:()=>Q(),style:h1(J),type:"button",children:[z&&Z==="start"&&t1.jsx("img",{src:z,alt:""}),ux(v),z&&Z==="end"&&t1.jsx("img",{src:z,alt:""})]})})},xm=cm.default(IP);var ei=require("react");var B7=require("react"),vm=require("react/jsx-runtime");function Mz(i){let[c,x]=B7.useState(!1),v=B7.useRef(null);return vm.jsx("textarea",{ref:v,...i,onKeyUp:()=>{x(!1)},onKeyDown:(Y)=>{if(Y.key==="Enter"&&Y.shiftKey){if(x(!0),v.current&&typeof window<"u"){let G=window.getComputedStyle(v.current),X=parseFloat(G.lineHeight);v.current.style.height=v.current.scrollHeight+X+"px"}}if(Y.key==="Backspace"){if(x(!0),v.current&&typeof window<"u"){let G=window.getComputedStyle(v.current),X=parseFloat(G.lineHeight);if(v.current.scrollHeight>X)v.current.style.height=v.current.scrollHeight-X+"px"}}i.onKeyDown&&i.onKeyDown(Y)},onBlur:(Y)=>{x(!1),i.onBlur&&i.onBlur(Y)},style:{resize:c?"vertical":"none",overflowY:"auto",...i.style}})}var F7=require("react");var qz=require("react/jsx-runtime"),AP=()=>qz.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",strokeWidth:"1.5",stroke:"currentColor",className:"size-5",children:qz.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M6 12L3.269 3.126A59.768 59.768 0 0121.485 12 59.77 59.77 0 013.27 20.876L5.999 12zm0 0h7.5"})}),zm=AP;var $7=require("react/jsx-runtime"),uP=({type:i="button",onClick:c,icons:x})=>{let v=F7.useRef(null),z=F7.useCallback(()=>{let J=v.current;if(J)J.style.transform="scale(0.8)",setTimeout(()=>{J.style.transform="scale(1)"},600)},[]);return $7.jsx("button",{ref:v,type:i,onClick:(J)=>{if(c)c(J);z()},className:"mr-1.5 rounded-md p-1 text-gray-500 ring-0 hover:bg-gray-100 disabled:opacity-40 disabled:hover:bg-transparent",style:{transition:"transform 300ms ease"},children:x.sendIcon?$7.jsx("img",{src:x.sendIcon,alt:""}):$7.jsx(zm,{})})},Zm=uP;var Oz=require("react/jsx-runtime"),RP=()=>Oz.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",strokeWidth:"1.5",stroke:"currentColor",className:"size-5",children:Oz.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M18.375 12.739l-7.693 7.693a4.5 4.5 0 01-6.364-6.364l10.94-10.94A3 3 0 1119.5 7.372L8.552 18.32m.009-.01l-.01.01m5.699-9.941l-7.81 7.81a1.5 1.5 0 002.112 2.13"})}),Jm=RP;var xx=require("react/jsx-runtime"),PP=({name:i,accept:c,fileInputRef:x,onSelectFile:v,icons:z})=>{return xx.jsxs(xx.Fragment,{children:[xx.jsx("button",{className:"rounded-md p-1 text-gray-500 ring-0 hover:bg-gray-100 disabled:opacity-40 disabled:hover:bg-transparent",type:"button",onClick:()=>{if(x.current)x.current.click()},children:z.attachFileIcon?xx.jsx("img",{src:z.attachFileIcon,alt:""}):xx.jsx(Jm,{})}),xx.jsx("input",{id:i+"__pie__file",name:i+"__pie__file",className:"hidden",type:"file",accept:c,ref:x,onChange:(Z)=>{if(Z.target.files)v(Z.target.files[0])}})]})},Ym=PP;var Lz=require("react/jsx-runtime"),DP=()=>Lz.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",strokeWidth:"1.5",stroke:"currentColor",className:"size-5 text-gray-500",children:Lz.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M19.5 14.25v-2.625a3.375 3.375 0 00-3.375-3.375h-1.5A1.125 1.125 0 0113.5 7.125v-1.5a3.375 3.375 0 00-3.375-3.375H8.25m2.25 0H5.625c-.621 0-1.125.504-1.125 1.125v17.25c0 .621.504 1.125 1.125 1.125h12.75c.621 0 1.125-.504 1.125-1.125V11.25a9 9 0 00-9-9z"})}),Gm=DP;var wz=require("react/jsx-runtime"),TP=()=>wz.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",strokeWidth:"1.5",stroke:"currentColor",className:"size-5",children:wz.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M6 18L18 6M6 6l12 12"})}),N7=TP;var Rx=require("react/jsx-runtime"),fP=({name:i,selectedFile:c,onDropFile:x})=>{return Rx.jsxs("div",{className:"flex w-full cursor-default flex-row items-center gap-2",children:[Rx.jsx(Gm,{}),Rx.jsx("span",{className:"flex-1",children:c.name}),Rx.jsx("input",{type:"hidden",name:i,value:""}),Rx.jsx("button",{className:"rounded-md p-1 text-gray-500 ring-0 hover:bg-gray-100 disabled:opacity-40 disabled:hover:bg-transparent",type:"button",onClick:x,children:Rx.jsx(N7,{})})]})},Xm=fP;var Q5=require("react/jsx-runtime"),nP=()=>Q5.jsxs("svg",{xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",strokeWidth:"1.5",stroke:"currentColor",className:"size-5",children:[Q5.jsx("path",{d:"M8 5C8 2.79086 9.79086 1 12 1C14.2091 1 16 2.79086 16 5V12C16 14.2091 14.2091 16 12 16C9.79086 16 8 14.2091 8 12V5Z"}),Q5.jsx("path",{d:"M6.25 11.8438V12C6.25 13.525 6.8558 14.9875 7.93414 16.0659C9.01247 17.1442 10.475 17.75 12 17.75C13.525 17.75 14.9875 17.1442 16.0659 16.0659C17.1442 14.9875 17.75 13.525 17.75 12V11.8438C17.75 11.2915 18.1977 10.8438 18.75 10.8438H19.25C19.8023 10.8438 20.25 11.2915 20.25 11.8437V12C20.25 14.188 19.3808 16.2865 17.8336 17.8336C16.5842 19.0831 14.9753 19.8903 13.25 20.1548V22C13.25 22.5523 12.8023 23 12.25 23H11.75C11.1977 23 10.75 22.5523 10.75 22V20.1548C9.02471 19.8903 7.41579 19.0831 6.16637 17.8336C4.61919 16.2865 3.75 14.188 3.75 12V11.8438C3.75 11.2915 4.19772 10.8438 4.75 10.8438H5.25C5.80228 10.8438 6.25 11.2915 6.25 11.8438Z"})]}),Qm=nP;var e1=require("react/jsx-runtime"),aP=({isListening:i,toggleListening:c,icons:x})=>{return e1.jsx("button",{className:"rounded-md p-1 text-gray-500 ring-0 hover:bg-gray-100 disabled:opacity-40 disabled:hover:bg-transparent",type:"button",onClick:c,children:i?x.cancelIcon?e1.jsx("img",{src:x.cancelIcon,alt:""}):e1.jsx(N7,{}):x.voiceRecordingIcon?e1.jsx("img",{src:x.voiceRecordingIcon,alt:""}):e1.jsx(Qm,{})})},pm=aP;var p5=require("react/jsx-runtime"),jP=({option:i,onClickOption:c})=>{return p5.jsxs("div",{className:"flex w-fit cursor-pointer flex-row place-content-center items-center gap-1 rounded-md border border-black bg-white px-2 py-1 text-black",onClick:()=>{c(i.title)},style:i.sx,children:[i.iconPosition==="start"&&p5.jsx("img",{src:i.iconUrl,alt:""}),i.title,i.iconPosition==="end"&&p5.jsx("img",{src:i.iconUrl,alt:""})]})},M7=jP;var Iz=require("react/jsx-runtime"),EP=({options:i,handleOptionClick:c})=>{return Iz.jsx("div",{className:"flex w-full flex-row flex-wrap justify-start gap-[5px]",children:i.map((x,v)=>{return Iz.jsx(M7,{option:x,onClickOption:c},v)})})},Az=EP;var Xc=require("react/jsx-runtime"),SP=ei.forwardRef(({name:i,defaultValue:c,defaultOptions:x,isArea:v,placeholder:z,fileAccept:Z,optionsPosition:J,icons:Y,handleOptionClick:G,handleSendMessage:X,sx:Q},p)=>{let W=ei.useRef(null),[H,K]=ei.useState(null),[m,U]=ei.useState(c),[O,M]=ei.useState(x),[$,N]=ei.useState(!1);ei.useImperativeHandle(p,()=>({clear:()=>{if(U(""),K(null),W.current)W.current.value=""},setValue:(L)=>U(L),setOptions:(L)=>M(L)})),ei.useEffect(()=>{U(c)},[c]),ei.useEffect(()=>{},[]);let w=()=>{};return Xc.jsxs("div",{className:"flex flex-col items-center gap-[0.1rem]",id:i+"_chat_input",style:Q,children:[O&&J==="top"&&Xc.jsx(Az,{options:O,handleOptionClick:G}),Xc.jsx("div",{className:"stretch relative flex size-full flex-1 flex-row items-stretch gap-3 last:mb-2 md:mx-4 md:flex-col md:last:mb-6 lg:mx-auto",children:Xc.jsxs("div",{className:"flex w-full grow flex-row items-center rounded-md bg-transparent",children:[H?Xc.jsx(Xm,{name:i,selectedFile:H,onDropFile:()=>{if(K(null),W.current)W.current.value=""}}):!v?Xc.jsx("input",{name:i,value:m,onChange:(L)=>U(L.target.value),onKeyDown:(L)=>{if(L.key==="Enter")L.preventDefault(),X()},tabIndex:0,placeholder:z,className:"m-0 w-full resize-none border-0 bg-transparent outline-none",style:{maxHeight:200,height:"100%",overflowY:"hidden"}}):Xc.jsx(Mz,{name:i,value:m,onChange:(L)=>U(L.target.value),onKeyDown:(L)=>{if(L.key==="Enter"&&!L.shiftKey)L.preventDefault(),X()},tabIndex:0,rows:2,placeholder:z,className:"m-0 w-full resize-none border-0 bg-transparent p-0 pl-2 pr-7 outline-none md:pl-0",style:{maxHeight:200,height:"100%",minHeight:24}}),Xc.jsx(pm,{isListening:$,toggleListening:w,icons:Y}),Xc.jsx(Ym,{name:i,fileInputRef:W,accept:Z,onSelectFile:K,icons:Y}),Xc.jsx(Zm,{onClick:X,icons:Y})]})}),O&&J==="bottom"&&Xc.jsx(Az,{options:O,handleOptionClick:G})]})}),Km=SP;var O7=require("react");var q7=require("react"),mm=require("react/jsx-runtime");function CP({children:i}){let[c,x]=q7.useState(i);return q7.useEffect(()=>{x(i)},[i]),mm.jsx("div",{className:"max-w-full first:mt-0",children:c})}var Wm=CP;var uz=require("react/jsx-runtime"),bP=()=>uz.jsx("svg",{width:"30",height:"30",viewBox:"0 0 16 16",xmlns:"http://www.w3.org/2000/svg",children:uz.jsx("path",{d:"m 8 1 c -1.65625 0 -3 1.34375 -3 3 s 1.34375 3 3 3 s 3 -1.34375 3 -3 s -1.34375 -3 -3 -3 z m -1.5 7 c -2.492188 0 -4.5 2.007812 -4.5 4.5 v 0.5 c 0 1.109375 0.890625 2 2 2 h 8 c 1.109375 0 2 -0.890625 2 -2 v -0.5 c 0 -2.492188 -2.007812 -4.5 -4.5 -4.5 z m 0 0",fill:"#2e3436"})}),Hm=bP;var K5=require("react/jsx-runtime");function _P({username:i,avatar:c}){return K5.jsx("div",{className:"w-[30px]",children:K5.jsx("div",{className:"relative flex size-[30px] items-center justify-center rounded-sm p-1 text-white",children:c?K5.jsx("img",{src:c,className:"absolute inset-0 rounded",alt:i}):K5.jsx(Hm,{})})})}var Rz=_P;var ic=require("react/jsx-runtime"),hP=({message:i,handleOptionClick:c,setUiAjaxConfiguration:x})=>{let[v,z]=O7.useState(!1);return O7.useEffect(()=>{let Z=setTimeout(()=>{if(v)z(!1)},1000);return()=>clearTimeout(Z)},[v]),ic.jsx("div",{className:"group w-full border-b border-black/10",id:i.id,children:ic.jsxs("div",{className:`flex gap-4 p-4 text-base md:max-w-2xl md:gap-6 md:py-6 lg:max-w-3xl xl:max-w-5xl ${i.align==="center"?"m-auto":""} ${i.align==="right"?"ml-auto justify-end":""} ${i.align==="left"?"mr-auto":""} `,children:[(i.align==="left"||i.align==="center")&&ic.jsx("div",{className:"relative flex shrink-0 flex-col items-end",children:ic.jsx(Rz,{username:i.username,avatar:i.avatar})}),ic.jsxs("div",{className:"relative flex w-[calc(100%-50px)] flex-col gap-1 md:gap-3 lg:w-[calc(100%-115px)]",children:[ic.jsx("div",{className:`markdown light prose w-full break-words dark:prose-invert first:mt-0 ${i.align==="right"?"flex justify-end self-end":""}`,children:typeof i.content==="string"?i.parseMode.toLowerCase()==="markdown"?ic.jsx(Wm,{children:i.content},Date.now()+Math.random()):i.parseMode.toLowerCase()==="html"?ux(i.content):i.content:ic.jsx(yi,{uiConfig:i.content,setUiAjaxConfiguration:x})}),ic.jsx("div",{className:"flex flex-row flex-wrap justify-start gap-1",children:i.options.map((Z,J)=>ic.jsx(M7,{onClickOption:c,option:Z},J))})]}),i.align==="right"&&ic.jsx("div",{className:"relative flex shrink-0 flex-col items-end",children:ic.jsx(Rz,{username:i.username,avatar:i.avatar})})]})})},Um=hP;var Cc=require("react"),Pz=require("react/jsx-runtime"),gP=Cc.forwardRef(({name:i,handleOptionClick:c,defaultMessages:x,sx:v,setUiAjaxConfiguration:z},Z)=>{let[J,Y]=Cc.useState(x),G=Cc.useRef(null),X=()=>{if(G.current)G.current.scrollTop=G.current.scrollHeight};return Cc.useEffect(()=>{X()},[J]),Cc.useImperativeHandle(Z,()=>({setMessages:(Q)=>Y(Q),addMessage:(Q)=>Y((p)=>[...p,Q]),scrollToBottom:X})),Pz.jsx("div",{id:i+"_messages",className:"flex flex-col items-center overflow-y-scroll",style:v,ref:G,children:J.map((Q)=>Pz.jsx(Um,{message:Q,handleOptionClick:c,setUiAjaxConfiguration:z},Q.id))})}),Vm=gP;var Y1=require("react"),i0=require("react/jsx-runtime"),yP=({data:i,setUiAjaxConfiguration:c})=>{let{name:x,defaultValue:v,defaultMessages:z,defaultOptions:Z,isArea:J,fileAccept:Y,placeholder:G,icons:X,optionsPosition:Q,sxMap:p={container:{},chatInput:{},messages:{}},depsNames:W,pathname:H,kwargs:K,useSocketioSupport:m,useCentrifugeSupport:U,centrifugeChannel:O}=i,M=Y1.useRef(null),$=Y1.useRef(null),[N,w]=Y1.useState(!1),L=g1(c,K,W,H);Y1.useEffect(()=>{if(N)requestAnimationFrame(()=>{L(),w(!1)})},[N]);let j=(h)=>{if(M.current)M.current.setValue(h),w(!0)},g=()=>{if(M.current)M.current.clear()},Gi=(h)=>{if(M.current)M.current.setOptions(h.options)},Ri=(h)=>{if($.current)$.current.addMessage(h.message)},y=(h)=>{if($.current)$.current.setMessages(h.messages)},Pi=()=>{w(!0)};return i0.jsx(Ki,{card:"ChatCard",data:i,methods:{clearInput:g,setOptions:Gi,addMessage:Ri,setMessages:y},useSocketioSupport:m,useCentrifugeSupport:U,centrifugeChannel:O,children:i0.jsxs("div",{className:"flex size-full flex-col",style:p.container,children:[i0.jsx(Vm,{ref:$,name:x,defaultMessages:z,sx:p.messages,handleOptionClick:j,setUiAjaxConfiguration:c}),i0.jsx(Km,{ref:M,name:x,isArea:J,defaultOptions:Z,placeholder:G,defaultValue:v,fileAccept:Y,sx:p.chatInput,handleSendMessage:Pi,handleOptionClick:j,optionsPosition:Q,icons:X})]})})},Bm=yP;var L7=require("react");var Dz=require("react/jsx-runtime"),lP=({data:i})=>{let{name:c,value:x,useSocketioSupport:v,useCentrifugeSupport:z,useMittSupport:Z,centrifugeChannel:J}=i,[Y,G]=L7.useState(x);return L7.useEffect(()=>{G(x)},[x]),Dz.jsx(Ki,{card:"HiddenCard",data:i,useSocketioSupport:v,useCentrifugeSupport:z,useMittSupport:Z,centrifugeChannel:J,methods:{update:({value:X})=>{G(X)}},children:Dz.jsx("input",{type:"hidden",id:c,name:c,value:Y})})},Tz=lP;var w7=require("react");var $m=require("react"),kP=$m.createContext(void 0),bc=kP;var I7=require("react/jsx-runtime"),dP=({data:i})=>{let{url:c}=i,x=w7.useContext(bc);return w7.useEffect(()=>{if(/^[a-zA-Z][a-zA-Z\d+\-.]*:\/\//.test(c))window.location.href=c;else x?.(c)},[c,x]),I7.jsx(I7.Fragment,{})},fz=dP;var A7=require("react");var Fm=b(lc(),1);var Qc=require("react");function sP(){let i=new AudioContext,c=i.createOscillator(),x=c.connect(i.createMediaStreamDestination());c.start();let v=x.stream.getAudioTracks()[0];return v.enabled=!1,v}function nz(i=null,c){let[x,v]=Qc.useState(!1),z=Qc.useRef(null),Z=Qc.useRef(null),J=Qc.useRef(null),Y=Qc.useCallback(async(p,W=!0)=>{if(z.current)G();let H=new RTCPeerConnection;if(H.onconnectionstatechange=()=>{if(H.connectionState==="connected")v(!0);else if(["disconnected","failed","closed"].includes(H.connectionState))v(!1)},H.ontrack=(N)=>{if(i)i.srcObject=N.streams[0]},W){let N=await navigator.mediaDevices.getUserMedia({audio:!0});H.addTrack(N.getTracks()[0],N)}else{let N=sP();H.addTrack(N)}let K=H.createDataChannel("oai-events");Z.current=K,J.current=new Promise((N)=>{K.addEventListener("open",()=>{N()})});let m=await H.createOffer();await H.setLocalDescription(m);let $=await(await fetch(`${"https://api.openai.com/v1/realtime/calls"}?model=${"gpt-realtime"}`,{method:"POST",body:m.sdp,headers:{Authorization:`Bearer ${p}`,"Content-Type":"application/sdp"}})).text();await H.setRemoteDescription({type:"answer",sdp:$}),z.current=H,await J.current},[i]),G=Qc.useCallback(()=>{let p=Z.current;if(p)p.close();z.current?.getSenders()?.forEach((W)=>W.track?.stop()),z.current?.close(),v(!1),z.current=null,Z.current=null,J.current=null},[i]),X=Qc.useCallback((p)=>{let W=Z.current;if(!W){console.error("Data channel is not ready",p);return}let H=new Date().toLocaleTimeString();if(p.event_id=p.event_id||crypto.randomUUID(),W.send(JSON.stringify(p)),!p.timestamp)p.timestamp=H;c?.(p)},[c,i]),Q=Qc.useCallback((p)=>{if(!Z.current){console.error("Data channel is not ready");return}let H=()=>{X({type:"conversation.item.create",item:{type:"message",role:"user",content:[{type:"input_text",text:p}]}}),X({type:"response.create"})};if(J.current)J.current.then(H);else H()},[c,i]);return Qc.useEffect(()=>{let p=Z.current;if(!p)return;let W=(H)=>{let K=JSON.parse(H.data);if(!K.timestamp)K.timestamp=new Date().toLocaleTimeString();c?.(K)};return p.addEventListener("message",W),()=>{p.removeEventListener("message",W)}},[c,i]),{isSessionActive:x,startSession:Y,stopSession:G,sendTextMessage:Q}}var Nm=require("react/jsx-runtime"),oP=({data:i})=>{let{html:c,useSocketioSupport:x,useCentrifugeSupport:v,useMittSupport:z,centrifugeChannel:Z}=i,[J,Y]=A7.useState(c),{isSessionActive:G,startSession:X,sendTextMessage:Q}=nz(null,(K)=>{if(console.log(K.type,K.type==="response.output_text.delta"&&K.delta),K.type==="response.output_text.delta"&&K.delta)Y((m)=>m+K.delta)});return A7.useEffect(()=>{Y(c)},[c]),Nm.jsx(Ki,{card:"HTMLEmbedCard",data:i,methods:{update:(K)=>{Y(K.value)},generateUsingAI:async(K)=>{try{if(!G&&K.token)await X(K.token,!1);Q(K.prompt)}catch(m){console.error("Failed to generate using AI",m)}},initializeAI:async(K)=>{if(!G&&K.token)await X(K.token,!1)}},useCentrifugeSupport:v,useSocketioSupport:x,useMittSupport:z,centrifugeChannel:Z,children:ux(J)})},az=Fm.default(oP);var Mm=require("react");var G1=require("react/jsx-runtime"),rP=({data:i})=>{let{useCentrifugeSupport:c,useSocketioSupport:x,useMittSupport:v,centrifugeChannel:z}=i,Z=Mm.useContext(bc);return G1.jsx(G1.Fragment,{children:G1.jsx(Ki,{card:"IOEventsCard",data:i,useCentrifugeSupport:c,useSocketioSupport:x,useMittSupport:v,centrifugeChannel:z,methods:{log:(G)=>{console.log("Log event",G)},redirect:(G)=>{if(G.to){let X=G.to;if(/^[a-zA-Z][a-zA-Z\d+\-.]*:\/\//.test(X))window.location.href=X;else Z?.(X)}else window.location.reload()}},children:G1.jsx(G1.Fragment,{})})})},jz=rP;var qm=b(lc(),1);var Om=require("react");var c0=require("react/jsx-runtime"),tP=({data:i})=>{let{name:c,title:x,url:v,iconUrl:z,iconPosition:Z,sx:J}=i,Y=Om.useContext(bc);return c0.jsx(Ki,{card:"RedirectButtonCard",data:i,children:c0.jsxs("button",{id:c,className:"box-border flex min-h-12 w-full min-w-min cursor-pointer items-center justify-center gap-4 rounded-l border border-black bg-white text-center text-black hover:bg-neutral-300",value:c,onClick:(X)=>{if(v)if(X.stopPropagation(),/^[a-zA-Z][a-zA-Z\d+\-.]*:\/\//.test(v))window.location.href=v;else Y?.(v)},style:h1(J),type:"button",children:[z&&Z==="start"&&c0.jsx("img",{src:z,alt:""}),ux(x),z&&Z==="end"&&c0.jsx("img",{src:z,alt:""})]})})},Ez=qm.default(tP);var Sz=!1;function x0(){if(Sz)return;cc({name:"SequenceCard",component:G2,metadata:{author:"PieData",description:"Simple div with styles joining few components"}}),cc({name:"UnionCard",component:X2,metadata:{author:"PieData",description:"Renders one of many components"}}),cc({name:"AjaxGroupCard",component:p2,metadata:{author:"PieData",description:"Group card with AJAX support"}}),cc({name:"AjaxButtonCard",component:xm,metadata:{author:"PieData",description:"Button with AJAX support"}}),cc({name:"RedirectButtonCard",component:Ez,metadata:{author:"PieData",description:"Button with Redirect on click"}}),cc({name:"ChatCard",component:Bm,metadata:{author:"PieData"}}),cc({name:"HiddenCard",component:Tz,metadata:{author:"PieData"}}),cc({name:"AutoRedirectCard",component:fz,metadata:{author:"PieData"}}),cc({name:"HTMLEmbedCard",component:az,metadata:{author:"PieData"}}),cc({name:"IOEventsCard",component:jz,metadata:{author:"PieData"}}),Sz=!0}function _c(){return Sz}var fi=require("react/jsx-runtime"),eP=({location:i,fallback:c,onError:x,initializePie:v})=>{let z=zx(),Z=H5(),J=Zx();u7.useEffect(()=>{if(_c())return;x0(),v()},[]);let Y=u7.useMemo(()=>wm.createAxiosDateTransformer({baseURL:z||""}),[z]),{data:G,isLoading:X,error:Q}=v0.useQuery({queryKey:["uiConfig",i.pathname+i.search,_c(),z],queryFn:async()=>{if(!z||!_c())return;let p="/api/content"+i.pathname+i.search;if(J)console.log("[PieRoot] Fetching UI configuration from:",p);let W=await Y.get(p,{headers:{"Access-Control-Allow-Origin":"*","Access-Control-Allow-Methods":"GET,PUT,POST,DELETE,PATCH,OPTIONS","Content-type":"application/json"},withCredentials:!0});if(J)console.log("[PieRoot] Received UI configuration:",W.data);return W.data},staleTime:1/0,gcTime:1/0,refetchOnWindowFocus:!1,refetchOnMount:!1,refetchOnReconnect:!1,retry:!0,retryDelay:(p)=>Math.min(1000*2**p,30000)});if(!z)return c??null;if(J)console.log("[PieRoot] Rendering with location:",i),console.log("[PieRoot] API_SERVER:",z),console.log("[PieRoot] Fallback provided:",!!c);if(Q){if(J)console.error("[PieRoot] Error fetching UI configuration:",Q),console.error("[PieRoot] Error details:",{message:Q.message,status:Q.response?.status,data:Q.response?.data});return x?.(),c}if(X||!G){if(J)console.log("[PieRoot] Loading state:",{isLoading:X,hasUiConfiguration:!!G});return c}if(J)console.log("[PieRoot] UI configuration loaded successfully:",G),console.log("[PieRoot] Rendering UI with configuration");return fi.jsx(Xx.Provider,{value:p0,children:fi.jsx(Hx.Provider,{value:p6(z),children:fi.jsx(Vx.Provider,{value:B6(z,Z),children:fi.jsx(vx.Provider,{value:c??fi.jsx(fi.Fragment,{}),children:fi.jsx(N6,{children:fi.jsx(q6,{children:fi.jsx(Lm.default.StyleRoot,{style:{display:"contents"},children:fi.jsx(yi,{uiConfig:G})})})})})})})})},iD=(i)=>{let c=new v0.QueryClient;return fi.jsx(bc.Provider,{value:i.onNavigate,children:fi.jsx(J0.Provider,{value:i.config,children:fi.jsx(v0.QueryClientProvider,{client:c,children:fi.jsx(eP,{...i})})})})},Im=iD;var P7=require("react"),z0=require("@tanstack/react-query"),um=b(lc(),1);var Rm=b($v(),1);var R7=require("react");var Am=()=>{let[i,c]=R7.useState(null),x=sz();return R7.useEffect(()=>{if(typeof window>"u")return;let v=window.Telegram.WebApp;if(v.ready(),x==="telegram_expanded"&&(v.platform==="ios"||v.platform==="android"))v.expand();c(v)},[]),i};var ni=require("react/jsx-runtime"),cD=({location:i,fallback:c,onError:x,initializePie:v})=>{let z=zx(),Z=H5(),J=Zx();P7.useEffect(()=>{if(_c())return;x0(),v()},[]);let Y=P7.useMemo(()=>Rm.createAxiosDateTransformer({baseURL:z}),[]);if(J)console.log("[PieRoot] Rendering with location:",i),console.log("[PieRoot] API_SERVER:",z),console.log("[PieRoot] Fallback provided:",!!c);if(!z)throw Error("Set PIE_API_SERVER and PIE_CENTRIFUGE_SERVER");let G=Am(),{data:X,isLoading:Q,error:p}=z0.useQuery({queryKey:["uiConfig",i.pathname+i.search,G?.initData,_c()],queryFn:async()=>{if(!_c())return;let W=i.search?"&":"?",H=G?.initData?`${W}initData=${encodeURIComponent(G.initData)}`:"",K="/api/content"+i.pathname+i.search+H;if(J)console.log("[PieRoot] Fetching UI configuration from:",K);let m=await Y.get(K,{headers:{"Access-Control-Allow-Origin":"*","Access-Control-Allow-Methods":"GET,PUT,POST,DELETE,PATCH,OPTIONS","Content-type":"application/json"},withCredentials:!0});if(J)console.log("[PieRoot] Received UI configuration:",m.data);return m.data},staleTime:1/0,gcTime:1/0,refetchOnWindowFocus:!1,refetchOnMount:!1,refetchOnReconnect:!1,retry:!0,retryDelay:(W)=>Math.min(1000*2**W,30000)});if(p&&J)return console.error("[PieRoot] Error fetching UI configuration:",p),console.error("[PieRoot] Error details:",{message:p.message,status:p.response?.status,data:p.response?.data}),x?.(),c;if(Q||!X){if(J)console.log("[PieRoot] Loading state:",{isLoading:Q,hasUiConfiguration:!!X});return c}if(J)console.log("[PieRoot] UI configuration loaded successfully:",X),console.log("[PieRoot] Rendering UI with configuration");return ni.jsx(Xx.Provider,{value:p0,children:ni.jsx(Hx.Provider,{value:p6(z),children:ni.jsx(Vx.Provider,{value:B6(z,Z),children:ni.jsx(vx.Provider,{value:c??ni.jsx(ni.Fragment,{}),children:ni.jsx(N6,{children:ni.jsx(q6,{children:ni.jsx(um.default.StyleRoot,{children:ni.jsx(yi,{uiConfig:X})})})})})})})})},xD=(i)=>{let c=new z0.QueryClient;return ni.jsx(bc.Provider,{value:i.onNavigate,children:ni.jsx(J0.Provider,{value:i.config,children:ni.jsx(z0.QueryClientProvider,{client:c,children:ni.jsx(cD,{...i})})})})},Pm=xD;
|
|
52
|
+
`);U=$.pop()??"";for(let N of $){let w=N.trim();if(!w)continue;try{let L=JSON.parse(w);i([L])}catch(L){if(Z)console.warn("Failed to parse streamed line:",w)}}}if(U.trim())try{let O=JSON.parse(U);i([O])}catch(O){if(Z)console.warn("Failed to parse final streamed line:",U)}return{}}else{let K=await Q.json();return i(K),K}}).catch((Q)=>{if(Z)console.error("AJAX request failed:",Q);return i(null),Q})}},g1=(i,c={},x=[],v)=>{let{apiServer:z,enableRenderingLog:Z}=Q1();return K2.useMemo(()=>HA(i,c,x,v,{apiServer:z,renderingLogEnabled:Z}),[i,c,x,v,z,Z])};var Nz=b(Fz(),1),J1=b(Fz(),1),ux=Nz.default.default||Nz.default;var cm=b(lc(),1);var t1=require("react/jsx-runtime"),IP=({data:i,setUiAjaxConfiguration:c})=>{let{name:x,title:v,iconUrl:z,iconPosition:Z,sx:J,pathname:Y,kwargs:G,depsNames:X}=i,Q=g1(c,G,X,Y);return t1.jsx(Ki,{card:"AjaxButtonCard",data:i,children:t1.jsxs("button",{id:x,className:"box-border flex min-h-12 w-full min-w-min cursor-pointer items-center justify-center gap-4 rounded-l border border-black bg-white text-center text-black hover:bg-neutral-300",value:x,onClick:()=>Q(),style:h1(J),type:"button",children:[z&&Z==="start"&&t1.jsx("img",{src:z,alt:""}),ux(v),z&&Z==="end"&&t1.jsx("img",{src:z,alt:""})]})})},xm=cm.default(IP);var ei=require("react");var B7=require("react"),vm=require("react/jsx-runtime");function Mz(i){let[c,x]=B7.useState(!1),v=B7.useRef(null);return vm.jsx("textarea",{ref:v,...i,onKeyUp:()=>{x(!1)},onKeyDown:(Y)=>{if(Y.key==="Enter"&&Y.shiftKey){if(x(!0),v.current&&typeof window<"u"){let G=window.getComputedStyle(v.current),X=parseFloat(G.lineHeight);v.current.style.height=v.current.scrollHeight+X+"px"}}if(Y.key==="Backspace"){if(x(!0),v.current&&typeof window<"u"){let G=window.getComputedStyle(v.current),X=parseFloat(G.lineHeight);if(v.current.scrollHeight>X)v.current.style.height=v.current.scrollHeight-X+"px"}}i.onKeyDown&&i.onKeyDown(Y)},onBlur:(Y)=>{x(!1),i.onBlur&&i.onBlur(Y)},style:{resize:c?"vertical":"none",overflowY:"auto",...i.style}})}var F7=require("react");var qz=require("react/jsx-runtime"),AP=()=>qz.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",strokeWidth:"1.5",stroke:"currentColor",className:"size-5",children:qz.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M6 12L3.269 3.126A59.768 59.768 0 0121.485 12 59.77 59.77 0 013.27 20.876L5.999 12zm0 0h7.5"})}),zm=AP;var $7=require("react/jsx-runtime"),uP=({type:i="button",onClick:c,icons:x})=>{let v=F7.useRef(null),z=F7.useCallback(()=>{let J=v.current;if(J)J.style.transform="scale(0.8)",setTimeout(()=>{J.style.transform="scale(1)"},600)},[]);return $7.jsx("button",{ref:v,type:i,onClick:(J)=>{if(c)c(J);z()},className:"mr-1.5 rounded-md p-1 text-gray-500 ring-0 hover:bg-gray-100 disabled:opacity-40 disabled:hover:bg-transparent",style:{transition:"transform 300ms ease"},children:x.sendIcon?$7.jsx("img",{src:x.sendIcon,alt:""}):$7.jsx(zm,{})})},Zm=uP;var Oz=require("react/jsx-runtime"),RP=()=>Oz.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",strokeWidth:"1.5",stroke:"currentColor",className:"size-5",children:Oz.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M18.375 12.739l-7.693 7.693a4.5 4.5 0 01-6.364-6.364l10.94-10.94A3 3 0 1119.5 7.372L8.552 18.32m.009-.01l-.01.01m5.699-9.941l-7.81 7.81a1.5 1.5 0 002.112 2.13"})}),Jm=RP;var xx=require("react/jsx-runtime"),PP=({name:i,accept:c,fileInputRef:x,onSelectFile:v,icons:z})=>{return xx.jsxs(xx.Fragment,{children:[xx.jsx("button",{className:"rounded-md p-1 text-gray-500 ring-0 hover:bg-gray-100 disabled:opacity-40 disabled:hover:bg-transparent",type:"button",onClick:()=>{if(x.current)x.current.click()},children:z.attachFileIcon?xx.jsx("img",{src:z.attachFileIcon,alt:""}):xx.jsx(Jm,{})}),xx.jsx("input",{id:i+"__pie__file",name:i+"__pie__file",className:"hidden",type:"file",accept:c,ref:x,onChange:(Z)=>{if(Z.target.files)v(Z.target.files[0])}})]})},Ym=PP;var Lz=require("react/jsx-runtime"),DP=()=>Lz.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",strokeWidth:"1.5",stroke:"currentColor",className:"size-5 text-gray-500",children:Lz.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M19.5 14.25v-2.625a3.375 3.375 0 00-3.375-3.375h-1.5A1.125 1.125 0 0113.5 7.125v-1.5a3.375 3.375 0 00-3.375-3.375H8.25m2.25 0H5.625c-.621 0-1.125.504-1.125 1.125v17.25c0 .621.504 1.125 1.125 1.125h12.75c.621 0 1.125-.504 1.125-1.125V11.25a9 9 0 00-9-9z"})}),Gm=DP;var wz=require("react/jsx-runtime"),TP=()=>wz.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",strokeWidth:"1.5",stroke:"currentColor",className:"size-5",children:wz.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M6 18L18 6M6 6l12 12"})}),N7=TP;var Rx=require("react/jsx-runtime"),fP=({name:i,selectedFile:c,onDropFile:x})=>{return Rx.jsxs("div",{className:"flex w-full cursor-default flex-row items-center gap-2",children:[Rx.jsx(Gm,{}),Rx.jsx("span",{className:"flex-1",children:c.name}),Rx.jsx("input",{type:"hidden",name:i,value:""}),Rx.jsx("button",{className:"rounded-md p-1 text-gray-500 ring-0 hover:bg-gray-100 disabled:opacity-40 disabled:hover:bg-transparent",type:"button",onClick:x,children:Rx.jsx(N7,{})})]})},Xm=fP;var Q5=require("react/jsx-runtime"),nP=()=>Q5.jsxs("svg",{xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",strokeWidth:"1.5",stroke:"currentColor",className:"size-5",children:[Q5.jsx("path",{d:"M8 5C8 2.79086 9.79086 1 12 1C14.2091 1 16 2.79086 16 5V12C16 14.2091 14.2091 16 12 16C9.79086 16 8 14.2091 8 12V5Z"}),Q5.jsx("path",{d:"M6.25 11.8438V12C6.25 13.525 6.8558 14.9875 7.93414 16.0659C9.01247 17.1442 10.475 17.75 12 17.75C13.525 17.75 14.9875 17.1442 16.0659 16.0659C17.1442 14.9875 17.75 13.525 17.75 12V11.8438C17.75 11.2915 18.1977 10.8438 18.75 10.8438H19.25C19.8023 10.8438 20.25 11.2915 20.25 11.8437V12C20.25 14.188 19.3808 16.2865 17.8336 17.8336C16.5842 19.0831 14.9753 19.8903 13.25 20.1548V22C13.25 22.5523 12.8023 23 12.25 23H11.75C11.1977 23 10.75 22.5523 10.75 22V20.1548C9.02471 19.8903 7.41579 19.0831 6.16637 17.8336C4.61919 16.2865 3.75 14.188 3.75 12V11.8438C3.75 11.2915 4.19772 10.8438 4.75 10.8438H5.25C5.80228 10.8438 6.25 11.2915 6.25 11.8438Z"})]}),Qm=nP;var e1=require("react/jsx-runtime"),aP=({isListening:i,toggleListening:c,icons:x})=>{return e1.jsx("button",{className:"rounded-md p-1 text-gray-500 ring-0 hover:bg-gray-100 disabled:opacity-40 disabled:hover:bg-transparent",type:"button",onClick:c,children:i?x.cancelIcon?e1.jsx("img",{src:x.cancelIcon,alt:""}):e1.jsx(N7,{}):x.voiceRecordingIcon?e1.jsx("img",{src:x.voiceRecordingIcon,alt:""}):e1.jsx(Qm,{})})},pm=aP;var p5=require("react/jsx-runtime"),jP=({option:i,onClickOption:c})=>{return p5.jsxs("div",{className:"flex w-fit cursor-pointer flex-row place-content-center items-center gap-1 rounded-md border border-black bg-white px-2 py-1 text-black",onClick:()=>{c(i.title)},style:i.sx,children:[i.iconPosition==="start"&&p5.jsx("img",{src:i.iconUrl,alt:""}),i.title,i.iconPosition==="end"&&p5.jsx("img",{src:i.iconUrl,alt:""})]})},M7=jP;var Iz=require("react/jsx-runtime"),EP=({options:i,handleOptionClick:c})=>{return Iz.jsx("div",{className:"flex w-full flex-row flex-wrap justify-start gap-[5px]",children:i.map((x,v)=>{return Iz.jsx(M7,{option:x,onClickOption:c},v)})})},Az=EP;var Xc=require("react/jsx-runtime"),SP=ei.forwardRef(({name:i,defaultValue:c,defaultOptions:x,isArea:v,placeholder:z,fileAccept:Z,optionsPosition:J,icons:Y,handleOptionClick:G,handleSendMessage:X,sx:Q},p)=>{let W=ei.useRef(null),[H,K]=ei.useState(null),[m,U]=ei.useState(c),[O,M]=ei.useState(x),[$,N]=ei.useState(!1);ei.useImperativeHandle(p,()=>({clear:()=>{if(U(""),K(null),W.current)W.current.value=""},setValue:(L)=>U(L),setOptions:(L)=>M(L)})),ei.useEffect(()=>{U(c)},[c]),ei.useEffect(()=>{},[]);let w=()=>{};return Xc.jsxs("div",{className:"flex flex-col items-center gap-[0.1rem]",id:i+"_chat_input",style:Q,children:[O&&J==="top"&&Xc.jsx(Az,{options:O,handleOptionClick:G}),Xc.jsx("div",{className:"stretch relative flex size-full flex-1 flex-row items-stretch gap-3 last:mb-2 md:mx-4 md:flex-col md:last:mb-6 lg:mx-auto",children:Xc.jsxs("div",{className:"flex w-full grow flex-row items-center rounded-md bg-transparent",children:[H?Xc.jsx(Xm,{name:i,selectedFile:H,onDropFile:()=>{if(K(null),W.current)W.current.value=""}}):!v?Xc.jsx("input",{name:i,value:m,onChange:(L)=>U(L.target.value),onKeyDown:(L)=>{if(L.key==="Enter")L.preventDefault(),X()},tabIndex:0,placeholder:z,className:"m-0 w-full resize-none border-0 bg-transparent outline-none",style:{maxHeight:200,height:"100%",overflowY:"hidden"}}):Xc.jsx(Mz,{name:i,value:m,onChange:(L)=>U(L.target.value),onKeyDown:(L)=>{if(L.key==="Enter"&&!L.shiftKey)L.preventDefault(),X()},tabIndex:0,rows:2,placeholder:z,className:"m-0 w-full resize-none border-0 bg-transparent p-0 pl-2 pr-7 outline-none md:pl-0",style:{maxHeight:200,height:"100%",minHeight:24}}),Xc.jsx(pm,{isListening:$,toggleListening:w,icons:Y}),Xc.jsx(Ym,{name:i,fileInputRef:W,accept:Z,onSelectFile:K,icons:Y}),Xc.jsx(Zm,{onClick:X,icons:Y})]})}),O&&J==="bottom"&&Xc.jsx(Az,{options:O,handleOptionClick:G})]})}),Km=SP;var O7=require("react");var q7=require("react"),mm=require("react/jsx-runtime");function CP({children:i}){let[c,x]=q7.useState(i);return q7.useEffect(()=>{x(i)},[i]),mm.jsx("div",{className:"max-w-full first:mt-0",children:c})}var Wm=CP;var uz=require("react/jsx-runtime"),bP=()=>uz.jsx("svg",{width:"30",height:"30",viewBox:"0 0 16 16",xmlns:"http://www.w3.org/2000/svg",children:uz.jsx("path",{d:"m 8 1 c -1.65625 0 -3 1.34375 -3 3 s 1.34375 3 3 3 s 3 -1.34375 3 -3 s -1.34375 -3 -3 -3 z m -1.5 7 c -2.492188 0 -4.5 2.007812 -4.5 4.5 v 0.5 c 0 1.109375 0.890625 2 2 2 h 8 c 1.109375 0 2 -0.890625 2 -2 v -0.5 c 0 -2.492188 -2.007812 -4.5 -4.5 -4.5 z m 0 0",fill:"#2e3436"})}),Hm=bP;var K5=require("react/jsx-runtime");function _P({username:i,avatar:c}){return K5.jsx("div",{className:"w-[30px]",children:K5.jsx("div",{className:"relative flex size-[30px] items-center justify-center rounded-sm p-1 text-white",children:c?K5.jsx("img",{src:c,className:"absolute inset-0 rounded",alt:i}):K5.jsx(Hm,{})})})}var Rz=_P;var ic=require("react/jsx-runtime"),hP=({message:i,handleOptionClick:c,setUiAjaxConfiguration:x})=>{let[v,z]=O7.useState(!1);return O7.useEffect(()=>{let Z=setTimeout(()=>{if(v)z(!1)},1000);return()=>clearTimeout(Z)},[v]),ic.jsx("div",{className:"group w-full border-b border-black/10",id:i.id,children:ic.jsxs("div",{className:`flex gap-4 p-4 text-base md:max-w-2xl md:gap-6 md:py-6 lg:max-w-3xl xl:max-w-5xl ${i.align==="center"?"m-auto":""} ${i.align==="right"?"ml-auto justify-end":""} ${i.align==="left"?"mr-auto":""} `,children:[(i.align==="left"||i.align==="center")&&ic.jsx("div",{className:"relative flex shrink-0 flex-col items-end",children:ic.jsx(Rz,{username:i.username,avatar:i.avatar})}),ic.jsxs("div",{className:"relative flex w-[calc(100%-50px)] flex-col gap-1 md:gap-3 lg:w-[calc(100%-115px)]",children:[ic.jsx("div",{className:`markdown light prose w-full break-words dark:prose-invert first:mt-0 ${i.align==="right"?"flex justify-end self-end":""}`,children:typeof i.content==="string"?i.parseMode.toLowerCase()==="markdown"?ic.jsx(Wm,{children:i.content},Date.now()+Math.random()):i.parseMode.toLowerCase()==="html"?ux(i.content):i.content:ic.jsx(yi,{uiConfig:i.content,setUiAjaxConfiguration:x})}),ic.jsx("div",{className:"flex flex-row flex-wrap justify-start gap-1",children:i.options.map((Z,J)=>ic.jsx(M7,{onClickOption:c,option:Z},J))})]}),i.align==="right"&&ic.jsx("div",{className:"relative flex shrink-0 flex-col items-end",children:ic.jsx(Rz,{username:i.username,avatar:i.avatar})})]})})},Um=hP;var Cc=require("react"),Pz=require("react/jsx-runtime"),gP=Cc.forwardRef(({name:i,handleOptionClick:c,defaultMessages:x,sx:v,setUiAjaxConfiguration:z},Z)=>{let[J,Y]=Cc.useState(x),G=Cc.useRef(null),X=()=>{if(G.current)G.current.scrollTop=G.current.scrollHeight};return Cc.useEffect(()=>{X()},[J]),Cc.useImperativeHandle(Z,()=>({setMessages:(Q)=>Y(Q),addMessage:(Q)=>Y((p)=>[...p,Q]),scrollToBottom:X})),Pz.jsx("div",{id:i+"_messages",className:"flex flex-col items-center overflow-y-scroll",style:v,ref:G,children:J.map((Q)=>Pz.jsx(Um,{message:Q,handleOptionClick:c,setUiAjaxConfiguration:z},Q.id))})}),Vm=gP;var Y1=require("react"),i0=require("react/jsx-runtime"),yP=({data:i,setUiAjaxConfiguration:c})=>{let{name:x,defaultValue:v,defaultMessages:z,defaultOptions:Z,isArea:J,fileAccept:Y,placeholder:G,icons:X,optionsPosition:Q,sxMap:p={container:{},chatInput:{},messages:{}},depsNames:W,pathname:H,kwargs:K,useSocketioSupport:m,useCentrifugeSupport:U,centrifugeChannel:O}=i,M=Y1.useRef(null),$=Y1.useRef(null),[N,w]=Y1.useState(!1),L=g1(c,K,W,H);Y1.useEffect(()=>{if(N)requestAnimationFrame(()=>{L(),w(!1)})},[N]);let j=(h)=>{if(M.current)M.current.setValue(h),w(!0)},g=()=>{if(M.current)M.current.clear()},Gi=(h)=>{if(M.current)M.current.setOptions(h.options)},Ri=(h)=>{if($.current)$.current.addMessage(h.message)},y=(h)=>{if($.current)$.current.setMessages(h.messages)},Pi=()=>{w(!0)};return i0.jsx(Ki,{card:"ChatCard",data:i,methods:{clearInput:g,setOptions:Gi,addMessage:Ri,setMessages:y},useSocketioSupport:m,useCentrifugeSupport:U,centrifugeChannel:O,children:i0.jsxs("div",{className:"flex size-full flex-col",style:p.container,children:[i0.jsx(Vm,{ref:$,name:x,defaultMessages:z,sx:p.messages,handleOptionClick:j,setUiAjaxConfiguration:c}),i0.jsx(Km,{ref:M,name:x,isArea:J,defaultOptions:Z,placeholder:G,defaultValue:v,fileAccept:Y,sx:p.chatInput,handleSendMessage:Pi,handleOptionClick:j,optionsPosition:Q,icons:X})]})})},Bm=yP;var L7=require("react");var Dz=require("react/jsx-runtime"),lP=({data:i})=>{let{name:c,value:x,useSocketioSupport:v,useCentrifugeSupport:z,useMittSupport:Z,centrifugeChannel:J}=i,[Y,G]=L7.useState(x);return L7.useEffect(()=>{G(x)},[x]),Dz.jsx(Ki,{card:"HiddenCard",data:i,useSocketioSupport:v,useCentrifugeSupport:z,useMittSupport:Z,centrifugeChannel:J,methods:{update:({value:X})=>{G(X)}},children:Dz.jsx("input",{type:"hidden",id:c,name:c,value:Y})})},Tz=lP;var w7=require("react");var $m=require("react"),kP=$m.createContext(void 0),bc=kP;var I7=require("react/jsx-runtime"),dP=({data:i})=>{let{url:c}=i,x=w7.useContext(bc);return w7.useEffect(()=>{if(/^[a-zA-Z][a-zA-Z\d+\-.]*:\/\//.test(c))window.location.href=c;else x?.(c)},[c,x]),I7.jsx(I7.Fragment,{})},fz=dP;var A7=require("react");var Fm=b(lc(),1);var Qc=require("react");function sP(){let i=new AudioContext,c=i.createOscillator(),x=c.connect(i.createMediaStreamDestination());c.start();let v=x.stream.getAudioTracks()[0];return v.enabled=!1,v}function nz(i=null,c){let[x,v]=Qc.useState(!1),z=Qc.useRef(null),Z=Qc.useRef(null),J=Qc.useRef(null),Y=Qc.useCallback(async(p,W=!0)=>{if(z.current)G();let H=new RTCPeerConnection;if(H.onconnectionstatechange=()=>{if(H.connectionState==="connected")v(!0);else if(["disconnected","failed","closed"].includes(H.connectionState))v(!1)},H.ontrack=(N)=>{if(i)i.srcObject=N.streams[0]},W){let N=await navigator.mediaDevices.getUserMedia({audio:!0});H.addTrack(N.getTracks()[0],N)}else{let N=sP();H.addTrack(N)}let K=H.createDataChannel("oai-events");Z.current=K,J.current=new Promise((N)=>{K.addEventListener("open",()=>{N()})});let m=await H.createOffer();await H.setLocalDescription(m);let $=await(await fetch(`${"https://api.openai.com/v1/realtime/calls"}?model=${"gpt-realtime"}`,{method:"POST",body:m.sdp,headers:{Authorization:`Bearer ${p}`,"Content-Type":"application/sdp"}})).text();await H.setRemoteDescription({type:"answer",sdp:$}),z.current=H,await J.current},[i]),G=Qc.useCallback(()=>{let p=Z.current;if(p)p.close();z.current?.getSenders()?.forEach((W)=>W.track?.stop()),z.current?.close(),v(!1),z.current=null,Z.current=null,J.current=null},[i]),X=Qc.useCallback((p)=>{let W=Z.current;if(!W){console.error("Data channel is not ready",p);return}let H=new Date().toLocaleTimeString();if(p.event_id=p.event_id||crypto.randomUUID(),W.send(JSON.stringify(p)),!p.timestamp)p.timestamp=H;c?.(p)},[c,i]),Q=Qc.useCallback((p)=>{if(!Z.current){console.error("Data channel is not ready");return}let H=()=>{X({type:"conversation.item.create",item:{type:"message",role:"user",content:[{type:"input_text",text:p}]}}),X({type:"response.create"})};if(J.current)J.current.then(H);else H()},[c,i]);return Qc.useEffect(()=>{let p=Z.current;if(!p)return;let W=(H)=>{let K=JSON.parse(H.data);if(!K.timestamp)K.timestamp=new Date().toLocaleTimeString();c?.(K)};return p.addEventListener("message",W),()=>{p.removeEventListener("message",W)}},[c,i]),{isSessionActive:x,startSession:Y,stopSession:G,sendTextMessage:Q}}var Nm=require("react/jsx-runtime"),oP=({data:i})=>{let{html:c,useSocketioSupport:x,useCentrifugeSupport:v,useMittSupport:z,centrifugeChannel:Z}=i,[J,Y]=A7.useState(c),{isSessionActive:G,startSession:X,sendTextMessage:Q}=nz(null,(K)=>{if(console.log(K.type,K.type==="response.output_text.delta"&&K.delta),K.type==="response.output_text.delta"&&K.delta)Y((m)=>m+K.delta)});return A7.useEffect(()=>{Y(c)},[c]),Nm.jsx(Ki,{card:"HTMLEmbedCard",data:i,methods:{update:(K)=>{Y(K.value)},generateUsingAI:async(K)=>{try{if(!G&&K.token)await X(K.token,!1);Q(K.prompt)}catch(m){console.error("Failed to generate using AI",m)}},initializeAI:async(K)=>{if(!G&&K.token)await X(K.token,!1)}},useCentrifugeSupport:v,useSocketioSupport:x,useMittSupport:z,centrifugeChannel:Z,children:ux(J)})},az=Fm.default(oP);var Mm=require("react");var G1=require("react/jsx-runtime"),rP=({data:i})=>{let{useCentrifugeSupport:c,useSocketioSupport:x,useMittSupport:v,centrifugeChannel:z}=i,Z=Mm.useContext(bc);return G1.jsx(G1.Fragment,{children:G1.jsx(Ki,{card:"IOEventsCard",data:i,useCentrifugeSupport:c,useSocketioSupport:x,useMittSupport:v,centrifugeChannel:z,methods:{log:(G)=>{console.log("Log event",G)},redirect:(G)=>{if(G.to){let X=G.to;if(/^[a-zA-Z][a-zA-Z\d+\-.]*:\/\//.test(X))window.location.href=X;else Z?.(X)}else window.location.reload()}},children:G1.jsx(G1.Fragment,{})})})},jz=rP;var qm=b(lc(),1);var Om=require("react");var c0=require("react/jsx-runtime"),tP=({data:i})=>{let{name:c,title:x,url:v,iconUrl:z,iconPosition:Z,sx:J}=i,Y=Om.useContext(bc);return c0.jsx(Ki,{card:"RedirectButtonCard",data:i,children:c0.jsxs("button",{id:c,className:"box-border flex min-h-12 w-full min-w-min cursor-pointer items-center justify-center gap-4 rounded-l border border-black bg-white text-center text-black hover:bg-neutral-300",value:c,onClick:(X)=>{if(v)if(X.stopPropagation(),/^[a-zA-Z][a-zA-Z\d+\-.]*:\/\//.test(v))window.location.href=v;else Y?.(v)},style:h1(J),type:"button",children:[z&&Z==="start"&&c0.jsx("img",{src:z,alt:""}),ux(x),z&&Z==="end"&&c0.jsx("img",{src:z,alt:""})]})})},Ez=qm.default(tP);var Sz=!1;function x0(){if(Sz)return;cc({name:"SequenceCard",component:G2,metadata:{author:"PieData",description:"Simple div with styles joining few components"}}),cc({name:"UnionCard",component:X2,metadata:{author:"PieData",description:"Renders one of many components"}}),cc({name:"AjaxGroupCard",component:p2,metadata:{author:"PieData",description:"Group card with AJAX support"}}),cc({name:"AjaxButtonCard",component:xm,metadata:{author:"PieData",description:"Button with AJAX support"}}),cc({name:"RedirectButtonCard",component:Ez,metadata:{author:"PieData",description:"Button with Redirect on click"}}),cc({name:"ChatCard",component:Bm,metadata:{author:"PieData"}}),cc({name:"HiddenCard",component:Tz,metadata:{author:"PieData"}}),cc({name:"AutoRedirectCard",component:fz,metadata:{author:"PieData"}}),cc({name:"HTMLEmbedCard",component:az,metadata:{author:"PieData"}}),cc({name:"IOEventsCard",component:jz,metadata:{author:"PieData"}}),Sz=!0}function _c(){return Sz}var fi=require("react/jsx-runtime"),eP=({location:i,fallback:c,onError:x,initializePie:v})=>{let z=zx(),Z=H5(),J=Zx();u7.useEffect(()=>{if(_c())return;x0(),v()},[]);let Y=u7.useMemo(()=>wm.createAxiosDateTransformer({baseURL:z||""}),[z]),{data:G,isLoading:X,error:Q}=v0.useQuery({queryKey:["uiConfig",i.pathname+i.search,_c(),z],queryFn:async()=>{if(!z||!_c())return;let p="/api/content"+i.pathname+(i.search.startsWith("?")?i.search:`?${i.search}`);if(J)console.log("[PieRoot] Fetching UI configuration from:",p);let W=await Y.get(p,{headers:{"Access-Control-Allow-Origin":"*","Access-Control-Allow-Methods":"GET,PUT,POST,DELETE,PATCH,OPTIONS","Content-type":"application/json"},withCredentials:!0});if(J)console.log("[PieRoot] Received UI configuration:",W.data);return W.data},staleTime:1/0,gcTime:1/0,refetchOnWindowFocus:!1,refetchOnMount:!1,refetchOnReconnect:!1,retry:!0,retryDelay:(p)=>Math.min(1000*2**p,30000)});if(!z)return c??null;if(J)console.log("[PieRoot] Rendering with location:",i),console.log("[PieRoot] API_SERVER:",z),console.log("[PieRoot] Fallback provided:",!!c);if(Q){if(J)console.error("[PieRoot] Error fetching UI configuration:",Q),console.error("[PieRoot] Error details:",{message:Q.message,status:Q.response?.status,data:Q.response?.data});return x?.(),c}if(X||!G){if(J)console.log("[PieRoot] Loading state:",{isLoading:X,hasUiConfiguration:!!G});return c}if(J)console.log("[PieRoot] UI configuration loaded successfully:",G),console.log("[PieRoot] Rendering UI with configuration");return fi.jsx(Xx.Provider,{value:p0,children:fi.jsx(Hx.Provider,{value:p6(z),children:fi.jsx(Vx.Provider,{value:B6(z,Z),children:fi.jsx(vx.Provider,{value:c??fi.jsx(fi.Fragment,{}),children:fi.jsx(N6,{children:fi.jsx(q6,{children:fi.jsx(Lm.default.StyleRoot,{style:{display:"contents"},children:fi.jsx(yi,{uiConfig:G})})})})})})})})},iD=(i)=>{let c=new v0.QueryClient;return fi.jsx(bc.Provider,{value:i.onNavigate,children:fi.jsx(J0.Provider,{value:i.config,children:fi.jsx(v0.QueryClientProvider,{client:c,children:fi.jsx(eP,{...i})})})})},Im=iD;var P7=require("react"),z0=require("@tanstack/react-query"),um=b(lc(),1);var Rm=b($v(),1);var R7=require("react");var Am=()=>{let[i,c]=R7.useState(null),x=sz();return R7.useEffect(()=>{if(typeof window>"u")return;let v=window.Telegram.WebApp;if(v.ready(),x==="telegram_expanded"&&(v.platform==="ios"||v.platform==="android"))v.expand();c(v)},[]),i};var ni=require("react/jsx-runtime"),cD=({location:i,fallback:c,onError:x,initializePie:v})=>{let z=zx(),Z=H5(),J=Zx();P7.useEffect(()=>{if(_c())return;x0(),v()},[]);let Y=P7.useMemo(()=>Rm.createAxiosDateTransformer({baseURL:z}),[]);if(J)console.log("[PieRoot] Rendering with location:",i),console.log("[PieRoot] API_SERVER:",z),console.log("[PieRoot] Fallback provided:",!!c);if(!z)throw Error("Set PIE_API_SERVER and PIE_CENTRIFUGE_SERVER");let G=Am(),{data:X,isLoading:Q,error:p}=z0.useQuery({queryKey:["uiConfig",i.pathname+i.search,G?.initData,_c()],queryFn:async()=>{if(!_c())return;let W=i.search?"&":"",H=G?.initData?`${W}initData=${encodeURIComponent(G.initData)}`:"",K="/api/content"+i.pathname+(i.search.startsWith("?")?i.search:`?${i.search}`)+H;if(J)console.log("[PieRoot] Fetching UI configuration from:",K);let m=await Y.get(K,{headers:{"Access-Control-Allow-Origin":"*","Access-Control-Allow-Methods":"GET,PUT,POST,DELETE,PATCH,OPTIONS","Content-type":"application/json"},withCredentials:!0});if(J)console.log("[PieRoot] Received UI configuration:",m.data);return m.data},staleTime:1/0,gcTime:1/0,refetchOnWindowFocus:!1,refetchOnMount:!1,refetchOnReconnect:!1,retry:!0,retryDelay:(W)=>Math.min(1000*2**W,30000)});if(p&&J)return console.error("[PieRoot] Error fetching UI configuration:",p),console.error("[PieRoot] Error details:",{message:p.message,status:p.response?.status,data:p.response?.data}),x?.(),c;if(Q||!X){if(J)console.log("[PieRoot] Loading state:",{isLoading:Q,hasUiConfiguration:!!X});return c}if(J)console.log("[PieRoot] UI configuration loaded successfully:",X),console.log("[PieRoot] Rendering UI with configuration");return ni.jsx(Xx.Provider,{value:p0,children:ni.jsx(Hx.Provider,{value:p6(z),children:ni.jsx(Vx.Provider,{value:B6(z,Z),children:ni.jsx(vx.Provider,{value:c??ni.jsx(ni.Fragment,{}),children:ni.jsx(N6,{children:ni.jsx(q6,{children:ni.jsx(um.default.StyleRoot,{children:ni.jsx(yi,{uiConfig:X})})})})})})})})},xD=(i)=>{let c=new z0.QueryClient;return ni.jsx(bc.Provider,{value:i.onNavigate,children:ni.jsx(J0.Provider,{value:i.config,children:ni.jsx(z0.QueryClientProvider,{client:c,children:ni.jsx(cD,{...i})})})})},Pm=xD;
|