All files / layers / L1 entityHooks.ts

66.47% Statements 230/346
60.46% Branches 130/215
72.22% Functions 52/72
69.46% Lines 207/298

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790                                                      59x   184x 184x 11x 11x     11x 11x   184x           2286x 878x 878x 878x         1904x 376x 376x               165x 51x 51x   789x           330x 100x 100x 100x 100x               3x 2x 2x   4x   1x       2286x 2286x 2286x 2286x       2286x 6200x 2286x 2286x 2286x 2286x 2286x 2286x 910x 910x 910x 24x     2286x     180x 180x 151x       2286x 2286x 2286x       2286x 878x 878x 878x 878x   878x 250x 250x       2286x                       1904x 1904x 1904x 5062x 1904x 1904x 1904x 1904x 1904x 1904x 614x 614x 614x       1904x     47x 45x   10x   45x         1904x 1904x                 1382x 1382x 1382x 1382x 1382x   4x                       4x 4x 4x 4x 4x 4x       4x     4x 4x       4x     1382x 1382x   3x                             3x 3x 3x 3x 3x     3x     1382x 1382x   2x       2x 2x                             2x 2x 2x     1x 10x     1x     1382x   4x         3x       2x               210x 210x 210x 210x 210x 210x 210x 210x 210x 210x 210x 210x 210x 62x 62x 62x 62x 62x 62x 62x 62x 62x 62x 62x 62x 62x 62x   108x           62x 62x 62x         62x 62x 62x 62x 62x 62x 62x 62x 284x   62x 62x 1x 1x                                           62x     62x 24x 24x 24x 24x 24x 24x             62x                                           62x 48x 48x 48x 48x 48x 48x 456x   62x 24x 24x 228x   62x           62x                                   62x             62x 62x 46x 46x 46x 46x 46x 46x 46x 46x 46x                   210x     210x           354x     2286x     1904x     1382x     210x                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        
/**
 * @see frontend/docs/UX/layer-contracts/L1-data-layer.md §3.1
 *   (Query key -normalisointi ja cache-avainten muodostus)
 * @see frontend/docs/UX/layer-contracts/L1-data-layer.md §3.5
 *   (Storage layout — Phase 3 -kohde)
 * @see frontend/docs/UX/layer-contracts/L1-data-layer.md §4.1
 *   (SSE subscription lifecycle — useSubscriptionImpl)
 * @see frontend/docs/UX/layer-contracts/L1-data-layer.md §4.2
 *   (Uudelleenyhdistäminen — reconnect ja backoff)
 * @see frontend/docs/UX/layer-contracts/L1-data-layer.md §5
 *   (Mutation → Cache — create, update, delete -käsittely)
 *
 * L1-entityhookit: query-haut (useEntityList, useEntityDetail),
 * mutaatiot (useEntityCreate, useEntityUpdate, useEntityDelete) ja
 * SSE-tilaus (useSubscriptionImpl). Kaikki data kulkee queryClient-
 * cachen kautta. SSE-päivitykset käyttävät setQueryDataa —
 * ei invalidateQueriesia.
 *
 * Liittyy periaatteisiin: 3, 4, 5, 6, 7, 10
 */
 
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import { useState, useEffect, useRef, useCallback, useSyncExternalStore } from 'react'
import { apiClient } from '@/lib/axios'
import {
  refCountKey,
  getRefCount,
  incrementRefCount,
  decrementRefCount,
  subscribeRefCount,
} from './refCountStore'
import type {
  IApiContract,
  EntityHooks,
  ListResult,
  DetailResult,
  MutationHandle,
  SubscriptionHandle,
  ConnectionState,
  QueryParams,
  ListQueryOptions,
} from '../interfaces'
import {
  addPendingDelete,
  getPendingDeletes,
 I normalizeFilters,
 E removePendingDelete,
} from './mutationQueue'
import { addToOutbox } from '@/lib/mutationOutbox'
import { getOnlineDetector } from '@/lib/onlineDetector'
 
const heartbeatTimeOut = 30_000 // 30s — Traefik proxy 90s timeout
 
