Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

refactor: Split utils file in many different files (#63864)

Rafael Audibert1cb11ef76ef1
diff --git a/frontend/src/exporter/Exporter.tsx b/frontend/src/exporter/Exporter.tsx
index 8244bf7771b4..fb2971ab0cb8 100644
--- a/frontend/src/exporter/Exporter.tsx
+++ b/frontend/src/exporter/Exporter.tsx
@@ -11,7 +11,7 @@ import { useThemedHtml } from 'lib/hooks/useThemedHtml'
import { LemonMarkdown } from 'lib/lemon-ui/LemonMarkdown'
import { Link } from 'lib/lemon-ui/Link'
import { WrappingLoadingSkeleton } from 'lib/ui/WrappingLoadingSkeleton/WrappingLoadingSkeleton'
-import { humanFriendlyDuration } from 'lib/utils'
+import { humanFriendlyDuration } from 'lib/utils/durations'
import { AUTO_REFRESH_INITIAL_INTERVAL_SECONDS } from 'scenes/dashboard/dashboardConstants'
import { teamLogic } from 'scenes/teamLogic'
diff --git a/frontend/src/initKea.ts b/frontend/src/initKea.ts
index cd7d38ef5fc4..7ab4c20bf6c9 100644
--- a/frontend/src/initKea.ts
+++ b/frontend/src/initKea.ts
@@ -9,8 +9,8 @@ import { windowValuesPlugin } from 'kea-window-values'
import posthog from 'posthog-js'
import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'
-import { identifierToHuman } from 'lib/utils'
-import { addProjectIdIfMissing, removeProjectIdIfPresent, stripTrailingSlash } from 'lib/utils/router-utils'
+import { addProjectIdIfMissing, removeProjectIdIfPresent, stripTrailingSlash } from 'lib/utils/kea-router'
+import { identifierToHuman } from 'lib/utils/strings'
import { getTabsSnapshotForHistory, sceneLogic } from 'scenes/sceneLogic'
import { disposablesPlugin } from '~/kea-disposables'
diff --git a/frontend/src/layout/GlobalShortcuts.tsx b/frontend/src/layout/GlobalShortcuts.tsx
index ca8ad465958a..c2a510dfa900 100644
--- a/frontend/src/layout/GlobalShortcuts.tsx
+++ b/frontend/src/layout/GlobalShortcuts.tsx
@@ -10,7 +10,7 @@ import { commandLogic } from 'lib/components/Command/commandLogic'
import { openJumpToTimestampModal } from 'lib/components/DateFilter/openJumpToTimestampModal'
import { helpMenuLogic } from 'lib/components/HelpMenu/helpMenuLogic'
import { superpowersLogic } from 'lib/components/Superpowers/superpowersLogic'
-import { removeProjectIdIfPresent } from 'lib/utils/router-utils'
+import { removeProjectIdIfPresent } from 'lib/utils/kea-router'
import { urls } from 'scenes/urls'
import { SidePanelTab } from '~/types'
diff --git a/frontend/src/layout/navigation-3000/components/KeyboardShortcut.tsx b/frontend/src/layout/navigation-3000/components/KeyboardShortcut.tsx
index 6e8142e5a130..d03477abae6a 100644
--- a/frontend/src/layout/navigation-3000/components/KeyboardShortcut.tsx
+++ b/frontend/src/layout/navigation-3000/components/KeyboardShortcut.tsx
@@ -1,7 +1,7 @@
import './KeyboardShortcut.scss'
-import { isMac, isMobile } from 'lib/utils'
import { cn } from 'lib/utils/css-classes'
+import { isMac, isMobile } from 'lib/utils/dom'
import { HotKeyOrModifier } from '~/types'
diff --git a/frontend/src/layout/navigation-3000/navigationLogic.tsx b/frontend/src/layout/navigation-3000/navigationLogic.tsx
index 6746ec486bf5..4c845e011ef8 100644
--- a/frontend/src/layout/navigation-3000/navigationLogic.tsx
+++ b/frontend/src/layout/navigation-3000/navigationLogic.tsx
@@ -34,8 +34,8 @@ import { Spinner, lemonToast } from '@posthog/lemon-ui'
import { FEATURE_FLAGS } from 'lib/constants'
import { LemonMenuOverlay } from 'lib/lemon-ui/LemonMenu/LemonMenu'
import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
-import { isNotNil } from 'lib/utils'
import { getAppContext } from 'lib/utils/getAppContext'
+import { isNotNil } from 'lib/utils/guards'
import { editorSceneLogic } from 'scenes/data-warehouse/editor/editorSceneLogic'
import { onboardingVariantChrome, resolveOnboardingFlowVariant } from 'scenes/onboarding/onboardingVariants'
import { organizationLogic } from 'scenes/organizationLogic'
diff --git a/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/AccessControlObject.tsx b/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/AccessControlObject.tsx
index 6135d0f011c9..2193ce5300d7 100644
--- a/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/AccessControlObject.tsx
+++ b/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/AccessControlObject.tsx
@@ -20,8 +20,8 @@ import { UserSelectItem } from 'lib/components/UserSelectItem'
import { LemonTableColumns } from 'lib/lemon-ui/LemonTable'
import { LemonTableLink } from 'lib/lemon-ui/LemonTable/LemonTableLink'
import { ProfileBubbles, ProfilePicture } from 'lib/lemon-ui/ProfilePicture'
-import { capitalizeFirstLetter, fullName } from 'lib/utils'
import { getAccessControlTooltip } from 'lib/utils/accessControlUtils'
+import { capitalizeFirstLetter, fullName } from 'lib/utils/strings'
import { urls } from 'scenes/urls'
import { userLogic } from 'scenes/userLogic'
diff --git a/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/AccessControlPopoutCTA.tsx b/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/AccessControlPopoutCTA.tsx
index 25b045a0a789..983ed0203b79 100644
--- a/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/AccessControlPopoutCTA.tsx
+++ b/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/AccessControlPopoutCTA.tsx
@@ -3,8 +3,8 @@ import { useActions } from 'kea'
import { IconOpenSidebar } from '@posthog/icons'
import { LemonBanner, LemonButton } from '@posthog/lemon-ui'
-import { toSentenceCase } from 'lib/utils'
import { captureAccessControlEvent, resourceTypeToString } from 'lib/utils/accessControlUtils'
+import { toSentenceCase } from 'lib/utils/strings'
import { sidePanelStateLogic } from '~/layout/navigation-3000/sidepanel/sidePanelStateLogic'
import { AccessControlResourceType, SidePanelTab } from '~/types'
diff --git a/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/ResourceAccessControlsV2/AccessControlFilters.tsx b/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/ResourceAccessControlsV2/AccessControlFilters.tsx
index dee78e168a5f..59a7d1ff93af 100644
--- a/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/ResourceAccessControlsV2/AccessControlFilters.tsx
+++ b/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/ResourceAccessControlsV2/AccessControlFilters.tsx
@@ -1,7 +1,7 @@
import { IconChevronDown } from '@posthog/icons'
import { LemonButton, LemonDropdown, LemonInput } from '@posthog/lemon-ui'
-import { fullName } from 'lib/utils'
+import { fullName } from 'lib/utils/strings'
import { AccessControlLevel, APIScopeObject, OrganizationMemberType, RoleType } from '~/types'
diff --git a/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/ResourceAccessControlsV2/AccessControlTable.tsx b/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/ResourceAccessControlsV2/AccessControlTable.tsx
index c894ec9660c2..fef1acb683cf 100644
--- a/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/ResourceAccessControlsV2/AccessControlTable.tsx
+++ b/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/ResourceAccessControlsV2/AccessControlTable.tsx
@@ -3,8 +3,8 @@ import { capitalizeFirstLetter } from 'kea-forms'
import { IconPencil } from '@posthog/icons'
import { LemonButton, LemonTable, LemonTableColumns, LemonTag, ProfilePicture } from '@posthog/lemon-ui'
-import { fullName } from 'lib/utils'
import { pluralizeResource } from 'lib/utils/accessControlUtils'
+import { fullName } from 'lib/utils/strings'
import { APIScopeObject } from '~/types'
diff --git a/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/ResourceAccessControlsV2/GroupedAccessControlRuleModal.tsx b/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/ResourceAccessControlsV2/GroupedAccessControlRuleModal.tsx
index dc72f9064825..3900c371f2df 100644
--- a/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/ResourceAccessControlsV2/GroupedAccessControlRuleModal.tsx
+++ b/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/ResourceAccessControlsV2/GroupedAccessControlRuleModal.tsx
@@ -3,8 +3,8 @@ import { useActions, useValues } from 'kea'
import { IconHome, IconInfo, IconPlus } from '@posthog/icons'
import { LemonButton, LemonDivider, LemonDropdown, LemonModal, LemonSelect, Link, Tooltip } from '@posthog/lemon-ui'
-import { toSentenceCase } from 'lib/utils'
import { getAccessControlTooltip } from 'lib/utils/accessControlUtils'
+import { toSentenceCase } from 'lib/utils/strings'
import { accessControlsLogic } from './accessControlsLogic'
import { groupedAccessControlRuleModalLogic } from './groupedAccessControlRuleModalLogic'
diff --git a/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/ResourceAccessControlsV2/accessControlsLogic.ts b/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/ResourceAccessControlsV2/accessControlsLogic.ts
index 39ac8c5e5225..ee041d434816 100644
--- a/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/ResourceAccessControlsV2/accessControlsLogic.ts
+++ b/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/ResourceAccessControlsV2/accessControlsLogic.ts
@@ -3,8 +3,8 @@ import { loaders } from 'kea-loaders'
import { urlToAction } from 'kea-router'
import api from 'lib/api'
-import { toSentenceCase } from 'lib/utils'
import { captureAccessControlEvent, pluralizeResource } from 'lib/utils/accessControlUtils'
+import { toSentenceCase } from 'lib/utils/strings'
import { membersLogic } from 'scenes/organization/membersLogic'
import { userLogic } from 'scenes/userLogic'
diff --git a/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/ResourceAccessControlsV2/helpers.ts b/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/ResourceAccessControlsV2/helpers.ts
index 38606f6c7e3f..82fe66792c7e 100644
--- a/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/ResourceAccessControlsV2/helpers.ts
+++ b/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/ResourceAccessControlsV2/helpers.ts
@@ -1,4 +1,4 @@
-import { toSentenceCase } from 'lib/utils'
+import { toSentenceCase } from 'lib/utils/strings'
import { APIScopeObject, AccessControlLevel } from '~/types'
diff --git a/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/ResourcesAccessControls.tsx b/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/ResourcesAccessControls.tsx
index dc1cbb6e73b4..cd5e91c73aa1 100644
--- a/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/ResourcesAccessControls.tsx
+++ b/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/ResourcesAccessControls.tsx
@@ -19,13 +19,13 @@ import {
import { PayGateMini } from 'lib/components/PayGateMini/PayGateMini'
import { UserSelectItem } from 'lib/components/UserSelectItem'
-import { fullName } from 'lib/utils'
import {
getAccessControlTooltip,
getMaximumAccessLevel,
getMinimumAccessLevel,
pluralizeResource,
} from 'lib/utils/accessControlUtils'
+import { fullName } from 'lib/utils/strings'
import { APIScopeObject, AccessControlLevel, AvailableFeature } from '~/types'
diff --git a/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/RolesAccessControls.tsx b/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/RolesAccessControls.tsx
index e1efd96c7a9d..ccbf0c148b6c 100644
--- a/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/RolesAccessControls.tsx
+++ b/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/RolesAccessControls.tsx
@@ -24,7 +24,7 @@ import { usersLemonSelectOptions } from 'lib/components/UserSelectItem'
import { OrganizationMembershipLevel } from 'lib/constants'
import { LemonField } from 'lib/lemon-ui/LemonField'
import { LemonTableLink } from 'lib/lemon-ui/LemonTable/LemonTableLink'
-import { fullName } from 'lib/utils'
+import { fullName } from 'lib/utils/strings'
import { organizationLogic } from 'scenes/organizationLogic'
import { urls } from 'scenes/urls'
import { userLogic } from 'scenes/userLogic'
diff --git a/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/accessControlLogic.ts b/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/accessControlLogic.ts
index f560badf449d..95ff1eed8a34 100644
--- a/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/accessControlLogic.ts
+++ b/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/accessControlLogic.ts
@@ -6,8 +6,8 @@ import { LemonSelectOption } from '@posthog/lemon-ui'
import api from 'lib/api'
import { upgradeModalLogic } from 'lib/components/UpgradeModal/upgradeModalLogic'
import { OrganizationMembershipLevel } from 'lib/constants'
-import { toSentenceCase } from 'lib/utils'
import { AccessControlUIVersion, captureAccessControlEvent } from 'lib/utils/accessControlUtils'
+import { toSentenceCase } from 'lib/utils/strings'
import { membersLogic } from 'scenes/organization/membersLogic'
import { teamLogic } from 'scenes/teamLogic'
diff --git a/frontend/src/layout/navigation-3000/sidepanel/panels/activity/sidePanelNotificationsLogic.tsx b/frontend/src/layout/navigation-3000/sidepanel/panels/activity/sidePanelNotificationsLogic.tsx
index 923934471ac0..0a9b8b5b3f7b 100644
--- a/frontend/src/layout/navigation-3000/sidepanel/panels/activity/sidePanelNotificationsLogic.tsx
+++ b/frontend/src/layout/navigation-3000/sidepanel/panels/activity/sidePanelNotificationsLogic.tsx
@@ -12,8 +12,9 @@ import { dayjs } from 'lib/dayjs'
import { LemonDialog } from 'lib/lemon-ui/LemonDialog'
import { LemonMarkdown } from 'lib/lemon-ui/LemonMarkdown'
import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
-import { retryWithBackoff, toParams } from 'lib/utils'
import { liveEventsHostOrigin } from 'lib/utils/apiHost'
+import { retryWithBackoff } from 'lib/utils/async'
+import { toParams } from 'lib/utils/url'
import { organizationLogic } from 'scenes/organizationLogic'
import { projectLogic } from 'scenes/projectLogic'
import { teamLogic } from 'scenes/teamLogic'
diff --git a/frontend/src/layout/navigation-3000/sidepanel/panels/exports/SidePanelExports.tsx b/frontend/src/layout/navigation-3000/sidepanel/panels/exports/SidePanelExports.tsx
index e4b17a2ea768..d1f3c37edc16 100644
--- a/frontend/src/layout/navigation-3000/sidepanel/panels/exports/SidePanelExports.tsx
+++ b/frontend/src/layout/navigation-3000/sidepanel/panels/exports/SidePanelExports.tsx
@@ -9,7 +9,7 @@ import { ScreenShotEditor } from 'lib/components/TakeScreenshot/ScreenShotEditor
import { takeScreenshotLogic } from 'lib/components/TakeScreenshot/takeScreenshotLogic'
import { dayjs } from 'lib/dayjs'
import { IconWithCount } from 'lib/lemon-ui/icons'
-import { humanFriendlyNumber } from 'lib/utils'
+import { humanFriendlyNumber } from 'lib/utils/numbers'
import { ExportedAssetType, ExporterFormat } from '~/types'
diff --git a/frontend/src/layout/navigation-3000/sidepanel/sidePanelContextLogic.ts b/frontend/src/layout/navigation-3000/sidepanel/sidePanelContextLogic.ts
index 84388bf6366d..83364fe8f571 100644
--- a/frontend/src/layout/navigation-3000/sidepanel/sidePanelContextLogic.ts
+++ b/frontend/src/layout/navigation-3000/sidepanel/sidePanelContextLogic.ts
@@ -2,7 +2,7 @@ import { connect, kea, path, selectors } from 'kea'
import { router } from 'kea-router'
import { objectsEqual } from 'kea-test-utils'
-import { removeProjectIdIfPresent } from 'lib/utils/router-utils'
+import { removeProjectIdIfPresent } from 'lib/utils/kea-router'
import { sceneLogic } from 'scenes/sceneLogic'
import { SceneConfig } from 'scenes/sceneTypes'
diff --git a/frontend/src/layout/navigation/Breadcrumbs/breadcrumbsLogic.tsx b/frontend/src/layout/navigation/Breadcrumbs/breadcrumbsLogic.tsx
index f3ca0e9c25ff..6afaecb8a7cb 100644
--- a/frontend/src/layout/navigation/Breadcrumbs/breadcrumbsLogic.tsx
+++ b/frontend/src/layout/navigation/Breadcrumbs/breadcrumbsLogic.tsx
@@ -1,7 +1,9 @@
import { actions, afterMount, connect, kea, listeners, path, props, reducers, selectors } from 'kea'
import { subscriptions } from 'kea-subscriptions'
-import { identifierToHuman, objectsEqual, stripHTTP } from 'lib/utils'
+import { objectsEqual } from 'lib/utils/objects'
+import { identifierToHuman } from 'lib/utils/strings'
+import { stripHTTP } from 'lib/utils/url'
import { organizationLogic } from 'scenes/organizationLogic'
import { preflightLogic } from 'scenes/PreflightCheck/preflightLogic'
import { projectLogic } from 'scenes/projectLogic'
diff --git a/frontend/src/layout/panel-layout/ProjectTree/ProjectTree.tsx b/frontend/src/layout/panel-layout/ProjectTree/ProjectTree.tsx
index bb2fb3c1bf7e..5ede630c878d 100644
--- a/frontend/src/layout/panel-layout/ProjectTree/ProjectTree.tsx
+++ b/frontend/src/layout/panel-layout/ProjectTree/ProjectTree.tsx
@@ -31,10 +31,10 @@ import { ProfilePicture } from 'lib/lemon-ui/ProfilePicture/ProfilePicture'
import { ButtonPrimitive } from 'lib/ui/Button/ButtonPrimitives'
import { ContextMenuGroup, ContextMenuItem } from 'lib/ui/ContextMenu/ContextMenu'
import { DropdownMenuGroup } from 'lib/ui/DropdownMenu/DropdownMenu'
-import { isMobile } from 'lib/utils'
import { cn } from 'lib/utils/css-classes'
+import { isMobile } from 'lib/utils/dom'
import { eventUsageLogic } from 'lib/utils/eventUsageLogic'
-import { removeProjectIdIfPresent } from 'lib/utils/router-utils'
+import { removeProjectIdIfPresent } from 'lib/utils/kea-router'
import { sceneConfigurations } from 'scenes/scenes'
import { teamLogic } from 'scenes/teamLogic'
diff --git a/frontend/src/layout/panel-layout/ProjectTree/menus/MenuItems.tsx b/frontend/src/layout/panel-layout/ProjectTree/menus/MenuItems.tsx
index c5810f37e783..1bf451b53fff 100644
--- a/frontend/src/layout/panel-layout/ProjectTree/menus/MenuItems.tsx
+++ b/frontend/src/layout/panel-layout/ProjectTree/menus/MenuItems.tsx
@@ -31,7 +31,7 @@ import {
DropdownMenuSubContent,
DropdownMenuSubTrigger,
} from 'lib/ui/DropdownMenu/DropdownMenu'
-import { pluralize } from 'lib/utils'
+import { pluralize } from 'lib/utils/strings'
import { openDeleteGroupTypeDialog } from 'scenes/settings/environment/GroupAnalyticsConfig'
import { groupAnalyticsConfigLogic } from 'scenes/settings/environment/groupAnalyticsConfigLogic'
diff --git a/frontend/src/layout/panel-layout/ProjectTree/projectTreeDataLogic.tsx b/frontend/src/layout/panel-layout/ProjectTree/projectTreeDataLogic.tsx
index ce282566fa4d..683db2e03467 100644
--- a/frontend/src/layout/panel-layout/ProjectTree/projectTreeDataLogic.tsx
+++ b/frontend/src/layout/panel-layout/ProjectTree/projectTreeDataLogic.tsx
@@ -10,9 +10,9 @@ import { lemonToast } from 'lib/lemon-ui/LemonToast'
import { TreeDataItem } from 'lib/lemon-ui/LemonTree/LemonTree'
import { Spinner } from 'lib/lemon-ui/Spinner'
import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
-import { capitalizeFirstLetter, humanList, identifierToHuman, pluralize } from 'lib/utils'
import { eventUsageLogic } from 'lib/utils/eventUsageLogic'
import { getCurrentTeamIdOrNone } from 'lib/utils/getAppContext'
+import { capitalizeFirstLetter, humanList, identifierToHuman, pluralize } from 'lib/utils/strings'
import { urls } from 'scenes/urls'
import { userLogic } from 'scenes/userLogic'
diff --git a/frontend/src/layout/panel-layout/ai-first/NavLink.tsx b/frontend/src/layout/panel-layout/ai-first/NavLink.tsx
index d306a287f25f..2d905e665f68 100644
--- a/frontend/src/layout/panel-layout/ai-first/NavLink.tsx
+++ b/frontend/src/layout/panel-layout/ai-first/NavLink.tsx
@@ -5,7 +5,7 @@ import { IconGear } from '@posthog/icons'
import { Link } from 'lib/lemon-ui/Link'
import { ButtonGroupPrimitive, ButtonPrimitive } from 'lib/ui/Button/ButtonPrimitives'
import { cn } from 'lib/utils/css-classes'
-import { removeProjectIdIfPresent } from 'lib/utils/router-utils'
+import { removeProjectIdIfPresent } from 'lib/utils/kea-router'
import { urls } from 'scenes/urls'
import { panelLayoutLogic } from '~/layout/panel-layout/panelLayoutLogic'
diff --git a/frontend/src/layout/panel-layout/ai-first/tabs/NavTabBrowse.tsx b/frontend/src/layout/panel-layout/ai-first/tabs/NavTabBrowse.tsx
index cec61cf70ecc..105441cb1bd9 100644
--- a/frontend/src/layout/panel-layout/ai-first/tabs/NavTabBrowse.tsx
+++ b/frontend/src/layout/panel-layout/ai-first/tabs/NavTabBrowse.tsx
@@ -24,9 +24,9 @@ import { ButtonPrimitive } from 'lib/ui/Button/ButtonPrimitives'
import { Collapsible } from 'lib/ui/Collapsible/Collapsible'
import { DropdownMenuGroup, DropdownMenuItem, DropdownMenuSeparator } from 'lib/ui/DropdownMenu/DropdownMenu'
import { LinkListItem } from 'lib/ui/LinkListItem/LinkListItem'
-import { humanFriendlyDetailedTime } from 'lib/utils'
import { cn } from 'lib/utils/css-classes'
-import { removeProjectIdIfPresent } from 'lib/utils/router-utils'
+import { humanFriendlyDetailedTime } from 'lib/utils/datetime'
+import { removeProjectIdIfPresent } from 'lib/utils/kea-router'
import { sceneLogic } from 'scenes/sceneLogic'
import { urls } from 'scenes/urls'
diff --git a/frontend/src/layout/panel-layout/panelLayoutLogic.tsx b/frontend/src/layout/panel-layout/panelLayoutLogic.tsx
index 25b7571615c7..4084ba3ca720 100644
--- a/frontend/src/layout/panel-layout/panelLayoutLogic.tsx
+++ b/frontend/src/layout/panel-layout/panelLayoutLogic.tsx
@@ -2,7 +2,7 @@ import { actions, afterMount, connect, kea, listeners, path, reducers, selectors
import { router, urlToAction } from 'kea-router'
import { LemonTreeRef } from 'lib/lemon-ui/LemonTree/LemonTree'
-import { removeProjectIdIfPresent } from 'lib/utils/router-utils'
+import { removeProjectIdIfPresent } from 'lib/utils/kea-router'
import { navigation3000Logic } from '../navigation-3000/navigationLogic'
import type { panelLayoutLogicType } from './panelLayoutLogicType'
diff --git a/frontend/src/lib/Chart.ts b/frontend/src/lib/Chart.ts
index 95cfd9d7e7e3..e9b51667fafb 100644
--- a/frontend/src/lib/Chart.ts
+++ b/frontend/src/lib/Chart.ts
@@ -6,7 +6,7 @@ import { ChartType, DefaultDataPoint, Chart as RawChart, Tooltip, registerables
import CrosshairPlugin from 'chartjs-plugin-crosshair'
import ZoomPlugin from 'chartjs-plugin-zoom'
-import { inStorybookTestRunner } from 'lib/utils'
+import { inStorybookTestRunner } from 'lib/utils/dom'
if (registerables) {
// required for storybook to work, not found in esbuild
diff --git a/frontend/src/lib/api-error.ts b/frontend/src/lib/api-error.ts
index 11e2094f8728..c2b2ce51640e 100644
--- a/frontend/src/lib/api-error.ts
+++ b/frontend/src/lib/api-error.ts
@@ -1,5 +1,5 @@
import { dayjs } from 'lib/dayjs'
-import { humanFriendlyDuration } from 'lib/utils'
+import { humanFriendlyDuration } from 'lib/utils/durations'
export class ApiError extends Error {
/** Django REST Framework `detail` - used in downstream error handling. */
diff --git a/frontend/src/lib/api.ts b/frontend/src/lib/api.ts
index d37adb8ae909..98a3ff719b38 100644
--- a/frontend/src/lib/api.ts
+++ b/frontend/src/lib/api.ts
@@ -7,7 +7,8 @@ import { ActivityLogProps } from 'lib/components/ActivityLog/ActivityLog'
import { ActivityLogItem } from 'lib/components/ActivityLog/humanizeActivity'
import { apiStatusLogic } from 'lib/logic/apiStatusLogic'
import { assertNotReadOnly } from 'lib/readOnlyGuard'
-import { objectClean, toParams } from 'lib/utils'
+import { objectClean } from 'lib/utils/objects'
+import { toParams } from 'lib/utils/url'
import { CohortCalculationHistoryResponse } from 'scenes/cohorts/cohortCalculationHistorySceneLogic'
import { EventSchema } from 'scenes/data-management/events/eventDefinitionSchemaLogic'
import { SchemaPropertyGroup } from 'scenes/data-management/schema/schemaManagementLogic'
diff --git a/frontend/src/lib/components/Account/ProjectCombobox.tsx b/frontend/src/lib/components/Account/ProjectCombobox.tsx
index 0311e6cc6cab..5083464c4d18 100644
--- a/frontend/src/lib/components/Account/ProjectCombobox.tsx
+++ b/frontend/src/lib/components/Account/ProjectCombobox.tsx
@@ -9,7 +9,7 @@ import { ButtonGroupPrimitive, ButtonPrimitive } from 'lib/ui/Button/ButtonPrimi
import { Combobox } from 'lib/ui/Combobox/Combobox'
import { Label } from 'lib/ui/Label/Label'
import { MenuSeparator } from 'lib/ui/Menus/Menus'
-import { getProjectSwitchTargetUrl } from 'lib/utils/router-utils'
+import { getProjectSwitchTargetUrl } from 'lib/utils/kea-router'
import { organizationLogic } from 'scenes/organizationLogic'
import { preflightLogic } from 'scenes/PreflightCheck/preflightLogic'
import { isAuthenticatedTeam, teamLogic } from 'scenes/teamLogic'
diff --git a/frontend/src/lib/components/Account/ProjectSwitcher.tsx b/frontend/src/lib/components/Account/ProjectSwitcher.tsx
index d8b4a3797209..a258a719ef99 100644
--- a/frontend/src/lib/components/Account/ProjectSwitcher.tsx
+++ b/frontend/src/lib/components/Account/ProjectSwitcher.tsx
@@ -9,7 +9,7 @@ import { IconBlank } from 'lib/lemon-ui/icons'
import { ButtonPrimitive } from 'lib/ui/Button/ButtonPrimitives'
import { MenuSeparator } from 'lib/ui/Menus/Menus'
import { cn } from 'lib/utils/css-classes'
-import { getProjectSwitchTargetUrl } from 'lib/utils/router-utils'
+import { getProjectSwitchTargetUrl } from 'lib/utils/kea-router'
import { organizationLogic } from 'scenes/organizationLogic'
import { preflightLogic } from 'scenes/PreflightCheck/preflightLogic'
import { isAuthenticatedTeam, teamLogic } from 'scenes/teamLogic'
diff --git a/frontend/src/lib/components/ActivityLog/humanizeActivity.tsx b/frontend/src/lib/components/ActivityLog/humanizeActivity.tsx
index 175c2bcef873..38f2ae9c3605 100644
--- a/frontend/src/lib/components/ActivityLog/humanizeActivity.tsx
+++ b/frontend/src/lib/components/ActivityLog/humanizeActivity.tsx
@@ -1,6 +1,6 @@
import { dayjs } from 'lib/dayjs'
import { LemonMarkdown } from 'lib/lemon-ui/LemonMarkdown'
-import { fullName } from 'lib/utils'
+import { fullName } from 'lib/utils/strings'
import { ActivityScope, InsightShortId, PersonType, UserBasicType } from '~/types'
diff --git a/frontend/src/lib/components/AddToDashboard/AddToDashboardModal.tsx b/frontend/src/lib/components/AddToDashboard/AddToDashboardModal.tsx
index 363fedb5e982..6084eb7370e1 100644
--- a/frontend/src/lib/components/AddToDashboard/AddToDashboardModal.tsx
+++ b/frontend/src/lib/components/AddToDashboard/AddToDashboardModal.tsx
@@ -12,7 +12,7 @@ import { LemonInput } from 'lib/lemon-ui/LemonInput/LemonInput'
import { LemonModal } from 'lib/lemon-ui/LemonModal'
import { Link } from 'lib/lemon-ui/Link'
import { Tooltip } from 'lib/lemon-ui/Tooltip'
-import { pluralize } from 'lib/utils'
+import { pluralize } from 'lib/utils/strings'
import { teamLogic } from 'scenes/teamLogic'
import { urls } from 'scenes/urls'
diff --git a/frontend/src/lib/components/Alerts/SnoozeButton.tsx b/frontend/src/lib/components/Alerts/SnoozeButton.tsx
index 28516638f209..df79777cd3a1 100644
--- a/frontend/src/lib/components/Alerts/SnoozeButton.tsx
+++ b/frontend/src/lib/components/Alerts/SnoozeButton.tsx
@@ -1,5 +1,5 @@
import { dayjs } from 'lib/dayjs'
-import { formatDate } from 'lib/utils'
+import { formatDate } from 'lib/utils/datetime'
import { DateFilter } from '../DateFilter/DateFilter'
diff --git a/frontend/src/lib/components/Alerts/alertLogic.ts b/frontend/src/lib/components/Alerts/alertLogic.ts
index b1a0be126c8e..b5238e3f864c 100644
--- a/frontend/src/lib/components/Alerts/alertLogic.ts
+++ b/frontend/src/lib/components/Alerts/alertLogic.ts
@@ -3,7 +3,7 @@ import { loaders } from 'kea-loaders'
import api from 'lib/api'
import { dayjs } from 'lib/dayjs'
-import { formatDate } from 'lib/utils'
+import { formatDate } from 'lib/utils/datetime'
import { AlertState } from '~/queries/schema/schema-general'
diff --git a/frontend/src/lib/components/Alerts/alertNotificationLogic.ts b/frontend/src/lib/components/Alerts/alertNotificationLogic.ts
index eabb74e53d15..c1dad6c57853 100644
--- a/frontend/src/lib/components/Alerts/alertNotificationLogic.ts
+++ b/frontend/src/lib/components/Alerts/alertNotificationLogic.ts
@@ -11,7 +11,7 @@ import {
PendingAlertNotification,
buildAlertFilterConfig,
buildHogFunctionPayload,
-} from 'lib/utils/alertUtils'
+} from 'lib/utils/alerts'
import { deleteWithUndo } from 'lib/utils/deleteWithUndo'
import { projectLogic } from 'scenes/projectLogic'
diff --git a/frontend/src/lib/components/Alerts/alertsLogic.ts b/frontend/src/lib/components/Alerts/alertsLogic.ts
index ca2b0f28c712..b62ef5b1ea64 100644
--- a/frontend/src/lib/components/Alerts/alertsLogic.ts
+++ b/frontend/src/lib/components/Alerts/alertsLogic.ts
@@ -4,7 +4,7 @@ import { loaders } from 'kea-loaders'
import { PaginationManual } from '@posthog/lemon-ui'
import api from 'lib/api'
-import { objectClean } from 'lib/utils'
+import { objectClean } from 'lib/utils/objects'
import { AlertState } from '~/queries/schema/schema-general'
diff --git a/frontend/src/lib/components/Alerts/views/AlertDestinationSelector.tsx b/frontend/src/lib/components/Alerts/views/AlertDestinationSelector.tsx
index c4de158f1de8..fd4dabb92424 100644
--- a/frontend/src/lib/components/Alerts/views/AlertDestinationSelector.tsx
+++ b/frontend/src/lib/components/Alerts/views/AlertDestinationSelector.tsx
@@ -1,5 +1,5 @@
import { INSIGHT_ALERT_FIRING_SUB_TEMPLATE_ID } from 'lib/constants'
-import { buildAlertFilterConfig } from 'lib/utils/alertUtils'
+import { buildAlertFilterConfig } from 'lib/utils/alerts'
import { LinkedHogFunctions } from 'scenes/hog-functions/list/LinkedHogFunctions'
import { urls } from 'scenes/urls'
diff --git a/frontend/src/lib/components/Alerts/views/AlertHistoryChart.tsx b/frontend/src/lib/components/Alerts/views/AlertHistoryChart.tsx
index 9cf43a96184d..08f15326638f 100644
--- a/frontend/src/lib/components/Alerts/views/AlertHistoryChart.tsx
+++ b/frontend/src/lib/components/Alerts/views/AlertHistoryChart.tsx
@@ -3,7 +3,8 @@ import { useMemo } from 'react'
import { Chart } from 'lib/Chart'
import { useChart } from 'lib/hooks/useChart'
-import { humanFriendlyNumber, pluralize } from 'lib/utils'
+import { humanFriendlyNumber } from 'lib/utils/numbers'
+import { pluralize } from 'lib/utils/strings'
import { InsightThresholdType } from '~/queries/schema/schema-general'
diff --git a/frontend/src/lib/components/Alerts/views/AlertHistorySection.tsx b/frontend/src/lib/components/Alerts/views/AlertHistorySection.tsx
index 19bec00cc9be..c1aa727e8105 100644
--- a/frontend/src/lib/components/Alerts/views/AlertHistorySection.tsx
+++ b/frontend/src/lib/components/Alerts/views/AlertHistorySection.tsx
@@ -20,7 +20,7 @@ import { EmptyMessage } from 'lib/components/EmptyMessage/EmptyMessage'
import { TZLabel } from 'lib/components/TZLabel'
import { dayjs } from 'lib/dayjs'
import { IconOpenInNew } from 'lib/lemon-ui/icons'
-import { formatDate } from 'lib/utils'
+import { formatDate } from 'lib/utils/datetime'
import { alertLogic, CHART_CHECKS_LIMIT, TABLE_CHECKS_PAGE_SIZE } from '../alertLogic'
import type { AlertCheck, AlertType, InvestigationVerdict } from '../types'
diff --git a/frontend/src/lib/components/Alerts/views/EditAlertModal.tsx b/frontend/src/lib/components/Alerts/views/EditAlertModal.tsx
index 8d5869ae97c5..7d47829ead46 100644
--- a/frontend/src/lib/components/Alerts/views/EditAlertModal.tsx
+++ b/frontend/src/lib/components/Alerts/views/EditAlertModal.tsx
@@ -12,7 +12,7 @@ import { useFeatureFlag } from 'lib/hooks/useFeatureFlag'
import { LemonButton } from 'lib/lemon-ui/LemonButton'
import { LemonField } from 'lib/lemon-ui/LemonField'
import { LemonModal } from 'lib/lemon-ui/LemonModal'
-import { formatDate } from 'lib/utils'
+import { formatDate } from 'lib/utils/datetime'
import { teamLogic } from 'scenes/teamLogic'
import { trendsDataLogic } from 'scenes/trends/trendsDataLogic'
import { urls } from 'scenes/urls'
diff --git a/frontend/src/lib/components/Alerts/views/InlineAlertNotifications.tsx b/frontend/src/lib/components/Alerts/views/InlineAlertNotifications.tsx
index ae3ac1a69bda..5a6edeb74674 100644
--- a/frontend/src/lib/components/Alerts/views/InlineAlertNotifications.tsx
+++ b/frontend/src/lib/components/Alerts/views/InlineAlertNotifications.tsx
@@ -10,7 +10,7 @@ import {
ALERT_NOTIFICATION_TYPE_SLACK,
ALERT_NOTIFICATION_TYPE_WEBHOOK,
PendingAlertNotification,
-} from 'lib/utils/alertUtils'
+} from 'lib/utils/alerts'
import { urls } from 'scenes/urls'
import { HogFunctionType, SlackChannelType } from '~/types'
diff --git a/frontend/src/lib/components/Alerts/views/ManageAlertsModal.tsx b/frontend/src/lib/components/Alerts/views/ManageAlertsModal.tsx
index 471a0122624a..827045ed5189 100644
--- a/frontend/src/lib/components/Alerts/views/ManageAlertsModal.tsx
+++ b/frontend/src/lib/components/Alerts/views/ManageAlertsModal.tsx
@@ -8,7 +8,7 @@ import { LemonModal } from 'lib/lemon-ui/LemonModal'
import { LemonTag } from 'lib/lemon-ui/LemonTag'
import { ProfileBubbles } from 'lib/lemon-ui/ProfilePicture'
import { Spinner } from 'lib/lemon-ui/Spinner'
-import { pluralize } from 'lib/utils'
+import { pluralize } from 'lib/utils/strings'
import { urls } from 'scenes/urls'
import { AlertState, InsightThresholdType } from '~/queries/schema/schema-general'
diff --git a/frontend/src/lib/components/AnnotationsOverlay/AnnotationsOverlay.tsx b/frontend/src/lib/components/AnnotationsOverlay/AnnotationsOverlay.tsx
index 480072a38b60..808d5655e5fd 100644
--- a/frontend/src/lib/components/AnnotationsOverlay/AnnotationsOverlay.tsx
+++ b/frontend/src/lib/components/AnnotationsOverlay/AnnotationsOverlay.tsx
@@ -14,7 +14,9 @@ import { LemonButton } from 'lib/lemon-ui/LemonButton'
import { LemonModal } from 'lib/lemon-ui/LemonModal'
import { Popover } from 'lib/lemon-ui/Popover/Popover'
import { ProfilePicture } from 'lib/lemon-ui/ProfilePicture'
-import { humanFriendlyDetailedTime, pluralize, shortTimeZone } from 'lib/utils'
+import { humanFriendlyDetailedTime } from 'lib/utils/datetime'
+import { pluralize } from 'lib/utils/strings'
+import { shortTimeZone } from 'lib/utils/timezones'
import { AnnotationModal } from 'scenes/annotations/AnnotationModal'
import { annotationModalLogic, annotationScopeToName } from 'scenes/annotations/annotationModalLogic'
import { insightLogic } from 'scenes/insights/insightLogic'
diff --git a/frontend/src/lib/components/AnnotationsOverlay/annotationsOverlayLogic.ts b/frontend/src/lib/components/AnnotationsOverlay/annotationsOverlayLogic.ts
index 1dbc844bff34..6719e988bb6c 100644
--- a/frontend/src/lib/components/AnnotationsOverlay/annotationsOverlayLogic.ts
+++ b/frontend/src/lib/components/AnnotationsOverlay/annotationsOverlayLogic.ts
@@ -4,8 +4,8 @@ import { isPersonPropertyFilter, parseProperties } from 'lib/components/Property
import { FEATURE_FLAGS } from 'lib/constants'
import { Dayjs, dayjs } from 'lib/dayjs'
import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
-import { groupBy } from 'lib/utils'
-import { parseDateInTimezone } from 'lib/utils/dateTimeUtils'
+import { groupBy } from 'lib/utils/arrays'
+import { parseDateInTimezone } from 'lib/utils/datetime'
import { insightLogic } from 'scenes/insights/insightLogic'
import { insightVizDataLogic } from 'scenes/insights/insightVizDataLogic'
import { teamLogic } from 'scenes/teamLogic'
diff --git a/frontend/src/lib/components/AppMetrics/AppMetricSummary.tsx b/frontend/src/lib/components/AppMetrics/AppMetricSummary.tsx
index 4706c332dc0e..e86adbc9e82f 100644
--- a/frontend/src/lib/components/AppMetrics/AppMetricSummary.tsx
+++ b/frontend/src/lib/components/AppMetrics/AppMetricSummary.tsx
@@ -2,7 +2,7 @@ import { useMemo } from 'react'
import { LemonLabel, LemonSkeleton, SpinnerOverlay } from '@posthog/lemon-ui'
-import { formatPercentageDiff, humanFriendlyNumber } from 'lib/utils'
+import { formatPercentageDiff, humanFriendlyNumber } from 'lib/utils/numbers'
import { LineGraph } from '~/queries/nodes/DataVisualization/Components/Charts/LineGraph'
import { AxisSeries } from '~/queries/nodes/DataVisualization/dataVisualizationLogic'
diff --git a/frontend/src/lib/components/AppMetrics/AppMetricsSparkline.tsx b/frontend/src/lib/components/AppMetrics/AppMetricsSparkline.tsx
index 3d066a216e00..b55b9c535669 100644
--- a/frontend/src/lib/components/AppMetrics/AppMetricsSparkline.tsx
+++ b/frontend/src/lib/components/AppMetrics/AppMetricsSparkline.tsx
@@ -5,7 +5,7 @@ import { useInView } from 'react-intersection-observer'
import { LemonSkeleton } from '@posthog/lemon-ui'
import { Sparkline, SparklineTimeSeries } from 'lib/components/Sparkline'
-import { inStorybookTestRunner } from 'lib/utils'
+import { inStorybookTestRunner } from 'lib/utils/dom'
import { AppMetricsLogicProps, appMetricsLogic } from './appMetricsLogic'
diff --git a/frontend/src/lib/components/AppMetrics/appMetricsLogic.ts b/frontend/src/lib/components/AppMetrics/appMetricsLogic.ts
index c64996a2fe18..0da6f47f4ae1 100644
--- a/frontend/src/lib/components/AppMetrics/appMetricsLogic.ts
+++ b/frontend/src/lib/components/AppMetrics/appMetricsLogic.ts
@@ -4,7 +4,8 @@ import { subscriptions } from 'kea-subscriptions'
import api from 'lib/api'
import { Dayjs, dayjs } from 'lib/dayjs'
-import { dateStringToDayJs, objectsEqual } from 'lib/utils'
+import { dateStringToDayJs } from 'lib/utils/dateFilters'
+import { objectsEqual } from 'lib/utils/objects'
import { teamLogic } from 'scenes/teamLogic'
import { HogQLQueryString, hogql } from '~/queries/utils'
diff --git a/frontend/src/lib/components/AppShortcuts/appShortcutLogic.tsx b/frontend/src/lib/components/AppShortcuts/appShortcutLogic.tsx
index 12ccfd972661..8b2650061d80 100644
--- a/frontend/src/lib/components/AppShortcuts/appShortcutLogic.tsx
+++ b/frontend/src/lib/components/AppShortcuts/appShortcutLogic.tsx
@@ -1,6 +1,6 @@
import { actions, afterMount, beforeUnmount, kea, path, reducers } from 'kea'
-import { isMac } from 'lib/utils'
+import { isMac } from 'lib/utils/dom'
import { Scene } from 'scenes/sceneTypes'
import type { appShortcutLogicType } from './appShortcutLogicType'
diff --git a/frontend/src/lib/components/AppShortcuts/useAppShortcut.ts b/frontend/src/lib/components/AppShortcuts/useAppShortcut.ts
index c63c4d86f844..ea0864533622 100644
--- a/frontend/src/lib/components/AppShortcuts/useAppShortcut.ts
+++ b/frontend/src/lib/components/AppShortcuts/useAppShortcut.ts
@@ -1,7 +1,7 @@
import { useActions } from 'kea'
import { useCallback, useEffect, useRef, useState } from 'react'
-import { isMac } from 'lib/utils'
+import { isMac } from 'lib/utils/dom'
import { AppShortcutType, appShortcutLogic } from './appShortcutLogic'
diff --git a/frontend/src/lib/components/AppShortcuts/utils/DebugCHQueriesImpl.tsx b/frontend/src/lib/components/AppShortcuts/utils/DebugCHQueriesImpl.tsx
index f45201c7a661..2d02ad074a79 100644
--- a/frontend/src/lib/components/AppShortcuts/utils/DebugCHQueriesImpl.tsx
+++ b/frontend/src/lib/components/AppShortcuts/utils/DebugCHQueriesImpl.tsx
@@ -15,8 +15,8 @@ import { LemonButton } from 'lib/lemon-ui/LemonButton'
import { LemonTable } from 'lib/lemon-ui/LemonTable'
import { LemonTag } from 'lib/lemon-ui/LemonTag'
import { Link } from 'lib/lemon-ui/Link'
-import { humanizeBytes } from 'lib/utils'
import { copyToClipboard } from 'lib/utils/copyToClipboard'
+import { humanizeBytes } from 'lib/utils/numbers'
import { preflightLogic } from 'scenes/PreflightCheck/preflightLogic'
import { urls } from 'scenes/urls'
diff --git a/frontend/src/lib/components/AuthorizedUrlList/authorizedUrlListLogic.ts b/frontend/src/lib/components/AuthorizedUrlList/authorizedUrlListLogic.ts
index 54fab69f8c1b..94d2a0ebc526 100644
--- a/frontend/src/lib/components/AuthorizedUrlList/authorizedUrlListLogic.ts
+++ b/frontend/src/lib/components/AuthorizedUrlList/authorizedUrlListLogic.ts
@@ -18,9 +18,9 @@ import { subscriptions } from 'kea-subscriptions'
import api from 'lib/api'
import { SetupTaskId, globalSetupLogic } from 'lib/components/ProductSetup'
-import { isDomain, isURL } from 'lib/utils'
import { copyToClipboard } from 'lib/utils/copyToClipboard'
import { addProductIntent } from 'lib/utils/product-intents'
+import { isDomain, isURL } from 'lib/utils/url'
import { sceneLogic } from 'scenes/sceneLogic'
import { teamLogic } from 'scenes/teamLogic'
import { urls } from 'scenes/urls'
diff --git a/frontend/src/lib/utils/AutocapturePreviewImage.stories.tsx b/frontend/src/lib/components/AutocapturePreviewImage/AutocapturePreviewImage.stories.tsx
similarity index 99%
rename from frontend/src/lib/utils/AutocapturePreviewImage.stories.tsx
rename to frontend/src/lib/components/AutocapturePreviewImage/AutocapturePreviewImage.stories.tsx
index 70a78ea131fe..1d44e07b41cd 100644
--- a/frontend/src/lib/utils/AutocapturePreviewImage.stories.tsx
+++ b/frontend/src/lib/components/AutocapturePreviewImage/AutocapturePreviewImage.stories.tsx
@@ -3,7 +3,7 @@ import { Meta, StoryObj } from '@storybook/react'
import { mswDecorator } from '~/mocks/browser'
import { ElementType } from '~/types'
-import { AutocaptureImageTab, AutocapturePreviewImage } from './autocapture-previews'
+import { AutocaptureImageTab, AutocapturePreviewImage } from './AutocapturePreviewImage'
const meta: Meta = {
title: 'Utils/Autocapture Preview Image',
diff --git a/frontend/src/lib/utils/autocapture-previews.tsx b/frontend/src/lib/components/AutocapturePreviewImage/AutocapturePreviewImage.tsx
similarity index 92%
rename from frontend/src/lib/utils/autocapture-previews.tsx
rename to frontend/src/lib/components/AutocapturePreviewImage/AutocapturePreviewImage.tsx
index 133dbd3a9009..eba7520634ca 100644
--- a/frontend/src/lib/utils/autocapture-previews.tsx
+++ b/frontend/src/lib/components/AutocapturePreviewImage/AutocapturePreviewImage.tsx
@@ -1,4 +1,4 @@
-import './autocapture-previews.scss'
+import './autocapture-preview-image.scss'
import posthog from 'posthog-js'
@@ -49,6 +49,10 @@ function correctRelativeSrcImages(
return img
}
+export function hasAutocaptureImage(elements: ElementType[] | undefined): boolean {
+ return !!elements?.find((el) => el.tag_name === 'img')?.attributes?.attr__src
+}
+
export function autocaptureToImage(elements: ElementType[] | undefined): null | AutocapturedImage {
const find = elements?.find((el) => el.tag_name === 'img')
const image = {
@@ -64,7 +68,7 @@ function AutocaptureImage({ img }: { img: AutocapturedImage }): JSX.Element | nu
return (
<div className="flex bg-primary items-center justify-center relative border-2">
{/* Transparent grid background */}
- <div className="ImagePreview__background absolute h-full w-full" />
+ <div className="AutocaptureImage__grid-background absolute h-full w-full" />
<img
className="relative z-10 max-h-100 object-contain"
diff --git a/frontend/src/lib/utils/autocapture-previews.scss b/frontend/src/lib/components/AutocapturePreviewImage/autocapture-preview-image.scss
similarity index 88%
rename from frontend/src/lib/utils/autocapture-previews.scss
rename to frontend/src/lib/components/AutocapturePreviewImage/autocapture-preview-image.scss
index 2a28a4b9b82f..22032f60283d 100644
--- a/frontend/src/lib/utils/autocapture-previews.scss
+++ b/frontend/src/lib/components/AutocapturePreviewImage/autocapture-preview-image.scss
@@ -1,4 +1,4 @@
-.ImagePreview__background {
+.AutocaptureImage__grid-background {
background: #eee
url('data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" width="400" height="400" fill-opacity=".25" ><rect x="200" width="200" height="200" /><rect y="200" width="200" height="200" /> </svg>');
background-size: 30px 30px;
diff --git a/frontend/src/lib/components/BaseCurrency/utils.tsx b/frontend/src/lib/components/BaseCurrency/utils.tsx
index c31138fa1b5e..7c12a037be69 100644
--- a/frontend/src/lib/components/BaseCurrency/utils.tsx
+++ b/frontend/src/lib/components/BaseCurrency/utils.tsx
@@ -6,7 +6,7 @@ import {
DISABLED_CURRENCIES,
IMPORTANT_CURRENCIES,
OTHER_CURRENCIES,
-} from 'lib/utils/geography/currency'
+} from 'lib/utils/currency'
import { CurrencyCode } from '~/queries/schema/schema-general'
diff --git a/frontend/src/lib/components/Cards/CardMeta.tsx b/frontend/src/lib/components/Cards/CardMeta.tsx
index 9fd6aed5b9f7..fece6415f025 100644
--- a/frontend/src/lib/components/Cards/CardMeta.tsx
+++ b/frontend/src/lib/components/Cards/CardMeta.tsx
@@ -10,7 +10,7 @@ import { IconSubtitles, IconSubtitlesOff } from 'lib/lemon-ui/icons'
import { LemonButton } from 'lib/lemon-ui/LemonButton'
import { More } from 'lib/lemon-ui/LemonButton/More'
import { Tooltip } from 'lib/lemon-ui/Tooltip'
-import { inStorybook, inStorybookTestRunner } from 'lib/utils'
+import { inStorybook, inStorybookTestRunner } from 'lib/utils/dom'
import { InsightColor } from '~/types'
diff --git a/frontend/src/lib/components/Cards/InsightCard/CompactUniversalFiltersDisplay.tsx b/frontend/src/lib/components/Cards/InsightCard/CompactUniversalFiltersDisplay.tsx
index 3419e6658a09..a109e849695f 100644
--- a/frontend/src/lib/components/Cards/InsightCard/CompactUniversalFiltersDisplay.tsx
+++ b/frontend/src/lib/components/Cards/InsightCard/CompactUniversalFiltersDisplay.tsx
@@ -13,7 +13,8 @@ import {
import { PropertyKeyInfo } from 'lib/components/PropertyKeyInfo'
import { TaxonomicFilterGroupType } from 'lib/components/TaxonomicFilter/types'
import { Link } from 'lib/lemon-ui/Link'
-import { allOperatorsMapping, capitalizeFirstLetter } from 'lib/utils'
+import { allOperatorsMapping } from 'lib/utils/operators'
+import { capitalizeFirstLetter } from 'lib/utils/strings'
import { urls } from 'scenes/urls'
import { cohortsModel } from '~/models/cohortsModel'
diff --git a/frontend/src/lib/components/Cards/InsightCard/ErrorTrackingUniversalFiltersDisplay.tsx b/frontend/src/lib/components/Cards/InsightCard/ErrorTrackingUniversalFiltersDisplay.tsx
index 2f67def34f0e..3eeaf28750fd 100644
--- a/frontend/src/lib/components/Cards/InsightCard/ErrorTrackingUniversalFiltersDisplay.tsx
+++ b/frontend/src/lib/components/Cards/InsightCard/ErrorTrackingUniversalFiltersDisplay.tsx
@@ -1,7 +1,7 @@
import { IconFilter, IconList, IconSort } from '@posthog/icons'
import { LemonTag } from 'lib/lemon-ui/LemonTag/LemonTag'
-import { pluralize } from 'lib/utils'
+import { pluralize } from 'lib/utils/strings'
import { MaxErrorTrackingSearchResponse } from '~/queries/schema/schema-assistant-error-tracking'
diff --git a/frontend/src/lib/components/Cards/InsightCard/InsightCard.tsx b/frontend/src/lib/components/Cards/InsightCard/InsightCard.tsx
index bdd612961395..6f7c746dda15 100644
--- a/frontend/src/lib/components/Cards/InsightCard/InsightCard.tsx
+++ b/frontend/src/lib/components/Cards/InsightCard/InsightCard.tsx
@@ -12,8 +12,8 @@ import { Resizeable } from 'lib/components/Cards/CardMeta'
import { FEATURE_FLAGS } from 'lib/constants'
import { usePageVisibility } from 'lib/hooks/usePageVisibility'
import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
-import { inStorybook, inStorybookTestRunner } from 'lib/utils'
import { accessLevelSatisfied, getAccessControlDisabledReason } from 'lib/utils/accessControlUtils'
+import { inStorybook, inStorybookTestRunner } from 'lib/utils/dom'
import { BreakdownColorConfig } from 'scenes/dashboard/DashboardInsightColorsModal'
import {
InsightErrorState,
diff --git a/frontend/src/lib/components/Cards/InsightCard/InsightDetails.tsx b/frontend/src/lib/components/Cards/InsightCard/InsightDetails.tsx
index 742308ec396a..e39a942103ce 100644
--- a/frontend/src/lib/components/Cards/InsightCard/InsightDetails.tsx
+++ b/frontend/src/lib/components/Cards/InsightCard/InsightDetails.tsx
@@ -24,7 +24,8 @@ import { LemonDivider } from 'lib/lemon-ui/LemonDivider'
import { LemonTag } from 'lib/lemon-ui/LemonTag/LemonTag'
import { Link } from 'lib/lemon-ui/Link'
import { ProfilePicture } from 'lib/lemon-ui/ProfilePicture'
-import { capitalizeFirstLetter, dateFilterToText } from 'lib/utils'
+import { dateFilterToText } from 'lib/utils/dateFilters'
+import { capitalizeFirstLetter } from 'lib/utils/strings'
import { BreakdownTag } from 'scenes/insights/filters/BreakdownFilter/BreakdownTag'
import { humanizePathsEventTypes, hasUnsupportedBreakdownForDataWarehouseTrends } from 'scenes/insights/utils'
import { QUERY_TYPES_METADATA } from 'scenes/saved-insights/SavedInsights'
diff --git a/frontend/src/lib/components/Cards/InsightCard/InsightMeta.tsx b/frontend/src/lib/components/Cards/InsightCard/InsightMeta.tsx
index 30dd19906561..c41549af4174 100644
--- a/frontend/src/lib/components/Cards/InsightCard/InsightMeta.tsx
+++ b/frontend/src/lib/components/Cards/InsightCard/InsightMeta.tsx
@@ -25,9 +25,9 @@ import { Popover } from 'lib/lemon-ui/Popover'
import { Spinner } from 'lib/lemon-ui/Spinner'
import { Splotch, SplotchColor } from 'lib/lemon-ui/Splotch'
import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
-import { capitalizeFirstLetter } from 'lib/utils'
import { accessLevelSatisfied } from 'lib/utils/accessControlUtils'
import { eventUsageLogic } from 'lib/utils/eventUsageLogic'
+import { capitalizeFirstLetter } from 'lib/utils/strings'
import { insightDataLogic } from 'scenes/insights/insightDataLogic'
import { insightLogic } from 'scenes/insights/insightLogic'
import { insightVizDataLogic } from 'scenes/insights/insightVizDataLogic'
diff --git a/frontend/src/lib/components/Cards/InsightCard/RecordingsUniversalFiltersDisplay.tsx b/frontend/src/lib/components/Cards/InsightCard/RecordingsUniversalFiltersDisplay.tsx
index 651bf740a70c..c33d872ebe22 100644
--- a/frontend/src/lib/components/Cards/InsightCard/RecordingsUniversalFiltersDisplay.tsx
+++ b/frontend/src/lib/components/Cards/InsightCard/RecordingsUniversalFiltersDisplay.tsx
@@ -3,7 +3,7 @@ import React from 'react'
import { IconClock, IconFilter, IconList, IconSort } from '@posthog/icons'
import { LemonTag } from 'lib/lemon-ui/LemonTag/LemonTag'
-import { pluralize } from 'lib/utils'
+import { pluralize } from 'lib/utils/strings'
import { humanFriendlyDurationFilter } from 'scenes/session-recordings/filters/DurationFilter'
import { DurationType, RecordingUniversalFilters } from '~/types'
diff --git a/frontend/src/lib/components/Cards/InsightCard/TopHeading.tsx b/frontend/src/lib/components/Cards/InsightCard/TopHeading.tsx
index c21d7d42e46b..a83a01b2e2f5 100644
--- a/frontend/src/lib/components/Cards/InsightCard/TopHeading.tsx
+++ b/frontend/src/lib/components/Cards/InsightCard/TopHeading.tsx
@@ -1,6 +1,6 @@
import { CardTopHeadingRow } from 'lib/components/Cards/CardTopHeadingRow'
-import { dateFilterToText } from 'lib/utils'
-import { alignResolvedDateRangeToInterval, formatResolvedDateRange } from 'lib/utils/dateTimeUtils'
+import { dateFilterToText } from 'lib/utils/dateFilters'
+import { alignResolvedDateRangeToInterval, formatResolvedDateRange } from 'lib/utils/datetime'
import { InsightTypeMetadata, QUERY_TYPES_METADATA } from 'scenes/saved-insights/SavedInsights'
import { Node, NodeKind, ResolvedDateRangeResponse } from '~/queries/schema/schema-general'
diff --git a/frontend/src/lib/components/Cards/TextCard/textCardMarkdown.ts b/frontend/src/lib/components/Cards/TextCard/textCardMarkdown.ts
index 6775b205e06a..db173703af96 100644
--- a/frontend/src/lib/components/Cards/TextCard/textCardMarkdown.ts
+++ b/frontend/src/lib/components/Cards/TextCard/textCardMarkdown.ts
@@ -5,7 +5,7 @@ import { TaskItem, TaskList } from '@tiptap/extension-list'
import { MarkdownManager } from '@tiptap/markdown'
import StarterKit from '@tiptap/starter-kit'
-import { expandFlattenedMarkdownTables } from 'lib/utils/expandFlattenedMarkdownTables'
+import { expandFlattenedMarkdownTables } from 'lib/utils/markdown'
function escapeHtmlAttribute(value: string): string {
return value.replace(/&/g, '&amp;').replace(/"/g, '&quot;')
diff --git a/frontend/src/lib/components/CommandBlock/CommandBlock.tsx b/frontend/src/lib/components/CommandBlock/CommandBlock.tsx
index 7995f2c1d18d..8c93b6171027 100644
--- a/frontend/src/lib/components/CommandBlock/CommandBlock.tsx
+++ b/frontend/src/lib/components/CommandBlock/CommandBlock.tsx
@@ -4,9 +4,9 @@ import { useState } from 'react'
import { IconCopy, IconTerminal } from '@posthog/icons'
-import { inStorybook, inStorybookTestRunner } from 'lib/utils'
import { copyToClipboard } from 'lib/utils/copyToClipboard'
import { cn } from 'lib/utils/css-classes'
+import { inStorybook, inStorybookTestRunner } from 'lib/utils/dom'
type Size = 'sm' | 'md'
type Decoration = 'plain' | 'rainbow'
diff --git a/frontend/src/lib/components/CompareFilter/CompareFilter.tsx b/frontend/src/lib/components/CompareFilter/CompareFilter.tsx
index 3970f523b434..bdc48082d515 100644
--- a/frontend/src/lib/components/CompareFilter/CompareFilter.tsx
+++ b/frontend/src/lib/components/CompareFilter/CompareFilter.tsx
@@ -5,7 +5,7 @@ import { LemonSelect } from '@posthog/lemon-ui'
import { RollingDateRangeFilter } from 'lib/components/DateFilter/RollingDateRangeFilter'
import { useWindowSize } from 'lib/hooks/useWindowSize'
-import { dateFromToText } from 'lib/utils'
+import { dateFromToText } from 'lib/utils/dateFilters'
import { CompareFilter as CompareFilterType } from '~/queries/schema/schema-general'
diff --git a/frontend/src/lib/components/CyclotronJob/CyclotronJobInputs.tsx b/frontend/src/lib/components/CyclotronJob/CyclotronJobInputs.tsx
index a7dada92c439..73f2a54c9db0 100644
--- a/frontend/src/lib/components/CyclotronJob/CyclotronJobInputs.tsx
+++ b/frontend/src/lib/components/CyclotronJob/CyclotronJobInputs.tsx
@@ -34,8 +34,10 @@ import { LemonMarkdown } from 'lib/lemon-ui/LemonMarkdown/LemonMarkdown'
import { CodeEditorInline } from 'lib/monaco/CodeEditorInline'
import { CodeEditorResizeable } from 'lib/monaco/CodeEditorResizable'
import { Combobox, ComboboxContent, ComboboxEmpty, ComboboxInput, ComboboxItem, ComboboxList } from 'lib/ui/quill'
-import { capitalizeFirstLetter, objectsEqual, uuid } from 'lib/utils'
import { copyToClipboard } from 'lib/utils/copyToClipboard'
+import { uuid } from 'lib/utils/dom'
+import { objectsEqual } from 'lib/utils/objects'
+import { capitalizeFirstLetter } from 'lib/utils/strings'
import { CyclotronJobInputSchemaType, CyclotronJobInputType, CyclotronJobInvocationGlobalsWithInputs } from '~/types'
diff --git a/frontend/src/lib/components/CyclotronJob/CyclotronJobInputsValidation.ts b/frontend/src/lib/components/CyclotronJob/CyclotronJobInputsValidation.ts
index 1e59608a5715..322767eec9ec 100644
--- a/frontend/src/lib/components/CyclotronJob/CyclotronJobInputsValidation.ts
+++ b/frontend/src/lib/components/CyclotronJob/CyclotronJobInputsValidation.ts
@@ -1,4 +1,4 @@
-import { tryJsonParse } from 'lib/utils'
+import { tryJsonParse } from 'lib/utils/json'
import { LiquidRenderer } from 'lib/utils/liquid'
import type { EmailTemplate } from 'scenes/hog-functions/email-templater/types'
diff --git a/frontend/src/lib/components/DatabaseTableTree/TreeRow.tsx b/frontend/src/lib/components/DatabaseTableTree/TreeRow.tsx
index 2d54277d94f6..180ad2ca314e 100644
--- a/frontend/src/lib/components/DatabaseTableTree/TreeRow.tsx
+++ b/frontend/src/lib/components/DatabaseTableTree/TreeRow.tsx
@@ -4,8 +4,8 @@ import { useCallback, useState } from 'react'
import { IconChevronDown, IconClock, IconEllipsis } from '@posthog/icons'
import { LemonButton, LemonMenu, LemonMenuItem, Spinner, Tooltip } from '@posthog/lemon-ui'
-import { humanFriendlyDetailedTime } from 'lib/utils'
import { copyToClipboard } from 'lib/utils/copyToClipboard'
+import { humanFriendlyDetailedTime } from 'lib/utils/datetime'
import { DatabaseSchemaTable } from '~/queries/schema/schema-general'
diff --git a/frontend/src/lib/components/DateDisplay/index.tsx b/frontend/src/lib/components/DateDisplay/index.tsx
index c1ead94cd3b1..2bfe45352ac1 100644
--- a/frontend/src/lib/components/DateDisplay/index.tsx
+++ b/frontend/src/lib/components/DateDisplay/index.tsx
@@ -1,7 +1,7 @@
import './DateDisplay.scss'
import { dayjs } from 'lib/dayjs'
-import { getConstrainedWeekRange } from 'lib/utils/dateTimeUtils'
+import { getConstrainedWeekRange } from 'lib/utils/datetime'
import { ResolvedDateRangeResponse } from '~/queries/schema/schema-general'
import { IntervalType } from '~/types'
diff --git a/frontend/src/lib/components/DateFilter/DateFilter.test.tsx b/frontend/src/lib/components/DateFilter/DateFilter.test.tsx
index 68b650e9b1ec..7ae81b7485e9 100644
--- a/frontend/src/lib/components/DateFilter/DateFilter.test.tsx
+++ b/frontend/src/lib/components/DateFilter/DateFilter.test.tsx
@@ -4,7 +4,7 @@ import { cleanup, render, screen, waitFor } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { Provider } from 'kea'
-import { dateMapping } from 'lib/utils'
+import { dateMapping } from 'lib/utils/dateFilters'
import { initKeaTests } from '~/test/init'
diff --git a/frontend/src/lib/components/DateFilter/DateFilter.tsx b/frontend/src/lib/components/DateFilter/DateFilter.tsx
index 66fecebb09f6..a10efded3ab8 100644
--- a/frontend/src/lib/components/DateFilter/DateFilter.tsx
+++ b/frontend/src/lib/components/DateFilter/DateFilter.tsx
@@ -17,8 +17,9 @@ import { dayjs } from 'lib/dayjs'
import { LemonCalendarSelect, LemonCalendarSelectProps } from 'lib/lemon-ui/LemonCalendar/LemonCalendarSelect'
import { LemonCalendarRange } from 'lib/lemon-ui/LemonCalendarRange/LemonCalendarRange'
import { Tooltip } from 'lib/lemon-ui/Tooltip'
-import { dateFilterToText, dateMapping, uuid } from 'lib/utils'
-import { formatResolvedDateRange } from 'lib/utils/dateTimeUtils'
+import { dateFilterToText, dateMapping } from 'lib/utils/dateFilters'
+import { formatResolvedDateRange } from 'lib/utils/datetime'
+import { uuid } from 'lib/utils/dom'
import { teamLogic } from 'scenes/teamLogic'
import { ResolvedDateRangeResponse } from '~/queries/schema/schema-general'
diff --git a/frontend/src/lib/components/DateFilter/dateFilterLogic.test.ts b/frontend/src/lib/components/DateFilter/dateFilterLogic.test.ts
index 17b3b941b603..78d47792e098 100644
--- a/frontend/src/lib/components/DateFilter/dateFilterLogic.test.ts
+++ b/frontend/src/lib/components/DateFilter/dateFilterLogic.test.ts
@@ -2,7 +2,7 @@ import { expectLogic } from 'kea-test-utils'
import { DateFilterLogicProps, DateFilterView } from 'lib/components/DateFilter/types'
import { dayjs } from 'lib/dayjs'
-import { dateMapping } from 'lib/utils'
+import { dateMapping } from 'lib/utils/dateFilters'
import { dateFilterLogic } from './dateFilterLogic'
diff --git a/frontend/src/lib/components/DateFilter/dateFilterLogic.ts b/frontend/src/lib/components/DateFilter/dateFilterLogic.ts
index f982265df8a8..8efd658fcabc 100644
--- a/frontend/src/lib/components/DateFilter/dateFilterLogic.ts
+++ b/frontend/src/lib/components/DateFilter/dateFilterLogic.ts
@@ -7,15 +7,8 @@ import {
SELECT_FIXED_VALUE_PLACEHOLDER,
} from 'lib/components/DateFilter/types'
import { Dayjs, dayjs } from 'lib/dayjs'
-import {
- dateFilterToText,
- dateStringToDayJs,
- formatDate,
- formatDateRange,
- formatDateTime,
- formatDateTimeRange,
- isDate,
-} from 'lib/utils'
+import { dateFilterToText, dateStringToDayJs } from 'lib/utils/dateFilters'
+import { formatDate, formatDateRange, formatDateTime, formatDateTimeRange, isDate } from 'lib/utils/datetime'
import { DateMappingOption } from '~/types'
diff --git a/frontend/src/lib/components/DateFilter/rollingDateRangeFilterLogic.ts b/frontend/src/lib/components/DateFilter/rollingDateRangeFilterLogic.ts
index 0dbecbe08ed2..d162b77c7b72 100644
--- a/frontend/src/lib/components/DateFilter/rollingDateRangeFilterLogic.ts
+++ b/frontend/src/lib/components/DateFilter/rollingDateRangeFilterLogic.ts
@@ -3,7 +3,7 @@ import './RollingDateRangeFilter.scss'
import { actions, kea, key, listeners, path, props, reducers, selectors } from 'kea'
import { Dayjs } from 'lib/dayjs'
-import { dateFilterToText } from 'lib/utils'
+import { dateFilterToText } from 'lib/utils/dateFilters'
import type { rollingDateRangeFilterLogicType } from './rollingDateRangeFilterLogicType'
diff --git a/frontend/src/lib/components/DefinitionPopover/CohortPopoverInfo.tsx b/frontend/src/lib/components/DefinitionPopover/CohortPopoverInfo.tsx
index 151095ff37fb..20695a7448b4 100644
--- a/frontend/src/lib/components/DefinitionPopover/CohortPopoverInfo.tsx
+++ b/frontend/src/lib/components/DefinitionPopover/CohortPopoverInfo.tsx
@@ -8,7 +8,7 @@ import {
operatorToHumanName,
propertyValueToHumanName,
} from 'lib/components/DefinitionPopover/utils'
-import { pluralize } from 'lib/utils'
+import { pluralize } from 'lib/utils/strings'
import { BEHAVIORAL_TYPE_TO_LABEL } from 'scenes/cohorts/CohortFilters/constants'
import {
COHORT_MATCHING_DAYS,
diff --git a/frontend/src/lib/components/DefinitionPopover/DefinitionPopoverContents.tsx b/frontend/src/lib/components/DefinitionPopover/DefinitionPopoverContents.tsx
index e542b15f16cb..8b0ceeea53ee 100644
--- a/frontend/src/lib/components/DefinitionPopover/DefinitionPopoverContents.tsx
+++ b/frontend/src/lib/components/DefinitionPopover/DefinitionPopoverContents.tsx
@@ -23,8 +23,8 @@ import { IconOpenInNew } from 'lib/lemon-ui/icons'
import { LemonTextArea } from 'lib/lemon-ui/LemonTextArea/LemonTextArea'
import { Popover } from 'lib/lemon-ui/Popover'
import { Tooltip } from 'lib/lemon-ui/Tooltip'
-import { isKeyOf } from 'lib/utils'
import { cn } from 'lib/utils/css-classes'
+import { isKeyOf } from 'lib/utils/guards'
import { getCoreFilterDefinition, getFilterLabel, isCoreFilter } from '~/taxonomy/helpers'
import {
diff --git a/frontend/src/lib/components/DefinitionPopover/definitionPopoverLogic.ts b/frontend/src/lib/components/DefinitionPopover/definitionPopoverLogic.ts
index 442a9b510747..091d9124a93f 100644
--- a/frontend/src/lib/components/DefinitionPopover/definitionPopoverLogic.ts
+++ b/frontend/src/lib/components/DefinitionPopover/definitionPopoverLogic.ts
@@ -7,8 +7,8 @@ import { getSingularType } from 'lib/components/DefinitionPopover/utils'
import { getDataWarehouseItemWithFieldDefaults } from 'lib/components/TaxonomicFilter/dataWarehouseItemUtils'
import { TaxonomicDefinitionTypes, TaxonomicFilterGroupType } from 'lib/components/TaxonomicFilter/types'
import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'
-import { capitalizeFirstLetter } from 'lib/utils'
import { eventUsageLogic } from 'lib/utils/eventUsageLogic'
+import { capitalizeFirstLetter } from 'lib/utils/strings'
import { teamLogic } from 'scenes/teamLogic'
import { urls } from 'scenes/urls'
diff --git a/frontend/src/lib/components/DefinitionPopover/utils.ts b/frontend/src/lib/components/DefinitionPopover/utils.ts
index 1b55b3ed62af..56b202fbe23a 100644
--- a/frontend/src/lib/components/DefinitionPopover/utils.ts
+++ b/frontend/src/lib/components/DefinitionPopover/utils.ts
@@ -1,6 +1,6 @@
import { isPropertyFilterWithOperator } from 'lib/components/PropertyFilters/utils'
import { TaxonomicFilterGroupType } from 'lib/components/TaxonomicFilter/types'
-import { allOperatorsMapping, genericOperatorMap } from 'lib/utils'
+import { allOperatorsMapping, genericOperatorMap } from 'lib/utils/operators'
import { AnyPropertyFilter, PropertyFilterValue, PropertyOperator } from '~/types'
diff --git a/frontend/src/lib/components/EditableField/EditableField.tsx b/frontend/src/lib/components/EditableField/EditableField.tsx
index ded58962a75f..909cf924be68 100644
--- a/frontend/src/lib/components/EditableField/EditableField.tsx
+++ b/frontend/src/lib/components/EditableField/EditableField.tsx
@@ -12,7 +12,7 @@ import { LemonButton } from 'lib/lemon-ui/LemonButton'
import { RawInputAutosize } from 'lib/lemon-ui/LemonInput/RawInputAutosize'
import { LemonMarkdown } from 'lib/lemon-ui/LemonMarkdown'
import { Tooltip } from 'lib/lemon-ui/Tooltip'
-import { pluralize } from 'lib/utils'
+import { pluralize } from 'lib/utils/strings'
import { AvailableFeature } from '~/types'
diff --git a/frontend/src/lib/components/EventPropertyTabs/EventPropertyTabs.tsx b/frontend/src/lib/components/EventPropertyTabs/EventPropertyTabs.tsx
index 82f8f08c041b..a45dbdb8f6a7 100644
--- a/frontend/src/lib/components/EventPropertyTabs/EventPropertyTabs.tsx
+++ b/frontend/src/lib/components/EventPropertyTabs/EventPropertyTabs.tsx
@@ -7,12 +7,12 @@ import { eventPropertyFilteringLogic } from 'lib/components/EventPropertyTabs/ev
import { HTMLElementsDisplay } from 'lib/components/HTMLElementsDisplay/HTMLElementsDisplay'
import { dayjs } from 'lib/dayjs'
import { LemonTab, LemonTabs, LemonTabsProps } from 'lib/lemon-ui/LemonTabs'
-import { isKeyOf } from 'lib/utils'
-import { AutocaptureImageTab, autocaptureToImage } from 'lib/utils/autocapture-previews'
+import { isKeyOf } from 'lib/utils/guards'
import { CORE_FILTER_DEFINITIONS_BY_GROUP, POSTHOG_EVENT_PROMOTED_PROPERTIES } from '~/taxonomy/taxonomy'
import { EventType, RecordingEventType } from '~/types'
+import { AutocaptureImageTab, hasAutocaptureImage } from '../AutocapturePreviewImage/AutocapturePreviewImage'
import { ErrorEventType } from '../Errors/types'
export type ErrorPropertyTabEvent = EventType | RecordingEventType | ErrorEventType
@@ -188,7 +188,7 @@ export const EventPropertyTabs = ({
),
}
: null,
- event.elements && autocaptureToImage(event.elements)
+ event.elements && hasAutocaptureImage(event.elements)
? {
key: 'image',
label: 'Image',
diff --git a/frontend/src/lib/components/ExportButton/exportsLogic.ts b/frontend/src/lib/components/ExportButton/exportsLogic.ts
index cd57aa0182cd..a866718af8e8 100644
--- a/frontend/src/lib/components/ExportButton/exportsLogic.ts
+++ b/frontend/src/lib/components/ExportButton/exportsLogic.ts
@@ -7,7 +7,7 @@ import { TriggerExportProps, downloadBlob, downloadExportedAsset } from 'lib/com
import { isLongRunningExportFormat } from 'lib/components/ExportButton/exportStatus'
import { dayjs } from 'lib/dayjs'
import { lemonToast } from 'lib/lemon-ui/LemonToast'
-import { delay } from 'lib/utils'
+import { delay } from 'lib/utils/async'
import { newInternalTab } from 'lib/utils/newInternalTab'
import type { SessionRecordingPlayerMode } from 'scenes/session-recordings/player/sessionRecordingPlayerLogic'
import { urls } from 'scenes/urls'
diff --git a/frontend/src/lib/components/FileSystem/LinkTo/LinkTo.tsx b/frontend/src/lib/components/FileSystem/LinkTo/LinkTo.tsx
index 60411fc8ed61..57ffe50e9e3c 100644
--- a/frontend/src/lib/components/FileSystem/LinkTo/LinkTo.tsx
+++ b/frontend/src/lib/components/FileSystem/LinkTo/LinkTo.tsx
@@ -8,7 +8,7 @@ import { linkToLogic } from 'lib/components/FileSystem/LinkTo/linkToLogic'
import { LemonButton } from 'lib/lemon-ui/LemonButton'
import { LemonField } from 'lib/lemon-ui/LemonField'
import { LemonModal } from 'lib/lemon-ui/LemonModal'
-import { pluralize } from 'lib/utils'
+import { pluralize } from 'lib/utils/strings'
import { splitPath } from '~/layout/panel-layout/ProjectTree/utils'
diff --git a/frontend/src/lib/components/FileSystem/MoveTo/MoveTo.tsx b/frontend/src/lib/components/FileSystem/MoveTo/MoveTo.tsx
index dfa83d9ac850..acef8e7679cd 100644
--- a/frontend/src/lib/components/FileSystem/MoveTo/MoveTo.tsx
+++ b/frontend/src/lib/components/FileSystem/MoveTo/MoveTo.tsx
@@ -8,7 +8,7 @@ import { moveToLogic } from 'lib/components/FileSystem/MoveTo/moveToLogic'
import { LemonButton } from 'lib/lemon-ui/LemonButton'
import { LemonField } from 'lib/lemon-ui/LemonField'
import { LemonModal } from 'lib/lemon-ui/LemonModal'
-import { pluralize } from 'lib/utils'
+import { pluralize } from 'lib/utils/strings'
import { splitPath } from '~/layout/panel-layout/ProjectTree/utils'
diff --git a/frontend/src/lib/components/HTMLElementsDisplay/SelectableElement.tsx b/frontend/src/lib/components/HTMLElementsDisplay/SelectableElement.tsx
index dda585faed7e..102ddf7f9b32 100644
--- a/frontend/src/lib/components/HTMLElementsDisplay/SelectableElement.tsx
+++ b/frontend/src/lib/components/HTMLElementsDisplay/SelectableElement.tsx
@@ -3,7 +3,7 @@ import './SelectableElement.scss'
import clsx from 'clsx'
import { ParsedCSSSelector } from 'lib/components/HTMLElementsDisplay/preselectWithCSS'
-import { objectsEqual } from 'lib/utils'
+import { objectsEqual } from 'lib/utils/objects'
import { ElementType } from '~/types'
diff --git a/frontend/src/lib/components/HTMLElementsDisplay/htmlElementsDisplayLogic.ts b/frontend/src/lib/components/HTMLElementsDisplay/htmlElementsDisplayLogic.ts
index 780620ad0661..5318d3689016 100644
--- a/frontend/src/lib/components/HTMLElementsDisplay/htmlElementsDisplayLogic.ts
+++ b/frontend/src/lib/components/HTMLElementsDisplay/htmlElementsDisplayLogic.ts
@@ -6,7 +6,7 @@ import {
parsedSelectorToSelectorString,
preselect,
} from 'lib/components/HTMLElementsDisplay/preselectWithCSS'
-import { objectsEqual } from 'lib/utils'
+import { objectsEqual } from 'lib/utils/objects'
import { ElementType } from '~/types'
diff --git a/frontend/src/lib/components/HedgehogMode/HedgehogMode.tsx b/frontend/src/lib/components/HedgehogMode/HedgehogMode.tsx
index 3b89738b56a0..833cd27b6ff3 100644
--- a/frontend/src/lib/components/HedgehogMode/HedgehogMode.tsx
+++ b/frontend/src/lib/components/HedgehogMode/HedgehogMode.tsx
@@ -1,7 +1,7 @@
import { useActions, useValues } from 'kea'
import { Suspense, lazy } from 'react'
-import { inStorybook } from 'lib/utils'
+import { inStorybook } from 'lib/utils/dom'
import { themeLogic } from '~/layout/navigation-3000/themeLogic'
import { toolbarConfigLogic } from '~/toolbar/toolbarConfigLogic'
diff --git a/frontend/src/lib/components/HelpMenu/posthogStatusLogic.tsx b/frontend/src/lib/components/HelpMenu/posthogStatusLogic.tsx
index e21fbda35b7a..581f41c9ea4e 100644
--- a/frontend/src/lib/components/HelpMenu/posthogStatusLogic.tsx
+++ b/frontend/src/lib/components/HelpMenu/posthogStatusLogic.tsx
@@ -1,7 +1,7 @@
import { connect, kea, path, selectors } from 'kea'
import { superpowersLogic } from 'lib/components/Superpowers/superpowersLogic'
-import { capitalizeFirstLetter } from 'lib/utils'
+import { capitalizeFirstLetter } from 'lib/utils/strings'
import { incidentStatusLogic } from './incidentStatusLogic'
import type { posthogStatusLogicType } from './posthogStatusLogicType'
diff --git a/frontend/src/lib/components/HoqQLPropertyInfo.tsx b/frontend/src/lib/components/HoqQLPropertyInfo.tsx
index 01263593bb9f..66439d5b7b7f 100644
--- a/frontend/src/lib/components/HoqQLPropertyInfo.tsx
+++ b/frontend/src/lib/components/HoqQLPropertyInfo.tsx
@@ -1,4 +1,4 @@
-import { midEllipsis } from 'lib/utils'
+import { midEllipsis } from 'lib/utils/strings'
type HoqQLPropertyInfoProps = {
value: string
diff --git a/frontend/src/lib/components/IframedToolbarBrowser/utils.ts b/frontend/src/lib/components/IframedToolbarBrowser/utils.ts
index 3863e5d9c5b7..b02242769332 100644
--- a/frontend/src/lib/components/IframedToolbarBrowser/utils.ts
+++ b/frontend/src/lib/components/IframedToolbarBrowser/utils.ts
@@ -1,6 +1,6 @@
import { CUSTOM_OPTION_KEY } from 'lib/components/DateFilter/types'
import { HeatmapFilters } from 'lib/components/heatmaps/types'
-import { dateMapping } from 'lib/utils'
+import { dateMapping } from 'lib/utils/dateFilters'
export enum PostHogAppToolbarEvent {
PH_TOOLBAR_INIT = 'ph-toolbar-init',
diff --git a/frontend/src/lib/components/IngestionControls/Summary.tsx b/frontend/src/lib/components/IngestionControls/Summary.tsx
index 2cee42fb04c1..ec71bfa73e00 100644
--- a/frontend/src/lib/components/IngestionControls/Summary.tsx
+++ b/frontend/src/lib/components/IngestionControls/Summary.tsx
@@ -3,7 +3,7 @@ import { match } from 'ts-pattern'
import { IconCheck, IconCircleDashed } from '@posthog/icons'
import { LemonBanner, Link } from '@posthog/lemon-ui'
-import { pluralize } from 'lib/utils'
+import { pluralize } from 'lib/utils/strings'
import { Trigger, TriggerType } from './types'
diff --git a/frontend/src/lib/components/IngestionControls/triggers/FlagTrigger/flagTriggerLogic.ts b/frontend/src/lib/components/IngestionControls/triggers/FlagTrigger/flagTriggerLogic.ts
index 6345d869f390..3ea0448d0040 100644
--- a/frontend/src/lib/components/IngestionControls/triggers/FlagTrigger/flagTriggerLogic.ts
+++ b/frontend/src/lib/components/IngestionControls/triggers/FlagTrigger/flagTriggerLogic.ts
@@ -2,7 +2,7 @@ import { actions, afterMount, kea, key, listeners, path, props, selectors } from
import { loaders } from 'kea-loaders'
import api from 'lib/api'
-import { isObject } from 'lib/utils'
+import { isObject } from 'lib/utils/guards'
import { variantKeyToIndexFeatureFlagPayloads } from 'scenes/feature-flags/featureFlagLogic'
import { LinkedFeatureFlag } from '../../types'
diff --git a/frontend/src/lib/components/IngestionControls/triggers/triggerGroups/CreateFromLegacyModal.tsx b/frontend/src/lib/components/IngestionControls/triggers/triggerGroups/CreateFromLegacyModal.tsx
index f4466adea3b6..211116fa355a 100644
--- a/frontend/src/lib/components/IngestionControls/triggers/triggerGroups/CreateFromLegacyModal.tsx
+++ b/frontend/src/lib/components/IngestionControls/triggers/triggerGroups/CreateFromLegacyModal.tsx
@@ -1,6 +1,6 @@
import { LemonBanner, LemonButton, LemonModal, LemonSnack, LemonTag } from '@posthog/lemon-ui'
-import { pluralize } from 'lib/utils'
+import { pluralize } from 'lib/utils/strings'
import { SessionRecordingTriggerGroup } from '~/lib/components/IngestionControls/types'
diff --git a/frontend/src/lib/components/IngestionControls/triggers/triggerGroups/replayTriggersV2Logic.ts b/frontend/src/lib/components/IngestionControls/triggers/triggerGroups/replayTriggersV2Logic.ts
index 34b03d725b66..a63da6c0e63d 100644
--- a/frontend/src/lib/components/IngestionControls/triggers/triggerGroups/replayTriggersV2Logic.ts
+++ b/frontend/src/lib/components/IngestionControls/triggers/triggerGroups/replayTriggersV2Logic.ts
@@ -1,7 +1,7 @@
import { actions, afterMount, connect, kea, listeners, path, reducers, selectors } from 'kea'
import { loaders } from 'kea-loaders'
-import { uuid } from 'lib/utils'
+import { uuid } from 'lib/utils/dom'
import { teamLogic } from 'scenes/teamLogic'
import {
diff --git a/frontend/src/lib/components/IngestionControls/triggers/triggerGroups/triggerGroupFormLogic.ts b/frontend/src/lib/components/IngestionControls/triggers/triggerGroups/triggerGroupFormLogic.ts
index bee8b107cdac..8f13ff0dd93b 100644
--- a/frontend/src/lib/components/IngestionControls/triggers/triggerGroups/triggerGroupFormLogic.ts
+++ b/frontend/src/lib/components/IngestionControls/triggers/triggerGroups/triggerGroupFormLogic.ts
@@ -4,7 +4,7 @@ import { forms } from 'kea-forms'
import { lemonToast } from '@posthog/lemon-ui'
import { ensureAnchored } from 'lib/components/IngestionControls/triggers/urlConfigLogic'
-import { uuid } from 'lib/utils'
+import { uuid } from 'lib/utils/dom'
import {
EventTriggerConfig,
diff --git a/frontend/src/lib/components/InsightLabel/index.tsx b/frontend/src/lib/components/InsightLabel/index.tsx
index f54b603b23da..9f3faaa2024c 100644
--- a/frontend/src/lib/components/InsightLabel/index.tsx
+++ b/frontend/src/lib/components/InsightLabel/index.tsx
@@ -10,7 +10,8 @@ import { parseAliasToReadable } from 'lib/components/PathCleanFilters/PathCleanF
import { PropertyKeyInfo } from 'lib/components/PropertyKeyInfo'
import { SeriesLetter } from 'lib/components/SeriesGlyph'
import { Tooltip } from 'lib/lemon-ui/Tooltip'
-import { capitalizeFirstLetter, hexToRGBA, midEllipsis } from 'lib/utils'
+import { hexToRGBA } from 'lib/utils/colors'
+import { capitalizeFirstLetter, midEllipsis } from 'lib/utils/strings'
import { formatEventName } from 'scenes/insights/utils'
import { mathsLogic } from 'scenes/trends/mathsLogic'
diff --git a/frontend/src/lib/components/LiveUserCount/LiveUserCount.tsx b/frontend/src/lib/components/LiveUserCount/LiveUserCount.tsx
index a298fe82b9f1..0072eb236699 100644
--- a/frontend/src/lib/components/LiveUserCount/LiveUserCount.tsx
+++ b/frontend/src/lib/components/LiveUserCount/LiveUserCount.tsx
@@ -7,8 +7,9 @@ import { IconPerson, IconVideoCamera } from '@posthog/icons'
import { Tooltip } from '@posthog/lemon-ui'
import { usePageVisibility } from 'lib/hooks/usePageVisibility'
-import { humanFriendlyLargeNumber, humanFriendlyNumber, pluralize } from 'lib/utils'
import { cn } from 'lib/utils/css-classes'
+import { humanFriendlyLargeNumber, humanFriendlyNumber } from 'lib/utils/numbers'
+import { pluralize } from 'lib/utils/strings'
import { teamLogic } from 'scenes/teamLogic'
import { LiveUserCountLogicProps, liveUserCountLogic } from './liveUserCountLogic'
diff --git a/frontend/src/lib/components/MCPHint/AgentBadgeRotator.tsx b/frontend/src/lib/components/MCPHint/AgentBadgeRotator.tsx
index 8a57596146ba..fd18dbb392cf 100644
--- a/frontend/src/lib/components/MCPHint/AgentBadgeRotator.tsx
+++ b/frontend/src/lib/components/MCPHint/AgentBadgeRotator.tsx
@@ -5,8 +5,8 @@ import { Link } from '@posthog/lemon-ui'
import { useInterval } from 'lib/hooks/useInterval'
import { IconSlack } from 'lib/lemon-ui/icons'
-import { inStorybook, inStorybookTestRunner } from 'lib/utils'
import { cn } from 'lib/utils/css-classes'
+import { inStorybook, inStorybookTestRunner } from 'lib/utils/dom'
import { AgentLogo, claudeLogo, cursorLogo, geminiLogo, openaiLogo } from '../AgentPromptButton/AgentLogo'
diff --git a/frontend/src/lib/components/MemberMultiSelect.tsx b/frontend/src/lib/components/MemberMultiSelect.tsx
index 2bdc4bec2846..0d63392d5789 100644
--- a/frontend/src/lib/components/MemberMultiSelect.tsx
+++ b/frontend/src/lib/components/MemberMultiSelect.tsx
@@ -10,7 +10,7 @@ import {
ProfilePicture,
} from '@posthog/lemon-ui'
-import { fullName } from 'lib/utils'
+import { fullName } from 'lib/utils/strings'
import { membersLogic } from 'scenes/organization/membersLogic'
import { UserBasicType } from '~/types'
diff --git a/frontend/src/lib/components/MemberSelect.tsx b/frontend/src/lib/components/MemberSelect.tsx
index 0fc015ef93ec..a80ca8eaa87f 100644
--- a/frontend/src/lib/components/MemberSelect.tsx
+++ b/frontend/src/lib/components/MemberSelect.tsx
@@ -10,7 +10,7 @@ import {
ProfilePicture,
} from '@posthog/lemon-ui'
-import { fullName } from 'lib/utils'
+import { fullName } from 'lib/utils/strings'
import { membersLogic } from 'scenes/organization/membersLogic'
import { UserBasicType } from '~/types'
diff --git a/frontend/src/lib/components/MemberSelectMultiple.tsx b/frontend/src/lib/components/MemberSelectMultiple.tsx
index 345b69309b79..75e6c91c714a 100644
--- a/frontend/src/lib/components/MemberSelectMultiple.tsx
+++ b/frontend/src/lib/components/MemberSelectMultiple.tsx
@@ -3,7 +3,7 @@ import { useActions, useValues } from 'kea'
import { LemonInputSelect } from '@posthog/lemon-ui'
import { useOnMountEffect } from 'lib/hooks/useOnMountEffect'
-import { fullName } from 'lib/utils'
+import { fullName } from 'lib/utils/strings'
import { membersLogic } from 'scenes/organization/membersLogic'
import { UserBasicType } from '~/types'
diff --git a/frontend/src/lib/components/NotFound/index.tsx b/frontend/src/lib/components/NotFound/index.tsx
index 34063f2d3bf1..1fbfeb687ceb 100644
--- a/frontend/src/lib/components/NotFound/index.tsx
+++ b/frontend/src/lib/components/NotFound/index.tsx
@@ -11,9 +11,9 @@ import { LemonButton, LemonCheckbox, ProfilePicture, SpinnerOverlay, lemonToast
import { useOnMountEffect } from 'lib/hooks/useOnMountEffect'
import { LemonMenuOverlay } from 'lib/lemon-ui/LemonMenu/LemonMenu'
import { Link } from 'lib/lemon-ui/Link'
-import { capitalizeFirstLetter } from 'lib/utils'
import { cn } from 'lib/utils/css-classes'
import { getAppContext } from 'lib/utils/getAppContext'
+import { capitalizeFirstLetter } from 'lib/utils/strings'
import { getDefaultEventsSceneQuery } from 'scenes/activity/explore/defaults'
import { useNotebookNode } from 'scenes/notebooks/Nodes/NotebookNodeContext'
import { preflightLogic } from 'scenes/PreflightCheck/preflightLogic'
diff --git a/frontend/src/lib/components/ObjectTags/ObjectTags.tsx b/frontend/src/lib/components/ObjectTags/ObjectTags.tsx
index e8406ac0d31e..ee1355268a82 100644
--- a/frontend/src/lib/components/ObjectTags/ObjectTags.tsx
+++ b/frontend/src/lib/components/ObjectTags/ObjectTags.tsx
@@ -6,7 +6,7 @@ import { IconPencil, IconPlus } from '@posthog/icons'
import { LemonInputSelect, LemonTag, LemonTagType } from '@posthog/lemon-ui'
import { objectTagsLogic } from 'lib/components/ObjectTags/objectTagsLogic'
-import { colorForString } from 'lib/utils'
+import { colorForString } from 'lib/utils/colors'
interface ObjectTagsPropsBase {
tags: string[]
diff --git a/frontend/src/lib/components/ObjectTags/objectTagsLogic.ts b/frontend/src/lib/components/ObjectTags/objectTagsLogic.ts
index e5f1443ed4c1..7d8e42f4716b 100644
--- a/frontend/src/lib/components/ObjectTags/objectTagsLogic.ts
+++ b/frontend/src/lib/components/ObjectTags/objectTagsLogic.ts
@@ -1,6 +1,6 @@
import { actions, kea, key, listeners, path, props, reducers } from 'kea'
-import { uniqueBy } from 'lib/utils'
+import { uniqueBy } from 'lib/utils/arrays'
import type { objectTagsLogicType } from './objectTagsLogicType'
diff --git a/frontend/src/lib/components/PropertiesTable/PropertiesTable.tsx b/frontend/src/lib/components/PropertiesTable/PropertiesTable.tsx
index 5cff1faf64bb..f42c886e7334 100644
--- a/frontend/src/lib/components/PropertiesTable/PropertiesTable.tsx
+++ b/frontend/src/lib/components/PropertiesTable/PropertiesTable.tsx
@@ -13,7 +13,8 @@ import { LemonButton } from 'lib/lemon-ui/LemonButton'
import { LemonTable, LemonTableColumns, LemonTableProps } from 'lib/lemon-ui/LemonTable'
import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
import { userPreferencesLogic } from 'lib/logic/userPreferencesLogic'
-import { isObject, isURL, isKeyOf } from 'lib/utils'
+import { isObject, isKeyOf } from 'lib/utils/guards'
+import { isURL } from 'lib/utils/url'
import { NewProperty } from 'scenes/persons/NewProperty'
import { preflightLogic } from 'scenes/PreflightCheck/preflightLogic'
import { urls } from 'scenes/urls'
diff --git a/frontend/src/lib/components/PropertiesTimeline/PropertiesTimeline.tsx b/frontend/src/lib/components/PropertiesTimeline/PropertiesTimeline.tsx
index 352618341fcb..ec901bf2e976 100644
--- a/frontend/src/lib/components/PropertiesTimeline/PropertiesTimeline.tsx
+++ b/frontend/src/lib/components/PropertiesTimeline/PropertiesTimeline.tsx
@@ -5,7 +5,7 @@ import { LemonDivider } from '@posthog/lemon-ui'
import { PropertiesTable } from 'lib/components/PropertiesTable'
import { Tooltip } from 'lib/lemon-ui/Tooltip'
-import { humanList } from 'lib/utils'
+import { humanList } from 'lib/utils/strings'
import { teamLogic } from 'scenes/teamLogic'
import { Properties } from '~/legacy-plugin-scaffold'
diff --git a/frontend/src/lib/components/PropertiesTimeline/propertiesTimelineLogic.ts b/frontend/src/lib/components/PropertiesTimeline/propertiesTimelineLogic.ts
index 129f08ae25aa..962c69d77ceb 100644
--- a/frontend/src/lib/components/PropertiesTimeline/propertiesTimelineLogic.ts
+++ b/frontend/src/lib/components/PropertiesTimeline/propertiesTimelineLogic.ts
@@ -4,7 +4,8 @@ import posthog from 'posthog-js'
import { Dayjs, dayjsUtcToTimezone } from 'lib/dayjs'
import { apiGetWithTimeToSeeDataTracking } from 'lib/internalMetrics'
-import { toParams, uuid } from 'lib/utils'
+import { uuid } from 'lib/utils/dom'
+import { toParams } from 'lib/utils/url'
import { teamLogic } from 'scenes/teamLogic'
import { Properties } from '~/legacy-plugin-scaffold'
diff --git a/frontend/src/lib/components/Property.tsx b/frontend/src/lib/components/Property.tsx
index d5507890df81..e379d22efe34 100644
--- a/frontend/src/lib/components/Property.tsx
+++ b/frontend/src/lib/components/Property.tsx
@@ -1,7 +1,7 @@
import { Link } from '@posthog/lemon-ui'
-import { isExternalLink } from 'lib/utils'
import stringWithWBR from 'lib/utils/stringWithWBR'
+import { isExternalLink } from 'lib/utils/url'
export function Property({ value }: { value: any }): JSX.Element {
let valueString: string
diff --git a/frontend/src/lib/components/PropertyFilters/components/DistinctIdSelect.tsx b/frontend/src/lib/components/PropertyFilters/components/DistinctIdSelect.tsx
index 20b5b4e81a44..c944ee6cff3c 100644
--- a/frontend/src/lib/components/PropertyFilters/components/DistinctIdSelect.tsx
+++ b/frontend/src/lib/components/PropertyFilters/components/DistinctIdSelect.tsx
@@ -2,7 +2,7 @@ import { useActions, useValues } from 'kea'
import { useId, useMemo } from 'react'
import { LemonInputSelect } from 'lib/lemon-ui/LemonInputSelect/LemonInputSelect'
-import { isOperatorMulti } from 'lib/utils'
+import { isOperatorMulti } from 'lib/utils/operators'
import type { PropertyFilterValue, PropertyOperator } from '~/types'
diff --git a/frontend/src/lib/components/PropertyFilters/components/GroupKeySelect.tsx b/frontend/src/lib/components/PropertyFilters/components/GroupKeySelect.tsx
index 105544a49d8b..18147d0d7d9c 100644
--- a/frontend/src/lib/components/PropertyFilters/components/GroupKeySelect.tsx
+++ b/frontend/src/lib/components/PropertyFilters/components/GroupKeySelect.tsx
@@ -2,7 +2,7 @@ import { useActions, useValues } from 'kea'
import { useMemo } from 'react'
import { LemonInputSelect, LemonInputSelectOption } from 'lib/lemon-ui/LemonInputSelect/LemonInputSelect'
-import { isOperatorMulti } from 'lib/utils'
+import { isOperatorMulti } from 'lib/utils/operators'
import { groupDisplayId } from 'scenes/persons/GroupActorDisplay'
import type { GroupTypeIndex, PropertyFilterValue, PropertyOperator } from '~/types'
diff --git a/frontend/src/lib/components/PropertyFilters/components/OperatorValueSelect.tsx b/frontend/src/lib/components/PropertyFilters/components/OperatorValueSelect.tsx
index 82e441986fe1..47faa2642b19 100644
--- a/frontend/src/lib/components/PropertyFilters/components/OperatorValueSelect.tsx
+++ b/frontend/src/lib/components/PropertyFilters/components/OperatorValueSelect.tsx
@@ -7,10 +7,10 @@ import { allOperatorsToHumanName } from 'lib/components/DefinitionPopover/utils'
import { dayjs } from 'lib/dayjs'
import { LemonInputSelect } from 'lib/lemon-ui/LemonInputSelect/LemonInputSelect'
import { Link } from 'lib/lemon-ui/Link'
+import { isMobile } from 'lib/utils/dom'
import {
allOperatorsMapping,
chooseOperatorMap,
- isMobile,
isOperatorCohort,
isOperatorDate,
isOperatorFlag,
@@ -18,7 +18,7 @@ import {
isOperatorRange,
isOperatorRegex,
isOperatorSemver,
-} from 'lib/utils'
+} from 'lib/utils/operators'
import { RE2_DOCS_LINK, formatRE2Error } from 'lib/utils/regexp'
import {
diff --git a/frontend/src/lib/components/PropertyFilters/components/PropertyFilterButton.tsx b/frontend/src/lib/components/PropertyFilters/components/PropertyFilterButton.tsx
index 7fcb3511bae3..be6ad8f875f3 100644
--- a/frontend/src/lib/components/PropertyFilters/components/PropertyFilterButton.tsx
+++ b/frontend/src/lib/components/PropertyFilters/components/PropertyFilterButton.tsx
@@ -8,7 +8,7 @@ import { IconX } from '@posthog/icons'
import { LemonButton, PopoverReferenceContext, Tooltip } from '@posthog/lemon-ui'
import { PropertyFilterIcon } from 'lib/components/PropertyFilters/components/PropertyFilterIcon'
-import { midEllipsis } from 'lib/utils'
+import { midEllipsis } from 'lib/utils/strings'
import { cohortsModel } from '~/models/cohortsModel'
import { propertyDefinitionsModel } from '~/models/propertyDefinitionsModel'
diff --git a/frontend/src/lib/components/PropertyFilters/components/PropertyFilterDatePicker.tsx b/frontend/src/lib/components/PropertyFilters/components/PropertyFilterDatePicker.tsx
index 57f8227afe04..7566f204e743 100644
--- a/frontend/src/lib/components/PropertyFilters/components/PropertyFilterDatePicker.tsx
+++ b/frontend/src/lib/components/PropertyFilters/components/PropertyFilterDatePicker.tsx
@@ -4,7 +4,7 @@ import { LemonCalendarSelectInput } from '@posthog/lemon-ui'
import { PropertyValueProps } from 'lib/components/PropertyFilters/components/PropertyValue'
import { dayjs } from 'lib/dayjs'
-import { isOperatorDate } from 'lib/utils'
+import { isOperatorDate } from 'lib/utils/operators'
import { PropertyFilterValue, PropertyOperator } from '~/types'
diff --git a/frontend/src/lib/components/PropertyFilters/components/PropertyValue.tsx b/frontend/src/lib/components/PropertyFilters/components/PropertyValue.tsx
index 45af4ac9b723..e4b9a4bd9650 100644
--- a/frontend/src/lib/components/PropertyFilters/components/PropertyValue.tsx
+++ b/frontend/src/lib/components/PropertyFilters/components/PropertyValue.tsx
@@ -23,15 +23,15 @@ import { isGroupCardFilterKey, propertyFilterTypeToPropertyDefinitionType } from
import { dayjs } from 'lib/dayjs'
import { IconErrorOutline } from 'lib/lemon-ui/icons'
import { LemonInputSelect } from 'lib/lemon-ui/LemonInputSelect/LemonInputSelect'
+import { formatDate } from 'lib/utils/datetime'
import {
- formatDate,
isOperatorBetween,
isOperatorDate,
isOperatorFlag,
isOperatorMulti,
isOperatorRegex,
- toString,
-} from 'lib/utils'
+} from 'lib/utils/operators'
+import { toString } from 'lib/utils/strings'
import {
PROPERTY_FILTER_TYPES_WITH_ALL_TIME_SUGGESTIONS,
diff --git a/frontend/src/lib/components/PropertyFilters/components/TaxonomicPropertyFilter.tsx b/frontend/src/lib/components/PropertyFilters/components/TaxonomicPropertyFilter.tsx
index 09945bb8e2a7..a46f9c65d02f 100644
--- a/frontend/src/lib/components/PropertyFilters/components/TaxonomicPropertyFilter.tsx
+++ b/frontend/src/lib/components/PropertyFilters/components/TaxonomicPropertyFilter.tsx
@@ -30,7 +30,8 @@ import { TaxonomicMenuToggle } from 'lib/components/TaxonomicPopover/TaxonomicMe
import { TaxonomicPopoverMenu } from 'lib/components/TaxonomicPopover/TaxonomicPopoverMenu'
import { FEATURE_FLAGS } from 'lib/constants'
import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
-import { isOperatorMulti, isOperatorRegex, toParams } from 'lib/utils'
+import { isOperatorMulti, isOperatorRegex } from 'lib/utils/operators'
+import { toParams } from 'lib/utils/url'
import { teamLogic } from 'scenes/teamLogic'
import { cohortsModel } from '~/models/cohortsModel'
diff --git a/frontend/src/lib/components/PropertyFilters/propertyFilterLogic.ts b/frontend/src/lib/components/PropertyFilters/propertyFilterLogic.ts
index 96d4b6d6d07e..c521f6186b0f 100644
--- a/frontend/src/lib/components/PropertyFilters/propertyFilterLogic.ts
+++ b/frontend/src/lib/components/PropertyFilters/propertyFilterLogic.ts
@@ -9,7 +9,7 @@ import {
} from 'lib/components/PropertyFilters/utils'
import { recentTaxonomicFiltersLogic } from 'lib/components/TaxonomicFilter/recentTaxonomicFiltersLogic'
import { TaxonomicFilterGroupType } from 'lib/components/TaxonomicFilter/types'
-import { isOperatorFlag } from 'lib/utils'
+import { isOperatorFlag } from 'lib/utils/operators'
import { teamLogic } from 'scenes/teamLogic'
import { AnyPropertyFilter, EmptyPropertyFilter } from '~/types'
diff --git a/frontend/src/lib/components/PropertyFilters/utils.ts b/frontend/src/lib/components/PropertyFilters/utils.ts
index 80e34fd3c560..38409fab13fe 100644
--- a/frontend/src/lib/components/PropertyFilters/utils.ts
+++ b/frontend/src/lib/components/PropertyFilters/utils.ts
@@ -1,13 +1,13 @@
import { TaxonomicFilterGroup, TaxonomicFilterGroupType } from 'lib/components/TaxonomicFilter/types'
+import { isKeyOf } from 'lib/utils/guards'
import {
allOperatorsMapping,
- capitalizeFirstLetter,
cohortOperatorMap,
isOperatorCohort,
isOperatorFlag,
isOperatorMulti,
- isKeyOf,
-} from 'lib/utils'
+} from 'lib/utils/operators'
+import { capitalizeFirstLetter } from 'lib/utils/strings'
import { propertyDefinitionsModelType } from '~/models/propertyDefinitionsModelType'
import { extractExpressionComment } from '~/queries/nodes/DataTable/utils'
diff --git a/frontend/src/lib/components/PropertyIcon/PropertyIcon.stories.tsx b/frontend/src/lib/components/PropertyIcon/PropertyIcon.stories.tsx
index 7304b93d25eb..e109b7039ce6 100644
--- a/frontend/src/lib/components/PropertyIcon/PropertyIcon.stories.tsx
+++ b/frontend/src/lib/components/PropertyIcon/PropertyIcon.stories.tsx
@@ -3,7 +3,7 @@ import type { Meta, StoryObj } from '@storybook/react'
import { PROPERTIES_ICON_MAP, PropertyIcon } from 'lib/components/PropertyIcon/PropertyIcon'
import { PropertyIconProps } from 'lib/components/PropertyIcon/types'
import { LemonTable } from 'lib/lemon-ui/LemonTable'
-import { COUNTRY_CODE_TO_LONG_NAME } from 'lib/utils/geography/country'
+import { COUNTRY_CODE_TO_LONG_NAME } from 'lib/utils/country'
type Story = StoryObj<PropertyIconProps>
const meta: Meta<PropertyIconProps> = {
diff --git a/frontend/src/lib/components/PropertyIcon/PropertyIconStandalone.tsx b/frontend/src/lib/components/PropertyIcon/PropertyIconStandalone.tsx
index e717ed7f36c0..4fba008f7a00 100644
--- a/frontend/src/lib/components/PropertyIcon/PropertyIconStandalone.tsx
+++ b/frontend/src/lib/components/PropertyIcon/PropertyIconStandalone.tsx
@@ -23,7 +23,7 @@ import {
IconWeb,
IconWindows,
} from 'lib/lemon-ui/icons'
-import { countryCodeToFlag } from 'lib/utils/geography/country'
+import { countryCodeToFlag } from 'lib/utils/country'
import { PropertyIconProps } from './types'
diff --git a/frontend/src/lib/components/PropertyKeyInfo.tsx b/frontend/src/lib/components/PropertyKeyInfo.tsx
index 14ece5de0502..1280a339bbf9 100644
--- a/frontend/src/lib/components/PropertyKeyInfo.tsx
+++ b/frontend/src/lib/components/PropertyKeyInfo.tsx
@@ -7,7 +7,7 @@ import React, { useState } from 'react'
import { LemonDivider, TooltipProps } from '@posthog/lemon-ui'
import { Popover } from 'lib/lemon-ui/Popover'
-import { pluralize } from 'lib/utils'
+import { pluralize } from 'lib/utils/strings'
import { surveyQuestionLabelsLogic } from 'scenes/surveys/surveyQuestionLabelsLogic'
import { PropertyKey, getCoreFilterDefinition } from '~/taxonomy/helpers'
diff --git a/frontend/src/lib/components/QuickFilters/quickFilterFormLogic.ts b/frontend/src/lib/components/QuickFilters/quickFilterFormLogic.ts
index a412c4903ef1..604a47176b96 100644
--- a/frontend/src/lib/components/QuickFilters/quickFilterFormLogic.ts
+++ b/frontend/src/lib/components/QuickFilters/quickFilterFormLogic.ts
@@ -2,7 +2,7 @@ import { LogicWrapper, actions, connect, kea, key, listeners, path, props, selec
import { forms } from 'kea-forms'
import { propertyFilterTypeToPropertyDefinitionType } from 'lib/components/PropertyFilters/utils'
-import { uuid } from 'lib/utils'
+import { uuid } from 'lib/utils/dom'
import { propertyDefinitionsModel } from '~/models/propertyDefinitionsModel'
import { PropertyFilterType, PropertyOperator, QuickFilter, QuickFilterOption } from '~/types'
diff --git a/frontend/src/lib/components/RichContentEditor/MentionsExtension.tsx b/frontend/src/lib/components/RichContentEditor/MentionsExtension.tsx
index 12c6e0a0eede..4d739109f1c0 100644
--- a/frontend/src/lib/components/RichContentEditor/MentionsExtension.tsx
+++ b/frontend/src/lib/components/RichContentEditor/MentionsExtension.tsx
@@ -7,8 +7,8 @@ import { forwardRef, useCallback, useEffect, useImperativeHandle, useMemo, useSt
import { LemonButton, ProfilePicture } from '@posthog/lemon-ui'
import { Popover } from 'lib/lemon-ui/Popover'
-import { isKeyOf } from 'lib/utils'
import { createFuse } from 'lib/utils/fuseSearch'
+import { isKeyOf } from 'lib/utils/guards'
import { membersLogic } from 'scenes/organization/membersLogic'
import { OrganizationMemberType } from '~/types'
diff --git a/frontend/src/lib/components/SaveToCohortModalContent/saveToCohortModalContentLogic.ts b/frontend/src/lib/components/SaveToCohortModalContent/saveToCohortModalContentLogic.ts
index 67c7519b0e3d..515dc9c407e5 100644
--- a/frontend/src/lib/components/SaveToCohortModalContent/saveToCohortModalContentLogic.ts
+++ b/frontend/src/lib/components/SaveToCohortModalContent/saveToCohortModalContentLogic.ts
@@ -5,7 +5,7 @@ import { router } from 'kea-router'
import { PaginationManual, lemonToast } from '@posthog/lemon-ui'
import api, { CountedPaginatedResponse } from 'lib/api'
-import { delay } from 'lib/utils'
+import { delay } from 'lib/utils/async'
import { cohortEditLogic } from 'scenes/cohorts/cohortEditLogic'
import { projectLogic } from 'scenes/projectLogic'
import { urls } from 'scenes/urls'
diff --git a/frontend/src/lib/components/Search/searchLogic.tsx b/frontend/src/lib/components/Search/searchLogic.tsx
index aa7ab7c256c7..9d4992b894f4 100644
--- a/frontend/src/lib/components/Search/searchLogic.tsx
+++ b/frontend/src/lib/components/Search/searchLogic.tsx
@@ -6,8 +6,8 @@ import { IconBell, IconClock, IconDownload, IconLeave, IconNotification } from '
import api from 'lib/api'
import { commandLogic } from 'lib/components/Command/commandLogic'
import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
-import { toSentenceCase } from 'lib/utils'
import { GroupQueryResult, mapGroupQueryResponse } from 'lib/utils/groups'
+import { toSentenceCase } from 'lib/utils/strings'
import { preflightLogic } from 'scenes/PreflightCheck/preflightLogic'
import { organizationIntegrationsLogic } from 'scenes/settings/organization/organizationIntegrationsLogic'
import { urls } from 'scenes/urls'
diff --git a/frontend/src/lib/components/Search/utils.ts b/frontend/src/lib/components/Search/utils.ts
index 9b3b1eedce34..c2c97acf65ae 100644
--- a/frontend/src/lib/components/Search/utils.ts
+++ b/frontend/src/lib/components/Search/utils.ts
@@ -1,6 +1,6 @@
import { Dayjs, dayjs } from 'lib/dayjs'
-import { pluralize } from 'lib/utils'
import { createFuse } from 'lib/utils/fuseSearch'
+import { pluralize } from 'lib/utils/strings'
interface FuseSearchable {
name: string
diff --git a/frontend/src/lib/components/SeriesGlyph.tsx b/frontend/src/lib/components/SeriesGlyph.tsx
index d6786383cc28..bf8a24bfc954 100644
--- a/frontend/src/lib/components/SeriesGlyph.tsx
+++ b/frontend/src/lib/components/SeriesGlyph.tsx
@@ -1,7 +1,8 @@
import { useValues } from 'kea'
import { getSeriesColor } from 'lib/colors'
-import { RGBToRGBA, alphabet, hexToRGBA, lightenDarkenColor } from 'lib/utils'
+import { RGBToRGBA, hexToRGBA, lightenDarkenColor } from 'lib/utils/colors'
+import { alphabet } from 'lib/utils/strings'
import { themeLogic } from '~/layout/navigation-3000/themeLogic'
diff --git a/frontend/src/lib/components/SessionTimeline/SessionTimeline.stories.tsx b/frontend/src/lib/components/SessionTimeline/SessionTimeline.stories.tsx
index a5edcdb4f21c..0ed24274d68c 100644
--- a/frontend/src/lib/components/SessionTimeline/SessionTimeline.stories.tsx
+++ b/frontend/src/lib/components/SessionTimeline/SessionTimeline.stories.tsx
@@ -2,7 +2,7 @@ import { Meta, StoryFn } from '@storybook/react'
import { useRef } from 'react'
import { Dayjs, dayjs } from 'lib/dayjs'
-import { uuid } from 'lib/utils'
+import { uuid } from 'lib/utils/dom'
import { SessionTimeline, SessionTimelineHandle } from './SessionTimeline'
import { ItemCategory, ItemCollector, ItemLoader, ItemRenderer, TimelineItem } from './timeline'
diff --git a/frontend/src/lib/components/Sharing/SharePasswordsTable.tsx b/frontend/src/lib/components/Sharing/SharePasswordsTable.tsx
index 28509dcf56aa..69b36d0ac3a9 100644
--- a/frontend/src/lib/components/Sharing/SharePasswordsTable.tsx
+++ b/frontend/src/lib/components/Sharing/SharePasswordsTable.tsx
@@ -5,8 +5,8 @@ import { IconCopy, IconPlus, IconTrash, IconWarning } from '@posthog/icons'
import { LemonButton, LemonInput, LemonModal } from '@posthog/lemon-ui'
import { LemonDialog } from 'lib/lemon-ui/LemonDialog'
-import { humanFriendlyDetailedTime } from 'lib/utils'
import { copyToClipboard } from 'lib/utils/copyToClipboard'
+import { humanFriendlyDetailedTime } from 'lib/utils/datetime'
import { sharePasswordsLogic } from './sharePasswordsLogic'
diff --git a/frontend/src/lib/components/Sharing/SharingModal.test.tsx b/frontend/src/lib/components/Sharing/SharingModal.test.tsx
index e1caba5d4e45..06e0f8098c04 100644
--- a/frontend/src/lib/components/Sharing/SharingModal.test.tsx
+++ b/frontend/src/lib/components/Sharing/SharingModal.test.tsx
@@ -7,12 +7,13 @@ import { eventUsageLogic } from 'lib/utils/eventUsageLogic'
import { useAvailableFeatures } from '~/mocks/features'
import { useMocks } from '~/mocks/jest'
+import { NodeKind } from '~/queries/schema/schema-general'
import { initKeaTests } from '~/test/init'
import { InsightShortId, QueryBasedInsightModel } from '~/types'
import { AvailableFeature } from '~/types'
import { sharingLogic } from './sharingLogic'
-import { SharingModal, SharingModalProps } from './SharingModal'
+import { getInsightDefinitionUrl, SharingModal, SharingModalProps } from './SharingModal'
const createdAt = '2022-06-28T12:30:51.459746Z'
const accessToken = '1AEQjQ2xNLGoiyI0UnNlLzOiBZWWMQ'
@@ -194,3 +195,50 @@ describe('SharingModal (insight)', () => {
expect(within(modal as HTMLElement).queryByText(/Show insight details/i)).toBeNull()
})
})
+
+describe('getInsightDefinitionUrl', () => {
+ it('generates a template link for an unsaved insight (raw query)', () => {
+ const query = {
+ kind: NodeKind.InsightVizNode,
+ source: {
+ kind: NodeKind.TrendsQuery,
+ series: [
+ {
+ kind: NodeKind.EventsNode,
+ event: null,
+ name: 'All events',
+ math: 'total',
+ },
+ ],
+ trendsFilter: {},
+ },
+ }
+ const url = getInsightDefinitionUrl({ query }, 'https://app.posthog.com')
+ expect(url).toMatch(/^https:\/\/app\.posthog\.com\/insights\/new#insight=TRENDS&q=%7B.*%7D(%20)?$/)
+ // Should not include /project/<id>
+ expect(url).not.toContain('/project/')
+ })
+
+ it('generates a template link for a saved insight (model)', () => {
+ interface MinimalInsight {
+ query: any
+ id: number
+ name: string
+ }
+ const savedInsight: MinimalInsight = {
+ query: {
+ kind: NodeKind.InsightVizNode,
+ source: {
+ kind: NodeKind.FunnelsQuery,
+ series: [],
+ funnelsFilter: {},
+ },
+ },
+ id: 123,
+ name: 'My Funnel',
+ }
+ const url = getInsightDefinitionUrl(savedInsight, 'https://app.posthog.com')
+ expect(url).toMatch(/^https:\/\/app\.posthog\.com\/insights\/new#insight=FUNNELS&q=%7B.*%7D(%20)?$/)
+ expect(url).not.toContain('/project/')
+ })
+})
diff --git a/frontend/src/lib/components/Sharing/SharingModal.tsx b/frontend/src/lib/components/Sharing/SharingModal.tsx
index 917ce3f8d740..c76e6114ffab 100644
--- a/frontend/src/lib/components/Sharing/SharingModal.tsx
+++ b/frontend/src/lib/components/Sharing/SharingModal.tsx
@@ -29,14 +29,15 @@ import { Tooltip } from 'lib/lemon-ui/Tooltip'
import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
import { accessLevelSatisfied } from 'lib/utils/accessControlUtils'
import { copyToClipboard } from 'lib/utils/copyToClipboard'
-import { getInsightDefinitionUrl } from 'lib/utils/insightLinks'
import { insightVizDataLogic } from 'scenes/insights/insightVizDataLogic'
import { preflightLogic } from 'scenes/PreflightCheck/preflightLogic'
import { projectLogic } from 'scenes/projectLogic'
import { urls } from 'scenes/urls'
import { AccessControlPopoutCTA } from '~/layout/navigation-3000/sidepanel/panels/access_control/AccessControlPopoutCTA'
+import { nodeKindToInsightType } from '~/queries/nodes/InsightQuery/utils/queryNodeToFilter'
import { AnyResponseType, Node } from '~/queries/schema/schema-general'
+import { NodeKind } from '~/queries/schema/schema-general'
import { isDataTableNode, isDataVisualizationNode, isInsightVizNode } from '~/queries/utils'
import {
AccessControlLevel,
@@ -45,6 +46,7 @@ import {
InsightShortId,
QueryBasedInsightModel,
} from '~/types'
+import { InsightType } from '~/types'
import { AccessControlAction } from '../AccessControlAction'
import { upgradeModalLogic } from '../UpgradeModal/upgradeModalLogic'
@@ -734,3 +736,40 @@ SharingModal.open = (props: SharingModalBaseProps) => {
},
})
}
+
+/**
+ * Build a canonical definition-based insight link ("template link").
+ * The link always points to `/insights/new` on the provided baseUrl and includes:
+ * #insight=<InsightType>&q=<URL-encoded JSON definition>
+ *
+ * It works for both saved insights (where `query` is persisted on the model)
+ * and unsaved/draft insights (pass the raw query object).
+ */
+export function getInsightDefinitionUrl(
+ insight: Pick<QueryBasedInsightModel, 'query'> | { query: Node<Record<string, any>> },
+ baseUrl: string
+): string {
+ if (!insight?.query) {
+ throw new Error('getInsightDefinitionUrl: insight.query is required')
+ }
+
+ // Derive InsightType from the query where possible so the #insight=<TYPE> hash param is present
+ let insightType: InsightType | undefined
+ type InsightVizNode = { kind: NodeKind.InsightVizNode; source?: { kind?: string } }
+ const kind = (
+ insight.query.kind === NodeKind.InsightVizNode
+ ? (insight.query as InsightVizNode).source?.kind
+ : insight.query.kind
+ ) as keyof typeof nodeKindToInsightType | undefined
+
+ if (kind && kind in nodeKindToInsightType) {
+ insightType = nodeKindToInsightType[kind as keyof typeof nodeKindToInsightType]
+ }
+
+ const relativeUrl = urls.insightNew({ query: insight.query, type: insightType })
+
+ // Ensure the link is project-agnostic (`/project/<id>` may get injected elsewhere)
+ const cleanedPath = relativeUrl.replace(/^\/project\/[^/]+/, '')
+
+ return `${baseUrl}${cleanedPath}`
+}
diff --git a/frontend/src/lib/components/SimpleKeyValueList.tsx b/frontend/src/lib/components/SimpleKeyValueList.tsx
index 4d75e5255947..54fd5627f377 100644
--- a/frontend/src/lib/components/SimpleKeyValueList.tsx
+++ b/frontend/src/lib/components/SimpleKeyValueList.tsx
@@ -4,7 +4,7 @@ import { ReactNode, useMemo, useState } from 'react'
import { JSONViewer } from 'lib/components/JSONViewer'
import { PropertyKeyInfo } from 'lib/components/PropertyKeyInfo'
import { TaxonomicFilterGroupType } from 'lib/components/TaxonomicFilter/types'
-import { isObject } from 'lib/utils'
+import { isObject } from 'lib/utils/guards'
import { getCoreFilterDefinition } from '~/taxonomy/helpers'
diff --git a/frontend/src/lib/components/Sparkline.tsx b/frontend/src/lib/components/Sparkline.tsx
index 73dd8987773d..995b4deb9109 100644
--- a/frontend/src/lib/components/Sparkline.tsx
+++ b/frontend/src/lib/components/Sparkline.tsx
@@ -9,7 +9,8 @@ import { getColorVar } from 'lib/colors'
import { useChart } from 'lib/hooks/useChart'
import { useEventListener } from 'lib/hooks/useEventListener'
import { useKeyboardHotkeys } from 'lib/hooks/useKeyboardHotkeys'
-import { hexToRGBA, humanFriendlyNumber } from 'lib/utils'
+import { hexToRGBA } from 'lib/utils/colors'
+import { humanFriendlyNumber } from 'lib/utils/numbers'
import { InsightTooltip } from 'scenes/insights/InsightTooltip/InsightTooltip'
import { LemonSkeleton } from '../lemon-ui/LemonSkeleton'
diff --git a/frontend/src/lib/components/Subscriptions/SubscriptionsModal.stories.tsx b/frontend/src/lib/components/Subscriptions/SubscriptionsModal.stories.tsx
index 1c7ef8c6dad4..54b0fa727d6e 100644
--- a/frontend/src/lib/components/Subscriptions/SubscriptionsModal.stories.tsx
+++ b/frontend/src/lib/components/Subscriptions/SubscriptionsModal.stories.tsx
@@ -6,7 +6,7 @@ import { useEffect, useRef, useState } from 'react'
import { FEATURE_FLAGS } from 'lib/constants'
import { LemonButton } from 'lib/lemon-ui/LemonButton'
import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
-import { uuid } from 'lib/utils'
+import { uuid } from 'lib/utils/dom'
import { useStorybookMocks } from '~/mocks/browser'
import preflightJson from '~/mocks/fixtures/_preflight.json'
diff --git a/frontend/src/lib/components/Subscriptions/subscriptionLogic.ts b/frontend/src/lib/components/Subscriptions/subscriptionLogic.ts
index dfb639f80afe..177cca430c50 100644
--- a/frontend/src/lib/components/Subscriptions/subscriptionLogic.ts
+++ b/frontend/src/lib/components/Subscriptions/subscriptionLogic.ts
@@ -8,7 +8,7 @@ import api, { ApiError } from 'lib/api'
import { dayjs } from 'lib/dayjs'
import { recordRecentSlackChannel, slackChannelId } from 'lib/integrations/slackChannel'
import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'
-import { isEmail } from 'lib/utils'
+import { isEmail } from 'lib/utils/url'
import { getInsightId } from 'scenes/insights/utils'
import { ExportedAssetType, ExporterFormat, SubscriptionResourceTypes, SubscriptionType } from '~/types'
diff --git a/frontend/src/lib/components/Subscriptions/utils.tsx b/frontend/src/lib/components/Subscriptions/utils.tsx
index c57464e9a0e1..b9e76af1dbd8 100644
--- a/frontend/src/lib/components/Subscriptions/utils.tsx
+++ b/frontend/src/lib/components/Subscriptions/utils.tsx
@@ -4,7 +4,7 @@ import { IconLetter } from '@posthog/icons'
import { LemonSelectOption, LemonSelectOptionLeaf, LemonSelectOptions } from '@posthog/lemon-ui'
import { IconSlack } from 'lib/lemon-ui/icons'
-import { range } from 'lib/utils'
+import { range } from 'lib/utils/arrays'
import { urls } from 'scenes/urls'
import { SubscriptionAIPromptMaxLength } from '~/queries/schema/schema-general'
diff --git a/frontend/src/lib/components/Subscriptions/views/ManageSubscriptions.tsx b/frontend/src/lib/components/Subscriptions/views/ManageSubscriptions.tsx
index fd1a2518c1d1..31475ebf86fe 100644
--- a/frontend/src/lib/components/Subscriptions/views/ManageSubscriptions.tsx
+++ b/frontend/src/lib/components/Subscriptions/views/ManageSubscriptions.tsx
@@ -10,7 +10,7 @@ import { LemonModal } from 'lib/lemon-ui/LemonModal'
import { LemonSkeleton } from 'lib/lemon-ui/LemonSkeleton'
import { ProfileBubbles } from 'lib/lemon-ui/ProfilePicture'
import { Spinner } from 'lib/lemon-ui/Spinner'
-import { capitalizeFirstLetter, pluralize } from 'lib/utils'
+import { capitalizeFirstLetter, pluralize } from 'lib/utils/strings'
import { isSubscriptionEnabled } from 'scenes/subscriptions/components/SubscriptionsTable'
import { urls } from 'scenes/urls'
diff --git a/frontend/src/lib/utils/exceptionUtils.ts b/frontend/src/lib/components/Support/exceptionUtils.ts
similarity index 93%
rename from frontend/src/lib/utils/exceptionUtils.ts
rename to frontend/src/lib/components/Support/exceptionUtils.ts
index 9e184680fa9f..c7579fd1e304 100644
--- a/frontend/src/lib/utils/exceptionUtils.ts
+++ b/frontend/src/lib/components/Support/exceptionUtils.ts
@@ -1,6 +1,7 @@
// Utility functions for parsing PostHog exception events
+// Only used to properly forward an exception information via the support form
-export interface ExceptionMetadata {
+interface ExceptionMetadata {
uuid: string
commitSha: string
feature: string
@@ -8,13 +9,13 @@ export interface ExceptionMetadata {
exceptionValue: string
}
-export interface StackTraceInfo {
+interface StackTraceInfo {
filename: string
functionName: string
lineNumber: string
}
-export type ParsedExceptionData = string
+type ParsedExceptionData = string
/**
* Extracts basic metadata from a PostHog exception event
diff --git a/frontend/src/lib/components/Support/supportLogic.ts b/frontend/src/lib/components/Support/supportLogic.ts
index ddec6f16c0d8..ecdbd47906a6 100644
--- a/frontend/src/lib/components/Support/supportLogic.ts
+++ b/frontend/src/lib/components/Support/supportLogic.ts
@@ -7,8 +7,7 @@ import { LemonSelectOptions } from '@posthog/lemon-ui'
import api from 'lib/api'
import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'
-import { uuid } from 'lib/utils'
-import { parseExceptionEvent } from 'lib/utils/exceptionUtils'
+import { uuid } from 'lib/utils/dom'
import { billingLogic } from 'scenes/billing/billingLogic'
import { organizationLogic } from 'scenes/organizationLogic'
import { preflightLogic } from 'scenes/PreflightCheck/preflightLogic'
@@ -27,6 +26,7 @@ import {
UserType,
} from '~/types'
+import { parseExceptionEvent } from './exceptionUtils'
import type { supportLogicType } from './supportLogicType'
import { openSupportModal } from './SupportModal'
@@ -399,6 +399,16 @@ export const SUPPORT_TICKET_TEMPLATES = {
"Please explain as fully as possible what you're aiming to do, and what you'd like help with.\n\nIf your question involves an existing insight or dashboard, please include a link to it.",
}
+const SUPPORT_TICKET_CUSTOM_FIELD_IDENTIFIERS = {
+ severity: 22084126888475,
+ distinct_id: 22129191462555,
+ target_area: 27242745654043,
+ organization_id: 27031528411291,
+ support_type: 26073267652251,
+ account_owner: 37742340880411,
+ exception_event: 39967113285659,
+} as const
+
export function getURLPathToTargetArea(pathname: string): SupportTicketTargetArea | null {
const pathParts = pathname.split('/')
@@ -666,23 +676,23 @@ export const supportLogic = kea<supportLogicType>([
tags: [planLevelTag, accountOwnerTag, ...(tags || [])],
custom_fields: [
{
- id: 22084126888475,
+ id: SUPPORT_TICKET_CUSTOM_FIELD_IDENTIFIERS.severity,
value: severity_level,
},
{
- id: 22129191462555,
+ id: SUPPORT_TICKET_CUSTOM_FIELD_IDENTIFIERS.distinct_id,
value: posthog.get_distinct_id(),
},
{
- id: 27242745654043,
+ id: SUPPORT_TICKET_CUSTOM_FIELD_IDENTIFIERS.target_area,
value: target_area ?? '',
},
{
- id: 27031528411291,
+ id: SUPPORT_TICKET_CUSTOM_FIELD_IDENTIFIERS.organization_id,
value: userLogic?.values?.user?.organization?.id ?? '',
},
{
- id: 26073267652251,
+ id: SUPPORT_TICKET_CUSTOM_FIELD_IDENTIFIERS.support_type,
value: values.hasAvailableFeature(AvailableFeature.PRIORITY_SUPPORT)
? 'priority_support'
: values.hasAvailableFeature(AvailableFeature.EMAIL_SUPPORT)
@@ -690,11 +700,11 @@ export const supportLogic = kea<supportLogicType>([
: 'free_support',
},
{
- id: 37742340880411,
+ id: SUPPORT_TICKET_CUSTOM_FIELD_IDENTIFIERS.account_owner,
value: accountOwner?.name || 'unassigned',
},
{
- id: 39967113285659,
+ id: SUPPORT_TICKET_CUSTOM_FIELD_IDENTIFIERS.exception_event,
value: exception_event ? parseExceptionEvent(exception_event) : '',
},
],
diff --git a/frontend/src/lib/components/SupportedPlatforms/SupportedPlatforms.tsx b/frontend/src/lib/components/SupportedPlatforms/SupportedPlatforms.tsx
index 27c5afa92a5a..ea99d9bac76f 100644
--- a/frontend/src/lib/components/SupportedPlatforms/SupportedPlatforms.tsx
+++ b/frontend/src/lib/components/SupportedPlatforms/SupportedPlatforms.tsx
@@ -3,8 +3,8 @@ import { Fragment, memo } from 'react'
import { IconCheck, IconInfo, IconX } from '@posthog/icons'
import { LemonDivider, Tooltip } from '@posthog/lemon-ui'
-import { isObject } from 'lib/utils'
import { cn } from 'lib/utils/css-classes'
+import { isObject } from 'lib/utils/guards'
import { PlatformSupport, PlatformSupportConfig } from './types'
diff --git a/frontend/src/lib/components/SurveyResponseDisplay/SurveyResponseDisplay.tsx b/frontend/src/lib/components/SurveyResponseDisplay/SurveyResponseDisplay.tsx
index 4e21f9495d22..f047505e5d42 100644
--- a/frontend/src/lib/components/SurveyResponseDisplay/SurveyResponseDisplay.tsx
+++ b/frontend/src/lib/components/SurveyResponseDisplay/SurveyResponseDisplay.tsx
@@ -7,7 +7,7 @@ import { LemonDivider, LemonTag, Link } from '@posthog/lemon-ui'
import { TZLabel } from 'lib/components/TZLabel'
import ViewRecordingButton, { ViewRecordingButtonVariant } from 'lib/components/ViewRecordingButton/ViewRecordingButton'
import { IconLink } from 'lib/lemon-ui/icons'
-import { countryCodeToFlag } from 'lib/utils/geography/country'
+import { countryCodeToFlag } from 'lib/utils/country'
import { PersonDisplay } from 'scenes/persons/PersonDisplay'
import { getThumbIcon } from 'scenes/surveys/hooks/useSurveyResponseColumns'
import { surveyLogic } from 'scenes/surveys/surveyLogic'
diff --git a/frontend/src/lib/components/TZLabel/index.tsx b/frontend/src/lib/components/TZLabel/index.tsx
index 80c0acdb900e..ad482a1def41 100644
--- a/frontend/src/lib/components/TZLabel/index.tsx
+++ b/frontend/src/lib/components/TZLabel/index.tsx
@@ -11,10 +11,11 @@ import { dayjs } from 'lib/dayjs'
import { useOnMountEffect } from 'lib/hooks/useOnMountEffect'
import { usePageVisibility } from 'lib/hooks/usePageVisibility'
import { IconLinux, IconWeb } from 'lib/lemon-ui/icons'
-import { humanFriendlyDetailedTime, shortTimeZone } from 'lib/utils'
import { copyToClipboard } from 'lib/utils/copyToClipboard'
import { cn } from 'lib/utils/css-classes'
+import { humanFriendlyDetailedTime } from 'lib/utils/datetime'
import { eventUsageLogic } from 'lib/utils/eventUsageLogic'
+import { shortTimeZone } from 'lib/utils/timezones'
import { urls } from 'scenes/urls'
import { teamLogic } from '../../../scenes/teamLogic'
diff --git a/frontend/src/lib/components/TakeScreenshot/ScreenShotEditor.tsx b/frontend/src/lib/components/TakeScreenshot/ScreenShotEditor.tsx
index 2ebe459f682d..70562229ce9c 100644
--- a/frontend/src/lib/components/TakeScreenshot/ScreenShotEditor.tsx
+++ b/frontend/src/lib/components/TakeScreenshot/ScreenShotEditor.tsx
@@ -6,7 +6,7 @@ import { LemonButton, LemonColorPicker, LemonInput, LemonModal, LemonSelect } fr
import { getSeriesColorPalette } from 'lib/colors'
import { Spinner } from 'lib/lemon-ui/Spinner/Spinner'
-import { downloadFile } from 'lib/utils'
+import { downloadFile } from 'lib/utils/dom'
import { FilmCameraHog } from '../hedgehogs'
import {
diff --git a/frontend/src/lib/components/TaxonomicFilter/InfiniteList.tsx b/frontend/src/lib/components/TaxonomicFilter/InfiniteList.tsx
index 7772259eec4d..4595b735eb71 100644
--- a/frontend/src/lib/components/TaxonomicFilter/InfiniteList.tsx
+++ b/frontend/src/lib/components/TaxonomicFilter/InfiniteList.tsx
@@ -35,10 +35,10 @@ import { LemonRow } from 'lib/lemon-ui/LemonRow'
import { LemonSkeleton } from 'lib/lemon-ui/LemonSkeleton'
import { Spinner } from 'lib/lemon-ui/Spinner/Spinner'
import { Tooltip } from 'lib/lemon-ui/Tooltip'
-import { pluralize } from 'lib/utils'
import { cn } from 'lib/utils/css-classes'
import { isDefinitionStale } from 'lib/utils/definitions'
import { eventUsageLogic } from 'lib/utils/eventUsageLogic'
+import { pluralize } from 'lib/utils/strings'
import { getCoreFilterDefinition } from '~/taxonomy/helpers'
import { EventDefinition, PropertyDefinition } from '~/types'
diff --git a/frontend/src/lib/components/TaxonomicFilter/eventTypeShortcuts.test.ts b/frontend/src/lib/components/TaxonomicFilter/eventTypeShortcuts.test.ts
index 2755fbb85e6d..3443de54fcc2 100644
--- a/frontend/src/lib/components/TaxonomicFilter/eventTypeShortcuts.test.ts
+++ b/frontend/src/lib/components/TaxonomicFilter/eventTypeShortcuts.test.ts
@@ -1,4 +1,4 @@
-import { eventTypeToVerb } from 'lib/utils'
+import { eventTypeToVerb } from 'lib/utils/events'
import {
AUTOCAPTURE_INTERACTIONS,
diff --git a/frontend/src/lib/components/TaxonomicFilter/eventTypeShortcuts.ts b/frontend/src/lib/components/TaxonomicFilter/eventTypeShortcuts.ts
index 3d24bdfd1ee8..68ba79aa9148 100644
--- a/frontend/src/lib/components/TaxonomicFilter/eventTypeShortcuts.ts
+++ b/frontend/src/lib/components/TaxonomicFilter/eventTypeShortcuts.ts
@@ -1,4 +1,4 @@
-import { eventTypeToVerb } from 'lib/utils'
+import { eventTypeToVerb } from 'lib/utils/events'
import { PropertyFilterType, PropertyOperator } from '~/types'
diff --git a/frontend/src/lib/components/TaxonomicFilter/recentTaxonomicFiltersLogic.ts b/frontend/src/lib/components/TaxonomicFilter/recentTaxonomicFiltersLogic.ts
index 18bd0a172423..c38f37f112be 100644
--- a/frontend/src/lib/components/TaxonomicFilter/recentTaxonomicFiltersLogic.ts
+++ b/frontend/src/lib/components/TaxonomicFilter/recentTaxonomicFiltersLogic.ts
@@ -1,8 +1,8 @@
import { actions, kea, path, reducers, selectors } from 'kea'
import { now } from 'lib/dayjs'
-import { isOperatorFlag } from 'lib/utils'
import { permanentlyMount } from 'lib/utils/kea-logic-builders'
+import { isOperatorFlag } from 'lib/utils/operators'
import { AnyPropertyFilter } from '~/types'
diff --git a/frontend/src/lib/components/TaxonomicFilter/taxonomicFilterLogic.tsx b/frontend/src/lib/components/TaxonomicFilter/taxonomicFilterLogic.tsx
index 1c114dfd48a0..0ef955665ed3 100644
--- a/frontend/src/lib/components/TaxonomicFilter/taxonomicFilterLogic.tsx
+++ b/frontend/src/lib/components/TaxonomicFilter/taxonomicFilterLogic.tsx
@@ -53,9 +53,12 @@ import { FEATURE_FLAGS } from 'lib/constants'
import { IconCohort } from 'lib/lemon-ui/icons'
import { Link } from 'lib/lemon-ui/Link'
import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
-import { capitalizeFirstLetter, isString, objectsEqual, pluralize, toParams } from 'lib/utils'
import { isDefinitionStale } from 'lib/utils/definitions'
-import { getPrimaryPropertyForEvent } from 'lib/utils/primaryEventProperty'
+import { getPrimaryPropertyForEvent } from 'lib/utils/events'
+import { isString } from 'lib/utils/guards'
+import { objectsEqual } from 'lib/utils/objects'
+import { capitalizeFirstLetter, pluralize } from 'lib/utils/strings'
+import { toParams } from 'lib/utils/url'
import {
getEventDefinitionIcon,
getEventMetadataDefinitionIcon,
diff --git a/frontend/src/lib/components/TaxonomicFilter/utils/buildGroupAnalyticsGroups.ts b/frontend/src/lib/components/TaxonomicFilter/utils/buildGroupAnalyticsGroups.ts
index 5c27e97af2d0..b4783d7ae54d 100644
--- a/frontend/src/lib/components/TaxonomicFilter/utils/buildGroupAnalyticsGroups.ts
+++ b/frontend/src/lib/components/TaxonomicFilter/utils/buildGroupAnalyticsGroups.ts
@@ -1,7 +1,8 @@
import { combineUrl } from 'kea-router'
import { TaxonomicFilterGroup, TaxonomicFilterGroupType } from 'lib/components/TaxonomicFilter/types'
-import { capitalizeFirstLetter, toParams } from 'lib/utils'
+import { capitalizeFirstLetter } from 'lib/utils/strings'
+import { toParams } from 'lib/utils/url'
import { getPropertyDefinitionIcon } from 'scenes/data-management/events/DefinitionHeader'
import { groupDisplayId } from 'scenes/persons/GroupActorDisplay'
diff --git a/frontend/src/lib/components/TaxonomicFilter/utils/buildTaxonomicGroups.tsx b/frontend/src/lib/components/TaxonomicFilter/utils/buildTaxonomicGroups.tsx
index 75cdb79c212b..29c28c8aaa4f 100644
--- a/frontend/src/lib/components/TaxonomicFilter/utils/buildTaxonomicGroups.tsx
+++ b/frontend/src/lib/components/TaxonomicFilter/utils/buildTaxonomicGroups.tsx
@@ -20,7 +20,8 @@ import { withKeywordShortcuts } from 'lib/components/TaxonomicFilter/utils/keywo
import { FEATURE_FLAGS } from 'lib/constants'
import { IconCohort } from 'lib/lemon-ui/icons'
import { Link } from 'lib/lemon-ui/Link'
-import { isString, pluralize } from 'lib/utils'
+import { isString } from 'lib/utils/guards'
+import { pluralize } from 'lib/utils/strings'
import {
getEventDefinitionIcon,
getEventMetadataDefinitionIcon,
diff --git a/frontend/src/lib/components/TerraformExporter/useTerraformExport.ts b/frontend/src/lib/components/TerraformExporter/useTerraformExport.ts
index 9cf06bf70f32..f18a8190cbeb 100644
--- a/frontend/src/lib/components/TerraformExporter/useTerraformExport.ts
+++ b/frontend/src/lib/components/TerraformExporter/useTerraformExport.ts
@@ -2,7 +2,7 @@ import { useValues } from 'kea'
import posthog from 'posthog-js'
import { useCallback, useEffect, useRef, useState } from 'react'
-import { buildAlertFilterConfig } from 'lib/utils/alertUtils'
+import { buildAlertFilterConfig } from 'lib/utils/alerts'
import { teamLogic } from 'scenes/teamLogic'
import { AlertType } from '~/lib/components/Alerts/types'
diff --git a/frontend/src/lib/components/TimelineSeekbar/TimelineSeekbar.tsx b/frontend/src/lib/components/TimelineSeekbar/TimelineSeekbar.tsx
index 665a91408941..ba8a74a838cf 100644
--- a/frontend/src/lib/components/TimelineSeekbar/TimelineSeekbar.tsx
+++ b/frontend/src/lib/components/TimelineSeekbar/TimelineSeekbar.tsx
@@ -7,7 +7,8 @@ import { LemonBadge } from '@posthog/lemon-ui'
import { Dayjs } from 'lib/dayjs'
import { Spinner } from 'lib/lemon-ui/Spinner/Spinner'
import { Tooltip } from 'lib/lemon-ui/Tooltip'
-import { humanFriendlyDetailedTime, pluralize } from 'lib/utils'
+import { humanFriendlyDetailedTime } from 'lib/utils/datetime'
+import { pluralize } from 'lib/utils/strings'
export interface TimelinePoint {
timestamp: Dayjs
diff --git a/frontend/src/lib/components/UnitPicker/GlobalCustomUnitModal.tsx b/frontend/src/lib/components/UnitPicker/GlobalCustomUnitModal.tsx
index f0ed3fa7a3d6..a65cb52f9e8b 100644
--- a/frontend/src/lib/components/UnitPicker/GlobalCustomUnitModal.tsx
+++ b/frontend/src/lib/components/UnitPicker/GlobalCustomUnitModal.tsx
@@ -5,7 +5,7 @@ import { LemonButton } from 'lib/lemon-ui/LemonButton'
import { LemonField } from 'lib/lemon-ui/LemonField'
import { LemonInput } from 'lib/lemon-ui/LemonInput/LemonInput'
import { LemonModal } from 'lib/lemon-ui/LemonModal'
-import { capitalizeFirstLetter } from 'lib/utils'
+import { capitalizeFirstLetter } from 'lib/utils/strings'
import { unitPickerModalLogic } from './unitPickerModalLogic'
diff --git a/frontend/src/lib/components/UniversalFilters/UniversalFilterButton.tsx b/frontend/src/lib/components/UniversalFilters/UniversalFilterButton.tsx
index 137dcd4cbe20..b8b695d6d055 100644
--- a/frontend/src/lib/components/UniversalFilters/UniversalFilterButton.tsx
+++ b/frontend/src/lib/components/UniversalFilters/UniversalFilterButton.tsx
@@ -9,7 +9,7 @@ import { LemonButton, PopoverReferenceContext } from '@posthog/lemon-ui'
import { PropertyFilterIcon } from 'lib/components/PropertyFilters/components/PropertyFilterIcon'
import { IconWithCount } from 'lib/lemon-ui/icons'
-import { midEllipsis } from 'lib/utils'
+import { midEllipsis } from 'lib/utils/strings'
import { cohortsModel } from '~/models/cohortsModel'
import { propertyDefinitionsModel } from '~/models/propertyDefinitionsModel'
diff --git a/frontend/src/lib/components/UserSelectItem.tsx b/frontend/src/lib/components/UserSelectItem.tsx
index 94c0290dede1..229de1d1ce9d 100644
--- a/frontend/src/lib/components/UserSelectItem.tsx
+++ b/frontend/src/lib/components/UserSelectItem.tsx
@@ -1,6 +1,6 @@
import { LemonInputSelectOption } from 'lib/lemon-ui/LemonInputSelect'
import { ProfilePicture } from 'lib/lemon-ui/ProfilePicture'
-import { fullName } from 'lib/utils'
+import { fullName } from 'lib/utils/strings'
import { UserBasicType, UserType } from '~/types'
diff --git a/frontend/src/lib/components/heatmaps/HeatmapEventsPanel.tsx b/frontend/src/lib/components/heatmaps/HeatmapEventsPanel.tsx
index f40130780f09..995d6bbed24b 100644
--- a/frontend/src/lib/components/heatmaps/HeatmapEventsPanel.tsx
+++ b/frontend/src/lib/components/heatmaps/HeatmapEventsPanel.tsx
@@ -6,7 +6,7 @@ import { LemonButton } from 'lib/lemon-ui/LemonButton'
import { LemonModal } from 'lib/lemon-ui/LemonModal'
import { LemonSkeleton } from 'lib/lemon-ui/LemonSkeleton'
import { LemonTable, LemonTableColumns } from 'lib/lemon-ui/LemonTable'
-import { humanFriendlyDetailedTime } from 'lib/utils'
+import { humanFriendlyDetailedTime } from 'lib/utils/datetime'
import { PersonDisplay } from 'scenes/persons/PersonDisplay'
import { urls } from 'scenes/urls'
diff --git a/frontend/src/lib/components/heatmaps/heatmapDataLogic.ts b/frontend/src/lib/components/heatmaps/heatmapDataLogic.ts
index 1104c783f21e..2f55c356eb38 100644
--- a/frontend/src/lib/components/heatmaps/heatmapDataLogic.ts
+++ b/frontend/src/lib/components/heatmaps/heatmapDataLogic.ts
@@ -21,7 +21,7 @@ import {
} from 'lib/components/IframedToolbarBrowser/utils'
import { LemonSelectOption } from 'lib/lemon-ui/LemonSelect'
import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'
-import { dateFilterToText } from 'lib/utils'
+import { dateFilterToText } from 'lib/utils/dateFilters'
import { getAppContext } from 'lib/utils/getAppContext'
import { toolbarConfigLogic, toolbarFetch } from '~/toolbar/toolbarConfigLogic'
diff --git a/frontend/src/lib/holidays.tsx b/frontend/src/lib/holidays.tsx
index 36d34302bc0d..e4d77c687ba9 100644
--- a/frontend/src/lib/holidays.tsx
+++ b/frontend/src/lib/holidays.tsx
@@ -1,7 +1,8 @@
import posthog from 'posthog-js'
+import { inStorybook, inStorybookTestRunner } from 'lib/utils/dom'
+
import { FEATURE_FLAGS } from './constants'
-import { inStorybook, inStorybookTestRunner } from './utils'
// Please remember that in Javascript months are 0-indexed
// January is 0 and December is 11
diff --git a/frontend/src/lib/hooks/useFeatureFlag.ts b/frontend/src/lib/hooks/useFeatureFlag.ts
index 5307355ce1e4..c6cf475e9522 100644
--- a/frontend/src/lib/hooks/useFeatureFlag.ts
+++ b/frontend/src/lib/hooks/useFeatureFlag.ts
@@ -2,7 +2,7 @@ import { useValues } from 'kea'
import { FEATURE_FLAGS } from 'lib/constants'
import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
-import { inStorybook, inStorybookTestRunner } from 'lib/utils'
+import { inStorybook, inStorybookTestRunner } from 'lib/utils/dom'
export const useFeatureFlag = (flag: keyof typeof FEATURE_FLAGS, match?: string): boolean => {
const { featureFlags } = useValues(featureFlagLogic)
diff --git a/frontend/src/lib/integrations/integrationsLogic.ts b/frontend/src/lib/integrations/integrationsLogic.ts
index a4d430c67942..3f784b5c8b64 100644
--- a/frontend/src/lib/integrations/integrationsLogic.ts
+++ b/frontend/src/lib/integrations/integrationsLogic.ts
@@ -6,7 +6,8 @@ import { LemonDialog, lemonToast } from '@posthog/lemon-ui'
import api, { ApiError, getCookie } from 'lib/api'
import { globalSetupLogic } from 'lib/components/ProductSetup'
-import { fromParamsGivenUrl, isKeyOf } from 'lib/utils'
+import { isKeyOf } from 'lib/utils/guards'
+import { fromParamsGivenUrl } from 'lib/utils/url'
import { preflightLogic } from 'scenes/PreflightCheck/preflightLogic'
import { teamLogic } from 'scenes/teamLogic'
import { urls } from 'scenes/urls'
diff --git a/frontend/src/lib/integrations/utils.ts b/frontend/src/lib/integrations/utils.ts
index 55923c2eb04e..db2da70f995e 100644
--- a/frontend/src/lib/integrations/utils.ts
+++ b/frontend/src/lib/integrations/utils.ts
@@ -1,4 +1,4 @@
-import { capitalizeFirstLetter } from 'lib/utils'
+import { capitalizeFirstLetter } from 'lib/utils/strings'
import { IntegrationKind } from '~/types'
diff --git a/frontend/src/lib/lemon-ui/LemonBadge/LemonBadge.tsx b/frontend/src/lib/lemon-ui/LemonBadge/LemonBadge.tsx
index ca2fa9c4071f..aa9c0ce049e9 100644
--- a/frontend/src/lib/lemon-ui/LemonBadge/LemonBadge.tsx
+++ b/frontend/src/lib/lemon-ui/LemonBadge/LemonBadge.tsx
@@ -3,7 +3,7 @@ import './LemonBadge.scss'
import clsx from 'clsx'
import { forwardRef } from 'react'
-import { compactNumber, humanFriendlyNumber } from 'lib/utils'
+import { compactNumber, humanFriendlyNumber } from 'lib/utils/numbers'
interface LemonBadgePropsBase {
size?: 'xsmall' | 'small' | 'medium' | 'large'
diff --git a/frontend/src/lib/lemon-ui/LemonButton/LemonButton.stories.tsx b/frontend/src/lib/lemon-ui/LemonButton/LemonButton.stories.tsx
index 2503ad88c1f1..286322d01ee5 100644
--- a/frontend/src/lib/lemon-ui/LemonButton/LemonButton.stories.tsx
+++ b/frontend/src/lib/lemon-ui/LemonButton/LemonButton.stories.tsx
@@ -8,7 +8,8 @@ import { AccessControlAction } from 'lib/components/AccessControlAction'
import { IconCalculate, IconLink } from 'lib/lemon-ui/icons'
import { LemonBanner } from 'lib/lemon-ui/LemonBanner'
import { LemonDivider } from 'lib/lemon-ui/LemonDivider'
-import { capitalizeFirstLetter, range } from 'lib/utils'
+import { range } from 'lib/utils/arrays'
+import { capitalizeFirstLetter } from 'lib/utils/strings'
import { urls } from 'scenes/urls'
import { AccessControlLevel, AccessControlResourceType } from '~/types'
diff --git a/frontend/src/lib/lemon-ui/LemonCalendar/LemonCalendar.test.tsx b/frontend/src/lib/lemon-ui/LemonCalendar/LemonCalendar.test.tsx
index 5e20df5ca686..d0250342d08e 100644
--- a/frontend/src/lib/lemon-ui/LemonCalendar/LemonCalendar.test.tsx
+++ b/frontend/src/lib/lemon-ui/LemonCalendar/LemonCalendar.test.tsx
@@ -2,7 +2,7 @@ import { render, within } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { dayjs } from 'lib/dayjs'
-import { range } from 'lib/utils'
+import { range } from 'lib/utils/arrays'
import { getAllByDataAttr, getByDataAttr } from '~/test/byDataAttr'
diff --git a/frontend/src/lib/lemon-ui/LemonCalendar/LemonCalendar.tsx b/frontend/src/lib/lemon-ui/LemonCalendar/LemonCalendar.tsx
index 576d399e4fc7..bd2dd3adb168 100644
--- a/frontend/src/lib/lemon-ui/LemonCalendar/LemonCalendar.tsx
+++ b/frontend/src/lib/lemon-ui/LemonCalendar/LemonCalendar.tsx
@@ -9,7 +9,7 @@ import { IconChevronLeft, IconChevronRight } from '@posthog/icons'
import { ScrollableShadows } from 'lib/components/ScrollableShadows/ScrollableShadows'
import { dayjs } from 'lib/dayjs'
import { LemonButton, LemonButtonProps } from 'lib/lemon-ui/LemonButton'
-import { range } from 'lib/utils'
+import { range } from 'lib/utils/arrays'
import { teamLogic } from 'scenes/teamLogic'
export interface LemonCalendarProps {
diff --git a/frontend/src/lib/lemon-ui/LemonCalendar/LemonCalendarSelect.stories.tsx b/frontend/src/lib/lemon-ui/LemonCalendar/LemonCalendarSelect.stories.tsx
index 0ba08a3615a7..30ca6f168d38 100644
--- a/frontend/src/lib/lemon-ui/LemonCalendar/LemonCalendarSelect.stories.tsx
+++ b/frontend/src/lib/lemon-ui/LemonCalendar/LemonCalendarSelect.stories.tsx
@@ -5,7 +5,7 @@ import { dayjs } from 'lib/dayjs'
import { LemonButton } from 'lib/lemon-ui/LemonButton'
import { LemonCalendarSelect, LemonCalendarSelectProps } from 'lib/lemon-ui/LemonCalendar/LemonCalendarSelect'
import { Popover } from 'lib/lemon-ui/Popover/Popover'
-import { formatDate } from 'lib/utils'
+import { formatDate } from 'lib/utils/datetime'
type Story = StoryObj<LemonCalendarSelectProps>
const meta: Meta<LemonCalendarSelectProps> = {
diff --git a/frontend/src/lib/lemon-ui/LemonCalendarRange/LemonCalendarRange.stories.tsx b/frontend/src/lib/lemon-ui/LemonCalendarRange/LemonCalendarRange.stories.tsx
index 27788e9db05b..a56fbb59b639 100644
--- a/frontend/src/lib/lemon-ui/LemonCalendarRange/LemonCalendarRange.stories.tsx
+++ b/frontend/src/lib/lemon-ui/LemonCalendarRange/LemonCalendarRange.stories.tsx
@@ -5,7 +5,7 @@ import { dayjs } from 'lib/dayjs'
import { LemonButton } from 'lib/lemon-ui/LemonButton'
import { LemonCalendarRange, LemonCalendarRangeProps } from 'lib/lemon-ui/LemonCalendarRange/LemonCalendarRange'
import { Popover } from 'lib/lemon-ui/Popover/Popover'
-import { formatDateRange } from 'lib/utils'
+import { formatDateRange } from 'lib/utils/datetime'
type Story = StoryObj<LemonCalendarRangeProps>
const meta: Meta<LemonCalendarRangeProps> = {
diff --git a/frontend/src/lib/lemon-ui/LemonCalendarRange/LemonCalendarRange.tsx b/frontend/src/lib/lemon-ui/LemonCalendarRange/LemonCalendarRange.tsx
index e9ef70c2bd64..e7893c463b4a 100644
--- a/frontend/src/lib/lemon-ui/LemonCalendarRange/LemonCalendarRange.tsx
+++ b/frontend/src/lib/lemon-ui/LemonCalendarRange/LemonCalendarRange.tsx
@@ -6,7 +6,7 @@ import { IconX } from '@posthog/icons'
import { dayjs } from 'lib/dayjs'
import { LemonButton } from 'lib/lemon-ui/LemonButton'
import { LemonSwitch } from 'lib/lemon-ui/LemonSwitch'
-import { formatDate, formatDateRange } from 'lib/utils'
+import { formatDate, formatDateRange } from 'lib/utils/datetime'
import { LemonCalendarRangeInline } from './LemonCalendarRangeInline'
diff --git a/frontend/src/lib/lemon-ui/LemonCalendarRange/LemonCalendarRangeInline.stories.tsx b/frontend/src/lib/lemon-ui/LemonCalendarRange/LemonCalendarRangeInline.stories.tsx
index 1b32b2c4d8b2..275bc62a64ce 100644
--- a/frontend/src/lib/lemon-ui/LemonCalendarRange/LemonCalendarRangeInline.stories.tsx
+++ b/frontend/src/lib/lemon-ui/LemonCalendarRange/LemonCalendarRangeInline.stories.tsx
@@ -3,7 +3,7 @@ import { useState } from 'react'
import { dayjs } from 'lib/dayjs'
import { LemonCalendarRangeProps } from 'lib/lemon-ui/LemonCalendarRange/LemonCalendarRange'
-import { formatDateRange } from 'lib/utils'
+import { formatDateRange } from 'lib/utils/datetime'
import { LemonCalendarRangeInline } from './LemonCalendarRangeInline'
diff --git a/frontend/src/lib/lemon-ui/LemonColor/LemonColorGlyph.tsx b/frontend/src/lib/lemon-ui/LemonColor/LemonColorGlyph.tsx
index 4fc2bd0ab243..2319abd1459b 100644
--- a/frontend/src/lib/lemon-ui/LemonColor/LemonColorGlyph.tsx
+++ b/frontend/src/lib/lemon-ui/LemonColor/LemonColorGlyph.tsx
@@ -3,7 +3,7 @@ import './LemonColorGlyph.scss'
import { useValues } from 'kea'
import { DataColorToken } from 'lib/colors'
-import { RGBToRGBA, hexToRGBA, lightenDarkenColor } from 'lib/utils'
+import { RGBToRGBA, hexToRGBA, lightenDarkenColor } from 'lib/utils/colors'
import { cn } from 'lib/utils/css-classes'
import { dataThemeLogic } from 'scenes/dataThemeLogic'
diff --git a/frontend/src/lib/lemon-ui/LemonColor/utils.ts b/frontend/src/lib/lemon-ui/LemonColor/utils.ts
index 721eafcb7bb7..9f87c635bd05 100644
--- a/frontend/src/lib/lemon-ui/LemonColor/utils.ts
+++ b/frontend/src/lib/lemon-ui/LemonColor/utils.ts
@@ -1,4 +1,4 @@
-import { hexToRGB } from 'lib/utils'
+import { hexToRGB } from 'lib/utils/colors'
type ReferenceColor = { name: string; group: string }
diff --git a/frontend/src/lib/lemon-ui/LemonInputSelect/LemonInputSelect.stories.tsx b/frontend/src/lib/lemon-ui/LemonInputSelect/LemonInputSelect.stories.tsx
index 745286c53d50..747c9f119148 100644
--- a/frontend/src/lib/lemon-ui/LemonInputSelect/LemonInputSelect.stories.tsx
+++ b/frontend/src/lib/lemon-ui/LemonInputSelect/LemonInputSelect.stories.tsx
@@ -1,7 +1,7 @@
import { Meta, StoryObj } from '@storybook/react'
import { useState } from 'react'
-import { capitalizeFirstLetter } from 'lib/utils'
+import { capitalizeFirstLetter } from 'lib/utils/strings'
import { ProfilePicture } from '../ProfilePicture'
import { LemonInputSelect, LemonInputSelectProps } from './LemonInputSelect'
diff --git a/frontend/src/lib/lemon-ui/LemonInputSelect/LemonInputSelect.tsx b/frontend/src/lib/lemon-ui/LemonInputSelect/LemonInputSelect.tsx
index b94c6db6cd3d..fc913e053a6b 100644
--- a/frontend/src/lib/lemon-ui/LemonInputSelect/LemonInputSelect.tsx
+++ b/frontend/src/lib/lemon-ui/LemonInputSelect/LemonInputSelect.tsx
@@ -15,7 +15,7 @@ import { AutoSizer } from 'lib/components/AutoSizer'
import { SortableDragIcon } from 'lib/lemon-ui/icons'
import { LemonSkeleton } from 'lib/lemon-ui/LemonSkeleton'
import { LemonSnack } from 'lib/lemon-ui/LemonSnack/LemonSnack'
-import { range } from 'lib/utils'
+import { range } from 'lib/utils/arrays'
import { createFuse } from 'lib/utils/fuseSearch'
import { KeyboardShortcut } from '~/layout/navigation-3000/components/KeyboardShortcut'
diff --git a/frontend/src/lib/lemon-ui/LemonSelect/LemonSearchableSelect.stories.tsx b/frontend/src/lib/lemon-ui/LemonSelect/LemonSearchableSelect.stories.tsx
index f9e2c955219d..6439c26cb88f 100644
--- a/frontend/src/lib/lemon-ui/LemonSelect/LemonSearchableSelect.stories.tsx
+++ b/frontend/src/lib/lemon-ui/LemonSelect/LemonSearchableSelect.stories.tsx
@@ -2,7 +2,7 @@ import type { Meta, StoryObj } from '@storybook/react'
import { LemonSearchableSelect, LemonSearchableSelectProps, LemonSelectOptions } from '@posthog/lemon-ui'
-import { capitalizeFirstLetter } from 'lib/utils'
+import { capitalizeFirstLetter } from 'lib/utils/strings'
type Story = StoryObj<LemonSearchableSelectProps<any>>
const meta: Meta<LemonSearchableSelectProps<any>> = {
diff --git a/frontend/src/lib/lemon-ui/LemonSelect/LemonSelect.stories.tsx b/frontend/src/lib/lemon-ui/LemonSelect/LemonSelect.stories.tsx
index 4ae54c894321..b8587d678a6f 100644
--- a/frontend/src/lib/lemon-ui/LemonSelect/LemonSelect.stories.tsx
+++ b/frontend/src/lib/lemon-ui/LemonSelect/LemonSelect.stories.tsx
@@ -1,7 +1,7 @@
import type { Meta, StoryObj } from '@storybook/react'
import { AccessControlAction } from 'lib/components/AccessControlAction'
-import { capitalizeFirstLetter } from 'lib/utils'
+import { capitalizeFirstLetter } from 'lib/utils/strings'
import { AccessControlLevel, AccessControlResourceType } from '~/types'
diff --git a/frontend/src/lib/lemon-ui/LemonSkeleton/LemonSkeleton.tsx b/frontend/src/lib/lemon-ui/LemonSkeleton/LemonSkeleton.tsx
index b67a5c4c8de3..1515d1303bf8 100644
--- a/frontend/src/lib/lemon-ui/LemonSkeleton/LemonSkeleton.tsx
+++ b/frontend/src/lib/lemon-ui/LemonSkeleton/LemonSkeleton.tsx
@@ -2,7 +2,7 @@ import './LemonSkeleton.scss'
import { useCancelAnimationsOnUnmount } from 'lib/hooks/useCancelAnimationsOnUnmount'
import { LemonButtonProps } from 'lib/lemon-ui/LemonButton'
-import { range } from 'lib/utils'
+import { range } from 'lib/utils/arrays'
import { cn } from 'lib/utils/css-classes'
export interface LemonSkeletonProps {
diff --git a/frontend/src/lib/lemon-ui/LemonToast/LemonToast.tsx b/frontend/src/lib/lemon-ui/LemonToast/LemonToast.tsx
index 27457be2cc5b..6d52c2e09153 100644
--- a/frontend/src/lib/lemon-ui/LemonToast/LemonToast.tsx
+++ b/frontend/src/lib/lemon-ui/LemonToast/LemonToast.tsx
@@ -5,7 +5,7 @@ import { IconCheckCircle, IconInfo, IconWarning, IconX } from '@posthog/icons'
import { getIncidentStatus, STATUS_PAGE_BASE } from 'lib/components/HelpMenu/incidentStatusLogic'
import { isChristmas } from 'lib/holidays'
-import { hashCodeForString } from 'lib/utils'
+import { hashCodeForString } from 'lib/utils/strings'
import { IconErrorOutline, IconGift } from '../icons'
import { LemonButton } from '../LemonButton'
diff --git a/frontend/src/lib/lemon-ui/LemonTree/LemonTree.tsx b/frontend/src/lib/lemon-ui/LemonTree/LemonTree.tsx
index ed7b3364aae6..902d420c3adf 100644
--- a/frontend/src/lib/lemon-ui/LemonTree/LemonTree.tsx
+++ b/frontend/src/lib/lemon-ui/LemonTree/LemonTree.tsx
@@ -28,8 +28,8 @@ import { IconEllipsis, IconUpload } from '@posthog/icons'
import { ScrollableShadows } from 'lib/components/ScrollableShadows/ScrollableShadows'
import { ButtonGroupPrimitive, ButtonPrimitive } from 'lib/ui/Button/ButtonPrimitives'
import { DropdownMenu, DropdownMenuContent, DropdownMenuTrigger } from 'lib/ui/DropdownMenu/DropdownMenu'
-import { pluralize } from 'lib/utils'
import { cn } from 'lib/utils/css-classes'
+import { pluralize } from 'lib/utils/strings'
import { ContextMenu, ContextMenuContent, ContextMenuTrigger } from '../../ui/ContextMenu/ContextMenu'
import { SideAction } from '../LemonButton'
diff --git a/frontend/src/lib/lemon-ui/Lettermark/Lettermark.stories.tsx b/frontend/src/lib/lemon-ui/Lettermark/Lettermark.stories.tsx
index 1fd94ff178db..115ca40ac4ef 100644
--- a/frontend/src/lib/lemon-ui/Lettermark/Lettermark.stories.tsx
+++ b/frontend/src/lib/lemon-ui/Lettermark/Lettermark.stories.tsx
@@ -1,6 +1,6 @@
import type { Meta, StoryObj } from '@storybook/react'
-import { range } from 'lib/utils'
+import { range } from 'lib/utils/arrays'
import { Lettermark, LettermarkColor, LettermarkProps, NUM_LETTERMARK_STYLES } from './Lettermark'
diff --git a/frontend/src/lib/lemon-ui/Link/Link.tsx b/frontend/src/lib/lemon-ui/Link/Link.tsx
index 46e412db7b62..cea0ba02fa8d 100644
--- a/frontend/src/lib/lemon-ui/Link/Link.tsx
+++ b/frontend/src/lib/lemon-ui/Link/Link.tsx
@@ -6,10 +6,10 @@ import React from 'react'
import { IconExternal, IconSend } from '@posthog/icons'
import { ButtonPrimitiveProps, buttonPrimitiveVariants } from 'lib/ui/Button/ButtonPrimitives'
-import { isExternalLink } from 'lib/utils'
import { cn } from 'lib/utils/css-classes'
import { getCurrentTeamId } from 'lib/utils/getAppContext'
-import { addProjectIdIfMissing, removeProjectIdIfPresent } from 'lib/utils/router-utils'
+import { addProjectIdIfMissing, removeProjectIdIfPresent } from 'lib/utils/kea-router'
+import { isExternalLink } from 'lib/utils/url'
import { useNotebookDrag } from 'scenes/notebooks/AddToNotebook/DraggableToNotebook'
import { urlToResource } from 'scenes/urls'
diff --git a/frontend/src/lib/lemon-ui/ProfilePicture/ProfileBubbles.stories.tsx b/frontend/src/lib/lemon-ui/ProfilePicture/ProfileBubbles.stories.tsx
index a58c940911df..09456e450968 100644
--- a/frontend/src/lib/lemon-ui/ProfilePicture/ProfileBubbles.stories.tsx
+++ b/frontend/src/lib/lemon-ui/ProfilePicture/ProfileBubbles.stories.tsx
@@ -1,6 +1,7 @@
import { Meta } from '@storybook/react'
-import { alphabet, range } from 'lib/utils'
+import { range } from 'lib/utils/arrays'
+import { alphabet } from 'lib/utils/strings'
import { ProfileBubbles as ProfileBubblesComponent, ProfileBubblesProps } from './ProfileBubbles'
diff --git a/frontend/src/lib/lemon-ui/ProfilePicture/ProfilePicture.tsx b/frontend/src/lib/lemon-ui/ProfilePicture/ProfilePicture.tsx
index 1df6f47363c4..57af5c0e5c0b 100644
--- a/frontend/src/lib/lemon-ui/ProfilePicture/ProfilePicture.tsx
+++ b/frontend/src/lib/lemon-ui/ProfilePicture/ProfilePicture.tsx
@@ -6,7 +6,8 @@ import md5 from 'md5'
import React, { useEffect, useMemo, useRef, useState } from 'react'
import { HedgehogModeProfile } from 'lib/components/HedgehogMode/HedgehogModeStatic'
-import { fullName, inStorybookTestRunner } from 'lib/utils'
+import { inStorybookTestRunner } from 'lib/utils/dom'
+import { fullName } from 'lib/utils/strings'
import { userLogic } from 'scenes/userLogic'
import { HedgehogConfig, MinimalHedgehogConfig, UserBasicType } from '~/types'
diff --git a/frontend/src/lib/logic/eventIngestionRestrictionLogic.test.ts b/frontend/src/lib/logic/eventIngestionRestrictionLogic.test.ts
index 27b402940fb8..04702959379c 100644
--- a/frontend/src/lib/logic/eventIngestionRestrictionLogic.test.ts
+++ b/frontend/src/lib/logic/eventIngestionRestrictionLogic.test.ts
@@ -3,7 +3,7 @@ import { MOCK_TEAM_ID } from 'lib/api.mock'
import { expectLogic } from 'kea-test-utils'
import api from 'lib/api'
-import { delay } from 'lib/utils'
+import { delay } from 'lib/utils/async'
import { initKeaTests } from '~/test/init'
diff --git a/frontend/src/lib/monaco/CodeEditorImpl.tsx b/frontend/src/lib/monaco/CodeEditorImpl.tsx
index 757e91717ba7..ff9de074ecd7 100644
--- a/frontend/src/lib/monaco/CodeEditorImpl.tsx
+++ b/frontend/src/lib/monaco/CodeEditorImpl.tsx
@@ -20,7 +20,7 @@ import { initHogTemplateLanguage } from 'lib/monaco/languages/hogTemplate'
import { initLiquidLanguage } from 'lib/monaco/languages/liquid'
import { clearLogicReference, initModel } from 'lib/monaco/modelLogicReference'
import { sharedMonacoOverflowRoot } from 'lib/monaco/sharedMonacoOverflowRoot'
-import { inStorybookTestRunner } from 'lib/utils'
+import { inStorybookTestRunner } from 'lib/utils/dom'
import { themeLogic } from '~/layout/navigation-3000/themeLogic'
import { AnyDataNode, HogLanguage, HogQLMetadataResponse, NodeKind } from '~/queries/schema/schema-general'
diff --git a/frontend/src/lib/sortable.ts b/frontend/src/lib/sortable.ts
index 8f25cd598c17..b9d4555e02ba 100644
--- a/frontend/src/lib/sortable.ts
+++ b/frontend/src/lib/sortable.ts
@@ -1,7 +1,8 @@
// Adapted from https://github.com/clauderic/dnd-kit/pull/805 to fix an issue where variable
// height items in a sortable container were not always firing collisions correctly.
-// Should be possible to remove this custom collision detection algorithm once a proper fix
-// is merged into dnd-kit.
+//
+// That PR got closed because dnd-kit is now exposing new React bindings. We should eventually
+// try and move to that to see if this is still needed.
import { CollisionDetection, DroppableContainer, UniqueIdentifier } from '@dnd-kit/core'
export const verticalSortableListCollisionDetection: CollisionDetection = (args) => {
diff --git a/frontend/src/lib/utils.test.ts b/frontend/src/lib/utils.test.ts
deleted file mode 100644
index 0120d116d566..000000000000
--- a/frontend/src/lib/utils.test.ts
+++ /dev/null
@@ -1,1646 +0,0 @@
-import tk from 'timekeeper'
-
-import { dayjs } from 'lib/dayjs'
-
-import { ElementType, EventType, PropertyOperator, PropertyType, TimeUnitType } from '~/types'
-
-import {
- areDatesValidForInterval,
- areObjectValuesEmpty,
- autoCaptureEventToDescription,
- average,
- booleanOperatorMap,
- calculateDays,
- capitalizeFirstLetter,
- ceilMsToClosestSecond,
- chooseOperatorMap,
- colonDelimitedDuration,
- compactNumber,
- dateFilterToText,
- dateMapping,
- dateStringToDayJs,
- dateTimeOperatorMap,
- durationOperatorMap,
- endWithPunctation,
- ensureStringIsNotBlank,
- eventToDescription,
- floorMsToClosestSecond,
- formatDateTimeRange,
- formatPercentageDiff,
- genericOperatorMap,
- getDefaultInterval,
- getFormattedLastWeekDate,
- getRelativeNextPath,
- hexToRGBA,
- humanFriendlyDuration,
- humanFriendlyLargeNumber,
- identifierToHuman,
- is12HoursOrLess,
- isExternalLink,
- isLessThan2Days,
- isOperatorMulti,
- isURL,
- median,
- midEllipsis,
- numericOperatorMap,
- objectClean,
- objectCleanWithEmpty,
- objectDiffShallow,
- parseTagsFilter,
- pluralize,
- range,
- retryWithBackoff,
- reverseColonDelimitedDuration,
- roundToDecimal,
- selectorOperatorMap,
- shortTimeZone,
- stringOperatorMap,
- toParams,
- wordPluralize,
-} from './utils'
-
-describe('lib/utils', () => {
- describe('toParams', () => {
- it('handles unusual input', () => {
- expect(toParams({})).toEqual('')
- expect(toParams([])).toEqual('')
- expect(toParams(undefined as any)).toEqual('')
- expect(toParams(null as any)).toEqual('')
- })
-
- it('can handle numeric values', () => {
- const actual = toParams({ a: 123 })
- expect(actual).toEqual('a=123')
- })
-
- it('encodes arrays as a single query param', () => {
- const actual = toParams({ include: ['a', 'b'] })
- expect(actual).toEqual('include=%5B%22a%22%2C%22b%22%5D')
- })
-
- it('can explode arrays to individual parameters', () => {
- const actual = toParams({ include: ['a', 'b'] }, true)
- expect(actual).toEqual('include=a&include=b')
- })
- })
-
- describe('capitalizeFirstLetter()', () => {
- it('returns the capitalized string', () => {
- expect(capitalizeFirstLetter('jane')).toEqual('Jane')
- expect(capitalizeFirstLetter('hello there!')).toEqual('Hello there!')
- expect(capitalizeFirstLetter('underscores_make_no_difference')).toEqual('Underscores_make_no_difference')
- })
- })
-
- describe('identifierToHuman()', () => {
- it('humanizes properly', () => {
- expect(identifierToHuman('testIdentifier')).toEqual('Test identifier')
- expect(identifierToHuman('testIdentifierX')).toEqual('Test identifier x')
- expect(identifierToHuman('something ')).toEqual('Something')
- expect(identifierToHuman(' some_property')).toEqual('Some property')
- expect(identifierToHuman(' Number666')).toEqual('Number 666')
- expect(identifierToHuman('7x')).toEqual('7x')
- expect(identifierToHuman('7X')).toEqual('7 x')
- expect(identifierToHuman('500')).toEqual('500')
- expect(identifierToHuman(404)).toEqual('404')
- expect(identifierToHuman('CreateProject')).toEqual('Create project')
- expect(identifierToHuman('hog_function/transformation')).toEqual('Hog function transformation')
- })
- })
-
- describe('midEllipsis()', () => {
- it('returns same string if short', () => {
- expect(midEllipsis('12', 10)).toEqual('12')
- expect(midEllipsis('1234567890', 10)).toEqual('1234567890')
- })
-
- it('formats string properly', () => {
- expect(midEllipsis('1234567890', 2)).toEqual('1…')
- expect(midEllipsis('1234567890', 4)).toEqual('12…0')
- expect(midEllipsis('1234567890', 8)).toEqual('1234…890')
- expect(midEllipsis('1234567890', 9)).toEqual('1234…7890')
- expect(midEllipsis('ZgZbZgD9Z4U2FsohDYAJ-hMdoxY7-oSdWwrEWtdBeM', 26)).toEqual('ZgZbZgD9Z4U2F…SdWwrEWtdBeM')
- expect(midEllipsis('ZgZbZgD9Z4U2FsohDYAJ-hMdoxY7-oSdWwrEWtdBeM', 25)).toEqual('ZgZbZgD9Z4U2…SdWwrEWtdBeM')
- expect(midEllipsis('ZgZbZgD9Z4U2FsohDYAJ-hMdoxY7-oSdWwrEWtdBeM', 24)).toEqual('ZgZbZgD9Z4U2…dWwrEWtdBeM')
- })
- })
-
- describe('isURL()', () => {
- it('recognizes URLs properly', () => {
- expect(isURL('https://www.posthog.com')).toEqual(true)
- expect(isURL('http://www.posthog.com')).toEqual(true)
- expect(isURL('http://www.posthog.com:8000/images')).toEqual(true)
- expect(isURL('http://localhost:8000/login?next=/insights')).toEqual(true)
- expect(isURL('http://localhost:8000/activity/explore?properties=%5B%5D')).toEqual(true)
- expect(isURL('https://apple.com/')).toEqual(true)
- expect(isURL('https://stripe.com')).toEqual(true)
- expect(isURL('https://spotify.com')).toEqual(true)
- expect(isURL('https://sevenapp.events/')).toEqual(true)
- expect(isURL('https://seven-stagingenv.web.app/')).toEqual(true)
- expect(isURL('https://salesforce.co.uk/')).toEqual(true)
- expect(isURL('https://valid.*.example.com')).toEqual(true)
- expect(isURL('https://*.valid.com')).toEqual(true)
- })
-
- it('recognizes non-URLs properly', () => {
- expect(isURL('1234567890')).toEqual(false)
- expect(isURL('www.posthog')).toEqual(false)
- expect(isURL('-.posthog')).toEqual(false)
- expect(isURL('posthog.3')).toEqual(false)
- expect(isURL(1)).toEqual(false)
- expect(isURL(true)).toEqual(false)
- expect(isURL(null)).toEqual(false)
- expect(isURL('')).toEqual(false)
- expect(isURL(' ')).toEqual(false)
- expect(
- isURL(
- 'https://client.rrrr.alpha.dev.foo.bar/9RvDy6gCmic_srrKs1db?sourceOrigin=rrrr&embedded={%22hostContext%22:%22landing%22,%22hostType%22:%22web%22,%22type%22:%22popsync%22}&share=1&wrapperUrl=https%3A%2F%2Fuat.rrrr.io%2F9RvDy6gCmicxyz&save=1&initialSearch={%22sites%22:%22google.com,gettyimages.com%22,%22safe%22:true,%22q%22:%22Perro%22}&opcid=4360f861-ffff-4444-9999-5257065a7dc3&waitForToken=1'
- )
- ).toEqual(false)
- })
-
- it('rejects dangerous protocols (XSS prevention)', () => {
- expect(isURL('javascript:alert(1)')).toEqual(false)
- expect(isURL('javascript:alert(document.cookie)')).toEqual(false)
- expect(isURL('JAVASCRIPT:alert(1)')).toEqual(false)
- expect(isURL('data:text/html,<script>alert(1)</script>')).toEqual(false)
- expect(isURL('vbscript:msgbox(1)')).toEqual(false)
- expect(isURL('file:///etc/passwd')).toEqual(false)
- })
- })
-
- describe('isExternalLink()', () => {
- it('recognizes external links properly', () => {
- expect(isExternalLink('http://www.posthog.com')).toEqual(true)
- expect(isExternalLink('https://www.posthog.com')).toEqual(true)
- expect(isExternalLink('mailto:[email protected]')).toEqual(true)
- })
-
- it('recognizes non-external links properly', () => {
- expect(isExternalLink('path')).toEqual(false)
- expect(isExternalLink('/path')).toEqual(false)
- expect(isExternalLink(1)).toEqual(false)
- expect(isExternalLink(true)).toEqual(false)
- expect(isExternalLink(null)).toEqual(false)
- })
- })
-
- describe('compactNumber()', () => {
- it('formats number correctly', () => {
- expect(compactNumber(10)).toEqual('10')
- expect(compactNumber(293)).toEqual('293')
- expect(compactNumber(5001)).toEqual('5 K')
- expect(compactNumber(5312)).toEqual('5.31 K')
- expect(compactNumber(5392)).toEqual('5.39 K')
- expect(compactNumber(2833102)).toEqual('2.83 M')
- expect(compactNumber(8283310234)).toEqual('8.28 B')
- expect(compactNumber(null)).toEqual('-')
- })
- })
-
- describe('roundToDecimal()', () => {
- it('formats number correctly', () => {
- expect(roundToDecimal(null)).toEqual('-')
- expect(roundToDecimal(293)).toEqual('293.00')
- expect(roundToDecimal(102.121233)).toEqual('102.12')
- expect(roundToDecimal(102.99999)).toEqual('103.00')
- expect(roundToDecimal(1212)).toEqual('1212.00')
- expect(roundToDecimal(1212, 3)).toEqual('1212.000')
- })
- })
-
- describe('pluralize()', () => {
- it('handles singular cases', () => {
- expect(pluralize(1, 'member')).toEqual('1 member')
- expect(pluralize(1, 'bacterium', 'bacteria', true)).toEqual('1 bacterium')
- expect(pluralize(1, 'word', undefined, false)).toEqual('word')
- })
- it('handles plural cases', () => {
- expect(pluralize(28321, 'member')).toEqual('28,321 members')
- expect(pluralize(99, 'bacterium', 'bacteria')).toEqual('99 bacteria')
- expect(pluralize(3, 'word', undefined, false)).toEqual('words')
- })
- })
-
- describe('wordPluralize()', () => {
- it('handles singular cases', () => {
- expect(wordPluralize('company')).toEqual('companies')
- expect(wordPluralize('person')).toEqual('people')
- expect(wordPluralize('bacterium')).toEqual('bacteria')
- expect(wordPluralize('word')).toEqual('words')
- expect(wordPluralize('child')).toEqual('children')
- expect(wordPluralize('knife')).toEqual('knives')
- })
-
- it('returns falsy input unchanged without throwing', () => {
- expect(wordPluralize('')).toEqual('')
- expect(wordPluralize(null as unknown as string)).toEqual('')
- expect(wordPluralize(undefined as unknown as string)).toEqual('')
- })
- })
-
- describe('endWithPunctation()', () => {
- it('adds period at the end when needed', () => {
- expect(endWithPunctation('Hello')).toEqual('Hello.')
- expect(endWithPunctation('Learn more! ')).toEqual('Learn more!')
- expect(endWithPunctation('Stop.')).toEqual('Stop.')
- expect(endWithPunctation(null)).toEqual('')
- expect(endWithPunctation(' ')).toEqual('')
- expect(endWithPunctation(' Why? ')).toEqual('Why?')
- })
- })
-
- describe('getFormattedLastWeekDate()', () => {
- it('happy case', () => {
- tk.freeze(new Date(1330688329321))
- expect(getFormattedLastWeekDate()).toEqual('January 13 - March 2, 2012')
- tk.reset()
- })
- })
-
- describe('dateFilterToText()', () => {
- beforeEach(() => {
- tk.freeze(new Date('2026-06-15T12:00:00.000Z'))
- })
- afterEach(() => {
- tk.reset()
- })
-
- describe('not formatted', () => {
- it('handles dayjs dates', () => {
- const from = dayjs('2018-04-04T16:00:00.000Z')
- const to = dayjs('2018-04-09T15:05:00.000Z')
-
- expect(dateFilterToText(from, to, 'custom')).toEqual('April 4 - April 9, 2018')
- })
-
- it('handles various ranges', () => {
- expect(dateFilterToText('dStart', null, 'default')).toEqual('Today')
- expect(dateFilterToText('2020-01-02', '2020-01-05', 'default')).toEqual('2020-01-02 - 2020-01-05')
- expect(dateFilterToText(null, null, 'default')).toEqual('default')
- expect(dateFilterToText('-24h', null, 'default')).toEqual('Last 24 hours')
- expect(dateFilterToText('-48h', undefined, 'default')).toEqual('Last 48 hours')
- expect(dateFilterToText('-1d', null, 'default')).toEqual('Last 1 day')
- expect(dateFilterToText('-1dStart', '-1dEnd', 'default')).toEqual('Yesterday')
- expect(dateFilterToText('-1mStart', '-1mEnd', 'default')).toEqual('Last month')
- })
-
- // The frontend DateFilter emits YYYY-MM-DD (without allowTimePrecision) or
- // YYYY-MM-DDTHH:mm:ss (with allowTimePrecision, used by recordings).
- // The AI agent (filter_session_recordings) emits YYYY-MM-DDTHH:mm:ss.SSS.
- // All cross-combinations must display correctly.
-
- it('handles ISO datetime without milliseconds (frontend DateFilter format)', () => {
- // Both dates as YYYY-MM-DDTHH:mm:ss
- expect(dateFilterToText('2026-02-01T00:00:00', '2026-02-04T23:59:59', 'default')).toEqual(
- 'February 1, 00:00:00 - February 4, 23:59:59'
- )
- // Non-midnight times
- expect(dateFilterToText('2026-02-01T14:30:00', '2026-02-04T18:45:00', 'default')).toEqual(
- 'February 1, 14:30 - February 4, 18:45'
- )
- })
-
- it('handles ISO datetime with milliseconds (AI agent format)', () => {
- // Both dates as YYYY-MM-DDTHH:mm:ss.SSS
- expect(dateFilterToText('2026-02-01T00:00:00.000', '2026-02-04T23:59:59.999', 'default')).toEqual(
- 'February 1, 00:00:00 - February 4, 23:59:59'
- )
- })
-
- it('handles mixed datetime formats (frontend × AI agent)', () => {
- // YYYY-MM-DDTHH:mm:ss from + YYYY-MM-DDTHH:mm:ss.SSS to
- expect(dateFilterToText('2026-02-01T00:00:00', '2026-02-04T23:59:59.999', 'default')).toEqual(
- 'February 1, 00:00:00 - February 4, 23:59:59'
- )
- // YYYY-MM-DDTHH:mm:ss.SSS from + YYYY-MM-DDTHH:mm:ss to
- expect(dateFilterToText('2026-02-01T00:00:00.000', '2026-02-04T23:59:59', 'default')).toEqual(
- 'February 1, 00:00:00 - February 4, 23:59:59'
- )
- })
-
- it('handles plain date + datetime (either direction)', () => {
- // YYYY-MM-DD from + YYYY-MM-DDTHH:mm:ss to
- expect(dateFilterToText('2026-02-01', '2026-02-04T23:59:59', 'default')).toEqual(
- 'February 1, 00:00:00 - February 4, 23:59:59'
- )
- // YYYY-MM-DD from + YYYY-MM-DDTHH:mm:ss.SSS to
- expect(dateFilterToText('2026-02-01', '2026-02-04T23:59:59.999', 'default')).toEqual(
- 'February 1, 00:00:00 - February 4, 23:59:59'
- )
- // YYYY-MM-DDTHH:mm:ss from + YYYY-MM-DD to (both resolve to midnight → times omitted)
- expect(dateFilterToText('2026-02-01T00:00:00', '2026-02-04', 'default')).toEqual(
- 'February 1 - February 4'
- )
- // YYYY-MM-DDTHH:mm:ss.SSS from + YYYY-MM-DD to (both resolve to midnight → times omitted)
- expect(dateFilterToText('2026-02-01T00:00:00.000', '2026-02-04', 'default')).toEqual(
- 'February 1 - February 4'
- )
- // Non-midnight datetime from + YYYY-MM-DD to
- expect(dateFilterToText('2026-02-01T14:30:00', '2026-02-04', 'default')).toEqual(
- 'February 1, 14:30 - February 4, 00:00'
- )
- })
-
- it('handles same-day datetime range', () => {
- expect(dateFilterToText('2026-02-01T09:00:00', '2026-02-01T17:00:00', 'default')).toEqual(
- 'February 1, 09:00 - 17:00'
- )
- })
-
- it('can have overridden date options', () => {
- expect(dateFilterToText('-21d', null, 'default', [{ key: 'Last 3 weeks', values: ['-21d'] }])).toEqual(
- 'Last 3 weeks'
- )
- })
- })
-
- describe('formatted', () => {
- it('handles dayjs dates', () => {
- const from = dayjs('2018-04-04T16:00:00.000Z')
- const to = dayjs('2018-04-09T15:05:00.000Z')
-
- expect(dateFilterToText(from, to, 'custom', dateMapping, true)).toEqual('April 4 - April 9, 2018')
- })
-
- it('handles various ranges', () => {
- // 2012-03-02T11:38:49.321Z
- tk.freeze(new Date(1330688329321))
- expect(dateFilterToText('dStart', null, 'default', dateMapping, true)).toEqual('March 2, 2012')
- expect(dateFilterToText('2020-01-02', '2020-01-05', 'default', dateMapping, true)).toEqual(
- 'January 2 - January 5, 2020'
- )
- expect(dateFilterToText(null, null, 'default', dateMapping, true)).toEqual('default')
- expect(dateFilterToText('-24h', null, 'default', dateMapping, true)).toEqual('March 1 - March 2, 2012')
- expect(dateFilterToText('-48h', undefined, 'default', dateMapping, true)).toEqual(
- 'February 29 - March 2, 2012'
- )
- expect(dateFilterToText('-1d', null, 'default', dateMapping, true)).toEqual('March 1 - March 2, 2012')
- expect(dateFilterToText('-1dStart', '-1dEnd', 'default', dateMapping, true)).toEqual('March 1, 2012')
- expect(dateFilterToText('-1mStart', '-1mEnd', 'default', dateMapping, true)).toEqual(
- 'February 1 - February 29, 2012'
- )
- expect(dateFilterToText('-180d', null, 'default', dateMapping, true)).toEqual(
- 'September 4, 2011 - March 2, 2012'
- )
- tk.reset()
- })
-
- it('can have overridden date options', () => {
- tk.freeze(new Date(1330688329321))
- expect(
- dateFilterToText(
- '-21d',
- null,
- 'default',
- [{ key: 'Last 3 weeks', values: ['-21d'], getFormattedDate: () => 'custom formatted date' }],
- true
- )
- ).toEqual('custom formatted date')
- tk.reset()
- })
-
- it('can have overridden date format', () => {
- const from = dayjs('2018-04-04T16:00:00.000Z').tz('America/New_York')
- const to = dayjs('2018-04-09T15:05:00.000Z').tz('America/New_York')
-
- expect(dateFilterToText(from, to, 'custom', dateMapping, true, 'YYYY-MM-DD hh:mm:ss')).toEqual(
- '2018-04-04 12:00:00 - 2018-04-09 11:05:00'
- )
- })
- })
-
- describe('week formatting respects weekStartDay', () => {
- // 2012-03-02 is a Friday
- beforeEach(() => {
- tk.freeze(new Date(1330688329321))
- })
- afterEach(() => {
- tk.reset()
- })
-
- it('This week with Sunday start (default)', () => {
- expect(
- dateFilterToText('wStart', undefined, 'default', dateMapping, true, undefined, undefined, 0)
- ).toEqual('February 26 - March 2, 2012')
- })
-
- it('This week with Monday start', () => {
- expect(
- dateFilterToText('wStart', undefined, 'default', dateMapping, true, undefined, undefined, 1)
- ).toEqual('February 27 - March 2, 2012')
- })
-
- it('Last week with Sunday start (default)', () => {
- expect(
- dateFilterToText('-1wStart', '-1wEnd', 'default', dateMapping, true, undefined, undefined, 0)
- ).toEqual('February 19 - February 25, 2012')
- })
-
- it('Last week with Monday start', () => {
- expect(
- dateFilterToText('-1wStart', '-1wEnd', 'default', dateMapping, true, undefined, undefined, 1)
- ).toEqual('February 20 - February 26, 2012')
- })
- })
- })
-
- describe('dateStringToDayJs', () => {
- beforeEach(() => {
- tk.freeze(1330688329321) // randomly chosen time on the 22nd of February 2022
- })
- afterEach(() => {
- tk.reset()
- })
-
- it('handles various dates', () => {
- expect(dateStringToDayJs('2022-02-22')?.utc(true).toISOString()).toEqual('2022-02-22T00:00:00.000Z')
- expect(dateStringToDayJs('1999-12-31')?.utc(true).toISOString()).toEqual('1999-12-31T00:00:00.000Z')
- })
-
- it('handles various units', () => {
- expect(dateStringToDayJs('d')?.utc(true).toISOString()).toEqual('2012-03-02T00:00:00.000Z')
- expect(dateStringToDayJs('m')?.utc(true).toISOString()).toEqual('2012-03-02T00:00:00.000Z')
- expect(dateStringToDayJs('w')?.utc(true).toISOString()).toEqual('2012-03-02T00:00:00.000Z')
- expect(dateStringToDayJs('q')?.utc(true).toISOString()).toEqual('2012-03-02T00:00:00.000Z')
- expect(dateStringToDayJs('y')?.utc(true).toISOString()).toEqual('2012-03-02T00:00:00.000Z')
- expect(dateStringToDayJs('x')).toEqual(null)
- })
-
- it('handles pluses and minuses', () => {
- expect(dateStringToDayJs('d')?.utc(true).toISOString()).toEqual('2012-03-02T00:00:00.000Z')
- expect(dateStringToDayJs('+d')?.utc(true).toISOString()).toEqual('2012-03-02T00:00:00.000Z')
- expect(dateStringToDayJs('-d')?.utc(true).toISOString()).toEqual('2012-03-02T00:00:00.000Z')
-
- expect(dateStringToDayJs('1d')?.utc(true).toISOString()).toEqual('2012-03-03T00:00:00.000Z')
- expect(dateStringToDayJs('2d')?.utc(true).toISOString()).toEqual('2012-03-04T00:00:00.000Z')
- expect(dateStringToDayJs('3d')?.utc(true).toISOString()).toEqual('2012-03-05T00:00:00.000Z')
- expect(dateStringToDayJs('33d')?.utc(true).toISOString()).toEqual('2012-04-04T00:00:00.000Z')
-
- expect(dateStringToDayJs('+1d')?.utc(true).toISOString()).toEqual('2012-03-03T00:00:00.000Z')
- expect(dateStringToDayJs('+2d')?.utc(true).toISOString()).toEqual('2012-03-04T00:00:00.000Z')
- expect(dateStringToDayJs('+3d')?.utc(true).toISOString()).toEqual('2012-03-05T00:00:00.000Z')
- expect(dateStringToDayJs('+33d')?.utc(true).toISOString()).toEqual('2012-04-04T00:00:00.000Z')
-
- expect(dateStringToDayJs('-1d')?.utc(true).toISOString()).toEqual('2012-03-01T00:00:00.000Z')
- expect(dateStringToDayJs('-2d')?.utc(true).toISOString()).toEqual('2012-02-29T00:00:00.000Z')
- expect(dateStringToDayJs('-3d')?.utc(true).toISOString()).toEqual('2012-02-28T00:00:00.000Z')
- expect(dateStringToDayJs('-33d')?.utc(true).toISOString()).toEqual('2012-01-29T00:00:00.000Z')
-
- expect(dateStringToDayJs('-33m')?.utc(true).toISOString()).toEqual('2009-06-02T00:00:00.000Z')
- expect(dateStringToDayJs('-33w')?.utc(true).toISOString()).toEqual('2011-07-15T00:00:00.000Z')
- expect(dateStringToDayJs('-33q')?.utc(true).toISOString()).toEqual('2003-12-02T00:00:00.000Z')
- expect(dateStringToDayJs('-33y')?.utc(true).toISOString()).toEqual('1979-03-02T00:00:00.000Z')
- })
-
- it('handles various start/end values', () => {
- expect(dateStringToDayJs('dStart')?.utc(true).toISOString()).toEqual('2012-03-02T00:00:00.000Z')
- expect(dateStringToDayJs('dEnd')?.utc(true).toISOString()).toEqual('2012-03-02T23:59:59.999Z')
- expect(dateStringToDayJs('wStart')?.utc(true).toISOString()).toEqual('2012-02-26T00:00:00.000Z')
- expect(dateStringToDayJs('wEnd')?.utc(true).toISOString()).toEqual('2012-03-03T23:59:59.999Z')
- expect(dateStringToDayJs('mStart')?.utc(true).toISOString()).toEqual('2012-03-01T00:00:00.000Z')
- expect(dateStringToDayJs('mEnd')?.utc(true).toISOString()).toEqual('2012-03-31T23:59:59.999Z')
- expect(dateStringToDayJs('qStart')?.utc(true).toISOString()).toEqual('2012-01-01T00:00:00.000Z')
- expect(dateStringToDayJs('qEnd')?.utc(true).toISOString()).toEqual('2012-03-31T23:59:59.999Z')
- expect(dateStringToDayJs('yStart')?.utc(true).toISOString()).toEqual('2012-01-01T00:00:00.000Z')
- expect(dateStringToDayJs('yEnd')?.utc(true).toISOString()).toEqual('2012-12-31T23:59:59.999Z')
- })
-
- it('handles various start/end values with units', () => {
- expect(dateStringToDayJs('1dStart')?.utc(true).toISOString()).toEqual('2012-03-03T00:00:00.000Z')
- expect(dateStringToDayJs('1dEnd')?.utc(true).toISOString()).toEqual('2012-03-03T23:59:59.999Z')
-
- expect(dateStringToDayJs('-1wStart')?.utc(true).toISOString()).toEqual('2012-02-19T00:00:00.000Z')
- expect(dateStringToDayJs('-1wEnd')?.utc(true).toISOString()).toEqual('2012-02-25T23:59:59.999Z')
-
- expect(dateStringToDayJs('12mStart')?.utc(true).toISOString()).toEqual('2013-03-01T00:00:00.000Z')
- expect(dateStringToDayJs('12mEnd')?.utc(true).toISOString()).toEqual('2013-03-31T23:59:59.999Z')
-
- expect(dateStringToDayJs('-4qStart')?.utc(true).toISOString()).toEqual('2011-01-01T00:00:00.000Z')
- expect(dateStringToDayJs('-4qEnd')?.utc(true).toISOString()).toEqual('2011-03-31T23:59:59.999Z')
-
- expect(dateStringToDayJs('0yStart')?.utc(true).toISOString()).toEqual('2012-01-01T00:00:00.000Z')
- expect(dateStringToDayJs('0yEnd')?.utc(true).toISOString()).toEqual('2012-12-31T23:59:59.999Z')
- })
- })
-
- describe('getDefaultInterval', () => {
- it('should return days for last 7 days', () => {
- expect(getDefaultInterval('-7d', null)).toEqual('day')
- })
-
- it('should return hours for last 24 hours', () => {
- expect(getDefaultInterval('-24h', null)).toEqual('hour')
- })
-
- it('should return days for month to date', () => {
- expect(getDefaultInterval('mStart', null)).toEqual('day')
- })
-
- it('should return days for week to date', () => {
- expect(getDefaultInterval('wStart', null)).toEqual('day')
- })
-
- it('should return month for year to date', () => {
- expect(getDefaultInterval('yStart', null)).toEqual('month')
- })
-
- it('should return month for all time', () => {
- expect(getDefaultInterval('all', null)).toEqual('month')
- })
-
- it('should handle explicit dates 6 months apart', () => {
- expect(getDefaultInterval('2023-10-01', '2023-04-01')).toEqual('month')
- })
- it('should handle explicit dates a month apart', () => {
- expect(getDefaultInterval('2023-10-01', '2023-09-01')).toEqual('week')
- })
- it('should handle explicit dates a week apart', () => {
- expect(getDefaultInterval('2023-10-01', '2023-09-25')).toEqual('day')
- })
- it('should handle explicit dates a day apart', () => {
- expect(getDefaultInterval('2023-10-02', '2023-10-01')).toEqual('hour')
- })
- it('should handle explicit dates 12 hours apart', () => {
- expect(getDefaultInterval('2023-10-01T18:00:00', '2023-10-01T6:00:00')).toEqual('hour')
- })
- })
-
- describe('areDatesValidForInterval', () => {
- it('should require interval to be month for all time', () => {
- expect(areDatesValidForInterval('month', 'all', null)).toEqual(true)
- expect(areDatesValidForInterval('week', 'all', null)).toEqual(false)
- expect(areDatesValidForInterval('day', 'all', null)).toEqual(false)
- expect(areDatesValidForInterval('hour', 'all', null)).toEqual(false)
- })
- it('should return false if the dates are one interval apart', () => {
- expect(areDatesValidForInterval('day', '-24h', null)).toEqual(false)
- expect(areDatesValidForInterval('week', '-7d', null)).toEqual(false)
- expect(areDatesValidForInterval('day', '-1d', null)).toEqual(false)
- })
- it('should return true if the dates are two intervals apart', () => {
- expect(areDatesValidForInterval('day', '-48h', null)).toEqual(true)
- expect(areDatesValidForInterval('week', '-14d', null)).toEqual(true)
- expect(areDatesValidForInterval('day', '-2d', null)).toEqual(true)
- })
- it('should return false for hourly if over 2 weeks', () => {
- expect(areDatesValidForInterval('hour', '-15d', null)).toEqual(false)
- })
- it('should support explicit dates', () => {
- expect(areDatesValidForInterval('month', '2023-08-01', '2023-11-01')).toEqual(true)
- expect(areDatesValidForInterval('week', '2023-10-01', '2023-11-01')).toEqual(true)
- expect(areDatesValidForInterval('day', '2023-10-16', '2023-11-01')).toEqual(true)
- expect(areDatesValidForInterval('hour', '2023-11-01T12', '2023-11-01T18')).toEqual(true)
- })
- })
-
- describe('hexToRGBA()', () => {
- it('converts hex to RGBA correctly', () => {
- expect(hexToRGBA('#ff0000', 0.3)).toEqual('rgba(255,0,0,0.3)')
- expect(hexToRGBA('#0000Cc', 0)).toEqual('rgba(0,0,204,0)')
- expect(hexToRGBA('#5375ff', 1)).toEqual('rgba(83,117,255,1)')
- })
- })
-
- describe('average()', () => {
- it('calculates average correctly', () => {
- expect(average([9, 4, 1, 3, 5, 7])).toEqual(4.8)
- expect(average([72, 35, 68, 66, 70, 9, 81])).toEqual(57.3) // Tests rounding too
- expect(average([86.4, 46.321, 45.304, 34.1, 147])).toEqual(71.8) // Tests rounding too
- })
- })
-
- describe('median()', () => {
- it('returns middle number if array length is odd', () => {
- expect(median([9, 4, 1, 3, 5, 7, 3, 6, 14])).toEqual(5)
- })
- it('returns avg of middle numbers if array length is even', () => {
- expect(median([9, 4, 0, 5, 7, 3, 6, 14])).toEqual(5.5)
- })
- })
-
- describe('humanFriendlyLargeNumber()', () => {
- it('returns the correct string', () => {
- expect(humanFriendlyLargeNumber(1.234)).toEqual('1.23')
- expect(humanFriendlyLargeNumber(12.34)).toEqual('12.3')
- expect(humanFriendlyLargeNumber(123.4)).toEqual('123')
- expect(humanFriendlyLargeNumber(1234)).toEqual('1.23K')
- expect(humanFriendlyLargeNumber(12345)).toEqual('12.3K')
- expect(humanFriendlyLargeNumber(123456)).toEqual('123K')
- expect(humanFriendlyLargeNumber(1234567)).toEqual('1.23M')
- expect(humanFriendlyLargeNumber(-1234567)).toEqual('-1.23M')
- expect(humanFriendlyLargeNumber(-1)).toEqual('-1')
- expect(humanFriendlyLargeNumber(-0.1)).toEqual('-0.1')
- expect(humanFriendlyLargeNumber(0)).toEqual('0')
- expect(humanFriendlyLargeNumber(NaN)).toEqual('NaN')
- expect(humanFriendlyLargeNumber(Infinity)).toEqual('inf')
- expect(humanFriendlyLargeNumber(-Infinity)).toEqual('-inf')
- })
- })
- describe('humanFriendlyDuration()', () => {
- it('returns correct value for 0 <= t < 1', () => {
- expect(humanFriendlyDuration(0)).toEqual('0s')
- expect(humanFriendlyDuration(0.001)).toEqual('1ms')
- expect(humanFriendlyDuration(0.02)).toEqual('20ms')
- expect(humanFriendlyDuration(0.3)).toEqual('300ms')
- expect(humanFriendlyDuration(0.999)).toEqual('999ms')
- })
-
- it('returns correct value for 1 < t <= 60', () => {
- expect(humanFriendlyDuration(60)).toEqual('1m')
- expect(humanFriendlyDuration(45)).toEqual('45s')
- expect(humanFriendlyDuration(44.8)).toEqual('45s')
- expect(humanFriendlyDuration(45.2)).toEqual('45s')
- expect(humanFriendlyDuration(45.2, { secondsFixed: 1 })).toEqual('45.2s')
- expect(humanFriendlyDuration(1.23)).toEqual('1s')
- expect(humanFriendlyDuration(1.23, { secondsPrecision: 3 })).toEqual('1.23s')
- expect(humanFriendlyDuration(1, { secondsPrecision: 3 })).toEqual('1s')
- expect(humanFriendlyDuration(1, { secondsFixed: 1 })).toEqual('1s')
- expect(humanFriendlyDuration(1)).toEqual('1s')
- })
- it('returns correct value for 60 < t < 120', () => {
- expect(humanFriendlyDuration(119.6)).toEqual('1m 59s')
- expect(humanFriendlyDuration(90)).toEqual('1m 30s')
- })
- it('returns correct value for t > 120', () => {
- expect(humanFriendlyDuration(360)).toEqual('6m')
- })
- it('returns correct value for t >= 3600', () => {
- expect(humanFriendlyDuration(3600)).toEqual('1h')
- expect(humanFriendlyDuration(3601)).toEqual('1h 1s')
- expect(humanFriendlyDuration(3961)).toEqual('1h 6m 1s')
- expect(humanFriendlyDuration(3961.333)).toEqual('1h 6m 1s')
- expect(humanFriendlyDuration(3961.666)).toEqual('1h 6m 1s')
- })
- it('returns correct value for t >= 86400', () => {
- expect(humanFriendlyDuration(86400)).toEqual('1d')
- expect(humanFriendlyDuration(86400.12)).toEqual('1d')
- })
- it('truncates to specified # of units', () => {
- expect(humanFriendlyDuration(3961, { maxUnits: 2 })).toEqual('1h 6m')
- expect(humanFriendlyDuration(30, { maxUnits: 2 })).toEqual('30s') // no change
- expect(humanFriendlyDuration(30, { maxUnits: 0 })).toEqual('') // returns no units (useless)
- })
- it('returns an empty string for nullish inputs', () => {
- expect(humanFriendlyDuration('', { maxUnits: 2 })).toEqual('')
- expect(humanFriendlyDuration(null, { maxUnits: 2 })).toEqual('')
- })
- })
-
- describe('colonDelimitedDuration()', () => {
- it('returns correct value for <= 60', () => {
- expect(colonDelimitedDuration(59.9)).toEqual('00:00:59')
- expect(colonDelimitedDuration(60)).toEqual('00:01:00')
- expect(colonDelimitedDuration(45)).toEqual('00:00:45')
- })
- it('returns correct value for 60 < t < 120', () => {
- expect(colonDelimitedDuration(90)).toEqual('00:01:30')
- })
- it('returns correct value for t > 120', () => {
- expect(colonDelimitedDuration(360)).toEqual('00:06:00')
- expect(colonDelimitedDuration(360.3233)).toEqual('00:06:00')
- expect(colonDelimitedDuration(360.782)).toEqual('00:06:00')
- })
- it('returns correct value for t >= 3600', () => {
- expect(colonDelimitedDuration(3600)).toEqual('01:00:00')
- expect(colonDelimitedDuration(3601)).toEqual('01:00:01')
- expect(colonDelimitedDuration(3961)).toEqual('01:06:01')
- })
- it('returns correct value for t >= 86400', () => {
- expect(colonDelimitedDuration(86400)).toEqual('24:00:00')
- expect(colonDelimitedDuration(90000)).toEqual('25:00:00')
- })
- it('returns correct value for numUnits < 3', () => {
- expect(colonDelimitedDuration(86400, 2)).toEqual('1440:00')
- expect(colonDelimitedDuration(86400, 1)).toEqual('86400')
- })
- it('returns correct value for numUnits >= 4', () => {
- expect(colonDelimitedDuration(86400, 4)).toEqual('01:00:00:00')
- expect(colonDelimitedDuration(90000, 4)).toEqual('01:01:00:00')
- expect(colonDelimitedDuration(90061, 4)).toEqual('01:01:01:01')
- expect(colonDelimitedDuration(604800, 5)).toEqual('01:00:00:00:00')
- expect(colonDelimitedDuration(604800, 6)).toEqual('01:00:00:00:00')
- expect(colonDelimitedDuration(604800.222, 5)).toEqual('01:00:00:00:00')
- expect(colonDelimitedDuration(604800.999, 6)).toEqual('01:00:00:00:00')
- })
- it('returns the smallest possible for numUnits = null', () => {
- expect(colonDelimitedDuration(59, null)).toEqual('00:59')
- expect(colonDelimitedDuration(3599, null)).toEqual('59:59')
- expect(colonDelimitedDuration(3600, null)).toEqual('01:00:00')
- })
- it('returns an empty string for nullish inputs', () => {
- expect(colonDelimitedDuration('')).toEqual('')
- expect(colonDelimitedDuration(null)).toEqual('')
- expect(colonDelimitedDuration(undefined)).toEqual('')
- })
- })
-
- describe('reverseColonDelimitedDuration()', () => {
- it('returns correct value', () => {
- expect(reverseColonDelimitedDuration('59')).toEqual(59)
- expect(reverseColonDelimitedDuration('59:59')).toEqual(3599)
- expect(reverseColonDelimitedDuration('23:59:59')).toEqual(86399)
- })
- it('returns an null for bad values', () => {
- expect(reverseColonDelimitedDuration('1232123')).toEqual(null)
- expect(reverseColonDelimitedDuration('AA:AA:AA')).toEqual(null)
- expect(reverseColonDelimitedDuration(undefined)).toEqual(null)
- })
- })
-
- describe('areObjectValuesEmpty()', () => {
- it('returns correct value for objects with empty values', () => {
- expect(areObjectValuesEmpty({ a: '', b: null, c: undefined })).toEqual(true)
- expect(areObjectValuesEmpty({ a: undefined, b: undefined })).toEqual(true)
- expect(areObjectValuesEmpty({})).toEqual(true)
- })
- it('returns correct value for objects with at least one non-empty value', () => {
- expect(areObjectValuesEmpty({ a: '', b: null, c: 'hello' })).toEqual(false)
- expect(areObjectValuesEmpty({ a: true, b: 'hello' })).toEqual(false)
- expect(areObjectValuesEmpty('hello' as any)).toEqual(false)
- expect(areObjectValuesEmpty(null as any)).toEqual(false)
- })
- })
-
- describe('ensureStringIsNotBlank()', () => {
- it('handles unusual input', () => {
- expect(ensureStringIsNotBlank(null)).toEqual(null)
- expect(ensureStringIsNotBlank({} as any)).toEqual(null)
- expect(ensureStringIsNotBlank(undefined)).toEqual(null)
- expect(ensureStringIsNotBlank(true as any)).toEqual(null)
- })
- it('handles blank strings as expected', () => {
- expect(ensureStringIsNotBlank('')).toEqual(null)
- expect(ensureStringIsNotBlank(' ')).toEqual(null)
- })
- it('handles happy case', () => {
- expect(ensureStringIsNotBlank('happyboy')).toEqual('happyboy')
- expect(ensureStringIsNotBlank(' happy boy ')).toEqual(' happy boy ')
- })
- })
-
- describe('objectDiffShallow()', () => {
- it('obj1 + result = obj2', () => {
- expect(objectDiffShallow({ b: '4' }, { b: '3', a: '2' })).toStrictEqual({ b: '3', a: '2' })
- expect(objectDiffShallow({ b: '4', c: '12' }, { b: '3', a: '2' })).toStrictEqual({
- b: '3',
- a: '2',
- c: undefined,
- })
- })
- })
-
- describe('objectClean()', () => {
- it('removes undefined values', () => {
- expect(objectClean({ a: 1, b: 'b', c: null, d: {}, e: [], f: undefined })).toStrictEqual({
- a: 1,
- b: 'b',
- c: null,
- d: {},
- e: [],
- })
- })
- })
-
- describe('objectCleanWithEmpty()', () => {
- it('removes undefined and empty values', () => {
- expect(
- objectCleanWithEmpty({ a: 1, b: 'b', c: null, d: {}, e: [], f: undefined, g: { x: 1 }, h: [1] })
- ).toStrictEqual({
- a: 1,
- b: 'b',
- c: null,
- g: { x: 1 },
- h: [1],
- })
- })
- })
-
- describe('eventToName()', () => {
- const baseEvent = {
- elements: [],
- event: '',
- properties: {},
- person: {},
- } as any as EventType
-
- it('handles page events as expected', () => {
- expect(
- eventToDescription({ ...baseEvent, event: '$pageview', properties: { $pathname: '/hello' } })
- ).toEqual('/hello')
- expect(
- eventToDescription({ ...baseEvent, event: '$pageleave', properties: { $pathname: '/bye' } })
- ).toEqual('/bye')
- })
-
- it('handles screen events using $screen_name', () => {
- expect(
- eventToDescription({ ...baseEvent, event: '$screen', properties: { $screen_name: 'CartScreen' } })
- ).toEqual('CartScreen')
- })
-
- it('falls back to event name when the primary property is missing', () => {
- // Old behaviour fell back to $current_url for $pageview without $pathname; the new
- // single-property contract returns the event name instead so the change is explicit
- // and consistent with $screen / $feature_flag_called.
- expect(
- eventToDescription({
- ...baseEvent,
- event: '$pageview',
- properties: { $current_url: 'https://example.com/' },
- })
- ).toEqual('$pageview')
- })
-
- it('handles no text autocapture as expected', () => {
- expect(
- eventToDescription({
- ...baseEvent,
- event: '$autocapture',
- properties: { $event_type: 'click' },
- })
- ).toEqual('clicked element')
- })
-
- it('handles long form autocapture as expected', () => {
- expect(
- eventToDescription({
- ...baseEvent,
- event: '$autocapture',
- properties: { $event_type: 'click' },
- elements: [{ tag_name: 'button', text: 'hello' } as ElementType],
- })
- ).toEqual('clicked button with text "hello"')
- })
-
- it('handles short form autocapture as expected', () => {
- expect(
- eventToDescription(
- {
- ...baseEvent,
- event: '$autocapture',
- properties: { $event_type: 'click' },
- elements: [{ tag_name: 'button', text: 'hello' } as ElementType],
- },
- true
- )
- ).toEqual('clicked "hello"')
- })
-
- it.each([
- ['with a flag key', { $feature_flag: 'my-flag-key' }, 'my-flag-key'],
- ['without the flag key property', {}, '$feature_flag_called'],
- ])('handles feature flag called events %s', (_, properties, expected) => {
- expect(
- eventToDescription({
- ...baseEvent,
- event: '$feature_flag_called',
- properties,
- })
- ).toEqual(expected)
- })
-
- it('handles unknown event/action', () => {
- expect(
- eventToDescription({
- ...baseEvent,
- event: 'custom event/action',
- })
- ).toEqual('custom event/action')
- })
- })
-
- describe('autoCaptureEventToDescription()', () => {
- const baseEvent = {
- elements: [],
- event: '$autocapture',
- properties: { $event_type: 'click' },
- person: {},
- } as any as EventType
-
- it('handles regular text by adding quotes', () => {
- expect(
- autoCaptureEventToDescription({
- ...baseEvent,
- properties: {
- ...baseEvent.properties,
- $el_text: 'Analyzing Characters with',
- },
- })
- ).toEqual('clicked element with text "Analyzing Characters with"')
- })
-
- it('prioritizes $el_text from properties over text in elements array', () => {
- expect(
- autoCaptureEventToDescription({
- ...baseEvent,
- properties: {
- ...baseEvent.properties,
- $el_text: 'Text from properties',
- },
- elements: [{ tag_name: 'button', text: 'Text from elements' } as ElementType],
- })
- ).toEqual('clicked button with text "Text from properties"')
- })
-
- it('handles text with double quotes without adding additional quotes', () => {
- expect(
- autoCaptureEventToDescription({
- ...baseEvent,
- properties: {
- ...baseEvent.properties,
- $el_text: 'Unit Skills Assessment 1: "',
- },
- })
- ).toEqual('clicked element with text "Unit Skills Assessment 1: ""')
- })
-
- it('handles text with single quotes without adding additional quotes', () => {
- expect(
- autoCaptureEventToDescription({
- ...baseEvent,
- properties: {
- ...baseEvent.properties,
- $el_text: "Reading Lesson: '",
- },
- })
- ).toEqual('clicked element with text "Reading Lesson: \'"')
- })
-
- it('handles longer text with single quotes without adding additional quotes', () => {
- expect(
- autoCaptureEventToDescription({
- ...baseEvent,
- properties: {
- ...baseEvent.properties,
- $el_text: "A Sense of Wonder: An Introduction to Science Fiction'",
- },
- })
- ).toEqual('clicked element with text "A Sense of Wonder: An Introduction to Science Fiction\'"')
- })
-
- it('handles text in elements array', () => {
- expect(
- autoCaptureEventToDescription({
- ...baseEvent,
- elements: [{ tag_name: 'button', text: 'hello world' } as ElementType],
- })
- ).toEqual('clicked button with text "hello world"')
- })
-
- it('handles text with quotes in elements array', () => {
- expect(
- autoCaptureEventToDescription({
- ...baseEvent,
- elements: [{ tag_name: 'button', text: 'hello "world"' } as ElementType],
- })
- ).toEqual('clicked button with text "hello "world""')
- })
-
- it('handles aria-label attributes', () => {
- expect(
- autoCaptureEventToDescription({
- ...baseEvent,
- elements: [
- {
- tag_name: 'button',
- attributes: { 'attr__aria-label': 'Close dialog' },
- } as ElementType,
- ],
- })
- ).toEqual('clicked button with aria label "Close dialog"')
- })
-
- it('handles aria-label attributes with quotes', () => {
- expect(
- autoCaptureEventToDescription({
- ...baseEvent,
- elements: [
- {
- tag_name: 'button',
- attributes: { 'attr__aria-label': 'Close "main" dialog' },
- } as ElementType,
- ],
- })
- ).toEqual('clicked button with aria label "Close "main" dialog"')
- })
- })
-
- describe('{floor|ceil}MsToClosestSecond()', () => {
- describe('ceil', () => {
- it('handles ms as expected', () => {
- expect(ceilMsToClosestSecond(10532)).toEqual(11000)
- expect(ceilMsToClosestSecond(1500)).toEqual(2000)
- expect(ceilMsToClosestSecond(500)).toEqual(1000)
- expect(ceilMsToClosestSecond(-10532)).toEqual(-10000)
- expect(ceilMsToClosestSecond(-1500)).toEqual(-1000)
- expect(ceilMsToClosestSecond(-500)).toEqual(-0)
- })
- it('handles whole seconds as expected', () => {
- expect(ceilMsToClosestSecond(0)).toEqual(0)
- expect(ceilMsToClosestSecond(1000)).toEqual(1000)
- expect(ceilMsToClosestSecond(-1000)).toEqual(-1000)
- })
- })
-
- describe('floor', () => {
- it('handles ms as expected', () => {
- expect(floorMsToClosestSecond(10532)).toEqual(10000)
- expect(floorMsToClosestSecond(1500)).toEqual(1000)
- expect(floorMsToClosestSecond(500)).toEqual(0)
- expect(floorMsToClosestSecond(-10532)).toEqual(-11000)
- expect(floorMsToClosestSecond(-1500)).toEqual(-2000)
- expect(floorMsToClosestSecond(-500)).toEqual(-1000)
- })
- it('handles whole seconds as expected', () => {
- expect(floorMsToClosestSecond(0)).toEqual(0)
- expect(floorMsToClosestSecond(1000)).toEqual(1000)
- expect(floorMsToClosestSecond(-1000)).toEqual(-1000)
- })
- })
-
- describe('choosing an operator for taxonomic filters', () => {
- const testCases = [
- { propertyType: PropertyType.DateTime, expected: dateTimeOperatorMap },
- { propertyType: PropertyType.String, expected: stringOperatorMap },
- { propertyType: PropertyType.Numeric, expected: numericOperatorMap },
- { propertyType: PropertyType.Boolean, expected: booleanOperatorMap },
- { propertyType: PropertyType.Duration, expected: durationOperatorMap },
- { propertyType: PropertyType.Selector, expected: selectorOperatorMap },
- { propertyType: undefined, expected: genericOperatorMap },
- ]
- testCases.forEach((testcase) => {
- it(`correctly maps ${testcase.propertyType} to operator options`, () => {
- expect(chooseOperatorMap(testcase.propertyType)).toEqual(testcase.expected)
- })
- })
- })
- })
-
- describe('calculateDays', () => {
- it('1 day to 1 day', () => {
- expect(calculateDays(1, TimeUnitType.Day)).toEqual(1)
- })
- it('1 week to 7 days', () => {
- expect(calculateDays(1, TimeUnitType.Week)).toEqual(7)
- })
- it('1 month to 30 days', () => {
- expect(calculateDays(1, TimeUnitType.Month)).toEqual(30)
- })
- it('1 year to 365 days', () => {
- expect(calculateDays(1, TimeUnitType.Year)).toEqual(365)
- })
- })
-
- describe('range', () => {
- it('creates simple range', () => {
- expect(range(4)).toEqual([0, 1, 2, 3])
- })
-
- it('creates offset range', () => {
- expect(range(1, 5)).toEqual([1, 2, 3, 4])
- })
- })
-
- describe('time ranges', () => {
- it('is less than or equal to 12 hours', () => {
- expect(is12HoursOrLess('-0h')).toBeTruthy()
- expect(is12HoursOrLess('-1h')).toBeTruthy()
- expect(is12HoursOrLess('-12h')).toBeTruthy()
- expect(is12HoursOrLess('-13h')).toBeFalsy()
-
- expect(is12HoursOrLess('-24h')).toBeFalsy()
- expect(is12HoursOrLess('-30h')).toBeFalsy()
- expect(is12HoursOrLess('-47h')).toBeFalsy()
- expect(is12HoursOrLess('-111h')).toBeFalsy()
-
- expect(is12HoursOrLess('-1.123h')).toBeFalsy()
- expect(is12HoursOrLess('1.123h')).toBeFalsy()
- expect(is12HoursOrLess('-ab1-13h')).toBeFalsy()
- expect(is12HoursOrLess('-1d')).toBeFalsy()
- expect(is12HoursOrLess('-1w')).toBeFalsy()
- expect(is12HoursOrLess('-1h-2h')).toBeFalsy()
- })
-
- it('is less than 2 days', () => {
- expect(isLessThan2Days('-0h')).toBeTruthy()
- expect(isLessThan2Days('-1h')).toBeTruthy()
- expect(isLessThan2Days('-12h')).toBeTruthy()
- expect(isLessThan2Days('-24h')).toBeTruthy()
- expect(isLessThan2Days('-30h')).toBeTruthy()
- expect(isLessThan2Days('-47h')).toBeTruthy()
-
- expect(isLessThan2Days('-48h')).toBeFalsy()
- expect(isLessThan2Days('-49h')).toBeFalsy()
- expect(isLessThan2Days('0h')).toBeFalsy()
- expect(isLessThan2Days('1h')).toBeFalsy()
- expect(isLessThan2Days('48h')).toBeFalsy()
- expect(isLessThan2Days('-13.123h')).toBeFalsy()
- expect(isLessThan2Days('13.123h')).toBeFalsy()
- expect(isLessThan2Days('-ab1-13h')).toBeFalsy()
- expect(isLessThan2Days('-1d-1h')).toBeFalsy()
- })
- })
-
- test('shortTimezone', () => {
- expect(shortTimeZone('UTC')).toEqual('UTC')
- // All timezones below don't observe DST for simplicity
- expect(shortTimeZone('America/Phoenix')).toEqual('MST')
- expect(shortTimeZone('Europe/Moscow')).toEqual('UTC+3')
- expect(shortTimeZone('Asia/Tokyo')).toEqual('UTC+9')
- })
-
- describe('getRelativeNextPath', () => {
- const location = {
- origin: 'https://us.posthog.com',
- protocol: 'https:',
- host: 'us.posthog.com',
- hostname: 'us.posthog.com',
- href: 'https://us.posthog.com/',
- } as Location
-
- it('returns relative path for same-origin absolute URL', () => {
- expect(getRelativeNextPath('https://us.posthog.com/test', location)).toBe('/test')
- })
-
- it('returns relative path for same-origin absolute URL with query and hash', () => {
- expect(getRelativeNextPath('https://us.posthog.com/test?foo=bar#baz', location)).toBe('/test?foo=bar#baz')
- })
-
- it('returns relative path for encoded same-origin absolute URL', () => {
- expect(getRelativeNextPath('https%3A%2F%2Fus.posthog.com%2Ftest', location)).toBe('/test')
- })
-
- it('returns relative path for root-relative path', () => {
- expect(getRelativeNextPath('/test', location)).toBe('/test')
- })
-
- it('returns relative path for root-relative path with query and hash', () => {
- expect(getRelativeNextPath('/test?foo=bar#baz', location)).toBe('/test?foo=bar#baz')
- })
-
- it('returns null for external absolute URL', () => {
- expect(getRelativeNextPath('https://evil.com/test', location)).toBeNull()
- })
-
- it('returns null for encoded external absolute URL', () => {
- expect(getRelativeNextPath('https%3A%2F%2Fevil.com%2Ftest', location)).toBeNull()
- })
-
- it('returns null for protocol-relative external URL', () => {
- expect(getRelativeNextPath('//evil.com/test', location)).toBeNull()
- })
-
- it('returns null for empty string', () => {
- expect(getRelativeNextPath('', location)).toBeNull()
- })
-
- it('returns null for malformed URL', () => {
- expect(getRelativeNextPath('http://', location)).toBeNull()
- expect(getRelativeNextPath('%%%%', location)).toBeNull()
- })
-
- it('returns null for non-string input', () => {
- expect(getRelativeNextPath(null, location)).toBeNull()
- expect(getRelativeNextPath(undefined, location)).toBeNull()
- })
-
- it('returns relative path for encoded root-relative path', () => {
- expect(getRelativeNextPath('%2Ftest%2Ffoo%3Fbar%3Dbaz%23hash', location)).toBe('/test/foo?bar=baz#hash')
- })
-
- it('returns null for encoded protocol-relative URL', () => {
- expect(getRelativeNextPath('%2F%2Fevil.com%2Ftest', location)).toBeNull()
- })
-
- it.each([
- ['/\\evil.com/path', '/-then-backslash'],
- ['/\\\\evil.com/path', '/-then-two-backslashes'],
- ['%2F%5Cevil.com%2Fpath', 'encoded /-then-backslash'],
- ])('returns null for backslash external bypass (%s — %s)', (input) => {
- // Browsers normalize backslashes in special-scheme URLs per WHATWG, so /\\evil.com
- // resolves to //evil.com and escapes the origin.
- expect(getRelativeNextPath(input, location)).toBeNull()
- })
- })
-
- describe('parseTagsFilter()', () => {
- describe('array input', () => {
- it('handles string arrays', () => {
- expect(parseTagsFilter(['tag1', 'tag2', 'tag3'])).toEqual(['tag1', 'tag2', 'tag3'])
- })
-
- it('handles mixed type arrays', () => {
- expect(parseTagsFilter(['tag1', 123, true, null, undefined])).toEqual([
- 'tag1',
- '123',
- 'true',
- 'null',
- 'undefined',
- ])
- })
-
- it('filters out empty values', () => {
- expect(parseTagsFilter(['tag1', '', 'tag2', null, 'tag3'])).toEqual(['tag1', 'tag2', 'null', 'tag3'])
- })
-
- it('handles empty array', () => {
- expect(parseTagsFilter([])).toEqual([])
- })
- })
-
- describe('JSON string input', () => {
- it('parses valid JSON arrays', () => {
- expect(parseTagsFilter('["tag1", "tag2", "tag3"]')).toEqual(['tag1', 'tag2', 'tag3'])
- })
-
- it('parses JSON arrays with mixed types', () => {
- expect(parseTagsFilter('["tag1", 123, true]')).toEqual(['tag1', '123', 'true'])
- })
-
- it('filters out empty values from JSON', () => {
- expect(parseTagsFilter('["tag1", "", "tag2", null, "tag3"]')).toEqual(['tag1', 'tag2', 'null', 'tag3'])
- })
-
- it('handles empty JSON array', () => {
- expect(parseTagsFilter('[]')).toEqual([])
- })
-
- it('handles malformed JSON gracefully', () => {
- expect(parseTagsFilter('["tag1", "tag2"')).toEqual(['["tag1"', '"tag2"'])
- })
-
- it('handles invalid JSON syntax', () => {
- expect(parseTagsFilter('{invalid json}')).toEqual(['{invalid json}'])
- })
-
- it('handles JSON that is not an array', () => {
- expect(parseTagsFilter('{"not": "an array"}')).toEqual(['{"not": "an array"}'])
- })
-
- it('handles JSON with trailing comma', () => {
- expect(parseTagsFilter('["tag1", "tag2",]')).toEqual(['["tag1"', '"tag2"', ']'])
- })
- })
-
- describe('comma-separated string input', () => {
- it('parses simple comma-separated values', () => {
- expect(parseTagsFilter('tag1,tag2,tag3')).toEqual(['tag1', 'tag2', 'tag3'])
- })
-
- it('trims whitespace from values', () => {
- expect(parseTagsFilter(' tag1 , tag2 , tag3 ')).toEqual(['tag1', 'tag2', 'tag3'])
- })
-
- it('filters out empty values', () => {
- expect(parseTagsFilter('tag1,,tag2, ,tag3')).toEqual(['tag1', 'tag2', 'tag3'])
- })
-
- it('handles single value', () => {
- expect(parseTagsFilter('tag1')).toEqual(['tag1'])
- })
-
- it('handles empty string', () => {
- expect(parseTagsFilter('')).toEqual([])
- })
-
- it('handles string with only whitespace', () => {
- expect(parseTagsFilter(' ')).toEqual([])
- })
-
- it('handles string with only commas', () => {
- expect(parseTagsFilter(',,')).toEqual([])
- })
-
- it('handles string with commas and whitespace', () => {
- expect(parseTagsFilter(' , , ')).toEqual([])
- })
- })
-
- describe('edge cases and invalid input', () => {
- it('returns undefined for null input', () => {
- expect(parseTagsFilter(null)).toBeUndefined()
- })
-
- it('returns undefined for undefined input', () => {
- expect(parseTagsFilter(undefined)).toBeUndefined()
- })
-
- it('returns undefined for number input', () => {
- expect(parseTagsFilter(123)).toBeUndefined()
- })
-
- it('returns undefined for boolean input', () => {
- expect(parseTagsFilter(true)).toBeUndefined()
- expect(parseTagsFilter(false)).toBeUndefined()
- })
-
- it('returns undefined for object input', () => {
- expect(parseTagsFilter({})).toBeUndefined()
- expect(parseTagsFilter({ tags: ['tag1'] })).toBeUndefined()
- })
-
- it('handles special characters in tags', () => {
- expect(parseTagsFilter('tag-with-dash,tag_with_underscore,tag.with.dots')).toEqual([
- 'tag-with-dash',
- 'tag_with_underscore',
- 'tag.with.dots',
- ])
- })
-
- it('handles unicode characters', () => {
- expect(parseTagsFilter('标签1,🏷️,тег')).toEqual(['标签1', '🏷️', 'тег'])
- })
-
- it('handles very long strings', () => {
- const longTag = 'a'.repeat(1000)
- expect(parseTagsFilter(longTag)).toEqual([longTag])
- })
-
- it('handles strings with newlines and tabs', () => {
- expect(parseTagsFilter('tag1\ntag2\ttag3')).toEqual(['tag1\ntag2\ttag3'])
- })
- })
- })
-
- describe('formatDateTimeRange()', () => {
- beforeEach(() => {
- tk.freeze(new Date('2025-03-15T12:00:00.000Z'))
- })
- afterEach(() => {
- tk.reset()
- })
-
- it('formats range in different years with full details', () => {
- const from = dayjs('2024-12-31T14:30:45')
- const to = dayjs('2025-01-01T16:45:30')
- expect(formatDateTimeRange(from, to)).toEqual('December 31, 2024 14:30:45 - January 1, 2025 16:45:30')
- })
-
- it('formats range in same year but different days', () => {
- const from = dayjs('2024-06-15T09:00:00')
- const to = dayjs('2024-06-20T17:30:00')
- expect(formatDateTimeRange(from, to)).toEqual('June 15, 2024 09:00 - June 20, 17:30')
- })
-
- it('hides time if both times are midnight', () => {
- const from = dayjs('2024-06-15T00:00:00')
- const to = dayjs('2024-06-20T00:00:00')
- expect(formatDateTimeRange(from, to)).toEqual('June 15, 2024 - June 20')
- })
-
- it('formats range in same year as current year', () => {
- const from = dayjs('2025-01-10T10:15:00')
- const to = dayjs('2025-02-05T14:20:00')
- expect(formatDateTimeRange(from, to)).toEqual('January 10, 10:15 - February 5, 14:20')
- })
-
- it('formats range on same day in different year', () => {
- const from = dayjs('2024-08-10T09:30:00')
- const to = dayjs('2024-08-10T18:45:00')
- expect(formatDateTimeRange(from, to)).toEqual('August 10, 2024 09:30 - 18:45')
- })
-
- it('formats range on same day in current year', () => {
- const from = dayjs('2025-03-15T08:00:00')
- const to = dayjs('2025-03-15T20:00:00')
- expect(formatDateTimeRange(from, to)).toEqual('08:00 - 20:00')
- })
-
- it('removes seconds when both times have zero seconds on same day', () => {
- const from = dayjs('2025-03-15T10:30:00')
- const to = dayjs('2025-03-15T14:45:00')
- expect(formatDateTimeRange(from, to)).toEqual('10:30 - 14:45')
- })
-
- it('includes seconds when start time has non-zero seconds', () => {
- const from = dayjs('2025-03-15T10:30:15')
- const to = dayjs('2025-03-15T14:45:00')
- expect(formatDateTimeRange(from, to)).toEqual('10:30:15 - 14:45:00')
- })
-
- it('includes seconds when end time has non-zero seconds', () => {
- const from = dayjs('2025-03-15T10:30:00')
- const to = dayjs('2025-03-15T14:45:30')
- expect(formatDateTimeRange(from, to)).toEqual('10:30:00 - 14:45:30')
- })
-
- it('includes seconds when both times have non-zero seconds', () => {
- const from = dayjs('2025-03-15T10:30:15')
- const to = dayjs('2025-03-15T14:45:30')
- expect(formatDateTimeRange(from, to)).toEqual('10:30:15 - 14:45:30')
- })
-
- it('handles range spanning different days in current year', () => {
- const from = dayjs('2025-03-14T22:00:00')
- const to = dayjs('2025-03-16T02:00:00')
- expect(formatDateTimeRange(from, to)).toEqual('March 14, 22:00 - March 16, 02:00')
- })
-
- it('handles very short time ranges on same day', () => {
- const from = dayjs('2025-03-15T12:00:00')
- const to = dayjs('2025-03-15T12:01:00')
- expect(formatDateTimeRange(from, to)).toEqual('12:00 - 12:01')
- })
- })
-
- describe('formatPercentageDiff()', () => {
- it.each([
- { current: 150, previous: 100, expected: '(+50.0%)' },
- { current: 200, previous: 100, expected: '(+100.0%)' },
- { current: 100, previous: 100, expected: '(+0.0%)' },
- { current: 50, previous: 100, expected: '(-50.0%)' },
- { current: 0, previous: 100, expected: '(-100.0%)' },
- { current: 125, previous: 100, expected: '(+25.0%)' },
- { current: 75, previous: 100, expected: '(-25.0%)' },
- ])('formats $current vs $previous as $expected', ({ current, previous, expected }) => {
- expect(formatPercentageDiff(current, previous)).toEqual(expected)
- })
-
- it.each([
- { current: 100, previous: 0, description: 'division by zero' },
- { current: 0, previous: 0, description: 'zero divided by zero' },
- ])('returns null for $description', ({ current, previous }) => {
- expect(formatPercentageDiff(current, previous)).toBeNull()
- })
- })
-
- describe('retryWithBackoff()', () => {
- it('returns result on first successful attempt', async () => {
- const fn = jest.fn().mockResolvedValue('success')
- const result = await retryWithBackoff(fn, { initialDelayMs: 0 })
- expect(result).toBe('success')
- expect(fn).toHaveBeenCalledTimes(1)
- })
-
- it('retries on failure and succeeds', async () => {
- const fn = jest
- .fn()
- .mockRejectedValueOnce(new Error('fail 1'))
- .mockRejectedValueOnce(new Error('fail 2'))
- .mockResolvedValue('success')
-
- const result = await retryWithBackoff(fn, { maxAttempts: 3, initialDelayMs: 0 })
- expect(result).toBe('success')
- expect(fn).toHaveBeenCalledTimes(3)
- })
-
- it('throws last error after all attempts exhausted', async () => {
- const errors = [new Error('fail 1'), new Error('fail 2'), new Error('fail 3')]
- let callCount = 0
- const fn = jest.fn().mockImplementation(() => Promise.reject(errors[callCount++]))
-
- await expect(retryWithBackoff(fn, { maxAttempts: 3, initialDelayMs: 0 })).rejects.toThrow('fail 3')
- expect(fn).toHaveBeenCalledTimes(3)
- })
-
- it('re-throws AbortError immediately without retrying', async () => {
- const fn = jest.fn().mockImplementation(() => {
- const error = new DOMException('Aborted', 'AbortError')
- return Promise.reject(error)
- })
-
- await expect(retryWithBackoff(fn, { maxAttempts: 3, initialDelayMs: 0 })).rejects.toThrow('Aborted')
- expect(fn).toHaveBeenCalledTimes(1)
- })
-
- it('throws immediately if signal is already aborted', async () => {
- const controller = new AbortController()
- controller.abort()
-
- const fn = jest.fn().mockResolvedValue('success')
- await expect(retryWithBackoff(fn, { signal: controller.signal })).rejects.toThrow('Aborted')
- expect(fn).not.toHaveBeenCalled()
- })
-
- it('applies exponential backoff between retries', async () => {
- jest.useFakeTimers()
- try {
- let callCount = 0
- const fn = jest.fn().mockImplementation(() => {
- callCount++
- if (callCount < 3) {
- return Promise.reject(new Error('fail'))
- }
- return Promise.resolve('success')
- })
-
- const promise = retryWithBackoff(fn, {
- maxAttempts: 3,
- initialDelayMs: 1000,
- backoffMultiplier: 2,
- })
-
- // First call happens immediately
- await Promise.resolve()
- expect(fn).toHaveBeenCalledTimes(1)
-
- // After 1000ms (initialDelayMs * 2^0), second attempt
- await jest.advanceTimersByTimeAsync(1000)
- expect(fn).toHaveBeenCalledTimes(2)
-
- // After 2000ms (initialDelayMs * 2^1), third attempt
- await jest.advanceTimersByTimeAsync(2000)
- expect(fn).toHaveBeenCalledTimes(3)
-
- await expect(promise).resolves.toBe('success')
- } finally {
- jest.useRealTimers()
- }
- })
-
- it('uses default options when none provided', async () => {
- const errors = [new Error('fail'), new Error('fail'), new Error('fail')]
- let callCount = 0
- const fn = jest.fn().mockImplementation(() => Promise.reject(errors[callCount++]))
-
- await expect(retryWithBackoff(fn, { initialDelayMs: 0 })).rejects.toThrow('fail')
- expect(fn).toHaveBeenCalledTimes(3) // default maxAttempts is 3
- })
-
- it('handles maxAttempts of 1 (no retries)', async () => {
- const fn = jest.fn().mockImplementation(() => Promise.reject(new Error('fail')))
-
- await expect(retryWithBackoff(fn, { maxAttempts: 1, initialDelayMs: 0 })).rejects.toThrow('fail')
- expect(fn).toHaveBeenCalledTimes(1)
- })
-
- it('does not retry when shouldRetry returns false', async () => {
- const error = new Error('non-retryable')
- const fn = jest.fn().mockImplementation(() => Promise.reject(error))
-
- await expect(
- retryWithBackoff(fn, {
- maxAttempts: 3,
- initialDelayMs: 0,
- shouldRetry: () => false,
- })
- ).rejects.toThrow('non-retryable')
- expect(fn).toHaveBeenCalledTimes(1)
- })
-
- it('retries when shouldRetry returns true', async () => {
- let callCount = 0
- const fn = jest.fn().mockImplementation(() => {
- callCount++
- if (callCount < 3) {
- return Promise.reject(new Error('retryable'))
- }
- return Promise.resolve('success')
- })
-
- const result = await retryWithBackoff(fn, {
- maxAttempts: 3,
- initialDelayMs: 0,
- shouldRetry: () => true,
- })
- expect(result).toBe('success')
- expect(fn).toHaveBeenCalledTimes(3)
- })
-
- it('stops retrying when shouldRetry returns false for specific error', async () => {
- const errors = [new Error('retry-me'), new Error('stop-here'), new Error('never-reached')]
- let callCount = 0
- const fn = jest.fn().mockImplementation(() => Promise.reject(errors[callCount++]))
-
- await expect(
- retryWithBackoff(fn, {
- maxAttempts: 3,
- initialDelayMs: 0,
- shouldRetry: (e) => e instanceof Error && e.message !== 'stop-here',
- })
- ).rejects.toThrow('stop-here')
- expect(fn).toHaveBeenCalledTimes(2)
- })
-
- it('receives the error in shouldRetry callback', async () => {
- const testError = new Error('test-error')
- const fn = jest.fn().mockImplementation(() => Promise.reject(testError))
- const shouldRetry = jest.fn().mockReturnValue(false)
-
- await expect(retryWithBackoff(fn, { maxAttempts: 3, initialDelayMs: 0, shouldRetry })).rejects.toThrow(
- 'test-error'
- )
- expect(shouldRetry).toHaveBeenCalledWith(testError)
- })
- })
-
- describe('isOperatorMulti', () => {
- it('returns true for operators that support multiple values', () => {
- expect(isOperatorMulti(PropertyOperator.Exact)).toBe(true)
- expect(isOperatorMulti(PropertyOperator.IsNot)).toBe(true)
- expect(isOperatorMulti(PropertyOperator.IContainsMulti)).toBe(true)
- expect(isOperatorMulti(PropertyOperator.NotIContainsMulti)).toBe(true)
- })
-
- it('returns false for operators that do not support multiple values', () => {
- expect(isOperatorMulti(PropertyOperator.IContains)).toBe(false)
- expect(isOperatorMulti(PropertyOperator.NotIContains)).toBe(false)
- expect(isOperatorMulti(PropertyOperator.GreaterThan)).toBe(false)
- expect(isOperatorMulti(PropertyOperator.LessThan)).toBe(false)
- expect(isOperatorMulti(PropertyOperator.IsSet)).toBe(false)
- expect(isOperatorMulti(PropertyOperator.IsNotSet)).toBe(false)
- expect(isOperatorMulti(PropertyOperator.Regex)).toBe(false)
- })
- })
-})
diff --git a/frontend/src/lib/utils.tsx b/frontend/src/lib/utils.tsx
deleted file mode 100644
index ba4ce6795b79..000000000000
--- a/frontend/src/lib/utils.tsx
+++ /dev/null
@@ -1,2550 +0,0 @@
-import equal from 'fast-deep-equal'
-import posthog from 'posthog-js'
-import { CSSProperties } from 'react'
-
-import { tagColors } from 'lib/colors'
-import { Dayjs, dayjs } from 'lib/dayjs'
-
-import {
- ActionType,
- ActorType,
- DateMappingOption,
- EventType,
- GroupActorType,
- IntervalType,
- PropertyOperator,
- PropertyType,
- SessionActorType,
- TimeUnitType,
-} from '~/types'
-
-import { CUSTOM_OPTION_KEY } from './components/DateFilter/types'
-import { LemonTagType } from './lemon-ui/LemonTag'
-import { getAppContext } from './utils/getAppContext'
-import { getPrimaryPropertyForEvent } from './utils/primaryEventProperty'
-
-// WARNING: Be very careful importing things here. This file is heavily used and can trigger a lot of cyclic imports
-// Preferably create a dedicated file in utils/..
-
-export function uuid(): string {
- return '10000000-1000-4000-8000-100000000000'.replace(/[018]/g, (c) =>
- (
- parseInt(c) ^
- ((typeof window?.crypto !== 'undefined' // in node tests, jsdom doesn't implement window.crypto
- ? window.crypto.getRandomValues(new Uint8Array(1))[0]
- : Math.floor(Math.random() * 256)) &
- (15 >> (parseInt(c) / 4)))
- ).toString(16)
- )
-}
-
-export function areObjectValuesEmpty(obj?: Record<string, any>): boolean {
- return (
- !!obj && typeof obj === 'object' && !Object.values(obj).some((x) => x !== null && x !== '' && x !== undefined)
- )
-}
-
-// taken from https://stackoverflow.com/questions/10420352/converting-file-size-in-bytes-to-human-readable-string/10420404
-export const humanizeBytes = (fileSizeInBytes: number | null): string => {
- if (fileSizeInBytes === null) {
- return ''
- }
-
- let i = -1
- let convertedBytes = fileSizeInBytes
- const byteUnits = ['kB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB']
- do {
- convertedBytes = convertedBytes / 1024
- i++
- } while (convertedBytes > 1024)
-
- if (convertedBytes < 0.1) {
- return fileSizeInBytes + ' bytes'
- }
- return convertedBytes.toFixed(2) + ' ' + byteUnits[i]
-}
-
-export function toSentenceCase(str: string): string {
- return str.replace(/\b\w/g, (c) => c.toUpperCase())
-}
-
-export function toParams(obj: Record<string, any>, explodeArrays: boolean = false): string {
- if (!obj) {
- return ''
- }
-
- function handleVal(val: any): string {
- if (dayjs.isDayjs(val)) {
- return encodeURIComponent(val.format('YYYY-MM-DD'))
- }
- val = typeof val === 'object' ? JSON.stringify(val) : val
- return encodeURIComponent(val)
- }
-
- return Object.entries(obj)
- .filter((item) => item[1] != undefined && item[1] != null)
- .reduce(
- (acc, [key, val]) => {
- /**
- * query parameter arrays can be handled in two ways
- * either they are encoded as a single query parameter
- * a=[1, 2] => a=%5B1%2C2%5D
- * or they are "exploded" so each item in the array is sent separately
- * a=[1, 2] => a=1&a=2
- **/
- if (explodeArrays && Array.isArray(val)) {
- val.forEach((v) => acc.push([key, v]))
- } else {
- acc.push([key, val])
- }
-
- return acc
- },
- [] as [string, any][]
- )
- .map(([key, val]) => `${key}=${handleVal(val)}`)
- .join('&')
-}
-
-export function fromParamsGivenUrl(url: string): Record<string, any> {
- return !url
- ? {}
- : url
- .replace(/^\?/, '')
- .split('&')
- .reduce(
- (paramsObject, paramString) => {
- const [key, value] = paramString.split('=')
- paramsObject[key] = decodeURIComponent(value)
- return paramsObject
- },
- {} as Record<string, any>
- )
-}
-
-export function fromParams(): Record<string, any> {
- return fromParamsGivenUrl(window.location.search)
-}
-
-export function tryDecodeURIComponent(value: string): string {
- try {
- return decodeURIComponent(value)
- } catch {
- return value
- }
-}
-
-// Parse a tags filter value coming from URL search params.
-// Supports:
-// - Repeated params handled upstream and aggregated as an array
-// - JSON array string (e.g. "[\"a\",\"b\"]")
-// - Comma-separated string (e.g. "a,b")
-export function parseTagsFilter(raw: unknown): string[] | undefined {
- if (Array.isArray(raw)) {
- return (raw as unknown[]).map((v) => String(v)).filter(Boolean)
- }
- if (typeof raw === 'string') {
- // Try JSON first
- try {
- const parsed = JSON.parse(raw)
- if (Array.isArray(parsed)) {
- return parsed.map((v) => String(v)).filter(Boolean)
- }
- } catch {
- // Fall through to comma-separated
- }
- return raw
- .split(',')
- .map((s) => s.trim())
- .filter(Boolean)
- }
- return undefined
-}
-
-/** Return percentage from number, e.g. 0.234 is 23.4%. */
-export function percentage(
- division: number,
- maximumFractionDigits: number = DEFAULT_DECIMAL_PLACES,
- fixedPrecision: boolean = false
-): string {
- if (division === Infinity) {
- return '∞%'
- }
-
- const maxDigits = validateFractionDigits(maximumFractionDigits, DEFAULT_DECIMAL_PLACES)
-
- return division.toLocaleString('en-US', {
- style: 'percent',
- maximumFractionDigits: maxDigits,
- minimumFractionDigits: fixedPrecision ? maxDigits : undefined,
- })
-}
-
-/**
- * Formats the percentage difference between two values for display.
- * Returns null if the result would be NaN or Infinity (e.g., division by zero).
- */
-export function formatPercentageDiff(current: number, previous: number): string | null {
- const diff = (current - previous) / previous
-
- if (!Number.isFinite(diff)) {
- return null
- }
-
- return diff >= 0 ? `(+${(diff * 100).toFixed(1)}%)` : `(-${(-diff * 100).toFixed(1)}%)`
-}
-
-export const selectStyle: Record<string, (base: Partial<CSSProperties>) => Partial<CSSProperties>> = {
- control: (base) => ({
- ...base,
- height: 31,
- minHeight: 31,
- }),
- indicatorsContainer: (base) => ({
- ...base,
- height: 31,
- }),
- input: (base) => ({
- ...base,
- paddingBottom: 0,
- paddingTop: 0,
- margin: 0,
- opacity: 1,
- }),
- valueContainer: (base) => ({
- ...base,
- padding: '0 8px',
- marginTop: -2,
- }),
- option: (base) => ({
- ...base,
- padding: '2px 15px',
- }),
-}
-
-export function splitKebabCase(string: string): string {
- return string.replace(/-/g, ' ')
-}
-
-export function capitalizeFirstLetter(string: string): string {
- return string.charAt(0).toUpperCase() + string.slice(1)
-}
-
-export function lowercaseFirstLetter(string: string): string {
- return string.charAt(0).toLowerCase() + string.slice(1)
-}
-
-export function getOrdinalSuffix(num: number): string {
- const j = num % 10
- const k = num % 100
- if (j === 1 && k !== 11) {
- return 'st'
- }
- if (j === 2 && k !== 12) {
- return 'nd'
- }
- if (j === 3 && k !== 13) {
- return 'rd'
- }
- return 'th'
-}
-
-export function fullName(props?: { first_name?: string; last_name?: string }): string {
- if (!props) {
- return 'Unknown User'
- }
- return `${props.first_name || ''} ${props.last_name || ''}`.trim()
-}
-
-export const genericOperatorMap: Record<string, string> = {
- exact: '= equals',
- is_not: "≠ doesn't equal",
- icontains: '∋ contains',
- not_icontains: "∌ doesn't contain",
- regex: '∼ matches regex',
- not_regex: "≁ doesn't match regex",
- gt: '> greater than',
- gte: '≥ greater than or equal',
- lt: '< less than',
- lte: '≤ less than or equal',
- is_set: '✓ is set',
- is_not_set: '✕ is not set',
-}
-
-export const stringOperatorMap: Record<string, string> = {
- exact: '= equals',
- is_not: "≠ doesn't equal",
- icontains: '∋ contains',
- not_icontains: "∌ doesn't contain",
- regex: '∼ matches regex',
- not_regex: "≁ doesn't match regex",
- is_set: '✓ is set',
- is_not_set: '✕ is not set',
- semver_eq: '= equals (semver)',
- semver_neq: '≠ not equal (semver)',
- semver_gt: '> greater than (semver)',
- semver_gte: '≥ greater than or equal (semver)',
- semver_lt: '< less than (semver)',
- semver_lte: '≤ less than or equal (semver)',
- semver_tilde: '~ tilde range (semver)',
- semver_caret: '^ caret range (semver)',
- semver_wildcard: '* wildcard (semver)',
-}
-
-export const stringArrayOperatorMap: Record<string, string> = {
- exact: '= equals',
- is_not: "≠ doesn't equal",
- icontains: '∋ contains',
- not_icontains: "∌ doesn't contain",
- regex: '∼ matches regex',
- not_regex: "≁ doesn't match regex",
-}
-
-export const numericOperatorMap: Record<string, string> = {
- exact: '= equals',
- is_not: "≠ doesn't equal",
- regex: '∼ matches regex',
- not_regex: "≁ doesn't match regex",
- gt: '> greater than',
- gte: '≥ greater than or equal',
- lt: '< less than',
- lte: '≤ less than or equal',
- is_set: '✓ is set',
- is_not_set: '✕ is not set',
-}
-
-export const dateTimeOperatorMap: Record<string, string> = {
- is_date_exact: '= equals',
- is_date_before: '< before',
- is_date_after: '> after',
- is_set: '✓ is set',
- is_not_set: '✕ is not set',
-}
-
-export const booleanOperatorMap: Record<string, string> = {
- exact: '= equals',
- is_not: "≠ doesn't equal",
- is_set: '✓ is set',
- is_not_set: '✕ is not set',
-}
-
-export const durationOperatorMap: Record<string, string> = {
- gt: '> greater than',
- lt: '< less than',
-}
-
-export const selectorOperatorMap: Record<string, string> = {
- exact: '= equals',
- is_not: "≠ doesn't equal",
-}
-
-export const cohortOperatorMap: Record<string, string> = {
- in: 'user in',
- not_in: 'user not in',
-}
-
-export const featureFlagOperatorMap: Record<string, string> = {
- flag_evaluates_to: '= evaluates to',
-}
-
-export const stickinessOperatorMap: Record<string, string> = {
- exact: '= exactly',
- gte: '≥ at least',
- lte: '≤ at most (but at least once)',
-}
-
-export const cleanedPathOperatorMap: Record<string, string> = {
- is_cleaned_path_exact: '= equals',
-}
-
-export const semverOperatorMap: Record<string, string> = {
- semver_eq: '= equals (semver)',
- semver_neq: '≠ not equal (semver)',
- semver_gt: '> greater than (semver)',
- semver_gte: '≥ greater than or equal (semver)',
- semver_lt: '< less than (semver)',
- semver_lte: '≤ less than or equal (semver)',
- semver_tilde: '~ tilde range (semver)',
- semver_caret: '^ caret range (semver)',
- semver_wildcard: '* wildcard (semver)',
-}
-
-export const assigneeOperatorMap: Record<string, string> = {
- exact: '= is',
- is_not: '≠ is not',
- is_not_set: '✕ is not set',
-}
-
-export const allOperatorsMapping: Record<string, string> = {
- ...assigneeOperatorMap,
- ...stickinessOperatorMap,
- ...dateTimeOperatorMap,
- ...semverOperatorMap,
- ...stringArrayOperatorMap,
- ...numericOperatorMap,
- ...genericOperatorMap,
- ...booleanOperatorMap,
- ...durationOperatorMap,
- ...selectorOperatorMap,
- ...cohortOperatorMap,
- ...featureFlagOperatorMap,
- ...cleanedPathOperatorMap,
- ...stringOperatorMap,
- // slight overkill to spread all of these into the map
- // but gives freedom for them to diverge more over time
-}
-
-const operatorMappingChoice: Record<keyof typeof PropertyType, Record<string, string>> = {
- DateTime: dateTimeOperatorMap,
- String: stringOperatorMap,
- Numeric: numericOperatorMap,
- Boolean: booleanOperatorMap,
- Duration: durationOperatorMap,
- Selector: selectorOperatorMap,
- Cohort: cohortOperatorMap,
- Flag: featureFlagOperatorMap,
- Assignee: assigneeOperatorMap,
- StringArray: stringArrayOperatorMap,
- Semver: semverOperatorMap,
-}
-
-export function chooseOperatorMap(propertyType: PropertyType | undefined): Record<string, string> {
- let choice = genericOperatorMap
- if (propertyType) {
- choice = operatorMappingChoice[propertyType] || genericOperatorMap
- }
- return choice
-}
-
-export function isOperatorMulti(operator: PropertyOperator): boolean {
- return [
- PropertyOperator.Exact,
- PropertyOperator.IsNot,
- PropertyOperator.IContainsMulti,
- PropertyOperator.NotIContainsMulti,
- ].includes(operator)
-}
-
-export function isOperatorFlag(operator: PropertyOperator): boolean {
- // these filter operators can only be just set, no additional parameter
- return [PropertyOperator.IsSet, PropertyOperator.IsNotSet, PropertyOperator.In, PropertyOperator.NotIn].includes(
- operator
- )
-}
-
-export function isOperatorCohort(operator: PropertyOperator): boolean {
- // these filter operators use value different ( to represent the number of the cohort )
- return [PropertyOperator.In, PropertyOperator.NotIn].includes(operator)
-}
-
-export function isOperatorRegex(operator: PropertyOperator): boolean {
- return [PropertyOperator.Regex, PropertyOperator.NotRegex].includes(operator)
-}
-
-export function isOperatorSemver(operator: PropertyOperator): boolean {
- return [
- PropertyOperator.SemverEq,
- PropertyOperator.SemverNeq,
- PropertyOperator.SemverGt,
- PropertyOperator.SemverGte,
- PropertyOperator.SemverLt,
- PropertyOperator.SemverLte,
- PropertyOperator.SemverTilde,
- PropertyOperator.SemverCaret,
- PropertyOperator.SemverWildcard,
- ].includes(operator)
-}
-
-export function isOperatorRange(operator: PropertyOperator): boolean {
- return [
- PropertyOperator.GreaterThan,
- PropertyOperator.GreaterThanOrEqual,
- PropertyOperator.LessThan,
- PropertyOperator.LessThanOrEqual,
- PropertyOperator.Between,
- PropertyOperator.NotBetween,
- ].includes(operator)
-}
-
-export function isOperatorDate(operator: PropertyOperator): boolean {
- return [PropertyOperator.IsDateBefore, PropertyOperator.IsDateAfter, PropertyOperator.IsDateExact].includes(
- operator
- )
-}
-
-export function isOperatorBetween(operator: PropertyOperator): boolean {
- return [PropertyOperator.Between, PropertyOperator.NotBetween].includes(operator)
-}
-
-/** Compare objects deeply. */
-export function objectsEqual(obj1: any, obj2: any): boolean {
- return equal(obj1, obj2)
-}
-
-export function isString(candidate: unknown): candidate is string {
- return typeof candidate === 'string'
-}
-
-export function isNumber(candidate: unknown): candidate is number {
- return typeof candidate === 'number'
-}
-
-export function isObject(candidate: unknown): candidate is Record<string, unknown> {
- return typeof candidate === 'object' && candidate !== null && !Array.isArray(candidate)
-}
-
-export function isEmptyObject(candidate: unknown): boolean {
- return isObject(candidate) && Object.keys(candidate).length === 0
-}
-
-export function isNonEmptyObject(candidate: unknown): candidate is Record<string, unknown> {
- return isObject(candidate) && !isEmptyObject(candidate)
-}
-
-/** Check whether a runtime key exists on an object and narrow it to `keyof T`. */
-export function isKeyOf<T extends object>(key: any, obj: T): key is keyof T {
- return key in obj
-}
-
-// https://stackoverflow.com/questions/25421233/javascript-removing-undefined-fields-from-an-object
-export function objectClean<T extends Record<string | number | symbol, unknown>>(
- obj: T,
- options?: { removeNulls?: boolean }
-): T {
- const { removeNulls = false } = options || {}
- const response = { ...obj }
- Object.keys(response).forEach((key) => {
- if (removeNulls ? response[key] == null : response[key] === undefined) {
- delete response[key]
- }
- })
- return response
-}
-export function objectCleanWithEmpty<T extends Record<string | number | symbol, unknown>>(
- obj: T,
- ignoredKeys: string[] = []
-): T {
- const response = { ...obj }
- Object.keys(response)
- .filter((key) => !ignoredKeys.includes(key))
- .forEach((key) => {
- // remove undefined values
- if (response[key] === undefined) {
- delete response[key]
- }
- // remove empty arrays i.e. []
- if (
- typeof response[key] === 'object' &&
- Array.isArray(response[key]) &&
- (response[key] as unknown[]).length === 0
- ) {
- delete response[key]
- }
- // remove empty objects i.e. {}
- if (
- typeof response[key] === 'object' &&
- !Array.isArray(response[key]) &&
- response[key] !== null &&
- Object.keys(response[key] as Record<string | number | symbol, unknown>).length === 0
- ) {
- delete response[key]
- }
- })
- return response
-}
-
-export const removeUndefinedAndNull = (obj: any): any => {
- if (Array.isArray(obj)) {
- return obj.map(removeUndefinedAndNull)
- } else if (obj && typeof obj === 'object') {
- return Object.entries(obj).reduce(
- (acc, [key, value]) => {
- if (value !== undefined && value !== null) {
- acc[key] = removeUndefinedAndNull(value)
- }
- return acc
- },
- {} as Record<string, any>
- )
- }
- return obj
-}
-
-/** Returns "response" from: obj2 = { ...obj1, ...response } */
-export function objectDiffShallow(obj1: Record<string, any>, obj2: Record<string, any>): Record<string, any> {
- const response: Record<string, any> = { ...obj2 }
- for (const key of Object.keys(obj1)) {
- if (key in response) {
- if (obj1[key] === response[key]) {
- delete response[key]
- }
- } else {
- response[key] = undefined
- }
- }
- return response
-}
-
-export function idToKey(array: Record<string, any>[], keyField: string = 'id'): Record<string, any> {
- const object: Record<string, any> = {}
- for (const element of array) {
- object[element[keyField]] = element
- }
- return object
-}
-
-export function makeDelay(ms: number): () => Promise<void> {
- return () => delay(ms)
-}
-
-export function delay(ms: number, signal?: AbortSignal): Promise<void> {
- return new Promise((resolve, reject) => {
- const timeoutId = setTimeout(resolve, ms)
- if (signal) {
- signal.addEventListener('abort', () => {
- clearTimeout(timeoutId)
- reject(new DOMException('Aborted', 'AbortError'))
- })
- }
- })
-}
-
-export interface RetryOptions {
- /** Maximum number of attempts before giving up. Defaults to 3. */
- maxAttempts?: number
- /** Initial delay in milliseconds before the first retry. Defaults to 1000. */
- initialDelayMs?: number
- /** Multiplier applied to delay after each failed attempt. Defaults to 1.5. */
- backoffMultiplier?: number
- /** AbortSignal to cancel retries. If aborted, throws AbortError immediately. */
- signal?: AbortSignal
- /**
- * Predicate to determine if an error should trigger a retry.
- * Return true to retry, false to throw immediately.
- * Defaults to retrying all errors except AbortError.
- *
- * @example
- * // Only retry network errors and 5xx server errors
- * shouldRetry: (error) => {
- * if (error instanceof Error && 'status' in error) {
- * const status = (error as any).status
- * return status >= 500 || status === 0 // 0 = network error
- * }
- * return true // retry unknown errors
- * }
- */
- shouldRetry?: (error: unknown) => boolean
-}
-
-/**
- * Retries a function with exponential backoff on failure.
- *
- * @param fn - The async function to retry
- * @param options - Configuration options for retry behavior
- * @returns The result of the function if successful
- * @throws The last error encountered if all attempts fail, or AbortError if cancelled
- *
- * @example
- * const data = await retryWithBackoff(() => api.fetchData(), {
- * maxAttempts: 3,
- * initialDelayMs: 1000,
- * backoffMultiplier: 1.5
- * })
- * // Delays: 1000ms after 1st failure, 1500ms after 2nd failure
- */
-export async function retryWithBackoff<T>(fn: () => Promise<T>, options: RetryOptions = {}): Promise<T> {
- const { maxAttempts = 3, initialDelayMs = 1000, backoffMultiplier = 1.5, signal, shouldRetry } = options
-
- if (signal?.aborted) {
- throw new DOMException('Aborted', 'AbortError')
- }
-
- const attempts = Math.max(maxAttempts, 1)
-
- let lastError: unknown
- for (let attempt = 0; attempt < attempts; attempt++) {
- try {
- return await fn()
- } catch (e) {
- if (e instanceof DOMException && e.name === 'AbortError') {
- throw e
- }
- lastError = e
- const isLastAttempt = attempt >= attempts - 1
- const canRetry = shouldRetry ? shouldRetry(e) : true
- if (isLastAttempt || !canRetry) {
- throw e
- }
- const delayMs = initialDelayMs * Math.pow(backoffMultiplier, attempt)
- await delay(delayMs, signal)
- }
- }
- throw lastError
-}
-
-export function clearDOMTextSelection(): void {
- if (window.getSelection) {
- if (window.getSelection()?.empty) {
- // Chrome
- window.getSelection()?.empty()
- } else if (window.getSelection()?.removeAllRanges) {
- // Firefox
- window.getSelection()?.removeAllRanges()
- }
- } else if ((document as any).selection) {
- // IE?
- ;(document as any).selection.empty()
- }
-}
-
-// trimBothEnds=false is useful when the input is slugified as the user is typing to allow them hitting space and continue typing
-export function slugify(
- text: string,
- { trimBothEnds = true, lowercase = true }: { trimBothEnds?: boolean; lowercase?: boolean } = {}
-): string {
- let result = text.toString()
- if (lowercase) {
- result = result.toLowerCase()
- }
- return result
- .normalize('NFD') // The normalize() method returns the Unicode Normalization Form of a given string.
- [trimBothEnds ? 'trim' : 'trimStart']()
- .replace(/\s+/g, '-') // Replace spaces with -
- .replace(/[^\w-]+/g, '') // Remove all non-word chars
- .replace(/--+/g, '-')
-}
-
-export const DEFAULT_DECIMAL_PLACES = 2
-
-function validateFractionDigits(maximumFractionDigits: number, fallback: number): number {
- if (
- isNaN(maximumFractionDigits) ||
- !Number.isInteger(maximumFractionDigits) ||
- maximumFractionDigits < 0 ||
- maximumFractionDigits > 100
- ) {
- return fallback
- }
- return maximumFractionDigits
-}
-
-/** Format number with comma as the thousands separator. */
-export function humanFriendlyNumber(
- d: number,
- maximumFractionDigits: number = DEFAULT_DECIMAL_PLACES,
- minimumFractionDigits: number = 0
-): string {
- return d.toLocaleString('en-US', {
- maximumFractionDigits: validateFractionDigits(maximumFractionDigits, DEFAULT_DECIMAL_PLACES),
- minimumFractionDigits: validateFractionDigits(minimumFractionDigits, 0),
- })
-}
-
-export function humanFriendlyLargeNumber(d: number): string {
- if (isNaN(d)) {
- return 'NaN'
- } else if (!isFinite(d)) {
- if (d > 0) {
- return 'inf'
- }
- return '-inf'
- }
- const trillion = 1_000_000_000_000
- const billion = 1_000_000_000
- const million = 1_000_000
- const thousand = 1_000
-
- // handle positive number only to make life easier
- const prefix = d >= 0 ? '' : '-'
- d = Math.abs(d)
-
- // round to 3 significant figures
- d = parseFloat(d.toPrecision(3))
-
- if (d >= trillion) {
- return `${prefix}${(d / trillion).toString()}T`
- } else if (d >= billion) {
- return `${prefix}${(d / billion).toString()}B`
- }
- if (d >= million) {
- return `${prefix}${(d / million).toString()}M`
- }
- if (d >= thousand) {
- return `${prefix}${(d / thousand).toString()}K`
- }
- return `${prefix}${d}`
-}
-
-/** Format currency from string with commas and a number of decimal places (defaults to 2). */
-export function humanFriendlyCurrency(
- d: string | undefined | number,
- precision: number = DEFAULT_DECIMAL_PLACES
-): string {
- if (!d) {
- d = '0.00'
- }
-
- let number: number
- if (typeof d === 'string') {
- number = parseFloat(d)
- } else {
- number = d
- }
-
- const validatedPrecision = validateFractionDigits(precision, DEFAULT_DECIMAL_PLACES)
- return `$${number.toLocaleString('en-US', { maximumFractionDigits: validatedPrecision, minimumFractionDigits: validatedPrecision })}`
-}
-
-export const humanFriendlyMilliseconds = (timestamp: number | undefined): string | undefined => {
- if (typeof timestamp !== 'number') {
- return undefined
- }
-
- if (timestamp < 1000) {
- return `${Math.ceil(timestamp)}ms`
- }
-
- return `${(timestamp / 1000).toFixed(2)}s`
-}
-
-export function humanFriendlyDuration(
- d: string | number | null | undefined,
- {
- maxUnits,
- secondsPrecision,
- secondsFixed,
- }: { maxUnits?: number; secondsPrecision?: number; secondsFixed?: number } = {}
-): string {
- // Convert `d` (seconds) to a human-readable duration string.
- // Example: `1d 10hrs 9mins 8s`
- if (d === '' || d === null || d === undefined || maxUnits === 0) {
- return ''
- }
- d = Number(d)
- if (d < 0) {
- return `-${humanFriendlyDuration(-d)}`
- }
- if (d === 0) {
- return `0s`
- }
- if (d < 1) {
- return `${Math.round(d * 1000)}ms`
- }
- if (d < 60) {
- if (secondsPrecision != null) {
- return `${parseFloat(d.toPrecision(secondsPrecision))}s` // round to s.f. then throw away trailing zeroes
- }
- return `${parseFloat(d.toFixed(secondsFixed ?? 0))}s` // round to fixed point then throw away trailing zeroes
- }
-
- const days = Math.floor(d / 86400)
- const h = Math.floor((d % 86400) / 3600)
- const m = Math.floor((d % 3600) / 60)
- const s = Math.floor((d % 3600) % 60)
-
- const dayDisplay = days > 0 ? days + 'd' : ''
- const hDisplay = h > 0 ? h + 'h' : ''
- const mDisplay = m > 0 ? m + 'm' : ''
- const sDisplay = s > 0 ? s + 's' : hDisplay || mDisplay ? '' : '0s'
-
- let units: string[] = []
- if (days > 0) {
- units = [dayDisplay, hDisplay].filter(Boolean)
- } else {
- units = [hDisplay, mDisplay, sDisplay].filter(Boolean)
- }
- return units.slice(0, maxUnits ?? undefined).join(' ')
-}
-
-export function humanFriendlyDiff(from: dayjs.Dayjs | string, to: dayjs.Dayjs | string): string {
- const diff = dayjs(to).diff(dayjs(from), 'seconds')
- return humanFriendlyDuration(diff)
-}
-
-export function humanFriendlyDetailedTime(
- date: dayjs.Dayjs | string | null | undefined,
- formatDate = 'MMMM DD, YYYY',
- formatTime = 'h:mm:ss A',
- options: { timestampStyle?: 'relative' | 'absolute' } = { timestampStyle: 'relative' }
-): string {
- if (!date) {
- return 'Never'
- }
- const parsedDate = dayjs(date)
-
- if (options.timestampStyle === 'absolute') {
- return parsedDate.format(`${formatDate} ${formatTime}`)
- }
-
- const today = dayjs().startOf('day')
- const yesterday = today.clone().subtract(1, 'days').startOf('day')
- if (parsedDate.isSame(dayjs(), 'm')) {
- return 'Just now'
- }
- let formatString: string
- if (parsedDate.isSame(today, 'd')) {
- formatString = `[Today] ${formatTime}`
- } else if (parsedDate.isSame(yesterday, 'd')) {
- formatString = `[Yesterday] ${formatTime}`
- } else {
- formatString = `${formatDate} ${formatTime}`
- }
- return parsedDate.format(formatString)
-}
-
-export function detailedTime(date: dayjs.Dayjs | string | null | undefined): string {
- if (!date) {
- return ''
- }
- return dayjs(date).format('MMMM DD, YYYY h:mm:ss A')
-}
-
-// Pad numbers with leading zeros
-export const zeroPad = (num: number, places: number): string => String(num).padStart(places, '0')
-
-export function colonDelimitedDuration(d: string | number | null | undefined, fixedUnits: number | null = 3): string {
- // Convert `d` (seconds) to a colon delimited duration. includes `numUnits` no. of units starting from right
- // Example: `01:10:09:08 = 1d 10hrs 9mins 8s`
- if (d === '' || d === null || d === undefined) {
- return ''
- }
- d = Number(d)
-
- let s = d
- let weeks = 0,
- days = 0,
- h = 0,
- m = 0
-
- weeks = !fixedUnits || fixedUnits > 4 ? Math.floor(s / 604800) : 0
- s -= weeks * 604800
-
- days = !fixedUnits || fixedUnits > 3 ? Math.floor(s / 86400) : 0
- s -= days * 86400
-
- h = !fixedUnits || fixedUnits > 2 ? Math.floor(s / 3600) : 0
- s -= h * 3600
-
- m = !fixedUnits || fixedUnits > 1 ? Math.floor(s / 60) : 0
- s -= m * 60
-
- s = Math.floor(s)
-
- let stopTrimming = false
- const units: string[] = []
-
- ;[weeks, days, h, m, s].forEach((unit, i) => {
- if (!fixedUnits && !unit && !stopTrimming && i < 3) {
- return
- }
- units.push(zeroPad(unit, 2))
- stopTrimming = true
- })
-
- if (fixedUnits) {
- return units.slice(-fixedUnits).join(':')
- }
-
- return units.join(':')
-}
-
-export function reverseColonDelimitedDuration(duration?: string | null): number | null {
- if (!duration) {
- return null
- }
-
- if (!/^(\d\d?:)*(\d\d?)$/.test(duration)) {
- return null
- }
-
- let seconds = 0
- const units = duration
- .split(':')
- .map((unit) => Number(unit))
- .reverse()
-
- ;[1, 60, 3600, 86400, 604800].forEach((unit, index) => {
- if (units[index]) {
- seconds += units[index] * unit
- }
- })
-
- return seconds
-}
-
-export function stripHTTP(url: string): string {
- url = url.replace(/(^[0-9]+_)/, '')
- url = url.replace(/(^\w+:|^)\/\//, '')
- return url
-}
-
-export function isDomain(url: string | URL): boolean {
- try {
- const parsedUrl = typeof url === 'string' ? new URL(url) : url
- if (parsedUrl.protocol.includes('http') && (!parsedUrl.pathname || parsedUrl.pathname === '/')) {
- return true
- }
- if (!parsedUrl.pathname.replace(/^\/\//, '').includes('/')) {
- return true
- }
- } catch {
- return false
- }
- return false
-}
-
-export function isURL(input: any): boolean {
- if (!input || typeof input !== 'string') {
- return false
- }
- const regexp = /^(http|capacitor|https):\/\/[\w*.-]+[\w*.-]+[\w\-._~:/?#[\]@%!$&'()*+,;=]+$/
- return !!input.trim().match(regexp)
-}
-
-export function isExternalLink(input: any): boolean {
- if (!input || typeof input !== 'string') {
- return false
- }
- const regexp = /^(https?:|mailto:|\/api\/)/
- return !!input.trim().match(regexp)
-}
-
-export function isEmail(string: string, options?: { requireTLD?: boolean }): boolean {
- if (!string) {
- return false
- }
- // https://html.spec.whatwg.org/multipage/input.html#valid-e-mail-address
- const regexp = options?.requireTLD
- ? /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*\.[a-zA-Z]{2,}$/
- : /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/
- return !!string.match?.(regexp)
-}
-
-export function truncate(str: string, maxLength: number): string {
- return str.length > maxLength ? str.slice(0, maxLength - 1) + '...' : str
-}
-
-export function eventToDescription(
- event: Pick<EventType, 'elements' | 'event' | 'properties'>,
- shortForm: boolean = false
-): string {
- if (event.event === '$autocapture') {
- return autoCaptureEventToDescription(event, shortForm)
- }
- // For events with a taxonomy-default primary property (e.g. `$pageview` -> `$pathname`,
- // `$screen` -> `$screen_name`, `$feature_flag_called` -> `$feature_flag`), use the property's
- // value as the description so consumers (notebooks, save-as-action, funnel labels, ...) get
- // useful context instead of the bare event name. Returns the event name when the property
- // isn't present on the event so callers always get something to display.
- const primaryKey = getPrimaryPropertyForEvent(event.event)
- if (primaryKey) {
- const value = event.properties[primaryKey]
- if (value != null && value !== '') {
- return String(value)
- }
- }
- return event.event
-}
-
-// $event_type to verb map
-export const eventTypeToVerb: { [key: string]: string } = {
- click: 'clicked',
- change: 'changed',
- submit: 'submitted',
- touch: 'touched a',
- value_changed: 'changed value in',
- toggle: 'toggled',
- menu_action: 'pressed menu',
- swipe: 'swiped',
- pinch: 'pinched',
- pan: 'panned',
- rotation: 'rotated',
- long_press: 'long pressed',
- scroll: 'scrolled in',
-}
-
-export function autoCaptureEventToDescription(
- event: Pick<EventType, 'elements' | 'event' | 'properties'>,
- shortForm: boolean = false
-): string {
- if (event.event !== '$autocapture') {
- return event.event
- }
-
- const getVerb = (): string => eventTypeToVerb[event.properties.$event_type] || 'interacted with'
-
- const getTag = (): string => {
- if (event.elements?.[0]?.tag_name === 'a') {
- return 'link'
- } else if (event.elements?.[0]?.tag_name === 'img') {
- return 'image'
- }
- return event.elements?.[0]?.tag_name ?? 'element'
- }
-
- const getValue = (): string | null => {
- if (event.properties.$el_text) {
- return `${shortForm ? '' : 'with text '}"${event.properties.$el_text}"`
- } else if (event.elements?.[0]?.text) {
- return `${shortForm ? '' : 'with text '}"${event.elements[0].text}"`
- } else if (event.elements?.[0]?.attributes?.['attr__aria-label']) {
- return `${shortForm ? '' : 'with aria label '}"${event.elements[0].attributes['attr__aria-label']}"`
- }
- return null
- }
-
- if (shortForm) {
- return [getVerb(), getValue() ?? getTag()].filter((x) => x).join(' ')
- }
- const value = getValue()
- return [getVerb(), getTag(), value].filter((x) => x).join(' ')
-}
-
-export function determineDifferenceType(
- firstDate: dayjs.Dayjs | string,
- secondDate: dayjs.Dayjs | string
-): 'year' | 'month' | 'week' | 'day' | 'hour' | 'minute' | 'second' {
- const first = dayjs(firstDate)
- const second = dayjs(secondDate)
- if (first.diff(second, 'years') !== 0) {
- return 'year'
- } else if (first.diff(second, 'months') !== 0) {
- return 'month'
- } else if (first.diff(second, 'weeks') !== 0) {
- return 'week'
- } else if (first.diff(second, 'days') !== 0) {
- return 'day'
- } else if (first.diff(second, 'hours') !== 0) {
- return 'hour'
- }
- return 'minute'
-}
-
-export const DATE_FORMAT = 'MMMM D, YYYY'
-export const DATE_TIME_FORMAT = 'MMMM D, YYYY HH:mm:ss'
-export const DATE_FORMAT_WITHOUT_YEAR = 'MMMM D'
-export const DATE_FORMAT_WITHOUT_DAY = 'HH:mm:ss'
-
-export const formatDate = (date: dayjs.Dayjs, format?: string): string => {
- return date.format(format ?? DATE_FORMAT)
-}
-
-export const formatDateTime = (date: dayjs.Dayjs, format?: string): string => {
- return date.format(format ?? DATE_TIME_FORMAT)
-}
-
-export const formatDateRange = (dateFrom: dayjs.Dayjs, dateTo: dayjs.Dayjs, format?: string): string => {
- let formatFrom = format ?? DATE_FORMAT
- const formatTo = format ?? DATE_FORMAT
- if ((!format || format === DATE_FORMAT) && dateFrom.year() === dateTo.year()) {
- formatFrom = DATE_FORMAT_WITHOUT_YEAR
- }
- return `${dateFrom.format(formatFrom)} - ${dateTo.format(formatTo)}`
-}
-
-export const formatDateTimeRange = (dateFrom: dayjs.Dayjs, dateTo: dayjs.Dayjs): string => {
- const MONTHDAY = 'MMMM D'
- const COMMA = ', '
- const YEAR = 'YYYY '
- const TIME = 'HH:mm'
- const SECONDS = ':ss'
-
- let fromComponents = [MONTHDAY, COMMA, YEAR, TIME, SECONDS]
- let toComponents = [MONTHDAY, COMMA, YEAR, TIME, SECONDS]
- if (dateFrom.year() === dateTo.year()) {
- toComponents = toComponents.filter((x) => x !== YEAR)
- if (dateTo.year() === dayjs().year()) {
- fromComponents = fromComponents.filter((x) => x !== YEAR)
- }
-
- if (dateFrom.isSame(dateTo, 'day')) {
- toComponents = toComponents.filter((x) => x !== MONTHDAY)
- toComponents = toComponents.filter((x) => x !== COMMA)
- if (dateFrom.isSame(dayjs(), 'day')) {
- fromComponents = fromComponents.filter((x) => x !== MONTHDAY)
- fromComponents = fromComponents.filter((x) => x !== COMMA)
- }
- }
-
- if (dateFrom.isSame(dayjs(dateFrom).startOf('day')) && dateTo.isSame(dayjs(dateTo).startOf('day'))) {
- fromComponents = fromComponents.filter((x) => x !== TIME)
- toComponents = toComponents.filter((x) => x !== TIME)
- }
-
- if (dateFrom.second() === 0 && dateTo.second() === 0) {
- fromComponents = fromComponents.filter((x) => x !== SECONDS)
- toComponents = toComponents.filter((x) => x !== SECONDS)
- }
-
- if (!fromComponents.includes(YEAR) && !fromComponents.includes(TIME)) {
- fromComponents = fromComponents.filter((x) => x !== COMMA)
- }
-
- if (!toComponents.includes(YEAR) && !toComponents.includes(TIME)) {
- toComponents = toComponents.filter((x) => x !== COMMA)
- }
- }
- return `${dateFrom.format(fromComponents.join(''))} - ${dateTo.format(toComponents.join(''))}`
-}
-
-/** Returns the start of the current week, respecting the team's week start day (0=Sunday, 1=Monday). */
-function startOfWeek(date: dayjs.Dayjs, weekStartDay?: number | null): dayjs.Dayjs {
- const start = weekStartDay === 1 ? 1 : 0
- return date.subtract((date.day() - start + 7) % 7, 'day').startOf('day')
-}
-
-export const dateMapping: DateMappingOption[] = [
- { key: CUSTOM_OPTION_KEY, values: [] },
- {
- key: 'Today',
- values: ['dStart'],
- getFormattedDate: (date: dayjs.Dayjs): string => date.startOf('d').format(DATE_FORMAT),
- defaultInterval: 'hour',
- },
- {
- key: 'Yesterday',
- values: ['-1dStart', '-1dEnd'],
- getFormattedDate: (date: dayjs.Dayjs): string => date.subtract(1, 'd').format(DATE_FORMAT),
- defaultInterval: 'hour',
- },
- {
- key: 'Last hour',
- values: ['-1h'],
- getFormattedDate: (date: dayjs.Dayjs): string => formatDateRange(date.subtract(1, 'h'), date),
- defaultInterval: 'minute',
- },
- {
- key: 'Last 24 hours',
- values: ['-24h'],
- getFormattedDate: (date: dayjs.Dayjs): string => formatDateRange(date.subtract(24, 'h'), date.endOf('d')),
- defaultInterval: 'hour',
- },
- {
- key: 'Last 48 hours',
- values: ['-48h'],
- getFormattedDate: (date: dayjs.Dayjs): string => formatDateRange(date.subtract(48, 'h'), date.endOf('d')),
- inactive: true,
- defaultInterval: 'hour',
- },
- {
- key: 'Last 7 days',
- values: ['-7d'],
- getFormattedDate: (date: dayjs.Dayjs): string => formatDateRange(date.subtract(7, 'd'), date.endOf('d')),
- defaultInterval: 'day',
- },
- {
- key: 'Last 14 days',
- values: ['-14d'],
- getFormattedDate: (date: dayjs.Dayjs): string => formatDateRange(date.subtract(14, 'd'), date.endOf('d')),
- defaultInterval: 'day',
- },
- {
- key: 'Last 30 days',
- values: ['-30d'],
- getFormattedDate: (date: dayjs.Dayjs): string => formatDateRange(date.subtract(30, 'd'), date.endOf('d')),
- defaultInterval: 'day',
- },
- {
- key: 'Last 90 days',
- values: ['-90d'],
- getFormattedDate: (date: dayjs.Dayjs): string => formatDateRange(date.subtract(90, 'd'), date.endOf('d')),
- defaultInterval: 'day',
- },
- {
- key: 'Last 180 days',
- values: ['-180d'],
- getFormattedDate: (date: dayjs.Dayjs): string => formatDateRange(date.subtract(180, 'd'), date.endOf('d')),
- defaultInterval: 'month',
- },
-
- {
- key: 'Last week',
- values: ['-1wStart', '-1wEnd'],
- getFormattedDate: (date: dayjs.Dayjs, _format?: string, weekStartDay?: number): string => {
- const lastWeekStart = startOfWeek(date, weekStartDay).subtract(7, 'day')
- return formatDateRange(lastWeekStart, lastWeekStart.add(6, 'day').endOf('d'))
- },
- defaultInterval: 'day',
- },
- {
- key: 'Last month',
- values: ['-1mStart', '-1mEnd'],
- getFormattedDate: (date: dayjs.Dayjs): string =>
- formatDateRange(date.subtract(1, 'month').startOf('month'), date.subtract(1, 'month').endOf('month')),
- defaultInterval: 'day',
- },
- {
- key: 'This week',
- values: ['wStart'],
- getFormattedDate: (date: dayjs.Dayjs, _format?: string, weekStartDay?: number): string =>
- formatDateRange(startOfWeek(date, weekStartDay), date.endOf('d')),
- defaultInterval: 'day',
- },
- {
- key: 'This month',
- values: ['mStart'],
- getFormattedDate: (date: dayjs.Dayjs): string => formatDateRange(date.startOf('month'), date.endOf('month')),
- defaultInterval: 'day',
- },
- {
- key: 'Year to date',
- values: ['yStart'],
- getFormattedDate: (date: dayjs.Dayjs): string => formatDateRange(date.startOf('y'), date.endOf('d')),
- defaultInterval: 'month',
- },
- {
- key: 'All time',
- values: ['all'],
- defaultInterval: 'month',
- },
-]
-
-export const isDate = /([0-9]{4}-[0-9]{2}-[0-9]{2})/
-
-export function getFormattedLastWeekDate(lastDay: dayjs.Dayjs = dayjs()): string {
- return formatDateRange(lastDay.subtract(7, 'week'), lastDay.endOf('d'))
-}
-
-const dateOptionsMap = {
- y: 'year',
- q: 'quarter',
- m: 'month',
- w: 'week',
- d: 'day',
- h: 'hour',
- M: 'minute',
- s: 'second',
-} as const
-
-export function dateFilterToText(
- dateFrom: string | dayjs.Dayjs | null | undefined,
- dateTo: string | dayjs.Dayjs | null | undefined,
- defaultValue: string | null,
- dateOptions: DateMappingOption[] = dateMapping,
- isDateFormatted: boolean = false,
- dateFormat: string = DATE_FORMAT,
- startOfRange: boolean = false,
- weekStartDay?: number
-): string | null {
- if (dayjs.isDayjs(dateFrom) && dayjs.isDayjs(dateTo)) {
- return formatDateRange(dateFrom, dateTo, dateFormat)
- }
- dateFrom = (dateFrom || undefined) as string | undefined
- dateTo = (dateTo || undefined) as string | undefined
-
- if (isDate.test(dateFrom || '') && isDate.test(dateTo || '')) {
- if (isDateFormatted) {
- return formatDateRange(dayjs(dateFrom, 'YYYY-MM-DD'), dayjs(dateTo, 'YYYY-MM-DD'))
- }
- if (dateFrom?.includes('T') || dateTo?.includes('T')) {
- // Parse each date individually - ISO 8601 datetimes (with T) use native parsing
- // to correctly handle seconds/milliseconds, plain dates use 'YYYY-MM-DD'
- const parsedFrom = dateFrom?.includes('T') ? dayjs(dateFrom) : dayjs(dateFrom, 'YYYY-MM-DD')
- const parsedTo = dateTo?.includes('T') ? dayjs(dateTo) : dayjs(dateTo, 'YYYY-MM-DD')
- return formatDateTimeRange(parsedFrom, parsedTo)
- }
- return `${dateFrom} - ${dateTo}`
- }
-
- // From date to today
- if (isDate.test(dateFrom || '') && !isDate.test(dateTo || '')) {
- const days = dayjs().diff(dayjs(dateFrom), 'days')
- if (days > 366) {
- return isDateFormatted ? `${dateFrom} - today` : formatDateRange(dayjs(dateFrom), dayjs())
- } else if (days > 0) {
- return isDateFormatted ? formatDateRange(dayjs(dateFrom), dayjs()) : `Last ${days} days`
- } else if (days === 0) {
- return isDateFormatted ? dayjs(dateFrom).format(dateFormat) : `Today`
- }
- return isDateFormatted ? `${dayjs(dateFrom).format(dateFormat)} - ` : `Starting from ${dateFrom}`
- }
-
- for (const { key, values, getFormattedDate } of dateOptions) {
- if (values[0] === dateFrom && values[1] === dateTo && key !== CUSTOM_OPTION_KEY) {
- return isDateFormatted && getFormattedDate ? getFormattedDate(dayjs(), dateFormat, weekStartDay) : key
- }
- }
-
- if (dateFrom) {
- const dateOption = dateOptionsMap[dateFrom.slice(-1) as keyof typeof dateOptionsMap]
- const counter = parseInt(dateFrom.slice(1, -1))
- if (dateOption && counter) {
- let date = null
- switch (dateOption) {
- case 'year':
- date = dayjs().subtract(counter, 'y')
- break
- case 'hour':
- date = dayjs().subtract(counter, 'h')
- break
- case 'quarter':
- date = dayjs().subtract(counter * 3, 'M')
- break
- case 'month':
- date = dayjs().subtract(counter, 'M')
- break
- case 'week':
- date = dayjs().subtract(counter * 7, 'd')
- break
- case 'minute':
- date = dayjs().subtract(counter, 'm')
- break
- case 'second':
- date = dayjs().subtract(counter, 's')
- break
- default:
- date = dayjs().subtract(counter, 'd')
- break
- }
- if (isDateFormatted) {
- return formatDateRange(date, dayjs().endOf('d'))
- } else if (startOfRange) {
- return formatDate(date, dateFormat)
- }
- return `Last ${counter} ${dateOption}${counter > 1 ? 's' : ''}`
- }
- }
-
- return defaultValue
-}
-
-// Converts a dateFrom string ("-2w") into english: "2 weeks"
-export function dateFromToText(dateFrom: string): string | undefined {
- const dateOption: (typeof dateOptionsMap)[keyof typeof dateOptionsMap] =
- dateOptionsMap[dateFrom.slice(-1) as keyof typeof dateOptionsMap]
- const counter = parseInt(dateFrom.slice(1, -1))
- if (dateOption && counter) {
- return `${counter} ${dateOption}${counter > 1 ? 's' : ''}`
- }
- return undefined
-}
-
-export type DateComponents = {
- amount: number
- unit: (typeof dateOptionsMap)[keyof typeof dateOptionsMap]
- clip: 'Start' | 'End'
-}
-
-export const isStringDateRegex = /^([-+]?)([0-9]*)([hdwmqy])(|Start|End)$/
-export function dateStringToComponents(date: string | null): DateComponents | null {
- if (!date) {
- return null
- }
- const matches = date.match(isStringDateRegex)
- if (!matches) {
- return null
- }
- const [, sign, rawAmount, rawUnit, clip] = matches
- const amount = rawAmount ? parseInt(sign + rawAmount) : 0
- const unit = dateOptionsMap[rawUnit as keyof typeof dateOptionsMap] || 'day'
- return { amount, unit, clip: clip as 'Start' | 'End' }
-}
-
-export function componentsToDayJs(
- { amount, unit, clip }: DateComponents,
- offset?: Dayjs,
- timezone: string = 'UTC'
-): Dayjs {
- const dayjsInstance = offset ?? dayjs().tz(timezone)
- let response: dayjs.Dayjs
- switch (unit) {
- case 'year':
- response = dayjsInstance.add(amount, 'year')
- break
- case 'quarter':
- response = dayjsInstance.add(amount * 3, 'month')
- break
- case 'month':
- response = dayjsInstance.add(amount, 'month')
- break
- case 'week':
- response = dayjsInstance.add(amount * 7, 'day')
- break
- case 'day':
- response = dayjsInstance.add(amount, 'day')
- break
- case 'hour':
- response = dayjsInstance.add(amount, 'hour')
- break
- case 'minute':
- response = dayjsInstance.add(amount, 'minute')
- break
- case 'second':
- response = dayjsInstance.add(amount, 'second')
- break
- default:
- throw new UnexpectedNeverError(unit)
- }
-
- if (clip === 'Start') {
- return response.startOf(unit)
- } else if (clip === 'End') {
- return response.endOf(unit)
- }
- return response
-}
-
-/** Convert a string like "-30d" or "2022-02-02" or "-1mEnd" to `Dayjs().startOf('day')` */
-export function dateStringToDayJs(date: string | null, timezone: string = 'UTC'): dayjs.Dayjs | null {
- if (isDate.test(date || '')) {
- return dayjs.tz(date, timezone)
- }
- const dateComponents = dateStringToComponents(date)
- if (!dateComponents) {
- return null
- }
- const offset: dayjs.Dayjs = dayjs().tz(timezone).startOf('day')
- const response = componentsToDayJs(dateComponents, offset, timezone)
- return response
-}
-
-export function isValidRelativeOrAbsoluteDate(date: string): boolean {
- if (isStringDateRegex.test(date)) {
- return true
- }
- if (dayjs(date).isValid()) {
- return true
- }
- if (date === 'all') {
- return true
- }
- return false
-}
-
-export const getDefaultInterval = (dateFrom: string | null, dateTo: string | null): IntervalType => {
- // use the default mapping if we can
- for (const mapping of dateMapping) {
- const mappingFrom = mapping.values[0] ?? null
- const mappingTo = mapping.values[1] ?? null
- if (mappingFrom === dateFrom && mappingTo === dateTo && mapping.defaultInterval) {
- return mapping.defaultInterval
- }
- }
-
- const parsedDateFrom = dateStringToComponents(dateFrom)
- const parsedDateTo = dateStringToComponents(dateTo)
-
- if (parsedDateFrom?.unit === 'hour' || parsedDateTo?.unit === 'hour') {
- return 'hour'
- }
-
- if (
- parsedDateFrom?.unit === 'day' ||
- parsedDateTo?.unit === 'day' ||
- dateFrom === 'mStart' ||
- dateFrom === 'wStart'
- ) {
- return 'day'
- }
-
- if (
- (parsedDateFrom?.unit === 'month' && parsedDateFrom.amount <= 3) ||
- (parsedDateTo?.unit === 'month' && parsedDateTo.amount <= 3) ||
- (parsedDateFrom?.unit === 'quarter' && parsedDateFrom.amount <= 1) ||
- (parsedDateTo?.unit === 'quarter' && parsedDateTo.amount <= 1)
- ) {
- return 'day'
- }
-
- if (
- parsedDateFrom?.unit === 'month' ||
- parsedDateTo?.unit === 'month' ||
- parsedDateFrom?.unit === 'quarter' ||
- parsedDateTo?.unit === 'quarter' ||
- parsedDateFrom?.unit === 'year' ||
- parsedDateTo?.unit === 'year' ||
- dateFrom === 'all'
- ) {
- return 'month'
- }
-
- const dateFromDayJs = dateStringToDayJs(dateFrom)
- const dateToDayJs = dateStringToDayJs(dateTo)
-
- const intervalMonths = dateFromDayJs?.diff(dateToDayJs, 'month')
- if (intervalMonths != null && Math.abs(intervalMonths) >= 2) {
- return 'month'
- }
- const intervalDays = dateFromDayJs?.diff(dateToDayJs, 'day')
- if (intervalDays != null && Math.abs(intervalDays) >= 14) {
- return 'week'
- }
- if (intervalDays != null && Math.abs(intervalDays) >= 2) {
- return 'day'
- }
- const intervalHours = dateFromDayJs?.diff(dateToDayJs, 'hour')
- if (intervalHours != null && Math.abs(intervalHours) >= 1) {
- return 'hour'
- }
-
- return 'day'
-}
-
-/* If the interval changes, check if it's compatible with the selected dates, and return new dates
- * from a map of sensible defaults if not */
-export const areDatesValidForInterval = (
- interval: IntervalType,
- oldDateFrom: string | null,
- oldDateTo: string | null
-): boolean => {
- const parsedOldDateFrom = dateStringToDayJs(oldDateFrom)
- const parsedOldDateTo = dateStringToDayJs(oldDateTo) || dayjs()
-
- if (oldDateFrom === 'all' || !parsedOldDateFrom) {
- return interval === 'month'
- } else if (interval === 'month') {
- return parsedOldDateTo.diff(parsedOldDateFrom, 'month') >= 2
- } else if (interval === 'week') {
- return parsedOldDateTo.diff(parsedOldDateFrom, 'week') >= 2
- } else if (interval === 'day') {
- const diff = parsedOldDateTo.diff(parsedOldDateFrom, 'day')
- return diff >= 2
- } else if (interval === 'hour') {
- return (
- parsedOldDateTo.diff(parsedOldDateFrom, 'hour') >= 2 &&
- parsedOldDateTo.diff(parsedOldDateFrom, 'hour') < 24 * 7 * 2 // 2 weeks
- )
- } else if (interval === 'minute') {
- return (
- parsedOldDateTo.diff(parsedOldDateFrom, 'minute') >= 2 &&
- parsedOldDateTo.diff(parsedOldDateFrom, 'minute') < 60 * 12 // 12 hours. picked based on max graph resolution
- )
- } else if (interval === 'second') {
- return (
- parsedOldDateTo.diff(parsedOldDateFrom, 'second') >= 2 &&
- parsedOldDateTo.diff(parsedOldDateFrom, 'second') < 60 * 60 // 1 hour
- )
- }
- throw new UnexpectedNeverError(interval)
-}
-
-const defaultDatesForInterval = {
- second: { dateFrom: '-1M', dateTo: null },
- minute: { dateFrom: '-1h', dateTo: null },
- hour: { dateFrom: '-24h', dateTo: null },
- day: { dateFrom: '-7d', dateTo: null },
- week: { dateFrom: '-28d', dateTo: null },
- month: { dateFrom: '-6m', dateTo: null },
-}
-
-export const updateDatesWithInterval = (
- interval: IntervalType,
- oldDateFrom: string | null,
- oldDateTo: string | null
-): { dateFrom: string | null; dateTo: string | null } => {
- if (areDatesValidForInterval(interval, oldDateFrom, oldDateTo)) {
- return {
- dateFrom: oldDateFrom,
- dateTo: oldDateTo,
- }
- }
- return defaultDatesForInterval[interval]
-}
-
-export function is12HoursOrLess(dateFrom: string | undefined | null): boolean {
- if (!dateFrom) {
- return false
- }
- return dateFrom.search(/^-([0-9]|1[0-2])h$/) != -1
-}
-export function isLessThan2Days(dateFrom: string | undefined | null): boolean {
- if (!dateFrom) {
- return false
- }
- return dateFrom.search(/^-(4[0-7]|[0-3]?[0-9])h|[1-2]d$/) != -1
-}
-
-export function clamp(value: number, min: number, max: number): number {
- return value > max ? max : value < min ? min : value
-}
-
-export function isMobile(): boolean {
- return navigator.userAgent.includes('Mobile')
-}
-
-export function isMac(): boolean {
- return navigator.platform.includes('Mac')
-}
-
-export function platformCommandControlKey(modifier: string): string {
- return `${isMac() ? '⌘' : 'Ctrl + '}${modifier}`
-}
-
-export function groupBy<T>(items: T[], groupResolver: (item: T) => string | number): Record<string | number, T[]> {
- const itemsGrouped: Record<string | number, T[]> = {}
- for (const item of items) {
- const group = groupResolver(item)
- if (!(group in itemsGrouped)) {
- itemsGrouped[group] = []
- } // Ensure there's an array to push to
- itemsGrouped[group].push(item)
- }
- return itemsGrouped
-}
-
-export function uniqueBy<T>(items: T[], uniqueResolver: (item: T) => any): T[] {
- const uniqueKeysSoFar = new Set<string>()
- const itemsUnique: T[] = []
- for (const item of items) {
- const uniqueKey = uniqueResolver(item)
- if (!uniqueKeysSoFar.has(uniqueKey)) {
- uniqueKeysSoFar.add(uniqueKey)
- itemsUnique.push(item)
- }
- }
- return itemsUnique
-}
-
-export function sample<T>(items: T[], size: number): T[] {
- if (!items.length) {
- throw Error('Items array is empty!')
- }
- if (size > items.length) {
- throw Error('Sample size cannot exceed items array length!')
- }
- const results: T[] = []
- const internalItems = [...items]
- if (size === items.length) {
- return internalItems
- }
- for (let i = 0; i < size; i++) {
- const index = Math.floor(Math.random() * internalItems.length)
- results.push(internalItems[index])
- internalItems.splice(index, 1)
- }
- return results
-}
-
-export function sampleOne<T>(items: T[]): T {
- if (!items.length) {
- throw Error('Items array is empty!')
- }
- const index = inStorybookTestRunner() ? 0 : Math.floor(Math.random() * items.length)
- return items[index]
-}
-
-/** Convert camelCase, PascalCase or snake_case to Sentence case or Title Case. */
-export function identifierToHuman(identifier: string | number, caseType: 'sentence' | 'title' = 'sentence'): string {
- const words: string[] = []
- let currentWord: string = ''
- String(identifier)
- .trim()
- .split('')
- .forEach((character) => {
- if (character === '_' || character === '-' || character === '/') {
- if (currentWord) {
- words.push(currentWord)
- }
- currentWord = ''
- } else if (
- character === character.toLowerCase() &&
- (!'0123456789'.includes(character) ||
- (currentWord && '0123456789'.includes(currentWord[currentWord.length - 1])))
- ) {
- currentWord += character
- } else {
- if (currentWord) {
- words.push(currentWord)
- }
- currentWord = character.toLowerCase()
- }
- })
- if (currentWord) {
- words.push(currentWord)
- }
- return capitalizeFirstLetter(
- words.map((word) => (caseType === 'sentence' ? word : capitalizeFirstLetter(word))).join(' ')
- )
-}
-
-export function parseGithubRepoURL(url: string): Record<string, string> {
- const match = url.match(
- /^https?:\/\/(?:www\.)?github\.com\/([A-Za-z0-9_.-]+)\/([A-Za-z0-9_.-]+)(\/(commit|tree|releases\/tag)\/([A-Za-z0-9_.\-/]+))?/
- )
-
- if (!match) {
- throw new Error(`${url} is not a valid GitHub URL`)
- }
-
- const [, user, repo, , type, path] = match
- return { user, repo, type, path }
-}
-
-export function someParentMatchesSelector(element: HTMLElement, selector: string): boolean {
- if (element.matches(selector)) {
- return true
- }
- return element.parentElement ? someParentMatchesSelector(element.parentElement, selector) : false
-}
-
-export function hashCodeForString(s: string): number {
- /* Hash function that returns a number for a given string. Useful for using the same colors for tags or avatars.
- Forked from https://github.com/segmentio/evergreen/
- */
- let hash = 0
- if (s.trim().length === 0) {
- return hash
- }
- for (let i = 0; i < s.length; i++) {
- const char = s.charCodeAt(i)
- hash = (hash << 5) - hash + char
- hash &= hash // Convert to 32bit integer
- }
- return Math.abs(hash)
-}
-
-export function colorForString(s: string): LemonTagType {
- /*
- Returns a color name for a given string, where the color will always be the same for the same string.
- */
- return tagColors[hashCodeForString(s) % tagColors.length]
-}
-
-/** Truncates a string (`input`) in the middle. `maxLength` represents the desired maximum length of the output. */
-export function midEllipsis(input: string, maxLength: number): string {
- if (input.length <= maxLength) {
- return input
- }
-
- const middle = Math.ceil(input.length / 2)
- const excessLeft = Math.ceil((input.length - maxLength) / 2)
- const excessRight = Math.ceil((input.length - maxLength + 1) / 2)
- return `${input.slice(0, middle - excessLeft)}…${input.slice(middle + excessRight)}`
-}
-
-export function pluralize(count: number, singular: string, plural?: string, includeNumber: boolean = true): string {
- if (!plural) {
- plural = singular + 's'
- }
- const form = count === 1 ? singular : plural
- return includeNumber ? `${humanFriendlyNumber(count)} ${form}` : form
-}
-
-const WORD_PLURALIZATION_RULES = [
- [/s?$/i, 's'],
- [/([^aeiou]ese)$/i, '$1'],
- [/(ax|test)is$/i, '$1es'],
- [/(alias|[^aou]us|t[lm]as|gas|ris)$/i, '$1es'],
- [/(e[mn]u)s?$/i, '$1s'],
- [/([^l]ias|[aeiou]las|[ejzr]as|[iu]am)$/i, '$1'],
- [/(alumn|syllab|vir|radi|nucle|fung|cact|stimul|termin|bacill|foc|uter|loc|strat)(?:us|i)$/i, '$1i'],
- [/(alumn|alg|vertebr)(?:a|ae)$/i, '$1ae'],
- [/(seraph|cherub)(?:im)?$/i, '$1im'],
- [/(her|at|gr)o$/i, '$1oes'],
- [
- /(agend|addend|millenni|dat|extrem|bacteri|desiderat|strat|candelabr|errat|ov|symposi|curricul|automat|quor)(?:a|um)$/i,
- '$1a',
- ],
- [/(apheli|hyperbat|periheli|asyndet|noumen|phenomen|criteri|organ|prolegomen|hedr|automat)(?:a|on)$/i, '$1a'],
- [/sis$/i, 'ses'],
- [/(?:(kni|wi|li)fe|(ar|l|ea|eo|oa|hoo)f)$/i, '$1$2ves'],
- [/([^aeiouy]|qu)y$/i, '$1ies'],
- [/([^ch][ieo][ln])ey$/i, '$1ies'],
- [/(x|ch|ss|sh|zz)$/i, '$1es'],
- [/(matr|cod|mur|sil|vert|ind|append)(?:ix|ex)$/i, '$1ices'],
- [/\b((?:tit)?m|l)(?:ice|ouse)$/i, '$1ice'],
- [/(pe)(?:rson|ople)$/i, '$1ople'],
- [/(child)(?:ren)?$/i, '$1ren'],
- [/eaux$/i, '$0'],
- [/m[ae]n$/i, 'men'],
-] as [RegExp, string][]
-
-export function wordPluralize(word: string): string {
- if (!word) {
- return word ?? ''
- }
-
- let len = WORD_PLURALIZATION_RULES.length
-
- // Iterate over the sanitization rules and use the first one to match.
- while (len--) {
- const [regex, replacement] = WORD_PLURALIZATION_RULES[len]
- if (regex.test(word)) {
- return word.replace(regex, replacement)
- }
- }
-
- return word
-}
-
-const COMPACT_NUMBER_MAGNITUDES = ['', 'K', 'M', 'B', 'T', 'P', 'E', 'Z', 'Y']
-
-/** Return a number in a compact format, with a SI suffix if applicable.
- * Server-side equivalent: utils.py#compact_number.
- */
-export function compactNumber(value: number | null): string {
- if (value === null) {
- return '-'
- }
-
- value = parseFloat(value.toPrecision(3))
- let magnitude = 0
- while (Math.abs(value) >= 1000) {
- magnitude++
- value /= 1000
- }
- return magnitude > 0 ? `${value} ${COMPACT_NUMBER_MAGNITUDES[magnitude]}` : value.toString()
-}
-
-export function roundToDecimal(value: number | null, places: number = 2): string {
- if (value === null) {
- return '-'
- }
- return (Math.round(value * 100) / 100).toFixed(places)
-}
-
-export function sortedKeys<T extends Record<string, any> = Record<string, any>>(object: T): T {
- const newObject: T = {} as T
- for (const key of Object.keys(object).sort()) {
- newObject[key as keyof T] = object[key]
- }
- return newObject
-}
-
-export const alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'.split('')
-
-export function endWithPunctation(text?: string | null): string {
- let trimmedText = text?.trim()
- if (!trimmedText) {
- return ''
- }
- if (!/[.!?]$/.test(trimmedText)) {
- trimmedText += '.'
- }
- return trimmedText
-}
-
-/**
- * Return the short timezone identifier for a specific timezone (e.g. BST, EST, PDT, UTC+2).
- * @param timeZone E.g. 'America/New_York'
- * @param atDate
- */
-export function shortTimeZone(timeZone?: string, atDate?: Date): string | null {
- const date = atDate ? new Date(atDate) : new Date()
- try {
- const localeTimeStringParts = date
- .toLocaleTimeString('en-us', { timeZoneName: 'short', timeZone: timeZone || undefined })
- .replace('GMT', 'UTC')
- .split(' ')
- return localeTimeStringParts[localeTimeStringParts.length - 1]
- } catch (e) {
- posthog.captureException(e)
- return null
- }
-}
-
-export function timeZoneLabel(timeZone: string, offset: number): string {
- const formattedZone = timeZone.replace(/\//g, ' / ').replace(/_/g, ' ')
- const sign = offset === 0 ? '±' : offset > 0 ? '+' : '-'
- const hours = Math.floor(Math.abs(offset))
- const minutes = Math.round((Math.abs(offset) % 1) * 60)
- .toString()
- .padStart(2, '0')
-
- return `${formattedZone} (UTC${sign}${hours}:${minutes})`
-}
-
-export function humanTzOffset(timezone?: string): string {
- const offset = dayjs().tz(timezone).utcOffset() / 60
- if (!offset) {
- return 'no offset'
- }
- const absoluteOffset = Math.abs(offset)
- const hourForm = absoluteOffset === 1 ? 'hour' : 'hours'
- const direction = offset > 0 ? 'ahead' : 'behind'
- return `${absoluteOffset} ${hourForm} ${direction}`
-}
-
-/** Join array of string into a list ("a, b, and c"). Uses the Oxford comma, but only if there are at least 3 items. */
-export function humanList(arr: readonly string[]): string {
- return arr.length > 2 ? arr.slice(0, -1).join(', ') + ', and ' + arr.at(-1) : arr.join(' and ')
-}
-
-export function hexToRGB(hex: string): { r: number; g: number; b: number; a: number } {
- // Remove the "#" if it exists
- hex = hex.replace(/^#/, '')
-
- // Handle shorthand notation (e.g., "#123" => "#112233")
- if (hex.length === 3 || hex.length === 4) {
- hex = hex
- .split('')
- .map((char) => char + char)
- .join('')
- }
-
- if (hex.length !== 6 && hex.length !== 8) {
- console.warn(`Incorrectly formatted color string: ${hex}.`)
- return { r: 0, g: 0, b: 0, a: 0 }
- }
-
- // Extract the rgb values
- const r = parseInt(hex.slice(0, 2), 16)
- const g = parseInt(hex.slice(2, 4), 16)
- const b = parseInt(hex.slice(4, 6), 16)
- const a = hex.length === 8 ? parseInt(hex.slice(6, 8), 16) / 255 : 1
-
- return { r, g, b, a }
-}
-
-export function hexToRGBA(hex: string, alpha = 1): string {
- /**
- * Returns an RGBA string with specified alpha if the hex string is valid.
- * @param hex e.g. '#FF0000'
- * @param alpha e.g. 0.5
- */
-
- const { r, g, b } = hexToRGB(hex)
- const a = alpha
- return `rgba(${[r, g, b, a].join(',')})`
-}
-
-export function RGBToHex(rgb: string): string {
- const rgbValues = rgb.replace('rgb(', '').replace(')', '').split(',').map(Number)
-
- return `#${rgbValues.map((val) => val.toString(16).padStart(2, '0')).join('')}`
-}
-
-export function RGBToRGBA(rgb: string, a: number): string {
- const [r, g, b] = rgb.slice(4, rgb.length - 1).split(',')
- return `rgba(${[r, g, b, a].join(',')})`
-}
-
-export function RGBToHSL(r: number, g: number, b: number): { h: number; s: number; l: number } {
- // Convert RGB values to the range 0-1
- r /= 255
- g /= 255
- b /= 255
-
- // Find min and max values of r, g, b
- const max = Math.max(r, g, b)
- const min = Math.min(r, g, b)
- const delta = max - min
-
- // Calculate lightness
- let h = 0,
- s = 0
- const l = (max + min) / 2
-
- if (delta !== 0) {
- // Calculate saturation
- s = l < 0.5 ? delta / (max + min) : delta / (2 - max - min)
-
- // Calculate hue
- switch (max) {
- case r:
- h = ((g - b) / delta + (g < b ? 6 : 0)) % 6
- break
- case g:
- h = (b - r) / delta + 2
- break
- case b:
- h = (r - g) / delta + 4
- break
- }
- h *= 60 // Convert hue to degrees
- }
-
- return {
- h: Math.round(h),
- s: Math.round(s * 100),
- l: Math.round(l * 100),
- }
-}
-
-export function lightenDarkenColor(hex: string, pct: number): string {
- /**
- * Returns a lightened or darkened color, similar to SCSS darken()
- * @param hex e.g. '#FF0000'
- * @param pct percentage amount to lighten or darken, e.g. -20
- */
-
- function output(val: number): number {
- return Math.max(0, Math.min(255, val))
- }
-
- const amt = Math.round(2.55 * pct)
- let { r, g, b } = hexToRGB(hex)
-
- r = output(r + amt)
- g = output(g + amt)
- b = output(b + amt)
-
- return `rgb(${[r, g, b].join(',')})`
-}
-
-/**
- * Gradate color saturation based on its intended strength.
- * This is for visualizations where a data point's color depends on its value.
- * @param color A HEX color to gradate.
- * @param strength The strength of the data point.
- * @param floor The minimum saturation. This preserves proportionality of strength, so doesn't just cut it off.
- */
-export function gradateColor(
- color: string,
- strength: number,
- floor: number = 0
-): `hsla(${number}, ${number}%, ${number}%, ${string})` {
- const { r, g, b } = hexToRGB(color)
- const { h, s, l } = RGBToHSL(r, g, b)
-
- const saturation = floor + (1 - floor) * strength
- return `hsla(${h}, ${s}%, ${l}%, ${saturation.toPrecision(3)})`
-}
-
-export function toString(input?: any): string {
- return input?.toString() || ''
-}
-
-export function average(input: number[]): number {
- /**
- * Returns the average of an array
- * @param input e.g. [100,50, 75]
- */
- return Math.round((input.reduce((acc, val) => acc + val, 0) / input.length) * 10) / 10
-}
-
-export function median(input: number[]): number {
- /**
- * Returns the median of an array
- * @param input e.g. [3,7,10]
- */
- const sorted = [...input].sort((a, b) => a - b)
- const half = Math.floor(sorted.length / 2)
-
- if (sorted.length % 2) {
- return sorted[half]
- }
- return average([sorted[half - 1], sorted[half]])
-}
-
-export function sum(input: number[]): number {
- return input.reduce((a, b) => a + b, 0)
-}
-
-export function validateJson(value: string): boolean {
- try {
- JSON.parse(value)
- return true
- } catch {
- return false
- }
-}
-
-export function tryJsonParse(value: string, fallback?: any): any {
- try {
- return JSON.parse(value)
- } catch {
- return fallback
- }
-}
-
-export function ensureStringIsNotBlank(s?: string | null): string | null {
- return typeof s === 'string' && s.trim() !== '' ? s : null
-}
-
-export function isMultiSeriesFormula(formula?: string | null): boolean {
- if (!formula) {
- return false
- }
- const count = (formula.match(/[a-zA-Z]/g) || []).length
- return count > 1
-}
-
-export function floorMsToClosestSecond(ms: number): number {
- return Math.floor(ms / 1000) * 1000
-}
-
-export function ceilMsToClosestSecond(ms: number): number {
- return Math.ceil(ms / 1000) * 1000
-}
-
-// https://stackoverflow.com/questions/40929260/find-last-index-of-element-inside-array-by-certain-condition
-export function findLastIndex<T>(array: Array<T>, predicate: (value: T, index: number, obj: T[]) => boolean): number {
- let l = array.length
- while (l--) {
- if (predicate(array[l], l, array)) {
- return l
- }
- }
- return -1
-}
-
-export function isGroupType(actor: ActorType): actor is GroupActorType {
- return actor.type === 'group'
-}
-
-export function isSessionType(actor: ActorType): actor is SessionActorType {
- return actor.type === 'session'
-}
-
-export function getEventNamesForAction(actionId: string | number, allActions: ActionType[]): string[] {
- const id = parseInt(String(actionId))
- return allActions
- .filter((a) => a.id === id)
- .flatMap((a) => a.steps?.filter((step) => step.event).map((step) => String(step.event)) as string[])
-}
-
-export const isUserLoggedIn = (): boolean => !getAppContext()?.anonymous
-
-// https://stackoverflow.com/questions/175739/how-can-i-check-if-a-string-is-a-valid-number
-export function isNumeric(x: unknown): x is number {
- if (typeof x === 'number') {
- return !isNaN(x) && isFinite(x)
- }
- if (typeof x !== 'string' || x.trim() === '') {
- return false
- }
- return !isNaN(Number(x))
-}
-
-/**
- * Check if the argument is not nullish (null or undefined).
- *
- * Useful as a typeguard, e.g. when passed to Array.filter()
- *
- * @example
- * const myList = [1, 2, null]; // type is (number | null)[]
- *
- * // using isNotNil
- * const myFilteredList1 = myList.filter(isNotNil) // type is number[]
- * const squaredList1 = myFilteredList1.map(x => x * x) // not a type error!
- *
- * // compared to:
- * const myFilteredList2 = myList.filter(x => x != null) // type is (number | null)[]
- * const squaredList2 = myFilteredList2.map(x => x * x) // Type Error: TS18047: x is possibly null
- */
-export function isNotNil<T>(arg: T): arg is Exclude<T, null | undefined> {
- return arg !== null && arg !== undefined
-}
-
-/** An error signaling that a value of type `never` in TypeScript was used unexpectedly at runtime.
- *
- * Useful for type-narrowing, will give a compile-time error if the type of x is not `never`.
- * See the example below where it catches a missing branch at compile-time.
- *
- * @example
- *
- * enum MyEnum {
- * a,
- * b,
- * }
- *
- * function handleEnum(x: MyEnum) {
- * switch (x) {
- * case MyEnum.a:
- * return
- * // missing branch
- * default:
- * throw new UnexpectedNeverError(x) // TS2345: Argument of type MyEnum is not assignable to parameter of type never
- * }
- * }
- *
- * function handleEnum(x: MyEnum) {
- * switch (x) {
- * case MyEnum.a:
- * return
- * case MyEnum.b:
- * return
- * default:
- * throw new UnexpectedNeverError(x) // no type error
- * }
- * }
- *
- */
-export class UnexpectedNeverError extends Error {
- constructor(x: never, message?: string) {
- message = message ?? 'Unexpected never: ' + String(x)
- super(message)
-
- // restore prototype chain, which is broken by Error
- // see https://stackoverflow.com/questions/41102060/typescript-extending-error-class
- const actualProto = new.target.prototype
- if (Object.setPrototypeOf) {
- Object.setPrototypeOf(this, actualProto)
- }
- }
-}
-
-export function promiseResolveReject<T>(): {
- resolve: (value: T) => void
- reject: (reason?: any) => void
- promise: Promise<T>
-} {
- let resolve: (value: T) => void
- let reject: (reason?: any) => void
- const promise = new Promise<T>((innerResolve, innerReject) => {
- resolve = innerResolve
- reject = innerReject
- })
- return { resolve: resolve!, reject: reject!, promise }
-}
-
-export type AsyncReturnType<T extends (...args: any) => any> = T extends (...args: any) => Promise<infer R> ? R : any
-
-export function calculateDays(timeValue: number, timeUnit: TimeUnitType): number {
- if (timeUnit === TimeUnitType.Year) {
- return timeValue * 365
- }
- if (timeUnit === TimeUnitType.Month) {
- return timeValue * 30
- }
- if (timeUnit === TimeUnitType.Week) {
- return timeValue * 7
- }
- return timeValue
-}
-
-// Compute the ISO week string for a given date
-// Useful above to show the toast once per week
-export function getISOWeekString(date = new Date()): string {
- const dayjs_date = dayjs(date)
-
- const year = dayjs_date.year()
- const week = dayjs_date.week()
-
- return `${year}-W${week}`
-}
-
-export function range(startOrEnd: number, end?: number): number[] {
- let length = startOrEnd
- let start = 0
- if (typeof end == 'number') {
- start = startOrEnd
- length = end - start
- }
- return Array.from({ length }, (_, i) => i + start)
-}
-
-export function interleave(arr: any[], delimiter: any): any[] {
- return arr.flatMap((item, index, _arr) =>
- _arr.length - 1 !== index // check for the last item
- ? [item, delimiter]
- : item
- )
-}
-
-export function downloadFile(file: File): void {
- // Create a link and set the URL using `createObjectURL`
- const link = document.createElement('a')
- link.style.display = 'none'
- link.href = URL.createObjectURL(file)
- link.download = file.name
-
- // It needs to be added to the DOM so it can be clicked
- document.body.appendChild(link)
- link.click()
-
- // To make this work on Firefox we need to wait
- // a little while before removing it.
- setTimeout(() => {
- URL.revokeObjectURL(link.href)
- link?.parentNode?.removeChild(link)
- }, 0)
-}
-
-export function inStorybookTestRunner(): boolean {
- return navigator.userAgent.includes('StorybookTestRunner')
-}
-
-export function inStorybook(): boolean {
- return '__STORYBOOK_CLIENT_API__' in window
-}
-
-/** We issue a cancel request, when the request is aborted or times out (frontend side), since in these cases the backend query might still be running. */
-export function shouldCancelQuery(error: any): boolean {
- return isAbortedRequest(error) || isTimedOutRequest(error)
-}
-
-export function isAbortedRequest(error: any): boolean {
- return error.name === 'AbortError' || error.message?.name === 'AbortError'
-}
-
-export function isTimedOutRequest(error: any): boolean {
- return error.status === 504
-}
-
-export function flattenObject<T extends Record<string, any>>(obj: T): Record<string, any> {
- return Object.entries(obj).reduce<Record<string, any>>((acc, [key, value]) => {
- if (value !== null && typeof value === 'object') {
- const flatChild = flattenObject(value)
- const normalizedKey = /^\d+$/.test(key) ? key.padStart(3, '0') : key
-
- Object.entries(flatChild).forEach(([subKey, subVal]) => {
- acc[`${normalizedKey}.${subKey}`] = subVal
- })
- return acc
- }
-
- acc[key] = value
- return acc
- }, {})
-}
-
-export const shouldIgnoreInput = (e: KeyboardEvent): boolean => {
- return (
- ['input', 'textarea'].includes((e.target as HTMLElement).tagName.toLowerCase()) ||
- (e.target as HTMLElement).isContentEditable ||
- (e.target as HTMLElement).parentElement?.isContentEditable ||
- false
- )
-}
-
-export const base64Encode = (str: string): string => {
- const data = new TextEncoder().encode(str)
- const binString = Array.from(data, (byte) => String.fromCharCode(byte)).join('')
- return btoa(binString)
-}
-
-export const base64Decode = (encodedString: string): string => {
- const data = base64ToUint8Array(encodedString)
- return new TextDecoder().decode(data)
-}
-
-export const base64ArrayBuffer = (encodedString: string): ArrayBufferLike => {
- const data = base64ToUint8Array(encodedString)
- return data.buffer
-}
-
-export const base64ToUint8Array = (encodedString: string): Uint8Array => {
- const binString = atob(encodedString)
- const data = new Uint8Array(binString.length)
- for (let i = 0; i < binString.length; i++) {
- data[i] = binString.charCodeAt(i)
- }
- return data
-}
-
-export function hasFormErrors(object: any): boolean {
- if (Array.isArray(object)) {
- return object.some(hasFormErrors)
- } else if (typeof object === 'object' && object !== null) {
- return Object.values(object).some(hasFormErrors)
- }
- return !!object
-}
-
-export function debounce<F extends (...args: Parameters<F>) => ReturnType<F>>(
- func: F,
- waitFor: number
-): (...args: Parameters<F>) => void {
- let timeout: ReturnType<typeof setTimeout>
- return (...args: Parameters<F>): void => {
- clearTimeout(timeout)
- timeout = setTimeout(() => func(...args), waitFor)
- }
-}
-
-export function interleaveArray<T1, T2>(arr: T1[], separator: T2): (T1 | T2)[] {
- return arr.flatMap((item, index, _arr) => (_arr.length - 1 !== index ? [item, separator] : [item]))
-}
-
-/**
- * Uses the non-standard `memory` extension available in Chromium based browsers to
- * get JS heap metrics.
- */
-export const getJSHeapMemory = (): {
- js_heap_used_mb?: number
- js_heap_total_mb?: number
- js_heap_limit_mb?: number
-} => {
- if ('memory' in window.performance) {
- const memory = (window.performance as any).memory
- return {
- js_heap_used_mb: +(memory.usedJSHeapSize / 1024 / 1024).toFixed(2),
- js_heap_total_mb: +(memory.totalJSHeapSize / 1024 / 1024).toFixed(2),
- js_heap_limit_mb: +(memory.jsHeapSizeLimit / 1024 / 1024).toFixed(2),
- }
- }
- return {}
-}
-
-export function getRelativeNextPath(nextPath: string | null | undefined, location: Location): string | null {
- if (!nextPath || typeof nextPath !== 'string') {
- return null
- }
- let decoded: string
- try {
- decoded = decodeURIComponent(nextPath)
- } catch {
- decoded = nextPath
- }
-
- // Protocol-relative URLs (e.g., //evil.com/test) are not allowed
- if (decoded.startsWith('//')) {
- return null
- }
-
- // Root-relative path — resolve against the current origin and verify it doesn't escape.
- // Browsers normalize backslashes in special-scheme URLs per WHATWG, so a raw startsWith('/')
- // check would accept '/\\evil.com/path', which the browser then loads as '//evil.com/path'.
- if (decoded.startsWith('/')) {
- try {
- const url = new URL(decoded, location.origin)
- if (url.origin !== location.origin) {
- return null
- }
- return url.pathname + url.search + url.hash
- } catch {
- return null
- }
- }
-
- // Try to parse as a full URL
- try {
- const url = new URL(decoded)
- if ((url.protocol === 'http:' || url.protocol === 'https:') && url.origin === location.origin) {
- return url.pathname + url.search + url.hash
- }
- return null
- } catch {
- return null
- }
-}
-
-export const formatPercentage = (x: number, options?: { precise?: boolean; compact?: boolean }): string => {
- let result: string
- if (options?.precise) {
- result = (x / 100).toLocaleString(undefined, { style: 'percent', maximumFractionDigits: 1 })
- } else if (x >= 1000) {
- result = humanFriendlyLargeNumber(x) + '%'
- } else {
- result = (x / 100).toLocaleString(undefined, { style: 'percent', maximumSignificantDigits: 2 })
- }
- if (options?.compact) {
- result = result.replace(/\s+%/, '%')
- }
- return result
-}
-
-/**
- * Checks if a string matches the canonical UUID/UUID-like format.
- *
- * This function only checks the structure:
- * - 8-4-4-4-12 hexadecimal characters
- * - 4 dashes in the correct positions
- * It does not enforce UUID version or variant.
- *
- * Examples:
- * - ✅ "0199ed4a-5c03-0000-3220-df21df612e95"
- * - ❌ "not-a-uuid"
- *
- * @param candidate - The string to test.
- * @returns True if the string matches the UUID-like structure.
- */
-export function isUUIDLike(candidate: string): boolean {
- return /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(candidate)
-}
-
-/**
- * Assigns a value to an object field while preserving key-based type inference.
- * Use this when the key is known but the incoming value is `unknown` and has
- * already been validated by surrounding logic.
- *
- * @param obj - Object to mutate.
- * @param key - Field name to assign on `obj`.
- * @param value - Value to assign; cast to `T[K]`.
- * @returns {void}
- */
-export function assignField<T, K extends keyof T>(obj: T, key: K, value: unknown): void {
- obj[key] = value as T[K]
-}
diff --git a/frontend/src/lib/utils/accessControlUtils.ts b/frontend/src/lib/utils/accessControlUtils.ts
index f9dac5e01e0b..1240014c1c56 100644
--- a/frontend/src/lib/utils/accessControlUtils.ts
+++ b/frontend/src/lib/utils/accessControlUtils.ts
@@ -1,7 +1,7 @@
import posthog from 'posthog-js'
-import { toSentenceCase } from 'lib/utils'
import { getAppContext } from 'lib/utils/getAppContext'
+import { toSentenceCase } from 'lib/utils/strings'
import { APIScopeObject, AccessControlLevel, AccessControlResourceType, AvailableFeature } from '~/types'
diff --git a/frontend/src/lib/actionUtils.test.ts b/frontend/src/lib/utils/actions.test.ts
similarity index 91%
rename from frontend/src/lib/actionUtils.test.ts
rename to frontend/src/lib/utils/actions.test.ts
index 69246099b53e..89842a47e6e1 100644
--- a/frontend/src/lib/actionUtils.test.ts
+++ b/frontend/src/lib/utils/actions.test.ts
@@ -1,4 +1,4 @@
-import { elementToSelector } from 'lib/actionUtils'
+import { elementToSelector } from 'lib/utils/actions'
import { ElementType } from '~/types'
diff --git a/frontend/src/lib/actionUtils.ts b/frontend/src/lib/utils/actions.ts
similarity index 89%
rename from frontend/src/lib/actionUtils.ts
rename to frontend/src/lib/utils/actions.ts
index 909649030098..c7befd0f7e69 100644
--- a/frontend/src/lib/actionUtils.ts
+++ b/frontend/src/lib/utils/actions.ts
@@ -1,5 +1,3 @@
-import { cssEscape } from 'lib/utils/cssEscape'
-
import { ElementType } from '~/types'
// these plus any element with cursor:pointer will be click targets
@@ -64,20 +62,20 @@ export function elementToSelector(element: ElementType, dataAttributes: string[]
return selector
}
if (element.attr_id) {
- selector += `[id="${cssEscape(element.attr_id)}"]`
+ selector += `[id="${CSS.escape(element.attr_id)}"]`
return selector
}
if (element.tag_name) {
- selector += cssEscape(element.tag_name)
+ selector += CSS.escape(element.tag_name)
}
if (element.attr_class) {
selector += element.attr_class
.filter((a) => a)
- .map((a) => `.${cssEscape(a)}`)
+ .map((a) => `.${CSS.escape(a)}`)
.join('')
}
if (element.href && element.tag_name === 'a') {
- selector += `[href="${cssEscape(element.href)}"]`
+ selector += `[href="${CSS.escape(element.href)}"]`
}
if (element.nth_child) {
selector += `:nth-child(${parseInt(element.nth_child as any)})`
diff --git a/frontend/src/lib/utils/alertUtils.test.ts b/frontend/src/lib/utils/alerts.test.ts
similarity index 99%
rename from frontend/src/lib/utils/alertUtils.test.ts
rename to frontend/src/lib/utils/alerts.test.ts
index dd58f52335f4..65c6a2fb568f 100644
--- a/frontend/src/lib/utils/alertUtils.test.ts
+++ b/frontend/src/lib/utils/alerts.test.ts
@@ -1,6 +1,6 @@
import { PropertyFilterType, PropertyOperator } from '~/types'
-import { PendingAlertNotification, buildAlertFilterConfig, buildHogFunctionPayload } from './alertUtils'
+import { PendingAlertNotification, buildAlertFilterConfig, buildHogFunctionPayload } from './alerts'
describe('alertUtils', () => {
describe('buildAlertFilterConfig', () => {
diff --git a/frontend/src/lib/utils/alertUtils.ts b/frontend/src/lib/utils/alerts.ts
similarity index 100%
rename from frontend/src/lib/utils/alertUtils.ts
rename to frontend/src/lib/utils/alerts.ts
diff --git a/frontend/src/lib/utils/arrays.test.ts b/frontend/src/lib/utils/arrays.test.ts
new file mode 100644
index 000000000000..ea160d536136
--- /dev/null
+++ b/frontend/src/lib/utils/arrays.test.ts
@@ -0,0 +1,13 @@
+import { range } from 'lib/utils/arrays'
+
+describe('arrays utils', () => {
+ describe('range', () => {
+ it('creates simple range', () => {
+ expect(range(4)).toEqual([0, 1, 2, 3])
+ })
+
+ it('creates offset range', () => {
+ expect(range(1, 5)).toEqual([1, 2, 3, 4])
+ })
+ })
+})
diff --git a/frontend/src/lib/utils/arrays.ts b/frontend/src/lib/utils/arrays.ts
new file mode 100644
index 000000000000..e0f8a16c07a5
--- /dev/null
+++ b/frontend/src/lib/utils/arrays.ts
@@ -0,0 +1,87 @@
+import { inStorybookTestRunner } from 'lib/utils/dom'
+
+export function groupBy<T>(items: T[], groupResolver: (item: T) => string | number): Record<string | number, T[]> {
+ const itemsGrouped: Record<string | number, T[]> = {}
+ for (const item of items) {
+ const group = groupResolver(item)
+ if (!(group in itemsGrouped)) {
+ itemsGrouped[group] = []
+ } // Ensure there's an array to push to
+ itemsGrouped[group].push(item)
+ }
+ return itemsGrouped
+}
+
+export function uniqueBy<T>(items: T[], uniqueResolver: (item: T) => any): T[] {
+ const uniqueKeysSoFar = new Set<string>()
+ const itemsUnique: T[] = []
+ for (const item of items) {
+ const uniqueKey = uniqueResolver(item)
+ if (!uniqueKeysSoFar.has(uniqueKey)) {
+ uniqueKeysSoFar.add(uniqueKey)
+ itemsUnique.push(item)
+ }
+ }
+ return itemsUnique
+}
+
+export function sample<T>(items: T[], size: number): T[] {
+ if (!items.length) {
+ throw Error('Items array is empty!')
+ }
+ if (size > items.length) {
+ throw Error('Sample size cannot exceed items array length!')
+ }
+ const results: T[] = []
+ const internalItems = [...items]
+ if (size === items.length) {
+ return internalItems
+ }
+ for (let i = 0; i < size; i++) {
+ const index = Math.floor(Math.random() * internalItems.length)
+ results.push(internalItems[index])
+ internalItems.splice(index, 1)
+ }
+ return results
+}
+
+export function sampleOne<T>(items: T[]): T {
+ if (!items.length) {
+ throw Error('Items array is empty!')
+ }
+ const index = inStorybookTestRunner() ? 0 : Math.floor(Math.random() * items.length)
+ return items[index]
+}
+
+// https://stackoverflow.com/questions/40929260/find-last-index-of-element-inside-array-by-certain-condition
+export function findLastIndex<T>(array: Array<T>, predicate: (value: T, index: number, obj: T[]) => boolean): number {
+ let l = array.length
+ while (l--) {
+ if (predicate(array[l], l, array)) {
+ return l
+ }
+ }
+ return -1
+}
+
+export function range(startOrEnd: number, end?: number): number[] {
+ let length = startOrEnd
+ let start = 0
+ if (typeof end == 'number') {
+ start = startOrEnd
+ length = end - start
+ }
+ return Array.from({ length }, (_, i) => i + start)
+}
+
+export function interleave(arr: any[], delimiter: any): any[] {
+ return arr.flatMap((item, index, _arr) =>
+ _arr.length - 1 !== index // check for the last item
+ ? [item, delimiter]
+ : item
+ )
+}
+
+export function interleaveArray<T1, T2>(arr: T1[], separator: T2): (T1 | T2)[] {
+ return arr.flatMap((item, index, _arr) => (_arr.length - 1 !== index ? [item, separator] : [item]))
+}
diff --git a/frontend/src/lib/utils/async.test.ts b/frontend/src/lib/utils/async.test.ts
new file mode 100644
index 000000000000..fc215d0c6884
--- /dev/null
+++ b/frontend/src/lib/utils/async.test.ts
@@ -0,0 +1,163 @@
+import { retryWithBackoff } from 'lib/utils/async'
+
+describe('async utils', () => {
+ describe('retryWithBackoff()', () => {
+ it('returns result on first successful attempt', async () => {
+ const fn = jest.fn().mockResolvedValue('success')
+ const result = await retryWithBackoff(fn, { initialDelayMs: 0 })
+ expect(result).toBe('success')
+ expect(fn).toHaveBeenCalledTimes(1)
+ })
+
+ it('retries on failure and succeeds', async () => {
+ const fn = jest
+ .fn()
+ .mockRejectedValueOnce(new Error('fail 1'))
+ .mockRejectedValueOnce(new Error('fail 2'))
+ .mockResolvedValue('success')
+
+ const result = await retryWithBackoff(fn, { maxAttempts: 3, initialDelayMs: 0 })
+ expect(result).toBe('success')
+ expect(fn).toHaveBeenCalledTimes(3)
+ })
+
+ it('throws last error after all attempts exhausted', async () => {
+ const errors = [new Error('fail 1'), new Error('fail 2'), new Error('fail 3')]
+ let callCount = 0
+ const fn = jest.fn().mockImplementation(() => Promise.reject(errors[callCount++]))
+
+ await expect(retryWithBackoff(fn, { maxAttempts: 3, initialDelayMs: 0 })).rejects.toThrow('fail 3')
+ expect(fn).toHaveBeenCalledTimes(3)
+ })
+
+ it('re-throws AbortError immediately without retrying', async () => {
+ const fn = jest.fn().mockImplementation(() => {
+ const error = new DOMException('Aborted', 'AbortError')
+ return Promise.reject(error)
+ })
+
+ await expect(retryWithBackoff(fn, { maxAttempts: 3, initialDelayMs: 0 })).rejects.toThrow('Aborted')
+ expect(fn).toHaveBeenCalledTimes(1)
+ })
+
+ it('throws immediately if signal is already aborted', async () => {
+ const controller = new AbortController()
+ controller.abort()
+
+ const fn = jest.fn().mockResolvedValue('success')
+ await expect(retryWithBackoff(fn, { signal: controller.signal })).rejects.toThrow('Aborted')
+ expect(fn).not.toHaveBeenCalled()
+ })
+
+ it('applies exponential backoff between retries', async () => {
+ jest.useFakeTimers()
+ try {
+ let callCount = 0
+ const fn = jest.fn().mockImplementation(() => {
+ callCount++
+ if (callCount < 3) {
+ return Promise.reject(new Error('fail'))
+ }
+ return Promise.resolve('success')
+ })
+
+ const promise = retryWithBackoff(fn, {
+ maxAttempts: 3,
+ initialDelayMs: 1000,
+ backoffMultiplier: 2,
+ })
+
+ // First call happens immediately
+ await Promise.resolve()
+ expect(fn).toHaveBeenCalledTimes(1)
+
+ // After 1000ms (initialDelayMs * 2^0), second attempt
+ await jest.advanceTimersByTimeAsync(1000)
+ expect(fn).toHaveBeenCalledTimes(2)
+
+ // After 2000ms (initialDelayMs * 2^1), third attempt
+ await jest.advanceTimersByTimeAsync(2000)
+ expect(fn).toHaveBeenCalledTimes(3)
+
+ await expect(promise).resolves.toBe('success')
+ } finally {
+ jest.useRealTimers()
+ }
+ })
+
+ it('uses default options when none provided', async () => {
+ const errors = [new Error('fail'), new Error('fail'), new Error('fail')]
+ let callCount = 0
+ const fn = jest.fn().mockImplementation(() => Promise.reject(errors[callCount++]))
+
+ await expect(retryWithBackoff(fn, { initialDelayMs: 0 })).rejects.toThrow('fail')
+ expect(fn).toHaveBeenCalledTimes(3) // default maxAttempts is 3
+ })
+
+ it('handles maxAttempts of 1 (no retries)', async () => {
+ const fn = jest.fn().mockImplementation(() => Promise.reject(new Error('fail')))
+
+ await expect(retryWithBackoff(fn, { maxAttempts: 1, initialDelayMs: 0 })).rejects.toThrow('fail')
+ expect(fn).toHaveBeenCalledTimes(1)
+ })
+
+ it('does not retry when shouldRetry returns false', async () => {
+ const error = new Error('non-retryable')
+ const fn = jest.fn().mockImplementation(() => Promise.reject(error))
+
+ await expect(
+ retryWithBackoff(fn, {
+ maxAttempts: 3,
+ initialDelayMs: 0,
+ shouldRetry: () => false,
+ })
+ ).rejects.toThrow('non-retryable')
+ expect(fn).toHaveBeenCalledTimes(1)
+ })
+
+ it('retries when shouldRetry returns true', async () => {
+ let callCount = 0
+ const fn = jest.fn().mockImplementation(() => {
+ callCount++
+ if (callCount < 3) {
+ return Promise.reject(new Error('retryable'))
+ }
+ return Promise.resolve('success')
+ })
+
+ const result = await retryWithBackoff(fn, {
+ maxAttempts: 3,
+ initialDelayMs: 0,
+ shouldRetry: () => true,
+ })
+ expect(result).toBe('success')
+ expect(fn).toHaveBeenCalledTimes(3)
+ })
+
+ it('stops retrying when shouldRetry returns false for specific error', async () => {
+ const errors = [new Error('retry-me'), new Error('stop-here'), new Error('never-reached')]
+ let callCount = 0
+ const fn = jest.fn().mockImplementation(() => Promise.reject(errors[callCount++]))
+
+ await expect(
+ retryWithBackoff(fn, {
+ maxAttempts: 3,
+ initialDelayMs: 0,
+ shouldRetry: (e) => e instanceof Error && e.message !== 'stop-here',
+ })
+ ).rejects.toThrow('stop-here')
+ expect(fn).toHaveBeenCalledTimes(2)
+ })
+
+ it('receives the error in shouldRetry callback', async () => {
+ const testError = new Error('test-error')
+ const fn = jest.fn().mockImplementation(() => Promise.reject(testError))
+ const shouldRetry = jest.fn().mockReturnValue(false)
+
+ await expect(retryWithBackoff(fn, { maxAttempts: 3, initialDelayMs: 0, shouldRetry })).rejects.toThrow(
+ 'test-error'
+ )
+ expect(shouldRetry).toHaveBeenCalledWith(testError)
+ })
+ })
+})
diff --git a/frontend/src/lib/utils/async.ts b/frontend/src/lib/utils/async.ts
new file mode 100644
index 000000000000..41f033e602ea
--- /dev/null
+++ b/frontend/src/lib/utils/async.ts
@@ -0,0 +1,113 @@
+export function makeDelay(ms: number): () => Promise<void> {
+ return () => delay(ms)
+}
+
+export function delay(ms: number, signal?: AbortSignal): Promise<void> {
+ return new Promise((resolve, reject) => {
+ const timeoutId = setTimeout(resolve, ms)
+ if (signal) {
+ signal.addEventListener('abort', () => {
+ clearTimeout(timeoutId)
+ reject(new DOMException('Aborted', 'AbortError'))
+ })
+ }
+ })
+}
+
+export interface RetryOptions {
+ /** Maximum number of attempts before giving up. Defaults to 3. */
+ maxAttempts?: number
+ /** Initial delay in milliseconds before the first retry. Defaults to 1000. */
+ initialDelayMs?: number
+ /** Multiplier applied to delay after each failed attempt. Defaults to 1.5. */
+ backoffMultiplier?: number
+ /** AbortSignal to cancel retries. If aborted, throws AbortError immediately. */
+ signal?: AbortSignal
+ /**
+ * Predicate to determine if an error should trigger a retry.
+ * Return true to retry, false to throw immediately.
+ * Defaults to retrying all errors except AbortError.
+ *
+ * @example
+ * // Only retry network errors and 5xx server errors
+ * shouldRetry: (error) => {
+ * if (error instanceof Error && 'status' in error) {
+ * const status = (error as any).status
+ * return status >= 500 || status === 0 // 0 = network error
+ * }
+ * return true // retry unknown errors
+ * }
+ */
+ shouldRetry?: (error: unknown) => boolean
+}
+
+/**
+ * Retries a function with exponential backoff on failure.
+ *
+ * @param fn - The async function to retry
+ * @param options - Configuration options for retry behavior
+ * @returns The result of the function if successful
+ * @throws The last error encountered if all attempts fail, or AbortError if cancelled
+ *
+ * @example
+ * const data = await retryWithBackoff(() => api.fetchData(), {
+ * maxAttempts: 3,
+ * initialDelayMs: 1000,
+ * backoffMultiplier: 1.5
+ * })
+ * // Delays: 1000ms after 1st failure, 1500ms after 2nd failure
+ */
+export async function retryWithBackoff<T>(fn: () => Promise<T>, options: RetryOptions = {}): Promise<T> {
+ const { maxAttempts = 3, initialDelayMs = 1000, backoffMultiplier = 1.5, signal, shouldRetry } = options
+
+ if (signal?.aborted) {
+ throw new DOMException('Aborted', 'AbortError')
+ }
+
+ const attempts = Math.max(maxAttempts, 1)
+
+ let lastError: unknown
+ for (let attempt = 0; attempt < attempts; attempt++) {
+ try {
+ return await fn()
+ } catch (e) {
+ if (e instanceof DOMException && e.name === 'AbortError') {
+ throw e
+ }
+ lastError = e
+ const isLastAttempt = attempt >= attempts - 1
+ const canRetry = shouldRetry ? shouldRetry(e) : true
+ if (isLastAttempt || !canRetry) {
+ throw e
+ }
+ const delayMs = initialDelayMs * Math.pow(backoffMultiplier, attempt)
+ await delay(delayMs, signal)
+ }
+ }
+ throw lastError
+}
+
+export function promiseResolveReject<T>(): {
+ resolve: (value: T) => void
+ reject: (reason?: any) => void
+ promise: Promise<T>
+} {
+ let resolve: (value: T) => void
+ let reject: (reason?: any) => void
+ const promise = new Promise<T>((innerResolve, innerReject) => {
+ resolve = innerResolve
+ reject = innerReject
+ })
+ return { resolve: resolve!, reject: reject!, promise }
+}
+
+export function debounce<F extends (...args: Parameters<F>) => ReturnType<F>>(
+ func: F,
+ waitFor: number
+): (...args: Parameters<F>) => void {
+ let timeout: ReturnType<typeof setTimeout>
+ return (...args: Parameters<F>): void => {
+ clearTimeout(timeout)
+ timeout = setTimeout(() => func(...args), waitFor)
+ }
+}
diff --git a/frontend/src/lib/utils/base64.ts b/frontend/src/lib/utils/base64.ts
new file mode 100644
index 000000000000..c2c5e11be612
--- /dev/null
+++ b/frontend/src/lib/utils/base64.ts
@@ -0,0 +1,24 @@
+export const base64Encode = (str: string): string => {
+ const data = new TextEncoder().encode(str)
+ const binString = Array.from(data, (byte) => String.fromCharCode(byte)).join('')
+ return btoa(binString)
+}
+
+export const base64Decode = (encodedString: string): string => {
+ const data = base64ToUint8Array(encodedString)
+ return new TextDecoder().decode(data)
+}
+
+export const base64ArrayBuffer = (encodedString: string): ArrayBufferLike => {
+ const data = base64ToUint8Array(encodedString)
+ return data.buffer
+}
+
+export const base64ToUint8Array = (encodedString: string): Uint8Array => {
+ const binString = atob(encodedString)
+ const data = new Uint8Array(binString.length)
+ for (let i = 0; i < binString.length; i++) {
+ data[i] = binString.charCodeAt(i)
+ }
+ return data
+}
diff --git a/frontend/src/lib/utils/colors.test.ts b/frontend/src/lib/utils/colors.test.ts
new file mode 100644
index 000000000000..2a997353b4b8
--- /dev/null
+++ b/frontend/src/lib/utils/colors.test.ts
@@ -0,0 +1,11 @@
+import { hexToRGBA } from 'lib/utils/colors'
+
+describe('colors utils', () => {
+ describe('hexToRGBA()', () => {
+ it('converts hex to RGBA correctly', () => {
+ expect(hexToRGBA('#ff0000', 0.3)).toEqual('rgba(255,0,0,0.3)')
+ expect(hexToRGBA('#0000Cc', 0)).toEqual('rgba(0,0,204,0)')
+ expect(hexToRGBA('#5375ff', 1)).toEqual('rgba(83,117,255,1)')
+ })
+ })
+})
diff --git a/frontend/src/lib/utils/colors.ts b/frontend/src/lib/utils/colors.ts
new file mode 100644
index 000000000000..88742f7752e1
--- /dev/null
+++ b/frontend/src/lib/utils/colors.ts
@@ -0,0 +1,141 @@
+import { tagColors } from 'lib/colors'
+import { LemonTagType } from 'lib/lemon-ui/LemonTag'
+import { hashCodeForString } from 'lib/utils/strings'
+
+export function colorForString(s: string): LemonTagType {
+ /*
+ Returns a color name for a given string, where the color will always be the same for the same string.
+ */
+ return tagColors[hashCodeForString(s) % tagColors.length]
+}
+
+export function hexToRGB(hex: string): { r: number; g: number; b: number; a: number } {
+ // Remove the "#" if it exists
+ hex = hex.replace(/^#/, '')
+
+ // Handle shorthand notation (e.g., "#123" => "#112233")
+ if (hex.length === 3 || hex.length === 4) {
+ hex = hex
+ .split('')
+ .map((char) => char + char)
+ .join('')
+ }
+
+ if (hex.length !== 6 && hex.length !== 8) {
+ console.warn(`Incorrectly formatted color string: ${hex}.`)
+ return { r: 0, g: 0, b: 0, a: 0 }
+ }
+
+ // Extract the rgb values
+ const r = parseInt(hex.slice(0, 2), 16)
+ const g = parseInt(hex.slice(2, 4), 16)
+ const b = parseInt(hex.slice(4, 6), 16)
+ const a = hex.length === 8 ? parseInt(hex.slice(6, 8), 16) / 255 : 1
+
+ return { r, g, b, a }
+}
+
+export function hexToRGBA(hex: string, alpha = 1): string {
+ /**
+ * Returns an RGBA string with specified alpha if the hex string is valid.
+ * @param hex e.g. '#FF0000'
+ * @param alpha e.g. 0.5
+ */
+
+ const { r, g, b } = hexToRGB(hex)
+ const a = alpha
+ return `rgba(${[r, g, b, a].join(',')})`
+}
+
+export function RGBToHex(rgb: string): string {
+ const rgbValues = rgb.replace('rgb(', '').replace(')', '').split(',').map(Number)
+
+ return `#${rgbValues.map((val) => val.toString(16).padStart(2, '0')).join('')}`
+}
+
+export function RGBToRGBA(rgb: string, a: number): string {
+ const [r, g, b] = rgb.slice(4, rgb.length - 1).split(',')
+ return `rgba(${[r, g, b, a].join(',')})`
+}
+
+export function RGBToHSL(r: number, g: number, b: number): { h: number; s: number; l: number } {
+ // Convert RGB values to the range 0-1
+ r /= 255
+ g /= 255
+ b /= 255
+
+ // Find min and max values of r, g, b
+ const max = Math.max(r, g, b)
+ const min = Math.min(r, g, b)
+ const delta = max - min
+
+ // Calculate lightness
+ let h = 0,
+ s = 0
+ const l = (max + min) / 2
+
+ if (delta !== 0) {
+ // Calculate saturation
+ s = l < 0.5 ? delta / (max + min) : delta / (2 - max - min)
+
+ // Calculate hue
+ switch (max) {
+ case r:
+ h = ((g - b) / delta + (g < b ? 6 : 0)) % 6
+ break
+ case g:
+ h = (b - r) / delta + 2
+ break
+ case b:
+ h = (r - g) / delta + 4
+ break
+ }
+ h *= 60 // Convert hue to degrees
+ }
+
+ return {
+ h: Math.round(h),
+ s: Math.round(s * 100),
+ l: Math.round(l * 100),
+ }
+}
+
+export function lightenDarkenColor(hex: string, pct: number): string {
+ /**
+ * Returns a lightened or darkened color, similar to SCSS darken()
+ * @param hex e.g. '#FF0000'
+ * @param pct percentage amount to lighten or darken, e.g. -20
+ */
+
+ function output(val: number): number {
+ return Math.max(0, Math.min(255, val))
+ }
+
+ const amt = Math.round(2.55 * pct)
+ let { r, g, b } = hexToRGB(hex)
+
+ r = output(r + amt)
+ g = output(g + amt)
+ b = output(b + amt)
+
+ return `rgb(${[r, g, b].join(',')})`
+}
+
+/**
+ * Gradate color saturation based on its intended strength.
+ * This is for visualizations where a data point's color depends on its value.
+ * @param color A HEX color to gradate.
+ * @param strength The strength of the data point.
+ * @param floor The minimum saturation. This preserves proportionality of strength, so doesn't just cut it off.
+ */
+export function gradateColor(
+ color: string,
+ strength: number,
+ floor: number = 0
+): `hsla(${number}, ${number}%, ${number}%, ${string})` {
+ const { r, g, b } = hexToRGB(color)
+ const { h, s, l } = RGBToHSL(r, g, b)
+
+ const saturation = floor + (1 - floor) * strength
+ return `hsla(${h}, ${s}%, ${l}%, ${saturation.toPrecision(3)})`
+}
diff --git a/frontend/src/lib/utils/concurrencyController.test.ts b/frontend/src/lib/utils/concurrencyController.test.ts
index 5146d4cabbd7..2e31018734b2 100644
--- a/frontend/src/lib/utils/concurrencyController.test.ts
+++ b/frontend/src/lib/utils/concurrencyController.test.ts
@@ -1,6 +1,6 @@
jest.unmock('lib/utils/concurrencyController')
-import { delay } from 'lib/utils'
+import { delay } from 'lib/utils/async'
import { ConcurrencyController } from './concurrencyController'
diff --git a/frontend/src/lib/utils/concurrencyController.ts b/frontend/src/lib/utils/concurrencyController.ts
index bc4ca19c5b80..db7f8b9aeb42 100644
--- a/frontend/src/lib/utils/concurrencyController.ts
+++ b/frontend/src/lib/utils/concurrencyController.ts
@@ -1,6 +1,6 @@
import FastPriorityQueue from 'fastpriorityqueue'
-import { promiseResolveReject } from 'lib/utils'
+import { promiseResolveReject } from 'lib/utils/async'
// Note that this file also exists in the nodejs package, please keep them in sync as the tests only exist for this version
diff --git a/frontend/src/lib/utils/geography/country.ts b/frontend/src/lib/utils/country.ts
similarity index 100%
rename from frontend/src/lib/utils/geography/country.ts
rename to frontend/src/lib/utils/country.ts
diff --git a/frontend/src/lib/utils/cssEscape.ts b/frontend/src/lib/utils/cssEscape.ts
deleted file mode 100644
index a542ca3136b7..000000000000
--- a/frontend/src/lib/utils/cssEscape.ts
+++ /dev/null
@@ -1,8 +0,0 @@
-/*!
- we used to use https://mths.be/cssescape v1.5.1 by @mathias | MIT license
- but the `finder` dependency has always been using `CSS.escape` from the browser
- and nobody has ever pointed out an error
- cssEscape function was only for IE11 users
- and they mustn't be using this anyway
- */
-export const cssEscape = CSS.escape
diff --git a/frontend/src/lib/utils/geography/currency.ts b/frontend/src/lib/utils/currency.ts
similarity index 99%
rename from frontend/src/lib/utils/geography/currency.ts
rename to frontend/src/lib/utils/currency.ts
index 92a1d87ee09d..ac29b05c6a54 100644
--- a/frontend/src/lib/utils/geography/currency.ts
+++ b/frontend/src/lib/utils/currency.ts
@@ -1,4 +1,4 @@
-import { humanFriendlyNumber } from 'lib/utils'
+import { humanFriendlyNumber } from 'lib/utils/numbers'
import { CurrencyCode } from '~/queries/schema/schema-general'
diff --git a/frontend/src/lib/utils/dataTableTransformations.ts b/frontend/src/lib/utils/dataTableTransformations.ts
deleted file mode 100644
index d40b61f8e290..000000000000
--- a/frontend/src/lib/utils/dataTableTransformations.ts
+++ /dev/null
@@ -1,18 +0,0 @@
-import { DataTableRow } from '~/queries/nodes/DataTable/dataTableLogic'
-
-/**
- * Transforms DataTable format back to DataTableRow format for clipboard operations
- */
-export function transformDataTableToDataTableRows(rows: Record<string, any>[], columns: string[]): DataTableRow[] {
- if (!columns.length || !rows.length) {
- return []
- }
-
- return rows.map((row) => ({
- result: columns.map((col, index) => {
- // Handle both direct column access and column_index format
- const columnKey = `${col}_${index}`
- return row[columnKey] !== undefined ? row[columnKey] : row[col]
- }),
- }))
-}
diff --git a/frontend/src/lib/utils/dateFilters.test.ts b/frontend/src/lib/utils/dateFilters.test.ts
new file mode 100644
index 000000000000..57ffa3d0d5b6
--- /dev/null
+++ b/frontend/src/lib/utils/dateFilters.test.ts
@@ -0,0 +1,390 @@
+import tk from 'timekeeper'
+
+import { dayjs } from 'lib/dayjs'
+import {
+ areDatesValidForInterval,
+ dateFilterToText,
+ dateMapping,
+ dateStringToDayJs,
+ getDefaultInterval,
+ is12HoursOrLess,
+ isLessThan2Days,
+} from 'lib/utils/dateFilters'
+
+describe('dateFilters utils', () => {
+ describe('dateFilterToText()', () => {
+ beforeEach(() => {
+ tk.freeze(new Date('2026-06-15T12:00:00.000Z'))
+ })
+ afterEach(() => {
+ tk.reset()
+ })
+
+ describe('not formatted', () => {
+ it('handles dayjs dates', () => {
+ const from = dayjs('2018-04-04T16:00:00.000Z')
+ const to = dayjs('2018-04-09T15:05:00.000Z')
+
+ expect(dateFilterToText(from, to, 'custom')).toEqual('April 4 - April 9, 2018')
+ })
+
+ it('handles various ranges', () => {
+ expect(dateFilterToText('dStart', null, 'default')).toEqual('Today')
+ expect(dateFilterToText('2020-01-02', '2020-01-05', 'default')).toEqual('2020-01-02 - 2020-01-05')
+ expect(dateFilterToText(null, null, 'default')).toEqual('default')
+ expect(dateFilterToText('-24h', null, 'default')).toEqual('Last 24 hours')
+ expect(dateFilterToText('-48h', undefined, 'default')).toEqual('Last 48 hours')
+ expect(dateFilterToText('-1d', null, 'default')).toEqual('Last 1 day')
+ expect(dateFilterToText('-1dStart', '-1dEnd', 'default')).toEqual('Yesterday')
+ expect(dateFilterToText('-1mStart', '-1mEnd', 'default')).toEqual('Last month')
+ })
+
+ // The frontend DateFilter emits YYYY-MM-DD (without allowTimePrecision) or
+ // YYYY-MM-DDTHH:mm:ss (with allowTimePrecision, used by recordings).
+ // The AI agent (filter_session_recordings) emits YYYY-MM-DDTHH:mm:ss.SSS.
+ // All cross-combinations must display correctly.
+
+ it('handles ISO datetime without milliseconds (frontend DateFilter format)', () => {
+ // Both dates as YYYY-MM-DDTHH:mm:ss
+ expect(dateFilterToText('2026-02-01T00:00:00', '2026-02-04T23:59:59', 'default')).toEqual(
+ 'February 1, 00:00:00 - February 4, 23:59:59'
+ )
+ // Non-midnight times
+ expect(dateFilterToText('2026-02-01T14:30:00', '2026-02-04T18:45:00', 'default')).toEqual(
+ 'February 1, 14:30 - February 4, 18:45'
+ )
+ })
+
+ it('handles ISO datetime with milliseconds (AI agent format)', () => {
+ // Both dates as YYYY-MM-DDTHH:mm:ss.SSS
+ expect(dateFilterToText('2026-02-01T00:00:00.000', '2026-02-04T23:59:59.999', 'default')).toEqual(
+ 'February 1, 00:00:00 - February 4, 23:59:59'
+ )
+ })
+
+ it('handles mixed datetime formats (frontend × AI agent)', () => {
+ // YYYY-MM-DDTHH:mm:ss from + YYYY-MM-DDTHH:mm:ss.SSS to
+ expect(dateFilterToText('2026-02-01T00:00:00', '2026-02-04T23:59:59.999', 'default')).toEqual(
+ 'February 1, 00:00:00 - February 4, 23:59:59'
+ )
+ // YYYY-MM-DDTHH:mm:ss.SSS from + YYYY-MM-DDTHH:mm:ss to
+ expect(dateFilterToText('2026-02-01T00:00:00.000', '2026-02-04T23:59:59', 'default')).toEqual(
+ 'February 1, 00:00:00 - February 4, 23:59:59'
+ )
+ })
+
+ it('handles plain date + datetime (either direction)', () => {
+ // YYYY-MM-DD from + YYYY-MM-DDTHH:mm:ss to
+ expect(dateFilterToText('2026-02-01', '2026-02-04T23:59:59', 'default')).toEqual(
+ 'February 1, 00:00:00 - February 4, 23:59:59'
+ )
+ // YYYY-MM-DD from + YYYY-MM-DDTHH:mm:ss.SSS to
+ expect(dateFilterToText('2026-02-01', '2026-02-04T23:59:59.999', 'default')).toEqual(
+ 'February 1, 00:00:00 - February 4, 23:59:59'
+ )
+ // YYYY-MM-DDTHH:mm:ss from + YYYY-MM-DD to (both resolve to midnight → times omitted)
+ expect(dateFilterToText('2026-02-01T00:00:00', '2026-02-04', 'default')).toEqual(
+ 'February 1 - February 4'
+ )
+ // YYYY-MM-DDTHH:mm:ss.SSS from + YYYY-MM-DD to (both resolve to midnight → times omitted)
+ expect(dateFilterToText('2026-02-01T00:00:00.000', '2026-02-04', 'default')).toEqual(
+ 'February 1 - February 4'
+ )
+ // Non-midnight datetime from + YYYY-MM-DD to
+ expect(dateFilterToText('2026-02-01T14:30:00', '2026-02-04', 'default')).toEqual(
+ 'February 1, 14:30 - February 4, 00:00'
+ )
+ })
+
+ it('handles same-day datetime range', () => {
+ expect(dateFilterToText('2026-02-01T09:00:00', '2026-02-01T17:00:00', 'default')).toEqual(
+ 'February 1, 09:00 - 17:00'
+ )
+ })
+
+ it('can have overridden date options', () => {
+ expect(dateFilterToText('-21d', null, 'default', [{ key: 'Last 3 weeks', values: ['-21d'] }])).toEqual(
+ 'Last 3 weeks'
+ )
+ })
+ })
+
+ describe('formatted', () => {
+ it('handles dayjs dates', () => {
+ const from = dayjs('2018-04-04T16:00:00.000Z')
+ const to = dayjs('2018-04-09T15:05:00.000Z')
+
+ expect(dateFilterToText(from, to, 'custom', dateMapping, true)).toEqual('April 4 - April 9, 2018')
+ })
+
+ it('handles various ranges', () => {
+ // 2012-03-02T11:38:49.321Z
+ tk.freeze(new Date(1330688329321))
+ expect(dateFilterToText('dStart', null, 'default', dateMapping, true)).toEqual('March 2, 2012')
+ expect(dateFilterToText('2020-01-02', '2020-01-05', 'default', dateMapping, true)).toEqual(
+ 'January 2 - January 5, 2020'
+ )
+ expect(dateFilterToText(null, null, 'default', dateMapping, true)).toEqual('default')
+ expect(dateFilterToText('-24h', null, 'default', dateMapping, true)).toEqual('March 1 - March 2, 2012')
+ expect(dateFilterToText('-48h', undefined, 'default', dateMapping, true)).toEqual(
+ 'February 29 - March 2, 2012'
+ )
+ expect(dateFilterToText('-1d', null, 'default', dateMapping, true)).toEqual('March 1 - March 2, 2012')
+ expect(dateFilterToText('-1dStart', '-1dEnd', 'default', dateMapping, true)).toEqual('March 1, 2012')
+ expect(dateFilterToText('-1mStart', '-1mEnd', 'default', dateMapping, true)).toEqual(
+ 'February 1 - February 29, 2012'
+ )
+ expect(dateFilterToText('-180d', null, 'default', dateMapping, true)).toEqual(
+ 'September 4, 2011 - March 2, 2012'
+ )
+ tk.reset()
+ })
+
+ it('can have overridden date options', () => {
+ tk.freeze(new Date(1330688329321))
+ expect(
+ dateFilterToText(
+ '-21d',
+ null,
+ 'default',
+ [{ key: 'Last 3 weeks', values: ['-21d'], getFormattedDate: () => 'custom formatted date' }],
+ true
+ )
+ ).toEqual('custom formatted date')
+ tk.reset()
+ })
+
+ it('can have overridden date format', () => {
+ const from = dayjs('2018-04-04T16:00:00.000Z').tz('America/New_York')
+ const to = dayjs('2018-04-09T15:05:00.000Z').tz('America/New_York')
+
+ expect(dateFilterToText(from, to, 'custom', dateMapping, true, 'YYYY-MM-DD hh:mm:ss')).toEqual(
+ '2018-04-04 12:00:00 - 2018-04-09 11:05:00'
+ )
+ })
+ })
+
+ describe('week formatting respects weekStartDay', () => {
+ // 2012-03-02 is a Friday
+ beforeEach(() => {
+ tk.freeze(new Date(1330688329321))
+ })
+ afterEach(() => {
+ tk.reset()
+ })
+
+ it('This week with Sunday start (default)', () => {
+ expect(
+ dateFilterToText('wStart', undefined, 'default', dateMapping, true, undefined, undefined, 0)
+ ).toEqual('February 26 - March 2, 2012')
+ })
+
+ it('This week with Monday start', () => {
+ expect(
+ dateFilterToText('wStart', undefined, 'default', dateMapping, true, undefined, undefined, 1)
+ ).toEqual('February 27 - March 2, 2012')
+ })
+
+ it('Last week with Sunday start (default)', () => {
+ expect(
+ dateFilterToText('-1wStart', '-1wEnd', 'default', dateMapping, true, undefined, undefined, 0)
+ ).toEqual('February 19 - February 25, 2012')
+ })
+
+ it('Last week with Monday start', () => {
+ expect(
+ dateFilterToText('-1wStart', '-1wEnd', 'default', dateMapping, true, undefined, undefined, 1)
+ ).toEqual('February 20 - February 26, 2012')
+ })
+ })
+ })
+
+ describe('dateStringToDayJs', () => {
+ beforeEach(() => {
+ tk.freeze(1330688329321) // randomly chosen time on the 22nd of February 2022
+ })
+ afterEach(() => {
+ tk.reset()
+ })
+
+ it('handles various dates', () => {
+ expect(dateStringToDayJs('2022-02-22')?.utc(true).toISOString()).toEqual('2022-02-22T00:00:00.000Z')
+ expect(dateStringToDayJs('1999-12-31')?.utc(true).toISOString()).toEqual('1999-12-31T00:00:00.000Z')
+ })
+
+ it('handles various units', () => {
+ expect(dateStringToDayJs('d')?.utc(true).toISOString()).toEqual('2012-03-02T00:00:00.000Z')
+ expect(dateStringToDayJs('m')?.utc(true).toISOString()).toEqual('2012-03-02T00:00:00.000Z')
+ expect(dateStringToDayJs('w')?.utc(true).toISOString()).toEqual('2012-03-02T00:00:00.000Z')
+ expect(dateStringToDayJs('q')?.utc(true).toISOString()).toEqual('2012-03-02T00:00:00.000Z')
+ expect(dateStringToDayJs('y')?.utc(true).toISOString()).toEqual('2012-03-02T00:00:00.000Z')
+ expect(dateStringToDayJs('x')).toEqual(null)
+ })
+
+ it('handles pluses and minuses', () => {
+ expect(dateStringToDayJs('d')?.utc(true).toISOString()).toEqual('2012-03-02T00:00:00.000Z')
+ expect(dateStringToDayJs('+d')?.utc(true).toISOString()).toEqual('2012-03-02T00:00:00.000Z')
+ expect(dateStringToDayJs('-d')?.utc(true).toISOString()).toEqual('2012-03-02T00:00:00.000Z')
+
+ expect(dateStringToDayJs('1d')?.utc(true).toISOString()).toEqual('2012-03-03T00:00:00.000Z')
+ expect(dateStringToDayJs('2d')?.utc(true).toISOString()).toEqual('2012-03-04T00:00:00.000Z')
+ expect(dateStringToDayJs('3d')?.utc(true).toISOString()).toEqual('2012-03-05T00:00:00.000Z')
+ expect(dateStringToDayJs('33d')?.utc(true).toISOString()).toEqual('2012-04-04T00:00:00.000Z')
+
+ expect(dateStringToDayJs('+1d')?.utc(true).toISOString()).toEqual('2012-03-03T00:00:00.000Z')
+ expect(dateStringToDayJs('+2d')?.utc(true).toISOString()).toEqual('2012-03-04T00:00:00.000Z')
+ expect(dateStringToDayJs('+3d')?.utc(true).toISOString()).toEqual('2012-03-05T00:00:00.000Z')
+ expect(dateStringToDayJs('+33d')?.utc(true).toISOString()).toEqual('2012-04-04T00:00:00.000Z')
+
+ expect(dateStringToDayJs('-1d')?.utc(true).toISOString()).toEqual('2012-03-01T00:00:00.000Z')
+ expect(dateStringToDayJs('-2d')?.utc(true).toISOString()).toEqual('2012-02-29T00:00:00.000Z')
+ expect(dateStringToDayJs('-3d')?.utc(true).toISOString()).toEqual('2012-02-28T00:00:00.000Z')
+ expect(dateStringToDayJs('-33d')?.utc(true).toISOString()).toEqual('2012-01-29T00:00:00.000Z')
+
+ expect(dateStringToDayJs('-33m')?.utc(true).toISOString()).toEqual('2009-06-02T00:00:00.000Z')
+ expect(dateStringToDayJs('-33w')?.utc(true).toISOString()).toEqual('2011-07-15T00:00:00.000Z')
+ expect(dateStringToDayJs('-33q')?.utc(true).toISOString()).toEqual('2003-12-02T00:00:00.000Z')
+ expect(dateStringToDayJs('-33y')?.utc(true).toISOString()).toEqual('1979-03-02T00:00:00.000Z')
+ })
+
+ it('handles various start/end values', () => {
+ expect(dateStringToDayJs('dStart')?.utc(true).toISOString()).toEqual('2012-03-02T00:00:00.000Z')
+ expect(dateStringToDayJs('dEnd')?.utc(true).toISOString()).toEqual('2012-03-02T23:59:59.999Z')
+ expect(dateStringToDayJs('wStart')?.utc(true).toISOString()).toEqual('2012-02-26T00:00:00.000Z')
+ expect(dateStringToDayJs('wEnd')?.utc(true).toISOString()).toEqual('2012-03-03T23:59:59.999Z')
+ expect(dateStringToDayJs('mStart')?.utc(true).toISOString()).toEqual('2012-03-01T00:00:00.000Z')
+ expect(dateStringToDayJs('mEnd')?.utc(true).toISOString()).toEqual('2012-03-31T23:59:59.999Z')
+ expect(dateStringToDayJs('qStart')?.utc(true).toISOString()).toEqual('2012-01-01T00:00:00.000Z')
+ expect(dateStringToDayJs('qEnd')?.utc(true).toISOString()).toEqual('2012-03-31T23:59:59.999Z')
+ expect(dateStringToDayJs('yStart')?.utc(true).toISOString()).toEqual('2012-01-01T00:00:00.000Z')
+ expect(dateStringToDayJs('yEnd')?.utc(true).toISOString()).toEqual('2012-12-31T23:59:59.999Z')
+ })
+
+ it('handles various start/end values with units', () => {
+ expect(dateStringToDayJs('1dStart')?.utc(true).toISOString()).toEqual('2012-03-03T00:00:00.000Z')
+ expect(dateStringToDayJs('1dEnd')?.utc(true).toISOString()).toEqual('2012-03-03T23:59:59.999Z')
+
+ expect(dateStringToDayJs('-1wStart')?.utc(true).toISOString()).toEqual('2012-02-19T00:00:00.000Z')
+ expect(dateStringToDayJs('-1wEnd')?.utc(true).toISOString()).toEqual('2012-02-25T23:59:59.999Z')
+
+ expect(dateStringToDayJs('12mStart')?.utc(true).toISOString()).toEqual('2013-03-01T00:00:00.000Z')
+ expect(dateStringToDayJs('12mEnd')?.utc(true).toISOString()).toEqual('2013-03-31T23:59:59.999Z')
+
+ expect(dateStringToDayJs('-4qStart')?.utc(true).toISOString()).toEqual('2011-01-01T00:00:00.000Z')
+ expect(dateStringToDayJs('-4qEnd')?.utc(true).toISOString()).toEqual('2011-03-31T23:59:59.999Z')
+
+ expect(dateStringToDayJs('0yStart')?.utc(true).toISOString()).toEqual('2012-01-01T00:00:00.000Z')
+ expect(dateStringToDayJs('0yEnd')?.utc(true).toISOString()).toEqual('2012-12-31T23:59:59.999Z')
+ })
+ })
+
+ describe('getDefaultInterval', () => {
+ it('should return days for last 7 days', () => {
+ expect(getDefaultInterval('-7d', null)).toEqual('day')
+ })
+
+ it('should return hours for last 24 hours', () => {
+ expect(getDefaultInterval('-24h', null)).toEqual('hour')
+ })
+
+ it('should return days for month to date', () => {
+ expect(getDefaultInterval('mStart', null)).toEqual('day')
+ })
+
+ it('should return days for week to date', () => {
+ expect(getDefaultInterval('wStart', null)).toEqual('day')
+ })
+
+ it('should return month for year to date', () => {
+ expect(getDefaultInterval('yStart', null)).toEqual('month')
+ })
+
+ it('should return month for all time', () => {
+ expect(getDefaultInterval('all', null)).toEqual('month')
+ })
+
+ it('should handle explicit dates 6 months apart', () => {
+ expect(getDefaultInterval('2023-10-01', '2023-04-01')).toEqual('month')
+ })
+ it('should handle explicit dates a month apart', () => {
+ expect(getDefaultInterval('2023-10-01', '2023-09-01')).toEqual('week')
+ })
+ it('should handle explicit dates a week apart', () => {
+ expect(getDefaultInterval('2023-10-01', '2023-09-25')).toEqual('day')
+ })
+ it('should handle explicit dates a day apart', () => {
+ expect(getDefaultInterval('2023-10-02', '2023-10-01')).toEqual('hour')
+ })
+ it('should handle explicit dates 12 hours apart', () => {
+ expect(getDefaultInterval('2023-10-01T18:00:00', '2023-10-01T6:00:00')).toEqual('hour')
+ })
+ })
+
+ describe('areDatesValidForInterval', () => {
+ it('should require interval to be month for all time', () => {
+ expect(areDatesValidForInterval('month', 'all', null)).toEqual(true)
+ expect(areDatesValidForInterval('week', 'all', null)).toEqual(false)
+ expect(areDatesValidForInterval('day', 'all', null)).toEqual(false)
+ expect(areDatesValidForInterval('hour', 'all', null)).toEqual(false)
+ })
+ it('should return false if the dates are one interval apart', () => {
+ expect(areDatesValidForInterval('day', '-24h', null)).toEqual(false)
+ expect(areDatesValidForInterval('week', '-7d', null)).toEqual(false)
+ expect(areDatesValidForInterval('day', '-1d', null)).toEqual(false)
+ })
+ it('should return true if the dates are two intervals apart', () => {
+ expect(areDatesValidForInterval('day', '-48h', null)).toEqual(true)
+ expect(areDatesValidForInterval('week', '-14d', null)).toEqual(true)
+ expect(areDatesValidForInterval('day', '-2d', null)).toEqual(true)
+ })
+ it('should return false for hourly if over 2 weeks', () => {
+ expect(areDatesValidForInterval('hour', '-15d', null)).toEqual(false)
+ })
+ it('should support explicit dates', () => {
+ expect(areDatesValidForInterval('month', '2023-08-01', '2023-11-01')).toEqual(true)
+ expect(areDatesValidForInterval('week', '2023-10-01', '2023-11-01')).toEqual(true)
+ expect(areDatesValidForInterval('day', '2023-10-16', '2023-11-01')).toEqual(true)
+ expect(areDatesValidForInterval('hour', '2023-11-01T12', '2023-11-01T18')).toEqual(true)
+ })
+ })
+
+ describe('time ranges', () => {
+ it('is less than or equal to 12 hours', () => {
+ expect(is12HoursOrLess('-0h')).toBeTruthy()
+ expect(is12HoursOrLess('-1h')).toBeTruthy()
+ expect(is12HoursOrLess('-12h')).toBeTruthy()
+ expect(is12HoursOrLess('-13h')).toBeFalsy()
+
+ expect(is12HoursOrLess('-24h')).toBeFalsy()
+ expect(is12HoursOrLess('-30h')).toBeFalsy()
+ expect(is12HoursOrLess('-47h')).toBeFalsy()
+ expect(is12HoursOrLess('-111h')).toBeFalsy()
+
+ expect(is12HoursOrLess('-1.123h')).toBeFalsy()
+ expect(is12HoursOrLess('1.123h')).toBeFalsy()
+ expect(is12HoursOrLess('-ab1-13h')).toBeFalsy()
+ expect(is12HoursOrLess('-1d')).toBeFalsy()
+ expect(is12HoursOrLess('-1w')).toBeFalsy()
+ expect(is12HoursOrLess('-1h-2h')).toBeFalsy()
+ })
+
+ it('is less than 2 days', () => {
+ expect(isLessThan2Days('-0h')).toBeTruthy()
+ expect(isLessThan2Days('-1h')).toBeTruthy()
+ expect(isLessThan2Days('-12h')).toBeTruthy()
+ expect(isLessThan2Days('-24h')).toBeTruthy()
+ expect(isLessThan2Days('-30h')).toBeTruthy()
+ expect(isLessThan2Days('-47h')).toBeTruthy()
+
+ expect(isLessThan2Days('-48h')).toBeFalsy()
+ expect(isLessThan2Days('-49h')).toBeFalsy()
+ expect(isLessThan2Days('0h')).toBeFalsy()
+ expect(isLessThan2Days('1h')).toBeFalsy()
+ expect(isLessThan2Days('48h')).toBeFalsy()
+ expect(isLessThan2Days('-13.123h')).toBeFalsy()
+ expect(isLessThan2Days('13.123h')).toBeFalsy()
+ expect(isLessThan2Days('-ab1-13h')).toBeFalsy()
+ expect(isLessThan2Days('-1d-1h')).toBeFalsy()
+ })
+ })
+})
diff --git a/frontend/src/lib/utils/dateFilters.ts b/frontend/src/lib/utils/dateFilters.ts
new file mode 100644
index 000000000000..191eff6e52ee
--- /dev/null
+++ b/frontend/src/lib/utils/dateFilters.ts
@@ -0,0 +1,469 @@
+import { CUSTOM_OPTION_KEY } from 'lib/components/DateFilter/types'
+import { Dayjs, dayjs } from 'lib/dayjs'
+import { DATE_FORMAT, formatDate, formatDateRange, formatDateTimeRange, isDate } from 'lib/utils/datetime'
+import { UnexpectedNeverError } from 'lib/utils/guards'
+
+import { DateMappingOption, IntervalType } from '~/types'
+
+/** Returns the start of the current week, respecting the team's week start day (0=Sunday, 1=Monday). */
+function startOfWeek(date: dayjs.Dayjs, weekStartDay?: number | null): dayjs.Dayjs {
+ const start = weekStartDay === 1 ? 1 : 0
+ return date.subtract((date.day() - start + 7) % 7, 'day').startOf('day')
+}
+
+export const dateMapping: DateMappingOption[] = [
+ { key: CUSTOM_OPTION_KEY, values: [] },
+ {
+ key: 'Today',
+ values: ['dStart'],
+ getFormattedDate: (date: dayjs.Dayjs): string => date.startOf('d').format(DATE_FORMAT),
+ defaultInterval: 'hour',
+ },
+ {
+ key: 'Yesterday',
+ values: ['-1dStart', '-1dEnd'],
+ getFormattedDate: (date: dayjs.Dayjs): string => date.subtract(1, 'd').format(DATE_FORMAT),
+ defaultInterval: 'hour',
+ },
+ {
+ key: 'Last hour',
+ values: ['-1h'],
+ getFormattedDate: (date: dayjs.Dayjs): string => formatDateRange(date.subtract(1, 'h'), date),
+ defaultInterval: 'minute',
+ },
+ {
+ key: 'Last 24 hours',
+ values: ['-24h'],
+ getFormattedDate: (date: dayjs.Dayjs): string => formatDateRange(date.subtract(24, 'h'), date.endOf('d')),
+ defaultInterval: 'hour',
+ },
+ {
+ key: 'Last 48 hours',
+ values: ['-48h'],
+ getFormattedDate: (date: dayjs.Dayjs): string => formatDateRange(date.subtract(48, 'h'), date.endOf('d')),
+ inactive: true,
+ defaultInterval: 'hour',
+ },
+ {
+ key: 'Last 7 days',
+ values: ['-7d'],
+ getFormattedDate: (date: dayjs.Dayjs): string => formatDateRange(date.subtract(7, 'd'), date.endOf('d')),
+ defaultInterval: 'day',
+ },
+ {
+ key: 'Last 14 days',
+ values: ['-14d'],
+ getFormattedDate: (date: dayjs.Dayjs): string => formatDateRange(date.subtract(14, 'd'), date.endOf('d')),
+ defaultInterval: 'day',
+ },
+ {
+ key: 'Last 30 days',
+ values: ['-30d'],
+ getFormattedDate: (date: dayjs.Dayjs): string => formatDateRange(date.subtract(30, 'd'), date.endOf('d')),
+ defaultInterval: 'day',
+ },
+ {
+ key: 'Last 90 days',
+ values: ['-90d'],
+ getFormattedDate: (date: dayjs.Dayjs): string => formatDateRange(date.subtract(90, 'd'), date.endOf('d')),
+ defaultInterval: 'day',
+ },
+ {
+ key: 'Last 180 days',
+ values: ['-180d'],
+ getFormattedDate: (date: dayjs.Dayjs): string => formatDateRange(date.subtract(180, 'd'), date.endOf('d')),
+ defaultInterval: 'month',
+ },
+
+ {
+ key: 'Last week',
+ values: ['-1wStart', '-1wEnd'],
+ getFormattedDate: (date: dayjs.Dayjs, _format?: string, weekStartDay?: number): string => {
+ const lastWeekStart = startOfWeek(date, weekStartDay).subtract(7, 'day')
+ return formatDateRange(lastWeekStart, lastWeekStart.add(6, 'day').endOf('d'))
+ },
+ defaultInterval: 'day',
+ },
+ {
+ key: 'Last month',
+ values: ['-1mStart', '-1mEnd'],
+ getFormattedDate: (date: dayjs.Dayjs): string =>
+ formatDateRange(date.subtract(1, 'month').startOf('month'), date.subtract(1, 'month').endOf('month')),
+ defaultInterval: 'day',
+ },
+ {
+ key: 'This week',
+ values: ['wStart'],
+ getFormattedDate: (date: dayjs.Dayjs, _format?: string, weekStartDay?: number): string =>
+ formatDateRange(startOfWeek(date, weekStartDay), date.endOf('d')),
+ defaultInterval: 'day',
+ },
+ {
+ key: 'This month',
+ values: ['mStart'],
+ getFormattedDate: (date: dayjs.Dayjs): string => formatDateRange(date.startOf('month'), date.endOf('month')),
+ defaultInterval: 'day',
+ },
+ {
+ key: 'Year to date',
+ values: ['yStart'],
+ getFormattedDate: (date: dayjs.Dayjs): string => formatDateRange(date.startOf('y'), date.endOf('d')),
+ defaultInterval: 'month',
+ },
+ {
+ key: 'All time',
+ values: ['all'],
+ defaultInterval: 'month',
+ },
+]
+
+const dateOptionsMap = {
+ y: 'year',
+ q: 'quarter',
+ m: 'month',
+ w: 'week',
+ d: 'day',
+ h: 'hour',
+ M: 'minute',
+ s: 'second',
+} as const
+
+export function dateFilterToText(
+ dateFrom: string | dayjs.Dayjs | null | undefined,
+ dateTo: string | dayjs.Dayjs | null | undefined,
+ defaultValue: string | null,
+ dateOptions: DateMappingOption[] = dateMapping,
+ isDateFormatted: boolean = false,
+ dateFormat: string = DATE_FORMAT,
+ startOfRange: boolean = false,
+ weekStartDay?: number
+): string | null {
+ if (dayjs.isDayjs(dateFrom) && dayjs.isDayjs(dateTo)) {
+ return formatDateRange(dateFrom, dateTo, dateFormat)
+ }
+ dateFrom = (dateFrom || undefined) as string | undefined
+ dateTo = (dateTo || undefined) as string | undefined
+
+ if (isDate.test(dateFrom || '') && isDate.test(dateTo || '')) {
+ if (isDateFormatted) {
+ return formatDateRange(dayjs(dateFrom, 'YYYY-MM-DD'), dayjs(dateTo, 'YYYY-MM-DD'))
+ }
+ if (dateFrom?.includes('T') || dateTo?.includes('T')) {
+ // Parse each date individually - ISO 8601 datetimes (with T) use native parsing
+ // to correctly handle seconds/milliseconds, plain dates use 'YYYY-MM-DD'
+ const parsedFrom = dateFrom?.includes('T') ? dayjs(dateFrom) : dayjs(dateFrom, 'YYYY-MM-DD')
+ const parsedTo = dateTo?.includes('T') ? dayjs(dateTo) : dayjs(dateTo, 'YYYY-MM-DD')
+ return formatDateTimeRange(parsedFrom, parsedTo)
+ }
+ return `${dateFrom} - ${dateTo}`
+ }
+
+ // From date to today
+ if (isDate.test(dateFrom || '') && !isDate.test(dateTo || '')) {
+ const days = dayjs().diff(dayjs(dateFrom), 'days')
+ if (days > 366) {
+ return isDateFormatted ? `${dateFrom} - today` : formatDateRange(dayjs(dateFrom), dayjs())
+ } else if (days > 0) {
+ return isDateFormatted ? formatDateRange(dayjs(dateFrom), dayjs()) : `Last ${days} days`
+ } else if (days === 0) {
+ return isDateFormatted ? dayjs(dateFrom).format(dateFormat) : `Today`
+ }
+ return isDateFormatted ? `${dayjs(dateFrom).format(dateFormat)} - ` : `Starting from ${dateFrom}`
+ }
+
+ for (const { key, values, getFormattedDate } of dateOptions) {
+ if (values[0] === dateFrom && values[1] === dateTo && key !== CUSTOM_OPTION_KEY) {
+ return isDateFormatted && getFormattedDate ? getFormattedDate(dayjs(), dateFormat, weekStartDay) : key
+ }
+ }
+
+ if (dateFrom) {
+ const dateOption = dateOptionsMap[dateFrom.slice(-1) as keyof typeof dateOptionsMap]
+ const counter = parseInt(dateFrom.slice(1, -1))
+ if (dateOption && counter) {
+ let date = null
+ switch (dateOption) {
+ case 'year':
+ date = dayjs().subtract(counter, 'y')
+ break
+ case 'hour':
+ date = dayjs().subtract(counter, 'h')
+ break
+ case 'quarter':
+ date = dayjs().subtract(counter * 3, 'M')
+ break
+ case 'month':
+ date = dayjs().subtract(counter, 'M')
+ break
+ case 'week':
+ date = dayjs().subtract(counter * 7, 'd')
+ break
+ case 'minute':
+ date = dayjs().subtract(counter, 'm')
+ break
+ case 'second':
+ date = dayjs().subtract(counter, 's')
+ break
+ default:
+ date = dayjs().subtract(counter, 'd')
+ break
+ }
+ if (isDateFormatted) {
+ return formatDateRange(date, dayjs().endOf('d'))
+ } else if (startOfRange) {
+ return formatDate(date, dateFormat)
+ }
+ return `Last ${counter} ${dateOption}${counter > 1 ? 's' : ''}`
+ }
+ }
+
+ return defaultValue
+}
+
+// Converts a dateFrom string ("-2w") into english: "2 weeks"
+export function dateFromToText(dateFrom: string): string | undefined {
+ const dateOption: (typeof dateOptionsMap)[keyof typeof dateOptionsMap] =
+ dateOptionsMap[dateFrom.slice(-1) as keyof typeof dateOptionsMap]
+ const counter = parseInt(dateFrom.slice(1, -1))
+ if (dateOption && counter) {
+ return `${counter} ${dateOption}${counter > 1 ? 's' : ''}`
+ }
+ return undefined
+}
+
+export type DateComponents = {
+ amount: number
+ unit: (typeof dateOptionsMap)[keyof typeof dateOptionsMap]
+ clip: 'Start' | 'End'
+}
+
+export const isStringDateRegex = /^([-+]?)([0-9]*)([hdwmqy])(|Start|End)$/
+
+export function dateStringToComponents(date: string | null): DateComponents | null {
+ if (!date) {
+ return null
+ }
+ const matches = date.match(isStringDateRegex)
+ if (!matches) {
+ return null
+ }
+ const [, sign, rawAmount, rawUnit, clip] = matches
+ const amount = rawAmount ? parseInt(sign + rawAmount) : 0
+ const unit = dateOptionsMap[rawUnit as keyof typeof dateOptionsMap] || 'day'
+ return { amount, unit, clip: clip as 'Start' | 'End' }
+}
+
+export function componentsToDayJs(
+ { amount, unit, clip }: DateComponents,
+ offset?: Dayjs,
+ timezone: string = 'UTC'
+): Dayjs {
+ const dayjsInstance = offset ?? dayjs().tz(timezone)
+ let response: dayjs.Dayjs
+ switch (unit) {
+ case 'year':
+ response = dayjsInstance.add(amount, 'year')
+ break
+ case 'quarter':
+ response = dayjsInstance.add(amount * 3, 'month')
+ break
+ case 'month':
+ response = dayjsInstance.add(amount, 'month')
+ break
+ case 'week':
+ response = dayjsInstance.add(amount * 7, 'day')
+ break
+ case 'day':
+ response = dayjsInstance.add(amount, 'day')
+ break
+ case 'hour':
+ response = dayjsInstance.add(amount, 'hour')
+ break
+ case 'minute':
+ response = dayjsInstance.add(amount, 'minute')
+ break
+ case 'second':
+ response = dayjsInstance.add(amount, 'second')
+ break
+ default:
+ throw new UnexpectedNeverError(unit)
+ }
+
+ if (clip === 'Start') {
+ return response.startOf(unit)
+ } else if (clip === 'End') {
+ return response.endOf(unit)
+ }
+ return response
+}
+
+/** Convert a string like "-30d" or "2022-02-02" or "-1mEnd" to `Dayjs().startOf('day')` */
+export function dateStringToDayJs(date: string | null, timezone: string = 'UTC'): dayjs.Dayjs | null {
+ if (isDate.test(date || '')) {
+ return dayjs.tz(date, timezone)
+ }
+ const dateComponents = dateStringToComponents(date)
+ if (!dateComponents) {
+ return null
+ }
+ const offset: dayjs.Dayjs = dayjs().tz(timezone).startOf('day')
+ const response = componentsToDayJs(dateComponents, offset, timezone)
+ return response
+}
+
+export function isValidRelativeOrAbsoluteDate(date: string): boolean {
+ if (isStringDateRegex.test(date)) {
+ return true
+ }
+ if (dayjs(date).isValid()) {
+ return true
+ }
+ if (date === 'all') {
+ return true
+ }
+ return false
+}
+
+export const getDefaultInterval = (dateFrom: string | null, dateTo: string | null): IntervalType => {
+ // use the default mapping if we can
+ for (const mapping of dateMapping) {
+ const mappingFrom = mapping.values[0] ?? null
+ const mappingTo = mapping.values[1] ?? null
+ if (mappingFrom === dateFrom && mappingTo === dateTo && mapping.defaultInterval) {
+ return mapping.defaultInterval
+ }
+ }
+
+ const parsedDateFrom = dateStringToComponents(dateFrom)
+ const parsedDateTo = dateStringToComponents(dateTo)
+
+ if (parsedDateFrom?.unit === 'hour' || parsedDateTo?.unit === 'hour') {
+ return 'hour'
+ }
+
+ if (
+ parsedDateFrom?.unit === 'day' ||
+ parsedDateTo?.unit === 'day' ||
+ dateFrom === 'mStart' ||
+ dateFrom === 'wStart'
+ ) {
+ return 'day'
+ }
+
+ if (
+ (parsedDateFrom?.unit === 'month' && parsedDateFrom.amount <= 3) ||
+ (parsedDateTo?.unit === 'month' && parsedDateTo.amount <= 3) ||
+ (parsedDateFrom?.unit === 'quarter' && parsedDateFrom.amount <= 1) ||
+ (parsedDateTo?.unit === 'quarter' && parsedDateTo.amount <= 1)
+ ) {
+ return 'day'
+ }
+
+ if (
+ parsedDateFrom?.unit === 'month' ||
+ parsedDateTo?.unit === 'month' ||
+ parsedDateFrom?.unit === 'quarter' ||
+ parsedDateTo?.unit === 'quarter' ||
+ parsedDateFrom?.unit === 'year' ||
+ parsedDateTo?.unit === 'year' ||
+ dateFrom === 'all'
+ ) {
+ return 'month'
+ }
+
+ const dateFromDayJs = dateStringToDayJs(dateFrom)
+ const dateToDayJs = dateStringToDayJs(dateTo)
+
+ const intervalMonths = dateFromDayJs?.diff(dateToDayJs, 'month')
+ if (intervalMonths != null && Math.abs(intervalMonths) >= 2) {
+ return 'month'
+ }
+ const intervalDays = dateFromDayJs?.diff(dateToDayJs, 'day')
+ if (intervalDays != null && Math.abs(intervalDays) >= 14) {
+ return 'week'
+ }
+ if (intervalDays != null && Math.abs(intervalDays) >= 2) {
+ return 'day'
+ }
+ const intervalHours = dateFromDayJs?.diff(dateToDayJs, 'hour')
+ if (intervalHours != null && Math.abs(intervalHours) >= 1) {
+ return 'hour'
+ }
+
+ return 'day'
+}
+
+/* If the interval changes, check if it's compatible with the selected dates, and return new dates
+ * from a map of sensible defaults if not */
+export const areDatesValidForInterval = (
+ interval: IntervalType,
+ oldDateFrom: string | null,
+ oldDateTo: string | null
+): boolean => {
+ const parsedOldDateFrom = dateStringToDayJs(oldDateFrom)
+ const parsedOldDateTo = dateStringToDayJs(oldDateTo) || dayjs()
+
+ if (oldDateFrom === 'all' || !parsedOldDateFrom) {
+ return interval === 'month'
+ } else if (interval === 'month') {
+ return parsedOldDateTo.diff(parsedOldDateFrom, 'month') >= 2
+ } else if (interval === 'week') {
+ return parsedOldDateTo.diff(parsedOldDateFrom, 'week') >= 2
+ } else if (interval === 'day') {
+ const diff = parsedOldDateTo.diff(parsedOldDateFrom, 'day')
+ return diff >= 2
+ } else if (interval === 'hour') {
+ return (
+ parsedOldDateTo.diff(parsedOldDateFrom, 'hour') >= 2 &&
+ parsedOldDateTo.diff(parsedOldDateFrom, 'hour') < 24 * 7 * 2 // 2 weeks
+ )
+ } else if (interval === 'minute') {
+ return (
+ parsedOldDateTo.diff(parsedOldDateFrom, 'minute') >= 2 &&
+ parsedOldDateTo.diff(parsedOldDateFrom, 'minute') < 60 * 12 // 12 hours. picked based on max graph resolution
+ )
+ } else if (interval === 'second') {
+ return (
+ parsedOldDateTo.diff(parsedOldDateFrom, 'second') >= 2 &&
+ parsedOldDateTo.diff(parsedOldDateFrom, 'second') < 60 * 60 // 1 hour
+ )
+ }
+ throw new UnexpectedNeverError(interval)
+}
+
+const defaultDatesForInterval = {
+ second: { dateFrom: '-1M', dateTo: null },
+ minute: { dateFrom: '-1h', dateTo: null },
+ hour: { dateFrom: '-24h', dateTo: null },
+ day: { dateFrom: '-7d', dateTo: null },
+ week: { dateFrom: '-28d', dateTo: null },
+ month: { dateFrom: '-6m', dateTo: null },
+}
+
+export const updateDatesWithInterval = (
+ interval: IntervalType,
+ oldDateFrom: string | null,
+ oldDateTo: string | null
+): { dateFrom: string | null; dateTo: string | null } => {
+ if (areDatesValidForInterval(interval, oldDateFrom, oldDateTo)) {
+ return {
+ dateFrom: oldDateFrom,
+ dateTo: oldDateTo,
+ }
+ }
+ return defaultDatesForInterval[interval]
+}
+
+export function is12HoursOrLess(dateFrom: string | undefined | null): boolean {
+ if (!dateFrom) {
+ return false
+ }
+ return dateFrom.search(/^-([0-9]|1[0-2])h$/) != -1
+}
+
+export function isLessThan2Days(dateFrom: string | undefined | null): boolean {
+ if (!dateFrom) {
+ return false
+ }
+ return dateFrom.search(/^-(4[0-7]|[0-3]?[0-9])h|[1-2]d$/) != -1
+}
diff --git a/frontend/src/lib/utils/dateRangeUtils.test.ts b/frontend/src/lib/utils/dateRangeUtils.test.ts
deleted file mode 100644
index 3c14b903ae67..000000000000
--- a/frontend/src/lib/utils/dateRangeUtils.test.ts
+++ /dev/null
@@ -1,364 +0,0 @@
-import { dayjs } from 'lib/dayjs'
-
-import { alignResolvedDateRangeToInterval, formatLocalizedDate, getConstrainedWeekRange } from './dateTimeUtils'
-
-describe('getConstrainedWeekRange', () => {
- beforeEach(() => {
- // Reset locale to default before each test
- dayjs.updateLocale('en', {
- weekStart: 0,
- })
- })
-
- describe('basic functionality', () => {
- it('should return week boundaries for a mid-week date with Sunday start', () => {
- const referenceDate = dayjs('2024-01-10') // Wednesday
- const result = getConstrainedWeekRange(referenceDate)
-
- expect(result.start.format('YYYY-MM-DD')).toBe('2024-01-07') // Sunday
- expect(result.end.format('YYYY-MM-DD')).toBe('2024-01-13') // Saturday
- })
-
- it('should return week boundaries for a mid-week date with Monday start', () => {
- const referenceDate = dayjs('2024-01-10') // Wednesday
- const result = getConstrainedWeekRange(referenceDate, null, 1)
-
- expect(result.start.format('YYYY-MM-DD')).toBe('2024-01-08') // Monday
- expect(result.end.format('YYYY-MM-DD')).toBe('2024-01-14') // Sunday
- })
-
- it('should handle reference date at start of week', () => {
- const referenceDate = dayjs('2024-01-07') // Sunday
- const result = getConstrainedWeekRange(referenceDate, null, 0)
-
- expect(result.start.format('YYYY-MM-DD')).toBe('2024-01-07') // Sunday
- expect(result.end.format('YYYY-MM-DD')).toBe('2024-01-13') // Saturday
- })
-
- it('should handle reference date at end of week', () => {
- const referenceDate = dayjs('2024-01-13') // Saturday
- const result = getConstrainedWeekRange(referenceDate, null, 0)
-
- expect(result.start.format('YYYY-MM-DD')).toBe('2024-01-07') // Sunday
- expect(result.end.format('YYYY-MM-DD')).toBe('2024-01-13') // Saturday
- })
- })
-
- describe('edge case handling', () => {
- it('should handle Sunday reference date with Monday week start', () => {
- const referenceDate = dayjs('2024-01-07') // Sunday
- const result = getConstrainedWeekRange(referenceDate, null, 1)
-
- // Sunday should be adjusted to Monday when week starts on Monday
- expect(result.start.format('YYYY-MM-DD')).toBe('2024-01-08') // Monday
- expect(result.end.format('YYYY-MM-DD')).toBe('2024-01-14') // Sunday
- })
-
- it('should handle Monday reference date with Sunday week start', () => {
- const referenceDate = dayjs('2024-01-08') // Monday
- const result = getConstrainedWeekRange(referenceDate, null, 0)
-
- // Monday should be adjusted to Sunday when week starts on Sunday
- expect(result.start.format('YYYY-MM-DD')).toBe('2024-01-07') // Sunday
- expect(result.end.format('YYYY-MM-DD')).toBe('2024-01-13') // Saturday
- })
-
- it('should prevent weekEnd from being before weekStart', () => {
- // This test simulates the edge case where dayjs locale manipulation
- // could cause weekEnd to be calculated before weekStart
- const referenceDate = dayjs('2024-01-01') // Monday, New Year's Day
- const result = getConstrainedWeekRange(referenceDate, null, 1)
-
- expect(result.start.isSameOrBefore(result.end)).toBe(true)
- })
-
- it('should handle year boundary dates', () => {
- const referenceDate = dayjs('2023-12-31') // Sunday, New Year's Eve
- const result = getConstrainedWeekRange(referenceDate, null, 0)
-
- expect(result.start.format('YYYY-MM-DD')).toBe('2023-12-31') // Sunday
- expect(result.end.format('YYYY-MM-DD')).toBe('2024-01-06') // Saturday
- })
- })
-
- describe('date range boundary constraints', () => {
- it('should constrain start date when boundary start is within week', () => {
- const referenceDate = dayjs('2024-01-10') // Wednesday
- const dateRangeBoundary = {
- start: dayjs('2024-01-09'), // Tuesday
- end: dayjs('2024-01-20'),
- }
- const result = getConstrainedWeekRange(referenceDate, dateRangeBoundary)
-
- expect(result.start.format('YYYY-MM-DD')).toBe('2024-01-09') // Tuesday (constrained)
- expect(result.end.format('YYYY-MM-DD')).toBe('2024-01-13') // Saturday (week end)
- })
-
- it('should constrain end date when boundary end is within week', () => {
- const referenceDate = dayjs('2024-01-10') // Wednesday
- const dateRangeBoundary = {
- start: dayjs('2024-01-01'),
- end: dayjs('2024-01-12'), // Friday
- }
- const result = getConstrainedWeekRange(referenceDate, dateRangeBoundary)
-
- expect(result.start.format('YYYY-MM-DD')).toBe('2024-01-07') // Sunday (week start)
- expect(result.end.format('YYYY-MM-DD')).toBe('2024-01-12') // Friday (constrained)
- })
-
- it('should constrain both start and end when boundary is within week', () => {
- const referenceDate = dayjs('2024-01-10') // Wednesday
- const dateRangeBoundary = {
- start: dayjs('2024-01-09'), // Tuesday
- end: dayjs('2024-01-11'), // Thursday
- }
- const result = getConstrainedWeekRange(referenceDate, dateRangeBoundary)
-
- expect(result.start.format('YYYY-MM-DD')).toBe('2024-01-09') // Tuesday (constrained)
- expect(result.end.format('YYYY-MM-DD')).toBe('2024-01-11') // Thursday (constrained)
- })
-
- it('should use week boundaries when date range is outside week', () => {
- const referenceDate = dayjs('2024-01-10') // Wednesday
- const dateRangeBoundary = {
- start: dayjs('2024-01-01'),
- end: dayjs('2024-01-31'),
- }
- const result = getConstrainedWeekRange(referenceDate, dateRangeBoundary)
-
- expect(result.start.format('YYYY-MM-DD')).toBe('2024-01-07') // Sunday (week start)
- expect(result.end.format('YYYY-MM-DD')).toBe('2024-01-13') // Saturday (week end)
- })
-
- it('should handle null date range boundary', () => {
- const referenceDate = dayjs('2024-01-10') // Wednesday
- const result = getConstrainedWeekRange(referenceDate, null)
-
- expect(result.start.format('YYYY-MM-DD')).toBe('2024-01-07') // Sunday
- expect(result.end.format('YYYY-MM-DD')).toBe('2024-01-13') // Saturday
- })
-
- it('should handle undefined date range boundary', () => {
- const referenceDate = dayjs('2024-01-10') // Wednesday
- const result = getConstrainedWeekRange(referenceDate)
-
- expect(result.start.format('YYYY-MM-DD')).toBe('2024-01-07') // Sunday
- expect(result.end.format('YYYY-MM-DD')).toBe('2024-01-13') // Saturday
- })
-
- it('should handle invalid date range boundary', () => {
- const referenceDate = dayjs('2024-01-10') // Wednesday
- const dateRangeBoundary = {
- start: dayjs('invalid'),
- end: dayjs('also-invalid'),
- }
- const result = getConstrainedWeekRange(referenceDate, dateRangeBoundary)
-
- expect(result.start.format('YYYY-MM-DD')).toBe('2024-01-07') // Sunday
- expect(result.end.format('YYYY-MM-DD')).toBe('2024-01-13') // Saturday
- })
- })
-
- describe('week start day variations', () => {
- it('should handle different week start days correctly', () => {
- const referenceDate = dayjs('2024-01-10') // Wednesday
-
- // Sunday start (default)
- const sundayResult = getConstrainedWeekRange(referenceDate, null, 0)
- expect(sundayResult.start.format('YYYY-MM-DD')).toBe('2024-01-07') // Sunday
- expect(sundayResult.end.format('YYYY-MM-DD')).toBe('2024-01-13') // Saturday
-
- // Monday start
- const mondayResult = getConstrainedWeekRange(referenceDate, null, 1)
- expect(mondayResult.start.format('YYYY-MM-DD')).toBe('2024-01-08') // Monday
- expect(mondayResult.end.format('YYYY-MM-DD')).toBe('2024-01-14') // Sunday
- })
-
- it('should handle cached reference date adjustment', () => {
- // Simulate a cached Sunday reference date when week start changes to Monday
- const sundayReference = dayjs('2024-01-07') // Sunday
- const result = getConstrainedWeekRange(sundayReference, null, 1)
-
- // Should adjust Sunday to Monday
- expect(result.start.format('YYYY-MM-DD')).toBe('2024-01-08') // Monday
- expect(result.end.format('YYYY-MM-DD')).toBe('2024-01-14') // Sunday
- })
-
- it('should handle cached reference date adjustment for Monday to Sunday', () => {
- // Simulate a cached Monday reference date when week start changes to Sunday
- const mondayReference = dayjs('2024-01-08') // Monday
- const result = getConstrainedWeekRange(mondayReference, null, 0)
-
- // Should adjust Monday to Sunday
- expect(result.start.format('YYYY-MM-DD')).toBe('2024-01-07') // Sunday
- expect(result.end.format('YYYY-MM-DD')).toBe('2024-01-13') // Saturday
- })
-
- it('should handle cached reference date adjustment with out of bounds date range', () => {
- // Simulate a cached Monday reference date when week start changes to Sunday
- const mondayReference = dayjs('2025-06-02') // Monday
- const dateRangeBoundary = {
- // In the cached data, the date range is from the Monday of the week, which makes the reference within bounds if the week starts on Monday
- // But if the week starts on Sunday, it will be out of bounds (will be on the previous week)
- start: dayjs('2025-06-09'),
- end: dayjs('2025-06-11'),
- }
- const result = getConstrainedWeekRange(mondayReference, dateRangeBoundary, 0)
-
- // Should ignore the boundary and return the week starting from the previous Sunday
- expect(result.start.format('YYYY-MM-DD')).toBe('2025-06-01') // Sunday of previous week
- expect(result.end.format('YYYY-MM-DD')).toBe('2025-06-07') // Saturday of previous week
- })
- })
-
- describe('return value validation', () => {
- it('should always return valid dayjs objects', () => {
- const referenceDate = dayjs('2024-01-10')
- const result = getConstrainedWeekRange(referenceDate)
-
- expect(result.start.isValid()).toBe(true)
- expect(result.end.isValid()).toBe(true)
- })
-
- it('should ensure end is not before start', () => {
- const referenceDate = dayjs('2024-01-10')
- const result = getConstrainedWeekRange(referenceDate)
-
- expect(result.start.isSameOrBefore(result.end)).toBe(true)
- })
-
- it('should return objects with correct structure', () => {
- const referenceDate = dayjs('2024-01-10')
- const result = getConstrainedWeekRange(referenceDate)
-
- expect(result).toHaveProperty('start')
- expect(result).toHaveProperty('end')
- expect(typeof result.start.format).toBe('function')
- expect(typeof result.end.format).toBe('function')
- })
- })
-})
-
-describe('formatLocalizedDate', () => {
- const originalLanguage = Object.getOwnPropertyDescriptor(window.navigator, 'language')
- const originalLang = document.documentElement.lang
-
- afterEach(() => {
- if (originalLanguage) {
- Object.defineProperty(window.navigator, 'language', originalLanguage)
- }
- document.documentElement.lang = originalLang
- })
-
- it('should return US date format for en-US locale', () => {
- Object.defineProperty(window.navigator, 'language', { value: 'en-US', configurable: true })
- expect(formatLocalizedDate()).toBe('MMM DD')
- })
-
- it('should return US date format for en-CA locale', () => {
- Object.defineProperty(window.navigator, 'language', { value: 'en-CA', configurable: true })
- expect(formatLocalizedDate()).toBe('MMM DD')
- })
-
- it('should return international date format for en-GB locale', () => {
- Object.defineProperty(window.navigator, 'language', { value: 'en-GB', configurable: true })
- expect(formatLocalizedDate()).toBe('DD MMM')
- })
-
- it('should handle locale with region suffix', () => {
- Object.defineProperty(window.navigator, 'language', { value: 'en-US-x-custom', configurable: true })
- expect(formatLocalizedDate()).toBe('MMM DD')
- })
-
- it('should handle locale without region (defaults to international format)', () => {
- Object.defineProperty(window.navigator, 'language', { value: 'en', configurable: true })
- expect(formatLocalizedDate()).toBe('DD MMM')
- })
-
- it('should fall back to document.documentElement.lang when navigator.language is undefined', () => {
- Object.defineProperty(window.navigator, 'language', { value: undefined, configurable: true })
- document.documentElement.lang = 'en-GB'
- expect(formatLocalizedDate()).toBe('DD MMM')
- })
-})
-
-describe('alignResolvedDateRangeToInterval', () => {
- it('returns undefined when resolvedDateRange is missing', () => {
- expect(alignResolvedDateRangeToInterval(undefined, 'month')).toBeUndefined()
- expect(alignResolvedDateRangeToInterval(null, 'month')).toBeUndefined()
- })
-
- it('returns undefined when date_from is empty', () => {
- expect(
- alignResolvedDateRangeToInterval({ date_from: '', date_to: '2026-04-07T23:59:59+00:00' }, 'month')
- ).toBeUndefined()
- })
-
- it.each([['day' as const], [null], [undefined]])('returns the range unchanged when interval is %s', (interval) => {
- const range = {
- date_from: '2025-04-07T00:00:00+00:00',
- date_to: '2026-04-07T23:59:59+00:00',
- }
- expect(alignResolvedDateRangeToInterval(range, interval)).toBe(range)
- })
-
- it('expands to full months when grouping by month', () => {
- expect(
- alignResolvedDateRangeToInterval(
- {
- date_from: '2025-04-07T00:00:00+00:00',
- date_to: '2026-04-07T23:59:59+00:00',
- },
- 'month'
- )
- ).toEqual({
- date_from: '2025-04-01T00:00:00+00:00',
- date_to: '2026-04-30T23:59:59+00:00',
- })
- })
-
- it('preserves a non-UTC timezone offset', () => {
- expect(
- alignResolvedDateRangeToInterval(
- {
- date_from: '2025-04-07T00:00:00-08:00',
- date_to: '2026-04-07T23:59:59-08:00',
- },
- 'month'
- )
- ).toEqual({
- date_from: '2025-04-01T00:00:00-08:00',
- date_to: '2026-04-30T23:59:59-08:00',
- })
- })
-
- it('normalizes a Z suffix to +00:00', () => {
- expect(
- alignResolvedDateRangeToInterval(
- {
- date_from: '2025-04-07T00:00:00Z',
- date_to: '2026-04-07T23:59:59Z',
- },
- 'month'
- )
- ).toEqual({
- date_from: '2025-04-01T00:00:00+00:00',
- date_to: '2026-04-30T23:59:59+00:00',
- })
- })
-
- it('handles an ISO string with no timezone suffix', () => {
- expect(
- alignResolvedDateRangeToInterval(
- {
- date_from: '2025-04-07T00:00:00',
- date_to: '2026-04-07T23:59:59',
- },
- 'month'
- )
- ).toEqual({
- date_from: '2025-04-01T00:00:00',
- date_to: '2026-04-30T23:59:59',
- })
- })
-})
diff --git a/frontend/src/lib/utils/dateTimeUtils.test.ts b/frontend/src/lib/utils/dateTimeUtils.test.ts
deleted file mode 100644
index 984d00ec06df..000000000000
--- a/frontend/src/lib/utils/dateTimeUtils.test.ts
+++ /dev/null
@@ -1,47 +0,0 @@
-import { dayjs } from 'lib/dayjs'
-
-import { parseDateInTimezone } from './dateTimeUtils'
-
-describe('parseDateInTimezone', () => {
- describe('date-only strings', () => {
- it.each([
- ['UTC', '+00:00'],
- ['America/Los_Angeles', '-07:00'],
- ['Asia/Tokyo', '+09:00'],
- ['Europe/Berlin', '+02:00'],
- ])('treats "2026-05-05" as wall-clock midnight in project tz %s', (timezone, expectedOffset) => {
- const out = parseDateInTimezone('2026-05-05', timezone)
- expect(out.format('YYYY-MM-DD HH:mm Z')).toEqual(`2026-05-05 00:00 ${expectedOffset}`)
- })
-
- it('returns the same calendar day across browser timezones (no DST drift)', () => {
- // The chart x-axis renders this with a 'D MMM' or 'MMM D' format.
- // Across DST boundaries and across browser timezones, the calendar day
- // for a date-only string must not shift by ±1 day.
- const out = parseDateInTimezone('2026-03-08', 'America/Los_Angeles')
- expect(out.format('D MMM YYYY')).toEqual('8 Mar 2026')
- })
- })
-
- describe('strings with explicit timezone offset', () => {
- it('treats Z-suffixed timestamps as real instants and converts to project tz', () => {
- // 2024-04-28 23:30 UTC = 2024-04-29 08:30 in Tokyo.
- const out = parseDateInTimezone('2024-04-28T23:30:00Z', 'Asia/Tokyo')
- expect(out.format('YYYY-MM-DD HH:mm Z')).toEqual('2024-04-29 08:30 +09:00')
- })
-
- it('treats +HH:MM offsets as real instants', () => {
- // 2024-04-28 00:00 -07:00 = 2024-04-28 07:00 UTC = 2024-04-28 16:00 Tokyo.
- const out = parseDateInTimezone('2024-04-28T00:00:00-07:00', 'Asia/Tokyo')
- expect(out.format('YYYY-MM-DD HH:mm Z')).toEqual('2024-04-28 16:00 +09:00')
- })
- })
-
- describe('invalid inputs', () => {
- it('returns an invalid Dayjs for unparseable strings instead of throwing', () => {
- const out = parseDateInTimezone('not-a-date', 'UTC')
- expect(dayjs.isDayjs(out)).toBe(true)
- expect(out.isValid()).toBe(false)
- })
- })
-})
diff --git a/frontend/src/lib/utils/datetime.test.ts b/frontend/src/lib/utils/datetime.test.ts
new file mode 100644
index 000000000000..abb29371f6fb
--- /dev/null
+++ b/frontend/src/lib/utils/datetime.test.ts
@@ -0,0 +1,510 @@
+import tk from 'timekeeper'
+
+import { dayjs } from 'lib/dayjs'
+import {
+ alignResolvedDateRangeToInterval,
+ formatDateTimeRange,
+ formatLocalizedDate,
+ getConstrainedWeekRange,
+ getFormattedLastWeekDate,
+ parseDateInTimezone,
+} from 'lib/utils/datetime'
+
+describe('datetime utils', () => {
+ describe('getFormattedLastWeekDate()', () => {
+ it('happy case', () => {
+ tk.freeze(new Date(1330688329321))
+ expect(getFormattedLastWeekDate()).toEqual('January 13 - March 2, 2012')
+ tk.reset()
+ })
+ })
+
+ describe('formatDateTimeRange()', () => {
+ beforeEach(() => {
+ tk.freeze(new Date('2025-03-15T12:00:00.000Z'))
+ })
+ afterEach(() => {
+ tk.reset()
+ })
+
+ it('formats range in different years with full details', () => {
+ const from = dayjs('2024-12-31T14:30:45')
+ const to = dayjs('2025-01-01T16:45:30')
+ expect(formatDateTimeRange(from, to)).toEqual('December 31, 2024 14:30:45 - January 1, 2025 16:45:30')
+ })
+
+ it('formats range in same year but different days', () => {
+ const from = dayjs('2024-06-15T09:00:00')
+ const to = dayjs('2024-06-20T17:30:00')
+ expect(formatDateTimeRange(from, to)).toEqual('June 15, 2024 09:00 - June 20, 17:30')
+ })
+
+ it('hides time if both times are midnight', () => {
+ const from = dayjs('2024-06-15T00:00:00')
+ const to = dayjs('2024-06-20T00:00:00')
+ expect(formatDateTimeRange(from, to)).toEqual('June 15, 2024 - June 20')
+ })
+
+ it('formats range in same year as current year', () => {
+ const from = dayjs('2025-01-10T10:15:00')
+ const to = dayjs('2025-02-05T14:20:00')
+ expect(formatDateTimeRange(from, to)).toEqual('January 10, 10:15 - February 5, 14:20')
+ })
+
+ it('formats range on same day in different year', () => {
+ const from = dayjs('2024-08-10T09:30:00')
+ const to = dayjs('2024-08-10T18:45:00')
+ expect(formatDateTimeRange(from, to)).toEqual('August 10, 2024 09:30 - 18:45')
+ })
+
+ it('formats range on same day in current year', () => {
+ const from = dayjs('2025-03-15T08:00:00')
+ const to = dayjs('2025-03-15T20:00:00')
+ expect(formatDateTimeRange(from, to)).toEqual('08:00 - 20:00')
+ })
+
+ it('removes seconds when both times have zero seconds on same day', () => {
+ const from = dayjs('2025-03-15T10:30:00')
+ const to = dayjs('2025-03-15T14:45:00')
+ expect(formatDateTimeRange(from, to)).toEqual('10:30 - 14:45')
+ })
+
+ it('includes seconds when start time has non-zero seconds', () => {
+ const from = dayjs('2025-03-15T10:30:15')
+ const to = dayjs('2025-03-15T14:45:00')
+ expect(formatDateTimeRange(from, to)).toEqual('10:30:15 - 14:45:00')
+ })
+
+ it('includes seconds when end time has non-zero seconds', () => {
+ const from = dayjs('2025-03-15T10:30:00')
+ const to = dayjs('2025-03-15T14:45:30')
+ expect(formatDateTimeRange(from, to)).toEqual('10:30:00 - 14:45:30')
+ })
+
+ it('includes seconds when both times have non-zero seconds', () => {
+ const from = dayjs('2025-03-15T10:30:15')
+ const to = dayjs('2025-03-15T14:45:30')
+ expect(formatDateTimeRange(from, to)).toEqual('10:30:15 - 14:45:30')
+ })
+
+ it('handles range spanning different days in current year', () => {
+ const from = dayjs('2025-03-14T22:00:00')
+ const to = dayjs('2025-03-16T02:00:00')
+ expect(formatDateTimeRange(from, to)).toEqual('March 14, 22:00 - March 16, 02:00')
+ })
+
+ it('handles very short time ranges on same day', () => {
+ const from = dayjs('2025-03-15T12:00:00')
+ const to = dayjs('2025-03-15T12:01:00')
+ expect(formatDateTimeRange(from, to)).toEqual('12:00 - 12:01')
+ })
+ })
+
+ describe('getConstrainedWeekRange', () => {
+ beforeEach(() => {
+ // Reset locale to default before each test
+ dayjs.updateLocale('en', {
+ weekStart: 0,
+ })
+ })
+
+ describe('basic functionality', () => {
+ it('should return week boundaries for a mid-week date with Sunday start', () => {
+ const referenceDate = dayjs('2024-01-10') // Wednesday
+ const result = getConstrainedWeekRange(referenceDate)
+
+ expect(result.start.format('YYYY-MM-DD')).toBe('2024-01-07') // Sunday
+ expect(result.end.format('YYYY-MM-DD')).toBe('2024-01-13') // Saturday
+ })
+
+ it('should return week boundaries for a mid-week date with Monday start', () => {
+ const referenceDate = dayjs('2024-01-10') // Wednesday
+ const result = getConstrainedWeekRange(referenceDate, null, 1)
+
+ expect(result.start.format('YYYY-MM-DD')).toBe('2024-01-08') // Monday
+ expect(result.end.format('YYYY-MM-DD')).toBe('2024-01-14') // Sunday
+ })
+
+ it('should handle reference date at start of week', () => {
+ const referenceDate = dayjs('2024-01-07') // Sunday
+ const result = getConstrainedWeekRange(referenceDate, null, 0)
+
+ expect(result.start.format('YYYY-MM-DD')).toBe('2024-01-07') // Sunday
+ expect(result.end.format('YYYY-MM-DD')).toBe('2024-01-13') // Saturday
+ })
+
+ it('should handle reference date at end of week', () => {
+ const referenceDate = dayjs('2024-01-13') // Saturday
+ const result = getConstrainedWeekRange(referenceDate, null, 0)
+
+ expect(result.start.format('YYYY-MM-DD')).toBe('2024-01-07') // Sunday
+ expect(result.end.format('YYYY-MM-DD')).toBe('2024-01-13') // Saturday
+ })
+ })
+
+ describe('edge case handling', () => {
+ it('should handle Sunday reference date with Monday week start', () => {
+ const referenceDate = dayjs('2024-01-07') // Sunday
+ const result = getConstrainedWeekRange(referenceDate, null, 1)
+
+ // Sunday should be adjusted to Monday when week starts on Monday
+ expect(result.start.format('YYYY-MM-DD')).toBe('2024-01-08') // Monday
+ expect(result.end.format('YYYY-MM-DD')).toBe('2024-01-14') // Sunday
+ })
+
+ it('should handle Monday reference date with Sunday week start', () => {
+ const referenceDate = dayjs('2024-01-08') // Monday
+ const result = getConstrainedWeekRange(referenceDate, null, 0)
+
+ // Monday should be adjusted to Sunday when week starts on Sunday
+ expect(result.start.format('YYYY-MM-DD')).toBe('2024-01-07') // Sunday
+ expect(result.end.format('YYYY-MM-DD')).toBe('2024-01-13') // Saturday
+ })
+
+ it('should prevent weekEnd from being before weekStart', () => {
+ // This test simulates the edge case where dayjs locale manipulation
+ // could cause weekEnd to be calculated before weekStart
+ const referenceDate = dayjs('2024-01-01') // Monday, New Year's Day
+ const result = getConstrainedWeekRange(referenceDate, null, 1)
+
+ expect(result.start.isSameOrBefore(result.end)).toBe(true)
+ })
+
+ it('should handle year boundary dates', () => {
+ const referenceDate = dayjs('2023-12-31') // Sunday, New Year's Eve
+ const result = getConstrainedWeekRange(referenceDate, null, 0)
+
+ expect(result.start.format('YYYY-MM-DD')).toBe('2023-12-31') // Sunday
+ expect(result.end.format('YYYY-MM-DD')).toBe('2024-01-06') // Saturday
+ })
+ })
+
+ describe('date range boundary constraints', () => {
+ it('should constrain start date when boundary start is within week', () => {
+ const referenceDate = dayjs('2024-01-10') // Wednesday
+ const dateRangeBoundary = {
+ start: dayjs('2024-01-09'), // Tuesday
+ end: dayjs('2024-01-20'),
+ }
+ const result = getConstrainedWeekRange(referenceDate, dateRangeBoundary)
+
+ expect(result.start.format('YYYY-MM-DD')).toBe('2024-01-09') // Tuesday (constrained)
+ expect(result.end.format('YYYY-MM-DD')).toBe('2024-01-13') // Saturday (week end)
+ })
+
+ it('should constrain end date when boundary end is within week', () => {
+ const referenceDate = dayjs('2024-01-10') // Wednesday
+ const dateRangeBoundary = {
+ start: dayjs('2024-01-01'),
+ end: dayjs('2024-01-12'), // Friday
+ }
+ const result = getConstrainedWeekRange(referenceDate, dateRangeBoundary)
+
+ expect(result.start.format('YYYY-MM-DD')).toBe('2024-01-07') // Sunday (week start)
+ expect(result.end.format('YYYY-MM-DD')).toBe('2024-01-12') // Friday (constrained)
+ })
+
+ it('should constrain both start and end when boundary is within week', () => {
+ const referenceDate = dayjs('2024-01-10') // Wednesday
+ const dateRangeBoundary = {
+ start: dayjs('2024-01-09'), // Tuesday
+ end: dayjs('2024-01-11'), // Thursday
+ }
+ const result = getConstrainedWeekRange(referenceDate, dateRangeBoundary)
+
+ expect(result.start.format('YYYY-MM-DD')).toBe('2024-01-09') // Tuesday (constrained)
+ expect(result.end.format('YYYY-MM-DD')).toBe('2024-01-11') // Thursday (constrained)
+ })
+
+ it('should use week boundaries when date range is outside week', () => {
+ const referenceDate = dayjs('2024-01-10') // Wednesday
+ const dateRangeBoundary = {
+ start: dayjs('2024-01-01'),
+ end: dayjs('2024-01-31'),
+ }
+ const result = getConstrainedWeekRange(referenceDate, dateRangeBoundary)
+
+ expect(result.start.format('YYYY-MM-DD')).toBe('2024-01-07') // Sunday (week start)
+ expect(result.end.format('YYYY-MM-DD')).toBe('2024-01-13') // Saturday (week end)
+ })
+
+ it('should handle null date range boundary', () => {
+ const referenceDate = dayjs('2024-01-10') // Wednesday
+ const result = getConstrainedWeekRange(referenceDate, null)
+
+ expect(result.start.format('YYYY-MM-DD')).toBe('2024-01-07') // Sunday
+ expect(result.end.format('YYYY-MM-DD')).toBe('2024-01-13') // Saturday
+ })
+
+ it('should handle undefined date range boundary', () => {
+ const referenceDate = dayjs('2024-01-10') // Wednesday
+ const result = getConstrainedWeekRange(referenceDate)
+
+ expect(result.start.format('YYYY-MM-DD')).toBe('2024-01-07') // Sunday
+ expect(result.end.format('YYYY-MM-DD')).toBe('2024-01-13') // Saturday
+ })
+
+ it('should handle invalid date range boundary', () => {
+ const referenceDate = dayjs('2024-01-10') // Wednesday
+ const dateRangeBoundary = {
+ start: dayjs('invalid'),
+ end: dayjs('also-invalid'),
+ }
+ const result = getConstrainedWeekRange(referenceDate, dateRangeBoundary)
+
+ expect(result.start.format('YYYY-MM-DD')).toBe('2024-01-07') // Sunday
+ expect(result.end.format('YYYY-MM-DD')).toBe('2024-01-13') // Saturday
+ })
+ })
+
+ describe('week start day variations', () => {
+ it('should handle different week start days correctly', () => {
+ const referenceDate = dayjs('2024-01-10') // Wednesday
+
+ // Sunday start (default)
+ const sundayResult = getConstrainedWeekRange(referenceDate, null, 0)
+ expect(sundayResult.start.format('YYYY-MM-DD')).toBe('2024-01-07') // Sunday
+ expect(sundayResult.end.format('YYYY-MM-DD')).toBe('2024-01-13') // Saturday
+
+ // Monday start
+ const mondayResult = getConstrainedWeekRange(referenceDate, null, 1)
+ expect(mondayResult.start.format('YYYY-MM-DD')).toBe('2024-01-08') // Monday
+ expect(mondayResult.end.format('YYYY-MM-DD')).toBe('2024-01-14') // Sunday
+ })
+
+ it('should handle cached reference date adjustment', () => {
+ // Simulate a cached Sunday reference date when week start changes to Monday
+ const sundayReference = dayjs('2024-01-07') // Sunday
+ const result = getConstrainedWeekRange(sundayReference, null, 1)
+
+ // Should adjust Sunday to Monday
+ expect(result.start.format('YYYY-MM-DD')).toBe('2024-01-08') // Monday
+ expect(result.end.format('YYYY-MM-DD')).toBe('2024-01-14') // Sunday
+ })
+
+ it('should handle cached reference date adjustment for Monday to Sunday', () => {
+ // Simulate a cached Monday reference date when week start changes to Sunday
+ const mondayReference = dayjs('2024-01-08') // Monday
+ const result = getConstrainedWeekRange(mondayReference, null, 0)
+
+ // Should adjust Monday to Sunday
+ expect(result.start.format('YYYY-MM-DD')).toBe('2024-01-07') // Sunday
+ expect(result.end.format('YYYY-MM-DD')).toBe('2024-01-13') // Saturday
+ })
+
+ it('should handle cached reference date adjustment with out of bounds date range', () => {
+ // Simulate a cached Monday reference date when week start changes to Sunday
+ const mondayReference = dayjs('2025-06-02') // Monday
+ const dateRangeBoundary = {
+ // In the cached data, the date range is from the Monday of the week, which makes the reference within bounds if the week starts on Monday
+ // But if the week starts on Sunday, it will be out of bounds (will be on the previous week)
+ start: dayjs('2025-06-09'),
+ end: dayjs('2025-06-11'),
+ }
+ const result = getConstrainedWeekRange(mondayReference, dateRangeBoundary, 0)
+
+ // Should ignore the boundary and return the week starting from the previous Sunday
+ expect(result.start.format('YYYY-MM-DD')).toBe('2025-06-01') // Sunday of previous week
+ expect(result.end.format('YYYY-MM-DD')).toBe('2025-06-07') // Saturday of previous week
+ })
+ })
+
+ describe('return value validation', () => {
+ it('should always return valid dayjs objects', () => {
+ const referenceDate = dayjs('2024-01-10')
+ const result = getConstrainedWeekRange(referenceDate)
+
+ expect(result.start.isValid()).toBe(true)
+ expect(result.end.isValid()).toBe(true)
+ })
+
+ it('should ensure end is not before start', () => {
+ const referenceDate = dayjs('2024-01-10')
+ const result = getConstrainedWeekRange(referenceDate)
+
+ expect(result.start.isSameOrBefore(result.end)).toBe(true)
+ })
+
+ it('should return objects with correct structure', () => {
+ const referenceDate = dayjs('2024-01-10')
+ const result = getConstrainedWeekRange(referenceDate)
+
+ expect(result).toHaveProperty('start')
+ expect(result).toHaveProperty('end')
+ expect(typeof result.start.format).toBe('function')
+ expect(typeof result.end.format).toBe('function')
+ })
+ })
+ })
+
+ describe('formatLocalizedDate', () => {
+ const originalLanguage = Object.getOwnPropertyDescriptor(window.navigator, 'language')
+ const originalLang = document.documentElement.lang
+
+ afterEach(() => {
+ if (originalLanguage) {
+ Object.defineProperty(window.navigator, 'language', originalLanguage)
+ }
+ document.documentElement.lang = originalLang
+ })
+
+ it('should return US date format for en-US locale', () => {
+ Object.defineProperty(window.navigator, 'language', { value: 'en-US', configurable: true })
+ expect(formatLocalizedDate()).toBe('MMM DD')
+ })
+
+ it('should return US date format for en-CA locale', () => {
+ Object.defineProperty(window.navigator, 'language', { value: 'en-CA', configurable: true })
+ expect(formatLocalizedDate()).toBe('MMM DD')
+ })
+
+ it('should return international date format for en-GB locale', () => {
+ Object.defineProperty(window.navigator, 'language', { value: 'en-GB', configurable: true })
+ expect(formatLocalizedDate()).toBe('DD MMM')
+ })
+
+ it('should handle locale with region suffix', () => {
+ Object.defineProperty(window.navigator, 'language', { value: 'en-US-x-custom', configurable: true })
+ expect(formatLocalizedDate()).toBe('MMM DD')
+ })
+
+ it('should handle locale without region (defaults to international format)', () => {
+ Object.defineProperty(window.navigator, 'language', { value: 'en', configurable: true })
+ expect(formatLocalizedDate()).toBe('DD MMM')
+ })
+
+ it('should fall back to document.documentElement.lang when navigator.language is undefined', () => {
+ Object.defineProperty(window.navigator, 'language', { value: undefined, configurable: true })
+ document.documentElement.lang = 'en-GB'
+ expect(formatLocalizedDate()).toBe('DD MMM')
+ })
+ })
+
+ describe('alignResolvedDateRangeToInterval', () => {
+ it('returns undefined when resolvedDateRange is missing', () => {
+ expect(alignResolvedDateRangeToInterval(undefined, 'month')).toBeUndefined()
+ expect(alignResolvedDateRangeToInterval(null, 'month')).toBeUndefined()
+ })
+
+ it('returns undefined when date_from is empty', () => {
+ expect(
+ alignResolvedDateRangeToInterval({ date_from: '', date_to: '2026-04-07T23:59:59+00:00' }, 'month')
+ ).toBeUndefined()
+ })
+
+ it.each([['day' as const], [null], [undefined]])(
+ 'returns the range unchanged when interval is %s',
+ (interval) => {
+ const range = {
+ date_from: '2025-04-07T00:00:00+00:00',
+ date_to: '2026-04-07T23:59:59+00:00',
+ }
+ expect(alignResolvedDateRangeToInterval(range, interval)).toBe(range)
+ }
+ )
+
+ it('expands to full months when grouping by month', () => {
+ expect(
+ alignResolvedDateRangeToInterval(
+ {
+ date_from: '2025-04-07T00:00:00+00:00',
+ date_to: '2026-04-07T23:59:59+00:00',
+ },
+ 'month'
+ )
+ ).toEqual({
+ date_from: '2025-04-01T00:00:00+00:00',
+ date_to: '2026-04-30T23:59:59+00:00',
+ })
+ })
+
+ it('preserves a non-UTC timezone offset', () => {
+ expect(
+ alignResolvedDateRangeToInterval(
+ {
+ date_from: '2025-04-07T00:00:00-08:00',
+ date_to: '2026-04-07T23:59:59-08:00',
+ },
+ 'month'
+ )
+ ).toEqual({
+ date_from: '2025-04-01T00:00:00-08:00',
+ date_to: '2026-04-30T23:59:59-08:00',
+ })
+ })
+
+ it('normalizes a Z suffix to +00:00', () => {
+ expect(
+ alignResolvedDateRangeToInterval(
+ {
+ date_from: '2025-04-07T00:00:00Z',
+ date_to: '2026-04-07T23:59:59Z',
+ },
+ 'month'
+ )
+ ).toEqual({
+ date_from: '2025-04-01T00:00:00+00:00',
+ date_to: '2026-04-30T23:59:59+00:00',
+ })
+ })
+
+ it('handles an ISO string with no timezone suffix', () => {
+ expect(
+ alignResolvedDateRangeToInterval(
+ {
+ date_from: '2025-04-07T00:00:00',
+ date_to: '2026-04-07T23:59:59',
+ },
+ 'month'
+ )
+ ).toEqual({
+ date_from: '2025-04-01T00:00:00',
+ date_to: '2026-04-30T23:59:59',
+ })
+ })
+ })
+
+ describe('parseDateInTimezone', () => {
+ describe('date-only strings', () => {
+ it.each([
+ ['UTC', '+00:00'],
+ ['America/Los_Angeles', '-07:00'],
+ ['Asia/Tokyo', '+09:00'],
+ ['Europe/Berlin', '+02:00'],
+ ])('treats "2026-05-05" as wall-clock midnight in project tz %s', (timezone, expectedOffset) => {
+ const out = parseDateInTimezone('2026-05-05', timezone)
+ expect(out.format('YYYY-MM-DD HH:mm Z')).toEqual(`2026-05-05 00:00 ${expectedOffset}`)
+ })
+
+ it('returns the same calendar day across browser timezones (no DST drift)', () => {
+ // The chart x-axis renders this with a 'D MMM' or 'MMM D' format.
+ // Across DST boundaries and across browser timezones, the calendar day
+ // for a date-only string must not shift by ±1 day.
+ const out = parseDateInTimezone('2026-03-08', 'America/Los_Angeles')
+ expect(out.format('D MMM YYYY')).toEqual('8 Mar 2026')
+ })
+ })
+
+ describe('strings with explicit timezone offset', () => {
+ it('treats Z-suffixed timestamps as real instants and converts to project tz', () => {
+ // 2024-04-28 23:30 UTC = 2024-04-29 08:30 in Tokyo.
+ const out = parseDateInTimezone('2024-04-28T23:30:00Z', 'Asia/Tokyo')
+ expect(out.format('YYYY-MM-DD HH:mm Z')).toEqual('2024-04-29 08:30 +09:00')
+ })
+
+ it('treats +HH:MM offsets as real instants', () => {
+ // 2024-04-28 00:00 -07:00 = 2024-04-28 07:00 UTC = 2024-04-28 16:00 Tokyo.
+ const out = parseDateInTimezone('2024-04-28T00:00:00-07:00', 'Asia/Tokyo')
+ expect(out.format('YYYY-MM-DD HH:mm Z')).toEqual('2024-04-28 16:00 +09:00')
+ })
+ })
+
+ describe('invalid inputs', () => {
+ it('returns an invalid Dayjs for unparseable strings instead of throwing', () => {
+ const out = parseDateInTimezone('not-a-date', 'UTC')
+ expect(dayjs.isDayjs(out)).toBe(true)
+ expect(out.isValid()).toBe(false)
+ })
+ })
+ })
+})
diff --git a/frontend/src/lib/utils/dateTimeUtils.ts b/frontend/src/lib/utils/datetime.ts
similarity index 50%
rename from frontend/src/lib/utils/dateTimeUtils.ts
rename to frontend/src/lib/utils/datetime.ts
index 6874bc289224..394a37a02a43 100644
--- a/frontend/src/lib/utils/dateTimeUtils.ts
+++ b/frontend/src/lib/utils/datetime.ts
@@ -3,6 +3,151 @@ import { dayjs } from 'lib/dayjs'
import { ResolvedDateRangeResponse } from '~/queries/schema/schema-general'
import { IntervalType } from '~/types'
+export function humanFriendlyDetailedTime(
+ date: dayjs.Dayjs | string | null | undefined,
+ formatDate = 'MMMM DD, YYYY',
+ formatTime = 'h:mm:ss A',
+ options: { timestampStyle?: 'relative' | 'absolute' } = { timestampStyle: 'relative' }
+): string {
+ if (!date) {
+ return 'Never'
+ }
+ const parsedDate = dayjs(date)
+
+ if (options.timestampStyle === 'absolute') {
+ return parsedDate.format(`${formatDate} ${formatTime}`)
+ }
+
+ const today = dayjs().startOf('day')
+ const yesterday = today.clone().subtract(1, 'days').startOf('day')
+ if (parsedDate.isSame(dayjs(), 'm')) {
+ return 'Just now'
+ }
+ let formatString: string
+ if (parsedDate.isSame(today, 'd')) {
+ formatString = `[Today] ${formatTime}`
+ } else if (parsedDate.isSame(yesterday, 'd')) {
+ formatString = `[Yesterday] ${formatTime}`
+ } else {
+ formatString = `${formatDate} ${formatTime}`
+ }
+ return parsedDate.format(formatString)
+}
+
+export function detailedTime(date: dayjs.Dayjs | string | null | undefined): string {
+ if (!date) {
+ return ''
+ }
+ return dayjs(date).format('MMMM DD, YYYY h:mm:ss A')
+}
+
+export function determineDifferenceType(
+ firstDate: dayjs.Dayjs | string,
+ secondDate: dayjs.Dayjs | string
+): 'year' | 'month' | 'week' | 'day' | 'hour' | 'minute' | 'second' {
+ const first = dayjs(firstDate)
+ const second = dayjs(secondDate)
+ if (first.diff(second, 'years') !== 0) {
+ return 'year'
+ } else if (first.diff(second, 'months') !== 0) {
+ return 'month'
+ } else if (first.diff(second, 'weeks') !== 0) {
+ return 'week'
+ } else if (first.diff(second, 'days') !== 0) {
+ return 'day'
+ } else if (first.diff(second, 'hours') !== 0) {
+ return 'hour'
+ }
+ return 'minute'
+}
+
+export const DATE_FORMAT = 'MMMM D, YYYY'
+
+export const DATE_TIME_FORMAT = 'MMMM D, YYYY HH:mm:ss'
+
+export const DATE_FORMAT_WITHOUT_YEAR = 'MMMM D'
+
+export const DATE_FORMAT_WITHOUT_DAY = 'HH:mm:ss'
+
+export const formatDate = (date: dayjs.Dayjs, format?: string): string => {
+ return date.format(format ?? DATE_FORMAT)
+}
+
+export const formatDateTime = (date: dayjs.Dayjs, format?: string): string => {
+ return date.format(format ?? DATE_TIME_FORMAT)
+}
+
+export const formatDateRange = (dateFrom: dayjs.Dayjs, dateTo: dayjs.Dayjs, format?: string): string => {
+ let formatFrom = format ?? DATE_FORMAT
+ const formatTo = format ?? DATE_FORMAT
+ if ((!format || format === DATE_FORMAT) && dateFrom.year() === dateTo.year()) {
+ formatFrom = DATE_FORMAT_WITHOUT_YEAR
+ }
+ return `${dateFrom.format(formatFrom)} - ${dateTo.format(formatTo)}`
+}
+
+export const formatDateTimeRange = (dateFrom: dayjs.Dayjs, dateTo: dayjs.Dayjs): string => {
+ const MONTHDAY = 'MMMM D'
+ const COMMA = ', '
+ const YEAR = 'YYYY '
+ const TIME = 'HH:mm'
+ const SECONDS = ':ss'
+
+ let fromComponents = [MONTHDAY, COMMA, YEAR, TIME, SECONDS]
+ let toComponents = [MONTHDAY, COMMA, YEAR, TIME, SECONDS]
+ if (dateFrom.year() === dateTo.year()) {
+ toComponents = toComponents.filter((x) => x !== YEAR)
+ if (dateTo.year() === dayjs().year()) {
+ fromComponents = fromComponents.filter((x) => x !== YEAR)
+ }
+
+ if (dateFrom.isSame(dateTo, 'day')) {
+ toComponents = toComponents.filter((x) => x !== MONTHDAY)
+ toComponents = toComponents.filter((x) => x !== COMMA)
+ if (dateFrom.isSame(dayjs(), 'day')) {
+ fromComponents = fromComponents.filter((x) => x !== MONTHDAY)
+ fromComponents = fromComponents.filter((x) => x !== COMMA)
+ }
+ }
+
+ if (dateFrom.isSame(dayjs(dateFrom).startOf('day')) && dateTo.isSame(dayjs(dateTo).startOf('day'))) {
+ fromComponents = fromComponents.filter((x) => x !== TIME)
+ toComponents = toComponents.filter((x) => x !== TIME)
+ }
+
+ if (dateFrom.second() === 0 && dateTo.second() === 0) {
+ fromComponents = fromComponents.filter((x) => x !== SECONDS)
+ toComponents = toComponents.filter((x) => x !== SECONDS)
+ }
+
+ if (!fromComponents.includes(YEAR) && !fromComponents.includes(TIME)) {
+ fromComponents = fromComponents.filter((x) => x !== COMMA)
+ }
+
+ if (!toComponents.includes(YEAR) && !toComponents.includes(TIME)) {
+ toComponents = toComponents.filter((x) => x !== COMMA)
+ }
+ }
+ return `${dateFrom.format(fromComponents.join(''))} - ${dateTo.format(toComponents.join(''))}`
+}
+
+export const isDate = /([0-9]{4}-[0-9]{2}-[0-9]{2})/
+
+export function getFormattedLastWeekDate(lastDay: dayjs.Dayjs = dayjs()): string {
+ return formatDateRange(lastDay.subtract(7, 'week'), lastDay.endOf('d'))
+}
+
+// Compute the ISO week string for a given date
+// Useful above to show the toast once per week
+export function getISOWeekString(date = new Date()): string {
+ const dayjs_date = dayjs(date)
+
+ const year = dayjs_date.year()
+ const week = dayjs_date.week()
+
+ return `${year}-W${week}`
+}
+
export interface DayJSDateRange {
start: dayjs.Dayjs
end: dayjs.Dayjs
@@ -94,7 +239,7 @@ export function formatResolvedDateRange(
return
}
- const formatDate = (iso: string): { dateTime: string; tz: string } => {
+ const formatIsoParts = (iso: string): { dateTime: string; tz: string } => {
// YYYY-MM-DD HH:mm
const dateTime = iso.slice(0, 16).replace('T', ' ')
// timezone (+00:00, -08:00, +08:00)
@@ -102,8 +247,8 @@ export function formatResolvedDateRange(
return { dateTime, tz }
}
- const from = formatDate(resolvedDateRange.date_from)
- const to = formatDate(resolvedDateRange.date_to)
+ const from = formatIsoParts(resolvedDateRange.date_from)
+ const to = formatIsoParts(resolvedDateRange.date_to)
return `${from.dateTime} - ${to.dateTime} (${from.tz})`
}
diff --git a/frontend/src/lib/utils/dom.ts b/frontend/src/lib/utils/dom.ts
new file mode 100644
index 000000000000..707a9802d670
--- /dev/null
+++ b/frontend/src/lib/utils/dom.ts
@@ -0,0 +1,131 @@
+import { CSSProperties } from 'react'
+
+export function uuid(): string {
+ return '10000000-1000-4000-8000-100000000000'.replace(/[018]/g, (c) =>
+ (
+ parseInt(c) ^
+ ((typeof window?.crypto !== 'undefined' // in node tests, jsdom doesn't implement window.crypto
+ ? window.crypto.getRandomValues(new Uint8Array(1))[0]
+ : Math.floor(Math.random() * 256)) &
+ (15 >> (parseInt(c) / 4)))
+ ).toString(16)
+ )
+}
+
+export const selectStyle: Record<string, (base: Partial<CSSProperties>) => Partial<CSSProperties>> = {
+ control: (base) => ({
+ ...base,
+ height: 31,
+ minHeight: 31,
+ }),
+ indicatorsContainer: (base) => ({
+ ...base,
+ height: 31,
+ }),
+ input: (base) => ({
+ ...base,
+ paddingBottom: 0,
+ paddingTop: 0,
+ margin: 0,
+ opacity: 1,
+ }),
+ valueContainer: (base) => ({
+ ...base,
+ padding: '0 8px',
+ marginTop: -2,
+ }),
+ option: (base) => ({
+ ...base,
+ padding: '2px 15px',
+ }),
+}
+
+export function clearDOMTextSelection(): void {
+ if (window.getSelection) {
+ if (window.getSelection()?.empty) {
+ // Chrome
+ window.getSelection()?.empty()
+ } else if (window.getSelection()?.removeAllRanges) {
+ // Firefox
+ window.getSelection()?.removeAllRanges()
+ }
+ } else if ((document as any).selection) {
+ // IE?
+ ;(document as any).selection.empty()
+ }
+}
+
+export function isMobile(): boolean {
+ return navigator.userAgent.includes('Mobile')
+}
+
+export function isMac(): boolean {
+ return navigator.platform.includes('Mac')
+}
+
+export function platformCommandControlKey(modifier: string): string {
+ return `${isMac() ? '⌘' : 'Ctrl + '}${modifier}`
+}
+
+export function someParentMatchesSelector(element: HTMLElement, selector: string): boolean {
+ if (element.matches(selector)) {
+ return true
+ }
+ return element.parentElement ? someParentMatchesSelector(element.parentElement, selector) : false
+}
+
+export function downloadFile(file: File): void {
+ // Create a link and set the URL using `createObjectURL`
+ const link = document.createElement('a')
+ link.style.display = 'none'
+ link.href = URL.createObjectURL(file)
+ link.download = file.name
+
+ // It needs to be added to the DOM so it can be clicked
+ document.body.appendChild(link)
+ link.click()
+
+ // To make this work on Firefox we need to wait
+ // a little while before removing it.
+ setTimeout(() => {
+ URL.revokeObjectURL(link.href)
+ link?.parentNode?.removeChild(link)
+ }, 0)
+}
+
+export function inStorybookTestRunner(): boolean {
+ return navigator.userAgent.includes('StorybookTestRunner')
+}
+
+export function inStorybook(): boolean {
+ return '__STORYBOOK_CLIENT_API__' in window
+}
+
+export const shouldIgnoreInput = (e: KeyboardEvent): boolean => {
+ return (
+ ['input', 'textarea'].includes((e.target as HTMLElement).tagName.toLowerCase()) ||
+ (e.target as HTMLElement).isContentEditable ||
+ (e.target as HTMLElement).parentElement?.isContentEditable ||
+ false
+ )
+}
+
+/**
+ * Uses the non-standard `memory` extension available in Chromium based browsers to
+ * get JS heap metrics.
+ */
+export const getJSHeapMemory = (): {
+ js_heap_used_mb?: number
+ js_heap_total_mb?: number
+ js_heap_limit_mb?: number
+} => {
+ if ('memory' in window.performance) {
+ const memory = (window.performance as any).memory
+ return {
+ js_heap_used_mb: +(memory.usedJSHeapSize / 1024 / 1024).toFixed(2),
+ js_heap_total_mb: +(memory.totalJSHeapSize / 1024 / 1024).toFixed(2),
+ js_heap_limit_mb: +(memory.jsHeapSizeLimit / 1024 / 1024).toFixed(2),
+ }
+ }
+ return {}
+}
diff --git a/frontend/src/lib/utils/durations.test.ts b/frontend/src/lib/utils/durations.test.ts
new file mode 100644
index 000000000000..422617d9d3bd
--- /dev/null
+++ b/frontend/src/lib/utils/durations.test.ts
@@ -0,0 +1,172 @@
+import {
+ calculateDays,
+ ceilMsToClosestSecond,
+ colonDelimitedDuration,
+ floorMsToClosestSecond,
+ humanFriendlyDuration,
+ reverseColonDelimitedDuration,
+} from 'lib/utils/durations'
+
+import { TimeUnitType } from '~/types'
+
+describe('durations utils', () => {
+ describe('humanFriendlyDuration()', () => {
+ it('returns correct value for 0 <= t < 1', () => {
+ expect(humanFriendlyDuration(0)).toEqual('0s')
+ expect(humanFriendlyDuration(0.001)).toEqual('1ms')
+ expect(humanFriendlyDuration(0.02)).toEqual('20ms')
+ expect(humanFriendlyDuration(0.3)).toEqual('300ms')
+ expect(humanFriendlyDuration(0.999)).toEqual('999ms')
+ })
+
+ it('returns correct value for 1 < t <= 60', () => {
+ expect(humanFriendlyDuration(60)).toEqual('1m')
+ expect(humanFriendlyDuration(45)).toEqual('45s')
+ expect(humanFriendlyDuration(44.8)).toEqual('45s')
+ expect(humanFriendlyDuration(45.2)).toEqual('45s')
+ expect(humanFriendlyDuration(45.2, { secondsFixed: 1 })).toEqual('45.2s')
+ expect(humanFriendlyDuration(1.23)).toEqual('1s')
+ expect(humanFriendlyDuration(1.23, { secondsPrecision: 3 })).toEqual('1.23s')
+ expect(humanFriendlyDuration(1, { secondsPrecision: 3 })).toEqual('1s')
+ expect(humanFriendlyDuration(1, { secondsFixed: 1 })).toEqual('1s')
+ expect(humanFriendlyDuration(1)).toEqual('1s')
+ })
+ it('returns correct value for 60 < t < 120', () => {
+ expect(humanFriendlyDuration(119.6)).toEqual('1m 59s')
+ expect(humanFriendlyDuration(90)).toEqual('1m 30s')
+ })
+ it('returns correct value for t > 120', () => {
+ expect(humanFriendlyDuration(360)).toEqual('6m')
+ })
+ it('returns correct value for t >= 3600', () => {
+ expect(humanFriendlyDuration(3600)).toEqual('1h')
+ expect(humanFriendlyDuration(3601)).toEqual('1h 1s')
+ expect(humanFriendlyDuration(3961)).toEqual('1h 6m 1s')
+ expect(humanFriendlyDuration(3961.333)).toEqual('1h 6m 1s')
+ expect(humanFriendlyDuration(3961.666)).toEqual('1h 6m 1s')
+ })
+ it('returns correct value for t >= 86400', () => {
+ expect(humanFriendlyDuration(86400)).toEqual('1d')
+ expect(humanFriendlyDuration(86400.12)).toEqual('1d')
+ })
+ it('truncates to specified # of units', () => {
+ expect(humanFriendlyDuration(3961, { maxUnits: 2 })).toEqual('1h 6m')
+ expect(humanFriendlyDuration(30, { maxUnits: 2 })).toEqual('30s') // no change
+ expect(humanFriendlyDuration(30, { maxUnits: 0 })).toEqual('') // returns no units (useless)
+ })
+ it('returns an empty string for nullish inputs', () => {
+ expect(humanFriendlyDuration('', { maxUnits: 2 })).toEqual('')
+ expect(humanFriendlyDuration(null, { maxUnits: 2 })).toEqual('')
+ })
+ })
+
+ describe('colonDelimitedDuration()', () => {
+ it('returns correct value for <= 60', () => {
+ expect(colonDelimitedDuration(59.9)).toEqual('00:00:59')
+ expect(colonDelimitedDuration(60)).toEqual('00:01:00')
+ expect(colonDelimitedDuration(45)).toEqual('00:00:45')
+ })
+ it('returns correct value for 60 < t < 120', () => {
+ expect(colonDelimitedDuration(90)).toEqual('00:01:30')
+ })
+ it('returns correct value for t > 120', () => {
+ expect(colonDelimitedDuration(360)).toEqual('00:06:00')
+ expect(colonDelimitedDuration(360.3233)).toEqual('00:06:00')
+ expect(colonDelimitedDuration(360.782)).toEqual('00:06:00')
+ })
+ it('returns correct value for t >= 3600', () => {
+ expect(colonDelimitedDuration(3600)).toEqual('01:00:00')
+ expect(colonDelimitedDuration(3601)).toEqual('01:00:01')
+ expect(colonDelimitedDuration(3961)).toEqual('01:06:01')
+ })
+ it('returns correct value for t >= 86400', () => {
+ expect(colonDelimitedDuration(86400)).toEqual('24:00:00')
+ expect(colonDelimitedDuration(90000)).toEqual('25:00:00')
+ })
+ it('returns correct value for numUnits < 3', () => {
+ expect(colonDelimitedDuration(86400, 2)).toEqual('1440:00')
+ expect(colonDelimitedDuration(86400, 1)).toEqual('86400')
+ })
+ it('returns correct value for numUnits >= 4', () => {
+ expect(colonDelimitedDuration(86400, 4)).toEqual('01:00:00:00')
+ expect(colonDelimitedDuration(90000, 4)).toEqual('01:01:00:00')
+ expect(colonDelimitedDuration(90061, 4)).toEqual('01:01:01:01')
+ expect(colonDelimitedDuration(604800, 5)).toEqual('01:00:00:00:00')
+ expect(colonDelimitedDuration(604800, 6)).toEqual('01:00:00:00:00')
+ expect(colonDelimitedDuration(604800.222, 5)).toEqual('01:00:00:00:00')
+ expect(colonDelimitedDuration(604800.999, 6)).toEqual('01:00:00:00:00')
+ })
+ it('returns the smallest possible for numUnits = null', () => {
+ expect(colonDelimitedDuration(59, null)).toEqual('00:59')
+ expect(colonDelimitedDuration(3599, null)).toEqual('59:59')
+ expect(colonDelimitedDuration(3600, null)).toEqual('01:00:00')
+ })
+ it('returns an empty string for nullish inputs', () => {
+ expect(colonDelimitedDuration('')).toEqual('')
+ expect(colonDelimitedDuration(null)).toEqual('')
+ expect(colonDelimitedDuration(undefined)).toEqual('')
+ })
+ })
+
+ describe('reverseColonDelimitedDuration()', () => {
+ it('returns correct value', () => {
+ expect(reverseColonDelimitedDuration('59')).toEqual(59)
+ expect(reverseColonDelimitedDuration('59:59')).toEqual(3599)
+ expect(reverseColonDelimitedDuration('23:59:59')).toEqual(86399)
+ })
+ it('returns an null for bad values', () => {
+ expect(reverseColonDelimitedDuration('1232123')).toEqual(null)
+ expect(reverseColonDelimitedDuration('AA:AA:AA')).toEqual(null)
+ expect(reverseColonDelimitedDuration(undefined)).toEqual(null)
+ })
+ })
+
+ describe('{floor|ceil}MsToClosestSecond()', () => {
+ describe('ceil', () => {
+ it('handles ms as expected', () => {
+ expect(ceilMsToClosestSecond(10532)).toEqual(11000)
+ expect(ceilMsToClosestSecond(1500)).toEqual(2000)
+ expect(ceilMsToClosestSecond(500)).toEqual(1000)
+ expect(ceilMsToClosestSecond(-10532)).toEqual(-10000)
+ expect(ceilMsToClosestSecond(-1500)).toEqual(-1000)
+ expect(ceilMsToClosestSecond(-500)).toEqual(-0)
+ })
+ it('handles whole seconds as expected', () => {
+ expect(ceilMsToClosestSecond(0)).toEqual(0)
+ expect(ceilMsToClosestSecond(1000)).toEqual(1000)
+ expect(ceilMsToClosestSecond(-1000)).toEqual(-1000)
+ })
+ })
+
+ describe('floor', () => {
+ it('handles ms as expected', () => {
+ expect(floorMsToClosestSecond(10532)).toEqual(10000)
+ expect(floorMsToClosestSecond(1500)).toEqual(1000)
+ expect(floorMsToClosestSecond(500)).toEqual(0)
+ expect(floorMsToClosestSecond(-10532)).toEqual(-11000)
+ expect(floorMsToClosestSecond(-1500)).toEqual(-2000)
+ expect(floorMsToClosestSecond(-500)).toEqual(-1000)
+ })
+ it('handles whole seconds as expected', () => {
+ expect(floorMsToClosestSecond(0)).toEqual(0)
+ expect(floorMsToClosestSecond(1000)).toEqual(1000)
+ expect(floorMsToClosestSecond(-1000)).toEqual(-1000)
+ })
+ })
+ })
+
+ describe('calculateDays', () => {
+ it('1 day to 1 day', () => {
+ expect(calculateDays(1, TimeUnitType.Day)).toEqual(1)
+ })
+ it('1 week to 7 days', () => {
+ expect(calculateDays(1, TimeUnitType.Week)).toEqual(7)
+ })
+ it('1 month to 30 days', () => {
+ expect(calculateDays(1, TimeUnitType.Month)).toEqual(30)
+ })
+ it('1 year to 365 days', () => {
+ expect(calculateDays(1, TimeUnitType.Year)).toEqual(365)
+ })
+ })
+})
diff --git a/frontend/src/lib/utils/durations.ts b/frontend/src/lib/utils/durations.ts
new file mode 100644
index 000000000000..2f5b314886eb
--- /dev/null
+++ b/frontend/src/lib/utils/durations.ts
@@ -0,0 +1,161 @@
+import { dayjs } from 'lib/dayjs'
+import { zeroPad } from 'lib/utils/numbers'
+
+import { TimeUnitType } from '~/types'
+
+export const humanFriendlyMilliseconds = (timestamp: number | undefined): string | undefined => {
+ if (typeof timestamp !== 'number') {
+ return undefined
+ }
+
+ if (timestamp < 1000) {
+ return `${Math.ceil(timestamp)}ms`
+ }
+
+ return `${(timestamp / 1000).toFixed(2)}s`
+}
+
+export function humanFriendlyDuration(
+ d: string | number | null | undefined,
+ {
+ maxUnits,
+ secondsPrecision,
+ secondsFixed,
+ }: { maxUnits?: number; secondsPrecision?: number; secondsFixed?: number } = {}
+): string {
+ // Convert `d` (seconds) to a human-readable duration string.
+ // Example: `1d 10hrs 9mins 8s`
+ if (d === '' || d === null || d === undefined || maxUnits === 0) {
+ return ''
+ }
+ d = Number(d)
+ if (d < 0) {
+ return `-${humanFriendlyDuration(-d)}`
+ }
+ if (d === 0) {
+ return `0s`
+ }
+ if (d < 1) {
+ return `${Math.round(d * 1000)}ms`
+ }
+ if (d < 60) {
+ if (secondsPrecision != null) {
+ return `${parseFloat(d.toPrecision(secondsPrecision))}s` // round to s.f. then throw away trailing zeroes
+ }
+ return `${parseFloat(d.toFixed(secondsFixed ?? 0))}s` // round to fixed point then throw away trailing zeroes
+ }
+
+ const days = Math.floor(d / 86400)
+ const h = Math.floor((d % 86400) / 3600)
+ const m = Math.floor((d % 3600) / 60)
+ const s = Math.floor((d % 3600) % 60)
+
+ const dayDisplay = days > 0 ? days + 'd' : ''
+ const hDisplay = h > 0 ? h + 'h' : ''
+ const mDisplay = m > 0 ? m + 'm' : ''
+ const sDisplay = s > 0 ? s + 's' : hDisplay || mDisplay ? '' : '0s'
+
+ let units: string[] = []
+ if (days > 0) {
+ units = [dayDisplay, hDisplay].filter(Boolean)
+ } else {
+ units = [hDisplay, mDisplay, sDisplay].filter(Boolean)
+ }
+ return units.slice(0, maxUnits ?? undefined).join(' ')
+}
+
+export function humanFriendlyDiff(from: dayjs.Dayjs | string, to: dayjs.Dayjs | string): string {
+ const diff = dayjs(to).diff(dayjs(from), 'seconds')
+ return humanFriendlyDuration(diff)
+}
+
+export function colonDelimitedDuration(d: string | number | null | undefined, fixedUnits: number | null = 3): string {
+ // Convert `d` (seconds) to a colon delimited duration. includes `numUnits` no. of units starting from right
+ // Example: `01:10:09:08 = 1d 10hrs 9mins 8s`
+ if (d === '' || d === null || d === undefined) {
+ return ''
+ }
+ d = Number(d)
+
+ let s = d
+ let weeks = 0,
+ days = 0,
+ h = 0,
+ m = 0
+
+ weeks = !fixedUnits || fixedUnits > 4 ? Math.floor(s / 604800) : 0
+ s -= weeks * 604800
+
+ days = !fixedUnits || fixedUnits > 3 ? Math.floor(s / 86400) : 0
+ s -= days * 86400
+
+ h = !fixedUnits || fixedUnits > 2 ? Math.floor(s / 3600) : 0
+ s -= h * 3600
+
+ m = !fixedUnits || fixedUnits > 1 ? Math.floor(s / 60) : 0
+ s -= m * 60
+
+ s = Math.floor(s)
+
+ let stopTrimming = false
+ const units: string[] = []
+
+ ;[weeks, days, h, m, s].forEach((unit, i) => {
+ if (!fixedUnits && !unit && !stopTrimming && i < 3) {
+ return
+ }
+ units.push(zeroPad(unit, 2))
+ stopTrimming = true
+ })
+
+ if (fixedUnits) {
+ return units.slice(-fixedUnits).join(':')
+ }
+
+ return units.join(':')
+}
+
+export function reverseColonDelimitedDuration(duration?: string | null): number | null {
+ if (!duration) {
+ return null
+ }
+
+ if (!/^(\d\d?:)*(\d\d?)$/.test(duration)) {
+ return null
+ }
+
+ let seconds = 0
+ const units = duration
+ .split(':')
+ .map((unit) => Number(unit))
+ .reverse()
+
+ ;[1, 60, 3600, 86400, 604800].forEach((unit, index) => {
+ if (units[index]) {
+ seconds += units[index] * unit
+ }
+ })
+
+ return seconds
+}
+
+export function floorMsToClosestSecond(ms: number): number {
+ return Math.floor(ms / 1000) * 1000
+}
+
+export function ceilMsToClosestSecond(ms: number): number {
+ return Math.ceil(ms / 1000) * 1000
+}
+
+export function calculateDays(timeValue: number, timeUnit: TimeUnitType): number {
+ if (timeUnit === TimeUnitType.Year) {
+ return timeValue * 365
+ }
+ if (timeUnit === TimeUnitType.Month) {
+ return timeValue * 30
+ }
+ if (timeUnit === TimeUnitType.Week) {
+ return timeValue * 7
+ }
+ return timeValue
+}
diff --git a/frontend/src/lib/utils/eventUsageLogic.ts b/frontend/src/lib/utils/eventUsageLogic.ts
index e40c54848cc6..7908a182cb29 100644
--- a/frontend/src/lib/utils/eventUsageLogic.ts
+++ b/frontend/src/lib/utils/eventUsageLogic.ts
@@ -5,7 +5,7 @@ import { TaxonomicFilterGroupType } from 'lib/components/TaxonomicFilter/types'
import type { Dayjs } from 'lib/dayjs'
import { now } from 'lib/dayjs'
import { TimeToSeeDataPayload } from 'lib/internalMetrics'
-import { objectClean } from 'lib/utils'
+import { objectClean } from 'lib/utils/objects'
import { BillingUsageInteractionProps } from 'scenes/billing/types'
import { SharedMetric } from 'scenes/experiments/SharedMetrics/sharedMetricLogic'
import { preflightLogic } from 'scenes/PreflightCheck/preflightLogic'
diff --git a/frontend/src/lib/utils/events.test.ts b/frontend/src/lib/utils/events.test.ts
new file mode 100644
index 000000000000..6cf252420040
--- /dev/null
+++ b/frontend/src/lib/utils/events.test.ts
@@ -0,0 +1,312 @@
+import {
+ autoCaptureEventToDescription,
+ eventToDescription,
+ getEventsWithPrimaryProperty,
+ getPrimaryPropertyForEvent,
+ hasTaxonomyPrimaryProperty,
+} from 'lib/utils/events'
+
+import { ElementType, EventType } from '~/types'
+
+describe('events utils', () => {
+ describe('eventToName()', () => {
+ const baseEvent = {
+ elements: [],
+ event: '',
+ properties: {},
+ person: {},
+ } as any as EventType
+
+ it('handles page events as expected', () => {
+ expect(
+ eventToDescription({ ...baseEvent, event: '$pageview', properties: { $pathname: '/hello' } })
+ ).toEqual('/hello')
+ expect(
+ eventToDescription({ ...baseEvent, event: '$pageleave', properties: { $pathname: '/bye' } })
+ ).toEqual('/bye')
+ })
+
+ it('handles screen events using $screen_name', () => {
+ expect(
+ eventToDescription({ ...baseEvent, event: '$screen', properties: { $screen_name: 'CartScreen' } })
+ ).toEqual('CartScreen')
+ })
+
+ it('falls back to event name when the primary property is missing', () => {
+ // Old behaviour fell back to $current_url for $pageview without $pathname; the new
+ // single-property contract returns the event name instead so the change is explicit
+ // and consistent with $screen / $feature_flag_called.
+ expect(
+ eventToDescription({
+ ...baseEvent,
+ event: '$pageview',
+ properties: { $current_url: 'https://example.com/' },
+ })
+ ).toEqual('$pageview')
+ })
+
+ it('handles no text autocapture as expected', () => {
+ expect(
+ eventToDescription({
+ ...baseEvent,
+ event: '$autocapture',
+ properties: { $event_type: 'click' },
+ })
+ ).toEqual('clicked element')
+ })
+
+ it('handles long form autocapture as expected', () => {
+ expect(
+ eventToDescription({
+ ...baseEvent,
+ event: '$autocapture',
+ properties: { $event_type: 'click' },
+ elements: [{ tag_name: 'button', text: 'hello' } as ElementType],
+ })
+ ).toEqual('clicked button with text "hello"')
+ })
+
+ it('handles short form autocapture as expected', () => {
+ expect(
+ eventToDescription(
+ {
+ ...baseEvent,
+ event: '$autocapture',
+ properties: { $event_type: 'click' },
+ elements: [{ tag_name: 'button', text: 'hello' } as ElementType],
+ },
+ true
+ )
+ ).toEqual('clicked "hello"')
+ })
+
+ it.each([
+ ['with a flag key', { $feature_flag: 'my-flag-key' }, 'my-flag-key'],
+ ['without the flag key property', {}, '$feature_flag_called'],
+ ])('handles feature flag called events %s', (_, properties, expected) => {
+ expect(
+ eventToDescription({
+ ...baseEvent,
+ event: '$feature_flag_called',
+ properties,
+ })
+ ).toEqual(expected)
+ })
+
+ it('handles unknown event/action', () => {
+ expect(
+ eventToDescription({
+ ...baseEvent,
+ event: 'custom event/action',
+ })
+ ).toEqual('custom event/action')
+ })
+ })
+
+ describe('autoCaptureEventToDescription()', () => {
+ const baseEvent = {
+ elements: [],
+ event: '$autocapture',
+ properties: { $event_type: 'click' },
+ person: {},
+ } as any as EventType
+
+ it('handles regular text by adding quotes', () => {
+ expect(
+ autoCaptureEventToDescription({
+ ...baseEvent,
+ properties: {
+ ...baseEvent.properties,
+ $el_text: 'Analyzing Characters with',
+ },
+ })
+ ).toEqual('clicked element with text "Analyzing Characters with"')
+ })
+
+ it('prioritizes $el_text from properties over text in elements array', () => {
+ expect(
+ autoCaptureEventToDescription({
+ ...baseEvent,
+ properties: {
+ ...baseEvent.properties,
+ $el_text: 'Text from properties',
+ },
+ elements: [{ tag_name: 'button', text: 'Text from elements' } as ElementType],
+ })
+ ).toEqual('clicked button with text "Text from properties"')
+ })
+
+ it('handles text with double quotes without adding additional quotes', () => {
+ expect(
+ autoCaptureEventToDescription({
+ ...baseEvent,
+ properties: {
+ ...baseEvent.properties,
+ $el_text: 'Unit Skills Assessment 1: "',
+ },
+ })
+ ).toEqual('clicked element with text "Unit Skills Assessment 1: ""')
+ })
+
+ it('handles text with single quotes without adding additional quotes', () => {
+ expect(
+ autoCaptureEventToDescription({
+ ...baseEvent,
+ properties: {
+ ...baseEvent.properties,
+ $el_text: "Reading Lesson: '",
+ },
+ })
+ ).toEqual('clicked element with text "Reading Lesson: \'"')
+ })
+
+ it('handles longer text with single quotes without adding additional quotes', () => {
+ expect(
+ autoCaptureEventToDescription({
+ ...baseEvent,
+ properties: {
+ ...baseEvent.properties,
+ $el_text: "A Sense of Wonder: An Introduction to Science Fiction'",
+ },
+ })
+ ).toEqual('clicked element with text "A Sense of Wonder: An Introduction to Science Fiction\'"')
+ })
+
+ it('handles text in elements array', () => {
+ expect(
+ autoCaptureEventToDescription({
+ ...baseEvent,
+ elements: [{ tag_name: 'button', text: 'hello world' } as ElementType],
+ })
+ ).toEqual('clicked button with text "hello world"')
+ })
+
+ it('handles text with quotes in elements array', () => {
+ expect(
+ autoCaptureEventToDescription({
+ ...baseEvent,
+ elements: [{ tag_name: 'button', text: 'hello "world"' } as ElementType],
+ })
+ ).toEqual('clicked button with text "hello "world""')
+ })
+
+ it('handles aria-label attributes', () => {
+ expect(
+ autoCaptureEventToDescription({
+ ...baseEvent,
+ elements: [
+ {
+ tag_name: 'button',
+ attributes: { 'attr__aria-label': 'Close dialog' },
+ } as ElementType,
+ ],
+ })
+ ).toEqual('clicked button with aria label "Close dialog"')
+ })
+
+ it('handles aria-label attributes with quotes', () => {
+ expect(
+ autoCaptureEventToDescription({
+ ...baseEvent,
+ elements: [
+ {
+ tag_name: 'button',
+ attributes: { 'attr__aria-label': 'Close "main" dialog' },
+ } as ElementType,
+ ],
+ })
+ ).toEqual('clicked button with aria label "Close "main" dialog"')
+ })
+ })
+
+ describe('getPrimaryPropertyForEvent', () => {
+ it('returns the core taxonomy default for built-in events', () => {
+ expect(getPrimaryPropertyForEvent('$pageview')).toBe('$pathname')
+ expect(getPrimaryPropertyForEvent('$pageleave')).toBe('$pathname')
+ expect(getPrimaryPropertyForEvent('$screen')).toBe('$screen_name')
+ expect(getPrimaryPropertyForEvent('$feature_flag_called')).toBe('$feature_flag')
+ })
+
+ it('returns null for events with no taxonomy default and no override', () => {
+ expect(getPrimaryPropertyForEvent('$autocapture')).toBeNull()
+ expect(getPrimaryPropertyForEvent('some_custom_event')).toBeNull()
+ })
+
+ it('returns null for missing event names', () => {
+ expect(getPrimaryPropertyForEvent(null)).toBeNull()
+ expect(getPrimaryPropertyForEvent(undefined)).toBeNull()
+ expect(getPrimaryPropertyForEvent('')).toBeNull()
+ })
+
+ it('ignores team-configured overrides for events that have a taxonomy default', () => {
+ // Taxonomy is immutable — users can only set primary properties for events
+ // without a fixed taxonomy entry.
+ expect(getPrimaryPropertyForEvent('$pageview', { $pageview: '$current_url' })).toBe('$pathname')
+ expect(getPrimaryPropertyForEvent('$screen', { $screen: 'my_custom_prop' })).toBe('$screen_name')
+ })
+
+ it('uses the team-configured override for custom events with no taxonomy default', () => {
+ expect(getPrimaryPropertyForEvent('order_placed', { order_placed: 'order_id' })).toBe('order_id')
+ })
+
+ it('returns null when no override and no taxonomy default', () => {
+ expect(getPrimaryPropertyForEvent('order_placed', { other_event: 'x' })).toBeNull()
+ })
+ })
+
+ describe('getEventsWithPrimaryProperty', () => {
+ it('returns events that have a taxonomy default', () => {
+ const events = [
+ { event: '$pageview', id: 1 },
+ { event: '$autocapture', id: 2 },
+ { event: '$screen', id: 3 },
+ ]
+ expect(getEventsWithPrimaryProperty(events)).toEqual([
+ { event: '$pageview', id: 1 },
+ { event: '$screen', id: 3 },
+ ])
+ })
+
+ it('returns events that have a team override (no taxonomy default)', () => {
+ const events = [
+ { event: 'order_placed', id: 1 },
+ { event: 'just_viewed', id: 2 },
+ ]
+ expect(getEventsWithPrimaryProperty(events, { order_placed: 'order_id' })).toEqual([
+ { event: 'order_placed', id: 1 },
+ ])
+ })
+
+ it('does not include events whose only override is on a taxonomy-fixed event', () => {
+ // Taxonomy wins, so an attempted override on $pageview is moot — but the event is still
+ // included because the taxonomy default already counts as a primary property.
+ const events = [{ event: '$pageview', id: 1 }]
+ expect(getEventsWithPrimaryProperty(events, { $pageview: '$current_url' })).toEqual(events)
+ })
+
+ it('returns an empty list when nothing has a primary property', () => {
+ const events = [
+ { event: '$autocapture', id: 1 },
+ { event: 'arbitrary_custom', id: 2 },
+ ]
+ expect(getEventsWithPrimaryProperty(events)).toEqual([])
+ })
+ })
+
+ describe('hasTaxonomyPrimaryProperty', () => {
+ it('is true for built-in events that have a primary property', () => {
+ expect(hasTaxonomyPrimaryProperty('$pageview')).toBe(true)
+ expect(hasTaxonomyPrimaryProperty('$pageleave')).toBe(true)
+ expect(hasTaxonomyPrimaryProperty('$screen')).toBe(true)
+ expect(hasTaxonomyPrimaryProperty('$feature_flag_called')).toBe(true)
+ })
+
+ it('is false for events with no taxonomy primary property', () => {
+ expect(hasTaxonomyPrimaryProperty('$autocapture')).toBe(false)
+ expect(hasTaxonomyPrimaryProperty('order_placed')).toBe(false)
+ expect(hasTaxonomyPrimaryProperty(null)).toBe(false)
+ expect(hasTaxonomyPrimaryProperty(undefined)).toBe(false)
+ expect(hasTaxonomyPrimaryProperty('')).toBe(false)
+ })
+ })
+})
diff --git a/frontend/src/lib/utils/events.ts b/frontend/src/lib/utils/events.ts
new file mode 100644
index 000000000000..71b2e018af50
--- /dev/null
+++ b/frontend/src/lib/utils/events.ts
@@ -0,0 +1,126 @@
+import { CORE_FILTER_DEFINITIONS_BY_GROUP } from '~/taxonomy/taxonomy'
+import { ActionType, EventType } from '~/types'
+
+export function hasTaxonomyPrimaryProperty(eventName: string | null | undefined): boolean {
+ return !!eventName && !!CORE_FILTER_DEFINITIONS_BY_GROUP.events[eventName]?.primary_property
+}
+
+/**
+ * Resolves the single property whose value a UI should display alongside an event.
+ *
+ * Taxonomy-configured defaults (e.g. `$pageview` -> `$pathname`) are immutable and
+ * always win; team-configured overrides only apply to events that do not have a
+ * taxonomy default.
+ *
+ * This is a pure client-side lookup — both the taxonomy and the overrides map are
+ * already in memory, so callers can invoke this in tight loops (e.g. selectors
+ * filtering all events in a session) without n+1 risk.
+ */
+export function getPrimaryPropertyForEvent(
+ eventName: string | null | undefined,
+ overrides?: Record<string, string | null | undefined>
+): string | null {
+ if (!eventName) {
+ return null
+ }
+ const taxonomyDefault = CORE_FILTER_DEFINITIONS_BY_GROUP.events[eventName]?.primary_property
+ if (taxonomyDefault) {
+ return taxonomyDefault
+ }
+ return overrides?.[eventName] ?? null
+}
+
+/**
+ * Filters a list of events down to those that have a primary property
+ * (taxonomy default or team override). Pure client-side — wraps
+ * `getPrimaryPropertyForEvent` so the intent reads as one operation.
+ */
+export function getEventsWithPrimaryProperty<T extends { event: string }>(
+ events: T[],
+ overrides?: Record<string, string | null | undefined>
+): T[] {
+ return events.filter((e) => getPrimaryPropertyForEvent(e.event, overrides) !== null)
+}
+
+export function eventToDescription(
+ event: Pick<EventType, 'elements' | 'event' | 'properties'>,
+ shortForm: boolean = false
+): string {
+ if (event.event === '$autocapture') {
+ return autoCaptureEventToDescription(event, shortForm)
+ }
+ // For events with a taxonomy-default primary property (e.g. `$pageview` -> `$pathname`,
+ // `$screen` -> `$screen_name`, `$feature_flag_called` -> `$feature_flag`), use the property's
+ // value as the description so consumers (notebooks, save-as-action, funnel labels, ...) get
+ // useful context instead of the bare event name. Returns the event name when the property
+ // isn't present on the event so callers always get something to display.
+ const primaryKey = getPrimaryPropertyForEvent(event.event)
+ if (primaryKey) {
+ const value = event.properties[primaryKey]
+ if (value != null && value !== '') {
+ return String(value)
+ }
+ }
+ return event.event
+}
+
+// $event_type to verb map
+export const eventTypeToVerb: { [key: string]: string } = {
+ click: 'clicked',
+ change: 'changed',
+ submit: 'submitted',
+ touch: 'touched a',
+ value_changed: 'changed value in',
+ toggle: 'toggled',
+ menu_action: 'pressed menu',
+ swipe: 'swiped',
+ pinch: 'pinched',
+ pan: 'panned',
+ rotation: 'rotated',
+ long_press: 'long pressed',
+ scroll: 'scrolled in',
+}
+
+export function autoCaptureEventToDescription(
+ event: Pick<EventType, 'elements' | 'event' | 'properties'>,
+ shortForm: boolean = false
+): string {
+ if (event.event !== '$autocapture') {
+ return event.event
+ }
+
+ const getVerb = (): string => eventTypeToVerb[event.properties.$event_type] || 'interacted with'
+
+ const getTag = (): string => {
+ if (event.elements?.[0]?.tag_name === 'a') {
+ return 'link'
+ } else if (event.elements?.[0]?.tag_name === 'img') {
+ return 'image'
+ }
+ return event.elements?.[0]?.tag_name ?? 'element'
+ }
+
+ const getValue = (): string | null => {
+ if (event.properties.$el_text) {
+ return `${shortForm ? '' : 'with text '}"${event.properties.$el_text}"`
+ } else if (event.elements?.[0]?.text) {
+ return `${shortForm ? '' : 'with text '}"${event.elements[0].text}"`
+ } else if (event.elements?.[0]?.attributes?.['attr__aria-label']) {
+ return `${shortForm ? '' : 'with aria label '}"${event.elements[0].attributes['attr__aria-label']}"`
+ }
+ return null
+ }
+
+ if (shortForm) {
+ return [getVerb(), getValue() ?? getTag()].filter((x) => x).join(' ')
+ }
+ const value = getValue()
+ return [getVerb(), getTag(), value].filter((x) => x).join(' ')
+}
+
+export function getEventNamesForAction(actionId: string | number, allActions: ActionType[]): string[] {
+ const id = parseInt(String(actionId))
+ return allActions
+ .filter((a) => a.id === id)
+ .flatMap((a) => a.steps?.filter((step) => step.event).map((step) => String(step.event)) as string[])
+}
diff --git a/frontend/src/lib/utils/expandFlattenedMarkdownTables.test.ts b/frontend/src/lib/utils/expandFlattenedMarkdownTables.test.ts
deleted file mode 100644
index 9d9dcbe8a5de..000000000000
--- a/frontend/src/lib/utils/expandFlattenedMarkdownTables.test.ts
+++ /dev/null
@@ -1,54 +0,0 @@
-import { expandFlattenedMarkdownTables } from './expandFlattenedMarkdownTables'
-
-describe('expandFlattenedMarkdownTables', () => {
- it('expands a flattened table into separate rows', () => {
- const input = '| a | b | |---|---| | 1 | 2 |'
- expect(expandFlattenedMarkdownTables(input)).toBe(['| a | b |', '|---|---|', '| 1 | 2 |'].join('\n'))
- })
-
- it('expands a flattened table embedded between other markdown lines', () => {
- const input = ['# Heading', '| a | b | |---|---| | 1 | 2 |', 'trailing paragraph'].join('\n')
- expect(expandFlattenedMarkdownTables(input)).toBe(
- ['# Heading', '| a | b |', '|---|---|', '| 1 | 2 |', 'trailing paragraph'].join('\n')
- )
- })
-
- it('expands a flattened table whose rows are glued together with no whitespace', () => {
- const input = '| Month | Boost | Scale ||-------|-------|-------|| Jul 2025 | 54 | 20 || Aug 2025 | 59 | 26 |'
- expect(expandFlattenedMarkdownTables(input)).toBe(
- [
- '| Month | Boost | Scale |',
- '|-------|-------|-------|',
- '| Jul 2025 | 54 | 20 |',
- '| Aug 2025 | 59 | 26 |',
- ].join('\n')
- )
- })
-
- it('handles alignment markers in the delimiter row', () => {
- const input = '| a | b | c | | :--- | :---: | ---: | | 1 | 2 | 3 |'
- expect(expandFlattenedMarkdownTables(input)).toBe(
- ['| a | b | c |', '| :--- | :---: | ---: |', '| 1 | 2 | 3 |'].join('\n')
- )
- })
-
- it('expands a header + delimiter row table with no data rows', () => {
- const input = '| a | b | |---|---|'
- expect(expandFlattenedMarkdownTables(input)).toBe(['| a | b |', '|---|---|'].join('\n'))
- })
-
- it('leaves a well-formed multi-line table untouched', () => {
- const input = ['| a | b |', '|---|---|', '| 1 | 2 |'].join('\n')
- expect(expandFlattenedMarkdownTables(input)).toBe(input)
- })
-
- it.each([
- { input: 'just a plain paragraph of text', desc: 'plain prose' },
- { input: 'see |foo| and |bar| for details', desc: 'inline pipes without a delimiter row' },
- { input: '| a | | b |', desc: 'two glued segments without a delimiter row' },
- { input: '', desc: 'empty string' },
- { input: '# Heading\n\nplain paragraph', desc: 'markdown without any pipes' },
- ])('leaves $desc untouched', ({ input }) => {
- expect(expandFlattenedMarkdownTables(input)).toBe(input)
- })
-})
diff --git a/frontend/src/lib/utils/expandFlattenedMarkdownTables.ts b/frontend/src/lib/utils/expandFlattenedMarkdownTables.ts
deleted file mode 100644
index 27dec740d5cc..000000000000
--- a/frontend/src/lib/utils/expandFlattenedMarkdownTables.ts
+++ /dev/null
@@ -1,20 +0,0 @@
-const TABLE_DELIMITER_SEGMENT_RE = /^\|(?:\s*:?-{2,}:?\s*\|)+\s*$/
-// Matches the boundary between two flattened rows: a closing `|` directly followed by the
-// next row's opening `|`. The whitespace is optional because some sources (e.g. AI chat
-// output) glue rows together with no space (`...Total ||-------|...`) while others keep one.
-const FLATTENED_TABLE_ROW_BOUNDARY_RE = /(?<=\|)\s*(?=\|)/
-
-// Slack, ChatGPT, Notion etc. strip newlines between table rows on plain-text copy.
-// Only splits when a delimiter row (`|---|---|`) is present, so prose with `|` is safe.
-export function expandFlattenedMarkdownTables(text: string): string {
- return text
- .split('\n')
- .flatMap((line) => {
- const segments = line.split(FLATTENED_TABLE_ROW_BOUNDARY_RE).map((s) => s.trim())
- if (segments.length < 2 || !segments.some((s) => TABLE_DELIMITER_SEGMENT_RE.test(s))) {
- return [line]
- }
- return segments
- })
- .join('\n')
-}
diff --git a/frontend/src/lib/utils/getAppContext.ts b/frontend/src/lib/utils/getAppContext.ts
index aaf5e470a85f..517b8427e35d 100644
--- a/frontend/src/lib/utils/getAppContext.ts
+++ b/frontend/src/lib/utils/getAppContext.ts
@@ -74,3 +74,5 @@ export function getCurrentOrganizationId(): OrganizationType['id'] {
}
return maybeOrgId
}
+
+export const isUserLoggedIn = (): boolean => !getAppContext()?.anonymous
diff --git a/frontend/src/lib/utils/guards.ts b/frontend/src/lib/utils/guards.ts
new file mode 100644
index 000000000000..40f4c88c077d
--- /dev/null
+++ b/frontend/src/lib/utils/guards.ts
@@ -0,0 +1,146 @@
+import { ActorType, GroupActorType, SessionActorType } from '~/types'
+
+export function isString(candidate: unknown): candidate is string {
+ return typeof candidate === 'string'
+}
+
+export function isNumber(candidate: unknown): candidate is number {
+ return typeof candidate === 'number'
+}
+
+export function isObject(candidate: unknown): candidate is Record<string, unknown> {
+ return typeof candidate === 'object' && candidate !== null && !Array.isArray(candidate)
+}
+
+export function isEmptyObject(candidate: unknown): boolean {
+ return isObject(candidate) && Object.keys(candidate).length === 0
+}
+
+export function isNonEmptyObject(candidate: unknown): candidate is Record<string, unknown> {
+ return isObject(candidate) && !isEmptyObject(candidate)
+}
+
+/** Check whether a runtime key exists on an object and narrow it to `keyof T`. */
+export function isKeyOf<T extends object>(key: any, obj: T): key is keyof T {
+ return key in obj
+}
+
+/**
+ * Check if the argument is not nullish (null or undefined).
+ *
+ * Useful as a typeguard, e.g. when passed to Array.filter()
+ *
+ * @example
+ * const myList = [1, 2, null]; // type is (number | null)[]
+ *
+ * // using isNotNil
+ * const myFilteredList1 = myList.filter(isNotNil) // type is number[]
+ * const squaredList1 = myFilteredList1.map(x => x * x) // not a type error!
+ *
+ * // compared to:
+ * const myFilteredList2 = myList.filter(x => x != null) // type is (number | null)[]
+ * const squaredList2 = myFilteredList2.map(x => x * x) // Type Error: TS18047: x is possibly null
+ */
+export function isNotNil<T>(arg: T): arg is Exclude<T, null | undefined> {
+ return arg !== null && arg !== undefined
+}
+
+// https://stackoverflow.com/questions/175739/how-can-i-check-if-a-string-is-a-valid-number
+export function isNumeric(x: unknown): x is number {
+ if (typeof x === 'number') {
+ return !isNaN(x) && isFinite(x)
+ }
+ if (typeof x !== 'string' || x.trim() === '') {
+ return false
+ }
+ return !isNaN(Number(x))
+}
+
+/**
+ * Checks if a string matches the canonical UUID/UUID-like format.
+ *
+ * This function only checks the structure:
+ * - 8-4-4-4-12 hexadecimal characters
+ * - 4 dashes in the correct positions
+ * It does not enforce UUID version or variant.
+ *
+ * Examples:
+ * - ✅ "0199ed4a-5c03-0000-3220-df21df612e95"
+ * - ❌ "not-a-uuid"
+ *
+ * @param candidate - The string to test.
+ * @returns True if the string matches the UUID-like structure.
+ */
+export function isUUIDLike(candidate: string): boolean {
+ return /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(candidate)
+}
+
+export function isGroupType(actor: ActorType): actor is GroupActorType {
+ return actor.type === 'group'
+}
+
+export function isSessionType(actor: ActorType): actor is SessionActorType {
+ return actor.type === 'session'
+}
+
+/** An error signaling that a value of type `never` in TypeScript was used unexpectedly at runtime.
+ *
+ * Useful for type-narrowing, will give a compile-time error if the type of x is not `never`.
+ * See the example below where it catches a missing branch at compile-time.
+ *
+ * @example
+ *
+ * enum MyEnum {
+ * a,
+ * b,
+ * }
+ *
+ * function handleEnum(x: MyEnum) {
+ * switch (x) {
+ * case MyEnum.a:
+ * return
+ * // missing branch
+ * default:
+ * throw new UnexpectedNeverError(x) // TS2345: Argument of type MyEnum is not assignable to parameter of type never
+ * }
+ * }
+ *
+ * function handleEnum(x: MyEnum) {
+ * switch (x) {
+ * case MyEnum.a:
+ * return
+ * case MyEnum.b:
+ * return
+ * default:
+ * throw new UnexpectedNeverError(x) // no type error
+ * }
+ * }
+ *
+ */
+export class UnexpectedNeverError extends Error {
+ constructor(x: never, message?: string) {
+ message = message ?? 'Unexpected never: ' + String(x)
+ super(message)
+
+ // restore prototype chain, which is broken by Error
+ // see https://stackoverflow.com/questions/41102060/typescript-extending-error-class
+ const actualProto = new.target.prototype
+ if (Object.setPrototypeOf) {
+ Object.setPrototypeOf(this, actualProto)
+ }
+ }
+}
+
+/**
+ * Assigns a value to an object field while preserving key-based type inference.
+ * Use this when the key is known but the incoming value is `unknown` and has
+ * already been validated by surrounding logic.
+ *
+ * @param obj - Object to mutate.
+ * @param key - Field name to assign on `obj`.
+ * @param value - Value to assign; cast to `T[K]`.
+ * @returns {void}
+ */
+export function assignField<T, K extends keyof T>(obj: T, key: K, value: unknown): void {
+ obj[key] = value as T[K]
+}
diff --git a/frontend/src/lib/utils/insightLinks.test.ts b/frontend/src/lib/utils/insightLinks.test.ts
deleted file mode 100644
index 5631dc5321e2..000000000000
--- a/frontend/src/lib/utils/insightLinks.test.ts
+++ /dev/null
@@ -1,50 +0,0 @@
-import { getInsightDefinitionUrl } from 'lib/utils/insightLinks'
-
-import { NodeKind } from '~/queries/schema/schema-general'
-
-describe('getInsightDefinitionUrl', () => {
- it('generates a template link for an unsaved insight (raw query)', () => {
- const query = {
- kind: NodeKind.InsightVizNode,
- source: {
- kind: NodeKind.TrendsQuery,
- series: [
- {
- kind: NodeKind.EventsNode,
- event: null,
- name: 'All events',
- math: 'total',
- },
- ],
- trendsFilter: {},
- },
- }
- const url = getInsightDefinitionUrl({ query }, 'https://app.posthog.com')
- expect(url).toMatch(/^https:\/\/app\.posthog\.com\/insights\/new#insight=TRENDS&q=%7B.*%7D(%20)?$/)
- // Should not include /project/<id>
- expect(url).not.toContain('/project/')
- })
-
- it('generates a template link for a saved insight (model)', () => {
- interface MinimalInsight {
- query: any
- id: number
- name: string
- }
- const savedInsight: MinimalInsight = {
- query: {
- kind: NodeKind.InsightVizNode,
- source: {
- kind: NodeKind.FunnelsQuery,
- series: [],
- funnelsFilter: {},
- },
- },
- id: 123,
- name: 'My Funnel',
- }
- const url = getInsightDefinitionUrl(savedInsight, 'https://app.posthog.com')
- expect(url).toMatch(/^https:\/\/app\.posthog\.com\/insights\/new#insight=FUNNELS&q=%7B.*%7D(%20)?$/)
- expect(url).not.toContain('/project/')
- })
-})
diff --git a/frontend/src/lib/utils/insightLinks.ts b/frontend/src/lib/utils/insightLinks.ts
deleted file mode 100644
index c916c3f849ed..000000000000
--- a/frontend/src/lib/utils/insightLinks.ts
+++ /dev/null
@@ -1,44 +0,0 @@
-import { urls } from 'scenes/urls'
-
-import { nodeKindToInsightType } from '~/queries/nodes/InsightQuery/utils/queryNodeToFilter'
-import type { Node } from '~/queries/schema/schema-general'
-import { NodeKind } from '~/queries/schema/schema-general'
-import type { QueryBasedInsightModel } from '~/types'
-import { InsightType } from '~/types'
-
-/**
- * Build a canonical definition-based insight link ("template link").
- * The link always points to `/insights/new` on the provided baseUrl and includes:
- * #insight=<InsightType>&q=<URL-encoded JSON definition>
- *
- * It works for both saved insights (where `query` is persisted on the model)
- * and unsaved/draft insights (pass the raw query object).
- */
-export function getInsightDefinitionUrl(
- insight: Pick<QueryBasedInsightModel, 'query'> | { query: Node<Record<string, any>> },
- baseUrl: string
-): string {
- if (!insight?.query) {
- throw new Error('getInsightDefinitionUrl: insight.query is required')
- }
-
- // Derive InsightType from the query where possible so the #insight=<TYPE> hash param is present
- let insightType: InsightType | undefined
- type InsightVizNode = { kind: NodeKind.InsightVizNode; source?: { kind?: string } }
- const kind = (
- insight.query.kind === NodeKind.InsightVizNode
- ? (insight.query as InsightVizNode).source?.kind
- : insight.query.kind
- ) as keyof typeof nodeKindToInsightType | undefined
-
- if (kind && kind in nodeKindToInsightType) {
- insightType = nodeKindToInsightType[kind as keyof typeof nodeKindToInsightType]
- }
-
- const relativeUrl = urls.insightNew({ query: insight.query, type: insightType })
-
- // Ensure the link is project-agnostic (`/project/<id>` may get injected elsewhere)
- const cleanedPath = relativeUrl.replace(/^\/project\/[^/]+/, '')
-
- return `${baseUrl}${cleanedPath}`
-}
diff --git a/frontend/src/lib/utils/json.ts b/frontend/src/lib/utils/json.ts
new file mode 100644
index 000000000000..e58ed733fa62
--- /dev/null
+++ b/frontend/src/lib/utils/json.ts
@@ -0,0 +1,16 @@
+export function validateJson(value: string): boolean {
+ try {
+ JSON.parse(value)
+ return true
+ } catch {
+ return false
+ }
+}
+
+export function tryJsonParse(value: string, fallback?: any): any {
+ try {
+ return JSON.parse(value)
+ } catch {
+ return fallback
+ }
+}
diff --git a/frontend/src/lib/utils/router-utils.test.ts b/frontend/src/lib/utils/kea-router.test.ts
similarity index 99%
rename from frontend/src/lib/utils/router-utils.test.ts
rename to frontend/src/lib/utils/kea-router.test.ts
index b061c54f52b6..f816cdf6af0c 100644
--- a/frontend/src/lib/utils/router-utils.test.ts
+++ b/frontend/src/lib/utils/kea-router.test.ts
@@ -1,4 +1,4 @@
-import { addProjectIdIfMissing, stripTrailingSlash } from 'lib/utils/router-utils'
+import { addProjectIdIfMissing, stripTrailingSlash } from 'lib/utils/kea-router'
describe('router-utils', () => {
it('does not redirect account URLs to a project URL', () => {
diff --git a/frontend/src/lib/utils/router-utils.ts b/frontend/src/lib/utils/kea-router.ts
similarity index 100%
rename from frontend/src/lib/utils/router-utils.ts
rename to frontend/src/lib/utils/kea-router.ts
diff --git a/frontend/src/lib/utils/markdown.test.ts b/frontend/src/lib/utils/markdown.test.ts
new file mode 100644
index 000000000000..f8760a449f4e
--- /dev/null
+++ b/frontend/src/lib/utils/markdown.test.ts
@@ -0,0 +1,100 @@
+import { expandFlattenedMarkdownTables, stripMarkdown } from 'lib/utils/markdown'
+
+describe('markdown utils', () => {
+ describe('stripMarkdown', () => {
+ it.each([
+ // Basic text
+ ['plain text', 'plain text'],
+
+ // Unordered lists with dashes
+ ['- item 1\n- item 2\n- item 3', '- item 1\n- item 2\n- item 3'],
+
+ // Ordered lists with numbers
+ ['1. first\n2. second\n3. third', '1. first\n2. second\n3. third'],
+
+ // Ordered list starting at different number
+ ['5. fifth\n6. sixth', '5. fifth\n6. sixth'],
+
+ // Links with URL preserved
+ ['[click here](https://example.com)', 'click here (https://example.com)'],
+ ['[PostHog](https://posthog.com/docs)', 'PostHog (https://posthog.com/docs)'],
+
+ // Link without text
+ ['[](https://example.com)', 'https://example.com'],
+
+ // Relative links get prefixed with origin
+ ['[docs](/docs/guide)', `docs (${window.location.origin}/docs/guide)`],
+ ['[api](api/v1)', `api (${window.location.origin}/api/v1)`],
+
+ // Bold/italic/code stripped
+ ['**bold** and *italic*', 'bold and italic'],
+ ['`inline code`', 'inline code'],
+
+ // Headings stripped
+ ['# Heading 1', 'Heading 1'],
+ ['## Heading 2', 'Heading 2'],
+
+ // Mixed content
+ [
+ '# Title\n\n- item 1\n- item 2\n\n[link](https://test.com)',
+ 'Title\n\n- item 1\n- item 2\n\nlink (https://test.com)',
+ ],
+ ])('converts %j to %j', (input, expected) => {
+ expect(stripMarkdown(input)).toBe(expected)
+ })
+ })
+
+ describe('expandFlattenedMarkdownTables', () => {
+ it('expands a flattened table into separate rows', () => {
+ const input = '| a | b | |---|---| | 1 | 2 |'
+ expect(expandFlattenedMarkdownTables(input)).toBe(['| a | b |', '|---|---|', '| 1 | 2 |'].join('\n'))
+ })
+
+ it('expands a flattened table embedded between other markdown lines', () => {
+ const input = ['# Heading', '| a | b | |---|---| | 1 | 2 |', 'trailing paragraph'].join('\n')
+ expect(expandFlattenedMarkdownTables(input)).toBe(
+ ['# Heading', '| a | b |', '|---|---|', '| 1 | 2 |', 'trailing paragraph'].join('\n')
+ )
+ })
+
+ it('expands a flattened table whose rows are glued together with no whitespace', () => {
+ const input =
+ '| Month | Boost | Scale ||-------|-------|-------|| Jul 2025 | 54 | 20 || Aug 2025 | 59 | 26 |'
+ expect(expandFlattenedMarkdownTables(input)).toBe(
+ [
+ '| Month | Boost | Scale |',
+ '|-------|-------|-------|',
+ '| Jul 2025 | 54 | 20 |',
+ '| Aug 2025 | 59 | 26 |',
+ ].join('\n')
+ )
+ })
+
+ it('handles alignment markers in the delimiter row', () => {
+ const input = '| a | b | c | | :--- | :---: | ---: | | 1 | 2 | 3 |'
+ expect(expandFlattenedMarkdownTables(input)).toBe(
+ ['| a | b | c |', '| :--- | :---: | ---: |', '| 1 | 2 | 3 |'].join('\n')
+ )
+ })
+
+ it('expands a header + delimiter row table with no data rows', () => {
+ const input = '| a | b | |---|---|'
+ expect(expandFlattenedMarkdownTables(input)).toBe(['| a | b |', '|---|---|'].join('\n'))
+ })
+
+ it('leaves a well-formed multi-line table untouched', () => {
+ const input = ['| a | b |', '|---|---|', '| 1 | 2 |'].join('\n')
+ expect(expandFlattenedMarkdownTables(input)).toBe(input)
+ })
+
+ it.each([
+ { input: 'just a plain paragraph of text', desc: 'plain prose' },
+ { input: 'see |foo| and |bar| for details', desc: 'inline pipes without a delimiter row' },
+ { input: '| a | | b |', desc: 'two glued segments without a delimiter row' },
+ { input: '', desc: 'empty string' },
+ { input: '# Heading\n\nplain paragraph', desc: 'markdown without any pipes' },
+ ])('leaves $desc untouched', ({ input }) => {
+ expect(expandFlattenedMarkdownTables(input)).toBe(input)
+ })
+ })
+})
diff --git a/frontend/src/lib/utils/stripMarkdown.ts b/frontend/src/lib/utils/markdown.ts
similarity index 80%
rename from frontend/src/lib/utils/stripMarkdown.ts
rename to frontend/src/lib/utils/markdown.ts
index df8e74e72829..a06f48cade37 100644
--- a/frontend/src/lib/utils/stripMarkdown.ts
+++ b/frontend/src/lib/utils/markdown.ts
@@ -1,5 +1,26 @@
import { marked } from 'marked'
+const TABLE_DELIMITER_SEGMENT_RE = /^\|(?:\s*:?-{2,}:?\s*\|)+\s*$/
+// Matches the boundary between two flattened rows: a closing `|` directly followed by the
+// next row's opening `|`. The whitespace is optional because some sources (e.g. AI chat
+// output) glue rows together with no space (`...Total ||-------|...`) while others keep one.
+const FLATTENED_TABLE_ROW_BOUNDARY_RE = /(?<=\|)\s*(?=\|)/
+
+// Slack, ChatGPT, Notion etc. strip newlines between table rows on plain-text copy.
+// Only splits when a delimiter row (`|---|---|`) is present, so prose with `|` is safe.
+export function expandFlattenedMarkdownTables(text: string): string {
+ return text
+ .split('\n')
+ .flatMap((line) => {
+ const segments = line.split(FLATTENED_TABLE_ROW_BOUNDARY_RE).map((s) => s.trim())
+ if (segments.length < 2 || !segments.some((s) => TABLE_DELIMITER_SEGMENT_RE.test(s))) {
+ return [line]
+ }
+ return segments
+ })
+ .join('\n')
+}
+
type Token = ReturnType<typeof marked.lexer>[number]
function resolveUrl(href: string): string {
diff --git a/frontend/src/lib/utils/newInternalTab.tsx b/frontend/src/lib/utils/newInternalTab.tsx
index b0d550aaa59f..65f6b35e3d30 100644
--- a/frontend/src/lib/utils/newInternalTab.tsx
+++ b/frontend/src/lib/utils/newInternalTab.tsx
@@ -1,4 +1,4 @@
-import { addProjectIdIfMissing } from 'lib/utils/router-utils'
+import { addProjectIdIfMissing } from 'lib/utils/kea-router'
export const NEW_INTERNAL_TAB = 'NEW_INTERNAL_TAB'
diff --git a/frontend/src/lib/utils/numbers.test.ts b/frontend/src/lib/utils/numbers.test.ts
new file mode 100644
index 000000000000..16c31b6a53ca
--- /dev/null
+++ b/frontend/src/lib/utils/numbers.test.ts
@@ -0,0 +1,91 @@
+import {
+ average,
+ compactNumber,
+ formatPercentageDiff,
+ humanFriendlyLargeNumber,
+ median,
+ roundToDecimal,
+} from 'lib/utils/numbers'
+
+describe('numbers utils', () => {
+ describe('compactNumber()', () => {
+ it('formats number correctly', () => {
+ expect(compactNumber(10)).toEqual('10')
+ expect(compactNumber(293)).toEqual('293')
+ expect(compactNumber(5001)).toEqual('5 K')
+ expect(compactNumber(5312)).toEqual('5.31 K')
+ expect(compactNumber(5392)).toEqual('5.39 K')
+ expect(compactNumber(2833102)).toEqual('2.83 M')
+ expect(compactNumber(8283310234)).toEqual('8.28 B')
+ expect(compactNumber(null)).toEqual('-')
+ })
+ })
+
+ describe('roundToDecimal()', () => {
+ it('formats number correctly', () => {
+ expect(roundToDecimal(null)).toEqual('-')
+ expect(roundToDecimal(293)).toEqual('293.00')
+ expect(roundToDecimal(102.121233)).toEqual('102.12')
+ expect(roundToDecimal(102.99999)).toEqual('103.00')
+ expect(roundToDecimal(1212)).toEqual('1212.00')
+ expect(roundToDecimal(1212, 3)).toEqual('1212.000')
+ })
+ })
+
+ describe('average()', () => {
+ it('calculates average correctly', () => {
+ expect(average([9, 4, 1, 3, 5, 7])).toEqual(4.8)
+ expect(average([72, 35, 68, 66, 70, 9, 81])).toEqual(57.3) // Tests rounding too
+ expect(average([86.4, 46.321, 45.304, 34.1, 147])).toEqual(71.8) // Tests rounding too
+ })
+ })
+
+ describe('median()', () => {
+ it('returns middle number if array length is odd', () => {
+ expect(median([9, 4, 1, 3, 5, 7, 3, 6, 14])).toEqual(5)
+ })
+ it('returns avg of middle numbers if array length is even', () => {
+ expect(median([9, 4, 0, 5, 7, 3, 6, 14])).toEqual(5.5)
+ })
+ })
+
+ describe('humanFriendlyLargeNumber()', () => {
+ it('returns the correct string', () => {
+ expect(humanFriendlyLargeNumber(1.234)).toEqual('1.23')
+ expect(humanFriendlyLargeNumber(12.34)).toEqual('12.3')
+ expect(humanFriendlyLargeNumber(123.4)).toEqual('123')
+ expect(humanFriendlyLargeNumber(1234)).toEqual('1.23K')
+ expect(humanFriendlyLargeNumber(12345)).toEqual('12.3K')
+ expect(humanFriendlyLargeNumber(123456)).toEqual('123K')
+ expect(humanFriendlyLargeNumber(1234567)).toEqual('1.23M')
+ expect(humanFriendlyLargeNumber(-1234567)).toEqual('-1.23M')
+ expect(humanFriendlyLargeNumber(-1)).toEqual('-1')
+ expect(humanFriendlyLargeNumber(-0.1)).toEqual('-0.1')
+ expect(humanFriendlyLargeNumber(0)).toEqual('0')
+ expect(humanFriendlyLargeNumber(NaN)).toEqual('NaN')
+ expect(humanFriendlyLargeNumber(Infinity)).toEqual('inf')
+ expect(humanFriendlyLargeNumber(-Infinity)).toEqual('-inf')
+ })
+ })
+
+ describe('formatPercentageDiff()', () => {
+ it.each([
+ { current: 150, previous: 100, expected: '(+50.0%)' },
+ { current: 200, previous: 100, expected: '(+100.0%)' },
+ { current: 100, previous: 100, expected: '(+0.0%)' },
+ { current: 50, previous: 100, expected: '(-50.0%)' },
+ { current: 0, previous: 100, expected: '(-100.0%)' },
+ { current: 125, previous: 100, expected: '(+25.0%)' },
+ { current: 75, previous: 100, expected: '(-25.0%)' },
+ ])('formats $current vs $previous as $expected', ({ current, previous, expected }) => {
+ expect(formatPercentageDiff(current, previous)).toEqual(expected)
+ })
+
+ it.each([
+ { current: 100, previous: 0, description: 'division by zero' },
+ { current: 0, previous: 0, description: 'zero divided by zero' },
+ ])('returns null for $description', ({ current, previous }) => {
+ expect(formatPercentageDiff(current, previous)).toBeNull()
+ })
+ })
+})
diff --git a/frontend/src/lib/utils/numbers.ts b/frontend/src/lib/utils/numbers.ts
new file mode 100644
index 000000000000..f4d5afccce13
--- /dev/null
+++ b/frontend/src/lib/utils/numbers.ts
@@ -0,0 +1,207 @@
+export const DEFAULT_DECIMAL_PLACES = 2
+
+function validateFractionDigits(maximumFractionDigits: number, fallback: number): number {
+ if (
+ isNaN(maximumFractionDigits) ||
+ !Number.isInteger(maximumFractionDigits) ||
+ maximumFractionDigits < 0 ||
+ maximumFractionDigits > 100
+ ) {
+ return fallback
+ }
+ return maximumFractionDigits
+}
+
+// taken from https://stackoverflow.com/questions/10420352/converting-file-size-in-bytes-to-human-readable-string/10420404
+export const humanizeBytes = (fileSizeInBytes: number | null): string => {
+ if (fileSizeInBytes === null) {
+ return ''
+ }
+
+ let i = -1
+ let convertedBytes = fileSizeInBytes
+ const byteUnits = ['kB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB']
+ do {
+ convertedBytes = convertedBytes / 1024
+ i++
+ } while (convertedBytes > 1024)
+
+ if (convertedBytes < 0.1) {
+ return fileSizeInBytes + ' bytes'
+ }
+ return convertedBytes.toFixed(2) + ' ' + byteUnits[i]
+}
+
+/** Return percentage from number, e.g. 0.234 is 23.4%. */
+export function percentage(
+ division: number,
+ maximumFractionDigits: number = DEFAULT_DECIMAL_PLACES,
+ fixedPrecision: boolean = false
+): string {
+ if (division === Infinity) {
+ return '∞%'
+ }
+
+ const maxDigits = validateFractionDigits(maximumFractionDigits, DEFAULT_DECIMAL_PLACES)
+
+ return division.toLocaleString('en-US', {
+ style: 'percent',
+ maximumFractionDigits: maxDigits,
+ minimumFractionDigits: fixedPrecision ? maxDigits : undefined,
+ })
+}
+
+/**
+ * Formats the percentage difference between two values for display.
+ * Returns null if the result would be NaN or Infinity (e.g., division by zero).
+ */
+export function formatPercentageDiff(current: number, previous: number): string | null {
+ const diff = (current - previous) / previous
+
+ if (!Number.isFinite(diff)) {
+ return null
+ }
+
+ return diff >= 0 ? `(+${(diff * 100).toFixed(1)}%)` : `(-${(-diff * 100).toFixed(1)}%)`
+}
+
+/** Format number with comma as the thousands separator. */
+export function humanFriendlyNumber(
+ d: number,
+ maximumFractionDigits: number = DEFAULT_DECIMAL_PLACES,
+ minimumFractionDigits: number = 0
+): string {
+ return d.toLocaleString('en-US', {
+ maximumFractionDigits: validateFractionDigits(maximumFractionDigits, DEFAULT_DECIMAL_PLACES),
+ minimumFractionDigits: validateFractionDigits(minimumFractionDigits, 0),
+ })
+}
+
+export function humanFriendlyLargeNumber(d: number): string {
+ if (isNaN(d)) {
+ return 'NaN'
+ } else if (!isFinite(d)) {
+ if (d > 0) {
+ return 'inf'
+ }
+ return '-inf'
+ }
+ const trillion = 1_000_000_000_000
+ const billion = 1_000_000_000
+ const million = 1_000_000
+ const thousand = 1_000
+
+ // handle positive number only to make life easier
+ const prefix = d >= 0 ? '' : '-'
+ d = Math.abs(d)
+
+ // round to 3 significant figures
+ d = parseFloat(d.toPrecision(3))
+
+ if (d >= trillion) {
+ return `${prefix}${(d / trillion).toString()}T`
+ } else if (d >= billion) {
+ return `${prefix}${(d / billion).toString()}B`
+ }
+ if (d >= million) {
+ return `${prefix}${(d / million).toString()}M`
+ }
+ if (d >= thousand) {
+ return `${prefix}${(d / thousand).toString()}K`
+ }
+ return `${prefix}${d}`
+}
+
+/** Format currency from string with commas and a number of decimal places (defaults to 2). */
+export function humanFriendlyCurrency(
+ d: string | undefined | number,
+ precision: number = DEFAULT_DECIMAL_PLACES
+): string {
+ if (!d) {
+ d = '0.00'
+ }
+
+ let number: number
+ if (typeof d === 'string') {
+ number = parseFloat(d)
+ } else {
+ number = d
+ }
+
+ const validatedPrecision = validateFractionDigits(precision, DEFAULT_DECIMAL_PLACES)
+ return `$${number.toLocaleString('en-US', { maximumFractionDigits: validatedPrecision, minimumFractionDigits: validatedPrecision })}`
+}
+
+const COMPACT_NUMBER_MAGNITUDES = ['', 'K', 'M', 'B', 'T', 'P', 'E', 'Z', 'Y']
+
+/** Return a number in a compact format, with a SI suffix if applicable.
+ * Server-side equivalent: utils.py#compact_number.
+ */
+export function compactNumber(value: number | null): string {
+ if (value === null) {
+ return '-'
+ }
+
+ value = parseFloat(value.toPrecision(3))
+ let magnitude = 0
+ while (Math.abs(value) >= 1000) {
+ magnitude++
+ value /= 1000
+ }
+ return magnitude > 0 ? `${value} ${COMPACT_NUMBER_MAGNITUDES[magnitude]}` : value.toString()
+}
+
+export function roundToDecimal(value: number | null, places: number = 2): string {
+ if (value === null) {
+ return '-'
+ }
+ return (Math.round(value * 100) / 100).toFixed(places)
+}
+
+export const formatPercentage = (x: number, options?: { precise?: boolean; compact?: boolean }): string => {
+ let result: string
+ if (options?.precise) {
+ result = (x / 100).toLocaleString(undefined, { style: 'percent', maximumFractionDigits: 1 })
+ } else if (x >= 1000) {
+ result = humanFriendlyLargeNumber(x) + '%'
+ } else {
+ result = (x / 100).toLocaleString(undefined, { style: 'percent', maximumSignificantDigits: 2 })
+ }
+ if (options?.compact) {
+ result = result.replace(/\s+%/, '%')
+ }
+ return result
+}
+
+export function average(input: number[]): number {
+ /**
+ * Returns the average of an array
+ * @param input e.g. [100,50, 75]
+ */
+ return Math.round((input.reduce((acc, val) => acc + val, 0) / input.length) * 10) / 10
+}
+
+export function median(input: number[]): number {
+ /**
+ * Returns the median of an array
+ * @param input e.g. [3,7,10]
+ */
+ const sorted = [...input].sort((a, b) => a - b)
+ const half = Math.floor(sorted.length / 2)
+
+ if (sorted.length % 2) {
+ return sorted[half]
+ }
+ return average([sorted[half - 1], sorted[half]])
+}
+
+export function sum(input: number[]): number {
+ return input.reduce((a, b) => a + b, 0)
+}
+
+export function clamp(value: number, min: number, max: number): number {
+ return value > max ? max : value < min ? min : value
+}
+
+// Pad numbers with leading zeros
+export const zeroPad = (num: number, places: number): string => String(num).padStart(places, '0')
diff --git a/frontend/src/lib/utils/objects.test.ts b/frontend/src/lib/utils/objects.test.ts
new file mode 100644
index 000000000000..0af386f1eb84
--- /dev/null
+++ b/frontend/src/lib/utils/objects.test.ts
@@ -0,0 +1,54 @@
+import { areObjectValuesEmpty, objectClean, objectCleanWithEmpty, objectDiffShallow } from 'lib/utils/objects'
+
+describe('objects utils', () => {
+ describe('areObjectValuesEmpty()', () => {
+ it('returns correct value for objects with empty values', () => {
+ expect(areObjectValuesEmpty({ a: '', b: null, c: undefined })).toEqual(true)
+ expect(areObjectValuesEmpty({ a: undefined, b: undefined })).toEqual(true)
+ expect(areObjectValuesEmpty({})).toEqual(true)
+ })
+ it('returns correct value for objects with at least one non-empty value', () => {
+ expect(areObjectValuesEmpty({ a: '', b: null, c: 'hello' })).toEqual(false)
+ expect(areObjectValuesEmpty({ a: true, b: 'hello' })).toEqual(false)
+ expect(areObjectValuesEmpty('hello' as any)).toEqual(false)
+ expect(areObjectValuesEmpty(null as any)).toEqual(false)
+ })
+ })
+
+ describe('objectDiffShallow()', () => {
+ it('obj1 + result = obj2', () => {
+ expect(objectDiffShallow({ b: '4' }, { b: '3', a: '2' })).toStrictEqual({ b: '3', a: '2' })
+ expect(objectDiffShallow({ b: '4', c: '12' }, { b: '3', a: '2' })).toStrictEqual({
+ b: '3',
+ a: '2',
+ c: undefined,
+ })
+ })
+ })
+
+ describe('objectClean()', () => {
+ it('removes undefined values', () => {
+ expect(objectClean({ a: 1, b: 'b', c: null, d: {}, e: [], f: undefined })).toStrictEqual({
+ a: 1,
+ b: 'b',
+ c: null,
+ d: {},
+ e: [],
+ })
+ })
+ })
+
+ describe('objectCleanWithEmpty()', () => {
+ it('removes undefined and empty values', () => {
+ expect(
+ objectCleanWithEmpty({ a: 1, b: 'b', c: null, d: {}, e: [], f: undefined, g: { x: 1 }, h: [1] })
+ ).toStrictEqual({
+ a: 1,
+ b: 'b',
+ c: null,
+ g: { x: 1 },
+ h: [1],
+ })
+ })
+ })
+})
diff --git a/frontend/src/lib/utils/objects.ts b/frontend/src/lib/utils/objects.ts
new file mode 100644
index 000000000000..23559631f423
--- /dev/null
+++ b/frontend/src/lib/utils/objects.ts
@@ -0,0 +1,133 @@
+import equal from 'fast-deep-equal'
+
+export function areObjectValuesEmpty(obj?: Record<string, any>): boolean {
+ return (
+ !!obj && typeof obj === 'object' && !Object.values(obj).some((x) => x !== null && x !== '' && x !== undefined)
+ )
+}
+
+/** Compare objects deeply. */
+export function objectsEqual(obj1: any, obj2: any): boolean {
+ return equal(obj1, obj2)
+}
+
+// https://stackoverflow.com/questions/25421233/javascript-removing-undefined-fields-from-an-object
+export function objectClean<T extends Record<string | number | symbol, unknown>>(
+ obj: T,
+ options?: { removeNulls?: boolean }
+): T {
+ const { removeNulls = false } = options || {}
+ const response = { ...obj }
+ Object.keys(response).forEach((key) => {
+ if (removeNulls ? response[key] == null : response[key] === undefined) {
+ delete response[key]
+ }
+ })
+ return response
+}
+export function objectCleanWithEmpty<T extends Record<string | number | symbol, unknown>>(
+ obj: T,
+ ignoredKeys: string[] = []
+): T {
+ const response = { ...obj }
+ Object.keys(response)
+ .filter((key) => !ignoredKeys.includes(key))
+ .forEach((key) => {
+ // remove undefined values
+ if (response[key] === undefined) {
+ delete response[key]
+ }
+ // remove empty arrays i.e. []
+ if (
+ typeof response[key] === 'object' &&
+ Array.isArray(response[key]) &&
+ (response[key] as unknown[]).length === 0
+ ) {
+ delete response[key]
+ }
+ // remove empty objects i.e. {}
+ if (
+ typeof response[key] === 'object' &&
+ !Array.isArray(response[key]) &&
+ response[key] !== null &&
+ Object.keys(response[key] as Record<string | number | symbol, unknown>).length === 0
+ ) {
+ delete response[key]
+ }
+ })
+ return response
+}
+
+export const removeUndefinedAndNull = (obj: any): any => {
+ if (Array.isArray(obj)) {
+ return obj.map(removeUndefinedAndNull)
+ } else if (obj && typeof obj === 'object') {
+ return Object.entries(obj).reduce(
+ (acc, [key, value]) => {
+ if (value !== undefined && value !== null) {
+ acc[key] = removeUndefinedAndNull(value)
+ }
+ return acc
+ },
+ {} as Record<string, any>
+ )
+ }
+ return obj
+}
+
+/** Returns "response" from: obj2 = { ...obj1, ...response } */
+export function objectDiffShallow(obj1: Record<string, any>, obj2: Record<string, any>): Record<string, any> {
+ const response: Record<string, any> = { ...obj2 }
+ for (const key of Object.keys(obj1)) {
+ if (key in response) {
+ if (obj1[key] === response[key]) {
+ delete response[key]
+ }
+ } else {
+ response[key] = undefined
+ }
+ }
+ return response
+}
+
+export function idToKey(array: Record<string, any>[], keyField: string = 'id'): Record<string, any> {
+ const object: Record<string, any> = {}
+ for (const element of array) {
+ object[element[keyField]] = element
+ }
+ return object
+}
+
+export function sortedKeys<T extends Record<string, any> = Record<string, any>>(object: T): T {
+ const newObject: T = {} as T
+ for (const key of Object.keys(object).sort()) {
+ newObject[key as keyof T] = object[key]
+ }
+ return newObject
+}
+
+export function flattenObject<T extends Record<string, any>>(obj: T): Record<string, any> {
+ return Object.entries(obj).reduce<Record<string, any>>((acc, [key, value]) => {
+ if (value !== null && typeof value === 'object') {
+ const flatChild = flattenObject(value)
+ const normalizedKey = /^\d+$/.test(key) ? key.padStart(3, '0') : key
+
+ Object.entries(flatChild).forEach(([subKey, subVal]) => {
+ acc[`${normalizedKey}.${subKey}`] = subVal
+ })
+ return acc
+ }
+
+ acc[key] = value
+ return acc
+ }, {})
+}
+
+export function hasFormErrors(object: any): boolean {
+ if (Array.isArray(object)) {
+ return object.some(hasFormErrors)
+ } else if (typeof object === 'object' && object !== null) {
+ return Object.values(object).some(hasFormErrors)
+ }
+ return !!object
+}
diff --git a/frontend/src/lib/utils/operators.test.ts b/frontend/src/lib/utils/operators.test.ts
new file mode 100644
index 000000000000..11e41be0cc0f
--- /dev/null
+++ b/frontend/src/lib/utils/operators.test.ts
@@ -0,0 +1,51 @@
+import {
+ booleanOperatorMap,
+ chooseOperatorMap,
+ dateTimeOperatorMap,
+ durationOperatorMap,
+ genericOperatorMap,
+ isOperatorMulti,
+ numericOperatorMap,
+ selectorOperatorMap,
+ stringOperatorMap,
+} from 'lib/utils/operators'
+
+import { PropertyOperator, PropertyType } from '~/types'
+
+describe('operators utils', () => {
+ describe('choosing an operator for taxonomic filters', () => {
+ const testCases = [
+ { propertyType: PropertyType.DateTime, expected: dateTimeOperatorMap },
+ { propertyType: PropertyType.String, expected: stringOperatorMap },
+ { propertyType: PropertyType.Numeric, expected: numericOperatorMap },
+ { propertyType: PropertyType.Boolean, expected: booleanOperatorMap },
+ { propertyType: PropertyType.Duration, expected: durationOperatorMap },
+ { propertyType: PropertyType.Selector, expected: selectorOperatorMap },
+ { propertyType: undefined, expected: genericOperatorMap },
+ ]
+ testCases.forEach((testcase) => {
+ it(`correctly maps ${testcase.propertyType} to operator options`, () => {
+ expect(chooseOperatorMap(testcase.propertyType)).toEqual(testcase.expected)
+ })
+ })
+ })
+
+ describe('isOperatorMulti', () => {
+ it('returns true for operators that support multiple values', () => {
+ expect(isOperatorMulti(PropertyOperator.Exact)).toBe(true)
+ expect(isOperatorMulti(PropertyOperator.IsNot)).toBe(true)
+ expect(isOperatorMulti(PropertyOperator.IContainsMulti)).toBe(true)
+ expect(isOperatorMulti(PropertyOperator.NotIContainsMulti)).toBe(true)
+ })
+
+ it('returns false for operators that do not support multiple values', () => {
+ expect(isOperatorMulti(PropertyOperator.IContains)).toBe(false)
+ expect(isOperatorMulti(PropertyOperator.NotIContains)).toBe(false)
+ expect(isOperatorMulti(PropertyOperator.GreaterThan)).toBe(false)
+ expect(isOperatorMulti(PropertyOperator.LessThan)).toBe(false)
+ expect(isOperatorMulti(PropertyOperator.IsSet)).toBe(false)
+ expect(isOperatorMulti(PropertyOperator.IsNotSet)).toBe(false)
+ expect(isOperatorMulti(PropertyOperator.Regex)).toBe(false)
+ })
+ })
+})
diff --git a/frontend/src/lib/utils/operators.ts b/frontend/src/lib/utils/operators.ts
new file mode 100644
index 000000000000..1e966f81360a
--- /dev/null
+++ b/frontend/src/lib/utils/operators.ts
@@ -0,0 +1,221 @@
+import { PropertyOperator, PropertyType } from '~/types'
+
+export const genericOperatorMap: Record<string, string> = {
+ exact: '= equals',
+ is_not: "≠ doesn't equal",
+ icontains: '∋ contains',
+ not_icontains: "∌ doesn't contain",
+ regex: '∼ matches regex',
+ not_regex: "≁ doesn't match regex",
+ gt: '> greater than',
+ gte: '≥ greater than or equal',
+ lt: '< less than',
+ lte: '≤ less than or equal',
+ is_set: '✓ is set',
+ is_not_set: '✕ is not set',
+}
+
+export const stringOperatorMap: Record<string, string> = {
+ exact: '= equals',
+ is_not: "≠ doesn't equal",
+ icontains: '∋ contains',
+ not_icontains: "∌ doesn't contain",
+ regex: '∼ matches regex',
+ not_regex: "≁ doesn't match regex",
+ is_set: '✓ is set',
+ is_not_set: '✕ is not set',
+ semver_eq: '= equals (semver)',
+ semver_neq: '≠ not equal (semver)',
+ semver_gt: '> greater than (semver)',
+ semver_gte: '≥ greater than or equal (semver)',
+ semver_lt: '< less than (semver)',
+ semver_lte: '≤ less than or equal (semver)',
+ semver_tilde: '~ tilde range (semver)',
+ semver_caret: '^ caret range (semver)',
+ semver_wildcard: '* wildcard (semver)',
+}
+
+export const stringArrayOperatorMap: Record<string, string> = {
+ exact: '= equals',
+ is_not: "≠ doesn't equal",
+ icontains: '∋ contains',
+ not_icontains: "∌ doesn't contain",
+ regex: '∼ matches regex',
+ not_regex: "≁ doesn't match regex",
+}
+
+export const numericOperatorMap: Record<string, string> = {
+ exact: '= equals',
+ is_not: "≠ doesn't equal",
+ regex: '∼ matches regex',
+ not_regex: "≁ doesn't match regex",
+ gt: '> greater than',
+ gte: '≥ greater than or equal',
+ lt: '< less than',
+ lte: '≤ less than or equal',
+ is_set: '✓ is set',
+ is_not_set: '✕ is not set',
+}
+
+export const dateTimeOperatorMap: Record<string, string> = {
+ is_date_exact: '= equals',
+ is_date_before: '< before',
+ is_date_after: '> after',
+ is_set: '✓ is set',
+ is_not_set: '✕ is not set',
+}
+
+export const booleanOperatorMap: Record<string, string> = {
+ exact: '= equals',
+ is_not: "≠ doesn't equal",
+ is_set: '✓ is set',
+ is_not_set: '✕ is not set',
+}
+
+export const durationOperatorMap: Record<string, string> = {
+ gt: '> greater than',
+ lt: '< less than',
+}
+
+export const selectorOperatorMap: Record<string, string> = {
+ exact: '= equals',
+ is_not: "≠ doesn't equal",
+}
+
+export const cohortOperatorMap: Record<string, string> = {
+ in: 'user in',
+ not_in: 'user not in',
+}
+
+export const featureFlagOperatorMap: Record<string, string> = {
+ flag_evaluates_to: '= evaluates to',
+}
+
+export const stickinessOperatorMap: Record<string, string> = {
+ exact: '= exactly',
+ gte: '≥ at least',
+ lte: '≤ at most (but at least once)',
+}
+
+export const cleanedPathOperatorMap: Record<string, string> = {
+ is_cleaned_path_exact: '= equals',
+}
+
+export const semverOperatorMap: Record<string, string> = {
+ semver_eq: '= equals (semver)',
+ semver_neq: '≠ not equal (semver)',
+ semver_gt: '> greater than (semver)',
+ semver_gte: '≥ greater than or equal (semver)',
+ semver_lt: '< less than (semver)',
+ semver_lte: '≤ less than or equal (semver)',
+ semver_tilde: '~ tilde range (semver)',
+ semver_caret: '^ caret range (semver)',
+ semver_wildcard: '* wildcard (semver)',
+}
+
+export const assigneeOperatorMap: Record<string, string> = {
+ exact: '= is',
+ is_not: '≠ is not',
+ is_not_set: '✕ is not set',
+}
+
+export const allOperatorsMapping: Record<string, string> = {
+ ...assigneeOperatorMap,
+ ...stickinessOperatorMap,
+ ...dateTimeOperatorMap,
+ ...semverOperatorMap,
+ ...stringArrayOperatorMap,
+ ...numericOperatorMap,
+ ...genericOperatorMap,
+ ...booleanOperatorMap,
+ ...durationOperatorMap,
+ ...selectorOperatorMap,
+ ...cohortOperatorMap,
+ ...featureFlagOperatorMap,
+ ...cleanedPathOperatorMap,
+ ...stringOperatorMap,
+ // slight overkill to spread all of these into the map
+ // but gives freedom for them to diverge more over time
+}
+
+const operatorMappingChoice: Record<keyof typeof PropertyType, Record<string, string>> = {
+ DateTime: dateTimeOperatorMap,
+ String: stringOperatorMap,
+ Numeric: numericOperatorMap,
+ Boolean: booleanOperatorMap,
+ Duration: durationOperatorMap,
+ Selector: selectorOperatorMap,
+ Cohort: cohortOperatorMap,
+ Flag: featureFlagOperatorMap,
+ Assignee: assigneeOperatorMap,
+ StringArray: stringArrayOperatorMap,
+ Semver: semverOperatorMap,
+}
+
+export function chooseOperatorMap(propertyType: PropertyType | undefined): Record<string, string> {
+ let choice = genericOperatorMap
+ if (propertyType) {
+ choice = operatorMappingChoice[propertyType] || genericOperatorMap
+ }
+ return choice
+}
+
+export function isOperatorMulti(operator: PropertyOperator): boolean {
+ return [
+ PropertyOperator.Exact,
+ PropertyOperator.IsNot,
+ PropertyOperator.IContainsMulti,
+ PropertyOperator.NotIContainsMulti,
+ ].includes(operator)
+}
+
+export function isOperatorFlag(operator: PropertyOperator): boolean {
+ // these filter operators can only be just set, no additional parameter
+ return [PropertyOperator.IsSet, PropertyOperator.IsNotSet, PropertyOperator.In, PropertyOperator.NotIn].includes(
+ operator
+ )
+}
+
+export function isOperatorCohort(operator: PropertyOperator): boolean {
+ // these filter operators use value different ( to represent the number of the cohort )
+ return [PropertyOperator.In, PropertyOperator.NotIn].includes(operator)
+}
+
+export function isOperatorRegex(operator: PropertyOperator): boolean {
+ return [PropertyOperator.Regex, PropertyOperator.NotRegex].includes(operator)
+}
+
+export function isOperatorSemver(operator: PropertyOperator): boolean {
+ return [
+ PropertyOperator.SemverEq,
+ PropertyOperator.SemverNeq,
+ PropertyOperator.SemverGt,
+ PropertyOperator.SemverGte,
+ PropertyOperator.SemverLt,
+ PropertyOperator.SemverLte,
+ PropertyOperator.SemverTilde,
+ PropertyOperator.SemverCaret,
+ PropertyOperator.SemverWildcard,
+ ].includes(operator)
+}
+
+export function isOperatorRange(operator: PropertyOperator): boolean {
+ return [
+ PropertyOperator.GreaterThan,
+ PropertyOperator.GreaterThanOrEqual,
+ PropertyOperator.LessThan,
+ PropertyOperator.LessThanOrEqual,
+ PropertyOperator.Between,
+ PropertyOperator.NotBetween,
+ ].includes(operator)
+}
+
+export function isOperatorDate(operator: PropertyOperator): boolean {
+ return [PropertyOperator.IsDateBefore, PropertyOperator.IsDateAfter, PropertyOperator.IsDateExact].includes(
+ operator
+ )
+}
+
+export function isOperatorBetween(operator: PropertyOperator): boolean {
+ return [PropertyOperator.Between, PropertyOperator.NotBetween].includes(operator)
+}
diff --git a/frontend/src/lib/utils/parseMarkdownToTipTap.ts b/frontend/src/lib/utils/parseMarkdownToTipTap.ts
index bc8dded674d1..34b11fe3be26 100644
--- a/frontend/src/lib/utils/parseMarkdownToTipTap.ts
+++ b/frontend/src/lib/utils/parseMarkdownToTipTap.ts
@@ -5,7 +5,7 @@ import { Table, TableCell, TableHeader, TableRow } from '@tiptap/extension-table
import { MarkdownManager } from '@tiptap/markdown'
import StarterKit from '@tiptap/starter-kit'
-import { expandFlattenedMarkdownTables } from 'lib/utils/expandFlattenedMarkdownTables'
+import { expandFlattenedMarkdownTables } from 'lib/utils/markdown'
const markdownManager = new MarkdownManager({
extensions: [
diff --git a/frontend/src/lib/utils/person-actions.ts b/frontend/src/lib/utils/person-actions.ts
deleted file mode 100644
index 331c5a5d6ec3..000000000000
--- a/frontend/src/lib/utils/person-actions.ts
+++ /dev/null
@@ -1,19 +0,0 @@
-import { lemonToast } from '@posthog/lemon-ui'
-
-import api from 'lib/api'
-
-export const openInAdminPanel = async (email: string): Promise<void> => {
- try {
- const response = await api.users.list(email)
-
- if (!response.results || response.results.length === 0) {
- throw new Error('User not found')
- }
-
- const userId = response.results[0].id
- window.open(`/admin/posthog/user/${userId}/change/`, '_blank')
- } catch (error) {
- const message = error instanceof Error ? error.message : String(error)
- lemonToast.error(`Failed to open admin panel: ${message}`)
- }
-}
diff --git a/frontend/src/lib/utils/primaryEventProperty.test.ts b/frontend/src/lib/utils/primaryEventProperty.test.ts
deleted file mode 100644
index b13617dbafbb..000000000000
--- a/frontend/src/lib/utils/primaryEventProperty.test.ts
+++ /dev/null
@@ -1,96 +0,0 @@
-import {
- getEventsWithPrimaryProperty,
- getPrimaryPropertyForEvent,
- hasTaxonomyPrimaryProperty,
-} from './primaryEventProperty'
-
-describe('getPrimaryPropertyForEvent', () => {
- it('returns the core taxonomy default for built-in events', () => {
- expect(getPrimaryPropertyForEvent('$pageview')).toBe('$pathname')
- expect(getPrimaryPropertyForEvent('$pageleave')).toBe('$pathname')
- expect(getPrimaryPropertyForEvent('$screen')).toBe('$screen_name')
- expect(getPrimaryPropertyForEvent('$feature_flag_called')).toBe('$feature_flag')
- })
-
- it('returns null for events with no taxonomy default and no override', () => {
- expect(getPrimaryPropertyForEvent('$autocapture')).toBeNull()
- expect(getPrimaryPropertyForEvent('some_custom_event')).toBeNull()
- })
-
- it('returns null for missing event names', () => {
- expect(getPrimaryPropertyForEvent(null)).toBeNull()
- expect(getPrimaryPropertyForEvent(undefined)).toBeNull()
- expect(getPrimaryPropertyForEvent('')).toBeNull()
- })
-
- it('ignores team-configured overrides for events that have a taxonomy default', () => {
- // Taxonomy is immutable — users can only set primary properties for events
- // without a fixed taxonomy entry.
- expect(getPrimaryPropertyForEvent('$pageview', { $pageview: '$current_url' })).toBe('$pathname')
- expect(getPrimaryPropertyForEvent('$screen', { $screen: 'my_custom_prop' })).toBe('$screen_name')
- })
-
- it('uses the team-configured override for custom events with no taxonomy default', () => {
- expect(getPrimaryPropertyForEvent('order_placed', { order_placed: 'order_id' })).toBe('order_id')
- })
-
- it('returns null when no override and no taxonomy default', () => {
- expect(getPrimaryPropertyForEvent('order_placed', { other_event: 'x' })).toBeNull()
- })
-})
-
-describe('getEventsWithPrimaryProperty', () => {
- it('returns events that have a taxonomy default', () => {
- const events = [
- { event: '$pageview', id: 1 },
- { event: '$autocapture', id: 2 },
- { event: '$screen', id: 3 },
- ]
- expect(getEventsWithPrimaryProperty(events)).toEqual([
- { event: '$pageview', id: 1 },
- { event: '$screen', id: 3 },
- ])
- })
-
- it('returns events that have a team override (no taxonomy default)', () => {
- const events = [
- { event: 'order_placed', id: 1 },
- { event: 'just_viewed', id: 2 },
- ]
- expect(getEventsWithPrimaryProperty(events, { order_placed: 'order_id' })).toEqual([
- { event: 'order_placed', id: 1 },
- ])
- })
-
- it('does not include events whose only override is on a taxonomy-fixed event', () => {
- // Taxonomy wins, so an attempted override on $pageview is moot — but the event is still
- // included because the taxonomy default already counts as a primary property.
- const events = [{ event: '$pageview', id: 1 }]
- expect(getEventsWithPrimaryProperty(events, { $pageview: '$current_url' })).toEqual(events)
- })
-
- it('returns an empty list when nothing has a primary property', () => {
- const events = [
- { event: '$autocapture', id: 1 },
- { event: 'arbitrary_custom', id: 2 },
- ]
- expect(getEventsWithPrimaryProperty(events)).toEqual([])
- })
-})
-
-describe('hasTaxonomyPrimaryProperty', () => {
- it('is true for built-in events that have a primary property', () => {
- expect(hasTaxonomyPrimaryProperty('$pageview')).toBe(true)
- expect(hasTaxonomyPrimaryProperty('$pageleave')).toBe(true)
- expect(hasTaxonomyPrimaryProperty('$screen')).toBe(true)
- expect(hasTaxonomyPrimaryProperty('$feature_flag_called')).toBe(true)
- })
-
- it('is false for events with no taxonomy primary property', () => {
- expect(hasTaxonomyPrimaryProperty('$autocapture')).toBe(false)
- expect(hasTaxonomyPrimaryProperty('order_placed')).toBe(false)
- expect(hasTaxonomyPrimaryProperty(null)).toBe(false)
- expect(hasTaxonomyPrimaryProperty(undefined)).toBe(false)
- expect(hasTaxonomyPrimaryProperty('')).toBe(false)
- })
-})
diff --git a/frontend/src/lib/utils/primaryEventProperty.ts b/frontend/src/lib/utils/primaryEventProperty.ts
deleted file mode 100644
index 73cf68673ad1..000000000000
--- a/frontend/src/lib/utils/primaryEventProperty.ts
+++ /dev/null
@@ -1,42 +0,0 @@
-import { CORE_FILTER_DEFINITIONS_BY_GROUP } from '~/taxonomy/taxonomy'
-
-export function hasTaxonomyPrimaryProperty(eventName: string | null | undefined): boolean {
- return !!eventName && !!CORE_FILTER_DEFINITIONS_BY_GROUP.events[eventName]?.primary_property
-}
-
-/**
- * Resolves the single property whose value a UI should display alongside an event.
- *
- * Taxonomy-configured defaults (e.g. `$pageview` -> `$pathname`) are immutable and
- * always win; team-configured overrides only apply to events that do not have a
- * taxonomy default.
- *
- * This is a pure client-side lookup — both the taxonomy and the overrides map are
- * already in memory, so callers can invoke this in tight loops (e.g. selectors
- * filtering all events in a session) without n+1 risk.
- */
-export function getPrimaryPropertyForEvent(
- eventName: string | null | undefined,
- overrides?: Record<string, string | null | undefined>
-): string | null {
- if (!eventName) {
- return null
- }
- const taxonomyDefault = CORE_FILTER_DEFINITIONS_BY_GROUP.events[eventName]?.primary_property
- if (taxonomyDefault) {
- return taxonomyDefault
- }
- return overrides?.[eventName] ?? null
-}
-
-/**
- * Filters a list of events down to those that have a primary property
- * (taxonomy default or team override). Pure client-side — wraps
- * `getPrimaryPropertyForEvent` so the intent reads as one operation.
- */
-export function getEventsWithPrimaryProperty<T extends { event: string }>(
- events: T[],
- overrides?: Record<string, string | null | undefined>
-): T[] {
- return events.filter((e) => getPrimaryPropertyForEvent(e.event, overrides) !== null)
-}
diff --git a/frontend/src/lib/utils/random.ts b/frontend/src/lib/utils/random.ts
deleted file mode 100644
index a6520c0c8f63..000000000000
--- a/frontend/src/lib/utils/random.ts
+++ /dev/null
@@ -1,15 +0,0 @@
-export function createSeededRandom(seed: number): () => number {
- // LCG constants from Numerical Recipes
- let m = 0x80000000 // 2^31
- let a = 1103515245
- let c = 12345
-
- let state = seed ? seed : Math.floor(Math.random() * (m - 1))
-
- return function () {
- state = (a * state + c) % m
- return state / m
- }
-}
-
-export const deterministicRandom = createSeededRandom(1234)
diff --git a/frontend/src/lib/utils/requests.ts b/frontend/src/lib/utils/requests.ts
new file mode 100644
index 000000000000..65b05ff98eeb
--- /dev/null
+++ b/frontend/src/lib/utils/requests.ts
@@ -0,0 +1,12 @@
+/** We issue a cancel request, when the request is aborted or times out (frontend side), since in these cases the backend query might still be running. */
+export function shouldCancelQuery(error: any): boolean {
+ return isAbortedRequest(error) || isTimedOutRequest(error)
+}
+
+export function isAbortedRequest(error: any): boolean {
+ return error.name === 'AbortError' || error.message?.name === 'AbortError'
+}
+
+export function isTimedOutRequest(error: any): boolean {
+ return error.status === 504
+}
diff --git a/frontend/src/lib/utils/sceneLogicUtils.ts b/frontend/src/lib/utils/sceneLogicUtils.ts
deleted file mode 100644
index 25a2313225ac..000000000000
--- a/frontend/src/lib/utils/sceneLogicUtils.ts
+++ /dev/null
@@ -1,39 +0,0 @@
-import { Params } from 'scenes/sceneTypes'
-
-/**
- * Forwards whitelisted query parameters from the current URL to the redirect URL.
- * Only forwards params that exist in the current URL and don't already exist in the redirect URL.
- * This is specifically used for scene redirects to maintain important query parameters across redirects.
- */
-export function withForwardedSearchParams(
- redirectUrl: string,
- currentSearchParams: Params,
- forwardedQueryParams: string[]
-): string {
- // If no params to forward, return the original URL
- if (!forwardedQueryParams?.length) {
- return redirectUrl
- }
-
- const redirectUrlObj = new URL(redirectUrl, window.location.origin)
- const redirectSearchParams = new URLSearchParams(redirectUrlObj.search)
- let paramsWereForwarded = false
-
- // For each whitelisted param that exists in current URL
- forwardedQueryParams.forEach((param) => {
- if (currentSearchParams[param] !== undefined && !redirectSearchParams.has(param)) {
- redirectSearchParams.set(param, currentSearchParams[param])
- paramsWereForwarded = true
- }
- })
-
- // Only modify the URL if we actually forwarded any params
- if (!paramsWereForwarded) {
- return redirectUrl
- }
-
- // Reconstruct the URL with the forwarded params
- redirectUrlObj.search = redirectSearchParams.toString()
- // Return just the pathname and search to avoid origin being included
- return redirectUrlObj.pathname + redirectUrlObj.search + redirectUrlObj.hash
-}
diff --git a/frontend/src/lib/utils/semver.test.ts b/frontend/src/lib/utils/semver.test.ts
index 67ee07860fc7..36ce05429bff 100644
--- a/frontend/src/lib/utils/semver.test.ts
+++ b/frontend/src/lib/utils/semver.test.ts
@@ -1,4 +1,4 @@
-import { createVersionChecker, highestVersion, lowestVersion, parseVersion, versionToString } from './semver'
+import { createVersionChecker, parseVersion } from './semver'
describe('semver', () => {
describe('parseVersion', () => {
@@ -17,41 +17,6 @@ describe('semver', () => {
})
})
- describe('lowerVersion', () => {
- it('should return the lower version', () => {
- expect(lowestVersion(['1.0.0', '1.0.1', '1.0.2'])).toEqual({ major: 1, minor: 0, patch: 0 })
- expect(lowestVersion(['1.0.0', '1.0', '1'])).toEqual({ major: 1, minor: 0, patch: 0 })
- expect(lowestVersion(['1.10', '1.2'])).toEqual({ major: 1, minor: 2 })
- expect(lowestVersion(['1.2.3', '1.2.3-alpha'])).toEqual({ major: 1, minor: 2, patch: 3, extra: 'alpha' })
- expect(lowestVersion(['1.2.3-alpha1', '1.2.3-alpha2'])).toEqual({
- major: 1,
- minor: 2,
- patch: 3,
- extra: 'alpha1',
- })
- })
- })
- describe('higherVersion', () => {
- it('should return the higher version', () => {
- expect(highestVersion(['1.0.0', '1.0.1', '1.0.2'])).toEqual({ major: 1, minor: 0, patch: 2 })
- expect(highestVersion(['1.0.0', '1.0', '1'])).toEqual({ major: 1 })
- expect(highestVersion(['1.10', '1.2'])).toEqual({ major: 1, minor: 10 })
- expect(highestVersion(['1.2.3', '1.2.3-alpha'])).toEqual({ major: 1, minor: 2, patch: 3 })
- expect(highestVersion(['1.2.3-alpha1', '1.2.3-alpha2'])).toEqual({
- major: 1,
- minor: 2,
- patch: 3,
- extra: 'alpha2',
- })
- })
- })
- describe('versionToString', () => {
- it('should convert version to string', () => {
- expect(versionToString({ major: 1, minor: 2, patch: 3 })).toEqual('1.2.3')
- expect(versionToString({ major: 1, minor: 2 })).toEqual('1.2')
- expect(versionToString({ major: 1 })).toEqual('1')
- })
- })
describe('createVersionChecker', () => {
it('should create a version checker that checks that a version is above or equal to a specified version', () => {
const isSupportedVersion = createVersionChecker('4.5.6')
diff --git a/frontend/src/lib/utils/semver.ts b/frontend/src/lib/utils/semver.ts
index 79cf377c5158..30a4da16fb03 100644
--- a/frontend/src/lib/utils/semver.ts
+++ b/frontend/src/lib/utils/semver.ts
@@ -27,14 +27,6 @@ export function parseVersion(version: string): SemanticVersion {
return { major: majorInt, minor: minorInt, patch: patchInt, extra }
}
-export function tryParseVersion(version: string): SemanticVersion | null {
- try {
- return parseVersion(version)
- } catch {
- return null
- }
-}
-
export interface SemanticVersionDiff {
kind: 'major' | 'minor' | 'patch' | 'extra'
diff: number
@@ -80,33 +72,6 @@ export function compareVersion(a: string | SemanticVersion, b: string | Semantic
return diff.diff
}
-export function lowestVersion(versions: (string | SemanticVersion)[]): SemanticVersion {
- const parsed = versions.map((v) => (typeof v === 'string' ? parseVersion(v) : v))
- // we expect this list to be small, so don't worry about nlogn vs n from using sort
- parsed.sort(compareVersion)
- return parsed[0]
-}
-
-export function highestVersion(versions: (string | SemanticVersion)[]): SemanticVersion {
- const parsed = versions.map((v) => (typeof v === 'string' ? parseVersion(v) : v))
- parsed.sort(compareVersion)
- return parsed[parsed.length - 1]
-}
-
-export function isEqualVersion(a: string | SemanticVersion, b: string | SemanticVersion): boolean {
- return diffVersions(a, b) === null
-}
-
-export function versionToString(version: SemanticVersion): string {
- const versionPart = `${version.major}${
- version.minor != null ? `.${version.minor}${version.patch != null ? `.${version.patch}` : ''}` : ''
- }`
- if (version.extra) {
- return `${versionPart}-${version.extra}`
- }
- return versionPart
-}
-
export function createVersionChecker(requiredVersion: string | SemanticVersion) {
return (version: string | SemanticVersion): boolean => {
const diff = diffVersions(version, requiredVersion)
diff --git a/frontend/src/lib/utils/slackChannelValue.test.ts b/frontend/src/lib/utils/slackChannelValue.test.ts
index 6969a42076e4..c6e8fdb939f7 100644
--- a/frontend/src/lib/utils/slackChannelValue.test.ts
+++ b/frontend/src/lib/utils/slackChannelValue.test.ts
@@ -1,17 +1,9 @@
import {
getSlackChannelDisplayLabelFromTargetValueSegment,
- getSlackChannelIdFromTargetValue,
parseCommaSeparatedSlackTargetDisplayLabels,
- parseSlackTargetForAlertPayload,
} from './slackChannelValue'
describe('slackChannelValue', () => {
- it('getSlackChannelIdFromTargetValue returns id before first pipe', () => {
- expect(getSlackChannelIdFromTargetValue('C123|#general')).toBe('C123')
- expect(getSlackChannelIdFromTargetValue(' C123 |#general')).toBe('C123')
- expect(getSlackChannelIdFromTargetValue('C123')).toBe('C123')
- })
-
it('getSlackChannelDisplayLabelFromTargetValueSegment returns hash label or full value', () => {
expect(getSlackChannelDisplayLabelFromTargetValueSegment('C123|#general')).toBe('#general')
expect(getSlackChannelDisplayLabelFromTargetValueSegment('C123')).toBe('C123')
@@ -23,12 +15,4 @@ describe('slackChannelValue', () => {
expect(parseCommaSeparatedSlackTargetDisplayLabels('C1|#a, C2|#b')).toEqual(['#a', '#b'])
expect(parseCommaSeparatedSlackTargetDisplayLabels('C1|#a, , C2|#b')).toEqual(['#a', '#b'])
})
-
- it('parseSlackTargetForAlertPayload returns id and name without hash', () => {
- expect(parseSlackTargetForAlertPayload('C123|#general')).toEqual({
- channelId: 'C123',
- channelName: 'general',
- })
- expect(parseSlackTargetForAlertPayload('C123')).toEqual({ channelId: 'C123', channelName: 'C123' })
- })
})
diff --git a/frontend/src/lib/utils/slackChannelValue.ts b/frontend/src/lib/utils/slackChannelValue.ts
index 0fede54581db..e8fbf5ebeaf6 100644
--- a/frontend/src/lib/utils/slackChannelValue.ts
+++ b/frontend/src/lib/utils/slackChannelValue.ts
@@ -1,13 +1,3 @@
-/**
- * Slack destinations in PostHog use `channelId|#channel-name` (see SlackIntegrationHelpers
- * option keys). Some stored values are channel id only until channels are loaded.
- */
-
-export function getSlackChannelIdFromTargetValue(value: string): string {
- const [channelId = ''] = value.split('|')
- return channelId.trim()
-}
-
/**
* Human-facing label for one comma-separated segment: `#name` after the first `|`, or the
* whole value when there is no pipe (e.g. raw id before resolution).
@@ -27,17 +17,3 @@ export function parseCommaSeparatedSlackTargetDisplayLabels(targetValue: string)
.map((part) => getSlackChannelDisplayLabelFromTargetValueSegment(part))
.filter((x): x is string => Boolean(x))
}
-
-/** For alert notification payloads: id segment and name without leading `#`, defaulting id when missing. */
-export function parseSlackTargetForAlertPayload(value: string): { channelId: string; channelName: string } {
- const channelId = getSlackChannelIdFromTargetValue(value)
- const pipe = value.indexOf('|')
- if (pipe === -1) {
- return { channelId, channelName: channelId }
- }
- const rawName = value
- .slice(pipe + 1)
- .trim()
- .replace(/^#/, '')
- return { channelId, channelName: rawName || channelId }
-}
diff --git a/frontend/src/lib/utils/stringWithWBR.tsx b/frontend/src/lib/utils/stringWithWBR.tsx
index d93de7a40fd0..088a9fe56755 100644
--- a/frontend/src/lib/utils/stringWithWBR.tsx
+++ b/frontend/src/lib/utils/stringWithWBR.tsx
@@ -1,3 +1,4 @@
+// Kept in a separate file and not ./strings.ts because this one requires .tsx extension
export default function stringWithWBR(text: string, splitAt = 30): JSX.Element {
const addWBRAfter = [',', '.', '/', '\\']
const naturalSplit = [' ', '-']
diff --git a/frontend/src/lib/utils/strings.test.ts b/frontend/src/lib/utils/strings.test.ts
new file mode 100644
index 000000000000..71edf6c2ec11
--- /dev/null
+++ b/frontend/src/lib/utils/strings.test.ts
@@ -0,0 +1,110 @@
+import {
+ capitalizeFirstLetter,
+ endWithPunctation,
+ ensureStringIsNotBlank,
+ identifierToHuman,
+ midEllipsis,
+ pluralize,
+ wordPluralize,
+} from 'lib/utils/strings'
+
+describe('strings utils', () => {
+ describe('capitalizeFirstLetter()', () => {
+ it('returns the capitalized string', () => {
+ expect(capitalizeFirstLetter('jane')).toEqual('Jane')
+ expect(capitalizeFirstLetter('hello there!')).toEqual('Hello there!')
+ expect(capitalizeFirstLetter('underscores_make_no_difference')).toEqual('Underscores_make_no_difference')
+ })
+ })
+
+ describe('identifierToHuman()', () => {
+ it('humanizes properly', () => {
+ expect(identifierToHuman('testIdentifier')).toEqual('Test identifier')
+ expect(identifierToHuman('testIdentifierX')).toEqual('Test identifier x')
+ expect(identifierToHuman('something ')).toEqual('Something')
+ expect(identifierToHuman(' some_property')).toEqual('Some property')
+ expect(identifierToHuman(' Number666')).toEqual('Number 666')
+ expect(identifierToHuman('7x')).toEqual('7x')
+ expect(identifierToHuman('7X')).toEqual('7 x')
+ expect(identifierToHuman('500')).toEqual('500')
+ expect(identifierToHuman(404)).toEqual('404')
+ expect(identifierToHuman('CreateProject')).toEqual('Create project')
+ expect(identifierToHuman('hog_function/transformation')).toEqual('Hog function transformation')
+ })
+ })
+
+ describe('midEllipsis()', () => {
+ it('returns same string if short', () => {
+ expect(midEllipsis('12', 10)).toEqual('12')
+ expect(midEllipsis('1234567890', 10)).toEqual('1234567890')
+ })
+
+ it('formats string properly', () => {
+ expect(midEllipsis('1234567890', 2)).toEqual('1…')
+ expect(midEllipsis('1234567890', 4)).toEqual('12…0')
+ expect(midEllipsis('1234567890', 8)).toEqual('1234…890')
+ expect(midEllipsis('1234567890', 9)).toEqual('1234…7890')
+ expect(midEllipsis('ZgZbZgD9Z4U2FsohDYAJ-hMdoxY7-oSdWwrEWtdBeM', 26)).toEqual('ZgZbZgD9Z4U2F…SdWwrEWtdBeM')
+ expect(midEllipsis('ZgZbZgD9Z4U2FsohDYAJ-hMdoxY7-oSdWwrEWtdBeM', 25)).toEqual('ZgZbZgD9Z4U2…SdWwrEWtdBeM')
+ expect(midEllipsis('ZgZbZgD9Z4U2FsohDYAJ-hMdoxY7-oSdWwrEWtdBeM', 24)).toEqual('ZgZbZgD9Z4U2…dWwrEWtdBeM')
+ })
+ })
+
+ describe('pluralize()', () => {
+ it('handles singular cases', () => {
+ expect(pluralize(1, 'member')).toEqual('1 member')
+ expect(pluralize(1, 'bacterium', 'bacteria', true)).toEqual('1 bacterium')
+ expect(pluralize(1, 'word', undefined, false)).toEqual('word')
+ })
+ it('handles plural cases', () => {
+ expect(pluralize(28321, 'member')).toEqual('28,321 members')
+ expect(pluralize(99, 'bacterium', 'bacteria')).toEqual('99 bacteria')
+ expect(pluralize(3, 'word', undefined, false)).toEqual('words')
+ })
+ })
+
+ describe('wordPluralize()', () => {
+ it('handles singular cases', () => {
+ expect(wordPluralize('company')).toEqual('companies')
+ expect(wordPluralize('person')).toEqual('people')
+ expect(wordPluralize('bacterium')).toEqual('bacteria')
+ expect(wordPluralize('word')).toEqual('words')
+ expect(wordPluralize('child')).toEqual('children')
+ expect(wordPluralize('knife')).toEqual('knives')
+ })
+
+ it('returns falsy input unchanged without throwing', () => {
+ expect(wordPluralize('')).toEqual('')
+ expect(wordPluralize(null as unknown as string)).toEqual('')
+ expect(wordPluralize(undefined as unknown as string)).toEqual('')
+ })
+ })
+
+ describe('endWithPunctation()', () => {
+ it('adds period at the end when needed', () => {
+ expect(endWithPunctation('Hello')).toEqual('Hello.')
+ expect(endWithPunctation('Learn more! ')).toEqual('Learn more!')
+ expect(endWithPunctation('Stop.')).toEqual('Stop.')
+ expect(endWithPunctation(null)).toEqual('')
+ expect(endWithPunctation(' ')).toEqual('')
+ expect(endWithPunctation(' Why? ')).toEqual('Why?')
+ })
+ })
+
+ describe('ensureStringIsNotBlank()', () => {
+ it('handles unusual input', () => {
+ expect(ensureStringIsNotBlank(null)).toEqual(null)
+ expect(ensureStringIsNotBlank({} as any)).toEqual(null)
+ expect(ensureStringIsNotBlank(undefined)).toEqual(null)
+ expect(ensureStringIsNotBlank(true as any)).toEqual(null)
+ })
+ it('handles blank strings as expected', () => {
+ expect(ensureStringIsNotBlank('')).toEqual(null)
+ expect(ensureStringIsNotBlank(' ')).toEqual(null)
+ })
+ it('handles happy case', () => {
+ expect(ensureStringIsNotBlank('happyboy')).toEqual('happyboy')
+ expect(ensureStringIsNotBlank(' happy boy ')).toEqual(' happy boy ')
+ })
+ })
+})
diff --git a/frontend/src/lib/utils/strings.ts b/frontend/src/lib/utils/strings.ts
new file mode 100644
index 000000000000..fadb05bfecc8
--- /dev/null
+++ b/frontend/src/lib/utils/strings.ts
@@ -0,0 +1,211 @@
+import { humanFriendlyNumber } from 'lib/utils/numbers'
+
+export function toSentenceCase(str: string): string {
+ return str.replace(/\b\w/g, (c) => c.toUpperCase())
+}
+
+export function splitKebabCase(string: string): string {
+ return string.replace(/-/g, ' ')
+}
+
+export function capitalizeFirstLetter(string: string): string {
+ return string.charAt(0).toUpperCase() + string.slice(1)
+}
+
+export function lowercaseFirstLetter(string: string): string {
+ return string.charAt(0).toLowerCase() + string.slice(1)
+}
+
+export function getOrdinalSuffix(num: number): string {
+ const j = num % 10
+ const k = num % 100
+ if (j === 1 && k !== 11) {
+ return 'st'
+ }
+ if (j === 2 && k !== 12) {
+ return 'nd'
+ }
+ if (j === 3 && k !== 13) {
+ return 'rd'
+ }
+ return 'th'
+}
+
+export function fullName(props?: { first_name?: string; last_name?: string }): string {
+ if (!props) {
+ return 'Unknown User'
+ }
+ return `${props.first_name || ''} ${props.last_name || ''}`.trim()
+}
+
+// trimBothEnds=false is useful when the input is slugified as the user is typing to allow them hitting space and continue typing
+export function slugify(
+ text: string,
+ { trimBothEnds = true, lowercase = true }: { trimBothEnds?: boolean; lowercase?: boolean } = {}
+): string {
+ let result = text.toString()
+ if (lowercase) {
+ result = result.toLowerCase()
+ }
+ return result
+ .normalize('NFD') // The normalize() method returns the Unicode Normalization Form of a given string.
+ [trimBothEnds ? 'trim' : 'trimStart']()
+ .replace(/\s+/g, '-') // Replace spaces with -
+ .replace(/[^\w-]+/g, '') // Remove all non-word chars
+ .replace(/--+/g, '-')
+}
+
+export function truncate(str: string, maxLength: number): string {
+ return str.length > maxLength ? str.slice(0, maxLength - 1) + '...' : str
+}
+
+/** Convert camelCase, PascalCase or snake_case to Sentence case or Title Case. */
+export function identifierToHuman(identifier: string | number, caseType: 'sentence' | 'title' = 'sentence'): string {
+ const words: string[] = []
+ let currentWord: string = ''
+ String(identifier)
+ .trim()
+ .split('')
+ .forEach((character) => {
+ if (character === '_' || character === '-' || character === '/') {
+ if (currentWord) {
+ words.push(currentWord)
+ }
+ currentWord = ''
+ } else if (
+ character === character.toLowerCase() &&
+ (!'0123456789'.includes(character) ||
+ (currentWord && '0123456789'.includes(currentWord[currentWord.length - 1])))
+ ) {
+ currentWord += character
+ } else {
+ if (currentWord) {
+ words.push(currentWord)
+ }
+ currentWord = character.toLowerCase()
+ }
+ })
+ if (currentWord) {
+ words.push(currentWord)
+ }
+ return capitalizeFirstLetter(
+ words.map((word) => (caseType === 'sentence' ? word : capitalizeFirstLetter(word))).join(' ')
+ )
+}
+
+export function hashCodeForString(s: string): number {
+ /* Hash function that returns a number for a given string. Useful for using the same colors for tags or avatars.
+ Forked from https://github.com/segmentio/evergreen/
+ */
+ let hash = 0
+ if (s.trim().length === 0) {
+ return hash
+ }
+ for (let i = 0; i < s.length; i++) {
+ const char = s.charCodeAt(i)
+ hash = (hash << 5) - hash + char
+ hash &= hash // Convert to 32bit integer
+ }
+ return Math.abs(hash)
+}
+
+/** Truncates a string (`input`) in the middle. `maxLength` represents the desired maximum length of the output. */
+export function midEllipsis(input: string, maxLength: number): string {
+ if (input.length <= maxLength) {
+ return input
+ }
+
+ const middle = Math.ceil(input.length / 2)
+ const excessLeft = Math.ceil((input.length - maxLength) / 2)
+ const excessRight = Math.ceil((input.length - maxLength + 1) / 2)
+ return `${input.slice(0, middle - excessLeft)}…${input.slice(middle + excessRight)}`
+}
+
+export function pluralize(count: number, singular: string, plural?: string, includeNumber: boolean = true): string {
+ if (!plural) {
+ plural = singular + 's'
+ }
+ const form = count === 1 ? singular : plural
+ return includeNumber ? `${humanFriendlyNumber(count)} ${form}` : form
+}
+
+const WORD_PLURALIZATION_RULES = [
+ [/s?$/i, 's'],
+ [/([^aeiou]ese)$/i, '$1'],
+ [/(ax|test)is$/i, '$1es'],
+ [/(alias|[^aou]us|t[lm]as|gas|ris)$/i, '$1es'],
+ [/(e[mn]u)s?$/i, '$1s'],
+ [/([^l]ias|[aeiou]las|[ejzr]as|[iu]am)$/i, '$1'],
+ [/(alumn|syllab|vir|radi|nucle|fung|cact|stimul|termin|bacill|foc|uter|loc|strat)(?:us|i)$/i, '$1i'],
+ [/(alumn|alg|vertebr)(?:a|ae)$/i, '$1ae'],
+ [/(seraph|cherub)(?:im)?$/i, '$1im'],
+ [/(her|at|gr)o$/i, '$1oes'],
+ [
+ /(agend|addend|millenni|dat|extrem|bacteri|desiderat|strat|candelabr|errat|ov|symposi|curricul|automat|quor)(?:a|um)$/i,
+ '$1a',
+ ],
+ [/(apheli|hyperbat|periheli|asyndet|noumen|phenomen|criteri|organ|prolegomen|hedr|automat)(?:a|on)$/i, '$1a'],
+ [/sis$/i, 'ses'],
+ [/(?:(kni|wi|li)fe|(ar|l|ea|eo|oa|hoo)f)$/i, '$1$2ves'],
+ [/([^aeiouy]|qu)y$/i, '$1ies'],
+ [/([^ch][ieo][ln])ey$/i, '$1ies'],
+ [/(x|ch|ss|sh|zz)$/i, '$1es'],
+ [/(matr|cod|mur|sil|vert|ind|append)(?:ix|ex)$/i, '$1ices'],
+ [/\b((?:tit)?m|l)(?:ice|ouse)$/i, '$1ice'],
+ [/(pe)(?:rson|ople)$/i, '$1ople'],
+ [/(child)(?:ren)?$/i, '$1ren'],
+ [/eaux$/i, '$0'],
+ [/m[ae]n$/i, 'men'],
+] as [RegExp, string][]
+
+export function wordPluralize(word: string): string {
+ if (!word) {
+ return word ?? ''
+ }
+
+ let len = WORD_PLURALIZATION_RULES.length
+
+ // Iterate over the sanitization rules and use the first one to match.
+ while (len--) {
+ const [regex, replacement] = WORD_PLURALIZATION_RULES[len]
+ if (regex.test(word)) {
+ return word.replace(regex, replacement)
+ }
+ }
+
+ return word
+}
+
+export const alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'.split('')
+
+export function endWithPunctation(text?: string | null): string {
+ let trimmedText = text?.trim()
+ if (!trimmedText) {
+ return ''
+ }
+ if (!/[.!?]$/.test(trimmedText)) {
+ trimmedText += '.'
+ }
+ return trimmedText
+}
+
+/** Join array of string into a list ("a, b, and c"). Uses the Oxford comma, but only if there are at least 3 items. */
+export function humanList(arr: readonly string[]): string {
+ return arr.length > 2 ? arr.slice(0, -1).join(', ') + ', and ' + arr.at(-1) : arr.join(' and ')
+}
+
+export function toString(input?: any): string {
+ return input?.toString() || ''
+}
+
+export function ensureStringIsNotBlank(s?: string | null): string | null {
+ return typeof s === 'string' && s.trim() !== '' ? s : null
+}
+
+export function isMultiSeriesFormula(formula?: string | null): boolean {
+ if (!formula) {
+ return false
+ }
+ const count = (formula.match(/[a-zA-Z]/g) || []).length
+ return count > 1
+}
diff --git a/frontend/src/lib/utils/stripMarkdown.test.ts b/frontend/src/lib/utils/stripMarkdown.test.ts
deleted file mode 100644
index 9edbce421f10..000000000000
--- a/frontend/src/lib/utils/stripMarkdown.test.ts
+++ /dev/null
@@ -1,44 +0,0 @@
-import { stripMarkdown } from './stripMarkdown'
-
-describe('stripMarkdown', () => {
- it.each([
- // Basic text
- ['plain text', 'plain text'],
-
- // Unordered lists with dashes
- ['- item 1\n- item 2\n- item 3', '- item 1\n- item 2\n- item 3'],
-
- // Ordered lists with numbers
- ['1. first\n2. second\n3. third', '1. first\n2. second\n3. third'],
-
- // Ordered list starting at different number
- ['5. fifth\n6. sixth', '5. fifth\n6. sixth'],
-
- // Links with URL preserved
- ['[click here](https://example.com)', 'click here (https://example.com)'],
- ['[PostHog](https://posthog.com/docs)', 'PostHog (https://posthog.com/docs)'],
-
- // Link without text
- ['[](https://example.com)', 'https://example.com'],
-
- // Relative links get prefixed with origin
- ['[docs](/docs/guide)', `docs (${window.location.origin}/docs/guide)`],
- ['[api](api/v1)', `api (${window.location.origin}/api/v1)`],
-
- // Bold/italic/code stripped
- ['**bold** and *italic*', 'bold and italic'],
- ['`inline code`', 'inline code'],
-
- // Headings stripped
- ['# Heading 1', 'Heading 1'],
- ['## Heading 2', 'Heading 2'],
-
- // Mixed content
- [
- '# Title\n\n- item 1\n- item 2\n\n[link](https://test.com)',
- 'Title\n\n- item 1\n- item 2\n\nlink (https://test.com)',
- ],
- ])('converts %j to %j', (input, expected) => {
- expect(stripMarkdown(input)).toBe(expected)
- })
-})
diff --git a/frontend/src/lib/utils/timestamps.ts b/frontend/src/lib/utils/timestamps.ts
deleted file mode 100644
index b8e96d661b54..000000000000
--- a/frontend/src/lib/utils/timestamps.ts
+++ /dev/null
@@ -1,29 +0,0 @@
-/**
- * Parse timestamp strings of form "1:23" or "00:01:23" into milliseconds
- * @param input - Timestamp string
- * @returns Number of milliseconds, or undefined if invalid
- */
-export function parseTimestampToMs(input?: string | null): number | undefined {
- if (input == null) {
- return undefined
- }
- const value = String(input).trim()
- if (!value.length) {
- return undefined
- }
-
- // Handle mm:ss or hh:mm:ss format
- const parts = value.split(':').map((p) => Number(p))
- if (parts.length > 1 && parts.length <= 3 && parts.every((n) => Number.isSafeInteger(n) && n >= 0)) {
- let seconds = 0
- if (parts.length === 2) {
- const [mm, ss] = parts
- seconds = mm * 60 + ss
- } else if (parts.length === 3) {
- const [hh, mm, ss] = parts
- seconds = hh * 3600 + mm * 60 + ss
- }
- return seconds * 1000
- }
- return undefined
-}
diff --git a/frontend/src/lib/utils/timezones.test.ts b/frontend/src/lib/utils/timezones.test.ts
new file mode 100644
index 000000000000..96d241b8da7b
--- /dev/null
+++ b/frontend/src/lib/utils/timezones.test.ts
@@ -0,0 +1,11 @@
+import { shortTimeZone } from 'lib/utils/timezones'
+
+describe('timezones utils', () => {
+ test('shortTimezone', () => {
+ expect(shortTimeZone('UTC')).toEqual('UTC')
+ // All timezones below don't observe DST for simplicity
+ expect(shortTimeZone('America/Phoenix')).toEqual('MST')
+ expect(shortTimeZone('Europe/Moscow')).toEqual('UTC+3')
+ expect(shortTimeZone('Asia/Tokyo')).toEqual('UTC+9')
+ })
+})
diff --git a/frontend/src/lib/utils/timezones.ts b/frontend/src/lib/utils/timezones.ts
new file mode 100644
index 000000000000..756ebf9828c6
--- /dev/null
+++ b/frontend/src/lib/utils/timezones.ts
@@ -0,0 +1,44 @@
+import posthog from 'posthog-js'
+
+import { dayjs } from 'lib/dayjs'
+
+/**
+ * Return the short timezone identifier for a specific timezone (e.g. BST, EST, PDT, UTC+2).
+ * @param timeZone E.g. 'America/New_York'
+ * @param atDate
+ */
+export function shortTimeZone(timeZone?: string, atDate?: Date): string | null {
+ const date = atDate ? new Date(atDate) : new Date()
+ try {
+ const localeTimeStringParts = date
+ .toLocaleTimeString('en-us', { timeZoneName: 'short', timeZone: timeZone || undefined })
+ .replace('GMT', 'UTC')
+ .split(' ')
+ return localeTimeStringParts[localeTimeStringParts.length - 1]
+ } catch (e) {
+ posthog.captureException(e)
+ return null
+ }
+}
+
+export function timeZoneLabel(timeZone: string, offset: number): string {
+ const formattedZone = timeZone.replace(/\//g, ' / ').replace(/_/g, ' ')
+ const sign = offset === 0 ? '±' : offset > 0 ? '+' : '-'
+ const hours = Math.floor(Math.abs(offset))
+ const minutes = Math.round((Math.abs(offset) % 1) * 60)
+ .toString()
+ .padStart(2, '0')
+
+ return `${formattedZone} (UTC${sign}${hours}:${minutes})`
+}
+
+export function humanTzOffset(timezone?: string): string {
+ const offset = dayjs().tz(timezone).utcOffset() / 60
+ if (!offset) {
+ return 'no offset'
+ }
+ const absoluteOffset = Math.abs(offset)
+ const hourForm = absoluteOffset === 1 ? 'hour' : 'hours'
+ const direction = offset > 0 ? 'ahead' : 'behind'
+ return `${absoluteOffset} ${hourForm} ${direction}`
+}
diff --git a/frontend/src/lib/utils/url.test.ts b/frontend/src/lib/utils/url.test.ts
new file mode 100644
index 000000000000..53089294009f
--- /dev/null
+++ b/frontend/src/lib/utils/url.test.ts
@@ -0,0 +1,300 @@
+import { getRelativeNextPath, isExternalLink, isURL, parseTagsFilter, toParams } from 'lib/utils/url'
+
+describe('url utils', () => {
+ describe('toParams', () => {
+ it('handles unusual input', () => {
+ expect(toParams({})).toEqual('')
+ expect(toParams([])).toEqual('')
+ expect(toParams(undefined as any)).toEqual('')
+ expect(toParams(null as any)).toEqual('')
+ })
+
+ it('can handle numeric values', () => {
+ const actual = toParams({ a: 123 })
+ expect(actual).toEqual('a=123')
+ })
+
+ it('encodes arrays as a single query param', () => {
+ const actual = toParams({ include: ['a', 'b'] })
+ expect(actual).toEqual('include=%5B%22a%22%2C%22b%22%5D')
+ })
+
+ it('can explode arrays to individual parameters', () => {
+ const actual = toParams({ include: ['a', 'b'] }, true)
+ expect(actual).toEqual('include=a&include=b')
+ })
+ })
+
+ describe('isURL()', () => {
+ it('recognizes URLs properly', () => {
+ expect(isURL('https://www.posthog.com')).toEqual(true)
+ expect(isURL('http://www.posthog.com')).toEqual(true)
+ expect(isURL('http://www.posthog.com:8000/images')).toEqual(true)
+ expect(isURL('http://localhost:8000/login?next=/insights')).toEqual(true)
+ expect(isURL('http://localhost:8000/activity/explore?properties=%5B%5D')).toEqual(true)
+ expect(isURL('https://apple.com/')).toEqual(true)
+ expect(isURL('https://stripe.com')).toEqual(true)
+ expect(isURL('https://spotify.com')).toEqual(true)
+ expect(isURL('https://sevenapp.events/')).toEqual(true)
+ expect(isURL('https://seven-stagingenv.web.app/')).toEqual(true)
+ expect(isURL('https://salesforce.co.uk/')).toEqual(true)
+ expect(isURL('https://valid.*.example.com')).toEqual(true)
+ expect(isURL('https://*.valid.com')).toEqual(true)
+ })
+
+ it('recognizes non-URLs properly', () => {
+ expect(isURL('1234567890')).toEqual(false)
+ expect(isURL('www.posthog')).toEqual(false)
+ expect(isURL('-.posthog')).toEqual(false)
+ expect(isURL('posthog.3')).toEqual(false)
+ expect(isURL(1)).toEqual(false)
+ expect(isURL(true)).toEqual(false)
+ expect(isURL(null)).toEqual(false)
+ expect(isURL('')).toEqual(false)
+ expect(isURL(' ')).toEqual(false)
+ expect(
+ isURL(
+ 'https://client.rrrr.alpha.dev.foo.bar/9RvDy6gCmic_srrKs1db?sourceOrigin=rrrr&embedded={%22hostContext%22:%22landing%22,%22hostType%22:%22web%22,%22type%22:%22popsync%22}&share=1&wrapperUrl=https%3A%2F%2Fuat.rrrr.io%2F9RvDy6gCmicxyz&save=1&initialSearch={%22sites%22:%22google.com,gettyimages.com%22,%22safe%22:true,%22q%22:%22Perro%22}&opcid=4360f861-ffff-4444-9999-5257065a7dc3&waitForToken=1'
+ )
+ ).toEqual(false)
+ })
+
+ it('rejects dangerous protocols (XSS prevention)', () => {
+ expect(isURL('javascript:alert(1)')).toEqual(false)
+ expect(isURL('javascript:alert(document.cookie)')).toEqual(false)
+ expect(isURL('JAVASCRIPT:alert(1)')).toEqual(false)
+ expect(isURL('data:text/html,<script>alert(1)</script>')).toEqual(false)
+ expect(isURL('vbscript:msgbox(1)')).toEqual(false)
+ expect(isURL('file:///etc/passwd')).toEqual(false)
+ })
+ })
+
+ describe('isExternalLink()', () => {
+ it('recognizes external links properly', () => {
+ expect(isExternalLink('http://www.posthog.com')).toEqual(true)
+ expect(isExternalLink('https://www.posthog.com')).toEqual(true)
+ expect(isExternalLink('mailto:[email protected]')).toEqual(true)
+ })
+
+ it('recognizes non-external links properly', () => {
+ expect(isExternalLink('path')).toEqual(false)
+ expect(isExternalLink('/path')).toEqual(false)
+ expect(isExternalLink(1)).toEqual(false)
+ expect(isExternalLink(true)).toEqual(false)
+ expect(isExternalLink(null)).toEqual(false)
+ })
+ })
+
+ describe('getRelativeNextPath', () => {
+ const location = {
+ origin: 'https://us.posthog.com',
+ protocol: 'https:',
+ host: 'us.posthog.com',
+ hostname: 'us.posthog.com',
+ href: 'https://us.posthog.com/',
+ } as Location
+
+ it('returns relative path for same-origin absolute URL', () => {
+ expect(getRelativeNextPath('https://us.posthog.com/test', location)).toBe('/test')
+ })
+
+ it('returns relative path for same-origin absolute URL with query and hash', () => {
+ expect(getRelativeNextPath('https://us.posthog.com/test?foo=bar#baz', location)).toBe('/test?foo=bar#baz')
+ })
+
+ it('returns relative path for encoded same-origin absolute URL', () => {
+ expect(getRelativeNextPath('https%3A%2F%2Fus.posthog.com%2Ftest', location)).toBe('/test')
+ })
+
+ it('returns relative path for root-relative path', () => {
+ expect(getRelativeNextPath('/test', location)).toBe('/test')
+ })
+
+ it('returns relative path for root-relative path with query and hash', () => {
+ expect(getRelativeNextPath('/test?foo=bar#baz', location)).toBe('/test?foo=bar#baz')
+ })
+
+ it('returns null for external absolute URL', () => {
+ expect(getRelativeNextPath('https://evil.com/test', location)).toBeNull()
+ })
+
+ it('returns null for encoded external absolute URL', () => {
+ expect(getRelativeNextPath('https%3A%2F%2Fevil.com%2Ftest', location)).toBeNull()
+ })
+
+ it('returns null for protocol-relative external URL', () => {
+ expect(getRelativeNextPath('//evil.com/test', location)).toBeNull()
+ })
+
+ it('returns null for empty string', () => {
+ expect(getRelativeNextPath('', location)).toBeNull()
+ })
+
+ it('returns null for malformed URL', () => {
+ expect(getRelativeNextPath('http://', location)).toBeNull()
+ expect(getRelativeNextPath('%%%%', location)).toBeNull()
+ })
+
+ it('returns null for non-string input', () => {
+ expect(getRelativeNextPath(null, location)).toBeNull()
+ expect(getRelativeNextPath(undefined, location)).toBeNull()
+ })
+
+ it('returns relative path for encoded root-relative path', () => {
+ expect(getRelativeNextPath('%2Ftest%2Ffoo%3Fbar%3Dbaz%23hash', location)).toBe('/test/foo?bar=baz#hash')
+ })
+
+ it('returns null for encoded protocol-relative URL', () => {
+ expect(getRelativeNextPath('%2F%2Fevil.com%2Ftest', location)).toBeNull()
+ })
+
+ it.each([
+ ['/\\evil.com/path', '/-then-backslash'],
+ ['/\\\\evil.com/path', '/-then-two-backslashes'],
+ ['%2F%5Cevil.com%2Fpath', 'encoded /-then-backslash'],
+ ])('returns null for backslash external bypass (%s — %s)', (input) => {
+ // Browsers normalize backslashes in special-scheme URLs per WHATWG, so /\\evil.com
+ // resolves to //evil.com and escapes the origin.
+ expect(getRelativeNextPath(input, location)).toBeNull()
+ })
+ })
+
+ describe('parseTagsFilter()', () => {
+ describe('array input', () => {
+ it('handles string arrays', () => {
+ expect(parseTagsFilter(['tag1', 'tag2', 'tag3'])).toEqual(['tag1', 'tag2', 'tag3'])
+ })
+
+ it('handles mixed type arrays', () => {
+ expect(parseTagsFilter(['tag1', 123, true, null, undefined])).toEqual([
+ 'tag1',
+ '123',
+ 'true',
+ 'null',
+ 'undefined',
+ ])
+ })
+
+ it('filters out empty values', () => {
+ expect(parseTagsFilter(['tag1', '', 'tag2', null, 'tag3'])).toEqual(['tag1', 'tag2', 'null', 'tag3'])
+ })
+
+ it('handles empty array', () => {
+ expect(parseTagsFilter([])).toEqual([])
+ })
+ })
+
+ describe('JSON string input', () => {
+ it('parses valid JSON arrays', () => {
+ expect(parseTagsFilter('["tag1", "tag2", "tag3"]')).toEqual(['tag1', 'tag2', 'tag3'])
+ })
+
+ it('parses JSON arrays with mixed types', () => {
+ expect(parseTagsFilter('["tag1", 123, true]')).toEqual(['tag1', '123', 'true'])
+ })
+
+ it('filters out empty values from JSON', () => {
+ expect(parseTagsFilter('["tag1", "", "tag2", null, "tag3"]')).toEqual(['tag1', 'tag2', 'null', 'tag3'])
+ })
+
+ it('handles empty JSON array', () => {
+ expect(parseTagsFilter('[]')).toEqual([])
+ })
+
+ it('handles malformed JSON gracefully', () => {
+ expect(parseTagsFilter('["tag1", "tag2"')).toEqual(['["tag1"', '"tag2"'])
+ })
+
+ it('handles invalid JSON syntax', () => {
+ expect(parseTagsFilter('{invalid json}')).toEqual(['{invalid json}'])
+ })
+
+ it('handles JSON that is not an array', () => {
+ expect(parseTagsFilter('{"not": "an array"}')).toEqual(['{"not": "an array"}'])
+ })
+
+ it('handles JSON with trailing comma', () => {
+ expect(parseTagsFilter('["tag1", "tag2",]')).toEqual(['["tag1"', '"tag2"', ']'])
+ })
+ })
+
+ describe('comma-separated string input', () => {
+ it('parses simple comma-separated values', () => {
+ expect(parseTagsFilter('tag1,tag2,tag3')).toEqual(['tag1', 'tag2', 'tag3'])
+ })
+
+ it('trims whitespace from values', () => {
+ expect(parseTagsFilter(' tag1 , tag2 , tag3 ')).toEqual(['tag1', 'tag2', 'tag3'])
+ })
+
+ it('filters out empty values', () => {
+ expect(parseTagsFilter('tag1,,tag2, ,tag3')).toEqual(['tag1', 'tag2', 'tag3'])
+ })
+
+ it('handles single value', () => {
+ expect(parseTagsFilter('tag1')).toEqual(['tag1'])
+ })
+
+ it('handles empty string', () => {
+ expect(parseTagsFilter('')).toEqual([])
+ })
+
+ it('handles string with only whitespace', () => {
+ expect(parseTagsFilter(' ')).toEqual([])
+ })
+
+ it('handles string with only commas', () => {
+ expect(parseTagsFilter(',,')).toEqual([])
+ })
+
+ it('handles string with commas and whitespace', () => {
+ expect(parseTagsFilter(' , , ')).toEqual([])
+ })
+ })
+
+ describe('edge cases and invalid input', () => {
+ it('returns undefined for null input', () => {
+ expect(parseTagsFilter(null)).toBeUndefined()
+ })
+
+ it('returns undefined for undefined input', () => {
+ expect(parseTagsFilter(undefined)).toBeUndefined()
+ })
+
+ it('returns undefined for number input', () => {
+ expect(parseTagsFilter(123)).toBeUndefined()
+ })
+
+ it('returns undefined for boolean input', () => {
+ expect(parseTagsFilter(true)).toBeUndefined()
+ expect(parseTagsFilter(false)).toBeUndefined()
+ })
+
+ it('returns undefined for object input', () => {
+ expect(parseTagsFilter({})).toBeUndefined()
+ expect(parseTagsFilter({ tags: ['tag1'] })).toBeUndefined()
+ })
+
+ it('handles special characters in tags', () => {
+ expect(parseTagsFilter('tag-with-dash,tag_with_underscore,tag.with.dots')).toEqual([
+ 'tag-with-dash',
+ 'tag_with_underscore',
+ 'tag.with.dots',
+ ])
+ })
+
+ it('handles unicode characters', () => {
+ expect(parseTagsFilter('标签1,🏷️,тег')).toEqual(['标签1', '🏷️', 'тег'])
+ })
+
+ it('handles very long strings', () => {
+ const longTag = 'a'.repeat(1000)
+ expect(parseTagsFilter(longTag)).toEqual([longTag])
+ })
+
+ it('handles strings with newlines and tabs', () => {
+ expect(parseTagsFilter('tag1\ntag2\ttag3')).toEqual(['tag1\ntag2\ttag3'])
+ })
+ })
+ })
+})
diff --git a/frontend/src/lib/utils/url.ts b/frontend/src/lib/utils/url.ts
new file mode 100644
index 000000000000..60bffc458f7a
--- /dev/null
+++ b/frontend/src/lib/utils/url.ts
@@ -0,0 +1,198 @@
+import { dayjs } from 'lib/dayjs'
+
+export function toParams(obj: Record<string, any>, explodeArrays: boolean = false): string {
+ if (!obj) {
+ return ''
+ }
+
+ function handleVal(val: any): string {
+ if (dayjs.isDayjs(val)) {
+ return encodeURIComponent(val.format('YYYY-MM-DD'))
+ }
+ val = typeof val === 'object' ? JSON.stringify(val) : val
+ return encodeURIComponent(val)
+ }
+
+ return Object.entries(obj)
+ .filter((item) => item[1] != undefined && item[1] != null)
+ .reduce(
+ (acc, [key, val]) => {
+ /**
+ * query parameter arrays can be handled in two ways
+ * either they are encoded as a single query parameter
+ * a=[1, 2] => a=%5B1%2C2%5D
+ * or they are "exploded" so each item in the array is sent separately
+ * a=[1, 2] => a=1&a=2
+ **/
+ if (explodeArrays && Array.isArray(val)) {
+ val.forEach((v) => acc.push([key, v]))
+ } else {
+ acc.push([key, val])
+ }
+
+ return acc
+ },
+ [] as [string, any][]
+ )
+ .map(([key, val]) => `${key}=${handleVal(val)}`)
+ .join('&')
+}
+
+export function fromParamsGivenUrl(url: string): Record<string, any> {
+ return !url
+ ? {}
+ : url
+ .replace(/^\?/, '')
+ .split('&')
+ .reduce(
+ (paramsObject, paramString) => {
+ const [key, value] = paramString.split('=')
+ paramsObject[key] = decodeURIComponent(value)
+ return paramsObject
+ },
+ {} as Record<string, any>
+ )
+}
+
+export function fromParams(): Record<string, any> {
+ return fromParamsGivenUrl(window.location.search)
+}
+
+export function tryDecodeURIComponent(value: string): string {
+ try {
+ return decodeURIComponent(value)
+ } catch {
+ return value
+ }
+}
+
+// Parse a tags filter value coming from URL search params.
+// Supports:
+// - Repeated params handled upstream and aggregated as an array
+// - JSON array string (e.g. "[\"a\",\"b\"]")
+// - Comma-separated string (e.g. "a,b")
+export function parseTagsFilter(raw: unknown): string[] | undefined {
+ if (Array.isArray(raw)) {
+ return (raw as unknown[]).map((v) => String(v)).filter(Boolean)
+ }
+ if (typeof raw === 'string') {
+ // Try JSON first
+ try {
+ const parsed = JSON.parse(raw)
+ if (Array.isArray(parsed)) {
+ return parsed.map((v) => String(v)).filter(Boolean)
+ }
+ } catch {
+ // Fall through to comma-separated
+ }
+ return raw
+ .split(',')
+ .map((s) => s.trim())
+ .filter(Boolean)
+ }
+ return undefined
+}
+
+export function stripHTTP(url: string): string {
+ url = url.replace(/(^[0-9]+_)/, '')
+ url = url.replace(/(^\w+:|^)\/\//, '')
+ return url
+}
+
+export function isDomain(url: string | URL): boolean {
+ try {
+ const parsedUrl = typeof url === 'string' ? new URL(url) : url
+ if (parsedUrl.protocol.includes('http') && (!parsedUrl.pathname || parsedUrl.pathname === '/')) {
+ return true
+ }
+ if (!parsedUrl.pathname.replace(/^\/\//, '').includes('/')) {
+ return true
+ }
+ } catch {
+ return false
+ }
+ return false
+}
+
+export function isURL(input: any): boolean {
+ if (!input || typeof input !== 'string') {
+ return false
+ }
+ const regexp = /^(http|capacitor|https):\/\/[\w*.-]+[\w*.-]+[\w\-._~:/?#[\]@%!$&'()*+,;=]+$/
+ return !!input.trim().match(regexp)
+}
+
+export function isExternalLink(input: any): boolean {
+ if (!input || typeof input !== 'string') {
+ return false
+ }
+ const regexp = /^(https?:|mailto:|\/api\/)/
+ return !!input.trim().match(regexp)
+}
+
+export function isEmail(string: string, options?: { requireTLD?: boolean }): boolean {
+ if (!string) {
+ return false
+ }
+ // https://html.spec.whatwg.org/multipage/input.html#valid-e-mail-address
+ const regexp = options?.requireTLD
+ ? /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*\.[a-zA-Z]{2,}$/
+ : /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/
+ return !!string.match?.(regexp)
+}
+
+export function parseGithubRepoURL(url: string): Record<string, string> {
+ const match = url.match(
+ /^https?:\/\/(?:www\.)?github\.com\/([A-Za-z0-9_.-]+)\/([A-Za-z0-9_.-]+)(\/(commit|tree|releases\/tag)\/([A-Za-z0-9_.\-/]+))?/
+ )
+
+ if (!match) {
+ throw new Error(`${url} is not a valid GitHub URL`)
+ }
+
+ const [, user, repo, , type, path] = match
+ return { user, repo, type, path }
+}
+
+export function getRelativeNextPath(nextPath: string | null | undefined, location: Location): string | null {
+ if (!nextPath || typeof nextPath !== 'string') {
+ return null
+ }
+ let decoded: string
+ try {
+ decoded = decodeURIComponent(nextPath)
+ } catch {
+ decoded = nextPath
+ }
+
+ // Protocol-relative URLs (e.g., //evil.com/test) are not allowed
+ if (decoded.startsWith('//')) {
+ return null
+ }
+
+ // Root-relative path — resolve against the current origin and verify it doesn't escape.
+ // Browsers normalize backslashes in special-scheme URLs per WHATWG, so a raw startsWith('/')
+ // check would accept '/\\evil.com/path', which the browser then loads as '//evil.com/path'.
+ if (decoded.startsWith('/')) {
+ try {
+ const url = new URL(decoded, location.origin)
+ if (url.origin !== location.origin) {
+ return null
+ }
+ return url.pathname + url.search + url.hash
+ } catch {
+ return null
+ }
+ }
+
+ // Try to parse as a full URL
+ try {
+ const url = new URL(decoded)
+ if ((url.protocol === 'http:' || url.protocol === 'https:') && url.origin === location.origin) {
+ return url.pathname + url.search + url.hash
+ }
+ return null
+ } catch {
+ return null
+ }
+}
diff --git a/frontend/src/lib/utils/wrapConsole.ts b/frontend/src/lib/utils/wrapConsole.ts
deleted file mode 100644
index c0f655d595ad..000000000000
--- a/frontend/src/lib/utils/wrapConsole.ts
+++ /dev/null
@@ -1,27 +0,0 @@
-/* oxlint-disable no-console */
-export function wrapConsole(level: 'log' | 'warn' | 'error', fn: (args: Array<unknown>) => boolean): () => void {
- // Flag the handler to prevent max call stack errors (any code in this execution might retrigger the log)
- const wrappedFn = console[level]
- let inWrap = false
-
- console[level] = function (...args: Array<unknown>) {
- try {
- if (inWrap) {
- wrappedFn(...args)
- return
- }
- inWrap = true
-
- if (fn(args)) {
- wrappedFn(...args)
- }
- } finally {
- inWrap = false
- }
- }
-
- return () => {
- console[level] = wrappedFn
- }
-}
-/* oxlint-enable no-console */
diff --git a/frontend/src/loadPostHogJS.tsx b/frontend/src/loadPostHogJS.tsx
index 7581c9f7f364..01f98aa8500e 100644
--- a/frontend/src/loadPostHogJS.tsx
+++ b/frontend/src/loadPostHogJS.tsx
@@ -2,7 +2,7 @@ import posthog, { BeforeSendFn, PostHogInterface, SessionRecordingOptions } from
import { sampleOnProperty } from 'posthog-js/lib/src/extensions/sampling'
import { FEATURE_FLAGS } from 'lib/constants'
-import { inStorybook, inStorybookTestRunner } from 'lib/utils'
+import { inStorybook, inStorybookTestRunner } from 'lib/utils/dom'
import { startDetachedElementTracking } from './detachedElementTracker'
import { startFramerateTracking } from './framerateTracker'
diff --git a/frontend/src/models/dashboardsModel.tsx b/frontend/src/models/dashboardsModel.tsx
index bc3bdb9ce7ac..860e654806aa 100644
--- a/frontend/src/models/dashboardsModel.tsx
+++ b/frontend/src/models/dashboardsModel.tsx
@@ -6,9 +6,10 @@ import api, { PaginatedResponse } from 'lib/api'
import { SetupTaskId, globalSetupLogic } from 'lib/components/ProductSetup'
import { GENERATED_DASHBOARD_PREFIX } from 'lib/constants'
import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'
-import { idToKey, isUserLoggedIn } from 'lib/utils'
import { DashboardEventSource, eventUsageLogic } from 'lib/utils/eventUsageLogic'
+import { isUserLoggedIn } from 'lib/utils/getAppContext'
import { permanentlyMount } from 'lib/utils/kea-logic-builders'
+import { idToKey } from 'lib/utils/objects'
import { teamLogic } from 'scenes/teamLogic'
import { urls } from 'scenes/urls'
diff --git a/frontend/src/models/groupsModel.ts b/frontend/src/models/groupsModel.ts
index e11b92105089..58b32849af61 100644
--- a/frontend/src/models/groupsModel.ts
+++ b/frontend/src/models/groupsModel.ts
@@ -5,7 +5,7 @@ import { subscriptions } from 'kea-subscriptions'
import api from 'lib/api'
import { TaxonomicFilterGroupType } from 'lib/components/TaxonomicFilter/types'
import { GroupsAccessStatus, groupsAccessLogic } from 'lib/introductions/groupsAccessLogic'
-import { wordPluralize } from 'lib/utils'
+import { wordPluralize } from 'lib/utils/strings'
import { projectLogic } from 'scenes/projectLogic'
import { GroupType, GroupTypeIndex } from '~/types'
diff --git a/frontend/src/models/primaryEventPropertiesModel.ts b/frontend/src/models/primaryEventPropertiesModel.ts
index cc06d1b2f949..b324ed970d26 100644
--- a/frontend/src/models/primaryEventPropertiesModel.ts
+++ b/frontend/src/models/primaryEventPropertiesModel.ts
@@ -4,7 +4,7 @@ import posthog from 'posthog-js'
import api from 'lib/api'
import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'
-import { hasTaxonomyPrimaryProperty } from 'lib/utils/primaryEventProperty'
+import { hasTaxonomyPrimaryProperty } from 'lib/utils/events'
import type { primaryEventPropertiesModelType } from './primaryEventPropertiesModelType'
diff --git a/frontend/src/models/propertyDefinitionsModel.ts b/frontend/src/models/propertyDefinitionsModel.ts
index bea927f5cea6..ea760d58684a 100644
--- a/frontend/src/models/propertyDefinitionsModel.ts
+++ b/frontend/src/models/propertyDefinitionsModel.ts
@@ -5,8 +5,10 @@ import { TaxonomicFilterValue } from 'lib/components/TaxonomicFilter/types'
import { dayjs } from 'lib/dayjs'
import { captureTimeToSeeData } from 'lib/internalMetrics'
import { lemonToast } from 'lib/lemon-ui/LemonToast'
-import { colonDelimitedDuration, toString, isKeyOf } from 'lib/utils'
+import { colonDelimitedDuration } from 'lib/utils/durations'
+import { isKeyOf } from 'lib/utils/guards'
import { permanentlyMount } from 'lib/utils/kea-logic-builders'
+import { toString } from 'lib/utils/strings'
import { teamLogic } from 'scenes/teamLogic'
import {
diff --git a/frontend/src/models/saveAsActionDialog.tsx b/frontend/src/models/saveAsActionDialog.tsx
index 871298a0f3f1..42d99c75c98f 100644
--- a/frontend/src/models/saveAsActionDialog.tsx
+++ b/frontend/src/models/saveAsActionDialog.tsx
@@ -6,7 +6,7 @@ import { LemonField } from 'lib/lemon-ui/LemonField'
import { LemonInput } from 'lib/lemon-ui/LemonInput'
import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'
import { Link } from 'lib/lemon-ui/Link'
-import { autoCaptureEventToDescription } from 'lib/utils'
+import { autoCaptureEventToDescription } from 'lib/utils/events'
import {
applyDataAttributeSelector,
applySubmitProperty,
diff --git a/frontend/src/products.tsx b/frontend/src/products.tsx
index 90b3a2c666ea..70b464a7ce7c 100644
--- a/frontend/src/products.tsx
+++ b/frontend/src/products.tsx
@@ -5,7 +5,7 @@ import { combineUrl } from 'kea-router'
import { AlertType } from 'lib/components/Alerts/types'
import { FEATURE_FLAGS, INSIGHT_VISUAL_ORDER } from 'lib/constants'
-import { toParams } from 'lib/utils'
+import { toParams } from 'lib/utils/url'
import type { Params } from 'scenes/sceneTypes'
import { SurveysTabs } from 'scenes/surveys/surveysLogic'
import { urls } from 'scenes/urls'
diff --git a/frontend/src/queries/nodes/DataNode/QueryExecutionDetails.tsx b/frontend/src/queries/nodes/DataNode/QueryExecutionDetails.tsx
index a8fc4209b822..f17da8151658 100644
--- a/frontend/src/queries/nodes/DataNode/QueryExecutionDetails.tsx
+++ b/frontend/src/queries/nodes/DataNode/QueryExecutionDetails.tsx
@@ -6,8 +6,8 @@ import { IconChip } from '@posthog/icons'
import { Popover } from 'lib/lemon-ui/Popover'
import { Tooltip } from 'lib/lemon-ui/Tooltip'
-
-import { humanFriendlyMilliseconds, humanizeBytes } from '~/lib/utils'
+import { humanFriendlyMilliseconds } from 'lib/utils/durations'
+import { humanizeBytes } from 'lib/utils/numbers'
import { dataNodeLogic } from './dataNodeLogic'
diff --git a/frontend/src/queries/nodes/DataNode/dataNodeLogic.queryCancellation.test.ts b/frontend/src/queries/nodes/DataNode/dataNodeLogic.queryCancellation.test.ts
index f188eb8f9f6c..882afff8453a 100644
--- a/frontend/src/queries/nodes/DataNode/dataNodeLogic.queryCancellation.test.ts
+++ b/frontend/src/queries/nodes/DataNode/dataNodeLogic.queryCancellation.test.ts
@@ -1,7 +1,7 @@
import { expectLogic } from 'kea-test-utils'
import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
-import * as libUtils from 'lib/utils'
+import * as libUtils from 'lib/utils/dom'
import { useMocks } from '~/mocks/jest'
import { dataNodeLogic } from '~/queries/nodes/DataNode/dataNodeLogic'
diff --git a/frontend/src/queries/nodes/DataNode/dataNodeLogic.ts b/frontend/src/queries/nodes/DataNode/dataNodeLogic.ts
index 79ae010dd1f5..ae37479b9258 100644
--- a/frontend/src/queries/nodes/DataNode/dataNodeLogic.ts
+++ b/frontend/src/queries/nodes/DataNode/dataNodeLogic.ts
@@ -19,8 +19,9 @@ import posthog from 'posthog-js'
import api, { ApiMethodOptions } from 'lib/api'
import { dayjs } from 'lib/dayjs'
-import { shouldCancelQuery, uuid } from 'lib/utils'
import { ConcurrencyController } from 'lib/utils/concurrencyController'
+import { uuid } from 'lib/utils/dom'
+import { shouldCancelQuery } from 'lib/utils/requests'
import { UNSAVED_INSIGHT_MIN_REFRESH_INTERVAL_MINUTES } from 'scenes/insights/insightLogic'
import { compareDataNodeQuery, haveVariablesOrFiltersChanged, validateQuery } from 'scenes/insights/utils/queryUtils'
import { sceneLogic } from 'scenes/sceneLogic'
diff --git a/frontend/src/queries/nodes/DataTable/DataTableCount.tsx b/frontend/src/queries/nodes/DataTable/DataTableCount.tsx
index 4c4dceff7f4f..f79ea47c85b2 100644
--- a/frontend/src/queries/nodes/DataTable/DataTableCount.tsx
+++ b/frontend/src/queries/nodes/DataTable/DataTableCount.tsx
@@ -1,6 +1,6 @@
import { useValues } from 'kea'
-import { pluralize } from 'lib/utils'
+import { pluralize } from 'lib/utils/strings'
import { dataNodeLogic } from '~/queries/nodes/DataNode/dataNodeLogic'
import { isActorsQuery, isEventsQuery, isGroupsQuery, isSessionsQuery } from '~/queries/utils'
diff --git a/frontend/src/queries/nodes/DataTable/DataTableExport.tsx b/frontend/src/queries/nodes/DataTable/DataTableExport.tsx
index 8682e355cf8b..ecf700dc9866 100644
--- a/frontend/src/queries/nodes/DataTable/DataTableExport.tsx
+++ b/frontend/src/queries/nodes/DataTable/DataTableExport.tsx
@@ -8,7 +8,7 @@ import { exportsLogic } from 'lib/components/ExportButton/exportsLogic'
import { SaveToCohortModalContent } from 'lib/components/SaveToCohortModalContent/SaveToCohortModalContent'
import { PERSON_DEFAULT_DISPLAY_NAME_PROPERTIES } from 'lib/constants'
import { LemonField } from 'lib/lemon-ui/LemonField'
-import { pluralize } from 'lib/utils'
+import { pluralize } from 'lib/utils/strings'
import { teamLogic } from 'scenes/teamLogic'
import { copyTableToCsv, copyTableToExcel, copyTableToJson } from '~/queries/nodes/DataTable/clipboardUtils'
diff --git a/frontend/src/queries/nodes/DataTable/InsightActorsQueryOptions.tsx b/frontend/src/queries/nodes/DataTable/InsightActorsQueryOptions.tsx
index ddcce0cacd12..f3f897771eff 100644
--- a/frontend/src/queries/nodes/DataTable/InsightActorsQueryOptions.tsx
+++ b/frontend/src/queries/nodes/DataTable/InsightActorsQueryOptions.tsx
@@ -1,7 +1,7 @@
import { useMountedLogic, useValues } from 'kea'
import { LemonSelect, LemonSelectOptions } from 'lib/lemon-ui/LemonSelect'
-import { isKeyOf } from 'lib/utils'
+import { isKeyOf } from 'lib/utils/guards'
import { cleanedInsightActorsQueryOptions } from 'scenes/trends/persons-modal/persons-modal-utils'
import { dataNodeLogic } from '~/queries/nodes/DataNode/dataNodeLogic'
diff --git a/frontend/src/queries/nodes/DataTable/dataTableLogic.ts b/frontend/src/queries/nodes/DataTable/dataTableLogic.ts
index 3201587aa24e..e7ac41730232 100644
--- a/frontend/src/queries/nodes/DataTable/dataTableLogic.ts
+++ b/frontend/src/queries/nodes/DataTable/dataTableLogic.ts
@@ -4,7 +4,7 @@ import { FEATURE_FLAGS } from 'lib/constants'
import { dayjs } from 'lib/dayjs'
import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
import { tabUiStateLogic } from 'lib/logic/tabUiStateLogic'
-import { objectsEqual, sortedKeys } from 'lib/utils'
+import { objectsEqual, sortedKeys } from 'lib/utils/objects'
import { RequiredExcept } from 'lib/utils/types'
import { teamLogic } from 'scenes/teamLogic'
diff --git a/frontend/src/queries/nodes/DataTable/renderColumn.tsx b/frontend/src/queries/nodes/DataTable/renderColumn.tsx
index 0fe48adccb18..e0b50228b1fd 100644
--- a/frontend/src/queries/nodes/DataTable/renderColumn.tsx
+++ b/frontend/src/queries/nodes/DataTable/renderColumn.tsx
@@ -13,9 +13,10 @@ import { LemonTag } from 'lib/lemon-ui/LemonTag/LemonTag'
import { Link } from 'lib/lemon-ui/Link'
import { Spinner } from 'lib/lemon-ui/Spinner/Spinner'
import { Tooltip } from 'lib/lemon-ui/Tooltip'
-import { autoCaptureEventToDescription, isURL } from 'lib/utils'
-import { COUNTRY_CODE_TO_LONG_NAME, countryCodeToFlag } from 'lib/utils/geography/country'
-import { formatCurrency } from 'lib/utils/geography/currency'
+import { COUNTRY_CODE_TO_LONG_NAME, countryCodeToFlag } from 'lib/utils/country'
+import { formatCurrency } from 'lib/utils/currency'
+import { autoCaptureEventToDescription } from 'lib/utils/events'
+import { isURL } from 'lib/utils/url'
import { GroupActorDisplay } from 'scenes/persons/GroupActorDisplay'
import { PersonDisplay, PersonDisplayProps } from 'scenes/persons/PersonDisplay'
import { sessionColumnRenderers } from 'scenes/sessions/sessionColumnRenderers'
diff --git a/frontend/src/queries/nodes/DataVisualization/Components/Charts/LineGraph.tsx b/frontend/src/queries/nodes/DataVisualization/Components/Charts/LineGraph.tsx
index 24a277b114e4..9dc5cbaebeee 100644
--- a/frontend/src/queries/nodes/DataVisualization/Components/Charts/LineGraph.tsx
+++ b/frontend/src/queries/nodes/DataVisualization/Components/Charts/LineGraph.tsx
@@ -32,7 +32,8 @@ import { getGraphColors, getSeriesColor } from 'lib/colors'
import { InsightLabel } from 'lib/components/InsightLabel'
import { useChart } from 'lib/hooks/useChart'
import { useKeyHeld } from 'lib/hooks/useKeyHeld'
-import { hexToRGBA, uuid } from 'lib/utils'
+import { hexToRGBA } from 'lib/utils/colors'
+import { uuid } from 'lib/utils/dom'
import { unpinTooltip, useInsightTooltip } from 'scenes/insights/useInsightTooltip'
import { teamLogic } from 'scenes/teamLogic'
diff --git a/frontend/src/queries/nodes/DataVisualization/Components/Heatmap/heatmapUtils.ts b/frontend/src/queries/nodes/DataVisualization/Components/Heatmap/heatmapUtils.ts
index 81ab1c48c16b..b62ee3c7bf51 100644
--- a/frontend/src/queries/nodes/DataVisualization/Components/Heatmap/heatmapUtils.ts
+++ b/frontend/src/queries/nodes/DataVisualization/Components/Heatmap/heatmapUtils.ts
@@ -1,4 +1,4 @@
-import { hexToRGB } from 'lib/utils'
+import { hexToRGB } from 'lib/utils/colors'
import { HeatmapGradientStop, HeatmapSettings } from '~/queries/schema/schema-general'
diff --git a/frontend/src/queries/nodes/DataVisualization/Components/Table.tsx b/frontend/src/queries/nodes/DataVisualization/Components/Table.tsx
index c9b87cf58b6d..282fcf3481dd 100644
--- a/frontend/src/queries/nodes/DataVisualization/Components/Table.tsx
+++ b/frontend/src/queries/nodes/DataVisualization/Components/Table.tsx
@@ -8,7 +8,7 @@ import { IconPin, IconPinFilled } from '@posthog/icons'
import { LemonTable, LemonTableColumn, Tooltip } from '@posthog/lemon-ui'
import { execHog } from 'lib/hog'
-import { lightenDarkenColor } from 'lib/utils'
+import { lightenDarkenColor } from 'lib/utils/colors'
import { InsightEmptyState, InsightErrorState } from 'scenes/insights/EmptyStates'
import { themeLogic } from '~/layout/navigation-3000/themeLogic'
diff --git a/frontend/src/queries/nodes/DataVisualization/Components/Variables/variablesLogic.ts b/frontend/src/queries/nodes/DataVisualization/Components/Variables/variablesLogic.ts
index 34b1d19d8e1a..a325e0f40dbb 100644
--- a/frontend/src/queries/nodes/DataVisualization/Components/Variables/variablesLogic.ts
+++ b/frontend/src/queries/nodes/DataVisualization/Components/Variables/variablesLogic.ts
@@ -1,7 +1,7 @@
import { actions, connect, kea, key, listeners, path, props, propsChanged, reducers, selectors } from 'kea'
import { subscriptions } from 'kea-subscriptions'
-import { objectsEqual } from 'lib/utils'
+import { objectsEqual } from 'lib/utils/objects'
import {
getVariablesFromQuery,
haveVariablesOrFiltersChanged,
diff --git a/frontend/src/queries/nodes/DataVisualization/dataVisualizationLogic.ts b/frontend/src/queries/nodes/DataVisualization/dataVisualizationLogic.ts
index 87035f86473d..e6976b2f103a 100644
--- a/frontend/src/queries/nodes/DataVisualization/dataVisualizationLogic.ts
+++ b/frontend/src/queries/nodes/DataVisualization/dataVisualizationLogic.ts
@@ -16,7 +16,10 @@ import { subscriptions } from 'kea-subscriptions'
import mergeObject from 'lodash.merge'
import { dayjs } from 'lib/dayjs'
-import { RGBToHex, compactNumber, lightenDarkenColor, objectsEqual, uuid } from 'lib/utils'
+import { RGBToHex, lightenDarkenColor } from 'lib/utils/colors'
+import { uuid } from 'lib/utils/dom'
+import { compactNumber } from 'lib/utils/numbers'
+import { objectsEqual } from 'lib/utils/objects'
import { sceneLogic } from 'scenes/sceneLogic'
import { Scene } from 'scenes/sceneTypes'
import { teamLogic } from 'scenes/teamLogic'
diff --git a/frontend/src/queries/nodes/InsightQuery/utils/filtersToQueryNode.ts b/frontend/src/queries/nodes/InsightQuery/utils/filtersToQueryNode.ts
index 9203e6000778..0614bfbad575 100644
--- a/frontend/src/queries/nodes/InsightQuery/utils/filtersToQueryNode.ts
+++ b/frontend/src/queries/nodes/InsightQuery/utils/filtersToQueryNode.ts
@@ -1,6 +1,7 @@
import posthog from 'posthog-js'
-import { isKeyOf, objectCleanWithEmpty } from 'lib/utils'
+import { isKeyOf } from 'lib/utils/guards'
+import { objectCleanWithEmpty } from 'lib/utils/objects'
import { transformLegacyHiddenLegendKeys } from 'scenes/funnels/funnelUtils'
import { MathAvailability } from 'scenes/insights/filters/ActionFilter/ActionFilterRow/ActionFilterRow'
import {
diff --git a/frontend/src/queries/nodes/InsightQuery/utils/queryNodeToFilter.ts b/frontend/src/queries/nodes/InsightQuery/utils/queryNodeToFilter.ts
index 84851339bc4b..a9ad404ef63b 100644
--- a/frontend/src/queries/nodes/InsightQuery/utils/queryNodeToFilter.ts
+++ b/frontend/src/queries/nodes/InsightQuery/utils/queryNodeToFilter.ts
@@ -1,5 +1,5 @@
import { TaxonomicFilterGroupType } from 'lib/components/TaxonomicFilter/types'
-import { objectClean } from 'lib/utils'
+import { objectClean } from 'lib/utils/objects'
import { ProductAnalyticsInsightNodeKind } from '~/queries/nodes/InsightQuery/defaults'
import {
diff --git a/frontend/src/queries/nodes/InsightViz/EditorFilterGroupTile.tsx b/frontend/src/queries/nodes/InsightViz/EditorFilterGroupTile.tsx
index f1158e45f4cd..3fb95487c6bc 100644
--- a/frontend/src/queries/nodes/InsightViz/EditorFilterGroupTile.tsx
+++ b/frontend/src/queries/nodes/InsightViz/EditorFilterGroupTile.tsx
@@ -4,7 +4,7 @@ import posthog from 'posthog-js'
import { IconCollapse, IconExpand } from '@posthog/icons'
import { LemonButton } from 'lib/lemon-ui/LemonButton'
-import { slugify } from 'lib/utils'
+import { slugify } from 'lib/utils/strings'
import type { InsightEditorFilterGroup, InsightLogicProps } from '~/types'
diff --git a/frontend/src/queries/nodes/InsightViz/EditorFilters.tsx b/frontend/src/queries/nodes/InsightViz/EditorFilters.tsx
index 92ea5cb7683a..f17b82f87eb2 100644
--- a/frontend/src/queries/nodes/InsightViz/EditorFilters.tsx
+++ b/frontend/src/queries/nodes/InsightViz/EditorFilters.tsx
@@ -4,7 +4,7 @@ import { IconInfo } from '@posthog/icons'
import { Link, Tooltip } from '@posthog/lemon-ui'
import { NON_BREAKDOWN_DISPLAY_TYPES } from 'lib/constants'
-import { pluralize } from 'lib/utils'
+import { pluralize } from 'lib/utils/strings'
import { funnelDataLogic } from 'scenes/funnels/funnelDataLogic'
import { Attribution } from 'scenes/insights/EditorFilters/AttributionFilter'
import { FunnelsAdvanced } from 'scenes/insights/EditorFilters/FunnelsAdvanced'
diff --git a/frontend/src/queries/nodes/InsightViz/InsightDisplayConfig.tsx b/frontend/src/queries/nodes/InsightViz/InsightDisplayConfig.tsx
index 89332aaf5723..27736bb602f7 100644
--- a/frontend/src/queries/nodes/InsightViz/InsightDisplayConfig.tsx
+++ b/frontend/src/queries/nodes/InsightViz/InsightDisplayConfig.tsx
@@ -16,8 +16,8 @@ import { UnitPicker } from 'lib/components/UnitPicker/UnitPicker'
import { FEATURE_FLAGS, NON_TIME_SERIES_DISPLAY_TYPES } from 'lib/constants'
import { LemonMenu, LemonMenuItems } from 'lib/lemon-ui/LemonMenu'
import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
-import { DEFAULT_DECIMAL_PLACES } from 'lib/utils'
-import { alignResolvedDateRangeToInterval, formatResolvedDateRange } from 'lib/utils/dateTimeUtils'
+import { alignResolvedDateRangeToInterval, formatResolvedDateRange } from 'lib/utils/datetime'
+import { DEFAULT_DECIMAL_PLACES } from 'lib/utils/numbers'
import { funnelDataLogic } from 'scenes/funnels/funnelDataLogic'
import { axisLabel } from 'scenes/insights/aggregationAxisFormat'
import { AxisLabelsFilter } from 'scenes/insights/EditorFilters/AxisLabelsFilter'
diff --git a/frontend/src/queries/nodes/InsightViz/LifecycleToggles.tsx b/frontend/src/queries/nodes/InsightViz/LifecycleToggles.tsx
index d758fab810fa..bd92d60d47fc 100644
--- a/frontend/src/queries/nodes/InsightViz/LifecycleToggles.tsx
+++ b/frontend/src/queries/nodes/InsightViz/LifecycleToggles.tsx
@@ -2,7 +2,7 @@ import { useActions, useValues } from 'kea'
import { LemonCheckbox, LemonLabel } from '@posthog/lemon-ui'
-import { capitalizeFirstLetter } from 'lib/utils'
+import { capitalizeFirstLetter } from 'lib/utils/strings'
import {
AGGREGATION_LABEL_FOR_CUSTOM_DATA_WAREHOUSE,
getAggregationTargetPronoun,
diff --git a/frontend/src/queries/nodes/InsightViz/PropertyGroupFilters/propertyGroupFilterLogic.ts b/frontend/src/queries/nodes/InsightViz/PropertyGroupFilters/propertyGroupFilterLogic.ts
index 9179cc9246ac..63d68fe1dee9 100644
--- a/frontend/src/queries/nodes/InsightViz/PropertyGroupFilters/propertyGroupFilterLogic.ts
+++ b/frontend/src/queries/nodes/InsightViz/PropertyGroupFilters/propertyGroupFilterLogic.ts
@@ -1,8 +1,8 @@
import { actions, kea, key, listeners, path, props, propsChanged, reducers, selectors } from 'kea'
import { convertPropertiesToPropertyGroup, isValidPropertyFilter } from 'lib/components/PropertyFilters/utils'
-import { objectsEqual } from 'lib/utils'
import { eventUsageLogic } from 'lib/utils/eventUsageLogic'
+import { objectsEqual } from 'lib/utils/objects'
import { ProductAnalyticsInsightQueryNode } from '~/queries/schema/schema-general'
import {
diff --git a/frontend/src/queries/nodes/InsightViz/SuggestionBanner.tsx b/frontend/src/queries/nodes/InsightViz/SuggestionBanner.tsx
index 62f7c07fc733..9188b8f086d7 100644
--- a/frontend/src/queries/nodes/InsightViz/SuggestionBanner.tsx
+++ b/frontend/src/queries/nodes/InsightViz/SuggestionBanner.tsx
@@ -3,7 +3,7 @@ import { useEffect, useRef } from 'react'
import { IconInfo, IconX } from '@posthog/icons'
import { LemonButton, Tooltip } from '@posthog/lemon-ui'
-import { pluralize } from 'lib/utils'
+import { pluralize } from 'lib/utils/strings'
import { compareInsightTopLevelSections } from 'scenes/insights/utils'
import { Node } from '~/queries/schema/schema-general'
diff --git a/frontend/src/queries/nodes/InsightViz/TrendsSeries.tsx b/frontend/src/queries/nodes/InsightViz/TrendsSeries.tsx
index ac4ba44ea3c6..a84c93fee3c4 100644
--- a/frontend/src/queries/nodes/InsightViz/TrendsSeries.tsx
+++ b/frontend/src/queries/nodes/InsightViz/TrendsSeries.tsx
@@ -4,8 +4,8 @@ import { LemonSwitch } from '@posthog/lemon-ui'
import { DataWarehousePopoverField, TaxonomicFilterGroupType } from 'lib/components/TaxonomicFilter/types'
import { SINGLE_SERIES_DISPLAY_TYPES } from 'lib/constants'
-import { alphabet } from 'lib/utils'
import { getProjectEventExistence } from 'lib/utils/getAppContext'
+import { alphabet } from 'lib/utils/strings'
import { ActionFilter } from 'scenes/insights/filters/ActionFilter/ActionFilter'
import { MathAvailability } from 'scenes/insights/filters/ActionFilter/ActionFilterRow/ActionFilterRow'
import { insightLogic } from 'scenes/insights/insightLogic'
diff --git a/frontend/src/queries/nodes/InsightViz/editorFilterUtils.ts b/frontend/src/queries/nodes/InsightViz/editorFilterUtils.ts
index 1f6440d16e5b..f0726f823077 100644
--- a/frontend/src/queries/nodes/InsightViz/editorFilterUtils.ts
+++ b/frontend/src/queries/nodes/InsightViz/editorFilterUtils.ts
@@ -1,4 +1,4 @@
-import { pluralize } from 'lib/utils'
+import { pluralize } from 'lib/utils/strings'
import { formatEventName } from 'scenes/insights/utils'
import { BreakdownFilter } from '~/queries/schema/schema-general'
diff --git a/frontend/src/queries/nodes/InsightViz/useEditorGroupExpansion.ts b/frontend/src/queries/nodes/InsightViz/useEditorGroupExpansion.ts
index f94820bd0b28..a471792f418a 100644
--- a/frontend/src/queries/nodes/InsightViz/useEditorGroupExpansion.ts
+++ b/frontend/src/queries/nodes/InsightViz/useEditorGroupExpansion.ts
@@ -1,6 +1,6 @@
import { useState } from 'react'
-import { inStorybook, inStorybookTestRunner } from 'lib/utils'
+import { inStorybook, inStorybookTestRunner } from 'lib/utils/dom'
export function useEditorGroupExpansion(
defaultExpanded: boolean | undefined,
diff --git a/frontend/src/queries/nodes/InsightViz/utils.ts b/frontend/src/queries/nodes/InsightViz/utils.ts
index 0799314c5c39..d8c0c2c3e525 100644
--- a/frontend/src/queries/nodes/InsightViz/utils.ts
+++ b/frontend/src/queries/nodes/InsightViz/utils.ts
@@ -1,7 +1,7 @@
import equal from 'fast-deep-equal'
import { ApiError } from 'lib/api'
-import { getEventNamesForAction } from 'lib/utils'
+import { getEventNamesForAction } from 'lib/utils/events'
import { examples } from '~/queries/examples'
import {
diff --git a/frontend/src/queries/nodes/OverviewGrid/OverviewGrid.tsx b/frontend/src/queries/nodes/OverviewGrid/OverviewGrid.tsx
index e4ee90c2e32d..1f3ed7654afe 100644
--- a/frontend/src/queries/nodes/OverviewGrid/OverviewGrid.tsx
+++ b/frontend/src/queries/nodes/OverviewGrid/OverviewGrid.tsx
@@ -9,8 +9,11 @@ import { getColorVar } from 'lib/colors'
import { PreAggregatedBadge } from 'lib/components/PreAggregatedBadge'
import { IconTrendingDown, IconTrendingFlat } from 'lib/lemon-ui/icons'
import { Tooltip } from 'lib/lemon-ui/Tooltip'
-import { formatPercentage, humanFriendlyDuration, humanFriendlyLargeNumber, isNotNil, range } from 'lib/utils'
-import { DEFAULT_CURRENCY, getCurrencySymbol } from 'lib/utils/geography/currency'
+import { range } from 'lib/utils/arrays'
+import { DEFAULT_CURRENCY, getCurrencySymbol } from 'lib/utils/currency'
+import { humanFriendlyDuration } from 'lib/utils/durations'
+import { isNotNil } from 'lib/utils/guards'
+import { formatPercentage, humanFriendlyLargeNumber } from 'lib/utils/numbers'
import { teamLogic } from 'scenes/teamLogic'
import { EvenlyDistributedRows } from '~/queries/nodes/WebOverview/EvenlyDistributedRows'
diff --git a/frontend/src/queries/nodes/OverviewGrid/OverviewMetricCardGrid.tsx b/frontend/src/queries/nodes/OverviewGrid/OverviewMetricCardGrid.tsx
index fa150887517c..3d06267f6ecd 100644
--- a/frontend/src/queries/nodes/OverviewGrid/OverviewMetricCardGrid.tsx
+++ b/frontend/src/queries/nodes/OverviewGrid/OverviewMetricCardGrid.tsx
@@ -8,7 +8,7 @@ import { MetricCard, type MetricChange } from '@posthog/quill-charts'
import { PreAggregatedBadge } from 'lib/components/PreAggregatedBadge'
import { Tooltip } from 'lib/lemon-ui/Tooltip'
-import { range } from 'lib/utils'
+import { range } from 'lib/utils/arrays'
import { teamLogic } from 'scenes/teamLogic'
import { formatItem, NO_BASELINE_CHANGE_SENTINEL, OverviewItem, SamplingNotice, SamplingRate } from './OverviewGrid'
diff --git a/frontend/src/queries/nodes/WebOverview/WebOverview.tsx b/frontend/src/queries/nodes/WebOverview/WebOverview.tsx
index 5558ec836ef9..2e91b1e2b10f 100644
--- a/frontend/src/queries/nodes/WebOverview/WebOverview.tsx
+++ b/frontend/src/queries/nodes/WebOverview/WebOverview.tsx
@@ -5,7 +5,7 @@ import { reverseProxyCheckerLogic } from 'lib/components/ReverseProxyChecker/rev
import { FEATURE_FLAGS } from 'lib/constants'
import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
import { useAttachedLogic } from 'lib/logic/scenes/useAttachedLogic'
-import { capitalizeFirstLetter } from 'lib/utils'
+import { capitalizeFirstLetter } from 'lib/utils/strings'
import { OverviewGrid } from '~/queries/nodes/OverviewGrid/OverviewGrid'
import { OverviewMetricCardGrid, OverviewMetricCardItem } from '~/queries/nodes/OverviewGrid/OverviewMetricCardGrid'
diff --git a/frontend/src/queries/query.ts b/frontend/src/queries/query.ts
index a298e8e46664..24a6a86969f8 100644
--- a/frontend/src/queries/query.ts
+++ b/frontend/src/queries/query.ts
@@ -1,6 +1,6 @@
import api, { ApiMethodOptions } from 'lib/api'
import posthog from 'lib/posthog-typed'
-import { delay } from 'lib/utils'
+import { delay } from 'lib/utils/async'
import {
DashboardFilter,
diff --git a/frontend/src/scenes/PreflightCheck/PreflightCheck.tsx b/frontend/src/scenes/PreflightCheck/PreflightCheck.tsx
index 524cbababc81..2488f145e15a 100644
--- a/frontend/src/scenes/PreflightCheck/PreflightCheck.tsx
+++ b/frontend/src/scenes/PreflightCheck/PreflightCheck.tsx
@@ -12,7 +12,7 @@ import { IconErrorOutline } from 'lib/lemon-ui/icons'
import { LemonButton } from 'lib/lemon-ui/LemonButton'
import { LemonDivider } from 'lib/lemon-ui/LemonDivider'
import { LemonRow } from 'lib/lemon-ui/LemonRow'
-import { capitalizeFirstLetter } from 'lib/utils'
+import { capitalizeFirstLetter } from 'lib/utils/strings'
import { SceneExport } from 'scenes/sceneTypes'
import { PreflightCheckStatus, PreflightItem, preflightLogic } from './preflightLogic'
diff --git a/frontend/src/scenes/actions/actionActivityDescriber.tsx b/frontend/src/scenes/actions/actionActivityDescriber.tsx
index a653b19d5f90..f04e0cdc7153 100644
--- a/frontend/src/scenes/actions/actionActivityDescriber.tsx
+++ b/frontend/src/scenes/actions/actionActivityDescriber.tsx
@@ -11,7 +11,7 @@ import {
import { SentenceList } from 'lib/components/ActivityLog/SentenceList'
import { ObjectTags } from 'lib/components/ObjectTags/ObjectTags'
import { Link } from 'lib/lemon-ui/Link'
-import { pluralize } from 'lib/utils'
+import { pluralize } from 'lib/utils/strings'
import { urls } from 'scenes/urls'
import { ActivityScope } from '~/types'
diff --git a/frontend/src/scenes/activity/explore/createActionFromEvent.tsx b/frontend/src/scenes/activity/explore/createActionFromEvent.tsx
index 862a987d7342..560b22c1674d 100644
--- a/frontend/src/scenes/activity/explore/createActionFromEvent.tsx
+++ b/frontend/src/scenes/activity/explore/createActionFromEvent.tsx
@@ -1,4 +1,4 @@
-import { CLICK_TARGETS, elementToSelector, matchesDataAttribute } from 'lib/actionUtils'
+import { CLICK_TARGETS, elementToSelector, matchesDataAttribute } from 'lib/utils/actions'
import { ActionStepType, ElementType, PropertyFilterType, PropertyOperator } from '~/types'
diff --git a/frontend/src/scenes/activity/explore/eventsSceneLogic.tsx b/frontend/src/scenes/activity/explore/eventsSceneLogic.tsx
index f4e0a5e06a6d..aad8f83d0aeb 100644
--- a/frontend/src/scenes/activity/explore/eventsSceneLogic.tsx
+++ b/frontend/src/scenes/activity/explore/eventsSceneLogic.tsx
@@ -7,7 +7,7 @@ import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'
import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
import { trackedActionToUrl } from 'lib/logic/scenes/trackedActionToUrl'
import { tabUiStateLogic } from 'lib/logic/tabUiStateLogic'
-import { objectsEqual } from 'lib/utils'
+import { objectsEqual } from 'lib/utils/objects'
import { applyTestAccountFilter, getDefaultEventsSceneQuery } from 'scenes/activity/explore/defaults'
import { sceneConfigurations } from 'scenes/scenes'
import { Scene } from 'scenes/sceneTypes'
diff --git a/frontend/src/scenes/activity/explore/sessionsColumns.tsx b/frontend/src/scenes/activity/explore/sessionsColumns.tsx
index b9b6d665531c..ddd1a5cc4244 100644
--- a/frontend/src/scenes/activity/explore/sessionsColumns.tsx
+++ b/frontend/src/scenes/activity/explore/sessionsColumns.tsx
@@ -1,6 +1,6 @@
import { TZLabel } from 'lib/components/TZLabel'
import { dayjs } from 'lib/dayjs'
-import { colonDelimitedDuration } from 'lib/utils'
+import { colonDelimitedDuration } from 'lib/utils/durations'
import { SessionDisplay } from 'scenes/sessions/SessionDisplay'
import { DataTableRow } from '~/queries/nodes/DataTable/dataTableLogic'
diff --git a/frontend/src/scenes/activity/explore/sessionsSceneLogic.tsx b/frontend/src/scenes/activity/explore/sessionsSceneLogic.tsx
index 484a0fe99afa..e3349c404bdd 100644
--- a/frontend/src/scenes/activity/explore/sessionsSceneLogic.tsx
+++ b/frontend/src/scenes/activity/explore/sessionsSceneLogic.tsx
@@ -6,7 +6,7 @@ import { UrlToActionPayload } from 'kea-router/lib/types'
import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'
import { trackedActionToUrl } from 'lib/logic/scenes/trackedActionToUrl'
import { tabUiStateLogic } from 'lib/logic/tabUiStateLogic'
-import { objectsEqual } from 'lib/utils'
+import { objectsEqual } from 'lib/utils/objects'
import { applyTestAccountFilter, getDefaultSessionsSceneQuery } from 'scenes/activity/explore/defaults'
import { sceneConfigurations } from 'scenes/scenes'
import { Scene } from 'scenes/sceneTypes'
diff --git a/frontend/src/scenes/annotations/AnnotationModal.tsx b/frontend/src/scenes/annotations/AnnotationModal.tsx
index 225707e1111e..b739ca85cbcb 100644
--- a/frontend/src/scenes/annotations/AnnotationModal.tsx
+++ b/frontend/src/scenes/annotations/AnnotationModal.tsx
@@ -15,7 +15,7 @@ import {
import { EmojiPickerPopover } from 'lib/components/EmojiPicker/EmojiPickerPopover'
import { LemonField } from 'lib/lemon-ui/LemonField'
import { LemonTextAreaMarkdown } from 'lib/lemon-ui/LemonTextArea/LemonTextAreaMarkdown'
-import { shortTimeZone } from 'lib/utils'
+import { shortTimeZone } from 'lib/utils/timezones'
import { urls } from 'scenes/urls'
import { AnnotationScope, AnnotationType } from '~/types'
diff --git a/frontend/src/scenes/approvals/PendingApprovalsBanner.tsx b/frontend/src/scenes/approvals/PendingApprovalsBanner.tsx
index 09d8f6a3483e..5fb843ae6f6a 100644
--- a/frontend/src/scenes/approvals/PendingApprovalsBanner.tsx
+++ b/frontend/src/scenes/approvals/PendingApprovalsBanner.tsx
@@ -2,7 +2,7 @@ import { useValues } from 'kea'
import { LemonBanner } from '@posthog/lemon-ui'
-import { pluralize } from 'lib/utils'
+import { pluralize } from 'lib/utils/strings'
import { urls } from 'scenes/urls'
import { pendingApprovalsLogic } from './pendingApprovalsLogic'
diff --git a/frontend/src/scenes/approvals/PendingChangeRequestBanner.tsx b/frontend/src/scenes/approvals/PendingChangeRequestBanner.tsx
index ebfb0d1b64a2..dbd95ff21809 100644
--- a/frontend/src/scenes/approvals/PendingChangeRequestBanner.tsx
+++ b/frontend/src/scenes/approvals/PendingChangeRequestBanner.tsx
@@ -3,7 +3,7 @@ import { useActions, useValues } from 'kea'
import { LemonBanner } from '@posthog/lemon-ui'
import { ProfilePicture } from 'lib/lemon-ui/ProfilePicture'
-import { humanFriendlyDetailedTime } from 'lib/utils'
+import { humanFriendlyDetailedTime } from 'lib/utils/datetime'
import { getApprovalActionDescription } from 'scenes/approvals/utils'
import { ChangeRequestActions } from './ChangeRequestActions'
diff --git a/frontend/src/scenes/approvals/changeRequestsLogic.ts b/frontend/src/scenes/approvals/changeRequestsLogic.ts
index e581e6414449..adf0ab8a94fa 100644
--- a/frontend/src/scenes/approvals/changeRequestsLogic.ts
+++ b/frontend/src/scenes/approvals/changeRequestsLogic.ts
@@ -4,7 +4,7 @@ import { loaders } from 'kea-loaders'
import { lemonToast } from '@posthog/lemon-ui'
import api from 'lib/api'
-import { toParams } from 'lib/utils'
+import { toParams } from 'lib/utils/url'
import { teamLogic } from 'scenes/teamLogic'
import { userLogic } from 'scenes/userLogic'
diff --git a/frontend/src/scenes/approvals/pendingApprovalsLogic.ts b/frontend/src/scenes/approvals/pendingApprovalsLogic.ts
index f90887c1f22b..6d17367bf7af 100644
--- a/frontend/src/scenes/approvals/pendingApprovalsLogic.ts
+++ b/frontend/src/scenes/approvals/pendingApprovalsLogic.ts
@@ -2,7 +2,7 @@ import { afterMount, connect, kea, path, selectors } from 'kea'
import { loaders } from 'kea-loaders'
import api from 'lib/api'
-import { toParams } from 'lib/utils'
+import { toParams } from 'lib/utils/url'
import { teamLogic } from 'scenes/teamLogic'
import { userLogic } from 'scenes/userLogic'
diff --git a/frontend/src/scenes/audit-logs/DetailFilters.tsx b/frontend/src/scenes/audit-logs/DetailFilters.tsx
index 6bf4e4e03707..88ba635e7dcd 100644
--- a/frontend/src/scenes/audit-logs/DetailFilters.tsx
+++ b/frontend/src/scenes/audit-logs/DetailFilters.tsx
@@ -11,7 +11,7 @@ import {
Tooltip,
} from '@posthog/lemon-ui'
-import { midEllipsis } from 'lib/utils'
+import { midEllipsis } from 'lib/utils/strings'
import { ActiveDetailFilter, advancedActivityLogsLogic } from './advancedActivityLogsLogic'
diff --git a/frontend/src/scenes/audit-logs/ExportsList.tsx b/frontend/src/scenes/audit-logs/ExportsList.tsx
index 8a764f73a3b9..d86df59bee62 100644
--- a/frontend/src/scenes/audit-logs/ExportsList.tsx
+++ b/frontend/src/scenes/audit-logs/ExportsList.tsx
@@ -4,7 +4,7 @@ import { IconDownload } from '@posthog/icons'
import { LemonButton, LemonTable, Tooltip } from '@posthog/lemon-ui'
import { DetectiveHog } from 'lib/components/hedgehogs'
-import { humanFriendlyDetailedTime } from 'lib/utils'
+import { humanFriendlyDetailedTime } from 'lib/utils/datetime'
import { ExportedAsset, advancedActivityLogsLogic } from './advancedActivityLogsLogic'
import {
diff --git a/frontend/src/scenes/audit-logs/advancedActivityLogsLogic.tsx b/frontend/src/scenes/audit-logs/advancedActivityLogsLogic.tsx
index 99b22d8d8e0c..022c0d2e5ef9 100644
--- a/frontend/src/scenes/audit-logs/advancedActivityLogsLogic.tsx
+++ b/frontend/src/scenes/audit-logs/advancedActivityLogsLogic.tsx
@@ -9,7 +9,8 @@ import { ADVANCED_ACTIVITY_PAGE_SIZE, OrganizationMembershipLevel } from 'lib/co
import { lemonToast } from 'lib/lemon-ui/LemonToast'
import { PaginationManual } from 'lib/lemon-ui/PaginationControl'
import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
-import { dateStringToDayJs, objectClean } from 'lib/utils'
+import { dateStringToDayJs } from 'lib/utils/dateFilters'
+import { objectClean } from 'lib/utils/objects'
import { organizationLogic } from 'scenes/organizationLogic'
import { teamLogic } from 'scenes/teamLogic'
diff --git a/frontend/src/scenes/authentication/account/credential-review/CredentialsReviewList.tsx b/frontend/src/scenes/authentication/account/credential-review/CredentialsReviewList.tsx
index 82ca5eeddf0f..6cfb56821ee6 100644
--- a/frontend/src/scenes/authentication/account/credential-review/CredentialsReviewList.tsx
+++ b/frontend/src/scenes/authentication/account/credential-review/CredentialsReviewList.tsx
@@ -2,7 +2,7 @@ import { useActions, useValues } from 'kea'
import { LemonButton, LemonDialog, LemonTable, Tooltip } from '@posthog/lemon-ui'
-import { humanFriendlyDetailedTime } from 'lib/utils'
+import { humanFriendlyDetailedTime } from 'lib/utils/datetime'
import { type PasskeyCredential, passkeySettingsLogic } from 'scenes/settings/user/passkeySettingsLogic'
import { personalAPIKeysLogic } from 'scenes/settings/user/personalAPIKeysLogic'
diff --git a/frontend/src/scenes/authentication/cli/CLIAuthorize.tsx b/frontend/src/scenes/authentication/cli/CLIAuthorize.tsx
index 2db3652867e9..fd479e4b7a2a 100644
--- a/frontend/src/scenes/authentication/cli/CLIAuthorize.tsx
+++ b/frontend/src/scenes/authentication/cli/CLIAuthorize.tsx
@@ -12,7 +12,8 @@ import { LemonBanner } from 'lib/lemon-ui/LemonBanner'
import { LemonField } from 'lib/lemon-ui/LemonField'
import { LemonModal } from 'lib/lemon-ui/LemonModal'
import { API_SCOPES } from 'lib/scopes'
-import { capitalizeFirstLetter, isKeyOf } from 'lib/utils'
+import { isKeyOf } from 'lib/utils/guards'
+import { capitalizeFirstLetter } from 'lib/utils/strings'
import { SceneExport } from 'scenes/sceneTypes'
import { urls } from 'scenes/urls'
diff --git a/frontend/src/scenes/authentication/login/loginLogic.test.ts b/frontend/src/scenes/authentication/login/loginLogic.test.ts
index 29f36b69c3f1..a73f34467a56 100644
--- a/frontend/src/scenes/authentication/login/loginLogic.test.ts
+++ b/frontend/src/scenes/authentication/login/loginLogic.test.ts
@@ -1,7 +1,7 @@
import { router } from 'kea-router'
import { testUtilsPlugin } from 'kea-test-utils'
-import { removeProjectIdIfPresent } from 'lib/utils/router-utils'
+import { removeProjectIdIfPresent } from 'lib/utils/kea-router'
import { handleLoginRedirect, loginLogic } from 'scenes/authentication/login/loginLogic'
import { initKea } from '~/initKea'
diff --git a/frontend/src/scenes/authentication/login/loginLogic.ts b/frontend/src/scenes/authentication/login/loginLogic.ts
index 35a0f9853db4..d91d01b16fc4 100644
--- a/frontend/src/scenes/authentication/login/loginLogic.ts
+++ b/frontend/src/scenes/authentication/login/loginLogic.ts
@@ -8,7 +8,7 @@ import { router } from 'kea-router'
import api from 'lib/api'
import { lemonToast } from 'lib/lemon-ui/LemonToast'
import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
-import { getRelativeNextPath } from 'lib/utils'
+import { getRelativeNextPath } from 'lib/utils/url'
import { devLoginLogic } from 'scenes/authentication/shared/devLoginLogic'
import { twoFactorResetLogic } from 'scenes/authentication/two-factor-reset/twoFactorResetLogic'
import { preflightLogic } from 'scenes/PreflightCheck/preflightLogic'
diff --git a/frontend/src/scenes/authentication/login/variants/legacy/LegacyLogin.tsx b/frontend/src/scenes/authentication/login/variants/legacy/LegacyLogin.tsx
index 9dd8f13833e6..809408f7cd79 100644
--- a/frontend/src/scenes/authentication/login/variants/legacy/LegacyLogin.tsx
+++ b/frontend/src/scenes/authentication/login/variants/legacy/LegacyLogin.tsx
@@ -15,7 +15,7 @@ import { LemonBanner } from 'lib/lemon-ui/LemonBanner'
import { LemonField } from 'lib/lemon-ui/LemonField'
import { Link } from 'lib/lemon-ui/Link'
import { Skeleton } from 'lib/ui/quill'
-import { isEmail } from 'lib/utils'
+import { isEmail } from 'lib/utils/url'
import { AuthShell } from 'scenes/authentication/shared/AuthShell'
import { OtherRegionHint } from 'scenes/authentication/shared/OtherRegionHint'
import { RedirectIfLoggedInOtherInstance } from 'scenes/authentication/shared/RedirectToLoggedInInstance'
diff --git a/frontend/src/scenes/authentication/shared/RedirectToLoggedInInstance.tsx b/frontend/src/scenes/authentication/shared/RedirectToLoggedInInstance.tsx
index bd0be58fac38..b627ba84843c 100644
--- a/frontend/src/scenes/authentication/shared/RedirectToLoggedInInstance.tsx
+++ b/frontend/src/scenes/authentication/shared/RedirectToLoggedInInstance.tsx
@@ -28,7 +28,7 @@ import { LemonButton, LemonModal } from '@posthog/lemon-ui'
import { getCookie } from 'lib/api'
import { useOnMountEffect } from 'lib/hooks/useOnMountEffect'
import { LemonProgress } from 'lib/lemon-ui/LemonProgress'
-import { roundToDecimal } from 'lib/utils'
+import { roundToDecimal } from 'lib/utils/numbers'
// cookie values
const PH_CURRENT_INSTANCE = 'ph_current_instance'
diff --git a/frontend/src/scenes/authentication/signup/signupForm/signupLogic.ts b/frontend/src/scenes/authentication/signup/signupForm/signupLogic.ts
index bcb6672d3244..d28ea1e53dbb 100644
--- a/frontend/src/scenes/authentication/signup/signupForm/signupLogic.ts
+++ b/frontend/src/scenes/authentication/signup/signupForm/signupLogic.ts
@@ -10,7 +10,7 @@ import api from 'lib/api'
import { ValidatedPasswordResult, validatePassword } from 'lib/components/PasswordStrength'
import { CLOUD_HOSTNAMES, FEATURE_FLAGS } from 'lib/constants'
import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
-import { getRelativeNextPath } from 'lib/utils'
+import { getRelativeNextPath } from 'lib/utils/url'
import { preflightLogic } from 'scenes/PreflightCheck/preflightLogic'
import { getPasskeyErrorMessage, isWebAuthnCancellation } from 'scenes/settings/user/passkeys/utils'
import { RegistrationBeginResponse } from 'scenes/settings/user/passkeySettingsLogic'
diff --git a/frontend/src/scenes/authentication/verify-email/verifyEmailLogic.ts b/frontend/src/scenes/authentication/verify-email/verifyEmailLogic.ts
index 19f671b1b13c..b9c23f2edf1e 100644
--- a/frontend/src/scenes/authentication/verify-email/verifyEmailLogic.ts
+++ b/frontend/src/scenes/authentication/verify-email/verifyEmailLogic.ts
@@ -4,7 +4,7 @@ import { router, urlToAction } from 'kea-router'
import api from 'lib/api'
import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'
-import { getRelativeNextPath } from 'lib/utils'
+import { getRelativeNextPath } from 'lib/utils/url'
import { urls } from 'scenes/urls'
import { userLogic } from 'scenes/userLogic'
diff --git a/frontend/src/scenes/billing/Billing.tsx b/frontend/src/scenes/billing/Billing.tsx
index a9793af25bde..7099ccf8048e 100644
--- a/frontend/src/scenes/billing/Billing.tsx
+++ b/frontend/src/scenes/billing/Billing.tsx
@@ -17,7 +17,7 @@ import { dayjs } from 'lib/dayjs'
import { LemonBanner } from 'lib/lemon-ui/LemonBanner'
import { SpinnerOverlay } from 'lib/lemon-ui/Spinner/Spinner'
import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
-import { toSentenceCase } from 'lib/utils'
+import { toSentenceCase } from 'lib/utils/strings'
import { couponLogic } from 'scenes/coupons/couponLogic'
import { getProductIcon } from 'scenes/onboarding/utils'
import { membersLogic } from 'scenes/organization/membersLogic'
diff --git a/frontend/src/scenes/billing/BillingProduct.tsx b/frontend/src/scenes/billing/BillingProduct.tsx
index 1fcac01ef2b2..293a47aad394 100644
--- a/frontend/src/scenes/billing/BillingProduct.tsx
+++ b/frontend/src/scenes/billing/BillingProduct.tsx
@@ -13,7 +13,8 @@ import { LemonBanner } from 'lib/lemon-ui/LemonBanner'
import { More } from 'lib/lemon-ui/LemonButton/More'
import { Tooltip } from 'lib/lemon-ui/Tooltip'
import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
-import { capitalizeFirstLetter, humanFriendlyCurrency } from 'lib/utils'
+import { humanFriendlyCurrency } from 'lib/utils/numbers'
+import { capitalizeFirstLetter } from 'lib/utils/strings'
import { getProductIcon } from 'scenes/onboarding/utils'
import { ProductKey } from '~/queries/schema/schema-general'
diff --git a/frontend/src/scenes/billing/BillingProductAddon.tsx b/frontend/src/scenes/billing/BillingProductAddon.tsx
index d8239a6488ab..d5ef541e9020 100644
--- a/frontend/src/scenes/billing/BillingProductAddon.tsx
+++ b/frontend/src/scenes/billing/BillingProductAddon.tsx
@@ -5,7 +5,7 @@ import { ReactNode, useRef } from 'react'
import { IconCheckCircle, IconInfo } from '@posthog/icons'
import { LemonSelectOptions, LemonTag, Link, Tooltip } from '@posthog/lemon-ui'
-import { humanFriendlyCurrency } from 'lib/utils'
+import { humanFriendlyCurrency } from 'lib/utils/numbers'
import { getProductIcon } from 'scenes/onboarding/utils'
import { BillingProductV2AddonType } from '~/types'
diff --git a/frontend/src/scenes/billing/BillingSummary.tsx b/frontend/src/scenes/billing/BillingSummary.tsx
index 2ca3bf687fae..615f414f88d9 100644
--- a/frontend/src/scenes/billing/BillingSummary.tsx
+++ b/frontend/src/scenes/billing/BillingSummary.tsx
@@ -2,7 +2,7 @@ import { useValues } from 'kea'
import { dayjs } from 'lib/dayjs'
import { LemonLabel } from 'lib/lemon-ui/LemonLabel/LemonLabel'
-import { humanFriendlyCurrency } from 'lib/utils'
+import { humanFriendlyCurrency } from 'lib/utils/numbers'
import { billingLogic } from './billingLogic'
import { StripePortalButton } from './StripePortalButton'
diff --git a/frontend/src/scenes/billing/PlatformAddonComparison.tsx b/frontend/src/scenes/billing/PlatformAddonComparison.tsx
index f9d00996497f..c9edb6a66a04 100644
--- a/frontend/src/scenes/billing/PlatformAddonComparison.tsx
+++ b/frontend/src/scenes/billing/PlatformAddonComparison.tsx
@@ -21,7 +21,8 @@ import { UNSUBSCRIBE_SURVEY_ID } from 'lib/constants'
import { dayjs } from 'lib/dayjs'
import { More } from 'lib/lemon-ui/LemonButton/More'
import { LemonCollapse } from 'lib/lemon-ui/LemonCollapse'
-import { humanFriendlyCurrency, toSentenceCase } from 'lib/utils'
+import { humanFriendlyCurrency } from 'lib/utils/numbers'
+import { toSentenceCase } from 'lib/utils/strings'
import { BillingFeatureType, BillingPlan, BillingProductV2AddonType, BillingProductV2Type } from '~/types'
diff --git a/frontend/src/scenes/billing/ProductPricingModal.tsx b/frontend/src/scenes/billing/ProductPricingModal.tsx
index 98a2806b18f2..0fc9a2e97183 100644
--- a/frontend/src/scenes/billing/ProductPricingModal.tsx
+++ b/frontend/src/scenes/billing/ProductPricingModal.tsx
@@ -1,6 +1,6 @@
import { LemonModal } from '@posthog/lemon-ui'
-import { capitalizeFirstLetter } from 'lib/utils'
+import { capitalizeFirstLetter } from 'lib/utils/strings'
import { BillingPlanType, BillingProductV2AddonType, BillingProductV2Type } from '~/types'
diff --git a/frontend/src/scenes/billing/UnsubscribeSurveyModal.tsx b/frontend/src/scenes/billing/UnsubscribeSurveyModal.tsx
index 50520636807e..deaa240a4cc1 100644
--- a/frontend/src/scenes/billing/UnsubscribeSurveyModal.tsx
+++ b/frontend/src/scenes/billing/UnsubscribeSurveyModal.tsx
@@ -19,7 +19,7 @@ import {
import { HeartHog } from 'lib/components/hedgehogs'
import { useHogfetti } from 'lib/components/Hogfetti/Hogfetti'
import { supportLogic } from 'lib/components/Support/supportLogic'
-import { humanFriendlyCurrency } from 'lib/utils'
+import { humanFriendlyCurrency } from 'lib/utils/numbers'
import { BillingProductV2AddonType, BillingProductV2Type } from '~/types'
diff --git a/frontend/src/scenes/billing/billing-utils.ts b/frontend/src/scenes/billing/billing-utils.ts
index 1356454ab768..ac9b4892cfdf 100644
--- a/frontend/src/scenes/billing/billing-utils.ts
+++ b/frontend/src/scenes/billing/billing-utils.ts
@@ -5,8 +5,10 @@ import Papa from 'papaparse'
import { FEATURE_FLAGS, OrganizationMembershipLevel } from 'lib/constants'
import { dayjs } from 'lib/dayjs'
-import { compactNumber, dateStringToDayJs, wordPluralize } from 'lib/utils'
+import { dateStringToDayJs } from 'lib/utils/dateFilters'
+import { compactNumber } from 'lib/utils/numbers'
import { membershipLevelToName } from 'lib/utils/permissioning'
+import { wordPluralize } from 'lib/utils/strings'
import { Params } from 'scenes/sceneTypes'
import { BillingPeriod, BillingProductV2AddonType, BillingProductV2Type, BillingTierType, BillingType } from '~/types'
diff --git a/frontend/src/scenes/billing/billingLogic.tsx b/frontend/src/scenes/billing/billingLogic.tsx
index 39f3724807ff..63a94bc7859b 100644
--- a/frontend/src/scenes/billing/billingLogic.tsx
+++ b/frontend/src/scenes/billing/billingLogic.tsx
@@ -13,8 +13,8 @@ import { LemonBannerAction } from 'lib/lemon-ui/LemonBanner/LemonBanner'
import { lemonBannerLogic } from 'lib/lemon-ui/LemonBanner/lemonBannerLogic'
import { LemonButtonPropsBase } from 'lib/lemon-ui/LemonButton'
import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
-import { pluralize } from 'lib/utils'
import { eventUsageLogic } from 'lib/utils/eventUsageLogic'
+import { pluralize } from 'lib/utils/strings'
import { organizationLogic } from 'scenes/organizationLogic'
import { preflightLogic } from 'scenes/PreflightCheck/preflightLogic'
import { userLogic } from 'scenes/userLogic'
diff --git a/frontend/src/scenes/billing/billingSpendLogic.ts b/frontend/src/scenes/billing/billingSpendLogic.ts
index f2c50cc3f8bc..e7e97bdefdd2 100644
--- a/frontend/src/scenes/billing/billingSpendLogic.ts
+++ b/frontend/src/scenes/billing/billingSpendLogic.ts
@@ -9,8 +9,9 @@ import { lemonToast } from '@posthog/lemon-ui'
import api from 'lib/api'
import { dayjs } from 'lib/dayjs'
-import { dateMapping, toParams } from 'lib/utils'
+import { dateMapping } from 'lib/utils/dateFilters'
import { eventUsageLogic } from 'lib/utils/eventUsageLogic'
+import { toParams } from 'lib/utils/url'
import { preflightLogic } from 'scenes/PreflightCheck/preflightLogic'
import { Params } from 'scenes/sceneTypes'
diff --git a/frontend/src/scenes/billing/billingUsageLogic.ts b/frontend/src/scenes/billing/billingUsageLogic.ts
index d08bcfbf7353..3ef52a5dd89d 100644
--- a/frontend/src/scenes/billing/billingUsageLogic.ts
+++ b/frontend/src/scenes/billing/billingUsageLogic.ts
@@ -9,8 +9,9 @@ import { lemonToast } from '@posthog/lemon-ui'
import api from 'lib/api'
import { dayjs } from 'lib/dayjs'
-import { dateMapping, toParams } from 'lib/utils'
+import { dateMapping } from 'lib/utils/dateFilters'
import { eventUsageLogic } from 'lib/utils/eventUsageLogic'
+import { toParams } from 'lib/utils/url'
import { preflightLogic } from 'scenes/PreflightCheck/preflightLogic'
import { Params } from 'scenes/sceneTypes'
diff --git a/frontend/src/scenes/cohorts/CohortFilters/CohortCriteriaGroups.tsx b/frontend/src/scenes/cohorts/CohortFilters/CohortCriteriaGroups.tsx
index e95b73306060..5e43dd6c267d 100644
--- a/frontend/src/scenes/cohorts/CohortFilters/CohortCriteriaGroups.tsx
+++ b/frontend/src/scenes/cohorts/CohortFilters/CohortCriteriaGroups.tsx
@@ -11,7 +11,7 @@ import { LemonBanner } from 'lib/lemon-ui/LemonBanner'
import { LemonButton } from 'lib/lemon-ui/LemonButton'
import { LemonDivider } from 'lib/lemon-ui/LemonDivider'
import { Lettermark, LettermarkColor } from 'lib/lemon-ui/Lettermark'
-import { alphabet } from 'lib/utils'
+import { alphabet } from 'lib/utils/strings'
import { CohortLogicProps, cohortEditLogic } from 'scenes/cohorts/cohortEditLogic'
import { CohortCriteriaRowBuilder } from 'scenes/cohorts/CohortFilters/CohortCriteriaRowBuilder'
import { criteriaToBehavioralFilterType, isCohortCriteriaGroup } from 'scenes/cohorts/cohortUtils'
diff --git a/frontend/src/scenes/cohorts/CohortFilters/CohortField.tsx b/frontend/src/scenes/cohorts/CohortFilters/CohortField.tsx
index b4ab04545a53..0bc0dcf44e09 100644
--- a/frontend/src/scenes/cohorts/CohortFilters/CohortField.tsx
+++ b/frontend/src/scenes/cohorts/CohortFilters/CohortField.tsx
@@ -14,7 +14,7 @@ import { dayjs } from 'lib/dayjs'
import { LemonButton, LemonButtonWithDropdown } from 'lib/lemon-ui/LemonButton'
import { LemonDivider } from 'lib/lemon-ui/LemonDivider'
import { LemonInput } from 'lib/lemon-ui/LemonInput/LemonInput'
-import { formatDate } from 'lib/utils'
+import { formatDate } from 'lib/utils/datetime'
import { cohortFieldLogic } from 'scenes/cohorts/CohortFilters/cohortFieldLogic'
import {
CohortEventFiltersFieldProps,
diff --git a/frontend/src/scenes/cohorts/CohortFilters/cohortFieldLogic.ts b/frontend/src/scenes/cohorts/CohortFilters/cohortFieldLogic.ts
index 64980a05a435..6f0a57683998 100644
--- a/frontend/src/scenes/cohorts/CohortFilters/cohortFieldLogic.ts
+++ b/frontend/src/scenes/cohorts/CohortFilters/cohortFieldLogic.ts
@@ -1,7 +1,7 @@
import { actions, connect, kea, key, listeners, path, props, propsChanged, reducers, selectors } from 'kea'
import { TaxonomicFilterGroupType } from 'lib/components/TaxonomicFilter/types'
-import { objectsEqual } from 'lib/utils'
+import { objectsEqual } from 'lib/utils/objects'
import { FIELD_VALUES, SCALE_FIELD_VALUES } from 'scenes/cohorts/CohortFilters/constants'
import { BehavioralFilterKey, FieldOptionsType, FieldValues } from 'scenes/cohorts/CohortFilters/types'
import { cleanBehavioralTypeCriteria, resolveCohortFieldValue } from 'scenes/cohorts/cohortUtils'
diff --git a/frontend/src/scenes/cohorts/cohortEditLogic.ts b/frontend/src/scenes/cohorts/cohortEditLogic.ts
index acbc934d0ba9..d8a374077f5a 100644
--- a/frontend/src/scenes/cohorts/cohortEditLogic.ts
+++ b/frontend/src/scenes/cohorts/cohortEditLogic.ts
@@ -25,8 +25,8 @@ import { SetupTaskId, globalSetupLogic } from 'lib/components/ProductSetup'
import { ENTITY_MATCH_TYPE } from 'lib/constants'
import { scrollToFormError } from 'lib/forms/scrollToFormError'
import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'
-import { isOperatorDate } from 'lib/utils'
import { eventUsageLogic } from 'lib/utils/eventUsageLogic'
+import { isOperatorDate } from 'lib/utils/operators'
import { NEW_COHORT, NEW_CRITERIA, NEW_CRITERIA_GROUP } from 'scenes/cohorts/CohortFilters/constants'
import { BehavioralFilterKey } from 'scenes/cohorts/CohortFilters/types'
import {
diff --git a/frontend/src/scenes/cohorts/cohortUtils.tsx b/frontend/src/scenes/cohorts/cohortUtils.tsx
index b8917db0af99..da93fc461a41 100644
--- a/frontend/src/scenes/cohorts/cohortUtils.tsx
+++ b/frontend/src/scenes/cohorts/cohortUtils.tsx
@@ -3,7 +3,9 @@ import { DeepPartialMap, ValidationErrorType } from 'kea-forms'
import { isEmptyProperty, propertyFilterTypeToPropertyDefinitionType } from 'lib/components/PropertyFilters/utils'
import { ENTITY_MATCH_TYPE, PROPERTY_MATCH_TYPE } from 'lib/constants'
-import { areObjectValuesEmpty, calculateDays, isNumeric } from 'lib/utils'
+import { calculateDays } from 'lib/utils/durations'
+import { isNumeric } from 'lib/utils/guards'
+import { areObjectValuesEmpty } from 'lib/utils/objects'
import { BEHAVIORAL_TYPE_TO_LABEL, CRITERIA_VALIDATIONS, ROWS } from 'scenes/cohorts/CohortFilters/constants'
import {
BehavioralFilterKey,
diff --git a/frontend/src/scenes/cohorts/cohortsSceneLogic.ts b/frontend/src/scenes/cohorts/cohortsSceneLogic.ts
index 7ce8fbdc4642..4f7233f33fa2 100644
--- a/frontend/src/scenes/cohorts/cohortsSceneLogic.ts
+++ b/frontend/src/scenes/cohorts/cohortsSceneLogic.ts
@@ -8,8 +8,8 @@ import { PaginationManual, Sorting } from '@posthog/lemon-ui'
import api, { CountedPaginatedResponse } from 'lib/api'
import { exportsLogic } from 'lib/components/ExportButton/exportsLogic'
import { trackedActionToUrl } from 'lib/logic/scenes/trackedActionToUrl'
-import { objectsEqual } from 'lib/utils'
import { deleteWithUndo } from 'lib/utils/deleteWithUndo'
+import { objectsEqual } from 'lib/utils/objects'
import { personsLogic } from 'scenes/persons/personsLogic'
import { urls } from 'scenes/urls'
diff --git a/frontend/src/scenes/comments/Comment.tsx b/frontend/src/scenes/comments/Comment.tsx
index dd53ec318618..06902ce2718a 100644
--- a/frontend/src/scenes/comments/Comment.tsx
+++ b/frontend/src/scenes/comments/Comment.tsx
@@ -17,7 +17,7 @@ import {
LemonRichContentEditor,
serializationOptions,
} from 'lib/lemon-ui/LemonRichContent/LemonRichContentEditor'
-import { colonDelimitedDuration } from 'lib/utils'
+import { colonDelimitedDuration } from 'lib/utils/durations'
import { KeyboardShortcut } from '~/layout/navigation-3000/components/KeyboardShortcut'
import { CommentType } from '~/types'
diff --git a/frontend/src/scenes/comments/commentsLogic.ts b/frontend/src/scenes/comments/commentsLogic.ts
index 82b54c925ebf..c4b62b226876 100644
--- a/frontend/src/scenes/comments/commentsLogic.ts
+++ b/frontend/src/scenes/comments/commentsLogic.ts
@@ -4,8 +4,8 @@ import { subscriptions } from 'kea-subscriptions'
import api from 'lib/api'
import { RichContentEditorType } from 'lib/components/RichContentEditor/types'
-import { isEmptyObject } from 'lib/utils'
import { deleteWithUndo } from 'lib/utils/deleteWithUndo'
+import { isEmptyObject } from 'lib/utils/guards'
import { membersLogic } from 'scenes/organization/membersLogic'
import { sceneLogic } from 'scenes/sceneLogic'
import { teamLogic } from 'scenes/teamLogic'
diff --git a/frontend/src/scenes/dashboard/DashboardReloadAction.tsx b/frontend/src/scenes/dashboard/DashboardReloadAction.tsx
index ca43b2efbb90..26e8403ad04a 100644
--- a/frontend/src/scenes/dashboard/DashboardReloadAction.tsx
+++ b/frontend/src/scenes/dashboard/DashboardReloadAction.tsx
@@ -12,7 +12,7 @@ import { dayjs } from 'lib/dayjs'
import { usePageVisibilityCb } from 'lib/hooks/usePageVisibility'
import { LemonMenuOverlay } from 'lib/lemon-ui/LemonMenu/LemonMenu'
import { LemonRadio } from 'lib/lemon-ui/LemonRadio'
-import { humanFriendlyDuration } from 'lib/utils'
+import { humanFriendlyDuration } from 'lib/utils/durations'
import { dashboardLogic } from 'scenes/dashboard/dashboardLogic'
import { Scene } from 'scenes/sceneTypes'
diff --git a/frontend/src/scenes/dashboard/DashboardSceneMenuBar.tsx b/frontend/src/scenes/dashboard/DashboardSceneMenuBar.tsx
index 879d6d14d1b4..20e9a6c1d798 100644
--- a/frontend/src/scenes/dashboard/DashboardSceneMenuBar.tsx
+++ b/frontend/src/scenes/dashboard/DashboardSceneMenuBar.tsx
@@ -24,10 +24,10 @@ import { SceneActivityIndicator } from 'lib/components/Scenes/SceneUpdateActivit
import { urlForSubscriptions } from 'lib/components/Subscriptions/utils'
import { FEATURE_FLAGS } from 'lib/constants'
import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
-import { slugify } from 'lib/utils'
import { getAccessControlDisabledReason, userHasAccess } from 'lib/utils/accessControlUtils'
import { DashboardEventSource } from 'lib/utils/eventUsageLogic'
import { newInternalTab } from 'lib/utils/newInternalTab'
+import { slugify } from 'lib/utils/strings'
import { deleteDashboardLogic } from 'scenes/dashboard/deleteDashboardLogic'
import { duplicateDashboardLogic } from 'scenes/dashboard/duplicateDashboardLogic'
import { interProjectCopyLogic } from 'scenes/resource-transfer/interProjectCopyLogic'
diff --git a/frontend/src/scenes/dashboard/DashboardScenePanel.tsx b/frontend/src/scenes/dashboard/DashboardScenePanel.tsx
index fe58be9fb42e..790e6893693f 100644
--- a/frontend/src/scenes/dashboard/DashboardScenePanel.tsx
+++ b/frontend/src/scenes/dashboard/DashboardScenePanel.tsx
@@ -15,8 +15,8 @@ import { SceneTags } from 'lib/components/Scenes/SceneTags'
import { SceneActivityIndicator } from 'lib/components/Scenes/SceneUpdateActivityInfo'
import { useFeatureFlag } from 'lib/hooks/useFeatureFlag'
import { ButtonPrimitive } from 'lib/ui/Button/ButtonPrimitives'
-import { slugify } from 'lib/utils'
import { DashboardEventSource } from 'lib/utils/eventUsageLogic'
+import { slugify } from 'lib/utils/strings'
import { deleteDashboardLogic } from 'scenes/dashboard/deleteDashboardLogic'
import { duplicateDashboardLogic } from 'scenes/dashboard/duplicateDashboardLogic'
import { interProjectCopyLogic } from 'scenes/resource-transfer/interProjectCopyLogic'
diff --git a/frontend/src/scenes/dashboard/NewDashboardModal.tsx b/frontend/src/scenes/dashboard/NewDashboardModal.tsx
index 328d55d3e986..7239d6c183e7 100644
--- a/frontend/src/scenes/dashboard/NewDashboardModal.tsx
+++ b/frontend/src/scenes/dashboard/NewDashboardModal.tsx
@@ -4,8 +4,8 @@ import { useMemo } from 'react'
import { LemonButton, LemonInput } from '@posthog/lemon-ui'
import { DialogClose, DialogPrimitive, DialogPrimitiveTitle } from 'lib/ui/DialogPrimitive/DialogPrimitive'
-import { pluralize } from 'lib/utils'
import { cn } from 'lib/utils/css-classes'
+import { pluralize } from 'lib/utils/strings'
import { dashboardTemplateChooserLogic } from 'scenes/dashboard/dashboards/templates/dashboardTemplateChooserLogic'
import { dashboardTemplatesLogic } from 'scenes/dashboard/dashboards/templates/dashboardTemplatesLogic'
import { newDashboardLogic } from 'scenes/dashboard/newDashboardLogic'
diff --git a/frontend/src/scenes/dashboard/dashboardActivityDescriber.tsx b/frontend/src/scenes/dashboard/dashboardActivityDescriber.tsx
index 1114f86bad30..9eb696bd323f 100644
--- a/frontend/src/scenes/dashboard/dashboardActivityDescriber.tsx
+++ b/frontend/src/scenes/dashboard/dashboardActivityDescriber.tsx
@@ -21,7 +21,8 @@ import {
VariablesSummary,
} from 'lib/components/Cards/InsightCard/InsightDetails'
import { ObjectTags } from 'lib/components/ObjectTags/ObjectTags'
-import { isKeyOf, pluralize } from 'lib/utils'
+import { isKeyOf } from 'lib/utils/guards'
+import { pluralize } from 'lib/utils/strings'
import { urls } from 'scenes/urls'
import { DashboardType } from '~/types'
diff --git a/frontend/src/scenes/dashboard/dashboardLogic.tsx b/frontend/src/scenes/dashboard/dashboardLogic.tsx
index fc8eba3047d9..c8515c0da5cc 100644
--- a/frontend/src/scenes/dashboard/dashboardLogic.tsx
+++ b/frontend/src/scenes/dashboard/dashboardLogic.tsx
@@ -37,9 +37,11 @@ import { FEATURE_FLAGS } from 'lib/constants'
import { Dayjs, dayjs, now } from 'lib/dayjs'
import { Link } from 'lib/lemon-ui/Link'
import { featureFlagLogic, getFeatureFlagPayload } from 'lib/logic/featureFlagLogic'
-import { clearDOMTextSelection, getJSHeapMemory, shouldCancelQuery, toParams, uuid } from 'lib/utils'
import { accessLevelSatisfied } from 'lib/utils/accessControlUtils'
+import { clearDOMTextSelection, getJSHeapMemory, uuid } from 'lib/utils/dom'
import { DashboardEventSource, eventUsageLogic } from 'lib/utils/eventUsageLogic'
+import { shouldCancelQuery } from 'lib/utils/requests'
+import { toParams } from 'lib/utils/url'
import { BREAKPOINTS, dashboardToSaveableTemplate, getDashboardTileDisplayName } from 'scenes/dashboard/dashboardUtils'
import { calculateDuplicateLayout, calculateLayouts } from 'scenes/dashboard/tileLayouts'
import {
diff --git a/frontend/src/scenes/dashboard/dashboardTemplateVariablesLogic.ts b/frontend/src/scenes/dashboard/dashboardTemplateVariablesLogic.ts
index c0dc4ae3fd03..057f57ffcb31 100644
--- a/frontend/src/scenes/dashboard/dashboardTemplateVariablesLogic.ts
+++ b/frontend/src/scenes/dashboard/dashboardTemplateVariablesLogic.ts
@@ -2,7 +2,7 @@ import { actions, afterMount, connect, kea, listeners, path, props, propsChanged
import { iframedToolbarBrowserLogic } from 'lib/components/IframedToolbarBrowser/iframedToolbarBrowserLogic'
import { PostHogAppToolbarEvent } from 'lib/components/IframedToolbarBrowser/utils'
-import { isEmptyObject } from 'lib/utils'
+import { isEmptyObject } from 'lib/utils/guards'
import {
ActionType,
diff --git a/frontend/src/scenes/dashboard/dashboardUtils.ts b/frontend/src/scenes/dashboard/dashboardUtils.ts
index d12819faa37a..3fd010f66b62 100644
--- a/frontend/src/scenes/dashboard/dashboardUtils.ts
+++ b/frontend/src/scenes/dashboard/dashboardUtils.ts
@@ -6,9 +6,11 @@ import { getDashboardWidgetCatalogEntry } from '@posthog/products-dashboards/fro
import api, { ApiMethodOptions, getJSONOrNull } from 'lib/api'
import type { Dayjs } from 'lib/dayjs'
import { currentSessionId } from 'lib/internalMetrics'
-import { objectClean, shouldCancelQuery, toParams } from 'lib/utils'
import { accessLevelSatisfied } from 'lib/utils/accessControlUtils'
import { DashboardEventSource } from 'lib/utils/eventUsageLogic'
+import { objectClean } from 'lib/utils/objects'
+import { shouldCancelQuery } from 'lib/utils/requests'
+import { toParams } from 'lib/utils/url'
import { getQueryBasedInsightModel } from '~/queries/nodes/InsightViz/utils'
import { pollForResults } from '~/queries/query'
diff --git a/frontend/src/scenes/dashboard/dashboards/dashboardsLogic.ts b/frontend/src/scenes/dashboard/dashboards/dashboardsLogic.ts
index ca7ec0a74c4b..cc1266623fb1 100644
--- a/frontend/src/scenes/dashboard/dashboards/dashboardsLogic.ts
+++ b/frontend/src/scenes/dashboard/dashboards/dashboardsLogic.ts
@@ -6,7 +6,7 @@ import api, { PaginatedResponse } from 'lib/api'
import { Sorting } from 'lib/lemon-ui/LemonTable/sorting'
import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
import { trackedActionToUrl } from 'lib/logic/scenes/trackedActionToUrl'
-import { objectClean } from 'lib/utils'
+import { objectClean } from 'lib/utils/objects'
import { teamLogic } from 'scenes/teamLogic'
import { userLogic } from 'scenes/userLogic'
diff --git a/frontend/src/scenes/dashboard/dashboards/templates/DashboardTemplatesTable.tsx b/frontend/src/scenes/dashboard/dashboards/templates/DashboardTemplatesTable.tsx
index 7a1964044085..0d3cc208a096 100644
--- a/frontend/src/scenes/dashboard/dashboards/templates/DashboardTemplatesTable.tsx
+++ b/frontend/src/scenes/dashboard/dashboards/templates/DashboardTemplatesTable.tsx
@@ -12,9 +12,9 @@ import type { Sorting } from 'lib/lemon-ui/LemonTable'
import { atColumn } from 'lib/lemon-ui/LemonTable/columnUtils'
import { ProfilePicture } from 'lib/lemon-ui/ProfilePicture'
import { Tooltip } from 'lib/lemon-ui/Tooltip'
-import { humanFriendlyNumber } from 'lib/utils'
import { userHasAccess } from 'lib/utils/accessControlUtils'
import { getAppContext } from 'lib/utils/getAppContext'
+import { humanFriendlyNumber } from 'lib/utils/numbers'
import { dashboardTemplatesLogic } from 'scenes/dashboard/dashboards/templates/dashboardTemplatesLogic'
import { dashboardTemplateEditorLogic } from 'scenes/dashboard/dashboardTemplateEditorLogic'
import { urls } from 'scenes/urls'
diff --git a/frontend/src/scenes/data-management/DataManagementScene.tsx b/frontend/src/scenes/data-management/DataManagementScene.tsx
index a00dd14ef705..0e5424f6a8ee 100644
--- a/frontend/src/scenes/data-management/DataManagementScene.tsx
+++ b/frontend/src/scenes/data-management/DataManagementScene.tsx
@@ -11,7 +11,7 @@ import { LemonTab } from 'lib/lemon-ui/LemonTabs'
import { LemonTag } from 'lib/lemon-ui/LemonTag'
import { Tooltip } from 'lib/lemon-ui/Tooltip'
import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
-import { capitalizeFirstLetter } from 'lib/utils'
+import { capitalizeFirstLetter } from 'lib/utils/strings'
import { Annotations } from 'scenes/annotations'
import { NewAnnotationButton } from 'scenes/annotations/AnnotationModal'
import { Comments } from 'scenes/data-management/comments/Comments'
diff --git a/frontend/src/scenes/data-management/MaterializedColumns/MaterializedColumns.tsx b/frontend/src/scenes/data-management/MaterializedColumns/MaterializedColumns.tsx
index d06dea7cbb75..930b4beddd4b 100644
--- a/frontend/src/scenes/data-management/MaterializedColumns/MaterializedColumns.tsx
+++ b/frontend/src/scenes/data-management/MaterializedColumns/MaterializedColumns.tsx
@@ -8,7 +8,7 @@ import { LemonTable, LemonTableColumn } from 'lib/lemon-ui/LemonTable'
import { LemonTag, LemonTagType } from 'lib/lemon-ui/LemonTag/LemonTag'
import { Spinner } from 'lib/lemon-ui/Spinner/Spinner'
import { Tooltip } from 'lib/lemon-ui/Tooltip/Tooltip'
-import { humanFriendlyDetailedTime } from 'lib/utils'
+import { humanFriendlyDetailedTime } from 'lib/utils/datetime'
import { SceneExport } from 'scenes/sceneTypes'
import { teamLogic } from 'scenes/teamLogic'
import { userLogic } from 'scenes/userLogic'
diff --git a/frontend/src/scenes/data-management/comments/commentsLogic.ts b/frontend/src/scenes/data-management/comments/commentsLogic.ts
index 25c8bc5902e1..5ba011d46f9b 100644
--- a/frontend/src/scenes/data-management/comments/commentsLogic.ts
+++ b/frontend/src/scenes/data-management/comments/commentsLogic.ts
@@ -5,7 +5,7 @@ import posthog from 'posthog-js'
import { LemonSelectOption, lemonToast } from '@posthog/lemon-ui'
import api from 'lib/api'
-import { capitalizeFirstLetter } from 'lib/utils'
+import { capitalizeFirstLetter } from 'lib/utils/strings'
import { getRecordingLinkInfo } from 'scenes/comments/commentUtils'
import { teamLogic } from 'scenes/teamLogic'
import { urls } from 'scenes/urls'
diff --git a/frontend/src/scenes/data-management/dataManagementDescribers.tsx b/frontend/src/scenes/data-management/dataManagementDescribers.tsx
index 4aebc969e502..0670d9d743c8 100644
--- a/frontend/src/scenes/data-management/dataManagementDescribers.tsx
+++ b/frontend/src/scenes/data-management/dataManagementDescribers.tsx
@@ -12,7 +12,7 @@ import { SentenceList } from 'lib/components/ActivityLog/SentenceList'
import { ObjectTags } from 'lib/components/ObjectTags/ObjectTags'
import { IconVerifiedEvent } from 'lib/lemon-ui/icons'
import { Link } from 'lib/lemon-ui/Link'
-import { pluralize } from 'lib/utils'
+import { pluralize } from 'lib/utils/strings'
import { urls } from 'scenes/urls'
import { ActivityScope } from '~/types'
diff --git a/frontend/src/scenes/data-management/database/databaseTableListLogic.ts b/frontend/src/scenes/data-management/database/databaseTableListLogic.ts
index e445b548bb0b..16815912c93b 100644
--- a/frontend/src/scenes/data-management/database/databaseTableListLogic.ts
+++ b/frontend/src/scenes/data-management/database/databaseTableListLogic.ts
@@ -1,7 +1,7 @@
import { actions, kea, path, reducers, selectors } from 'kea'
import { loaders } from 'kea-loaders'
-import { objectsEqual } from 'lib/utils'
+import { objectsEqual } from 'lib/utils/objects'
import { performQuery } from '~/queries/query'
import {
diff --git a/frontend/src/scenes/data-management/definition/DefinitionEdit.tsx b/frontend/src/scenes/data-management/definition/DefinitionEdit.tsx
index 0f40c6610e25..4f20bef6089e 100644
--- a/frontend/src/scenes/data-management/definition/DefinitionEdit.tsx
+++ b/frontend/src/scenes/data-management/definition/DefinitionEdit.tsx
@@ -23,8 +23,8 @@ import { LemonLabel } from 'lib/lemon-ui/LemonLabel/LemonLabel'
import { LemonSelect } from 'lib/lemon-ui/LemonSelect'
import { LemonTextArea } from 'lib/lemon-ui/LemonTextArea/LemonTextArea'
import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'
+import { getPrimaryPropertyForEvent, hasTaxonomyPrimaryProperty } from 'lib/utils/events'
import { eventUsageLogic } from 'lib/utils/eventUsageLogic'
-import { getPrimaryPropertyForEvent, hasTaxonomyPrimaryProperty } from 'lib/utils/primaryEventProperty'
import { definitionEditLogic } from 'scenes/data-management/definition/definitionEditLogic'
import { DefinitionLogicProps, definitionLogic } from 'scenes/data-management/definition/definitionLogic'
import { PropertyAccessControl } from 'scenes/data-management/definition/PropertyAccessControl'
diff --git a/frontend/src/scenes/data-management/definition/DefinitionView.tsx b/frontend/src/scenes/data-management/definition/DefinitionView.tsx
index 3567d2635929..85e7223f0104 100644
--- a/frontend/src/scenes/data-management/definition/DefinitionView.tsx
+++ b/frontend/src/scenes/data-management/definition/DefinitionView.tsx
@@ -18,7 +18,7 @@ import { FEATURE_FLAGS } from 'lib/constants'
import { LemonButton } from 'lib/lemon-ui/LemonButton'
import { LemonDialog } from 'lib/lemon-ui/LemonDialog'
import { SpinnerOverlay } from 'lib/lemon-ui/Spinner/Spinner'
-import { getPrimaryPropertyForEvent } from 'lib/utils/primaryEventProperty'
+import { getPrimaryPropertyForEvent } from 'lib/utils/events'
import { DefinitionLogicProps, definitionLogic } from 'scenes/data-management/definition/definitionLogic'
import { EventDefinitionExperiments } from 'scenes/data-management/events/EventDefinitionExperiments'
import { EventDefinitionInsights } from 'scenes/data-management/events/EventDefinitionInsights'
diff --git a/frontend/src/scenes/data-management/definition/definitionEditLogic.ts b/frontend/src/scenes/data-management/definition/definitionEditLogic.ts
index 1db5aa94490a..6c04556ea412 100644
--- a/frontend/src/scenes/data-management/definition/definitionEditLogic.ts
+++ b/frontend/src/scenes/data-management/definition/definitionEditLogic.ts
@@ -6,7 +6,7 @@ import { subscriptions } from 'kea-subscriptions'
import api from 'lib/api'
import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'
-import { capitalizeFirstLetter } from 'lib/utils'
+import { capitalizeFirstLetter } from 'lib/utils/strings'
import { DefinitionLogicProps, definitionLogic } from 'scenes/data-management/definition/definitionLogic'
import { propertyAccessControlLogic } from 'scenes/data-management/definition/propertyAccessControlLogic'
import { eventDefinitionsTableLogic } from 'scenes/data-management/events/eventDefinitionsTableLogic'
diff --git a/frontend/src/scenes/data-management/events/eventDefinitionsTableLogic.ts b/frontend/src/scenes/data-management/events/eventDefinitionsTableLogic.ts
index 8d7c31a3e806..fab65fcec65f 100644
--- a/frontend/src/scenes/data-management/events/eventDefinitionsTableLogic.ts
+++ b/frontend/src/scenes/data-management/events/eventDefinitionsTableLogic.ts
@@ -5,8 +5,9 @@ import { actionToUrl, combineUrl, router, urlToAction } from 'kea-router'
import api, { PaginatedResponse } from 'lib/api'
import { convertPropertyGroupToProperties } from 'lib/components/PropertyFilters/utils'
import { EVENT_DEFINITIONS_PER_PAGE, PROPERTY_DEFINITIONS_PER_EVENT } from 'lib/constants'
-import { objectsEqual, parseTagsFilter } from 'lib/utils'
import { eventUsageLogic } from 'lib/utils/eventUsageLogic'
+import { objectsEqual } from 'lib/utils/objects'
+import { parseTagsFilter } from 'lib/utils/url'
import { AnyPropertyFilter, EventDefinition, EventDefinitionType, PropertyDefinition } from '~/types'
diff --git a/frontend/src/scenes/data-management/events/eventInsightsLogic.ts b/frontend/src/scenes/data-management/events/eventInsightsLogic.ts
index 589556e2c2fc..bc723f7808ff 100644
--- a/frontend/src/scenes/data-management/events/eventInsightsLogic.ts
+++ b/frontend/src/scenes/data-management/events/eventInsightsLogic.ts
@@ -3,8 +3,9 @@ import { loaders } from 'kea-loaders'
import api from 'lib/api'
import { Sorting } from 'lib/lemon-ui/LemonTable'
-import { objectsEqual, toParams } from 'lib/utils'
import { eventUsageLogic } from 'lib/utils/eventUsageLogic'
+import { objectsEqual } from 'lib/utils/objects'
+import { toParams } from 'lib/utils/url'
import { InsightsResult, SavedInsightFilters, cleanFilters } from 'scenes/saved-insights/savedInsightsLogic'
import { teamLogic } from 'scenes/teamLogic'
diff --git a/frontend/src/scenes/data-management/ingestion-warnings/ingestionWarningsLogic.ts b/frontend/src/scenes/data-management/ingestion-warnings/ingestionWarningsLogic.ts
index df3c9d878797..2fb8a070b889 100644
--- a/frontend/src/scenes/data-management/ingestion-warnings/ingestionWarningsLogic.ts
+++ b/frontend/src/scenes/data-management/ingestion-warnings/ingestionWarningsLogic.ts
@@ -3,7 +3,7 @@ import { loaders } from 'kea-loaders'
import api from 'lib/api'
import { dayjs, dayjsUtcToTimezone } from 'lib/dayjs'
-import { range } from 'lib/utils'
+import { range } from 'lib/utils/arrays'
import { projectLogic } from 'scenes/projectLogic'
import { Scene } from 'scenes/sceneTypes'
import { urls } from 'scenes/urls'
diff --git a/frontend/src/scenes/data-management/properties/propertyDefinitionsTableLogic.ts b/frontend/src/scenes/data-management/properties/propertyDefinitionsTableLogic.ts
index e9baaef36c88..ca89eabf364e 100644
--- a/frontend/src/scenes/data-management/properties/propertyDefinitionsTableLogic.ts
+++ b/frontend/src/scenes/data-management/properties/propertyDefinitionsTableLogic.ts
@@ -5,8 +5,9 @@ import { actionToUrl, combineUrl, router, urlToAction } from 'kea-router'
import api from 'lib/api'
import { EVENT_PROPERTY_DEFINITIONS_PER_PAGE } from 'lib/constants'
import { LemonSelectOption } from 'lib/lemon-ui/LemonSelect'
-import { capitalizeFirstLetter, objectsEqual } from 'lib/utils'
import { eventUsageLogic } from 'lib/utils/eventUsageLogic'
+import { objectsEqual } from 'lib/utils/objects'
+import { capitalizeFirstLetter } from 'lib/utils/strings'
import {
PropertyDefinitionsPaginatedResponse,
normalizePropertyDefinitionEndpointUrl,
diff --git a/frontend/src/scenes/data-pipelines/DataPipelinesNewScene.tsx b/frontend/src/scenes/data-pipelines/DataPipelinesNewScene.tsx
index 4aec6118b676..c16b11321a68 100644
--- a/frontend/src/scenes/data-pipelines/DataPipelinesNewScene.tsx
+++ b/frontend/src/scenes/data-pipelines/DataPipelinesNewScene.tsx
@@ -3,7 +3,7 @@ import { BindLogic, kea, path, props, selectors, useValues } from 'kea'
import { LemonSkeleton } from '@posthog/lemon-ui'
import { NotFound } from 'lib/components/NotFound'
-import { capitalizeFirstLetter } from 'lib/utils'
+import { capitalizeFirstLetter } from 'lib/utils/strings'
import { humanizeHogFunctionType } from 'scenes/hog-functions/hog-function-utils'
import { HogFunctionTemplateList } from 'scenes/hog-functions/list/HogFunctionTemplateList'
import { Scene, SceneExport } from 'scenes/sceneTypes'
diff --git a/frontend/src/scenes/data-pipelines/batch-exports/BatchExportConfiguration.tsx b/frontend/src/scenes/data-pipelines/batch-exports/BatchExportConfiguration.tsx
index a0e70c6a933b..dd477040ef35 100644
--- a/frontend/src/scenes/data-pipelines/batch-exports/BatchExportConfiguration.tsx
+++ b/frontend/src/scenes/data-pipelines/batch-exports/BatchExportConfiguration.tsx
@@ -16,7 +16,7 @@ import { LemonInputSelect } from 'lib/lemon-ui/LemonInputSelect/LemonInputSelect
import { LemonLabel } from 'lib/lemon-ui/LemonLabel'
import { Spinner } from 'lib/lemon-ui/Spinner'
import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
-import { timeZoneLabel } from 'lib/utils'
+import { timeZoneLabel } from 'lib/utils/timezones'
import { DatabaseTable } from 'scenes/data-management/database/DatabaseTable'
import { preflightLogic } from 'scenes/PreflightCheck/preflightLogic'
import { teamLogic } from 'scenes/teamLogic'
diff --git a/frontend/src/scenes/data-pipelines/batch-exports/BatchExportRuns.tsx b/frontend/src/scenes/data-pipelines/batch-exports/BatchExportRuns.tsx
index c67a6094edf6..135c40d692ed 100644
--- a/frontend/src/scenes/data-pipelines/batch-exports/BatchExportRuns.tsx
+++ b/frontend/src/scenes/data-pipelines/batch-exports/BatchExportRuns.tsx
@@ -7,7 +7,8 @@ import { DateFilter } from 'lib/components/DateFilter/DateFilter'
import { NotFound } from 'lib/components/NotFound'
import { TZLabel } from 'lib/components/TZLabel'
import { IconCancel } from 'lib/lemon-ui/icons'
-import { capitalizeFirstLetter, humanFriendlyNumber, humanizeBytes } from 'lib/utils'
+import { humanFriendlyNumber, humanizeBytes } from 'lib/utils/numbers'
+import { capitalizeFirstLetter } from 'lib/utils/strings'
import { BatchExportConfiguration, BatchExportRun, GroupedBatchExportRuns } from '~/types'
diff --git a/frontend/src/scenes/data-pipelines/legacy-plugins/PipelineNodeLogs.tsx b/frontend/src/scenes/data-pipelines/legacy-plugins/PipelineNodeLogs.tsx
index 2945aff779a4..6615f18ee993 100644
--- a/frontend/src/scenes/data-pipelines/legacy-plugins/PipelineNodeLogs.tsx
+++ b/frontend/src/scenes/data-pipelines/legacy-plugins/PipelineNodeLogs.tsx
@@ -4,7 +4,7 @@ import { IconSearch } from '@posthog/icons'
import { LemonButton, LemonCheckbox, LemonInput, LemonSnack, LemonTable } from '@posthog/lemon-ui'
import { LOGS_PORTION_LIMIT } from 'lib/constants'
-import { pluralize } from 'lib/utils'
+import { pluralize } from 'lib/utils/strings'
import { ALL_LOG_LEVELS, PipelineNodeLogsLogicProps, pipelineNodeLogsLogic } from './pipelineNodeLogsLogic'
diff --git a/frontend/src/scenes/data-pipelines/legacy-plugins/PipelinePluginImage.tsx b/frontend/src/scenes/data-pipelines/legacy-plugins/PipelinePluginImage.tsx
index 4861a577d9ec..851e6e2a16a0 100644
--- a/frontend/src/scenes/data-pipelines/legacy-plugins/PipelinePluginImage.tsx
+++ b/frontend/src/scenes/data-pipelines/legacy-plugins/PipelinePluginImage.tsx
@@ -2,7 +2,7 @@ import { useEffect, useState } from 'react'
import { IconTerminal } from '@posthog/icons'
-import { parseGithubRepoURL } from 'lib/utils'
+import { parseGithubRepoURL } from 'lib/utils/url'
import { PluginType } from '~/types'
diff --git a/frontend/src/scenes/data-pipelines/utils/nonHogFunctionsLogic.tsx b/frontend/src/scenes/data-pipelines/utils/nonHogFunctionsLogic.tsx
index eb4f4fe226ef..76e230eb3b6b 100644
--- a/frontend/src/scenes/data-pipelines/utils/nonHogFunctionsLogic.tsx
+++ b/frontend/src/scenes/data-pipelines/utils/nonHogFunctionsLogic.tsx
@@ -3,7 +3,7 @@ import { loaders } from 'kea-loaders'
import api from 'lib/api'
import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
-import { parseGithubRepoURL } from 'lib/utils'
+import { parseGithubRepoURL } from 'lib/utils/url'
import { organizationLogic } from 'scenes/organizationLogic'
import { teamLogic } from 'scenes/teamLogic'
import { userLogic } from 'scenes/userLogic'
diff --git a/frontend/src/scenes/data-warehouse/editor/OutputPane.tsx b/frontend/src/scenes/data-warehouse/editor/OutputPane.tsx
index 29c89cbaec41..c547de1dfde7 100644
--- a/frontend/src/scenes/data-warehouse/editor/OutputPane.tsx
+++ b/frontend/src/scenes/data-warehouse/editor/OutputPane.tsx
@@ -31,7 +31,6 @@ import { IconTableChart } from 'lib/lemon-ui/icons'
import { Link } from 'lib/lemon-ui/Link'
import { LoadingBar } from 'lib/lemon-ui/LoadingBar'
import { copyToClipboard } from 'lib/utils/copyToClipboard'
-import { transformDataTableToDataTableRows } from 'lib/utils/dataTableTransformations'
import { InsightErrorState, StatelessInsightLoadingState } from 'scenes/insights/EmptyStates'
import { HogQLBoldNumber } from 'scenes/insights/views/BoldNumber/BoldNumber'
import { urls } from 'scenes/urls'
@@ -42,6 +41,7 @@ import { dataNodeLogic } from '~/queries/nodes/DataNode/dataNodeLogic'
import { ElapsedTime } from '~/queries/nodes/DataNode/ElapsedTime'
import { LoadPreviewText } from '~/queries/nodes/DataNode/LoadNext'
import { QueryExecutionDetails } from '~/queries/nodes/DataNode/QueryExecutionDetails'
+import { DataTableRow } from '~/queries/nodes/DataTable/dataTableLogic'
import { LineGraph } from '~/queries/nodes/DataVisualization/Components/Charts/LineGraph'
import { PieChart } from '~/queries/nodes/DataVisualization/Components/Charts/PieChart'
import { TwoDimensionalHeatmap } from '~/queries/nodes/DataVisualization/Components/Heatmap/TwoDimensionalHeatmap'
@@ -398,6 +398,23 @@ function VisualizationActions({
)
}
+/**
+ * Transforms DataTable format back to DataTableRow format for clipboard operations
+ */
+function transformDataTableToDataTableRows(rows: Record<string, any>[], columns: string[]): DataTableRow[] {
+ if (!columns.length || !rows.length) {
+ return []
+ }
+
+ return rows.map((row) => ({
+ result: columns.map((col, index) => {
+ // Handle both direct column access and column_index format
+ const columnKey = `${col}_${index}`
+ return row[columnKey] !== undefined ? row[columnKey] : row[col]
+ }),
+ }))
+}
+
interface ResultsActionsProps {
response: HogQLQueryResponse | undefined
rows: Record<string, any>[]
diff --git a/frontend/src/scenes/data-warehouse/editor/editorSceneLogic.tsx b/frontend/src/scenes/data-warehouse/editor/editorSceneLogic.tsx
index 4d8870f4b0a5..8c86ea7f2a75 100644
--- a/frontend/src/scenes/data-warehouse/editor/editorSceneLogic.tsx
+++ b/frontend/src/scenes/data-warehouse/editor/editorSceneLogic.tsx
@@ -2,8 +2,8 @@ import equal from 'fast-deep-equal'
import { actions, connect, kea, key, listeners, path, props, reducers, selectors } from 'kea'
import { FEATURE_FLAGS } from 'lib/constants'
-import { removeUndefinedAndNull } from 'lib/utils'
import { copyToClipboard } from 'lib/utils/copyToClipboard'
+import { removeUndefinedAndNull } from 'lib/utils/objects'
import { Scene } from 'scenes/sceneTypes'
import { urls } from 'scenes/urls'
diff --git a/frontend/src/scenes/data-warehouse/editor/output-pane-tabs/QueryInfo.tsx b/frontend/src/scenes/data-warehouse/editor/output-pane-tabs/QueryInfo.tsx
index 8ddda684bdb6..62f4c332f91b 100644
--- a/frontend/src/scenes/data-warehouse/editor/output-pane-tabs/QueryInfo.tsx
+++ b/frontend/src/scenes/data-warehouse/editor/output-pane-tabs/QueryInfo.tsx
@@ -9,7 +9,7 @@ import { LemonSegmentedButton } from 'lib/lemon-ui/LemonSegmentedButton'
import { LemonTag } from 'lib/lemon-ui/LemonTag'
import { Tooltip } from 'lib/lemon-ui/Tooltip'
import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
-import { humanFriendlyDetailedTime } from 'lib/utils'
+import { humanFriendlyDetailedTime } from 'lib/utils/datetime'
import { dataWarehouseViewsLogic } from 'scenes/data-warehouse/saved_queries/dataWarehouseViewsLogic'
import { MaterializationStatusPanel } from 'scenes/data-warehouse/saved_queries/MaterializationStatusPanel'
diff --git a/frontend/src/scenes/data-warehouse/editor/sidebar/graph/UpstreamGraph.tsx b/frontend/src/scenes/data-warehouse/editor/sidebar/graph/UpstreamGraph.tsx
index d240f6d42aba..4500843d4f6a 100644
--- a/frontend/src/scenes/data-warehouse/editor/sidebar/graph/UpstreamGraph.tsx
+++ b/frontend/src/scenes/data-warehouse/editor/sidebar/graph/UpstreamGraph.tsx
@@ -24,7 +24,7 @@ import { LemonButton, LemonTag, LemonTagType, lemonToast } from '@posthog/lemon-
import api from 'lib/api'
import { Tooltip } from 'lib/lemon-ui/Tooltip'
-import { humanFriendlyDetailedTime } from 'lib/utils'
+import { humanFriendlyDetailedTime } from 'lib/utils/datetime'
import { themeLogic } from '~/layout/navigation-3000/themeLogic'
import { LineageNode as LineageNodeType } from '~/types'
diff --git a/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.tsx b/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.tsx
index 4d8e49033726..693c59b3a263 100644
--- a/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.tsx
+++ b/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.tsx
@@ -32,7 +32,8 @@ import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
import { trackedActionToUrl } from 'lib/logic/scenes/trackedActionToUrl'
import { clearLogicReference, initModel } from 'lib/monaco/CodeEditor'
import { codeEditorLogic } from 'lib/monaco/codeEditorLogic'
-import { objectsEqual, slugify } from 'lib/utils'
+import { objectsEqual } from 'lib/utils/objects'
+import { slugify } from 'lib/utils/strings'
import { DashboardLoadAction, dashboardLogic } from 'scenes/dashboard/dashboardLogic'
import { databaseTableListLogic } from 'scenes/data-management/database/databaseTableListLogic'
import { parseQueryTablesAndColumns, queryUsesFiltersPlaceholder } from 'scenes/data-warehouse/editor/sql-utils'
diff --git a/frontend/src/scenes/data-warehouse/saved_queries/MaterializationStatusPanel.tsx b/frontend/src/scenes/data-warehouse/saved_queries/MaterializationStatusPanel.tsx
index 75653adf05bc..6228329c6df6 100644
--- a/frontend/src/scenes/data-warehouse/saved_queries/MaterializationStatusPanel.tsx
+++ b/frontend/src/scenes/data-warehouse/saved_queries/MaterializationStatusPanel.tsx
@@ -11,8 +11,10 @@ import { LemonSelect } from 'lib/lemon-ui/LemonSelect'
import { LemonTag, LemonTagType } from 'lib/lemon-ui/LemonTag'
import { Tooltip } from 'lib/lemon-ui/Tooltip'
import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
-import { humanFriendlyDetailedTime, humanFriendlyDuration, humanFriendlyNumber } from 'lib/utils'
import { getAccessControlDisabledReason } from 'lib/utils/accessControlUtils'
+import { humanFriendlyDetailedTime } from 'lib/utils/datetime'
+import { humanFriendlyDuration } from 'lib/utils/durations'
+import { humanFriendlyNumber } from 'lib/utils/numbers'
import { LogsViewer } from 'scenes/hog-functions/logs/LogsViewer'
import { teamLogic } from 'scenes/teamLogic'
import { userLogic } from 'scenes/userLogic'
diff --git a/frontend/src/scenes/data-warehouse/scene/ViewsTab.tsx b/frontend/src/scenes/data-warehouse/scene/ViewsTab.tsx
index acbcc4037a14..bc8d734a8623 100644
--- a/frontend/src/scenes/data-warehouse/scene/ViewsTab.tsx
+++ b/frontend/src/scenes/data-warehouse/scene/ViewsTab.tsx
@@ -6,7 +6,7 @@ import { AccessControlAction } from 'lib/components/AccessControlAction'
import { TZLabel } from 'lib/components/TZLabel'
import { More } from 'lib/lemon-ui/LemonButton/More'
import { LemonTableLink } from 'lib/lemon-ui/LemonTable/LemonTableLink'
-import { humanFriendlyDetailedTime } from 'lib/utils'
+import { humanFriendlyDetailedTime } from 'lib/utils/datetime'
import { STATUS_TAG_SETTINGS } from 'scenes/models/nodeDetailConstants'
import { urls } from 'scenes/urls'
diff --git a/frontend/src/scenes/debug/QueryLogTable.tsx b/frontend/src/scenes/debug/QueryLogTable.tsx
index 004b40d9d5d1..0c4e8dd5f44a 100644
--- a/frontend/src/scenes/debug/QueryLogTable.tsx
+++ b/frontend/src/scenes/debug/QueryLogTable.tsx
@@ -7,8 +7,7 @@ import { LemonButton } from 'lib/lemon-ui/LemonButton'
import { LemonTable } from 'lib/lemon-ui/LemonTable'
import { LemonTag } from 'lib/lemon-ui/LemonTag'
import { Tooltip } from 'lib/lemon-ui/Tooltip'
-
-import { humanFriendlyNumber } from '~/lib/utils'
+import { humanFriendlyNumber } from 'lib/utils/numbers'
import { queryLogTableLogic } from './queryLogTableLogic'
diff --git a/frontend/src/scenes/experiments/CopyExperimentToProjectModal.tsx b/frontend/src/scenes/experiments/CopyExperimentToProjectModal.tsx
index 4b6daf0c328b..cfebdd41a878 100644
--- a/frontend/src/scenes/experiments/CopyExperimentToProjectModal.tsx
+++ b/frontend/src/scenes/experiments/CopyExperimentToProjectModal.tsx
@@ -6,7 +6,7 @@ import { LemonInput, LemonModal, LemonSelect } from '@posthog/lemon-ui'
import api from 'lib/api'
import { LemonButton } from 'lib/lemon-ui/LemonButton'
import { PaginationManual } from 'lib/lemon-ui/PaginationControl'
-import { toParams } from 'lib/utils'
+import { toParams } from 'lib/utils/url'
import { experimentsLogic } from 'scenes/experiments/experimentsLogic'
import { slugifyFeatureFlagKey } from 'scenes/feature-flags/featureFlagLogic'
import { FLAGS_PER_PAGE, FeatureFlagsFilters } from 'scenes/feature-flags/featureFlagsLogic'
diff --git a/frontend/src/scenes/experiments/ExperimentForm/VariantDistributionEditor.tsx b/frontend/src/scenes/experiments/ExperimentForm/VariantDistributionEditor.tsx
index 8b8f1091bd19..b3941d785b7b 100644
--- a/frontend/src/scenes/experiments/ExperimentForm/VariantDistributionEditor.tsx
+++ b/frontend/src/scenes/experiments/ExperimentForm/VariantDistributionEditor.tsx
@@ -6,7 +6,8 @@ import { LemonInput } from 'lib/lemon-ui/LemonInput'
import { LemonSlider } from 'lib/lemon-ui/LemonSlider'
import { Lettermark, LettermarkColor } from 'lib/lemon-ui/Lettermark'
import { Tooltip } from 'lib/lemon-ui/Tooltip'
-import { alphabet, formatPercentage } from 'lib/utils'
+import { formatPercentage } from 'lib/utils/numbers'
+import { alphabet } from 'lib/utils/strings'
import type { MultivariateFlagVariant } from '~/types'
diff --git a/frontend/src/scenes/experiments/ExperimentForm/VariantsPanelCreateFeatureFlag.tsx b/frontend/src/scenes/experiments/ExperimentForm/VariantsPanelCreateFeatureFlag.tsx
index c29e31a41326..c065e422765d 100644
--- a/frontend/src/scenes/experiments/ExperimentForm/VariantsPanelCreateFeatureFlag.tsx
+++ b/frontend/src/scenes/experiments/ExperimentForm/VariantsPanelCreateFeatureFlag.tsx
@@ -13,7 +13,8 @@ import { LemonSlider } from 'lib/lemon-ui/LemonSlider'
import { Lettermark, LettermarkColor } from 'lib/lemon-ui/Lettermark'
import { Link } from 'lib/lemon-ui/Link/Link'
import { Tooltip } from 'lib/lemon-ui/Tooltip'
-import { alphabet, formatPercentage } from 'lib/utils'
+import { formatPercentage } from 'lib/utils/numbers'
+import { alphabet } from 'lib/utils/strings'
import { teamLogic } from 'scenes/teamLogic'
import type { Experiment, MultivariateFlagVariant } from '~/types'
diff --git a/frontend/src/scenes/experiments/ExperimentForm/selectExistingFeatureFlagModalLogic.ts b/frontend/src/scenes/experiments/ExperimentForm/selectExistingFeatureFlagModalLogic.ts
index a41590191fdf..3c303588ad25 100644
--- a/frontend/src/scenes/experiments/ExperimentForm/selectExistingFeatureFlagModalLogic.ts
+++ b/frontend/src/scenes/experiments/ExperimentForm/selectExistingFeatureFlagModalLogic.ts
@@ -4,8 +4,8 @@ import { loaders } from 'kea-loaders'
import { PaginationManual } from '@posthog/lemon-ui'
import api from 'lib/api'
-import { toParams } from 'lib/utils'
import { eventUsageLogic } from 'lib/utils/eventUsageLogic'
+import { toParams } from 'lib/utils/url'
import { FLAGS_PER_PAGE } from 'scenes/feature-flags/featureFlagsLogic'
import { teamLogic } from 'scenes/teamLogic'
diff --git a/frontend/src/scenes/experiments/ExperimentForm/variantsPanelLogic.ts b/frontend/src/scenes/experiments/ExperimentForm/variantsPanelLogic.ts
index 2969db170e08..f5dc3489ef44 100644
--- a/frontend/src/scenes/experiments/ExperimentForm/variantsPanelLogic.ts
+++ b/frontend/src/scenes/experiments/ExperimentForm/variantsPanelLogic.ts
@@ -1,7 +1,7 @@
import { kea } from 'kea'
import api from 'lib/api'
-import { toParams } from 'lib/utils'
+import { toParams } from 'lib/utils/url'
import { experimentsLogic } from 'scenes/experiments/experimentsLogic'
import { validateFeatureFlagKey } from 'scenes/feature-flags/featureFlagLogic'
import { featureFlagsLogic } from 'scenes/feature-flags/featureFlagsLogic'
diff --git a/frontend/src/scenes/experiments/ExperimentMetricConversionWindowFilter.tsx b/frontend/src/scenes/experiments/ExperimentMetricConversionWindowFilter.tsx
index 69fdbbf43877..f88d09b5bc40 100644
--- a/frontend/src/scenes/experiments/ExperimentMetricConversionWindowFilter.tsx
+++ b/frontend/src/scenes/experiments/ExperimentMetricConversionWindowFilter.tsx
@@ -1,7 +1,7 @@
import { LemonInput } from 'lib/lemon-ui/LemonInput'
import { LemonRadio } from 'lib/lemon-ui/LemonRadio'
import { LemonSelect, LemonSelectOption } from 'lib/lemon-ui/LemonSelect'
-import { capitalizeFirstLetter, pluralize } from 'lib/utils'
+import { capitalizeFirstLetter, pluralize } from 'lib/utils/strings'
import { TIME_INTERVAL_BOUNDS } from 'scenes/funnels/funnelUtils'
import { SceneSection } from '~/layout/scenes/components/SceneSection'
diff --git a/frontend/src/scenes/experiments/ExperimentView/ExperimentReloadAction.tsx b/frontend/src/scenes/experiments/ExperimentView/ExperimentReloadAction.tsx
index 0e7cdfdee276..0b0d8236470e 100644
--- a/frontend/src/scenes/experiments/ExperimentView/ExperimentReloadAction.tsx
+++ b/frontend/src/scenes/experiments/ExperimentView/ExperimentReloadAction.tsx
@@ -11,7 +11,7 @@ import { LemonMenuOverlay } from 'lib/lemon-ui/LemonMenu/LemonMenu'
import { LemonRadio } from 'lib/lemon-ui/LemonRadio'
import { Spinner } from 'lib/lemon-ui/Spinner'
import { Label } from 'lib/ui/Label/Label'
-import { humanFriendlyDuration } from 'lib/utils'
+import { humanFriendlyDuration } from 'lib/utils/durations'
import { experimentLogic } from '../experimentLogic'
diff --git a/frontend/src/scenes/experiments/ExperimentView/Exposures.tsx b/frontend/src/scenes/experiments/ExperimentView/Exposures.tsx
index 98dc48aeef82..442a3a5ee9c2 100644
--- a/frontend/src/scenes/experiments/ExperimentView/Exposures.tsx
+++ b/frontend/src/scenes/experiments/ExperimentView/Exposures.tsx
@@ -7,7 +7,8 @@ import { LemonButton, LemonCollapse, LemonTable, LemonTag, Spinner, Tooltip } fr
import { getSeriesBackgroundColor, getSeriesColor } from 'lib/colors'
import { dayjs } from 'lib/dayjs'
import { useChart } from 'lib/hooks/useChart'
-import { humanFriendlyLargeNumber, humanFriendlyNumber, pluralize } from 'lib/utils'
+import { humanFriendlyLargeNumber, humanFriendlyNumber } from 'lib/utils/numbers'
+import { pluralize } from 'lib/utils/strings'
import {
ExperimentExposureCriteria,
diff --git a/frontend/src/scenes/experiments/ExperimentWizard/steps/VariantsStep.tsx b/frontend/src/scenes/experiments/ExperimentWizard/steps/VariantsStep.tsx
index 6da9c80ac40e..20b4d8dd03af 100644
--- a/frontend/src/scenes/experiments/ExperimentWizard/steps/VariantsStep.tsx
+++ b/frontend/src/scenes/experiments/ExperimentWizard/steps/VariantsStep.tsx
@@ -3,7 +3,8 @@ import { useActions, useValues } from 'kea'
import { getSeriesColor } from 'lib/colors'
import { LemonBanner } from 'lib/lemon-ui/LemonBanner'
import { Lettermark, LettermarkColor } from 'lib/lemon-ui/Lettermark'
-import { alphabet, formatPercentage } from 'lib/utils'
+import { formatPercentage } from 'lib/utils/numbers'
+import { alphabet } from 'lib/utils/strings'
import type { FeatureFlagType } from '~/types'
diff --git a/frontend/src/scenes/experiments/Experiments.tsx b/frontend/src/scenes/experiments/Experiments.tsx
index 3c6393d15370..0ed70e803127 100644
--- a/frontend/src/scenes/experiments/Experiments.tsx
+++ b/frontend/src/scenes/experiments/Experiments.tsx
@@ -21,8 +21,8 @@ import { LemonTable, LemonTableColumn, LemonTableColumns } from 'lib/lemon-ui/Le
import { atColumn, createdAtColumn, createdByColumn } from 'lib/lemon-ui/LemonTable/columnUtils'
import { LemonTableLink } from 'lib/lemon-ui/LemonTable/LemonTableLink'
import { LemonTabs } from 'lib/lemon-ui/LemonTabs'
-import { pluralize } from 'lib/utils'
import { addProductIntentForCrossSell } from 'lib/utils/product-intents'
+import { pluralize } from 'lib/utils/strings'
import stringWithWBR from 'lib/utils/stringWithWBR'
import MaxTool from 'scenes/max/MaxTool'
import { useMaxTool } from 'scenes/max/useMaxTool'
diff --git a/frontend/src/scenes/experiments/Metrics/Selectors.tsx b/frontend/src/scenes/experiments/Metrics/Selectors.tsx
index 022fc9816b42..db8b6cdc06d0 100644
--- a/frontend/src/scenes/experiments/Metrics/Selectors.tsx
+++ b/frontend/src/scenes/experiments/Metrics/Selectors.tsx
@@ -7,7 +7,7 @@ import { HogQLEditor } from 'lib/components/HogQLEditor/HogQLEditor'
import { TaxonomicFilterGroupType } from 'lib/components/TaxonomicFilter/types'
import { groupsAccessLogic } from 'lib/introductions/groupsAccessLogic'
import { Tooltip } from 'lib/lemon-ui/Tooltip'
-import { capitalizeFirstLetter, pluralize } from 'lib/utils'
+import { capitalizeFirstLetter, pluralize } from 'lib/utils/strings'
import { TIME_INTERVAL_BOUNDS } from 'scenes/funnels/funnelUtils'
import { GroupIntroductionFooter } from 'scenes/groups/GroupsIntroduction'
import { FUNNEL_STEP_COUNT_LIMIT } from 'scenes/insights/EditorFilters/FunnelsQuerySteps'
diff --git a/frontend/src/scenes/experiments/Metrics/SharedMetricModal.tsx b/frontend/src/scenes/experiments/Metrics/SharedMetricModal.tsx
index b645f0fa890e..186173ecc283 100644
--- a/frontend/src/scenes/experiments/Metrics/SharedMetricModal.tsx
+++ b/frontend/src/scenes/experiments/Metrics/SharedMetricModal.tsx
@@ -3,7 +3,7 @@ import { useActions, useValues } from 'kea'
import { LemonBanner, LemonButton, LemonInput, LemonLabel, LemonModal, Link } from '@posthog/lemon-ui'
import { LemonTable } from 'lib/lemon-ui/LemonTable'
-import { pluralize } from 'lib/utils'
+import { pluralize } from 'lib/utils/strings'
import { urls } from 'scenes/urls'
import { tagsModel } from '~/models/tagsModel'
diff --git a/frontend/src/scenes/experiments/Metrics/sharedMetricModalLogic.ts b/frontend/src/scenes/experiments/Metrics/sharedMetricModalLogic.ts
index 3f869e6cd597..6bca8f0f227b 100644
--- a/frontend/src/scenes/experiments/Metrics/sharedMetricModalLogic.ts
+++ b/frontend/src/scenes/experiments/Metrics/sharedMetricModalLogic.ts
@@ -2,8 +2,8 @@ import { actions, connect, kea, listeners, path, reducers, selectors } from 'kea
import { loaders } from 'kea-loaders'
import api, { CountedPaginatedResponse } from 'lib/api'
-import { toParams } from 'lib/utils'
import { eventUsageLogic } from 'lib/utils/eventUsageLogic'
+import { toParams } from 'lib/utils/url'
import { teamLogic } from 'scenes/teamLogic'
import { NodeKind } from '~/queries/schema/schema-general'
diff --git a/frontend/src/scenes/experiments/MetricsView/new/MetricRowGroup.tsx b/frontend/src/scenes/experiments/MetricsView/new/MetricRowGroup.tsx
index 36ed6635f9bf..ce7b3aa04340 100644
--- a/frontend/src/scenes/experiments/MetricsView/new/MetricRowGroup.tsx
+++ b/frontend/src/scenes/experiments/MetricsView/new/MetricRowGroup.tsx
@@ -8,7 +8,7 @@ import { IconTrending } from '@posthog/icons'
import { IconTrendingDown } from 'lib/lemon-ui/icons'
import { LemonCollapse } from 'lib/lemon-ui/LemonCollapse'
-import { humanFriendlyLargeNumber } from 'lib/utils'
+import { humanFriendlyLargeNumber } from 'lib/utils/numbers'
import { VariantTag } from 'scenes/experiments/ExperimentView/VariantTag'
import { BreakdownTag } from 'scenes/insights/filters/BreakdownFilter/BreakdownTag'
import { formatBreakdownLabel } from 'scenes/insights/utils'
diff --git a/frontend/src/scenes/experiments/MetricsView/new/MetricRowGroupTooltip.tsx b/frontend/src/scenes/experiments/MetricsView/new/MetricRowGroupTooltip.tsx
index 00ae06abbdbc..5221acf97650 100644
--- a/frontend/src/scenes/experiments/MetricsView/new/MetricRowGroupTooltip.tsx
+++ b/frontend/src/scenes/experiments/MetricsView/new/MetricRowGroupTooltip.tsx
@@ -1,7 +1,7 @@
import { IconCursorClick } from '@posthog/icons'
import { LemonTag } from 'lib/lemon-ui/LemonTag'
-import { humanFriendlyNumber } from 'lib/utils'
+import { humanFriendlyNumber } from 'lib/utils/numbers'
import { VariantTag } from 'scenes/experiments/ExperimentView/VariantTag'
import { ExperimentMetric } from '~/queries/schema/schema-general'
diff --git a/frontend/src/scenes/experiments/MetricsView/new/ResultDetails.tsx b/frontend/src/scenes/experiments/MetricsView/new/ResultDetails.tsx
index 21b65434aabc..2cc05ac4bd92 100644
--- a/frontend/src/scenes/experiments/MetricsView/new/ResultDetails.tsx
+++ b/frontend/src/scenes/experiments/MetricsView/new/ResultDetails.tsx
@@ -7,7 +7,7 @@ import { LemonCollapse, LemonTable, LemonTableColumns, LemonTabs } from '@postho
import { CodeSnippet, Language } from 'lib/components/CodeSnippet'
import ViewRecordingsPlaylistButton from 'lib/components/ViewRecordingButton/ViewRecordingsPlaylistButton'
import { FEATURE_FLAGS } from 'lib/constants'
-import { humanFriendlyNumber } from 'lib/utils'
+import { humanFriendlyNumber } from 'lib/utils/numbers'
import { FunnelChart } from 'scenes/experiments/charts/funnel/FunnelChart'
import { experimentLogic } from 'scenes/experiments/experimentLogic'
import { VariantTag } from 'scenes/experiments/ExperimentView/VariantTag'
diff --git a/frontend/src/scenes/experiments/MetricsView/new/VariantTimeseriesTooltip.tsx b/frontend/src/scenes/experiments/MetricsView/new/VariantTimeseriesTooltip.tsx
index 687920b25b7d..72c110719e03 100644
--- a/frontend/src/scenes/experiments/MetricsView/new/VariantTimeseriesTooltip.tsx
+++ b/frontend/src/scenes/experiments/MetricsView/new/VariantTimeseriesTooltip.tsx
@@ -4,7 +4,7 @@ import { IconCalendar, IconClock, IconHome, IconLaptop } from '@posthog/icons'
import { dayjs } from 'lib/dayjs'
import { IconWeb } from 'lib/lemon-ui/icons'
-import { shortTimeZone } from 'lib/utils'
+import { shortTimeZone } from 'lib/utils/timezones'
import { teamLogic } from 'scenes/teamLogic'
const DATE_FORMAT = 'MMM D, YYYY'
diff --git a/frontend/src/scenes/experiments/MetricsView/shared/utils.ts b/frontend/src/scenes/experiments/MetricsView/shared/utils.ts
index 0b76c15b9c0d..d098ec0d0f7f 100644
--- a/frontend/src/scenes/experiments/MetricsView/shared/utils.ts
+++ b/frontend/src/scenes/experiments/MetricsView/shared/utils.ts
@@ -1,4 +1,4 @@
-import { humanFriendlyLargeNumber } from 'lib/utils'
+import { humanFriendlyLargeNumber } from 'lib/utils/numbers'
import type {
ActionsNode,
diff --git a/frontend/src/scenes/experiments/RunningTimeCalculator/calculations.test.ts b/frontend/src/scenes/experiments/RunningTimeCalculator/calculations.test.ts
index db42fa90216d..c048a1b6f2a0 100644
--- a/frontend/src/scenes/experiments/RunningTimeCalculator/calculations.test.ts
+++ b/frontend/src/scenes/experiments/RunningTimeCalculator/calculations.test.ts
@@ -1,4 +1,4 @@
-import { uuid } from 'lib/utils'
+import { uuid } from 'lib/utils/dom'
import {
CachedNewExperimentQueryResponse,
diff --git a/frontend/src/scenes/experiments/SharedMetrics/SharedMetrics.tsx b/frontend/src/scenes/experiments/SharedMetrics/SharedMetrics.tsx
index 535504354378..157320124cc5 100644
--- a/frontend/src/scenes/experiments/SharedMetrics/SharedMetrics.tsx
+++ b/frontend/src/scenes/experiments/SharedMetrics/SharedMetrics.tsx
@@ -17,7 +17,7 @@ import {
import { More } from 'lib/lemon-ui/LemonButton/More'
import { createdAtColumn, createdByColumn } from 'lib/lemon-ui/LemonTable/columnUtils'
import { LemonTableLink } from 'lib/lemon-ui/LemonTable/LemonTableLink'
-import { pluralize } from 'lib/utils'
+import { pluralize } from 'lib/utils/strings'
import stringWithWBR from 'lib/utils/stringWithWBR'
import { SceneExport } from 'scenes/sceneTypes'
import { urls } from 'scenes/urls'
diff --git a/frontend/src/scenes/experiments/SharedMetrics/sharedMetricsLogic.tsx b/frontend/src/scenes/experiments/SharedMetrics/sharedMetricsLogic.tsx
index 65b4d4a5a115..b6d9cb095680 100644
--- a/frontend/src/scenes/experiments/SharedMetrics/sharedMetricsLogic.tsx
+++ b/frontend/src/scenes/experiments/SharedMetrics/sharedMetricsLogic.tsx
@@ -4,7 +4,7 @@ import { loaders } from 'kea-loaders'
import { lemonToast } from '@posthog/lemon-ui'
import api, { CountedPaginatedResponse } from 'lib/api'
-import { toParams } from 'lib/utils'
+import { toParams } from 'lib/utils/url'
import { teamLogic } from 'scenes/teamLogic'
import type { SharedMetric } from './sharedMetricLogic'
diff --git a/frontend/src/scenes/experiments/charts/funnel/FunnelTooltip.tsx b/frontend/src/scenes/experiments/charts/funnel/FunnelTooltip.tsx
index d2525ef40941..5e6bbc595b06 100644
--- a/frontend/src/scenes/experiments/charts/funnel/FunnelTooltip.tsx
+++ b/frontend/src/scenes/experiments/charts/funnel/FunnelTooltip.tsx
@@ -5,7 +5,8 @@ import { EntityFilterInfo } from 'lib/components/EntityFilterInfo'
import { LemonDivider } from 'lib/lemon-ui/LemonDivider'
import { LemonRow } from 'lib/lemon-ui/LemonRow'
import { Lettermark, LettermarkColor } from 'lib/lemon-ui/Lettermark'
-import { humanFriendlyDuration, humanFriendlyNumber, percentage } from 'lib/utils'
+import { humanFriendlyDuration } from 'lib/utils/durations'
+import { humanFriendlyNumber, percentage } from 'lib/utils/numbers'
import { ClickToInspectActors } from 'scenes/insights/InsightTooltip/InsightTooltip'
import { useInsightTooltip } from 'scenes/insights/useInsightTooltip'
import { formatBreakdownLabel } from 'scenes/insights/utils'
diff --git a/frontend/src/scenes/experiments/charts/funnel/StepBar.tsx b/frontend/src/scenes/experiments/charts/funnel/StepBar.tsx
index 50fe2220da6d..b3b3f8527179 100644
--- a/frontend/src/scenes/experiments/charts/funnel/StepBar.tsx
+++ b/frontend/src/scenes/experiments/charts/funnel/StepBar.tsx
@@ -3,7 +3,7 @@ import { useActions } from 'kea'
import { useRef } from 'react'
import { useFeatureFlag } from 'lib/hooks/useFeatureFlag'
-import { percentage } from 'lib/utils'
+import { percentage } from 'lib/utils/numbers'
import {
ExperimentActorsQuery,
diff --git a/frontend/src/scenes/experiments/charts/funnel/StepLegend.tsx b/frontend/src/scenes/experiments/charts/funnel/StepLegend.tsx
index b7e21cbe89e1..f12f74eda5f2 100644
--- a/frontend/src/scenes/experiments/charts/funnel/StepLegend.tsx
+++ b/frontend/src/scenes/experiments/charts/funnel/StepLegend.tsx
@@ -4,7 +4,9 @@ import { IconTrendingFlat, IconTrendingFlatDown } from 'lib/lemon-ui/icons'
import { LemonRow } from 'lib/lemon-ui/LemonRow'
import { Lettermark, LettermarkColor } from 'lib/lemon-ui/Lettermark'
import { Tooltip } from 'lib/lemon-ui/Tooltip'
-import { capitalizeFirstLetter, humanFriendlyDuration, percentage, pluralize } from 'lib/utils'
+import { humanFriendlyDuration } from 'lib/utils/durations'
+import { percentage } from 'lib/utils/numbers'
+import { capitalizeFirstLetter, pluralize } from 'lib/utils/strings'
import { isExperimentFunnelMetric } from '~/queries/schema/schema-general'
import { FunnelStepWithConversionMetrics, StepOrderValue } from '~/types'
diff --git a/frontend/src/scenes/experiments/experimentLogic.tsx b/frontend/src/scenes/experiments/experimentLogic.tsx
index f05db3ecf169..a354a6042a77 100644
--- a/frontend/src/scenes/experiments/experimentLogic.tsx
+++ b/frontend/src/scenes/experiments/experimentLogic.tsx
@@ -9,9 +9,10 @@ import { SetupTaskId, globalSetupLogic } from 'lib/components/ProductSetup'
import { dayjs } from 'lib/dayjs'
import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'
import { featureFlagLogic, type FeatureFlagsSet } from 'lib/logic/featureFlagLogic'
-import { hasFormErrors, toParams } from 'lib/utils'
import { eventUsageLogic } from 'lib/utils/eventUsageLogic'
-import { addProjectIdIfMissing } from 'lib/utils/router-utils'
+import { addProjectIdIfMissing } from 'lib/utils/kea-router'
+import { hasFormErrors } from 'lib/utils/objects'
+import { toParams } from 'lib/utils/url'
import { showApprovalRequiredToast } from 'scenes/approvals/ApprovalRequiredBanner'
import { dispatchChangeRequestCreated } from 'scenes/approvals/utils'
import { billingLogic } from 'scenes/billing/billingLogic'
diff --git a/frontend/src/scenes/experiments/experimentTimeseriesLogic.ts b/frontend/src/scenes/experiments/experimentTimeseriesLogic.ts
index 6dcd99e99dea..10efb39ad2f3 100644
--- a/frontend/src/scenes/experiments/experimentTimeseriesLogic.ts
+++ b/frontend/src/scenes/experiments/experimentTimeseriesLogic.ts
@@ -5,8 +5,9 @@ import api from 'lib/api'
import { ChartDataset as ChartJsDataset } from 'lib/Chart'
import { getSeriesColor } from 'lib/colors'
import { lemonToast } from 'lib/lemon-ui/LemonToast'
-import { hexToRGBA, pluralize } from 'lib/utils'
+import { hexToRGBA } from 'lib/utils/colors'
import { eventUsageLogic } from 'lib/utils/eventUsageLogic'
+import { pluralize } from 'lib/utils/strings'
import { teamLogic } from 'scenes/teamLogic'
import {
diff --git a/frontend/src/scenes/experiments/experimentsLogic.ts b/frontend/src/scenes/experiments/experimentsLogic.ts
index 54957d6b3836..d901beaa0ddd 100644
--- a/frontend/src/scenes/experiments/experimentsLogic.ts
+++ b/frontend/src/scenes/experiments/experimentsLogic.ts
@@ -6,7 +6,8 @@ import { LemonTagType, PaginationManual } from '@posthog/lemon-ui'
import api, { CountedPaginatedResponse } from 'lib/api'
import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'
-import { objectsEqual, toParams } from 'lib/utils'
+import { objectsEqual } from 'lib/utils/objects'
+import { toParams } from 'lib/utils/url'
import { FLAGS_PER_PAGE, type FeatureFlagsResult, featureFlagsLogic } from 'scenes/feature-flags/featureFlagsLogic'
import { projectLogic } from 'scenes/projectLogic'
import { teamLogic } from 'scenes/teamLogic'
diff --git a/frontend/src/scenes/experiments/legacy/components/LegacyDataCollection.tsx b/frontend/src/scenes/experiments/legacy/components/LegacyDataCollection.tsx
index ae3681a9843a..ca65c9a18d84 100644
--- a/frontend/src/scenes/experiments/legacy/components/LegacyDataCollection.tsx
+++ b/frontend/src/scenes/experiments/legacy/components/LegacyDataCollection.tsx
@@ -5,7 +5,7 @@ import { LemonDivider, Tooltip } from '@posthog/lemon-ui'
import { dayjs } from 'lib/dayjs'
import { LemonProgress } from 'lib/lemon-ui/LemonProgress'
-import { humanFriendlyNumber } from 'lib/utils'
+import { humanFriendlyNumber } from 'lib/utils/numbers'
import {
ExperimentTrendsQuery,
diff --git a/frontend/src/scenes/experiments/legacy/components/LegacyFunnelConversionWindowFilter.tsx b/frontend/src/scenes/experiments/legacy/components/LegacyFunnelConversionWindowFilter.tsx
index d96b9e347e36..1995ae51e35c 100644
--- a/frontend/src/scenes/experiments/legacy/components/LegacyFunnelConversionWindowFilter.tsx
+++ b/frontend/src/scenes/experiments/legacy/components/LegacyFunnelConversionWindowFilter.tsx
@@ -3,7 +3,7 @@ import type { LemonSelectOption } from '@posthog/lemon-ui'
import { LemonInput, LemonSelect } from '@posthog/lemon-ui'
import { Tooltip } from 'lib/lemon-ui/Tooltip'
-import { capitalizeFirstLetter, pluralize } from 'lib/utils'
+import { capitalizeFirstLetter, pluralize } from 'lib/utils/strings'
import { TIME_INTERVAL_BOUNDS } from 'scenes/funnels/funnelUtils'
import { FunnelConversionWindowTimeUnit } from '~/types'
diff --git a/frontend/src/scenes/experiments/legacy/components/LegacySummaryTable.tsx b/frontend/src/scenes/experiments/legacy/components/LegacySummaryTable.tsx
index eae124577120..a0d9efa84e6b 100644
--- a/frontend/src/scenes/experiments/legacy/components/LegacySummaryTable.tsx
+++ b/frontend/src/scenes/experiments/legacy/components/LegacySummaryTable.tsx
@@ -7,7 +7,7 @@ import { LemonTable, LemonTableColumns, LemonTag, Tooltip } from '@posthog/lemon
import { EntityFilterInfo } from 'lib/components/EntityFilterInfo'
import ViewRecordingsPlaylistButton from 'lib/components/ViewRecordingButton/ViewRecordingsPlaylistButton'
import { LemonProgress } from 'lib/lemon-ui/LemonProgress'
-import { humanFriendlyNumber } from 'lib/utils'
+import { humanFriendlyNumber } from 'lib/utils/numbers'
import { ExperimentFunnelsQuery, ExperimentTrendsQuery, isExperimentTrendsQuery } from '~/queries/schema/schema-general'
import {
diff --git a/frontend/src/scenes/experiments/legacy/metricsView/LegacyVariantTooltip.tsx b/frontend/src/scenes/experiments/legacy/metricsView/LegacyVariantTooltip.tsx
index 71f630cda83a..4f811ddae9ca 100644
--- a/frontend/src/scenes/experiments/legacy/metricsView/LegacyVariantTooltip.tsx
+++ b/frontend/src/scenes/experiments/legacy/metricsView/LegacyVariantTooltip.tsx
@@ -1,5 +1,5 @@
import { LemonProgress } from 'lib/lemon-ui/LemonProgress'
-import { humanFriendlyNumber } from 'lib/utils'
+import { humanFriendlyNumber } from 'lib/utils/numbers'
import { InsightType, TrendExperimentVariant } from '~/types'
diff --git a/frontend/src/scenes/experiments/notebook/NotebookExperimentComponent.tsx b/frontend/src/scenes/experiments/notebook/NotebookExperimentComponent.tsx
index fe3366ca34be..ea08a600a398 100644
--- a/frontend/src/scenes/experiments/notebook/NotebookExperimentComponent.tsx
+++ b/frontend/src/scenes/experiments/notebook/NotebookExperimentComponent.tsx
@@ -6,7 +6,8 @@ import { LemonBanner, LemonDivider, LemonSkeleton } from '@posthog/lemon-ui'
import { NotFound } from 'lib/components/NotFound'
import { dayjs } from 'lib/dayjs'
-import { humanFriendlyDiff, humanFriendlyNumber } from 'lib/utils'
+import { humanFriendlyDiff } from 'lib/utils/durations'
+import { humanFriendlyNumber } from 'lib/utils/numbers'
import {
CachedNewExperimentQueryResponse,
diff --git a/frontend/src/scenes/experiments/stories/ExperimentAsymmetricIntervals.stories.tsx b/frontend/src/scenes/experiments/stories/ExperimentAsymmetricIntervals.stories.tsx
index 703b0a4a65c3..4314ae45348d 100644
--- a/frontend/src/scenes/experiments/stories/ExperimentAsymmetricIntervals.stories.tsx
+++ b/frontend/src/scenes/experiments/stories/ExperimentAsymmetricIntervals.stories.tsx
@@ -1,6 +1,6 @@
import { Meta, StoryObj } from '@storybook/react'
-import { makeDelay } from 'lib/utils'
+import { makeDelay } from 'lib/utils/async'
import { App } from 'scenes/App'
import { urls } from 'scenes/urls'
diff --git a/frontend/src/scenes/experiments/stories/ExperimentFrequentistFiveVariants.stories.tsx b/frontend/src/scenes/experiments/stories/ExperimentFrequentistFiveVariants.stories.tsx
index 272f2a43825b..0e1783ecdb0f 100644
--- a/frontend/src/scenes/experiments/stories/ExperimentFrequentistFiveVariants.stories.tsx
+++ b/frontend/src/scenes/experiments/stories/ExperimentFrequentistFiveVariants.stories.tsx
@@ -1,6 +1,6 @@
import { Meta, StoryObj } from '@storybook/react'
-import { makeDelay } from 'lib/utils'
+import { makeDelay } from 'lib/utils/async'
import { mswDecorator } from '~/mocks/browser'
import EXPERIMENT_FREQUENTIST_FIVE_VARIANTS from '~/mocks/fixtures/api/experiments/experiment_frequentist_five_variants.json'
diff --git a/frontend/src/scenes/experiments/stories/ExperimentFrequentistTwoVariants.stories.tsx b/frontend/src/scenes/experiments/stories/ExperimentFrequentistTwoVariants.stories.tsx
index 2b3002384755..e1139bb46356 100644
--- a/frontend/src/scenes/experiments/stories/ExperimentFrequentistTwoVariants.stories.tsx
+++ b/frontend/src/scenes/experiments/stories/ExperimentFrequentistTwoVariants.stories.tsx
@@ -1,6 +1,6 @@
import { Meta, StoryObj } from '@storybook/react'
-import { makeDelay } from 'lib/utils'
+import { makeDelay } from 'lib/utils/async'
import { App } from 'scenes/App'
import { urls } from 'scenes/urls'
diff --git a/frontend/src/scenes/experiments/stories/ExperimentWithFunnelMetric.stories.tsx b/frontend/src/scenes/experiments/stories/ExperimentWithFunnelMetric.stories.tsx
index 0e0c6a252b40..78f1e8ffb0b8 100644
--- a/frontend/src/scenes/experiments/stories/ExperimentWithFunnelMetric.stories.tsx
+++ b/frontend/src/scenes/experiments/stories/ExperimentWithFunnelMetric.stories.tsx
@@ -1,6 +1,6 @@
import { Meta, StoryObj } from '@storybook/react'
-import { makeDelay } from 'lib/utils'
+import { makeDelay } from 'lib/utils/async'
import { App } from 'scenes/App'
import { urls } from 'scenes/urls'
diff --git a/frontend/src/scenes/experiments/stories/ExperimentWithLegacyFunnelsQuery.stories.tsx b/frontend/src/scenes/experiments/stories/ExperimentWithLegacyFunnelsQuery.stories.tsx
index 09b5b9a918bd..53fbe339ebfc 100644
--- a/frontend/src/scenes/experiments/stories/ExperimentWithLegacyFunnelsQuery.stories.tsx
+++ b/frontend/src/scenes/experiments/stories/ExperimentWithLegacyFunnelsQuery.stories.tsx
@@ -1,6 +1,6 @@
import { Meta, StoryObj } from '@storybook/react'
-import { makeDelay } from 'lib/utils'
+import { makeDelay } from 'lib/utils/async'
import { App } from 'scenes/App'
import { urls } from 'scenes/urls'
diff --git a/frontend/src/scenes/experiments/stories/ExperimentWithLegacyTrendsQuery.stories.tsx b/frontend/src/scenes/experiments/stories/ExperimentWithLegacyTrendsQuery.stories.tsx
index 4cf61428cb0c..438ce4a0020f 100644
--- a/frontend/src/scenes/experiments/stories/ExperimentWithLegacyTrendsQuery.stories.tsx
+++ b/frontend/src/scenes/experiments/stories/ExperimentWithLegacyTrendsQuery.stories.tsx
@@ -1,6 +1,6 @@
import { Meta, StoryObj } from '@storybook/react'
-import { makeDelay } from 'lib/utils'
+import { makeDelay } from 'lib/utils/async'
import { App } from 'scenes/App'
import { urls } from 'scenes/urls'
diff --git a/frontend/src/scenes/experiments/stories/ExperimentWithMeanMetric.stories.tsx b/frontend/src/scenes/experiments/stories/ExperimentWithMeanMetric.stories.tsx
index 04a7c64a1e81..bff2344c821c 100644
--- a/frontend/src/scenes/experiments/stories/ExperimentWithMeanMetric.stories.tsx
+++ b/frontend/src/scenes/experiments/stories/ExperimentWithMeanMetric.stories.tsx
@@ -1,6 +1,6 @@
import { Meta, StoryObj } from '@storybook/react'
-import { makeDelay } from 'lib/utils'
+import { makeDelay } from 'lib/utils/async'
import { App } from 'scenes/App'
import { urls } from 'scenes/urls'
diff --git a/frontend/src/scenes/experiments/stories/ExperimentWithMultipleMetrics.stories.tsx b/frontend/src/scenes/experiments/stories/ExperimentWithMultipleMetrics.stories.tsx
index d93ca20f7cee..1bc25e86b2f1 100644
--- a/frontend/src/scenes/experiments/stories/ExperimentWithMultipleMetrics.stories.tsx
+++ b/frontend/src/scenes/experiments/stories/ExperimentWithMultipleMetrics.stories.tsx
@@ -1,6 +1,6 @@
import { Meta, StoryObj } from '@storybook/react'
-import { makeDelay } from 'lib/utils'
+import { makeDelay } from 'lib/utils/async'
import { App } from 'scenes/App'
import { urls } from 'scenes/urls'
diff --git a/frontend/src/scenes/experiments/stories/ExperimentWithMultipleMetricsReordered.stories.tsx b/frontend/src/scenes/experiments/stories/ExperimentWithMultipleMetricsReordered.stories.tsx
index 158ef2b22a41..bf08e8fc7e44 100644
--- a/frontend/src/scenes/experiments/stories/ExperimentWithMultipleMetricsReordered.stories.tsx
+++ b/frontend/src/scenes/experiments/stories/ExperimentWithMultipleMetricsReordered.stories.tsx
@@ -1,6 +1,6 @@
import { Meta, StoryObj } from '@storybook/react'
-import { makeDelay } from 'lib/utils'
+import { makeDelay } from 'lib/utils/async'
import { App } from 'scenes/App'
import { urls } from 'scenes/urls'
diff --git a/frontend/src/scenes/experiments/stories/ExperimentWithRatioMetric.stories.tsx b/frontend/src/scenes/experiments/stories/ExperimentWithRatioMetric.stories.tsx
index bf17fa4a7fb1..5046afb5f70a 100644
--- a/frontend/src/scenes/experiments/stories/ExperimentWithRatioMetric.stories.tsx
+++ b/frontend/src/scenes/experiments/stories/ExperimentWithRatioMetric.stories.tsx
@@ -1,6 +1,6 @@
import { Meta, StoryObj } from '@storybook/react'
-import { makeDelay } from 'lib/utils'
+import { makeDelay } from 'lib/utils/async'
import { App } from 'scenes/App'
import { urls } from 'scenes/urls'
diff --git a/frontend/src/scenes/experiments/utils.ts b/frontend/src/scenes/experiments/utils.ts
index a85cf7aa97d5..14c3718a3ebd 100644
--- a/frontend/src/scenes/experiments/utils.ts
+++ b/frontend/src/scenes/experiments/utils.ts
@@ -3,7 +3,7 @@ import { match } from 'ts-pattern'
import { getSeriesColor } from 'lib/colors'
import { EXPERIMENT_DEFAULT_DURATION, FunnelLayout } from 'lib/constants'
import { dayjs } from 'lib/dayjs'
-import { uuid } from 'lib/utils'
+import { uuid } from 'lib/utils/dom'
import { MathAvailability } from 'scenes/insights/filters/ActionFilter/ActionFilterRow/ActionFilterRow'
import {
diff --git a/frontend/src/scenes/exports/ExportsScene.tsx b/frontend/src/scenes/exports/ExportsScene.tsx
index 89d1a4d95bae..2bde54b4a128 100644
--- a/frontend/src/scenes/exports/ExportsScene.tsx
+++ b/frontend/src/scenes/exports/ExportsScene.tsx
@@ -9,7 +9,7 @@ import { exportsLogic } from 'lib/components/ExportButton/exportsLogic'
import { getExportDisabledReason, getExportPendingLabel } from 'lib/components/ExportButton/exportStatus'
import { takeScreenshotLogic } from 'lib/components/TakeScreenshot/takeScreenshotLogic'
import { dayjs } from 'lib/dayjs'
-import { humanFriendlyNumber } from 'lib/utils'
+import { humanFriendlyNumber } from 'lib/utils/numbers'
import { sceneConfigurations } from 'scenes/scenes'
import { Scene, SceneExport } from 'scenes/sceneTypes'
diff --git a/frontend/src/scenes/feature-flags/ConfirmationModal.tsx b/frontend/src/scenes/feature-flags/ConfirmationModal.tsx
index e6713e8cfef8..9fddb494c545 100644
--- a/frontend/src/scenes/feature-flags/ConfirmationModal.tsx
+++ b/frontend/src/scenes/feature-flags/ConfirmationModal.tsx
@@ -1,7 +1,7 @@
import { IconWarning } from '@posthog/icons'
import { LemonDialog, Link } from '@posthog/lemon-ui'
-import { capitalizeFirstLetter } from 'lib/utils'
+import { capitalizeFirstLetter } from 'lib/utils/strings'
import { urls } from 'scenes/urls'
import { FeatureFlagType } from '~/types'
diff --git a/frontend/src/scenes/feature-flags/FeatureFlagEvaluationContexts.tsx b/frontend/src/scenes/feature-flags/FeatureFlagEvaluationContexts.tsx
index 87efc9b7ab51..9ee43c064e78 100644
--- a/frontend/src/scenes/feature-flags/FeatureFlagEvaluationContexts.tsx
+++ b/frontend/src/scenes/feature-flags/FeatureFlagEvaluationContexts.tsx
@@ -7,7 +7,7 @@ import { LemonInputSelect } from 'lib/lemon-ui/LemonInputSelect'
import { LemonTag } from 'lib/lemon-ui/LemonTag'
import { Tooltip } from 'lib/lemon-ui/Tooltip'
import { ButtonPrimitive } from 'lib/ui/Button/ButtonPrimitives'
-import { colorForString } from 'lib/utils'
+import { colorForString } from 'lib/utils/colors'
import { defaultEvaluationContextsLogic } from './defaultEvaluationContextsLogic'
import { featureFlagEvaluationContextsLogic } from './featureFlagEvaluationContextsLogic'
diff --git a/frontend/src/scenes/feature-flags/FeatureFlagForm.tsx b/frontend/src/scenes/feature-flags/FeatureFlagForm.tsx
index d52c0171a81a..aa3bef9d6632 100644
--- a/frontend/src/scenes/feature-flags/FeatureFlagForm.tsx
+++ b/frontend/src/scenes/feature-flags/FeatureFlagForm.tsx
@@ -55,7 +55,7 @@ import { IconArrowDown, IconArrowUp, SortableDragIcon } from 'lib/lemon-ui/icons
import { LemonDialog } from 'lib/lemon-ui/LemonDialog'
import { LemonField } from 'lib/lemon-ui/LemonField'
import 'lib/lemon-ui/Lettermark'
-import { alphabet } from 'lib/utils'
+import { alphabet } from 'lib/utils/strings'
import { ApprovalActionKey } from 'scenes/approvals/utils'
import { JSONEditorInput } from 'scenes/feature-flags/JSONEditorInput'
import { urls } from 'scenes/urls'
diff --git a/frontend/src/scenes/feature-flags/FeatureFlagReleaseConditions.tsx b/frontend/src/scenes/feature-flags/FeatureFlagReleaseConditions.tsx
index 728013907942..db3969d1cda5 100644
--- a/frontend/src/scenes/feature-flags/FeatureFlagReleaseConditions.tsx
+++ b/frontend/src/scenes/feature-flags/FeatureFlagReleaseConditions.tsx
@@ -26,7 +26,9 @@ import { LemonRadio } from 'lib/lemon-ui/LemonRadio'
import { LemonSlider } from 'lib/lemon-ui/LemonSlider'
import { LemonTag } from 'lib/lemon-ui/LemonTag/LemonTag'
import { Spinner } from 'lib/lemon-ui/Spinner/Spinner'
-import { capitalizeFirstLetter, clamp, dateFilterToText, dateStringToComponents, pluralize } from 'lib/utils'
+import { dateFilterToText, dateStringToComponents } from 'lib/utils/dateFilters'
+import { clamp } from 'lib/utils/numbers'
+import { capitalizeFirstLetter, pluralize } from 'lib/utils/strings'
import { FeatureFlagConditionWarning } from 'scenes/feature-flags/FeatureFlagConditionWarning'
import { PercentageInput } from 'scenes/feature-flags/PercentageInput'
import { urls } from 'scenes/urls'
diff --git a/frontend/src/scenes/feature-flags/FeatureFlagReleaseConditionsCollapsible.tsx b/frontend/src/scenes/feature-flags/FeatureFlagReleaseConditionsCollapsible.tsx
index 6c8561f59c67..33ec5a713bae 100644
--- a/frontend/src/scenes/feature-flags/FeatureFlagReleaseConditionsCollapsible.tsx
+++ b/frontend/src/scenes/feature-flags/FeatureFlagReleaseConditionsCollapsible.tsx
@@ -54,7 +54,8 @@ import { LemonSlider } from 'lib/lemon-ui/LemonSlider'
import { LemonTag } from 'lib/lemon-ui/LemonTag/LemonTag'
import { Link } from 'lib/lemon-ui/Link'
import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
-import { clamp, humanFriendlyNumber, pluralize } from 'lib/utils'
+import { clamp, humanFriendlyNumber } from 'lib/utils/numbers'
+import { pluralize } from 'lib/utils/strings'
import { groupsModel } from '~/models/groupsModel'
import {
diff --git a/frontend/src/scenes/feature-flags/FeatureFlagSchedule.tsx b/frontend/src/scenes/feature-flags/FeatureFlagSchedule.tsx
index 602529b3dc63..1789077cf2dd 100644
--- a/frontend/src/scenes/feature-flags/FeatureFlagSchedule.tsx
+++ b/frontend/src/scenes/feature-flags/FeatureFlagSchedule.tsx
@@ -28,7 +28,8 @@ import { TZLabel } from 'lib/components/TZLabel'
import { dayjs } from 'lib/dayjs'
import { ProfilePicture } from 'lib/lemon-ui/ProfilePicture'
import { Tooltip } from 'lib/lemon-ui/Tooltip'
-import { hasFormErrors, shortTimeZone } from 'lib/utils'
+import { hasFormErrors } from 'lib/utils/objects'
+import { shortTimeZone } from 'lib/utils/timezones'
import { teamLogic } from 'scenes/teamLogic'
import { urls } from 'scenes/urls'
diff --git a/frontend/src/scenes/feature-flags/FeatureFlagVariantsForm.tsx b/frontend/src/scenes/feature-flags/FeatureFlagVariantsForm.tsx
index 9cc33dabbf6a..de4ade1c78fa 100644
--- a/frontend/src/scenes/feature-flags/FeatureFlagVariantsForm.tsx
+++ b/frontend/src/scenes/feature-flags/FeatureFlagVariantsForm.tsx
@@ -8,7 +8,7 @@ import ViewRecordingsPlaylistButton from 'lib/components/ViewRecordingButton/Vie
import { LemonField } from 'lib/lemon-ui/LemonField'
import { Lettermark, LettermarkColor } from 'lib/lemon-ui/Lettermark'
import { Link } from 'lib/lemon-ui/Link'
-import { alphabet } from 'lib/utils'
+import { alphabet } from 'lib/utils/strings'
import { JSONEditorInput } from 'scenes/feature-flags/JSONEditorInput'
import { PercentageInput } from 'scenes/feature-flags/PercentageInput'
import { getSurveyForFeatureFlagVariant } from 'scenes/surveys/utils'
diff --git a/frontend/src/scenes/feature-flags/FeatureFlagVariantsSection.tsx b/frontend/src/scenes/feature-flags/FeatureFlagVariantsSection.tsx
index 7982a8a7fe17..0b7816ba85e4 100644
--- a/frontend/src/scenes/feature-flags/FeatureFlagVariantsSection.tsx
+++ b/frontend/src/scenes/feature-flags/FeatureFlagVariantsSection.tsx
@@ -1,7 +1,7 @@
import { LemonCollapse, Lettermark, LettermarkColor } from '@posthog/lemon-ui'
import { CopyToClipboardInline } from 'lib/components/CopyToClipboard'
-import { alphabet } from 'lib/utils'
+import { alphabet } from 'lib/utils/strings'
import { FeatureFlagType, MultivariateFlagVariant } from '~/types'
diff --git a/frontend/src/scenes/feature-flags/FeatureFlags.tsx b/frontend/src/scenes/feature-flags/FeatureFlags.tsx
index 02c65efbba0b..d4e1e8ad16e8 100644
--- a/frontend/src/scenes/feature-flags/FeatureFlags.tsx
+++ b/frontend/src/scenes/feature-flags/FeatureFlags.tsx
@@ -25,11 +25,12 @@ import { LemonTabs } from 'lib/lemon-ui/LemonTabs'
import { Tooltip } from 'lib/lemon-ui/Tooltip'
import { featureFlagLogic as enabledFeaturesLogic } from 'lib/logic/featureFlagLogic'
import { WrappingLoadingSkeleton } from 'lib/ui/WrappingLoadingSkeleton/WrappingLoadingSkeleton'
-import { pluralize, toParams } from 'lib/utils'
import { copyToClipboard } from 'lib/utils/copyToClipboard'
import { cn } from 'lib/utils/css-classes'
import { deleteWithUndo } from 'lib/utils/deleteWithUndo'
+import { pluralize } from 'lib/utils/strings'
import stringWithWBR from 'lib/utils/stringWithWBR'
+import { toParams } from 'lib/utils/url'
import { PendingApprovalsBanner } from 'scenes/approvals/PendingApprovalsBanner'
import { NotificationsPane } from 'scenes/hog-functions/list/NotificationsPane'
import { projectLogic } from 'scenes/projectLogic'
diff --git a/frontend/src/scenes/feature-flags/activityDescriptions.tsx b/frontend/src/scenes/feature-flags/activityDescriptions.tsx
index 178334f8ab0a..518dd2cd0d03 100644
--- a/frontend/src/scenes/feature-flags/activityDescriptions.tsx
+++ b/frontend/src/scenes/feature-flags/activityDescriptions.tsx
@@ -14,7 +14,7 @@ import { SentenceList } from 'lib/components/ActivityLog/SentenceList'
import { ObjectTags } from 'lib/components/ObjectTags/ObjectTags'
import { PropertyFilterButton } from 'lib/components/PropertyFilters/components/PropertyFilterButton'
import { Link } from 'lib/lemon-ui/Link'
-import { pluralize } from 'lib/utils'
+import { pluralize } from 'lib/utils/strings'
import { urls } from 'scenes/urls'
import {
diff --git a/frontend/src/scenes/feature-flags/featureFlagLogic.ts b/frontend/src/scenes/feature-flags/featureFlagLogic.ts
index 11a2487a2b37..b89701be06d9 100644
--- a/frontend/src/scenes/feature-flags/featureFlagLogic.ts
+++ b/frontend/src/scenes/feature-flags/featureFlagLogic.ts
@@ -29,9 +29,10 @@ import { scrollToFormError } from 'lib/forms/scrollToFormError'
import { LemonDialog } from 'lib/lemon-ui/LemonDialog'
import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'
import { featureFlagLogic as enabledFeaturesLogic } from 'lib/logic/featureFlagLogic'
-import { objectsEqual, slugify } from 'lib/utils'
import { deleteWithUndo } from 'lib/utils/deleteWithUndo'
import { eventUsageLogic } from 'lib/utils/eventUsageLogic'
+import { objectsEqual } from 'lib/utils/objects'
+import { slugify } from 'lib/utils/strings'
import { experimentLogic } from 'scenes/experiments/experimentLogic'
import { FeatureFlagsTab, featureFlagsLogic } from 'scenes/feature-flags/featureFlagsLogic'
import { projectLogic } from 'scenes/projectLogic'
diff --git a/frontend/src/scenes/feature-flags/featureFlagReleaseConditionsLogic.ts b/frontend/src/scenes/feature-flags/featureFlagReleaseConditionsLogic.ts
index 3b6c117b4efd..7a856d9fa52b 100644
--- a/frontend/src/scenes/feature-flags/featureFlagReleaseConditionsLogic.ts
+++ b/frontend/src/scenes/feature-flags/featureFlagReleaseConditionsLogic.ts
@@ -18,7 +18,7 @@ import { v4 as uuidv4 } from 'uuid'
import api from 'lib/api'
import { isEmptyProperty } from 'lib/components/PropertyFilters/utils'
import { TaxonomicFilterGroupType, TaxonomicFilterProps } from 'lib/components/TaxonomicFilter/types'
-import { objectsEqual } from 'lib/utils'
+import { objectsEqual } from 'lib/utils/objects'
import { projectLogic } from 'scenes/projectLogic'
import { groupsModel } from '~/models/groupsModel'
diff --git a/frontend/src/scenes/feature-flags/featureFlagsLogic.ts b/frontend/src/scenes/feature-flags/featureFlagsLogic.ts
index 5f7b758ebac7..45d08b72016d 100644
--- a/frontend/src/scenes/feature-flags/featureFlagsLogic.ts
+++ b/frontend/src/scenes/feature-flags/featureFlagsLogic.ts
@@ -6,7 +6,8 @@ import { PaginationManual } from '@posthog/lemon-ui'
import api, { CountedPaginatedResponse } from 'lib/api'
import { SetupTaskId, globalSetupLogic } from 'lib/components/ProductSetup'
-import { objectsEqual, parseTagsFilter, toParams } from 'lib/utils'
+import { objectsEqual } from 'lib/utils/objects'
+import { parseTagsFilter, toParams } from 'lib/utils/url'
import { showApprovalRequiredToast } from 'scenes/approvals/ApprovalRequiredBanner'
import { dispatchChangeRequestCreated } from 'scenes/approvals/utils'
import { projectLogic } from 'scenes/projectLogic'
diff --git a/frontend/src/scenes/feature-flags/projects-grid/projectsGridLogic.ts b/frontend/src/scenes/feature-flags/projects-grid/projectsGridLogic.ts
index 9cca9314cf37..d82f7ffbddba 100644
--- a/frontend/src/scenes/feature-flags/projects-grid/projectsGridLogic.ts
+++ b/frontend/src/scenes/feature-flags/projects-grid/projectsGridLogic.ts
@@ -2,8 +2,8 @@ import { actions, afterMount, connect, kea, listeners, path, reducers, selectors
import { loaders } from 'kea-loaders'
import api from 'lib/api'
-import { toParams } from 'lib/utils'
import { getCurrentTeamId } from 'lib/utils/getAppContext'
+import { toParams } from 'lib/utils/url'
import { organizationLogic } from 'scenes/organizationLogic'
import { projectLogic } from 'scenes/projectLogic'
import { teamLogic } from 'scenes/teamLogic'
diff --git a/frontend/src/scenes/funnels/FunnelBarHorizontal/Bar.tsx b/frontend/src/scenes/funnels/FunnelBarHorizontal/Bar.tsx
index 9a03abec866c..909caccebd41 100644
--- a/frontend/src/scenes/funnels/FunnelBarHorizontal/Bar.tsx
+++ b/frontend/src/scenes/funnels/FunnelBarHorizontal/Bar.tsx
@@ -2,7 +2,8 @@ import { useValues } from 'kea'
import { LemonDropdown } from '@posthog/lemon-ui'
-import { capitalizeFirstLetter, percentage } from 'lib/utils'
+import { percentage } from 'lib/utils/numbers'
+import { capitalizeFirstLetter } from 'lib/utils/strings'
import { insightLogic } from 'scenes/insights/insightLogic'
import { Noun } from '~/models/groupsModel'
diff --git a/frontend/src/scenes/funnels/FunnelBarHorizontal/FunnelBarHorizontal.tsx b/frontend/src/scenes/funnels/FunnelBarHorizontal/FunnelBarHorizontal.tsx
index f402deb3a8c9..6e750c97fb94 100644
--- a/frontend/src/scenes/funnels/FunnelBarHorizontal/FunnelBarHorizontal.tsx
+++ b/frontend/src/scenes/funnels/FunnelBarHorizontal/FunnelBarHorizontal.tsx
@@ -9,7 +9,8 @@ import { EntityFilterInfo } from 'lib/components/EntityFilterInfo'
import { SeriesGlyph } from 'lib/components/SeriesGlyph'
import { IconTrendingFlat, IconTrendingFlatDown } from 'lib/lemon-ui/icons'
import { Tooltip } from 'lib/lemon-ui/Tooltip'
-import { humanFriendlyDuration, percentage } from 'lib/utils'
+import { humanFriendlyDuration } from 'lib/utils/durations'
+import { percentage } from 'lib/utils/numbers'
import { insightLogic } from 'scenes/insights/insightLogic'
import { getActionFilterFromFunnelStep } from 'scenes/insights/views/Funnels/funnelStepTableUtils'
diff --git a/frontend/src/scenes/funnels/FunnelBarVertical/StepBar.tsx b/frontend/src/scenes/funnels/FunnelBarVertical/StepBar.tsx
index ebd02b9bfb3b..68d58220491b 100644
--- a/frontend/src/scenes/funnels/FunnelBarVertical/StepBar.tsx
+++ b/frontend/src/scenes/funnels/FunnelBarVertical/StepBar.tsx
@@ -2,7 +2,7 @@ import clsx from 'clsx'
import { useActions, useValues } from 'kea'
import { useRef } from 'react'
-import { percentage } from 'lib/utils'
+import { percentage } from 'lib/utils/numbers'
import { insightLogic } from 'scenes/insights/insightLogic'
import { FunnelStepWithConversionMetrics } from '~/types'
diff --git a/frontend/src/scenes/funnels/FunnelCanvasLabel.tsx b/frontend/src/scenes/funnels/FunnelCanvasLabel.tsx
index 39478bca982d..67531fd832b7 100644
--- a/frontend/src/scenes/funnels/FunnelCanvasLabel.tsx
+++ b/frontend/src/scenes/funnels/FunnelCanvasLabel.tsx
@@ -5,7 +5,8 @@ import { IconInfo, IconTestTube } from '@posthog/icons'
import { LemonButton, Link } from '@posthog/lemon-ui'
import { Tooltip } from 'lib/lemon-ui/Tooltip'
-import { humanFriendlyDuration, percentage } from 'lib/utils'
+import { humanFriendlyDuration } from 'lib/utils/durations'
+import { percentage } from 'lib/utils/numbers'
import { getExperimentMetricFromInsight } from 'scenes/experiments/utils'
import { funnelDataLogic } from 'scenes/funnels/funnelDataLogic'
import { insightLogic } from 'scenes/insights/insightLogic'
diff --git a/frontend/src/scenes/funnels/FunnelHistogram.tsx b/frontend/src/scenes/funnels/FunnelHistogram.tsx
index 42a1fbba6339..c684dc30c95c 100644
--- a/frontend/src/scenes/funnels/FunnelHistogram.tsx
+++ b/frontend/src/scenes/funnels/FunnelHistogram.tsx
@@ -5,7 +5,8 @@ import clsx from 'clsx'
import { useValues } from 'kea'
import { useRef } from 'react'
-import { hashCodeForString, humanFriendlyDuration } from 'lib/utils'
+import { humanFriendlyDuration } from 'lib/utils/durations'
+import { hashCodeForString } from 'lib/utils/strings'
import { insightLogic } from 'scenes/insights/insightLogic'
import { Histogram } from 'scenes/insights/views/Histogram'
diff --git a/frontend/src/scenes/funnels/FunnelLineGraph.tsx b/frontend/src/scenes/funnels/FunnelLineGraph.tsx
index e157dba9ee47..2d283f3e38d2 100644
--- a/frontend/src/scenes/funnels/FunnelLineGraph.tsx
+++ b/frontend/src/scenes/funnels/FunnelLineGraph.tsx
@@ -2,7 +2,7 @@ import { useValues } from 'kea'
import { DateDisplay } from 'lib/components/DateDisplay'
import { dayjs } from 'lib/dayjs'
-import { capitalizeFirstLetter } from 'lib/utils'
+import { capitalizeFirstLetter } from 'lib/utils/strings'
import { insightLogic } from 'scenes/insights/insightLogic'
import { getDatumTitle } from 'scenes/insights/InsightTooltip/insightTooltipUtils'
import { formatBreakdownLabel } from 'scenes/insights/utils'
diff --git a/frontend/src/scenes/funnels/FunnelTooltip.tsx b/frontend/src/scenes/funnels/FunnelTooltip.tsx
index 801c40c391e4..1c45c0814a27 100644
--- a/frontend/src/scenes/funnels/FunnelTooltip.tsx
+++ b/frontend/src/scenes/funnels/FunnelTooltip.tsx
@@ -6,7 +6,8 @@ import { EntityFilterInfo } from 'lib/components/EntityFilterInfo'
import { LemonDivider } from 'lib/lemon-ui/LemonDivider'
import { LemonRow } from 'lib/lemon-ui/LemonRow'
import { Lettermark, LettermarkColor } from 'lib/lemon-ui/Lettermark'
-import { humanFriendlyDuration, humanFriendlyNumber, percentage } from 'lib/utils'
+import { humanFriendlyDuration } from 'lib/utils/durations'
+import { humanFriendlyNumber, percentage } from 'lib/utils/numbers'
import { insightLogic } from 'scenes/insights/insightLogic'
import { ClickToInspectActors } from 'scenes/insights/InsightTooltip/InsightTooltip'
import { useInsightTooltip } from 'scenes/insights/useInsightTooltip'
diff --git a/frontend/src/scenes/funnels/funnelDataLogic.ts b/frontend/src/scenes/funnels/funnelDataLogic.ts
index e335d6c07a87..1d74d8013e4d 100644
--- a/frontend/src/scenes/funnels/funnelDataLogic.ts
+++ b/frontend/src/scenes/funnels/funnelDataLogic.ts
@@ -5,7 +5,7 @@ import { DataColorTheme, DataColorToken } from 'lib/colors'
import { BIN_COUNT_AUTO } from 'lib/constants'
import { dayjs } from 'lib/dayjs'
import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
-import { average, percentage, sum } from 'lib/utils'
+import { average, percentage, sum } from 'lib/utils/numbers'
import { dashboardLogic } from 'scenes/dashboard/dashboardLogic'
import { getColorFromToken } from 'scenes/dataThemeLogic'
import { AGGREGATION_LABEL_FOR_CUSTOM_DATA_WAREHOUSE } from 'scenes/insights/filters/aggregationTargetUtils'
diff --git a/frontend/src/scenes/funnels/funnelUtils.tsx b/frontend/src/scenes/funnels/funnelUtils.tsx
index 5babc75d7584..9a8f035f6310 100644
--- a/frontend/src/scenes/funnels/funnelUtils.tsx
+++ b/frontend/src/scenes/funnels/funnelUtils.tsx
@@ -1,13 +1,9 @@
import { FunnelLayout } from 'lib/constants'
import { dayjs } from 'lib/dayjs'
-import {
- autoCaptureEventToDescription,
- capitalizeFirstLetter,
- clamp,
- humanFriendlyDuration,
- percentage,
- pluralize,
-} from 'lib/utils'
+import { humanFriendlyDuration } from 'lib/utils/durations'
+import { autoCaptureEventToDescription } from 'lib/utils/events'
+import { clamp, percentage } from 'lib/utils/numbers'
+import { capitalizeFirstLetter, pluralize } from 'lib/utils/strings'
import { elementsToAction } from 'scenes/activity/explore/createActionFromEvent'
import { teamLogic } from 'scenes/teamLogic'
diff --git a/frontend/src/scenes/groups/Group.tsx b/frontend/src/scenes/groups/Group.tsx
index bed94a0d3951..116b7ea0a987 100644
--- a/frontend/src/scenes/groups/Group.tsx
+++ b/frontend/src/scenes/groups/Group.tsx
@@ -14,7 +14,7 @@ import { LemonTabs } from 'lib/lemon-ui/LemonTabs'
import { Link } from 'lib/lemon-ui/Link'
import { Spinner, SpinnerOverlay } from 'lib/lemon-ui/Spinner/Spinner'
import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
-import { capitalizeFirstLetter } from 'lib/utils'
+import { capitalizeFirstLetter } from 'lib/utils/strings'
import { GroupLogicProps, groupLogic } from 'scenes/groups/groupLogic'
import { NotebookSelectButton } from 'scenes/notebooks/NotebookSelectButton/NotebookSelectButton'
import { NotebookNodeType } from 'scenes/notebooks/types'
diff --git a/frontend/src/scenes/groups/GroupOverview.tsx b/frontend/src/scenes/groups/GroupOverview.tsx
index b7072c069853..fc48226024cc 100644
--- a/frontend/src/scenes/groups/GroupOverview.tsx
+++ b/frontend/src/scenes/groups/GroupOverview.tsx
@@ -1,6 +1,6 @@
import { useValues } from 'kea'
-import { capitalizeFirstLetter } from 'lib/utils'
+import { capitalizeFirstLetter } from 'lib/utils/strings'
import { Group } from '~/types'
diff --git a/frontend/src/scenes/groups/Groups.tsx b/frontend/src/scenes/groups/Groups.tsx
index 2b9b2fe91b5c..2b82c36c0a85 100644
--- a/frontend/src/scenes/groups/Groups.tsx
+++ b/frontend/src/scenes/groups/Groups.tsx
@@ -7,7 +7,7 @@ import { useFeatureFlag } from 'lib/hooks/useFeatureFlag'
import { groupsAccessLogic } from 'lib/introductions/groupsAccessLogic'
import { LemonButton } from 'lib/lemon-ui/LemonButton'
import { Link } from 'lib/lemon-ui/Link'
-import { capitalizeFirstLetter } from 'lib/utils'
+import { capitalizeFirstLetter } from 'lib/utils/strings'
import { GroupsIntroduction } from 'scenes/groups/GroupsIntroduction'
import { PersonsManagementSceneTabs } from 'scenes/persons-management/PersonsManagementSceneTabs'
import { SceneExport } from 'scenes/sceneTypes'
diff --git a/frontend/src/scenes/groups/RelatedGroups.tsx b/frontend/src/scenes/groups/RelatedGroups.tsx
index 95c5d73dabd2..411afe053c88 100644
--- a/frontend/src/scenes/groups/RelatedGroups.tsx
+++ b/frontend/src/scenes/groups/RelatedGroups.tsx
@@ -3,7 +3,7 @@ import { useValues } from 'kea'
import { IconPerson } from '@posthog/icons'
import { LemonTable, LemonTableColumns } from 'lib/lemon-ui/LemonTable'
-import { capitalizeFirstLetter } from 'lib/utils'
+import { capitalizeFirstLetter } from 'lib/utils/strings'
import { relatedGroupsLogic } from 'scenes/groups/relatedGroupsLogic'
import { GroupActorDisplay } from 'scenes/persons/GroupActorDisplay'
import { PersonDisplay } from 'scenes/persons/PersonDisplay'
diff --git a/frontend/src/scenes/groups/groupLogic.ts b/frontend/src/scenes/groups/groupLogic.ts
index bd0d98139fdb..00381abd47b1 100644
--- a/frontend/src/scenes/groups/groupLogic.ts
+++ b/frontend/src/scenes/groups/groupLogic.ts
@@ -7,9 +7,10 @@ import api from 'lib/api'
import { FEATURE_FLAGS } from 'lib/constants'
import { lemonToast } from 'lib/lemon-ui/LemonToast'
import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
-import { objectsEqual, toParams } from 'lib/utils'
-import { capitalizeFirstLetter } from 'lib/utils'
import { eventUsageLogic } from 'lib/utils/eventUsageLogic'
+import { objectsEqual } from 'lib/utils/objects'
+import { capitalizeFirstLetter } from 'lib/utils/strings'
+import { toParams } from 'lib/utils/url'
import { groupDisplayId } from 'scenes/persons/GroupActorDisplay'
import { Scene } from 'scenes/sceneTypes'
import { teamLogic } from 'scenes/teamLogic'
diff --git a/frontend/src/scenes/groups/groupsNewLogic.ts b/frontend/src/scenes/groups/groupsNewLogic.ts
index 15cf699b4d92..f3c31f19ed89 100644
--- a/frontend/src/scenes/groups/groupsNewLogic.ts
+++ b/frontend/src/scenes/groups/groupsNewLogic.ts
@@ -8,7 +8,7 @@ import api from 'lib/api'
import { FEATURE_FLAGS } from 'lib/constants'
import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'
import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
-import { capitalizeFirstLetter } from 'lib/utils'
+import { capitalizeFirstLetter } from 'lib/utils/strings'
import { Scene } from 'scenes/sceneTypes'
import { urls } from 'scenes/urls'
diff --git a/frontend/src/scenes/groups/groupsSceneLogic.ts b/frontend/src/scenes/groups/groupsSceneLogic.ts
index 68747b3344b5..d91a8fc6e421 100644
--- a/frontend/src/scenes/groups/groupsSceneLogic.ts
+++ b/frontend/src/scenes/groups/groupsSceneLogic.ts
@@ -2,7 +2,7 @@ import { actions, connect, kea, path, reducers, selectors } from 'kea'
import { urlToAction } from 'kea-router'
import { GroupsAccessStatus } from 'lib/introductions/groupsAccessLogic'
-import { capitalizeFirstLetter } from 'lib/utils'
+import { capitalizeFirstLetter } from 'lib/utils/strings'
import { Scene } from 'scenes/sceneTypes'
import { urls } from 'scenes/urls'
diff --git a/frontend/src/scenes/groups/relatedGroupsLogic.ts b/frontend/src/scenes/groups/relatedGroupsLogic.ts
index 8df2fb04c48a..c74c8c2d2483 100644
--- a/frontend/src/scenes/groups/relatedGroupsLogic.ts
+++ b/frontend/src/scenes/groups/relatedGroupsLogic.ts
@@ -2,7 +2,7 @@ import { connect, events, kea, key, path, props, selectors } from 'kea'
import { loaders } from 'kea-loaders'
import api from 'lib/api'
-import { toParams } from 'lib/utils'
+import { toParams } from 'lib/utils/url'
import { teamLogic } from 'scenes/teamLogic'
import { ActorType } from '~/types'
diff --git a/frontend/src/scenes/health/HealthScene.tsx b/frontend/src/scenes/health/HealthScene.tsx
index ab2ccdc16ac5..03ee67d9ec7b 100644
--- a/frontend/src/scenes/health/HealthScene.tsx
+++ b/frontend/src/scenes/health/HealthScene.tsx
@@ -6,7 +6,7 @@ import { LemonBanner, LemonButton, LemonMenu } from '@posthog/lemon-ui'
import { supportLogic } from 'lib/components/Support/supportLogic'
import { FEATURE_FLAGS } from 'lib/constants'
import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
-import { humanFriendlyDuration } from 'lib/utils'
+import { humanFriendlyDuration } from 'lib/utils/durations'
import { SceneExport } from 'scenes/sceneTypes'
import { urls } from 'scenes/urls'
diff --git a/frontend/src/scenes/health/components/IngestionWarningTable.tsx b/frontend/src/scenes/health/components/IngestionWarningTable.tsx
index 40998506359a..c20be0367c15 100644
--- a/frontend/src/scenes/health/components/IngestionWarningTable.tsx
+++ b/frontend/src/scenes/health/components/IngestionWarningTable.tsx
@@ -1,6 +1,6 @@
import { TZLabel } from 'lib/components/TZLabel'
import { LemonTable, LemonTableColumns } from 'lib/lemon-ui/LemonTable'
-import { humanFriendlyNumber } from 'lib/utils'
+import { humanFriendlyNumber } from 'lib/utils/numbers'
import { WARNING_TYPE_TO_DESCRIPTION } from 'scenes/data-management/ingestion-warnings/IngestionWarningsView'
import type { HealthIssue } from '../types'
diff --git a/frontend/src/scenes/health/healthUtils.ts b/frontend/src/scenes/health/healthUtils.ts
index 24f1f6e69677..d96bf99da26b 100644
--- a/frontend/src/scenes/health/healthUtils.ts
+++ b/frontend/src/scenes/health/healthUtils.ts
@@ -1,6 +1,6 @@
import type { LemonTagType } from '@posthog/lemon-ui'
-import { identifierToHuman } from 'lib/utils'
+import { identifierToHuman } from 'lib/utils/strings'
import { categoryForKind, HEALTH_CATEGORY_CONFIG, KIND_LABELS } from './healthCategories'
import type { HealthIssueKind } from './healthCategories'
diff --git a/frontend/src/scenes/health/pipelineStatus/PipelineStatusIssueCard.tsx b/frontend/src/scenes/health/pipelineStatus/PipelineStatusIssueCard.tsx
index 18a25db69b44..e308e63ac932 100644
--- a/frontend/src/scenes/health/pipelineStatus/PipelineStatusIssueCard.tsx
+++ b/frontend/src/scenes/health/pipelineStatus/PipelineStatusIssueCard.tsx
@@ -1,7 +1,7 @@
import { IconDatabase, IconPlug, IconRevert, IconServer, IconX } from '@posthog/icons'
import { LemonButton, LemonTag, Link } from '@posthog/lemon-ui'
-import { humanFriendlyDetailedTime } from 'lib/utils'
+import { humanFriendlyDetailedTime } from 'lib/utils/datetime'
import { urls } from 'scenes/urls'
import type { DataHealthIssue } from './pipelineHealthLogic'
diff --git a/frontend/src/scenes/heatmaps/components/FilterPanel.tsx b/frontend/src/scenes/heatmaps/components/FilterPanel.tsx
index 0d4917299509..4b04495002ec 100644
--- a/frontend/src/scenes/heatmaps/components/FilterPanel.tsx
+++ b/frontend/src/scenes/heatmaps/components/FilterPanel.tsx
@@ -14,7 +14,7 @@ import { TaxonomicFilterGroupType } from 'lib/components/TaxonomicFilter/types'
import { useFeatureFlag } from 'lib/hooks/useFeatureFlag'
import { LoadingBar } from 'lib/lemon-ui/LoadingBar'
import { Popover } from 'lib/lemon-ui/Popover'
-import { inStorybook, inStorybookTestRunner } from 'lib/utils'
+import { inStorybook, inStorybookTestRunner } from 'lib/utils/dom'
import { COHORTS_ONLY_SUPPORT_IN_PICKER_PROPS } from 'scenes/feature-flags/cohortPickerProps'
import { TestAccountFilter } from 'scenes/insights/filters/TestAccountFilter'
diff --git a/frontend/src/scenes/heatmaps/components/heatmapsBrowserLogic.ts b/frontend/src/scenes/heatmaps/components/heatmapsBrowserLogic.ts
index b4d774d6246d..f66321d33863 100644
--- a/frontend/src/scenes/heatmaps/components/heatmapsBrowserLogic.ts
+++ b/frontend/src/scenes/heatmaps/components/heatmapsBrowserLogic.ts
@@ -14,7 +14,7 @@ import { heatmapDataLogic } from 'lib/components/heatmaps/heatmapDataLogic'
import { CommonFilters, HeatmapFixedPositionMode } from 'lib/components/heatmaps/types'
import { PostHogAppToolbarEvent, calculateViewportRange } from 'lib/components/IframedToolbarBrowser/utils'
import { LemonBannerProps } from 'lib/lemon-ui/LemonBanner'
-import { objectsEqual } from 'lib/utils'
+import { objectsEqual } from 'lib/utils/objects'
import { removeReplayIframeDataFromLocalStorage } from 'scenes/session-recordings/player/sessionRecordingPlayerLogic'
import { hogql } from '~/queries/utils'
diff --git a/frontend/src/scenes/heatmaps/scenes/heatmaps/heatmapsSceneLogic.ts b/frontend/src/scenes/heatmaps/scenes/heatmaps/heatmapsSceneLogic.ts
index 490a0049f0ec..54b273bc4dcb 100644
--- a/frontend/src/scenes/heatmaps/scenes/heatmaps/heatmapsSceneLogic.ts
+++ b/frontend/src/scenes/heatmaps/scenes/heatmaps/heatmapsSceneLogic.ts
@@ -1,8 +1,8 @@
import { actions, afterMount, connect, kea, listeners, path, reducers, selectors } from 'kea'
import api from 'lib/api'
-import { objectsEqual } from 'lib/utils'
import { deleteWithUndo } from 'lib/utils/deleteWithUndo'
+import { objectsEqual } from 'lib/utils/objects'
import { sceneConfigurations } from 'scenes/scenes'
import { Scene } from 'scenes/sceneTypes'
import { teamLogic } from 'scenes/teamLogic'
diff --git a/frontend/src/scenes/hog-functions/HogFunctionScene.tsx b/frontend/src/scenes/hog-functions/HogFunctionScene.tsx
index c88c8dede241..207aae7e1d58 100644
--- a/frontend/src/scenes/hog-functions/HogFunctionScene.tsx
+++ b/frontend/src/scenes/hog-functions/HogFunctionScene.tsx
@@ -13,7 +13,7 @@ import { LemonSkeleton } from 'lib/lemon-ui/LemonSkeleton'
import { LemonTab, LemonTabs } from 'lib/lemon-ui/LemonTabs'
import { LemonTag } from 'lib/lemon-ui/LemonTag/LemonTag'
import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
-import { capitalizeFirstLetter } from 'lib/utils'
+import { capitalizeFirstLetter } from 'lib/utils/strings'
import { DataPipelinesNewSceneKind } from 'scenes/data-pipelines/DataPipelinesNewScene'
import { HogFunctionConfiguration } from 'scenes/hog-functions/configuration/HogFunctionConfiguration'
import {
diff --git a/frontend/src/scenes/hog-functions/configuration/components/hogFunctionSourceWebhookTestLogic.tsx b/frontend/src/scenes/hog-functions/configuration/components/hogFunctionSourceWebhookTestLogic.tsx
index f9b3970dbf6a..d968afc727ff 100644
--- a/frontend/src/scenes/hog-functions/configuration/components/hogFunctionSourceWebhookTestLogic.tsx
+++ b/frontend/src/scenes/hog-functions/configuration/components/hogFunctionSourceWebhookTestLogic.tsx
@@ -1,8 +1,8 @@
import { actions, connect, kea, key, path, props, reducers, selectors } from 'kea'
import { forms } from 'kea-forms'
-import { tryJsonParse } from 'lib/utils'
import { publicWebhooksHostOrigin } from 'lib/utils/apiHost'
+import { tryJsonParse } from 'lib/utils/json'
import { HogFunctionConfigurationLogicProps, hogFunctionConfigurationLogic } from '../hogFunctionConfigurationLogic'
import type { hogFunctionSourceWebhookTestLogicType } from './hogFunctionSourceWebhookTestLogicType'
diff --git a/frontend/src/scenes/hog-functions/configuration/hogFunctionConfigurationLogic.tsx b/frontend/src/scenes/hog-functions/configuration/hogFunctionConfigurationLogic.tsx
index 7b112b483abc..5997be95cda4 100644
--- a/frontend/src/scenes/hog-functions/configuration/hogFunctionConfigurationLogic.tsx
+++ b/frontend/src/scenes/hog-functions/configuration/hogFunctionConfigurationLogic.tsx
@@ -15,8 +15,8 @@ import {
CyclotronJobInputsValidationResult,
} from 'lib/components/CyclotronJob/CyclotronJobInputsValidation'
import { dayjs } from 'lib/dayjs'
-import { uuid } from 'lib/utils'
import { deleteWithUndo } from 'lib/utils/deleteWithUndo'
+import { uuid } from 'lib/utils/dom'
import { addProductIntent } from 'lib/utils/product-intents'
import { asDisplay } from 'scenes/persons/person-utils'
import { projectLogic } from 'scenes/projectLogic'
diff --git a/frontend/src/scenes/hog-functions/configuration/hogFunctionTestLogic.tsx b/frontend/src/scenes/hog-functions/configuration/hogFunctionTestLogic.tsx
index 72c3001a98e1..3ddf59c89ad4 100644
--- a/frontend/src/scenes/hog-functions/configuration/hogFunctionTestLogic.tsx
+++ b/frontend/src/scenes/hog-functions/configuration/hogFunctionTestLogic.tsx
@@ -5,8 +5,8 @@ import type { editor } from 'monaco-editor'
import { lemonToast } from '@posthog/lemon-ui'
import api from 'lib/api'
-import { tryJsonParse } from 'lib/utils'
import { getCurrentTeamId } from 'lib/utils/getAppContext'
+import { tryJsonParse } from 'lib/utils/json'
import { groupsModel } from '~/models/groupsModel'
import { CyclotronJobInvocationGlobals, CyclotronJobTestInvocationResult } from '~/types'
diff --git a/frontend/src/scenes/hog-functions/email-templater/emailTemplaterLogic.tsx b/frontend/src/scenes/hog-functions/email-templater/emailTemplaterLogic.tsx
index 8e867e28eeb9..57e5293045de 100644
--- a/frontend/src/scenes/hog-functions/email-templater/emailTemplaterLogic.tsx
+++ b/frontend/src/scenes/hog-functions/email-templater/emailTemplaterLogic.tsx
@@ -7,7 +7,7 @@ import { LemonDialog } from '@posthog/lemon-ui'
import api from 'lib/api'
import { lemonToast } from 'lib/lemon-ui/LemonToast'
-import { objectsEqual } from 'lib/utils'
+import { objectsEqual } from 'lib/utils/objects'
import { preflightLogic } from 'scenes/PreflightCheck/preflightLogic'
import { PreflightStatus, PropertyDefinition, PropertyDefinitionType, Realm } from '~/types'
diff --git a/frontend/src/scenes/hog-functions/list/hogFunctionTemplateListLogic.tsx b/frontend/src/scenes/hog-functions/list/hogFunctionTemplateListLogic.tsx
index cd050dd01ddc..86a3c5b26057 100644
--- a/frontend/src/scenes/hog-functions/list/hogFunctionTemplateListLogic.tsx
+++ b/frontend/src/scenes/hog-functions/list/hogFunctionTemplateListLogic.tsx
@@ -9,8 +9,8 @@ import { lemonToast } from '@posthog/lemon-ui'
import api from 'lib/api'
import { FEATURE_FLAGS, FeatureFlagKey } from 'lib/constants'
import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
-import { objectsEqual } from 'lib/utils'
import { createFuse } from 'lib/utils/fuseSearch'
+import { objectsEqual } from 'lib/utils/objects'
import { urls } from 'scenes/urls'
import { userLogic } from 'scenes/userLogic'
diff --git a/frontend/src/scenes/hog-functions/list/hogFunctionsListLogic.tsx b/frontend/src/scenes/hog-functions/list/hogFunctionsListLogic.tsx
index 42e9abe7fd23..454f3ce9f038 100644
--- a/frontend/src/scenes/hog-functions/list/hogFunctionsListLogic.tsx
+++ b/frontend/src/scenes/hog-functions/list/hogFunctionsListLogic.tsx
@@ -6,8 +6,8 @@ import { lemonToast } from '@posthog/lemon-ui'
import api from 'lib/api'
import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
-import { objectsEqual } from 'lib/utils'
import { deleteWithUndo } from 'lib/utils/deleteWithUndo'
+import { objectsEqual } from 'lib/utils/objects'
import { projectLogic } from 'scenes/projectLogic'
import { userLogic } from 'scenes/userLogic'
diff --git a/frontend/src/scenes/hog-functions/logs/HogFunctionLogs.tsx b/frontend/src/scenes/hog-functions/logs/HogFunctionLogs.tsx
index 6a0029084c47..28dee2af7ffd 100644
--- a/frontend/src/scenes/hog-functions/logs/HogFunctionLogs.tsx
+++ b/frontend/src/scenes/hog-functions/logs/HogFunctionLogs.tsx
@@ -6,7 +6,7 @@ import { IconEllipsis } from '@posthog/icons'
import { LemonButton, LemonCheckbox, LemonDialog, LemonMenu, LemonTag } from '@posthog/lemon-ui'
import { LemonTableColumns } from 'lib/lemon-ui/LemonTable'
-import { capitalizeFirstLetter } from 'lib/utils'
+import { capitalizeFirstLetter } from 'lib/utils/strings'
import { urls } from 'scenes/urls'
import { hogFunctionConfigurationLogic } from '../configuration/hogFunctionConfigurationLogic'
diff --git a/frontend/src/scenes/hog-functions/logs/LogLevelsPicker.tsx b/frontend/src/scenes/hog-functions/logs/LogLevelsPicker.tsx
index a42810853651..66a33f49a14f 100644
--- a/frontend/src/scenes/hog-functions/logs/LogLevelsPicker.tsx
+++ b/frontend/src/scenes/hog-functions/logs/LogLevelsPicker.tsx
@@ -2,7 +2,7 @@ import { IconFilter } from '@posthog/icons'
import { LemonMenu } from '@posthog/lemon-ui'
import { LemonButton } from 'lib/lemon-ui/LemonButton'
-import { capitalizeFirstLetter } from 'lib/utils'
+import { capitalizeFirstLetter } from 'lib/utils/strings'
import { ALL_LOG_LEVELS } from 'scenes/hog-functions/logs/logsViewerLogic'
import { LogEntryLevel } from '~/types'
diff --git a/frontend/src/scenes/hog-functions/logs/LogsViewer.tsx b/frontend/src/scenes/hog-functions/logs/LogsViewer.tsx
index 0b2e274a7667..de0984a710b6 100644
--- a/frontend/src/scenes/hog-functions/logs/LogsViewer.tsx
+++ b/frontend/src/scenes/hog-functions/logs/LogsViewer.tsx
@@ -17,7 +17,7 @@ import { CopyToClipboardInline } from 'lib/components/CopyToClipboard'
import { DateFilter } from 'lib/components/DateFilter/DateFilter'
import { TZLabel } from 'lib/components/TZLabel'
import { IconWithCount } from 'lib/lemon-ui/icons'
-import { pluralize } from 'lib/utils'
+import { pluralize } from 'lib/utils/strings'
import { LogEntryLevel } from '~/types'
diff --git a/frontend/src/scenes/hog-functions/metrics/HogFunctionEventEstimates.tsx b/frontend/src/scenes/hog-functions/metrics/HogFunctionEventEstimates.tsx
index 43a517bb72b0..44edfb956e5e 100644
--- a/frontend/src/scenes/hog-functions/metrics/HogFunctionEventEstimates.tsx
+++ b/frontend/src/scenes/hog-functions/metrics/HogFunctionEventEstimates.tsx
@@ -5,7 +5,7 @@ import { LemonLabel, LemonSelect, SpinnerOverlay } from '@posthog/lemon-ui'
import { Sparkline } from 'lib/components/Sparkline'
import { LemonBanner } from 'lib/lemon-ui/LemonBanner'
import { LemonButton } from 'lib/lemon-ui/LemonButton'
-import { base64Encode } from 'lib/utils'
+import { base64Encode } from 'lib/utils/base64'
import { urls } from 'scenes/urls'
import { Query } from '~/queries/Query/Query'
diff --git a/frontend/src/scenes/hog-functions/misc/HogFunctionStatusTag.tsx b/frontend/src/scenes/hog-functions/misc/HogFunctionStatusTag.tsx
index dec555817b8a..03c1b931c590 100644
--- a/frontend/src/scenes/hog-functions/misc/HogFunctionStatusTag.tsx
+++ b/frontend/src/scenes/hog-functions/misc/HogFunctionStatusTag.tsx
@@ -1,6 +1,6 @@
import { LemonTag } from '@posthog/lemon-ui'
-import { capitalizeFirstLetter } from 'lib/utils'
+import { capitalizeFirstLetter } from 'lib/utils/strings'
import { HogFunctionTemplateStatus } from '~/types'
diff --git a/frontend/src/scenes/hog-functions/misc/activityDescriptions.tsx b/frontend/src/scenes/hog-functions/misc/activityDescriptions.tsx
index 83246345c6db..f8d43de58861 100644
--- a/frontend/src/scenes/hog-functions/misc/activityDescriptions.tsx
+++ b/frontend/src/scenes/hog-functions/misc/activityDescriptions.tsx
@@ -9,7 +9,7 @@ import {
import { LemonDropdown } from 'lib/lemon-ui/LemonDropdown'
import { Link } from 'lib/lemon-ui/Link'
import { Spinner } from 'lib/lemon-ui/Spinner'
-import { isObject } from 'lib/utils'
+import { isObject } from 'lib/utils/guards'
import { urls } from 'scenes/urls'
import { HogFunctionTypeType } from '~/types'
diff --git a/frontend/src/scenes/hog-functions/testing/HogFunctionTesting.tsx b/frontend/src/scenes/hog-functions/testing/HogFunctionTesting.tsx
index 404da8307c5e..1a13fefa9721 100644
--- a/frontend/src/scenes/hog-functions/testing/HogFunctionTesting.tsx
+++ b/frontend/src/scenes/hog-functions/testing/HogFunctionTesting.tsx
@@ -21,7 +21,7 @@ import { DateFilter } from 'lib/components/DateFilter/DateFilter'
import { PropertyKeyInfo } from 'lib/components/PropertyKeyInfo'
import { TaxonomicFilterGroupType } from 'lib/components/TaxonomicFilter/types'
import { TZLabel } from 'lib/components/TZLabel'
-import { capitalizeFirstLetter } from 'lib/utils'
+import { capitalizeFirstLetter } from 'lib/utils/strings'
import { InsightEmptyState } from 'scenes/insights/EmptyStates'
import { PersonDisplay } from 'scenes/persons/PersonDisplay'
import { urls } from 'scenes/urls'
diff --git a/frontend/src/scenes/inbox/SignalCard.tsx b/frontend/src/scenes/inbox/SignalCard.tsx
index 60d759085acf..cd9670983d09 100644
--- a/frontend/src/scenes/inbox/SignalCard.tsx
+++ b/frontend/src/scenes/inbox/SignalCard.tsx
@@ -8,7 +8,7 @@ import { TZLabel } from 'lib/components/TZLabel'
import ViewRecordingButton, { RecordingPlayerType } from 'lib/components/ViewRecordingButton/ViewRecordingButton'
import { LemonMarkdown } from 'lib/lemon-ui/LemonMarkdown'
import { signalCardSourceLine } from 'lib/signals/signalCardSourceLine'
-import { humanFriendlyDetailedTime } from 'lib/utils'
+import { humanFriendlyDetailedTime } from 'lib/utils/datetime'
import { sourceProductColor } from 'scenes/debug/signals/helpers'
import type { SignalNode } from 'scenes/debug/signals/types'
import { urls } from 'scenes/urls'
diff --git a/frontend/src/scenes/insights/EditorFilters/PathsEventTypes.tsx b/frontend/src/scenes/insights/EditorFilters/PathsEventTypes.tsx
index 857ddd7389a6..3a65db503523 100644
--- a/frontend/src/scenes/insights/EditorFilters/PathsEventTypes.tsx
+++ b/frontend/src/scenes/insights/EditorFilters/PathsEventTypes.tsx
@@ -2,7 +2,7 @@ import { useActions, useValues } from 'kea'
import { LemonButton, LemonButtonWithDropdown } from 'lib/lemon-ui/LemonButton'
import { LemonCheckbox } from 'lib/lemon-ui/LemonCheckbox'
-import { capitalizeFirstLetter } from 'lib/utils'
+import { capitalizeFirstLetter } from 'lib/utils/strings'
import { pathsDataLogic } from 'scenes/paths/pathsDataLogic'
import { PathsFilter } from '~/queries/schema/schema-general'
diff --git a/frontend/src/scenes/insights/EditorFilters/RetentionCondition.tsx b/frontend/src/scenes/insights/EditorFilters/RetentionCondition.tsx
index b1ea2f7a8697..a5cb34276a53 100644
--- a/frontend/src/scenes/insights/EditorFilters/RetentionCondition.tsx
+++ b/frontend/src/scenes/insights/EditorFilters/RetentionCondition.tsx
@@ -7,7 +7,7 @@ import { LemonButton, LemonCheckbox, LemonInput, LemonSelect } from '@posthog/le
import { DataWarehousePopoverField, TaxonomicFilterGroupType } from 'lib/components/TaxonomicFilter/types'
import { Tooltip } from 'lib/lemon-ui/Tooltip'
-import { getOrdinalSuffix } from 'lib/utils'
+import { getOrdinalSuffix } from 'lib/utils/strings'
import { AggregationSelect } from 'scenes/insights/filters/AggregationSelect'
import { keyForInsightLogicProps } from 'scenes/insights/sharedUtils'
import { getRetentionPropertyFilterGroupTypes } from 'scenes/insights/utils/propertyTaxonomicGroupTypes'
diff --git a/frontend/src/scenes/insights/EditorFilters/RetentionOptions.tsx b/frontend/src/scenes/insights/EditorFilters/RetentionOptions.tsx
index f4a00571ce95..594b22fb7da6 100644
--- a/frontend/src/scenes/insights/EditorFilters/RetentionOptions.tsx
+++ b/frontend/src/scenes/insights/EditorFilters/RetentionOptions.tsx
@@ -4,7 +4,7 @@ import { Link } from '@posthog/lemon-ui'
import { FEATURE_FLAGS } from 'lib/constants'
import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
-import { pluralize } from 'lib/utils'
+import { pluralize } from 'lib/utils/strings'
import { insightLogic } from 'scenes/insights/insightLogic'
import { retentionLogic } from 'scenes/retention/retentionLogic'
diff --git a/frontend/src/scenes/insights/EmptyStates/EmptyStates.tsx b/frontend/src/scenes/insights/EmptyStates/EmptyStates.tsx
index 95ac8149d987..a3a23451f5b3 100644
--- a/frontend/src/scenes/insights/EmptyStates/EmptyStates.tsx
+++ b/frontend/src/scenes/insights/EmptyStates/EmptyStates.tsx
@@ -19,7 +19,8 @@ import { IconChristmasOrnament, IconErrorOutline, IconOpenInNew } from 'lib/lemo
import { LemonMenuOverlay } from 'lib/lemon-ui/LemonMenu/LemonMenu'
import { Link } from 'lib/lemon-ui/Link'
import { LoadingBar } from 'lib/lemon-ui/LoadingBar'
-import { humanFriendlyNumber, humanizeBytes, inStorybook, inStorybookTestRunner } from 'lib/utils'
+import { inStorybook, inStorybookTestRunner } from 'lib/utils/dom'
+import { humanFriendlyNumber, humanizeBytes } from 'lib/utils/numbers'
import { funnelDataLogic } from 'scenes/funnels/funnelDataLogic'
import { entityFilterLogic } from 'scenes/insights/filters/ActionFilter/entityFilterLogic'
import { insightLogic } from 'scenes/insights/insightLogic'
diff --git a/frontend/src/scenes/insights/InsightNav/insightNavLogic.tsx b/frontend/src/scenes/insights/InsightNav/insightNavLogic.tsx
index cbb197d0c6b7..d7d516bea15e 100644
--- a/frontend/src/scenes/insights/InsightNav/insightNavLogic.tsx
+++ b/frontend/src/scenes/insights/InsightNav/insightNavLogic.tsx
@@ -3,7 +3,7 @@ import { router } from 'kea-router'
import { FEATURE_FLAGS } from 'lib/constants'
import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
-import { identifierToHuman } from 'lib/utils'
+import { identifierToHuman } from 'lib/utils/strings'
import { insightDataLogic } from 'scenes/insights/insightDataLogic'
import { keyForInsightLogicProps } from 'scenes/insights/sharedUtils'
import { filterTestAccountsDefaultsLogic } from 'scenes/settings/environment/filterTestAccountDefaultsLogic'
diff --git a/frontend/src/scenes/insights/InsightTooltip/InsightTooltip.stories.tsx b/frontend/src/scenes/insights/InsightTooltip/InsightTooltip.stories.tsx
index 6fdfdb00e139..8e8dbea1c079 100644
--- a/frontend/src/scenes/insights/InsightTooltip/InsightTooltip.stories.tsx
+++ b/frontend/src/scenes/insights/InsightTooltip/InsightTooltip.stories.tsx
@@ -2,7 +2,7 @@ import type { Meta, StoryObj } from '@storybook/react'
import { useMountedLogic } from 'kea'
import { SeriesLetter } from 'lib/components/SeriesGlyph'
-import { humanFriendlyNumber } from 'lib/utils'
+import { humanFriendlyNumber } from 'lib/utils/numbers'
import { cohortsModel } from '~/models/cohortsModel'
import { InsightType } from '~/types'
diff --git a/frontend/src/scenes/insights/InsightTooltip/InsightTooltip.tsx b/frontend/src/scenes/insights/InsightTooltip/InsightTooltip.tsx
index 31b65539c417..136a98bd6b53 100644
--- a/frontend/src/scenes/insights/InsightTooltip/InsightTooltip.tsx
+++ b/frontend/src/scenes/insights/InsightTooltip/InsightTooltip.tsx
@@ -10,7 +10,7 @@ import { InsightLabel } from 'lib/components/InsightLabel'
import { dayjs } from 'lib/dayjs'
import { LemonTable, LemonTableColumn, LemonTableColumns } from 'lib/lemon-ui/LemonTable'
import { Tooltip } from 'lib/lemon-ui/Tooltip'
-import { shortTimeZone } from 'lib/utils'
+import { shortTimeZone } from 'lib/utils/timezones'
import { formatAggregationValue } from 'scenes/insights/utils'
import { teamLogic } from 'scenes/teamLogic'
diff --git a/frontend/src/scenes/insights/InsightTooltip/insightTooltipUtils.tsx b/frontend/src/scenes/insights/InsightTooltip/insightTooltipUtils.tsx
index cc7265785d62..2936bc1e262b 100644
--- a/frontend/src/scenes/insights/InsightTooltip/insightTooltipUtils.tsx
+++ b/frontend/src/scenes/insights/InsightTooltip/insightTooltipUtils.tsx
@@ -2,8 +2,8 @@ import React from 'react'
import { parseAliasToReadable } from 'lib/components/PathCleanFilters/PathCleanFilterItem'
import { dayjs } from 'lib/dayjs'
-import { capitalizeFirstLetter, midEllipsis, pluralize } from 'lib/utils'
-import { getConstrainedWeekRange, parseDateInTimezone } from 'lib/utils/dateTimeUtils'
+import { getConstrainedWeekRange, parseDateInTimezone } from 'lib/utils/datetime'
+import { capitalizeFirstLetter, midEllipsis, pluralize } from 'lib/utils/strings'
import { cohortsModel } from '~/models/cohortsModel'
import { propertyDefinitionsModel } from '~/models/propertyDefinitionsModel'
diff --git a/frontend/src/scenes/insights/aggregationAxisFormat.ts b/frontend/src/scenes/insights/aggregationAxisFormat.ts
index d9f28731bc3c..4d47814a2783 100644
--- a/frontend/src/scenes/insights/aggregationAxisFormat.ts
+++ b/frontend/src/scenes/insights/aggregationAxisFormat.ts
@@ -1,8 +1,9 @@
import posthog from 'posthog-js'
import { LemonSelectOptionLeaf } from 'lib/lemon-ui/LemonSelect'
-import { compactNumber, humanFriendlyCurrency, humanFriendlyDuration, humanFriendlyNumber, percentage } from 'lib/utils'
-import { formatCurrency } from 'lib/utils/geography/currency'
+import { formatCurrency } from 'lib/utils/currency'
+import { humanFriendlyDuration } from 'lib/utils/durations'
+import { compactNumber, humanFriendlyCurrency, humanFriendlyNumber, percentage } from 'lib/utils/numbers'
import { CurrencyCode, TrendsFilter } from '~/queries/schema/schema-general'
import { ChartDisplayType, TrendsFilterType } from '~/types'
diff --git a/frontend/src/scenes/insights/filters/ActionFilter/ActionFilter.stories.tsx b/frontend/src/scenes/insights/filters/ActionFilter/ActionFilter.stories.tsx
index 6c7be9db72c1..47c23e85c04e 100644
--- a/frontend/src/scenes/insights/filters/ActionFilter/ActionFilter.stories.tsx
+++ b/frontend/src/scenes/insights/filters/ActionFilter/ActionFilter.stories.tsx
@@ -7,7 +7,8 @@ import { useRef, useState } from 'react'
import { taxonomicFilterMocksDecorator } from 'lib/components/TaxonomicFilter/__mocks__/taxonomicFilterMocksDecorator'
import { TaxonomicFilterGroupType } from 'lib/components/TaxonomicFilter/types'
import { SINGLE_SERIES_DISPLAY_TYPES } from 'lib/constants'
-import { alphabet, uuid } from 'lib/utils'
+import { uuid } from 'lib/utils/dom'
+import { alphabet } from 'lib/utils/strings'
import { insightLogic } from 'scenes/insights/insightLogic'
import { isFilterWithDisplay, isLifecycleFilter } from 'scenes/insights/sharedUtils'
diff --git a/frontend/src/scenes/insights/filters/ActionFilter/ActionFilterGroup/ActionFilterGroup.test.ts b/frontend/src/scenes/insights/filters/ActionFilter/ActionFilterGroup/ActionFilterGroup.test.ts
index dbbaca17e9c3..9947074452ea 100644
--- a/frontend/src/scenes/insights/filters/ActionFilter/ActionFilterGroup/ActionFilterGroup.test.ts
+++ b/frontend/src/scenes/insights/filters/ActionFilter/ActionFilterGroup/ActionFilterGroup.test.ts
@@ -1,6 +1,6 @@
import { expectLogic } from 'kea-test-utils'
-import * as libUtils from 'lib/utils'
+import * as libUtils from 'lib/utils/dom'
import {
entityFilterLogic,
singleFilterToGroupFilter,
diff --git a/frontend/src/scenes/insights/filters/ActionFilter/ActionFilterGroup/actionFilterGroupLogic.ts b/frontend/src/scenes/insights/filters/ActionFilter/ActionFilterGroup/actionFilterGroupLogic.ts
index ecec0313b0e1..82d45e626986 100644
--- a/frontend/src/scenes/insights/filters/ActionFilter/ActionFilterGroup/actionFilterGroupLogic.ts
+++ b/frontend/src/scenes/insights/filters/ActionFilter/ActionFilterGroup/actionFilterGroupLogic.ts
@@ -1,7 +1,7 @@
import { actions, connect, kea, key, listeners, path, props, reducers, selectors } from 'kea'
import { TaxonomicFilterGroupType } from 'lib/components/TaxonomicFilter/types'
-import { uuid } from 'lib/utils'
+import { uuid } from 'lib/utils/dom'
import { MathCategory, mathTypeToApiValues, mathsLogic } from 'scenes/trends/mathsLogic'
import { AnyPropertyFilter, EntityType, EntityTypes, FilterLogicalOperator } from '~/types'
diff --git a/frontend/src/scenes/insights/filters/ActionFilter/ActionFilterRow/ActionFilterRow.tsx b/frontend/src/scenes/insights/filters/ActionFilter/ActionFilterRow/ActionFilterRow.tsx
index 884dd5f598b7..205e92fe4eec 100644
--- a/frontend/src/scenes/insights/filters/ActionFilter/ActionFilterRow/ActionFilterRow.tsx
+++ b/frontend/src/scenes/insights/filters/ActionFilter/ActionFilterRow/ActionFilterRow.tsx
@@ -23,7 +23,7 @@ import {
import { TaxonomicPopover, TaxonomicPopoverProps } from 'lib/components/TaxonomicPopover/TaxonomicPopover'
import { IconWithCount, SortableDragIcon } from 'lib/lemon-ui/icons'
import { LemonButton } from 'lib/lemon-ui/LemonButton'
-import { getEventNamesForAction } from 'lib/utils'
+import { getEventNamesForAction } from 'lib/utils/events'
import { databaseTableListLogic } from 'scenes/data-management/database/databaseTableListLogic'
import { funnelDataLogic } from 'scenes/funnels/funnelDataLogic'
import { insightDataLogic } from 'scenes/insights/insightDataLogic'
diff --git a/frontend/src/scenes/insights/filters/ActionFilter/ActionFilterRow/saveAsActionUtils.ts b/frontend/src/scenes/insights/filters/ActionFilter/ActionFilterRow/saveAsActionUtils.ts
index ab425fe1e217..66051df02feb 100644
--- a/frontend/src/scenes/insights/filters/ActionFilter/ActionFilterRow/saveAsActionUtils.ts
+++ b/frontend/src/scenes/insights/filters/ActionFilter/ActionFilterRow/saveAsActionUtils.ts
@@ -1,4 +1,4 @@
-import { truncate } from 'lib/utils'
+import { truncate } from 'lib/utils/strings'
import {
ActionStepStringMatching,
diff --git a/frontend/src/scenes/insights/filters/ActionFilter/ActionFilterRow/useMathSelectorOptions.tsx b/frontend/src/scenes/insights/filters/ActionFilter/ActionFilterRow/useMathSelectorOptions.tsx
index 1a747d379ebe..a932c421d801 100644
--- a/frontend/src/scenes/insights/filters/ActionFilter/ActionFilterRow/useMathSelectorOptions.tsx
+++ b/frontend/src/scenes/insights/filters/ActionFilter/ActionFilterRow/useMathSelectorOptions.tsx
@@ -4,7 +4,7 @@ import { useState } from 'react'
import { IconWarning } from '@posthog/icons'
import { LemonSelect, LemonSelectOption, LemonSelectOptions } from '@posthog/lemon-ui'
-import { capitalizeFirstLetter } from 'lib/utils'
+import { capitalizeFirstLetter } from 'lib/utils/strings'
import { GroupIntroductionFooter } from 'scenes/groups/GroupsIntroduction'
import {
COUNT_PER_ACTOR_MATH_DEFINITIONS,
diff --git a/frontend/src/scenes/insights/filters/ActionFilter/entityFilterLogic.test.ts b/frontend/src/scenes/insights/filters/ActionFilter/entityFilterLogic.test.ts
index 42d42b43ba1b..a1042fd188f2 100644
--- a/frontend/src/scenes/insights/filters/ActionFilter/entityFilterLogic.test.ts
+++ b/frontend/src/scenes/insights/filters/ActionFilter/entityFilterLogic.test.ts
@@ -1,7 +1,7 @@
import { expectLogic } from 'kea-test-utils'
import { TaxonomicFilterGroupType } from 'lib/components/TaxonomicFilter/types'
-import * as libUtils from 'lib/utils'
+import * as libUtils from 'lib/utils/dom'
import { entityFilterLogic, toLocalFilters } from 'scenes/insights/filters/ActionFilter/entityFilterLogic'
import { useMocks } from '~/mocks/jest'
diff --git a/frontend/src/scenes/insights/filters/ActionFilter/entityFilterLogic.ts b/frontend/src/scenes/insights/filters/ActionFilter/entityFilterLogic.ts
index cbe65c533fd8..7f6ebed02b6c 100644
--- a/frontend/src/scenes/insights/filters/ActionFilter/entityFilterLogic.ts
+++ b/frontend/src/scenes/insights/filters/ActionFilter/entityFilterLogic.ts
@@ -4,9 +4,10 @@ import { actions, connect, events, kea, key, listeners, path, props, reducers, s
import { convertPropertyGroupToProperties } from 'lib/components/PropertyFilters/utils'
import { defaultDataWarehousePopoverFields } from 'lib/components/TaxonomicFilter/taxonomicFilterLogic'
import { DataWarehousePopoverField } from 'lib/components/TaxonomicFilter/types'
-import { assignField, uuid } from 'lib/utils'
+import { uuid } from 'lib/utils/dom'
import { GraphSeriesAddedSource, eventUsageLogic } from 'lib/utils/eventUsageLogic'
import { getDefaultEventLabel, getDefaultEventName } from 'lib/utils/getAppContext'
+import { assignField } from 'lib/utils/guards'
import {
ActionFilter,
diff --git a/frontend/src/scenes/insights/filters/InsightDateFilter/InsightDateFilter.tsx b/frontend/src/scenes/insights/filters/InsightDateFilter/InsightDateFilter.tsx
index 201c97c0e36a..beb64e1e00c7 100644
--- a/frontend/src/scenes/insights/filters/InsightDateFilter/InsightDateFilter.tsx
+++ b/frontend/src/scenes/insights/filters/InsightDateFilter/InsightDateFilter.tsx
@@ -3,8 +3,8 @@ import { useActions, useValues } from 'kea'
import { IconCalendar } from '@posthog/icons'
import { DateFilter } from 'lib/components/DateFilter/DateFilter'
-import { dateMapping } from 'lib/utils'
-import { alignResolvedDateRangeToInterval } from 'lib/utils/dateTimeUtils'
+import { dateMapping } from 'lib/utils/dateFilters'
+import { alignResolvedDateRangeToInterval } from 'lib/utils/datetime'
import { insightLogic } from 'scenes/insights/insightLogic'
import { insightVizDataLogic } from 'scenes/insights/insightVizDataLogic'
diff --git a/frontend/src/scenes/insights/insightDataLogic.tsx b/frontend/src/scenes/insights/insightDataLogic.tsx
index b4920a7b1d00..2bcf303143cb 100644
--- a/frontend/src/scenes/insights/insightDataLogic.tsx
+++ b/frontend/src/scenes/insights/insightDataLogic.tsx
@@ -3,8 +3,8 @@ import { loaders } from 'kea-loaders'
import { actionToUrl, router } from 'kea-router'
import api from 'lib/api'
-import { objectsEqual } from 'lib/utils'
import { eventUsageLogic } from 'lib/utils/eventUsageLogic'
+import { objectsEqual } from 'lib/utils/objects'
import { keyForInsightLogicProps } from 'scenes/insights/sharedUtils'
import { sceneLogic } from 'scenes/sceneLogic'
import { Scene } from 'scenes/sceneTypes'
diff --git a/frontend/src/scenes/insights/insightLogic.tsx b/frontend/src/scenes/insights/insightLogic.tsx
index 601548177395..24ab01048344 100644
--- a/frontend/src/scenes/insights/insightLogic.tsx
+++ b/frontend/src/scenes/insights/insightLogic.tsx
@@ -23,10 +23,11 @@ import { FEATURE_FLAGS } from 'lib/constants'
import { LemonField } from 'lib/lemon-ui/LemonField'
import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'
import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
-import { isEmptyObject, isObject, objectsEqual } from 'lib/utils'
import { accessLevelSatisfied } from 'lib/utils/accessControlUtils'
import { deleteInsightWithUndo } from 'lib/utils/deleteWithUndo'
import { InsightEventSource, eventUsageLogic } from 'lib/utils/eventUsageLogic'
+import { isEmptyObject, isObject } from 'lib/utils/guards'
+import { objectsEqual } from 'lib/utils/objects'
import { isDashboardFilterEmpty } from 'scenes/dashboard/dashboardFilterEmpty'
import { DashboardLoadAction, dashboardLogic } from 'scenes/dashboard/dashboardLogic'
import { insightSceneLogic } from 'scenes/insights/insightSceneLogic'
diff --git a/frontend/src/scenes/insights/insightSceneLogic.test.ts b/frontend/src/scenes/insights/insightSceneLogic.test.ts
index e02cca0abce6..20d7a12f960f 100644
--- a/frontend/src/scenes/insights/insightSceneLogic.test.ts
+++ b/frontend/src/scenes/insights/insightSceneLogic.test.ts
@@ -3,7 +3,7 @@ import { MOCK_TEAM_ID } from 'lib/api.mock'
import { combineUrl, router } from 'kea-router'
import { expectLogic, partial } from 'kea-test-utils'
-import { addProjectIdIfMissing } from 'lib/utils/router-utils'
+import { addProjectIdIfMissing } from 'lib/utils/kea-router'
import { insightSceneLogic } from 'scenes/insights/insightSceneLogic'
import { sceneLogic } from 'scenes/sceneLogic'
import { Scene } from 'scenes/sceneTypes'
diff --git a/frontend/src/scenes/insights/insightSceneLogic.tsx b/frontend/src/scenes/insights/insightSceneLogic.tsx
index c054b502f310..703677345462 100644
--- a/frontend/src/scenes/insights/insightSceneLogic.tsx
+++ b/frontend/src/scenes/insights/insightSceneLogic.tsx
@@ -6,8 +6,8 @@ import api from 'lib/api'
import { AlertType } from 'lib/components/Alerts/types'
import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
import { trackedActionToUrl } from 'lib/logic/scenes/trackedActionToUrl'
-import { isEmptyObject, isObject } from 'lib/utils'
import { InsightEventSource, eventUsageLogic } from 'lib/utils/eventUsageLogic'
+import { isEmptyObject, isObject } from 'lib/utils/guards'
import { isDashboardFilterEmpty } from 'scenes/dashboard/dashboardFilterEmpty'
import { dashboardLogic } from 'scenes/dashboard/dashboardLogic'
import { createEmptyInsight, insightLogic } from 'scenes/insights/insightLogic'
diff --git a/frontend/src/scenes/insights/insightUsageLogic.ts b/frontend/src/scenes/insights/insightUsageLogic.ts
index e68a8151f023..e2d41e607dbf 100644
--- a/frontend/src/scenes/insights/insightUsageLogic.ts
+++ b/frontend/src/scenes/insights/insightUsageLogic.ts
@@ -2,8 +2,8 @@ import { actions, connect, kea, key, listeners, path, props, reducers } from 'ke
import { subscriptions } from 'kea-subscriptions'
import api from 'lib/api'
-import { objectsEqual } from 'lib/utils'
import { eventUsageLogic } from 'lib/utils/eventUsageLogic'
+import { objectsEqual } from 'lib/utils/objects'
import { projectLogic } from 'scenes/projectLogic'
import { isSharedView } from '~/exporter/exporterViewLogic'
diff --git a/frontend/src/scenes/insights/insightVizDataLogic.ts b/frontend/src/scenes/insights/insightVizDataLogic.ts
index 7635dedfb6dd..44ebb72bbfdf 100644
--- a/frontend/src/scenes/insights/insightVizDataLogic.ts
+++ b/frontend/src/scenes/insights/insightVizDataLogic.ts
@@ -12,7 +12,7 @@ import { parseProperties } from 'lib/components/PropertyFilters/utils'
import { FEATURE_FLAGS, NON_TIME_SERIES_DISPLAY_TYPES, NON_VALUES_ON_SERIES_DISPLAY_TYPES } from 'lib/constants'
import { dayjs } from 'lib/dayjs'
import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
-import { dateMapping, is12HoursOrLess, isLessThan2Days } from 'lib/utils'
+import { dateMapping, is12HoursOrLess, isLessThan2Days } from 'lib/utils/dateFilters'
import { eventUsageLogic } from 'lib/utils/eventUsageLogic'
import { databaseTableListLogic } from 'scenes/data-management/database/databaseTableListLogic'
import { dataThemeLogic } from 'scenes/dataThemeLogic'
diff --git a/frontend/src/scenes/insights/summarizeInsight.ts b/frontend/src/scenes/insights/summarizeInsight.ts
index 8d2a30f1d53b..998fd9c56848 100644
--- a/frontend/src/scenes/insights/summarizeInsight.ts
+++ b/frontend/src/scenes/insights/summarizeInsight.ts
@@ -2,7 +2,7 @@ import { useValues } from 'kea'
import { PROPERTY_FILTER_TYPE_TO_TAXONOMIC_FILTER_GROUP_TYPE } from 'lib/components/PropertyFilters/utils'
import { RETENTION_FIRST_OCCURRENCE_MATCHING_FILTERS } from 'lib/constants'
-import { alphabet, capitalizeFirstLetter } from 'lib/utils'
+import { alphabet, capitalizeFirstLetter } from 'lib/utils/strings'
import {
getDisplayNameFromEntityFilter,
getDisplayNameFromEntityNode,
diff --git a/frontend/src/scenes/insights/utils.tsx b/frontend/src/scenes/insights/utils.tsx
index 41cacfccb352..4ae206e56b3a 100644
--- a/frontend/src/scenes/insights/utils.tsx
+++ b/frontend/src/scenes/insights/utils.tsx
@@ -7,13 +7,16 @@ import { LemonButtonProps } from '@posthog/lemon-ui'
import api from 'lib/api'
import { DataColorTheme, DataColorToken } from 'lib/colors'
import { dayjs } from 'lib/dayjs'
-import { ensureStringIsNotBlank, humanFriendlyNumber, isEmptyObject, isObject, objectsEqual } from 'lib/utils'
import { getCurrentTeamId } from 'lib/utils/getAppContext'
+import { isEmptyObject, isObject } from 'lib/utils/guards'
+import { humanFriendlyNumber } from 'lib/utils/numbers'
+import { objectsEqual } from 'lib/utils/objects'
+import { removeUndefinedAndNull } from 'lib/utils/objects'
+import { ensureStringIsNotBlank } from 'lib/utils/strings'
import { IndexedTrendResult } from 'scenes/trends/types'
import { urls } from 'scenes/urls'
import { propertyFilterTypeToPropertyDefinitionType } from '~/lib/components/PropertyFilters/utils'
-import { removeUndefinedAndNull } from '~/lib/utils'
import { FormatPropertyValueForDisplayFunction } from '~/models/propertyDefinitionsModel'
import { examples } from '~/queries/examples'
import {
diff --git a/frontend/src/scenes/insights/utils/cleanFilters.ts b/frontend/src/scenes/insights/utils/cleanFilters.ts
index 1fa857e98fc7..77b8463b3cfb 100644
--- a/frontend/src/scenes/insights/utils/cleanFilters.ts
+++ b/frontend/src/scenes/insights/utils/cleanFilters.ts
@@ -8,8 +8,8 @@ import {
RETENTION_MEAN_NONE,
ShownAsValue,
} from 'lib/constants'
-import { clamp } from 'lib/utils'
import { getDefaultEventName } from 'lib/utils/getAppContext'
+import { clamp } from 'lib/utils/numbers'
import { isURLNormalizeable } from 'scenes/insights/filters/BreakdownFilter/taxonomicBreakdownFilterUtils'
import {
isFunnelsFilter,
diff --git a/frontend/src/scenes/insights/utils/queryUtils.ts b/frontend/src/scenes/insights/utils/queryUtils.ts
index 75f51440b50d..930bfcf833fe 100644
--- a/frontend/src/scenes/insights/utils/queryUtils.ts
+++ b/frontend/src/scenes/insights/utils/queryUtils.ts
@@ -1,4 +1,4 @@
-import { objectCleanWithEmpty, objectsEqual, removeUndefinedAndNull } from 'lib/utils'
+import { objectCleanWithEmpty, objectsEqual, removeUndefinedAndNull } from 'lib/utils/objects'
import { isValidRE2 } from 'lib/utils/regexp'
import { isFunnelWithEnoughSteps, isFunnelWithIncompleteDataWarehouseStep } from 'scenes/funnels/funnelUtils'
diff --git a/frontend/src/scenes/insights/views/BoldNumber/BoldNumber.tsx b/frontend/src/scenes/insights/views/BoldNumber/BoldNumber.tsx
index db8f58e720d4..edf03b57a5f5 100644
--- a/frontend/src/scenes/insights/views/BoldNumber/BoldNumber.tsx
+++ b/frontend/src/scenes/insights/views/BoldNumber/BoldNumber.tsx
@@ -10,7 +10,7 @@ import { IconTrending } from '@posthog/icons'
import { LemonRow, Link } from '@posthog/lemon-ui'
import { IconFlare, IconTrendingDown, IconTrendingFlat } from 'lib/lemon-ui/icons'
-import { percentage } from 'lib/utils'
+import { percentage } from 'lib/utils/numbers'
import { formatAggregationAxisValue } from 'scenes/insights/aggregationAxisFormat'
import { InsightEmptyState } from 'scenes/insights/EmptyStates'
import { InsightTooltip } from 'scenes/insights/InsightTooltip/InsightTooltip'
diff --git a/frontend/src/scenes/insights/views/CalendarHeatMap/TrendsCalendarHeatMap.tsx b/frontend/src/scenes/insights/views/CalendarHeatMap/TrendsCalendarHeatMap.tsx
index 92c1b4ed40b5..4301e681164d 100644
--- a/frontend/src/scenes/insights/views/CalendarHeatMap/TrendsCalendarHeatMap.tsx
+++ b/frontend/src/scenes/insights/views/CalendarHeatMap/TrendsCalendarHeatMap.tsx
@@ -3,7 +3,7 @@ import { useValues } from 'kea'
import { LemonButton } from '@posthog/lemon-ui'
import { dayjs } from 'lib/dayjs'
-import { timeZoneLabel } from 'lib/utils'
+import { timeZoneLabel } from 'lib/utils/timezones'
import { insightLogic } from 'scenes/insights/insightLogic'
import { teamLogic } from 'scenes/teamLogic'
import { urls } from 'scenes/urls'
diff --git a/frontend/src/scenes/insights/views/CalendarHeatMap/utils.ts b/frontend/src/scenes/insights/views/CalendarHeatMap/utils.ts
index e0edba4b0af1..0ce8e309bb9f 100644
--- a/frontend/src/scenes/insights/views/CalendarHeatMap/utils.ts
+++ b/frontend/src/scenes/insights/views/CalendarHeatMap/utils.ts
@@ -1,4 +1,4 @@
-import { humanFriendlyNumber } from 'lib/utils'
+import { humanFriendlyNumber } from 'lib/utils/numbers'
export interface AxisConfig {
values: string[]
diff --git a/frontend/src/scenes/insights/views/Funnels/CorrelationMatrix.tsx b/frontend/src/scenes/insights/views/Funnels/CorrelationMatrix.tsx
index 67273100bbc0..ca734e0cd531 100644
--- a/frontend/src/scenes/insights/views/Funnels/CorrelationMatrix.tsx
+++ b/frontend/src/scenes/insights/views/Funnels/CorrelationMatrix.tsx
@@ -12,7 +12,8 @@ import { LemonBanner } from 'lib/lemon-ui/LemonBanner'
import { Link } from 'lib/lemon-ui/Link'
import { Spinner } from 'lib/lemon-ui/Spinner/Spinner'
import { Tooltip } from 'lib/lemon-ui/Tooltip'
-import { capitalizeFirstLetter, percentage, pluralize } from 'lib/utils'
+import { percentage } from 'lib/utils/numbers'
+import { capitalizeFirstLetter, pluralize } from 'lib/utils/strings'
import { funnelCorrelationDetailsLogic } from 'scenes/funnels/funnelCorrelationDetailsLogic'
import { funnelCorrelationLogic } from 'scenes/funnels/funnelCorrelationLogic'
import { funnelPersonsModalLogic } from 'scenes/funnels/funnelPersonsModalLogic'
diff --git a/frontend/src/scenes/insights/views/Funnels/FunnelConversionWindowFilter.tsx b/frontend/src/scenes/insights/views/Funnels/FunnelConversionWindowFilter.tsx
index 9bc3c4846906..beae36967282 100644
--- a/frontend/src/scenes/insights/views/Funnels/FunnelConversionWindowFilter.tsx
+++ b/frontend/src/scenes/insights/views/Funnels/FunnelConversionWindowFilter.tsx
@@ -4,7 +4,7 @@ import { IconInfo } from '@posthog/icons'
import { LemonInput, LemonSelect, LemonSelectOption } from '@posthog/lemon-ui'
import { Tooltip } from 'lib/lemon-ui/Tooltip'
-import { capitalizeFirstLetter, pluralize } from 'lib/utils'
+import { capitalizeFirstLetter, pluralize } from 'lib/utils/strings'
import { funnelDataLogic } from 'scenes/funnels/funnelDataLogic'
import { TIME_INTERVAL_BOUNDS } from 'scenes/funnels/funnelUtils'
diff --git a/frontend/src/scenes/insights/views/Funnels/FunnelCorrelationTable.tsx b/frontend/src/scenes/insights/views/Funnels/FunnelCorrelationTable.tsx
index 42871155a063..f7e5eff65b1b 100644
--- a/frontend/src/scenes/insights/views/Funnels/FunnelCorrelationTable.tsx
+++ b/frontend/src/scenes/insights/views/Funnels/FunnelCorrelationTable.tsx
@@ -12,7 +12,7 @@ import { IconSelectEvents, IconTrendingDown } from 'lib/lemon-ui/icons'
import { LemonButton } from 'lib/lemon-ui/LemonButton'
import { Link } from 'lib/lemon-ui/Link'
import { Spinner } from 'lib/lemon-ui/Spinner/Spinner'
-import { capitalizeFirstLetter } from 'lib/utils'
+import { capitalizeFirstLetter } from 'lib/utils/strings'
import { funnelCorrelationLogic } from 'scenes/funnels/funnelCorrelationLogic'
import { funnelCorrelationUsageLogic } from 'scenes/funnels/funnelCorrelationUsageLogic'
import { funnelDataLogic } from 'scenes/funnels/funnelDataLogic'
diff --git a/frontend/src/scenes/insights/views/Funnels/FunnelPropertyCorrelationTable.tsx b/frontend/src/scenes/insights/views/Funnels/FunnelPropertyCorrelationTable.tsx
index 7e277247c0bb..79333bdf72f2 100644
--- a/frontend/src/scenes/insights/views/Funnels/FunnelPropertyCorrelationTable.tsx
+++ b/frontend/src/scenes/insights/views/Funnels/FunnelPropertyCorrelationTable.tsx
@@ -14,7 +14,7 @@ import { VisibilitySensor } from 'lib/components/VisibilitySensor/VisibilitySens
import { IconSelectProperties, IconTrendingDown } from 'lib/lemon-ui/icons'
import { Link } from 'lib/lemon-ui/Link'
import { Popover } from 'lib/lemon-ui/Popover'
-import { capitalizeFirstLetter } from 'lib/utils'
+import { capitalizeFirstLetter } from 'lib/utils/strings'
import { funnelCorrelationUsageLogic } from 'scenes/funnels/funnelCorrelationUsageLogic'
import { funnelDataLogic } from 'scenes/funnels/funnelDataLogic'
import { funnelPersonsModalLogic } from 'scenes/funnels/funnelPersonsModalLogic'
diff --git a/frontend/src/scenes/insights/views/Funnels/FunnelStepsTable.tsx b/frontend/src/scenes/insights/views/Funnels/FunnelStepsTable.tsx
index 6541541ee59c..47e599d2ebec 100644
--- a/frontend/src/scenes/insights/views/Funnels/FunnelStepsTable.tsx
+++ b/frontend/src/scenes/insights/views/Funnels/FunnelStepsTable.tsx
@@ -9,7 +9,8 @@ import { LemonCheckbox } from 'lib/lemon-ui/LemonCheckbox'
import { LemonRow } from 'lib/lemon-ui/LemonRow'
import { LemonTable, LemonTableColumn, LemonTableColumnGroup } from 'lib/lemon-ui/LemonTable'
import { Lettermark, LettermarkColor } from 'lib/lemon-ui/Lettermark'
-import { humanFriendlyDuration, humanFriendlyNumber, percentage } from 'lib/utils'
+import { humanFriendlyDuration } from 'lib/utils/durations'
+import { humanFriendlyNumber, percentage } from 'lib/utils/numbers'
import { funnelDataLogic } from 'scenes/funnels/funnelDataLogic'
import { funnelPersonsModalLogic } from 'scenes/funnels/funnelPersonsModalLogic'
import { getVisibilityKey } from 'scenes/funnels/funnelUtils'
diff --git a/frontend/src/scenes/insights/views/InsightsTable/InsightsTable.tsx b/frontend/src/scenes/insights/views/InsightsTable/InsightsTable.tsx
index cc7992ac808d..d5da974dadf9 100644
--- a/frontend/src/scenes/insights/views/InsightsTable/InsightsTable.tsx
+++ b/frontend/src/scenes/insights/views/InsightsTable/InsightsTable.tsx
@@ -6,7 +6,7 @@ import { useCallback, useMemo, useState } from 'react'
import { LemonButton } from 'lib/lemon-ui/LemonButton'
import { LemonTable, LemonTableColumn } from 'lib/lemon-ui/LemonTable'
-import { COUNTRY_CODE_TO_LONG_NAME } from 'lib/utils/geography/country'
+import { COUNTRY_CODE_TO_LONG_NAME } from 'lib/utils/country'
import { formatAggregationAxisValue } from 'scenes/insights/aggregationAxisFormat'
import { insightLogic } from 'scenes/insights/insightLogic'
import { formatBreakdownLabel } from 'scenes/insights/utils'
diff --git a/frontend/src/scenes/insights/views/InsightsTable/columns/AggregationColumn.tsx b/frontend/src/scenes/insights/views/InsightsTable/columns/AggregationColumn.tsx
index ec4e50d5312e..96f627b92fb7 100644
--- a/frontend/src/scenes/insights/views/InsightsTable/columns/AggregationColumn.tsx
+++ b/frontend/src/scenes/insights/views/InsightsTable/columns/AggregationColumn.tsx
@@ -6,8 +6,8 @@ import { ReactNode } from 'react'
import { IconChevronDown } from '@posthog/icons'
import { LemonMenu, LemonMenuItem } from '@posthog/lemon-ui'
-import { average, median } from 'lib/utils'
import { eventUsageLogic } from 'lib/utils/eventUsageLogic'
+import { average, median } from 'lib/utils/numbers'
import { formatAggregationAxisValue } from 'scenes/insights/aggregationAxisFormat'
import { formatAggregationValue } from 'scenes/insights/utils'
import { teamLogic } from 'scenes/teamLogic'
diff --git a/frontend/src/scenes/insights/views/InsightsTable/columns/BreakdownColumn.tsx b/frontend/src/scenes/insights/views/InsightsTable/columns/BreakdownColumn.tsx
index 4082a5131bc5..38d992b4b6e4 100644
--- a/frontend/src/scenes/insights/views/InsightsTable/columns/BreakdownColumn.tsx
+++ b/frontend/src/scenes/insights/views/InsightsTable/columns/BreakdownColumn.tsx
@@ -3,8 +3,8 @@ import { Link, Tooltip } from '@posthog/lemon-ui'
import { parseAliasToReadable } from 'lib/components/PathCleanFilters/PathCleanFilterItem'
import { PropertyKeyInfo } from 'lib/components/PropertyKeyInfo'
-import { isURL } from 'lib/utils'
import stringWithWBR from 'lib/utils/stringWithWBR'
+import { isURL } from 'lib/utils/url'
import { formatBreakdownType } from 'scenes/insights/utils'
import { IndexedTrendResult } from 'scenes/trends/types'
diff --git a/frontend/src/scenes/insights/views/InsightsTable/columns/SeriesColumn.tsx b/frontend/src/scenes/insights/views/InsightsTable/columns/SeriesColumn.tsx
index 536cd812b7e7..501ff3f8300d 100644
--- a/frontend/src/scenes/insights/views/InsightsTable/columns/SeriesColumn.tsx
+++ b/frontend/src/scenes/insights/views/InsightsTable/columns/SeriesColumn.tsx
@@ -3,7 +3,7 @@ import clsx from 'clsx'
import { Tooltip } from '@posthog/lemon-ui'
import { InsightLabel } from 'lib/components/InsightLabel'
-import { capitalizeFirstLetter } from 'lib/utils'
+import { capitalizeFirstLetter } from 'lib/utils/strings'
import { IndexedTrendResult } from 'scenes/trends/types'
import { TrendResult } from '~/types'
diff --git a/frontend/src/scenes/insights/views/InsightsTable/columns/WorldMapColumn.tsx b/frontend/src/scenes/insights/views/InsightsTable/columns/WorldMapColumn.tsx
index 03feb5b821ea..d166d95a280b 100644
--- a/frontend/src/scenes/insights/views/InsightsTable/columns/WorldMapColumn.tsx
+++ b/frontend/src/scenes/insights/views/InsightsTable/columns/WorldMapColumn.tsx
@@ -1,5 +1,5 @@
import { PropertyKeyInfo } from 'lib/components/PropertyKeyInfo'
-import { COUNTRY_CODE_TO_LONG_NAME } from 'lib/utils/geography/country'
+import { COUNTRY_CODE_TO_LONG_NAME } from 'lib/utils/country'
import { IndexedTrendResult } from 'scenes/trends/types'
export function WorldMapColumnTitle(): JSX.Element {
diff --git a/frontend/src/scenes/insights/views/LineGraph/LineGraph.tsx b/frontend/src/scenes/insights/views/LineGraph/LineGraph.tsx
index 345c6c994205..e112b9d62f48 100644
--- a/frontend/src/scenes/insights/views/LineGraph/LineGraph.tsx
+++ b/frontend/src/scenes/insights/views/LineGraph/LineGraph.tsx
@@ -36,6 +36,7 @@ import { useChart } from 'lib/hooks/useChart'
import { useKeyHeld } from 'lib/hooks/useKeyHeld'
import { useOnMountEffect } from 'lib/hooks/useOnMountEffect'
import { useResizeObserver } from 'lib/hooks/useResizeObserver'
+import { hexToRGBA, lightenDarkenColor } from 'lib/utils/colors'
import { formatAggregationAxisValue, formatPercentStackAxisValue } from 'scenes/insights/aggregationAxisFormat'
import { insightLogic } from 'scenes/insights/insightLogic'
import { InsightTooltip } from 'scenes/insights/InsightTooltip/InsightTooltip'
@@ -51,7 +52,6 @@ import { useChartZoom } from 'scenes/web-analytics/hooks/useChartZoom'
import { ErrorBoundary } from '~/layout/ErrorBoundary'
import { themeLogic } from '~/layout/navigation-3000/themeLogic'
-import { hexToRGBA, lightenDarkenColor } from '~/lib/utils'
import { groupsModel } from '~/models/groupsModel'
import { GoalLine, TrendsFilter } from '~/queries/schema/schema-general'
import { GraphDataset, GraphPoint, GraphPointPayload, GraphType } from '~/types'
diff --git a/frontend/src/scenes/insights/views/LineGraph/PieChart.tsx b/frontend/src/scenes/insights/views/LineGraph/PieChart.tsx
index 7c98ebaf0883..e3cec77c379d 100644
--- a/frontend/src/scenes/insights/views/LineGraph/PieChart.tsx
+++ b/frontend/src/scenes/insights/views/LineGraph/PieChart.tsx
@@ -13,7 +13,7 @@ import {
} from 'lib/Chart'
import { SeriesLetter } from 'lib/components/SeriesGlyph'
import { useChart } from 'lib/hooks/useChart'
-import { isString } from 'lib/utils'
+import { isString } from 'lib/utils/guards'
import {
formatAggregationAxisValue,
formatAggregationAxisValueWithShareOfTotal,
diff --git a/frontend/src/scenes/insights/views/RegionMap/RegionMap.tsx b/frontend/src/scenes/insights/views/RegionMap/RegionMap.tsx
index df60c0ab65c5..cf9a9b6f0087 100644
--- a/frontend/src/scenes/insights/views/RegionMap/RegionMap.tsx
+++ b/frontend/src/scenes/insights/views/RegionMap/RegionMap.tsx
@@ -4,8 +4,8 @@ import { useActions, useValues } from 'kea'
import React, { useEffect, useRef } from 'react'
import { ComposableMap, Geographies, Geography } from 'react-simple-maps'
-import { gradateColor } from 'lib/utils'
-import { COUNTRY_CODE_TO_LONG_NAME, countryCodeToFlag } from 'lib/utils/geography/country'
+import { gradateColor } from 'lib/utils/colors'
+import { COUNTRY_CODE_TO_LONG_NAME, countryCodeToFlag } from 'lib/utils/country'
import { formatAggregationAxisValue } from 'scenes/insights/aggregationAxisFormat'
import { insightLogic } from 'scenes/insights/insightLogic'
import { InsightTooltip } from 'scenes/insights/InsightTooltip/InsightTooltip'
diff --git a/frontend/src/scenes/insights/views/WorldMap/WorldMap.tsx b/frontend/src/scenes/insights/views/WorldMap/WorldMap.tsx
index 9c6d6d4f3324..d6ccc62fe5f3 100644
--- a/frontend/src/scenes/insights/views/WorldMap/WorldMap.tsx
+++ b/frontend/src/scenes/insights/views/WorldMap/WorldMap.tsx
@@ -4,8 +4,8 @@ import { style } from 'd3'
import { props, useActions, useValues } from 'kea'
import React, { useEffect, useRef } from 'react'
-import { gradateColor } from 'lib/utils'
-import { COUNTRY_CODE_TO_LONG_NAME, countryCodeToFlag } from 'lib/utils/geography/country'
+import { gradateColor } from 'lib/utils/colors'
+import { COUNTRY_CODE_TO_LONG_NAME, countryCodeToFlag } from 'lib/utils/country'
import { formatAggregationAxisValue } from 'scenes/insights/aggregationAxisFormat'
import { insightLogic } from 'scenes/insights/insightLogic'
import { InsightTooltip } from 'scenes/insights/InsightTooltip/InsightTooltip'
diff --git a/frontend/src/scenes/instance/AsyncMigrations/AsyncMigrationDetails.tsx b/frontend/src/scenes/instance/AsyncMigrations/AsyncMigrationDetails.tsx
index 5345184c8511..7458c01f95af 100644
--- a/frontend/src/scenes/instance/AsyncMigrations/AsyncMigrationDetails.tsx
+++ b/frontend/src/scenes/instance/AsyncMigrations/AsyncMigrationDetails.tsx
@@ -5,7 +5,7 @@ import { IconRefresh } from '@posthog/icons'
import { LemonButton } from 'lib/lemon-ui/LemonButton'
import { LemonTable, LemonTableColumns } from 'lib/lemon-ui/LemonTable'
import { Spinner } from 'lib/lemon-ui/Spinner/Spinner'
-import { humanFriendlyDetailedTime } from 'lib/utils'
+import { humanFriendlyDetailedTime } from 'lib/utils/datetime'
import { AsyncMigration, AsyncMigrationError, asyncMigrationsLogic } from './asyncMigrationsLogic'
diff --git a/frontend/src/scenes/instance/AsyncMigrations/AsyncMigrations.tsx b/frontend/src/scenes/instance/AsyncMigrations/AsyncMigrations.tsx
index f4e5db9cd05f..33033e338c5f 100644
--- a/frontend/src/scenes/instance/AsyncMigrations/AsyncMigrations.tsx
+++ b/frontend/src/scenes/instance/AsyncMigrations/AsyncMigrations.tsx
@@ -15,7 +15,7 @@ import { LemonTabs } from 'lib/lemon-ui/LemonTabs'
import { LemonTag, LemonTagType } from 'lib/lemon-ui/LemonTag/LemonTag'
import { Spinner } from 'lib/lemon-ui/Spinner/Spinner'
import { Tooltip } from 'lib/lemon-ui/Tooltip'
-import { humanFriendlyDetailedTime } from 'lib/utils'
+import { humanFriendlyDetailedTime } from 'lib/utils/datetime'
import { AsyncMigrationParametersModal } from 'scenes/instance/AsyncMigrations/AsyncMigrationParametersModal'
import { SceneExport } from 'scenes/sceneTypes'
import { userLogic } from 'scenes/userLogic'
diff --git a/frontend/src/scenes/instance/AsyncMigrations/asyncMigrationParameterFormLogic.ts b/frontend/src/scenes/instance/AsyncMigrations/asyncMigrationParameterFormLogic.ts
index 303eeb5ec8bf..5137d127408c 100644
--- a/frontend/src/scenes/instance/AsyncMigrations/asyncMigrationParameterFormLogic.ts
+++ b/frontend/src/scenes/instance/AsyncMigrations/asyncMigrationParameterFormLogic.ts
@@ -1,7 +1,7 @@
import { kea, key, path, props } from 'kea'
import { forms } from 'kea-forms'
-import { isNumber } from 'lib/utils'
+import { isNumber } from 'lib/utils/guards'
import { AsyncMigrationModalProps, asyncMigrationsLogic } from 'scenes/instance/AsyncMigrations/asyncMigrationsLogic'
import type { asyncMigrationParameterFormLogicType } from './asyncMigrationParameterFormLogicType'
diff --git a/frontend/src/scenes/instance/SystemStatus/InstanceConfigSaveModal.tsx b/frontend/src/scenes/instance/SystemStatus/InstanceConfigSaveModal.tsx
index 1d0c6573b4dc..e11442c75e63 100644
--- a/frontend/src/scenes/instance/SystemStatus/InstanceConfigSaveModal.tsx
+++ b/frontend/src/scenes/instance/SystemStatus/InstanceConfigSaveModal.tsx
@@ -3,7 +3,7 @@ import { useActions, useValues } from 'kea'
import { LemonButton, LemonModal } from '@posthog/lemon-ui'
import { LemonBanner } from 'lib/lemon-ui/LemonBanner'
-import { pluralize } from 'lib/utils'
+import { pluralize } from 'lib/utils/strings'
import { SystemStatusRow } from '~/types'
diff --git a/frontend/src/scenes/instance/SystemStatus/InstanceConfigTab.tsx b/frontend/src/scenes/instance/SystemStatus/InstanceConfigTab.tsx
index f9737aff7d34..c867431f6aa1 100644
--- a/frontend/src/scenes/instance/SystemStatus/InstanceConfigTab.tsx
+++ b/frontend/src/scenes/instance/SystemStatus/InstanceConfigTab.tsx
@@ -7,7 +7,7 @@ import { useKeyboardHotkeys } from 'lib/hooks/useKeyboardHotkeys'
import { useOnMountEffect } from 'lib/hooks/useOnMountEffect'
import { IconOpenInNew } from 'lib/lemon-ui/icons'
import { LemonTable, LemonTableColumns } from 'lib/lemon-ui/LemonTable'
-import { pluralize } from 'lib/utils'
+import { pluralize } from 'lib/utils/strings'
import { EnvironmentConfigOption, preflightLogic } from 'scenes/PreflightCheck/preflightLogic'
import { InstanceSetting } from '~/types'
diff --git a/frontend/src/scenes/instance/SystemStatus/OverviewTab.tsx b/frontend/src/scenes/instance/SystemStatus/OverviewTab.tsx
index b32a0f6a6d3d..9ba7b1b91d1d 100644
--- a/frontend/src/scenes/instance/SystemStatus/OverviewTab.tsx
+++ b/frontend/src/scenes/instance/SystemStatus/OverviewTab.tsx
@@ -4,7 +4,7 @@ import { LemonTable } from '@posthog/lemon-ui'
import { IconOpenInNew } from 'lib/lemon-ui/icons'
import { Link } from 'lib/lemon-ui/Link'
-import { isKeyOf } from 'lib/utils'
+import { isKeyOf } from 'lib/utils/guards'
import { SystemStatusRow, SystemStatusSubrows } from '~/types'
diff --git a/frontend/src/scenes/instance/SystemStatus/systemStatusLogic.ts b/frontend/src/scenes/instance/SystemStatus/systemStatusLogic.ts
index 19250330a75c..98a2fc082314 100644
--- a/frontend/src/scenes/instance/SystemStatus/systemStatusLogic.ts
+++ b/frontend/src/scenes/instance/SystemStatus/systemStatusLogic.ts
@@ -4,8 +4,8 @@ import { actionToUrl, urlToAction } from 'kea-router'
import api from 'lib/api'
import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'
-import { isUserLoggedIn } from 'lib/utils'
import { eventUsageLogic } from 'lib/utils/eventUsageLogic'
+import { isUserLoggedIn } from 'lib/utils/getAppContext'
import { preflightLogic } from 'scenes/PreflightCheck/preflightLogic'
import { userLogic } from 'scenes/userLogic'
diff --git a/frontend/src/scenes/max/Thread.tsx b/frontend/src/scenes/max/Thread.tsx
index b8b7b7aa9e77..f5e1f9b04b73 100644
--- a/frontend/src/scenes/max/Thread.tsx
+++ b/frontend/src/scenes/max/Thread.tsx
@@ -41,15 +41,16 @@ import { TopHeading } from 'lib/components/Cards/InsightCard/TopHeading'
import { CodeSnippet, Language } from 'lib/components/CodeSnippet/CodeSnippet'
import { NotFound } from 'lib/components/NotFound'
import { useFeatureFlag } from 'lib/hooks/useFeatureFlag'
-import { inStorybookTestRunner, pluralize } from 'lib/utils'
import { cn } from 'lib/utils/css-classes'
+import { inStorybookTestRunner } from 'lib/utils/dom'
+import { pluralize } from 'lib/utils/strings'
import { preflightLogic } from 'scenes/PreflightCheck/preflightLogic'
import { sceneLogic } from 'scenes/sceneLogic'
import { urls } from 'scenes/urls'
import { userLogic } from 'scenes/userLogic'
import { copyToClipboard } from '~/lib/utils/copyToClipboard'
-import { stripMarkdown } from '~/lib/utils/stripMarkdown'
+import { stripMarkdown } from '~/lib/utils/markdown'
import { Query } from '~/queries/Query/Query'
import {
AssistantForm,
diff --git a/frontend/src/scenes/max/components/FloatingSuggestionsDisplay.tsx b/frontend/src/scenes/max/components/FloatingSuggestionsDisplay.tsx
index 71f6c1390eaa..604d599f85cb 100644
--- a/frontend/src/scenes/max/components/FloatingSuggestionsDisplay.tsx
+++ b/frontend/src/scenes/max/components/FloatingSuggestionsDisplay.tsx
@@ -4,7 +4,7 @@ import { router } from 'kea-router'
import { LemonButton, Tooltip } from '@posthog/lemon-ui'
import { cn } from 'lib/utils/css-classes'
-import { removeProjectIdIfPresent } from 'lib/utils/router-utils'
+import { removeProjectIdIfPresent } from 'lib/utils/kea-router'
import { SuggestionGroup, SuggestionItem, maxLogic } from '../maxLogic'
import { maxThreadLogic } from '../maxThreadLogic'
diff --git a/frontend/src/scenes/max/max-constants.tsx b/frontend/src/scenes/max/max-constants.tsx
index 34499af1b9c6..8e9b52a1b169 100644
--- a/frontend/src/scenes/max/max-constants.tsx
+++ b/frontend/src/scenes/max/max-constants.tsx
@@ -18,10 +18,10 @@ import {
import { FEATURE_FLAGS } from 'lib/constants'
import { IconQuestionAnswer, IconRobot } from 'lib/lemon-ui/icons'
+import { isObject } from 'lib/utils/guards'
import { Scene } from 'scenes/sceneTypes'
import { iconForType } from '~/layout/panel-layout/ProjectTree/defaultTree'
-import { isObject } from '~/lib/utils'
import {
AgentMode,
AssistantTool,
diff --git a/frontend/src/scenes/max/maxContextLogic.ts b/frontend/src/scenes/max/maxContextLogic.ts
index afad614bcb94..5407e80b4606 100644
--- a/frontend/src/scenes/max/maxContextLogic.ts
+++ b/frontend/src/scenes/max/maxContextLogic.ts
@@ -5,7 +5,7 @@ import posthog from 'posthog-js'
import { IconBug, IconCheckbox, IconDashboard, IconGraph, IconNotebook } from '@posthog/icons'
import { TaxonomicFilterGroupType } from 'lib/components/TaxonomicFilter/types'
-import { objectsEqual } from 'lib/utils'
+import { objectsEqual } from 'lib/utils/objects'
import { DashboardLoadAction, RefreshStatus, dashboardLogic } from 'scenes/dashboard/dashboardLogic'
import { insightLogic } from 'scenes/insights/insightLogic'
import { insightSceneLogic } from 'scenes/insights/insightSceneLogic'
diff --git a/frontend/src/scenes/max/maxLogic.tsx b/frontend/src/scenes/max/maxLogic.tsx
index c42a47021a45..c225caae9f93 100644
--- a/frontend/src/scenes/max/maxLogic.tsx
+++ b/frontend/src/scenes/max/maxLogic.tsx
@@ -9,7 +9,8 @@ import { dayjs } from 'lib/dayjs'
import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'
import { trackedActionToUrl } from 'lib/logic/scenes/trackedActionToUrl'
import { tabUiStateLogic } from 'lib/logic/tabUiStateLogic'
-import { objectsEqual, uuid } from 'lib/utils'
+import { uuid } from 'lib/utils/dom'
+import { objectsEqual } from 'lib/utils/objects'
import { sceneLogic } from 'scenes/sceneLogic'
import { Scene, SceneTab } from 'scenes/sceneTypes'
import { urls } from 'scenes/urls'
diff --git a/frontend/src/scenes/max/maxThreadLogic.tsx b/frontend/src/scenes/max/maxThreadLogic.tsx
index b8f6eaa8a783..b8d7e492ce16 100644
--- a/frontend/src/scenes/max/maxThreadLogic.tsx
+++ b/frontend/src/scenes/max/maxThreadLogic.tsx
@@ -24,7 +24,7 @@ import { FEATURE_FLAGS } from 'lib/constants'
import { dayjs } from 'lib/dayjs'
import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'
import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
-import { uuid } from 'lib/utils'
+import { uuid } from 'lib/utils/dom'
import { maxContextLogic } from 'scenes/max/maxContextLogic'
import { notebookLogic } from 'scenes/notebooks/Notebook/notebookLogic'
import { NotebookTarget } from 'scenes/notebooks/types'
diff --git a/frontend/src/scenes/max/utils.ts b/frontend/src/scenes/max/utils.ts
index 9bbb9090b5e0..66bf2b797ccb 100644
--- a/frontend/src/scenes/max/utils.ts
+++ b/frontend/src/scenes/max/utils.ts
@@ -2,7 +2,7 @@ import posthog from 'posthog-js'
import { FEATURE_FLAGS } from 'lib/constants'
import { dayjs } from 'lib/dayjs'
-import { humanFriendlyDuration } from 'lib/utils'
+import { humanFriendlyDuration } from 'lib/utils/durations'
import { VisualizationBlock } from '~/queries/schema/schema-assistant-artifacts'
import {
diff --git a/frontend/src/scenes/max/utils/markdownToTiptap.ts b/frontend/src/scenes/max/utils/markdownToTiptap.ts
index 178e9359a0da..fb6df56d2b59 100644
--- a/frontend/src/scenes/max/utils/markdownToTiptap.ts
+++ b/frontend/src/scenes/max/utils/markdownToTiptap.ts
@@ -3,7 +3,7 @@ import { MarkdownManager } from '@tiptap/markdown'
import StarterKit from '@tiptap/starter-kit'
import { JSONContent } from 'lib/components/RichContentEditor/types'
-import { expandFlattenedMarkdownTables } from 'lib/utils/expandFlattenedMarkdownTables'
+import { expandFlattenedMarkdownTables } from 'lib/utils/markdown'
const markdownManager = new MarkdownManager({
extensions: [StarterKit, Table, TableRow, TableHeader, TableCell],
diff --git a/frontend/src/scenes/max/utils/thinkingMessages.ts b/frontend/src/scenes/max/utils/thinkingMessages.ts
index c4787f2404da..5e312a3919fa 100644
--- a/frontend/src/scenes/max/utils/thinkingMessages.ts
+++ b/frontend/src/scenes/max/utils/thinkingMessages.ts
@@ -1,4 +1,4 @@
-import { inStorybookTestRunner } from 'lib/utils'
+import { inStorybookTestRunner } from 'lib/utils/dom'
import { AssistantMessage } from '~/queries/schema/schema-assistant-messages'
diff --git a/frontend/src/scenes/models/DagsTab.tsx b/frontend/src/scenes/models/DagsTab.tsx
index 0614d0cf7d16..96efe24136a2 100644
--- a/frontend/src/scenes/models/DagsTab.tsx
+++ b/frontend/src/scenes/models/DagsTab.tsx
@@ -13,7 +13,7 @@ import {
import { More } from 'lib/lemon-ui/LemonButton/More'
import { LemonField } from 'lib/lemon-ui/LemonField'
-import { pluralize } from 'lib/utils'
+import { pluralize } from 'lib/utils/strings'
import { DataModelingDAG, DataModelingSyncInterval } from '~/types'
diff --git a/frontend/src/scenes/models/NodeDetailMaterialization.tsx b/frontend/src/scenes/models/NodeDetailMaterialization.tsx
index 68d181f22912..78d55533af69 100644
--- a/frontend/src/scenes/models/NodeDetailMaterialization.tsx
+++ b/frontend/src/scenes/models/NodeDetailMaterialization.tsx
@@ -4,7 +4,7 @@ import { LemonButton, LemonTable, LemonTag, Tooltip } from '@posthog/lemon-ui'
import { TZLabel } from 'lib/components/TZLabel'
import { dayjsUtcToTimezone } from 'lib/dayjs'
-import { humanFriendlyDuration } from 'lib/utils'
+import { humanFriendlyDuration } from 'lib/utils/durations'
import { LogsViewer } from 'scenes/hog-functions/logs/LogsViewer'
import { teamLogic } from 'scenes/teamLogic'
import { userLogic } from 'scenes/userLogic'
diff --git a/frontend/src/scenes/notebooks/AddExperimentsToNotebookModal/addExperimentsToNotebookModalLogic.ts b/frontend/src/scenes/notebooks/AddExperimentsToNotebookModal/addExperimentsToNotebookModalLogic.ts
index c5438029f462..0534d9ac68b8 100644
--- a/frontend/src/scenes/notebooks/AddExperimentsToNotebookModal/addExperimentsToNotebookModalLogic.ts
+++ b/frontend/src/scenes/notebooks/AddExperimentsToNotebookModal/addExperimentsToNotebookModalLogic.ts
@@ -3,7 +3,8 @@ import { loaders } from 'kea-loaders'
import api, { CountedPaginatedResponse } from 'lib/api'
import { Sorting } from 'lib/lemon-ui/LemonTable'
-import { objectsEqual, toParams } from 'lib/utils'
+import { objectsEqual } from 'lib/utils/objects'
+import { toParams } from 'lib/utils/url'
import { teamLogic } from 'scenes/teamLogic'
import { Experiment } from '~/types'
diff --git a/frontend/src/scenes/notebooks/Nodes/NodeWrapper.tsx b/frontend/src/scenes/notebooks/Nodes/NodeWrapper.tsx
index 3c02adb4fcc2..2b97ce14f251 100644
--- a/frontend/src/scenes/notebooks/Nodes/NodeWrapper.tsx
+++ b/frontend/src/scenes/notebooks/Nodes/NodeWrapper.tsx
@@ -16,7 +16,7 @@ import './NodeWrapper.scss'
import { LemonSkeleton } from 'lib/lemon-ui/LemonSkeleton'
import { BindLogic, useActions, useMountedLogic, useValues } from 'kea'
import { notebookLogic } from '../Notebook/notebookLogic'
-import { hashCodeForString } from 'lib/utils'
+import { hashCodeForString } from 'lib/utils/strings'
import { useInView } from 'react-intersection-observer'
import { ErrorBoundary } from '~/layout/ErrorBoundary'
import { NotebookNodeLogicProps, notebookNodeLogic } from './notebookNodeLogic'
diff --git a/frontend/src/scenes/notebooks/Nodes/NotebookNodeGroup.tsx b/frontend/src/scenes/notebooks/Nodes/NotebookNodeGroup.tsx
index d3c475714671..8ccd3d8e6d6c 100644
--- a/frontend/src/scenes/notebooks/Nodes/NotebookNodeGroup.tsx
+++ b/frontend/src/scenes/notebooks/Nodes/NotebookNodeGroup.tsx
@@ -10,7 +10,7 @@ import { TZLabel } from 'lib/components/TZLabel'
import { IconTrendingDown, IconTrendingFlat } from 'lib/lemon-ui/icons'
import { LemonSkeleton } from 'lib/lemon-ui/LemonSkeleton'
import { useAttachedLogic } from 'lib/logic/scenes/useAttachedLogic'
-import { formatCurrency } from 'lib/utils/geography/currency'
+import { formatCurrency } from 'lib/utils/currency'
import stringWithWBR from 'lib/utils/stringWithWBR'
import { groupLogic } from 'scenes/groups/groupLogic'
import { createPostHogWidgetNode } from 'scenes/notebooks/Nodes/NodeWrapper'
diff --git a/frontend/src/scenes/notebooks/Nodes/NotebookNodePerson.tsx b/frontend/src/scenes/notebooks/Nodes/NotebookNodePerson.tsx
index 25815263e55e..c80bdb45702f 100644
--- a/frontend/src/scenes/notebooks/Nodes/NotebookNodePerson.tsx
+++ b/frontend/src/scenes/notebooks/Nodes/NotebookNodePerson.tsx
@@ -10,8 +10,8 @@ import { TZLabel } from 'lib/components/TZLabel'
import { dayjs } from 'lib/dayjs'
import { LemonSkeleton } from 'lib/lemon-ui/LemonSkeleton'
import { useAttachedLogic } from 'lib/logic/scenes/useAttachedLogic'
-import { compactNumber } from 'lib/utils'
-import { formatCurrency } from 'lib/utils/geography/currency'
+import { formatCurrency } from 'lib/utils/currency'
+import { compactNumber } from 'lib/utils/numbers'
import { createPostHogWidgetNode } from 'scenes/notebooks/Nodes/NodeWrapper'
import { asDisplay } from 'scenes/persons/person-utils'
import { PersonIcon } from 'scenes/persons/PersonDisplay'
diff --git a/frontend/src/scenes/notebooks/Nodes/NotebookNodePersonFeed/AISessionSummary/AISessionSummary.tsx b/frontend/src/scenes/notebooks/Nodes/NotebookNodePersonFeed/AISessionSummary/AISessionSummary.tsx
index a6d0b88d2de4..b045635bff05 100644
--- a/frontend/src/scenes/notebooks/Nodes/NotebookNodePersonFeed/AISessionSummary/AISessionSummary.tsx
+++ b/frontend/src/scenes/notebooks/Nodes/NotebookNodePersonFeed/AISessionSummary/AISessionSummary.tsx
@@ -4,7 +4,7 @@ import { IconSparkles } from '@posthog/icons'
import { LemonButton, LemonDivider } from '@posthog/lemon-ui'
import { LemonProgress } from 'lib/lemon-ui/LemonProgress'
-import { pluralize } from 'lib/utils'
+import { pluralize } from 'lib/utils/strings'
import { SessionSummaryComponent } from 'scenes/session-recordings/player/PlayerSummaryViews'
import { sessionRecordingPlayerLogic } from 'scenes/session-recordings/player/sessionRecordingPlayerLogic'
diff --git a/frontend/src/scenes/notebooks/Nodes/NotebookNodePersonFeed/Session.tsx b/frontend/src/scenes/notebooks/Nodes/NotebookNodePersonFeed/Session.tsx
index b700d5a99374..3723d36d900e 100644
--- a/frontend/src/scenes/notebooks/Nodes/NotebookNodePersonFeed/Session.tsx
+++ b/frontend/src/scenes/notebooks/Nodes/NotebookNodePersonFeed/Session.tsx
@@ -5,7 +5,8 @@ import { IconCollapse, IconExpand, IconRewindPlay } from '@posthog/icons'
import { LemonButton } from '@posthog/lemon-ui'
import { dayjs } from 'lib/dayjs'
-import { humanFriendlyDetailedTime, humanFriendlyDuration } from 'lib/utils'
+import { humanFriendlyDetailedTime } from 'lib/utils/datetime'
+import { humanFriendlyDuration } from 'lib/utils/durations'
import { NotebookNodeType } from 'scenes/notebooks/types'
import { notebookNodeLogic } from '../notebookNodeLogic'
diff --git a/frontend/src/scenes/notebooks/Nodes/NotebookNodePersonFeed/SessionEvent.tsx b/frontend/src/scenes/notebooks/Nodes/NotebookNodePersonFeed/SessionEvent.tsx
index 3f1735180f42..55c4398900d1 100644
--- a/frontend/src/scenes/notebooks/Nodes/NotebookNodePersonFeed/SessionEvent.tsx
+++ b/frontend/src/scenes/notebooks/Nodes/NotebookNodePersonFeed/SessionEvent.tsx
@@ -1,5 +1,5 @@
import { dayjs } from 'lib/dayjs'
-import { eventToDescription } from 'lib/utils'
+import { eventToDescription } from 'lib/utils/events'
import { EventType } from '~/types'
diff --git a/frontend/src/scenes/notebooks/Nodes/NotebookNodePersonFeed/notebookNodePersonFeedLogic.ts b/frontend/src/scenes/notebooks/Nodes/NotebookNodePersonFeed/notebookNodePersonFeedLogic.ts
index 8b66604efd14..9892296b16c6 100644
--- a/frontend/src/scenes/notebooks/Nodes/NotebookNodePersonFeed/notebookNodePersonFeedLogic.ts
+++ b/frontend/src/scenes/notebooks/Nodes/NotebookNodePersonFeed/notebookNodePersonFeedLogic.ts
@@ -2,7 +2,7 @@ import { actions, afterMount, connect, kea, key, listeners, path, props, reducer
import { loaders } from 'kea-loaders'
import api from 'lib/api'
-import { pluralize } from 'lib/utils'
+import { pluralize } from 'lib/utils/strings'
import { preflightLogic } from 'scenes/PreflightCheck/preflightLogic'
import { SessionSummaryContent } from 'scenes/session-recordings/player/player-meta/types'
diff --git a/frontend/src/lib/utils/timestamps.test.ts b/frontend/src/scenes/notebooks/Nodes/NotebookNodeRecording.test.ts
similarity index 97%
rename from frontend/src/lib/utils/timestamps.test.ts
rename to frontend/src/scenes/notebooks/Nodes/NotebookNodeRecording.test.ts
index 5dcb6d9ae67a..165be171a8bd 100644
--- a/frontend/src/lib/utils/timestamps.test.ts
+++ b/frontend/src/scenes/notebooks/Nodes/NotebookNodeRecording.test.ts
@@ -1,4 +1,4 @@
-import { parseTimestampToMs } from './timestamps'
+import { parseTimestampToMs } from './NotebookNodeRecording'
describe('parseTimestampToMs', () => {
describe('valid inputs', () => {
diff --git a/frontend/src/scenes/notebooks/Nodes/NotebookNodeRecording.tsx b/frontend/src/scenes/notebooks/Nodes/NotebookNodeRecording.tsx
index 5095f0e514f6..7788aa07d910 100644
--- a/frontend/src/scenes/notebooks/Nodes/NotebookNodeRecording.tsx
+++ b/frontend/src/scenes/notebooks/Nodes/NotebookNodeRecording.tsx
@@ -6,8 +6,7 @@ import { LemonInput, LemonSwitch } from '@posthog/lemon-ui'
import { NotFound } from 'lib/components/NotFound'
import { useOnMountEffect } from 'lib/hooks/useOnMountEffect'
-import { colonDelimitedDuration } from 'lib/utils'
-import { parseTimestampToMs } from 'lib/utils/timestamps'
+import { colonDelimitedDuration } from 'lib/utils/durations'
import { createPostHogWidgetNode } from 'scenes/notebooks/Nodes/NodeWrapper'
import { asDisplay } from 'scenes/persons/person-utils'
import { sessionRecordingDataCoordinatorLogic } from 'scenes/session-recordings/player/sessionRecordingDataCoordinatorLogic'
@@ -194,3 +193,33 @@ export function sessionRecordingPlayerProps(id: SessionRecordingId): SessionReco
playerKey: `notebook-${id}`,
}
}
+
+/**
+ * Parse timestamp strings of form "1:23" or "00:01:23" into milliseconds
+ * @param input - Timestamp string
+ * @returns Number of milliseconds, or undefined if invalid
+ */
+export function parseTimestampToMs(input?: string | null): number | undefined {
+ if (input == null) {
+ return undefined
+ }
+ const value = String(input).trim()
+ if (!value.length) {
+ return undefined
+ }
+
+ // Handle mm:ss or hh:mm:ss format
+ const parts = value.split(':').map((p) => Number(p))
+ if (parts.length > 1 && parts.length <= 3 && parts.every((n) => Number.isSafeInteger(n) && n >= 0)) {
+ let seconds = 0
+ if (parts.length === 2) {
+ const [mm, ss] = parts
+ seconds = mm * 60 + ss
+ } else if (parts.length === 3) {
+ const [hh, mm, ss] = parts
+ seconds = hh * 3600 + mm * 60 + ss
+ }
+ return seconds * 1000
+ }
+ return undefined
+}
diff --git a/frontend/src/scenes/notebooks/Nodes/notebookNodeLogic.ts b/frontend/src/scenes/notebooks/Nodes/notebookNodeLogic.ts
index 82f8307f3218..4a34ce1f9823 100644
--- a/frontend/src/scenes/notebooks/Nodes/notebookNodeLogic.ts
+++ b/frontend/src/scenes/notebooks/Nodes/notebookNodeLogic.ts
@@ -18,7 +18,7 @@ import { LemonMenuItems } from '@posthog/lemon-ui'
import api from 'lib/api'
import { JSONContent, RichContentNode } from 'lib/components/RichContentEditor/types'
-import { hashCodeForString } from 'lib/utils'
+import { hashCodeForString } from 'lib/utils/strings'
import { sqlEditorLogic } from 'scenes/data-warehouse/editor/sqlEditorLogic'
import { SQLEditorMode } from 'scenes/data-warehouse/editor/sqlEditorModes'
diff --git a/frontend/src/scenes/notebooks/Nodes/utils.test.tsx b/frontend/src/scenes/notebooks/Nodes/utils.test.tsx
index aa2305edb2ae..dce5caf9c628 100644
--- a/frontend/src/scenes/notebooks/Nodes/utils.test.tsx
+++ b/frontend/src/scenes/notebooks/Nodes/utils.test.tsx
@@ -16,12 +16,12 @@ import {
} from './utils'
// Mock dependencies for Group revenue utilities
-jest.mock('lib/utils', () => ({
- ...jest.requireActual('lib/utils'),
+jest.mock('lib/utils/numbers', () => ({
+ ...jest.requireActual('lib/utils/numbers'),
percentage: jest.fn((value: number) => `${(value * 100).toFixed(1)}%`),
}))
-jest.mock('lib/utils/geography/currency', () => ({
+jest.mock('lib/utils/currency', () => ({
formatCurrency: jest.fn((value: number) => `$${value.toFixed(2)}`),
}))
diff --git a/frontend/src/scenes/notebooks/Nodes/utils.tsx b/frontend/src/scenes/notebooks/Nodes/utils.tsx
index b6b64c87adcb..db08f86281de 100644
--- a/frontend/src/scenes/notebooks/Nodes/utils.tsx
+++ b/frontend/src/scenes/notebooks/Nodes/utils.tsx
@@ -6,8 +6,10 @@ import posthog from 'posthog-js'
import { type ReactNode, useCallback, useMemo, useRef } from 'react'
import { TTEditor } from 'lib/components/RichContentEditor/types'
-import { percentage, tryJsonParse, uuid } from 'lib/utils'
-import { formatCurrency } from 'lib/utils/geography/currency'
+import { formatCurrency } from 'lib/utils/currency'
+import { uuid } from 'lib/utils/dom'
+import { tryJsonParse } from 'lib/utils/json'
+import { percentage } from 'lib/utils/numbers'
import { CurrencyCode } from '~/queries/schema/schema-general'
import { Group } from '~/types'
diff --git a/frontend/src/scenes/notebooks/Notebook/CollapsibleHeading.tsx b/frontend/src/scenes/notebooks/Notebook/CollapsibleHeading.tsx
index fb9736de9eea..c4215f90fb39 100644
--- a/frontend/src/scenes/notebooks/Notebook/CollapsibleHeading.tsx
+++ b/frontend/src/scenes/notebooks/Notebook/CollapsibleHeading.tsx
@@ -7,7 +7,7 @@ import { Editor, ReactRenderer } from '@tiptap/react'
import { IconEye, IconTriangleDownFilled, IconTriangleRightFilled } from '@posthog/icons'
import { LemonButton } from '@posthog/lemon-ui'
-import { humanList, identifierToHuman, pluralize } from 'lib/utils'
+import { humanList, identifierToHuman, pluralize } from 'lib/utils/strings'
import { NotebookNodeType } from '../types'
diff --git a/frontend/src/scenes/notebooks/Notebook/Editor.tsx b/frontend/src/scenes/notebooks/Notebook/Editor.tsx
index 96e8e2c121a0..c4026c200a19 100644
--- a/frontend/src/scenes/notebooks/Notebook/Editor.tsx
+++ b/frontend/src/scenes/notebooks/Notebook/Editor.tsx
@@ -18,7 +18,7 @@ import { RichContentNodeMention } from 'lib/components/RichContentEditor/RichCon
import { RichContentNode, TTEditor } from 'lib/components/RichContentEditor/types'
import { createEditor } from 'lib/components/RichContentEditor/utils'
import { useFeatureFlag } from 'lib/hooks/useFeatureFlag'
-import { uuid } from 'lib/utils'
+import { uuid } from 'lib/utils/dom'
import { MentionsExtension } from '../../../lib/components/RichContentEditor/MentionsExtension'
import { NotebookMarkComment } from '../Marks/NotebookMarkComment'
diff --git a/frontend/src/scenes/notebooks/Notebook/InlineMenu.tsx b/frontend/src/scenes/notebooks/Notebook/InlineMenu.tsx
index 75cfbdecdff0..5143f83be74a 100644
--- a/frontend/src/scenes/notebooks/Notebook/InlineMenu.tsx
+++ b/frontend/src/scenes/notebooks/Notebook/InlineMenu.tsx
@@ -10,7 +10,7 @@ import { LemonButton, LemonDivider, LemonInput } from '@posthog/lemon-ui'
import { richContentEditorLogic } from 'lib/components/RichContentEditor/richContentEditorLogic'
import { RichContentEditorType } from 'lib/components/RichContentEditor/types'
import { IconBold, IconItalic, IconLink, IconOpenInNew } from 'lib/lemon-ui/icons'
-import { isURL } from 'lib/utils'
+import { isURL } from 'lib/utils/url'
import NotebookIconHeading from './NotebookIconHeading'
diff --git a/frontend/src/scenes/notebooks/Notebook/MarkdownNotebookDiscussionComment.tsx b/frontend/src/scenes/notebooks/Notebook/MarkdownNotebookDiscussionComment.tsx
index eff9d57b35bc..b81c42483d10 100644
--- a/frontend/src/scenes/notebooks/Notebook/MarkdownNotebookDiscussionComment.tsx
+++ b/frontend/src/scenes/notebooks/Notebook/MarkdownNotebookDiscussionComment.tsx
@@ -12,7 +12,7 @@ import {
} from 'lib/components/MarkdownNotebook/types'
import { TZLabel } from 'lib/components/TZLabel'
import { dayjs } from 'lib/dayjs'
-import { uuid } from 'lib/utils'
+import { uuid } from 'lib/utils/dom'
import { userLogic } from 'scenes/userLogic'
/**
diff --git a/frontend/src/scenes/notebooks/Notebook/MarkdownNotebookV2Renderer.tsx b/frontend/src/scenes/notebooks/Notebook/MarkdownNotebookV2Renderer.tsx
index 097bbf1085a7..c178962ad0f5 100644
--- a/frontend/src/scenes/notebooks/Notebook/MarkdownNotebookV2Renderer.tsx
+++ b/frontend/src/scenes/notebooks/Notebook/MarkdownNotebookV2Renderer.tsx
@@ -3,7 +3,7 @@ import { useCallback, useMemo, useState } from 'react'
import { MarkdownNotebook } from 'lib/components/MarkdownNotebook'
import type { MarkdownNotebookAskAIRequest } from 'lib/components/MarkdownNotebook'
-import { uuid } from 'lib/utils'
+import { uuid } from 'lib/utils/dom'
import { InlineNotebookAIRunner } from './MarkdownNotebookAIChat'
import { NOTEBOOK_MARKDOWN_REGISTRY } from './markdownNotebookRegistry'
diff --git a/frontend/src/scenes/notebooks/Notebook/NotebookColumnRight.tsx b/frontend/src/scenes/notebooks/Notebook/NotebookColumnRight.tsx
index bff1def8f1da..4270f010cf18 100644
--- a/frontend/src/scenes/notebooks/Notebook/NotebookColumnRight.tsx
+++ b/frontend/src/scenes/notebooks/Notebook/NotebookColumnRight.tsx
@@ -1,7 +1,7 @@
import clsx from 'clsx'
import { BuiltLogic, useValues } from 'kea'
-import { uuid } from 'lib/utils'
+import { uuid } from 'lib/utils/dom'
import { NotebookNodeChildRenderer } from '../Nodes/NodeWrapper'
import { notebookNodeLogicType } from '../Nodes/notebookNodeLogicType'
diff --git a/frontend/src/scenes/notebooks/Notebook/NotebookShareModal.tsx b/frontend/src/scenes/notebooks/Notebook/NotebookShareModal.tsx
index 9a999743ee7e..aad27ae8353a 100644
--- a/frontend/src/scenes/notebooks/Notebook/NotebookShareModal.tsx
+++ b/frontend/src/scenes/notebooks/Notebook/NotebookShareModal.tsx
@@ -7,7 +7,7 @@ import { LemonBanner, LemonButton, LemonDivider, LemonModal } from '@posthog/lem
import { SHARING_MODAL_WIDTH, SharingModalContent } from 'lib/components/Sharing/SharingModal'
import { useFeatureFlag } from 'lib/hooks/useFeatureFlag'
-import { base64Encode } from 'lib/utils'
+import { base64Encode } from 'lib/utils/base64'
import { copyToClipboard } from 'lib/utils/copyToClipboard'
import { urls } from 'scenes/urls'
diff --git a/frontend/src/scenes/notebooks/Notebook/SlashCommands.tsx b/frontend/src/scenes/notebooks/Notebook/SlashCommands.tsx
index fe327b50a3eb..12eda9fb6f9e 100644
--- a/frontend/src/scenes/notebooks/Notebook/SlashCommands.tsx
+++ b/frontend/src/scenes/notebooks/Notebook/SlashCommands.tsx
@@ -29,9 +29,9 @@ import { IconBold, IconItalic, IconTableChart } from 'lib/lemon-ui/icons'
import { LemonMenu, LemonMenuItem } from 'lib/lemon-ui/LemonMenu'
import { Popover } from 'lib/lemon-ui/Popover'
import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
-import { isKeyOf } from 'lib/utils'
import { selectFiles } from 'lib/utils/file-utils'
import { createFuse } from 'lib/utils/fuseSearch'
+import { isKeyOf } from 'lib/utils/guards'
import { ValueOf } from 'lib/utils/types'
import { KeyboardShortcut } from '~/layout/navigation-3000/components/KeyboardShortcut'
diff --git a/frontend/src/scenes/notebooks/Notebook/migrations/migrate.ts b/frontend/src/scenes/notebooks/Notebook/migrations/migrate.ts
index 14c7220734e8..6779521d7745 100644
--- a/frontend/src/scenes/notebooks/Notebook/migrations/migrate.ts
+++ b/frontend/src/scenes/notebooks/Notebook/migrations/migrate.ts
@@ -1,7 +1,7 @@
import { JSONContent } from '@tiptap/core'
import api from 'lib/api'
-import { isEmptyObject } from 'lib/utils'
+import { isEmptyObject } from 'lib/utils/guards'
import { NotebookNodePlaylistAttributes } from 'scenes/notebooks/Nodes/NotebookNodePlaylist'
import { NotebookNodeType, NotebookType } from 'scenes/notebooks/types'
import { convertLegacyFiltersToUniversalFilters } from 'scenes/session-recordings/playlist/sessionRecordingsPlaylistLogic'
diff --git a/frontend/src/scenes/notebooks/Notebook/notebookCollabLogic.ts b/frontend/src/scenes/notebooks/Notebook/notebookCollabLogic.ts
index a5bec7ba952a..2dd78150bbf5 100644
--- a/frontend/src/scenes/notebooks/Notebook/notebookCollabLogic.ts
+++ b/frontend/src/scenes/notebooks/Notebook/notebookCollabLogic.ts
@@ -6,7 +6,7 @@ import posthog from 'posthog-js'
import api from 'lib/api'
import { JSONContent, TTEditor } from 'lib/components/RichContentEditor/types'
-import { uuid } from 'lib/utils'
+import { uuid } from 'lib/utils/dom'
import { getCurrentTeamId } from 'lib/utils/getAppContext'
import { notebooksCollabPresenceCreate } from 'products/notebooks/frontend/generated/api'
diff --git a/frontend/src/scenes/notebooks/Notebook/notebookLogic.ts b/frontend/src/scenes/notebooks/Notebook/notebookLogic.ts
index 68112f5371a6..c2fec8ddf2b4 100644
--- a/frontend/src/scenes/notebooks/Notebook/notebookLogic.ts
+++ b/frontend/src/scenes/notebooks/Notebook/notebookLogic.ts
@@ -35,10 +35,13 @@ import type { NotebookCollaborationConflict } from 'lib/components/MarkdownNoteb
import { EditorRange, JSONContent } from 'lib/components/RichContentEditor/types'
import { FEATURE_FLAGS } from 'lib/constants'
import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
-import { base64Decode, base64Encode, downloadFile, objectsEqual, slugify, uuid } from 'lib/utils'
import { accessLevelSatisfied } from 'lib/utils/accessControlUtils'
+import { base64Decode, base64Encode } from 'lib/utils/base64'
import { copyToClipboard } from 'lib/utils/copyToClipboard'
+import { uuid, downloadFile } from 'lib/utils/dom'
import { getCurrentTeamId } from 'lib/utils/getAppContext'
+import { objectsEqual } from 'lib/utils/objects'
+import { slugify } from 'lib/utils/strings'
import { commentsLogic } from 'scenes/comments/commentsLogic'
import { urls } from 'scenes/urls'
diff --git a/frontend/src/scenes/notebooks/NotebookCanvasScene.tsx b/frontend/src/scenes/notebooks/NotebookCanvasScene.tsx
index 4c5a68c75b16..c471e5def019 100644
--- a/frontend/src/scenes/notebooks/NotebookCanvasScene.tsx
+++ b/frontend/src/scenes/notebooks/NotebookCanvasScene.tsx
@@ -4,8 +4,8 @@ import { useMemo } from 'react'
import { IconEllipsis } from '@posthog/icons'
import { LemonButton, LemonMenu, lemonToast } from '@posthog/lemon-ui'
-import { uuid } from 'lib/utils'
import { copyToClipboard } from 'lib/utils/copyToClipboard'
+import { uuid } from 'lib/utils/dom'
import { getTextFromFile, selectFiles } from 'lib/utils/file-utils'
import { SceneExport } from 'scenes/sceneTypes'
import { urls } from 'scenes/urls'
diff --git a/frontend/src/scenes/notebooks/NotebooksScene.tsx b/frontend/src/scenes/notebooks/NotebooksScene.tsx
index 144e01b629a3..f44c17373780 100644
--- a/frontend/src/scenes/notebooks/NotebooksScene.tsx
+++ b/frontend/src/scenes/notebooks/NotebooksScene.tsx
@@ -6,7 +6,7 @@ import { LemonButton, LemonMenu, Tooltip, lemonToast } from '@posthog/lemon-ui'
import { AccessControlAction } from 'lib/components/AccessControlAction'
import { AppShortcut } from 'lib/components/AppShortcuts/AppShortcut'
import { keyBinds } from 'lib/components/AppShortcuts/shortcuts'
-import { base64Encode } from 'lib/utils'
+import { base64Encode } from 'lib/utils/base64'
import { getTextFromFile, selectFiles } from 'lib/utils/file-utils'
import { notebooksTableLogic } from 'scenes/notebooks/NotebooksTable/notebooksTableLogic'
import { Scene, SceneExport } from 'scenes/sceneTypes'
diff --git a/frontend/src/scenes/notebooks/NotebooksTable/notebooksTableLogic.ts b/frontend/src/scenes/notebooks/NotebooksTable/notebooksTableLogic.ts
index 306cf08c9eb1..fb872f1017dc 100644
--- a/frontend/src/scenes/notebooks/NotebooksTable/notebooksTableLogic.ts
+++ b/frontend/src/scenes/notebooks/NotebooksTable/notebooksTableLogic.ts
@@ -4,7 +4,7 @@ import { loaders } from 'kea-loaders'
import { PaginationManual, Sorting } from '@posthog/lemon-ui'
import api, { CountedPaginatedResponse } from 'lib/api'
-import { objectClean, objectsEqual } from 'lib/utils'
+import { objectClean, objectsEqual } from 'lib/utils/objects'
import { SIDE_PANEL_CONTEXT_KEY, SidePanelSceneContext } from '~/layout/navigation-3000/sidepanel/types'
import { notebooksModel } from '~/models/notebooksModel'
diff --git a/frontend/src/scenes/onboarding/billing/PlanCards.tsx b/frontend/src/scenes/onboarding/billing/PlanCards.tsx
index 3ffd95cc6877..4d993c95ff10 100644
--- a/frontend/src/scenes/onboarding/billing/PlanCards.tsx
+++ b/frontend/src/scenes/onboarding/billing/PlanCards.tsx
@@ -9,8 +9,8 @@ import { LemonButton } from '@posthog/lemon-ui'
import { BillingUpgradeCTA } from 'lib/components/BillingUpgradeCTA'
import { HeartHog } from 'lib/components/hedgehogs'
-import { pluralize } from 'lib/utils'
import { eventUsageLogic } from 'lib/utils/eventUsageLogic'
+import { pluralize } from 'lib/utils/strings'
import { billingLogic } from 'scenes/billing/billingLogic'
import { billingProductLogic } from 'scenes/billing/billingProductLogic'
import { paymentEntryLogic } from 'scenes/billing/paymentEntryLogic'
diff --git a/frontend/src/scenes/onboarding/onboardingLogic.tsx b/frontend/src/scenes/onboarding/onboardingLogic.tsx
index 924cea1c17c7..65be9a914df0 100644
--- a/frontend/src/scenes/onboarding/onboardingLogic.tsx
+++ b/frontend/src/scenes/onboarding/onboardingLogic.tsx
@@ -6,9 +6,9 @@ import { globalSetupLogic } from 'lib/components/ProductSetup/globalSetupLogic'
import { FEATURE_FLAGS, OrganizationMembershipLevel } from 'lib/constants'
import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'
import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
-import { isKeyOf } from 'lib/utils'
import { eventUsageLogic } from 'lib/utils/eventUsageLogic'
-import { removeProjectIdIfPresent } from 'lib/utils/router-utils'
+import { isKeyOf } from 'lib/utils/guards'
+import { removeProjectIdIfPresent } from 'lib/utils/kea-router'
import { billingLogic } from 'scenes/billing/billingLogic'
import { organizationLogic } from 'scenes/organizationLogic'
import { preflightLogic } from 'scenes/PreflightCheck/preflightLogic'
diff --git a/frontend/src/scenes/onboarding/productSelection/productSelectionLogic.ts b/frontend/src/scenes/onboarding/productSelection/productSelectionLogic.ts
index 905a978f5095..2e978e993a1a 100644
--- a/frontend/src/scenes/onboarding/productSelection/productSelectionLogic.ts
+++ b/frontend/src/scenes/onboarding/productSelection/productSelectionLogic.ts
@@ -1,8 +1,8 @@
import { actions, afterMount, connect, kea, listeners, path, reducers, selectors } from 'kea'
import { router } from 'kea-router'
-import { getRelativeNextPath } from 'lib/utils'
import { eventUsageLogic } from 'lib/utils/eventUsageLogic'
+import { getRelativeNextPath } from 'lib/utils/url'
import { onboardingLogic } from 'scenes/onboarding/onboardingLogic'
import { USE_CASE_OPTIONS, UseCaseOption, getRecommendedProducts } from 'scenes/onboarding/productRecommendations'
import { teamLogic } from 'scenes/teamLogic'
diff --git a/frontend/src/scenes/onboarding/sdks/OnboardingInstallStep/index.tsx b/frontend/src/scenes/onboarding/sdks/OnboardingInstallStep/index.tsx
index 738d8b7ea6b6..aaee932bfeaa 100644
--- a/frontend/src/scenes/onboarding/sdks/OnboardingInstallStep/index.tsx
+++ b/frontend/src/scenes/onboarding/sdks/OnboardingInstallStep/index.tsx
@@ -3,7 +3,7 @@ import posthog from 'posthog-js'
import { useEffect, useRef, useState } from 'react'
import { useFeatureFlag } from 'lib/hooks/useFeatureFlag'
-import { isMobile } from 'lib/utils'
+import { isMobile } from 'lib/utils/dom'
import { teamLogic } from 'scenes/teamLogic'
import { ProductKey } from '~/queries/schema/schema-general'
diff --git a/frontend/src/scenes/onboarding/sdks/SdkHealthScene.tsx b/frontend/src/scenes/onboarding/sdks/SdkHealthScene.tsx
index 539989032ec2..174485362ffa 100644
--- a/frontend/src/scenes/onboarding/sdks/SdkHealthScene.tsx
+++ b/frontend/src/scenes/onboarding/sdks/SdkHealthScene.tsx
@@ -7,7 +7,7 @@ import { LemonBanner, LemonButton, LemonTag, Link } from '@posthog/lemon-ui'
import { FEATURE_FLAGS } from 'lib/constants'
import { useOnMountEffect } from 'lib/hooks/useOnMountEffect'
import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
-import { inStorybook, inStorybookTestRunner } from 'lib/utils'
+import { inStorybook, inStorybookTestRunner } from 'lib/utils/dom'
import { preflightLogic } from 'scenes/PreflightCheck/preflightLogic'
import { SceneExport } from 'scenes/sceneTypes'
import { urls } from 'scenes/urls'
diff --git a/frontend/src/scenes/onboarding/sdks/sdksLogic.tsx b/frontend/src/scenes/onboarding/sdks/sdksLogic.tsx
index 2a4b721966fe..30f4dbfda76b 100644
--- a/frontend/src/scenes/onboarding/sdks/sdksLogic.tsx
+++ b/frontend/src/scenes/onboarding/sdks/sdksLogic.tsx
@@ -5,8 +5,8 @@ import { urlToAction } from 'kea-router'
import api from 'lib/api'
import { LemonSelectOptions } from 'lib/lemon-ui/LemonSelect/LemonSelect'
import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
-import { isKeyOf } from 'lib/utils'
import { eventUsageLogic } from 'lib/utils/eventUsageLogic'
+import { isKeyOf } from 'lib/utils/guards'
import { liveEventsLogic } from 'scenes/activity/live/liveEventsLogic'
import { userLogic } from 'scenes/userLogic'
diff --git a/frontend/src/scenes/organization/ConfirmOrganization/confirmOrganizationLogic.ts b/frontend/src/scenes/organization/ConfirmOrganization/confirmOrganizationLogic.ts
index ca48ddb2445a..81854f718cd5 100644
--- a/frontend/src/scenes/organization/ConfirmOrganization/confirmOrganizationLogic.ts
+++ b/frontend/src/scenes/organization/ConfirmOrganization/confirmOrganizationLogic.ts
@@ -4,7 +4,7 @@ import { urlToAction } from 'kea-router'
import api from 'lib/api'
import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'
-import { getRelativeNextPath } from 'lib/utils'
+import { getRelativeNextPath } from 'lib/utils/url'
import type { confirmOrganizationLogicType } from './confirmOrganizationLogicType'
diff --git a/frontend/src/scenes/organization/membersExportLogic.ts b/frontend/src/scenes/organization/membersExportLogic.ts
index 345ea7d26e2b..ca10c9da5ab7 100644
--- a/frontend/src/scenes/organization/membersExportLogic.ts
+++ b/frontend/src/scenes/organization/membersExportLogic.ts
@@ -3,10 +3,10 @@ import { actions, connect, kea, listeners, path, selectors } from 'kea'
import { downloadBlob } from 'lib/components/ExportButton/exporter'
import { dayjs } from 'lib/dayjs'
import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'
-import { capitalizeFirstLetter, fullName } from 'lib/utils'
-import { slugify } from 'lib/utils'
import { permanentlyMount } from 'lib/utils/kea-logic-builders'
import { membershipLevelToName } from 'lib/utils/permissioning'
+import { capitalizeFirstLetter, fullName } from 'lib/utils/strings'
+import { slugify } from 'lib/utils/strings'
import { organizationLogic } from 'scenes/organizationLogic'
import { OrganizationMemberType } from '~/types'
diff --git a/frontend/src/scenes/organizationLogic.tsx b/frontend/src/scenes/organizationLogic.tsx
index 4e0edaec3a86..f2977a5af3dc 100644
--- a/frontend/src/scenes/organizationLogic.tsx
+++ b/frontend/src/scenes/organizationLogic.tsx
@@ -8,7 +8,7 @@ import { timeSensitiveAuthenticationLogic } from 'lib/components/TimeSensitiveAu
import { OrganizationMembershipLevel } from 'lib/constants'
import { dayjs } from 'lib/dayjs'
import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'
-import { isUserLoggedIn } from 'lib/utils'
+import { isUserLoggedIn } from 'lib/utils/getAppContext'
import { getAppContext } from 'lib/utils/getAppContext'
import { sidePanelStateLogic } from '~/layout/navigation-3000/sidepanel/sidePanelStateLogic'
diff --git a/frontend/src/scenes/paths-v2/PathsV2.tsx b/frontend/src/scenes/paths-v2/PathsV2.tsx
index 6a7f4f71b60d..6c649a42abec 100644
--- a/frontend/src/scenes/paths-v2/PathsV2.tsx
+++ b/frontend/src/scenes/paths-v2/PathsV2.tsx
@@ -4,7 +4,7 @@ import { useActions, useValues } from 'kea'
import { useEffect, useRef, useState } from 'react'
import { useResizeObserver } from 'lib/hooks/useResizeObserver'
-import { lightenDarkenColor } from 'lib/utils'
+import { lightenDarkenColor } from 'lib/utils/colors'
import { InsightEmptyState, InsightErrorState } from 'scenes/insights/EmptyStates'
import { insightDataLogic } from 'scenes/insights/insightDataLogic'
import { insightLogic } from 'scenes/insights/insightLogic'
diff --git a/frontend/src/scenes/paths-v2/pathUtils.ts b/frontend/src/scenes/paths-v2/pathUtils.ts
index cefa85a887af..52c8572f0845 100644
--- a/frontend/src/scenes/paths-v2/pathUtils.ts
+++ b/frontend/src/scenes/paths-v2/pathUtils.ts
@@ -1,6 +1,6 @@
import { RGBColor } from 'd3'
-import { tryDecodeURIComponent } from 'lib/utils'
+import { tryDecodeURIComponent } from 'lib/utils/url'
import { FunnelPathsFilter, PathsFilter } from '~/queries/schema/schema-general'
import { FunnelPathType } from '~/types'
diff --git a/frontend/src/scenes/paths/PathNodeCardMenu.tsx b/frontend/src/scenes/paths/PathNodeCardMenu.tsx
index 6f1b0d25131a..7d2fcc54eb5b 100644
--- a/frontend/src/scenes/paths/PathNodeCardMenu.tsx
+++ b/frontend/src/scenes/paths/PathNodeCardMenu.tsx
@@ -4,7 +4,7 @@ import { IconClock } from '@posthog/icons'
import { LemonButton } from '@posthog/lemon-ui'
import { IconTrendingFlat, IconTrendingFlatDown } from 'lib/lemon-ui/icons'
-import { humanFriendlyDuration } from 'lib/utils'
+import { humanFriendlyDuration } from 'lib/utils/durations'
import { PATH_NODE_CARD_WIDTH } from './constants'
import { pathsDataLogicType } from './pathsDataLogicType'
diff --git a/frontend/src/scenes/paths/pathUtils.ts b/frontend/src/scenes/paths/pathUtils.ts
index dc2ba84b3a34..966aa07f28a9 100644
--- a/frontend/src/scenes/paths/pathUtils.ts
+++ b/frontend/src/scenes/paths/pathUtils.ts
@@ -1,6 +1,6 @@
import { RGBColor } from 'd3'
-import { tryDecodeURIComponent } from 'lib/utils'
+import { tryDecodeURIComponent } from 'lib/utils/url'
import { FunnelPathsFilter, PathsFilter } from '~/queries/schema/schema-general'
import { FunnelPathType } from '~/types'
diff --git a/frontend/src/scenes/paths/renderPaths.ts b/frontend/src/scenes/paths/renderPaths.ts
index 70abb4acab30..5420b1058ac8 100644
--- a/frontend/src/scenes/paths/renderPaths.ts
+++ b/frontend/src/scenes/paths/renderPaths.ts
@@ -2,7 +2,7 @@ import * as d3 from 'd3'
import { RefObject } from 'react'
import { D3Selector } from 'lib/hooks/useD3'
-import { stripHTTP } from 'lib/utils'
+import { stripHTTP } from 'lib/utils/url'
import { FunnelPathsFilter, PathsFilter } from '~/queries/schema/schema-general'
import sankey, { sankeyJustify, sankeyLinkHorizontal, type SankeyLink, type SankeyLayout } from '~/vendor/d3/sankey'
diff --git a/frontend/src/scenes/persons-management/personsManagementSceneLogic.tsx b/frontend/src/scenes/persons-management/personsManagementSceneLogic.tsx
index 353b89c7da84..3ff246972ca5 100644
--- a/frontend/src/scenes/persons-management/personsManagementSceneLogic.tsx
+++ b/frontend/src/scenes/persons-management/personsManagementSceneLogic.tsx
@@ -4,7 +4,7 @@ import { FEATURE_FLAGS } from 'lib/constants'
import { GroupsAccessStatus } from 'lib/introductions/groupsAccessLogic'
import { LemonTab } from 'lib/lemon-ui/LemonTabs'
import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
-import { capitalizeFirstLetter } from 'lib/utils'
+import { capitalizeFirstLetter } from 'lib/utils/strings'
import { urls } from 'scenes/urls'
import { groupsModel } from '~/models/groupsModel'
diff --git a/frontend/src/scenes/persons/MergeSplitPerson.tsx b/frontend/src/scenes/persons/MergeSplitPerson.tsx
index 6ce85dd121a8..996eec19e27a 100644
--- a/frontend/src/scenes/persons/MergeSplitPerson.tsx
+++ b/frontend/src/scenes/persons/MergeSplitPerson.tsx
@@ -4,7 +4,7 @@ import { LemonButton, LemonModal, LemonSegmentedButton, LemonSelect } from '@pos
import { LemonBanner } from 'lib/lemon-ui/LemonBanner'
import { LemonInputSelect } from 'lib/lemon-ui/LemonInputSelect/LemonInputSelect'
-import { pluralize } from 'lib/utils'
+import { pluralize } from 'lib/utils/strings'
import { PersonType } from '~/types'
diff --git a/frontend/src/scenes/persons/PersonScene.tsx b/frontend/src/scenes/persons/PersonScene.tsx
index c6e9e874d165..30cd4a644f3d 100644
--- a/frontend/src/scenes/persons/PersonScene.tsx
+++ b/frontend/src/scenes/persons/PersonScene.tsx
@@ -17,9 +17,9 @@ import { LemonTabs } from 'lib/lemon-ui/LemonTabs'
import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'
import { SpinnerOverlay } from 'lib/lemon-ui/Spinner/Spinner'
import { Tooltip } from 'lib/lemon-ui/Tooltip'
-import { isMobile, pluralize } from 'lib/utils'
import { copyToClipboard } from 'lib/utils/copyToClipboard'
-import { openInAdminPanel } from 'lib/utils/person-actions'
+import { isMobile } from 'lib/utils/dom'
+import { pluralize } from 'lib/utils/strings'
import { RelatedGroups } from 'scenes/groups/RelatedGroups'
import { NotebookSelectButton } from 'scenes/notebooks/NotebookSelectButton/NotebookSelectButton'
import { NotebookNodeType } from 'scenes/notebooks/types'
@@ -518,6 +518,22 @@ function OpenInAdminPanelButton({ size = 'small' }: { size?: LemonButtonProps['s
const { person } = useValues(personsLogic)
const disabledReason = !person?.properties.email ? 'Person has no email' : undefined
+ const openInAdminPanel = async (email: string): Promise<void> => {
+ try {
+ const response = await api.users.list(email)
+
+ if (!response.results || response.results.length === 0) {
+ throw new Error('User not found')
+ }
+
+ const userId = response.results[0].id
+ window.open(`/admin/posthog/user/${userId}/change/`, '_blank')
+ } catch (error) {
+ const message = error instanceof Error ? error.message : String(error)
+ lemonToast.error(`Failed to open admin panel: ${message}`)
+ }
+ }
+
return (
<LemonButton
type="secondary"
diff --git a/frontend/src/scenes/persons/PersonsScene.tsx b/frontend/src/scenes/persons/PersonsScene.tsx
index cff94f5e4017..b01e4ef00dab 100644
--- a/frontend/src/scenes/persons/PersonsScene.tsx
+++ b/frontend/src/scenes/persons/PersonsScene.tsx
@@ -9,7 +9,7 @@ import { useOnMountEffect } from 'lib/hooks/useOnMountEffect'
import { LemonField } from 'lib/lemon-ui/LemonField'
import { Link } from 'lib/lemon-ui/Link'
import { ButtonPrimitive } from 'lib/ui/Button/ButtonPrimitives'
-import { isUUIDLike } from 'lib/utils'
+import { isUUIDLike } from 'lib/utils/guards'
import { PersonsManagementSceneTabs } from 'scenes/persons-management/PersonsManagementSceneTabs'
import { sceneConfigurations } from 'scenes/scenes'
import { Scene, SceneExport } from 'scenes/sceneTypes'
diff --git a/frontend/src/scenes/persons/activityDescriptions.tsx b/frontend/src/scenes/persons/activityDescriptions.tsx
index 4745bf3ffea9..209b8c957371 100644
--- a/frontend/src/scenes/persons/activityDescriptions.tsx
+++ b/frontend/src/scenes/persons/activityDescriptions.tsx
@@ -6,7 +6,7 @@ import {
} from 'lib/components/ActivityLog/humanizeActivity'
import { SentenceList } from 'lib/components/ActivityLog/SentenceList'
import { Link } from 'lib/lemon-ui/Link'
-import { isObject } from 'lib/utils'
+import { isObject } from 'lib/utils/guards'
import { PersonDisplay } from 'scenes/persons/PersonDisplay'
import { urls } from 'scenes/urls'
diff --git a/frontend/src/scenes/persons/person-utils.test.ts b/frontend/src/scenes/persons/person-utils.test.ts
index eb34d182c502..2fd57ffa828f 100644
--- a/frontend/src/scenes/persons/person-utils.test.ts
+++ b/frontend/src/scenes/persons/person-utils.test.ts
@@ -1,4 +1,4 @@
-import { uuid } from 'lib/utils'
+import { uuid } from 'lib/utils/dom'
import { urls } from 'scenes/urls'
import { PersonType } from '~/types'
diff --git a/frontend/src/scenes/persons/person-utils.ts b/frontend/src/scenes/persons/person-utils.ts
index 7d310754b6e5..b0b2a6707723 100644
--- a/frontend/src/scenes/persons/person-utils.ts
+++ b/frontend/src/scenes/persons/person-utils.ts
@@ -3,7 +3,8 @@ import './PersonDisplay.scss'
import { PERSON_DEFAULT_DISPLAY_NAME_PROPERTIES } from 'lib/constants'
import { NUM_LETTERMARK_STYLES } from 'lib/lemon-ui/Lettermark/Lettermark'
import { ProfilePictureProps } from 'lib/lemon-ui/ProfilePicture'
-import { isUUIDLike, midEllipsis } from 'lib/utils'
+import { isUUIDLike } from 'lib/utils/guards'
+import { midEllipsis } from 'lib/utils/strings'
import { teamLogic } from 'scenes/teamLogic'
import { urls } from 'scenes/urls'
diff --git a/frontend/src/scenes/persons/personDeleteModalLogic.tsx b/frontend/src/scenes/persons/personDeleteModalLogic.tsx
index 28dbc7854206..b2e19f2dbfc0 100644
--- a/frontend/src/scenes/persons/personDeleteModalLogic.tsx
+++ b/frontend/src/scenes/persons/personDeleteModalLogic.tsx
@@ -4,7 +4,7 @@ import posthog from 'posthog-js'
import api from 'lib/api'
import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'
-import { toParams } from 'lib/utils'
+import { toParams } from 'lib/utils/url'
import { PersonType } from '~/types'
diff --git a/frontend/src/scenes/persons/personsLogic.tsx b/frontend/src/scenes/persons/personsLogic.tsx
index b6dfd8d86a98..296c7ea28223 100644
--- a/frontend/src/scenes/persons/personsLogic.tsx
+++ b/frontend/src/scenes/persons/personsLogic.tsx
@@ -10,8 +10,10 @@ import { FEATURE_FLAGS, PERSON_DISPLAY_NAME_COLUMN_NAME } from 'lib/constants'
import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'
import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
import { trackedActionToUrl } from 'lib/logic/scenes/trackedActionToUrl'
-import { isAbortedRequest, objectsEqual, toParams } from 'lib/utils'
import { eventUsageLogic } from 'lib/utils/eventUsageLogic'
+import { objectsEqual } from 'lib/utils/objects'
+import { isAbortedRequest } from 'lib/utils/requests'
+import { toParams } from 'lib/utils/url'
import { sceneConfigurations } from 'scenes/scenes'
import { Scene } from 'scenes/sceneTypes'
import { teamLogic } from 'scenes/teamLogic'
diff --git a/frontend/src/scenes/persons/relatedFeatureFlagsLogic.ts b/frontend/src/scenes/persons/relatedFeatureFlagsLogic.ts
index b7da26237769..fb3e01b7bb7a 100644
--- a/frontend/src/scenes/persons/relatedFeatureFlagsLogic.ts
+++ b/frontend/src/scenes/persons/relatedFeatureFlagsLogic.ts
@@ -3,7 +3,7 @@ import { loaders } from 'kea-loaders'
import { urlToAction } from 'kea-router'
import api from 'lib/api'
-import { toParams } from 'lib/utils'
+import { toParams } from 'lib/utils/url'
import { FeatureFlagsFilters, featureFlagsLogic } from 'scenes/feature-flags/featureFlagsLogic'
import { projectLogic } from 'scenes/projectLogic'
import { urls } from 'scenes/urls'
diff --git a/frontend/src/scenes/product-tours/components/AutoShowSection.tsx b/frontend/src/scenes/product-tours/components/AutoShowSection.tsx
index d16cc6ad24d7..9ff541f42419 100644
--- a/frontend/src/scenes/product-tours/components/AutoShowSection.tsx
+++ b/frontend/src/scenes/product-tours/components/AutoShowSection.tsx
@@ -16,7 +16,7 @@ import {
import { EventSelect } from 'lib/components/EventSelect/EventSelect'
import { PropertyFilters } from 'lib/components/PropertyFilters/PropertyFilters'
import { TaxonomicFilterGroupType } from 'lib/components/TaxonomicFilter/types'
-import { toSentenceCase } from 'lib/utils'
+import { toSentenceCase } from 'lib/utils/strings'
import { AddEventButton } from 'scenes/surveys/AddEventButton'
import { SurveyMatchTypeLabels } from 'scenes/surveys/constants'
import {
diff --git a/frontend/src/scenes/product-tours/editor/TranslationsPanel.tsx b/frontend/src/scenes/product-tours/editor/TranslationsPanel.tsx
index 3fd3688fdfe0..99ebc7a37e74 100644
--- a/frontend/src/scenes/product-tours/editor/TranslationsPanel.tsx
+++ b/frontend/src/scenes/product-tours/editor/TranslationsPanel.tsx
@@ -6,8 +6,8 @@ import { IconCopy, IconTrash } from '@posthog/icons'
import { LemonButton, LemonTag, Link } from '@posthog/lemon-ui'
import { LemonInputSelect, LemonInputSelectOption } from 'lib/lemon-ui/LemonInputSelect/LemonInputSelect'
-import { toSentenceCase } from 'lib/utils'
import { copyToClipboard } from 'lib/utils/copyToClipboard'
+import { toSentenceCase } from 'lib/utils/strings'
import { productTourLogic } from '../productTourLogic'
diff --git a/frontend/src/scenes/product-tours/editor/productTourCSSUtils.ts b/frontend/src/scenes/product-tours/editor/productTourCSSUtils.ts
index 143a43bb4388..a82bef4b38d9 100644
--- a/frontend/src/scenes/product-tours/editor/productTourCSSUtils.ts
+++ b/frontend/src/scenes/product-tours/editor/productTourCSSUtils.ts
@@ -1,4 +1,4 @@
-import { hexToRGB, hexToRGBA } from 'lib/utils'
+import { hexToRGB, hexToRGBA } from 'lib/utils/colors'
import { ProductTourAppearance } from '~/types'
diff --git a/frontend/src/scenes/product-tours/productTourLogic.ts b/frontend/src/scenes/product-tours/productTourLogic.ts
index b17f54dcb090..98cb0976adc2 100644
--- a/frontend/src/scenes/product-tours/productTourLogic.ts
+++ b/frontend/src/scenes/product-tours/productTourLogic.ts
@@ -9,7 +9,7 @@ import { lemonToast } from '@posthog/lemon-ui'
import api from 'lib/api'
import { dayjs } from 'lib/dayjs'
-import { dateStringToDayJs } from 'lib/utils'
+import { dateStringToDayJs } from 'lib/utils/dateFilters'
import { eventUsageLogic } from 'lib/utils/eventUsageLogic'
import { NEW_FLAG } from 'scenes/feature-flags/featureFlagLogic'
import { sceneConfigurations } from 'scenes/scenes'
diff --git a/frontend/src/scenes/product-tours/productToursLogic.ts b/frontend/src/scenes/product-tours/productToursLogic.ts
index fc47649de520..f5caf015ff67 100644
--- a/frontend/src/scenes/product-tours/productToursLogic.ts
+++ b/frontend/src/scenes/product-tours/productToursLogic.ts
@@ -6,7 +6,7 @@ import { lemonToast } from '@posthog/lemon-ui'
import api, { PaginatedResponse } from 'lib/api'
import { dayjs } from 'lib/dayjs'
-import { uuid } from 'lib/utils'
+import { uuid } from 'lib/utils/dom'
import { eventUsageLogic } from 'lib/utils/eventUsageLogic'
import { addProductIntent } from 'lib/utils/product-intents'
import { sceneConfigurations } from 'scenes/scenes'
diff --git a/frontend/src/scenes/product-tours/stepUtils.tsx b/frontend/src/scenes/product-tours/stepUtils.tsx
index 33e87a97c854..f1fe0532283d 100644
--- a/frontend/src/scenes/product-tours/stepUtils.tsx
+++ b/frontend/src/scenes/product-tours/stepUtils.tsx
@@ -2,7 +2,7 @@ import { JSONContent } from '@tiptap/core'
import { IconMessage, IconQuestion } from '@posthog/icons'
-import { uuid } from 'lib/utils'
+import { uuid } from 'lib/utils/dom'
import {
PRODUCT_TOUR_STEP_WIDTHS,
diff --git a/frontend/src/scenes/project-homepage/ai-first/HomepageInput.tsx b/frontend/src/scenes/project-homepage/ai-first/HomepageInput.tsx
index 4abe8f0d43b8..1d7e6db5b070 100644
--- a/frontend/src/scenes/project-homepage/ai-first/HomepageInput.tsx
+++ b/frontend/src/scenes/project-homepage/ai-first/HomepageInput.tsx
@@ -12,7 +12,7 @@ import { Link } from 'lib/lemon-ui/Link'
import { ButtonPrimitive } from 'lib/ui/Button/ButtonPrimitives'
import { Label } from 'lib/ui/Label/Label'
import { TextareaPrimitive } from 'lib/ui/TextareaPrimitive/TextareaPrimitive'
-import { uuid } from 'lib/utils'
+import { uuid } from 'lib/utils/dom'
import { SidebarQuestionInput } from 'scenes/max/components/SidebarQuestionInput'
import { handsFreeLogic } from 'scenes/max/handsFreeLogic'
import { Intro } from 'scenes/max/Intro'
diff --git a/frontend/src/scenes/project-homepage/ai-first/HomepageThread.tsx b/frontend/src/scenes/project-homepage/ai-first/HomepageThread.tsx
index 085750263327..b1decb0a7571 100644
--- a/frontend/src/scenes/project-homepage/ai-first/HomepageThread.tsx
+++ b/frontend/src/scenes/project-homepage/ai-first/HomepageThread.tsx
@@ -2,7 +2,7 @@ import { BindLogic, useActions, useValues } from 'kea'
import { useEffect, useRef } from 'react'
import { ScrollableShadows } from 'lib/components/ScrollableShadows/ScrollableShadows'
-import { uuid } from 'lib/utils'
+import { uuid } from 'lib/utils/dom'
import { ThreadAutoScroller } from 'scenes/max/components/ThreadAutoScroller'
import { maxLogic } from 'scenes/max/maxLogic'
import { MaxThreadLogicProps, maxThreadLogic } from 'scenes/max/maxThreadLogic'
diff --git a/frontend/src/scenes/projectLogic.ts b/frontend/src/scenes/projectLogic.ts
index aeab0f91d553..7c67cc8f8fff 100644
--- a/frontend/src/scenes/projectLogic.ts
+++ b/frontend/src/scenes/projectLogic.ts
@@ -4,9 +4,10 @@ import { router } from 'kea-router'
import api, { ApiConfig } from 'lib/api'
import { lemonToast } from 'lib/lemon-ui/LemonToast'
-import { identifierToHuman, isUserLoggedIn } from 'lib/utils'
import { eventUsageLogic } from 'lib/utils/eventUsageLogic'
+import { isUserLoggedIn } from 'lib/utils/getAppContext'
import { getAppContext } from 'lib/utils/getAppContext'
+import { identifierToHuman } from 'lib/utils/strings'
import { ProjectType } from '~/types'
diff --git a/frontend/src/scenes/retention/RetentionGraph.tsx b/frontend/src/scenes/retention/RetentionGraph.tsx
index a4ad80fec042..549596563cc2 100644
--- a/frontend/src/scenes/retention/RetentionGraph.tsx
+++ b/frontend/src/scenes/retention/RetentionGraph.tsx
@@ -2,7 +2,7 @@ import { useActions, useValues } from 'kea'
import { FEATURE_FLAGS } from 'lib/constants'
import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
-import { roundToDecimal } from 'lib/utils'
+import { roundToDecimal } from 'lib/utils/numbers'
import { insightLogic } from 'scenes/insights/insightLogic'
import { TrendsFilter } from '~/queries/schema/schema-general'
diff --git a/frontend/src/scenes/retention/RetentionModal.tsx b/frontend/src/scenes/retention/RetentionModal.tsx
index cdee6e69acdc..1aec235fe04a 100644
--- a/frontend/src/scenes/retention/RetentionModal.tsx
+++ b/frontend/src/scenes/retention/RetentionModal.tsx
@@ -7,7 +7,9 @@ import { LemonButton, LemonModal } from '@posthog/lemon-ui'
import { exportsLogic } from 'lib/components/ExportButton/exportsLogic'
import { SpinnerOverlay } from 'lib/lemon-ui/Spinner/Spinner'
-import { capitalizeFirstLetter, isGroupType, percentage } from 'lib/utils'
+import { isGroupType } from 'lib/utils/guards'
+import { percentage } from 'lib/utils/numbers'
+import { capitalizeFirstLetter } from 'lib/utils/strings'
import { insightLogic } from 'scenes/insights/insightLogic'
import { groupDisplayId } from 'scenes/persons/GroupActorDisplay'
import { asDisplay } from 'scenes/persons/person-utils'
diff --git a/frontend/src/scenes/retention/RetentionTable.tsx b/frontend/src/scenes/retention/RetentionTable.tsx
index 57cb7b0a9d6b..0f7836cfb158 100644
--- a/frontend/src/scenes/retention/RetentionTable.tsx
+++ b/frontend/src/scenes/retention/RetentionTable.tsx
@@ -7,7 +7,8 @@ import React from 'react'
import { IconChevronDown, IconChevronRight } from '@posthog/icons'
import { Tooltip } from 'lib/lemon-ui/Tooltip'
-import { gradateColor, humanFriendlyNumber } from 'lib/utils'
+import { gradateColor } from 'lib/utils/colors'
+import { humanFriendlyNumber } from 'lib/utils/numbers'
import { insightLogic } from 'scenes/insights/insightLogic'
import { themeLogic } from '~/layout/navigation-3000/themeLogic'
diff --git a/frontend/src/scenes/retention/retentionLogic.ts b/frontend/src/scenes/retention/retentionLogic.ts
index 097d7c51458a..f9c5ef5cb1a3 100644
--- a/frontend/src/scenes/retention/retentionLogic.ts
+++ b/frontend/src/scenes/retention/retentionLogic.ts
@@ -5,7 +5,7 @@ import { CUSTOM_OPTION_KEY } from 'lib/components/DateFilter/types'
import { FEATURE_FLAGS } from 'lib/constants'
import { dayjs } from 'lib/dayjs'
import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
-import { formatDateRange } from 'lib/utils'
+import { formatDateRange } from 'lib/utils/datetime'
import { insightVizDataLogic } from 'scenes/insights/insightVizDataLogic'
import { keyForInsightLogicProps } from 'scenes/insights/sharedUtils'
import { BREAKDOWN_OTHER_DISPLAY, BREAKDOWN_OTHER_STRING_LABEL, formatBreakdownLabel } from 'scenes/insights/utils'
diff --git a/frontend/src/scenes/retention/retentionTableLogic.ts b/frontend/src/scenes/retention/retentionTableLogic.ts
index a5b3f35c4387..96925686a9f6 100644
--- a/frontend/src/scenes/retention/retentionTableLogic.ts
+++ b/frontend/src/scenes/retention/retentionTableLogic.ts
@@ -1,6 +1,6 @@
import { actions, afterMount, connect, kea, key, listeners, path, props, reducers, selectors } from 'kea'
-import { capitalizeFirstLetter } from 'lib/utils'
+import { capitalizeFirstLetter } from 'lib/utils/strings'
import { insightVizDataLogic } from 'scenes/insights/insightVizDataLogic'
import { keyForInsightLogicProps } from 'scenes/insights/sharedUtils'
diff --git a/frontend/src/scenes/saved-insights/SavedInsights.tsx b/frontend/src/scenes/saved-insights/SavedInsights.tsx
index d648c1e0308c..a82bc3afddca 100644
--- a/frontend/src/scenes/saved-insights/SavedInsights.tsx
+++ b/frontend/src/scenes/saved-insights/SavedInsights.tsx
@@ -56,11 +56,11 @@ import { LemonTag } from 'lib/lemon-ui/LemonTag'
import { ProfilePicture } from 'lib/lemon-ui/ProfilePicture'
import { Tooltip } from 'lib/lemon-ui/Tooltip'
import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
-import { isNonEmptyObject } from 'lib/utils'
import { accessLevelSatisfied } from 'lib/utils/accessControlUtils'
import { cn } from 'lib/utils/css-classes'
import { deleteInsightWithUndo } from 'lib/utils/deleteWithUndo'
import { eventUsageLogic } from 'lib/utils/eventUsageLogic'
+import { isNonEmptyObject } from 'lib/utils/guards'
import { SavedInsightsEmptyState } from 'scenes/insights/EmptyStates'
import { useSummarizeInsight } from 'scenes/insights/summarizeInsight'
import { INSIGHT_TYPE_URLS } from 'scenes/insights/utils'
diff --git a/frontend/src/scenes/saved-insights/SavedInsightsFilters.tsx b/frontend/src/scenes/saved-insights/SavedInsightsFilters.tsx
index 04ddff12455b..b95089d33416 100644
--- a/frontend/src/scenes/saved-insights/SavedInsightsFilters.tsx
+++ b/frontend/src/scenes/saved-insights/SavedInsightsFilters.tsx
@@ -10,8 +10,8 @@ import { LemonInput } from 'lib/lemon-ui/LemonInput/LemonInput'
import { LemonSelect } from 'lib/lemon-ui/LemonSelect'
import { LemonSwitch } from 'lib/lemon-ui/LemonSwitch'
import { Tooltip } from 'lib/lemon-ui/Tooltip'
-import { fullName } from 'lib/utils'
import { cn } from 'lib/utils/css-classes'
+import { fullName } from 'lib/utils/strings'
import { membersLogic } from 'scenes/organization/membersLogic'
import { INSIGHT_TYPE_OPTIONS } from 'scenes/saved-insights/SavedInsights'
import { SavedInsightFilters } from 'scenes/saved-insights/savedInsightsLogic'
diff --git a/frontend/src/scenes/saved-insights/activityDescriptions.tsx b/frontend/src/scenes/saved-insights/activityDescriptions.tsx
index 9d9380bdaa28..fd374b97c541 100644
--- a/frontend/src/scenes/saved-insights/activityDescriptions.tsx
+++ b/frontend/src/scenes/saved-insights/activityDescriptions.tsx
@@ -19,7 +19,8 @@ import {
} from 'lib/components/Cards/InsightCard/InsightDetails'
import { ObjectTags } from 'lib/components/ObjectTags/ObjectTags'
import { Link } from 'lib/lemon-ui/Link'
-import { areObjectValuesEmpty, pluralize } from 'lib/utils'
+import { areObjectValuesEmpty } from 'lib/utils/objects'
+import { pluralize } from 'lib/utils/strings'
import { urls } from 'scenes/urls'
import { filtersToQueryNode } from '~/queries/nodes/InsightQuery/utils/filtersToQueryNode'
diff --git a/frontend/src/scenes/saved-insights/addSavedInsightsModalLogic.ts b/frontend/src/scenes/saved-insights/addSavedInsightsModalLogic.ts
index 200f8d0a1b41..f8ce734c1b82 100644
--- a/frontend/src/scenes/saved-insights/addSavedInsightsModalLogic.ts
+++ b/frontend/src/scenes/saved-insights/addSavedInsightsModalLogic.ts
@@ -7,8 +7,9 @@ import { FEATURE_FLAGS } from 'lib/constants'
import { Sorting } from 'lib/lemon-ui/LemonTable'
import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'
import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
-import { objectsEqual, toParams } from 'lib/utils'
import { eventUsageLogic } from 'lib/utils/eventUsageLogic'
+import { objectsEqual } from 'lib/utils/objects'
+import { toParams } from 'lib/utils/url'
import { DashboardLoadAction, dashboardLogic } from 'scenes/dashboard/dashboardLogic'
import { insightsApi } from 'scenes/insights/utils/api'
import { teamLogic } from 'scenes/teamLogic'
diff --git a/frontend/src/scenes/saved-insights/savedInsightsLogic.ts b/frontend/src/scenes/saved-insights/savedInsightsLogic.ts
index a577638be925..e5af3d9f74db 100644
--- a/frontend/src/scenes/saved-insights/savedInsightsLogic.ts
+++ b/frontend/src/scenes/saved-insights/savedInsightsLogic.ts
@@ -9,8 +9,9 @@ import { Sorting } from 'lib/lemon-ui/LemonTable'
import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'
import { PaginationManual } from 'lib/lemon-ui/PaginationControl'
import { trackedActionToUrl } from 'lib/logic/scenes/trackedActionToUrl'
-import { objectDiffShallow, objectsEqual, toParams } from 'lib/utils'
import { eventUsageLogic } from 'lib/utils/eventUsageLogic'
+import { objectDiffShallow, objectsEqual } from 'lib/utils/objects'
+import { toParams } from 'lib/utils/url'
import { deleteDashboardLogic } from 'scenes/dashboard/deleteDashboardLogic'
import { duplicateDashboardLogic } from 'scenes/dashboard/duplicateDashboardLogic'
import { insightsApi } from 'scenes/insights/utils/api'
diff --git a/frontend/src/lib/utils/sceneLogicUtils.test.ts b/frontend/src/scenes/sceneLogic.test.ts
similarity index 98%
rename from frontend/src/lib/utils/sceneLogicUtils.test.ts
rename to frontend/src/scenes/sceneLogic.test.ts
index 8d59608b07f2..626bbbb4db08 100644
--- a/frontend/src/lib/utils/sceneLogicUtils.test.ts
+++ b/frontend/src/scenes/sceneLogic.test.ts
@@ -1,6 +1,6 @@
-import { withForwardedSearchParams } from './sceneLogicUtils'
+import { withForwardedSearchParams } from './sceneLogic'
-describe('sceneLogicUtils', () => {
+describe('sceneLogic', () => {
describe('withForwardedSearchParams', () => {
it('returns original URL when no params to forward', () => {
const redirectUrl = '/dashboard'
diff --git a/frontend/src/scenes/sceneLogic.test.tsx b/frontend/src/scenes/sceneLogic.test.tsx
index 000eb6a9400e..0b14d3f94088 100644
--- a/frontend/src/scenes/sceneLogic.test.tsx
+++ b/frontend/src/scenes/sceneLogic.test.tsx
@@ -4,7 +4,7 @@ import { expectLogic, partial, truth } from 'kea-test-utils'
import api from 'lib/api'
import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
-import { removeProjectIdIfPresent } from 'lib/utils/router-utils'
+import { removeProjectIdIfPresent } from 'lib/utils/kea-router'
import { Scene } from 'scenes/sceneTypes'
import { teamLogic } from 'scenes/teamLogic'
import { urls } from 'scenes/urls'
diff --git a/frontend/src/scenes/sceneLogic.tsx b/frontend/src/scenes/sceneLogic.tsx
index 708a2960e460..6de6fd1fcbc8 100644
--- a/frontend/src/scenes/sceneLogic.tsx
+++ b/frontend/src/scenes/sceneLogic.tsx
@@ -10,11 +10,11 @@ import { TeamMembershipLevel } from 'lib/constants'
import { trackFileSystemLogView } from 'lib/hooks/useFileSystemLogView'
import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'
import { Spinner } from 'lib/lemon-ui/Spinner'
-import { getRelativeNextPath, identifierToHuman } from 'lib/utils'
import { getAppContext } from 'lib/utils/getAppContext'
import { isChunkLoadError } from 'lib/utils/isChunkLoadError'
-import { addProjectIdIfMissing, removeProjectIdIfPresent, stripTrailingSlash } from 'lib/utils/router-utils'
-import { withForwardedSearchParams } from 'lib/utils/sceneLogicUtils'
+import { addProjectIdIfMissing, removeProjectIdIfPresent, stripTrailingSlash } from 'lib/utils/kea-router'
+import { identifierToHuman } from 'lib/utils/strings'
+import { getRelativeNextPath } from 'lib/utils/url'
import {
emptySceneParams,
forwardedRedirectQueryParams,
@@ -169,6 +169,44 @@ const restoreMainContentScrollTop = (scrollTop: number, onlyIfTabId?: string): v
})
}
+/**
+ * Forwards whitelisted query parameters from the current URL to the redirect URL.
+ * Only forwards params that exist in the current URL and don't already exist in the redirect URL.
+ * This is specifically used for scene redirects to maintain important query parameters across redirects.
+ */
+export function withForwardedSearchParams(
+ redirectUrl: string,
+ currentSearchParams: Params,
+ forwardedQueryParams: string[]
+): string {
+ // If no params to forward, return the original URL
+ if (!forwardedQueryParams?.length) {
+ return redirectUrl
+ }
+
+ const redirectUrlObj = new URL(redirectUrl, window.location.origin)
+ const redirectSearchParams = new URLSearchParams(redirectUrlObj.search)
+ let paramsWereForwarded = false
+
+ // For each whitelisted param that exists in current URL
+ forwardedQueryParams.forEach((param) => {
+ if (currentSearchParams[param] !== undefined && !redirectSearchParams.has(param)) {
+ redirectSearchParams.set(param, currentSearchParams[param])
+ paramsWereForwarded = true
+ }
+ })
+
+ // Only modify the URL if we actually forwarded any params
+ if (!paramsWereForwarded) {
+ return redirectUrl
+ }
+
+ // Reconstruct the URL with the forwarded params
+ redirectUrlObj.search = redirectSearchParams.toString()
+ // Return just the pathname and search to avoid origin being included
+ return redirectUrlObj.pathname + redirectUrlObj.search + redirectUrlObj.hash
+}
+
export const sceneLogic = kea<sceneLogicType>([
props(
{} as {
diff --git a/frontend/src/scenes/session-recordings/apm/NetworkView.stories.tsx b/frontend/src/scenes/session-recordings/apm/NetworkView.stories.tsx
index 1d4bb493cd0d..e131a80828a3 100644
--- a/frontend/src/scenes/session-recordings/apm/NetworkView.stories.tsx
+++ b/frontend/src/scenes/session-recordings/apm/NetworkView.stories.tsx
@@ -6,7 +6,7 @@ import { useCallback, useRef, useState } from 'react'
import { LemonTable } from '@posthog/lemon-ui'
import { Tooltip } from 'lib/lemon-ui/Tooltip'
-import { humanFriendlyMilliseconds } from 'lib/utils'
+import { humanFriendlyMilliseconds } from 'lib/utils/durations'
import { initiatorTypeToColor } from 'scenes/session-recordings/apm/performance-event-utils'
import { MethodTag, StatusTag } from 'scenes/session-recordings/apm/playerInspector/ItemPerformanceEvent'
diff --git a/frontend/src/scenes/session-recordings/apm/components/AssetProportions.tsx b/frontend/src/scenes/session-recordings/apm/components/AssetProportions.tsx
index f7335ac5c7ae..ca3e33a77a4d 100644
--- a/frontend/src/scenes/session-recordings/apm/components/AssetProportions.tsx
+++ b/frontend/src/scenes/session-recordings/apm/components/AssetProportions.tsx
@@ -1,7 +1,7 @@
import { Tooltip } from '@posthog/lemon-ui'
import { useResizeBreakpoints } from 'lib/hooks/useResizeObserver'
-import { humanizeBytes } from 'lib/utils'
+import { humanizeBytes } from 'lib/utils/numbers'
import { assetTypeToColor } from 'scenes/session-recordings/apm/performance-event-utils'
import { AssetSizeInfo } from 'scenes/session-recordings/apm/performanceEventDataLogic'
diff --git a/frontend/src/scenes/session-recordings/apm/components/PerformanceCard.tsx b/frontend/src/scenes/session-recordings/apm/components/PerformanceCard.tsx
index b71f20d8a7f3..7166f73c8af8 100644
--- a/frontend/src/scenes/session-recordings/apm/components/PerformanceCard.tsx
+++ b/frontend/src/scenes/session-recordings/apm/components/PerformanceCard.tsx
@@ -2,7 +2,7 @@ import clsx from 'clsx'
import { Link } from 'lib/lemon-ui/Link'
import { Spinner } from 'lib/lemon-ui/Spinner'
-import { humanFriendlyMilliseconds } from 'lib/utils'
+import { humanFriendlyMilliseconds } from 'lib/utils/durations'
import { PerformanceEvent, RecordingEventType } from '~/types'
diff --git a/frontend/src/scenes/session-recordings/apm/networkViewLogic.ts b/frontend/src/scenes/session-recordings/apm/networkViewLogic.ts
index f49c96d29ee3..6e259d8e5198 100644
--- a/frontend/src/scenes/session-recordings/apm/networkViewLogic.ts
+++ b/frontend/src/scenes/session-recordings/apm/networkViewLogic.ts
@@ -1,7 +1,7 @@
import { actions, afterMount, connect, kea, key, path, props, reducers, selectors } from 'kea'
import { Dayjs, dayjs } from 'lib/dayjs'
-import { humanFriendlyMilliseconds } from 'lib/utils'
+import { humanFriendlyMilliseconds } from 'lib/utils/durations'
import { performanceEventDataLogic } from 'scenes/session-recordings/apm/performanceEventDataLogic'
import { percentagesWithinEventRange } from 'scenes/session-recordings/apm/waterfall/TimingBar'
import {
diff --git a/frontend/src/scenes/session-recordings/apm/performance-event-utils.ts b/frontend/src/scenes/session-recordings/apm/performance-event-utils.ts
index e2a6706f76a3..7cce204368dd 100644
--- a/frontend/src/scenes/session-recordings/apm/performance-event-utils.ts
+++ b/frontend/src/scenes/session-recordings/apm/performance-event-utils.ts
@@ -2,7 +2,8 @@ import { CapturedNetworkRequest } from 'posthog-js'
import { eventWithTime } from 'posthog-js/rrweb-types'
import { getSeriesBackgroundColor, getSeriesColor } from 'lib/colors'
-import { assignField, humanizeBytes, isKeyOf } from 'lib/utils'
+import { assignField, isKeyOf } from 'lib/utils/guards'
+import { humanizeBytes } from 'lib/utils/numbers'
import { PerformanceEvent } from '~/types'
diff --git a/frontend/src/scenes/session-recordings/apm/playerInspector/ItemPerformanceEvent.tsx b/frontend/src/scenes/session-recordings/apm/playerInspector/ItemPerformanceEvent.tsx
index 9297652176fe..2f3a62b6705d 100644
--- a/frontend/src/scenes/session-recordings/apm/playerInspector/ItemPerformanceEvent.tsx
+++ b/frontend/src/scenes/session-recordings/apm/playerInspector/ItemPerformanceEvent.tsx
@@ -7,7 +7,9 @@ import { LemonDivider, LemonTabs, LemonTag, LemonTagType, Link } from '@posthog/
import { CodeSnippet, Language } from 'lib/components/CodeSnippet'
import { SimpleKeyValueList } from 'lib/components/SimpleKeyValueList'
import { Dayjs, dayjs } from 'lib/dayjs'
-import { humanFriendlyMilliseconds, isURL, isKeyOf } from 'lib/utils'
+import { humanFriendlyMilliseconds } from 'lib/utils/durations'
+import { isKeyOf } from 'lib/utils/guards'
+import { isURL } from 'lib/utils/url'
import { PerformanceEventSizeInfo, itemSizeInfo } from 'scenes/session-recordings/apm/performance-event-utils'
import { NavigationItem } from 'scenes/session-recordings/player/inspector/components/NavigationItem'
import { PerformanceEventLabel } from 'scenes/session-recordings/player/inspector/components/PerformanceEventLabel'
diff --git a/frontend/src/scenes/session-recordings/apm/waterfall/TimingBar.tsx b/frontend/src/scenes/session-recordings/apm/waterfall/TimingBar.tsx
index 334f8a553053..b56da99d8487 100644
--- a/frontend/src/scenes/session-recordings/apm/waterfall/TimingBar.tsx
+++ b/frontend/src/scenes/session-recordings/apm/waterfall/TimingBar.tsx
@@ -1,6 +1,6 @@
import { getSeriesColor } from 'lib/colors'
import { Tooltip } from 'lib/lemon-ui/Tooltip'
-import { humanFriendlyMilliseconds } from 'lib/utils'
+import { humanFriendlyMilliseconds } from 'lib/utils/durations'
import { PerformanceEvent } from '~/types'
diff --git a/frontend/src/scenes/session-recordings/collections/SessionRecordingCollections.tsx b/frontend/src/scenes/session-recordings/collections/SessionRecordingCollections.tsx
index 015d1b4308fa..305494857fdd 100644
--- a/frontend/src/scenes/session-recordings/collections/SessionRecordingCollections.tsx
+++ b/frontend/src/scenes/session-recordings/collections/SessionRecordingCollections.tsx
@@ -20,7 +20,7 @@ import { TZLabel } from 'lib/components/TZLabel'
import { More } from 'lib/lemon-ui/LemonButton/More'
import { LemonTableColumn, LemonTableColumns } from 'lib/lemon-ui/LemonTable'
import { createdByColumn } from 'lib/lemon-ui/LemonTable/columnUtils'
-import { isObject } from 'lib/utils'
+import { isObject } from 'lib/utils/guards'
import { urls } from 'scenes/urls'
import {
diff --git a/frontend/src/scenes/session-recordings/collections/sessionRecordingCollectionsLogic.ts b/frontend/src/scenes/session-recordings/collections/sessionRecordingCollectionsLogic.ts
index b4bf6027fa05..5d2232d00bf9 100644
--- a/frontend/src/scenes/session-recordings/collections/sessionRecordingCollectionsLogic.ts
+++ b/frontend/src/scenes/session-recordings/collections/sessionRecordingCollectionsLogic.ts
@@ -7,8 +7,9 @@ import { lemonToast } from '@posthog/lemon-ui'
import api from 'lib/api'
import { Sorting } from 'lib/lemon-ui/LemonTable'
import { PaginationManual } from 'lib/lemon-ui/PaginationControl'
-import { objectClean, objectsEqual, toParams } from 'lib/utils'
-import { removeProjectIdIfPresent } from 'lib/utils/router-utils'
+import { removeProjectIdIfPresent } from 'lib/utils/kea-router'
+import { objectClean, objectsEqual } from 'lib/utils/objects'
+import { toParams } from 'lib/utils/url'
import { sessionRecordingEventUsageLogic } from 'scenes/session-recordings/sessionRecordingEventUsageLogic'
import { urls } from 'scenes/urls'
diff --git a/frontend/src/scenes/session-recordings/components/ItemTimeDisplay.tsx b/frontend/src/scenes/session-recordings/components/ItemTimeDisplay.tsx
index 31d80b58a64e..c446d4c71cec 100644
--- a/frontend/src/scenes/session-recordings/components/ItemTimeDisplay.tsx
+++ b/frontend/src/scenes/session-recordings/components/ItemTimeDisplay.tsx
@@ -2,9 +2,9 @@ import { useValues } from 'kea'
import { Dayjs } from 'lib/dayjs'
import { Tooltip } from 'lib/lemon-ui/Tooltip'
-import { colonDelimitedDuration } from 'lib/utils'
import { cn } from 'lib/utils/css-classes'
-import { formatLocalizedDate } from 'lib/utils/dateTimeUtils'
+import { formatLocalizedDate } from 'lib/utils/datetime'
+import { colonDelimitedDuration } from 'lib/utils/durations'
import { TimestampFormat } from '../player/playerSettingsLogic'
import { playerSettingsLogic } from '../player/playerSettingsLogic'
diff --git a/frontend/src/scenes/session-recordings/components/RecordingRow.tsx b/frontend/src/scenes/session-recordings/components/RecordingRow.tsx
index 39f83be72bfc..fa9b3456019c 100644
--- a/frontend/src/scenes/session-recordings/components/RecordingRow.tsx
+++ b/frontend/src/scenes/session-recordings/components/RecordingRow.tsx
@@ -4,7 +4,7 @@ import { useActions } from 'kea'
import { IconPlayCircle } from 'lib/lemon-ui/icons'
import { LemonSnack } from 'lib/lemon-ui/LemonSnack'
import { ProfilePicture } from 'lib/lemon-ui/ProfilePicture'
-import { humanFriendlyDuration } from 'lib/utils'
+import { humanFriendlyDuration } from 'lib/utils/durations'
import { asDisplay } from 'scenes/persons/person-utils'
import { sessionPlayerModalLogic } from 'scenes/session-recordings/player/modal/sessionPlayerModalLogic'
import { sessionRecordingEventUsageLogic } from 'scenes/session-recordings/sessionRecordingEventUsageLogic'
diff --git a/frontend/src/scenes/session-recordings/components/SimpleTimeLabel.tsx b/frontend/src/scenes/session-recordings/components/SimpleTimeLabel.tsx
index 271d12308b52..fff38d3ccf3c 100644
--- a/frontend/src/scenes/session-recordings/components/SimpleTimeLabel.tsx
+++ b/frontend/src/scenes/session-recordings/components/SimpleTimeLabel.tsx
@@ -2,8 +2,8 @@ import clsx from 'clsx'
import { memo } from 'react'
import { Dayjs, dayjs } from 'lib/dayjs'
-import { shortTimeZone } from 'lib/utils'
-import { formatLocalizedDate } from 'lib/utils/dateTimeUtils'
+import { formatLocalizedDate } from 'lib/utils/datetime'
+import { shortTimeZone } from 'lib/utils/timezones'
import { TimestampFormat } from 'scenes/session-recordings/player/playerSettingsLogic'
function formattedReplayTime(
diff --git a/frontend/src/scenes/session-recordings/file-playback/sessionRecordingFilePlaybackSceneLogic.ts b/frontend/src/scenes/session-recordings/file-playback/sessionRecordingFilePlaybackSceneLogic.ts
index b775eb5cf20c..fbcbcaedc2e6 100644
--- a/frontend/src/scenes/session-recordings/file-playback/sessionRecordingFilePlaybackSceneLogic.ts
+++ b/frontend/src/scenes/session-recordings/file-playback/sessionRecordingFilePlaybackSceneLogic.ts
@@ -6,7 +6,7 @@ import { lemonToast } from '@posthog/lemon-ui'
import { createWindowIdRegistry } from '@posthog/replay-shared'
import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
-import { uuid } from 'lib/utils'
+import { uuid } from 'lib/utils/dom'
import { Scene } from 'scenes/sceneTypes'
import { urls } from 'scenes/urls'
diff --git a/frontend/src/scenes/session-recordings/filters/SavedFilters.tsx b/frontend/src/scenes/session-recordings/filters/SavedFilters.tsx
index 143c5a85f16f..e2cd05bbf85c 100644
--- a/frontend/src/scenes/session-recordings/filters/SavedFilters.tsx
+++ b/frontend/src/scenes/session-recordings/filters/SavedFilters.tsx
@@ -15,8 +15,8 @@ import {
import { AccessControlAction } from 'lib/components/AccessControlAction'
import { TZLabel } from 'lib/components/TZLabel'
import { IconArrowUp } from 'lib/lemon-ui/icons'
-import { isObject } from 'lib/utils'
import { copyToClipboard } from 'lib/utils/copyToClipboard'
+import { isObject } from 'lib/utils/guards'
import { urls } from 'scenes/urls'
import {
diff --git a/frontend/src/scenes/session-recordings/filters/recordingsQueryConversions.ts b/frontend/src/scenes/session-recordings/filters/recordingsQueryConversions.ts
index 65b3a87d809e..5de2aa8428fc 100644
--- a/frontend/src/scenes/session-recordings/filters/recordingsQueryConversions.ts
+++ b/frontend/src/scenes/session-recordings/filters/recordingsQueryConversions.ts
@@ -9,7 +9,7 @@ import {
isLogEntryPropertyFilter,
isRecordingPropertyFilter,
} from 'lib/components/UniversalFilters/utils'
-import { isString } from 'lib/utils'
+import { isString } from 'lib/utils/guards'
import { NodeKind, RecordingOrder, RecordingsQuery, VALID_RECORDING_ORDERS } from '~/queries/schema/schema-general'
import {
diff --git a/frontend/src/scenes/session-recordings/filters/sessionRecordingSavedFiltersLogic.ts b/frontend/src/scenes/session-recordings/filters/sessionRecordingSavedFiltersLogic.ts
index 1ae71cfe5075..b8bd318a16a4 100644
--- a/frontend/src/scenes/session-recordings/filters/sessionRecordingSavedFiltersLogic.ts
+++ b/frontend/src/scenes/session-recordings/filters/sessionRecordingSavedFiltersLogic.ts
@@ -4,7 +4,8 @@ import { router } from 'kea-router'
import api from 'lib/api'
import { PaginationManual } from 'lib/lemon-ui/PaginationControl'
-import { objectClean, toParams } from 'lib/utils'
+import { objectClean } from 'lib/utils/objects'
+import { toParams } from 'lib/utils/url'
import { sessionRecordingEventUsageLogic } from 'scenes/session-recordings/sessionRecordingEventUsageLogic'
import { urls } from 'scenes/urls'
diff --git a/frontend/src/scenes/session-recordings/player/PlayerSidebar.tsx b/frontend/src/scenes/session-recordings/player/PlayerSidebar.tsx
index 3c0b46bf070b..179523fa8e75 100644
--- a/frontend/src/scenes/session-recordings/player/PlayerSidebar.tsx
+++ b/frontend/src/scenes/session-recordings/player/PlayerSidebar.tsx
@@ -8,7 +8,7 @@ import { LemonButton, LemonTabs } from '@posthog/lemon-ui'
import { Resizer } from 'lib/components/Resizer/Resizer'
import { ResizerLogicProps, resizerLogic } from 'lib/components/Resizer/resizerLogic'
import { integrationsLogic } from 'lib/integrations/integrationsLogic'
-import { capitalizeFirstLetter, splitKebabCase } from 'lib/utils'
+import { capitalizeFirstLetter, splitKebabCase } from 'lib/utils/strings'
import { SessionRecordingSidebarStacking, SessionRecordingSidebarTab } from '~/types'
diff --git a/frontend/src/scenes/session-recordings/player/commenting/playerFrameCommentOverlayLogic.ts b/frontend/src/scenes/session-recordings/player/commenting/playerFrameCommentOverlayLogic.ts
index b43cc2e93bae..7f7519fac6d4 100644
--- a/frontend/src/scenes/session-recordings/player/commenting/playerFrameCommentOverlayLogic.ts
+++ b/frontend/src/scenes/session-recordings/player/commenting/playerFrameCommentOverlayLogic.ts
@@ -6,7 +6,7 @@ import api from 'lib/api'
import { JSONContent, RichContentEditorType } from 'lib/components/RichContentEditor/types'
import { Dayjs, dayjs } from 'lib/dayjs'
import { lemonToast } from 'lib/lemon-ui/LemonToast'
-import { colonDelimitedDuration } from 'lib/utils'
+import { colonDelimitedDuration } from 'lib/utils/durations'
import { membersLogic } from 'scenes/organization/membersLogic'
import { playerCommentModel } from 'scenes/session-recordings/player/commenting/playerCommentModel'
import { isSingleEmoji } from 'scenes/session-recordings/utils'
diff --git a/frontend/src/scenes/session-recordings/player/controller/ClipRecording.tsx b/frontend/src/scenes/session-recordings/player/controller/ClipRecording.tsx
index f9693d2a4664..d9dccea26fc4 100644
--- a/frontend/src/scenes/session-recordings/player/controller/ClipRecording.tsx
+++ b/frontend/src/scenes/session-recordings/player/controller/ClipRecording.tsx
@@ -5,8 +5,8 @@ import { LemonButton, LemonSegmentedButton } from '@posthog/lemon-ui'
import { IconRecordingClip } from 'lib/lemon-ui/icons'
import { LemonSegmentedSelect } from 'lib/lemon-ui/LemonSegmentedSelect'
-import { colonDelimitedDuration } from 'lib/utils'
import { cn } from 'lib/utils/css-classes'
+import { colonDelimitedDuration } from 'lib/utils/durations'
import { sessionRecordingPlayerLogic } from 'scenes/session-recordings/player/sessionRecordingPlayerLogic'
import { KeyboardShortcut } from '~/layout/navigation-3000/components/KeyboardShortcut'
diff --git a/frontend/src/scenes/session-recordings/player/controller/PlayerControllerTime.tsx b/frontend/src/scenes/session-recordings/player/controller/PlayerControllerTime.tsx
index db80b47a7096..083dc3b3855a 100644
--- a/frontend/src/scenes/session-recordings/player/controller/PlayerControllerTime.tsx
+++ b/frontend/src/scenes/session-recordings/player/controller/PlayerControllerTime.tsx
@@ -7,9 +7,11 @@ import { LemonButton, LemonButtonProps, Tooltip } from '@posthog/lemon-ui'
import { Dayjs, dayjs } from 'lib/dayjs'
import { useKeyHeld } from 'lib/hooks/useKeyHeld'
import { IconSkipBackward } from 'lib/lemon-ui/icons'
-import { capitalizeFirstLetter, colonDelimitedDuration, shortTimeZone } from 'lib/utils'
import { cn } from 'lib/utils/css-classes'
-import { formatLocalizedDate } from 'lib/utils/dateTimeUtils'
+import { formatLocalizedDate } from 'lib/utils/datetime'
+import { colonDelimitedDuration } from 'lib/utils/durations'
+import { capitalizeFirstLetter } from 'lib/utils/strings'
+import { shortTimeZone } from 'lib/utils/timezones'
import { SimpleTimeLabel } from 'scenes/session-recordings/components/SimpleTimeLabel'
import {
ONE_SECOND_MS,
diff --git a/frontend/src/scenes/session-recordings/player/controller/PlayerSeekbarPreview.tsx b/frontend/src/scenes/session-recordings/player/controller/PlayerSeekbarPreview.tsx
index df541701de9d..ee47e3e6ac09 100644
--- a/frontend/src/scenes/session-recordings/player/controller/PlayerSeekbarPreview.tsx
+++ b/frontend/src/scenes/session-recordings/player/controller/PlayerSeekbarPreview.tsx
@@ -4,8 +4,8 @@ import { useDebouncedCallback } from 'use-debounce'
import { Dayjs } from 'lib/dayjs'
import useIsHovering from 'lib/hooks/useIsHovering'
-import { colonDelimitedDuration } from 'lib/utils'
import { cn } from 'lib/utils/css-classes'
+import { colonDelimitedDuration } from 'lib/utils/durations'
import { PlayerFrame } from '../PlayerFrame'
import { TimestampFormat } from '../playerSettingsLogic'
diff --git a/frontend/src/scenes/session-recordings/player/controller/PlayerSeekbarTicks.tsx b/frontend/src/scenes/session-recordings/player/controller/PlayerSeekbarTicks.tsx
index c1975650c1a6..4d91063e9888 100644
--- a/frontend/src/scenes/session-recordings/player/controller/PlayerSeekbarTicks.tsx
+++ b/frontend/src/scenes/session-recordings/player/controller/PlayerSeekbarTicks.tsx
@@ -11,8 +11,8 @@ import { TaxonomicFilterGroupType } from 'lib/components/TaxonomicFilter/types'
import { RichContentPreview } from 'lib/lemon-ui/LemonRichContent/LemonRichContentEditor'
import { ProfilePicture } from 'lib/lemon-ui/ProfilePicture'
import { Tooltip } from 'lib/lemon-ui/Tooltip'
-import { autoCaptureEventToDescription } from 'lib/utils'
-import { getPrimaryPropertyForEvent } from 'lib/utils/primaryEventProperty'
+import { autoCaptureEventToDescription } from 'lib/utils/events'
+import { getPrimaryPropertyForEvent } from 'lib/utils/events'
import {
InspectorListItem,
InspectorListItemComment,
diff --git a/frontend/src/scenes/session-recordings/player/controller/seekbarLogic.ts b/frontend/src/scenes/session-recordings/player/controller/seekbarLogic.ts
index 5d91ac10797e..3a2286ab999a 100644
--- a/frontend/src/scenes/session-recordings/player/controller/seekbarLogic.ts
+++ b/frontend/src/scenes/session-recordings/player/controller/seekbarLogic.ts
@@ -1,7 +1,7 @@
import { actions, connect, kea, key, listeners, path, props, reducers, selectors } from 'kea'
import { MutableRefObject } from 'react'
-import { clamp } from 'lib/utils'
+import { clamp } from 'lib/utils/numbers'
import {
SessionRecordingPlayerLogicProps,
sessionRecordingPlayerLogic,
diff --git a/frontend/src/scenes/session-recordings/player/inspector/PlayerInspectorControls.tsx b/frontend/src/scenes/session-recordings/player/inspector/PlayerInspectorControls.tsx
index dc4ea136072a..341342b15d71 100644
--- a/frontend/src/scenes/session-recordings/player/inspector/PlayerInspectorControls.tsx
+++ b/frontend/src/scenes/session-recordings/player/inspector/PlayerInspectorControls.tsx
@@ -19,7 +19,7 @@ import { LemonButton, LemonInput, SideAction, Tooltip } from '@posthog/lemon-ui'
import { FEATURE_FLAGS } from 'lib/constants'
import { IconUnverifiedEvent } from 'lib/lemon-ui/icons'
import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
-import { capitalizeFirstLetter } from 'lib/utils'
+import { capitalizeFirstLetter } from 'lib/utils/strings'
import { SettingsBar, SettingsButton, SettingsToggle } from 'scenes/session-recordings/components/PanelSettings'
import { SharedListMiniFilter, miniFiltersLogic } from 'scenes/session-recordings/player/inspector/miniFiltersLogic'
import {
diff --git a/frontend/src/scenes/session-recordings/player/inspector/components/AIEventItems.tsx b/frontend/src/scenes/session-recordings/player/inspector/components/AIEventItems.tsx
index 5b38b9a04a44..e68761744962 100644
--- a/frontend/src/scenes/session-recordings/player/inspector/components/AIEventItems.tsx
+++ b/frontend/src/scenes/session-recordings/player/inspector/components/AIEventItems.tsx
@@ -1,7 +1,7 @@
import { JSONViewer } from 'lib/components/JSONViewer'
import { IconExclamation } from 'lib/lemon-ui/icons'
-import { isObject } from 'lib/utils'
import { cn } from 'lib/utils/css-classes'
+import { isObject } from 'lib/utils/guards'
import { AIDataLoading } from 'products/ai_observability/frontend/components/AIDataLoading'
import { ConversationMessagesDisplay } from 'products/ai_observability/frontend/ConversationDisplay/ConversationMessagesDisplay'
diff --git a/frontend/src/scenes/session-recordings/player/inspector/components/ItemConsoleLog.tsx b/frontend/src/scenes/session-recordings/player/inspector/components/ItemConsoleLog.tsx
index 72ab78906867..d93a51da2633 100644
--- a/frontend/src/scenes/session-recordings/player/inspector/components/ItemConsoleLog.tsx
+++ b/frontend/src/scenes/session-recordings/player/inspector/components/ItemConsoleLog.tsx
@@ -7,7 +7,7 @@ import { CodeSnippet, Language } from 'lib/components/CodeSnippet'
import { SimpleKeyValueList } from 'lib/components/SimpleKeyValueList'
import { LemonLabel } from 'lib/lemon-ui/LemonLabel/LemonLabel'
import { Tooltip } from 'lib/lemon-ui/Tooltip'
-import { ceilMsToClosestSecond } from 'lib/utils'
+import { ceilMsToClosestSecond } from 'lib/utils/durations'
import { ItemTimeDisplay } from '../../../components/ItemTimeDisplay'
import { sessionRecordingPlayerLogic } from '../../sessionRecordingPlayerLogic'
diff --git a/frontend/src/scenes/session-recordings/player/inspector/components/ItemEvent.stories.tsx b/frontend/src/scenes/session-recordings/player/inspector/components/ItemEvent.stories.tsx
index 3dd1186c0978..3eb25f17b2d3 100644
--- a/frontend/src/scenes/session-recordings/player/inspector/components/ItemEvent.stories.tsx
+++ b/frontend/src/scenes/session-recordings/player/inspector/components/ItemEvent.stories.tsx
@@ -2,7 +2,7 @@ import type { Meta, StoryObj } from '@storybook/react'
import { dayjs } from 'lib/dayjs'
import { LemonDivider } from 'lib/lemon-ui/LemonDivider'
-import { uuid } from 'lib/utils'
+import { uuid } from 'lib/utils/dom'
import {
ItemEvent,
ItemEventDetail,
diff --git a/frontend/src/scenes/session-recordings/player/inspector/components/ItemEvent.tsx b/frontend/src/scenes/session-recordings/player/inspector/components/ItemEvent.tsx
index aa920c032c9c..879edf48e329 100644
--- a/frontend/src/scenes/session-recordings/player/inspector/components/ItemEvent.tsx
+++ b/frontend/src/scenes/session-recordings/player/inspector/components/ItemEvent.tsx
@@ -5,6 +5,7 @@ import { useEffect, useState } from 'react'
import { IconCollapse, IconExpand, IconShare } from '@posthog/icons'
import { LemonButton, LemonMenu, Link } from '@posthog/lemon-ui'
+import { AutocapturePreviewImage } from 'lib/components/AutocapturePreviewImage/AutocapturePreviewImage'
import { ErrorDisplay, idFrom } from 'lib/components/Errors/ErrorDisplay'
import { ErrorEventType } from 'lib/components/Errors/types'
import { getExceptionAttributes } from 'lib/components/Errors/utils'
@@ -17,9 +18,11 @@ import { FEATURE_FLAGS } from 'lib/constants'
import { IconOpenInNew } from 'lib/lemon-ui/icons'
import { Spinner } from 'lib/lemon-ui/Spinner'
import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
-import { autoCaptureEventToDescription, capitalizeFirstLetter, ceilMsToClosestSecond, isString } from 'lib/utils'
-import { AutocapturePreviewImage } from 'lib/utils/autocapture-previews'
-import { getPrimaryPropertyForEvent } from 'lib/utils/primaryEventProperty'
+import { ceilMsToClosestSecond } from 'lib/utils/durations'
+import { autoCaptureEventToDescription } from 'lib/utils/events'
+import { getPrimaryPropertyForEvent } from 'lib/utils/events'
+import { isString } from 'lib/utils/guards'
+import { capitalizeFirstLetter } from 'lib/utils/strings'
import { insightUrlForEvent } from 'scenes/insights/utils'
import { urls } from 'scenes/urls'
diff --git a/frontend/src/scenes/session-recordings/player/inspector/components/ItemInactivity.tsx b/frontend/src/scenes/session-recordings/player/inspector/components/ItemInactivity.tsx
index c22ae5574f86..e9b8c575164f 100644
--- a/frontend/src/scenes/session-recordings/player/inspector/components/ItemInactivity.tsx
+++ b/frontend/src/scenes/session-recordings/player/inspector/components/ItemInactivity.tsx
@@ -1,7 +1,7 @@
import { IconClock } from '@posthog/icons'
import { LemonDivider } from 'lib/lemon-ui/LemonDivider'
-import { humanFriendlyDuration } from 'lib/utils'
+import { humanFriendlyDuration } from 'lib/utils/durations'
import { InspectorListItemInactivity } from 'scenes/session-recordings/player/inspector/playerInspectorLogic'
export function ItemInactivity({ item }: { item: InspectorListItemInactivity }): JSX.Element {
diff --git a/frontend/src/scenes/session-recordings/player/inspector/components/ItemLog.stories.tsx b/frontend/src/scenes/session-recordings/player/inspector/components/ItemLog.stories.tsx
index c3a1c3c42b1d..eae7e5c61342 100644
--- a/frontend/src/scenes/session-recordings/player/inspector/components/ItemLog.stories.tsx
+++ b/frontend/src/scenes/session-recordings/player/inspector/components/ItemLog.stories.tsx
@@ -3,7 +3,7 @@ import { BindLogic } from 'kea'
import { dayjs } from 'lib/dayjs'
import { LemonDivider } from 'lib/lemon-ui/LemonDivider'
-import { uuid } from 'lib/utils'
+import { uuid } from 'lib/utils/dom'
import { sessionRecordingPlayerLogic } from 'scenes/session-recordings/player/sessionRecordingPlayerLogic'
import { mswDecorator } from '~/mocks/browser'
diff --git a/frontend/src/scenes/session-recordings/player/inspector/components/ItemSummary.tsx b/frontend/src/scenes/session-recordings/player/inspector/components/ItemSummary.tsx
index 9df4de305fbb..f479e8396437 100644
--- a/frontend/src/scenes/session-recordings/player/inspector/components/ItemSummary.tsx
+++ b/frontend/src/scenes/session-recordings/player/inspector/components/ItemSummary.tsx
@@ -3,7 +3,7 @@ import clsx from 'clsx'
import { IconCursor, IconKeyboard, IconWarning } from '@posthog/icons'
import { Tooltip } from '@posthog/lemon-ui'
-import { pluralize } from 'lib/utils'
+import { pluralize } from 'lib/utils/strings'
import { InspectorListItemSummary } from '../playerInspectorLogic'
diff --git a/frontend/src/scenes/session-recordings/player/inspector/components/PinPrimaryPropertyButton.test.tsx b/frontend/src/scenes/session-recordings/player/inspector/components/PinPrimaryPropertyButton.test.tsx
index 2d673cb46b86..17866b967819 100644
--- a/frontend/src/scenes/session-recordings/player/inspector/components/PinPrimaryPropertyButton.test.tsx
+++ b/frontend/src/scenes/session-recordings/player/inspector/components/PinPrimaryPropertyButton.test.tsx
@@ -3,7 +3,7 @@ import '@testing-library/jest-dom'
import { cleanup, render } from '@testing-library/react'
import { Provider } from 'kea'
-import { getPrimaryPropertyForEvent } from 'lib/utils/primaryEventProperty'
+import { getPrimaryPropertyForEvent } from 'lib/utils/events'
import { primaryEventPropertiesModel } from '~/models/primaryEventPropertiesModel'
import { initKeaTests } from '~/test/init'
diff --git a/frontend/src/scenes/session-recordings/player/inspector/components/PinPrimaryPropertyButton.tsx b/frontend/src/scenes/session-recordings/player/inspector/components/PinPrimaryPropertyButton.tsx
index 85762cad95bf..842505ca6afd 100644
--- a/frontend/src/scenes/session-recordings/player/inspector/components/PinPrimaryPropertyButton.tsx
+++ b/frontend/src/scenes/session-recordings/player/inspector/components/PinPrimaryPropertyButton.tsx
@@ -3,7 +3,7 @@ import { useActions, useValues } from 'kea'
import { IconPin, IconPinFilled } from '@posthog/icons'
import { LemonButton } from '@posthog/lemon-ui'
-import { getPrimaryPropertyForEvent, hasTaxonomyPrimaryProperty } from 'lib/utils/primaryEventProperty'
+import { getPrimaryPropertyForEvent, hasTaxonomyPrimaryProperty } from 'lib/utils/events'
import { primaryEventPropertiesModel } from '~/models/primaryEventPropertiesModel'
diff --git a/frontend/src/scenes/session-recordings/player/inspector/components/PlayerInspectorListItem.tsx b/frontend/src/scenes/session-recordings/player/inspector/components/PlayerInspectorListItem.tsx
index dee78aa3c407..b1b79317b5a1 100644
--- a/frontend/src/scenes/session-recordings/player/inspector/components/PlayerInspectorListItem.tsx
+++ b/frontend/src/scenes/session-recordings/player/inspector/components/PlayerInspectorListItem.tsx
@@ -25,7 +25,8 @@ import { LemonButton, LemonDivider } from '@posthog/lemon-ui'
import { Dayjs } from 'lib/dayjs'
import useIsHovering from 'lib/hooks/useIsHovering'
import { Tooltip } from 'lib/lemon-ui/Tooltip'
-import { ceilMsToClosestSecond, objectsEqual } from 'lib/utils'
+import { ceilMsToClosestSecond } from 'lib/utils/durations'
+import { objectsEqual } from 'lib/utils/objects'
import { ItemTimeDisplay } from 'scenes/session-recordings/components/ItemTimeDisplay'
import {
ItemAnyComment,
diff --git a/frontend/src/scenes/session-recordings/player/inspector/playerInspectorLogic.ts b/frontend/src/scenes/session-recordings/player/inspector/playerInspectorLogic.ts
index 5f9bc07a07be..94e25e54990b 100644
--- a/frontend/src/scenes/session-recordings/player/inspector/playerInspectorLogic.ts
+++ b/frontend/src/scenes/session-recordings/player/inspector/playerInspectorLogic.ts
@@ -15,8 +15,11 @@ import { TaxonomicFilterGroupType } from 'lib/components/TaxonomicFilter/types'
import { FEATURE_FLAGS } from 'lib/constants'
import { Dayjs, dayjs } from 'lib/dayjs'
import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
-import { ceilMsToClosestSecond, eventToDescription, humanizeBytes, toParams } from 'lib/utils'
+import { ceilMsToClosestSecond } from 'lib/utils/durations'
+import { eventToDescription } from 'lib/utils/events'
import { createFuse } from 'lib/utils/fuseSearch'
+import { humanizeBytes } from 'lib/utils/numbers'
+import { toParams } from 'lib/utils/url'
import { getText } from 'scenes/comments/Comment'
import {
InspectorListItemPerformance,
diff --git a/frontend/src/scenes/session-recordings/player/player-meta/PlayerMeta.tsx b/frontend/src/scenes/session-recordings/player/player-meta/PlayerMeta.tsx
index 1e18ea1ea2fc..f270a77e2f0b 100644
--- a/frontend/src/scenes/session-recordings/player/player-meta/PlayerMeta.tsx
+++ b/frontend/src/scenes/session-recordings/player/player-meta/PlayerMeta.tsx
@@ -10,7 +10,7 @@ import { CopyToClipboardInline } from 'lib/components/CopyToClipboard'
import { useResizeBreakpoints } from 'lib/hooks/useResizeObserver'
import { LemonSkeleton } from 'lib/lemon-ui/LemonSkeleton'
import { Tooltip } from 'lib/lemon-ui/Tooltip'
-import { isObject } from 'lib/utils'
+import { isObject } from 'lib/utils/guards'
import { DraggableToNotebook } from 'scenes/notebooks/AddToNotebook/DraggableToNotebook'
import { IconWindow } from 'scenes/session-recordings/player/icons'
import { PlayerMetaLinks } from 'scenes/session-recordings/player/player-meta/PlayerMetaLinks'
diff --git a/frontend/src/scenes/session-recordings/player/player-meta/PlayerMetaTopSettings.tsx b/frontend/src/scenes/session-recordings/player/player-meta/PlayerMetaTopSettings.tsx
index 63ae3c9804a7..31d2e35210e4 100644
--- a/frontend/src/scenes/session-recordings/player/player-meta/PlayerMetaTopSettings.tsx
+++ b/frontend/src/scenes/session-recordings/player/player-meta/PlayerMetaTopSettings.tsx
@@ -7,8 +7,8 @@ import { LemonButton, LemonDialog, Link } from '@posthog/lemon-ui'
import { SESSION_RECORDINGS_TTL_WARNING_THRESHOLD_DAYS } from 'lib/constants'
import { IconHeatmap } from 'lib/lemon-ui/icons'
-import { humanFriendlyDuration } from 'lib/utils'
import { cn } from 'lib/utils/css-classes'
+import { humanFriendlyDuration } from 'lib/utils/durations'
import {
SettingsBar,
SettingsButton,
diff --git a/frontend/src/scenes/session-recordings/player/player-meta/playerMetaLogic.tsx b/frontend/src/scenes/session-recordings/player/player-meta/playerMetaLogic.tsx
index 8da76d8e82b2..1530b2721fab 100644
--- a/frontend/src/scenes/session-recordings/player/player-meta/playerMetaLogic.tsx
+++ b/frontend/src/scenes/session-recordings/player/player-meta/playerMetaLogic.tsx
@@ -9,14 +9,11 @@ import { IconClock, IconCursorClick, IconHourglass, IconKeyboard, IconWarning }
import { PropertyFilterIcon } from 'lib/components/PropertyFilters/components/PropertyFilterIcon'
import { TaxonomicFilterGroupType } from 'lib/components/TaxonomicFilter/types'
import { Dayjs } from 'lib/dayjs'
-import {
- capitalizeFirstLetter,
- ceilMsToClosestSecond,
- humanFriendlyDuration,
- isEmptyObject,
- percentage,
-} from 'lib/utils'
-import { COUNTRY_CODE_TO_LONG_NAME } from 'lib/utils/geography/country'
+import { COUNTRY_CODE_TO_LONG_NAME } from 'lib/utils/country'
+import { ceilMsToClosestSecond, humanFriendlyDuration } from 'lib/utils/durations'
+import { isEmptyObject } from 'lib/utils/guards'
+import { percentage } from 'lib/utils/numbers'
+import { capitalizeFirstLetter } from 'lib/utils/strings'
import { OverviewItem } from 'scenes/session-recordings/components/OverviewGrid'
import { Timestamp } from 'scenes/session-recordings/player/controller/PlayerControllerTime'
import { sessionRecordingDataCoordinatorLogic } from 'scenes/session-recordings/player/sessionRecordingDataCoordinatorLogic'
diff --git a/frontend/src/scenes/session-recordings/player/playlist-popover/playlistPopoverLogic.ts b/frontend/src/scenes/session-recordings/player/playlist-popover/playlistPopoverLogic.ts
index 76aac6641f6f..1568beace829 100644
--- a/frontend/src/scenes/session-recordings/player/playlist-popover/playlistPopoverLogic.ts
+++ b/frontend/src/scenes/session-recordings/player/playlist-popover/playlistPopoverLogic.ts
@@ -3,7 +3,7 @@ import { forms } from 'kea-forms'
import { lazyLoaders, loaders } from 'kea-loaders'
import api from 'lib/api'
-import { toParams } from 'lib/utils'
+import { toParams } from 'lib/utils/url'
import {
SessionRecordingPlayerLogicProps,
sessionRecordingPlayerLogic,
diff --git a/frontend/src/scenes/session-recordings/player/sessionEventsDataLogic.ts b/frontend/src/scenes/session-recordings/player/sessionEventsDataLogic.ts
index 6afa94958972..f64e47e76632 100644
--- a/frontend/src/scenes/session-recordings/player/sessionEventsDataLogic.ts
+++ b/frontend/src/scenes/session-recordings/player/sessionEventsDataLogic.ts
@@ -9,7 +9,7 @@ import { ViewportResolution } from '@posthog/replay-shared'
import api from 'lib/api'
import { Dayjs, dayjs } from 'lib/dayjs'
import { chainToElements } from 'lib/utils/elements-chain'
-import { getEventsWithPrimaryProperty } from 'lib/utils/primaryEventProperty'
+import { getEventsWithPrimaryProperty } from 'lib/utils/events'
import { TimeTree } from 'lib/utils/time-tree'
import { primaryEventPropertiesModel } from '~/models/primaryEventPropertiesModel'
diff --git a/frontend/src/scenes/session-recordings/player/sessionRecordingDataCoordinatorLogic.performance.test.ts b/frontend/src/scenes/session-recordings/player/sessionRecordingDataCoordinatorLogic.performance.test.ts
index 48e762beb9f3..a7e9adfbb713 100644
--- a/frontend/src/scenes/session-recordings/player/sessionRecordingDataCoordinatorLogic.performance.test.ts
+++ b/frontend/src/scenes/session-recordings/player/sessionRecordingDataCoordinatorLogic.performance.test.ts
@@ -2,7 +2,7 @@ import { readFileSync } from 'fs'
import { expectLogic } from 'kea-test-utils'
import { join } from 'path'
-import { uuid } from 'lib/utils'
+import { uuid } from 'lib/utils/dom'
import { sessionRecordingDataCoordinatorLogic } from 'scenes/session-recordings/player/sessionRecordingDataCoordinatorLogic'
import { setupSessionRecordingTest } from './__mocks__/test-setup'
diff --git a/frontend/src/scenes/session-recordings/player/sessionRecordingPlayerLogic.ts b/frontend/src/scenes/session-recordings/player/sessionRecordingPlayerLogic.ts
index 65f1e94d0b6c..919aea11b74e 100644
--- a/frontend/src/scenes/session-recordings/player/sessionRecordingPlayerLogic.ts
+++ b/frontend/src/scenes/session-recordings/player/sessionRecordingPlayerLogic.ts
@@ -34,7 +34,10 @@ import api from 'lib/api'
import { exportsLogic } from 'lib/components/ExportButton/exportsLogic'
import { dayjs, now } from 'lib/dayjs'
import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
-import { clamp, downloadFile, findLastIndex, objectsEqual, uuid } from 'lib/utils'
+import { findLastIndex } from 'lib/utils/arrays'
+import { downloadFile, uuid } from 'lib/utils/dom'
+import { clamp } from 'lib/utils/numbers'
+import { objectsEqual } from 'lib/utils/objects'
import { openBillingPopupModal } from 'scenes/billing/BillingPopup'
import { ReplayIframeData } from 'scenes/heatmaps/components/heatmapsBrowserLogic'
import { preflightLogic } from 'scenes/PreflightCheck/preflightLogic'
diff --git a/frontend/src/scenes/session-recordings/player/share/playerShareLogic.ts b/frontend/src/scenes/session-recordings/player/share/playerShareLogic.ts
index 7e1d9f9c1475..5523d50ada6b 100644
--- a/frontend/src/scenes/session-recordings/player/share/playerShareLogic.ts
+++ b/frontend/src/scenes/session-recordings/player/share/playerShareLogic.ts
@@ -2,7 +2,7 @@ import { kea, key, path, props, selectors } from 'kea'
import { forms } from 'kea-forms'
import { combineUrl } from 'kea-router'
-import { colonDelimitedDuration, reverseColonDelimitedDuration } from 'lib/utils'
+import { colonDelimitedDuration, reverseColonDelimitedDuration } from 'lib/utils/durations'
import { urls } from 'scenes/urls'
import type { playerShareLogicType } from './playerShareLogicType'
diff --git a/frontend/src/scenes/session-recordings/playlist/Playlist.tsx b/frontend/src/scenes/session-recordings/playlist/Playlist.tsx
index 142f62761bca..9bd78c638c1d 100644
--- a/frontend/src/scenes/session-recordings/playlist/Playlist.tsx
+++ b/frontend/src/scenes/session-recordings/playlist/Playlist.tsx
@@ -19,7 +19,8 @@ import {
import { PropertyKeyInfo } from 'lib/components/PropertyKeyInfo'
import { useResizeBreakpoints } from 'lib/hooks/useResizeObserver'
import { LemonTableLoader } from 'lib/lemon-ui/LemonTable/LemonTableLoader'
-import { pluralize, range } from 'lib/utils'
+import { range } from 'lib/utils/arrays'
+import { pluralize } from 'lib/utils/strings'
import { DraggableToNotebook } from 'scenes/notebooks/AddToNotebook/DraggableToNotebook'
import { useNotebookNode } from 'scenes/notebooks/Nodes/NotebookNodeContext'
import { RecordingsUniversalFiltersEmbedButton } from 'scenes/session-recordings/filters/RecordingsUniversalFiltersEmbed'
diff --git a/frontend/src/scenes/session-recordings/playlist/SessionRecordingPreview.tsx b/frontend/src/scenes/session-recordings/playlist/SessionRecordingPreview.tsx
index fec135ae9ab8..a0875b8ea562 100644
--- a/frontend/src/scenes/session-recordings/playlist/SessionRecordingPreview.tsx
+++ b/frontend/src/scenes/session-recordings/playlist/SessionRecordingPreview.tsx
@@ -23,7 +23,7 @@ import { LemonCheckbox } from 'lib/lemon-ui/LemonCheckbox'
import { LemonSkeleton } from 'lib/lemon-ui/LemonSkeleton'
import { Tooltip } from 'lib/lemon-ui/Tooltip'
import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
-import { colonDelimitedDuration } from 'lib/utils'
+import { colonDelimitedDuration } from 'lib/utils/durations'
import { DraggableToNotebook } from 'scenes/notebooks/AddToNotebook/DraggableToNotebook'
import { asDisplay } from 'scenes/persons/person-utils'
import { preflightLogic } from 'scenes/PreflightCheck/preflightLogic'
diff --git a/frontend/src/scenes/session-recordings/playlist/playlistUtils.ts b/frontend/src/scenes/session-recordings/playlist/playlistUtils.ts
index e9e33ae8e2f4..1ea463352424 100644
--- a/frontend/src/scenes/session-recordings/playlist/playlistUtils.ts
+++ b/frontend/src/scenes/session-recordings/playlist/playlistUtils.ts
@@ -6,8 +6,8 @@ import { convertPropertyGroupToProperties, isValidPropertyFilter } from 'lib/com
import { TaxonomicFilterGroupType } from 'lib/components/TaxonomicFilter/types'
import { isActionFilter, isEventFilter } from 'lib/components/UniversalFilters/utils'
import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'
-import { genericOperatorMap } from 'lib/utils'
import { deleteWithUndo } from 'lib/utils/deleteWithUndo'
+import { genericOperatorMap } from 'lib/utils/operators'
import { toLocalFilters } from 'scenes/insights/filters/ActionFilter/entityFilterLogic'
import { getDisplayNameFromEntityFilter } from 'scenes/insights/utils'
import { DEFAULT_RECORDING_FILTERS } from 'scenes/session-recordings/playlist/sessionRecordingsPlaylistLogic'
diff --git a/frontend/src/scenes/session-recordings/playlist/sessionRecordingsPlaylistLogic.ts b/frontend/src/scenes/session-recordings/playlist/sessionRecordingsPlaylistLogic.ts
index 2eba7005b452..42ac95f3ead9 100644
--- a/frontend/src/scenes/session-recordings/playlist/sessionRecordingsPlaylistLogic.ts
+++ b/frontend/src/scenes/session-recordings/playlist/sessionRecordingsPlaylistLogic.ts
@@ -18,8 +18,10 @@ import {
} from 'lib/components/UniversalFilters/utils'
import { FEATURE_FLAGS } from 'lib/constants'
import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
-import { isString, objectClean, objectsEqual, toParams } from 'lib/utils'
import { getCurrentTeamId } from 'lib/utils/getAppContext'
+import { isString } from 'lib/utils/guards'
+import { objectClean, objectsEqual } from 'lib/utils/objects'
+import { toParams } from 'lib/utils/url'
import { createPlaylist } from 'scenes/session-recordings/playlist/playlistUtils'
import { sessionRecordingEventUsageLogic } from 'scenes/session-recordings/sessionRecordingEventUsageLogic'
import { urls } from 'scenes/urls'
diff --git a/frontend/src/scenes/session-recordings/playlist/sessionRecordingsPlaylistSceneLogic.ts b/frontend/src/scenes/session-recordings/playlist/sessionRecordingsPlaylistSceneLogic.ts
index 60c0096cc248..0d90b9d27b20 100644
--- a/frontend/src/scenes/session-recordings/playlist/sessionRecordingsPlaylistSceneLogic.ts
+++ b/frontend/src/scenes/session-recordings/playlist/sessionRecordingsPlaylistSceneLogic.ts
@@ -5,7 +5,7 @@ import { beforeUnload, router, urlToAction } from 'kea-router'
import api from 'lib/api'
import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
-import { removeProjectIdIfPresent } from 'lib/utils/router-utils'
+import { removeProjectIdIfPresent } from 'lib/utils/kea-router'
import { sceneLogic } from 'scenes/sceneLogic'
import { Scene } from 'scenes/sceneTypes'
import {
diff --git a/frontend/src/scenes/session-recordings/sessionReplaySceneLogic.ts b/frontend/src/scenes/session-recordings/sessionReplaySceneLogic.ts
index 21693863fc76..498dc6dcedce 100644
--- a/frontend/src/scenes/session-recordings/sessionReplaySceneLogic.ts
+++ b/frontend/src/scenes/session-recordings/sessionReplaySceneLogic.ts
@@ -2,7 +2,7 @@ import { actions, kea, listeners, path, reducers, selectors } from 'kea'
import { router, urlToAction } from 'kea-router'
import { trackedActionToUrl } from 'lib/logic/scenes/trackedActionToUrl'
-import { capitalizeFirstLetter } from 'lib/utils'
+import { capitalizeFirstLetter } from 'lib/utils/strings'
import { sceneConfigurations } from 'scenes/scenes'
import { Scene } from 'scenes/sceneTypes'
import { urls } from 'scenes/urls'
diff --git a/frontend/src/scenes/sessions/components/SessionMetricsCard.tsx b/frontend/src/scenes/sessions/components/SessionMetricsCard.tsx
index bc5cf696989f..e677cb3ced17 100644
--- a/frontend/src/scenes/sessions/components/SessionMetricsCard.tsx
+++ b/frontend/src/scenes/sessions/components/SessionMetricsCard.tsx
@@ -2,7 +2,7 @@ import { useValues } from 'kea'
import { LemonCard, LemonSkeleton } from '@posthog/lemon-ui'
-import { humanFriendlyDuration } from 'lib/utils'
+import { humanFriendlyDuration } from 'lib/utils/durations'
import { sessionProfileLogic } from '../sessionProfileLogic'
diff --git a/frontend/src/scenes/settings/Settings.tsx b/frontend/src/scenes/settings/Settings.tsx
index b2a39eca93f2..afa3c5a4141b 100644
--- a/frontend/src/scenes/settings/Settings.tsx
+++ b/frontend/src/scenes/settings/Settings.tsx
@@ -33,8 +33,8 @@ import {
TooltipContent,
TooltipTrigger,
} from 'lib/ui/quill'
-import { inStorybookTestRunner } from 'lib/utils'
import { getAccessControlDisabledReason } from 'lib/utils/accessControlUtils'
+import { inStorybookTestRunner } from 'lib/utils/dom'
import { urls } from 'scenes/urls'
import { ErrorBoundary } from '~/layout/ErrorBoundary'
diff --git a/frontend/src/scenes/settings/SettingsScene.tsx b/frontend/src/scenes/settings/SettingsScene.tsx
index 19ad866f40e8..96bf4b126b66 100644
--- a/frontend/src/scenes/settings/SettingsScene.tsx
+++ b/frontend/src/scenes/settings/SettingsScene.tsx
@@ -2,7 +2,7 @@ import { useValues } from 'kea'
import { router } from 'kea-router'
import { useAnchor } from 'lib/hooks/useAnchor'
-import { capitalizeFirstLetter } from 'lib/utils'
+import { capitalizeFirstLetter } from 'lib/utils/strings'
import { SceneExport } from 'scenes/sceneTypes'
import { SceneContent } from '~/layout/scenes/components/SceneContent'
diff --git a/frontend/src/scenes/settings/environment/CoreEventsSettings.tsx b/frontend/src/scenes/settings/environment/CoreEventsSettings.tsx
index 7231466289a4..daa0c837576c 100644
--- a/frontend/src/scenes/settings/environment/CoreEventsSettings.tsx
+++ b/frontend/src/scenes/settings/environment/CoreEventsSettings.tsx
@@ -6,7 +6,7 @@ import { LemonButton, LemonInput, LemonLabel, LemonModal, LemonSelect, LemonText
import { TaxonomicFilterGroupType } from 'lib/components/TaxonomicFilter/types'
import { LemonTable } from 'lib/lemon-ui/LemonTable'
-import { uuid } from 'lib/utils'
+import { uuid } from 'lib/utils/dom'
import { ActionFilter as ActionFilterComponent } from 'scenes/insights/filters/ActionFilter/ActionFilter'
import { MathAvailability } from 'scenes/insights/filters/ActionFilter/ActionFilterRow/ActionFilterRow'
diff --git a/frontend/src/scenes/settings/environment/CustomChannelTypes.tsx b/frontend/src/scenes/settings/environment/CustomChannelTypes.tsx
index 7365980c9171..d9de092a0e8f 100644
--- a/frontend/src/scenes/settings/environment/CustomChannelTypes.tsx
+++ b/frontend/src/scenes/settings/environment/CustomChannelTypes.tsx
@@ -12,8 +12,10 @@ import { LemonButton } from 'lib/lemon-ui/LemonButton'
import { LemonInputSelect, LemonInputSelectOption } from 'lib/lemon-ui/LemonInputSelect'
import { LemonSelect } from 'lib/lemon-ui/LemonSelect'
import { Link } from 'lib/lemon-ui/Link'
-import { UnexpectedNeverError, genericOperatorMap, uuid } from 'lib/utils'
+import { uuid } from 'lib/utils/dom'
import { eventUsageLogic } from 'lib/utils/eventUsageLogic'
+import { UnexpectedNeverError } from 'lib/utils/guards'
+import { genericOperatorMap } from 'lib/utils/operators'
import { teamLogic } from 'scenes/teamLogic'
import { urls } from 'scenes/urls'
diff --git a/frontend/src/scenes/settings/environment/ManagedReverseProxy.tsx b/frontend/src/scenes/settings/environment/ManagedReverseProxy.tsx
index 78dce6904ac0..c976001189a9 100644
--- a/frontend/src/scenes/settings/environment/ManagedReverseProxy.tsx
+++ b/frontend/src/scenes/settings/environment/ManagedReverseProxy.tsx
@@ -25,7 +25,7 @@ import { OrganizationMembershipLevel } from 'lib/constants'
import { LemonField } from 'lib/lemon-ui/LemonField'
import { LemonMarkdown } from 'lib/lemon-ui/LemonMarkdown'
import { Link } from 'lib/lemon-ui/Link'
-import { isKeyOf } from 'lib/utils'
+import { isKeyOf } from 'lib/utils/guards'
import { useMaxTool } from 'scenes/max/useMaxTool'
import { preflightLogic } from 'scenes/PreflightCheck/preflightLogic'
diff --git a/frontend/src/scenes/settings/environment/ReplayTriggers.tsx b/frontend/src/scenes/settings/environment/ReplayTriggers.tsx
index 808bff49a845..4c0e7248736b 100644
--- a/frontend/src/scenes/settings/environment/ReplayTriggers.tsx
+++ b/frontend/src/scenes/settings/environment/ReplayTriggers.tsx
@@ -9,7 +9,7 @@ import { FeatureFlagTrigger, Trigger, TriggerType } from 'lib/components/Ingesti
import { PayGateMini } from 'lib/components/PayGateMini/PayGateMini'
import { FEATURE_FLAGS } from 'lib/constants'
import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
-import { pluralize } from 'lib/utils'
+import { pluralize } from 'lib/utils/strings'
import {
ReplayPlatform,
replayTriggersLogic,
diff --git a/frontend/src/scenes/settings/environment/SessionRecordingSettings.tsx b/frontend/src/scenes/settings/environment/SessionRecordingSettings.tsx
index 2b59ad753689..c5ac2110cb96 100644
--- a/frontend/src/scenes/settings/environment/SessionRecordingSettings.tsx
+++ b/frontend/src/scenes/settings/environment/SessionRecordingSettings.tsx
@@ -19,7 +19,7 @@ import { AuthorizedUrlListType } from 'lib/components/AuthorizedUrlList/authoriz
import { RestrictionScope, useRestrictedArea } from 'lib/components/RestrictedArea'
import { SESSION_RECORDING_OPT_OUT_SURVEY_ID, TeamMembershipLevel } from 'lib/constants'
import { LemonLabel } from 'lib/lemon-ui/LemonLabel/LemonLabel'
-import { isObject } from 'lib/utils'
+import { isObject } from 'lib/utils/guards'
import { organizationLogic } from 'scenes/organizationLogic'
import { InternalMultipleChoiceSurvey } from 'scenes/session-recordings/components/InternalSurvey/InternalMultipleChoiceSurvey'
import { getMaskingConfigFromLevel, getMaskingLevelFromConfig } from 'scenes/session-recordings/utils'
diff --git a/frontend/src/scenes/settings/environment/TeamSettings.tsx b/frontend/src/scenes/settings/environment/TeamSettings.tsx
index c33e109e0338..e44cef1ef0c9 100644
--- a/frontend/src/scenes/settings/environment/TeamSettings.tsx
+++ b/frontend/src/scenes/settings/environment/TeamSettings.tsx
@@ -13,8 +13,9 @@ import { getPublicSupportSnippet } from 'lib/components/Support/supportLogic'
import { TeamMembershipLevel } from 'lib/constants'
import { LemonField } from 'lib/lemon-ui/LemonField'
import { Link } from 'lib/lemon-ui/Link'
-import { debounce, inStorybook, inStorybookTestRunner } from 'lib/utils'
import { userHasAccess } from 'lib/utils/accessControlUtils'
+import { debounce } from 'lib/utils/async'
+import { inStorybook, inStorybookTestRunner } from 'lib/utils/dom'
import { organizationLogic } from 'scenes/organizationLogic'
import { preflightLogic } from 'scenes/PreflightCheck/preflightLogic'
import { teamLogic } from 'scenes/teamLogic'
diff --git a/frontend/src/scenes/settings/environment/TimezoneConfig.tsx b/frontend/src/scenes/settings/environment/TimezoneConfig.tsx
index 5203ab619943..5bd3212e44e8 100644
--- a/frontend/src/scenes/settings/environment/TimezoneConfig.tsx
+++ b/frontend/src/scenes/settings/environment/TimezoneConfig.tsx
@@ -5,7 +5,7 @@ import { TeamMembershipLevel } from 'lib/constants'
import { LemonDialog } from 'lib/lemon-ui/LemonDialog'
import { LemonInputSelect } from 'lib/lemon-ui/LemonInputSelect/LemonInputSelect'
import { LemonSkeleton } from 'lib/lemon-ui/LemonSkeleton'
-import { timeZoneLabel } from 'lib/utils'
+import { timeZoneLabel } from 'lib/utils/timezones'
import { preflightLogic } from 'scenes/PreflightCheck/preflightLogic'
import { teamLogic } from 'scenes/teamLogic'
diff --git a/frontend/src/scenes/settings/environment/proxyLogic.ts b/frontend/src/scenes/settings/environment/proxyLogic.ts
index 45f93be30330..e2f006c7fec8 100644
--- a/frontend/src/scenes/settings/environment/proxyLogic.ts
+++ b/frontend/src/scenes/settings/environment/proxyLogic.ts
@@ -9,8 +9,8 @@ import api from 'lib/api'
import { SetupTaskId } from 'lib/components/ProductSetup'
import { globalSetupLogic } from 'lib/components/ProductSetup/globalSetupLogic'
import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'
-import { isDomain } from 'lib/utils'
import { apiHostOrigin } from 'lib/utils/apiHost'
+import { isDomain } from 'lib/utils/url'
import { organizationLogic } from 'scenes/organizationLogic'
import { userLogic } from 'scenes/userLogic'
diff --git a/frontend/src/scenes/settings/organization/CIMDVerificationTokens.tsx b/frontend/src/scenes/settings/organization/CIMDVerificationTokens.tsx
index 5d2cb6437976..00c159f51432 100644
--- a/frontend/src/scenes/settings/organization/CIMDVerificationTokens.tsx
+++ b/frontend/src/scenes/settings/organization/CIMDVerificationTokens.tsx
@@ -6,7 +6,7 @@ import { LemonButton, LemonDialog, LemonInput, LemonModal, LemonTable, Link } fr
import { CodeSnippet, Language } from 'lib/components/CodeSnippet'
import { IconKey } from 'lib/lemon-ui/icons'
import { LemonBanner } from 'lib/lemon-ui/LemonBanner'
-import { humanFriendlyDetailedTime } from 'lib/utils'
+import { humanFriendlyDetailedTime } from 'lib/utils/datetime'
import { cimdVerificationTokensLogic, CIMDVerificationToken } from './cimdVerificationTokensLogic'
diff --git a/frontend/src/scenes/settings/organization/InviteModal.tsx b/frontend/src/scenes/settings/organization/InviteModal.tsx
index 3147eca3dd8c..e377de44b594 100644
--- a/frontend/src/scenes/settings/organization/InviteModal.tsx
+++ b/frontend/src/scenes/settings/organization/InviteModal.tsx
@@ -11,8 +11,9 @@ import { OrganizationMembershipLevel } from 'lib/constants'
import { LemonBanner } from 'lib/lemon-ui/LemonBanner'
import { LemonButton } from 'lib/lemon-ui/LemonButton'
import { LemonModal } from 'lib/lemon-ui/LemonModal'
-import { capitalizeFirstLetter, isEmail, pluralize } from 'lib/utils'
import { organizationMembershipLevelIntegers } from 'lib/utils/permissioning'
+import { capitalizeFirstLetter, pluralize } from 'lib/utils/strings'
+import { isEmail } from 'lib/utils/url'
import { organizationLogic } from 'scenes/organizationLogic'
import { preflightLogic } from 'scenes/PreflightCheck/preflightLogic'
import { userLogic } from 'scenes/userLogic'
diff --git a/frontend/src/scenes/settings/organization/Members.tsx b/frontend/src/scenes/settings/organization/Members.tsx
index c838aa0703cf..e93cf1301bb4 100644
--- a/frontend/src/scenes/settings/organization/Members.tsx
+++ b/frontend/src/scenes/settings/organization/Members.tsx
@@ -16,12 +16,12 @@ import { LemonTable, LemonTableColumns } from 'lib/lemon-ui/LemonTable'
import { LemonTag } from 'lib/lemon-ui/LemonTag/LemonTag'
import { ProfilePicture } from 'lib/lemon-ui/ProfilePicture'
import { Tooltip } from 'lib/lemon-ui/Tooltip'
-import { capitalizeFirstLetter, fullName } from 'lib/utils'
import {
getReasonForAccessLevelChangeProhibition,
membershipLevelToName,
organizationMembershipLevelIntegers,
} from 'lib/utils/permissioning'
+import { capitalizeFirstLetter, fullName } from 'lib/utils/strings'
import { twoFactorLogic } from 'scenes/authentication/two-factor-setup/twoFactorLogic'
import { membersExportLogic } from 'scenes/organization/membersExportLogic'
import { membersLogic } from 'scenes/organization/membersLogic'
diff --git a/frontend/src/scenes/settings/organization/OAuthApps.tsx b/frontend/src/scenes/settings/organization/OAuthApps.tsx
index cd3653cebc4f..3c12c91ba1c2 100644
--- a/frontend/src/scenes/settings/organization/OAuthApps.tsx
+++ b/frontend/src/scenes/settings/organization/OAuthApps.tsx
@@ -4,8 +4,8 @@ import { IconCopy } from '@posthog/icons'
import { LemonButton, LemonSkeleton, LemonTable, LemonTag } from '@posthog/lemon-ui'
import { IconKey } from 'lib/lemon-ui/icons'
-import { humanFriendlyDetailedTime } from 'lib/utils'
import { copyToClipboard } from 'lib/utils/copyToClipboard'
+import { humanFriendlyDetailedTime } from 'lib/utils/datetime'
import { OrganizationOAuthApplicationApi } from '~/generated/core/api.schemas'
diff --git a/frontend/src/scenes/settings/organization/OrganizationPersonalAPIKeys.tsx b/frontend/src/scenes/settings/organization/OrganizationPersonalAPIKeys.tsx
index f12235ab37b7..ee7f3b323797 100644
--- a/frontend/src/scenes/settings/organization/OrganizationPersonalAPIKeys.tsx
+++ b/frontend/src/scenes/settings/organization/OrganizationPersonalAPIKeys.tsx
@@ -7,7 +7,7 @@ import { useRestrictedArea } from 'lib/components/RestrictedArea'
import { TZLabel } from 'lib/components/TZLabel'
import { OrganizationMembershipLevel } from 'lib/constants'
import { LemonTable, LemonTableColumns } from 'lib/lemon-ui/LemonTable'
-import { fullName } from 'lib/utils'
+import { fullName } from 'lib/utils/strings'
import { TagList } from 'scenes/settings/user/PersonalAPIKeys'
import { AvailableFeature } from '~/types'
diff --git a/frontend/src/scenes/settings/organization/inviteLogic.ts b/frontend/src/scenes/settings/organization/inviteLogic.ts
index 32c7d019cb8f..e69d0e4137e6 100644
--- a/frontend/src/scenes/settings/organization/inviteLogic.ts
+++ b/frontend/src/scenes/settings/organization/inviteLogic.ts
@@ -5,7 +5,7 @@ import api, { PaginatedResponse } from 'lib/api'
import { OrganizationMembershipLevel } from 'lib/constants'
import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'
import { bindModalToUrl } from 'lib/logic/bindModalToUrl'
-import { pluralize } from 'lib/utils'
+import { pluralize } from 'lib/utils/strings'
import { organizationLogic } from 'scenes/organizationLogic'
import { preflightLogic } from 'scenes/PreflightCheck/preflightLogic'
diff --git a/frontend/src/scenes/settings/organization/organizationPersonalAPIKeysLogic.ts b/frontend/src/scenes/settings/organization/organizationPersonalAPIKeysLogic.ts
index 68e2b61289ba..5714f6cc43df 100644
--- a/frontend/src/scenes/settings/organization/organizationPersonalAPIKeysLogic.ts
+++ b/frontend/src/scenes/settings/organization/organizationPersonalAPIKeysLogic.ts
@@ -2,7 +2,7 @@ import { actions, afterMount, kea, path, reducers, selectors } from 'kea'
import { loaders } from 'kea-loaders'
import api, { ApiConfig } from 'lib/api'
-import { fullName } from 'lib/utils'
+import { fullName } from 'lib/utils/strings'
import { getPersonalApiKeysListUrl } from 'products/platform_features/frontend/generated/api'
import type { OrganizationPersonalAPIKeyApi } from 'products/platform_features/frontend/generated/api.schemas'
diff --git a/frontend/src/scenes/settings/project/ProjectSecretAPIKeys.tsx b/frontend/src/scenes/settings/project/ProjectSecretAPIKeys.tsx
index 0bf46b1438da..9498c1e8cdd5 100644
--- a/frontend/src/scenes/settings/project/ProjectSecretAPIKeys.tsx
+++ b/frontend/src/scenes/settings/project/ProjectSecretAPIKeys.tsx
@@ -8,7 +8,7 @@ import { RestrictionScope, useRestrictedArea } from 'lib/components/RestrictedAr
import { TeamMembershipLevel } from 'lib/constants'
import { LemonField } from 'lib/lemon-ui/LemonField'
import { PROJECT_SECRET_API_KEY_SCOPE_PRESETS } from 'lib/scopes'
-import { capitalizeFirstLetter } from 'lib/utils'
+import { capitalizeFirstLetter } from 'lib/utils/strings'
import { APIKeyTable } from '../shared/APIKeyTable'
import { ScopeAccessRow } from '../shared/ScopeAccessRow'
diff --git a/frontend/src/scenes/settings/settingsSceneLogic.ts b/frontend/src/scenes/settings/settingsSceneLogic.ts
index 006c1cdf8dac..7db1f87dd2f5 100644
--- a/frontend/src/scenes/settings/settingsSceneLogic.ts
+++ b/frontend/src/scenes/settings/settingsSceneLogic.ts
@@ -1,8 +1,8 @@
import { connect, kea, listeners, path, selectors } from 'kea'
import { actionToUrl, router, urlToAction } from 'kea-router'
-import { capitalizeFirstLetter } from 'lib/utils'
import { copyToClipboard } from 'lib/utils/copyToClipboard'
+import { capitalizeFirstLetter } from 'lib/utils/strings'
import { Scene } from 'scenes/sceneTypes'
import type { Params } from 'scenes/sceneTypes'
import { urls } from 'scenes/urls'
diff --git a/frontend/src/scenes/settings/shared/APIKeyTable.tsx b/frontend/src/scenes/settings/shared/APIKeyTable.tsx
index 2dab4d5ba184..b912935d2ce3 100644
--- a/frontend/src/scenes/settings/shared/APIKeyTable.tsx
+++ b/frontend/src/scenes/settings/shared/APIKeyTable.tsx
@@ -2,7 +2,7 @@ import { IconEllipsis } from '@posthog/icons'
import { LemonButton, LemonDialog, LemonMenu, LemonTable, LemonTableColumn, LemonTag, Tooltip } from '@posthog/lemon-ui'
import { Link } from 'lib/lemon-ui/Link'
-import { detailedTime, humanFriendlyDetailedTime } from 'lib/utils'
+import { detailedTime, humanFriendlyDetailedTime } from 'lib/utils/datetime'
export interface APIKeyTableRow {
id: string
diff --git a/frontend/src/scenes/settings/user/ConnectedApps.tsx b/frontend/src/scenes/settings/user/ConnectedApps.tsx
index eed55ce93f43..51e39bd85413 100644
--- a/frontend/src/scenes/settings/user/ConnectedApps.tsx
+++ b/frontend/src/scenes/settings/user/ConnectedApps.tsx
@@ -5,7 +5,7 @@ import { LemonButton, LemonDialog, LemonTable, LemonTag } from '@posthog/lemon-u
import { DetectiveHog } from 'lib/components/hedgehogs'
import { IconKey } from 'lib/lemon-ui/icons'
-import { humanFriendlyDetailedTime } from 'lib/utils'
+import { humanFriendlyDetailedTime } from 'lib/utils/datetime'
import { connectedAppsLogic, ConnectedApp } from './connectedAppsLogic'
diff --git a/frontend/src/scenes/settings/user/PasskeyList.tsx b/frontend/src/scenes/settings/user/PasskeyList.tsx
index 0eabefe47487..2fda0a53f3fd 100644
--- a/frontend/src/scenes/settings/user/PasskeyList.tsx
+++ b/frontend/src/scenes/settings/user/PasskeyList.tsx
@@ -4,7 +4,7 @@ import { IconCheckCircle, IconChip, IconClock, IconLaptop, IconLock, IconPencil,
import { LemonButton, LemonTable, Spinner } from '@posthog/lemon-ui'
import { IconLink, IconSync } from 'lib/lemon-ui/icons'
-import { humanFriendlyDetailedTime } from 'lib/utils'
+import { humanFriendlyDetailedTime } from 'lib/utils/datetime'
import { PasskeyCredential, passkeySettingsLogic } from './passkeySettingsLogic'
diff --git a/frontend/src/scenes/settings/user/UserDangerZone.tsx b/frontend/src/scenes/settings/user/UserDangerZone.tsx
index 4b46b4a2b645..b95e359f7df9 100644
--- a/frontend/src/scenes/settings/user/UserDangerZone.tsx
+++ b/frontend/src/scenes/settings/user/UserDangerZone.tsx
@@ -6,7 +6,8 @@ import { IconTrash } from '@posthog/icons'
import { LemonButton, LemonDialog, LemonInput, LemonModal, LemonTable, LemonTag, Tooltip } from '@posthog/lemon-ui'
import { OrganizationMembershipLevel } from 'lib/constants'
-import { detailedTime, humanFriendlyDetailedTime, isNotNil } from 'lib/utils'
+import { detailedTime, humanFriendlyDetailedTime } from 'lib/utils/datetime'
+import { isNotNil } from 'lib/utils/guards'
import { urls } from 'scenes/urls'
import { userLogic } from 'scenes/userLogic'
diff --git a/frontend/src/scenes/surveys/SurveyEdit.tsx b/frontend/src/scenes/surveys/SurveyEdit.tsx
index dfcfbc98c613..e879367f312b 100644
--- a/frontend/src/scenes/surveys/SurveyEdit.tsx
+++ b/frontend/src/scenes/surveys/SurveyEdit.tsx
@@ -33,7 +33,7 @@ import { LemonField } from 'lib/lemon-ui/LemonField'
import { LemonRadio, LemonRadioOption } from 'lib/lemon-ui/LemonRadio'
import { Tooltip } from 'lib/lemon-ui/Tooltip'
import { featureFlagLogic as enabledFeaturesLogic } from 'lib/logic/featureFlagLogic'
-import { formatDate } from 'lib/utils'
+import { formatDate } from 'lib/utils/datetime'
import { ValueOf } from 'lib/utils/types'
import { featureFlagLogic } from 'scenes/feature-flags/featureFlagLogic'
import { FeatureFlagReleaseConditions } from 'scenes/feature-flags/FeatureFlagReleaseConditions'
diff --git a/frontend/src/scenes/surveys/SurveyOverview.tsx b/frontend/src/scenes/surveys/SurveyOverview.tsx
index b9e16a0e5cbd..a95bb06ba927 100644
--- a/frontend/src/scenes/surveys/SurveyOverview.tsx
+++ b/frontend/src/scenes/surveys/SurveyOverview.tsx
@@ -6,7 +6,7 @@ import { LemonButton, LemonDivider, Link } from '@posthog/lemon-ui'
import { TZLabel } from 'lib/components/TZLabel'
import { IconAreaChart, IconGridView, IconLink, IconListView } from 'lib/lemon-ui/icons'
-import { pluralize } from 'lib/utils'
+import { pluralize } from 'lib/utils/strings'
import { FirstSurveyHelper } from 'scenes/surveys/components/empty-state/FirstSurveyHelper'
import { SURVEY_TYPE_LABEL_MAP, SurveyQuestionLabel } from 'scenes/surveys/constants'
import { CopySurveyLink } from 'scenes/surveys/CopySurveyLink'
diff --git a/frontend/src/scenes/surveys/SurveyRepeatSchedule.tsx b/frontend/src/scenes/surveys/SurveyRepeatSchedule.tsx
index be983884ff88..d00e2ad1ffb1 100644
--- a/frontend/src/scenes/surveys/SurveyRepeatSchedule.tsx
+++ b/frontend/src/scenes/surveys/SurveyRepeatSchedule.tsx
@@ -7,7 +7,7 @@ import { LemonBanner, LemonInput, LemonSnack, Link } from '@posthog/lemon-ui'
import { LemonField } from 'lib/lemon-ui/LemonField'
import { LemonRadio } from 'lib/lemon-ui/LemonRadio'
-import { pluralize } from 'lib/utils'
+import { pluralize } from 'lib/utils/strings'
import { LinkToSurveyFormSection } from 'scenes/surveys/components/LinkToSurveyFormSection'
import { SURVEY_FORM_INPUT_IDS } from 'scenes/surveys/constants'
diff --git a/frontend/src/scenes/surveys/SurveyResponseFilters.tsx b/frontend/src/scenes/surveys/SurveyResponseFilters.tsx
index e861eff16d3e..0a3d60e910c6 100644
--- a/frontend/src/scenes/surveys/SurveyResponseFilters.tsx
+++ b/frontend/src/scenes/surveys/SurveyResponseFilters.tsx
@@ -9,8 +9,8 @@ import { PropertyValue } from 'lib/components/PropertyFilters/components/Propert
import { PropertyFilters } from 'lib/components/PropertyFilters/PropertyFilters'
import { TaxonomicFilterGroupType } from 'lib/components/TaxonomicFilter/types'
import { LemonDivider } from 'lib/lemon-ui/LemonDivider'
-import { allOperatorsMapping } from 'lib/utils'
import { copyToClipboard } from 'lib/utils/copyToClipboard'
+import { allOperatorsMapping } from 'lib/utils/operators'
import { QUESTION_TYPE_ICON_MAP, SurveyQuestionLabel } from 'scenes/surveys/constants'
import { getSurveyEndDateForQuery, getSurveyIdBasedResponseKey, getSurveyStartDateForQuery } from 'scenes/surveys/utils'
diff --git a/frontend/src/scenes/surveys/SurveyStatsSummary.tsx b/frontend/src/scenes/surveys/SurveyStatsSummary.tsx
index db1d219b50ce..35d002b58147 100644
--- a/frontend/src/scenes/surveys/SurveyStatsSummary.tsx
+++ b/frontend/src/scenes/surveys/SurveyStatsSummary.tsx
@@ -6,7 +6,8 @@ import { LemonSkeleton, LemonSwitch } from '@posthog/lemon-ui'
import { TZLabel } from 'lib/components/TZLabel'
import { dayjs } from 'lib/dayjs'
import { Tooltip } from 'lib/lemon-ui/Tooltip'
-import { humanFriendlyNumber, percentage, pluralize } from 'lib/utils'
+import { humanFriendlyNumber, percentage } from 'lib/utils/numbers'
+import { pluralize } from 'lib/utils/strings'
import { StackedBar, StackedBarSegment, StackedBarSkeleton } from 'scenes/surveys/components/StackedBar'
import { CopySurveyLink } from 'scenes/surveys/CopySurveyLink'
diff --git a/frontend/src/scenes/surveys/SurveyViewRedesign/SurveySidebar.tsx b/frontend/src/scenes/surveys/SurveyViewRedesign/SurveySidebar.tsx
index aaebb750418c..da25646846c6 100644
--- a/frontend/src/scenes/surveys/SurveyViewRedesign/SurveySidebar.tsx
+++ b/frontend/src/scenes/surveys/SurveyViewRedesign/SurveySidebar.tsx
@@ -7,7 +7,7 @@ import { LemonButton, LemonMenu, LemonSelect, Link } from '@posthog/lemon-ui'
import { exportsLogic } from 'lib/components/ExportButton/exportsLogic'
import { TZLabel } from 'lib/components/TZLabel'
-import { pluralize } from 'lib/utils'
+import { pluralize } from 'lib/utils/strings'
import { SURVEY_TYPE_LABEL_MAP } from 'scenes/surveys/constants'
import { SurveyAppearancePreview } from 'scenes/surveys/SurveyAppearancePreview'
import { surveyLogic } from 'scenes/surveys/surveyLogic'
diff --git a/frontend/src/scenes/surveys/components/StackedBar.tsx b/frontend/src/scenes/surveys/components/StackedBar.tsx
index 6c02f91773d8..857d03d849df 100644
--- a/frontend/src/scenes/surveys/components/StackedBar.tsx
+++ b/frontend/src/scenes/surveys/components/StackedBar.tsx
@@ -2,7 +2,7 @@ import clsx from 'clsx'
import { LemonSkeleton } from 'lib/lemon-ui/LemonSkeleton'
import { Tooltip } from 'lib/lemon-ui/Tooltip'
-import { humanFriendlyNumber } from 'lib/utils'
+import { humanFriendlyNumber } from 'lib/utils/numbers'
const formatCount = (count: number, total: number): string => {
if ((count / total) * 100 < 3) {
diff --git a/frontend/src/scenes/surveys/components/SurveyOpportunityButton.tsx b/frontend/src/scenes/surveys/components/SurveyOpportunityButton.tsx
index 4f7ceb6b5d1a..ec98eb10bd8f 100644
--- a/frontend/src/scenes/surveys/components/SurveyOpportunityButton.tsx
+++ b/frontend/src/scenes/surveys/components/SurveyOpportunityButton.tsx
@@ -8,7 +8,7 @@ import { LemonButton, Tooltip } from '@posthog/lemon-ui'
import { FEATURE_FLAGS } from 'lib/constants'
import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
-import { formatPercentage } from 'lib/utils'
+import { formatPercentage } from 'lib/utils/numbers'
import { addProductIntent, addProductIntentForCrossSell } from 'lib/utils/product-intents'
import { useMaxTool } from 'scenes/max/useMaxTool'
import { urls } from 'scenes/urls'
diff --git a/frontend/src/scenes/surveys/components/question-branching/QuestionBranchingInput.tsx b/frontend/src/scenes/surveys/components/question-branching/QuestionBranchingInput.tsx
index 97659746adb7..15962dab22d7 100644
--- a/frontend/src/scenes/surveys/components/question-branching/QuestionBranchingInput.tsx
+++ b/frontend/src/scenes/surveys/components/question-branching/QuestionBranchingInput.tsx
@@ -3,7 +3,7 @@ import { useActions, useValues } from 'kea'
import { LemonDialog, LemonSelect } from '@posthog/lemon-ui'
import { LemonField } from 'lib/lemon-ui/LemonField'
-import { truncate } from 'lib/utils'
+import { truncate } from 'lib/utils/strings'
import { NPS_DETRACTOR_LABEL, NPS_PASSIVE_LABEL, NPS_PROMOTER_LABEL } from 'scenes/surveys/constants'
import {
diff --git a/frontend/src/scenes/surveys/components/question-visualizations/SurveyQuestionVisualization.tsx b/frontend/src/scenes/surveys/components/question-visualizations/SurveyQuestionVisualization.tsx
index 28a2fb2334c6..9fad1edb3f51 100644
--- a/frontend/src/scenes/surveys/components/question-visualizations/SurveyQuestionVisualization.tsx
+++ b/frontend/src/scenes/surveys/components/question-visualizations/SurveyQuestionVisualization.tsx
@@ -3,8 +3,9 @@ import { useValues } from 'kea'
import { IconCopy } from '@posthog/icons'
import { LemonButton, LemonSkeleton } from '@posthog/lemon-ui'
-import { humanFriendlyNumber, pluralize } from 'lib/utils'
import { copyToClipboard } from 'lib/utils/copyToClipboard'
+import { humanFriendlyNumber } from 'lib/utils/numbers'
+import { pluralize } from 'lib/utils/strings'
import { StatelessInsightLoadingState } from 'scenes/insights/EmptyStates'
import { AnalyzeResponsesButton } from 'scenes/surveys/components/AnalyzeResponsesButton'
import { MultipleChoiceQuestionViz } from 'scenes/surveys/components/question-visualizations/MultipleChoiceQuestionViz'
diff --git a/frontend/src/scenes/surveys/components/question-visualizations/questionVizTransforms.ts b/frontend/src/scenes/surveys/components/question-visualizations/questionVizTransforms.ts
index 76d11d062ea9..dddaf3507f93 100644
--- a/frontend/src/scenes/surveys/components/question-visualizations/questionVizTransforms.ts
+++ b/frontend/src/scenes/surveys/components/question-visualizations/questionVizTransforms.ts
@@ -1,4 +1,4 @@
-import { hexToRGB } from 'lib/utils'
+import { hexToRGB } from 'lib/utils/colors'
// Share of the base color kept for non-highlighted bars. Stronger dim when a filter is actually
// applied (active), lighter when a choice is only "armed" for a follow-up click. Keeps must stay
diff --git a/frontend/src/scenes/surveys/constants.tsx b/frontend/src/scenes/surveys/constants.tsx
index 0de05407f4b5..e08a55819d33 100644
--- a/frontend/src/scenes/surveys/constants.tsx
+++ b/frontend/src/scenes/surveys/constants.tsx
@@ -1,7 +1,7 @@
import { IconComment } from '@posthog/icons'
import { IconAreaChart, IconGridView, IconLink, IconListView } from 'lib/lemon-ui/icons'
-import { allOperatorsMapping } from 'lib/utils'
+import { allOperatorsMapping } from 'lib/utils/operators'
import {
AccessControlLevel,
diff --git a/frontend/src/scenes/surveys/language.tsx b/frontend/src/scenes/surveys/language.tsx
index 1f0b5d9a844e..8f24d939c226 100644
--- a/frontend/src/scenes/surveys/language.tsx
+++ b/frontend/src/scenes/surveys/language.tsx
@@ -1,4 +1,4 @@
-import { COUNTRY_CODE_TO_LONG_NAME, LANGUAGE_CODE_TO_NAME } from 'lib/utils/geography/country'
+import { COUNTRY_CODE_TO_LONG_NAME, LANGUAGE_CODE_TO_NAME } from 'lib/utils/country'
import { Survey } from '~/types'
diff --git a/frontend/src/scenes/surveys/surveyActivityDescriber.tsx b/frontend/src/scenes/surveys/surveyActivityDescriber.tsx
index f46552397287..2a59f392f328 100644
--- a/frontend/src/scenes/surveys/surveyActivityDescriber.tsx
+++ b/frontend/src/scenes/surveys/surveyActivityDescriber.tsx
@@ -11,7 +11,7 @@ import {
userNameForLogItem,
} from 'lib/components/ActivityLog/humanizeActivity'
import { Link } from 'lib/lemon-ui/Link'
-import { truncate } from 'lib/utils'
+import { truncate } from 'lib/utils/strings'
import { urls } from 'scenes/urls'
import {
diff --git a/frontend/src/scenes/surveys/surveyLogic.tsx b/frontend/src/scenes/surveys/surveyLogic.tsx
index a4d2ff7c76bc..b2c711a6c6f1 100644
--- a/frontend/src/scenes/surveys/surveyLogic.tsx
+++ b/frontend/src/scenes/surveys/surveyLogic.tsx
@@ -12,9 +12,11 @@ import { SetupTaskId, globalSetupLogic } from 'lib/components/ProductSetup'
import { FEATURE_FLAGS } from 'lib/constants'
import { dayjs } from 'lib/dayjs'
import { FeatureFlagsSet, featureFlagLogic as enabledFlagLogic } from 'lib/logic/featureFlagLogic'
-import { allOperatorsMapping, hasFormErrors, isObject, objectClean } from 'lib/utils'
import { deleteWithUndo } from 'lib/utils/deleteWithUndo'
import { eventUsageLogic } from 'lib/utils/eventUsageLogic'
+import { isObject } from 'lib/utils/guards'
+import { hasFormErrors, objectClean } from 'lib/utils/objects'
+import { allOperatorsMapping } from 'lib/utils/operators'
import { maxGlobalLogic } from 'scenes/max/maxGlobalLogic'
import { projectLogic } from 'scenes/projectLogic'
import { Scene } from 'scenes/sceneTypes'
diff --git a/frontend/src/scenes/surveys/surveysLogic.tsx b/frontend/src/scenes/surveys/surveysLogic.tsx
index 59169fc6ad45..1eb0b53f6f74 100644
--- a/frontend/src/scenes/surveys/surveysLogic.tsx
+++ b/frontend/src/scenes/surveys/surveysLogic.tsx
@@ -8,7 +8,7 @@ import api, { CountedPaginatedResponse } from 'lib/api'
import { SetupTaskId, globalSetupLogic } from 'lib/components/ProductSetup'
import { FEATURE_FLAGS } from 'lib/constants'
import { featureFlagLogic as enabledFlagLogic } from 'lib/logic/featureFlagLogic'
-import { pluralize } from 'lib/utils'
+import { pluralize } from 'lib/utils/strings'
import { sceneConfigurations } from 'scenes/scenes'
import { Scene } from 'scenes/sceneTypes'
import { SURVEY_PAGE_SIZE } from 'scenes/surveys/constants'
diff --git a/frontend/src/scenes/surveys/utils.ts b/frontend/src/scenes/surveys/utils.ts
index 29d39d542073..015dddf302d9 100644
--- a/frontend/src/scenes/surveys/utils.ts
+++ b/frontend/src/scenes/surveys/utils.ts
@@ -3,7 +3,7 @@ import { DeepPartialMap, ValidationErrorType } from 'kea-forms'
import posthog from 'posthog-js'
import { dayjs } from 'lib/dayjs'
-import { dateStringToDayJs } from 'lib/utils'
+import { dateStringToDayJs } from 'lib/utils/dateFilters'
import { getAppContext } from 'lib/utils/getAppContext'
import { NEW_SURVEY, NewSurvey, SURVEY_CREATED_SOURCE, SURVEY_RATING_SCALE } from 'scenes/surveys/constants'
import { SurveyRatingResults } from 'scenes/surveys/surveyLogic'
diff --git a/frontend/src/scenes/surveys/wizard/steps/WhereStep.tsx b/frontend/src/scenes/surveys/wizard/steps/WhereStep.tsx
index af7df0830af7..e933e6a4c586 100644
--- a/frontend/src/scenes/surveys/wizard/steps/WhereStep.tsx
+++ b/frontend/src/scenes/surveys/wizard/steps/WhereStep.tsx
@@ -9,7 +9,7 @@ import api from 'lib/api'
import { FlagSelector } from 'lib/components/FlagSelector'
import { ANY_VARIANT, variantOptions } from 'lib/components/IngestionControls/triggers/FlagTrigger/VariantSelector'
import { LemonRadio } from 'lib/lemon-ui/LemonRadio'
-import { humanFriendlyNumber } from 'lib/utils'
+import { humanFriendlyNumber } from 'lib/utils/numbers'
import { formatRE2Error } from 'lib/utils/regexp'
import { featureFlagLogic } from 'scenes/feature-flags/featureFlagLogic'
import { teamLogic } from 'scenes/teamLogic'
diff --git a/frontend/src/scenes/team-activity/marketing_analytics_config/marketingAnalyticsConfigurationDescriber.tsx b/frontend/src/scenes/team-activity/marketing_analytics_config/marketingAnalyticsConfigurationDescriber.tsx
index 0134f6eb9cf5..72df77e9a0dd 100644
--- a/frontend/src/scenes/team-activity/marketing_analytics_config/marketingAnalyticsConfigurationDescriber.tsx
+++ b/frontend/src/scenes/team-activity/marketing_analytics_config/marketingAnalyticsConfigurationDescriber.tsx
@@ -1,5 +1,5 @@
import { ActivityChange, ChangeMapping } from 'lib/components/ActivityLog/humanizeActivity'
-import { objectsEqual } from 'lib/utils'
+import { objectsEqual } from 'lib/utils/objects'
import { MarketingAnalyticsConfig, SourceMap } from '~/queries/schema/schema-general'
diff --git a/frontend/src/scenes/team-activity/revenue_analytics_config/revenueAnalyticsConfigurationDescriber.tsx b/frontend/src/scenes/team-activity/revenue_analytics_config/revenueAnalyticsConfigurationDescriber.tsx
index 838b1c9ef044..3e438b00971a 100644
--- a/frontend/src/scenes/team-activity/revenue_analytics_config/revenueAnalyticsConfigurationDescriber.tsx
+++ b/frontend/src/scenes/team-activity/revenue_analytics_config/revenueAnalyticsConfigurationDescriber.tsx
@@ -1,5 +1,5 @@
import { ActivityChange, ChangeMapping } from 'lib/components/ActivityLog/humanizeActivity'
-import { objectsEqual } from 'lib/utils'
+import { objectsEqual } from 'lib/utils/objects'
import {
RevenueAnalyticsConfig,
diff --git a/frontend/src/scenes/team-activity/teamActivityDescriber.tsx b/frontend/src/scenes/team-activity/teamActivityDescriber.tsx
index e3de890d6a5b..e8bc6f8bfe12 100644
--- a/frontend/src/scenes/team-activity/teamActivityDescriber.tsx
+++ b/frontend/src/scenes/team-activity/teamActivityDescriber.tsx
@@ -12,8 +12,9 @@ import { PathCleanFilterItem } from 'lib/components/PathCleanFilters/PathCleanFi
import { keyFromFilter } from 'lib/components/PathCleanFilters/PathCleanFilters'
import PropertyFiltersDisplay from 'lib/components/PropertyFilters/components/PropertyFiltersDisplay'
import { Link } from 'lib/lemon-ui/Link'
-import { isObject, pluralize } from 'lib/utils'
-import { CURRENCY_SYMBOL_TO_EMOJI_MAP, CURRENCY_SYMBOL_TO_NAME_MAP } from 'lib/utils/geography/currency'
+import { CURRENCY_SYMBOL_TO_EMOJI_MAP, CURRENCY_SYMBOL_TO_NAME_MAP } from 'lib/utils/currency'
+import { isObject } from 'lib/utils/guards'
+import { pluralize } from 'lib/utils/strings'
import { urls } from 'scenes/urls'
import { CurrencyCode } from '~/queries/schema/schema-general'
diff --git a/frontend/src/scenes/teamLogic.tsx b/frontend/src/scenes/teamLogic.tsx
index 76f78ba51fea..1fefb4b5d2bc 100644
--- a/frontend/src/scenes/teamLogic.tsx
+++ b/frontend/src/scenes/teamLogic.tsx
@@ -8,9 +8,9 @@ import { OrganizationMembershipLevel } from 'lib/constants'
import { IconSwapHoriz } from 'lib/lemon-ui/icons'
import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'
import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
-import { identifierToHuman, isUserLoggedIn } from 'lib/utils'
+import { DEFAULT_CURRENCY } from 'lib/utils/currency'
import { eventUsageLogic } from 'lib/utils/eventUsageLogic'
-import { DEFAULT_CURRENCY } from 'lib/utils/geography/currency'
+import { isUserLoggedIn } from 'lib/utils/getAppContext'
import { getAppContext } from 'lib/utils/getAppContext'
import {
type ProductCrossSellProperties,
@@ -18,6 +18,7 @@ import {
addProductIntent,
addProductIntentForCrossSell,
} from 'lib/utils/product-intents'
+import { identifierToHuman } from 'lib/utils/strings'
import { customProductsLogic } from '~/layout/panel-layout/ProjectTree/customProductsLogic'
import { CurrencyCode, CustomerAnalyticsConfig, ProductKey } from '~/queries/schema/schema-general'
diff --git a/frontend/src/scenes/trends/persons-modal/PersonsModal.tsx b/frontend/src/scenes/trends/persons-modal/PersonsModal.tsx
index f420776f87db..34f3ac2faddd 100644
--- a/frontend/src/scenes/trends/persons-modal/PersonsModal.tsx
+++ b/frontend/src/scenes/trends/persons-modal/PersonsModal.tsx
@@ -29,7 +29,8 @@ import { LemonTabs } from 'lib/lemon-ui/LemonTabs'
import { ProfilePicture } from 'lib/lemon-ui/ProfilePicture'
import { Spinner } from 'lib/lemon-ui/Spinner/Spinner'
import { Tooltip } from 'lib/lemon-ui/Tooltip'
-import { capitalizeFirstLetter, isGroupType, isSessionType, midEllipsis, pluralize } from 'lib/utils'
+import { isGroupType, isSessionType } from 'lib/utils/guards'
+import { capitalizeFirstLetter, midEllipsis, pluralize } from 'lib/utils/strings'
import { InsightErrorState, InsightValidationError } from 'scenes/insights/EmptyStates'
import { isOtherBreakdown } from 'scenes/insights/utils'
import { GroupActorDisplay, groupDisplayId } from 'scenes/persons/GroupActorDisplay'
diff --git a/frontend/src/scenes/trends/persons-modal/SessionActorDisplay.tsx b/frontend/src/scenes/trends/persons-modal/SessionActorDisplay.tsx
index c6d768f43d23..bef7336ecc7d 100644
--- a/frontend/src/scenes/trends/persons-modal/SessionActorDisplay.tsx
+++ b/frontend/src/scenes/trends/persons-modal/SessionActorDisplay.tsx
@@ -1,5 +1,5 @@
import { CopyToClipboardInline } from 'lib/components/CopyToClipboard'
-import { humanFriendlyDuration } from 'lib/utils'
+import { humanFriendlyDuration } from 'lib/utils/durations'
import { asDisplay } from 'scenes/persons/person-utils'
import { gatherIconProperties, PropertyIcons } from 'scenes/session-recordings/playlist/SessionRecordingPreview'
diff --git a/frontend/src/scenes/trends/persons-modal/persons-modal-utils.tsx b/frontend/src/scenes/trends/persons-modal/persons-modal-utils.tsx
index 304d792e9291..706e91f1d7ce 100644
--- a/frontend/src/scenes/trends/persons-modal/persons-modal-utils.tsx
+++ b/frontend/src/scenes/trends/persons-modal/persons-modal-utils.tsx
@@ -1,6 +1,6 @@
import { PropertyKeyInfo } from 'lib/components/PropertyKeyInfo'
import { TaxonomicFilterGroupType } from 'lib/components/TaxonomicFilter/types'
-import { pluralize } from 'lib/utils'
+import { pluralize } from 'lib/utils/strings'
import {
InsightActorsQuery,
diff --git a/frontend/src/scenes/trends/persons-modal/personsModalLogic.ts b/frontend/src/scenes/trends/persons-modal/personsModalLogic.ts
index 0d4994c2400b..573f71a7fa36 100644
--- a/frontend/src/scenes/trends/persons-modal/personsModalLogic.ts
+++ b/frontend/src/scenes/trends/persons-modal/personsModalLogic.ts
@@ -5,8 +5,8 @@ import { combineUrl, router, urlToAction } from 'kea-router'
import { lemonToast } from '@posthog/lemon-ui'
import api from 'lib/api'
-import { assignField, isGroupType, isSessionType } from 'lib/utils'
import { eventUsageLogic } from 'lib/utils/eventUsageLogic'
+import { assignField, isGroupType, isSessionType } from 'lib/utils/guards'
import { cleanFilters } from 'scenes/insights/utils/cleanFilters'
import { sceneLogic } from 'scenes/sceneLogic'
import { teamLogic } from 'scenes/teamLogic'
diff --git a/frontend/src/scenes/trends/trendsDataLogic.ts b/frontend/src/scenes/trends/trendsDataLogic.ts
index aed5dcb38e3d..0072d42928bf 100644
--- a/frontend/src/scenes/trends/trendsDataLogic.ts
+++ b/frontend/src/scenes/trends/trendsDataLogic.ts
@@ -2,7 +2,7 @@ import { actions, connect, kea, key, listeners, path, props, reducers, selectors
import { DataColorTheme, DataColorToken } from 'lib/colors'
import { dayjs } from 'lib/dayjs'
-import { isMultiSeriesFormula } from 'lib/utils'
+import { isMultiSeriesFormula } from 'lib/utils/strings'
import { dashboardLogic } from 'scenes/dashboard/dashboardLogic'
import { getColorFromToken } from 'scenes/dataThemeLogic'
import { insightVizDataLogic } from 'scenes/insights/insightVizDataLogic'
diff --git a/frontend/src/scenes/trends/viz/ActionsLineGraph.tsx b/frontend/src/scenes/trends/viz/ActionsLineGraph.tsx
index 3d0c43e0301d..5c36e1706a95 100644
--- a/frontend/src/scenes/trends/viz/ActionsLineGraph.tsx
+++ b/frontend/src/scenes/trends/viz/ActionsLineGraph.tsx
@@ -5,7 +5,8 @@ import { insightAlertsLogic } from 'lib/components/Alerts/insightAlertsLogic'
import { DateDisplay } from 'lib/components/DateDisplay'
import { PropertyKeyInfo } from 'lib/components/PropertyKeyInfo'
import { ciRanges, movingAverage } from 'lib/statistics'
-import { capitalizeFirstLetter, hexToRGBA } from 'lib/utils'
+import { hexToRGBA } from 'lib/utils/colors'
+import { capitalizeFirstLetter } from 'lib/utils/strings'
import { insightLogic } from 'scenes/insights/insightLogic'
import { teamLogic } from 'scenes/teamLogic'
import { datasetToActorsQuery } from 'scenes/trends/viz/datasetToActorsQuery'
diff --git a/frontend/src/scenes/web-analytics/CalendarHeatMap/CalendarHeatMapCell.tsx b/frontend/src/scenes/web-analytics/CalendarHeatMap/CalendarHeatMapCell.tsx
index f39972f8a4d6..708f73d54315 100644
--- a/frontend/src/scenes/web-analytics/CalendarHeatMap/CalendarHeatMapCell.tsx
+++ b/frontend/src/scenes/web-analytics/CalendarHeatMap/CalendarHeatMapCell.tsx
@@ -1,6 +1,7 @@
import { Tooltip } from 'lib/lemon-ui/Tooltip'
-import { gradateColor, humanFriendlyLargeNumber } from 'lib/utils'
+import { gradateColor } from 'lib/utils/colors'
import { cn } from 'lib/utils/css-classes'
+import { humanFriendlyLargeNumber } from 'lib/utils/numbers'
interface HeatMapCellProps {
values: HeatMapValues
diff --git a/frontend/src/scenes/web-analytics/LiveMetricsDashboard/LiveLocationsCard.tsx b/frontend/src/scenes/web-analytics/LiveMetricsDashboard/LiveLocationsCard.tsx
index 5733934e1a1c..dac09e68530e 100644
--- a/frontend/src/scenes/web-analytics/LiveMetricsDashboard/LiveLocationsCard.tsx
+++ b/frontend/src/scenes/web-analytics/LiveMetricsDashboard/LiveLocationsCard.tsx
@@ -3,7 +3,7 @@ import { useState } from 'react'
import { IconGlobe } from '@posthog/icons'
import { LemonTabs } from '@posthog/lemon-ui'
-import { COUNTRY_CODE_TO_LONG_NAME, countryCodeToFlag } from 'lib/utils/geography/country'
+import { COUNTRY_CODE_TO_LONG_NAME, countryCodeToFlag } from 'lib/utils/country'
import { BreakdownLiveCard } from './BreakdownLiveCard'
import { buildCityKey, CityBreakdownItem, CountryBreakdownItem } from './LiveWebAnalyticsMetricsTypes'
diff --git a/frontend/src/scenes/web-analytics/LiveMetricsDashboard/LivePersonDrillDownRow.tsx b/frontend/src/scenes/web-analytics/LiveMetricsDashboard/LivePersonDrillDownRow.tsx
index c2f61f46a8ec..b3a0877de4ea 100644
--- a/frontend/src/scenes/web-analytics/LiveMetricsDashboard/LivePersonDrillDownRow.tsx
+++ b/frontend/src/scenes/web-analytics/LiveMetricsDashboard/LivePersonDrillDownRow.tsx
@@ -2,7 +2,7 @@ import { IconPlay } from '@posthog/icons'
import { LemonButton, Link } from '@posthog/lemon-ui'
import { TZLabel } from 'lib/components/TZLabel'
-import { pluralize } from 'lib/utils'
+import { pluralize } from 'lib/utils/strings'
import { PersonDisplay } from 'scenes/persons/PersonDisplay'
import { urls } from 'scenes/urls'
diff --git a/frontend/src/scenes/web-analytics/LiveMetricsDashboard/LiveWebAnalyticsMetrics.tsx b/frontend/src/scenes/web-analytics/LiveMetricsDashboard/LiveWebAnalyticsMetrics.tsx
index d86ad5d6e87d..0912231d5e1c 100644
--- a/frontend/src/scenes/web-analytics/LiveMetricsDashboard/LiveWebAnalyticsMetrics.tsx
+++ b/frontend/src/scenes/web-analytics/LiveMetricsDashboard/LiveWebAnalyticsMetrics.tsx
@@ -24,7 +24,7 @@ import { FEATURE_FLAGS } from 'lib/constants'
import { usePageVisibility } from 'lib/hooks/usePageVisibility'
import { IconWithCount } from 'lib/lemon-ui/icons/icons'
import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
-import { COUNTRY_CODE_TO_LONG_NAME, countryCodeToFlag } from 'lib/utils/geography/country'
+import { COUNTRY_CODE_TO_LONG_NAME, countryCodeToFlag } from 'lib/utils/country'
import { LiveEventsFeed, LiveEventsFeedColumn } from 'scenes/activity/live/LiveEventsFeed'
import { teamLogic } from 'scenes/teamLogic'
diff --git a/frontend/src/scenes/web-analytics/LiveMetricsDashboard/LiveWorldMap.tsx b/frontend/src/scenes/web-analytics/LiveMetricsDashboard/LiveWorldMap.tsx
index 2e4e6bb6c9a6..da3115981a38 100644
--- a/frontend/src/scenes/web-analytics/LiveMetricsDashboard/LiveWorldMap.tsx
+++ b/frontend/src/scenes/web-analytics/LiveMetricsDashboard/LiveWorldMap.tsx
@@ -3,7 +3,7 @@ import '~/scenes/insights/views/WorldMap/WorldMap.scss'
import { useActions, useValues } from 'kea'
import React, { useCallback, useEffect } from 'react'
-import { gradateColor } from 'lib/utils'
+import { gradateColor } from 'lib/utils/colors'
import { countryVectors } from 'scenes/insights/views/WorldMap/countryVectors'
import { CountryBreakdownItem } from './LiveWebAnalyticsMetricsTypes'
diff --git a/frontend/src/scenes/web-analytics/LiveMetricsDashboard/liveWebAnalyticsMetricsLogic.tsx b/frontend/src/scenes/web-analytics/LiveMetricsDashboard/liveWebAnalyticsMetricsLogic.tsx
index 4aff83658502..7cfcb99755e0 100644
--- a/frontend/src/scenes/web-analytics/LiveMetricsDashboard/liveWebAnalyticsMetricsLogic.tsx
+++ b/frontend/src/scenes/web-analytics/LiveMetricsDashboard/liveWebAnalyticsMetricsLogic.tsx
@@ -7,9 +7,9 @@ import { lemonToast } from '@posthog/lemon-ui'
import { FEATURE_FLAGS } from 'lib/constants'
import { dayjs } from 'lib/dayjs'
import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
-import { hashCodeForString } from 'lib/utils'
import { liveEventsHostOrigin } from 'lib/utils/apiHost'
import { CATEGORY_LABELS } from 'lib/utils/botDetection'
+import { hashCodeForString } from 'lib/utils/strings'
import { deduplicateEvents } from 'scenes/activity/live/deduplicateEvents'
import { teamLogic } from 'scenes/teamLogic'
import { ProductTab } from 'scenes/web-analytics/common'
diff --git a/frontend/src/scenes/web-analytics/LiveMetricsDashboard/liveWorldMapLogic.tsx b/frontend/src/scenes/web-analytics/LiveMetricsDashboard/liveWorldMapLogic.tsx
index d60779046e7a..244e73a7e017 100644
--- a/frontend/src/scenes/web-analytics/LiveMetricsDashboard/liveWorldMapLogic.tsx
+++ b/frontend/src/scenes/web-analytics/LiveMetricsDashboard/liveWorldMapLogic.tsx
@@ -1,7 +1,7 @@
import { actions, events, kea, listeners, path, reducers, selectors } from 'kea'
import { getSeriesColor } from 'lib/colors'
-import { COUNTRY_CODE_TO_LONG_NAME, countryCodeToFlag } from 'lib/utils/geography/country'
+import { COUNTRY_CODE_TO_LONG_NAME, countryCodeToFlag } from 'lib/utils/country'
import { CountryBreakdownItem } from './LiveWebAnalyticsMetricsTypes'
import type { liveWorldMapLogicType } from './liveWorldMapLogicType'
diff --git a/frontend/src/scenes/web-analytics/WebAnalyticsDashboard.tsx b/frontend/src/scenes/web-analytics/WebAnalyticsDashboard.tsx
index deab5764ebde..6963190d6216 100644
--- a/frontend/src/scenes/web-analytics/WebAnalyticsDashboard.tsx
+++ b/frontend/src/scenes/web-analytics/WebAnalyticsDashboard.tsx
@@ -21,7 +21,7 @@ import { LemonTag } from 'lib/lemon-ui/LemonTag'
import { Link, PostHogComDocsURL } from 'lib/lemon-ui/Link/Link'
import { Popover } from 'lib/lemon-ui/Popover'
import { FeatureFlagsSet, featureFlagLogic } from 'lib/logic/featureFlagLogic'
-import { isNotNil } from 'lib/utils'
+import { isNotNil } from 'lib/utils/guards'
import { addProductIntentForCrossSell } from 'lib/utils/product-intents'
import { Scene } from 'scenes/sceneTypes'
import { QuickSurveyType } from 'scenes/surveys/quick-create/types'
diff --git a/frontend/src/scenes/web-analytics/WebAnalyticsFilters.tsx b/frontend/src/scenes/web-analytics/WebAnalyticsFilters.tsx
index 546a1a180309..42988ca03faf 100644
--- a/frontend/src/scenes/web-analytics/WebAnalyticsFilters.tsx
+++ b/frontend/src/scenes/web-analytics/WebAnalyticsFilters.tsx
@@ -26,7 +26,7 @@ import { LemonInputSelect, LemonInputSelectOption } from 'lib/lemon-ui/LemonInpu
import { LemonSegmentedSelect } from 'lib/lemon-ui/LemonSegmentedSelect'
import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
import { copyToClipboard } from 'lib/utils/copyToClipboard'
-import { COUNTRY_CODE_TO_LONG_NAME, countryCodeToFlag } from 'lib/utils/geography/country'
+import { COUNTRY_CODE_TO_LONG_NAME, countryCodeToFlag } from 'lib/utils/country'
import MaxTool from 'scenes/max/MaxTool'
import { Scene } from 'scenes/sceneTypes'
import { shareNudgeLogic } from 'scenes/web-analytics/shareNudgeLogic'
diff --git a/frontend/src/scenes/web-analytics/botAnalyticsLogic.ts b/frontend/src/scenes/web-analytics/botAnalyticsLogic.ts
index 34110b30f6c2..c8e880f06a2e 100644
--- a/frontend/src/scenes/web-analytics/botAnalyticsLogic.ts
+++ b/frontend/src/scenes/web-analytics/botAnalyticsLogic.ts
@@ -1,7 +1,7 @@
import { actions, connect, kea, listeners, path, reducers, selectors } from 'kea'
import { router } from 'kea-router'
-import { isNotNil } from 'lib/utils'
+import { isNotNil } from 'lib/utils/guards'
import {
EventsNode,
diff --git a/frontend/src/scenes/web-analytics/common.ts b/frontend/src/scenes/web-analytics/common.ts
index f10044293e16..9cdbd6f09de1 100644
--- a/frontend/src/scenes/web-analytics/common.ts
+++ b/frontend/src/scenes/web-analytics/common.ts
@@ -3,7 +3,8 @@ import { BreakPointFunction } from 'kea'
import { LemonMenuItem } from '@posthog/lemon-ui'
import { PostHogComDocsURL } from 'lib/lemon-ui/Link/Link'
-import { UnexpectedNeverError, getDefaultInterval } from 'lib/utils'
+import { getDefaultInterval } from 'lib/utils/dateFilters'
+import { UnexpectedNeverError } from 'lib/utils/guards'
import { hogqlQuery } from '~/queries/query'
import {
diff --git a/frontend/src/scenes/web-analytics/constants.ts b/frontend/src/scenes/web-analytics/constants.ts
index 088a8437288b..066d6a1c82f0 100644
--- a/frontend/src/scenes/web-analytics/constants.ts
+++ b/frontend/src/scenes/web-analytics/constants.ts
@@ -1,6 +1,7 @@
import { TaxonomicFilterGroupType } from 'lib/components/TaxonomicFilter/types'
import { dayjs } from 'lib/dayjs'
-import { dateMapping, formatDateRange } from 'lib/utils'
+import { dateMapping } from 'lib/utils/dateFilters'
+import { formatDateRange } from 'lib/utils/datetime'
import { AnyPropertyFilter, DateMappingOption, PropertyFilterType, PropertyOperator } from '~/types'
diff --git a/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/components/MarketingAnalyticsFilters/ConversionGoalModal.tsx b/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/components/MarketingAnalyticsFilters/ConversionGoalModal.tsx
index b0dec388665e..344813bb2539 100644
--- a/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/components/MarketingAnalyticsFilters/ConversionGoalModal.tsx
+++ b/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/components/MarketingAnalyticsFilters/ConversionGoalModal.tsx
@@ -5,7 +5,7 @@ import { IconChevronDown, IconChevronRight } from '@posthog/icons'
import { LemonButton, LemonInput, LemonModal } from '@posthog/lemon-ui'
import { Link } from 'lib/lemon-ui/Link'
-import { objectsEqual } from 'lib/utils'
+import { objectsEqual } from 'lib/utils/objects'
import { urls } from 'scenes/urls'
import { ConversionGoalFilter } from '~/queries/schema/schema-general'
diff --git a/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/components/settings/AttributionSettings.tsx b/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/components/settings/AttributionSettings.tsx
index bf7941684ea7..7037c36bb0ee 100644
--- a/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/components/settings/AttributionSettings.tsx
+++ b/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/components/settings/AttributionSettings.tsx
@@ -9,7 +9,7 @@ import { TeamMembershipLevel } from 'lib/constants'
import { useFeatureFlag } from 'lib/hooks/useFeatureFlag'
import { Spinner } from 'lib/lemon-ui/Spinner'
import { Tooltip } from 'lib/lemon-ui/Tooltip'
-import { debounce } from 'lib/utils'
+import { debounce } from 'lib/utils/async'
import { teamLogic } from 'scenes/teamLogic'
import { AttributionMode } from '~/queries/schema/schema-general'
diff --git a/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/components/settings/ColumnMappingModal.tsx b/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/components/settings/ColumnMappingModal.tsx
index 8feb2033ebfd..96793dcf542a 100644
--- a/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/components/settings/ColumnMappingModal.tsx
+++ b/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/components/settings/ColumnMappingModal.tsx
@@ -5,7 +5,7 @@ import { IconCheck, IconWarning, IconX } from '@posthog/icons'
import { LemonButton, LemonModal, Spinner } from '@posthog/lemon-ui'
import { LemonInputSelect, LemonInputSelectOption } from 'lib/lemon-ui/LemonInputSelect/LemonInputSelect'
-import { CURRENCY_SYMBOL_TO_NAME_MAP, IMPORTANT_CURRENCIES, OTHER_CURRENCIES } from 'lib/utils/geography/currency'
+import { CURRENCY_SYMBOL_TO_NAME_MAP, IMPORTANT_CURRENCIES, OTHER_CURRENCIES } from 'lib/utils/currency'
import {
MARKETING_ANALYTICS_SCHEMA,
diff --git a/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/components/settings/ConversionGoalsConfiguration.tsx b/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/components/settings/ConversionGoalsConfiguration.tsx
index 85febad9b911..7fe57b065234 100644
--- a/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/components/settings/ConversionGoalsConfiguration.tsx
+++ b/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/components/settings/ConversionGoalsConfiguration.tsx
@@ -7,7 +7,7 @@ import { LemonButton, LemonInput } from '@posthog/lemon-ui'
import { RestrictionScope, useRestrictedArea } from 'lib/components/RestrictedArea'
import { TeamMembershipLevel } from 'lib/constants'
import { LemonTable } from 'lib/lemon-ui/LemonTable'
-import { uuid } from 'lib/utils'
+import { uuid } from 'lib/utils/dom'
import { QUERY_TYPES_METADATA } from 'scenes/saved-insights/SavedInsights'
import { SceneSection } from '~/layout/scenes/components/SceneSection'
diff --git a/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/logic/marketingAnalyticsLogic.ts b/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/logic/marketingAnalyticsLogic.ts
index aa670cb2b585..e5f5969cb078 100644
--- a/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/logic/marketingAnalyticsLogic.ts
+++ b/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/logic/marketingAnalyticsLogic.ts
@@ -3,7 +3,8 @@ import { actionToUrl } from 'kea-router'
import { FEATURE_FLAGS } from 'lib/constants'
import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
-import { getDefaultInterval, isValidRelativeOrAbsoluteDate, updateDatesWithInterval, uuid } from 'lib/utils'
+import { getDefaultInterval, isValidRelativeOrAbsoluteDate, updateDatesWithInterval } from 'lib/utils/dateFilters'
+import { uuid } from 'lib/utils/dom'
import { teamLogic } from 'scenes/teamLogic'
import { urls } from 'scenes/urls'
import { MARKETING_ANALYTICS_DATA_COLLECTION_NODE_ID } from 'scenes/web-analytics/tabs/marketing-analytics/frontend/logic/marketingAnalyticsTilesLogic'
diff --git a/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/logic/marketingAnalyticsTableLogic.ts b/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/logic/marketingAnalyticsTableLogic.ts
index 61f82d5541b8..c57977f65012 100644
--- a/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/logic/marketingAnalyticsTableLogic.ts
+++ b/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/logic/marketingAnalyticsTableLogic.ts
@@ -1,7 +1,7 @@
import { actions, connect, kea, listeners, path, reducers, selectors } from 'kea'
import { actionToUrl, urlToAction } from 'kea-router'
-import { isNotNil } from 'lib/utils'
+import { isNotNil } from 'lib/utils/guards'
import {
ConversionGoalFilter,
diff --git a/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/logic/marketingAnalyticsTilesLogic.ts b/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/logic/marketingAnalyticsTilesLogic.ts
index c61ea774558d..d96be3f82910 100644
--- a/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/logic/marketingAnalyticsTilesLogic.ts
+++ b/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/logic/marketingAnalyticsTilesLogic.ts
@@ -1,7 +1,7 @@
import { connect, kea, path, selectors } from 'kea'
-import { isNotNil } from 'lib/utils'
-import { getCurrencySymbol } from 'lib/utils/geography/currency'
+import { getCurrencySymbol } from 'lib/utils/currency'
+import { isNotNil } from 'lib/utils/guards'
import { MARKETING_ANALYTICS_DEFAULT_QUERY_TAGS, QueryTile, TileId, loadPriorityMap } from 'scenes/web-analytics/common'
import { getDashboardItemId } from 'scenes/web-analytics/insightsUtils'
diff --git a/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/shared.tsx b/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/shared.tsx
index 907e4589a127..0f0bb039748a 100644
--- a/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/shared.tsx
+++ b/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/shared.tsx
@@ -6,9 +6,10 @@ import { LemonSegmentedButtonOption } from '@posthog/lemon-ui'
import { getColorVar } from 'lib/colors'
import { IconAreaChart, IconTrendingDown, IconTrendingFlat } from 'lib/lemon-ui/icons'
import { Tooltip } from 'lib/lemon-ui/Tooltip/Tooltip'
-import { humanFriendlyDuration, humanFriendlyLargeNumber, humanFriendlyNumber, percentage } from 'lib/utils'
-import { isNotNil } from 'lib/utils'
-import { DEFAULT_CURRENCY, getCurrencySymbol } from 'lib/utils/geography/currency'
+import { DEFAULT_CURRENCY, getCurrencySymbol } from 'lib/utils/currency'
+import { humanFriendlyDuration } from 'lib/utils/durations'
+import { isNotNil } from 'lib/utils/guards'
+import { humanFriendlyLargeNumber, humanFriendlyNumber, percentage } from 'lib/utils/numbers'
import { teamLogic } from 'scenes/teamLogic'
import { InfinityValue, MarketingAnalyticsItem, WebAnalyticsItemKind } from '~/queries/schema/schema-general'
diff --git a/frontend/src/scenes/web-analytics/tiles/WebAnalyticsErrorTracking.tsx b/frontend/src/scenes/web-analytics/tiles/WebAnalyticsErrorTracking.tsx
index 1b7c8e924e72..9d055d506cda 100644
--- a/frontend/src/scenes/web-analytics/tiles/WebAnalyticsErrorTracking.tsx
+++ b/frontend/src/scenes/web-analytics/tiles/WebAnalyticsErrorTracking.tsx
@@ -7,7 +7,7 @@ import { IconOpenInNew } from 'lib/lemon-ui/icons'
import { LemonButton } from 'lib/lemon-ui/LemonButton'
import { LemonTableLink } from 'lib/lemon-ui/LemonTable/LemonTableLink'
import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
-import { humanFriendlyLargeNumber } from 'lib/utils'
+import { humanFriendlyLargeNumber } from 'lib/utils/numbers'
import { teamLogic } from 'scenes/teamLogic'
import { urls } from 'scenes/urls'
import { ErrorTrackingTile } from 'scenes/web-analytics/common'
diff --git a/frontend/src/scenes/web-analytics/tiles/WebAnalyticsRecordings.tsx b/frontend/src/scenes/web-analytics/tiles/WebAnalyticsRecordings.tsx
index 076d03cc3c50..68e3d29c744a 100644
--- a/frontend/src/scenes/web-analytics/tiles/WebAnalyticsRecordings.tsx
+++ b/frontend/src/scenes/web-analytics/tiles/WebAnalyticsRecordings.tsx
@@ -9,7 +9,7 @@ import { LemonSkeleton } from 'lib/lemon-ui/LemonSkeleton'
import { LemonTable } from 'lib/lemon-ui/LemonTable'
import { ProfilePicture } from 'lib/lemon-ui/ProfilePicture'
import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
-import { humanFriendlyDuration } from 'lib/utils'
+import { humanFriendlyDuration } from 'lib/utils/durations'
import { asDisplay } from 'scenes/persons/person-utils'
import { ActivityScoreLabel } from 'scenes/session-recordings/components/RecordingRow'
import { sessionRecordingsPlaylistLogic } from 'scenes/session-recordings/playlist/sessionRecordingsPlaylistLogic'
diff --git a/frontend/src/scenes/web-analytics/tiles/WebAnalyticsTile.tsx b/frontend/src/scenes/web-analytics/tiles/WebAnalyticsTile.tsx
index 164a6dc47e28..f69e17d9e049 100644
--- a/frontend/src/scenes/web-analytics/tiles/WebAnalyticsTile.tsx
+++ b/frontend/src/scenes/web-analytics/tiles/WebAnalyticsTile.tsx
@@ -17,19 +17,17 @@ import { LemonButton } from 'lib/lemon-ui/LemonButton'
import { LemonSwitch } from 'lib/lemon-ui/LemonSwitch'
import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'
import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
-import {
- UnexpectedNeverError,
- capitalizeFirstLetter,
- humanFriendlyDuration,
- percentage,
- tryDecodeURIComponent,
-} from 'lib/utils'
import {
COUNTRY_CODE_TO_LONG_NAME,
LANGUAGE_CODE_TO_NAME,
countryCodeToFlag,
languageCodeToFlag,
-} from 'lib/utils/geography/country'
+} from 'lib/utils/country'
+import { humanFriendlyDuration } from 'lib/utils/durations'
+import { UnexpectedNeverError } from 'lib/utils/guards'
+import { percentage } from 'lib/utils/numbers'
+import { capitalizeFirstLetter } from 'lib/utils/strings'
+import { tryDecodeURIComponent } from 'lib/utils/url'
import { teamLogic } from 'scenes/teamLogic'
import { urls } from 'scenes/urls'
import { userLogic } from 'scenes/userLogic'
diff --git a/frontend/src/scenes/web-analytics/tiles/skeletons/ChartTileSkeleton.tsx b/frontend/src/scenes/web-analytics/tiles/skeletons/ChartTileSkeleton.tsx
index 907e17d1fac0..b6d5d4f5e288 100644
--- a/frontend/src/scenes/web-analytics/tiles/skeletons/ChartTileSkeleton.tsx
+++ b/frontend/src/scenes/web-analytics/tiles/skeletons/ChartTileSkeleton.tsx
@@ -1,5 +1,5 @@
import { LemonSkeleton } from 'lib/lemon-ui/LemonSkeleton'
-import { range } from 'lib/utils'
+import { range } from 'lib/utils/arrays'
export interface ChartTileSkeletonProps {
bars?: number
diff --git a/frontend/src/scenes/web-analytics/tiles/skeletons/TableTileSkeleton.tsx b/frontend/src/scenes/web-analytics/tiles/skeletons/TableTileSkeleton.tsx
index e6082845aa49..99dc0ae9480a 100644
--- a/frontend/src/scenes/web-analytics/tiles/skeletons/TableTileSkeleton.tsx
+++ b/frontend/src/scenes/web-analytics/tiles/skeletons/TableTileSkeleton.tsx
@@ -1,5 +1,5 @@
import { LemonSkeleton } from 'lib/lemon-ui/LemonSkeleton'
-import { range } from 'lib/utils'
+import { range } from 'lib/utils/arrays'
export interface TableTileSkeletonProps {
rows?: number
diff --git a/frontend/src/scenes/web-analytics/webAnalyticsFilterLogic.ts b/frontend/src/scenes/web-analytics/webAnalyticsFilterLogic.ts
index 493f71dfa09b..4b0d50a96338 100644
--- a/frontend/src/scenes/web-analytics/webAnalyticsFilterLogic.ts
+++ b/frontend/src/scenes/web-analytics/webAnalyticsFilterLogic.ts
@@ -1,8 +1,8 @@
import { actions, connect, kea, listeners, path, reducers, selectors } from 'kea'
import { AuthorizedUrlListType, authorizedUrlListLogic } from 'lib/components/AuthorizedUrlList/authorizedUrlListLogic'
-import { isNotNil } from 'lib/utils'
import { eventUsageLogic } from 'lib/utils/eventUsageLogic'
+import { isNotNil } from 'lib/utils/guards'
import { CompareFilter, WebAnalyticsPropertyFilter, WebAnalyticsPropertyFilters } from '~/queries/schema/schema-general'
import { PropertyFilterBaseValue, PropertyFilterType, PropertyOperator, WebAnalyticsFiltersConfig } from '~/types'
diff --git a/frontend/src/scenes/web-analytics/webAnalyticsFilterPresetsLogic.ts b/frontend/src/scenes/web-analytics/webAnalyticsFilterPresetsLogic.ts
index 04a00f67c4a9..f7f2d10d9185 100644
--- a/frontend/src/scenes/web-analytics/webAnalyticsFilterPresetsLogic.ts
+++ b/frontend/src/scenes/web-analytics/webAnalyticsFilterPresetsLogic.ts
@@ -4,7 +4,8 @@ import { router } from 'kea-router'
import api, { PaginatedResponse } from 'lib/api'
import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'
-import { objectsEqual, toParams } from 'lib/utils'
+import { objectsEqual } from 'lib/utils/objects'
+import { toParams } from 'lib/utils/url'
import { WebAnalyticsFilterPresetType } from '~/types'
diff --git a/frontend/src/scenes/web-analytics/webAnalyticsLogic.tsx b/frontend/src/scenes/web-analytics/webAnalyticsLogic.tsx
index 2baaeee0b4f3..032844c4312e 100644
--- a/frontend/src/scenes/web-analytics/webAnalyticsLogic.tsx
+++ b/frontend/src/scenes/web-analytics/webAnalyticsLogic.tsx
@@ -18,16 +18,12 @@ import { LemonButton } from 'lib/lemon-ui/LemonButton'
import { Link } from 'lib/lemon-ui/Link/Link'
import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
import { trackedActionToUrl } from 'lib/logic/scenes/trackedActionToUrl'
-import {
- UnexpectedNeverError,
- getDefaultInterval,
- isNotNil,
- isValidRelativeOrAbsoluteDate,
- objectsEqual,
-} from 'lib/utils'
+import { getDefaultInterval, isValidRelativeOrAbsoluteDate } from 'lib/utils/dateFilters'
import { isDefinitionStale } from 'lib/utils/definitions'
import { eventUsageLogic } from 'lib/utils/eventUsageLogic'
import { getCurrentTeamId } from 'lib/utils/getAppContext'
+import { UnexpectedNeverError, isNotNil } from 'lib/utils/guards'
+import { objectsEqual } from 'lib/utils/objects'
import { addProductIntentForCrossSell } from 'lib/utils/product-intents'
import { preflightLogic } from 'scenes/PreflightCheck/preflightLogic'
import { Scene } from 'scenes/sceneTypes'
diff --git a/frontend/src/toolbar/actions/SelectorCount.tsx b/frontend/src/toolbar/actions/SelectorCount.tsx
index 44ced15e1211..dda8c5e6167d 100644
--- a/frontend/src/toolbar/actions/SelectorCount.tsx
+++ b/frontend/src/toolbar/actions/SelectorCount.tsx
@@ -1,7 +1,7 @@
import { querySelectorAllDeep } from 'query-selector-shadow-dom'
import { useMemo } from 'react'
-import { pluralize } from 'lib/utils'
+import { pluralize } from 'lib/utils/strings'
interface SelectorCountProps {
selector: string | null
diff --git a/frontend/src/toolbar/actions/StepField.tsx b/frontend/src/toolbar/actions/StepField.tsx
index f691b899b52c..9d59bc84b6ab 100644
--- a/frontend/src/toolbar/actions/StepField.tsx
+++ b/frontend/src/toolbar/actions/StepField.tsx
@@ -5,7 +5,6 @@ import { LemonCheckbox } from 'lib/lemon-ui/LemonCheckbox'
import { LemonInput } from 'lib/lemon-ui/LemonInput/LemonInput'
import { LemonSegmentedButton } from 'lib/lemon-ui/LemonSegmentedButton'
import { LemonTextArea } from 'lib/lemon-ui/LemonTextArea/LemonTextArea'
-import { cssEscape } from 'lib/utils/cssEscape'
import { SelectorCount } from '~/toolbar/actions/SelectorCount'
import { ActionStepForm } from '~/toolbar/types'
@@ -37,7 +36,7 @@ function hrefSelector(step: ActionStepForm): string | null {
return null
}
- return `a[href${matchOperator}"${cssEscape(step.href)}"]`
+ return `a[href${matchOperator}"${CSS.escape(step.href)}"]`
}
export function StepField({ step, item, label, caption }: StepFieldProps): JSX.Element {
diff --git a/frontend/src/toolbar/bar/Toolbar.tsx b/frontend/src/toolbar/bar/Toolbar.tsx
index 7ff3b6151984..78a36f0054bc 100644
--- a/frontend/src/toolbar/bar/Toolbar.tsx
+++ b/frontend/src/toolbar/bar/Toolbar.tsx
@@ -35,7 +35,7 @@ import { useKeyboardHotkeys } from 'lib/hooks/useKeyboardHotkeys'
import { IconFlare, IconMenu } from 'lib/lemon-ui/icons'
import { LemonMenu, LemonMenuItem, LemonMenuItems } from 'lib/lemon-ui/LemonMenu'
import { Link } from 'lib/lemon-ui/Link'
-import { inStorybook, inStorybookTestRunner } from 'lib/utils'
+import { inStorybook, inStorybookTestRunner } from 'lib/utils/dom'
import { ActionsToolbarMenu } from '~/toolbar/actions/ActionsToolbarMenu'
import { AuthConfirmModal } from '~/toolbar/bar/AuthConfirmModal'
diff --git a/frontend/src/toolbar/bar/ToolbarButton.tsx b/frontend/src/toolbar/bar/ToolbarButton.tsx
index 075d21d2ba4f..b819caec300a 100644
--- a/frontend/src/toolbar/bar/ToolbarButton.tsx
+++ b/frontend/src/toolbar/bar/ToolbarButton.tsx
@@ -7,7 +7,7 @@ import React from 'react'
import { Tooltip } from '@posthog/lemon-ui'
-import { capitalizeFirstLetter } from 'lib/utils'
+import { capitalizeFirstLetter } from 'lib/utils/strings'
import { MenuState, toolbarLogic } from './toolbarLogic'
diff --git a/frontend/src/toolbar/debug/eventDebugMenuLogic.ts b/frontend/src/toolbar/debug/eventDebugMenuLogic.ts
index f46d573713df..2021b9ea40a8 100644
--- a/frontend/src/toolbar/debug/eventDebugMenuLogic.ts
+++ b/frontend/src/toolbar/debug/eventDebugMenuLogic.ts
@@ -1,6 +1,6 @@
import { actions, afterMount, connect, kea, path, reducers, selectors } from 'kea'
-import { uuid } from 'lib/utils'
+import { uuid } from 'lib/utils/dom'
import { permanentlyMount } from 'lib/utils/kea-logic-builders'
import { CLOUD_INTERNAL_POSTHOG_PROPERTY_KEYS } from '~/taxonomy/taxonomy'
diff --git a/frontend/src/toolbar/elements/AutocaptureElement.tsx b/frontend/src/toolbar/elements/AutocaptureElement.tsx
index f312cb5dc352..b1c9faef1420 100644
--- a/frontend/src/toolbar/elements/AutocaptureElement.tsx
+++ b/frontend/src/toolbar/elements/AutocaptureElement.tsx
@@ -1,6 +1,6 @@
import { memo } from 'react'
-import { objectsEqual } from 'lib/utils'
+import { objectsEqual } from 'lib/utils/objects'
import { ElementRect } from '~/toolbar/types'
import { EMPTY_STYLE, rectEqual } from '~/toolbar/utils'
diff --git a/frontend/src/toolbar/elements/AutocaptureElementLabel.tsx b/frontend/src/toolbar/elements/AutocaptureElementLabel.tsx
index cb316a25ac84..9e4035522dea 100644
--- a/frontend/src/toolbar/elements/AutocaptureElementLabel.tsx
+++ b/frontend/src/toolbar/elements/AutocaptureElementLabel.tsx
@@ -1,6 +1,6 @@
import { memo } from 'react'
-import { objectsEqual } from 'lib/utils'
+import { objectsEqual } from 'lib/utils/objects'
import { ElementRect } from '~/toolbar/types'
import { EMPTY_STYLE, inBounds, rectEqual } from '~/toolbar/utils'
diff --git a/frontend/src/toolbar/elements/Elements.tsx b/frontend/src/toolbar/elements/Elements.tsx
index 922dfe497b2a..7245a7145df5 100644
--- a/frontend/src/toolbar/elements/Elements.tsx
+++ b/frontend/src/toolbar/elements/Elements.tsx
@@ -3,7 +3,7 @@ import { Fragment, memo } from 'react'
import { HeatmapCanvas } from 'lib/components/heatmaps/HeatmapCanvas'
import { useShiftKeyPressed } from 'lib/components/heatmaps/useShiftKeyPressed'
-import { compactNumber } from 'lib/utils'
+import { compactNumber } from 'lib/utils/numbers'
import { AutocaptureElement } from '~/toolbar/elements/AutocaptureElement'
import { AutocaptureElementLabel } from '~/toolbar/elements/AutocaptureElementLabel'
diff --git a/frontend/src/toolbar/elements/domElementIndex.test.ts b/frontend/src/toolbar/elements/domElementIndex.test.ts
index 10dc06aef37c..b68549e48a8e 100644
--- a/frontend/src/toolbar/elements/domElementIndex.test.ts
+++ b/frontend/src/toolbar/elements/domElementIndex.test.ts
@@ -1,6 +1,6 @@
import { collectAllElementsDeep, querySelectorAllDeep } from 'query-selector-shadow-dom'
-import { elementToSelector } from 'lib/actionUtils'
+import { elementToSelector } from 'lib/utils/actions'
import { CountedHTMLElement, ElementsEventType } from '~/toolbar/types'
diff --git a/frontend/src/toolbar/elements/domElementIndex.ts b/frontend/src/toolbar/elements/domElementIndex.ts
index 559b5216ff31..b4fa5a04005e 100644
--- a/frontend/src/toolbar/elements/domElementIndex.ts
+++ b/frontend/src/toolbar/elements/domElementIndex.ts
@@ -1,4 +1,4 @@
-import { matchesDataAttribute } from 'lib/actionUtils'
+import { matchesDataAttribute } from 'lib/utils/actions'
import { CountedHTMLElement, ElementsEventType } from '~/toolbar/types'
import { ElementType } from '~/types'
diff --git a/frontend/src/toolbar/elements/elementsLogic.ts b/frontend/src/toolbar/elements/elementsLogic.ts
index 1a7db6f86c1b..ab44b049c103 100644
--- a/frontend/src/toolbar/elements/elementsLogic.ts
+++ b/frontend/src/toolbar/elements/elementsLogic.ts
@@ -1,8 +1,8 @@
import { actions, connect, events, kea, listeners, path, reducers, selectors } from 'kea'
import { collectAllElementsDeep } from 'query-selector-shadow-dom'
-import { EXPERIMENT_TARGET_SELECTOR } from 'lib/actionUtils'
-import { debounce } from 'lib/utils'
+import { EXPERIMENT_TARGET_SELECTOR } from 'lib/utils/actions'
+import { debounce } from 'lib/utils/async'
import { actionsLogic } from '~/toolbar/actions/actionsLogic'
import { actionsTabLogic } from '~/toolbar/actions/actionsTabLogic'
diff --git a/frontend/src/toolbar/elements/heatmapToolbarMenuLogic.ts b/frontend/src/toolbar/elements/heatmapToolbarMenuLogic.ts
index b8e3e0381cd1..6a056e4b00ea 100644
--- a/frontend/src/toolbar/elements/heatmapToolbarMenuLogic.ts
+++ b/frontend/src/toolbar/elements/heatmapToolbarMenuLogic.ts
@@ -6,9 +6,9 @@ import { windowValues } from 'kea-window-values'
import { PostHog } from 'posthog-js'
import { collectAllElementsDeep, querySelectorAllDeep } from 'query-selector-shadow-dom'
-import { elementToSelector } from 'lib/actionUtils'
import type { PaginatedResponse } from 'lib/api'
import { heatmapDataLogic } from 'lib/components/heatmaps/heatmapDataLogic'
+import { elementToSelector } from 'lib/utils/actions'
import { createVersionChecker } from 'lib/utils/semver'
import { DOMIndex, buildDOMIndex, matchEventToElementUsingIndex } from '~/toolbar/elements/domElementIndex'
diff --git a/frontend/src/toolbar/experiments/experimentsTabLogic.test.ts b/frontend/src/toolbar/experiments/experimentsTabLogic.test.ts
index 7b0902a98acd..b2bc11dc7aa1 100644
--- a/frontend/src/toolbar/experiments/experimentsTabLogic.test.ts
+++ b/frontend/src/toolbar/experiments/experimentsTabLogic.test.ts
@@ -1,7 +1,7 @@
import { router } from 'kea-router'
import { expectLogic } from 'kea-test-utils'
-import { EXPERIMENT_TARGET_SELECTOR } from 'lib/actionUtils'
+import { EXPERIMENT_TARGET_SELECTOR } from 'lib/utils/actions'
jest.mock('lib/lemon-ui/LemonToast/LemonToast', () => ({
lemonToast: { success: jest.fn(), error: jest.fn() },
diff --git a/frontend/src/toolbar/experiments/experimentsTabLogic.tsx b/frontend/src/toolbar/experiments/experimentsTabLogic.tsx
index e282861fed2a..60cb42cb533c 100644
--- a/frontend/src/toolbar/experiments/experimentsTabLogic.tsx
+++ b/frontend/src/toolbar/experiments/experimentsTabLogic.tsx
@@ -2,8 +2,8 @@ import { actions, connect, events, kea, listeners, path, reducers, selectors } f
import { forms } from 'kea-forms'
import { subscriptions } from 'kea-subscriptions'
-import { EXPERIMENT_TARGET_SELECTOR } from 'lib/actionUtils'
import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'
+import { EXPERIMENT_TARGET_SELECTOR } from 'lib/utils/actions'
import { isLaunched } from 'scenes/experiments/experimentsLogic'
import { urls } from 'scenes/urls'
diff --git a/frontend/src/toolbar/product-tours/elementInference.ts b/frontend/src/toolbar/product-tours/elementInference.ts
index 4d39cf39114f..0c2828656cf8 100644
--- a/frontend/src/toolbar/product-tours/elementInference.ts
+++ b/frontend/src/toolbar/product-tours/elementInference.ts
@@ -1,6 +1,6 @@
import { querySelectorAllDeep } from 'query-selector-shadow-dom'
-import { TAGS_TO_IGNORE } from 'lib/actionUtils'
+import { TAGS_TO_IGNORE } from 'lib/utils/actions'
import { toolbarLogger } from '~/toolbar/toolbarLogger'
import { captureToolbarException } from '~/toolbar/toolbarPosthogJS'
diff --git a/frontend/src/toolbar/product-tours/productToursLogic.ts b/frontend/src/toolbar/product-tours/productToursLogic.ts
index 7cb44d56dd77..6943db9cbd8a 100644
--- a/frontend/src/toolbar/product-tours/productToursLogic.ts
+++ b/frontend/src/toolbar/product-tours/productToursLogic.ts
@@ -6,7 +6,7 @@ import { subscriptions } from 'kea-subscriptions'
import { findElement } from 'posthog-js/dist/element-inference'
import { lemonToast } from 'lib/lemon-ui/LemonToast'
-import { uuid } from 'lib/utils'
+import { uuid } from 'lib/utils/dom'
import { ProductTourEvent } from 'scenes/product-tours/constants'
import { DEFAULT_APPEARANCE } from 'scenes/product-tours/constants'
import { prepareStepForRender, prepareStepsForRender } from 'scenes/product-tours/editor/generateStepHtml'
diff --git a/frontend/src/toolbar/utils.ts b/frontend/src/toolbar/utils.ts
index cce89f7c1a98..b52a4ba8a7b9 100644
--- a/frontend/src/toolbar/utils.ts
+++ b/frontend/src/toolbar/utils.ts
@@ -2,8 +2,7 @@ import { finder } from '@medv/finder'
import { querySelectorAllDeep } from 'query-selector-shadow-dom'
import { CSSProperties } from 'react'
-import { CLICK_TARGETS, CLICK_TARGET_SELECTOR, TAGS_TO_IGNORE, escapeRegex } from 'lib/actionUtils'
-import { cssEscape } from 'lib/utils/cssEscape'
+import { CLICK_TARGETS, CLICK_TARGET_SELECTOR, TAGS_TO_IGNORE, escapeRegex } from 'lib/utils/actions'
import { patch } from '~/toolbar/patch'
import { toolbarLogger } from '~/toolbar/toolbarLogger'
@@ -146,7 +145,7 @@ function computeElementQuery(element: HTMLElement, dataAttributes: string[]): st
continue
}
- const escapedSelector = `[${cssEscape(name)}="${cssEscape(value)}"]`
+ const escapedSelector = `[${CSS.escape(name)}="${CSS.escape(value)}"]`
const unescapedSelector = `[${name}="${value}"]`
if (querySelectorAllDeep(escapedSelector).length == 1) {
@@ -407,7 +406,7 @@ export function getElementForStep(step: ActionStepForm, allElements?: HTMLElemen
}
if (step.href && (step.href_selected || typeof step.href_selected === 'undefined')) {
- selector += `[href="${cssEscape(step.href)}"]`
+ selector += `[href="${CSS.escape(step.href)}"]`
}
const hasText = step.text && step.text.trim() && (step.text_selected || typeof step.text_selected === 'undefined')
diff --git a/frontend/src/toolbar/web-vitals/WebVitalsToolbarMenu.tsx b/frontend/src/toolbar/web-vitals/WebVitalsToolbarMenu.tsx
index 72b8a0bb42e2..5da1b0bb49d0 100644
--- a/frontend/src/toolbar/web-vitals/WebVitalsToolbarMenu.tsx
+++ b/frontend/src/toolbar/web-vitals/WebVitalsToolbarMenu.tsx
@@ -2,7 +2,7 @@ import { useValues } from 'kea'
import { LemonBanner, Link, Spinner, Tooltip } from '@posthog/lemon-ui'
-import { inStorybook, inStorybookTestRunner } from 'lib/utils'
+import { inStorybook, inStorybookTestRunner } from 'lib/utils/dom'
import { urls } from 'scenes/urls'
import {
diff --git a/frontend/src/toolbar/web-vitals/webVitalsToolbarLogic.ts b/frontend/src/toolbar/web-vitals/webVitalsToolbarLogic.ts
index e2d63bca8341..55224b6ca7d2 100644
--- a/frontend/src/toolbar/web-vitals/webVitalsToolbarLogic.ts
+++ b/frontend/src/toolbar/web-vitals/webVitalsToolbarLogic.ts
@@ -2,7 +2,7 @@ import { actions, afterMount, connect, kea, path, reducers } from 'kea'
import { loaders } from 'kea-loaders'
import { encodeParams, router, urlToAction } from 'kea-router'
-import { inStorybook, inStorybookTestRunner } from 'lib/utils'
+import { inStorybook, inStorybookTestRunner } from 'lib/utils/dom'
import { permanentlyMount } from 'lib/utils/kea-logic-builders'
import { WebVitalsMetric } from '~/queries/schema/schema-general'
diff --git a/playwright/e2e/early-access-management.spec.ts b/playwright/e2e/early-access-management.spec.ts
index 4bac3757c52a..ad6c234595aa 100644
--- a/playwright/e2e/early-access-management.spec.ts
+++ b/playwright/e2e/early-access-management.spec.ts
@@ -1,4 +1,4 @@
-import { delay } from 'lib/utils'
+import { delay } from 'lib/utils/async'
import { randomString } from '../utils'
import { PlaywrightWorkspaceSetupResult, expect, test } from '../utils/workspace-test-base'
diff --git a/playwright/page-models/cohortPage.ts b/playwright/page-models/cohortPage.ts
index 11b253235852..b6945dea7fee 100644
--- a/playwright/page-models/cohortPage.ts
+++ b/playwright/page-models/cohortPage.ts
@@ -1,6 +1,6 @@
import { Page } from '@playwright/test'
-import { delay } from 'lib/utils'
+import { delay } from 'lib/utils/async'
import { expect } from '../utils/workspace-test-base'
diff --git a/products/actions/frontend/components/ActionsTable.tsx b/products/actions/frontend/components/ActionsTable.tsx
index 42f073379741..6448d334ccb4 100644
--- a/products/actions/frontend/components/ActionsTable.tsx
+++ b/products/actions/frontend/components/ActionsTable.tsx
@@ -17,7 +17,7 @@ import { createdAtColumn, createdByColumn } from 'lib/lemon-ui/LemonTable/column
import { LemonTableLink } from 'lib/lemon-ui/LemonTable/LemonTableLink'
import { LemonTableColumn, LemonTableColumns } from 'lib/lemon-ui/LemonTable/types'
import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
-import { stripHTTP } from 'lib/utils'
+import { stripHTTP } from 'lib/utils/url'
import { teamLogic } from 'scenes/teamLogic'
import { urls } from 'scenes/urls'
import { userLogic } from 'scenes/userLogic'
diff --git a/products/ai_observability/frontend/AIObservabilityScene.tsx b/products/ai_observability/frontend/AIObservabilityScene.tsx
index 54be1e5956c0..37535810dac0 100644
--- a/products/ai_observability/frontend/AIObservabilityScene.tsx
+++ b/products/ai_observability/frontend/AIObservabilityScene.tsx
@@ -17,7 +17,7 @@ import { dayjs } from 'lib/dayjs'
import { Tooltip } from 'lib/lemon-ui/Tooltip'
import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
import { useAttachedLogic } from 'lib/logic/scenes/useAttachedLogic'
-import { objectsEqual } from 'lib/utils'
+import { objectsEqual } from 'lib/utils/objects'
import { EventDetails } from 'scenes/activity/explore/EventDetails'
import { Dashboard } from 'scenes/dashboard/Dashboard'
import { dashboardLogic } from 'scenes/dashboard/dashboardLogic'
diff --git a/products/ai_observability/frontend/AIObservabilityTools.tsx b/products/ai_observability/frontend/AIObservabilityTools.tsx
index beeaa13174a5..6b3b655aa542 100644
--- a/products/ai_observability/frontend/AIObservabilityTools.tsx
+++ b/products/ai_observability/frontend/AIObservabilityTools.tsx
@@ -3,12 +3,12 @@ import { combineUrl, router } from 'kea-router'
import { IconGraph, IconRetentionHeatmap, IconTrends, IconUserPaths } from '@posthog/icons'
-import { escapeRegex } from 'lib/actionUtils'
import { FEATURE_FLAGS } from 'lib/constants'
import { LemonButton } from 'lib/lemon-ui/LemonButton'
import { Link } from 'lib/lemon-ui/Link'
import { Tooltip } from 'lib/lemon-ui/Tooltip'
import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
+import { escapeRegex } from 'lib/utils/actions'
import { urls } from 'scenes/urls'
import { DataTable } from '~/queries/nodes/DataTable/DataTable'
diff --git a/products/ai_observability/frontend/AIObservabilityTraceScene.tsx b/products/ai_observability/frontend/AIObservabilityTraceScene.tsx
index 7c5c6885155b..2ac5804a04ba 100644
--- a/products/ai_observability/frontend/AIObservabilityTraceScene.tsx
+++ b/products/ai_observability/frontend/AIObservabilityTraceScene.tsx
@@ -48,7 +48,7 @@ import { useKeyboardHotkeys } from 'lib/hooks/useKeyboardHotkeys'
import { IconWithCount } from 'lib/lemon-ui/icons/icons'
import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
import { useAttachedLogic } from 'lib/logic/scenes/useAttachedLogic'
-import { identifierToHuman, pluralize } from 'lib/utils'
+import { identifierToHuman, pluralize } from 'lib/utils/strings'
import { InsightEmptyState, InsightErrorState } from 'scenes/insights/EmptyStates'
import { PersonDisplay } from 'scenes/persons/PersonDisplay'
import { SceneExport } from 'scenes/sceneTypes'
diff --git a/products/ai_observability/frontend/ConversationDisplay/ConversationMessagesDisplay.tsx b/products/ai_observability/frontend/ConversationDisplay/ConversationMessagesDisplay.tsx
index 12c6d8d0a8d7..c39708c865b3 100644
--- a/products/ai_observability/frontend/ConversationDisplay/ConversationMessagesDisplay.tsx
+++ b/products/ai_observability/frontend/ConversationDisplay/ConversationMessagesDisplay.tsx
@@ -9,7 +9,7 @@ import { CopyToClipboardInline } from 'lib/components/CopyToClipboard'
import { HighlightedJSONViewer } from 'lib/components/HighlightedJSONViewer'
import { IconExclamation, IconEyeHidden } from 'lib/lemon-ui/icons'
import { LemonMarkdown } from 'lib/lemon-ui/LemonMarkdown'
-import { isObject } from 'lib/utils'
+import { isObject } from 'lib/utils/guards'
import { getJsonContainerForDisplay, JSONValueDisplay } from '../components/JSONValueDisplay'
import { MessageSentimentBar } from '../components/SentimentTag'
diff --git a/products/ai_observability/frontend/ConversationDisplay/EvaluationDisplay.tsx b/products/ai_observability/frontend/ConversationDisplay/EvaluationDisplay.tsx
index 5bef3fec34ea..95b77f3da567 100644
--- a/products/ai_observability/frontend/ConversationDisplay/EvaluationDisplay.tsx
+++ b/products/ai_observability/frontend/ConversationDisplay/EvaluationDisplay.tsx
@@ -1,7 +1,7 @@
import { IconCheck, IconMinus, IconX } from '@posthog/icons'
import { LemonTag, Link } from '@posthog/lemon-ui'
-import { lowercaseFirstLetter } from 'lib/utils'
+import { lowercaseFirstLetter } from 'lib/utils/strings'
import { urls } from 'scenes/urls'
import { EventType } from '~/types'
diff --git a/products/ai_observability/frontend/ConversationDisplay/MetadataHeader.tsx b/products/ai_observability/frontend/ConversationDisplay/MetadataHeader.tsx
index bdd7d2546a1d..aa19b338f72c 100644
--- a/products/ai_observability/frontend/ConversationDisplay/MetadataHeader.tsx
+++ b/products/ai_observability/frontend/ConversationDisplay/MetadataHeader.tsx
@@ -3,7 +3,7 @@ import clsx from 'clsx'
import { LemonTag } from '@posthog/lemon-ui'
import { dayjs } from 'lib/dayjs'
-import { lowercaseFirstLetter } from 'lib/utils'
+import { lowercaseFirstLetter } from 'lib/utils/strings'
import { CostBreakdownTooltip } from '../components/CostBreakdownTooltip'
import { MetadataTag } from '../components/MetadataTag'
diff --git a/products/ai_observability/frontend/ConversationDisplay/TagDisplay.tsx b/products/ai_observability/frontend/ConversationDisplay/TagDisplay.tsx
index e88bb2cde9d6..0b61a678a0be 100644
--- a/products/ai_observability/frontend/ConversationDisplay/TagDisplay.tsx
+++ b/products/ai_observability/frontend/ConversationDisplay/TagDisplay.tsx
@@ -1,6 +1,6 @@
import { LemonTag, Link } from '@posthog/lemon-ui'
-import { lowercaseFirstLetter } from 'lib/utils'
+import { lowercaseFirstLetter } from 'lib/utils/strings'
import { urls } from 'scenes/urls'
import { EventType } from '~/types'
diff --git a/products/ai_observability/frontend/aiObservabilitySessionLogic.test.ts b/products/ai_observability/frontend/aiObservabilitySessionLogic.test.ts
index b01d287645c1..75545d2d295d 100644
--- a/products/ai_observability/frontend/aiObservabilitySessionLogic.test.ts
+++ b/products/ai_observability/frontend/aiObservabilitySessionLogic.test.ts
@@ -3,7 +3,7 @@ import { MOCK_TEAM_ID } from 'lib/api.mock'
import { combineUrl, router } from 'kea-router'
import { expectLogic } from 'kea-test-utils'
-import { addProjectIdIfMissing } from 'lib/utils/router-utils'
+import { addProjectIdIfMissing } from 'lib/utils/kea-router'
import { sceneLogic } from 'scenes/sceneLogic'
import { urls } from 'scenes/urls'
diff --git a/products/ai_observability/frontend/aiObservabilitySharedLogic.ts b/products/ai_observability/frontend/aiObservabilitySharedLogic.ts
index 9f239643e8c9..a7bbebf07f85 100644
--- a/products/ai_observability/frontend/aiObservabilitySharedLogic.ts
+++ b/products/ai_observability/frontend/aiObservabilitySharedLogic.ts
@@ -5,8 +5,7 @@ import { router, urlToAction } from 'kea-router'
import { SetupTaskId, globalSetupLogic } from 'lib/components/ProductSetup'
import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
import { trackedActionToUrl } from 'lib/logic/scenes/trackedActionToUrl'
-import { objectsEqual } from 'lib/utils'
-import { hasRecentAIEvents } from 'lib/utils/aiEventsUtils'
+import { objectsEqual } from 'lib/utils/objects'
import { sceneLogic } from 'scenes/sceneLogic'
import { filterTestAccountsDefaultsLogic } from 'scenes/settings/environment/filterTestAccountDefaultsLogic'
import { teamLogic } from 'scenes/teamLogic'
@@ -20,6 +19,7 @@ import { AnyPropertyFilter, Breadcrumb } from '~/types'
import type { aiObservabilitySharedLogicType } from './aiObservabilitySharedLogicType'
import { AI_OBSERVABILITY_CLUSTER_URL_PATTERN } from './clusters/constants'
import { parserRecipesLogic } from './settings/parserRecipesLogic'
+import { hasRecentAIEvents } from './utils/aiEvents'
export const AI_OBSERVABILITY_DATA_COLLECTION_NODE_ID = 'ai-observability-data'
diff --git a/products/ai_observability/frontend/aiObservabilityTraceLogic.test.ts b/products/ai_observability/frontend/aiObservabilityTraceLogic.test.ts
index 8b09bc370b02..ee4f669ced23 100644
--- a/products/ai_observability/frontend/aiObservabilityTraceLogic.test.ts
+++ b/products/ai_observability/frontend/aiObservabilityTraceLogic.test.ts
@@ -3,7 +3,7 @@ import { MOCK_TEAM_ID } from 'lib/api.mock'
import { combineUrl, router } from 'kea-router'
import { expectLogic } from 'kea-test-utils'
-import { addProjectIdIfMissing } from 'lib/utils/router-utils'
+import { addProjectIdIfMissing } from 'lib/utils/kea-router'
import { sceneLogic } from 'scenes/sceneLogic'
import { urls } from 'scenes/urls'
diff --git a/products/ai_observability/frontend/components/EvalResultBadges.tsx b/products/ai_observability/frontend/components/EvalResultBadges.tsx
index 9271a02c3fb0..a12b91d0df51 100644
--- a/products/ai_observability/frontend/components/EvalResultBadges.tsx
+++ b/products/ai_observability/frontend/components/EvalResultBadges.tsx
@@ -4,7 +4,7 @@ import { IconCheck, IconMinus, IconWarning, IconX } from '@posthog/icons'
import { LemonSkeleton, LemonTag, LemonTagProps, Tooltip } from '@posthog/lemon-ui'
import { dayjs } from 'lib/dayjs'
-import { pluralize } from 'lib/utils'
+import { pluralize } from 'lib/utils/strings'
import { TraceViewMode, aiObservabilityTraceLogic } from '../aiObservabilityTraceLogic'
import { EvaluationRun } from '../evaluations/types'
diff --git a/products/ai_observability/frontend/components/JSONValueDisplay.tsx b/products/ai_observability/frontend/components/JSONValueDisplay.tsx
index 6bdbb9986335..ec59fbed6902 100644
--- a/products/ai_observability/frontend/components/JSONValueDisplay.tsx
+++ b/products/ai_observability/frontend/components/JSONValueDisplay.tsx
@@ -1,5 +1,5 @@
import { HighlightedJSONViewer } from 'lib/components/HighlightedJSONViewer'
-import { isObject } from 'lib/utils'
+import { isObject } from 'lib/utils/guards'
import { isEmptyJSONStructure, parsePartialJSON, safeStringify } from '../utils'
diff --git a/products/ai_observability/frontend/components/MetricTag.tsx b/products/ai_observability/frontend/components/MetricTag.tsx
index 13a394e95d98..c2fd0051430c 100644
--- a/products/ai_observability/frontend/components/MetricTag.tsx
+++ b/products/ai_observability/frontend/components/MetricTag.tsx
@@ -1,7 +1,7 @@
import { LemonTag } from '@posthog/lemon-ui'
import { CopyToClipboardInline } from 'lib/components/CopyToClipboard'
-import { identifierToHuman } from 'lib/utils'
+import { identifierToHuman } from 'lib/utils/strings'
interface MetricTagProps {
properties: Record<string, any>
diff --git a/products/ai_observability/frontend/datasets/SaveToDatasetButton.tsx b/products/ai_observability/frontend/datasets/SaveToDatasetButton.tsx
index 109c4db0e92a..2710a0c3cb10 100644
--- a/products/ai_observability/frontend/datasets/SaveToDatasetButton.tsx
+++ b/products/ai_observability/frontend/datasets/SaveToDatasetButton.tsx
@@ -8,7 +8,7 @@ import { LemonButton, LemonDivider, LemonDropdown, LemonInput, LemonSkeleton } f
import { AccessControlAction } from 'lib/components/AccessControlAction'
import { LemonField } from 'lib/lemon-ui/LemonField'
-import { isObject } from 'lib/utils'
+import { isObject } from 'lib/utils/guards'
import { urls } from 'scenes/urls'
import { AccessControlLevel, AccessControlResourceType, DatasetItem } from '~/types'
diff --git a/products/ai_observability/frontend/datasets/aiObservabilityDatasetLogic.ts b/products/ai_observability/frontend/datasets/aiObservabilityDatasetLogic.ts
index d0cb2f2f3512..cffbffba384e 100644
--- a/products/ai_observability/frontend/datasets/aiObservabilityDatasetLogic.ts
+++ b/products/ai_observability/frontend/datasets/aiObservabilityDatasetLogic.ts
@@ -3,11 +3,12 @@ import { forms } from 'kea-forms'
import { loaders } from 'kea-loaders'
import { combineUrl, router, urlToAction } from 'kea-router'
+import { objectsEqual } from 'lib/utils/objects'
+
import api, { CountedPaginatedResponse } from '~/lib/api'
import { lemonToast } from '~/lib/lemon-ui/LemonToast/LemonToast'
import { PaginationManual } from '~/lib/lemon-ui/PaginationControl'
import { trackedActionToUrl } from '~/lib/logic/scenes/trackedActionToUrl'
-import { objectsEqual } from '~/lib/utils'
import { ProductIntentContext, ProductKey } from '~/queries/schema/schema-general'
import { sceneLogic } from '~/scenes/sceneLogic'
import { teamLogic } from '~/scenes/teamLogic'
diff --git a/products/ai_observability/frontend/datasets/aiObservabilityDatasetsLogic.ts b/products/ai_observability/frontend/datasets/aiObservabilityDatasetsLogic.ts
index bd708f5bb0a9..ceba42aea581 100644
--- a/products/ai_observability/frontend/datasets/aiObservabilityDatasetsLogic.ts
+++ b/products/ai_observability/frontend/datasets/aiObservabilityDatasetsLogic.ts
@@ -2,12 +2,14 @@ import { actions, afterMount, kea, listeners, path, props, reducers, selectors }
import { loaders } from 'kea-loaders'
import { router, urlToAction } from 'kea-router'
+import { objectsEqual } from 'lib/utils/objects'
+import { pluralize } from 'lib/utils/strings'
+
import api, { CountedPaginatedResponse } from '~/lib/api'
import { Sorting } from '~/lib/lemon-ui/LemonTable'
import { lemonToast } from '~/lib/lemon-ui/LemonToast/LemonToast'
import { PaginationManual } from '~/lib/lemon-ui/PaginationControl'
import { trackedActionToUrl } from '~/lib/logic/scenes/trackedActionToUrl'
-import { objectsEqual, pluralize } from '~/lib/utils'
import { sceneLogic } from '~/scenes/sceneLogic'
import { urls } from '~/scenes/urls'
import { Dataset } from '~/types'
diff --git a/products/ai_observability/frontend/evaluations/AIObservabilityEvaluationsScene.tsx b/products/ai_observability/frontend/evaluations/AIObservabilityEvaluationsScene.tsx
index a84a8c85ef9a..8ff983da9d8f 100644
--- a/products/ai_observability/frontend/evaluations/AIObservabilityEvaluationsScene.tsx
+++ b/products/ai_observability/frontend/evaluations/AIObservabilityEvaluationsScene.tsx
@@ -22,7 +22,7 @@ import { LemonTableColumns } from 'lib/lemon-ui/LemonTable'
import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
import { useAttachedLogic } from 'lib/logic/scenes/useAttachedLogic'
import { deleteWithUndo } from 'lib/utils/deleteWithUndo'
-import { removeProjectIdIfPresent } from 'lib/utils/router-utils'
+import { removeProjectIdIfPresent } from 'lib/utils/kea-router'
import { SceneExport } from 'scenes/sceneTypes'
import { teamLogic } from 'scenes/teamLogic'
import { urls } from 'scenes/urls'
diff --git a/products/ai_observability/frontend/evaluations/offlineEvaluationsLogic.ts b/products/ai_observability/frontend/evaluations/offlineEvaluationsLogic.ts
index d92c4e64cf46..2393ffb5de7e 100644
--- a/products/ai_observability/frontend/evaluations/offlineEvaluationsLogic.ts
+++ b/products/ai_observability/frontend/evaluations/offlineEvaluationsLogic.ts
@@ -4,8 +4,8 @@ import { router, urlToAction } from 'kea-router'
import api from 'lib/api'
import { trackedActionToUrl } from 'lib/logic/scenes/trackedActionToUrl'
-import { dateStringToDayJs, isValidRelativeOrAbsoluteDate } from 'lib/utils'
-import { removeProjectIdIfPresent } from 'lib/utils/router-utils'
+import { dateStringToDayJs, isValidRelativeOrAbsoluteDate } from 'lib/utils/dateFilters'
+import { removeProjectIdIfPresent } from 'lib/utils/kea-router'
import { urls } from 'scenes/urls'
import { getCurrentTeamId } from '~/lib/utils/getAppContext'
diff --git a/products/ai_observability/frontend/playground/AIObservabilityPlaygroundScene.tsx b/products/ai_observability/frontend/playground/AIObservabilityPlaygroundScene.tsx
index 4403cf5ac306..633664b76a06 100644
--- a/products/ai_observability/frontend/playground/AIObservabilityPlaygroundScene.tsx
+++ b/products/ai_observability/frontend/playground/AIObservabilityPlaygroundScene.tsx
@@ -34,8 +34,8 @@ import { AnimatedCollapsible } from 'lib/components/AnimatedCollapsible'
import { LemonMarkdown } from 'lib/lemon-ui/LemonMarkdown'
import { useAttachedLogic } from 'lib/logic/scenes/useAttachedLogic'
import { CodeEditorResizeable } from 'lib/monaco/CodeEditorResizable'
-import { humanFriendlyDuration } from 'lib/utils'
import { copyToClipboard } from 'lib/utils/copyToClipboard'
+import { humanFriendlyDuration } from 'lib/utils/durations'
import { sceneConfigurations } from 'scenes/scenes'
import { Scene, SceneExport } from 'scenes/sceneTypes'
import { urls } from 'scenes/urls'
diff --git a/products/ai_observability/frontend/playground/llmPlaygroundPromptsLogic.ts b/products/ai_observability/frontend/playground/llmPlaygroundPromptsLogic.ts
index c6f237c8ad7a..b3c0ea0e1c2f 100644
--- a/products/ai_observability/frontend/playground/llmPlaygroundPromptsLogic.ts
+++ b/products/ai_observability/frontend/playground/llmPlaygroundPromptsLogic.ts
@@ -5,7 +5,8 @@ import posthog from 'posthog-js'
import { lemonToast } from '@posthog/lemon-ui'
import api from 'lib/api'
-import { isObject, uuid } from 'lib/utils'
+import { uuid } from 'lib/utils/dom'
+import { isObject } from 'lib/utils/guards'
import { teamLogic } from 'scenes/teamLogic'
import { urls } from 'scenes/urls'
diff --git a/products/ai_observability/frontend/playground/llmPlaygroundRunLogic.ts b/products/ai_observability/frontend/playground/llmPlaygroundRunLogic.ts
index 3d21cc96dee9..4cec67b5cc6a 100644
--- a/products/ai_observability/frontend/playground/llmPlaygroundRunLogic.ts
+++ b/products/ai_observability/frontend/playground/llmPlaygroundRunLogic.ts
@@ -5,7 +5,7 @@ import { lemonToast } from '@posthog/lemon-ui'
import api, { ApiError, RateLimitError } from 'lib/api'
import { SetupTaskId, globalSetupLogic } from 'lib/components/ProductSetup'
-import { uuid } from 'lib/utils'
+import { uuid } from 'lib/utils/dom'
import type { ModelOption } from '../modelPickerLogic'
import { llmProviderKeysLogic } from '../settings/llmProviderKeysLogic'
diff --git a/products/ai_observability/frontend/prompts/llmPromptsLogic.ts b/products/ai_observability/frontend/prompts/llmPromptsLogic.ts
index 0ab058295296..c49960137f22 100644
--- a/products/ai_observability/frontend/prompts/llmPromptsLogic.ts
+++ b/products/ai_observability/frontend/prompts/llmPromptsLogic.ts
@@ -2,12 +2,13 @@ import { actions, afterMount, kea, listeners, path, props, reducers, selectors }
import { loaders } from 'kea-loaders'
import { router, urlToAction } from 'kea-router'
+import { objectsEqual } from 'lib/utils/objects'
+
import api, { CountedPaginatedResponse } from '~/lib/api'
import { Sorting } from '~/lib/lemon-ui/LemonTable'
import { lemonToast } from '~/lib/lemon-ui/LemonToast/LemonToast'
import { PaginationManual } from '~/lib/lemon-ui/PaginationControl'
import { trackedActionToUrl } from '~/lib/logic/scenes/trackedActionToUrl'
-import { objectsEqual } from '~/lib/utils'
import { sceneLogic } from '~/scenes/sceneLogic'
import { urls } from '~/scenes/urls'
import { LLMPrompt } from '~/types'
diff --git a/products/ai_observability/frontend/reviewQueues/aiObservabilityReviewQueuesLogic.test.ts b/products/ai_observability/frontend/reviewQueues/aiObservabilityReviewQueuesLogic.test.ts
index 565cc3a690a9..00a6254dbaab 100644
--- a/products/ai_observability/frontend/reviewQueues/aiObservabilityReviewQueuesLogic.test.ts
+++ b/products/ai_observability/frontend/reviewQueues/aiObservabilityReviewQueuesLogic.test.ts
@@ -3,7 +3,7 @@ import { MOCK_DEFAULT_TEAM, MOCK_TEAM_ID } from '~/lib/api.mock'
import { combineUrl, router } from 'kea-router'
import { expectLogic } from 'kea-test-utils'
-import { addProjectIdIfMissing } from 'lib/utils/router-utils'
+import { addProjectIdIfMissing } from 'lib/utils/kea-router'
import { urls } from 'scenes/urls'
import { initKeaTests } from '~/test/init'
diff --git a/products/ai_observability/frontend/reviewQueues/aiObservabilityReviewQueuesLogic.ts b/products/ai_observability/frontend/reviewQueues/aiObservabilityReviewQueuesLogic.ts
index d2f507eead15..5a1c8bb2ac43 100644
--- a/products/ai_observability/frontend/reviewQueues/aiObservabilityReviewQueuesLogic.ts
+++ b/products/ai_observability/frontend/reviewQueues/aiObservabilityReviewQueuesLogic.ts
@@ -5,11 +5,12 @@ import { router, urlToAction } from 'kea-router'
import { LemonDialog } from '@posthog/lemon-ui'
import { Sorting } from 'lib/lemon-ui/LemonTable'
+import { objectsEqual } from 'lib/utils/objects'
+import { pluralize } from 'lib/utils/strings'
import { lemonToast } from '~/lib/lemon-ui/LemonToast/LemonToast'
import { PaginationManual } from '~/lib/lemon-ui/PaginationControl'
import { trackedActionToUrl } from '~/lib/logic/scenes/trackedActionToUrl'
-import { objectsEqual, pluralize } from '~/lib/utils'
import { urls } from '~/scenes/urls'
import type {
diff --git a/products/ai_observability/frontend/scoreDefinitions/aiObservabilityScoreDefinitionsLogic.ts b/products/ai_observability/frontend/scoreDefinitions/aiObservabilityScoreDefinitionsLogic.ts
index ddc41d39e67e..ba71c928f5c4 100644
--- a/products/ai_observability/frontend/scoreDefinitions/aiObservabilityScoreDefinitionsLogic.ts
+++ b/products/ai_observability/frontend/scoreDefinitions/aiObservabilityScoreDefinitionsLogic.ts
@@ -3,12 +3,13 @@ import { loaders } from 'kea-loaders'
import { router, urlToAction } from 'kea-router'
import { Sorting } from 'lib/lemon-ui/LemonTable'
+import { objectsEqual } from 'lib/utils/objects'
+import { pluralize } from 'lib/utils/strings'
import { ApiConfig } from '~/lib/api'
import { lemonToast } from '~/lib/lemon-ui/LemonToast/LemonToast'
import { PaginationManual } from '~/lib/lemon-ui/PaginationControl'
import { trackedActionToUrl } from '~/lib/logic/scenes/trackedActionToUrl'
-import { objectsEqual, pluralize } from '~/lib/utils'
import { urls } from '~/scenes/urls'
import {
diff --git a/products/ai_observability/frontend/tabs/aiObservabilityToolsLogic.ts b/products/ai_observability/frontend/tabs/aiObservabilityToolsLogic.ts
index 7ab5e0c4b5b2..5744fa515f71 100644
--- a/products/ai_observability/frontend/tabs/aiObservabilityToolsLogic.ts
+++ b/products/ai_observability/frontend/tabs/aiObservabilityToolsLogic.ts
@@ -1,7 +1,7 @@
import { actions, connect, kea, path, props, reducers, selectors } from 'kea'
-import { escapeRegex } from 'lib/actionUtils'
import { TaxonomicFilterGroupType } from 'lib/components/TaxonomicFilter/types'
+import { escapeRegex } from 'lib/utils/actions'
import { groupsModel } from '~/models/groupsModel'
import {
diff --git a/products/ai_observability/frontend/traceExportUtils.ts b/products/ai_observability/frontend/traceExportUtils.ts
index 92f2e2a2c3d1..916c8192e569 100644
--- a/products/ai_observability/frontend/traceExportUtils.ts
+++ b/products/ai_observability/frontend/traceExportUtils.ts
@@ -1,5 +1,6 @@
-import { downloadFile, slugify } from 'lib/utils'
import { copyToClipboard } from 'lib/utils/copyToClipboard'
+import { downloadFile } from 'lib/utils/dom'
+import { slugify } from 'lib/utils/strings'
import { LLMTrace, LLMTraceEvent } from '~/queries/schema/schema-general'
diff --git a/products/ai_observability/frontend/traceReviews/aiObservabilityReviewsLogic.ts b/products/ai_observability/frontend/traceReviews/aiObservabilityReviewsLogic.ts
index 64520804ee8b..3ffa8fff53bc 100644
--- a/products/ai_observability/frontend/traceReviews/aiObservabilityReviewsLogic.ts
+++ b/products/ai_observability/frontend/traceReviews/aiObservabilityReviewsLogic.ts
@@ -6,12 +6,13 @@ import { lemonToast } from '@posthog/lemon-ui'
import { Sorting } from 'lib/lemon-ui/LemonTable'
import { copyToClipboard } from 'lib/utils/copyToClipboard'
+import { objectsEqual } from 'lib/utils/objects'
+import { pluralize } from 'lib/utils/strings'
import { CountedPaginatedResponse } from '~/lib/api'
import { ApiConfig } from '~/lib/api'
import { PaginationManual } from '~/lib/lemon-ui/PaginationControl'
import { trackedActionToUrl } from '~/lib/logic/scenes/trackedActionToUrl'
-import { objectsEqual, pluralize } from '~/lib/utils'
import { urls } from '~/scenes/urls'
import { llmAnalyticsScoreDefinitionsList as aiObservabilityScoreDefinitionsList } from '../generated/api'
diff --git a/products/ai_observability/frontend/utils.ts b/products/ai_observability/frontend/utils.ts
index aee46b28efe7..6b121927dce2 100644
--- a/products/ai_observability/frontend/utils.ts
+++ b/products/ai_observability/frontend/utils.ts
@@ -2,7 +2,7 @@ import * as PartialJSON from 'partial-json'
import api from 'lib/api'
import { dayjs } from 'lib/dayjs'
-import { isObject, isString } from 'lib/utils'
+import { isObject, isString } from 'lib/utils/guards'
import { LLMTrace, LLMTraceEvent } from '~/queries/schema/schema-general'
import { hogql } from '~/queries/utils'
diff --git a/frontend/src/lib/utils/aiEventsUtils.test.ts b/products/ai_observability/frontend/utils/aiEvents.test.ts
similarity index 95%
rename from frontend/src/lib/utils/aiEventsUtils.test.ts
rename to products/ai_observability/frontend/utils/aiEvents.test.ts
index ba7e2528e1a6..489c8bf3a927 100644
--- a/frontend/src/lib/utils/aiEventsUtils.test.ts
+++ b/products/ai_observability/frontend/utils/aiEvents.test.ts
@@ -4,7 +4,7 @@ import { dayjs } from 'lib/dayjs'
import { useMocks } from '~/mocks/jest'
import { initKeaTests } from '~/test/init'
-import { AI_EVENT_NAMES, hasRecentAIEvents } from './aiEventsUtils'
+import { hasRecentAIEvents } from './aiEvents'
describe('aiEventsUtils', () => {
beforeEach(() => {
@@ -12,12 +12,6 @@ describe('aiEventsUtils', () => {
jest.clearAllMocks()
})
- describe('AI_EVENT_NAMES', () => {
- it('should contain all expected AI event names', () => {
- expect(AI_EVENT_NAMES).toEqual(['$ai_generation', '$ai_trace', '$ai_span', '$ai_embedding'])
- })
- })
-
describe('hasRecentAIEvents', () => {
it('returns true when a valid non-stale EventDefinition exists', async () => {
const recentDate = dayjs().subtract(1, 'day').toISOString()
diff --git a/frontend/src/lib/utils/aiEventsUtils.ts b/products/ai_observability/frontend/utils/aiEvents.ts
similarity index 92%
rename from frontend/src/lib/utils/aiEventsUtils.ts
rename to products/ai_observability/frontend/utils/aiEvents.ts
index 981944fc999a..47638553d832 100644
--- a/frontend/src/lib/utils/aiEventsUtils.ts
+++ b/products/ai_observability/frontend/utils/aiEvents.ts
@@ -1,12 +1,11 @@
import api from 'lib/api'
+import { isDefinitionStale } from 'lib/utils/definitions'
import { HogQLQuery, NodeKind, ProductKey } from '~/queries/schema/schema-general'
import { hogql } from '~/queries/utils'
import { EventDefinitionType } from '~/types'
-import { isDefinitionStale } from './definitions'
-
-export const AI_EVENT_NAMES = ['$ai_generation', '$ai_trace', '$ai_span', '$ai_embedding']
+const AI_EVENT_NAMES = ['$ai_generation', '$ai_trace', '$ai_span', '$ai_embedding']
// Use a longer staleness window than the global default so orgs that ingested AI events
// in the past, paused, and have since resumed still land on the dashboard rather than the
diff --git a/products/alerts/frontend/components/editAlertModal/AlertDefinitionSection.tsx b/products/alerts/frontend/components/editAlertModal/AlertDefinitionSection.tsx
index 879a58d2583a..e87053db9fee 100644
--- a/products/alerts/frontend/components/editAlertModal/AlertDefinitionSection.tsx
+++ b/products/alerts/frontend/components/editAlertModal/AlertDefinitionSection.tsx
@@ -16,7 +16,7 @@ import { AlertSimulationResult } from 'lib/components/Alerts/types'
import { DetectorSelector, getDefaultWindow } from 'lib/components/Alerts/views/DetectorSelector'
import { SimulationSummary } from 'lib/components/Alerts/views/SimulationSummary'
import { LemonField } from 'lib/lemon-ui/LemonField'
-import { alphabet } from 'lib/utils'
+import { alphabet } from 'lib/utils/strings'
import { AlertConditionType, InsightThresholdType } from '~/queries/schema/schema-general'
diff --git a/products/conversations/frontend/components/Assignee/AssigneeDisplay.tsx b/products/conversations/frontend/components/Assignee/AssigneeDisplay.tsx
index 88224a2f322f..91059e3e67e2 100644
--- a/products/conversations/frontend/components/Assignee/AssigneeDisplay.tsx
+++ b/products/conversations/frontend/components/Assignee/AssigneeDisplay.tsx
@@ -5,8 +5,9 @@ import { match } from 'ts-pattern'
import { IconPerson } from '@posthog/icons'
import { ProfilePicture } from '@posthog/lemon-ui'
-import { UnexpectedNeverError, fullName } from 'lib/utils'
import { cn } from 'lib/utils/css-classes'
+import { UnexpectedNeverError } from 'lib/utils/guards'
+import { fullName } from 'lib/utils/strings'
import { assigneeSelectLogic } from './assigneeSelectLogic'
import { Assignee, RoleAssignee, TicketAssignee, UserAssignee } from './types'
diff --git a/products/conversations/frontend/components/SidePanel/TicketsList.tsx b/products/conversations/frontend/components/SidePanel/TicketsList.tsx
index a86c02c9fb10..9b9756daa4ba 100644
--- a/products/conversations/frontend/components/SidePanel/TicketsList.tsx
+++ b/products/conversations/frontend/components/SidePanel/TicketsList.tsx
@@ -6,7 +6,7 @@ import { LemonBadge, LemonButton, LemonTag, Spinner } from '@posthog/lemon-ui'
import { Link } from '@posthog/lemon-ui'
import { TZLabel } from 'lib/components/TZLabel'
-import { stripMarkdown } from 'lib/utils/stripMarkdown'
+import { stripMarkdown } from 'lib/utils/markdown'
import type { ConversationTicket } from '../../types'
import { sidepanelTicketsLogic } from './sidepanelTicketsLogic'
diff --git a/products/conversations/frontend/components/SlaBusinessHours/CyclotronJobInputBusinessHours.tsx b/products/conversations/frontend/components/SlaBusinessHours/CyclotronJobInputBusinessHours.tsx
index df9b59932619..5c8181f3dae1 100644
--- a/products/conversations/frontend/components/SlaBusinessHours/CyclotronJobInputBusinessHours.tsx
+++ b/products/conversations/frontend/components/SlaBusinessHours/CyclotronJobInputBusinessHours.tsx
@@ -3,7 +3,7 @@ import { useValues } from 'kea'
import { LemonDivider, LemonInputSelect, LemonLabel, LemonSelect } from '@posthog/lemon-ui'
import type { CustomInputRendererProps } from 'lib/components/CyclotronJob/customInputRenderers'
-import { timeZoneLabel } from 'lib/utils'
+import { timeZoneLabel } from 'lib/utils/timezones'
import { preflightLogic } from 'scenes/PreflightCheck/preflightLogic'
import { teamLogic } from 'scenes/teamLogic'
diff --git a/products/conversations/frontend/scenes/ticket/PreviousTicketsPanel.tsx b/products/conversations/frontend/scenes/ticket/PreviousTicketsPanel.tsx
index aee414d03073..a449a1e9e655 100644
--- a/products/conversations/frontend/scenes/ticket/PreviousTicketsPanel.tsx
+++ b/products/conversations/frontend/scenes/ticket/PreviousTicketsPanel.tsx
@@ -1,7 +1,7 @@
import { LemonCollapse, LemonTag, Link } from '@posthog/lemon-ui'
import { TZLabel } from 'lib/components/TZLabel'
-import { stripMarkdown } from 'lib/utils/stripMarkdown'
+import { stripMarkdown } from 'lib/utils/markdown'
import { urls } from 'scenes/urls'
import { Ticket } from '../../types'
diff --git a/products/conversations/frontend/scenes/tickets/SupportTicketsScene.tsx b/products/conversations/frontend/scenes/tickets/SupportTicketsScene.tsx
index 2dcf86bc4707..349bb5e494ef 100644
--- a/products/conversations/frontend/scenes/tickets/SupportTicketsScene.tsx
+++ b/products/conversations/frontend/scenes/tickets/SupportTicketsScene.tsx
@@ -22,8 +22,8 @@ import { DateFilter } from 'lib/components/DateFilter/DateFilter'
import { ObjectTags } from 'lib/components/ObjectTags/ObjectTags'
import { TZLabel } from 'lib/components/TZLabel'
import { useBulkSelection } from 'lib/lemon-ui/LemonTable/useBulkSelection'
+import { stripMarkdown } from 'lib/utils/markdown'
import { newInternalTab } from 'lib/utils/newInternalTab'
-import { stripMarkdown } from 'lib/utils/stripMarkdown'
import { PersonDisplay } from 'scenes/persons/PersonDisplay'
import { SceneExport } from 'scenes/sceneTypes'
import { teamLogic } from 'scenes/teamLogic'
diff --git a/products/customer_analytics/frontend/CustomerAnalyticsFilters.tsx b/products/customer_analytics/frontend/CustomerAnalyticsFilters.tsx
index 95485bf32c08..9d8d827a5b63 100644
--- a/products/customer_analytics/frontend/CustomerAnalyticsFilters.tsx
+++ b/products/customer_analytics/frontend/CustomerAnalyticsFilters.tsx
@@ -10,7 +10,7 @@ import { FilterBar } from 'lib/components/FilterBar'
import { TestAccountFilterSwitch } from 'lib/components/TestAccountFiltersSwitch'
import { dayjs } from 'lib/dayjs'
import { groupsAccessLogic } from 'lib/introductions/groupsAccessLogic'
-import { formatDateRange } from 'lib/utils'
+import { formatDateRange } from 'lib/utils/datetime'
import { eventUsageLogic } from 'lib/utils/eventUsageLogic'
import { Scene } from 'scenes/sceneTypes'
import { teamLogic } from 'scenes/teamLogic'
diff --git a/products/customer_analytics/frontend/components/Accounts/AccountNotebooksExpansion.tsx b/products/customer_analytics/frontend/components/Accounts/AccountNotebooksExpansion.tsx
index d2c21985556e..748d64e2936e 100644
--- a/products/customer_analytics/frontend/components/Accounts/AccountNotebooksExpansion.tsx
+++ b/products/customer_analytics/frontend/components/Accounts/AccountNotebooksExpansion.tsx
@@ -14,7 +14,7 @@ import {
import { TZLabel } from 'lib/components/TZLabel'
import { IconSlack } from 'lib/lemon-ui/icons'
-import { fullName } from 'lib/utils'
+import { fullName } from 'lib/utils/strings'
import { urls } from 'scenes/urls'
import type { AccountNotebookApi } from 'products/customer_analytics/frontend/generated/api.schemas'
diff --git a/products/customer_analytics/frontend/components/Accounts/AccountRelatedUsersExpansion.tsx b/products/customer_analytics/frontend/components/Accounts/AccountRelatedUsersExpansion.tsx
index e97ca4e56e51..bf1e26ff953d 100644
--- a/products/customer_analytics/frontend/components/Accounts/AccountRelatedUsersExpansion.tsx
+++ b/products/customer_analytics/frontend/components/Accounts/AccountRelatedUsersExpansion.tsx
@@ -3,7 +3,7 @@ import posthog from 'posthog-js'
import { LemonTable, LemonTableColumns, Link } from '@posthog/lemon-ui'
-import { fullName } from 'lib/utils'
+import { fullName } from 'lib/utils/strings'
import { urls } from 'scenes/urls'
import { accountRelatedUsersLogic, AccountOrganizationMember, PAGE_SIZE } from './accountRelatedUsersLogic'
diff --git a/products/customer_analytics/frontend/components/Accounts/accountBillingLogic.ts b/products/customer_analytics/frontend/components/Accounts/accountBillingLogic.ts
index d21654d1b772..4658084f47e9 100644
--- a/products/customer_analytics/frontend/components/Accounts/accountBillingLogic.ts
+++ b/products/customer_analytics/frontend/components/Accounts/accountBillingLogic.ts
@@ -3,7 +3,7 @@ import { loaders } from 'kea-loaders'
import posthog from 'posthog-js'
import { dayjs } from 'lib/dayjs'
-import { dateStringToDayJs } from 'lib/utils'
+import { dateStringToDayJs } from 'lib/utils/dateFilters'
import { insightsApi } from 'scenes/insights/utils/api'
import { DataVisualizationNode, HogQLVariable, NodeKind } from '~/queries/schema/schema-general'
diff --git a/products/customer_analytics/frontend/components/Accounts/accountsColumnConfigLogic.ts b/products/customer_analytics/frontend/components/Accounts/accountsColumnConfigLogic.ts
index fd59762761a7..929acbd1cb38 100644
--- a/products/customer_analytics/frontend/components/Accounts/accountsColumnConfigLogic.ts
+++ b/products/customer_analytics/frontend/components/Accounts/accountsColumnConfigLogic.ts
@@ -1,6 +1,6 @@
import { actions, afterMount, connect, kea, path, reducers, selectors } from 'kea'
-import { objectsEqual } from 'lib/utils'
+import { objectsEqual } from 'lib/utils/objects'
import { databaseTableListLogic } from 'scenes/data-management/database/databaseTableListLogic'
import { teamLogic } from 'scenes/teamLogic'
diff --git a/products/customer_analytics/frontend/components/Accounts/accountsLogic.ts b/products/customer_analytics/frontend/components/Accounts/accountsLogic.ts
index cfa7283c9f9b..f09ac3317cb2 100644
--- a/products/customer_analytics/frontend/components/Accounts/accountsLogic.ts
+++ b/products/customer_analytics/frontend/components/Accounts/accountsLogic.ts
@@ -3,7 +3,7 @@ import { actionToUrl, router, urlToAction } from 'kea-router'
import posthog from 'posthog-js'
import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'
-import { objectsEqual } from 'lib/utils'
+import { objectsEqual } from 'lib/utils/objects'
import { teamLogic } from 'scenes/teamLogic'
import { urls } from 'scenes/urls'
import { userLogic } from 'scenes/userLogic'
diff --git a/products/customer_analytics/frontend/components/Accounts/accountsOverviewTilesLogic.ts b/products/customer_analytics/frontend/components/Accounts/accountsOverviewTilesLogic.ts
index 1aa319d37774..cc98583a4c03 100644
--- a/products/customer_analytics/frontend/components/Accounts/accountsOverviewTilesLogic.ts
+++ b/products/customer_analytics/frontend/components/Accounts/accountsOverviewTilesLogic.ts
@@ -2,7 +2,7 @@ import { actions, afterMount, connect, kea, listeners, path, reducers, selectors
import posthog from 'posthog-js'
import { v4 as uuidv4 } from 'uuid'
-import { objectsEqual } from 'lib/utils'
+import { objectsEqual } from 'lib/utils/objects'
import { dataNodeLogic } from '~/queries/nodes/DataNode/dataNodeLogic'
import { AccountsQueryResponse, DataNode } from '~/queries/schema/schema-general'
diff --git a/products/customer_analytics/frontend/components/Accounts/accountsViewsLogic.ts b/products/customer_analytics/frontend/components/Accounts/accountsViewsLogic.ts
index db14356734bd..88c01adb1137 100644
--- a/products/customer_analytics/frontend/components/Accounts/accountsViewsLogic.ts
+++ b/products/customer_analytics/frontend/components/Accounts/accountsViewsLogic.ts
@@ -6,8 +6,8 @@ import posthog from 'posthog-js'
import api from 'lib/api'
import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'
-import { objectsEqual } from 'lib/utils'
import { getCurrentTeamId } from 'lib/utils/getAppContext'
+import { objectsEqual } from 'lib/utils/objects'
import { teamLogic } from 'scenes/teamLogic'
import { userLogic } from 'scenes/userLogic'
diff --git a/products/customer_analytics/frontend/components/CustomerJourneys/customerJourneysLogic.ts b/products/customer_analytics/frontend/components/CustomerJourneys/customerJourneysLogic.ts
index 36e52a1776f1..b9e6a17a2215 100644
--- a/products/customer_analytics/frontend/components/CustomerJourneys/customerJourneysLogic.ts
+++ b/products/customer_analytics/frontend/components/CustomerJourneys/customerJourneysLogic.ts
@@ -5,8 +5,8 @@ import posthog from 'posthog-js'
import api from 'lib/api'
import { LemonSelectOptions } from 'lib/lemon-ui/LemonSelect/LemonSelect'
import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'
-import { isUUIDLike } from 'lib/utils'
import { eventUsageLogic } from 'lib/utils/eventUsageLogic'
+import { isUUIDLike } from 'lib/utils/guards'
import { FunnelsQuery, InsightVizNode } from '~/queries/schema/schema-general'
import { isInsightVizNode } from '~/queries/utils'
diff --git a/products/customer_analytics/frontend/components/CustomerJourneys/journeyBuilderLogic.ts b/products/customer_analytics/frontend/components/CustomerJourneys/journeyBuilderLogic.ts
index c3ae7067cfb5..2e3934f357af 100644
--- a/products/customer_analytics/frontend/components/CustomerJourneys/journeyBuilderLogic.ts
+++ b/products/customer_analytics/frontend/components/CustomerJourneys/journeyBuilderLogic.ts
@@ -4,9 +4,9 @@ import posthog from 'posthog-js'
import { TaxonomicFilterGroupType } from 'lib/components/TaxonomicFilter/types'
import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'
-import { isEmptyObject } from 'lib/utils'
import { eventUsageLogic } from 'lib/utils/eventUsageLogic'
import { getDefaultEventName, getProjectEventExistence } from 'lib/utils/getAppContext'
+import { isEmptyObject } from 'lib/utils/guards'
import { funnelPathsExpansionLogic } from 'scenes/funnels/FunnelFlowGraph/funnelPathsExpansionLogic'
import { PathExpansion } from 'scenes/funnels/FunnelFlowGraph/pathFlowUtils'
import { insightDataLogic } from 'scenes/insights/insightDataLogic'
diff --git a/products/customer_analytics/frontend/components/PersonDisplayNameNudgeBanner.tsx b/products/customer_analytics/frontend/components/PersonDisplayNameNudgeBanner.tsx
index 359b31f4b327..711534ed2c38 100644
--- a/products/customer_analytics/frontend/components/PersonDisplayNameNudgeBanner.tsx
+++ b/products/customer_analytics/frontend/components/PersonDisplayNameNudgeBanner.tsx
@@ -3,7 +3,7 @@ import { useEffect } from 'react'
import { LemonBanner, LemonSkeleton } from '@posthog/lemon-ui'
-import { isUUIDLike } from 'lib/utils'
+import { isUUIDLike } from 'lib/utils/guards'
import { personsSceneLogic } from 'scenes/persons/personsSceneLogic'
import { urls } from 'scenes/urls'
diff --git a/products/customer_analytics/frontend/components/UsageMetricCard.tsx b/products/customer_analytics/frontend/components/UsageMetricCard.tsx
index acbf091ac7a1..45bc70b7e49a 100644
--- a/products/customer_analytics/frontend/components/UsageMetricCard.tsx
+++ b/products/customer_analytics/frontend/components/UsageMetricCard.tsx
@@ -3,7 +3,12 @@ import { LemonCard, LemonSkeleton, Tooltip } from '@posthog/lemon-ui'
import { Sparkline } from 'lib/components/Sparkline'
import { IconTrendingDown, IconTrendingFlat } from 'lib/lemon-ui/icons'
-import { formatPercentage, humanFriendlyCurrency, humanFriendlyLargeNumber, humanFriendlyNumber } from 'lib/utils'
+import {
+ formatPercentage,
+ humanFriendlyCurrency,
+ humanFriendlyLargeNumber,
+ humanFriendlyNumber,
+} from 'lib/utils/numbers'
import { UsageMetric } from '~/queries/schema/schema-general'
diff --git a/products/customer_analytics/frontend/components/ZendeskTicketsFilters/OrderBy.tsx b/products/customer_analytics/frontend/components/ZendeskTicketsFilters/OrderBy.tsx
index c3c07d7453ce..4a29f73b79c6 100644
--- a/products/customer_analytics/frontend/components/ZendeskTicketsFilters/OrderBy.tsx
+++ b/products/customer_analytics/frontend/components/ZendeskTicketsFilters/OrderBy.tsx
@@ -2,7 +2,7 @@ import { useActions, useValues } from 'kea'
import { LemonSelect } from '@posthog/lemon-ui'
-import { capitalizeFirstLetter } from 'lib/utils'
+import { capitalizeFirstLetter } from 'lib/utils/strings'
import { zendeskTicketsFiltersLogic } from './zendeskTicketsFiltersLogic'
diff --git a/products/customer_analytics/frontend/components/ZendeskTicketsFilters/Priority.tsx b/products/customer_analytics/frontend/components/ZendeskTicketsFilters/Priority.tsx
index 940300858ab3..2c6981905ca3 100644
--- a/products/customer_analytics/frontend/components/ZendeskTicketsFilters/Priority.tsx
+++ b/products/customer_analytics/frontend/components/ZendeskTicketsFilters/Priority.tsx
@@ -2,7 +2,7 @@ import { useActions, useValues } from 'kea'
import { LemonSelect } from '@posthog/lemon-ui'
-import { capitalizeFirstLetter } from 'lib/utils'
+import { capitalizeFirstLetter } from 'lib/utils/strings'
import { zendeskTicketsFiltersLogic } from './zendeskTicketsFiltersLogic'
diff --git a/products/customer_analytics/frontend/components/ZendeskTicketsFilters/Status.tsx b/products/customer_analytics/frontend/components/ZendeskTicketsFilters/Status.tsx
index b8eacc111f47..06f9c2ed53ca 100644
--- a/products/customer_analytics/frontend/components/ZendeskTicketsFilters/Status.tsx
+++ b/products/customer_analytics/frontend/components/ZendeskTicketsFilters/Status.tsx
@@ -2,7 +2,7 @@ import { useActions, useValues } from 'kea'
import { LemonSelect } from '@posthog/lemon-ui'
-import { capitalizeFirstLetter } from 'lib/utils'
+import { capitalizeFirstLetter } from 'lib/utils/strings'
import { zendeskTicketsFiltersLogic } from './zendeskTicketsFiltersLogic'
diff --git a/products/customer_analytics/frontend/customerAnalyticsConfigLogic.ts b/products/customer_analytics/frontend/customerAnalyticsConfigLogic.ts
index d7524f07069d..24ba139e5151 100644
--- a/products/customer_analytics/frontend/customerAnalyticsConfigLogic.ts
+++ b/products/customer_analytics/frontend/customerAnalyticsConfigLogic.ts
@@ -1,6 +1,6 @@
import { actions, connect, kea, listeners, path, selectors } from 'kea'
-import { isEmptyObject } from 'lib/utils'
+import { isEmptyObject } from 'lib/utils/guards'
import { teamLogic } from 'scenes/teamLogic'
import {
diff --git a/products/customer_analytics/frontend/customerAnalyticsSceneLogic.ts b/products/customer_analytics/frontend/customerAnalyticsSceneLogic.ts
index f8202b6f5751..146120e2ae22 100644
--- a/products/customer_analytics/frontend/customerAnalyticsSceneLogic.ts
+++ b/products/customer_analytics/frontend/customerAnalyticsSceneLogic.ts
@@ -3,7 +3,8 @@ import { router, urlToAction } from 'kea-router'
import { FunnelLayout } from 'lib/constants'
import { trackedActionToUrl } from 'lib/logic/scenes/trackedActionToUrl'
-import { capitalizeFirstLetter, getDefaultInterval, wordPluralize } from 'lib/utils'
+import { getDefaultInterval } from 'lib/utils/dateFilters'
+import { capitalizeFirstLetter, wordPluralize } from 'lib/utils/strings'
import { sceneConfigurations } from 'scenes/scenes'
import { Scene } from 'scenes/sceneTypes'
import { urls } from 'scenes/urls'
diff --git a/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/account/CustomerAnalyticsAccountConfig.tsx b/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/account/CustomerAnalyticsAccountConfig.tsx
index 792433ca5b3a..5c9f52da92f3 100644
--- a/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/account/CustomerAnalyticsAccountConfig.tsx
+++ b/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/account/CustomerAnalyticsAccountConfig.tsx
@@ -5,7 +5,7 @@ import { LemonSelect } from '@posthog/lemon-ui'
import { RestrictionScope, useRestrictedArea } from 'lib/components/RestrictedArea'
import { TeamMembershipLevel } from 'lib/constants'
import { groupsAccessLogic } from 'lib/introductions/groupsAccessLogic'
-import { capitalizeFirstLetter, wordPluralize } from 'lib/utils'
+import { capitalizeFirstLetter, wordPluralize } from 'lib/utils/strings'
import { GroupsIntroduction } from 'scenes/groups/GroupsIntroduction'
import { teamLogic } from 'scenes/teamLogic'
diff --git a/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/events/customerAnalyticsDashboardEventsLogic.ts b/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/events/customerAnalyticsDashboardEventsLogic.ts
index 8235b0371b1f..12b5ddb8bbe6 100644
--- a/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/events/customerAnalyticsDashboardEventsLogic.ts
+++ b/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/events/customerAnalyticsDashboardEventsLogic.ts
@@ -1,7 +1,7 @@
import { actions, connect, kea, listeners, path, reducers, selectors } from 'kea'
import { urlToAction } from 'kea-router'
-import { isEmptyObject } from 'lib/utils'
+import { isEmptyObject } from 'lib/utils/guards'
import { MathAvailability } from 'scenes/insights/filters/ActionFilter/ActionFilterRow/ActionFilterRow'
import { actionsAndEventsToSeries } from '~/queries/nodes/InsightQuery/utils/filtersToQueryNode'
diff --git a/products/customer_analytics/frontend/scenes/CustomerJourneyTemplatesScene/journeyTemplatePickerLogic.ts b/products/customer_analytics/frontend/scenes/CustomerJourneyTemplatesScene/journeyTemplatePickerLogic.ts
index e629b64e261e..fd0735f8fc32 100644
--- a/products/customer_analytics/frontend/scenes/CustomerJourneyTemplatesScene/journeyTemplatePickerLogic.ts
+++ b/products/customer_analytics/frontend/scenes/CustomerJourneyTemplatesScene/journeyTemplatePickerLogic.ts
@@ -3,8 +3,8 @@ import { lazyLoaders } from 'kea-loaders'
import { router } from 'kea-router'
import api from 'lib/api'
-import { isEmptyObject } from 'lib/utils'
import { eventUsageLogic } from 'lib/utils/eventUsageLogic'
+import { isEmptyObject } from 'lib/utils/guards'
import { urls } from 'scenes/urls'
import { getQueryBasedInsightModel } from '~/queries/nodes/InsightViz/utils'
diff --git a/products/dashboards/frontend/components/WidgetCard/WidgetCardHeader.tsx b/products/dashboards/frontend/components/WidgetCard/WidgetCardHeader.tsx
index 538c2cebb599..d3f7b6a24642 100644
--- a/products/dashboards/frontend/components/WidgetCard/WidgetCardHeader.tsx
+++ b/products/dashboards/frontend/components/WidgetCard/WidgetCardHeader.tsx
@@ -7,7 +7,7 @@ import { More, MoreProps } from 'lib/lemon-ui/LemonButton/More'
import { LemonMarkdown } from 'lib/lemon-ui/LemonMarkdown'
import { Link } from 'lib/lemon-ui/Link'
import { Spinner } from 'lib/lemon-ui/Spinner'
-import { dateFilterToText } from 'lib/utils'
+import { dateFilterToText } from 'lib/utils/dateFilters'
import { DashboardPlacement } from '~/types'
diff --git a/products/dashboards/frontend/widgets/session_replay/sessionReplayWidgetSavedFiltersLogic.ts b/products/dashboards/frontend/widgets/session_replay/sessionReplayWidgetSavedFiltersLogic.ts
index c3f6ab8b6fb0..057a1e353495 100644
--- a/products/dashboards/frontend/widgets/session_replay/sessionReplayWidgetSavedFiltersLogic.ts
+++ b/products/dashboards/frontend/widgets/session_replay/sessionReplayWidgetSavedFiltersLogic.ts
@@ -2,7 +2,7 @@ import { afterMount, kea, path, selectors } from 'kea'
import { loaders } from 'kea-loaders'
import api from 'lib/api'
-import { toParams } from 'lib/utils'
+import { toParams } from 'lib/utils/url'
import type { SessionRecordingPlaylistType } from '~/types'
diff --git a/products/data_warehouse/frontend/scenes/SourceScene/tabs/CDCSection.tsx b/products/data_warehouse/frontend/scenes/SourceScene/tabs/CDCSection.tsx
index a94958669547..6fb91a1c135c 100644
--- a/products/data_warehouse/frontend/scenes/SourceScene/tabs/CDCSection.tsx
+++ b/products/data_warehouse/frontend/scenes/SourceScene/tabs/CDCSection.tsx
@@ -22,8 +22,8 @@ import { LemonField } from 'lib/lemon-ui/LemonField'
import { LemonRadio } from 'lib/lemon-ui/LemonRadio'
import { lemonToast } from 'lib/lemon-ui/LemonToast'
import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
-import { humanizeBytes } from 'lib/utils'
import { copyToClipboard } from 'lib/utils/copyToClipboard'
+import { humanizeBytes } from 'lib/utils/numbers'
import { AccessControlLevel, AccessControlResourceType, ExternalDataSource } from '~/types'
diff --git a/products/data_warehouse/frontend/scenes/SourceScene/tabs/DirectQuerySchemasTab.tsx b/products/data_warehouse/frontend/scenes/SourceScene/tabs/DirectQuerySchemasTab.tsx
index 79804631237c..6e0054f91397 100644
--- a/products/data_warehouse/frontend/scenes/SourceScene/tabs/DirectQuerySchemasTab.tsx
+++ b/products/data_warehouse/frontend/scenes/SourceScene/tabs/DirectQuerySchemasTab.tsx
@@ -13,8 +13,9 @@ import {
Tooltip,
} from '@posthog/lemon-ui'
-import { groupBy, pluralize } from 'lib/utils'
+import { groupBy } from 'lib/utils/arrays'
import { newInternalTab } from 'lib/utils/newInternalTab'
+import { pluralize } from 'lib/utils/strings'
import { ExternalDataSource, ExternalDataSourceSchema } from '~/types'
diff --git a/products/data_warehouse/frontend/scenes/SourceScene/tabs/SchemasTab.tsx b/products/data_warehouse/frontend/scenes/SourceScene/tabs/SchemasTab.tsx
index cbe4088fbbca..8787c5307fc0 100644
--- a/products/data_warehouse/frontend/scenes/SourceScene/tabs/SchemasTab.tsx
+++ b/products/data_warehouse/frontend/scenes/SourceScene/tabs/SchemasTab.tsx
@@ -24,7 +24,7 @@ import { More } from 'lib/lemon-ui/LemonButton/More'
import { LemonMenu } from 'lib/lemon-ui/LemonMenu'
import { LemonTableLink } from 'lib/lemon-ui/LemonTable/LemonTableLink'
import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
-import { pluralize } from 'lib/utils'
+import { pluralize } from 'lib/utils/strings'
import { teamLogic } from 'scenes/teamLogic'
import { urls } from 'scenes/urls'
diff --git a/products/data_warehouse/frontend/scenes/SourceScene/tabs/WebhookLogsSection.tsx b/products/data_warehouse/frontend/scenes/SourceScene/tabs/WebhookLogsSection.tsx
index f516431b5ee1..bce0dba2531a 100644
--- a/products/data_warehouse/frontend/scenes/SourceScene/tabs/WebhookLogsSection.tsx
+++ b/products/data_warehouse/frontend/scenes/SourceScene/tabs/WebhookLogsSection.tsx
@@ -6,7 +6,7 @@ import { LemonButton, LemonCheckbox, LemonDialog, LemonMenu, LemonTag } from '@p
import { LemonCard } from 'lib/lemon-ui/LemonCard'
import { LemonTableColumns } from 'lib/lemon-ui/LemonTable'
-import { capitalizeFirstLetter } from 'lib/utils'
+import { capitalizeFirstLetter } from 'lib/utils/strings'
import { hogFunctionLogsLogic } from 'scenes/hog-functions/logs/hogFunctionLogsLogic'
import { LogsViewer } from 'scenes/hog-functions/logs/LogsViewer'
import { GroupedLogEntry, LogsViewerLogicProps } from 'scenes/hog-functions/logs/logsViewerLogic'
diff --git a/products/data_warehouse/frontend/scenes/SourceScene/tabs/sourceSettingsLogic.ts b/products/data_warehouse/frontend/scenes/SourceScene/tabs/sourceSettingsLogic.ts
index 4f03f879cc82..463ef918c9c3 100644
--- a/products/data_warehouse/frontend/scenes/SourceScene/tabs/sourceSettingsLogic.ts
+++ b/products/data_warehouse/frontend/scenes/SourceScene/tabs/sourceSettingsLogic.ts
@@ -7,7 +7,8 @@ import posthog from 'posthog-js'
import { lemonToast } from '@posthog/lemon-ui'
import api from 'lib/api'
-import { objectsEqual, pluralize } from 'lib/utils'
+import { objectsEqual } from 'lib/utils/objects'
+import { pluralize } from 'lib/utils/strings'
import { urls } from 'scenes/urls'
import { SourceConfig, SourceFieldConfig } from '~/queries/schema/schema-general'
diff --git a/products/data_warehouse/frontend/shared/components/forms/SchemaForm.tsx b/products/data_warehouse/frontend/shared/components/forms/SchemaForm.tsx
index 61172e881ab5..583c6b6222bb 100644
--- a/products/data_warehouse/frontend/shared/components/forms/SchemaForm.tsx
+++ b/products/data_warehouse/frontend/shared/components/forms/SchemaForm.tsx
@@ -14,7 +14,7 @@ import {
} from '@posthog/lemon-ui'
import { useFloatingContainer } from 'lib/hooks/useFloatingContainerContext'
-import { pluralize } from 'lib/utils'
+import { pluralize } from 'lib/utils/strings'
import { ExternalDataSourceSyncSchema } from '~/types'
diff --git a/products/data_warehouse/frontend/shared/components/forms/schemaGroupingUtils.ts b/products/data_warehouse/frontend/shared/components/forms/schemaGroupingUtils.ts
index d7f4ad0fbfb5..3857a03c8978 100644
--- a/products/data_warehouse/frontend/shared/components/forms/schemaGroupingUtils.ts
+++ b/products/data_warehouse/frontend/shared/components/forms/schemaGroupingUtils.ts
@@ -1,4 +1,4 @@
-import { groupBy } from 'lib/utils'
+import { groupBy } from 'lib/utils/arrays'
export function splitQualifiedTableName(
table: string,
diff --git a/products/early_access_features/frontend/earlyAccessFeatureLogic.ts b/products/early_access_features/frontend/earlyAccessFeatureLogic.ts
index 21316e371aec..199ae381e7d1 100644
--- a/products/early_access_features/frontend/earlyAccessFeatureLogic.ts
+++ b/products/early_access_features/frontend/earlyAccessFeatureLogic.ts
@@ -10,7 +10,7 @@ import api from 'lib/api'
import { tryShowMCPHint } from 'lib/components/MCPHint/mcpHintLogic'
import { SetupTaskId, globalSetupLogic } from 'lib/components/ProductSetup'
import { LemonDialog } from 'lib/lemon-ui/LemonDialog'
-import { identifierToHuman } from 'lib/utils'
+import { identifierToHuman } from 'lib/utils/strings'
import { teamLogic } from 'scenes/teamLogic'
import { urls } from 'scenes/urls'
diff --git a/products/endpoints/frontend/EndpointFromInsightModal.tsx b/products/endpoints/frontend/EndpointFromInsightModal.tsx
index a69c5a1eef47..373b64fbb135 100644
--- a/products/endpoints/frontend/EndpointFromInsightModal.tsx
+++ b/products/endpoints/frontend/EndpointFromInsightModal.tsx
@@ -8,7 +8,7 @@ import { LemonModal } from 'lib/lemon-ui/LemonModal'
import { LemonTable } from 'lib/lemon-ui/LemonTable'
import { LemonTextArea } from 'lib/lemon-ui/LemonTextArea'
import { Link } from 'lib/lemon-ui/Link'
-import { slugify } from 'lib/utils'
+import { slugify } from 'lib/utils/strings'
import { urls } from 'scenes/urls'
import { EndpointQueryNode, HogQLQuery } from '~/queries/schema/schema-general'
diff --git a/products/endpoints/frontend/EndpointHeader.tsx b/products/endpoints/frontend/EndpointHeader.tsx
index ef3641529b6e..170e2f9ed043 100644
--- a/products/endpoints/frontend/EndpointHeader.tsx
+++ b/products/endpoints/frontend/EndpointHeader.tsx
@@ -6,8 +6,8 @@ import { LemonButton, LemonLabel, LemonSwitch } from '@posthog/lemon-ui'
import { AccessControlAction } from 'lib/components/AccessControlAction'
import { superpowersLogic } from 'lib/components/Superpowers/superpowersLogic'
import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'
-import { objectsEqual } from 'lib/utils'
import { getAccessControlDisabledReason } from 'lib/utils/accessControlUtils'
+import { objectsEqual } from 'lib/utils/objects'
import { SceneTitleSection } from '~/layout/scenes/components/SceneTitleSection'
import { EndpointRequest } from '~/queries/schema/schema-general'
diff --git a/products/endpoints/frontend/EndpointsUsage.tsx b/products/endpoints/frontend/EndpointsUsage.tsx
index ef8f371a8e58..461087024b04 100644
--- a/products/endpoints/frontend/EndpointsUsage.tsx
+++ b/products/endpoints/frontend/EndpointsUsage.tsx
@@ -2,7 +2,8 @@ import { useValues } from 'kea'
import { useMemo } from 'react'
import { Link } from 'lib/lemon-ui/Link'
-import { humanFriendlyDuration, humanFriendlyNumber, humanizeBytes } from 'lib/utils'
+import { humanFriendlyDuration } from 'lib/utils/durations'
+import { humanFriendlyNumber, humanizeBytes } from 'lib/utils/numbers'
import { urls } from 'scenes/urls'
import { Query } from '~/queries/Query/Query'
diff --git a/products/endpoints/frontend/EndpointsUsageFilters.tsx b/products/endpoints/frontend/EndpointsUsageFilters.tsx
index 36f3dc6580fc..3072ea193401 100644
--- a/products/endpoints/frontend/EndpointsUsageFilters.tsx
+++ b/products/endpoints/frontend/EndpointsUsageFilters.tsx
@@ -6,7 +6,7 @@ import { LemonButton, LemonInputSelect, LemonSelect } from '@posthog/lemon-ui'
import { DateFilter } from 'lib/components/DateFilter/DateFilter'
import { FilterBar } from 'lib/components/FilterBar'
import { dayjs } from 'lib/dayjs'
-import { formatDateRange } from 'lib/utils'
+import { formatDateRange } from 'lib/utils/datetime'
import { EndpointsUsageBreakdown } from '~/queries/schema/schema-general'
import { IntervalType } from '~/types'
diff --git a/products/endpoints/frontend/endpointLogic.tsx b/products/endpoints/frontend/endpointLogic.tsx
index b5cea4fd6002..ab672eedf8be 100644
--- a/products/endpoints/frontend/endpointLogic.tsx
+++ b/products/endpoints/frontend/endpointLogic.tsx
@@ -6,8 +6,9 @@ import api from 'lib/api'
import { SetupTaskId, globalSetupLogic } from 'lib/components/ProductSetup'
import { LemonDialog } from 'lib/lemon-ui/LemonDialog'
import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'
-import { debounce, slugify } from 'lib/utils'
+import { debounce } from 'lib/utils/async'
import { permanentlyMount } from 'lib/utils/kea-logic-builders'
+import { slugify } from 'lib/utils/strings'
import { teamLogic } from 'scenes/teamLogic'
import { urls } from 'scenes/urls'
diff --git a/products/endpoints/frontend/endpointsUsageLogic.tsx b/products/endpoints/frontend/endpointsUsageLogic.tsx
index a5c948bb385b..dd195f94159c 100644
--- a/products/endpoints/frontend/endpointsUsageLogic.tsx
+++ b/products/endpoints/frontend/endpointsUsageLogic.tsx
@@ -3,7 +3,7 @@ import { router, urlToAction } from 'kea-router'
import { dayjs } from 'lib/dayjs'
import { trackedActionToUrl } from 'lib/logic/scenes/trackedActionToUrl'
-import { dateStringToDayJs } from 'lib/utils'
+import { dateStringToDayJs } from 'lib/utils/dateFilters'
import { urls } from 'scenes/urls'
import {
diff --git a/products/endpoints/frontend/nodes/EndpointsUsageOverviewNode.tsx b/products/endpoints/frontend/nodes/EndpointsUsageOverviewNode.tsx
index 0a14c6cae754..19ea24671462 100644
--- a/products/endpoints/frontend/nodes/EndpointsUsageOverviewNode.tsx
+++ b/products/endpoints/frontend/nodes/EndpointsUsageOverviewNode.tsx
@@ -4,8 +4,9 @@ import { useState } from 'react'
import { LemonSkeleton } from '@posthog/lemon-ui'
import { useAttachedLogic } from 'lib/logic/scenes/useAttachedLogic'
-import { humanFriendlyDuration, humanFriendlyNumber, humanizeBytes } from 'lib/utils'
import { cn } from 'lib/utils/css-classes'
+import { humanFriendlyDuration } from 'lib/utils/durations'
+import { humanFriendlyNumber, humanizeBytes } from 'lib/utils/numbers'
import { dataNodeLogic } from '~/queries/nodes/DataNode/dataNodeLogic'
import {
diff --git a/products/engineering_analytics/frontend/scenes/EngineeringAnalyticsPullRequests.tsx b/products/engineering_analytics/frontend/scenes/EngineeringAnalyticsPullRequests.tsx
index caa773bfef6b..7c8abc661b44 100644
--- a/products/engineering_analytics/frontend/scenes/EngineeringAnalyticsPullRequests.tsx
+++ b/products/engineering_analytics/frontend/scenes/EngineeringAnalyticsPullRequests.tsx
@@ -14,8 +14,10 @@ import {
} from '@posthog/lemon-ui'
import { TZLabel } from 'lib/components/TZLabel'
-import { humanFriendlyDuration, humanFriendlyNumber, pluralize } from 'lib/utils'
+import { humanFriendlyDuration } from 'lib/utils/durations'
import { newInternalTab } from 'lib/utils/newInternalTab'
+import { humanFriendlyNumber } from 'lib/utils/numbers'
+import { pluralize } from 'lib/utils/strings'
import { urls } from 'scenes/urls'
import { CIStatusTag } from '../components/CIStatusTag'
diff --git a/products/engineering_analytics/frontend/scenes/EngineeringAnalyticsWorkflows.tsx b/products/engineering_analytics/frontend/scenes/EngineeringAnalyticsWorkflows.tsx
index 26d5c80214b6..c25acde7381f 100644
--- a/products/engineering_analytics/frontend/scenes/EngineeringAnalyticsWorkflows.tsx
+++ b/products/engineering_analytics/frontend/scenes/EngineeringAnalyticsWorkflows.tsx
@@ -5,8 +5,10 @@ import { LemonTable, LemonTableColumns, Link } from '@posthog/lemon-ui'
import { DateFilter } from 'lib/components/DateFilter/DateFilter'
import { Sparkline } from 'lib/components/Sparkline'
import { TZLabel } from 'lib/components/TZLabel'
-import { dateFilterToText, dateMapping, humanFriendlyDuration, humanFriendlyNumber } from 'lib/utils'
import { cn } from 'lib/utils/css-classes'
+import { dateFilterToText, dateMapping } from 'lib/utils/dateFilters'
+import { humanFriendlyDuration } from 'lib/utils/durations'
+import { humanFriendlyNumber } from 'lib/utils/numbers'
import { ConnectGitHubSource } from '../components/ConnectGitHubSource'
import { githubWorkflowUrl } from '../lib/github'
diff --git a/products/engineering_analytics/frontend/scenes/PullRequestDetailScene.tsx b/products/engineering_analytics/frontend/scenes/PullRequestDetailScene.tsx
index 001ab8a5843b..f9f6656e3283 100644
--- a/products/engineering_analytics/frontend/scenes/PullRequestDetailScene.tsx
+++ b/products/engineering_analytics/frontend/scenes/PullRequestDetailScene.tsx
@@ -14,8 +14,9 @@ import {
import { TZLabel } from 'lib/components/TZLabel'
import { dayjs } from 'lib/dayjs'
-import { capitalizeFirstLetter, humanFriendlyDuration, pluralize } from 'lib/utils'
import { cn } from 'lib/utils/css-classes'
+import { humanFriendlyDuration } from 'lib/utils/durations'
+import { capitalizeFirstLetter, pluralize } from 'lib/utils/strings'
import { SceneExport } from 'scenes/sceneTypes'
import { SceneContent } from '~/layout/scenes/components/SceneContent'
diff --git a/products/engineering_analytics/frontend/scenes/engineeringAnalyticsLogic.ts b/products/engineering_analytics/frontend/scenes/engineeringAnalyticsLogic.ts
index f2347f238fca..7b3ddd995d04 100644
--- a/products/engineering_analytics/frontend/scenes/engineeringAnalyticsLogic.ts
+++ b/products/engineering_analytics/frontend/scenes/engineeringAnalyticsLogic.ts
@@ -3,7 +3,7 @@ import { loaders } from 'kea-loaders'
import { ApiConfig } from 'lib/api'
import { dayjs } from 'lib/dayjs'
-import { objectsEqual } from 'lib/utils'
+import { objectsEqual } from 'lib/utils/objects'
import {
engineeringAnalyticsCiCards,
diff --git a/products/error_tracking/frontend/__mocks__/error_tracking_query.ts b/products/error_tracking/frontend/__mocks__/error_tracking_query.ts
index bc40928f8216..565617645467 100644
--- a/products/error_tracking/frontend/__mocks__/error_tracking_query.ts
+++ b/products/error_tracking/frontend/__mocks__/error_tracking_query.ts
@@ -1,4 +1,5 @@
-import { range, uuid } from 'lib/utils'
+import { range } from 'lib/utils/arrays'
+import { uuid } from 'lib/utils/dom'
import { ErrorTrackingQueryResponse, ErrorTrackingRelationalIssue } from '~/queries/schema/schema-general'
diff --git a/products/error_tracking/frontend/__mocks__/stack_frames/batch_get.ts b/products/error_tracking/frontend/__mocks__/stack_frames/batch_get.ts
index e1fec00e5858..e3db0765a745 100644
--- a/products/error_tracking/frontend/__mocks__/stack_frames/batch_get.ts
+++ b/products/error_tracking/frontend/__mocks__/stack_frames/batch_get.ts
@@ -3,7 +3,7 @@ import {
ErrorTrackingStackFrame,
ErrorTrackingStackFrameRecord,
} from 'lib/components/Errors/types'
-import { uuid } from 'lib/utils'
+import { uuid } from 'lib/utils/dom'
import { EventType } from '~/types'
diff --git a/products/error_tracking/frontend/components/ActivityDescriber.tsx b/products/error_tracking/frontend/components/ActivityDescriber.tsx
index cddd472c2ed3..6bf29f016420 100644
--- a/products/error_tracking/frontend/components/ActivityDescriber.tsx
+++ b/products/error_tracking/frontend/components/ActivityDescriber.tsx
@@ -13,7 +13,7 @@ import {
userNameForLogItem,
} from 'lib/components/ActivityLog/humanizeActivity'
import { SentenceList } from 'lib/components/ActivityLog/SentenceList'
-import { objectsEqual } from 'lib/utils'
+import { objectsEqual } from 'lib/utils/objects'
import { urls } from 'scenes/urls'
import { ErrorTrackingIssue, ErrorTrackingRelationalIssue } from '~/queries/schema/schema-general'
diff --git a/products/error_tracking/frontend/components/Assignee/AssigneeDisplay.tsx b/products/error_tracking/frontend/components/Assignee/AssigneeDisplay.tsx
index c78d40355112..2c910b57c910 100644
--- a/products/error_tracking/frontend/components/Assignee/AssigneeDisplay.tsx
+++ b/products/error_tracking/frontend/components/Assignee/AssigneeDisplay.tsx
@@ -5,8 +5,9 @@ import { match } from 'ts-pattern'
import { IconPerson } from '@posthog/icons'
import { ProfilePicture } from '@posthog/lemon-ui'
-import { UnexpectedNeverError, fullName } from 'lib/utils'
import { cn } from 'lib/utils/css-classes'
+import { UnexpectedNeverError } from 'lib/utils/guards'
+import { fullName } from 'lib/utils/strings'
import { ErrorTrackingIssue } from '~/queries/schema/schema-general'
diff --git a/products/error_tracking/frontend/components/Breakdowns/BreakdownsSearchBar.tsx b/products/error_tracking/frontend/components/Breakdowns/BreakdownsSearchBar.tsx
index bcabac72f090..b050f892861e 100644
--- a/products/error_tracking/frontend/components/Breakdowns/BreakdownsSearchBar.tsx
+++ b/products/error_tracking/frontend/components/Breakdowns/BreakdownsSearchBar.tsx
@@ -8,7 +8,7 @@ import { PropertyKeyInfo } from 'lib/components/PropertyKeyInfo'
import { TaxonomicFilter } from 'lib/components/TaxonomicFilter/TaxonomicFilter'
import { TaxonomicFilterGroupType } from 'lib/components/TaxonomicFilter/types'
import { Popover } from 'lib/lemon-ui/Popover'
-import { dateMapping } from 'lib/utils'
+import { dateMapping } from 'lib/utils/dateFilters'
import { TestAccountFilter } from 'scenes/insights/filters/TestAccountFilter'
import { breakdownFiltersLogic } from './breakdownFiltersLogic'
diff --git a/products/error_tracking/frontend/components/ContextDisplay/ContextDisplay.tsx b/products/error_tracking/frontend/components/ContextDisplay/ContextDisplay.tsx
index 996cd634bda9..2f86520cbd64 100644
--- a/products/error_tracking/frontend/components/ContextDisplay/ContextDisplay.tsx
+++ b/products/error_tracking/frontend/components/ContextDisplay/ContextDisplay.tsx
@@ -6,7 +6,7 @@ import { Spinner } from '@posthog/lemon-ui'
import { ExceptionAttributes } from 'lib/components/Errors/types'
import { concatValues } from 'lib/components/Errors/utils'
import { isUniversalGroupFilterLike } from 'lib/components/UniversalFilters/utils'
-import { identifierToHuman } from 'lib/utils'
+import { identifierToHuman } from 'lib/utils/strings'
import {
AnyPropertyFilter,
diff --git a/products/error_tracking/frontend/components/ErrorTrackingIssueList/ErrorTrackingIssueList.tsx b/products/error_tracking/frontend/components/ErrorTrackingIssueList/ErrorTrackingIssueList.tsx
index d183451acfa6..273ff93eee28 100644
--- a/products/error_tracking/frontend/components/ErrorTrackingIssueList/ErrorTrackingIssueList.tsx
+++ b/products/error_tracking/frontend/components/ErrorTrackingIssueList/ErrorTrackingIssueList.tsx
@@ -6,8 +6,8 @@ import { Link } from '@posthog/lemon-ui'
import { getRuntimeFromLib } from 'lib/components/Errors/utils'
import { TZLabel } from 'lib/components/TZLabel'
-import { humanFriendlyLargeNumber } from 'lib/utils'
import { cn } from 'lib/utils/css-classes'
+import { humanFriendlyLargeNumber } from 'lib/utils/numbers'
import { urls } from 'scenes/urls'
import { ErrorTrackingIssue } from '~/queries/schema/schema-general'
diff --git a/products/error_tracking/frontend/components/IssueFilters/DateRange.tsx b/products/error_tracking/frontend/components/IssueFilters/DateRange.tsx
index 35ca2f502e1e..6fc9a5b27fd2 100644
--- a/products/error_tracking/frontend/components/IssueFilters/DateRange.tsx
+++ b/products/error_tracking/frontend/components/IssueFilters/DateRange.tsx
@@ -1,8 +1,8 @@
import { useActions, useValues } from 'kea'
import { DateFilter } from 'lib/components/DateFilter/DateFilter'
-import { dateMapping } from 'lib/utils'
import { cn } from 'lib/utils/css-classes'
+import { dateMapping } from 'lib/utils/dateFilters'
import { issueFiltersLogic } from './issueFiltersLogic'
diff --git a/products/error_tracking/frontend/components/IssueMetadata.tsx b/products/error_tracking/frontend/components/IssueMetadata.tsx
index adc545771076..56f3fe4d2053 100644
--- a/products/error_tracking/frontend/components/IssueMetadata.tsx
+++ b/products/error_tracking/frontend/components/IssueMetadata.tsx
@@ -7,7 +7,7 @@ import { LemonSkeleton, Tooltip } from '@posthog/lemon-ui'
import { ErrorTrackingSpikeEvent } from 'lib/components/Errors/types'
import { dayjs } from 'lib/dayjs'
-import { humanFriendlyLargeNumber } from 'lib/utils'
+import { humanFriendlyLargeNumber } from 'lib/utils/numbers'
import { ErrorTrackingIssueAggregations } from '~/queries/schema/schema-general'
diff --git a/products/error_tracking/frontend/components/SpikeDetailsPopover.tsx b/products/error_tracking/frontend/components/SpikeDetailsPopover.tsx
index 13d7cb6b2a6e..ff4500c5e62a 100644
--- a/products/error_tracking/frontend/components/SpikeDetailsPopover.tsx
+++ b/products/error_tracking/frontend/components/SpikeDetailsPopover.tsx
@@ -6,7 +6,7 @@ import { LemonBanner, LemonSkeleton, Popover } from '@posthog/lemon-ui'
import api from 'lib/api'
import { ErrorTrackingSpikeEvent } from 'lib/components/Errors/types'
import { dayjs } from 'lib/dayjs'
-import { humanFriendlyLargeNumber } from 'lib/utils'
+import { humanFriendlyLargeNumber } from 'lib/utils/numbers'
import { ErrorTrackingIssueAggregations } from '~/queries/schema/schema-general'
diff --git a/products/error_tracking/frontend/components/VolumeSparkline/formatCompactVolumeHover.ts b/products/error_tracking/frontend/components/VolumeSparkline/formatCompactVolumeHover.ts
index 0cd149e45072..908a944ba496 100644
--- a/products/error_tracking/frontend/components/VolumeSparkline/formatCompactVolumeHover.ts
+++ b/products/error_tracking/frontend/components/VolumeSparkline/formatCompactVolumeHover.ts
@@ -1,5 +1,5 @@
import { dayjs } from 'lib/dayjs'
-import { humanFriendlyLargeNumber } from 'lib/utils'
+import { humanFriendlyLargeNumber } from 'lib/utils/numbers'
import type { SparklineDatum } from './types'
diff --git a/products/error_tracking/frontend/hooks/use-sparkline-data.tsx b/products/error_tracking/frontend/hooks/use-sparkline-data.tsx
index ed3249f46d10..db828b895f3e 100644
--- a/products/error_tracking/frontend/hooks/use-sparkline-data.tsx
+++ b/products/error_tracking/frontend/hooks/use-sparkline-data.tsx
@@ -2,7 +2,7 @@ import { useValues } from 'kea'
import { useMemo } from 'react'
import { ErrorTrackingSpikeEvent } from 'lib/components/Errors/types'
-import { dateStringToDayJs } from 'lib/utils'
+import { dateStringToDayJs } from 'lib/utils/dateFilters'
import { DateRange, ErrorTrackingIssueAggregations } from '~/queries/schema/schema-general'
diff --git a/products/error_tracking/frontend/scenes/ErrorTrackingConfigurationScene/rate_limit/IssueRateLimitSettings.tsx b/products/error_tracking/frontend/scenes/ErrorTrackingConfigurationScene/rate_limit/IssueRateLimitSettings.tsx
index 7812eb677bf7..ef82996b5a59 100644
--- a/products/error_tracking/frontend/scenes/ErrorTrackingConfigurationScene/rate_limit/IssueRateLimitSettings.tsx
+++ b/products/error_tracking/frontend/scenes/ErrorTrackingConfigurationScene/rate_limit/IssueRateLimitSettings.tsx
@@ -7,7 +7,7 @@ import { LemonButton } from 'lib/lemon-ui/LemonButton'
import { LemonField } from 'lib/lemon-ui/LemonField'
import { LemonInput } from 'lib/lemon-ui/LemonInput'
import { LemonSkeleton } from 'lib/lemon-ui/LemonSkeleton'
-import { humanFriendlyLargeNumber } from 'lib/utils'
+import { humanFriendlyLargeNumber } from 'lib/utils/numbers'
import { urls } from 'scenes/urls'
import { issueRateLimitConfigLogic } from './issueRateLimitConfigLogic'
diff --git a/products/error_tracking/frontend/scenes/ErrorTrackingConfigurationScene/rate_limit/RateLimitSimulationChart.tsx b/products/error_tracking/frontend/scenes/ErrorTrackingConfigurationScene/rate_limit/RateLimitSimulationChart.tsx
index b448e1b416bd..4fafcb95877a 100644
--- a/products/error_tracking/frontend/scenes/ErrorTrackingConfigurationScene/rate_limit/RateLimitSimulationChart.tsx
+++ b/products/error_tracking/frontend/scenes/ErrorTrackingConfigurationScene/rate_limit/RateLimitSimulationChart.tsx
@@ -2,7 +2,7 @@ import { useMemo } from 'react'
import { getColorVar } from 'lib/colors'
import { dayjs } from 'lib/dayjs'
-import { pluralize } from 'lib/utils'
+import { pluralize } from 'lib/utils/strings'
import { LineGraph } from '~/queries/nodes/DataVisualization/Components/Charts/LineGraph'
import { ChartDisplayType } from '~/types'
diff --git a/products/error_tracking/frontend/scenes/ErrorTrackingConfigurationScene/releases/Releases.tsx b/products/error_tracking/frontend/scenes/ErrorTrackingConfigurationScene/releases/Releases.tsx
index a65279eb02ce..1752c1e66331 100644
--- a/products/error_tracking/frontend/scenes/ErrorTrackingConfigurationScene/releases/Releases.tsx
+++ b/products/error_tracking/frontend/scenes/ErrorTrackingConfigurationScene/releases/Releases.tsx
@@ -5,7 +5,7 @@ import { IconExternal } from '@posthog/icons'
import { LemonTable, LemonTableColumns, Link } from '@posthog/lemon-ui'
import { ErrorTrackingRelease } from 'lib/components/Errors/types'
-import { humanFriendlyDetailedTime } from 'lib/utils'
+import { humanFriendlyDetailedTime } from 'lib/utils/datetime'
import { GitMetadataParser } from 'products/error_tracking/frontend/components/ReleasesPreview/gitMetadataParser'
diff --git a/products/error_tracking/frontend/scenes/ErrorTrackingConfigurationScene/rules/DisabledRuleBanner.tsx b/products/error_tracking/frontend/scenes/ErrorTrackingConfigurationScene/rules/DisabledRuleBanner.tsx
index e486d6164cf1..f1de22fe9c75 100644
--- a/products/error_tracking/frontend/scenes/ErrorTrackingConfigurationScene/rules/DisabledRuleBanner.tsx
+++ b/products/error_tracking/frontend/scenes/ErrorTrackingConfigurationScene/rules/DisabledRuleBanner.tsx
@@ -2,7 +2,7 @@ import { useActions } from 'kea'
import { LemonBanner } from '@posthog/lemon-ui'
-import { truncate } from 'lib/utils'
+import { truncate } from 'lib/utils/strings'
import { sidePanelStateLogic } from '~/layout/navigation-3000/sidepanel/sidePanelStateLogic'
import { SidePanelTab } from '~/types'
diff --git a/products/error_tracking/frontend/scenes/ErrorTrackingConfigurationScene/symbol_sets/SymbolSets.tsx b/products/error_tracking/frontend/scenes/ErrorTrackingConfigurationScene/symbol_sets/SymbolSets.tsx
index cef6f027c158..1b9855915b1a 100644
--- a/products/error_tracking/frontend/scenes/ErrorTrackingConfigurationScene/symbol_sets/SymbolSets.tsx
+++ b/products/error_tracking/frontend/scenes/ErrorTrackingConfigurationScene/symbol_sets/SymbolSets.tsx
@@ -17,7 +17,8 @@ import {
import { ErrorTrackingSymbolSet, SymbolSetStatusFilter } from 'lib/components/Errors/types'
import { IconArrowDown, IconArrowUp } from 'lib/lemon-ui/icons'
-import { humanFriendlyDetailedTime, pluralize } from 'lib/utils'
+import { humanFriendlyDetailedTime } from 'lib/utils/datetime'
+import { pluralize } from 'lib/utils/strings'
import { ReleasePreviewPill } from 'products/error_tracking/frontend/components/ReleasesPreview/ReleasePreviewPill'
diff --git a/products/error_tracking/frontend/scenes/ErrorTrackingConfigurationScene/symbol_sets/symbolSetLogic.tsx b/products/error_tracking/frontend/scenes/ErrorTrackingConfigurationScene/symbol_sets/symbolSetLogic.tsx
index 23ab9aee46bf..82960f8bbae9 100644
--- a/products/error_tracking/frontend/scenes/ErrorTrackingConfigurationScene/symbol_sets/symbolSetLogic.tsx
+++ b/products/error_tracking/frontend/scenes/ErrorTrackingConfigurationScene/symbol_sets/symbolSetLogic.tsx
@@ -5,7 +5,7 @@ import { lemonToast } from '@posthog/lemon-ui'
import api, { CountedPaginatedResponse } from 'lib/api'
import { ErrorTrackingSymbolSet, SymbolSetStatusFilter } from 'lib/components/Errors/types'
-import { pluralize } from 'lib/utils'
+import { pluralize } from 'lib/utils/strings'
import { Scene } from 'scenes/sceneTypes'
import { urls } from 'scenes/urls'
diff --git a/products/error_tracking/frontend/scenes/ErrorTrackingIssueScene/ScenePanel/ErrorTrackingIssueScenePanel.tsx b/products/error_tracking/frontend/scenes/ErrorTrackingIssueScene/ScenePanel/ErrorTrackingIssueScenePanel.tsx
index fe79718bdf89..540dc31125ef 100644
--- a/products/error_tracking/frontend/scenes/ErrorTrackingIssueScene/ScenePanel/ErrorTrackingIssueScenePanel.tsx
+++ b/products/error_tracking/frontend/scenes/ErrorTrackingIssueScene/ScenePanel/ErrorTrackingIssueScenePanel.tsx
@@ -12,9 +12,9 @@ import { useFeatureFlag } from 'lib/hooks/useFeatureFlag'
import { IconFingerprint } from 'lib/lemon-ui/icons'
import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
import { ButtonPrimitive } from 'lib/ui/Button/ButtonPrimitives'
-import { pluralize } from 'lib/utils'
import { copyToClipboard } from 'lib/utils/copyToClipboard'
import { addProductIntentForCrossSell } from 'lib/utils/product-intents'
+import { pluralize } from 'lib/utils/strings'
import { QuickSurveyType } from 'scenes/surveys/quick-create/types'
import { QuickSurveyModal } from 'scenes/surveys/QuickSurveyModal'
import { urls } from 'scenes/urls'
diff --git a/products/error_tracking/frontend/scenes/ErrorTrackingIssueScene/errorTrackingIssueSceneLogic.ts b/products/error_tracking/frontend/scenes/ErrorTrackingIssueScene/errorTrackingIssueSceneLogic.ts
index b2441b66b5b4..bc14ccc9ea61 100644
--- a/products/error_tracking/frontend/scenes/ErrorTrackingIssueScene/errorTrackingIssueSceneLogic.ts
+++ b/products/error_tracking/frontend/scenes/ErrorTrackingIssueScene/errorTrackingIssueSceneLogic.ts
@@ -13,7 +13,7 @@ import {
} from 'lib/components/Errors/types'
import { SetupTaskId, globalSetupLogic } from 'lib/components/ProductSetup'
import { Dayjs, dayjs } from 'lib/dayjs'
-import { uuid } from 'lib/utils'
+import { uuid } from 'lib/utils/dom'
import { MaxContextInput, createMaxContextHelpers } from 'scenes/max/maxTypes'
import { Scene } from 'scenes/sceneTypes'
import { Params } from 'scenes/sceneTypes'
diff --git a/products/error_tracking/frontend/scenes/ErrorTrackingScene/tabs/insights/SummaryStats.tsx b/products/error_tracking/frontend/scenes/ErrorTrackingScene/tabs/insights/SummaryStats.tsx
index 1c8b511d2a17..335c5ff04c76 100644
--- a/products/error_tracking/frontend/scenes/ErrorTrackingScene/tabs/insights/SummaryStats.tsx
+++ b/products/error_tracking/frontend/scenes/ErrorTrackingScene/tabs/insights/SummaryStats.tsx
@@ -2,7 +2,7 @@ import { useValues } from 'kea'
import { LemonSkeleton } from '@posthog/lemon-ui'
-import { compactNumber } from 'lib/utils'
+import { compactNumber } from 'lib/utils/numbers'
import { errorTrackingInsightsLogic } from './errorTrackingInsightsLogic'
diff --git a/products/error_tracking/frontend/scenes/ErrorTrackingScene/tabs/insights/queries.ts b/products/error_tracking/frontend/scenes/ErrorTrackingScene/tabs/insights/queries.ts
index 8da32a05e1fd..8fbb096f495b 100644
--- a/products/error_tracking/frontend/scenes/ErrorTrackingScene/tabs/insights/queries.ts
+++ b/products/error_tracking/frontend/scenes/ErrorTrackingScene/tabs/insights/queries.ts
@@ -1,5 +1,5 @@
import { dayjs } from 'lib/dayjs'
-import { dateStringToDayJs } from 'lib/utils'
+import { dateStringToDayJs } from 'lib/utils/dateFilters'
import { urls } from 'scenes/urls'
import { InsightVizNode, NodeKind, ProductKey, TrendsQuery } from '~/queries/schema/schema-general'
diff --git a/products/error_tracking/frontend/scenes/ErrorTrackingScene/tabs/issues/IssuesList.tsx b/products/error_tracking/frontend/scenes/ErrorTrackingScene/tabs/issues/IssuesList.tsx
index 62ee1a7a196a..a9c1e555c132 100644
--- a/products/error_tracking/frontend/scenes/ErrorTrackingScene/tabs/issues/IssuesList.tsx
+++ b/products/error_tracking/frontend/scenes/ErrorTrackingScene/tabs/issues/IssuesList.tsx
@@ -3,8 +3,8 @@ import { useMemo } from 'react'
import { Tooltip } from '@posthog/lemon-ui'
-import { humanFriendlyLargeNumber } from 'lib/utils'
import { cn } from 'lib/utils/css-classes'
+import { humanFriendlyLargeNumber } from 'lib/utils/numbers'
import { SceneStickyBar } from '~/layout/scenes/components/SceneStickyBar'
import { insightVizDataNodeKey } from '~/queries/nodes/InsightViz/insightVizKeys'
diff --git a/products/error_tracking/frontend/scenes/ErrorTrackingScene/tabs/recommendations/LongRunningIssuesRecommendationCard.tsx b/products/error_tracking/frontend/scenes/ErrorTrackingScene/tabs/recommendations/LongRunningIssuesRecommendationCard.tsx
index d476a338d40e..7b017248de57 100644
--- a/products/error_tracking/frontend/scenes/ErrorTrackingScene/tabs/recommendations/LongRunningIssuesRecommendationCard.tsx
+++ b/products/error_tracking/frontend/scenes/ErrorTrackingScene/tabs/recommendations/LongRunningIssuesRecommendationCard.tsx
@@ -3,7 +3,7 @@ import { useActions } from 'kea'
import { LemonButton, LemonTag, Link } from '@posthog/lemon-ui'
import { dayjs } from 'lib/dayjs'
-import { humanFriendlyLargeNumber } from 'lib/utils'
+import { humanFriendlyLargeNumber } from 'lib/utils/numbers'
import { urls } from 'scenes/urls'
import { RecommendationCard } from './RecommendationCard'
diff --git a/products/error_tracking/frontend/utils.ts b/products/error_tracking/frontend/utils.ts
index 825565923218..4404d9fa2433 100644
--- a/products/error_tracking/frontend/utils.ts
+++ b/products/error_tracking/frontend/utils.ts
@@ -5,7 +5,7 @@ import { MouseEvent } from 'react'
import { ErrorTrackingException } from 'lib/components/Errors/types'
import { Dayjs, dayjs } from 'lib/dayjs'
-import { componentsToDayJs, dateStringToComponents, dateStringToDayJs, isStringDateRegex } from 'lib/utils'
+import { componentsToDayJs, dateStringToComponents, dateStringToDayJs, isStringDateRegex } from 'lib/utils/dateFilters'
import { Params } from 'scenes/sceneTypes'
import { DateRange, ErrorTrackingIssue } from '~/queries/schema/schema-general'
diff --git a/products/experiments/manifest.tsx b/products/experiments/manifest.tsx
index f959c90bbb2b..93c109efae91 100644
--- a/products/experiments/manifest.tsx
+++ b/products/experiments/manifest.tsx
@@ -1,4 +1,4 @@
-import { toParams } from 'lib/utils'
+import { toParams } from 'lib/utils/url'
import { urls } from 'scenes/urls'
import { ExperimentMetric, ProductItemCategory, ProductKey } from '~/queries/schema/schema-general'
diff --git a/products/logs/frontend/LogsScene.stories.tsx b/products/logs/frontend/LogsScene.stories.tsx
index 8cb637070a22..64f89f409fa7 100644
--- a/products/logs/frontend/LogsScene.stories.tsx
+++ b/products/logs/frontend/LogsScene.stories.tsx
@@ -3,8 +3,9 @@ import { router } from 'kea-router'
import { useEffect } from 'react'
import { dayjs } from 'lib/dayjs'
-import { dateStringToDayJs, inStorybookTestRunner, sampleOne, uuid } from 'lib/utils'
-import { deterministicRandom } from 'lib/utils/random'
+import { sampleOne } from 'lib/utils/arrays'
+import { dateStringToDayJs } from 'lib/utils/dateFilters'
+import { inStorybookTestRunner, uuid } from 'lib/utils/dom'
import { App } from 'scenes/App'
import { urls } from 'scenes/urls'
@@ -13,6 +14,22 @@ import { MockSignature } from '~/mocks/utils'
import { LogMessage, LogSeverityLevel } from '~/queries/schema/schema-general'
import { PropertyFilterType } from '~/types'
+function createSeededRandom(seed: number): () => number {
+ // LCG constants from Numerical Recipes
+ let m = 0x80000000 // 2^31
+ let a = 1103515245
+ let c = 12345
+
+ let state = seed ? seed : Math.floor(Math.random() * (m - 1))
+
+ return function () {
+ state = (a * state + c) % m
+ return state / m
+ }
+}
+
+const deterministicRandom = createSeededRandom(1234)
+
const delayIfNotTestRunner = async (): Promise<void> => {
await new Promise((resolve) => setTimeout(resolve, inStorybookTestRunner() ? 0 : 200 + Math.random() * 1000))
}
diff --git a/products/logs/frontend/components/LogsAlerting/LogsAlertEventHistory.tsx b/products/logs/frontend/components/LogsAlerting/LogsAlertEventHistory.tsx
index 724aae0185d9..e02c86ab7d3c 100644
--- a/products/logs/frontend/components/LogsAlerting/LogsAlertEventHistory.tsx
+++ b/products/logs/frontend/components/LogsAlerting/LogsAlertEventHistory.tsx
@@ -3,7 +3,7 @@ import { BindLogic, useActions, useValues } from 'kea'
import { LemonButton, LemonModal, LemonTable, LemonTableColumns, LemonTag, LemonTagType } from '@posthog/lemon-ui'
import { TZLabel } from 'lib/components/TZLabel'
-import { truncate } from 'lib/utils'
+import { truncate } from 'lib/utils/strings'
import {
LogsAlertConfigurationApi,
diff --git a/products/logs/frontend/components/LogsAlerting/LogsAlertSimulation.tsx b/products/logs/frontend/components/LogsAlerting/LogsAlertSimulation.tsx
index 88215380caf3..b3c50678ae6b 100644
--- a/products/logs/frontend/components/LogsAlerting/LogsAlertSimulation.tsx
+++ b/products/logs/frontend/components/LogsAlerting/LogsAlertSimulation.tsx
@@ -6,7 +6,7 @@ import { TZLabel } from 'lib/components/TZLabel'
import { dayjs } from 'lib/dayjs'
import { useChart } from 'lib/hooks/useChart'
import { Tooltip } from 'lib/lemon-ui/Tooltip'
-import { humanFriendlyDuration } from 'lib/utils'
+import { humanFriendlyDuration } from 'lib/utils/durations'
import { LogsAlertSimulateBucketApi, LogsAlertSimulateResponseApi } from 'products/logs/frontend/generated/api.schemas'
diff --git a/products/logs/frontend/components/LogsAlerting/LogsAlertStateTimeline.tsx b/products/logs/frontend/components/LogsAlerting/LogsAlertStateTimeline.tsx
index 9a6ec31efa1d..0c60b65c0184 100644
--- a/products/logs/frontend/components/LogsAlerting/LogsAlertStateTimeline.tsx
+++ b/products/logs/frontend/components/LogsAlerting/LogsAlertStateTimeline.tsx
@@ -3,8 +3,8 @@ import { createPortal } from 'react-dom'
import { dayjs } from 'lib/dayjs'
import { useResizeObserver } from 'lib/hooks/useResizeObserver'
-import { shortTimeZone } from 'lib/utils'
import { cn } from 'lib/utils/css-classes'
+import { shortTimeZone } from 'lib/utils/timezones'
import {
LogsAlertConfigurationStateEnumApi,
diff --git a/products/logs/frontend/components/LogsSampling/LogsSamplingRulesSortableTable.tsx b/products/logs/frontend/components/LogsSampling/LogsSamplingRulesSortableTable.tsx
index 7795ea56e696..cf6259934297 100644
--- a/products/logs/frontend/components/LogsSampling/LogsSamplingRulesSortableTable.tsx
+++ b/products/logs/frontend/components/LogsSampling/LogsSamplingRulesSortableTable.tsx
@@ -25,7 +25,7 @@ import { LemonButton, LemonSwitch } from '@posthog/lemon-ui'
import { SortableDragIcon } from 'lib/lemon-ui/icons'
import { Tooltip } from 'lib/lemon-ui/Tooltip/Tooltip'
-import { compactNumber, humanizeBytes } from 'lib/utils'
+import { compactNumber, humanizeBytes } from 'lib/utils/numbers'
import { urls } from 'scenes/urls'
import { LogsSamplingRuleApi } from 'products/logs/frontend/generated/api.schemas'
diff --git a/products/logs/frontend/components/LogsServices/LogsServices.tsx b/products/logs/frontend/components/LogsServices/LogsServices.tsx
index 01a216f0f282..689ed2186139 100644
--- a/products/logs/frontend/components/LogsServices/LogsServices.tsx
+++ b/products/logs/frontend/components/LogsServices/LogsServices.tsx
@@ -17,7 +17,7 @@ import type { LemonTableColumns } from '@posthog/lemon-ui'
import { Sparkline } from 'lib/components/Sparkline'
import { useFeatureFlag } from 'lib/hooks/useFeatureFlag'
-import { humanFriendlyNumber } from 'lib/utils'
+import { humanFriendlyNumber } from 'lib/utils/numbers'
import { urls } from 'scenes/urls'
import { logsViewerModalLogic } from 'products/logs/frontend/components/LogsViewer/LogsViewerModal/logsViewerModalLogic'
diff --git a/products/logs/frontend/components/LogsViewer/Filters/DateRangeFilter.tsx b/products/logs/frontend/components/LogsViewer/Filters/DateRangeFilter.tsx
index 448360fc7a91..625338724ad2 100644
--- a/products/logs/frontend/components/LogsViewer/Filters/DateRangeFilter.tsx
+++ b/products/logs/frontend/components/LogsViewer/Filters/DateRangeFilter.tsx
@@ -3,7 +3,7 @@ import { useActions, useValues } from 'kea'
import { DateFilter } from 'lib/components/DateFilter/DateFilter'
import { CUSTOM_OPTION_KEY } from 'lib/components/DateFilter/types'
import { dayjs } from 'lib/dayjs'
-import { DATE_TIME_FORMAT, formatDateRange } from 'lib/utils'
+import { DATE_TIME_FORMAT, formatDateRange } from 'lib/utils/datetime'
import { DateMappingOption } from '~/types'
diff --git a/products/logs/frontend/components/LogsViewer/Filters/zoom-utils.ts b/products/logs/frontend/components/LogsViewer/Filters/zoom-utils.ts
index 2621e825a2a9..0f1f089a4bae 100644
--- a/products/logs/frontend/components/LogsViewer/Filters/zoom-utils.ts
+++ b/products/logs/frontend/components/LogsViewer/Filters/zoom-utils.ts
@@ -1,5 +1,5 @@
import { dayjs } from 'lib/dayjs'
-import { dateStringToDayJs } from 'lib/utils'
+import { dateStringToDayJs } from 'lib/utils/dateFilters'
const RELATIVE_DATE_REGEX = /(^-?)(\d+)([hdwmy])$/
diff --git a/products/logs/frontend/components/LogsViewer/LogsExportMenu.tsx b/products/logs/frontend/components/LogsViewer/LogsExportMenu.tsx
index ffbc250fe8de..08bc7ada57de 100644
--- a/products/logs/frontend/components/LogsViewer/LogsExportMenu.tsx
+++ b/products/logs/frontend/components/LogsViewer/LogsExportMenu.tsx
@@ -3,7 +3,7 @@ import { useActions, useValues } from 'kea'
import { IconDownload } from '@posthog/icons'
import { LemonButton, LemonMenu } from '@posthog/lemon-ui'
-import { humanFriendlyNumber } from 'lib/utils'
+import { humanFriendlyNumber } from 'lib/utils/numbers'
import { logsExportLogic } from './logsExportLogic'
import { logsViewerLogic } from './logsViewerLogic'
diff --git a/products/logs/frontend/components/LogsViewer/LogsViewerSparkline/index.tsx b/products/logs/frontend/components/LogsViewer/LogsViewerSparkline/index.tsx
index e6d271dc88a4..d2653a972d7a 100644
--- a/products/logs/frontend/components/LogsViewer/LogsViewerSparkline/index.tsx
+++ b/products/logs/frontend/components/LogsViewer/LogsViewerSparkline/index.tsx
@@ -7,8 +7,8 @@ import { LemonButton, LemonSelect, SpinnerOverlay } from '@posthog/lemon-ui'
import { AnyScaleOptions, Sparkline } from 'lib/components/Sparkline'
import { dayjs } from 'lib/dayjs'
import { useFeatureFlag } from 'lib/hooks/useFeatureFlag'
-import { shortTimeZone } from 'lib/utils'
import { cn } from 'lib/utils/css-classes'
+import { shortTimeZone } from 'lib/utils/timezones'
import { DateRange, LogsSparklineBreakdownBy } from '~/queries/schema/schema-general'
diff --git a/products/logs/frontend/components/LogsViewer/LogsViewerToolbar.tsx b/products/logs/frontend/components/LogsViewer/LogsViewerToolbar.tsx
index 937dda95b94a..cc02fc6c0d2d 100644
--- a/products/logs/frontend/components/LogsViewer/LogsViewerToolbar.tsx
+++ b/products/logs/frontend/components/LogsViewer/LogsViewerToolbar.tsx
@@ -3,7 +3,7 @@ import { useActions, useValues } from 'kea'
import { IconExpand45 } from '@posthog/icons'
import { LemonButton, LemonCheckbox, LemonSegmentedButton } from '@posthog/lemon-ui'
-import { humanFriendlyNumber } from 'lib/utils'
+import { humanFriendlyNumber } from 'lib/utils/numbers'
import { KeyboardShortcut } from '~/layout/navigation-3000/components/KeyboardShortcut'
diff --git a/products/logs/frontend/components/LogsViewer/TimezoneSelect.tsx b/products/logs/frontend/components/LogsViewer/TimezoneSelect.tsx
index 6d0d86af7a54..8529bac5f98c 100644
--- a/products/logs/frontend/components/LogsViewer/TimezoneSelect.tsx
+++ b/products/logs/frontend/components/LogsViewer/TimezoneSelect.tsx
@@ -3,7 +3,7 @@ import { useValues } from 'kea'
import { IconGlobe, IconHome, IconLaptop } from '@posthog/icons'
import { LemonSelect, LemonSelectOptionLeaf, LemonSelectSection } from '@posthog/lemon-ui'
-import { shortTimeZone } from 'lib/utils'
+import { shortTimeZone } from 'lib/utils/timezones'
import { teamLogic } from 'scenes/teamLogic'
export interface TimezoneSelectProps {
diff --git a/products/logs/frontend/components/LogsViewer/data/logsViewerDataLogic.ts b/products/logs/frontend/components/LogsViewer/data/logsViewerDataLogic.ts
index 2735abaa0b57..a29c16bef59a 100644
--- a/products/logs/frontend/components/LogsViewer/data/logsViewerDataLogic.ts
+++ b/products/logs/frontend/components/LogsViewer/data/logsViewerDataLogic.ts
@@ -11,7 +11,7 @@ import api from 'lib/api'
import { dataColorVars } from 'lib/colors'
import { SetupTaskId, globalSetupLogic } from 'lib/components/ProductSetup'
import { dayjs } from 'lib/dayjs'
-import { humanFriendlyDetailedTime } from 'lib/utils'
+import { humanFriendlyDetailedTime } from 'lib/utils/datetime'
import { teamLogic } from 'scenes/teamLogic'
import {
diff --git a/products/logs/frontend/components/SetupPrompt/logsIngestionLogic.test.ts b/products/logs/frontend/components/SetupPrompt/logsIngestionLogic.test.ts
index bd4a9b47ed41..4a966baae356 100644
--- a/products/logs/frontend/components/SetupPrompt/logsIngestionLogic.test.ts
+++ b/products/logs/frontend/components/SetupPrompt/logsIngestionLogic.test.ts
@@ -5,8 +5,8 @@ import { initKeaTests } from '~/test/init'
import { logsIngestionLogic } from './logsIngestionLogic'
-jest.mock('lib/utils', () => ({
- ...jest.requireActual('lib/utils'),
+jest.mock('lib/utils/async', () => ({
+ ...jest.requireActual('lib/utils/async'),
delay: () => Promise.resolve(),
}))
diff --git a/products/logs/frontend/components/SetupPrompt/logsIngestionLogic.tsx b/products/logs/frontend/components/SetupPrompt/logsIngestionLogic.tsx
index be7f5099794d..90da7a24859d 100644
--- a/products/logs/frontend/components/SetupPrompt/logsIngestionLogic.tsx
+++ b/products/logs/frontend/components/SetupPrompt/logsIngestionLogic.tsx
@@ -2,7 +2,7 @@ import { afterMount, kea, path, reducers, selectors } from 'kea'
import { loaders } from 'kea-loaders'
import api from 'lib/api'
-import { retryWithBackoff } from 'lib/utils'
+import { retryWithBackoff } from 'lib/utils/async'
import type { logsIngestionLogicType } from './logsIngestionLogicType'
diff --git a/products/logs/frontend/logsSceneLogic.tsx b/products/logs/frontend/logsSceneLogic.tsx
index d95ea07ba295..e191fb1b65a2 100644
--- a/products/logs/frontend/logsSceneLogic.tsx
+++ b/products/logs/frontend/logsSceneLogic.tsx
@@ -6,7 +6,7 @@ import { syncSearchParams, updateSearchParams } from '@posthog/products-error-tr
import { DEFAULT_UNIVERSAL_GROUP_FILTER } from 'lib/components/UniversalFilters/universalFiltersLogic'
import { trackedActionToUrl } from 'lib/logic/scenes/trackedActionToUrl'
-import { parseTagsFilter } from 'lib/utils'
+import { parseTagsFilter } from 'lib/utils/url'
import { sqlEditorLogic } from 'scenes/data-warehouse/editor/sqlEditorLogic'
import { SQLEditorMode } from 'scenes/data-warehouse/editor/sqlEditorModes'
import { Params } from 'scenes/sceneTypes'
diff --git a/products/logs/frontend/scenes/LogsSamplingDetailScene/LogsSamplingDetailScene.tsx b/products/logs/frontend/scenes/LogsSamplingDetailScene/LogsSamplingDetailScene.tsx
index 4b4ecf7cf104..f97860a26990 100644
--- a/products/logs/frontend/scenes/LogsSamplingDetailScene/LogsSamplingDetailScene.tsx
+++ b/products/logs/frontend/scenes/LogsSamplingDetailScene/LogsSamplingDetailScene.tsx
@@ -5,7 +5,7 @@ import { IconInfo, IconRefresh } from '@posthog/icons'
import { LemonButton, LemonDialog } from '@posthog/lemon-ui'
import { Tooltip } from 'lib/lemon-ui/Tooltip/Tooltip'
-import { compactNumber, humanizeBytes } from 'lib/utils'
+import { compactNumber, humanizeBytes } from 'lib/utils/numbers'
import { SceneExport } from 'scenes/sceneTypes'
import { SceneContent } from '~/layout/scenes/components/SceneContent'
diff --git a/products/logs/frontend/utils.tsx b/products/logs/frontend/utils.tsx
index 59604c3db7b3..ca3a6c107389 100644
--- a/products/logs/frontend/utils.tsx
+++ b/products/logs/frontend/utils.tsx
@@ -1,5 +1,5 @@
import { isValidPropertyFilter } from 'lib/components/PropertyFilters/utils'
-import { capitalizeFirstLetter } from 'lib/utils'
+import { capitalizeFirstLetter } from 'lib/utils/strings'
import { AnyPropertyFilter } from '~/types'
diff --git a/products/mcp_analytics/frontend/MCPAnalyticsToolDetail.tsx b/products/mcp_analytics/frontend/MCPAnalyticsToolDetail.tsx
index 4c1075c2ffd8..acc4555323e4 100644
--- a/products/mcp_analytics/frontend/MCPAnalyticsToolDetail.tsx
+++ b/products/mcp_analytics/frontend/MCPAnalyticsToolDetail.tsx
@@ -28,7 +28,7 @@ import {
import { buildTheme } from 'lib/charts/utils/theme'
import { TZLabel } from 'lib/components/TZLabel'
import { LemonMarkdown } from 'lib/lemon-ui/LemonMarkdown'
-import { humanFriendlyNumber } from 'lib/utils'
+import { humanFriendlyNumber } from 'lib/utils/numbers'
import { PersonDisplay } from 'scenes/persons/PersonDisplay'
import { teamLogic } from 'scenes/teamLogic'
import { urls } from 'scenes/urls'
diff --git a/products/mcp_analytics/frontend/dashboard/HarnessDonut.tsx b/products/mcp_analytics/frontend/dashboard/HarnessDonut.tsx
index f19af3940dc8..60dcf6aa31d2 100644
--- a/products/mcp_analytics/frontend/dashboard/HarnessDonut.tsx
+++ b/products/mcp_analytics/frontend/dashboard/HarnessDonut.tsx
@@ -10,7 +10,7 @@ import {
} from '@posthog/quill-charts'
import { Skeleton } from '@posthog/quill-primitives'
-import { formatPercentage } from 'lib/utils'
+import { formatPercentage } from 'lib/utils/numbers'
import { type HarnessRow } from '../mcpDashboardOverviewLogic'
import { Card } from './Card'
diff --git a/products/mcp_analytics/frontend/dashboard/KpiTiles.tsx b/products/mcp_analytics/frontend/dashboard/KpiTiles.tsx
index 0d92b50b3f39..9b0367f39e19 100644
--- a/products/mcp_analytics/frontend/dashboard/KpiTiles.tsx
+++ b/products/mcp_analytics/frontend/dashboard/KpiTiles.tsx
@@ -2,7 +2,7 @@ import { Link } from '@posthog/lemon-ui'
import { type ChartTheme, MetricCard } from '@posthog/quill-charts'
import { Card, CardContent, Skeleton } from '@posthog/quill-primitives'
-import { formatPercentage } from 'lib/utils'
+import { formatPercentage } from 'lib/utils/numbers'
import { urls } from 'scenes/urls'
import { type KPIData, KPIMetric } from '../mcpDashboardOverviewLogic'
diff --git a/products/mcp_analytics/frontend/dashboard/NotableSessionsTable.tsx b/products/mcp_analytics/frontend/dashboard/NotableSessionsTable.tsx
index c5b864d5626a..01fa6e3d4db2 100644
--- a/products/mcp_analytics/frontend/dashboard/NotableSessionsTable.tsx
+++ b/products/mcp_analytics/frontend/dashboard/NotableSessionsTable.tsx
@@ -14,7 +14,7 @@ import {
TableRow,
} from '@posthog/quill-primitives'
-import { formatPercentage } from 'lib/utils'
+import { formatPercentage } from 'lib/utils/numbers'
import { urls } from 'scenes/urls'
import { type NotableSession } from '../mcpDashboardOverviewLogic'
diff --git a/products/mcp_analytics/frontend/dashboard/ToolErrorRateChart.tsx b/products/mcp_analytics/frontend/dashboard/ToolErrorRateChart.tsx
index 39c29432553f..f4f71bd31f68 100644
--- a/products/mcp_analytics/frontend/dashboard/ToolErrorRateChart.tsx
+++ b/products/mcp_analytics/frontend/dashboard/ToolErrorRateChart.tsx
@@ -10,7 +10,7 @@ import {
} from '@posthog/quill-charts'
import { Skeleton } from '@posthog/quill-primitives'
-import { formatPercentage } from 'lib/utils'
+import { formatPercentage } from 'lib/utils/numbers'
import { type ToolRow } from '../mcpDashboardOverviewLogic'
import { Card, CardState } from './Card'
diff --git a/products/mcp_analytics/frontend/dashboard/formatters.ts b/products/mcp_analytics/frontend/dashboard/formatters.ts
index 6261ff945c7c..154010b21105 100644
--- a/products/mcp_analytics/frontend/dashboard/formatters.ts
+++ b/products/mcp_analytics/frontend/dashboard/formatters.ts
@@ -1,4 +1,5 @@
-import { humanFriendlyDuration, humanFriendlyLargeNumber } from 'lib/utils'
+import { humanFriendlyDuration } from 'lib/utils/durations'
+import { humanFriendlyLargeNumber } from 'lib/utils/numbers'
const EMPTY = '—'
diff --git a/products/mcp_analytics/frontend/mcpAnalyticsToolQualityLogic.ts b/products/mcp_analytics/frontend/mcpAnalyticsToolQualityLogic.ts
index 3992a290f734..9153ddf2619f 100644
--- a/products/mcp_analytics/frontend/mcpAnalyticsToolQualityLogic.ts
+++ b/products/mcp_analytics/frontend/mcpAnalyticsToolQualityLogic.ts
@@ -4,7 +4,7 @@ import { actionToUrl, router, urlToAction } from 'kea-router'
import api from 'lib/api'
import { dayjs } from 'lib/dayjs'
-import { dateStringToDayJs } from 'lib/utils'
+import { dateStringToDayJs } from 'lib/utils/dateFilters'
import { teamLogic } from 'scenes/teamLogic'
import { urls } from 'scenes/urls'
diff --git a/products/mcp_analytics/frontend/tool-quality/ToolQualityCharts.tsx b/products/mcp_analytics/frontend/tool-quality/ToolQualityCharts.tsx
index 09332c8f36ff..1f1f803fa887 100644
--- a/products/mcp_analytics/frontend/tool-quality/ToolQualityCharts.tsx
+++ b/products/mcp_analytics/frontend/tool-quality/ToolQualityCharts.tsx
@@ -10,7 +10,7 @@ import {
legendItemsFromSeries,
} from '@posthog/quill-charts'
-import { formatPercentage } from 'lib/utils'
+import { formatPercentage } from 'lib/utils/numbers'
import { Card, CardState } from '../dashboard/Card'
import { formatMsAsSeconds } from '../dashboard/formatters'
diff --git a/products/mcp_analytics/frontend/tool-quality/ToolQualityTable.tsx b/products/mcp_analytics/frontend/tool-quality/ToolQualityTable.tsx
index b5fc908afeb0..84a6d576cd6a 100644
--- a/products/mcp_analytics/frontend/tool-quality/ToolQualityTable.tsx
+++ b/products/mcp_analytics/frontend/tool-quality/ToolQualityTable.tsx
@@ -24,7 +24,8 @@ import {
import { TZLabel } from 'lib/components/TZLabel'
import { LinkPrimitive } from 'lib/lemon-ui/Link/Link'
import { Tooltip } from 'lib/lemon-ui/Tooltip'
-import { formatPercentage, pluralize } from 'lib/utils'
+import { formatPercentage } from 'lib/utils/numbers'
+import { pluralize } from 'lib/utils/strings'
import { urls } from 'scenes/urls'
import { formatMs, formatNumber } from '../dashboard/formatters'
diff --git a/products/metrics/frontend/components/MetricsViewer.tsx b/products/metrics/frontend/components/MetricsViewer.tsx
index 44ab26bb6777..6e6dcfb2bc66 100644
--- a/products/metrics/frontend/components/MetricsViewer.tsx
+++ b/products/metrics/frontend/components/MetricsViewer.tsx
@@ -7,7 +7,7 @@ import { DateFilter } from 'lib/components/DateFilter/DateFilter'
import { CUSTOM_OPTION_KEY } from 'lib/components/DateFilter/types'
import { AnyScaleOptions, Sparkline } from 'lib/components/Sparkline'
import { dayjs } from 'lib/dayjs'
-import { DATE_TIME_FORMAT, formatDateRange } from 'lib/utils'
+import { DATE_TIME_FORMAT, formatDateRange } from 'lib/utils/datetime'
import { DateMappingOption } from '~/types'
diff --git a/products/metrics/frontend/components/metricsViewerLogic.tsx b/products/metrics/frontend/components/metricsViewerLogic.tsx
index ab9e72fa05fe..808500eb6b78 100644
--- a/products/metrics/frontend/components/metricsViewerLogic.tsx
+++ b/products/metrics/frontend/components/metricsViewerLogic.tsx
@@ -2,7 +2,7 @@ import { actions, connect, kea, listeners, path, reducers, selectors } from 'kea
import { loaders } from 'kea-loaders'
import { dayjs } from 'lib/dayjs'
-import { dateStringToDayJs } from 'lib/utils'
+import { dateStringToDayJs } from 'lib/utils/dateFilters'
import { teamLogic } from 'scenes/teamLogic'
import { metricsQueryCreate } from 'products/metrics/frontend/generated/api'
diff --git a/products/metrics/frontend/metricsIngestionLogic.tsx b/products/metrics/frontend/metricsIngestionLogic.tsx
index 33672fb5b628..5c6b05d63e4f 100644
--- a/products/metrics/frontend/metricsIngestionLogic.tsx
+++ b/products/metrics/frontend/metricsIngestionLogic.tsx
@@ -2,7 +2,7 @@ import { afterMount, kea, path, reducers, selectors } from 'kea'
import { loaders } from 'kea-loaders'
import api from 'lib/api'
-import { retryWithBackoff } from 'lib/utils'
+import { retryWithBackoff } from 'lib/utils/async'
import type { metricsIngestionLogicType } from './metricsIngestionLogicType'
diff --git a/products/product_analytics/frontend/insights/funnels/FunnelBarHorizontalChart/StepHeader.tsx b/products/product_analytics/frontend/insights/funnels/FunnelBarHorizontalChart/StepHeader.tsx
index 8b745b421c94..aecba3748277 100644
--- a/products/product_analytics/frontend/insights/funnels/FunnelBarHorizontalChart/StepHeader.tsx
+++ b/products/product_analytics/frontend/insights/funnels/FunnelBarHorizontalChart/StepHeader.tsx
@@ -1,7 +1,7 @@
import clsx from 'clsx'
import { EntityFilterInfo } from 'lib/components/EntityFilterInfo'
-import { humanFriendlyDuration } from 'lib/utils'
+import { humanFriendlyDuration } from 'lib/utils/durations'
import { DuplicateStepIndicator } from 'scenes/funnels/FunnelBarHorizontal/DuplicateStepIndicator'
import { FunnelStepMore } from 'scenes/funnels/FunnelStepMore'
import { getActionFilterFromFunnelStep } from 'scenes/insights/views/Funnels/funnelStepTableUtils'
diff --git a/products/product_analytics/frontend/insights/funnels/FunnelHistogramChart/FunnelHistogramChart.tsx b/products/product_analytics/frontend/insights/funnels/FunnelHistogramChart/FunnelHistogramChart.tsx
index 579dd1f8ac6b..fcc2beacc27c 100644
--- a/products/product_analytics/frontend/insights/funnels/FunnelHistogramChart/FunnelHistogramChart.tsx
+++ b/products/product_analytics/frontend/insights/funnels/FunnelHistogramChart/FunnelHistogramChart.tsx
@@ -6,7 +6,8 @@ import { BarChart, ValueLabels } from '@posthog/quill-charts'
import type { BarChartConfig } from '@posthog/quill-charts'
import { buildTheme } from 'lib/charts/utils/theme'
-import { hexToRGBA, humanFriendlyNumber } from 'lib/utils'
+import { hexToRGBA } from 'lib/utils/colors'
+import { humanFriendlyNumber } from 'lib/utils/numbers'
import { funnelDataLogic } from 'scenes/funnels/funnelDataLogic'
import { insightLogic } from 'scenes/insights/insightLogic'
import { insightVizDataLogic } from 'scenes/insights/insightVizDataLogic'
diff --git a/products/product_analytics/frontend/insights/funnels/FunnelHistogramChart/funnelHistogramTransforms.ts b/products/product_analytics/frontend/insights/funnels/FunnelHistogramChart/funnelHistogramTransforms.ts
index e785a1aff54b..5bfed33c123f 100644
--- a/products/product_analytics/frontend/insights/funnels/FunnelHistogramChart/funnelHistogramTransforms.ts
+++ b/products/product_analytics/frontend/insights/funnels/FunnelHistogramChart/funnelHistogramTransforms.ts
@@ -1,6 +1,6 @@
import type { Series } from '@posthog/quill-charts'
-import { humanFriendlyDuration } from 'lib/utils'
+import { humanFriendlyDuration } from 'lib/utils/durations'
import type { HistogramGraphDatum } from '~/types'
diff --git a/products/product_analytics/frontend/insights/funnels/FunnelLineChart/handleFunnelLineChartClick.tsx b/products/product_analytics/frontend/insights/funnels/FunnelLineChart/handleFunnelLineChartClick.tsx
index 83df352ac89f..86c7d5cd4505 100644
--- a/products/product_analytics/frontend/insights/funnels/FunnelLineChart/handleFunnelLineChartClick.tsx
+++ b/products/product_analytics/frontend/insights/funnels/FunnelLineChart/handleFunnelLineChartClick.tsx
@@ -1,6 +1,6 @@
import { DateDisplay } from 'lib/components/DateDisplay'
import { dayjs } from 'lib/dayjs'
-import { capitalizeFirstLetter } from 'lib/utils'
+import { capitalizeFirstLetter } from 'lib/utils/strings'
import { hasBreakdown } from 'scenes/funnels/funnelUtils'
import { formatBreakdownLabel } from 'scenes/insights/utils'
import type { OpenPersonsModalProps } from 'scenes/trends/persons-modal/PersonsModal'
diff --git a/products/product_analytics/frontend/insights/retention/shared/RetentionTooltip.tsx b/products/product_analytics/frontend/insights/retention/shared/RetentionTooltip.tsx
index e694c97acf21..bf1e8c48c74b 100644
--- a/products/product_analytics/frontend/insights/retention/shared/RetentionTooltip.tsx
+++ b/products/product_analytics/frontend/insights/retention/shared/RetentionTooltip.tsx
@@ -2,7 +2,7 @@ import { useCallback, useMemo } from 'react'
import type { TooltipContext } from '@posthog/quill-charts'
-import { roundToDecimal } from 'lib/utils'
+import { roundToDecimal } from 'lib/utils/numbers'
import { InsightTooltip } from 'scenes/insights/InsightTooltip/InsightTooltip'
import type { SeriesDatum } from 'scenes/insights/InsightTooltip/insightTooltipUtils'
diff --git a/products/product_analytics/frontend/insights/trends/TrendsBarChart/TrendsBarChart.tsx b/products/product_analytics/frontend/insights/trends/TrendsBarChart/TrendsBarChart.tsx
index 331f34fa8210..1ad8af4900a7 100644
--- a/products/product_analytics/frontend/insights/trends/TrendsBarChart/TrendsBarChart.tsx
+++ b/products/product_analytics/frontend/insights/trends/TrendsBarChart/TrendsBarChart.tsx
@@ -13,7 +13,7 @@ import {
import type { BarChartConfig, PointClickData, TimeSeriesBarChartConfig, TooltipContext } from '@posthog/quill-charts'
import { buildTheme } from 'lib/charts/utils/theme'
-import { percentage } from 'lib/utils'
+import { percentage } from 'lib/utils/numbers'
import { formatAggregationAxisValue } from 'scenes/insights/aggregationAxisFormat'
import { InsightEmptyState } from 'scenes/insights/EmptyStates'
import { insightLogic } from 'scenes/insights/insightLogic'
diff --git a/products/product_analytics/frontend/insights/trends/TrendsBarChart/trendsBarChartTransforms.test.ts b/products/product_analytics/frontend/insights/trends/TrendsBarChart/trendsBarChartTransforms.test.ts
index 32f2a20bffa2..9b5a5e7cd123 100644
--- a/products/product_analytics/frontend/insights/trends/TrendsBarChart/trendsBarChartTransforms.test.ts
+++ b/products/product_analytics/frontend/insights/trends/TrendsBarChart/trendsBarChartTransforms.test.ts
@@ -1,4 +1,4 @@
-import { hexToRGBA } from 'lib/utils'
+import { hexToRGBA } from 'lib/utils/colors'
import type { CurrencyCode, GoalLine as SchemaGoalLine, TrendsFilter } from '~/queries/schema/schema-general'
diff --git a/products/product_analytics/frontend/insights/trends/TrendsLineChart/TrendsLineChart.tsx b/products/product_analytics/frontend/insights/trends/TrendsLineChart/TrendsLineChart.tsx
index 6573791daf2a..4ec6def86629 100644
--- a/products/product_analytics/frontend/insights/trends/TrendsLineChart/TrendsLineChart.tsx
+++ b/products/product_analytics/frontend/insights/trends/TrendsLineChart/TrendsLineChart.tsx
@@ -6,7 +6,7 @@ import type { PointClickData, TooltipConfig, TooltipContext } from '@posthog/qui
import { buildTheme } from 'lib/charts/utils/theme'
import { ciRanges } from 'lib/statistics'
-import { percentage } from 'lib/utils'
+import { percentage } from 'lib/utils/numbers'
import { formatAggregationAxisValue } from 'scenes/insights/aggregationAxisFormat'
import { InsightEmptyState } from 'scenes/insights/EmptyStates'
import { insightLogic } from 'scenes/insights/insightLogic'
diff --git a/products/product_analytics/frontend/insights/trends/shared/TrendsTooltip.tsx b/products/product_analytics/frontend/insights/trends/shared/TrendsTooltip.tsx
index cdef5196edd4..d6d308c64b6b 100644
--- a/products/product_analytics/frontend/insights/trends/shared/TrendsTooltip.tsx
+++ b/products/product_analytics/frontend/insights/trends/shared/TrendsTooltip.tsx
@@ -3,7 +3,7 @@ import { useCallback, useMemo } from 'react'
import type { TooltipContext } from '@posthog/quill-charts'
import { SeriesLetter } from 'lib/components/SeriesGlyph'
-import { percentage } from 'lib/utils'
+import { percentage } from 'lib/utils/numbers'
import { formatAggregationAxisValue } from 'scenes/insights/aggregationAxisFormat'
import { InsightTooltip } from 'scenes/insights/InsightTooltip/InsightTooltip'
import { getDatumTitle, SeriesDatum } from 'scenes/insights/InsightTooltip/insightTooltipUtils'
diff --git a/products/replay_vision/frontend/components/ObservationCard.tsx b/products/replay_vision/frontend/components/ObservationCard.tsx
index d96a05efef2a..3f12674b690b 100644
--- a/products/replay_vision/frontend/components/ObservationCard.tsx
+++ b/products/replay_vision/frontend/components/ObservationCard.tsx
@@ -1,7 +1,7 @@
import { IconRewindPlay, IconSparkles } from '@posthog/icons'
import { LemonTag, Link, Spinner, Tooltip } from '@posthog/lemon-ui'
-import { colonDelimitedDuration } from 'lib/utils'
+import { colonDelimitedDuration } from 'lib/utils/durations'
import { urls } from 'scenes/urls'
import type { ReplayObservationApi, ScannerSnapshotApi } from '../generated/api.schemas'
diff --git a/products/replay_vision/frontend/replay_scanners/components/ScannerRunTab.tsx b/products/replay_vision/frontend/replay_scanners/components/ScannerRunTab.tsx
index 5b4f857766de..c8350843026e 100644
--- a/products/replay_vision/frontend/replay_scanners/components/ScannerRunTab.tsx
+++ b/products/replay_vision/frontend/replay_scanners/components/ScannerRunTab.tsx
@@ -7,7 +7,7 @@ import { LemonButton, LemonInput, LemonTable, LemonTag, Link, Spinner } from '@p
import { AccessControlAction } from 'lib/components/AccessControlAction'
import { TZLabel } from 'lib/components/TZLabel'
import { LemonTableColumns } from 'lib/lemon-ui/LemonTable'
-import { humanFriendlyDuration } from 'lib/utils'
+import { humanFriendlyDuration } from 'lib/utils/durations'
import { ReplayFiltersTab } from 'scenes/session-recordings/filters/RecordingsUniversalFiltersEmbed'
import {
SessionRecordingPlaylistLogicProps,
diff --git a/products/replay_vision/frontend/replay_scanners/replayScannerLogic.ts b/products/replay_vision/frontend/replay_scanners/replayScannerLogic.ts
index 0b47cf76d0b7..a1cbbbcb6f6c 100644
--- a/products/replay_vision/frontend/replay_scanners/replayScannerLogic.ts
+++ b/products/replay_vision/frontend/replay_scanners/replayScannerLogic.ts
@@ -5,7 +5,7 @@ import { actionToUrl, router, urlToAction } from 'kea-router'
import { dayjs } from 'lib/dayjs'
import { lemonToast } from 'lib/lemon-ui/LemonToast'
-import { objectsEqual } from 'lib/utils'
+import { objectsEqual } from 'lib/utils/objects'
import { teamLogic } from 'scenes/teamLogic'
import { urls } from 'scenes/urls'
diff --git a/products/revenue_analytics/frontend/RevenueAnalyticsFilters.tsx b/products/revenue_analytics/frontend/RevenueAnalyticsFilters.tsx
index 9591fd3f7f88..7279c8051d7e 100644
--- a/products/revenue_analytics/frontend/RevenueAnalyticsFilters.tsx
+++ b/products/revenue_analytics/frontend/RevenueAnalyticsFilters.tsx
@@ -15,7 +15,7 @@ import { TaxonomicFilter } from 'lib/components/TaxonomicFilter/TaxonomicFilter'
import { TaxonomicFilterGroupType } from 'lib/components/TaxonomicFilter/types'
import { dayjs } from 'lib/dayjs'
import { IconAreaChart, IconWithCount } from 'lib/lemon-ui/icons'
-import { DATE_FORMAT, formatDateRange } from 'lib/utils'
+import { DATE_FORMAT, formatDateRange } from 'lib/utils/datetime'
import { BreakdownTag } from 'scenes/insights/filters/BreakdownFilter/BreakdownTag'
import MaxTool from 'scenes/max/MaxTool'
import { Scene } from 'scenes/sceneTypes'
diff --git a/products/revenue_analytics/frontend/RevenueAnalyticsViewStatusIcon.tsx b/products/revenue_analytics/frontend/RevenueAnalyticsViewStatusIcon.tsx
index 9cc99df1011b..25c0a8c4115c 100644
--- a/products/revenue_analytics/frontend/RevenueAnalyticsViewStatusIcon.tsx
+++ b/products/revenue_analytics/frontend/RevenueAnalyticsViewStatusIcon.tsx
@@ -5,7 +5,7 @@ import { IconCheckCircle, IconClock, IconInfo, IconRefresh, IconWarning } from '
import { LemonButton, LemonTable, Link, Popover } from '@posthog/lemon-ui'
import { dayjs } from 'lib/dayjs'
-import { humanFriendlyDuration } from 'lib/utils'
+import { humanFriendlyDuration } from 'lib/utils/durations'
import { urls } from 'scenes/urls'
import { DataWarehouseSavedQuery } from '~/types'
diff --git a/products/revenue_analytics/frontend/nodes/RevenueAnalyticsGrossRevenueNode.tsx b/products/revenue_analytics/frontend/nodes/RevenueAnalyticsGrossRevenueNode.tsx
index 90693d50d779..648ae2a7924c 100644
--- a/products/revenue_analytics/frontend/nodes/RevenueAnalyticsGrossRevenueNode.tsx
+++ b/products/revenue_analytics/frontend/nodes/RevenueAnalyticsGrossRevenueNode.tsx
@@ -2,7 +2,7 @@ import { BindLogic, BuiltLogic, LogicWrapper, useValues } from 'kea'
import { useState } from 'react'
import { useAttachedLogic } from 'lib/logic/scenes/useAttachedLogic'
-import { getCurrencySymbol } from 'lib/utils/geography/currency'
+import { getCurrencySymbol } from 'lib/utils/currency'
import { insightLogic } from 'scenes/insights/insightLogic'
import { insightVizDataLogic } from 'scenes/insights/insightVizDataLogic'
diff --git a/products/revenue_analytics/frontend/nodes/RevenueAnalyticsMRRNode.tsx b/products/revenue_analytics/frontend/nodes/RevenueAnalyticsMRRNode.tsx
index aaf444139099..4ec716190e76 100644
--- a/products/revenue_analytics/frontend/nodes/RevenueAnalyticsMRRNode.tsx
+++ b/products/revenue_analytics/frontend/nodes/RevenueAnalyticsMRRNode.tsx
@@ -5,7 +5,7 @@ import { IconGraph } from '@posthog/icons'
import { LemonButton, LemonSegmentedButton, LemonSegmentedButtonOption } from '@posthog/lemon-ui'
import { useAttachedLogic } from 'lib/logic/scenes/useAttachedLogic'
-import { getCurrencySymbol } from 'lib/utils/geography/currency'
+import { getCurrencySymbol } from 'lib/utils/currency'
import { insightLogic } from 'scenes/insights/insightLogic'
import { insightVizDataLogic } from 'scenes/insights/insightVizDataLogic'
diff --git a/products/revenue_analytics/frontend/nodes/RevenueAnalyticsMetricsNode.tsx b/products/revenue_analytics/frontend/nodes/RevenueAnalyticsMetricsNode.tsx
index 102a2016a57d..03fc32fd1e44 100644
--- a/products/revenue_analytics/frontend/nodes/RevenueAnalyticsMetricsNode.tsx
+++ b/products/revenue_analytics/frontend/nodes/RevenueAnalyticsMetricsNode.tsx
@@ -2,7 +2,7 @@ import { BindLogic, BuiltLogic, LogicWrapper, useValues } from 'kea'
import { useState } from 'react'
import { useAttachedLogic } from 'lib/logic/scenes/useAttachedLogic'
-import { getCurrencySymbol } from 'lib/utils/geography/currency'
+import { getCurrencySymbol } from 'lib/utils/currency'
import { insightLogic } from 'scenes/insights/insightLogic'
import { insightVizDataLogic } from 'scenes/insights/insightVizDataLogic'
diff --git a/products/revenue_analytics/frontend/nodes/RevenueAnalyticsOverviewNode.tsx b/products/revenue_analytics/frontend/nodes/RevenueAnalyticsOverviewNode.tsx
index 6c376a66ce5a..b434b336f282 100644
--- a/products/revenue_analytics/frontend/nodes/RevenueAnalyticsOverviewNode.tsx
+++ b/products/revenue_analytics/frontend/nodes/RevenueAnalyticsOverviewNode.tsx
@@ -5,7 +5,7 @@ import { LemonSkeleton } from '@posthog/lemon-ui'
import { useAttachedLogic } from 'lib/logic/scenes/useAttachedLogic'
import { cn } from 'lib/utils/css-classes'
-import { formatCurrency } from 'lib/utils/geography/currency'
+import { formatCurrency } from 'lib/utils/currency'
import { teamLogic } from 'scenes/teamLogic'
import { dataNodeLogic } from '~/queries/nodes/DataNode/dataNodeLogic'
diff --git a/products/revenue_analytics/frontend/nodes/RevenueAnalyticsTopCustomersNode.tsx b/products/revenue_analytics/frontend/nodes/RevenueAnalyticsTopCustomersNode.tsx
index 0ed2fd649e7c..7d475e3f9b90 100644
--- a/products/revenue_analytics/frontend/nodes/RevenueAnalyticsTopCustomersNode.tsx
+++ b/products/revenue_analytics/frontend/nodes/RevenueAnalyticsTopCustomersNode.tsx
@@ -2,7 +2,7 @@ import { BindLogic, BuiltLogic, LogicWrapper, useValues } from 'kea'
import { useMemo, useState } from 'react'
import { useAttachedLogic } from 'lib/logic/scenes/useAttachedLogic'
-import { getCurrencySymbol } from 'lib/utils/geography/currency'
+import { getCurrencySymbol } from 'lib/utils/currency'
import { InsightLoadingState } from 'scenes/insights/EmptyStates'
import { insightLogic } from 'scenes/insights/insightLogic'
import { InsightsWrapper } from 'scenes/insights/InsightsWrapper'
diff --git a/products/revenue_analytics/frontend/nodes/modals/MRRBreakdownChart.tsx b/products/revenue_analytics/frontend/nodes/modals/MRRBreakdownChart.tsx
index a631e58d2491..6ecce99c93b3 100644
--- a/products/revenue_analytics/frontend/nodes/modals/MRRBreakdownChart.tsx
+++ b/products/revenue_analytics/frontend/nodes/modals/MRRBreakdownChart.tsx
@@ -2,7 +2,7 @@ import { useValues } from 'kea'
import { useCallback } from 'react'
import { getBarColorFromStatus } from 'lib/colors'
-import { getCurrencySymbol } from 'lib/utils/geography/currency'
+import { getCurrencySymbol } from 'lib/utils/currency'
import { InsightsWrapper } from 'scenes/insights/InsightsWrapper'
import { teamLogic } from 'scenes/teamLogic'
diff --git a/products/revenue_analytics/frontend/revenueAnalyticsLogic.ts b/products/revenue_analytics/frontend/revenueAnalyticsLogic.ts
index 830ef084a5d8..82c3f610165a 100644
--- a/products/revenue_analytics/frontend/revenueAnalyticsLogic.ts
+++ b/products/revenue_analytics/frontend/revenueAnalyticsLogic.ts
@@ -5,8 +5,9 @@ import { lemonToast } from '@posthog/lemon-ui'
import api from 'lib/api'
import { trackedActionToUrl } from 'lib/logic/scenes/trackedActionToUrl'
-import { getDefaultInterval, objectsEqual } from 'lib/utils'
+import { getDefaultInterval } from 'lib/utils/dateFilters'
import { eventUsageLogic } from 'lib/utils/eventUsageLogic'
+import { objectsEqual } from 'lib/utils/objects'
import { dataWarehouseViewsLogic } from 'scenes/data-warehouse/saved_queries/dataWarehouseViewsLogic'
import { MaxContextInput, createMaxContextHelpers } from 'scenes/max/maxTypes'
import { teamLogic } from 'scenes/teamLogic'
diff --git a/products/revenue_analytics/frontend/settings/EventConfiguration.tsx b/products/revenue_analytics/frontend/settings/EventConfiguration.tsx
index caaaf334c09a..9500466b6ba0 100644
--- a/products/revenue_analytics/frontend/settings/EventConfiguration.tsx
+++ b/products/revenue_analytics/frontend/settings/EventConfiguration.tsx
@@ -8,7 +8,7 @@ import { AccessControlAction } from 'lib/components/AccessControlAction'
import { FEATURE_FLAGS } from 'lib/constants'
import { LemonTable } from 'lib/lemon-ui/LemonTable'
import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
-import { CURRENCY_SYMBOL_TO_EMOJI_MAP, getCurrencySymbol } from 'lib/utils/geography/currency'
+import { CURRENCY_SYMBOL_TO_EMOJI_MAP, getCurrencySymbol } from 'lib/utils/currency'
import { DataWarehouseManagedViewsetImpactModal } from 'scenes/data-management/managed-viewsets/DataWarehouseManagedViewsetImpactModal'
import { disableDataWarehouseManagedViewsetModalLogic } from 'scenes/data-management/managed-viewsets/disableDataWarehouseManagedViewsetModalLogic'
diff --git a/products/revenue_analytics/frontend/settings/GoalsConfiguration.tsx b/products/revenue_analytics/frontend/settings/GoalsConfiguration.tsx
index 48f934e94ea8..5406c679f089 100644
--- a/products/revenue_analytics/frontend/settings/GoalsConfiguration.tsx
+++ b/products/revenue_analytics/frontend/settings/GoalsConfiguration.tsx
@@ -10,10 +10,11 @@ import { LemonButton } from 'lib/lemon-ui/LemonButton'
import { LemonCalendarSelectInput } from 'lib/lemon-ui/LemonCalendar/LemonCalendarSelect'
import { LemonInput } from 'lib/lemon-ui/LemonInput'
import { LemonTable, LemonTableColumns } from 'lib/lemon-ui/LemonTable'
-import { humanFriendlyNumber, inStorybook, inStorybookTestRunner } from 'lib/utils'
import { cn } from 'lib/utils/css-classes'
+import { getCurrencySymbol } from 'lib/utils/currency'
+import { inStorybook, inStorybookTestRunner } from 'lib/utils/dom'
import { eventUsageLogic } from 'lib/utils/eventUsageLogic'
-import { getCurrencySymbol } from 'lib/utils/geography/currency'
+import { humanFriendlyNumber } from 'lib/utils/numbers'
import { teamLogic } from 'scenes/teamLogic'
import { SceneSection } from '~/layout/scenes/components/SceneSection'
diff --git a/products/revenue_analytics/frontend/settings/RevenueExampleTableColumns.tsx b/products/revenue_analytics/frontend/settings/RevenueExampleTableColumns.tsx
index 2e122fd35c09..f598ab453952 100644
--- a/products/revenue_analytics/frontend/settings/RevenueExampleTableColumns.tsx
+++ b/products/revenue_analytics/frontend/settings/RevenueExampleTableColumns.tsx
@@ -1,6 +1,6 @@
-import { humanFriendlyNumber } from 'lib/utils'
-import { CURRENCY_SYMBOL_TO_EMOJI_MAP } from 'lib/utils/geography/currency'
-import { getCurrencySymbol } from 'lib/utils/geography/currency'
+import { CURRENCY_SYMBOL_TO_EMOJI_MAP } from 'lib/utils/currency'
+import { getCurrencySymbol } from 'lib/utils/currency'
+import { humanFriendlyNumber } from 'lib/utils/numbers'
import { CurrencyCode } from '~/queries/schema/schema-general'
diff --git a/products/revenue_analytics/frontend/settings/revenueAnalyticsSettingsLogic.ts b/products/revenue_analytics/frontend/settings/revenueAnalyticsSettingsLogic.ts
index 3b89f708c497..9f77bceb5f6f 100644
--- a/products/revenue_analytics/frontend/settings/revenueAnalyticsSettingsLogic.ts
+++ b/products/revenue_analytics/frontend/settings/revenueAnalyticsSettingsLogic.ts
@@ -6,8 +6,8 @@ import { lemonToast } from '@posthog/lemon-ui'
import { SetupTaskId, globalSetupLogic } from 'lib/components/ProductSetup'
import { dayjs } from 'lib/dayjs'
-import { objectsEqual } from 'lib/utils'
import { eventUsageLogic } from 'lib/utils/eventUsageLogic'
+import { objectsEqual } from 'lib/utils/objects'
import { databaseTableListLogic } from 'scenes/data-management/database/databaseTableListLogic'
import { teamLogic } from 'scenes/teamLogic'
diff --git a/products/revenue_analytics/frontend/tiles/TopCustomersTile.tsx b/products/revenue_analytics/frontend/tiles/TopCustomersTile.tsx
index fdb573b88961..091da9ae7021 100644
--- a/products/revenue_analytics/frontend/tiles/TopCustomersTile.tsx
+++ b/products/revenue_analytics/frontend/tiles/TopCustomersTile.tsx
@@ -5,8 +5,8 @@ import { IconInfo, IconLineGraph } from '@posthog/icons'
import { LemonSegmentedButton, Tooltip } from '@posthog/lemon-ui'
import { IconTableChart } from 'lib/lemon-ui/icons'
-import { humanFriendlyNumber } from 'lib/utils'
-import { getCurrencySymbol } from 'lib/utils/geography/currency'
+import { getCurrencySymbol } from 'lib/utils/currency'
+import { humanFriendlyNumber } from 'lib/utils/numbers'
import { teamLogic } from 'scenes/teamLogic'
import { Query } from '~/queries/Query/Query'
diff --git a/products/session_summaries/frontend/SessionGroupSummaryDetailsMetadata.tsx b/products/session_summaries/frontend/SessionGroupSummaryDetailsMetadata.tsx
index c495f1e6ddb6..e73e8e1a4f56 100644
--- a/products/session_summaries/frontend/SessionGroupSummaryDetailsMetadata.tsx
+++ b/products/session_summaries/frontend/SessionGroupSummaryDetailsMetadata.tsx
@@ -1,7 +1,7 @@
import { IconClock } from '@posthog/icons'
import { TZLabel } from 'lib/components/TZLabel'
-import { colonDelimitedDuration } from 'lib/utils'
+import { colonDelimitedDuration } from 'lib/utils/durations'
import { PatternAssignedEventSegmentContext } from './types'
diff --git a/products/session_summaries/frontend/SessionGroupSummaryDetailsModal.tsx b/products/session_summaries/frontend/SessionGroupSummaryDetailsModal.tsx
index 17bf36d2ad76..17684ef7442a 100644
--- a/products/session_summaries/frontend/SessionGroupSummaryDetailsModal.tsx
+++ b/products/session_summaries/frontend/SessionGroupSummaryDetailsModal.tsx
@@ -4,8 +4,8 @@ import { useEffect } from 'react'
import { IconShare, IconX } from '@posthog/icons'
import { LemonButton, LemonModal } from '@posthog/lemon-ui'
-import { colonDelimitedDuration } from 'lib/utils'
import { copyToClipboard } from 'lib/utils/copyToClipboard'
+import { colonDelimitedDuration } from 'lib/utils/durations'
import { playerMetaLogic } from 'scenes/session-recordings/player/player-meta/playerMetaLogic'
import { sessionSummaryProgressLogic } from 'scenes/session-recordings/player/player-meta/sessionSummaryProgressLogic'
import { SessionRecordingPlayer } from 'scenes/session-recordings/player/SessionRecordingPlayer'
diff --git a/products/session_summaries/frontend/SessionGroupSummaryScene.tsx b/products/session_summaries/frontend/SessionGroupSummaryScene.tsx
index a05b76acb587..e73bcd6d671c 100644
--- a/products/session_summaries/frontend/SessionGroupSummaryScene.tsx
+++ b/products/session_summaries/frontend/SessionGroupSummaryScene.tsx
@@ -15,7 +15,7 @@ import {
import { IconPlayCircle } from 'lib/lemon-ui/icons'
import { LemonMenu } from 'lib/lemon-ui/LemonMenu'
-import { debounce } from 'lib/utils'
+import { debounce } from 'lib/utils/async'
import { copyToClipboard } from 'lib/utils/copyToClipboard'
import { sceneConfigurations } from 'scenes/scenes'
import { Scene, SceneExport } from 'scenes/sceneTypes'
diff --git a/products/session_summaries/frontend/sessionGroupSummariesTableLogic.ts b/products/session_summaries/frontend/sessionGroupSummariesTableLogic.ts
index 36bf7d469b67..600f7bb8ca6c 100644
--- a/products/session_summaries/frontend/sessionGroupSummariesTableLogic.ts
+++ b/products/session_summaries/frontend/sessionGroupSummariesTableLogic.ts
@@ -4,7 +4,7 @@ import { loaders } from 'kea-loaders'
import { PaginationManual, Sorting } from '@posthog/lemon-ui'
import api, { CountedPaginatedResponse } from 'lib/api'
-import { objectClean } from 'lib/utils'
+import { objectClean } from 'lib/utils/objects'
import { Breadcrumb } from '~/types'
diff --git a/products/skills/frontend/llmSkillsLogic.ts b/products/skills/frontend/llmSkillsLogic.ts
index b93f45ac9350..943e7d93b8bc 100644
--- a/products/skills/frontend/llmSkillsLogic.ts
+++ b/products/skills/frontend/llmSkillsLogic.ts
@@ -2,12 +2,13 @@ import { actions, afterMount, kea, listeners, path, props, reducers, selectors }
import { loaders } from 'kea-loaders'
import { router, urlToAction } from 'kea-router'
+import { objectsEqual } from 'lib/utils/objects'
+
import { ApiConfig } from '~/lib/api'
import { Sorting } from '~/lib/lemon-ui/LemonTable'
import { lemonToast } from '~/lib/lemon-ui/LemonToast/LemonToast'
import { PaginationManual } from '~/lib/lemon-ui/PaginationControl'
import { trackedActionToUrl } from '~/lib/logic/scenes/trackedActionToUrl'
-import { objectsEqual } from '~/lib/utils'
import { sceneLogic } from '~/scenes/sceneLogic'
import { urls } from '~/scenes/urls'
diff --git a/products/tasks/frontend/components/TaskDetailPage.tsx b/products/tasks/frontend/components/TaskDetailPage.tsx
index a7b1bd9f7351..3ba13264d7ee 100644
--- a/products/tasks/frontend/components/TaskDetailPage.tsx
+++ b/products/tasks/frontend/components/TaskDetailPage.tsx
@@ -11,7 +11,7 @@ import { dayjs } from 'lib/dayjs'
import { LemonMarkdown } from 'lib/lemon-ui/LemonMarkdown'
import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
import { ButtonPrimitive } from 'lib/ui/Button/ButtonPrimitives'
-import { humanFriendlyDuration } from 'lib/utils'
+import { humanFriendlyDuration } from 'lib/utils/durations'
import { urls } from 'scenes/urls'
import { SceneContent } from '~/layout/scenes/components/SceneContent'
diff --git a/products/tasks/frontend/lib/util-functions.ts b/products/tasks/frontend/lib/util-functions.ts
index 7f2d5f410c97..332f56a9c74c 100644
--- a/products/tasks/frontend/lib/util-functions.ts
+++ b/products/tasks/frontend/lib/util-functions.ts
@@ -1,5 +1,5 @@
import { dayjs } from 'lib/dayjs'
-import { humanFriendlyDuration } from 'lib/utils'
+import { humanFriendlyDuration } from 'lib/utils/durations'
export function formatTimeAgo(date: string | Date): string {
const diff = dayjs().diff(dayjs(date), 'seconds')
diff --git a/products/tasks/frontend/logics/taskDetailSceneLogic.ts b/products/tasks/frontend/logics/taskDetailSceneLogic.ts
index 6649c752ac2b..2392879863fc 100644
--- a/products/tasks/frontend/logics/taskDetailSceneLogic.ts
+++ b/products/tasks/frontend/logics/taskDetailSceneLogic.ts
@@ -16,7 +16,7 @@ import { loaders } from 'kea-loaders'
import { actionToUrl, router, urlToAction } from 'kea-router'
import api from 'lib/api'
-import { isUUIDLike } from 'lib/utils'
+import { isUUIDLike } from 'lib/utils/guards'
import { teamLogic } from 'scenes/teamLogic'
import { urls } from 'scenes/urls'
diff --git a/products/tracing/frontend/TraceCompareFlame.tsx b/products/tracing/frontend/TraceCompareFlame.tsx
index ade21ef81f59..cf5d3f8af426 100644
--- a/products/tracing/frontend/TraceCompareFlame.tsx
+++ b/products/tracing/frontend/TraceCompareFlame.tsx
@@ -5,7 +5,7 @@ import React from 'react'
import { IconChevronRight } from '@posthog/icons'
import { LemonDropdown, Link, SpinnerOverlay, Tooltip } from '@posthog/lemon-ui'
-import { humanFriendlyNumber } from 'lib/utils'
+import { humanFriendlyNumber } from 'lib/utils/numbers'
import { SpanTreeNode } from '~/queries/schema/schema-general'
diff --git a/products/tracing/frontend/TraceCompareTable.tsx b/products/tracing/frontend/TraceCompareTable.tsx
index 7d745147915a..c759354a51e1 100644
Binary files a/products/tracing/frontend/TraceCompareTable.tsx and b/products/tracing/frontend/TraceCompareTable.tsx differ
diff --git a/products/tracing/frontend/TracingFilterBar.tsx b/products/tracing/frontend/TracingFilterBar.tsx
index da16328f9325..bd584bed6f13 100644
--- a/products/tracing/frontend/TracingFilterBar.tsx
+++ b/products/tracing/frontend/TracingFilterBar.tsx
@@ -15,7 +15,7 @@ import { universalFiltersLogic } from 'lib/components/UniversalFilters/universal
import { isUniversalGroupFilterLike } from 'lib/components/UniversalFilters/utils'
import { dayjs } from 'lib/dayjs'
import { useOnMountEffect } from 'lib/hooks/useOnMountEffect'
-import { DATE_TIME_FORMAT, formatDateRange } from 'lib/utils'
+import { DATE_TIME_FORMAT, formatDateRange } from 'lib/utils/datetime'
import { DateRange } from '~/queries/schema/schema-general'
import {
diff --git a/products/tracing/frontend/TracingSparkline.tsx b/products/tracing/frontend/TracingSparkline.tsx
index 33b0f4f2d774..b8f06919c46a 100644
--- a/products/tracing/frontend/TracingSparkline.tsx
+++ b/products/tracing/frontend/TracingSparkline.tsx
@@ -5,8 +5,8 @@ import { LemonButton, SpinnerOverlay } from '@posthog/lemon-ui'
import { AnyScaleOptions, Sparkline } from 'lib/components/Sparkline'
import { dayjs } from 'lib/dayjs'
-import { shortTimeZone } from 'lib/utils'
import { cn } from 'lib/utils/css-classes'
+import { shortTimeZone } from 'lib/utils/timezones'
import { DateRange } from '~/queries/schema/schema-general'
diff --git a/products/tracing/frontend/components/SetupPrompt/tracingIngestionLogic.test.ts b/products/tracing/frontend/components/SetupPrompt/tracingIngestionLogic.test.ts
index aa82b6cb6d30..1b712cd3e6fd 100644
--- a/products/tracing/frontend/components/SetupPrompt/tracingIngestionLogic.test.ts
+++ b/products/tracing/frontend/components/SetupPrompt/tracingIngestionLogic.test.ts
@@ -5,8 +5,8 @@ import { initKeaTests } from '~/test/init'
import { tracingIngestionLogic } from './tracingIngestionLogic'
-jest.mock('lib/utils', () => {
- const actual = jest.requireActual<typeof import('lib/utils')>('lib/utils')
+jest.mock('lib/utils/async', () => {
+ const actual = jest.requireActual<typeof import('lib/utils/async')>('lib/utils/async')
return {
...actual,
// Run the real retry loop with no inter-attempt backoff. Otherwise the 1000ms + 1500ms
diff --git a/products/tracing/frontend/components/SetupPrompt/tracingIngestionLogic.tsx b/products/tracing/frontend/components/SetupPrompt/tracingIngestionLogic.tsx
index 7acd4eb5cf62..55c54d002f06 100644
--- a/products/tracing/frontend/components/SetupPrompt/tracingIngestionLogic.tsx
+++ b/products/tracing/frontend/components/SetupPrompt/tracingIngestionLogic.tsx
@@ -2,7 +2,7 @@ import { afterMount, kea, path, reducers, selectors } from 'kea'
import { loaders } from 'kea-loaders'
import api from 'lib/api'
-import { retryWithBackoff } from 'lib/utils'
+import { retryWithBackoff } from 'lib/utils/async'
import type { tracingIngestionLogicType } from './tracingIngestionLogicType'
diff --git a/products/tracing/frontend/tracingDataLogic.ts b/products/tracing/frontend/tracingDataLogic.ts
index 32e70e30017c..f521ea767cf5 100644
--- a/products/tracing/frontend/tracingDataLogic.ts
+++ b/products/tracing/frontend/tracingDataLogic.ts
@@ -7,7 +7,7 @@ import { lemonToast } from '@posthog/lemon-ui'
import api from 'lib/api'
import { dataColorVars } from 'lib/colors'
import { dayjs } from 'lib/dayjs'
-import { humanFriendlyDetailedTime } from 'lib/utils'
+import { humanFriendlyDetailedTime } from 'lib/utils/datetime'
import { AggregatedSpanRow, SpanTreeNode } from '~/queries/schema/schema-general'
import { PropertyGroupFilter } from '~/types'
diff --git a/products/tracing/frontend/tracingSceneLogic.ts b/products/tracing/frontend/tracingSceneLogic.ts
index 30b8f488041e..7340fefd1747 100644
--- a/products/tracing/frontend/tracingSceneLogic.ts
+++ b/products/tracing/frontend/tracingSceneLogic.ts
@@ -5,7 +5,7 @@ import posthog from 'posthog-js'
import { DEFAULT_UNIVERSAL_GROUP_FILTER } from 'lib/components/UniversalFilters/universalFiltersLogic'
import { trackedActionToUrl } from 'lib/logic/scenes/trackedActionToUrl'
-import { parseTagsFilter } from 'lib/utils'
+import { parseTagsFilter } from 'lib/utils/url'
import { Params } from 'scenes/sceneTypes'
import { Breadcrumb } from '~/types'
diff --git a/products/workflows/frontend/Workflows/WorkflowMetricsSummary.tsx b/products/workflows/frontend/Workflows/WorkflowMetricsSummary.tsx
index f7be708859fa..c5b8a6287c49 100644
--- a/products/workflows/frontend/Workflows/WorkflowMetricsSummary.tsx
+++ b/products/workflows/frontend/Workflows/WorkflowMetricsSummary.tsx
@@ -6,7 +6,7 @@ import { LemonLabel, LemonTable, LemonTableColumns, SpinnerOverlay } from '@post
import { getColorVar } from 'lib/colors'
import { AppMetricsTrends } from 'lib/components/AppMetrics/AppMetricsTrends'
import { AppMetricSummary } from 'lib/components/AppMetrics/AppMetricSummary'
-import { humanFriendlyNumber } from 'lib/utils'
+import { humanFriendlyNumber } from 'lib/utils/numbers'
import {
WORKFLOW_SUMMARY_METRICS,
diff --git a/products/workflows/frontend/Workflows/WorkflowsTable.tsx b/products/workflows/frontend/Workflows/WorkflowsTable.tsx
index dc3ccebc6108..0edeea694a69 100644
--- a/products/workflows/frontend/Workflows/WorkflowsTable.tsx
+++ b/products/workflows/frontend/Workflows/WorkflowsTable.tsx
@@ -14,7 +14,7 @@ import { LemonTable, LemonTableColumn, LemonTableColumns } from 'lib/lemon-ui/Le
import { updatedAtColumn } from 'lib/lemon-ui/LemonTable/columnUtils'
import { LemonTableLink } from 'lib/lemon-ui/LemonTable/LemonTableLink'
import { ProfilePicture } from 'lib/lemon-ui/ProfilePicture'
-import { capitalizeFirstLetter } from 'lib/utils'
+import { capitalizeFirstLetter } from 'lib/utils/strings'
import { urls } from 'scenes/urls'
import { getHogFlowStep } from './hogflows/steps/HogFlowSteps'
diff --git a/products/workflows/frontend/Workflows/hogflows/HogFlowManualTriggerButton.tsx b/products/workflows/frontend/Workflows/hogflows/HogFlowManualTriggerButton.tsx
index df7989f654f6..8b8181d67690 100644
--- a/products/workflows/frontend/Workflows/hogflows/HogFlowManualTriggerButton.tsx
+++ b/products/workflows/frontend/Workflows/hogflows/HogFlowManualTriggerButton.tsx
@@ -5,7 +5,7 @@ import { IconChevronDown } from '@posthog/icons'
import { LemonButton, LemonInput, Popover } from '@posthog/lemon-ui'
import { LemonField } from 'lib/lemon-ui/LemonField'
-import { humanFriendlyNumber } from 'lib/utils'
+import { humanFriendlyNumber } from 'lib/utils/numbers'
import { CyclotronJobInputSchemaType } from '~/types'
diff --git a/products/workflows/frontend/Workflows/hogflows/filters/HogFlowFilters.tsx b/products/workflows/frontend/Workflows/hogflows/filters/HogFlowFilters.tsx
index b5b5638466b3..877be1a5cabd 100644
--- a/products/workflows/frontend/Workflows/hogflows/filters/HogFlowFilters.tsx
+++ b/products/workflows/frontend/Workflows/hogflows/filters/HogFlowFilters.tsx
@@ -3,7 +3,7 @@ import { useValues } from 'kea'
import { PropertyFilters } from 'lib/components/PropertyFilters/PropertyFilters'
import { TaxonomicFilterGroupType } from 'lib/components/TaxonomicFilter/types'
import { useFeatureFlag } from 'lib/hooks/useFeatureFlag'
-import { isOperatorSemver } from 'lib/utils'
+import { isOperatorSemver } from 'lib/utils/operators'
import { ActionFilter } from 'scenes/insights/filters/ActionFilter/ActionFilter'
import { MathAvailability } from 'scenes/insights/filters/ActionFilter/ActionFilterRow/ActionFilterRow'
diff --git a/products/workflows/frontend/Workflows/hogflows/hogFlowEditorLogic.tsx b/products/workflows/frontend/Workflows/hogflows/hogFlowEditorLogic.tsx
index 76cf564cc995..e92f5d67446f 100644
--- a/products/workflows/frontend/Workflows/hogflows/hogFlowEditorLogic.tsx
+++ b/products/workflows/frontend/Workflows/hogflows/hogFlowEditorLogic.tsx
@@ -20,7 +20,7 @@ import { lemonToast } from '@posthog/lemon-ui'
import { AppMetricsTotalsRequest, loadAppMetricsTotals } from 'lib/components/AppMetrics/appMetricsLogic'
import { trackedActionToUrl } from 'lib/logic/scenes/trackedActionToUrl'
-import { uuid } from 'lib/utils'
+import { uuid } from 'lib/utils/dom'
import { urls } from 'scenes/urls'
import { optOutCategoriesLogic } from '../../OptOuts/optOutCategoriesLogic'
diff --git a/products/workflows/frontend/Workflows/hogflows/panel/HogFlowEditorPanel.tsx b/products/workflows/frontend/Workflows/hogflows/panel/HogFlowEditorPanel.tsx
index 3b5e2c20788f..5052827d8efe 100644
--- a/products/workflows/frontend/Workflows/hogflows/panel/HogFlowEditorPanel.tsx
+++ b/products/workflows/frontend/Workflows/hogflows/panel/HogFlowEditorPanel.tsx
@@ -5,7 +5,7 @@ import { useActions, useValues } from 'kea'
import { IconArrowLeft, IconTrash } from '@posthog/icons'
import { LemonBadge, LemonButton, LemonTab, LemonTabs, Tooltip } from '@posthog/lemon-ui'
-import { capitalizeFirstLetter } from 'lib/utils'
+import { capitalizeFirstLetter } from 'lib/utils/strings'
import { workflowLogic } from '../../workflowLogic'
import { HOG_FLOW_EDITOR_MODES, HogFlowEditorMode, hogFlowEditorLogic } from '../hogFlowEditorLogic'
diff --git a/products/workflows/frontend/Workflows/hogflows/panel/testing/HogFlowEditorNotificationPanelTest.tsx b/products/workflows/frontend/Workflows/hogflows/panel/testing/HogFlowEditorNotificationPanelTest.tsx
index ded78bbad4f4..17cdd28277bc 100644
--- a/products/workflows/frontend/Workflows/hogflows/panel/testing/HogFlowEditorNotificationPanelTest.tsx
+++ b/products/workflows/frontend/Workflows/hogflows/panel/testing/HogFlowEditorNotificationPanelTest.tsx
@@ -18,7 +18,7 @@ import {
} from '@posthog/lemon-ui'
import { LemonField } from 'lib/lemon-ui/LemonField'
-import { isEmail } from 'lib/utils'
+import { isEmail } from 'lib/utils/url'
import { HogFunctionTestEditor } from 'scenes/hog-functions/configuration/HogFunctionTest'
import { LogsViewerTable } from 'scenes/hog-functions/logs/LogsViewer'
import { asDisplay } from 'scenes/persons/person-utils'
diff --git a/products/workflows/frontend/Workflows/hogflows/panel/testing/hogFlowEditorNotificationTestLogic.ts b/products/workflows/frontend/Workflows/hogflows/panel/testing/hogFlowEditorNotificationTestLogic.ts
index 825247345643..713b9d501fb8 100644
--- a/products/workflows/frontend/Workflows/hogflows/panel/testing/hogFlowEditorNotificationTestLogic.ts
+++ b/products/workflows/frontend/Workflows/hogflows/panel/testing/hogFlowEditorNotificationTestLogic.ts
@@ -6,7 +6,7 @@ import { lemonToast } from '@posthog/lemon-ui'
import api from 'lib/api'
import { dayjs } from 'lib/dayjs'
-import { uuid } from 'lib/utils'
+import { uuid } from 'lib/utils/dom'
import { performWideEventsQueryInTwoPhases } from 'scenes/hog-functions/sampleEventsQuery'
import { EventsQuery, NodeKind } from '~/queries/schema/schema-general'
diff --git a/products/workflows/frontend/Workflows/hogflows/panel/testing/hogFlowEditorTestLogic.ts b/products/workflows/frontend/Workflows/hogflows/panel/testing/hogFlowEditorTestLogic.ts
index b35d788427fa..e6d56b96f42c 100644
--- a/products/workflows/frontend/Workflows/hogflows/panel/testing/hogFlowEditorTestLogic.ts
+++ b/products/workflows/frontend/Workflows/hogflows/panel/testing/hogFlowEditorTestLogic.ts
@@ -8,7 +8,7 @@ import { lemonToast } from '@posthog/lemon-ui'
import api from 'lib/api'
import { dayjs } from 'lib/dayjs'
import { groupsAccessLogic } from 'lib/introductions/groupsAccessLogic'
-import { uuid } from 'lib/utils'
+import { uuid } from 'lib/utils/dom'
import { performWideEventsQueryInTwoPhases } from 'scenes/hog-functions/sampleEventsQuery'
import { groupsModel } from '~/models/groupsModel'
diff --git a/products/workflows/frontend/Workflows/hogflows/registry/triggers/surveys.tsx b/products/workflows/frontend/Workflows/hogflows/registry/triggers/surveys.tsx
index 9205ee62afdc..3898d87bc4f4 100644
--- a/products/workflows/frontend/Workflows/hogflows/registry/triggers/surveys.tsx
+++ b/products/workflows/frontend/Workflows/hogflows/registry/triggers/surveys.tsx
@@ -7,7 +7,7 @@ import { IconOpenInNew } from 'lib/lemon-ui/icons'
import { LemonField } from 'lib/lemon-ui/LemonField'
import { LemonRadio } from 'lib/lemon-ui/LemonRadio'
import { Link } from 'lib/lemon-ui/Link'
-import { truncate } from 'lib/utils'
+import { truncate } from 'lib/utils/strings'
import { TestAccountFilter } from 'scenes/insights/filters/TestAccountFilter/TestAccountFilter'
import { urls } from 'scenes/urls'
diff --git a/products/workflows/frontend/Workflows/hogflows/steps/StepTrigger.tsx b/products/workflows/frontend/Workflows/hogflows/steps/StepTrigger.tsx
index aef0e49fe7b6..8d4395aa0d98 100644
--- a/products/workflows/frontend/Workflows/hogflows/steps/StepTrigger.tsx
+++ b/products/workflows/frontend/Workflows/hogflows/steps/StepTrigger.tsx
@@ -36,9 +36,9 @@ import { IconAdsClick } from 'lib/lemon-ui/icons'
import { LemonField } from 'lib/lemon-ui/LemonField'
import { LemonRadio } from 'lib/lemon-ui/LemonRadio'
import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
-import { humanFriendlyNumber } from 'lib/utils'
import { publicWebhooksHostOrigin } from 'lib/utils/apiHost'
import { createFuse } from 'lib/utils/fuseSearch'
+import { humanFriendlyNumber } from 'lib/utils/numbers'
import { COHORTS_ONLY_SUPPORT_IN_PICKER_PROPS } from 'scenes/feature-flags/cohortPickerProps'
import { TestAccountFilter } from 'scenes/insights/filters/TestAccountFilter/TestAccountFilter'
diff --git a/products/workflows/frontend/Workflows/hogflows/steps/StepWaitUntilTimeWindow.tsx b/products/workflows/frontend/Workflows/hogflows/steps/StepWaitUntilTimeWindow.tsx
index 9666c019aefb..599196377ebc 100644
--- a/products/workflows/frontend/Workflows/hogflows/steps/StepWaitUntilTimeWindow.tsx
+++ b/products/workflows/frontend/Workflows/hogflows/steps/StepWaitUntilTimeWindow.tsx
@@ -5,7 +5,7 @@ import { LemonDivider, LemonInputSelect, LemonLabel, LemonSelect, LemonSwitch }
import { FEATURE_FLAGS } from 'lib/constants'
import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
-import { timeZoneLabel } from 'lib/utils'
+import { timeZoneLabel } from 'lib/utils/timezones'
import { preflightLogic } from 'scenes/PreflightCheck/preflightLogic'
import { teamLogic } from 'scenes/teamLogic'
diff --git a/products/workflows/frontend/Workflows/hogflows/steps/batchTriggerLogic.ts b/products/workflows/frontend/Workflows/hogflows/steps/batchTriggerLogic.ts
index 0241e695af01..30abdeed7ee0 100644
--- a/products/workflows/frontend/Workflows/hogflows/steps/batchTriggerLogic.ts
+++ b/products/workflows/frontend/Workflows/hogflows/steps/batchTriggerLogic.ts
@@ -2,7 +2,7 @@ import { actions, afterMount, kea, key, listeners, path, props, propsChanged, re
import { loaders } from 'kea-loaders'
import api, { ApiError } from 'lib/api'
-import { objectsEqual } from 'lib/utils'
+import { objectsEqual } from 'lib/utils/objects'
import { BlastRadiusApi } from 'products/workflows/frontend/generated/api.schemas'
diff --git a/products/workflows/frontend/Workflows/hogflows/steps/components/RecurringSchedulePicker.tsx b/products/workflows/frontend/Workflows/hogflows/steps/components/RecurringSchedulePicker.tsx
index 674fcc2e0f02..6a9bdb95c139 100644
--- a/products/workflows/frontend/Workflows/hogflows/steps/components/RecurringSchedulePicker.tsx
+++ b/products/workflows/frontend/Workflows/hogflows/steps/components/RecurringSchedulePicker.tsx
@@ -12,7 +12,7 @@ import {
} from '@posthog/lemon-ui'
import { dayjs } from 'lib/dayjs'
-import { timeZoneLabel } from 'lib/utils'
+import { timeZoneLabel } from 'lib/utils/timezones'
import { preflightLogic } from 'scenes/PreflightCheck/preflightLogic'
import { workflowLogic } from '../../../workflowLogic'
diff --git a/products/workflows/frontend/Workflows/hogflows/steps/components/StepViewMetrics.tsx b/products/workflows/frontend/Workflows/hogflows/steps/components/StepViewMetrics.tsx
index 1b2aeb35c4d3..05d28c1b5471 100644
--- a/products/workflows/frontend/Workflows/hogflows/steps/components/StepViewMetrics.tsx
+++ b/products/workflows/frontend/Workflows/hogflows/steps/components/StepViewMetrics.tsx
@@ -3,7 +3,7 @@ import { useValues } from 'kea'
import { IconCheck, IconFilter, IconX } from '@posthog/icons'
import { LemonSkeleton, Tooltip } from '@posthog/lemon-ui'
-import { humanFriendlyLargeNumber } from 'lib/utils'
+import { humanFriendlyLargeNumber } from 'lib/utils/numbers'
import { HogFlowEditorActionMetrics, hogFlowEditorLogic } from '../../hogFlowEditorLogic'
import { HogFlowAction } from '../../types'
diff --git a/products/workflows/frontend/Workflows/hogflows/steps/stepDelayLogic.test.ts b/products/workflows/frontend/Workflows/hogflows/steps/stepDelayLogic.test.ts
index e81de8980ada..ebcca766d47d 100644
--- a/products/workflows/frontend/Workflows/hogflows/steps/stepDelayLogic.test.ts
+++ b/products/workflows/frontend/Workflows/hogflows/steps/stepDelayLogic.test.ts
@@ -1,7 +1,7 @@
import { resetContext } from 'kea'
import { expectLogic, partial, testUtilsPlugin } from 'kea-test-utils'
-import { uuid } from 'lib/utils'
+import { uuid } from 'lib/utils/dom'
import { initKeaTests } from '~/test/init'
diff --git a/products/workflows/frontend/Workflows/hogflows/steps/stepWaitUntilTimeWindowLogic.test.ts b/products/workflows/frontend/Workflows/hogflows/steps/stepWaitUntilTimeWindowLogic.test.ts
index 787efd30ce95..2e2252300a4c 100644
--- a/products/workflows/frontend/Workflows/hogflows/steps/stepWaitUntilTimeWindowLogic.test.ts
+++ b/products/workflows/frontend/Workflows/hogflows/steps/stepWaitUntilTimeWindowLogic.test.ts
@@ -1,7 +1,7 @@
import { resetContext } from 'kea'
import { expectLogic, partial, testUtilsPlugin } from 'kea-test-utils'
-import { uuid } from 'lib/utils'
+import { uuid } from 'lib/utils/dom'
import { initKeaTests } from '~/test/init'
import { WeekdayType } from '~/types'
diff --git a/products/workflows/frontend/WorkflowsScene.tsx b/products/workflows/frontend/WorkflowsScene.tsx
index 0a7b42f0acfd..07735016af68 100644
--- a/products/workflows/frontend/WorkflowsScene.tsx
+++ b/products/workflows/frontend/WorkflowsScene.tsx
@@ -11,8 +11,8 @@ import { integrationsLogic } from 'lib/integrations/integrationsLogic'
import { IconSlack, IconTwilio } from 'lib/lemon-ui/icons'
import { LemonTab, LemonTabs } from 'lib/lemon-ui/LemonTabs'
import { trackedActionToUrl } from 'lib/logic/scenes/trackedActionToUrl'
-import { capitalizeFirstLetter } from 'lib/utils'
import { addProductIntent } from 'lib/utils/product-intents'
+import { capitalizeFirstLetter } from 'lib/utils/strings'
import { sceneConfigurations } from 'scenes/scenes'
import { Scene, SceneExport } from 'scenes/sceneTypes'
import { urls } from 'scenes/urls'