modelence 0.19.1 → 0.20.0-files.dev.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/bin/modelence.js +2 -2
- package/dist/bin/modelence.js.map +1 -1
- package/dist/chunk-5LP23CUB.js +3 -0
- package/dist/chunk-5LP23CUB.js.map +1 -0
- package/dist/chunk-A2J5PPAQ.js +29 -0
- package/dist/chunk-A2J5PPAQ.js.map +1 -0
- package/dist/chunk-GPKIS2JI.js +3 -0
- package/dist/chunk-GPKIS2JI.js.map +1 -0
- package/dist/chunk-JDYWT45S.js +2 -0
- package/dist/chunk-JDYWT45S.js.map +1 -0
- package/dist/chunk-TBGXZXAA.js +2 -0
- package/dist/chunk-TBGXZXAA.js.map +1 -0
- package/dist/chunk-YLLX26A4.js +2 -0
- package/dist/chunk-YLLX26A4.js.map +1 -0
- package/dist/chunk-YRR32LTF.js +2 -0
- package/dist/chunk-YRR32LTF.js.map +1 -0
- package/dist/client.d.ts +67 -23
- package/dist/client.js +1 -1
- package/dist/client.js.map +1 -1
- package/dist/collectCss-4YETFI7P.js +2 -0
- package/dist/collectCss-4YETFI7P.js.map +1 -0
- package/dist/{index-CLpVWWuj.d.ts → index-CgNFVSg6.d.ts} +1 -1
- package/dist/index.d.ts +2 -2
- package/dist/index.js +1 -1
- package/dist/{package-FOVTOR5M.js → package-OLG24DKG.js} +2 -2
- package/dist/{package-FOVTOR5M.js.map → package-OLG24DKG.js.map} +1 -1
- package/dist/render-A7HWHWAE.js +2 -0
- package/dist/render-A7HWHWAE.js.map +1 -0
- package/dist/renderApp-QYMNQ3KS.js +2 -0
- package/dist/renderApp-QYMNQ3KS.js.map +1 -0
- package/dist/server-OYDAIDR6.js +2 -0
- package/dist/server-OYDAIDR6.js.map +1 -0
- package/dist/server.d.ts +37 -9
- package/dist/server.js +1 -20
- package/dist/server.js.map +1 -1
- package/dist/transport-BBEHTFCG.js +2 -0
- package/dist/transport-BBEHTFCG.js.map +1 -0
- package/dist/{types-CzGfkwti.d.ts → types-B_R3eHmq.d.ts} +6 -6
- package/dist/{types-JMIT4IDG.d.ts → types-_BTBqn8b.d.ts} +2 -2
- package/dist/types.d.ts +3 -3
- package/package.json +3 -1
- package/dist/chunk-VBRGC3XM.js +0 -3
- package/dist/chunk-VBRGC3XM.js.map +0 -1
- package/dist/types-DLDzAym7.d.ts +0 -8
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/client/AppProvider.tsx","../src/websocket/socketio/client.ts","../src/websocket/client.ts","../src/client/query.ts","../src/client/queryProvider.tsx"],"names":["SSR_STATE_SCRIPT_ID","isInitialized","hasServerRenderedMarkup","AppProvider","children","loadingElement","isServer","isLoading","setIsLoading","useState","isSessionInitialized","useEffect","initConfig","_isReconciliationPending","reconcileSession","initSession","jsx","socketClient","activeLiveSubscriptions","getSocket","resubscribeAll","authToken","getAuthToken","clientInfo","getClientInfo","sub","init","props","baseUrl","getClientConfig","io","channel","on","category","listener","once","off","emit","eventName","id","joinChannel","leaveChannel","liveQueryCounter","subscribeLiveQuery","method","args","onData","onError","subscriptionId","handleData","sid","data","typeMap","reviveResponseTypes","handleError","error","socket","websocketProvider","client_default","websocketClientProvider","setWebsocketClientProvider","provider","getWebsocketClientProvider","startWebsockets","queryClientRef","cacheUnsubscribe","websocketsStarted","subscriptions","connectModelenceQueryClient","queryClient","disconnectModelenceQueryClient","event","subscriptionKey","hashKey","cancelError","r","hasConnectedQueryClient","ModelenceQueryClient","modelenceQuery","methodName","callMethod","modelenceLiveQuery","queryKey","resolve","reject","currentSub","modelenceMutation","defaultArgs","variables","createQueryKey","SSR_QUERY_STATE_SCRIPT_ID","readDehydratedState","node","e","ModelenceQueryProvider","client","dehydratedState","internalClient","qc","QueryClient","state","QueryClientProvider","HydrationBoundary"],"mappings":"oTAiBA,IAAMA,CAAAA,CAAsB,qBAAA,CAOxBC,CAAAA,CAAgB,KAAA,CAKpB,SAASC,CAAAA,EAAmC,CAC1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AAAA,EACA,IAAII,WAAAA,CAAY,CACd,cAAA,CAAgB,CACd,OAAA,CAAS,CACP,SAAA,CAAW,GACb,CACF,CACF,CAAC,CAAA,CACH,OAAI,OAAO,MAAA,CAAW,GAAA,EACpB/B,CAAAA,CAA4B8B,CAAE,CAAA,CAEzBA,CACT,CAAC,CAAA,CAEKE,CAAAA,CAAQJ,CAAAA,EAAmBL,EAAAA,EAAoB,CAErD,OACE3E,GAAAA,CAACqF,mBAAAA,CAAA,CAAoB,MAAA,CAAQJ,CAAAA,CAC3B,QAAA,CAAAjF,GAAAA,CAACsF,iBAAAA,CAAA,CAAkB,KAAA,CAAOF,CAAAA,CAAQ,QAAA,CAAAhG,CAAAA,CAAS,CAAA,CAC7C,CAEJ","file":"chunk-YRR32LTF.js","sourcesContent":["/*\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 React, { useState, useEffect, ReactNode } from 'react';\nimport {\n _isReconciliationPending,\n initSession,\n isSessionInitialized,\n reconcileSession,\n} from './session';\n\nconst SSR_STATE_SCRIPT_ID = '__MODELENCE_STATE__';\n\ninterface AppProviderProps {\n children: ReactNode;\n loadingElement?: ReactNode;\n}\n\nlet isInitialized = false;\n\n// Presence of the state script signals server-rendered markup in the DOM,\n// even if `hydrateSession` failed to parse it. Hiding under a loading shell\n// here would cause a hydration mismatch and a flash-of-spinner.\nfunction hasServerRenderedMarkup(): boolean {\n return typeof document !== 'undefined' && document.getElementById(SSR_STATE_SCRIPT_ID) !== null;\n}\n\nexport function AppProvider({ children, loadingElement }: AppProviderProps) {\n const isServer = typeof window === 'undefined';\n const [isLoading, setIsLoading] = useState(\n () => !isServer && !isSessionInitialized() && !hasServerRenderedMarkup()\n );\n\n useEffect(() => {\n async function initConfig() {\n if (isInitialized) {\n return;\n }\n\n isInitialized = true;\n\n if (isSessionInitialized()) {\n // SSR couldn't authenticate via cookie; reconcile via body token now.\n if (_isReconciliationPending()) {\n await reconcileSession();\n }\n return;\n }\n\n await initSession();\n setIsLoading(false);\n }\n\n void initConfig();\n }, []);\n\n if (isLoading) {\n return loadingElement ?? <div>Loading...</div>;\n }\n\n return children;\n}\n","import io, { Socket } from 'socket.io-client';\nimport { WebsocketClientProvider } from '../types';\nimport { ClientChannel } from '../clientChannel';\nimport { getAuthToken, getClientInfo } from '@/auth/client';\nimport { getClientConfig } from '@/client/clientConfig';\nimport { reviveResponseTypes } from '@/methods/serialize';\n\nlet socketClient: Socket | null = null;\n\ninterface ActiveLiveSubscription {\n subscriptionId: string;\n method: string;\n args: Record<string, unknown>;\n}\nconst activeLiveSubscriptions = new Map<string, ActiveLiveSubscription>();\n\nfunction getSocket(): Socket {\n if (!socketClient) {\n throw new Error('WebSocket not initialized. Call startWebsockets() first.');\n }\n return socketClient;\n}\n\nfunction resubscribeAll() {\n const authToken = getAuthToken();\n const clientInfo = getClientInfo();\n for (const sub of activeLiveSubscriptions.values()) {\n socketClient?.emit('subscribeLiveQuery', {\n subscriptionId: sub.subscriptionId,\n method: sub.method,\n args: sub.args,\n authToken,\n clientInfo,\n });\n }\n}\n\nfunction init(props: { channels?: ClientChannel<unknown>[] }) {\n const baseUrl = getClientConfig()?.baseUrl ?? '/';\n socketClient = io(baseUrl, {\n transports: ['websocket'],\n auth: {\n token: getAuthToken(),\n },\n });\n\n // Subscribe to all live queries on connect/reconnect\n socketClient.on('connect', () => {\n if (activeLiveSubscriptions.size > 0) {\n console.log(\n `[Modelence] WebSocket reconnected, re-subscribing to ${activeLiveSubscriptions.size} live queries`\n );\n resubscribeAll();\n }\n });\n\n props.channels?.forEach((channel) => channel.init());\n}\n\nfunction on<T = unknown>({\n category,\n listener,\n}: {\n category: string;\n listener: (data: T) => void;\n}) {\n getSocket().on(category, listener);\n}\n\nfunction once<T = unknown>({\n category,\n listener,\n}: {\n category: string;\n listener: (data: T) => void;\n}) {\n getSocket().once(category, listener);\n}\n\nfunction off<T = unknown>({\n category,\n listener,\n}: {\n category: string;\n listener: (data: T) => void;\n}) {\n getSocket().off(category, listener);\n}\n\nfunction emit({ eventName, category, id }: { eventName: string; category: string; id: string }) {\n getSocket().emit(eventName, `${category}:${id}`);\n}\n\nfunction joinChannel({ category, id }: { category: string; id: string }) {\n emit({\n eventName: 'joinChannel',\n category,\n id,\n });\n}\n\nfunction leaveChannel({ category, id }: { category: string; id: string }) {\n emit({\n eventName: 'leaveChannel',\n category,\n id,\n });\n}\n\nlet liveQueryCounter = 0;\n\nexport function subscribeLiveQuery<T = unknown>(\n method: string,\n args: Record<string, unknown>,\n onData: (data: T) => void,\n onError?: (error: string) => void\n): () => void {\n const subscriptionId = `sub-${++liveQueryCounter}-${Date.now()}`;\n\n const handleData = ({\n subscriptionId: sid,\n data,\n typeMap,\n }: {\n subscriptionId: string;\n data: T;\n typeMap?: Record<string, unknown>;\n }) => {\n if (sid === subscriptionId) {\n onData(reviveResponseTypes(data, typeMap));\n }\n };\n\n const handleError = ({\n subscriptionId: sid,\n error,\n }: {\n subscriptionId: string;\n error: string;\n }) => {\n if (sid === subscriptionId) {\n console.error(`[Modelence] Live query error for ${method}:`, error);\n onError?.(error);\n }\n };\n\n const socket = getSocket();\n socket.on('liveQueryData', handleData);\n socket.on('liveQueryError', handleError);\n\n activeLiveSubscriptions.set(subscriptionId, { subscriptionId, method, args });\n\n // Only emit if already connected; otherwise the connect handler will handle it\n if (socket.connected) {\n socket.emit('subscribeLiveQuery', {\n subscriptionId,\n method,\n args,\n authToken: getAuthToken(),\n clientInfo: getClientInfo(),\n });\n }\n\n // Return unsubscribe function\n return () => {\n activeLiveSubscriptions.delete(subscriptionId);\n socket.emit('unsubscribeLiveQuery', { subscriptionId });\n socket.off('liveQueryData', handleData);\n socket.off('liveQueryError', handleError);\n };\n}\n\nconst websocketProvider: WebsocketClientProvider = {\n init,\n on,\n once,\n off,\n emit,\n joinChannel,\n leaveChannel,\n};\n\nexport default websocketProvider;\n","import { ClientChannel } from './clientChannel';\nimport websocketProvider, { subscribeLiveQuery } from './socketio/client';\nimport { WebsocketClientProvider } from './types';\n\nexport { subscribeLiveQuery };\n\nlet websocketClientProvider: WebsocketClientProvider | null = null;\n\nexport function setWebsocketClientProvider(provider: WebsocketClientProvider | null) {\n websocketClientProvider = provider;\n}\n\nexport function getWebsocketClientProvider() {\n return websocketClientProvider;\n}\n\nexport function startWebsockets(props?: {\n provider?: WebsocketClientProvider;\n channels?: ClientChannel[];\n}) {\n if (websocketClientProvider) {\n console.warn('WebSocket already initialized. Skipping initialization.');\n return;\n }\n\n const provider = props?.provider || websocketProvider;\n setWebsocketClientProvider(provider);\n try {\n provider.init({\n channels: props?.channels,\n });\n } catch (error) {\n setWebsocketClientProvider(null);\n throw error;\n }\n}\n","'use client';\n\nimport { QueryClient, hashKey } from '@tanstack/react-query';\nimport { callMethod } from './method';\nimport { startWebsockets, subscribeLiveQuery } from '../websocket/client';\n\ntype Args = Record<string, unknown>;\n\ninterface Subscription {\n unsubscribe: () => void;\n resolvers: Set<{\n resolve: (data: unknown) => void;\n reject: (error: Error) => void;\n }>;\n}\n\nlet queryClientRef: QueryClient | null = null;\nlet cacheUnsubscribe: (() => void) | null = null;\nlet websocketsStarted = false;\nconst subscriptions = new Map<string, Subscription>();\n\n/**\n * Connects a `QueryClient` to Modelence's live-query layer. Auto-called by\n * `<ModelenceQueryProvider>`; only call manually if you mount your own\n * `<QueryClientProvider>`.\n *\n * Note: WebSocket setup is deferred until the first `modelenceLiveQuery`\n * call, so apps that only use `modelenceQuery`/`modelenceMutation` never\n * open a socket.\n */\nexport function connectModelenceQueryClient(queryClient: QueryClient) {\n if (queryClientRef === queryClient) {\n return;\n }\n\n if (queryClientRef) {\n disconnectModelenceQueryClient();\n }\n\n queryClientRef = queryClient;\n\n cacheUnsubscribe = queryClient.getQueryCache().subscribe((event) => {\n if (event.type === 'removed') {\n const subscriptionKey = hashKey(event.query.queryKey);\n const sub = subscriptions.get(subscriptionKey);\n if (sub) {\n if (sub.resolvers.size > 0) {\n const cancelError = new Error('Query was removed from cache');\n sub.resolvers.forEach((r) => r.reject(cancelError));\n sub.resolvers.clear();\n }\n sub.unsubscribe();\n subscriptions.delete(subscriptionKey);\n }\n }\n });\n}\n\n/**\n * Whether a `QueryClient` is already connected to the live-query layer.\n * `renderApp` uses this to avoid injecting its own `<ModelenceQueryProvider>`\n * when the app already mounts its own provider and connects it beforehand.\n */\nexport function hasConnectedQueryClient(): boolean {\n return queryClientRef !== null;\n}\n\nexport function disconnectModelenceQueryClient() {\n if (cacheUnsubscribe) {\n cacheUnsubscribe();\n cacheUnsubscribe = null;\n }\n subscriptions.forEach((sub) => sub.unsubscribe());\n subscriptions.clear();\n queryClientRef = null;\n websocketsStarted = false;\n}\n\n/** @deprecated Use `connectModelenceQueryClient(queryClient)` instead. */\nexport class ModelenceQueryClient {\n connect(queryClient: QueryClient) {\n connectModelenceQueryClient(queryClient);\n }\n}\n\n/**\n * @example\n * ```tsx\n * const { data } = useQuery(modelenceQuery('todo.getAll'));\n * ```\n */\nexport function modelenceQuery<T = unknown>(methodName: string, args: Args = {}) {\n return {\n queryKey: [methodName, args],\n queryFn: () => callMethod<T>(methodName, args),\n };\n}\n\n/**\n * Live query — data updates in real time as the underlying collection changes.\n * Requires a `QueryClient` connected via `<ModelenceQueryProvider>` or\n * `connectModelenceQueryClient(...)`.\n */\nexport function modelenceLiveQuery<T = unknown>(methodName: string, args: Args = {}) {\n const queryKey = ['live', methodName, args] as const;\n const subscriptionKey = hashKey(queryKey);\n\n return {\n queryKey,\n queryFn: () =>\n new Promise<T>((resolve, reject) => {\n // Live queries are WebSocket subscriptions — no server snapshot. Stay\n // pending on the server so Suspense renders; client re-runs after hydration.\n if (typeof window === 'undefined') {\n return;\n }\n\n if (!queryClientRef) {\n const error = new Error(\n 'Modelence: connect a QueryClient before using modelenceLiveQuery(). Mount <ModelenceQueryProvider> or call connectModelenceQueryClient().'\n );\n console.error('[Modelence]', error.message);\n reject(error);\n return;\n }\n\n if (!websocketsStarted) {\n startWebsockets();\n websocketsStarted = true;\n }\n\n let sub = subscriptions.get(subscriptionKey);\n\n if (!sub) {\n const unsubscribe = subscribeLiveQuery<T>(\n methodName,\n args,\n (data) => {\n const currentSub = subscriptions.get(subscriptionKey);\n\n if (currentSub?.resolvers.size) {\n currentSub.resolvers.forEach((r) => r.resolve(data));\n currentSub.resolvers.clear();\n }\n\n if (queryClientRef) {\n queryClientRef.setQueryData(queryKey, data);\n }\n },\n (error) => {\n const currentSub = subscriptions.get(subscriptionKey);\n if (currentSub) {\n if (currentSub.resolvers.size) {\n currentSub.resolvers.forEach((r) => r.reject(new Error(error)));\n currentSub.resolvers.clear();\n }\n currentSub.unsubscribe();\n subscriptions.delete(subscriptionKey);\n }\n }\n );\n\n sub = { unsubscribe, resolvers: new Set() };\n subscriptions.set(subscriptionKey, sub);\n }\n\n // Shared map stores resolvers across `T` instantiations; erase the union.\n sub.resolvers.add({\n resolve: resolve as (data: unknown) => void,\n reject,\n });\n }),\n staleTime: Infinity,\n refetchOnWindowFocus: false,\n refetchOnMount: false,\n refetchOnReconnect: false,\n gcTime: 0,\n };\n}\n\nexport function modelenceMutation<T = unknown>(methodName: string, defaultArgs: Args = {}) {\n return {\n mutationFn: (variables: Args = {}) =>\n callMethod<T>(methodName, { ...defaultArgs, ...variables }),\n };\n}\n\nexport type ModelenceQueryKey<T extends string, U extends Args = Args> = readonly [T, U];\n\n/** Builds a query key matching `modelenceQuery(...)` for cache operations. */\nexport function createQueryKey<T extends string, U extends Args = Args>(\n methodName: T,\n args: U = {} as U\n): ModelenceQueryKey<T, U> {\n return [methodName, args] as const;\n}\n","'use client';\n\nimport React, { useState, type ReactNode } from 'react';\nimport {\n QueryClient,\n QueryClientProvider,\n HydrationBoundary,\n type DehydratedState,\n} from '@tanstack/react-query';\nimport { connectModelenceQueryClient } from './query';\n\nconst SSR_QUERY_STATE_SCRIPT_ID = '__MODELENCE_QUERY_STATE__';\n\nfunction readDehydratedState(): DehydratedState | undefined {\n if (typeof document === 'undefined') {\n return undefined;\n }\n\n const node = document.getElementById(SSR_QUERY_STATE_SCRIPT_ID);\n if (!node || !node.textContent) {\n return undefined;\n }\n\n try {\n return JSON.parse(node.textContent) as DehydratedState;\n } catch (e) {\n console.error('Modelence: failed to parse SSR query state', e);\n return undefined;\n }\n}\n\ninterface ModelenceQueryProviderProps {\n children: ReactNode;\n client?: QueryClient;\n dehydratedState?: DehydratedState;\n}\n\nexport function ModelenceQueryProvider({\n children,\n client,\n dehydratedState,\n}: ModelenceQueryProviderProps) {\n const [internalClient] = useState(() => {\n const qc =\n client ??\n new QueryClient({\n defaultOptions: {\n queries: {\n staleTime: 60 * 1000,\n },\n },\n });\n if (typeof window !== 'undefined') {\n connectModelenceQueryClient(qc);\n }\n return qc;\n });\n\n const state = dehydratedState ?? readDehydratedState();\n\n return (\n <QueryClientProvider client={internalClient}>\n <HydrationBoundary state={state}>{children}</HydrationBoundary>\n </QueryClientProvider>\n );\n}\n"]}
|
package/dist/client.d.ts
CHANGED
|
@@ -1,7 +1,8 @@
|
|
|
1
|
-
import { b as ClientInfo, c as ConfigKey, d as ConfigParams, A as AnyMethodShape, V as ValueType, e as ConfigType, O as OAuthProvider, W as WebsocketClientProvider, f as ClientChannel } from './types-
|
|
1
|
+
import { b as ClientInfo, c as ConfigKey, d as ConfigParams, A as AnyMethodShape, V as ValueType, e as ConfigType, O as OAuthProvider, W as WebsocketClientProvider, f as ClientChannel } from './types-B_R3eHmq.js';
|
|
2
2
|
import { ObjectId } from 'mongodb';
|
|
3
|
-
import React from 'react';
|
|
4
|
-
import
|
|
3
|
+
import React, { ReactNode } from 'react';
|
|
4
|
+
import * as react_jsx_runtime from 'react/jsx-runtime';
|
|
5
|
+
import { QueryClient, DehydratedState } from '@tanstack/react-query';
|
|
5
6
|
import 'http';
|
|
6
7
|
import 'express';
|
|
7
8
|
|
|
@@ -207,12 +208,72 @@ declare const systemConfig: {
|
|
|
207
208
|
|
|
208
209
|
type ErrorHandler = (error: Error, methodName: string) => void;
|
|
209
210
|
|
|
210
|
-
|
|
211
|
+
type SsrRouter = (props: {
|
|
212
|
+
children: React.ReactNode;
|
|
213
|
+
location?: string;
|
|
214
|
+
}) => React.ReactElement;
|
|
215
|
+
interface RenderAppOptions {
|
|
211
216
|
loadingElement: React.ReactNode;
|
|
212
217
|
routesElement: React.ReactNode;
|
|
213
218
|
favicon?: string;
|
|
214
219
|
errorHandler?: ErrorHandler;
|
|
215
|
-
|
|
220
|
+
router?: SsrRouter;
|
|
221
|
+
}
|
|
222
|
+
declare function renderApp(options: RenderAppOptions): void;
|
|
223
|
+
|
|
224
|
+
interface ModelenceQueryProviderProps {
|
|
225
|
+
children: ReactNode;
|
|
226
|
+
client?: QueryClient;
|
|
227
|
+
dehydratedState?: DehydratedState;
|
|
228
|
+
}
|
|
229
|
+
declare function ModelenceQueryProvider({ children, client, dehydratedState, }: ModelenceQueryProviderProps): react_jsx_runtime.JSX.Element;
|
|
230
|
+
|
|
231
|
+
type Args = Record<string, unknown>;
|
|
232
|
+
/**
|
|
233
|
+
* Connects a `QueryClient` to Modelence's live-query layer. Auto-called by
|
|
234
|
+
* `<ModelenceQueryProvider>`; only call manually if you mount your own
|
|
235
|
+
* `<QueryClientProvider>`.
|
|
236
|
+
*
|
|
237
|
+
* Note: WebSocket setup is deferred until the first `modelenceLiveQuery`
|
|
238
|
+
* call, so apps that only use `modelenceQuery`/`modelenceMutation` never
|
|
239
|
+
* open a socket.
|
|
240
|
+
*/
|
|
241
|
+
declare function connectModelenceQueryClient(queryClient: QueryClient): void;
|
|
242
|
+
declare function disconnectModelenceQueryClient(): void;
|
|
243
|
+
/** @deprecated Use `connectModelenceQueryClient(queryClient)` instead. */
|
|
244
|
+
declare class ModelenceQueryClient {
|
|
245
|
+
connect(queryClient: QueryClient): void;
|
|
246
|
+
}
|
|
247
|
+
/**
|
|
248
|
+
* @example
|
|
249
|
+
* ```tsx
|
|
250
|
+
* const { data } = useQuery(modelenceQuery('todo.getAll'));
|
|
251
|
+
* ```
|
|
252
|
+
*/
|
|
253
|
+
declare function modelenceQuery<T = unknown>(methodName: string, args?: Args): {
|
|
254
|
+
queryKey: (string | Args)[];
|
|
255
|
+
queryFn: () => Promise<T>;
|
|
256
|
+
};
|
|
257
|
+
/**
|
|
258
|
+
* Live query — data updates in real time as the underlying collection changes.
|
|
259
|
+
* Requires a `QueryClient` connected via `<ModelenceQueryProvider>` or
|
|
260
|
+
* `connectModelenceQueryClient(...)`.
|
|
261
|
+
*/
|
|
262
|
+
declare function modelenceLiveQuery<T = unknown>(methodName: string, args?: Args): {
|
|
263
|
+
queryKey: readonly ["live", string, Args];
|
|
264
|
+
queryFn: () => Promise<T>;
|
|
265
|
+
staleTime: number;
|
|
266
|
+
refetchOnWindowFocus: boolean;
|
|
267
|
+
refetchOnMount: boolean;
|
|
268
|
+
refetchOnReconnect: boolean;
|
|
269
|
+
gcTime: number;
|
|
270
|
+
};
|
|
271
|
+
declare function modelenceMutation<T = unknown>(methodName: string, defaultArgs?: Args): {
|
|
272
|
+
mutationFn: (variables?: Args) => Promise<T>;
|
|
273
|
+
};
|
|
274
|
+
type ModelenceQueryKey<T extends string, U extends Args = Args> = readonly [T, U];
|
|
275
|
+
/** Builds a query key matching `modelenceQuery(...)` for cache operations. */
|
|
276
|
+
declare function createQueryKey<T extends string, U extends Args = Args>(methodName: T, args?: U): ModelenceQueryKey<T, U>;
|
|
216
277
|
|
|
217
278
|
type User = {
|
|
218
279
|
id: string;
|
|
@@ -409,23 +470,6 @@ declare function startWebsockets(props?: {
|
|
|
409
470
|
|
|
410
471
|
declare function getLocalStorageSession(): any;
|
|
411
472
|
|
|
412
|
-
type UploadFileParams = {
|
|
413
|
-
filePath: string;
|
|
414
|
-
contentType: string;
|
|
415
|
-
visibility: FileVisibility;
|
|
416
|
-
};
|
|
417
|
-
type UploadFileResult = {
|
|
418
|
-
filePath: string;
|
|
419
|
-
};
|
|
420
|
-
declare function uploadFile(file: File | Blob, { filePath, contentType, visibility }: UploadFileParams): Promise<UploadFileResult>;
|
|
421
|
-
declare function deleteFile(filePath: string): Promise<void>;
|
|
422
|
-
declare function downloadFile(filePath: string): Promise<{
|
|
423
|
-
downloadUrl: string;
|
|
424
|
-
}>;
|
|
425
|
-
declare function getFileUrl(filePath: string): Promise<{
|
|
426
|
-
url: string;
|
|
427
|
-
}>;
|
|
428
|
-
|
|
429
473
|
declare const AppProvider: any;
|
|
430
474
|
|
|
431
|
-
export { AppProvider, type CallMethodOptions, ClientChannel, type ClientConfig, type MethodArgs, MethodError, type UserInfo, ValueType, callMethod, configureClient, createClientModule,
|
|
475
|
+
export { AppProvider, type CallMethodOptions, ClientChannel, type ClientConfig, type MethodArgs, MethodError, ModelenceQueryClient, type ModelenceQueryKey, ModelenceQueryProvider, type UserInfo, ValueType, callMethod, configureClient, connectModelenceQueryClient, createClientModule, createQueryKey, disconnectModelenceQueryClient, getConfig, getLocalStorageSession, getWebsocketClientProvider, linkOAuthProvider, loginWithPassword, logout, modelenceLiveQuery, modelenceMutation, modelenceQuery, renderApp, resendEmailVerification, resetPassword, sendResetPasswordToken, setWebsocketClientProvider, signupWithPassword, startWebsockets, subscribeLiveQuery, systemConfig, unlinkOAuthProvider, updateProfile, useSession, verifyEmail };
|
package/dist/client.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
|
|
1
|
+
export{f as AppProvider,e as ClientChannel,a as createClientModule,d as renderApp,b as systemConfig}from'./chunk-TBGXZXAA.js';export{i as ModelenceQueryClient,n as ModelenceQueryProvider,f as connectModelenceQueryClient,m as createQueryKey,h as disconnectModelenceQueryClient,d as getWebsocketClientProvider,k as modelenceLiveQuery,l as modelenceMutation,j as modelenceQuery,c as setWebsocketClientProvider,e as startWebsockets,b as subscribeLiveQuery}from'./chunk-YRR32LTF.js';export{q as MethodError,t as callMethod,b as configureClient,v as getConfig,a as getLocalStorageSession,l as linkOAuthProvider,e as loginWithPassword,i as logout,h as resendEmailVerification,k as resetPassword,j as sendResetPasswordToken,d as signupWithPassword,m as unlinkOAuthProvider,f as updateProfile,E as useSession,g as verifyEmail}from'./chunk-YLLX26A4.js';import'./chunk-5M6FUMUK.js';import'./chunk-DO5TZLF5.js';//# sourceMappingURL=client.js.map
|
|
2
2
|
//# sourceMappingURL=client.js.map
|
package/dist/client.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/client/localStorage.ts","../src/client/clientConfig.ts","../src/auth/client/index.ts","../src/client/errorHandler.ts","../src/client/method.ts","../src/config/client.ts","../src/client/session.ts","../src/client/AppProvider.tsx","../src/client/module.ts","../src/system/client.ts","../src/client/renderApp.tsx","../src/websocket/socketio/client.ts","../src/websocket/client.ts","../src/websocket/clientChannel.ts","../src/files/client.ts","../src/client.ts"],"names":["getLocalStorageSession","sessionJson","e","setLocalStorageSession","session","config","configureClient","userConfig","getClientConfig","signupWithPassword","options","email","password","handle","firstName","lastName","avatarUrl","callMethod","loginWithPassword","user","setCurrentUser","updateProfile","verifyEmail","token","resendEmailVerification","logout","sendResetPasswordToken","resetPassword","linkOAuthProvider","provider","baseUrl","getAuthToken","nonceResponse","nonce","url","unlinkOAuthProvider","getClientInfo","errorHandler","error","methodName","setErrorHandler","handler","handleError","MethodError","message","status","code","args","call","endpoint","response","text","result","reviveResponseTypes","getConfig","key","_setConfig","configs","useSessionStore","create","set","isInitialized","SESSION_HEARTBEAT_INTERVAL","time","userSchema","z","parseUser","parsedData","role","initSession","loopSessionHeartbeat","enrichedUser","useSession","state","AppProvider","children","loadingElement","isLoading","setIsLoading","useState","useEffect","initConfig","jsx","createClientModule","moduleName","name","rest","getArgs","pageParam","systemConfig","renderApp","routesElement","favicon","ReactDOM","React","link","newLink","socketClient","activeLiveSubscriptions","getSocket","resubscribeAll","authToken","clientInfo","sub","init","props","io","channel","on","category","listener","once","off","emit","eventName","id","joinChannel","leaveChannel","liveQueryCounter","subscribeLiveQuery","method","onData","onError","subscriptionId","handleData","sid","data","typeMap","socket","websocketProvider","client_default","websocketClientProvider","setWebsocketClientProvider","getWebsocketClientProvider","startWebsockets","ClientChannel","onMessage","uploadFile","file","filePath","contentType","visibility","fields","resolvedFilePath","formData","value","uploadResponse","deleteFile","downloadFile","getFileUrl"],"mappings":"sRAAO,SAASA,CAAAA,EAAyB,CACvC,IAAMC,CAAAA,CAAc,YAAA,CAAa,OAAA,CAAQ,mBAAmB,CAAA,CAC5D,GAAI,CACF,OAAOA,CAAAA,CAAc,IAAA,CAAK,KAAA,CAAMA,CAAW,CAAA,CAAI,IACjD,CAAA,MAASC,CAAAA,CAAG,CACV,OAAA,OAAA,CAAQ,KAAA,CAAM,yCAAA,CAA2CA,CAAC,CAAA,CACnD,IACT,CACF,CAEO,SAASC,CAAAA,CAAuBC,CAAAA,CAAiB,CACtD,YAAA,CAAa,OAAA,CAAQ,mBAAA,CAAqB,IAAA,CAAK,SAAA,CAAUA,CAAO,CAAC,EACnE,CCGA,IAAIC,CAAAA,CAA8B,IAAA,CAgC3B,SAASC,CAAAA,CAAgBC,CAAAA,CAA0B,CACxDF,CAAAA,CAASE,EACX,CAEO,SAASC,CAAAA,EAAuC,CACrD,OAAOH,CACT,CCXA,eAAsBI,CAAAA,CAAmBC,CAAAA,CAOtC,CACD,GAAM,CAAE,KAAA,CAAAC,CAAAA,CAAO,QAAA,CAAAC,CAAAA,CAAU,MAAA,CAAAC,CAAAA,CAAQ,SAAA,CAAAC,EAAW,QAAA,CAAAC,CAAAA,CAAU,SAAA,CAAAC,CAAU,CAAA,CAAIN,CAAAA,CACpE,MAAMO,CAAAA,CAAW,iCAAA,CAAmC,CAClD,KAAA,CAAAN,CAAAA,CACA,QAAA,CAAAC,CAAAA,CACA,GAAIC,CAAAA,GAAW,MAAA,CAAY,CAAE,MAAA,CAAAA,CAAO,CAAA,CAAI,EAAC,CACzC,GAAIC,CAAAA,GAAc,MAAA,CAAY,CAAE,SAAA,CAAAA,C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AE,CAAA,CAGhF,OAAO,CAAE,QAAA,CAAUH,CAAiB,CACtC,CAEA,eAAsBI,EAAAA,CAAWR,CAAAA,CAAiC,CAChE,MAAM1H,CAAAA,CAAW,0BAAA,CAA4B,CAAE,QAAA,CAAA0H,CAAS,CAAC,EAC3D,CAEA,eAAsBS,EAAAA,CAAaT,CAAAA,CAAoD,CACrF,OAAO1H,EAAW,4BAAA,CAA8B,CAAE,QAAA,CAAA0H,CAAS,CAAC,CAC9D,CAEA,eAAsBU,EAAAA,CAAWV,CAAAA,CAA4C,CAC3E,OAAO1H,CAAAA,CAAW,0BAAA,CAA4B,CAAE,QAAA,CAAA0H,CAAS,CAAC,CAC5D,CC7CO,IAAMjE,CAAAA,CACX,WAAA,GAAeoB,CAAAA,CAEXA,CAAAA,CAAM,SAAA,CAAUpB,CAAmB,CAAA,CACnCA","file":"client.js","sourcesContent":["export function getLocalStorageSession() {\n const sessionJson = localStorage.getItem('modelence.session');\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 localStorage.setItem('modelence.session', JSON.stringify(session));\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\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 { getLocalStorageSession } 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\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 const config = getClientConfig();\n if (config) {\n config.setAuthToken(session.authToken);\n }\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 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 * Reset password.\n * @param options.token - The password reset token.\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,\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 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/**\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 const baseUrl = getClientConfig()?.baseUrl ?? '';\n return await call<T>(`${baseUrl}/api/_internal/method/${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 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 { AppConfig, ConfigKey, Configs } from './types';\n\nlet config: Record<ConfigKey, AppConfig> = {};\n\n/**\n * @sidebarTitle getConfig (client)\n *\n * @param key\n * @returns\n */\nexport function getConfig(key: ConfigKey): string | number | boolean | undefined {\n return config[key]?.value;\n}\n\nexport function _setConfig(configs: Configs) {\n config = configs;\n}\n","import { create } from 'zustand';\nimport { z } from 'zod';\nimport { callMethod } from './method';\nimport { _setConfig } from '../config/client';\nimport { 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;\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 async function initSession() {\n if (isInitialized) {\n return;\n }\n\n isInitialized = true;\n\n const { configs, session, user } = await callMethod<{\n configs: Configs;\n session: object & { authToken: string };\n user: object;\n }>('_system.session.init');\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\nasync function loopSessionHeartbeat() {\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 getHeartbeatTimer() {\n return heartbeatTimer;\n}\n\nexport function stopHeartbeatTimer() {\n if (heartbeatTimer) {\n clearTimeout(heartbeatTimer);\n heartbeatTimer = null;\n }\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 const user = useSessionStore((state) => state.user);\n return { user };\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 React, { useState, useEffect, ReactNode } from 'react';\nimport { initSession } from './session';\n\ninterface AppProviderProps {\n children: ReactNode;\n loadingElement?: ReactNode;\n}\n\nlet isInitialized = false;\n\nexport function AppProvider({ children, loadingElement }: AppProviderProps) {\n const [isLoading, setIsLoading] = useState(true);\n\n useEffect(() => {\n async function initConfig() {\n if (isInitialized) {\n return;\n }\n\n isInitialized = true;\n\n await initSession();\n setIsLoading(false);\n }\n\n void initConfig();\n }, []);\n\n if (isLoading) {\n return loadingElement ?? <div>Loading...</div>;\n }\n\n return children;\n}\n","'use client';\n\nimport type { ObjectId } from 'mongodb';\nimport type { ConfigParams, ConfigType, ValueType } from '../config/types';\nimport { callMethod, type MethodArgs } from './method';\nimport type { AnyMethodShape } from '../methods/types';\n\n// Pulls the config store value without importing server-side code\nimport { getConfig as _getClientConfig } from '../config/client';\n\n// ── type helpers ─────────────────────────────────────────────────────────────\n\n/**\n * Recursively maps ObjectId → string to match the sanitized runtime values\n * sent over the wire. Dates are preserved (revived via typeMap on the client).\n */\ntype Sanitized<T> = T extends ObjectId\n ? string\n : T extends Date\n ? Date\n : T extends (infer U)[]\n ? Sanitized<U>[]\n : T extends object\n ? { [K in keyof T]: Sanitized<T[K]> }\n : T;\n\ntype ExtractArgs<M> = M extends (args: infer A, ...rest: any[]) => any // eslint-disable-line @typescript-eslint/no-explicit-any\n ? A\n : M extends { handler: (args: infer A, ...rest: any[]) => any } // eslint-disable-line @typescript-eslint/no-explicit-any\n ? A\n : MethodArgs;\n\ntype ExtractResult<M> = M extends (...args: any[]) => Promise<infer R> // eslint-disable-line @typescript-eslint/no-explicit-any\n ? Sanitized<R>\n : M extends { handler: (...args: any[]) => Promise<infer R> } // eslint-disable-line @typescript-eslint/no-explicit-any\n ? Sanitized<R>\n : unknown;\n\ntype PublicKeyOf<TSchema extends Record<string, ConfigParams>> = {\n [K in keyof TSchema as TSchema[K] extends ConfigParams<ConfigType, true>\n ? string & K\n : never]: ValueType<TSchema[K]['type']>;\n};\n\ntype AnyModule = {\n name: string;\n configSchema: Record<string, ConfigParams>;\n queries: Record<string, AnyMethodShape>;\n mutations: Record<string, AnyMethodShape>;\n};\n\n// ── createClientModule ────────────────────────────────────────────────────────\n\n/**\n * Creates a typed client accessor for a module's public configs, queries, and mutations.\n *\n * Use `import type` to reference the module so no server code is bundled on the client.\n * Arg and return types for queries and mutations are inferred automatically from the\n * server-side handler signatures.\n *\n * @param moduleName - The module's name as passed to `new Module(name, ...)`.\n *\n * @example\n * ```ts\n * // src/client/payments.ts\n * import type paymentsModule from '../server/payments';\n * import { createClientModule } from 'modelence/client';\n *\n * export const payments = createClientModule<typeof paymentsModule>('payments');\n * ```\n *\n * ```ts\n * // src/components/Checkout.tsx\n * import { useQuery, useMutation } from '@tanstack/react-query';\n * import { payments } from '../client/payments';\n *\n * // Typed config — public keys only, private and secret keys excluded:\n * const currency = payments.getConfig('currency'); // string | undefined\n *\n * // Typed query — pass directly to useQuery:\n * const { data: products } = useQuery(payments.query('getProducts', { page: 1 }));\n *\n * // Typed mutation — pass directly to useMutation:\n * const { mutate: charge } = useMutation(payments.mutation('charge'));\n * charge({ amount: 100 }); // args typed from handler signature\n * ```\n */\nexport function createClientModule<TModule extends AnyModule>(moduleName: string) {\n return {\n getConfig<K extends keyof PublicKeyOf<TModule['configSchema']> & string>(\n key: K\n ): PublicKeyOf<TModule['configSchema']>[K] | undefined {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return _getClientConfig(`${moduleName}.${key}`) as any;\n },\n\n query<K extends keyof TModule['queries'] & string>(\n name: K,\n ...rest: {} extends ExtractArgs<TModule['queries'][K]>\n ? [args?: ExtractArgs<TModule['queries'][K]>]\n : [args: ExtractArgs<TModule['queries'][K]>]\n ) {\n const args = (rest[0] ?? {}) as ExtractArgs<TModule['queries'][K]>;\n return {\n queryKey: [moduleName, name, args] as const,\n queryFn: (): Promise<ExtractResult<TModule['queries'][K]>> =>\n callMethod<ExtractResult<TModule['queries'][K]>>(\n `${moduleName}.${name}`,\n args as MethodArgs\n ),\n };\n },\n\n mutation<K extends keyof TModule['mutations'] & string>(name: K) {\n return {\n mutationFn: (\n args: ExtractArgs<TModule['mutations'][K]>\n ): Promise<ExtractResult<TModule['mutations'][K]>> =>\n callMethod<ExtractResult<TModule['mutations'][K]>>(\n `${moduleName}.${name}`,\n args as MethodArgs\n ),\n };\n },\n\n /**\n * Returns options for `useInfiniteQuery`. The `getArgs` callback receives the\n * current `pageParam` and returns the args to pass to the query handler.\n * Spread the result into `useInfiniteQuery` alongside `getNextPageParam`.\n *\n * Annotate the `pageParam` type in the callback so TypeScript can infer the\n * page param type — no manual generic needed on `useInfiniteQuery`.\n */\n infiniteQuery<K extends keyof TModule['queries'] & string, TPageParam = unknown>(\n name: K,\n getArgs: (pageParam: TPageParam | undefined) => ExtractArgs<TModule['queries'][K]>\n ) {\n return {\n queryKey: [moduleName, name, 'infinite', getArgs(undefined)] as const,\n // Included so TanStack infers TPageParam from the callback type, not from a bare `undefined`.\n initialPageParam: undefined as TPageParam | undefined,\n queryFn: ({\n pageParam,\n }: {\n pageParam: TPageParam | undefined;\n }): Promise<ExtractResult<TModule['queries'][K]>> =>\n callMethod<ExtractResult<TModule['queries'][K]>>(\n `${moduleName}.${name}`,\n getArgs(pageParam) as MethodArgs\n ),\n };\n },\n };\n}\n","import type systemModule from './index';\nimport { createClientModule } from '../client/module';\n\nexport const systemConfig = createClientModule<typeof systemModule>('_system');\n","import React from 'react';\nimport ReactDOM from 'react-dom/client';\nimport { AppProvider } from '../client';\nimport { setErrorHandler, ErrorHandler } from './errorHandler';\n\nexport function renderApp({\n loadingElement,\n routesElement,\n favicon,\n errorHandler,\n}: {\n loadingElement: React.ReactNode;\n routesElement: React.ReactNode;\n favicon?: string;\n errorHandler?: ErrorHandler;\n}) {\n if (errorHandler) {\n setErrorHandler(errorHandler);\n }\n\n window.addEventListener('unload', () => {\n // The presence of any 'unload' event handler, even empty,\n // prevents bfcache in most browsers\n });\n\n ReactDOM.createRoot(document.getElementById('root')!).render(\n <React.StrictMode>\n <AppProvider loadingElement={loadingElement}>{routesElement}</AppProvider>\n </React.StrictMode>\n );\n\n if (favicon) {\n const link = document.querySelector(\"link[rel~='icon']\") as HTMLLinkElement;\n if (!link) {\n const newLink = document.createElement('link');\n newLink.rel = 'icon';\n newLink.href = favicon;\n document.head.appendChild(newLink);\n } else {\n link.href = favicon;\n }\n }\n}\n","import io, { Socket } from 'socket.io-client';\nimport { WebsocketClientProvider } from '../types';\nimport { ClientChannel } from '../clientChannel';\nimport { getAuthToken, getClientInfo } from '@/auth/client';\nimport { getClientConfig } from '@/client/clientConfig';\nimport { reviveResponseTypes } from '@/methods/serialize';\n\nlet socketClient: Socket | null = null;\n\ninterface ActiveLiveSubscription {\n subscriptionId: string;\n method: string;\n args: Record<string, unknown>;\n}\nconst activeLiveSubscriptions = new Map<string, ActiveLiveSubscription>();\n\nfunction getSocket(): Socket {\n if (!socketClient) {\n throw new Error('WebSocket not initialized. Call startWebsockets() first.');\n }\n return socketClient;\n}\n\nfunction resubscribeAll() {\n const authToken = getAuthToken();\n const clientInfo = getClientInfo();\n for (const sub of activeLiveSubscriptions.values()) {\n socketClient?.emit('subscribeLiveQuery', {\n subscriptionId: sub.subscriptionId,\n method: sub.method,\n args: sub.args,\n authToken,\n clientInfo,\n });\n }\n}\n\nfunction init(props: { channels?: ClientChannel<unknown>[] }) {\n const baseUrl = getClientConfig()?.baseUrl ?? '/';\n socketClient = io(baseUrl, {\n transports: ['websocket'],\n auth: {\n token: getAuthToken(),\n },\n });\n\n // Subscribe to all live queries on connect/reconnect\n socketClient.on('connect', () => {\n if (activeLiveSubscriptions.size > 0) {\n console.log(\n `[Modelence] WebSocket reconnected, re-subscribing to ${activeLiveSubscriptions.size} live queries`\n );\n resubscribeAll();\n }\n });\n\n props.channels?.forEach((channel) => channel.init());\n}\n\nfunction on<T = unknown>({\n category,\n listener,\n}: {\n category: string;\n listener: (data: T) => void;\n}) {\n getSocket().on(category, listener);\n}\n\nfunction once<T = unknown>({\n category,\n listener,\n}: {\n category: string;\n listener: (data: T) => void;\n}) {\n getSocket().once(category, listener);\n}\n\nfunction off<T = unknown>({\n category,\n listener,\n}: {\n category: string;\n listener: (data: T) => void;\n}) {\n getSocket().off(category, listener);\n}\n\nfunction emit({ eventName, category, id }: { eventName: string; category: string; id: string }) {\n getSocket().emit(eventName, `${category}:${id}`);\n}\n\nfunction joinChannel({ category, id }: { category: string; id: string }) {\n emit({\n eventName: 'joinChannel',\n category,\n id,\n });\n}\n\nfunction leaveChannel({ category, id }: { category: string; id: string }) {\n emit({\n eventName: 'leaveChannel',\n category,\n id,\n });\n}\n\nlet liveQueryCounter = 0;\n\nexport function subscribeLiveQuery<T = unknown>(\n method: string,\n args: Record<string, unknown>,\n onData: (data: T) => void,\n onError?: (error: string) => void\n): () => void {\n const subscriptionId = `sub-${++liveQueryCounter}-${Date.now()}`;\n\n const handleData = ({\n subscriptionId: sid,\n data,\n typeMap,\n }: {\n subscriptionId: string;\n data: T;\n typeMap?: Record<string, unknown>;\n }) => {\n if (sid === subscriptionId) {\n onData(reviveResponseTypes(data, typeMap));\n }\n };\n\n const handleError = ({\n subscriptionId: sid,\n error,\n }: {\n subscriptionId: string;\n error: string;\n }) => {\n if (sid === subscriptionId) {\n console.error(`[Modelence] Live query error for ${method}:`, error);\n onError?.(error);\n }\n };\n\n const socket = getSocket();\n socket.on('liveQueryData', handleData);\n socket.on('liveQueryError', handleError);\n\n activeLiveSubscriptions.set(subscriptionId, { subscriptionId, method, args });\n\n // Only emit if already connected; otherwise the connect handler will handle it\n if (socket.connected) {\n socket.emit('subscribeLiveQuery', {\n subscriptionId,\n method,\n args,\n authToken: getAuthToken(),\n clientInfo: getClientInfo(),\n });\n }\n\n // Return unsubscribe function\n return () => {\n activeLiveSubscriptions.delete(subscriptionId);\n socket.emit('unsubscribeLiveQuery', { subscriptionId });\n socket.off('liveQueryData', handleData);\n socket.off('liveQueryError', handleError);\n };\n}\n\nconst websocketProvider: WebsocketClientProvider = {\n init,\n on,\n once,\n off,\n emit,\n joinChannel,\n leaveChannel,\n};\n\nexport default websocketProvider;\n","import { ClientChannel } from './clientChannel';\nimport websocketProvider, { subscribeLiveQuery } from './socketio/client';\nimport { WebsocketClientProvider } from './types';\n\nexport { subscribeLiveQuery };\n\nlet websocketClientProvider: WebsocketClientProvider | null = null;\n\nexport function setWebsocketClientProvider(provider: WebsocketClientProvider | null) {\n websocketClientProvider = provider;\n}\n\nexport function getWebsocketClientProvider() {\n return websocketClientProvider;\n}\n\nexport function startWebsockets(props?: {\n provider?: WebsocketClientProvider;\n channels?: ClientChannel[];\n}) {\n if (websocketClientProvider) {\n console.warn('WebSocket already initialized. Skipping initialization.');\n return;\n }\n\n const provider = props?.provider || websocketProvider;\n setWebsocketClientProvider(provider);\n try {\n provider.init({\n channels: props?.channels,\n });\n } catch (error) {\n setWebsocketClientProvider(null);\n throw error;\n }\n}\n","import { getWebsocketClientProvider } from './client';\n\nexport class ClientChannel<T = unknown> {\n public readonly category: string;\n private readonly onMessage: (data: T) => void;\n\n constructor(category: string, onMessage: (data: T) => void) {\n this.category = category;\n this.onMessage = onMessage;\n }\n\n init() {\n getWebsocketClientProvider()?.on({\n category: this.category,\n listener: this.onMessage,\n });\n }\n\n joinChannel(id: string) {\n getWebsocketClientProvider()?.joinChannel({\n category: this.category,\n id,\n });\n }\n\n leaveChannel(id: string) {\n getWebsocketClientProvider()?.leaveChannel({\n category: this.category,\n id,\n });\n }\n}\n","import { callMethod } from '../client/method';\nimport type { FileVisibility, GetUploadUrlResult } from './types';\n\ntype UploadFileParams = {\n filePath: string;\n contentType: string;\n visibility: FileVisibility;\n};\n\ntype UploadFileResult = {\n filePath: string;\n};\n\nexport async function uploadFile(\n file: File | Blob,\n { filePath, contentType, visibility }: UploadFileParams\n): Promise<UploadFileResult> {\n const {\n url,\n fields,\n filePath: resolvedFilePath,\n } = await callMethod<GetUploadUrlResult>('_system.files.getUploadUrl', {\n filePath,\n contentType,\n visibility,\n });\n\n const formData = new FormData();\n for (const [key, value] of Object.entries(fields)) {\n formData.append(key, value);\n }\n formData.append('file', file);\n\n const uploadResponse = await fetch(url, {\n method: 'POST',\n body: formData,\n });\n\n if (!uploadResponse.ok) {\n throw new Error(`Failed to upload file: HTTP status: ${uploadResponse.status}`);\n }\n\n return { filePath: resolvedFilePath };\n}\n\nexport async function deleteFile(filePath: string): Promise<void> {\n await callMethod('_system.files.deleteFile', { filePath });\n}\n\nexport async function downloadFile(filePath: string): Promise<{ downloadUrl: string }> {\n return callMethod('_system.files.downloadFile', { filePath });\n}\n\nexport async function getFileUrl(filePath: string): Promise<{ url: string }> {\n return callMethod('_system.files.getFileUrl', { filePath });\n}\n","import React from 'react';\n\nimport { AppProvider as OriginalAppProvider } from './client/AppProvider';\n\nexport { configureClient, type ClientConfig } from './client/clientConfig';\nexport { getConfig } from './config/client';\nexport { createClientModule } from './client/module';\nexport type { ValueType } from './config/types';\nexport { systemConfig } from './system/client';\n\nexport const AppProvider =\n 'useClient' in React\n ? // @ts-ignore: React.useClient only exists in Next.js\n React.useClient(OriginalAppProvider)\n : OriginalAppProvider;\n\nexport { renderApp } from './client/renderApp';\nexport { callMethod, MethodError, type MethodArgs, type CallMethodOptions } from './client/method';\nexport { useSession } from './client/session';\nexport {\n signupWithPassword,\n loginWithPassword,\n verifyEmail,\n updateProfile,\n resendEmailVerification,\n logout,\n sendResetPasswordToken,\n resetPassword,\n linkOAuthProvider,\n unlinkOAuthProvider,\n type UserInfo,\n} from './auth/client';\nexport {\n getWebsocketClientProvider,\n setWebsocketClientProvider,\n startWebsockets,\n subscribeLiveQuery,\n} from './websocket/client';\nexport { ClientChannel } from './websocket/clientChannel';\nexport { getLocalStorageSession } from './client/localStorage';\nexport { uploadFile, deleteFile, downloadFile, getFileUrl } from './files/client';\n"]}
|
|
1
|
+
{"version":3,"sources":[],"names":[],"mappings":"","file":"client.js"}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import a from'path';import u from'fs';var l=/\.(css|scss|sass|less|styl|stylus|pcss|postcss)(\?|$)/,p=Object.freeze({hrefs:[],source:"dev"});function y(s,e){let t=s.moduleGraph.getModuleById(d(s,e));if(!t)return p;let i=new Set,o=[],n=new Set,c=r=>{if(!i.has(r)){i.add(r),r.url&&l.test(r.url)&&!n.has(r.url)&&(n.add(r.url),o.push(r.url));for(let f of r.importedModules)c(f);for(let f of r.ssrImportedModules)c(f);}};return c(t),{hrefs:o,source:"dev"}}function d(s,e){let t=s.config.root;return a.join(t,e).replace(/\\/g,"/")}function A(s){let e=a.resolve(process.cwd(),s,".vite","ssr-manifest.json");if(!u.existsSync(e))return {hrefs:[],source:"prod"};let t;try{t=JSON.parse(u.readFileSync(e,"utf-8"));}catch(o){return console.warn("Modelence SSR: failed to parse ssr-manifest.json",o),{hrefs:[],source:"prod"}}let i=new Set;for(let o of Object.values(t))if(Array.isArray(o))for(let n of o)typeof n=="string"&&l.test(n)&&i.add(n);return {hrefs:Array.from(i),source:"prod"}}function v(s){return s.hrefs.length===0?"":s.hrefs.map(e=>`<link rel="stylesheet" href="${S(e)}">`).join("")}function C(s){return s.hrefs.map(e=>`<${e}>; rel=preload; as=style`)}function S(s){return s.replace(/&/g,"&").replace(/"/g,""")}export{C as buildEarlyHintsLink,y as collectDevCssAssets,A as loadProdCssAssets,v as renderStylesheetLinks};//# sourceMappingURL=collectCss-4YETFI7P.js.map
|
|
2
|
+
//# sourceMappingURL=collectCss-4YETFI7P.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/ssr/collectCss.ts"],"names":["CSS_EXTENSION_REGEX","EMPTY_ASSETS","collectDevCssAssets","viteServer","entryVirtualPath","ssrModule","resolveEntryId","seen","hrefs","hrefSet","walk","mod","imported","root","path","loadProdCssAssets","clientBuildDir","manifestPath","fs","manifest","error","assets","asset","renderStylesheetLinks","href","escapeAttribute","buildEarlyHintsLink","value"],"mappings":"sCAIA,IAAMA,C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AAgCC,CAAAA,CAAgBD,CAAI,CAAC,CAAA,EAAA,CAAI,CAAA,CACvE,IAAA,CAAK,EAAE,CACZ,CAGO,SAASE,CAAAA,CAAoBL,CAAAA,CAA6B,CAC/D,OAAOA,CAAAA,CAAO,KAAA,CAAM,GAAA,CAAKG,GAAS,CAAA,CAAA,EAAIA,CAAI,CAAA,wBAAA,CAA0B,CACtE,CAEA,SAASC,CAAAA,CAAgBE,CAAAA,CAAuB,CAC9C,OAAOA,CAAAA,CAAM,OAAA,CAAQ,IAAA,CAAM,OAAO,CAAA,CAAE,OAAA,CAAQ,IAAA,CAAM,QAAQ,CAC5D","file":"collectCss-4YETFI7P.js","sourcesContent":["import path from 'path';\nimport fs from 'fs';\nimport type { ViteDevServer, ModuleNode } from 'vite';\n\nconst CSS_EXTENSION_REGEX = /\\.(css|scss|sass|less|styl|stylus|pcss|postcss)(\\?|$)/;\n\nexport type CssAssetSource = 'dev' | 'prod';\n\nexport interface CssAssets {\n /** URLs for `<link rel=\"stylesheet\">`. Dev: Vite transform; prod: built asset. */\n hrefs: string[];\n source: CssAssetSource;\n}\n\nconst EMPTY_ASSETS: CssAssets = Object.freeze({ hrefs: [], source: 'dev' }) as CssAssets;\n\n// Walks the dev module graph from the SSR entry to gather CSS hrefs the\n// browser can fetch directly, killing FOUC in dev.\nexport function collectDevCssAssets(\n viteServer: ViteDevServer,\n entryVirtualPath: string\n): CssAssets {\n const ssrModule = viteServer.moduleGraph.getModuleById(\n resolveEntryId(viteServer, entryVirtualPath)\n );\n if (!ssrModule) {\n return EMPTY_ASSETS;\n }\n\n const seen = new Set<ModuleNode>();\n const hrefs: string[] = [];\n const hrefSet = new Set<string>();\n\n const walk = (mod: ModuleNode) => {\n if (seen.has(mod)) {\n return;\n }\n seen.add(mod);\n\n if (mod.url && CSS_EXTENSION_REGEX.test(mod.url) && !hrefSet.has(mod.url)) {\n hrefSet.add(mod.url);\n hrefs.push(mod.url);\n }\n\n for (const imported of mod.importedModules) {\n walk(imported);\n }\n for (const imported of mod.ssrImportedModules) {\n walk(imported);\n }\n };\n\n walk(ssrModule);\n\n return { hrefs, source: 'dev' };\n}\n\nfunction resolveEntryId(viteServer: ViteDevServer, entryVirtualPath: string): string {\n const root = viteServer.config.root;\n return path.join(root, entryVirtualPath).replace(/\\\\/g, '/');\n}\n\ntype SsrManifest = Record<string, string[]>;\n\n// Flatten all CSS hrefs from the SSR manifest. Per-request filtering would\n// be ideal but we don't have the rendered module list at boot, so emit all.\nexport function loadProdCssAssets(clientBuildDir: string): CssAssets {\n const manifestPath = path.resolve(process.cwd(), clientBuildDir, '.vite', 'ssr-manifest.json');\n\n if (!fs.existsSync(manifestPath)) {\n return { hrefs: [], source: 'prod' };\n }\n\n let manifest: SsrManifest;\n try {\n manifest = JSON.parse(fs.readFileSync(manifestPath, 'utf-8')) as SsrManifest;\n } catch (error) {\n console.warn('Modelence SSR: failed to parse ssr-manifest.json', error);\n return { hrefs: [], source: 'prod' };\n }\n\n const hrefSet = new Set<string>();\n for (const assets of Object.values(manifest)) {\n if (!Array.isArray(assets)) {\n continue;\n }\n for (const asset of assets) {\n if (typeof asset === 'string' && CSS_EXTENSION_REGEX.test(asset)) {\n hrefSet.add(asset);\n }\n }\n }\n\n return { hrefs: Array.from(hrefSet), source: 'prod' };\n}\n\nexport function renderStylesheetLinks(assets: CssAssets): string {\n if (assets.hrefs.length === 0) {\n return '';\n }\n return assets.hrefs\n .map((href) => `<link rel=\"stylesheet\" href=\"${escapeAttribute(href)}\">`)\n .join('');\n}\n\n// Link header values for 103 Early Hints (preload CSS before render starts).\nexport function buildEarlyHintsLink(assets: CssAssets): string[] {\n return assets.hrefs.map((href) => `<${href}>; rel=preload; as=style`);\n}\n\nfunction escapeAttribute(value: string): string {\n return value.replace(/&/g, '&').replace(/\"/g, '"');\n}\n"]}
|
|
@@ -12,7 +12,7 @@ interface AppServerInitOptions {
|
|
|
12
12
|
}
|
|
13
13
|
interface AppServer {
|
|
14
14
|
init: (options: AppServerInitOptions) => Promise<void>;
|
|
15
|
-
handler: (req: Request, res: Response) => void
|
|
15
|
+
handler: (req: Request, res: Response) => void | Promise<void>;
|
|
16
16
|
middlewares?: () => ExpressMiddleware[];
|
|
17
17
|
}
|
|
18
18
|
|
package/dist/index.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
export { C as ConfigSchema, W as WebsocketClientProvider, a as WebsocketServerProvider } from './types-
|
|
2
|
-
export { M as ModelenceConfig } from './index-
|
|
1
|
+
export { C as ConfigSchema, W as WebsocketClientProvider, a as WebsocketServerProvider } from './types-B_R3eHmq.js';
|
|
2
|
+
export { M as ModelenceConfig } from './index-CgNFVSg6.js';
|
|
3
3
|
import 'http';
|
|
4
4
|
import 'mongodb';
|
|
5
5
|
import 'express';
|
package/dist/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
export{b as AuthError,a as ModelenceError,d as RateLimitError,c as ValidationError}from'./chunk-MIRF7FP3.js';export{a as time}from'./chunk-DO5TZLF5.js'
|
|
1
|
+
export{b as AuthError,a as ModelenceError,d as RateLimitError,c as ValidationError}from'./chunk-MIRF7FP3.js';import'./chunk-55J6XMHW.js';export{a as time}from'./chunk-DO5TZLF5.js';//# sourceMappingURL=index.js.map
|
|
2
2
|
//# sourceMappingURL=index.js.map
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
export{l as author,i as bin,n as bugs,s as default,q as dependencies,d as description,p as devDependencies,g as exports,h as files,o as homepage,m as license,e as main,b as name,r as peerDependencies,k as repository,j as scripts,a as type,f as types,c as version}from'./chunk-
|
|
2
|
-
//# sourceMappingURL=package-
|
|
1
|
+
export{l as author,i as bin,n as bugs,s as default,q as dependencies,d as description,p as devDependencies,g as exports,h as files,o as homepage,m as license,e as main,b as name,r as peerDependencies,k as repository,j as scripts,a as type,f as types,c as version}from'./chunk-5LP23CUB.js';//# sourceMappingURL=package-OLG24DKG.js.map
|
|
2
|
+
//# sourceMappingURL=package-OLG24DKG.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":[],"names":[],"mappings":"","file":"package-
|
|
1
|
+
{"version":3,"sources":[],"names":[],"mappings":"","file":"package-OLG24DKG.js"}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import {a,b,c}from'./chunk-JDYWT45S.js';import'./chunk-GPKIS2JI.js';import'./chunk-7LPSX5A6.js';import {a as a$1,n}from'./chunk-YRR32LTF.js';import {C,u,D as D$1}from'./chunk-YLLX26A4.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?D$1(r.session.user):null},M=r=>{let o=c();if(o)return o.session.configs[r]?.value};function D(){C(J),u(M);}async function X(r){let{callContext:o,loadingElement:C,routesElement:S,router:u,location:x,onShellReady:E,onError:b$1}=r;D();let i=await a("_system.session.init",{},o),n$1=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:n$1,children:O})}),l=null;await new Promise((s,d)=>{b({callContext:o,queryClient:n$1,session:{user:i.user,configs:i.configs??{}}},()=>{let e=renderToPipeableStream(Q,{onShellReady(){l=e,E?.(),s(e);},onShellError(t){d(t);},onError(t){b$1?.(t);}});return e});});let a$2=null,_=s=>new Promise((d,e)=>{if(!l){e(new Error("SSR stream was not initialized"));return}let t=new Writable({write(m,c,I){s.write(m,N=>I(N??void 0));},final(m){try{let c=dehydrate(n$1);a$2=JSON.stringify(c);}finally{n$1.clear();}m(),d();}});t.on("error",e),s.on("error",e),l.pipe(t);});return {sessionState:JSON.stringify({session:i}),pipe:_,getQueryState:()=>{if(a$2===null)throw new Error("getQueryState() called before stream finished");return a$2}}}export{X as renderSsrTreeStream};//# sourceMappingURL=render-A7HWHWAE.js.map
|
|
2
|
+
//# sourceMappingURL=render-A7HWHWAE.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/ssr/render.tsx"],"names":["sessionResolver","ctx","getSsrContext","_parseSessionUser","configResolver","key","ensureSsrResolversInstalled","_setSsrSessionResolver","_setSsrConfigResolver","renderSsrTreeStream","options","callContext","loadingElement","routesElement","router","location","onShellReady","onError","sessionPayload","callInProcessMethod","queryClient","QueryClient","routedTree","tree","jsx","AppProvider","ModelenceQueryProvider","streamRef","resolve","reject","runWithSsrContext","stream","renderToPipeableStream","error","queryStateJson","pipe","destination","passthrough","Writable","chunk","_encoding","callback","err","dehydratedState","dehydrate"],"mappings":"saAkBA,IAAMA,CAAAA,CAAkB,IAAM,CAC5B,IAAMC,CAAAA,CAAMC,CAAAA,EAAc,CAC1B,OAAKD,CAAAA,CAGEE,GAAAA,CAAkBF,CAAAA,CAAI,OAAA,CAAQ,IAAI,CAAA,CAFhC,IAGX,CAAA,CAEMG,CAAAA,CAAkBC,GAAmB,CACzC,IAAMJ,CAAAA,CAAMC,CAAAA,GACZ,GAAKD,CAAAA,CAGL,OAAOA,CAAAA,CAAI,QAAQ,OAAA,CAAQI,CAAG,CAAA,EAAG,KACnC,EAEA,SAASC,CAAAA,EAA8B,CACrCC,CAAAA,CAAuBP,CAAe,CAAA,CACtCQ,CAAAA,CAAsBJ,CAAc,EACtC,CA0BA,eAAsBK,CAAAA,CAAoBC,CAAAA,CAAqD,CAC7F,GAAM,CAAE,WAAA,CAAAC,CAAAA,CAAa,cAAA,CAAAC,EAAgB,aAAA,CAAAC,CAAAA,CAAe,MAAA,CAAAC,CAAAA,CAAQ,SAAAC,CAAAA,CAAU,YAAA,CAAAC,CAAAA,CAAc,OAAA,CAAAC,GAAQ,CAAA,CAC1FP,CAAAA,CAEFJ,CAAAA,EAA4B,CAE5B,IAAMY,CAAAA,CAAiB,MAAMC,CAAAA,CAC3B,sBAAA,CACA,EAAC,CACDR,CACF,CAAA,CAEMS,GAAAA,CAAc,IAA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D,MACF,CAKA,IAAMQ,CAAAA,CAAc,IAAIC,QAAAA,CAAS,CAC/B,KAAA,CAAMC,CAAAA,CAAOC,CAAAA,CAAWC,CAAAA,CAAU,CAChCL,CAAAA,CAAY,KAAA,CAAMG,CAAAA,CAAQG,CAAAA,EAAQD,EAASC,CAAAA,EAAO,MAAS,CAAC,EAC9D,EACA,KAAA,CAAMD,CAAAA,CAAU,CACd,GAAI,CACF,IAAME,CAAAA,CAAmCC,SAAAA,CAAUxB,GAAW,EAC9Dc,GAAAA,CAAiB,IAAA,CAAK,SAAA,CAAUS,CAAe,EACjD,CAAA,OAAE,CACAvB,GAAAA,CAAY,KAAA,GACd,CACAqB,CAAAA,EAAS,CACTb,CAAAA,GACF,CACF,CAAC,CAAA,CAEDS,CAAAA,CAAY,GAAG,OAAA,CAASR,CAAM,CAAA,CAC9BO,CAAAA,CAAY,GAAG,OAAA,CAASP,CAAM,CAAA,CAE9BF,CAAAA,CAAU,KAAKU,CAAW,EAC5B,CAAC,CAAA,CAGH,OAAO,CACL,YAAA,CAAc,IAAA,CAAK,SAAA,CAAU,CAAE,OAAA,CAASnB,CAAe,CAAC,CAAA,CACxD,KAAAiB,CAAAA,CACA,aAAA,CAAe,IAAM,CACnB,GAAID,GAAAA,GAAmB,IAAA,CACrB,MAAM,IAAI,MAAM,+CAA+C,CAAA,CAEjE,OAAOA,GACT,CACF,CACF","file":"render-A7HWHWAE.js","sourcesContent":["import React from 'react';\nimport { renderToPipeableStream, type PipeableStream } from 'react-dom/server';\nimport { Writable } from 'node:stream';\nimport { QueryClient, dehydrate, type DehydratedState } from '@tanstack/react-query';\nimport { AppProvider } from '../client/AppProvider';\nimport { ModelenceQueryProvider } from '../client/queryProvider';\nimport { getSsrContext, runWithSsrContext } from './context';\nimport { callInProcessMethod } from './callInProcess';\nimport type { Context } from '../methods/types';\nimport {\n _parseSessionUser,\n _setSsrSessionResolver,\n type SessionInitPayload,\n} from '../client/session';\nimport { _setSsrConfigResolver } from '../config/client';\nimport type { ConfigKey, Configs } from '../config/types';\nimport type { SsrRouter } from '../client/renderApp';\n\nconst sessionResolver = () => {\n const ctx = getSsrContext();\n if (!ctx) {\n return null;\n }\n return _parseSessionUser(ctx.session.user);\n};\n\nconst configResolver = (key: ConfigKey) => {\n const ctx = getSsrContext();\n if (!ctx) {\n return undefined;\n }\n return ctx.session.configs[key]?.value;\n};\n\nfunction ensureSsrResolversInstalled() {\n _setSsrSessionResolver(sessionResolver);\n _setSsrConfigResolver(configResolver);\n}\n\nexport type SsrRenderOptions = {\n callContext: Context;\n loadingElement: React.ReactNode;\n routesElement: React.ReactNode;\n router?: SsrRouter;\n location?: string;\n};\n\nexport type SsrStreamHandle = {\n /** Session bootstrap payload — inline before the shell flushes. */\n sessionState: string;\n /** Pipe React's HTML into `destination`. Resolves when streaming finishes. */\n pipe: (destination: Writable) => Promise<void>;\n /** Dehydrated query state. Only call after `pipe()` resolves. */\n getQueryState: () => string;\n};\n\nexport type SsrStreamOptions = SsrRenderOptions & {\n /** Fires when the shell is flushed; caller writes prelude + state here. */\n onShellReady?: () => void;\n /** Non-fatal SSR errors (Suspense fallbacks, etc.). */\n onError?: (error: unknown) => void;\n};\n\nexport async function renderSsrTreeStream(options: SsrStreamOptions): Promise<SsrStreamHandle> {\n const { callContext, loadingElement, routesElement, router, location, onShellReady, onError } =\n options;\n\n ensureSsrResolversInstalled();\n\n const sessionPayload = await callInProcessMethod<SessionInitPayload>(\n '_system.session.init',\n {},\n callContext\n );\n\n const queryClient = new QueryClient({\n defaultOptions: {\n queries: {\n retry: false,\n gcTime: 0,\n },\n },\n });\n\n const routedTree = router ? router({ children: routesElement, location }) : routesElement;\n const tree = (\n <AppProvider loadingElement={loadingElement}>\n <ModelenceQueryProvider client={queryClient}>{routedTree}</ModelenceQueryProvider>\n </AppProvider>\n );\n\n let streamRef: PipeableStream | null = null;\n // Resolves with the stream once React renders above-fallback content;\n // rejects on shell errors so the caller can fall back to a static response.\n const shellReady = new Promise<PipeableStream>((resolve, reject) => {\n // Run the render inside the SSR context so components can resolve\n // session/config/query state from the per-request scope.\n runWithSsrContext(\n {\n callContext,\n queryClient,\n session: {\n user: sessionPayload.user,\n configs: (sessionPayload.configs as Configs) ?? {},\n },\n },\n () => {\n const stream = renderToPipeableStream(tree, {\n onShellReady() {\n streamRef = stream;\n onShellReady?.();\n resolve(stream);\n },\n onShellError(error) {\n reject(error);\n },\n onError(error) {\n onError?.(error);\n },\n });\n return stream;\n }\n );\n });\n\n // Await so shell errors surface before the caller starts piping.\n await shellReady;\n\n let queryStateJson: string | null = null;\n\n const pipe = (destination: Writable): Promise<void> => {\n return new Promise((resolve, reject) => {\n if (!streamRef) {\n reject(new Error('SSR stream was not initialized'));\n return;\n }\n\n // react-dom calls `destination.end()` when done. The caller still needs\n // to write the epilogue + query state, so wrap with a passthrough whose\n // `final()` resolves the pipe promise without closing the response.\n const passthrough = new Writable({\n write(chunk, _encoding, callback) {\n destination.write(chunk, (err) => callback(err ?? undefined));\n },\n final(callback) {\n try {\n const dehydratedState: DehydratedState = dehydrate(queryClient);\n queryStateJson = JSON.stringify(dehydratedState);\n } finally {\n queryClient.clear();\n }\n callback();\n resolve();\n },\n });\n\n passthrough.on('error', reject);\n destination.on('error', reject);\n\n streamRef.pipe(passthrough);\n });\n };\n\n return {\n sessionState: JSON.stringify({ session: sessionPayload }),\n pipe,\n getQueryState: () => {\n if (queryStateJson === null) {\n throw new Error('getQueryState() called before stream finished');\n }\n return queryStateJson;\n },\n };\n}\n"]}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":[],"names":[],"mappings":"","file":"renderApp-QYMNQ3KS.js"}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
export{g as getCallContext,f as startServer}from'./chunk-A2J5PPAQ.js';import'./chunk-5LP23CUB.js';import'./chunk-GPKIS2JI.js';import'./chunk-MIRF7FP3.js';import'./chunk-7LPSX5A6.js';import'./chunk-5M6FUMUK.js';import'./chunk-DO5TZLF5.js';//# sourceMappingURL=server-OYDAIDR6.js.map
|
|
2
|
+
//# sourceMappingURL=server-OYDAIDR6.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":[],"names":[],"mappings":"","file":"server-OYDAIDR6.js"}
|
package/dist/server.d.ts
CHANGED
|
@@ -1,13 +1,12 @@
|
|
|
1
|
-
import { A as AppServer } from './index-
|
|
2
|
-
import { d as ConfigParams, C as ConfigSchema, A as AnyMethodShape, S as ServerChannel, V as ValueType, g as SignupProps, U as UpdateProfileProps, h as AuthSuccessProps, i as AuthErrorProps, j as ConnectionInfo, k as User, l as OAuthErrorInfo, a as WebsocketServerProvider, R as RoleDefinition, M as MethodDefinition,
|
|
3
|
-
export { e as ConfigType } from './types-
|
|
4
|
-
import { S as Store, R as RouteDefinition, C as CronJobInputParams, a as RateLimitRule, E as EmailProvider, b as RateLimitType, I as InferDocumentType, c as EmailPayload } from './types-
|
|
5
|
-
export { H as HttpMethod, d as RouteHandler, e as RouteParams, f as RouteResponse, s as schema } from './types-
|
|
1
|
+
import { A as AppServer } from './index-CgNFVSg6.js';
|
|
2
|
+
import { d as ConfigParams, C as ConfigSchema, A as AnyMethodShape, S as ServerChannel, V as ValueType, g as SignupProps, U as UpdateProfileProps, h as AuthSuccessProps, i as AuthErrorProps, j as ConnectionInfo, k as User, l as OAuthErrorInfo, a as WebsocketServerProvider, R as RoleDefinition, M as MethodDefinition, m as Session, c as ConfigKey, n as AppConfig, o as UserInfo, p as Role } from './types-B_R3eHmq.js';
|
|
3
|
+
export { e as ConfigType } from './types-B_R3eHmq.js';
|
|
4
|
+
import { S as Store, R as RouteDefinition, C as CronJobInputParams, a as RateLimitRule, E as EmailProvider, b as RateLimitType, I as InferDocumentType, c as EmailPayload } from './types-_BTBqn8b.js';
|
|
5
|
+
export { H as HttpMethod, d as RouteHandler, e as RouteParams, f as RouteResponse, s as schema } from './types-_BTBqn8b.js';
|
|
6
6
|
import { ObjectId as ObjectId$1 } from 'mongodb';
|
|
7
7
|
export { ObjectId } from 'mongodb';
|
|
8
8
|
import * as zod from 'zod';
|
|
9
|
-
import {
|
|
10
|
-
import 'express';
|
|
9
|
+
import { Response } from 'express';
|
|
11
10
|
import 'http';
|
|
12
11
|
|
|
13
12
|
/** Array of Store instances that will be provisioned when the module is loaded */
|
|
@@ -467,8 +466,10 @@ type AppOptions = {
|
|
|
467
466
|
defaultRoles?: Record<string, string>;
|
|
468
467
|
migrations?: Array<MigrationScript>;
|
|
469
468
|
websocket?: WebsocketConfig;
|
|
469
|
+
/** Enable server-side rendering of the user's React tree. */
|
|
470
|
+
ssr?: boolean;
|
|
470
471
|
};
|
|
471
|
-
declare function startApp({ modules, roles, defaultRoles, server, migrations, email, auth, security, websocket, }: AppOptions): Promise<void>;
|
|
472
|
+
declare function startApp({ modules, roles, defaultRoles, server, migrations, email, auth, security, websocket, ssr, }: AppOptions): Promise<void>;
|
|
472
473
|
|
|
473
474
|
/**
|
|
474
475
|
* Publish function provided to watch handlers.
|
|
@@ -820,6 +821,26 @@ declare const usersCollection: Store<{
|
|
|
820
821
|
declare function disableUser(userId: ObjectId$1): Promise<void>;
|
|
821
822
|
declare function deleteUser(userId: ObjectId$1): Promise<void>;
|
|
822
823
|
|
|
824
|
+
declare const sessionsCollection: Store<{
|
|
825
|
+
authToken: zod.ZodString;
|
|
826
|
+
createdAt: zod.ZodDate;
|
|
827
|
+
expiresAt: zod.ZodDate;
|
|
828
|
+
userId: zod.ZodNullable<zod.ZodType<ObjectId$1, zod.ZodTypeDef, ObjectId$1>>;
|
|
829
|
+
}, Record<string, (this: Pick<InferDocumentType<{
|
|
830
|
+
authToken: zod.ZodString;
|
|
831
|
+
createdAt: zod.ZodDate;
|
|
832
|
+
expiresAt: zod.ZodDate;
|
|
833
|
+
userId: zod.ZodNullable<zod.ZodType<ObjectId$1, zod.ZodTypeDef, ObjectId$1>>;
|
|
834
|
+
}>, "createdAt" | "userId" | "expiresAt" | "authToken"> & {
|
|
835
|
+
_id: ObjectId$1;
|
|
836
|
+
}, ...args: any[]) => any>>;
|
|
837
|
+
declare function obtainSession(authToken: string | null): Promise<Session>;
|
|
838
|
+
declare function setSessionUser(authToken: string, userId: ObjectId$1): Promise<void>;
|
|
839
|
+
declare function clearSessionUser(authToken: string): Promise<void>;
|
|
840
|
+
declare function invalidateAllUserSessions(userId: ObjectId$1): Promise<void>;
|
|
841
|
+
declare function createSession(userId?: ObjectId$1 | null): Promise<Session>;
|
|
842
|
+
declare function setAuthTokenCookie(res: Response, authToken: string): void;
|
|
843
|
+
|
|
823
844
|
/**
|
|
824
845
|
* This function will check all rate limit rules on the specified bucket and type,
|
|
825
846
|
* throw an error if any of them are exceeded and increase the count of the rate limit record.
|
|
@@ -905,6 +926,13 @@ declare function authenticate(authToken: string | null): Promise<{
|
|
|
905
926
|
|
|
906
927
|
declare function sendEmail(payload: EmailPayload): Promise<void> | undefined;
|
|
907
928
|
|
|
929
|
+
type FileVisibility = 'public' | 'private';
|
|
930
|
+
type GetUploadUrlResult = {
|
|
931
|
+
url: string;
|
|
932
|
+
fields: Record<string, string>;
|
|
933
|
+
filePath: string;
|
|
934
|
+
};
|
|
935
|
+
|
|
908
936
|
type DownloadFileResult = {
|
|
909
937
|
downloadUrl: string;
|
|
910
938
|
};
|
|
@@ -920,4 +948,4 @@ declare function deleteFile(filePath: string): Promise<void>;
|
|
|
920
948
|
declare function downloadFile(filePath: string): Promise<DownloadFileResult>;
|
|
921
949
|
declare function getFileUrl(filePath: string): Promise<GetFileUrlResult>;
|
|
922
950
|
|
|
923
|
-
export { type AppOptions, type AuthConfig, type AuthOption, type AuthRateLimitOverride, type AuthRateLimitsConfig, type CloudBackendConnectResponse, ConfigSchema, CronJobInputParams, FileVisibility, LiveData, type LiveDataConfig, type LiveQueryCleanup, type LiveQueryPublish, type LiveQueryWatch, Module, RateLimitRule, RateLimitType, RoleDefinition, RouteDefinition, type SecurityConfig, ServerChannel, Store, UserInfo, ValueType, authenticate, consumeRateLimit, createQuery, usersCollection as dbUsers, deleteFile, deleteUser, disableUser, downloadFile, getConfig, getFileUrl, getUploadUrl, sendEmail, startApp };
|
|
951
|
+
export { type AppOptions, type AuthConfig, type AuthOption, type AuthRateLimitOverride, type AuthRateLimitsConfig, type CloudBackendConnectResponse, ConfigSchema, CronJobInputParams, type FileVisibility, LiveData, type LiveDataConfig, type LiveQueryCleanup, type LiveQueryPublish, type LiveQueryWatch, Module, RateLimitRule, RateLimitType, RoleDefinition, RouteDefinition, type SecurityConfig, ServerChannel, Store, UserInfo, ValueType, authenticate, clearSessionUser, consumeRateLimit, createQuery, createSession, sessionsCollection as dbSessions, usersCollection as dbUsers, deleteFile, deleteUser, disableUser, downloadFile, getConfig, getFileUrl, getUploadUrl, invalidateAllUserSessions, obtainSession, sendEmail, setAuthTokenCookie, setSessionUser, startApp };
|