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.

feat(exporter): split exporter bundle with ESM code splitting and lazy scenes (#57782)

Paul D'Ambraeaaf9cf94d08
diff --git a/common/esbuilder/utils.mjs b/common/esbuilder/utils.mjs
index 33905012ecbf..fdf6d7a29161 100644
--- a/common/esbuilder/utils.mjs
+++ b/common/esbuilder/utils.mjs
@@ -279,7 +279,8 @@ function getChunks(result) {
(i) => i.kind === 'import-statement' && i.path.startsWith('dist/chunk-')
)
const exports = output.exports.filter((e) => e !== 'default' && e !== 'scene')
- if (importStatements.length > 0 && (exports.length > 0 || output.entryPoint === 'src/index.tsx')) {
+ const isRootEntry = output.entryPoint === 'src/index.tsx' || output.entryPoint === 'src/exporter/index.tsx'
+ if (importStatements.length > 0 && (exports.length > 0 || isRootEntry)) {
chunks[exports[0] || 'index'] = importStatements.map((i) =>
i.path.replace('dist/chunk-', '').replace('.js', '')
)
@@ -356,10 +357,42 @@ export async function buildInParallel(configs, { onBuildStart, onBuildComplete }
/** Get the main ".js" and ".css" files for a build */
function getBuiltEntryPoints(config, result) {
+ // Normalise entryPoints: support both array form and object form { name: path }
+ const entryValues = Array.isArray(config.entryPoints) ? config.entryPoints : Object.values(config.entryPoints || {})
+
+ // Primary: scan the metafile directly — works regardless of entryNames overrides.
+ // CSS outputs never have entryPoint set, so we find JS entries first, then locate
+ // each companion CSS by matching the same base name (hashes differ between JS and CSS).
+ const jsFiles = []
+ for (const [outputPath, output] of Object.entries(result.metafile?.outputs || {})) {
+ if (output.entryPoint && entryValues.includes(output.entryPoint) && outputPath.endsWith('.js')) {
+ jsFiles.push(path.resolve(process.cwd(), outputPath))
+ }
+ }
+ if (jsFiles.length > 0) {
+ const allFiles = [...jsFiles]
+ const allOutputPaths = Object.keys(result.metafile?.outputs || {})
+ for (const jsFile of jsFiles) {
+ // Strip optional hash suffix: "dist/exporter-HASH.js" -> "dist/exporter"
+ const baseName = jsFile.replace(/(-[A-Z0-9]+)?\.js$/, '')
+ for (const outputPath of allOutputPaths) {
+ if (!outputPath.endsWith('.css')) {
+ continue
+ }
+ const absoluteCss = path.resolve(process.cwd(), outputPath)
+ if (absoluteCss.startsWith(baseName + '-') || absoluteCss === baseName + '.css') {
+ allFiles.push(absoluteCss)
+ }
+ }
+ }
+ return allFiles
+ }
+
+ // Fallback: path-based convention for configs where metafile scan yields nothing
let outfiles = []
if (config.outdir) {
// convert "src/index.tsx" --> /a/posthog/frontend/dist/index.js
- outfiles = config.entryPoints.map((file) =>
+ outfiles = entryValues.map((file) =>
path
.resolve(config.absWorkingDir, file)
.replace('/src/', '/dist/')
@@ -369,24 +402,21 @@ function getBuiltEntryPoints(config, result) {
outfiles = [path.resolve(config.absWorkingDir, config.outfile)]
}
- const builtFiles = []
+ const fallbackFiles = []
for (const outfile of outfiles) {
- // convert "/a/something.tsx" --> "/a/something-"
const fileNoExt = outfile.replace(/\.[^/]+$/, '')
- // find if we built a .js or .css file that matches
- for (const file of Object.keys(result.metafile.outputs)) {
+ for (const file of Object.keys(result.metafile?.outputs || {})) {
const absoluteFile = path.resolve(process.cwd(), file)
if (
(absoluteFile.startsWith(`${fileNoExt}-`) && (file.endsWith('.js') || file.endsWith('.css'))) ||
absoluteFile === `${fileNoExt}.js` ||
absoluteFile === `${fileNoExt}.css`
) {
- builtFiles.push(absoluteFile)
+ fallbackFiles.push(absoluteFile)
}
}
}
-
- return builtFiles
+ return fallbackFiles
}
let buildsInProgress = 0
diff --git a/frontend/build.mjs b/frontend/build.mjs
index e44edbcb79aa..cd15e130b800 100755
--- a/frontend/build.mjs
+++ b/frontend/build.mjs
@@ -79,10 +79,10 @@ await buildInParallel(
},
{
name: 'Exporter',
- globalName: 'posthogExporter',
- entryPoints: ['src/exporter/index.tsx'],
- format: 'iife',
- outfile: path.resolve(__dirname, 'dist', 'exporter.js'),
+ entryPoints: { exporter: 'src/exporter/index.tsx' },
+ splitting: true,
+ format: 'esm',
+ outdir: path.resolve(__dirname, 'dist'),
...common,
},
{
diff --git a/frontend/src/exporter/Exporter.tsx b/frontend/src/exporter/Exporter.tsx
index efede9ef06cb..1e270bab1014 100644
--- a/frontend/src/exporter/Exporter.tsx
+++ b/frontend/src/exporter/Exporter.tsx
@@ -3,35 +3,28 @@ import './Exporter.scss'
import clsx from 'clsx'
import { BindLogic, useValues } from 'kea'
-import { useCallback, useEffect } from 'react'
+import { lazy, Suspense, useEffect } from 'react'
import { Logo } from 'lib/brand/Logo'
-import { HeatmapCanvas } from 'lib/components/heatmaps/HeatmapCanvas'
-import { usePageVisibilityCb } from 'lib/hooks/usePageVisibility'
import { useResizeObserver } from 'lib/hooks/useResizeObserver'
import { useThemedHtml } from 'lib/hooks/useThemedHtml'
import { LemonMarkdown } from 'lib/lemon-ui/LemonMarkdown'
import { Link } from 'lib/lemon-ui/Link'
import { humanFriendlyDuration } from 'lib/utils'
-import { Dashboard } from 'scenes/dashboard/Dashboard'
-import { dashboardLogic } from 'scenes/dashboard/dashboardLogic'
-import { Notebook } from 'scenes/notebooks/Notebook/Notebook'
-import { SessionRecordingPlayer } from 'scenes/session-recordings/player/SessionRecordingPlayer'
-import { SessionRecordingPlayerMode } from 'scenes/session-recordings/player/sessionRecordingPlayerLogic'
+import { AUTO_REFRESH_INITIAL_INTERVAL_SECONDS } from 'scenes/dashboard/dashboardConstants'
import { teamLogic } from 'scenes/teamLogic'
-import { ExportedInsight } from '~/exporter/ExportedInsight/ExportedInsight'
import { ExporterLogin } from '~/exporter/ExporterLogin'
import { ExportType, ExportedData } from '~/exporter/types'
-import { getQueryBasedDashboard } from '~/queries/nodes/InsightViz/utils'
-import {
- AUTO_REFRESH_INITIAL_INTERVAL_SECONDS,
- scheduleSharedDashboardStaleAutoForceIfEligible,
-} from '~/scenes/dashboard/dashboardUtils'
-import { DashboardPlacement } from '~/types'
import { exporterViewLogic } from './exporterViewLogic'
+const LazyDashboardScene = lazy(() => import('./scenes/ExporterDashboardScene'))
+const LazyNotebookScene = lazy(() => import('./scenes/ExporterNotebookScene'))
+const LazyRecordingScene = lazy(() => import('./scenes/ExporterRecordingScene'))
+const LazyHeatmapScene = lazy(() => import('./scenes/ExporterHeatmapScene'))
+const LazyInsightScene = lazy(() => import('./scenes/ExporterInsightScene'))
+
function resolveForcedTheme(theme?: 'light' | 'dark' | 'system'): 'light' | 'dark' | null {
if (theme === 'light' || theme === 'dark') {
return theme
@@ -44,89 +37,7 @@ function resolveForcedTheme(theme?: 'light' | 'dark' | 'system'): 'light' | 'dar
: 'light'
}
-function ExportHeatmap(): JSX.Element {
- const { exportedData, isLoading, screenshotUrl } = useValues(exporterViewLogic)
- const { exportToken } = exportedData
- const width = exportedData.heatmap_context?.width
-
- return (
- <div
- className="heatmap-exporter relative"
- // eslint-disable-next-line react/forbid-dom-props
- style={{
- width: width ? `${width}px` : '100%',
- minHeight: '100vh',
- overflow: 'hidden',
- }}
- >
- <HeatmapCanvas
- positioning="absolute"
- widthOverride={width ?? null}
- context="in-app"
- exportToken={exportToken}
- />
- {exportedData.heatmap_context?.heatmap_type === 'screenshot' ? (
- isLoading ? null : (
- <img
- src={screenshotUrl ?? ''}
- alt="Heatmap"
- // eslint-disable-next-line react/forbid-dom-props
- style={{ width: '100%', height: 'auto', display: 'block' }}
- />
- )
- ) : (
- <iframe
- id="heatmap-iframe"
- ref={null}
- title="Heatmap export"
- className="bg-white"
- // eslint-disable-next-line react/forbid-dom-props
- style={{ width: '100%', height: '100vh', display: 'block' }}
- src={exportedData.heatmap_url ?? ''}
- onLoad={() => {}}
- // these two sandbox values are necessary so that the site and toolbar can run
- // this is a very loose sandbox,
- // but we specify it so that at least other capabilities are denied
- sandbox="allow-scripts allow-same-origin"
- // we don't allow things such as camera access though
- allow=""
- />
- )}
- </div>
- )
-}
-
-function SharedDashboardAutoRefresh({ dashboardId }: { dashboardId: number }): JSX.Element | null {
- const logic = dashboardLogic({ id: dashboardId, placement: DashboardPlacement.Public })
- const { setAutoRefresh, setPageVisibility, triggerDashboardRefresh } = logic.actions
-
- // Tie auto-refresh to tab visibility AND fire a one-shot staleness check when the tab
- // regains focus — Chrome throttles background timers, so the periodic interval can drift
- // well past the staleness budget before the next tick. Reading `logic.values` inside the
- // callback gets the live `effectiveLastRefresh` rather than a stale closure value.
- const onVisibilityChange = useCallback(
- (visible: boolean) => {
- setPageVisibility(visible)
- if (visible) {
- scheduleSharedDashboardStaleAutoForceIfEligible({
- effectiveLastRefresh: logic.values.effectiveLastRefresh,
- triggerDashboardRefresh: () => void triggerDashboardRefresh(),
- })
- }
- },
- [setPageVisibility, triggerDashboardRefresh, logic]
- )
- usePageVisibilityCb(onVisibilityChange)
-
- useEffect(() => {
- setAutoRefresh(true, AUTO_REFRESH_INITIAL_INTERVAL_SECONDS)
- }, [setAutoRefresh])
-
- return null
-}
-
export function Exporter(props: ExportedData): JSX.Element {
- // NOTE: Mounting the logic is important as it is used by sub-logics
const {
type,
dashboard,
@@ -238,40 +149,37 @@ export function Exporter(props: ExportedData): JSX.Element {
</div>
</div>
)}
- <Notebook
- shortId={notebook.short_id}
- editable={false}
- cachedNotebook={notebook}
- cachedInsightsByShortId={insights}
- cachedInlineQueryResultsByNodeId={inlineQueryResults}
- />
+ <Suspense fallback={null}>
+ <LazyNotebookScene
+ notebook={notebook}
+ insights={insights}
+ inline_query_results={inlineQueryResults}
+ />
+ </Suspense>
</div>
) : insight ? (
- <ExportedInsight insight={insight} themes={themes!} exportOptions={exportOptions} />
+ <Suspense fallback={null}>
+ <LazyInsightScene insight={insight} themes={themes!} exportOptions={exportOptions} />
+ </Suspense>
) : dashboard ? (
- <>
- {type !== ExportType.Image && <SharedDashboardAutoRefresh dashboardId={dashboard.id} />}
- <Dashboard
- id={String(dashboard.id)}
- dashboard={getQueryBasedDashboard(dashboard)!}
- placement={
- type === ExportType.Image ? DashboardPlacement.Export : DashboardPlacement.Public
- }
- themes={themes}
- />
- </>
+ <Suspense fallback={null}>
+ <LazyDashboardScene dashboard={dashboard} type={type} themes={themes} />
+ </Suspense>
) : recording ? (
- <SessionRecordingPlayer
- playerKey="exporter"
- sessionRecordingId={recording.id}
- mode={props.mode ?? SessionRecordingPlayerMode.Sharing}
- autoPlay={props.autoplay ?? false}
- withSidebar={showInspector}
- noBorder={props.noBorder ?? false}
- accessToken={exportToken}
- />
+ <Suspense fallback={null}>
+ <LazyRecordingScene
+ recording={recording}
+ mode={props.mode}
+ autoplay={props.autoplay}
+ noBorder={props.noBorder}
+ exportToken={exportToken}
+ showInspector={showInspector}
+ />
+ </Suspense>
) : type === ExportType.Heatmap ? (
- <ExportHeatmap />
+ <Suspense fallback={null}>
+ <LazyHeatmapScene />
+ </Suspense>
) : (
<h1 className="text-center p-4">Something went wrong...</h1>
)}
diff --git a/frontend/src/exporter/scenes/ExporterDashboardScene.tsx b/frontend/src/exporter/scenes/ExporterDashboardScene.tsx
new file mode 100644
index 000000000000..c02e86db6cc0
--- /dev/null
+++ b/frontend/src/exporter/scenes/ExporterDashboardScene.tsx
@@ -0,0 +1,60 @@
+import { useActions } from 'kea'
+import { useCallback, useEffect } from 'react'
+
+import { usePageVisibilityCb } from 'lib/hooks/usePageVisibility'
+import { Dashboard } from 'scenes/dashboard/Dashboard'
+import { AUTO_REFRESH_INITIAL_INTERVAL_SECONDS } from 'scenes/dashboard/dashboardConstants'
+import { dashboardLogic } from 'scenes/dashboard/dashboardLogic'
+import { scheduleSharedDashboardStaleAutoForceIfEligible } from 'scenes/dashboard/dashboardUtils'
+
+import { getQueryBasedDashboard } from '~/queries/nodes/InsightViz/utils'
+import { DashboardPlacement } from '~/types'
+
+import { ExportType, ExportedData } from '../types'
+
+function SharedDashboardAutoRefresh({ dashboardId }: { dashboardId: number }): JSX.Element | null {
+ const logic = dashboardLogic({ id: dashboardId, placement: DashboardPlacement.Public })
+ const { setAutoRefresh, setPageVisibility, triggerDashboardRefresh } = useActions(logic)
+
+ const onVisibilityChange = useCallback(
+ (visible: boolean) => {
+ setPageVisibility(visible)
+ if (visible) {
+ scheduleSharedDashboardStaleAutoForceIfEligible({
+ effectiveLastRefresh: logic.values.effectiveLastRefresh,
+ triggerDashboardRefresh: () => void triggerDashboardRefresh(),
+ })
+ }
+ },
+ [setPageVisibility, triggerDashboardRefresh, logic]
+ )
+ usePageVisibilityCb(onVisibilityChange)
+
+ useEffect(() => {
+ setAutoRefresh(true, AUTO_REFRESH_INITIAL_INTERVAL_SECONDS)
+ }, [setAutoRefresh])
+
+ return null
+}
+
+export default function ExporterDashboardScene({
+ dashboard,
+ type,
+ themes,
+}: {
+ dashboard: NonNullable<ExportedData['dashboard']>
+ type: ExportedData['type']
+ themes: ExportedData['themes']
+}): JSX.Element {
+ return (
+ <>
+ {type !== ExportType.Image && <SharedDashboardAutoRefresh dashboardId={dashboard.id} />}
+ <Dashboard
+ id={String(dashboard.id)}
+ dashboard={getQueryBasedDashboard(dashboard)!}
+ placement={type === ExportType.Image ? DashboardPlacement.Export : DashboardPlacement.Public}
+ themes={themes}
+ />
+ </>
+ )
+}
diff --git a/frontend/src/exporter/scenes/ExporterHeatmapScene.tsx b/frontend/src/exporter/scenes/ExporterHeatmapScene.tsx
new file mode 100644
index 000000000000..683ce532842e
--- /dev/null
+++ b/frontend/src/exporter/scenes/ExporterHeatmapScene.tsx
@@ -0,0 +1,55 @@
+import { useValues } from 'kea'
+
+import { HeatmapCanvas } from 'lib/components/heatmaps/HeatmapCanvas'
+
+import { exporterViewLogic } from '../exporterViewLogic'
+
+export default function ExporterHeatmapScene(): JSX.Element {
+ const { exportedData, isLoading, screenshotUrl } = useValues(exporterViewLogic)
+ const { exportToken } = exportedData
+ const width = exportedData.heatmap_context?.width
+
+ return (
+ <div
+ className="heatmap-exporter relative"
+ // eslint-disable-next-line react/forbid-dom-props
+ style={{
+ width: width ? `${width}px` : '100%',
+ minHeight: '100vh',
+ overflow: 'hidden',
+ }}
+ >
+ <HeatmapCanvas
+ positioning="absolute"
+ widthOverride={width ?? null}
+ context="in-app"
+ exportToken={exportToken}
+ />
+ {exportedData.heatmap_context?.heatmap_type === 'screenshot' ? (
+ isLoading ? null : (
+ <img
+ src={screenshotUrl ?? ''}
+ alt="Heatmap"
+ // eslint-disable-next-line react/forbid-dom-props
+ style={{ width: '100%', height: 'auto', display: 'block' }}
+ />
+ )
+ ) : (
+ <iframe
+ id="heatmap-iframe"
+ title="Heatmap export"
+ className="bg-white"
+ // eslint-disable-next-line react/forbid-dom-props
+ style={{ width: '100%', height: '100vh', display: 'block' }}
+ src={exportedData.heatmap_url ?? ''}
+ // these two sandbox values are necessary so that the site and toolbar can run
+ // this is a very loose sandbox,
+ // but we specify it so that at least other capabilities are denied
+ sandbox="allow-scripts allow-same-origin"
+ // we don't allow things such as camera access though
+ allow=""
+ />
+ )}
+ </div>
+ )
+}
diff --git a/frontend/src/exporter/scenes/ExporterInsightScene.tsx b/frontend/src/exporter/scenes/ExporterInsightScene.tsx
new file mode 100644
index 000000000000..e7e58c4b5ad4
--- /dev/null
+++ b/frontend/src/exporter/scenes/ExporterInsightScene.tsx
@@ -0,0 +1,16 @@
+import { ExportedInsight } from '~/exporter/ExportedInsight/ExportedInsight'
+import { SharingConfigurationSettings } from '~/queries/schema/schema-general'
+
+import { ExportedData } from '../types'
+
+export default function ExporterInsightScene({
+ insight,
+ themes,
+ exportOptions,
+}: {
+ insight: NonNullable<ExportedData['insight']>
+ themes: NonNullable<ExportedData['themes']>
+ exportOptions: SharingConfigurationSettings
+}): JSX.Element {
+ return <ExportedInsight insight={insight} themes={themes} exportOptions={exportOptions} />
+}
diff --git a/frontend/src/exporter/scenes/ExporterNotebookScene.tsx b/frontend/src/exporter/scenes/ExporterNotebookScene.tsx
new file mode 100644
index 000000000000..7d1a4acbca4d
--- /dev/null
+++ b/frontend/src/exporter/scenes/ExporterNotebookScene.tsx
@@ -0,0 +1,23 @@
+import { Notebook } from 'scenes/notebooks/Notebook/Notebook'
+
+import { ExportedData } from '../types'
+
+export default function ExporterNotebookScene({
+ notebook,
+ insights,
+ inline_query_results: inlineQueryResults,
+}: {
+ notebook: NonNullable<ExportedData['notebook']>
+ insights: ExportedData['insights']
+ inline_query_results: ExportedData['inline_query_results']
+}): JSX.Element {
+ return (
+ <Notebook
+ shortId={notebook.short_id}
+ editable={false}
+ cachedNotebook={notebook}
+ cachedInsightsByShortId={insights}
+ cachedInlineQueryResultsByNodeId={inlineQueryResults}
+ />
+ )
+}
diff --git a/frontend/src/exporter/scenes/ExporterRecordingScene.tsx b/frontend/src/exporter/scenes/ExporterRecordingScene.tsx
new file mode 100644
index 000000000000..21a2cbf35bde
--- /dev/null
+++ b/frontend/src/exporter/scenes/ExporterRecordingScene.tsx
@@ -0,0 +1,32 @@
+import { SessionRecordingPlayer } from 'scenes/session-recordings/player/SessionRecordingPlayer'
+import { SessionRecordingPlayerMode } from 'scenes/session-recordings/player/sessionRecordingPlayerLogic'
+
+import { ExportedData } from '../types'
+
+export default function ExporterRecordingScene({
+ recording,
+ mode,
+ autoplay,
+ noBorder,
+ exportToken,
+ showInspector,
+}: {
+ recording: NonNullable<ExportedData['recording']>
+ mode: ExportedData['mode']
+ autoplay: ExportedData['autoplay']
+ noBorder: ExportedData['noBorder']
+ exportToken: ExportedData['exportToken']
+ showInspector: ExportedData['showInspector']
+}): JSX.Element {
+ return (
+ <SessionRecordingPlayer
+ playerKey="exporter"
+ sessionRecordingId={recording.id}
+ mode={mode ?? SessionRecordingPlayerMode.Sharing}
+ autoPlay={autoplay ?? false}
+ withSidebar={showInspector ?? false}
+ noBorder={noBorder ?? false}
+ accessToken={exportToken}
+ />
+ )
+}
diff --git a/frontend/src/scenes/dashboard/dashboardConstants.ts b/frontend/src/scenes/dashboard/dashboardConstants.ts
new file mode 100644
index 000000000000..fbdda8e7e1bd
--- /dev/null
+++ b/frontend/src/scenes/dashboard/dashboardConstants.ts
@@ -0,0 +1,2 @@
+export const AUTO_REFRESH_INITIAL_INTERVAL_SECONDS = 1800
+export const SHARED_DASHBOARD_AUTO_FORCE_IF_STALE_MINUTES = AUTO_REFRESH_INITIAL_INTERVAL_SECONDS / 60
diff --git a/frontend/src/scenes/dashboard/dashboardUtils.ts b/frontend/src/scenes/dashboard/dashboardUtils.ts
index 9f25b0185017..93729963e579 100644
--- a/frontend/src/scenes/dashboard/dashboardUtils.ts
+++ b/frontend/src/scenes/dashboard/dashboardUtils.ts
@@ -4,6 +4,12 @@ import { lemonToast } from '@posthog/lemon-ui'
import api, { ApiMethodOptions, getJSONOrNull } from 'lib/api'
import type { Dayjs } from 'lib/dayjs'
+
+import {
+ AUTO_REFRESH_INITIAL_INTERVAL_SECONDS,
+ SHARED_DASHBOARD_AUTO_FORCE_IF_STALE_MINUTES,
+} from './dashboardConstants'
+export { AUTO_REFRESH_INITIAL_INTERVAL_SECONDS, SHARED_DASHBOARD_AUTO_FORCE_IF_STALE_MINUTES }
import { currentSessionId } from 'lib/internalMetrics'
import { objectClean, shouldCancelQuery, toParams } from 'lib/utils'
import { accessLevelSatisfied } from 'lib/utils/accessControlUtils'
@@ -115,16 +121,8 @@ export const DEFAULT_AUTO_PREVIEW_TILE_LIMIT = 10
const RATE_LIMIT_ERROR_MESSAGE = 'concurrency_limit_exceeded'
-export const AUTO_REFRESH_INITIAL_INTERVAL_SECONDS = 1800
export const QUICK_FILTER_DEBOUNCE_MS = 1500
-/**
- * Cold-start one-shot threshold: if data is older than this when a shared dashboard loads,
- * trigger one immediate force_blocking refresh. Aligned with the periodic interval and the
- * backend throttle (`SHARED_FORCE_BLOCKING_MIN_AGE`).
- */
-export const SHARED_DASHBOARD_AUTO_FORCE_IF_STALE_MINUTES = AUTO_REFRESH_INITIAL_INTERVAL_SECONDS / 60
-
function staleAgeMinutes(effectiveLastRefresh: Dayjs | null): number | null {
if (!effectiveLastRefresh) {
return null