dolphin-client 1.1.3 → 1.1.4

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.
@@ -1,29 +1,29 @@
1
- var DolphinModule=(()=>{var U=Object.defineProperty;var nt=Object.getOwnPropertyDescriptor;var it=Object.getOwnPropertyNames;var st=Object.prototype.hasOwnProperty;var rt=(w,t)=>{for(var e in t)U(w,e,{get:t[e],enumerable:!0})},ot=(w,t,e,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of it(t))!st.call(w,s)&&s!==e&&U(w,s,{get:()=>t[s],enumerable:!(i=nt(t,s))||i.enumerable});return w};var at=w=>ot(U({},"__esModule",{value:!0}),w);var lt={};rt(lt,{DolphinClient:()=>$});var N=class{client;constructor(t){return this.client=t,this._createProxy([])}_createProxy(t){let e=t.join("/"),i=r=>this.request("GET",e,null,r);i.get=(r,a)=>typeof r=="string"?this.request("GET",r,null,a):this.request("GET",e,null,r),i.post=(r,a,y)=>typeof r=="string"?this.request("POST",r,a,y):this.request("POST",e,r,a),i.put=(r,a,y)=>typeof r=="string"?this.request("PUT",r,a,y):this.request("PUT",e,r,a),i.patch=(r,a,y)=>typeof r=="string"?this.request("PATCH",r,a,y):this.request("PATCH",e,r,a),i.del=(r,a)=>typeof r=="string"?this.request("DELETE",r,null,a):this.request("DELETE",e,null,r),i.request=(r,a,y,T)=>{let E=a?e?`${e}/${a.startsWith("/")?a.slice(1):a}`:a:e;return this.request(r,E,y,T)},i.requestDirect=(r,a,y,T)=>this.requestDirect(r,a,y,T),i._findCSRFToken=()=>this._findCSRFToken(),i._resolveBaseUrl=r=>this._resolveBaseUrl(r),i._normalizeValidationErrors=r=>this._normalizeValidationErrors(r);let s=["get","post","put","patch","del","request","requestDirect","_findCSRFToken","_resolveBaseUrl","_normalizeValidationErrors"];return new Proxy(i,{get:(r,a)=>typeof a=="string"&&!s.includes(a)?this._createProxy([...t,a]):r[a]})}_findCSRFToken(){if(typeof document>"u")return null;let t=["csrf-token","_csrf","xsrf-token","csrf_token"];for(let r of t){let a=document.querySelector(`meta[name="${r}"], meta[content][name$="${r}"]`);if(a){let y=a.getAttribute("content");if(y)return y}}let e=["_csrfToken","_token","_csrf","csrf_token"];for(let r of e){let a=document.querySelector(`input[type="hidden"][name="${r}"]`);if(a&&a.value)return a.value}let i=["csrfToken","XSRF-TOKEN","_csrf","csrf_token"];for(let r of i){let a=document.cookie.match(new RegExp("(^|;\\s*)"+r+"=([^;]*)"));if(a)return decodeURIComponent(a[2])}let s=typeof window<"u"&&window.wpApiSettings?.nonce;return s||null}_resolveBaseUrl(t){if(t.startsWith("http://")||t.startsWith("https://"))return t;let e=this.client.httpUrl;if(typeof document<"u"){let s=document.querySelector("base[href]");if(s){let r=s.getAttribute("href")||"";if(r&&r!=="/"){let a=r.endsWith("/")?r.slice(0,-1):r;e=`${this.client.httpUrl}${a.startsWith("/")?a:"/"+a}`}}else{let r=document.querySelector('meta[name="base-path"]');if(r){let a=r.getAttribute("content")||"";if(a&&a!=="/"){let y=a.endsWith("/")?a.slice(0,-1):a;e=`${this.client.httpUrl}${y.startsWith("/")?y:"/"+y}`}}}}let i=t.startsWith("/")?t:"/"+t;return`${e}${i}`}_normalizeValidationErrors(t){let e={};if(!t||typeof t!="object")return e;let i=t.errors||t.validationErrors||t;if(Array.isArray(i)){for(let s of i)if(s&&typeof s=="object"){let r=s.path||s.param||s.field||s.property,a=s.msg||s.message||s.error;r&&a&&(e[r]=Array.isArray(a)?a[0]:a)}return e}if(typeof i=="object"&&i!==null)for(let s in i){let r=i[s];if(r)if(Array.isArray(r))r.length>0&&(e[s]=String(r[0]));else if(typeof r=="object"){let a=Object.keys(r);if(a.length>0){let y=a[0];e[s]=String(r[y])}}else e[s]=String(r)}return e}async request(t,e,i=null,s={}){if(this.client.offline){let r=this.client.offline.isOnline,a=`${t.toUpperCase()}:${e}`;if(t.toUpperCase()==="GET")if(r)try{let y=await this.requestDirect(t,e,i,s);return await this.client.offline.setCache(a,y),y}catch(y){let T=await this.client.offline.getCache(a);if(T!=null)return T;throw y}else{let y=await this.client.offline.getCache(a);if(y!=null)return y;throw{status:503,data:{error:"Offline, no cache available"}}}else return r?this.requestDirect(t,e,i,s):(await this.client.offline.queueMutation(t,e,i),this.client._dispatch("offline:queued",{method:t,path:e,body:i}),{success:!0,offline:!0,message:"Mutation queued offline"})}return this.requestDirect(t,e,i,s)}async requestDirect(t,e,i=null,s={}){let r=s._isRetry===!0,a=t.toUpperCase(),y=i,E={...!["GET","HEAD"].includes(a)?{"Content-Type":"application/json"}:{},...s.headers||{}};["PUT","PATCH","DELETE"].includes(a)&&(this.client.options.methodSpoofing||s.methodSpoofing)&&(E["X-HTTP-Method-Override"]=a,y instanceof FormData?y.append("_method",a):y&&typeof y=="object"?y={...y,_method:a}:y||(y={_method:a}),a="POST");let D=this._resolveBaseUrl(e);this.client.options.debug&&console.log("%c\u{1F680} [Dolphin API Request]:","color: #3b82f6; font-weight: bold;",t.toUpperCase(),e,y||"");let k=new AbortController,M=setTimeout(()=>k.abort(),this.client.options.timeout);if(this.client.accessToken&&(E.Authorization=`Bearer ${this.client.accessToken}`),["POST","PUT","PATCH","DELETE"].includes(t.toUpperCase())){let h=this._findCSRFToken();h&&(E["X-CSRF-Token"]=h,E["X-XSRF-TOKEN"]=h,E["X-CSRFToken"]=h,E["X-WP-Nonce"]=h,y&&typeof y=="object"&&!y._csrfToken&&!y._token&&!y._csrf&&(y={...y,_csrfToken:h,_token:h,_csrf:h}))}let x={...s};delete x._isRetry,delete x.methodSpoofing;try{let h=await fetch(D,{method:a,headers:E,signal:k.signal,...y?{body:JSON.stringify(y)}:{},...x});if(clearTimeout(M),h.status===401&&!r&&this.client.options.autoRefreshToken&&await this.client.auth._silentRefresh())return this.request(t,e,i,{...s,_isRetry:!0});let f=(h.headers.get("content-type")||"").includes("application/json")?await h.json():await h.text();if(!h.ok)throw{status:h.status,data:f};if(this.client.options.debug&&console.log("%c\u2705 [Dolphin API Success]:","color: #10b981; font-weight: bold;",t.toUpperCase(),e,f),f&&typeof f=="object"&&f.accessToken&&(this.client.setToken(f.accessToken),f.user&&(this.client.auth.user=f.user)),this.client.options.autoBroadcast&&["POST","PUT","PATCH","DELETE"].includes(t.toUpperCase())){let n=e.startsWith("/")?e.substring(1):e;this.client.publish(n,{method:t.toUpperCase(),payload:i,result:f})}return f}catch(h){if(clearTimeout(M),this.client.options.debug&&console.error("%c\u274C [Dolphin API Error]:","color: #ef4444; font-weight: bold;",t.toUpperCase(),e,h),h&&typeof h=="object"&&h.data){let d=this._normalizeValidationErrors(h.data);if(Object.keys(d).length>0)for(let f in d)this.client.publish(`errors/${f}`,d[f])}throw h.name==="AbortError"?{status:408,data:{error:"Request timed out"}}:h}}};var R=class{client;user;_refreshing;constructor(t){this.client=t,this.user=null,this._refreshing=!1}async login(t,e){let i=await this.client.api.post("/api/auth/login",{email:t,password:e});return i.accessToken&&(this.client.setToken(i.accessToken),this.user=i.user||null),i}async register(t){return this.client.api.post("/api/auth/register",t)}async me(){let t=await this.client.api.get("/api/auth/me");return t.success&&(this.user=t.data),t}async logout(){try{await this.client.api.post("/api/auth/logout")}catch{}this.client.setToken(null),this.user=null}async refresh(){return this._silentRefresh()}async _silentRefresh(){if(this._refreshing)return!1;this._refreshing=!0;try{let t=await this.client.api.post("/api/auth/refresh",null,{_isRetry:!0});return t.accessToken?(this.client.setToken(t.accessToken),!0):!1}catch{return this.client.setToken(null),!1}finally{this._refreshing=!1}}async verify2FA(t,e){let i={code:t,email:e||this.user?.email},s=await this.client.api.post("/api/auth/2fa/verify",i);return s.accessToken&&(this.client.setToken(s.accessToken),s.user&&(this.user=s.user)),s}async enable2FA(){return this.client.api.post("/api/auth/2fa/enable")}async disable2FA(t){return this.client.api.post("/api/auth/2fa/disable",{code:t})}async forgotPassword(t){return this.client.api.post("/api/auth/forgot-password",{email:t})}async resetPassword(t,e){return this.client.api.post("/api/auth/reset-password",{token:t,newPassword:e})}};var O=class{client;data;listeners;subscribed;_unsubscribers;constructor(t){return this.client=t,this.data=new Map,this.listeners=new Set,this.subscribed=new Set,this._unsubscribers=new Map,new Proxy(this,{get:(e,i)=>{if(i in e)return e[i];if(typeof i=="string")return this._getCollection(i)}})}_getCollection(t){if(!this.data.has(t)){let e={_rawItems:[],items:[],loading:!0,error:null,success:!1,_filter:null,_sort:null,where:i=>(e._filter=i,this._applyTransform(e),e),orderBy:(i,s="asc")=>(e._sort={key:i,direction:s},this._applyTransform(e),e),reset:()=>(e._filter=null,e._sort=null,this._applyTransform(e),e)};this.data.set(t,e),this._fetchAndSync(t)}return this.data.get(t)}async _fetchAndSync(t){let e=this.data.get(t);try{let i=await this.client.api.get(`/${t.toLowerCase()}`);if(e._rawItems=Array.isArray(i)?i:i.data||[],e.loading=!1,e.success=!0,e.error=null,this._applyTransform(e),!this.subscribed.has(t)){let s=()=>this.client.unsubscribe(`db:sync/${t.toLowerCase()}`,r),r=a=>{this._handleRemoteUpdate(t,a)};this.client.subscribe(`db:sync/${t.toLowerCase()}`,r),this._unsubscribers.set(t,s),this.subscribed.add(t)}}catch(i){e.loading=!1,e.success=!1,e.error=i.data?.error||i.message||"Fetch failed",this._notify()}}_applyTransform(t){let e=[...t._rawItems];if(t._filter&&(e=e.filter(t._filter)),t._sort){let{key:i,direction:s}=t._sort;e.sort((r,a)=>r[i]===a[i]?0:(r[i]>a[i]?1:-1)*(s==="asc"?1:-1))}t.items=e,this._notify()}_handleRemoteUpdate(t,e){let i=this.data.get(t);if(!i)return;let{type:s,data:r}=e,a=i._rawItems;s==="create"?a=[...a,r]:s==="update"?a=a.map(y=>y.id===r.id||y._id===r._id?{...y,...r}:y):s==="delete"&&(a=a.filter(y=>!(r.id!=null&&y.id===r.id||r._id!=null&&y._id===r._id))),i._rawItems=a,this._applyTransform(i)}subscribe(t){return this.listeners.add(t),()=>this.listeners.delete(t)}getSnapshot(t){return this.data.get(t)||{items:[],loading:!1,error:null,success:!1}}_notify(){this.listeners.forEach(t=>t())}destroy(){this._unsubscribers.forEach(t=>{try{t()}catch{}}),this._unsubscribers.clear(),this.subscribed.clear(),this.listeners.clear(),this.data.clear()}};var $=class{host;httpUrl;deviceId;options;socket;storage;accessToken;api;auth;store;handlers;signalHandlers;fileHandlers;_offlineQueue;reconnectAttempts;_reconnectTimer;_attachedListeners;constructor(t="",e="",i={}){!t&&typeof window<"u"&&(t=window.location.host);let s="http:";t.startsWith("https://")?s="https:":t.startsWith("http://")?s="http:":typeof window<"u"&&(s=window.location.protocol),this.host=(t||"localhost").replace(/\/$/,"").replace(/^https?:\/\//,""),this.httpUrl=`${s}//${this.host}`,this.deviceId=e||(typeof crypto<"u"&&typeof crypto.randomUUID=="function"?"web_"+crypto.randomUUID().replace(/-/g,"").slice(0,8):"web_"+Math.random().toString(36).slice(2,10)),this.options={timeout:15e3,chunkSize:65536,maxReconnect:5,autoRefreshToken:!0,debug:!1,methodSpoofing:!1,routerViewport:"main, #viewport, body",routerTransitions:!0,...i},this.socket=null,this.storage=typeof localStorage<"u"?localStorage:{getItem:()=>null,setItem:()=>{},removeItem:()=>{}},this.accessToken=this.storage.getItem("dolphin_token"),this.api=new N(this),this.auth=new R(this),this.store=new O(this),this.handlers=new Map,this.signalHandlers=new Set,this.fileHandlers=new Set,this._offlineQueue=[],this.reconnectAttempts=0,this._reconnectTimer=null,this._attachedListeners=[],typeof window<"u"&&typeof this._initDOMBinding=="function"&&this._initDOMBinding(),typeof this._initOffline=="function"&&this._initOffline(),typeof this._initA11y=="function"&&this._initA11y(),typeof this._initI18n=="function"&&this._initI18n(),typeof this._initDragDrop=="function"&&this._initDragDrop(),typeof this._initCollab=="function"&&this._initCollab()}setToken(t){this.accessToken=t,t?this.storage.setItem("dolphin_token",t):this.storage.removeItem("dolphin_token")}async connect(){return this.socket&&(this.socket.readyState===WebSocket.OPEN||this.socket.readyState===WebSocket.CONNECTING)?Promise.resolve():new Promise((t,e)=>{let s=`${this.httpUrl.startsWith("https")?"wss:":"ws:"}//${this.host}/realtime?deviceId=${this.deviceId}`;console.log(`[Dolphin] Connecting to ${s}...`),this.socket=new WebSocket(s),this.socket.onopen=()=>{console.log(`[Dolphin] Connected as "${this.deviceId}" \u{1F42C}`),this.reconnectAttempts=0,this._flushOfflineQueue(),t()},this.socket.onmessage=r=>this._handleMessage(r.data),this.socket.onclose=()=>{console.warn("[Dolphin] Connection closed"),this._maybeReconnect()},this.socket.onerror=r=>{console.error("[Dolphin] WebSocket error:",r),e(r)}})}disconnect(){this._reconnectTimer!==null&&(clearTimeout(this._reconnectTimer),this._reconnectTimer=null),this.socket&&(this.socket.onclose=null,this.socket.close(),this.socket=null),typeof this._collabCleanup=="function"&&this._collabCleanup(),this.cleanupDomListeners()}_handleMessage(t){try{let e=JSON.parse(t);this.options.debug&&console.log("%c\u{1F4E5} [Dolphin WS Incoming]:","color: #eab308; font-weight: bold;",e),e.type&&e.from&&(e.to===this.deviceId||e.to==="all")&&(e.msgId&&e.type!=="ACK"&&this._sendAck(e.from,e.msgId),this.signalHandlers.forEach(i=>i(e))),e.type==="FILE_AVAILABLE"&&this.fileHandlers.forEach(i=>i(e)),e.type==="FILE_CHUNK"&&(this.saveFileProgress(e.fileId,e.chunkIndex),this._dispatch("file:chunk",e),this._dispatch(`file:chunk/${e.fileId}`,e)),e.type==="FILE_UPLOAD_ACK"&&this._dispatch(`file:upload:ack/${e.fileId}`,e),e.type==="PULL_RESPONSE"&&(this._dispatch("pull:response",e.payload,e.topic),this._dispatch(`pull:response/${e.topic}`,e.payload,e.topic)),e.topic&&e.payload!==void 0&&this.handlers.forEach((i,s)=>{this._matchTopic(s,e.topic)&&i.forEach(r=>r(e.payload,e.topic))})}catch{this._dispatch("raw",t)}}_dispatch(t,e,i){let s=this.handlers.get(t);s&&s.forEach(r=>r(e,i||t))}_sendRaw(t){this.options.debug&&console.log("%c\u{1F4E4} [Dolphin WS Outgoing]:","color: #8b5cf6; font-weight: bold;",t);let e=typeof t=="string"?t:JSON.stringify(t);this.socket&&this.socket.readyState===WebSocket.OPEN?this.socket.send(e):this._offlineQueue.length<100&&this._offlineQueue.push(e)}_flushOfflineQueue(){for(;this._offlineQueue.length>0;){let t=this._offlineQueue.shift();this.socket&&this.socket.readyState===WebSocket.OPEN&&this.socket.send(t)}}_sendAck(t,e){this._sendRaw({type:"ACK",from:this.deviceId,to:t,data:{ackId:e},timestamp:Date.now()})}_matchTopic(t,e){if(t===e||t==="#")return!0;let i=t.split("/"),s=e.split("/");if(i.length!==s.length&&!t.includes("#"))return!1;for(let r=0;r<i.length;r++){if(i[r]==="#")return!0;if(i[r]!=="+"&&i[r]!==s[r])return!1}return i.length===s.length}_maybeReconnect(){if(this.reconnectAttempts<this.options.maxReconnect){this.reconnectAttempts++;let t=Math.pow(2,this.reconnectAttempts)*1e3;console.log(`[Dolphin] Reconnecting in ${t/1e3}s (attempt ${this.reconnectAttempts})...`),this._reconnectTimer=setTimeout(()=>{this._reconnectTimer=null,this.connect().catch(()=>{})},t)}else console.error("[Dolphin] Max reconnect attempts reached.")}subscribe(t,e){this.handlers.has(t)||(this.handlers.set(t,new Set),this._sendRaw({type:"sub",topic:t})),this.handlers.get(t).add(e)}unsubscribe(t,e){if(this.handlers.has(t)){let i=this.handlers.get(t);i.delete(e),i.size===0&&(this.handlers.delete(t),this._sendRaw({type:"unsub",topic:t}))}}publish(t,e){this._sendRaw({topic:t,payload:e})}pubPush(t,e){this._sendRaw({type:"pub",topic:t,payload:e})}subPull(t,e=10){this._sendRaw({type:"PULL_REQUEST",topic:t,count:e})}async pubFile(t,e,i="",s){let r;e instanceof Blob?r=await e.arrayBuffer():e instanceof ArrayBuffer?r=e:r=e.buffer||e;let a=new Uint8Array(r),y=this.options.chunkSize,T=Math.ceil(a.length/y);this._sendRaw({type:"FILE_UPLOAD_START",fileId:t,name:i,size:a.length,totalChunks:T,chunkSize:y});for(let E=0;E<T;E++){let D=a.slice(E*y,(E+1)*y),k=this._uint8ToBase64(D);this._sendRaw({type:"FILE_UPLOAD_CHUNK",fileId:t,chunkIndex:E,totalChunks:T,data:k}),s&&s(Math.round((E+1)/T*100)),E%10===0&&await new Promise(M=>setTimeout(M,0))}this._sendRaw({type:"FILE_UPLOAD_DONE",fileId:t})}_uint8ToBase64(t){let e="";for(let i=0;i<t.length;i++)e+=String.fromCharCode(t[i]);return typeof btoa<"u"?btoa(e):Buffer.from(e,"binary").toString("base64")}subFile(t,e=0){this._sendRaw({type:"FILE_REQUEST",fileId:t,startChunk:e})}resumeFile(t){let e=parseInt(this.storage.getItem(`dolphin_file_${t}`)||"-1");this.subFile(t,e+1)}saveFileProgress(t,e){this.storage.setItem(`dolphin_file_${t}`,e.toString())}onSignal(t){this.signalHandlers.add(t)}offSignal(t){this.signalHandlers.delete(t)}onFileAvailable(t){this.fileHandlers.add(t)}offFileAvailable(t){this.fileHandlers.delete(t)}addDomListener(t,e,i){t&&(t.addEventListener(e,i),this._attachedListeners=this._attachedListeners||[],this._attachedListeners.push({target:t,event:e,cb:i}))}cleanupDomListeners(){this._attachedListeners&&(this._attachedListeners.forEach(({target:t,event:e,cb:i})=>{try{t.removeEventListener(e,i)}catch{}}),this._attachedListeners=[])}};function B(w){let t=new Map;function e(h){return h.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function i(h,d){if(!(!d||typeof d!="object"))try{let f=new Proxy(d,{has(o,c){return!0},get(o,c){if(typeof c=="string"){if(c in o)return o[c];if(typeof globalThis<"u"&&c in globalThis)return globalThis[c];if(typeof window<"u"&&c in window)return window[c]}}});return new Function("ctx",`with(ctx) { return (${h}); }`)(f)}catch{return d[h]}}function s(h,d){let f=[],n="",o=!1,c=!1,p=!1,l=0;for(let g=0;g<h.length;g++){let u=h[g];u==="'"&&!c&&!p?o=!o:u==='"'&&!o&&!p?c=!c:u==="`"&&!o&&!c?p=!p:u==="("||u==="["||u==="{"?!o&&!c&&!p&&l++:(u===")"||u==="]"||u==="}")&&!o&&!c&&!p&&l--,u===d&&!o&&!c&&!p&&l===0?(f.push(n),n=""):n+=u}return f.push(n),f}function r(h){let d=!1,f=!1,n=!1,o=0;for(let c=0;c<h.length;c++){let p=h[c];if(p==="'"&&!f&&!n?d=!d:p==='"'&&!d&&!n?f=!f:p==="`"&&!d&&!f?n=!n:p==="("||p==="["||p==="{"?!d&&!f&&!n&&o++:(p===")"||p==="]"||p==="}")&&!d&&!f&&!n&&o--,p===":"&&!d&&!f&&!n&&o===0)return[h.slice(0,c),h.slice(c+1)]}return null}function a(h){let d=h.getAttribute("data-rt-template");if(!d)return null;if(typeof document<"u"&&!d.includes("<"))try{let f=document.querySelector(d);if(f)return f.innerHTML}catch{}return d}function y(h,d){if(!h.includes("{#if")&&!h.includes("{#each")){let f=h;for(let n in d){let o=n.replace(/[.*+?^$${}()|[\]\\]/g,"\\$&");f=f.replace(new RegExp("\\{\\{"+o+"\\}}","g"),d[n]!==void 0&&d[n]!==null?d[n]:"")}return f=f.replace(/\{\{([\s\S]*?)\}\}/g,(n,o)=>{let c=o.trim();if(!c)return"";if(/^[a-zA-Z_$][a-zA-Z0-9_$]*(?:\??\.[a-zA-Z_$][a-zA-Z0-9_$]*)+$/.test(c)){let p=c.split(/\??\./),l=d;for(let g of p){if(l==null){l=void 0;break}l=l[g]}return l??""}return n}),f}try{let f=m=>m.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/\t/g,"\\t"),n=`let out = "";
2
- `,o=0,c=/(\{\{([\s\S]*?)\}\}|\{#if\s+([\s\S]*?)\}|\{:else\s+if\s+([\s\S]*?)\}|\{:else\}|\{\/if\}|\{#each\s+([\s\S]*?)\s+as\s+([a-zA-Z_$][a-zA-Z0-9_$]*)(?:\s*,\s*([a-zA-Z_$][a-zA-Z0-9_$]*))?\}|\{\/each\}|\{([^{}]+?)\})/g,p=[],l;for(;(l=c.exec(h))!==null;){let m=h.slice(o,l.index);m&&(n+=`out += "${f(m)}";
3
- `);let _=l[0];if(_.startsWith("{{")){let S=l[2];n+=`out += (${S} !== undefined && ${S} !== null ? ${S} : "");
4
- `}else if(_.startsWith("{#if")){let S=l[3];n+=`if (${S}) {
5
- `}else if(_.startsWith("{:else if")){let S=l[4];n+=`} else if (${S}) {
6
- `}else if(_.startsWith("{:else}"))n+=`} else {
7
- `;else if(_.startsWith("{/if}"))n+=`}
8
- `;else if(_.startsWith("{#each")){let S=l[5],C=l[6],v=l[7];p.push({indexVar:v}),n+=`if (typeof ${S} !== "undefined" && ${S} !== null && Array.isArray(${S})) {
9
- `,v&&(n+=` let ${v} = 0;
10
- `),n+=` for (let ${C} of ${S}) {
11
- `}else if(_.startsWith("{/each}")){let S=p.pop();S&&S.indexVar&&(n+=` ${S.indexVar}++;
12
- `),n+=` }
1
+ var DolphinModule=(()=>{var F=Object.defineProperty;var st=Object.getOwnPropertyDescriptor;var it=Object.getOwnPropertyNames;var rt=Object.prototype.hasOwnProperty;var ot=(w,t)=>{for(var e in t)F(w,e,{get:t[e],enumerable:!0})},at=(w,t,e,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of it(t))!rt.call(w,s)&&s!==e&&F(w,s,{get:()=>t[s],enumerable:!(n=st(t,s))||n.enumerable});return w};var ct=w=>at(F({},"__esModule",{value:!0}),w);var ut={};ot(ut,{DolphinClient:()=>M});var N=class{client;constructor(t){return this.client=t,this._createProxy([])}_createProxy(t){let e=t.join("/"),n=i=>this.request("GET",e,null,i);n.get=(i,o)=>typeof i=="string"?this.request("GET",i,null,o):this.request("GET",e,null,i),n.post=(i,o,f)=>typeof i=="string"?this.request("POST",i,o,f):this.request("POST",e,i,o),n.put=(i,o,f)=>typeof i=="string"?this.request("PUT",i,o,f):this.request("PUT",e,i,o),n.patch=(i,o,f)=>typeof i=="string"?this.request("PATCH",i,o,f):this.request("PATCH",e,i,o),n.del=(i,o)=>typeof i=="string"?this.request("DELETE",i,null,o):this.request("DELETE",e,null,i),n.request=(i,o,f,A)=>{let v=o?e?`${e}/${o.startsWith("/")?o.slice(1):o}`:o:e;return this.request(i,v,f,A)},n.requestDirect=(i,o,f,A)=>this.requestDirect(i,o,f,A),n._findCSRFToken=()=>this._findCSRFToken(),n._resolveBaseUrl=i=>this._resolveBaseUrl(i),n._normalizeValidationErrors=i=>this._normalizeValidationErrors(i);let s=["get","post","put","patch","del","request","requestDirect","_findCSRFToken","_resolveBaseUrl","_normalizeValidationErrors"];return new Proxy(n,{get:(i,o)=>typeof o=="string"&&!s.includes(o)?this._createProxy([...t,o]):i[o]})}_findCSRFToken(){if(typeof document>"u")return null;let t=["csrf-token","_csrf","xsrf-token","csrf_token"];for(let i of t){let o=document.querySelector(`meta[name="${i}"], meta[content][name$="${i}"]`);if(o){let f=o.getAttribute("content");if(f)return f}}let e=["_csrfToken","_token","_csrf","csrf_token"];for(let i of e){let o=document.querySelector(`input[type="hidden"][name="${i}"]`);if(o&&o.value)return o.value}let n=["csrfToken","XSRF-TOKEN","_csrf","csrf_token"];for(let i of n){let o=document.cookie.match(new RegExp("(^|;\\s*)"+i+"=([^;]*)"));if(o)return decodeURIComponent(o[2])}let s=typeof window<"u"&&window.wpApiSettings?.nonce;return s||null}_resolveBaseUrl(t){if(t.startsWith("http://")||t.startsWith("https://"))return t;let e=this.client.httpUrl;if(typeof document<"u"){let s=document.querySelector("base[href]");if(s){let i=s.getAttribute("href")||"";if(i&&i!=="/"){let o=i.endsWith("/")?i.slice(0,-1):i;e=`${this.client.httpUrl}${o.startsWith("/")?o:"/"+o}`}}else{let i=document.querySelector('meta[name="base-path"]');if(i){let o=i.getAttribute("content")||"";if(o&&o!=="/"){let f=o.endsWith("/")?o.slice(0,-1):o;e=`${this.client.httpUrl}${f.startsWith("/")?f:"/"+f}`}}}}let n=t.startsWith("/")?t:"/"+t;return`${e}${n}`}_normalizeValidationErrors(t){let e={};if(!t||typeof t!="object")return e;let n=t.errors||t.validationErrors||t;if(Array.isArray(n)){for(let s of n)if(s&&typeof s=="object"){let i=s.path||s.param||s.field||s.property,o=s.msg||s.message||s.error;i&&o&&(e[i]=Array.isArray(o)?o[0]:o)}return e}if(typeof n=="object"&&n!==null)for(let s in n){let i=n[s];if(i)if(Array.isArray(i))i.length>0&&(e[s]=String(i[0]));else if(typeof i=="object"){let o=Object.keys(i);if(o.length>0){let f=o[0];e[s]=String(i[f])}}else e[s]=String(i)}return e}async request(t,e,n=null,s={}){if(this.client.offline){let i=this.client.offline.isOnline,o=`${t.toUpperCase()}:${e}`;if(t.toUpperCase()==="GET")if(i)try{let f=await this.requestDirect(t,e,n,s);return await this.client.offline.setCache(o,f),f}catch(f){let A=await this.client.offline.getCache(o);if(A!=null)return A;throw f}else{let f=await this.client.offline.getCache(o);if(f!=null)return f;throw{status:503,data:{error:"Offline, no cache available"}}}else return i?this.requestDirect(t,e,n,s):(await this.client.offline.queueMutation(t,e,n),this.client._dispatch("offline:queued",{method:t,path:e,body:n}),{success:!0,offline:!0,message:"Mutation queued offline"})}return this.requestDirect(t,e,n,s)}async requestDirect(t,e,n=null,s={}){let i=s._isRetry===!0,o=t.toUpperCase(),f=n,v={...!["GET","HEAD"].includes(o)?{"Content-Type":"application/json"}:{},...s.headers||{}};["PUT","PATCH","DELETE"].includes(o)&&(this.client.options.methodSpoofing||s.methodSpoofing)&&(v["X-HTTP-Method-Override"]=o,f instanceof FormData?f.append("_method",o):f&&typeof f=="object"?f={...f,_method:o}:f||(f={_method:o}),o="POST");let D=this._resolveBaseUrl(e);this.client.options.debug&&console.log("%c\u{1F680} [Dolphin API Request]:","color: #3b82f6; font-weight: bold;",t.toUpperCase(),e,f||"");let k=new AbortController,$=setTimeout(()=>k.abort(),this.client.options.timeout);if(this.client.accessToken&&(v.Authorization=`Bearer ${this.client.accessToken}`),["POST","PUT","PATCH","DELETE"].includes(t.toUpperCase())){let y=this._findCSRFToken();y&&(v["X-CSRF-Token"]=y,v["X-XSRF-TOKEN"]=y,v["X-CSRFToken"]=y,v["X-WP-Nonce"]=y,f&&typeof f=="object"&&!f._csrfToken&&!f._token&&!f._csrf&&(f={...f,_csrfToken:y,_token:y,_csrf:y}))}let I={...s};delete I._isRetry,delete I.methodSpoofing;try{let y=await fetch(D,{method:o,headers:v,signal:k.signal,...f?{body:JSON.stringify(f)}:{},...I});if(clearTimeout($),y.status===401&&!i&&this.client.options.autoRefreshToken&&await this.client.auth._silentRefresh())return this.request(t,e,n,{...s,_isRetry:!0});let h=(y.headers.get("content-type")||"").includes("application/json")?await y.json():await y.text();if(!y.ok)throw{status:y.status,data:h};if(this.client.options.debug&&console.log("%c\u2705 [Dolphin API Success]:","color: #10b981; font-weight: bold;",t.toUpperCase(),e,h),h&&typeof h=="object"&&h.accessToken&&(this.client.setToken(h.accessToken),h.user&&(this.client.auth.user=h.user)),this.client.options.autoBroadcast&&["POST","PUT","PATCH","DELETE"].includes(t.toUpperCase())){let r=e.startsWith("/")?e.substring(1):e;this.client.publish(r,{method:t.toUpperCase(),payload:n,result:h})}return h}catch(y){if(clearTimeout($),this.client.options.debug&&console.error("%c\u274C [Dolphin API Error]:","color: #ef4444; font-weight: bold;",t.toUpperCase(),e,y),y&&typeof y=="object"&&y.data){let d=this._normalizeValidationErrors(y.data);if(Object.keys(d).length>0)for(let h in d)this.client.publish(`errors/${h}`,d[h])}throw y.name==="AbortError"?{status:408,data:{error:"Request timed out"}}:y}}};var R=class{client;user;_refreshing;constructor(t){this.client=t,this.user=null,this._refreshing=!1}async login(t,e){let n=await this.client.api.post("/api/auth/login",{email:t,password:e});return n.accessToken&&(this.client.setToken(n.accessToken),this.user=n.user||null),n}async register(t){return this.client.api.post("/api/auth/register",t)}async me(){let t=await this.client.api.get("/api/auth/me");return t.success&&(this.user=t.data),t}async logout(){try{await this.client.api.post("/api/auth/logout")}catch{}this.client.setToken(null),this.user=null}async refresh(){return this._silentRefresh()}async _silentRefresh(){if(this._refreshing)return!1;this._refreshing=!0;try{let t=await this.client.api.post("/api/auth/refresh",null,{_isRetry:!0});return t.accessToken?(this.client.setToken(t.accessToken),!0):!1}catch{return this.client.setToken(null),!1}finally{this._refreshing=!1}}async verify2FA(t,e){let n={code:t,email:e||this.user?.email},s=await this.client.api.post("/api/auth/2fa/verify",n);return s.accessToken&&(this.client.setToken(s.accessToken),s.user&&(this.user=s.user)),s}async enable2FA(){return this.client.api.post("/api/auth/2fa/enable")}async disable2FA(t){return this.client.api.post("/api/auth/2fa/disable",{code:t})}async forgotPassword(t){return this.client.api.post("/api/auth/forgot-password",{email:t})}async resetPassword(t,e){return this.client.api.post("/api/auth/reset-password",{token:t,newPassword:e})}};var O=class{_src=[];_filtered=null;_filters=new Map;_sortFn=null;_version=0;constructor(t=[]){this._src=[...t]}_invalidate(){this._filtered=null,this._version++}getVersion(){return this._version}search(t,e=[]){if(!t||!t.trim())this._filters.delete("__search__");else{let n=t.trim().toLowerCase();this._filters.set("__search__",s=>(e.length?e:Object.keys(s)).some(o=>String(s[o]??"").toLowerCase().includes(n)))}return this._invalidate(),this}filter(t,e){let n=`__filter_${String(t)}__`;return e==null||e===""?this._filters.delete(n):this._filters.set(n,s=>s[t]===e),this._invalidate(),this}range(t,e,n){let s=`__range_${String(t)}__`;return this._filters.set(s,i=>{let o=Number(i[t]);return!isNaN(o)&&o>=e&&o<=n}),this._invalidate(),this}sort(t,e=!0){return this._sortFn=(n,s)=>{let i=n[t],o=s[t];return i==null&&o==null?0:i==null?e?1:-1:o==null?e?-1:1:typeof i=="number"&&typeof o=="number"?e?i-o:o-i:String(i).localeCompare(String(o))*(e?1:-1)},this._invalidate(),this}clearFilters(){return this._filters.clear(),this._sortFn=null,this._invalidate(),this}get(){if(this._filtered!==null)return this._filtered;let t=this._src;for(let e of this._filters.values())t=t.filter(e);return this._sortFn&&(t=[...t].sort(this._sortFn)),this._filtered=t,t}page(t=1,e=10){let n=this.get(),s=(t-1)*e,i=Math.ceil(n.length/e);return{data:n.slice(s,s+e),total:n.length,page:t,size:e,pages:i,hasNext:t<i,hasPrev:t>1}}get length(){return this.get().length}get total(){return this._src.length}setSource(t){return this._src=[...t],this._invalidate(),this}add(t){return this._src=[...this._src,t],this._invalidate(),this}push(...t){return this._src=[...this._src,...t],this._invalidate(),this}updateById(t,e,n="id"){return this._src=this._src.map(s=>s[n]===t?{...s,...e}:s),this._invalidate(),this}removeById(t,e="id"){return this._src=this._src.filter(n=>n[e]!==t),this._invalidate(),this}remove(t){return this._src=this._src.filter((e,n)=>!t(e,n)),this._invalidate(),this}getSource(){return this._src}},q=class{client;data;listeners;subscribed;_unsubscribers;_fetching;_batchPending;_engines;_trackingIds;constructor(t){return this.client=t,this.data=new Map,this.listeners=new Set,this.subscribed=new Set,this._unsubscribers=new Map,this._fetching=new Set,this._batchPending=!1,this._engines=new Map,this._trackingIds=new Map,new Proxy(this,{get:(e,n)=>{if(n in e)return e[n];if(typeof n=="string")return this._getCollection(n)}})}_getCollection(t){if(!this.data.has(t)){let e=new O([]);this._engines.set(t,e);let n={_rawItems:[],items:[],loading:!0,error:null,success:!1,_filter:null,_sort:null,where:s=>(n._filter=s,this._applyTransform(n,e),n),orderBy:(s,i="asc")=>(n._sort={key:s,direction:i},this._applyTransform(n,e),n),reset:()=>(n._filter=null,n._sort=null,e.clearFilters(),this._applyTransform(n,e),n),search:(s,i)=>(e.search(s,i),this._applyTransform(n,e),n),filter:(s,i)=>(e.filter(s,i),this._applyTransform(n,e),n),range:(s,i,o)=>(e.range(s,i,o),this._applyTransform(n,e),n),sort:(s,i=!0)=>(e.sort(s,i),this._applyTransform(n,e),n),clearFilters:()=>(e.clearFilters(),this._applyTransform(n,e),n),page:(s=1,i=10)=>e.page(s,i),add:s=>(e.add(s),n._rawItems=e.getSource(),this._applyTransform(n,e),n),updateById:(s,i,o="id")=>(e.updateById(s,i,o),n._rawItems=e.getSource(),this._applyTransform(n,e),n),deleteById:(s,i="id")=>(e.removeById(s,i),n._rawItems=e.getSource(),this._applyTransform(n,e),n),optimisticDelete:async(s,i,o="id")=>{let f=[...n._rawItems];e.removeById(s,o),n._rawItems=e.getSource(),this._applyTransform(n,e);try{await i()}catch(A){throw e.setSource(f),n._rawItems=f,this._applyTransform(n,e),A}},optimisticUpdate:async(s,i,o,f="id")=>{let A=[...n._rawItems];e.updateById(s,i,f),n._rawItems=e.getSource(),this._applyTransform(n,e);try{await o()}catch(v){throw e.setSource(A),n._rawItems=A,this._applyTransform(n,e),v}},trackStart:s=>(this._trackStart(t,s),n),trackEnd:s=>(this._trackEnd(t,s),n),isLoading:s=>this._isTracking(t,s),get length(){return e.length},get total(){return e.total}};this.data.set(t,n),this._fetchAndSync(t)}return this.data.get(t)}_applyTransform(t,e){let n=e?e.get():[...t._rawItems||[]];if(t._filter&&(n=n.filter(t._filter)),t._sort){let{key:s,direction:i}=t._sort;n=[...n].sort((o,f)=>o[s]===f[s]?0:(o[s]>f[s]?1:-1)*(i==="asc"?1:-1))}t.items=n,this._batchNotify()}_batchNotify(){if(typeof process<"u",this._batchPending)return;this._batchPending=!0,(typeof queueMicrotask<"u"?queueMicrotask:e=>Promise.resolve().then(e))(()=>{this._batchPending=!1,this._notify()})}async _fetchAndSync(t,e=0){if(this._fetching.has(t))return;this._fetching.add(t);let n=this.data.get(t),s=this._engines.get(t);try{let i=await this.client.api.get(`/${t.toLowerCase()}`),o=Array.isArray(i)?i:i?.data??[];if(n._rawItems=o,n.loading=!1,n.success=!0,n.error=null,s.setSource(o),this._applyTransform(n,s),!this.subscribed.has(t)){let f=v=>{this._handleRemoteUpdate(t,v)},A=()=>{this.client.unsubscribe(`db:sync/${t.toLowerCase()}`,f)};this.client.subscribe(`db:sync/${t.toLowerCase()}`,f),this._unsubscribers.set(t,A),this.subscribed.add(t)}}catch(i){if(n.loading=!1,n.success=!1,n.error=i?.data?.error||i?.message||"Fetch failed",this._batchNotify(),e<3){let o=Math.pow(2,e)*1e3;this.client.options?.debug&&console.warn(`[Dolphin Store] Retrying "${t}" in ${o}ms (attempt ${e+1}/3)`),setTimeout(()=>{this._fetching.delete(t),this._fetchAndSync(t,e+1)},o);return}}finally{(e>=3||!n.error)&&this._fetching.delete(t)}}_handleRemoteUpdate(t,e){let n=this.data.get(t);if(!n)return;let s=this._engines.get(t);s?s.total!==(n._rawItems||[]).length&&s.setSource(n._rawItems||[]):(s=new O(n._rawItems||[]),this._engines.set(t,s));let{type:i,data:o}=e;if(i==="create")s.push(o);else if(i==="update"){let f=o.id!=null?"id":"_id";s.updateById(o[f],o,f)}else i==="delete"&&(o.id!=null?s.removeById(o.id,"id"):o._id!=null&&s.removeById(o._id,"_id"));n._rawItems=s.getSource(),this._applyTransform(n,s)}_trackStart(t,e){this._trackingIds.has(t)||this._trackingIds.set(t,new Set),this._trackingIds.get(t).add(e),this._batchNotify()}_trackEnd(t,e){this._trackingIds.get(t)?.delete(e),this._batchNotify()}_isTracking(t,e){return this._trackingIds.get(t)?.has(e)??!1}subscribe(t){return this.listeners.add(t),()=>this.listeners.delete(t)}getSnapshot(t){return this.data.get(t)||{items:[],loading:!1,error:null,success:!1}}_notify(){this.listeners.forEach(t=>{try{t()}catch{}})}destroy(){this._unsubscribers.forEach(t=>{try{t()}catch{}}),this._unsubscribers.clear(),this.subscribed.clear(),this.listeners.clear(),this.data.clear(),this._engines.clear(),this._trackingIds.clear(),this._fetching.clear()}};var M=class{host;httpUrl;deviceId;options;socket;storage;accessToken;api;auth;store;handlers;signalHandlers;fileHandlers;_offlineQueue;reconnectAttempts;_reconnectTimer;_attachedListeners;constructor(t="",e="",n={}){!t&&typeof window<"u"&&(t=window.location.host);let s="http:";t.startsWith("https://")?s="https:":t.startsWith("http://")?s="http:":typeof window<"u"&&(s=window.location.protocol),this.host=(t||"localhost").replace(/\/$/,"").replace(/^https?:\/\//,""),this.httpUrl=`${s}//${this.host}`,this.deviceId=e||(typeof crypto<"u"&&typeof crypto.randomUUID=="function"?"web_"+crypto.randomUUID().replace(/-/g,"").slice(0,8):"web_"+Math.random().toString(36).slice(2,10)),this.options={timeout:15e3,chunkSize:65536,maxReconnect:5,autoRefreshToken:!0,debug:!1,methodSpoofing:!1,routerViewport:"main, #viewport, body",routerTransitions:!0,...n},this.socket=null,this.storage=typeof localStorage<"u"?localStorage:{getItem:()=>null,setItem:()=>{},removeItem:()=>{}},this.accessToken=this.storage.getItem("dolphin_token"),this.api=new N(this),this.auth=new R(this),this.store=new q(this),this.handlers=new Map,this.signalHandlers=new Set,this.fileHandlers=new Set,this._offlineQueue=[],this.reconnectAttempts=0,this._reconnectTimer=null,this._attachedListeners=[],typeof window<"u"&&typeof this._initDOMBinding=="function"&&this._initDOMBinding(),typeof this._initOffline=="function"&&this._initOffline(),typeof this._initA11y=="function"&&this._initA11y(),typeof this._initI18n=="function"&&this._initI18n(),typeof this._initDragDrop=="function"&&this._initDragDrop(),typeof this._initCollab=="function"&&this._initCollab()}setToken(t){this.accessToken=t,t?this.storage.setItem("dolphin_token",t):this.storage.removeItem("dolphin_token")}async connect(){return this.socket&&(this.socket.readyState===WebSocket.OPEN||this.socket.readyState===WebSocket.CONNECTING)?Promise.resolve():new Promise((t,e)=>{let s=`${this.httpUrl.startsWith("https")?"wss:":"ws:"}//${this.host}/realtime?deviceId=${this.deviceId}`;console.log(`[Dolphin] Connecting to ${s}...`),this.socket=new WebSocket(s),this.socket.onopen=()=>{console.log(`[Dolphin] Connected as "${this.deviceId}" \u{1F42C}`),this.reconnectAttempts=0,this._flushOfflineQueue(),t()},this.socket.onmessage=i=>this._handleMessage(i.data),this.socket.onclose=()=>{console.warn("[Dolphin] Connection closed"),this._maybeReconnect()},this.socket.onerror=i=>{console.error("[Dolphin] WebSocket error:",i),e(i)}})}disconnect(){this._reconnectTimer!==null&&(clearTimeout(this._reconnectTimer),this._reconnectTimer=null),this.socket&&(this.socket.onclose=null,this.socket.close(),this.socket=null),typeof this._collabCleanup=="function"&&this._collabCleanup(),this.cleanupDomListeners()}_handleMessage(t){try{let e=JSON.parse(t);this.options.debug&&console.log("%c\u{1F4E5} [Dolphin WS Incoming]:","color: #eab308; font-weight: bold;",e),e.type&&e.from&&(e.to===this.deviceId||e.to==="all")&&(e.msgId&&e.type!=="ACK"&&this._sendAck(e.from,e.msgId),this.signalHandlers.forEach(n=>n(e))),e.type==="FILE_AVAILABLE"&&this.fileHandlers.forEach(n=>n(e)),e.type==="FILE_CHUNK"&&(this.saveFileProgress(e.fileId,e.chunkIndex),this._dispatch("file:chunk",e),this._dispatch(`file:chunk/${e.fileId}`,e)),e.type==="FILE_UPLOAD_ACK"&&this._dispatch(`file:upload:ack/${e.fileId}`,e),e.type==="PULL_RESPONSE"&&(this._dispatch("pull:response",e.payload,e.topic),this._dispatch(`pull:response/${e.topic}`,e.payload,e.topic)),e.topic&&e.payload!==void 0&&this.handlers.forEach((n,s)=>{this._matchTopic(s,e.topic)&&n.forEach(i=>i(e.payload,e.topic))})}catch{this._dispatch("raw",t)}}_dispatch(t,e,n){let s=this.handlers.get(t);s&&s.forEach(i=>i(e,n||t))}_sendRaw(t){this.options.debug&&console.log("%c\u{1F4E4} [Dolphin WS Outgoing]:","color: #8b5cf6; font-weight: bold;",t);let e=typeof t=="string"?t:JSON.stringify(t);this.socket&&this.socket.readyState===WebSocket.OPEN?this.socket.send(e):this._offlineQueue.length<100&&this._offlineQueue.push(e)}_flushOfflineQueue(){for(;this._offlineQueue.length>0;){let t=this._offlineQueue.shift();this.socket&&this.socket.readyState===WebSocket.OPEN&&this.socket.send(t)}}_sendAck(t,e){this._sendRaw({type:"ACK",from:this.deviceId,to:t,data:{ackId:e},timestamp:Date.now()})}_matchTopic(t,e){if(t===e||t==="#")return!0;let n=t.split("/"),s=e.split("/");if(n.length!==s.length&&!t.includes("#"))return!1;for(let i=0;i<n.length;i++){if(n[i]==="#")return!0;if(n[i]!=="+"&&n[i]!==s[i])return!1}return n.length===s.length}_maybeReconnect(){if(this.reconnectAttempts<this.options.maxReconnect){this.reconnectAttempts++;let t=Math.pow(2,this.reconnectAttempts)*1e3;console.log(`[Dolphin] Reconnecting in ${t/1e3}s (attempt ${this.reconnectAttempts})...`),this._reconnectTimer=setTimeout(()=>{this._reconnectTimer=null,this.connect().catch(()=>{})},t)}else console.error("[Dolphin] Max reconnect attempts reached.")}subscribe(t,e){this.handlers.has(t)||(this.handlers.set(t,new Set),this._sendRaw({type:"sub",topic:t})),this.handlers.get(t).add(e)}unsubscribe(t,e){if(this.handlers.has(t)){let n=this.handlers.get(t);n.delete(e),n.size===0&&(this.handlers.delete(t),this._sendRaw({type:"unsub",topic:t}))}}publish(t,e){this._sendRaw({topic:t,payload:e})}pubPush(t,e){this._sendRaw({type:"pub",topic:t,payload:e})}subPull(t,e=10){this._sendRaw({type:"PULL_REQUEST",topic:t,count:e})}async pubFile(t,e,n="",s){let i;e instanceof Blob?i=await e.arrayBuffer():e instanceof ArrayBuffer?i=e:i=e.buffer||e;let o=new Uint8Array(i),f=this.options.chunkSize,A=Math.ceil(o.length/f);this._sendRaw({type:"FILE_UPLOAD_START",fileId:t,name:n,size:o.length,totalChunks:A,chunkSize:f});for(let v=0;v<A;v++){let D=o.slice(v*f,(v+1)*f),k=this._uint8ToBase64(D);this._sendRaw({type:"FILE_UPLOAD_CHUNK",fileId:t,chunkIndex:v,totalChunks:A,data:k}),s&&s(Math.round((v+1)/A*100)),v%10===0&&await new Promise($=>setTimeout($,0))}this._sendRaw({type:"FILE_UPLOAD_DONE",fileId:t})}_uint8ToBase64(t){let e="";for(let n=0;n<t.length;n++)e+=String.fromCharCode(t[n]);return typeof btoa<"u"?btoa(e):Buffer.from(e,"binary").toString("base64")}subFile(t,e=0){this._sendRaw({type:"FILE_REQUEST",fileId:t,startChunk:e})}resumeFile(t){let e=parseInt(this.storage.getItem(`dolphin_file_${t}`)||"-1");this.subFile(t,e+1)}saveFileProgress(t,e){this.storage.setItem(`dolphin_file_${t}`,e.toString())}onSignal(t){this.signalHandlers.add(t)}offSignal(t){this.signalHandlers.delete(t)}onFileAvailable(t){this.fileHandlers.add(t)}offFileAvailable(t){this.fileHandlers.delete(t)}addDomListener(t,e,n){t&&(t.addEventListener(e,n),this._attachedListeners=this._attachedListeners||[],this._attachedListeners.push({target:t,event:e,cb:n}))}cleanupDomListeners(){this._attachedListeners&&(this._attachedListeners.forEach(({target:t,event:e,cb:n})=>{try{t.removeEventListener(e,n)}catch{}}),this._attachedListeners=[])}};function j(w){let t=new Map;function e(y){return y.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function n(y,d){if(!(!d||typeof d!="object"))try{let h=new Proxy(d,{has(a,c){return!0},get(a,c){if(typeof c=="string"){if(c in a)return a[c];if(typeof globalThis<"u"&&c in globalThis)return globalThis[c];if(typeof window<"u"&&c in window)return window[c]}}});return new Function("ctx",`with(ctx) { return (${y}); }`)(h)}catch{return d[y]}}function s(y,d){let h=[],r="",a=!1,c=!1,p=!1,l=0;for(let g=0;g<y.length;g++){let u=y[g];u==="'"&&!c&&!p?a=!a:u==='"'&&!a&&!p?c=!c:u==="`"&&!a&&!c?p=!p:u==="("||u==="["||u==="{"?!a&&!c&&!p&&l++:(u===")"||u==="]"||u==="}")&&!a&&!c&&!p&&l--,u===d&&!a&&!c&&!p&&l===0?(h.push(r),r=""):r+=u}return h.push(r),h}function i(y){let d=!1,h=!1,r=!1,a=0;for(let c=0;c<y.length;c++){let p=y[c];if(p==="'"&&!h&&!r?d=!d:p==='"'&&!d&&!r?h=!h:p==="`"&&!d&&!h?r=!r:p==="("||p==="["||p==="{"?!d&&!h&&!r&&a++:(p===")"||p==="]"||p==="}")&&!d&&!h&&!r&&a--,p===":"&&!d&&!h&&!r&&a===0)return[y.slice(0,c),y.slice(c+1)]}return null}function o(y){let d=y.getAttribute("data-rt-template");if(!d)return null;if(typeof document<"u"&&!d.includes("<"))try{let h=document.querySelector(d);if(h)return h.innerHTML}catch{}return d}function f(y,d){if(!y.includes("{#if")&&!y.includes("{#each")){let h=y;for(let r in d){let a=r.replace(/[.*+?^$${}()|[\]\\]/g,"\\$&");h=h.replace(new RegExp("\\{\\{"+a+"\\}}","g"),d[r]!==void 0&&d[r]!==null?d[r]:"")}return h=h.replace(/\{\{([\s\S]*?)\}\}/g,(r,a)=>{let c=a.trim();if(!c)return"";if(/^[a-zA-Z_$][a-zA-Z0-9_$]*(?:\??\.[a-zA-Z_$][a-zA-Z0-9_$]*)+$/.test(c)){let p=c.split(/\??\./),l=d;for(let g of p){if(l==null){l=void 0;break}l=l[g]}return l??""}return r}),h}try{let h=m=>m.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/\t/g,"\\t"),r=`let out = "";
2
+ `,a=0,c=/(\{\{([\s\S]*?)\}\}|\{#if\s+([\s\S]*?)\}|\{:else\s+if\s+([\s\S]*?)\}|\{:else\}|\{\/if\}|\{#each\s+([\s\S]*?)\s+as\s+([a-zA-Z_$][a-zA-Z0-9_$]*)(?:\s*,\s*([a-zA-Z_$][a-zA-Z0-9_$]*))?\}|\{\/each\}|\{([^{}]+?)\})/g,p=[],l;for(;(l=c.exec(y))!==null;){let m=y.slice(a,l.index);m&&(r+=`out += "${h(m)}";
3
+ `);let _=l[0];if(_.startsWith("{{")){let T=l[2];r+=`out += (${T} !== undefined && ${T} !== null ? ${T} : "");
4
+ `}else if(_.startsWith("{#if")){let T=l[3];r+=`if (${T}) {
5
+ `}else if(_.startsWith("{:else if")){let T=l[4];r+=`} else if (${T}) {
6
+ `}else if(_.startsWith("{:else}"))r+=`} else {
7
+ `;else if(_.startsWith("{/if}"))r+=`}
8
+ `;else if(_.startsWith("{#each")){let T=l[5],C=l[6],E=l[7];p.push({indexVar:E}),r+=`if (typeof ${T} !== "undefined" && ${T} !== null && Array.isArray(${T})) {
9
+ `,E&&(r+=` let ${E} = 0;
10
+ `),r+=` for (let ${C} of ${T}) {
11
+ `}else if(_.startsWith("{/each}")){let T=p.pop();T&&T.indexVar&&(r+=` ${T.indexVar}++;
12
+ `),r+=` }
13
13
  }
14
- `}else if(_.startsWith("{")){let S=l[8];S&&(n+=`out += (${S} !== undefined && ${S} !== null ? ${S} : "");
15
- `)}o=c.lastIndex}let g=h.slice(o);g&&(n+=`out += "${f(g)}";
16
- `),n+=`return out;
14
+ `}else if(_.startsWith("{")){let T=l[8];T&&(r+=`out += (${T} !== undefined && ${T} !== null ? ${T} : "");
15
+ `)}a=c.lastIndex}let g=y.slice(a);g&&(r+=`out += "${h(g)}";
16
+ `),r+=`return out;
17
17
  `;let u=`
18
18
  with (context) {
19
19
  try {
20
- ${n}
20
+ ${r}
21
21
  } catch (innerErr) {
22
22
  console.warn('[Dolphin Template Eval Warning]:', innerErr);
23
23
  return '';
24
24
  }
25
25
  }
26
- `,A=d;return typeof Proxy<"u"&&d!==null&&typeof d=="object"&&(A=new Proxy(d,{has(m,_){return typeof _!="symbol"},get(m,_){if(_!==Symbol.unscopables){if(_ in m)return m[_];if(typeof globalThis<"u"&&_ in globalThis)return globalThis[_];if(typeof window<"u"&&_ in window)return window[_]}}})),new Function("context",u)(A)}catch(f){console.error("[Dolphin Template Compiler Error]:",f);let n=h;for(let o in d){let c=o.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");n=n.replace(new RegExp(`\\{\\{${c}\\}\\}`,"g"),d[o]!==void 0&&d[o]!==null?d[o]:"")}return n}}function T(h){if(typeof document>"u")return h;try{let d=new DOMParser,n=/<\s*(?:body|html)\b/i.test(h)?h:`<body>${h}</body>`,c=d.parseFromString(n,"text/html").body,p=l=>{let g=l.tagName.toLowerCase();if(["script","iframe","object","embed","link","style","meta","applet","svg"].includes(g)){l.parentNode?.removeChild(l);return}let u=l.attributes;for(let A=u.length-1;A>=0;A--){let b=u[A].name.toLowerCase(),m=u[A].value.toLowerCase();(b.startsWith("on")||["src","href","data"].includes(b)&&(m.includes("javascript:")||m.includes("data:text/html")))&&l.removeAttribute(u[A].name)}Array.from(l.children).forEach(p)};return Array.from(c.children).forEach(p),c.innerHTML}catch{return h}}function E(h,d){if(h.nodeType!==d.nodeType){h.parentNode?.replaceChild(d.cloneNode(!0),h);return}if(h.nodeType===Node.TEXT_NODE){h.textContent!==d.textContent&&(h.textContent=d.textContent);return}if(h.nodeType===Node.ELEMENT_NODE){let f=h,n=d;if(f.tagName!==n.tagName){f.parentNode?.replaceChild(n.cloneNode(!0),f);return}let o=f.attributes,c=n.attributes;for(let b=o.length-1;b>=0;b--){let m=o[b].name;n.hasAttribute(m)||f.removeAttribute(m)}for(let b=0;b<c.length;b++){let m=c[b].name,_=c[b].value;f.getAttribute(m)!==_&&f.setAttribute(m,_)}f.tagName==="INPUT"||f.tagName==="TEXTAREA"?(f.value!==n.value&&(f.value=n.value),f.checked!==n.checked&&(f.checked=n.checked)):f.tagName==="SELECT"&&f.value!==n.value&&(f.value=n.value);let p=Array.from(f.childNodes),l=Array.from(n.childNodes),g=p.length,u=l.length,A=Math.max(g,u);for(let b=0;b<A;b++)b>=g?f.appendChild(l[b].cloneNode(!0)):b>=u?f.removeChild(p[b]):E(p[b],l[b])}}function D(h,d){if(typeof document>"u")return;let f=document.createElement(h.tagName);f.innerHTML=d;let n=Array.from(h.childNodes),o=Array.from(f.childNodes),c=n.length,p=o.length,l=Math.max(c,p);for(let g=0;g<l;g++)g>=c?h.appendChild(o[g].cloneNode(!0)):g>=p?h.removeChild(n[g]):E(n[g],o[g])}let k=new Map,M=!1;function x(h,d){k.set(h,d),M||(M=!0,(typeof requestAnimationFrame<"u"?requestAnimationFrame:n=>setTimeout(n,0))(()=>{k.forEach((n,o)=>{o.isConnected!==!1&&D(o,n)}),k.clear(),M=!1}))}w.setStoreState=function(h,d,f,n){this.uiStores=this.uiStores||new Map,this.uiStores.has(h)||this.uiStores.set(h,{});let o=this.uiStores.get(h);o[d]=f,this.options.debug&&console.log("%c\u{1F4BE} [Dolphin Store Update]:","color: #ec4899; font-weight: bold;",`${h}.${d}`,"=",f),typeof document<"u"&&document.querySelectorAll(`[data-store-read="${h}.${d}"]`).forEach(p=>{p!==n&&(p.tagName==="INPUT"||p.tagName==="TEXTAREA"?p.type==="checkbox"?p.checked=!!f:p.value=f??"":p.textContent=f??"")}),this.publish(`store/${h}`,o),typeof this._updateDOM=="function"&&this._updateDOM(`store/${h}`,o)},w.getStoreState=function(h,d){this.uiStores=this.uiStores||new Map;let f=this.uiStores.get(h);return f?f[d]:void 0},w._scanStoreBinds=function(){if(typeof document>"u")return;document.querySelectorAll("dolphin-store").forEach(n=>{if(typeof n.getAttribute!="function")return;let o=n.getAttribute("name")||n.getAttribute("data-store");if(!o)return;let c=n.children&&n.children.length>0;if(c?typeof n.setAttribute=="function"&&(n.setAttribute("data-rt-bind",`store/${o}`),n.setAttribute("data-rt-type","context")):n.style&&(n.style.display="none"),!c){let l=n.textContent?n.textContent.trim():"";if(l&&l.startsWith("{"))try{let g=JSON.parse(l);g&&typeof g=="object"&&Object.keys(g).forEach(u=>{this.setStoreState(o,u,g[u])})}catch(g){console.error(`[Dolphin Store Init Error] Failed to parse JSON inside <dolphin-store name="${o}">:`,g)}}let p=n.getAttribute("template");if(n.attributes){let l=["name","data-store","style","data-rt-bind","data-rt-type","template"];Array.from(n.attributes).forEach(g=>{if(!l.includes(g.name)){let u=g.value;u==="true"?u=!0:u==="false"?u=!1:u==="null"?u=null:!isNaN(Number(u))&&u.trim()!==""&&(u=Number(u)),this.setStoreState(o,g.name,u)}})}if(p&&!c&&n.parentNode&&typeof document<"u"){let l=`_ds_${o}_${p.replace(/[^a-z0-9]/gi,"_")}`,g=document.querySelector(`[data-ds-wired="${l}"]`);if(g||(g=document.createElement("div"),g.setAttribute("data-rt-bind",`store/${o}`),g.setAttribute("data-rt-template",p),g.setAttribute("data-ds-wired",l),n.parentNode.insertBefore(g,n.nextSibling)),typeof this._updateDOM=="function"){this.uiStores=this.uiStores||new Map;let u=this.uiStores.get(o)||{};this._updateDOM(`store/${o}`,u)}}if(c&&typeof this._updateDOM=="function"){this.uiStores=this.uiStores||new Map;let l=this.uiStores.get(o)||{};this._updateDOM(`store/${o}`,l)}}),document.querySelectorAll("[data-store-write]").forEach(n=>{let o=n.getAttribute("data-store-write");if(o){let c=o.split(".");if(c.length===2){let p=c[0],l=c[1],g=n.type==="checkbox"?n.checked:n.value;this.uiStores=this.uiStores||new Map,this.uiStores.has(p)||this.uiStores.set(p,{});let u=this.uiStores.get(p);u[l]===void 0&&(u[l]=g)}}}),document.querySelectorAll("[data-store-read]").forEach(n=>{let o=n.getAttribute("data-store-read");if(o){let c=o.split(".");if(c.length===2){let p=c[0],l=c[1],g=this.getStoreState(p,l);g!=null&&(n.tagName==="INPUT"||n.tagName==="TEXTAREA"?n.type==="checkbox"?n.checked=!!g:n.value=g:n.textContent=g)}}})},w.getClosestContext=function(h,d){let f=h;for(;f;){if(f._rtContext){let n=f._rtContext;return d?n[d]:n}f=f.parentElement||f.parentNode}return null},w._executeStoreAction=function(h,d){this.uiStores=this.uiStores||new Map;let f=d&&typeof this.getClosestContext=="function"?this.getClosestContext(d):null,n=new Proxy({},{has:(o,c)=>!0,get:(o,c)=>{if(typeof c=="string")return c==="log"?p=>{if(p===void 0){let l={};this.uiStores.forEach((g,u)=>{l[u]={...g}}),console.log("%c\u{1F4CA} [Dolphin All UI Stores]:","color: #06b6d4; font-weight: bold;",l)}else if(p&&typeof p=="object"&&p.__isStoreProxy__){let l=p.__storeName__,g=this.uiStores.get(l);console.log(`%c\u{1F4CA} [Dolphin Store: ${l}]:`,"color: #06b6d4; font-weight: bold;",g?{...g}:{})}else console.log("%c\u{1F4CA} [Dolphin Log]:","color: #06b6d4; font-weight: bold;",p)}:f&&f[c]!==void 0?f[c]:typeof globalThis<"u"&&c in globalThis?globalThis[c]:typeof window<"u"&&c in window?window[c]:new Proxy({},{get:(p,l)=>{if(l==="__storeName__")return c;if(l==="__isStoreProxy__")return!0;if(typeof l=="string")return this.getStoreState(c,l)},set:(p,l,g)=>typeof l=="string"?(this.setStoreState(c,l,g),!0):!1})}});try{new Function("ctx",`with(ctx) { ${h} }`)(n)}catch(o){console.error("%c[Dolphin Store Action Error]:","color: #ef4444; font-weight: bold;",o),d&&console.error("%cFailed Element:","color: #f97316; font-weight: bold;",d),console.error("%cFailed Expression:","color: #3b82f6; font-style: italic;",h)}},w._initDOMBinding=function(){if(this._domInitialized)return;this._domInitialized=!0;let h=["input","change","keyup","paste","blur"],d=new WeakMap;h.forEach(n=>{this.addDomListener(document,n,o=>{if(!o.target||!o.target.getAttribute)return;let c=o.target.getAttribute("data-store-write");if(c){let u=c.split(".");if(u.length===2){let A=u[0],b=u[1],m=o.target.type==="checkbox"?o.target.checked:o.target.value;this.setStoreState(A,b,m,o.target)}}let p=o.target.getAttribute("data-rt-validate"),l=o.target.name;if(p&&l&&typeof this.validateField=="function"){let u=o.target.closest("form"),A=u?Object.fromEntries(new FormData(u).entries()):{},b=this.validateField(o.target.value,p,A);b?(o.target.classList.add("invalid"),this.publish(`errors/${l}`,b)):(o.target.classList.remove("invalid"),this.publish(`errors/${l}`,""))}let g=o.target.getAttribute("data-rt-push");if(g){let u=o.target.getAttribute("data-rt-debounce"),A=u?parseInt(u,10):0,b=()=>{let m={name:o.target.name,value:o.target.value};this.pubPush(g,m)};if(A>0){d.has(o.target)&&clearTimeout(d.get(o.target));let m=setTimeout(b,A);d.set(o.target,m)}else b()}})}),this.addDomListener(document,"submit",async n=>{if(!n.target||!n.target.getAttribute)return;let o=n.target.getAttribute("data-rt-submit"),c=n.target.getAttribute("data-api-submit");if(o||c){n.target.querySelectorAll("[name]").forEach(m=>{let _=m.name;_&&(this.publish(`errors/${_}`,""),m.classList.remove("invalid"))});let l=n.target.querySelectorAll("[data-rt-validate]"),g=!0;if(l.length>0&&typeof this.validateField=="function"){let m=Object.fromEntries(new FormData(n.target).entries());l.forEach(_=>{let S=_.getAttribute("data-rt-validate"),C=_.name;if(S&&C){let v=this.validateField(_.value,S,m);v&&(g=!1,_.classList.add("invalid"),this.publish(`errors/${C}`,v))}})}if(!g){n.preventDefault(),n.stopPropagation();return}n.preventDefault();let u=this.getClosestContext(n.target)||{},A=new FormData(n.target),b=Object.fromEntries(A.entries());if(o){let m=o;for(let _ in u){let S=e(_);m=m.replace(new RegExp(`\\{\\{${S}\\}\\}`,"g"),u[_]!==void 0&&u[_]!==null?u[_]:"")}this.publish(m,b)}else if(c){let m=c;for(let v in u){let L=e(v);m=m.replace(new RegExp(`\\{\\{${L}\\}\\}`,"g"),u[v]!==void 0&&u[v]!==null?u[v]:"")}let _=m.trim().split(" "),S=_.length>1?_[0].toUpperCase():"POST",C=_.length>1?_[1]:_[0];b._method&&(S=String(b._method).toUpperCase());try{let v=await this.api.request(S,C,b),L=n.target.getAttribute("data-api-result");L&&this._updateDOM(L,v);let P=n.target.getAttribute("data-api-redirect");P&&(window.location.href=P),n.target.hasAttribute("data-api-reload")&&window.location.reload()}catch(v){console.error("[Dolphin] API Submit Error:",v)}}}}),["click","change","submit","input","keydown","keyup","dblclick","focus","blur","mouseenter","mouseleave"].forEach(n=>{this.addDomListener(document,n,async o=>{if(!o.target||!o.target.closest)return;let c=o.target.closest(`[data-rt-${n}]`),p=o.target.closest(`[data-api-${n}]`);if(c){n==="submit"&&o.preventDefault();let g=c.getAttribute(`data-rt-${n}`),u=c.getAttribute("data-rt-payload"),A=this.getClosestContext(c)||{},b={};if(u){let m=u;for(let _ in A){let S=e(_);m=m.replace(new RegExp(`\\{\\{${S}\\}\\}`,"g"),A[_]!==void 0&&A[_]!==null?A[_]:"")}try{b=JSON.parse(m)}catch{b={}}}this.publish(g,b)}if(p){n==="submit"&&o.preventDefault();let g=p.getAttribute(`data-api-${n}`),u=p.getAttribute("data-api-payload"),A=this.getClosestContext(p)||{},b=g.trim().split(" "),m=b.length>1?b[0].toUpperCase():"POST",_=b.length>1?b[1]:b[0],S=null;if(u){let C=u;for(let v in A){let L=e(v);C=C.replace(new RegExp(`\\{\\{${L}\\}\\}`,"g"),A[v]!==void 0&&A[v]!==null?A[v]:"")}try{S=JSON.parse(C)}catch{S=null}}try{let C=await this.api.request(m,_,S),v=p.getAttribute("data-api-result");v&&this._updateDOM(v,C);let L=p.getAttribute("data-api-redirect");L&&(window.location.href=L),p.hasAttribute("data-api-reload")&&window.location.reload()}catch(C){console.error(`[Dolphin] API ${n} Error:`,C)}}let l=o.target.closest(`[data-store-${n}]`);if(l){n==="submit"&&o.preventDefault();let g=l.getAttribute(`data-store-${n}`);g&&this._executeStoreAction(g,l)}})}),this.subscribe("#",(n,o)=>{this._updateDOM(o,n)}),this._scanAndFetchAPIBinds(),this._scanStoreBinds(),this._resolveImports(),this._initSPARouter()},w._scanAndFetchAPIBinds=async function(){if(typeof document>"u")return;let h=document.querySelectorAll("[data-api-get]");for(let d of Array.from(h)){let f=d.getAttribute("data-api-get");if(f&&!(typeof d.hasAttribute=="function"&&d.hasAttribute("data-api-initialized"))){typeof d.setAttribute=="function"&&d.setAttribute("data-api-initialized","true");try{let n=await this.api.get(f),o=d.getAttribute("data-api-store");if(o){let p=o.split(".");p.length===2&&this.setStoreState(p[0],p[1],n)}let c=d.getAttribute("data-rt-bind");if(c&&!o)this._updateDOM(c,n);else if(!o){let p=a(d);if(p&&typeof n=="object"&&n!==null){let l=this._applyDeclarativeDirectives(d,n);if(Array.isArray(l)){let g="";for(let u of l)g+=y(p,u);x(d,g)}else x(d,y(p,l))}else if(d.tagName==="INPUT"||d.tagName==="TEXTAREA")d.value=typeof n=="object"?n.value!==void 0?n.value:"":n;else{let l=typeof n=="object"?n.html||n.text||JSON.stringify(n):String(n);d.innerHTML=T(l)}}}catch(n){console.error("[Dolphin] API Get Error:",n)}}}},w._applyDeclarativeDirectives=function(h,d){let f=d;if(typeof d=="object"&&d!==null){let n=o=>{let c=[...o],p=h.getAttribute("data-rt-filter");if(p){let u=p.split("==");if(u.length===2){let A=u[0].trim(),b=u[1].trim(),m,_=b.split(".");_.length===2?m=this.getStoreState(_[0],_[1]):m=d[b]!==void 0?d[b]:this.getStoreState("app",b),m!=null&&m!==""&&(c=c.filter(S=>S[A]===m))}}let l=h.getAttribute("data-rt-search");if(l){let u=l.split("==");if(u.length===2){let A=u[0].trim(),b=u[1].trim(),m,_=b.split(".");if(_.length===2?m=this.getStoreState(_[0],_[1]):m=d[b]!==void 0?d[b]:this.getStoreState("app",b),m!=null&&m!==""){let S=String(m).toLowerCase();c=c.filter(C=>{let v=C[A];return v!=null&&String(v).toLowerCase().includes(S)})}}}let g=h.getAttribute("data-rt-sort");if(g){let u,A=g.split(".");if(A.length===2?u=this.getStoreState(A[0],A[1]):u=d[g]!==void 0?d[g]:this.getStoreState("app",g),u&&u!=="")if(u==="popular")c.sort((b,m)=>{let _=b.rating?.rate||b.rate||0;return(m.rating?.rate||m.rate||0)-_});else{let b="",m="asc";u.endsWith("-low")||u.endsWith("-asc")?(b=u.replace("-low","").replace("-asc",""),m="asc"):(u.endsWith("-high")||u.endsWith("-desc"))&&(b=u.replace("-high","").replace("-desc",""),m="desc"),b&&c.sort((_,S)=>{let C=(Y,tt)=>tt.split(".").reduce((W,et)=>W&&W[et],Y),v=C(_,b),L=C(S,b);if(v===void 0&&(v=_[b]),L===void 0&&(L=S[b]),typeof v=="string"&&typeof L=="string")return m==="asc"?v.localeCompare(L):L.localeCompare(v);let P=Number(v),q=Number(L);return!isNaN(P)&&!isNaN(q)?m==="asc"?P-q:q-P:0})}}return c};if(Array.isArray(d))f=n(d);else{let o="";for(let c in d)if(Array.isArray(d[c])){o=c;break}if(o){let c=n(d[o]);f={...d,[o]:c}}}}return f},w._updateDOM=function(h,d){if(typeof document>"u")return;document.querySelectorAll(`[data-rt-bind="${h}"]`).forEach(n=>{let o=this._applyDeclarativeDirectives(n,d);if(n.getAttribute("data-rt-type")==="context"&&typeof o=="object"&&o!==null){n._rtContext=o;let p=l=>{if(l.hasAttribute("data-rt-text")){let g=l.getAttribute("data-rt-text");if(g){let u=i(g,o);u!=null&&(l.textContent=u)}}if(l.hasAttribute("data-rt-html")){let g=l.getAttribute("data-rt-html");if(g){let u=i(g,o);u!=null&&(l.innerHTML=T(u))}}if(l.hasAttribute("data-rt-attr")){let g=l.getAttribute("data-rt-attr");g&&s(g,",").forEach(u=>{let A=r(u);if(A){let b=A[0].trim(),m=A[1].trim();if(b&&m){let _=i(m,o);_!=null&&l.setAttribute(b,_)}}})}if(l.hasAttribute("data-rt-class")){let g=l.getAttribute("data-rt-class");g&&s(g,",").forEach(u=>{let A=r(u);if(A){let b=A[0].trim(),m=A[1].trim(),_=b.split(/\s+/).filter(Boolean);i(m,o)?_.forEach(S=>l.classList.add(S)):_.forEach(S=>l.classList.remove(S))}})}if(l.hasAttribute("data-rt-if")){let g=l.getAttribute("data-rt-if");g&&(i(g,o)?l.style.display="":l.style.display="none")}if(l.hasAttribute("data-rt-hide")){let g=l.getAttribute("data-rt-hide");g&&(i(g,o)?l.style.display="none":l.style.display="")}};p(n),n.querySelectorAll("[data-rt-text], [data-rt-html], [data-rt-attr], [data-rt-class], [data-rt-if], [data-rt-hide]").forEach(p);return}let c=a(n);if(c&&typeof o=="object"&&o!==null){if(Array.isArray(o)){let p="";for(let l of o)p+=y(c,l);x(n,p)}else x(n,y(c,o));return}if(n.tagName==="INPUT"||n.tagName==="TEXTAREA")n.value=typeof o=="object"?o.value!==void 0?o.value:"":o;else if(c)n.innerHTML=typeof o=="object"?o.html||o.text||JSON.stringify(o):String(o);else{let p=typeof o=="object"?o.html||o.text||JSON.stringify(o):String(o);n.innerHTML=T(p)}})},w._resolveImports=async function(h){if(typeof document>"u")return;let d=h||document.body||document;if(!d||typeof d.querySelectorAll!="function")return;let f=d.querySelectorAll("[data-import]");if(f.length===0)return;let n=async(c,p)=>{let l=c.getAttribute("data-import");if(!l)return;if(p.has(l)){console.warn(`[Dolphin Component Warning]: Circular import detected for "${l}". Skipping resolving.`),c.innerHTML=`<span style="color:red;font-weight:bold;">Circular import: ${l}</span>`;return}p.add(l);let g=l.indexOf("#"),u=g!==-1?l.substring(0,g):l,A=g!==-1?l.substring(g):null,b=t.get(u);b||(b=fetch(u).then(S=>{if(!S.ok)throw new Error(`HTTP ${S.status}`);return S.text()}),b.catch(()=>t.delete(u)),t.set(u,b));let m="";try{if(m=await b,A&&typeof DOMParser<"u"){let v=new DOMParser().parseFromString(m,"text/html").querySelector(A);v?m=v.outerHTML:(console.warn(`[Dolphin Component Warning]: Selector "${A}" not found in imported file "${u}".`),m=`<span style="color:orange;font-weight:bold;">Selector ${A} not found in ${u}</span>`)}}catch(S){console.error(`[Dolphin Component Error]: Failed to fetch component "${u}":`,S),m=`<span style="color:red;font-weight:bold;">Failed to import ${u}</span>`}c.innerHTML=T(m),c.removeAttribute("data-import");let _=c.querySelectorAll("[data-import]");if(_.length>0){let S=Array.from(_).map(C=>n(C,new Set(p)));await Promise.all(S)}this._scanStoreBinds(),this._scanAndFetchAPIBinds()},o=Array.from(f).map(c=>n(c,new Set));await Promise.all(o)},w._initSPARouter=function(){if(typeof window>"u"||typeof document>"u"||this._routerInitialized)return;this._routerInitialized=!0;let h=null,d=()=>{let o=(this.options.routerViewport||"main, #viewport, body").split(",").map(c=>c.trim());for(let c of o){let p=document.querySelector(c);if(p)return p}return document.body},f=async(n,o=!0)=>{try{this.options.debug&&console.log(`%c\u{1F6E3}\uFE0F [Dolphin Router]: Navigating to ${n}...`,"color: #3b82f6; font-weight: bold;"),h&&h.abort(),h=new AbortController;let c=h.signal,p=d();this.options.routerTransitions&&p&&(p.classList.add("dolphin-fade-out"),await new Promise(_=>setTimeout(_,150)));let l=await fetch(n,{signal:c});if(!l.ok)throw new Error(`HTTP ${l.status}`);let g=await l.text();h=null;let A=new DOMParser().parseFromString(g,"text/html");A.title&&(document.title=A.title);let b=A.querySelector(this.options.routerViewport||"main, #viewport, body"),m=d();b&&m?(m.innerHTML=b.innerHTML,Array.from(b.attributes).forEach(_=>{m.setAttribute(_.name,_.value)})):m&&(m.innerHTML=A.body.innerHTML),o&&window.history.pushState({dolphinSpa:!0,url:n},"",n),this.options.routerTransitions&&m&&(m.classList.remove("dolphin-fade-out"),m.classList.add("dolphin-fade-in"),setTimeout(()=>m.classList.remove("dolphin-fade-in"),300)),await this._resolveImports(m),this._scanStoreBinds(),this._scanAndFetchAPIBinds()}catch(c){if(c&&c.name==="AbortError")return;console.error("[Dolphin Router Error]: Failed to route page:",c),window.location.href=n}};if(this.addDomListener(document,"click",n=>{let o=n.target.closest("a");if(!o||!o.hasAttribute("data-spa")&&o.getAttribute("data-spa")!=="true")return;let c=o.getAttribute("href");!c||c.startsWith("#")||c.startsWith("javascript:")||c.startsWith("mailto:")||c.startsWith("tel:")||new URL(c,window.location.href).origin!==window.location.origin||(n.preventDefault(),f(c))}),this.addDomListener(window,"popstate",n=>{n.state&&n.state.dolphinSpa?f(n.state.url,!1):n.state===null&&f(window.location.pathname,!1)}),this.options.routerTransitions){let n=document.createElement("style");n.innerHTML=`
26
+ `,S=d;return typeof Proxy<"u"&&d!==null&&typeof d=="object"&&(S=new Proxy(d,{has(m,_){return typeof _!="symbol"},get(m,_){if(_!==Symbol.unscopables){if(_ in m)return m[_];if(typeof globalThis<"u"&&_ in globalThis)return globalThis[_];if(typeof window<"u"&&_ in window)return window[_]}}})),new Function("context",u)(S)}catch(h){console.error("[Dolphin Template Compiler Error]:",h);let r=y;for(let a in d){let c=a.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");r=r.replace(new RegExp(`\\{\\{${c}\\}\\}`,"g"),d[a]!==void 0&&d[a]!==null?d[a]:"")}return r}}function A(y){if(typeof document>"u")return y;try{let d=new DOMParser,r=/<\s*(?:body|html)\b/i.test(y)?y:`<body>${y}</body>`,c=d.parseFromString(r,"text/html").body,p=l=>{let g=l.tagName.toLowerCase();if(["script","iframe","object","embed","link","style","meta","applet","svg"].includes(g)){l.parentNode?.removeChild(l);return}let u=l.attributes;for(let S=u.length-1;S>=0;S--){let b=u[S].name.toLowerCase(),m=u[S].value.toLowerCase();(b.startsWith("on")||["src","href","data"].includes(b)&&(m.includes("javascript:")||m.includes("data:text/html")))&&l.removeAttribute(u[S].name)}Array.from(l.children).forEach(p)};return Array.from(c.children).forEach(p),c.innerHTML}catch{return y}}function v(y,d){if(y.nodeType!==d.nodeType){y.parentNode?.replaceChild(d.cloneNode(!0),y);return}if(y.nodeType===Node.TEXT_NODE){y.textContent!==d.textContent&&(y.textContent=d.textContent);return}if(y.nodeType===Node.ELEMENT_NODE){let h=y,r=d;if(h.tagName!==r.tagName){h.parentNode?.replaceChild(r.cloneNode(!0),h);return}let a=h.attributes,c=r.attributes;for(let b=a.length-1;b>=0;b--){let m=a[b].name;r.hasAttribute(m)||h.removeAttribute(m)}for(let b=0;b<c.length;b++){let m=c[b].name,_=c[b].value;h.getAttribute(m)!==_&&h.setAttribute(m,_)}h.tagName==="INPUT"||h.tagName==="TEXTAREA"?(h.value!==r.value&&(h.value=r.value),h.checked!==r.checked&&(h.checked=r.checked)):h.tagName==="SELECT"&&h.value!==r.value&&(h.value=r.value);let p=Array.from(h.childNodes),l=Array.from(r.childNodes),g=p.length,u=l.length,S=Math.max(g,u);for(let b=0;b<S;b++)b>=g?h.appendChild(l[b].cloneNode(!0)):b>=u?h.removeChild(p[b]):v(p[b],l[b])}}function D(y,d){if(typeof document>"u")return;let h=document.createElement(y.tagName);h.innerHTML=d;let r=Array.from(y.childNodes),a=Array.from(h.childNodes),c=r.length,p=a.length,l=Math.max(c,p);for(let g=0;g<l;g++)g>=c?y.appendChild(a[g].cloneNode(!0)):g>=p?y.removeChild(r[g]):v(r[g],a[g])}let k=new Map,$=!1;function I(y,d){k.set(y,d),$||($=!0,(typeof requestAnimationFrame<"u"?requestAnimationFrame:r=>setTimeout(r,0))(()=>{k.forEach((r,a)=>{a.isConnected!==!1&&D(a,r)}),k.clear(),$=!1}))}w.setStoreState=function(y,d,h,r){this.uiStores=this.uiStores||new Map,this.uiStores.has(y)||this.uiStores.set(y,{});let a=this.uiStores.get(y);a[d]=h,this.options.debug&&console.log("%c\u{1F4BE} [Dolphin Store Update]:","color: #ec4899; font-weight: bold;",`${y}.${d}`,"=",h),typeof document<"u"&&document.querySelectorAll(`[data-store-read="${y}.${d}"]`).forEach(p=>{p!==r&&(p.tagName==="INPUT"||p.tagName==="TEXTAREA"?p.type==="checkbox"?p.checked=!!h:p.value=h??"":p.textContent=h??"")}),this.publish(`store/${y}`,a),typeof this._updateDOM=="function"&&this._updateDOM(`store/${y}`,a)},w.getStoreState=function(y,d){this.uiStores=this.uiStores||new Map;let h=this.uiStores.get(y);return h?h[d]:void 0},w._scanStoreBinds=function(){if(typeof document>"u")return;document.querySelectorAll("dolphin-store").forEach(r=>{if(typeof r.getAttribute!="function")return;let a=r.getAttribute("name")||r.getAttribute("data-store");if(!a)return;let c=r.children&&r.children.length>0;if(c?typeof r.setAttribute=="function"&&(r.setAttribute("data-rt-bind",`store/${a}`),r.setAttribute("data-rt-type","context")):r.style&&(r.style.display="none"),!c){let l=r.textContent?r.textContent.trim():"";if(l&&l.startsWith("{"))try{let g=JSON.parse(l);g&&typeof g=="object"&&Object.keys(g).forEach(u=>{this.setStoreState(a,u,g[u])})}catch(g){console.error(`[Dolphin Store Init Error] Failed to parse JSON inside <dolphin-store name="${a}">:`,g)}}let p=r.getAttribute("template");if(r.attributes){let l=["name","data-store","style","data-rt-bind","data-rt-type","template"];Array.from(r.attributes).forEach(g=>{if(!l.includes(g.name)){let u=g.value;u==="true"?u=!0:u==="false"?u=!1:u==="null"?u=null:!isNaN(Number(u))&&u.trim()!==""&&(u=Number(u)),this.setStoreState(a,g.name,u)}})}if(p&&!c&&r.parentNode&&typeof document<"u"){let l=`_ds_${a}_${p.replace(/[^a-z0-9]/gi,"_")}`,g=document.querySelector(`[data-ds-wired="${l}"]`);if(g||(g=document.createElement("div"),g.setAttribute("data-rt-bind",`store/${a}`),g.setAttribute("data-rt-template",p),g.setAttribute("data-ds-wired",l),r.parentNode.insertBefore(g,r.nextSibling)),typeof this._updateDOM=="function"){this.uiStores=this.uiStores||new Map;let u=this.uiStores.get(a)||{};this._updateDOM(`store/${a}`,u)}}if(c&&typeof this._updateDOM=="function"){this.uiStores=this.uiStores||new Map;let l=this.uiStores.get(a)||{};this._updateDOM(`store/${a}`,l)}}),document.querySelectorAll("[data-store-write]").forEach(r=>{let a=r.getAttribute("data-store-write");if(a){let c=a.split(".");if(c.length===2){let p=c[0],l=c[1],g=r.type==="checkbox"?r.checked:r.value;this.uiStores=this.uiStores||new Map,this.uiStores.has(p)||this.uiStores.set(p,{});let u=this.uiStores.get(p);u[l]===void 0&&(u[l]=g)}}}),document.querySelectorAll("[data-store-read]").forEach(r=>{let a=r.getAttribute("data-store-read");if(a){let c=a.split(".");if(c.length===2){let p=c[0],l=c[1],g=this.getStoreState(p,l);g!=null&&(r.tagName==="INPUT"||r.tagName==="TEXTAREA"?r.type==="checkbox"?r.checked=!!g:r.value=g:r.textContent=g)}}})},w.getClosestContext=function(y,d){let h=y;for(;h;){if(h._rtContext){let r=h._rtContext;return d?r[d]:r}h=h.parentElement||h.parentNode}return null},w._executeStoreAction=function(y,d){this.uiStores=this.uiStores||new Map;let h=d&&typeof this.getClosestContext=="function"?this.getClosestContext(d):null,r=new Proxy({},{has:(a,c)=>!0,get:(a,c)=>{if(typeof c=="string"){if(c==="log")return p=>{if(p===void 0){let l={};this.uiStores.forEach((g,u)=>{l[u]={...g}}),console.log("%c\u{1F4CA} [Dolphin All UI Stores]:","color: #06b6d4; font-weight: bold;",l)}else if(p&&typeof p=="object"&&p.__isStoreProxy__){let l=p.__storeName__,g=this.uiStores.get(l);console.log(`%c\u{1F4CA} [Dolphin Store: ${l}]:`,"color: #06b6d4; font-weight: bold;",g?{...g}:{})}else console.log("%c\u{1F4CA} [Dolphin Log]:","color: #06b6d4; font-weight: bold;",p)};if(this.store&&this.store.data&&typeof this.store.data.has=="function"&&this.store.data.has(c)){let p=this.store.data.get(c),l=this,g=c,u=new Set(["search","filter","range","sort","clearFilters","where","orderBy","reset","add","updateById","deleteById","optimisticDelete","optimisticUpdate","trackStart","trackEnd"]);return new Proxy(p,{get(S,b){return typeof S[b]=="function"?(...m)=>{let _=S[b](...m);if(u.has(b)&&typeof l._updateDOM=="function"){let T=()=>{typeof l._updateDOM=="function"&&l._updateDOM(`store/${g}`,p)};_&&typeof _.then=="function"?_.then(T).catch(T):T()}return _}:S[b]}})}return h&&h[c]!==void 0?h[c]:typeof globalThis<"u"&&c in globalThis?globalThis[c]:typeof window<"u"&&c in window?window[c]:new Proxy({},{get:(p,l)=>{if(l==="__storeName__")return c;if(l==="__isStoreProxy__")return!0;if(typeof l=="string")return this.getStoreState(c,l)},set:(p,l,g)=>typeof l=="string"?(this.setStoreState(c,l,g),!0):!1})}}});try{new Function("ctx",`with(ctx) { ${y} }`)(r)}catch(a){console.error("%c[Dolphin Store Action Error]:","color: #ef4444; font-weight: bold;",a),d&&console.error("%cFailed Element:","color: #f97316; font-weight: bold;",d),console.error("%cFailed Expression:","color: #3b82f6; font-style: italic;",y)}},w._initDOMBinding=function(){if(this._domInitialized)return;this._domInitialized=!0;let y=["input","change","keyup","paste","blur"],d=new WeakMap;y.forEach(r=>{this.addDomListener(document,r,a=>{if(!a.target||!a.target.getAttribute)return;let c=a.target.getAttribute("data-store-write");if(c){let u=c.split(".");if(u.length===2){let S=u[0],b=u[1],m=a.target.type==="checkbox"?a.target.checked:a.target.value;this.setStoreState(S,b,m,a.target)}}let p=a.target.getAttribute("data-rt-validate"),l=a.target.name;if(p&&l&&typeof this.validateField=="function"){let u=a.target.closest("form"),S=u?Object.fromEntries(new FormData(u).entries()):{},b=this.validateField(a.target.value,p,S);b?(a.target.classList.add("invalid"),this.publish(`errors/${l}`,b)):(a.target.classList.remove("invalid"),this.publish(`errors/${l}`,""))}let g=a.target.getAttribute("data-rt-push");if(g){let u=a.target.getAttribute("data-rt-debounce"),S=u?parseInt(u,10):0,b=()=>{let m={name:a.target.name,value:a.target.value};this.pubPush(g,m)};if(S>0){d.has(a.target)&&clearTimeout(d.get(a.target));let m=setTimeout(b,S);d.set(a.target,m)}else b()}})}),this.addDomListener(document,"submit",async r=>{if(!r.target||!r.target.getAttribute)return;let a=r.target.getAttribute("data-rt-submit"),c=r.target.getAttribute("data-api-submit");if(a||c){r.target.querySelectorAll("[name]").forEach(m=>{let _=m.name;_&&(this.publish(`errors/${_}`,""),m.classList.remove("invalid"))});let l=r.target.querySelectorAll("[data-rt-validate]"),g=!0;if(l.length>0&&typeof this.validateField=="function"){let m=Object.fromEntries(new FormData(r.target).entries());l.forEach(_=>{let T=_.getAttribute("data-rt-validate"),C=_.name;if(T&&C){let E=this.validateField(_.value,T,m);E&&(g=!1,_.classList.add("invalid"),this.publish(`errors/${C}`,E))}})}if(!g){r.preventDefault(),r.stopPropagation();return}r.preventDefault();let u=this.getClosestContext(r.target)||{},S=new FormData(r.target),b=Object.fromEntries(S.entries());if(a){let m=a;for(let _ in u){let T=e(_);m=m.replace(new RegExp(`\\{\\{${T}\\}\\}`,"g"),u[_]!==void 0&&u[_]!==null?u[_]:"")}this.publish(m,b)}else if(c){let m=c;for(let E in u){let L=e(E);m=m.replace(new RegExp(`\\{\\{${L}\\}\\}`,"g"),u[E]!==void 0&&u[E]!==null?u[E]:"")}let _=m.trim().split(" "),T=_.length>1?_[0].toUpperCase():"POST",C=_.length>1?_[1]:_[0];b._method&&(T=String(b._method).toUpperCase());try{let E=await this.api.request(T,C,b),L=r.target.getAttribute("data-api-result");L&&this._updateDOM(L,E);let P=r.target.getAttribute("data-api-redirect");P&&(window.location.href=P),r.target.hasAttribute("data-api-reload")&&window.location.reload()}catch(E){console.error("[Dolphin] API Submit Error:",E)}}}}),["click","change","submit","input","keydown","keyup","dblclick","focus","blur","mouseenter","mouseleave"].forEach(r=>{this.addDomListener(document,r,async a=>{if(!a.target||!a.target.closest)return;let c=a.target.closest(`[data-rt-${r}]`),p=a.target.closest(`[data-api-${r}]`);if(c){r==="submit"&&a.preventDefault();let g=c.getAttribute(`data-rt-${r}`),u=c.getAttribute("data-rt-payload"),S=this.getClosestContext(c)||{},b={};if(u){let m=u;for(let _ in S){let T=e(_);m=m.replace(new RegExp(`\\{\\{${T}\\}\\}`,"g"),S[_]!==void 0&&S[_]!==null?S[_]:"")}try{b=JSON.parse(m)}catch{b={}}}this.publish(g,b)}if(p){r==="submit"&&a.preventDefault();let g=p.getAttribute(`data-api-${r}`),u=p.getAttribute("data-api-payload"),S=this.getClosestContext(p)||{},b=g.trim().split(" "),m=b.length>1?b[0].toUpperCase():"POST",_=b.length>1?b[1]:b[0],T=null;if(u){let C=u;for(let E in S){let L=e(E);C=C.replace(new RegExp(`\\{\\{${L}\\}\\}`,"g"),S[E]!==void 0&&S[E]!==null?S[E]:"")}try{T=JSON.parse(C)}catch{T=null}}try{let C=await this.api.request(m,_,T),E=p.getAttribute("data-api-result");E&&this._updateDOM(E,C);let L=p.getAttribute("data-api-redirect");L&&(window.location.href=L),p.hasAttribute("data-api-reload")&&window.location.reload()}catch(C){console.error(`[Dolphin] API ${r} Error:`,C)}}let l=a.target.closest(`[data-store-${r}]`);if(l){r==="submit"&&a.preventDefault();let g=l.getAttribute(`data-store-${r}`);g&&this._executeStoreAction(g,l)}})}),this.subscribe("#",(r,a)=>{this._updateDOM(a,r)}),this._scanAndFetchAPIBinds(),this._scanStoreBinds(),this._resolveImports(),this._initSPARouter()},w._scanAndFetchAPIBinds=async function(){if(typeof document>"u")return;let y=document.querySelectorAll("[data-api-get]");for(let d of Array.from(y)){let h=d.getAttribute("data-api-get");if(h&&!(typeof d.hasAttribute=="function"&&d.hasAttribute("data-api-initialized"))){typeof d.setAttribute=="function"&&d.setAttribute("data-api-initialized","true");try{let r=await this.api.get(h),a=d.getAttribute("data-api-store");if(a){let p=a.split(".");p.length===2&&this.setStoreState(p[0],p[1],r)}let c=d.getAttribute("data-rt-bind");if(c&&!a)this._updateDOM(c,r);else if(!a){let p=o(d);if(p&&typeof r=="object"&&r!==null){let l=this._applyDeclarativeDirectives(d,r);if(Array.isArray(l)){let g="";for(let u of l)g+=f(p,u);I(d,g)}else I(d,f(p,l))}else if(d.tagName==="INPUT"||d.tagName==="TEXTAREA")d.value=typeof r=="object"?r.value!==void 0?r.value:"":r;else{let l=typeof r=="object"?r.html||r.text||JSON.stringify(r):String(r);d.innerHTML=A(l)}}}catch(r){console.error("[Dolphin] API Get Error:",r)}}}},w._applyDeclarativeDirectives=function(y,d){let h=d;if(typeof d=="object"&&d!==null){let r=a=>{let c=[...a],p=y.getAttribute("data-rt-filter");if(p){let u=p.split("==");if(u.length===2){let S=u[0].trim(),b=u[1].trim(),m,_=b.split(".");_.length===2?m=this.getStoreState(_[0],_[1]):m=d[b]!==void 0?d[b]:this.getStoreState("app",b),m!=null&&m!==""&&(c=c.filter(T=>T[S]===m))}}let l=y.getAttribute("data-rt-search");if(l){let u=l.split("==");if(u.length===2){let S=u[0].trim(),b=u[1].trim(),m,_=b.split(".");if(_.length===2?m=this.getStoreState(_[0],_[1]):m=d[b]!==void 0?d[b]:this.getStoreState("app",b),m!=null&&m!==""){let T=String(m).toLowerCase();c=c.filter(C=>{let E=C[S];return E!=null&&String(E).toLowerCase().includes(T)})}}}let g=y.getAttribute("data-rt-sort");if(g){let u,S=g.split(".");if(S.length===2?u=this.getStoreState(S[0],S[1]):u=d[g]!==void 0?d[g]:this.getStoreState("app",g),u&&u!=="")if(u==="popular")c.sort((b,m)=>{let _=b.rating?.rate||b.rate||0;return(m.rating?.rate||m.rate||0)-_});else{let b="",m="asc";u.endsWith("-low")||u.endsWith("-asc")?(b=u.replace("-low","").replace("-asc",""),m="asc"):(u.endsWith("-high")||u.endsWith("-desc"))&&(b=u.replace("-high","").replace("-desc",""),m="desc"),b&&c.sort((_,T)=>{let C=(tt,et)=>et.split(".").reduce((W,nt)=>W&&W[nt],tt),E=C(_,b),L=C(T,b);if(E===void 0&&(E=_[b]),L===void 0&&(L=T[b]),typeof E=="string"&&typeof L=="string")return m==="asc"?E.localeCompare(L):L.localeCompare(E);let P=Number(E),B=Number(L);return!isNaN(P)&&!isNaN(B)?m==="asc"?P-B:B-P:0})}}return c};if(Array.isArray(d))h=r(d);else{let a="";for(let c in d)if(Array.isArray(d[c])){a=c;break}if(a){let c=r(d[a]);h={...d,[a]:c}}}}return h},w._updateDOM=function(y,d){if(typeof document>"u")return;document.querySelectorAll(`[data-rt-bind="${y}"]`).forEach(r=>{let a=this._applyDeclarativeDirectives(r,d);if(r.getAttribute("data-rt-type")==="context"&&typeof a=="object"&&a!==null){r._rtContext=a;let p=l=>{if(l.hasAttribute("data-rt-text")){let g=l.getAttribute("data-rt-text");if(g){let u=n(g,a);u!=null&&(l.textContent=u)}}if(l.hasAttribute("data-rt-html")){let g=l.getAttribute("data-rt-html");if(g){let u=n(g,a);u!=null&&(l.innerHTML=A(u))}}if(l.hasAttribute("data-rt-attr")){let g=l.getAttribute("data-rt-attr");g&&s(g,",").forEach(u=>{let S=i(u);if(S){let b=S[0].trim(),m=S[1].trim();if(b&&m){let _=n(m,a);_!=null&&l.setAttribute(b,_)}}})}if(l.hasAttribute("data-rt-class")){let g=l.getAttribute("data-rt-class");g&&s(g,",").forEach(u=>{let S=i(u);if(S){let b=S[0].trim(),m=S[1].trim(),_=b.split(/\s+/).filter(Boolean);n(m,a)?_.forEach(T=>l.classList.add(T)):_.forEach(T=>l.classList.remove(T))}})}if(l.hasAttribute("data-rt-if")){let g=l.getAttribute("data-rt-if");g&&(n(g,a)?l.style.display="":l.style.display="none")}if(l.hasAttribute("data-rt-hide")){let g=l.getAttribute("data-rt-hide");g&&(n(g,a)?l.style.display="none":l.style.display="")}};p(r),r.querySelectorAll("[data-rt-text], [data-rt-html], [data-rt-attr], [data-rt-class], [data-rt-if], [data-rt-hide]").forEach(p);return}let c=o(r);if(c&&typeof a=="object"&&a!==null){if(Array.isArray(a)){let p="";for(let l of a)p+=f(c,l);I(r,p)}else I(r,f(c,a));return}if(r.tagName==="INPUT"||r.tagName==="TEXTAREA")r.value=typeof a=="object"?a.value!==void 0?a.value:"":a;else if(c)r.innerHTML=typeof a=="object"?a.html||a.text||JSON.stringify(a):String(a);else{let p=typeof a=="object"?a.html||a.text||JSON.stringify(a):String(a);r.innerHTML=A(p)}})},w._resolveImports=async function(y){if(typeof document>"u")return;let d=y||document.body||document;if(!d||typeof d.querySelectorAll!="function")return;let h=d.querySelectorAll("[data-import]");if(h.length===0)return;let r=async(c,p)=>{let l=c.getAttribute("data-import");if(!l)return;if(p.has(l)){console.warn(`[Dolphin Component Warning]: Circular import detected for "${l}". Skipping resolving.`),c.innerHTML=`<span style="color:red;font-weight:bold;">Circular import: ${l}</span>`;return}p.add(l);let g=l.indexOf("#"),u=g!==-1?l.substring(0,g):l,S=g!==-1?l.substring(g):null,b=t.get(u);b||(b=fetch(u).then(T=>{if(!T.ok)throw new Error(`HTTP ${T.status}`);return T.text()}),b.catch(()=>t.delete(u)),t.set(u,b));let m="";try{if(m=await b,S&&typeof DOMParser<"u"){let E=new DOMParser().parseFromString(m,"text/html").querySelector(S);E?m=E.outerHTML:(console.warn(`[Dolphin Component Warning]: Selector "${S}" not found in imported file "${u}".`),m=`<span style="color:orange;font-weight:bold;">Selector ${S} not found in ${u}</span>`)}}catch(T){console.error(`[Dolphin Component Error]: Failed to fetch component "${u}":`,T),m=`<span style="color:red;font-weight:bold;">Failed to import ${u}</span>`}c.innerHTML=A(m),c.removeAttribute("data-import");let _=c.querySelectorAll("[data-import]");if(_.length>0){let T=Array.from(_).map(C=>r(C,new Set(p)));await Promise.all(T)}this._scanStoreBinds(),this._scanAndFetchAPIBinds()},a=Array.from(h).map(c=>r(c,new Set));await Promise.all(a)},w._initSPARouter=function(){if(typeof window>"u"||typeof document>"u"||this._routerInitialized)return;this._routerInitialized=!0;let y=null,d=()=>{let a=(this.options.routerViewport||"main, #viewport, body").split(",").map(c=>c.trim());for(let c of a){let p=document.querySelector(c);if(p)return p}return document.body},h=async(r,a=!0)=>{try{this.options.debug&&console.log(`%c\u{1F6E3}\uFE0F [Dolphin Router]: Navigating to ${r}...`,"color: #3b82f6; font-weight: bold;"),y&&y.abort(),y=new AbortController;let c=y.signal,p=d();this.options.routerTransitions&&p&&(p.classList.add("dolphin-fade-out"),await new Promise(_=>setTimeout(_,150)));let l=await fetch(r,{signal:c});if(!l.ok)throw new Error(`HTTP ${l.status}`);let g=await l.text();y=null;let S=new DOMParser().parseFromString(g,"text/html");S.title&&(document.title=S.title);let b=S.querySelector(this.options.routerViewport||"main, #viewport, body"),m=d();b&&m?(m.innerHTML=b.innerHTML,Array.from(b.attributes).forEach(_=>{m.setAttribute(_.name,_.value)})):m&&(m.innerHTML=S.body.innerHTML),a&&window.history.pushState({dolphinSpa:!0,url:r},"",r),this.options.routerTransitions&&m&&(m.classList.remove("dolphin-fade-out"),m.classList.add("dolphin-fade-in"),setTimeout(()=>m.classList.remove("dolphin-fade-in"),300)),await this._resolveImports(m),this._scanStoreBinds(),this._scanAndFetchAPIBinds()}catch(c){if(c&&c.name==="AbortError")return;console.error("[Dolphin Router Error]: Failed to route page:",c),window.location.href=r}};if(this.addDomListener(document,"click",r=>{let a=r.target.closest("a");if(!a||!a.hasAttribute("data-spa")&&a.getAttribute("data-spa")!=="true")return;let c=a.getAttribute("href");!c||c.startsWith("#")||c.startsWith("javascript:")||c.startsWith("mailto:")||c.startsWith("tel:")||new URL(c,window.location.href).origin!==window.location.origin||(r.preventDefault(),h(c))}),this.addDomListener(window,"popstate",r=>{r.state&&r.state.dolphinSpa?h(r.state.url,!1):r.state===null&&h(window.location.pathname,!1)}),this.options.routerTransitions){let r=document.createElement("style");r.innerHTML=`
27
27
  .dolphin-fade-out {
28
28
  opacity: 0;
29
29
  transition: opacity 0.15s ease-in-out;
@@ -34,4 +34,4 @@ var DolphinModule=(()=>{var U=Object.defineProperty;var nt=Object.getOwnProperty
34
34
  main, #viewport, body {
35
35
  transition: opacity 0.15s ease-in-out;
36
36
  }
37
- `,document.head.appendChild(n)}}}var F=class{client;db;isOnline;memoryCache=new Map;memoryMutations=[];constructor(t){this.client=t,this.isOnline=typeof window<"u"&&typeof navigator<"u"?navigator.onLine:!0,this.initDB(),this.setupNetworkListeners()}initDB(){if(!(typeof indexedDB>"u"))try{let t=indexedDB.open("dolphin_offline",1);t.onupgradeneeded=e=>{let i=e.target.result;i.objectStoreNames.contains("cache")||i.createObjectStore("cache"),i.objectStoreNames.contains("mutations")||i.createObjectStore("mutations",{keyPath:"id",autoIncrement:!0})},t.onsuccess=e=>{this.db=e.target.result,this.isOnline&&this.syncMutations()}}catch(t){console.warn("[Dolphin Offline] Failed to initialize IndexedDB:",t)}}setupNetworkListeners(){typeof window>"u"||(this.client.addDomListener(window,"online",()=>{this.isOnline=!0,this.client._dispatch("network:status",{online:!0}),this.syncMutations()}),this.client.addDomListener(window,"offline",()=>{this.isOnline=!1,this.client._dispatch("network:status",{online:!1})}))}async getCache(t){return this.db?new Promise(e=>{try{let r=this.db.transaction("cache","readonly").objectStore("cache").get(t);r.onsuccess=()=>e(r.result?r.result.data:null),r.onerror=()=>e(null)}catch{e(null)}}):this.memoryCache.get(t)}async setCache(t,e){if(!this.db){this.memoryCache.set(t,e);return}return new Promise(i=>{try{let s=this.db.transaction("cache","readwrite");s.objectStore("cache").put({data:e,timestamp:Date.now()},t),s.oncomplete=()=>i(),s.onerror=()=>{console.warn("[Dolphin Offline] setCache write failed for key:",t),i()}}catch{i()}})}async queueMutation(t,e,i){let s={method:t,path:e,payload:i,timestamp:Date.now()};if(!this.db){this.memoryMutations.push(s);return}return new Promise(r=>{try{let a=this.db.transaction("mutations","readwrite");a.objectStore("mutations").add(s),a.oncomplete=()=>r(),a.onerror=()=>{console.warn("[Dolphin Offline] queueMutation write failed:",t,e),this.memoryMutations.push(s),r()}}catch{r()}})}async getMutations(){return this.db?new Promise(t=>{try{let s=this.db.transaction("mutations","readonly").objectStore("mutations").getAll();s.onsuccess=()=>t(s.result||[]),s.onerror=()=>t([])}catch{t([])}}):[...this.memoryMutations]}async removeMutation(t){if(!this.db){this.memoryMutations=this.memoryMutations.filter(e=>e.id!==t);return}return new Promise(e=>{try{let i=this.db.transaction("mutations","readwrite");i.objectStore("mutations").delete(t),i.oncomplete=()=>e(),i.onerror=()=>{console.warn("[Dolphin Offline] removeMutation failed for id:",t),e()}}catch{e()}})}async syncMutations(){let t=await this.getMutations();if(t.length!==0){console.log(`[Dolphin Offline] Syncing ${t.length} queued mutations...`);for(let e of t)try{await this.client.api.requestDirect(e.method,e.path,e.payload),e.id!==void 0?await this.removeMutation(e.id):this.memoryMutations.shift()}catch(i){if(console.error(`[Dolphin Offline] Sync failed for mutation ${e.method} ${e.path}:`,i),i&&i.status&&i.status>=400&&i.status<500)console.warn("[Dolphin Offline] Discarding invalid mutation."),e.id!==void 0?await this.removeMutation(e.id):this.memoryMutations.shift();else break}}}};function j(w){w._initOffline=function(){this.offline=new F(this)}}function ct(w,t,e){let i=t.split(",");for(let s of i){let r=s.trim().split(":"),a=r[0],y=r[1];if(a==="required"){if(!w||w.trim()==="")return"This field is required"}else if(a==="email"){if(w&&w.trim()!==""&&!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(w))return"Please enter a valid email address"}else if(a==="min"){let T=parseInt(y,10);if(!w||w.length<T)return`Must be at least ${T} characters`}else if(a==="match"&&e&&w!==e[y])return`Must match ${y}`}return null}function V(w){w.validateField=ct}function z(w){w.animateElement=function(t,e,i=300){if(typeof t.animate!="function"){t.classList.add(e),setTimeout(()=>t.classList.remove(e),i);return}e==="fade-in"?t.animate([{opacity:0,transform:"translateY(10px)"},{opacity:1,transform:"translateY(0)"}],{duration:i,easing:"ease-out"}):e==="fade-out"&&t.animate([{opacity:1,transform:"translateY(0)"},{opacity:0,transform:"translateY(10px)"}],{duration:i,easing:"ease-in"})},w.staggerListItems=function(t,e,i=50){if(typeof document>"u")return;t.querySelectorAll(e).forEach((r,a)=>{r.style.animationDelay=`${a*i}ms`,r.classList.add("staggered-item")})}}function K(w){w._initA11y=function(){typeof document>"u"||(this.addDomListener(document,"keydown",t=>{if(t.key!=="Tab")return;document.querySelectorAll("[data-rt-a11y-focus-trap]").forEach(i=>{if(i.style.display==="none"||i.hasAttribute("aria-hidden")&&i.getAttribute("aria-hidden")==="true")return;let r=Array.from(i.querySelectorAll('a[href], area[href], input:not([disabled]), select:not([disabled]), textarea:not([disabled]), button:not([disabled]), iframe, object, embed, [tabindex="0"], [contenteditable]'));if(r.length===0)return;let a=r[0],y=r[r.length-1];t.shiftKey?document.activeElement===a&&(y.focus(),t.preventDefault()):document.activeElement===y&&(a.focus(),t.preventDefault())})}),this.addDomListener(document,"keydown",t=>{if(!["ArrowUp","ArrowDown","Enter"].includes(t.key))return;document.querySelectorAll("[data-rt-keynav]").forEach(i=>{let s=Array.from(i.children);if(s.length===0)return;let r=s.findIndex(a=>a.classList.contains("active")||document.activeElement===a);t.key==="ArrowDown"?(r=(r+1)%s.length,s[r].focus(),s.forEach((a,y)=>{y===r?a.classList.add("active"):a.classList.remove("active")}),t.preventDefault()):t.key==="ArrowUp"?(r=(r-1+s.length)%s.length,s[r].focus(),s.forEach((a,y)=>{y===r?a.classList.add("active"):a.classList.remove("active")}),t.preventDefault()):t.key==="Enter"&&r!==-1&&(s[r].click(),t.preventDefault())})}))},w.autoAriaModal=function(t,e){e?(t.setAttribute("role","dialog"),t.setAttribute("aria-modal","true"),t.setAttribute("aria-hidden","false"),t.focus()):t.setAttribute("aria-hidden","true")}}function X(w){w._initI18n=function(){if(this.i18n=this.i18n||{locale:"en",dicts:{}},typeof document>"u")return;if(document.querySelectorAll("[data-i18n-dict]").forEach(e=>{let i=e.getAttribute("data-i18n-dict");if(i)try{let s=JSON.parse(e.textContent||"{}");this.i18n.dicts[i]={...this.i18n.dicts[i]||{},...s}}catch(s){console.warn("[Dolphin i18n] Failed to parse dictionary for locale:",i,s)}}),!this.i18n.locale&&typeof navigator<"u"){let e=navigator.language.split("-")[0];this.i18n.dicts[e]&&(this.i18n.locale=e)}this.addDomListener(document,"click",e=>{let i=e.target.closest("[data-i18n-switch]");if(i){let s=i.getAttribute("data-i18n-switch");s&&this.setLocale(s)}}),this.translateDOM()},w.setLocale=function(t){this.i18n=this.i18n||{locale:"en",dicts:{}},this.i18n.locale=t,this.translateDOM(),this.publish("i18n/locale",t)},w.translateDOM=function(){if(typeof document>"u")return;this.i18n=this.i18n||{locale:"en",dicts:{}};let t=this.i18n.locale||"en",e=this.i18n.dicts[t]||{};document.querySelectorAll("[data-i18n-key]").forEach(s=>{let r=s.getAttribute("data-i18n-key");if(!r)return;let a=r.split(".").reduce((T,E)=>T?T[E]:null,e);a==null&&(a=r);let y=s.getAttribute("data-i18n-params");if(y)try{let T=JSON.parse(y),E=D=>D.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");for(let D in T){let k=E(D);a=a.replace(new RegExp(`\\{\\{${k}\\}\\}`,"g"),T[D])}}catch{}s.tagName==="INPUT"||s.tagName==="TEXTAREA"?s.placeholder=a:s.textContent=a})}}function J(w){w._initDragDrop=function(){typeof document>"u"||(this.addDomListener(document,"dragstart",t=>{let e=t.target.closest("[data-drag]");if(!e)return;let i=e.getAttribute("data-drag");i&&(t.dataTransfer.setData("text/plain",i),t.dataTransfer.effectAllowed="move",e.classList.add("dragging"))}),this.addDomListener(document,"dragend",t=>{let e=t.target.closest("[data-drag]");e&&e.classList.remove("dragging")}),this.addDomListener(document,"dragover",t=>{let e=t.target.closest("[data-drop]");e&&(t.preventDefault(),e.classList.add("drag-over"))}),this.addDomListener(document,"dragleave",t=>{let e=t.target.closest("[data-drop]");e&&e.classList.remove("drag-over")}),this.addDomListener(document,"drop",t=>{let e=t.target.closest("[data-drop]");if(!e)return;t.preventDefault(),e.classList.remove("drag-over");let i=e.getAttribute("data-drop"),s=t.dataTransfer.getData("text/plain");if(i&&s)try{let r=JSON.parse(s);this.publish(i,r)}catch{this.publish(i,{value:s})}}),this.addDomListener(document,"dragover",t=>{let e=t.target.closest("[data-sortable]");if(!e)return;t.preventDefault();let i=e.querySelector(".dragging");if(!i)return;let r=Array.from(e.querySelectorAll("[data-drag]:not(.dragging)")).find(a=>{let y=a.getBoundingClientRect();return t.clientY-y.top-y.height/2<0});r?e.insertBefore(i,r):e.appendChild(i)}),this.addDomListener(document,"drop",t=>{let e=t.target.closest("[data-sortable]");if(!e)return;let i=e.getAttribute("data-sortable");if(!i)return;let r=Array.from(e.querySelectorAll("[data-drag]")).map((a,y)=>{let T=a.getAttribute("data-drag");try{return{index:y,payload:JSON.parse(T||"{}")}}catch{return{index:y,payload:T}}});this.publish(i,r)}))}}function Q(w){w._initCollab=function(){if(typeof document>"u")return;let t=new Map,e=new Map,i=5e3;this.addDomListener(document,"mousemove",s=>{document.querySelectorAll("[data-rt-cursor-share]").forEach(a=>{let y=a.getAttribute("data-rt-cursor-share");if(!y)return;let T=a.getBoundingClientRect(),E=(s.clientX-T.left)/T.width,D=(s.clientY-T.top)/T.height,k=Date.now();(!a._lastSent||k-a._lastSent>50)&&(a._lastSent=k,this.pubPush(`collab/${y}/cursor/${this.deviceId}`,{deviceId:this.deviceId,x:E,y:D}))})}),this.addDomListener(document,"input",s=>{let r=s.target.getAttribute("data-rt-typing");if(!r)return;let a=r,y=T=>{this.pubPush(`collab/${a}/typing/${this.deviceId}`,{deviceId:this.deviceId,typing:T})};s.target._isTyping||(s.target._isTyping=!0,y(!0)),s.target._typingTimer&&clearTimeout(s.target._typingTimer),s.target._typingTimer=setTimeout(()=>{s.target._isTyping=!1,s.target._typingTimer=null,y(!1)},2e3)}),this.addDomListener(document,"input",s=>{let r=s.target.getAttribute("data-rt-crdt");if(!r)return;let a=r,y=s.target.value,T=Date.now();this.publish(`collab/${a}/crdt`,{deviceId:this.deviceId,value:y,timestamp:T,cursorPos:s.target.selectionStart})}),this.subscribe("collab/+/cursor/+",(s,r)=>{let a=r.split("/"),y=a[1],T=a[3];if(T===this.deviceId)return;let E=document.querySelector(`[data-rt-cursor-share="${y}"]`);if(!E)return;let D=`${y}::${T}`,k=t.get(D);(!k||!document.contains(k))&&(k=document.createElement("div"),k.className=`rt-cursor rt-cursor-${T}`,k.style.position="absolute",k.style.width="10px",k.style.height="10px",k.style.borderRadius="50%",k.style.backgroundColor="#"+Math.floor(Math.random()*16777215).toString(16).padStart(6,"0"),k.style.pointerEvents="none",E.appendChild(k),t.set(D,k));let M=E.getBoundingClientRect();k.style.left=s.x*M.width+"px",k.style.top=s.y*M.height+"px",e.has(D)&&clearTimeout(e.get(D)),e.set(D,setTimeout(()=>{let x=t.get(D);x&&x.parentNode&&x.parentNode.removeChild(x),t.delete(D),e.delete(D)},i))}),this.subscribe("collab/+/crdt",(s,r)=>{if(s.deviceId===this.deviceId)return;let y=r.split("/")[1];document.querySelectorAll(`[data-rt-crdt="${y}"]`).forEach(E=>{if(!E._lastUpdate||s.timestamp>E._lastUpdate){E._lastUpdate=s.timestamp;let D=E.selectionStart;E.value=s.value,document.activeElement===E&&E.setSelectionRange(D,D)}})}),this._collabCleanup=()=>{e.forEach(s=>clearTimeout(s)),e.clear(),t.forEach(s=>{s&&s.parentNode&&s.parentNode.removeChild(s)}),t.clear()}}}function Z(w){w.registerServiceWorker=async function(t="/sw.js"){if(typeof navigator>"u"||!("serviceWorker"in navigator))return console.warn("[Dolphin PWA] Service Workers are not supported in this browser."),null;try{let e=await navigator.serviceWorker.register(t);return console.log("[Dolphin PWA] Service Worker registered successfully with scope:",e.scope),e}catch(e){return console.error("[Dolphin PWA] Service Worker registration failed:",e),null}},w.subscribePushNotifications=async function(t){if(typeof window>"u"||!("serviceWorker"in navigator)||!("PushManager"in window))return console.warn("[Dolphin PWA] Push notifications are not supported in this browser."),null;try{let e=await navigator.serviceWorker.ready,i=await e.pushManager.getSubscription();if(!i){let s="=".repeat((4-t.length%4)%4),r=(t+s).replace(/\-/g,"+").replace(/_/g,"/"),a=window.atob(r),y=new Uint8Array(a.length);for(let T=0;T<a.length;++T)y[T]=a.charCodeAt(T);i=await e.pushManager.subscribe({userVisibleOnly:!0,applicationServerKey:y})}return console.log("[Dolphin PWA] Subscribed to push notifications:",i),i}catch(e){return console.error("[Dolphin PWA] Push notification subscription failed:",e),null}}}function I(){if(typeof jest<"u"&&typeof jest.fn=="function")return jest.fn();let w=(...t)=>(w.mock.calls.push(t),w._implementation?w._implementation(...t):w._returnValue);return w.mock={calls:[]},w._returnValue=void 0,w._implementation=null,w.mockReturnValue=t=>(w._returnValue=t,w),w.mockImplementation=t=>(w._implementation=t,w),w}var H=class{static render(t){if(typeof document>"u")throw new Error("DolphinTestUtils.render requires a DOM document environment to execute.");let e=document.createElement("div");return e.innerHTML=t,document.body.appendChild(e),{container:e,find:i=>e.querySelector(i),fireEvent:(i,s)=>{let r=document.createEvent("Event");r.initEvent(s,!0,!0),i.dispatchEvent(r)}}}static mockWebSocket(){let t=[],e={readyState:1,send:i=>{t.push(i)},close:I(),onopen:I(),onmessage:I(),onclose:I(),onerror:I(),sentMessages:t};return global.WebSocket=class{static OPEN=1;readyState=e.readyState;send=e.send;close=e.close;set onopen(i){e.onopen=i}get onopen(){return e.onopen}set onmessage(i){e.onmessage=i}get onmessage(){return e.onmessage}set onclose(i){e.onclose=i}get getonclose(){return e.onclose}constructor(){setTimeout(()=>e.onopen&&e.onopen(),0)}},e}static simulateClick(t){let e={target:t,preventDefault:I(),stopPropagation:I()};(global.document._listeners?.click||[]).forEach(s=>s(e))}static simulateChange(t,e){t.value=e;let i={target:t,preventDefault:I(),stopPropagation:I()};(global.document._listeners?.change||[]).forEach(r=>r(i))}};function G(w){w.testing=H}B($.prototype);j($.prototype);V($.prototype);z($.prototype);K($.prototype);X($.prototype);J($.prototype);Q($.prototype);Z($.prototype);G($.prototype);typeof window<"u"&&(window.DolphinClient=$,document.addEventListener("DOMContentLoaded",()=>{if(!window.dolphin){let w=document.querySelector('script[src*="dolphin-client"]'),t=w?w.getAttribute("data-debug")==="true":!1,e=new $(void 0,void 0,{debug:t});window.dolphin=e,t&&(console.log("%c\u{1F42C} [Dolphin Client] Auto-initialized local reactive engine!","color: #06b6d4; font-weight: bold; font-size: 14px;"),console.log('%c\u{1F449} Tip: You can access the client instance via "window.dolphin" in console.',"color: #94a3b8; font-style: italic;")),document.querySelector('[data-store-write="app.username"]')&&e.setStoreState("app","username","\u0928\u092E\u0938\u094D\u0924\u0947 \u0938\u093E\u0925\u0940!")}}));return at(lt);})();
37
+ `,document.head.appendChild(r)}}}var U=class{client;db;isOnline;memoryCache=new Map;memoryMutations=[];constructor(t){this.client=t,this.isOnline=typeof window<"u"&&typeof navigator<"u"?navigator.onLine:!0,this.initDB(),this.setupNetworkListeners()}initDB(){if(!(typeof indexedDB>"u"))try{let t=indexedDB.open("dolphin_offline",1);t.onupgradeneeded=e=>{let n=e.target.result;n.objectStoreNames.contains("cache")||n.createObjectStore("cache"),n.objectStoreNames.contains("mutations")||n.createObjectStore("mutations",{keyPath:"id",autoIncrement:!0})},t.onsuccess=e=>{this.db=e.target.result,this.isOnline&&this.syncMutations()}}catch(t){console.warn("[Dolphin Offline] Failed to initialize IndexedDB:",t)}}setupNetworkListeners(){typeof window>"u"||(this.client.addDomListener(window,"online",()=>{this.isOnline=!0,this.client._dispatch("network:status",{online:!0}),this.syncMutations()}),this.client.addDomListener(window,"offline",()=>{this.isOnline=!1,this.client._dispatch("network:status",{online:!1})}))}async getCache(t){return this.db?new Promise(e=>{try{let i=this.db.transaction("cache","readonly").objectStore("cache").get(t);i.onsuccess=()=>e(i.result?i.result.data:null),i.onerror=()=>e(null)}catch{e(null)}}):this.memoryCache.get(t)}async setCache(t,e){if(!this.db){this.memoryCache.set(t,e);return}return new Promise(n=>{try{let s=this.db.transaction("cache","readwrite");s.objectStore("cache").put({data:e,timestamp:Date.now()},t),s.oncomplete=()=>n(),s.onerror=()=>{console.warn("[Dolphin Offline] setCache write failed for key:",t),n()}}catch{n()}})}async queueMutation(t,e,n){let s={method:t,path:e,payload:n,timestamp:Date.now()};if(!this.db){this.memoryMutations.push(s);return}return new Promise(i=>{try{let o=this.db.transaction("mutations","readwrite");o.objectStore("mutations").add(s),o.oncomplete=()=>i(),o.onerror=()=>{console.warn("[Dolphin Offline] queueMutation write failed:",t,e),this.memoryMutations.push(s),i()}}catch{i()}})}async getMutations(){return this.db?new Promise(t=>{try{let s=this.db.transaction("mutations","readonly").objectStore("mutations").getAll();s.onsuccess=()=>t(s.result||[]),s.onerror=()=>t([])}catch{t([])}}):[...this.memoryMutations]}async removeMutation(t){if(!this.db){this.memoryMutations=this.memoryMutations.filter(e=>e.id!==t);return}return new Promise(e=>{try{let n=this.db.transaction("mutations","readwrite");n.objectStore("mutations").delete(t),n.oncomplete=()=>e(),n.onerror=()=>{console.warn("[Dolphin Offline] removeMutation failed for id:",t),e()}}catch{e()}})}async syncMutations(){let t=await this.getMutations();if(t.length!==0){console.log(`[Dolphin Offline] Syncing ${t.length} queued mutations...`);for(let e of t)try{await this.client.api.requestDirect(e.method,e.path,e.payload),e.id!==void 0?await this.removeMutation(e.id):this.memoryMutations.shift()}catch(n){if(console.error(`[Dolphin Offline] Sync failed for mutation ${e.method} ${e.path}:`,n),n&&n.status&&n.status>=400&&n.status<500)console.warn("[Dolphin Offline] Discarding invalid mutation."),e.id!==void 0?await this.removeMutation(e.id):this.memoryMutations.shift();else break}}}};function V(w){w._initOffline=function(){this.offline=new U(this)}}function lt(w,t,e){let n=t.split(",");for(let s of n){let i=s.trim().split(":"),o=i[0],f=i[1];if(o==="required"){if(!w||w.trim()==="")return"This field is required"}else if(o==="email"){if(w&&w.trim()!==""&&!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(w))return"Please enter a valid email address"}else if(o==="min"){let A=parseInt(f,10);if(!w||w.length<A)return`Must be at least ${A} characters`}else if(o==="match"&&e&&w!==e[f])return`Must match ${f}`}return null}function z(w){w.validateField=lt}function K(w){w.animateElement=function(t,e,n=300){if(typeof t.animate!="function"){t.classList.add(e),setTimeout(()=>t.classList.remove(e),n);return}e==="fade-in"?t.animate([{opacity:0,transform:"translateY(10px)"},{opacity:1,transform:"translateY(0)"}],{duration:n,easing:"ease-out"}):e==="fade-out"&&t.animate([{opacity:1,transform:"translateY(0)"},{opacity:0,transform:"translateY(10px)"}],{duration:n,easing:"ease-in"})},w.staggerListItems=function(t,e,n=50){if(typeof document>"u")return;t.querySelectorAll(e).forEach((i,o)=>{i.style.animationDelay=`${o*n}ms`,i.classList.add("staggered-item")})}}function X(w){w._initA11y=function(){typeof document>"u"||(this.addDomListener(document,"keydown",t=>{if(t.key!=="Tab")return;document.querySelectorAll("[data-rt-a11y-focus-trap]").forEach(n=>{if(n.style.display==="none"||n.hasAttribute("aria-hidden")&&n.getAttribute("aria-hidden")==="true")return;let i=Array.from(n.querySelectorAll('a[href], area[href], input:not([disabled]), select:not([disabled]), textarea:not([disabled]), button:not([disabled]), iframe, object, embed, [tabindex="0"], [contenteditable]'));if(i.length===0)return;let o=i[0],f=i[i.length-1];t.shiftKey?document.activeElement===o&&(f.focus(),t.preventDefault()):document.activeElement===f&&(o.focus(),t.preventDefault())})}),this.addDomListener(document,"keydown",t=>{if(!["ArrowUp","ArrowDown","Enter"].includes(t.key))return;document.querySelectorAll("[data-rt-keynav]").forEach(n=>{let s=Array.from(n.children);if(s.length===0)return;let i=s.findIndex(o=>o.classList.contains("active")||document.activeElement===o);t.key==="ArrowDown"?(i=(i+1)%s.length,s[i].focus(),s.forEach((o,f)=>{f===i?o.classList.add("active"):o.classList.remove("active")}),t.preventDefault()):t.key==="ArrowUp"?(i=(i-1+s.length)%s.length,s[i].focus(),s.forEach((o,f)=>{f===i?o.classList.add("active"):o.classList.remove("active")}),t.preventDefault()):t.key==="Enter"&&i!==-1&&(s[i].click(),t.preventDefault())})}))},w.autoAriaModal=function(t,e){e?(t.setAttribute("role","dialog"),t.setAttribute("aria-modal","true"),t.setAttribute("aria-hidden","false"),t.focus()):t.setAttribute("aria-hidden","true")}}function J(w){w._initI18n=function(){if(this.i18n=this.i18n||{locale:"en",dicts:{}},typeof document>"u")return;if(document.querySelectorAll("[data-i18n-dict]").forEach(e=>{let n=e.getAttribute("data-i18n-dict");if(n)try{let s=JSON.parse(e.textContent||"{}");this.i18n.dicts[n]={...this.i18n.dicts[n]||{},...s}}catch(s){console.warn("[Dolphin i18n] Failed to parse dictionary for locale:",n,s)}}),!this.i18n.locale&&typeof navigator<"u"){let e=navigator.language.split("-")[0];this.i18n.dicts[e]&&(this.i18n.locale=e)}this.addDomListener(document,"click",e=>{let n=e.target.closest("[data-i18n-switch]");if(n){let s=n.getAttribute("data-i18n-switch");s&&this.setLocale(s)}}),this.translateDOM()},w.setLocale=function(t){this.i18n=this.i18n||{locale:"en",dicts:{}},this.i18n.locale=t,this.translateDOM(),this.publish("i18n/locale",t)},w.translateDOM=function(){if(typeof document>"u")return;this.i18n=this.i18n||{locale:"en",dicts:{}};let t=this.i18n.locale||"en",e=this.i18n.dicts[t]||{};document.querySelectorAll("[data-i18n-key]").forEach(s=>{let i=s.getAttribute("data-i18n-key");if(!i)return;let o=i.split(".").reduce((A,v)=>A?A[v]:null,e);o==null&&(o=i);let f=s.getAttribute("data-i18n-params");if(f)try{let A=JSON.parse(f),v=D=>D.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");for(let D in A){let k=v(D);o=o.replace(new RegExp(`\\{\\{${k}\\}\\}`,"g"),A[D])}}catch{}s.tagName==="INPUT"||s.tagName==="TEXTAREA"?s.placeholder=o:s.textContent=o})}}function Q(w){w._initDragDrop=function(){typeof document>"u"||(this.addDomListener(document,"dragstart",t=>{let e=t.target.closest("[data-drag]");if(!e)return;let n=e.getAttribute("data-drag");n&&(t.dataTransfer.setData("text/plain",n),t.dataTransfer.effectAllowed="move",e.classList.add("dragging"))}),this.addDomListener(document,"dragend",t=>{let e=t.target.closest("[data-drag]");e&&e.classList.remove("dragging")}),this.addDomListener(document,"dragover",t=>{let e=t.target.closest("[data-drop]");e&&(t.preventDefault(),e.classList.add("drag-over"))}),this.addDomListener(document,"dragleave",t=>{let e=t.target.closest("[data-drop]");e&&e.classList.remove("drag-over")}),this.addDomListener(document,"drop",t=>{let e=t.target.closest("[data-drop]");if(!e)return;t.preventDefault(),e.classList.remove("drag-over");let n=e.getAttribute("data-drop"),s=t.dataTransfer.getData("text/plain");if(n&&s)try{let i=JSON.parse(s);this.publish(n,i)}catch{this.publish(n,{value:s})}}),this.addDomListener(document,"dragover",t=>{let e=t.target.closest("[data-sortable]");if(!e)return;t.preventDefault();let n=e.querySelector(".dragging");if(!n)return;let i=Array.from(e.querySelectorAll("[data-drag]:not(.dragging)")).find(o=>{let f=o.getBoundingClientRect();return t.clientY-f.top-f.height/2<0});i?e.insertBefore(n,i):e.appendChild(n)}),this.addDomListener(document,"drop",t=>{let e=t.target.closest("[data-sortable]");if(!e)return;let n=e.getAttribute("data-sortable");if(!n)return;let i=Array.from(e.querySelectorAll("[data-drag]")).map((o,f)=>{let A=o.getAttribute("data-drag");try{return{index:f,payload:JSON.parse(A||"{}")}}catch{return{index:f,payload:A}}});this.publish(n,i)}))}}function Z(w){w._initCollab=function(){if(typeof document>"u")return;let t=new Map,e=new Map,n=5e3;this.addDomListener(document,"mousemove",s=>{document.querySelectorAll("[data-rt-cursor-share]").forEach(o=>{let f=o.getAttribute("data-rt-cursor-share");if(!f)return;let A=o.getBoundingClientRect(),v=(s.clientX-A.left)/A.width,D=(s.clientY-A.top)/A.height,k=Date.now();(!o._lastSent||k-o._lastSent>50)&&(o._lastSent=k,this.pubPush(`collab/${f}/cursor/${this.deviceId}`,{deviceId:this.deviceId,x:v,y:D}))})}),this.addDomListener(document,"input",s=>{let i=s.target.getAttribute("data-rt-typing");if(!i)return;let o=i,f=A=>{this.pubPush(`collab/${o}/typing/${this.deviceId}`,{deviceId:this.deviceId,typing:A})};s.target._isTyping||(s.target._isTyping=!0,f(!0)),s.target._typingTimer&&clearTimeout(s.target._typingTimer),s.target._typingTimer=setTimeout(()=>{s.target._isTyping=!1,s.target._typingTimer=null,f(!1)},2e3)}),this.addDomListener(document,"input",s=>{let i=s.target.getAttribute("data-rt-crdt");if(!i)return;let o=i,f=s.target.value,A=Date.now();this.publish(`collab/${o}/crdt`,{deviceId:this.deviceId,value:f,timestamp:A,cursorPos:s.target.selectionStart})}),this.subscribe("collab/+/cursor/+",(s,i)=>{let o=i.split("/"),f=o[1],A=o[3];if(A===this.deviceId)return;let v=document.querySelector(`[data-rt-cursor-share="${f}"]`);if(!v)return;let D=`${f}::${A}`,k=t.get(D);(!k||!document.contains(k))&&(k=document.createElement("div"),k.className=`rt-cursor rt-cursor-${A}`,k.style.position="absolute",k.style.width="10px",k.style.height="10px",k.style.borderRadius="50%",k.style.backgroundColor="#"+Math.floor(Math.random()*16777215).toString(16).padStart(6,"0"),k.style.pointerEvents="none",v.appendChild(k),t.set(D,k));let $=v.getBoundingClientRect();k.style.left=s.x*$.width+"px",k.style.top=s.y*$.height+"px",e.has(D)&&clearTimeout(e.get(D)),e.set(D,setTimeout(()=>{let I=t.get(D);I&&I.parentNode&&I.parentNode.removeChild(I),t.delete(D),e.delete(D)},n))}),this.subscribe("collab/+/crdt",(s,i)=>{if(s.deviceId===this.deviceId)return;let f=i.split("/")[1];document.querySelectorAll(`[data-rt-crdt="${f}"]`).forEach(v=>{if(!v._lastUpdate||s.timestamp>v._lastUpdate){v._lastUpdate=s.timestamp;let D=v.selectionStart;v.value=s.value,document.activeElement===v&&v.setSelectionRange(D,D)}})}),this._collabCleanup=()=>{e.forEach(s=>clearTimeout(s)),e.clear(),t.forEach(s=>{s&&s.parentNode&&s.parentNode.removeChild(s)}),t.clear()}}}function G(w){w.registerServiceWorker=async function(t="/sw.js"){if(typeof navigator>"u"||!("serviceWorker"in navigator))return console.warn("[Dolphin PWA] Service Workers are not supported in this browser."),null;try{let e=await navigator.serviceWorker.register(t);return console.log("[Dolphin PWA] Service Worker registered successfully with scope:",e.scope),e}catch(e){return console.error("[Dolphin PWA] Service Worker registration failed:",e),null}},w.subscribePushNotifications=async function(t){if(typeof window>"u"||!("serviceWorker"in navigator)||!("PushManager"in window))return console.warn("[Dolphin PWA] Push notifications are not supported in this browser."),null;try{let e=await navigator.serviceWorker.ready,n=await e.pushManager.getSubscription();if(!n){let s="=".repeat((4-t.length%4)%4),i=(t+s).replace(/\-/g,"+").replace(/_/g,"/"),o=window.atob(i),f=new Uint8Array(o.length);for(let A=0;A<o.length;++A)f[A]=o.charCodeAt(A);n=await e.pushManager.subscribe({userVisibleOnly:!0,applicationServerKey:f})}return console.log("[Dolphin PWA] Subscribed to push notifications:",n),n}catch(e){return console.error("[Dolphin PWA] Push notification subscription failed:",e),null}}}function x(){if(typeof jest<"u"&&typeof jest.fn=="function")return jest.fn();let w=(...t)=>(w.mock.calls.push(t),w._implementation?w._implementation(...t):w._returnValue);return w.mock={calls:[]},w._returnValue=void 0,w._implementation=null,w.mockReturnValue=t=>(w._returnValue=t,w),w.mockImplementation=t=>(w._implementation=t,w),w}var H=class{static render(t){if(typeof document>"u")throw new Error("DolphinTestUtils.render requires a DOM document environment to execute.");let e=document.createElement("div");return e.innerHTML=t,document.body.appendChild(e),{container:e,find:n=>e.querySelector(n),fireEvent:(n,s)=>{let i=document.createEvent("Event");i.initEvent(s,!0,!0),n.dispatchEvent(i)}}}static mockWebSocket(){let t=[],e={readyState:1,send:n=>{t.push(n)},close:x(),onopen:x(),onmessage:x(),onclose:x(),onerror:x(),sentMessages:t};return global.WebSocket=class{static OPEN=1;readyState=e.readyState;send=e.send;close=e.close;set onopen(n){e.onopen=n}get onopen(){return e.onopen}set onmessage(n){e.onmessage=n}get onmessage(){return e.onmessage}set onclose(n){e.onclose=n}get getonclose(){return e.onclose}constructor(){setTimeout(()=>e.onopen&&e.onopen(),0)}},e}static simulateClick(t){let e={target:t,preventDefault:x(),stopPropagation:x()};(global.document._listeners?.click||[]).forEach(s=>s(e))}static simulateChange(t,e){t.value=e;let n={target:t,preventDefault:x(),stopPropagation:x()};(global.document._listeners?.change||[]).forEach(i=>i(n))}};function Y(w){w.testing=H}j(M.prototype);V(M.prototype);z(M.prototype);K(M.prototype);X(M.prototype);J(M.prototype);Q(M.prototype);Z(M.prototype);G(M.prototype);Y(M.prototype);typeof window<"u"&&(window.DolphinClient=M,document.addEventListener("DOMContentLoaded",()=>{if(!window.dolphin){let w=document.querySelector('script[src*="dolphin-client"]'),t=w?w.getAttribute("data-debug")==="true":!1,e=new M(void 0,void 0,{debug:t});window.dolphin=e,t&&(console.log("%c\u{1F42C} [Dolphin Client] Auto-initialized local reactive engine!","color: #06b6d4; font-weight: bold; font-size: 14px;"),console.log('%c\u{1F449} Tip: You can access the client instance via "window.dolphin" in console.',"color: #94a3b8; font-style: italic;")),document.querySelector('[data-store-write="app.username"]')&&e.setStoreState("app","username","\u0928\u092E\u0938\u094D\u0924\u0947 \u0938\u093E\u0925\u0940!")}}));return ct(ut);})();