modelence 0.25.0 → 0.25.1

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.
Files changed (40) hide show
  1. package/README.md +4 -0
  2. package/dist/bin/modelence.js +1 -1
  3. package/dist/bin/modelence.js.map +1 -1
  4. package/dist/{chunk-BVJJCQ6Y.js → chunk-6CIFSSQP.js} +4 -4
  5. package/dist/chunk-6CIFSSQP.js.map +1 -0
  6. package/dist/{chunk-FXPFIA66.js → chunk-DAV46WE7.js} +3 -3
  7. package/dist/{chunk-FXPFIA66.js.map → chunk-DAV46WE7.js.map} +1 -1
  8. package/dist/{chunk-7JUFVY6Q.js → chunk-FF6FEX7U.js} +2 -2
  9. package/dist/{chunk-7JUFVY6Q.js.map → chunk-FF6FEX7U.js.map} +1 -1
  10. package/dist/{chunk-J3ZZEZIV.js → chunk-IKIOVFVD.js} +13 -13
  11. package/dist/chunk-IKIOVFVD.js.map +1 -0
  12. package/dist/chunk-K4PI6L5V.js +2 -0
  13. package/dist/chunk-K4PI6L5V.js.map +1 -0
  14. package/dist/{chunk-VKGZ35WJ.js → chunk-KJBMQRY6.js} +2 -2
  15. package/dist/{chunk-VKGZ35WJ.js.map → chunk-KJBMQRY6.js.map} +1 -1
  16. package/dist/{chunk-7MIBHVZS.js → chunk-NAWQYPGM.js} +3 -3
  17. package/dist/{chunk-7MIBHVZS.js.map → chunk-NAWQYPGM.js.map} +1 -1
  18. package/dist/{chunk-CAN2CWEI.js → chunk-S5OQYKNR.js} +2 -2
  19. package/dist/{chunk-CAN2CWEI.js.map → chunk-S5OQYKNR.js.map} +1 -1
  20. package/dist/client.js +1 -1
  21. package/dist/{package-PKGSNHLQ.js → package-GGPYIET6.js} +2 -2
  22. package/dist/{package-PKGSNHLQ.js.map → package-GGPYIET6.js.map} +1 -1
  23. package/dist/{render-GH7MWT27.js → render-WY23X5RN.js} +2 -2
  24. package/dist/{render-GH7MWT27.js.map → render-WY23X5RN.js.map} +1 -1
  25. package/dist/renderApp-FRZBJICP.js +2 -0
  26. package/dist/{renderApp-5P62J4NO.js.map → renderApp-FRZBJICP.js.map} +1 -1
  27. package/dist/server-J75POKU5.js +2 -0
  28. package/dist/{server-LBKWH4I3.js.map → server-J75POKU5.js.map} +1 -1
  29. package/dist/server.d.ts +3 -1
  30. package/dist/server.js +1 -1
  31. package/dist/transport-RJFMTIDK.js +2 -0
  32. package/dist/{transport-QMFZ67HR.js.map → transport-RJFMTIDK.js.map} +1 -1
  33. package/package.json +1 -1
  34. package/dist/chunk-5M6FUMUK.js +0 -2
  35. package/dist/chunk-5M6FUMUK.js.map +0 -1
  36. package/dist/chunk-BVJJCQ6Y.js.map +0 -1
  37. package/dist/chunk-J3ZZEZIV.js.map +0 -1
  38. package/dist/renderApp-5P62J4NO.js +0 -2
  39. package/dist/server-LBKWH4I3.js +0 -2
  40. package/dist/transport-QMFZ67HR.js +0 -2
