From 857ad86bbcf8c906af104b2a5a947b82f384dc3a Mon Sep 17 00:00:00 2001 From: Phani Raj Date: Mon, 23 Sep 2024 10:41:23 -0500 Subject: [PATCH 1/8] submit partial responses for Surveys --- src/extensions/surveys.tsx | 15 ++++++--------- src/web-experiments.ts | 14 ++++++++++++++ 2 files changed, 20 insertions(+), 9 deletions(-) diff --git a/src/extensions/surveys.tsx b/src/extensions/surveys.tsx index f3ee53e50..29073f581 100644 --- a/src/extensions/surveys.tsx +++ b/src/extensions/surveys.tsx @@ -555,19 +555,16 @@ export function Questions({ // Old SDK, no branching if (!posthog.getNextSurveyStep) { - const isLastDisplayedQuestion = displayQuestionIndex === survey.questions.length - 1 - if (isLastDisplayedQuestion) { - sendSurveyEvent({ ...questionsResponses, [responseKey]: res }, survey, posthog) - } else { - setCurrentQuestionIndex(displayQuestionIndex + 1) - } + logger.info('POSTHOG SURVEYS: Sending survey response', questionsResponses) + sendSurveyEvent({ ...questionsResponses, [responseKey]: res }, survey, posthog) + setCurrentQuestionIndex(displayQuestionIndex + 1) return } const nextStep = posthog.getNextSurveyStep(survey, displayQuestionIndex, res) - if (nextStep === SurveyQuestionBranchingType.End) { - sendSurveyEvent({ ...questionsResponses, [responseKey]: res }, survey, posthog) - } else { + logger.info('POSTHOG SURVEYS: Sending survey response', questionsResponses) + sendSurveyEvent({ ...questionsResponses, [responseKey]: res }, survey, posthog) + if (nextStep !== SurveyQuestionBranchingType.End) { setCurrentQuestionIndex(nextStep) } } diff --git a/src/web-experiments.ts b/src/web-experiments.ts index 2499c5450..2145cb236 100644 --- a/src/web-experiments.ts +++ b/src/web-experiments.ts @@ -13,6 +13,8 @@ import { isNullish } from './utils/type-utils' import { isUrlMatchingRegex } from './utils/request-utils' import { logger } from './utils/logger' import { Info } from './utils/event-utils' +import { Survey } from './posthog-surveys-types' +import { getSurveySeenKey } from './extensions/surveys/surveys-utils' export const webExperimentUrlValidationMap: Record< WebExperimentUrlMatchType, @@ -80,6 +82,15 @@ export class WebExperiments { this.getWebExperimentsAndEvaluateDisplayLogic() } + sendExperimentAppliedEvent(experiment: string, variant: string) { + if (!this.instance) return + + this.instance.capture('$webexperiment_applied', { + $experiment_name: experiment, + $experiment_variant: variant, + }) + } + public getWebExperimentsAndEvaluateDisplayLogic = (forceReload: boolean = false): void => { this.getWebExperiments((webExperiments) => { WebExperiments.logInfo(`retrieved web experiments from the server`) @@ -102,6 +113,7 @@ export class WebExperiments { const selectedVariant = this._featureFlags[webExperiment.feature_flag_key] as unknown as string if (selectedVariant && webExperiment.variants[selectedVariant]) { + this.sendExperimentAppliedEvent(webExperiment.name, selectedVariant) WebExperiments.applyTransforms( webExperiment.name, selectedVariant, @@ -113,6 +125,7 @@ export class WebExperiments { const testVariant = webExperiment.variants[variant] const matchTest = WebExperiments.matchesTestVariant(testVariant) if (matchTest) { + this.sendExperimentAppliedEvent(webExperiment.name, variant) WebExperiments.applyTransforms(webExperiment.name, variant, testVariant.transforms) } } @@ -212,6 +225,7 @@ export class WebExperiments { } private static applyTransforms(experiment: string, variant: string, transforms: WebExperimentTransform[]) { + sendExperimentEvent(experiment, variant) transforms.forEach((transform) => { if (transform.selector) { WebExperiments.logInfo( From 3cffb82e273380d8c6ea958fbe424a2f5a0a6793 Mon Sep 17 00:00:00 2001 From: Phani Raj Date: Mon, 23 Sep 2024 20:49:32 -0500 Subject: [PATCH 2/8] Send consistent survey response uuid --- src/extensions/surveys.tsx | 26 ++++++++++++++-- src/extensions/surveys/surveys-utils.tsx | 39 ++++++++++++++++-------- src/posthog-core.ts | 2 +- src/types.ts | 1 + src/web-experiments.ts | 14 --------- 5 files changed, 52 insertions(+), 30 deletions(-) diff --git a/src/extensions/surveys.tsx b/src/extensions/surveys.tsx index 29073f581..aff7c3bfc 100644 --- a/src/extensions/surveys.tsx +++ b/src/extensions/surveys.tsx @@ -34,6 +34,7 @@ import { } from './surveys/components/QuestionTypes' import { logger } from '../utils/logger' import { Cancel } from './surveys/components/QuestionHeader' +import { uuidv7 } from '../uuidv7' // We cast the types here which is dangerous but protected by the top level generateSurveys call const window = _window as Window & typeof globalThis @@ -297,10 +298,13 @@ export const renderSurveysPreview = ({ survey.appearance?.backgroundColor || defaultSurveyAppearance.backgroundColor || 'white' ) + const surveyResponseUUID = uuidv7() + Preact.render( = {}, survey: Survey, - posthog?: PostHog + posthog?: PostHog, + closeSurvey?: boolean, + surveyResponseUUID?: string ) => { if (!posthog) return localStorage.setItem(getSurveySeenKey(survey), 'true') - posthog.capture('survey sent', { - $survey_name: survey.name, - $survey_id: survey.id, - $survey_iteration: survey.current_iteration, - $survey_iteration_start_date: survey.current_iteration_start_date, - $survey_questions: survey.questions.map((question) => question.question), - sessionRecordingUrl: posthog.get_session_replay_url?.(), - ...responses, - $set: { - [getSurveyInteractionProperty(survey, 'responded')]: true, + posthog.capture( + 'survey sent', + { + $survey_name: survey.name, + $survey_completed: closeSurvey || false, + $survey_id: survey.id, + $survey_iteration: survey.current_iteration, + $survey_iteration_start_date: survey.current_iteration_start_date, + $survey_questions: survey.questions.map((question) => question.question), + sessionRecordingUrl: posthog.get_session_replay_url?.(), + ...responses, + $set: { + [getSurveyInteractionProperty(survey, 'responded')]: true, + }, }, - }) - window.dispatchEvent(new Event('PHSurveySent')) + { + uuid: surveyResponseUUID, + } as unknown as CaptureOptions + ) + + if (closeSurvey) { + window.dispatchEvent(new Event('PHSurveySent')) + } } export const dismissedSurveyEvent = (survey: Survey, posthog?: PostHog, readOnly?: boolean) => { diff --git a/src/posthog-core.ts b/src/posthog-core.ts index aa9dbba86..8ddd874a6 100644 --- a/src/posthog-core.ts +++ b/src/posthog-core.ts @@ -818,7 +818,7 @@ export class PostHog { const timestamp = options?.timestamp || systemTime let data: CaptureResult = { - uuid: uuidv7(), + uuid: options?.uuid || uuidv7(), event: event_name, properties: this._calculate_event_properties(event_name, properties || {}, timestamp), } diff --git a/src/types.ts b/src/types.ts index 1558c0a32..06c0e4878 100644 --- a/src/types.ts +++ b/src/types.ts @@ -332,6 +332,7 @@ export interface CaptureOptions { skip_client_rate_limiting?: boolean /** if set skips the client side rate limiting */ transport?: RequestOptions['transport'] /** if set, overrides the desired transport method */ timestamp?: Date + uuid?: string } export type FlagVariant = { flag: string; variant: string } diff --git a/src/web-experiments.ts b/src/web-experiments.ts index 2145cb236..2499c5450 100644 --- a/src/web-experiments.ts +++ b/src/web-experiments.ts @@ -13,8 +13,6 @@ import { isNullish } from './utils/type-utils' import { isUrlMatchingRegex } from './utils/request-utils' import { logger } from './utils/logger' import { Info } from './utils/event-utils' -import { Survey } from './posthog-surveys-types' -import { getSurveySeenKey } from './extensions/surveys/surveys-utils' export const webExperimentUrlValidationMap: Record< WebExperimentUrlMatchType, @@ -82,15 +80,6 @@ export class WebExperiments { this.getWebExperimentsAndEvaluateDisplayLogic() } - sendExperimentAppliedEvent(experiment: string, variant: string) { - if (!this.instance) return - - this.instance.capture('$webexperiment_applied', { - $experiment_name: experiment, - $experiment_variant: variant, - }) - } - public getWebExperimentsAndEvaluateDisplayLogic = (forceReload: boolean = false): void => { this.getWebExperiments((webExperiments) => { WebExperiments.logInfo(`retrieved web experiments from the server`) @@ -113,7 +102,6 @@ export class WebExperiments { const selectedVariant = this._featureFlags[webExperiment.feature_flag_key] as unknown as string if (selectedVariant && webExperiment.variants[selectedVariant]) { - this.sendExperimentAppliedEvent(webExperiment.name, selectedVariant) WebExperiments.applyTransforms( webExperiment.name, selectedVariant, @@ -125,7 +113,6 @@ export class WebExperiments { const testVariant = webExperiment.variants[variant] const matchTest = WebExperiments.matchesTestVariant(testVariant) if (matchTest) { - this.sendExperimentAppliedEvent(webExperiment.name, variant) WebExperiments.applyTransforms(webExperiment.name, variant, testVariant.transforms) } } @@ -225,7 +212,6 @@ export class WebExperiments { } private static applyTransforms(experiment: string, variant: string, transforms: WebExperimentTransform[]) { - sendExperimentEvent(experiment, variant) transforms.forEach((transform) => { if (transform.selector) { WebExperiments.logInfo( From 07e8d08b33f47e8b1dd48fc738dab9c2d3a70b4f Mon Sep 17 00:00:00 2001 From: Phani Raj Date: Tue, 24 Sep 2024 17:49:11 -0500 Subject: [PATCH 3/8] saving work --- package.json | 2 +- playground/nextjs/package.json | 2 +- playground/nextjs/src/posthog.ts | 1 + src/extensions/surveys.tsx | 18 ++++++++---------- src/extensions/surveys/surveys-utils.tsx | 14 ++++++++++---- src/posthog-core.ts | 2 ++ src/types.ts | 3 ++- 7 files changed, 25 insertions(+), 17 deletions(-) diff --git a/package.json b/package.json index fe08b1b17..982acacc5 100644 --- a/package.json +++ b/package.json @@ -12,7 +12,7 @@ "build-react": "cd react; NODE_ENV=dev pnpm i; pnpm build;", "lint": "eslint src && eslint cypress", "prettier": "prettier --write src/ functional_tests/", - "prepublishOnly": "pnpm lint && pnpm test && pnpm build && pnpm test:react", + "prepublishOnly": "pnpm build", "test": "pnpm test:unit && pnpm test:custom-eslint-rules && pnpm test:functional", "test:unit": "jest src", "test:custom-eslint-rules": "jest eslint-rules", diff --git a/playground/nextjs/package.json b/playground/nextjs/package.json index 4811df568..763828667 100644 --- a/playground/nextjs/package.json +++ b/playground/nextjs/package.json @@ -21,7 +21,7 @@ "eslint": "8.34.0", "eslint-config-next": "13.1.6", "next": "13.5.6", - "posthog-js": "1.128.3", + "posthog-js": "file:.yalc/posthog-js", "react": "18.2.0", "react-dom": "18.2.0", "typescript": "4.9.5" diff --git a/playground/nextjs/src/posthog.ts b/playground/nextjs/src/posthog.ts index ae913c0aa..a959ea48d 100644 --- a/playground/nextjs/src/posthog.ts +++ b/playground/nextjs/src/posthog.ts @@ -49,6 +49,7 @@ if (typeof window !== 'undefined') { session_recording: { recordCrossOriginIframes: true, }, + disable_survey_partial_response: false, debug: true, scroll_root_selector: ['#scroll_element', 'html'], persistence: cookieConsentGiven() ? 'localStorage+cookie' : 'memory', diff --git a/src/extensions/surveys.tsx b/src/extensions/surveys.tsx index aff7c3bfc..e455c9e95 100644 --- a/src/extensions/surveys.tsx +++ b/src/extensions/surveys.tsx @@ -35,6 +35,7 @@ import { import { logger } from '../utils/logger' import { Cancel } from './surveys/components/QuestionHeader' import { uuidv7 } from '../uuidv7' +import {uuid} from "fast-check"; // We cast the types here which is dangerous but protected by the top level generateSurveys call const window = _window as Window & typeof globalThis @@ -298,13 +299,10 @@ export const renderSurveysPreview = ({ survey.appearance?.backgroundColor || defaultSurveyAppearance.backgroundColor || 'white' ) - const surveyResponseUUID = uuidv7() - Preact.render( getDisplayOrderQuestions(survey), [survey]) + const surveyResponseUUID = useMemo(() => uuidv7(), [survey]) // Sync preview state useEffect(() => { @@ -565,7 +559,9 @@ export function Questions({ // Old SDK, no branching if (!posthog.getNextSurveyStep) { const isLastDisplayedQuestion = displayQuestionIndex === survey.questions.length - 1 - logger.info('POSTHOG SURVEYS: Sending survey response', questionsResponses) + logger.info(`POSTHOG SURVEYS: Sending survey response with id : ${surveyResponseUUID} `, questionsResponses) + // eslint-disable-next-line no-console + console.log(`POSTHOG SURVEYS: Sending survey response with id : ${surveyResponseUUID} `, questionsResponses) sendSurveyEvent( { ...questionsResponses, [responseKey]: res }, survey, @@ -578,7 +574,9 @@ export function Questions({ } const nextStep = posthog.getNextSurveyStep(survey, displayQuestionIndex, res) - logger.info('POSTHOG SURVEYS: Sending survey response', questionsResponses) + logger.info(`POSTHOG SURVEYS: Sending survey response with id : ${surveyResponseUUID}`, questionsResponses) + // eslint-disable-next-line no-console + console.log(`POSTHOG SURVEYS: Sending survey response with id : ${surveyResponseUUID}`, questionsResponses) sendSurveyEvent( { ...questionsResponses, [responseKey]: res }, survey, diff --git a/src/extensions/surveys/surveys-utils.tsx b/src/extensions/surveys/surveys-utils.tsx index 24b370bf1..5b67be293 100644 --- a/src/extensions/surveys/surveys-utils.tsx +++ b/src/extensions/surveys/surveys-utils.tsx @@ -534,17 +534,23 @@ export const sendSurveyEvent = ( responses: Record = {}, survey: Survey, posthog?: PostHog, - closeSurvey?: boolean, + surveyCompleted?: boolean, surveyResponseUUID?: string ) => { if (!posthog) return + + if (!surveyCompleted && posthog.config.disable_survey_partial_response) { + // do not send partial responses + return + } + localStorage.setItem(getSurveySeenKey(survey), 'true') posthog.capture( 'survey sent', { $survey_name: survey.name, - $survey_completed: closeSurvey || false, + $survey_completed: surveyCompleted || false, $survey_id: survey.id, $survey_iteration: survey.current_iteration, $survey_iteration_start_date: survey.current_iteration_start_date, @@ -557,10 +563,10 @@ export const sendSurveyEvent = ( }, { uuid: surveyResponseUUID, - } as unknown as CaptureOptions + } ) - if (closeSurvey) { + if (surveyCompleted) { window.dispatchEvent(new Event('PHSurveySent')) } } diff --git a/src/posthog-core.ts b/src/posthog-core.ts index 8ddd874a6..6ea704db5 100644 --- a/src/posthog-core.ts +++ b/src/posthog-core.ts @@ -142,6 +142,7 @@ export const defaultConfig = (): PostHogConfig => ({ disable_persistence: false, disable_web_experiments: true, // disabled in beta. disable_surveys: false, + disable_survey_partial_response: false, enable_recording_console_log: undefined, // When undefined, it falls back to the server-side setting secure_cookie: window?.location?.protocol === 'https:', ip: true, @@ -817,6 +818,7 @@ export class PostHog { const systemTime = new Date() const timestamp = options?.timestamp || systemTime + logger.info(`CORE: in capture function, uuid is : `, options?.uuid) let data: CaptureResult = { uuid: options?.uuid || uuidv7(), event: event_name, diff --git a/src/types.ts b/src/types.ts index 06c0e4878..da2731595 100644 --- a/src/types.ts +++ b/src/types.ts @@ -157,6 +157,7 @@ export interface PostHogConfig { /** @deprecated - use `disable_persistence` instead */ disable_cookie?: boolean disable_surveys: boolean + disable_survey_partial_response: boolean disable_web_experiments: boolean /** If set, posthog-js will never load external scripts such as those needed for Session Replay or Surveys. */ disable_external_dependency_loading?: boolean @@ -332,7 +333,7 @@ export interface CaptureOptions { skip_client_rate_limiting?: boolean /** if set skips the client side rate limiting */ transport?: RequestOptions['transport'] /** if set, overrides the desired transport method */ timestamp?: Date - uuid?: string + insert_id?: string } export type FlagVariant = { flag: string; variant: string } From 536de627471f0805763e08bdffd4b55b2a9d6a2d Mon Sep 17 00:00:00 2001 From: Phani Raj Date: Wed, 25 Sep 2024 15:29:32 -0500 Subject: [PATCH 4/8] send insert_id --- src/extensions/surveys.tsx | 25 ++++++++++++++++-------- src/extensions/surveys/surveys-utils.tsx | 4 ++-- src/posthog-core.ts | 8 ++++++-- 3 files changed, 25 insertions(+), 12 deletions(-) diff --git a/src/extensions/surveys.tsx b/src/extensions/surveys.tsx index e455c9e95..800e689c5 100644 --- a/src/extensions/surveys.tsx +++ b/src/extensions/surveys.tsx @@ -35,7 +35,7 @@ import { import { logger } from '../utils/logger' import { Cancel } from './surveys/components/QuestionHeader' import { uuidv7 } from '../uuidv7' -import {uuid} from "fast-check"; +import { uuid } from 'fast-check' // We cast the types here which is dangerous but protected by the top level generateSurveys call const window = _window as Window & typeof globalThis @@ -531,7 +531,10 @@ export function Questions({ const { isPreviewMode, previewPageIndex, handleCloseSurveyPopup, isPopup } = useContext(SurveyContext) const [currentQuestionIndex, setCurrentQuestionIndex] = useState(previewPageIndex || 0) const surveyQuestions = useMemo(() => getDisplayOrderQuestions(survey), [survey]) - const surveyResponseUUID = useMemo(() => uuidv7(), [survey]) + const surveyResponseInsertID = useMemo( + () => Math.random().toString(36).substring(2, 10) + Math.random().toString(36).substring(2, 10), + [survey] + ) // Sync preview state useEffect(() => { @@ -559,30 +562,36 @@ export function Questions({ // Old SDK, no branching if (!posthog.getNextSurveyStep) { const isLastDisplayedQuestion = displayQuestionIndex === survey.questions.length - 1 - logger.info(`POSTHOG SURVEYS: Sending survey response with id : ${surveyResponseUUID} `, questionsResponses) + logger.info( + `POSTHOG SURVEYS: Sending survey response with id : ${surveyResponseInsertID} `, + questionsResponses + ) // eslint-disable-next-line no-console - console.log(`POSTHOG SURVEYS: Sending survey response with id : ${surveyResponseUUID} `, questionsResponses) + console.log( + `POSTHOG SURVEYS: Sending survey response with id : ${surveyResponseInsertID} `, + questionsResponses + ) sendSurveyEvent( { ...questionsResponses, [responseKey]: res }, survey, posthog, isLastDisplayedQuestion, - surveyResponseUUID + surveyResponseInsertID ) setCurrentQuestionIndex(displayQuestionIndex + 1) return } const nextStep = posthog.getNextSurveyStep(survey, displayQuestionIndex, res) - logger.info(`POSTHOG SURVEYS: Sending survey response with id : ${surveyResponseUUID}`, questionsResponses) + logger.info(`POSTHOG SURVEYS: Sending survey response with id : ${surveyResponseInsertID}`, questionsResponses) // eslint-disable-next-line no-console - console.log(`POSTHOG SURVEYS: Sending survey response with id : ${surveyResponseUUID}`, questionsResponses) + console.log(`POSTHOG SURVEYS: Sending survey response with id : ${surveyResponseInsertID}`, questionsResponses) sendSurveyEvent( { ...questionsResponses, [responseKey]: res }, survey, posthog, nextStep === SurveyQuestionBranchingType.End, - surveyResponseUUID + surveyResponseInsertID ) if (nextStep !== SurveyQuestionBranchingType.End) { setCurrentQuestionIndex(nextStep) diff --git a/src/extensions/surveys/surveys-utils.tsx b/src/extensions/surveys/surveys-utils.tsx index 5b67be293..4fc77d5e7 100644 --- a/src/extensions/surveys/surveys-utils.tsx +++ b/src/extensions/surveys/surveys-utils.tsx @@ -535,7 +535,7 @@ export const sendSurveyEvent = ( survey: Survey, posthog?: PostHog, surveyCompleted?: boolean, - surveyResponseUUID?: string + surveyResponseInsertID?: string ) => { if (!posthog) return @@ -562,7 +562,7 @@ export const sendSurveyEvent = ( }, }, { - uuid: surveyResponseUUID, + insert_id: surveyResponseInsertID, } ) diff --git a/src/posthog-core.ts b/src/posthog-core.ts index 6ea704db5..173146365 100644 --- a/src/posthog-core.ts +++ b/src/posthog-core.ts @@ -818,13 +818,17 @@ export class PostHog { const systemTime = new Date() const timestamp = options?.timestamp || systemTime - logger.info(`CORE: in capture function, uuid is : `, options?.uuid) + logger.info(`CORE: in capture function, insert_id is : `, options?.insert_id) let data: CaptureResult = { - uuid: options?.uuid || uuidv7(), + uuid: uuidv7(), event: event_name, properties: this._calculate_event_properties(event_name, properties || {}, timestamp), } + if (options?.insert_id) { + data.properties.$insert_id = options?.insert_id + } + if (clientRateLimitContext) { data.properties['$lib_rate_limit_remaining_tokens'] = clientRateLimitContext.remainingTokens } From 9a737221d65a211d4c0a6fa89075c4740447f7ff Mon Sep 17 00:00:00 2001 From: Phani Raj Date: Wed, 20 Nov 2024 11:41:47 -0600 Subject: [PATCH 5/8] rename property to --- src/extensions/surveys.tsx | 7 ------ src/extensions/surveys/surveys-utils.tsx | 31 ++++++++++-------------- 2 files changed, 13 insertions(+), 25 deletions(-) diff --git a/src/extensions/surveys.tsx b/src/extensions/surveys.tsx index aa41ff1e3..768fb1271 100644 --- a/src/extensions/surveys.tsx +++ b/src/extensions/surveys.tsx @@ -564,11 +564,6 @@ export function Questions({ `POSTHOG SURVEYS: Sending survey response with id : ${surveyResponseInsertID} `, questionsResponses ) - // eslint-disable-next-line no-console - console.log( - `POSTHOG SURVEYS: Sending survey response with id : ${surveyResponseInsertID} `, - questionsResponses - ) sendSurveyEvent( { ...questionsResponses, [responseKey]: res }, survey, @@ -582,8 +577,6 @@ export function Questions({ const nextStep = posthog.getNextSurveyStep(survey, displayQuestionIndex, res) logger.info(`POSTHOG SURVEYS: Sending survey response with id : ${surveyResponseInsertID}`, questionsResponses) - // eslint-disable-next-line no-console - console.log(`POSTHOG SURVEYS: Sending survey response with id : ${surveyResponseInsertID}`, questionsResponses) sendSurveyEvent( { ...questionsResponses, [responseKey]: res }, survey, diff --git a/src/extensions/surveys/surveys-utils.tsx b/src/extensions/surveys/surveys-utils.tsx index 489538c73..93f09bc16 100644 --- a/src/extensions/surveys/surveys-utils.tsx +++ b/src/extensions/surveys/surveys-utils.tsx @@ -545,25 +545,20 @@ export const sendSurveyEvent = ( localStorage.setItem(getSurveySeenKey(survey), 'true') - posthog.capture( - 'survey sent', - { - $survey_name: survey.name, - $survey_completed: surveyCompleted || false, - $survey_id: survey.id, - $survey_iteration: survey.current_iteration, - $survey_iteration_start_date: survey.current_iteration_start_date, - $survey_questions: survey.questions.map((question) => question.question), - sessionRecordingUrl: posthog.get_session_replay_url?.(), - ...responses, - $set: { - [getSurveyInteractionProperty(survey, 'responded')]: true, - }, + posthog.capture('survey sent', { + $survey_name: survey.name, + $survey_completed: surveyCompleted || false, + $survey_id: survey.id, + $survey_response_id: surveyResponseInsertID, + $survey_iteration: survey.current_iteration, + $survey_iteration_start_date: survey.current_iteration_start_date, + $survey_questions: survey.questions.map((question) => question.question), + sessionRecordingUrl: posthog.get_session_replay_url?.(), + ...responses, + $set: { + [getSurveyInteractionProperty(survey, 'responded')]: true, }, - { - insert_id: surveyResponseInsertID, - } - ) + }) if (surveyCompleted) { window.dispatchEvent(new Event('PHSurveySent')) From 92cdc4b787a4a717833dc2abf0a307ddbd286ad3 Mon Sep 17 00:00:00 2001 From: Phani Raj Date: Wed, 20 Nov 2024 11:44:24 -0600 Subject: [PATCH 6/8] remove insert_id override --- package.json | 42 +++++++++++++++++++--------------- playground/nextjs/package.json | 11 +++++---- src/posthog-core.ts | 5 ---- src/types.ts | 1 - 4 files changed, 29 insertions(+), 30 deletions(-) diff --git a/package.json b/package.json index 982acacc5..8b5e20c78 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "posthog-js", - "version": "1.161.3", + "version": "1.187.2", "description": "Posthog-js allows you to automatically capture usage and send events to PostHog.", "repository": "https://github.com/PostHog/posthog-js", "author": "hey@posthog.com", @@ -11,8 +11,9 @@ "build-rollup": "rm -rf lib && tsc -b && rollup -c --bundleConfigAsCjs", "build-react": "cd react; NODE_ENV=dev pnpm i; pnpm build;", "lint": "eslint src && eslint cypress", + "lint:fix": "eslint src --fix && eslint cypress --fix", "prettier": "prettier --write src/ functional_tests/", - "prepublishOnly": "pnpm build", + "prepublishOnly": "pnpm lint && pnpm build && pnpm test && pnpm test:react", "test": "pnpm test:unit && pnpm test:custom-eslint-rules && pnpm test:functional", "test:unit": "jest src", "test:custom-eslint-rules": "jest eslint-rules", @@ -37,39 +38,44 @@ "react/package.json" ], "dependencies": { + "core-js": "^3.38.1", "fflate": "^0.4.8", "preact": "^10.19.3", - "web-vitals": "^4.0.1" + "web-vitals": "^4.2.0" }, "devDependencies": { "@babel/core": "7.18.9", "@babel/plugin-syntax-decorators": "^7.23.3", + "@babel/plugin-transform-exponentiation-operator": "^7.25.9", + "@babel/plugin-transform-nullish-coalescing-operator": "^7.25.8", "@babel/plugin-transform-react-jsx": "^7.23.4", "@babel/preset-env": "7.18.9", "@babel/preset-typescript": "^7.18.6", "@cypress/skip-test": "^2.6.1", "@jest/globals": "^27.5.1", "@rollup/plugin-babel": "^6.0.4", + "@rollup/plugin-commonjs": "^28.0.1", "@rollup/plugin-json": "^6.1.0", - "@rollup/plugin-node-resolve": "^15.2.3", + "@rollup/plugin-node-resolve": "^15.3.0", "@rollup/plugin-terser": "^0.4.4", - "@rollup/plugin-typescript": "^11.1.6", - "@rrweb/types": "2.0.0-alpha.13", + "@rollup/plugin-typescript": "^12.1.1", + "@rrweb/record": "2.0.0-alpha.17", + "@rrweb/rrweb-plugin-console-record": "2.0.0-alpha.17", + "@rrweb/types": "2.0.0-alpha.17", "@sentry/types": "8.7.0", "@testing-library/dom": "^9.3.0", - "@testing-library/jest-dom": "^6.4.5", + "@testing-library/jest-dom": "^6.5.0", "@testing-library/preact": "^3.2.4", "@types/eslint": "^8.44.6", - "@types/jest": "^29.5.1", + "@types/jest": "^27.5.2", "@types/node": "^22.5.0", "@types/react-dom": "^18.0.10", "@types/sinon": "^17.0.1", - "@types/uuid": "^9.0.1", "@types/web": "^0.0.154", "@typescript-eslint/eslint-plugin": "^8.2.0", "@typescript-eslint/parser": "^8.2.0", - "babel-eslint": "10.1.0", "babel-jest": "^26.6.3", + "browserslist": "^4.24.2", "compare-versions": "^6.1.0", "cypress": "13.6.3", "cypress-localstorage-commands": "^2.2.6", @@ -77,15 +83,14 @@ "eslint": "8.57.0", "eslint-config-posthog-js": "link:eslint-rules", "eslint-config-prettier": "^8.5.0", - "eslint-plugin-compat": "^4.1.4", - "eslint-plugin-jest": "^28.8.0", + "eslint-plugin-compat": "^6.0.1", + "eslint-plugin-jest": "^28.8.3", "eslint-plugin-no-only-tests": "^3.1.0", "eslint-plugin-posthog-js": "link:eslint-rules", "eslint-plugin-prettier": "^4.2.1", "eslint-plugin-react": "^7.30.1", "eslint-plugin-react-hooks": "^4.6.0", "expect": "^29.7.0", - "express": "^4.19.2", "fast-check": "^2.17.0", "husky": "^8.0.1", "jest": "^27.5.1", @@ -98,16 +103,14 @@ "posthog-js": "link:", "preact-render-to-string": "^6.3.1", "prettier": "^2.7.1", - "rollup": "^4.9.6", - "rollup-plugin-dts": "^6.1.0", + "rollup": "^4.24.0", + "rollup-plugin-dts": "^6.1.1", "rollup-plugin-visualizer": "^5.12.0", - "rrweb": "2.0.0-alpha.13", - "rrweb-snapshot": "2.0.0-alpha.13", "sinon": "9.0.2", "testcafe": "1.19.0", "testcafe-browser-provider-browserstack": "1.14.0", - "tslib": "^2.5.0", "ts-node": "^10.9.2", + "tslib": "^2.5.0", "typescript": "^5.5.4", "yargs": "^17.7.2" }, @@ -124,7 +127,8 @@ ], "pnpm": { "patchedDependencies": { - "rrweb@2.0.0-alpha.13": "patches/rrweb@2.0.0-alpha.13.patch" + "@rrweb/rrweb-plugin-console-record@2.0.0-alpha.17": "patches/@rrweb__rrweb-plugin-console-record@2.0.0-alpha.17.patch", + "@rrweb/record@2.0.0-alpha.17": "patches/@rrweb__record@2.0.0-alpha.17.patch" } } } diff --git a/playground/nextjs/package.json b/playground/nextjs/package.json index 763828667..9f2d195b3 100644 --- a/playground/nextjs/package.json +++ b/playground/nextjs/package.json @@ -13,23 +13,24 @@ "link-posthog-js": "cd ../../ && pnpm link --global && cd playground/nextjs && pnpm link --global posthog-js" }, "dependencies": { - "@lottiefiles/react-lottie-player": "^3.5.3", + "@lottiefiles/react-lottie-player": "^3.5.4", "@types/node": "18.13.0", "@types/react": "18.0.28", "@types/react-dom": "18.0.10", "cookie": "^0.6.0", "eslint": "8.34.0", "eslint-config-next": "13.1.6", + "hls.js": "^1.5.15", "next": "13.5.6", - "posthog-js": "file:.yalc/posthog-js", + "posthog-js": "1.166.0", "react": "18.2.0", "react-dom": "18.2.0", "typescript": "4.9.5" }, "devDependencies": { "@types/cookie": "^0.6.0", - "autoprefixer": "^10.4.17", - "postcss": "^8.4.35", - "tailwindcss": "^3.4.1" + "autoprefixer": "^10.4.20", + "postcss": "^8.4.47", + "tailwindcss": "^3.4.13" } } diff --git a/src/posthog-core.ts b/src/posthog-core.ts index b1b5560b9..c1922c0a6 100644 --- a/src/posthog-core.ts +++ b/src/posthog-core.ts @@ -845,17 +845,12 @@ export class PostHog { const systemTime = new Date() const timestamp = options?.timestamp || systemTime - logger.info(`CORE: in capture function, insert_id is : `, options?.insert_id) let data: CaptureResult = { uuid: uuidv7(), event: event_name, properties: this._calculate_event_properties(event_name, properties || {}, timestamp), } - if (options?.insert_id) { - data.properties.$insert_id = options?.insert_id - } - if (clientRateLimitContext) { data.properties['$lib_rate_limit_remaining_tokens'] = clientRateLimitContext.remainingTokens } diff --git a/src/types.ts b/src/types.ts index 7591c3681..d54708952 100644 --- a/src/types.ts +++ b/src/types.ts @@ -470,7 +470,6 @@ export interface CaptureOptions { skip_client_rate_limiting?: boolean /** if set skips the client side rate limiting */ transport?: RequestOptions['transport'] /** if set, overrides the desired transport method */ timestamp?: Date - insert_id?: string } export type FlagVariant = { flag: string; variant: string } From 229b9580e0ebc7084f1572e50b0701ef03d219be Mon Sep 17 00:00:00 2001 From: Phani Raj Date: Fri, 22 Nov 2024 09:33:04 -0600 Subject: [PATCH 7/8] use responseId that's passed in --- src/extensions/surveys.tsx | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/src/extensions/surveys.tsx b/src/extensions/surveys.tsx index 768fb1271..f3db87e12 100644 --- a/src/extensions/surveys.tsx +++ b/src/extensions/surveys.tsx @@ -456,6 +456,11 @@ export function SurveyPopup({ removeSurveyFromFocus: (id: string) => void isPopup?: boolean }) { + const surveyResponseInsertID = useMemo( + () => survey.id + Math.random().toString(36).substring(2, 10) + Math.random().toString(36).substring(2, 10), + [survey.id] + ) + const isPreviewMode = Number.isInteger(previewPageIndex) // NB: The client-side code passes the millisecondDelay in seconds, but setTimeout expects milliseconds, so we multiply by 1000 const surveyPopupDelayMilliseconds = survey.appearance?.surveyPopupDelaySeconds @@ -493,6 +498,7 @@ export function SurveyPopup({ forceDisableHtml={!!forceDisableHtml} posthog={posthog} styleOverrides={style} + surveyResponseInsertID={surveyResponseInsertID} /> ) : ( getDisplayOrderQuestions(survey), [survey]) - const surveyResponseInsertID = useMemo( - () => Math.random().toString(36).substring(2, 10) + Math.random().toString(36).substring(2, 10), - [survey] - ) // Sync preview state useEffect(() => { From b8a9e044a5d6c7c2803450bddef4154b532c9520 Mon Sep 17 00:00:00 2001 From: Phani Raj Date: Fri, 20 Dec 2024 11:16:00 -0600 Subject: [PATCH 8/8] Apply suggestions from code review Co-authored-by: Manoel Aranda Neto <5731772+marandaneto@users.noreply.github.com> --- src/posthog-core.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/posthog-core.ts b/src/posthog-core.ts index 1a8f7aa4e..4727782f6 100644 --- a/src/posthog-core.ts +++ b/src/posthog-core.ts @@ -145,7 +145,7 @@ export const defaultConfig = (): PostHogConfig => ({ disable_persistence: false, disable_web_experiments: true, // disabled in beta. disable_surveys: false, - disable_survey_partial_response: false, + disable_survey_partial_response: true, enable_recording_console_log: undefined, // When undefined, it falls back to the server-side setting secure_cookie: window?.location?.protocol === 'https:', ip: true,