Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

make fetch priority and headers configurable #1204

Draft
wants to merge 13 commits into
base: master
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/chilly-mugs-applaud.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@segment/analytics-core': patch
---

Fix integration type
23 changes: 23 additions & 0 deletions .changeset/heavy-taxis-suffer.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
---
'@segment/analytics-next': minor
---
Add new `headers` setting, along with `fetchPriority`.

```ts
analytics.load("<YOUR_WRITE_KEY>",
{
integrations: {
'Segment.io': {
deliveryStrategy: {
strategy: "standard" // also works for 'batching'
config: {
headers: { 'x-api-key': 'foo' } or () => {...}
fetchPriority: 'low' | 'high', // new setting
},
},
},
},
}
)

```
34 changes: 34 additions & 0 deletions packages/browser/src/browser/__tests__/integration.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1533,3 +1533,37 @@ describe('Options', () => {
})
})
})

describe('setting headers', () => {
it('allows setting headers', async () => {
const [ajs] = await AnalyticsBrowser.load(
{
writeKey,
},
{
integrations: {
'Segment.io': {
deliveryStrategy: {
config: {
headers: {
'X-Test': 'foo',
},
},
},
},
},
}
)

await ajs.track('sup')

await sleep(10)
const [call] = fetchCalls.filter((el) =>
el.url.toString().includes('api.segment.io')
)
expect(call.headers).toEqual({
'Content-Type': 'text/plain',
'X-Test': 'foo',
})
})
})
2 changes: 1 addition & 1 deletion packages/browser/src/browser/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -301,7 +301,7 @@ async function registerPlugins(
basePlugins.push(
await segmentio(
analytics,
mergedSettings['Segment.io'] as SegmentioSettings,
mergedSettings['Segment.io'],
cdnSettings.integrations
)
)
Expand Down
6 changes: 3 additions & 3 deletions packages/browser/src/core/analytics/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ import { Emitter } from '@segment/analytics-generic-utils'
import {
Callback,
EventFactory,
Integrations,
IntegrationsOptions,
Plan,
EventProperties,
SegmentEvent,
Expand Down Expand Up @@ -135,7 +135,7 @@ export interface InitOptions {
storage?: StorageSettings
user?: UserOptions
group?: UserOptions
integrations?: Integrations
integrations?: IntegrationsOptions
plan?: Plan
retryQueue?: boolean
obfuscate?: boolean
Expand Down Expand Up @@ -197,7 +197,7 @@ export class Analytics
private _universalStorage: UniversalStorage

initialized = false
integrations: Integrations
integrations: IntegrationsOptions
options: InitOptions
queue: EventQueue

Expand Down
14 changes: 7 additions & 7 deletions packages/browser/src/core/events/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { v4 as uuid } from '@lukeed/uuid'
import { ID, User } from '../user'
import {
Options,
Integrations,
IntegrationsOptions,
EventProperties,
Traits,
SegmentEvent,
Expand Down Expand Up @@ -53,7 +53,7 @@ export class EventFactory extends CoreEventFactory {
event: string,
properties?: EventProperties,
options?: Options,
globalIntegrations?: Integrations,
globalIntegrations?: IntegrationsOptions,
pageCtx?: PageContext
): SegmentEvent {
const ev = super.track(event, properties, options, globalIntegrations)
Expand All @@ -66,7 +66,7 @@ export class EventFactory extends CoreEventFactory {
page: string | null,
properties?: EventProperties,
options?: Options,
globalIntegrations?: Integrations,
globalIntegrations?: IntegrationsOptions,
pageCtx?: PageContext
): SegmentEvent {
const ev = super.page(
Expand All @@ -85,7 +85,7 @@ export class EventFactory extends CoreEventFactory {
screen: string | null,
properties?: EventProperties,
options?: Options,
globalIntegrations?: Integrations,
globalIntegrations?: IntegrationsOptions,
pageCtx?: PageContext
): SegmentEvent {
const ev = super.screen(
Expand All @@ -103,7 +103,7 @@ export class EventFactory extends CoreEventFactory {
userId: ID,
traits?: Traits,
options?: Options,
globalIntegrations?: Integrations,
globalIntegrations?: IntegrationsOptions,
pageCtx?: PageContext
): SegmentEvent {
const ev = super.identify(userId, traits, options, globalIntegrations)
Expand All @@ -115,7 +115,7 @@ export class EventFactory extends CoreEventFactory {
groupId: ID,
traits?: Traits,
options?: Options,
globalIntegrations?: Integrations,
globalIntegrations?: IntegrationsOptions,
pageCtx?: PageContext
): SegmentEvent {
const ev = super.group(groupId, traits, options, globalIntegrations)
Expand All @@ -127,7 +127,7 @@ export class EventFactory extends CoreEventFactory {
to: string,
from: string | null,
options?: Options,
globalIntegrations?: Integrations,
globalIntegrations?: IntegrationsOptions,
pageCtx?: PageContext
): SegmentEvent {
const ev = super.alias(to, from, options, globalIntegrations)
Expand Down
4 changes: 2 additions & 2 deletions packages/browser/src/core/events/interfaces.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import {
CoreOptions,
CoreSegmentEvent,
Callback,
Integrations,
IntegrationsOptions,
Plan,
TrackPlan,
PlanEvent,
Expand All @@ -24,7 +24,7 @@ export type EventProperties = Record<string, any>
export interface SegmentEvent extends CoreSegmentEvent {}

export type {
Integrations,
IntegrationsOptions,
Plan,
TrackPlan,
PlanEvent,
Expand Down
8 changes: 4 additions & 4 deletions packages/browser/src/lib/merged-options.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { JSONObject, Options } from '../core/events/interfaces'
import { Options } from '../core/events/interfaces'
import { CDNSettings } from '../browser'

/**
Expand All @@ -13,7 +13,7 @@ import { CDNSettings } from '../browser'
export function mergedOptions(
cdnSettings: CDNSettings,
options: Options
): Record<string, JSONObject> {
): Record<string, any> {
const optionOverrides = Object.entries(options.integrations ?? {}).reduce(
(overrides, [integration, options]) => {
if (typeof options === 'object') {
Expand All @@ -28,7 +28,7 @@ export function mergedOptions(
[integration]: {},
}
},
{} as Record<string, JSONObject>
{} as Record<string, any>
)

return Object.entries(cdnSettings.integrations).reduce(
Expand All @@ -41,6 +41,6 @@ export function mergedOptions(
},
}
},
{} as Record<string, JSONObject>
{} as Record<string, any>
)
}
4 changes: 2 additions & 2 deletions packages/browser/src/plugins/ajs-destination/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { Integrations, JSONObject } from '../../core/events'
import { IntegrationsOptions, JSONObject } from '../../core/events'
import { Alias, Facade, Group, Identify, Page, Track } from '@segment/facade'
import { Analytics, InitOptions } from '../../core/analytics'
import { CDNSettings } from '../../browser'
Expand Down Expand Up @@ -332,7 +332,7 @@
export function ajsDestinations(
writeKey: string,
settings: CDNSettings,
globalIntegrations: Integrations = {},
globalIntegrations: IntegrationsOptions = {},

Check warning on line 335 in packages/browser/src/plugins/ajs-destination/index.ts

View check run for this annotation

Codecov / codecov/patch

packages/browser/src/plugins/ajs-destination/index.ts#L335

Added line #L335 was not covered by tests
options: InitOptions = {},
routingMiddleware?: DestinationMiddlewareFunction,
legacyIntegrationSources?: ClassicIntegrationSource[]
Expand Down
4 changes: 2 additions & 2 deletions packages/browser/src/plugins/ajs-destination/utils.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { Integrations } from '@segment/analytics-core'
import { IntegrationsOptions } from '@segment/analytics-core'
import { RemoteIntegrationSettings } from '../..'

export const isInstallableIntegration = (
Expand All @@ -20,7 +20,7 @@

export const isDisabledIntegration = (
integrationName: string,
globalIntegrations: Integrations
globalIntegrations: IntegrationsOptions

Check warning on line 23 in packages/browser/src/plugins/ajs-destination/utils.ts

View check run for this annotation

Codecov / codecov/patch

packages/browser/src/plugins/ajs-destination/utils.ts#L23

Added line #L23 was not covered by tests
) => {
const allDisableAndNotDefined =
globalIntegrations.All === false &&
Expand Down
9 changes: 5 additions & 4 deletions packages/browser/src/plugins/remote-loader/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import type { Integrations } from '../../core/events/interfaces'
import type { IntegrationsOptions } from '../../core/events/interfaces'
import { CDNSettings } from '../../browser'
import { JSONObject, JSONValue } from '../../core/events'
import { Plugin, InternalPluginWithAddMiddleware } from '../../core/plugin'
Expand Down Expand Up @@ -198,7 +198,7 @@
}

function isPluginDisabled(
userIntegrations: Integrations,
userIntegrations: IntegrationsOptions,
remotePlugin: RemotePlugin
) {
const creationNameEnabled = userIntegrations[remotePlugin.creationName]
Expand Down Expand Up @@ -260,7 +260,7 @@

export async function remoteLoader(
settings: CDNSettings,
userIntegrations: Integrations,
userIntegrations: IntegrationsOptions,
mergedIntegrations: Record<string, JSONObject>,
options?: InitOptions,
routingMiddleware?: DestinationMiddlewareFunction,
Expand All @@ -281,9 +281,10 @@
) || (await loadPluginFactory(remotePlugin, options?.obfuscate))

if (pluginFactory) {
const intg = mergedIntegrations[remotePlugin.name]

Check warning on line 284 in packages/browser/src/plugins/remote-loader/index.ts

View check run for this annotation

Codecov / codecov/patch

packages/browser/src/plugins/remote-loader/index.ts#L284

Added line #L284 was not covered by tests
const plugin = await pluginFactory({
...remotePlugin.settings,
...mergedIntegrations[remotePlugin.name],
...intg,
})
const plugins = Array.isArray(plugin) ? plugin : [plugin]

Expand Down
90 changes: 89 additions & 1 deletion packages/browser/src/plugins/segmentio/__tests__/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,95 @@ describe('Segment.io', () => {
})
})

describe('configuring a keep alive', () => {
describe('configuring headers', () => {
it('should accept additional headers', async () => {
const analytics = new Analytics({ writeKey: 'foo' })

await analytics.register(
await segmentio(analytics, {
apiKey: '',
deliveryStrategy: {
config: {
headers: {
'X-My-Header': 'foo',
},
},
},
})
)

await analytics.track('foo')
const [_, params] = spyMock.mock.lastCall
expect(params.headers['X-My-Header']).toBe('foo')
expect(params.headers['Content-Type']).toBe('text/plain')
})

it('should allow additional headers to be a function', async () => {
const analytics = new Analytics({ writeKey: 'foo' })

await analytics.register(
await segmentio(analytics, {
apiKey: '',
deliveryStrategy: {
config: {
headers: () => ({
'X-My-Header': 'foo',
}),
},
},
})
)

await analytics.track('foo')
const [_, params] = spyMock.mock.lastCall
expect(params.headers['X-My-Header']).toBe('foo')
expect(params.headers['Content-Type']).toBe('text/plain')
})

it('should allow content type to be overridden', async () => {
const analytics = new Analytics({ writeKey: 'foo' })

await analytics.register(
await segmentio(analytics, {
apiKey: '',
deliveryStrategy: {
config: {
headers: () => ({
'Content-Type': 'bar',
}),
},
},
})
)

await analytics.track('foo')
const [_, params] = spyMock.mock.lastCall
expect(params.headers['Content-Type']).toBe('bar')
})
})

describe('configuring fetch priority', () => {
it('should accept fetch priority configuration', async () => {
const analytics = new Analytics({ writeKey: 'foo' })

await analytics.register(
await segmentio(analytics, {
apiKey: '',
deliveryStrategy: {
config: {
fetchPriority: 'high',
},
},
})
)

await analytics.track('foo')
const [_, params] = spyMock.mock.lastCall
expect(params.priority).toBe('high')
})
})

describe('configuring keepalive', () => {
it('should accept keepalive configuration', async () => {
const analytics = new Analytics({ writeKey: 'foo' })

Expand Down
Loading
Loading