modelence 0.24.0 → 0.24.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/dist/{chunk-V3EQDOEU.js → chunk-3RGPZ5RE.js} +3 -3
  2. package/dist/{chunk-V3EQDOEU.js.map → chunk-3RGPZ5RE.js.map} +1 -1
  3. package/dist/chunk-BQ4WG67Z.js +2 -0
  4. package/dist/chunk-BQ4WG67Z.js.map +1 -0
  5. package/dist/chunk-BVJJCQ6Y.js +4 -0
  6. package/dist/chunk-BVJJCQ6Y.js.map +1 -0
  7. package/dist/{chunk-NPBIRXLC.js → chunk-CAN2CWEI.js} +2 -2
  8. package/dist/{chunk-NPBIRXLC.js.map → chunk-CAN2CWEI.js.map} +1 -1
  9. package/dist/chunk-NMG65UCR.js +3 -0
  10. package/dist/chunk-NMG65UCR.js.map +1 -0
  11. package/dist/chunk-VKGZ35WJ.js +2 -0
  12. package/dist/chunk-VKGZ35WJ.js.map +1 -0
  13. package/dist/{chunk-6FAEWW7A.js → chunk-VVJ5HBG5.js} +5 -5
  14. package/dist/{chunk-6FAEWW7A.js.map → chunk-VVJ5HBG5.js.map} +1 -1
  15. package/dist/client.d.ts +48 -8
  16. package/dist/client.js +1 -1
  17. package/dist/{package-PLJALKWH.js → package-FRHPJWXY.js} +2 -2
  18. package/dist/{package-PLJALKWH.js.map → package-FRHPJWXY.js.map} +1 -1
  19. package/dist/render-7S2MBT7R.js +2 -0
  20. package/dist/{render-RQCPSN7B.js.map → render-7S2MBT7R.js.map} +1 -1
  21. package/dist/renderApp-RWQKYP54.js +2 -0
  22. package/dist/{renderApp-UF5FLZHD.js.map → renderApp-RWQKYP54.js.map} +1 -1
  23. package/dist/server-BR352GUJ.js +2 -0
  24. package/dist/{server-GF7ON6QY.js.map → server-BR352GUJ.js.map} +1 -1
  25. package/dist/server.js +1 -1
  26. package/dist/transport-QMFZ67HR.js +2 -0
  27. package/dist/{transport-3V4KGAAU.js.map → transport-QMFZ67HR.js.map} +1 -1
  28. package/package.json +1 -1
  29. package/dist/chunk-63RBLFRJ.js +0 -4
  30. package/dist/chunk-63RBLFRJ.js.map +0 -1
  31. package/dist/chunk-DKK3TACA.js +0 -3
  32. package/dist/chunk-DKK3TACA.js.map +0 -1
  33. package/dist/chunk-LR6IBZVP.js +0 -2
  34. package/dist/chunk-LR6IBZVP.js.map +0 -1
  35. package/dist/chunk-WD5PEREO.js +0 -2
  36. package/dist/chunk-WD5PEREO.js.map +0 -1
  37. package/dist/render-RQCPSN7B.js +0 -2
  38. package/dist/renderApp-UF5FLZHD.js +0 -2
  39. package/dist/server-GF7ON6QY.js +0 -2
  40. package/dist/transport-3V4KGAAU.js +0 -2
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/config/client.ts","../src/client/localStorage.ts","../src/client/clientConfig.ts","../src/auth/client/oauthVerifier.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","pendingVerifier","STORAGE_KEY","getSessionStorage","storage","probe","randomHex","byteLength","bytes","cryptoObj","i","out","byte","startOAuthVerifier","consumeOAuthVerifier","verifier","resetOAuthVerifier","persistSession","completeLogin","result","setCurrentUser","signupWithPassword","options","email","password","handle","firstName","lastName","avatarUrl","callMethod","loginWithPassword","updateProfile","user","verifyEmail","token","resendEmailVerification","logout","sendResetPasswordToken","sendMagicLink","loginWithMagicLink","loginWithOneTimeCode","code","resetPassword","signInWithOAuth","provider","redirectUri","baseUrl","codeChallenge","url","webUrl","loginWithOAuth","codeVerifier","linkOAuthProvider","getAuthToken","nonceResponse","nonce","unlinkOAuthProvider","getClientInfo","errorHandler","error","methodName","setErrorHandler","handler","handleError","MethodError","message","status","defaultCallMethodTransport","args","call","TRANSPORT_KEY","getTransport","setCallMethodTransport","next","previous","endpoint","response","text","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,CAAAA,CAAuC,EAAC,CAGxCC,CAAAA,CAA8C,KAG3C,SAASC,CAAAA,CAAsBC,CAAAA,CAAoC,CACxEF,CAAAA,CAAoBE,EACtB,CAQO,SAASC,EAAAA,CAAUC,EAAuD,CAC/E,OAAI,OAAO,MAAA,CAAW,GAAA,EAAeJ,CAAAA,CAC5BA,CAAAA,CAAkBI,CAAG,CAAA,CAEvBL,EAAOK,CAAG,CAAA,EAAG,KACtB,CAEO,SAASC,EAAWC,CAAAA,CAAkB,CAC3CP,CAAAA,CAASO,EACX,CC3BA,IAAMC,EAAc,mBAAA,CAEpB,SAASC,GAA2B,CAClC,OAAO,OAAO,UAAA,CAAe,GAAA,EAAe,OAAO,UAAA,CAAW,YAAA,CAAiB,GACjF,CAEO,SAASC,CAAAA,EAAyB,CACvC,GAAI,CAACD,GAAgB,CACnB,OAAO,IAAA,CAGT,IAAME,CAAAA,CAAc,UAAA,CAAW,aAAa,OAAA,CAAQH,CAAW,EAC/D,GAAI,CACF,OAAOG,CAAAA,CAAc,IAAA,CAAK,KAAA,CAAMA,CAAW,CAAA,CAAI,IACjD,OAASC,CAAAA,CAAG,CACV,eAAQ,KAAA,CAAM,yCAAA,CAA2CA,CAAC,CAAA,CACnD,IACT,CACF,CAEO,SAASC,CAAAA,CAAuBC,EAAiB,CACjDL,CAAAA,EAAgB,EAIrB,UAAA,CAAW,YAAA,CAAa,OAAA,CAAQD,EAAa,IAAA,CAAK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A,CAAMA,CAAAA,EAAqB,CAAA,CAG/B,CAAE,IAAA,CADI1B,EAAiB8B,CAAAA,EAAUA,CAAAA,CAAM,IAAI,CACpC,CAChB","file":"chunk-WD5PEREO.js","sourcesContent":["import { AppConfig, ConfigKey, 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","/**\n * Device-side binding for the native OAuth flow (PKCE-style).\n *\n * The deep link that carries the exchange code back into the app is the weakest\n * hop in the chain: a custom scheme can be claimed by any installed app, and a\n * crafted `myapp://auth?code=...` can be handed to the device from outside the\n * flow entirely. Without a device-held secret, redeeming such a code silently\n * rebinds the session to whoever minted it.\n *\n * So `signInWithOAuth` mints a verifier, keeps it in memory, and sends only a\n * derived challenge to the server. `loginWithOAuth` replays the verifier at\n * redemption, and the server checks it against the challenge bound to the code\n * when it was minted. A code minted for an attacker's flow carries the\n * attacker's challenge and cannot be redeemed by this device.\n *\n * Why not the RFC 7636 `S256` transform: bare React Native ships neither\n * `crypto.subtle` nor `crypto.getRandomValues`, so a SHA-256 challenge would\n * force a native crypto dependency on every consumer. The challenge is instead\n * sent as the verifier itself over TLS and stored only as a hash server-side,\n * which is the `plain` method of the same RFC. The property that matters here —\n * a code is redeemable only by the device that started the flow — is identical;\n * what `S256` additionally protects against is a challenge leaking from the\n * *authorization request*, which for us never leaves the TLS channel between\n * the app and its own server.\n */\n\n/** Verifier length in characters. 32 bytes of entropy, hex-encoded. */\nconst VERIFIER_BYTES = 32;\n\n/**\n * The verifier for the in-flight sign-in.\n *\n * Memory suffices on native, where the app survives in the background. A\n * browser — including Expo Web, where `Linking.openURL` navigates the same tab —\n * tears down this module on the way to the provider, so it is mirrored into\n * `sessionStorage`: tab-scoped and discarded on close, which fits a credential\n * that lives for one redirect round trip.\n */\nlet pendingVerifier: string | null = null;\nconst STORAGE_KEY = 'modelence.oauth.verifier';\n\n/**\n * Returns `sessionStorage` when it is usable, else null. Access can throw\n * outright (Safari private mode, webviews with storage disabled), and presence\n * does not imply usability — hence the probe.\n */\nfunction getSessionStorage(): Storage | null {\n try {\n const storage = (globalThis as { sessionStorage?: Storage }).sessionStorage;\n if (!storage) return null;\n const probe = `${STORAGE_KEY}.probe`;\n storage.setItem(probe, '1');\n storage.removeItem(probe);\n return storage;\n } catch {\n return null;\n }\n}\n\n/**\n * Random hex string from the best source the runtime offers.\n *\n * Bare React Native has no `crypto.getRandomValues`, so `Math.random` is the\n * fallback. It is weaker than a CSPRNG, but the verifier only needs to resist an\n * attacker who cannot read process memory — and one who can has already won.\n */\nfunction randomHex(byteLength: number): string {\n const bytes = new Uint8Array(byteLength);\n\n const cryptoObj = (globalThis as { crypto?: Crypto }).crypto;\n if (cryptoObj?.getRandomValues) {\n cryptoObj.getRandomValues(bytes);\n } else {\n for (let i = 0; i < bytes.length; i++) {\n bytes[i] = Math.floor(Math.random() * 256);\n }\n }\n\n let out = '';\n for (const byte of bytes) {\n out += byte.toString(16).padStart(2, '0');\n }\n return out;\n}\n\n/**\n * Mints a fresh verifier for a new sign-in and returns the challenge to send.\n *\n * Any previously pending verifier is discarded: only the most recently started\n * flow is redeemable, so an abandoned flow cannot be completed later.\n */\nexport function startOAuthVerifier(): string {\n pendingVerifier = randomHex(VERIFIER_BYTES);\n\n // Mirrored so a browser flow survives the navigation to the provider. Failure\n // to persist is not fatal: native runtimes rely on the in-memory copy.\n try {\n getSessionStorage()?.setItem(STORAGE_KEY, pendingVerifier);\n } catch {\n // Storage full or blocked mid-flow; the in-memory value still applies.\n }\n\n return pendingVerifier;\n}\n\n/**\n * Returns the pending verifier and clears it, so a given verifier is replayed\n * at most once even if the deep link fires twice.\n */\nexport function consumeOAuthVerifier(): string | null {\n // In-memory first: it is authoritative on native and identical on web when\n // the page was never replaced.\n const verifier = pendingVerifier ?? getSessionStorage()?.getItem(STORAGE_KEY) ?? null;\n resetOAuthVerifier();\n return verifier;\n}\n\n/**\n * Drops only the in-memory copy, leaving any persisted one intact.\n *\n * Exists to let tests reproduce a page navigation, which is precisely the case\n * the persisted copy exists for: the module is rebuilt, storage is not.\n */\nexport function __resetInMemoryVerifierForTests(): void {\n pendingVerifier = null;\n}\n\n/** Clears any pending verifier. Exposed for tests and for abandoning a flow. */\nexport function resetOAuthVerifier(): void {\n pendingVerifier = null;\n try {\n getSessionStorage()?.removeItem(STORAGE_KEY);\n } catch {\n // Nothing to do — a verifier that cannot be cleared still expires with the tab.\n }\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';\nimport { consumeOAuthVerifier, startOAuthVerifier } from './oauthVerifier';\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 * Stores the session from a completed sign-in and returns the enriched user.\n *\n * Every login method ends the same way — persist the auth token, then publish\n * the user to the reactive session store. Kept in one place so a new sign-in\n * method cannot half-implement it.\n */\nfunction completeLogin(result: { user: RawUserData; session: { authToken: string } }) {\n persistSession(result.session);\n return setCurrentUser(result.user);\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 result = await callMethod<{ user: RawUserData; session: { authToken: string } }>(\n '_system.user.loginWithPassword',\n {\n email,\n password,\n }\n );\n return completeLogin(result);\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 result = await callMethod<{ user: RawUserData; session: { authToken: string } }>(\n '_system.user.loginWithMagicLink'\n );\n return completeLogin(result);\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 result = await callMethod<{ user: RawUserData; session: { authToken: string } }>(\n '_system.user.loginWithOneTimeCode',\n { email, code }\n );\n return completeLogin(result);\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 * Start an OAuth sign-in.\n *\n * On the web this navigates to the provider and the flow finishes on its own —\n * the session cookie is set and the browser lands back on your site.\n *\n * Pass `redirectUri` to run the native flow: the device browser opens the\n * provider, and when the flow completes Modelence redirects back to that deep\n * link with a single-use `code` query parameter. Hand that code to\n * {@link loginWithOAuth} to finish signing in. The redirect target must be\n * listed in the server's `auth.mobile.redirectUrls`, otherwise the request is\n * rejected before the provider is ever reached.\n *\n * The native flow additionally binds the sign-in to this device: a verifier is\n * held in memory here and replayed by `loginWithOAuth`, so a `code` delivered\n * to the app from outside this flow cannot be redeemed.\n *\n * @example Web\n * ```ts\n * await signInWithOAuth({ provider: 'google' });\n * ```\n *\n * @example React Native\n * ```ts\n * import { parseDeepLinkParams } from 'modelence/client';\n *\n * await signInWithOAuth({ provider: 'google', redirectUri: 'myapp://auth' });\n *\n * Linking.addEventListener('url', async ({ url }) => {\n * const { code } = parseDeepLinkParams(url);\n * if (code) await loginWithOAuth({ code });\n * });\n * ```\n * @param options.provider - The OAuth provider to sign in with ('google' or 'github').\n * @param options.redirectUri - Deep link to return to. Required on React Native.\n */\nexport async function signInWithOAuth(options: {\n provider: OAuthProvider;\n redirectUri?: string;\n}): Promise<void> {\n const { provider, redirectUri } = options;\n const config = getClientConfig();\n const baseUrl = config?.baseUrl ?? '';\n\n // `redirectUri` — not the presence of `openUrl` — decides the flow. An\n // Electron or Capacitor client may set `openUrl` purely to control how links\n // open while still completing the ordinary cookie-based web flow.\n if (redirectUri) {\n if (!config?.openUrl) {\n throw new Error(\n 'signInWithOAuth was given a redirectUri but the client has no openUrl. ' +\n 'Configure openUrl (e.g. (url) => Linking.openURL(url)) to use the native flow.'\n );\n }\n\n const codeChallenge = startOAuthVerifier();\n const url =\n `${baseUrl}/api/_internal/auth/${provider}?mode=login&platform=mobile` +\n `&redirectUri=${encodeURIComponent(redirectUri)}` +\n `&codeChallenge=${encodeURIComponent(codeChallenge)}`;\n config.openUrl(url);\n return;\n }\n\n const webUrl = `${baseUrl}/api/_internal/auth/${provider}?mode=login`;\n if (config?.openUrl) {\n config.openUrl(webUrl);\n return;\n }\n\n window.location.href = webUrl;\n}\n\n/**\n * Complete a native OAuth sign-in with the code from the deep link.\n *\n * Exchanges the single-use code that {@link signInWithOAuth} delivered to your\n * app's deep link for a session, stores the auth token, and returns the\n * signed-in user. Codes are valid for one minute and can only be redeemed once.\n *\n * Pairs with `signInWithOAuth({ provider, redirectUri })` — the flow that hands\n * a code back to your app. It works on native and under Expo Web, where the\n * verifier is kept in `sessionStorage` so it survives the navigation to the\n * provider. A plain web app that calls `signInWithOAuth({ provider })` with no\n * `redirectUri` is signed in by a session cookie and never needs this.\n *\n * The verifier minted by `signInWithOAuth` is replayed here, which is what\n * makes a code usable only by the client that started the flow. Calling this\n * without a preceding `signInWithOAuth` — as a crafted deep link would — fails\n * before the code is ever sent.\n *\n * @example\n * ```ts\n * const user = await loginWithOAuth({ code });\n * ```\n * @param options.code - The `code` query parameter from the deep link.\n */\nexport async function loginWithOAuth(options: { code: string }) {\n const { code } = options;\n\n const codeVerifier = consumeOAuthVerifier();\n if (!codeVerifier) {\n // Thrown mid-flow, so apps surface it in the UI: the thrown message is for\n // the end user, the console line for whoever is debugging.\n console.error(\n '[modelence] loginWithOAuth was called with no sign-in in progress. ' +\n 'Either signInWithOAuth was never called on this client, or the code came ' +\n 'from somewhere other than a flow this client started. On native, the app ' +\n 'process must survive the round trip; in a browser the verifier is kept in ' +\n 'sessionStorage, so a new tab or a cleared session also produces this. ' +\n 'A plain web app that never calls signInWithOAuth({ redirectUri }) does not ' +\n 'need loginWithOAuth at all — the cookie flow signs the user in on its own.'\n );\n\n throw new Error('This sign-in link is no longer valid. Please sign in again.');\n }\n\n const result = await callMethod<{ user: RawUserData; session: { authToken: string } }>(\n '_system.user.loginWithOAuth',\n { code, codeVerifier }\n );\n return completeLogin(result);\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 * Without `redirectUri` this navigates the current context and authenticates\n * with an httpOnly cookie, so it only works where the navigation stays in the\n * same cookie jar — a browser, or a webview that navigates in place. Clients\n * whose `openUrl` opens an external browser (Electron, Capacitor) must pass a\n * `redirectUri`: that flow carries a single-use nonce in the URL and does not\n * depend on cookies.\n *\n * @example\n * ```ts\n * linkOAuthProvider({ provider: 'google' });\n * ```\n * @param options.provider - The OAuth provider to link ('google' or 'github').\n * @param options.redirectUri - Deep link to return to once linking completes.\n * Required for React Native and any client that opens URLs externally; must be\n * listed in the server's `auth.mobile.redirectUrls`. Without it the flow ends\n * wherever the navigation lands rather than back in the app.\n */\nexport async function linkOAuthProvider(options: {\n provider: OAuthProvider;\n redirectUri?: string;\n}): Promise<void> {\n const { provider, redirectUri } = options;\n const config = getClientConfig();\n const baseUrl = config?.baseUrl ?? '';\n\n if (redirectUri) {\n if (!config?.openUrl) {\n throw new Error(\n 'linkOAuthProvider was given a redirectUri but the client has no openUrl. ' +\n 'Configure openUrl (e.g. (url) => Linking.openURL(url)) to use the native flow.'\n );\n }\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 =\n `${baseUrl}/api/_internal/auth/${provider}?mode=link` +\n `&linkNonce=${encodeURIComponent(nonce)}` +\n `&platform=mobile&redirectUri=${encodeURIComponent(redirectUri)}`;\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 // Same-context navigation, not `config.openUrl`: this authenticates with the\n // httpOnly cookie just set on this origin, and `openUrl` may open a system\n // browser that never received it. (`signInWithOAuth` can use `openUrl` on\n // its web path because that path is stateless.) Clients that open externally\n // should pass a `redirectUri` and take the nonce flow above.\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,2 +0,0 @@
1
- import {a,b,c}from'./chunk-NPBIRXLC.js';import'./chunk-63RBLFRJ.js';import'./chunk-UW37F3GV.js';import {a as a$1,n}from'./chunk-DKK3TACA.js';import {m,a as a$2,n as n$1}from'./chunk-WD5PEREO.js';import'./chunk-5M6FUMUK.js';import'./chunk-DO5TZLF5.js';import {renderToPipeableStream}from'react-dom/server';import {Writable}from'stream';import {QueryClient,dehydrate}from'@tanstack/react-query';import {jsx}from'react/jsx-runtime';var J=()=>{let r=c();return r?n$1(r.session.user):null},M=r=>{let n=c();if(n)return n.session.configs[r]?.value};function D(){m(J),a$2(M);}async function X(r){let{callContext:n$1,loadingElement:C,routesElement:S,router:u,location:x,onShellReady:E,onError:b$1}=r;D();let l=await a("_system.session.init",{},n$1),i=new QueryClient({defaultOptions:{queries:{retry:false,gcTime:0}}}),O=u?u({children:S,location:x}):S,Q=jsx(a$1,{loadingElement:C,children:jsx(n,{client:i,children:O})}),a$2=null;await new Promise((s,m)=>{b({callContext:n$1,queryClient:i,session:{user:l.user,configs:l.configs??{}}},()=>{let e=renderToPipeableStream(Q,{onShellReady(){a$2=e,E?.(),s(e);},onShellError(t){m(t);},onError(t){b$1?.(t);}});return e});});let d=null,_=s=>new Promise((m,e)=>{if(!a$2){e(new Error("SSR stream was not initialized"));return}let t=new Writable({write(o,c,I){s.write(o,N=>I(N??void 0));},final(o){try{let c=dehydrate(i);d=JSON.stringify(c);}finally{i.clear();}o(),m();}});t.on("error",o=>{s.destroy(o),e(o);}),s.on("error",e),a$2.pipe(t);});return {sessionState:JSON.stringify({session:l}),pipe:_,getQueryState:()=>{if(d===null)throw new Error("getQueryState() called before stream finished");return d}}}export{X as renderSsrTreeStream};//# sourceMappingURL=render-RQCPSN7B.js.map
2
- //# sourceMappingURL=render-RQCPSN7B.js.map
@@ -1,2 +0,0 @@
1
- export{c as _getSsrSnapshot,d as renderApp}from'./chunk-LR6IBZVP.js';import'./chunk-DKK3TACA.js';import'./chunk-WD5PEREO.js';import'./chunk-5M6FUMUK.js';import'./chunk-DO5TZLF5.js';//# sourceMappingURL=renderApp-UF5FLZHD.js.map
2
- //# sourceMappingURL=renderApp-UF5FLZHD.js.map
@@ -1,2 +0,0 @@
1
- export{g as getCallContext,f as startServer}from'./chunk-6FAEWW7A.js';import'./chunk-V3EQDOEU.js';import'./chunk-63RBLFRJ.js';import'./chunk-VYR7VQMQ.js';import'./chunk-UW37F3GV.js';import'./chunk-5M6FUMUK.js';import'./chunk-DO5TZLF5.js';//# sourceMappingURL=server-GF7ON6QY.js.map
2
- //# sourceMappingURL=server-GF7ON6QY.js.map
@@ -1,2 +0,0 @@
1
- import {c,a}from'./chunk-NPBIRXLC.js';import'./chunk-63RBLFRJ.js';import'./chunk-UW37F3GV.js';import {J,I}from'./chunk-WD5PEREO.js';import'./chunk-5M6FUMUK.js';import'./chunk-DO5TZLF5.js';function d(){return J(async(t,r)=>{let o=c();return o?a(t,r,o.callContext):I(t,r)})}export{d as installSsrCallMethodTransport};//# sourceMappingURL=transport-3V4KGAAU.js.map
2
- //# sourceMappingURL=transport-3V4KGAAU.js.map