pulse-ui-client 0.0.10 → 0.0.13

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.ts CHANGED
@@ -1,14 +1,19 @@
1
1
  export { PulseProvider, usePulseClient, PulseView } from "./pulse";
2
2
  export type { PulseConfig, PulseProviderProps, PulsePrerender } from "./pulse";
3
+ export { usePulseChannel } from "./usePulseChannel";
4
+ export { PulseChannelResetError } from "./channel";
5
+ export type { ChannelBridge } from "./channel";
3
6
  export { PulseSocketIOClient } from "./client";
4
7
  export type { PulseClient, MountedView, ConnectionStatusListener, ServerErrorListener, } from "./client";
5
8
  export type { VDOM, VDOMNode, VDOMElement, VDOMUpdate, ComponentRegistry, } from "./vdom";
6
9
  export { VDOMRenderer, applyUpdates as applyReactTreeUpdates, RenderLazy, } from "./renderer";
7
- export type { ServerMessage, ServerInitMessage, ServerUpdateMessage, ServerErrorMessage, ServerErrorInfo, ServerApiCallMessage, ServerNavigateToMessage, ClientMessage, ClientCallbackMessage, ClientMountMessage, ClientNavigateMessage, ClientUnmountMessage, ClientApiResultMessage, } from "./messages";
10
+ export { PulseForm, submitForm } from "./form";
11
+ export type { PulseFormProps } from "./form";
12
+ export type { ServerMessage, ServerInitMessage, ServerUpdateMessage, ServerErrorMessage, ServerErrorInfo, ServerApiCallMessage, ServerNavigateToMessage, ServerChannelRequestMessage, ServerChannelResponseMessage, ServerChannelMessage, ClientMessage, ClientCallbackMessage, ClientMountMessage, ClientNavigateMessage, ClientUnmountMessage, ClientApiResultMessage, ClientChannelRequestMessage, ClientChannelResponseMessage, ClientChannelMessage, } from "./messages";
8
13
  export { SocketIOTransport } from "./transport";
9
14
  export type { Transport, MessageListener } from "./transport";
10
15
  export { extractServerRouteInfo } from "./helpers";
11
16
  export type { RouteInfo } from "./helpers";
12
17
  export { extractEvent } from "./serialize/events";
13
18
  export { encodeForWire, decodeFromWire, cleanForSerialization, } from "./serialize/clean";
