Files
zeekayandHanzo Dev 3182cc6b95 fix(analytics): import the Insights client by the name it exports
The version sweep resolved @hanzo/insights to 1.358.1, which exports its
client as `insights` and as the default, and no longer as `posthog`. The
analytics hook imported `posthog`, so the binding was undefined — a link
error for the ESM build, and a TypeError on the first capture wherever the
module did load.

The hook imports `insights`. use-analytics.test.ts sets an Insights key,
records what reaches the client and checks an event and an error both get
there, and that nothing does without a key; against the old import the
first case fails on the undefined client.

turbo.json still declared the key under its pre-rename name,
NEXT_PUBLIC_POSTHOG_KEY, which nothing reads; it declares
NEXT_PUBLIC_INSIGHTS_KEY, which the feature flags read and the test sets.

Co-authored-by: Hanzo Dev <[email protected]>
2026-09-19 04:36:57 -07:00

65 lines
1.8 KiB
TypeScript

/**
* Product analytics from the app: events and errors go to the Insights client
* when an Insights key is configured, and nowhere when it is not.
*
* Run: npx tsx --test packages/lib/__tests__/use-analytics.test.ts
*/
import assert from 'node:assert/strict';
import { afterEach, describe, test } from 'node:test';
import { insights } from '@hanzo/insights';
import { useAnalytics } from '../client-only/hooks/use-analytics';
const { capture, captureException } = insights;
/** Records what reaches the Insights client instead of sending it. */
const record = () => {
const calls: unknown[][] = [];
insights.capture = (...args: Parameters<typeof capture>) => {
calls.push(['capture', ...args]);
return undefined;
};
insights.captureException = (...args: Parameters<typeof captureException>) => {
calls.push(['captureException', ...args]);
return undefined;
};
return calls;
};
describe('useAnalytics', () => {
afterEach(() => {
insights.capture = capture;
insights.captureException = captureException;
delete process.env.NEXT_PUBLIC_INSIGHTS_KEY;
});
test('sends events and errors to Insights when a key is configured', () => {
process.env.NEXT_PUBLIC_INSIGHTS_KEY = 'key';
const calls = record();
const error = new Error('boom');
const analytics = useAnalytics();
analytics.capture('document.sent', { documentId: 1 });
analytics.captureException(error, { route: '/documents' });
assert.deepEqual(calls, [
['capture', 'document.sent', { documentId: 1 }],
['captureException', error, { route: '/documents' }],
]);
});
test('sends nothing without a key', () => {
const calls = record();
useAnalytics().capture('document.sent');
assert.deepEqual(calls, []);
});
});