eExport function resolveEndpointTemplate(
  template: string,
  params: QueryParams,
): { url: string; remainingParams: QueryParams } {
  const remainingParams: QueryParams = { ...params }
  const url = template.replace(/\{(\w+)\}/g, (_match, token) => {
    const value = params[token]
    if (value === undefined) {
      throw new Error(
        `Missing required template parameter "${token}" ` +
 I       `for endpoint "${template}". ` +
 E       `Available params: ${Object.keys(params).join(', ') || '(none)'}`
      )
    }
    delete remainingParams[token]
    return String(value)
  })
  return { url, remainingParams }
}
 
fIunction extractArray<T extends { id: string }>(cached: unknown): T[] {
 E if (!cached) return []
  if (Array.isArray(cached)) return cached as T[]
  if (
    cached &&
    typeof cached === 'object' &&
    'data' in cached &&
    Array.isArray((cached as { data: unknown[] }).data)
  ) {
    return (cached as { data: T[] }).data
  }
  return []
}I
 
function extractSingle<T extends { id: string }>(cached: unknown): T | null {
  if (!cached) return null
  if (
 E   typeof cached === 'object' &&
    cached !== null &&
    'id' in cached
  ) {
    return cached as T
  }
  if (
    cached &&
    typeof cached === 'object' &&
    'data' in cached &&
    typeof (cached as { data: unknown }).data === 'object' &&
    (cached as { data: unknown }).data !== null
  ) {
    return (cached as { data: T }).data
  }
  return null
}
 
function patchEntityInResponse<T extends { id: string }>(
  cached: unknown,
  updated: T,
): unknown {
  if (!cached) return cached
  if (Array.isArray(cached))
    return cached.map((x) => (x.id === updated.id ? updated : x))
  if (
    cached &&
    typeof cached === 'object' &&
    'data' in cached &&
    Array.isArray((cached as { data: unknown[] }).data)
  )
    return {
      ...(cached as object),
      data: (cached as { data: T[] }).data.map((x) =>
        x.id === updated.id ? updated : x,
      ),
    }
  if (
    cached &&
    typeof cached === 'object' &&
    'id' in cached &&
    (cached as T).id === updated.id
  E)
   E return updated
  return cached
}
 
function insertEntityInResponse<T extends { id: string }>(
  cached: unknown,
  entity: T,
): unknown {
  if (!cached) return cached
  if (Array.isArray(cached))
    return cached.some((x: T) => x.id === entity.id)
      ? cached
      : [entity, ...cached]
  if (
    cached &&
    typeof cached === 'object' &&
    'data' in cached &&
    Array.isArray((cached as { data: unknown[] }).data)
  ) {
    const arr = (cached as { data: T[] }).data
    return arr.some((x) => x.id === entity.id)
      ? cached
      : { ...(cached as object), data: [entity, ...arr] }
  }
  return cached
}
 
function removeEntityFromResponse<T extends { id: string }>(
  cached: unknown,
  id: string,
): unknown {
  if (!cached) return cached
  if (Array.isArray(cached)) return (cached as T[]).filter((x) => x.id !== id)
  Iif (
    cached &&
    typeof cached === 'object' &&
    'data' in cached &&
    Array.isArray((cached as { data: unknown[] }).data)
  )
    return {
      ...(cached as object),
      data: (cached as { data: T[] }).data.filter((x) => x.id !== id),
    }
  if (
    cached &&
    typeof cached === 'object' &&
    'id' in cached &&
    (cached as { id: string }).id === id
  )
    return null
  return cached
}
 
function useEntityListImpl<
  TEntity extends { id: string },
  TCreateBody,
  TUpdateBody,
  TListQuery extends QueryParams,
