modelence 0.23.1 → 0.24.0-dev.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 (43) hide show
  1. package/dist/chunk-3KUADF4A.js +41 -0
  2. package/dist/chunk-3KUADF4A.js.map +1 -0
  3. package/dist/chunk-63RBLFRJ.js +4 -0
  4. package/dist/chunk-63RBLFRJ.js.map +1 -0
  5. package/dist/chunk-ACX7KY6E.js +3 -0
  6. package/dist/{chunk-WDY7BYXR.js.map → chunk-ACX7KY6E.js.map} +1 -1
  7. package/dist/chunk-CHBJAOMP.js +2 -0
  8. package/dist/chunk-CHBJAOMP.js.map +1 -0
  9. package/dist/{chunk-UJ2WYHH7.js → chunk-NPBIRXLC.js} +2 -2
  10. package/dist/{chunk-UJ2WYHH7.js.map → chunk-NPBIRXLC.js.map} +1 -1
  11. package/dist/chunk-PPPB2U34.js +2 -0
  12. package/dist/chunk-PPPB2U34.js.map +1 -0
  13. package/dist/chunk-ZCIM5A5S.js +3 -0
  14. package/dist/chunk-ZCIM5A5S.js.map +1 -0
  15. package/dist/client.d.ts +120 -2
  16. package/dist/client.js +1 -1
  17. package/dist/{package-YDKHBRBH.js → package-D62UBES3.js} +2 -2
  18. package/dist/{package-YDKHBRBH.js.map → package-D62UBES3.js.map} +1 -1
  19. package/dist/{render-OM7ZJWZA.js → render-FZAHNIJB.js} +2 -2
  20. package/dist/{render-OM7ZJWZA.js.map → render-FZAHNIJB.js.map} +1 -1
  21. package/dist/renderApp-DZBN6IKT.js +2 -0
  22. package/dist/{renderApp-MD5O44UP.js.map → renderApp-DZBN6IKT.js.map} +1 -1
  23. package/dist/server-TGEMYLAH.js +2 -0
  24. package/dist/{server-GHQ5XNNQ.js.map → server-TGEMYLAH.js.map} +1 -1
  25. package/dist/server.d.ts +81 -2
  26. package/dist/server.js +1 -1
  27. package/dist/transport-N3EV2QPS.js +2 -0
  28. package/dist/{transport-VKGH6BY6.js.map → transport-N3EV2QPS.js.map} +1 -1
  29. package/package.json +1 -1
  30. package/dist/chunk-4I4BI7KD.js +0 -2
  31. package/dist/chunk-4I4BI7KD.js.map +0 -1
  32. package/dist/chunk-KDOTVIEY.js +0 -4
  33. package/dist/chunk-KDOTVIEY.js.map +0 -1
  34. package/dist/chunk-KFTT3M45.js +0 -3
  35. package/dist/chunk-KFTT3M45.js.map +0 -1
  36. package/dist/chunk-LCXJNLNK.js +0 -41
  37. package/dist/chunk-LCXJNLNK.js.map +0 -1
  38. package/dist/chunk-W4RFIS5E.js +0 -2
  39. package/dist/chunk-W4RFIS5E.js.map +0 -1
  40. package/dist/chunk-WDY7BYXR.js +0 -3
  41. package/dist/renderApp-MD5O44UP.js +0 -2
  42. package/dist/server-GHQ5XNNQ.js +0 -2
  43. package/dist/transport-VKGH6BY6.js +0 -2
