Skip to content

Commit

Permalink
Move to string types
Browse files Browse the repository at this point in the history
  • Loading branch information
benjackwhite committed Feb 1, 2024
1 parent f8bf3c7 commit c7e742e
Show file tree
Hide file tree
Showing 9 changed files with 36 additions and 66 deletions.
43 changes: 18 additions & 25 deletions src/decide.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@ import { STORED_GROUP_PROPERTIES_KEY, STORED_PERSON_PROPERTIES_KEY } from './con
import { _isUndefined } from './utils/type-utils'
import { logger } from './utils/logger'
import { window, document, assignableWindow } from './utils/globals'
import { RequestRouterTarget } from './utils/request-router'

export class Decide {
instance: PostHog
Expand Down Expand Up @@ -36,7 +35,7 @@ export class Decide {

const encoded_data = _base64Encode(json_data)
this.instance._send_request(
this.instance.requestRouter.endpointFor(RequestRouterTarget.DECIDE, '/decide/?v=3'),
this.instance.requestRouter.endpointFor('decide', '/decide/?v=3'),
{ data: encoded_data, verbose: true },
{ method: 'POST' },
(response) => this.parseDecideResponse(response as DecideResponse)
Expand Down Expand Up @@ -77,18 +76,15 @@ export class Decide {
const surveysGenerator = window?.extendPostHogWithSurveys

if (response['surveys'] && !surveysGenerator) {
loadScript(
this.instance.requestRouter.endpointFor(RequestRouterTarget.ASSETS, '/static/surveys.js'),
(err) => {
if (err) {
return logger.error(`Could not load surveys script`, err)
}

// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
window.extendPostHogWithSurveys(this.instance)
loadScript(this.instance.requestRouter.endpointFor('assets', '/static/surveys.js'), (err) => {
if (err) {
return logger.error(`Could not load surveys script`, err)
}
)

// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
window.extendPostHogWithSurveys(this.instance)
})
}

// eslint-disable-next-line @typescript-eslint/ban-ts-comment
Expand All @@ -99,24 +95,21 @@ export class Decide {
!!response['autocaptureExceptions'] &&
_isUndefined(exceptionAutoCaptureAddedToWindow)
) {
loadScript(
this.instance.requestRouter.endpointFor(RequestRouterTarget.ASSETS, '/static/exception-autocapture.js'),
(err) => {
if (err) {
return logger.error(`Could not load exception autocapture script`, err)
}

// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
window.extendPostHogWithExceptionAutocapture(this.instance, response)
loadScript(this.instance.requestRouter.endpointFor('assets', '/static/exception-autocapture.js'), (err) => {
if (err) {
return logger.error(`Could not load exception autocapture script`, err)
}
)

// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
window.extendPostHogWithExceptionAutocapture(this.instance, response)
})
}

if (response['siteApps']) {
if (this.instance.config.opt_in_site_apps) {
for (const { id, url } of response['siteApps']) {
const scriptUrl = this.instance.requestRouter.endpointFor(RequestRouterTarget.ASSETS, url)
const scriptUrl = this.instance.requestRouter.endpointFor('assets', url)

assignableWindow[`__$$ph_site_app_${id}`] = this.instance

Expand Down
3 changes: 1 addition & 2 deletions src/extensions/exception-autocapture/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ import { isPrimitive } from './type-checking'

import { _isArray, _isObject, _isUndefined } from '../../utils/type-utils'
import { logger } from '../../utils/logger'
import { RequestRouterTarget } from 'utils/request-router'

const EXCEPTION_INGESTION_ENDPOINT = '/e/'

Expand Down Expand Up @@ -130,7 +129,7 @@ export class ExceptionObserver {

const propertiesToSend = { ...properties, ...errorProperties }

const posthogHost = this.instance.requestRouter.endpointFor(RequestRouterTarget.UI)
const posthogHost = this.instance.requestRouter.endpointFor('ui')
errorProperties.$exception_personURL = posthogHost + '/person/' + this.instance.get_distinct_id()

this.sendExceptionEvent(propertiesToSend)
Expand Down
6 changes: 1 addition & 5 deletions src/extensions/replay/sessionrecording.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,6 @@ import { assignableWindow, window } from '../../utils/globals'
import { buildNetworkRequestOptions } from './config'
import { isLocalhost } from '../../utils/request-utils'
import { userOptedOut } from '../../gdpr-utils'
import { RequestRouterTarget } from 'utils/request-router'

const BASE_ENDPOINT = '/s/'

Expand Down Expand Up @@ -414,10 +413,7 @@ export class SessionRecording {
// recorder.js from cdn since it hasn't been loaded.
if (this.instance.__loaded_recorder_version !== this.recordingVersion) {
loadScript(
this.instance.requestRouter.endpointFor(
RequestRouterTarget.ASSETS,
`/static/${recorderJS}?v=${Config.LIB_VERSION}`
),
this.instance.requestRouter.endpointFor('assets', `/static/${recorderJS}?v=${Config.LIB_VERSION}`),
(err) => {
if (err) {
return logger.error(`Could not load ${recorderJS}`, err)
Expand Down
6 changes: 1 addition & 5 deletions src/extensions/sentry-integration.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,6 @@
* @param {string} [prefix] Optional: Url of a self-hosted sentry instance (default: https://sentry.io/organizations/)
*/

import { RequestRouterTarget } from '../utils/request-router'
import { PostHog } from '../posthog-core'

// NOTE - we can't import from @sentry/types because it changes frequently and causes clashes
Expand Down Expand Up @@ -65,10 +64,7 @@ export class SentryIntegration implements _SentryIntegration {
if (event.level !== 'error' || !_posthog.__loaded) return event
if (!event.tags) event.tags = {}

const personUrl = _posthog.requestRouter.endpointFor(
RequestRouterTarget.UI,
'/person/' + _posthog.get_distinct_id()
)
const personUrl = _posthog.requestRouter.endpointFor('ui', '/person/' + _posthog.get_distinct_id())
event.tags['PostHog Person URL'] = personUrl
if (_posthog.sessionRecordingStarted()) {
event.tags['PostHog Recording URL'] = _posthog.get_session_replay_url({ withTimestamp: true })
Expand Down
3 changes: 1 addition & 2 deletions src/extensions/toolbar.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ import { DecideResponse, ToolbarParams } from '../types'
import { _getHashParam } from '../utils/request-utils'
import { logger } from '../utils/logger'
import { window, document, assignableWindow } from '../utils/globals'
import { RequestRouterTarget } from 'utils/request-router'

// TRICKY: Many web frameworks will modify the route on load, potentially before posthog is initialized.
// To get ahead of this we grab it as soon as the posthog-js is parsed
Expand Down Expand Up @@ -126,7 +125,7 @@ export class Toolbar {
// only load the toolbar once, even if there are multiple instances of PostHogLib
assignableWindow['_postHogToolbarLoaded'] = true

const host = this.instance.requestRouter.endpointFor(RequestRouterTarget.ASSETS)
const host = this.instance.requestRouter.endpointFor('assets')
// toolbar.js is served from the PostHog CDN, this has a TTL of 24 hours.
// the toolbar asset includes a rotating "token" that is valid for 5 minutes.
const fiveMinutesInMillis = 5 * 60 * 1000
Expand Down
9 changes: 3 additions & 6 deletions src/posthog-core.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ import { compressData, decideCompression } from './compression'
import { addParamsToURL, encodePostData, xhr } from './send-request'
import { RetryQueue } from './retry-queue'
import { SessionIdManager } from './sessionid'
import { RequestRouter, RequestRouterTarget } from './utils/request-router'
import { RequestRouter } from './utils/request-router'
import {
AutocaptureConfig,
CaptureOptions,
Expand Down Expand Up @@ -914,10 +914,7 @@ export class PostHog {

// TODO: This doesn't really work 🤔 as the other endpoints call this with "options.endpoint"
// which now needs to be a complete override
const url = this.requestRouter.endpointFor(
RequestRouterTarget.CAPTURE_EVENTS,
options.endpoint || this.analyticsDefaultEndpoint
)
const url = this.requestRouter.endpointFor('capture_events', options.endpoint || this.analyticsDefaultEndpoint)

const has_unique_traits = options !== __NOOPTIONS

Expand Down Expand Up @@ -1536,7 +1533,7 @@ export class PostHog {
return ''
}
const { sessionId, sessionStartTimestamp } = this.sessionManager.checkAndGetSessionAndWindowId(true)
let url = this.requestRouter.endpointFor(RequestRouterTarget.UI, '/replay/' + sessionId)
let url = this.requestRouter.endpointFor('ui', '/replay/' + sessionId)
if (options?.withTimestamp && sessionStartTimestamp) {
const LOOK_BACK = options.timestampLookBack ?? 10
if (!sessionStartTimestamp) {
Expand Down
5 changes: 2 additions & 3 deletions src/posthog-featureflags.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,6 @@ import {

import { _isArray } from './utils/type-utils'
import { logger } from './utils/logger'
import { RequestRouterTarget } from './utils/request-router'

const PERSISTENCE_ACTIVE_FEATURE_FLAGS = '$active_feature_flags'
const PERSISTENCE_OVERRIDE_FEATURE_FLAGS = '$override_feature_flags'
Expand Down Expand Up @@ -191,7 +190,7 @@ export class PostHogFeatureFlags {

const encoded_data = _base64Encode(json_data)
this.instance._send_request(
this.instance.requestRouter.endpointFor(RequestRouterTarget.DECIDE, '/decide/?v=3'),
this.instance.requestRouter.endpointFor('decide', '/decide/?v=3'),
{ data: encoded_data },
{ method: 'POST' },
this.instance._prepare_callback((response) => {
Expand Down Expand Up @@ -359,7 +358,7 @@ export class PostHogFeatureFlags {
if (!existing_early_access_features || force_reload) {
this.instance._send_request(
this.instance.requestRouter.endpointFor(
RequestRouterTarget.ASSETS,
'assets',
`/api/early_access_features/?token=${this.instance.config.token}`
),
{},
Expand Down
6 changes: 1 addition & 5 deletions src/posthog-surveys.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ import { SURVEYS } from './constants'
import { SurveyCallback, SurveyUrlMatchType } from './posthog-surveys-types'
import { _isUrlMatchingRegex } from './utils/request-utils'
import { window, document } from './utils/globals'
import { RequestRouterTarget } from 'utils/request-router'

export const surveyUrlValidationMap: Record<SurveyUrlMatchType, (conditionsUrl: string) => boolean> = {
icontains: (conditionsUrl) =>
Expand All @@ -23,10 +22,7 @@ export class PostHogSurveys {
const existingSurveys = this.instance.get_property(SURVEYS)
if (!existingSurveys || forceReload) {
this.instance._send_request(
this.instance.requestRouter.endpointFor(
RequestRouterTarget.ASSETS,
`/api/surveys/?token=${this.instance.config.token}`
),
this.instance.requestRouter.endpointFor('assets', `/api/surveys/?token=${this.instance.config.token}`),
{},
{ method: 'GET' },
(response) => {
Expand Down
21 changes: 8 additions & 13 deletions src/utils/request-router.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,13 +12,7 @@ export enum RequestRouterRegion {
CUSTOM = 'custom',
}

export enum RequestRouterTarget {
UI = 'ui',
CAPTURE_EVENTS = 'capture_events',
CAPTURE_REPLAY = 'capture_replay',
DECIDE = 'decide',
ASSETS = 'assets',
}
export type RequestRouterTarget = 'ui' | 'capture_events' | 'capture_replay' | 'decide' | 'assets'

// DEV NOTES:
// app.posthog.com should become us.i.posthog.com as the base host
Expand All @@ -45,10 +39,10 @@ export class RequestRouter {
}
}

endpointFor(target: RequestRouterTarget, path: string = '') {
endpointFor(target: RequestRouterTarget, path: string = ''): string {
const uiHost = this.instance.config.ui_host || this.instance.config.api_host

if (target === RequestRouterTarget.UI) {
if (target === 'ui') {
return uiHost
}

Expand All @@ -59,13 +53,14 @@ export class RequestRouter {
const suffix = 'i.posthog.com' + path

switch (target) {
case RequestRouterTarget.CAPTURE_EVENTS:
case 'capture_events':
return `https://${this.region}-c.${suffix}`
case RequestRouterTarget.CAPTURE_REPLAY:
case 'capture_replay':
return `https://${this.region}-s.${suffix}`
case RequestRouterTarget.DECIDE:
case 'decide':
return `https://${this.region}-d.${suffix}`
case RequestRouterTarget.ASSETS:
case 'assets':
default:
// TODO: Is this right? This would be all things like surveys / early access requests
return `https://${this.region}.${suffix}`
}
Expand Down

0 comments on commit c7e742e

Please sign in to comment.