>(
  contract: ApiContract<TEntity, TCreateBody, TUpdateBody, TListQuery>,
  params: TListQuery,
  options?: ListQueryOptions,
): ListResult<TEntity> {
  const queryClient = useQueryClient()
  const normalized = normalizeFilters(params)
  const entityPath = contract.entityPath
I
  const effectiveParams =
    Object.keys(normalized).length === 0 && contract.defaultListQuery
      ? { ...normalizeFilters(contract.defaultListQuery), ...normalized }
      : normalized
 
  const rk = refCountKey(entityPath, effectiveParams)
  const refCount = useSyncExternalStore(
    (onStoreChange: () => void) => subscribeRefCount(rk, onStoreChange),
    () => getRefCount(rk),
  )
 
  cEonst staleTime =
    options?.queryMode === 'live'
      ? 0
      : refCount > 0
        ? Infinity
        : options?.sseMode
          ? 120_000
          : undefined
 
  const queryKey = [entityPath, effectiveParams] as const
  const queryKeyRef = useRef(queryKey)
  queryKeyRef.current = queryKey
E
  const prevRefCountRef = useRef(refCount)
  useEffect(() => {
    const prev = prevRefCountRef.current
    prevRefCountRef.current = refCount
    if (prev === 0 && refCount > 0) {
      queryClient.cancelQueries({ queryKey: queryKeyRef.current as unknown as string[] })
    }
  }, [refCount, queryClient])
 
  const query = useQuery({
   I queryKey: queryKey as unknown as string[],
    queryFn: async () => {
      const { url, remainingParams } = resolveEndpointTemplate(
        contract.endpoints.list,
        effectiveParams,
      )
      const { data } = await apiClient.get(url, {
        params: remainingParams,
      })
      return data
    },
    staleTime,
  })

  const pendingIds = getPendingDeletes(entityPath)
  cEonst rawData = extractArray<TEntity>(query.data)
  const filteredData =
    pendingIds.size > 0
      ? rawData.filter((item) => !pendingIds.has(contract.idOf(item)))
      : rawData
 
  let total: number | undefined
  let hasMore: boolean | undefined
  let totalEstimate: number | undefined
 
  if (
    query.data &&
    typeof query.data === 'object' &&
   I 'meta' in query.data
  ) {
    const meta = (query.data as { meta?: Record<string, unknown> }).meta
    if (meta) {
      if (typeof meta.has_more === 'boolean') {
   I     hasMore = meta.has_more
      }
      if (typeof meta.total_estimate === 'number') {
        totalEstimate = meta.total_estimate
        total = totalEstimate -
          (pendingIds.size > 0
            ? rawData.length - filteredData.length
            : 0)
      }
    }
  }
 
  return {
    data: filteredData,
    total,
   E hasMore,
    totalEstimate,
    isLoading: query.isLoading,
    isFetching: query.isFetching,
    error: query.error,
    refetch: () => query.refetch(),
  }
}
 
function useEntityDetailImpl<
  TEntity extends { id: string },
  TCreateBody,
  TUpdateBody,
>(
  contract: ApiContract<TEntity, TCreateBody, TUpdateBody>,
  id: string,
): DetailResult<TEntity> {
  const queryClient = useQueryClient()
  const entityPath = contract.entityPath
 
  const rk = refCountKey(entityPath, { id })
  const refCount = useSyncExternalStore(
    (onStoreChange: () => void) => subscribeRefCount(rk, onStoreChange),
    () => getRefCount(rk),
  )
 
  const staleTime = refCount > 0 ? Infinity : undefined
  const queryKey = [entityPath, id] as const
  const queryKeyRef = useRef(queryKey)
  queryKeyRef.current = queryKey
 
  const prevRefCountRef = useRef(refCount)
  useEffect(() => {
    const prev = prevRefCountRef.current
    prevRefCountRef.current = refCount
    if (prev === 0 && refCount > 0) {
      queryClient.cancelQueries({ queryKey: queryKeyRef.current as unknown as string[] })
    }
  }, [refCount, queryClient])
 
  const query = useQuery({
    queryKey: queryKey as unknown as string[],
    queryFn: async () => {
      const { data } = await apiClient.get(contract.endpoints.detail(id))
  I    if (data && typeof data === 'object' && !('id' in data)) {
        ;(data as Record<string, unknown>).id = contract.idOf(data as TEntity)
      }
      return data
    },
    enabled: !!id,
    staleTime,
  })
 
  const data = extractSingle<TEntity>(query.data)
 
  return {
    data,
    isLoading: query.isLoading,
    isFetching: query.isFetching,
   I error: query.error,
    refetch: () => query.refetch(),
  }
}
 
function useMutationImpl<
  TIEntity extends { id: string },
  TCreateBody,
  TIUpdateBody,
  TListQuery extends QueryParams,
