@pol-studios/db 1.0.33 → 1.0.35
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/UserMetadataContext-QLIv-mfF.d.ts +171 -0
- package/dist/auth/context.d.ts +52 -4
- package/dist/auth/context.js +26 -1
- package/dist/auth/hooks.d.ts +107 -3
- package/dist/auth/hooks.js +9 -2
- package/dist/auth/index.d.ts +5 -5
- package/dist/auth/index.js +40 -9
- package/dist/chunk-5HJLTYRA.js +355 -0
- package/dist/chunk-5HJLTYRA.js.map +1 -0
- package/dist/chunk-6KN7KLEG.js +1 -0
- package/dist/{chunk-PNC6CG5U.js → chunk-7NFMEDJW.js} +42 -9
- package/dist/chunk-7NFMEDJW.js.map +1 -0
- package/dist/{chunk-4EJ6LUH7.js → chunk-HFIGNQ7T.js} +6 -4
- package/dist/{chunk-4EJ6LUH7.js.map → chunk-HFIGNQ7T.js.map} +1 -1
- package/dist/{chunk-3XCW225W.js → chunk-NP34C3O3.js} +53 -256
- package/dist/chunk-NP34C3O3.js.map +1 -0
- package/dist/{chunk-E64B4PJZ.js → chunk-QHXN6BNL.js} +3 -3
- package/dist/{chunk-OUCPYEKC.js → chunk-U4BZKCBH.js} +4 -4
- package/dist/chunk-UBHORKBS.js +215 -0
- package/dist/chunk-UBHORKBS.js.map +1 -0
- package/dist/{chunk-E6JL3RUF.js → chunk-YQUNORJD.js} +176 -85
- package/dist/chunk-YQUNORJD.js.map +1 -0
- package/dist/hooks/index.js +9 -7
- package/dist/index.js +18 -15
- package/dist/index.native.js +18 -15
- package/dist/index.web.js +13 -10
- package/dist/index.web.js.map +1 -1
- package/dist/with-auth/index.js +7 -5
- package/dist/with-auth/index.js.map +1 -1
- package/package.json +1 -1
- package/dist/UserMetadataContext-yLZQu24J.d.ts +0 -33
- package/dist/chunk-3XCW225W.js.map +0 -1
- package/dist/chunk-E6JL3RUF.js.map +0 -1
- package/dist/chunk-NSIAAYW3.js +0 -1
- package/dist/chunk-PNC6CG5U.js.map +0 -1
- /package/dist/{chunk-NSIAAYW3.js.map → chunk-6KN7KLEG.js.map} +0 -0
- /package/dist/{chunk-E64B4PJZ.js.map → chunk-QHXN6BNL.js.map} +0 -0
- /package/dist/{chunk-OUCPYEKC.js.map → chunk-U4BZKCBH.js.map} +0 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/hooks/useDbQueryById.ts","../src/hooks/useAdvanceQuery.ts","../src/hooks/useDbInsert.ts","../src/hooks/useDbUpdate.ts","../src/hooks/useDbUpsert.ts","../src/hooks/useDbDelete.ts","../src/hooks/useDbInfiniteQuery.ts","../src/hooks/useDbCount.ts","../src/hooks/useSyncStatus.ts","../src/hooks/useSyncControl.ts","../src/hooks/useOnlineStatus.ts"],"sourcesContent":["/**\n * V3 useDbQueryById Hook\n *\n * React hook for querying a single record by ID from a table.\n * Works identically whether PowerSync or Supabase is the backend.\n * Uses React Query for state management and caching.\n */\n\nimport { useCallback, useEffect, useMemo } from \"react\";\nimport { useQuery } from \"@tanstack/react-query\";\nimport { useDataLayerCore } from \"./useDataLayer\";\nimport type { WhereClause } from \"../core/types\";\nimport { devLog, devWarn } from \"../utils/dev-log\";\n\n// =============================================================================\n// Types\n// =============================================================================\n\n/**\n * Options for useDbQueryById hook\n */\nexport interface UseDbQueryByIdOptions {\n /** Columns to select (Supabase-style select string) */\n select?: string;\n /** Whether the query is enabled (default: true if id is provided) */\n enabled?: boolean;\n /** React Query stale time in ms (default: 30000) */\n staleTime?: number;\n}\n\n/**\n * Result from useDbQueryById hook\n */\nexport interface UseDbQueryByIdResult<T> {\n /** Query data (undefined while loading, null if not found) */\n data: T | null | undefined;\n /** Whether query is loading (initial load) */\n isLoading: boolean;\n /** Whether query is in pending state */\n isPending: boolean;\n /** Whether query is currently fetching (including refetch) */\n isFetching: boolean;\n /** Query error if any */\n error: Error | null;\n /** Refetch the query */\n refetch: () => Promise<void>;\n}\n\n// =============================================================================\n// Helper Functions\n// =============================================================================\n\n/**\n * Build a query key for React Query\n *\n * Creates a stable, unique key for caching based on table, ID, and select.\n * Keys are namespaced with \"v3\" to avoid collisions with V2 queries.\n */\nfunction buildQueryKey(table: string, id: string | number | null | undefined, select?: string): unknown[] {\n return [\"v3\", \"queryById\", table, id, select ?? \"*\"];\n}\n\n// =============================================================================\n// Hook Implementation\n// =============================================================================\n\n/**\n * Hook for querying a single record by ID\n *\n * This hook provides a unified interface for fetching a single record that works\n * identically whether the backend is PowerSync (offline-first) or\n * Supabase (online-only). It uses React Query for caching and state management.\n *\n * Features:\n * - Automatic backend selection based on DataLayerProvider configuration\n * - React Query integration for caching, deduplication, and background updates\n * - Automatic disabling when ID is null/undefined\n * - Fallback to query with where clause if adapter doesn't support queryById\n * - Type-safe with generic type parameter\n *\n * @param table - The table name to query\n * @param id - The record ID (query is disabled if null/undefined)\n * @param options - Query options (select, enabled, staleTime)\n * @returns Query result with data, loading states, error, and refetch function\n *\n * @example\n * // Basic query by ID\n * const { data, isLoading, error } = useDbQueryById<Task>(\"Task\", taskId);\n *\n * @example\n * // Query with relations\n * const { data, isLoading, error } = useDbQueryById<Task>(\"Task\", taskId, {\n * select: \"*, Project(*), AssignedUser:User(*)\",\n * });\n *\n * @example\n * // Conditional query based on other state\n * const { data } = useDbQueryById<Project>(\"Project\", selectedProjectId, {\n * enabled: hasPermission && !!selectedProjectId,\n * });\n *\n * @example\n * // With custom stale time\n * const { data } = useDbQueryById<User>(\"User\", userId, {\n * staleTime: 60000, // 1 minute\n * });\n */\nexport function useDbQueryById<T = Record<string, unknown>>(table: string, id: string | number | null | undefined, options: UseDbQueryByIdOptions = {}): UseDbQueryByIdResult<T> {\n const {\n registry\n } = useDataLayerCore();\n const {\n select,\n enabled = id != null,\n staleTime = 30000\n } = options;\n\n // Get adapter for this table\n // No isInitialized check needed - if we get here, core context exists = initialized\n const adapter = useMemo(() => {\n try {\n return registry.getAdapter(table);\n } catch {\n return null;\n }\n }, [registry, table]);\n\n // Build query key - memoized to prevent unnecessary re-renders\n const queryKey = useMemo(() => buildQueryKey(table, id, select), [table, id, select]);\n\n // Query function\n const queryFn = useCallback(async (): Promise<T | null> => {\n if (!adapter) {\n throw new Error(`Adapter not available for table: ${table}`);\n }\n if (id == null) {\n return null;\n }\n\n // Use queryById if available, otherwise fall back to query with where\n if (adapter.queryById) {\n return adapter.queryById<T>(table, String(id), {\n select\n });\n }\n\n // Fallback: use query with where clause\n const result = await adapter.query<T>(table, {\n select,\n where: {\n id\n } as WhereClause,\n limit: 1\n });\n return result.data[0] ?? null;\n }, [adapter, table, id, select]);\n\n // Execute query with React Query\n const query = useQuery({\n queryKey,\n queryFn,\n enabled: enabled && adapter !== null && id != null,\n staleTime\n });\n\n // Dev logging for debugging\n useEffect(() => {\n const adapterName = adapter?.name ?? \"unknown\";\n\n // Log errors\n if (query.isError && query.error) {\n devWarn(\"useDbQueryById\", `${table}(${id}) via ${adapterName}: Error - ${query.error.message}`);\n }\n\n // Log not found (only after successful fetch, not during loading)\n if (query.isSuccess && query.data === null) {\n devLog(\"useDbQueryById\", `${table}(${id}) via ${adapterName}: not found`);\n }\n }, [query.isError, query.error, query.isSuccess, query.data, table, id, adapter]);\n\n // Build refetch function\n const refetch = useCallback(async () => {\n await query.refetch();\n }, [query]);\n return {\n data: query.data,\n isLoading: query.isLoading,\n isPending: query.isPending,\n isFetching: query.isFetching,\n error: query.error as Error | null,\n refetch\n };\n}\nexport default useDbQueryById;","/**\n * V3 useAdvanceQuery Hook\n *\n * Hybrid query hook that combines PowerSync (local SQLite) with edge function filtering.\n * - When NO filters active: Uses PowerSync for fast local queries that stay in sync\n * - When filters active: Uses edge function for complex filtering\n *\n * This provides the best of both worlds:\n * - Fast, reactive local queries via PowerSync\n * - Complex filtering, natural language queries, and aggregations via edge function\n *\n * @example\n * const [result, filters, setFilters] = useAdvanceQuery<Equipment[]>(\n * \"EquipmentFixtureUnit\",\n * {\n * select: \"*, EquipmentFixtureUnitControl(*)\",\n * where: { projectDatabaseId: 123 },\n * orderBy: [{ field: \"unitNumber\", direction: \"asc\" }],\n * filterKey: \"equipment-filters\",\n * }\n * );\n */\n\nimport { Dispatch, SetStateAction, useCallback, useMemo, useRef, useState, useEffect } from \"react\";\nimport { useQuery } from \"@tanstack/react-query\";\nimport { useDataLayerCore } from \"./useDataLayer\";\nimport { useDbQuery } from \"./useDbQuery\";\nimport type { TableIdentifier, ResolveRowType, UseDbQueryOptions } from \"./useDbQuery\";\nimport type { QueryOptions } from \"../core/types\";\nimport { useSessionStorageState } from \"@pol-studios/hooks/storage\";\nimport { isUsable, omit } from \"@pol-studios/utils\";\nimport { getSupabaseUrl } from \"../config\";\nimport useSupabase from \"../useSupabase\";\nimport { devLog, devWarn } from \"../utils/dev-log\";\n\n// =============================================================================\n// Types (re-exported from useDbAdvanceQuery for compatibility)\n// =============================================================================\n\nexport type FilterOperator = \"=\" | \">\" | \">=\" | \"<\" | \"<=\" | \"contains\" | \"ilike\" | \"is\" | \"in\" | \"ai_search\";\nexport interface Filter {\n id: string;\n field: string;\n op: FilterOperator;\n value: string | number | string[] | number[] | boolean | null;\n not?: boolean;\n similarity?: number;\n where?: string;\n display?: string;\n}\nexport interface FilterGroup {\n id: string;\n op: \"AND\" | \"OR\";\n filters: Array<Filter | FilterGroup>;\n not?: boolean;\n}\nexport interface Pagination {\n offset?: number;\n limit?: number;\n}\nexport interface Sort {\n field: string;\n direction: \"asc\" | \"desc\";\n}\nexport interface QueryState extends FilterGroup {\n pagination?: Pagination;\n sort?: Sort[];\n distinctOn?: string[];\n naturalLanguageQuery?: string;\n isReady: boolean;\n}\nexport interface ClarificationQuestion {\n question: string;\n suggestions: Array<{\n interpretation: string;\n field_path: string;\n example: string;\n confidence: number;\n }>;\n}\n\n// =============================================================================\n// Options and Result Types\n// =============================================================================\n\nexport interface UseAdvanceQueryOptions extends Omit<UseDbQueryOptions, \"realtime\"> {\n /** Key for persisting filter state (required for filter state persistence) */\n filterKey: string;\n /** Initial filter state */\n initialFilters?: QueryState;\n /** Timeout for edge function requests in ms (default: 15000) */\n timeout?: number;\n /** Count mode: \"exact\" | \"estimated\" | \"\" (default: \"exact\") */\n count?: \"exact\" | \"estimated\" | \"\";\n /**\n * Whether to enable real-time subscriptions\n * - PowerSync path: Uses watch() for reactive updates (default: true when PowerSync)\n * - Edge function path: Uses Supabase realtime to invalidate query on changes\n */\n realtime?: boolean;\n}\nexport interface UseAdvanceQueryResult<T> {\n data: T[] | undefined;\n isLoading: boolean;\n isPending: boolean;\n isFetching: boolean;\n isRefetching: boolean;\n isSuccess: boolean;\n isError: boolean;\n error: Error | null;\n refetch: () => Promise<void>;\n count?: number;\n clarification?: ClarificationQuestion;\n}\n\n// =============================================================================\n// Default Filter State\n// =============================================================================\n\nconst createDefaultFilterState = (): QueryState => ({\n id: \"root\",\n op: \"AND\",\n filters: [],\n pagination: undefined,\n sort: [],\n isReady: true\n});\n\n// =============================================================================\n// Hook Implementation\n// =============================================================================\n\n/**\n * Hybrid advance query hook\n *\n * Uses PowerSync (local SQLite) when no filters are active for fast, reactive queries.\n * Falls back to edge function when filters are active for complex filtering.\n */\nexport function useAdvanceQuery<T extends TableIdentifier>(table: T, options: UseAdvanceQueryOptions): [UseAdvanceQueryResult<ResolveRowType<T>>, QueryState, Dispatch<SetStateAction<QueryState>>];\nexport function useAdvanceQuery<T>(table: string, options: UseAdvanceQueryOptions): [UseAdvanceQueryResult<T>, QueryState, Dispatch<SetStateAction<QueryState>>];\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport function useAdvanceQuery<T = any>(table: TableIdentifier | string, options: UseAdvanceQueryOptions): [UseAdvanceQueryResult<T>, QueryState, Dispatch<SetStateAction<QueryState>>] {\n const tableName = typeof table === \"string\" ? table : `${(table as {\n schema: string;\n table: string;\n }).schema}.${(table as {\n schema: string;\n table: string;\n }).table}`;\n const {\n registry,\n queryClient,\n powerSync\n } = useDataLayerCore();\n const supabase = useSupabase();\n const {\n filterKey,\n initialFilters,\n enabled = true,\n timeout = 15000,\n count = \"exact\",\n realtime,\n select,\n where,\n orderBy,\n limit,\n offset,\n ...restOptions\n } = options;\n\n // Determine if realtime should be enabled\n // Default: true for PowerSync path, false for edge function path\n const isPowerSync = powerSync !== null;\n const realtimeEnabled = realtime ?? isPowerSync;\n\n // ==========================================================================\n // Filter State Management\n // ==========================================================================\n\n const defaultFilterState = useMemo(() => initialFilters ?? createDefaultFilterState(),\n // eslint-disable-next-line react-hooks/exhaustive-deps\n [] // Only compute once\n );\n const [filtersRaw, setFiltersRaw] = useSessionStorageState<QueryState>(filterKey, defaultFilterState);\n const filters = filtersRaw ?? defaultFilterState;\n\n // Type-safe setFilters wrapper\n const setFilters: Dispatch<SetStateAction<QueryState>> = useCallback(action => {\n if (typeof action === \"function\") {\n setFiltersRaw(prev => action(prev ?? defaultFilterState));\n } else {\n setFiltersRaw(action);\n }\n }, [setFiltersRaw, defaultFilterState]);\n\n // ==========================================================================\n // Determine Query Strategy\n // ==========================================================================\n\n const hasAdvancedFilters = useMemo(() => (filters?.filters?.length ?? 0) > 0 || !!filters?.naturalLanguageQuery, [filters?.filters?.length, filters?.naturalLanguageQuery]);\n\n // Use direct DB query (via useDbQuery) when: no advanced filters\n // useDbQuery handles adapter selection (PowerSync vs Supabase) based on sync status\n // This ensures queries use Supabase during initial sync when PowerSync hasn't synced yet\n const usePowerSyncPath = !hasAdvancedFilters;\n\n // ==========================================================================\n // PowerSync Query (no filters path)\n // ==========================================================================\n\n // Convert orderBy from Sort[] to QueryOptions orderBy format\n const powerSyncOrderBy = useMemo(() => {\n if (filters?.sort && filters.sort.length > 0) {\n return filters.sort.map(s => ({\n field: s.field,\n direction: s.direction\n }));\n }\n return orderBy;\n }, [filters?.sort, orderBy]);\n const powerSyncResult = useDbQuery<T>(table as string, {\n select,\n where,\n orderBy: powerSyncOrderBy,\n limit: filters?.pagination?.limit ?? limit,\n offset: filters?.pagination?.offset ?? offset,\n enabled: enabled && usePowerSyncPath && filters?.isReady !== false,\n realtime: realtimeEnabled // Enable watch() subscriptions for reactive updates\n });\n\n // ==========================================================================\n // Edge Function Query (with filters path)\n // ==========================================================================\n\n const [extraData, setExtraData] = useState<{\n count?: number;\n key?: string;\n }>({});\n const edgeFunctionQueryKey = useMemo(() => [\"v3\", \"advance-query\", tableName, select, JSON.stringify(where), JSON.stringify(filters)], [tableName, select, where, filters]);\n const edgeFunctionResult = useQuery<{\n data: T[];\n count?: number;\n clarification?: ClarificationQuestion;\n }>({\n queryKey: edgeFunctionQueryKey,\n queryFn: async ({\n signal\n }) => {\n const {\n data: {\n session\n }\n } = await supabase.auth.getSession();\n if (!session?.access_token) {\n throw new Error(\"No active session\");\n }\n const controller = new AbortController();\n signal.addEventListener(\"abort\", () => controller.abort());\n const timeoutId = setTimeout(() => controller.abort(), timeout);\n try {\n // Build filter body\n const filterBody = {\n id: filters.id || \"root\",\n op: filters.op || \"AND\",\n not: filters.not,\n filters: filters.filters || []\n };\n\n // Parse base where conditions into filters\n const baseFilters: Filter[] = [];\n if (where) {\n Object.entries(where).forEach(([field, value]) => {\n if (value !== undefined && value !== null) {\n if (typeof value === \"object\" && \"in\" in value) {\n // Handle { in: [...] } syntax\n baseFilters.push({\n id: `base-${field}`,\n field,\n op: \"in\",\n value: (value as {\n in: unknown[];\n }).in as string[] | number[]\n });\n } else {\n baseFilters.push({\n id: `base-${field}`,\n field,\n op: \"=\",\n value: value as string | number | boolean | null\n });\n }\n }\n });\n }\n\n // Combine base filters with user filters\n const combinedFilters = [...baseFilters, ...filterBody.filters];\n const currentKey = `${tableName}${select}${JSON.stringify(omit(filters, [\"pagination\", \"isReady\"]))}`;\n const res = await fetch(`${getSupabaseUrl()}/functions/v1/query?forceDenoVersion=2`, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n Authorization: `Bearer ${session.access_token}`\n },\n body: JSON.stringify({\n table: tableName,\n schema: \"public\",\n select: select ?? \"*\",\n filters: {\n id: filterBody.id,\n op: filterBody.op,\n not: filterBody.not,\n filters: combinedFilters\n },\n pagination: filters.pagination,\n sort: filters.sort || orderBy?.map(o => ({\n field: o.field,\n direction: o.direction\n })),\n distinctOn: filters.distinctOn,\n naturalLanguageQuery: filters.naturalLanguageQuery,\n count: currentKey === extraData.key ? \"\" : count\n }),\n signal: controller.signal\n });\n if (!res.ok) {\n const errorData = await res.json();\n const errorMessage = typeof errorData?.error === \"string\" ? errorData.error : errorData?.error?.message || errorData?.message || \"Query failed\";\n throw new Error(errorMessage);\n }\n const result = await res.json();\n\n // Handle clarification response\n if (result.clarification) {\n return {\n data: [] as T[],\n count: 0,\n clarification: result.clarification\n };\n }\n setExtraData(prev => ({\n count: prev.key === currentKey ? prev.count : result.count,\n key: currentKey\n }));\n return {\n data: result.data as T[],\n count: result.count\n };\n } finally {\n clearTimeout(timeoutId);\n }\n },\n enabled: enabled && !usePowerSyncPath && filters?.isReady !== false,\n staleTime: 30000,\n gcTime: 300000,\n refetchOnMount: true,\n refetchOnWindowFocus: false\n });\n\n // ==========================================================================\n // Supabase Realtime Subscription (edge function path only)\n // ==========================================================================\n\n // When realtime is enabled and using edge function path,\n // subscribe to Supabase realtime to invalidate query on changes\n useEffect(() => {\n // Only set up realtime for edge function path when realtime is enabled\n if (!realtimeEnabled || usePowerSyncPath || !enabled) {\n return;\n }\n\n // Build filter for the subscription based on where clause\n const channel = supabase.channel(`advance-query-${tableName}-${filterKey}`).on(\"postgres_changes\", {\n event: \"*\",\n // Listen to INSERT, UPDATE, DELETE\n schema: \"public\",\n table: tableName\n // Note: We can't easily filter by complex where clauses,\n // so we invalidate on any change to the table\n }, () => {\n // Invalidate the query to trigger a refetch\n queryClient.invalidateQueries({\n queryKey: edgeFunctionQueryKey\n });\n }).subscribe();\n return () => {\n supabase.removeChannel(channel);\n };\n }, [realtimeEnabled, usePowerSyncPath, enabled, supabase, tableName, filterKey, queryClient, edgeFunctionQueryKey]);\n\n // ==========================================================================\n // Dev Logging (edge function path only - PowerSync path logs via useDbQuery)\n // ==========================================================================\n\n useEffect(() => {\n // Only log for edge function path\n if (usePowerSyncPath) return;\n const pathName = \"EdgeFunction\";\n\n // Log errors\n if (edgeFunctionResult.isError && edgeFunctionResult.error) {\n devWarn(\"useAdvanceQuery\", `${tableName} via ${pathName}: Error - ${edgeFunctionResult.error.message}`);\n }\n\n // Log empty results (only after successful fetch)\n if (edgeFunctionResult.isSuccess && edgeFunctionResult.data?.data?.length === 0) {\n devLog(\"useAdvanceQuery\", `${tableName} via ${pathName}: 0 results`);\n }\n }, [usePowerSyncPath, edgeFunctionResult.isError, edgeFunctionResult.error, edgeFunctionResult.isSuccess, edgeFunctionResult.data, tableName]);\n\n // ==========================================================================\n // Combine Results\n // ==========================================================================\n\n const result = useMemo((): UseAdvanceQueryResult<T> => {\n if (usePowerSyncPath) {\n // PowerSync path\n return {\n data: powerSyncResult.data as T[] | undefined,\n isLoading: powerSyncResult.isLoading,\n isPending: powerSyncResult.isPending,\n isFetching: powerSyncResult.isFetching,\n isRefetching: powerSyncResult.isRefetching,\n isSuccess: powerSyncResult.isSuccess,\n isError: powerSyncResult.isError,\n error: powerSyncResult.error,\n refetch: powerSyncResult.refetch,\n count: powerSyncResult.count ?? powerSyncResult.data?.length\n };\n }\n\n // Edge function path\n return {\n data: edgeFunctionResult.data?.data,\n isLoading: edgeFunctionResult.isLoading,\n isPending: edgeFunctionResult.isPending,\n isFetching: edgeFunctionResult.isFetching,\n isRefetching: edgeFunctionResult.isFetching,\n isSuccess: edgeFunctionResult.isSuccess,\n isError: edgeFunctionResult.isError,\n error: edgeFunctionResult.error as Error | null,\n refetch: async () => {\n await edgeFunctionResult.refetch();\n },\n count: edgeFunctionResult.data?.count ?? extraData.count,\n clarification: edgeFunctionResult.data?.clarification\n };\n }, [usePowerSyncPath, powerSyncResult, edgeFunctionResult, extraData.count]);\n return [result, filters, setFilters];\n}\nexport default useAdvanceQuery;","import { c as _c } from \"react/compiler-runtime\";\n/**\n * V3 useDbInsert Hook\n *\n * React hook for inserting records into a table using the V3 adapter pattern.\n * Integrates with React Query for mutation management and cache invalidation.\n */\n\nimport { useCallback } from \"react\";\nimport { useMutation, useQueryClient } from \"@tanstack/react-query\";\nimport { useDataLayerCore } from \"./useDataLayer\";\n\n/**\n * Options for useDbInsert hook\n */\nexport interface UseDbInsertOptions<T> {\n /** Callback when insert succeeds */\n onSuccess?: (data: T) => void;\n /** Callback when insert fails */\n onError?: (error: Error) => void;\n /** Tables to invalidate after successful insert */\n invalidateTables?: string[];\n}\n\n/**\n * Result from useDbInsert hook\n */\nexport interface UseDbInsertResult<T> {\n /** Trigger insert (fire and forget) */\n mutate: (data: Partial<T>) => void;\n /** Trigger insert and await result */\n mutateAsync: (data: Partial<T>) => Promise<T>;\n /** Whether mutation is in progress */\n isPending: boolean;\n /** Mutation error if any */\n error: Error | null;\n /** Reset mutation state */\n reset: () => void;\n /** Last successful data */\n data: T | undefined;\n}\n\n/**\n * Hook for inserting records into a table\n *\n * Uses the V3 adapter pattern to route inserts to the appropriate backend\n * (PowerSync, Supabase, or Cached) based on table configuration.\n *\n * @param table - The table name to insert into\n * @param options - Optional configuration for callbacks and cache invalidation\n * @returns Mutation result with mutate/mutateAsync functions\n *\n * @example\n * ```typescript\n * const { mutateAsync, isPending } = useDbInsert<Task>(\"Task\");\n * const newTask = await mutateAsync({ title: \"New Task\", status: \"pending\" });\n * ```\n *\n * @example\n * ```typescript\n * // With options\n * const { mutate } = useDbInsert<Project>(\"Project\", {\n * onSuccess: (data) => console.log(\"Created:\", data),\n * onError: (error) => console.error(\"Failed:\", error),\n * invalidateTables: [\"Project\", \"ProjectSummary\"],\n * });\n * ```\n */\nexport function useDbInsert(table, t0) {\n const $ = _c(25);\n let t1;\n if ($[0] !== t0) {\n t1 = t0 === undefined ? {} : t0;\n $[0] = t0;\n $[1] = t1;\n } else {\n t1 = $[1];\n }\n const options = t1;\n const {\n registry\n } = useDataLayerCore();\n const queryClient = useQueryClient();\n const {\n onSuccess,\n onError,\n invalidateTables: t2\n } = options;\n let t3;\n if ($[2] !== t2 || $[3] !== table) {\n t3 = t2 === undefined ? [table] : t2;\n $[2] = t2;\n $[3] = table;\n $[4] = t3;\n } else {\n t3 = $[4];\n }\n const invalidateTables = t3;\n let t4;\n if ($[5] !== registry || $[6] !== table) {\n t4 = async data => {\n const adapter = registry.getAdapter(table, \"write\");\n return await adapter.insert(table, data);\n };\n $[5] = registry;\n $[6] = table;\n $[7] = t4;\n } else {\n t4 = $[7];\n }\n const mutationFn = t4;\n let t5;\n if ($[8] !== invalidateTables || $[9] !== onSuccess || $[10] !== queryClient) {\n t5 = data_0 => {\n invalidateTables.forEach(t => {\n queryClient.invalidateQueries({\n predicate: query => query.queryKey[0] === \"v3\" && query.queryKey[2] === t\n });\n });\n onSuccess?.(data_0);\n };\n $[8] = invalidateTables;\n $[9] = onSuccess;\n $[10] = queryClient;\n $[11] = t5;\n } else {\n t5 = $[11];\n }\n let t6;\n if ($[12] !== onError) {\n t6 = error => {\n onError?.(error instanceof Error ? error : new Error(String(error)));\n };\n $[12] = onError;\n $[13] = t6;\n } else {\n t6 = $[13];\n }\n let t7;\n if ($[14] !== mutationFn || $[15] !== t5 || $[16] !== t6) {\n t7 = {\n mutationFn,\n onSuccess: t5,\n onError: t6\n };\n $[14] = mutationFn;\n $[15] = t5;\n $[16] = t6;\n $[17] = t7;\n } else {\n t7 = $[17];\n }\n const mutation = useMutation(t7);\n const t8 = mutation.error as Error | null;\n let t9;\n if ($[18] !== mutation.data || $[19] !== mutation.isPending || $[20] !== mutation.mutate || $[21] !== mutation.mutateAsync || $[22] !== mutation.reset || $[23] !== t8) {\n t9 = {\n mutate: mutation.mutate,\n mutateAsync: mutation.mutateAsync,\n isPending: mutation.isPending,\n error: t8,\n reset: mutation.reset,\n data: mutation.data\n };\n $[18] = mutation.data;\n $[19] = mutation.isPending;\n $[20] = mutation.mutate;\n $[21] = mutation.mutateAsync;\n $[22] = mutation.reset;\n $[23] = t8;\n $[24] = t9;\n } else {\n t9 = $[24];\n }\n return t9;\n}\nexport default useDbInsert;","import { c as _c } from \"react/compiler-runtime\";\n/**\n * V3 useDbUpdate Hook\n *\n * React hook for updating records in a table using the V3 adapter pattern.\n * Integrates with React Query for mutation management, cache invalidation,\n * and optional optimistic updates.\n */\n\nimport { useCallback } from \"react\";\nimport { useMutation, useQueryClient } from \"@tanstack/react-query\";\nimport { useDataLayerCore } from \"./useDataLayer\";\n\n/**\n * Options for useDbUpdate hook\n */\nexport interface UseDbUpdateOptions<T> {\n /** Callback when update succeeds */\n onSuccess?: (data: T) => void;\n /** Callback when update fails */\n onError?: (error: Error) => void;\n /** Tables to invalidate after successful update */\n invalidateTables?: string[];\n /** Enable optimistic updates */\n optimistic?: boolean;\n}\n\n/**\n * Result from useDbUpdate hook\n */\nexport interface UseDbUpdateResult<T> {\n /** Trigger update (fire and forget) */\n mutate: (params: {\n id: string;\n data: Partial<T>;\n }) => void;\n /** Trigger update and await result */\n mutateAsync: (params: {\n id: string;\n data: Partial<T>;\n }) => Promise<T>;\n /** Whether mutation is in progress */\n isPending: boolean;\n /** Mutation error if any */\n error: Error | null;\n /** Reset mutation state */\n reset: () => void;\n /** Last successful data */\n data: T | undefined;\n}\n\n/**\n * Hook for updating records in a table\n *\n * Uses the V3 adapter pattern to route updates to the appropriate backend\n * (PowerSync, Supabase, or Cached) based on table configuration.\n *\n * @param table - The table name to update records in\n * @param options - Optional configuration for callbacks, cache invalidation, and optimistic updates\n * @returns Mutation result with mutate/mutateAsync functions\n *\n * @example\n * ```typescript\n * const { mutateAsync, isPending } = useDbUpdate<Task>(\"Task\");\n * const updated = await mutateAsync({ id: taskId, data: { status: \"completed\" } });\n * ```\n *\n * @example\n * ```typescript\n * // With optimistic updates\n * const { mutate } = useDbUpdate<Project>(\"Project\", {\n * optimistic: true,\n * onSuccess: (data) => console.log(\"Updated:\", data),\n * onError: (error) => console.error(\"Failed:\", error),\n * });\n * ```\n */\nexport function useDbUpdate(table, t0) {\n const $ = _c(32);\n let t1;\n if ($[0] !== t0) {\n t1 = t0 === undefined ? {} : t0;\n $[0] = t0;\n $[1] = t1;\n } else {\n t1 = $[1];\n }\n const options = t1;\n const {\n registry\n } = useDataLayerCore();\n const queryClient = useQueryClient();\n const {\n onSuccess,\n onError,\n invalidateTables: t2,\n optimistic: t3\n } = options;\n let t4;\n if ($[2] !== t2 || $[3] !== table) {\n t4 = t2 === undefined ? [table] : t2;\n $[2] = t2;\n $[3] = table;\n $[4] = t4;\n } else {\n t4 = $[4];\n }\n const invalidateTables = t4;\n const optimistic = t3 === undefined ? false : t3;\n let t5;\n if ($[5] !== registry || $[6] !== table) {\n t5 = async params => {\n const adapter = registry.getAdapter(table, \"write\");\n return await adapter.update(table, params.id, params.data);\n };\n $[5] = registry;\n $[6] = table;\n $[7] = t5;\n } else {\n t5 = $[7];\n }\n const mutationFn = t5;\n let t6;\n if ($[8] !== optimistic || $[9] !== queryClient || $[10] !== table) {\n t6 = optimistic ? async () => {\n await queryClient.cancelQueries({\n predicate: query => query.queryKey[0] === \"v3\" && query.queryKey[2] === table\n });\n const previousData = queryClient.getQueriesData({\n predicate: query_0 => query_0.queryKey[0] === \"v3\" && query_0.queryKey[2] === table\n });\n return {\n previousData\n };\n } : undefined;\n $[8] = optimistic;\n $[9] = queryClient;\n $[10] = table;\n $[11] = t6;\n } else {\n t6 = $[11];\n }\n let t7;\n if ($[12] !== invalidateTables || $[13] !== onSuccess || $[14] !== queryClient) {\n t7 = data => {\n invalidateTables.forEach(t => {\n queryClient.invalidateQueries({\n predicate: query_1 => query_1.queryKey[0] === \"v3\" && query_1.queryKey[2] === t\n });\n });\n onSuccess?.(data);\n };\n $[12] = invalidateTables;\n $[13] = onSuccess;\n $[14] = queryClient;\n $[15] = t7;\n } else {\n t7 = $[15];\n }\n let t8;\n if ($[16] !== onError || $[17] !== optimistic || $[18] !== queryClient) {\n t8 = (error, _variables, context) => {\n if (optimistic && context?.previousData) {\n context.previousData.forEach(t9 => {\n const [queryKey, data_0] = t9;\n queryClient.setQueryData(queryKey, data_0);\n });\n }\n onError?.(error instanceof Error ? error : new Error(String(error)));\n };\n $[16] = onError;\n $[17] = optimistic;\n $[18] = queryClient;\n $[19] = t8;\n } else {\n t8 = $[19];\n }\n let t9;\n if ($[20] !== mutationFn || $[21] !== t6 || $[22] !== t7 || $[23] !== t8) {\n t9 = {\n mutationFn,\n onMutate: t6,\n onSuccess: t7,\n onError: t8\n };\n $[20] = mutationFn;\n $[21] = t6;\n $[22] = t7;\n $[23] = t8;\n $[24] = t9;\n } else {\n t9 = $[24];\n }\n const mutation = useMutation(t9);\n const t10 = mutation.error as Error | null;\n let t11;\n if ($[25] !== mutation.data || $[26] !== mutation.isPending || $[27] !== mutation.mutate || $[28] !== mutation.mutateAsync || $[29] !== mutation.reset || $[30] !== t10) {\n t11 = {\n mutate: mutation.mutate,\n mutateAsync: mutation.mutateAsync,\n isPending: mutation.isPending,\n error: t10,\n reset: mutation.reset,\n data: mutation.data\n };\n $[25] = mutation.data;\n $[26] = mutation.isPending;\n $[27] = mutation.mutate;\n $[28] = mutation.mutateAsync;\n $[29] = mutation.reset;\n $[30] = t10;\n $[31] = t11;\n } else {\n t11 = $[31];\n }\n return t11;\n}\nexport default useDbUpdate;","import { c as _c } from \"react/compiler-runtime\";\n/**\n * V3 useDbUpsert Hook\n *\n * React hook for upserting (insert or update) records in a table using the V3 adapter pattern.\n * Integrates with React Query for mutation management and cache invalidation.\n */\n\nimport { useCallback } from \"react\";\nimport { useMutation, useQueryClient } from \"@tanstack/react-query\";\nimport { useDataLayerCore } from \"./useDataLayer\";\n\n/**\n * Options for useDbUpsert hook\n */\nexport interface UseDbUpsertOptions<T> {\n /** Callback when upsert succeeds */\n onSuccess?: (data: T) => void;\n /** Callback when upsert fails */\n onError?: (error: Error) => void;\n /** Tables to invalidate after successful upsert */\n invalidateTables?: string[];\n}\n\n/**\n * Result from useDbUpsert hook\n */\nexport interface UseDbUpsertResult<T> {\n /** Trigger upsert (fire and forget) */\n mutate: (data: Partial<T>) => void;\n /** Trigger upsert and await result */\n mutateAsync: (data: Partial<T>) => Promise<T>;\n /** Whether mutation is in progress */\n isPending: boolean;\n /** Mutation error if any */\n error: Error | null;\n /** Reset mutation state */\n reset: () => void;\n /** Last successful data */\n data: T | undefined;\n}\n\n/**\n * Hook for upserting (insert or update) records in a table\n *\n * Uses the V3 adapter pattern to route upserts to the appropriate backend\n * (PowerSync, Supabase, or Cached) based on table configuration.\n *\n * If the record has an ID and exists, it will be updated.\n * Otherwise, a new record will be inserted.\n *\n * @param table - The table name to upsert into\n * @param options - Optional configuration for callbacks and cache invalidation\n * @returns Mutation result with mutate/mutateAsync functions\n *\n * @example\n * ```typescript\n * const { mutateAsync, isPending } = useDbUpsert<Task>(\"Task\");\n * const task = await mutateAsync({ id: existingId, title: \"Updated Title\" });\n * ```\n *\n * @example\n * ```typescript\n * // Insert if no ID, update if ID exists\n * const { mutate } = useDbUpsert<Setting>(\"Setting\", {\n * onSuccess: (data) => console.log(\"Upserted:\", data),\n * invalidateTables: [\"Setting\", \"UserPreferences\"],\n * });\n *\n * // This will insert (no id)\n * mutate({ key: \"theme\", value: \"dark\" });\n *\n * // This will update (has id)\n * mutate({ id: \"setting-123\", key: \"theme\", value: \"light\" });\n * ```\n */\nexport function useDbUpsert(table, t0) {\n const $ = _c(25);\n let t1;\n if ($[0] !== t0) {\n t1 = t0 === undefined ? {} : t0;\n $[0] = t0;\n $[1] = t1;\n } else {\n t1 = $[1];\n }\n const options = t1;\n const {\n registry\n } = useDataLayerCore();\n const queryClient = useQueryClient();\n const {\n onSuccess,\n onError,\n invalidateTables: t2\n } = options;\n let t3;\n if ($[2] !== t2 || $[3] !== table) {\n t3 = t2 === undefined ? [table] : t2;\n $[2] = t2;\n $[3] = table;\n $[4] = t3;\n } else {\n t3 = $[4];\n }\n const invalidateTables = t3;\n let t4;\n if ($[5] !== registry || $[6] !== table) {\n t4 = async data => {\n const adapter = registry.getAdapter(table, \"write\");\n return await adapter.upsert(table, data);\n };\n $[5] = registry;\n $[6] = table;\n $[7] = t4;\n } else {\n t4 = $[7];\n }\n const mutationFn = t4;\n let t5;\n if ($[8] !== invalidateTables || $[9] !== onSuccess || $[10] !== queryClient) {\n t5 = data_0 => {\n invalidateTables.forEach(t => {\n queryClient.invalidateQueries({\n predicate: query => query.queryKey[0] === \"v3\" && query.queryKey[2] === t\n });\n });\n onSuccess?.(data_0);\n };\n $[8] = invalidateTables;\n $[9] = onSuccess;\n $[10] = queryClient;\n $[11] = t5;\n } else {\n t5 = $[11];\n }\n let t6;\n if ($[12] !== onError) {\n t6 = error => {\n onError?.(error instanceof Error ? error : new Error(String(error)));\n };\n $[12] = onError;\n $[13] = t6;\n } else {\n t6 = $[13];\n }\n let t7;\n if ($[14] !== mutationFn || $[15] !== t5 || $[16] !== t6) {\n t7 = {\n mutationFn,\n onSuccess: t5,\n onError: t6\n };\n $[14] = mutationFn;\n $[15] = t5;\n $[16] = t6;\n $[17] = t7;\n } else {\n t7 = $[17];\n }\n const mutation = useMutation(t7);\n const t8 = mutation.error as Error | null;\n let t9;\n if ($[18] !== mutation.data || $[19] !== mutation.isPending || $[20] !== mutation.mutate || $[21] !== mutation.mutateAsync || $[22] !== mutation.reset || $[23] !== t8) {\n t9 = {\n mutate: mutation.mutate,\n mutateAsync: mutation.mutateAsync,\n isPending: mutation.isPending,\n error: t8,\n reset: mutation.reset,\n data: mutation.data\n };\n $[18] = mutation.data;\n $[19] = mutation.isPending;\n $[20] = mutation.mutate;\n $[21] = mutation.mutateAsync;\n $[22] = mutation.reset;\n $[23] = t8;\n $[24] = t9;\n } else {\n t9 = $[24];\n }\n return t9;\n}\nexport default useDbUpsert;","import { c as _c } from \"react/compiler-runtime\";\n/**\n * V3 useDbDelete Hook\n *\n * React hook for deleting records from a table using the V3 adapter pattern.\n * Integrates with React Query for mutation management, cache invalidation,\n * and optional optimistic deletes.\n */\n\nimport { useCallback } from \"react\";\nimport { useMutation, useQueryClient } from \"@tanstack/react-query\";\nimport { useDataLayerCore } from \"./useDataLayer\";\n\n/**\n * Options for useDbDelete hook\n */\nexport interface UseDbDeleteOptions {\n /** Callback when delete succeeds */\n onSuccess?: () => void;\n /** Callback when delete fails */\n onError?: (error: Error) => void;\n /** Tables to invalidate after successful delete */\n invalidateTables?: string[];\n /** Enable optimistic delete */\n optimistic?: boolean;\n}\n\n/**\n * Result from useDbDelete hook\n */\nexport interface UseDbDeleteResult {\n /** Trigger delete (fire and forget) */\n mutate: (id: string) => void;\n /** Trigger delete and await completion */\n mutateAsync: (id: string) => Promise<void>;\n /** Whether mutation is in progress */\n isPending: boolean;\n /** Mutation error if any */\n error: Error | null;\n /** Reset mutation state */\n reset: () => void;\n}\n\n/**\n * Hook for deleting records from a table\n *\n * Uses the V3 adapter pattern to route deletes to the appropriate backend\n * (PowerSync, Supabase, or Cached) based on table configuration.\n *\n * @param table - The table name to delete from\n * @param options - Optional configuration for callbacks, cache invalidation, and optimistic deletes\n * @returns Mutation result with mutate/mutateAsync functions\n *\n * @example\n * ```typescript\n * const { mutateAsync, isPending } = useDbDelete(\"Task\");\n * await mutateAsync(taskId);\n * ```\n *\n * @example\n * ```typescript\n * // With optimistic delete for instant UI feedback\n * const { mutate } = useDbDelete(\"Comment\", {\n * optimistic: true,\n * onSuccess: () => console.log(\"Deleted successfully\"),\n * onError: (error) => console.error(\"Delete failed:\", error),\n * invalidateTables: [\"Comment\", \"Post\"],\n * });\n *\n * // Immediately removes from UI, rolls back on failure\n * mutate(commentId);\n * ```\n */\nexport function useDbDelete(table, t0) {\n const $ = _c(31);\n let t1;\n if ($[0] !== t0) {\n t1 = t0 === undefined ? {} : t0;\n $[0] = t0;\n $[1] = t1;\n } else {\n t1 = $[1];\n }\n const options = t1;\n const {\n registry\n } = useDataLayerCore();\n const queryClient = useQueryClient();\n const {\n onSuccess,\n onError,\n invalidateTables: t2,\n optimistic: t3\n } = options;\n let t4;\n if ($[2] !== t2 || $[3] !== table) {\n t4 = t2 === undefined ? [table] : t2;\n $[2] = t2;\n $[3] = table;\n $[4] = t4;\n } else {\n t4 = $[4];\n }\n const invalidateTables = t4;\n const optimistic = t3 === undefined ? false : t3;\n let t5;\n if ($[5] !== registry || $[6] !== table) {\n t5 = async id => {\n const adapter = registry.getAdapter(table, \"write\");\n await adapter.delete(table, id);\n };\n $[5] = registry;\n $[6] = table;\n $[7] = t5;\n } else {\n t5 = $[7];\n }\n const mutationFn = t5;\n let t6;\n if ($[8] !== optimistic || $[9] !== queryClient || $[10] !== table) {\n t6 = optimistic ? async id_0 => {\n await queryClient.cancelQueries({\n predicate: query => query.queryKey[0] === \"v3\" && query.queryKey[2] === table\n });\n const previousData = queryClient.getQueriesData({\n predicate: query_0 => query_0.queryKey[0] === \"v3\" && query_0.queryKey[2] === table\n });\n queryClient.setQueriesData({\n predicate: query_1 => query_1.queryKey[0] === \"v3\" && query_1.queryKey[2] === table\n }, old => {\n if (!old?.data) {\n return old;\n }\n return {\n ...old,\n data: old.data.filter(item => item.id !== id_0)\n };\n });\n return {\n previousData\n };\n } : undefined;\n $[8] = optimistic;\n $[9] = queryClient;\n $[10] = table;\n $[11] = t6;\n } else {\n t6 = $[11];\n }\n let t7;\n if ($[12] !== invalidateTables || $[13] !== onSuccess || $[14] !== queryClient) {\n t7 = () => {\n invalidateTables.forEach(t => {\n queryClient.invalidateQueries({\n predicate: query_2 => query_2.queryKey[0] === \"v3\" && query_2.queryKey[2] === t\n });\n });\n onSuccess?.();\n };\n $[12] = invalidateTables;\n $[13] = onSuccess;\n $[14] = queryClient;\n $[15] = t7;\n } else {\n t7 = $[15];\n }\n let t8;\n if ($[16] !== onError || $[17] !== optimistic || $[18] !== queryClient) {\n t8 = (error, _id, context) => {\n if (optimistic && context?.previousData) {\n context.previousData.forEach(t9 => {\n const [queryKey, data] = t9;\n queryClient.setQueryData(queryKey, data);\n });\n }\n onError?.(error instanceof Error ? error : new Error(String(error)));\n };\n $[16] = onError;\n $[17] = optimistic;\n $[18] = queryClient;\n $[19] = t8;\n } else {\n t8 = $[19];\n }\n let t9;\n if ($[20] !== mutationFn || $[21] !== t6 || $[22] !== t7 || $[23] !== t8) {\n t9 = {\n mutationFn,\n onMutate: t6,\n onSuccess: t7,\n onError: t8\n };\n $[20] = mutationFn;\n $[21] = t6;\n $[22] = t7;\n $[23] = t8;\n $[24] = t9;\n } else {\n t9 = $[24];\n }\n const mutation = useMutation(t9);\n const t10 = mutation.error as Error | null;\n let t11;\n if ($[25] !== mutation.isPending || $[26] !== mutation.mutate || $[27] !== mutation.mutateAsync || $[28] !== mutation.reset || $[29] !== t10) {\n t11 = {\n mutate: mutation.mutate,\n mutateAsync: mutation.mutateAsync,\n isPending: mutation.isPending,\n error: t10,\n reset: mutation.reset\n };\n $[25] = mutation.isPending;\n $[26] = mutation.mutate;\n $[27] = mutation.mutateAsync;\n $[28] = mutation.reset;\n $[29] = t10;\n $[30] = t11;\n } else {\n t11 = $[30];\n }\n return t11;\n}\nexport default useDbDelete;","/**\n * V3 useDbInfiniteQuery Hook\n *\n * React hook for querying records with infinite scroll pagination.\n * Works identically whether PowerSync or Supabase is the backend.\n * Uses React Query's useInfiniteQuery for state management and caching.\n *\n * Types are automatically inferred from table names when you augment\n * the DatabaseTypes interface with your app's Database type.\n *\n * @example\n * // In your app's types/db.d.ts:\n * declare module \"@pol-studios/db\" {\n * interface DatabaseTypes {\n * database: import(\"@/database.types\").Database;\n * }\n * }\n *\n * // Then usage auto-infers types:\n * const { data, fetchNextPage, hasNextPage } = useDbInfiniteQuery(\"EquipmentFixtureUnit\", {\n * pageSize: 20,\n * orderBy: [{ field: \"createdAt\", direction: \"desc\" }],\n * });\n */\n\nimport { useMemo, useCallback, useEffect } from \"react\";\nimport { useInfiniteQuery, InfiniteData } from \"@tanstack/react-query\";\nimport { useDataLayerCore } from \"./useDataLayer\";\nimport type { QueryOptions, WhereClause } from \"../core/types\";\nimport { devLog, devWarn } from \"../utils/dev-log\";\n\n// =============================================================================\n// Module Augmentation Interface\n// =============================================================================\n\n/**\n * Augment this interface in your app to enable automatic type inference.\n */\n// eslint-disable-next-line @typescript-eslint/no-empty-interface\nexport interface DatabaseTypes {}\n\n// =============================================================================\n// Database Type Helpers\n// =============================================================================\n\n/**\n * The configured Database type, or a generic fallback\n */\ntype ConfiguredDatabase = DatabaseTypes extends {\n database: infer DB;\n} ? DB : GenericSchema;\n\n/**\n * Generic schema structure for fallback\n */\ntype GenericSchema = {\n public: {\n Tables: Record<string, {\n Row: Record<string, unknown>;\n }>;\n Views: Record<string, {\n Row: Record<string, unknown>;\n }>;\n };\n [schema: string]: {\n Tables: Record<string, {\n Row: Record<string, unknown>;\n }>;\n Views?: Record<string, {\n Row: Record<string, unknown>;\n }>;\n };\n};\n\n/**\n * Default schema from Database (usually \"public\")\n */\ntype DefaultSchema = ConfiguredDatabase extends {\n public: infer S;\n} ? S : never;\n\n/**\n * Extract all valid table names from the default schema\n */\nexport type PublicTableNames = DefaultSchema extends {\n Tables: infer T;\n} ? keyof T & string : string;\n\n/**\n * Extract all valid schema names\n */\nexport type SchemaNames = keyof ConfiguredDatabase & string;\n\n/**\n * Extract table names for a specific schema\n */\nexport type SchemaTableNames<S extends string> = ConfiguredDatabase extends { [K in S]: {\n Tables: infer T;\n} } ? keyof T & string : string;\n\n/**\n * Build dot notation strings for all schema.table combinations\n */\ntype SchemaDotTable = { [S in SchemaNames]: S extends \"public\" ? never : `${S}.${SchemaTableNames<S>}` }[SchemaNames];\n\n/**\n * Table identifier - provides autocomplete for valid table names\n */\nexport type TableIdentifier = PublicTableNames | SchemaDotTable | { [S in Exclude<SchemaNames, \"public\">]: {\n schema: S;\n table: SchemaTableNames<S>;\n} }[Exclude<SchemaNames, \"public\">];\n\n/**\n * Resolve row type from a table identifier\n */\nexport type ResolveRowType<T extends TableIdentifier> = T extends string ? T extends `${infer Schema}.${infer Table}` ? ConfiguredDatabase extends { [K in Schema]: {\n Tables: { [K2 in Table]: {\n Row: infer R;\n } };\n} } ? R : Record<string, unknown> : DefaultSchema extends {\n Tables: { [K in T]: {\n Row: infer R;\n } };\n} ? R : DefaultSchema extends {\n Views: { [K in T]: {\n Row: infer R;\n } };\n} ? R : Record<string, unknown> : T extends {\n schema: infer S;\n table: infer TN;\n} ? S extends string ? TN extends string ? ConfiguredDatabase extends { [K in S]: {\n Tables: { [K2 in TN]: {\n Row: infer R;\n } };\n} } ? R : Record<string, unknown> : Record<string, unknown> : Record<string, unknown> : Record<string, unknown>;\n\n// =============================================================================\n// Types\n// =============================================================================\n\n/**\n * Options for useDbInfiniteQuery hook\n */\nexport interface UseDbInfiniteQueryOptions extends Omit<QueryOptions, \"limit\" | \"offset\" | \"enabled\"> {\n /** Whether the query is enabled (default: true) */\n enabled?: boolean;\n /** React Query stale time in ms (default: 30000) */\n staleTime?: number;\n /** Whether to refetch on window focus (default: true) */\n refetchOnWindowFocus?: boolean;\n /** Number of items per page (default: 50) */\n pageSize?: number;\n /** Text to search for */\n searchText?: string;\n /** Fields to search in when searchText is provided */\n searchFields?: string[];\n}\n\n/**\n * Result from useDbInfiniteQuery hook\n */\nexport interface UseDbInfiniteQueryResult<T> {\n /** Flattened array of all loaded data */\n data: T[] | undefined;\n /** Whether query is loading (initial load) */\n isLoading: boolean;\n /** Whether query is in pending state */\n isPending: boolean;\n /** Whether query is currently fetching (including refetch) */\n isFetching: boolean;\n /** Query error if any */\n error: Error | null;\n /** Function to fetch the next page */\n fetchNextPage: () => Promise<void>;\n /** Whether there are more pages to load */\n hasNextPage: boolean;\n /** Whether currently fetching the next page */\n isFetchingNextPage: boolean;\n /** Total count of items (if available) */\n count?: number;\n /** Refetch all pages */\n refetch: () => Promise<void>;\n}\n\n/**\n * Internal page result type\n */\ninterface PageResult<T> {\n data: T[];\n count?: number;\n}\n\n// =============================================================================\n// Helper Functions\n// =============================================================================\n\n/**\n * Build a query key for React Query infinite queries\n */\nfunction buildInfiniteQueryKey(table: string, options: UseDbInfiniteQueryOptions): unknown[] {\n return [\"v3\", \"infinite-query\", table, options.select ?? \"*\", JSON.stringify(options.where ?? {}), JSON.stringify(options.orderBy ?? []), options.pageSize ?? 50, options.searchText ?? \"\", JSON.stringify(options.searchFields ?? [])];\n}\n\n/**\n * Serialize query options for dependency tracking\n */\nfunction serializeInfiniteQueryOptions(options: UseDbInfiniteQueryOptions): string {\n return JSON.stringify({\n select: options.select,\n where: options.where,\n orderBy: options.orderBy,\n pageSize: options.pageSize,\n searchText: options.searchText,\n searchFields: options.searchFields\n });\n}\n\n/**\n * Helper to resolve table name from TableIdentifier\n */\nfunction resolveTableName(table: TableIdentifier): string {\n if (typeof table === \"string\") {\n return table;\n }\n return `${table.schema}.${table.table}`;\n}\n\n/**\n * Build search where clause from searchText and searchFields\n */\nfunction buildSearchWhereClause(searchText: string, searchFields: string[], existingWhere?: WhereClause): WhereClause {\n const searchWhere: WhereClause = {};\n if (searchFields.length === 1) {\n searchWhere[searchFields[0]] = {\n like: `%${searchText}%`\n };\n } else if (searchFields.length > 1) {\n searchWhere[searchFields[0]] = {\n like: `%${searchText}%`\n };\n }\n return {\n ...existingWhere,\n ...searchWhere\n };\n}\n\n// =============================================================================\n// Hook Implementation\n// =============================================================================\n\n/**\n * Hook for querying records with infinite scroll pagination\n *\n * @param table - Table name (string) or { schema, table } object\n * @param options - Query options (select, where, orderBy, pageSize, searchText, etc.)\n * @returns Query result with data, loading states, pagination controls, and refetch function\n *\n * @example\n * // Basic infinite query - types auto-inferred from table name\n * const { data, fetchNextPage, hasNextPage } = useDbInfiniteQuery(\"EquipmentFixtureUnit\");\n *\n * @example\n * // With search and pagination\n * const { data, fetchNextPage, hasNextPage, isFetchingNextPage } = useDbInfiniteQuery(\"Task\", {\n * pageSize: 20,\n * searchText: searchQuery,\n * searchFields: [\"name\", \"description\"],\n * orderBy: [{ field: \"createdAt\", direction: \"desc\" }],\n * });\n *\n * @example\n * // In a FlatList or similar\n * <FlatList\n * data={data}\n * onEndReached={() => hasNextPage && fetchNextPage()}\n * ListFooterComponent={isFetchingNextPage ? <Spinner /> : null}\n * />\n */\nexport function useDbInfiniteQuery<T extends TableIdentifier>(table: T, options?: UseDbInfiniteQueryOptions): UseDbInfiniteQueryResult<ResolveRowType<T>>;\n\n/**\n * Overload for explicit type parameter (backwards compatibility)\n */\nexport function useDbInfiniteQuery<T>(table: string, options?: UseDbInfiniteQueryOptions): UseDbInfiniteQueryResult<T>;\nexport function useDbInfiniteQuery<T>(table: TableIdentifier, options: UseDbInfiniteQueryOptions = {}): UseDbInfiniteQueryResult<T> {\n const tableName = resolveTableName(table);\n const {\n registry\n } = useDataLayerCore();\n const {\n enabled = true,\n staleTime = 30000,\n refetchOnWindowFocus = true,\n pageSize = 50,\n searchText,\n searchFields,\n ...queryOptions\n } = options;\n\n // Get adapter for this table\n // No isInitialized check needed - if we get here, core context exists = initialized\n const adapter = useMemo(() => {\n try {\n return registry.getAdapter(tableName);\n } catch {\n return null;\n }\n }, [registry, tableName]);\n\n // Serialize options for stable dependency tracking\n const serializedOptions = useMemo(() => serializeInfiniteQueryOptions(options), [options.select, options.where, options.orderBy, options.pageSize, options.searchText, options.searchFields]);\n\n // Build query key\n const queryKey = useMemo(() => buildInfiniteQueryKey(tableName, options), [tableName, serializedOptions]);\n\n // Build the where clause including search conditions\n const effectiveWhere = useMemo(() => {\n if (searchText && searchFields && searchFields.length > 0) {\n return buildSearchWhereClause(searchText, searchFields, queryOptions.where);\n }\n return queryOptions.where;\n }, [searchText, searchFields, queryOptions.where]);\n\n // Memoize base query options\n const memoizedQueryOptions = useMemo(() => ({\n select: queryOptions.select,\n where: effectiveWhere,\n orderBy: queryOptions.orderBy\n }), [queryOptions.select, effectiveWhere, queryOptions.orderBy]);\n\n // Execute infinite query with React Query\n const infiniteQuery = useInfiniteQuery<PageResult<T>, Error, InfiniteData<PageResult<T>, number>, unknown[], number>({\n queryKey,\n queryFn: async ({\n pageParam\n }) => {\n if (!adapter) {\n throw new Error(`Adapter not available for table: ${tableName}`);\n }\n const offset = (pageParam - 1) * pageSize;\n const result = await adapter.query<T>(tableName, {\n ...memoizedQueryOptions,\n limit: pageSize,\n offset\n });\n return {\n data: result.data ?? [],\n count: result.count\n };\n },\n initialPageParam: 1,\n getNextPageParam: (lastPage, allPages) => {\n const totalLoaded = allPages.reduce((sum, page) => sum + page.data.length, 0);\n const totalCount = lastPage.count;\n if (totalCount !== undefined && totalLoaded >= totalCount) {\n return undefined;\n }\n if (lastPage.data.length < pageSize) {\n return undefined;\n }\n return allPages.length + 1;\n },\n enabled: enabled && adapter !== null,\n staleTime,\n refetchOnWindowFocus\n });\n\n // Flatten all pages into a single data array\n const flattenedData = useMemo(() => {\n if (!infiniteQuery.data?.pages) return undefined;\n return infiniteQuery.data.pages.flatMap(page_0 => page_0.data);\n }, [infiniteQuery.data?.pages]);\n\n // Get total count from the last page\n const count = useMemo(() => {\n if (!infiniteQuery.data?.pages || infiniteQuery.data.pages.length === 0) {\n return undefined;\n }\n return infiniteQuery.data.pages[infiniteQuery.data.pages.length - 1].count;\n }, [infiniteQuery.data?.pages]);\n\n // Build fetchNextPage function\n const fetchNextPage = useCallback(async () => {\n await infiniteQuery.fetchNextPage();\n }, [infiniteQuery]);\n\n // Build refetch function\n const refetch = useCallback(async () => {\n await infiniteQuery.refetch();\n }, [infiniteQuery]);\n\n // Dev logging for debugging\n useEffect(() => {\n const adapterName = adapter?.name ?? \"unknown\";\n\n // Log errors\n if (infiniteQuery.isError && infiniteQuery.error) {\n devWarn(\"useDbInfiniteQuery\", `${tableName} via ${adapterName}: Error - ${infiniteQuery.error.message}`);\n }\n\n // Log empty results (only after successful fetch, not during loading)\n if (infiniteQuery.isSuccess && flattenedData?.length === 0) {\n devLog(\"useDbInfiniteQuery\", `${tableName} via ${adapterName}: 0 results`);\n }\n }, [infiniteQuery.isError, infiniteQuery.error, infiniteQuery.isSuccess, flattenedData, tableName, adapter]);\n return {\n data: flattenedData,\n isLoading: infiniteQuery.isLoading,\n isPending: infiniteQuery.isPending,\n isFetching: infiniteQuery.isFetching,\n error: infiniteQuery.error as Error | null,\n fetchNextPage,\n hasNextPage: infiniteQuery.hasNextPage ?? false,\n isFetchingNextPage: infiniteQuery.isFetchingNextPage,\n count,\n refetch\n };\n}\nexport default useDbInfiniteQuery;","import { c as _c } from \"react/compiler-runtime\";\n/**\n * V3 useDbCount Hook\n *\n * React hook for counting records in a table.\n * Works with the data layer using either PowerSync or Supabase backend.\n */\n\nimport { useMemo, useCallback, useEffect } from \"react\";\nimport { useQuery } from \"@tanstack/react-query\";\nimport { useDataLayerCore } from \"./useDataLayer\";\nimport type { WhereClause } from \"../core/types\";\nimport { devWarn } from \"../utils/dev-log\";\n\n// =============================================================================\n// Types\n// =============================================================================\n\n/**\n * Options for useDbCount hook\n */\nexport interface UseDbCountOptions {\n /** Filter conditions */\n where?: WhereClause;\n /** Whether the query is enabled (default: true) */\n enabled?: boolean;\n /** React Query stale time in ms (default: 30000) */\n staleTime?: number;\n}\n\n/**\n * Result from useDbCount hook\n */\nexport interface UseDbCountResult {\n /** The count value */\n count: number | undefined;\n /** Whether query is loading */\n isLoading: boolean;\n /** Whether query is fetching */\n isFetching: boolean;\n /** Query error if any */\n error: Error | null;\n /** Refetch the count */\n refetch: () => Promise<void>;\n}\n\n// =============================================================================\n// Hook Implementation\n// =============================================================================\n\n/**\n * Hook for counting records in a table\n *\n * @param table - The table name to count\n * @param options - Count options (where filter, enabled)\n * @returns Count result with loading states\n *\n * @example\n * // Simple count\n * const { count, isLoading } = useDbCount(\"EquipmentFixtureUnit\");\n *\n * @example\n * // Count with filter\n * const { count } = useDbCount(\"EquipmentFixtureUnit\", {\n * where: { projectDatabaseId: 123 },\n * });\n */\nexport function useDbCount(table, t0) {\n const $ = _c(37);\n let t1;\n if ($[0] !== t0) {\n t1 = t0 === undefined ? {} : t0;\n $[0] = t0;\n $[1] = t1;\n } else {\n t1 = $[1];\n }\n const options = t1;\n const {\n registry\n } = useDataLayerCore();\n const {\n enabled: t2,\n staleTime: t3,\n where\n } = options;\n const enabled = t2 === undefined ? true : t2;\n const staleTime = t3 === undefined ? 30000 : t3;\n let t4;\n try {\n let t5;\n if ($[2] !== registry || $[3] !== table) {\n t5 = registry.getAdapter(table);\n $[2] = registry;\n $[3] = table;\n $[4] = t5;\n } else {\n t5 = $[4];\n }\n t4 = t5;\n } catch {\n t4 = null;\n }\n const adapter = t4;\n let t5;\n if ($[5] !== where) {\n t5 = JSON.stringify(where ?? {});\n $[5] = where;\n $[6] = t5;\n } else {\n t5 = $[6];\n }\n let t6;\n if ($[7] !== t5 || $[8] !== table) {\n t6 = [\"v3\", \"count\", table, t5];\n $[7] = t5;\n $[8] = table;\n $[9] = t6;\n } else {\n t6 = $[9];\n }\n const queryKey = t6;\n let t7;\n if ($[10] !== adapter || $[11] !== table || $[12] !== where) {\n t7 = async () => {\n if (!adapter) {\n throw new Error(`Adapter not available for table: ${table}`);\n }\n const result = await adapter.query(table, {\n where,\n select: \"id\"\n });\n return result.count ?? result.data.length;\n };\n $[10] = adapter;\n $[11] = table;\n $[12] = where;\n $[13] = t7;\n } else {\n t7 = $[13];\n }\n const queryFn = t7;\n const t8 = enabled && adapter !== null;\n let t9;\n if ($[14] !== queryFn || $[15] !== queryKey || $[16] !== staleTime || $[17] !== t8) {\n t9 = {\n queryKey,\n queryFn,\n enabled: t8,\n staleTime\n };\n $[14] = queryFn;\n $[15] = queryKey;\n $[16] = staleTime;\n $[17] = t8;\n $[18] = t9;\n } else {\n t9 = $[18];\n }\n const query = useQuery(t9);\n let t10;\n if ($[19] !== adapter?.name || $[20] !== query.error || $[21] !== query.isError || $[22] !== table) {\n t10 = () => {\n if (query.isError && query.error) {\n const adapterName = adapter?.name ?? \"unknown\";\n devWarn(\"useDbCount\", `${table} via ${adapterName}: Error - ${query.error.message}`);\n }\n };\n $[19] = adapter?.name;\n $[20] = query.error;\n $[21] = query.isError;\n $[22] = table;\n $[23] = t10;\n } else {\n t10 = $[23];\n }\n let t11;\n if ($[24] !== adapter || $[25] !== query.error || $[26] !== query.isError || $[27] !== table) {\n t11 = [query.isError, query.error, table, adapter];\n $[24] = adapter;\n $[25] = query.error;\n $[26] = query.isError;\n $[27] = table;\n $[28] = t11;\n } else {\n t11 = $[28];\n }\n useEffect(t10, t11);\n let t12;\n if ($[29] !== query) {\n t12 = async () => {\n await query.refetch();\n };\n $[29] = query;\n $[30] = t12;\n } else {\n t12 = $[30];\n }\n const refetch = t12;\n const t13 = query.error as Error | null;\n let t14;\n if ($[31] !== query.data || $[32] !== query.isFetching || $[33] !== query.isLoading || $[34] !== refetch || $[35] !== t13) {\n t14 = {\n count: query.data,\n isLoading: query.isLoading,\n isFetching: query.isFetching,\n error: t13,\n refetch\n };\n $[31] = query.data;\n $[32] = query.isFetching;\n $[33] = query.isLoading;\n $[34] = refetch;\n $[35] = t13;\n $[36] = t14;\n } else {\n t14 = $[36];\n }\n return t14;\n}\nexport default useDbCount;","import { c as _c } from \"react/compiler-runtime\";\n/**\n * V3 useSyncStatus Hook\n *\n * Provides sync status information from the data layer.\n * Returns default \"always synced\" status when PowerSync is not available.\n *\n * Uses the split context architecture for optimal performance.\n */\n\nimport { useState, useEffect, useContext } from \"react\";\nimport { DataLayerStatusContext, DataLayerCoreContext } from \"../providers/DataLayerContext\";\nimport type { SyncStatus } from \"../core/types\";\n\n/**\n * Default sync status when PowerSync is not available\n */\nconst defaultSyncStatus: SyncStatus = {\n isConnected: true,\n // Supabase-only mode is always \"connected\" when online\n isSyncing: false,\n lastSyncedAt: null,\n pendingUploads: 0,\n error: null\n};\n\n/**\n * Hook to get the current sync status\n *\n * When PowerSync is not available, returns a default \"always synced\" status.\n *\n * This hook uses the split context architecture - it only subscribes to\n * status changes, not core value changes.\n *\n * @example\n * const { isSyncing, pendingUploads, isConnected } = useSyncStatus();\n *\n * if (pendingUploads > 0) {\n * console.log(`${pendingUploads} changes waiting to sync`);\n * }\n */\nexport function useSyncStatus() {\n const $ = _c(6);\n const statusContext = useContext(DataLayerStatusContext);\n const coreContext = useContext(DataLayerCoreContext);\n if (!statusContext || !coreContext) {\n throw new Error(\"useSyncStatus must be used within a DataLayerProvider. Make sure you have wrapped your app with <DataLayerProvider>.\");\n }\n const {\n syncStatus,\n status\n } = statusContext;\n const {\n powerSync\n } = coreContext;\n const [currentStatus, setCurrentStatus] = useState(syncStatus);\n let t0;\n let t1;\n if ($[0] !== powerSync || $[1] !== status.currentBackend || $[2] !== status.isOnline || $[3] !== syncStatus) {\n t0 = () => {\n if (powerSync && status.currentBackend === \"powersync\") {\n setCurrentStatus(syncStatus);\n } else {\n setCurrentStatus({\n ...defaultSyncStatus,\n isConnected: status.isOnline\n });\n }\n };\n t1 = [syncStatus, status.currentBackend, status.isOnline, powerSync];\n $[0] = powerSync;\n $[1] = status.currentBackend;\n $[2] = status.isOnline;\n $[3] = syncStatus;\n $[4] = t0;\n $[5] = t1;\n } else {\n t0 = $[4];\n t1 = $[5];\n }\n useEffect(t0, t1);\n return currentStatus;\n}\nexport default useSyncStatus;","import { c as _c } from \"react/compiler-runtime\";\n/**\n * V3 useSyncControl Hook\n *\n * Provides sync control functions from the data layer.\n * Returns no-op functions when PowerSync is not available.\n *\n * Uses the split context architecture for optimal performance.\n */\n\nimport { useMemo, useContext } from \"react\";\nimport { DataLayerCoreContext } from \"../providers/DataLayerContext\";\nimport type { SyncControl } from \"../core/types\";\n\n/**\n * Hook to get sync controls for PowerSync\n *\n * When PowerSync is not available, all methods are no-ops that log a warning.\n *\n * PERFORMANCE: This hook only subscribes to DataLayerCoreContext (stable values),\n * NOT DataLayerStatusContext. This means components using useSyncControl() will\n * NOT re-render when network status or sync status changes.\n *\n * @example\n * const { triggerSync, startLiveSync, stopLiveSync } = useSyncControl();\n *\n * // Manually trigger a sync\n * await triggerSync();\n *\n * // Start/stop live sync\n * await startLiveSync();\n * stopLiveSync();\n */\nexport function useSyncControl() {\n const $ = _c(1);\n const coreContext = useContext(DataLayerCoreContext);\n if (!coreContext) {\n throw new Error(\"useSyncControl must be used within a DataLayerProvider. Make sure you have wrapped your app with <DataLayerProvider>.\");\n }\n const {\n syncControl,\n powerSync\n } = coreContext;\n const isPowerSyncActive = powerSync !== null;\n let t0;\n if ($[0] === Symbol.for(\"react.memo_cache_sentinel\")) {\n t0 = {\n triggerSync: _temp,\n startLiveSync: _temp2,\n stopLiveSync: _temp3,\n setScope: _temp4,\n pauseAutoRetry: _temp5,\n resumeAutoRetry: _temp6,\n isAutoRetryPaused: false,\n addPendingMutation: _temp7,\n removePendingMutation: _temp8\n };\n $[0] = t0;\n } else {\n t0 = $[0];\n }\n const noOpControls = t0;\n let t1;\n bb0: {\n if (isPowerSyncActive) {\n t1 = syncControl;\n break bb0;\n }\n t1 = noOpControls;\n }\n const controls = t1;\n return controls;\n}\nfunction _temp8() {}\nfunction _temp7() {}\nfunction _temp6() {\n console.warn(\"[useSyncControl] resumeAutoRetry called but PowerSync is not available\");\n}\nfunction _temp5() {\n console.warn(\"[useSyncControl] pauseAutoRetry called but PowerSync is not available\");\n}\nasync function _temp4(_scopeName, _values) {\n console.warn(\"[useSyncControl] setScope called but PowerSync is not available\");\n}\nfunction _temp3() {\n console.warn(\"[useSyncControl] stopLiveSync called but PowerSync is not available\");\n}\nasync function _temp2() {\n console.warn(\"[useSyncControl] startLiveSync called but PowerSync is not available\");\n}\nasync function _temp() {\n console.warn(\"[useSyncControl] triggerSync called but PowerSync is not available\");\n}\nexport default useSyncControl;","import { c as _c } from \"react/compiler-runtime\";\n/**\n * V3 useOnlineStatus Hook\n *\n * Provides online/connection status information.\n * Uses DataLayerProvider's status as the SINGLE source of truth.\n *\n * On React Native: status.isOnline comes from PowerSync platform adapter (NetInfo)\n * On Web: status.isOnline comes from browser navigator.onLine\n */\n\nimport { useMemo } from \"react\";\nimport { useDataLayerCore, useDataLayerStatus } from \"./useDataLayer\";\n\n/**\n * Online status information\n */\nexport interface OnlineStatus {\n /** Whether the device has network connectivity */\n isOnline: boolean;\n /** Whether PowerSync is connected (false if using Supabase-only) */\n isConnected: boolean;\n /** Current backend being used */\n backend: \"powersync\" | \"supabase\" | null;\n}\n\n/**\n * Hook to get online/connection status\n *\n * Uses DataLayerProvider's status as the single source of truth:\n * - On React Native: isOnline comes from PowerSync platform adapter (NetInfo)\n * - On Web: isOnline comes from browser navigator.onLine\n *\n * @example\n * const { isOnline, isConnected, backend } = useOnlineStatus();\n *\n * if (!isOnline) {\n * return <OfflineBanner />;\n * }\n */\nexport function useOnlineStatus() {\n const $ = _c(4);\n const {\n powerSync\n } = useDataLayerCore();\n const {\n status\n } = useDataLayerStatus();\n const t0 = powerSync !== null && status.powerSyncStatus === \"available\";\n let t1;\n if ($[0] !== status.currentBackend || $[1] !== status.isOnline || $[2] !== t0) {\n t1 = {\n isOnline: status.isOnline,\n isConnected: t0,\n backend: status.currentBackend\n };\n $[0] = status.currentBackend;\n $[1] = status.isOnline;\n $[2] = t0;\n $[3] = t1;\n } else {\n t1 = $[3];\n }\n return t1;\n}\nexport default useOnlineStatus;"],"mappings":";;;;;;;;;;;;;;;;;AAQA,SAAS,aAAa,WAAW,eAAe;AAChD,SAAS,gBAAgB;AAiDzB,SAAS,cAAc,OAAe,IAAwC,QAA4B;AACxG,SAAO,CAAC,MAAM,aAAa,OAAO,IAAI,UAAU,GAAG;AACrD;AA+CO,SAAS,eAA4C,OAAe,IAAwC,UAAiC,CAAC,GAA4B;AAC/K,QAAM;AAAA,IACJ;AAAA,EACF,IAAI,iBAAiB;AACrB,QAAM;AAAA,IACJ;AAAA,IACA,UAAU,MAAM;AAAA,IAChB,YAAY;AAAA,EACd,IAAI;AAIJ,QAAM,UAAU,QAAQ,MAAM;AAC5B,QAAI;AACF,aAAO,SAAS,WAAW,KAAK;AAAA,IAClC,QAAQ;AACN,aAAO;AAAA,IACT;AAAA,EACF,GAAG,CAAC,UAAU,KAAK,CAAC;AAGpB,QAAM,WAAW,QAAQ,MAAM,cAAc,OAAO,IAAI,MAAM,GAAG,CAAC,OAAO,IAAI,MAAM,CAAC;AAGpF,QAAM,UAAU,YAAY,YAA+B;AACzD,QAAI,CAAC,SAAS;AACZ,YAAM,IAAI,MAAM,oCAAoC,KAAK,EAAE;AAAA,IAC7D;AACA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,wEAAwE;AACvF;AACA,SAAS,SAAS;AAChB,UAAQ,KAAK,uEAAuE;AACtF;AACA,eAAe,OAAO,YAAY,SAAS;AACzC,UAAQ,KAAK,iEAAiE;AAChF;AACA,SAAS,SAAS;AAChB,UAAQ,KAAK,qEAAqE;AACpF;AACA,eAAe,SAAS;AACtB,UAAQ,KAAK,sEAAsE;AACrF;AACA,eAAe,QAAQ;AACrB,UAAQ,KAAK,oEAAoE;AACnF;;;AC5FA,SAAS,KAAKC,WAAU;AAwCjB,SAAS,kBAAkB;AAChC,QAAM,IAAIC,IAAG,CAAC;AACd,QAAM;AAAA,IACJ;AAAA,EACF,IAAI,iBAAiB;AACrB,QAAM;AAAA,IACJ;AAAA,EACF,IAAI,mBAAmB;AACvB,QAAM,KAAK,cAAc,QAAQ,OAAO,oBAAoB;AAC5D,MAAI;AACJ,MAAI,EAAE,CAAC,MAAM,OAAO,kBAAkB,EAAE,CAAC,MAAM,OAAO,YAAY,EAAE,CAAC,MAAM,IAAI;AAC7E,SAAK;AAAA,MACH,UAAU,OAAO;AAAA,MACjB,aAAa;AAAA,MACb,SAAS,OAAO;AAAA,IAClB;AACA,MAAE,CAAC,IAAI,OAAO;AACd,MAAE,CAAC,IAAI,OAAO;AACd,MAAE,CAAC,IAAI;AACP,MAAE,CAAC,IAAI;AAAA,EACT,OAAO;AACL,SAAK,EAAE,CAAC;AAAA,EACV;AACA,SAAO;AACT;","names":["useCallback","useMemo","useEffect","useQuery","useMemo","useCallback","useQuery","result","useEffect","_c","useMutation","useQueryClient","_c","useQueryClient","t9","useMutation","_c","useMutation","useQueryClient","_c","useQueryClient","useMutation","_c","useMutation","useQueryClient","_c","useQueryClient","t9","useMutation","useMemo","useCallback","useEffect","useMemo","useCallback","useEffect","_c","useEffect","useQuery","_c","t5","useQuery","useEffect","_c","useState","useEffect","_c","useState","useEffect","_c","useContext","_c","useContext","_c","_c"]}
|
|
@@ -3,12 +3,12 @@ import {
|
|
|
3
3
|
createAdapterRegistry,
|
|
4
4
|
createSupabaseAdapter,
|
|
5
5
|
stripSchemaPrefix
|
|
6
|
-
} from "./chunk-
|
|
6
|
+
} from "./chunk-HFIGNQ7T.js";
|
|
7
7
|
import {
|
|
8
8
|
DataLayerContext,
|
|
9
9
|
DataLayerCoreContext,
|
|
10
10
|
DataLayerStatusContext
|
|
11
|
-
} from "./chunk-
|
|
11
|
+
} from "./chunk-UBHORKBS.js";
|
|
12
12
|
import {
|
|
13
13
|
QueryExecutor,
|
|
14
14
|
extractRelationNames,
|
|
@@ -4952,4 +4952,4 @@ object-assign/index.js:
|
|
|
4952
4952
|
@license MIT
|
|
4953
4953
|
*)
|
|
4954
4954
|
*/
|
|
4955
|
-
//# sourceMappingURL=chunk-
|
|
4955
|
+
//# sourceMappingURL=chunk-QHXN6BNL.js.map
|
|
@@ -1,15 +1,15 @@
|
|
|
1
1
|
import {
|
|
2
2
|
useDbUpsert
|
|
3
|
-
} from "./chunk-
|
|
3
|
+
} from "./chunk-NP34C3O3.js";
|
|
4
4
|
import {
|
|
5
5
|
UserMetadata
|
|
6
6
|
} from "./chunk-SM73S2DY.js";
|
|
7
7
|
import {
|
|
8
8
|
useSetupAuth
|
|
9
|
-
} from "./chunk-
|
|
9
|
+
} from "./chunk-7NFMEDJW.js";
|
|
10
10
|
import {
|
|
11
11
|
useDbQuery
|
|
12
|
-
} from "./chunk-
|
|
12
|
+
} from "./chunk-YQUNORJD.js";
|
|
13
13
|
import {
|
|
14
14
|
useSupabase
|
|
15
15
|
} from "./chunk-DMVUEJG2.js";
|
|
@@ -467,4 +467,4 @@ export {
|
|
|
467
467
|
useSetUserMetadata,
|
|
468
468
|
useUserMetadataState
|
|
469
469
|
};
|
|
470
|
-
//# sourceMappingURL=chunk-
|
|
470
|
+
//# sourceMappingURL=chunk-U4BZKCBH.js.map
|
|
@@ -0,0 +1,215 @@
|
|
|
1
|
+
// src/providers/DataLayerContext.ts
|
|
2
|
+
import { createContext } from "react";
|
|
3
|
+
var DataLayerCoreContext = createContext(null);
|
|
4
|
+
DataLayerCoreContext.displayName = "DataLayerCoreContext";
|
|
5
|
+
var DataLayerStatusContext = createContext(null);
|
|
6
|
+
DataLayerStatusContext.displayName = "DataLayerStatusContext";
|
|
7
|
+
var DataLayerContext = createContext(null);
|
|
8
|
+
DataLayerContext.displayName = "DataLayerContext";
|
|
9
|
+
|
|
10
|
+
// src/hooks/useDataLayer.ts
|
|
11
|
+
import { useContext } from "react";
|
|
12
|
+
function useDataLayerCore() {
|
|
13
|
+
const context = useContext(DataLayerCoreContext);
|
|
14
|
+
if (!context) {
|
|
15
|
+
throw new Error("useDataLayerCore must be used within a DataLayerProvider. Make sure you have wrapped your app with <DataLayerProvider>.");
|
|
16
|
+
}
|
|
17
|
+
return context;
|
|
18
|
+
}
|
|
19
|
+
function useDataLayerCoreOptional() {
|
|
20
|
+
return useContext(DataLayerCoreContext);
|
|
21
|
+
}
|
|
22
|
+
function useDataLayerStatus() {
|
|
23
|
+
const context = useContext(DataLayerStatusContext);
|
|
24
|
+
if (!context) {
|
|
25
|
+
throw new Error("useDataLayerStatus must be used within a DataLayerProvider. Make sure you have wrapped your app with <DataLayerProvider>.");
|
|
26
|
+
}
|
|
27
|
+
return context;
|
|
28
|
+
}
|
|
29
|
+
function useDataLayer() {
|
|
30
|
+
const context = useContext(DataLayerContext);
|
|
31
|
+
if (!context) {
|
|
32
|
+
throw new Error("useDataLayer must be used within a DataLayerProvider. Make sure you have wrapped your app with <DataLayerProvider>.");
|
|
33
|
+
}
|
|
34
|
+
return context;
|
|
35
|
+
}
|
|
36
|
+
function useDataLayerOptional() {
|
|
37
|
+
return useContext(DataLayerContext);
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
// src/hooks/useDbQuery.ts
|
|
41
|
+
import { useMemo, useEffect, useCallback, useRef } from "react";
|
|
42
|
+
import { useQuery } from "@tanstack/react-query";
|
|
43
|
+
|
|
44
|
+
// src/utils/dev-log.ts
|
|
45
|
+
function devLog(prefix, message) {
|
|
46
|
+
if (typeof __DEV__ !== "undefined" && __DEV__) {
|
|
47
|
+
console.log(`[${prefix}] ${message}`);
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
function devWarn(prefix, message) {
|
|
51
|
+
if (typeof __DEV__ !== "undefined" && __DEV__) {
|
|
52
|
+
console.warn(`[${prefix}] ${message}`);
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
// src/hooks/useDbQuery.ts
|
|
57
|
+
function buildQueryKey(table, options) {
|
|
58
|
+
return ["v3", "query", table, options.select ?? "*", JSON.stringify(options.where ?? {}), JSON.stringify(options.orderBy ?? []), options.limit, options.offset];
|
|
59
|
+
}
|
|
60
|
+
function serializeQueryOptions(options) {
|
|
61
|
+
return JSON.stringify({
|
|
62
|
+
select: options.select,
|
|
63
|
+
where: options.where,
|
|
64
|
+
orderBy: options.orderBy,
|
|
65
|
+
limit: options.limit,
|
|
66
|
+
offset: options.offset
|
|
67
|
+
});
|
|
68
|
+
}
|
|
69
|
+
function resolveTableName(table) {
|
|
70
|
+
if (typeof table === "string") {
|
|
71
|
+
return table;
|
|
72
|
+
}
|
|
73
|
+
return `${table.schema}.${table.table}`;
|
|
74
|
+
}
|
|
75
|
+
function useDbQuery(table, options = {}) {
|
|
76
|
+
const tableName = typeof table === "string" ? table : resolveTableName(table);
|
|
77
|
+
const {
|
|
78
|
+
registry,
|
|
79
|
+
queryClient,
|
|
80
|
+
powerSync
|
|
81
|
+
} = useDataLayerCore();
|
|
82
|
+
const isPowerSync = powerSync !== null;
|
|
83
|
+
const {
|
|
84
|
+
enabled = true,
|
|
85
|
+
staleTime = isPowerSync ? 0 : 3e4,
|
|
86
|
+
gcTime = 3e5,
|
|
87
|
+
// 5 minutes - keep in memory for instant display while refetching
|
|
88
|
+
refetchOnWindowFocus = true,
|
|
89
|
+
refetchOnMount = isPowerSync ? "always" : true,
|
|
90
|
+
realtime = isPowerSync,
|
|
91
|
+
// Enable real-time subscriptions by default for PowerSync
|
|
92
|
+
...queryOptions
|
|
93
|
+
} = options;
|
|
94
|
+
const adapter = useMemo(() => {
|
|
95
|
+
try {
|
|
96
|
+
return registry.getAdapter(tableName);
|
|
97
|
+
} catch {
|
|
98
|
+
return null;
|
|
99
|
+
}
|
|
100
|
+
}, [registry, tableName]);
|
|
101
|
+
const serializedOptions = useMemo(() => serializeQueryOptions(options), [options.select, options.where, options.orderBy, options.limit, options.offset]);
|
|
102
|
+
const queryKey = useMemo(() => buildQueryKey(tableName, options), [tableName, serializedOptions]);
|
|
103
|
+
const memoizedQueryOptions = useMemo(() => ({
|
|
104
|
+
select: queryOptions.select,
|
|
105
|
+
where: queryOptions.where,
|
|
106
|
+
orderBy: queryOptions.orderBy,
|
|
107
|
+
limit: queryOptions.limit,
|
|
108
|
+
offset: queryOptions.offset
|
|
109
|
+
}), [serializedOptions]);
|
|
110
|
+
const queryFn = useCallback(async () => {
|
|
111
|
+
const currentAdapter = registry.getAdapter(tableName);
|
|
112
|
+
const result = await currentAdapter.query(tableName, memoizedQueryOptions);
|
|
113
|
+
return result;
|
|
114
|
+
}, [registry, tableName, memoizedQueryOptions]);
|
|
115
|
+
const query = useQuery({
|
|
116
|
+
queryKey,
|
|
117
|
+
queryFn,
|
|
118
|
+
enabled: enabled && adapter !== null,
|
|
119
|
+
staleTime,
|
|
120
|
+
gcTime,
|
|
121
|
+
refetchOnWindowFocus,
|
|
122
|
+
refetchOnMount
|
|
123
|
+
});
|
|
124
|
+
const invalidateTimeoutRef = useRef(null);
|
|
125
|
+
const debouncedInvalidate = useCallback(() => {
|
|
126
|
+
if (invalidateTimeoutRef.current) {
|
|
127
|
+
clearTimeout(invalidateTimeoutRef.current);
|
|
128
|
+
}
|
|
129
|
+
invalidateTimeoutRef.current = setTimeout(() => {
|
|
130
|
+
queryClient.invalidateQueries({
|
|
131
|
+
queryKey
|
|
132
|
+
});
|
|
133
|
+
}, 100);
|
|
134
|
+
}, [queryClient, queryKey]);
|
|
135
|
+
useEffect(() => {
|
|
136
|
+
return () => {
|
|
137
|
+
if (invalidateTimeoutRef.current) {
|
|
138
|
+
clearTimeout(invalidateTimeoutRef.current);
|
|
139
|
+
}
|
|
140
|
+
};
|
|
141
|
+
}, []);
|
|
142
|
+
useEffect(() => {
|
|
143
|
+
let currentAdapter_0;
|
|
144
|
+
try {
|
|
145
|
+
currentAdapter_0 = registry.getAdapter(tableName);
|
|
146
|
+
} catch {
|
|
147
|
+
return;
|
|
148
|
+
}
|
|
149
|
+
if (!realtime || !currentAdapter_0?.subscribe) {
|
|
150
|
+
return;
|
|
151
|
+
}
|
|
152
|
+
const isPowerSyncAdapter = currentAdapter_0.name === "powersync";
|
|
153
|
+
let isFirstCallback = isPowerSyncAdapter;
|
|
154
|
+
const unsubscribe = currentAdapter_0.subscribe(tableName, memoizedQueryOptions, (data) => {
|
|
155
|
+
if (isFirstCallback) {
|
|
156
|
+
isFirstCallback = false;
|
|
157
|
+
return;
|
|
158
|
+
}
|
|
159
|
+
const hasRelations = memoizedQueryOptions.select?.includes("(");
|
|
160
|
+
if (hasRelations) {
|
|
161
|
+
debouncedInvalidate();
|
|
162
|
+
} else {
|
|
163
|
+
queryClient.setQueryData(queryKey, {
|
|
164
|
+
data,
|
|
165
|
+
count: data.length
|
|
166
|
+
});
|
|
167
|
+
}
|
|
168
|
+
});
|
|
169
|
+
return () => {
|
|
170
|
+
unsubscribe?.();
|
|
171
|
+
};
|
|
172
|
+
}, [realtime, registry, tableName, memoizedQueryOptions, queryClient, queryKey, debouncedInvalidate]);
|
|
173
|
+
useEffect(() => {
|
|
174
|
+
const adapterName = adapter?.name ?? "unknown";
|
|
175
|
+
if (query.isError && query.error) {
|
|
176
|
+
devWarn("useDbQuery", `${tableName} via ${adapterName}: Error - ${query.error.message}`);
|
|
177
|
+
}
|
|
178
|
+
if (query.isSuccess && query.data?.data?.length === 0) {
|
|
179
|
+
devLog("useDbQuery", `${tableName} via ${adapterName}: 0 results`);
|
|
180
|
+
}
|
|
181
|
+
}, [query.isError, query.error, query.isSuccess, query.data, tableName, adapter]);
|
|
182
|
+
const refetch = useCallback(async () => {
|
|
183
|
+
await query.refetch();
|
|
184
|
+
}, [query]);
|
|
185
|
+
return {
|
|
186
|
+
data: query.data?.data,
|
|
187
|
+
isLoading: query.isLoading,
|
|
188
|
+
isPending: query.isPending,
|
|
189
|
+
isFetching: query.isFetching,
|
|
190
|
+
isRefetching: query.isFetching,
|
|
191
|
+
// Alias for V2 compatibility
|
|
192
|
+
isSuccess: query.isSuccess,
|
|
193
|
+
isError: query.isError,
|
|
194
|
+
error: query.error,
|
|
195
|
+
refetch,
|
|
196
|
+
count: query.data?.count,
|
|
197
|
+
isStale: query.isStale,
|
|
198
|
+
dataUpdatedAt: query.dataUpdatedAt ?? null
|
|
199
|
+
};
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
export {
|
|
203
|
+
DataLayerCoreContext,
|
|
204
|
+
DataLayerStatusContext,
|
|
205
|
+
DataLayerContext,
|
|
206
|
+
useDataLayerCore,
|
|
207
|
+
useDataLayerCoreOptional,
|
|
208
|
+
useDataLayerStatus,
|
|
209
|
+
useDataLayer,
|
|
210
|
+
useDataLayerOptional,
|
|
211
|
+
devLog,
|
|
212
|
+
devWarn,
|
|
213
|
+
useDbQuery
|
|
214
|
+
};
|
|
215
|
+
//# sourceMappingURL=chunk-UBHORKBS.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/providers/DataLayerContext.ts","../src/hooks/useDataLayer.ts","../src/hooks/useDbQuery.ts","../src/utils/dev-log.ts"],"sourcesContent":["/**\n * V3 Data Layer Context\n *\n * Defines the React context and types for the V3 data layer provider.\n * This context provides access to adapters, sync status, and core instances.\n *\n * PERFORMANCE OPTIMIZATION:\n * The context is split into two separate contexts to prevent unnecessary re-renders:\n * - DataLayerCoreContext: Stable values that don't change after initialization\n * - DataLayerStatusContext: Dynamic values that change during runtime\n *\n * The original DataLayerContext is kept for backward compatibility.\n */\n\nimport { createContext } from \"react\";\nimport type { SupabaseClient } from \"@supabase/supabase-js\";\nimport type { QueryClient } from \"@tanstack/react-query\";\nimport type { AdapterRegistry } from \"../adapters/registry\";\nimport type { PowerSyncDatabase } from \"../query/executor\";\nimport type { DatabaseSchema, SyncStatus, SyncControl } from \"../core/types\";\nimport type { BackendStatus, AutoDetectionResult } from \"../adapters/auto-detector\";\nimport type { TableDataAdapter } from \"../adapters/types\";\n\n// =============================================================================\n// Status Types\n// =============================================================================\n\n/**\n * Status of the data layer initialization\n */\nexport interface DataLayerStatus {\n /** Whether the data layer is fully initialized */\n isInitialized: boolean;\n /** Current active backend */\n currentBackend: \"powersync\" | \"supabase\" | null;\n /** PowerSync connection status */\n powerSyncStatus: BackendStatus;\n /** Whether device is online */\n isOnline: boolean;\n /** Last auto-detection result */\n lastDetection: AutoDetectionResult | null;\n /** Initialization error if any */\n error: Error | null;\n /** Whether initial sync has completed (from PowerSync) */\n hasSynced: boolean;\n}\n\n// =============================================================================\n// Split Context Types (Performance Optimization)\n// =============================================================================\n\n/**\n * STABLE core context - values that don't change after initialization\n *\n * Use useDataLayerCore() to access these values in query/mutation hooks\n * to avoid re-renders when sync status changes.\n */\nexport interface DataLayerCoreContextValue {\n /** Adapter registry for getting table adapters */\n registry: AdapterRegistry;\n /** Get adapter for a specific table (defaults to 'read' operation) */\n getAdapter: (table: string, operation?: 'read' | 'write') => TableDataAdapter;\n /** PowerSync database instance (null when not available) */\n powerSync: PowerSyncDatabase | null;\n /** Supabase client (always available) */\n supabase: SupabaseClient;\n /** React Query client */\n queryClient: QueryClient;\n /** Database schema */\n schema: DatabaseSchema;\n /** Sync controls (for PowerSync, no-op for Supabase-only) - stable reference */\n syncControl: SyncControl;\n}\n\n/**\n * DYNAMIC status context - values that change during runtime\n *\n * Use useDataLayerStatus() for UI components that display sync status,\n * online indicator, etc. Components using this WILL re-render when status changes.\n */\nexport interface DataLayerStatusContextValue {\n /** Current status */\n status: DataLayerStatus;\n /** Sync status (for PowerSync, no-op for Supabase-only) */\n syncStatus: SyncStatus;\n}\n\n// =============================================================================\n// Combined Context Value Type (Backward Compatibility)\n// =============================================================================\n\n/**\n * Context value for the data layer (combines core and status)\n *\n * @deprecated Prefer using useDataLayerCore() or useDataLayerStatus() for better performance.\n * This combined interface is kept for backward compatibility.\n */\nexport interface DataLayerContextValue {\n /** Adapter registry for getting table adapters */\n registry: AdapterRegistry;\n\n /** Get adapter for a specific table (defaults to 'read' operation) */\n getAdapter: (table: string, operation?: 'read' | 'write') => TableDataAdapter;\n\n /** PowerSync database instance (null when not available) */\n powerSync: PowerSyncDatabase | null;\n\n /** Supabase client (always available) */\n supabase: SupabaseClient;\n\n /** React Query client */\n queryClient: QueryClient;\n\n /** Database schema */\n schema: DatabaseSchema;\n\n /** Current status */\n status: DataLayerStatus;\n\n /** Sync status (for PowerSync, no-op for Supabase-only) */\n syncStatus: SyncStatus;\n\n /** Sync controls (for PowerSync, no-op for Supabase-only) */\n syncControl: SyncControl;\n}\n\n// =============================================================================\n// Context Creation\n// =============================================================================\n\n/**\n * STABLE Core context - values that don't change after initialization\n *\n * Use useDataLayerCore() hook to access. Components consuming this context\n * will NOT re-render when sync status or network status changes.\n */\nexport const DataLayerCoreContext = createContext<DataLayerCoreContextValue | null>(null);\nDataLayerCoreContext.displayName = \"DataLayerCoreContext\";\n\n/**\n * DYNAMIC Status context - values that change during runtime\n *\n * Use useDataLayerStatus() hook to access. Components consuming this context\n * WILL re-render when sync status or network status changes.\n */\nexport const DataLayerStatusContext = createContext<DataLayerStatusContextValue | null>(null);\nDataLayerStatusContext.displayName = \"DataLayerStatusContext\";\n\n/**\n * Combined data layer context (backward compatibility)\n *\n * @deprecated Prefer using DataLayerCoreContext or DataLayerStatusContext for better performance.\n * Provides access to the V3 data layer throughout the React component tree.\n * Must be accessed via the useDataLayer hook or similar consumer.\n */\nexport const DataLayerContext = createContext<DataLayerContextValue | null>(null);\nDataLayerContext.displayName = \"DataLayerContext\";","/**\n * V3 Data Layer Hooks\n *\n * Provides access to the V3 data layer context for components.\n * This module provides three hooks for different use cases:\n *\n * - useDataLayerCore(): Stable values only (registry, adapters, clients)\n * Use in query/mutation hooks to avoid re-renders on status changes.\n *\n * - useDataLayerStatus(): Dynamic values only (status, syncStatus, syncControl)\n * Use for UI components that display sync status, online indicator, etc.\n *\n * - useDataLayer(): Combined access (backward compatible)\n * Use when you need both core and status values.\n */\n\nimport { useContext } from \"react\";\nimport { DataLayerContext, DataLayerCoreContext, DataLayerStatusContext, type DataLayerContextValue, type DataLayerCoreContextValue, type DataLayerStatusContextValue } from \"../providers/DataLayerContext\";\n\n// =============================================================================\n// PERFORMANCE-OPTIMIZED HOOKS (Recommended)\n// =============================================================================\n\n/**\n * Hook to access ONLY the stable core values (registry, adapters, clients)\n *\n * PERFORMANCE BENEFIT: Components using this hook will NOT re-render when\n * network status or sync status changes. Use this in query/mutation hooks.\n *\n * Provides access to:\n * - registry: Adapter registry for getting table adapters\n * - getAdapter: Function to get adapter for a specific table\n * - powerSync: PowerSync database instance (null when not available)\n * - supabase: Supabase client (always available)\n * - queryClient: React Query client\n * - schema: Database schema\n *\n * @throws Error if used outside of DataLayerProvider\n *\n * @example\n * const { getAdapter, supabase } = useDataLayerCore();\n * const adapter = getAdapter(\"Task\");\n * // This component won't re-render on sync status changes\n */\nexport function useDataLayerCore() {\n const context = useContext(DataLayerCoreContext);\n if (!context) {\n throw new Error(\"useDataLayerCore must be used within a DataLayerProvider. Make sure you have wrapped your app with <DataLayerProvider>.\");\n }\n return context;\n}\n\n/**\n * Hook to access ONLY the STABLE core context (optional version).\n * Returns null if DataLayerProvider is not present, rather than throwing.\n * Use this when you need graceful fallback behavior.\n *\n * @example\n * const dataLayerCore = useDataLayerCoreOptional();\n * if (dataLayerCore) {\n * // Use V3 adapter pattern\n * } else {\n * // Fall back to Supabase\n * }\n */\nexport function useDataLayerCoreOptional() {\n return useContext(DataLayerCoreContext);\n}\n\n/**\n * Hook to access ONLY the dynamic status values\n *\n * PERFORMANCE BENEFIT: Only components that actually need status information\n * will re-render when status changes. Use for UI components that display\n * sync status, online indicator, pending uploads count, etc.\n *\n * Provides access to:\n * - status: Current initialization and connection status\n * - syncStatus: Sync status for PowerSync\n * - syncControl: Sync controls for PowerSync\n *\n * @throws Error if used outside of DataLayerProvider\n *\n * @example\n * const { status, syncStatus } = useDataLayerStatus();\n *\n * return (\n * <StatusBar\n * isOnline={status.isOnline}\n * pendingUploads={syncStatus.pendingUploads}\n * />\n * );\n */\nexport function useDataLayerStatus() {\n const context = useContext(DataLayerStatusContext);\n if (!context) {\n throw new Error(\"useDataLayerStatus must be used within a DataLayerProvider. Make sure you have wrapped your app with <DataLayerProvider>.\");\n }\n return context;\n}\n\n// =============================================================================\n// BACKWARD COMPATIBLE HOOKS\n// =============================================================================\n\n/**\n * Hook to access the V3 data layer context (combined core + status)\n *\n * NOTE: Consider using useDataLayerCore() or useDataLayerStatus() instead\n * for better render performance. This hook re-renders on ALL status changes.\n *\n * Provides access to:\n * - registry: Adapter registry for getting table adapters\n * - getAdapter: Function to get adapter for a specific table\n * - powerSync: PowerSync database instance (null when not available)\n * - supabase: Supabase client (always available)\n * - queryClient: React Query client\n * - schema: Database schema\n * - status: Current initialization and connection status\n * - syncStatus: Sync status for PowerSync\n * - syncControl: Sync controls for PowerSync\n *\n * @throws Error if used outside of DataLayerProvider\n *\n * @example\n * const { getAdapter, status } = useDataLayer();\n *\n * if (status.isInitialized) {\n * const adapter = getAdapter(\"Task\");\n * // Use adapter...\n * }\n */\nexport function useDataLayer() {\n const context = useContext(DataLayerContext);\n if (!context) {\n throw new Error(\"useDataLayer must be used within a DataLayerProvider. Make sure you have wrapped your app with <DataLayerProvider>.\");\n }\n return context;\n}\n\n/**\n * Hook to safely access data layer context (returns null if not in provider)\n *\n * Use this when you need to check if the data layer is available\n * without throwing an error. Useful for conditional rendering or\n * components that may be rendered outside the provider context.\n *\n * @example\n * const dataLayer = useDataLayerOptional();\n *\n * if (dataLayer) {\n * // Safe to use data layer\n * } else {\n * // Render fallback UI\n * }\n */\nexport function useDataLayerOptional() {\n return useContext(DataLayerContext);\n}\nexport default useDataLayer;","/**\n * V3 useDbQuery Hook\n *\n * React hook for querying multiple records from a table.\n * Works identically whether PowerSync or Supabase is the backend.\n * Uses React Query for state management and caching.\n *\n * Types are automatically inferred from table names when you augment\n * the DatabaseTypes interface with your app's Database type.\n *\n * @example\n * // In your app's types/db.d.ts:\n * declare module \"@pol-studios/db\" {\n * interface DatabaseTypes {\n * database: import(\"@/database.types\").Database;\n * }\n * }\n *\n * // Then usage auto-infers types:\n * const { data } = useDbQuery(\"EquipmentFixtureUnit\", { ... });\n * // data is typed as Tables<\"EquipmentFixtureUnit\">[]\n */\n\nimport { useMemo, useEffect, useCallback, useRef } from \"react\";\nimport { useQuery } from \"@tanstack/react-query\";\nimport { useDataLayerCore } from \"./useDataLayer\";\nimport type { QueryOptions } from \"../core/types\";\nimport { devLog, devWarn } from \"../utils/dev-log\";\n\n// =============================================================================\n// Module Augmentation Interface\n// =============================================================================\n\n/**\n * Augment this interface in your app to enable automatic type inference.\n *\n * @example\n * // In types/db.d.ts\n * declare module \"@pol-studios/db\" {\n * interface DatabaseTypes {\n * database: import(\"@/database.types\").Database;\n * }\n * }\n */\n// eslint-disable-next-line @typescript-eslint/no-empty-interface\nexport interface DatabaseTypes {}\n\n// =============================================================================\n// Database Type Helpers\n// =============================================================================\n\n/**\n * The configured Database type, or a generic fallback\n */\ntype ConfiguredDatabase = DatabaseTypes extends {\n database: infer DB;\n} ? DB : GenericSchema;\n\n/**\n * Generic schema structure for fallback\n */\ntype GenericSchema = {\n public: {\n Tables: Record<string, {\n Row: Record<string, unknown>;\n }>;\n Views: Record<string, {\n Row: Record<string, unknown>;\n }>;\n };\n [schema: string]: {\n Tables: Record<string, {\n Row: Record<string, unknown>;\n }>;\n Views?: Record<string, {\n Row: Record<string, unknown>;\n }>;\n };\n};\n\n/**\n * Default schema from Database (usually \"public\")\n */\ntype DefaultSchema = ConfiguredDatabase extends {\n public: infer S;\n} ? S : never;\n\n/**\n * Extract all valid table names from the default schema\n */\nexport type PublicTableNames = DefaultSchema extends {\n Tables: infer T;\n} ? keyof T & string : string;\n\n/**\n * Extract all valid schema names\n */\nexport type SchemaNames = keyof ConfiguredDatabase & string;\n\n/**\n * Extract table names for a specific schema\n */\nexport type SchemaTableNames<S extends string> = ConfiguredDatabase extends { [K in S]: {\n Tables: infer T;\n} } ? keyof T & string : string;\n\n/**\n * Build dot notation strings for all schema.table combinations\n */\ntype SchemaDotTable = { [S in SchemaNames]: S extends \"public\" ? never // Skip public schema for dot notation\n: `${S}.${SchemaTableNames<S>}` }[SchemaNames];\n\n/**\n * Table identifier - provides autocomplete for valid table names\n *\n * Supports:\n * - \"TableName\" - public schema tables\n * - \"schema.TableName\" - dot notation for other schemas\n * - { schema, table } - object format for other schemas\n */\nexport type TableIdentifier = PublicTableNames | SchemaDotTable | { [S in Exclude<SchemaNames, \"public\">]: {\n schema: S;\n table: SchemaTableNames<S>;\n} }[Exclude<SchemaNames, \"public\">];\n\n/**\n * Resolve row type from a table identifier\n *\n * Supports:\n * - \"TableName\" → public schema\n * - \"schema.TableName\" → specified schema (dot notation)\n * - { schema: \"schema\", table: \"TableName\" } → specified schema (object)\n */\nexport type ResolveRowType<T extends TableIdentifier> = T extends string ?\n// Check for dot notation first (e.g., \"core.Profile\")\nT extends `${infer Schema}.${infer Table}` ? ConfiguredDatabase extends { [K in Schema]: {\n Tables: { [K2 in Table]: {\n Row: infer R;\n } };\n} } ? R : Record<string, unknown> :\n// Plain string - look in public schema\nDefaultSchema extends {\n Tables: { [K in T]: {\n Row: infer R;\n } };\n} ? R : DefaultSchema extends {\n Views: { [K in T]: {\n Row: infer R;\n } };\n} ? R : Record<string, unknown> : T extends {\n schema: infer S;\n table: infer TN;\n} ?\n// Object with schema - look in specified schema\nS extends string ? TN extends string ? ConfiguredDatabase extends { [K in S]: {\n Tables: { [K2 in TN]: {\n Row: infer R;\n } };\n} } ? R : Record<string, unknown> : Record<string, unknown> : Record<string, unknown> : Record<string, unknown>;\n\n// =============================================================================\n// Types\n// =============================================================================\n\n/**\n * Options for useDbQuery hook\n */\nexport interface UseDbQueryOptions extends Omit<QueryOptions, \"enabled\"> {\n /** Whether the query is enabled (default: true) */\n enabled?: boolean;\n /**\n * React Query stale time in ms\n * Default depends on backend:\n * - PowerSync (offline): 0 - always refetch from SQLite (disk is fast)\n * - Supabase (online): 30000 - use normal caching\n */\n staleTime?: number;\n /** React Query gcTime (cache time) in ms (default: 300000 - 5 minutes) */\n gcTime?: number;\n /** Whether to refetch on window focus (default: true) */\n refetchOnWindowFocus?: boolean;\n /**\n * Whether to refetch on mount\n * Default depends on backend:\n * - PowerSync (offline): \"always\" - always query SQLite\n * - Supabase (online): true - refetch if stale\n */\n refetchOnMount?: boolean | \"always\";\n /** Whether to enable real-time subscriptions (if adapter supports) */\n realtime?: boolean;\n /** If true, returns single item instead of array (for compatibility with V2) */\n single?: boolean;\n}\n\n/**\n * Result from useDbQuery hook\n */\nexport interface UseDbQueryResult<T> {\n /** Query data */\n data: T[] | undefined;\n /** Whether query is loading (initial load) */\n isLoading: boolean;\n /** Whether query is in pending state */\n isPending: boolean;\n /** Whether query is currently fetching (including refetch) */\n isFetching: boolean;\n /** Whether query is currently refetching (alias for isFetching for V2 compatibility) */\n isRefetching: boolean;\n /** Whether query completed successfully */\n isSuccess: boolean;\n /** Whether query errored */\n isError: boolean;\n /** Query error if any */\n error: Error | null;\n /** Refetch the query */\n refetch: () => Promise<void>;\n /** Total count (if pagination is used) */\n count?: number;\n /** Whether data is stale */\n isStale: boolean;\n /** Timestamp of last data update */\n dataUpdatedAt: number | null;\n}\n\n// =============================================================================\n// Helper Functions\n// =============================================================================\n\n/**\n * Build a query key for React Query\n *\n * Creates a stable, unique key for caching based on table and query options.\n * Keys are namespaced with \"v3\" to avoid collisions with V2 queries.\n *\n * NOTE: Backend is intentionally NOT included in the key. The data is the same\n * regardless of whether it comes from Supabase or PowerSync - switching backends\n * should NOT invalidate the cache. This is critical for offline-first UX.\n */\nfunction buildQueryKey(table: string, options: UseDbQueryOptions): unknown[] {\n return [\"v3\", \"query\", table, options.select ?? \"*\", JSON.stringify(options.where ?? {}), JSON.stringify(options.orderBy ?? []), options.limit, options.offset];\n}\n\n/**\n * Serialize query options for dependency tracking\n */\nfunction serializeQueryOptions(options: UseDbQueryOptions): string {\n return JSON.stringify({\n select: options.select,\n where: options.where,\n orderBy: options.orderBy,\n limit: options.limit,\n offset: options.offset\n });\n}\n\n// =============================================================================\n// Hook Implementation\n// =============================================================================\n\n/**\n * Helper to resolve table name from TableIdentifier\n */\nfunction resolveTableName(table: TableIdentifier): string {\n if (typeof table === \"string\") {\n return table;\n }\n return `${table.schema}.${table.table}`;\n}\n\n/**\n * Hook for querying multiple records from a table\n *\n * This hook provides a unified interface for querying data that works\n * identically whether the backend is PowerSync (offline-first) or\n * Supabase (online-only). It uses React Query for caching and state management.\n *\n * Features:\n * - Automatic type inference from table names (when DatabaseTypes is augmented)\n * - Automatic backend selection based on DataLayerProvider configuration\n * - React Query integration for caching, deduplication, and background updates\n * - Optional real-time subscriptions (when adapter supports it)\n * - Pagination support with count\n *\n * @param table - Table name (string) or { schema, table } object\n * @param options - Query options (select, where, orderBy, limit, offset, etc.)\n * @returns Query result with data, loading states, error, and refetch function\n *\n * @example\n * // Basic query - types auto-inferred from table name\n * const { data } = useDbQuery(\"EquipmentFixtureUnit\");\n * // data is typed as Tables<\"EquipmentFixtureUnit\">[]\n *\n * @example\n * // Query from non-public schema\n * const { data } = useDbQuery({ schema: \"core\", table: \"Profile\" });\n * // data is typed as Tables<{ schema: \"core\" }, \"Profile\">[]\n *\n * @example\n * // Query with filters and sorting\n * const { data } = useDbQuery(\"Task\", {\n * select: \"*, Project(*)\",\n * where: { status: \"active\" },\n * orderBy: [{ field: \"createdAt\", direction: \"desc\" }],\n * limit: 10,\n * });\n */\n/**\n * Main hook signature with auto-inferred types from table identifiers\n */\nexport function useDbQuery<T extends TableIdentifier>(table: T, options?: UseDbQueryOptions): UseDbQueryResult<ResolveRowType<T>>;\n\n/**\n * Overload for explicit type parameter when table name is a string literal\n */\nexport function useDbQuery<T>(table: string, options?: UseDbQueryOptions): UseDbQueryResult<T>;\n\n// Implementation signature - uses any to satisfy both overloads\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport function useDbQuery<T = any>(table: TableIdentifier | string, options: UseDbQueryOptions = {}): UseDbQueryResult<T> {\n const tableName = typeof table === \"string\" ? table : resolveTableName(table as TableIdentifier);\n const {\n registry,\n queryClient,\n powerSync\n } = useDataLayerCore();\n\n // Determine if using PowerSync (offline/SQLite) or Supabase (online)\n const isPowerSync = powerSync !== null;\n\n // Backend-aware defaults:\n // - PowerSync: staleTime=0, refetchOnMount=\"always\" (SQLite is fast, always query disk)\n // - Supabase: staleTime=30000, refetchOnMount=true (use normal React Query caching)\n // - realtime: PowerSync=true (use watch() for live updates), Supabase=false (no streaming)\n const {\n enabled = true,\n staleTime = isPowerSync ? 0 : 30000,\n gcTime = 300000,\n // 5 minutes - keep in memory for instant display while refetching\n refetchOnWindowFocus = true,\n refetchOnMount = isPowerSync ? \"always\" : true,\n realtime = isPowerSync,\n // Enable real-time subscriptions by default for PowerSync\n ...queryOptions\n } = options;\n\n // Get adapter for this table\n // No isInitialized check needed - if we get here, core context exists = initialized\n const adapter = useMemo(() => {\n try {\n return registry.getAdapter(tableName);\n } catch {\n return null;\n }\n }, [registry, tableName]);\n\n // Serialize options into a stable memoized value BEFORE using in other dependencies\n const serializedOptions = useMemo(() => serializeQueryOptions(options), [options.select, options.where, options.orderBy, options.limit, options.offset]);\n\n // Build query key - memoized to prevent unnecessary re-renders\n // Backend is NOT included - cache persists across backend switches for offline-first UX\n const queryKey = useMemo(() => buildQueryKey(tableName, options), [tableName, serializedOptions]);\n\n // Memoize query options to prevent re-creating on every render\n const memoizedQueryOptions = useMemo(() => ({\n select: queryOptions.select,\n where: queryOptions.where,\n orderBy: queryOptions.orderBy,\n limit: queryOptions.limit,\n offset: queryOptions.offset\n }), [serializedOptions]);\n\n // Query function - resolve adapter lazily at query time to ensure we always\n // have the latest adapter instance (the memoized adapter may be stale)\n const queryFn = useCallback(async () => {\n // Use currentAdapter directly - registry.getAdapter() throws if unavailable\n const currentAdapter = registry.getAdapter(tableName);\n const result = await currentAdapter.query(tableName, memoizedQueryOptions);\n return result;\n }, [registry, tableName, memoizedQueryOptions]);\n\n // Execute query with React Query\n // Backend-aware caching strategy:\n // - PowerSync: SQLite is source of truth, always refetch from disk (it's fast)\n // - Supabase: Use normal React Query caching to avoid unnecessary network requests\n const query = useQuery({\n queryKey,\n queryFn,\n enabled: enabled && adapter !== null,\n staleTime,\n gcTime,\n refetchOnWindowFocus,\n refetchOnMount\n });\n\n // Create debounced invalidation function for subscriptions\n const invalidateTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);\n const debouncedInvalidate = useCallback(() => {\n if (invalidateTimeoutRef.current) {\n clearTimeout(invalidateTimeoutRef.current);\n }\n invalidateTimeoutRef.current = setTimeout(() => {\n queryClient.invalidateQueries({\n queryKey\n });\n }, 100);\n }, [queryClient, queryKey]);\n\n // Clean up timeout on unmount\n useEffect(() => {\n return () => {\n if (invalidateTimeoutRef.current) {\n clearTimeout(invalidateTimeoutRef.current);\n }\n };\n }, []);\n\n // Set up real-time subscription if enabled\n useEffect(() => {\n // Resolve adapter lazily to get current backend\n let currentAdapter_0;\n try {\n currentAdapter_0 = registry.getAdapter(tableName);\n } catch {\n return; // Adapter not available yet\n }\n if (!realtime || !currentAdapter_0?.subscribe) {\n return;\n }\n\n // Only skip first callback for PowerSync adapter (which fires immediately with current data)\n // SupabaseAdapter's subscribe only fires on actual database changes\n // Use currentAdapter.name for the isFirstCallback check (survives minification)\n const isPowerSyncAdapter = currentAdapter_0.name === \"powersync\";\n let isFirstCallback = isPowerSyncAdapter;\n const unsubscribe = currentAdapter_0.subscribe(tableName, memoizedQueryOptions, data => {\n // Skip the first callback since initial query handles it\n if (isFirstCallback) {\n isFirstCallback = false;\n return;\n }\n\n // Check if query has relations (contains parentheses like \"Table(*)\")\n const hasRelations = memoizedQueryOptions.select?.includes(\"(\");\n if (hasRelations) {\n // Has relations - use debounced invalidation to prevent rapid successive invalidations\n debouncedInvalidate();\n } else {\n // No relations - safe to directly update cache with flat data\n queryClient.setQueryData(queryKey, {\n data,\n count: data.length\n });\n }\n });\n return () => {\n unsubscribe?.();\n };\n }, [realtime, registry, tableName, memoizedQueryOptions, queryClient, queryKey, debouncedInvalidate]);\n\n // Dev logging for debugging\n useEffect(() => {\n const adapterName = adapter?.name ?? \"unknown\";\n\n // Log errors\n if (query.isError && query.error) {\n devWarn(\"useDbQuery\", `${tableName} via ${adapterName}: Error - ${query.error.message}`);\n }\n\n // Log empty results (only after successful fetch, not during loading)\n if (query.isSuccess && query.data?.data?.length === 0) {\n devLog(\"useDbQuery\", `${tableName} via ${adapterName}: 0 results`);\n }\n }, [query.isError, query.error, query.isSuccess, query.data, tableName, adapter]);\n\n // Build refetch function\n const refetch = useCallback(async () => {\n await query.refetch();\n }, [query]);\n return {\n data: query.data?.data as T[] | undefined,\n isLoading: query.isLoading,\n isPending: query.isPending,\n isFetching: query.isFetching,\n isRefetching: query.isFetching,\n // Alias for V2 compatibility\n isSuccess: query.isSuccess,\n isError: query.isError,\n error: query.error as Error | null,\n refetch,\n count: query.data?.count,\n isStale: query.isStale,\n dataUpdatedAt: query.dataUpdatedAt ?? null\n };\n}\nexport default useDbQuery;","/**\n * Development-only logging utility for V3 hooks\n *\n * Logs are only output when __DEV__ is true (development builds).\n * In production builds, these calls are no-ops.\n */\n\ndeclare const __DEV__: boolean;\n\n/**\n * Log a message with a prefix, only in development\n *\n * @param prefix - Hook or component name (e.g., \"useDbQuery\")\n * @param message - Message to log\n *\n * @example\n * devLog(\"useDbQuery\", \"EquipmentUnit via PowerSync: 0 results\");\n * // Output: [useDbQuery] EquipmentUnit via PowerSync: 0 results\n */\nexport function devLog(prefix: string, message: string): void {\n if (typeof __DEV__ !== \"undefined\" && __DEV__) {\n console.log(`[${prefix}] ${message}`);\n }\n}\n\n/**\n * Log a warning with a prefix, only in development\n */\nexport function devWarn(prefix: string, message: string): void {\n if (typeof __DEV__ !== \"undefined\" && __DEV__) {\n console.warn(`[${prefix}] ${message}`);\n }\n}\n\n/**\n * Log an error with a prefix, only in development\n */\nexport function devError(prefix: string, message: string, error?: unknown): void {\n if (typeof __DEV__ !== \"undefined\" && __DEV__) {\n if (error) {\n console.error(`[${prefix}] ${message}`, error);\n } else {\n console.error(`[${prefix}] ${message}`);\n }\n }\n}"],"mappings":";AAcA,SAAS,qBAAqB;AA0HvB,IAAM,uBAAuB,cAAgD,IAAI;AACxF,qBAAqB,cAAc;AAQ5B,IAAM,yBAAyB,cAAkD,IAAI;AAC5F,uBAAuB,cAAc;AAS9B,IAAM,mBAAmB,cAA4C,IAAI;AAChF,iBAAiB,cAAc;;;AC5I/B,SAAS,kBAAkB;AA4BpB,SAAS,mBAAmB;AACjC,QAAM,UAAU,WAAW,oBAAoB;AAC/C,MAAI,CAAC,SAAS;AACZ,UAAM,IAAI,MAAM,yHAAyH;AAAA,EAC3I;AACA,SAAO;AACT;AAeO,SAAS,2BAA2B;AACzC,SAAO,WAAW,oBAAoB;AACxC;AA0BO,SAAS,qBAAqB;AACnC,QAAM,UAAU,WAAW,sBAAsB;AACjD,MAAI,CAAC,SAAS;AACZ,UAAM,IAAI,MAAM,2HAA2H;AAAA,EAC7I;AACA,SAAO;AACT;AAiCO,SAAS,eAAe;AAC7B,QAAM,UAAU,WAAW,gBAAgB;AAC3C,MAAI,CAAC,SAAS;AACZ,UAAM,IAAI,MAAM,qHAAqH;AAAA,EACvI;AACA,SAAO;AACT;AAkBO,SAAS,uBAAuB;AACrC,SAAO,WAAW,gBAAgB;AACpC;;;ACvIA,SAAS,SAAS,WAAW,aAAa,cAAc;AACxD,SAAS,gBAAgB;;;ACLlB,SAAS,OAAO,QAAgB,SAAuB;AAC5D,MAAI,OAAO,YAAY,e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