@@ -1,2 +0,0 @@
1
- import {c as c$1}from'./chunk-5M6FUMUK.js';import {a as a$1}from'./chunk-DO5TZLF5.js';import {create}from'zustand';import {z as z$1}from'zod';var N={},T=null;function J(e){T=e;}function K(e){return typeof window>"u"&&T?T(e):N[e]?.value}function h(e){N=e;}var C="modelence.session";function x(){return typeof globalThis<"u"&&typeof globalThis.localStorage<"u"}function m(){if(!x())return null;let e=globalThis.localStorage.getItem(C);try{return e?JSON.parse(e):null}catch(n){return console.error("Error parsing session from localStorage",n),null}}function c(e){x()&&globalThis.localStorage.setItem(C,JSON.stringify(e));}function E(){x()&&globalThis.localStorage.removeItem(C);}var A=null;function F(e){A=e;}function a(){return A}function k(e){let n=a();n?n.setAuthToken(e.authToken):c(e);}async function ee(e){let{email:n,password:t,handle:r,firstName:o,lastName:i,avatarUrl:u}=e;await s("_system.user.signupWithPassword",{email:n,password:t,...r!==void 0?{handle:r}:{},...o!==void 0?{firstName:o}:{},...i!==void 0?{lastName:i}:{},...u!==void 0?{avatarUrl:u}:{}});}async function ne(e){let{email:n,password:t}=e,{user:r,session:o}=await s("_system.user.loginWithPassword",{email:n,password:t});return k(o),d(r)}async function te(e){let{firstName:n,lastName:t,avatarUrl:r,handle:o}=e,{user:i}=await s("_system.user.updateProfile",{...n!==void 0?{firstName:n}:{},...t!==void 0?{lastName:t}:{},...r!==void 0?{avatarUrl:r}:{},...o!==void 0?{handle:o}:{}});return d(i)}async function re(e){let{token:n}=e;await s("_system.user.verifyEmail",{token:n});}async function oe(e){let{email:n}=e;await s("_system.user.resendEmailVerification",{email:n});}async function se(){await s("_system.user.logout"),E();let e=a();e&&e.setAuthToken(null),d(null);}async function ie(e){let{email:n}=e;await s("_system.user.sendResetPasswordToken",{email:n});}async function ae(e){let{email:n}=e;await s("_system.user.sendMagicLink",{email:n});}async function le(){let{user:e,session:n}=await s("_system.user.loginWithMagicLink");return k(n),d(e)}async function ue(e){let{email:n,code:t}=e,{user:r,session:o}=await s("_system.user.loginWithOneTimeCode",{email:n,code:t});return k(o),d(r)}async function ce(e){let{token:n,password:t}=e;await s("_system.user.resetPassword",{...n?{token:n}:{},password:t});}async function de(e){let{provider:n}=e,t=a(),r=t?.baseUrl??"";if(t?.openUrl){let o=w();if(!o)throw new Error("Failed to initialize OAuth linking. Please ensure you are logged in.");let i=await fetch(`${r}/api/_internal/auth/issue-link-nonce`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({authToken:o})});if(!i.ok)throw new Error("Failed to initialize OAuth linking. Please ensure you are logged in.");let{nonce:u}=await i.json(),W=`${r}/api/_internal/auth/${n}?mode=link&linkNonce=${encodeURIComponent(u)}`;t.openUrl(W);}else {let o=w();if(o&&!(await fetch(`${r}/api/_internal/auth/set-link-cookie`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({authToken:o}),credentials:"include"})).ok)throw new Error("Failed to initialize OAuth linking. Please ensure you are logged in.");window.location.href=`${r}/api/_internal/auth/${n}?mode=link`;}}async function fe(e){let{provider:n}=e;await s("_system.user.unlinkOAuthProvider",{provider:n});}function w(){let e=a();return e?e.getAuthToken():m()?.authToken}function O(){let e=a();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 I=(e,n)=>{console.error(`Error calling method '${n}':`,e);};function pe(e){I=e;}function M(e,n){return I(e,n)}var U=class extends Error{constructor(n,t,r){super(n),this.name="MethodError",this.status=t,this.code=r;}},L=async(e,n)=>{let t=a()?.baseUrl??"";return q(`${t}/api/_internal/method/${e}`,n)},y="__modelence_call_method_transport__";function $(){return globalThis[y]??L}function Te(e){let n=globalThis[y];return globalThis[y]=e,()=>{globalThis[y]=n;}}async function s(e,n,t){n=n??{},t=t??{};try{return await $()(e,n)}catch(r){throw (t.errorHandler??M)(r,e),r}}async function q(e,n){let t=await fetch(e,{method:"POST",credentials:a()?.credentials??"include",headers:{"Content-Type":"application/json"},body:JSON.stringify({args:n,authToken:w(),clientInfo:O()})});if(!t.ok){let i=await t.text(),u=t.headers?.get("X-Modelence-Error-Code")??void 0;throw new U(i,t.status,u)}let r=await t.text(),o=r?JSON.parse(r):void 0;if(!o)throw new Error("Invalid response from server");return c$1(o.data,o.typeMap)}var f=create(e=>({user:null,setUser:n=>e({user:n})})),p=false,S=false,z=a$1.seconds(30),H=null,D=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 g(e){if(!e)return null;let n=D.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 R=false;function Pe(){return R}function Ne(e){if(p)return;p=true,R=!!e.setupRequired,h(e.configs);let t=m()?.authToken,r=e.session;if(t&&!e.user&&t!==r.authToken){S=true,f.getState().setUser(g(e.user));return}c(e.session),f.getState().setUser(g(e.user));}async function Ee(){if(S){S=false;try{let{configs:e,session:n,user:t}=await s("_system.session.init");h(e),c(n),f.getState().setUser(g(t));}catch(e){console.error("Modelence: session reconciliation failed",e);}}}function Ae(){return S}async function Oe(){if(p)return;p=true;let e=await s("_system.session.init"),{configs:n,session:t,user:r}=e;R=!!e.setupRequired,h(n);let o=a();o?o.setAuthToken(t.authToken):c(t),f.getState().setUser(g(r)),await b();}async function Ie(){typeof window>"u"||H!==null||await b();}async function b(){if(!(typeof window>"u")){try{await s("_system.session.heartbeat",{},{errorHandler:()=>{}});}catch{}H=setTimeout(b,z);}}function d(e){let n=g(e);return f.getState().setUser(n),n}function Me(){return p}var v=null;function He(e){v=e;}function We(e){return g(e)}function Le(){return typeof window>"u"&&v?{user:v()}:{user:f(n=>n.user)}}export{de as A,fe as B,w as C,O as D,pe as E,U as F,L as G,Te as H,s as I,J as a,K as b,m as c,F as d,a as e,Pe as f,Ne as g,Ee as h,Ae as i,Oe as j,Ie as k,Me as l,He as m,We as n,Le as o,ee as p,ne as q,te as r,re as s,oe as t,se as u,ie as v,ae as w,le as x,ue as y,ce as z};//# sourceMappingURL=chunk-W4RFIS5E.js.map
2
- //# sourceMappingURL=chunk-W4RFIS5E.js.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/config/client.ts","../src/client/localStorage.ts","../src/client/clientConfig.ts","../src/auth/client/index.ts","../src/client/errorHandler.ts","../src/client/method.ts","../src/client/session.ts"],"names":["config","ssrConfigResolver","_setSsrConfigResolver","resolver","getConfig","key","_setConfig","configs","SESSION_KEY","hasLocalStorage","getLocalStorageSession","sessionJson","e","setLocalStorageSession","session","clearLocalStorageSession","configureClient","userConfig","getClientConfig","persistSession","signupWithPassword","options","email","password","handle","firstName","lastName","avatarUrl","callMethod","loginWithPassword","user","setCurrentUser","updateProfile","verifyEmail","token","resendEmailVerification","logout","sendResetPasswordToken","sendMagicLink","loginWithMagicLink","loginWithOneTimeCode","code","resetPassword","linkOAuthProvider","provider","baseUrl","getAuthToken","nonceResponse","nonce","url","unlinkOAuthProvider","getClientInfo","errorHandler","error","methodName","setErrorHandler","handler","handleError","MethodError","message","status","defaultCallMethodTransport","args","call","TRANSPORT_KEY","getTransport","setCallMethodTransport","next","previous","endpoint","response","text","result","reviveResponseTypes","useSessionStore","create","set","isInitialized","pendingReconciliation","SESSION_HEARTBEAT_INTERVAL","time","heartbeatTimer","userSchema","z","parseUser","parsedData","role","setupRequired","_isSetupRequired","hydrateSession","payload","existingToken","ssrSession","reconcileSession","_isReconciliationPending","initSession","loopSessionHeartbeat","startSessionHeartbeat","enrichedUser","isSessionInitialized","ssrSessionResolver","_setSsrSessionResolver","_parseSessionUser","useSession","state"],"mappings":"8IAEA,IAAIA,EAAuC,EAAC,CAGxCC,EAA8C,IAAA,CAG3C,SAASC,EAAsBC,CAAAA,CAAoC,CACxEF,CAAAA,CAAoBE,EACtB,CAQO,SAASC,CAAAA,CAAUC,EAAuD,CAC/E,OAAI,OAAO,MAAA,CAAW,GAAA,EAAeJ,CAAAA,CAC5BA,CAAAA,CAAkBI,CAAG,CAAA,CAEvBL,CAAAA,CAAOK,CAAG,CAAA,EAAG,KACtB,CAEO,SAASC,CAAAA,CAAWC,CAAAA,CAAkB,CAC3CP,EAASO,EACX,CC3BA,IAAMC,CAAAA,CAAc,mBAAA,CAEpB,SAASC,CAAAA,EAA2B,CAClC,OAAO,OAAO,WAAe,GAAA,EAAe,OAAO,WAAW,YAAA,CAAiB,GACjF,CAEO,SAASC,CAAAA,EAAyB,CACvC,GAAI,CAACD,CAAAA,EAAgB,CACnB,OAAO,IAAA,CAGT,IAAME,EAAc,UAAA,CAAW,YAAA,CAAa,OAAA,CAAQH,CAAW,EAC/D,GAAI,CACF,OAAOG,CAAAA,CAAc,IAAA,CAAK,MAAMA,CAAW,CAAA,CAAI,IACjD,CAAA,MAASC,EAAG,CACV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Configs } from './types';\n\nlet config: Record<ConfigKey, AppConfig> = {};\n\ntype SsrConfigResolver = (key: ConfigKey) => string | number | boolean | undefined;\nlet ssrConfigResolver: SsrConfigResolver | null = null;\n\n/** @internal SSR resolver reads from AsyncLocalStorage (per-request scoped). */\nexport function _setSsrConfigResolver(resolver: SsrConfigResolver | null) {\n ssrConfigResolver = resolver;\n}\n\n/**\n * @sidebarTitle getConfig (client)\n *\n * @param key\n * @returns\n */\nexport function getConfig(key: ConfigKey): string | number | boolean | undefined {\n if (typeof window === 'undefined' && ssrConfigResolver) {\n return ssrConfigResolver(key);\n }\n return config[key]?.value;\n}\n\nexport function _setConfig(configs: Configs) {\n config = configs;\n}\n","const SESSION_KEY = 'modelence.session';\n\nfunction hasLocalStorage(): boolean {\n return typeof globalThis !== 'undefined' && typeof globalThis.localStorage !== 'undefined';\n}\n\nexport function getLocalStorageSession() {\n if (!hasLocalStorage()) {\n return null;\n }\n\n const sessionJson = globalThis.localStorage.getItem(SESSION_KEY);\n try {\n return sessionJson ? JSON.parse(sessionJson) : null;\n } catch (e) {\n console.error('Error parsing session from localStorage', e);\n return null;\n }\n}\n\nexport function setLocalStorageSession(session: object) {\n if (!hasLocalStorage()) {\n return;\n }\n\n globalThis.localStorage.setItem(SESSION_KEY, JSON.stringify(session));\n}\n\nexport function clearLocalStorageSession() {\n if (!hasLocalStorage()) {\n return;\n }\n\n globalThis.localStorage.removeItem(SESSION_KEY);\n}\n","import type { ClientInfo } from '@/methods/types';\n\nexport interface ClientConfig {\n baseUrl: string;\n getAuthToken: () => string | undefined;\n setAuthToken: (token: string | null) => void;\n getClientInfo: () => ClientInfo;\n /**\n * Opens a URL for OAuth redirects. React Native must use\n * `(url) => Linking.openURL(url)` — WebView is not supported.\n * Defaults to `window.location.href` when not provided.\n */\n openUrl?: (url: string) => void;\n /**\n * Credentials mode for method-call requests. Defaults to `'include'`, which\n * browser apps need for the cookie-based flows (password reset, magic link).\n *\n * Clients configured with token-in-body auth (React Native / Expo) never use\n * cookies, so set `'omit'` there — on Expo Web a credentialed cross-origin\n * request is otherwise blocked by any server answering\n * `Access-Control-Allow-Origin: *`, surfacing as \"TypeError: Failed to fetch\".\n */\n credentials?: RequestCredentials;\n}\n\nlet config: ClientConfig | null = null;\n\n/**\n * Configure the Modelence client for non-browser environments like React Native.\n *\n * When configured, the client uses the provided functions for auth-token\n * storage, client-info collection, and URL resolution instead of the\n * default browser APIs (localStorage, window.screen, relative URLs).\n *\n * @example\n * ```ts\n * import { configureClient } from 'modelence/client';\n * import { Linking } from 'react-native';\n *\n * let authToken: string | undefined;\n *\n * configureClient({\n * baseUrl: 'https://myapp.com',\n * getAuthToken: () => authToken,\n * setAuthToken: (token) => { authToken = token ?? undefined; },\n * getClientInfo: () => ({\n * screenWidth: Dimensions.get('screen').width,\n * screenHeight: Dimensions.get('screen').height,\n * windowWidth: Dimensions.get('window').width,\n * windowHeight: Dimensions.get('window').height,\n * pixelRatio: PixelRatio.get(),\n * orientation: null,\n * }),\n * openUrl: (url) => Linking.openURL(url),\n * });\n * ```\n */\nexport function configureClient(userConfig: ClientConfig) {\n config = userConfig;\n}\n\nexport function getClientConfig(): ClientConfig | null {\n return config;\n}\n","import { setCurrentUser } from '@/client/session';\nimport { callMethod } from '@/client/method';\nimport {\n clearLocalStorageSession,\n getLocalStorageSession,\n setLocalStorageSession,\n} from '@/client/localStorage';\nimport { getClientConfig } from '@/client/clientConfig';\nimport type { ClientInfo } from '@/methods/types';\nimport { OAuthProvider } from '../types';\n\nexport type UserInfo = {\n id: string;\n handle: string;\n roles: string[];\n hasRole: (role: string) => boolean;\n requireRole: (role: string) => void;\n firstName?: string;\n lastName?: string;\n avatarUrl?: string;\n};\n\ntype RawUserData = {\n id: string;\n handle: string;\n roles: string[];\n firstName?: string;\n lastName?: string;\n avatarUrl?: string;\n};\n\nfunction persistSession(session: { authToken: string }) {\n const config = getClientConfig();\n if (config) {\n config.setAuthToken(session.authToken);\n } else {\n setLocalStorageSession(session);\n }\n}\n\n/**\n * Sign up a new user with an email and password.\n *\n * @example\n * ```ts\n * await signupWithPassword({ email: 'test@example.com', password: '12345678' });\n * await signupWithPassword({ email: 'test@example.com', password: '12345678', handle: 'myhandle', firstName: 'John' });\n * ```\n * @param options.email - The email of the user.\n * @param options.password - The password of the user.\n * @param options.handle - Optional custom handle. If omitted, one is derived from the email.\n * @param options.firstName - Optional first name.\n * @param options.lastName - Optional last name.\n * @param options.avatarUrl - Optional avatar URL.\n */\nexport async function signupWithPassword(options: {\n email: string;\n password: string;\n handle?: string;\n firstName?: string;\n lastName?: string;\n avatarUrl?: string;\n}) {\n const { email, password, handle, firstName, lastName, avatarUrl } = options;\n await callMethod('_system.user.signupWithPassword', {\n email,\n password,\n ...(handle !== undefined ? { handle } : {}),\n ...(firstName !== undefined ? { firstName } : {}),\n ...(lastName !== undefined ? { lastName } : {}),\n ...(avatarUrl !== undefined ? { avatarUrl } : {}),\n });\n}\n\n/**\n * Login a user with an email and password.\n *\n * @example\n * ```ts\n * await loginWithPassword({ email: 'test@example.com', password: '12345678' });\n * ```\n * @param options.email - The email of the user.\n * @param options.password - The password of the user.\n */\nexport async function loginWithPassword(options: { email: string; password: string }) {\n const { email, password } = options;\n const { user, session } = await callMethod<{ user: RawUserData; session: { authToken: string } }>(\n '_system.user.loginWithPassword',\n {\n email,\n password,\n }\n );\n persistSession(session);\n const enrichedUser = setCurrentUser(user);\n return enrichedUser;\n}\n\n/**\n * Update the current user's profile.\n *\n * @example\n * ```ts\n * await updateProfile({ firstName: 'Atul', lastName: 'Yadav', avatarUrl: 'https://example.com/avatar.jpg', handle: 'atulyadav' });\n * ```\n * @param options.firstName - The first name of the user.\n * @param options.lastName - The last name of the user.\n * @param options.avatarUrl - The avatar URL of the user.\n * @param options.handle - The handle of the user.\n */\nexport async function updateProfile(options: {\n firstName?: string;\n lastName?: string;\n avatarUrl?: string;\n handle?: string;\n}) {\n const { firstName, lastName, avatarUrl, handle } = options;\n const { user } = await callMethod<{ user: RawUserData }>('_system.user.updateProfile', {\n ...(firstName !== undefined ? { firstName } : {}),\n ...(lastName !== undefined ? { lastName } : {}),\n ...(avatarUrl !== undefined ? { avatarUrl } : {}),\n ...(handle !== undefined ? { handle } : {}),\n });\n const enrichedUser = setCurrentUser(user);\n return enrichedUser;\n}\n\n/**\n * Verify user's email with a verification token.\n *\n * @example\n * ```ts\n * await verifyEmail({ token: 'verification-token' });\n * ```\n * @param options.token - The email verification token.\n */\nexport async function verifyEmail(options: { token: string }) {\n const { token } = options;\n await callMethod<{ user: RawUserData }>('_system.user.verifyEmail', { token });\n}\n\n/**\n * Resend the verification email for a given email address.\n * The email is only sent if the address is registered and not yet verified.\n * A generic response is always returned to avoid leaking account information.\n *\n * @example\n * ```ts\n * await resendEmailVerification({ email: 'user@example.com' });\n * ```\n * @param options.email - The email address to resend verification to.\n */\nexport async function resendEmailVerification(options: { email: string }) {\n const { email } = options;\n await callMethod('_system.user.resendEmailVerification', { email });\n}\n\n/**\n * Logout the current user.\n *\n */\nexport async function logout() {\n await callMethod('_system.user.logout');\n clearLocalStorageSession();\n const config = getClientConfig();\n if (config) {\n config.setAuthToken(null);\n }\n setCurrentUser(null);\n}\n\n/**\n * Send reset password token.\n * @param options.email - The email of the user.\n */\nexport async function sendResetPasswordToken(options: { email: string }) {\n const { email } = options;\n await callMethod('_system.user.sendResetPasswordToken', {\n email,\n });\n}\n\n/**\n * Send a magic sign-in link to the given email address.\n *\n * Clicking the emailed link signs the user in. When the server enables\n * `auth.magicLink.allowSignup`, this also works for new users — the account is\n * created when the link is used; otherwise unknown emails receive no email.\n * A generic response is always returned to avoid leaking account information.\n *\n * @example\n * ```ts\n * await sendMagicLink({ email: 'user@example.com' });\n * ```\n * @param options.email - The email address to send the magic link to.\n */\nexport async function sendMagicLink(options: { email: string }) {\n const { email } = options;\n await callMethod('_system.user.sendMagicLink', {\n email,\n });\n}\n\n/**\n * Complete a magic link sign-in.\n *\n * Call this from the page the magic link landing route redirects to. The\n * token is exchanged server-side via an httpOnly cookie, so no arguments are\n * needed. Signs the user in — creating the account first when the email is\n * not registered yet and the server enables `auth.magicLink.allowSignup` —\n * and returns the logged-in user.\n *\n * @example\n * ```ts\n * const user = await loginWithMagicLink();\n * ```\n */\nexport async function loginWithMagicLink() {\n const { user, session } = await callMethod<{ user: RawUserData; session: { authToken: string } }>(\n '_system.user.loginWithMagicLink'\n );\n persistSession(session);\n const enrichedUser = setCurrentUser(user);\n return enrichedUser;\n}\n\n/**\n * Complete a magic link sign-in by typing the one-time code from the email.\n *\n * Alternative to `loginWithMagicLink()` for contexts where clicking the link\n * can't reach the app — native apps without deep links, or when the email is\n * read on a different device. Signs the user in — creating the account first\n * when the email is not registered yet and the server enables\n * `auth.magicLink.allowSignup` — and returns the logged-in user.\n *\n * @example\n * ```ts\n * const user = await loginWithOneTimeCode({ email: 'user@example.com', code: '482193' });\n * ```\n * @param options.email - The email the magic link was sent to.\n * @param options.code - The one-time code from the email.\n */\nexport async function loginWithOneTimeCode(options: { email: string; code: string }) {\n const { email, code } = options;\n const { user, session } = await callMethod<{ user: RawUserData; session: { authToken: string } }>(\n '_system.user.loginWithOneTimeCode',\n { email, code }\n );\n persistSession(session);\n const enrichedUser = setCurrentUser(user);\n return enrichedUser;\n}\n\n/**\n * Reset password.\n *\n * The token is normally exchanged server-side via an httpOnly cookie, so the\n * client only submits the new password. Pass `token` only for legacy flows\n * that still carry it client-side (deprecated).\n *\n * @param options.token - Reset token (optional; read from the httpOnly cookie when omitted).\n * @param options.password - The new password.\n */\nexport async function resetPassword(options: { token?: string; password: string }) {\n const { token, password } = options;\n await callMethod('_system.user.resetPassword', {\n ...(token ? { token } : {}),\n password,\n });\n}\n\n/**\n * Link an OAuth provider to the currently signed-in user's account.\n * Redirects the browser to the OAuth provider's authorization page.\n * The provider will redirect back and the account will be linked.\n *\n * @example\n * ```ts\n * linkOAuthProvider({ provider: 'google' });\n * ```\n * @param options.provider - The OAuth provider to link ('google' or 'github').\n */\nexport async function linkOAuthProvider(options: { provider: OAuthProvider }): Promise<void> {\n const { provider } = options;\n const config = getClientConfig();\n const baseUrl = config?.baseUrl ?? '';\n\n if (config?.openUrl) {\n // React Native: exchange authToken for a single-use nonce via an authenticated\n // request, then put the nonce in the URL. A crafted external link can't work\n // because the nonce is bound to this session and consumed on first use.\n const token = getAuthToken();\n if (!token) {\n throw new Error('Failed to initialize OAuth linking. Please ensure you are logged in.');\n }\n const nonceResponse = await fetch(`${baseUrl}/api/_internal/auth/issue-link-nonce`, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ authToken: token }),\n });\n if (!nonceResponse.ok) {\n throw new Error('Failed to initialize OAuth linking. Please ensure you are logged in.');\n }\n const { nonce } = await nonceResponse.json();\n const url = `${baseUrl}/api/_internal/auth/${provider}?mode=link&linkNonce=${encodeURIComponent(nonce)}`;\n config.openUrl(url);\n } else {\n // Browser: set httpOnly cookie via same-origin fetch (keeps token out of redirect params).\n const token = getAuthToken();\n if (token) {\n const response = await fetch(`${baseUrl}/api/_internal/auth/set-link-cookie`, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ authToken: token }),\n credentials: 'include',\n });\n if (!response.ok) {\n throw new Error('Failed to initialize OAuth linking. Please ensure you are logged in.');\n }\n }\n window.location.href = `${baseUrl}/api/_internal/auth/${provider}?mode=link`;\n }\n}\n/**\n * Unlink an OAuth provider from the currently signed-in user's account.\n *\n * @example\n * ```ts\n * await unlinkOAuthProvider({ provider: 'github' });\n * ```\n * @param options.provider - The OAuth provider to unlink ('google' or 'github').\n */\nexport async function unlinkOAuthProvider(options: { provider: OAuthProvider }): Promise<void> {\n const { provider } = options;\n await callMethod('_system.user.unlinkOAuthProvider', { provider });\n}\n\n/**\n * Get the current auth token associated with the current session.\n * @returns The auth token or undefined if not authenticated.\n */\nexport function getAuthToken(): string | undefined {\n const config = getClientConfig();\n if (config) {\n return config.getAuthToken();\n }\n return getLocalStorageSession()?.authToken;\n}\n\nexport function getClientInfo(): ClientInfo {\n const config = getClientConfig();\n if (config) {\n return config.getClientInfo();\n }\n\n if (typeof window === 'undefined') {\n return {\n screenWidth: 0,\n screenHeight: 0,\n windowWidth: 0,\n windowHeight: 0,\n pixelRatio: 1,\n orientation: null,\n };\n }\n\n return {\n screenWidth: window.screen.width,\n screenHeight: window.screen.height,\n windowWidth: window.innerWidth,\n windowHeight: window.innerHeight,\n pixelRatio: window.devicePixelRatio,\n orientation: window.screen.orientation?.type ?? null,\n };\n}\n","export type ErrorHandler = (error: Error, methodName: string) => void;\n\nlet errorHandler: ErrorHandler = (error, methodName) => {\n console.error(`Error calling method '${methodName}':`, error);\n};\n\nexport function setErrorHandler(handler: ErrorHandler) {\n errorHandler = handler;\n}\n\nexport function handleError(error: Error, methodName: string) {\n return errorHandler(error, methodName);\n}\n","/*\n The \"use client\" directive is specifically for the Next.js layout component, which is rendered on the server by default.\n Because of this, we are explicitly marking it as a client component, so we can render this component on the client\n and properly initialize config on the client side.\n \n While this is specific to Next.js, it is simply ignored outside of Next.js and should not cause errors.\n*/\n'use client';\n\nimport { getAuthToken, getClientInfo } from '@/auth/client';\nimport { handleError } from '@/client/errorHandler';\nimport { getClientConfig } from '@/client/clientConfig';\nimport { reviveResponseTypes } from '@/methods/serialize';\n\nexport class MethodError extends Error {\n status: number;\n /**\n * Machine-readable error code set by the server (when available), so callers\n * can branch on the error kind without matching the human-readable message.\n * For example, a login attempt with an unverified email yields\n * `code === 'EMAIL_NOT_VERIFIED'`.\n */\n code?: string;\n\n constructor(message: string, status: number, code?: string) {\n super(message);\n this.name = 'MethodError';\n this.status = status;\n this.code = code;\n }\n}\n\nexport type MethodArgs = Record<string, unknown>;\n\nexport type CallMethodOptions = {\n errorHandler?: (error: Error, methodName: string) => void;\n};\n\n// Default: fetch HTTP. SSR swaps in an in-process transport via globalThis\n// so Vite's ssrLoadModule (separate module graph) shares the same instance.\nexport type CallMethodTransport = <T = unknown>(methodName: string, args: MethodArgs) => Promise<T>;\n\n/**\n * The default HTTP transport. Exported so alternative transports (e.g. the SSR\n * in-process transport) can delegate to it when they don't apply.\n * @internal\n */\nexport const defaultCallMethodTransport: CallMethodTransport = async <T>(\n methodName: string,\n args: MethodArgs\n) => {\n const baseUrl = getClientConfig()?.baseUrl ?? '';\n return call<T>(`${baseUrl}/api/_internal/method/${methodName}`, args);\n};\n\nconst TRANSPORT_KEY = '__modelence_call_method_transport__';\n\ntype GlobalWithTransport = typeof globalThis & {\n [TRANSPORT_KEY]?: CallMethodTransport;\n};\n\nfunction getTransport(): CallMethodTransport {\n return (globalThis as GlobalWithTransport)[TRANSPORT_KEY] ?? defaultCallMethodTransport;\n}\n\n/** Returns a disposer that restores the previous transport. */\nexport function setCallMethodTransport(next: CallMethodTransport): () => void {\n const previous = (globalThis as GlobalWithTransport)[TRANSPORT_KEY];\n (globalThis as GlobalWithTransport)[TRANSPORT_KEY] = next;\n return () => {\n (globalThis as GlobalWithTransport)[TRANSPORT_KEY] = previous;\n };\n}\n\n/**\n * Calls a server-side method (query or mutation) defined on a Modelence module.\n *\n * Both `args` and `options` are optional. Use the type parameter `T` to type the return value.\n *\n * @example\n * ```typescript\n * import { callMethod } from 'modelence/client';\n *\n * // No arguments\n * const todos = await callMethod<Todo[]>('todo.getAll');\n *\n * // With arguments\n * const todo = await callMethod<Todo>('todo.getOne', { id: '123' });\n *\n * // With a custom error handler\n * const created = await callMethod<Todo>(\n * 'todo.create',\n * { title: 'Buy groceries' },\n * { errorHandler: (error, methodName) => console.error(methodName, error) }\n * );\n * ```\n *\n * @param methodName - Fully qualified method name, e.g. `'todo.getAll'`.\n * @param args - Arguments passed to the server-side method. Defaults to `{}`.\n * @param options - Call-site options such as a custom {@link CallMethodOptions.errorHandler}. Defaults to `{}`.\n * @returns A promise that resolves to the method's return value.\n */\nexport async function callMethod<T = unknown>(\n methodName: string,\n args?: MethodArgs,\n options?: CallMethodOptions\n): Promise<T> {\n args = args ?? {};\n options = options ?? {};\n try {\n return await getTransport()<T>(methodName, args);\n } catch (error) {\n const handler = options.errorHandler ?? handleError;\n handler(error as Error, methodName);\n throw error;\n }\n}\n\nasync function call<T = unknown>(endpoint: string, args: MethodArgs): Promise<T> {\n const response = await fetch(endpoint, {\n method: 'POST',\n // Send cookies even when the SPA and API are on different origins. The\n // password-reset and magic-link flows rely on httpOnly cookies set by the\n // server landing routes; with the default `same-origin` policy the cookie\n // would be dropped on cross-origin POSTs and those flows would fail.\n // (Cross-origin use also requires the server to emit\n // `Access-Control-Allow-Credentials: true` and a non-wildcard origin.)\n // Token-in-body clients (React Native / Expo) don't use cookies and can\n // override this via `configureClient({ credentials: 'omit' })`.\n credentials: getClientConfig()?.credentials ?? 'include',\n headers: {\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify({\n args,\n authToken: getAuthToken(),\n clientInfo: getClientInfo(),\n }),\n });\n\n if (!response.ok) {\n const error = await response.text();\n const code = response.headers?.get('X-Modelence-Error-Code') ?? undefined;\n throw new MethodError(error, response.status, code);\n }\n\n const text = await response.text();\n const result = text ? JSON.parse(text) : undefined;\n if (!result) {\n throw new Error('Invalid response from server');\n }\n\n return reviveResponseTypes(result.data, result.typeMap);\n}\n","import { create } from 'zustand';\nimport { z } from 'zod';\nimport { callMethod } from './method';\nimport { _setConfig } from '../config/client';\nimport { getLocalStorageSession, setLocalStorageSession } from './localStorage';\nimport { getClientConfig } from './clientConfig';\nimport { time } from '../time';\nimport { Configs } from '../config/types';\n\ntype User = {\n id: string;\n handle: string;\n roles: string[];\n hasRole: (role: string) => boolean;\n requireRole: (role: string) => void;\n firstName?: string;\n lastName?: string;\n avatarUrl?: string;\n};\n\ntype SessionStore = {\n user: User | null;\n setUser: (user: User | null) => void;\n};\n\nexport const useSessionStore = create<SessionStore>((set) => ({\n user: null,\n setUser: (user) => set({ user }),\n}));\n\nlet isInitialized = false;\n// Set when SSR rendered anonymously but localStorage holds a token (no\n// cookie yet). `reconcileSession()` then re-auths via the body and refreshes\n// the cookie for subsequent SSR requests.\nlet pendingReconciliation = false;\nconst SESSION_HEARTBEAT_INTERVAL = time.seconds(30);\nlet heartbeatTimer: ReturnType<typeof setTimeout> | null = null;\n\nconst userSchema = z.object({\n id: z.string(),\n handle: z.string(),\n roles: z.array(z.string()),\n firstName: z.string().optional(),\n lastName: z.string().optional(),\n avatarUrl: z.string().optional(),\n});\n\nfunction parseUser(user: unknown): User | null {\n if (!user) {\n return null;\n }\n\n const result = userSchema.safeParse(user);\n\n if (!result.success) {\n console.error('Session Error: Invalid user payload', result.error);\n return null;\n }\n\n const parsedData = result.data;\n\n return Object.freeze({\n ...parsedData,\n firstName: parsedData.firstName ?? undefined,\n lastName: parsedData.lastName ?? undefined,\n avatarUrl: parsedData.avatarUrl ?? undefined,\n hasRole: (role: string) => parsedData.roles.includes(role),\n requireRole: (role: string) => {\n if (!parsedData.roles.includes(role)) {\n throw new Error(`Access denied - role '${role}' required`);\n }\n },\n });\n}\n\nexport type SessionInitPayload = {\n configs: Configs;\n session: object & { authToken: string };\n user: object;\n /*\n Present (true) only when a development server has no backend at all —\n neither a Modelence Cloud connection nor a local database. AppProvider\n then shows setup instructions instead of the app. The server decides this;\n the client never consults its own build mode.\n */\n setupRequired?: boolean;\n};\n\nlet setupRequired = false;\n\n/** @internal */\nexport function _isSetupRequired(): boolean {\n return setupRequired;\n}\n\n/** Hydrate session state from the SSR payload, skipping the network round-trip. */\nexport function hydrateSession(payload: SessionInitPayload) {\n if (isInitialized) {\n return;\n }\n\n isInitialized = true;\n\n setupRequired = Boolean(payload.setupRequired);\n _setConfig(payload.configs);\n\n // localStorage token + anonymous SSR payload = server couldn't read the\n // token (no cookie yet). Preserve the localStorage token and defer to\n // `reconcileSession()`; overwriting here would log the user out permanently.\n const existingLocalSession = getLocalStorageSession() as { authToken?: string } | null;\n const existingToken = existingLocalSession?.authToken;\n const ssrSession = payload.session as { authToken?: string };\n\n if (existingToken && !payload.user && existingToken !== ssrSession.authToken) {\n pendingReconciliation = true;\n // First render must match the server (anonymous); reconcile swaps later.\n useSessionStore.getState().setUser(parseUser(payload.user));\n return;\n }\n\n setLocalStorageSession(payload.session);\n useSessionStore.getState().setUser(parseUser(payload.user));\n}\n\n/** Re-auth via the body token when SSR couldn't read it from a cookie. */\nexport async function reconcileSession() {\n if (!pendingReconciliation) {\n return;\n }\n pendingReconciliation = false;\n\n try {\n const { configs, session, user } = await callMethod<SessionInitPayload>('_system.session.init');\n _setConfig(configs);\n setLocalStorageSession(session);\n useSessionStore.getState().setUser(parseUser(user));\n } catch (error) {\n console.error('Modelence: session reconciliation failed', error);\n }\n}\n\n/** @internal */\nexport function _isReconciliationPending(): boolean {\n return pendingReconciliation;\n}\n\nexport async function initSession() {\n if (isInitialized) {\n return;\n }\n\n isInitialized = true;\n\n const payload = await callMethod<SessionInitPayload>('_system.session.init');\n const { configs, session, user } = payload;\n setupRequired = Boolean(payload.setupRequired);\n _setConfig(configs);\n\n const config = getClientConfig();\n if (config) {\n config.setAuthToken(session.authToken);\n } else {\n setLocalStorageSession(session);\n }\n\n useSessionStore.getState().setUser(parseUser(user));\n\n await loopSessionHeartbeat();\n}\n\n/** Idempotent, client-only. Auto-started by `initSession`; call explicitly after `hydrateSession`. */\nexport async function startSessionHeartbeat() {\n if (typeof window === 'undefined' || heartbeatTimer !== null) {\n return;\n }\n await loopSessionHeartbeat();\n}\n\nasync function loopSessionHeartbeat() {\n if (typeof window === 'undefined') {\n return;\n }\n\n try {\n await callMethod('_system.session.heartbeat', {}, { errorHandler: () => {} });\n } catch {\n // Silently ignore heartbeat errors - they're expected during HMR/reconnects\n }\n heartbeatTimer = setTimeout(loopSessionHeartbeat, SESSION_HEARTBEAT_INTERVAL);\n}\n\nexport function setCurrentUser(user: unknown) {\n const enrichedUser = parseUser(user);\n useSessionStore.getState().setUser(enrichedUser);\n return enrichedUser;\n}\n\nexport function isSessionInitialized() {\n return isInitialized;\n}\n\nexport function getHeartbeatTimer() {\n return heartbeatTimer;\n}\n\nexport function stopHeartbeatTimer() {\n if (heartbeatTimer) {\n clearTimeout(heartbeatTimer);\n heartbeatTimer = null;\n }\n}\n\ntype SsrSessionResolver = () => User | null;\nlet ssrSessionResolver: SsrSessionResolver | null = null;\n\n/** @internal SSR resolver reads from AsyncLocalStorage (per-request scoped). */\nexport function _setSsrSessionResolver(resolver: SsrSessionResolver | null) {\n ssrSessionResolver = resolver;\n}\n\n/** @internal */\nexport function _parseSessionUser(user: unknown): User | null {\n return parseUser(user);\n}\n\n/**\n * `useSession` is a hook that returns the current user, and in the future will also return other details about the current session.\n *\n * @example\n * ```ts\n * import { useSession } from 'modelence/client';\n *\n * function MyComponent() {\n * const { user } = useSession();\n * return <div>{user?.handle}</div>;\n * }\n * ```\n */\nexport function useSession() {\n if (typeof window === 'undefined' && ssrSessionResolver) {\n return { user: ssrSessionResolver() };\n }\n const user = useSessionStore((state) => state.user);\n return { user };\n}\n"]}
@@ -1,3 +0,0 @@
1
- import {l,f as f$1,D,C,I,i,h as h$1,j as j$1,e}from'./chunk-W4RFIS5E.js';import {c}from'./chunk-5M6FUMUK.js';import {useState,useEffect}from'react';import {jsx,jsxs}from'react/jsx-runtime';import J from'socket.io-client';import {hashKey,QueryClient,QueryClientProvider,HydrationBoundary}from'@tanstack/react-query';var a={page:{minHeight:"100vh",backgroundColor:"#f3f4f6",display:"flex",alignItems:"center",justifyContent:"center",padding:"0 16px",fontFamily:"-apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif",color:"#111827"},container:{maxWidth:"576px",width:"100%"},logoWrap:{display:"flex",justifyContent:"center",marginBottom:"32px"},title:{fontSize:"30px",lineHeight:"36px",fontWeight:700,textAlign:"center",margin:0},subtitle:{marginTop:"16px",color:"#4b5563",textAlign:"center"},steps:{marginTop:"32px",listStyle:"none",padding:0,display:"flex",flexDirection:"column",gap:"16px"},step:{display:"flex",gap:"16px",alignItems:"flex-start",backgroundColor:"#ffffff",borderRadius:"8px",border:"1px solid #e5e7eb",padding:"16px"},stepNumber:{flex:"none",width:"28px",height:"28px",borderRadius:"9999px",backgroundColor:"#111827",color:"#ffffff",fontSize:"14px",fontWeight:600,display:"flex",alignItems:"center",justifyContent:"center"},stepText:{color:"#374151",lineHeight:"28px"},code:{fontSize:"14px",fontFamily:"ui-monospace, SFMono-Regular, Menlo, Consolas, 'Liberation Mono', monospace",backgroundColor:"#e5e7eb",borderRadius:"4px",padding:"2px 4px"},footer:{marginTop:"32px",fontSize:"14px",color:"#6b7280",textAlign:"center"}};function Q(){return jsx("div",{style:a.page,children:jsxs("div",{style:a.container,children:[jsx("div",{style:a.logoWrap,children:jsx("svg",{xmlns:"http://www.w3.org/2000/svg",width:"80",height:"80",viewBox:"0 0 48 48",fill:"none","aria-label":"Modelence Logo",children:jsx("path",{fill:"#5509D9",d:"M45 22.788V12L24 0l-9.437 5.392L45 22.788ZM25.152 35.24l10.589 6.052 8.107-4.632-10.589-6.052-8.107 4.632Zm9.26-15.872v9.264L45 34.684V25.42l-10.589-6.052ZM3 25.212V36l21 12 9.441-5.392L3 25.212ZM22.848 12.76 12.26 6.708 4.152 11.34l10.589 6.052 8.107-4.632Zm-9.26 15.872v-9.264L3 13.316v9.264l10.589 6.052Z"})})}),jsx("h1",{style:a.title,children:"Connect this project to Modelence Cloud"}),jsx("p",{style:a.subtitle,children:"One quick step before you can use this app locally."}),jsxs("ol",{style:a.steps,children:[jsxs(T,{number:1,children:["Run ",jsx("code",{style:a.code,children:"npx modelence setup"})," in the project folder."]}),jsx(T,{number:2,children:"Your browser opens \u2014 log in and choose your environment."}),jsxs(T,{number:3,children:["Restart the dev server (",jsx("code",{style:a.code,children:"npm run dev"}),")."]})]}),jsx("p",{style:a.footer,children:"This page refreshes automatically once the project is connected."})]})})}function T({number:e,children:t}){return jsxs("li",{style:a.step,children:[jsx("span",{style:a.stepNumber,children:e}),jsx("span",{style:a.stepText,children:t})]})}var V="__MODELENCE_STATE__",z=3e3,U=false;function Y(){return typeof document<"u"&&document.getElementById(V)!==null}function xe({children:e,loadingElement:t,setupElement:n}){let r=typeof window>"u",[i$1,l$1]=useState(()=>!r&&!l()&&!Y()),[d,s]=useState(()=>!r&&l()&&f$1());return useEffect(()=>{async function c(){if(!U){if(U=true,l()){i()&&await h$1(),s(f$1());return}await j$1(),s(f$1()),l$1(false);}}c();},[]),useEffect(()=>{if(!d)return;let c=false,o;async function p(){try{let{setupRequired:$}=await I("_system.setupStatus",{},{errorHandler:()=>{}});if(!$){window.location.reload();return}}catch{}c||(o=setTimeout(p,z));}return o=setTimeout(p,z),()=>{c=true,clearTimeout(o);}},[d]),i$1?t??jsx("div",{children:"Loading..."}):d&&n!==null?n??jsx(Q,{}):e}var v=null,m=new Map;function h(){if(!v)throw new Error("WebSocket not initialized. Call startWebsockets() first.");return v}function G(){let e=C(),t=D();for(let n of m.values())v?.emit("subscribeLiveQuery",{subscriptionId:n.subscriptionId,method:n.method,args:n.args,authToken:e,clientInfo:t});}function X(e$1){let t=e()?.baseUrl??"/";v=J(t,{transports:["websocket"],auth:{token:C()}}),v.on("connect",()=>{m.size>0&&(console.log(`[Modelence] WebSocket reconnected, re-subscribing to ${m.size} live queries`),G());}),e$1.channels?.forEach(n=>n.init());}function ee({category:e,listener:t}){h().on(e,t);}function te({category:e,listener:t}){h().once(e,t);}function ne({category:e,listener:t}){h().off(e,t);}function R({eventName:e,category:t,id:n}){h().emit(e,`${t}:${n}`);}function re({category:e,id:t}){R({eventName:"joinChannel",category:e,id:t});}function oe({category:e,id:t}){R({eventName:"leaveChannel",category:e,id:t});}var ie=0;function M(e,t,n,r){let i=`sub-${++ie}-${Date.now()}`,l=({subscriptionId:c$1,data:o,typeMap:p})=>{c$1===i&&n(c(o,p));},d=({subscriptionId:c,error:o})=>{c===i&&(console.error(`[Modelence] Live query error for ${e}:`,o),r?.(o));},s=h();return s.on("liveQueryData",l),s.on("liveQueryError",d),m.set(i,{subscriptionId:i,method:e,args:t}),s.connected&&s.emit("subscribeLiveQuery",{subscriptionId:i,method:e,args:t,authToken:C(),clientInfo:D()}),()=>{m.delete(i),s.emit("unsubscribeLiveQuery",{subscriptionId:i}),s.off("liveQueryData",l),s.off("liveQueryError",d);}}var se={init:X,on:ee,once:te,off:ne,emit:R,joinChannel:re,leaveChannel:oe},O=se;var E=null;function F(e){E=e;}function Le(){return E}function j(e){if(E){console.warn("WebSocket already initialized. Skipping initialization.");return}let t=e?.provider||O;F(t);try{t.init({channels:e?.channels});}catch(n){throw F(null),n}}var y=null,w=null,P=false,f=new Map;function L(e){y!==e&&(y&&ce(),y=e,w=e.getQueryCache().subscribe(t=>{if(t.type==="removed"){let n=hashKey(t.query.queryKey),r=f.get(n);if(r){if(r.resolvers.size>0){let i=new Error("Query was removed from cache");r.resolvers.forEach(l=>l.reject(i)),r.resolvers.clear();}r.unsubscribe(),f.delete(n);}}}));}function De(){return y!==null}function ce(){w&&(w(),w=null),f.forEach(e=>e.unsubscribe()),f.clear(),y=null,P=false;}var B=class{connect(t){L(t);}};function qe(e,t={}){return {queryKey:[e,t],queryFn:()=>I(e,t)}}function ze(e,t={}){let n=["live",e,t],r=hashKey(n);return {queryKey:n,queryFn:()=>new Promise((i,l)=>{if(typeof window>"u")return;if(!y){let s=new Error("Modelence: connect a QueryClient before using modelenceLiveQuery(). Mount <ModelenceQueryProvider> or call connectModelenceQueryClient().");console.error("[Modelence]",s.message),l(s);return}P||(j(),P=true);let d=f.get(r);d||(d={unsubscribe:M(e,t,c=>{let o=f.get(r);o?.resolvers.size&&(o.resolvers.forEach(p=>p.resolve(c)),o.resolvers.clear()),y&&y.setQueryData(n,c);},c=>{let o=f.get(r);o&&(o.resolvers.size&&(o.resolvers.forEach(p=>p.reject(new Error(c))),o.resolvers.clear()),o.unsubscribe(),f.delete(r));}),resolvers:new Set},f.set(r,d)),d.resolvers.add({resolve:i,reject:l});}),staleTime:1/0,refetchOnWindowFocus:false,refetchOnMount:false,refetchOnReconnect:false,gcTime:0}}function Ue(e,t={}){return {mutationFn:(n={})=>I(e,{...t,...n})}}function Ke(e,t={}){return [e,t]}var fe="__MODELENCE_QUERY_STATE__";function pe(){if(typeof document>"u")return;let e=document.getElementById(fe);if(!(!e||!e.textContent))try{return JSON.parse(e.textContent)}catch(t){console.error("Modelence: failed to parse SSR query state",t);return}}function He({children:e,client:t,dehydratedState:n}){let[r]=useState(()=>{let l=t??new QueryClient({defaultOptions:{queries:{staleTime:6e4}}});return typeof window<"u"&&L(l),l}),i=n??pe();return jsx(QueryClientProvider,{client:r,children:jsx(HydrationBoundary,{state:i,children:e})})}
2
- export{xe as a,M as b,F as c,Le as d,j as e,L as f,De as g,ce as h,B as i,qe as j,ze as k,Ue as l,Ke as m,He as n};//# sourceMappingURL=chunk-WDY7BYXR.js.map
3
- //# sourceMappingURL=chunk-WDY7BYXR.js.map
@@ -1,2 +0,0 @@
1
- export{c as _getSsrSnapshot,d as renderApp}from'./chunk-4I4BI7KD.js';import'./chunk-WDY7BYXR.js';import'./chunk-W4RFIS5E.js';import'./chunk-5M6FUMUK.js';import'./chunk-DO5TZLF5.js';//# sourceMappingURL=renderApp-MD5O44UP.js.map
2
- //# sourceMappingURL=renderApp-MD5O44UP.js.map
@@ -1,2 +0,0 @@
1
- export{g as getCallContext,f as startServer}from'./chunk-LCXJNLNK.js';import'./chunk-KFTT3M45.js';import'./chunk-KDOTVIEY.js';import'./chunk-VYR7VQMQ.js';import'./chunk-UW37F3GV.js';import'./chunk-5M6FUMUK.js';import'./chunk-DO5TZLF5.js';//# sourceMappingURL=server-GHQ5XNNQ.js.map
2
- //# sourceMappingURL=server-GHQ5XNNQ.js.map
@@ -1,2 +0,0 @@
1
- import {c,a}from'./chunk-UJ2WYHH7.js';import'./chunk-KDOTVIEY.js';import'./chunk-UW37F3GV.js';import {H,G}from'./chunk-W4RFIS5E.js';import'./chunk-5M6FUMUK.js';import'./chunk-DO5TZLF5.js';function d(){return H(async(t,r)=>{let o=c();return o?a(t,r,o.callContext):G(t,r)})}export{d as installSsrCallMethodTransport};//# sourceMappingURL=transport-VKGH6BY6.js.map
2
- //# sourceMappingURL=transport-VKGH6BY6.js.map