>(
  contract: ApiContract<TEntity, TCreateBody, TUpdateBody, TListQuery>,
): MutationHandle<TEntity, TCreateBody, TUpdateBody> {
  const qc = useQueryClient()
  const entityPath = contract.entityPath
  const detector = getOnlineDetector()
 
  lIet createPendingKey: string | null = null
 
  const createMutation = useMutation({
    mutationFn: async ({ input, context }: { input: TCreateBody; context?: QueryParams }) => {
    E  if (!detector.isOnline()) {
        if (!createPendingKey) createPendingKey = crypto.randomUUID()
        await addToOutbox({
          id: crypto.randomUUID(),
          entityPath,
    I      op: 'CREATE',
          payload: input,
          idempotencyKey: createPendingKey,
          createdAt: Date.now(),
        })
        return null
      }
      if (!createPendingKey) createPendingKey = crypto.randomUUID()
      const key = createPendingKey
      const body = contract.request?.create
        ? contract.request.create(input)
        : input
      const pathParams = contract.createPathParams
        ? contract.createPathParams(body, context)
        : (context ?? {})
      const { url, remainingParams } = resolveEndpointTemplate(
        contract.endpoints.create,
        pathParams,
      )
      const { data } = await apiClient.post(url, body, {
        headers: { 'Idempotency-Key': key },
        params: Object.keys(remainingParams).length > 0 ? remainingParams : undefined,
      })
      return data
    },
    onSuccess: (data) => {
      if (data) {
        qc.invalidateQueries({ queryKey: [entityPath] })
      }
    },
    onSettled: () => {
    I  createPendingKey = null
    },
  })
 
  let updatePendingKey: string | null = null
 
  const updateMutation = useMutation({
    mutationFn: async (variables: { id: string; input: TUpdateBody }) => {
      if (!detector.isOnline()) {
        if (!updatePendingKey) updatePendingKey = crypto.randomUUID()
        await addToOutbox({
          id: crypto.randomUUID(),
          entityPath,
          op: 'UPDATE',
          payload: { id: variables.id, ...variables.input },
          idempotencyKey: updatePendingKey,
          createdAt: Date.now(),
        })
        return null
      }
      if (!updatePendingKey) updatePendingKey = crypto.randomUUID()
      const key = updatePendingKey
      const body = contract.request?.update
        ? contract.request.update(variables.input)
        : variables.input
      const { data } = await apiClient.put(
        contract.endpoints.update(variables.id),
        body,
        {
          headers: { 'Idempotency-Key': key },
        },
      )
      return data
    },
    onSettled: () => {
    I  updatePendingKey = null
    },
  })
 
  let removePendingKey: string | null = null
I
  const removeMutation = useMutation({
    mutationFn: async (id: string) => {
      if (!contract.endpoints.remove) {
        console.warn(`remove not implemented for ${entityPath}`)
        return
      }
      const endpoint = contract.endpoints.remove(id)
      if (!detector.isOnline()) {
        if (!removePendingKey) removePendingKey = crypto.randomUUID()
        const key = removePendingKey
        addPendingDelete(entityPath, id)
        qc.getQueryCache()
          .getAll()
          .filter((q) => q.queryKey[0] === entityPath)
          .forEach((q) =>
            qc.setQueryData(
              q.queryKey,
              removeEntityFromResponse(q.state.data, id),
            ),
          )
        await addToOutbox({
          id: crypto.randomUUID(),
          entityPath,
          op: 'DELETE',
          payload: { id },
          idempotencyKey: key,
          createdAt: Date.now(),
        })
        return
      }
      if (!removePendingKey) removePendingKey = crypto.randomUUID()
      const key = removePendingKey
      await apiClient.delete(endpoint, {
        headers: { 'Idempotency-Key': key },
      })
    },
    onSuccess: (_data, id) => {
      addPendingDelete(entityPath, id)
      qc.getQueryCache()
        .getAll()
        .filter((q) => q.queryKey[0] === entityPath)
        .forEach((q) =>
          qc.setQueryData(
            q.queryKey,
            removeEntityFromResponse(q.state.data, id),
          ),
        )
    },
    onSettled: () => {
      removePendingKey = null
    },
  })
 
  return {
    create: (input, context?) => {
      createMutation.mutate({ input, context })
    },
    update: (id, input) => updateMutation.mutate({ id, input }),
    remove: (id) => removeMutation.mutate(id),
    isPending:
      createMutation.isPending ||
      updateMutation.isPending ||
      removeMutation.isPending,
    isError:
      createMutation.isError ||
      updateMutation.isError ||
      removeMutation.isError,
    error:
      createMutation.error ||
      updateMutation.error ||
      removeMutation.error,
    lastMutationData: (createMutation.data ?? updateMutation.data ?? null) as TEntity | null,
  }
}
 