14
- export { stringify, parse } from "./serialize/v1";
19
+ export { serialize as serialize, deserialize as deserialize, } from "./serialize/v3";
package/dist/index.js CHANGED
@@ -1,3 +1,3 @@
1
- import{useEffect as p,useState as c,useMemo as n,createContext as z1,useContext as G1}from"react";import D1,{cloneElement as k,createElement as e,lazy as R1,Suspense as A1}from"react";var o="$$fragment",r="$$";function a(W){return typeof W==="object"&&W!==null}function t(W){return typeof W==="object"&&W!==null&&W.tag.startsWith("$$")&&W.tag!=="$$fragment"}import{jsx as x,Fragment as f1}from"react/jsx-runtime";class M{client;path;components;callbackCache;constructor(W,q,Z){this.client=W;this.path=q;this.components=Z;this.callbackCache=new Map}getCallback(W){let q=this.callbackCache.get(W);if(!q)q=(...Z)=>this.client.invokeCallback(this.path,W,Z),this.callbackCache.set(W,q);return q}renderNode(W){if(W==null||typeof W==="boolean"||typeof W==="number"||typeof W==="string")return W;if(a(W)){let{tag:q,props:Z={},children:J=[]}=W,$={};for(let[z,Q]of Object.entries(Z))if(typeof Q==="string"&&Q.startsWith("$$fn:")){let X=Q.substring(5);$[z]=this.getCallback(X)}else $[z]=Q;if(W.key)$.key=W.key;let G=[];for(let z of J)G.push(this.renderNode(z));if(t(W)){let z=W.tag.slice(r.length),Q=this.components[z];return e(Q,$,...G)}return e(q===o?D1.Fragment:q,$,...G)}return null}}function y(W){let q=W.props?.children;if(q==null)return[];return Array.isArray(q)?q.slice():[q]}function N1(W,q){let Z={};for(let[J,$]of Object.entries(q||{}))if(typeof $==="string"&&$.startsWith("$$fn:")){let G=$.substring(5);Z[J]=W.getCallback(G)}else Z[J]=$;return Z}function O1(W,q){return k(W,void 0,...q)}function u(W,q,Z){let J=W;for(let $ of q){let G=$.path.split(".").filter((Q)=>Q.length>0).map(Number),z=(Q,X)=>{if(X<G.length){H(Q,G,X),Q=Q;let F=G[X],U=y(Q),P=U[F];return U[F]=z(P,X+1),O1(Q,U)}switch($.type){case"replace":return Z.renderNode($.data);case"update_props":{H(Q,G,X),Q=Q;let U={...Q.props??{}};console.log("update_props, data:",$.data);let P=$.data;if(P.remove&&P.remove.length>0){for(let D of P.remove)if(D in U)delete U[D]}if(P.set){let D=N1(Z,P.set);for(let[R,f]of Object.entries(D))U[R]=f}return console.log("Old props:",Q.props),console.log("New props:",U),k(Q,U)}case"insert":{H(Q,G,X),Q=Q;let F=y(Q);return F.splice($.idx,0,Z.renderNode($.data)),k(Q,null,...F)}case"remove":{H(Q,G,X),Q=Q;let F=y(Q);return F.splice($.idx,1),k(Q,null,...F)}case"move":{H(Q,G,X),Q=Q;let F=y(Q),U=F.splice($.data.from_index,1)[0];return F.splice($.data.to_index,0,U),k(Q,null,...F)}default:throw Error(`[Pulse renderer] Unknown update type: ${$.type}`)}};J=z(J,0)}return J}function C1(W,q){let Z=R1(W);return({children:J,...$})=>{return x(A1,{fallback:q??x(f1,{}),children:x(Z,{...$,children:J})})}}function H(W,q,Z){return!0}function I(){function W(q,Z){return(J)=>{let $={};for(let G of q)$[G]=J[G];if(Z)for(let G in Z){let z=Z[G];$[G]=z(J)}return $}}return W}var I1=(W)=>W.tagName.toLowerCase(),B1=["id","className","tagName","localName","clientHeight","clientLeft","clientTop","clientWidth","scrollHeight","scrollLeft","scrollTop","scrollWidth","slot"],K1=["autofocus","tabIndex","nonce"],w1=["accessKey","accessKeyLabel","autocapitalize","dir","draggable","hidden","inert","lang","offsetHeight","offsetLeft","offsetTop","offsetWidth","popover","spellcheck","title","translate","writingSuggestions","contentEditable","enterKeyHint","isContentEditable","inputMode"],g1=I()(B1,{tagName:I1}),H1=I()(K1),k1=I()(w1);function B(W){return{...g1(W),...H1(W),...k1(W)}}function V(W,q){let Z=I()(W,q);return(J)=>({...B(J),...Z(J)})}var Y1=["hash","host","hostname","href","origin","password","pathname","port","protocol","search","target","download","rel","hreflang","type","username","ping","referrerPolicy","text"],j1=V(Y1),L1=["alt","coords","download","hash","host","hostname","href","origin","password","pathname","port","protocol","rel","search","shape","target","username","ping","referrerPolicy"],y1=V(L1),M1=["autoplay","controls","crossOrigin","currentSrc","currentTime","defaultMuted","defaultPlaybackRate","duration","ended","loop","muted","networkState","paused","playbackRate","preload","readyState","seeking","src","volume","preservesPitch"],Q1=V(M1),b1=(W)=>Q1(W),S1=["disabled","name","type","value","formAction","formEnctype","formMethod","formNoValidate","formTarget","popoverTargetAction"],_1=V(S1),T1=["value"],h1=V(T1),m1=["height","src","type","width","align","name"],p1=V(m1),x1=["disabled","name","type","validationMessage","willValidate"],u1=V(x1),E1=["acceptCharset","action","autocomplete","encoding","enctype","length","method","name","noValidate","target","rel"],v1=V(E1),i1=["allow","allowFullscreen","height","name","referrerPolicy","src","srcdoc","width","align","frameBorder","longDesc","marginHeight","marginWidth","scrolling","sandbox"],c1=V(i1),n1=["alt","crossOrigin","decoding","height","isMap","loading","naturalHeight","naturalWidth","referrerPolicy","sizes","src","srcset","useMap","width","align","border","complete","hspace","longDesc","lowsrc","name","vspace","x","y","fetchPriority"],s1=V(n1),l1=["accept","alt","autocomplete","checked","defaultChecked","defaultValue","dirName","disabled","height","indeterminate","max","maxLength","min","minLength","multiple","name","pattern","placeholder","readOnly","required","selectionDirection","selectionEnd","selectionStart","size","src","step","type","value","valueAsNumber","width","align","capture","formAction","formEnctype","formMethod","formNoValidate","formTarget","useMap","validationMessage","willValidate","popoverTargetAction"],d1=V(l1),o1=["htmlFor"],r1=V(o1),a1=["value","type"],t1=V(a1),e1=["as","crossOrigin","disabled","fetchPriority","href","hreflang","imageSizes","imageSrcset","integrity","media","referrerPolicy","rel","type","charset","rev","target","sizes"],WW=V(e1),qW=["name"],ZW=V(qW),$W=["high","low","max","min","optimum","value"],QW=V($W),JW=["cite","dateTime"],W1=V(JW),XW=["reversed","start","type","compact"],zW=V(XW),GW=["data","height","name","type","useMap","width","validationMessage","willValidate","align","archive","border","code","codeBase","codeType","declare","hspace","standby","vspace"],FW=V(GW),VW=["disabled","label"],UW=V(VW),PW=["defaultSelected","disabled","index","label","selected","text","value"],DW=V(PW),RW=["defaultValue","name","type","value","htmlFor","validationMessage","willValidate"],AW=V(RW),NW=["max","position","value"],OW=V(NW),CW=["cite"],q1=V(CW),fW=(W)=>B(W),IW=["async","crossOrigin","defer","fetchPriority","integrity","noModule","referrerPolicy","src","text","type","charset"],BW=I()(IW,{event:(W)=>W.event,htmlFor:(W)=>W.htmlFor}),KW=(W)=>({...B(W),...BW(W)}),wW=["autocomplete","disabled","length","multiple","name","required","selectedIndex","size","type","value","validationMessage","willValidate"],gW=V(wW),HW=["name"],kW=V(HW),YW=["height","media","sizes","src","srcset","type","width"],jW=V(YW),LW=["align"],yW=V(LW),MW=["abbr","cellIndex","colSpan","headers","rowSpan","scope","align","axis","bgColor","ch","chOff","height","noWrap","vAlign","width"],Z1=V(MW),bW=["span","align","ch","chOff","vAlign","width"],$1=V(bW),SW=["align","bgColor","border","cellPadding","cellSpacing","frame","rules","summary","width"],_W=V(SW),TW=["rowIndex","sectionRowIndex","align","bgColor","ch","chOff","vAlign"],hW=V(TW),mW=["align","ch","chOff","vAlign"],E=V(mW),pW=(W)=>B(W),xW=["autocomplete","cols","defaultValue","dirName","disabled","maxLength","minLength","name","placeholder","readOnly","required","rows","selectionDirection","selectionEnd","selectionStart","value","wrap","textLength","validationMessage","willValidate"],uW=V(xW),EW=["dateTime"],vW=V(EW),iW=["default","kind","label","readyState","src","srclang"],cW=V(iW),nW=["height","poster","videoHeight","videoWidth","width","playsInline"],sW=I()(nW),lW=(W)=>({...Q1(W),...sW(W)}),dW=["clear"],oW=V(dW),rW=["href","target"],aW=V(rW),tW=["aLink","background","bgColor","link","text","vLink"],eW=V(tW),Wq=["compact"],qq=V(Wq),Zq=["open"],$q=V(Zq),Qq=["open","returnValue"],Jq=V(Qq),Xq=["align"],zq=V(Xq),Gq=(W)=>B(W),Fq=["align"],K=V(Fq),Vq=["align","color","noShade","size","width"],Uq=V(Vq),Pq=["version"],Dq=V(Pq),Rq=(W)=>B(W),Aq=["content","httpEquiv","name","scheme"],Nq=V(Aq),Oq=["align"],Cq=V(Oq),fq=(W)=>B(W),Iq=["width"],Bq=V(Iq),Kq=(W)=>B(W),wq=["media","type","disabled"],gq=V(wq),Hq=["text"],kq=V(Hq),Yq=["compact","type"],jq=V(Yq),Lq={A:j1,AREA:y1,AUDIO:b1,BASE:aW,BLOCKQUOTE:q1,Q:q1,BODY:eW,BR:oW,BUTTON:_1,CANVAS:B,CAPTION:yW,CITE:fW,COL:$1,COLGROUP:$1,DATA:h1,DETAILS:$q,DIALOG:Jq,DIV:zq,DL:qq,EMBED:p1,FIELDSET:u1,FORM:v1,H1:K,H2:K,H3:K,H4:K,H5:K,H6:K,HEAD:Gq,HR:Uq,HTML:Dq,IFRAME:c1,IMG:s1,INPUT:d1,LABEL:r1,LI:t1,LINK:WW,MAP:ZW,MENU:Rq,META:Nq,METER:QW,INS:W1,DEL:W1,OBJECT:FW,OL:zW,OPTGROUP:UW,OPTION:DW,OUTPUT:AW,P:Cq,PICTURE:fq,PRE:Bq,PROGRESS:OW,SCRIPT:KW,SELECT:gW,SLOT:kW,SOURCE:jW,SPAN:Kq,STYLE:gq,TABLE:_W,TBODY:E,THEAD:E,TFOOT:E,TD:Z1,TH:Z1,TEMPLATE:pW,TEXTAREA:uW,TIME:vW,TITLE:kq,TR:hW,TRACK:cW,UL:jq,VIDEO:lW};function b(W){let q=W.tagName.toUpperCase(),Z=Lq[q];if(Z)return Z(W);throw Error(`Unexpected HTML element tag: ${W.tagName} (update .web/custom/serialize.ts)`)}var yq=(W)=>b(W.target),Y=(W)=>W.relatedTarget?b(W.relatedTarget):null;function A(W,q){return I()(W,{target:yq,...q||{}})}var C=["target","bubbles","cancelable","defaultPrevented","eventPhase","isTrusted","timeStamp","type"],S=[...C,"detail"],_=[...S,"altKey","button","buttons","clientX","clientY","ctrlKey","metaKey","movementX","movementY","pageX","pageY","screenX","screenY","shiftKey"],Mq=[..._,"pointerId","pressure","tangentialPressure","tiltX","tiltY","twist","width","height","pointerType","isPrimary"],bq=A(C),Sq=A(S),_q=A(_,{relatedTarget:Y}),Tq=A(C,{clipboardData:(W)=>J1(W.clipboardData)}),hq=A([...C,"data"]),mq=A(_,{relatedTarget:Y,dataTransfer:(W)=>J1(W.dataTransfer)}),pq=A(Mq,{relatedTarget:Y}),xq=A(C,{relatedTarget:Y}),uq=A(C),Eq=A(C),vq=A(C),iq=A([...S,"altKey","ctrlKey","code","key","locale","location","metaKey","repeat","shiftKey"]),cq=A([...S,"altKey","ctrlKey","metaKey","shiftKey","changedTouches","targetTouches","touches"],{changedTouches:(W)=>v(W.changedTouches),targetTouches:(W)=>v(W.targetTouches),touches:(W)=>v(W.touches)}),nq=A([..._,"deltaMode","deltaX","deltaY","deltaZ"],{relatedTarget:Y}),sq=A([...C,"animationName","elapsedTime","pseudoElement"]),lq=A([...C,"oldState","newState"]),dq=A([...C,"elapsedTime","propertyName","pseudoElement"]);function v(W){return Array.from(W).map((q)=>({target:b(q.target),identifier:q.identifier,screenX:q.screenX,screenY:q.screenY,clientX:q.clientX,clientY:q.clientY,pageX:q.pageX,pageY:q.pageY}))}function J1(W){if(!W)return null;let q=[];if(W.items)for(let Z=0;Z<W.items.length;Z++){let J=W.items[Z];q.push({kind:J.kind,type:J.type})}return{drop_effect:W.dropEffect,effect_allowed:W.effectAllowed,items:q,types:Array.from(W.types||[])}}var N={};function O(W,q,Z){for(let J of q)W[J]=Z}O(N,["pointerdown","pointermove","pointerup","pointercancel","gotpointercapture","lostpointercapture","pointerenter","pointerleave","pointerover","pointerout"],pq);O(N,["click","contextmenu","dblclick","mousedown","mouseenter","mouseleave","mousemove","mouseout","mouseover","mouseup"],_q);O(N,["drag","dragend","dragenter","dragexit","dragleave","dragover","dragstart","drop"],mq);O(N,["keydown","keypress","keyup"],iq);O(N,["focus","blur"],xq);O(N,["change","input"],vq);O(N,["invalid"],Eq);O(N,["reset","submit"],uq);O(N,["copy","cut","paste"],Tq);O(N,["compositionend","compositionstart","compositionupdate"],hq);O(N,["touchcancel","touchend","touchmove","touchstart"],cq);O(N,["scroll"],Sq);O(N,["wheel"],nq);O(N,["animationstart","animationend","animationiteration"],sq);O(N,["transitionend"],dq);O(N,["toggle"],lq);function i(W){if(W&&typeof W==="object"&&"nativeEvent"in W&&typeof W.isDefaultPrevented==="function"){let q=W;if(typeof q.type!=="string")return W;let Z=N[q.type.toLowerCase()];if(Z)return Z(q);return bq(q)}return W}function T(W,q){let Z=[],J=q.map(()=>[]),$=new Map,G=(z)=>{let Q=$.get(z);if(Q!==void 0)return Q;if(z==null||typeof z==="number"||typeof z==="string"||typeof z==="boolean"){let X=Z.length;return Z.push(z),$.set(z,X),X}for(let X=0;X<q.length;X++){let F=q[X];if(F.check(z)){if($.has(z))return $.get(z);let U=Z.length;Z.push([]),$.set(z,U);let P=F.encode(z,(D)=>G(D));return Z[U]=P,J[X].push(U),U}}if(z&&typeof z==="object"){if($.has(z))return $.get(z);if(Array.isArray(z)){let U=Z.length;Z.push([]),$.set(z,U);let P=[];for(let D=0;D<z.length;D++)P.push(G(z[D]));return Z[U]=P,U}let X=Z.length;Z.push({}),$.set(z,X);let F={};for(let U of Object.keys(z)){let P=z[U],D=G(P);F[U]=D}return Z[X]=F,X}throw Error(`Unsupported value in serialize(): ${String(z)} (type ${typeof z})`)};return G(W),[J,Z]}function X1(W,q){let[Z,J]=W,$=new Map;for(let Q=0;Q<Z.length;Q++)for(let X of Z[Q]??[])$.set(X,Q);let G=new Map,z=(Q)=>{if(G.has(Q))return G.get(Q);if(Q<0||Q>=J.length)throw Error(`Invalid serialized data: missing entry at index ${Q}`);let X=J[Q];if($.has(Q)){let D=q[$.get(Q)].decode(J[Q],(R)=>z(R));return G.set(Q,D),D}if(X==null||typeof X==="number"||typeof X==="string"||typeof X==="boolean")return X??=void 0,G.set(Q,X),X;if(Array.isArray(X)){let P=[];G.set(Q,P);for(let D of X)P.push(z(D));return P}let F={};G.set(Q,F);let U=X;for(let P in U)F[P]=z(U[P]);return F};if(J.length===0)throw Error("Invalid serialized data: empty entries array");return z(0)}var oq={check(W){return W instanceof Date},encode(W,q){return{t:q("date"),ts:q(W.getTime())}},decode(W,q){if(q(W.t)!=="date")throw Error("Invalid date payload");let J=q(W.ts);return new Date(J)}},rq={check(W){return typeof File<"u"&&W instanceof File},encode(W,q){return{t:q("file"),n:q(W.name),tp:q(W.type),sz:q(W.size),lm:q(W.lastModified),b:W}},decode(W,q){let Z=W;if(q(Z.t)!=="file")throw Error("Invalid file payload");let $=q(Z.n),G=q(Z.tp),z=q(Z.sz),Q=q(Z.lm),X=Z.file;if(typeof File<"u"){if(X instanceof File)return X;if(X&&(X instanceof Uint8Array||X instanceof ArrayBuffer)){let F=X instanceof Uint8Array?X:new Uint8Array(X);return new File([F],$,{type:G,lastModified:Q})}if(typeof Blob<"u"&&X instanceof Blob)return new File([X],$,{type:G,lastModified:Q})}return{name:$,type:G,size:z,lastModified:Q,file:X}}},aq={check(W){return typeof FormData<"u"&&W instanceof FormData},encode(W,q){let Z={};for(let[J,$]of W.entries()){let G=Z[J];if(G===void 0)Z[J]=$;else if(Array.isArray(G))G.push($);else Z[J]=[G,$]}return{t:q("formdata"),f:q(Z)}},decode(W,q){if(q(W.t)!=="formdata")throw Error("Invalid formdata payload");let J=q(W.f),$=new FormData;for(let[G,z]of Object.entries(J))if(Array.isArray(z))for(let Q of z)$.append(G,Q);else $.append(G,z);return $}},tq={check(W){return W instanceof Set},encode(W,q){return{t:q("set"),items:q(Array.from(W.values()))}},decode(W,q){if(q(W.t)!=="set")throw Error("Invalid set payload");let J=q(W.items);return new Set(J)}},eq={check(W){return W instanceof Map},encode(W,q){return{t:q("map"),entries:q(Array.from(W.entries()))}},decode(W,q){if(q(W.t)!=="map")throw Error("Invalid map payload");let J=q(W.entries);return new Map(J)}};function j(){return[oq,rq,aq,tq,eq]}import{io as WZ}from"socket.io-client";class h{url;renderId;frameworkNavigate;activeViews;socket=null;messageQueue;connectionListeners=new Set;serverErrors=new Map;serverErrorListeners=new Set;constructor(W,q,Z){this.url=W;this.renderId=q;this.frameworkNavigate=Z;this.socket=null,this.activeViews=new Map,this.messageQueue=[]}isConnected(){return this.socket?.connected??!1}async connect(){if(this.socket)return;return new Promise((W,q)=>{let Z=WZ(this.url,{transports:["websocket","webtransport"],auth:{renderId:this.renderId}});this.socket=Z,Z.on("connect",()=>{console.log("[SocketIOTransport] Connected:",this.socket?.id);for(let[J,$]of this.activeViews)Z.emit("message",T({type:"mount",path:J,routeInfo:$.routeInfo},j()));for(let J of this.messageQueue){if(J.type==="mount"&&this.activeViews.has(J.path))continue;if(J.type==="navigate")continue;Z.emit("message",T(J,j()))}this.messageQueue=[],this.notifyConnectionListeners(!0),W()}),Z.on("connect_error",(J)=>{console.error("[SocketIOTransport] Connection failed:",J),this.notifyConnectionListeners(!1),q(J)}),Z.on("disconnect",()=>{console.log("[SocketIOTransport] Disconnected"),this.notifyConnectionListeners(!1)}),Z.on("message",(J)=>this.handleServerMessage(X1(J,j())))})}onConnectionChange(W){return this.connectionListeners.add(W),W(this.isConnected()),()=>{this.connectionListeners.delete(W)}}notifyConnectionListeners(W){for(let q of this.connectionListeners)q(W)}onServerError(W){this.serverErrorListeners.add(W);for(let[q,Z]of this.serverErrors)W(q,Z);return()=>{this.serverErrorListeners.delete(W)}}notifyServerError(W,q){for(let Z of this.serverErrorListeners)Z(W,q)}async sendMessage(W){if(this.isConnected())this.socket.emit("message",T(W,j()));else this.messageQueue.push(W)}mountView(W,q){if(this.activeViews.has(W))throw Error(`Path ${W} is already mounted`);this.activeViews.set(W,q),this.sendMessage({type:"mount",path:W,routeInfo:q.routeInfo})}async navigate(W,q){await this.sendMessage({type:"navigate",path:W,routeInfo:q})}unmount(W){this.sendMessage({type:"unmount",path:W}),this.activeViews.delete(W)}disconnect(){this.socket?.disconnect(),this.socket=null,this.messageQueue=[],this.connectionListeners.clear(),this.activeViews.clear(),this.serverErrors.clear(),this.serverErrorListeners.clear()}handleServerMessage(W){switch(W.type){case"vdom_init":{let q=this.activeViews.get(W.path);if(!q)return;if(q)q.onInit(W.vdom);if(this.serverErrors.has(W.path))this.serverErrors.delete(W.path),this.notifyServerError(W.path,null);break}case"vdom_update":{let q=this.activeViews.get(W.path);if(!q)return;if(q.onUpdate(W.ops),this.serverErrors.has(W.path))this.serverErrors.delete(W.path),this.notifyServerError(W.path,null);break}case"server_error":{if(!this.activeViews.has(W.path))return;this.serverErrors.set(W.path,W.error),this.notifyServerError(W.path,W.error);break}case"api_call":{this.performApiCall(W);break}case"navigate_to":{let q=!!W.replace,Z=W.path||"";if(Z.startsWith("//"))Z=`${window.location.protocol}${Z}`;if(/^[a-zA-Z][a-zA-Z0-9+.-]*:/.test(Z))if(Z.startsWith("http://")||Z.startsWith("https://"))try{let $=new URL(Z);if($.origin===window.location.origin){let G=`${$.pathname}${$.search}${$.hash}`;this.frameworkNavigate(G,{replace:q})}else if(q)window.location.replace(Z);else window.location.assign(Z)}catch{if(q)window.location.replace(Z);else window.location.assign(Z)}else if(q)window.location.replace(Z);else window.location.assign(Z);else this.frameworkNavigate(Z,{replace:q});break}default:console.error("Unexpected message:",W)}}async performApiCall(W){try{let q=await fetch(W.url,{method:W.method||"GET",headers:{...W.headers||{},...W.body!=null&&!("content-type"in(W.headers||{}))?{"content-type":"application/json"}:{}},body:W.body!=null?typeof W.body==="string"?W.body:JSON.stringify(W.body):void 0,credentials:W.credentials||"include"}),Z={};q.headers.forEach((z,Q)=>Z[Q]=z);let J=null;if((q.headers.get("content-type")||"").includes("application/json"))J=await q.json().catch(()=>null);else J=await q.text().catch(()=>null);let G={type:"api_result",id:W.id,ok:q.ok,status:q.status,headers:Z,body:J};await this.sendMessage(G)}catch(q){let Z={type:"api_result",id:W.id,ok:!1,status:0,headers:{},body:{error:String(q)}};await this.sendMessage(Z)}}async invokeCallback(W,q,Z){await this.sendMessage({type:"callback",path:W,callback:q,args:Z.map(i)})}}import{useLocation as qZ,useParams as ZZ,useNavigate as $Z}from"react-router";import{jsx as w,jsxs as m}from"react/jsx-runtime";var F1=z1(null),V1=z1(null),U1=()=>{let W=G1(F1);if(!W)throw Error("usePulseClient must be used within a PulseProvider");return W},QZ=(W)=>{let q=G1(V1);if(!q)throw Error("usePulsePrerender must be used within a PulseProvider");let Z=q.views[W];if(!Z)throw Error(`No prerender found for '${W}'`);return Z},s=typeof window<"u";function JZ({children:W,config:q,prerender:Z}){let[J,$]=c(!0),G=$Z(),{renderId:z,views:Q}=Z,X=n(()=>new h(q.serverAddress,z,G),[q.serverAddress,G,z]);return p(()=>X.onConnectionChange($),[X]),p(()=>{if(s)return X.connect(),()=>X.disconnect()},[X]),w(F1.Provider,{value:X,children:m(V1.Provider,{value:Z,children:[!J&&w("div",{style:{position:"fixed",bottom:"20px",right:"20px",backgroundColor:"red",color:"white",padding:"10px",borderRadius:"5px",zIndex:1000},children:"Failed to connect to the server."}),W]})})}function XZ({externalComponents:W,path:q}){let Z=U1(),J=QZ(q),$=n(()=>new M(Z,q,W),[Z,q,W]),[G,z]=c(()=>$.renderNode(J)),[Q,X]=c(null),F=qZ(),U=ZZ(),P=n(()=>{let{"*":D="",...R}=U,f=new URLSearchParams(F.search);return{hash:F.hash,pathname:F.pathname,query:F.search,queryParams:Object.fromEntries(f.entries()),pathParams:R,catchall:D.length>0?D.split("/"):[]}},[F.hash,F.pathname,F.search,JSON.stringify(U)]);if(p(()=>{if(s){Z.mountView(q,{routeInfo:P,onInit:(R)=>{z($.renderNode(R))},onUpdate:(R)=>{z((f)=>f==null?f:u(f,R,$))}});let D=Z.onServerError((R,f)=>{if(R===q)X(f)});return()=>{D(),Z.unmount(q)}}},[Z]),p(()=>{if(s)Z.navigate(q,P)},[Z,q,P]),Q)return w(zZ,{error:Q});return G}function zZ({error:W}){return m("div",{style:{padding:16,border:"1px solid #e00",background:"#fff5f5",color:"#900",fontFamily:'ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace',whiteSpace:"pre-wrap"},children:[m("div",{style:{fontWeight:700,marginBottom:8},children:["Server Error during ",W.phase]}),W.message&&w("div",{children:W.message}),W.stack&&m("details",{open:!0,style:{marginTop:8},children:[w("summary",{children:"Stack trace"}),w("pre",{style:{margin:0},children:W.stack})]})]})}import{io as GZ}from"socket.io-client";class P1{url;socket=null;listener=null;messageQueue=[];connectionListeners=new Set;constructor(W){this.url=W}connect(W){return this.listener=W,new Promise((q,Z)=>{this.socket=GZ(this.url,{transports:["websocket"]}),this.socket.on("connect",()=>{console.log("[SocketIOTransport] Connected:",this.socket?.id);for(let J of this.messageQueue)this.socket?.emit("message",J);this.messageQueue=[],this.notifyConnectionListeners(!0),q()}),this.socket.on("connect_error",(J)=>{console.error("[SocketIOTransport] Connection failed:",J),this.notifyConnectionListeners(!1),Z(J)}),this.socket.on("disconnect",()=>{console.log("[SocketIOTransport] Disconnected"),this.notifyConnectionListeners(!1)}),this.socket.on("message",(J)=>{this.listener?.(J)})})}disconnect(){this.socket?.disconnect(),this.socket=null,this.listener=null,this.messageQueue=[],this.connectionListeners.clear()}async sendMessage(W){if(this.isConnected())this.socket.emit("message",W);else this.messageQueue.push(W)}isConnected(){return this.socket?.connected||!1}onConnectionChange(W){return this.connectionListeners.add(W),W(this.isConnected()),()=>{this.connectionListeners.delete(W)}}notifyConnectionListeners(W){for(let q of this.connectionListeners)q(W)}}function FZ({params:W,request:q}){let{"*":Z="",...J}=W,$=new URL(q.url);return{hash:$.hash,pathname:$.pathname,query:$.search,queryParams:Object.fromEntries($.searchParams.entries()),pathParams:J,catchall:Z.length>1?Z.split("/"):[]}}function VZ(W){if(W===null||typeof W!=="object")return!1;let q=Object.getPrototypeOf(W);return q===Object.prototype||q===null}function l(W){return typeof W==="function"||typeof W==="symbol"||typeof W>"u"}async function UZ(W){let q=await W.arrayBuffer();return Array.from(new Uint8Array(q))}async function PZ(W){return await L(W,{seen:new WeakMap,nextId:1})}function DZ(W,q){if(W.seen.get(q)!==void 0)return null;let J=W.nextId++;return W.seen.set(q,J),J}async function L(W,q){if(W===null||typeof W!=="object")return W;if(W instanceof Date)return{__t:"datetime",timestamp:W.getTime()};if(W instanceof FormData){let Q=DZ(q,W);if(Q===null)return{__t:"ref",id:q.seen.get(W)};let X={};for(let[U,P]of W.entries()){let D=await L(P,q);if(D===void 0)continue;if(Object.prototype.hasOwnProperty.call(X,U)){let R=X[U];if(Array.isArray(R))R.push(D);else X[U]=[R,D]}else X[U]=D}return{__t:"formdata",fields:X,__id:Q}}if(W instanceof File){let Q=W,X=await UZ(W);return{__t:"file",name:Q.name,type:Q.type,size:Q.size,lastModified:Q.lastModified,content:X}}let Z=W,J=q.seen.get(Z);if(J!==void 0)return{__t:"ref",id:J};let $=q.nextId++;if(q.seen.set(Z,$),Array.isArray(W)){let X=(await Promise.all(W.map((U)=>L(U,q)))).filter((U)=>U!==void 0);return{__t:"array",__id:$,items:X}}let G={};if(VZ(W))for(let Q of Object.keys(W)){let X=W[Q];if(l(X))continue;let F=await L(X,q);if(F!==void 0)G[Q]=F}else for(let Q in W){let X=W[Q];if(l(X))continue;let F=await L(X,q);if(F!==void 0)G[Q]=F}return{__t:"object",__id:$,props:G}}function RZ(W){return g(W)}function g(W){if(W===null||typeof W!=="object")return W;let q=W,Z=q.__t;if(Z==="datetime"){let $=q.timestamp;return new Date($)}if(Z==="file"){let $=q.content;if(Array.isArray($))return{...q,content:new Uint8Array($)};return q}if(Z==="formdata"){let $=q.fields,G={};for(let z of Object.keys($)){let Q=$[z];if(Array.isArray(Q))G[z]=Q.map((X)=>g(X));else G[z]=g(Q)}return{__t:"formdata",fields:G}}if(Z==="array")return q.items.map((G)=>g(G));if(Z==="object"){let $=q.props,G={};for(let z of Object.keys($))G[z]=g($[z]);return G}if(Z==="ref")return q;let J={};for(let $ of Object.keys(q))J[$]=g(q[$]);return J}function AZ(W){return d(W,new WeakSet)}function d(W,q){if(W===null||typeof W!=="object")return W;if(q.has(W))return;if(q.add(W),Array.isArray(W))return W.map((J)=>d(J,q)).filter((J)=>J!==void 0);let Z={};for(let J in W){let $=W[J];if(l($))continue;let G=d($,q);if(G!==void 0)Z[J]=G}return Z}function NZ(W){return W instanceof Date}function OZ(W){return typeof File<"u"&&W instanceof File}function CZ(W){return typeof FormData<"u"&&W instanceof FormData}function fZ(W){let q=new Map,Z=1,J=($)=>{if($===null||typeof $!=="object")return $;let G=$;if(q.has(G))return{__ref:q.get(G)};if(NZ($)){let X=Z++;return q.set(G,X),{__pulse:"date",__id:X,timestamp:$.getTime()}}if(OZ($)){let X=Z++;return q.set(G,X),{__pulse:"file",__id:X,name:$.name,type:$.type,size:$.size,lastModified:$.lastModified,file:$}}if(CZ($)){let X=Z++;q.set(G,X);let F={};for(let[U,P]of $.entries()){let D=J(P);if(Object.prototype.hasOwnProperty.call(F,U)){let R=F[U];if(Array.isArray(R))R.push(D);else F[U]=[R,D]}else F[U]=D}return{__pulse:"formdata",__id:X,fields:F}}let z=Z++;if(q.set(G,z),Array.isArray($))return{__pulse:"array",__id:z,items:$.map(J)};let Q={};for(let X in $){let F=$[X];if(typeof F==="function"||typeof F==="symbol"||typeof F>"u")continue;Q[X]=J(F)}return{__pulse:"object",__id:z,__data:Q}};return J(W)}function IZ(W){let q=new Map,Z=(J)=>{if(J===null||typeof J!=="object")return J;if(Array.isArray(J))return J.map(Z);let $=J;if($.__ref!==void 0){let z=$.__ref;return q.get(z)||null}if($.__pulse==="date"){let z=$.__id,Q=new Date($.timestamp);return q.set(z,Q),Q}if($.__pulse==="file"){let{__id:z,file:Q}=$;return q.set(z,Q),Q}if($.__pulse==="formdata"){let{__id:z,fields:Q}=$,X=new FormData;q.set(z,X);for(let[F,U]of Object.entries(Q))if(Array.isArray(U))for(let P of U){let D=Z(P);X.append(F,D)}else{let P=Z(U);X.append(F,P)}return X}if($.__pulse==="array"){let z=$.__id,Q=[];q.set(z,Q);let X=$.items;for(let F=0;F<X.length;F++)Q[F]=Z(X[F]);return Q}if($.__pulse==="object"){let z=$.__id,Q={};q.set(z,Q);let X=$.__data;for(let[F,U]of Object.entries(X))Q[F]=Z(U);return Q}let G={};for(let[z,Q]of Object.entries($))G[z]=Z(Q);return G};return Z(W)}export{U1 as usePulseClient,fZ as stringify,IZ as parse,FZ as extractServerRouteInfo,i as extractEvent,PZ as encodeForWire,RZ as decodeFromWire,AZ as cleanForSerialization,u as applyReactTreeUpdates,M as VDOMRenderer,P1 as SocketIOTransport,C1 as RenderLazy,XZ as PulseView,h as PulseSocketIOClient,JZ as PulseProvider};
1
+ import{useEffect as E,useState as a,useMemo as t,createContext as AW,useContext as NW}from"react";import jW,{cloneElement as L,createElement as XW,lazy as BW,Suspense as KW}from"react";var QW="$$fragment",qW="$$";function zW(W){return typeof W==="object"&&W!==null}function JW(W){return typeof W==="object"&&W!==null&&W.tag.startsWith("$$")&&W.tag!=="$$fragment"}import{jsx as n,Fragment as YW}from"react/jsx-runtime";class h{client;path;components;callbackCache;constructor(W,Z,$){this.client=W;this.path=Z;this.components=$;this.callbackCache=new Map}getCallback(W){let Z=this.callbackCache.get(W);if(!Z)Z=(...$)=>this.client.invokeCallback(this.path,W,$),this.callbackCache.set(W,Z);return Z}renderNode(W){if(W==null||typeof W==="boolean"||typeof W==="number"||typeof W==="string")return W;if(zW(W)){let{tag:Z,props:$={},children:Q=[]}=W,q={};for(let[U,z]of Object.entries($))if(typeof z==="string"&&z.startsWith("$$fn:")){let V=z.substring(5);q[U]=this.getCallback(V)}else q[U]=z;if(W.key)q.key=W.key;let J=[];for(let U of Q)J.push(this.renderNode(U));if(JW(W)){let U=W.tag.slice(qW.length),z=this.components[U];return XW(z,q,...J)}return XW(Z===QW?jW.Fragment:Z,q,...J)}return null}}function g(W){let Z=W.props?.children;if(Z==null)return[];return Array.isArray(Z)?Z.slice():[Z]}function kW(W,Z){let $={};for(let[Q,q]of Object.entries(Z||{}))if(typeof q==="string"&&q.startsWith("$$fn:")){let J=q.substring(5);$[Q]=W.getCallback(J)}else $[Q]=q;return $}function HW(W,Z){return L(W,void 0,...Z)}function d(W,Z,$){let Q=W;for(let q of Z){let J=q.path.split(".").filter((z)=>z.length>0).map(Number),U=(z,V)=>{if(V<J.length){M(z,J,V),z=z;let X=J[V],P=g(z),C=P[X];return P[X]=U(C,V+1),HW(z,P)}switch(q.type){case"replace":return $.renderNode(q.data);case"update_props":{M(z,J,V),z=z;let P={...z.props??{}},C=q.data;if(C.remove&&C.remove.length>0){for(let D of C.remove)if(D in P)delete P[D]}if(C.set){let D=kW($,C.set);for(let[G,f]of Object.entries(D))P[G]=f}return L(z,P)}case"insert":{M(z,J,V),z=z;let X=g(z);return X.splice(q.idx,0,$.renderNode(q.data)),L(z,null,...X)}case"remove":{M(z,J,V),z=z;let X=g(z);return X.splice(q.idx,1),L(z,null,...X)}case"move":{M(z,J,V),z=z;let X=g(z),P=X.splice(q.data.from_index,1)[0];return X.splice(q.data.to_index,0,P),L(z,null,...X)}default:throw Error(`[Pulse renderer] Unknown update type: ${q.type}`)}};Q=U(Q,0)}return Q}function yW(W,Z){let $=BW(W);return({children:Q,...q})=>{return n(KW,{fallback:Z??n(YW,{}),children:n($,{...q,children:Q})})}}function M(W,Z,$){return!0}function B(){function W(Z,$){return(Q)=>{let q={};for(let J of Z)q[J]=Q[J];if($)for(let J in $){let U=$[J];q[J]=U(Q)}return q}}return W}var bW=(W)=>W.tagName.toLowerCase(),MW=["id","className","tagName","localName","clientHeight","clientLeft","clientTop","clientWidth","scrollHeight","scrollLeft","scrollTop","scrollWidth","slot"],LW=["autofocus","tabIndex","nonce"],SW=["accessKey","accessKeyLabel","autocapitalize","dir","draggable","hidden","inert","lang","offsetHeight","offsetLeft","offsetTop","offsetWidth","popover","spellcheck","title","translate","writingSuggestions","contentEditable","enterKeyHint","isContentEditable","inputMode"],TW=B()(MW,{tagName:bW}),_W=B()(LW),gW=B()(SW);function K(W){return{...TW(W),..._W(W),...gW(W)}}function F(W,Z){let $=B()(W,Z);return(Q)=>({...K(Q),...$(Q)})}var hW=["hash","host","hostname","href","origin","password","pathname","port","protocol","search","target","download","rel","hreflang","type","username","ping","referrerPolicy","text"],xW=F(hW),pW=["alt","coords","download","hash","host","hostname","href","origin","password","pathname","port","protocol","rel","search","shape","target","username","ping","referrerPolicy"],mW=F(pW),vW=["autoplay","controls","crossOrigin","currentSrc","currentTime","defaultMuted","defaultPlaybackRate","duration","ended","loop","muted","networkState","paused","playbackRate","preload","readyState","seeking","src","volume","preservesPitch"],DW=F(vW),uW=(W)=>DW(W),EW=["disabled","name","type","value","formAction","formEnctype","formMethod","formNoValidate","formTarget","popoverTargetAction"],iW=F(EW),cW=["value"],nW=F(cW),dW=["height","src","type","width","align","name"],lW=F(dW),oW=["disabled","name","type","validationMessage","willValidate"],sW=F(oW),rW=["acceptCharset","action","autocomplete","encoding","enctype","length","method","name","noValidate","target","rel"],aW=F(rW),tW=["allow","allowFullscreen","height","name","referrerPolicy","src","srcdoc","width","align","frameBorder","longDesc","marginHeight","marginWidth","scrolling","sandbox"],eW=F(tW),W1=["alt","crossOrigin","decoding","height","isMap","loading","naturalHeight","naturalWidth","referrerPolicy","sizes","src","srcset","useMap","width","align","border","complete","hspace","longDesc","lowsrc","name","vspace","x","y","fetchPriority"],Z1=F(W1),$1=["accept","alt","autocomplete","checked","defaultChecked","defaultValue","dirName","disabled","height","indeterminate","max","maxLength","min","minLength","multiple","name","pattern","placeholder","readOnly","required","selectionDirection","selectionEnd","selectionStart","size","src","step","type","value","valueAsNumber","width","align","capture","formAction","formEnctype","formMethod","formNoValidate","formTarget","useMap","validationMessage","willValidate","popoverTargetAction"],Q1=F($1),q1=["htmlFor"],z1=F(q1),J1=["value","type"],X1=F(J1),F1=["as","crossOrigin","disabled","fetchPriority","href","hreflang","imageSizes","imageSrcset","integrity","media","referrerPolicy","rel","type","charset","rev","target","sizes"],G1=F(F1),V1=["name"],U1=F(V1),D1=["high","low","max","min","optimum","value"],P1=F(D1),f1=["cite","dateTime"],FW=F(f1),C1=["reversed","start","type","compact"],A1=F(C1),N1=["data","height","name","type","useMap","width","validationMessage","willValidate","align","archive","border","code","codeBase","codeType","declare","hspace","standby","vspace"],O1=F(N1),R1=["disabled","label"],I1=F(R1),w1=["defaultSelected","disabled","index","label","selected","text","value"],j1=F(w1),B1=["defaultValue","name","type","value","htmlFor","validationMessage","willValidate"],K1=F(B1),k1=["max","position","value"],H1=F(k1),y1=["cite"],GW=F(y1),Y1=(W)=>K(W),b1=["async","crossOrigin","defer","fetchPriority","integrity","noModule","referrerPolicy","src","text","type","charset"],M1=B()(b1,{event:(W)=>W.event,htmlFor:(W)=>W.htmlFor}),L1=(W)=>({...K(W),...M1(W)}),S1=["autocomplete","disabled","length","multiple","name","required","selectedIndex","size","type","value","validationMessage","willValidate"],T1=F(S1),_1=["name"],g1=F(_1),h1=["height","media","sizes","src","srcset","type","width"],x1=F(h1),p1=["align"],m1=F(p1),v1=["abbr","cellIndex","colSpan","headers","rowSpan","scope","align","axis","bgColor","ch","chOff","height","noWrap","vAlign","width"],VW=F(v1),u1=["span","align","ch","chOff","vAlign","width"],UW=F(u1),E1=["align","bgColor","border","cellPadding","cellSpacing","frame","rules","summary","width"],i1=F(E1),c1=["rowIndex","sectionRowIndex","align","bgColor","ch","chOff","vAlign"],n1=F(c1),d1=["align","ch","chOff","vAlign"],l=F(d1),l1=(W)=>K(W),o1=["autocomplete","cols","defaultValue","dirName","disabled","maxLength","minLength","name","placeholder","readOnly","required","rows","selectionDirection","selectionEnd","selectionStart","value","wrap","textLength","validationMessage","willValidate"],s1=F(o1),r1=["dateTime"],a1=F(r1),t1=["default","kind","label","readyState","src","srclang"],e1=F(t1),W3=["height","poster","videoHeight","videoWidth","width","playsInline"],Z3=B()(W3),$3=(W)=>({...DW(W),...Z3(W)}),Q3=["clear"],q3=F(Q3),z3=["href","target"],J3=F(z3),X3=["aLink","background","bgColor","link","text","vLink"],F3=F(X3),G3=["compact"],V3=F(G3),U3=["open"],D3=F(U3),P3=["open","returnValue"],f3=F(P3),C3=["align"],A3=F(C3),N3=(W)=>K(W),O3=["align"],y=F(O3),R3=["align","color","noShade","size","width"],I3=F(R3),w3=["version"],j3=F(w3),B3=(W)=>K(W),K3=["content","httpEquiv","name","scheme"],k3=F(K3),H3=["align"],y3=F(H3),Y3=(W)=>K(W),b3=["width"],M3=F(b3),L3=(W)=>K(W),S3=["media","type","disabled"],T3=F(S3),_3=["text"],g3=F(_3),h3=["compact","type"],x3=F(h3),p3={A:xW,AREA:mW,AUDIO:uW,BASE:J3,BLOCKQUOTE:GW,Q:GW,BODY:F3,BR:q3,BUTTON:iW,CANVAS:K,CAPTION:m1,CITE:Y1,COL:UW,COLGROUP:UW,DATA:nW,DETAILS:D3,DIALOG:f3,DIV:A3,DL:V3,EMBED:lW,FIELDSET:sW,FORM:aW,H1:y,H2:y,H3:y,H4:y,H5:y,H6:y,HEAD:N3,HR:I3,HTML:j3,IFRAME:eW,IMG:Z1,INPUT:Q1,LABEL:z1,LI:X1,LINK:G1,MAP:U1,MENU:B3,META:k3,METER:P1,INS:FW,DEL:FW,OBJECT:O1,OL:A1,OPTGROUP:I1,OPTION:j1,OUTPUT:K1,P:y3,PICTURE:Y3,PRE:M3,PROGRESS:H1,SCRIPT:L1,SELECT:T1,SLOT:g1,SOURCE:x1,SPAN:L3,STYLE:T3,TABLE:i1,TBODY:l,THEAD:l,TFOOT:l,TD:VW,TH:VW,TEMPLATE:l1,TEXTAREA:s1,TIME:a1,TITLE:g3,TR:n1,TRACK:e1,UL:x3,VIDEO:$3};function x(W){let Z=W.tagName.toUpperCase(),$=p3[Z];if($)return $(W);throw Error(`Unexpected HTML element tag: ${W.tagName} (update .web/custom/serialize.ts)`)}var m3=(W)=>x(W.target),S=(W)=>W.relatedTarget?x(W.relatedTarget):null;function A(W,Z){return B()(W,{target:m3,...Z||{}})}var w=["target","bubbles","cancelable","defaultPrevented","eventPhase","isTrusted","timeStamp","type"],p=[...w,"detail"],m=[...p,"altKey","button","buttons","clientX","clientY","ctrlKey","metaKey","movementX","movementY","pageX","pageY","screenX","screenY","shiftKey"],v3=[...m,"pointerId","pressure","tangentialPressure","tiltX","tiltY","twist","width","height","pointerType","isPrimary"],u3=A(w),E3=A(p),i3=A(m,{relatedTarget:S}),c3=A(w,{clipboardData:(W)=>PW(W.clipboardData)}),n3=A([...w,"data"]),d3=A(m,{relatedTarget:S,dataTransfer:(W)=>PW(W.dataTransfer)}),l3=A(v3,{relatedTarget:S}),o3=A(w,{relatedTarget:S}),s3=A(w),r3=A(w),a3=A(w),t3=A([...p,"altKey","ctrlKey","code","key","locale","location","metaKey","repeat","shiftKey"]),e3=A([...p,"altKey","ctrlKey","metaKey","shiftKey","changedTouches","targetTouches","touches"],{changedTouches:(W)=>o(W.changedTouches),targetTouches:(W)=>o(W.targetTouches),touches:(W)=>o(W.touches)}),WZ=A([...m,"deltaMode","deltaX","deltaY","deltaZ"],{relatedTarget:S}),ZZ=A([...w,"animationName","elapsedTime","pseudoElement"]),$Z=A([...w,"oldState","newState"]),QZ=A([...w,"elapsedTime","propertyName","pseudoElement"]);function o(W){return Array.from(W).map((Z)=>({target:x(Z.target),identifier:Z.identifier,screenX:Z.screenX,screenY:Z.screenY,clientX:Z.clientX,clientY:Z.clientY,pageX:Z.pageX,pageY:Z.pageY}))}function PW(W){if(!W)return null;let Z=[];if(W.items)for(let $=0;$<W.items.length;$++){let Q=W.items[$];Z.push({kind:Q.kind,type:Q.type})}return{drop_effect:W.dropEffect,effect_allowed:W.effectAllowed,items:Z,types:Array.from(W.types||[])}}var N={};function R(W,Z,$){for(let Q of Z)W[Q]=$}R(N,["pointerdown","pointermove","pointerup","pointercancel","gotpointercapture","lostpointercapture","pointerenter","pointerleave","pointerover","pointerout"],l3);R(N,["click","contextmenu","dblclick","mousedown","mouseenter","mouseleave","mousemove","mouseout","mouseover","mouseup"],i3);R(N,["drag","dragend","dragenter","dragexit","dragleave","dragover","dragstart","drop"],d3);R(N,["keydown","keypress","keyup"],t3);R(N,["focus","blur"],o3);R(N,["change","input"],a3);R(N,["invalid"],r3);R(N,["reset","submit"],s3);R(N,["copy","cut","paste"],c3);R(N,["compositionend","compositionstart","compositionupdate"],n3);R(N,["touchcancel","touchend","touchmove","touchstart"],e3);R(N,["scroll"],E3);R(N,["wheel"],WZ);R(N,["animationstart","animationend","animationiteration"],ZZ);R(N,["transitionend"],QZ);R(N,["toggle"],$Z);function s(W){if(W&&typeof W==="object"&&"nativeEvent"in W&&typeof W.isDefaultPrevented==="function"){let Z=W;if(typeof Z.type!=="string")return W;let $=N[Z.type.toLowerCase()];if($)return $(Z);return u3(Z)}return W}function T(W){let Z=new Map,$=[],Q=[],q=[],J=[],U=0;function z(X){if(X==null||typeof X==="number"||typeof X==="string"||typeof X==="boolean")return X;let P=U++,C=Z.get(X);if(C!==void 0)return $.push(P),C;if(Z.set(X,P),X instanceof Date)return Q.push(P),X.getTime();if(Array.isArray(X)){let D=X.length,G=Array(D);for(let f=0;f<D;f++)G[f]=z(X[f]);return G}if(X instanceof Map){J.push(P);let D={};for(let[G,f]of X.entries())D[String(G)]=z(f);return D}if(X instanceof Set){q.push(P);let D=X.size,G=Array(D),f=0;for(let I of X)G[f]=z(I),f+=1;return G}if(typeof X==="object"){let D={},G=Object.keys(X);for(let f=0;f<G.length;f++){let I=G[f];D[I]=z(X[I])}return D}throw Error(`Unsupported value in serialization: ${X}`)}let V=z(W);return[[$,Q,q,J],V]}function r(W,Z){let[[$,Q,q,J],U]=W,z=new Set($),V=new Set(Q),X=new Set(q),P=new Set(J),C=[];function D(G){let f=C.length;if(z.has(f))return C.push(null),C[G];if(V.has(f)){let I=new Date(G);return C.push(I),I}if(G==null||typeof G==="number"||typeof G==="string"||typeof G==="boolean"){if(Z?.coerceNullsToUndefined)return G??void 0;return G}if(Array.isArray(G)){if(X.has(f)){let O=new Set;C.push(O);for(let j=0;j<G.length;j++)O.add(D(G[j]));return O}let I=G.length,H=Array(I);C.push(H);for(let O=0;O<I;O++)H[O]=D(G[O]);return H}if(typeof G==="object"){if(P.has(f)){let O=new Map;C.push(O);let j=Object.keys(G);for(let c=0;c<j.length;c++){let $W=j[c];O.set($W,D(G[$W]))}return O}let I={};C.push(I);let H=Object.keys(G);for(let O=0;O<H.length;O++){let j=H[O];I[j]=D(G[j])}return I}throw Error(`Unsupported value in deserialization: ${G}`)}return D(U)}import{io as FZ}from"socket.io-client";class k extends Error{constructor(W){super(W);this.name="PulseChannelResetError"}}function qZ(){if(typeof crypto<"u"&&typeof crypto.randomUUID==="function")return crypto.randomUUID().replace(/-/g,"");return Math.random().toString(16).slice(2)+Math.random().toString(16).slice(2)}function zZ(W){if(W instanceof Error)return W.message;if(typeof W==="string")return W;try{return JSON.stringify(W)}catch{return String(W)}}function JZ(W){return typeof W.responseTo==="string"}function XZ(W){return typeof W.event==="string"}class fW{client;id;handlers=new Map;pending=new Map;backlog=[];closed=!1;constructor(W,Z){this.client=W;this.id=Z}emit(W,Z){this.ensureOpen(),this.client.sendChannelMessage({type:"channel_message",channel:this.id,event:W,payload:Z})}async request(W,Z){this.ensureOpen();let $=qZ();return new Promise((Q,q)=>{this.pending.set($,{resolve:Q,reject:q}),this.client.sendChannelMessage({type:"channel_message",channel:this.id,event:W,payload:Z,requestId:$}).catch((J)=>{this.pending.delete($),q(J)})})}on(W,Z){this.ensureOpen();let $=this.handlers.get(W);if(!$)$=new Set,this.handlers.set(W,$);return $.add(Z),this.flushBacklog(W),()=>{let Q=this.handlers.get(W);if(!Q)return;if(Q.delete(Z),Q.size===0)this.handlers.delete(W)}}handleServerMessage(W){if(JZ(W))return this.resolvePending(W),this.closed;if(this.closed)return!0;if(!XZ(W))return this.closed;if(W.event==="__close__")return this.close(new k("Channel closed by server")),!0;if(W.requestId)this.dispatchRequest(W);else this.dispatchEvent(W);return this.closed}handleDisconnect(W){this.close(W)}dispose(W){this.close(W)}ensureOpen(){if(this.closed)throw new k("Channel is closed")}flushBacklog(W){if(this.backlog.length===0)return;let Z=[];for(let $ of this.backlog)if($.event===W)this.dispatchEvent($);else Z.push($);this.backlog=Z}dispatchEvent(W){let Z=this.handlers.get(W.event);if(!Z||Z.size===0){this.backlog.push(W);return}for(let $ of Z)try{let Q=$(W.payload);if(Q&&typeof Q.then==="function")Q.catch((q)=>{console.error("Pulse channel handler error",q)})}catch(Q){console.error("Pulse channel handler error",Q)}}async dispatchRequest(W){let Z=this.handlers.get(W.event),$,Q;if(Z&&Z.size>0)for(let q of Z)try{let J=q(W.payload);if($=await Promise.resolve(J),$!==void 0)break}catch(J){Q=J;break}if(Q){await this.client.sendChannelMessage({type:"channel_message",channel:this.id,event:void 0,responseTo:W.requestId,error:zZ(Q)});return}await this.client.sendChannelMessage({type:"channel_message",channel:this.id,event:void 0,responseTo:W.requestId,payload:$})}resolvePending(W){let Z=W.responseTo?this.pending.get(W.responseTo):void 0;if(!Z)return;if(this.pending.delete(W.responseTo),W.error!==void 0&&W.error!==null)Z.reject(new k(String(W.error)));else Z.resolve(W.payload)}close(W){if(this.closed)return;this.closed=!0;for(let Z of this.pending.values())Z.reject(W);this.pending.clear(),this.handlers.clear(),this.backlog=[]}}function CW(W,Z){return new fW(W,Z)}class v{url;renderId;frameworkNavigate;activeViews;socket=null;messageQueue;connectionListeners=new Set;serverErrors=new Map;serverErrorListeners=new Set;channels=new Map;constructor(W,Z,$){this.url=W;this.renderId=Z;this.frameworkNavigate=$;this.socket=null,this.activeViews=new Map,this.messageQueue=[]}isConnected(){return this.socket?.connected??!1}async connect(){if(this.socket)return;return new Promise((W,Z)=>{let $=FZ(this.url,{transports:["websocket","webtransport"],auth:{renderId:this.renderId}});this.socket=$,$.on("connect",()=>{console.log("[SocketIOTransport] Connected:",this.socket?.id);for(let[Q,q]of this.activeViews)$.emit("message",T({type:"mount",path:Q,routeInfo:q.routeInfo}));for(let Q of this.messageQueue){if(Q.type==="mount"&&this.activeViews.has(Q.path))continue;if(Q.type==="navigate")continue;$.emit("message",T(Q))}this.messageQueue=[],this.notifyConnectionListeners(!0),W()}),$.on("connect_error",(Q)=>{console.error("[SocketIOTransport] Connection failed:",Q),this.notifyConnectionListeners(!1),Z(Q)}),$.on("disconnect",()=>{console.log("[SocketIOTransport] Disconnected"),this.handleTransportDisconnect(),this.notifyConnectionListeners(!1)}),$.on("message",(Q)=>this.handleServerMessage(r(Q,{coerceNullsToUndefined:!0})))})}onConnectionChange(W){return this.connectionListeners.add(W),W(this.isConnected()),()=>{this.connectionListeners.delete(W)}}notifyConnectionListeners(W){for(let Z of this.connectionListeners)Z(W)}onServerError(W){this.serverErrorListeners.add(W);for(let[Z,$]of this.serverErrors)W(Z,$);return()=>{this.serverErrorListeners.delete(W)}}notifyServerError(W,Z){for(let $ of this.serverErrorListeners)$(W,Z)}async sendMessage(W){if(this.isConnected())this.socket.emit("message",T(W));else this.messageQueue.push(W)}async sendChannelMessage(W){await this.sendMessage(W)}mountView(W,Z){if(this.activeViews.has(W))throw Error(`Path ${W} is already mounted`);this.activeViews.set(W,Z),this.sendMessage({type:"mount",path:W,routeInfo:Z.routeInfo})}async navigate(W,Z){await this.sendMessage({type:"navigate",path:W,routeInfo:Z})}unmount(W){this.sendMessage({type:"unmount",path:W}),this.activeViews.delete(W)}disconnect(){this.socket?.disconnect(),this.socket=null,this.messageQueue=[],this.connectionListeners.clear(),this.activeViews.clear(),this.serverErrors.clear(),this.serverErrorListeners.clear();for(let{bridge:W}of this.channels.values())W.dispose(new k("Client disconnected"));this.channels.clear()}handleServerMessage(W){switch(W.type){case"vdom_init":{let Z=this.activeViews.get(W.path);if(!Z)return;if(Z)Z.onInit(W.vdom);if(this.serverErrors.has(W.path))this.serverErrors.delete(W.path),this.notifyServerError(W.path,null);break}case"vdom_update":{let Z=this.activeViews.get(W.path);if(!Z)return;if(Z.onUpdate(W.ops),this.serverErrors.has(W.path))this.serverErrors.delete(W.path),this.notifyServerError(W.path,null);break}case"server_error":{if(!this.activeViews.has(W.path))return;this.serverErrors.set(W.path,W.error),this.notifyServerError(W.path,W.error);break}case"api_call":{this.performApiCall(W);break}case"navigate_to":{let Z=!!W.replace,$=W.path||"";if($.startsWith("//"))$=`${window.location.protocol}${$}`;if(/^[a-zA-Z][a-zA-Z0-9+.-]*:/.test($))if($.startsWith("http://")||$.startsWith("https://"))try{let q=new URL($);if(q.origin===window.location.origin){let J=`${q.pathname}${q.search}${q.hash}`;this.frameworkNavigate(J,{replace:Z})}else if(Z)window.location.replace($);else window.location.assign($)}catch{if(Z)window.location.replace($);else window.location.assign($)}else if(Z)window.location.replace($);else window.location.assign($);else this.frameworkNavigate($,{replace:Z});break}case"channel_message":{this.routeChannelMessage(W);break}default:console.error("Unexpected message:",W)}}async performApiCall(W){try{let Z=await fetch(W.url,{method:W.method||"GET",headers:{...W.headers||{},...W.body!=null&&!("content-type"in(W.headers||{}))?{"content-type":"application/json"}:{}},body:W.body!=null?typeof W.body==="string"?W.body:JSON.stringify(W.body):void 0,credentials:W.credentials||"include"}),$={};Z.headers.forEach((U,z)=>$[z]=U);let Q=null;if((Z.headers.get("content-type")||"").includes("application/json"))Q=await Z.json().catch(()=>null);else Q=await Z.text().catch(()=>null);let J={type:"api_result",id:W.id,ok:Z.ok,status:Z.status,headers:$,body:Q};await this.sendMessage(J)}catch(Z){let $={type:"api_result",id:W.id,ok:!1,status:0,headers:{},body:{error:String(Z)}};await this.sendMessage($)}}async invokeCallback(W,Z,$){await this.sendMessage({type:"callback",path:W,callback:Z,args:$.map(s)})}acquireChannel(W){let Z=this.ensureChannelEntry(W);return Z.refCount+=1,Z.bridge}releaseChannel(W){let Z=this.channels.get(W);if(!Z)return;if(Z.refCount=Math.max(0,Z.refCount-1),Z.refCount===0)Z.bridge.dispose(new k("Channel released")),this.channels.delete(W)}ensureChannelEntry(W){let Z=this.channels.get(W);if(!Z)Z={bridge:CW(this,W),refCount:0},this.channels.set(W,Z);return Z}routeChannelMessage(W){let Z=this.ensureChannelEntry(W.channel);if(Z.bridge.handleServerMessage(W)&&Z.refCount===0)this.channels.delete(W.channel)}handleTransportDisconnect(){for(let W of this.channels.values())W.bridge.handleDisconnect(new k("Connection lost"))}}import{useLocation as GZ,useParams as VZ,useNavigate as UZ}from"react-router";import{jsx as Y,jsxs as u}from"react/jsx-runtime";var OW=AW(null),RW=AW(null),i=()=>{let W=NW(OW);if(!W)throw Error("usePulseClient must be used within a PulseProvider");return W},DZ=(W)=>{let Z=NW(RW);if(!Z)throw Error("usePulsePrerender must be used within a PulseProvider");let $=Z.views[W];if(!$)throw Error(`No prerender found for '${W}'`);return $},e=typeof window<"u";function PZ({children:W,config:Z,prerender:$}){let[Q,q]=a(!0),J=UZ(),{renderId:U}=$,z=t(()=>new v(Z.serverAddress,U,J),[Z.serverAddress,J,U]);return E(()=>z.onConnectionChange(q),[z]),E(()=>{if(e)return z.connect(),()=>z.disconnect()},[z]),Y(OW.Provider,{value:z,children:u(RW.Provider,{value:$,children:[!Q&&Y("div",{style:{position:"fixed",bottom:"20px",right:"20px",backgroundColor:"red",color:"white",padding:"10px",borderRadius:"5px",zIndex:1000},children:"Failed to connect to the server."}),W]})})}function fZ({externalComponents:W,path:Z}){let $=i(),Q=DZ(Z),q=t(()=>new h($,Z,W),[$,Z,W]),[J,U]=a(()=>q.renderNode(Q)),[z,V]=a(null),X=GZ(),P=VZ(),C=t(()=>{let{"*":D="",...G}=P,f=new URLSearchParams(X.search);return{hash:X.hash,pathname:X.pathname,query:X.search,queryParams:Object.fromEntries(f.entries()),pathParams:G,catchall:D.length>0?D.split("/"):[]}},[X.hash,X.pathname,X.search,JSON.stringify(P)]);if(E(()=>{if(e){$.mountView(Z,{routeInfo:C,onInit:(G)=>{U(q.renderNode(G))},onUpdate:(G)=>{U((f)=>f==null?f:d(f,G,q))}});let D=$.onServerError((G,f)=>{if(G===Z)V(f)});return()=>{D(),$.unmount(Z)}}},[$]),E(()=>{if(e)$.navigate(Z,C)},[$,Z,C]),z)return Y(CZ,{error:z});return J}function CZ({error:W}){return u("div",{style:{padding:16,border:"1px solid #e00",background:"#fff5f5",color:"#900",fontFamily:'ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace',whiteSpace:"pre-wrap"},children:[u("div",{style:{fontWeight:700,marginBottom:8},children:["Server Error during ",W.phase]}),W.message&&Y("div",{children:W.message}),W.stack&&u("details",{open:!0,style:{marginTop:8},children:[Y("summary",{children:"Stack trace"}),Y("pre",{style:{margin:0},children:W.stack})]})]})}import{useEffect as AZ,useMemo as NZ}from"react";function OZ(W){let Z=i(),$=NZ(()=>{if(!W)throw Error("usePulseChannel requires a non-empty channelId");return Z.acquireChannel(W)},[Z,W]);return AZ(()=>{return()=>{Z.releaseChannel(W)}},[Z,W]),$}import{forwardRef as RZ,useCallback as IZ}from"react";import{jsx as jZ}from"react/jsx-runtime";var wZ=RZ(function({onSubmit:Z,action:$,...Q},q){return jZ("form",{...Q,action:$,ref:q,onSubmit:IZ((J)=>IW({event:J,action:$,onSubmit:Z}),[$,Z])})});async function IW({event:W,action:Z,onSubmit:$,formData:Q,force:q}){if($?.(W),!q&&W.defaultPrevented)return;let J=W.currentTarget;W.preventDefault();let U=W.nativeEvent;if(!Q)Q=new FormData(J,U.submitter);let z=new URL(Z,window.location.href);try{await fetch(z,{method:"POST",credentials:"include",body:Q})}catch(V){throw V}}import{io as BZ}from"socket.io-client";class wW{url;socket=null;listener=null;messageQueue=[];connectionListeners=new Set;constructor(W){this.url=W}connect(W){return this.listener=W,new Promise((Z,$)=>{this.socket=BZ(this.url,{transports:["websocket"]}),this.socket.on("connect",()=>{console.log("[SocketIOTransport] Connected:",this.socket?.id);for(let Q of this.messageQueue)this.socket?.emit("message",Q);this.messageQueue=[],this.notifyConnectionListeners(!0),Z()}),this.socket.on("connect_error",(Q)=>{console.error("[SocketIOTransport] Connection failed:",Q),this.notifyConnectionListeners(!1),$(Q)}),this.socket.on("disconnect",()=>{console.log("[SocketIOTransport] Disconnected"),this.notifyConnectionListeners(!1)}),this.socket.on("message",(Q)=>{this.listener?.(Q)})})}disconnect(){this.socket?.disconnect(),this.socket=null,this.listener=null,this.messageQueue=[],this.connectionListeners.clear()}async sendMessage(W){if(this.isConnected())this.socket.emit("message",W);else this.messageQueue.push(W)}isConnected(){return this.socket?.connected||!1}onConnectionChange(W){return this.connectionListeners.add(W),W(this.isConnected()),()=>{this.connectionListeners.delete(W)}}notifyConnectionListeners(W){for(let Z of this.connectionListeners)Z(W)}}function KZ({params:W,request:Z}){let{"*":$="",...Q}=W,q=new URL(Z.url);return{hash:q.hash,pathname:q.pathname,query:q.search,queryParams:Object.fromEntries(q.searchParams.entries()),pathParams:Q,catchall:$.length>1?$.split("/"):[]}}function kZ(W){if(W===null||typeof W!=="object")return!1;let Z=Object.getPrototypeOf(W);return Z===Object.prototype||Z===null}function WW(W){return typeof W==="function"||typeof W==="symbol"||typeof W>"u"}async function HZ(W){let Z=await W.arrayBuffer();return Array.from(new Uint8Array(Z))}async function yZ(W){return await _(W,{seen:new WeakMap,nextId:1})}function YZ(W,Z){if(W.seen.get(Z)!==void 0)return null;let Q=W.nextId++;return W.seen.set(Z,Q),Q}async function _(W,Z){if(W===null||typeof W!=="object")return W;if(W instanceof Date)return{__t:"datetime",timestamp:W.getTime()};if(W instanceof FormData){let z=YZ(Z,W);if(z===null)return{__t:"ref",id:Z.seen.get(W)};let V={};for(let[P,C]of W.entries()){let D=await _(C,Z);if(D===void 0)continue;if(Object.prototype.hasOwnProperty.call(V,P)){let G=V[P];if(Array.isArray(G))G.push(D);else V[P]=[G,D]}else V[P]=D}return{__t:"formdata",fields:V,__id:z}}if(W instanceof File){let z=W,V=await HZ(W);return{__t:"file",name:z.name,type:z.type,size:z.size,lastModified:z.lastModified,content:V}}let $=W,Q=Z.seen.get($);if(Q!==void 0)return{__t:"ref",id:Q};let q=Z.nextId++;if(Z.seen.set($,q),Array.isArray(W)){let V=(await Promise.all(W.map((P)=>_(P,Z)))).filter((P)=>P!==void 0);return{__t:"array",__id:q,items:V}}let J={};if(kZ(W))for(let z of Object.keys(W)){let V=W[z];if(WW(V))continue;let X=await _(V,Z);if(X!==void 0)J[z]=X}else for(let z in W){let V=W[z];if(WW(V))continue;let X=await _(V,Z);if(X!==void 0)J[z]=X}return{__t:"object",__id:q,props:J}}function bZ(W){return b(W)}function b(W){if(W===null||typeof W!=="object")return W;let Z=W,$=Z.__t;if($==="datetime"){let q=Z.timestamp;return new Date(q)}if($==="file"){let q=Z.content;if(Array.isArray(q))return{...Z,content:new Uint8Array(q)};return Z}if($==="formdata"){let q=Z.fields,J={};for(let U of Object.keys(q)){let z=q[U];if(Array.isArray(z))J[U]=z.map((V)=>b(V));else J[U]=b(z)}return{__t:"formdata",fields:J}}if($==="array")return Z.items.map((J)=>b(J));if($==="object"){let q=Z.props,J={};for(let U of Object.keys(q))J[U]=b(q[U]);return J}if($==="ref")return Z;let Q={};for(let q of Object.keys(Z))Q[q]=b(Z[q]);return Q}function MZ(W){return ZW(W,new WeakSet)}function ZW(W,Z){if(W===null||typeof W!=="object")return W;if(Z.has(W))return;if(Z.add(W),Array.isArray(W))return W.map((Q)=>ZW(Q,Z)).filter((Q)=>Q!==void 0);let $={};for(let Q in W){let q=W[Q];if(WW(q))continue;let J=ZW(q,Z);if(J!==void 0)$[Q]=J}return $}export{i as usePulseClient,OZ as usePulseChannel,IW as submitForm,T as serialize,KZ as extractServerRouteInfo,s as extractEvent,yZ as encodeForWire,r as deserialize,bZ as decodeFromWire,MZ as cleanForSerialization,d as applyReactTreeUpdates,h as VDOMRenderer,wW as SocketIOTransport,yW as RenderLazy,fZ as PulseView,v as PulseSocketIOClient,PZ as PulseProvider,wZ as PulseForm,k as PulseChannelResetError};
2
2
 
3
- //# debugId=9693F40BB63A52DC64756E2164756E21
3
+ //# debugId=618B63A0B4F1253264756E2164756E21