@@ -0,0 +1,2 @@
1
+ function f(n){return typeof n=="object"&&n!==null&&"toHexString"in n&&typeof n.toHexString=="function"}function u(n){if(n==null||typeof n!="object")return n;if(f(n))return n.toHexString();if(n instanceof Date)return n;if(Array.isArray(n)){let e=null;for(let t=0;t<n.length;t++){let r=n[t];if(r===null||typeof r!="object"){e!==null&&e.push(r);continue}let i=u(r);i!==r?(e===null&&(e=n.slice(0,t)),e.push(i)):e!==null&&e.push(r);}return e!==null?e:n}let o=null;for(let[e,t]of Object.entries(n)){if(t===null||typeof t!="object"){o!==null&&(o[e]=t);continue}let r=u(t);r!==t&&(o===null&&(o={...n}),o[e]=r);}return o!==null?o:n}function s(n){if(n instanceof Date)return {type:"date"};if(Array.isArray(n)){let o={};for(let e=0;e<n.length;e++){let t=n[e],r=s(t);r&&(o[e]=r);}return Object.keys(o).length>0?{type:"array",elements:o}:null}if(typeof n=="object"&&n!==null){let o={};for(let[e,t]of Object.entries(n)){let r=s(t);r&&(o[e]=r);}return Object.keys(o).length>0?{type:"object",props:o}:null}return null}function c(n,o){return !o||n==null?n:o.type==="date"?new Date(n):o.type==="array"?Array.isArray(n)?n.map((e,t)=>c(e,o.elements?.[t])):n:o.type==="object"?typeof n!="object"||n===null?n:Object.fromEntries(Object.entries(n).map(([e,t])=>[e,c(t,o.props?.[e])])):n}export{u as a,s as b,c};//# sourceMappingURL=chunk-K4PI6L5V.js.map
2
+ //# sourceMappingURL=chunk-K4PI6L5V.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/methods/serialize.ts"],"names":["isObjectId","value","sanitizeResult","result","out","i","item","sanitized","key","getResponseTypeMap","elements","subTypeMap","props","reviveResponseTypes","data","typeMap","index"],"mappings":"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","file":"chunk-K4PI6L5V.js","sourcesContent":["function isObjectId(value: unknown): value is { toHexString(): string } {\n return (\n typeof value === 'object' &&\n value !== null &&\n 'toHexString' in value &&\n typeof (value as Record<string, unknown>).toHexString === 'function'\n );\n}\n\n/**\n * Recursively converts all MongoDB ObjectId instances to hex strings.\n * Uses duck typing (checks for toHexString method) to avoid importing mongodb on the client.\n * Returns the original input reference unchanged when no ObjectId is present (no allocation).\n */\nexport function sanitizeResult(result: unknown): unknown {\n if (result == null || typeof result !== 'object') {\n return result;\n }\n\n if (isObjectId(result)) {\n return result.toHexString();\n }\n\n if (result instanceof Date) {\n return result;\n }\n\n if (Array.isArray(result)) {\n let out: unknown[] | null = null;\n for (let i = 0; i < result.length; i++) {\n const item = result[i];\n // Primitives and null can never contain an ObjectId — skip recursion.\n if (item === null || typeof item !== 'object') {\n if (out !== null) out.push(item);\n continue;\n }\n const sanitized = sanitizeResult(item);\n if (sanitized !== item) {\n if (out === null) {\n // Copy-on-first-write: preserve all preceding elements.\n out = result.slice(0, i);\n }\n out.push(sanitized);\n } else if (out !== null) {\n out.push(item);\n }\n }\n return out !== null ? out : result;\n }\n\n let out: Record<string, unknown> | null = null;\n for (const [key, value] of Object.entries(result as Record<string, unknown>)) {\n if (value === null || typeof value !== 'object') {\n if (out !== null) out[key] = value;\n continue;\n }\n const sanitized = sanitizeResult(value);\n if (sanitized !== value) {\n if (out === null) {\n out = { ...(result as Record<string, unknown>) };\n }\n out[key] = sanitized;\n }\n }\n return out !== null ? out : result;\n}\n\nexport function getResponseTypeMap(result: unknown) {\n if (result instanceof Date) {\n return { type: 'date' };\n }\n\n if (Array.isArray(result)) {\n const elements: Record<string, unknown> = {};\n for (let i = 0; i < result.length; i++) {\n const item = result[i];\n const subTypeMap = getResponseTypeMap(item);\n if (subTypeMap) {\n elements[i] = subTypeMap;\n }\n }\n return Object.keys(elements).length > 0\n ? {\n type: 'array',\n elements,\n }\n : null;\n }\n\n if (typeof result === 'object' && result !== null) {\n const props: Record<string, unknown> = {};\n for (const [key, value] of Object.entries(result)) {\n const subTypeMap = getResponseTypeMap(value);\n if (subTypeMap) {\n props[key] = subTypeMap;\n }\n }\n return Object.keys(props).length > 0\n ? {\n type: 'object',\n props,\n }\n : null;\n }\n\n return null;\n}\n\nexport function reviveResponseTypes<T = unknown>(data: T, typeMap?: Record<string, unknown>): T {\n if (!typeMap || data == null) {\n return data;\n }\n\n if (typeMap.type === 'date') {\n return new Date(data as string) as T;\n }\n\n if (typeMap.type === 'array') {\n if (!Array.isArray(data)) {\n return data;\n }\n return (data as unknown[]).map((item: unknown, index: number) =>\n reviveResponseTypes(\n item,\n (typeMap.elements as Record<string, unknown>)?.[index] as\n | Record<string, unknown>\n | undefined\n )\n ) as T;\n }\n\n if (typeMap.type === 'object') {\n if (typeof data !== 'object' || data === null) {\n return data;\n }\n return Object.fromEntries(\n Object.entries(data as Record<string, unknown>).map(([key, value]) => [\n key,\n reviveResponseTypes(\n value,\n (typeMap.props as Record<string, unknown>)?.[key] as Record<string, unknown>\n ),\n ])\n ) as T;\n }\n\n return data;\n}\n"]}
@@ -1,2 +1,2 @@
1
- import {c}from'./chunk-5M6FUMUK.js';import {a as a$1}from'./chunk-DO5TZLF5.js';import Qe from'socket.io-client';import {create}from'zustand';import {z as z$1}from'zod';import {hashKey}from'@tanstack/react-query';var ee={},$=null;function Ye(e){$=e;}function Je(e){return typeof window>"u"&&$?$(e):ee[e]?.value}function A(e){ee=e;}var K="modelence.session";function j(){return typeof globalThis<"u"&&typeof globalThis.localStorage<"u"}function M(){if(!j())return null;let e=globalThis.localStorage.getItem(K);try{return e?JSON.parse(e):null}catch(n){return console.error("Error parsing session from localStorage",n),null}}function w(e){j()&&globalThis.localStorage.setItem(K,JSON.stringify(e));}function ne(){j()&&globalThis.localStorage.removeItem(K);}var te=null;function Xe(e){te=e;}function d(){return te}var re=(e,n)=>{console.error(`Error calling method '${n}':`,e);};function en(e){re=e;}function oe(e,n){return re(e,n)}var D=class extends Error{constructor(n,t,r){super(n),this.name="MethodError",this.status=t,this.code=r;}},Te=async(e,n)=>{let t=d()?.baseUrl??"";return Ce(`${t}/api/_internal/method/${e}`,n)},O="__modelence_call_method_transport__";function ke(){return globalThis[O]??Te}function an(e){let n=globalThis[O];return globalThis[O]=e,()=>{globalThis[O]=n;}}async function a(e,n,t){n=n??{},t=t??{};try{return await ke()(e,n)}catch(r){throw (t.errorHandler??oe)(r,e),r}}async function Ce(e,n){let t=await fetch(e,{method:"POST",credentials:d()?.credentials??"include",headers:{"Content-Type":"application/json"},body:JSON.stringify({args:n,authToken:h(),clientInfo:T()})});if(!t.ok){let i=await t.text(),s=t.headers?.get("X-Modelence-Error-Code")??void 0;throw new D(i,t.status,s)}let r=await t.text(),o=r?JSON.parse(r):void 0;if(!o)throw new Error("Invalid response from server");return c(o.data,o.typeMap)}var V=null;function ie(e){V=e;}function un(){return V}function ae(e){if(V){console.warn("WebSocket already initialized. Skipping initialization.");return}let n=e?.provider||se;ie(n);try{n.init({channels:e?.channels});}catch(t){throw ie(null),t}}var g=null,R=null,z=false,p=new Map;function Se(e){g!==e&&(g&&xe(),g=e,R=e.getQueryCache().subscribe(n=>{if(n.type==="removed"){let t=hashKey(n.query.queryKey),r=p.get(t);if(r){if(r.resolvers.size>0){let o=new Error("Query was removed from cache");r.resolvers.forEach(i=>i.reject(o)),r.resolvers.clear();}r.unsubscribe(),p.delete(t);}}}));}function mn(){return g!==null}function xe(){R&&(R(),R=null),p.forEach(e=>e.unsubscribe()),p.clear(),g=null,z=false;}function ue(){g&&g.invalidateQueries();}var le=class{connect(n){Se(n);}};function wn(e,n={}){return {queryKey:[e,n],queryFn:()=>a(e,n)}}function yn(e,n={}){let t=["live",e,n],r=hashKey(t);return {queryKey:t,queryFn:()=>new Promise((o,i)=>{if(typeof window>"u")return;if(!g){let l=new Error("Modelence: connect a QueryClient before using modelenceLiveQuery(). Mount <ModelenceQueryProvider> or call connectModelenceQueryClient().");console.error("[Modelence]",l.message),i(l);return}z||(ae(),z=true);let s=p.get(r);s||(s={unsubscribe:q(e,n,c=>{let u=p.get(r);u?.resolvers.size&&(u.resolvers.forEach(f=>f.resolve(c)),u.resolvers.clear()),g&&g.setQueryData(t,c);},c=>{let u=p.get(r);u&&(u.resolvers.size&&(u.resolvers.forEach(f=>f.reject(new Error(c))),u.resolvers.clear()),u.unsubscribe(),p.delete(r));}),resolvers:new Set},p.set(r,s)),s.resolvers.add({resolve:o,reject:i});}),staleTime:1/0,refetchOnWindowFocus:false,refetchOnMount:false,refetchOnReconnect:false,gcTime:0}}function vn(e,n={}){return {mutationFn:(t={})=>a(e,{...n,...t})}}function bn(e,n={}){return [e,n]}var y=create(e=>({user:null,setUser:n=>e({user:n})})),C=false,I=false,Pe=a$1.seconds(30),k=null,Ee=z$1.object({id:z$1.string(),handle:z$1.string(),roles:z$1.array(z$1.string()),firstName:z$1.string().optional(),lastName:z$1.string().optional(),avatarUrl:z$1.string().optional()});function v(e){if(!e)return null;let n=Ee.safeParse(e);if(!n.success)return console.error("Session Error: Invalid user payload",n.error),null;let t=n.data;return Object.freeze({...t,firstName:t.firstName??void 0,lastName:t.lastName??void 0,avatarUrl:t.avatarUrl??void 0,hasRole:r=>t.roles.includes(r),requireRole:r=>{if(!t.roles.includes(r))throw new Error(`Access denied - role '${r}' required`)}})}var Y=false;function Mn(){return Y}function On(e){if(C)return;C=true,Y=!!e.setupRequired,A(e.configs);let t=M()?.authToken,r=e.session;if(t&&!e.user&&t!==r.authToken){I=true,y.getState().setUser(v(e.user));return}w(e.session),y.getState().setUser(v(e.user));}async function Rn(){if(I){I=false;try{let{configs:e,session:n,user:t}=await a("_system.session.init");A(e),w(n),y.getState().setUser(v(t));}catch(e){console.error("Modelence: session reconciliation failed",e);}}}function In(){return I}function de(e){let{configs:n,session:t,user:r}=e;Y=!!e.setupRequired,A(n);let o=d();o?o.setAuthToken(t.authToken):w(t),y.getState().setUser(v(r));}async function _n(){if(C)return;C=true;let e=await a("_system.session.init");de(e),await _();}async function Wn(){k!==null&&(clearTimeout(k),k=null);try{let e=await a("_system.session.init");de(e),ue();}catch(e){console.error("Modelence: session revalidation failed on pageshow",e);}finally{_();}}async function Ln(){typeof window>"u"||k!==null||await _();}async function _(){if(!(typeof window>"u")){try{await a("_system.session.heartbeat",{},{errorHandler:()=>{}});}catch{}k=setTimeout(_,Pe);}}function W(e){let n=v(e);return y.getState().setUser(n),n}function Nn(){return C}var F=null;function Qn(e){F=e;}function Hn(e){return v(e)}function $n(){return typeof window>"u"&&F?{user:F()}:{user:y(n=>n.user)}}var fe="modelence:oauth-code",ge="modelence:oauth-code-ack";function pe(){let e=globalThis.window;return Ae(e)?e:null}function Ae(e){if(typeof e!="object"||e===null)return false;let n=e;return typeof n.addEventListener=="function"&&typeof n.removeEventListener=="function"&&typeof n.location?.origin=="string"}function N(e){return typeof e=="object"&&e!==null&&typeof e.postMessage=="function"}function Me(e){if(typeof e!="object"||e===null)return false;let n=e;return n.type===fe&&typeof n.code=="string"&&n.code.length>0}function Oe(e){if(typeof e!="object"||e===null)return false;let n=e;return n.type===ge&&typeof n.accepted=="boolean"}var J=null;function he(e,n,t){L();let r=pe();if(!r)return;let o=r.location.origin,i=s=>{if(s.source!==e||s.origin!==o||!Me(s.data))return;L();let{code:l}=s.data,c={type:ge,accepted:true};try{e.postMessage(c,o);}catch{}Promise.resolve().then(()=>n(l)).catch(u=>t?.(u)).finally(()=>Re(e));};r.addEventListener("message",i),J=()=>r.removeEventListener("message",i);}function Re(e){try{e.close?.();}catch{}}function L(){J?.(),J=null;}function me(e){let n=pe(),t=n?.opener;if(!n||!N(t))return Promise.resolve(false);let r=n.location.origin;return new Promise(o=>{let i=false,s=f=>{i||(i=true,clearTimeout(c),n.removeEventListener("message",l),o(f));},l=f=>{f.source===t&&f.origin===r&&Oe(f.data)&&s(f.data.accepted);},c=setTimeout(()=>s(false),3e3);n.addEventListener("message",l);let u={type:fe,code:e};try{t.postMessage(u,r);}catch{s(false);}})}var we="modelence-oauth";var b=null,S="modelence.oauth.verifier";function Q(){try{let e=globalThis.sessionStorage;if(!e)return null;let n=`${S}.probe`;return e.setItem(n,"1"),e.removeItem(n),e}catch{return null}}function Ie(e){let n=new Uint8Array(e),t=globalThis.crypto;if(t?.getRandomValues)t.getRandomValues(n);else for(let o=0;o<n.length;o++)n[o]=Math.floor(Math.random()*256);let r="";for(let o of n)r+=o.toString(16).padStart(2,"0");return r}function ye(){b=Ie(32);try{Q()?.setItem(S,b);}catch{}return b}function B(){if(b!==null)return true;try{return !!Q()?.getItem(S)}catch{return false}}function ve(){let e=b??Q()?.getItem(S)??null;return _e(),e}function _e(){b=null;try{Q()?.removeItem(S);}catch{}}function We(e){let n=d();n?n.setAuthToken(e.authToken):w(e);}function H(e){return We(e.session),W(e.user)}async function Bn(e){let{email:n,password:t,handle:r,firstName:o,lastName:i,avatarUrl:s}=e;await a("_system.user.signupWithPassword",{email:n,password:t,...r!==void 0?{handle:r}:{},...o!==void 0?{firstName:o}:{},...i!==void 0?{lastName:i}:{},...s!==void 0?{avatarUrl:s}:{}});}async function Gn(e){let{email:n,password:t}=e,r=await a("_system.user.loginWithPassword",{email:n,password:t});return H(r)}async function Xn(e){let{firstName:n,lastName:t,avatarUrl:r,handle:o}=e,{user:i}=await a("_system.user.updateProfile",{...n!==void 0?{firstName:n}:{},...t!==void 0?{lastName:t}:{},...r!==void 0?{avatarUrl:r}:{},...o!==void 0?{handle:o}:{}});return W(i)}async function Zn(e){let{token:n}=e;await a("_system.user.verifyEmail",{token:n});}async function et(e){let{email:n}=e;await a("_system.user.resendEmailVerification",{email:n});}async function nt(){await a("_system.user.logout"),ne();let e=d();e&&e.setAuthToken(null),W(null);}async function tt(e){let{email:n}=e;await a("_system.user.sendResetPasswordToken",{email:n});}async function rt(e){let{email:n}=e;await a("_system.user.sendMagicLink",{email:n});}async function ot(){let e=await a("_system.user.loginWithMagicLink");return H(e)}async function it(e){let{email:n,code:t}=e,r=await a("_system.user.loginWithOneTimeCode",{email:n,code:t});return H(r)}async function st(e){let{token:n,password:t}=e;await a("_system.user.resetPassword",{...n?{token:n}:{},password:t});}async function at(e){let{provider:n,redirectUri:t}=e,r=d(),o=r?.baseUrl??"";if(t){if(!r?.openUrl)throw new Error("signInWithOAuth was given a redirectUri but the client has no openUrl. Configure openUrl (e.g. (url) => Linking.openURL(url)) to use the native flow.");let s=ye(),l=`${o}/api/_internal/auth/${n}?mode=login&platform=mobile&redirectUri=${encodeURIComponent(t)}&codeChallenge=${encodeURIComponent(s)}`,c=r.openUrl(l);if(N(c)){try{c.name=we;}catch{}be(c);return}if(c===null&&typeof window<"u")throw new Error("signInWithOAuth could not open the sign-in popup \u2014 the browser blocked it. Call signInWithOAuth directly from a click or other user gesture, or allow popups for this site.");return}let i=`${o}/api/_internal/auth/${n}?mode=login`;if(r?.openUrl){r.openUrl(i);return}window.location.href=i;}function be(e){he(e,G,n=>{console.error("[modelence] Failed to complete the OAuth sign-in in the opening page.",n);});}function Le(e){return B()?(be(e),true):false}async function G(e){let n=ve();if(!n)throw Ne();let t=await a("_system.user.loginWithOAuth",{code:e,codeVerifier:n});return H(t)}function Ne(){return console.error("[modelence] loginWithOAuth was called with no sign-in in progress. Either signInWithOAuth was never called on this client, or the code came from somewhere other than a flow this client started. On native, the app process must survive the round trip; in a browser the verifier is kept in sessionStorage, so a new tab or a cleared session also produces this. If the app runs in an iframe and opens the provider in a popup, openUrl must return the window from window.open so the popup can hand the code back to that page \u2014 and note that a provider sending Cross-Origin-Opener-Policy: same-origin severs window.opener during the round trip, which breaks that handoff with no way for this code to tell it apart from the cases above. A plain web app that never calls signInWithOAuth({ redirectUri }) does not need loginWithOAuth at all \u2014 the cookie flow signs the user in on its own."),new Error("This sign-in link is no longer valid. Please sign in again.")}async function lt(e){let{code:n}=e;return B()?G(n):await me(n)?null:G(n)}function ct(e){let{popup:n}=e;return N(n)?Le(n):false}function ut(){L();}async function dt(e){let{provider:n,redirectUri:t}=e,r=d(),o=r?.baseUrl??"";if(t){if(!r?.openUrl)throw new Error("linkOAuthProvider was given a redirectUri but the client has no openUrl. Configure openUrl (e.g. (url) => Linking.openURL(url)) to use the native flow.");let i=h();if(!i)throw new Error("Failed to initialize OAuth linking. Please ensure you are logged in.");let s=await fetch(`${o}/api/_internal/auth/issue-link-nonce`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({authToken:i})});if(!s.ok)throw new Error("Failed to initialize OAuth linking. Please ensure you are logged in.");let{nonce:l}=await s.json(),c=`${o}/api/_internal/auth/${n}?mode=link&linkNonce=${encodeURIComponent(l)}&platform=mobile&redirectUri=${encodeURIComponent(t)}`;r.openUrl(c);}else {let i=h();if(i&&!(await fetch(`${o}/api/_internal/auth/set-link-cookie`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({authToken:i}),credentials:"include"})).ok)throw new Error("Failed to initialize OAuth linking. Please ensure you are logged in.");window.location.href=`${o}/api/_internal/auth/${n}?mode=link`;}}async function ft(e){let{provider:n}=e;await a("_system.user.unlinkOAuthProvider",{provider:n});}function h(){let e=d();return e?e.getAuthToken():M()?.authToken}function T(){let e=d();return e?e.getClientInfo():typeof window>"u"?{screenWidth:0,screenHeight:0,windowWidth:0,windowHeight:0,pixelRatio:1,orientation:null}:{screenWidth:window.screen.width,screenHeight:window.screen.height,windowWidth:window.innerWidth,windowHeight:window.innerHeight,pixelRatio:window.devicePixelRatio,orientation:window.screen.orientation?.type??null}}var x=null,U=new Map;function P(){if(!x)throw new Error("WebSocket not initialized. Call startWebsockets() first.");return x}function He(){let e=h(),n=T();for(let t of U.values())x?.emit("subscribeLiveQuery",{subscriptionId:t.subscriptionId,method:t.method,args:t.args,authToken:e,clientInfo:n});}function $e(e){let n=d()?.baseUrl??"/";x=Qe(n,{transports:["websocket"],auth:{token:h()}}),x.on("connect",()=>{U.size>0&&(console.log(`[Modelence] WebSocket reconnected, re-subscribing to ${U.size} live queries`),He());}),e.channels?.forEach(t=>t.init());}function Ke({category:e,listener:n}){P().on(e,n);}function je({category:e,listener:n}){P().once(e,n);}function De({category:e,listener:n}){P().off(e,n);}function X({eventName:e,category:n,id:t}){P().emit(e,`${n}:${t}`);}function qe({category:e,id:n}){X({eventName:"joinChannel",category:e,id:n});}function Ve({category:e,id:n}){X({eventName:"leaveChannel",category:e,id:n});}var ze=0;function q(e,n,t,r){let o=`sub-${++ze}-${Date.now()}`,i=({subscriptionId:c$1,data:u,typeMap:f})=>{c$1===o&&t(c(u,f));},s=({subscriptionId:c,error:u})=>{c===o&&(console.error(`[Modelence] Live query error for ${e}:`,u),r?.(u));},l=P();return l.on("liveQueryData",i),l.on("liveQueryError",s),U.set(o,{subscriptionId:o,method:e,args:n}),l.connected&&l.emit("subscribeLiveQuery",{subscriptionId:o,method:e,args:n,authToken:h(),clientInfo:T()}),()=>{U.delete(o),l.emit("unsubscribeLiveQuery",{subscriptionId:o}),l.off("liveQueryData",i),l.off("liveQueryError",s);}}var Fe={init:$e,on:Ke,once:je,off:De,emit:X,joinChannel:qe,leaveChannel:Ve},se=Fe;export{$n as A,Bn as B,Gn as C,Xn as D,Zn as E,et as F,nt as G,tt as H,rt as I,ot as J,it as K,st as L,at as M,lt as N,ct as O,ut as P,dt as Q,ft as R,en as S,D as T,Te as U,an as V,a as W,Ye as a,Je as b,M as c,Xe as d,q as e,ie as f,un as g,ae as h,Se as i,mn as j,xe as k,le as l,wn as m,yn as n,vn as o,bn as p,Mn as q,On as r,Rn as s,In as t,_n as u,Wn as v,Ln as w,Nn as x,Qn as y,Hn as z};//# sourceMappingURL=chunk-VKGZ35WJ.js.map
2
- //# sourceMappingURL=chunk-VKGZ35WJ.js.map
1
+ import {c}from'./chunk-K4PI6L5V.js';import {a as a$1}from'./chunk-DO5TZLF5.js';import Qe from'socket.io-client';import {create}from'zustand';import {z as z$1}from'zod';import {hashKey}from'@tanstack/react-query';var ee={},$=null;function Ye(e){$=e;}function Je(e){return typeof window>"u"&&$?$(e):ee[e]?.value}function A(e){ee=e;}var K="modelence.session";function j(){return typeof globalThis<"u"&&typeof globalThis.localStorage<"u"}function M(){if(!j())return null;let e=globalThis.localStorage.getItem(K);try{return e?JSON.parse(e):null}catch(n){return console.error("Error parsing session from localStorage",n),null}}function w(e){j()&&globalThis.localStorage.setItem(K,JSON.stringify(e));}function ne(){j()&&globalThis.localStorage.removeItem(K);}var te=null;function Xe(e){te=e;}function d(){return te}var re=(e,n)=>{console.error(`Error calling method '${n}':`,e);};function en(e){re=e;}function oe(e,n){return re(e,n)}var D=class extends Error{constructor(n,t,r){super(n),this.name="MethodError",this.status=t,this.code=r;}},Te=async(e,n)=>{let t=d()?.baseUrl??"";return Ce(`${t}/api/_internal/method/${e}`,n)},O="__modelence_call_method_transport__";function ke(){return globalThis[O]??Te}function an(e){let n=globalThis[O];return globalThis[O]=e,()=>{globalThis[O]=n;}}async function a(e,n,t){n=n??{},t=t??{};try{return await ke()(e,n)}catch(r){throw (t.errorHandler??oe)(r,e),r}}async function Ce(e,n){let t=await fetch(e,{method:"POST",credentials:d()?.credentials??"include",headers:{"Content-Type":"application/json"},body:JSON.stringify({args:n,authToken:h(),clientInfo:T()})});if(!t.ok){let i=await t.text(),s=t.headers?.get("X-Modelence-Error-Code")??void 0;throw new D(i,t.status,s)}let r=await t.text(),o=r?JSON.parse(r):void 0;if(!o)throw new Error("Invalid response from server");return c(o.data,o.typeMap)}var V=null;function ie(e){V=e;}function un(){return V}function ae(e){if(V){console.warn("WebSocket already initialized. Skipping initialization.");return}let n=e?.provider||se;ie(n);try{n.init({channels:e?.channels});}catch(t){throw ie(null),t}}var g=null,R=null,z=false,p=new Map;function Se(e){g!==e&&(g&&xe(),g=e,R=e.getQueryCache().subscribe(n=>{if(n.type==="removed"){let t=hashKey(n.query.queryKey),r=p.get(t);if(r){if(r.resolvers.size>0){let o=new Error("Query was removed from cache");r.resolvers.forEach(i=>i.reject(o)),r.resolvers.clear();}r.unsubscribe(),p.delete(t);}}}));}function mn(){return g!==null}function xe(){R&&(R(),R=null),p.forEach(e=>e.unsubscribe()),p.clear(),g=null,z=false;}function ue(){g&&g.invalidateQueries();}var le=class{connect(n){Se(n);}};function wn(e,n={}){return {queryKey:[e,n],queryFn:()=>a(e,n)}}function yn(e,n={}){let t=["live",e,n],r=hashKey(t);return {queryKey:t,queryFn:()=>new Promise((o,i)=>{if(typeof window>"u")return;if(!g){let l=new Error("Modelence: connect a QueryClient before using modelenceLiveQuery(). Mount <ModelenceQueryProvider> or call connectModelenceQueryClient().");console.error("[Modelence]",l.message),i(l);return}z||(ae(),z=true);let s=p.get(r);s||(s={unsubscribe:q(e,n,c=>{let u=p.get(r);u?.resolvers.size&&(u.resolvers.forEach(f=>f.resolve(c)),u.resolvers.clear()),g&&g.setQueryData(t,c);},c=>{let u=p.get(r);u&&(u.resolvers.size&&(u.resolvers.forEach(f=>f.reject(new Error(c))),u.resolvers.clear()),u.unsubscribe(),p.delete(r));}),resolvers:new Set},p.set(r,s)),s.resolvers.add({resolve:o,reject:i});}),staleTime:1/0,refetchOnWindowFocus:false,refetchOnMount:false,refetchOnReconnect:false,gcTime:0}}function vn(e,n={}){return {mutationFn:(t={})=>a(e,{...n,...t})}}function bn(e,n={}){return [e,n]}var y=create(e=>({user:null,setUser:n=>e({user:n})})),C=false,I=false,Pe=a$1.seconds(30),k=null,Ee=z$1.object({id:z$1.string(),handle:z$1.string(),roles:z$1.array(z$1.string()),firstName:z$1.string().optional(),lastName:z$1.string().optional(),avatarUrl:z$1.string().optional()});function v(e){if(!e)return null;let n=Ee.safeParse(e);if(!n.success)return console.error("Session Error: Invalid user payload",n.error),null;let t=n.data;return Object.freeze({...t,firstName:t.firstName??void 0,lastName:t.lastName??void 0,avatarUrl:t.avatarUrl??void 0,hasRole:r=>t.roles.includes(r),requireRole:r=>{if(!t.roles.includes(r))throw new Error(`Access denied - role '${r}' required`)}})}var Y=false;function Mn(){return Y}function On(e){if(C)return;C=true,Y=!!e.setupRequired,A(e.configs);let t=M()?.authToken,r=e.session;if(t&&!e.user&&t!==r.authToken){I=true,y.getState().setUser(v(e.user));return}w(e.session),y.getState().setUser(v(e.user));}async function Rn(){if(I){I=false;try{let{configs:e,session:n,user:t}=await a("_system.session.init");A(e),w(n),y.getState().setUser(v(t));}catch(e){console.error("Modelence: session reconciliation failed",e);}}}function In(){return I}function de(e){let{configs:n,session:t,user:r}=e;Y=!!e.setupRequired,A(n);let o=d();o?o.setAuthToken(t.authToken):w(t),y.getState().setUser(v(r));}async function _n(){if(C)return;C=true;let e=await a("_system.session.init");de(e),await _();}async function Wn(){k!==null&&(clearTimeout(k),k=null);try{let e=await a("_system.session.init");de(e),ue();}catch(e){console.error("Modelence: session revalidation failed on pageshow",e);}finally{_();}}async function Ln(){typeof window>"u"||k!==null||await _();}async function _(){if(!(typeof window>"u")){try{await a("_system.session.heartbeat",{},{errorHandler:()=>{}});}catch{}k=setTimeout(_,Pe);}}function W(e){let n=v(e);return y.getState().setUser(n),n}function Nn(){return C}var F=null;function Qn(e){F=e;}function Hn(e){return v(e)}function $n(){return typeof window>"u"&&F?{user:F()}:{user:y(n=>n.user)}}var fe="modelence:oauth-code",ge="modelence:oauth-code-ack";function pe(){let e=globalThis.window;return Ae(e)?e:null}function Ae(e){if(typeof e!="object"||e===null)return false;let n=e;return typeof n.addEventListener=="function"&&typeof n.removeEventListener=="function"&&typeof n.location?.origin=="string"}function N(e){return typeof e=="object"&&e!==null&&typeof e.postMessage=="function"}function Me(e){if(typeof e!="object"||e===null)return false;let n=e;return n.type===fe&&typeof n.code=="string"&&n.code.length>0}function Oe(e){if(typeof e!="object"||e===null)return false;let n=e;return n.type===ge&&typeof n.accepted=="boolean"}var J=null;function he(e,n,t){L();let r=pe();if(!r)return;let o=r.location.origin,i=s=>{if(s.source!==e||s.origin!==o||!Me(s.data))return;L();let{code:l}=s.data,c={type:ge,accepted:true};try{e.postMessage(c,o);}catch{}Promise.resolve().then(()=>n(l)).catch(u=>t?.(u)).finally(()=>Re(e));};r.addEventListener("message",i),J=()=>r.removeEventListener("message",i);}function Re(e){try{e.close?.();}catch{}}function L(){J?.(),J=null;}function me(e){let n=pe(),t=n?.opener;if(!n||!N(t))return Promise.resolve(false);let r=n.location.origin;return new Promise(o=>{let i=false,s=f=>{i||(i=true,clearTimeout(c),n.removeEventListener("message",l),o(f));},l=f=>{f.source===t&&f.origin===r&&Oe(f.data)&&s(f.data.accepted);},c=setTimeout(()=>s(false),3e3);n.addEventListener("message",l);let u={type:fe,code:e};try{t.postMessage(u,r);}catch{s(false);}})}var we="modelence-oauth";var b=null,S="modelence.oauth.verifier";function Q(){try{let e=globalThis.sessionStorage;if(!e)return null;let n=`${S}.probe`;return e.setItem(n,"1"),e.removeItem(n),e}catch{return null}}function Ie(e){let n=new Uint8Array(e),t=globalThis.crypto;if(t?.getRandomValues)t.getRandomValues(n);else for(let o=0;o<n.length;o++)n[o]=Math.floor(Math.random()*256);let r="";for(let o of n)r+=o.toString(16).padStart(2,"0");return r}function ye(){b=Ie(32);try{Q()?.setItem(S,b);}catch{}return b}function B(){if(b!==null)return true;try{return !!Q()?.getItem(S)}catch{return false}}function ve(){let e=b??Q()?.getItem(S)??null;return _e(),e}function _e(){b=null;try{Q()?.removeItem(S);}catch{}}function We(e){let n=d();n?n.setAuthToken(e.authToken):w(e);}function H(e){return We(e.session),W(e.user)}async function Bn(e){let{email:n,password:t,handle:r,firstName:o,lastName:i,avatarUrl:s}=e;await a("_system.user.signupWithPassword",{email:n,password:t,...r!==void 0?{handle:r}:{},...o!==void 0?{firstName:o}:{},...i!==void 0?{lastName:i}:{},...s!==void 0?{avatarUrl:s}:{}});}async function Gn(e){let{email:n,password:t}=e,r=await a("_system.user.loginWithPassword",{email:n,password:t});return H(r)}async function Xn(e){let{firstName:n,lastName:t,avatarUrl:r,handle:o}=e,{user:i}=await a("_system.user.updateProfile",{...n!==void 0?{firstName:n}:{},...t!==void 0?{lastName:t}:{},...r!==void 0?{avatarUrl:r}:{},...o!==void 0?{handle:o}:{}});return W(i)}async function Zn(e){let{token:n}=e;await a("_system.user.verifyEmail",{token:n});}async function et(e){let{email:n}=e;await a("_system.user.resendEmailVerification",{email:n});}async function nt(){await a("_system.user.logout"),ne();let e=d();e&&e.setAuthToken(null),W(null);}async function tt(e){let{email:n}=e;await a("_system.user.sendResetPasswordToken",{email:n});}async function rt(e){let{email:n}=e;await a("_system.user.sendMagicLink",{email:n});}async function ot(){let e=await a("_system.user.loginWithMagicLink");return H(e)}async function it(e){let{email:n,code:t}=e,r=await a("_system.user.loginWithOneTimeCode",{email:n,code:t});return H(r)}async function st(e){let{token:n,password:t}=e;await a("_system.user.resetPassword",{...n?{token:n}:{},password:t});}async function at(e){let{provider:n,redirectUri:t}=e,r=d(),o=r?.baseUrl??"";if(t){if(!r?.openUrl)throw new Error("signInWithOAuth was given a redirectUri but the client has no openUrl. Configure openUrl (e.g. (url) => Linking.openURL(url)) to use the native flow.");let s=ye(),l=`${o}/api/_internal/auth/${n}?mode=login&platform=mobile&redirectUri=${encodeURIComponent(t)}&codeChallenge=${encodeURIComponent(s)}`,c=r.openUrl(l);if(N(c)){try{c.name=we;}catch{}be(c);return}if(c===null&&typeof window<"u")throw new Error("signInWithOAuth could not open the sign-in popup \u2014 the browser blocked it. Call signInWithOAuth directly from a click or other user gesture, or allow popups for this site.");return}let i=`${o}/api/_internal/auth/${n}?mode=login`;if(r?.openUrl){r.openUrl(i);return}window.location.href=i;}function be(e){he(e,G,n=>{console.error("[modelence] Failed to complete the OAuth sign-in in the opening page.",n);});}function Le(e){return B()?(be(e),true):false}async function G(e){let n=ve();if(!n)throw Ne();let t=await a("_system.user.loginWithOAuth",{code:e,codeVerifier:n});return H(t)}function Ne(){return console.error("[modelence] loginWithOAuth was called with no sign-in in progress. Either signInWithOAuth was never called on this client, or the code came from somewhere other than a flow this client started. On native, the app process must survive the round trip; in a browser the verifier is kept in sessionStorage, so a new tab or a cleared session also produces this. If the app runs in an iframe and opens the provider in a popup, openUrl must return the window from window.open so the popup can hand the code back to that page \u2014 and note that a provider sending Cross-Origin-Opener-Policy: same-origin severs window.opener during the round trip, which breaks that handoff with no way for this code to tell it apart from the cases above. A plain web app that never calls signInWithOAuth({ redirectUri }) does not need loginWithOAuth at all \u2014 the cookie flow signs the user in on its own."),new Error("This sign-in link is no longer valid. Please sign in again.")}async function lt(e){let{code:n}=e;return B()?G(n):await me(n)?null:G(n)}function ct(e){let{popup:n}=e;return N(n)?Le(n):false}function ut(){L();}async function dt(e){let{provider:n,redirectUri:t}=e,r=d(),o=r?.baseUrl??"";if(t){if(!r?.openUrl)throw new Error("linkOAuthProvider was given a redirectUri but the client has no openUrl. Configure openUrl (e.g. (url) => Linking.openURL(url)) to use the native flow.");let i=h();if(!i)throw new Error("Failed to initialize OAuth linking. Please ensure you are logged in.");let s=await fetch(`${o}/api/_internal/auth/issue-link-nonce`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({authToken:i})});if(!s.ok)throw new Error("Failed to initialize OAuth linking. Please ensure you are logged in.");let{nonce:l}=await s.json(),c=`${o}/api/_internal/auth/${n}?mode=link&linkNonce=${encodeURIComponent(l)}&platform=mobile&redirectUri=${encodeURIComponent(t)}`;r.openUrl(c);}else {let i=h();if(i&&!(await fetch(`${o}/api/_internal/auth/set-link-cookie`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({authToken:i}),credentials:"include"})).ok)throw new Error("Failed to initialize OAuth linking. Please ensure you are logged in.");window.location.href=`${o}/api/_internal/auth/${n}?mode=link`;}}async function ft(e){let{provider:n}=e;await a("_system.user.unlinkOAuthProvider",{provider:n});}function h(){let e=d();return e?e.getAuthToken():M()?.authToken}function T(){let e=d();return e?e.getClientInfo():typeof window>"u"?{screenWidth:0,screenHeight:0,windowWidth:0,windowHeight:0,pixelRatio:1,orientation:null}:{screenWidth:window.screen.width,screenHeight:window.screen.height,windowWidth:window.innerWidth,windowHeight:window.innerHeight,pixelRatio:window.devicePixelRatio,orientation:window.screen.orientation?.type??null}}var x=null,U=new Map;function P(){if(!x)throw new Error("WebSocket not initialized. Call startWebsockets() first.");return x}function He(){let e=h(),n=T();for(let t of U.values())x?.emit("subscribeLiveQuery",{subscriptionId:t.subscriptionId,method:t.method,args:t.args,authToken:e,clientInfo:n});}function $e(e){let n=d()?.baseUrl??"/";x=Qe(n,{transports:["websocket"],auth:{token:h()}}),x.on("connect",()=>{U.size>0&&(console.log(`[Modelence] WebSocket reconnected, re-subscribing to ${U.size} live queries`),He());}),e.channels?.forEach(t=>t.init());}function Ke({category:e,listener:n}){P().on(e,n);}function je({category:e,listener:n}){P().once(e,n);}function De({category:e,listener:n}){P().off(e,n);}function X({eventName:e,category:n,id:t}){P().emit(e,`${n}:${t}`);}function qe({category:e,id:n}){X({eventName:"joinChannel",category:e,id:n});}function Ve({category:e,id:n}){X({eventName:"leaveChannel",category:e,id:n});}var ze=0;function q(e,n,t,r){let o=`sub-${++ze}-${Date.now()}`,i=({subscriptionId:c$1,data:u,typeMap:f})=>{c$1===o&&t(c(u,f));},s=({subscriptionId:c,error:u})=>{c===o&&(console.error(`[Modelence] Live query error for ${e}:`,u),r?.(u));},l=P();return l.on("liveQueryData",i),l.on("liveQueryError",s),U.set(o,{subscriptionId:o,method:e,args:n}),l.connected&&l.emit("subscribeLiveQuery",{subscriptionId:o,method:e,args:n,authToken:h(),clientInfo:T()}),()=>{U.delete(o),l.emit("unsubscribeLiveQuery",{subscriptionId:o}),l.off("liveQueryData",i),l.off("liveQueryError",s);}}var Fe={init:$e,on:Ke,once:je,off:De,emit:X,joinChannel:qe,leaveChannel:Ve},se=Fe;export{$n as A,Bn as B,Gn as C,Xn as D,Zn as E,et as F,nt as G,tt as H,rt as I,ot as J,it as K,st as L,at as M,lt as N,ct as O,ut as P,dt as Q,ft as R,en as S,D as T,Te as U,an as V,a as W,Ye as a,Je as b,M as c,Xe as d,q as e,ie as f,un as g,ae as h,Se as i,mn as j,xe as k,le as l,wn as m,yn as n,vn as o,bn as p,Mn as q,On as r,Rn as s,In as t,_n as u,Wn as v,Ln as w,Nn as x,Qn as y,Hn as z};//# sourceMappingURL=chunk-KJBMQRY6.js.map
2
+ //# sourceMappingURL=chunk-KJBMQRY6.js.map