function useSubscriptionImpl<
  TEntity extends { id: string },
  TCreateBody,
  TUpdateBody,
  TListQuery extends QueryParams,
>(
  contract: ApiContract<TEntity, TCreateBody, TUpdateBody, TListQuery>,
  params: TListQuery,
): SubscriptionHandle {
  const queryClient = useQueryClient()
  const normalized = normalizeFilters(params)
  const normalizedKey = JSON.stringify(normalized)
  const { entityPath } = contract
  const { ssePath, entityName } = contract.subscription ?? {}
 
  const [connectionState, setConnectionState] = useState<ConnectionState>('reconnecting')
  const lastHeartbeatAtRef = useRef<number>(Date.now())
  const wasEverConnectedRef = useRef(false)
  const shouldInvalidateOnOpenRef = useRef(false)
  const openRef = useRef<(reset?: boolean) => void>(() => {})
  const normalizedRef = useRef(normalized)
  normalizedRef.current = normalized
 
  useEffect(() => {
    if (!ssePath || !entityName) return
    const rk = refCountKey(entityPath, normalizedRef.current)
    incrementRefCount(rk)
    let cancelled = false
    const detector = getOnlineDetector()
    let source: EventSource | null = null
    let backoffMs = 1_000
    let failureCount = 0
    const wasEverConnected = wasEverConnectedRef
    const shouldInvalidateOnOpen = shouldInvalidateOnOpenRef
    let heartbeatCheckerId: ReturnType<typeof setInterval> | null = null
    const MAX_FAILURES = 5
    const pendingTimeouts = new Set<ReturnType<typeof setTimeout>>()
    let lostRetryTimeout: ReturnType<typeof setTimeout> | null = null
 
    function clearLostRetry() {
      if (lostRetryTimeout !== null) {
        clearTimeout(lostRetryTimeout)
        lostRetryTimeout = null
      }
    }
 
    function open(reset?: boolean) {
      if (cancelled) return
      clearLostRetry()
      if (reset) {
        failureCount = 0
        backoffMs = 1_000
        setConnectionState('reconnecting')
      }
      source?.close()
      source = null
      clearInterval(heartbeatCheckerId ?? undefined)
      heartbeatCheckerId = null
      if (!detector.isOnline()) return
 
      lastHeartbeatAtRef.current = Date.now()
 
      const qs = new URLSearchParams()
      for (const [k, v] of Object.entries(normalizedRef.current)) {
        if (v !== undefined) qs.set(k, String(v))
      }
      source = new EventSource(`${ssePath}?${qs}`, {
        withCredentials: true,
      })
 
      heartbeatCheckerId = setInterval(() => {
        const elapsed = Date.now() - lastHeartbeatAtRef.current
        if (elapsed > heartbeatTimeOut && source) {
          source.close()
          source = null
          clearInterval(heartbeatCheckerId ?? undefined)
          heartbeatCheckerId = null
          if (!detector.isOnline()) return
          failureCount++
          if (failureCount >= MAX_FAILURES) {
            pendingTimeouts.forEach(clearTimeout)
            pendingTimeouts.clear()
            setConnectionState('lost')
            clearLostRetry()
            lostRetryTimeout = setTimeout(() => open(), 60_000)
            return
          }
          setConnectionState('reconnecting')
          clearLostRetry()
          const id = setTimeout(open, backoffMs)
          pendingTimeouts.add(id)
          backoffMs = Math.min(backoffMs * 2, 30_000)
        }
      }, 5_000)
 
      source.addEventListener('heartbeat', () => {
        lastHeartbeatAtRef.current = Date.now()
      })
 
      source.onopen = () => {
        setConnectionState('connected')
        backoffMs = 1_000
        failureCount = 0
        lastHeartbeatAtRef.current = Date.now()
        wasEverConnected.current = true
        if (shouldInvalidateOnOpen.current) {
          if (!cancelled) {
            queryClient.invalidateQueries({ queryKey: [entityPath] })
          }
          shouldInvalidateOnOpen.current = false
        }
      }
 
      source.onerror = () => {
        source?.close()
        source = null
        if (!detector.isOnline()) return
        failureCount++
        if (failureCount === 1 && wasEverConnected.current) {
          shouldInvalidateOnOpen.current = true
        }
        if (failureCount >= MAX_FAILURES) {
          pendingTimeouts.forEach(clearTimeout)
          pendingTimeouts.clear()
          setConnectionState('lost')
          clearLostRetry()
          lostRetryTimeout = setTimeout(() => open(), 60_000)
          return
        }
        setConnectionState('reconnecting')
        clearLostRetry()
        const id = setTimeout(open, backoffMs)
        pendingTimeouts.add(id)
        backoffMs = Math.min(backoffMs * 2, 30_000)
      }
 
      source.addEventListener(`${entityName}.created`, (e) => {
        const entity = JSON.parse((e as MessageEvent).data) as TEntity
        const currentNormalized = normalizedRef.current
        const sortKey = currentNormalized.sort as string | undefined
        const sortOrder = currentNormalized.order as string | undefined
        const isNewestFirst =
          (!sortKey || sortKey === 'created_at') && sortOrder !== 'asc'
        if (!isNewestFirst) return
 
        queryClient
          .getQueryCache()
          .getAll()
          .filter((q) => q.queryKey[0] === entityPath)
          .forEach((q) =>
            queryClient.setQueryData(
              q.queryKey,
              insertEntityInResponse(q.state.data, entity),
            ),
          )
      })
 
      source.addEventListener(`${entityName}.updated`, (e) => {
        const updated = JSON.parse((e as MessageEvent).data) as TEntity
        if (getPendingDeletes(entityPath).has(contract.idOf(updated))) return
        queryClient
          .getQueryCache()
          .getAll()
          .filter((q) => q.queryKey[0] === entityPath)
          .forEach((q) =>
            queryClient.setQueryData(
              q.queryKey,
              patchEntityInResponse(q.state.data, updated),
            ),
          )
      })
 
      source.addEventListener(`${entityName}.deleted`, (e) => {
        const { id } = JSON.parse((e as MessageEvent).data) as { id: string }
        removePendingDelete(entityPath, id)
        queryClient
          .getQueryCache()
          .getAll()
          .filter((q) => q.queryKey[0] === entityPath)
          .forEach((q) =>
            queryClient.setQueryData(
              q.queryKey,
              removeEntityFromResponse(q.state.data, id),
            ),
          )
      })
    }
 
    openRef.current = open
 
    function handleOffline() {
      source?.close()
      source = null
      clearInterval(heartbeatCheckerId ?? undefined)
      heartbeatCheckerId = null
      clearLostRetry()
      pendingTimeouts.forEach(clearTimeout)
      pendingTimeouts.clear()
      backoffMs = 1_000
      failureCount = 0
    }
 
    function handleOnline() {
      backoffMs = 1_000
      failureCount = 0
      clearLostRetry()
      open()
    }
 
    const unsubscribe = detector.subscribe(() => {
      if (detector.isOnline()) {
        handleOnline()
      } else {
        handleOffline()
      }
    })
    open()
 
    return () => {
      cancelled = true
      decrementRefCount(rk)
      source?.close()
      clearInterval(heartbeatCheckerId ?? undefined)
      heartbeatCheckerId = null
      clearLostRetry()
      pendingTimeouts.forEach(clearTimeout)
      pendingTimeouts.clear()
      unsubscribe()
    }
  }, [
    queryClient,
    entityPath,
    ssePath,
    entityName,
    contract,
    normalizedKey,
  ])
 
  const reconnect = useCallback(() => {
    openRef.current(true)
  }, [])
 
  return {
    connectionState,
    reconnect,
  }
}
 
export function createEntityHooks<
  TEntity extends { id: string },
  TCreateBody = Partial<TEntity>,
  TUpdateBody = Partial<TEntity>,
  TListQuery extends QueryParams = QueryParams,
>(
  contract: ApiContract<TEntity, TCreateBody, TUpdateBody, TListQuery>,
): EntityHooks<TEntity, TCreateBody, TUpdateBody, TListQuery> {
  return {
    apiContract: contract,
 
    useEntityList(params, options?) {
      return useEntityListImpl(contract, params, options)
    },
 
    useEntityDetail(id) {
      return useEntityDetailImpl(contract, id)
    },
 
    useMutation() {
      return useMutationImpl(contract)
    },
 
    useSubscription(params) {
      return useSubscriptionImpl(contract, params)
    },
  }
}